code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const Allocator = std.mem.Allocator; /// /// A comptime bitmap that uses a specific type to store the entries. No allocators needed. /// /// Arguments: /// IN BitmapType: type - The integer type to use to store entries. /// /// Return: type. /// The bitmap type created. /// pub fn ComptimeBitmap(comptime BitmapType: type) type { return struct { const Self = @This(); /// The number of entries that one bitmap type can hold. Evaluates to the number of bits the type has pub const NUM_ENTRIES: usize = std.meta.bitCount(BitmapType); /// The value that a full bitmap will have pub const BITMAP_FULL = std.math.maxInt(BitmapType); /// The type of an index into a bitmap entry. The smallest integer needed to represent all bit positions in the bitmap entry type pub const IndexType = std.meta.Int(.unsigned, std.math.log2(std.math.ceilPowerOfTwo(u16, std.meta.bitCount(BitmapType)) catch unreachable)); bitmap: BitmapType, num_free_entries: BitmapType, /// /// Create an instance of this bitmap type. /// /// Return: Self. /// The bitmap instance. /// pub fn init() Self { return .{ .bitmap = 0, .num_free_entries = NUM_ENTRIES, }; } /// /// Set an entry within a bitmap as occupied. /// /// Arguments: /// IN/OUT self: *Self - The bitmap to modify. /// IN idx: IndexType - The index within the bitmap to set. /// pub fn setEntry(self: *Self, idx: IndexType) void { if (!self.isSet(idx)) { self.bitmap |= self.indexToBit(idx); self.num_free_entries -= 1; } } /// /// Set an entry within a bitmap as unoccupied. /// /// Arguments: /// IN/OUT self: *Self - The bitmap to modify. /// IN idx: IndexType - The index within the bitmap to clear. /// pub fn clearEntry(self: *Self, idx: IndexType) void { if (self.isSet(idx)) { self.bitmap &= ~self.indexToBit(idx); self.num_free_entries += 1; } } /// /// Convert a global bitmap index into the bit corresponding to an entry within a single BitmapType. /// /// Arguments: /// IN self: *const Self - The bitmap to use. /// IN idx: IndexType - The index into all of the bitmaps entries. /// /// Return: BitmapType. /// The bit corresponding to that index but within a single BitmapType. /// fn indexToBit(self: *const Self, idx: IndexType) BitmapType { return @as(BitmapType, 1) << idx; } /// /// Find a number of contiguous free entries and set them. /// /// Arguments: /// IN/OUT self: *Self - The bitmap to modify. /// IN num: usize - The number of entries to set. /// /// Return: ?IndexType /// The first entry set or null if there weren't enough contiguous entries. /// pub fn setContiguous(self: *Self, num: usize) ?IndexType { if (num > self.num_free_entries) { return null; } var count: usize = 0; var start: ?IndexType = null; var bit: IndexType = 0; while (true) { const entry = bit; if (entry >= NUM_ENTRIES) { return null; } if ((self.bitmap & @as(BitmapType, 1) << bit) != 0) { // This is a one so clear the progress count = 0; start = null; } else { // It's a zero so increment the count count += 1; if (start == null) { // Start of the contiguous zeroes start = entry; } if (count == num) { // Reached the desired number break; } } // Avoiding overflow by checking if bit is less than the max - 1 if (bit < NUM_ENTRIES - 1) { bit += 1; } else { break; } } if (count == num) { if (start) |start_entry| { var i: IndexType = 0; while (i < num) : (i += 1) { self.setEntry(start_entry + i); } return start_entry; } } return null; } /// /// Set the first free entry within the bitmaps as occupied. /// /// Return: ?IndexType. /// The index within all bitmaps that was set or null if there wasn't one free. /// 0 .. NUM_ENTRIES - 1 if in the first bitmap, NUM_ENTRIES .. NUM_ENTRIES * 2 - 1 if in the second etc. /// pub fn setFirstFree(self: *Self) ?IndexType { if (self.num_free_entries == 0 or self.bitmap == BITMAP_FULL) { std.debug.assert(self.num_free_entries == 0 and self.bitmap == BITMAP_FULL); return null; } const bit = @truncate(IndexType, @ctz(BitmapType, ~self.bitmap)); self.setEntry(bit); return bit; } /// /// Check if an entry is set. /// /// Arguments: /// IN self: *const Self - The bitmap to check. /// IN idx: usize - The entry to check. /// /// Return: bool. /// True if the entry is set, else false. /// pub fn isSet(self: *const Self, idx: IndexType) bool { return (self.bitmap & self.indexToBit(idx)) != 0; } }; } /// /// A bitmap that uses a specific type to store the entries. /// /// Arguments: /// IN BitmapType: type - The integer type to use to store entries. /// /// Return: type. /// The bitmap type created. /// pub fn Bitmap(comptime BitmapType: type) type { return struct { /// The possible errors thrown by bitmap functions pub const BitmapError = error{ /// The address given was outside the region covered by a bitmap OutOfBounds, }; const Self = @This(); /// The number of entries that one bitmap type can hold. Evaluates to the number of bits the type has pub const ENTRIES_PER_BITMAP: usize = std.meta.bitCount(BitmapType); /// The value that a full bitmap will have pub const BITMAP_FULL = std.math.maxInt(BitmapType); /// The type of an index into a bitmap entry. The smallest integer needed to represent all bit positions in the bitmap entry type pub const IndexType = std.meta.Int(.unsigned, std.math.log2(std.math.ceilPowerOfTwo(u16, std.meta.bitCount(BitmapType)) catch unreachable)); num_bitmaps: usize, num_entries: usize, bitmaps: []BitmapType, num_free_entries: usize, allocator: *std.mem.Allocator, /// /// Create an instance of this bitmap type. /// /// Arguments: /// IN num_entries: usize - The number of entries that the bitmap created will have. /// The number of BitmapType required to store this many entries will be allocated and each will be zeroed. /// IN allocator: *std.mem.Allocator - The allocator to use when allocating the BitmapTypes required. /// /// Return: Self. /// The bitmap instance. /// /// Error: std.mem.Allocator.Error /// OutOfMemory: There isn't enough memory available to allocate the required number of BitmapType. /// pub fn init(num_entries: usize, allocator: *std.mem.Allocator) !Self { const num = std.mem.alignForward(num_entries, ENTRIES_PER_BITMAP) / ENTRIES_PER_BITMAP; const self = Self{ .num_bitmaps = num, .num_entries = num_entries, .bitmaps = try allocator.alloc(BitmapType, num), .num_free_entries = num_entries, .allocator = allocator, }; for (self.bitmaps) |*bmp| { bmp.* = 0; } return self; } /// /// Clone this bitmap. /// /// Arguments: /// IN self: *Self - The bitmap to clone. /// /// Return: Self /// The cloned bitmap /// /// Error: std.mem.Allocator.Error /// OutOfMemory: There isn't enough memory available to allocate the required number of BitmapType. /// pub fn clone(self: *const Self) std.mem.Allocator.Error!Self { var copy = try init(self.num_entries, self.allocator); var i: usize = 0; while (i < copy.num_entries) : (i += 1) { if (self.isSet(i) catch unreachable) { copy.setEntry(i) catch unreachable; } } return copy; } /// /// Free the memory occupied by this bitmap's internal state. It will become unusable afterwards. /// /// Arguments: /// IN self: *Self - The bitmap that should be deinitialised /// pub fn deinit(self: *Self) void { self.allocator.free(self.bitmaps); } /// /// Set an entry within a bitmap as occupied. /// /// Arguments: /// IN/OUT self: *Self - The bitmap to modify. /// IN idx: usize - The index within the bitmap to set. /// /// Error: BitmapError. /// OutOfBounds: The index given is out of bounds. /// pub fn setEntry(self: *Self, idx: usize) BitmapError!void { if (idx >= self.num_entries) { return BitmapError.OutOfBounds; } if (!try self.isSet(idx)) { const bit = self.indexToBit(idx); self.bitmaps[idx / ENTRIES_PER_BITMAP] |= bit; self.num_free_entries -= 1; } } /// /// Set an entry within a bitmap as unoccupied. /// /// Arguments: /// IN/OUT self: *Self - The bitmap to modify. /// IN idx: usize - The index within the bitmap to clear. /// /// Error: BitmapError. /// OutOfBounds: The index given is out of bounds. /// pub fn clearEntry(self: *Self, idx: usize) BitmapError!void { if (idx >= self.num_entries) { return BitmapError.OutOfBounds; } if (try self.isSet(idx)) { const bit = self.indexToBit(idx); self.bitmaps[idx / ENTRIES_PER_BITMAP] &= ~bit; self.num_free_entries += 1; } } /// /// Convert a global bitmap index into the bit corresponding to an entry within a single BitmapType. /// /// Arguments: /// IN self: *const Self - The bitmap to use. /// IN idx: usize - The index into all of the bitmaps entries. /// /// Return: BitmapType. /// The bit corresponding to that index but within a single BitmapType. /// fn indexToBit(self: *const Self, idx: usize) BitmapType { return @as(BitmapType, 1) << @intCast(IndexType, idx % ENTRIES_PER_BITMAP); } /// /// Find a number of contiguous free entries and set them. /// /// Arguments: /// IN/OUT self: *Self - The bitmap to modify. /// IN num: usize - The number of entries to set. /// /// Return: ?usize /// The first entry set or null if there weren't enough contiguous entries. /// pub fn setContiguous(self: *Self, num: usize) ?usize { if (num > self.num_free_entries) { return null; } var count: usize = 0; var start: ?usize = null; for (self.bitmaps) |bmp, i| { var bit: IndexType = 0; while (true) { const entry = bit + i * ENTRIES_PER_BITMAP; if (entry >= self.num_entries) { return null; } if ((bmp & @as(BitmapType, 1) << bit) != 0) { // This is a one so clear the progress count = 0; start = null; } else { // It's a zero so increment the count count += 1; if (start == null) { // Start of the contiguous zeroes start = entry; } if (count == num) { // Reached the desired number break; } } // Avoiding overflow by checking if bit is less than the max - 1 if (bit < ENTRIES_PER_BITMAP - 1) { bit += 1; } else { // Reached the end of the bitmap break; } } if (count == num) { break; } } if (count == num) { if (start) |start_entry| { var i: usize = 0; while (i < num) : (i += 1) { // Can't fail as the entry was found to be free self.setEntry(start_entry + i) catch unreachable; } return start_entry; } } return null; } /// /// Set the first free entry within the bitmaps as occupied. /// /// Return: ?usize. /// The index within all bitmaps that was set or null if there wasn't one free. /// 0 .. ENTRIES_PER_BITMAP - 1 if in the first bitmap, ENTRIES_PER_BITMAP .. ENTRIES_PER_BITMAP * 2 - 1 if in the second etc. /// pub fn setFirstFree(self: *Self) ?usize { if (self.num_free_entries == 0) { return null; } for (self.bitmaps) |*bmp, i| { if (bmp.* == BITMAP_FULL) { continue; } const bit = @truncate(IndexType, @ctz(BitmapType, ~bmp.*)); const idx = bit + i * ENTRIES_PER_BITMAP; // Failing here means that the index is outside of the bitmap, so there are no free entries self.setEntry(idx) catch return null; return idx; } return null; } /// /// Check if an entry is set. /// /// Arguments: /// IN self: *const Self - The bitmap to check. /// IN idx: usize - The entry to check. /// /// Return: bool. /// True if the entry is set, else false. /// /// Error: BitmapError. /// OutOfBounds: The index given is out of bounds. /// pub fn isSet(self: *const Self, idx: usize) BitmapError!bool { if (idx >= self.num_entries) { return BitmapError.OutOfBounds; } return (self.bitmaps[idx / ENTRIES_PER_BITMAP] & self.indexToBit(idx)) != 0; } }; } test "Comptime setEntry" { var bmp = ComptimeBitmap(u32).init(); testing.expectEqual(@as(u32, 32), bmp.num_free_entries); bmp.setEntry(0); testing.expectEqual(@as(u32, 1), bmp.bitmap); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); bmp.setEntry(1); testing.expectEqual(@as(u32, 3), bmp.bitmap); testing.expectEqual(@as(u32, 30), bmp.num_free_entries); // Repeat setting entry 1 to make sure state doesn't change bmp.setEntry(1); testing.expectEqual(@as(u32, 3), bmp.bitmap); testing.expectEqual(@as(u32, 30), bmp.num_free_entries); } test "Comptime clearEntry" { var bmp = ComptimeBitmap(u32).init(); testing.expectEqual(@as(u32, 32), bmp.num_free_entries); bmp.setEntry(0); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); bmp.setEntry(1); testing.expectEqual(@as(u32, 30), bmp.num_free_entries); testing.expectEqual(@as(u32, 3), bmp.bitmap); bmp.clearEntry(0); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); testing.expectEqual(@as(u32, 2), bmp.bitmap); // Repeat to make sure state doesn't change bmp.clearEntry(0); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); testing.expectEqual(@as(u32, 2), bmp.bitmap); // Try clearing an unset entry to make sure state doesn't change bmp.clearEntry(2); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); testing.expectEqual(@as(u32, 2), bmp.bitmap); } test "Comptime setFirstFree" { var bmp = ComptimeBitmap(u32).init(); // Allocate the first entry testing.expectEqual(bmp.setFirstFree() orelse unreachable, 0); testing.expectEqual(bmp.bitmap, 1); // Allocate the second entry testing.expectEqual(bmp.setFirstFree() orelse unreachable, 1); testing.expectEqual(bmp.bitmap, 3); // Make all but the MSB occupied and try to allocate it bmp.bitmap = ComptimeBitmap(u32).BITMAP_FULL & ~@as(u32, 1 << (ComptimeBitmap(u32).NUM_ENTRIES - 1)); bmp.num_free_entries = 1; testing.expectEqual(bmp.setFirstFree() orelse unreachable, ComptimeBitmap(u32).NUM_ENTRIES - 1); testing.expectEqual(bmp.bitmap, ComptimeBitmap(u32).BITMAP_FULL); // We should no longer be able to allocate any entries testing.expectEqual(bmp.setFirstFree(), null); testing.expectEqual(bmp.bitmap, ComptimeBitmap(u32).BITMAP_FULL); } test "Comptime isSet" { var bmp = ComptimeBitmap(u32).init(); bmp.bitmap = 1; // Make sure that only the set entry is considered set testing.expect(bmp.isSet(0)); var i: usize = 1; while (i < ComptimeBitmap(u32).NUM_ENTRIES) : (i += 1) { testing.expect(!bmp.isSet(@truncate(ComptimeBitmap(u32).IndexType, i))); } bmp.bitmap = 3; testing.expect(bmp.isSet(0)); testing.expect(bmp.isSet(1)); i = 2; while (i < ComptimeBitmap(u32).NUM_ENTRIES) : (i += 1) { testing.expect(!bmp.isSet(@truncate(ComptimeBitmap(u32).IndexType, i))); } bmp.bitmap = 11; testing.expect(bmp.isSet(0)); testing.expect(bmp.isSet(1)); testing.expect(!bmp.isSet(2)); testing.expect(bmp.isSet(3)); i = 4; while (i < ComptimeBitmap(u32).NUM_ENTRIES) : (i += 1) { testing.expect(!bmp.isSet(@truncate(ComptimeBitmap(u32).IndexType, i))); } } test "Comptime indexToBit" { var bmp = ComptimeBitmap(u8).init(); testing.expectEqual(bmp.indexToBit(0), 1); testing.expectEqual(bmp.indexToBit(1), 2); testing.expectEqual(bmp.indexToBit(2), 4); testing.expectEqual(bmp.indexToBit(3), 8); testing.expectEqual(bmp.indexToBit(4), 16); testing.expectEqual(bmp.indexToBit(5), 32); testing.expectEqual(bmp.indexToBit(6), 64); testing.expectEqual(bmp.indexToBit(7), 128); } test "Comptime setContiguous" { var bmp = ComptimeBitmap(u15).init(); // Test trying to set more entries than the bitmap has testing.expectEqual(bmp.setContiguous(ComptimeBitmap(u15).NUM_ENTRIES + 1), null); // All entries should still be free testing.expectEqual(bmp.num_free_entries, ComptimeBitmap(u15).NUM_ENTRIES); testing.expectEqual(bmp.setContiguous(3) orelse unreachable, 0); testing.expectEqual(bmp.setContiguous(4) orelse unreachable, 3); // 0b0000.0000.0111.1111 bmp.bitmap |= 0x200; // 0b0000.0010.0111.1111 testing.expectEqual(bmp.setContiguous(3) orelse unreachable, 10); // 0b0001.1110.0111.1111 testing.expectEqual(bmp.setContiguous(5), null); testing.expectEqual(bmp.setContiguous(2), 7); // 0b001.1111.1111.1111 // Test trying to set beyond the end of the bitmaps testing.expectEqual(bmp.setContiguous(3), null); testing.expectEqual(bmp.setContiguous(2), 13); } test "setEntry" { var bmp = try Bitmap(u32).init(31, std.testing.allocator); defer bmp.deinit(); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); try bmp.setEntry(0); testing.expectEqual(@as(u32, 1), bmp.bitmaps[0]); testing.expectEqual(@as(u32, 30), bmp.num_free_entries); try bmp.setEntry(1); testing.expectEqual(@as(u32, 3), bmp.bitmaps[0]); testing.expectEqual(@as(u32, 29), bmp.num_free_entries); // Repeat setting entry 1 to make sure state doesn't change try bmp.setEntry(1); testing.expectEqual(@as(u32, 3), bmp.bitmaps[0]); testing.expectEqual(@as(u32, 29), bmp.num_free_entries); testing.expectError(Bitmap(u32).BitmapError.OutOfBounds, bmp.setEntry(31)); testing.expectEqual(@as(u32, 29), bmp.num_free_entries); } test "clearEntry" { var bmp = try Bitmap(u32).init(32, std.testing.allocator); defer bmp.deinit(); testing.expectEqual(@as(u32, 32), bmp.num_free_entries); try bmp.setEntry(0); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); try bmp.setEntry(1); testing.expectEqual(@as(u32, 30), bmp.num_free_entries); testing.expectEqual(@as(u32, 3), bmp.bitmaps[0]); try bmp.clearEntry(0); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); testing.expectEqual(@as(u32, 2), bmp.bitmaps[0]); // Repeat to make sure state doesn't change try bmp.clearEntry(0); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); testing.expectEqual(@as(u32, 2), bmp.bitmaps[0]); // Try clearing an unset entry to make sure state doesn't change try bmp.clearEntry(2); testing.expectEqual(@as(u32, 31), bmp.num_free_entries); testing.expectEqual(@as(u32, 2), bmp.bitmaps[0]); testing.expectError(Bitmap(u32).BitmapError.OutOfBounds, bmp.clearEntry(32)); } test "setFirstFree multiple bitmaps" { var bmp = try Bitmap(u8).init(9, std.testing.allocator); defer bmp.deinit(); // Allocate the first entry testing.expectEqual(bmp.setFirstFree() orelse unreachable, 0); testing.expectEqual(bmp.bitmaps[0], 1); // Allocate the second entry testing.expectEqual(bmp.setFirstFree() orelse unreachable, 1); testing.expectEqual(bmp.bitmaps[0], 3); // Allocate the entirety of the first bitmap var entry: u32 = 2; var expected: u8 = 7; while (entry < Bitmap(u8).ENTRIES_PER_BITMAP) { testing.expectEqual(bmp.setFirstFree() orelse unreachable, entry); testing.expectEqual(bmp.bitmaps[0], expected); if (entry + 1 < Bitmap(u8).ENTRIES_PER_BITMAP) { entry += 1; expected = expected * 2 + 1; } else { break; } } // Try allocating an entry in the next bitmap testing.expectEqual(bmp.setFirstFree() orelse unreachable, Bitmap(u8).ENTRIES_PER_BITMAP); testing.expectEqual(bmp.bitmaps[0], Bitmap(u8).BITMAP_FULL); testing.expectEqual(bmp.bitmaps[1], 1); // We should no longer be able to allocate any entries testing.expectEqual(bmp.setFirstFree(), null); testing.expectEqual(bmp.bitmaps[0], Bitmap(u8).BITMAP_FULL); testing.expectEqual(bmp.bitmaps[1], 1); } test "setFirstFree" { var bmp = try Bitmap(u32).init(32, std.testing.allocator); defer bmp.deinit(); // Allocate the first entry testing.expectEqual(bmp.setFirstFree() orelse unreachable, 0); testing.expectEqual(bmp.bitmaps[0], 1); // Allocate the second entry testing.expectEqual(bmp.setFirstFree() orelse unreachable, 1); testing.expectEqual(bmp.bitmaps[0], 3); // Make all but the MSB occupied and try to allocate it bmp.bitmaps[0] = Bitmap(u32).BITMAP_FULL & ~@as(u32, 1 << (Bitmap(u32).ENTRIES_PER_BITMAP - 1)); testing.expectEqual(bmp.setFirstFree() orelse unreachable, Bitmap(u32).ENTRIES_PER_BITMAP - 1); testing.expectEqual(bmp.bitmaps[0], Bitmap(u32).BITMAP_FULL); // We should no longer be able to allocate any entries testing.expectEqual(bmp.setFirstFree(), null); testing.expectEqual(bmp.bitmaps[0], Bitmap(u32).BITMAP_FULL); } test "isSet" { var bmp = try Bitmap(u32).init(32, std.testing.allocator); defer bmp.deinit(); bmp.bitmaps[0] = 1; // Make sure that only the set entry is considered set testing.expect(try bmp.isSet(0)); var i: u32 = 1; while (i < bmp.num_entries) : (i += 1) { testing.expect(!try bmp.isSet(i)); } bmp.bitmaps[0] = 3; testing.expect(try bmp.isSet(0)); testing.expect(try bmp.isSet(1)); i = 2; while (i < bmp.num_entries) : (i += 1) { testing.expect(!try bmp.isSet(i)); } bmp.bitmaps[0] = 11; testing.expect(try bmp.isSet(0)); testing.expect(try bmp.isSet(1)); testing.expect(!try bmp.isSet(2)); testing.expect(try bmp.isSet(3)); i = 4; while (i < bmp.num_entries) : (i += 1) { testing.expect(!try bmp.isSet(i)); } testing.expectError(Bitmap(u32).BitmapError.OutOfBounds, bmp.isSet(33)); } test "indexToBit" { var bmp = try Bitmap(u8).init(10, std.testing.allocator); defer bmp.deinit(); testing.expectEqual(bmp.indexToBit(0), 1); testing.expectEqual(bmp.indexToBit(1), 2); testing.expectEqual(bmp.indexToBit(2), 4); testing.expectEqual(bmp.indexToBit(3), 8); testing.expectEqual(bmp.indexToBit(4), 16); testing.expectEqual(bmp.indexToBit(5), 32); testing.expectEqual(bmp.indexToBit(6), 64); testing.expectEqual(bmp.indexToBit(7), 128); testing.expectEqual(bmp.indexToBit(8), 1); testing.expectEqual(bmp.indexToBit(9), 2); } test "setContiguous" { var bmp = try Bitmap(u4).init(15, std.testing.allocator); defer bmp.deinit(); // Test trying to set more entries than the bitmap has testing.expectEqual(bmp.setContiguous(bmp.num_entries + 1), null); // All entries should still be free testing.expectEqual(bmp.num_free_entries, bmp.num_entries); testing.expectEqual(bmp.setContiguous(3) orelse unreachable, 0); testing.expectEqual(bmp.setContiguous(4) orelse unreachable, 3); // 0b0000.0000.0111.1111 bmp.bitmaps[2] |= 2; // 0b0000.0010.0111.1111 testing.expectEqual(bmp.setContiguous(3) orelse unreachable, 10); // 0b0001.1110.0111.1111 testing.expectEqual(bmp.setContiguous(5), null); testing.expectEqual(bmp.setContiguous(2), 7); // 0b001.1111.1111.1111 // Test trying to set beyond the end of the bitmaps testing.expectEqual(bmp.setContiguous(3), null); testing.expectEqual(bmp.setContiguous(2), 13); }
src/kernel/lib/bitmap.zig
const std = @import("std"); const testing = std.testing; const VARIABLE_START_CHAR: u8 = '{'; const VARIABLE_END_CHAR: u8 = '}'; const VARIABLE_PATH_CHAR: u8 = '.'; const EtchTokenScanner = struct { const Self = @This(); const State = enum { TopLevel, BeginReadingVariable, ReadingVariable }; const Token = union(enum) { /// Copy `n` bytes to the output buffer RawSequence: usize, /// Append the variable to the output buffer Variable: struct { /// Variable path to trace through the provided arguments struct path: []const u8, /// Size of the variable definition to skip in the original input string size: usize, }, /// Insert the literal char for the variable start sequence EscapedVariableToken, }; state: State = .TopLevel, head: usize = 0, input: []const u8, current_variable_begin_idx: ?usize = null, current_variable_path_idx: ?usize = null, fn cur(self: Self) u8 { return self.input[self.head]; } fn isDone(self: Self) bool { return self.head >= self.input.len; } fn next(comptime self: *Self) !?Token { while (!self.isDone()) { switch (self.state) { .ReadingVariable => { while (!self.isDone()) { const cur_char = self.cur(); const hit_end_char = cur_char == VARIABLE_END_CHAR; const hit_space = std.ascii.isSpace(cur_char); if (hit_end_char or hit_space) { const var_end_idx = self.head; if (hit_space) { comptime var found_end = false; while (!self.isDone()) { if (self.cur() == VARIABLE_END_CHAR) { found_end = true; break; } self.head += 1; } if (!found_end) return error.UnfinishedVariableDeclaration; } self.state = .TopLevel; self.head += 1; if (self.current_variable_begin_idx) |var_beg_idx| { if (self.current_variable_path_idx) |var_path_beg_idx| { const token = Token{ .Variable = .{ .path = self.input[var_path_beg_idx..var_end_idx], .size = self.head - var_beg_idx } }; self.current_variable_begin_idx = null; self.current_variable_path_idx = null; return token; } else return error.NoVariablePathProvided; } else return error.TemplateVariableEndWithoutBeginning; } self.head += 1; } }, .BeginReadingVariable => { if (self.cur() == VARIABLE_START_CHAR) { self.head += 1; self.state = .TopLevel; return .EscapedVariableToken; } else { while (!self.isDone()) { const cur_char = self.cur(); if (cur_char == VARIABLE_END_CHAR) return error.NoVariablePathProvided; if (cur_char == VARIABLE_PATH_CHAR) { self.current_variable_path_idx = self.head; self.state = .ReadingVariable; self.head += 1; break; } self.head += 1; } } }, .TopLevel => { var bytes: usize = 0; while (!self.isDone()) { if (self.cur() == VARIABLE_START_CHAR) { self.state = .BeginReadingVariable; self.current_variable_begin_idx = self.head; self.head += 1; break; } self.head += 1; bytes += 1; } return Token{ .RawSequence = bytes }; }, } } return null; } }; const EtchTemplateError = error{ InvalidPath, } || std.mem.Allocator.Error; const StructVariable = union(enum) { String: []const u8, }; /// Return the builtin.StructField for the provided `path` at `arguments` fn lookupPath(comptime arguments: anytype, comptime path: []const u8) StructVariable { comptime var items: [std.mem.count(u8, path, ".")][]const u8 = undefined; comptime var item_idx: usize = 0; comptime var head: usize = 1; inline while (comptime std.mem.indexOfScalarPos(u8, path, head, VARIABLE_PATH_CHAR)) |idx| { items[item_idx] = path[head..idx]; item_idx += 1; head = idx + 1; } items[item_idx] = path[head..]; comptime var struct_field_ptr: ?std.builtin.TypeInfo.StructField = null; inline for (items) |item, i| { if (struct_field_ptr) |*ptr| { if (std.meta.fieldIndex(ptr.field_type, item)) |idx| { ptr.* = std.meta.fields(ptr.field_type)[idx]; } else @compileError("Item '" ++ item ++ "' does not exist on provided struct"); } else { if (std.meta.fieldIndex(@TypeOf(arguments), item)) |idx| { struct_field_ptr = std.meta.fields(@TypeOf(arguments))[idx]; } else @compileError("Item '" ++ item ++ "' does not exist on provided struct"); } if (struct_field_ptr) |ptr| { if (i == items.len - 1) { if (comptime std.mem.eql(u8, ptr.name, item)) { if (ptr.default_value) |val| { return StructVariable{ .String = val }; } else @compileError("Unable to get length of field '" ++ item ++ "', is it null?"); } else @compileError("Item '" ++ item ++ "' does not exist on provided struct"); } } } @compileError("Item '" ++ item ++ "' does not exist on provided struct"); } fn getSizeNeededForTemplate(comptime input: []const u8, arguments: anytype) !usize { var bytesNeeded: usize = 0; var scanner = EtchTokenScanner{ .input = input, }; while (try scanner.next()) |token| { bytesNeeded += switch (token) { .RawSequence => |s| s, .Variable => |v| switch (lookupPath(arguments, v.path)) { .String => |item| item.len, }, .EscapedVariableToken => 1, }; } return bytesNeeded; } pub fn etchBuf(buf: []u8, comptime input: []const u8, arguments: anytype) []u8 { comptime var scanner = EtchTokenScanner{ .input = input, }; comptime var input_ptr: usize = 0; comptime var buf_ptr: usize = 0; inline while (comptime try scanner.next()) |token| { comptime var input_move_amt = 0; comptime var buf_move_amt = 0; switch (token) { .RawSequence => |s| { input_move_amt = s; buf_move_amt = s; std.mem.copy(u8, buf[buf_ptr .. buf_ptr + s], input[input_ptr .. input_ptr + s]); }, .Variable => |v| { comptime const variable = lookupPath(arguments, v.path); input_move_amt = v.size; switch (variable) { .String => |item| { buf_move_amt = item.len; std.mem.copy(u8, buf[buf_ptr .. buf_ptr + item.len], item[0..]); }, } }, .EscapedVariableToken => { input_move_amt = 2; buf_move_amt = 1; buf[buf_ptr] = VARIABLE_START_CHAR; }, } input_ptr += input_move_amt; buf_ptr += buf_move_amt; } return buf[0..buf_ptr]; } pub fn etch(allocator: *std.mem.Allocator, comptime input: []const u8, arguments: anytype) ![]u8 { const bytesNeeded = comptime getSizeNeededForTemplate(input, arguments) catch |e| { switch (e) { .UnfinishedVariableDeclaration => @compileError("Reached end of template input, but found unfinished variable declaration"), .TemplateVariableEndWithoutBeginning => @compileError("Found template variable end without finding a beginning"), .NoVariablePathProvided => @compileError("No variable definition path provided"), } }; var buf = try allocator.alloc(u8, bytesNeeded); return etchBuf(buf, input, arguments); } test "basic interpolation" { std.debug.print("\n", .{}); var timer = try std.time.Timer.start(); const out = try etch( testing.allocator, "Hello, { .person.name.first } {{ { .person.name.last }", .{ .butt = "cumsicle", .person = .{ .name = .{ .first = "Haze", .last = "Booth" } } }, ); defer testing.allocator.free(out); testing.expectEqualStrings(out, "Hello, Haze { Booth"); }
src/main.zig
const std = @import("std"); const testing = std.testing; const SYS = std.os.SYS; const allocator = std.testing.allocator; const syspect = @import("syspect"); const utils = @import("utils.zig"); /// Runs 'target_argv' program using syspect.Inspector. /// Inspects each syscall. /// Ensures any 'gettid()' calls return the same tid we think called it. pub fn ensure_pid_properly_tracked(target_argv: []const []const u8) !void { const syscalls = &[_]SYS{}; var inspector = syspect.Inspector.init(allocator, syscalls, .{ .inverse = true }); defer inspector.deinit(); const child_pid = try inspector.spawn_process(allocator, target_argv); while (try inspector.next_syscall()) |syscall| { switch (syscall) { .pre_call => |context| { try inspector.resume_tracee(context.pid); }, .post_call => |context| { if (context.registers.syscall == @enumToInt(SYS.gettid)) { testing.expectEqual(@intCast(syspect.c.regT, context.pid), context.registers.result); } try inspector.resume_tracee(context.pid); }, } } // Ensure we properly acknowledge a state where all tracees have exited. testing.expectEqual(false, inspector.has_tracees); testing.expectEqual(try inspector.next_syscall(), null); } /// Runs and inspects a program, tracking specific calls. /// Runs applicable tests on every inspected syscall. /// Expects syscalls to show up in order. /// Expects the expected syscalls to be the only ones inspected from program start to end. pub fn test_specific_calls(target_argv: []const []const u8, expected_calls: []const Syscall) !void { // Create a buffer, we are unlikely to use its entire size. // We would receive an "index out of bounds" error if we used more syscalls than allocated for here. var tracked_syscalls: [100]SYS = undefined; var unique_calls: usize = 0; // Creates a unique set of syscalls from 'expected_calls'. for (expected_calls) |expected| { // Check to see if expected call id is already tracked. for (tracked_syscalls) |tracked| { if (expected.id != tracked) { tracked_syscalls[unique_calls] = expected.id; unique_calls += 1; break; } } } var inspector = syspect.Inspector.init(allocator, tracked_syscalls[0..unique_calls], .{ .inverse = false }); defer inspector.deinit(); _ = try inspector.spawn_process(allocator, target_argv); try test_some_calls(&inspector, expected_calls); // Next syscall returns null when there are no tracee's left alive. // We expect this to be the case here, as the program should have exited. if ((try inspector.next_syscall()) != null) return error.TooManySyscalls; } /// Gathers next_syscall for each expected syscall; Compares what we expect with what we get. /// Has no protection against race conditions. /// Takes an 'Inspector' that has already attached to or spawned a process. /// Does not guarantee the process has ended. pub fn test_some_calls(inspector: *syspect.Inspector, expected_calls: []const Syscall) !void { for (expected_calls) |expected| { try test_call(try next_syscall(inspector), expected); var expected2 = expected; // Same syscall, except it now we expect it to have been started expected2.started = !expected.started; try test_call(try next_syscall(inspector), expected2); } } /// Tests a syscall against an expected result. fn test_call(context: syspect.Inspector.SyscallContext, expected: Syscall) !void { switch (context) { .pre_call => |pre_call| { utils.expectEnumEqual(SYS, expected.id, pre_call.registers.syscall); testing.expectEqual(expected.started, false); if (expected.pid) |epid| { testing.expectEqual(epid, pre_call.pid); } // Do not test for result here, because there is no result on a pre_call }, .post_call => |post_call| { utils.expectEnumEqual(SYS, expected.id, post_call.registers.syscall); testing.expectEqual(expected.started, true); if (expected.pid) |epid| { testing.expectEqual(epid, post_call.pid); } if (expected.result) |eresult| { testing.expectEqual(eresult, post_call.registers.result); } // Ensure gettid returns the same pid we expect to be making the syscall. if (post_call.registers.syscall == @enumToInt(SYS.gettid)) { testing.expectEqual(@intCast(syspect.c.regT, post_call.pid), post_call.registers.result); } }, } } // Convenience function // Gathers next syscall and starts or resumes tracee fn next_syscall(inspector: *syspect.Inspector) !syspect.Inspector.SyscallContext { const context = (try inspector.next_syscall()).?; switch (context) { .pre_call => |syscall| try inspector.resume_tracee(syscall.pid), .post_call => |syscall| try inspector.resume_tracee(syscall.pid), } return context; } pub const Syscall = struct { id: SYS, // Expected PID of this syscalls caller. Null means we do not test against PID. pid: ?std.os.pid_t = null, // Expected result. Null means we do not test against the result. result: ?syspect.c.regT = null, // Has the syscall been started? Value changed when it passes a test, // as we expect all syscalls to loop through 'start, end' states. started: bool = false, }; /// Out of order call tracking /// Tracks system calls in a way that ignores potential race conditions. pub fn ooo_call_tracking(inspector: *syspect.Inspector, calls: []Syscall) !void { var remaining: usize = calls.len * 2; while (remaining > 0) : (remaining -= 1) { const context = (try inspector.next_syscall()).?; switch (context) { .pre_call => |syscall| { const id = @intToEnum(SYS, syscall.registers.syscall); const call = try verify(calls, Syscall{ .id = id, .pid = syscall.pid, .started = false }); call.started = !call.started; try inspector.resume_tracee(syscall.pid); }, .post_call => |syscall| { const id = @intToEnum(SYS, syscall.registers.syscall); const call = try verify(calls, Syscall{ .id = id, .pid = syscall.pid, .started = true }); call.started = !call.started; try inspector.resume_tracee(syscall.pid); }, } } } /// Verifies a syscall falls within expected boundaries fn verify(syscalls: []Syscall, syscall: Syscall) !*Syscall { for (syscalls) |*hay| { var needle = syscall; if (hay.pid == null) needle.pid = null; if (hay.result == null) needle.result = null; if (std.meta.eql(needle, hay.*)) { return hay; } } std.debug.warn("syscall unmatched: {} {}\n", .{ @tagName(syscall.id), syscall }); return error.UnmatchedSyscall; }
tests/src/generic.zig
const std = @import("std"); test "example" { const input = @embedFile("14_example.txt"); const result10 = try run(input, 10); const result40 = try run(input, 40); try std.testing.expectEqual(@as(usize, 1588), result10); try std.testing.expectEqual(@as(usize, 2188189693529), result40); } pub fn main() !void { const input = @embedFile("14.txt"); std.debug.print("{}\n", .{try run(input, 10)}); std.debug.print("{}\n", .{try run(input, 40)}); } const Polymer = struct { rules: [100][3]u8, rule_len: usize, char_counts: [256]usize, // can be [26]usize or less but I've gots bytes to spare rule_counts: [100]usize, fn init() Polymer { return Polymer{ .rules = undefined, .rule_len = 0, .char_counts = .{0} ** 256, .rule_counts = .{0} ** 100, }; } fn addRule(self: *Polymer, pair: [2]u8, insertion: u8) !void { if (self.rule_len == 100) return error.TooManyRulesError; self.rules[self.rule_len] = .{ pair[0], pair[1], insertion }; self.rule_len += 1; } fn nextStep(self: *Polymer) !void { var new_counts: [100]usize = undefined; std.mem.copy(usize, &new_counts, &self.rule_counts); for (self.rule_counts[0..self.rule_len]) |c, i| { if (c == 0) continue; const rule = self.rules[i]; const first_idx = try self.getRuleIdx(.{ rule[0], rule[2] }); const second_idx = try self.getRuleIdx(.{ rule[2], rule[1] }); new_counts[i] -= c; new_counts[first_idx] += c; new_counts[second_idx] += c; self.char_counts[rule[2]] += c; } std.mem.copy(usize, &self.rule_counts, &new_counts); } fn calculate(self: *Polymer, template: []const u8, steps: usize) !usize { for (template) |c| self.char_counts[c] += 1; for (template[1..]) |c, i| { const rule_idx = try self.getRuleIdx(.{ template[i], c }); self.rule_counts[rule_idx] += 1; } var step: usize = 0; while (step < steps) : (step += 1) { try self.nextStep(); } var min = @as(usize, 0) -% 1; // MAXusize var max = @as(usize, 0); for (self.char_counts) |c| { if (c == 0) continue; min = @minimum(c, min); max = @maximum(c, max); } return max - min; } fn getRuleIdx(self: *const Polymer, pair: [2]u8) !usize { for (self.rules[0..self.rule_len]) |rule, i| { if (rule[0] == pair[0] and rule[1] == pair[1]) return i; } else return error.RuleNotFound; } }; fn run(input: []const u8, steps: usize) !usize { const first_newline_idx = std.mem.indexOfScalar(u8, input, '\n') orelse return error.ParseError; var polymer = Polymer.init(); var lines = std.mem.split(u8, input[first_newline_idx + 2 ..], "\n"); while (lines.next()) |line| { try polymer.addRule(.{ line[0], line[1] }, line[line.len - 1]); } return polymer.calculate(input[0..first_newline_idx], steps); }
shritesh+zig/14.zig
const bs = @import("./bitstream.zig"); const bu = @import("./bits.zig"); // bits utilities const hm = @import("./huffman.zig"); const lz = @import("./lz77.zig"); const tables = @import("./tables.zig"); const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const math = std.math; const SIZE_MAX = math.maxInt(u64); const UINT8_MAX = math.maxInt(u8); const LITLEN_EOB = 256; const LITLEN_MAX = 285; const LITLEN_TBL_OFFSET = 257; const MIN_LEN = 3; const MAX_LEN = 258; const DISTSYM_MAX = 29; const MIN_DISTANCE = 1; const MAX_DISTANCE = 32768; const MIN_CODELEN_LENS = 4; const MAX_CODELEN_LENS = 19; const MIN_LITLEN_LENS = 257; const MAX_LITLEN_LENS = 288; const MIN_DIST_LENS = 1; const MAX_DIST_LENS = 32; const CODELEN_MAX_LIT = 15; const CODELEN_COPY = 16; const CODELEN_COPY_MIN = 3; const CODELEN_COPY_MAX = 6; const CODELEN_ZEROS = 17; const CODELEN_ZEROS_MIN = 3; const CODELEN_ZEROS_MAX = 10; const CODELEN_ZEROS2 = 18; const CODELEN_ZEROS2_MIN = 11; const CODELEN_ZEROS2_MAX = 138; pub const inf_stat_t = enum { HWINF_OK, // Inflation was successful. HWINF_FULL, // Not enough room in the output buffer. HWINF_ERR, // Error in the input data. }; fn inf_block( is: *bs.istream_t, dst: [*]u8, dst_cap: usize, dst_pos: *usize, litlen_dec: *const hm.huffman_decoder_t, dist_dec: *const hm.huffman_decoder_t, ) inf_stat_t { var bits: u64 = 0; var used: usize = 0; var used_tot: usize = 0; var dist: usize = 0; var len: usize = 0; var litlen: u32 = 0; var distsym: u32 = 0; var ebits: u16 = 0; while (true) { // Read a litlen symbol. bits = bs.istream_bits(is); litlen = hm.huffman_decode(litlen_dec, @truncate(u16, bits), &used) catch { return inf_stat_t.HWINF_ERR; }; bits >>= @intCast(u6, used); used_tot = used; if (litlen < 0 or litlen > LITLEN_MAX) { // Failed to decode, or invalid symbol. return inf_stat_t.HWINF_ERR; // replaced by the catch above } else if (litlen <= UINT8_MAX) { // Literal. if (!bs.istream_advance(is, used_tot)) { return inf_stat_t.HWINF_ERR; } if (dst_pos.* == dst_cap) { return inf_stat_t.HWINF_FULL; } lz.lz77_output_lit(dst, dst_pos.*, @intCast(u8, litlen)); dst_pos.* += 1; continue; } else if (litlen == LITLEN_EOB) { // End of block. if (!bs.istream_advance(is, used_tot)) { return inf_stat_t.HWINF_ERR; } return inf_stat_t.HWINF_OK; } // It is a back reference. Figure out the length. assert(litlen >= LITLEN_TBL_OFFSET and litlen <= LITLEN_MAX); len = tables.litlen_tbl[litlen - LITLEN_TBL_OFFSET].base_len; ebits = tables.litlen_tbl[litlen - LITLEN_TBL_OFFSET].ebits; if (ebits != 0) { len += bu.lsb(bits, @intCast(u6, ebits)); bits >>= @intCast(u6, ebits); used_tot += ebits; } assert(len >= MIN_LEN and len <= MAX_LEN); // Get the distance. distsym = hm.huffman_decode(dist_dec, @truncate(u16, bits), &used) catch { return inf_stat_t.HWINF_ERR; }; bits >>= @intCast(u6, used); used_tot += used; if (distsym < 0 or distsym > DISTSYM_MAX) { // Failed to decode, or invalid symbol. return inf_stat_t.HWINF_ERR; // replaced by the catch above } dist = tables.dist_tbl[distsym].base_dist; ebits = tables.dist_tbl[distsym].ebits; if (ebits != 0) { dist += bu.lsb(bits, @intCast(u6, ebits)); bits >>= @intCast(u6, ebits); used_tot += ebits; } assert(dist >= MIN_DISTANCE and dist <= MAX_DISTANCE); assert(used_tot <= bs.ISTREAM_MIN_BITS); if (!bs.istream_advance(is, used_tot)) { return inf_stat_t.HWINF_ERR; } // Bounds check and output the backref. if (dist > dst_pos.*) { return inf_stat_t.HWINF_ERR; } if (bu.round_up(len, 8) <= dst_cap - dst_pos.*) { lz.lz77_output_backref64(dst, dst_pos.*, dist, len); } else if (len <= dst_cap - dst_pos.*) { lz.lz77_output_backref(dst, dst_pos.*, dist, len); } else { return inf_stat_t.HWINF_FULL; } dst_pos.* += len; } } // RFC 1951, 3.2.7 const codelen_lengths_order: [MAX_CODELEN_LENS]usize = [_]usize{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15, }; fn init_dyn_decoders( is: *bs.istream_t, litlen_dec: *hm.huffman_decoder_t, dist_dec: *hm.huffman_decoder_t, ) inf_stat_t { var bits: u64 = 0; var num_litlen_lens: usize = 0; var num_dist_lens: usize = 0; var num_codelen_lens: usize = 0; var codelen_lengths: [MAX_CODELEN_LENS]u8 = undefined; mem.set(u8, codelen_lengths[0..], 0); var code_lengths: [MAX_LITLEN_LENS + MAX_DIST_LENS]u8 = undefined; mem.set(u8, code_lengths[0..], 0); var i: usize = 0; var n: usize = 0; var used: usize = 0; var sym: u32 = 0; var codelen_dec: hm.huffman_decoder_t = undefined; bits = bs.istream_bits(is); // Number of litlen codeword lengths (5 bits + 257). num_litlen_lens = @intCast(usize, bu.lsb(bits, 5) + MIN_LITLEN_LENS); bits >>= 5; assert(num_litlen_lens <= MAX_LITLEN_LENS); // Number of dist codeword lengths (5 bits + 1). num_dist_lens = @intCast(usize, bu.lsb(bits, 5) + MIN_DIST_LENS); bits >>= 5; assert(num_dist_lens <= MAX_DIST_LENS); // Number of code length lengths (4 bits + 4). num_codelen_lens = @intCast(usize, bu.lsb(bits, 4) + MIN_CODELEN_LENS); bits >>= 4; assert(num_codelen_lens <= MAX_CODELEN_LENS); if (!bs.istream_advance(is, 5 + 5 + 4)) { return inf_stat_t.HWINF_ERR; } // Read the codelen codeword lengths (3 bits each) // and initialize the codelen decoder. i = 0; while (i < num_codelen_lens) : (i += 1) { bits = bs.istream_bits(is); codelen_lengths[codelen_lengths_order[i]] = @intCast(u8, bu.lsb(bits, 3)); if (!bs.istream_advance(is, 3)) { return inf_stat_t.HWINF_ERR; } } while (i < MAX_CODELEN_LENS) : (i += 1) { codelen_lengths[codelen_lengths_order[i]] = 0; } if (!hm.huffman_decoder_init(&codelen_dec, &codelen_lengths, MAX_CODELEN_LENS)) { return inf_stat_t.HWINF_ERR; } // Read the litlen and dist codeword lengths. i = 0; while (i < num_litlen_lens + num_dist_lens) { bits = bs.istream_bits(is); sym = hm.huffman_decode(&codelen_dec, @truncate(u16, bits), &used) catch { return inf_stat_t.HWINF_ERR; }; bits >>= @intCast(u6, used); if (!bs.istream_advance(is, used)) { return inf_stat_t.HWINF_ERR; } if (sym >= 0 and sym <= CODELEN_MAX_LIT) { // A literal codeword length. code_lengths[i] = @intCast(u8, sym); i += 1; } else if (sym == CODELEN_COPY) { // Copy the previous codeword length 3--6 times. if (i < 1) { return inf_stat_t.HWINF_ERR; // No previous length. } // 2 bits + 3 n = @intCast(usize, bu.lsb(bits, 2)) + CODELEN_COPY_MIN; if (!bs.istream_advance(is, 2)) { return inf_stat_t.HWINF_ERR; } assert(n >= CODELEN_COPY_MIN and n <= CODELEN_COPY_MAX); if (i + n > num_litlen_lens + num_dist_lens) { return inf_stat_t.HWINF_ERR; } while (n > 0) : (n -= 1) { code_lengths[i] = code_lengths[i - 1]; i += 1; } } else if (sym == CODELEN_ZEROS) { // 3--10 zeros; 3 bits + 3 n = @intCast(usize, bu.lsb(bits, 3) + CODELEN_ZEROS_MIN); if (!bs.istream_advance(is, 3)) { return inf_stat_t.HWINF_ERR; } assert(n >= CODELEN_ZEROS_MIN and n <= CODELEN_ZEROS_MAX); if (i + n > num_litlen_lens + num_dist_lens) { return inf_stat_t.HWINF_ERR; } while (n > 0) : (n -= 1) { code_lengths[i] = 0; i += 1; } } else if (sym == CODELEN_ZEROS2) { // 11--138 zeros; 7 bits + 138. n = @intCast(usize, bu.lsb(bits, 7) + CODELEN_ZEROS2_MIN); if (!bs.istream_advance(is, 7)) { return inf_stat_t.HWINF_ERR; } assert(n >= CODELEN_ZEROS2_MIN and n <= CODELEN_ZEROS2_MAX); if (i + n > num_litlen_lens + num_dist_lens) { return inf_stat_t.HWINF_ERR; } while (n > 0) : (n -= 1) { code_lengths[i] = 0; i += 1; } } else { // Invalid symbol. return inf_stat_t.HWINF_ERR; } } if (!hm.huffman_decoder_init(litlen_dec, &code_lengths, num_litlen_lens)) { return inf_stat_t.HWINF_ERR; } if (!hm.huffman_decoder_init(dist_dec, code_lengths[num_litlen_lens..].ptr, num_dist_lens)) { return inf_stat_t.HWINF_ERR; } return inf_stat_t.HWINF_OK; } fn inf_dyn_block( is: *bs.istream_t, dst: [*]u8, dst_cap: usize, dst_pos: *usize, ) inf_stat_t { var s: inf_stat_t = undefined; var litlen_dec: hm.huffman_decoder_t = hm.huffman_decoder_t{}; var dist_dec: hm.huffman_decoder_t = hm.huffman_decoder_t{}; s = init_dyn_decoders(is, &litlen_dec, &dist_dec); if (s != inf_stat_t.HWINF_OK) { return s; } return inf_block(is, dst, dst_cap, dst_pos, &litlen_dec, &dist_dec); } fn inf_fixed_block( is: *bs.istream_t, dst: [*]u8, dst_cap: usize, dst_pos: *usize, ) inf_stat_t { var litlen_dec: hm.huffman_decoder_t = hm.huffman_decoder_t{}; var dist_dec: hm.huffman_decoder_t = hm.huffman_decoder_t{}; _ = hm.huffman_decoder_init( &litlen_dec, &tables.fixed_litlen_lengths, tables.fixed_litlen_lengths.len, ); _ = hm.huffman_decoder_init( &dist_dec, &tables.fixed_dist_lengths, tables.fixed_dist_lengths.len, ); return inf_block(is, dst, dst_cap, dst_pos, &litlen_dec, &dist_dec); } fn inf_noncomp_block( is: *bs.istream_t, dst: [*]u8, dst_cap: usize, dst_pos: *usize, ) inf_stat_t { var p: [*]const u8 = undefined; var len: u16 = 0; var nlen: u16 = 0; p = @ptrCast([*]const u8, bs.istream_byte_align(is)); // Read len and nlen (2 x 16 bits). if (!bs.istream_advance(is, 32)) { return inf_stat_t.HWINF_ERR; // Not enough input. } len = bu.read16le(p); nlen = bu.read16le(p + 2); p += 4; if (nlen != (~len & 0xffff)) { return inf_stat_t.HWINF_ERR; } if (!bs.istream_advance(is, @intCast(usize, len) * 8)) { return inf_stat_t.HWINF_ERR; // Not enough input. } if (dst_cap - dst_pos.* < len) { return inf_stat_t.HWINF_FULL; // Not enough room to output. } mem.copy(u8, dst[(dst_pos.*)..(dst_pos.* + len)], p[0..len]); dst_pos.* += len; return inf_stat_t.HWINF_OK; } // Decompress (inflate) the Deflate stream in src. The number of input bytes // used, at most src_len, is stored in *src_used on success. Output is written // to dst. The number of bytes written, at most dst_cap, is stored in *dst_used // on success. src[0..src_len-1] and dst[0..dst_cap-1] must not overlap. pub fn hwinflate( src: [*]const u8, src_len: usize, src_used: *usize, dst: [*]u8, dst_cap: usize, dst_used: *usize, ) inf_stat_t { var is: bs.istream_t = undefined; var dst_pos: usize = 0; var bits: u64 = 0; var bfinal: u1 = 0; var s: inf_stat_t = undefined; bs.istream_init(&is, src, src_len); dst_pos = 0; while (bfinal == 0) { // Read the 3-bit block header. bits = bs.istream_bits(&is); if (!bs.istream_advance(&is, 3)) { return inf_stat_t.HWINF_ERR; } bfinal = @truncate(u1, bits & @as(u64, 1)); bits >>= 1; s = switch (bu.lsb(bits, 2)) { // 00: No compression. 0 => inf_noncomp_block(&is, dst, dst_cap, &dst_pos), // 01: Compressed with fixed Huffman codes. 1 => inf_fixed_block(&is, dst, dst_cap, &dst_pos), // 10: Compressed with "dynamic" Huffman codes. 2 => inf_dyn_block(&is, dst, dst_cap, &dst_pos), // Invalid block type. else => return inf_stat_t.HWINF_ERR, }; if (s != inf_stat_t.HWINF_OK) { return s; } } src_used.* = bs.istream_bytes_read(&is); assert(dst_pos <= dst_cap); dst_used.* = dst_pos; return inf_stat_t.HWINF_OK; } // The largest number of bytes that will fit in any kind of block is 65,534. // It will fit in an uncompressed block (max 65,535 bytes) and a Huffman // block with only literals (65,535 symbols including end-of-block marker). */ const MAX_BLOCK_LEN_BYTES = 65534; const deflate_state_t: type = struct { os: bs.ostream_t, block_src: [*]const u8, // First src byte in the block. block_len: usize, // Number of symbols in the current block. block_len_bytes: usize, // Number of src bytes in the block. // Symbol frequencies for the current block. litlen_freqs: [LITLEN_MAX + 1]u16, dist_freqs: [DISTSYM_MAX + 1]u16, block: [MAX_BLOCK_LEN_BYTES + 1]struct { distance: u16, // Backref distance. u: packed union { lit: u16, // Literal byte or end-of-block. len: u16, // Backref length (distance != 0). }, }, }; fn reset_block(s: *deflate_state_t) void { s.block_len = 0; s.block_len_bytes = 0; mem.set(u16, s.litlen_freqs[0..], 0); mem.set(u16, s.dist_freqs[0..], 0); } const codelen_sym_t: type = struct { sym: u8, count: u8, // For symbols 16, 17, 18. }; inline fn min(a: usize, b: usize) usize { return if (a < b) a else b; } // Encode the n code lengths in lens into encoded, returning the number of // elements in encoded. fn encode_lens(lens: [*]const u8, n: usize, encoded: [*]codelen_sym_t) usize { var i: usize = 0; var j: usize = 0; var num_encoded: usize = 0; var count: u8 = 0; i = 0; num_encoded = 0; while (i < n) { if (lens[i] == 0) { // Scan past the end of this zero run (max 138). j = i; while (j < min(n, i + CODELEN_ZEROS2_MAX) and lens[j] == 0) : (j += 1) {} count = @intCast(u8, j - i); if (count < CODELEN_ZEROS_MIN) { // Output a single zero. encoded[num_encoded].sym = 0; num_encoded += 1; i += 1; continue; } // Output a repeated zero. if (count <= CODELEN_ZEROS_MAX) { // Repeated zero 3--10 times. assert(count >= CODELEN_ZEROS_MIN and count <= CODELEN_ZEROS_MAX); encoded[num_encoded].sym = CODELEN_ZEROS; encoded[num_encoded].count = count; num_encoded += 1; } else { // Repeated zero 11--138 times. assert(count >= CODELEN_ZEROS2_MIN and count <= CODELEN_ZEROS2_MAX); encoded[num_encoded].sym = CODELEN_ZEROS2; encoded[num_encoded].count = count; num_encoded += 1; } i = j; continue; } // Output len. encoded[num_encoded].sym = lens[i]; i += 1; num_encoded += 1; // Scan past the end of the run of this len (max 6). j = i; while (j < min(n, i + CODELEN_COPY_MAX) and lens[j] == lens[i - 1]) : (j += 1) {} count = @intCast(u8, j - i); if (count >= CODELEN_COPY_MIN) { // Repeat last len 3--6 times. assert(count >= CODELEN_COPY_MIN and count <= CODELEN_COPY_MAX); encoded[num_encoded].sym = CODELEN_COPY; encoded[num_encoded].count = count; num_encoded += 1; i = j; continue; } } return num_encoded; } // Zlib always emits two non-zero distance codeword lengths (see build_trees), // and versions before 1.2.1.1 (and possibly other implementations) would fail // to inflate compressed data where that's not the case. See comment in // https://github.com/google/zopfli/blob/zopfli-1.0.3/src/zopfli/deflate.c#L75 // Tweak the encoder to ensure compatibility. fn tweak_dist_encoder(e: *hm.huffman_encoder_t) void { var i: usize = 0; var n: usize = 0; var nonzero_idx: usize = SIZE_MAX; n = 0; i = 0; while (i <= DISTSYM_MAX) : (i += 1) { if (e.lengths[i] != 0) { n += 1; nonzero_idx = i; if (n == 2) { return; } } } assert(n < 2); if (n == 0) { // Give symbols 0 and 1 codewords of length 1. e.lengths[0] = 1; e.lengths[1] = 1; e.codewords[0] = 0; e.codewords[1] = 1; return; } assert(n == 1); assert(nonzero_idx != SIZE_MAX); if (nonzero_idx == 0) { // Symbol 0 already has a codeword of length 1. // Give symbol 1 a codeword of length 1. assert(e.lengths[0] == 1); assert(e.codewords[0] == 0); e.lengths[1] = 1; e.codewords[1] = 1; } else { // Give symbol 0 a codeword of length 1 ("0") and // update the other symbol's codeword to "1". assert(e.lengths[0] == 0); assert(e.codewords[nonzero_idx] == 0); e.lengths[0] = 1; e.codewords[0] = 0; e.codewords[nonzero_idx] = 1; } } // Encode litlen_lens and dist_lens into encoded. *num_litlen_lens and // *num_dist_lens will be set to the number of encoded litlen and dist lens, // respectively. Returns the number of elements in encoded. fn encode_dist_litlen_lens( litlen_lens: [*]const u8, dist_lens: [*]const u8, encoded: [*]codelen_sym_t, num_litlen_lens: *usize, num_dist_lens: *usize, ) usize { var i: usize = 0; var n: usize = 0; var lens: [LITLEN_MAX + 1 + DISTSYM_MAX + 1]u8 = undefined; num_litlen_lens.* = LITLEN_MAX + 1; num_dist_lens.* = DISTSYM_MAX + 1; // Drop trailing zero litlen lengths. assert(litlen_lens[LITLEN_EOB] != 0); // "EOB len should be non-zero." while (litlen_lens[num_litlen_lens.* - 1] == 0) { num_litlen_lens.* -= 1; } assert(num_litlen_lens.* >= MIN_LITLEN_LENS); // Drop trailing zero dist lengths, keeping at least one. while (dist_lens[num_dist_lens.* - 1] == 0 and num_dist_lens.* > 1) { num_dist_lens.* -= 1; } assert(num_dist_lens.* >= MIN_DIST_LENS); // Copy the lengths into a unified array. n = 0; i = 0; while (i < num_litlen_lens.*) : (i += 1) { lens[n] = litlen_lens[i]; n += 1; } i = 0; while (i < num_dist_lens.*) : (i += 1) { lens[n] = dist_lens[i]; n += 1; } return encode_lens(&lens, n, encoded); } // Count the number of significant (not trailing zeros) codelen lengths. fn count_codelen_lens(codelen_lens: [*]const u8) usize { var n: usize = MAX_CODELEN_LENS; // Drop trailing zero lengths. while (codelen_lens[codelen_lengths_order[n - 1]] == 0) { n -= 1; } // The first 4 lengths in the order (16, 17, 18, 0) cannot be used to // encode any non-zero lengths. Since there will always be at least // one non-zero codeword length (for EOB), n will be >= 4. assert(n >= MIN_CODELEN_LENS and n <= MAX_CODELEN_LENS); return n; } // Calculate the number of bits for an uncompressed block, including header. fn uncomp_block_len(s: *const deflate_state_t) usize { var bit_pos: usize = 0; var padding: usize = 0; // Bit position after writing the block header. bit_pos = bs.ostream_bit_pos(&s.os) + 3; padding = bu.round_up(bit_pos, 8) - bit_pos; // Header + padding + len/nlen + block contents. return 3 + padding + 2 * 16 + s.block_len_bytes * 8; } // Calculate the number of bits for a Huffman encoded block body. */ fn huffman_block_body_len( s: *const deflate_state_t, litlen_lens: [*]const u8, dist_lens: [*]const u8, ) usize { var i: usize = 0; var freq: usize = 0; var len: usize = 0; len = 0; i = 0; while (i <= LITLEN_MAX) : (i += 1) { freq = s.litlen_freqs[i]; len += litlen_lens[i] * freq; if (i >= LITLEN_TBL_OFFSET) { len += tables.litlen_tbl[i - LITLEN_TBL_OFFSET].ebits * freq; } } i = 0; while (i <= DISTSYM_MAX) : (i += 1) { freq = s.dist_freqs[i]; len += dist_lens[i] * freq; len += tables.dist_tbl[i].ebits * freq; } return len; } // Calculate the number of bits for a dynamic Huffman block. fn dyn_block_len( s: *const deflate_state_t, num_codelen_lens: usize, codelen_freqs: [*]const u16, codelen_enc: *const hm.huffman_encoder_t, litlen_enc: *const hm.huffman_encoder_t, dist_enc: *const hm.huffman_encoder_t, ) usize { var len: usize = 0; var i: usize = 0; var freq: usize = 0; // Block header. len = 3; // Nbr of litlen, dist, and codelen lengths. len += 5 + 5 + 4; // Codelen lengths. len += 3 * num_codelen_lens; // Codelen encoding. i = 0; while (i < MAX_CODELEN_LENS) : (i += 1) { freq = codelen_freqs[i]; len += codelen_enc.lengths[i] * freq; // Extra bits. if (i == CODELEN_COPY) { len += 2 * freq; } else if (i == CODELEN_ZEROS) { len += 3 * freq; } else if (i == CODELEN_ZEROS2) { len += 7 * freq; } } return len + huffman_block_body_len(s, &litlen_enc.lengths, &dist_enc.lengths); } fn distance2dist(distance: usize) u8 { assert(distance >= 1 and distance <= MAX_DISTANCE); return if (distance <= 256) tables.distance2dist_lo[(distance - 1)] else tables.distance2dist_hi[(distance - 1) >> 7]; } fn write_huffman_block( s: *deflate_state_t, litlen_enc: *const hm.huffman_encoder_t, dist_enc: *const hm.huffman_encoder_t, ) bool { var i: usize = 0; var nbits: usize = 0; var distance: u16 = 0; var dist: u16 = 0; var len: u16 = 0; var litlen: u16 = 0; var bits: u64 = 0; var ebits: u64 = 0; i = 0; while (i < s.block_len) : (i += 1) { if (s.block[i].distance == 0) { // Literal or EOB. litlen = s.block[i].u.lit; assert(litlen <= LITLEN_EOB); if (!bs.ostream_write(&s.os, litlen_enc.codewords[litlen], litlen_enc.lengths[litlen])) { return false; } continue; } // Back reference length. len = s.block[i].u.len; litlen = tables.len2litlen[len]; // litlen bits bits = litlen_enc.codewords[litlen]; nbits = litlen_enc.lengths[litlen]; // ebits ebits = len - tables.litlen_tbl[litlen - LITLEN_TBL_OFFSET].base_len; bits |= ebits << @intCast(u6, nbits); nbits += tables.litlen_tbl[litlen - LITLEN_TBL_OFFSET].ebits; // Back reference distance. distance = s.block[i].distance; dist = distance2dist(distance); // dist bits bits |= @intCast(u64, dist_enc.codewords[dist]) << @intCast(u6, nbits); nbits += dist_enc.lengths[dist]; // ebits ebits = distance - tables.dist_tbl[dist].base_dist; bits |= ebits << @intCast(u6, nbits); nbits += tables.dist_tbl[dist].ebits; if (!bs.ostream_write(&s.os, bits, nbits)) { return false; } } return true; } fn write_dynamic_block( s: *deflate_state_t, final: bool, num_litlen_lens: usize, num_dist_lens: usize, num_codelen_lens: usize, codelen_enc: *const hm.huffman_encoder_t, encoded_lens: [*]const codelen_sym_t, num_encoded_lens: usize, litlen_enc: *const hm.huffman_encoder_t, dist_enc: *const hm.huffman_encoder_t, ) bool { var i: usize = 0; var codelen: u8 = 0; var sym: u8 = 0; var nbits: u6 = 0; var bits: u64 = 0; var hlit: u64 = 0; var hdist: u64 = 0; var hclen: u64 = 0; var count: u64 = 0; // Block header. var is_final: u64 = if (final) 1 else 0; bits = (0x2 << 1) | is_final; nbits = 3; // hlit (5 bits) hlit = num_litlen_lens - MIN_LITLEN_LENS; bits |= hlit << nbits; nbits += 5; // hdist (5 bits) hdist = num_dist_lens - MIN_DIST_LENS; bits |= hdist << nbits; nbits += 5; // hclen (4 bits) hclen = num_codelen_lens - MIN_CODELEN_LENS; bits |= hclen << nbits; nbits += 4; if (!bs.ostream_write(&s.os, bits, nbits)) { return false; } // Codelen lengths. i = 0; while (i < num_codelen_lens) : (i += 1) { codelen = codelen_enc.lengths[codelen_lengths_order[i]]; if (!bs.ostream_write(&s.os, codelen, 3)) { return false; } } // Litlen and dist code lengths. i = 0; while (i < num_encoded_lens) : (i += 1) { sym = encoded_lens[i].sym; bits = codelen_enc.codewords[sym]; nbits = @intCast(u6, codelen_enc.lengths[sym]); count = encoded_lens[i].count; if (sym == CODELEN_COPY) { // 2 ebits bits |= (count - CODELEN_COPY_MIN) << nbits; nbits += 2; } else if (sym == CODELEN_ZEROS) { // 3 ebits bits |= (count - CODELEN_ZEROS_MIN) << nbits; nbits += 3; } else if (sym == CODELEN_ZEROS2) { // 7 ebits bits |= (count - CODELEN_ZEROS2_MIN) << nbits; nbits += 7; } if (!bs.ostream_write(&s.os, bits, nbits)) { return false; } } return write_huffman_block(s, litlen_enc, dist_enc); } fn write_static_block(s: *deflate_state_t, final: bool) bool { var litlen_enc: hm.huffman_encoder_t = undefined; var dist_enc: hm.huffman_encoder_t = undefined; // Write the block header. var is_final: u64 = if (final) 1 else 0; if (!bs.ostream_write(&s.os, @as(u64, 0b10) | is_final, 3)) { return false; } hm.huffman_encoder_init2( &litlen_enc, &tables.fixed_litlen_lengths, tables.fixed_litlen_lengths.len, ); hm.huffman_encoder_init2( &dist_enc, &tables.fixed_dist_lengths, tables.fixed_dist_lengths.len, ); return write_huffman_block(s, &litlen_enc, &dist_enc); } fn write_uncomp_block(s: *deflate_state_t, final: bool) bool { var len_nlen: [4]u8 = undefined; // Write the block header. var is_final: u64 = if (final) 1 else 0; if (!bs.ostream_write(&s.os, is_final, 3)) { return false; } len_nlen[0] = @truncate(u8, s.block_len_bytes >> 0); len_nlen[1] = @intCast(u8, s.block_len_bytes >> 8); len_nlen[2] = ~len_nlen[0]; len_nlen[3] = ~len_nlen[1]; if (!bs.ostream_write_bytes_aligned(&s.os, &len_nlen, len_nlen.len)) { return false; } if (!bs.ostream_write_bytes_aligned(&s.os, s.block_src, s.block_len_bytes)) { return false; } return true; } // Write the current deflate block, marking it final if that parameter is true, // returning false if there is not enough room in the output stream. fn write_block(s: *deflate_state_t, final: bool) bool { var old_bit_pos: usize = 0; var uncomp_len: usize = 0; var static_len: usize = 0; var dynamic_len: usize = 0; var dyn_litlen_enc: hm.huffman_encoder_t = undefined; var dyn_dist_enc: hm.huffman_encoder_t = undefined; var codelen_enc: hm.huffman_encoder_t = undefined; var num_encoded_lens: usize = 0; var num_litlen_lens: usize = 0; var num_dist_lens: usize = 0; var encoded_lens: [LITLEN_MAX + 1 + DISTSYM_MAX + 1]codelen_sym_t = undefined; var codelen_freqs: [MAX_CODELEN_LENS]u16 = [_]u16{0} ** MAX_CODELEN_LENS; var num_codelen_lens: usize = 0; var i: usize = 0; old_bit_pos = bs.ostream_bit_pos(&s.os); // Add the end-of-block marker in case we write a Huffman block. assert(s.block_len < s.block.len); assert(s.litlen_freqs[LITLEN_EOB] == 0); s.block[s.block_len].distance = 0; s.block[s.block_len].u.lit = LITLEN_EOB; s.block_len += 1; s.litlen_freqs[LITLEN_EOB] = 1; uncomp_len = uncomp_block_len(s); static_len = 3 + huffman_block_body_len(s, &tables.fixed_litlen_lengths, &tables.fixed_dist_lengths); // Compute "dynamic" Huffman codes. hm.huffman_encoder_init(&dyn_litlen_enc, &s.litlen_freqs, LITLEN_MAX + 1, 15); hm.huffman_encoder_init(&dyn_dist_enc, &s.dist_freqs, DISTSYM_MAX + 1, 15); tweak_dist_encoder(&dyn_dist_enc); // Encode the litlen and dist code lengths. num_encoded_lens = encode_dist_litlen_lens( &dyn_litlen_enc.lengths, &dyn_dist_enc.lengths, &encoded_lens, &num_litlen_lens, &num_dist_lens, ); // Compute the codelen code. i = 0; while (i < num_encoded_lens) : (i += 1) { codelen_freqs[encoded_lens[i].sym] += 1; } hm.huffman_encoder_init(&codelen_enc, &codelen_freqs, MAX_CODELEN_LENS, 7); num_codelen_lens = count_codelen_lens(&codelen_enc.lengths); dynamic_len = dyn_block_len( s, num_codelen_lens, &codelen_freqs, &codelen_enc, &dyn_litlen_enc, &dyn_dist_enc, ); if (uncomp_len <= dynamic_len and uncomp_len <= static_len) { if (!write_uncomp_block(s, final)) { return false; } assert(bs.ostream_bit_pos(&s.os) - old_bit_pos == uncomp_len); } else if (static_len <= dynamic_len) { if (!write_static_block(s, final)) { return false; } assert(bs.ostream_bit_pos(&s.os) - old_bit_pos == static_len); } else { if (!write_dynamic_block( s, final, num_litlen_lens, num_dist_lens, num_codelen_lens, &codelen_enc, &encoded_lens, num_encoded_lens, &dyn_litlen_enc, &dyn_dist_enc, )) { return false; } assert(bs.ostream_bit_pos(&s.os) - old_bit_pos == dynamic_len); } return true; } fn lit_callback(lit: u8, aux: anytype) bool { var s: *deflate_state_t = aux; if (s.block_len_bytes + 1 > MAX_BLOCK_LEN_BYTES) { if (!write_block(s, false)) { return false; } s.block_src += s.block_len_bytes; reset_block(s); } assert(s.block_len < s.block.len); s.block[s.block_len].distance = 0; s.block[s.block_len].u.lit = lit; s.block_len += 1; s.block_len_bytes += 1; s.litlen_freqs[lit] += 1; return true; } fn backref_callback(dist: usize, len: usize, aux: anytype) bool { var s: *deflate_state_t = aux; if (s.block_len_bytes + len > MAX_BLOCK_LEN_BYTES) { if (!write_block(s, false)) { return false; } s.block_src += s.block_len_bytes; reset_block(s); } assert(s.block_len < s.block.len); s.block[s.block_len].distance = @intCast(u16, dist); s.block[s.block_len].u.len = @intCast(u16, len); s.block_len += 1; s.block_len_bytes += len; assert(len >= MIN_LEN and len <= MAX_LEN); assert(dist >= MIN_DISTANCE and dist <= MAX_DISTANCE); s.litlen_freqs[tables.len2litlen[len]] += 1; s.dist_freqs[distance2dist(dist)] += 1; return true; } // PKZip Method 8: Deflate / Inflate. // Compress (deflate) the data in src into dst. The number of bytes output, at // most dst_cap, is stored in *dst_used. Returns false if there is not enough // room in dst. src and dst must not overlap. pub fn hwdeflate(src: [*]const u8, src_len: usize, dst: [*]u8, dst_cap: usize, dst_used: *usize) bool { var s: deflate_state_t = undefined; bs.ostream_init(&s.os, dst, dst_cap); reset_block(&s); s.block_src = src; if (!lz.lz77_compress( src, src_len, MAX_DISTANCE, MAX_LEN, true, lit_callback, backref_callback, &s, )) { return false; } if (!write_block(&s, true)) { return false; } // The end of the final block should match the end of src. assert(s.block_src + s.block_len_bytes == src + src_len); dst_used.* = bs.ostream_bytes_written(&s.os); return true; }
src/deflate.zig
const std = @import("std"); const ascii = std.ascii; const fmt = std.fmt; const mem = std.mem; const unicode = std.unicode; const testing = std.testing; const expect = testing.expect; // Key is a key of hash tables to be used in this package. pub const Key = std.ArrayList(u8); // Table is a table from a key to a TOML value. pub const Table = std.HashMap(Key, Value, hashKey, eqlKey); fn eqlKey(a: Key, b: Key) bool { return std.mem.eql(u8, a.items, b.items); } fn hashKey(a: Key) u32 { return std.hash_map.hashString(a.items); } pub const ValueTag = enum { String, Int, Float, Bool, Table, Array, }; // Value represents a TOML value. // TODO: support date/datetime format. pub const Value = union(ValueTag) { String: std.ArrayList(u8), Int: i64, Float: f64, Bool: bool, Table: Table, Array: std.ArrayList(Value), pub fn deinit(self: Value) void { switch (self) { .String => |str| str.deinit(), .Table => |data| { var i = data.iterator(); while (i.next()) |kv| { kv.key.deinit(); kv.value.deinit(); } data.deinit(); }, .Array => |objs| { for (objs.items) |item| { item.deinit(); } objs.deinit(); }, else => {}, } } pub fn get(self: Value, key: []const u8) ?Value { if (self != .Table) return null; var a = Key.init(self.Table.allocator); defer a.deinit(); if (a.appendSlice(key)) |_| { if (self.Table.get(a)) |kv| { return kv.value; } else { return null; } } else |err| { return null; } } pub fn idx(self: Value, i: usize) ?Value { if (self != .Array) return null; if (i >= self.Array.items.len) return null; return self.Array.items[i]; } // size returns the number of children in the value. // If self is a string, it returns the string length. // It returns 0 for other leaf values. pub fn size(self: Value) usize { switch (self) { .Table => |tbl| return tbl.size, .Array => |arr| return arr.items.len, .String => |str| return str.items.len, else => return 0, } } }; // ParseError is the possible error during parsing. pub const ParseError = error { // Generic failure of parsing, incorrect syntax. FailedToParse, // The key name conflict. DuplicatedKey, // The receiving data type is not as expected. IncorrectDataType, // The return type is not supported. UnknownReturnType, // No related field is found for a key. FieldNotFound, // Expected to see a linebeak but could not found. LinebreakExpected, }; const VisitType = enum { // Not visited None, // Unable to extend through bracket CantExtend, // Unable to extend through both bracket and keyvalue CantExtendKeyvalue, // Can extend by bracket Extendable, }; const VisitedNode = struct { visit_type: VisitType, children: std.HashMap(Key, VisitedNode, hashKey, eqlKey), allocator: *mem.Allocator, fn init(allocator: *mem.Allocator) VisitedNode { return .{ .visit_type = .None, .children = std.HashMap(Key, VisitedNode, hashKey, eqlKey).init(allocator), .allocator = allocator, }; } fn deinit(self: VisitedNode) void { var i = self.children.iterator(); while (i.next()) |kv| { kv.key.deinit(); kv.value.deinit(); } self.children.deinit(); } fn visitedType(self: *VisitedNode, key: Key) VisitType { if (self.children.get(key)) |kv| { return kv.value.visit_type; } return .None; } fn markVisited(self: *VisitedNode, key: Key, visit_type: VisitType) !void { var copiedKey = Key.init(self.allocator); _ = copiedKey.appendSlice(key.items) catch |err| { copiedKey.deinit(); return err; }; var gpr = self.children.getOrPut(copiedKey) catch |err| { copiedKey.deinit(); return err; }; if (gpr.found_existing) { copiedKey.deinit(); gpr.kv.value.visit_type = visit_type; } else { var v = VisitedNode.init(self.allocator); v.visit_type = visit_type; gpr.kv.value = v; } } fn idxToKey(self: *VisitedNode, idx: usize) !Key { var key = Key.init(self.allocator); try std.fmt.formatInt(idx, 16, false, std.fmt.FormatOptions{}, key.outStream()); return key; } fn markVisitedIdx(self: *VisitedNode, idx: usize, visit_type: VisitType) !void { var key = try self.idxToKey(idx); defer key.deinit(); return self.markVisited(key, visit_type); } fn getChild(self: *VisitedNode, key: Key) ?*VisitedNode { if (self.children.get(key)) |kv| { return &kv.value; } return null; } fn getChildIdx(self: *VisitedNode, idx: usize) ?*VisitedNode { var key = self.idxToKey(idx) catch return null; defer key.deinit(); return self.getChild(key); } }; // Parser is a parser of TOML. Use 'parse' method to create the parsed result. // It takes an allocator as a parameter, and the parse results and its internal // structure will be allocated by this allocator. // If the specified type has init() and deinit() functions, it will use these // methods for allocating/deallocating the object. pub const Parser = struct { allocator: *std.mem.Allocator, pub fn init(allocator: *std.mem.Allocator) !*Parser { var parser = try allocator.create(Parser); parser.allocator = allocator; return parser; } fn skipSpaces(self: *Parser, input: []const u8, offset: usize) usize { var i = offset; while (i < input.len and (input[i] == ' ' or input[i] == '\t')) : (i+=1) {} return i; } fn skipSpacesAndCommentsWithLinebreak(self: *Parser, input: []const u8, offset: usize, has_linebreak: *bool) usize { var i = offset; while (i < input.len) : (i+=1) { if (input[i] == '#') { while (i < input.len and input[i] != '\n') : (i+=1) {} has_linebreak.* = true; } else if (input[i] == '\n') { has_linebreak.* = true; } else if (!ascii.isSpace(input[i])) { return i; } } return i; } fn skipSpacesAndComments(self: *Parser, input: []const u8, offset: usize) usize { var has_linebreak = false; return self.skipSpacesAndCommentsWithLinebreak(input, offset, &has_linebreak); } fn parseTrue(self: *Parser, input: []const u8, offset: usize, value: *bool) ParseError!usize { if (offset+4 > input.len) { return ParseError.FailedToParse; } if (!mem.eql(u8, "true", input[offset..(offset+4)])) { return ParseError.FailedToParse; } if (offset+4 < input.len and ascii.isAlNum(input[offset+4])) { return ParseError.FailedToParse; } value.* = true; return offset+4; } fn parseFalse(self: *Parser, input: []const u8, offset: usize, value: *bool) ParseError!usize { if (offset+5 > input.len) { return ParseError.FailedToParse; } if (!mem.eql(u8, "false", input[offset..(offset+5)])) { return ParseError.FailedToParse; } if (offset+5 < input.len and ascii.isAlNum(input[offset+5])) { return ParseError.FailedToParse; } value.* = false; return offset+5; } fn parseBool(self: *Parser, input: []const u8, offset: usize, value: *bool) ParseError!usize { return self.parseTrue(input, offset, value) catch self.parseFalse(input, offset, value); } fn parseInt(self: *Parser, input: []const u8, offset: usize, comptime T: type, value: *T) !usize { var i = offset; var start = offset; var initial = true; var underscore_count: u64 = 0; var base: u8 = 10; while (i < input.len) : (i+=1) { if (initial and (input[i] == '+' or input[i] == '-')) { // Negative value is set for unsigned types. if (!@typeInfo(T).Int.is_signed and input[i] == '-') return ParseError.IncorrectDataType; initial = false; continue; } if (initial and input[i] == '0' and i+1 < input.len) { var n = ascii.toLower(input[i+1]); if (n == 'o' or n == 'x' or n == 'b') { initial = false; i += 1; start+=2; base = switch (n) { 'x' => 16, 'o' => 8, 'b' => 2, else => undefined, }; continue; } } initial = false; if (input[i] == '_') { underscore_count += 1; continue; } const c = input[i]; if (ascii.isDigit(c) and (c - '0') < base) { continue; } if (base > 10 and ascii.isAlpha(c) and (ascii.toLower(c) - 'a' + 10) < base) { continue; } if (ascii.isAlpha(c)) { return ParseError.FailedToParse; } break; } if (i == start) { return ParseError.FailedToParse; } var buf: []const u8 = undefined; var buf_for_cleanup: []u8 = undefined; var buf_allocated = (underscore_count > 0); defer if (buf_allocated) { self.allocator.free(buf_for_cleanup); }; if (buf_allocated) { buf_for_cleanup = try self.allocator.alloc(u8, i-start-underscore_count); var j = start; var p: usize = 0; while (j < i) : (j+=1) { if (input[j] != '_') { buf_for_cleanup[p] = input[j]; p+=1; } } buf = buf_for_cleanup; } else { buf = input[start..i]; } value.* = try fmt.parseInt(T, buf, base); return i; } fn checkSignedPattern(self: *Parser, input: []const u8, offset: usize, pattern: []const u8) ?usize { var i = offset; if (input[i] == '+' or input[i] == '-') i+=1; if (i+pattern.len > input.len) return null; if (!mem.eql(u8, input[i..(i+pattern.len)], pattern)) return null; if (i+pattern.len == input.len or !ascii.isAlNum(input[i+pattern.len])) return i+pattern.len; return null; } fn parseFloat(self: *Parser, input: []const u8, offset: usize, comptime T: type, value: *T) !usize { if (self.checkSignedPattern(input, offset, "inf")) |out| { if (input[offset] == '-') { value.* = -std.math.inf(T); } else { value.* = std.math.inf(T); } return out; } if (self.checkSignedPattern(input, offset, "nan")) |out| { value.* = std.math.nan(T); return out; } var i = offset; var has_e = false; var has_num = false; var has_dot = false; var allow_sign = true; while (i < input.len) : (i+=1) { const c = input[i]; if (allow_sign and (c == '+' or c == '-')) { allow_sign = false; continue; } allow_sign = false; if (has_num and !has_e and ascii.toLower(c) == 'e') { has_e = true; allow_sign = true; continue; } if (ascii.isDigit(c)) { has_num = true; continue; } if (!has_dot and !has_e and c == '.') { has_dot = true; continue; } if (ascii.isAlpha(c)) return ParseError.FailedToParse; break; } if (i == offset) { return ParseError.FailedToParse; } if (!has_dot and !has_e) { return ParseError.FailedToParse; } value.* = try fmt.parseFloat(T, input[offset..i]); return i; } fn hasPrefix(s: []const u8, p: []const u8) bool { if (s.len < p.len) { return false; } for (p) |c, i| { if (s[i] != c) { return false; } } return true; } fn parseQuotedString(self: *Parser, input: []const u8, offset: usize, s: *Key) !usize { if (input[offset] != '"') { return ParseError.FailedToParse; } var start = offset+1; var multiLine = false; if (hasPrefix(input[start..], "\"\"")) { start+=2; multiLine = true; if (start < input.len and input[start] == '\n') start+=1; } var end = start; var inSkippingSpaces = false; var upperSurrogate: ?u21 = null; while (end < input.len) : (end += 1) { if (input[end] == '\\') { if (end >= input.len-1) { return ParseError.FailedToParse; } end+=1; _ = switch (input[end]) { 'b' => try s.append('\x08'), 't' => try s.append('\t'), 'n' => try s.append('\n'), 'f' => try s.append('\x0c'), 'r' => try s.append('\r'), '"' => try s.append('\"'), '\\' => try s.append('\\'), '\n' => { if (!multiLine) { return ParseError.FailedToParse; } inSkippingSpaces = true; }, 'u' => { end+=1; if (end+4>input.len) { return ParseError.FailedToParse; } var chr = try fmt.parseInt(u21, input[end..(end+4)], 16); if (chr >= 0xd800 and chr <= 0xdfff) { // handling of surrogate pair. if (upperSurrogate) |us| { chr = (((us & 0x3ff) + 0x40) << 10) | (chr & 0x3ff); upperSurrogate = null; } else { upperSurrogate = chr; end+=3; continue; } } var buf: []u8 = try self.allocator.alloc(u8, try unicode.utf8CodepointSequenceLength(chr)); defer self.allocator.free(buf); _ = try unicode.utf8Encode(chr, buf); _ = try s.appendSlice(buf); end+=3; }, 'U' => { end+=1; if (end+8>input.len) { return ParseError.FailedToParse; } var chr = try fmt.parseInt(u21, input[end..(end+8)], 16); var buf: []u8 = try self.allocator.alloc(u8, try unicode.utf8CodepointSequenceLength(chr)); defer self.allocator.free(buf); _ = try unicode.utf8Encode(chr, buf); _ = try s.appendSlice(buf); end+=7; }, else => return ParseError.FailedToParse, }; } else if (!multiLine and input[end] == '"') { return end+1; } else if (multiLine and hasPrefix(input[end..], "\"\"\"")) { end+=3; if (end < input.len and input[end] == '"') { _ = try s.append('"'); end+=1; if (end < input.len and input[end] == '"') { _ = try s.append('"'); end+=1; } } return end; } else if (multiLine and inSkippingSpaces and (ascii.isSpace(input[end]) or input[end] == '\n')) { // do nothing, skipping continue; } else if (input[end] == '\n' and !multiLine) { return ParseError.FailedToParse; } else { inSkippingSpaces = false; _ = try s.append(input[end]); } } return ParseError.FailedToParse; } fn parseLiteralString(self: *Parser, input: []const u8, offset: usize, s: *Key) !usize { if (input[offset] != '\'') { return ParseError.FailedToParse; } var start = offset+1; var multiLine = false; if (hasPrefix(input[start..], "''")) { start+=2; multiLine = true; if (start < input.len and input[start] == '\n') start+=1; } var end = start; while (end < input.len) : (end += 1) { if (!multiLine and input[end] == '\n') { return ParseError.FailedToParse; } if ((multiLine and hasPrefix(input[end..], "'''")) or (!multiLine and input[end] == '\'')) { _ = try s.appendSlice(input[start..end]); if (multiLine) { return end+3; } return end+1; } } return ParseError.FailedToParse; } fn parseString(self: *Parser, input: []const u8, offset_in: usize, s: *Key) !usize { if (input[offset_in] == '"') { return self.parseQuotedString(input, offset_in, s); } return self.parseLiteralString(input, offset_in, s); } const tokenResult = struct { token: []const u8, offset: usize }; fn parseToken(self: *Parser, input: []const u8, offset_in: usize, s: *Key) !usize { var offset = self.skipSpaces(input, offset_in); var i: usize = offset; while (i < input.len) : (i+=1) { if (!((input[i] >= 'A' and input[i] <= 'Z') or (input[i] >= 'a' and input[i] <= 'z') or (input[i] >= '0' and input[i] <= '9') or input[i] == '_' or input[i] == '-')) { break; } } if (i == offset) { return ParseError.FailedToParse; } _ = try s.appendSlice(input[offset..i]); return i; } const keyResult = struct { keys: std.ArrayList(Key), offset: usize, fn init(allocator: *std.mem.Allocator) keyResult { return .{ .keys = std.ArrayList(Key).init(allocator), .offset = 0}; } fn deinit(self: keyResult) void { for (self.keys.items) |key| { key.deinit(); } self.keys.deinit(); } }; fn parseKey(self: *Parser, input: []const u8, offset_in: usize) !keyResult { var result = keyResult.init(self.allocator); errdefer result.deinit(); var offset = offset_in; while (offset < input.len) : (offset+=1) { offset = self.skipSpaces(input, offset); var tokenArr = Key.init(self.allocator); { errdefer tokenArr.deinit(); if (input[offset] == '"') { offset = try self.parseQuotedString(input, offset, &tokenArr); } else if (input[offset] == '\'') { offset = try self.parseLiteralString(input, offset, &tokenArr); } else { offset = try self.parseToken(input, offset, &tokenArr); } } _ = try result.keys.append(tokenArr); offset = self.skipSpaces(input, offset); if (offset >= input.len or input[offset] != '.') { break; } } result.offset = offset; return result; } fn parseArray(self: *Parser, input: []const u8, offset_in: usize, visited: *VisitedNode, comptime T: type, v: *std.ArrayList(T)) anyerror!usize { if (input[offset_in] != '[') { return ParseError.FailedToParse; } var offset = offset_in+1; while (true) { offset = self.skipSpacesAndComments(input, offset); if (input[offset] == ']') return offset+1; var e = try self.createT(T); errdefer self.destroyT(T, e); offset = try self.parseValue(input, offset, visited, T, &e); _ = try v.append(e); offset = self.skipSpacesAndComments(input, offset); if (input[offset] == ']') { return offset+1; } else if (input[offset] != ',') { return ParseError.FailedToParse; } offset = self.skipSpacesAndComments(input, offset+1); } return ParseError.FailedToParse; } fn parseInlineTable(self: *Parser, input: []const u8, offset_in: usize, visited: *VisitedNode, comptime T: type, v: *T) !usize { if (input[offset_in] != '{') return ParseError.FailedToParse; var offset = offset_in+1; while (true) { offset = self.skipSpacesAndComments(input, offset); if (input[offset] == '}') return offset+1; offset = try self.parseAssign(input, offset, visited, T, v); offset = self.skipSpacesAndComments(input, offset); if (input[offset] == '}') { return offset+1; } else if (input[offset] != ',') { return ParseError.FailedToParse; } offset+=1; } return ParseError.FailedToParse; } fn parseValue(self: *Parser, input: []const u8, offset_in: usize, visited: *VisitedNode, comptime T: type, v: *T) !usize { var offset = self.skipSpaces(input, offset_in); if (T == Value) { if (input[offset] == '"' or input[offset] == '\'') { var s = Key.init(self.allocator); errdefer s.deinit(); offset = try self.parseString(input, offset, &s); v.* = Value{.String = s}; return offset; } else if (input[offset] == 'f' or input[offset] == 't') { var b = false; offset = try self.parseBool(input, offset, &b); v.* = Value{.Bool = b}; return offset; } else if (input[offset] == '[') { var a = std.ArrayList(Value).init(self.allocator); errdefer a.deinit(); offset = try self.parseArray(input, offset, visited, Value, &a); v.* = Value{.Array = a}; return offset; } else if (input[offset] == '{') { v.* = Value{.Table = Table.init(self.allocator)}; errdefer v.deinit(); return self.parseInlineTable(input, offset, visited, Value, v); } var f: f64 = 0.0; if (self.parseFloat(input, offset, f64, &f)) |offset_out| { v.* = Value{.Float = f}; return offset_out; } else |err| { var i: i64 = 0; offset = try self.parseInt(input, offset, i64, &i); v.* = Value{.Int = i}; return offset; } } if (T == Key) { var s = Key.init(self.allocator); errdefer s.deinit(); offset = try self.parseString(input, offset, &s); v.* = Value{.String = s}; return offset; } switch (@typeInfo(T)) { .Bool => return self.parseBool(input, offset, v), .Int => return self.parseInt(input, offset, T, v), .Float => return self.parseFloat(input, offset, T, v), .Enum => |e| { if (input[offset] == '"' or input[offset] == '\'') { var s = Key.init(self.allocator); defer s.deinit(); offset = try self.parseString(input, offset, &s); inline for (e.fields) |field| { if (mem.eql(u8, field.name, s.items)) { v.* = @intToEnum(T, field.value); return offset; } } return ParseError.IncorrectDataType; } var i: e.tag_type = 0; offset = try self.parseInt(input, offset, e.tag_type, &i); v.* = @intToEnum(T, i); return offset; }, .Pointer => |ptr| { if (ptr.size == .One) { v.* = try self.allocator.create(ptr.child); errdefer self.allocator.destroy(v.*); return self.parseValue(input, offset, visited, ptr.child, v.*); } var allocator = if (ptr.size == .C) std.heap.c_allocator else self.allocator ; var a = std.ArrayList(ptr.child).init(allocator); errdefer a.deinit(); if (ptr.child == u8) { offset = try if (input[offset] == '[') self.parseArray(input, offset, visited, ptr.child, &a) else self.parseString(input, offset, &a); } else { offset = try self.parseArray(input, offset, visited, ptr.child, &a); } v.* = a.items; return offset; }, .Array => |arr| { var a = sstd.ArrayList(arr.child).init(self.allocator); defer a.deinit(); if (arr.child_type == u8) { offset = try self.parseString(input, offset, &a); } else { offset = try self.parseArray(input, offset, visited, ptr.child, &a); } for (a.items) |item, i| { if (i < arr.len) { v.*[i] = item; } } return offset; }, .Struct => return self.parseInlineTable(input, offset, visited, T, v), else => return ParseError.IncorrectDataType, } } fn lookupAndParseValue(self: *Parser, input: []const u8, offset_in: usize, keys: []Key, visited: *VisitedNode, comptime T: type, v: *T) anyerror!usize { var key = Key.init(self.allocator); try key.appendSlice(keys[0].items); if (keys.len == 1) { if (visited.visitedType(key) != .None) { key.deinit(); return ParseError.DuplicatedKey; } if (T == Value) { errdefer key.deinit(); if (v.* != .Table) { return ParseError.IncorrectDataType; } try visited.markVisited(key, .CantExtendKeyvalue); var nv = Value{.Bool = false}; var offset = try self.parseValue(input, offset_in, visited, Value, &nv); _ = try v.*.Table.put(key, nv); return offset; } else { defer key.deinit(); comptime var ti = @typeInfo(T); if (ti != .Struct) return ParseError.IncorrectDataType; inline for (ti.Struct.fields) |field| { if (mem.eql(u8, key.items, field.name)) { try visited.markVisited(key, .CantExtendKeyvalue); return self.parseValue(input, offset_in, visited, field.field_type, &(@field(v, field.name))); } } return ParseError.FieldNotFound; } } var newvtype = if (keys.len > 2) VisitType.Extendable else VisitType.CantExtend; var vtype = visited.visitedType(key); if (vtype == .CantExtendKeyvalue) { key.deinit(); return ParseError.DuplicatedKey; } if (T == Value) { if (v.* == .Table) { var gpr = try v.*.Table.getOrPut(key); defer if (gpr.found_existing) key.deinit(); if (gpr.found_existing) { if (gpr.kv.value != .Table) { return ParseError.IncorrectDataType; } } else { gpr.kv.value = Value{.Table = Table.init(self.allocator)}; } if (vtype == .None or newvtype == .Extendable) try visited.markVisited(key, newvtype); return self.lookupAndParseValue( input, offset_in, keys[1..(keys.len)], visited.getChild(key).?, Value, &gpr.kv.value); } return ParseError.IncorrectDataType; } defer key.deinit(); comptime var ti = @typeInfo(T); if (ti != .Struct) return ParseError.IncorrectDataType; inline for (ti.Struct.fields) |field| { if (mem.eql(u8, key.items, field.name)) { comptime var fti = @typeInfo(field.field_type); if (fti == .Pointer and fti.Pointer.size == .One) { if (visited.visitedType(key) != .None) { return self.lookupAndParseValue( input, offset_in, keys[1..(keys.len)], visited.getChild(key).?, fti.Pointer.child, @field(v, field.name)); } try visited.markVisited(key, newvtype); var f = try self.allocator.create(fti.Pointer.child); errdefer self.allocator.destroy(f); var offset = try self.lookupAndParseValue( input, offset_in, keys[1..(keys.len)], visited, fti.Pointer.child, f); @field(v, field.name) = f; return offset; } if (vtype == .None or newvtype == .Extendable) try visited.markVisited(key, newvtype); return self.lookupAndParseValue( input, offset_in, keys[1..(keys.len)], visited.getChild(key).?, field.field_type, &(@field(v, field.name))); } } return ParseError.FieldNotFound; } fn parseAssign(self: *Parser, input: []const u8, offset_in: usize, visited: *VisitedNode, comptime T: type, data: *T) !usize { var keys = try self.parseKey(input, offset_in); defer keys.deinit(); if (input[keys.offset] != '=') { return ParseError.FailedToParse; } return self.lookupAndParseValue(input, keys.offset+1, keys.keys.items, visited, T, data); } const parseBracketResult = struct{ data: *Table, offset: usize }; fn lookupAndParseKVs( self: *Parser, input: []const u8, offset_in: usize, keys: []Key, is_array: bool, visited: *VisitedNode, comptime T: type, data: *T) !usize { var key = Key.init(self.allocator); try key.appendSlice(keys[0].items); var vtype = visited.visitedType(key); if (keys.len == 1) { if (vtype == .CantExtend or vtype == .CantExtendKeyvalue) { key.deinit(); return ParseError.DuplicatedKey; } if (!is_array and vtype != .None) { key.deinit(); return ParseError.DuplicatedKey; } if (T == Value) { if (data.* != .Table) { return ParseError.IncorrectDataType; } var gpr = try data.Table.getOrPut(key); if (gpr.found_existing) { defer key.deinit(); if (gpr.kv.value != .Array) return ParseError.IncorrectDataType; if (!is_array) return ParseError.IncorrectDataType; var v = Value{.Table = Table.init(self.allocator)}; errdefer v.deinit(); var vchild = visited.getChild(key).?; var idx = gpr.kv.value.Array.items.len; try vchild.markVisitedIdx(idx, .Extendable); var offset = try self.parseKVs( input, offset_in, vchild.getChildIdx(idx).?, Value, &v); _ = try gpr.kv.value.Array.append(v); return offset; } try visited.markVisited(key, .Extendable); if (is_array) { var v = Value{.Table = Table.init(self.allocator)}; errdefer v.deinit(); var vchild = visited.getChild(key).?; try vchild.markVisitedIdx(0, .Extendable); var offset = try self.parseKVs( input, offset_in, vchild.getChildIdx(0).?, Value, &v); var a = std.ArrayList(Value).init(self.allocator); errdefer a.deinit(); _ = try a.append(v); gpr.kv.value = Value{.Array = a}; return offset; } gpr.kv.value = Value{.Table = Table.init(self.allocator)}; return self.parseKVs( input, offset_in, visited.getChild(key).?, Value, &gpr.kv.value); } defer key.deinit(); if (@typeInfo(T) != .Struct) return ParseError.IncorrectDataType; inline for (@typeInfo(T).Struct.fields) |field| { if (mem.eql(u8, key.items, field.name)) { switch (@typeInfo(field.field_type)) { .Pointer => |ptr| { if (ptr.size == .One) { if (is_array) return ParseError.IncorrectDataType; if (vtype == .None) try visited.markVisited(key, .Extendable); @field(data, field.name) = try self.createT(field.field_type); errdefer self.destroyT(field.field_type, @field(data, field.name)); return self.parseKVs( input, offset_in, visited.getChild(key).?, ptr.child, @field(data, field.name)); } if (!is_array) return ParseError.IncorrectDataType; var l = if (vtype == .None) 0 else @field(data, field.name).len; if (l == 0) { try visited.markVisited(key, .Extendable); @field(data, field.name) = try self.allocator.alloc(ptr.child, 1); } else { @field(data, field.name) = try self.allocator.realloc(@field(data, field.name), l+1); } @field(data, field.name)[l] = try self.createT(ptr.child); var vchild = visited.getChild(key).?; try vchild.markVisitedIdx(l, .Extendable); return self.parseKVs( input, offset_in, vchild.getChildIdx(l).?, ptr.child, &(@field(data, field.name)[l])); }, .Struct => |str| { if (vtype == .None) try visited.markVisited(key, .Extendable); return self.parseKVs( input, offset_in, visited.getChild(key).?, field.field_type, &(@field(data, field.name))); }, else => {}, } } } return ParseError.IncorrectDataType; } if (vtype == .CantExtend or vtype == .CantExtendKeyvalue) return ParseError.DuplicatedKey; if (T == Value) { if (data.* != .Table) { return ParseError.IncorrectDataType; } var gpr = try data.Table.getOrPut(key); if (gpr.found_existing) { defer key.deinit(); if (gpr.kv.value == .Array) { var idx = gpr.kv.value.Array.items.len-1; return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?.getChildIdx(idx).?, T, &gpr.kv.value.Array.items[idx]); } return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?, T, &gpr.kv.value); } try visited.markVisited(key, .Extendable); gpr.kv.value = Value{.Table = Table.init(self.allocator)}; return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?, T, &gpr.kv.value); } defer key.deinit(); if (@typeInfo(T) != .Struct) return ParseError.IncorrectDataType; inline for (@typeInfo(T).Struct.fields) |field| { if (mem.eql(u8, key.items, field.name)) { switch (@typeInfo(field.field_type)) { .Pointer => |ptr| { if (ptr.size == .One) { if (vtype == .Extendable) { return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?, ptr.child, @field(data, field.name)); } try visited.markVisited(key, .Extendable); @field(data, field.name) = try self.createT(field.field_type); errdefer self.destroyT(field.field_type, @field(data, field.name)); return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?, ptr.child, @field(data, field.name)); } if (vtype == .None) return ParseError.FailedToParse; var idx = @field(data, field.name).len - 1; return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?.getChildIdx(idx).?, ptr.child, &(@field(data, field.name)[idx])); }, .Struct => |str| { try visited.markVisited(key, .Extendable); return self.lookupAndParseKVs( input, offset_in, keys[1..(keys.len)], is_array, visited.getChild(key).?, field.field_type, &(@field(data, field.name))); }, else => {}, } } } return ParseError.IncorrectDataType; } fn parseBracket(self: *Parser, input: []const u8, offset_in: usize, visited: *VisitedNode, comptime T: type, data: *T) !usize { var offset = self.skipSpaces(input, offset_in); if (input[offset] != '[') { return ParseError.FailedToParse; } var count: usize = 1; if (input[offset+count] == '[') { count = 2; } var keys = try self.parseKey(input, offset+count); defer keys.deinit(); var i: usize = 0; while (i < count) : (i += 1) { if (input[keys.offset+i] != ']') return ParseError.FailedToParse; } offset = keys.offset+count; var has_linebreak = false; offset = self.skipSpacesAndCommentsWithLinebreak(input, offset, &has_linebreak); if (offset >= input.len) return offset; if (!has_linebreak) return ParseError.LinebreakExpected; return self.lookupAndParseKVs(input, offset, keys.keys.items, count > 1, visited, T, data); } fn createT(self: *Parser, comptime T: type) !T { if (T == Value) { return Value{.Table = Table.init(self.allocator)}; } else if (@typeInfo(T) == .Struct and @hasDecl(T, "init")) { comptime var ft = @typeInfo(@TypeOf(T.init)).Fn; if (ft.return_type == T and ft.args.len == 1 and ft.args[0].arg_type.? == *std.mem.Allocator) { return T.init(self.allocator); } } else { switch (@typeInfo(T)) { .Pointer => |ptr| return self.allocator.create(ptr.child), else => return undefined, } } return ParseError.UnknownReturnType; } fn destroyT(self: *Parser, comptime T: type, v: T) void { if (T == Value) { return v.deinit(); } else if (@typeInfo(T) == .Struct and @hasDecl(T, "deinit")) { switch (@typeInfo(@TypeOf(v.deinit))) { .BoundFn => |f| if (f.args.len == 0) { v.deinit(); }, else => {}, } } else { switch (@typeInfo(T)) { .Pointer => |ptr| self.allocator.destroy(v), else => {}, } } } fn parseKVs(self: *Parser, input: []const u8, offset_in: usize, visited: *VisitedNode, comptime T: type, value: *T) !usize { if (T == Value and value.* != .Table) { return ParseError.IncorrectDataType; } var offset: usize = offset_in; offset = self.skipSpacesAndComments(input, offset); while (offset < input.len) { if (input[offset] == '[') { return offset; } offset = try self.parseAssign(input, offset, visited, T, value); var has_linebreak = false; offset = self.skipSpacesAndCommentsWithLinebreak(input, offset, &has_linebreak); if (offset < input.len and !has_linebreak) return ParseError.LinebreakExpected; } return offset; } // parse parses the given input as a TOML data. pub fn parse(self: *Parser, comptime T: type, input: []const u8) !T { var visited = VisitedNode.init(self.allocator); defer visited.deinit(); var top = try self.createT(T); errdefer self.destroyT(T, top); var offset = try switch (@typeInfo(T)) { .Pointer => |ptr| self.parseKVs(input, 0, &visited, ptr.child, top), else => self.parseKVs(input, 0, &visited, T, &top), }; offset = self.skipSpacesAndComments(input, offset); while (offset < input.len) { offset = try switch(@typeInfo(T)) { .Pointer => |ptr| self.parseBracket(input, offset, &visited, ptr.child, top), else => self.parseBracket(input, offset, &visited, T, &top), }; offset = self.skipSpacesAndComments(input, offset); } return top; } }; // helper for tests. fn checkS(v: Value, key: []const u8, e: []const u8) bool { if (v.get(key)) |r| { if (r == .String) { return mem.eql(u8, r.String.items, e); } else { std.debug.warn("value {} is not a string\n", .{r}); } } else { std.debug.warn("key {} not found\n", .{key}); } return false; } test "empty" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, ""); expect(parsed.Table.size == 0); } test "simple-kv" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, " \t foo\t= 42 # comment1 \nbar= \t42."); defer parsed.deinit(); expect(parsed.Table.size == 2); expect(parsed.get("foo").?.Int == 42); expect(parsed.get("bar").?.Float == 42.0); } test "simple-struct" { const st = struct { foo: i64, bar: f64, }; var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(st, " \t foo\t= 42 # comment1 \nbar= \t42."); expect(parsed.foo == 42); expect(parsed.bar == 42.0); } test "string-kv" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, "#test\n \t foo\t= \"bar\" \n"); defer parsed.deinit(); expect(parsed.size() == 1); expect(checkS(parsed, "foo", "bar")); } test "string-struct" { const st = struct { foo: []u8, }; var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(st, "#test\n \t foo\t= \"bar\" \n"); defer allocator.free(parsed.foo); expect(mem.eql(u8, parsed.foo, "bar")); } test "bracket-kv" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, "[foo]\nbar=42\nbaz=true\n[quox]\nbar=96\n"); defer parsed.deinit(); expect(parsed.size() == 2); var o1 = parsed.get("foo").?; expect(o1.size() == 2); expect(o1.get("bar").?.Int == 42); expect(o1.get("baz").?.Bool); var o2 = parsed.get("quox").?; expect(o2.size() == 1); expect(o2.get("bar").?.Int == 96); } test "bracket-struct" { const foo = struct { bar: i64, baz: bool, }; const quox = struct { bar: i64, }; const st = struct { foo: *foo, quox: quox, }; var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(st, "[foo]\nbar=42\nbaz=true\n[quox]\nbar=96\n"); defer allocator.destroy(parsed.foo); expect(parsed.foo.bar == 42); expect(parsed.foo.baz); expect(parsed.quox.bar == 96); } test "double-bracket" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, "[[foo]]\nbar=42\nbaz=true\n[[foo]]\nbar=96\n"); defer parsed.deinit(); expect(parsed.size() == 1); var a = parsed.get("foo").?; expect(a.size() == 2); var o1 = a.idx(0).?; expect(o1.size() == 2); expect(o1.get("bar").?.Int == 42); expect(o1.get("baz").?.Bool); var o2 = a.idx(1).?; expect(o2.size() == 1); expect(o2.get("bar").?.Int == 96); } const subtable_text = \\[[fruit]] \\ name = "apple" \\ [fruit.physical] # subtable \\ color = "red" \\ shape = "round" \\ \\ [[fruit.variety]] \\ name = "red delicious" \\ [[fruit.variety]] \\ name = "granny smith" \\ \\[[fruit]] \\ name = "banana" \\ [[fruit.variety]] \\ name = "plantain" ; test "double-bracket-subtable" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, subtable_text); defer parsed.deinit(); expect(parsed.size() == 1); var fruits = parsed.get("fruit").?; expect(fruits.size() == 2); var apple = fruits.idx(0).?; expect(apple.size() == 3); expect(checkS(apple, "name", "apple")); var physical = apple.get("physical").?; expect(checkS(physical, "color", "red")); expect(checkS(physical, "shape", "round")); var varieties = apple.get("variety").?; expect(varieties.size() == 2); expect(checkS(varieties.idx(0).?, "name", "<NAME>")); expect(checkS(varieties.idx(1).?, "name", "<NAME>")); var banana = fruits.idx(1).?; expect(banana.size() == 2); expect(checkS(banana, "name", "banana")); varieties = banana.get("variety").?; expect(varieties.size() == 1); expect(checkS(varieties.idx(0).?, "name", "plantain")); } const fruit_physical = struct { const fruit_shape = enum { round, long, sphere, }; color: []u8, shape: fruit_shape, }; const fruit_variety = struct { name: []u8, }; const fruit = struct { name: []u8, physical: fruit_physical, variety: []fruit_variety, allocator: *mem.Allocator, fn init(allocator: *mem.Allocator) fruit { return .{ .name = "", .physical = .{.color = "", .shape = undefined}, .variety = &[0]fruit_variety{}, .allocator = allocator}; } fn deinit(self: fruit) void { self.allocator.free(self.name); self.allocator.free(self.physical.color); for (self.variety) |v| { self.allocator.free(v.name); } self.allocator.free(self.variety); } }; const tfruits = struct { fruit: []fruit, allocator: *mem.Allocator, fn init(allocator: *mem.Allocator) tfruits { return .{.fruit = &[0]fruit{}, .allocator = allocator}; } fn deinit(self: tfruits) void { for (self.fruit) |f| { f.deinit(); } self.allocator.free(self.fruit); } }; test "double-bracket-subtable-struct" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(tfruits, subtable_text); defer allocator.free(parsed.fruit); defer for (parsed.fruit) |f| { f.deinit(); }; expect(parsed.fruit.len == 2); var apple = parsed.fruit[0]; expect(mem.eql(u8, apple.name, "apple")); expect(mem.eql(u8, apple.physical.color, "red")); expect(apple.physical.shape == .round); expect(apple.variety.len == 2); expect(mem.eql(u8, apple.variety[0].name, "red delicious")); expect(mem.eql(u8, apple.variety[1].name, "granny smith")); var banana = parsed.fruit[1]; expect(mem.eql(u8, banana.name, "banana")); expect(banana.variety.len == 1); expect(mem.eql(u8, banana.variety[0].name, "plantain")); } const example_data = \\# This is a TOML document \\ \\title = "TOML Example" \\ \\[owner] \\name = "<NAME>" \\#datetime is not supported yet \\#dob = 1979-05-27T07:32:00-08:00 \\ \\[database] \\enabled = true \\ports = [ 8001, 8001, 8002 ] \\data = [ ["delta", "phi"], [3.14] ] \\temp_targets = { cpu = 79.5, case = 72.0 } \\ \\[servers] \\ \\[servers.alpha] \\ip = "10.0.0.1" \\role = "frontend" \\ \\[servers.beta] \\ip = "10.0.0.2" \\role = "backend" ; test "example" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, example_data); defer parsed.deinit(); expect(parsed.size() == 4); expect(checkS(parsed, "title", "TOML Example")); var owner = parsed.get("owner").?; expect(owner.size() == 1); expect(checkS(owner, "name", "<NAME>")); var database = parsed.get("database").?; expect(database.get("enabled").?.Bool); var ports = database.get("ports").?; expect(ports.size() == 3); expect(ports.idx(0).?.Int == 8001); expect(ports.idx(1).?.Int == 8001); expect(ports.idx(2).?.Int == 8002); var data = database.get("data").?; expect(data.size() == 2); expect(mem.eql(u8, data.idx(0).?.idx(0).?.String.items, "delta")); expect(mem.eql(u8, data.idx(0).?.idx(1).?.String.items, "phi")); expect(data.idx(1).?.idx(0).?.Float == 3.14); var temp_targets = database.get("temp_targets").?; expect(temp_targets.size() == 2); expect(temp_targets.get("cpu").?.Float == 79.5); expect(temp_targets.get("case").?.Float == 72.0); var servers = parsed.get("servers").?; expect(servers.size() == 2); var alpha = servers.get("alpha").?; expect(checkS(alpha, "ip", "10.0.0.1")); expect(checkS(alpha, "role", "frontend")); var beta = servers.get("beta").?; expect(checkS(beta, "ip", "10.0.0.2")); expect(checkS(beta, "role", "backend")); } test "parseBool" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var b = false; expect((try parser.parseBool("true", 0, &b)) == 4); expect(b); expect((try parser.parseBool("true ", 0, &b)) == 4); expect(b); expect(parser.parseBool("trues", 0, &b) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); expect((try parser.parseBool("false", 0, &b)) == 5); expect(!b); expect((try parser.parseBool("false ", 0, &b)) == 5); expect(!b); expect(parser.parseBool("falses", 0, &b) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); } test "parseInt" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var n: i64 = 0; expect((try parser.parseInt("123", 0, i64, &n)) == 3); expect(n == 123); expect((try parser.parseInt("-123", 0, i64, &n)) == 4); expect(n == -123); expect((try parser.parseInt("+123_456_789", 0, i64, &n)) == 12); expect(n == 123456789); expect((try parser.parseInt("0XFF", 0, i64, &n)) == 4); expect(n == 255); expect((try parser.parseInt("0Xa", 0, i64, &n)) == 3); expect(n == 10); expect((try parser.parseInt("0o20", 0, i64, &n)) == 4); expect(n == 16); expect((try parser.parseInt("0b0100", 0, i64, &n)) == 6); expect(n == 4); // hexadecimal with underscore. expect((try parser.parseInt("0xa_1", 0, i64, &n)) == 5); expect(n == 161); // invalid octal. expect(parser.parseInt("0o9", 0, i64, &n) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); // invalid binary. expect(parser.parseInt("0b2", 0, i64, &n) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); // invalid hexadecimal. expect(parser.parseInt("0xQ", 0, i64, &n) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); // invalid prefix. expect(parser.parseInt("0q0", 0, i64, &n) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); // signs can't be combined with prefix. expect(parser.parseInt("+0xdeadbeef", 0, i64, &n) catch |err| e: { expect(err == ParseError.FailedToParse); break :e 0; } == 0); } test "parseFloat" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); comptime var types = [2]type{f64, f32}; inline for (types) |t| { var f: t = 0.0; expect((try parser.parseFloat("1.5", 0, t, &f)) == 3); expect(f == 1.5); expect((try parser.parseFloat("-1e2", 0, t, &f)) == 4); expect(f == -1e2); expect((try parser.parseFloat(".2e-1", 0, t, &f)) == 5); expect(f == 0.2e-1); expect((try parser.parseFloat("1.e+2", 0, t, &f)) == 5); expect(f == 1e+2); expect((try parser.parseFloat("inf", 0, t, &f)) == 3); expect(f == std.math.inf(t)); expect((try parser.parseFloat("-inf", 0, t, &f)) == 4); expect(f == -std.math.inf(t)); expect((try parser.parseFloat("nan", 0, t, &f)) == 3); expect(std.math.isNan(f)); expect((try parser.parseFloat("+nan", 0, t, &f)) == 4); expect(std.math.isNan(f)); } } test "parseString" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var s = Key.init(allocator); defer s.deinit(); expect((try parser.parseString("\"foo\"", 0, &s)) == 5); expect(mem.eql(u8, s.items, "foo")); } test "parseString-escape" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var s = Key.init(allocator); defer s.deinit(); expect((try parser.parseString("\"\\b\\t\\n\\f\\r\\\"\\\\\"", 0, &s)) == 16); expect(mem.eql(u8, s.items, "\x08\t\n\x0c\r\"\\")); } test "parseString-escape-numerical" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var s = Key.init(allocator); defer s.deinit(); expect((try parser.parseString("\"a\\u3042b\\U0001F600\\uD83D\\uDE00\"", 0, &s)) == 32); expect(mem.eql(u8, s.items, "a\xe3\x81\x82b\xF0\x9F\x98\x80\xF0\x9F\x98\x80")); } test "parseString-multi" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var s = Key.init(allocator); defer s.deinit(); expect((try parser.parseString("\"\"\"aaa\nbbb\\\n \n ccc\"\"\"", 0, &s)) == 22); expect(mem.eql(u8, s.items, "aaa\nbbbccc")); } test "parseLiteralString" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var s = Key.init(allocator); defer s.deinit(); expect((try parser.parseLiteralString("'\\\\ServerX\\admin$\\system32\\'", 0, &s)) == 28); expect(mem.eql(u8, s.items, "\\\\ServerX\\admin$\\system32\\")); _ = try s.resize(0); expect((try parser.parseLiteralString("'''\nThe first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n'''", 0, &s)) == 93); expect(mem.eql(u8, s.items, "The first newline is\ntrimmed in raw strings.\n All other whitespace\n is preserved.\n")); _ = try s.resize(0); expect((try parser.parseLiteralString("''''That's still pointless', she said.'''", 0, &s)) == 41); expect(mem.eql(u8, s.items, "'That's still pointless', she said.")); _ = try s.resize(0); } test "parseKey" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var keys = try parser.parseKey("abc.123.a-z = 42", 0); defer keys.deinit(); expect(keys.offset == 12); expect(keys.keys.items.len == 3); expect(mem.eql(u8, keys.keys.items[0].items, "abc")); expect(mem.eql(u8, keys.keys.items[1].items, "123")); expect(mem.eql(u8, keys.keys.items[2].items, "a-z")); } test "parseKey-quoted" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var keys = try parser.parseKey("site.\"google.com\" = true", 0); defer keys.deinit(); expect(keys.offset == 18); expect(keys.keys.items.len == 2); expect(mem.eql(u8, keys.keys.items[0].items, "site")); expect(mem.eql(u8, keys.keys.items[1].items, "google.com")); } test "parseArray" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var a = std.ArrayList(Value).init(allocator); defer a.deinit(); var v = VisitedNode.init(allocator); defer v.deinit(); expect((try parser.parseArray("[ 42, 43.0,\n true, false ]", 0, &v, Value, &a)) == 26); expect(a.items.len == 4); expect(a.items[0].Int == 42); expect(a.items[1].Float == 43.0); expect(a.items[2].Bool); expect(!a.items[3].Bool); } test "parseInlineTable" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var t = Value{.Table = Table.init(allocator)}; defer t.deinit(); var v = VisitedNode.init(allocator); defer v.deinit(); expect((try parser.parseInlineTable("{ x = 1, y = 2 }", 0, &v, Value, &t)) == 16); expect(t.size() == 2); expect(t.get("x").?.Int == 1); expect(t.get("y").?.Int == 2); } // examples are from https://toml.io/en/v1.0.0-rc.1. test "examples1" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\# This is a full-line comment \\key = "value" # This is a comment at the end of a line \\another = "# This is not a comment" ); defer parsed.deinit(); expect(checkS(parsed, "key", "value")); expect(checkS(parsed, "another", "# This is not a comment")); } test "examples2" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\key = "value" \\bare_key = "value" \\bare-key = "value" \\1234 = "value" \\"127.0.0.1" = "value" \\"character encoding" = "value" \\"ʎǝʞ" = "value" \\'key2' = "value" \\'quoted "value"' = "value" ); defer parsed.deinit(); expect(checkS(parsed, "key", "value")); expect(checkS(parsed, "bare_key", "value")); expect(checkS(parsed, "bare-key", "value")); expect(checkS(parsed, "1234", "value")); expect(checkS(parsed, "127.0.0.1", "value")); expect(checkS(parsed, "character encoding", "value")); expect(checkS(parsed, "ʎǝʞ", "value")); expect(checkS(parsed, "key2", "value")); expect(checkS(parsed, "quoted \"value\"", "value")); } test "example3" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\"" = "blank" # VALID but discouraged ); defer parsed.deinit(); expect(checkS(parsed, "", "blank")); } test "example4" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\name = "Orange" \\physical.color = "orange" \\physical.shape = "round" \\site."google.com" = true ); defer parsed.deinit(); expect(checkS(parsed, "name", "Orange")); expect(checkS(parsed.get("physical").?, "color", "orange")); expect(checkS(parsed.get("physical").?, "shape", "round")); expect(parsed.get("site").?.get("google.com").?.Bool); } test "example5" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, "3.14159 = \"pi\""); defer parsed.deinit(); expect(checkS(parsed.get("3").?, "14159", "pi")); } test "example6" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\# This makes the key "fruit" into a table. \\fruit.apple.smooth = true \\ \\# So then you can add to the table "fruit" like so: \\fruit.orange = 2 ); defer parsed.deinit(); expect(parsed.get("fruit").?.get("apple").?.get("smooth").?.Bool); expect(parsed.get("fruit").?.get("orange").?.Int == 2); } fn deepEqual(v1: Value, v2: Value) bool { switch (v1) { .Int => |i| return (v2 == .Int) and i == v2.Int, .Float => |f1| return (v2 == .Float) and f1 == v2.Float, .Bool => |b1| return (v2 == .Bool) and b1 == v2.Bool, .String => |s1| return (v2 == .String) and mem.eql(u8, s1.items, v2.String.items), .Array => |a1| { if (v2 != .Array) return false; if (a1.items.len != v2.Array.items.len) return false; for (a1.items) |e, i| { if (!deepEqual(e, v2.Array.items[i])) return false; } return true; }, .Table => |t1| { if (v2 != .Table) return false; if (t1.size != v2.Table.size) return false; var iter = t1.iterator(); while (iter.next()) |kv| { if (v2.Table.get(kv.key)) |kv2| { if (!deepEqual(kv.value, kv2.value)) return false; } else { return false; } } return true; }, } } test "example7" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var p1 = try parser.parse(Value, \\apple.type = "fruit" \\orange.type = "fruit" \\ \\apple.skin = "thin" \\orange.skin = "thick" \\ \\apple.color = "red" \\orange.color = "orange" ); defer p1.deinit(); var p2 = try parser.parse(Value, \\apple.type = "fruit" \\apple.skin = "thin" \\apple.color = "red" \\ \\orange.type = "fruit" \\orange.skin = "thick" \\orange.color = "orange" ); defer p2.deinit(); expect(deepEqual(p1, p2)); } test "exapmle8" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\str = "I'm a string. \"You can quote me\". Name\tJos\u00E9\nLocation\tSF." \\str1 = """ \\Roses are red \\Violets are blue""" \\# On a Unix system, the above multi-line string will most likely be the same as: \\str2 = "Roses are red\nViolets are blue" \\ \\# On a Windows system, it will most likely be equivalent to: \\str3 = "Roses are red\r\nViolets are blue" \\str4 = "The quick brown fox jumps over the lazy dog." \\ \\str5 = """ \\The quick brown \ \\ \\ \\ fox jumps over \ \\ the lazy dog.""" \\ \\str6 = """\ \\ The quick brown \ \\ fox jumps over \ \\ the lazy dog.\ \\ """ \\str7 = """Here are two quotation marks: "". Simple enough.""" \\# str5 = """Here are three quotation marks: """.""" # INVALID \\str8 = """Here are three quotation marks: ""\".""" \\str9 = """Here are fifteen quotation marks: ""\"""\"""\"""\"""\".""" \\ \\# "This," she said, "is just a pointless statement." \\str10 = """"This," she said, "is just a pointless statement."""" \\winpath = 'C:\Users\nodejs\templates' \\winpath2 = '\\ServerX\admin$\system32\' \\quoted = 'Tom "Dubs" Preston-Werner' \\regex = '<\i\c*\s*>' \\regex2 = '''I [dw]on't need \d{2} apples''' \\lines = ''' \\The first newline is \\trimmed in raw strings. \\ All other whitespace \\ is preserved. \\''' \\quot15 = '''Here are fifteen quotation marks: """""""""""""""''' \\ \\# apos15 = '''Here are fifteen apostrophes: '''''''''''''''''' # INVALID \\apos15 = "Here are fifteen apostrophes: '''''''''''''''" \\ \\# 'That's still pointless', she said. \\str11 = ''''That's still pointless', she said.''' ); defer parsed.deinit(); expect(checkS(parsed, "str", "I'm a string. \"You can quote me\". Name\tJos\xC3\xA9\nLocation\tSF.")); expect(checkS(parsed, "str1", "Roses are red\nViolets are blue")); expect(checkS(parsed, "str2", "Roses are red\nViolets are blue")); expect(checkS(parsed, "str3", "Roses are red\r\nViolets are blue")); expect(checkS(parsed, "str4", "The quick brown fox jumps over the lazy dog.")); expect(checkS(parsed, "str5", "The quick brown fox jumps over the lazy dog.")); expect(checkS(parsed, "str6", "The quick brown fox jumps over the lazy dog.")); expect(checkS(parsed, "str7", "Here are two quotation marks: \"\". Simple enough.")); expect(checkS(parsed, "str8", "Here are three quotation marks: \"\"\".")); expect(checkS(parsed, "str9", "Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\".")); expect(checkS(parsed, "str10", "\"This,\" she said, \"is just a pointless statement.\"")); expect(checkS(parsed, "winpath", "C:\\Users\\nodejs\\templates")); expect(checkS(parsed, "winpath2", "\\\\ServerX\\admin$\\system32\\")); expect(checkS(parsed, "quoted", "Tom \"Dubs\" Preston-Werner")); expect(checkS(parsed, "regex", "<\\i\\c*\\s*>")); expect(checkS(parsed, "regex2", "I [dw]on't need \\d{2} apples")); expect(checkS(parsed, "lines", \\The first newline is \\trimmed in raw strings. \\ All other whitespace \\ is preserved. \\ )); expect(checkS(parsed, "quot15", "Here are fifteen quotation marks: \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"")); expect(checkS(parsed, "apos15", "Here are fifteen apostrophes: '''''''''''''''")); expect(checkS(parsed, "str11", "'That's still pointless', she said.")); } test "example9" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\int1 = +99 \\int2 = 42 \\int3 = 0 \\int4 = -17 \\int5 = 1_000 \\int6 = 5_349_221 \\int7 = 1_2_3_4_5 # VALID but discouraged \\# hexadecimal with prefix `0x` \\hex1 = 0xDEADBEEF \\hex2 = 0xdeadbeef \\hex3 = 0xdead_beef \\ \\# octal with prefix `0o` \\oct1 = 0o01234567 \\oct2 = 0o755 # useful for Unix file permissions \\ \\# binary with prefix `0b` \\bin1 = 0b11010110 ); defer parsed.deinit(); expect(parsed.get("int1").?.Int == 99); expect(parsed.get("int2").?.Int == 42); expect(parsed.get("int3").?.Int == 0); expect(parsed.get("int4").?.Int == -17); expect(parsed.get("int5").?.Int == 1000); expect(parsed.get("int6").?.Int == 5349221); expect(parsed.get("int7").?.Int == 12345); expect(parsed.get("hex1").?.Int == 0xdeadbeef); expect(parsed.get("hex2").?.Int == 0xdeadbeef); expect(parsed.get("hex3").?.Int == 0xdeadbeef); expect(parsed.get("oct1").?.Int == 0o01234567); expect(parsed.get("oct2").?.Int == 0o755); expect(parsed.get("bin1").?.Int == 0b11010110); } test "examples10" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\integers = [ 1, 2, 3 ] \\colors = [ "red", "yellow", "green" ] \\nested_array_of_int = [ [ 1, 2 ], [3, 4, 5] ] \\nested_mixed_array = [ [ 1, 2 ], ["a", "b", "c"] ] \\string_array = [ "all", 'strings', """are the same""", '''type''' ] \\ \\# Mixed-type arrays are allowed \\numbers = [ 0.1, 0.2, 0.5, 1, 2, 5 ] \\contributors = [ \\ "<NAME> <<EMAIL>>", \\ { name = "<NAME>", email = "<EMAIL>", url = "https://example.com/bazqux" } \\] \\integers2 = [ \\ 1, 2, 3 \\] \\ \\integers3 = [ \\ 1, \\ 2, # this is ok \\] ); defer parsed.deinit(); expect(parsed.get("integers").?.idx(0).?.Int == 1); expect(parsed.get("integers").?.Array.items[1].Int == 2); expect(parsed.get("integers").?.Array.items[2].Int == 3); expect(mem.eql(u8, parsed.get("colors").?.Array.items[0].String.items, "red")); expect(mem.eql(u8, parsed.get("colors").?.Array.items[1].String.items, "yellow")); expect(mem.eql(u8, parsed.get("colors").?.Array.items[2].String.items, "green")); expect(parsed.get("nested_array_of_int").?.Array.items[0].Array.items[0].Int == 1); expect(parsed.get("nested_array_of_int").?.Array.items[0].Array.items[1].Int == 2); expect(parsed.get("nested_array_of_int").?.Array.items[1].Array.items[0].Int == 3); expect(parsed.get("nested_array_of_int").?.Array.items[1].Array.items[1].Int == 4); expect(parsed.get("nested_array_of_int").?.Array.items[1].Array.items[2].Int == 5); expect(parsed.get("nested_mixed_array").?.Array.items[0].Array.items[0].Int == 1); expect(parsed.get("nested_mixed_array").?.Array.items[0].Array.items[1].Int == 2); expect(mem.eql(u8, parsed.get("nested_mixed_array").?.Array.items[1].Array.items[0].String.items, "a")); expect(mem.eql(u8, parsed.get("nested_mixed_array").?.Array.items[1].Array.items[1].String.items, "b")); expect(mem.eql(u8, parsed.get("nested_mixed_array").?.Array.items[1].Array.items[2].String.items, "c")); expect(mem.eql(u8, parsed.get("string_array").?.Array.items[0].String.items, "all")); expect(mem.eql(u8, parsed.get("string_array").?.Array.items[1].String.items, "strings")); expect(mem.eql(u8, parsed.get("string_array").?.Array.items[2].String.items, "are the same")); expect(mem.eql(u8, parsed.get("string_array").?.Array.items[3].String.items, "type")); expect(parsed.get("numbers").?.Array.items[0].Float == 0.1); expect(parsed.get("numbers").?.Array.items[1].Float == 0.2); expect(parsed.get("numbers").?.Array.items[2].Float == 0.5); expect(parsed.get("numbers").?.Array.items[3].Int == 1); expect(parsed.get("numbers").?.Array.items[4].Int == 2); expect(parsed.get("numbers").?.Array.items[5].Int == 5); expect(mem.eql(u8, parsed.get("contributors").?.Array.items[0].String.items, "<NAME> <<EMAIL>>")); expect(mem.eql(u8, parsed.get("contributors").?.Array.items[1].get("name").?.String.items, "<NAME>")); expect(mem.eql(u8, parsed.get("contributors").?.Array.items[1].get("email").?.String.items, "<EMAIL>")); expect(mem.eql(u8, parsed.get("contributors").?.Array.items[1].get("url").?.String.items, "https://example.com/bazqux")); expect(parsed.get("integers2").?.Array.items[0].Int == 1); expect(parsed.get("integers2").?.Array.items[1].Int == 2); expect(parsed.get("integers2").?.Array.items[2].Int == 3); expect(parsed.get("integers3").?.Array.items[0].Int == 1); expect(parsed.get("integers3").?.Array.items[1].Int == 2); expect(parsed.get("integers3").?.Array.items.len == 2); } test "example11" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\[table-1] \\key1 = "some string" \\key2 = 123 \\ \\[table-2] \\key1 = "another string" \\key2 = 456 \\[dog."tater.man"] \\type.name = "pug" \\[fruit] \\apple.color = "red" \\apple.taste.sweet = true \\ \\# [fruit.apple] # INVALID \\# [fruit.apple.taste] # INVALID \\ \\[fruit.apple.texture] # you can add sub-tables \\smooth = true ); defer parsed.deinit(); var tbl1 = parsed.get("table-1").?; expect(checkS(tbl1, "key1", "some string")); expect(tbl1.get("key2").?.Int == 123); var tbl2 = parsed.get("table-2").?; expect(checkS(tbl2, "key1", "another string")); expect(tbl2.get("key2").?.Int == 456); var taterman = parsed.get("dog").?.get("tater.man").?; expect(checkS(taterman.get("type").?, "name", "pug")); var apple = parsed.get("fruit").?.get("apple").?; expect(checkS(apple, "color", "red")); expect(apple.get("taste").?.get("sweet").?.Bool); } test "example12" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var parsed = try parser.parse(Value, \\name = { first = "Tom", last = "Preston-Werner" } \\point = { x = 1, y = 2 } \\animal = { type.name = "pug" } ); defer parsed.deinit(); expect(checkS(parsed.get("name").?, "first", "Tom")); expect(checkS(parsed.get("name").?, "last", "Preston-Werner")); expect(parsed.get("point").?.get("x").?.Int == 1); expect(parsed.get("point").?.get("y").?.Int == 2); expect(checkS(parsed.get("animal").?.get("type").?, "name", "pug")); } test "examples-invalid" { var tester = testing.LeakCountAllocator.init(std.heap.page_allocator); defer tester.validate() catch {}; var allocator = &tester.allocator; var parser = try Parser.init(allocator); defer allocator.destroy(parser); var invalids = [_][]const u8 { "key = # INVALID", "first = \"Tom\" last = \"Preston-Werner\" # INVALID", "= \"no key name\" # INVALID", \\# DO NOT DO THIS \\name = "Tom" \\name = "Pradyun" , \\# This defines the value of fruit.apple to be an integer. \\fruit.apple = 1 \\ \\# But then this treats fruit.apple like it's a table. \\# You can't turn an integer into a table. \\fruit.apple.smooth = true , \\[fruit] \\apple = "red" \\ \\[fruit] \\orange = "orange" , \\[fruit] \\apple = "red" \\ \\[fruit.apple] \\texture = "smooth" , \\[fruit] \\apple.color = "red" \\apple.taste.sweet = true \\[fruit.apple] # INVALID \\test = true , \\[fruit] \\apple.color = "red" \\apple.taste.sweet = true \\[fruit.apple.taste] # INVALID \\test = true , \\[product] \\type = { name = "Nail" } \\type.edible = false # INVALID , \\[product] \\type.name = "Nail" \\type = { edible = false } # INVALID , \\[fruit.physical] # subtable, but to which parent element should it belong? \\ color = "red" \\ shape = "round" \\ \\[[fruit]] \\ name = "apple" , \\fruit = [] \\ \\[[fruit]] # Not allowed \\foo = "bar" , \\[[fruit]] \\ name = "apple" \\ \\ [[fruit.variety]] \\ name = "red delicious" \\ \\ # INVALID: This table conflicts with the previous array of tables \\ [fruit.variety] \\ name = "granny smith" , \\[[fruit]] \\ name = "apple" \\ \\ [[fruit.variety]] \\ name = "red delicious" \\ \\ [fruit.physical] \\ color = "red" \\ shape = "round" \\ \\ # INVALID: This array of tables conflicts with the previous table \\ [[fruit.physical]] \\ color = "green" }; for (invalids) |invalid| { if (parser.parse(Value, invalid)) |parsed| { std.debug.warn("Unexpectedly success of parsing for {} as {}\n", .{invalid, parsed}); parsed.deinit(); expect(false); } else |err| {} } }
toml.zig
pub const Size = usize; pub const Float = f32; pub const Int = c_int; pub const UInt = c_uint; pub const Bool = c_int; pub const FileType = enum(c_int) { invalid, gltf, glb, }; pub const Result = enum(c_int) { success, data_too_short, unknown_format, invalid_json, invalid_gltf, invalid_options, file_not_found, io_error, out_of_memory, legacy_gltf, }; pub const MemoryOptions = extern struct { alloc: fn (user: ?*anyopaque, size: Size) callconv(.C) ?*anyopaque, free: fn (user: ?*anyopaque, ptr: ?*anyopaque) callconv(.C) void, user_data: ?*anyopaque, }; // TODO: Write proper function prototypes pub const FileOptions = extern struct { read: ?*anyopaque, release: ?*anyopaque, user_data: ?*anyopaque, }; pub const Options = extern struct { file_type: FileType, json_token_count: Size, memory: MemoryOptions, file: FileOptions, }; pub const BufferViewType = enum(c_int) { invalid, indices, vertices, }; pub const AttributeType = enum(c_int) { invalid, position, normal, tangent, texcoord, color, joints, weights, }; pub const ComponentType = enum(c_int) { invalid, r_8, r_8u, r_16, r_16u, r_32u, r_32f, }; pub const Type = enum(c_int) { invalid, scalar, vec2, vec3, vec4, mat2, mat3, mat4, }; pub const PrimitiveType = enum(c_int) { points, lines, line_loop, line_strip, triangles, triangle_strip, triangle_fan, }; pub const AlphaMode = enum(c_int) { @"opaque", mask, blend, }; pub const AnimationPathType = enum(c_int) { invalid, translation, rotation, scale, weights, }; pub const InterpolationType = enum(c_int) { linear, step, cubic_spline, }; pub const CameraType = enum(c_int) { invalid, perspective, orthographic, }; pub const LightType = enum(c_int) { invalid, directional, point, spot, }; pub const DataFreeMethod = enum(c_int) { none, file_release, memory_free, }; pub const MeshoptCompressionMode = enum(c_int) { invalid, attributes, triangles, indices, }; pub const MeshoptCompressionFilter = enum(c_int) { none, octahedral, quaternion, exponential, }; pub const Extras = extern struct { start_offset: Size, end_offset: Size, }; pub const Extension = extern struct { name: [*:0]u8, data: [*:0]u8, }; pub const Buffer = extern struct { name: ?[*:0]u8, size: Size, uri: ?[*:0]u8, data: ?*anyopaque, // loaded by loadBuffers() data_free_method: DataFreeMethod, extras: Extras, extensions_count: Size, extensions: ?[*]Extension, }; pub const MeshoptCompression = extern struct { buffer: *Buffer, offset: Size, size: Size, stride: Size, count: Size, mode: MeshoptCompressionMode, filter: MeshoptCompressionFilter, }; pub const BufferView = extern struct { name: ?[*:0]u8, buffer: *Buffer, offset: Size, size: Size, stride: Size, // 0 == automatically determined by accessor view_type: BufferViewType, data: ?*anyopaque, // overrides buffer.data if present, filled by extensions has_meshopt_compression: Bool, meshopt_compression: MeshoptCompression, extras: Extras, extensions_count: Size, extensions: ?[*]Extension, };
libs/zmesh/src/zcgltf.zig
const sdl = @import("./sdl.zig"); const core = @import("core"); const geometry = core.geometry; const Coord = geometry.Coord; const Rect = geometry.Rect; const makeCoord = geometry.makeCoord; const textures = @import("./textures.zig"); pub const LinearMenuState = struct { cursor_position: usize, entry_count: usize, enter_pressed: bool, pub fn init() LinearMenuState { return LinearMenuState{ .cursor_position = 0, .entry_count = 0, .enter_pressed = false, }; } pub fn moveUp(self: *LinearMenuState) void { if (self.cursor_position == 0) return; self.cursor_position -= 1; } pub fn moveDown(self: *LinearMenuState) void { self.cursor_position += 1; if (self.cursor_position >= self.entry_count) { self.cursor_position = if (self.entry_count == 0) 0 else self.entry_count - 1; } } pub fn ensureButtonCount(self: *LinearMenuState, button_count: usize) void { if (button_count > self.entry_count) { self.entry_count = button_count; } } pub fn enter(self: *LinearMenuState) void { self.enter_pressed = true; } pub fn beginFrame(self: *LinearMenuState) void { self.enter_pressed = false; } }; pub const Gui = struct { _renderer: *sdl.Renderer, _menu_state: *LinearMenuState, _cursor_icon: Rect, _button_count: usize, _cursor: Coord, _scale: i32, _bold: bool, _marginBottom: i32, pub fn init(renderer: *sdl.Renderer, menu_state: *LinearMenuState, cursor_icon: Rect) Gui { return Gui{ ._renderer = renderer, ._menu_state = menu_state, ._cursor_icon = cursor_icon, ._button_count = 0, ._cursor = geometry.makeCoord(0, 0), ._scale = 0, ._bold = false, ._marginBottom = 0, }; } pub fn seek(self: *Gui, x: i32, y: i32) void { self._cursor.x = x; self._cursor.y = y; } pub fn seekRelative(self: *Gui, dx: i32, dy: i32) void { self._cursor.x += dx; self._cursor.y += dy; } pub fn scale(self: *Gui, s: i32) void { self._scale = s; } pub fn bold(self: *Gui, b: bool) void { self._bold = b; } pub fn marginBottom(self: *Gui, m: i32) void { self._marginBottom = m; } pub fn text(self: *Gui, string: []const u8) void { self._cursor.y = textures.renderTextScaled(self._renderer, string, self._cursor, self._bold, self._scale).y; self._cursor.y += self._marginBottom * self._scale; } pub fn imageAndText(self: *Gui, sprite: Rect, string: []const u8) void { textures.renderSprite(self._renderer, sprite, self._cursor); const text_heigh = textures.getCharRect(' ', self._bold).height * self._scale; const text_position = Coord{ .x = self._cursor.x + sprite.width + 4, .y = self._cursor.y + if (sprite.height < text_heigh) 0 else @divTrunc(sprite.height, 2) - @divTrunc(text_heigh, 2), }; const starting_y = self._cursor.y; self._cursor.y = textures.renderTextScaled(self._renderer, string, text_position, self._bold, self._scale).y; if (self._cursor.y < starting_y + sprite.height) { self._cursor.y = starting_y + sprite.height; } self._cursor.y += self._marginBottom * self._scale; } pub fn button(self: *Gui, string: []const u8) bool { var start_position = self._cursor; self.text(string); const this_button_index = self._button_count; self._button_count += 1; self._menu_state.ensureButtonCount(self._button_count); if (self._menu_state.cursor_position == this_button_index) { // also render the cursor const icon_position = makeCoord(start_position.x - self._cursor_icon.width, start_position.y); textures.renderSprite(self._renderer, self._cursor_icon, icon_position); return self._menu_state.enter_pressed; } return false; } };
src/gui/gui.zig
const std = @import("std"); fn setup(step: *std.build.LibExeObjStep, mode: std.builtin.Mode, target: anytype, options: *std.build.OptionsStep) void { step.addCSourceFile("src/utils.c", &[_][]const u8{ "-Wall", "-Wextra", "-Werror", "-O3" }); step.setTarget(target); step.linkLibC(); step.setBuildMode(mode); step.addOptions("build_options", options); } pub fn build(b: *std.build.Builder) void { // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const step_128 = b.option( bool, "step-128", "process 128 bytes of input per StructuralIndexer step. defaults to 64 if this flag is not present. ", ) orelse false; const ondemand = b.option( bool, "ondemand", "use the ondemand parser for validation", ) orelse false; const ondemand_read_cap = b.option( u16, "ondemand-read-cap", "the capacity of the ondemand read buffer. defaults to 4096 (4 Kb)", ) orelse 4096; const options = b.addOptions(); options.addOption(bool, "step_128", step_128); options.addOption(bool, "ondemand", ondemand); options.addOption(u16, "ondemand_read_cap", ondemand_read_cap); const lib = b.addStaticLibrary("simdjzon", "src/simdjzon.zig"); setup(lib, mode, target, options); lib.install(); var main_tests = b.addTest("src/tests.zig"); setup(main_tests, mode, target, options); // main_tests.setFilter("ondemand array iteration"); const test_step = b.step("test", "Run tests"); test_step.dependOn(&main_tests.step); const exe = b.addExecutable("simdjzon", "src/main.zig"); setup(exe, mode, target, options); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| run_cmd.addArgs(args); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
build.zig
const std = @import("../std.zig"); const build = @import("../build.zig"); const Step = build.Step; const Builder = build.Builder; const fs = std.fs; const warn = std.debug.warn; const ArrayList = std.ArrayList; const WriteFileStep = @This(); pub const base_id = .write_file; step: Step, builder: *Builder, output_dir: []const u8, files: std.TailQueue(File), pub const File = struct { source: build.GeneratedFile, basename: []const u8, bytes: []const u8, }; pub fn init(builder: *Builder) WriteFileStep { return WriteFileStep{ .builder = builder, .step = Step.init(.write_file, "writefile", builder.allocator, make), .files = .{}, .output_dir = undefined, }; } pub fn add(self: *WriteFileStep, basename: []const u8, bytes: []const u8) void { const node = self.builder.allocator.create(std.TailQueue(File).Node) catch unreachable; node.* = .{ .data = .{ .source = build.GeneratedFile{ .step = &self.step }, .basename = self.builder.dupePath(basename), .bytes = self.builder.dupe(bytes), }, }; self.files.append(node); } /// Gets a file source for the given basename. If the file does not exist, returns `null`. pub fn getFileSource(step: *WriteFileStep, basename: []const u8) ?build.FileSource { var it = step.files.first; while (it) |node| : (it = node.next) { if (std.mem.eql(u8, node.data.basename, basename)) return build.FileSource{ .generated = &node.data.source }; } return null; } fn make(step: *Step) !void { const self = @fieldParentPtr(WriteFileStep, "step", step); // The cache is used here not really as a way to speed things up - because writing // the data to a file would probably be very fast - but as a way to find a canonical // location to put build artifacts. // If, for example, a hard-coded path was used as the location to put WriteFileStep // files, then two WriteFileSteps executing in parallel might clobber each other. // TODO port the cache system from stage1 to zig std lib. Until then we use blake2b // directly and construct the path, and no "cache hit" detection happens; the files // are always written. var hash = std.crypto.hash.blake2.Blake2b384.init(.{}); // Random bytes to make WriteFileStep unique. Refresh this with // new random bytes when WriteFileStep implementation is modified // in a non-backwards-compatible way. hash.update("eagVR1dYXoE7ARDP"); { var it = self.files.first; while (it) |node| : (it = node.next) { hash.update(node.data.basename); hash.update(node.data.bytes); hash.update("|"); } } var digest: [48]u8 = undefined; hash.final(&digest); var hash_basename: [64]u8 = undefined; _ = fs.base64_encoder.encode(&hash_basename, &digest); self.output_dir = try fs.path.join(self.builder.allocator, &[_][]const u8{ self.builder.cache_root, "o", &hash_basename, }); // TODO replace with something like fs.makePathAndOpenDir fs.cwd().makePath(self.output_dir) catch |err| { warn("unable to make path {s}: {s}\n", .{ self.output_dir, @errorName(err) }); return err; }; var dir = try fs.cwd().openDir(self.output_dir, .{}); defer dir.close(); { var it = self.files.first; while (it) |node| : (it = node.next) { dir.writeFile(node.data.basename, node.data.bytes) catch |err| { warn("unable to write {s} into {s}: {s}\n", .{ node.data.basename, self.output_dir, @errorName(err), }); return err; }; node.data.source.path = fs.path.join( self.builder.allocator, &[_][]const u8{ self.output_dir, node.data.basename }, ) catch unreachable; } } }
lib/std/build/WriteFileStep.zig
const kernel = @import("kernel.zig"); const Physical = kernel.Physical; const Virtual = kernel.Virtual; const log = kernel.log.scoped(.PhysicalMemory); const TODO = kernel.TODO; pub var map: Map = undefined; /// This contains physical memory regions pub const Map = struct { usable: []Entry, reclaimable: []Entry, framebuffer: []Region, kernel_and_modules: []Region, reserved: []Region, pub const RegionType = enum(u3) { usable = 0, reclaimable = 1, framebuffer = 2, kernel_and_modules = 3, reserved = 4, }; pub fn find_address(mmap: *Map, physical_address: Physical.Address) ?RegionType { for (mmap.usable) |region| { if (physical_address.belongs_to_region(region.descriptor)) { return .usable; } } for (mmap.reclaimable) |region| { if (physical_address.belongs_to_region(region.descriptor)) { return .reclaimable; } } for (mmap.framebuffer) |region| { if (physical_address.belongs_to_region(region)) { return .framebuffer; } } for (mmap.kernel_and_modules) |region| { if (physical_address.belongs_to_region(region)) { return .kernel_and_modules; } } for (mmap.reserved) |region| { if (physical_address.belongs_to_region(region)) { return .reserved; } } return null; } pub const Entry = struct { descriptor: Region, allocated_size: u64, type: Type, pub const BitsetBaseType = u64; pub const Type = enum(u64) { usable = 0, reclaimable = 1, framebuffer = 2, kernel_and_modules = 3, reserved = 4, }; pub fn get_bitset(entry: *Entry) []BitsetBaseType { return get_bitset_from_address_and_size(entry.descriptor.address, entry.descriptor.size); } pub fn get_bitset_from_address_and_size(address: Physical.Address, size: u64) []BitsetBaseType { const page_count = kernel.bytes_to_pages(size, true); const bitset_len = kernel.remainder_division_maybe_exact(page_count, @bitSizeOf(BitsetBaseType), false); return if (kernel.Virtual.initialized) address.access_higher_half([*]BitsetBaseType)[0..bitset_len] else address.access_identity([*]BitsetBaseType)[0..bitset_len]; } pub fn setup_bitset(entry: *Entry) void { log.debug("Setting up bitset", .{}); const page_count = kernel.bytes_to_pages(entry.allocated_size, true); log.debug("Set up bitset", .{}); const bitsize = @bitSizeOf(Map.Entry.BitsetBaseType); const quotient = page_count / bitsize; const remainder_bitsize_max: u64 = bitsize - 1; const popcount = @popCount(@TypeOf(remainder_bitsize_max), remainder_bitsize_max); const remainder = @intCast(kernel.IntType(.unsigned, popcount), page_count % bitsize); const bitset = entry.get_bitset(); for (bitset[0..quotient]) |*bitset_elem| { bitset_elem.* = kernel.maxInt(Map.Entry.BitsetBaseType); } var remainder_i: @TypeOf(remainder) = 0; while (remainder_i < remainder) : (remainder_i += 1) { bitset[quotient] |= @as(u64, 1) << remainder_i; } } fn debug(entry: *Entry) void { log.debug("(0x{x},\t{})", .{ entry.descriptor.address, entry.descriptor.size }); } }; pub fn debug(memory_map: *Map) void { log.debug("Usable", .{}); for (memory_map.usable) |region| { log.debug("(0x{x},\t0x{x},\t{})", .{ region.address, region.address + region.size, region.size }); } log.debug("Reclaimable", .{}); for (memory_map.reclaimable) |region| { log.debug("(0x{x},\t0x{x},\t{})", .{ region.address, region.address + region.size, region.size }); } log.debug("Framebuffer", .{}); for (memory_map.framebuffer) |region| { log.debug("(0x{x},\t0x{x},\t{})", .{ region.address, region.address + region.size, region.size }); } log.debug("Kernel and modules", .{}); for (memory_map.kernel_and_modules) |region| { log.debug("(0x{x},\t0x{x},\t{})", .{ region.address, region.address + region.size, region.size }); } log.debug("Reserved", .{}); for (memory_map.reserved) |region| { log.debug("(0x{x},\t0x{x},\t{})", .{ region.address, region.address + region.size, region.size }); } } }; pub fn allocate_pages(page_count: u64) ?Physical.Address { const take_hint = true; const size = page_count * kernel.arch.page_size; // TODO: don't allocate if they are different regions (this can cause issues?) for (map.usable) |*region| { if (region.descriptor.size - region.allocated_size >= size) { const region_page_count = region.descriptor.size / kernel.arch.page_size; const supposed_bitset_size = region_page_count / @bitSizeOf(Map.Entry.BitsetBaseType); const bitset = region.get_bitset(); kernel.assert(@src(), bitset.len >= supposed_bitset_size); var region_allocated_page_count: u64 = 0; const allocated_page_count = region.allocated_size / kernel.arch.page_size; const start_index = if (take_hint) allocated_page_count / @bitSizeOf(u64) else 0; var first_address: u64 = 0; bitset_loop: for (bitset[start_index..]) |*bitset_elem| { comptime var bit: u64 = 0; inline while (bit < @bitSizeOf(u64)) : (bit += 1) { const bit_set = bitset_elem.* & (1 << bit) != 0; if (region_allocated_page_count == page_count) { break :bitset_loop; } else { if (!bit_set) { if (first_address == 0) { const offset = (bit + (start_index * @bitSizeOf(u64))) * kernel.arch.page_size; first_address = region.descriptor.address.value + offset; } bitset_elem.* = bitset_elem.* | (1 << bit); region_allocated_page_count += 1; } } } } if (region_allocated_page_count == page_count) { const result = first_address; region.allocated_size += region_allocated_page_count * kernel.arch.page_size; kernel.assert(@src(), result != 0); return Physical.Address.new(result); } kernel.assert(@src(), region.allocated_size + size > region.descriptor.size); kernel.assert(@src(), first_address != 0); const original_allocated_size = region.allocated_size - (region_allocated_page_count * kernel.arch.page_size); const original_allocated_page_count = original_allocated_size / kernel.arch.page_size; var byte = original_allocated_page_count / @bitSizeOf(u64); var bit = original_allocated_page_count % @bitSizeOf(u64); kernel.assert(@src(), region_allocated_page_count > 0); if (bit > 0) { while (bit < @bitSizeOf(u64)) : (bit += 1) { bitset[byte] &= (~(@as(u64, 1) << @intCast(u6, bit))); region_allocated_page_count -= 1; } } if (region_allocated_page_count >= 64) { TODO(@src()); } if (region_allocated_page_count > 0) { TODO(@src()); } region.allocated_size = original_allocated_size; } } @panic("allocation failed, no memory"); } pub const Region = struct { address: Physical.Address, size: u64, pub fn new(address: Physical.Address, size: u64) Region { return Region{ .address = address, .size = size, }; } pub fn map(region: Region, address_space: *Virtual.AddressSpace, base_virtual_address: Virtual.Address, flags: kernel.Virtual.AddressSpace.Flags) void { return region.map_extended(address_space, base_virtual_address, true, flags); } pub fn map_extended(region: Region, address_space: *Virtual.AddressSpace, base_virtual_address: Virtual.Address, comptime is_page_aligned: bool, flags: kernel.Virtual.AddressSpace.Flags) void { var physical_address = region.address; var virtual_address = base_virtual_address; var region_size = region.size; if (!is_page_aligned) { physical_address.page_align_backward(); virtual_address.page_align_backward(); region_size = kernel.align_forward(region_size, kernel.arch.page_size); } log.debug("Mapping (0x{x}, 0x{x}) to (0x{x}, 0x{x})", .{ physical_address.value, physical_address.value + region_size, virtual_address.value, virtual_address.value + region_size }); var size_it: u64 = 0; while (size_it < region_size) : (size_it += kernel.arch.page_size) { address_space.arch.map(physical_address, virtual_address, flags); physical_address.page_up(); virtual_address.page_up(); } } };
src/kernel/physical_memory.zig
const std = @import("std"); const testing = std.testing; pub fn Entry(comptime T: type) type { return struct { const Self = @This(); storage: *const std.ArrayList(T), idx: usize, // index into .storage.items pub fn get(self: *Self) *T { return &self.storage.items[self.idx]; } pub fn getConst(self: *Self) *const T { return &self.storage.items[self.idx]; } }; } /// A wrapper for std.ArrayList (append-only) to provide a way of accessing a relocatable /// area of heap-memory. Returns a struct with local idx + pointer to the std.ArrayList when adding entries. pub fn IndexedArrayList(comptime T: type) type { return struct { const Self = @This(); storage: std.ArrayList(T), pub fn init(allocator: std.mem.Allocator) Self { return .{ .storage = std.ArrayList(T).init(allocator) }; } pub fn deinit(self: *Self) void { self.storage.deinit(); } pub fn addOne(self: *Self) error{OutOfMemory}!Entry(T) { _ = try self.storage.addOne(); var idx = self.storage.items.len - 1; return Entry(T){ .storage = &self.storage, .idx = idx }; } }; } test "can add and get entries" { var mylist = IndexedArrayList(u64).init(std.testing.allocator); defer mylist.deinit(); // Add first entry var el = try mylist.addOne(); try testing.expect(el.idx == 0); try testing.expect(el.storage == &mylist.storage); el.get().* = 123; try testing.expect(el.get().* == 123); // Add second entry var el2 = try mylist.addOne(); try testing.expect(el2.idx == 1); try testing.expect(el2.storage == &mylist.storage); el2.get().* = 321; try testing.expect(el.get().* == 123); try testing.expect(el2.get().* == 321); } // TODO: Performance tests, cache-friendliness test "performance comparisons" { if (true) return error.SkipZigTest; const Data = struct { string: [256]u8, string2: [128]u8, string3: [128]u8, val: usize, }; const iterations = 100; const reps_pr_iteration = 100000; // Testing the IndexedArrayList { var start = std.time.milliTimestamp(); var iteration_counter: usize = 0; while (iteration_counter < iterations) : (iteration_counter += 1) { var mylist = IndexedArrayList(Data).init(std.testing.allocator); defer mylist.deinit(); var i: usize = 0; var sum: usize = 0; while (i < reps_pr_iteration) : (i += 1) { var el = try mylist.addOne(); el.get().*.val = i; sum += el.get().*.val; } } std.debug.print("time IndexedArrayList: {d}ms\n", .{@divTrunc(std.time.milliTimestamp() - start, iterations)}); } // Testing the std.ArrayList for comparison { var start = std.time.milliTimestamp(); var iteration_counter: usize = 0; while (iteration_counter < iterations) : (iteration_counter += 1) { var mylist = std.ArrayList(Data).init(std.testing.allocator); defer mylist.deinit(); var i: usize = 0; var sum: usize = 0; while (i < reps_pr_iteration) : (i += 1) { var el = try mylist.addOne(); el.*.val = i; sum += el.*.val; } } std.debug.print("time std.ArrayList: {d}ms\n", .{@divTrunc(std.time.milliTimestamp() - start, iterations)}); } } // TODO: Create minimal example of const-issue to verify if it's a feature/bug and how it better could be solved
libdaya/src/indexedarraylist.zig
const c = @import("../c.zig"); const vk = @import("../vk.zig"); const std = @import("std"); const shader_util = @import("../shaders/shader_util.zig"); usingnamespace @cImport({ @cInclude("fira_sans_regular.h"); }); const vkctxt = @import("../vulkan_wrapper/vulkan_context.zig"); const Buffer = vkctxt.Buffer; const UI = @import("ui.zig").UI; const printError = @import("../application/print_error.zig").printError; const rg = @import("../renderer/render_graph/render_graph.zig"); const RenderGraph = rg.RenderGraph; const Texture = @import("../renderer/render_graph/resources/texture.zig").Texture; const PushConstBlock = packed struct { scale_translate: [4]f32, }; pub const UIVulkanContext = struct { parent: *UI, font_texture: Texture, descriptor_pool: vk.DescriptorPool, descriptor_set_layout: vk.DescriptorSetLayout, descriptor_set: vk.DescriptorSet, pipeline_cache: vk.PipelineCache, frag_shader: vk.ShaderModule, vert_shader: vk.ShaderModule, vertex_buffers: []Buffer, index_buffers: []Buffer, vertex_buffer_counts: []usize, index_buffer_counts: []usize, render_pass: vk.RenderPass, pipeline_layout: vk.PipelineLayout, pipeline: vk.Pipeline, pub fn init(self: *UIVulkanContext, parent: *UI) void { self.parent = parent; shader_util.initShaderCompilation(); self.initResources(); } pub fn deinit(self: *UIVulkanContext) void { vkctxt.vkd.deviceWaitIdle(vkctxt.vkc.device) catch return; for (self.vertex_buffers) |*buffer| if (buffer.buffer != .null_handle) buffer.destroy(); vkctxt.vkc.allocator.free(self.vertex_buffers); for (self.index_buffers) |*buffer| if (buffer.buffer != .null_handle) buffer.destroy(); vkctxt.vkc.allocator.free(self.index_buffers); vkctxt.vkc.allocator.free(self.vertex_buffer_counts); vkctxt.vkc.allocator.free(self.index_buffer_counts); vkctxt.vkd.destroyPipeline(vkctxt.vkc.device, self.pipeline, null); vkctxt.vkd.destroyPipelineLayout(vkctxt.vkc.device, self.pipeline_layout, null); vkctxt.vkd.destroyRenderPass(vkctxt.vkc.device, self.render_pass, null); vkctxt.vkd.destroyShaderModule(vkctxt.vkc.device, self.vert_shader, null); vkctxt.vkd.destroyShaderModule(vkctxt.vkc.device, self.frag_shader, null); vkctxt.vkd.destroyPipelineCache(vkctxt.vkc.device, self.pipeline_cache, null); vkctxt.vkd.destroyDescriptorSetLayout(vkctxt.vkc.device, self.descriptor_set_layout, null); vkctxt.vkd.destroyDescriptorPool(vkctxt.vkc.device, self.descriptor_pool, null); self.font_texture.destroy(); } pub fn render(self: *UIVulkanContext, command_buffer: vk.CommandBuffer, frame_index: u32) void { self.updateBuffers(frame_index); const io: *c.ImGuiIO = c.igGetIO(); const clear_color: vk.ClearValue = .{ .color = .{ .float_32 = [_]f32{ 0.6, 0.3, 0.6, 1.0 } } }; const render_pass_info: vk.RenderPassBeginInfo = .{ .render_pass = self.render_pass, .framebuffer = rg.global_render_graph.final_swapchain.framebuffers[rg.global_render_graph.image_index], .render_area = .{ .offset = .{ .x = 0, .y = 0 }, .extent = rg.global_render_graph.final_swapchain.image_extent, }, .clear_value_count = 1, .p_clear_values = @ptrCast([*]const vk.ClearValue, &clear_color), }; vkctxt.vkd.cmdBeginRenderPass(command_buffer, render_pass_info, .@"inline"); defer vkctxt.vkd.cmdEndRenderPass(command_buffer); vkctxt.vkd.cmdBindDescriptorSets(command_buffer, .graphics, self.pipeline_layout, 0, 1, @ptrCast([*]const vk.DescriptorSet, &self.descriptor_set), 0, undefined); vkctxt.vkd.cmdBindPipeline(command_buffer, .graphics, self.pipeline); const viewport: vk.Viewport = .{ .width = io.DisplaySize.x, .height = io.DisplaySize.y, .min_depth = 0.0, .max_depth = 1.0, .x = 0, .y = 0, }; vkctxt.vkd.cmdSetViewport(command_buffer, 0, 1, @ptrCast([*]const vk.Viewport, &viewport)); const push_const_block: PushConstBlock = .{ .scale_translate = [4]f32{ 2.0 / viewport.width, 2.0 / viewport.height, -1.0, -1.0 }, }; vkctxt.vkd.cmdPushConstants(command_buffer, self.pipeline_layout, .{ .vertex_bit = true }, 0, @sizeOf(PushConstBlock), @ptrCast([*]const PushConstBlock, &push_const_block)); // Render commands const draw_data: *c.ImDrawData = c.igGetDrawData() orelse return; var vertex_offset: i32 = 0; var index_offset: u32 = 0; if (draw_data.CmdListsCount == 0) return; const offset: u64 = 0; vkctxt.vkd.cmdBindVertexBuffers(command_buffer, 0, 1, @ptrCast([*]const vk.Buffer, &self.vertex_buffers[frame_index].buffer), @ptrCast([*]const u64, &offset)); vkctxt.vkd.cmdBindIndexBuffer(command_buffer, self.index_buffers[frame_index].buffer, 0, .uint16); const clip_off: c.ImVec2 = draw_data.DisplayPos; const clip_scale: c.ImVec2 = draw_data.FramebufferScale; var i: usize = 0; while (i < draw_data.CmdListsCount) : (i += 1) { const cmd_list: *c.ImDrawList = draw_data.CmdLists[i]; var j: usize = 0; while (j < cmd_list.CmdBuffer.Size) : (j += 1) { const pcmd: c.ImDrawCmd = cmd_list.CmdBuffer.Data[j]; const clip_rect: c.ImVec4 = .{ .x = std.math.max(0.0, (pcmd.ClipRect.x - clip_off.x) * clip_scale.x), .y = std.math.max(0.0, (pcmd.ClipRect.y - clip_off.y) * clip_scale.y), .z = (pcmd.ClipRect.z - clip_off.x) * clip_scale.x, .w = (pcmd.ClipRect.w - clip_off.y) * clip_scale.y, }; const scissor_rect: vk.Rect2D = .{ .offset = .{ .x = @floatToInt(i32, clip_rect.x), .y = @floatToInt(i32, clip_rect.y), }, .extent = .{ .width = @floatToInt(u32, pcmd.ClipRect.z - pcmd.ClipRect.x), .height = @floatToInt(u32, pcmd.ClipRect.w - pcmd.ClipRect.y), }, }; vkctxt.vkd.cmdSetScissor(command_buffer, 0, 1, @ptrCast([*]const vk.Rect2D, &scissor_rect)); // Bind descriptor that user specified with igImage if (pcmd.TextureId != null) { const alignment: u26 = @alignOf([*]const vk.DescriptorSet); const descriptor_set: [*]const vk.DescriptorSet = @ptrCast([*]const vk.DescriptorSet, @alignCast(alignment, pcmd.TextureId.?)); vkctxt.vkd.cmdBindDescriptorSets(command_buffer, .graphics, self.pipeline_layout, 0, 1, descriptor_set, 0, undefined); } vkctxt.vkd.cmdDrawIndexed(command_buffer, pcmd.ElemCount, 1, index_offset, vertex_offset, 0); index_offset += pcmd.ElemCount; // Return font descriptor if (pcmd.TextureId != null) vkctxt.vkd.cmdBindDescriptorSets(command_buffer, .graphics, self.pipeline_layout, 0, 1, @ptrCast([*]const vk.DescriptorSet, &self.descriptor_set), 0, undefined); } vertex_offset += cmd_list.VtxBuffer.Size; } } fn updateBuffers(self: *UIVulkanContext, frame_index: u32) void { const draw_data: *c.ImDrawData = c.igGetDrawData() orelse return; const vertex_buffer_size: vk.DeviceSize = @intCast(u64, draw_data.TotalVtxCount) * @sizeOf(c.ImDrawVert); const index_buffer_size: vk.DeviceSize = @intCast(u64, draw_data.TotalIdxCount) * @sizeOf(c.ImDrawIdx); if (vertex_buffer_size == 0 or index_buffer_size == 0) return; // Update only if vertex or index count has changed if (self.vertex_buffers[frame_index].buffer == .null_handle or self.vertex_buffer_counts[frame_index] < draw_data.TotalVtxCount) { if (self.vertex_buffers[frame_index].buffer != .null_handle) { vkctxt.vkd.queueWaitIdle(vkctxt.vkc.present_queue) catch |err| { vkctxt.printVulkanError("Can't wait present queue", err, vkctxt.vkc.allocator); }; self.vertex_buffers[frame_index].destroy(); } self.vertex_buffers[frame_index].init(vertex_buffer_size, .{ .vertex_buffer_bit = true }, .{ .host_visible_bit = true }); self.vertex_buffer_counts[frame_index] = @intCast(usize, draw_data.TotalVtxCount); } if (self.index_buffers[frame_index].buffer == .null_handle or self.index_buffer_counts[frame_index] < draw_data.TotalIdxCount) { if (self.index_buffers[frame_index].buffer != .null_handle) { vkctxt.vkd.queueWaitIdle(vkctxt.vkc.present_queue) catch |err| { vkctxt.printVulkanError("Can't wait present queue", err, vkctxt.vkc.allocator); }; self.index_buffers[frame_index].destroy(); } self.index_buffers[frame_index].init(index_buffer_size, .{ .index_buffer_bit = true }, .{ .host_visible_bit = true }); self.index_buffer_counts[frame_index] = @intCast(usize, draw_data.TotalIdxCount); } var vtx_dst: [*]c.ImDrawVert = @ptrCast([*]c.ImDrawVert, @alignCast(@alignOf(c.ImDrawVert), self.vertex_buffers[frame_index].mapped_memory)); var idx_dst: [*]c.ImDrawIdx = @ptrCast([*]c.ImDrawIdx, @alignCast(@alignOf(c.ImDrawIdx), self.index_buffers[frame_index].mapped_memory)); var n: usize = 0; while (n < draw_data.CmdListsCount) : (n += 1) { const cmd_list: *c.ImDrawList = draw_data.CmdLists[n]; @memcpy( @ptrCast([*]align(4) u8, @alignCast(4, vtx_dst)), @ptrCast([*]align(4) const u8, @alignCast(4, cmd_list.VtxBuffer.Data)), @intCast(usize, cmd_list.VtxBuffer.Size) * @sizeOf(c.ImDrawVert), ); @memcpy( @ptrCast([*]align(2) u8, @alignCast(2, idx_dst)), @ptrCast([*]align(2) const u8, @alignCast(2, cmd_list.IdxBuffer.Data)), @intCast(usize, cmd_list.IdxBuffer.Size) * @sizeOf(c.ImDrawIdx), ); vtx_dst += @intCast(usize, cmd_list.VtxBuffer.Size); idx_dst += @intCast(usize, cmd_list.IdxBuffer.Size); } self.vertex_buffers[frame_index].flush(); self.index_buffers[frame_index].flush(); } fn createRenderPass(self: *UIVulkanContext) void { const color_attachment: vk.AttachmentDescription = .{ .format = rg.global_render_graph.final_swapchain.image_format, .samples = .{ .@"1_bit" = true }, .load_op = self.parent.render_pass.load_op, .store_op = .store, .stencil_load_op = .dont_care, .stencil_store_op = .dont_care, .initial_layout = self.parent.render_pass.initial_layout, .final_layout = self.parent.render_pass.final_layout, .flags = .{}, }; const color_attachment_ref: vk.AttachmentReference = .{ .attachment = 0, .layout = .color_attachment_optimal, }; const subpass: vk.SubpassDescription = .{ .pipeline_bind_point = .graphics, .color_attachment_count = 1, .p_color_attachments = @ptrCast([*]const vk.AttachmentReference, &color_attachment_ref), .flags = .{}, .input_attachment_count = 0, .p_input_attachments = undefined, .p_resolve_attachments = undefined, .p_depth_stencil_attachment = undefined, .preserve_attachment_count = 0, .p_preserve_attachments = undefined, }; const dependency: vk.SubpassDependency = .{ .src_subpass = vk.SUBPASS_EXTERNAL, .dst_subpass = 0, .src_stage_mask = .{ .color_attachment_output_bit = true }, .src_access_mask = .{}, .dst_stage_mask = .{ .color_attachment_output_bit = true }, .dst_access_mask = .{ .color_attachment_read_bit = true, .color_attachment_write_bit = true }, .dependency_flags = .{}, }; const render_pass_create_info: vk.RenderPassCreateInfo = .{ .attachment_count = 1, .p_attachments = @ptrCast([*]const vk.AttachmentDescription, &color_attachment), .subpass_count = 1, .p_subpasses = @ptrCast([*]const vk.SubpassDescription, &subpass), .dependency_count = 1, .p_dependencies = @ptrCast([*]const vk.SubpassDependency, &dependency), .flags = .{}, }; self.render_pass = vkctxt.vkd.createRenderPass(vkctxt.vkc.device, render_pass_create_info, null) catch |err| { vkctxt.printVulkanError("Can't create render pass for ui", err, vkctxt.vkc.allocator); return; }; } fn createGraphicsPipeline(self: *UIVulkanContext) void { const push_constant_range: vk.PushConstantRange = .{ .stage_flags = .{ .vertex_bit = true }, .offset = 0, .size = @sizeOf(PushConstBlock), }; const pipeline_layout_create_info: vk.PipelineLayoutCreateInfo = .{ .set_layout_count = 1, .p_set_layouts = @ptrCast([*]const vk.DescriptorSetLayout, &self.descriptor_set_layout), .push_constant_range_count = 1, .p_push_constant_ranges = @ptrCast([*]const vk.PushConstantRange, &push_constant_range), .flags = .{}, }; self.pipeline_layout = vkctxt.vkd.createPipelineLayout(vkctxt.vkc.device, pipeline_layout_create_info, null) catch |err| { vkctxt.printVulkanError("Can't create pipeline layout", err, vkctxt.vkc.allocator); return; }; const input_assembly_state: vk.PipelineInputAssemblyStateCreateInfo = .{ .topology = .triangle_list, .flags = .{}, .primitive_restart_enable = vk.FALSE, }; const rasterization_state: vk.PipelineRasterizationStateCreateInfo = .{ .polygon_mode = .fill, .cull_mode = .{}, .front_face = .counter_clockwise, .flags = .{}, .depth_clamp_enable = vk.FALSE, .line_width = 1.0, .rasterizer_discard_enable = vk.FALSE, .depth_bias_enable = vk.FALSE, .depth_bias_constant_factor = 0, .depth_bias_clamp = 0, .depth_bias_slope_factor = 0, }; const blend_attachment_state: vk.PipelineColorBlendAttachmentState = .{ .blend_enable = vk.TRUE, .color_write_mask = .{ .r_bit = true, .g_bit = true, .b_bit = true, .a_bit = true }, .src_color_blend_factor = .src_alpha, .dst_color_blend_factor = .one_minus_src_alpha, .color_blend_op = .add, .src_alpha_blend_factor = .one_minus_src_alpha, .dst_alpha_blend_factor = .zero, .alpha_blend_op = .add, }; const color_blend_state: vk.PipelineColorBlendStateCreateInfo = .{ .attachment_count = 1, .p_attachments = @ptrCast([*]const vk.PipelineColorBlendAttachmentState, &blend_attachment_state), .flags = .{}, .logic_op_enable = vk.FALSE, .logic_op = undefined, .blend_constants = [4]f32{ 0.0, 0.0, 0.0, 0.0 }, }; const depth_stencil_state: vk.PipelineDepthStencilStateCreateInfo = .{ .depth_test_enable = vk.FALSE, .depth_write_enable = vk.FALSE, .depth_compare_op = .less_or_equal, .back = .{ .compare_op = .always, .fail_op = .keep, .pass_op = .keep, .depth_fail_op = .keep, .compare_mask = 0, .write_mask = 0, .reference = 0, }, .front = .{ .compare_op = .never, .fail_op = .keep, .pass_op = .keep, .depth_fail_op = .keep, .compare_mask = 0, .write_mask = 0, .reference = 0, }, .depth_bounds_test_enable = vk.FALSE, .stencil_test_enable = vk.FALSE, .flags = .{}, .min_depth_bounds = 0.0, .max_depth_bounds = 0.0, }; const viewport_state: vk.PipelineViewportStateCreateInfo = .{ .viewport_count = 1, .p_viewports = null, .scissor_count = 1, .p_scissors = null, .flags = .{}, }; const multisample_state: vk.PipelineMultisampleStateCreateInfo = .{ .rasterization_samples = .{ .@"1_bit" = true }, .flags = .{}, .sample_shading_enable = vk.FALSE, .min_sample_shading = 0, .p_sample_mask = undefined, .alpha_to_coverage_enable = vk.FALSE, .alpha_to_one_enable = vk.FALSE, }; const dynamic_enabled_states = [_]vk.DynamicState{ .viewport, .scissor }; const dynamic_state: vk.PipelineDynamicStateCreateInfo = .{ .p_dynamic_states = @ptrCast([*]const vk.DynamicState, &dynamic_enabled_states), .dynamic_state_count = 2, .flags = .{}, }; const vertex_input_bindings: vk.VertexInputBindingDescription = .{ .binding = 0, .stride = @sizeOf(c.ImDrawVert), .input_rate = .vertex, }; const vertex_input_attributes = [_]vk.VertexInputAttributeDescription{ .{ .binding = 0, .location = 0, .format = .r32g32_sfloat, .offset = @offsetOf(c.ImDrawVert, "pos"), }, .{ .binding = 0, .location = 1, .format = .r32g32_sfloat, .offset = @offsetOf(c.ImDrawVert, "uv"), }, .{ .binding = 0, .location = 2, .format = .r8g8b8a8_unorm, .offset = @offsetOf(c.ImDrawVert, "col"), }, }; const vertex_input_state: vk.PipelineVertexInputStateCreateInfo = .{ .vertex_binding_description_count = 1, .p_vertex_binding_descriptions = @ptrCast([*]const vk.VertexInputBindingDescription, &vertex_input_bindings), .vertex_attribute_description_count = 3, .p_vertex_attribute_descriptions = @ptrCast([*]const vk.VertexInputAttributeDescription, &vertex_input_attributes), .flags = .{}, }; const ui_vert_shader_stage: vk.PipelineShaderStageCreateInfo = .{ .stage = .{ .vertex_bit = true }, .module = self.vert_shader, .p_name = "main", .flags = .{}, .p_specialization_info = null, }; const ui_frag_shader_stage: vk.PipelineShaderStageCreateInfo = .{ .stage = .{ .fragment_bit = true }, .module = self.frag_shader, .p_name = "main", .flags = .{}, .p_specialization_info = null, }; const shader_stages = [_]vk.PipelineShaderStageCreateInfo{ ui_vert_shader_stage, ui_frag_shader_stage }; const pipeline_create_info: vk.GraphicsPipelineCreateInfo = .{ .layout = self.pipeline_layout, .render_pass = self.render_pass, .flags = .{}, .base_pipeline_index = -1, .base_pipeline_handle = .null_handle, .p_input_assembly_state = &input_assembly_state, .p_rasterization_state = &rasterization_state, .p_color_blend_state = &color_blend_state, .p_multisample_state = &multisample_state, .p_viewport_state = &viewport_state, .p_depth_stencil_state = &depth_stencil_state, .p_dynamic_state = &dynamic_state, .p_vertex_input_state = &vertex_input_state, .stage_count = 2, .p_stages = @ptrCast([*]const vk.PipelineShaderStageCreateInfo, &shader_stages), .p_tessellation_state = null, .subpass = 0, }; _ = vkctxt.vkd.createGraphicsPipelines( vkctxt.vkc.device, self.pipeline_cache, 1, @ptrCast([*]const vk.GraphicsPipelineCreateInfo, &pipeline_create_info), null, @ptrCast([*]vk.Pipeline, &self.pipeline), ) catch |err| { vkctxt.printVulkanError("Can't create graphics pipeline for ui", err, vkctxt.vkc.allocator); return; }; } fn initFonts(self: *UIVulkanContext) void { var io: c.ImGuiIO = c.igGetIO().*; var scale: [2]f32 = undefined; c.glfwGetWindowContentScale(self.parent.app.window, &scale[0], &scale[1]); _ = c.ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(io.Fonts, @ptrCast([*c]const u8, &c.FiraSans_compressed_data_base85), 13.0 * scale[1], null, null); var font_data: [*c]u8 = undefined; var tex_dim: [2]c_int = undefined; c.ImFontAtlas_GetTexDataAsRGBA32(io.Fonts, @ptrCast([*c][*c]u8, &font_data), &tex_dim[0], &tex_dim[1], null); const tex_size: usize = @intCast(usize, 4 * tex_dim[0] * tex_dim[1]); const buffer_info: vk.BufferCreateInfo = .{ .size = tex_size, .usage = .{ .transfer_src_bit = true, }, .sharing_mode = .exclusive, .flags = .{}, .queue_family_index_count = 0, .p_queue_family_indices = undefined, }; var staging_buffer: vk.Buffer = vkctxt.vkd.createBuffer(vkctxt.vkc.device, buffer_info, null) catch |err| { vkctxt.printVulkanError("Can't crete buffer for font texture", err, vkctxt.vkc.allocator); return; }; defer vkctxt.vkd.destroyBuffer(vkctxt.vkc.device, staging_buffer, null); var mem_req: vk.MemoryRequirements = vkctxt.vkd.getBufferMemoryRequirements(vkctxt.vkc.device, staging_buffer); const alloc_info: vk.MemoryAllocateInfo = .{ .allocation_size = mem_req.size, .memory_type_index = vkctxt.vkc.getMemoryType(mem_req.memory_type_bits, .{ .host_visible_bit = true, .host_coherent_bit = true }), }; var staging_buffer_memory: vk.DeviceMemory = vkctxt.vkd.allocateMemory(vkctxt.vkc.device, alloc_info, null) catch |err| { vkctxt.printVulkanError("Can't allocate buffer for font texture", err, vkctxt.vkc.allocator); return; }; defer vkctxt.vkd.freeMemory(vkctxt.vkc.device, staging_buffer_memory, null); vkctxt.vkd.bindBufferMemory(vkctxt.vkc.device, staging_buffer, staging_buffer_memory, 0) catch |err| { vkctxt.printVulkanError("Can't bind buffer memory for font texture", err, vkctxt.vkc.allocator); return; }; var mapped_memory: *anyopaque = vkctxt.vkd.mapMemory(vkctxt.vkc.device, staging_buffer_memory, 0, tex_size, .{}) catch |err| { vkctxt.printVulkanError("Can't map memory for font texture", err, vkctxt.vkc.allocator); return; } orelse return; @memcpy(@ptrCast([*]u8, mapped_memory), font_data, tex_size); vkctxt.vkd.unmapMemory(vkctxt.vkc.device, staging_buffer_memory); self.font_texture.init("Font Texture", @intCast(u32, tex_dim[0]), @intCast(u32, tex_dim[1]), .r8g8b8a8_unorm, vkctxt.vkc.allocator); self.font_texture.alloc(); const command_buffer: vk.CommandBuffer = rg.global_render_graph.allocateCommandBuffer(); RenderGraph.beginSingleTimeCommands(command_buffer); self.font_texture.transitionImageLayout(command_buffer, .@"undefined", .transfer_dst_optimal); const region: vk.BufferImageCopy = .{ .buffer_offset = 0, .buffer_row_length = 0, .buffer_image_height = 0, .image_subresource = .{ .aspect_mask = .{ .color_bit = true }, .mip_level = 0, .base_array_layer = 0, .layer_count = 1, }, .image_offset = .{ .x = 0, .y = 0, .z = 0 }, .image_extent = .{ .width = @intCast(u32, tex_dim[0]), .height = @intCast(u32, tex_dim[1]), .depth = 1, }, }; vkctxt.vkd.cmdCopyBufferToImage(command_buffer, staging_buffer, self.font_texture.image, .transfer_dst_optimal, 1, @ptrCast([*]const vk.BufferImageCopy, &region)); self.font_texture.transitionImageLayout(command_buffer, .transfer_dst_optimal, .shader_read_only_optimal); RenderGraph.endSingleTimeCommands(command_buffer); rg.global_render_graph.submitCommandBuffer(command_buffer); const pool_size: vk.DescriptorPoolSize = .{ .type = .combined_image_sampler, .descriptor_count = 1, }; const descriptor_pool_info: vk.DescriptorPoolCreateInfo = .{ .pool_size_count = 1, .p_pool_sizes = @ptrCast([*]const vk.DescriptorPoolSize, &pool_size), .max_sets = 2, .flags = .{}, }; self.descriptor_pool = vkctxt.vkd.createDescriptorPool(vkctxt.vkc.device, descriptor_pool_info, null) catch |err| { vkctxt.printVulkanError("Can't create descriptor pool for ui", err, vkctxt.vkc.allocator); return; }; const set_layout_bindings: vk.DescriptorSetLayoutBinding = .{ .stage_flags = .{ .fragment_bit = true }, .binding = 0, .descriptor_count = 1, .descriptor_type = .combined_image_sampler, .p_immutable_samplers = undefined, }; const set_layout_create_info: vk.DescriptorSetLayoutCreateInfo = .{ .binding_count = 1, .p_bindings = @ptrCast([*]const vk.DescriptorSetLayoutBinding, &set_layout_bindings), .flags = .{}, }; self.descriptor_set_layout = vkctxt.vkd.createDescriptorSetLayout(vkctxt.vkc.device, set_layout_create_info, null) catch |err| { vkctxt.printVulkanError("Can't create descriptor set layout for ui", err, vkctxt.vkc.allocator); return; }; const descriptor_set_allocate_info: vk.DescriptorSetAllocateInfo = .{ .descriptor_pool = self.descriptor_pool, .p_set_layouts = @ptrCast([*]const vk.DescriptorSetLayout, &self.descriptor_set_layout), .descriptor_set_count = 1, }; vkctxt.vkd.allocateDescriptorSets(vkctxt.vkc.device, descriptor_set_allocate_info, @ptrCast([*]vk.DescriptorSet, &self.descriptor_set)) catch |err| { vkctxt.printVulkanError("Can't allocate descriptor set for ui", err, vkctxt.vkc.allocator); return; }; const font_descriptor_image_info: vk.DescriptorImageInfo = .{ .sampler = self.font_texture.sampler, .image_view = self.font_texture.view, .image_layout = .shader_read_only_optimal, }; const write_descriptor_set: vk.WriteDescriptorSet = .{ .dst_set = self.descriptor_set, .descriptor_type = .combined_image_sampler, .dst_binding = 0, .p_image_info = @ptrCast([*]const vk.DescriptorImageInfo, &font_descriptor_image_info), .descriptor_count = 1, .dst_array_element = 0, .p_buffer_info = undefined, .p_texel_buffer_view = undefined, }; vkctxt.vkd.updateDescriptorSets(vkctxt.vkc.device, 1, @ptrCast([*]const vk.WriteDescriptorSet, &write_descriptor_set), 0, undefined); } fn initResources(self: *UIVulkanContext) void { self.initFonts(); const pipeline_cache_create_info: vk.PipelineCacheCreateInfo = .{ .flags = .{}, .initial_data_size = 0, .p_initial_data = undefined, }; self.pipeline_cache = vkctxt.vkd.createPipelineCache(vkctxt.vkc.device, pipeline_cache_create_info, null) catch |err| { vkctxt.printVulkanError("Can't create pipeline cache", err, vkctxt.vkc.allocator); return; }; const ui_vert = @embedFile("ui.vert"); const ui_frag = @embedFile("ui.frag"); self.vert_shader = shader_util.loadShader(ui_vert, .vertex); self.frag_shader = shader_util.loadShader(ui_frag, .fragment); self.createRenderPass(); self.createGraphicsPipeline(); const buffer_count: u32 = rg.global_render_graph.final_swapchain.image_count; self.vertex_buffers = vkctxt.vkc.allocator.alloc(Buffer, buffer_count) catch unreachable; self.index_buffers = vkctxt.vkc.allocator.alloc(Buffer, buffer_count) catch unreachable; self.vertex_buffer_counts = vkctxt.vkc.allocator.alloc(usize, buffer_count) catch unreachable; self.index_buffer_counts = vkctxt.vkc.allocator.alloc(usize, buffer_count) catch unreachable; for (self.vertex_buffers) |*buffer| { buffer.* = undefined; buffer.buffer = .null_handle; } for (self.index_buffers) |*buffer| { buffer.* = undefined; buffer.buffer = .null_handle; } for (self.vertex_buffer_counts) |*count| count.* = 0; for (self.index_buffer_counts) |*count| count.* = 0; } };
src/ui/ui_vulkan.zig
const base = @import("../base.zig"); const gen = @import("../gen.zig"); const COMMON = [_:null]?base.Segment{ .{ .offset = 0, .month = 1, .day_start = 1, .day_end = 31 }, .{ .offset = 31, .month = 2, .day_start = 1, .day_end = 28 }, .{ .offset = 59, .month = 3, .day_start = 1, .day_end = 31 }, .{ .offset = 90, .month = 4, .day_start = 1, .day_end = 30 }, .{ .offset = 120, .month = 5, .day_start = 1, .day_end = 31 }, .{ .offset = 151, .month = 6, .day_start = 1, .day_end = 30 }, .{ .offset = 181, .month = 7, .day_start = 1, .day_end = 31 }, .{ .offset = 212, .month = 8, .day_start = 1, .day_end = 31 }, .{ .offset = 243, .month = 9, .day_start = 1, .day_end = 30 }, .{ .offset = 273, .month = 10, .day_start = 1, .day_end = 31 }, .{ .offset = 304, .month = 11, .day_start = 1, .day_end = 30 }, .{ .offset = 334, .month = 12, .day_start = 1, .day_end = 31 }, }; const LEAP = [_:null]?base.Segment{ .{ .offset = 0, .month = 1, .day_start = 1, .day_end = 31 }, .{ .offset = 31, .month = 2, .day_start = 1, .day_end = 29 }, .{ .offset = 60, .month = 3, .day_start = 1, .day_end = 31 }, .{ .offset = 91, .month = 4, .day_start = 1, .day_end = 30 }, .{ .offset = 121, .month = 5, .day_start = 1, .day_end = 31 }, .{ .offset = 152, .month = 6, .day_start = 1, .day_end = 30 }, .{ .offset = 182, .month = 7, .day_start = 1, .day_end = 31 }, .{ .offset = 213, .month = 8, .day_start = 1, .day_end = 31 }, .{ .offset = 244, .month = 9, .day_start = 1, .day_end = 30 }, .{ .offset = 274, .month = 10, .day_start = 1, .day_end = 31 }, .{ .offset = 305, .month = 11, .day_start = 1, .day_end = 30 }, .{ .offset = 335, .month = 12, .day_start = 1, .day_end = 31 }, }; var common_var: [COMMON.len:null]?base.Segment = COMMON; var leap_var: [LEAP.len:null]?base.Segment = LEAP; pub const gregorian = base.Cal{ .intercalary_list = null, .common_lookup_list = @ptrCast([*:null]?base.Segment, &common_var), .leap_lookup_list = @as([*:null]?base.Segment, &leap_var), .leap_cycle = .{ .year_count = 4, .leap_year_count = 1, .offset_years = 0, .common_days = gen.dayCount(COMMON[0..COMMON.len]), .leap_days = gen.leapDayCount(COMMON[0..COMMON.len], LEAP[0..LEAP.len]), .offset_days = 0, .skip100 = true, .skip4000 = false, .symmetric = false, }, .week = .{ .start = @enumToInt(base.Weekday7.NoWeekday), .length = gen.lastOfEnum(base.Weekday7), .continuous = true, }, .epoch_mjd = gen.mjdFromVcalc(-678574.5), //1 Jan, 1 CE .common_month_max = gen.monthMax(COMMON[0..COMMON.len]), .leap_month_max = gen.monthMax(LEAP[0..LEAP.len]), .year0 = false, }; pub const gregorian_year_zero = base.Cal{ .intercalary_list = gregorian.intercalary_list, .common_lookup_list = gregorian.common_lookup_list, .leap_lookup_list = gregorian.leap_lookup_list, .leap_cycle = gregorian.leap_cycle, .week = gregorian.week, .epoch_mjd = gregorian.epoch_mjd, .common_month_max = gregorian.common_month_max, .leap_month_max = gregorian.leap_month_max, .year0 = true, };
src/cal/gregorian.zig
const std = @import("std"); const gdt = @import("gdt.zig"); const isr = @import("isr.zig"); const layout = @import("layout.zig"); const mem = @import("mem.zig"); const vmem = @import("vmem.zig"); const scheduler = @import("scheduler.zig"); const x86 = @import("x86.zig"); const Array = std.ArrayList; const List = std.IntrusiveLinkedList; const Mailbox = @import("ipc.zig").Mailbox; const Message = std.os.zen.Message; const Process = @import("process.zig").Process; const assert = std.debug.assert; const STACK_SIZE = x86.PAGE_SIZE; // Size of thread stacks. // Keep track of all the threads. var threads = Array(?&Thread).init(&mem.allocator); // List of threads inside a process. pub const ThreadList = List(Thread, "process_link"); // Queue of threads (for scheduler and mailboxes). pub const ThreadQueue = List(Thread, "queue_link"); // Structure representing a thread. pub const Thread = struct { // TODO: simplify once #679 is solved. process_link: List(Thread, "process_link").Node, queue_link: List(Thread, "queue_link").Node, context: isr.Context, process: &Process, local_tid: u8, tid: u16, message_destination: &Message, // Address where to deliver messages. mailbox: Mailbox, // Private thread mailbox. //// // Create a new thread inside the current process. // NOTE: Do not call this function directly. Use Process.createThread instead. // // Arguments: // entry_point: The entry point of the new thread. // // Returns: // Pointer to the new thread structure. // fn init(process: &Process, local_tid: u8, entry_point: usize) &Thread { assert (scheduler.current_process == process); // Calculate the address of the thread stack and map it. const stack = getStack(local_tid); vmem.mapZone(stack, null, STACK_SIZE, vmem.PAGE_WRITE | vmem.PAGE_USER); // Allocate and initialize the thread structure. const thread = mem.allocator.create(Thread) catch unreachable; *thread = Thread { .context = initContext(entry_point, stack), .process = process, .local_tid = local_tid, .tid = u16(threads.len), .process_link = ThreadList.Node.initIntrusive(), .queue_link = ThreadQueue.Node.initIntrusive(), .mailbox = Mailbox.init(), .message_destination = undefined, }; threads.append(@ptrCast(?&Thread, thread)) catch unreachable; // TODO: simplify once #836 is solved. return thread; } //// // Destroy the thread and schedule a new one if necessary. // pub fn destroy(self: &Thread) void { assert (scheduler.current_process == self.process); // Unmap the thread stack. var stack = getStack(self.local_tid); vmem.unmapZone(stack, STACK_SIZE); // Get the thread off the process and scheduler, and deallocate its structure. self.process.removeThread(self); threads.items[self.tid] = null; mem.allocator.destroy(self); // TODO: get the thread off IPC waiting queues. } }; //// // Get a thread. // // Arguments: // tid: The ID of the thread. // // Returns: // Pointer to the thread, null if non-existent. // pub fn get(tid: u16) ?&Thread { return threads.items[tid]; } //// // Set up the initial context of a thread. // // Arguments: // entry_point: Entry point of the thread. // stack: The beginning of the stack. // // Returns: // The initialized context. // fn initContext(entry_point: usize, stack: usize) isr.Context { // Insert a trap return address to destroy the thread on return. var stack_top = @intToPtr(&usize, stack + STACK_SIZE - @sizeOf(usize)); *stack_top = layout.THREAD_DESTROY; return isr.Context { .cs = gdt.USER_CODE | gdt.USER_RPL, .ss = gdt.USER_DATA | gdt.USER_RPL, .eip = entry_point, .esp = @ptrToInt(stack_top), .eflags = 0x202, .registers = isr.Registers.init(), .interrupt_n = 0, .error_code = 0, }; } //// // Get the address of a thread stack. // // Arguments: // local_tid: Local TID of the thread inside the process. // // Returns: // The address of the beginning of the stack. // fn getStack(local_tid: u8) usize { const stack = layout.USER_STACKS + (2 * (local_tid - 1) * STACK_SIZE); assert (stack < layout.USER_STACKS_END); return stack; }
kernel/thread.zig
const std = @import("std"); const pokemon = @import("pokemon"); const gba = @import("gba"); const gb = @import("gb"); const gen3 = @import("gen3.zig"); const gen2 = @import("gen2.zig"); const io = std.io; const os = std.os; const math = std.math; const mem = std.mem; const debug = std.debug; const common = pokemon.common; pub fn main() !void { var direct_allocator = std.heap.DirectAllocator.init(); defer direct_allocator.deinit(); // NOTE: Do we want to use another allocator for arguments? Does it matter? Idk. const args = try os.argsAlloc(&direct_allocator.allocator); defer os.argsFree(&direct_allocator.allocator, args); if (args.len < 2) { debug.warn("No file was provided.\n"); return error.NoFileInArguments; } for (args[1..]) |arg| { var arena = std.heap.ArenaAllocator.init(&direct_allocator.allocator); defer arena.deinit(); const allocator = &arena.allocator; var file = os.File.openRead(arg) catch |err| { debug.warn("Couldn't open {}.\n", arg); return err; }; defer file.close(); var file_stream = file.inStream(); var stream = &file_stream.stream; const data = try stream.readAllAlloc(allocator, math.maxInt(usize)); defer allocator.free(data); var gamecode: []const u8 = undefined; var game_title: []const u8 = undefined; const version = blk: { const gba_gamecode = gbaGamecode(data); const gba_game_title = gbaGameTitle(data); const gb_gamecode = gbGamecode(data); const gb_title = gbGameTitle(data); if (getVersion(gba_gamecode)) |v| { gamecode = gba_gamecode; game_title = gba_game_title; break :blk v; } else |err1| if (getVersion(gb_gamecode)) |v| { gamecode = gb_gamecode; game_title = gb_title; break :blk v; } else |err2| if (getVersion(gb_title)) |v| { gamecode = gb_gamecode; game_title = gb_title; break :blk v; } else |err3| { debug.warn("Neither gba gamecode '{}', gb gamecode '{}' or gb title '{}' correspond with any Pokemon game.\n", gba_gamecode, gb_gamecode, gb_title); return err3; } }; switch (version.gen()) { 1 => unreachable, 2 => { const info = try gen2.findInfoInFile(data, version, allocator); debug.warn(".base_stats = Offset {{ .start = 0x{X7}, .len = {d3}, }},\n", info.base_stats.start, info.base_stats.len); }, 3 => { const info = try gen3.findInfoInFile(data, version); debug.warn("Info{{\n"); debug.warn(" .game_title = \"{}\",\n", game_title); debug.warn(" .gamecode = \"{}\",\n", gamecode); debug.warn(" .version = libpoke.Version.{},\n", @tagName(version)); debug.warn(" .trainers = TrainerSection"); dumpSection(info.trainers); debug.warn(" .moves = MoveSection"); dumpSection(info.moves); debug.warn(" .machine_learnsets = MachineLearnsetSection"); dumpSection(info.machine_learnsets); debug.warn(" .base_stats = BaseStatsSection"); dumpSection(info.base_stats); debug.warn(" .evolutions = EvolutionSection"); dumpSection(info.evolutions); debug.warn(" .level_up_learnset_pointers = LevelUpLearnsetPointerSection"); dumpSection(info.level_up_learnset_pointers); debug.warn(" .hms = HmSection"); dumpSection(info.hms); debug.warn(" .tms = TmSection"); dumpSection(info.tms); debug.warn(" .items = ItemSection"); dumpSection(info.items); debug.warn(" .wild_pokemon_headers = WildPokemonHeaderSection"); dumpSection(info.wild_pokemon_headers); debug.warn("}};\n"); }, else => unreachable, } } } fn dumpSection(sec: var) void { debug.warn("{{\n"); debug.warn(" .start = 0x{X8},\n", sec.start); debug.warn(" .len = {},\n", sec.len); debug.warn(" }},\n"); } fn getVersion(gamecode: []const u8) !pokemon.Version { if (mem.startsWith(u8, gamecode, "BPE")) return pokemon.Version.Emerald; if (mem.startsWith(u8, gamecode, "BPR")) return pokemon.Version.FireRed; if (mem.startsWith(u8, gamecode, "BPG")) return pokemon.Version.LeafGreen; if (mem.startsWith(u8, gamecode, "AXV")) return pokemon.Version.Ruby; if (mem.startsWith(u8, gamecode, "AXP")) return pokemon.Version.Sapphire; if (mem.startsWith(u8, gamecode, "AAX")) return pokemon.Version.Silver; if (mem.startsWith(u8, gamecode, "AAU")) return pokemon.Version.Gold; if (mem.startsWith(u8, gamecode, "BYT")) return pokemon.Version.Crystal; if (mem.startsWith(u8, gamecode, "POKEMON RED")) return pokemon.Version.Red; if (mem.startsWith(u8, gamecode, "POKEMON BLUE")) return pokemon.Version.Blue; if (mem.startsWith(u8, gamecode, "POKEMON YELLOW")) return pokemon.Version.Yellow; return error.UnknownPokemonVersion; } fn gbaGamecode(data: []const u8) []const u8 { const header = &@bytesToSlice(gba.Header, data[0..@sizeOf(gba.Header)])[0]; return header.gamecode; } fn gbaGameTitle(data: []const u8) []const u8 { const header = &@bytesToSlice(gba.Header, data[0..@sizeOf(gba.Header)])[0]; return header.game_title; } fn gbGamecode(data: []const u8) []const u8 { const header = &@bytesToSlice(gb.Header, data[0..@sizeOf(gb.Header)])[0]; return header.title.split.gamecode; } fn gbGameTitle(data: []const u8) []const u8 { const header = &@bytesToSlice(gb.Header, data[0..@sizeOf(gb.Header)])[0]; return header.title.full; }
tools/offset-finder/main.zig
const std = @import("std"); usingnamespace @import("ast.zig"); usingnamespace @import("types.zig"); //digraph graphname { // "A" -> {B C} // "A" -> X // X -> " lol hi" //} pub const DotPrinter = struct { printTypes: bool, const Self = @This(); pub fn init(writer: anytype, printTypes: bool) !Self { try writer.writeAll("digraph Ast {\n"); return Self{ .printTypes = printTypes, }; } pub fn deinit(self: *Self, writer: anytype) void { writer.writeAll("}") catch {}; } fn newLine(self: *Self, writer: anytype) anyerror!void { try writer.writeAll("\n "); } fn printNode(self: *Self, writer: anytype, ast: *Ast) anyerror!void { const UnionTagType = @typeInfo(AstSpec).Union.tag_type.?; try std.fmt.format(writer, "\"{s} #{}", .{ @tagName(@as(UnionTagType, ast.spec)), ast.id }); if (self.printTypes) { try std.fmt.format(writer, "\\n{}", .{ast.typ}); } try self.printNodeArg(writer, ast); try std.fmt.format(writer, "\"", .{}); } fn printConnection(self: *Self, writer: anytype, from: *Ast, to: *Ast) anyerror!void { try writer.writeAll(" "); try self.printNode(writer, from); try writer.writeAll(" -> "); try self.printNode(writer, to); try writer.writeAll("\n"); } pub fn printGraph(self: *Self, writer: anytype, _ast: *Ast) anyerror!void { switch (_ast.spec) { // .Access => |*ast| { try self.printConnection(writer, _ast, ast.left); try self.printConnection(writer, _ast, ast.right); try self.printGraph(writer, ast.left); try self.printGraph(writer, ast.right); }, .Assignment => |*ast| { try self.printConnection(writer, _ast, ast.pattern); try self.printConnection(writer, _ast, ast.value); try self.printGraph(writer, ast.pattern); try self.printGraph(writer, ast.value); }, .Block => |*ast| { for (ast.body.items) |expr| { try self.printConnection(writer, _ast, expr); try self.printGraph(writer, expr); } }, .Call => |*ast| { try self.printConnection(writer, _ast, ast.func); try self.printGraph(writer, ast.func); for (ast.args.items) |expr| { try self.printConnection(writer, _ast, expr); try self.printGraph(writer, expr); } }, .ConstDecl => |*ast| { try self.printConnection(writer, _ast, ast.pattern); try self.printGraph(writer, ast.pattern); if (ast.typ) |typ| { try self.printConnection(writer, _ast, typ); try self.printGraph(writer, typ); } try self.printConnection(writer, _ast, ast.value); try self.printGraph(writer, ast.value); }, .VarDecl => |*ast| { try self.printConnection(writer, _ast, ast.pattern); try self.printGraph(writer, ast.pattern); if (ast.typ) |typ| { try self.printConnection(writer, _ast, typ); try self.printGraph(writer, typ); } if (ast.value) |val| { try self.printConnection(writer, _ast, val); try self.printGraph(writer, val); } }, .Lambda => |*ast| { for (ast.args.items) |expr| { try self.printConnection(writer, _ast, expr); try self.printGraph(writer, expr); } try self.printConnection(writer, _ast, ast.body); try self.printGraph(writer, ast.body); }, .Pipe => |*ast| { //try self.printConnection(writer, _ast, ast.left); try self.printConnection(writer, _ast, ast.right); //try self.printGraph(writer, ast.left); try self.printGraph(writer, ast.right); }, .Tuple => |*ast| { for (ast.values.items) |expr| { try self.printConnection(writer, _ast, expr); try self.printGraph(writer, expr); } }, .Function => |*ast| { for (ast.args.items) |expr| { try self.printConnection(writer, _ast, expr); try self.printGraph(writer, expr); } try self.printConnection(writer, _ast, ast.body); try self.printGraph(writer, ast.body); }, else => {}, } } pub fn printNodeArg(self: *Self, writer: anytype, ast: *Ast) anyerror!void { switch (ast.spec) { .Access => |*acc| try std.fmt.format(writer, "\\n.", .{}), .Assignment => |*ass| try std.fmt.format(writer, "\\n=", .{}), .Block => |*block| try std.fmt.format(writer, "\\n{{}}", .{}), .Call => |*call| try std.fmt.format(writer, "\\n()", .{}), .ConstDecl => |*decl| try std.fmt.format(writer, "\\n::", .{}), .Float => |float| try std.fmt.format(writer, "\\n{}", .{float.value}), .Function => |*func| try std.fmt.format(writer, "\\nfn", .{}), .Identifier => |id| try std.fmt.format(writer, "\\n{s}", .{id.name}), .Int => |int| try std.fmt.format(writer, "\\n{}", .{int.value}), .Lambda => |*lambda| try std.fmt.format(writer, "\\n||", .{}), .Pipe => |*pipe| try std.fmt.format(writer, "\\n->", .{}), .Return => |*ret| try std.fmt.format(writer, "\\nreturn", .{}), .String => |text| try std.fmt.format(writer, "\\n{s}", .{text.value}), .Tuple => |*tuple| try std.fmt.format(writer, "\\n(,)", .{}), .VarDecl => |*decl| try std.fmt.format(writer, "\\n:=", .{}), //else => try writer.writeAll("<Unknown>"), } } };
src/dot_printer.zig
const std = @import("std"); const Edge = enum{ left, right, top, bottom }; pub const RectF = struct { x: f32 = 0, y: f32 = 0, width: f32 = 0, height: f32 = 0, }; pub const Rect = struct { x: i32 = 0, y: i32 = 0, width: i32 = 0, height: i32 = 0, pub fn right(self: Rect) i32 { return self.x + self.width; } pub fn left(self: Rect) i32 { return self.x; } pub fn top(self: Rect) i32 { return self.y; } pub fn bottom(self: Rect) i32 { return self.y + self.height; } pub fn centerX(self: Rect) i32 { return self.x + @divTrunc(self.width, 2); } pub fn centerY(self: Rect) i32 { return self.y + @divTrunc(self.height, 2); } pub fn halfRect(self: Rect, edge: Edge) Rect { return switch (edge) { .top => Rect{ .x = self.x, .y = self.y, .width = self.width, .h = @divTrunc(self.height, 2) }, .bottom => Rect{ .x = self.x, .y = self.y + @divTrunc(self.h, 2), .width = self.width, .height = @divTrunc(self.height, 2) }, .left => Rect{ .x = self.x, .y = self.y, .width = @divTrunc(self.width, 2), .h = self.height }, .right => Rect{ .x = self.x + @divTrunc(self.width, 2), .y = self.y, .width = @divTrunc(self.width, 2), .height = self.height }, }; } pub fn contract(self: *Rect, hor: i32, vert: i32) void { self.x += hor; self.y += vert; self.width -= hor * 2; self.height -= vert * 2; } pub fn expandEdge(self: *Rect, edge: Edge, move_x: i32) void { const amt = std.math.absInt(move_x) catch unreachable; switch (edge) { .top => { self.y -= amt; self.height += amt; }, .bottom => { self.height += amt; }, .left => { self.x -= amt; self.width += amt; }, .right => { self.width += amt; }, } } pub fn side(self: Rect, edge: Edge) i32 { return switch (edge) { .left => self.x, .right => self.x + self.width, .top => self.y, .bottom => self.y + self.height, }; } pub fn contains(self: Rect, x: i32, y: i32) bool { return self.x <= x and x < self.right() and self.y <= y and y < self.bottom(); } pub fn asRectF(self: Rect) RectF { return .{ .x = @intToFloat(f32, self.x), .y = @intToFloat(f32, self.y), .width = @intToFloat(f32, self.width), .height = @intToFloat(f32, self.height), }; } };
src/math/rect.zig
const std = @import("std"); const mem = std.mem; const net = std.net; const os = std.os; const time = std.time; const IO = @import("tigerbeetle-io").IO; const http = @import("http"); const Client = struct { io: IO, sock: os.socket_t, address: std.net.Address, recv_timeout_ns: u63, send_buf: []u8, recv_buf: []u8, allocator: mem.Allocator, completions: [2]IO.Completion = undefined, done: bool = false, fn init(allocator: mem.Allocator, address: std.net.Address, recv_timeout_ns: u63) !Client { const sock = try os.socket(address.any.family, os.SOCK_STREAM | os.SOCK_CLOEXEC, 0); const send_buf = try allocator.alloc(u8, 8192); const recv_buf = try allocator.alloc(u8, 8192); return Client{ .io = try IO.init(256, 0), .sock = sock, .address = address, .recv_timeout_ns = recv_timeout_ns, .send_buf = send_buf, .recv_buf = recv_buf, .allocator = allocator, }; } pub fn deinit(self: *Client) void { self.allocator.free(self.send_buf); self.allocator.free(self.recv_buf); self.io.deinit(); } pub fn run(self: *Client) !void { self.io.connect(*Client, self, connectCallback, &self.completions[0], self.sock, self.address); while (!self.done) try self.io.tick(); } fn connectCallback( self: *Client, completion: *IO.Completion, result: IO.ConnectError!void, ) void { if (result) |_| { self.sendHello(); } else |err| { std.debug.print("connectCallback err={s}\n", .{@errorName(err)}); self.done = true; } } fn sendHello(self: *Client) void { var fbs = std.io.fixedBufferStream(self.send_buf); var w = fbs.writer(); std.fmt.format(w, "Hello from client!\n", .{}) catch unreachable; self.io.send( *Client, self, sendCallback, &self.completions[0], self.sock, fbs.getWritten(), if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); } fn sendCallback( self: *Client, completion: *IO.Completion, result: IO.SendError!usize, ) void { const sent = result catch @panic("send error"); std.debug.print("Sent: {s}", .{self.send_buf[0..sent]}); self.recvWithTimeout(); } fn recvWithTimeout(self: *Client) void { self.io.recv( *Client, self, recvCallback, &self.completions[0], self.sock, self.recv_buf, if (std.Target.current.os.tag == .linux) os.MSG_NOSIGNAL else 0, ); self.io.timeout( *Client, self, timeoutCallback, &self.completions[1], self.recv_timeout_ns, ); } fn recvCallback( self: *Client, completion: *IO.Completion, result: IO.RecvError!usize, ) void { if (result) |received| { std.debug.print("Received: {s}", .{self.recv_buf[0..received]}); self.io.cancelTimeout( *Client, self, cancelTimeoutCallback, &self.completions[0], &self.completions[1], ); } else |err| { std.debug.print("recvCallback err={s}\n", .{@errorName(err)}); if (err != error.Canceled) { @panic(@errorName(err)); } } } fn timeoutCallback( self: *Client, completion: *IO.Completion, result: IO.TimeoutError!void, ) void { std.debug.print("timeoutCallback start\n", .{}); if (result) |_| { completion.io.cancel( *Client, self, cancelRecvCallback, &self.completions[1], &self.completions[0], ); } else |err| { std.debug.print("timeoutCallback err={s}\n", .{@errorName(err)}); if (err != error.Canceled) { @panic(@errorName(err)); } } } fn cancelRecvCallback( self: *Client, completion: *IO.Completion, result: IO.CancelError!void, ) void { std.debug.print("cancelRecvCallback start\n", .{}); self.close(); } fn cancelTimeoutCallback( self: *Client, completion: *IO.Completion, result: IO.CancelTimeoutError!void, ) void { std.debug.print("cancelTimeoutCallback start\n", .{}); self.close(); } fn close(self: *Client) void { self.io.close( *Client, self, closeCallback, &self.completions[0], self.sock, ); } fn closeCallback( self: *Client, completion: *IO.Completion, result: IO.CloseError!void, ) void { std.debug.print("closeCallback start\n", .{}); _ = result catch @panic("close error"); self.done = true; } }; pub fn main() anyerror!void { const allocator = std.heap.page_allocator; const address = try std.net.Address.parseIp4("127.0.0.1", 3131); var recv_timeout: u63 = 500 * std.time.ns_per_ms; var args = std.process.args(); if (args.nextPosix()) |_| { if (args.nextPosix()) |arg| { if (std.fmt.parseInt(u63, arg, 10)) |v| { recv_timeout = v * std.time.ns_per_ms; } else |_| {} } } std.debug.print("recv_timeout={d} ms.\n", .{recv_timeout / time.ns_per_ms}); var client = try Client.init(allocator, address, recv_timeout); defer client.deinit(); try client.run(); }
examples/tcp_echo_client_timeout.zig
const std = @import("std"); const os = std.os; const wayland = @import("wayland"); const wl = wayland.client.wl; const xdg = wayland.client.xdg; const Context = struct { shm: ?*wl.Shm, compositor: ?*wl.Compositor, wm_base: ?*xdg.WmBase, }; pub fn main() anyerror!void { const display = try wl.Display.connect(null); const registry = try display.getRegistry(); var context = Context{ .shm = null, .compositor = null, .wm_base = null, }; registry.setListener(*Context, registryListener, &context); _ = try display.roundtrip(); const shm = context.shm orelse return error.NoWlShm; const compositor = context.compositor orelse return error.NoWlCompositor; const wm_base = context.wm_base orelse return error.NoXdgWmBase; const buffer = blk: { const width = 128; const height = 128; const stride = width * 4; const size = stride * height; const fd = try os.memfd_create("hello-zig-wayland", 0); try os.ftruncate(fd, size); const data = try os.mmap(null, size, os.PROT.READ | os.PROT.WRITE, os.MAP.SHARED, fd, 0); std.mem.copy(u8, data, @embedFile("cat.bgra")); const pool = try shm.createPool(fd, size); defer pool.destroy(); break :blk try pool.createBuffer(0, width, height, stride, wl.Shm.Format.argb8888); }; defer buffer.destroy(); const surface = try compositor.createSurface(); defer surface.destroy(); const xdg_surface = try wm_base.getXdgSurface(surface); defer xdg_surface.destroy(); const xdg_toplevel = try xdg_surface.getToplevel(); defer xdg_toplevel.destroy(); var running = true; xdg_surface.setListener(*wl.Surface, xdgSurfaceListener, surface); xdg_toplevel.setListener(*bool, xdgToplevelListener, &running); surface.commit(); _ = try display.roundtrip(); surface.attach(buffer, 0, 0); surface.commit(); while (running) _ = try display.dispatch(); } fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, context: *Context) void { switch (event) { .global => |global| { if (std.cstr.cmp(global.interface, wl.Compositor.getInterface().name) == 0) { context.compositor = registry.bind(global.name, wl.Compositor, 1) catch return; } else if (std.cstr.cmp(global.interface, wl.Shm.getInterface().name) == 0) { context.shm = registry.bind(global.name, wl.Shm, 1) catch return; } else if (std.cstr.cmp(global.interface, xdg.WmBase.getInterface().name) == 0) { context.wm_base = registry.bind(global.name, xdg.WmBase, 1) catch return; } }, .global_remove => {}, } } fn xdgSurfaceListener(xdg_surface: *xdg.Surface, event: xdg.Surface.Event, surface: *wl.Surface) void { switch (event) { .configure => |configure| { xdg_surface.ackConfigure(configure.serial); surface.commit(); }, } } fn xdgToplevelListener(_: *xdg.Toplevel, event: xdg.Toplevel.Event, running: *bool) void { switch (event) { .configure => {}, .close => running.* = false, } }
hello.zig
const std = @import("std"); const platform = @import("platform"); const util = @import("util.zig"); const vfs = @import("vfs.zig"); const task = @import("task.zig"); const wasm_rt = @import("runtime/wasm.zig"); const Error = error{NotImplemented, NotCapable}; pub const RuntimeType = enum { wasm, native, // TODO zpu, // TODO }; pub const Runtime = union(RuntimeType) { wasm: wasm_rt.Runtime, native: void, zpu: void, fn start(self: *Runtime) void { switch (self.*) { .wasm => self.wasm.start(), .native => unreachable, else => unreachable, } } fn deinit(self: *Runtime) void { switch (self.*) { .wasm => self.wasm.deinit(), .native => unreachable, else => unreachable, } } }; pub const RuntimeArg = union(RuntimeType) { wasm: wasm_rt.Runtime.Args, native: void, zpu: void }; pub const Credentials = struct { uid: u32 = 0, gid: u32 = 0, extra_groups: ?[]u32 = null, key: u128 = 0xFFFF_EEEE_DDDD_BEEF_CCCC_AAAA_FFEE_DEAD, // Internal process key. Not yet used. }; pub const Fd = struct { pub const Num = u32; // No more than 65536 open Fds pub const max_num: Fd.Num = 65536; pub const Flags = struct { sync: bool = false, nonblock: bool = false, }; pub const OpenFlags = extern union { Flags: packed struct { truncate: bool = false, exclusive: bool = false, directory: bool = false, create: bool = false, }, Int: u16, }; pub const Rights = extern union { Flags: packed struct { sock_shutdown: bool = true, poll_fd_readwrite: bool = true, path_unlink_file: bool = true, path_remove_directory: bool = true, path_symlink: bool = true, fd_filestat_set_times: bool = true, fd_filestat_set_size: bool = true, fd_filestat_get: bool = true, path_filestat_set_times: bool = true, path_filestat_set_size: bool = true, path_filestat_get: bool = true, path_rename_target: bool = true, path_rename_source: bool = true, path_readlink: bool = true, fd_readdir: bool = true, path_open: bool = true, path_link_target: bool = true, path_link_source: bool = true, path_create_file: bool = true, path_create_directory: bool = true, fd_allocate: bool = true, fd_advise: bool = true, fd_write: bool = true, fd_tell: bool = true, fd_sync: bool = true, fd_fdstat_set_flags: bool = true, fd_seek: bool = true, fd_read: bool = true, fd_datasync: bool = true, }, Int: u64, }; num: Fd.Num, name: ?[]const u8 = null, node: *vfs.Node, preopen: bool = false, flags: Fd.Flags = .{}, open_flags: Fd.OpenFlags = .{ .Flags = .{} }, rights: Fd.Rights = .{ .Flags = .{} }, inheriting_rights: Fd.Rights = .{ .Flags = .{} }, seek_offset: u64 = 0, proc: ?*Process = null, pub fn checkRights(self: Fd, comptime rights: anytype) !void { inline for (rights) |right| { if (!@field(self.rights.Flags, right)) return Error.NotCapable; } } pub fn open(self: *Fd, path: []const u8, oflags: Fd.OpenFlags, rights_base: Fd.Rights, inheriting_rights: Fd.Rights, fdflags: Fd.Flags, mode: vfs.FileMode) !*Fd { try self.checkRights(.{"path_open"}); var ret_node: ?*Node = self.node.findRecursive(path) catch |err| { if (!oflags.Flags.create || err != vfs.NoSuchFile) return err; ret_node = null; }; errdefer if (ret_node != null) ret_node.?.close(); if (ret_node) |ret_node_tmp| { if (oflags.Flags.exclusive) return vfs.FileExists; if (oflags.Flags.directory && ret_node_tmp.stat.type != .directory) return vfs.NotDirectory; } else if (oflags.Flags.create) { var parent_dir = vfs.dirname(path); var parent_node: *Node = if (parent_dir.len == 0) self.node else try self.node.findRecursive(parent_dir); ret_node = try parent_node.create(vfs.basename(path), if (oflags.Flags.directory) .directory else .file, mode); } else { unreachable; } // TODO: truncate var new_fd = try self.proc.?.allocator.create(Fd); errdefer self.proc.?.allocator.destroy(new_fd); // TODO: handle rights properly new_fd .* = .{ .proc = self.proc, .node = ret_node.?, .flags = fdflags, .rights = rights_base, .inheriting_rights = inheriting_rights, .num = undefined }; var fd_num: Fd.Num = 0; while (fd_num < Fd.max_num) { new_fd.num = fd_num self.proc.?.open_nodes.putNoClobber(new_fd.num, new_fd) catch { fd_num += 1; continue; } break; } return new_fd; } pub fn write(self: *Fd, buffer: []const u8) !usize { try self.checkRights(.{"fd_write"}); var written: usize = 0; while (true) { self.proc.?.task().yield(); written = self.node.write(self.seek_offset, buffer) catch |err| switch (err) { vfs.Error.Again => { if (!self.flags.nonblock) continue else return err; }, else => { return err; }, }; break; } self.seek_offset += @truncate(u64, written); return written; } pub fn read(self: *Fd, buffer: []u8) !usize { try self.checkRights(.{"fd_read"}); var amount: usize = 0; while (true) { self.proc.?.task().yield(); amount = self.node.read(self.seek_offset, buffer) catch |err| switch (err) { vfs.Error.Again => { if (!self.flags.nonblock) continue else return err; }, else => { return err; }, }; break; } self.seek_offset += @truncate(u64, amount); return amount; } pub fn close(self: *Fd) !void { try self.node.close(); if (self.proc) |proc| { proc.allocator.destroy(self); } } }; pub const Process = struct { pub const Id = task.Task.Id; pub const Arg = struct { name: []const u8 = "<unnamed>", argv: []const u8 = "<unnamed>", credentials: Credentials = .{}, fds: []const Fd = &[_]Fd{}, runtime_arg: RuntimeArg, stack_size: usize = 131072, parent_pid: ?Process.Id = null, }; host: *ProcessHost, arena_allocator: std.heap.ArenaAllocator = undefined, allocator: *std.mem.Allocator = undefined, name: []const u8 = "<unnamed>", argv: []const u8 = "<unnamed>", argc: usize = 1, credentials: Credentials = .{}, runtime: Runtime = undefined, open_nodes: std.AutoHashMap(Fd.Num, *Fd) = undefined, exit_code: ?u32 = undefined, internal_task: ?*task.Task = null, pub inline fn task(self: *Process) *task.Task { return self.internal_task.?; } pub fn init(host: *ProcessHost, arg: Process.Arg) !*Process { var proc = try host.allocator.create(Process); proc.* = .{ .host = host }; proc.arena_allocator = std.heap.ArenaAllocator.init(host.allocator); errdefer proc.arena_allocator.deinit(); proc.allocator = &proc.arena_allocator.allocator; proc.name = try proc.allocator.dupe(u8, arg.name); errdefer proc.allocator.free(proc.name); proc.argv = try proc.allocator.dupe(u8, arg.argv); errdefer proc.allocator.free(proc.name); proc.argc = util.countElem(u8, arg.argv, '\x00'); proc.credentials = arg.credentials; proc.runtime = switch (arg.runtime_arg) { .wasm => .{ .wasm = try wasm_rt.Runtime.init(proc, arg.runtime_arg.wasm) }, else => { return Error.NotImplemented; }, }; errdefer proc.runtime.deinit(); proc.open_nodes = @TypeOf(proc.open_nodes).init(proc.allocator); for (arg.fds) |fd| { var fd_alloced = try proc.allocator.create(Fd); fd_alloced.* = fd; fd_alloced.proc = proc; try proc.open_nodes.putNoClobber(fd.num, fd_alloced); errdefer proc.allocator.destroy(fd_alloced); try fd_alloced.node.open(); errdefer fd_alloced.node.close(); } return proc; } pub fn entryPoint(self_task: *task.Task) void { var process = self_task.cookie.?.as(Process); process.runtime.start(); self_task.killed = true; } pub fn deinit(self: *Process) void { self.runtime.deinit(); for (self.open_nodes.items()) |fd| { fd.value.node.close() catch @panic("Failed to close open node!"); } self.arena_allocator.deinit(); self.host.allocator.destroy(self); } pub fn deinitTrampoline(self_task: *task.Task) void { self_task.cookie.?.as(Process).deinit(); } }; pub const ProcessHost = struct { scheduler: task.Scheduler, allocator: *std.mem.Allocator, pub fn init(allocator: *std.mem.Allocator) !ProcessHost { return ProcessHost{ .scheduler = try task.Scheduler.init(allocator), .allocator = allocator }; } pub inline fn createProcess(self: *ProcessHost, options: Process.Arg) !*Process { var proc = try Process.init(self, options); var ret = try self.scheduler.spawn(options.parent_pid, Process.entryPoint, util.asCookie(proc), options.stack_size); proc.internal_task = ret; ret.on_deinit = Process.deinitTrampoline; return proc; } pub inline fn get(self: *ProcessHost, id: Process.Id) ?*Process { var my_task = self.scheduler.tasks.get(id); if (my_task == null) return null; return my_task.?.cookie.?.as(Process); } pub fn loopOnce(self: *ProcessHost) void { var sched = &self.scheduler; sched.loopOnce(); } };
kernel/process.zig
const std = @import("std"); const Module = @import("module.zig"); const Op = @import("op.zig"); const util = @import("util.zig"); const debug_buffer = std.builtin.mode == .Debug; fn sexpr(reader: anytype) Sexpr(@TypeOf(reader)) { return .{ .reader = reader, ._debug_buffer = if (debug_buffer) std.fifo.LinearFifo(u8, .{ .Static = 0x100 }).init() else {}, }; } fn Sexpr(comptime Reader: type) type { return struct { const Self = @This(); reader: Reader, current_stack: isize = 0, _peek: ?u8 = null, _debug_buffer: if (debug_buffer) std.fifo.LinearFifo(u8, .{ .Static = 0x100 }) else void, const Token = enum { OpenParen, CloseParen, Atom, }; pub const List = struct { ctx: *Self, stack_level: isize, const Next = union(enum) { Atom: []const u8, List: List }; pub fn next(self: List, allocator: *std.mem.Allocator) !?Next { if (self.isAtEnd()) return null; return switch (try self.ctx.scan()) { .OpenParen => Next{ .List = .{ .ctx = self.ctx, .stack_level = self.ctx.current_stack } }, .CloseParen => null, .Atom => Next{ .Atom = try self.loadIntoAllocator(allocator) }, }; } pub fn obtainAtom(self: List, allocator: *std.mem.Allocator) ![]u8 { return (try self.nextAtom(allocator)) orelse error.ExpectedAtomGotNull; } pub fn obtainList(self: List) !List { return (try self.nextList()) orelse error.ExpectedListGotNull; } pub fn nextAtom(self: List, allocator: *std.mem.Allocator) !?[]u8 { if (self.isAtEnd()) return null; return switch (try self.ctx.scan()) { .OpenParen => error.ExpectedAtomGotList, .CloseParen => null, .Atom => try self.loadIntoAllocator(allocator), }; } pub fn nextList(self: List) !?List { if (self.isAtEnd()) return null; return switch (try self.ctx.scan()) { .OpenParen => List{ .ctx = self.ctx, .stack_level = self.ctx.current_stack }, .CloseParen => null, .Atom => error.ExpectedListGotAtom, }; } pub fn expectEnd(self: List) !void { if (self.isAtEnd()) return; switch (try self.ctx.scan()) { .CloseParen => {}, else => return error.ExpectedEndOfList, } } fn isAtEnd(self: List) bool { switch (self.stack_level - self.ctx.current_stack) { 0 => return false, 1 => { if (debug_buffer and self.ctx._debug_buffer.peekItem(self.ctx._debug_buffer.count - 1) != ')') { self.ctx.debugDump(std.io.getStdOut().writer()) catch {}; unreachable; } return true; }, else => { if (debug_buffer) { self.ctx.debugDump(std.io.getStdOut().writer()) catch {}; std.debug.print("Unexpected list depth -- Current {} != List {}\n", .{ self.ctx.current_stack, self.stack_level }); } unreachable; }, } } fn loadIntoAllocator(self: List, allocator: *std.mem.Allocator) ![]u8 { var list = std.ArrayList(u8).init(allocator); const writer = list.writer(); const first = try self.ctx.readByte(); try writer.writeByte(first); const is_string = first == '"'; while (true) { const byte = try self.ctx.readByte(); if (is_string) { try writer.writeByte(byte); // TODO: handle escape sequences? if (byte == '"') { return list.toOwnedSlice(); } } else { switch (byte) { 0, ' ', '\t', '\n', '(', ')' => { self.ctx.putBack(byte); return list.toOwnedSlice(); }, else => try writer.writeByte(byte), } } } } }; pub fn root(self: *Self) !List { const token = try self.scan(); std.debug.assert(token == .OpenParen); return List{ .ctx = self, .stack_level = self.current_stack }; } pub fn debugDump(self: Self, writer: anytype) !void { var tmp = self._debug_buffer; const reader = tmp.reader(); var buf: [0x100]u8 = undefined; const size = try reader.read(&buf); try writer.writeAll(buf[0..size]); try writer.writeByte('\n'); } fn skipPast(self: *Self, seq: []const u8) !void { std.debug.assert(seq.len > 0); var matched: usize = 0; while (true) { const byte = try self.readByte(); if (byte == seq[matched]) { matched += 1; if (matched >= seq.len) { return; } } else { matched = 0; } } } pub fn expectEos(self: *Self) !void { const value = self.scan() catch |err| switch (err) { error.EndOfStream => return, else => return err, }; return error.ExpectEos; } fn readByte(self: *Self) !u8 { if (self._peek) |p| { self._peek = null; return p; } else { const byte = try self.reader.readByte(); if (debug_buffer) { if (self._debug_buffer.writableLength() == 0) { self._debug_buffer.discard(1); std.debug.assert(self._debug_buffer.writableLength() == 1); } self._debug_buffer.writeAssumeCapacity(&[_]u8{byte}); } return byte; } } fn peek(self: *Self) !u8 { return self._peek orelse { const byte = try self.readByte(); self._peek = byte; return byte; }; } fn putBack(self: *Self, byte: u8) void { std.debug.assert(self._peek == null); self._peek = byte; } fn scan(self: *Self) !Token { while (true) { const byte = try self.readByte(); switch (byte) { 0, ' ', '\t', '\n' => {}, '(' => { const next = self.peek() catch |err| switch (err) { error.EndOfStream => 0, else => return err, }; if (next == ';') { // Comment block -- skip to next segment try self.skipPast(";)"); } else { self.current_stack += 1; return Token.OpenParen; } }, ')' => { if (self.current_stack <= 0) { return error.UnmatchedParens; } self.current_stack -= 1; return Token.CloseParen; }, ';' => try self.skipPast("\n"), else => { self.putBack(byte); if (self.current_stack <= 0) { return error.TrailingLiteral; } return Token.Atom; }, } } } }; } test "sexpr" { var buf: [256]u8 align(32) = undefined; var ring = util.RingAllocator.init(&buf, 32); { var fbs = std.io.fixedBufferStream("(a bc 42)"); var s = sexpr(fbs.reader()); const root = try s.root(); try std.testing.expectEqualSlices(u8, "a", try root.obtainAtom(&ring.allocator)); try std.testing.expectEqualSlices(u8, "bc", try root.obtainAtom(&ring.allocator)); try std.testing.expectEqualSlices(u8, "42", try root.obtainAtom(&ring.allocator)); try root.expectEnd(); try root.expectEnd(); try root.expectEnd(); } { var fbs = std.io.fixedBufferStream("(() ())"); var s = sexpr(fbs.reader()); const root = try s.root(); const first = try root.obtainList(); try std.testing.expectEqual(@as(?@TypeOf(root), null), try first.nextList()); const second = try root.obtainList(); try std.testing.expectEqual(@as(?@TypeOf(root), null), try second.nextList()); } { var fbs = std.io.fixedBufferStream("( ( ( ())))"); var s = sexpr(fbs.reader()); const root = try s.root(); const first = try root.obtainList(); const second = try first.obtainList(); const third = try second.obtainList(); try third.expectEnd(); try second.expectEnd(); try first.expectEnd(); } { var fbs = std.io.fixedBufferStream("(block (; ; ; ;) ;; label = @1\n local.get 4)"); var s = sexpr(fbs.reader()); const root = try s.root(); try std.testing.expectEqualSlices(u8, "block", try root.obtainAtom(&ring.allocator)); try std.testing.expectEqualSlices(u8, "local.get", try root.obtainAtom(&ring.allocator)); try std.testing.expectEqualSlices(u8, "4", try root.obtainAtom(&ring.allocator)); try root.expectEnd(); } } pub fn parse(allocator: *std.mem.Allocator, reader: anytype) !Module { var result = try parseNoValidate(allocator, reader); errdefer result.deinit(); try result.postProcess(); return result; } pub fn parseNoValidate(allocator: *std.mem.Allocator, reader: anytype) !Module { var ctx = sexpr(reader); const root = try ctx.root(); errdefer if (debug_buffer) ctx.debugDump(std.io.getStdOut().writer()) catch {}; var ring_buf: [256]u8 align(32) = undefined; var ring = util.RingAllocator.init(&ring_buf, 32); if (!std.mem.eql(u8, try root.obtainAtom(&ring.allocator), "module")) { return error.ExpectModule; } var arena = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); var customs = std.ArrayList(Module.Section(.custom)).init(&arena.allocator); var types = std.ArrayList(Module.Section(.type)).init(&arena.allocator); var imports = std.ArrayList(Module.Section(.import)).init(&arena.allocator); var functions = std.ArrayList(Module.Section(.function)).init(&arena.allocator); var tables = std.ArrayList(Module.Section(.table)).init(&arena.allocator); var memories = std.ArrayList(Module.Section(.memory)).init(&arena.allocator); var globals = std.ArrayList(Module.Section(.global)).init(&arena.allocator); var exports = std.ArrayList(Module.Section(.@"export")).init(&arena.allocator); var start: ?Module.Section(.start) = null; var elements = std.ArrayList(Module.Section(.element)).init(&arena.allocator); var codes = std.ArrayList(Module.Section(.code)).init(&arena.allocator); var data = std.ArrayList(Module.Section(.data)).init(&arena.allocator); while (try root.nextList()) |command| { const swhash = util.Swhash(8); switch (swhash.match(try command.obtainAtom(&ring.allocator))) { swhash.case("memory") => { try memories.append(.{ .limits = .{ .initial = try std.fmt.parseInt(u32, try command.obtainAtom(&ring.allocator), 10), .maximum = if (try command.nextAtom(&ring.allocator)) |value| try std.fmt.parseInt(u32, value, 10) else null, }, }); // TODO: this is broken // try command.expectEnd(); }, swhash.case("type") => { while (try command.nextList()) |args| { switch (swhash.match(try args.obtainAtom(&ring.allocator))) { swhash.case("func") => { var params = std.ArrayList(Module.Type.Value).init(&arena.allocator); var result: ?Module.Type.Value = null; while (try args.nextList()) |pair| { const loc = try pair.obtainAtom(&ring.allocator); const typ: Module.Type.Value = switch (swhash.match(try pair.obtainAtom(&ring.allocator))) { swhash.case("i32") => .I32, swhash.case("i64") => .I64, swhash.case("f32") => .F32, swhash.case("f64") => .F64, else => return error.ExpectedType, }; switch (swhash.match(loc)) { swhash.case("param") => try params.append(typ), swhash.case("result") => result = typ, else => return error.ExpectedLoc, } try pair.expectEnd(); } try types.append(.{ .form = .Func, .param_types = params.items, .return_type = result, }); }, else => return error.TypeNotRecognized, } } }, swhash.case("import") => { const module = try command.obtainAtom(&arena.allocator); if (module[0] != '"') { return error.ExpectString; } const field = try command.obtainAtom(&arena.allocator); if (field[0] != '"') { return error.ExpectString; } var result = Module.Section(.import){ .module = module[1 .. module.len - 1], .field = field[1 .. field.len - 1], .kind = undefined, }; const kind_list = try command.obtainList(); switch (swhash.match(try kind_list.obtainAtom(&ring.allocator))) { swhash.case("func") => { const type_pair = try kind_list.obtainList(); if (!std.mem.eql(u8, "type", try type_pair.obtainAtom(&ring.allocator))) { @panic("TODO inline function prototypes"); } const index = try type_pair.obtainAtom(&ring.allocator); try type_pair.expectEnd(); result.kind = .{ .Function = @intToEnum(Module.Index.FuncType, try std.fmt.parseInt(u32, index, 10)), }; }, swhash.case("table") => @panic("TODO"), swhash.case("memory") => @panic("TODO"), swhash.case("global") => @panic("TODO"), else => return error.ImportNotSupported, } try kind_list.expectEnd(); try command.expectEnd(); try imports.append(result); }, swhash.case("func") => { var params = std.ArrayList(Module.Type.Value).init(&arena.allocator); var locals = std.ArrayList(Module.Type.Value).init(&arena.allocator); var result: ?Module.Type.Value = null; while (command.obtainList()) |pair| { const loc = try pair.obtainAtom(&ring.allocator); const typ: Module.Type.Value = switch (swhash.match(try pair.obtainAtom(&ring.allocator))) { swhash.case("i32") => .I32, swhash.case("i64") => .I64, swhash.case("f32") => .F32, swhash.case("f64") => .F64, else => return error.ExpectedType, }; switch (swhash.match(loc)) { swhash.case("param") => try params.append(typ), swhash.case("local") => try locals.append(typ), swhash.case("result") => result = typ, else => return error.ExpectedLoc, } try pair.expectEnd(); } else |err| switch (err) { error.ExpectedListGotNull, error.ExpectedListGotAtom => {}, else => return err, } var body = std.ArrayList(Module.Instr).init(&arena.allocator); while (try command.nextAtom(&ring.allocator)) |op_string| { for (op_string) |*letter| { if (letter.* == '.') { letter.* = '_'; } } const op = std.meta.stringToEnum(std.wasm.Opcode, op_string) orelse return error.OpNotFound; const op_meta = Op.Meta.of(op); try body.append(.{ .op = op, .pop_len = @intCast(u8, op_meta.pop.len), .arg = switch (op_meta.arg_kind) { .Void => undefined, .Type => blk: { const pair = command.obtainList() catch |err| switch (err) { error.ExpectedListGotAtom => break :blk Op.Arg{ .Type = .Void }, else => |e| return e, }; if (!std.mem.eql(u8, try pair.obtainAtom(&ring.allocator), "result")) { return error.ExpectedResult; } const typ: Op.Arg.Type = switch (swhash.match(try pair.obtainAtom(&ring.allocator))) { swhash.case("void") => .Void, swhash.case("i32") => .I32, swhash.case("i64") => .I64, swhash.case("f32") => .F32, swhash.case("f64") => .F64, else => return error.ExpectedType, }; try pair.expectEnd(); break :blk Op.Arg{ .Type = typ }; }, .U32z, .Mem, .Array => @panic("TODO"), else => blk: { const arg = try command.obtainAtom(&ring.allocator); break :blk @as(Op.Arg, switch (op_meta.arg_kind) { .Void, .Type, .U32z, .Mem, .Array => unreachable, .I32 => .{ .I32 = try std.fmt.parseInt(i32, arg, 10) }, .U32 => .{ .U32 = try std.fmt.parseInt(u32, arg, 10) }, .I64 => .{ .I64 = try std.fmt.parseInt(i64, arg, 10) }, .U64 => .{ .U64 = try std.fmt.parseInt(u64, arg, 10) }, .F32 => .{ .F32 = try std.fmt.parseFloat(f32, arg) }, .F64 => .{ .F64 = try std.fmt.parseFloat(f64, arg) }, }); }, }, }); } try functions.append(.{ .type_idx = @intToEnum(Module.Index.FuncType, @intCast(u32, types.items.len)), }); try codes.append(.{ .locals = locals.items, .body = body.items, }); try types.append(.{ .form = .Func, .param_types = params.items, .return_type = result, }); }, swhash.case("global") => { // 'skip' the id const id = (try command.next(&ring.allocator)) orelse return error.ExpectedNext; const next = blk: { // a comment was skipped so 'id' is the actual Atom/List we want if (id != .Atom or id.Atom[0] != '$') break :blk id; // if it was an id get next list/atom break :blk (try command.next(&ring.allocator)) orelse return error.ExpectedNext; }; const mutable = blk: { if (next == .Atom) break :blk false; const mut = try next.List.obtainAtom(&ring.allocator); break :blk std.mem.eql(u8, mut, "mut"); }; const valtype = blk: { const type_atom = switch (next) { .List => |list| list_blk: { const res = try list.obtainAtom(&ring.allocator); try list.expectEnd(); break :list_blk res; }, .Atom => |atom| atom, }; break :blk @as(Module.Type.Value, switch (swhash.match(type_atom)) { swhash.case("i32") => .I32, swhash.case("i64") => .I64, swhash.case("f32") => .F32, swhash.case("f64") => .F64, else => return error.ExpectedType, }); }; const init_pair = try command.obtainList(); var op_string = try init_pair.obtainAtom(&ring.allocator); for (op_string) |*letter| { if (letter.* == '.') { letter.* = '_'; } } const op = std.meta.stringToEnum(std.wasm.Opcode, op_string) orelse return error.OpNotFound; const value = try init_pair.obtainAtom(&ring.allocator); const result: Module.InitExpr = switch (op) { .i32_const => .{ .i32_const = try std.fmt.parseInt(i32, value, 10) }, .i64_const => .{ .i64_const = try std.fmt.parseInt(i64, value, 10) }, .f32_const => .{ .f32_const = try std.fmt.parseFloat(f32, value) }, .f64_const => .{ .f64_const = try std.fmt.parseFloat(f64, value) }, else => return error.UnsupportedInitExpr, }; try init_pair.expectEnd(); try globals.append(.{ .@"type" = .{ .content_type = valtype, .mutability = mutable, }, .init = result, }); }, swhash.case("export") => { const export_name = try command.obtainAtom(&arena.allocator); if (export_name[0] != '"') { return error.ExpectString; } std.debug.assert(export_name[export_name.len - 1] == '"'); const pair = try command.obtainList(); const kind = try pair.obtainAtom(&ring.allocator); const index = try pair.obtainAtom(&ring.allocator); try exports.append(.{ .field = export_name[1 .. export_name.len - 1], .kind = switch (swhash.match(kind)) { swhash.case("func") => .Function, swhash.case("table") => .Table, swhash.case("memory") => .Memory, swhash.case("global") => .Global, else => return error.ExpectExternalKind, }, .index = try std.fmt.parseInt(u32, index, 10), }); try pair.expectEnd(); }, else => return error.CommandNotRecognized, } try command.expectEnd(); } try root.expectEnd(); try ctx.expectEos(); return Module{ .custom = customs.items, .@"type" = types.items, .import = imports.items, .function = functions.items, .table = tables.items, .memory = memories.items, .global = globals.items, .@"export" = exports.items, .start = start, .element = elements.items, .code = codes.items, .data = data.items, .arena = arena, }; } test "parseNoValidate" { { var fbs = std.io.fixedBufferStream("(module)"); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); try std.testing.expectEqual(@as(usize, 0), module.memory.len); try std.testing.expectEqual(@as(usize, 0), module.function.len); try std.testing.expectEqual(@as(usize, 0), module.@"export".len); } { var fbs = std.io.fixedBufferStream("(module (memory 42))"); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); try std.testing.expectEqual(@as(usize, 1), module.memory.len); try std.testing.expectEqual(@as(u32, 42), module.memory[0].limits.initial); } { var fbs = std.io.fixedBufferStream( \\(module \\ (func (param i64) (param f32) (result i64) (local f64) \\ local.get 0 \\ drop \\ local.get 0)) ); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); try std.testing.expectEqual(@as(usize, 1), module.function.len); const func_type = module.@"type"[0]; try std.testing.expectEqual(@as(usize, 2), func_type.param_types.len); try std.testing.expectEqual(Module.Type.Value.I64, func_type.param_types[0]); try std.testing.expectEqual(Module.Type.Value.F32, func_type.param_types[1]); try std.testing.expectEqual(Module.Type.Value.I64, func_type.return_type.?); const code = module.code[0]; try std.testing.expectEqual(@as(usize, 1), code.locals.len); try std.testing.expectEqual(Module.Type.Value.F64, code.locals[0]); try std.testing.expectEqual(@as(usize, 3), code.body.len); } { var fbs = std.io.fixedBufferStream( \\(module \\ (func (param i32) (result i32) local.get 0) \\ (export "foo" (func 0))) ); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); try std.testing.expectEqual(@as(usize, 1), module.function.len); try std.testing.expectEqual(@as(usize, 1), module.@"export".len); try std.testing.expectEqualSlices(u8, "foo", module.@"export"[0].field); try std.testing.expectEqual(Module.ExternalKind.Function, module.@"export"[0].kind); try std.testing.expectEqual(@as(u32, 0), module.@"export"[0].index); } { var fbs = std.io.fixedBufferStream( \\(module \\ (type (;0;) (func (param i32) (result i32))) \\ (import "env" "fibonacci" (func (type 0)))) ); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); try std.testing.expectEqual(@as(usize, 1), module.@"type".len); try std.testing.expectEqual(Module.Type.Form.Func, module.@"type"[0].form); try std.testing.expectEqual(@as(usize, 1), module.@"type"[0].param_types.len); try std.testing.expectEqual(Module.Type.Value.I32, module.@"type"[0].param_types[0]); try std.testing.expectEqual(Module.Type.Value.I32, module.@"type"[0].return_type.?); try std.testing.expectEqual(@as(usize, 1), module.import.len); try std.testing.expectEqualSlices(u8, "env", module.import[0].module); try std.testing.expectEqualSlices(u8, "fibonacci", module.import[0].field); try std.testing.expectEqual(Module.ExternalKind.Function, module.import[0].kind); try std.testing.expectEqual(@intToEnum(Module.Index.FuncType, 0), module.import[0].kind.Function); try std.testing.expectEqual(@as(usize, 0), module.function.len); } { var fbs = std.io.fixedBufferStream( \\(module \\ (global $x (mut i32) (i32.const -12)) \\ (global $x i64 (i64.const 12)) \\ (global (;1;) i32 (i32.const 10))) ); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); try std.testing.expectEqual(@as(usize, 3), module.global.len); try std.testing.expectEqual(Module.Type.Value.I32, module.global[0].@"type".content_type); try std.testing.expectEqual(true, module.global[0].@"type".mutability); try std.testing.expectEqual(@as(i32, -12), module.global[0].init.i32_const); try std.testing.expectEqual(Module.Type.Value.I64, module.global[1].@"type".content_type); try std.testing.expectEqual(false, module.global[1].@"type".mutability); try std.testing.expectEqual(@as(i64, 12), module.global[1].init.i64_const); try std.testing.expectEqual(Module.Type.Value.I32, module.global[2].@"type".content_type); try std.testing.expectEqual(false, module.global[2].@"type".mutability); try std.testing.expectEqual(@as(i32, 10), module.global[2].init.i32_const); } } test "parse blocks" { var fbs = std.io.fixedBufferStream( \\(module \\ (func (result i32) \\ block (result i32) \\ loop \\ br 0 \\ br 1 \\ end \\ end)) ); var module = try parseNoValidate(std.testing.allocator, fbs.reader()); defer module.deinit(); const body = module.code[0].body; try std.testing.expectEqual(@as(usize, 6), body.len); try std.testing.expectEqual(std.wasm.Opcode.block, body[0].op); try std.testing.expectEqual(Op.Arg.Type.I32, body[0].arg.Type); try std.testing.expectEqual(std.wasm.Opcode.loop, body[1].op); try std.testing.expectEqual(Op.Arg.Type.Void, body[1].arg.Type); try std.testing.expectEqual(std.wasm.Opcode.br, body[2].op); try std.testing.expectEqual(@as(u32, 0), body[2].arg.U32); try std.testing.expectEqual(std.wasm.Opcode.br, body[3].op); try std.testing.expectEqual(@as(u32, 1), body[3].arg.U32); try std.testing.expectEqual(std.wasm.Opcode.end, body[4].op); try std.testing.expectEqual(std.wasm.Opcode.end, body[5].op); }
src/wat.zig
const std = @import("std"); const math = std.math; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const log = std.log.scoped(.vsr); const config = @import("config.zig"); /// The version of our Viewstamped Replication protocol in use, including customizations. /// For backwards compatibility through breaking changes (e.g. upgrading checksums/ciphers). pub const Version: u8 = 0; pub const Replica = @import("vsr/replica.zig").Replica; pub const Client = @import("vsr/client.zig").Client; pub const Clock = @import("vsr/clock.zig").Clock; pub const Journal = @import("vsr/journal.zig").Journal; /// Viewstamped Replication protocol commands: pub const Command = packed enum(u8) { reserved, ping, pong, request, prepare, prepare_ok, reply, commit, start_view_change, do_view_change, start_view, recovery, recovery_response, request_start_view, request_headers, request_prepare, headers, nack_prepare, eviction, }; /// This type exists to avoid making the Header type dependant on the state /// machine used, which would cause awkward circular type dependencies. pub const Operation = enum(u8) { /// Operations reserved by VR protocol (for all state machines): /// The value 0 is reserved to prevent a spurious zero from being interpreted as an operation. reserved = 0, /// The value 1 is reserved to initialize the cluster. init = 1, /// The value 2 is reserved to register a client session with the cluster. register = 2, /// Operations exported by the state machine (all other values are free): _, pub fn from(comptime StateMachine: type, op: StateMachine.Operation) Operation { check_state_machine_operations(StateMachine.Operation); return @intToEnum(Operation, @enumToInt(op)); } pub fn cast(self: Operation, comptime StateMachine: type) StateMachine.Operation { check_state_machine_operations(StateMachine.Operation); return @intToEnum(StateMachine.Operation, @enumToInt(self)); } fn check_state_machine_operations(comptime Op: type) void { if (!@hasField(Op, "reserved") or std.meta.fieldInfo(Op, .reserved).value != 0) { @compileError("StateMachine.Operation must have a 'reserved' field with value 0"); } if (!@hasField(Op, "init") or std.meta.fieldInfo(Op, .init).value != 1) { @compileError("StateMachine.Operation must have an 'init' field with value 1"); } if (!@hasField(Op, "register") or std.meta.fieldInfo(Op, .register).value != 2) { @compileError("StateMachine.Operation must have a 'register' field with value 2"); } } }; /// Network message and journal entry header: /// We reuse the same header for both so that prepare messages from the leader can simply be /// journalled as is by the followers without requiring any further modification. /// TODO Move from packed struct to extern struct for C ABI: pub const Header = packed struct { comptime { assert(@sizeOf(Header) == 128); } /// A checksum covering only the remainder of this header. /// This allows the header to be trusted without having to recv() or read() the associated body. /// This checksum is enough to uniquely identify a network message or journal entry. checksum: u128 = 0, /// A checksum covering only the associated body after this header. checksum_body: u128 = 0, /// A backpointer to the previous request or prepare checksum for hash chain verification. /// This provides a cryptographic guarantee for linearizability: /// 1. across our distributed log of prepares, and /// 2. across a client's requests and our replies. /// This may also be used as the initialization vector for AEAD encryption at rest, provided /// that the leader ratchets the encryption key every view change to ensure that prepares /// reordered through a view change never repeat the same IV for the same encryption key. parent: u128 = 0, /// Each client process generates a unique, random and ephemeral client ID at initialization. /// The client ID identifies connections made by the client to the cluster for the sake of /// routing messages back to the client. /// /// With the client ID in hand, the client then registers a monotonically increasing session /// number (committed through the cluster) to allow the client's session to be evicted safely /// from the client table if too many concurrent clients cause the client table to overflow. /// The monotonically increasing session number prevents duplicate client requests from being /// replayed. /// /// The problem of routing is therefore solved by the 128-bit client ID, and the problem of /// detecting whether a session has been evicted is solved by the session number. client: u128 = 0, /// The checksum of the message to which this message refers, or a unique recovery nonce. /// /// We use this cryptographic context in various ways, for example: /// /// * A `request` sets this to the client's session number. /// * A `prepare` sets this to the checksum of the client's request. /// * A `prepare_ok` sets this to the checksum of the prepare being acked. /// * A `commit` sets this to the checksum of the latest committed prepare. /// * A `request_prepare` sets this to the checksum of the prepare being requested. /// * A `nack_prepare` sets this to the checksum of the prepare being nacked. /// /// This allows for cryptographic guarantees beyond request, op, and commit numbers, which have /// low entropy and may otherwise collide in the event of any correctness bugs. context: u128 = 0, /// Each request is given a number by the client and later requests must have larger numbers /// than earlier ones. The request number is used by the replicas to avoid running requests more /// than once; it is also used by the client to discard duplicate responses to its requests. /// A client is allowed to have at most one request inflight at a time. request: u32 = 0, /// The cluster number binds intention into the header, so that a client or replica can indicate /// the cluster it believes it is speaking to, instead of accidentally talking to the wrong /// cluster (for example, staging vs production). cluster: u32, /// The cluster reconfiguration epoch number (for future use). epoch: u32 = 0, /// Every message sent from one replica to another contains the sending replica's current view. /// A `u32` allows for a minimum lifetime of 136 years at a rate of one view change per second. view: u32 = 0, /// The op number of the latest prepare that may or may not yet be committed. Uncommitted ops /// may be replaced by different ops if they do not survive through a view change. op: u64 = 0, /// The commit number of the latest committed prepare. Committed ops are immutable. commit: u64 = 0, /// The journal offset to which this message relates. This enables direct access to a prepare in /// storage, without yet having any previous prepares. All prepares are of variable size, since /// a prepare may contain any number of data structures (even if these are of fixed size). offset: u64 = 0, /// The size of the Header structure (always), plus any associated body. size: u32 = @sizeOf(Header), /// The index of the replica in the cluster configuration array that authored this message. /// This identifies only the ultimate author because messages may be forwarded amongst replicas. replica: u8 = 0, /// The Viewstamped Replication protocol command for this message. command: Command, /// The state machine operation to apply. operation: Operation = .reserved, /// The version of the protocol implementation that originated this message. version: u8 = Version, pub fn calculate_checksum(self: *const Header) u128 { const checksum_size = @sizeOf(@TypeOf(self.checksum)); assert(checksum_size == 16); var target: [32]u8 = undefined; std.crypto.hash.Blake3.hash(std.mem.asBytes(self)[checksum_size..], target[0..], .{}); return @bitCast(u128, target[0..checksum_size].*); } pub fn calculate_checksum_body(self: *const Header, body: []const u8) u128 { assert(self.size == @sizeOf(Header) + body.len); const checksum_size = @sizeOf(@TypeOf(self.checksum_body)); assert(checksum_size == 16); var target: [32]u8 = undefined; std.crypto.hash.Blake3.hash(body[0..], target[0..], .{}); return @bitCast(u128, target[0..checksum_size].*); } /// This must be called only after set_checksum_body() so that checksum_body is also covered: pub fn set_checksum(self: *Header) void { self.checksum = self.calculate_checksum(); } pub fn set_checksum_body(self: *Header, body: []const u8) void { self.checksum_body = self.calculate_checksum_body(body); } pub fn valid_checksum(self: *const Header) bool { return self.checksum == self.calculate_checksum(); } pub fn valid_checksum_body(self: *const Header, body: []const u8) bool { return self.checksum_body == self.calculate_checksum_body(body); } /// Returns null if all fields are set correctly according to the command, or else a warning. /// This does not verify that checksum is valid, and expects that this has already been done. pub fn invalid(self: *const Header) ?[]const u8 { if (self.version != Version) return "version != Version"; if (self.size < @sizeOf(Header)) return "size < @sizeOf(Header)"; if (self.epoch != 0) return "epoch != 0"; return switch (self.command) { .reserved => self.invalid_reserved(), .request => self.invalid_request(), .prepare => self.invalid_prepare(), .prepare_ok => self.invalid_prepare_ok(), else => return null, // TODO Add validators for all commands. }; } fn invalid_reserved(self: *const Header) ?[]const u8 { assert(self.command == .reserved); if (self.parent != 0) return "parent != 0"; if (self.client != 0) return "client != 0"; if (self.context != 0) return "context != 0"; if (self.request != 0) return "request != 0"; if (self.cluster != 0) return "cluster != 0"; if (self.view != 0) return "view != 0"; if (self.op != 0) return "op != 0"; if (self.commit != 0) return "commit != 0"; if (self.offset != 0) return "offset != 0"; if (self.replica != 0) return "replica != 0"; if (self.operation != .reserved) return "operation != .reserved"; return null; } fn invalid_request(self: *const Header) ?[]const u8 { assert(self.command == .request); if (self.client == 0) return "client == 0"; if (self.op != 0) return "op != 0"; if (self.commit != 0) return "commit != 0"; if (self.offset != 0) return "offset != 0"; if (self.replica != 0) return "replica != 0"; switch (self.operation) { .reserved => return "operation == .reserved", .init => return "operation == .init", .register => { // The first request a client makes must be to register with the cluster: if (self.parent != 0) return "parent != 0"; if (self.context != 0) return "context != 0"; if (self.request != 0) return "request != 0"; // The .register operation carries no payload: if (self.size != @sizeOf(Header)) return "size != @sizeOf(Header)"; }, else => { // Thereafter, the client must provide the session number in the context: // These requests should set `parent` to the `checksum` of the previous reply. if (self.context == 0) return "context == 0"; if (self.request == 0) return "request == 0"; }, } return null; } fn invalid_prepare(self: *const Header) ?[]const u8 { assert(self.command == .prepare); switch (self.operation) { .reserved => return "operation == .reserved", .init => { if (self.parent != 0) return "init: parent != 0"; if (self.client != 0) return "init: client != 0"; if (self.context != 0) return "init: context != 0"; if (self.request != 0) return "init: request != 0"; if (self.view != 0) return "init: view != 0"; if (self.op != 0) return "init: op != 0"; if (self.commit != 0) return "init: commit != 0"; if (self.offset != 0) return "init: offset != 0"; if (self.size != @sizeOf(Header)) return "init: size != @sizeOf(Header)"; if (self.replica != 0) return "init: replica != 0"; }, else => { if (self.client == 0) return "client == 0"; if (self.op == 0) return "op == 0"; if (self.op <= self.commit) return "op <= commit"; if (self.operation == .register) { // Client session numbers are replaced by the reference to the previous prepare. if (self.request != 0) return "request != 0"; } else { // Client session numbers are replaced by the reference to the previous prepare. if (self.request == 0) return "request == 0"; } }, } return null; } fn invalid_prepare_ok(self: *const Header) ?[]const u8 { assert(self.command == .prepare_ok); if (self.size != @sizeOf(Header)) return "size != @sizeOf(Header)"; switch (self.operation) { .reserved => return "operation == .reserved", .init => { if (self.parent != 0) return "init: parent != 0"; if (self.client != 0) return "init: client != 0"; if (self.context != 0) return "init: context != 0"; if (self.request != 0) return "init: request != 0"; if (self.view != 0) return "init: view != 0"; if (self.op != 0) return "init: op != 0"; if (self.commit != 0) return "init: commit != 0"; if (self.offset != 0) return "init: offset != 0"; if (self.replica != 0) return "init: replica != 0"; }, else => { if (self.client == 0) return "client == 0"; if (self.op == 0) return "op == 0"; if (self.op <= self.commit) return "op <= commit"; if (self.operation == .register) { if (self.request != 0) return "request != 0"; } else { if (self.request == 0) return "request == 0"; } }, } return null; } /// Returns whether the immediate sender is a replica or client (if this can be determined). /// Some commands such as .request or .prepare may be forwarded on to other replicas so that /// Header.replica or Header.client only identifies the ultimate origin, not the latest peer. pub fn peer_type(self: *const Header) enum { unknown, replica, client } { switch (self.command) { .reserved => unreachable, // These messages cannot always identify the peer as they may be forwarded: .request => switch (self.operation) { // However, we do not forward the first .register request sent by a client: .register => return .client, else => return .unknown, }, .prepare => return .unknown, // These messages identify the peer as either a replica or a client: // TODO Assert that pong responses from a replica do not echo the pinging client's ID. .ping, .pong => { if (self.client > 0) { assert(self.replica == 0); return .client; } else { return .replica; } }, // All other messages identify the peer as a replica: else => return .replica, } } pub fn reserved() Header { var header = Header{ .command = .reserved, .cluster = 0 }; header.set_checksum_body(&[0]u8{}); header.set_checksum(); assert(header.invalid() == null); return header; } }; pub const Timeout = struct { name: []const u8, id: u128, after: u64, attempts: u8 = 0, rtt: u64 = config.rtt_ticks, rtt_multiple: u8 = config.rtt_multiple, ticks: u64 = 0, ticking: bool = false, /// Increments the attempts counter and resets the timeout with exponential backoff and jitter. /// Allows the attempts counter to wrap from time to time. /// The overflow period is kept short to surface any related bugs sooner rather than later. /// We do not saturate the counter as this would cause round-robin retries to get stuck. pub fn backoff(self: *Timeout, prng: *std.rand.DefaultPrng) void { assert(self.ticking); self.ticks = 0; self.attempts +%= 1; log.debug("{}: {s} backing off", .{ self.id, self.name }); self.set_after_for_rtt_and_attempts(prng); } /// It's important to check that when fired() is acted on that the timeout is stopped/started, /// otherwise further ticks around the event loop may trigger a thundering herd of messages. pub fn fired(self: *Timeout) bool { if (self.ticking and self.ticks >= self.after) { log.debug("{}: {s} fired", .{ self.id, self.name }); if (self.ticks > self.after) { log.emerg("{}: {s} is firing every tick", .{ self.id, self.name }); @panic("timeout was not reset correctly"); } return true; } else { return false; } } pub fn reset(self: *Timeout) void { self.attempts = 0; self.ticks = 0; assert(self.ticking); // TODO Use self.prng to adjust for rtt and attempts. log.debug("{}: {s} reset", .{ self.id, self.name }); } /// Sets the value of `after` as a function of `rtt` and `attempts`. /// Adds exponential backoff and jitter. /// May be called only after a timeout has been stopped or reset, to prevent backward jumps. pub fn set_after_for_rtt_and_attempts(self: *Timeout, prng: *std.rand.DefaultPrng) void { // If `after` is reduced by this function to less than `ticks`, then `fired()` will panic: assert(self.ticks == 0); assert(self.rtt > 0); const after = (self.rtt * self.rtt_multiple) + exponential_backoff_with_jitter( prng, config.backoff_min_ticks, config.backoff_max_ticks, self.attempts, ); // TODO Clamp `after` to min/max tick bounds for timeout. log.debug("{}: {s} after={}..{} (rtt={} min={} max={} attempts={})", .{ self.id, self.name, self.after, after, self.rtt, config.backoff_min_ticks, config.backoff_max_ticks, self.attempts, }); self.after = after; assert(self.after > 0); } pub fn set_rtt(self: *Timeout, rtt_ticks: u64) void { assert(self.rtt > 0); assert(rtt_ticks > 0); log.debug("{}: {s} rtt={}..{}", .{ self.id, self.name, self.rtt, rtt_ticks, }); self.rtt = rtt_ticks; } pub fn start(self: *Timeout) void { self.attempts = 0; self.ticks = 0; self.ticking = true; // TODO Use self.prng to adjust for rtt and attempts. log.debug("{}: {s} started", .{ self.id, self.name }); } pub fn stop(self: *Timeout) void { self.attempts = 0; self.ticks = 0; self.ticking = false; log.debug("{}: {s} stopped", .{ self.id, self.name }); } pub fn tick(self: *Timeout) void { if (self.ticking) self.ticks += 1; } }; /// Calculates exponential backoff with jitter to prevent cascading failure due to thundering herds. pub fn exponential_backoff_with_jitter( prng: *std.rand.DefaultPrng, min: u64, max: u64, attempt: u64, ) u64 { const range = max - min; assert(range > 0); // Do not use `@truncate(u6, attempt)` since that only discards the high bits: // We want a saturating exponent here instead. const exponent = @intCast(u6, std.math.min(std.math.maxInt(u6), attempt)); // A "1" shifted left gives any power of two: // 1<<0 = 1, 1<<1 = 2, 1<<2 = 4, 1<<3 = 8 const power = std.math.shlExact(u128, 1, exponent) catch unreachable; // Do not truncate. // Calculate the capped exponential backoff component, `min(range, min * 2 ^ attempt)`: const backoff = std.math.min(range, std.math.max(1, min) * power); const jitter = prng.random.uintAtMostBiased(u64, backoff); const result = @intCast(u64, min + jitter); assert(result >= min); assert(result <= max); return result; } test "exponential_backoff_with_jitter" { const testing = std.testing; const attempts = 1000; var prng = std.rand.DefaultPrng.init(0); const max: u64 = std.math.maxInt(u64); const min = max - attempts; var attempt = max - attempts; while (attempt < max) : (attempt += 1) { const ebwj = exponential_backoff_with_jitter(&prng, min, max, attempt); try testing.expect(ebwj >= min); try testing.expect(ebwj <= max); } // Check that `backoff` is calculated correctly when min is 0 by taking `std.math.max(1, min)`. // Otherwise, the final result will always be 0. This was an actual bug we encountered. // If the PRNG ever changes, then there is a small chance that we may collide for 0, // but this is outweighed by the probability that we refactor and fail to take the max. try testing.expect(exponential_backoff_with_jitter(&prng, 0, max, 0) > 0); } /// Returns An array containing the remote or local addresses of each of the 2f + 1 replicas: /// Unlike the VRR paper, we do not sort the array but leave the order explicitly to the user. /// There are several advantages to this: /// * The operator may deploy a cluster with proximity in mind since replication follows order. /// * A replica's IP address may be changed without reconfiguration. /// This does require that the user specify the same order to all replicas. /// The caller owns the memory of the returned slice of addresses. /// TODO Unit tests. /// TODO Integrate into `src/cli.zig`. pub fn parse_addresses(allocator: *std.mem.Allocator, raw: []const u8) ![]std.net.Address { var addresses = try allocator.alloc(std.net.Address, config.replicas_max); errdefer allocator.free(addresses); var index: usize = 0; var comma_iterator = std.mem.split(raw, ","); while (comma_iterator.next()) |raw_address| : (index += 1) { if (raw_address.len == 0) return error.AddressHasTrailingComma; if (index == config.replicas_max) return error.AddressLimitExceeded; var colon_iterator = std.mem.split(raw_address, ":"); // The split iterator will always return non-null once, even if the delimiter is not found: const raw_ipv4 = colon_iterator.next().?; if (colon_iterator.next()) |raw_port| { if (colon_iterator.next() != null) return error.AddressHasMoreThanOneColon; const port = std.fmt.parseUnsigned(u16, raw_port, 10) catch |err| switch (err) { error.Overflow => return error.PortOverflow, error.InvalidCharacter => return error.PortInvalid, }; addresses[index] = std.net.Address.parseIp4(raw_ipv4, port) catch { return error.AddressInvalid; }; } else { // There was no colon in the address so there are now two cases: // 1. an IPv4 address with the default port, or // 2. a port with the default IPv4 address. // Let's try parsing as a port first: if (std.fmt.parseUnsigned(u16, raw_address, 10)) |port| { addresses[index] = std.net.Address.parseIp4(config.address, port) catch unreachable; } else |err| switch (err) { error.Overflow => return error.PortOverflow, error.InvalidCharacter => { // Something was not a digit, let's try parsing as an IPv4 instead: addresses[index] = std.net.Address.parseIp4(raw_address, config.port) catch { return error.AddressInvalid; }; }, } } } return addresses[0..index]; } pub fn sector_floor(offset: u64) u64 { const sectors = math.divFloor(u64, offset, config.sector_size) catch unreachable; return sectors * config.sector_size; } pub fn sector_ceil(offset: u64) u64 { const sectors = math.divCeil(u64, offset, config.sector_size) catch unreachable; return sectors * config.sector_size; }
src/vsr.zig
const std = @import("std"); const rand = std.rand; const fs = std.fs; const print = std.debug.print; const m = std.math; pub fn Vec3(comptime T: type) type { return struct { const Self = @This(); x: T, y: T, z: T, pub fn init(x: T, y: T, z: T) Self { return Vec3(T){ .x = x, .y = y, .z = z, }; } pub fn plus(left: *const Self, right: *const Self) Self { return Vec3(T){ .x = left.x + right.x, .y = left.y + right.y, .z = left.z + right.z, }; } pub fn minus(left: *const Self, right: *const Self) Vec3(T) { return Vec3(T){ .x = left.x - right.x, .y = left.y - right.y, .z = left.z - right.z, }; } pub fn div(vec: *const Self, scale: T) Vec3(T) { return Vec3(T){ .x = vec.x / scale, .y = vec.y / scale, .z = vec.z / scale, }; } pub fn mul(vec: *const Self, scale: T) Vec3(T) { return Vec3(T){ .x = vec.x * scale, .y = vec.y * scale, .z = vec.z * scale, }; } pub fn dot(u: *const Self, v: *const Self) T { return u.x * v.x + u.y * v.y + u.z * v.z; } pub fn length(vec: *const Self) T { return m.sqrt(m.pow(T, vec.x, 2) + m.pow(T, vec.y, 2) + m.pow(T, vec.z, 2)); } pub fn length_squared(vec: *const Self) T { return m.pow(T, vec.x, 2) + m.pow(T, vec.y, 2) + m.pow(T, vec.z, 2); } pub fn unit(vec: *const Self) Self { return vec.div(vec.length()); } }; } const Point3 = Vec3; const Colour = Point3(f32); pub fn rgb(r: f32, g: f32, b: f32) Colour { return Colour{ .x = r, .y = g, .z = b, }; } const HitRecord = struct { p: Point3(f32), normal: Vec3(f32), t: f32, front_face: bool, pub const Self = @This(); pub fn setFaceNormal(self: *Self, ray: *const Ray, out_normal: Vec3(f32)) void { self.front_face = (ray.direction.dot(&out_normal) < 0); self.normal = if (self.front_face) out_normal else out_normal.mul(-1); } }; const Sphere = struct { center: Point3(f32), radius: f32, pub fn hit(self: *const Sphere, ray: *const Ray, t_min: f32, t_max: f32) ?HitRecord { const radius = self.radius; const center = self.center; // https://stackoverflow.com/a/1986458 const oc = ray.origin.minus(&center); const r2 = radius * radius; const a = ray.direction.length_squared(); const half_b = oc.dot(&ray.direction); const c = oc.length_squared() - r2; const discriminant = half_b * half_b - a * c; if (discriminant < 0.0) { return null; } const sqrtd = m.sqrt(discriminant); var root = (-half_b - sqrtd) / a; if (root < t_min or root > t_max) { root = (-half_b + sqrtd) / a; if (root < t_min or root > t_max) { return null; } } const t = root; const p = ray.at(t); const normal = p.minus(&center).div(radius); var rec = HitRecord{ .t = t, .p = p, .normal = undefined, .front_face = undefined, }; rec.setFaceNormal(ray, normal); return rec; } }; const Ray = struct { origin: Point3(f32), direction: Vec3(f32), pub fn at(ray: Ray, t: f32) Point3(f32) { // P(t)=A+tb return ray.origin.plus(&ray.direction.mul(t)); } pub fn hitSphere(ray: Ray, radius: f32, center: Point3(f32)) f32 { // https://stackoverflow.com/a/1986458 const oc = ray.origin.minus(&center); const r2 = radius * radius; const a = ray.direction.length_squared(); const half_b = oc.dot(&ray.direction); const c = oc.length_squared() - r2; const discriminant = half_b * half_b - a * c; if (discriminant < 0.0) { return -1.0; } else { return (-half_b - m.sqrt(discriminant)) / a; } } pub fn colour(ray: Ray) Colour { const inf = m.inf(f32); const maybeHit = hitSpheres(&spheres, &ray, 0, inf); if (maybeHit) |hit| { const N = hit.normal; // map RGB to normal XYZ in interval 0-1 return N.plus(&rgb(1, 1, 1)).mul(0.5); } const unit_dir = ray.direction.unit(); const tz = 0.5 * (unit_dir.y + 1.0); const end = rgb(0.5, 0.7, 1.0); const start = rgb(0, 0, 1); return start.mul(1.0 - tz).plus(&end.mul(tz)); } }; pub fn writeColour(f: std.fs.File, col: Colour, samples_per_pixel: i32) !void { const w = f.writer(); //const scale: f32 = @divFloor(@intToFloat(f32, 1), @intToFloat(f32, samples_per_pixel)); // XXX: Change to mul to avoid divides? const c = col.div(@intToFloat(f32, samples_per_pixel)); try w.print("{} {} {}\n", .{ @floatToInt(i32, 255.999 * c.x), @floatToInt(i32, 255.999 * c.y), @floatToInt(i32, 255.999 * c.z) }); } pub fn hitSpheres(s: *const [4]Sphere, ray: *const Ray, t_min: f32, t_max: f32) ?HitRecord { var nearest = t_max; var lastHit: ?HitRecord = undefined; for (s) |sphere| { if (sphere.hit(ray, t_min, nearest)) |hit| { lastHit = hit; nearest = hit.t; } } return lastHit; } const spheres = [_]Sphere{ Sphere{ .center = Point3(f32){ .x = 0, .y = 0, .z = -3 }, .radius = 0.5, }, Sphere{ .center = Point3(f32){ .x = -0.7, .y = 0, .z = -2 }, .radius = 0.5, }, Sphere{ .center = Point3(f32){ .x = 1, .y = 0, .z = -4 }, .radius = 0.5, }, Sphere{ .center = Point3(f32){ .x = 0, .y = -100.5, .z = -1 }, .radius = 100, }, }; pub fn main() anyerror!void { const stdout_file = std.io.getStdOut(); const stdout = std.io.getStdOut().writer(); const aspect_ratio = 16.0 / 9.0; const image_width = 600; const image_height = @floatToInt(i32, image_width / aspect_ratio); const samples_per_pixel = 100; const viewport_height = 2.0; const viewport_width = aspect_ratio * viewport_height; const focal_length = 1.0; const origin = Point3(f32){ .x = 0, .y = 0, .z = 0 }; const horizontal = Vec3(f32){ .x = viewport_width, .y = 0, .z = 0 }; const vertical = Vec3(f32){ .x = 0, .y = viewport_height, .z = 0 }; const hor_2 = horizontal.mul(0.5); const ver_2 = vertical.mul(0.5); const lower_left_corner = origin.minus(&hor_2).minus(&ver_2).minus(&Vec3(f32){ .x = 0, .y = 0, .z = focal_length }); var prng = std.rand.DefaultPrng.init(0); try stdout.print("P3\n{} {}\n255\n", .{ image_width, image_height }); var j: i32 = image_height - 1; while (j >= 0) : (j -= 1) { var i: i32 = 0; while (i < image_width) : (i += 1) { var pixel_colour = rgb(0, 0, 0); const fi: f32 = @intToFloat(f32, i); const fj: f32 = @intToFloat(f32, j); var s: i32 = 0; while (s < samples_per_pixel) : (s += 1) { const rand_u = prng.random.float(f32); const rand_v = prng.random.float(f32); const u: f32 = (rand_u + fi) / @intToFloat(f32, (image_width - 1)); const v: f32 = (rand_u + fj) / @intToFloat(f32, (image_height - 1)); const target = lower_left_corner.plus(&vertical.mul(v)).plus(&horizontal.mul(u)).minus(&origin); const ray = Ray{ .origin = origin, .direction = target }; pixel_colour = pixel_colour.plus(&ray.colour()); } try writeColour(stdout_file, pixel_colour, samples_per_pixel); } } }
src/main.zig
const std = @import("std"); usingnamespace @import("interpreter.zig"); usingnamespace @import("intrinsics.zig"); usingnamespace @import("gc.zig"); usingnamespace @import("sourcelocation.zig"); pub const ExprErrors = error{ AlreadyReported, UnexpectedRightParen, ExpectedNumber, InvalidArgumentType, InvalidArgumentCount, SyntaxError, Eof }; pub const ExprType = enum { sym, num, lst, lam, mac, fun, env, err, any }; pub const ExprValue = union(ExprType) { sym: []const u8, num: f64, lst: std.ArrayList(*Expr), lam: std.ArrayList(*Expr), mac: std.ArrayList(*Expr), fun: fn (evaluator: *Interpreter, env: *Env, []const *Expr) anyerror!*Expr, env: *Env, err: *Expr, any: usize, }; /// A Bio expression with a value and an optional environment (lambda expressions /// must know in which environment they were defined) pub const Expr = struct { val: ExprValue, env: ?*Env = null, src: SourceLocation = .{}, /// Create a new expression with an undefined value pub fn create(register_with_gc: bool) !*Expr { var self = try allocator.create(Expr); if (register_with_gc) { gc.inc(); try gc.registered_expr.append(self); } self.* = Expr{ .val = undefined }; self.src.file = SourceLocation.current().file; self.src.line = SourceLocation.current().line; self.src.col = SourceLocation.current().col; return self; } /// Called by the GC to clean up expression resources. Note that symbols /// are deallocated by sweeping the internalized string map. pub fn deinit(self: *Expr) void { if (self.val == ExprType.lst) { self.val.lst.deinit(); } else if (self.val == ExprType.lam) { self.val.lam.deinit(); } else if (self.val == ExprType.mac) { self.val.mac.deinit(); } } /// Returns an owned string representation of this expression pub fn toStringAlloc(self: *Expr) anyerror![]u8 { switch (self.val) { ExprValue.sym => return try std.fmt.allocPrint(allocator, "{s}", .{self.val.sym}), ExprValue.num => return try std.fmt.allocPrint(allocator, "{d}", .{self.val.num}), ExprValue.lam => return try std.fmt.allocPrint(allocator, "<lambda>", .{}), ExprValue.mac => return try std.fmt.allocPrint(allocator, "<macro>", .{}), ExprValue.fun => return try std.fmt.allocPrint(allocator, "<function>", .{}), ExprValue.env => return try std.fmt.allocPrint(allocator, "<env>", .{}), ExprValue.any => return try std.fmt.allocPrint(allocator, "<any>", .{}), ExprValue.err => |err_expr| { const err_str = try err_expr.toStringAlloc(); defer allocator.free(err_str); return try std.fmt.allocPrint(allocator, "{s}", .{err_str}); }, ExprValue.lst => |lst| { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); var bufWriter = buf.writer(); try bufWriter.writeAll("("); for (lst.items) |item, index| { const itemBuf = try item.toStringAlloc(); defer allocator.free(itemBuf); try bufWriter.writeAll(itemBuf); if (index + 1 < lst.items.len) { try bufWriter.writeAll(" "); } } try bufWriter.writeAll(")"); return buf.toOwnedSlice(); }, } } /// Prints the expression to stdout pub fn print(self: *Expr) anyerror!void { const str = try self.toStringAlloc(); defer allocator.free(str); try std.io.getStdOut().writer().print("{s}", .{str}); } }; /// Environment for variable bindings. Instances are named to get friendly debugging output. pub const Env = struct { const hash_util = struct { pub fn hash(_: hash_util, key: *Expr) u32 { std.debug.assert(key.val == ExprType.sym); return @truncate(u32, std.hash.Wyhash.hash(0, key.val.sym)); } pub fn eql(_: hash_util, first: *Expr, second: *Expr) bool { std.debug.assert(first.val == ExprType.sym and second.val == ExprType.sym); return std.mem.eql(u8, first.val.sym, second.val.sym); } }; map: std.ArrayHashMap(*Expr, *Expr, hash_util, true), parent: ?*Env = null, name: []const u8, pub fn deinit(self: *Env) void { self.map.deinit(); } /// Put symbol/value by first interning the symbol pub fn put(self: *Env, key: []const u8, val: *Expr) !void { const binding_expr = try makeAtomByDuplicating(key); try self.putWithSymbol(binding_expr, val); } /// Put symbol/value pub fn putWithSymbol(self: *Env, variable_name: *Expr, val: *Expr) anyerror!void { try self.map.put(variable_name, val); } /// Look up a variable in this or a parent environment pub fn lookup(self: *Env, sym: []const u8, recursive: bool) ?*Expr { var lookupSym = Expr{ .val = ExprValue{ .sym = sym } }; if (self.map.get(&lookupSym)) |val| { return val; } else if (self.parent) |parent| { return if (recursive) parent.lookup(sym, recursive) else null; } else { return null; } } /// Recursively search for the binding, replace it if found. /// If the new value is null, the binding is removed instead. pub fn replace(self: *Env, var_name: *Expr, val: ?*Expr) *Expr { if (self.map.get(var_name)) |_| { if (val) |value| { self.putWithSymbol(var_name, value) catch return &expr_atom_nil; return value; } else { _ = self.map.swapRemove(var_name); } } else if (self.parent) |parent| { return parent.replace(var_name, val); } return &expr_atom_nil; } }; /// Make an environment expression pub fn makeEnv(parent: ?*Env, name: []const u8) !*Env { var environment = try allocator.create(Env); environment.parent = parent; environment.map = @TypeOf(environment.map).init(allocator); environment.name = name; try gc.registered_envs.append(environment); return environment; } /// Duplicates the input and return an atom pub fn makeAtomByDuplicating(literal: []const u8) anyerror!*Expr { return try makeAtomImplementation(literal, false); } /// Takes ownership of the input and returns an atom pub fn makeAtomAndTakeOwnership(literal: []const u8) anyerror!*Expr { return try makeAtomImplementation(literal, true); } /// Make and return a potentially interned atom (symbol or number) fn makeAtomImplementation(literal: []const u8, take_ownership: bool) anyerror!*Expr { const intrinsic_atoms: []const *Expr = &.{ &expr_atom_quasi_quote, &expr_atom_quote, &expr_atom_unquote, &expr_atom_unquote_splicing, &expr_atom_list, &expr_atom_if, &expr_atom_cond, &expr_atom_begin, &expr_atom_nil, &expr_atom_rest, &expr_atom_true, &expr_atom_false, &expr_atom_last_eval, &expr_atom_last_try_err, &expr_atom_last_try_value, }; // Lazy initialization of the interned intrinsics map if (interned_intrinsics.count() == 0) { for (intrinsic_atoms) |atom| { try interned_intrinsics.put(allocator, atom.val.sym, atom); } } return interned_intrinsics.get(literal) orelse { // Zig's parseFloat is too lenient and accepts input like "." and "--" // For Bio, we require at least one digit. if (std.mem.indexOfAny(u8, literal, "0123456789")) |_| { if (std.fmt.parseFloat(f64, literal)) |num| { defer { if (take_ownership) { allocator.free(literal); } } const internalizable = @floor(num) == num and !std.math.isInf(num) and num > -1024 and num < 1024; if (internalizable) { if (interned_nums.get(@floatToInt(i16, num))) |expr| { return expr; } } var expr = try Expr.create(false); expr.val = ExprValue{ .num = num }; if (internalizable) { try interned_nums.put(allocator, @floatToInt(i16, num), expr); } else { try gc.registered_expr.append(expr); } return expr; } else |_| {} } return try makeAtomLiteral(literal, take_ownership); }; } /// Make an interned literal atom pub fn makeAtomLiteral(literal: []const u8, take_ownership: bool) anyerror!*Expr { var sym = sym_blk: { const maybe_entry = interned_syms.getEntry(literal); if (maybe_entry) |entry| { // There's already an entry, free the input if we're supposed to take ownership if (take_ownership) { allocator.free(literal); } break :sym_blk entry.key_ptr.*; } else { const res = if (take_ownership) literal else try allocator.dupe(u8, literal); try interned_syms.put(allocator, res, {}); break :sym_blk res; } }; var expr = try Expr.create(true); expr.val = ExprValue{ .sym = sym }; return expr; } /// Make a list expression pub fn makeListExpr(initial_expressions: ?[]const *Expr) !*Expr { var expr = try Expr.create(true); expr.val = ExprValue{ .lst = std.ArrayList(*Expr).init(allocator) }; if (initial_expressions) |expressions| { for (expressions) |e| { try expr.val.lst.append(e); } } return expr; } /// Make a lambda expression pub fn makeLambdaExpr(env: *Env) !*Expr { var expr = try Expr.create(true); // This is a crucial detail: we're recording the environment that existed at the // time of lambda definition. This will be the parent environment whenever we // are invoking the lambda in Interpreter#eval expr.env = env; expr.val = ExprValue{ .lam = std.ArrayList(*Expr).init(allocator) }; return expr; } /// Make a macro expression pub fn makeMacroExpr() !*Expr { var expr = try Expr.create(true); expr.val = ExprValue{ .mac = std.ArrayList(*Expr).init(allocator) }; return expr; } /// Make a numeric expression pub fn makeNumExpr(num: f64) !*Expr { var expr = try Expr.create(true); expr.val = ExprValue{ .num = num }; return expr; } /// Make an error expression pub fn makeError(expr: *Expr) !*Expr { var error_expr = try Expr.create(true); error_expr.val = ExprValue{ .err = expr }; return error_expr; }
src/ast.zig
const warn = std.debug.warn; const time = std.os.time; const std = @import("std"); const date = @import("gregorianDate.zig"); fn today() date.Date { // Get UTC and manually adjust to Pacific Daylight Time // (For demonstration only -- This is not the correct way to convert to civil time!) const now = time.timestamp() - u64(7 * 3600); return date.FromCode(@truncate(i32, @intCast(i64, @divFloor(now, u64(86400))))); } fn nextElectionDay(t: date.Date) date.Date { var eYear = t.year(); if (@rem(eYear, 2) != 0) { eYear += 1; } const e = date.FromCardinal(date.Nth.First, date.Weekday.Monday, eYear, 11) catch date.max; var ec = e.code(); if (ec + 1 < t.code()) { // Election day this year has passed. The next election is 2 years away. const e2 = date.FromCardinal(date.Nth.First, date.Weekday.Monday, eYear + 2, 11) catch date.max; ec = e2.code(); } // Election day in the U. S. is always on the day *after* the first Monday of November. return date.FromCode(ec + 1); } pub fn main() void { // Note the range error below: var my_date = date.FromYmd(2019, 3, 130) catch date.min; warn("\nGregorianDate\ntype: {}\nsize: {}\nvalue: {}-{}-{}\n", @typeName(@typeOf(my_date)), @intCast(u32, @sizeOf(@typeOf(my_date))), my_date.year(), my_date.month(), my_date.day()); var my_date2 = date.FromYmd(2019, 3, 30) catch date.min; warn("\nmy_date2: {}-{}-{}\n", my_date2.year(), @tagName(my_date2.monthEnum()), my_date2.day()); // compare dates without normalizing var cmp_res = my_date.compare(my_date2); warn("\ncmp_res: {}\n", cmp_res); // find the weekday for a given date var code: i32 = my_date2.code(); warn("\nmy_date2.code() = {}\nweekday = {}\n", code, @tagName(date.weekday(code))); // what is 90 days after my_date2? var my_date3 = date.FromCode(code + 90); warn("\nmy_date2 + 90: {}-{}-{}\n", my_date3.year(), my_date3.month(), my_date3.day()); // Today const t = today(); const tc = t.code(); warn("Today: {}-{}-{}\n", t.year(), t.month(), t.day()); const eday = nextElectionDay(t); warn("Election day is {}-{}-{}, {} days from today.\n", eday.year(), eday.month(), eday.day(), eday.code() - tc); // Convert a date code to Julian Date const unix_to_julian_bias: f64 = 2440587.5; warn("Today is JD {}.\n", unix_to_julian_bias + @intToFloat(f64, tc)); // Convert a date code to _Rata Die_ const rata_die_offset: i32 = 719163; warn("Today is rata die {}.\n", rata_die_offset + tc); // Convert a date code to Unix time (seconds since 1970-1-1) if (tc >= 0) { warn("Today began {} seconds after 1970-1-1.\n", @intCast(u64, tc) * u64(86400)); } }
src/example.zig
const std = @import("std"); const testing = std.testing; const Vector2 = @import("zalgebra").Vector2; const za = @import("zalgebra"); pub const RectInt = Rect(i32); pub const RectFloat = Rect(f32); pub fn Rect(comptime T: type) type { return struct { pub const Vec2 = Vector2(T); const Self = @This(); lower_bound: Vec2, upper_bound: Vec2, /// Contruct Rectangle form given 2 Vector2 pub fn new(lower_bound: Vec2, upper_bound: Vec2) Self { return .{ .lower_bound = lower_bound, .upper_bound = upper_bound, }; } pub fn newFromCenter(m_pos: Vec2, h_size: Vec2) Self { return .{ .lower_bound = m_pos.sub(h_size), .upper_bound = m_pos.add(h_size), }; } pub fn newRectInt(m_pos: Vec2, h_size: Vec2, screen: Vec2, screen_size: Vec2) RectInt { return .{ .lower_bound = .{ .x = @floatToInt(i32, m_pos.x - screen.x + screen_size.x - h_size.x), .y = @floatToInt(i32, screen.y + screen_size.y - m_pos.y - h_size.y), }, .upper_bound = .{ .x = @floatToInt(i32, h_size.x * 2), .y = @floatToInt(i32, h_size.y * 2), }, }; } pub fn extent(self: Self, size: Vec2) Self { return .{ .lower_bound = self.lower_bound.sub(size), .upper_bound = self.upper_bound.add(size), }; } pub fn testOverlap(a: Self, b: Self) bool { const d1 = Vec2.sub(b.lower_bound, a.upper_bound); const d2 = Vec2.sub(a.lower_bound, b.upper_bound); if (d1.x > 0 or d1.y > 0) return false; if (d2.x > 0 or d2.y > 0) return false; return true; } /// Contruct new aabb with 2 given aabb pub fn combine(a: Self, b: Self) Self { return Self.new( Vec2.min(a.lower_bound, b.lower_bound), Vec2.max(a.upper_bound, b.upper_bound), ); } pub fn contains(a: Self, b: Self) bool { var result = true; result = result and a.lower_bound.x <= b.lower_bound.x; result = result and a.lower_bound.y <= b.lower_bound.y; result = result and b.upper_bound.x <= a.upper_bound.x; result = result and b.upper_bound.y <= a.upper_bound.y; return result; } pub fn getPerimeter(self: Self) T { const wx = self.upper_bound.x - self.lower_bound.x; const wy = self.upper_bound.y - self.lower_bound.y; return 2 * (wx + wy); } pub fn bottomLeft(self: Self) Vec2 { return self.lower_bound; } pub fn topRight(self: Self) Vec2 { return self.upper_bound; } pub fn bottomRight(self: Self) Vec2 { return Vec2.new(self.upper_bound.x, self.lower_bound.y); } pub fn topLeft(self: Self) Vec2 { return Vec2.new(self.lower_bound.x, self.upper_bound.y); } pub fn zero() Self { return Self.new(Vec2.zero(), Vec2.zero()); } }; } test "basic" { const Vec2 = RectInt.Vec2; const v1 = Vec2.new(1, 1); const v2 = Vec2.new(3, 3); const v3 = Vec2.new(2, 2); const v4 = Vec2.new(4, 4); const a1 = RectInt.new(v1, v2); const a2 = RectInt.new(v3, v4); try testing.expect(a1.testOverlap(a2)); try testing.expect(a1.getPerimeter() == 8); const a3 = a1.combine(a2); try testing.expect(a3.lower_bound.eql(v1) and a3.upper_bound.eql(v4)); }
src/physic/rect.zig
const vk = @import("../../../vk.zig"); const std = @import("std"); const printError = @import("../../../application/print_error.zig").printError; const RGResource = @import("../render_graph_resource.zig").RGResource; const RenderGraph = @import("../render_graph.zig").RenderGraph; const Texture = @import("texture.zig").Texture; pub const ViewportTexture = struct { rg_resource: RGResource, allocator: std.mem.Allocator, textures: []Texture, width: u32, height: u32, // Used for resizing new_width: u32, new_height: u32, image_format: vk.Format, usage: vk.ImageUsageFlags, image_layout: vk.ImageLayout, pub fn init(self: *ViewportTexture, name: []const u8, in_flight: u32, width: u32, height: u32, image_format: vk.Format, allocator: std.mem.Allocator) void { self.width = width; self.height = height; self.image_format = image_format; self.rg_resource.init(name, allocator); self.allocator = allocator; self.textures = allocator.alloc(Texture, in_flight) catch unreachable; self.usage = .{ .sampled_bit = true, .color_attachment_bit = true, .transfer_dst_bit = true, }; self.image_layout = .shader_read_only_optimal; } pub fn deinit(self: *ViewportTexture) void { self.allocator.free(self.textures); } pub fn alloc(self: *ViewportTexture) void { for (self.textures) |*tex| { tex.init(self.rg_resource.name, self.width, self.height, self.image_format, self.allocator); tex.image_create_info.usage = self.usage; tex.image_layout = self.image_layout; tex.alloc(); } } pub fn destroy(self: *ViewportTexture) void { for (self.textures) |*tex| tex.destroy(); } pub fn resize(self: *ViewportTexture, rg: *RenderGraph, new_width: u32, new_height: u32) void { self.new_width = new_width; self.new_height = new_height; rg.changeResourceBetweenFrames(&self.rg_resource, resizeBetweenFrames); } fn resizeBetweenFrames(res: *RGResource) void { const self: *ViewportTexture = @fieldParentPtr(ViewportTexture, "rg_resource", res); self.width = self.new_width; self.height = self.new_height; self.destroy(); self.alloc(); } };
src/renderer/render_graph/resources/viewport_texture.zig
const std = @import("std"); const states = @import("state.zig"); const build_map = @import("build_map.zig"); const searches = @import("search.zig"); const htmlgen = @import("htmlgen.zig"); const State = states.State; const OutError = std.fs.File.ReadError; const InError = std.fs.File.WriteError; fn loadState(state_path: []const u8, state: *State) !void { var path = try std.fs.path.resolve( state.allocator, &[_][]const u8{state_path}, ); var state_file = try std.fs.cwd().openFile(path, .{ .read = true, .write = false }); defer state_file.close(); var in = state_file.inStream(); var deserial = std.io.Deserializer(.Big, .Bit, @TypeOf(in)).init(in); try deserial.deserializeInto(state); } fn doSearch(state: *State, search_term: []u8) !void { try searches.doSearch(state, search_term); } fn doBuild(state_path: []const u8, state: *State, zig_std_path: []u8) !void { try build_map.build(state, "std", zig_std_path); std.debug.warn("build finished, {} total defs\n", .{state.map.size}); const resolved_path = try std.fs.path.resolve(state.allocator, &[_][]const u8{state_path}); var state_file = try (std.fs.cwd().openFile(resolved_path, .{ .write = true, }) catch |err| blk: { if (err != error.FileNotFound) break :blk err; break :blk std.fs.cwd().createFile(resolved_path, .{}); }); defer state_file.close(); var out = state_file.outStream(); var serial = std.io.Serializer(.Big, .Bit, @TypeOf(out)).init(out); try state.serialize(&serial); std.debug.warn("serialization OK\n", .{}); } pub fn main() anyerror!void { var allocator = std.heap.direct_allocator; var state = State.init(allocator); defer state.deinit(); var args_it = std.process.args(); if (!args_it.skip()) @panic("expected self arg"); const state_path = try (args_it.next(allocator) orelse @panic("expected state.bin file path")); const action = try (args_it.next(allocator) orelse @panic("expected action arg")); if (std.mem.eql(u8, action, "build")) { const zig_std_path = try (args_it.next(allocator) orelse @panic("expected zig stdlib path arg")); try doBuild(state_path, &state, zig_std_path); } else if (std.mem.eql(u8, action, "search")) { const search_term = try (args_it.next(allocator) orelse @panic("expected search term arg")); try loadState(state_path, &state); try doSearch(&state, search_term); } else if (std.mem.eql(u8, action, "htmlgen")) { const out_path = try (args_it.next(allocator) orelse @panic("expected out path arg")); try loadState(state_path, &state); try htmlgen.genHtml(&state, out_path); } else { @panic("invalid action"); } }
src/main.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const process = std.process; const Allocator = std.mem.Allocator; const util = @import("util.zig"); const ResponseEntry = struct { title: []const u8, name: []const u8, }; const Response = struct { examples: []ResponseEntry, }; pub fn main() !void { const stderr = std.io.getStdErr().writer(); const stdout = std.io.getStdOut().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; defer _ = gpa.deinit(); const exe_path = try util.resolveExePath(allocator); defer allocator.free(exe_path); // try stderr.print("file.cgi: exe_path={}\n", .{exe_path}); const home_path = try util.resolveHomePath(allocator, exe_path); defer allocator.free(home_path); // try stderr.print("file.cgi: home_path={}\n", .{home_path}); const tmp_path = try util.resolveTmpPath(allocator, exe_path); defer allocator.free(tmp_path); // try stderr.print("file.cgi: tmp_path={}\n", .{tmp_path}); std.fs.cwd().access(tmp_path, .{ .read = true }) catch |err| { try stdout.print("Status: 400 Bad Request\n\n", .{}); return; }; const src_path = try util.resolveSrcPath(allocator, exe_path); defer allocator.free(src_path); // try stderr.print("file.cgi: src_path={}\n", .{src_path}); std.fs.cwd().access(src_path, .{ .read = true }) catch |err| { try stdout.print("Status: 400 Bad Request\n\n", .{}); return; }; var env_map = try process.getEnvMap(allocator); defer env_map.deinit(); // var env_it = env_map.iterator(); // while (env_it.next()) |entry| { // try stderr.print("file.cgi: key={}, value={}\n", .{ entry.key, entry.value }); // } var remote_ip = env_map.get("HTTP_X_REAL_IP"); if (remote_ip == null) { remote_ip = env_map.get("REMOTE_ADDR"); if (remote_ip == null) { remote_ip = "?"; } } var opt_example_name: ?[]const u8 = null; const opt_query_string = env_map.get("QUERY_STRING"); try stderr.print("file.cgi: opt_query_string={}\n", .{opt_query_string}); if (opt_query_string) |query_string| { const prefix = "name="; if (std.mem.startsWith(u8, query_string, prefix)) { var tmp = query_string[prefix.len..]; if (std.mem.indexOf(u8, tmp, "&") == null) { opt_example_name = tmp; } else { try stdout.print("Status: 400 Bad Request\n\n", .{}); return; } } } try stderr.print("file.cgi: remote_ip={}, example_name={}\n", .{remote_ip.?, opt_example_name}); if (opt_example_name) |example_name| { const example_path = try util.resolveExamplePath(allocator, exe_path, example_name); defer allocator.free(example_path); try stderr.print("file.cgi: remote_ip={}, example_path={}\n", .{remote_ip.?, example_path}); std.fs.cwd().access(example_path, .{ .read = true }) catch |err| { try stdout.print("Status: 400 Bad Request\n\n", .{}); return; }; var string2 = std.ArrayList(u8).init(allocator); defer string2.deinit(); var example_dir = try std.fs.cwd().openDir(example_path, .{ .iterate = true }); defer example_dir.close(); var it = example_dir.iterate(); while (try it.next()) |entry| { if (entry.kind == .File) { const file_name = entry.name; // try stderr.print("file.cgi: file_name={}\n", .{file_name}); try string2.appendSlice("//@file_name="); try string2.appendSlice(file_name); try string2.appendSlice("\n"); const file = try example_dir.openFile(file_name, .{ .read = true }); defer file.close(); var buffer: [16 * 1024]u8 = undefined; const bytes_read = try file.readAll(&buffer); try string2.appendSlice(buffer[0..bytes_read]); } } try stdout.print("Content-Type: text/plain\n", .{}); try stdout.print("Content-Length: {}\n", .{string2.items.len}); try stdout.print("\n", .{}); try stdout.print("{}\n", .{string2.items}); } else { var exampleList = std.ArrayList(ResponseEntry).init(allocator); defer exampleList.deinit(); const src_dir = try std.fs.cwd().openDir(src_path, .{ .iterate = true }); var it = src_dir.iterate(); while (try it.next()) |entry| { if (entry.kind == .Directory) { const title = try util.readTitleFromExample(allocator, src_path, entry.name); // free after json is serialized!!! // try stderr.print("file.cgi: name={}\n", .{entry.name}); // try stderr.print("file.cgi: title={}\n", .{title}); const tmp = ResponseEntry{ .title = title, .name = entry.name }; try exampleList.append(tmp); } } const examples = exampleList.toOwnedSlice(); std.sort.sort(ResponseEntry, examples, {}, ascendingName); const response = &Response{ .examples = examples }; defer allocator.free(response.examples); var string2 = std.ArrayList(u8).init(allocator); defer string2.deinit(); try std.json.stringify(response, .{}, string2.writer()); // must free title strings allocated in while loop for (response.examples) |example| { allocator.free(example.title); } // write http response try stdout.print("Content-Type: application/json\n", .{}); try stdout.print("Content-Length: {}\n", .{string2.items.len}); try stdout.print("\n", .{}); try stdout.print("{}\n", .{string2.items}); } } fn ascendingName(context: void, a: ResponseEntry, b: ResponseEntry) bool { return std.mem.lessThan(u8, a.name, b.name); }
src/file.zig
const std = @import("std"); test "example" { const input = @embedFile("13_example.txt"); const result = try run(input, 1); try std.testing.expectEqual(@as(usize, 17), result); } pub fn main() !void { const input = @embedFile("13.txt"); const result = try run(input, 1); std.debug.print("{}\n", .{result}); } const Paper = struct { dots: Set, height: usize, width: usize, const size = 1500; const Set = std.StaticBitSet(size * size); fn init() Paper { return Paper{ .dots = Set.initEmpty(), .height = 0, .width = 0, }; } fn mark(self: *Paper, x: usize, y: usize) void { self.dots.set(y * size + x); self.width = @maximum(self.width, x + 1); self.height = @maximum(self.height, y + 1); } fn fold(self: *Paper, axis: u8, n: usize) !void { switch (axis) { 'x' => { var dx: usize = 1; while (dx <= n) : (dx += 1) { const x = n + dx; const mirror_x = n - dx; var y: usize = 0; while (y < self.height) : (y += 1) { if (self.dots.isSet(y * size + x)) { self.dots.set(y * size + mirror_x); } } } self.width = n; }, 'y' => { var dy: usize = 1; while (dy <= n) : (dy += 1) { const y = n + dy; const mirror_y = n - dy; var x: usize = 0; while (x < self.width) : (x += 1) { if (self.dots.isSet(y * size + x)) { self.dots.set(mirror_y * size + x); } } } self.height = n; }, else => return error.InvalidAxisError, } } fn countVisibleDots(self: Paper) usize { var count: usize = 0; var y: usize = 0; while (y < self.height) : (y += 1) { var x: usize = 0; while (x < self.width) : (x += 1) { if (self.dots.isSet(y * size + x)) count += 1; } } return count; } }; fn run(input: []const u8, folds: usize) !usize { var paper = Paper.init(); var lines = std.mem.split(u8, input, "\n"); while (lines.next()) |line| { if (line.len == 0) break; const comma_idx = std.mem.indexOfScalar(u8, line, ',') orelse return error.ParseError; const x = try std.fmt.parseInt(usize, line[0..comma_idx], 10); const y = try std.fmt.parseInt(usize, line[comma_idx + 1 ..], 10); paper.mark(x, y); } var i: usize = 0; while (i < folds) : (i += 1) { if (lines.next()) |line| { const equal_idx = std.mem.indexOfScalar(u8, line, '=') orelse return error.ParseError; const axis = line[equal_idx - 1]; const n = try std.fmt.parseInt(usize, line[equal_idx + 1 ..], 10); try paper.fold(axis, n); } else return error.ParseError; } return paper.countVisibleDots(); }
shritesh+zig/13a.zig
const std = @import("std"); const win = std.os.windows; const ascii = std.ascii; const fmt = std.fmt; const heap = std.heap; const fs = std.fs; const mem = std.mem; const process = std.process; export fn handlerRoutine(dwCtrlType: win.DWORD) callconv(win.WINAPI) win.BOOL { return switch (dwCtrlType) { win.CTRL_C_EVENT => win.TRUE, win.CTRL_BREAK_EVENT => win.TRUE, win.CTRL_CLOSE_EVENT => win.TRUE, win.CTRL_LOGOFF_EVENT => win.TRUE, win.CTRL_SHUTDOWN_EVENT => win.TRUE, else => win.FALSE, }; } // removeSuffix removes the suffix from the slice fn removeSuffix(comptime T: type, slice: []const T, suffix: []const T) []const T { if (mem.endsWith(u8, slice, suffix)) { return slice[0 .. slice.len - suffix.len]; } else { return slice; } } // pathWithExtension returns the path with the specified extension fn pathWithExtension(allocator: *mem.Allocator, path: []const u8, extension: []const u8) ![]const u8 { const path_extension = fs.path.extension(path); const path_no_extension = removeSuffix(u8, path, path_extension); return fmt.allocPrint(allocator, "{s}.{s}", .{ path_no_extension, extension }); } // trimSpaces removes spaces from the beginning and end of a string fn trimSpaces(slice: []const u8) []const u8 { return mem.trim(u8, slice, &ascii.spaces); } pub fn main() anyerror!void { var arena = heap.ArenaAllocator.init(heap.page_allocator); defer arena.deinit(); const ally = &arena.allocator; // Collect arguments const args = try process.argsAlloc(ally); // Shim filename var program_path = try fs.selfExePathAlloc(ally); var shim_path = pathWithExtension(ally, program_path, "shim") catch { std.log.crit("Cannot make out shim path.", .{}); return; }; // Place to store the shim file contents var cfg = std.BufMap.init(ally); // Open shim file for reading var shim_file = fs.openFileAbsolute(shim_path, .{}) catch { std.log.crit("Unable to open shim file. ({s})", .{shim_path}); return; }; defer shim_file.close(); // Go through the shim file and collect key-value pairs var reader = shim_file.reader(); var line_buf: [1024]u8 = undefined; while (try reader.readUntilDelimiterOrEof(&line_buf, '\n')) |line| { // The lines should look like this: `key = value` // Find index of equals, if it doesn't exist we just skip this line const equals_index = mem.indexOfScalar(u8, line, '=') orelse continue; const key = trimSpaces(line[0..equals_index]); const value = trimSpaces(line[equals_index + 1 .. line.len]); try cfg.put(key, value); } // Arguments sent to the child process var cmd_args = std.ArrayList([]const u8).init(ally); // Add the program name from shim file if (cfg.get("path")) |cfg_path| { try cmd_args.append(cfg_path); } else { std.log.crit("`path` not found in shim file", .{}); return; } // Pass all arguments from our process except program name try cmd_args.appendSlice(args[1..]); // Pass all arguments from shim file if (cfg.get("args")) |cfg_args| { var it = mem.split(cfg_args, " "); while (it.next()) |cfg_arg| { try cmd_args.append(cfg_arg); } } try win.SetConsoleCtrlHandler(handlerRoutine, true); // Spawn child process var child = try std.ChildProcess.init(cmd_args.items, ally); _ = try child.spawnAndWait(); }
src/main.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const assert = std.debug.assert; const BigIntConst = std.math.big.int.Const; const BigIntMutable = std.math.big.int.Mutable; const Type = @import("type.zig").Type; const Value = @import("value.zig").Value; const TypedValue = @import("TypedValue.zig"); const ir = @import("ir.zig"); const IrModule = @import("Module.zig"); /// This struct is relevent only for the ZIR Module text format. It is not used for /// semantic analysis of Zig source code. pub const Decl = struct { name: []const u8, /// Hash of slice into the source of the part after the = and before the next instruction. contents_hash: std.zig.SrcHash, inst: *Inst, }; /// These are instructions that correspond to the ZIR text format. See `ir.Inst` for /// in-memory, analyzed instructions with types and values. pub const Inst = struct { tag: Tag, /// Byte offset into the source. src: usize, /// Pre-allocated field for mapping ZIR text instructions to post-analysis instructions. analyzed_inst: ?*ir.Inst = null, /// These names are used directly as the instruction names in the text format. pub const Tag = enum { /// Arithmetic addition, asserts no integer overflow. add, /// Twos complement wrapping integer addition. addwrap, /// Allocates stack local memory. Its lifetime ends when the block ends that contains /// this instruction. The operand is the type of the allocated object. alloc, /// Same as `alloc` except the type is inferred. alloc_inferred, /// Create an `anyframe->T`. anyframe_type, /// Array concatenation. `a ++ b` array_cat, /// Array multiplication `a ** b` array_mul, /// Create an array type array_type, /// Create an array type with sentinel array_type_sentinel, /// Function parameter value. These must be first in a function's main block, /// in respective order with the parameters. arg, /// Type coercion. as, /// Inline assembly. @"asm", /// Bitwise AND. `&` bitand, /// TODO delete this instruction, it has no purpose. bitcast, /// An arbitrary typed pointer is pointer-casted to a new Pointer. /// The destination type is given by LHS. The cast is to be evaluated /// as if it were a bit-cast operation from the operand pointer element type to the /// provided destination type. bitcast_ref, /// A typed result location pointer is bitcasted to a new result location pointer. /// The new result location pointer has an inferred type. bitcast_result_ptr, /// Bitwise NOT. `~` bitnot, /// Bitwise OR. `|` bitor, /// A labeled block of code, which can return a value. block, /// A block of code, which can return a value. There are no instructions that break out of /// this block; it is implied that the final instruction is the result. block_flat, /// Same as `block` but additionally makes the inner instructions execute at comptime. block_comptime, /// Same as `block_flat` but additionally makes the inner instructions execute at comptime. block_comptime_flat, /// Boolean AND. See also `bitand`. booland, /// Boolean NOT. See also `bitnot`. boolnot, /// Boolean OR. See also `bitor`. boolor, /// Return a value from a `Block`. @"break", breakpoint, /// Same as `break` but without an operand; the operand is assumed to be the void value. breakvoid, /// Function call. call, /// `<` cmp_lt, /// `<=` cmp_lte, /// `==` cmp_eq, /// `>=` cmp_gte, /// `>` cmp_gt, /// `!=` cmp_neq, /// Coerces a result location pointer to a new element type. It is evaluated "backwards"- /// as type coercion from the new element type to the old element type. /// LHS is destination element type, RHS is result pointer. coerce_result_ptr, /// This instruction does a `coerce_result_ptr` operation on a `Block`'s /// result location pointer, whose type is inferred by peer type resolution on the /// `Block`'s corresponding `break` instructions. coerce_result_block_ptr, /// Equivalent to `as(ptr_child_type(typeof(ptr)), value)`. coerce_to_ptr_elem, /// Emit an error message and fail compilation. compileerror, /// Conditional branch. Splits control flow based on a boolean condition value. condbr, /// Special case, has no textual representation. @"const", /// Declares the beginning of a statement. Used for debug info. dbg_stmt, /// Represents a pointer to a global decl by name. declref, /// Represents a pointer to a global decl by string name. declref_str, /// The syntax `@foo` is equivalent to `declval("foo")`. /// declval is equivalent to declref followed by deref. declval, /// Same as declval but the parameter is a `*Module.Decl` rather than a name. declval_in_module, /// Load the value from a pointer. deref, /// Arithmetic division. Asserts no integer overflow. div, /// Given a pointer to an array, slice, or pointer, returns a pointer to the element at /// the provided index. elemptr, /// Emits a compile error if the operand is not `void`. ensure_result_used, /// Emits a compile error if an error is ignored. ensure_result_non_error, /// Emits a compile error if operand cannot be indexed. ensure_indexable, /// Create a `E!T` type. error_union_type, /// Create an error set. error_set, /// Export the provided Decl as the provided name in the compilation's output object file. @"export", /// Given a pointer to a struct or object that contains virtual fields, returns a pointer /// to the named field. fieldptr, /// Convert a larger float type to any other float type, possibly causing a loss of precision. floatcast, /// Declare a function body. @"fn", /// Returns a function type. fntype, /// @import(operand) import, /// Integer literal. int, /// Convert an integer value to another integer type, asserting that the destination type /// can hold the same mathematical value. intcast, /// Make an integer type out of signedness and bit count. inttype, /// Return a boolean false if an optional is null. `x != null` isnonnull, /// Return a boolean true if an optional is null. `x == null` isnull, /// Return a boolean true if value is an error iserr, /// A labeled block of code that loops forever. At the end of the body it is implied /// to repeat; no explicit "repeat" instruction terminates loop bodies. loop, /// Merge two error sets into one, `E1 || E2`. merge_error_sets, /// Ambiguously remainder division or modulus. If the computation would possibly have /// a different value depending on whether the operation is remainder division or modulus, /// a compile error is emitted. Otherwise the computation is performed. mod_rem, /// Arithmetic multiplication. Asserts no integer overflow. mul, /// Twos complement wrapping integer multiplication. mulwrap, /// Given a reference to a function and a parameter index, returns the /// type of the parameter. TODO what happens when the parameter is `anytype`? param_type, /// An alternative to using `const` for simple primitive values such as `true` or `u8`. /// TODO flatten so that each primitive has its own ZIR Inst Tag. primitive, /// Convert a pointer to a `usize` integer. ptrtoint, /// Turns an R-Value into a const L-Value. In other words, it takes a value, /// stores it in a memory location, and returns a const pointer to it. If the value /// is `comptime`, the memory location is global static constant data. Otherwise, /// the memory location is in the stack frame, local to the scope containing the /// instruction. ref, /// Obtains a pointer to the return value. ret_ptr, /// Obtains the return type of the in-scope function. ret_type, /// Sends control flow back to the function's callee. Takes an operand as the return value. @"return", /// Same as `return` but there is no operand; the operand is implicitly the void value. returnvoid, /// Integer shift-left. Zeroes are shifted in from the right hand side. shl, /// Integer shift-right. Arithmetic or logical depending on the signedness of the integer type. shr, /// Create a const pointer type with element type T. `*const T` single_const_ptr_type, /// Create a mutable pointer type with element type T. `*T` single_mut_ptr_type, /// Create a const pointer type with element type T. `[*]const T` many_const_ptr_type, /// Create a mutable pointer type with element type T. `[*]T` many_mut_ptr_type, /// Create a const pointer type with element type T. `[*c]const T` c_const_ptr_type, /// Create a mutable pointer type with element type T. `[*c]T` c_mut_ptr_type, /// Create a mutable slice type with element type T. `[]T` mut_slice_type, /// Create a const slice type with element type T. `[]T` const_slice_type, /// Create a pointer type with attributes ptr_type, /// Slice operation `array_ptr[start..end:sentinel]` slice, /// Slice operation with just start `lhs[rhs..]` slice_start, /// Write a value to a pointer. For loading, see `deref`. store, /// String Literal. Makes an anonymous Decl and then takes a pointer to it. str, /// Arithmetic subtraction. Asserts no integer overflow. sub, /// Twos complement wrapping integer subtraction. subwrap, /// Returns the type of a value. typeof, /// Is the builtin @TypeOf which returns the type after peertype resolution of one or more params typeof_peer, /// Asserts control-flow will not reach this instruction. Not safety checked - the compiler /// will assume the correctness of this instruction. unreach_nocheck, /// Asserts control-flow will not reach this instruction. In safety-checked modes, /// this will generate a call to the panic function unless it can be proven unreachable /// by the compiler. @"unreachable", /// Bitwise XOR. `^` xor, /// Create an optional type '?T' optional_type, /// Unwraps an optional value 'lhs.?' unwrap_optional_safe, /// Same as previous, but without safety checks. Used for orelse, if and while unwrap_optional_unsafe, /// Gets the payload of an error union unwrap_err_safe, /// Same as previous, but without safety checks. Used for orelse, if and while unwrap_err_unsafe, /// Gets the error code value of an error union unwrap_err_code, /// Takes a *E!T and raises a compiler error if T != void ensure_err_payload_void, /// Enum literal enum_literal, /// A switch expression. switchbr, /// A range in a switch case, `lhs...rhs`. /// Only checks that `lhs >= rhs` if they are ints, everything else is /// validated by the .switch instruction. switch_range, pub fn Type(tag: Tag) type { return switch (tag) { .breakpoint, .dbg_stmt, .returnvoid, .alloc_inferred, .ret_ptr, .ret_type, .unreach_nocheck, .@"unreachable", => NoOp, .boolnot, .deref, .@"return", .isnull, .isnonnull, .iserr, .ptrtoint, .alloc, .ensure_result_used, .ensure_result_non_error, .ensure_indexable, .bitcast_result_ptr, .ref, .bitcast_ref, .typeof, .single_const_ptr_type, .single_mut_ptr_type, .many_const_ptr_type, .many_mut_ptr_type, .c_const_ptr_type, .c_mut_ptr_type, .mut_slice_type, .const_slice_type, .optional_type, .unwrap_optional_safe, .unwrap_optional_unsafe, .unwrap_err_safe, .unwrap_err_unsafe, .unwrap_err_code, .ensure_err_payload_void, .anyframe_type, .bitnot, .import, => UnOp, .add, .addwrap, .array_cat, .array_mul, .array_type, .bitand, .bitor, .booland, .boolor, .div, .mod_rem, .mul, .mulwrap, .shl, .shr, .store, .sub, .subwrap, .cmp_lt, .cmp_lte, .cmp_eq, .cmp_gte, .cmp_gt, .cmp_neq, .as, .floatcast, .intcast, .bitcast, .coerce_result_ptr, .xor, .error_union_type, .merge_error_sets, .slice_start, .switch_range, => BinOp, .block, .block_flat, .block_comptime, .block_comptime_flat, => Block, .arg => Arg, .array_type_sentinel => ArrayTypeSentinel, .@"break" => Break, .breakvoid => BreakVoid, .call => Call, .coerce_to_ptr_elem => CoerceToPtrElem, .declref => DeclRef, .declref_str => DeclRefStr, .declval => DeclVal, .declval_in_module => DeclValInModule, .coerce_result_block_ptr => CoerceResultBlockPtr, .compileerror => CompileError, .loop => Loop, .@"const" => Const, .str => Str, .int => Int, .inttype => IntType, .fieldptr => FieldPtr, .@"asm" => Asm, .@"fn" => Fn, .@"export" => Export, .param_type => ParamType, .primitive => Primitive, .fntype => FnType, .elemptr => ElemPtr, .condbr => CondBr, .ptr_type => PtrType, .enum_literal => EnumLiteral, .error_set => ErrorSet, .slice => Slice, .switchbr => SwitchBr, .typeof_peer => TypeOfPeer, }; } /// Returns whether the instruction is one of the control flow "noreturn" types. /// Function calls do not count. pub fn isNoReturn(tag: Tag) bool { return switch (tag) { .add, .addwrap, .alloc, .alloc_inferred, .array_cat, .array_mul, .array_type, .array_type_sentinel, .arg, .as, .@"asm", .bitand, .bitcast, .bitcast_ref, .bitcast_result_ptr, .bitor, .block, .block_flat, .block_comptime, .block_comptime_flat, .boolnot, .booland, .boolor, .breakpoint, .call, .cmp_lt, .cmp_lte, .cmp_eq, .cmp_gte, .cmp_gt, .cmp_neq, .coerce_result_ptr, .coerce_result_block_ptr, .coerce_to_ptr_elem, .@"const", .dbg_stmt, .declref, .declref_str, .declval, .declval_in_module, .deref, .div, .elemptr, .ensure_result_used, .ensure_result_non_error, .ensure_indexable, .@"export", .floatcast, .fieldptr, .@"fn", .fntype, .int, .intcast, .inttype, .isnonnull, .isnull, .iserr, .mod_rem, .mul, .mulwrap, .param_type, .primitive, .ptrtoint, .ref, .ret_ptr, .ret_type, .shl, .shr, .single_const_ptr_type, .single_mut_ptr_type, .many_const_ptr_type, .many_mut_ptr_type, .c_const_ptr_type, .c_mut_ptr_type, .mut_slice_type, .const_slice_type, .store, .str, .sub, .subwrap, .typeof, .xor, .optional_type, .unwrap_optional_safe, .unwrap_optional_unsafe, .unwrap_err_safe, .unwrap_err_unsafe, .unwrap_err_code, .ptr_type, .ensure_err_payload_void, .enum_literal, .merge_error_sets, .anyframe_type, .error_union_type, .bitnot, .error_set, .slice, .slice_start, .import, .switch_range, .typeof_peer, => false, .@"break", .breakvoid, .condbr, .compileerror, .@"return", .returnvoid, .unreach_nocheck, .@"unreachable", .loop, .switchbr, => true, }; } }; /// Prefer `castTag` to this. pub fn cast(base: *Inst, comptime T: type) ?*T { if (@hasField(T, "base_tag")) { return base.castTag(T.base_tag); } inline for (@typeInfo(Tag).Enum.fields) |field| { const tag = @intToEnum(Tag, field.value); if (base.tag == tag) { if (T == tag.Type()) { return @fieldParentPtr(T, "base", base); } return null; } } unreachable; } pub fn castTag(base: *Inst, comptime tag: Tag) ?*tag.Type() { if (base.tag == tag) { return @fieldParentPtr(tag.Type(), "base", base); } return null; } pub const NoOp = struct { base: Inst, positionals: struct {}, kw_args: struct {}, }; pub const UnOp = struct { base: Inst, positionals: struct { operand: *Inst, }, kw_args: struct {}, }; pub const BinOp = struct { base: Inst, positionals: struct { lhs: *Inst, rhs: *Inst, }, kw_args: struct {}, }; pub const Arg = struct { pub const base_tag = Tag.arg; base: Inst, positionals: struct { name: []const u8, }, kw_args: struct {}, }; pub const Block = struct { pub const base_tag = Tag.block; base: Inst, positionals: struct { body: Module.Body, }, kw_args: struct {}, }; pub const Break = struct { pub const base_tag = Tag.@"break"; base: Inst, positionals: struct { block: *Block, operand: *Inst, }, kw_args: struct {}, }; pub const BreakVoid = struct { pub const base_tag = Tag.breakvoid; base: Inst, positionals: struct { block: *Block, }, kw_args: struct {}, }; pub const Call = struct { pub const base_tag = Tag.call; base: Inst, positionals: struct { func: *Inst, args: []*Inst, }, kw_args: struct { modifier: std.builtin.CallOptions.Modifier = .auto, }, }; pub const CoerceToPtrElem = struct { pub const base_tag = Tag.coerce_to_ptr_elem; base: Inst, positionals: struct { ptr: *Inst, value: *Inst, }, kw_args: struct {}, }; pub const DeclRef = struct { pub const base_tag = Tag.declref; base: Inst, positionals: struct { name: []const u8, }, kw_args: struct {}, }; pub const DeclRefStr = struct { pub const base_tag = Tag.declref_str; base: Inst, positionals: struct { name: *Inst, }, kw_args: struct {}, }; pub const DeclVal = struct { pub const base_tag = Tag.declval; base: Inst, positionals: struct { name: []const u8, }, kw_args: struct {}, }; pub const DeclValInModule = struct { pub const base_tag = Tag.declval_in_module; base: Inst, positionals: struct { decl: *IrModule.Decl, }, kw_args: struct {}, }; pub const CoerceResultBlockPtr = struct { pub const base_tag = Tag.coerce_result_block_ptr; base: Inst, positionals: struct { dest_type: *Inst, block: *Block, }, kw_args: struct {}, }; pub const CompileError = struct { pub const base_tag = Tag.compileerror; base: Inst, positionals: struct { msg: []const u8, }, kw_args: struct {}, }; pub const Const = struct { pub const base_tag = Tag.@"const"; base: Inst, positionals: struct { typed_value: TypedValue, }, kw_args: struct {}, }; pub const Str = struct { pub const base_tag = Tag.str; base: Inst, positionals: struct { bytes: []const u8, }, kw_args: struct {}, }; pub const Int = struct { pub const base_tag = Tag.int; base: Inst, positionals: struct { int: BigIntConst, }, kw_args: struct {}, }; pub const Loop = struct { pub const base_tag = Tag.loop; base: Inst, positionals: struct { body: Module.Body, }, kw_args: struct {}, }; pub const FieldPtr = struct { pub const base_tag = Tag.fieldptr; base: Inst, positionals: struct { object_ptr: *Inst, field_name: *Inst, }, kw_args: struct {}, }; pub const Asm = struct { pub const base_tag = Tag.@"asm"; base: Inst, positionals: struct { asm_source: *Inst, return_type: *Inst, }, kw_args: struct { @"volatile": bool = false, output: ?*Inst = null, inputs: []*Inst = &[0]*Inst{}, clobbers: []*Inst = &[0]*Inst{}, args: []*Inst = &[0]*Inst{}, }, }; pub const Fn = struct { pub const base_tag = Tag.@"fn"; base: Inst, positionals: struct { fn_type: *Inst, body: Module.Body, }, kw_args: struct {}, }; pub const FnType = struct { pub const base_tag = Tag.fntype; base: Inst, positionals: struct { param_types: []*Inst, return_type: *Inst, }, kw_args: struct { cc: std.builtin.CallingConvention = .Unspecified, }, }; pub const IntType = struct { pub const base_tag = Tag.inttype; base: Inst, positionals: struct { signed: *Inst, bits: *Inst, }, kw_args: struct {}, }; pub const Export = struct { pub const base_tag = Tag.@"export"; base: Inst, positionals: struct { symbol_name: *Inst, decl_name: []const u8, }, kw_args: struct {}, }; pub const ParamType = struct { pub const base_tag = Tag.param_type; base: Inst, positionals: struct { func: *Inst, arg_index: usize, }, kw_args: struct {}, }; pub const Primitive = struct { pub const base_tag = Tag.primitive; base: Inst, positionals: struct { tag: Builtin, }, kw_args: struct {}, pub const Builtin = enum { i8, u8, i16, u16, i32, u32, i64, u64, isize, usize, c_short, c_ushort, c_int, c_uint, c_long, c_ulong, c_longlong, c_ulonglong, c_longdouble, c_void, f16, f32, f64, f128, bool, void, noreturn, type, anyerror, comptime_int, comptime_float, @"true", @"false", @"null", @"undefined", void_value, pub fn toTypedValue(self: Builtin) TypedValue { return switch (self) { .i8 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i8_type) }, .u8 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u8_type) }, .i16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i16_type) }, .u16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u16_type) }, .i32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i32_type) }, .u32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u32_type) }, .i64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.i64_type) }, .u64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.u64_type) }, .isize => .{ .ty = Type.initTag(.type), .val = Value.initTag(.isize_type) }, .usize => .{ .ty = Type.initTag(.type), .val = Value.initTag(.usize_type) }, .c_short => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_short_type) }, .c_ushort => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ushort_type) }, .c_int => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_int_type) }, .c_uint => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_uint_type) }, .c_long => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_long_type) }, .c_ulong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ulong_type) }, .c_longlong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_longlong_type) }, .c_ulonglong => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_ulonglong_type) }, .c_longdouble => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_longdouble_type) }, .c_void => .{ .ty = Type.initTag(.type), .val = Value.initTag(.c_void_type) }, .f16 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f16_type) }, .f32 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f32_type) }, .f64 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f64_type) }, .f128 => .{ .ty = Type.initTag(.type), .val = Value.initTag(.f128_type) }, .bool => .{ .ty = Type.initTag(.type), .val = Value.initTag(.bool_type) }, .void => .{ .ty = Type.initTag(.type), .val = Value.initTag(.void_type) }, .noreturn => .{ .ty = Type.initTag(.type), .val = Value.initTag(.noreturn_type) }, .type => .{ .ty = Type.initTag(.type), .val = Value.initTag(.type_type) }, .anyerror => .{ .ty = Type.initTag(.type), .val = Value.initTag(.anyerror_type) }, .comptime_int => .{ .ty = Type.initTag(.type), .val = Value.initTag(.comptime_int_type) }, .comptime_float => .{ .ty = Type.initTag(.type), .val = Value.initTag(.comptime_float_type) }, .@"true" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_true) }, .@"false" => .{ .ty = Type.initTag(.bool), .val = Value.initTag(.bool_false) }, .@"null" => .{ .ty = Type.initTag(.@"null"), .val = Value.initTag(.null_value) }, .@"undefined" => .{ .ty = Type.initTag(.@"undefined"), .val = Value.initTag(.undef) }, .void_value => .{ .ty = Type.initTag(.void), .val = Value.initTag(.void_value) }, }; } }; }; pub const ElemPtr = struct { pub const base_tag = Tag.elemptr; base: Inst, positionals: struct { array_ptr: *Inst, index: *Inst, }, kw_args: struct {}, }; pub const CondBr = struct { pub const base_tag = Tag.condbr; base: Inst, positionals: struct { condition: *Inst, then_body: Module.Body, else_body: Module.Body, }, kw_args: struct {}, }; pub const PtrType = struct { pub const base_tag = Tag.ptr_type; base: Inst, positionals: struct { child_type: *Inst, }, kw_args: struct { @"allowzero": bool = false, @"align": ?*Inst = null, align_bit_start: ?*Inst = null, align_bit_end: ?*Inst = null, mutable: bool = true, @"volatile": bool = false, sentinel: ?*Inst = null, size: std.builtin.TypeInfo.Pointer.Size = .One, }, }; pub const ArrayTypeSentinel = struct { pub const base_tag = Tag.array_type_sentinel; base: Inst, positionals: struct { len: *Inst, sentinel: *Inst, elem_type: *Inst, }, kw_args: struct {}, }; pub const EnumLiteral = struct { pub const base_tag = Tag.enum_literal; base: Inst, positionals: struct { name: []const u8, }, kw_args: struct {}, }; pub const ErrorSet = struct { pub const base_tag = Tag.error_set; base: Inst, positionals: struct { fields: [][]const u8, }, kw_args: struct {}, }; pub const Slice = struct { pub const base_tag = Tag.slice; base: Inst, positionals: struct { array_ptr: *Inst, start: *Inst, }, kw_args: struct { end: ?*Inst = null, sentinel: ?*Inst = null, }, }; pub const SwitchBr = struct { pub const base_tag = Tag.switchbr; base: Inst, positionals: struct { target_ptr: *Inst, /// List of all individual items and ranges items: []*Inst, cases: []Case, else_body: Module.Body, }, kw_args: struct { /// Pointer to first range if such exists. range: ?*Inst = null, special_prong: enum { none, @"else", underscore, } = .none, }, pub const Case = struct { item: *Inst, body: Module.Body, }; }; pub const TypeOfPeer = struct { pub const base_tag = .typeof_peer; base: Inst, positionals: struct { items: []*Inst, }, kw_args: struct {}, }; }; pub const ErrorMsg = struct { byte_offset: usize, msg: []const u8, }; pub const Module = struct { decls: []*Decl, arena: std.heap.ArenaAllocator, error_msg: ?ErrorMsg = null, metadata: std.AutoHashMap(*Inst, MetaData), body_metadata: std.AutoHashMap(*Body, BodyMetaData), pub const MetaData = struct { deaths: ir.Inst.DeathsInt, addr: usize, }; pub const BodyMetaData = struct { deaths: []*Inst, }; pub const Body = struct { instructions: []*Inst, }; pub fn deinit(self: *Module, allocator: *Allocator) void { self.metadata.deinit(); self.body_metadata.deinit(); allocator.free(self.decls); self.arena.deinit(); self.* = undefined; } /// This is a debugging utility for rendering the tree to stderr. pub fn dump(self: Module) void { self.writeToStream(std.heap.page_allocator, std.io.getStdErr().outStream()) catch {}; } const DeclAndIndex = struct { decl: *Decl, index: usize, }; /// TODO Look into making a table to speed this up. pub fn findDecl(self: Module, name: []const u8) ?DeclAndIndex { for (self.decls) |decl, i| { if (mem.eql(u8, decl.name, name)) { return DeclAndIndex{ .decl = decl, .index = i, }; } } return null; } pub fn findInstDecl(self: Module, inst: *Inst) ?DeclAndIndex { for (self.decls) |decl, i| { if (decl.inst == inst) { return DeclAndIndex{ .decl = decl, .index = i, }; } } return null; } /// The allocator is used for temporary storage, but this function always returns /// with no resources allocated. pub fn writeToStream(self: Module, allocator: *Allocator, stream: anytype) !void { var write = Writer{ .module = &self, .inst_table = InstPtrTable.init(allocator), .block_table = std.AutoHashMap(*Inst.Block, []const u8).init(allocator), .loop_table = std.AutoHashMap(*Inst.Loop, []const u8).init(allocator), .arena = std.heap.ArenaAllocator.init(allocator), .indent = 2, .next_instr_index = undefined, }; defer write.arena.deinit(); defer write.inst_table.deinit(); defer write.block_table.deinit(); defer write.loop_table.deinit(); // First, build a map of *Inst to @ or % indexes try write.inst_table.ensureCapacity(@intCast(u32, self.decls.len)); for (self.decls) |decl, decl_i| { try write.inst_table.putNoClobber(decl.inst, .{ .inst = decl.inst, .index = null, .name = decl.name }); } for (self.decls) |decl, i| { write.next_instr_index = 0; try stream.print("@{} ", .{decl.name}); try write.writeInstToStream(stream, decl.inst); try stream.writeByte('\n'); } } }; const InstPtrTable = std.AutoHashMap(*Inst, struct { inst: *Inst, index: ?usize, name: []const u8 }); const Writer = struct { module: *const Module, inst_table: InstPtrTable, block_table: std.AutoHashMap(*Inst.Block, []const u8), loop_table: std.AutoHashMap(*Inst.Loop, []const u8), arena: std.heap.ArenaAllocator, indent: usize, next_instr_index: usize, fn writeInstToStream( self: *Writer, stream: anytype, inst: *Inst, ) (@TypeOf(stream).Error || error{OutOfMemory})!void { inline for (@typeInfo(Inst.Tag).Enum.fields) |enum_field| { const expected_tag = @field(Inst.Tag, enum_field.name); if (inst.tag == expected_tag) { return self.writeInstToStreamGeneric(stream, expected_tag, inst); } } unreachable; // all tags handled } fn writeInstToStreamGeneric( self: *Writer, stream: anytype, comptime inst_tag: Inst.Tag, base: *Inst, ) (@TypeOf(stream).Error || error{OutOfMemory})!void { const SpecificInst = inst_tag.Type(); const inst = @fieldParentPtr(SpecificInst, "base", base); const Positionals = @TypeOf(inst.positionals); try stream.writeAll("= " ++ @tagName(inst_tag) ++ "("); const pos_fields = @typeInfo(Positionals).Struct.fields; inline for (pos_fields) |arg_field, i| { if (i != 0) { try stream.writeAll(", "); } try self.writeParamToStream(stream, &@field(inst.positionals, arg_field.name)); } comptime var need_comma = pos_fields.len != 0; const KW_Args = @TypeOf(inst.kw_args); inline for (@typeInfo(KW_Args).Struct.fields) |arg_field, i| { if (@typeInfo(arg_field.field_type) == .Optional) { if (@field(inst.kw_args, arg_field.name)) |non_optional| { if (need_comma) try stream.writeAll(", "); try stream.print("{}=", .{arg_field.name}); try self.writeParamToStream(stream, &non_optional); need_comma = true; } } else { if (need_comma) try stream.writeAll(", "); try stream.print("{}=", .{arg_field.name}); try self.writeParamToStream(stream, &@field(inst.kw_args, arg_field.name)); need_comma = true; } } try stream.writeByte(')'); } fn writeParamToStream(self: *Writer, stream: anytype, param_ptr: anytype) !void { const param = param_ptr.*; if (@typeInfo(@TypeOf(param)) == .Enum) { return stream.writeAll(@tagName(param)); } switch (@TypeOf(param)) { *Inst => return self.writeInstParamToStream(stream, param), []*Inst => { try stream.writeByte('['); for (param) |inst, i| { if (i != 0) { try stream.writeAll(", "); } try self.writeInstParamToStream(stream, inst); } try stream.writeByte(']'); }, Module.Body => { try stream.writeAll("{\n"); if (self.module.body_metadata.get(param_ptr)) |metadata| { if (metadata.deaths.len > 0) { try stream.writeByteNTimes(' ', self.indent); try stream.writeAll("; deaths={"); for (metadata.deaths) |death, i| { if (i != 0) try stream.writeAll(", "); try self.writeInstParamToStream(stream, death); } try stream.writeAll("}\n"); } } for (param.instructions) |inst| { const my_i = self.next_instr_index; self.next_instr_index += 1; try self.inst_table.putNoClobber(inst, .{ .inst = inst, .index = my_i, .name = undefined }); try stream.writeByteNTimes(' ', self.indent); try stream.print("%{} ", .{my_i}); if (inst.cast(Inst.Block)) |block| { const name = try std.fmt.allocPrint(&self.arena.allocator, "label_{}", .{my_i}); try self.block_table.put(block, name); } else if (inst.cast(Inst.Loop)) |loop| { const name = try std.fmt.allocPrint(&self.arena.allocator, "loop_{}", .{my_i}); try self.loop_table.put(loop, name); } self.indent += 2; try self.writeInstToStream(stream, inst); if (self.module.metadata.get(inst)) |metadata| { try stream.print(" ; deaths=0b{b}", .{metadata.deaths}); // This is conditionally compiled in because addresses mess up the tests due // to Address Space Layout Randomization. It's super useful when debugging // codegen.zig though. if (!std.builtin.is_test) { try stream.print(" 0x{x}", .{metadata.addr}); } } self.indent -= 2; try stream.writeByte('\n'); } try stream.writeByteNTimes(' ', self.indent - 2); try stream.writeByte('}'); }, bool => return stream.writeByte("01"[@boolToInt(param)]), []u8, []const u8 => return stream.print("\"{Z}\"", .{param}), BigIntConst, usize => return stream.print("{}", .{param}), TypedValue => return stream.print("TypedValue{{ .ty = {}, .val = {}}}", .{ param.ty, param.val }), *IrModule.Decl => return stream.print("Decl({s})", .{param.name}), *Inst.Block => { const name = self.block_table.get(param).?; return stream.print("\"{Z}\"", .{name}); }, *Inst.Loop => { const name = self.loop_table.get(param).?; return stream.print("\"{Z}\"", .{name}); }, [][]const u8 => { try stream.writeByte('['); for (param) |str, i| { if (i != 0) { try stream.writeAll(", "); } try stream.print("\"{Z}\"", .{str}); } try stream.writeByte(']'); }, []Inst.SwitchBr.Case => { if (param.len == 0) { return stream.writeAll("{}"); } try stream.writeAll("{\n"); for (param) |*case, i| { if (i != 0) { try stream.writeAll(",\n"); } try stream.writeByteNTimes(' ', self.indent); self.indent += 2; try self.writeParamToStream(stream, &case.item); try stream.writeAll(" => "); try self.writeParamToStream(stream, &case.body); self.indent -= 2; } try stream.writeByte('\n'); try stream.writeByteNTimes(' ', self.indent - 2); try stream.writeByte('}'); }, else => |T| @compileError("unimplemented: rendering parameter of type " ++ @typeName(T)), } } fn writeInstParamToStream(self: *Writer, stream: anytype, inst: *Inst) !void { if (self.inst_table.get(inst)) |info| { if (info.index) |i| { try stream.print("%{}", .{info.index}); } else { try stream.print("@{}", .{info.name}); } } else if (inst.cast(Inst.DeclVal)) |decl_val| { try stream.print("@{}", .{decl_val.positionals.name}); } else if (inst.cast(Inst.DeclValInModule)) |decl_val| { try stream.print("@{}", .{decl_val.positionals.decl.name}); } else { // This should be unreachable in theory, but since ZIR is used for debugging the compiler // we output some debug text instead. try stream.print("?{}?", .{@tagName(inst.tag)}); } } }; pub fn parse(allocator: *Allocator, source: [:0]const u8) Allocator.Error!Module { var global_name_map = std.StringHashMap(*Inst).init(allocator); defer global_name_map.deinit(); var parser: Parser = .{ .allocator = allocator, .arena = std.heap.ArenaAllocator.init(allocator), .i = 0, .source = source, .global_name_map = &global_name_map, .decls = .{}, .unnamed_index = 0, .block_table = std.StringHashMap(*Inst.Block).init(allocator), .loop_table = std.StringHashMap(*Inst.Loop).init(allocator), }; defer parser.block_table.deinit(); defer parser.loop_table.deinit(); errdefer parser.arena.deinit(); parser.parseRoot() catch |err| switch (err) { error.ParseFailure => { assert(parser.error_msg != null); }, else => |e| return e, }; return Module{ .decls = parser.decls.toOwnedSlice(allocator), .arena = parser.arena, .error_msg = parser.error_msg, .metadata = std.AutoHashMap(*Inst, Module.MetaData).init(allocator), .body_metadata = std.AutoHashMap(*Module.Body, Module.BodyMetaData).init(allocator), }; } const Parser = struct { allocator: *Allocator, arena: std.heap.ArenaAllocator, i: usize, source: [:0]const u8, decls: std.ArrayListUnmanaged(*Decl), global_name_map: *std.StringHashMap(*Inst), error_msg: ?ErrorMsg = null, unnamed_index: usize, block_table: std.StringHashMap(*Inst.Block), loop_table: std.StringHashMap(*Inst.Loop), const Body = struct { instructions: std.ArrayList(*Inst), name_map: *std.StringHashMap(*Inst), }; fn parseBody(self: *Parser, body_ctx: ?*Body) !Module.Body { var name_map = std.StringHashMap(*Inst).init(self.allocator); defer name_map.deinit(); var body_context = Body{ .instructions = std.ArrayList(*Inst).init(self.allocator), .name_map = if (body_ctx) |bctx| bctx.name_map else &name_map, }; defer body_context.instructions.deinit(); try requireEatBytes(self, "{"); skipSpace(self); while (true) : (self.i += 1) switch (self.source[self.i]) { ';' => _ = try skipToAndOver(self, '\n'), '%' => { self.i += 1; const ident = try skipToAndOver(self, ' '); skipSpace(self); try requireEatBytes(self, "="); skipSpace(self); const decl = try parseInstruction(self, &body_context, ident); const ident_index = body_context.instructions.items.len; if (try body_context.name_map.fetchPut(ident, decl.inst)) |_| { return self.fail("redefinition of identifier '{}'", .{ident}); } try body_context.instructions.append(decl.inst); continue; }, ' ', '\n' => continue, '}' => { self.i += 1; break; }, else => |byte| return self.failByte(byte), }; // Move the instructions to the arena const instrs = try self.arena.allocator.alloc(*Inst, body_context.instructions.items.len); mem.copy(*Inst, instrs, body_context.instructions.items); return Module.Body{ .instructions = instrs }; } fn parseStringLiteral(self: *Parser) ![]u8 { const start = self.i; try self.requireEatBytes("\""); while (true) : (self.i += 1) switch (self.source[self.i]) { '"' => { self.i += 1; const span = self.source[start..self.i]; var bad_index: usize = undefined; const parsed = std.zig.parseStringLiteral(&self.arena.allocator, span, &bad_index) catch |err| switch (err) { error.InvalidCharacter => { self.i = start + bad_index; const bad_byte = self.source[self.i]; return self.fail("invalid string literal character: '{c}'\n", .{bad_byte}); }, else => |e| return e, }; return parsed; }, '\\' => { self.i += 1; continue; }, 0 => return self.failByte(0), else => continue, }; } fn parseIntegerLiteral(self: *Parser) !BigIntConst { const start = self.i; if (self.source[self.i] == '-') self.i += 1; while (true) : (self.i += 1) switch (self.source[self.i]) { '0'...'9' => continue, else => break, }; const number_text = self.source[start..self.i]; const base = 10; // TODO reuse the same array list for this const limbs_buffer_len = std.math.big.int.calcSetStringLimbsBufferLen(base, number_text.len); const limbs_buffer = try self.allocator.alloc(std.math.big.Limb, limbs_buffer_len); defer self.allocator.free(limbs_buffer); const limb_len = std.math.big.int.calcSetStringLimbCount(base, number_text.len); const limbs = try self.arena.allocator.alloc(std.math.big.Limb, limb_len); var result = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result.setString(base, number_text, limbs_buffer, self.allocator) catch |err| switch (err) { error.InvalidCharacter => { self.i = start; return self.fail("invalid digit in integer literal", .{}); }, }; return result.toConst(); } fn parseRoot(self: *Parser) !void { // The IR format is designed so that it can be tokenized and parsed at the same time. while (true) { switch (self.source[self.i]) { ';' => _ = try skipToAndOver(self, '\n'), '@' => { self.i += 1; const ident = try skipToAndOver(self, ' '); skipSpace(self); try requireEatBytes(self, "="); skipSpace(self); const decl = try parseInstruction(self, null, ident); const ident_index = self.decls.items.len; if (try self.global_name_map.fetchPut(ident, decl.inst)) |_| { return self.fail("redefinition of identifier '{}'", .{ident}); } try self.decls.append(self.allocator, decl); }, ' ', '\n' => self.i += 1, 0 => break, else => |byte| return self.fail("unexpected byte: '{c}'", .{byte}), } } } fn eatByte(self: *Parser, byte: u8) bool { if (self.source[self.i] != byte) return false; self.i += 1; return true; } fn skipSpace(self: *Parser) void { while (self.source[self.i] == ' ' or self.source[self.i] == '\n') { self.i += 1; } } fn requireEatBytes(self: *Parser, bytes: []const u8) !void { const start = self.i; for (bytes) |byte| { if (self.source[self.i] != byte) { self.i = start; return self.fail("expected '{}'", .{bytes}); } self.i += 1; } } fn skipToAndOver(self: *Parser, byte: u8) ![]const u8 { const start_i = self.i; while (self.source[self.i] != 0) : (self.i += 1) { if (self.source[self.i] == byte) { const result = self.source[start_i..self.i]; self.i += 1; return result; } } return self.fail("unexpected EOF", .{}); } /// ParseFailure is an internal error code; handled in `parse`. const InnerError = error{ ParseFailure, OutOfMemory }; fn failByte(self: *Parser, byte: u8) InnerError { if (byte == 0) { return self.fail("unexpected EOF", .{}); } else { return self.fail("unexpected byte: '{c}'", .{byte}); } } fn fail(self: *Parser, comptime format: []const u8, args: anytype) InnerError { @setCold(true); self.error_msg = ErrorMsg{ .byte_offset = self.i, .msg = try std.fmt.allocPrint(&self.arena.allocator, format, args), }; return error.ParseFailure; } fn parseInstruction(self: *Parser, body_ctx: ?*Body, name: []const u8) InnerError!*Decl { const contents_start = self.i; const fn_name = try skipToAndOver(self, '('); inline for (@typeInfo(Inst.Tag).Enum.fields) |field| { if (mem.eql(u8, field.name, fn_name)) { const tag = @field(Inst.Tag, field.name); return parseInstructionGeneric(self, field.name, tag.Type(), tag, body_ctx, name, contents_start); } } return self.fail("unknown instruction '{}'", .{fn_name}); } fn parseInstructionGeneric( self: *Parser, comptime fn_name: []const u8, comptime InstType: type, tag: Inst.Tag, body_ctx: ?*Body, inst_name: []const u8, contents_start: usize, ) InnerError!*Decl { const inst_specific = try self.arena.allocator.create(InstType); inst_specific.base = .{ .src = self.i, .tag = tag, }; if (InstType == Inst.Block) { try self.block_table.put(inst_name, inst_specific); } else if (InstType == Inst.Loop) { try self.loop_table.put(inst_name, inst_specific); } if (@hasField(InstType, "ty")) { inst_specific.ty = opt_type orelse { return self.fail("instruction '" ++ fn_name ++ "' requires type", .{}); }; } const Positionals = @TypeOf(inst_specific.positionals); inline for (@typeInfo(Positionals).Struct.fields) |arg_field| { if (self.source[self.i] == ',') { self.i += 1; skipSpace(self); } else if (self.source[self.i] == ')') { return self.fail("expected positional parameter '{}'", .{arg_field.name}); } @field(inst_specific.positionals, arg_field.name) = try parseParameterGeneric( self, arg_field.field_type, body_ctx, ); skipSpace(self); } const KW_Args = @TypeOf(inst_specific.kw_args); inst_specific.kw_args = .{}; // assign defaults skipSpace(self); while (eatByte(self, ',')) { skipSpace(self); const name = try skipToAndOver(self, '='); inline for (@typeInfo(KW_Args).Struct.fields) |arg_field| { const field_name = arg_field.name; if (mem.eql(u8, name, field_name)) { const NonOptional = switch (@typeInfo(arg_field.field_type)) { .Optional => |info| info.child, else => arg_field.field_type, }; @field(inst_specific.kw_args, field_name) = try parseParameterGeneric(self, NonOptional, body_ctx); break; } } else { return self.fail("unrecognized keyword parameter: '{}'", .{name}); } skipSpace(self); } try requireEatBytes(self, ")"); const decl = try self.arena.allocator.create(Decl); decl.* = .{ .name = inst_name, .contents_hash = std.zig.hashSrc(self.source[contents_start..self.i]), .inst = &inst_specific.base, }; //std.debug.warn("parsed {} = '{}'\n", .{ inst_specific.base.name, inst_specific.base.contents }); return decl; } fn parseParameterGeneric(self: *Parser, comptime T: type, body_ctx: ?*Body) !T { if (@typeInfo(T) == .Enum) { const start = self.i; while (true) : (self.i += 1) switch (self.source[self.i]) { ' ', '\n', ',', ')' => { const enum_name = self.source[start..self.i]; return std.meta.stringToEnum(T, enum_name) orelse { return self.fail("tag '{}' not a member of enum '{}'", .{ enum_name, @typeName(T) }); }; }, 0 => return self.failByte(0), else => continue, }; } switch (T) { Module.Body => return parseBody(self, body_ctx), bool => { const bool_value = switch (self.source[self.i]) { '0' => false, '1' => true, else => |byte| return self.fail("expected '0' or '1' for boolean value, found {c}", .{byte}), }; self.i += 1; return bool_value; }, []*Inst => { try requireEatBytes(self, "["); skipSpace(self); if (eatByte(self, ']')) return &[0]*Inst{}; var instructions = std.ArrayList(*Inst).init(&self.arena.allocator); while (true) { skipSpace(self); try instructions.append(try parseParameterInst(self, body_ctx)); skipSpace(self); if (!eatByte(self, ',')) break; } try requireEatBytes(self, "]"); return instructions.toOwnedSlice(); }, *Inst => return parseParameterInst(self, body_ctx), []u8, []const u8 => return self.parseStringLiteral(), BigIntConst => return self.parseIntegerLiteral(), usize => { const big_int = try self.parseIntegerLiteral(); return big_int.to(usize) catch |err| return self.fail("integer literal: {}", .{@errorName(err)}); }, TypedValue => return self.fail("'const' is a special instruction; not legal in ZIR text", .{}), *IrModule.Decl => return self.fail("'declval_in_module' is a special instruction; not legal in ZIR text", .{}), *Inst.Block => { const name = try self.parseStringLiteral(); return self.block_table.get(name).?; }, *Inst.Loop => { const name = try self.parseStringLiteral(); return self.loop_table.get(name).?; }, [][]const u8 => { try requireEatBytes(self, "["); skipSpace(self); if (eatByte(self, ']')) return &[0][]const u8{}; var strings = std.ArrayList([]const u8).init(&self.arena.allocator); while (true) { skipSpace(self); try strings.append(try self.parseStringLiteral()); skipSpace(self); if (!eatByte(self, ',')) break; } try requireEatBytes(self, "]"); return strings.toOwnedSlice(); }, []Inst.SwitchBr.Case => { try requireEatBytes(self, "{"); skipSpace(self); if (eatByte(self, '}')) return &[0]Inst.SwitchBr.Case{}; var cases = std.ArrayList(Inst.SwitchBr.Case).init(&self.arena.allocator); while (true) { const cur = try cases.addOne(); skipSpace(self); cur.item = try self.parseParameterGeneric(*Inst, body_ctx); skipSpace(self); try requireEatBytes(self, "=>"); cur.body = try self.parseBody(body_ctx); skipSpace(self); if (!eatByte(self, ',')) break; } skipSpace(self); try requireEatBytes(self, "}"); return cases.toOwnedSlice(); }, else => @compileError("Unimplemented: ir parseParameterGeneric for type " ++ @typeName(T)), } return self.fail("TODO parse parameter {}", .{@typeName(T)}); } fn parseParameterInst(self: *Parser, body_ctx: ?*Body) !*Inst { const local_ref = switch (self.source[self.i]) { '@' => false, '%' => true, else => |byte| return self.fail("unexpected byte: '{c}'", .{byte}), }; const map = if (local_ref) if (body_ctx) |bc| bc.name_map else return self.fail("referencing a % instruction in global scope", .{}) else self.global_name_map; self.i += 1; const name_start = self.i; while (true) : (self.i += 1) switch (self.source[self.i]) { 0, ' ', '\n', ',', ')', ']' => break, else => continue, }; const ident = self.source[name_start..self.i]; return map.get(ident) orelse { const bad_name = self.source[name_start - 1 .. self.i]; const src = name_start - 1; if (local_ref) { self.i = src; return self.fail("unrecognized identifier: {}", .{bad_name}); } else { const declval = try self.arena.allocator.create(Inst.DeclVal); declval.* = .{ .base = .{ .src = src, .tag = Inst.DeclVal.base_tag, }, .positionals = .{ .name = ident }, .kw_args = .{}, }; return &declval.base; } }; } fn generateName(self: *Parser) ![]u8 { const result = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${}", .{self.unnamed_index}); self.unnamed_index += 1; return result; } }; pub fn emit(allocator: *Allocator, old_module: *IrModule) !Module { var ctx: EmitZIR = .{ .allocator = allocator, .decls = .{}, .arena = std.heap.ArenaAllocator.init(allocator), .old_module = old_module, .next_auto_name = 0, .names = std.StringArrayHashMap(void).init(allocator), .primitive_table = std.AutoHashMap(Inst.Primitive.Builtin, *Decl).init(allocator), .indent = 0, .block_table = std.AutoHashMap(*ir.Inst.Block, *Inst.Block).init(allocator), .loop_table = std.AutoHashMap(*ir.Inst.Loop, *Inst.Loop).init(allocator), .metadata = std.AutoHashMap(*Inst, Module.MetaData).init(allocator), .body_metadata = std.AutoHashMap(*Module.Body, Module.BodyMetaData).init(allocator), }; errdefer ctx.metadata.deinit(); errdefer ctx.body_metadata.deinit(); defer ctx.block_table.deinit(); defer ctx.loop_table.deinit(); defer ctx.decls.deinit(allocator); defer ctx.names.deinit(); defer ctx.primitive_table.deinit(); errdefer ctx.arena.deinit(); try ctx.emit(); return Module{ .decls = ctx.decls.toOwnedSlice(allocator), .arena = ctx.arena, .metadata = ctx.metadata, .body_metadata = ctx.body_metadata, }; } /// For debugging purposes, prints a function representation to stderr. pub fn dumpFn(old_module: IrModule, module_fn: *IrModule.Fn) void { const allocator = old_module.gpa; var ctx: EmitZIR = .{ .allocator = allocator, .decls = .{}, .arena = std.heap.ArenaAllocator.init(allocator), .old_module = &old_module, .next_auto_name = 0, .names = std.StringArrayHashMap(void).init(allocator), .primitive_table = std.AutoHashMap(Inst.Primitive.Builtin, *Decl).init(allocator), .indent = 0, .block_table = std.AutoHashMap(*ir.Inst.Block, *Inst.Block).init(allocator), .loop_table = std.AutoHashMap(*ir.Inst.Loop, *Inst.Loop).init(allocator), .metadata = std.AutoHashMap(*Inst, Module.MetaData).init(allocator), .body_metadata = std.AutoHashMap(*Module.Body, Module.BodyMetaData).init(allocator), }; defer ctx.metadata.deinit(); defer ctx.body_metadata.deinit(); defer ctx.block_table.deinit(); defer ctx.loop_table.deinit(); defer ctx.decls.deinit(allocator); defer ctx.names.deinit(); defer ctx.primitive_table.deinit(); defer ctx.arena.deinit(); const fn_ty = module_fn.owner_decl.typed_value.most_recent.typed_value.ty; _ = ctx.emitFn(module_fn, 0, fn_ty) catch |err| { std.debug.print("unable to dump function: {}\n", .{err}); return; }; var module = Module{ .decls = ctx.decls.items, .arena = ctx.arena, .metadata = ctx.metadata, .body_metadata = ctx.body_metadata, }; module.dump(); } const EmitZIR = struct { allocator: *Allocator, arena: std.heap.ArenaAllocator, old_module: *const IrModule, decls: std.ArrayListUnmanaged(*Decl), names: std.StringArrayHashMap(void), next_auto_name: usize, primitive_table: std.AutoHashMap(Inst.Primitive.Builtin, *Decl), indent: usize, block_table: std.AutoHashMap(*ir.Inst.Block, *Inst.Block), loop_table: std.AutoHashMap(*ir.Inst.Loop, *Inst.Loop), metadata: std.AutoHashMap(*Inst, Module.MetaData), body_metadata: std.AutoHashMap(*Module.Body, Module.BodyMetaData), fn emit(self: *EmitZIR) !void { // Put all the Decls in a list and sort them by name to avoid nondeterminism introduced // by the hash table. var src_decls = std.ArrayList(*IrModule.Decl).init(self.allocator); defer src_decls.deinit(); try src_decls.ensureCapacity(self.old_module.decl_table.items().len); try self.decls.ensureCapacity(self.allocator, self.old_module.decl_table.items().len); try self.names.ensureCapacity(self.old_module.decl_table.items().len); for (self.old_module.decl_table.items()) |entry| { const decl = entry.value; src_decls.appendAssumeCapacity(decl); self.names.putAssumeCapacityNoClobber(mem.spanZ(decl.name), {}); } std.sort.sort(*IrModule.Decl, src_decls.items, {}, (struct { fn lessThan(context: void, a: *IrModule.Decl, b: *IrModule.Decl) bool { return a.src_index < b.src_index; } }).lessThan); // Emit all the decls. for (src_decls.items) |ir_decl| { switch (ir_decl.analysis) { .unreferenced => continue, .complete => {}, .codegen_failure => {}, // We still can emit the ZIR. .codegen_failure_retryable => {}, // We still can emit the ZIR. .in_progress => unreachable, .outdated => unreachable, .sema_failure, .sema_failure_retryable, .dependency_failure, => if (self.old_module.failed_decls.get(ir_decl)) |err_msg| { const fail_inst = try self.arena.allocator.create(Inst.CompileError); fail_inst.* = .{ .base = .{ .src = ir_decl.src(), .tag = Inst.CompileError.base_tag, }, .positionals = .{ .msg = try self.arena.allocator.dupe(u8, err_msg.msg), }, .kw_args = .{}, }; const decl = try self.arena.allocator.create(Decl); decl.* = .{ .name = mem.spanZ(ir_decl.name), .contents_hash = undefined, .inst = &fail_inst.base, }; try self.decls.append(self.allocator, decl); continue; }, } if (self.old_module.export_owners.get(ir_decl)) |exports| { for (exports) |module_export| { const symbol_name = try self.emitStringLiteral(module_export.src, module_export.options.name); const export_inst = try self.arena.allocator.create(Inst.Export); export_inst.* = .{ .base = .{ .src = module_export.src, .tag = Inst.Export.base_tag, }, .positionals = .{ .symbol_name = symbol_name.inst, .decl_name = mem.spanZ(module_export.exported_decl.name), }, .kw_args = .{}, }; _ = try self.emitUnnamedDecl(&export_inst.base); } } const new_decl = try self.emitTypedValue(ir_decl.src(), ir_decl.typed_value.most_recent.typed_value); new_decl.name = try self.arena.allocator.dupe(u8, mem.spanZ(ir_decl.name)); } } const ZirBody = struct { inst_table: *std.AutoHashMap(*ir.Inst, *Inst), instructions: *std.ArrayList(*Inst), }; fn resolveInst(self: *EmitZIR, new_body: ZirBody, inst: *ir.Inst) !*Inst { if (inst.cast(ir.Inst.Constant)) |const_inst| { const new_inst = if (const_inst.val.cast(Value.Payload.Function)) |func_pl| blk: { const owner_decl = func_pl.func.owner_decl; break :blk try self.emitDeclVal(inst.src, mem.spanZ(owner_decl.name)); } else if (const_inst.val.cast(Value.Payload.DeclRef)) |declref| blk: { const decl_ref = try self.emitDeclRef(inst.src, declref.decl); try new_body.instructions.append(decl_ref); break :blk decl_ref; } else if (const_inst.val.cast(Value.Payload.Variable)) |var_pl| blk: { const owner_decl = var_pl.variable.owner_decl; break :blk try self.emitDeclVal(inst.src, mem.spanZ(owner_decl.name)); } else blk: { break :blk (try self.emitTypedValue(inst.src, .{ .ty = inst.ty, .val = const_inst.val })).inst; }; _ = try new_body.inst_table.put(inst, new_inst); return new_inst; } else { return new_body.inst_table.get(inst).?; } } fn emitDeclVal(self: *EmitZIR, src: usize, decl_name: []const u8) !*Inst { const declval = try self.arena.allocator.create(Inst.DeclVal); declval.* = .{ .base = .{ .src = src, .tag = Inst.DeclVal.base_tag, }, .positionals = .{ .name = try self.arena.allocator.dupe(u8, decl_name) }, .kw_args = .{}, }; return &declval.base; } fn emitComptimeIntVal(self: *EmitZIR, src: usize, val: Value) !*Decl { const big_int_space = try self.arena.allocator.create(Value.BigIntSpace); const int_inst = try self.arena.allocator.create(Inst.Int); int_inst.* = .{ .base = .{ .src = src, .tag = Inst.Int.base_tag, }, .positionals = .{ .int = val.toBigInt(big_int_space), }, .kw_args = .{}, }; return self.emitUnnamedDecl(&int_inst.base); } fn emitDeclRef(self: *EmitZIR, src: usize, module_decl: *IrModule.Decl) !*Inst { const declref_inst = try self.arena.allocator.create(Inst.DeclRef); declref_inst.* = .{ .base = .{ .src = src, .tag = Inst.DeclRef.base_tag, }, .positionals = .{ .name = mem.spanZ(module_decl.name), }, .kw_args = .{}, }; return &declref_inst.base; } fn emitFn(self: *EmitZIR, module_fn: *IrModule.Fn, src: usize, ty: Type) Allocator.Error!*Decl { var inst_table = std.AutoHashMap(*ir.Inst, *Inst).init(self.allocator); defer inst_table.deinit(); var instructions = std.ArrayList(*Inst).init(self.allocator); defer instructions.deinit(); switch (module_fn.analysis) { .queued => unreachable, .in_progress => unreachable, .success => |body| { try self.emitBody(body, &inst_table, &instructions); }, .sema_failure => { const err_msg = self.old_module.failed_decls.get(module_fn.owner_decl).?; const fail_inst = try self.arena.allocator.create(Inst.CompileError); fail_inst.* = .{ .base = .{ .src = src, .tag = Inst.CompileError.base_tag, }, .positionals = .{ .msg = try self.arena.allocator.dupe(u8, err_msg.msg), }, .kw_args = .{}, }; try instructions.append(&fail_inst.base); }, .dependency_failure => { const fail_inst = try self.arena.allocator.create(Inst.CompileError); fail_inst.* = .{ .base = .{ .src = src, .tag = Inst.CompileError.base_tag, }, .positionals = .{ .msg = try self.arena.allocator.dupe(u8, "depends on another failed Decl"), }, .kw_args = .{}, }; try instructions.append(&fail_inst.base); }, } const fn_type = try self.emitType(src, ty); const arena_instrs = try self.arena.allocator.alloc(*Inst, instructions.items.len); mem.copy(*Inst, arena_instrs, instructions.items); const fn_inst = try self.arena.allocator.create(Inst.Fn); fn_inst.* = .{ .base = .{ .src = src, .tag = Inst.Fn.base_tag, }, .positionals = .{ .fn_type = fn_type.inst, .body = .{ .instructions = arena_instrs }, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&fn_inst.base); } fn emitTypedValue(self: *EmitZIR, src: usize, typed_value: TypedValue) Allocator.Error!*Decl { const allocator = &self.arena.allocator; if (typed_value.val.cast(Value.Payload.DeclRef)) |decl_ref| { const decl = decl_ref.decl; return try self.emitUnnamedDecl(try self.emitDeclRef(src, decl)); } else if (typed_value.val.cast(Value.Payload.Variable)) |variable| { return self.emitTypedValue(src, .{ .ty = typed_value.ty, .val = variable.variable.init, }); } if (typed_value.val.isUndef()) { const as_inst = try self.arena.allocator.create(Inst.BinOp); as_inst.* = .{ .base = .{ .tag = .as, .src = src, }, .positionals = .{ .lhs = (try self.emitType(src, typed_value.ty)).inst, .rhs = (try self.emitPrimitive(src, .@"undefined")).inst, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&as_inst.base); } switch (typed_value.ty.zigTypeTag()) { .Pointer => { const ptr_elem_type = typed_value.ty.elemType(); switch (ptr_elem_type.zigTypeTag()) { .Array => { // TODO more checks to make sure this can be emitted as a string literal //const array_elem_type = ptr_elem_type.elemType(); //if (array_elem_type.eql(Type.initTag(.u8)) and // ptr_elem_type.hasSentinel(Value.initTag(.zero))) //{ //} const bytes = typed_value.val.toAllocatedBytes(allocator) catch |err| switch (err) { error.AnalysisFail => unreachable, else => |e| return e, }; return self.emitStringLiteral(src, bytes); }, else => |t| std.debug.panic("TODO implement emitTypedValue for pointer to {}", .{@tagName(t)}), } }, .ComptimeInt => return self.emitComptimeIntVal(src, typed_value.val), .Int => { const as_inst = try self.arena.allocator.create(Inst.BinOp); as_inst.* = .{ .base = .{ .tag = .as, .src = src, }, .positionals = .{ .lhs = (try self.emitType(src, typed_value.ty)).inst, .rhs = (try self.emitComptimeIntVal(src, typed_value.val)).inst, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&as_inst.base); }, .Type => { const ty = try typed_value.val.toType(&self.arena.allocator); return self.emitType(src, ty); }, .Fn => { const module_fn = typed_value.val.cast(Value.Payload.Function).?.func; return self.emitFn(module_fn, src, typed_value.ty); }, .Array => { // TODO more checks to make sure this can be emitted as a string literal //const array_elem_type = ptr_elem_type.elemType(); //if (array_elem_type.eql(Type.initTag(.u8)) and // ptr_elem_type.hasSentinel(Value.initTag(.zero))) //{ //} const bytes = typed_value.val.toAllocatedBytes(allocator) catch |err| switch (err) { error.AnalysisFail => unreachable, else => |e| return e, }; const str_inst = try self.arena.allocator.create(Inst.Str); str_inst.* = .{ .base = .{ .src = src, .tag = Inst.Str.base_tag, }, .positionals = .{ .bytes = bytes, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&str_inst.base); }, .Void => return self.emitPrimitive(src, .void_value), .Bool => if (typed_value.val.toBool()) return self.emitPrimitive(src, .@"true") else return self.emitPrimitive(src, .@"false"), .EnumLiteral => { const enum_literal = @fieldParentPtr(Value.Payload.Bytes, "base", typed_value.val.ptr_otherwise); const inst = try self.arena.allocator.create(Inst.Str); inst.* = .{ .base = .{ .src = src, .tag = .enum_literal, }, .positionals = .{ .bytes = enum_literal.data, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&inst.base); }, else => |t| std.debug.panic("TODO implement emitTypedValue for {}", .{@tagName(t)}), } } fn emitNoOp(self: *EmitZIR, src: usize, old_inst: *ir.Inst.NoOp, tag: Inst.Tag) Allocator.Error!*Inst { const new_inst = try self.arena.allocator.create(Inst.NoOp); new_inst.* = .{ .base = .{ .src = src, .tag = tag, }, .positionals = .{}, .kw_args = .{}, }; return &new_inst.base; } fn emitUnOp( self: *EmitZIR, src: usize, new_body: ZirBody, old_inst: *ir.Inst.UnOp, tag: Inst.Tag, ) Allocator.Error!*Inst { const new_inst = try self.arena.allocator.create(Inst.UnOp); new_inst.* = .{ .base = .{ .src = src, .tag = tag, }, .positionals = .{ .operand = try self.resolveInst(new_body, old_inst.operand), }, .kw_args = .{}, }; return &new_inst.base; } fn emitBinOp( self: *EmitZIR, src: usize, new_body: ZirBody, old_inst: *ir.Inst.BinOp, tag: Inst.Tag, ) Allocator.Error!*Inst { const new_inst = try self.arena.allocator.create(Inst.BinOp); new_inst.* = .{ .base = .{ .src = src, .tag = tag, }, .positionals = .{ .lhs = try self.resolveInst(new_body, old_inst.lhs), .rhs = try self.resolveInst(new_body, old_inst.rhs), }, .kw_args = .{}, }; return &new_inst.base; } fn emitCast( self: *EmitZIR, src: usize, new_body: ZirBody, old_inst: *ir.Inst.UnOp, tag: Inst.Tag, ) Allocator.Error!*Inst { const new_inst = try self.arena.allocator.create(Inst.BinOp); new_inst.* = .{ .base = .{ .src = src, .tag = tag, }, .positionals = .{ .lhs = (try self.emitType(old_inst.base.src, old_inst.base.ty)).inst, .rhs = try self.resolveInst(new_body, old_inst.operand), }, .kw_args = .{}, }; return &new_inst.base; } fn emitBody( self: *EmitZIR, body: ir.Body, inst_table: *std.AutoHashMap(*ir.Inst, *Inst), instructions: *std.ArrayList(*Inst), ) Allocator.Error!void { const new_body = ZirBody{ .inst_table = inst_table, .instructions = instructions, }; for (body.instructions) |inst| { const new_inst = switch (inst.tag) { .constant => unreachable, // excluded from function bodies .breakpoint => try self.emitNoOp(inst.src, inst.castTag(.breakpoint).?, .breakpoint), .unreach => try self.emitNoOp(inst.src, inst.castTag(.unreach).?, .unreach_nocheck), .retvoid => try self.emitNoOp(inst.src, inst.castTag(.retvoid).?, .returnvoid), .dbg_stmt => try self.emitNoOp(inst.src, inst.castTag(.dbg_stmt).?, .dbg_stmt), .not => try self.emitUnOp(inst.src, new_body, inst.castTag(.not).?, .boolnot), .ret => try self.emitUnOp(inst.src, new_body, inst.castTag(.ret).?, .@"return"), .ptrtoint => try self.emitUnOp(inst.src, new_body, inst.castTag(.ptrtoint).?, .ptrtoint), .isnull => try self.emitUnOp(inst.src, new_body, inst.castTag(.isnull).?, .isnull), .isnonnull => try self.emitUnOp(inst.src, new_body, inst.castTag(.isnonnull).?, .isnonnull), .iserr => try self.emitUnOp(inst.src, new_body, inst.castTag(.iserr).?, .iserr), .load => try self.emitUnOp(inst.src, new_body, inst.castTag(.load).?, .deref), .ref => try self.emitUnOp(inst.src, new_body, inst.castTag(.ref).?, .ref), .unwrap_optional => try self.emitUnOp(inst.src, new_body, inst.castTag(.unwrap_optional).?, .unwrap_optional_unsafe), .wrap_optional => try self.emitCast(inst.src, new_body, inst.castTag(.wrap_optional).?, .as), .add => try self.emitBinOp(inst.src, new_body, inst.castTag(.add).?, .add), .sub => try self.emitBinOp(inst.src, new_body, inst.castTag(.sub).?, .sub), .store => try self.emitBinOp(inst.src, new_body, inst.castTag(.store).?, .store), .cmp_lt => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_lt).?, .cmp_lt), .cmp_lte => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_lte).?, .cmp_lte), .cmp_eq => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_eq).?, .cmp_eq), .cmp_gte => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_gte).?, .cmp_gte), .cmp_gt => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_gt).?, .cmp_gt), .cmp_neq => try self.emitBinOp(inst.src, new_body, inst.castTag(.cmp_neq).?, .cmp_neq), .booland => try self.emitBinOp(inst.src, new_body, inst.castTag(.booland).?, .booland), .boolor => try self.emitBinOp(inst.src, new_body, inst.castTag(.boolor).?, .boolor), .bitcast => try self.emitCast(inst.src, new_body, inst.castTag(.bitcast).?, .bitcast), .intcast => try self.emitCast(inst.src, new_body, inst.castTag(.intcast).?, .intcast), .floatcast => try self.emitCast(inst.src, new_body, inst.castTag(.floatcast).?, .floatcast), .alloc => blk: { const new_inst = try self.arena.allocator.create(Inst.UnOp); new_inst.* = .{ .base = .{ .src = inst.src, .tag = .alloc, }, .positionals = .{ .operand = (try self.emitType(inst.src, inst.ty)).inst, }, .kw_args = .{}, }; break :blk &new_inst.base; }, .arg => blk: { const old_inst = inst.castTag(.arg).?; const new_inst = try self.arena.allocator.create(Inst.Arg); new_inst.* = .{ .base = .{ .src = inst.src, .tag = .arg, }, .positionals = .{ .name = try self.arena.allocator.dupe(u8, mem.spanZ(old_inst.name)), }, .kw_args = .{}, }; break :blk &new_inst.base; }, .block => blk: { const old_inst = inst.castTag(.block).?; const new_inst = try self.arena.allocator.create(Inst.Block); try self.block_table.put(old_inst, new_inst); var block_body = std.ArrayList(*Inst).init(self.allocator); defer block_body.deinit(); try self.emitBody(old_inst.body, inst_table, &block_body); new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.Block.base_tag, }, .positionals = .{ .body = .{ .instructions = block_body.toOwnedSlice() }, }, .kw_args = .{}, }; break :blk &new_inst.base; }, .loop => blk: { const old_inst = inst.castTag(.loop).?; const new_inst = try self.arena.allocator.create(Inst.Loop); try self.loop_table.put(old_inst, new_inst); var loop_body = std.ArrayList(*Inst).init(self.allocator); defer loop_body.deinit(); try self.emitBody(old_inst.body, inst_table, &loop_body); new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.Loop.base_tag, }, .positionals = .{ .body = .{ .instructions = loop_body.toOwnedSlice() }, }, .kw_args = .{}, }; break :blk &new_inst.base; }, .brvoid => blk: { const old_inst = inst.cast(ir.Inst.BrVoid).?; const new_block = self.block_table.get(old_inst.block).?; const new_inst = try self.arena.allocator.create(Inst.BreakVoid); new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.BreakVoid.base_tag, }, .positionals = .{ .block = new_block, }, .kw_args = .{}, }; break :blk &new_inst.base; }, .br => blk: { const old_inst = inst.castTag(.br).?; const new_block = self.block_table.get(old_inst.block).?; const new_inst = try self.arena.allocator.create(Inst.Break); new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.Break.base_tag, }, .positionals = .{ .block = new_block, .operand = try self.resolveInst(new_body, old_inst.operand), }, .kw_args = .{}, }; break :blk &new_inst.base; }, .call => blk: { const old_inst = inst.castTag(.call).?; const new_inst = try self.arena.allocator.create(Inst.Call); const args = try self.arena.allocator.alloc(*Inst, old_inst.args.len); for (args) |*elem, i| { elem.* = try self.resolveInst(new_body, old_inst.args[i]); } new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.Call.base_tag, }, .positionals = .{ .func = try self.resolveInst(new_body, old_inst.func), .args = args, }, .kw_args = .{}, }; break :blk &new_inst.base; }, .assembly => blk: { const old_inst = inst.castTag(.assembly).?; const new_inst = try self.arena.allocator.create(Inst.Asm); const inputs = try self.arena.allocator.alloc(*Inst, old_inst.inputs.len); for (inputs) |*elem, i| { elem.* = (try self.emitStringLiteral(inst.src, old_inst.inputs[i])).inst; } const clobbers = try self.arena.allocator.alloc(*Inst, old_inst.clobbers.len); for (clobbers) |*elem, i| { elem.* = (try self.emitStringLiteral(inst.src, old_inst.clobbers[i])).inst; } const args = try self.arena.allocator.alloc(*Inst, old_inst.args.len); for (args) |*elem, i| { elem.* = try self.resolveInst(new_body, old_inst.args[i]); } new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.Asm.base_tag, }, .positionals = .{ .asm_source = (try self.emitStringLiteral(inst.src, old_inst.asm_source)).inst, .return_type = (try self.emitType(inst.src, inst.ty)).inst, }, .kw_args = .{ .@"volatile" = old_inst.is_volatile, .output = if (old_inst.output) |o| (try self.emitStringLiteral(inst.src, o)).inst else null, .inputs = inputs, .clobbers = clobbers, .args = args, }, }; break :blk &new_inst.base; }, .condbr => blk: { const old_inst = inst.castTag(.condbr).?; var then_body = std.ArrayList(*Inst).init(self.allocator); var else_body = std.ArrayList(*Inst).init(self.allocator); defer then_body.deinit(); defer else_body.deinit(); const then_deaths = try self.arena.allocator.alloc(*Inst, old_inst.thenDeaths().len); const else_deaths = try self.arena.allocator.alloc(*Inst, old_inst.elseDeaths().len); for (old_inst.thenDeaths()) |death, i| { then_deaths[i] = try self.resolveInst(new_body, death); } for (old_inst.elseDeaths()) |death, i| { else_deaths[i] = try self.resolveInst(new_body, death); } try self.emitBody(old_inst.then_body, inst_table, &then_body); try self.emitBody(old_inst.else_body, inst_table, &else_body); const new_inst = try self.arena.allocator.create(Inst.CondBr); try self.body_metadata.put(&new_inst.positionals.then_body, .{ .deaths = then_deaths }); try self.body_metadata.put(&new_inst.positionals.else_body, .{ .deaths = else_deaths }); new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.CondBr.base_tag, }, .positionals = .{ .condition = try self.resolveInst(new_body, old_inst.condition), .then_body = .{ .instructions = then_body.toOwnedSlice() }, .else_body = .{ .instructions = else_body.toOwnedSlice() }, }, .kw_args = .{}, }; break :blk &new_inst.base; }, .switchbr => blk: { const old_inst = inst.castTag(.switchbr).?; const cases = try self.arena.allocator.alloc(Inst.SwitchBr.Case, old_inst.cases.len); const new_inst = try self.arena.allocator.create(Inst.SwitchBr); new_inst.* = .{ .base = .{ .src = inst.src, .tag = Inst.SwitchBr.base_tag, }, .positionals = .{ .target_ptr = try self.resolveInst(new_body, old_inst.target_ptr), .cases = cases, .items = &[_]*Inst{}, // TODO this should actually be populated .else_body = undefined, // populated below }, .kw_args = .{}, }; var body_tmp = std.ArrayList(*Inst).init(self.allocator); defer body_tmp.deinit(); for (old_inst.cases) |*case, i| { body_tmp.items.len = 0; const case_deaths = try self.arena.allocator.alloc(*Inst, old_inst.caseDeaths(i).len); for (old_inst.caseDeaths(i)) |death, j| { case_deaths[j] = try self.resolveInst(new_body, death); } try self.body_metadata.put(&cases[i].body, .{ .deaths = case_deaths }); try self.emitBody(case.body, inst_table, &body_tmp); const item = (try self.emitTypedValue(inst.src, .{ .ty = old_inst.target_ptr.ty.elemType(), .val = case.item, })).inst; cases[i] = .{ .item = item, .body = .{ .instructions = try self.arena.allocator.dupe(*Inst, body_tmp.items) }, }; } { // else const else_deaths = try self.arena.allocator.alloc(*Inst, old_inst.elseDeaths().len); for (old_inst.elseDeaths()) |death, j| { else_deaths[j] = try self.resolveInst(new_body, death); } try self.body_metadata.put(&new_inst.positionals.else_body, .{ .deaths = else_deaths }); body_tmp.items.len = 0; try self.emitBody(old_inst.else_body, inst_table, &body_tmp); new_inst.positionals.else_body = .{ .instructions = try self.arena.allocator.dupe(*Inst, body_tmp.items), }; } break :blk &new_inst.base; }, .varptr => @panic("TODO"), }; try self.metadata.put(new_inst, .{ .deaths = inst.deaths, .addr = @ptrToInt(inst), }); try instructions.append(new_inst); try inst_table.put(inst, new_inst); } } fn emitType(self: *EmitZIR, src: usize, ty: Type) Allocator.Error!*Decl { switch (ty.tag()) { .i8 => return self.emitPrimitive(src, .i8), .u8 => return self.emitPrimitive(src, .u8), .i16 => return self.emitPrimitive(src, .i16), .u16 => return self.emitPrimitive(src, .u16), .i32 => return self.emitPrimitive(src, .i32), .u32 => return self.emitPrimitive(src, .u32), .i64 => return self.emitPrimitive(src, .i64), .u64 => return self.emitPrimitive(src, .u64), .isize => return self.emitPrimitive(src, .isize), .usize => return self.emitPrimitive(src, .usize), .c_short => return self.emitPrimitive(src, .c_short), .c_ushort => return self.emitPrimitive(src, .c_ushort), .c_int => return self.emitPrimitive(src, .c_int), .c_uint => return self.emitPrimitive(src, .c_uint), .c_long => return self.emitPrimitive(src, .c_long), .c_ulong => return self.emitPrimitive(src, .c_ulong), .c_longlong => return self.emitPrimitive(src, .c_longlong), .c_ulonglong => return self.emitPrimitive(src, .c_ulonglong), .c_longdouble => return self.emitPrimitive(src, .c_longdouble), .c_void => return self.emitPrimitive(src, .c_void), .f16 => return self.emitPrimitive(src, .f16), .f32 => return self.emitPrimitive(src, .f32), .f64 => return self.emitPrimitive(src, .f64), .f128 => return self.emitPrimitive(src, .f128), .anyerror => return self.emitPrimitive(src, .anyerror), else => switch (ty.zigTypeTag()) { .Bool => return self.emitPrimitive(src, .bool), .Void => return self.emitPrimitive(src, .void), .NoReturn => return self.emitPrimitive(src, .noreturn), .Type => return self.emitPrimitive(src, .type), .ComptimeInt => return self.emitPrimitive(src, .comptime_int), .ComptimeFloat => return self.emitPrimitive(src, .comptime_float), .Fn => { const param_types = try self.allocator.alloc(Type, ty.fnParamLen()); defer self.allocator.free(param_types); ty.fnParamTypes(param_types); const emitted_params = try self.arena.allocator.alloc(*Inst, param_types.len); for (param_types) |param_type, i| { emitted_params[i] = (try self.emitType(src, param_type)).inst; } const fntype_inst = try self.arena.allocator.create(Inst.FnType); fntype_inst.* = .{ .base = .{ .src = src, .tag = Inst.FnType.base_tag, }, .positionals = .{ .param_types = emitted_params, .return_type = (try self.emitType(src, ty.fnReturnType())).inst, }, .kw_args = .{ .cc = ty.fnCallingConvention(), }, }; return self.emitUnnamedDecl(&fntype_inst.base); }, .Int => { const info = ty.intInfo(self.old_module.getTarget()); const signed = try self.emitPrimitive(src, switch (info.signedness) { .signed => .@"true", .unsigned => .@"false", }); const bits_payload = try self.arena.allocator.create(Value.Payload.Int_u64); bits_payload.* = .{ .int = info.bits }; const bits = try self.emitComptimeIntVal(src, Value.initPayload(&bits_payload.base)); const inttype_inst = try self.arena.allocator.create(Inst.IntType); inttype_inst.* = .{ .base = .{ .src = src, .tag = Inst.IntType.base_tag, }, .positionals = .{ .signed = signed.inst, .bits = bits.inst, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&inttype_inst.base); }, .Pointer => { if (ty.isSinglePointer()) { const inst = try self.arena.allocator.create(Inst.UnOp); const tag: Inst.Tag = if (ty.isConstPtr()) .single_const_ptr_type else .single_mut_ptr_type; inst.* = .{ .base = .{ .src = src, .tag = tag, }, .positionals = .{ .operand = (try self.emitType(src, ty.elemType())).inst, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&inst.base); } else { std.debug.panic("TODO implement emitType for {}", .{ty}); } }, .Optional => { var buf: Type.Payload.PointerSimple = undefined; const inst = try self.arena.allocator.create(Inst.UnOp); inst.* = .{ .base = .{ .src = src, .tag = .optional_type, }, .positionals = .{ .operand = (try self.emitType(src, ty.optionalChild(&buf))).inst, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&inst.base); }, .Array => { var len_pl = Value.Payload.Int_u64{ .int = ty.arrayLen() }; const len = Value.initPayload(&len_pl.base); const inst = if (ty.sentinel()) |sentinel| blk: { const inst = try self.arena.allocator.create(Inst.ArrayTypeSentinel); inst.* = .{ .base = .{ .src = src, .tag = .array_type, }, .positionals = .{ .len = (try self.emitTypedValue(src, .{ .ty = Type.initTag(.usize), .val = len, })).inst, .sentinel = (try self.emitTypedValue(src, .{ .ty = ty.elemType(), .val = sentinel, })).inst, .elem_type = (try self.emitType(src, ty.elemType())).inst, }, .kw_args = .{}, }; break :blk &inst.base; } else blk: { const inst = try self.arena.allocator.create(Inst.BinOp); inst.* = .{ .base = .{ .src = src, .tag = .array_type, }, .positionals = .{ .lhs = (try self.emitTypedValue(src, .{ .ty = Type.initTag(.usize), .val = len, })).inst, .rhs = (try self.emitType(src, ty.elemType())).inst, }, .kw_args = .{}, }; break :blk &inst.base; }; return self.emitUnnamedDecl(inst); }, else => std.debug.panic("TODO implement emitType for {}", .{ty}), }, } } fn autoName(self: *EmitZIR) ![]u8 { while (true) { const proposed_name = try std.fmt.allocPrint(&self.arena.allocator, "unnamed${}", .{self.next_auto_name}); self.next_auto_name += 1; const gop = try self.names.getOrPut(proposed_name); if (!gop.found_existing) { gop.entry.value = {}; return proposed_name; } } } fn emitPrimitive(self: *EmitZIR, src: usize, tag: Inst.Primitive.Builtin) !*Decl { const gop = try self.primitive_table.getOrPut(tag); if (!gop.found_existing) { const primitive_inst = try self.arena.allocator.create(Inst.Primitive); primitive_inst.* = .{ .base = .{ .src = src, .tag = Inst.Primitive.base_tag, }, .positionals = .{ .tag = tag, }, .kw_args = .{}, }; gop.entry.value = try self.emitUnnamedDecl(&primitive_inst.base); } return gop.entry.value; } fn emitStringLiteral(self: *EmitZIR, src: usize, str: []const u8) !*Decl { const str_inst = try self.arena.allocator.create(Inst.Str); str_inst.* = .{ .base = .{ .src = src, .tag = Inst.Str.base_tag, }, .positionals = .{ .bytes = str, }, .kw_args = .{}, }; return self.emitUnnamedDecl(&str_inst.base); } fn emitUnnamedDecl(self: *EmitZIR, inst: *Inst) !*Decl { const decl = try self.arena.allocator.create(Decl); decl.* = .{ .name = try self.autoName(), .contents_hash = undefined, .inst = inst, }; try self.decls.append(self.allocator, decl); return decl; } }; /// For debugging purposes, like dumpFn but for unanalyzed zir blocks pub fn dumpZir(allocator: *Allocator, kind: []const u8, decl_name: [*:0]const u8, instructions: []*Inst) !void { var fib = std.heap.FixedBufferAllocator.init(&[_]u8{}); var module = Module{ .decls = &[_]*Decl{}, .arena = std.heap.ArenaAllocator.init(&fib.allocator), .metadata = std.AutoHashMap(*Inst, Module.MetaData).init(&fib.allocator), .body_metadata = std.AutoHashMap(*Module.Body, Module.BodyMetaData).init(&fib.allocator), }; var write = Writer{ .module = &module, .inst_table = InstPtrTable.init(allocator), .block_table = std.AutoHashMap(*Inst.Block, []const u8).init(allocator), .loop_table = std.AutoHashMap(*Inst.Loop, []const u8).init(allocator), .arena = std.heap.ArenaAllocator.init(allocator), .indent = 4, .next_instr_index = 0, }; defer write.arena.deinit(); defer write.inst_table.deinit(); defer write.block_table.deinit(); defer write.loop_table.deinit(); try write.inst_table.ensureCapacity(@intCast(u32, instructions.len)); const stderr = std.io.getStdErr().outStream(); try stderr.print("{} {s} {{ // unanalyzed\n", .{ kind, decl_name }); for (instructions) |inst| { const my_i = write.next_instr_index; write.next_instr_index += 1; if (inst.cast(Inst.Block)) |block| { const name = try std.fmt.allocPrint(&write.arena.allocator, "label_{}", .{my_i}); try write.block_table.put(block, name); } else if (inst.cast(Inst.Loop)) |loop| { const name = try std.fmt.allocPrint(&write.arena.allocator, "loop_{}", .{my_i}); try write.loop_table.put(loop, name); } try write.inst_table.putNoClobber(inst, .{ .inst = inst, .index = my_i, .name = "inst" }); try stderr.print(" %{} ", .{my_i}); try write.writeInstToStream(stderr, inst); try stderr.writeByte('\n'); } try stderr.print("}} // {} {s}\n\n", .{ kind, decl_name }); }
src/zir.zig
const aoc = @import("../aoc.zig"); const std = @import("std"); const SnailfishNumber = struct { const Elements = std.ArrayList(struct { number: u8, depth: u8, }); elements: Elements, fn initFromLine(allocator: std.mem.Allocator, line: []const u8) !SnailfishNumber { var snailfish_number = SnailfishNumber { .elements = Elements.init(allocator), }; var depth: u8 = 0; for (line) |c| { switch (c) { '[' => depth += 1, ']' => depth -= 1, ',' => {}, else => try snailfish_number.elements.append(.{ .number = c - '0', .depth = depth - 1 }) } } return snailfish_number; } fn deinit(self: *SnailfishNumber) void { self.elements.deinit(); } fn add(self: *const SnailfishNumber, other: *const SnailfishNumber) !SnailfishNumber { // std.debug.print("{s: <8}", .{" "}); // var asdf: u8 = 0; // while (asdf < 25) : (asdf += 1) { // std.debug.print("{: >4} ", .{asdf}); // } // std.debug.print("\n", .{}); var result = SnailfishNumber { .elements = Elements.init(self.elements.allocator), }; for (self.elements.items) |element| { try result.elements.append(.{ .number = element.number, .depth = element.depth + 1, }); } for (other.elements.items) |element| { try result.elements.append(.{ .number = element.number, .depth = element.depth + 1, }); } blk: while (true) { // Explode for (result.elements.items) |element, idx| { const depth = element.depth; if (depth >= 4 and result.elements.items[idx + 1].depth == depth) { if (idx > 0) { result.elements.items[idx - 1].number += element.number; } if (idx < result.elements.items.len - 2) { result.elements.items[idx + 2].number += result.elements.items[idx + 1].number; } result.elements.items[idx] = .{ .number = 0, .depth = depth - 1, }; _ = result.elements.orderedRemove(idx + 1); // std.debug.print("x {: <2},{: <2} ", .{idx, idx+1}); // result.print(); continue :blk; } } // Split for (result.elements.items) |element, idx| { const number = element.number; if (element.number >= 10) { const depth = element.depth; result.elements.items[idx] = .{ .number = try std.math.divFloor(u8, number, 2), .depth = depth + 1, }; try result.elements.insert(idx + 1, .{ .number = try std.math.divCeil(u8, number, 2), .depth = depth + 1, }); // std.debug.print("s {: <2} ", .{idx}); // result.print(); continue :blk; } } // Done break; } // result.print(); return result; } fn magnitude(self: *const SnailfishNumber, depth: u8, idx: *u8) usize { // std.debug.print("d{} i{}\n", .{depth, idx.*}); const left = @as(usize, 3) * blk: { const element = self.elements.items[idx.*]; break :blk if (element.depth != depth) self.magnitude(depth + 1, idx) else element.number ; }; idx.* += 1; const right = @as(usize, 2) * blk: { const element = self.elements.items[idx.*]; break :blk if (element.depth != depth) self.magnitude(depth + 1, idx) else element.number ; }; // std.debug.print("={}\n", .{left + right}); return left + right; } fn print(self: *const SnailfishNumber) void { for (self.elements.items) |element| { std.debug.print("{: >2}d{} ", .{element.number, element.depth}); } std.debug.print("\n", .{}); } }; pub fn run(problem: *aoc.Problem) !aoc.Solution { var numbers = std.ArrayList(SnailfishNumber).init(problem.allocator); defer { for (numbers.items) |*number| { number.deinit(); } numbers.deinit(); } const total_sum = blk: { var result: ?SnailfishNumber = null; while (problem.line()) |line| { var next = try SnailfishNumber.initFromLine(problem.allocator, line); try numbers.append(next); if (result) |*r| { var next_result = try r.add(&next); r.deinit(); result = next_result; } else { result = try numbers.items[0].add(&next); } } defer result.?.deinit(); var idx: u8 = 0; break :blk result.?.magnitude(0, &idx); }; const max_sum = blk: { var max_sum: usize = 0; var i: u8 = 0; while (i < numbers.items.len) : (i += 1) { var j: u8 = 0; while (j < numbers.items.len) : (j += 1) { if (i == j) { continue; } var result = try numbers.items[i].add(&numbers.items[j]); defer result.deinit(); var idx: u8 = 0; max_sum = std.math.max(max_sum, result.magnitude(0, &idx)); } } break :blk max_sum; }; return problem.solution(total_sum, max_sum); }
src/main/zig/2021/day18.zig
const Target = @import("std").Target; pub const CInt = struct { id: Id, zig_name: []const u8, c_name: []const u8, is_signed: bool, pub const Id = enum { Short, UShort, Int, UInt, Long, ULong, LongLong, ULongLong, }; pub const list = [_]CInt{ CInt{ .id = .Short, .zig_name = "c_short", .c_name = "short", .is_signed = true, }, CInt{ .id = .UShort, .zig_name = "c_ushort", .c_name = "unsigned short", .is_signed = false, }, CInt{ .id = .Int, .zig_name = "c_int", .c_name = "int", .is_signed = true, }, CInt{ .id = .UInt, .zig_name = "c_uint", .c_name = "unsigned int", .is_signed = false, }, CInt{ .id = .Long, .zig_name = "c_long", .c_name = "long", .is_signed = true, }, CInt{ .id = .ULong, .zig_name = "c_ulong", .c_name = "unsigned long", .is_signed = false, }, CInt{ .id = .LongLong, .zig_name = "c_longlong", .c_name = "long long", .is_signed = true, }, CInt{ .id = .ULongLong, .zig_name = "c_ulonglong", .c_name = "unsigned long long", .is_signed = false, }, }; pub fn sizeInBits(cint: CInt, self: Target) u32 { const arch = self.cpu.arch; switch (self.os.tag) { .freestanding, .other => switch (self.cpu.arch) { .msp430 => switch (cint.id) { .Short, .UShort, .Int, .UInt, => return 16, .Long, .ULong, => return 32, .LongLong, .ULongLong, => return 64, }, else => switch (cint.id) { .Short, .UShort, => return 16, .Int, .UInt, => return 32, .Long, .ULong, => return self.cpu.arch.ptrBitWidth(), .LongLong, .ULongLong, => return 64, }, }, .linux, .macosx, .freebsd, .openbsd, => switch (cint.id) { .Short, .UShort, => return 16, .Int, .UInt, => return 32, .Long, .ULong, => return self.cpu.arch.ptrBitWidth(), .LongLong, .ULongLong, => return 64, }, .windows, .uefi => switch (cint.id) { .Short, .UShort, => return 16, .Int, .UInt, => return 32, .Long, .ULong, .LongLong, .ULongLong, => return 64, }, .ananas, .cloudabi, .dragonfly, .fuchsia, .ios, .kfreebsd, .lv2, .netbsd, .solaris, .haiku, .minix, .rtems, .nacl, .cnk, .aix, .cuda, .nvcl, .amdhsa, .ps4, .elfiamcu, .tvos, .watchos, .mesa3d, .contiki, .amdpal, .hermit, .hurd, .wasi, .emscripten, => @panic("TODO specify the C integer type sizes for this OS"), } } };
src-self-hosted/c_int.zig
const std = @import("std"); const mem = std.mem; const Format = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 173, hi: u21 = 917631, pub fn init(allocator: *mem.Allocator) !Format { var instance = Format{ .allocator = allocator, .array = try allocator.alloc(bool, 917459), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; index = 1363; while (index <= 1368) : (index += 1) { instance.array[index] = true; } instance.array[1391] = true; instance.array[1584] = true; instance.array[1634] = true; instance.array[2101] = true; instance.array[5985] = true; index = 8030; while (index <= 8034) : (index += 1) { instance.array[index] = true; } index = 8061; while (index <= 8065) : (index += 1) { instance.array[index] = true; } index = 8115; while (index <= 8119) : (index += 1) { instance.array[index] = true; } index = 8121; while (index <= 8130) : (index += 1) { instance.array[index] = true; } instance.array[65106] = true; index = 65356; while (index <= 65358) : (index += 1) { instance.array[index] = true; } instance.array[69648] = true; instance.array[69664] = true; index = 78723; while (index <= 78731) : (index += 1) { instance.array[index] = true; } index = 113651; while (index <= 113654) : (index += 1) { instance.array[index] = true; } index = 118982; while (index <= 118989) : (index += 1) { instance.array[index] = true; } instance.array[917332] = true; index = 917363; while (index <= 917458) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *Format) void { self.allocator.free(self.array); } // isFormat checks if cp is of the kind Format. pub fn isFormat(self: Format, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedGeneralCategory/Format.zig
const wlr = @import("../wlroots.zig"); const os = @import("std").os; const pixman = @import("pixman"); const wayland = @import("wayland"); const wl = wayland.server.wl; pub const Surface = extern struct { pub const State = extern struct { pub const field = struct { pub const buffer = 1 << 0; pub const surface_damage = 1 << 1; pub const buffer_damage = 1 << 2; pub const opaque_region = 1 << 3; pub const input_region = 1 << 4; pub const transform = 1 << 5; pub const scale = 1 << 6; pub const frame_callback_list = 1 << 7; pub const viewport = 1 << 8; }; /// This is a bitfield of State.field members committed: u32, buffer_resource: ?*wl.Buffer, dx: i32, dy: i32, surface_damage: pixman.Region32, buffer_damage: pixman.Region32, @"opaque": pixman.Region32, input: pixman.Region32, transform: wl.Output.Transform, scale: i32, frame_callback_list: wl.list.Head(wl.Callback, null), width: c_int, height: c_int, buffer_width: c_int, buffer_height: c_int, viewport: extern struct { has_src: bool, has_dst: bool, src: wlr.FBox, dst_width: c_int, dst_height: c_int, }, buffer_destroy: wl.Listener(*wl.Buffer), }; pub const Role = extern struct { name: [*:0]const u8, commit: ?fn (surface: *Surface) callconv(.C) void, precommit: ?fn (surface: *Surface) callconv(.C) void, }; resource: *wl.Surface, renderer: *wlr.Renderer, buffer: ?*wlr.ClientBuffer, sx: c_int, sy: c_int, buffer_damage: pixman.Region32, opaque_region: pixman.Region32, input_region: pixman.Region32, current: State, pending: State, previous: State, role: ?*const Role, role_data: ?*c_void, events: extern struct { commit: wl.Signal(*wlr.Surface), new_subsurface: wl.Signal(*wlr.Subsurface), destroy: wl.Signal(*wlr.Surface), }, subsurfaces: wl.list.Head(Subsurface, "parent_link"), subsurface_pending_list: wl.list.Head(Subsurface, "parent_pending_link"), renderer_destroy: wl.Listener(*wlr.Renderer), data: usize, extern fn wlr_surface_create( client: *wl.Client, version: u32, id: u32, renderer: *wlr.Renderer, resource_list: ?*wl.list.Head(wl.Surface, null), ) ?*Surface; pub fn create( client: *wl.Client, version: u32, id: u32, renderer: *wlr.Renderer, resource_list: ?*wl.list.Head(wl.Surface, null), ) !*Surface { return wlr_surface_create(client, version, id, renderer, resource_list) orelse error.OutOfMemory; } extern fn wlr_surface_set_role( surface: *Surface, role: *const Role, role_data: ?*c_void, error_resource: ?*wl.Resource, error_code: u32, ) bool; pub const setRole = wlr_surface_set_role; // Just check if Surface.buffer is null, that's all this function does extern fn wlr_surface_has_buffer(surface: *Surface) bool; extern fn wlr_surface_get_texture(surface: *Surface) ?*wlr.Texture; pub const getTexture = wlr_surface_get_texture; extern fn wlr_surface_get_root_surface(surface: *Surface) ?*Surface; pub const getRootSurface = wlr_surface_get_root_surface; extern fn wlr_surface_point_accepts_input(surface: *Surface, sx: f64, sy: f64) bool; pub const pointAcceptsInput = wlr_surface_point_accepts_input; extern fn wlr_surface_surface_at(surface: *Surface, sx: f64, sy: f64, sub_x: *f64, sub_y: *f64) ?*Surface; pub const surfaceAt = wlr_surface_surface_at; extern fn wlr_surface_send_enter(surface: *Surface, output: *wlr.Output) void; pub const sendEnter = wlr_surface_send_enter; extern fn wlr_surface_send_leave(surface: *Surface, output: *wlr.Output) void; pub const sendLeave = wlr_surface_send_leave; extern fn wlr_surface_send_frame_done(surface: *Surface, when: *const os.timespec) void; pub const sendFrameDone = wlr_surface_send_frame_done; extern fn wlr_surface_get_extends(surface: *Surface, box: *wlr.Box) void; pub const getExtends = wlr_surface_get_extends; extern fn wlr_surface_from_resource(resource: *wl.Surface) *Surface; pub const fromWlSurface = wlr_surface_from_resource; extern fn wlr_surface_for_each_surface( surface: *Surface, iterator: fn (surface: *Surface, sx: c_int, sy: c_int, data: ?*c_void) callconv(.C) void, user_data: ?*c_void, ) void; pub inline fn forEachSurface( surface: *Surface, comptime T: type, iterator: fn (surface: *Surface, sx: c_int, sy: c_int, data: T) callconv(.C) void, data: T, ) void { wlr_surface_for_each_surface( surface, @ptrCast(fn (surface: *Surface, sx: c_int, sy: c_int, data: ?*c_void) callconv(.C) void, iterator), data, ); } extern fn wlr_surface_get_effective_damage(surface: *Surface, damage: *pixman.Region32) void; pub const getEffectiveDamage = wlr_surface_get_effective_damage; extern fn wlr_surface_get_buffer_source_box(surface: *Surface, box: *wlr.FBox) void; pub const getBufferSourceBox = wlr_surface_get_buffer_source_box; extern fn wlr_surface_accepts_touch(seat: *wlr.Seat, surface: *Surface) bool; pub fn acceptsTouch(surface: *Surface, seat: *wlr.Seat) bool { return wlr_surface_accepts_touch(seat, surface); } extern fn wlr_surface_is_xdg_surface(surface: *Surface) bool; pub const isXdgSurface = wlr_surface_is_xdg_surface; extern fn wlr_surface_is_layer_surface(surface: *Surface) bool; pub const isLayerSurface = wlr_surface_is_layer_surface; extern fn wlr_surface_is_xwayland_surface(surface: *Surface) bool; pub const isXWaylandSurface = wlr_surface_is_xwayland_surface; }; pub const Subsurface = extern struct { pub const State = extern struct { x: i32, y: i32, }; resource: *wl.Subsurface, surface: *Surface, parent: ?*Surface, current: State, pending: State, cached: Surface.State, has_cache: bool, synchronized: bool, reordered: bool, mapped: bool, /// Surface.subsurfaces parent_link: wl.list.Link, /// Surface.subsurface_pending_list parent_pending_link: wl.list.Link, surface_destroy: wl.Listener(*Surface), parent_destroy: wl.Listener(*Surface), events: extern struct { destroy: wl.Signal(*Subsurface), map: wl.Signal(*Subsurface), unmap: wl.Signal(*Subsurface), }, data: usize, extern fn wlr_subsurface_create( surface: *Surface, parent: *Surface, version: u32, id: u32, resource_list: ?*wl.list.Head(wl.Subsurface, null), ) ?*Subsurface; pub fn create( surface: *Surface, parent: *Surface, version: u32, id: u32, resource_list: ?*wl.list.Head(wl.Subsurface, null), ) !*Subsurface { return wlr_subsurface_create(surface, parent, version, id, resource_list) orelse error.OutOfMemory; } };
src/types/surface.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const assert = std.debug.assert; pub const main = tools.defaultMain("2021/day21.txt", run); pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { // var arena_alloc = std.heap.ArenaAllocator.init(gpa); // defer arena_alloc.deinit(); // const arena = arena_alloc.allocator(); var it = std.mem.tokenize(u8, input, "\n"); const player1_start_pos = if (tools.match_pattern("Player 1 starting position: {}", it.next().?)) |val| @intCast(u4, val[0].imm - 1) else unreachable; const player2_start_pos = if (tools.match_pattern("Player 2 starting position: {}", it.next().?)) |val| @intCast(u4, val[0].imm - 1) else unreachable; const ans1 = ans: { var scores = [2]u32{ 0, 0 }; var die: u16 = 1; var positions = [2]u4{ player1_start_pos, player2_start_pos }; var turn: u1 = 0; var roll_count: u32 = 0; const die_faces = 100; const score_win = 1000; while (scores[0] < score_win and scores[1] < score_win) { const roll = (((die - 1) % die_faces) + 1) + (((die + 1 - 1) % die_faces) + 1) + (((die + 2 - 1) % die_faces) + 1); die = ((die + 3 - 1) % die_faces + 1); roll_count += 3; positions[turn] = @intCast(u4, (positions[turn] + roll) % 10); scores[turn] += (positions[turn] + 1); trace("player{}, rolls {}, pos={}, score={}\n", .{ turn, roll, positions[turn] + 1, scores[turn] }); turn +%= 1; } break :ans roll_count * scores[turn]; }; const ans2 = ans: { const victory_score = 21; const cardinal = try gpa.create([42][victory_score + 10][victory_score + 10][10][10]u64); defer gpa.destroy(cardinal); //var cardinal = std.mem.zeroes([42][victory_score+10][victory_score+10][10][10]u64); @memset(@ptrCast([*]u8, cardinal), 0, @sizeOf(@TypeOf(cardinal.*))); cardinal[0][0][0][player1_start_pos][player2_start_pos] = 1; const rolls = [_]struct { score: u8, nb: u8 }{ .{ .score = 3, .nb = 1 }, .{ .score = 4, .nb = 3 }, .{ .score = 5, .nb = 6 }, .{ .score = 6, .nb = 7 }, .{ .score = 7, .nb = 6 }, .{ .score = 8, .nb = 3 }, .{ .score = 9, .nb = 1 }, }; var wins1: u128 = 0; var wins2: u128 = 0; var turn: u32 = 1; while (turn < 42) : (turn += 1) { for ([_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }) |pos1| { for ([_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }) |pos2| { var score1: u32 = 0; while (score1 <= victory_score + 9) : (score1 += 1) { var score2: u32 = 0; while (score2 <= victory_score + 9) : (score2 += 1) { for (rolls) |roll| { const prevpos1 = (pos1 + 10 - roll.score) % 10; const prevpos2 = (pos2 + 10 - roll.score) % 10; if (score1 >= (pos1 + 1) and (turn % 2 == 1)) { const prevscore1 = score1 - (pos1 + 1); if (prevscore1 < victory_score and score2 < victory_score) cardinal[turn][score1][score2][pos1][pos2] += cardinal[turn - 1][prevscore1][score2][prevpos1][pos2] * roll.nb; } if (score2 >= (pos2 + 1) and (turn % 2 == 0)) { const prevscore2 = score2 - (pos2 + 1); if (prevscore2 < victory_score and score1 < victory_score) cardinal[turn][score1][score2][pos1][pos2] += cardinal[turn - 1][score1][prevscore2][pos1][prevpos2] * roll.nb; } } if (cardinal[turn][score1][score2][pos1][pos2] > 0) trace("card[turn: {d}][score1: {d}][score2: {d}][p1: {d}][p2: {d}]={d}\n", .{ turn, score1, score2, pos1, pos2, cardinal[turn][score1][score2][pos1][pos2] }); wins1 += @boolToInt(score1 >= victory_score and score2 < victory_score) * cardinal[turn][score1][score2][pos1][pos2]; wins2 += @boolToInt(score1 < victory_score and score2 >= victory_score) * cardinal[turn][score1][score2][pos1][pos2]; } } } } } break :ans @maximum(wins1, wins2); }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans1}), try std.fmt.allocPrint(gpa, "{}", .{ans2}), }; } test { { const res = try run( \\Player 1 starting position: 4 \\Player 2 starting position: 8 , std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("739785", res[0]); try std.testing.expectEqualStrings("444356092776315", res[1]); } }
2021/day21.zig
const std = @import("std"); const fmt = std.fmt; const Allocator = std.mem.Allocator; const testing = std.testing; /// Parses the different types of Redis strings and keeps /// track of the string metadata information when present. /// Useful to know when Redis is replying with a verbatim /// markdown string, for example. /// /// Requires an allocator, so it can only be used with `sendAlloc`. pub const Verbatim = struct { format: Format, string: []u8, pub const Format = union(enum) { Simple: void, Err: void, Verbatim: [3]u8, }; pub const Redis = struct { pub const Parser = struct { pub fn parse(_: u8, comptime _: type, _: anytype) !Verbatim { @compileError("Verbatim requires an allocator, use `parseAlloc`."); } pub fn destroy(self: Verbatim, comptime _: type, allocator: Allocator) void { allocator.free(self.string); } pub fn parseAlloc(tag: u8, comptime rootParser: type, allocator: Allocator, msg: anytype) !Verbatim { switch (tag) { else => return error.DecodingError, '-', '!' => { try rootParser.parseFromTag(void, tag, msg); return error.GotErrorReply; }, '$', '+' => return Verbatim{ .format = Format{ .Simple = {} }, .string = try rootParser.parseAllocFromTag([]u8, tag, allocator, msg), }, '=' => { // TODO: write real implementation var buf: [100]u8 = undefined; var end: usize = 0; for (buf) |*elem, i| { const ch = try msg.readByte(); elem.* = ch; if (ch == '\r') { end = i; break; } } try msg.skipBytes(1, .{}); var size = try fmt.parseInt(usize, buf[0..end], 10); // We must consider the case in which a malformed // verbatim string is received. By the protocol standard // a verbatim string must start with a `<3 letter type>:` // prefix, but since modules will be able to produce // this kind of data, we should protect ourselves // from potential errors. var format: Format = undefined; if (size >= 4) { format = Format{ .Verbatim = [3]u8{ try msg.readByte(), try msg.readByte(), try msg.readByte(), }, }; // Skip the `:` character, subtract what we consumed try msg.skipBytes(1, .{}); size -= 4; } else { format = Format{ .Err = {} }; } var res = try allocator.alloc(u8, size); errdefer allocator.free(res); try msg.readNoEof(res[0..size]); try msg.skipBytes(2, .{}); return Verbatim{ .format = format, .string = res }; }, } } }; }; }; test "verbatim" { const parser = @import("../parser.zig").RESP3Parser; const allocator = std.heap.page_allocator; { const reply = try Verbatim.Redis.Parser.parseAlloc('+', parser, allocator, MakeSimpleString().reader()); try testing.expectEqualSlices(u8, "Yayyyy I'm a string!", reply.string); switch (reply.format) { else => unreachable, .Simple => {}, } } { const reply = try Verbatim.Redis.Parser.parseAlloc('$', parser, allocator, MakeBlobString().reader()); try testing.expectEqualSlices(u8, "Hello World!", reply.string); switch (reply.format) { else => unreachable, .Simple => {}, } } { const reply = try Verbatim.Redis.Parser.parseAlloc('=', parser, allocator, MakeVerbatimString().reader()); try testing.expectEqualSlices(u8, "Oh hello there!", reply.string); switch (reply.format) { else => unreachable, .Verbatim => |format| try testing.expectEqualSlices(u8, "txt", &format), } } { const reply = try Verbatim.Redis.Parser.parseAlloc('=', parser, allocator, MakeBadVerbatimString().reader()); try testing.expectEqualSlices(u8, "t", reply.string); switch (reply.format) { else => unreachable, .Err => {}, } } { const reply = try Verbatim.Redis.Parser.parseAlloc('=', parser, allocator, MakeBadVerbatimString2().reader()); try testing.expectEqualSlices(u8, "", reply.string); switch (reply.format) { else => unreachable, .Verbatim => |format| try testing.expectEqualSlices(u8, "mkd", &format), } } } fn MakeSimpleString() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("+Yayyyy I'm a string!\r\n"[1..]); } fn MakeBlobString() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("$12\r\nHello World!\r\n"[1..]); } fn MakeVerbatimString() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("=19\r\ntxt:Oh hello there!\r\n"[1..]); } fn MakeBadVerbatimString() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("=1\r\nt\r\n"[1..]); } fn MakeBadVerbatimString2() std.io.FixedBufferStream([]const u8) { return std.io.fixedBufferStream("=4\r\nmkd:\r\n"[1..]); }
src/types/verbatim.zig
const std = @import("std"); const c = @import("c.zig"); const shaderc = @import("shaderc.zig"); pub const Preview = struct { const Self = @This(); device: c.WGPUDeviceId, queue: c.WGPUQueueId, // We render into tex[0] in tiles to keep up a good framerate, then // copy to tex[1] to render the complete image without tearing tex: [2]c.WGPUTextureId, tex_view: [2]c.WGPUTextureViewId, tex_size: c.WGPUExtent3d, bind_group: c.WGPUBindGroupId, uniform_buffer: c.WGPUBufferId, render_pipeline: c.WGPURenderPipelineId, start_time: i64, uniforms: c.fpPreviewUniforms, draw_continuously: bool, pub fn init( alloc: *std.mem.Allocator, device: c.WGPUDeviceId, frag: []const u32, draw_continuously: bool, ) !Preview { var arena = std.heap.ArenaAllocator.init(alloc); const tmp_alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); // Build the shaders using shaderc const vert_spv = shaderc.build_shader_from_file(tmp_alloc, "shaders/preview.vert") catch { std.debug.panic("Could not build preview.vert", .{}); }; const vert_shader = c.wgpu_device_create_shader_module( device, (c.WGPUShaderSource){ .bytes = vert_spv.ptr, .length = vert_spv.len, }, ); defer c.wgpu_shader_module_destroy(vert_shader); const frag_shader = c.wgpu_device_create_shader_module( device, (c.WGPUShaderSource){ .bytes = frag.ptr, .length = frag.len, }, ); defer c.wgpu_shader_module_destroy(frag_shader); //////////////////////////////////////////////////////////////////////////////// // Uniform buffers const uniform_buffer = c.wgpu_device_create_buffer( device, &(c.WGPUBufferDescriptor){ .label = "Uniforms", .size = @sizeOf(c.fpPreviewUniforms), .usage = c.WGPUBufferUsage_UNIFORM | c.WGPUBufferUsage_COPY_DST, .mapped_at_creation = false, }, ); //////////////////////////////////////////////////////////////////////////////// const bind_group_layout_entries = [_]c.WGPUBindGroupLayoutEntry{ (c.WGPUBindGroupLayoutEntry){ .binding = 0, .visibility = c.WGPUShaderStage_VERTEX | c.WGPUShaderStage_FRAGMENT, .ty = c.WGPUBindingType_UniformBuffer, .has_dynamic_offset = false, .min_buffer_binding_size = 0, .multisampled = undefined, .view_dimension = undefined, .texture_component_type = undefined, .storage_texture_format = undefined, .count = undefined, }, }; const bind_group_layout = c.wgpu_device_create_bind_group_layout( device, &(c.WGPUBindGroupLayoutDescriptor){ .label = "bind group layout", .entries = &bind_group_layout_entries, .entries_length = bind_group_layout_entries.len, }, ); defer c.wgpu_bind_group_layout_destroy(bind_group_layout); const bind_group_entries = [_]c.WGPUBindGroupEntry{ (c.WGPUBindGroupEntry){ .binding = 0, .buffer = uniform_buffer, .offset = 0, .size = @sizeOf(c.fpPreviewUniforms), .sampler = 0, // None .texture_view = 0, // None }, }; const bind_group = c.wgpu_device_create_bind_group( device, &(c.WGPUBindGroupDescriptor){ .label = "bind group", .layout = bind_group_layout, .entries = &bind_group_entries, .entries_length = bind_group_entries.len, }, ); const bind_group_layouts = [_]c.WGPUBindGroupId{bind_group_layout}; // Render pipelines (?!?) const pipeline_layout = c.wgpu_device_create_pipeline_layout( device, &(c.WGPUPipelineLayoutDescriptor){ .bind_group_layouts = &bind_group_layouts, .bind_group_layouts_length = bind_group_layouts.len, }, ); defer c.wgpu_pipeline_layout_destroy(pipeline_layout); const render_pipeline = c.wgpu_device_create_render_pipeline( device, &(c.WGPURenderPipelineDescriptor){ .layout = pipeline_layout, .vertex_stage = (c.WGPUProgrammableStageDescriptor){ .module = vert_shader, .entry_point = "main", }, .fragment_stage = &(c.WGPUProgrammableStageDescriptor){ .module = frag_shader, .entry_point = "main", }, .rasterization_state = &(c.WGPURasterizationStateDescriptor){ .front_face = c.WGPUFrontFace_Ccw, .cull_mode = c.WGPUCullMode_None, .depth_bias = 0, .depth_bias_slope_scale = 0.0, .depth_bias_clamp = 0.0, }, .primitive_topology = c.WGPUPrimitiveTopology_TriangleList, .color_states = &(c.WGPUColorStateDescriptor){ .format = c.WGPUTextureFormat_Bgra8Unorm, .alpha_blend = (c.WGPUBlendDescriptor){ .src_factor = c.WGPUBlendFactor_One, .dst_factor = c.WGPUBlendFactor_Zero, .operation = c.WGPUBlendOperation_Add, }, .color_blend = (c.WGPUBlendDescriptor){ .src_factor = c.WGPUBlendFactor_One, .dst_factor = c.WGPUBlendFactor_Zero, .operation = c.WGPUBlendOperation_Add, }, .write_mask = c.WGPUColorWrite_ALL, }, .color_states_length = 1, .depth_stencil_state = null, .vertex_state = (c.WGPUVertexStateDescriptor){ .index_format = c.WGPUIndexFormat_Uint16, .vertex_buffers = null, .vertex_buffers_length = 0, }, .sample_count = 1, .sample_mask = 0, .alpha_to_coverage_enabled = false, }, ); const start_time = std.time.milliTimestamp(); return Self{ .device = device, .queue = c.wgpu_device_get_default_queue(device), .render_pipeline = render_pipeline, .uniform_buffer = uniform_buffer, .bind_group = bind_group, .start_time = start_time, .draw_continuously = draw_continuously, // Assigned in set_size below .tex = undefined, .tex_view = undefined, .tex_size = undefined, .uniforms = .{ .iResolution = .{ .x = 0, .y = 0, .z = 0 }, .iTime = 0.0, .iMouse = .{ .x = 0, .y = 0, .z = 0, .w = 0 }, ._tiles_per_side = 1, ._tile_num = 0, }, }; } fn destroy_textures(self: *const Self) void { // If the texture was created, then destroy it if (self.uniforms.iResolution.x != 0) { for (self.tex) |t| { c.wgpu_texture_destroy(t); } for (self.tex_view) |t| { c.wgpu_texture_view_destroy(t); } } } pub fn adjust_tiles(self: *Self, dt: i64) void { // What's the total render time, approximately? const dt_est = std.math.pow(i64, self.uniforms._tiles_per_side, 2) * dt; // We'd like to keep the UI running at 60 FPS, approximately const t = std.math.ceil(std.math.sqrt(@intToFloat(f32, @divFloor(dt_est, 16)))); std.debug.print( "Switching from {} to {} tiles per side\n", .{ self.uniforms._tiles_per_side, t }, ); var t_ = @floatToInt(u32, t); if (t_ > 5) { t_ = 5; } self.uniforms._tiles_per_side = t_; self.uniforms._tile_num = 0; } pub fn deinit(self: *const Self) void { c.wgpu_bind_group_destroy(self.bind_group); c.wgpu_buffer_destroy(self.uniform_buffer); c.wgpu_render_pipeline_destroy(self.render_pipeline); self.destroy_textures(); } pub fn set_size(self: *Self, width: u32, height: u32) void { self.destroy_textures(); self.tex_size = (c.WGPUExtent3d){ .width = @intCast(u32, width / 2), .height = @intCast(u32, height), .depth = 1, }; var i: u8 = 0; while (i < 2) : (i += 1) { self.tex[i] = c.wgpu_device_create_texture( self.device, &(c.WGPUTextureDescriptor){ .size = self.tex_size, .mip_level_count = 1, .sample_count = 1, .dimension = c.WGPUTextureDimension_D2, .format = c.WGPUTextureFormat_Bgra8Unorm, // We render to this texture, then use it as a source when // blitting into the final UI image .usage = if (i == 0) (c.WGPUTextureUsage_OUTPUT_ATTACHMENT | c.WGPUTextureUsage_COPY_SRC) else (c.WGPUTextureUsage_OUTPUT_ATTACHMENT | c.WGPUTextureUsage_COPY_SRC | c.WGPUTextureUsage_SAMPLED | c.WGPUTextureUsage_COPY_DST), .label = "preview_tex", }, ); self.tex_view[i] = c.wgpu_texture_create_view( self.tex[i], &(c.WGPUTextureViewDescriptor){ .label = "preview_tex_view", .dimension = c.WGPUTextureViewDimension_D2, .format = c.WGPUTextureFormat_Bgra8Unorm, .aspect = c.WGPUTextureAspect_All, .base_mip_level = 0, .level_count = 1, .base_array_layer = 0, .array_layer_count = 1, }, ); } self.uniforms.iResolution.x = @intToFloat(f32, width) / 2; self.uniforms.iResolution.y = @intToFloat(f32, height); } pub fn redraw(self: *Self) void { const cmd_encoder = c.wgpu_device_create_command_encoder( self.device, &(c.WGPUCommandEncoderDescriptor){ .label = "preview encoder" }, ); // Set the time in the uniforms array if (self.uniforms._tile_num == 0) { const time_ms = std.time.milliTimestamp() - self.start_time; self.uniforms.iTime = @intToFloat(f32, time_ms) / 1000.0; } c.wgpu_queue_write_buffer( self.queue, self.uniform_buffer, 0, @ptrCast([*c]const u8, &self.uniforms), @sizeOf(c.fpPreviewUniforms), ); const load_op: c.WGPULoadOp = if (self.uniforms._tile_num == 0) c.WGPULoadOp_Clear else c.WGPULoadOp_Load; const color_attachments = [_]c.WGPURenderPassColorAttachmentDescriptor{ (c.WGPURenderPassColorAttachmentDescriptor){ .attachment = if (self.uniforms._tiles_per_side == 1) self.tex_view[1] else self.tex_view[0], .resolve_target = 0, .channel = (c.WGPUPassChannel_Color){ .load_op = load_op, .store_op = c.WGPUStoreOp_Store, .clear_value = (c.WGPUColor){ .r = 0.0, .g = 0.0, .b = 0.0, .a = 1.0, }, .read_only = false, }, }, }; const rpass = c.wgpu_command_encoder_begin_render_pass( cmd_encoder, &(c.WGPURenderPassDescriptor){ .color_attachments = &color_attachments, .color_attachments_length = color_attachments.len, .depth_stencil_attachment = null, }, ); c.wgpu_render_pass_set_pipeline(rpass, self.render_pipeline); c.wgpu_render_pass_set_bind_group(rpass, 0, self.bind_group, null, 0); c.wgpu_render_pass_draw(rpass, 6, 1, 0, 0); c.wgpu_render_pass_end_pass(rpass); // Move on to the next tile if (self.uniforms._tiles_per_side > 1) { self.uniforms._tile_num += 1; } // If we just finished rendering every tile, then also copy // to the deployment tex if (self.uniforms._tile_num == std.math.pow(u32, self.uniforms._tiles_per_side, 2)) { const src = (c.WGPUTextureCopyView){ .texture = self.tex[0], .mip_level = 0, .origin = (c.WGPUOrigin3d){ .x = 0, .y = 0, .z = 0 }, }; const dst = (c.WGPUTextureCopyView){ .texture = self.tex[1], .mip_level = 0, .origin = (c.WGPUOrigin3d){ .x = 0, .y = 0, .z = 0 }, }; c.wgpu_command_encoder_copy_texture_to_texture( cmd_encoder, &src, &dst, &self.tex_size, ); self.uniforms._tile_num = 0; } const cmd_buf = c.wgpu_command_encoder_finish(cmd_encoder, null); c.wgpu_queue_submit(self.queue, &cmd_buf, 1); } };
src/preview.zig
const std = @import("../../std.zig"); const builtin = @import("builtin"); const linux = std.os.linux; const mem = std.mem; const elf = std.elf; const expect = std.testing.expect; test "getpid" { expect(linux.getpid() != 0); } test "timer" { const epoll_fd = linux.epoll_create(); var err = linux.getErrno(epoll_fd); expect(err == 0); const timer_fd = linux.timerfd_create(linux.CLOCK_MONOTONIC, 0); expect(linux.getErrno(timer_fd) == 0); const time_interval = linux.timespec{ .tv_sec = 0, .tv_nsec = 2000000, }; const new_time = linux.itimerspec{ .it_interval = time_interval, .it_value = time_interval, }; err = linux.timerfd_settime(@intCast(i32, timer_fd), 0, &new_time, null); expect(err == 0); var event = linux.epoll_event{ .events = linux.EPOLLIN | linux.EPOLLOUT | linux.EPOLLET, .data = linux.epoll_data{ .ptr = 0 }, }; err = linux.epoll_ctl(@intCast(i32, epoll_fd), linux.EPOLL_CTL_ADD, @intCast(i32, timer_fd), &event); expect(err == 0); const events_one: linux.epoll_event = undefined; var events = []linux.epoll_event{events_one} ** 8; // TODO implicit cast from *[N]T to [*]T err = linux.epoll_wait(@intCast(i32, epoll_fd), @ptrCast([*]linux.epoll_event, &events), 8, -1); } export fn iter_fn(info: *linux.dl_phdr_info, size: usize, data: ?*usize) i32 { var counter = data.?; // Count how many libraries are loaded counter.* += usize(1); // The image should contain at least a PT_LOAD segment if (info.dlpi_phnum < 1) return -1; // Quick & dirty validation of the phdr pointers, make sure we're not // pointing to some random gibberish var i: usize = 0; var found_load = false; while (i < info.dlpi_phnum) : (i += 1) { const phdr = info.dlpi_phdr[i]; if (phdr.p_type != elf.PT_LOAD) continue; // Find the ELF header const elf_header = @intToPtr(*elf.Ehdr, phdr.p_vaddr - phdr.p_offset); // Validate the magic if (!mem.eql(u8, elf_header.e_ident[0..], "\x7fELF")) return -1; // Consistency check if (elf_header.e_phnum != info.dlpi_phnum) return -1; found_load = true; break; } if (!found_load) return -1; return 42; } test "dl_iterate_phdr" { var counter: usize = 0; expect(linux.dl_iterate_phdr(usize, iter_fn, &counter) != 0); expect(counter != 0); }
std/os/linux/test.zig
const std = @import("std"); const mem = std.mem; const u = std.unicode; const t = @import("testing.zig"); const Input = @import("input.zig"); usingnamespace @import("ghost_party.zig"); usingnamespace @import("meta.zig"); usingnamespace @import("parser.zig"); usingnamespace @import("result.zig"); const Str = []const u8; /// Constructs a parser that returns `[]const u8` "String" slices /// Because the string type matches the input type, the combinators /// abuse the fact that adjacent slices can be merged. pub fn StringParser(comptime P: type) type { return struct { const Self = @This(); pub usingnamespace (Parser(P)); pub const Many = Repeat(0, null); pub const Many1 = Repeat(1, null); pub const Opt = Repeat(0, 1); pub fn Repeat(min: usize, max: ?usize) type { return StringParser(struct { pub fn parse(input: Input) Result(Str) { var tail = input; var n: usize = 0; var res: Result(Str) = undefined; while (max == null or n <= max.?) : (n += 1) { switch (Self.parse(tail)) { .None => |r| { res = Result(Str).fail(r); break; }, .Some => |r| { tail = r.tail; }, } } if (n >= min) { res = Result(Str).some(input.diff(tail), tail); } return res; } }); } pub fn Seq(comptime next: type) type { return StringParser(struct { pub fn parse(input: Input) Result(Str) { var tail = input; switch (Self.parse(tail)) { .None => |r| return Result(Str).fail(r), .Some => |r| { tail = r.tail; }, } switch (next.parse(tail)) { .None => |r| return Result(Str).fail(r), .Some => |r| { tail = r.tail; }, } return Result(Str).some(input.diff(tail), tail); } }); } }; } pub fn String(comptime str: Str) type { return StringParser(struct { pub fn parse(input: Input) Result(Str) { if (!mem.eql(u8, input.peek(str.len), str)) { return Result([]const u8).none(); } return Result([]const u8).some(str, input.take(str.len)); } }); } test "parse string" { try t.expectSome(String("👻🥳"), "👻🥳"); try t.expectNone(String("👻🥳"), "👻👻"); } pub fn Char(comptime char: u21) type { return StringParser(struct { pub fn parse(input: Input) Result(Str) { return CharRange(char, char).parse(input); } }); } test "parse code point" { try t.expectSomeEqualSlice(u8, "👻", Char('👻'), "👻"); try t.expectNone(Char('👻'), ""); } pub fn CharRange(comptime low: u21, high: u21) type { const none = Result(Str).none; return StringParser(struct { pub fn parse(input: Input) Result(Str) { if (input.len() < 1) return none(); const len = u.utf8ByteSequenceLength(input.peek(1)[0]) catch return none(); const char = u.utf8Decode(input.peek(len)) catch return none(); if (low <= char and char <= high) { return Result(Str).some(input.peek(len), input.take(len)); } return none(); } }); } test "parse range of matching code points" { var c: u8 = 'a'; while (c <= 'z') : (c += 1) { const s: [1]u8 = .{c}; try t.expectSomeEqualSlice(u8, s[0..], CharRange('a', 'z'), s[0..]); } } test "parse range of non-matching code points" { var c: u8 = 'a'; while (c <= 'z') : (c += 1) { const s: [1]u8 = .{c}; try t.expectNone(CharRange('A', 'Z'), s[0..]); } } // MARK: StringParser Combinator Tests test "parse a string of many" { const ghost_ghost = ghost ** 2; try t.expectSomeEqualSlice(u8, ghost_ghost, Char('👻').Many, ghost_ghost); try t.expectSomeEqualSlice(u8, ghost, Char('👻').Many, ghost_party); try t.expectSomeEqualSlice(u8, "", Char('👻').Many, party_ghost); } test "parse a string of at least one" { const ghost_ghost = ghost ** 2; try t.expectSomeEqualSlice(u8, ghost_ghost, Char('👻').Many1, ghost_ghost); try t.expectSomeEqualSlice(u8, ghost, Char('👻').Many1, ghost_party); try t.expectNone(Char('👻').Many1, party_ghost); } test "parse a sequence of strings" { try t.expectSomeEqualSlice(u8, ghost_party, Char('👻').Seq(Char('🥳')), ghost_party); try t.expectNone(Char('👻').Seq(Char('🥳')), party_ghost); } test "parse intergers" { const Number = Char('-').Opt.Seq(CharRange('0', '9').Many1); const Int = Number.Map(i32, testStrToInt); try t.expectSomeExactlyEqual(-42, Int, "-42"); try t.expectSomeExactlyEqual(17, Int, "17"); try t.expectNone(Int, "x"); } fn testStrToInt(str: []const u8) i32 { return std.fmt.parseInt(i32, str, 10) catch unreachable; }
src/string_parser.zig
usingnamespace @import("enum.zig"); usingnamespace @import("../../types.zig"); pub const BlendDesc = extern struct { AlphaToCoverageEnable: BOOL, IndependentBlendEnable: BOOL, RenderTarget: [8]RenderTargetBlendDesc, }; pub const BlendDesc1 = extern struct { AlphaToCoverageEnable: BOOL, IndependentBlendEnable: BOOL, RenderTarget: [8]RenderTargetBlendDesc1, }; pub const Box = extern struct { left: UINT, top: UINT, front: UINT, right: UINT, bottom: UINT, back: UINT, }; pub const CounterDesc = extern struct { Counter: Counter, MiscFlags: UINT, }; pub const CounterInfo = extern struct { LastDeviceDependentCounter: Counter, NumSimultaneousCounters: UINT, NumDetectableParallelUnits: UINT8, }; pub const DepthStencilDesc = extern struct { DepthEnable: BOOL, DepthWriteMask: DepthWriteMask, DepthFunc: ComparisonFunc, StencilEnable: BOOL, StencilReadMask: UINT8, StencilWriteMask: UINT8, FrontFace: DepthStencilOpDesc, BackFace: DepthStencilOpDesc, }; pub const DepthStencilOpDesc = extern struct { StencilFailOp: StencilOp, StencilDepthFailOp: StencilOp, StencilPassOp: StencilOp, StencilFunc: ComparisonFunc, }; pub const DrawIndexedInstancedIndirectArgs = extern struct { IndexCountPerInstance: UINT, InstanceCount: UINT, StartIndexLocation: UINT, BaseVertexLocation: INT, StartInstanceLocation: UINT, }; pub const DrawInstancedIndirectArgs = extern struct { VertexCountPerInstance: UINT, InstanceCount: UINT, StartVertexLocation: UINT, StartInstanceLocation: UINT, }; pub const FeatureDataArchitectureInfo = extern struct { TileBasedDeferredRenderer: BOOL, }; pub const FeatureDataD3D9Options = extern struct { FullNonPow2TextureSupport: BOOL, }; pub const FeatureDataD3D9Options1 = extern struct { FullNonPow2TextureSupported: BOOL, DepthAsTextureWithLessEqualComparisonFilterSupported: BOOL, SimpleInstancingSupported: BOOL, TextureCubeFaceRenderTargetWithNonCubeDepthStencilSupported: BOOL, }; pub const FeatureDataD3D9ShadowSupport = extern struct { SupportsDepthAsTextureWithLessEqualComparisonFilter: BOOL, }; pub const FeatureDataD3D9SimpleInstancingSupport = extern struct { SimpleInstancingSupported: BOOL, }; pub const FeatureDataD3D10XHardwareOptions = extern struct { ComputeShadersPlusRawAndStructuredBuffersViaShader4X: BOOL, }; pub const FeatureDataD3D11Options = extern struct { OutputMergerLogicOp: BOOL, UAVOnlyRenderingForcedSampleCount: BOOL, DiscardAPIsSeenByDriver: BOOL, FlagsForUpdateAndCopySeenByDriver: BOOL, ClearView: BOOL, CopyWithOverlap: BOOL, ConstantBufferPartialUpdate: BOOL, ConstantBufferOffsetting: BOOL, MapNoOverwriteOnDynamicConstantBuffer: BOOL, MapNoOverwriteOnDynamicBufferSRV: BOOL, MultisampleRTVWithForcedSampleCountOne: BOOL, SAD4ShaderInstructions: BOOL, ExtendedDoublesShaderInstructions: BOOL, ExtendedResourceSharing: BOOL, }; pub const FeatureDataD3D11Options1 = extern struct { TiledResourcesTier: TiledResourcesTier, MinMaxFiltering: BOOL, ClearViewAlsoSupportsDepthOnlyFormats: BOOL, MapOnDefaultBuffers: BOOL, }; pub const FeatureDataD3D11Options2 = extern struct { PSSpecifiedStencilRefSupported: BOOL, TypedUAVLoadAdditionalFormats: BOOL, ROVsSupported: BOOL, ConservativeRasterizationTier: ConservativeRasterizationTier, TiledResourcesTier: TiledResourcesTier, MapOnDefaultTextures: BOOL, StandardSwizzle: BOOL, UnifiedMemoryArchitecture: BOOL, }; pub const FeatureDataD3D11Options3 = extern struct { VPAndRTArrayIndexFromAnyShaderFeedingRasterizer: BOOL, }; pub const FeatureDataD3D11Options4 = extern struct { ExtendedNV12SharedTextureSupported: BOOL, }; pub const FeatureDataDoubles = extern struct { DoublePrecisionFloatShaderOps: BOOL, }; pub const FeatureDataFormatSupport = extern enum { InFormat: DXGIFormat, OutFormatSupport: UINT, }; pub const FeatureDataFormatSupport2 = extern enum { InFormat: DXGIFormat, OutFormatSupport2: UINT, }; pub const FeatureDataGPUVirtualAddressSupport = extern struct { MaxGPUVirtualAddressBitsPerProcess: UINT, MaxGPUVirtualAddressBitsPerResource: UINT, }; pub const FeatureDataMarketSupport = extern struct { Profile: BOOL, }; pub const FeatureDataShaderCache = extern struct { SupportFlags: UINT, }; pub const FeatureDataShaderMinPrecisionSupport = extern struct { PixelShaderMinPrecision: UINT, AllOtherShaderStagesMinPrecision: UINT, }; pub const FeatureDataThreading = extern struct { DriverConcurrentCreates: BOOL, DriverCommandLists: BOOL, }; pub const InputeElementDesc = extern struct { SemanticName: LPCSTR, SemanticIndex: UINT, Format: DXGIFormat, InputSlot: UINT, AlignedByteOffset: UINT, InputSlotClass: InputClassification, InstanceDataStepRate: UINT, }; pub const QueryPipelineStatistics = extern struct { IAVertices: UINT64, IAPrimitives: UINT64, VSInvocations: UINT64, GSInvocations: UINT64, GSPrimitives: UINT64, CInvocations: UINT64, CPrimitives: UINT64, PSInvocations: UINT64, HSInvocations: UINT64, DSInvocations: UINT64, CSInvocations: UINT64, }; pub const QueryDataSOStatistics = extern struct { NumPrimitivesWritten: UINT64, PrimitivesStorageNeeded: UINT64, }; pub const QueryDataTimestampDisjoint = extern struct { Frequency: UINT64, Disjoint: BOOL, }; pub const QueryDesc = extern struct { Query: Query, MiscFlags: UINT, }; pub const RasterizerDesc = extern struct { FillMode: FillMode, CullMode: CullMode, FrontCounterClockwise: BOOL, DepthBias: INT, DepthBiasClamp: FLOAT, SlopeScaledDepthBias: FLOAT, DepthClipEnable: BOOL, ScissorEnable: BOOL, MultisampleEnable: BOOL, AntialiasedLineEnable: BOOL, }; pub const Rect = extern struct { left: LONG, top: LONG, right: LONG, bottom: LONG, }; pub const RenderTargetBlendDesc = extern struct { BlendEnable: BOOL, SrcBlend: Blend, DestBlend: Blend, BlendOp: BlendOp, SrcBlendAlpha: Blend, DestBlendAlpha: Blend, BlendOpAlpha: BlendOp, RenderTargetWriteMask: UINT8, }; pub const RenderTargetBlendDesc1 = extern struct { BlendEnable: BOOL, LogicOpEnable: BOOL, SrcBlend: Blend, DestBlend: Blend, BlendOp: BlendOp, SrcBlendAlpha: Blend, DestBlendAlpha: Blend, BlendOpAlpha: BlendOp, LogicOp: LogicOp, RenderTargetWriteMask: UINT8, }; pub const SamplerDesc = extern struct { Filter: Filter, AddressU: TextureAddressMode, AddressV: TextureAddressMode, AddressW: TextureAddressMode, MipLODBias: FLOAT, MaxAnisotropy: UINT, ComparisonFunc: ComparisonFunc, BorderColor: [4]FLOAT, MinLOD: FLOAT, MaxLOD: FLOAT, }; pub const SODeclarationEntry = extern struct { Stream: UINT, SemanticName: LPCSTR, SemanticIndex: UINT, StartComponent: BYTE, ComponentCount: BYTE, OutputSlot: BYTE, }; pub const Viewport = extern struct { TopLeftX: FLOAT, TopLeftY: FLOAT, Width: FLOAT, Height: FLOAT, MinDepth: FLOAT, MaxDepth: FLOAT, };
directx11/core/struct.zig
const std = @import("std"); const p_alloc = std.heap.page_allocator; const mem = std.mem; const Allocator = mem.Allocator; const print = std.debug.print; const StringHashMap = std.StringHashMap; const AutoHashMap = std.AutoHashMap; pub fn StringBufSet(comptime T: anytype) type { return struct { hash_map: StringHashMap(T), const Self = @This(); pub fn init(allocator: *mem.Allocator) Self { return .{ .hash_map = StringHashMap(T).init(allocator) }; } pub fn deinit(self: *Self) void { var it = self.hash_map.iterator(); while (it.next()) |entry| self.free(entry.key_ptr.*); self.hash_map.deinit(); } /// `key` is copied into the BufMap. pub fn put(self: *Self, key: []const u8, value: T) !void { var get_or_put = try self.hash_map.getOrPut(key); if (!get_or_put.found_existing) { get_or_put.key_ptr.* = self.copy(key) catch |err| { _ = self.hash_map.remove(key); return err; }; } get_or_put.value_ptr.* = value; } pub fn get(self: Self, key: []const u8) ?T { return self.hash_map.get(key); } pub fn contains(self: Self, key: []const u8) bool { return self.hash_map.contains(key); } pub fn getEntry(self: Self, key: []const u8) ?StringHashMap(T).Entry { return self.hash_map.getEntry(key); } pub fn delete(self: *Self, key: []const u8) void { const entry = self.hash_map.remove(key) orelse return; self.free(entry.key); } pub fn count(self: Self) usize { return self.hash_map.count(); } pub fn iterator(self: *const Self) StringHashMap(T).Iterator { return self.hash_map.iterator(); } fn free(self: Self, value: []const u8) void { self.hash_map.allocator.free(value); } fn copy(self: Self, value: []const u8) ![]u8 { return self.hash_map.allocator.dupe(u8, value); } }; }
demo/common/utils.zig
const std = @import("std"); const SUBCOMMANDS = @import("src/subcommands.zig").SUBCOMMANDS; const coreutils_version = std.builtin.Version{ .major = 0, .minor = 0, .patch = 6 }; pub fn build(b: *std.build.Builder) !void { b.prominent_compile_errors = true; const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); if (!target.isLinux()) { std.debug.print("Currently only linux is supported\n", .{}); return error.UnsupportedOperatingSystem; } const trace = b.option(bool, "trace", "enable tracy tracing") orelse false; const options = b.addOptions(); options.addOption(bool, "trace", trace); const version = v: { const version_string = b.fmt( "{d}.{d}.{d}", .{ coreutils_version.major, coreutils_version.minor, coreutils_version.patch }, ); var code: u8 = undefined; const git_describe_untrimmed = b.execAllowFail(&[_][]const u8{ "git", "-C", b.build_root, "describe", "--match", "*.*.*", "--tags", }, &code, .Ignore) catch { break :v version_string; }; const git_describe = std.mem.trim(u8, git_describe_untrimmed, " \n\r"); switch (std.mem.count(u8, git_describe, "-")) { 0 => { // Tagged release version (e.g. 0.8.0). if (!std.mem.eql(u8, git_describe, version_string)) { std.debug.print( "Zig-Coreutils version '{s}' does not match Git tag '{s}'\n", .{ version_string, git_describe }, ); std.process.exit(1); } break :v version_string; }, 2 => { // Untagged development build (e.g. 0.8.0-684-gbbe2cca1a). var it = std.mem.split(u8, git_describe, "-"); const tagged_ancestor = it.next() orelse unreachable; const commit_height = it.next() orelse unreachable; const commit_id = it.next() orelse unreachable; const ancestor_ver = try std.builtin.Version.parse(tagged_ancestor); if (coreutils_version.order(ancestor_ver) != .gt) { std.debug.print( "Zig-Coreutils version '{}' must be greater than tagged ancestor '{}'\n", .{ coreutils_version, ancestor_ver }, ); std.process.exit(1); } // Check that the commit hash is prefixed with a 'g' (a Git convention). if (commit_id.len < 1 or commit_id[0] != 'g') { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); break :v version_string; } // The version is reformatted in accordance with the https://semver.org specification. break :v b.fmt("{s}-dev.{s}+{s}", .{ version_string, commit_height, commit_id[1..] }); }, else => { std.debug.print("Unexpected `git describe` output: {s}\n", .{git_describe}); break :v version_string; }, } }; options.addOption([:0]const u8, "version", try b.allocator.dupeZ(u8, version)); const main_exe = b.addExecutable("zig-coreutils", "src/main.zig"); main_exe.setTarget(target); main_exe.setBuildMode(mode); main_exe.single_threaded = true; if (mode != .Debug) { main_exe.link_function_sections = true; main_exe.want_lto = true; } main_exe.install(); main_exe.addOptions("options", options); main_exe.addPackagePath("zsw", "zsw/src/main.zig"); if (trace) { includeTracy(main_exe); } const test_step = b.addTest("src/main.zig"); test_step.addOptions("options", options); test_step.addPackagePath("zsw", "zsw/src/main.zig"); if (trace) { includeTracy(test_step); } const run_test_step = b.step("test", "Run the tests"); run_test_step.dependOn(&test_step.step); // as this is set as the default step also get it to trigger an install of the main exe test_step.step.dependOn(b.getInstallStep()); b.default_step = run_test_step; } fn includeTracy(exe: *std.build.LibExeObjStep) void { exe.linkLibC(); exe.linkLibCpp(); exe.addIncludeDir("tracy"); const tracy_c_flags: []const []const u8 = if (exe.target.isWindows() and exe.target.getAbi() == .gnu) &.{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined", "-D_WIN32_WINNT=0x601" } else &.{ "-DTRACY_ENABLE=1", "-fno-sanitize=undefined" }; exe.addCSourceFile("tracy/TracyClient.cpp", tracy_c_flags); if (exe.target.isWindows()) { exe.linkSystemLibrary("Advapi32"); exe.linkSystemLibrary("User32"); exe.linkSystemLibrary("Ws2_32"); exe.linkSystemLibrary("DbgHelp"); } }
build.zig
const std = @import("std"); const bcm2835 = @import("bcm2835.zig"); const mocks = @import("integration-tests/mocks.zig"); const gpio = @import("gpio.zig"); pub fn main() anyerror!void { // var gpalloc = std.heap.GeneralPurposeAllocator(.{}){}; // defer _= gpalloc.deinit(); // var mock_mem = try mocks.MockGpioMemoryMapper.init(&gpalloc.allocator,bcm2835.BoardInfo.gpio_registers); // defer mock_mem.deinit(); // std.log.info("All your codebase are belong to us.{}, {}", .{bcm2835.BoardInfo.peripheral_addresses.start, 0b100011}); // _ = try bcm2835.Bcm2385GpioMemoryMapper.init(); // std.log.info("sizeof u3 = {}, bitsizeof u3 = {}", .{@sizeOf(u3),@bitSizeOf(gpio.Mode)}); // try gpio.init(&mock_mem.memory_mapper); // try gpio.setLevel(2,gpio.Level.High); // try gpio.setMode(12, gpio.Mode.Alternate0); // _ = try gpio.getLevel(2); // in mock mode this of course will not display High because the level is read in a different register! var mapper = try bcm2835.Bcm2385GpioMemoryMapper.init(); defer mapper.deinit(); try gpio.init(&mapper.memory_mapper); //try setAllPinModes(.Output); const pin_number = 3; try gpio.setMode(pin_number, gpio.Mode.Output); _ = try gpio.getMode(pin_number); var idx: u32 = 0; while (idx < 100) : (idx += 1) { std.log.info("idx {}", .{idx}); std.log.info("set pin to high", .{}); try gpio.setLevel(pin_number, .High); std.time.sleep(500000000); //500ms std.log.info("set pin to low", .{}); try gpio.setLevel(pin_number, .Low); std.time.sleep(500000000); //500ms } } fn setAllPinLevels(level: gpio.Level) !void { var pin: u8 = 0; while (pin < bcm2835.BoardInfo.NUM_GPIO_PINS) : (pin += 1) { try gpio.setLevel(pin, level); } } fn setAllPinModes(mode: gpio.Mode) !void { var pin: u8 = 0; while (pin < bcm2835.BoardInfo.NUM_GPIO_PINS) : (pin += 1) { std.log.info("Setting mode for pin {}", .{pin}); try gpio.setMode(pin, mode); } }
src/main.zig
const std = @import("std"); const HashMap = std.HashMap; const core = @import("../index.zig"); const Coord = core.geometry.Coord; const Species = core.protocol.Species; const Floor = core.protocol.Floor; const Wall = core.protocol.Wall; const ThingPosition = core.protocol.ThingPosition; const TerrainSpace = core.protocol.TerrainSpace; const StatusConditions = core.protocol.StatusConditions; const map_gen = @import("./map_gen.zig"); /// an "id" is a strictly server-side concept. pub fn IdMap(comptime V: type) type { return std.AutoHashMap(u32, V); } pub fn CoordMap(comptime V: type) type { return std.AutoHashMap(Coord, V); } pub const Terrain = core.matrix.Matrix(TerrainSpace); pub const oob_terrain = TerrainSpace{ .floor = .unknown, .wall = .stone, }; pub const Individual = struct { species: Species, abs_position: ThingPosition, status_conditions: StatusConditions = 0, has_shield: bool = false, pub fn clone(self: Individual, allocator: *std.mem.Allocator) !*Individual { var other = try allocator.create(Individual); other.* = self; return other; } }; pub const StateDiff = union(enum) { spawn: IdAndIndividual, despawn: IdAndIndividual, small_move: IdAndCoord, large_move: IdAndCoords, polymorph: Polymorph, status_condition_diff: struct { id: u32, from: StatusConditions, to: StatusConditions, }, terrain_update: TerrainDiff, pub const IdAndIndividual = struct { id: u32, individual: Individual, }; pub const IdAndCoord = struct { id: u32, coord: Coord, }; pub const IdAndCoords = struct { id: u32, coords: [2]Coord, }; pub const Polymorph = struct { id: u32, from: Species, to: Species, }; pub const TerrainDiff = struct { at: Coord, from: TerrainSpace, to: TerrainSpace, }; }; pub const GameState = struct { allocator: *std.mem.Allocator, terrain: Terrain, individuals: IdMap(*Individual), pub fn generate(allocator: *std.mem.Allocator) !GameState { var game_state = GameState{ .allocator = allocator, .terrain = undefined, .individuals = IdMap(*Individual).init(allocator), }; try map_gen.generate(allocator, &game_state.terrain, &game_state.individuals); return game_state; } pub fn clone(self: GameState) !GameState { return GameState{ .allocator = self.allocator, .terrain = self.terrain, .individuals = blk: { var ret = IdMap(*Individual).init(self.allocator); var iterator = self.individuals.iterator(); while (iterator.next()) |kv| { try ret.putNoClobber(kv.key, try kv.value.*.clone(self.allocator)); } break :blk ret; }, }; } pub fn applyStateChanges(self: *GameState, state_changes: []const StateDiff) !void { for (state_changes) |diff| { switch (diff) { .spawn => |data| { try self.individuals.putNoClobber(data.id, try data.individual.clone(self.allocator)); }, .despawn => |data| { self.individuals.removeAssertDiscard(data.id); }, .small_move => |id_and_coord| { const individual = self.individuals.get(id_and_coord.id).?; individual.abs_position.small = individual.abs_position.small.plus(id_and_coord.coord); }, .large_move => |id_and_coords| { const individual = self.individuals.get(id_and_coords.id).?; individual.abs_position.large = .{ individual.abs_position.large[0].plus(id_and_coords.coords[0]), individual.abs_position.large[1].plus(id_and_coords.coords[1]), }; }, .polymorph => |polymorph| { const individual = self.individuals.get(polymorph.id).?; individual.species = polymorph.to; }, .status_condition_diff => |data| { const individual = self.individuals.get(data.id).?; individual.status_conditions = data.to; }, .terrain_update => |data| { self.terrain.atCoord(data.at).?.* = data.to; }, } } } pub fn undoStateChanges(self: *GameState, state_changes: []const StateDiff) !void { for (state_changes) |_, forwards_i| { // undo backwards const diff = state_changes[state_changes.len - 1 - forwards_i]; switch (diff) { .spawn => |data| { self.individuals.removeAssertDiscard(data.id); }, .despawn => |data| { try self.individuals.putNoClobber(data.id, try data.individual.clone(self.allocator)); }, .small_move => |id_and_coord| { const individual = self.individuals.get(id_and_coord.id).?; individual.abs_position.small = individual.abs_position.small.minus(id_and_coord.coord); }, .large_move => |id_and_coords| { const individual = self.individuals.get(id_and_coords.id).?; individual.abs_position.large = .{ individual.abs_position.large[0].minus(id_and_coords.coords[0]), individual.abs_position.large[1].minus(id_and_coords.coords[1]), }; }, .polymorph => |polymorph| { const individual = self.individuals.get(polymorph.id).?; individual.species = polymorph.from; }, .status_condition_diff => |data| { const individual = self.individuals.get(data.id).?; individual.status_conditions = data.from; }, .terrain_update => |data| { self.terrain.atCoord(data.at).?.* = data.from; }, } } } pub fn terrainAt(self: GameState, coord: Coord) TerrainSpace { return self.terrain.getCoord(coord) orelse oob_terrain; } };
src/server/game_model.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const webgpu = @import("../../../webgpu.zig"); const vulkan = @import("../vulkan.zig"); const vk = @import("../vk.zig"); const QueueFamilies = @import("../QueueFamilies.zig"); const Adapter = @This(); pub const vtable = webgpu.Adapter.VTable{ .request_device_fn = requestDevice, }; super: webgpu.Adapter, handle: vk.PhysicalDevice, queue_families: QueueFamilies, pub fn create(instance: *vulkan.Instance, physical_device: vk.PhysicalDevice) !*Adapter { var adapter = try instance.allocator.create(Adapter); errdefer instance.allocator.destroy(adapter); adapter.super = .{ .__vtable = &vtable, .instance = &instance.super, .features = undefined, .limits = undefined, .device_id = undefined, .vendor_id = undefined, .backend_type = .vulkan, .adapter_type = undefined, .name = undefined, }; adapter.handle = physical_device; var properties = instance.vki.getPhysicalDeviceProperties(adapter.handle); const name = try instance.allocator.dupeZ(u8, std.mem.sliceTo(&properties.device_name, 0)); errdefer instance.allocator.free(name); adapter.super.features = adapter.calculateSupportedFeatures(); adapter.super.limits = adapter.calculateSupportedLimits(); adapter.super.device_id = properties.device_id; adapter.super.vendor_id = properties.vendor_id; adapter.super.adapter_type = switch (properties.device_type) { .integrated_gpu => .integrated_gpu, .discrete_gpu => .discrete_gpu, .cpu => .cpu, else => .unknown, }; adapter.super.name = name; adapter.queue_families = try QueueFamilies.find(adapter); return adapter; } pub fn destroy(adapter: *Adapter) void { var instance = @fieldParentPtr(vulkan.Instance, "super", adapter.super.instance); instance.allocator.free(adapter.super.name); instance.allocator.destroy(adapter); } fn requestDevice(super: *webgpu.Adapter, descriptor: webgpu.DeviceDescriptor) webgpu.Adapter.RequestDeviceError!*webgpu.Device { var adapter = @fieldParentPtr(Adapter, "super", super); var device = vulkan.Device.create(adapter, descriptor) catch |err| switch (err) { error.OutOfMemory => |_err| return _err, else => return error.Failed, }; return &device.super; } fn calculateSupportedFeatures(adapter: *Adapter) webgpu.Features { var instance = @fieldParentPtr(vulkan.Instance, "super", adapter.super.instance); var _features = instance.vki.getPhysicalDeviceFeatures(adapter.handle); var features = webgpu.Features{}; features.texture_compression_bc = _features.texture_compression_bc == vk.TRUE; features.texture_compression_etc2 = _features.texture_compression_etc2 == vk.TRUE; features.texture_compression_astc = _features.texture_compression_astc_ldr == vk.TRUE; features.timestamp_query = _features.pipeline_statistics_query == vk.TRUE and _features.occlusion_query_precise == vk.TRUE; features.indirect_first_instance = _features.draw_indirect_first_instance == vk.TRUE; return features; } fn calculateSupportedLimits(adapter: *Adapter) webgpu.Limits { var instance = @fieldParentPtr(vulkan.Instance, "super", adapter.super.instance); var properties = instance.vki.getPhysicalDeviceProperties(adapter.handle); var limits = webgpu.Limits{}; limits.max_texture_dimension1d = properties.limits.max_image_dimension_1d; limits.max_texture_dimension2d = properties.limits.max_image_dimension_2d; limits.max_texture_dimension3d = properties.limits.max_image_dimension_3d; limits.max_texture_array_layers = properties.limits.max_image_array_layers; limits.max_bind_groups = properties.limits.max_bound_descriptor_sets; limits.max_dynamic_uniform_buffers_per_pipeline_layout = properties.limits.max_descriptor_set_uniform_buffers_dynamic; limits.max_dynamic_storage_buffers_per_pipeline_layout = properties.limits.max_descriptor_set_storage_buffers_dynamic; limits.max_sampled_textures_per_shader_stage = properties.limits.max_per_stage_descriptor_sampled_images; limits.max_samplers_per_shader_stage = properties.limits.max_per_stage_descriptor_samplers; limits.max_storage_buffers_per_shader_stage = properties.limits.max_per_stage_descriptor_storage_buffers; limits.max_storage_textures_per_shader_stage = properties.limits.max_per_stage_descriptor_storage_images; limits.max_uniform_buffers_per_shader_stage = properties.limits.max_per_stage_descriptor_uniform_buffers; limits.max_uniform_buffer_binding_size = properties.limits.max_uniform_buffer_range; limits.max_storage_buffer_binding_size = properties.limits.max_storage_buffer_range; limits.min_uniform_buffer_offset_alignment = @intCast(u32, properties.limits.min_uniform_buffer_offset_alignment); limits.min_storage_buffer_offset_alignment = @intCast(u32, properties.limits.min_storage_buffer_offset_alignment); limits.max_vertex_buffers = properties.limits.max_vertex_input_bindings; limits.max_vertex_attributes = properties.limits.max_vertex_input_attributes; limits.max_vertex_buffer_array_stride = properties.limits.max_vertex_input_binding_stride; limits.max_inter_stage_shader_components = properties.limits.max_vertex_output_components; limits.max_compute_workgroup_storage_size = properties.limits.max_compute_shared_memory_size; limits.max_compute_invocations_per_workgroup = properties.limits.max_compute_work_group_invocations; limits.max_compute_workgroup_size_x = properties.limits.max_compute_work_group_size[0]; limits.max_compute_workgroup_size_y = properties.limits.max_compute_work_group_size[1]; limits.max_compute_workgroup_size_z = properties.limits.max_compute_work_group_size[2]; limits.max_compute_workgroups_per_dimension = std.math.min3( properties.limits.max_compute_work_group_count[0], properties.limits.max_compute_work_group_count[1], properties.limits.max_compute_work_group_count[2], ); return limits; }
src/backends/vulkan/instance/Adapter.zig
test "" { @import("std").meta.refAllDecls(@This()); } usingnamespace @import("../include/psploadexec.zig"); usingnamespace @import("../include/pspthreadman.zig"); usingnamespace @import("../include/psptypes.zig"); usingnamespace @import("debug.zig"); const root = @import("root"); //If there's an issue this is the internal exit (wait 10 seconds and exit). pub fn exitErr() void { //Hang for 10 seconds for error reporting var stat = sceKernelDelayThread(10 * 1000 * 1000); //Exit out. sceKernelExitGame(); } const has_std_os = if (@hasDecl(root, "os")) true else false; //This calls your main function as a thread. pub fn _module_main_thread(argc: SceSize, argv: ?*c_void) callconv(.C) c_int { if (has_std_os) { pspos.system.__pspOsInit(argv); } switch (@typeInfo(@typeInfo(@TypeOf(root.main)).Fn.return_type.?)) { .NoReturn => { root.main(); }, .Void => { root.main(); return 0; }, .Int => |info| { if (info.bits != 8 or info.is_signed) { @compileError(bad_main_ret); } return root.main(); }, .ErrorUnion => { const result = root.main() catch |err| { print("ERROR CAUGHT: "); print(@errorName(err)); print("\nExiting in 10 seconds..."); exitErr(); return 1; }; switch (@typeInfo(@TypeOf(result))) { .Void => return 0, .Int => |info| { if (info.bits != 8) { @compileError(bad_main_ret); } return result; }, else => @compileError(bad_main_ret), } }, else => @compileError(bad_main_ret), } if (exitOnEnd) { sceKernelExitGame(); } return 0; } //Stub! // //Modified BSD License //==================== // //_Copyright � `2020`, `<NAME>`_ //_All rights reserved._ // //Redistribution and use in source and binary forms, with or without //modification, are permitted provided that the following conditions are met: // //1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. //2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. //3. Neither the name of the `<organization>` nor the // names of its contributors may be used to endorse or promote products // derived from this software without specific prior written permission. // //THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS �AS IS� AND //ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED //WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE //DISCLAIMED. IN NO EVENT SHALL `<NAME>` BE LIABLE FOR ANY //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Thanks to mrneo240 (<NAME>) for the help // comptime { asm ( \\.data \\.globl module_info \\.globl __syslib_exports \\.globl __library_exports \\ \\.set push \\ \\.section .lib.ent.top, "a", @progbits \\ .align 2 \\ .word 0 \\__lib_ent_top: \\ \\.section .lib.ent.btm, "a", @progbits \\ .align 2 \\__lib_ent_bottom: \\ .word 0 \\ \\.section .lib.stub.top, "a", @progbits \\ .align 2 \\ .word 0 \\__lib_stub_top: \\ \\.section .lib.stub.btm, "a", @progbits \\ .align 2 \\__lib_stub_bottom: \\ .word 0 \\ \\.set pop \\ \\.section .rodata.sceResident, "a", @progbits \\__syslib_exports: \\ .word 0xD632ACDB \\ .word 0xF01D73A7 \\ .word module_start \\ .word module_info \\ \\.section .lib.ent, "a", @progbits \\__library_exports: \\ .word 0 \\ .hword 0 \\ .hword 0x8000 \\ .byte 4 \\ .byte 1 \\ .hword 1 \\ .word __syslib_exports ); } fn intToString(int: u32, buf: []u8) ![]const u8 { return try @import("std").fmt.bufPrint(buf, "{}", .{int}); } pub fn module_info(comptime name: []const u8, comptime attrib: u16, comptime major: u8, comptime minor: u8) []const u8 { @setEvalBranchQuota(10000); var buf: [3]u8 = undefined; const maj = intToString(major, &buf) catch unreachable; buf = undefined; const min = intToString(minor, &buf) catch unreachable; buf = undefined; const attr = intToString(attrib, &buf) catch unreachable; buf = undefined; const count = intToString(27 - name.len, &buf) catch unreachable; return ( \\.section .rodata.sceModuleInfo, "a", @progbits \\module_info: \\.align 5 \\.hword ++ attr ++ "\n" ++ \\.byte ++ maj ++ "\n" ++ \\.byte ++ min ++ "\n" ++ \\.ascii " ++ name ++ "\"\n" ++ \\.space ++ count ++ "\n" ++ \\.byte 0 \\.word _gp \\.word __lib_ent_top \\.word __lib_ent_bottom \\.word __lib_stub_top \\.word __lib_stub_bottom ); } const pspos = @import("../pspos.zig"); //Entry point - launches main through the thread above. pub export fn module_start(argc: c_uint, argv: ?*c_void) c_int { var thid: SceUID = sceKernelCreateThread("zig_user_main", _module_main_thread, 0x20, 256 * 1024, 0b10000000000000000100000000000000, 0); return sceKernelStartThread(thid, argc, argv); }
src/psp/utils/module.zig
//-------------------------------------------------------------------------------- // Section: Types (12) //-------------------------------------------------------------------------------- pub const GAMING_DEVICE_VENDOR_ID = enum(i32) { NONE = 0, MICROSOFT = -1024700366, }; pub const GAMING_DEVICE_VENDOR_ID_NONE = GAMING_DEVICE_VENDOR_ID.NONE; pub const GAMING_DEVICE_VENDOR_ID_MICROSOFT = GAMING_DEVICE_VENDOR_ID.MICROSOFT; pub const GAMING_DEVICE_DEVICE_ID = enum(i32) { NONE = 0, XBOX_ONE = 1988865574, XBOX_ONE_S = 712204761, XBOX_ONE_X = 1523980231, XBOX_ONE_X_DEVKIT = 284675555, }; pub const GAMING_DEVICE_DEVICE_ID_NONE = GAMING_DEVICE_DEVICE_ID.NONE; pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE = GAMING_DEVICE_DEVICE_ID.XBOX_ONE; pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE_S = GAMING_DEVICE_DEVICE_ID.XBOX_ONE_S; pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE_X = GAMING_DEVICE_DEVICE_ID.XBOX_ONE_X; pub const GAMING_DEVICE_DEVICE_ID_XBOX_ONE_X_DEVKIT = GAMING_DEVICE_DEVICE_ID.XBOX_ONE_X_DEVKIT; pub const GAMING_DEVICE_MODEL_INFORMATION = extern struct { vendorId: GAMING_DEVICE_VENDOR_ID, deviceId: GAMING_DEVICE_DEVICE_ID, }; pub const GameUICompletionRoutine = fn( returnCode: HRESULT, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) void; pub const PlayerPickerUICompletionRoutine = fn( returnCode: HRESULT, context: ?*c_void, selectedXuids: [*]const ?HSTRING, selectedXuidsCount: usize, ) callconv(@import("std").os.windows.WINAPI) void; pub const KnownGamingPrivileges = enum(i32) { BROADCAST = 190, VIEW_FRIENDS_LIST = 197, GAME_DVR = 198, SHARE_KINECT_CONTENT = 199, MULTIPLAYER_PARTIES = 203, COMMUNICATION_VOICE_INGAME = 205, COMMUNICATION_VOICE_SKYPE = 206, CLOUD_GAMING_MANAGE_SESSION = 207, CLOUD_GAMING_JOIN_SESSION = 208, CLOUD_SAVED_GAMES = 209, SHARE_CONTENT = 211, PREMIUM_CONTENT = 214, SUBSCRIPTION_CONTENT = 219, SOCIAL_NETWORK_SHARING = 220, PREMIUM_VIDEO = 224, VIDEO_COMMUNICATIONS = 235, PURCHASE_CONTENT = 245, USER_CREATED_CONTENT = 247, PROFILE_VIEWING = 249, COMMUNICATIONS = 252, MULTIPLAYER_SESSIONS = 254, ADD_FRIEND = 255, }; pub const XPRIVILEGE_BROADCAST = KnownGamingPrivileges.BROADCAST; pub const XPRIVILEGE_VIEW_FRIENDS_LIST = KnownGamingPrivileges.VIEW_FRIENDS_LIST; pub const XPRIVILEGE_GAME_DVR = KnownGamingPrivileges.GAME_DVR; pub const XPRIVILEGE_SHARE_KINECT_CONTENT = KnownGamingPrivileges.SHARE_KINECT_CONTENT; pub const XPRIVILEGE_MULTIPLAYER_PARTIES = KnownGamingPrivileges.MULTIPLAYER_PARTIES; pub const XPRIVILEGE_COMMUNICATION_VOICE_INGAME = KnownGamingPrivileges.COMMUNICATION_VOICE_INGAME; pub const XPRIVILEGE_COMMUNICATION_VOICE_SKYPE = KnownGamingPrivileges.COMMUNICATION_VOICE_SKYPE; pub const XPRIVILEGE_CLOUD_GAMING_MANAGE_SESSION = KnownGamingPrivileges.CLOUD_GAMING_MANAGE_SESSION; pub const XPRIVILEGE_CLOUD_GAMING_JOIN_SESSION = KnownGamingPrivileges.CLOUD_GAMING_JOIN_SESSION; pub const XPRIVILEGE_CLOUD_SAVED_GAMES = KnownGamingPrivileges.CLOUD_SAVED_GAMES; pub const XPRIVILEGE_SHARE_CONTENT = KnownGamingPrivileges.SHARE_CONTENT; pub const XPRIVILEGE_PREMIUM_CONTENT = KnownGamingPrivileges.PREMIUM_CONTENT; pub const XPRIVILEGE_SUBSCRIPTION_CONTENT = KnownGamingPrivileges.SUBSCRIPTION_CONTENT; pub const XPRIVILEGE_SOCIAL_NETWORK_SHARING = KnownGamingPrivileges.SOCIAL_NETWORK_SHARING; pub const XPRIVILEGE_PREMIUM_VIDEO = KnownGamingPrivileges.PREMIUM_VIDEO; pub const XPRIVILEGE_VIDEO_COMMUNICATIONS = KnownGamingPrivileges.VIDEO_COMMUNICATIONS; pub const XPRIVILEGE_PURCHASE_CONTENT = KnownGamingPrivileges.PURCHASE_CONTENT; pub const XPRIVILEGE_USER_CREATED_CONTENT = KnownGamingPrivileges.USER_CREATED_CONTENT; pub const XPRIVILEGE_PROFILE_VIEWING = KnownGamingPrivileges.PROFILE_VIEWING; pub const XPRIVILEGE_COMMUNICATIONS = KnownGamingPrivileges.COMMUNICATIONS; pub const XPRIVILEGE_MULTIPLAYER_SESSIONS = KnownGamingPrivileges.MULTIPLAYER_SESSIONS; pub const XPRIVILEGE_ADD_FRIEND = KnownGamingPrivileges.ADD_FRIEND; const CLSID_XblIdpAuthManager_Value = @import("zig.zig").Guid.initString("ce23534b-56d8-4978-86a2-7ee570640468"); pub const CLSID_XblIdpAuthManager = &CLSID_XblIdpAuthManager_Value; const CLSID_XblIdpAuthTokenResult_Value = @import("zig.zig").Guid.initString("9f493441-744a-410c-ae2b-9a22f7c7731f"); pub const CLSID_XblIdpAuthTokenResult = &CLSID_XblIdpAuthTokenResult_Value; pub const XBL_IDP_AUTH_TOKEN_STATUS = enum(i32) { SUCCESS = 0, OFFLINE_SUCCESS = 1, NO_ACCOUNT_SET = 2, LOAD_MSA_ACCOUNT_FAILED = 3, XBOX_VETO = 4, MSA_INTERRUPT = 5, OFFLINE_NO_CONSENT = 6, VIEW_NOT_SET = 7, UNKNOWN = -1, }; pub const XBL_IDP_AUTH_TOKEN_STATUS_SUCCESS = XBL_IDP_AUTH_TOKEN_STATUS.SUCCESS; pub const XBL_IDP_AUTH_TOKEN_STATUS_OFFLINE_SUCCESS = XBL_IDP_AUTH_TOKEN_STATUS.OFFLINE_SUCCESS; pub const XBL_IDP_AUTH_TOKEN_STATUS_NO_ACCOUNT_SET = XBL_IDP_AUTH_TOKEN_STATUS.NO_ACCOUNT_SET; pub const XBL_IDP_AUTH_TOKEN_STATUS_LOAD_MSA_ACCOUNT_FAILED = XBL_IDP_AUTH_TOKEN_STATUS.LOAD_MSA_ACCOUNT_FAILED; pub const XBL_IDP_AUTH_TOKEN_STATUS_XBOX_VETO = XBL_IDP_AUTH_TOKEN_STATUS.XBOX_VETO; pub const XBL_IDP_AUTH_TOKEN_STATUS_MSA_INTERRUPT = XBL_IDP_AUTH_TOKEN_STATUS.MSA_INTERRUPT; pub const XBL_IDP_AUTH_TOKEN_STATUS_OFFLINE_NO_CONSENT = XBL_IDP_AUTH_TOKEN_STATUS.OFFLINE_NO_CONSENT; pub const XBL_IDP_AUTH_TOKEN_STATUS_VIEW_NOT_SET = XBL_IDP_AUTH_TOKEN_STATUS.VIEW_NOT_SET; pub const XBL_IDP_AUTH_TOKEN_STATUS_UNKNOWN = XBL_IDP_AUTH_TOKEN_STATUS.UNKNOWN; const IID_IXblIdpAuthManager_Value = @import("zig.zig").Guid.initString("eb5ddb08-8bbf-449b-ac21-b02ddeb3b136"); pub const IID_IXblIdpAuthManager = &IID_IXblIdpAuthManager_Value; pub const IXblIdpAuthManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetGamerAccount: fn( self: *const IXblIdpAuthManager, msaAccountId: ?[*:0]const u16, xuid: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGamerAccount: fn( self: *const IXblIdpAuthManager, msaAccountId: ?*?PWSTR, xuid: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAppViewInitialized: fn( self: *const IXblIdpAuthManager, appSid: ?[*:0]const u16, msaAccountId: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnvironment: fn( self: *const IXblIdpAuthManager, environment: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSandbox: fn( self: *const IXblIdpAuthManager, sandbox: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTokenAndSignatureWithTokenResult: fn( self: *const IXblIdpAuthManager, msaAccountId: ?[*:0]const u16, appSid: ?[*:0]const u16, msaTarget: ?[*:0]const u16, msaPolicy: ?[*:0]const u16, httpMethod: ?[*:0]const u16, uri: ?[*:0]const u16, headers: ?[*:0]const u16, body: [*:0]u8, bodySize: u32, forceRefresh: BOOL, result: ?*?*IXblIdpAuthTokenResult, ) 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 IXblIdpAuthManager_SetGamerAccount(self: *const T, msaAccountId: ?[*:0]const u16, xuid: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthManager.VTable, self.vtable).SetGamerAccount(@ptrCast(*const IXblIdpAuthManager, self), msaAccountId, xuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthManager_GetGamerAccount(self: *const T, msaAccountId: ?*?PWSTR, xuid: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthManager.VTable, self.vtable).GetGamerAccount(@ptrCast(*const IXblIdpAuthManager, self), msaAccountId, xuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthManager_SetAppViewInitialized(self: *const T, appSid: ?[*:0]const u16, msaAccountId: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthManager.VTable, self.vtable).SetAppViewInitialized(@ptrCast(*const IXblIdpAuthManager, self), appSid, msaAccountId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthManager_GetEnvironment(self: *const T, environment: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthManager.VTable, self.vtable).GetEnvironment(@ptrCast(*const IXblIdpAuthManager, self), environment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthManager_GetSandbox(self: *const T, sandbox: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthManager.VTable, self.vtable).GetSandbox(@ptrCast(*const IXblIdpAuthManager, self), sandbox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthManager_GetTokenAndSignatureWithTokenResult(self: *const T, msaAccountId: ?[*:0]const u16, appSid: ?[*:0]const u16, msaTarget: ?[*:0]const u16, msaPolicy: ?[*:0]const u16, httpMethod: ?[*:0]const u16, uri: ?[*:0]const u16, headers: ?[*:0]const u16, body: [*:0]u8, bodySize: u32, forceRefresh: BOOL, result: ?*?*IXblIdpAuthTokenResult) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthManager.VTable, self.vtable).GetTokenAndSignatureWithTokenResult(@ptrCast(*const IXblIdpAuthManager, self), msaAccountId, appSid, msaTarget, msaPolicy, httpMethod, uri, headers, body, bodySize, forceRefresh, result); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IXblIdpAuthTokenResult_Value = @import("zig.zig").Guid.initString("46ce0225-f267-4d68-b299-b2762552dec1"); pub const IID_IXblIdpAuthTokenResult = &IID_IXblIdpAuthTokenResult_Value; pub const IXblIdpAuthTokenResult = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetStatus: fn( self: *const IXblIdpAuthTokenResult, status: ?*XBL_IDP_AUTH_TOKEN_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetErrorCode: fn( self: *const IXblIdpAuthTokenResult, errorCode: ?*HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetToken: fn( self: *const IXblIdpAuthTokenResult, token: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignature: fn( self: *const IXblIdpAuthTokenResult, signature: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSandbox: fn( self: *const IXblIdpAuthTokenResult, sandbox: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnvironment: fn( self: *const IXblIdpAuthTokenResult, environment: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMsaAccountId: fn( self: *const IXblIdpAuthTokenResult, msaAccountId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetXuid: fn( self: *const IXblIdpAuthTokenResult, xuid: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGamertag: fn( self: *const IXblIdpAuthTokenResult, gamertag: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAgeGroup: fn( self: *const IXblIdpAuthTokenResult, ageGroup: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrivileges: fn( self: *const IXblIdpAuthTokenResult, privileges: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMsaTarget: fn( self: *const IXblIdpAuthTokenResult, msaTarget: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMsaPolicy: fn( self: *const IXblIdpAuthTokenResult, msaPolicy: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMsaAppId: fn( self: *const IXblIdpAuthTokenResult, msaAppId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRedirect: fn( self: *const IXblIdpAuthTokenResult, redirect: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMessage: fn( self: *const IXblIdpAuthTokenResult, message: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHelpId: fn( self: *const IXblIdpAuthTokenResult, helpId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEnforcementBans: fn( self: *const IXblIdpAuthTokenResult, enforcementBans: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRestrictions: fn( self: *const IXblIdpAuthTokenResult, restrictions: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTitleRestrictions: fn( self: *const IXblIdpAuthTokenResult, titleRestrictions: ?*?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 IXblIdpAuthTokenResult_GetStatus(self: *const T, status: ?*XBL_IDP_AUTH_TOKEN_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetStatus(@ptrCast(*const IXblIdpAuthTokenResult, self), status); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetErrorCode(self: *const T, errorCode: ?*HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetErrorCode(@ptrCast(*const IXblIdpAuthTokenResult, self), errorCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetToken(self: *const T, token: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetToken(@ptrCast(*const IXblIdpAuthTokenResult, self), token); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetSignature(self: *const T, signature: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetSignature(@ptrCast(*const IXblIdpAuthTokenResult, self), signature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetSandbox(self: *const T, sandbox: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetSandbox(@ptrCast(*const IXblIdpAuthTokenResult, self), sandbox); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetEnvironment(self: *const T, environment: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetEnvironment(@ptrCast(*const IXblIdpAuthTokenResult, self), environment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetMsaAccountId(self: *const T, msaAccountId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetMsaAccountId(@ptrCast(*const IXblIdpAuthTokenResult, self), msaAccountId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetXuid(self: *const T, xuid: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetXuid(@ptrCast(*const IXblIdpAuthTokenResult, self), xuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetGamertag(self: *const T, gamertag: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetGamertag(@ptrCast(*const IXblIdpAuthTokenResult, self), gamertag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetAgeGroup(self: *const T, ageGroup: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetAgeGroup(@ptrCast(*const IXblIdpAuthTokenResult, self), ageGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetPrivileges(self: *const T, privileges: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetPrivileges(@ptrCast(*const IXblIdpAuthTokenResult, self), privileges); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetMsaTarget(self: *const T, msaTarget: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetMsaTarget(@ptrCast(*const IXblIdpAuthTokenResult, self), msaTarget); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetMsaPolicy(self: *const T, msaPolicy: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetMsaPolicy(@ptrCast(*const IXblIdpAuthTokenResult, self), msaPolicy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetMsaAppId(self: *const T, msaAppId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetMsaAppId(@ptrCast(*const IXblIdpAuthTokenResult, self), msaAppId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetRedirect(self: *const T, redirect: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetRedirect(@ptrCast(*const IXblIdpAuthTokenResult, self), redirect); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetMessage(self: *const T, message: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetMessage(@ptrCast(*const IXblIdpAuthTokenResult, self), message); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetHelpId(self: *const T, helpId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetHelpId(@ptrCast(*const IXblIdpAuthTokenResult, self), helpId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetEnforcementBans(self: *const T, enforcementBans: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetEnforcementBans(@ptrCast(*const IXblIdpAuthTokenResult, self), enforcementBans); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetRestrictions(self: *const T, restrictions: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetRestrictions(@ptrCast(*const IXblIdpAuthTokenResult, self), restrictions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult_GetTitleRestrictions(self: *const T, titleRestrictions: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult.VTable, self.vtable).GetTitleRestrictions(@ptrCast(*const IXblIdpAuthTokenResult, self), titleRestrictions); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IXblIdpAuthTokenResult2_Value = @import("zig.zig").Guid.initString("75d760b0-60b9-412d-994f-26b2cd5f7812"); pub const IID_IXblIdpAuthTokenResult2 = &IID_IXblIdpAuthTokenResult2_Value; pub const IXblIdpAuthTokenResult2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetModernGamertag: fn( self: *const IXblIdpAuthTokenResult2, value: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetModernGamertagSuffix: fn( self: *const IXblIdpAuthTokenResult2, value: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUniqueModernGamertag: fn( self: *const IXblIdpAuthTokenResult2, value: ?*?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 IXblIdpAuthTokenResult2_GetModernGamertag(self: *const T, value: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult2.VTable, self.vtable).GetModernGamertag(@ptrCast(*const IXblIdpAuthTokenResult2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult2_GetModernGamertagSuffix(self: *const T, value: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult2.VTable, self.vtable).GetModernGamertagSuffix(@ptrCast(*const IXblIdpAuthTokenResult2, self), value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXblIdpAuthTokenResult2_GetUniqueModernGamertag(self: *const T, value: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IXblIdpAuthTokenResult2.VTable, self.vtable).GetUniqueModernGamertag(@ptrCast(*const IXblIdpAuthTokenResult2, self), value); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (30) //-------------------------------------------------------------------------------- pub extern "api-ms-win-gaming-expandedresources-l1-1-0" fn HasExpandedResources( hasExpandedResources: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-expandedresources-l1-1-0" fn GetExpandedResourceExclusiveCpuCount( exclusiveCpuCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-expandedresources-l1-1-0" fn ReleaseExclusiveCpuSets( ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-deviceinformation-l1-1-0" fn GetGamingDeviceModelInformation( information: ?*GAMING_DEVICE_MODEL_INFORMATION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn ShowGameInviteUI( serviceConfigurationId: ?HSTRING, sessionTemplateName: ?HSTRING, sessionId: ?HSTRING, invitationDisplayText: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn ShowPlayerPickerUI( promptDisplayText: ?HSTRING, xuids: [*]const ?HSTRING, xuidsCount: usize, preSelectedXuids: ?[*]const ?HSTRING, preSelectedXuidsCount: usize, minSelectionCount: usize, maxSelectionCount: usize, completionRoutine: ?PlayerPickerUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn ShowProfileCardUI( targetUserXuid: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn ShowChangeFriendRelationshipUI( targetUserXuid: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn ShowTitleAchievementsUI( titleId: u32, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn ProcessPendingGameUI( waitForCompletion: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-0" fn TryCancelPendingGameUI( ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "api-ms-win-gaming-tcui-l1-1-1" fn CheckGamingPrivilegeWithUI( privilegeId: u32, scope: ?HSTRING, policy: ?HSTRING, friendlyMessage: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-1" fn CheckGamingPrivilegeSilently( privilegeId: u32, scope: ?HSTRING, policy: ?HSTRING, hasPrivilege: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn ShowGameInviteUIForUser( user: ?*IInspectable, serviceConfigurationId: ?HSTRING, sessionTemplateName: ?HSTRING, sessionId: ?HSTRING, invitationDisplayText: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn ShowPlayerPickerUIForUser( user: ?*IInspectable, promptDisplayText: ?HSTRING, xuids: [*]const ?HSTRING, xuidsCount: usize, preSelectedXuids: ?[*]const ?HSTRING, preSelectedXuidsCount: usize, minSelectionCount: usize, maxSelectionCount: usize, completionRoutine: ?PlayerPickerUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn ShowProfileCardUIForUser( user: ?*IInspectable, targetUserXuid: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn ShowChangeFriendRelationshipUIForUser( user: ?*IInspectable, targetUserXuid: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn ShowTitleAchievementsUIForUser( user: ?*IInspectable, titleId: u32, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn CheckGamingPrivilegeWithUIForUser( user: ?*IInspectable, privilegeId: u32, scope: ?HSTRING, policy: ?HSTRING, friendlyMessage: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-2" fn CheckGamingPrivilegeSilentlyForUser( user: ?*IInspectable, privilegeId: u32, scope: ?HSTRING, policy: ?HSTRING, hasPrivilege: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-3" fn ShowGameInviteUIWithContext( serviceConfigurationId: ?HSTRING, sessionTemplateName: ?HSTRING, sessionId: ?HSTRING, invitationDisplayText: ?HSTRING, customActivationContext: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-3" fn ShowGameInviteUIWithContextForUser( user: ?*IInspectable, serviceConfigurationId: ?HSTRING, sessionTemplateName: ?HSTRING, sessionId: ?HSTRING, invitationDisplayText: ?HSTRING, customActivationContext: ?HSTRING, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowGameInfoUI( titleId: u32, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowGameInfoUIForUser( user: ?*IInspectable, titleId: u32, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowFindFriendsUI( completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowFindFriendsUIForUser( user: ?*IInspectable, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowCustomizeUserProfileUI( completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowCustomizeUserProfileUIForUser( user: ?*IInspectable, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowUserSettingsUI( completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "api-ms-win-gaming-tcui-l1-1-4" fn ShowUserSettingsUIForUser( user: ?*IInspectable, completionRoutine: ?GameUICompletionRoutine, context: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (6) //-------------------------------------------------------------------------------- const BOOL = @import("foundation.zig").BOOL; const HRESULT = @import("foundation.zig").HRESULT; const HSTRING = @import("system/win_rt.zig").HSTRING; const IInspectable = @import("system/win_rt.zig").IInspectable; const IUnknown = @import("system/com.zig").IUnknown; const PWSTR = @import("foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "GameUICompletionRoutine")) { _ = GameUICompletionRoutine; } if (@hasDecl(@This(), "PlayerPickerUICompletionRoutine")) { _ = PlayerPickerUICompletionRoutine; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
deps/zigwin32/win32/gaming.zig
const ffs = @import("count0bits.zig"); const testing = @import("std").testing; fn test__ffsdi2(a: u64, expected: i32) !void { var x = @bitCast(i64, a); var result = ffs.__ffsdi2(x); try testing.expectEqual(expected, result); } test "ffsdi2" { try test__ffsdi2(0x00000000_00000001, 1); try test__ffsdi2(0x00000000_00000002, 2); try test__ffsdi2(0x00000000_00000003, 1); try test__ffsdi2(0x00000000_00000004, 3); try test__ffsdi2(0x00000000_00000005, 1); try test__ffsdi2(0x00000000_00000006, 2); try test__ffsdi2(0x00000000_00000007, 1); try test__ffsdi2(0x00000000_00000008, 4); try test__ffsdi2(0x00000000_00000009, 1); try test__ffsdi2(0x00000000_0000000A, 2); try test__ffsdi2(0x00000000_0000000B, 1); try test__ffsdi2(0x00000000_0000000C, 3); try test__ffsdi2(0x00000000_0000000D, 1); try test__ffsdi2(0x00000000_0000000E, 2); try test__ffsdi2(0x00000000_0000000F, 1); try test__ffsdi2(0x00000000_00000010, 5); try test__ffsdi2(0x00000000_00000011, 1); try test__ffsdi2(0x00000000_00000012, 2); try test__ffsdi2(0x00000000_00000013, 1); try test__ffsdi2(0x00000000_00000014, 3); try test__ffsdi2(0x00000000_00000015, 1); try test__ffsdi2(0x00000000_00000016, 2); try test__ffsdi2(0x00000000_00000017, 1); try test__ffsdi2(0x00000000_00000018, 4); try test__ffsdi2(0x00000000_00000019, 1); try test__ffsdi2(0x00000000_0000001A, 2); try test__ffsdi2(0x00000000_0000001B, 1); try test__ffsdi2(0x00000000_0000001C, 3); try test__ffsdi2(0x00000000_0000001D, 1); try test__ffsdi2(0x00000000_0000001E, 2); try test__ffsdi2(0x00000000_0000001F, 1); try test__ffsdi2(0x00000000_00000020, 6); try test__ffsdi2(0x00000000_00000021, 1); try test__ffsdi2(0x00000000_00000022, 2); try test__ffsdi2(0x00000000_00000023, 1); try test__ffsdi2(0x00000000_00000024, 3); try test__ffsdi2(0x00000000_00000025, 1); try test__ffsdi2(0x00000000_00000026, 2); try test__ffsdi2(0x00000000_00000027, 1); try test__ffsdi2(0x00000000_00000028, 4); try test__ffsdi2(0x00000000_00000029, 1); try test__ffsdi2(0x00000000_0000002A, 2); try test__ffsdi2(0x00000000_0000002B, 1); try test__ffsdi2(0x00000000_0000002C, 3); try test__ffsdi2(0x00000000_0000002D, 1); try test__ffsdi2(0x00000000_0000002E, 2); try test__ffsdi2(0x00000000_0000002F, 1); try test__ffsdi2(0x00000000_00000030, 5); try test__ffsdi2(0x00000000_00000031, 1); try test__ffsdi2(0x00000000_00000032, 2); try test__ffsdi2(0x00000000_00000033, 1); try test__ffsdi2(0x00000000_00000034, 3); try test__ffsdi2(0x00000000_00000035, 1); try test__ffsdi2(0x00000000_00000036, 2); try test__ffsdi2(0x00000000_00000037, 1); try test__ffsdi2(0x00000000_00000038, 4); try test__ffsdi2(0x00000000_00000039, 1); try test__ffsdi2(0x00000000_0000003A, 2); try test__ffsdi2(0x00000000_0000003B, 1); try test__ffsdi2(0x00000000_0000003C, 3); try test__ffsdi2(0x00000000_0000003D, 1); try test__ffsdi2(0x00000000_0000003E, 2); try test__ffsdi2(0x00000000_0000003F, 1); try test__ffsdi2(0x00000000_00000040, 7); try test__ffsdi2(0x00000000_00000041, 1); try test__ffsdi2(0x00000000_00000042, 2); try test__ffsdi2(0x00000000_00000043, 1); try test__ffsdi2(0x00000000_00000044, 3); try test__ffsdi2(0x00000000_00000045, 1); try test__ffsdi2(0x00000000_00000046, 2); try test__ffsdi2(0x00000000_00000047, 1); try test__ffsdi2(0x00000000_00000048, 4); try test__ffsdi2(0x00000000_00000049, 1); try test__ffsdi2(0x00000000_0000004A, 2); try test__ffsdi2(0x00000000_0000004B, 1); try test__ffsdi2(0x00000000_0000004C, 3); try test__ffsdi2(0x00000000_0000004D, 1); try test__ffsdi2(0x00000000_0000004E, 2); try test__ffsdi2(0x00000000_0000004F, 1); try test__ffsdi2(0x00000000_00000050, 5); try test__ffsdi2(0x00000000_00000051, 1); try test__ffsdi2(0x00000000_00000052, 2); try test__ffsdi2(0x00000000_00000053, 1); try test__ffsdi2(0x00000000_00000054, 3); try test__ffsdi2(0x00000000_00000055, 1); try test__ffsdi2(0x00000000_00000056, 2); try test__ffsdi2(0x00000000_00000057, 1); try test__ffsdi2(0x00000000_00000058, 4); try test__ffsdi2(0x00000000_00000059, 1); try test__ffsdi2(0x00000000_0000005A, 2); try test__ffsdi2(0x00000000_0000005B, 1); try test__ffsdi2(0x00000000_0000005C, 3); try test__ffsdi2(0x00000000_0000005D, 1); try test__ffsdi2(0x00000000_0000005E, 2); try test__ffsdi2(0x00000000_0000005F, 1); try test__ffsdi2(0x00000000_00000060, 6); try test__ffsdi2(0x00000000_00000061, 1); try test__ffsdi2(0x00000000_00000062, 2); try test__ffsdi2(0x00000000_00000063, 1); try test__ffsdi2(0x00000000_00000064, 3); try test__ffsdi2(0x00000000_00000065, 1); try test__ffsdi2(0x00000000_00000066, 2); try test__ffsdi2(0x00000000_00000067, 1); try test__ffsdi2(0x00000000_00000068, 4); try test__ffsdi2(0x00000000_00000069, 1); try test__ffsdi2(0x00000000_0000006A, 2); try test__ffsdi2(0x00000000_0000006B, 1); try test__ffsdi2(0x00000000_0000006C, 3); try test__ffsdi2(0x00000000_0000006D, 1); try test__ffsdi2(0x00000000_0000006E, 2); try test__ffsdi2(0x00000000_0000006F, 1); try test__ffsdi2(0x00000000_00000070, 5); try test__ffsdi2(0x00000000_00000071, 1); try test__ffsdi2(0x00000000_00000072, 2); try test__ffsdi2(0x00000000_00000073, 1); try test__ffsdi2(0x00000000_00000074, 3); try test__ffsdi2(0x00000000_00000075, 1); try test__ffsdi2(0x00000000_00000076, 2); try test__ffsdi2(0x00000000_00000077, 1); try test__ffsdi2(0x00000000_00000078, 4); try test__ffsdi2(0x00000000_00000079, 1); try test__ffsdi2(0x00000000_0000007A, 2); try test__ffsdi2(0x00000000_0000007B, 1); try test__ffsdi2(0x00000000_0000007C, 3); try test__ffsdi2(0x00000000_0000007D, 1); try test__ffsdi2(0x00000000_0000007E, 2); try test__ffsdi2(0x00000000_0000007F, 1); try test__ffsdi2(0x00000000_00000080, 8); try test__ffsdi2(0x00000000_00000081, 1); try test__ffsdi2(0x00000000_00000082, 2); try test__ffsdi2(0x00000000_00000083, 1); try test__ffsdi2(0x00000000_00000084, 3); try test__ffsdi2(0x00000000_00000085, 1); try test__ffsdi2(0x00000000_00000086, 2); try test__ffsdi2(0x00000000_00000087, 1); try test__ffsdi2(0x00000000_00000088, 4); try test__ffsdi2(0x00000000_00000089, 1); try test__ffsdi2(0x00000000_0000008A, 2); try test__ffsdi2(0x00000000_0000008B, 1); try test__ffsdi2(0x00000000_0000008C, 3); try test__ffsdi2(0x00000000_0000008D, 1); try test__ffsdi2(0x00000000_0000008E, 2); try test__ffsdi2(0x00000000_0000008F, 1); try test__ffsdi2(0x00000000_00000090, 5); try test__ffsdi2(0x00000000_00000091, 1); try test__ffsdi2(0x00000000_00000092, 2); try test__ffsdi2(0x00000000_00000093, 1); try test__ffsdi2(0x00000000_00000094, 3); try test__ffsdi2(0x00000000_00000095, 1); try test__ffsdi2(0x00000000_00000096, 2); try test__ffsdi2(0x00000000_00000097, 1); try test__ffsdi2(0x00000000_00000098, 4); try test__ffsdi2(0x00000000_00000099, 1); try test__ffsdi2(0x00000000_0000009A, 2); try test__ffsdi2(0x00000000_0000009B, 1); try test__ffsdi2(0x00000000_0000009C, 3); try test__ffsdi2(0x00000000_0000009D, 1); try test__ffsdi2(0x00000000_0000009E, 2); try test__ffsdi2(0x00000000_0000009F, 1); try test__ffsdi2(0x00000000_000000A0, 6); try test__ffsdi2(0x00000000_000000A1, 1); try test__ffsdi2(0x00000000_000000A2, 2); try test__ffsdi2(0x00000000_000000A3, 1); try test__ffsdi2(0x00000000_000000A4, 3); try test__ffsdi2(0x00000000_000000A5, 1); try test__ffsdi2(0x00000000_000000A6, 2); try test__ffsdi2(0x00000000_000000A7, 1); try test__ffsdi2(0x00000000_000000A8, 4); try test__ffsdi2(0x00000000_000000A9, 1); try test__ffsdi2(0x00000000_000000AA, 2); try test__ffsdi2(0x00000000_000000AB, 1); try test__ffsdi2(0x00000000_000000AC, 3); try test__ffsdi2(0x00000000_000000AD, 1); try test__ffsdi2(0x00000000_000000AE, 2); try test__ffsdi2(0x00000000_000000AF, 1); try test__ffsdi2(0x00000000_000000B0, 5); try test__ffsdi2(0x00000000_000000B1, 1); try test__ffsdi2(0x00000000_000000B2, 2); try test__ffsdi2(0x00000000_000000B3, 1); try test__ffsdi2(0x00000000_000000B4, 3); try test__ffsdi2(0x00000000_000000B5, 1); try test__ffsdi2(0x00000000_000000B6, 2); try test__ffsdi2(0x00000000_000000B7, 1); try test__ffsdi2(0x00000000_000000B8, 4); try test__ffsdi2(0x00000000_000000B9, 1); try test__ffsdi2(0x00000000_000000BA, 2); try test__ffsdi2(0x00000000_000000BB, 1); try test__ffsdi2(0x00000000_000000BC, 3); try test__ffsdi2(0x00000000_000000BD, 1); try test__ffsdi2(0x00000000_000000BE, 2); try test__ffsdi2(0x00000000_000000BF, 1); try test__ffsdi2(0x00000000_000000C0, 7); try test__ffsdi2(0x00000000_000000C1, 1); try test__ffsdi2(0x00000000_000000C2, 2); try test__ffsdi2(0x00000000_000000C3, 1); try test__ffsdi2(0x00000000_000000C4, 3); try test__ffsdi2(0x00000000_000000C5, 1); try test__ffsdi2(0x00000000_000000C6, 2); try test__ffsdi2(0x00000000_000000C7, 1); try test__ffsdi2(0x00000000_000000C8, 4); try test__ffsdi2(0x00000000_000000C9, 1); try test__ffsdi2(0x00000000_000000CA, 2); try test__ffsdi2(0x00000000_000000CB, 1); try test__ffsdi2(0x00000000_000000CC, 3); try test__ffsdi2(0x00000000_000000CD, 1); try test__ffsdi2(0x00000000_000000CE, 2); try test__ffsdi2(0x00000000_000000CF, 1); try test__ffsdi2(0x00000000_000000D0, 5); try test__ffsdi2(0x00000000_000000D1, 1); try test__ffsdi2(0x00000000_000000D2, 2); try test__ffsdi2(0x00000000_000000D3, 1); try test__ffsdi2(0x00000000_000000D4, 3); try test__ffsdi2(0x00000000_000000D5, 1); try test__ffsdi2(0x00000000_000000D6, 2); try test__ffsdi2(0x00000000_000000D7, 1); try test__ffsdi2(0x00000000_000000D8, 4); try test__ffsdi2(0x00000000_000000D9, 1); try test__ffsdi2(0x00000000_000000DA, 2); try test__ffsdi2(0x00000000_000000DB, 1); try test__ffsdi2(0x00000000_000000DC, 3); try test__ffsdi2(0x00000000_000000DD, 1); try test__ffsdi2(0x00000000_000000DE, 2); try test__ffsdi2(0x00000000_000000DF, 1); try test__ffsdi2(0x00000000_000000E0, 6); try test__ffsdi2(0x00000000_000000E1, 1); try test__ffsdi2(0x00000000_000000E2, 2); try test__ffsdi2(0x00000000_000000E3, 1); try test__ffsdi2(0x00000000_000000E4, 3); try test__ffsdi2(0x00000000_000000E5, 1); try test__ffsdi2(0x00000000_000000E6, 2); try test__ffsdi2(0x00000000_000000E7, 1); try test__ffsdi2(0x00000000_000000E8, 4); try test__ffsdi2(0x00000000_000000E9, 1); try test__ffsdi2(0x00000000_000000EA, 2); try test__ffsdi2(0x00000000_000000EB, 1); try test__ffsdi2(0x00000000_000000EC, 3); try test__ffsdi2(0x00000000_000000ED, 1); try test__ffsdi2(0x00000000_000000EE, 2); try test__ffsdi2(0x00000000_000000EF, 1); try test__ffsdi2(0x00000000_000000F0, 5); try test__ffsdi2(0x00000000_000000F1, 1); try test__ffsdi2(0x00000000_000000F2, 2); try test__ffsdi2(0x00000000_000000F3, 1); try test__ffsdi2(0x00000000_000000F4, 3); try test__ffsdi2(0x00000000_000000F5, 1); try test__ffsdi2(0x00000000_000000F6, 2); try test__ffsdi2(0x00000000_000000F7, 1); try test__ffsdi2(0x00000000_000000F8, 4); try test__ffsdi2(0x00000000_000000F9, 1); try test__ffsdi2(0x00000000_000000FA, 2); try test__ffsdi2(0x00000000_000000FB, 1); try test__ffsdi2(0x00000000_000000FC, 3); try test__ffsdi2(0x00000000_000000FD, 1); try test__ffsdi2(0x00000000_000000FE, 2); try test__ffsdi2(0x00000000_000000FF, 1); try test__ffsdi2(0x00000000_00000000, 0); try test__ffsdi2(0x80000000_00000000, 64); try test__ffsdi2(0x40000000_00000000, 63); try test__ffsdi2(0x20000000_00000000, 62); try test__ffsdi2(0x10000000_00000000, 61); try test__ffsdi2(0x08000000_00000000, 60); try test__ffsdi2(0x04000000_00000000, 59); try test__ffsdi2(0x02000000_00000000, 58); try test__ffsdi2(0x01000000_00000000, 57); try test__ffsdi2(0x00800000_00000000, 56); try test__ffsdi2(0x00400000_00000000, 55); try test__ffsdi2(0x00200000_00000000, 54); try test__ffsdi2(0x00100000_00000000, 53); try test__ffsdi2(0x00080000_00000000, 52); try test__ffsdi2(0x00040000_00000000, 51); try test__ffsdi2(0x00020000_00000000, 50); try test__ffsdi2(0x00010000_00000000, 49); try test__ffsdi2(0x00008000_00000000, 48); try test__ffsdi2(0x00004000_00000000, 47); try test__ffsdi2(0x00002000_00000000, 46); try test__ffsdi2(0x00001000_00000000, 45); try test__ffsdi2(0x00000800_00000000, 44); try test__ffsdi2(0x00000400_00000000, 43); try test__ffsdi2(0x00000200_00000000, 42); try test__ffsdi2(0x00000100_00000000, 41); try test__ffsdi2(0x00000080_00000000, 40); try test__ffsdi2(0x00000040_00000000, 39); try test__ffsdi2(0x00000020_00000000, 38); try test__ffsdi2(0x00000010_00000000, 37); try test__ffsdi2(0x00000008_00000000, 36); try test__ffsdi2(0x00000004_00000000, 35); try test__ffsdi2(0x00000002_00000000, 34); try test__ffsdi2(0x00000001_00000000, 33); try test__ffsdi2(0x00000000_80000000, 32); try test__ffsdi2(0x00000000_40000000, 31); try test__ffsdi2(0x00000000_20000000, 30); try test__ffsdi2(0x00000000_10000000, 29); try test__ffsdi2(0x00000000_08000000, 28); try test__ffsdi2(0x00000000_04000000, 27); try test__ffsdi2(0x00000000_02000000, 26); try test__ffsdi2(0x00000000_01000000, 25); try test__ffsdi2(0x00000000_00800000, 24); try test__ffsdi2(0x00000000_00400000, 23); try test__ffsdi2(0x00000000_00200000, 22); try test__ffsdi2(0x00000000_00100000, 21); try test__ffsdi2(0x00000000_00080000, 20); try test__ffsdi2(0x00000000_00040000, 19); try test__ffsdi2(0x00000000_00020000, 18); try test__ffsdi2(0x00000000_00010000, 17); try test__ffsdi2(0x00000000_00008000, 16); try test__ffsdi2(0x00000000_00004000, 15); try test__ffsdi2(0x00000000_00002000, 14); try test__ffsdi2(0x00000000_00001000, 13); try test__ffsdi2(0x00000000_00000800, 12); try test__ffsdi2(0x00000000_00000400, 11); try test__ffsdi2(0x00000000_00000200, 10); try test__ffsdi2(0x00000000_00000100, 9); }
lib/std/special/compiler_rt/ffsdi2_test.zig
const std = @import("std"); pub usingnamespace @import("./Formatter/property.zig"); pub fn format(allocator: *std.mem.Allocator, string: []const u8, prop: []Property) ![]const u8 { var str = std.ArrayList(u8).init(allocator); var i: usize = 0; while (true) { if (i == prop.len) break; _ = try prop[i].write(str.writer()); i += 1; } for (string) |char| { if (char == '%') { try str.appendSlice("%%"); } else { try str.append(char); } } i -= 1; while (true) { if (prop[i].close()) |p| { _ = try p.write(str.writer()); } if (i == 0) break; i -= 1; } return str.toOwnedSlice(); } pub fn unformat(allocator: *std.mem.Allocator, string: []const u8) ![]const u8 { var str = std.ArrayList(u8).init(allocator); var i: usize = 0; while (i < string.len) : (i += 1) { if (string[i] == '%') { if (string[i + 1] == '%') { try str.append(string[i]); continue; } var l = std.mem.indexOf(u8, string[i..], "}"); if (l) |idx| i += idx; } else { try str.append(string[i]); } } return str.toOwnedSlice(); } test "format string" { var prop = [_]Property{ .swap, .{ .offset = 16 }, .{ .background = comptime try Color.fromString("#deadbeef") }, }; var str1 = try format(std.testing.allocator, "Hello, World!", &prop); defer std.testing.allocator.free(str1); var str2 = try format(std.testing.allocator, "Battery: 100%", &prop); defer std.testing.allocator.free(str2); std.testing.expectEqualStrings("%{R}%{O16}%{B#deadbeef}Hello, World!%{B-}%{R}", str1); std.testing.expectEqualStrings("%{R}%{O16}%{B#deadbeef}Battery: 100%%%{B-}%{R}", str2); } test "unformat string" { var q1 = try unformat(std.testing.allocator, "%{F#ff0000}Hello%{F-}, %{R}World!%{R}"); defer std.testing.allocator.free(q1); var q2 = try unformat(std.testing.allocator, "Battery: %{T1}100%{T-}%%"); defer std.testing.allocator.free(q2); std.testing.expectEqualStrings("Hello, World!", q1); std.testing.expectEqualStrings("Battery: 100%", q2); }
src/Formatter.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const info = std.log.info; const print = std.debug.print; const fmt = std.fmt; const ArrayList = std.ArrayList; const assert = std.debug.assert; const utils = @import("utils.zig"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const P2Type = struct { allergen: []u8, ingredient: []u8 }; const P2Ctx = struct { allo: *std.mem.Allocator }; fn lt_fn(ctx: P2Ctx, a: P2Type, b: P2Type) bool { const a_val = std.cstr.addNullByte(ctx.allo, a.allergen) catch unreachable; const b_val = std.cstr.addNullByte(ctx.allo, b.allergen) catch unreachable; const result = std.cstr.cmp(a_val, b_val) == -1; ctx.allo.free(a_val); ctx.allo.free(b_val); return result; } const Entry = struct { allocator: *std.mem.Allocator, ingredients: ArrayList([]u8), allergens: ArrayList([]u8), pub fn from_line(allo: *std.mem.Allocator, line: []const u8) Entry { var ingredients = ArrayList([]u8).init(allo); var allergens = ArrayList([]u8).init(allo); const token_sep: [1]u8 = .{' '}; var token_iter = std.mem.split(line, &token_sep); // parse ingredients while (token_iter.next()) |token| { if (std.mem.startsWith(u8, token, "(")) break; // allergen time const ingredient = allo.dupe(u8, token) catch unreachable; ingredients.append(ingredient) catch unreachable; } // parse allergens while (token_iter.next()) |token| { const clean_token = token[0 .. token.len - 1]; const allergen = allo.dupe(u8, clean_token) catch unreachable; allergens.append(allergen) catch unreachable; } return .{ .allocator = allo, .ingredients = ingredients, .allergens = allergens, }; } pub fn contains_ingredient(self: *const Entry, target_ingredient: []const u8) i32 { for (self.ingredients.items) |ingredient, i| { if (std.ascii.eqlIgnoreCase(ingredient, target_ingredient)) return @intCast(i32, i); } return -1; } pub fn contains_allergen(self: *const Entry, target_allergen: []const u8) i32 { for (self.allergens.items) |allergen, i| { if (std.ascii.eqlIgnoreCase(allergen, target_allergen)) return @intCast(i32, i); } return -1; } pub fn remove_ingredient(self: *Entry, ingr: []const u8) void { const index = self.contains_ingredient(ingr); if (index < 0) return; const item = self.ingredients.swapRemove(@intCast(usize, index)); self.allocator.free(item); } pub fn remove_allergen(self: *Entry, aller: []const u8) void { const index = self.contains_allergen(aller); if (index < 0) return; const item = self.allergens.swapRemove(@intCast(usize, index)); self.allocator.free(item); } pub fn print(self: *const Entry) void { print("<", .{}); for (self.ingredients.items) |item| { print("{} ", .{item}); } print(" -- ", .{}); for (self.allergens.items) |item| { print("{} ", .{item}); } print(">\n", .{}); } pub fn deinit(self: *Entry) void { for (self.ingredients.items) |ingredient| self.allocator.free(ingredient); self.ingredients.deinit(); for (self.allergens.items) |allergen| self.allocator.free(allergen); self.allergens.deinit(); } }; pub fn get_unique_allergens(entries: []Entry, output: *ArrayList([]u8)) void { // populate arraylist with all unique allergens for (entries) |entry| { for (entry.allergens.items) |allergen| { var exists = false; for (output.items) |existing_allergen| { const match = std.ascii.eqlIgnoreCase(existing_allergen, allergen); if (match) { exists = true; break; } } if (!exists) output.append(allergen) catch unreachable; } } } pub fn main() !void { const begin = @divTrunc(std.time.nanoTimestamp(), 1000); // setup // var p1: usize = 1; defer _ = gpa.deinit(); var allo = &gpa.allocator; var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1"); defer allo.free(lines.buffer); var entries = try allo.alloc(Entry, 0); defer { for (entries) |*entry| entry.deinit(); allo.free(entries); } while (lines.next()) |line| { const entry = Entry.from_line(allo, line); entries = try allo.realloc(entries, entries.len + 1); entries[entries.len - 1] = entry; } info("entries: {}", .{entries.len}); // p1 // info("== solving p1 ==", .{}); var pairs = ArrayList(P2Type).init(allo); // for p2 defer pairs.deinit(); var unique_allergens = ArrayList([]u8).init(allo); defer unique_allergens.deinit(); get_unique_allergens(entries, &unique_allergens); while (true) { for (unique_allergens.items) |target_allergen, ua_i| { info(">> matching unique allergen: {} in {} entries", .{ target_allergen, entries.len }); //for (entries) |entry| { // entry.print(); //} var candidate_ingredients = std.BufSet.init(allo); defer candidate_ingredients.deinit(); var inited = false; for (entries) |entry, i| { if (!(entry.contains_allergen(target_allergen) >= 0)) { continue; } if (!inited) { inited = true; for (entry.ingredients.items) |ingredient| { candidate_ingredients.put(ingredient) catch unreachable; } } else { var existing_ingr = candidate_ingredients.iterator(); // remove old ingredients that are not in this entry while (existing_ingr.next()) |ingr| { if (!(entry.contains_ingredient(ingr.key) >= 0)) { candidate_ingredients.delete(ingr.key); } } } } // should only be one candidate left if (candidate_ingredients.count() == 1) { const ingredient = candidate_ingredients.iterator().next() orelse unreachable; info("!!! allergen {} is in {}", .{ target_allergen, ingredient.key }); // for p2 const _ingredient = try allo.dupe(u8, ingredient.key); const _allergen = try allo.dupe(u8, target_allergen); try pairs.append(P2Type{ .allergen = _allergen, .ingredient = _ingredient }); // end for p2 // remove this ingredient and allergen from all entries for (entries) |*entry| { entry.remove_ingredient(ingredient.key); entry.remove_allergen(target_allergen); } _ = unique_allergens.swapRemove(ua_i); break; } } if (unique_allergens.items.len == 0) { break; } } var p1_result: usize = 0; for (entries) |entry| { p1_result += entry.ingredients.items.len; } info("p1: {}", .{p1_result}); // p2 // std.sort.sort(P2Type, pairs.items, P2Ctx{ .allo = allo }, lt_fn); print("p2: ", .{}); for (pairs.items) |item| { print("{},", .{item.ingredient}); allo.free(item.ingredient); allo.free(item.allergen); } print("\n", .{}); // end const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin; print("all done in {} microseconds\n", .{delta}); }
day_21/src/main.zig
const std = @import("std"); const crypto = std.crypto; const debug = std.debug; const fmt = std.fmt; const math = std.math; const mem = std.mem; const pwhash = crypto.pwhash; const testing = std.testing; const Sha512 = crypto.hash.sha2.Sha512; const utils = crypto.utils; const phc_format = @import("phc_encoding.zig"); const KdfError = pwhash.KdfError; const HasherError = pwhash.HasherError; const EncodingError = phc_format.Error; const Error = pwhash.Error; const salt_length: usize = 16; const salt_str_length: usize = 22; const ct_str_length: usize = 31; const ct_length: usize = 24; const dk_length: usize = ct_length - 1; /// Length (in bytes) of a password hash in crypt encoding pub const hash_length: usize = 60; pub const State = struct { sboxes: [4][256]u32 = [4][256]u32{ .{ 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e, 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440, 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a, 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677, 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032, 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239, 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0, 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98, 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe, 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d, 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7, 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463, 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09, 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb, 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8, 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82, 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573, 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b, 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8, 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0, 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c, 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1, 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9, 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf, 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af, 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5, 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915, 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915, 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a, }, .{ 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266, 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e, 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1, 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1, 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8, 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd, 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7, 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331, 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af, 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87, 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2, 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd, 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509, 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3, 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a, 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960, 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28, 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84, 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf, 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e, 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7, 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281, 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696, 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73, 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0, 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250, 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285, 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061, 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e, 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc, 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340, 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7, }, .{ 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068, 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840, 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504, 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb, 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6, 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b, 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb, 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b, 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c, 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc, 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564, 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115, 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728, 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e, 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d, 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b, 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb, 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c, 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9, 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe, 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc, 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61, 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9, 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c, 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633, 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169, 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027, 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62, 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76, 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc, 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c, 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0, }, .{ 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe, 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4, 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6, 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22, 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6, 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59, 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51, 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c, 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28, 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd, 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319, 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f, 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32, 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166, 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb, 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47, 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d, 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048, 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd, 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7, 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f, 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525, 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442, 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e, 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d, 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299, 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc, 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a, 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b, 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060, 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9, 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6, }, }, subkeys: [18]u32 = [18]u32{ 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917, 0x9216d5d9, 0x8979fb1b, }, fn toWord(data: []const u8, current: *usize) u32 { var t: u32 = 0; var j = current.*; var i: usize = 0; while (i < 4) : (i += 1) { if (j >= data.len) j = 0; t = (t << 8) | data[j]; j += 1; } current.* = j; return t; } fn expand0(state: *State, key: []const u8) void { var i: usize = 0; var j: usize = 0; while (i < state.subkeys.len) : (i += 1) { state.subkeys[i] ^= toWord(key, &j); } var halves = Halves{ .l = 0, .r = 0 }; i = 0; while (i < 18) : (i += 2) { state.encipher(&halves); state.subkeys[i] = halves.l; state.subkeys[i + 1] = halves.r; } i = 0; while (i < 4) : (i += 1) { var k: usize = 0; while (k < 256) : (k += 2) { state.encipher(&halves); state.sboxes[i][k] = halves.l; state.sboxes[i][k + 1] = halves.r; } } } fn expand(state: *State, data: []const u8, key: []const u8) void { var i: usize = 0; var j: usize = 0; while (i < state.subkeys.len) : (i += 1) { state.subkeys[i] ^= toWord(key, &j); } var halves = Halves{ .l = 0, .r = 0 }; i = 0; j = 0; while (i < 18) : (i += 2) { halves.l ^= toWord(data, &j); halves.r ^= toWord(data, &j); state.encipher(&halves); state.subkeys[i] = halves.l; state.subkeys[i + 1] = halves.r; } i = 0; while (i < 4) : (i += 1) { var k: usize = 0; while (k < 256) : (k += 2) { halves.l ^= toWord(data, &j); halves.r ^= toWord(data, &j); state.encipher(&halves); state.sboxes[i][k] = halves.l; state.sboxes[i][k + 1] = halves.r; } } } const Halves = struct { l: u32, r: u32 }; fn feistelF(state: State, x: u32) u32 { var r = state.sboxes[0][@truncate(u8, x >> 24)]; r +%= state.sboxes[1][@truncate(u8, x >> 16)]; r ^= state.sboxes[2][@truncate(u8, x >> 8)]; r +%= state.sboxes[3][@truncate(u8, x)]; return r; } fn halfRound(state: State, i: u32, j: u32, n: usize) u32 { return i ^ state.feistelF(j) ^ state.subkeys[n]; } fn encipher(state: State, halves: *Halves) void { halves.l ^= state.subkeys[0]; var i: usize = 1; while (i < 16) : (i += 2) { halves.r = state.halfRound(halves.r, halves.l, i); halves.l = state.halfRound(halves.l, halves.r, i + 1); } const halves_last = Halves{ .l = halves.r ^ state.subkeys[i], .r = halves.l }; halves.* = halves_last; } fn encrypt(state: State, data: []u32) void { debug.assert(data.len % 2 == 0); var i: usize = 0; while (i < data.len) : (i += 2) { var halves = Halves{ .l = data[i], .r = data[i + 1] }; state.encipher(&halves); data[i] = halves.l; data[i + 1] = halves.r; } } }; pub const Params = struct { rounds_log: u6, }; pub fn bcrypt( password: []const u8, salt: [salt_length]u8, params: Params, ) [dk_length]u8 { var state = State{}; var password_buf: [73]u8 = undefined; const trimmed_len = math.min(password.len, password_buf.len - 1); mem.copy(u8, password_buf[0..], password[0..trimmed_len]); password_buf[trimmed_len] = 0; var passwordZ = password_buf[0 .. trimmed_len + 1]; state.expand(salt[0..], passwordZ); const rounds: u64 = @as(u64, 1) << params.rounds_log; var k: u64 = 0; while (k < rounds) : (k += 1) { state.expand0(passwordZ); state.expand0(salt[0..]); } utils.secureZero(u8, &password_buf); var cdata = [6]u32{ 0x4f727068, 0x65616e42, 0x65686f6c, 0x64657253, 0x63727944, 0x6f756274 }; // "OrpheanBeholderScryDoubt" k = 0; while (k < 64) : (k += 1) { state.encrypt(&cdata); } var ct: [ct_length]u8 = undefined; for (cdata) |c, i| { mem.writeIntBig(u32, ct[i * 4 ..][0..4], c); } return ct[0..dk_length].*; } const pbkdf_prf = struct { const Self = @This(); pub const mac_length = 32; hasher: Sha512, sha2pass: [Sha512.digest_length]u8, pub fn create(out: *[mac_length]u8, msg: []const u8, key: []const u8) void { var ctx = Self.init(key); ctx.update(msg); ctx.final(out); } pub fn init(key: []const u8) Self { var self: Self = undefined; self.hasher = Sha512.init(.{}); Sha512.hash(key, &self.sha2pass, .{}); return self; } pub fn update(self: *Self, msg: []const u8) void { self.hasher.update(msg); } pub fn final(self: *Self, out: *[mac_length]u8) void { var sha2salt: [Sha512.digest_length]u8 = undefined; self.hasher.final(&sha2salt); out.* = hash(self.sha2pass, sha2salt); } /// Matches OpenBSD function /// https://github.com/openbsd/src/blob/6df1256b7792691e66c2ed9d86a8c103069f9e34/lib/libutil/bcrypt_pbkdf.c#L98 fn hash(sha2pass: [Sha512.digest_length]u8, sha2salt: [Sha512.digest_length]u8) [32]u8 { var cdata: [8]u32 = undefined; { const ciphertext = "OxychromaticBlowfishSwatDynamite"; var j: usize = 0; for (cdata) |*v| { v.* = State.toWord(ciphertext, &j); } } var state = State{}; { // key expansion state.expand(&sha2salt, &sha2pass); var i: usize = 0; while (i < 64) : (i += 1) { state.expand0(&sha2salt); state.expand0(&sha2pass); } } { // encryption var i: usize = 0; while (i < 64) : (i += 1) { state.encrypt(&cdata); } } // copy out var out: [32]u8 = undefined; for (cdata) |v, i| { std.mem.writeIntLittle(u32, out[4 * i ..][0..4], v); } // zap crypto.utils.secureZero(u32, &cdata); crypto.utils.secureZero(State, @as(*[1]State, &state)); return out; } }; /// bcrypt PBKDF2 implementation with variations to match OpenBSD /// https://github.com/openbsd/src/blob/6df1256b7792691e66c2ed9d86a8c103069f9e34/lib/libutil/bcrypt_pbkdf.c#L98 /// /// This particular variant is used in e.g. SSH pub fn pbkdf(pass: []const u8, salt: []const u8, key: []u8, rounds: u32) !void { try crypto.pwhash.pbkdf2(key, pass, salt, rounds, pbkdf_prf); } const crypt_format = struct { /// String prefix for bcrypt pub const prefix = "$2"; // bcrypt has its own variant of base64, with its own alphabet and no padding const Codec = struct { const alphabet = "./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; fn encode(b64: []u8, bin: []const u8) void { var i: usize = 0; var j: usize = 0; while (i < bin.len) { var c1 = bin[i]; i += 1; b64[j] = alphabet[c1 >> 2]; j += 1; c1 = (c1 & 3) << 4; if (i >= bin.len) { b64[j] = alphabet[c1]; j += 1; break; } var c2 = bin[i]; i += 1; c1 |= (c2 >> 4) & 0x0f; b64[j] = alphabet[c1]; j += 1; c1 = (c2 & 0x0f) << 2; if (i >= bin.len) { b64[j] = alphabet[c1]; j += 1; break; } c2 = bin[i]; i += 1; c1 |= (c2 >> 6) & 3; b64[j] = alphabet[c1]; b64[j + 1] = alphabet[c2 & 0x3f]; j += 2; } debug.assert(j == b64.len); } fn decode(bin: []u8, b64: []const u8) EncodingError!void { var i: usize = 0; var j: usize = 0; while (j < bin.len) { const c1 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i]) orelse return EncodingError.InvalidEncoding); const c2 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 1]) orelse return EncodingError.InvalidEncoding); bin[j] = (c1 << 2) | ((c2 & 0x30) >> 4); j += 1; if (j >= bin.len) { break; } const c3 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 2]) orelse return EncodingError.InvalidEncoding); bin[j] = ((c2 & 0x0f) << 4) | ((c3 & 0x3c) >> 2); j += 1; if (j >= bin.len) { break; } const c4 = @intCast(u8, mem.indexOfScalar(u8, alphabet, b64[i + 3]) orelse return EncodingError.InvalidEncoding); bin[j] = ((c3 & 0x03) << 6) | c4; j += 1; i += 4; } } }; fn strHashInternal( password: []const u8, salt: [salt_length]u8, params: Params, ) [hash_length]u8 { var dk = bcrypt(password, salt, params); var salt_str: [salt_str_length]u8 = undefined; Codec.encode(salt_str[0..], salt[0..]); var ct_str: [ct_str_length]u8 = undefined; Codec.encode(ct_str[0..], dk[0..]); var s_buf: [hash_length]u8 = undefined; const s = fmt.bufPrint( s_buf[0..], "{s}b${d}{d}${s}{s}", .{ prefix, params.rounds_log / 10, params.rounds_log % 10, salt_str, ct_str }, ) catch unreachable; debug.assert(s.len == s_buf.len); return s_buf; } }; /// Hash and verify passwords using the PHC format. const PhcFormatHasher = struct { const alg_id = "bcrypt"; const BinValue = phc_format.BinValue; const HashResult = struct { alg_id: []const u8, r: u6, salt: BinValue(salt_length), hash: BinValue(dk_length), }; /// Return a non-deterministic hash of the password encoded as a PHC-format string pub fn create( password: []const u8, params: Params, buf: []u8, ) HasherError![]const u8 { var salt: [salt_length]u8 = undefined; crypto.random.bytes(&salt); const hash = bcrypt(password, salt, params); return phc_format.serialize(HashResult{ .alg_id = alg_id, .r = params.rounds_log, .salt = try BinValue(salt_length).fromSlice(&salt), .hash = try BinValue(dk_length).fromSlice(&hash), }, buf); } /// Verify a password against a PHC-format encoded string pub fn verify( str: []const u8, password: []const u8, ) HasherError!void { const hash_result = try phc_format.deserialize(HashResult, str); if (!mem.eql(u8, hash_result.alg_id, alg_id)) return HasherError.PasswordVerificationFailed; if (hash_result.salt.len != salt_length or hash_result.hash.len != dk_length) return HasherError.InvalidEncoding; const hash = bcrypt(password, hash_result.salt.buf, .{ .rounds_log = hash_result.r }); const expected_hash = hash_result.hash.constSlice(); if (!mem.eql(u8, &hash, expected_hash)) return HasherError.PasswordVerificationFailed; } }; /// Hash and verify passwords using the modular crypt format. const CryptFormatHasher = struct { /// Length of a string returned by the create() function pub const pwhash_str_length: usize = hash_length; /// Return a non-deterministic hash of the password encoded into the modular crypt format pub fn create( password: []const u8, params: Params, buf: []u8, ) HasherError![]const u8 { if (buf.len < pwhash_str_length) return HasherError.NoSpaceLeft; var salt: [salt_length]u8 = undefined; crypto.random.bytes(&salt); const hash = crypt_format.strHashInternal(password, salt, params); mem.copy(u8, buf, &hash); return buf[0..pwhash_str_length]; } /// Verify a password against a string in modular crypt format pub fn verify( str: []const u8, password: []const u8, ) HasherError!void { if (str.len != pwhash_str_length or str[3] != '$' or str[6] != '$') return HasherError.InvalidEncoding; const rounds_log_str = str[4..][0..2]; const rounds_log = fmt.parseInt(u6, rounds_log_str[0..], 10) catch return HasherError.InvalidEncoding; const salt_str = str[7..][0..salt_str_length]; var salt: [salt_length]u8 = undefined; try crypt_format.Codec.decode(salt[0..], salt_str[0..]); const wanted_s = crypt_format.strHashInternal(password, salt, .{ .rounds_log = rounds_log }); if (!mem.eql(u8, wanted_s[0..], str[0..])) return HasherError.PasswordVerificationFailed; } }; /// Options for hashing a password. pub const HashOptions = struct { allocator: ?mem.Allocator = null, params: Params, encoding: pwhash.Encoding, }; /// Compute a hash of a password using 2^rounds_log rounds of the bcrypt key stretching function. /// bcrypt is a computationally expensive and cache-hard function, explicitly designed to slow down exhaustive searches. /// /// The function returns a string that includes all the parameters required for verification. /// /// IMPORTANT: by design, bcrypt silently truncates passwords to 72 bytes. /// If this is an issue for your application, hash the password first using a function such as SHA-512, /// and then use the resulting hash as the password parameter for bcrypt. pub fn strHash( password: []const u8, options: HashOptions, out: []u8, ) Error![]const u8 { switch (options.encoding) { .phc => return PhcFormatHasher.create(password, options.params, out), .crypt => return CryptFormatHasher.create(password, options.params, out), } } /// Options for hash verification. pub const VerifyOptions = struct { allocator: ?mem.Allocator = null, }; /// Verify that a previously computed hash is valid for a given password. pub fn strVerify( str: []const u8, password: []const u8, _: VerifyOptions, ) Error!void { if (mem.startsWith(u8, str, crypt_format.prefix)) { return CryptFormatHasher.verify(str, password); } else { return PhcFormatHasher.verify(str, password); } } test "bcrypt codec" { var salt: [salt_length]u8 = undefined; crypto.random.bytes(&salt); var salt_str: [salt_str_length]u8 = undefined; crypt_format.Codec.encode(salt_str[0..], salt[0..]); var salt2: [salt_length]u8 = undefined; try crypt_format.Codec.decode(salt2[0..], salt_str[0..]); try testing.expectEqualSlices(u8, salt[0..], salt2[0..]); } test "bcrypt crypt format" { const hash_options = HashOptions{ .params = .{ .rounds_log = 5 }, .encoding = .crypt, }; const verify_options = VerifyOptions{}; var buf: [hash_length]u8 = undefined; const s = try strHash("password", hash_options, &buf); try testing.expect(mem.startsWith(u8, s, crypt_format.prefix)); try strVerify(s, "password", verify_options); try testing.expectError( error.PasswordVerificationFailed, strVerify(s, "invalid password", verify_options), ); var long_buf: [hash_length]u8 = undefined; const long_s = try strHash("password" ** 100, hash_options, &long_buf); try testing.expect(mem.startsWith(u8, long_s, crypt_format.prefix)); try strVerify(long_s, "password" ** 100, verify_options); try strVerify(long_s, "password" ** 101, verify_options); try strVerify( "$2b$08$WUQKyBCaKpziCwUXHiMVvu40dYVjkTxtWJlftl0PpjY2BxWSvFIEe", "The devil himself", verify_options, ); } test "bcrypt phc format" { if (@import("builtin").zig_backend != .stage1) return error.SkipZigTest; // TODO const hash_options = HashOptions{ .params = .{ .rounds_log = 5 }, .encoding = .phc, }; const verify_options = VerifyOptions{}; const prefix = "$bcrypt$"; var buf: [hash_length * 2]u8 = undefined; const s = try strHash("password", hash_options, &buf); try testing.expect(mem.startsWith(u8, s, prefix)); try strVerify(s, "password", verify_options); try testing.expectError( error.PasswordVerificationFailed, strVerify(s, "invalid password", verify_options), ); var long_buf: [hash_length * 2]u8 = undefined; const long_s = try strHash("password" ** 100, hash_options, &long_buf); try testing.expect(mem.startsWith(u8, long_s, prefix)); try strVerify(long_s, "password" ** 100, verify_options); try strVerify(long_s, "password" ** 101, verify_options); try strVerify( "$bcrypt$r=5$2NopntlgE2lX3cTwr4qz8A$r3T7iKYQNnY4hAhGjk9RmuyvgrYJZwc", "The devil himself", verify_options, ); }
lib/std/crypto/bcrypt.zig
const std = @import("index.zig"); const debug = std.debug; const assert = debug.assert; const mem = std.mem; const Allocator = mem.Allocator; pub fn ArrayList(comptime T: type) type { return AlignedArrayList(T, @alignOf(T)); } pub fn AlignedArrayList(comptime T: type, comptime A: u29) type{ return struct { const Self = this; /// Use toSlice instead of slicing this directly, because if you don't /// specify the end position of the slice, this will potentially give /// you uninitialized memory. items: []align(A) T, len: usize, allocator: &Allocator, /// Deinitialize with `deinit` or use `toOwnedSlice`. pub fn init(allocator: &Allocator) Self { return Self { .items = []align(A) T{}, .len = 0, .allocator = allocator, }; } pub fn deinit(l: &Self) void { l.allocator.free(l.items); } pub fn toSlice(l: &Self) []align(A) T { return l.items[0..l.len]; } pub fn toSliceConst(l: &const Self) []align(A) const T { return l.items[0..l.len]; } pub fn at(l: &const Self, n: usize) T { return l.toSliceConst()[n]; } /// ArrayList takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Deinitialize with `deinit` or use `toOwnedSlice`. pub fn fromOwnedSlice(allocator: &Allocator, slice: []align(A) T) Self { return Self { .items = slice, .len = slice.len, .allocator = allocator, }; } /// The caller owns the returned memory. ArrayList becomes empty. pub fn toOwnedSlice(self: &Self) []align(A) T { const allocator = self.allocator; const result = allocator.alignedShrink(T, A, self.items, self.len); *self = init(allocator); return result; } pub fn insert(l: &Self, n: usize, item: &const T) !void { try l.ensureCapacity(l.len + 1); l.len += 1; mem.copy(T, l.items[n+1..l.len], l.items[n..l.len-1]); l.items[n] = *item; } pub fn insertSlice(l: &Self, n: usize, items: []align(A) const T) !void { try l.ensureCapacity(l.len + items.len); l.len += items.len; mem.copy(T, l.items[n+items.len..l.len], l.items[n..l.len-items.len]); mem.copy(T, l.items[n..n+items.len], items); } pub fn append(l: &Self, item: &const T) !void { const new_item_ptr = try l.addOne(); *new_item_ptr = *item; } pub fn appendSlice(l: &Self, items: []align(A) const T) !void { try l.ensureCapacity(l.len + items.len); mem.copy(T, l.items[l.len..], items); l.len += items.len; } pub fn resize(l: &Self, new_len: usize) !void { try l.ensureCapacity(new_len); l.len = new_len; } pub fn shrink(l: &Self, new_len: usize) void { assert(new_len <= l.len); l.len = new_len; } pub fn ensureCapacity(l: &Self, new_capacity: usize) !void { var better_capacity = l.items.len; if (better_capacity >= new_capacity) return; while (true) { better_capacity += better_capacity / 2 + 8; if (better_capacity >= new_capacity) break; } l.items = try l.allocator.alignedRealloc(T, A, l.items, better_capacity); } pub fn addOne(l: &Self) !&T { const new_length = l.len + 1; try l.ensureCapacity(new_length); const result = &l.items[l.len]; l.len = new_length; return result; } pub fn pop(self: &Self) T { self.len -= 1; return self.items[self.len]; } pub fn popOrNull(self: &Self) ?T { if (self.len == 0) return null; return self.pop(); } }; } test "basic ArrayList test" { var list = ArrayList(i32).init(debug.global_allocator); defer list.deinit(); {var i: usize = 0; while (i < 10) : (i += 1) { list.append(i32(i + 1)) catch unreachable; }} {var i: usize = 0; while (i < 10) : (i += 1) { assert(list.items[i] == i32(i + 1)); }} assert(list.pop() == 10); assert(list.len == 9); list.appendSlice([]const i32 { 1, 2, 3 }) catch unreachable; assert(list.len == 12); assert(list.pop() == 3); assert(list.pop() == 2); assert(list.pop() == 1); assert(list.len == 9); list.appendSlice([]const i32 {}) catch unreachable; assert(list.len == 9); } test "insert ArrayList test" { var list = ArrayList(i32).init(debug.global_allocator); defer list.deinit(); try list.append(1); try list.insert(0, 5); assert(list.items[0] == 5); assert(list.items[1] == 1); try list.insertSlice(1, []const i32 { 9, 8 }); assert(list.items[0] == 5); assert(list.items[1] == 9); assert(list.items[2] == 8); const items = []const i32 { 1 }; try list.insertSlice(0, items[0..0]); assert(list.items[0] == 5); }
std/array_list.zig
const std = @import("std"); const ELF = @import("../elf.zig"); const phdr = @import("../data-structures/phdr.zig"); const ehdr = @import("../data-structures/ehdr.zig"); const PhdrErrors = error{ E_Phoff_Phentsize_or_Phnum_is_zero, }; fn phdrParse32( elf: ELF.ELF, alloc: std.mem.Allocator, ) !std.ArrayList(phdr.Phdr) { var list = std.ArrayList(phdr.Phdr).init(alloc); var phdr1: phdr.Elf32_Phdr = undefined; const stream = elf.file.reader(); var i: u64 = 0; while (i < elf.ehdr.phnum) : (i = i + 1) { const offset = elf.ehdr.phoff + @sizeOf(@TypeOf(phdr1)) * i; try elf.file.seekableStream().seekTo(offset); try stream.readNoEof(std.mem.asBytes(&phdr1)); var phdr2: phdr.Phdr = undefined; phdr2.ptype = @intToEnum(phdr.p_type, phdr1.p_type); phdr2.flags = @bitCast(phdr.p_flags, phdr1.p_flags); phdr2.offset = phdr1.p_offset; phdr2.vaddr = phdr1.p_vaddr; phdr2.paddr = phdr1.p_paddr; phdr2.filesz = phdr1.p_filesz; phdr2.memsz = phdr1.p_memsz; phdr2.palign = phdr1.p_align; try list.append(phdr2); } return list; } fn phdrParse64( elf: ELF.ELF, alloc: std.mem.Allocator, ) !std.ArrayList(phdr.Phdr) { var list = std.ArrayList(phdr.Phdr).init(alloc); var phdr1: phdr.Elf64_Phdr = undefined; const stream = elf.file.reader(); var i: u64 = 0; while (i < elf.ehdr.phnum) : (i = i + 1) { const offset = elf.ehdr.phoff + @sizeOf(@TypeOf(phdr1)) * i; try elf.file.seekableStream().seekTo(offset); try stream.readNoEof(std.mem.asBytes(&phdr1)); var phdr2: phdr.Phdr = undefined; phdr2.ptype = @intToEnum(phdr.p_type, phdr1.p_type); phdr2.flags = @bitCast(phdr.p_flags, phdr1.p_flags); phdr2.offset = phdr1.p_offset; phdr2.vaddr = phdr1.p_vaddr; phdr2.paddr = phdr1.p_paddr; phdr2.filesz = phdr1.p_filesz; phdr2.memsz = phdr1.p_memsz; phdr2.palign = phdr1.p_align; try list.append(phdr2); } return list; } pub fn phdrParse( elf: ELF.ELF, alloc: std.mem.Allocator, ) !std.ArrayList(phdr.Phdr) { if (elf.is32 == false) { return phdrParse64(elf, alloc); } else { return phdrParse32(elf, alloc); } } fn phdrsToPacked32( phdrs: std.ArrayList(phdr.Phdr), alloc: std.mem.Allocator, ) ![]phdr.Elf32_Phdr { var arraylist = std.ArrayList(phdr.Elf32_Phdr).init(alloc); defer arraylist.deinit(); for (phdrs.items) |p| { var x: phdr.Elf32_Phdr = undefined; x.p_align = @truncate(std.elf.Elf32_Word, p.palign); x.p_filesz = @truncate(std.elf.Elf32_Word, p.filesz); x.p_flags = @bitCast(std.elf.Elf32_Word, p.flags); x.p_memsz = @truncate(std.elf.Elf32_Word, p.memsz); x.p_offset = @truncate(std.elf.Elf32_Off, p.offset); x.p_paddr = @truncate(std.elf.Elf32_Addr, p.paddr); x.p_type = @enumToInt(p.ptype); x.p_vaddr = @truncate(std.elf.Elf32_Word, p.vaddr); try arraylist.append(x); } return alloc.dupe(phdr.Elf32_Phdr, arraylist.items); } fn phdrsToPacked64( phdrs: std.ArrayList(phdr.Phdr), alloc: std.mem.Allocator, ) ![]phdr.Elf64_Phdr { var arraylist = std.ArrayList(phdr.Elf64_Phdr).init(alloc); defer arraylist.deinit(); for (phdrs.items) |p| { var x: phdr.Elf64_Phdr = undefined; x.p_align = @truncate(std.elf.Elf64_Xword, p.palign); x.p_filesz = @truncate(std.elf.Elf64_Xword, p.filesz); x.p_flags = @bitCast(std.elf.Elf64_Word, p.flags); x.p_memsz = @truncate(std.elf.Elf64_Word, p.memsz); x.p_offset = @truncate(std.elf.Elf64_Off, p.offset); x.p_paddr = @truncate(std.elf.Elf64_Addr, p.paddr); x.p_type = @enumToInt(p.ptype); x.p_vaddr = @truncate(std.elf.Elf64_Addr, p.vaddr); try arraylist.append(x); } return alloc.dupe(phdr.Elf64_Phdr, arraylist.items); } pub fn writePhdrList( a: ELF.ELF, alloc: std.mem.Allocator, ) !void { if (a.ehdr.phoff == 0 or a.ehdr.phnum == 0 or a.ehdr.phentsize == 0) { return PhdrErrors.E_Phoff_Phentsize_or_Phnum_is_zero; } if (a.is32) { var phdr2 = try phdrsToPacked32(a.phdrs, alloc); try a.file.pwriteAll(std.mem.sliceAsBytes(phdr2), a.ehdr.phoff); } else { var phdr2 = try phdrsToPacked64(a.phdrs, alloc); try a.file.pwriteAll(std.mem.sliceAsBytes(phdr2), a.ehdr.phoff); } }
src/functions/phdr.zig
const std = @import("std"); const testing = std.testing; const expect = testing.expect; const expectEqual = testing.expectEqual; const expectApproxEqRel = testing.expectApproxEqRel; pub const Vector2 = packed struct { x: f32, y: f32, pub fn init(x: f32, y: f32) Vector2 { return .{ .x = x, .y = y }; } pub fn set(value: f32) Vector2 { return .{ .x = value, .y = value }; } pub fn normalize(v: Vector2) Vector2 { return multiplyScalar(v, 1.0 / length(v)); } pub fn length(v: Vector2) f32 { return std.math.sqrt(dot(v, v)); } pub fn squaredLength(v: Vector2) f32 { return dot(v, v); } pub fn dot(a: Vector2, b: Vector2) f32 { return a.x * b.x + a.y * b.y; } pub fn add(a: Vector2, b: Vector2) Vector2 { return init(a.x + b.x, a.y + b.y); } pub fn subtract(a: Vector2, b: Vector2) Vector2 { return init(a.x - b.x, a.y - b.y); } pub fn multiply(a: Vector2, b: Vector2) Vector2 { return init(a.x * b.x, a.y * b.y); } pub fn divide(a: Vector2, b: Vector2) Vector2 { return init(a.x / b.x, a.y / b.y); } pub fn addScalar(a: Vector2, b: f32) Vector2 { return init(a.x + b, a.y + b); } pub fn subtractScalar(a: Vector2, b: f32) Vector2 { return init(a.x - b, a.y - b); } pub fn multiplyScalar(a: Vector2, b: f32) Vector2 { return init(a.x * b, a.y * b); } pub fn divideScalar(a: Vector2, b: f32) Vector2 { return init(a.x / b, a.y / b); } }; test "Vector2" { var v1 = Vector2.init(1, 2); var v2 = Vector2.init(5, 6); var v: Vector2 = undefined; var s: f32 = undefined; v = Vector2.init(1, 2); try expectEqual(@as(f32, 1.0), v.x); try expectEqual(@as(f32, 2.0), v.y); v = Vector2.set(4); try expectEqual(@as(f32, 4.0), v.x); try expectEqual(@as(f32, 4.0), v.y); v = v1.add(v2); try expectEqual(Vector2.init(6, 8), v); v = v1.addScalar(14); try expectEqual(Vector2.init(15, 16), v); v = v1.subtract(v2); try expectEqual(Vector2.init(-4, -4), v); v = v1.subtractScalar(-4); try expectEqual(Vector2.init(5, 6), v); v = v1.multiply(v2); try expectEqual(Vector2.init(5, 12), v); v = v1.multiplyScalar(-4); try expectEqual(Vector2.init(-4, -8), v); v = v1.divide(v2); try expectApproxEqRel(@as(f32, 1.0/5.0), v.x, 0.0001); try expectApproxEqRel(@as(f32, 2.0/6.0), v.y, 0.0001); v = v1.divideScalar(2); try expectApproxEqRel(@as(f32, 1.0/2.0), v.x, 0.0001); try expectApproxEqRel(@as(f32, 2.0/2.0), v.y, 0.0001); s = Vector2.dot(v1, v2); try expectApproxEqRel(@as(f32, 17.0), s, 0.0001); s = Vector2.squaredLength(v1); try expectApproxEqRel(@as(f32, 5.0), s, 0.0001); s = Vector2.length(v1); try expectApproxEqRel(@as(f32, 2.236), s, 0.0001); v = Vector2.normalize(v1); try expectApproxEqRel(@as(f32, 1.0/2.236), v.x, 0.0001); try expectApproxEqRel(@as(f32, 2.0/2.236), v.y, 0.0001); }
src/vector2.zig
const std = @import("std"); const assert = std.debug.assert; usingnamespace @import("types.zig"); const OperandType = @import("operand.zig").OperandType; // When we want to refer to a register but don't care about it's bit size pub const RegisterName = enum(u8) { AX = 0x00, CX, DX, BX, SP, BP, SI, DI, R8, R9, R10, R11, R12, R13, R14, R15 = 0x0F, }; pub const RegisterType = enum(u16) { General = 0x0000, Segment = OperandType.Class.reg_seg.asTag(), Float = OperandType.Class.reg_st.asTag(), Control = OperandType.Class.reg_cr.asTag(), Debug = OperandType.Class.reg_dr.asTag(), Mask = OperandType.Class.reg_k.asTag(), Bound = OperandType.Class.reg_bnd.asTag(), MMX = OperandType.Class.mm.asTag(), XMM = OperandType.Class.xmm.asTag(), YMM = OperandType.Class.ymm.asTag(), ZMM = OperandType.Class.zmm.asTag(), }; /// Special control and debug registers pub const Register = enum(u16) { const tag_mask = 0xFF00; const tag_general = @enumToInt(RegisterType.General); const tag_segment = @enumToInt(RegisterType.Segment); const tag_float = @enumToInt(RegisterType.Float); const tag_control = @enumToInt(RegisterType.Control); const tag_debug = @enumToInt(RegisterType.Debug); const tag_mmx = @enumToInt(RegisterType.MMX); const tag_xmm = @enumToInt(RegisterType.XMM); const tag_ymm = @enumToInt(RegisterType.YMM); const tag_zmm = @enumToInt(RegisterType.ZMM); const tag_mask_reg = @enumToInt(RegisterType.Mask); const tag_bound_reg = @enumToInt(RegisterType.Bound); // We use special format for these registers: // u8: .RSSNNNN // // N: register number // S: size (1 << 0bSS) bytes // R: needs REX prefix // .: unused const rex_flag: u8 = 0x40; const gpr_size_mask: u8 = 0x30; AL = 0x00 | tag_general, CL, DL, BL, AH, // becomes SPL when using REX prefix CH, // becomes BPL when using REX prefix DH, // becomes SIL when using REX prefix BH, // becomes DIL when using REX prefix R8B, R9B, R10B, R11B, R12B, R13B, R14B, R15B = 0x0F | tag_general, // 16 bit registers AX = 0x10 | tag_general, CX, DX, BX, SP, BP, SI, DI, R8W, R9W, R10W, R11W, R12W, R13W, R14W, R15W = 0x1F | tag_general, // 32 bit registers EAX = 0x20 | tag_general, ECX, EDX, EBX, ESP, EBP, ESI, EDI, R8D, R9D, R10D, R11D, R12D, R13D, R14D, R15D = 0x2F | tag_general, // We use a flag 0x80 to mark registers that require REX prefix // 64 bit register RAX = 0x30 | tag_general, RCX, RDX, RBX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15 = 0x3F | tag_general, // special 8 bit registers added in x86-64: SPL = 0x04 | rex_flag | tag_general, // would be AH without REX flag BPL = 0x05 | rex_flag | tag_general, // would be CH without REX flag SIL = 0x06 | rex_flag | tag_general, // would be DH without REX flag DIL = 0x07 | rex_flag | tag_general, // would be BH without REX flag // Segment registers ES = 0x00 | tag_segment, CS, SS, DS, FS, GS = 0x05 | tag_segment, /// Segment registers with extension bit set in REX /// These registers are identical to the other segment registers, but we /// include them for completness. ES_ = 0x08 | tag_segment, CS_, SS_, DS_, FS_, GS_ = 0x0d | tag_segment, ST0 = 0x00 | tag_float, ST1, ST2, ST3, ST4, ST5, ST6, ST7 = 0x07 | tag_float, // ST0_ = 0x18 | tag_float, // ST1_, // ST2_, // ST3_, // ST4_, // ST5_, // ST6_, // ST7_ = 0x1F | tag_float, MM0 = 0x00 | tag_mmx, MM1, MM2, MM3, MM4, MM5, MM6, MM7, MM0_, MM1_, MM2_, MM3_, MM4_, MM5_, MM6_, MM7_ = 0x0F | tag_mmx, // Most of these are not valid to use, but keep them for completeness CR0 = 0x00 | tag_control, CR1, CR2, CR3, CR4, CR5, CR6, CR7, CR8, CR9, CR10, CR11, CR12, CR13, CR14, CR15 = 0x0F | tag_control, // Most of these are not valid to use, but keep them for completeness DR0 = 0x00 | tag_debug, DR1, DR2, DR3, DR4, DR5, DR6, DR7, DR8, DR9, DR10, DR11, DR12, DR13, DR14, DR15 = 0x0F | tag_debug, XMM0 = 0x00 | tag_xmm, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7, XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, XMM16, XMM17, XMM18, XMM19, XMM20, XMM21, XMM22, XMM23, XMM24, XMM25, XMM26, XMM27, XMM28, XMM29, XMM30, XMM31 = 0x1F | tag_xmm, YMM0 = 0x00 | tag_ymm, YMM1, YMM2, YMM3, YMM4, YMM5, YMM6, YMM7, YMM8, YMM9, YMM10, YMM11, YMM12, YMM13, YMM14, YMM15, YMM16, YMM17, YMM18, YMM19, YMM20, YMM21, YMM22, YMM23, YMM24, YMM25, YMM26, YMM27, YMM28, YMM29, YMM30, YMM31 = 0x1F | tag_ymm, ZMM0 = 0x00 | tag_zmm, ZMM1, ZMM2, ZMM3, ZMM4, ZMM5, ZMM6, ZMM7, ZMM8, ZMM9, ZMM10, ZMM11, ZMM12, ZMM13, ZMM14, ZMM15, ZMM16, ZMM17, ZMM18, ZMM19, ZMM20, ZMM21, ZMM22, ZMM23, ZMM24, ZMM25, ZMM26, ZMM27, ZMM28, ZMM29, ZMM30, ZMM31 = 0x1F | tag_zmm, K0 = 0x00 | tag_mask_reg, K1, K2, K3, K4, K5, K6, K7 = 0x07 | tag_mask_reg, BND0 = 0x00 | tag_bound_reg, BND1, BND2, BND3 = 0x03 | tag_bound_reg, pub fn create(reg_size: BitSize, reg_num: u8) Register { std.debug.assert(reg_num <= 0x0F); switch (reg_size) { // TODO: does this need to handle AH vs SIL edge case? .Bit8 => return @intToEnum(Register, (0 << 4) | reg_num), .Bit16 => return @intToEnum(Register, (1 << 4) | reg_num), .Bit32 => return @intToEnum(Register, (2 << 4) | reg_num), .Bit64 => return @intToEnum(Register, (3 << 4) | reg_num), else => unreachable, } } /// If the register needs rex to be used, ie: BPL, SPL, SIL, DIL, pub fn needsRex(self: Register) bool { return self.registerType() == .General and (@enumToInt(self) & rex_flag) == rex_flag; } pub fn needsNoRex(self: Register) bool { return switch (self) { .AH, .CH, .DH, .BH => true, else => false, }; } pub fn name(self: Register) RegisterName { assert(self.registerType() == .General); return switch (self) { .AH, .CH, .DH, .BH => @intToEnum(RegisterName, self.number() & 0x03), else => @intToEnum(RegisterName, self.number()), }; } pub fn number(self: Register) u8 { if (self.registerType() == .General) { return @intCast(u8, @enumToInt(self) & 0x0F); } else { return @intCast(u8, @enumToInt(self) & 0xFF); } } pub fn numberRm(self: Register) u3 { return @intCast(u3, @enumToInt(self) & 0x07); } pub fn numberRex(self: Register) u1 { return @intCast(u1, (@enumToInt(self) >> 3) & 0x01); } pub fn numberEvex(self: Register) u1 { return @intCast(u1, (@enumToInt(self) >> 4) & 0x01); } pub fn registerType(self: Register) RegisterType { return @intToEnum(RegisterType, tag_mask & @enumToInt(self)); } pub fn isVector(self: Register) bool { return switch (self.registerType()) { .XMM, .YMM, .ZMM => true, else => false, }; } pub fn dataSize(self: Register) DataSize { switch (self.registerType()) { .General => { const masked = @intCast(u8, @enumToInt(self) & gpr_size_mask); const byte_size = @as(u8, 1) << @intCast(u3, (masked >> 4)); return DataSize.fromByteValue(byte_size); }, .Segment => return DataSize.WORD, // TODO: These registers do have a size, but this is a hack to // make modrm encoding work .Control, .Debug, .MMX, .XMM, .YMM, .ZMM, .Bound, .Mask, .Float, => return DataSize.Void, // .MMX => return DataSize.QWORD, // .XMM => return DataSize.OWORD, // .XMM => return DataSize.XMM_WORD, // .YMM => return DataSize.YMM_WORD, // .ZMM => return DataSize.ZMM_WORD, } } pub fn bitSize(self: Register) BitSize { return self.dataSize().bitSize(); } };
src/x86/register.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const testing = std.testing; const TypeId = builtin.TypeId; const TypeInfo = builtin.TypeInfo; pub fn lessThan(comptime T: type, a: T, b: T) bool { const info = @typeInfo(T); switch (info) { .Int, .Float, .ComptimeFloat, .ComptimeInt => return a < b, .Bool => return @boolToInt(a) < @boolToInt(b), .Optional => |optional| { const a_value = a orelse { return if (b) |_| true else false; }; const b_value = b orelse return false; return lessThan(optional.child, a_value, b_value); }, .ErrorUnion => |err_union| { const a_value = a catch |a_err| { if (b) |_| { return true; } else |b_err| { return lessThan(err_union.error_set, a_err, b_err); } }; const b_value = b catch return false; return lessThan(err_union.payload, a_value, b_value); }, // TODO: mem.lessThan is wrong .Array => |arr| return mem.lessThan(arr.child, &a, &b), .Enum => |e| return @enumToInt(a) < @enumToInt(b), .ErrorSet => return @errorToInt(a) < @errorToInt(b), .Null, .Void => return false, .Vector, .Undefined, .Type, .NoReturn, .Fn, .BoundFn, .Opaque, .AnyFrame, .Frame, .Struct, .Union, .Pointer, .EnumLiteral, => { @compileError("Cannot get a default less than for " ++ @typeName(T)); return false; }, } } test "generic.compare.lessThan(u64)" { testing.expect(lessThan(u64, 1, 2)); testing.expect(!lessThan(u64, 1, 1)); testing.expect(!lessThan(u64, 1, 0)); } test "generic.compare.lessThan(i64)" { testing.expect(lessThan(i64, 0, 1)); testing.expect(!lessThan(i64, 0, 0)); testing.expect(!lessThan(i64, 0, -1)); } test "generic.compare.lessThan(comptime_int)" { testing.expect(lessThan(comptime_int, 0, 1)); testing.expect(!lessThan(comptime_int, 0, 0)); testing.expect(!lessThan(comptime_int, 0, -1)); } test "generic.compare.lessThan(f64)" { testing.expect(lessThan(f64, 0, 1)); testing.expect(!lessThan(f64, 0, 0)); testing.expect(!lessThan(f64, 0, -1)); } test "generic.compare.lessThan(comptime_float)" { testing.expect(lessThan(comptime_float, 0.0, 1.0)); testing.expect(!lessThan(comptime_float, 0.0, 0.0)); testing.expect(!lessThan(comptime_float, 0.0, -1.0)); } test "generic.compare.lessThan(bool)" { testing.expect(lessThan(bool, false, true)); testing.expect(!lessThan(bool, true, true)); testing.expect(!lessThan(bool, true, false)); } test "generic.compare.lessThan(?i64)" { const nul: ?i64 = null; testing.expect(lessThan(?i64, 0, 1)); testing.expect(!lessThan(?i64, 0, 0)); testing.expect(!lessThan(?i64, 0, -1)); testing.expect(lessThan(?i64, nul, 0)); testing.expect(!lessThan(?i64, nul, nul)); testing.expect(!lessThan(?i64, 0, nul)); } //TODO implement @typeInfo for global error set //test "generic.compare.lessThan(error!i64)" { // const err : error!i64 = error.No; // testing.expect( lessThan(error!i64, 0, 1)); // testing.expect(!lessThan(error!i64, 0, 0)); // testing.expect(!lessThan(error!i64, 0, -1)); // testing.expect( lessThan(error!i64, err, 0 )); // testing.expect(!lessThan(error!i64, err, err)); // testing.expect(!lessThan(error!i64, 0 , err)); //} test "generic.compare.lessThan([1]u8)" { testing.expect(lessThan([1]u8, "1".*, "2".*)); testing.expect(!lessThan([1]u8, "1".*, "1".*)); testing.expect(!lessThan([1]u8, "1".*, "0".*)); } test "generic.compare.lessThan(enum)" { const E = enum { A = 0, B = 1, }; testing.expect(lessThan(E, E.A, E.B)); testing.expect(!lessThan(E, E.B, E.B)); testing.expect(!lessThan(E, E.B, E.A)); } //TODO implement @typeInfo for global error set //test "generic.compare.lessThan(error)" { // testing.expect( lessThan(error, error.A, error.B)); // testing.expect(!lessThan(error, error.B, error.B)); // testing.expect(!lessThan(error, error.B, error.A)); //} //test "generic.compare.lessThan(null)" { // comptime testing.expect(!lessThan(@typeOf(null), null, null)); //} test "generic.compare.lessThan(void)" { testing.expect(!lessThan(void, void{}, void{})); } pub fn equal(comptime T: type, a: T, b: T) bool { const info = @typeInfo(T); switch (info) { .Int, .Float, .ComptimeInt, .ComptimeFloat, .Enum, .ErrorSet, .Type, .Void, .Fn, .Null, .Bool, .EnumLiteral, .AnyFrame, => return a == b, // We don't follow pointers, as this would `lessThan` recursive on recursive types (like LinkedList .Pointer => |ptr| switch (ptr.size) { .Slice => { return a.ptr == b.ptr and a.len == b.len; }, else => return a == b, }, .Array => { if (a.len != b.len) return false; for (a) |_, i| { if (!equal(T.Child, a[i], b[i])) return false; } return true; }, .Optional => |optional| { const a_value = a orelse { return if (b) |_| false else true; }; const b_value = b orelse return false; return equal(optional.child, a_value, b_value); }, .ErrorUnion => |err_union| { const a_value = a catch |a_err| { if (b) |_| { return false; } else |b_err| { return equal(err_union.error_set, a_err, b_err); } }; const b_value = b catch return false; return equal(err_union.payload, a_value, b_value); }, .Struct => |struct_info| { inline for (struct_info.fields) |field| { if (!fieldsEql(T, field.name, a, b)) return false; } return true; }, .Vector, .Undefined, .NoReturn, .BoundFn, .Opaque, .Frame, .Union, => { @compileError("Cannot get a default equal for " ++ @typeName(T)); return false; }, } } fn fieldsEql(comptime T: type, comptime field: []const u8, a: T, b: T) bool { const af = @field(a, field); const bf = @field(b, field); return equal(@TypeOf(af), af, bf); } test "generic.compare.equal(i32)" { testing.expect(equal(i32, 1, 1)); testing.expect(!equal(i32, 0, 1)); } test "generic.compare.equal(comptime_int)" { testing.expect(equal(comptime_int, 1, 1)); testing.expect(!equal(comptime_int, 0, 1)); } test "generic.compare.equal(f32)" { testing.expect(equal(f32, 1, 1)); testing.expect(!equal(f32, 0, 1)); } test "generic.compare.equal(comptime_float)" { testing.expect(equal(comptime_float, 1.1, 1.1)); testing.expect(!equal(comptime_float, 0.0, 1.1)); } test "generic.compare.equal(bool)" { testing.expect(equal(bool, true, true)); testing.expect(!equal(bool, true, false)); } test "generic.compare.equal(type)" { comptime { testing.expect(equal(type, u8, u8)); testing.expect(!equal(type, u16, u8)); } } test "generic.compare.equal(enum)" { const E = enum { A, B, }; testing.expect(equal(E, E.A, E.A)); testing.expect(!equal(E, E.A, E.B)); } //TODO implement @typeInfo for global error set //test "generic.compare.equal(error)" { // testing.expect( equal(error, error.A, error.A)); // testing.expect(!equal(error, error.A, error.B)); //} test "generic.compare.equal(&i64)" { var a: i64 = undefined; var b: i64 = undefined; testing.expect(equal(*i64, &a, &a)); testing.expect(!equal(*i64, &a, &b)); } test "generic.compare.equal(?i64)" { var nul: ?i64 = null; testing.expect(equal(?i64, 1, 1)); testing.expect(equal(?i64, nul, nul)); testing.expect(!equal(?i64, 1, 0)); testing.expect(!equal(?i64, 1, nul)); } //TODO implement @typeInfo for global error set //test "generic.compare.equal(%i32)" { // const a : error!i32 = 1; // const b : error!i32 = error.TestError1; // const errorEqual = equal(error!i32); // testing.expect( errorEqual(a, (error!i32)(1))); // testing.expect(!errorEqual(a, (error!i32)(0))); // testing.expect(!errorEqual(a, (error!i32)(error.TestError1))); // testing.expect( errorEqual(b, (error!i32)(error.TestError1))); // testing.expect(!errorEqual(b, (error!i32)(error.TestError2))); // testing.expect(!errorEqual(b, (error!i32)(0))); //} test "generic.compare.equal([1]u8)" { testing.expect(equal([1]u8, "1".*, "1".*)); testing.expect(!equal([1]u8, "1".*, "0".*)); } test "generic.compare.equal(null)" { comptime testing.expect(equal(@TypeOf(null), null, null)); } test "generic.compare.equal(void)" { testing.expect(equal(void, void{}, void{})); } test "generic.compare.equal(struct)" { const Struct = packed struct { a: u3, b: u3, }; testing.expect(equal(Struct, Struct{ .a = 1, .b = 1 }, Struct{ .a = 1, .b = 1 })); testing.expect(!equal(Struct, Struct{ .a = 0, .b = 0 }, Struct{ .a = 1, .b = 1 })); } test "generic.compare.equal([]const u8)" { const a = "1"; const b = "0"; testing.expect(equal([]const u8, a, a)); testing.expect(!equal([]const u8, a, b)); } //unreachable //[1] 6911 abort (core dumped) zig test src/index.zig //test "equal(fn()void)" { // const T = struct { // fn a() void {} // fn b() void {} // }; // // testing.expect( equal(fn()void, T.a, T.a)); // testing.expect(!equal(fn()void, T.a, T.b)); //}
src/generic/compare.zig
const std = @import("std"); const foilz = @import("src/archiver.zig"); const log = std.log; const Builder = std.build.Builder; const CrossTarget = std.zig.CrossTarget; const Mode = std.builtin.Mode; const LibExeObjStep = std.build.LibExeObjStep; var builder: *Builder = undefined; var target: *CrossTarget = undefined; var mode: *Mode = undefined; var wrapper_exe: *LibExeObjStep = undefined; pub fn build(b: *Builder) !void { log.info("Zig is building an Elixir binary... ⚡", .{}); builder = b; target = &builder.standardTargetOptions(.{}); mode = &builder.standardReleaseOptions(); // Run build steps! _ = try run_archiver(); _ = try build_wrapper(); log.info("DONE 🚀", .{}); } pub fn run_archiver() !void { log.info("Generating and compressing release payload... 📦", .{}); const release_path = std.os.getenv("__BURRITO_RELEASE_PATH"); try foilz.pack_directory(release_path.?, "./payload.foilz"); const compress_cmd = builder.addSystemCommand(&[_][]const u8{ "/bin/bash", "-c", "gzip -9nf payload.foilz" }); try compress_cmd.step.make(); } pub fn build_wrapper() !void { log.info("Building wrapper and embedding payload... 🌯", .{}); const release_name = std.os.getenv("__BURRITO_RELEASE_NAME"); const plugin_path = std.os.getenv("__BURRITO_PLUGIN_PATH"); const is_prod = std.os.getenv("__BURRITO_IS_PROD"); wrapper_exe = builder.addExecutable(release_name.?, "src/wrapper.zig"); const exe_options = builder.addOptions(); wrapper_exe.addOptions("build_options", exe_options); exe_options.addOption([]const u8, "RELEASE_NAME", release_name.?); if (std.mem.eql(u8, is_prod.?, "1")) { exe_options.addOption(bool, "IS_PROD", true); } else { exe_options.addOption(bool, "IS_PROD", false); } wrapper_exe.setTarget(target.*); wrapper_exe.setBuildMode(mode.*); if (target.isWindows()) { wrapper_exe.linkSystemLibrary("c"); wrapper_exe.addIncludeDir("src/"); } if (plugin_path) |plugin| { log.info("Plugin found! {s} 🔌", .{plugin}); wrapper_exe.addPackagePath("burrito_plugin", plugin); } else { wrapper_exe.addPackagePath("burrito_plugin", "./_dummy_plugin.zig"); } wrapper_exe.install(); const run_cmd = wrapper_exe.run(); run_cmd.step.dependOn(builder.getInstallStep()); const run_step = builder.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
build.zig
const std = @import("std"); const net = std.net; usingnamespace @import("primitive_types.zig"); // TODO(vincent): test all error codes pub const ErrorCode = packed enum(u32) { ServerError = 0x0000, ProtocolError = 0x000A, AuthError = 0x0100, UnavailableReplicas = 0x1000, CoordinatorOverloaded = 0x1001, CoordinatorIsBootstrapping = 0x1002, TruncateError = 0x1003, WriteTimeout = 0x1100, ReadTimeout = 0x1200, ReadFailure = 0x1300, FunctionFailure = 0x1400, WriteFailure = 0x1500, CDCWriteFailure = 0x1600, CASWriteUnknown = 0x1700, SyntaxError = 0x2000, Unauthorized = 0x2100, InvalidQuery = 0x2200, ConfigError = 0x2300, AlreadyExists = 0x2400, Unprepared = 0x2500, }; pub const UnavailableReplicasError = struct { consistency_level: Consistency, required: u32, alive: u32, }; pub const FunctionFailureError = struct { keyspace: []const u8, function: []const u8, arg_types: []const []const u8, }; pub const WriteError = struct { // TODO(vincent): document this pub const WriteType = enum { SIMPLE, BATCH, UNLOGGED_BATCH, COUNTER, BATCH_LOG, CAS, VIEW, CDC, }; pub const Timeout = struct { consistency_level: Consistency, received: u32, block_for: u32, write_type: WriteType, contentions: ?u16, }; pub const Failure = struct { pub const Reason = struct { endpoint: net.Address, // TODO(vincent): what's this failure code ?! failure_code: u16, }; consistency_level: Consistency, received: u32, block_for: u32, reason_map: []Reason, write_type: WriteType, }; pub const CASUnknown = struct { consistency_level: Consistency, received: u32, block_for: u32, }; }; pub const ReadError = struct { pub const Timeout = struct { consistency_level: Consistency, received: u32, block_for: u32, data_present: u8, }; pub const Failure = struct { pub const Reason = struct { endpoint: net.Address, // TODO(vincent): what's this failure code ?! failure_code: u16, }; consistency_level: Consistency, received: u32, block_for: u32, reason_map: []Reason, data_present: u8, }; }; pub const AlreadyExistsError = struct { keyspace: []const u8, table: []const u8, }; pub const UnpreparedError = struct { statement_id: []const u8, };
src/error.zig
pub const TIMER0 = struct { const base = 0xe0002800; pub const LOAD3 = @intToPtr(*volatile u8, base + 0x0); pub const LOAD2 = @intToPtr(*volatile u8, base + 0x4); pub const LOAD1 = @intToPtr(*volatile u8, base + 0x8); pub const LOAD0 = @intToPtr(*volatile u8, base + 0xc); /// Load value when Timer is (re-)enabled. /// In One-Shot mode, the value written to this register specify the /// Timer’s duration in clock cycles. pub fn load(x: u32) void { LOAD3.* = @truncate(u8, x >> 24); LOAD2.* = @truncate(u8, x >> 16); LOAD1.* = @truncate(u8, x >> 8); LOAD0.* = @truncate(u8, x); } pub const RELOAD3 = @intToPtr(*volatile u8, base + 0x10); pub const RELOAD2 = @intToPtr(*volatile u8, base + 0x14); pub const RELOAD1 = @intToPtr(*volatile u8, base + 0x18); pub const RELOAD0 = @intToPtr(*volatile u8, base + 0x1c); /// Reload value when Timer reaches 0. /// In Periodic mode, the value written to this register specify the /// Timer’s period in clock cycles. pub fn reload(x: u32) void { RELOAD3.* = @truncate(u8, x >> 24); RELOAD2.* = @truncate(u8, x >> 16); RELOAD1.* = @truncate(u8, x >> 8); RELOAD0.* = @truncate(u8, x); } /// Enable of the Timer. /// Set if to 1 to enable/start the Timer and 0 to disable the Timer pub const EN = @intToPtr(*volatile bool, base + 0x20); pub fn start() void { EN.* = true; } pub fn stop() void { EN.* = false; } /// Update of the current countdown value. /// A write to this register latches the current countdown value to value /// register. pub const UPDATE_VALUE = @intToPtr(*volatile bool, base + 0x24); pub const VALUE3 = @intToPtr(*volatile u8, base + 0x28); pub const VALUE2 = @intToPtr(*volatile u8, base + 0x2c); pub const VALUE1 = @intToPtr(*volatile u8, base + 0x30); pub const VALUE0 = @intToPtr(*volatile u8, base + 0x34); pub fn latchedValue() u32 { return (@as(u32, VALUE3.*) << 24) | (@as(u32, VALUE2.*) << 16) | (@as(u32, VALUE1.*) << 8) | (@as(u32, VALUE0.*)); } pub fn value() u32 { UPDATE_VALUE.* = true; return latchedValue(); } /// This register contains the current raw level of the Event trigger. /// Writes to this register have no effect. pub const EV_STATUS = @intToPtr(*volatile bool, base + 0x38); /// When an Event occurs, the corresponding bit will be set in this /// register. To clear the Event, set the corresponding bit in this /// register. pub const EV_PENDING = @intToPtr(*volatile bool, base + 0x3c); /// This register enables the corresponding Events. Write a 0 to this /// register to disable individual events. pub const EV_ENABLE = @intToPtr(*volatile bool, base + 0x40); };
riscv-zig-blink/src/fomu/timer0.zig
pub const Vertex = struct { pos: @Vector(4, f32), col: @Vector(4, f32), uv: @Vector(2, f32), }; pub const vertices = [_]Vertex{ .{ .pos = .{ 1, -1, 1, 1 }, .col = .{ 1, 0, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, -1, 1, 1 }, .col = .{ 0, 0, 1, 1 }, .uv = .{ 1, 1 } }, .{ .pos = .{ -1, -1, -1, 1 }, .col = .{ 0, 0, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ 1, -1, -1, 1 }, .col = .{ 1, 0, 0, 1 }, .uv = .{ 0, 0 } }, .{ .pos = .{ 1, -1, 1, 1 }, .col = .{ 1, 0, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, -1, -1, 1 }, .col = .{ 0, 0, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ 1, 1, 1, 1 }, .col = .{ 1, 1, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ 1, -1, 1, 1 }, .col = .{ 1, 0, 1, 1 }, .uv = .{ 1, 1 } }, .{ .pos = .{ 1, -1, -1, 1 }, .col = .{ 1, 0, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ 1, 1, -1, 1 }, .col = .{ 1, 1, 0, 1 }, .uv = .{ 0, 0 } }, .{ .pos = .{ 1, 1, 1, 1 }, .col = .{ 1, 1, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ 1, -1, -1, 1 }, .col = .{ 1, 0, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ -1, 1, 1, 1 }, .col = .{ 0, 1, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ 1, 1, 1, 1 }, .col = .{ 1, 1, 1, 1 }, .uv = .{ 1, 1 } }, .{ .pos = .{ 1, 1, -1, 1 }, .col = .{ 1, 1, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ -1, 1, -1, 1 }, .col = .{ 0, 1, 0, 1 }, .uv = .{ 0, 0 } }, .{ .pos = .{ -1, 1, 1, 1 }, .col = .{ 0, 1, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ 1, 1, -1, 1 }, .col = .{ 1, 1, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ -1, -1, 1, 1 }, .col = .{ 0, 0, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, 1, 1, 1 }, .col = .{ 0, 1, 1, 1 }, .uv = .{ 1, 1 } }, .{ .pos = .{ -1, 1, -1, 1 }, .col = .{ 0, 1, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ -1, -1, -1, 1 }, .col = .{ 0, 0, 0, 1 }, .uv = .{ 0, 0 } }, .{ .pos = .{ -1, -1, 1, 1 }, .col = .{ 0, 0, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, 1, -1, 1 }, .col = .{ 0, 1, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ 1, 1, 1, 1 }, .col = .{ 1, 1, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, 1, 1, 1 }, .col = .{ 0, 1, 1, 1 }, .uv = .{ 1, 1 } }, .{ .pos = .{ -1, -1, 1, 1 }, .col = .{ 0, 0, 1, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ -1, -1, 1, 1 }, .col = .{ 0, 0, 1, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ 1, -1, 1, 1 }, .col = .{ 1, 0, 1, 1 }, .uv = .{ 0, 0 } }, .{ .pos = .{ 1, 1, 1, 1 }, .col = .{ 1, 1, 1, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ 1, -1, -1, 1 }, .col = .{ 1, 0, 0, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, -1, -1, 1 }, .col = .{ 0, 0, 0, 1 }, .uv = .{ 1, 1 } }, .{ .pos = .{ -1, 1, -1, 1 }, .col = .{ 0, 1, 0, 1 }, .uv = .{ 1, 0 } }, .{ .pos = .{ 1, 1, -1, 1 }, .col = .{ 1, 1, 0, 1 }, .uv = .{ 0, 0 } }, .{ .pos = .{ 1, -1, -1, 1 }, .col = .{ 1, 0, 0, 1 }, .uv = .{ 0, 1 } }, .{ .pos = .{ -1, 1, -1, 1 }, .col = .{ 0, 1, 0, 1 }, .uv = .{ 1, 0 } }, };
examples/textured-cube/cube_mesh.zig
const stdx = @import("stdx"); const Function = stdx.Function; const graphics = @import("graphics"); const Color = graphics.Color; const platform = @import("platform"); const MouseUpEvent = platform.MouseUpEvent; const MouseDownEvent = platform.MouseDownEvent; const ui = @import("../ui.zig"); const Padding = ui.widgets.Padding; const Text = ui.widgets.Text; const log = stdx.log.scoped(.button); pub const TextButton = struct { props: struct { onClick: ?Function(fn (MouseUpEvent) void) = null, bg_color: Color = Color.init(220, 220, 220, 255), bg_pressed_color: Color = Color.Gray.darker(), border_size: f32 = 1, border_color: Color = Color.Gray, corner_radius: f32 = 0, text: ?[]const u8, }, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { return c.decl(Button, .{ .onClick = self.props.onClick, .bg_color = self.props.bg_color, .bg_pressed_color = self.props.bg_pressed_color, .border_size = self.props.border_size, .border_color = self.props.border_color, .corner_radius = self.props.corner_radius, .child = c.decl(Padding, .{ .padding = 10, .child = c.decl(Text, .{ .text = self.props.text, }), }), }); } }; pub const Button = struct { props: struct { onClick: ?Function(fn (platform.MouseUpEvent) void) = null, bg_color: Color = Color.init(220, 220, 220, 255), bg_pressed_color: Color = Color.Gray.darker(), border_size: f32 = 1, border_color: Color = Color.Gray, corner_radius: f32 = 0, child: ui.FrameId = ui.NullFrameId, halign: ui.HAlign = .Center, }, pressed: bool, const Self = @This(); pub fn build(self: *Self, c: *ui.BuildContext) ui.FrameId { _ = c; return self.props.child; } pub fn init(self: *Self, c: *ui.InitContext) void { self.pressed = false; c.addMouseDownHandler(c.node, handleMouseDownEvent); c.addMouseUpHandler(c.node, handleMouseUpEvent); } fn handleMouseUpEvent(node: *ui.Node, e: ui.MouseUpEvent) void { var self = node.getWidget(Self); if (e.val.button == .Left) { if (self.pressed) { self.pressed = false; if (self.props.onClick) |cb| { cb.call(.{ e.val }); } } } } fn handleMouseDownEvent(node: *ui.Node, e: ui.Event(MouseDownEvent)) ui.EventResult { var self = node.getWidget(Self); if (e.val.button == .Left) { e.ctx.requestFocus(onBlur); self.pressed = true; } return .Continue; } fn onBlur(node: *ui.Node, ctx: *ui.CommonContext) void { _ = ctx; var self = node.getWidget(Self); self.pressed = false; } /// Defaults to a fixed size if there is no child widget. pub fn layout(self: *Self, c: *ui.LayoutContext) ui.LayoutSize { const cstr = c.getSizeConstraint(); var res: ui.LayoutSize = cstr; if (self.props.child != ui.NullFrameId) { const child_node = c.getNode().children.items[0]; var child_size = c.computeLayout(child_node, cstr); child_size.cropTo(cstr); res = child_size; if (c.prefer_exact_width) { res.width = cstr.width; } if (c.prefer_exact_height) { res.height = cstr.height; } switch (self.props.halign) { .Left => c.setLayout(child_node, ui.Layout.initWithSize(0, 0, child_size)), .Center => c.setLayout(child_node, ui.Layout.initWithSize((res.width - child_size.width)/2, 0, child_size)), .Right => c.setLayout(child_node, ui.Layout.initWithSize(res.width - child_size.width, 0, child_size)), } return res; } else { res = ui.LayoutSize.init(150, 40); if (c.prefer_exact_width) { res.width = cstr.width; } if (c.prefer_exact_height) { res.height = cstr.height; } return res; } } pub fn render(self: *Self, ctx: *ui.RenderContext) void { const alo = ctx.getAbsLayout(); const g = ctx.getGraphics(); if (!self.pressed) { g.setFillColor(self.props.bg_color); } else { g.setFillColor(self.props.bg_pressed_color); } if (self.props.corner_radius > 0) { g.fillRoundRect(alo.x, alo.y, alo.width, alo.height, self.props.corner_radius); g.setLineWidth(self.props.border_size); g.setStrokeColor(self.props.border_color); g.drawRoundRect(alo.x, alo.y, alo.width, alo.height, self.props.corner_radius); } else { g.fillRect(alo.x, alo.y, alo.width, alo.height); g.setLineWidth(self.props.border_size); g.setStrokeColor(self.props.border_color); g.drawRect(alo.x, alo.y, alo.width, alo.height); } } };
ui/src/widgets/button.zig
const std = @import("std"); const stdx = @import("stdx"); const t = stdx.testing; const string = stdx.string; const ds = stdx.ds; const algo = stdx.algo; const log = stdx.log.scoped(.ttf); // NOTES: // Chrome does not support SVG in fonts but they support colored bitmaps. // - https://bugs.chromium.org/p/chromium/issues/detail?id=306078#c53) // - See also https://github.com/fontforge/fontforge/issues/677 // COLR table - https://docs.microsoft.com/en-us/typography/opentype/spec/colr // CPAL table - https://docs.microsoft.com/en-us/typography/opentype/spec/cpal // SVG table - https://docs.microsoft.com/en-us/typography/opentype/spec/svg // SBIX table - https://docs.microsoft.com/en-us/typography/opentype/spec/sbix (promoted by apple) // OTF data types: https://docs.microsoft.com/en-us/typography/opentype/spec/otff // Use ttx from fonttools to create a human readable .ttx file from ttf: https://simoncozens.github.io/fonts-and-layout/opentype.html // LINKS: // https://github.com/RazrFalcon/ttf-parser // https://github.com/nothings/stb/pull/750 (Pulling svg glyph data) const PLATFORM_ID_UNICODE = 0; const PLATFORM_ID_MACINTOSH = 1; const PLATFORM_ID_WINDOWS = 3; const UNICODE_EID_UNICODE_1_0 = 0; // deprecated const UNICODE_EID_UNICODE_1_1 = 1; // deprecated const WINDOWS_EID_SYMBOL = 0; const WINDOWS_EID_UNICODE_BMP = 1; const WINDOWS_EID_UNICODE_FULL_REPERTOIRE = 10; // Requires a format 12 glyph index const BITMAP_FLAG_HORIZONTAL_METRICS: i8 = 1; pub const NAME_ID_FONT_FAMILY: u16 = 1; const FontError = error{ InvalidFont, Unsupported, }; // In font design units. pub const VMetrics = struct { // max distance above baseline (positive units) ascender: i16, // max distance below baseline (negative units) descender: i16, // gap between the previous row's descent and current row's ascent. line_gap: i16, }; // In font design units. const GlyphHMetrics = struct { advance_width: u16, left_side_bearing: i16, }; const GlyphBitmap = struct { width: u8, height: u8, bearing_x: i8, bearing_y: i8, advance: u8, /// Order is row major. Size of data is width * height. data: []const u8, pub fn deinit(self: @This(), alloc: std.mem.Allocator) void { alloc.free(self.data); } }; const GlyphColorBitmap = struct { // In px units. width: u8, height: u8, left_side_bearing: i8, bearing_y: i8, advance_width: u8, // How many px in the bitmap represent 1 em. This lets us scale the px units to the font size. x_px_per_em: u8, y_px_per_em: u8, png_data: []const u8, }; const GlyphMapperIface = struct { const Self = @This(); ptr: *anyopaque, get_glyph_id_fn: fn (*anyopaque, cp: u21) FontError!?u16, fn init(ptr: anytype) Self { const ImplPtr = @TypeOf(ptr); const gen = struct { fn getGlyphId(_ptr: *anyopaque, cp: u21) FontError!?u16 { const self = stdx.mem.ptrCastAlign(ImplPtr, _ptr); return self.getGlyphId(cp); } }; return .{ .ptr = ptr, .get_glyph_id_fn = gen.getGlyphId, }; } // Maps codepoint to glyph index. fn getGlyphId(self: Self, cp: u21) FontError!?u16 { return self.get_glyph_id_fn(self.ptr, cp); } }; /// Loads TTF/OTF/OTB. /// Contains useful data from initial parse of the file. pub const OpenTypeFont = struct { const Self = @This(); start: usize, data: []const u8, // Offsets from &data[0]. // https://docs.microsoft.com/en-us/typography/opentype/spec/head head_offset: usize, // https://docs.microsoft.com/en-us/typography/opentype/spec/hhea hhea_offset: usize, // https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx hmtx_offset: usize, // https://docs.microsoft.com/en-us/typography/opentype/spec/cbdt cbdt_offset: ?usize, // https://docs.microsoft.com/en-us/typography/opentype/spec/ebdt ebdt_offset: ?usize, // https://docs.microsoft.com/en-us/typography/opentype/spec/eblc eblc_offset: ?usize, // https://docs.microsoft.com/en-us/typography/opentype/spec/cblc cblc_offset: ?usize, glyf_offset: ?usize, cff_offset: ?usize, glyph_map_format: u16, glyph_mapper: GlyphMapperIface, glyph_mapper_box: ds.SizedBox, num_glyphs: usize, // From hhea. ascender: i16, descender: i16, line_gap: i16, // https://help.fontlab.com/fontlab-vi/Font-Sizes-and-the-Coordinate-System/ // This is the height in font design units of the internal font size. // Note that the concept of font size isn't the maximum height of the font. // Units-per-em (UPM) is used to scale to user defined font size like pixels. units_per_em: u16, // start_offset is offset that begins the font data in a font collection file (ttc). // start_offset is 0 if it's a ttf/otf file. pub fn init(alloc: std.mem.Allocator, data: []const u8, start_offset: usize) !Self { var new = Self{ .data = data, .start = start_offset, .head_offset = undefined, .hhea_offset = undefined, .hmtx_offset = undefined, .cbdt_offset = null, .cblc_offset = null, .ebdt_offset = null, .eblc_offset = null, .glyf_offset = null, .cff_offset = null, .glyph_mapper = undefined, .glyph_mapper_box = undefined, .glyph_map_format = 0, .num_glyphs = 0, .ascender = undefined, .descender = undefined, .line_gap = undefined, .units_per_em = undefined, }; try new.loadTables(alloc); new.ascender = fromBigI16(&data[new.hhea_offset + 4]); new.descender = fromBigI16(&data[new.hhea_offset + 6]); new.line_gap = fromBigI16(&data[new.hhea_offset + 8]); new.units_per_em = fromBigU16(&data[new.head_offset + 18]); return new; } pub fn deinit(self: Self) void { self.glyph_mapper_box.deinit(); } pub fn hasGlyphOutlines(self: Self) bool { return self.glyf_offset != null or self.cff_offset != null; } pub fn hasColorBitmap(self: Self) bool { return self.cbdt_offset != null; } pub fn hasEmbeddedBitmap(self: Self) bool { return self.ebdt_offset != null; } pub fn getVerticalMetrics(self: Self) VMetrics { return .{ .ascender = self.ascender, .descender = self.descender, .line_gap = self.line_gap, }; } pub fn getBitmapVerticalMetrics(self: Self) VMetrics { if (self.ebdt_offset == null) { @panic("No ebdt"); } const num_bitmap_sizes = fromBigU32(&self.data[self.eblc_offset.? + 4]); var i: usize = 0; while (i < num_bitmap_sizes) : (i += 1) { const BitmapSizeRecordSize = 48; const horz_ascender = @bitCast(i8, self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 16]); const horz_descender = @bitCast(i8, self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 17]); // Bitmap fonts store their vmetrics in the BitmapSizeRecord. return .{ .ascender = horz_ascender, .descender = horz_descender, .line_gap = 0, }; } @panic("No bitmap size record."); } pub fn getGlyphHMetrics(self: *const Self, glyph_id: u16) GlyphHMetrics { // If glyph_id >= num_hmetrics, then the advance is in the last hmetric record, // and left side bearing is in array following the hmetric records. // See https://docs.microsoft.com/en-us/typography/opentype/spec/hmtx const num_hmetrics = fromBigU16(&self.data[self.hhea_offset + 34]); if (glyph_id < num_hmetrics) { return .{ .advance_width = fromBigU16(&self.data[self.hmtx_offset + 4 * glyph_id]), .left_side_bearing = fromBigI16(&self.data[self.hmtx_offset + 4 * glyph_id + 2]), }; } else { return .{ .advance_width = fromBigU16(&self.data[self.hmtx_offset + 4 * (num_hmetrics - 1)]), .left_side_bearing = fromBigI16(&self.data[self.hmtx_offset + 4 * num_hmetrics + 2 * (glyph_id - num_hmetrics)]), }; } } // Given user font size unit, returns the scale needed to multiply with font design units. // eg. bitmap px font size, note the glyphs drawn onto the resulting bitmap can exceed the px font size, since // the concept of font size does not equate to the maximum height of the font. pub fn getScaleToUserFontSize(self: *const Self, size: f32) f32 { return size / @intToFloat(f32, self.units_per_em); } /// Get's the bitmap (monochrome or grayscale) for a glyph id. pub fn getGlyphBitmap(self: Self, alloc: std.mem.Allocator, glyph_id: u16) !?GlyphBitmap { if (self.ebdt_offset == null) { return null; } const num_bitmap_sizes = fromBigU32(&self.data[self.eblc_offset.? + 4]); var i: usize = 0; while (i < num_bitmap_sizes) : (i += 1) { const BitmapSizeRecordSize = 48; const index_subtable_array_offset = fromBigU32(&self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize]); const num_subtables = fromBigU32(&self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 8]); const start_glyph_id = fromBigU16(&self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 36]); const end_glyph_id = fromBigU16(&self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 38]); const ppemx = self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 40]; const ppemy = self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 41]; const flags = self.data[self.eblc_offset.? + 8 + i * BitmapSizeRecordSize + 43]; // These aren't always filled in. _ = start_glyph_id; _ = end_glyph_id; _ = ppemx; _ = ppemy; _ = flags; const SubtableArrayItemSize = 8; var j: usize = 0; while (j < num_subtables) : (j += 1) { const item_offset = self.eblc_offset.? + index_subtable_array_offset + j * SubtableArrayItemSize; const sub_start_glyph_id = fromBigU16(&self.data[item_offset]); const sub_end_glyph_id = fromBigU16(&self.data[item_offset+2]); const sub_add_offset = fromBigU32(&self.data[item_offset+4]); if (glyph_id >= sub_start_glyph_id and glyph_id <= sub_end_glyph_id) { const subtable_idx = self.eblc_offset.? + index_subtable_array_offset + sub_add_offset; const index_format = fromBigU16(&self.data[subtable_idx]); const image_format = fromBigU16(&self.data[subtable_idx+2]); const data_offset = fromBigU32(&self.data[subtable_idx+4]); switch (index_format) { 2 => { const glyph_size = fromBigU32(&self.data[subtable_idx+8]); const height = self.data[subtable_idx+12]; const width = self.data[subtable_idx+13]; const hori_bearing_x = @bitCast(i8, self.data[subtable_idx+14]); const hori_bearing_y = @bitCast(i8, self.data[subtable_idx+15]); const hori_advance = self.data[subtable_idx+16]; const glyph_idx = glyph_id - sub_start_glyph_id; const glyph_data = self.data[self.ebdt_offset.? + data_offset + glyph_idx * glyph_size..][0..glyph_size]; return try parseGlyphBitmapData5(alloc, width, height, hori_bearing_x, hori_bearing_y, hori_advance, glyph_data); }, 3 => { const glyph_idx = glyph_id - sub_start_glyph_id; const glyph_offset = fromBigU16(&self.data[subtable_idx+8+glyph_idx*2]); return try parseGlyphBitmapData(alloc, image_format, self.data[self.ebdt_offset.?+data_offset+glyph_offset..]); }, else => { log.debug("unsupported format: {}", .{index_format}); return error.UnsupportedIndexFormat; }, } } } } return null; } /// Format #5 has metrics data provided. pub fn parseGlyphBitmapData5(alloc: std.mem.Allocator, width: u8, height: u8, bearing_x: i8, bearing_y: i8, advance: u8, data: []const u8) !GlyphBitmap { const cdata = alloc.alloc(u8, width * height) catch @panic("error"); var reader = std.io.bitReader(.Big, std.io.fixedBufferStream(data).reader()); var out_bits: usize = undefined; for (cdata) |_, i| { const val = try reader.readBits(u1, 1, &out_bits); if (val == 1) { cdata[i] = 255; } else { cdata[i] = 0; } } return GlyphBitmap{ .bearing_x = bearing_x, .bearing_y = bearing_y, .advance = advance, .width = width, .height = height, .data = cdata, }; } pub fn parseGlyphBitmapData(alloc: std.mem.Allocator, image_format: u16, data: []const u8) !GlyphBitmap { switch (image_format) { 2 => { const num_rows = data[0]; const num_cols = data[1]; const bearing_x = @bitCast(i8, data[2]); const bearing_y = @bitCast(i8, data[3]); const advance = data[4]; if (num_rows * num_cols > 1e3) { return error.GlyphTooBig; } const cdata = alloc.alloc(u8, num_rows * num_cols) catch @panic("error"); var reader = std.io.bitReader(.Big, std.io.fixedBufferStream(data[5..]).reader()); var out_bits: usize = undefined; for (cdata) |_, i| { const val = try reader.readBits(u1, 1, &out_bits); if (val == 1) { cdata[i] = 255; } else { cdata[i] = 0; } } return GlyphBitmap{ .bearing_x = bearing_x, .bearing_y = bearing_y, .advance = advance, .width = num_cols, .height = num_rows, .data = cdata, }; }, else => return error.UnsupportedImageFormat, } } // Get's the color bitmap data for glyph id. // eg. NotoColorEmoji.ttf has png data. // Doesn't cache anything. pub fn getGlyphColorBitmap(self: *const Self, glyph_id: u16) !?GlyphColorBitmap { if (self.cbdt_offset == null) { return null; } // Retrieve bitmap location from cblc: https://docs.microsoft.com/en-us/typography/opentype/spec/cblc const num_bitmap_records = fromBigU32(&self.data[self.cblc_offset.? + 4]); // log.debug("bitmap records: {}", .{num_bitmap_records}); var i: usize = 0; while (i < num_bitmap_records) : (i += 1) { const b_offset = self.cblc_offset.? + 8 + i * 48; const start_glyph_id = fromBigU16(&self.data[b_offset + 40]); const end_glyph_id = fromBigU16(&self.data[b_offset + 42]); const x_px_per_em = self.data[b_offset + 44]; const y_px_per_em = self.data[b_offset + 45]; const flags = @bitCast(i8, self.data[b_offset + 47]); if (flags != BITMAP_FLAG_HORIZONTAL_METRICS) { // This record is not for horizontally text. continue; } // log.debug("ppem {} {} {}", .{x_px_per_em, y_px_per_em, flags}); if (glyph_id >= start_glyph_id and glyph_id <= end_glyph_id) { // Scan more granular range in index subtables. const ist_start_offset = self.cblc_offset.? + fromBigU32(&self.data[b_offset + 0]); const num_index_subtables = fromBigU32(&self.data[b_offset + 8]); // log.debug("num subtables: {}", .{num_index_subtables}); var ist_i: usize = 0; while (ist_i < num_index_subtables) : (ist_i += 1) { // Start by looking at the IndexSubTableArray const arr_offset = ist_start_offset + ist_i * 8; const arr_start_glyph_id = fromBigU16(&self.data[arr_offset + 0]); const arr_end_glyph_id = fromBigU16(&self.data[arr_offset + 2]); // log.debug("glyph id: {}", .{glyph_id}); if (glyph_id >= arr_start_glyph_id and glyph_id <= arr_end_glyph_id) { // log.debug("index subtable array {} {}", .{arr_start_glyph_id, arr_end_glyph_id}); const ist_body_offset = ist_start_offset + fromBigU32(&self.data[arr_offset + 4]); const index_format = fromBigU16(&self.data[ist_body_offset + 0]); const image_format = fromBigU16(&self.data[ist_body_offset + 2]); const image_data_start_offset = self.cbdt_offset.? + fromBigU32(&self.data[ist_body_offset + 4]); // log.debug("format {} {}", .{index_format, image_format}); var glyph_data: []const u8 = undefined; if (index_format == 1) { const glyph_id_delta = glyph_id - arr_start_glyph_id; const glyph_data_offset = fromBigU32(&self.data[ist_body_offset + 8 + glyph_id_delta * 4]); // There is always a data offset after the glyph, even the last glyph. Used to calculate glyph data size. const next_glyph_data_offset = fromBigU32(&self.data[ist_body_offset + 8 + (glyph_id_delta + 1) * 4]); // log.debug("glyph data {} {}", .{glyph_data_offset, next_glyph_data_offset}); glyph_data = self.data[image_data_start_offset + glyph_data_offset .. image_data_start_offset + next_glyph_data_offset]; } else { return FontError.Unsupported; } if (image_format == 17) { // https://docs.microsoft.com/en-us/typography/opentype/spec/cbdt#format-17-small-metrics-png-image-data // log.debug("data len: {}", .{fromBigU32(&glyph_data[5])}); return GlyphColorBitmap{ .width = glyph_data[1], .height = glyph_data[0], .left_side_bearing = @bitCast(i8, glyph_data[2]), .bearing_y = @bitCast(i8, glyph_data[3]), .advance_width = glyph_data[4], .x_px_per_em = x_px_per_em, .y_px_per_em = y_px_per_em, .png_data = glyph_data[9..], }; } else { return FontError.Unsupported; } } } } } return null; } // Returns glyph id for utf codepoint. pub fn getGlyphId(self: *const Self, cp: u21) !?u16 { return self.glyph_mapper.getGlyphId(cp); } pub fn allocFontFamilyName(self: *const Self, alloc: std.mem.Allocator) ?[]const u8 { return self.allocNameString(alloc, NAME_ID_FONT_FAMILY); } // stbtt has GetFontNameString but requires you to pass in specific platformId, encodingId and languageId. // This will return the first acceptable value for a given nameId. Useful for getting things like font family. pub fn allocNameString(self: *const Self, alloc: std.mem.Allocator, name_id: u16) ?[]const u8 { const pos = self.findTable("name".*) orelse return null; const data = self.data; const count = fromBigU16(&data[pos + 2]); const string_data_pos = pos + fromBigU16(&data[pos + 4]); var i: usize = 0; while (i < count) : (i += 1) { const loc = pos + 6 + 12 * i; const platform_id = fromBigU16(&data[loc]); const encoding_id = fromBigU16(&data[loc + 2]); // Currently only looks for unicode encoding. // https://github.com/RazrFalcon/fontdb/blob/master/src/lib.rs looks at mac roman as well. if (!isUnicodeEncoding(platform_id, encoding_id)) { continue; } // const lang_id = fromBigU16(&data[loc+4]); const it_name_id = fromBigU16(&data[loc + 6]); if (it_name_id == name_id) { const len = fromBigU16(&data[loc + 8]); const str_pos = string_data_pos + fromBigU16(&data[loc + 10]); return allocBigUTF16(alloc, data[str_pos .. str_pos + len]); } } return null; } // Based on https://github.com/RazrFalcon/ttf-parser/blob/master/src/tables/name.rs is_unicode_encoding fn isUnicodeEncoding(platform_id: u16, encoding_id: u16) bool { return switch (platform_id) { PLATFORM_ID_UNICODE => true, PLATFORM_ID_WINDOWS => switch (encoding_id) { WINDOWS_EID_SYMBOL, WINDOWS_EID_UNICODE_BMP, WINDOWS_EID_UNICODE_FULL_REPERTOIRE => true, else => false, }, else => false, }; } // Only retrieves offset info. // Returns error if minimum data isn't fn loadTables(self: *Self, alloc: std.mem.Allocator) !void { var loaded_glyph_map = false; var found_hhea = false; var found_hmtx = false; var found_head = false; errdefer { if (loaded_glyph_map) { self.glyph_mapper_box.deinit(); } } const data = self.data; const start = self.start; const num_tables = fromBigU16(&data[start + 4]); const tabledir = start + 12; var i: usize = 0; while (i < num_tables) : (i += 1) { const loc = tabledir + 16 * i; const val: [4]u8 = data[loc .. loc + 4][0..4].*; if (std.meta.eql(val, "CBDT".*)) { self.cbdt_offset = fromBigU32(&data[loc + 8]); } else if (std.meta.eql(val, "EBLC".*)) { self.eblc_offset = fromBigU32(&data[loc + 8]); } else if (std.meta.eql(val, "EBDT".*)) { self.ebdt_offset = fromBigU32(&data[loc + 8]); } else if (std.meta.eql(val, "CBLC".*)) { self.cblc_offset = fromBigU32(&data[loc + 8]); } else if (std.meta.eql(val, "head".*)) { self.head_offset = fromBigU32(&data[loc + 8]); found_head = true; } else if (std.meta.eql(val, "hhea".*)) { self.hhea_offset = fromBigU32(&data[loc + 8]); found_hhea = true; } else if (std.meta.eql(val, "hmtx".*)) { self.hmtx_offset = fromBigU32(&data[loc + 8]); found_hmtx = true; } else if (std.meta.eql(val, "glyf".*)) { self.glyf_offset = fromBigU32(&data[loc + 8]); } else if (std.meta.eql(val, "CFF ".*)) { self.cff_offset = fromBigU32(&data[loc + 8]); } else if (std.meta.eql(val, "maxp".*)) { const offset = fromBigU32(&data[loc + 8]); // https://docs.microsoft.com/en-us/typography/opentype/spec/maxp self.num_glyphs = fromBigU16(&data[offset + 4]); } else if (std.meta.eql(val, "cmap".*)) { const t_offset = fromBigU32(&data[loc + 8]); // https://docs.microsoft.com/en-us/typography/opentype/spec/cmap const cmap_num_tables = fromBigU16(&data[t_offset + 2]); var cmap_i: usize = 0; // log.debug("cmap num tables: {}", .{cmap_num_tables}); while (cmap_i < cmap_num_tables) : (cmap_i += 1) { const r_offset = t_offset + 4 + cmap_i * 8; const platform_id = fromBigU16(&data[r_offset]); const encoding_id = fromBigU16(&data[r_offset + 2]); // log.debug("platform: {} {}", .{platform_id, encoding_id}); if (isUnicodeEncoding(platform_id, encoding_id)) { const st_offset = t_offset + fromBigU32(&data[r_offset + 4]); const format = fromBigU16(&data[st_offset]); // log.debug("format: {}", .{format}); if (format == 14) { // Unicode variation sequences // https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-14-unicode-variation-sequences // NotoColorEmoji.ttf // TODO: // Since we don't support UVS we can ignore this table for now. // const mapper = UvsGlyphMapper.init(alloc, ds.Transient([]const u8).init(data), st_offset); // self.glyph_mapper = @ptrCast(*ds.Opaque, mapper); // self.deinit_glyph_mapper = @field(mapper, "deinit_fn"); // self.get_glyph_index_fn = @field(mapper, "get_glyph_index_fn"); // loaded_glyph_map = true; continue; } else if (format == 12) { const mapper = ds.Box(SegmentedCoverageGlyphMapper).create(alloc) catch unreachable; mapper.ptr.init(data, st_offset); self.glyph_mapper = GlyphMapperIface.init(mapper.ptr); self.glyph_mapper_box = mapper.toSized(); loaded_glyph_map = true; } else if (format == 4) { const mapper = ds.Box(SegmentGlyphMapper).create(alloc) catch unreachable; mapper.ptr.init(data, st_offset); self.glyph_mapper = GlyphMapperIface.init(mapper.ptr); self.glyph_mapper_box = mapper.toSized(); loaded_glyph_map = true; } if (loaded_glyph_map) { self.glyph_map_format = format; break; } } } } } // Required. if (!loaded_glyph_map or !found_head or !found_hhea or !found_hmtx) { // No codepoint glyph index mapping found. return error.InvalidFont; } // Must have either glyph outlines or glyph color bitmap. if (!self.hasColorBitmap() and !self.hasGlyphOutlines()) { return error.InvalidFont; } } pub fn printTables(self: *const Self) void { const start = self.start; const num_tables = fromBigU16(&self.data[start + 4]); const tabledir = start + 12; var i: usize = 0; while (i < num_tables) : (i += 1) { const loc = tabledir + 16 * i; const val: [4]u8 = stdx.mem.to_array_ptr(u8, &self.data[loc], 4).*; log.debug("table {s}", .{val}); } } // Copied from stbtt__find_table fn findTable(self: *const Self, tag: [4]u8) ?usize { const start = self.start; const num_tables = fromBigU16(&self.data[start + 4]); const tabledir = start + 12; var i: usize = 0; while (i < num_tables) : (i += 1) { const loc = tabledir + 16 * i; const val: [4]u8 = self.data[loc .. loc + 4][0..4].*; if (std.meta.eql(val, tag)) { return fromBigU32(&self.data[loc + 8]); } } return null; } }; // Standard mapping that only supports Unicode Basic Multilingual Plane characters (U+0000 to U+FFFF) // https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-4-segment-mapping-to-delta-values // Example font: NunitoSans-Regular.ttf const SegmentGlyphMapper = struct { const Self = @This(); data: []const u8, offset: usize, num_segments: usize, fn init(self: *Self, data: []const u8, offset: usize) void { self.* = .{ .data = data, .num_segments = fromBigU16(&data[offset + 6]) >> 1, .offset = offset, }; // log.debug("num segments: {}", .{new.num_segments}); } // Does not cache records. fn getGlyphId(self: *Self, cp: u21) FontError!?u16 { // This mapping only supports utf basic codepoints. if (cp > std.math.maxInt(u16)) { return null; } const S = struct { fn compare(ctx: *const SegmentGlyphMapper, target_cp: u16, idx: usize) std.math.Order { const end_code = fromBigU16(&ctx.data[ctx.offset + 14 + idx * 2]); const start_code = fromBigU16(&ctx.data[ctx.offset + 16 + (ctx.num_segments + idx) * 2]); if (target_cp > end_code) { return .gt; } else if (target_cp < start_code) { return .lt; } else { return .eq; } } }; const cp16 = @intCast(u16, cp); if (algo.binarySearchByIndex(self.num_segments, cp16, self, S.compare)) |i| { // log.debug("i {}", .{i}); const start_code = fromBigU16(&self.data[self.offset + 16 + (self.num_segments + i) * 2]); const id_range_offsets_loc = self.offset + 16 + (self.num_segments * 3) * 2; const id_range_offset_loc = id_range_offsets_loc + i * 2; const id_range_offset = fromBigU16(&self.data[id_range_offset_loc]); if (id_range_offset == 0) { // Use id_delta const id_deltas_loc = self.offset + 16 + (self.num_segments * 2) * 2; // although id_delta a i16, since it's modulo 2^8, we can interpret it as u16 and just add with overflow. const id_delta = fromBigU16(&self.data[id_deltas_loc + i * 2]); var res: u16 = undefined; _ = @addWithOverflow(u16, id_delta, cp16, &res); return res; } else { // Use id_range_offset const glyph_offset = id_range_offset_loc + (cp16 - start_code) * 2 + id_range_offset; return fromBigU16(&self.data[glyph_offset]); } } else { return null; } } }; // https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-12-segmented-coverage // NotoColorEmoji.ttf const SegmentedCoverageGlyphMapper = struct { const Self = @This(); data: []const u8, offset: usize, num_group_records: usize, fn init(self: *Self, data: []const u8, offset: usize) void { self.* = .{ .data = data, .num_group_records = fromBigU32(&data[offset + 12]), .offset = offset, }; // log.debug("num group records: {}", .{new.num_group_records}); } // Does not cache records. Every query scans through all records for the codepoint. fn getGlyphId(self: *Self, cp: u21) FontError!?u16 { // TODO: groups are sorted by start char code so we can do binary search. var i: usize = 0; while (i < self.num_group_records) : (i += 1) { const g_offset = self.offset + 16 + i * 12; const start_cp = fromBigU32(&self.data[g_offset]); const end_cp = fromBigU32(&self.data[g_offset + 4]); // log.debug("range {} {}", .{start_cp, end_cp}); if (cp >= start_cp and cp <= end_cp) { const start_glyph_id = fromBigU32(&self.data[g_offset + 8]); const res = @intCast(u16, start_glyph_id + (cp - start_cp)); // log.debug("{} - {} {} - {} {}", .{cp, start_cp, end_cp, start_glyph_id, res}); return res; } } return null; } }; // https://docs.microsoft.com/en-us/typography/opentype/spec/cmap#format-14-unicode-variation-sequences // https://ccjktype.fonts.adobe.com/2013/05/opentype-cmap-table-ramblings.html // format 14 (not independent, works in conjunction with format 4 or 12) // NotoColorEmoji.ttf const UvsGlyphMapper = struct { const Self = @This(); data: []const u8, offset: usize, num_records: usize, fn init(self: *Self, data: []const u8, offset: usize) *Self { self.* = .{ .data = data, .num_records = fromBigU32(&data.value[offset + 6]), .offset = offset, }; log.debug("num uvs records: {}", .{self.num_records}); } // Does not cache records. Every query scans through all records for the codepoint + variation selector. // Starting working on this but realized this isn't what we need atm since we don't support UVS. // Unfinished, code left here to resume if we do support UVS. fn getGlyphId(self: *Self, cp: u21, var_selector: u21) FontError!u16 { var i: usize = 0; while (i < self.num_records) : (i += 1) { const vs_offset = self.offset + 10 + i * 11; const record_var_selector = fromBigU24(&self.data.value[vs_offset]); if (var_selector != record_var_selector) { continue; } const def_offset = fromBigU32(&self.data.value[vs_offset + 3]); const non_def_offset = fromBigU32(&self.data.value[vs_offset + 7]); log.debug("def/nondef {} {}", .{ def_offset, non_def_offset }); if (def_offset > 0) { const num_range_records = fromBigU32(&self.data.value[self.offset + def_offset]); var range_i: usize = 0; while (range_i < num_range_records) : (range_i += 1) { // TODO: since range records are ordered by starting cp, we can do binary search. const r_offset = self.offset + def_offset + 4 + range_i * 4; const start_cp = fromBigU24(&self.data.value[r_offset]); const additional_count = self.data.value[r_offset + 3]; if (cp >= start_cp and cp <= start_cp + additional_count) { // TODO } // log.debug("range: {} {}", .{start_cp, additional_count}); } log.debug("num ranges: {}", .{num_range_records}); } else if (non_def_offset > 0) { log.debug("TODO: non default uvs table", .{}); return FontError.Unsupported; } else { return FontError.InvalidFont; } } return 0; } }; fn allocBigUTF16(alloc: std.mem.Allocator, data: []const u8) []const u8 { const utf16 = std.mem.bytesAsSlice(u16, data); const aligned = alloc.alloc(u16, utf16.len) catch @panic("error"); defer alloc.free(aligned); for (utf16) |it, i| { aligned[i] = it; } return stdx.unicode.utf16beToUtf8Alloc(alloc, aligned) catch @panic("error"); } // TTF files use big endian. fn fromBigU16(ptr: *const u8) u16 { const arr_ptr = @intToPtr(*[2]u8, @ptrToInt(ptr)); return std.mem.readIntBig(u16, arr_ptr); } fn fromBigI16(ptr: *const u8) i16 { const arr_ptr = @intToPtr(*[2]u8, @ptrToInt(ptr)); return std.mem.readIntBig(i16, arr_ptr); } fn fromBigU24(ptr: *const u8) u24 { const arr_ptr = @intToPtr(*[3]u8, @ptrToInt(ptr)); return std.mem.readIntBig(u24, arr_ptr); } fn fromBigU32(ptr: *const u8) u32 { const arr_ptr = @intToPtr(*[4]u8, @ptrToInt(ptr)); return std.mem.readIntBig(u32, arr_ptr); } const tamzen = @embedFile("../../assets/tamzen5x9r.otb"); test "Parse tamzen." { const font = try OpenTypeFont.init(t.alloc, tamzen, 0); defer font.deinit(); const glyph_id = (try font.getGlyphId('a')).?; const glyph = (try font.getGlyphBitmap(t.alloc, glyph_id)).?; defer glyph.deinit(t.alloc); try t.eq(glyph.width, 4); try t.eq(glyph.height, 4); try t.eq(glyph.bearing_x, 0); try t.eq(glyph.bearing_y, 4); try t.eq(glyph.advance, 5); try t.eqSlice(u8, glyph.data, &.{0, 255, 255, 255, 255, 0, 0, 255, 255, 0, 0, 255, 0, 255, 255, 255}); } const vera_ttf = @embedFile("../../assets/vera.ttf"); test "Parse vera.ttf" { const font = try OpenTypeFont.init(t.alloc, vera_ttf, 0); defer font.deinit(); const glyph_id = (try font.getGlyphId('i')).?; try t.eq(glyph_id, 76); }
graphics/src/ttf.zig
const std = @import("std"); const link = @import("../link.zig"); const Module = @import("../Module.zig"); const Compilation = @import("../Compilation.zig"); const Inst = @import("../ir.zig").Inst; const Value = @import("../value.zig").Value; const Type = @import("../type.zig").Type; const C = link.File.C; const Decl = Module.Decl; const mem = std.mem; const log = std.log.scoped(.c); const Writer = std.ArrayList(u8).Writer; /// Maps a name from Zig source to C. Currently, this will always give the same /// output for any given input, sometimes resulting in broken identifiers. fn map(allocator: *std.mem.Allocator, name: []const u8) ![]const u8 { return allocator.dupe(u8, name); } const Mutability = enum { Const, Mut }; fn renderTypeAndName( ctx: *Context, writer: Writer, ty: Type, name: []const u8, mutability: Mutability, ) error{ OutOfMemory, AnalysisFail }!void { var suffix = std.ArrayList(u8).init(&ctx.arena.allocator); var render_ty = ty; while (render_ty.zigTypeTag() == .Array) { const sentinel_bit = @boolToInt(render_ty.sentinel() != null); const c_len = render_ty.arrayLen() + sentinel_bit; try suffix.writer().print("[{d}]", .{c_len}); render_ty = render_ty.elemType(); } try renderType(ctx, writer, render_ty); const const_prefix = switch (mutability) { .Const => "const ", .Mut => "", }; try writer.print(" {s}{s}{s}", .{ const_prefix, name, suffix.items }); } fn renderType( ctx: *Context, writer: Writer, t: Type, ) error{ OutOfMemory, AnalysisFail }!void { switch (t.zigTypeTag()) { .NoReturn => { try writer.writeAll("zig_noreturn void"); }, .Void => try writer.writeAll("void"), .Bool => try writer.writeAll("bool"), .Int => { switch (t.tag()) { .u8 => try writer.writeAll("uint8_t"), .i8 => try writer.writeAll("int8_t"), .u16 => try writer.writeAll("uint16_t"), .i16 => try writer.writeAll("int16_t"), .u32 => try writer.writeAll("uint32_t"), .i32 => try writer.writeAll("int32_t"), .u64 => try writer.writeAll("uint64_t"), .i64 => try writer.writeAll("int64_t"), .usize => try writer.writeAll("uintptr_t"), .isize => try writer.writeAll("intptr_t"), .c_short => try writer.writeAll("short"), .c_ushort => try writer.writeAll("unsigned short"), .c_int => try writer.writeAll("int"), .c_uint => try writer.writeAll("unsigned int"), .c_long => try writer.writeAll("long"), .c_ulong => try writer.writeAll("unsigned long"), .c_longlong => try writer.writeAll("long long"), .c_ulonglong => try writer.writeAll("unsigned long long"), .int_signed, .int_unsigned => { const info = t.intInfo(ctx.target); const sign_prefix = switch (info.signedness) { .signed => "i", .unsigned => "", }; inline for (.{ 8, 16, 32, 64, 128 }) |nbits| { if (info.bits <= nbits) { try writer.print("{s}int{d}_t", .{ sign_prefix, nbits }); break; } } else { return ctx.fail(ctx.decl.src(), "TODO: C backend: implement integer types larger than 128 bits", .{}); } }, else => unreachable, } }, .Pointer => { if (t.isSlice()) { return ctx.fail(ctx.decl.src(), "TODO: C backend: implement slices", .{}); } else { try renderType(ctx, writer, t.elemType()); try writer.writeAll(" *"); if (t.isConstPtr()) { try writer.writeAll("const "); } if (t.isVolatilePtr()) { try writer.writeAll("volatile "); } } }, .Array => { try renderType(ctx, writer, t.elemType()); try writer.writeAll(" *"); }, else => |e| return ctx.fail(ctx.decl.src(), "TODO: C backend: implement type {s}", .{ @tagName(e), }), } } fn renderValue( ctx: *Context, writer: Writer, t: Type, val: Value, ) error{ OutOfMemory, AnalysisFail }!void { switch (t.zigTypeTag()) { .Int => { if (t.isSignedInt()) return writer.print("{d}", .{val.toSignedInt()}); return writer.print("{d}", .{val.toUnsignedInt()}); }, .Pointer => switch (val.tag()) { .undef, .zero => try writer.writeAll("0"), .one => try writer.writeAll("1"), .decl_ref => { const decl = val.castTag(.decl_ref).?.data; // Determine if we must pointer cast. const decl_tv = decl.typed_value.most_recent.typed_value; if (t.eql(decl_tv.ty)) { try writer.print("&{s}", .{decl.name}); } else { try writer.writeAll("("); try renderType(ctx, writer, t); try writer.print(")&{s}", .{decl.name}); } }, .function => { const func = val.castTag(.function).?.data; try writer.print("{s}", .{func.owner_decl.name}); }, .extern_fn => { const decl = val.castTag(.extern_fn).?.data; try writer.print("{s}", .{decl.name}); }, else => |e| return ctx.fail( ctx.decl.src(), "TODO: C backend: implement Pointer value {s}", .{@tagName(e)}, ), }, .Array => { // First try specific tag representations for more efficiency. switch (val.tag()) { .undef, .empty_struct_value, .empty_array => try writer.writeAll("{}"), .bytes => { const bytes = val.castTag(.bytes).?.data; // TODO: make our own C string escape instead of using {Z} try writer.print("\"{Z}\"", .{bytes}); }, else => { // Fall back to generic implementation. try writer.writeAll("{"); var index: usize = 0; const len = t.arrayLen(); const elem_ty = t.elemType(); while (index < len) : (index += 1) { if (index != 0) try writer.writeAll(","); const elem_val = try val.elemValue(&ctx.arena.allocator, index); try renderValue(ctx, writer, elem_ty, elem_val); } if (t.sentinel()) |sentinel_val| { if (index != 0) try writer.writeAll(","); try renderValue(ctx, writer, elem_ty, sentinel_val); } try writer.writeAll("}"); }, } }, else => |e| return ctx.fail(ctx.decl.src(), "TODO: C backend: implement value {s}", .{ @tagName(e), }), } } fn renderFunctionSignature( ctx: *Context, writer: Writer, decl: *Decl, ) !void { const tv = decl.typed_value.most_recent.typed_value; // Determine whether the function is globally visible. const is_global = blk: { switch (tv.val.tag()) { .extern_fn => break :blk true, .function => { const func = tv.val.castTag(.function).?.data; break :blk ctx.module.decl_exports.contains(func.owner_decl); }, else => unreachable, } }; if (!is_global) { try writer.writeAll("static "); } try renderType(ctx, writer, tv.ty.fnReturnType()); // Use the child allocator directly, as we know the name can be freed before // the rest of the arena. const decl_name = mem.span(decl.name); const name = try map(ctx.arena.child_allocator, decl_name); defer ctx.arena.child_allocator.free(name); try writer.print(" {s}(", .{name}); var param_len = tv.ty.fnParamLen(); if (param_len == 0) try writer.writeAll("void") else { var index: usize = 0; while (index < param_len) : (index += 1) { if (index > 0) { try writer.writeAll(", "); } try renderType(ctx, writer, tv.ty.fnParamType(index)); try writer.print(" arg{}", .{index}); } } try writer.writeByte(')'); } fn indent(file: *C) !void { const indent_size = 4; const indent_level = 1; const indent_amt = indent_size * indent_level; try file.main.writer().writeByteNTimes(' ', indent_amt); } pub fn generate(file: *C, module: *Module, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; var arena = std.heap.ArenaAllocator.init(file.base.allocator); defer arena.deinit(); var inst_map = std.AutoHashMap(*Inst, []u8).init(&arena.allocator); defer inst_map.deinit(); var ctx = Context{ .decl = decl, .arena = &arena, .inst_map = &inst_map, .target = file.base.options.target, .header = &file.header, .module = module, }; defer { file.error_msg = ctx.error_msg; ctx.deinit(); } if (tv.val.castTag(.function)) |func_payload| { const writer = file.main.writer(); try renderFunctionSignature(&ctx, writer, decl); try writer.writeAll(" {"); const func: *Module.Fn = func_payload.data; const instructions = func.analysis.success.instructions; if (instructions.len > 0) { try writer.writeAll("\n"); for (instructions) |inst| { if (switch (inst.tag) { .add => try genBinOp(&ctx, file, inst.castTag(.add).?, "+"), .alloc => try genAlloc(&ctx, file, inst.castTag(.alloc).?), .arg => try genArg(&ctx), .assembly => try genAsm(&ctx, file, inst.castTag(.assembly).?), .block => try genBlock(&ctx, file, inst.castTag(.block).?), .bitcast => try genBitcast(&ctx, file, inst.castTag(.bitcast).?), .breakpoint => try genBreakpoint(file, inst.castTag(.breakpoint).?), .call => try genCall(&ctx, file, inst.castTag(.call).?), .cmp_eq => try genBinOp(&ctx, file, inst.castTag(.cmp_eq).?, "=="), .cmp_gt => try genBinOp(&ctx, file, inst.castTag(.cmp_gt).?, ">"), .cmp_gte => try genBinOp(&ctx, file, inst.castTag(.cmp_gte).?, ">="), .cmp_lt => try genBinOp(&ctx, file, inst.castTag(.cmp_lt).?, "<"), .cmp_lte => try genBinOp(&ctx, file, inst.castTag(.cmp_lte).?, "<="), .cmp_neq => try genBinOp(&ctx, file, inst.castTag(.cmp_neq).?, "!="), .dbg_stmt => try genDbgStmt(&ctx, inst.castTag(.dbg_stmt).?), .intcast => try genIntCast(&ctx, file, inst.castTag(.intcast).?), .load => try genLoad(&ctx, file, inst.castTag(.load).?), .ret => try genRet(&ctx, file, inst.castTag(.ret).?), .retvoid => try genRetVoid(file), .store => try genStore(&ctx, file, inst.castTag(.store).?), .sub => try genBinOp(&ctx, file, inst.castTag(.sub).?, "-"), .unreach => try genUnreach(file, inst.castTag(.unreach).?), else => |e| return ctx.fail(decl.src(), "TODO: C backend: implement codegen for {}", .{e}), }) |name| { try ctx.inst_map.putNoClobber(inst, name); } } } try writer.writeAll("}\n\n"); } else if (tv.val.tag() == .extern_fn) { return; // handled when referenced } else { const writer = file.constants.writer(); try writer.writeAll("static "); // TODO ask the Decl if it is const // https://github.com/ziglang/zig/issues/7582 try renderTypeAndName(&ctx, writer, tv.ty, mem.span(decl.name), .Mut); try writer.writeAll(" = "); try renderValue(&ctx, writer, tv.ty, tv.val); try writer.writeAll(";\n"); } } pub fn generateHeader( comp: *Compilation, module: *Module, header: *C.Header, decl: *Decl, ) error{ AnalysisFail, OutOfMemory }!void { switch (decl.typed_value.most_recent.typed_value.ty.zigTypeTag()) { .Fn => { var inst_map = std.AutoHashMap(*Inst, []u8).init(comp.gpa); defer inst_map.deinit(); var arena = std.heap.ArenaAllocator.init(comp.gpa); defer arena.deinit(); var ctx = Context{ .decl = decl, .arena = &arena, .inst_map = &inst_map, .target = comp.getTarget(), .header = header, .module = module, }; const writer = header.buf.writer(); renderFunctionSignature(&ctx, writer, decl) catch |err| { if (err == error.AnalysisFail) { try module.failed_decls.put(module.gpa, decl, ctx.error_msg); } return err; }; try writer.writeAll(";\n"); }, else => {}, } } const Context = struct { decl: *Decl, inst_map: *std.AutoHashMap(*Inst, []u8), arena: *std.heap.ArenaAllocator, argdex: usize = 0, unnamed_index: usize = 0, error_msg: *Compilation.ErrorMsg = undefined, target: std.Target, header: *C.Header, module: *Module, fn resolveInst(self: *Context, inst: *Inst) ![]u8 { if (inst.value()) |val| { var out = std.ArrayList(u8).init(&self.arena.allocator); try renderValue(self, out.writer(), inst.ty, val); return out.toOwnedSlice(); } return self.inst_map.get(inst).?; // Instruction does not dominate all uses! } fn name(self: *Context) ![]u8 { const val = try std.fmt.allocPrint(&self.arena.allocator, "__temp_{}", .{self.unnamed_index}); self.unnamed_index += 1; return val; } fn fail(self: *Context, src: usize, comptime format: []const u8, args: anytype) error{ AnalysisFail, OutOfMemory } { self.error_msg = try Compilation.ErrorMsg.create(self.arena.child_allocator, src, format, args); return error.AnalysisFail; } fn deinit(self: *Context) void { self.* = undefined; } }; fn genAlloc(ctx: *Context, file: *C, alloc: *Inst.NoOp) !?[]u8 { const writer = file.main.writer(); // First line: the variable used as data storage. try indent(file); const local_name = try ctx.name(); const elem_type = alloc.base.ty.elemType(); const mutability: Mutability = if (alloc.base.ty.isConstPtr()) .Const else .Mut; try renderTypeAndName(ctx, writer, elem_type, local_name, mutability); try writer.writeAll(";\n"); // Second line: a pointer to it so that we can refer to it as the allocation. // One line for the variable, one line for the pointer to the variable, which we return. try indent(file); const ptr_local_name = try ctx.name(); try renderTypeAndName(ctx, writer, alloc.base.ty, ptr_local_name, .Const); try writer.print(" = &{s};\n", .{local_name}); return ptr_local_name; } fn genArg(ctx: *Context) !?[]u8 { const name = try std.fmt.allocPrint(&ctx.arena.allocator, "arg{}", .{ctx.argdex}); ctx.argdex += 1; return name; } fn genRetVoid(file: *C) !?[]u8 { try indent(file); try file.main.writer().print("return;\n", .{}); return null; } fn genLoad(ctx: *Context, file: *C, inst: *Inst.UnOp) !?[]u8 { const operand = try ctx.resolveInst(inst.operand); const writer = file.main.writer(); try indent(file); const local_name = try ctx.name(); try renderTypeAndName(ctx, writer, inst.base.ty, local_name, .Const); try writer.print(" = *{s};\n", .{operand}); return local_name; } fn genRet(ctx: *Context, file: *C, inst: *Inst.UnOp) !?[]u8 { try indent(file); const writer = file.main.writer(); try writer.print("return {s};\n", .{try ctx.resolveInst(inst.operand)}); return null; } fn genIntCast(ctx: *Context, file: *C, inst: *Inst.UnOp) !?[]u8 { if (inst.base.isUnused()) return null; try indent(file); const writer = file.main.writer(); const name = try ctx.name(); const from = try ctx.resolveInst(inst.operand); try renderTypeAndName(ctx, writer, inst.base.ty, name, .Const); try writer.writeAll(" = ("); try renderType(ctx, writer, inst.base.ty); try writer.print("){s};\n", .{from}); return name; } fn genStore(ctx: *Context, file: *C, inst: *Inst.BinOp) !?[]u8 { // *a = b; try indent(file); const writer = file.main.writer(); const dest_ptr_name = try ctx.resolveInst(inst.lhs); const src_val_name = try ctx.resolveInst(inst.rhs); try writer.print("*{s} = {s};\n", .{ dest_ptr_name, src_val_name }); return null; } fn genBinOp(ctx: *Context, file: *C, inst: *Inst.BinOp, operator: []const u8) !?[]u8 { if (inst.base.isUnused()) return null; try indent(file); const lhs = try ctx.resolveInst(inst.lhs); const rhs = try ctx.resolveInst(inst.rhs); const writer = file.main.writer(); const name = try ctx.name(); try renderTypeAndName(ctx, writer, inst.base.ty, name, .Const); try writer.print(" = {s} {s} {s};\n", .{ lhs, operator, rhs }); return name; } fn genCall(ctx: *Context, file: *C, inst: *Inst.Call) !?[]u8 { try indent(file); const writer = file.main.writer(); const header = file.header.buf.writer(); if (inst.func.castTag(.constant)) |func_inst| { const fn_decl = if (func_inst.val.castTag(.extern_fn)) |extern_fn| extern_fn.data else if (func_inst.val.castTag(.function)) |func_payload| func_payload.data.owner_decl else unreachable; const fn_ty = fn_decl.typed_value.most_recent.typed_value.ty; const ret_ty = fn_ty.fnReturnType(); const unused_result = inst.base.isUnused(); var result_name: ?[]u8 = null; if (unused_result) { if (ret_ty.hasCodeGenBits()) { try writer.print("(void)", .{}); } } else { const local_name = try ctx.name(); try renderTypeAndName(ctx, writer, ret_ty, local_name, .Const); try writer.writeAll(" = "); result_name = local_name; } const fn_name = mem.spanZ(fn_decl.name); if (file.called.get(fn_name) == null) { try file.called.put(fn_name, {}); try renderFunctionSignature(ctx, header, fn_decl); try header.writeAll(";\n"); } try writer.print("{s}(", .{fn_name}); if (inst.args.len != 0) { for (inst.args) |arg, i| { if (i > 0) { try writer.writeAll(", "); } if (arg.value()) |val| { try renderValue(ctx, writer, arg.ty, val); } else { const val = try ctx.resolveInst(arg); try writer.print("{}", .{val}); } } } try writer.writeAll(");\n"); return result_name; } else { return ctx.fail(ctx.decl.src(), "TODO: C backend: implement function pointers", .{}); } } fn genDbgStmt(ctx: *Context, inst: *Inst.NoOp) !?[]u8 { // TODO emit #line directive here with line number and filename return null; } fn genBlock(ctx: *Context, file: *C, inst: *Inst.Block) !?[]u8 { return ctx.fail(ctx.decl.src(), "TODO: C backend: implement blocks", .{}); } fn genBitcast(ctx: *Context, file: *C, inst: *Inst.UnOp) !?[]u8 { const writer = file.main.writer(); try indent(file); const local_name = try ctx.name(); const operand = try ctx.resolveInst(inst.operand); try renderTypeAndName(ctx, writer, inst.base.ty, local_name, .Const); if (inst.base.ty.zigTypeTag() == .Pointer and inst.operand.ty.zigTypeTag() == .Pointer) { try writer.writeAll(" = ("); try renderType(ctx, writer, inst.base.ty); try writer.print("){s};\n", .{operand}); } else { try writer.writeAll(";\n"); try indent(file); try writer.print("memcpy(&{s}, &{s}, sizeof {s});\n", .{ local_name, operand, local_name }); } return local_name; } fn genBreakpoint(file: *C, inst: *Inst.NoOp) !?[]u8 { try indent(file); try file.main.writer().writeAll("zig_breakpoint();\n"); return null; } fn genUnreach(file: *C, inst: *Inst.NoOp) !?[]u8 { try indent(file); try file.main.writer().writeAll("zig_unreachable();\n"); return null; } fn genAsm(ctx: *Context, file: *C, as: *Inst.Assembly) !?[]u8 { try indent(file); const writer = file.main.writer(); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; try writer.writeAll("register "); try renderType(ctx, writer, arg.ty); try writer.print(" {}_constant __asm__(\"{}\") = ", .{ reg, reg }); // TODO merge constant handling into inst_map as well if (arg.castTag(.constant)) |c| { try renderValue(ctx, writer, arg.ty, c.val); try writer.writeAll(";\n "); } else { const gop = try ctx.inst_map.getOrPut(arg); if (!gop.found_existing) { return ctx.fail(ctx.decl.src(), "Internal error in C backend: asm argument not found in inst_map", .{}); } try writer.print("{};\n ", .{gop.entry.value}); } } else { return ctx.fail(ctx.decl.src(), "TODO non-explicit inline asm regs", .{}); } } try writer.print("__asm {} (\"{}\"", .{ if (as.is_volatile) @as([]const u8, "volatile") else "", as.asm_source }); if (as.output) |o| { return ctx.fail(ctx.decl.src(), "TODO inline asm output", .{}); } if (as.inputs.len > 0) { if (as.output == null) { try writer.writeAll(" :"); } try writer.writeAll(": "); for (as.inputs) |i, index| { if (i[0] == '{' and i[i.len - 1] == '}') { const reg = i[1 .. i.len - 1]; const arg = as.args[index]; if (index > 0) { try writer.writeAll(", "); } try writer.print("\"\"({}_constant)", .{reg}); } else { // This is blocked by the earlier test unreachable; } } } try writer.writeAll(");\n"); return null; }
src/codegen/c.zig
const kernel = @import("../../kernel.zig"); const TODO = kernel.TODO; var plic_base: u64 = 0; var plic_size: u64 = 0; const max_interrupt = 32; pub const Interrupt = struct { handler: fn () u64, pending_operations_handler: fn () void, pub fn register(interrupt: Interrupt, index: u64) void { interrupt_handlers[index] = interrupt; } }; var interrupt_handlers: [max_interrupt]Interrupt = undefined; inline fn get_priority() [*]volatile u32 { return @intToPtr([*]volatile u32, plic_base + 0); } inline fn get_pending() [*]volatile u32 { return @intToPtr([*]volatile u32, plic_base + 0x1000); } inline fn get_senable(hart_id: u64) [*]volatile u32 { return @intToPtr([*]volatile u32, plic_base + 0x2080 + hart_id * 0x1000); } inline fn get_spriority(hart_id: u64) [*]volatile u32 { return @intToPtr([*]volatile u32, plic_base + 0x201000 + hart_id * 0x1000); } inline fn get_sclaim(hart_id: u64) *volatile u32 { return @intToPtr(*volatile u32, plic_base + 0x201004 + hart_id * 0x1000); } pub fn init(hart_id: u64) void { log.debug("About to initialized interrupts", .{}); const plic_dt = kernel.arch.device_tree.find_property("soc", "reg", .exact, &[_][]const u8{"plic"}, &[_]kernel.arch.DeviceTree.SearchType{.start}) orelse @panic("unable to find PLIC in the device tree"); plic_base = kernel.arch.dt_read_int(u64, plic_dt.value); plic_size = kernel.arch.dt_read_int(u64, plic_dt.value[@sizeOf(u64)..]); kernel.assert(@src(), plic_size & (kernel.arch.page_size - 1) == 0); kernel.arch.Virtual.directMap( kernel.arch.Virtual.kernel_init_pagetable, plic_base, plic_size / kernel.arch.page_size, kernel.arch.PTE_READ | kernel.arch.PTE_WRITE, false, ); var interrupt_i: u64 = 1; while (interrupt_i <= max_interrupt) : (interrupt_i += 1) { get_priority()[interrupt_i] = 0xffff_ffff; } get_senable(hart_id)[0] = 0b11111111111; get_spriority(hart_id)[0] = 0; log.debug("PLIC initialized", .{}); } const log = kernel.log.scoped(.Interrupts_init); const ilog = kernel.log.scoped(.Interrupts_PLIC); // TODO: should this be locked? pub fn handle_external_interrupt(hart_id: u64) void { const claimed_interrupt_number = get_sclaim(hart_id).*; //ilog.debug("PLIC interrupt number: {}", .{claimed_interrupt_number}); if (claimed_interrupt_number == 0) @panic("PLIC handler is told an external interrupt has been received, but claim indicates otherwise"); const operations_to_be_handled = interrupt_handlers[claimed_interrupt_number].handler(); get_sclaim(hart_id).* = claimed_interrupt_number; if (operations_to_be_handled > 0) { interrupt_handlers[claimed_interrupt_number].pending_operations_handler(); } }
src/kernel/arch/riscv64/interrupts.zig
const std = @import("std"); const types = @import("types.zig"); const ast = std.zig.ast; pub const Encoding = enum { utf8, utf16, }; pub const DocumentPosition = struct { line: []const u8, line_index: usize, absolute_index: usize, }; pub fn documentPosition(doc: types.TextDocument, position: types.Position, encoding: Encoding) !DocumentPosition { var split_iterator = std.mem.split(doc.text, "\n"); var line_idx: i64 = 0; var line: []const u8 = ""; while (line_idx < position.line) : (line_idx += 1) { line = split_iterator.next() orelse return error.InvalidParams; } const line_start_idx = split_iterator.index.?; line = split_iterator.next() orelse return error.InvalidParams; if (encoding == .utf8) { const index = @intCast(i64, line_start_idx) + position.character; if (index < 0 or index > @intCast(i64, doc.text.len)) { return error.InvalidParams; } return DocumentPosition{ .line = line, .absolute_index = @intCast(usize, index), .line_index = @intCast(usize, position.character) }; } else { const utf8 = doc.text[line_start_idx..]; var utf8_idx: usize = 0; var utf16_idx: usize = 0; while (utf16_idx < position.character) { if (utf8_idx > utf8.len) { return error.InvalidParams; } const n = try std.unicode.utf8ByteSequenceLength(utf8[utf8_idx]); const next_utf8_idx = utf8_idx + n; const codepoint = try std.unicode.utf8Decode(utf8[utf8_idx..next_utf8_idx]); if (codepoint < 0x10000) { utf16_idx += 1; } else { utf16_idx += 2; } utf8_idx = next_utf8_idx; } return DocumentPosition{ .line = line, .absolute_index = line_start_idx + utf8_idx, .line_index = utf8_idx }; } } pub const TokenLocation = struct { line: usize, column: usize, offset: usize, pub fn add(lhs: TokenLocation, rhs: TokenLocation) TokenLocation { return .{ .line = lhs.line + rhs.line, .column = if (rhs.line == 0) lhs.column + rhs.column else rhs.column, .offset = rhs.offset, }; } }; pub fn tokenRelativeLocation(tree: ast.Tree, start_index: usize, next_token_index: usize, encoding: Encoding) !TokenLocation { const start = next_token_index; var loc = TokenLocation{ .line = 0, .column = 0, .offset = 0, }; const token_start = start; const source = tree.source[start_index..]; var i: usize = 0; while (i + start_index < token_start) { const c = source[i]; if (c == '\n') { loc.line += 1; loc.column = 0; i += 1; } else { if (encoding == .utf16) { const n = try std.unicode.utf8ByteSequenceLength(c); const codepoint = try std.unicode.utf8Decode(source[i .. i + n]); if (codepoint < 0x10000) { loc.column += 1; } else { loc.column += 2; } i += n; } else { loc.column += 1; i += 1; } } } loc.offset = i + start_index; return loc; } /// Asserts the token is comprised of valid utf8 pub fn tokenLength(tree: ast.Tree, token: ast.TokenIndex, encoding: Encoding) usize { const token_loc = tokenLocation(tree, token); if (encoding == .utf8) return token_loc.end - token_loc.start; var i: usize = token_loc.start; var utf16_len: usize = 0; while (i < token_loc.end) { const n = std.unicode.utf8ByteSequenceLength(tree.source[i]) catch unreachable; const codepoint = std.unicode.utf8Decode(tree.source[i .. i + n]) catch unreachable; if (codepoint < 0x10000) { utf16_len += 1; } else { utf16_len += 2; } i += n; } return utf16_len; } /// Token location inside source pub const Loc = struct { start: usize, end: usize, }; pub fn tokenLocation(tree: ast.Tree, token_index: ast.TokenIndex) Loc { const start = tree.tokens.items(.start)[token_index]; const tag = tree.tokens.items(.tag)[token_index]; // For some tokens, re-tokenization is needed to find the end. var tokenizer: std.zig.Tokenizer = .{ .buffer = tree.source, .index = start, .pending_invalid_token = null, }; const token = tokenizer.next(); std.debug.assert(token.tag == tag); return .{ .start = token.loc.start, .end = token.loc.end }; } pub fn documentRange(doc: types.TextDocument, encoding: Encoding) !types.Range { var line_idx: i64 = 0; var curr_line: []const u8 = doc.text; var split_iterator = std.mem.split(doc.text, "\n"); while (split_iterator.next()) |line| : (line_idx += 1) { curr_line = line; } if (encoding == .utf8) { return types.Range{ .start = .{ .line = 0, .character = 0, }, .end = .{ .line = line_idx, .character = @intCast(i64, curr_line.len), }, }; } else { var utf16_len: usize = 0; var line_utf8_idx: usize = 0; while (line_utf8_idx < curr_line.len) { const n = try std.unicode.utf8ByteSequenceLength(curr_line[line_utf8_idx]); const codepoint = try std.unicode.utf8Decode(curr_line[line_utf8_idx .. line_utf8_idx + n]); if (codepoint < 0x10000) { utf16_len += 1; } else { utf16_len += 2; } line_utf8_idx += n; } return types.Range{ .start = .{ .line = 0, .character = 0, }, .end = .{ .line = line_idx, .character = @intCast(i64, utf16_len), }, }; } } // Updated version from std that allows for failures // by removing the unreachables and returning up to that point // so that we can always provide information while the user is still typing pub fn lastToken(tree: ast.Tree, node: ast.Node.Index) ast.TokenIndex { const Node = ast.Node; const TokenIndex = ast.TokenIndex; const tags = tree.nodes.items(.tag); const datas = tree.nodes.items(.data); const main_tokens = tree.nodes.items(.main_token); const token_starts = tree.tokens.items(.start); const token_tags = tree.tokens.items(.tag); var n = node; var end_offset: TokenIndex = 0; while (true) switch (tags[n]) { .root => return @intCast(TokenIndex, tree.tokens.len - 1), .@"usingnamespace", .bool_not, .negation, .bit_not, .negation_wrap, .address_of, .@"try", .@"await", .optional_type, .@"resume", .@"nosuspend", .@"comptime", => n = datas[n].lhs, .test_decl, .@"errdefer", .@"defer", .@"catch", .equal_equal, .bang_equal, .less_than, .greater_than, .less_or_equal, .greater_or_equal, .assign_mul, .assign_div, .assign_mod, .assign_add, .assign_sub, .assign_bit_shift_left, .assign_bit_shift_right, .assign_bit_and, .assign_bit_xor, .assign_bit_or, .assign_mul_wrap, .assign_add_wrap, .assign_sub_wrap, .assign, .merge_error_sets, .mul, .div, .mod, .array_mult, .mul_wrap, .add, .sub, .array_cat, .add_wrap, .sub_wrap, .bit_shift_left, .bit_shift_right, .bit_and, .bit_xor, .bit_or, .@"orelse", .bool_and, .bool_or, .anyframe_type, .error_union, .if_simple, .while_simple, .for_simple, .fn_proto_simple, .fn_proto_multi, .ptr_type_aligned, .ptr_type_sentinel, .ptr_type, .ptr_type_bit_range, .array_type, .switch_case_one, .switch_case, .switch_range, => n = datas[n].rhs, .field_access, .unwrap_optional, .grouped_expression, .multiline_string_literal, .error_set_decl, .asm_simple, .asm_output, .asm_input, .error_value, => return datas[n].rhs + end_offset, .@"anytype", .anyframe_literal, .char_literal, .integer_literal, .float_literal, .false_literal, .true_literal, .null_literal, .undefined_literal, .unreachable_literal, .identifier, .deref, .enum_literal, .string_literal, => return main_tokens[n] + end_offset, .@"return" => if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; }, .call, .async_call => { end_offset += 1; // for the rparen const params = tree.extraData(datas[n].rhs, Node.SubRange); if (params.end - params.start == 0) { return main_tokens[n] + end_offset; } n = tree.extra_data[params.end - 1]; // last parameter }, .tagged_union_enum_tag => { const members = tree.extraData(datas[n].rhs, Node.SubRange); if (members.end - members.start == 0) { end_offset += 4; // for the rparen + rparen + lbrace + rbrace n = datas[n].lhs; } else { end_offset += 1; // for the rbrace n = tree.extra_data[members.end - 1]; // last parameter } }, .call_comma, .async_call_comma, .tagged_union_enum_tag_trailing, => { end_offset += 2; // for the comma/semicolon + rparen/rbrace const params = tree.extraData(datas[n].rhs, Node.SubRange); std.debug.assert(params.end > params.start); n = tree.extra_data[params.end - 1]; // last parameter }, .@"switch" => { const cases = tree.extraData(datas[n].rhs, Node.SubRange); if (cases.end - cases.start == 0) { end_offset += 3; // rparen, lbrace, rbrace n = datas[n].lhs; // condition expression } else { end_offset += 1; // for the rbrace n = tree.extra_data[cases.end - 1]; // last case } }, .container_decl_arg => { const members = tree.extraData(datas[n].rhs, Node.SubRange); if (members.end - members.start == 0) { end_offset += 3; // for the rparen + lbrace + rbrace n = datas[n].lhs; } else { end_offset += 1; // for the rbrace n = tree.extra_data[members.end - 1]; // last parameter } }, .@"asm" => { const extra = tree.extraData(datas[n].rhs, Node.Asm); return extra.rparen + end_offset; }, .array_init, .struct_init, => { const elements = tree.extraData(datas[n].rhs, Node.SubRange); std.debug.assert(elements.end - elements.start > 0); end_offset += 1; // for the rbrace n = tree.extra_data[elements.end - 1]; // last element }, .array_init_comma, .struct_init_comma, .container_decl_arg_trailing, .switch_comma, => { const members = tree.extraData(datas[n].rhs, Node.SubRange); std.debug.assert(members.end - members.start > 0); end_offset += 2; // for the comma + rbrace n = tree.extra_data[members.end - 1]; // last parameter }, .array_init_dot, .struct_init_dot, .block, .container_decl, .tagged_union, .builtin_call, => { std.debug.assert(datas[n].rhs - datas[n].lhs > 0); end_offset += 1; // for the rbrace n = tree.extra_data[datas[n].rhs - 1]; // last statement }, .array_init_dot_comma, .struct_init_dot_comma, .block_semicolon, .container_decl_trailing, .tagged_union_trailing, .builtin_call_comma, => { std.debug.assert(datas[n].rhs - datas[n].lhs > 0); end_offset += 2; // for the comma/semicolon + rbrace/rparen n = tree.extra_data[datas[n].rhs - 1]; // last member }, .call_one, .async_call_one, .array_access, => { end_offset += 1; // for the rparen/rbracket if (datas[n].rhs == 0) { return main_tokens[n] + end_offset; } n = datas[n].rhs; }, .array_init_dot_two, .block_two, .builtin_call_two, .struct_init_dot_two, .container_decl_two, .tagged_union_two, => { if (datas[n].rhs != 0) { end_offset += 1; // for the rparen/rbrace n = datas[n].rhs; } else if (datas[n].lhs != 0) { end_offset += 1; // for the rparen/rbrace n = datas[n].lhs; } else { switch (tags[n]) { .array_init_dot_two, .block_two, .struct_init_dot_two, => end_offset += 1, // rbrace .builtin_call_two => end_offset += 2, // lparen/lbrace + rparen/rbrace .container_decl_two => { var i: u32 = 2; // lbrace + rbrace while (token_tags[main_tokens[n] + i] == .container_doc_comment) i += 1; end_offset += i; }, .tagged_union_two => { var i: u32 = 5; // (enum) {} while (token_tags[main_tokens[n] + i] == .container_doc_comment) i += 1; end_offset += i; }, else => unreachable, } return main_tokens[n] + end_offset; } }, .array_init_dot_two_comma, .builtin_call_two_comma, .block_two_semicolon, .struct_init_dot_two_comma, .container_decl_two_trailing, .tagged_union_two_trailing, => { end_offset += 2; // for the comma/semicolon + rbrace/rparen if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; // returns { } } }, .simple_var_decl => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } }, .aligned_var_decl => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { end_offset += 1; // for the rparen n = datas[n].lhs; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } }, .global_var_decl => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else { const extra = tree.extraData(datas[n].lhs, Node.GlobalVarDecl); if (extra.section_node != 0) { end_offset += 1; // for the rparen n = extra.section_node; } else if (extra.align_node != 0) { end_offset += 1; // for the rparen n = extra.align_node; } else if (extra.type_node != 0) { n = extra.type_node; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } } }, .local_var_decl => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else { const extra = tree.extraData(datas[n].lhs, Node.LocalVarDecl); if (extra.align_node != 0) { end_offset += 1; // for the rparen n = extra.align_node; } else if (extra.type_node != 0) { n = extra.type_node; } else { end_offset += 1; // from mut token to name return main_tokens[n] + end_offset; } } }, .container_field_init => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .container_field_align => { if (datas[n].rhs != 0) { end_offset += 1; // for the rparen n = datas[n].rhs; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .container_field => { const extra = tree.extraData(datas[n].rhs, Node.ContainerField); if (extra.value_expr != 0) { n = extra.value_expr; } else if (extra.align_expr != 0) { end_offset += 1; // for the rparen n = extra.align_expr; } else if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .array_init_one, .struct_init_one, => { end_offset += 1; // rbrace if (datas[n].rhs == 0) { return main_tokens[n] + end_offset; } else { n = datas[n].rhs; } }, .slice_open, .call_one_comma, .async_call_one_comma, .array_init_one_comma, .struct_init_one_comma, => { end_offset += 2; // ellipsis2 + rbracket, or comma + rparen n = datas[n].rhs; std.debug.assert(n != 0); }, .slice => { const extra = tree.extraData(datas[n].rhs, Node.Slice); std.debug.assert(extra.end != 0); // should have used slice_open end_offset += 1; // rbracket n = extra.end; }, .slice_sentinel => { const extra = tree.extraData(datas[n].rhs, Node.SliceSentinel); std.debug.assert(extra.sentinel != 0); // should have used slice end_offset += 1; // rbracket n = extra.sentinel; }, .@"continue" => { if (datas[n].lhs != 0) { return datas[n].lhs + end_offset; } else { return main_tokens[n] + end_offset; } }, .@"break" => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else if (datas[n].lhs != 0) { return datas[n].lhs + end_offset; } else { return main_tokens[n] + end_offset; } }, .fn_decl => { if (datas[n].rhs != 0) { n = datas[n].rhs; } else { n = datas[n].lhs; } }, .fn_proto_one => { const extra = tree.extraData(datas[n].lhs, Node.FnProtoOne); // linksection, callconv, align can appear in any order, so we // find the last one here. var max_node: Node.Index = datas[n].rhs; var max_start = token_starts[main_tokens[max_node]]; var max_offset: TokenIndex = 0; if (extra.align_expr != 0) { const start = token_starts[main_tokens[extra.align_expr]]; if (start > max_start) { max_node = extra.align_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.section_expr != 0) { const start = token_starts[main_tokens[extra.section_expr]]; if (start > max_start) { max_node = extra.section_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.callconv_expr != 0) { const start = token_starts[main_tokens[extra.callconv_expr]]; if (start > max_start) { max_node = extra.callconv_expr; max_start = start; max_offset = 1; // for the rparen } } n = max_node; end_offset += max_offset; }, .fn_proto => { const extra = tree.extraData(datas[n].lhs, Node.FnProto); // linksection, callconv, align can appear in any order, so we // find the last one here. var max_node: Node.Index = datas[n].rhs; var max_start = token_starts[main_tokens[max_node]]; var max_offset: TokenIndex = 0; if (extra.align_expr != 0) { const start = token_starts[main_tokens[extra.align_expr]]; if (start > max_start) { max_node = extra.align_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.section_expr != 0) { const start = token_starts[main_tokens[extra.section_expr]]; if (start > max_start) { max_node = extra.section_expr; max_start = start; max_offset = 1; // for the rparen } } if (extra.callconv_expr != 0) { const start = token_starts[main_tokens[extra.callconv_expr]]; if (start > max_start) { max_node = extra.callconv_expr; max_start = start; max_offset = 1; // for the rparen } } n = max_node; end_offset += max_offset; }, .while_cont => { const extra = tree.extraData(datas[n].rhs, Node.WhileCont); std.debug.assert(extra.then_expr != 0); n = extra.then_expr; }, .@"while" => { const extra = tree.extraData(datas[n].rhs, Node.While); std.debug.assert(extra.else_expr != 0); n = extra.else_expr; }, .@"if", .@"for" => { const extra = tree.extraData(datas[n].rhs, Node.If); std.debug.assert(extra.else_expr != 0); n = extra.else_expr; }, .@"suspend" => { if (datas[n].lhs != 0) { n = datas[n].lhs; } else { return main_tokens[n] + end_offset; } }, .array_type_sentinel => { const extra = tree.extraData(datas[n].rhs, Node.ArrayTypeSentinel); n = extra.elem_type; }, }; }
src/offsets.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; const with_dissassemble = false; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const Computer = tools.IntCode_Computer; const Tile = struct { color: u1, visited: u1, fn to_char(m: @This()) u8 { return if (m.color != 0) '*' else ' '; } }; const Map = tools.Map(Tile, 2500, 1000, true); const Vec2 = tools.Vec2; fn run_part(initial_color: u1, computer: *Computer, boot_image: []const Computer.Data, map: *Map) void { const dirs = [_]Vec2{ .{ .x = 0, .y = -1 }, .{ .x = 1, .y = 0 }, .{ .x = 0, .y = 1 }, .{ .x = -1, .y = 0 } }; var pos = Vec2{ .x = 0, .y = 0 }; var dir: u2 = 0; var cycle = enum { paint, turn, }.paint; map.bbox = tools.BBox.empty; map.set(pos, Tile{ .color = initial_color, .visited = 1 }); { computer.boot(boot_image); trace("starting {}\n", .{computer.name}); _ = async computer.run(); } { const c = computer; while (!c.is_halted()) { if (c.io_mode == .input) { c.io_port = if (map.get(pos)) |m| m.color else 0; trace("wrting input to {} = {}\n", .{ c.name, c.io_port }); } else if (c.io_mode == .output) { // try stdout.print("{} outputs {}\n", .{ c.name, c.io_port }); if (cycle == .paint) { map.set(pos, Tile{ .color = @intCast(u1, c.io_port), .visited = 1 }); cycle = .turn; } else { if (c.io_port == 0) { dir -%= 1; } else { dir +%= 1; } pos.x += dirs[dir].x; pos.y += dirs[dir].y; cycle = .paint; } } trace("resuming {}\n", .{c.name}); resume c.io_runframe; } } } pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const int_count = blk: { var int_count: usize = 0; var it = std.mem.split(u8, input, ","); while (it.next()) |_| int_count += 1; break :blk int_count; }; const boot_image = try allocator.alloc(Computer.Data, int_count); defer allocator.free(boot_image); { var it = std.mem.split(u8, input, ","); var i: usize = 0; while (it.next()) |n_text| : (i += 1) { const trimmed = std.mem.trim(u8, n_text, " \n\r\t"); boot_image[i] = try std.fmt.parseInt(Computer.Data, trimmed, 10); } } if (with_dissassemble) Computer.disassemble(boot_image); var computer = Computer{ .name = "Painter", .memory = try allocator.alloc(Computer.Data, 10000), }; defer allocator.free(computer.memory); var map = Map{ .default_tile = Tile{ .color = 0, .visited = 0 } }; // part1 run_part(0, &computer, boot_image, &map); const totalpainted = ans: { var c: usize = 0; for (map.map) |m| { c += m.visited; } break :ans c; }; // part2 run_part(1, &computer, boot_image, &map); var storage: [10000]u8 = undefined; const view = map.printToBuf(null, null, Tile.to_char, &storage); return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{totalpainted}), try std.fmt.allocPrint(allocator, "{s}", .{view}), }; } pub const main = tools.defaultMain("2019/day11.txt", run);
2019/day11.zig
const std = @import("std"); const io = std.io; const crypto = std.crypto; const stdin = io.getStdIn().reader(); const stdout = io.getStdOut().writer(); const print = stdout.print; // TODO: figure out how to not need this everywhere const maxConsoleInputLength: u8 = 64; const User = struct { username: [maxConsoleInputLength]u8, salt: []const u8, password_hashed: []const u8, }; const Command = struct { name: []const u8, description: []const u8, }; // TODO: find out how to get passed args // TODO: if args work, add auto-loop mode bool const skipStartup = false; const applicationAsciiArtEnabled = true; const applicationAsciiArtRaw = \\ _____ __ __ _ | \\ / __(_)_ _ ___ / /__ / / ___ ___ _(_)__ | {s} \\ _\ \/ / ' \/ _ \/ / -_) / /_/ _ \/ _ `/ / _ \ | {s} \\/___/_/_/_/_/ .__/_/\__/ /____|___/\_, /_/_//_/ | {s} \\ /_/ /___/ | ; const applicationAsciiArt = std.fmt.comptimePrint(applicationAsciiArtRaw, .{ applicationName, applicationDescription, applicationVersion }); const applicationName = "Simple Login, by eilume"; const applicationVersion = "Status: In-progress"; const applicationDescription = "A simple and very fake console login system."; const commandList = [_]Command{ Command{ .name = "newuser", .description = "Creates a new user", }, Command{ .name = "help", .description = "Displays list of commands", }, Command{ .name = "exit", .description = "Quits the application", }, }; fn stringTrim(string: []const u8) []const u8 { var lastZeroIndex: usize = string.len - 1; for (string) |character, index| { if (character == 0 or character == 32) { lastZeroIndex = index; } } return string[0..lastZeroIndex]; } // TODO: support arbitrary array lengths fn stringPad(string: []const u8, output: *[8]u8) void { for (string) |character, index| { output[index] = character; } var i: usize = string.len; while (i < output.len) { // TODO: this doesn't work correctly // output[i] = 0x20; // Space in utf-8 output[i] = ' '; i += 1; } } fn getConsoleInput(buffer: *[maxConsoleInputLength]u8) !void { try getConsoleInputWithMessage(&buffer.*, ""); } fn getConsoleInputWithMessage(buffer: *[maxConsoleInputLength]u8, text: []const u8) !void { buffer.* = undefined; try print("{s}", .{text}); const amount = try stdin.read(&buffer.*); if (amount == buffer.len) { std.log.err("input went over max length, {}, so input will be trimmed", .{maxConsoleInputLength}); } buffer.*[amount - 1] = 0; } fn usernameIsValid(username: *[maxConsoleInputLength]u8) !bool { try print("\nDEBUG: testing if username: '{s}' is valid and not taken...\n\n", .{username.*}); return true; } fn registerUser(username: *[maxConsoleInputLength]u8, password: *[maxConsoleInputLength]u8) !bool { var salt: [32]u8 = undefined; crypto.random.bytes(&salt); var saltedPassword = [_]u8{undefined} ** (maxConsoleInputLength + 32); _ = try std.fmt.bufPrint(&saltedPassword, "{s}{s}", .{ salt, password.* }); var password_hash: [64]u8 = undefined; crypto.hash.sha2.Sha512.hash(saltedPassword[0..], &password_hash, crypto.hash.sha2.Sha512.Options{}); var user: User = User{ .username = username.*, .salt = salt[0..], .password_hashed = password_hash[0..] }; try print("\n-=: Created user :=-\n\n", .{}); try print("username: {s}\n", .{user.username}); try print("salt: {s}\n", .{user.salt}); try print("password_hash: {}\n", .{std.fmt.fmtSliceHexLower(user.password_hashed)}); return true; } fn createUser() !void { try print("\n-=: Create User :=-\n", .{}); var createUserLoop: bool = true; var username: [maxConsoleInputLength]u8 = undefined; var password: [maxConsoleInputLength]u8 = undefined; var password_confirm: [maxConsoleInputLength]u8 = undefined; while (createUserLoop) { try print("\n", .{}); try getConsoleInputWithMessage(&username, "Username: "); if (try usernameIsValid(&username)) { try getConsoleInputWithMessage(&password, "Password: "); try getConsoleInputWithMessage(&password_confirm, "Password (confirm): "); var passwordEqual: bool = std.mem.eql(u8, password[0..], password_confirm[0..]); if (passwordEqual) { if (try registerUser(&username, &password)) { createUserLoop = false; } } if (!passwordEqual) { try print("\nFailed: Passwords not equal\n", .{}); } } else { try print("\nFailed: Username is not valid\n", .{}); } } } fn startup() !void { if (applicationAsciiArtEnabled) { try print("\n{s}\n", .{applicationAsciiArt}); } else { try print("\n{s}\n{s}\n{s}\n", .{ applicationName, applicationDescription, applicationVersion }); } try print("\nType 'help' for list of commands\n", .{}); } fn help() !void { try print("\nList of commands:\n\n", .{}); var namePadded: [8]u8 = undefined; for (commandList) |command| { stringPad(command.name, &namePadded); try print("{s} | {s}\n", .{ namePadded, command.description }); } } pub fn main() anyerror!void { var running: bool = true; var input_buffer: [maxConsoleInputLength]u8 = undefined; if (!skipStartup) try startup(); while (running) { try print("\n", .{}); try getConsoleInputWithMessage(&input_buffer, "Enter Command: "); if (std.mem.eql(u8, stringTrim(input_buffer[0..]), "newuser")) { try createUser(); } else if (std.mem.eql(u8, stringTrim(input_buffer[0..]), "help") or std.mem.eql(u8, stringTrim(input_buffer[0..]), "?")) { try help(); } else if (std.mem.eql(u8, stringTrim(input_buffer[0..]), "exit") or std.mem.eql(u8, stringTrim(input_buffer[0..]), "quit")) { return; } else { try print("Unknown command '{s}'\n", .{input_buffer[0..]}); } } }
src/main.zig
const std = @import("std"); const json = std.json; const testing = std.testing; const assert = std.debug.assert; const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayList = std.ArrayList; const StringArrayHashMap = std.StringArrayHashMap; const Writer = std.io.Writer; const logger = std.log.scoped(.nestedtext); // ----------------------------------------------------------------------------- // Helpers // ----------------------------------------------------------------------------- /// Return a slice corresponding to the first line of the given input, /// including the terminating newline character(s). If there is no terminating /// newline the entire input slice is returned. Returns null if the input is /// empty. fn readline(input: []const u8) ?[]const u8 { if (input.len == 0) return null; var idx: usize = 0; while (idx < input.len) : (idx += 1) { // Handle '\n' if (input[idx] == '\n') return input[0 .. idx + 1]; // Handle '\r' if (input[idx] == '\r') { // Handle '\r\n' if (input.len > idx + 1 and input[idx + 1] == '\n') return input[0 .. idx + 2] else return input[0 .. idx + 1]; } } return input; } // ----------------------------------------------------------------------------- // Types // ----------------------------------------------------------------------------- pub const ParseError = error{ RootLevelIndent, InvalidIndentation, TabIndentation, InvalidItem, MissingObjectValue, UnrecognisedLine, DuplicateKey, }; pub const StringifyOptions = struct { indent: usize = 2, }; pub const ParseOptions = struct { /// Behaviour when a duplicate field is encountered. duplicate_field_behavior: enum { UseFirst, UseLast, Error, } = .Error, /// Whether to copy strings or return existing slices. copy_strings: bool = true, }; pub const ValueTree = struct { arena: ArenaAllocator, root: ?Value, pub fn deinit(self: @This()) void { self.arena.deinit(); } pub fn stringify( self: @This(), options: StringifyOptions, out_stream: anytype, ) @TypeOf(out_stream).Error!void { if (self.root) |value| try value.stringify(options, out_stream); } pub fn toJson(self: @This(), allocator: *Allocator) !json.ValueTree { if (self.root) |value| return value.toJson(allocator) else return json.ValueTree{ .arena = ArenaAllocator.init(allocator), .root = json.Value.Null, }; } }; pub const Map = StringArrayHashMap(Value); pub const Array = ArrayList(Value); pub const Value = union(enum) { String: []const u8, List: Array, Object: Map, pub fn stringify( value: @This(), options: StringifyOptions, out_stream: anytype, ) @TypeOf(out_stream).Error!void { try value.stringifyInternal(options, out_stream, 0, false, false); } pub fn toJson(value: @This(), allocator: *Allocator) !json.ValueTree { var json_tree: json.ValueTree = undefined; json_tree.arena = ArenaAllocator.init(allocator); json_tree.root = try value.toJsonValue(&json_tree.arena.allocator); return json_tree; } fn toJsonValue(value: @This(), allocator: *Allocator) anyerror!json.Value { switch (value) { .String => |inner| return json.Value{ .String = inner }, .List => |inner| { var json_array = json.Array.init(allocator); for (inner.items) |elem| { const json_elem = try elem.toJsonValue(allocator); try json_array.append(json_elem); } return json.Value{ .Array = json_array }; }, .Object => |inner| { var json_map = json.ObjectMap.init(allocator); var iter = inner.iterator(); while (iter.next()) |elem| { const json_value = try elem.value_ptr.*.toJsonValue(allocator); try json_map.put(elem.key_ptr.*, json_value); } return json.Value{ .Object = json_map }; }, } } fn stringifyInternal( value: @This(), options: StringifyOptions, out_stream: anytype, indent: usize, nested: bool, force_multiline_string: bool, ) @TypeOf(out_stream).Error!void { switch (value) { .String => |string| { if (nested and std.mem.indexOfAny(u8, string, "\r\n") == null and !force_multiline_string) { // Single-line string. if (string.len > 0) try out_stream.writeByte(' '); try out_stream.writeAll(string); } else else_blk: { // Multi-line string. if (nested) try out_stream.writeByte('\n'); if (string.len == 0) { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeByte('>'); break :else_blk; } var idx: usize = 0; while (readline(string[idx..])) |line| { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeByte('>'); if (line[0] == '\n' or line[0] == '\r') try out_stream.print("{s}", .{line}) else if (line.len > 0) try out_stream.print(" {s}", .{line}); idx += line.len; } const last_char = string[string.len - 1]; if (last_char == '\n' or last_char == '\r') { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeByte('>'); } } }, .List => |list| { if (nested) try out_stream.writeByte('\n'); if (list.items.len == 0) { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeAll("[]"); return; } for (list.items) |*elem| { if (elem != &list.items[0]) try out_stream.writeByte('\n'); try out_stream.writeByteNTimes(' ', indent); try out_stream.writeByte('-'); try elem.stringifyInternal( options, out_stream, indent + options.indent, true, false, ); } }, .Object => |object| { if (nested) try out_stream.writeByte('\n'); if (object.count() == 0) { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeAll("{}"); return; } var iter = object.iterator(); var first_elem = true; while (iter.next()) |elem| { var force_multiline_string_next = false; if (!first_elem) try out_stream.writeByte('\n'); const key = elem.key_ptr.*; if (key.len > 0 and // No newlines std.mem.indexOfAny(u8, key, "\r\n") == null and // No leading whitespace or other special characters std.mem.indexOfAny(u8, key[0..1], "#[{ \t") == null and // No trailing whitespace std.mem.indexOfAny(u8, key[key.len - 1 ..], " \t") == null and // No leading special characters followed by a space !(std.mem.indexOfAny(u8, key[0..1], ">-") != null and (key.len == 1 or key[1] == ' ')) and // No internal colons followed by a space std.mem.indexOf(u8, key, ": ") == null) { // Simple key. try out_stream.writeByteNTimes(' ', indent); try out_stream.print("{s}:", .{key}); } else else_blk: { // Multi-line key. force_multiline_string_next = true; if (key.len == 0) { try out_stream.writeByte(':'); break :else_blk; } var idx: usize = 0; while (readline(key[idx..])) |line| { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeByte(':'); if (line.len > 0) try out_stream.print(" {s}", .{line}); idx += line.len; } const last_char = key[key.len - 1]; if (last_char == '\n' or last_char == '\r') { try out_stream.writeByteNTimes(' ', indent); try out_stream.writeByte(':'); } } try elem.value_ptr.*.stringifyInternal( options, out_stream, indent + options.indent, true, force_multiline_string_next, ); first_elem = false; } }, } } }; /// Memory owned by caller on success - free with 'ValueTree.deinit()'. pub fn fromJson(allocator: *Allocator, json_value: json.Value) !ValueTree { var tree: ValueTree = undefined; tree.arena = ArenaAllocator.init(allocator); errdefer tree.deinit(); tree.root = try fromJsonInternal(&tree.arena.allocator, json_value); return tree; } fn fromJsonInternal(allocator: *Allocator, json_value: json.Value) anyerror!Value { switch (json_value) { .Null => return Value{ .String = "null" }, .Bool => |inner| return Value{ .String = if (inner) "true" else "false" }, .Integer, .Float, .String, .NumberString, => { var buffer = ArrayList(u8).init(allocator); errdefer buffer.deinit(); switch (json_value) { .Integer => |inner| { try buffer.writer().print("{d}", .{inner}); }, .Float => |inner| { try buffer.writer().print("{e}", .{inner}); }, .String, .NumberString => |inner| { try buffer.writer().print("{s}", .{inner}); }, else => unreachable, } return Value{ .String = buffer.items }; }, .Array => |inner| { var array = Array.init(allocator); for (inner.items) |elem| { try array.append(try fromJsonInternal(allocator, elem)); } return Value{ .List = array }; }, .Object => |inner| { var map = Map.init(allocator); var iter = inner.iterator(); while (iter.next()) |elem| { try map.put( try allocator.dupe(u8, elem.key_ptr.*), try fromJsonInternal(allocator, elem.value_ptr.*), ); } return Value{ .Object = map }; }, } } /// Convert an arbitrary type to Nestedtext. /// Memory owned by the caller, can be freed with 'ValueTree.deinit()'.' pub fn fromArbitraryType(allocator: *Allocator, value: anytype) !ValueTree { var tree: ValueTree = undefined; tree.arena = ArenaAllocator.init(allocator); errdefer tree.deinit(); tree.root = try fromArbitraryTypeInternal(&tree.arena.allocator, value); return tree; } fn fromArbitraryTypeInternal(allocator: *Allocator, value: anytype) anyerror!Value { const T = @TypeOf(value); switch (@typeInfo(T)) { .Null, .Void => return Value{ .String = "null" }, .Bool => return Value{ .String = if (value) "true" else "false" }, .Int, .ComptimeInt, .Float, .ComptimeFloat => { return Value{ .String = try std.fmt.allocPrint(allocator, "{d}", .{value}) }; }, .Optional => { if (value) |payload| { return fromArbitraryTypeInternal(allocator, payload); } else { return fromArbitraryTypeInternal(allocator, null); } }, .Enum, .EnumLiteral => return Value{ .String = @tagName(value) }, .ErrorSet => return Value{ .String = @errorName(value) }, .Union => |union_info| { // TODO: Could be simplified if // https://github.com/ziglang/zig/issues/9271 is accepted. if (union_info.tag_type) |UnionTagType| { inline for (union_info.fields) |u_field| { if (value == @field(UnionTagType, u_field.name)) { return fromArbitraryTypeInternal(allocator, @field(value, u_field.name)); } } } else { @compileError("Unable to stringify untagged union '" ++ @typeName(T) ++ "'"); } }, .Struct => |struct_info| { var map = Map.init(allocator); errdefer map.deinit(); inline for (struct_info.fields) |Field| { try map.put( Field.name, try fromArbitraryTypeInternal(allocator, @field(value, Field.name)), ); } return Value{ .Object = map }; }, .Array => { // Convert to a slice (must be done explicitly since there's no // type signature it can be implicitly cast to match, so by default // you get a single-element pointer). const Slice = []const std.meta.Elem(@TypeOf(&value)); return fromArbitraryTypeInternal(allocator, @as(Slice, &value)); }, .Vector => |vec_info| { const array: [vec_info.len]vec_info.child = value; return fromArbitraryTypeInternal(allocator, &array); }, .Pointer => |ptr_info| switch (ptr_info.size) { .One => return fromArbitraryTypeInternal(allocator, value.*), .Slice => { if (ptr_info.child == u8) { // Always treating this as a string - may want the option to // treat as an array and handle escapes (see // std.json.StringifyOptions). return Value{ .String = try allocator.dupe(u8, value) }; } else { var array = Array.init(allocator); errdefer array.deinit(); for (value) |x| { try array.append(try fromArbitraryTypeInternal(allocator, x)); } return Value{ .List = array }; } }, else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"), }, else => @compileError("Unable to stringify type '" ++ @typeName(T) ++ "'"), } unreachable; } // ----------------------------------------------------------------------------- // Parsing logic // ----------------------------------------------------------------------------- pub const Parser = struct { allocator: *Allocator, options: ParseOptions, /// If non-null, this struct is filled in by each call to parse() or parseTyped(). diags: ?*Diags = null, const Self = @This(); pub const Diags = union(enum) { Empty, ParseError: struct { lineno: usize, message: []const u8 }, }; const LineType = union(enum) { Blank, Comment, String: struct { value: []const u8 }, ListItem: struct { value: ?[]const u8 }, ObjectItem: struct { key: []const u8, value: ?[]const u8 }, ObjectKey: struct { value: []const u8 }, InlineContainer: struct { value: []const u8 }, Unrecognised, InvalidTabIndent, pub fn isObject(self: @This()) bool { return switch (self) { .ObjectItem, .ObjectKey => true, else => false, }; } }; const Line = struct { text: []const u8, lineno: usize, depth: usize, kind: LineType, }; const LinesIter = struct { text: []const u8, idx: usize = 0, next_line: ?Line = null, pub fn init(text: []const u8) LinesIter { var self = LinesIter{ .text = text }; self.advanceToNextContentLine(); return self; } pub fn next(self: *LinesIter) ?Line { const line = self.next_line; self.advanceToNextContentLine(); return line; } pub fn peekNext(self: LinesIter) ?Line { return self.next_line; } fn advanceToNextContentLine(self: *LinesIter) void { while (readline(self.text[self.idx..])) |full_line| { const lineno = if (self.next_line) |line| line.lineno else 0; const line = parseLine(full_line, lineno + 1); self.next_line = line; self.idx += full_line.len; switch (line.kind) { .Blank, .Comment => {}, // continue else => return, } } self.next_line = null; } fn parseLine(full_line: []const u8, lineno: usize) Line { const text = std.mem.trimRight(u8, full_line, &[_]u8{ '\n', '\r' }); var kind: LineType = undefined; // Trim spaces and tabs separately to check tabs are not used in // indentation of non-ignored lines. const stripped = std.mem.trimLeft(u8, text, " "); const tab_stripped = std.mem.trimLeft(u8, text, " \t"); const depth = text.len - stripped.len; if (tab_stripped.len == 0) { kind = .Blank; } else if (tab_stripped[0] == '#') { kind = .Comment; } else if (parseString(tab_stripped)) |index| { kind = if (tab_stripped.len < stripped.len) .InvalidTabIndent else .{ .String = .{ .value = full_line[text.len - stripped.len + index ..], }, }; } else if (parseList(tab_stripped)) |value| { kind = if (tab_stripped.len < stripped.len) .InvalidTabIndent else .{ .ListItem = .{ .value = if (value.len > 0) value else null, }, }; } else if (parseInlineContainer(tab_stripped)) { kind = if (tab_stripped.len < stripped.len) .InvalidTabIndent else .{ .InlineContainer = .{ .value = std.mem.trimRight(u8, stripped, " \t"), }, }; } else if (parseObjectKey(tab_stripped)) |index| { // Behaves just like string line. kind = if (tab_stripped.len < stripped.len) .InvalidTabIndent else .{ .ObjectKey = .{ .value = full_line[text.len - stripped.len + index ..], }, }; } else if (parseObject(tab_stripped)) |result| { kind = if (tab_stripped.len < stripped.len) .InvalidTabIndent else .{ .ObjectItem = .{ .key = result[0].?, // May be null if the value is on the following line(s). .value = result[1], }, }; } else { kind = .Unrecognised; } return .{ .text = text, .lineno = lineno, .depth = depth, .kind = kind }; } fn parseString(text: []const u8) ?usize { assert(text.len > 0); if (text[0] != '>') return null; if (text.len == 1) return 1; if (text[1] == ' ') return 2; return null; } fn parseList(text: []const u8) ?[]const u8 { assert(text.len > 0); if (text[0] != '-') return null; if (text.len == 1) return ""; if (text[1] == ' ') return text[2..]; return null; } fn parseObjectKey(text: []const u8) ?usize { // Behaves just like string line. assert(text.len > 0); if (text[0] != ':') return null; if (text.len == 1) return 1; if (text[1] == ' ') return 2; return null; } fn parseObject(text: []const u8) ?[2]?[]const u8 { for (text) |char, i| { if (char == ':') { if (text.len > i + 1 and text[i + 1] != ' ') continue; const key = std.mem.trim(u8, text[0..i], " \t"); const value = if (text.len > i + 2) text[i + 2 ..] else null; return [_]?[]const u8{ key, value }; } } return null; } fn parseInlineContainer(text: []const u8) bool { assert(text.len > 0); return (text[0] == '[' or text[0] == '{'); } }; const CharIter = struct { text: []const u8, idx: usize = 0, pub fn next(self: *@This()) ?u8 { if (self.idx >= self.text.len) return null; const char = self.text[self.idx]; self.idx += 1; return char; } }; pub fn init(allocator: *Allocator, options: ParseOptions) Self { return .{ .allocator = allocator, .options = options, }; } /// Parse into a tree of 'Value's. /// Memory owned by caller on success - free with 'ValueTree.deinit()'. pub fn parse(p: Self, input: []const u8) !ValueTree { if (p.diags) |diags| diags.* = Diags.Empty; var tree: ValueTree = undefined; tree.arena = ArenaAllocator.init(p.allocator); errdefer tree.deinit(); var lines = LinesIter.init(input); tree.root = if (lines.peekNext()) |first_line| blk: { if (first_line.depth > 0) { p.maybeStoreDiags( first_line.lineno, "Unexpected indentation on first content line", ); return ParseError.RootLevelIndent; } // Recursively parse break :blk try p.readValue(&tree.arena.allocator, &lines); } else null; return tree; } /// Parse into a given type. /// Memory owned by caller on success - free with 'Parser.parseTypedFree()'. pub fn parseTyped(p: Self, comptime T: type, input: []const u8) !T { // Note that although parsing into a given type may not need an allocator // (since we use stack memory for non-pointer types), the current // implementation just parses normally for simplicity, and this always // requires an allocator (for non-trivial cases). Hence the allocator // field of the struct is non-optional. var tree = try p.parse(input); defer tree.deinit(); if (tree.root) |root| { return p.parseTypedInternal(T, root); } else { // TODO return error.NotYetHandlingEmptyFile; } } /// Releases resources created by 'parseTyped()'. pub fn parseTypedFree(p: Self, value: anytype) void { const T = @TypeOf(value); p.parseTypedFreeInternal(T, value); } fn parseTypedInternal(p: Self, comptime T: type, value: Value) !T { // TODO: Store diags on errors. switch (@typeInfo(T)) { .Bool => { switch (value) { .String => |str| { if (std.mem.eql(u8, str, "true") or std.mem.eql(u8, str, "True") or std.mem.eql(u8, str, "TRUE")) { return true; } else if (std.mem.eql(u8, str, "false") or std.mem.eql(u8, str, "False") or std.mem.eql(u8, str, "FALSE")) { return false; } else return error.UnexpectedType; }, else => return error.UnexpectedType, } }, .Int, .ComptimeInt => { switch (value) { .String => |str| return try std.fmt.parseInt(T, str, 0), else => return error.UnexpectedType, } }, .Float, .ComptimeFloat => { switch (value) { .String => |str| return try std.fmt.parseFloat(T, str), else => return error.UnexpectedType, } }, .Void => { switch (value) { .String => |str| { if (std.mem.eql(u8, str, "null") or std.mem.eql(u8, str, "NULL") or str.len == 0) { return {}; } }, else => return error.UnexpectedType, } return error.UnexpectedType; }, .Optional => |optional_info| { switch (value) { .String => |str| { if (std.mem.eql(u8, str, "null") or std.mem.eql(u8, str, "NULL") or str.len == 0) { return null; } }, else => { // Fall through. }, } return try p.parseTypedInternal(optional_info.child, value); }, .Enum => |_| { switch (value) { // Note that if the value is numeric then it could be // intepreted as the enum number (use std.meta.intToEnum()), // but we choose not to interpret in this way currently. .String => |str| return (std.meta.stringToEnum(T, str) orelse error.InvalidEnumTag), else => return error.UnexpectedType, } }, .Union => |union_info| { if (union_info.tag_type) |_| { // Try each of the union fields until we find one with a type // that the value can successfully be parsed into. inline for (union_info.fields) |field| { if (p.parseTypedInternal(field.field_type, value)) |val| { return @unionInit(T, field.name, val); } else |err| { // Bubble up OutOfMemory error. // Parsing some types won't have OutOfMemory in their // error-sets - merge it in so that this condition is // valid. if (@as(@TypeOf(err) || error{OutOfMemory}, err) == error.OutOfMemory) return err; } } return error.UnexpectedType; } else { @compileError("Unable to parse into untagged union '" ++ @typeName(T) ++ "'"); } }, .Struct => |struct_info| { var ret: T = undefined; var obj: Map = undefined; // Check the value type. switch (value) { .Object => |_obj| obj = _obj, else => return error.UnexpectedType, } // Keep track of fields seen for error cleanup. var fields_seen = [_]bool{false} ** struct_info.fields.len; errdefer { inline for (struct_info.fields) |field, i| if (fields_seen[i] and !field.is_comptime) p.parseTypedFreeInternal(field.field_type, @field(ret, field.name)); } // Loop over values in the parsed object. var iter = obj.iterator(); while (iter.next()) |entry| { const key = entry.key_ptr.*; const val = entry.value_ptr.*; var key_field_found = false; // Loop over struct fields, looking for one that matches the current key. inline for (struct_info.fields) |field, i| { if (std.mem.eql(u8, field.name, key)) { if (field.is_comptime) { // TODO: ?? return error.NotImplemented; } else { @field(ret, field.name) = try p.parseTypedInternal(field.field_type, val); } fields_seen[i] = true; key_field_found = true; break; } } // Key found in the data but no corresponding field in the struct. if (!key_field_found) return error.UnexpectedObjectKey; } // Check for missing fields. inline for (struct_info.fields) |field, i| if (!fields_seen[i]) { if (field.default_value) |default| { if (!field.is_comptime) @field(ret, field.name) = default; } else { return error.MissingField; } }; return ret; }, .Array => |array_info| { // TODO: Allow array to have spare space, perhaps require terminated? var ret: T = undefined; switch (value) { .List => |list| { var idx: usize = 0; if (list.items.len != ret.len) return error.UnexpectedType; errdefer { // Without the len check indexing into the array is not allowed. if (ret.len > 0) while (true) : (idx -= 1) { p.parseTypedFreeInternal(array_info.child, ret[idx]); }; } // Without the len check indexing into the array is not allowed. if (ret.len > 0) while (idx < ret.len) : (idx += 1) { ret[idx] = try p.parseTypedInternal(array_info.child, list.items[idx]); }; }, .String => |str| { if (array_info.child != u8) return error.UnexpectedType; if (str.len != ret.len) return error.UnexpectedType; std.mem.copy(u8, &ret, str); }, else => return error.UnexpectedType, } return ret; }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => { const ret: T = try p.allocator.create(ptr_info.child); errdefer p.allocator.destroy(ret); ret.* = try p.parseTypedInternal(ptr_info.child, value); return ret; }, .Slice => { switch (value) { .List => |list| { var array = ArrayList(ptr_info.child).init(p.allocator); errdefer { var i: usize = array.items.len; while (i > 0) : (i -= 1) { p.parseTypedFreeInternal(ptr_info.child, array.pop()); } array.deinit(); } try array.ensureTotalCapacity(list.items.len); for (list.items) |val| { array.appendAssumeCapacity(try p.parseTypedInternal(ptr_info.child, val)); } return array.toOwnedSlice(); }, .String => |str| { if (ptr_info.child != u8) return error.UnexpectedType; return p.allocator.dupe(u8, str); }, else => return error.UnexpectedType, } }, else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"), } }, else => @compileError("Unable to parse into type '" ++ @typeName(T) ++ "'"), } unreachable; } fn parseTypedFreeInternal(p: Self, comptime T: type, value: T) void { switch (@typeInfo(T)) { .Optional => { if (value) |v| { return p.parseTypedFreeInternal(@TypeOf(v), v); } }, .Union => |union_info| { if (union_info.tag_type) |UnionTagType| { inline for (union_info.fields) |field| { if (value == @field(UnionTagType, field.name)) { p.parseTypedFreeInternal(field.field_type, @field(value, field.name)); break; } } } else unreachable; }, .Struct => |struct_info| { inline for (struct_info.fields) |field| { if (!field.is_comptime) { p.parseTypedFreeInternal(field.field_type, @field(value, field.name)); } } }, .Array => |array_info| { for (value) |v| { p.parseTypedFreeInternal(array_info.child, v); } }, .Pointer => |ptr_info| { switch (ptr_info.size) { .One => { p.parseTypedFreeInternal(ptr_info.child, value.*); p.allocator.destroy(value); }, .Slice => { for (value) |v| { p.parseTypedFreeInternal(ptr_info.child, v); } p.allocator.free(value); }, else => unreachable, } }, else => {}, } } fn readValue(p: Self, allocator: *Allocator, lines: *LinesIter) anyerror!Value { // Call read<type>() with the first line of the type queued up as the // next line in the lines iterator. const next_line = lines.peekNext().?; return switch (next_line.kind) { .String => .{ .String = try p.readString(allocator, lines) }, .ListItem => .{ .List = try p.readList(allocator, lines) }, .ObjectItem, .ObjectKey => .{ .Object = try p.readObject(allocator, lines) }, .InlineContainer => try p.readInlineContainer(allocator, lines), .Unrecognised => { p.maybeStoreDiags(next_line.lineno, "Unrecognised line type"); return error.UnrecognisedLine; }, .InvalidTabIndent => { p.maybeStoreDiags( next_line.lineno, "Tabs not allowed in indentation of non-ignored lines", ); return error.TabIndentation; }, .Blank, .Comment => unreachable, // Skipped by iterator }; } fn readString(p: Self, allocator: *Allocator, lines: *LinesIter) ![]const u8 { var buffer = ArrayList(u8).init(allocator); errdefer buffer.deinit(); var writer = buffer.writer(); assert(lines.peekNext().?.kind == .String); const depth = lines.peekNext().?.depth; while (lines.next()) |line| { if (line.kind != .String) { p.maybeStoreDiags( line.lineno, "Invalid line type following multi-line string", ); return error.InvalidItem; } const is_last_line = lines.peekNext() == null or lines.peekNext().?.depth < depth; const str_line = line.kind.String; if (line.depth > depth) { p.maybeStoreDiags(line.lineno, "Invalid indentation of multi-line string"); return error.InvalidIndentation; } // String must be copied as it's not contiguous in-file. if (is_last_line) try writer.writeAll(std.mem.trimRight(u8, str_line.value, &[_]u8{ '\n', '\r' })) else try writer.writeAll(str_line.value); if (is_last_line) break; } return buffer.items; } fn readList(p: Self, allocator: *Allocator, lines: *LinesIter) !Array { var array = Array.init(allocator); errdefer array.deinit(); assert(lines.peekNext().?.kind == .ListItem); const depth = lines.peekNext().?.depth; while (lines.next()) |line| { if (line.kind != .ListItem) { p.maybeStoreDiags(line.lineno, "Invalid line type following list item"); return error.InvalidItem; } const list_line = line.kind.ListItem; if (line.depth > depth) { p.maybeStoreDiags(line.lineno, "Invalid indentation following list item"); return error.InvalidIndentation; } var value: Value = undefined; if (list_line.value) |str| { value = .{ .String = try p.maybeDupString(allocator, str) }; } else if (lines.peekNext() != null and lines.peekNext().?.depth > depth) { value = try p.readValue(allocator, lines); } else { value = .{ .String = "" }; } try array.append(value); if (lines.peekNext() != null and lines.peekNext().?.depth < depth) break; } return array; } fn readObject(p: Self, allocator: *Allocator, lines: *LinesIter) anyerror!Map { var map = Map.init(allocator); errdefer map.deinit(); assert(lines.peekNext().?.kind.isObject()); const depth = lines.peekNext().?.depth; while (lines.peekNext()) |line| { if (!line.kind.isObject()) { p.maybeStoreDiags(line.lineno, "Invalid line type following object item"); return error.InvalidItem; } if (line.depth > depth) { p.maybeStoreDiags(line.lineno, "Invalid indentation following object item"); return error.InvalidIndentation; } const key = switch (line.kind) { .ObjectItem => |obj_line| blk: { _ = lines.next(); // Advance iterator break :blk try p.maybeDupString(allocator, obj_line.key); }, .ObjectKey => try p.readObjectKey(allocator, lines), else => unreachable, }; if (map.contains(key)) { switch (p.options.duplicate_field_behavior) { .UseFirst => continue, .UseLast => {}, .Error => { p.maybeStoreDiags(line.lineno, "Duplicate object key"); return error.DuplicateKey; }, } } const value: Value = blk: { if (line.kind == .ObjectItem and line.kind.ObjectItem.value != null) { const string = line.kind.ObjectItem.value.?; break :blk .{ .String = try p.maybeDupString(allocator, string) }; } else if (lines.peekNext() != null and lines.peekNext().?.depth > depth) { break :blk try p.readValue(allocator, lines); } else if (line.kind == .ObjectKey) { p.maybeStoreDiags(line.lineno, "Multiline object key must be followed by value"); return error.MissingObjectValue; } else { break :blk .{ .String = "" }; } }; try map.put(key, value); if (lines.peekNext() != null and lines.peekNext().?.depth < depth) break; } return map; } fn readObjectKey(p: Self, allocator: *Allocator, lines: *LinesIter) ![]const u8 { // Handled just like strings. var buffer = ArrayList(u8).init(allocator); errdefer buffer.deinit(); var writer = buffer.writer(); assert(lines.peekNext().?.kind == .ObjectKey); const depth = lines.peekNext().?.depth; while (lines.next()) |line| { if (line.kind != .ObjectKey) { p.maybeStoreDiags( line.lineno, "Invalid line type following object key line", ); return error.InvalidItem; } const is_last_line = lines.peekNext() == null or lines.peekNext().?.depth != depth; const key_line = line.kind.ObjectKey; if (line.depth > depth) { p.maybeStoreDiags(line.lineno, "Invalid indentation of object key line"); return error.InvalidIndentation; } // String must be copied as it's not contiguous in-file. if (is_last_line) try writer.writeAll(std.mem.trimRight(u8, key_line.value, &[_]u8{ '\n', '\r' })) else try writer.writeAll(key_line.value); if (is_last_line) break; } return buffer.items; } fn readInlineContainer(p: Self, allocator: *Allocator, lines: *LinesIter) !Value { const line = lines.next().?; assert(line.kind == .InlineContainer); const line_text = line.kind.InlineContainer.value; var text_iter = CharIter{ .text = line_text }; const value: Value = switch (text_iter.next().?) { '[' => .{ .List = try p.parseInlineList(allocator, &text_iter, line.lineno) }, '{' => .{ .Object = try p.parseInlineObject(allocator, &text_iter, line.lineno) }, else => unreachable, }; if (text_iter.idx != text_iter.text.len) { p.maybeStoreDiags(line.lineno, "Unexpected text following closing bracket/brace"); return error.InvalidItem; } // Check next content line is dedented. if (lines.peekNext() != null and lines.peekNext().?.depth >= line.depth) { p.maybeStoreDiags(line.lineno, "Invalid indentation following list item"); return error.InvalidIndentation; } return value; } fn parseInlineList(p: Self, allocator: *Allocator, text_iter: *CharIter, lineno: usize) anyerror!Array { var array = Array.init(allocator); errdefer array.deinit(); // State machine: // 1. Looking for value (or closing brace -> finished) // 2. Looking for comma (or closing brace -> finished) // 3. Looking for value // 4. Looking for comma (or closing brace -> finished) // ... const Token = enum { Value, ValueOrEnd, CommaOrEnd, Finished, }; var next_token = Token.ValueOrEnd; var parsed_value: ?Value = null; // First character is the first one after the opening '['. while (text_iter.next()) |char| { // Skip over whitespace between the tokens. if (char == ' ' or char == '\t') continue; // Check the character and/or consume some text for the expected token. switch (next_token) { .Value, .ValueOrEnd => { if (next_token == .ValueOrEnd and char == ']') { next_token = .Finished; break; } if (char == '[') parsed_value = .{ .List = try p.parseInlineList(allocator, text_iter, lineno), } else if (char == '{') parsed_value = .{ .Object = try p.parseInlineObject(allocator, text_iter, lineno), } else if (p.parseInlineContainerString(text_iter, "[]{},")) |value| parsed_value = .{ .String = try p.maybeDupString(allocator, value) } else { p.maybeStoreDiags(lineno, "Expected an inline list value"); return error.InvalidItem; } next_token = .CommaOrEnd; }, .CommaOrEnd => { if (char != ',' and char != ']') { p.maybeStoreDiags(lineno, "Unexpected character after inline list value"); return error.InvalidItem; } try array.append(parsed_value.?); parsed_value = null; if (char == ']') { next_token = .Finished; break; } next_token = .Value; }, .Finished => unreachable, } } if (next_token != .Finished) { p.maybeStoreDiags(lineno, "Missing closing brace ']'"); return error.InvalidItem; } return array; } fn parseInlineObject(p: Self, allocator: *Allocator, text_iter: *CharIter, lineno: usize) anyerror!Map { var map = Map.init(allocator); errdefer map.deinit(); // State machine: // 1. Looking for key (or closing brace -> finished) // 2. Looking for colon // 3. Looking for value // 4. Looking for comma (or closing brace -> finished) // 5. Looking for key // 6. Looking for colon // ... const Token = enum { Key, KeyOrEnd, Colon, Value, CommaOrEnd, Finished, }; var next_token = Token.KeyOrEnd; var parsed_key: ?[]const u8 = null; var parsed_value: ?Value = null; // First character is the first one after the opening '{'. while (text_iter.next()) |char| { // Skip over whitespace between the tokens. if (char == ' ' or char == '\t') continue; // Check the character and/or consume some text for the expected token. switch (next_token) { .Key, .KeyOrEnd => { if (next_token == .KeyOrEnd and char == '}') { next_token = .Finished; break; } if (p.parseInlineContainerString(text_iter, "[]{},:")) |key| parsed_key = key else { p.maybeStoreDiags(lineno, "Expected an inline object key"); return error.InvalidItem; } next_token = .Colon; }, .Colon => { if (char != ':') { p.maybeStoreDiags(lineno, "Unexpected character after inline object key"); return error.InvalidItem; } next_token = .Value; }, .Value => { if (char == '[') parsed_value = .{ .List = try p.parseInlineList(allocator, text_iter, lineno), } else if (char == '{') parsed_value = .{ .Object = try p.parseInlineObject(allocator, text_iter, lineno), } else if (p.parseInlineContainerString(text_iter, "[]{},:")) |value| parsed_value = .{ .String = try p.maybeDupString(allocator, value) } else { p.maybeStoreDiags(lineno, "Expected an inline object value"); return error.InvalidItem; } next_token = .CommaOrEnd; }, .CommaOrEnd => { if (char != ',' and char != '}') { p.maybeStoreDiags(lineno, "Unexpected character after inline object value"); return error.InvalidItem; } try map.put(parsed_key.?, parsed_value.?); parsed_key = null; parsed_value = null; if (char == '}') { next_token = .Finished; break; } next_token = .Key; }, .Finished => unreachable, } } if (next_token != .Finished) { p.maybeStoreDiags(lineno, "Missing closing brace '}'"); return error.InvalidItem; } return map; } fn parseInlineContainerString(_: Self, text_iter: *CharIter, disallowed_chars: []const u8) ?[]const u8 { const start_idx = text_iter.idx - 1; const end_idx = blk: { if (std.mem.indexOfAnyPos(u8, text_iter.text, start_idx, disallowed_chars)) |idx| break :blk idx else break :blk text_iter.text.len; }; if (end_idx == start_idx) return null; // Zero-length (empty string) text_iter.idx = end_idx; return std.mem.trim(u8, text_iter.text[start_idx..end_idx], " \t"); } fn maybeDupString(p: Self, allocator: *Allocator, string: []const u8) ![]const u8 { return if (p.options.copy_strings) try allocator.dupe(u8, string) else string; } fn maybeStoreDiags(p: Self, lineno: usize, message: []const u8) void { if (p.diags) |diags| diags.* = .{ .ParseError = .{ .lineno = lineno, .message = message, }, }; } }; // ----------------------------------------------------------------------------- // Tests // ----------------------------------------------------------------------------- test "parse empty" { var p = Parser.init(testing.allocator, .{}); var tree = try p.parse(""); defer tree.deinit(); try testing.expectEqual(@as(?Value, null), tree.root); } test "basic parse: string" { var p = Parser.init(testing.allocator, .{}); const s = \\> this is a \\> multiline \\> string ; var tree = try p.parse(s); defer tree.deinit(); try testing.expectEqualStrings("this is a\nmultiline\nstring", tree.root.?.String); } test "basic parse: list" { var p = Parser.init(testing.allocator, .{}); const s = \\- foo \\- bar ; var tree = try p.parse(s); defer tree.deinit(); const array: Array = tree.root.?.List; try testing.expectEqualStrings("foo", array.items[0].String); try testing.expectEqualStrings("bar", array.items[1].String); } test "basic parse: object" { var p = Parser.init(testing.allocator, .{}); const s = \\foo: 1 \\bar: False ; var tree = try p.parse(s); defer tree.deinit(); const map: Map = tree.root.?.Object; try testing.expectEqualStrings("1", map.get("foo").?.String); try testing.expectEqualStrings("False", map.get("bar").?.String); } test "nested parse: object inside object" { var p = Parser.init(testing.allocator, .{}); const s = \\foo: 1 \\bar: \\ nest1: 2 \\ nest2: 3 \\baz: ; var tree = try p.parse(s); defer tree.deinit(); const map: Map = tree.root.?.Object; try testing.expectEqualStrings("1", map.get("foo").?.String); try testing.expectEqualStrings("", map.get("baz").?.String); try testing.expectEqualStrings("2", map.get("bar").?.Object.get("nest1").?.String); try testing.expectEqualStrings("3", map.get("bar").?.Object.get("nest2").?.String); } test "failed parse: multi-line string indent" { var p = Parser.init(testing.allocator, .{}); var diags: Parser.Diags = undefined; p.diags = &diags; const s = \\> foo \\ > bar ; try testing.expectError(error.InvalidIndentation, p.parse(s)); try testing.expectEqual(@as(usize, 2), diags.ParseError.lineno); try testing.expectEqualStrings( "Invalid indentation of multi-line string", diags.ParseError.message, ); } test "typed parse: bool" { var p = Parser.init(testing.allocator, .{}); try testing.expectEqual(true, try p.parseTyped(bool, "> true")); try testing.expectEqual(true, try p.parseTyped(bool, "> True")); try testing.expectEqual(true, try p.parseTyped(bool, "> TRUE")); try testing.expectEqual(false, try p.parseTyped(bool, "> false")); try testing.expectEqual(false, try p.parseTyped(bool, "> False")); try testing.expectEqual(false, try p.parseTyped(bool, "> FALSE")); } test "typed parse: int" { var p = Parser.init(testing.allocator, .{}); try testing.expectEqual(@as(u1, 1), try p.parseTyped(u1, "> 1")); try testing.expectEqual(@as(u8, 17), try p.parseTyped(u8, "> 0x11")); } test "typed parse: float" { var p = Parser.init(testing.allocator, .{}); try testing.expectEqual(@as(f64, 1.1), try p.parseTyped(f64, "> 1.1")); } test "typed parse: optional" { var p = Parser.init(testing.allocator, .{}); try testing.expectEqual(@as(?isize, -42), try p.parseTyped(?isize, "> -000_042")); try testing.expectEqual(@as(?[0]u8, null), try p.parseTyped(?[0]u8, "> null")); try testing.expectEqual(@as(?bool, null), try p.parseTyped(?bool, "> NULL")); try testing.expectEqual(@as(?f64, null), try p.parseTyped(?f64, ">")); } test "typed parse: array" { var p = Parser.init(testing.allocator, .{}); try testing.expectEqual([0]bool{}, try p.parseTyped([0]bool, "[]")); try testing.expectEqual([3]i32{ 1, 2, 3 }, try p.parseTyped([3]i32, "[1, 2, 3]")); try testing.expectEqualStrings("hello", &(try p.parseTyped([5]u8, "> hello"))); } test "typed parse: struct" { var p = Parser.init(testing.allocator, .{}); const MyStruct = struct { foo: usize, bar: ?bool, }; try testing.expectEqual( MyStruct{ .foo = 1, .bar = true }, try p.parseTyped(MyStruct, "{foo: 1, bar: TRUE}"), ); try testing.expectEqual( MyStruct{ .foo = 123456, .bar = @as(?bool, null) }, try p.parseTyped(MyStruct, "{foo: 123456, bar: null}"), ); } test "typed parse: enum" { var p = Parser.init(testing.allocator, .{}); const MyEnum = enum { foo, bar, }; try testing.expectEqual(MyEnum.foo, try p.parseTyped(MyEnum, "> foo")); try testing.expectEqual(MyEnum.bar, try p.parseTyped(MyEnum, "> bar")); } test "typed parse: union" { var p = Parser.init(testing.allocator, .{}); const MyUnion = union(enum) { foo: usize, bar: bool, baz, }; try testing.expectEqual(MyUnion{ .foo = 1 }, try p.parseTyped(MyUnion, "> 1")); try testing.expectEqual(MyUnion{ .bar = false }, try p.parseTyped(MyUnion, "> false")); try testing.expectEqual(MyUnion.baz, try p.parseTyped(MyUnion, "> null")); } test "typed parse: pointer to single elem" { var p = Parser.init(testing.allocator, .{}); { const r = try p.parseTyped(*bool, "> false"); defer p.parseTypedFree(r); try testing.expectEqual(false, r.*); } } test "typed parse: slice" { var p = Parser.init(testing.allocator, .{}); { const r = try p.parseTyped([]?bool, "[true, false, null]"); defer p.parseTypedFree(r); try testing.expectEqualSlices(?bool, &[_]?bool{ true, false, null }, r); } { const r = try p.parseTyped([]u8, "> foo"); defer p.parseTypedFree(r); try testing.expectEqualStrings("foo", r); } { const r = try p.parseTyped([]u8, "[102, 111, 111]"); defer p.parseTypedFree(r); try testing.expectEqualStrings("foo", r); } } fn testStringify(expected: []const u8, tree: ValueTree) !void { var buffer: [128]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try tree.stringify(.{}, fbs.writer()); try testing.expectEqualStrings(expected, fbs.getWritten()); } fn testToJson(expected: []const u8, tree: ValueTree) !void { var json_tree = try tree.toJson(testing.allocator); defer json_tree.deinit(); var buffer: [128]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); try json_tree.root.jsonStringify(.{}, fbs.writer()); try testing.expectEqualStrings(expected, fbs.getWritten()); } test "stringify: string" { var p = Parser.init(testing.allocator, .{}); const s = \\> this is a \\> multiline \\> string ; var tree = try p.parse(s); defer tree.deinit(); try testStringify(s, tree); } test "stringify: list" { var p = Parser.init(testing.allocator, .{}); const s = \\- foo \\- bar ; var tree = try p.parse(s); defer tree.deinit(); try testStringify(s, tree); } test "stringify: object" { var p = Parser.init(testing.allocator, .{}); const s = \\foo: 1 \\bar: False ; var tree = try p.parse(s); defer tree.deinit(); try testStringify(s, tree); } test "stringify: multiline string inside object" { var p = Parser.init(testing.allocator, .{}); const s = \\foo: \\ > multi \\ > line \\bar: ; var tree = try p.parse(s); defer tree.deinit(); try testStringify(s, tree); } test "convert to JSON: string" { var p = Parser.init(testing.allocator, .{}); const s = \\> this is a \\> multiline \\> string ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("\"this is a\\nmultiline\\nstring\"", tree); } test "convert to JSON: list" { var p = Parser.init(testing.allocator, .{}); const s = \\- foo \\- bar ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("[\"foo\",\"bar\"]", tree); } test "convert to JSON: object" { var p = Parser.init(testing.allocator, .{}); const s = \\foo: 1 \\bar: False ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("{\"foo\":\"1\",\"bar\":\"False\"}", tree); } test "convert to JSON: object inside object" { var p = Parser.init(testing.allocator, .{}); const s = \\bar: \\ nest1: 1 \\ nest2: 2 ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("{\"bar\":{\"nest1\":\"1\",\"nest2\":\"2\"}}", tree); } test "convert to JSON: list inside object" { var p = Parser.init(testing.allocator, .{}); const s = \\bar: \\ - nest1 \\ - nest2 ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("{\"bar\":[\"nest1\",\"nest2\"]}", tree); } test "convert to JSON: multiline string inside object" { var p = Parser.init(testing.allocator, .{}); const s = \\foo: \\ > multi \\ > line ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("{\"foo\":\"multi\\nline\"}", tree); } test "convert to JSON: multiline string inside list" { var p = Parser.init(testing.allocator, .{}); const s = \\- \\ > multi \\ > line \\- ; var tree = try p.parse(s); defer tree.deinit(); try testToJson("[\"multi\\nline\",\"\"]", tree); } test "from type: bool" { { const tree = try fromArbitraryType(testing.allocator, true); defer tree.deinit(); try testStringify("> true", tree); } { const tree = try fromArbitraryType(testing.allocator, false); defer tree.deinit(); try testStringify("> false", tree); } } test "from type: number" { { const tree = try fromArbitraryType(testing.allocator, @as(u1, 1)); defer tree.deinit(); try testStringify("> 1", tree); } { const tree = try fromArbitraryType(testing.allocator, @as(isize, -123456)); defer tree.deinit(); try testStringify("> -123456", tree); } { const tree = try fromArbitraryType(testing.allocator, @as(f64, 1.1)); defer tree.deinit(); try testStringify("> 1.1", tree); } } test "from type: optional" { { const tree = try fromArbitraryType(testing.allocator, null); defer tree.deinit(); try testStringify("> null", tree); } { const tree = try fromArbitraryType(testing.allocator, @as(?bool, false)); defer tree.deinit(); try testStringify("> false", tree); } } test "from type: enum" { { const MyEnum = enum { foo, bar, }; const tree = try fromArbitraryType(testing.allocator, MyEnum.foo); defer tree.deinit(); try testStringify("> foo", tree); } { const tree = try fromArbitraryType(testing.allocator, .enum_literal); defer tree.deinit(); try testStringify("> enum_literal", tree); } } test "from type: error" { { const tree = try fromArbitraryType(testing.allocator, error.SomeError); defer tree.deinit(); try testStringify("> SomeError", tree); } } test "from type: union" { const MyUnion = union(enum) { foo: usize, bar: bool, baz, }; { const tree = try fromArbitraryType(testing.allocator, MyUnion{ .foo = 123 }); defer tree.deinit(); try testStringify("> 123", tree); } { const tree = try fromArbitraryType(testing.allocator, MyUnion{ .bar = true }); defer tree.deinit(); try testStringify("> true", tree); } { const tree = try fromArbitraryType(testing.allocator, MyUnion{ .baz = {} }); defer tree.deinit(); try testStringify("> null", tree); } { // Note that without the curly-brace syntax to explicitly pass 'void', // the value is treated as a field of the underlying enum used by the // tagged enum. This is treated differently in the conversion, using // the enum field name rather than the union payload... const tree = try fromArbitraryType(testing.allocator, MyUnion.baz); defer tree.deinit(); try testStringify("> baz", tree); } } test "from type: struct" { const MyStruct = struct { foo: usize, bar: ?bool = false, baz: void = {}, }; { const tree = try fromArbitraryType( testing.allocator, MyStruct{ .foo = 1 }, ); defer tree.deinit(); try testToJson("{\"foo\":\"1\",\"bar\":\"false\",\"baz\":\"null\"}", tree); } } test "from type: pointer to single elem" { const value = false; { const tree = try fromArbitraryType(testing.allocator, &value); defer tree.deinit(); try testStringify("> false", tree); } } test "from type: array/slice" { const array = [_]i8{ 1, -5, -0, 0123 }; const slice: []const i8 = &array; const expected_json = "[\"1\",\"-5\",\"0\",\"123\"]"; { const tree = try fromArbitraryType(testing.allocator, array); defer tree.deinit(); try testToJson(expected_json, tree); } { const tree = try fromArbitraryType(testing.allocator, slice); defer tree.deinit(); try testToJson(expected_json, tree); } { // Pointer to array (not a slice). const tree = try fromArbitraryType(testing.allocator, &array); defer tree.deinit(); try testToJson(expected_json, tree); } } test "from type: string" { { const tree = try fromArbitraryType(testing.allocator, "hello"); defer tree.deinit(); try testStringify("> hello", tree); } }
src/nestedtext.zig
const std = @import("std"); const mem = std.mem; const uefi = std.os.uefi; const Allocator = mem.Allocator; const Guid = uefi.Guid; pub const DevicePathProtocol = packed struct { type: DevicePathType, subtype: u8, length: u16, pub const guid align(8) = Guid{ .time_low = 0x09576e91, .time_mid = 0x6d3f, .time_high_and_version = 0x11d2, .clock_seq_high_and_reserved = 0x8e, .clock_seq_low = 0x39, .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b }, }; /// Returns the next DevicePathProtocol node in the sequence, if any. pub fn next(self: *DevicePathProtocol) ?*DevicePathProtocol { if (self.type == .End and @intToEnum(EndDevicePath.Subtype, self.subtype) == .EndEntire) return null; return @ptrCast(*DevicePathProtocol, @ptrCast([*]u8, self) + self.length); } /// Calculates the total length of the device path structure in bytes, including the end of device path node. pub fn size(self: *DevicePathProtocol) usize { var node = self; while (node.next()) |next_node| { node = next_node; } return (@ptrToInt(node) + node.length) - @ptrToInt(self); } /// Creates a file device path from the existing device path and a file path. pub fn create_file_device_path(self: *DevicePathProtocol, allocator: Allocator, path: [:0]const u16) !*DevicePathProtocol { var path_size = self.size(); // 2 * (path.len + 1) for the path and its null terminator, which are u16s // DevicePathProtocol for the extra node before the end var buf = try allocator.alloc(u8, path_size + 2 * (path.len + 1) + @sizeOf(DevicePathProtocol)); mem.copy(u8, buf, @ptrCast([*]const u8, self)[0..path_size]); // Pointer to the copy of the end node of the current chain, which is - 4 from the buffer // as the end node itself is 4 bytes (type: u8 + subtype: u8 + length: u16). var new = @ptrCast(*MediaDevicePath.FilePathDevicePath, buf.ptr + path_size - 4); new.type = .Media; new.subtype = .FilePath; new.length = @sizeOf(MediaDevicePath.FilePathDevicePath) + 2 * (@intCast(u16, path.len) + 1); // The same as new.getPath(), but not const as we're filling it in. var ptr = @ptrCast([*:0]u16, @alignCast(2, @ptrCast([*]u8, new)) + @sizeOf(MediaDevicePath.FilePathDevicePath)); for (path) |s, i| ptr[i] = s; ptr[path.len] = 0; var end = @ptrCast(*EndDevicePath.EndEntireDevicePath, @ptrCast(*DevicePathProtocol, new).next().?); end.type = .End; end.subtype = .EndEntire; end.length = @sizeOf(EndDevicePath.EndEntireDevicePath); return @ptrCast(*DevicePathProtocol, buf.ptr); } pub fn getDevicePath(self: *const DevicePathProtocol) ?DevicePath { inline for (@typeInfo(DevicePath).Union.fields) |ufield| { const enum_value = std.meta.stringToEnum(DevicePathType, ufield.name); // Got the associated union type for self.type, now // we need to initialize it and its subtype if (self.type == enum_value) { var subtype = self.initSubtype(ufield.field_type); if (subtype) |sb| { // e.g. return .{ .Hardware = .{ .Pci = @ptrCast(...) } } return @unionInit(DevicePath, ufield.name, sb); } } } return null; } pub fn initSubtype(self: *const DevicePathProtocol, comptime TUnion: type) ?TUnion { const type_info = @typeInfo(TUnion).Union; const TTag = type_info.tag_type.?; inline for (type_info.fields) |subtype| { // The tag names match the union names, so just grab that off the enum const tag_val: u8 = @enumToInt(@field(TTag, subtype.name)); if (self.subtype == tag_val) { // e.g. expr = .{ .Pci = @ptrCast(...) } return @unionInit(TUnion, subtype.name, @ptrCast(subtype.field_type, self)); } } return null; } }; pub const DevicePath = union(DevicePathType) { Hardware: HardwareDevicePath, Acpi: AcpiDevicePath, Messaging: MessagingDevicePath, Media: MediaDevicePath, BiosBootSpecification: BiosBootSpecificationDevicePath, End: EndDevicePath, }; pub const DevicePathType = enum(u8) { Hardware = 0x01, Acpi = 0x02, Messaging = 0x03, Media = 0x04, BiosBootSpecification = 0x05, End = 0x7f, _, }; pub const HardwareDevicePath = union(Subtype) { Pci: *const PciDevicePath, PcCard: *const PcCardDevicePath, MemoryMapped: *const MemoryMappedDevicePath, Vendor: *const VendorDevicePath, Controller: *const ControllerDevicePath, Bmc: *const BmcDevicePath, pub const Subtype = enum(u8) { Pci = 1, PcCard = 2, MemoryMapped = 3, Vendor = 4, Controller = 5, Bmc = 6, _, }; pub const PciDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, function: u8, device: u8, }; pub const PcCardDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, function_number: u8, }; pub const MemoryMappedDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, memory_type: u32, start_address: u64, end_address: u64, }; pub const VendorDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, vendor_guid: Guid, }; pub const ControllerDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, controller_number: u32, }; pub const BmcDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, interface_type: u8, base_address: usize, }; }; pub const AcpiDevicePath = union(Subtype) { Acpi: *const BaseAcpiDevicePath, ExpandedAcpi: *const ExpandedAcpiDevicePath, Adr: *const AdrDevicePath, pub const Subtype = enum(u8) { Acpi = 1, ExpandedAcpi = 2, Adr = 3, _, }; pub const BaseAcpiDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, hid: u32, uid: u32, }; pub const ExpandedAcpiDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, hid: u32, uid: u32, cid: u32, // variable length u16[*:0] strings // hid_str, uid_str, cid_str }; pub const AdrDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, adr: u32, // multiple adr entries can optionally follow pub fn adrs(self: *const AdrDevicePath) []const u32 { // self.length is a minimum of 8 with one adr which is size 4. var entries = (self.length - 4) / @sizeOf(u32); return @ptrCast([*]const u32, &self.adr)[0..entries]; } }; }; pub const MessagingDevicePath = union(Subtype) { Atapi: *const AtapiDevicePath, Scsi: *const ScsiDevicePath, FibreChannel: *const FibreChannelDevicePath, FibreChannelEx: *const FibreChannelExDevicePath, @"1394": *const F1394DevicePath, Usb: *const UsbDevicePath, Sata: *const SataDevicePath, UsbWwid: *const UsbWwidDevicePath, Lun: *const DeviceLogicalUnitDevicePath, UsbClass: *const UsbClassDevicePath, I2o: *const I2oDevicePath, MacAddress: *const MacAddressDevicePath, Ipv4: *const Ipv4DevicePath, Ipv6: *const Ipv6DevicePath, Vlan: *const VlanDevicePath, InfiniBand: *const InfiniBandDevicePath, Uart: *const UartDevicePath, Vendor: *const VendorDefinedDevicePath, pub const Subtype = enum(u8) { Atapi = 1, Scsi = 2, FibreChannel = 3, FibreChannelEx = 21, @"1394" = 4, Usb = 5, Sata = 18, UsbWwid = 16, Lun = 17, UsbClass = 15, I2o = 6, MacAddress = 11, Ipv4 = 12, Ipv6 = 13, Vlan = 20, InfiniBand = 9, Uart = 14, Vendor = 10, _, }; pub const AtapiDevicePath = packed struct { const Role = enum(u8) { Master = 0, Slave = 1, }; const Rank = enum(u8) { Primary = 0, Secondary = 1, }; type: DevicePathType, subtype: Subtype, length: u16, primary_secondary: Rank, slave_master: Role, logical_unit_number: u16, }; pub const ScsiDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, target_id: u16, logical_unit_number: u16, }; pub const FibreChannelDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, reserved: u32, world_wide_name: u64, logical_unit_number: u64, }; pub const FibreChannelExDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, reserved: u32, world_wide_name: [8]u8, logical_unit_number: [8]u8, }; pub const F1394DevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, reserved: u32, guid: u64, }; pub const UsbDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, parent_port_number: u8, interface_number: u8, }; pub const SataDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, hba_port_number: u16, port_multiplier_port_number: u16, logical_unit_number: u16, }; pub const UsbWwidDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, interface_number: u16, device_vendor_id: u16, device_product_id: u16, pub fn serial_number(self: *const UsbWwidDevicePath) []const u16 { var serial_len = (self.length - @sizeOf(UsbWwidDevicePath)) / @sizeOf(u16); return @ptrCast([*]u16, @ptrCast([*]u8, self) + @sizeOf(UsbWwidDevicePath))[0..serial_len]; } }; pub const DeviceLogicalUnitDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, lun: u8, }; pub const UsbClassDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, vendor_id: u16, product_id: u16, device_class: u8, device_subclass: u8, device_protocol: u8, }; pub const I2oDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, tid: u32, }; pub const MacAddressDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, mac_address: uefi.MacAddress, if_type: u8, }; pub const Ipv4DevicePath = packed struct { pub const IpType = enum(u8) { Dhcp = 0, Static = 1, }; type: DevicePathType, subtype: Subtype, length: u16, local_ip_address: uefi.Ipv4Address, remote_ip_address: uefi.Ipv4Address, local_port: u16, remote_port: u16, network_protocol: u16, static_ip_address: IpType, gateway_ip_address: u32, subnet_mask: u32, }; pub const Ipv6DevicePath = packed struct { pub const Origin = enum(u8) { Manual = 0, AssignedStateless = 1, AssignedStateful = 2, }; type: DevicePathType, subtype: Subtype, length: u16, local_ip_address: uefi.Ipv6Address, remote_ip_address: uefi.Ipv6Address, local_port: u16, remote_port: u16, protocol: u16, ip_address_origin: Origin, prefix_length: u8, gateway_ip_address: uefi.Ipv6Address, }; pub const VlanDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, vlan_id: u16, }; pub const InfiniBandDevicePath = packed struct { pub const ResourceFlags = packed struct { pub const ControllerType = enum(u1) { Ioc = 0, Service = 1, }; ioc_or_service: ControllerType, extend_boot_environment: bool, console_protocol: bool, storage_protocol: bool, network_protocol: bool, // u1 + 4 * bool = 5 bits, we need a total of 32 bits reserved: u27, }; type: DevicePathType, subtype: Subtype, length: u16, resource_flags: ResourceFlags, port_gid: [16]u8, service_id: u64, target_port_id: u64, device_id: u64, }; pub const UartDevicePath = packed struct { pub const Parity = enum(u8) { Default = 0, None = 1, Even = 2, Odd = 3, Mark = 4, Space = 5, _, }; pub const StopBits = enum(u8) { Default = 0, One = 1, OneAndAHalf = 2, Two = 3, _, }; type: DevicePathType, subtype: Subtype, length: u16, reserved: u16, baud_rate: u32, data_bits: u8, parity: Parity, stop_bits: StopBits, }; pub const VendorDefinedDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, vendor_guid: Guid, }; }; pub const MediaDevicePath = union(Subtype) { HardDrive: *const HardDriveDevicePath, Cdrom: *const CdromDevicePath, Vendor: *const VendorDevicePath, FilePath: *const FilePathDevicePath, MediaProtocol: *const MediaProtocolDevicePath, PiwgFirmwareFile: *const PiwgFirmwareFileDevicePath, PiwgFirmwareVolume: *const PiwgFirmwareVolumeDevicePath, RelativeOffsetRange: *const RelativeOffsetRangeDevicePath, RamDisk: *const RamDiskDevicePath, pub const Subtype = enum(u8) { HardDrive = 1, Cdrom = 2, Vendor = 3, FilePath = 4, MediaProtocol = 5, PiwgFirmwareFile = 6, PiwgFirmwareVolume = 7, RelativeOffsetRange = 8, RamDisk = 9, _, }; pub const HardDriveDevicePath = packed struct { pub const Format = enum(u8) { LegacyMbr = 0x01, GuidPartitionTable = 0x02, }; pub const SignatureType = enum(u8) { NoSignature = 0x00, /// "32-bit signature from address 0x1b8 of the type 0x01 MBR" MbrSignature = 0x01, GuidSignature = 0x02, }; type: DevicePathType, subtype: Subtype, length: u16, partition_number: u32, partition_start: u64, partition_size: u64, partition_signature: [16]u8, partition_format: Format, signature_type: SignatureType, }; pub const CdromDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, boot_entry: u32, partition_start: u64, partition_size: u64, }; pub const VendorDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, guid: Guid, // vendor-defined variable data }; pub const FilePathDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, pub fn getPath(self: *const FilePathDevicePath) [*:0]const u16 { return @ptrCast([*:0]const u16, @alignCast(2, @ptrCast([*]const u8, self)) + @sizeOf(FilePathDevicePath)); } }; pub const MediaProtocolDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, guid: Guid, }; pub const PiwgFirmwareFileDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, fv_filename: Guid, }; pub const PiwgFirmwareVolumeDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, fv_name: Guid, }; pub const RelativeOffsetRangeDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, reserved: u32, start: u64, end: u64, }; pub const RamDiskDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, start: u64, end: u64, disk_type: Guid, instance: u16, }; }; pub const BiosBootSpecificationDevicePath = union(Subtype) { BBS101: *const BBS101DevicePath, pub const Subtype = enum(u8) { BBS101 = 1, _, }; pub const BBS101DevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, device_type: u16, status_flag: u16, pub fn getDescription(self: *const BBS101DevicePath) [*:0]const u8 { return @ptrCast([*:0]const u8, self) + @sizeOf(BBS101DevicePath); } }; }; pub const EndDevicePath = union(Subtype) { EndEntire: *const EndEntireDevicePath, EndThisInstance: *const EndThisInstanceDevicePath, pub const Subtype = enum(u8) { EndEntire = 0xff, EndThisInstance = 0x01, _, }; pub const EndEntireDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, }; pub const EndThisInstanceDevicePath = packed struct { type: DevicePathType, subtype: Subtype, length: u16, }; };
lib/std/os/uefi/protocols/device_path_protocol.zig
const std = @import("std"); const Csr = @import("csr.zig").Csr; const Mstatus = @import("csr.zig").Mstatus; const MCause = @import("csr.zig").MCause; const Mtvec = @import("csr.zig").Mtvec; const Stvec = @import("csr.zig").Stvec; const SCause = @import("csr.zig").SCause; const Satp = @import("csr.zig").Satp; const InstructionType = @import("instruction.zig").InstructionType; const Instruction = @import("instruction.zig").Instruction; const PrivilegeLevel = @import("types.zig").PrivilegeLevel; const IntegerRegister = @import("types.zig").IntegerRegister; const ExceptionCode = @import("types.zig").ExceptionCode; const ContextStatus = @import("types.zig").ContextStatus; const VectorMode = @import("types.zig").VectorMode; const AddressTranslationMode = @import("types.zig").AddressTranslationMode; const CpuState = @This(); memory: []u8, x: [32]u64 = [_]u64{0} ** 32, pc: usize = 0, privilege_level: PrivilegeLevel = .Machine, mstatus: Mstatus = Mstatus.initial_state, /// mstatus:sie supervisor_interrupts_enabled: bool = false, /// mstatus:spie supervisor_interrupts_enabled_prior: bool = false, /// mstatus:spp supervisor_previous_privilege_level: PrivilegeLevel = .Supervisor, /// mstatus:mie machine_interrupts_enabled: bool = false, /// mstatus:mpie machine_interrupts_enabled_prior: bool = false, /// mstatus:mpp machine_previous_privilege_level: PrivilegeLevel = .Machine, /// mstatus:fs floating_point_status: ContextStatus = .Initial, /// mstatus:xs extension_status: ContextStatus = .Initial, /// mstatus:ds state_dirty: bool = false, /// mstatus:mprv modify_privilege: bool = false, /// mstatus:sum supervisor_user_memory_access: bool = false, /// mstatus:mxr executable_readable: bool = false, /// mstatus:tvm trap_virtual_memory: bool = false, /// mstatus:tw timeout_wait: bool = false, /// mstatus:tsr trap_sret: bool = false, mepc: u64 = 0, mcause: MCause = .{ .backing = 0 }, mtval: u64 = 0, sepc: u64 = 0, scause: SCause = .{ .backing = 0 }, stval: u64 = 0, mhartid: u64 = 0, mtvec: Mtvec = .{ .backing = 0 }, machine_vector_base_address: u64 = 0, machine_vector_mode: VectorMode = .Direct, stvec: Stvec = .{ .backing = 0 }, supervisor_vector_base_address: u64 = 0, supervisor_vector_mode: VectorMode = .Direct, satp: Satp = .{ .backing = 0 }, address_translation_mode: AddressTranslationMode = .Bare, asid: u16 = 0, ppn_address: u64 = 0, medeleg: u64 = 0, mideleg: u64 = 0, mie: u64 = 0, mip: u64 = 0, pub fn dump(self: CpuState, writer: anytype) !void { var i: usize = 0; while (i < 32 - 3) : (i += 4) { if (i == 0) { try writer.print("{s:>9}: 0x{x:<16} {s:>9}: 0x{x:<16} {s:>9}: 0x{x:<16} {s:>9}: 0x{x:<16}\n", .{ "pc", self.pc, IntegerRegister.getIntegerRegister(i + 1).getString(), self.x[i + 1], IntegerRegister.getIntegerRegister(i + 2).getString(), self.x[i + 2], IntegerRegister.getIntegerRegister(i + 3).getString(), self.x[i + 3], }); continue; } try writer.print("{s:>9}: 0x{x:<16} {s:>9}: 0x{x:<16} {s:>9}: 0x{x:<16} {s:>9}: 0x{x:<16}\n", .{ IntegerRegister.getIntegerRegister(i).getString(), self.x[i], IntegerRegister.getIntegerRegister(i + 1).getString(), self.x[i + 1], IntegerRegister.getIntegerRegister(i + 2).getString(), self.x[i + 2], IntegerRegister.getIntegerRegister(i + 3).getString(), self.x[i + 3], }); } try writer.print("privilege: {s} - mhartid: {} - machine interrupts: {} - super interrupts: {}\n", .{ @tagName(self.privilege_level), self.mhartid, self.machine_interrupts_enabled, self.supervisor_interrupts_enabled, }); try writer.print("super interrupts prior: {} - super previous privilege: {s}\n", .{ self.supervisor_interrupts_enabled_prior, @tagName(self.supervisor_previous_privilege_level), }); try writer.print("machine interrupts prior: {} - machine previous privilege: {s}\n", .{ self.machine_interrupts_enabled_prior, @tagName(self.machine_previous_privilege_level), }); try writer.print("mcause: {x} - machine exception pc: 0x{x} - machine trap value {}\n", .{ self.mcause.backing, self.mepc, self.mtval, }); try writer.print("scause: {x} - super exception pc: 0x{x} - super trap value {}\n", .{ self.scause.backing, self.sepc, self.stval, }); try writer.print("address mode: {s} - asid: {} - ppn address: 0x{x}\n", .{ @tagName(self.address_translation_mode), self.asid, self.ppn_address, }); try writer.print("medeleg: 0b{b:0>64}\n", .{self.medeleg}); try writer.print("mideleg: 0b{b:0>64}\n", .{self.mideleg}); try writer.print("mie: 0b{b:0>64}\n", .{self.mie}); try writer.print("mip: 0b{b:0>64}\n", .{self.mip}); try writer.print("machine vector mode: {s} machine vector base address: 0x{x}\n", .{ @tagName(self.machine_vector_mode), self.machine_vector_base_address, }); try writer.print("super vector mode: {s} super vector base address: 0x{x}\n", .{ @tagName(self.supervisor_vector_mode), self.supervisor_vector_base_address, }); try writer.print("dirty state: {} - floating point: {s} - extension: {s}\n", .{ self.state_dirty, @tagName(self.floating_point_status), @tagName(self.extension_status), }); try writer.print("modify privilege: {} - super user access: {} - execute readable: {}\n", .{ self.modify_privilege, self.supervisor_user_memory_access, self.executable_readable, }); try writer.print("trap virtual memory: {} - timeout wait: {} - trap sret: {}\n", .{ self.trap_virtual_memory, self.timeout_wait, self.trap_sret, }); } comptime { std.testing.refAllDecls(@This()); }
lib/CpuState.zig
const std = @import("std"); const sdk = @import("sdk"); const surface = @import("surface.zig"); const mods = @import("mods.zig"); const hud = @import("hud.zig"); pub const THud = struct { pub const Part = union(enum) { text: []u8, component: struct { mod: []u8, name: []u8, format: [:0]u8, }, color: ?sdk.Color, align_: u32, }; pub const Line = struct { color: sdk.Color, parts: []Part, }; arena: std.heap.ArenaAllocator.State, font: surface.Font, spacing: f32, padding: f32, lines: []Line, fn evalLine(self: *THud, slot: u8, line: Line, draw_pos: ?std.meta.Vector(2, f32)) !f32 { _ = self; var width: f32 = 0; var align_base: f32 = 0; if (draw_pos != null) surface.setColor(line.color); for (line.parts) |p| switch (p) { .text => |str| { if (draw_pos) |pos| surface.drawText(self.font, pos + std.meta.Vector(2, f32){ width, 0 }, str); width += surface.getTextLength(self.font, str); }, .component => |info| { if (mods.getMod(info.mod)) |mod| { if (mod.thud_components.get(info.name)) |comp| { var buf: [64]u8 = undefined; const size = comp.call(info.mod, slot, info.format, &buf, buf.len); var str: []u8 = undefined; if (size <= 64) { str = buf[0..size]; } else { str = try allocator.alloc(u8, size); _ = comp.call(info.mod, slot, info.format, str.ptr, buf.len); } if (draw_pos) |pos| surface.drawText(self.font, pos + std.meta.Vector(2, f32){ width, 0 }, str); width += surface.getTextLength(self.font, str); if (size > 64) allocator.free(str); } } }, .color => |c| if (draw_pos != null) surface.setColor(c orelse line.color), .align_ => |x| { width = std.math.max(width, @intToFloat(f32, x) + align_base); align_base = width; }, }; return width; } pub fn calcSize(self: *THud, slot: u8) std.meta.Vector(2, f32) { var width: f32 = 0; var height: f32 = 0; for (self.lines) |line, i| { if (i > 0) height += self.spacing; height += surface.getFontHeight(self.font); const w = self.evalLine(slot, line, null) catch 0; // TODO if (w > width) width = w; } return std.meta.Vector(2, f32){ width + self.padding * 2, height + self.padding * 2, }; } pub fn draw(self: *THud, slot: u8) void { const size = self.calcSize(slot); surface.setColor(.{ .r = 0, .g = 0, .b = 0, .a = 192 }); surface.fillRect(std.meta.Vector(2, f32){ 0, 0 }, size); const x = self.padding; var y = self.padding; for (self.lines) |line, i| { _ = self.evalLine(slot, line, std.meta.Vector(2, f32){ x, y }) catch {}; // TODO y += surface.getFontHeight(self.font); if (i > 0) y += self.spacing; } } }; fn Parser(comptime Reader: type) type { return struct { allocator: std.mem.Allocator, reader: Reader, peeked: ?u8 = null, const Self = @This(); fn peek(self: *Self) !u8 { if (self.peeked == null) self.peeked = try self.reader.readByte(); return self.peeked.?; } fn next(self: *Self) !u8 { const c = self.peek(); self.peeked = null; return c; } pub fn parse(self: *Self) ![]THud.Part { var parts = std.ArrayList(THud.Part).init(self.allocator); var str = std.ArrayList(u8).init(self.allocator); while (true) { const c = self.next() catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; if (c == '{') { if ((try self.peek()) == '{') { _ = self.next() catch unreachable; try str.append('{'); } else { if (str.items.len > 0) try parts.append(.{ .text = str.toOwnedSlice() }); try parts.append(try self.parseExpansion()); } } else { try str.append(c); } } if (str.items.len > 0) try parts.append(.{ .text = str.toOwnedSlice() }); return parts.toOwnedSlice(); } fn parseExpansion(self: *Self) !THud.Part { var mod = std.ArrayList(u8).init(self.allocator); defer mod.deinit(); var c = try self.next(); while (c != '.') { if (c < 'a' and c > 'z' and c != '-') return error.BadModName; try mod.append(c); c = try self.next(); } var component = std.ArrayList(u8).init(self.allocator); defer component.deinit(); c = try self.next(); while (c != ':' and c != '}') { if (c < 'a' and c > 'z' and c != '-') return error.BadComponentName; try component.append(c); c = try self.next(); } var format = std.ArrayList(u8).init(self.allocator); defer format.deinit(); if (c == ':') { c = try self.next(); while (c != '}') { try format.append(c); c = try self.next(); } } if (mod.items.len > 0) { const format1 = try format.toOwnedSliceSentinel(0); return THud.Part{ .component = .{ .mod = mod.toOwnedSlice(), .name = component.toOwnedSlice(), .format = format1, } }; } // Built-in expansion if (std.mem.eql(u8, component.items, "color")) { if (std.mem.eql(u8, format.items, "reset")) { return THud.Part{ .color = null }; } return THud.Part{ .color = try parseColor(format.items) }; } if (std.mem.eql(u8, component.items, "align")) { const x = parseUint(format.items) catch return error.BadAlign; return THud.Part{ .align_ = x }; } return error.UnknownExpansion; } fn parseColor(col: []const u8) !sdk.Color { if (col.len == 3) { const r = (try parseColorChar(col[0])) * 17; const g = (try parseColorChar(col[1])) * 17; const b = (try parseColorChar(col[2])) * 17; return sdk.Color{ .r = r, .g = g, .b = b }; } else if (col.len == 6) { const r = (try parseColorChar(col[0])) * 16 + (try parseColorChar(col[1])); const g = (try parseColorChar(col[2])) * 16 + (try parseColorChar(col[3])); const b = (try parseColorChar(col[4])) * 16 + (try parseColorChar(col[5])); return sdk.Color{ .r = r, .g = g, .b = b }; } else { return error.BadColor; } } fn parseColorChar(c: u8) !u8 { if (c >= '0' and c <= '9') return c - '0'; if (c >= 'a' and c <= 'f') return 10 + c - 'a'; if (c >= 'A' and c <= 'F') return 10 + c - 'A'; return error.BadColor; } fn parseUint(str: []const u8) !u32 { var x: u32 = 0; for (str) |c| { if (c < '0' and c > '9') return error.BadInt; x *= 10; x += c - '0'; } return x; } }; } fn parser(allocator1: std.mem.Allocator, r: anytype) Parser(@TypeOf(r)) { return .{ .allocator = allocator1, .reader = r }; } var thuds: []hud.Hud(THud) = undefined; var allocator: std.mem.Allocator = undefined; pub fn init(allocator1: std.mem.Allocator) !void { @setEvalBranchQuota(10000); allocator = allocator1; const RawInfo = struct { font_name: []u8, font_size: f32, color: [4]u8, spacing: f32, padding: f32, screen_anchor: [2]f32, hud_anchor: [2]f32, pix_off: [2]i32, scale: f32, lines: [][]u8, }; var parse_arena = std.heap.ArenaAllocator.init(allocator); defer parse_arena.deinit(); var file_contents = try std.fs.cwd().readFileAlloc(allocator, "thud.json", std.math.maxInt(usize)); defer allocator.free(file_contents); const cfg = try std.json.parse([]RawInfo, &std.json.TokenStream.init(file_contents), .{ .allocator = parse_arena.allocator() }); var huds = std.ArrayList(hud.Hud(THud)).init(allocator); defer { for (huds.items) |h| h.ctx.arena.promote(allocator).deinit(); huds.deinit(); } for (cfg) |raw| { var arena = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); var lines = std.ArrayList(THud.Line).init(arena.allocator()); for (raw.lines) |line| { var s = std.io.fixedBufferStream(line); const parts = try parser(arena.allocator(), s.reader()).parse(); try lines.append(.{ .color = .{ .r = raw.color[0], .g = raw.color[1], .b = raw.color[2], .a = raw.color[3], }, .parts = parts, }); } const name = try arena.allocator().dupeZ(u8, raw.font_name); try huds.append(.{ .ctx = .{ .arena = arena.state, .font = .{ .name = name, .tall = raw.font_size, }, .spacing = raw.spacing, .padding = raw.padding, .lines = lines.toOwnedSlice(), }, .screen_anchor = std.meta.Vector(2, f32){ raw.screen_anchor[0], raw.screen_anchor[1] }, .hud_anchor = std.meta.Vector(2, f32){ raw.hud_anchor[0], raw.hud_anchor[1] }, .pix_off = std.meta.Vector(2, i32){ raw.pix_off[0], raw.pix_off[1] }, .scale = raw.scale, }); } thuds = huds.toOwnedSlice(); } pub fn deinit() void { for (thuds) |*h| h.ctx.arena.promote(allocator).deinit(); allocator.free(thuds); } pub fn drawAll(slot: u8) void { for (thuds) |*h| h.draw(slot); }
src/thud.zig
const common = @import("common.zig"); const rom = @import("rom.zig"); const std = @import("std"); const fs = std.fs; const io = std.io; const math = std.math; const mem = std.mem; const os = std.os; const gba = rom.gba; const li16 = rom.int.li16; const li32 = rom.int.li32; const lu16 = rom.int.lu16; const lu32 = rom.int.lu32; const lu64 = rom.int.lu64; pub const encodings = @import("gen3/encodings.zig"); pub const offsets = @import("gen3/offsets.zig"); pub const script = @import("gen3/script.zig"); comptime { std.testing.refAllDecls(@This()); } pub const Language = enum { en_us, }; pub fn Ptr(comptime P: type) type { return rom.ptr.RelativePointer(P, u32, .Little, 0x8000000, 0); } pub fn Slice(comptime S: type) type { return rom.ptr.RelativeSlice(S, u32, .Little, .len_first, 0x8000000); } pub const BasePokemon = extern struct { stats: common.Stats, types: [2]u8, catch_rate: u8, base_exp_yield: u8, ev_yield: common.EvYield, items: [2]lu16, gender_ratio: u8, egg_cycles: u8, base_friendship: u8, growth_rate: common.GrowthRate, egg_groups: [2]common.EggGroup, abilities: [2]u8, safari_zone_rate: u8, color: common.Color, padding: [2]u8, comptime { std.debug.assert(@sizeOf(@This()) == 28); } }; pub const Gender = enum(u1) { male = 0, female = 1, }; pub const Trainer = extern struct { party_type: common.PartyType, class: u8, encounter_music: packed struct { music: u7, gender: Gender, }, trainer_picture: u8, name: [12]u8, items: [4]lu16, is_double: lu32, ai: lu32, party: Party, comptime { std.debug.assert(@sizeOf(@This()) == 40); } pub fn partyBytes(trainer: Trainer, data: []u8) ![]u8 { return switch (trainer.party_type) { .none => mem.sliceAsBytes(try trainer.party.none.toSlice(data)), .item => mem.sliceAsBytes(try trainer.party.item.toSlice(data)), .moves => mem.sliceAsBytes(try trainer.party.moves.toSlice(data)), .both => mem.sliceAsBytes(try trainer.party.both.toSlice(data)), }; } pub fn partyAt(trainer: Trainer, index: usize, data: []u8) !*PartyMemberBase { return switch (trainer.party_type) { .none => &(try trainer.party.none.toSlice(data))[index].base, .item => &(try trainer.party.item.toSlice(data))[index].base, .moves => &(try trainer.party.moves.toSlice(data))[index].base, .both => &(try trainer.party.both.toSlice(data))[index].base, }; } pub fn partyLen(trainer: Trainer) u8 { return switch (trainer.party_type) { .none => @intCast(u8, trainer.party.none.len()), .item => @intCast(u8, trainer.party.item.len()), .moves => @intCast(u8, trainer.party.moves.len()), .both => @intCast(u8, trainer.party.both.len()), }; } }; pub const Party = packed union { none: Slice([]PartyMemberNone), item: Slice([]PartyMemberItem), moves: Slice([]PartyMemberMoves), both: Slice([]PartyMemberBoth), pub fn memberSize(party_type: common.PartyType) usize { return switch (party_type) { .none => @sizeOf(PartyMemberNone), .item => @sizeOf(PartyMemberItem), .moves => @sizeOf(PartyMemberMoves), .both => @sizeOf(PartyMemberBoth), }; } comptime { std.debug.assert(@sizeOf(@This()) == 8); } }; pub const PartyMemberBase = extern struct { iv: lu16 = lu16.init(0), level: lu16 = lu16.init(0), species: lu16 = lu16.init(0), comptime { std.debug.assert(@sizeOf(@This()) == 6); } pub fn toParent(base: *PartyMemberBase, comptime Parent: type) *Parent { return @fieldParentPtr(Parent, "base", base); } }; pub const PartyMemberNone = extern struct { base: PartyMemberBase = PartyMemberBase{}, pad: lu16 = lu16.init(0), comptime { std.debug.assert(@sizeOf(@This()) == 8); } }; pub const PartyMemberItem = extern struct { base: PartyMemberBase = PartyMemberBase{}, item: lu16 = lu16.init(0), comptime { std.debug.assert(@sizeOf(@This()) == 8); } }; pub const PartyMemberMoves = extern struct { base: PartyMemberBase = PartyMemberBase{}, pad: lu16 = lu16.init(0), moves: [4]lu16 = [_]lu16{lu16.init(0)} ** 4, comptime { std.debug.assert(@sizeOf(@This()) == 16); } }; pub const PartyMemberBoth = extern struct { base: PartyMemberBase = PartyMemberBase{}, item: lu16 = lu16.init(0), moves: [4]lu16 = [_]lu16{lu16.init(0)} ** 4, comptime { std.debug.assert(@sizeOf(@This()) == 16); } }; pub const Move = extern struct { effect: u8, power: u8, type: u8, accuracy: u8, pp: u8, side_effect_chance: u8, target: u8, priority: u8, flags0: u8, flags1: u8, flags2: u8, // The last byte is normally unused, but there exists patches // to make this last byte define the moves category (phys/spec/status). category: common.MoveCategory, comptime { std.debug.assert(@sizeOf(@This()) == 12); } }; pub const FRLGPocket = enum(u8) { none = 0x00, items = 0x01, key_items = 0x02, poke_balls = 0x03, tms_hms = 0x04, berries = 0x05, }; pub const RSEPocket = enum(u8) { none = 0x00, items = 0x01, poke_balls = 0x02, tms_hms = 0x03, berries = 0x04, key_items = 0x05, }; pub const Pocket = packed union { frlg: FRLGPocket, rse: RSEPocket, }; pub const Item = extern struct { name: [14]u8, id: lu16, price: lu16, battle_effect: u8, battle_effect_param: u8, description: Ptr([*:0xff]u8), importance: u8, unknown: u8, pocket: Pocket, type: u8, field_use_func: Ptr(*u8), battle_usage: lu32, battle_use_func: Ptr(*u8), secondary_id: lu32, comptime { std.debug.assert(@sizeOf(@This()) == 44); } }; pub const LevelUpMove = packed struct { id: u9, level: u7, pub const term = LevelUpMove{ .id = math.maxInt(u9), .level = math.maxInt(u7), }; comptime { std.debug.assert(@sizeOf(@This()) == 2); } }; pub const EmeraldPokedexEntry = extern struct { category_name: [12]u8, height: lu16, weight: lu16, description: Ptr([*]u8), unused: lu16, pokemon_scale: lu16, pokemon_offset: li16, trainer_scale: lu16, trainer_offset: li16, padding: lu16, comptime { std.debug.assert(@sizeOf(@This()) == 32); } }; pub const RSFrLgPokedexEntry = extern struct { category_name: [12]u8, height: lu16, weight: lu16, description: Ptr([*]u8), unused_description: Ptr([*]u8), unused: lu16, pokemon_scale: lu16, pokemon_offset: li16, trainer_scale: lu16, trainer_offset: li16, padding: lu16, comptime { std.debug.assert(@sizeOf(@This()) == 36); } }; pub const Pokedex = union { emerald: []EmeraldPokedexEntry, rsfrlg: []RSFrLgPokedexEntry, }; pub const WildPokemon = extern struct { min_level: u8, max_level: u8, species: lu16, comptime { std.debug.assert(@sizeOf(@This()) == 4); } }; pub fn WildPokemonInfo(comptime len: usize) type { return extern struct { encounter_rate: u8, pad: [3]u8, wild_pokemons: Ptr(*[len]WildPokemon), comptime { std.debug.assert(@sizeOf(@This()) == 8); } }; } pub const WildPokemonHeader = extern struct { map_group: u8, map_num: u8, pad: [2]u8, land: Ptr(*WildPokemonInfo(12)), surf: Ptr(*WildPokemonInfo(5)), rock_smash: Ptr(*WildPokemonInfo(5)), fishing: Ptr(*WildPokemonInfo(10)), comptime { std.debug.assert(@sizeOf(@This()) == 20); } }; pub const Evolution = extern struct { method: common.EvoMethod, padding1: u8, param: lu16, target: lu16, padding2: [2]u8, comptime { std.debug.assert(@sizeOf(Evolution) == 8); } }; pub const MapHeader = extern struct { map_layout: Ptr(*MapLayout), map_events: Ptr(*MapEvents), map_scripts: Ptr([*]MapScript), map_connections: Ptr(*anyopaque), music: lu16, map_data_id: lu16, map_sec: u8, cave: u8, weather: u8, map_type: u8, pad: u8, escape_rope: u8, flags: Flags, map_battle_scene: u8, pub const Flags = packed struct { allow_cycling: bool, allow_escaping: bool, allow_running: bool, show_map_name: bool, unused: u4, comptime { std.debug.assert(@sizeOf(@This()) == 1); } }; comptime { std.debug.assert(@sizeOf(@This()) == 28); } }; pub const MapLayout = extern struct { width: li32, height: li32, border: Ptr(*lu16), map: Ptr(*lu16), primary_tileset: Ptr(*Tileset), secondary_tileset: Ptr(*Tileset), comptime { std.debug.assert(@sizeOf(@This()) == 24); } }; pub const Tileset = extern struct { is_compressed: u8, is_secondary: u8, padding: [2]u8, tiles: Ptr(*anyopaque), palettes: Ptr(*anyopaque), metatiles: Ptr(*lu16), metatiles_attributes: Ptr(*[512]lu16), callback: Ptr(*anyopaque), comptime { std.debug.assert(@sizeOf(@This()) == 24); } }; pub const MapEvents = extern struct { obj_events_len: u8, warps_len: u8, coord_events_len: u8, bg_events_len: u8, obj_events: Ptr([*]ObjectEvent), warps: Ptr([*]Warp), coord_events: Ptr([*]CoordEvent), bg_events: Ptr([*]BgEvent), comptime { std.debug.assert(@sizeOf(@This()) == 20); } }; pub const ObjectEvent = extern struct { index: u8, gfx: u8, replacement: u8, pad1: u8, x: lu16, y: lu16, evelavtion: u8, movement_type: u8, radius: Point, pad2: u8, trainer_type: lu16, sight_radius_tree_etc: lu16, script: Ptr(?[*]u8), event_flag: lu16, pad3: [2]u8, pub const Point = packed struct { y: u4, x: u4, }; comptime { std.debug.assert(@sizeOf(@This()) == 24); } }; pub const Warp = extern struct { x: lu16, y: lu16, byte: u8, warp: u8, map_num: u8, map_group: u8, comptime { std.debug.assert(@sizeOf(@This()) == 8); } }; pub const CoordEvent = extern struct { x: lu16, y: lu16, elevation: u8, pad1: u8, trigger: lu16, index: lu16, pad2: [2]u8, scripts: Ptr([*]u8), comptime { std.debug.assert(@sizeOf(@This()) == 16); } }; pub const BgEvent = extern struct { x: lu16, y: lu16, elevation: u8, kind: u8, pad: [2]u8, unknown: [4]u8, comptime { std.debug.assert(@sizeOf(@This()) == 12); } }; pub const MapScript = extern struct { @"type": u8, addr: packed union { @"0": void, @"2": Ptr([*]MapScript2), other: Ptr([*]u8), }, comptime { std.debug.assert(@sizeOf(@This()) == 5); } }; pub const MapScript2 = extern struct { word1: lu16, word2: lu16, addr: Ptr([*]u8), comptime { std.debug.assert(@sizeOf(@This()) == 8); } }; const StaticPokemon = struct { species: *lu16, level: *u8, }; const PokeballItem = struct { item: *lu16, amount: *lu16, }; const TrainerParty = struct { size: u32 = 0, members: [6]PartyMemberBoth = [_]PartyMemberBoth{PartyMemberBoth{}} ** 6, }; pub const Game = struct { allocator: mem.Allocator, version: common.Version, free_offset: usize, data: []u8, // These fields are owned by the game and will be applied to // the rom oppon calling `apply`. trainer_parties: []TrainerParty, // All these fields point into data header: *gba.Header, starters: [3]*lu16, starters_repeat: [3]*lu16, text_delays: []u8, trainers: []Trainer, moves: []Move, machine_learnsets: []lu64, pokemons: []BasePokemon, evolutions: [][5]Evolution, level_up_learnset_pointers: []Ptr([*]LevelUpMove), hms: []lu16, tms: []lu16, items: []Item, pokedex: Pokedex, species_to_national_dex: []lu16, wild_pokemon_headers: []WildPokemonHeader, map_headers: []MapHeader, pokemon_names: [][11]u8, ability_names: [][13]u8, move_names: [][13]u8, type_names: [][7]u8, static_pokemons: []StaticPokemon, given_pokemons: []StaticPokemon, pokeball_items: []PokeballItem, text: []*Ptr([*:0xff]u8), pub fn identify(reader: anytype) !offsets.Info { const header = try reader.readStruct(gba.Header); for (offsets.infos) |info| { if (!mem.eql(u8, info.game_title.span(), header.game_title.span())) continue; if (!mem.eql(u8, &info.gamecode, &header.gamecode)) continue; try header.validate(); return info; } return error.UnknownGame; } pub fn fromFile(file: fs.File, allocator: mem.Allocator) !Game { const reader = file.reader(); const info = try identify(reader); const size = try file.getEndPos(); try file.seekTo(0); if (size % 0x1000000 != 0 or size > 1024 * 1024 * 32) return error.InvalidRomSize; const gba_rom = try allocator.alloc(u8, 1024 * 1024 * 32); errdefer allocator.free(gba_rom); const free_offset = try reader.readAll(gba_rom); mem.set(u8, gba_rom[free_offset..], 0xff); const trainers = info.trainers.slice(gba_rom); const trainer_parties = try allocator.alloc(TrainerParty, trainers.len); mem.set(TrainerParty, trainer_parties, TrainerParty{}); for (trainer_parties) |*party, i| { party.size = trainers[i].partyLen(); var j: usize = 0; while (j < party.size) : (j += 1) { const base = try trainers[i].partyAt(j, gba_rom); party.members[j].base = base.*; switch (trainers[i].party_type) { .none => {}, .item => party.members[j].item = base.toParent(PartyMemberItem).item, .moves => party.members[j].moves = base.toParent(PartyMemberMoves).moves, .both => { const member = base.toParent(PartyMemberBoth); party.members[j].item = member.item; party.members[j].moves = member.moves; }, } } } const ScriptData = struct { // These keep track of the pointer to what VAR_0x8000 and VAR_0x8001 // was last set to by the script. This variables are used by callstd // to give and optain items. VAR_0x8000: ?*lu16 = null, VAR_0x8001: ?*lu16 = null, static_pokemons: std.ArrayList(StaticPokemon), given_pokemons: std.ArrayList(StaticPokemon), pokeball_items: std.ArrayList(PokeballItem), text: std.ArrayList(*Ptr([*:0xff]u8)), fn processCommand(script_data: *@This(), gba_data: []u8, command: *script.Command) !void { const tag = command.tag; const data = command.data(); switch (tag) { .setwildbattle => try script_data.static_pokemons.append(.{ .species = &data.setwildbattle.species, .level = &data.setwildbattle.level, }), .givemon => try script_data.given_pokemons.append(.{ .species = &data.givemon.species, .level = &data.givemon.level, }), .setorcopyvar => { if (data.setorcopyvar.destination.value() == 0x8000) script_data.VAR_0x8000 = &data.setorcopyvar.source; if (data.setorcopyvar.destination.value() == 0x8001) script_data.VAR_0x8001 = &data.setorcopyvar.source; }, .callstd => switch (data.callstd.function) { script.STD_OBTAIN_ITEM, script.STD_FIND_ITEM => { try script_data.pokeball_items.append(PokeballItem{ .item = script_data.VAR_0x8000 orelse return, .amount = script_data.VAR_0x8001 orelse return, }); }, else => {}, }, .loadword => switch (data.loadword.destination) { 0 => { _ = data.loadword.value.toSliceZ(gba_data) catch return; try script_data.text.append(&data.loadword.value); }, else => {}, }, .message => { _ = data.message.text.toSliceZ(gba_data) catch return; try script_data.text.append(&data.message.text); }, else => {}, } } fn deinit(data: @This()) void { data.static_pokemons.deinit(); data.given_pokemons.deinit(); data.pokeball_items.deinit(); data.text.deinit(); } }; var script_data = ScriptData{ .static_pokemons = std.ArrayList(StaticPokemon).init(allocator), .given_pokemons = std.ArrayList(StaticPokemon).init(allocator), .pokeball_items = std.ArrayList(PokeballItem).init(allocator), .text = std.ArrayList(*Ptr([*:0xff]u8)).init(allocator), }; errdefer script_data.deinit(); const map_headers = info.map_headers.slice(gba_rom); @setEvalBranchQuota(100000); for (map_headers) |map_header| { const scripts = try map_header.map_scripts.toSliceEnd(gba_rom); for (scripts) |s| { if (s.@"type" == 0) break; if (s.@"type" == 2 or s.@"type" == 4) continue; const script_bytes = try s.addr.other.toSliceEnd(gba_rom); var decoder = script.CommandDecoder{ .bytes = script_bytes }; while (try decoder.next()) |command| try script_data.processCommand(gba_rom, command); } const events = try map_header.map_events.toPtr(gba_rom); for (try events.obj_events.toSlice(gba_rom, events.obj_events_len)) |obj_event| { const script_bytes = obj_event.script.toSliceEnd(gba_rom) catch continue; var decoder = script.CommandDecoder{ .bytes = script_bytes }; while (try decoder.next()) |command| try script_data.processCommand(gba_rom, command); } for (try events.coord_events.toSlice(gba_rom, events.coord_events_len)) |coord_event| { const script_bytes = coord_event.scripts.toSliceEnd(gba_rom) catch continue; var decoder = script.CommandDecoder{ .bytes = script_bytes }; while (try decoder.next()) |command| try script_data.processCommand(gba_rom, command); } for (try events.obj_events.toSlice(gba_rom, events.obj_events_len)) |obj_event| { const script_bytes = obj_event.script.toSliceEnd(gba_rom) catch continue; var decoder = script.CommandDecoder{ .bytes = script_bytes }; while (try decoder.next()) |command| try script_data.processCommand(gba_rom, command); } } return Game{ .version = info.version, .allocator = allocator, .free_offset = free_offset, .data = gba_rom, .trainer_parties = trainer_parties, .header = @ptrCast(*gba.Header, &gba_rom[0]), .starters = [_]*lu16{ info.starters[0].ptr(gba_rom), info.starters[1].ptr(gba_rom), info.starters[2].ptr(gba_rom), }, .starters_repeat = [3]*lu16{ info.starters_repeat[0].ptr(gba_rom), info.starters_repeat[1].ptr(gba_rom), info.starters_repeat[2].ptr(gba_rom), }, .text_delays = info.text_delays.slice(gba_rom), .trainers = trainers, .moves = info.moves.slice(gba_rom), .machine_learnsets = info.machine_learnsets.slice(gba_rom), .pokemons = info.pokemons.slice(gba_rom), .evolutions = info.evolutions.slice(gba_rom), .level_up_learnset_pointers = info.level_up_learnset_pointers.slice(gba_rom), .hms = info.hms.slice(gba_rom), .tms = info.tms.slice(gba_rom), .items = info.items.slice(gba_rom), .pokedex = switch (info.version) { .emerald => .{ .emerald = info.pokedex.emerald.slice(gba_rom) }, .ruby, .sapphire, .fire_red, .leaf_green, => .{ .rsfrlg = info.pokedex.rsfrlg.slice(gba_rom) }, else => unreachable, }, .species_to_national_dex = info.species_to_national_dex.slice(gba_rom), .wild_pokemon_headers = info.wild_pokemon_headers.slice(gba_rom), .pokemon_names = info.pokemon_names.slice(gba_rom), .ability_names = info.ability_names.slice(gba_rom), .move_names = info.move_names.slice(gba_rom), .type_names = info.type_names.slice(gba_rom), .map_headers = map_headers, .static_pokemons = script_data.static_pokemons.toOwnedSlice(), .given_pokemons = script_data.given_pokemons.toOwnedSlice(), .pokeball_items = script_data.pokeball_items.toOwnedSlice(), .text = script_data.text.toOwnedSlice(), }; } pub fn apply(game: *Game) !void { try game.applyTrainerParties(); } fn applyTrainerParties(game: *Game) !void { const trainer_parties = game.trainer_parties; const trainers = game.trainers; for (trainer_parties) |party, i| { const trainer = &trainers[i]; const party_bytes = try trainer.partyBytes(game.data); const party_type = trainer.party_type; const party_size = party.size * Party.memberSize(party_type); if (party_size == 0) { const p = &trainer.party.none; p.inner.len = lu32.init(party.size); continue; } const bytes = if (party_bytes.len < party_size) try game.requestFreeBytes(party_size) else party_bytes; const writer = io.fixedBufferStream(bytes).writer(); for (party.members[0..party.size]) |member| { switch (party_type) { .none => writer.writeAll(&mem.toBytes(PartyMemberNone{ .base = member.base, })) catch unreachable, .item => writer.writeAll(&mem.toBytes(PartyMemberItem{ .base = member.base, .item = member.item, })) catch unreachable, .moves => writer.writeAll(&mem.toBytes(PartyMemberMoves{ .base = member.base, .moves = member.moves, })) catch unreachable, .both => writer.writeAll(&mem.toBytes(member)) catch unreachable, } } const p = &trainer.party.none; p.inner.ptr.inner = (try Ptr([*]u8).init(bytes.ptr, game.data)).inner; p.inner.len = lu32.init(party.size); } } pub fn write(game: Game, writer: anytype) !void { try game.header.validate(); try writer.writeAll(game.data); } pub fn requestFreeBytes(game: *Game, size: usize) ![]u8 { const Range = struct { start: usize, end: usize }; for ([_]Range{ .{ .start = game.free_offset, .end = game.data.len }, .{ .start = 0, .end = game.free_offset }, }) |range| { var i = mem.alignForward(range.start, 4); outer: while (i + size <= range.end) : (i += 4) { // We ensure that the byte before our start byte is // also 0xff. This is because we want to ensure that // data that is terminated with 0xff does not get // its terminator given away as free space. const prev_byte = if (i == 0) 0xff else game.data[i - 1]; if (prev_byte != 0xff) continue :outer; const res = game.data[i..][0..size]; for (res) |b| { if (b != 0xff) continue :outer; } game.free_offset = i + size; return res; } } return error.NoFreeSpaceAvailable; } pub fn deinit(game: Game) void { game.allocator.free(game.data); game.allocator.free(game.static_pokemons); game.allocator.free(game.given_pokemons); game.allocator.free(game.pokeball_items); game.allocator.free(game.trainer_parties); } };
src/core/gen3.zig
usingnamespace @import("root").preamble; const build_options = @import("build_options"); const copernicus_data = @embedFile(build_options.copernicus_path); const process = os.kernel.process; const blob = copernicus_data[32..]; const text_base = std.mem.readIntLittle(usize, copernicus_data[0..8]); const text_size = data_offset; const text_offset = 0; const text = copernicus_data[32 + text_offset ..][0..text_size]; const data_base = text_base + text_size; const data_size = rodata_offset - data_offset; const data_offset = std.mem.readIntLittle(usize, copernicus_data[8..16]); const data = copernicus_data[32 + data_offset ..][0..data_size]; const rodata_base = data_base + data_size; const rodata_size = blob.len - rodata_offset; const rodata_offset = std.mem.readIntLittle(usize, copernicus_data[16..24]); const rodata = copernicus_data[32 + rodata_offset ..][0..rodata_size]; var copernicus_text_obj = process.memory_object.staticMemoryObject(@as([]const u8, text), os.memory.paging.rx()); var copernicus_data_obj = process.memory_object.staticMemoryObject(@as([]const u8, data), os.memory.paging.rw()); var copernicus_rodata_obj = process.memory_object.staticMemoryObject(@as([]const u8, rodata), os.memory.paging.ro()); comptime { if (text_size == 0) { @compileError("No copernicus text section"); } } pub fn map(addr_space: *process.address_space.AddrSpace) !usize { try addr_space.allocateAt(text_base, text_size); _ = try addr_space.lazyMap(text_base, text_size, try copernicus_text_obj.makeRegion()); errdefer addr_space.freeAndUnmap(text_base, text_size); if (data_size > 0) { try addr_space.allocateAt(data_base, data_size); _ = try addr_space.lazyMap(data_base, data_size, try copernicus_data_obj.makeRegion()); errdefer addr_space.freeAndUnmap(data_base, data_size); } if (rodata_size > 0) { try addr_space.allocateAt(rodata_base, rodata_size); _ = try addr_space.lazyMap(rodata_base, rodata_size, try copernicus_rodata_obj.makeRegion()); errdefer addr_space.freeAndUnmap(rodata_base, rodata_size); } return text_base; }
subprojects/flork/src/kernel/copernicus.zig
const c = @import("c.zig"); const nk = @import("../nuklear.zig"); const std = @import("std"); const mem = std.mem; const testing = std.testing; pub const Colors = enum(u8) { text = c.NK_COLOR_TEXT, window = c.NK_COLOR_WINDOW, header = c.NK_COLOR_HEADER, border = c.NK_COLOR_BORDER, button = c.NK_COLOR_BUTTON, button_hover = c.NK_COLOR_BUTTON_HOVER, button_active = c.NK_COLOR_BUTTON_ACTIVE, toggle = c.NK_COLOR_TOGGLE, toggle_hover = c.NK_COLOR_TOGGLE_HOVER, toggle_cursor = c.NK_COLOR_TOGGLE_CURSOR, select = c.NK_COLOR_SELECT, select_active = c.NK_COLOR_SELECT_ACTIVE, slider = c.NK_COLOR_SLIDER, slider_cursor = c.NK_COLOR_SLIDER_CURSOR, slider_cursor_hover = c.NK_COLOR_SLIDER_CURSOR_HOVER, slider_cursor_active = c.NK_COLOR_SLIDER_CURSOR_ACTIVE, property = c.NK_COLOR_PROPERTY, edit = c.NK_COLOR_EDIT, edit_cursor = c.NK_COLOR_EDIT_CURSOR, combo = c.NK_COLOR_COMBO, chart = c.NK_COLOR_CHART, chart_color = c.NK_COLOR_CHART_COLOR, chart_color_highlight = c.NK_COLOR_CHART_COLOR_HIGHLIGHT, scrollbar = c.NK_COLOR_SCROLLBAR, scrollbar_cursor = c.NK_COLOR_SCROLLBAR_CURSOR, scrollbar_cursor_hover = c.NK_COLOR_SCROLLBAR_CURSOR_HOVER, scrollbar_cursor_active = c.NK_COLOR_SCROLLBAR_CURSOR_ACTIVE, tab_header = c.NK_COLOR_TAB_HEADER, fn toNuklear(color: Colors) c.enum_nk_style_colors { return @intToEnum(c.enum_nk_style_colors, @enumToInt(color)); } }; pub const ColorArray = std.EnumArray(Colors, nk.Color); pub fn default(ctx: *nk.Context) void { return c.nk_style_default(ctx); } pub fn fromTable(ctx: *nk.Context, table: ColorArray) void { return c.nk_style_from_table(ctx, &table.values); } pub fn loadCursor(ctx: *nk.Context, cursor: nk.StyleCursor, cur: nk.Cursor) void { return c.nk_style_load_cursor(ctx, cursor, &cur); } pub fn loadAllCursors(ctx: *nk.Context, cursors: *const [c.NK_CURSOR_COUNT]nk.Cursor) void { return c.nk_style_load_all_cursors(ctx, nk.discardConst(cursors)); } pub fn getColorByName(color: Colors) [:0]const u8 { const name = getColorByNameZ(color); return mem.spanZ(name); } pub fn getColorByNameZ(color: Colors) [*:0]const u8 { return @ptrCast([*:0]const u8, c.nk_style_get_color_by_name(color.toNuklear())); } pub fn setFont(ctx: *nk.Context, font: *const nk.UserFont) void { return c.nk_style_set_font(ctx, font); } pub fn setCursor(ctx: *nk.Context, u: nk.StyleCursor) bool { return c.nk_style_set_cursor(ctx, u) != 0; } pub fn showCursor(ctx: *nk.Context) void { return c.nk_style_show_cursor(ctx); } pub fn hideCursor(ctx: *nk.Context) void { return c.nk_style_hide_cursor(ctx); } pub fn pushFont(ctx: *nk.Context, font: *const nk.UserFont) bool { return c.nk_style_push_font(ctx, font) != 0; } pub fn popFont(ctx: *nk.Context) bool { return c.nk_style_pop_font(ctx) != 0; } pub fn itemImage(img: nk.Image) nk.StyleItem { return c.nk_style_item_image(img); } pub fn itemColor(y: nk.Color) nk.StyleItem { return c.nk_style_item_color(y); } pub fn itemHide() nk.StyleItem { return c.nk_style_item_hide(); } test { std.testing.refAllDecls(@This()); }
src/style.zig
const std = @import("std"); const bld = std.build; var ldns_path: ?[]const u8 = undefined; var rabbitmq_path: ?[]const u8 = undefined; var ssl_path: ?[]const u8 = undefined; var crypto_path: ?[]const u8 = undefined; var zamqp_path: []const u8 = undefined; var zdns_path: []const u8 = undefined; var version: []const u8 = undefined; pub fn build(b: *bld.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(); ldns_path = b.option([]const u8, "static-ldns", "path to libldns.a"); rabbitmq_path = b.option([]const u8, "static-rabbitmq", "path to librabbitmq.a"); ssl_path = b.option([]const u8, "static-ssl", "path to libssl.a"); crypto_path = b.option([]const u8, "static-crypto", "path to libcrypto.a"); zamqp_path = b.option([]const u8, "zamqp", "path to zamqp.zig") orelse "../zamqp/src/zamqp.zig"; zdns_path = b.option([]const u8, "zdns", "path to zdns.zig") orelse "../zdns/src/zdns.zig"; const version_override = b.option([]const u8, "version", "override version from git describe"); const git_describe_argv = &[_][]const u8{ "git", "-C", b.build_root, "describe", "--dirty", "--abbrev=7", "--tags", "--always", "--first-parent" }; version = version_override orelse std.mem.trim(u8, try b.exec(git_describe_argv), " \n\r"); const server_exe = b.addExecutable("zone2json-server", "src/main.zig"); const server_run_cmd = setupExe(b, server_exe, target, mode); const server_run_step = b.step("run-server", "Run the RPC server"); server_run_step.dependOn(&server_run_cmd.step); const exe = b.addExecutable("zone2json", "src/cli_tool.zig"); const run_cmd = setupExe(b, exe, target, mode); const run_step = b.step("run", "Run the CLI tool"); run_step.dependOn(&run_cmd.step); const test_cmd = b.addTest("src/test.zig"); addDependencies(test_cmd); test_cmd.setTarget(target); test_cmd.setBuildMode(mode); const test_step = b.step("test", "Run tests"); test_step.dependOn(&test_cmd.step); test_step.dependOn(try compareOutput(b, exe)); } fn addDependencies(step: *bld.LibExeObjStep) void { step.linkLibC(); if (ldns_path) |path| { step.addObjectFile(path); } else { step.linkSystemLibrary("ldns"); } if (rabbitmq_path) |path| { step.addObjectFile(path); } else { step.linkSystemLibrary("rabbitmq"); } if (ldns_path != null or rabbitmq_path != null) { if (ssl_path) |path| { step.addObjectFile(path); } else { step.linkSystemLibrary("ssl"); } if (crypto_path) |path| { step.addObjectFile(path); } else { step.linkSystemLibrary("crypto"); } } step.addPackagePath("zamqp", zamqp_path); step.addPackagePath("zdns", zdns_path); } fn setupExe(b: *bld.Builder, exe: *bld.LibExeObjStep, target: std.zig.CrossTarget, mode: std.builtin.Mode) *bld.RunStep { exe.addBuildOption([]const u8, "version", version); // add FreeBSD library paths exe.addIncludeDir("/usr/local/include"); exe.addLibPath("/usr/local/lib"); addDependencies(exe); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } return run_cmd; } pub fn compareOutput(b: *bld.Builder, exe: *bld.LibExeObjStep) !*bld.Step { const dirPath = "test/zones/"; const testDir = try std.fs.cwd().openDirZ(dirPath, .{ .iterate = true }); var it = testDir.iterate(); const step = b.step("compare-output", "Test - Compare output"); while (try it.next()) |file| { if (std.mem.endsWith(u8, file.name, ".zone")) { const run = exe.run(); run.addArg(try std.mem.concat(b.allocator, u8, &[_][]const u8{ dirPath, file.name })); const jsonFileName = try std.mem.concat(b.allocator, u8, &[_][]const u8{ file.name[0 .. file.name.len - "zone".len], "json" }); run.expectStdOutEqual(try testDir.readFileAlloc(b.allocator, jsonFileName, 50 * 1024)); step.dependOn(&run.step); } } return step; }
build.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const info = std.log.info; const print = std.debug.print; const fmt = std.fmt; const utils = @import("utils.zig"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const PassportField = struct { is_set: bool = false, is_ok: bool = false, }; const Passport = struct { byr: PassportField = PassportField{}, iyr: PassportField = PassportField{}, eyr: PassportField = PassportField{}, hgt: PassportField = PassportField{}, hcl: PassportField = PassportField{}, ecl: PassportField = PassportField{}, pid: PassportField = PassportField{}, cid: PassportField = PassportField{}, pub fn empty() Passport { return Passport{}; } pub fn parse_from_line(self: *Passport, allo: *std.mem.Allocator, line: []const u8) !void { const token_separator: [1]u8 = .{' '}; const prop_separator: [1]u8 = .{':'}; var tokens = std.mem.split(line, &token_separator); while (tokens.next()) |token| { var pair = std.mem.split(token, &prop_separator); const key = pair.next() orelse unreachable; const val = pair.next() orelse unreachable; try self.parse_prop(allo, key, val); } } pub fn parse_prop(self: *Passport, allo: *std.mem.Allocator, key: []const u8, val: []const u8) !void { info("parsing prop {} {}", .{ key, val }); if (std.mem.eql(u8, key, "byr")) { self.byr.is_set = true; const num = fmt.parseUnsigned(usize, val, 10) catch { return; }; self.byr.is_ok = (1920 <= num) and (num <= 2002); return; } if (std.mem.eql(u8, key, "iyr")) { self.iyr.is_set = true; const num = fmt.parseUnsigned(usize, val, 10) catch { return; }; self.iyr.is_ok = (2010 <= num) and (num <= 2020); return; } if (std.mem.eql(u8, key, "eyr")) { self.eyr.is_set = true; const num = fmt.parseUnsigned(usize, val, 10) catch { return; }; self.eyr.is_ok = (2020 <= num) and (num <= 2030); return; } if (std.mem.eql(u8, key, "hgt")) { self.hgt.is_set = true; if (std.mem.endsWith(u8, val, "cm")) { const idx = std.mem.indexOf(u8, val, "cm") orelse { return; }; const num = fmt.parseUnsigned(usize, val[0..idx], 10) catch { return; }; self.hgt.is_ok = (150 <= num) and (num <= 193); return; } if (std.mem.endsWith(u8, val, "in")) { const idx = std.mem.indexOf(u8, val, "in") orelse { return; }; const num = fmt.parseUnsigned(usize, val[0..idx], 10) catch { return; }; self.hgt.is_ok = (59 <= num) and (num <= 76); return; } } if (std.mem.eql(u8, key, "hcl")) { self.hcl.is_set = true; if (!std.mem.startsWith(u8, val, "#")) { return; } if (val.len != 7) { return; } const num = fmt.parseUnsigned(usize, val[1..7], 16) catch { return; }; self.hcl.is_ok = true; } if (std.mem.eql(u8, key, "ecl")) { self.ecl.is_set = true; self.ecl.is_ok = std.mem.eql(u8, val, "amb") or std.mem.eql(u8, val, "blu") or std.mem.eql(u8, val, "brn") or std.mem.eql(u8, val, "gry") or std.mem.eql(u8, val, "grn") or std.mem.eql(u8, val, "hzl") or std.mem.eql(u8, val, "oth"); } if (std.mem.eql(u8, key, "pid")) { self.pid.is_set = true; if (val.len != 9) { return; } _ = fmt.parseUnsigned(usize, val[0..9], 10) catch { return; }; self.pid.is_ok = true; } if (std.mem.eql(u8, key, "cid")) { self.cid.is_set = true; } } pub fn p1_ok(self: Passport) bool { return self.byr.is_set and self.iyr.is_set and self.eyr.is_set and self.hgt.is_set and self.hcl.is_set and self.ecl.is_set and self.pid.is_set; } pub fn p2_ok(self: Passport) bool { return self.byr.is_ok and self.iyr.is_ok and self.eyr.is_ok and self.hgt.is_ok and self.hcl.is_ok and self.ecl.is_ok and self.pid.is_ok; } }; pub fn main() !void { // allocator defer _ = gpa.deinit(); var allo = &gpa.allocator; const lines: [][]const u8 = try utils.read_input_lines(allo, "./input1"); defer allo.free(lines); print("== got {} input lines ==\n", .{lines.len}); // part1 // var p1_cnt: usize = 0; var p2_cnt: usize = 0; var pp: Passport = Passport.empty(); var i: usize = 0; for (lines) |line| { defer allo.free(line); i += 1; info("--- line {}/{} {}", .{ i, lines.len, line }); if (line.len == 0) { if (pp.p1_ok()) { p1_cnt += 1; } if (pp.p2_ok()) { p2_cnt += 1; } pp = Passport.empty(); continue; } pp.parse_from_line(allo, line) catch |err| { info("line had err: {}", .{err}); break; }; } print("valid p1 passports: {}\n", .{p1_cnt}); print("valid p2 passports: {}\n", .{p2_cnt}); }
day_04/src/main.zig
const compiler_rt_armhf_target = false; // TODO const ConditionalOperator = enum { Eq, Lt, Le, Ge, Gt, }; pub nakedcc fn __aeabi_fcmpeq() noreturn { @setRuntimeSafety(false); @call(.{ .modifier = .always_inline }, aeabi_fcmp, .{.Eq}); unreachable; } pub nakedcc fn __aeabi_fcmplt() noreturn { @setRuntimeSafety(false); @call(.{ .modifier = .always_inline }, aeabi_fcmp, .{.Lt}); unreachable; } pub nakedcc fn __aeabi_fcmple() noreturn { @setRuntimeSafety(false); @call(.{ .modifier = .always_inline }, aeabi_fcmp, .{.Le}); unreachable; } pub nakedcc fn __aeabi_fcmpge() noreturn { @setRuntimeSafety(false); @call(.{ .modifier = .always_inline }, aeabi_fcmp, .{.Ge}); unreachable; } pub nakedcc fn __aeabi_fcmpgt() noreturn { @setRuntimeSafety(false); @call(.{ .modifier = .always_inline }, aeabi_fcmp, .{.Gt}); unreachable; } inline fn convert_fcmp_args_to_sf2_args() void { asm volatile ( \\ vmov s0, r0 \\ vmov s1, r1 ); } fn aeabi_fcmp(comptime cond: ConditionalOperator) void { @setRuntimeSafety(false); asm volatile ( \\ push { r4, lr } ); if (compiler_rt_armhf_target) { convert_fcmp_args_to_sf2_args(); } switch (cond) { .Eq => asm volatile ( \\ bl __eqsf2 \\ cmp r0, #0 \\ beq 1f \\ movs r0, #0 \\ pop { r4, pc } \\ 1: ), .Lt => asm volatile ( \\ bl __ltsf2 \\ cmp r0, #0 \\ blt 1f \\ movs r0, #0 \\ pop { r4, pc } \\ 1: ), .Le => asm volatile ( \\ bl __lesf2 \\ cmp r0, #0 \\ ble 1f \\ movs r0, #0 \\ pop { r4, pc } \\ 1: ), .Ge => asm volatile ( \\ bl __ltsf2 \\ cmp r0, #0 \\ bge 1f \\ movs r0, #0 \\ pop { r4, pc } \\ 1: ), .Gt => asm volatile ( \\ bl __gtsf2 \\ cmp r0, #0 \\ bgt 1f \\ movs r0, #0 \\ pop { r4, pc } \\ 1: ), } asm volatile ( \\ movs r0, #1 \\ pop { r4, pc } ); }
lib/std/special/compiler_rt/arm/aeabi_fcmp.zig
const builtin = @import("builtin"); const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const h = @cImport(@cInclude("behavior/translate_c_macros.h")); test "casting to void with a macro" { h.IGNORE_ME_1(42); h.IGNORE_ME_2(42); h.IGNORE_ME_3(42); h.IGNORE_ME_4(42); h.IGNORE_ME_5(42); h.IGNORE_ME_6(42); h.IGNORE_ME_7(42); h.IGNORE_ME_8(42); h.IGNORE_ME_9(42); h.IGNORE_ME_10(42); } test "initializer list expression" { if (builtin.zig_backend == .stage2_c) 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 try expectEqual(h.Color{ .r = 200, .g = 200, .b = 200, .a = 255, }, h.LIGHTGRAY); } test "sizeof in macros" { if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO try expect(@as(c_int, @sizeOf(u32)) == h.MY_SIZEOF(u32)); try expect(@as(c_int, @sizeOf(u32)) == h.MY_SIZEOF2(u32)); } test "reference to a struct type" { try expect(@sizeOf(h.struct_Foo) == h.SIZE_OF_FOO); } test "cast negative integer to pointer" { 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_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO try expectEqual(@intToPtr(?*anyopaque, @bitCast(usize, @as(isize, -1))), h.MAP_FAILED); } test "casting to union with a macro" { 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_c) 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 l: c_long = 42; const d: f64 = 2.0; var casted = h.UNION_CAST(l); try expect(l == casted.l); casted = h.UNION_CAST(d); try expect(d == casted.d); } test "nested comma operator" { 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_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO try expectEqual(@as(c_int, 3), h.NESTED_COMMA_OPERATOR); }
test/behavior/translate_c_macros.zig
const std = @import("std"); const Builder = std.build.Builder; const Step = std.build.Step; const assert = std.debug.assert; const print = std.debug.print; const Exercise = struct { /// main_file must have the format key_name.zig. /// The key will be used as a shorthand to build /// just one example. main_file: []const u8, /// This is the desired output of the program. /// A program passes if its output ends with this string. output: []const u8, /// This is an optional hint to give if the program does not succeed. hint: []const u8 = "", /// By default, we verify output against stderr. /// Set this to true to check stdout instead. check_stdout: bool = false, /// Returns the name of the main file with .zig stripped. pub fn baseName(self: Exercise) []const u8 { assert(std.mem.endsWith(u8, self.main_file, ".zig")); return self.main_file[0 .. self.main_file.len - 4]; } /// Returns the key of the main file, which is the text before the _. /// For example, "01_hello.zig" has the key "01". pub fn key(self: Exercise) []const u8 { const end_index = std.mem.indexOfScalar(u8, self.main_file, '_'); assert(end_index != null); // main file must be key_description.zig return self.main_file[0..end_index.?]; } }; const exercises = [_]Exercise{ .{ .main_file = "01_hello.zig", .output = "Hello world", .hint = "Note the error: the source file has a hint for fixing 'main'.", }, .{ .main_file = "02_std.zig", .output = "Standard Library", }, .{ .main_file = "03_assignment.zig", .output = "55 314159 -11", .hint = "There are three mistakes in this one!", }, .{ .main_file = "04_arrays.zig", .output = "Fourth: 7, Length: 8", .hint = "There are two things to complete here.", }, .{ .main_file = "05_arrays2.zig", .output = "LEET: 1337, Bits: 100110011001", .hint = "Fill in the two arrays.", }, .{ .main_file = "06_strings.zig", .output = "d=d ha ha ha Major Tom", .hint = "Each '???' needs something filled in.", }, .{ .main_file = "07_strings2.zig", .output = "Ziggy", .hint = "Please fix the lyrics!", }, .{ .main_file = "08_quiz.zig", .output = "Program in Zig", .hint = "See if you can fix the program!", }, .{ .main_file = "09_if.zig", .output = "Foo is 1!", }, .{ .main_file = "10_if2.zig", .output = "price is $17", }, .{ .main_file = "11_while.zig", .output = "n=1024", .hint = "You probably want a 'less than' condition.", }, .{ .main_file = "12_while2.zig", .output = "n=1024", .hint = "It might help to look back at the previous exercise.", }, .{ .main_file = "13_while3.zig", .output = "1 2 4 7 8 11 13 14 16 17 19", }, .{ .main_file = "14_while4.zig", .output = "n=4", }, .{ .main_file = "15_for.zig", .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.", }, .{ .main_file = "16_for2.zig", .output = "13", }, .{ .main_file = "17_quiz2.zig", .output = "8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16", .hint = "This is a famous game!", }, .{ .main_file = "18_functions.zig", .output = "Question: 42", .hint = "Can you help write the function?", }, .{ .main_file = "19_functions2.zig", .output = "2 4 8 16", }, .{ .main_file = "20_quiz3.zig", .output = "32 64 128 256", .hint = "Unexpected pop quiz! Help!", }, .{ .main_file = "21_errors.zig", .output = "2<4. 3<4. 4=4. 5>4. 6>4.", .hint = "What's the deal with fours?", }, .{ .main_file = "22_errors2.zig", .output = "I compiled", .hint = "Get the error union type right to allow this to compile.", }, .{ .main_file = "23_errors3.zig", .output = "a=64, b=22", }, .{ .main_file = "24_errors4.zig", .output = "a=20, b=14, c=10", }, .{ .main_file = "25_errors5.zig", .output = "a=0, b=19, c=0", }, .{ .main_file = "26_hello2.zig", .output = "Hello world", .hint = "Try using a try!", .check_stdout = true, }, .{ .main_file = "27_defer.zig", .output = "One Two", }, .{ .main_file = "28_defer2.zig", .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.", }, .{ .main_file = "29_errdefer.zig", .output = "Getting number...got 5. Getting number...failed!", }, .{ .main_file = "30_switch.zig", .output = "ZIG?", }, .{ .main_file = "31_switch2.zig", .output = "ZIG!", }, .{ .main_file = "32_unreachable.zig", .output = "1 2 3 9 8 7", }, .{ .main_file = "33_iferror.zig", .output = "2<4. 3<4. 4=4. 5>4. 6>4.", .hint = "Seriously, what's the deal with fours?", }, .{ .main_file = "34_quiz4.zig", .output = "my_num=42", .hint = "Can you make this work?", .check_stdout = true, }, .{ .main_file = "35_enums.zig", .output = "1 2 3 9 8 7", .hint = "This problem seems familiar...", }, .{ .main_file = "36_enums2.zig", .output = "#0000ff", .hint = "I'm feeling blue about this.", }, .{ .main_file = "37_structs.zig", .output = "Your wizard has 90 health and 25 gold.", }, .{ .main_file = "38_structs2.zig", .output = "Character 2 - G:10 H:100 XP:20", }, .{ .main_file = "39_pointers.zig", .output = "num1: 5, num2: 5", .hint = "Pointers aren't so bad.", }, .{ .main_file = "40_pointers2.zig", .output = "a: 12, b: 12", }, .{ .main_file = "41_pointers3.zig", .output = "foo=6, bar=11", }, .{ .main_file = "42_pointers4.zig", .output = "num: 5, more_nums: 1 1 5 1", }, .{ .main_file = "43_pointers5.zig", .output = "Wizard (G:10 H:100 XP:20)", }, .{ .main_file = "44_quiz5.zig", .output = "Elephant A. Elephant B. Elephant C.", .hint = "Oh no! We forgot Elephant B!", }, .{ .main_file = "45_optionals.zig", .output = "The Ultimate Answer: 42.", }, // optional fields (elephant tail - no longer need circular) // super-simple struct method // use struct method for elephant tails // quiz: add elephant trunk (like tail)! }; /// Check the zig version to make sure it can compile the examples properly. /// This will compile with Zig 0.6.0 and later. fn checkVersion() bool { if (!@hasDecl(std.builtin, "zig_version")) { return false; } const needed_version = std.SemanticVersion.parse("0.8.0-dev.1065") catch unreachable; const version = std.builtin.zig_version; const order = version.order(needed_version); return order != .lt; } pub fn build(b: *Builder) void { // Use a comptime branch for the version check. // If this fails, code after this block is not compiled. // It is parsed though, so versions of zig from before 0.6.0 // cannot do the version check and will just fail to compile. // We could fix this by moving the ziglings code to a separate file, // but 0.5.0 was a long time ago, it is unlikely that anyone who // attempts these exercises is still using it. if (comptime !checkVersion()) { // very old versions of Zig used warn instead of print. const stderrPrintFn = if (@hasDecl(std.debug, "print")) std.debug.print else std.debug.warn; stderrPrintFn( \\Error: Your version of zig is too old. Please download a master build from \\https://ziglang.org/download/ \\ , .{}); return; } use_color_escapes = false; switch (b.color) { .on => use_color_escapes = true, .off => use_color_escapes = false, .auto => { if (std.io.getStdErr().supportsAnsiEscapeCodes()) { use_color_escapes = true; } else if (std.builtin.os.tag == .windows) { const w32 = struct { const WINAPI = std.os.windows.WINAPI; const DWORD = std.os.windows.DWORD; const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004; const STD_ERROR_HANDLE = @bitCast(DWORD, @as(i32, -12)); extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*c_void; extern "kernel32" fn GetConsoleMode(console: ?*c_void, out_mode: *DWORD) callconv(WINAPI) u32; extern "kernel32" fn SetConsoleMode(console: ?*c_void, mode: DWORD) callconv(WINAPI) u32; }; const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE); var mode: w32.DWORD = 0; if (w32.GetConsoleMode(handle, &mode) != 0) { mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING; use_color_escapes = w32.SetConsoleMode(handle, mode) != 0; } } }, } if (use_color_escapes) { red_text = "\x1b[31m"; green_text = "\x1b[32m"; bold_text = "\x1b[1m"; reset_text = "\x1b[0m"; } const header_step = b.addLog( \\ \\ _ _ _ \\ ___(_) __ _| (_)_ __ __ _ ___ \\ |_ | |/ _' | | | '_ \ / _' / __| \\ / /| | (_| | | | | | | (_| \__ \ \\ /___|_|\__, |_|_|_| |_|\__, |___/ \\ |___/ |___/ \\ \\ , .{}); const verify_all = b.step("ziglings", "Verify all ziglings"); verify_all.dependOn(&header_step.step); b.default_step = verify_all; var prev_chain_verify = verify_all; for (exercises) |ex| { const base_name = ex.baseName(); const file_path = std.fs.path.join(b.allocator, &[_][]const u8{ "exercises", ex.main_file, }) catch unreachable; const build_step = b.addExecutable(base_name, file_path); build_step.install(); const verify_step = ZiglingStep.create(b, ex); const key = ex.key(); const named_test = b.step(b.fmt("{s}_test", .{key}), b.fmt("Run {s} without verifying output", .{ex.main_file})); const run_step = build_step.run(); named_test.dependOn(&run_step.step); const named_install = b.step(b.fmt("{s}_install", .{key}), b.fmt("Install {s} to zig-cache/bin", .{ex.main_file})); named_install.dependOn(&build_step.install_step.?.step); const named_verify = b.step(b.fmt("{s}_only", .{key}), b.fmt("Verify {s} only", .{ex.main_file})); named_verify.dependOn(&verify_step.step); const chain_verify = b.allocator.create(Step) catch unreachable; chain_verify.* = Step.initNoOp(.Custom, b.fmt("chain {s}", .{key}), b.allocator); chain_verify.dependOn(&verify_step.step); const named_chain = b.step(key, b.fmt("Verify all solutions starting at {s}", .{ex.main_file})); named_chain.dependOn(&header_step.step); named_chain.dependOn(chain_verify); prev_chain_verify.dependOn(chain_verify); prev_chain_verify = chain_verify; } } var use_color_escapes = false; var red_text: []const u8 = ""; var green_text: []const u8 = ""; var bold_text: []const u8 = ""; var reset_text: []const u8 = ""; const ZiglingStep = struct { step: Step, exercise: Exercise, builder: *Builder, pub fn create(builder: *Builder, exercise: Exercise) *@This() { const self = builder.allocator.create(@This()) catch unreachable; self.* = .{ .step = Step.init(.Custom, exercise.main_file, builder.allocator, make), .exercise = exercise, .builder = builder, }; return self; } fn make(step: *Step) anyerror!void { const self = @fieldParentPtr(@This(), "step", step); self.makeInternal() catch { if (self.exercise.hint.len > 0) { print("\n{s}hint: {s}{s}", .{ bold_text, self.exercise.hint, reset_text }); } print("\n{s}Edit exercises/{s} and run this again.{s}", .{ red_text, self.exercise.main_file, reset_text }); print("\n{s}To continue from this zigling, use this command:{s}\n {s}zig build {s}{s}\n", .{ red_text, reset_text, bold_text, self.exercise.key(), reset_text }); std.os.exit(0); }; } fn makeInternal(self: *@This()) !void { print("Compiling {s}...\n", .{self.exercise.main_file}); const exe_file = try self.doCompile(); print("Verifying {s}...\n", .{self.exercise.main_file}); const cwd = self.builder.build_root; const argv = [_][]const u8{exe_file}; const child = std.ChildProcess.init(&argv, self.builder.allocator) catch unreachable; defer child.deinit(); child.cwd = cwd; child.env_map = self.builder.env_map; child.stdin_behavior = .Inherit; if (self.exercise.check_stdout) { child.stdout_behavior = .Pipe; child.stderr_behavior = .Inherit; } else { child.stdout_behavior = .Inherit; child.stderr_behavior = .Pipe; } child.spawn() catch |err| { print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text }); return err; }; // Allow up to 1 MB of stdout capture const max_output_len = 1 * 1024 * 1024; const output = if (self.exercise.check_stdout) try child.stdout.?.reader().readAllAlloc(self.builder.allocator, max_output_len) else try child.stderr.?.reader().readAllAlloc(self.builder.allocator, max_output_len); // at this point stdout is closed, wait for the process to terminate const term = child.wait() catch |err| { print("{s}Unable to spawn {s}: {s}{s}\n", .{ red_text, argv[0], @errorName(err), reset_text }); return err; }; // make sure it exited cleanly. switch (term) { .Exited => |code| { if (code != 0) { print("{s}{s} exited with error code {d} (expected {d}){s}\n", .{ red_text, self.exercise.main_file, code, 0, reset_text }); return error.BadExitCode; } }, else => { print("{s}{s} terminated unexpectedly{s}\n", .{ red_text, self.exercise.main_file, reset_text }); return error.UnexpectedTermination; }, } // validate the output if (std.mem.indexOf(u8, output, self.exercise.output) == null) { print( \\ \\{s}----------- Expected this output -----------{s} \\{s} \\{s}----------- but found -----------{s} \\{s} \\{s}-----------{s} \\ , .{ red_text, reset_text, self.exercise.output, red_text, reset_text, output, red_text, reset_text }); return error.InvalidOutput; } print("{s}{s}{s}\n", .{ green_text, output, reset_text }); } // The normal compile step calls os.exit, so we can't use it as a library :( // This is a stripped down copy of std.build.LibExeObjStep.make. fn doCompile(self: *@This()) ![]const u8 { const builder = self.builder; var zig_args = std.ArrayList([]const u8).init(builder.allocator); defer zig_args.deinit(); zig_args.append(builder.zig_exe) catch unreachable; zig_args.append("build-exe") catch unreachable; if (builder.color != .auto) { zig_args.append("--color") catch unreachable; zig_args.append(@tagName(builder.color)) catch unreachable; } const zig_file = std.fs.path.join(builder.allocator, &[_][]const u8{ "exercises", self.exercise.main_file }) catch unreachable; zig_args.append(builder.pathFromRoot(zig_file)) catch unreachable; zig_args.append("--cache-dir") catch unreachable; zig_args.append(builder.pathFromRoot(builder.cache_root)) catch unreachable; zig_args.append("--enable-cache") catch unreachable; const argv = zig_args.items; var code: u8 = undefined; const output_dir_nl = builder.execAllowFail(argv, &code, .Inherit) catch |err| { switch (err) { error.FileNotFound => { print("{s}{s}: Unable to spawn the following command: file not found{s}\n", .{ red_text, self.exercise.main_file, reset_text }); for (argv) |v| print("{s} ", .{v}); print("\n", .{}); }, error.ExitCodeFailure => { print("{s}{s}: The following command exited with error code {}:{s}\n", .{ red_text, self.exercise.main_file, code, reset_text }); for (argv) |v| print("{s} ", .{v}); print("\n", .{}); }, error.ProcessTerminated => { print("{s}{s}: The following command terminated unexpectedly:{s}\n", .{ red_text, self.exercise.main_file, reset_text }); for (argv) |v| print("{s} ", .{v}); print("\n", .{}); }, else => {}, } return err; }; const build_output_dir = std.mem.trimRight(u8, output_dir_nl, "\r\n"); const target_info = std.zig.system.NativeTargetInfo.detect( builder.allocator, .{}, ) catch unreachable; const target = target_info.target; const file_name = std.zig.binNameAlloc(builder.allocator, .{ .root_name = self.exercise.baseName(), .target = target, .output_mode = .Exe, .link_mode = .Static, .version = null, }) catch unreachable; return std.fs.path.join(builder.allocator, &[_][]const u8{ build_output_dir, file_name, }); } };
build.zig
const print = @import("std").debug.print; pub fn main() void { // A "tuple": const foo = .{ true, false, @as(i32, 42), @as(f32, 3.141592), }; // We'll be implementing this: printTuple(foo); // This is just for fun, because we can: const nothing = .{}; print("\n", nothing); } // Let's make our own generic "tuple" printer. This should take a // "tuple" and print out each field in the following format: // // "name"(type):value // // Example: // // "0"(bool):true // // You'll be putting this together. But don't worry, everything // you need is documented in the comments. fn printTuple(tuple: anytype) void { // 1. Get a list of fields in the input 'tuple' // parameter. You'll need: // // @TypeOf() - takes a value, returns its type. // // @typeInfo() - takes a type, returns a TypeInfo union // with fields specific to that type. // // The list of a struct type's fields can be found in // TypeInfo's Struct.fields. // // Example: // // @typeInfo(Circle).Struct.fields // // This will be an array of StructFields. const fields = @typeInfo(@TypeOf(tuple)).Struct.fields; // 2. Loop through each field. This must be done at compile // time. // // Hint: remember 'inline' loops? // inline for (fields) |field| { // 3. Print the field's name, type, and value. // // Each 'field' in this loop is one of these: // // pub const StructField = struct { // name: []const u8, // field_type: type, // default_value: anytype, // is_comptime: bool, // alignment: comptime_int, // }; // // You'll need this builtin: // // @field(lhs: anytype, comptime field_name: []const u8) // // The first parameter is the value to be accessed, // the second parameter is a string with the name of // the field you wish to access. The value of the // field is returned. // // Example: // // @field(foo, "x"); // returns the value at foo.x // // The first field should print as: "0"(bool):true print("\"{s}\"({s}):{any} ", .{ field.name, field.field_type, // @field(field, "default_value"), field.default_value, }); } }
exercises/082_anonymous_structs3.zig
const std = @import("std.zig"); const StringHashMap = std.StringHashMap; const mem = @import("mem.zig"); const Allocator = mem.Allocator; const testing = std.testing; pub const BufSet = struct { hash_map: BufSetHashMap, const BufSetHashMap = StringHashMap(void); pub fn init(a: *Allocator) BufSet { var self = BufSet{ .hash_map = BufSetHashMap.init(a) }; return self; } pub fn deinit(self: *BufSet) void { for (self.hash_map.items()) |entry| { self.free(entry.key); } self.hash_map.deinit(); self.* = undefined; } pub fn put(self: *BufSet, key: []const u8) !void { if (self.hash_map.get(key) == null) { const key_copy = try self.copy(key); errdefer self.free(key_copy); _ = try self.hash_map.put(key_copy, {}); } } pub fn exists(self: BufSet, key: []const u8) bool { return self.hash_map.get(key) != null; } pub fn delete(self: *BufSet, key: []const u8) void { const entry = self.hash_map.remove(key) orelse return; self.free(entry.key); } pub fn count(self: *const BufSet) usize { return self.hash_map.count(); } pub fn iterator(self: *const BufSet) BufSetHashMap.Iterator { return self.hash_map.iterator(); } pub fn allocator(self: *const BufSet) *Allocator { return self.hash_map.allocator; } fn free(self: *const BufSet, value: []const u8) void { self.hash_map.allocator.free(value); } fn copy(self: *const BufSet, value: []const u8) ![]const u8 { const result = try self.hash_map.allocator.alloc(u8, value.len); mem.copy(u8, result, value); return result; } }; test "BufSet" { var bufset = BufSet.init(std.testing.allocator); defer bufset.deinit(); try bufset.put("x"); testing.expect(bufset.count() == 1); bufset.delete("x"); testing.expect(bufset.count() == 0); try bufset.put("x"); try bufset.put("y"); try bufset.put("z"); }
lib/std/buf_set.zig
const std = @import("std"); const Extent3D = @import("data.zig").Extent3D; const TextureView = @import("TextureView.zig"); const Texture = @This(); /// The type erased pointer to the Texture implementation /// Equal to c.WGPUTexture for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, destroy: fn (ptr: *anyopaque) void, setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void, createView: fn (ptr: *anyopaque, descriptor: *const TextureView.Descriptor) TextureView, }; pub inline fn reference(texture: Texture) void { texture.vtable.reference(texture.ptr); } pub inline fn release(texture: Texture) void { texture.vtable.release(texture.ptr); } pub inline fn setLabel(texture: Texture, label: [:0]const u8) void { texture.vtable.setLabel(texture.ptr, label); } pub inline fn destroy(texture: Texture) void { texture.vtable.destroy(texture.ptr); } pub inline fn createView(texture: Texture, descriptor: *const TextureView.Descriptor) TextureView { return texture.vtable.createView(texture.ptr, descriptor); } pub const Descriptor = struct { reserved: ?*anyopaque = null, label: ?[*:0]const u8 = null, usage: Usage, dimension: Dimension, size: Extent3D, format: Format, mip_level_count: u32, sample_count: u32, }; pub const Usage = packed struct { copy_src: bool = false, copy_dst: bool = false, texture_binding: bool = false, storage_binding: bool = false, render_attachment: bool = false, present: bool = false, _pad0: u2 = 0, _pad1: u8 = 0, _pad2: u16 = 0, comptime { std.debug.assert( @sizeOf(@This()) == @sizeOf(u32) and @bitSizeOf(@This()) == @bitSizeOf(u32), ); } pub fn equal(a: Usage, b: Usage) bool { return a.copy_src == b.copy_src and a.copy_dst == b.copy_dst and a.texture_binding == b.texture_binding and a.storage_binding == b.storage_binding and a.render_attachment == b.render_attachment and a.present == b.present; } }; pub const Format = enum(u32) { none = 0x00000000, r8_unorm = 0x00000001, r8_snorm = 0x00000002, r8_uint = 0x00000003, r8_sint = 0x00000004, r16_uint = 0x00000005, r16_sint = 0x00000006, r16_float = 0x00000007, rg8_unorm = 0x00000008, rg8_snorm = 0x00000009, rg8_uint = 0x0000000a, rg8_sint = 0x0000000b, r32_float = 0x0000000c, r32_uint = 0x0000000d, r32_sint = 0x0000000e, rg16_uint = 0x0000000f, rg16_sint = 0x00000010, rg16_float = 0x00000011, rgba8_unorm = 0x00000012, rgba8_unorm_srgb = 0x00000013, rgba8_snorm = 0x00000014, rgba8_uint = 0x00000015, rgba8_sint = 0x00000016, bgra8_unorm = 0x00000017, bgra8_unorm_srgb = 0x00000018, rgb10a2_unorm = 0x00000019, rg11b10u_float = 0x0000001a, rgb9e5u_float = 0x0000001b, rg32_float = 0x0000001c, rg32_uint = 0x0000001d, rg32_sint = 0x0000001e, rgba16_uint = 0x0000001f, rgba16_sint = 0x00000020, rgba16_float = 0x00000021, rgba32_float = 0x00000022, rgba32_uint = 0x00000023, rgba32_sint = 0x00000024, stencil8 = 0x00000025, depth16_unorm = 0x00000026, depth24_plus = 0x00000027, depth24_plus_stencil8 = 0x00000028, depth24_unorm_stencil8 = 0x00000029, depth32_float = 0x0000002a, depth32_float_stencil8 = 0x0000002b, bc1rgba_unorm = 0x0000002c, bc1rgba_unorm_srgb = 0x0000002d, bc2rgba_unorm = 0x0000002e, bc2rgba_unorm_srgb = 0x0000002f, bc3rgba_unorm = 0x00000030, bc3rgba_unorm_srgb = 0x00000031, bc4r_unorm = 0x00000032, bc4r_snorm = 0x00000033, bc5rg_unorm = 0x00000034, bc5rg_snorm = 0x00000035, bc6hrgbu_float = 0x00000036, bc6hrgb_float = 0x00000037, bc7rgba_unorm = 0x00000038, bc7rgba_unorm_srgb = 0x00000039, etc2rgb8_unorm = 0x0000003a, etc2rgb8_unorm_srgb = 0x0000003b, etc2rgb8a1_unorm = 0x0000003c, etc2rgb8a1_unorm_srgb = 0x0000003d, etc2rgba8_unorm = 0x0000003e, etc2rgba8_unorm_srgb = 0x0000003f, eacr11_unorm = 0x00000040, eacr11_snorm = 0x00000041, eacrg11_unorm = 0x00000042, eacrg11_snorm = 0x00000043, astc4x4_unorm = 0x00000044, astc4x4_unorm_srgb = 0x00000045, astc5x4_unorm = 0x00000046, astc5x4_unorm_srgb = 0x00000047, astc5x5_unorm = 0x00000048, astc5x5_unorm_srgb = 0x00000049, astc6x5_unorm = 0x0000004a, astc6x5_unorm_srgb = 0x0000004b, astc6x6_unorm = 0x0000004c, astc6x6_unorm_srgb = 0x0000004d, astc8x5_unorm = 0x0000004e, astc8x5_unorm_srgb = 0x0000004f, astc8x6_unorm = 0x00000050, astc8x6_unorm_srgb = 0x00000051, astc8x8_unorm = 0x00000052, astc8x8_unorm_srgb = 0x00000053, astc10x5_unorm = 0x00000054, astc10x5_unorm_srgb = 0x00000055, astc10x6_unorm = 0x00000056, astc10x6_unorm_srgb = 0x00000057, astc10x8_unorm = 0x00000058, astc10x8_unorm_srgb = 0x00000059, astc10x10_unorm = 0x0000005a, astc10x10_unorm_srgb = 0x0000005b, astc12x10_unorm = 0x0000005c, astc12x10_unorm_srgb = 0x0000005d, astc12x12_unorm = 0x0000005e, astc12x12_unorm_srgb = 0x0000005f, r8bg8biplanar420_unorm = 0x00000060, }; pub const Aspect = enum(u32) { all = 0x00000000, stencil_only = 0x00000001, depth_only = 0x00000002, plane0_only = 0x00000003, plane1_only = 0x00000004, }; pub const ComponentType = enum(u32) { float = 0x00000000, sint = 0x00000001, uint = 0x00000002, depth_comparison = 0x00000003, }; pub const Dimension = enum(u32) { dimension_1d = 0x00000000, dimension_2d = 0x00000001, dimension_3d = 0x00000002, }; pub const SampleType = enum(u32) { none = 0x00000000, float = 0x00000001, unfilterable_float = 0x00000002, depth = 0x00000003, sint = 0x00000004, uint = 0x00000005, }; pub const BindingLayout = extern struct { reserved: ?*anyopaque = null, sample_type: SampleType = .float, view_dimension: TextureView.Dimension = .dimension_2d, multisampled: bool = false, }; pub const DataLayout = extern struct { reserved: ?*anyopaque = null, offset: u64 = 0, bytes_per_row: u32, rows_per_image: u32, }; test { _ = VTable; _ = reference; _ = release; _ = destroy; _ = Descriptor; _ = Usage; _ = Format; _ = Aspect; _ = ComponentType; _ = Dimension; _ = SampleType; _ = BindingLayout; _ = DataLayout; }
gpu/src/Texture.zig
const sabaton = @import("root").sabaton; const std = @import("std"); const RSDP = packed struct { signature: [8]u8, checksum: u8, oemid: [6]u8, revision: u8, rsdt_addr: u32, extended_length: u32, xsdt_addr: u64, extended_checksum: u8, }; fn signature(name: []const u8) u32 { return std.mem.readInt(u32, name[0..4], std.builtin.endian); } fn print_sig(table: []const u8) void { var offset: usize = 0; while(offset < 4) : (offset += 1) { sabaton.putchar(table[offset]); } } pub fn try_get_addr(tables: []u8, sig: []const u8) ?usize { const table = find_table(tables, signature(sig)); return @ptrToInt((table orelse { if(sabaton.debug) { sabaton.puts("Couldn't find table with signature "); print_sig(sig); sabaton.putchar('\n'); } return null; }).ptr); } fn parse_root_sdt(comptime T: type, addr: usize) !void { const sdt = try map_sdt(addr); var offset: u64 = 36; while(offset + @sizeOf(T) <= sdt.len): (offset += @sizeOf(T)) { try parse_sdt(std.mem.readInt(T, sdt.to_slice()[offset..][0..@sizeOf(T)], builtin.endian)); } } fn fixup_root(comptime T: type, root_table: []u8, acpi_tables_c: []u8) void { var acpi_tables = acpi_tables_c; var offset: u64 = 36; while(acpi_tables.len > 8) { const len = std.mem.readInt(u32, acpi_tables[4..8], std.builtin.endian); if(len == 0) break; const sig = signature(acpi_tables); if(sabaton.debug) { sabaton.puts("Got table with signature "); print_sig(acpi_tables); sabaton.putchar('\n'); } switch(sig) { // Ignore root tables signature("RSDT"), signature("XSDT") => { }, // Nope, we don't point to this one either apparently. // https://github.com/qemu/qemu/blob/d0dddab40e472ba62b5f43f11cc7dba085dabe71/hw/arm/virt-acpi-build.c#L693 signature("DSDT") => { }, else => { // We add everything else // sabaton.log_hex("At offset ", offset); if(offset + @sizeOf(T) > root_table.len) { if(sabaton.debug) { sabaton.log_hex("Root table size is ", root_table.len); sabaton.puts("Can't fit this table pointer! :(\n"); break; } } else { const ptr_bytes = root_table[offset..][0..@sizeOf(T)]; const table_ptr = @intCast(u32, @ptrToInt(acpi_tables.ptr)); std.mem.writeInt(T, ptr_bytes, table_ptr, std.builtin.endian); offset += @sizeOf(T); } }, } acpi_tables = acpi_tables[len..]; } std.mem.writeInt(u32, root_table[4..][0..4], @intCast(u32, offset), std.builtin.endian); } fn fixup_fadt(fadt: []u8, dsdt: []u8) void { // We have both a FADT and DSDT on ACPI >= 2, so // The FADT needs to point to the DSDT const dsdt_addr = @ptrToInt(dsdt.ptr); // Offset: https://gcc.godbolt.org/z/j59fxx std.mem.writeInt(u64, fadt[152..][0..8], dsdt_addr, std.builtin.endian); } pub fn init(rsdp: []u8, tables_c: []u8) void { if(rsdp.len < @sizeOf(RSDP)) { if(sabaton.debug) sabaton.puts("RSDP too small, can't add."); return; } // Fixup RSDP const rsdp_val = @intToPtr(*RSDP, @ptrToInt(rsdp.ptr)); var got_root = false; var fadt_opt: ?[]u8 = null; var dsdt_opt: ?[]u8 = null; var tables = tables_c; while(tables.len > 8) { const len = std.mem.readInt(u32, tables[4..8], std.builtin.endian); if(len == 0) break; const table = tables[0..len]; const sig = signature(table); switch(sig) { signature("RSDT") => { sabaton.puts("Found RSDT!\n"); rsdp_val.rsdt_addr = @intCast(u32, @ptrToInt(table.ptr)); got_root = true; fixup_root(u32, table, tables_c); }, signature("XSDT") => { sabaton.puts("Found XSDT!\n"); rsdp_val.xsdt_addr = @intCast(u64, @ptrToInt(table.ptr)); got_root = true; fixup_root(u64, table, tables_c); }, signature("FADT") => fadt_opt = table, signature("DSDT") => dsdt_opt = table, else => { }, } tables = tables[len..]; } if(got_root) { if(sabaton.debug) { sabaton.puts("Adding RSDP\n"); sabaton.log("RSDP: {}\n", .{rsdp_val.*}); } sabaton.add_rsdp(@ptrToInt(rsdp.ptr)); if(rsdp_val.revision >= 2) { if(fadt_opt) |fadt| { if(dsdt_opt) |dsdt| { fixup_fadt(fadt, dsdt); } } } } }
src/platform/acpi.zig
pub const HH_DISPLAY_TOPIC = @as(u32, 0); pub const HH_HELP_FINDER = @as(u32, 0); pub const HH_DISPLAY_TOC = @as(u32, 1); pub const HH_DISPLAY_INDEX = @as(u32, 2); pub const HH_DISPLAY_SEARCH = @as(u32, 3); pub const HH_SET_WIN_TYPE = @as(u32, 4); pub const HH_GET_WIN_TYPE = @as(u32, 5); pub const HH_GET_WIN_HANDLE = @as(u32, 6); pub const HH_ENUM_INFO_TYPE = @as(u32, 7); pub const HH_SET_INFO_TYPE = @as(u32, 8); pub const HH_SYNC = @as(u32, 9); pub const HH_RESERVED1 = @as(u32, 10); pub const HH_RESERVED2 = @as(u32, 11); pub const HH_RESERVED3 = @as(u32, 12); pub const HH_KEYWORD_LOOKUP = @as(u32, 13); pub const HH_DISPLAY_TEXT_POPUP = @as(u32, 14); pub const HH_HELP_CONTEXT = @as(u32, 15); pub const HH_TP_HELP_CONTEXTMENU = @as(u32, 16); pub const HH_TP_HELP_WM_HELP = @as(u32, 17); pub const HH_CLOSE_ALL = @as(u32, 18); pub const HH_ALINK_LOOKUP = @as(u32, 19); pub const HH_GET_LAST_ERROR = @as(u32, 20); pub const HH_ENUM_CATEGORY = @as(u32, 21); pub const HH_ENUM_CATEGORY_IT = @as(u32, 22); pub const HH_RESET_IT_FILTER = @as(u32, 23); pub const HH_SET_INCLUSIVE_FILTER = @as(u32, 24); pub const HH_SET_EXCLUSIVE_FILTER = @as(u32, 25); pub const HH_INITIALIZE = @as(u32, 28); pub const HH_UNINITIALIZE = @as(u32, 29); pub const HH_SET_QUERYSERVICE = @as(u32, 30); pub const HH_PRETRANSLATEMESSAGE = @as(u32, 253); pub const HH_SET_GLOBAL_PROPERTY = @as(u32, 252); pub const HH_SAFE_DISPLAY_TOPIC = @as(u32, 32); pub const HHWIN_PROP_TAB_AUTOHIDESHOW = @as(u32, 1); pub const HHWIN_PROP_ONTOP = @as(u32, 2); pub const HHWIN_PROP_NOTITLEBAR = @as(u32, 4); pub const HHWIN_PROP_NODEF_STYLES = @as(u32, 8); pub const HHWIN_PROP_NODEF_EXSTYLES = @as(u32, 16); pub const HHWIN_PROP_TRI_PANE = @as(u32, 32); pub const HHWIN_PROP_NOTB_TEXT = @as(u32, 64); pub const HHWIN_PROP_POST_QUIT = @as(u32, 128); pub const HHWIN_PROP_AUTO_SYNC = @as(u32, 256); pub const HHWIN_PROP_TRACKING = @as(u32, 512); pub const HHWIN_PROP_TAB_SEARCH = @as(u32, 1024); pub const HHWIN_PROP_TAB_HISTORY = @as(u32, 2048); pub const HHWIN_PROP_TAB_FAVORITES = @as(u32, 4096); pub const HHWIN_PROP_CHANGE_TITLE = @as(u32, 8192); pub const HHWIN_PROP_NAV_ONLY_WIN = @as(u32, 16384); pub const HHWIN_PROP_NO_TOOLBAR = @as(u32, 32768); pub const HHWIN_PROP_MENU = @as(u32, 65536); pub const HHWIN_PROP_TAB_ADVSEARCH = @as(u32, 131072); pub const HHWIN_PROP_USER_POS = @as(u32, 262144); pub const HHWIN_PROP_TAB_CUSTOM1 = @as(u32, 524288); pub const HHWIN_PROP_TAB_CUSTOM2 = @as(u32, 1048576); pub const HHWIN_PROP_TAB_CUSTOM3 = @as(u32, 2097152); pub const HHWIN_PROP_TAB_CUSTOM4 = @as(u32, 4194304); pub const HHWIN_PROP_TAB_CUSTOM5 = @as(u32, 8388608); pub const HHWIN_PROP_TAB_CUSTOM6 = @as(u32, 16777216); pub const HHWIN_PROP_TAB_CUSTOM7 = @as(u32, 33554432); pub const HHWIN_PROP_TAB_CUSTOM8 = @as(u32, 67108864); pub const HHWIN_PROP_TAB_CUSTOM9 = @as(u32, 134217728); pub const HHWIN_TB_MARGIN = @as(u32, 268435456); pub const HHWIN_PARAM_PROPERTIES = @as(u32, 2); pub const HHWIN_PARAM_STYLES = @as(u32, 4); pub const HHWIN_PARAM_EXSTYLES = @as(u32, 8); pub const HHWIN_PARAM_RECT = @as(u32, 16); pub const HHWIN_PARAM_NAV_WIDTH = @as(u32, 32); pub const HHWIN_PARAM_SHOWSTATE = @as(u32, 64); pub const HHWIN_PARAM_INFOTYPES = @as(u32, 128); pub const HHWIN_PARAM_TB_FLAGS = @as(u32, 256); pub const HHWIN_PARAM_EXPANSION = @as(u32, 512); pub const HHWIN_PARAM_TABPOS = @as(u32, 1024); pub const HHWIN_PARAM_TABORDER = @as(u32, 2048); pub const HHWIN_PARAM_HISTORY_COUNT = @as(u32, 4096); pub const HHWIN_PARAM_CUR_TAB = @as(u32, 8192); pub const HHWIN_BUTTON_EXPAND = @as(u32, 2); pub const HHWIN_BUTTON_BACK = @as(u32, 4); pub const HHWIN_BUTTON_FORWARD = @as(u32, 8); pub const HHWIN_BUTTON_STOP = @as(u32, 16); pub const HHWIN_BUTTON_REFRESH = @as(u32, 32); pub const HHWIN_BUTTON_HOME = @as(u32, 64); pub const HHWIN_BUTTON_BROWSE_FWD = @as(u32, 128); pub const HHWIN_BUTTON_BROWSE_BCK = @as(u32, 256); pub const HHWIN_BUTTON_NOTES = @as(u32, 512); pub const HHWIN_BUTTON_CONTENTS = @as(u32, 1024); pub const HHWIN_BUTTON_SYNC = @as(u32, 2048); pub const HHWIN_BUTTON_OPTIONS = @as(u32, 4096); pub const HHWIN_BUTTON_PRINT = @as(u32, 8192); pub const HHWIN_BUTTON_INDEX = @as(u32, 16384); pub const HHWIN_BUTTON_SEARCH = @as(u32, 32768); pub const HHWIN_BUTTON_HISTORY = @as(u32, 65536); pub const HHWIN_BUTTON_FAVORITES = @as(u32, 131072); pub const HHWIN_BUTTON_JUMP1 = @as(u32, 262144); pub const HHWIN_BUTTON_JUMP2 = @as(u32, 524288); pub const HHWIN_BUTTON_ZOOM = @as(u32, 1048576); pub const HHWIN_BUTTON_TOC_NEXT = @as(u32, 2097152); pub const HHWIN_BUTTON_TOC_PREV = @as(u32, 4194304); pub const IDTB_EXPAND = @as(u32, 200); pub const IDTB_CONTRACT = @as(u32, 201); pub const IDTB_STOP = @as(u32, 202); pub const IDTB_REFRESH = @as(u32, 203); pub const IDTB_BACK = @as(u32, 204); pub const IDTB_HOME = @as(u32, 205); pub const IDTB_SYNC = @as(u32, 206); pub const IDTB_PRINT = @as(u32, 207); pub const IDTB_OPTIONS = @as(u32, 208); pub const IDTB_FORWARD = @as(u32, 209); pub const IDTB_NOTES = @as(u32, 210); pub const IDTB_BROWSE_FWD = @as(u32, 211); pub const IDTB_BROWSE_BACK = @as(u32, 212); pub const IDTB_CONTENTS = @as(u32, 213); pub const IDTB_INDEX = @as(u32, 214); pub const IDTB_SEARCH = @as(u32, 215); pub const IDTB_HISTORY = @as(u32, 216); pub const IDTB_FAVORITES = @as(u32, 217); pub const IDTB_JUMP1 = @as(u32, 218); pub const IDTB_JUMP2 = @as(u32, 219); pub const IDTB_CUSTOMIZE = @as(u32, 221); pub const IDTB_ZOOM = @as(u32, 222); pub const IDTB_TOC_NEXT = @as(u32, 223); pub const IDTB_TOC_PREV = @as(u32, 224); pub const HH_MAX_TABS = @as(u32, 19); pub const HH_FTS_DEFAULT_PROXIMITY = @as(i32, -1); pub const CLSID_IITPropList = Guid.initString("4662daae-d393-11d0-9a56-00c04fb68bf7"); pub const PROP_ADD = @as(u32, 0); pub const PROP_DELETE = @as(u32, 1); pub const PROP_UPDATE = @as(u32, 2); pub const TYPE_VALUE = @as(u32, 0); pub const TYPE_POINTER = @as(u32, 1); pub const TYPE_STRING = @as(u32, 2); pub const CLSID_IITDatabase = Guid.initString("66673452-8c23-11d0-a84e-00aa006c7d01"); pub const CLSID_IITDatabaseLocal = Guid.initString("4662daa9-d393-11d0-9a56-00c04fb68bf7"); pub const STDPROP_UID = @as(u32, 1); pub const STDPROP_TITLE = @as(u32, 2); pub const STDPROP_USERDATA = @as(u32, 3); pub const STDPROP_KEY = @as(u32, 4); pub const STDPROP_SORTKEY = @as(u32, 100); pub const STDPROP_DISPLAYKEY = @as(u32, 101); pub const STDPROP_SORTORDINAL = @as(u32, 102); pub const STDPROP_INDEX_TEXT = @as(u32, 200); pub const STDPROP_INDEX_VFLD = @as(u32, 201); pub const STDPROP_INDEX_DTYPE = @as(u32, 202); pub const STDPROP_INDEX_LENGTH = @as(u32, 203); pub const STDPROP_INDEX_BREAK = @as(u32, 204); pub const STDPROP_INDEX_TERM = @as(u32, 210); pub const STDPROP_INDEX_TERM_RAW_LENGTH = @as(u32, 211); pub const STDPROP_USERPROP_BASE = @as(u32, 65536); pub const STDPROP_USERPROP_MAX = @as(u32, 2147483647); pub const CLSID_IITCmdInt = Guid.initString("4662daa2-d393-11d0-9a56-00c04fb68bf7"); pub const CLSID_IITSvMgr = Guid.initString("4662daa3-d393-11d0-9a56-00c04fb68bf7"); pub const CLSID_IITWordWheelUpdate = Guid.initString("4662daa5-d393-11d0-9a56-00c04fb68bf7"); pub const CLSID_IITGroupUpdate = Guid.initString("4662daa4-d393-11d0-9a56-00c04fb68bf7"); pub const CLSID_IITIndexBuild = Guid.initString("8fa0d5aa-dedf-11d0-9a61-00c04fb68bf7"); pub const CLSID_IITWWFilterBuild = Guid.initString("8fa0d5ab-dedf-11d0-9a61-00c04fb68bf7"); pub const CLSID_IITWordWheel = Guid.initString("d73725c2-8c12-11d0-a84e-00aa006c7d01"); pub const CLSID_IITWordWheelLocal = Guid.initString("4662daa8-d393-11d0-9a56-00c04fb68bf7"); pub const ITWW_OPEN_NOCONNECT = @as(u32, 1); pub const ITWW_CBKEY_MAX = @as(u32, 1024); pub const IITWBC_BREAK_ACCEPT_WILDCARDS = @as(u32, 1); pub const IITWBC_BREAK_AND_STEM = @as(u32, 2); pub const E_NOTEXIST = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479552)); pub const E_DUPLICATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479551)); pub const E_BADVERSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479550)); pub const E_BADFILE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479549)); pub const E_BADFORMAT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479548)); pub const E_NOPERMISSION = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479547)); pub const E_ASSERT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479546)); pub const E_INTERRUPT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479545)); pub const E_NOTSUPPORTED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479544)); pub const E_OUTOFRANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479543)); pub const E_GROUPIDTOOBIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479542)); pub const E_TOOMANYTITLES = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479541)); pub const E_NOMERGEDDATA = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479540)); pub const E_NOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479539)); pub const E_CANTFINDDLL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479538)); pub const E_NOHANDLE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479537)); pub const E_GETLASTERROR = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479536)); pub const E_BADPARAM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479535)); pub const E_INVALIDSTATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479534)); pub const E_NOTOPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479533)); pub const E_ALREADYOPEN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479533)); pub const E_UNKNOWN_TRANSPORT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479530)); pub const E_UNSUPPORTED_TRANSPORT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479529)); pub const E_BADFILTERSIZE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479528)); pub const E_TOOMANYOBJECTS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479527)); pub const E_NAMETOOLONG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479520)); pub const E_FILECREATE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479504)); pub const E_FILECLOSE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479503)); pub const E_FILEREAD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479502)); pub const E_FILESEEK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479501)); pub const E_FILEWRITE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479500)); pub const E_FILEDELETE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479499)); pub const E_FILEINVALID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479498)); pub const E_FILENOTFOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479497)); pub const E_DISKFULL = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479496)); pub const E_TOOMANYTOPICS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479472)); pub const E_TOOMANYDUPS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479471)); pub const E_TREETOOBIG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479470)); pub const E_BADBREAKER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479469)); pub const E_BADVALUE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479468)); pub const E_ALL_WILD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479467)); pub const E_TOODEEP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479466)); pub const E_EXPECTEDTERM = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479465)); pub const E_MISSLPAREN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479464)); pub const E_MISSRPAREN = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479463)); pub const E_MISSQUOTE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479462)); pub const E_NULLQUERY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479461)); pub const E_STOPWORD = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479460)); pub const E_BADRANGEOP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479459)); pub const E_UNMATCHEDTYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479458)); pub const E_WORDTOOLONG = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479457)); pub const E_BADINDEXFLAGS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479456)); pub const E_WILD_IN_DTYPE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479455)); pub const E_NOSTEMMER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479454)); pub const E_MISSINGPROP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479424)); pub const E_PROPLISTNOTEMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479423)); pub const E_PROPLISTEMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479422)); pub const E_ALREADYINIT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479421)); pub const E_NOTINIT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479420)); pub const E_RESULTSETEMPTY = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479419)); pub const E_TOOMANYCOLUMNS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479418)); pub const E_NOKEYPROP = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147479417)); pub const CLSID_IITResultSet = Guid.initString("4662daa7-d393-11d0-9a56-00c04fb68bf7"); pub const MAX_COLUMNS = @as(u32, 256); pub const CLSID_ITStdBreaker = Guid.initString("4662daaf-d393-11d0-9a56-00c04fb68bf7"); pub const CLSID_ITEngStemmer = Guid.initString("8fa0d5a8-dedf-11d0-9a61-00c04fb68bf7"); pub const HHWIN_NAVTYPE_TOC = @as(i32, 0); pub const HHWIN_NAVTYPE_INDEX = @as(i32, 1); pub const HHWIN_NAVTYPE_SEARCH = @as(i32, 2); pub const HHWIN_NAVTYPE_FAVORITES = @as(i32, 3); pub const HHWIN_NAVTYPE_HISTORY = @as(i32, 4); pub const HHWIN_NAVTYPE_AUTHOR = @as(i32, 5); pub const HHWIN_NAVTYPE_CUSTOM_FIRST = @as(i32, 11); pub const IT_INCLUSIVE = @as(i32, 0); pub const IT_EXCLUSIVE = @as(i32, 1); pub const IT_HIDDEN = @as(i32, 2); pub const HHWIN_NAVTAB_TOP = @as(i32, 0); pub const HHWIN_NAVTAB_LEFT = @as(i32, 1); pub const HHWIN_NAVTAB_BOTTOM = @as(i32, 2); pub const HH_TAB_CONTENTS = @as(i32, 0); pub const HH_TAB_INDEX = @as(i32, 1); pub const HH_TAB_SEARCH = @as(i32, 2); pub const HH_TAB_FAVORITES = @as(i32, 3); pub const HH_TAB_HISTORY = @as(i32, 4); pub const HH_TAB_AUTHOR = @as(i32, 5); pub const HH_TAB_CUSTOM_FIRST = @as(i32, 11); pub const HH_TAB_CUSTOM_LAST = @as(i32, 19); pub const HHACT_TAB_CONTENTS = @as(i32, 0); pub const HHACT_TAB_INDEX = @as(i32, 1); pub const HHACT_TAB_SEARCH = @as(i32, 2); pub const HHACT_TAB_HISTORY = @as(i32, 3); pub const HHACT_TAB_FAVORITES = @as(i32, 4); pub const HHACT_EXPAND = @as(i32, 5); pub const HHACT_CONTRACT = @as(i32, 6); pub const HHACT_BACK = @as(i32, 7); pub const HHACT_FORWARD = @as(i32, 8); pub const HHACT_STOP = @as(i32, 9); pub const HHACT_REFRESH = @as(i32, 10); pub const HHACT_HOME = @as(i32, 11); pub const HHACT_SYNC = @as(i32, 12); pub const HHACT_OPTIONS = @as(i32, 13); pub const HHACT_PRINT = @as(i32, 14); pub const HHACT_HIGHLIGHT = @as(i32, 15); pub const HHACT_CUSTOMIZE = @as(i32, 16); pub const HHACT_JUMP1 = @as(i32, 17); pub const HHACT_JUMP2 = @as(i32, 18); pub const HHACT_ZOOM = @as(i32, 19); pub const HHACT_TOC_NEXT = @as(i32, 20); pub const HHACT_TOC_PREV = @as(i32, 21); pub const HHACT_NOTES = @as(i32, 22); pub const HHACT_LAST_ENUM = @as(i32, 23); //-------------------------------------------------------------------------------- // Section: Types (27) //-------------------------------------------------------------------------------- pub const WORD_WHEEL_OPEN_FLAGS = enum(u32) { T = 0, _, pub fn initFlags(o: struct { T: u1 = 0, }) WORD_WHEEL_OPEN_FLAGS { return @intToEnum(WORD_WHEEL_OPEN_FLAGS, (if (o.T == 1) @enumToInt(WORD_WHEEL_OPEN_FLAGS.T) else 0) ); } }; pub const ITWW_OPEN_CONNECT = WORD_WHEEL_OPEN_FLAGS.T; pub const HHN_NOTIFY = extern struct { hdr: NMHDR, pszUrl: ?[*:0]const u8, }; pub const HH_POPUP = extern struct { cbStruct: i32, hinst: ?HINSTANCE, idString: u32, pszText: ?*i8, pt: POINT, clrForeground: u32, clrBackground: u32, rcMargins: RECT, pszFont: ?*i8, }; pub const HH_AKLINK = extern struct { cbStruct: i32, fReserved: BOOL, pszKeywords: ?*i8, pszUrl: ?*i8, pszMsgText: ?*i8, pszMsgTitle: ?*i8, pszWindow: ?*i8, fIndexOnFail: BOOL, }; pub const HH_ENUM_IT = extern struct { cbStruct: i32, iType: i32, pszCatName: ?[*:0]const u8, pszITName: ?[*:0]const u8, pszITDescription: ?[*:0]const u8, }; pub const HH_ENUM_CAT = extern struct { cbStruct: i32, pszCatName: ?[*:0]const u8, pszCatDescription: ?[*:0]const u8, }; pub const HH_SET_INFOTYPE = extern struct { cbStruct: i32, pszCatName: ?[*:0]const u8, pszInfoTypeName: ?[*:0]const u8, }; pub const HH_FTS_QUERY = extern struct { cbStruct: i32, fUniCodeStrings: BOOL, pszSearchQuery: ?*i8, iProximity: i32, fStemmedSearch: BOOL, fTitleOnly: BOOL, fExecute: BOOL, pszWindow: ?*i8, }; pub const HH_WINTYPE = extern struct { cbStruct: i32, fUniCodeStrings: BOOL, pszType: ?*i8, fsValidMembers: u32, fsWinProperties: u32, pszCaption: ?*i8, dwStyles: u32, dwExStyles: u32, rcWindowPos: RECT, nShowState: i32, hwndHelp: ?HWND, hwndCaller: ?HWND, paInfoTypes: ?*u32, hwndToolBar: ?HWND, hwndNavigation: ?HWND, hwndHTML: ?HWND, iNavWidth: i32, rcHTML: RECT, pszToc: ?*i8, pszIndex: ?*i8, pszFile: ?*i8, pszHome: ?*i8, fsToolBarFlags: u32, fNotExpanded: BOOL, curNavType: i32, tabpos: i32, idNotify: i32, tabOrder: [20]u8, cHistory: i32, pszJump1: ?*i8, pszJump2: ?*i8, pszUrlJump1: ?*i8, pszUrlJump2: ?*i8, rcMinSize: RECT, cbInfoTypes: i32, pszCustomTabs: ?*i8, }; pub const HHNTRACK = extern struct { hdr: NMHDR, pszCurUrl: ?[*:0]const u8, idAction: i32, phhWinType: ?*HH_WINTYPE, }; pub const HH_GPROPID = enum(i32) { SINGLETHREAD = 1, TOOLBAR_MARGIN = 2, UI_LANGUAGE = 3, CURRENT_SUBSET = 4, CONTENT_LANGUAGE = 5, }; pub const HH_GPROPID_SINGLETHREAD = HH_GPROPID.SINGLETHREAD; pub const HH_GPROPID_TOOLBAR_MARGIN = HH_GPROPID.TOOLBAR_MARGIN; pub const HH_GPROPID_UI_LANGUAGE = HH_GPROPID.UI_LANGUAGE; pub const HH_GPROPID_CURRENT_SUBSET = HH_GPROPID.CURRENT_SUBSET; pub const HH_GPROPID_CONTENT_LANGUAGE = HH_GPROPID.CONTENT_LANGUAGE; pub const HH_GLOBAL_PROPERTY = extern struct { id: HH_GPROPID, @"var": VARIANT, }; pub const CProperty = extern struct { dwPropID: u32, cbData: u32, dwType: u32, Anonymous: extern union { lpszwData: ?PWSTR, lpvData: ?*anyopaque, dwValue: u32, }, fPersist: BOOL, }; const IID_IITPropList_Value = Guid.initString("1f403bb1-9997-11d0-a850-00aa006c7d01"); pub const IID_IITPropList = &IID_IITPropList_Value; pub const IITPropList = extern struct { pub const VTable = extern struct { base: IPersistStreamInit.VTable, Set: fn( self: *const IITPropList, PropID: u32, lpszwString: ?[*:0]const u16, dwOperation: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set1: fn( self: *const IITPropList, PropID: u32, lpvData: ?*anyopaque, cbData: u32, dwOperation: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set2: fn( self: *const IITPropList, PropID: u32, dwData: u32, dwOperation: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IITPropList, Prop: ?*CProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IITPropList, PropID: u32, Property: ?*CProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IITPropList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPersist: fn( self: *const IITPropList, fPersist: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPersist1: fn( self: *const IITPropList, PropID: u32, fPersist: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFirst: fn( self: *const IITPropList, Property: ?*CProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNext: fn( self: *const IITPropList, Property: ?*CProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropCount: fn( self: *const IITPropList, cProp: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveHeader: fn( self: *const IITPropList, lpvData: ?*anyopaque, dwHdrSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveData: fn( self: *const IITPropList, lpvHeader: ?*anyopaque, dwHdrSize: u32, lpvData: ?*anyopaque, dwBufSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHeaderSize: fn( self: *const IITPropList, dwHdrSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataSize: fn( self: *const IITPropList, lpvHeader: ?*anyopaque, dwHdrSize: u32, dwDataSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveDataToStream: fn( self: *const IITPropList, lpvHeader: ?*anyopaque, dwHdrSize: u32, pStream: ?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadFromMem: fn( self: *const IITPropList, lpvData: ?*anyopaque, dwBufSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SaveToMem: fn( self: *const IITPropList, lpvData: ?*anyopaque, dwBufSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPersistStreamInit.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_Set(self: *const T, PropID: u32, lpszwString: ?[*:0]const u16, dwOperation: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).Set(@ptrCast(*const IITPropList, self), PropID, lpszwString, dwOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_Set1(self: *const T, PropID: u32, lpvData: ?*anyopaque, cbData: u32, dwOperation: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).Set(@ptrCast(*const IITPropList, self), PropID, lpvData, cbData, dwOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_Set2(self: *const T, PropID: u32, dwData: u32, dwOperation: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).Set(@ptrCast(*const IITPropList, self), PropID, dwData, dwOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_Add(self: *const T, Prop: ?*CProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).Add(@ptrCast(*const IITPropList, self), Prop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_Get(self: *const T, PropID: u32, Property: ?*CProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).Get(@ptrCast(*const IITPropList, self), PropID, Property); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).Clear(@ptrCast(*const IITPropList, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_SetPersist(self: *const T, fPersist: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).SetPersist(@ptrCast(*const IITPropList, self), fPersist); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_SetPersist1(self: *const T, PropID: u32, fPersist: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).SetPersist(@ptrCast(*const IITPropList, self), PropID, fPersist); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_GetFirst(self: *const T, Property: ?*CProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).GetFirst(@ptrCast(*const IITPropList, self), Property); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_GetNext(self: *const T, Property: ?*CProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).GetNext(@ptrCast(*const IITPropList, self), Property); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_GetPropCount(self: *const T, cProp: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).GetPropCount(@ptrCast(*const IITPropList, self), cProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_SaveHeader(self: *const T, lpvData: ?*anyopaque, dwHdrSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).SaveHeader(@ptrCast(*const IITPropList, self), lpvData, dwHdrSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_SaveData(self: *const T, lpvHeader: ?*anyopaque, dwHdrSize: u32, lpvData: ?*anyopaque, dwBufSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).SaveData(@ptrCast(*const IITPropList, self), lpvHeader, dwHdrSize, lpvData, dwBufSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_GetHeaderSize(self: *const T, dwHdrSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).GetHeaderSize(@ptrCast(*const IITPropList, self), dwHdrSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_GetDataSize(self: *const T, lpvHeader: ?*anyopaque, dwHdrSize: u32, dwDataSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).GetDataSize(@ptrCast(*const IITPropList, self), lpvHeader, dwHdrSize, dwDataSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_SaveDataToStream(self: *const T, lpvHeader: ?*anyopaque, dwHdrSize: u32, pStream: ?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).SaveDataToStream(@ptrCast(*const IITPropList, self), lpvHeader, dwHdrSize, pStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_LoadFromMem(self: *const T, lpvData: ?*anyopaque, dwBufSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).LoadFromMem(@ptrCast(*const IITPropList, self), lpvData, dwBufSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITPropList_SaveToMem(self: *const T, lpvData: ?*anyopaque, dwBufSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITPropList.VTable, self.vtable).SaveToMem(@ptrCast(*const IITPropList, self), lpvData, dwBufSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IITDatabase_Value = Guid.initString("8fa0d5a2-dedf-11d0-9a61-00c04fb68bf7"); pub const IID_IITDatabase = &IID_IITDatabase_Value; pub const IITDatabase = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Open: fn( self: *const IITDatabase, lpszHost: ?[*:0]const u16, lpszMoniker: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IITDatabase, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateObject: fn( self: *const IITDatabase, rclsid: ?*const Guid, pdwObjInstance: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetObject: fn( self: *const IITDatabase, dwObjInstance: u32, riid: ?*const Guid, ppvObj: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetObjectPersistence: fn( self: *const IITDatabase, lpwszObject: ?[*:0]const u16, dwObjInstance: u32, ppvPersistence: ?*?*anyopaque, fStream: BOOL, ) 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 IITDatabase_Open(self: *const T, lpszHost: ?[*:0]const u16, lpszMoniker: ?[*:0]const u16, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITDatabase.VTable, self.vtable).Open(@ptrCast(*const IITDatabase, self), lpszHost, lpszMoniker, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITDatabase_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITDatabase.VTable, self.vtable).Close(@ptrCast(*const IITDatabase, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITDatabase_CreateObject(self: *const T, rclsid: ?*const Guid, pdwObjInstance: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITDatabase.VTable, self.vtable).CreateObject(@ptrCast(*const IITDatabase, self), rclsid, pdwObjInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITDatabase_GetObject(self: *const T, dwObjInstance: u32, riid: ?*const Guid, ppvObj: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IITDatabase.VTable, self.vtable).GetObject(@ptrCast(*const IITDatabase, self), dwObjInstance, riid, ppvObj); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITDatabase_GetObjectPersistence(self: *const T, lpwszObject: ?[*:0]const u16, dwObjInstance: u32, ppvPersistence: ?*?*anyopaque, fStream: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IITDatabase.VTable, self.vtable).GetObjectPersistence(@ptrCast(*const IITDatabase, self), lpwszObject, dwObjInstance, ppvPersistence, fStream); } };} pub usingnamespace MethodMixin(@This()); }; pub const IITGroup = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const IITQuery = extern struct { placeholder: usize, // TODO: why is this type empty? }; const IID_IITWordWheel_Value = Guid.initString("8fa0d5a4-dedf-11d0-9a61-00c04fb68bf7"); pub const IID_IITWordWheel = &IID_IITWordWheel_Value; pub const IITWordWheel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Open: fn( self: *const IITWordWheel, lpITDB: ?*IITDatabase, lpszMoniker: ?[*:0]const u16, dwFlags: WORD_WHEEL_OPEN_FLAGS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Close: fn( self: *const IITWordWheel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLocaleInfo: fn( self: *const IITWordWheel, pdwCodePageID: ?*u32, plcid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSorterInstance: fn( self: *const IITWordWheel, pdwObjInstance: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Count: fn( self: *const IITWordWheel, pcEntries: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lookup: fn( self: *const IITWordWheel, lpcvPrefix: ?*const anyopaque, fExactMatch: BOOL, plEntry: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lookup1: fn( self: *const IITWordWheel, lEntry: i32, lpITResult: ?*IITResultSet, cEntries: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lookup2: fn( self: *const IITWordWheel, lEntry: i32, lpvKeyBuf: ?*anyopaque, cbKeyBuf: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetGroup: fn( self: *const IITWordWheel, piitGroup: ?*IITGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGroup: fn( self: *const IITWordWheel, ppiitGroup: ?*?*IITGroup, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataCount: fn( self: *const IITWordWheel, lEntry: i32, pdwCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetData: fn( self: *const IITWordWheel, lEntry: i32, lpITResult: ?*IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDataColumns: fn( self: *const IITWordWheel, pRS: ?*IITResultSet, ) 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 IITWordWheel_Open(self: *const T, lpITDB: ?*IITDatabase, lpszMoniker: ?[*:0]const u16, dwFlags: WORD_WHEEL_OPEN_FLAGS) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).Open(@ptrCast(*const IITWordWheel, self), lpITDB, lpszMoniker, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_Close(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).Close(@ptrCast(*const IITWordWheel, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_GetLocaleInfo(self: *const T, pdwCodePageID: ?*u32, plcid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).GetLocaleInfo(@ptrCast(*const IITWordWheel, self), pdwCodePageID, plcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_GetSorterInstance(self: *const T, pdwObjInstance: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).GetSorterInstance(@ptrCast(*const IITWordWheel, self), pdwObjInstance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_Count(self: *const T, pcEntries: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).Count(@ptrCast(*const IITWordWheel, self), pcEntries); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_Lookup(self: *const T, lpcvPrefix: ?*const anyopaque, fExactMatch: BOOL, plEntry: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).Lookup(@ptrCast(*const IITWordWheel, self), lpcvPrefix, fExactMatch, plEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_Lookup1(self: *const T, lEntry: i32, lpITResult: ?*IITResultSet, cEntries: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).Lookup(@ptrCast(*const IITWordWheel, self), lEntry, lpITResult, cEntries); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_Lookup2(self: *const T, lEntry: i32, lpvKeyBuf: ?*anyopaque, cbKeyBuf: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).Lookup(@ptrCast(*const IITWordWheel, self), lEntry, lpvKeyBuf, cbKeyBuf); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_SetGroup(self: *const T, piitGroup: ?*IITGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).SetGroup(@ptrCast(*const IITWordWheel, self), piitGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_GetGroup(self: *const T, ppiitGroup: ?*?*IITGroup) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).GetGroup(@ptrCast(*const IITWordWheel, self), ppiitGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_GetDataCount(self: *const T, lEntry: i32, pdwCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).GetDataCount(@ptrCast(*const IITWordWheel, self), lEntry, pdwCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_GetData(self: *const T, lEntry: i32, lpITResult: ?*IITResultSet) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).GetData(@ptrCast(*const IITWordWheel, self), lEntry, lpITResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITWordWheel_GetDataColumns(self: *const T, pRS: ?*IITResultSet) callconv(.Inline) HRESULT { return @ptrCast(*const IITWordWheel.VTable, self.vtable).GetDataColumns(@ptrCast(*const IITWordWheel, self), pRS); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IStemSink_Value = Guid.initString("fe77c330-7f42-11ce-be57-00aa0051fe20"); pub const IID_IStemSink = &IID_IStemSink_Value; pub const IStemSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, PutAltWord: fn( self: *const IStemSink, pwcInBuf: ?[*:0]const u16, cwc: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutWord: fn( self: *const IStemSink, pwcInBuf: ?[*:0]const u16, cwc: 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 IStemSink_PutAltWord(self: *const T, pwcInBuf: ?[*:0]const u16, cwc: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemSink.VTable, self.vtable).PutAltWord(@ptrCast(*const IStemSink, self), pwcInBuf, cwc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStemSink_PutWord(self: *const T, pwcInBuf: ?[*:0]const u16, cwc: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemSink.VTable, self.vtable).PutWord(@ptrCast(*const IStemSink, self), pwcInBuf, cwc); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IStemmerConfig_Value = Guid.initString("8fa0d5a7-dedf-11d0-9a61-00c04fb68bf7"); pub const IID_IStemmerConfig = &IID_IStemmerConfig_Value; pub const IStemmerConfig = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetLocaleInfo: fn( self: *const IStemmerConfig, dwCodePageID: u32, lcid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLocaleInfo: fn( self: *const IStemmerConfig, pdwCodePageID: ?*u32, plcid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetControlInfo: fn( self: *const IStemmerConfig, grfStemFlags: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetControlInfo: fn( self: *const IStemmerConfig, pgrfStemFlags: ?*u32, pdwReserved: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadExternalStemmerData: fn( self: *const IStemmerConfig, pStream: ?*IStream, dwExtDataType: 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 IStemmerConfig_SetLocaleInfo(self: *const T, dwCodePageID: u32, lcid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemmerConfig.VTable, self.vtable).SetLocaleInfo(@ptrCast(*const IStemmerConfig, self), dwCodePageID, lcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStemmerConfig_GetLocaleInfo(self: *const T, pdwCodePageID: ?*u32, plcid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemmerConfig.VTable, self.vtable).GetLocaleInfo(@ptrCast(*const IStemmerConfig, self), pdwCodePageID, plcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStemmerConfig_SetControlInfo(self: *const T, grfStemFlags: u32, dwReserved: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemmerConfig.VTable, self.vtable).SetControlInfo(@ptrCast(*const IStemmerConfig, self), grfStemFlags, dwReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStemmerConfig_GetControlInfo(self: *const T, pgrfStemFlags: ?*u32, pdwReserved: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemmerConfig.VTable, self.vtable).GetControlInfo(@ptrCast(*const IStemmerConfig, self), pgrfStemFlags, pdwReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IStemmerConfig_LoadExternalStemmerData(self: *const T, pStream: ?*IStream, dwExtDataType: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IStemmerConfig.VTable, self.vtable).LoadExternalStemmerData(@ptrCast(*const IStemmerConfig, self), pStream, dwExtDataType); } };} pub usingnamespace MethodMixin(@This()); }; pub const IITStopWordList = extern struct { placeholder: usize, // TODO: why is this type empty? }; const IID_IWordBreakerConfig_Value = Guid.initString("8fa0d5a6-dedf-11d0-9a61-00c04fb68bf7"); pub const IID_IWordBreakerConfig = &IID_IWordBreakerConfig_Value; pub const IWordBreakerConfig = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetLocaleInfo: fn( self: *const IWordBreakerConfig, dwCodePageID: u32, lcid: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLocaleInfo: fn( self: *const IWordBreakerConfig, pdwCodePageID: ?*u32, plcid: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBreakWordType: fn( self: *const IWordBreakerConfig, dwBreakWordType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBreakWordType: fn( self: *const IWordBreakerConfig, pdwBreakWordType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetControlInfo: fn( self: *const IWordBreakerConfig, grfBreakFlags: u32, dwReserved: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetControlInfo: fn( self: *const IWordBreakerConfig, pgrfBreakFlags: ?*u32, pdwReserved: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, LoadExternalBreakerData: fn( self: *const IWordBreakerConfig, pStream: ?*IStream, dwExtDataType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetWordStemmer: fn( self: *const IWordBreakerConfig, rclsid: ?*const Guid, pStemmer: ?*IStemmer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWordStemmer: fn( self: *const IWordBreakerConfig, ppStemmer: ?*?*IStemmer, ) 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 IWordBreakerConfig_SetLocaleInfo(self: *const T, dwCodePageID: u32, lcid: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).SetLocaleInfo(@ptrCast(*const IWordBreakerConfig, self), dwCodePageID, lcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_GetLocaleInfo(self: *const T, pdwCodePageID: ?*u32, plcid: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).GetLocaleInfo(@ptrCast(*const IWordBreakerConfig, self), pdwCodePageID, plcid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_SetBreakWordType(self: *const T, dwBreakWordType: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).SetBreakWordType(@ptrCast(*const IWordBreakerConfig, self), dwBreakWordType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_GetBreakWordType(self: *const T, pdwBreakWordType: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).GetBreakWordType(@ptrCast(*const IWordBreakerConfig, self), pdwBreakWordType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_SetControlInfo(self: *const T, grfBreakFlags: u32, dwReserved: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).SetControlInfo(@ptrCast(*const IWordBreakerConfig, self), grfBreakFlags, dwReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_GetControlInfo(self: *const T, pgrfBreakFlags: ?*u32, pdwReserved: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).GetControlInfo(@ptrCast(*const IWordBreakerConfig, self), pgrfBreakFlags, pdwReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_LoadExternalBreakerData(self: *const T, pStream: ?*IStream, dwExtDataType: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).LoadExternalBreakerData(@ptrCast(*const IWordBreakerConfig, self), pStream, dwExtDataType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_SetWordStemmer(self: *const T, rclsid: ?*const Guid, pStemmer: ?*IStemmer) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).SetWordStemmer(@ptrCast(*const IWordBreakerConfig, self), rclsid, pStemmer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IWordBreakerConfig_GetWordStemmer(self: *const T, ppStemmer: ?*?*IStemmer) callconv(.Inline) HRESULT { return @ptrCast(*const IWordBreakerConfig.VTable, self.vtable).GetWordStemmer(@ptrCast(*const IWordBreakerConfig, self), ppStemmer); } };} pub usingnamespace MethodMixin(@This()); }; pub const PRIORITY = enum(i32) { LOW = 0, NORMAL = 1, HIGH = 2, }; pub const PRIORITY_LOW = PRIORITY.LOW; pub const PRIORITY_NORMAL = PRIORITY.NORMAL; pub const PRIORITY_HIGH = PRIORITY.HIGH; pub const ROWSTATUS = extern struct { lRowFirst: i32, cRows: i32, cProperties: i32, cRowsTotal: i32, }; pub const COLUMNSTATUS = extern struct { cPropCount: i32, cPropsLoaded: i32, }; pub const PFNCOLHEAPFREE = fn( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; const IID_IITResultSet_Value = Guid.initString("3bb91d41-998b-11d0-a850-00aa006c7d01"); pub const IID_IITResultSet = &IID_IITResultSet_Value; pub const IITResultSet = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetColumnPriority: fn( self: *const IITResultSet, lColumnIndex: i32, ColumnPriority: PRIORITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetColumnHeap: fn( self: *const IITResultSet, lColumnIndex: i32, lpvHeap: ?*anyopaque, pfnColHeapFree: ?PFNCOLHEAPFREE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetKeyProp: fn( self: *const IITResultSet, PropID: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IITResultSet, PropID: u32, dwDefaultData: u32, Priority: PRIORITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add1: fn( self: *const IITResultSet, PropID: u32, lpszwDefault: ?[*:0]const u16, Priority: PRIORITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add2: fn( self: *const IITResultSet, PropID: u32, lpvDefaultData: ?*anyopaque, cbData: u32, Priority: PRIORITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add3: fn( self: *const IITResultSet, lpvHdr: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Append: fn( self: *const IITResultSet, lpvHdr: ?*anyopaque, lpvData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set: fn( self: *const IITResultSet, lRowIndex: i32, lColumnIndex: i32, lpvData: ?*anyopaque, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set1: fn( self: *const IITResultSet, lRowIndex: i32, lColumnIndex: i32, lpwStr: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set2: fn( self: *const IITResultSet, lRowIndex: i32, lColumnIndex: i32, dwData: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set3: fn( self: *const IITResultSet, lRowIndex: i32, lpvHdr: ?*anyopaque, lpvData: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Copy: fn( self: *const IITResultSet, pRSCopy: ?*IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AppendRows: fn( self: *const IITResultSet, pResSrc: ?*IITResultSet, lRowSrcFirst: i32, cSrcRows: i32, lRowFirstDest: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IITResultSet, lRowIndex: i32, lColumnIndex: i32, Prop: ?*CProperty, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetKeyProp: fn( self: *const IITResultSet, KeyPropID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnPriority: fn( self: *const IITResultSet, lColumnIndex: i32, ColumnPriority: ?*PRIORITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRowCount: fn( self: *const IITResultSet, lNumberOfRows: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnCount: fn( self: *const IITResultSet, lNumberOfColumns: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumn: fn( self: *const IITResultSet, lColumnIndex: i32, PropID: ?*u32, dwType: ?*u32, lpvDefaultValue: ?*?*anyopaque, cbSize: ?*u32, ColumnPriority: ?*PRIORITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumn1: fn( self: *const IITResultSet, lColumnIndex: i32, PropID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnFromPropID: fn( self: *const IITResultSet, PropID: u32, lColumnIndex: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ClearRows: fn( self: *const IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Free: fn( self: *const IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsCompleted: fn( self: *const IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Cancel: fn( self: *const IITResultSet, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Pause: fn( self: *const IITResultSet, fPause: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRowStatus: fn( self: *const IITResultSet, lRowFirst: i32, cRows: i32, lpRowStatus: ?*ROWSTATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumnStatus: fn( self: *const IITResultSet, lpColStatus: ?*COLUMNSTATUS, ) 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 IITResultSet_SetColumnPriority(self: *const T, lColumnIndex: i32, ColumnPriority: PRIORITY) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).SetColumnPriority(@ptrCast(*const IITResultSet, self), lColumnIndex, ColumnPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_SetColumnHeap(self: *const T, lColumnIndex: i32, lpvHeap: ?*anyopaque, pfnColHeapFree: ?PFNCOLHEAPFREE) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).SetColumnHeap(@ptrCast(*const IITResultSet, self), lColumnIndex, lpvHeap, pfnColHeapFree); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_SetKeyProp(self: *const T, PropID: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).SetKeyProp(@ptrCast(*const IITResultSet, self), PropID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Add(self: *const T, PropID: u32, dwDefaultData: u32, Priority: PRIORITY) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Add(@ptrCast(*const IITResultSet, self), PropID, dwDefaultData, Priority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Add1(self: *const T, PropID: u32, lpszwDefault: ?[*:0]const u16, Priority: PRIORITY) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Add(@ptrCast(*const IITResultSet, self), PropID, lpszwDefault, Priority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Add2(self: *const T, PropID: u32, lpvDefaultData: ?*anyopaque, cbData: u32, Priority: PRIORITY) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Add(@ptrCast(*const IITResultSet, self), PropID, lpvDefaultData, cbData, Priority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Add3(self: *const T, lpvHdr: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Add(@ptrCast(*const IITResultSet, self), lpvHdr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Append(self: *const T, lpvHdr: ?*anyopaque, lpvData: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Append(@ptrCast(*const IITResultSet, self), lpvHdr, lpvData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Set(self: *const T, lRowIndex: i32, lColumnIndex: i32, lpvData: ?*anyopaque, cbData: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Set(@ptrCast(*const IITResultSet, self), lRowIndex, lColumnIndex, lpvData, cbData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Set1(self: *const T, lRowIndex: i32, lColumnIndex: i32, lpwStr: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Set(@ptrCast(*const IITResultSet, self), lRowIndex, lColumnIndex, lpwStr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Set2(self: *const T, lRowIndex: i32, lColumnIndex: i32, dwData: usize) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Set(@ptrCast(*const IITResultSet, self), lRowIndex, lColumnIndex, dwData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Set3(self: *const T, lRowIndex: i32, lpvHdr: ?*anyopaque, lpvData: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Set(@ptrCast(*const IITResultSet, self), lRowIndex, lpvHdr, lpvData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Copy(self: *const T, pRSCopy: ?*IITResultSet) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Copy(@ptrCast(*const IITResultSet, self), pRSCopy); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_AppendRows(self: *const T, pResSrc: ?*IITResultSet, lRowSrcFirst: i32, cSrcRows: i32, lRowFirstDest: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).AppendRows(@ptrCast(*const IITResultSet, self), pResSrc, lRowSrcFirst, cSrcRows, lRowFirstDest); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Get(self: *const T, lRowIndex: i32, lColumnIndex: i32, Prop: ?*CProperty) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Get(@ptrCast(*const IITResultSet, self), lRowIndex, lColumnIndex, Prop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetKeyProp(self: *const T, KeyPropID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetKeyProp(@ptrCast(*const IITResultSet, self), KeyPropID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetColumnPriority(self: *const T, lColumnIndex: i32, ColumnPriority: ?*PRIORITY) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetColumnPriority(@ptrCast(*const IITResultSet, self), lColumnIndex, ColumnPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetRowCount(self: *const T, lNumberOfRows: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetRowCount(@ptrCast(*const IITResultSet, self), lNumberOfRows); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetColumnCount(self: *const T, lNumberOfColumns: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetColumnCount(@ptrCast(*const IITResultSet, self), lNumberOfColumns); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetColumn(self: *const T, lColumnIndex: i32, PropID: ?*u32, dwType: ?*u32, lpvDefaultValue: ?*?*anyopaque, cbSize: ?*u32, ColumnPriority: ?*PRIORITY) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetColumn(@ptrCast(*const IITResultSet, self), lColumnIndex, PropID, dwType, lpvDefaultValue, cbSize, ColumnPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetColumn1(self: *const T, lColumnIndex: i32, PropID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetColumn(@ptrCast(*const IITResultSet, self), lColumnIndex, PropID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetColumnFromPropID(self: *const T, PropID: u32, lColumnIndex: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetColumnFromPropID(@ptrCast(*const IITResultSet, self), PropID, lColumnIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Clear(@ptrCast(*const IITResultSet, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_ClearRows(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).ClearRows(@ptrCast(*const IITResultSet, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Free(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Free(@ptrCast(*const IITResultSet, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_IsCompleted(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).IsCompleted(@ptrCast(*const IITResultSet, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Cancel(@ptrCast(*const IITResultSet, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_Pause(self: *const T, fPause: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).Pause(@ptrCast(*const IITResultSet, self), fPause); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetRowStatus(self: *const T, lRowFirst: i32, cRows: i32, lpRowStatus: ?*ROWSTATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetRowStatus(@ptrCast(*const IITResultSet, self), lRowFirst, cRows, lpRowStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IITResultSet_GetColumnStatus(self: *const T, lpColStatus: ?*COLUMNSTATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IITResultSet.VTable, self.vtable).GetColumnStatus(@ptrCast(*const IITResultSet, self), lpColStatus); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (0) //-------------------------------------------------------------------------------- //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (15) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IPersistStreamInit = @import("../system/com.zig").IPersistStreamInit; const IStemmer = @import("../system/search.zig").IStemmer; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const NMHDR = @import("../ui/controls.zig").NMHDR; const POINT = @import("../foundation.zig").POINT; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; 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(), "PFNCOLHEAPFREE")) { _ = PFNCOLHEAPFREE; } @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/data/html_help.zig
const std = @import("std"); const assert = std.debug.assert; const crypto = std.crypto; const log = std.log.scoped(.state_machine); const mem = std.mem; const Allocator = mem.Allocator; usingnamespace @import("tigerbeetle.zig"); const HashMapAccounts = std.AutoHashMap(u128, Account); const HashMapTransfers = std.AutoHashMap(u128, Transfer); pub const Operation = packed enum(u8) { // We reserve command "0" to detect an accidental zero byte being interpreted as an operation: reserved, init, create_accounts, create_transfers, commit_transfers, lookup_accounts, pub fn jsonStringify(self: Command, options: StringifyOptions, writer: anytype) !void { try std.fmt.format(writer, "\"{}\"", .{@tagName(self)}); } }; pub const StateMachine = struct { allocator: *Allocator, prepare_timestamp: u64, commit_timestamp: u64, accounts: HashMapAccounts, transfers: HashMapTransfers, pub fn init(allocator: *Allocator, accounts_max: usize, transfers_max: usize) !StateMachine { var accounts = HashMapAccounts.init(allocator); errdefer accounts.deinit(); try accounts.ensureCapacity(@intCast(u32, accounts_max)); var transfers = HashMapTransfers.init(allocator); errdefer transfers.deinit(); try transfers.ensureCapacity(@intCast(u32, transfers_max)); // TODO After recovery, set prepare_timestamp max(wall clock, op timestamp). // TODO After recovery, set commit_timestamp max(wall clock, commit timestamp). return StateMachine{ .allocator = allocator, .prepare_timestamp = 0, .commit_timestamp = 0, .accounts = accounts, .transfers = transfers, }; } pub fn deinit(self: *StateMachine) void { self.accounts.deinit(); self.transfers.deinit(); } pub fn prepare(self: *StateMachine, operation: Operation, batch: []u8) void { switch (operation) { .create_accounts => self.prepare_timestamps(Account, batch), .create_transfers => self.prepare_timestamps(Transfer, batch), .commit_transfers => self.prepare_timestamps(Commit, batch), .lookup_accounts => {}, else => unreachable, } } pub fn prepare_timestamps(self: *StateMachine, comptime T: type, batch: []u8) void { // Guard against the wall clock going backwards by taking the max with timestamps issued: self.prepare_timestamp = std.math.max( self.prepare_timestamp, @intCast(u64, std.time.nanoTimestamp()), ); assert(self.prepare_timestamp > self.commit_timestamp); var sum_reserved_timestamps: usize = 0; for (mem.bytesAsSlice(T, batch)) |*event| { sum_reserved_timestamps += event.timestamp; self.prepare_timestamp += 1; event.timestamp = self.prepare_timestamp; } // The client is responsible for ensuring that timestamps are reserved: // Use a single branch condition to detect non-zero reserved timestamps. // Summing then branching once is faster than branching every iteration of the loop. assert(sum_reserved_timestamps == 0); } pub fn commit( self: *StateMachine, operation: Operation, batch: []const u8, results: []u8, ) usize { return switch (operation) { .init => 0, .create_accounts => self.apply_create_accounts(batch, results), .create_transfers => self.apply_create_transfers(batch, results), .commit_transfers => self.apply_commit_transfers(batch, results), .lookup_accounts => self.apply_lookup_accounts(batch, results), else => unreachable, }; } pub fn apply_create_accounts(self: *StateMachine, input: []const u8, output: []u8) usize { const batch = mem.bytesAsSlice(Account, input); var results = mem.bytesAsSlice(CreateAccountResults, output); var results_count: usize = 0; for (batch) |event, index| { log.debug("create_accounts {}/{}: {}", .{ index + 1, batch.len, event }); const result = self.create_account(event); log.debug("{}", .{result}); if (result != .ok) { results[results_count] = .{ .index = @intCast(u32, index), .result = result }; results_count += 1; } } return results_count * @sizeOf(CreateAccountResults); } pub fn apply_create_transfers(self: *StateMachine, input: []const u8, output: []u8) usize { const batch = mem.bytesAsSlice(Transfer, input); var results = mem.bytesAsSlice(CreateTransferResults, output); var results_count: usize = 0; for (batch) |event, index| { log.debug("create_transfers {}/{}: {}", .{ index + 1, batch.len, event }); const result = self.create_transfer(event); log.debug("{}", .{result}); if (result != .ok) { results[results_count] = .{ .index = @intCast(u32, index), .result = result }; results_count += 1; } } return results_count * @sizeOf(CreateTransferResults); } pub fn apply_commit_transfers(self: *StateMachine, input: []const u8, output: []u8) usize { const batch = mem.bytesAsSlice(Commit, input); var results = mem.bytesAsSlice(CommitTransferResults, output); var results_count: usize = 0; for (batch) |event, index| { log.debug("commit_transfers {}/{}: {}", .{ index + 1, batch.len, event }); const result = self.commit_transfer(event); log.debug("{}", .{result}); if (result != .ok) { results[results_count] = .{ .index = @intCast(u32, index), .result = result }; results_count += 1; } } return results_count * @sizeOf(CommitTransferResults); } pub fn apply_lookup_accounts(self: *StateMachine, input: []const u8, output: []u8) usize { const batch = mem.bytesAsSlice(u128, input); // TODO Do the same for other apply methods: var output_len = @divFloor(output.len, @sizeOf(Account)) * @sizeOf(Account); var results = mem.bytesAsSlice(Account, output[0..output_len]); var results_count: usize = 0; for (batch) |id, index| { if (self.get_account(id)) |result| { results[results_count] = result.*; results_count += 1; } } return results_count * @sizeOf(Account); } pub fn create_account(self: *StateMachine, a: Account) CreateAccountResult { assert(a.timestamp > self.commit_timestamp); if (a.custom != 0) return .reserved_field_custom; if (a.padding != 0) return .reserved_field_padding; if (a.flags.padding != 0) return .reserved_flag_padding; // Opening balances may never exceed limits: if (a.exceeds_debit_reserved_limit(0)) return .exceeds_debit_reserved_limit; if (a.exceeds_debit_accepted_limit(0)) return .exceeds_debit_accepted_limit; if (a.exceeds_credit_reserved_limit(0)) return .exceeds_credit_reserved_limit; if (a.exceeds_credit_accepted_limit(0)) return .exceeds_credit_accepted_limit; // Accounts may never reserve more than they could possibly accept: if (a.debit_accepted_limit > 0 and a.debit_reserved_limit > a.debit_accepted_limit) { return .debit_reserved_limit_exceeds_debit_accepted_limit; } if (a.credit_accepted_limit > 0 and a.credit_reserved_limit > a.credit_accepted_limit) { return .credit_reserved_limit_exceeds_credit_accepted_limit; } var hash_map_result = self.accounts.getOrPutAssumeCapacity(a.id); if (hash_map_result.found_existing) { const exists = hash_map_result.entry.value; if (exists.unit != a.unit) return .exists_with_different_unit; if (exists.debit_reserved_limit != a.debit_reserved_limit or exists.debit_accepted_limit != a.debit_accepted_limit or exists.credit_reserved_limit != a.credit_reserved_limit or exists.credit_accepted_limit != a.credit_accepted_limit) { return .exists_with_different_limits; } if (exists.custom != a.custom) return .exists_with_different_custom_field; if (@bitCast(u64, exists.flags) != @bitCast(u64, a.flags)) { return .exists_with_different_flags; } return .exists; } else { hash_map_result.entry.value = a; self.commit_timestamp = a.timestamp; return .ok; } } pub fn create_transfer(self: *StateMachine, t: Transfer) CreateTransferResult { assert(t.timestamp > self.commit_timestamp); if (t.flags.padding != 0) return .reserved_flag_padding; if (t.flags.accept and !t.flags.auto_commit) return .reserved_flag_accept; if (t.flags.reject) return .reserved_flag_reject; if (t.flags.auto_commit) { if (!t.flags.accept) return .auto_commit_must_accept; if (t.timeout != 0) return .auto_commit_cannot_timeout; } if (t.custom_1 != 0 or t.custom_2 != 0) { if (!t.flags.condition) return .reserved_field_custom; } if (t.custom_3 != 0) return .reserved_field_custom; if (t.amount == 0) return .amount_is_zero; if (t.debit_account_id == t.credit_account_id) return .accounts_are_the_same; // The etymology of the DR and CR abbreviations for debit and credit is interesting, either: // 1. derived from the Latin past participles of debitum and creditum, debere and credere, // 2. standing for debit record and credit record, or // 3. relating to debtor and creditor. // We use them to distinguish between `cr` (credit account), and `c` (commit). var dr = self.get_account(t.debit_account_id) orelse return .debit_account_not_found; var cr = self.get_account(t.credit_account_id) orelse return .credit_account_not_found; assert(t.timestamp > dr.timestamp); assert(t.timestamp > cr.timestamp); if (dr.unit != cr.unit) return .accounts_have_different_units; // TODO We need a lookup before inserting in case transfer exists and would overflow limits. if (!t.flags.auto_commit) { if (dr.exceeds_debit_reserved_limit(t.amount)) return .exceeds_debit_reserved_limit; if (cr.exceeds_credit_reserved_limit(t.amount)) return .exceeds_credit_reserved_limit; } if (dr.exceeds_debit_accepted_limit(t.amount)) return .exceeds_debit_accepted_limit; if (cr.exceeds_credit_accepted_limit(t.amount)) return .exceeds_credit_accepted_limit; var hash_map_result = self.transfers.getOrPutAssumeCapacity(t.id); if (hash_map_result.found_existing) { const exists = hash_map_result.entry.value; if (exists.debit_account_id != t.debit_account_id) { return .exists_with_different_debit_account_id; } if (exists.credit_account_id != t.credit_account_id) { return .exists_with_different_credit_account_id; } if (exists.custom_1 != t.custom_1 or exists.custom_2 != t.custom_2 or exists.custom_3 != t.custom_3) { return .exists_with_different_custom_fields; } if (exists.amount != t.amount) return .exists_with_different_amount; if (exists.timeout != t.timeout) return .exists_with_different_timeout; if (@bitCast(u64, exists.flags) != @bitCast(u64, t.flags)) { if (!exists.flags.auto_commit and !t.flags.auto_commit) { if (exists.flags.accept) return .exists_and_already_committed_and_accepted; if (exists.flags.reject) return .exists_and_already_committed_and_rejected; } return .exists_with_different_flags; } return .exists; } else { hash_map_result.entry.value = t; if (t.flags.auto_commit) { dr.debit_accepted += t.amount; cr.credit_accepted += t.amount; } else { dr.debit_reserved += t.amount; cr.credit_reserved += t.amount; } self.commit_timestamp = t.timestamp; return .ok; } } pub fn commit_transfer(self: *StateMachine, c: Commit) CommitTransferResult { assert(c.timestamp > self.commit_timestamp); if (c.flags.padding != 0) return .reserved_flag_padding; if (!c.flags.accept and !c.flags.reject) return .commit_must_accept_or_reject; if (c.flags.accept and c.flags.reject) return .commit_cannot_accept_and_reject; if (c.custom_1 != 0 or c.custom_2 != 0) { if (!c.flags.preimage) return .reserved_field_custom; } if (c.custom_3 != 0) return .reserved_field_custom; var t = self.get_transfer(c.id) orelse return .transfer_not_found; assert(c.timestamp > t.timestamp); if (t.flags.accept or t.flags.reject) { if (t.flags.auto_commit) return .already_auto_committed; if (t.flags.accept and c.flags.reject) return .already_committed_but_accepted; if (t.flags.reject and c.flags.accept) return .already_committed_but_rejected; return .already_committed; } if (t.timeout > 0 and t.timestamp + t.timeout <= c.timestamp) return .transfer_expired; if (t.flags.condition) { if (!c.flags.preimage) return .condition_requires_preimage; } else if (c.flags.preimage) { return .preimage_requires_condition; } var dr = self.get_account(t.debit_account_id) orelse return .debit_account_not_found; var cr = self.get_account(t.credit_account_id) orelse return .credit_account_not_found; assert(t.timestamp > dr.timestamp); assert(t.timestamp > cr.timestamp); assert(!t.flags.auto_commit); if (dr.debit_reserved < t.amount) return .debit_amount_was_not_reserved; if (cr.credit_reserved < t.amount) return .credit_amount_was_not_reserved; if (dr.exceeds_debit_accepted_limit(t.amount)) return .exceeds_debit_accepted_limit; if (dr.exceeds_credit_accepted_limit(t.amount)) return .exceeds_credit_accepted_limit; dr.debit_reserved -= t.amount; cr.credit_reserved -= t.amount; if (c.flags.accept) { t.flags.accept = true; dr.debit_accepted += t.amount; cr.credit_accepted += t.amount; } else { assert(c.flags.reject); t.flags.reject = true; } assert(t.flags.accept or t.flags.reject); self.commit_timestamp = c.timestamp; return .ok; } pub fn valid_preimage(condition: u256, preimage: u256) bool { var target: [32]u8 = undefined; crypto.hash.sha2.Sha256.hash(@bitCast([32]u8, preimage)[0..], target[0..], .{}); return mem.eql(u8, target[0..], @bitCast([32]u8, condition)[0..]); } /// This is our core private method for changing balances. /// Returns a live pointer to an Account entry in the accounts hash map. /// This is intended to lookup an Account and modify balances directly by reference. /// This pointer is invalidated if the hash map is resized by another insert, e.g. if we get a /// pointer, insert another account without capacity, and then modify this pointer... BOOM! /// This is a sharp tool but replaces a lookup, copy and update with a single lookup. fn get_account(self: *StateMachine, id: u128) ?*Account { if (self.accounts.getEntry(id)) |entry| { return &entry.value; } else { return null; } } /// See the above comment for get_account(). fn get_transfer(self: *StateMachine, id: u128) ?*Transfer { if (self.transfers.getEntry(id)) |entry| { return &entry.value; } else { return null; } } };
src/state_machine.zig
pub const WM_ADSPROP_NOTIFY_PAGEINIT = @as(u32, 2125); pub const WM_ADSPROP_NOTIFY_PAGEHWND = @as(u32, 2126); pub const WM_ADSPROP_NOTIFY_CHANGE = @as(u32, 2127); pub const WM_ADSPROP_NOTIFY_APPLY = @as(u32, 2128); pub const WM_ADSPROP_NOTIFY_SETFOCUS = @as(u32, 2129); pub const WM_ADSPROP_NOTIFY_FOREGROUND = @as(u32, 2130); pub const WM_ADSPROP_NOTIFY_EXIT = @as(u32, 2131); pub const WM_ADSPROP_NOTIFY_ERROR = @as(u32, 2134); pub const CLSID_CommonQuery = Guid.initString("83bc5ec0-6f2a-11d0-a1c4-00aa00c16e65"); pub const QUERYFORM_CHANGESFORMLIST = @as(u64, 1); pub const QUERYFORM_CHANGESOPTFORMLIST = @as(u64, 2); pub const CQFF_NOGLOBALPAGES = @as(u32, 1); pub const CQFF_ISOPTIONAL = @as(u32, 2); pub const CQPM_INITIALIZE = @as(u32, 1); pub const CQPM_RELEASE = @as(u32, 2); pub const CQPM_ENABLE = @as(u32, 3); pub const CQPM_GETPARAMETERS = @as(u32, 5); pub const CQPM_CLEARFORM = @as(u32, 6); pub const CQPM_PERSIST = @as(u32, 7); pub const CQPM_HELP = @as(u32, 8); pub const CQPM_SETDEFAULTPARAMETERS = @as(u32, 9); pub const CQPM_HANDLERSPECIFIC = @as(u32, 268435456); pub const OQWF_OKCANCEL = @as(u32, 1); pub const OQWF_DEFAULTFORM = @as(u32, 2); pub const OQWF_SINGLESELECT = @as(u32, 4); pub const OQWF_LOADQUERY = @as(u32, 8); pub const OQWF_REMOVESCOPES = @as(u32, 16); pub const OQWF_REMOVEFORMS = @as(u32, 32); pub const OQWF_ISSUEONOPEN = @as(u32, 64); pub const OQWF_SHOWOPTIONAL = @as(u32, 128); pub const OQWF_SAVEQUERYONOK = @as(u32, 512); pub const OQWF_HIDEMENUS = @as(u32, 1024); pub const OQWF_HIDESEARCHUI = @as(u32, 2048); pub const OQWF_PARAMISPROPERTYBAG = @as(u32, 2147483648); pub const CLSID_DsAdminCreateObj = Guid.initString("e301a009-f901-11d2-82b9-00c04f68928b"); pub const DSA_NEWOBJ_CTX_PRECOMMIT = @as(u32, 1); pub const DSA_NEWOBJ_CTX_COMMIT = @as(u32, 2); pub const DSA_NEWOBJ_CTX_POSTCOMMIT = @as(u32, 3); pub const DSA_NEWOBJ_CTX_CLEANUP = @as(u32, 4); pub const DSA_NOTIFY_DEL = @as(u32, 1); pub const DSA_NOTIFY_REN = @as(u32, 2); pub const DSA_NOTIFY_MOV = @as(u32, 4); pub const DSA_NOTIFY_PROP = @as(u32, 8); pub const DSA_NOTIFY_FLAG_ADDITIONAL_DATA = @as(u32, 2); pub const DSA_NOTIFY_FLAG_FORCE_ADDITIONAL_DATA = @as(u32, 1); pub const CLSID_MicrosoftDS = Guid.initString("fe1290f0-cfbd-11cf-a330-00aa00c16e65"); pub const CLSID_DsPropertyPages = Guid.initString("0d45d530-764b-11d0-a1ca-00aa00c16e65"); pub const CLSID_DsDomainTreeBrowser = Guid.initString("1698790a-e2b4-11d0-b0b1-00c04fd8dca6"); pub const CLSID_DsDisplaySpecifier = Guid.initString("1ab4a8c0-6a0b-11d2-ad49-00c04fa31a86"); pub const CLSID_DsFolderProperties = Guid.initString("9e51e0d0-6e0f-11d2-9601-00c04fa31a86"); pub const DSOBJECT_ISCONTAINER = @as(u32, 1); pub const DSOBJECT_READONLYPAGES = @as(u32, 2147483648); pub const DSPROVIDER_UNUSED_0 = @as(u32, 1); pub const DSPROVIDER_UNUSED_1 = @as(u32, 2); pub const DSPROVIDER_UNUSED_2 = @as(u32, 4); pub const DSPROVIDER_UNUSED_3 = @as(u32, 8); pub const DSPROVIDER_ADVANCED = @as(u32, 16); pub const DSPROVIDER_AD_LDS = @as(u32, 32); pub const DSDSOF_HASUSERANDSERVERINFO = @as(u32, 1); pub const DSDSOF_SIMPLEAUTHENTICATE = @as(u32, 2); pub const DSDSOF_DONTSIGNSEAL = @as(u32, 4); pub const DSDSOF_DSAVAILABLE = @as(u32, 1073741824); pub const DBDTF_RETURNFQDN = @as(u32, 1); pub const DBDTF_RETURNMIXEDDOMAINS = @as(u32, 2); pub const DBDTF_RETURNEXTERNAL = @as(u32, 4); pub const DBDTF_RETURNINBOUND = @as(u32, 8); pub const DBDTF_RETURNINOUTBOUND = @as(u32, 16); pub const DSSSF_SIMPLEAUTHENTICATE = @as(u32, 1); pub const DSSSF_DONTSIGNSEAL = @as(u32, 2); pub const DSSSF_DSAVAILABLE = @as(u32, 2147483648); pub const DSGIF_ISNORMAL = @as(u32, 0); pub const DSGIF_ISOPEN = @as(u32, 1); pub const DSGIF_ISDISABLED = @as(u32, 2); pub const DSGIF_ISMASK = @as(u32, 15); pub const DSGIF_GETDEFAULTICON = @as(u32, 16); pub const DSGIF_DEFAULTISCONTAINER = @as(u32, 32); pub const DSICCF_IGNORETREATASLEAF = @as(u32, 1); pub const DSECAF_NOTLISTED = @as(u32, 1); pub const DSCCIF_HASWIZARDDIALOG = @as(u32, 1); pub const DSCCIF_HASWIZARDPRIMARYPAGE = @as(u32, 2); pub const DSBI_NOBUTTONS = @as(u32, 1); pub const DSBI_NOLINES = @as(u32, 2); pub const DSBI_NOLINESATROOT = @as(u32, 4); pub const DSBI_CHECKBOXES = @as(u32, 256); pub const DSBI_NOROOT = @as(u32, 65536); pub const DSBI_INCLUDEHIDDEN = @as(u32, 131072); pub const DSBI_EXPANDONOPEN = @as(u32, 262144); pub const DSBI_ENTIREDIRECTORY = @as(u32, 589824); pub const DSBI_RETURN_FORMAT = @as(u32, 1048576); pub const DSBI_HASCREDENTIALS = @as(u32, 2097152); pub const DSBI_IGNORETREATASLEAF = @as(u32, 4194304); pub const DSBI_SIMPLEAUTHENTICATE = @as(u32, 8388608); pub const DSBI_RETURNOBJECTCLASS = @as(u32, 16777216); pub const DSBI_DONTSIGNSEAL = @as(u32, 33554432); pub const DSB_MAX_DISPLAYNAME_CHARS = @as(u32, 64); pub const DSBF_STATE = @as(u32, 1); pub const DSBF_ICONLOCATION = @as(u32, 2); pub const DSBF_DISPLAYNAME = @as(u32, 4); pub const DSBS_CHECKED = @as(u32, 1); pub const DSBS_HIDDEN = @as(u32, 2); pub const DSBS_ROOT = @as(u32, 4); pub const DSBM_QUERYINSERTW = @as(u32, 100); pub const DSBM_QUERYINSERTA = @as(u32, 101); pub const DSBM_QUERYINSERT = @as(u32, 100); pub const DSBM_CHANGEIMAGESTATE = @as(u32, 102); pub const DSBM_HELP = @as(u32, 103); pub const DSBM_CONTEXTMENU = @as(u32, 104); pub const DSBID_BANNER = @as(u32, 256); pub const DSBID_CONTAINERLIST = @as(u32, 257); pub const DS_FORCE_REDISCOVERY = @as(u32, 1); pub const DS_DIRECTORY_SERVICE_REQUIRED = @as(u32, 16); pub const DS_DIRECTORY_SERVICE_PREFERRED = @as(u32, 32); pub const DS_GC_SERVER_REQUIRED = @as(u32, 64); pub const DS_PDC_REQUIRED = @as(u32, 128); pub const DS_BACKGROUND_ONLY = @as(u32, 256); pub const DS_IP_REQUIRED = @as(u32, 512); pub const DS_KDC_REQUIRED = @as(u32, 1024); pub const DS_TIMESERV_REQUIRED = @as(u32, 2048); pub const DS_WRITABLE_REQUIRED = @as(u32, 4096); pub const DS_GOOD_TIMESERV_PREFERRED = @as(u32, 8192); pub const DS_AVOID_SELF = @as(u32, 16384); pub const DS_ONLY_LDAP_NEEDED = @as(u32, 32768); pub const DS_IS_FLAT_NAME = @as(u32, 65536); pub const DS_IS_DNS_NAME = @as(u32, 131072); pub const DS_TRY_NEXTCLOSEST_SITE = @as(u32, 262144); pub const DS_DIRECTORY_SERVICE_6_REQUIRED = @as(u32, 524288); pub const DS_WEB_SERVICE_REQUIRED = @as(u32, 1048576); pub const DS_DIRECTORY_SERVICE_8_REQUIRED = @as(u32, 2097152); pub const DS_DIRECTORY_SERVICE_9_REQUIRED = @as(u32, 4194304); pub const DS_DIRECTORY_SERVICE_10_REQUIRED = @as(u32, 8388608); pub const DS_KEY_LIST_SUPPORT_REQUIRED = @as(u32, 16777216); pub const DS_RETURN_DNS_NAME = @as(u32, 1073741824); pub const DS_RETURN_FLAT_NAME = @as(u32, 2147483648); pub const DS_PDC_FLAG = @as(u32, 1); pub const DS_GC_FLAG = @as(u32, 4); pub const DS_LDAP_FLAG = @as(u32, 8); pub const DS_DS_FLAG = @as(u32, 16); pub const DS_KDC_FLAG = @as(u32, 32); pub const DS_TIMESERV_FLAG = @as(u32, 64); pub const DS_CLOSEST_FLAG = @as(u32, 128); pub const DS_WRITABLE_FLAG = @as(u32, 256); pub const DS_GOOD_TIMESERV_FLAG = @as(u32, 512); pub const DS_NDNC_FLAG = @as(u32, 1024); pub const DS_SELECT_SECRET_DOMAIN_6_FLAG = @as(u32, 2048); pub const DS_FULL_SECRET_DOMAIN_6_FLAG = @as(u32, 4096); pub const DS_WS_FLAG = @as(u32, 8192); pub const DS_DS_8_FLAG = @as(u32, 16384); pub const DS_DS_9_FLAG = @as(u32, 32768); pub const DS_DS_10_FLAG = @as(u32, 65536); pub const DS_KEY_LIST_FLAG = @as(u32, 131072); pub const DS_PING_FLAGS = @as(u32, 1048575); pub const DS_DNS_CONTROLLER_FLAG = @as(u32, 536870912); pub const DS_DNS_DOMAIN_FLAG = @as(u32, 1073741824); pub const DS_DNS_FOREST_FLAG = @as(u32, 2147483648); pub const DS_DOMAIN_IN_FOREST = @as(u32, 1); pub const DS_DOMAIN_DIRECT_OUTBOUND = @as(u32, 2); pub const DS_DOMAIN_TREE_ROOT = @as(u32, 4); pub const DS_DOMAIN_PRIMARY = @as(u32, 8); pub const DS_DOMAIN_NATIVE_MODE = @as(u32, 16); pub const DS_DOMAIN_DIRECT_INBOUND = @as(u32, 32); pub const DS_GFTI_UPDATE_TDO = @as(u32, 1); pub const DS_GFTI_VALID_FLAGS = @as(u32, 1); pub const DS_ONLY_DO_SITE_NAME = @as(u32, 1); pub const DS_NOTIFY_AFTER_SITE_RECORDS = @as(u32, 2); pub const CLSID_DsQuery = Guid.initString("8a23e65e-31c2-11d0-891c-00a024ab2dbb"); pub const CLSID_DsFindObjects = Guid.initString("83ee3fe1-57d9-11d0-b932-00a024ab2dbb"); pub const CLSID_DsFindPeople = Guid.initString("83ee3fe2-57d9-11d0-b932-00a024ab2dbb"); pub const CLSID_DsFindPrinter = Guid.initString("b577f070-7ee2-11d0-913f-00aa00c16e65"); pub const CLSID_DsFindComputer = Guid.initString("16006700-87ad-11d0-9140-00aa00c16e65"); pub const CLSID_DsFindVolume = Guid.initString("c1b3cbf1-886a-11d0-9140-00aa00c16e65"); pub const CLSID_DsFindContainer = Guid.initString("c1b3cbf2-886a-11d0-9140-00aa00c16e65"); pub const CLSID_DsFindAdvanced = Guid.initString("83ee3fe3-57d9-11d0-b932-00a024ab2dbb"); pub const CLSID_DsFindDomainController = Guid.initString("538c7b7e-d25e-11d0-9742-00a0c906af45"); pub const CLSID_DsFindWriteableDomainController = Guid.initString("7cbef079-aa84-444b-bc70-68e41283eabc"); pub const CLSID_DsFindFrsMembers = Guid.initString("94ce4b18-b3d3-11d1-b9b4-00c04fd8d5b0"); pub const DSQPF_NOSAVE = @as(u32, 1); pub const DSQPF_SAVELOCATION = @as(u32, 2); pub const DSQPF_SHOWHIDDENOBJECTS = @as(u32, 4); pub const DSQPF_ENABLEADMINFEATURES = @as(u32, 8); pub const DSQPF_ENABLEADVANCEDFEATURES = @as(u32, 16); pub const DSQPF_HASCREDENTIALS = @as(u32, 32); pub const DSQPF_NOCHOOSECOLUMNS = @as(u32, 64); pub const DSQPM_GETCLASSLIST = @as(u32, 268435456); pub const DSQPM_HELPTOPICS = @as(u32, 268435457); pub const DSROLE_PRIMARY_DS_RUNNING = @as(u32, 1); pub const DSROLE_PRIMARY_DS_MIXED_MODE = @as(u32, 2); pub const DSROLE_UPGRADE_IN_PROGRESS = @as(u32, 4); pub const DSROLE_PRIMARY_DS_READONLY = @as(u32, 8); pub const DSROLE_PRIMARY_DOMAIN_GUID_PRESENT = @as(u32, 16777216); pub const ADS_ATTR_CLEAR = @as(u32, 1); pub const ADS_ATTR_UPDATE = @as(u32, 2); pub const ADS_ATTR_APPEND = @as(u32, 3); pub const ADS_ATTR_DELETE = @as(u32, 4); pub const ADS_EXT_MINEXTDISPID = @as(u32, 1); pub const ADS_EXT_MAXEXTDISPID = @as(u32, 16777215); pub const ADS_EXT_INITCREDENTIALS = @as(u32, 1); pub const ADS_EXT_INITIALIZE_COMPLETE = @as(u32, 2); pub const DS_BEHAVIOR_WIN2000 = @as(u32, 0); pub const DS_BEHAVIOR_WIN2003_WITH_MIXED_DOMAINS = @as(u32, 1); pub const DS_BEHAVIOR_WIN2003 = @as(u32, 2); pub const DS_BEHAVIOR_WIN2008 = @as(u32, 3); pub const DS_BEHAVIOR_WIN2008R2 = @as(u32, 4); pub const DS_BEHAVIOR_WIN2012 = @as(u32, 5); pub const DS_BEHAVIOR_WIN2012R2 = @as(u32, 6); pub const DS_BEHAVIOR_WIN2016 = @as(u32, 7); pub const DS_BEHAVIOR_LONGHORN = @as(u32, 3); pub const DS_BEHAVIOR_WIN7 = @as(u32, 4); pub const DS_BEHAVIOR_WIN8 = @as(u32, 5); pub const DS_BEHAVIOR_WINBLUE = @as(u32, 6); pub const DS_BEHAVIOR_WINTHRESHOLD = @as(u32, 7); pub const ACTRL_DS_OPEN = @as(u32, 0); pub const ACTRL_DS_CREATE_CHILD = @as(u32, 1); pub const ACTRL_DS_DELETE_CHILD = @as(u32, 2); pub const ACTRL_DS_LIST = @as(u32, 4); pub const ACTRL_DS_SELF = @as(u32, 8); pub const ACTRL_DS_READ_PROP = @as(u32, 16); pub const ACTRL_DS_WRITE_PROP = @as(u32, 32); pub const ACTRL_DS_DELETE_TREE = @as(u32, 64); pub const ACTRL_DS_LIST_OBJECT = @as(u32, 128); pub const ACTRL_DS_CONTROL_ACCESS = @as(u32, 256); pub const NTDSAPI_BIND_ALLOW_DELEGATION = @as(u32, 1); pub const NTDSAPI_BIND_FIND_BINDING = @as(u32, 2); pub const NTDSAPI_BIND_FORCE_KERBEROS = @as(u32, 4); pub const DS_REPSYNC_ASYNCHRONOUS_OPERATION = @as(u32, 1); pub const DS_REPSYNC_WRITEABLE = @as(u32, 2); pub const DS_REPSYNC_PERIODIC = @as(u32, 4); pub const DS_REPSYNC_INTERSITE_MESSAGING = @as(u32, 8); pub const DS_REPSYNC_FULL = @as(u32, 32); pub const DS_REPSYNC_URGENT = @as(u32, 64); pub const DS_REPSYNC_NO_DISCARD = @as(u32, 128); pub const DS_REPSYNC_FORCE = @as(u32, 256); pub const DS_REPSYNC_ADD_REFERENCE = @as(u32, 512); pub const DS_REPSYNC_NEVER_COMPLETED = @as(u32, 1024); pub const DS_REPSYNC_TWO_WAY = @as(u32, 2048); pub const DS_REPSYNC_NEVER_NOTIFY = @as(u32, 4096); pub const DS_REPSYNC_INITIAL = @as(u32, 8192); pub const DS_REPSYNC_USE_COMPRESSION = @as(u32, 16384); pub const DS_REPSYNC_ABANDONED = @as(u32, 32768); pub const DS_REPSYNC_SELECT_SECRETS = @as(u32, 32768); pub const DS_REPSYNC_INITIAL_IN_PROGRESS = @as(u32, 65536); pub const DS_REPSYNC_PARTIAL_ATTRIBUTE_SET = @as(u32, 131072); pub const DS_REPSYNC_REQUEUE = @as(u32, 262144); pub const DS_REPSYNC_NOTIFICATION = @as(u32, 524288); pub const DS_REPSYNC_ASYNCHRONOUS_REPLICA = @as(u32, 1048576); pub const DS_REPSYNC_CRITICAL = @as(u32, 2097152); pub const DS_REPSYNC_FULL_IN_PROGRESS = @as(u32, 4194304); pub const DS_REPSYNC_PREEMPTED = @as(u32, 8388608); pub const DS_REPSYNC_NONGC_RO_REPLICA = @as(u32, 16777216); pub const DS_REPADD_ASYNCHRONOUS_OPERATION = @as(u32, 1); pub const DS_REPADD_WRITEABLE = @as(u32, 2); pub const DS_REPADD_INITIAL = @as(u32, 4); pub const DS_REPADD_PERIODIC = @as(u32, 8); pub const DS_REPADD_INTERSITE_MESSAGING = @as(u32, 16); pub const DS_REPADD_ASYNCHRONOUS_REPLICA = @as(u32, 32); pub const DS_REPADD_DISABLE_NOTIFICATION = @as(u32, 64); pub const DS_REPADD_DISABLE_PERIODIC = @as(u32, 128); pub const DS_REPADD_USE_COMPRESSION = @as(u32, 256); pub const DS_REPADD_NEVER_NOTIFY = @as(u32, 512); pub const DS_REPADD_TWO_WAY = @as(u32, 1024); pub const DS_REPADD_CRITICAL = @as(u32, 2048); pub const DS_REPADD_SELECT_SECRETS = @as(u32, 4096); pub const DS_REPADD_NONGC_RO_REPLICA = @as(u32, 16777216); pub const DS_REPDEL_ASYNCHRONOUS_OPERATION = @as(u32, 1); pub const DS_REPDEL_WRITEABLE = @as(u32, 2); pub const DS_REPDEL_INTERSITE_MESSAGING = @as(u32, 4); pub const DS_REPDEL_IGNORE_ERRORS = @as(u32, 8); pub const DS_REPDEL_LOCAL_ONLY = @as(u32, 16); pub const DS_REPDEL_NO_SOURCE = @as(u32, 32); pub const DS_REPDEL_REF_OK = @as(u32, 64); pub const DS_REPMOD_ASYNCHRONOUS_OPERATION = @as(u32, 1); pub const DS_REPMOD_WRITEABLE = @as(u32, 2); pub const DS_REPMOD_UPDATE_FLAGS = @as(u32, 1); pub const DS_REPMOD_UPDATE_INSTANCE = @as(u32, 2); pub const DS_REPMOD_UPDATE_ADDRESS = @as(u32, 2); pub const DS_REPMOD_UPDATE_SCHEDULE = @as(u32, 4); pub const DS_REPMOD_UPDATE_RESULT = @as(u32, 8); pub const DS_REPMOD_UPDATE_TRANSPORT = @as(u32, 16); pub const DS_REPUPD_ASYNCHRONOUS_OPERATION = @as(u32, 1); pub const DS_REPUPD_WRITEABLE = @as(u32, 2); pub const DS_REPUPD_ADD_REFERENCE = @as(u32, 4); pub const DS_REPUPD_DELETE_REFERENCE = @as(u32, 8); pub const DS_REPUPD_REFERENCE_GCSPN = @as(u32, 16); pub const DS_INSTANCETYPE_IS_NC_HEAD = @as(u32, 1); pub const DS_INSTANCETYPE_NC_IS_WRITEABLE = @as(u32, 4); pub const DS_INSTANCETYPE_NC_COMING = @as(u32, 16); pub const DS_INSTANCETYPE_NC_GOING = @as(u32, 32); pub const NTDSDSA_OPT_IS_GC = @as(u32, 1); pub const NTDSDSA_OPT_DISABLE_INBOUND_REPL = @as(u32, 2); pub const NTDSDSA_OPT_DISABLE_OUTBOUND_REPL = @as(u32, 4); pub const NTDSDSA_OPT_DISABLE_NTDSCONN_XLATE = @as(u32, 8); pub const NTDSDSA_OPT_DISABLE_SPN_REGISTRATION = @as(u32, 16); pub const NTDSDSA_OPT_GENERATE_OWN_TOPO = @as(u32, 32); pub const NTDSDSA_OPT_BLOCK_RPC = @as(u32, 64); pub const NTDSCONN_OPT_IS_GENERATED = @as(u32, 1); pub const NTDSCONN_OPT_TWOWAY_SYNC = @as(u32, 2); pub const NTDSCONN_OPT_OVERRIDE_NOTIFY_DEFAULT = @as(u32, 4); pub const NTDSCONN_OPT_USE_NOTIFY = @as(u32, 8); pub const NTDSCONN_OPT_DISABLE_INTERSITE_COMPRESSION = @as(u32, 16); pub const NTDSCONN_OPT_USER_OWNED_SCHEDULE = @as(u32, 32); pub const NTDSCONN_OPT_RODC_TOPOLOGY = @as(u32, 64); pub const NTDSCONN_KCC_NO_REASON = @as(u32, 0); pub const NTDSCONN_KCC_GC_TOPOLOGY = @as(u32, 1); pub const NTDSCONN_KCC_RING_TOPOLOGY = @as(u32, 2); pub const NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY = @as(u32, 4); pub const NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY = @as(u32, 8); pub const NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY = @as(u32, 16); pub const NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY = @as(u32, 32); pub const NTDSCONN_KCC_INTERSITE_TOPOLOGY = @as(u32, 64); pub const NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY = @as(u32, 128); pub const NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY = @as(u32, 256); pub const NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY = @as(u32, 512); pub const FRSCONN_PRIORITY_MASK = @as(u32, 1879048192); pub const FRSCONN_MAX_PRIORITY = @as(u32, 8); pub const NTDSCONN_OPT_IGNORE_SCHEDULE_MASK = @as(u32, 2147483648); pub const NTDSSETTINGS_OPT_IS_AUTO_TOPOLOGY_DISABLED = @as(u32, 1); pub const NTDSSETTINGS_OPT_IS_TOPL_CLEANUP_DISABLED = @as(u32, 2); pub const NTDSSETTINGS_OPT_IS_TOPL_MIN_HOPS_DISABLED = @as(u32, 4); pub const NTDSSETTINGS_OPT_IS_TOPL_DETECT_STALE_DISABLED = @as(u32, 8); pub const NTDSSETTINGS_OPT_IS_INTER_SITE_AUTO_TOPOLOGY_DISABLED = @as(u32, 16); pub const NTDSSETTINGS_OPT_IS_GROUP_CACHING_ENABLED = @as(u32, 32); pub const NTDSSETTINGS_OPT_FORCE_KCC_WHISTLER_BEHAVIOR = @as(u32, 64); pub const NTDSSETTINGS_OPT_FORCE_KCC_W2K_ELECTION = @as(u32, 128); pub const NTDSSETTINGS_OPT_IS_RAND_BH_SELECTION_DISABLED = @as(u32, 256); pub const NTDSSETTINGS_OPT_IS_SCHEDULE_HASHING_ENABLED = @as(u32, 512); pub const NTDSSETTINGS_OPT_IS_REDUNDANT_SERVER_TOPOLOGY_ENABLED = @as(u32, 1024); pub const NTDSSETTINGS_OPT_W2K3_IGNORE_SCHEDULES = @as(u32, 2048); pub const NTDSSETTINGS_OPT_W2K3_BRIDGES_REQUIRED = @as(u32, 4096); pub const NTDSSETTINGS_DEFAULT_SERVER_REDUNDANCY = @as(u32, 2); pub const NTDSTRANSPORT_OPT_IGNORE_SCHEDULES = @as(u32, 1); pub const NTDSTRANSPORT_OPT_BRIDGES_REQUIRED = @as(u32, 2); pub const NTDSSITECONN_OPT_USE_NOTIFY = @as(u32, 1); pub const NTDSSITECONN_OPT_TWOWAY_SYNC = @as(u32, 2); pub const NTDSSITECONN_OPT_DISABLE_COMPRESSION = @as(u32, 4); pub const NTDSSITELINK_OPT_USE_NOTIFY = @as(u32, 1); pub const NTDSSITELINK_OPT_TWOWAY_SYNC = @as(u32, 2); pub const NTDSSITELINK_OPT_DISABLE_COMPRESSION = @as(u32, 4); pub const DS_REPSYNCALL_NO_OPTIONS = @as(u32, 0); pub const DS_REPSYNCALL_ABORT_IF_SERVER_UNAVAILABLE = @as(u32, 1); pub const DS_REPSYNCALL_SYNC_ADJACENT_SERVERS_ONLY = @as(u32, 2); pub const DS_REPSYNCALL_ID_SERVERS_BY_DN = @as(u32, 4); pub const DS_REPSYNCALL_DO_NOT_SYNC = @as(u32, 8); pub const DS_REPSYNCALL_SKIP_INITIAL_CHECK = @as(u32, 16); pub const DS_REPSYNCALL_PUSH_CHANGES_OUTWARD = @as(u32, 32); pub const DS_REPSYNCALL_CROSS_SITE_BOUNDARIES = @as(u32, 64); pub const DS_LIST_DSA_OBJECT_FOR_SERVER = @as(u32, 0); pub const DS_LIST_DNS_HOST_NAME_FOR_SERVER = @as(u32, 1); pub const DS_LIST_ACCOUNT_OBJECT_FOR_SERVER = @as(u32, 2); pub const DS_ROLE_SCHEMA_OWNER = @as(u32, 0); pub const DS_ROLE_DOMAIN_OWNER = @as(u32, 1); pub const DS_ROLE_PDC_OWNER = @as(u32, 2); pub const DS_ROLE_RID_OWNER = @as(u32, 3); pub const DS_ROLE_INFRASTRUCTURE_OWNER = @as(u32, 4); pub const DS_SCHEMA_GUID_NOT_FOUND = @as(u32, 0); pub const DS_SCHEMA_GUID_ATTR = @as(u32, 1); pub const DS_SCHEMA_GUID_ATTR_SET = @as(u32, 2); pub const DS_SCHEMA_GUID_CLASS = @as(u32, 3); pub const DS_SCHEMA_GUID_CONTROL_RIGHT = @as(u32, 4); pub const DS_KCC_FLAG_ASYNC_OP = @as(u32, 1); pub const DS_KCC_FLAG_DAMPED = @as(u32, 2); pub const DS_EXIST_ADVISORY_MODE = @as(u32, 1); pub const DS_REPL_INFO_FLAG_IMPROVE_LINKED_ATTRS = @as(u32, 1); pub const DS_REPL_NBR_WRITEABLE = @as(u32, 16); pub const DS_REPL_NBR_SYNC_ON_STARTUP = @as(u32, 32); pub const DS_REPL_NBR_DO_SCHEDULED_SYNCS = @as(u32, 64); pub const DS_REPL_NBR_USE_ASYNC_INTERSITE_TRANSPORT = @as(u32, 128); pub const DS_REPL_NBR_TWO_WAY_SYNC = @as(u32, 512); pub const DS_REPL_NBR_NONGC_RO_REPLICA = @as(u32, 1024); pub const DS_REPL_NBR_RETURN_OBJECT_PARENTS = @as(u32, 2048); pub const DS_REPL_NBR_SELECT_SECRETS = @as(u32, 4096); pub const DS_REPL_NBR_FULL_SYNC_IN_PROGRESS = @as(u32, 65536); pub const DS_REPL_NBR_FULL_SYNC_NEXT_PACKET = @as(u32, 131072); pub const DS_REPL_NBR_GCSPN = @as(u32, 1048576); pub const DS_REPL_NBR_NEVER_SYNCED = @as(u32, 2097152); pub const DS_REPL_NBR_PREEMPTED = @as(u32, 16777216); pub const DS_REPL_NBR_IGNORE_CHANGE_NOTIFICATIONS = @as(u32, 67108864); pub const DS_REPL_NBR_DISABLE_SCHEDULED_SYNC = @as(u32, 134217728); pub const DS_REPL_NBR_COMPRESS_CHANGES = @as(u32, 268435456); pub const DS_REPL_NBR_NO_CHANGE_NOTIFICATIONS = @as(u32, 536870912); pub const DS_REPL_NBR_PARTIAL_ATTRIBUTE_SET = @as(u32, 1073741824); pub const ADAM_REPL_AUTHENTICATION_MODE_NEGOTIATE_PASS_THROUGH = @as(u32, 0); pub const ADAM_REPL_AUTHENTICATION_MODE_NEGOTIATE = @as(u32, 1); pub const ADAM_REPL_AUTHENTICATION_MODE_MUTUAL_AUTH_REQUIRED = @as(u32, 2); pub const FLAG_FOREST_OPTIONAL_FEATURE = @as(u32, 1); pub const FLAG_DOMAIN_OPTIONAL_FEATURE = @as(u32, 2); pub const FLAG_DISABLABLE_OPTIONAL_FEATURE = @as(u32, 4); pub const FLAG_SERVER_OPTIONAL_FEATURE = @as(u32, 8); pub const DSOP_SCOPE_TYPE_TARGET_COMPUTER = @as(u32, 1); pub const DSOP_SCOPE_TYPE_UPLEVEL_JOINED_DOMAIN = @as(u32, 2); pub const DSOP_SCOPE_TYPE_DOWNLEVEL_JOINED_DOMAIN = @as(u32, 4); pub const DSOP_SCOPE_TYPE_ENTERPRISE_DOMAIN = @as(u32, 8); pub const DSOP_SCOPE_TYPE_GLOBAL_CATALOG = @as(u32, 16); pub const DSOP_SCOPE_TYPE_EXTERNAL_UPLEVEL_DOMAIN = @as(u32, 32); pub const DSOP_SCOPE_TYPE_EXTERNAL_DOWNLEVEL_DOMAIN = @as(u32, 64); pub const DSOP_SCOPE_TYPE_WORKGROUP = @as(u32, 128); pub const DSOP_SCOPE_TYPE_USER_ENTERED_UPLEVEL_SCOPE = @as(u32, 256); pub const DSOP_SCOPE_TYPE_USER_ENTERED_DOWNLEVEL_SCOPE = @as(u32, 512); pub const DSOP_SCOPE_FLAG_STARTING_SCOPE = @as(u32, 1); pub const DSOP_SCOPE_FLAG_WANT_PROVIDER_WINNT = @as(u32, 2); pub const DSOP_SCOPE_FLAG_WANT_PROVIDER_LDAP = @as(u32, 4); pub const DSOP_SCOPE_FLAG_WANT_PROVIDER_GC = @as(u32, 8); pub const DSOP_SCOPE_FLAG_WANT_SID_PATH = @as(u32, 16); pub const DSOP_SCOPE_FLAG_WANT_DOWNLEVEL_BUILTIN_PATH = @as(u32, 32); pub const DSOP_SCOPE_FLAG_DEFAULT_FILTER_USERS = @as(u32, 64); pub const DSOP_SCOPE_FLAG_DEFAULT_FILTER_GROUPS = @as(u32, 128); pub const DSOP_SCOPE_FLAG_DEFAULT_FILTER_COMPUTERS = @as(u32, 256); pub const DSOP_SCOPE_FLAG_DEFAULT_FILTER_CONTACTS = @as(u32, 512); pub const DSOP_SCOPE_FLAG_DEFAULT_FILTER_SERVICE_ACCOUNTS = @as(u32, 1024); pub const DSOP_SCOPE_FLAG_DEFAULT_FILTER_PASSWORDSETTINGS_OBJECTS = @as(u32, 2048); pub const DSOP_FILTER_INCLUDE_ADVANCED_VIEW = @as(u32, 1); pub const DSOP_FILTER_USERS = @as(u32, 2); pub const DSOP_FILTER_BUILTIN_GROUPS = @as(u32, 4); pub const DSOP_FILTER_WELL_KNOWN_PRINCIPALS = @as(u32, 8); pub const DSOP_FILTER_UNIVERSAL_GROUPS_DL = @as(u32, 16); pub const DSOP_FILTER_UNIVERSAL_GROUPS_SE = @as(u32, 32); pub const DSOP_FILTER_GLOBAL_GROUPS_DL = @as(u32, 64); pub const DSOP_FILTER_GLOBAL_GROUPS_SE = @as(u32, 128); pub const DSOP_FILTER_DOMAIN_LOCAL_GROUPS_DL = @as(u32, 256); pub const DSOP_FILTER_DOMAIN_LOCAL_GROUPS_SE = @as(u32, 512); pub const DSOP_FILTER_CONTACTS = @as(u32, 1024); pub const DSOP_FILTER_COMPUTERS = @as(u32, 2048); pub const DSOP_FILTER_SERVICE_ACCOUNTS = @as(u32, 4096); pub const DSOP_FILTER_PASSWORDSETTINGS_OBJECTS = @as(u32, 8192); pub const DSOP_DOWNLEVEL_FILTER_USERS = @as(u32, 2147483649); pub const DSOP_DOWNLEVEL_FILTER_LOCAL_GROUPS = @as(u32, 2147483650); pub const DSOP_DOWNLEVEL_FILTER_GLOBAL_GROUPS = @as(u32, 2147483652); pub const DSOP_DOWNLEVEL_FILTER_COMPUTERS = @as(u32, 2147483656); pub const DSOP_DOWNLEVEL_FILTER_WORLD = @as(u32, 2147483664); pub const DSOP_DOWNLEVEL_FILTER_AUTHENTICATED_USER = @as(u32, 2147483680); pub const DSOP_DOWNLEVEL_FILTER_ANONYMOUS = @as(u32, 2147483712); pub const DSOP_DOWNLEVEL_FILTER_BATCH = @as(u32, 2147483776); pub const DSOP_DOWNLEVEL_FILTER_CREATOR_OWNER = @as(u32, 2147483904); pub const DSOP_DOWNLEVEL_FILTER_CREATOR_GROUP = @as(u32, 2147484160); pub const DSOP_DOWNLEVEL_FILTER_DIALUP = @as(u32, 2147484672); pub const DSOP_DOWNLEVEL_FILTER_INTERACTIVE = @as(u32, 2147485696); pub const DSOP_DOWNLEVEL_FILTER_NETWORK = @as(u32, 2147487744); pub const DSOP_DOWNLEVEL_FILTER_SERVICE = @as(u32, 2147491840); pub const DSOP_DOWNLEVEL_FILTER_SYSTEM = @as(u32, 2147500032); pub const DSOP_DOWNLEVEL_FILTER_EXCLUDE_BUILTIN_GROUPS = @as(u32, 2147516416); pub const DSOP_DOWNLEVEL_FILTER_TERMINAL_SERVER = @as(u32, 2147549184); pub const DSOP_DOWNLEVEL_FILTER_ALL_WELLKNOWN_SIDS = @as(u32, 2147614720); pub const DSOP_DOWNLEVEL_FILTER_LOCAL_SERVICE = @as(u32, 2147745792); pub const DSOP_DOWNLEVEL_FILTER_NETWORK_SERVICE = @as(u32, 2148007936); pub const DSOP_DOWNLEVEL_FILTER_REMOTE_LOGON = @as(u32, 2148532224); pub const DSOP_DOWNLEVEL_FILTER_INTERNET_USER = @as(u32, 2149580800); pub const DSOP_DOWNLEVEL_FILTER_OWNER_RIGHTS = @as(u32, 2151677952); pub const DSOP_DOWNLEVEL_FILTER_SERVICES = @as(u32, 2155872256); pub const DSOP_DOWNLEVEL_FILTER_LOCAL_LOGON = @as(u32, 2164260864); pub const DSOP_DOWNLEVEL_FILTER_THIS_ORG_CERT = @as(u32, 2181038080); pub const DSOP_DOWNLEVEL_FILTER_IIS_APP_POOL = @as(u32, 2214592512); pub const DSOP_DOWNLEVEL_FILTER_ALL_APP_PACKAGES = @as(u32, 2281701376); pub const DSOP_DOWNLEVEL_FILTER_LOCAL_ACCOUNTS = @as(u32, 2415919104); pub const DSOP_FLAG_MULTISELECT = @as(u32, 1); pub const DSOP_FLAG_SKIP_TARGET_COMPUTER_DC_CHECK = @as(u32, 2); pub const SCHEDULE_INTERVAL = @as(u32, 0); pub const SCHEDULE_BANDWIDTH = @as(u32, 1); pub const SCHEDULE_PRIORITY = @as(u32, 2); pub const FACILITY_NTDSB = @as(u32, 2048); pub const FACILITY_BACKUP = @as(u32, 2047); pub const FACILITY_SYSTEM = @as(u32, 0); pub const STATUS_SEVERITY_SUCCESS = @as(u32, 0); pub const STATUS_SEVERITY_INFORMATIONAL = @as(u32, 1); pub const STATUS_SEVERITY_WARNING = @as(u32, 2); pub const STATUS_SEVERITY_ERROR = @as(u32, 3); pub const CLSID_DsObjectPicker = Guid.initString("17d6ccd8-3b7b-11d2-b9e0-00c04fd8dbf7"); //-------------------------------------------------------------------------------- // Section: Types (264) //-------------------------------------------------------------------------------- pub const CQFORM = extern struct { cbStruct: u32, dwFlags: u32, clsid: Guid, hIcon: ?HICON, pszTitle: ?[*:0]const u16, }; pub const LPCQADDFORMSPROC = fn( lParam: LPARAM, pForm: ?*CQFORM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPCQADDPAGESPROC = fn( lParam: LPARAM, clsidForm: ?*const Guid, pPage: ?*CQPAGE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const LPCQPAGEPROC = fn( pPage: ?*CQPAGE, hwnd: ?HWND, uMsg: u32, wParam: WPARAM, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const CQPAGE = extern struct { cbStruct: u32, dwFlags: u32, pPageProc: ?LPCQPAGEPROC, hInstance: ?HINSTANCE, idPageName: i32, idPageTemplate: i32, pDlgProc: ?DLGPROC, lParam: LPARAM, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IQueryForm_Value = @import("../zig.zig").Guid.initString("8cfcee30-39bd-11d0-b8d1-00a024ab2dbb"); pub const IID_IQueryForm = &IID_IQueryForm_Value; pub const IQueryForm = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IQueryForm, hkForm: ?HKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddForms: fn( self: *const IQueryForm, pAddFormsProc: ?LPCQADDFORMSPROC, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPages: fn( self: *const IQueryForm, pAddPagesProc: ?LPCQADDPAGESPROC, lParam: LPARAM, ) 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 IQueryForm_Initialize(self: *const T, hkForm: ?HKEY) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryForm.VTable, self.vtable).Initialize(@ptrCast(*const IQueryForm, self), hkForm); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IQueryForm_AddForms(self: *const T, pAddFormsProc: ?LPCQADDFORMSPROC, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryForm.VTable, self.vtable).AddForms(@ptrCast(*const IQueryForm, self), pAddFormsProc, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IQueryForm_AddPages(self: *const T, pAddPagesProc: ?LPCQADDPAGESPROC, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IQueryForm.VTable, self.vtable).AddPages(@ptrCast(*const IQueryForm, self), pAddPagesProc, lParam); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPersistQuery_Value = @import("../zig.zig").Guid.initString("1a3114b8-a62e-11d0-a6c5-00a0c906af45"); pub const IID_IPersistQuery = &IID_IPersistQuery_Value; pub const IPersistQuery = extern struct { pub const VTable = extern struct { base: IPersist.VTable, WriteString: fn( self: *const IPersistQuery, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReadString: fn( self: *const IPersistQuery, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pBuffer: ?PWSTR, cchBuffer: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteInt: fn( self: *const IPersistQuery, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, value: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReadInt: fn( self: *const IPersistQuery, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteStruct: fn( self: *const IPersistQuery, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pStruct: ?*anyopaque, cbStruct: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReadStruct: fn( self: *const IPersistQuery, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pStruct: ?*anyopaque, cbStruct: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clear: fn( self: *const IPersistQuery, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPersist.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_WriteString(self: *const T, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pValue: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).WriteString(@ptrCast(*const IPersistQuery, self), pSection, pValueName, pValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_ReadString(self: *const T, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pBuffer: ?PWSTR, cchBuffer: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).ReadString(@ptrCast(*const IPersistQuery, self), pSection, pValueName, pBuffer, cchBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_WriteInt(self: *const T, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, value: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).WriteInt(@ptrCast(*const IPersistQuery, self), pSection, pValueName, value); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_ReadInt(self: *const T, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).ReadInt(@ptrCast(*const IPersistQuery, self), pSection, pValueName, pValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_WriteStruct(self: *const T, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pStruct: ?*anyopaque, cbStruct: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).WriteStruct(@ptrCast(*const IPersistQuery, self), pSection, pValueName, pStruct, cbStruct); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_ReadStruct(self: *const T, pSection: ?[*:0]const u16, pValueName: ?[*:0]const u16, pStruct: ?*anyopaque, cbStruct: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).ReadStruct(@ptrCast(*const IPersistQuery, self), pSection, pValueName, pStruct, cbStruct); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPersistQuery_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPersistQuery.VTable, self.vtable).Clear(@ptrCast(*const IPersistQuery, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const OPENQUERYWINDOW = extern struct { cbStruct: u32, dwFlags: u32, clsidHandler: Guid, pHandlerParameters: ?*anyopaque, clsidDefaultForm: Guid, pPersistQuery: ?*IPersistQuery, Anonymous: extern union { pFormParameters: ?*anyopaque, ppbFormParameters: ?*IPropertyBag, }, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_ICommonQuery_Value = @import("../zig.zig").Guid.initString("ab50dec0-6f1d-11d0-a1c4-00aa00c16e65"); pub const IID_ICommonQuery = &IID_ICommonQuery_Value; pub const ICommonQuery = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OpenQueryWindow: fn( self: *const ICommonQuery, hwndParent: ?HWND, pQueryWnd: ?*OPENQUERYWINDOW, ppDataObject: ?*?*IDataObject, ) 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 ICommonQuery_OpenQueryWindow(self: *const T, hwndParent: ?HWND, pQueryWnd: ?*OPENQUERYWINDOW, ppDataObject: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const ICommonQuery.VTable, self.vtable).OpenQueryWindow(@ptrCast(*const ICommonQuery, self), hwndParent, pQueryWnd, ppDataObject); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_PropertyEntry_Value = @import("../zig.zig").Guid.initString("72d3edc2-a4c4-11d0-8533-00c04fd8d503"); pub const CLSID_PropertyEntry = &CLSID_PropertyEntry_Value; const CLSID_PropertyValue_Value = @import("../zig.zig").Guid.initString("7b9e38b0-a97c-11d0-8534-00c04fd8d503"); pub const CLSID_PropertyValue = &CLSID_PropertyValue_Value; const CLSID_AccessControlEntry_Value = @import("../zig.zig").Guid.initString("b75ac000-9bdd-11d0-852c-00c04fd8d503"); pub const CLSID_AccessControlEntry = &CLSID_AccessControlEntry_Value; const CLSID_AccessControlList_Value = @import("../zig.zig").Guid.initString("b85ea052-9bdd-11d0-852c-00c04fd8d503"); pub const CLSID_AccessControlList = &CLSID_AccessControlList_Value; const CLSID_SecurityDescriptor_Value = @import("../zig.zig").Guid.initString("b958f73c-9bdd-11d0-852c-00c04fd8d503"); pub const CLSID_SecurityDescriptor = &CLSID_SecurityDescriptor_Value; const CLSID_LargeInteger_Value = @import("../zig.zig").Guid.initString("927971f5-0939-11d1-8be1-00c04fd8d503"); pub const CLSID_LargeInteger = &CLSID_LargeInteger_Value; const CLSID_NameTranslate_Value = @import("../zig.zig").Guid.initString("274fae1f-3626-11d1-a3a4-00c04fb950dc"); pub const CLSID_NameTranslate = &CLSID_NameTranslate_Value; const CLSID_CaseIgnoreList_Value = @import("../zig.zig").Guid.initString("15f88a55-4680-11d1-a3b4-00c04fb950dc"); pub const CLSID_CaseIgnoreList = &CLSID_CaseIgnoreList_Value; const CLSID_FaxNumber_Value = @import("../zig.zig").Guid.initString("a5062215-4681-11d1-a3b4-00c04fb950dc"); pub const CLSID_FaxNumber = &CLSID_FaxNumber_Value; const CLSID_NetAddress_Value = @import("../zig.zig").Guid.initString("b0b71247-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_NetAddress = &CLSID_NetAddress_Value; const CLSID_OctetList_Value = @import("../zig.zig").Guid.initString("1241400f-4680-11d1-a3b4-00c04fb950dc"); pub const CLSID_OctetList = &CLSID_OctetList_Value; const CLSID_Email_Value = @import("../zig.zig").Guid.initString("8f92a857-478e-11d1-a3b4-00c04fb950dc"); pub const CLSID_Email = &CLSID_Email_Value; const CLSID_Path_Value = @import("../zig.zig").Guid.initString("b2538919-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_Path = &CLSID_Path_Value; const CLSID_ReplicaPointer_Value = @import("../zig.zig").Guid.initString("f5d1badf-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_ReplicaPointer = &CLSID_ReplicaPointer_Value; const CLSID_Timestamp_Value = @import("../zig.zig").Guid.initString("b2bed2eb-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_Timestamp = &CLSID_Timestamp_Value; const CLSID_PostalAddress_Value = @import("../zig.zig").Guid.initString("0a75afcd-4680-11d1-a3b4-00c04fb950dc"); pub const CLSID_PostalAddress = &CLSID_PostalAddress_Value; const CLSID_BackLink_Value = @import("../zig.zig").Guid.initString("fcbf906f-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_BackLink = &CLSID_BackLink_Value; const CLSID_TypedName_Value = @import("../zig.zig").Guid.initString("b33143cb-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_TypedName = &CLSID_TypedName_Value; const CLSID_Hold_Value = @import("../zig.zig").Guid.initString("b3ad3e13-4080-11d1-a3ac-00c04fb950dc"); pub const CLSID_Hold = &CLSID_Hold_Value; const CLSID_Pathname_Value = @import("../zig.zig").Guid.initString("080d0d78-f421-11d0-a36e-00c04fb950dc"); pub const CLSID_Pathname = &CLSID_Pathname_Value; const CLSID_ADSystemInfo_Value = @import("../zig.zig").Guid.initString("50b6327f-afd1-11d2-9cb9-0000f87a369e"); pub const CLSID_ADSystemInfo = &CLSID_ADSystemInfo_Value; const CLSID_WinNTSystemInfo_Value = @import("../zig.zig").Guid.initString("66182ec4-afd1-11d2-9cb9-0000f87a369e"); pub const CLSID_WinNTSystemInfo = &CLSID_WinNTSystemInfo_Value; const CLSID_DNWithBinary_Value = @import("../zig.zig").Guid.initString("7e99c0a3-f935-11d2-ba96-00c04fb6d0d1"); pub const CLSID_DNWithBinary = &CLSID_DNWithBinary_Value; const CLSID_DNWithString_Value = @import("../zig.zig").Guid.initString("334857cc-f934-11d2-ba96-00c04fb6d0d1"); pub const CLSID_DNWithString = &CLSID_DNWithString_Value; const CLSID_ADsSecurityUtility_Value = @import("../zig.zig").Guid.initString("f270c64a-ffb8-4ae4-85fe-3a75e5347966"); pub const CLSID_ADsSecurityUtility = &CLSID_ADsSecurityUtility_Value; pub const ADSTYPEENUM = enum(i32) { INVALID = 0, DN_STRING = 1, CASE_EXACT_STRING = 2, CASE_IGNORE_STRING = 3, PRINTABLE_STRING = 4, NUMERIC_STRING = 5, BOOLEAN = 6, INTEGER = 7, OCTET_STRING = 8, UTC_TIME = 9, LARGE_INTEGER = 10, PROV_SPECIFIC = 11, OBJECT_CLASS = 12, CASEIGNORE_LIST = 13, OCTET_LIST = 14, PATH = 15, POSTALADDRESS = 16, TIMESTAMP = 17, BACKLINK = 18, TYPEDNAME = 19, HOLD = 20, NETADDRESS = 21, REPLICAPOINTER = 22, FAXNUMBER = 23, EMAIL = 24, NT_SECURITY_DESCRIPTOR = 25, UNKNOWN = 26, DN_WITH_BINARY = 27, DN_WITH_STRING = 28, }; pub const ADSTYPE_INVALID = ADSTYPEENUM.INVALID; pub const ADSTYPE_DN_STRING = ADSTYPEENUM.DN_STRING; pub const ADSTYPE_CASE_EXACT_STRING = ADSTYPEENUM.CASE_EXACT_STRING; pub const ADSTYPE_CASE_IGNORE_STRING = ADSTYPEENUM.CASE_IGNORE_STRING; pub const ADSTYPE_PRINTABLE_STRING = ADSTYPEENUM.PRINTABLE_STRING; pub const ADSTYPE_NUMERIC_STRING = ADSTYPEENUM.NUMERIC_STRING; pub const ADSTYPE_BOOLEAN = ADSTYPEENUM.BOOLEAN; pub const ADSTYPE_INTEGER = ADSTYPEENUM.INTEGER; pub const ADSTYPE_OCTET_STRING = ADSTYPEENUM.OCTET_STRING; pub const ADSTYPE_UTC_TIME = ADSTYPEENUM.UTC_TIME; pub const ADSTYPE_LARGE_INTEGER = ADSTYPEENUM.LARGE_INTEGER; pub const ADSTYPE_PROV_SPECIFIC = ADSTYPEENUM.PROV_SPECIFIC; pub const ADSTYPE_OBJECT_CLASS = ADSTYPEENUM.OBJECT_CLASS; pub const ADSTYPE_CASEIGNORE_LIST = ADSTYPEENUM.CASEIGNORE_LIST; pub const ADSTYPE_OCTET_LIST = ADSTYPEENUM.OCTET_LIST; pub const ADSTYPE_PATH = ADSTYPEENUM.PATH; pub const ADSTYPE_POSTALADDRESS = ADSTYPEENUM.POSTALADDRESS; pub const ADSTYPE_TIMESTAMP = ADSTYPEENUM.TIMESTAMP; pub const ADSTYPE_BACKLINK = ADSTYPEENUM.BACKLINK; pub const ADSTYPE_TYPEDNAME = ADSTYPEENUM.TYPEDNAME; pub const ADSTYPE_HOLD = ADSTYPEENUM.HOLD; pub const ADSTYPE_NETADDRESS = ADSTYPEENUM.NETADDRESS; pub const ADSTYPE_REPLICAPOINTER = ADSTYPEENUM.REPLICAPOINTER; pub const ADSTYPE_FAXNUMBER = ADSTYPEENUM.FAXNUMBER; pub const ADSTYPE_EMAIL = ADSTYPEENUM.EMAIL; pub const ADSTYPE_NT_SECURITY_DESCRIPTOR = ADSTYPEENUM.NT_SECURITY_DESCRIPTOR; pub const ADSTYPE_UNKNOWN = ADSTYPEENUM.UNKNOWN; pub const ADSTYPE_DN_WITH_BINARY = ADSTYPEENUM.DN_WITH_BINARY; pub const ADSTYPE_DN_WITH_STRING = ADSTYPEENUM.DN_WITH_STRING; pub const ADS_OCTET_STRING = extern struct { dwLength: u32, lpValue: ?*u8, }; pub const ADS_NT_SECURITY_DESCRIPTOR = extern struct { dwLength: u32, lpValue: ?*u8, }; pub const ADS_PROV_SPECIFIC = extern struct { dwLength: u32, lpValue: ?*u8, }; pub const ADS_CASEIGNORE_LIST = extern struct { Next: ?*ADS_CASEIGNORE_LIST, String: ?PWSTR, }; pub const ADS_OCTET_LIST = extern struct { Next: ?*ADS_OCTET_LIST, Length: u32, Data: ?*u8, }; pub const ADS_PATH = extern struct { Type: u32, VolumeName: ?PWSTR, Path: ?PWSTR, }; pub const ADS_POSTALADDRESS = extern struct { PostalAddress: [6]?PWSTR, }; pub const ADS_TIMESTAMP = extern struct { WholeSeconds: u32, EventID: u32, }; pub const ADS_BACKLINK = extern struct { RemoteID: u32, ObjectName: ?PWSTR, }; pub const ADS_TYPEDNAME = extern struct { ObjectName: ?PWSTR, Level: u32, Interval: u32, }; pub const ADS_HOLD = extern struct { ObjectName: ?PWSTR, Amount: u32, }; pub const ADS_NETADDRESS = extern struct { AddressType: u32, AddressLength: u32, Address: ?*u8, }; pub const ADS_REPLICAPOINTER = extern struct { ServerName: ?PWSTR, ReplicaType: u32, ReplicaNumber: u32, Count: u32, ReplicaAddressHints: ?*ADS_NETADDRESS, }; pub const ADS_FAXNUMBER = extern struct { TelephoneNumber: ?PWSTR, NumberOfBits: u32, Parameters: ?*u8, }; pub const ADS_EMAIL = extern struct { Address: ?PWSTR, Type: u32, }; pub const ADS_DN_WITH_BINARY = extern struct { dwLength: u32, lpBinaryValue: ?*u8, pszDNString: ?PWSTR, }; pub const ADS_DN_WITH_STRING = extern struct { pszStringValue: ?PWSTR, pszDNString: ?PWSTR, }; pub const ADSVALUE = extern struct { dwType: ADSTYPEENUM, Anonymous: extern union { DNString: ?*u16, CaseExactString: ?*u16, CaseIgnoreString: ?*u16, PrintableString: ?*u16, NumericString: ?*u16, Boolean: u32, Integer: u32, OctetString: ADS_OCTET_STRING, UTCTime: SYSTEMTIME, LargeInteger: LARGE_INTEGER, ClassName: ?*u16, ProviderSpecific: ADS_PROV_SPECIFIC, pCaseIgnoreList: ?*ADS_CASEIGNORE_LIST, pOctetList: ?*ADS_OCTET_LIST, pPath: ?*ADS_PATH, pPostalAddress: ?*ADS_POSTALADDRESS, Timestamp: ADS_TIMESTAMP, BackLink: ADS_BACKLINK, pTypedName: ?*ADS_TYPEDNAME, Hold: ADS_HOLD, pNetAddress: ?*ADS_NETADDRESS, pReplicaPointer: ?*ADS_REPLICAPOINTER, pFaxNumber: ?*ADS_FAXNUMBER, Email: ADS_EMAIL, SecurityDescriptor: ADS_NT_SECURITY_DESCRIPTOR, pDNWithBinary: ?*ADS_DN_WITH_BINARY, pDNWithString: ?*ADS_DN_WITH_STRING, }, }; pub const ADS_ATTR_INFO = extern struct { pszAttrName: ?PWSTR, dwControlCode: u32, dwADsType: ADSTYPEENUM, pADsValues: ?*ADSVALUE, dwNumValues: u32, }; pub const ADS_AUTHENTICATION_ENUM = enum(u32) { SECURE_AUTHENTICATION = 1, USE_ENCRYPTION = 2, // USE_SSL = 2, this enum value conflicts with USE_ENCRYPTION READONLY_SERVER = 4, PROMPT_CREDENTIALS = 8, NO_AUTHENTICATION = 16, FAST_BIND = 32, USE_SIGNING = 64, USE_SEALING = 128, USE_DELEGATION = 256, SERVER_BIND = 512, NO_REFERRAL_CHASING = 1024, AUTH_RESERVED = 2147483648, }; pub const ADS_SECURE_AUTHENTICATION = ADS_AUTHENTICATION_ENUM.SECURE_AUTHENTICATION; pub const ADS_USE_ENCRYPTION = ADS_AUTHENTICATION_ENUM.USE_ENCRYPTION; pub const ADS_USE_SSL = ADS_AUTHENTICATION_ENUM.USE_ENCRYPTION; pub const ADS_READONLY_SERVER = ADS_AUTHENTICATION_ENUM.READONLY_SERVER; pub const ADS_PROMPT_CREDENTIALS = ADS_AUTHENTICATION_ENUM.PROMPT_CREDENTIALS; pub const ADS_NO_AUTHENTICATION = ADS_AUTHENTICATION_ENUM.NO_AUTHENTICATION; pub const ADS_FAST_BIND = ADS_AUTHENTICATION_ENUM.FAST_BIND; pub const ADS_USE_SIGNING = ADS_AUTHENTICATION_ENUM.USE_SIGNING; pub const ADS_USE_SEALING = ADS_AUTHENTICATION_ENUM.USE_SEALING; pub const ADS_USE_DELEGATION = ADS_AUTHENTICATION_ENUM.USE_DELEGATION; pub const ADS_SERVER_BIND = ADS_AUTHENTICATION_ENUM.SERVER_BIND; pub const ADS_NO_REFERRAL_CHASING = ADS_AUTHENTICATION_ENUM.NO_REFERRAL_CHASING; pub const ADS_AUTH_RESERVED = ADS_AUTHENTICATION_ENUM.AUTH_RESERVED; pub const ADS_OBJECT_INFO = extern struct { pszRDN: ?PWSTR, pszObjectDN: ?PWSTR, pszParentDN: ?PWSTR, pszSchemaDN: ?PWSTR, pszClassName: ?PWSTR, }; pub const ADS_STATUSENUM = enum(i32) { S_OK = 0, INVALID_SEARCHPREF = 1, INVALID_SEARCHPREFVALUE = 2, }; pub const ADS_STATUS_S_OK = ADS_STATUSENUM.S_OK; pub const ADS_STATUS_INVALID_SEARCHPREF = ADS_STATUSENUM.INVALID_SEARCHPREF; pub const ADS_STATUS_INVALID_SEARCHPREFVALUE = ADS_STATUSENUM.INVALID_SEARCHPREFVALUE; pub const ADS_DEREFENUM = enum(i32) { NEVER = 0, SEARCHING = 1, FINDING = 2, ALWAYS = 3, }; pub const ADS_DEREF_NEVER = ADS_DEREFENUM.NEVER; pub const ADS_DEREF_SEARCHING = ADS_DEREFENUM.SEARCHING; pub const ADS_DEREF_FINDING = ADS_DEREFENUM.FINDING; pub const ADS_DEREF_ALWAYS = ADS_DEREFENUM.ALWAYS; pub const ADS_SCOPEENUM = enum(i32) { BASE = 0, ONELEVEL = 1, SUBTREE = 2, }; pub const ADS_SCOPE_BASE = ADS_SCOPEENUM.BASE; pub const ADS_SCOPE_ONELEVEL = ADS_SCOPEENUM.ONELEVEL; pub const ADS_SCOPE_SUBTREE = ADS_SCOPEENUM.SUBTREE; pub const ADS_PREFERENCES_ENUM = enum(i32) { ASYNCHRONOUS = 0, DEREF_ALIASES = 1, SIZE_LIMIT = 2, TIME_LIMIT = 3, ATTRIBTYPES_ONLY = 4, SEARCH_SCOPE = 5, TIMEOUT = 6, PAGESIZE = 7, PAGED_TIME_LIMIT = 8, CHASE_REFERRALS = 9, SORT_ON = 10, CACHE_RESULTS = 11, ADSIFLAG = 12, }; pub const ADSIPROP_ASYNCHRONOUS = ADS_PREFERENCES_ENUM.ASYNCHRONOUS; pub const ADSIPROP_DEREF_ALIASES = ADS_PREFERENCES_ENUM.DEREF_ALIASES; pub const ADSIPROP_SIZE_LIMIT = ADS_PREFERENCES_ENUM.SIZE_LIMIT; pub const ADSIPROP_TIME_LIMIT = ADS_PREFERENCES_ENUM.TIME_LIMIT; pub const ADSIPROP_ATTRIBTYPES_ONLY = ADS_PREFERENCES_ENUM.ATTRIBTYPES_ONLY; pub const ADSIPROP_SEARCH_SCOPE = ADS_PREFERENCES_ENUM.SEARCH_SCOPE; pub const ADSIPROP_TIMEOUT = ADS_PREFERENCES_ENUM.TIMEOUT; pub const ADSIPROP_PAGESIZE = ADS_PREFERENCES_ENUM.PAGESIZE; pub const ADSIPROP_PAGED_TIME_LIMIT = ADS_PREFERENCES_ENUM.PAGED_TIME_LIMIT; pub const ADSIPROP_CHASE_REFERRALS = ADS_PREFERENCES_ENUM.CHASE_REFERRALS; pub const ADSIPROP_SORT_ON = ADS_PREFERENCES_ENUM.SORT_ON; pub const ADSIPROP_CACHE_RESULTS = ADS_PREFERENCES_ENUM.CACHE_RESULTS; pub const ADSIPROP_ADSIFLAG = ADS_PREFERENCES_ENUM.ADSIFLAG; pub const ADSI_DIALECT_ENUM = enum(i32) { LDAP = 0, SQL = 1, }; pub const ADSI_DIALECT_LDAP = ADSI_DIALECT_ENUM.LDAP; pub const ADSI_DIALECT_SQL = ADSI_DIALECT_ENUM.SQL; pub const ADS_CHASE_REFERRALS_ENUM = enum(i32) { NEVER = 0, SUBORDINATE = 32, EXTERNAL = 64, ALWAYS = 96, }; pub const ADS_CHASE_REFERRALS_NEVER = ADS_CHASE_REFERRALS_ENUM.NEVER; pub const ADS_CHASE_REFERRALS_SUBORDINATE = ADS_CHASE_REFERRALS_ENUM.SUBORDINATE; pub const ADS_CHASE_REFERRALS_EXTERNAL = ADS_CHASE_REFERRALS_ENUM.EXTERNAL; pub const ADS_CHASE_REFERRALS_ALWAYS = ADS_CHASE_REFERRALS_ENUM.ALWAYS; pub const ADS_SEARCHPREF_ENUM = enum(i32) { ASYNCHRONOUS = 0, DEREF_ALIASES = 1, SIZE_LIMIT = 2, TIME_LIMIT = 3, ATTRIBTYPES_ONLY = 4, SEARCH_SCOPE = 5, TIMEOUT = 6, PAGESIZE = 7, PAGED_TIME_LIMIT = 8, CHASE_REFERRALS = 9, SORT_ON = 10, CACHE_RESULTS = 11, DIRSYNC = 12, TOMBSTONE = 13, VLV = 14, ATTRIBUTE_QUERY = 15, SECURITY_MASK = 16, DIRSYNC_FLAG = 17, EXTENDED_DN = 18, }; pub const ADS_SEARCHPREF_ASYNCHRONOUS = ADS_SEARCHPREF_ENUM.ASYNCHRONOUS; pub const ADS_SEARCHPREF_DEREF_ALIASES = ADS_SEARCHPREF_ENUM.DEREF_ALIASES; pub const ADS_SEARCHPREF_SIZE_LIMIT = ADS_SEARCHPREF_ENUM.SIZE_LIMIT; pub const ADS_SEARCHPREF_TIME_LIMIT = ADS_SEARCHPREF_ENUM.TIME_LIMIT; pub const ADS_SEARCHPREF_ATTRIBTYPES_ONLY = ADS_SEARCHPREF_ENUM.ATTRIBTYPES_ONLY; pub const ADS_SEARCHPREF_SEARCH_SCOPE = ADS_SEARCHPREF_ENUM.SEARCH_SCOPE; pub const ADS_SEARCHPREF_TIMEOUT = ADS_SEARCHPREF_ENUM.TIMEOUT; pub const ADS_SEARCHPREF_PAGESIZE = ADS_SEARCHPREF_ENUM.PAGESIZE; pub const ADS_SEARCHPREF_PAGED_TIME_LIMIT = ADS_SEARCHPREF_ENUM.PAGED_TIME_LIMIT; pub const ADS_SEARCHPREF_CHASE_REFERRALS = ADS_SEARCHPREF_ENUM.CHASE_REFERRALS; pub const ADS_SEARCHPREF_SORT_ON = ADS_SEARCHPREF_ENUM.SORT_ON; pub const ADS_SEARCHPREF_CACHE_RESULTS = ADS_SEARCHPREF_ENUM.CACHE_RESULTS; pub const ADS_SEARCHPREF_DIRSYNC = ADS_SEARCHPREF_ENUM.DIRSYNC; pub const ADS_SEARCHPREF_TOMBSTONE = ADS_SEARCHPREF_ENUM.TOMBSTONE; pub const ADS_SEARCHPREF_VLV = ADS_SEARCHPREF_ENUM.VLV; pub const ADS_SEARCHPREF_ATTRIBUTE_QUERY = ADS_SEARCHPREF_ENUM.ATTRIBUTE_QUERY; pub const ADS_SEARCHPREF_SECURITY_MASK = ADS_SEARCHPREF_ENUM.SECURITY_MASK; pub const ADS_SEARCHPREF_DIRSYNC_FLAG = ADS_SEARCHPREF_ENUM.DIRSYNC_FLAG; pub const ADS_SEARCHPREF_EXTENDED_DN = ADS_SEARCHPREF_ENUM.EXTENDED_DN; pub const ADS_PASSWORD_ENCODING_ENUM = enum(i32) { REQUIRE_SSL = 0, CLEAR = 1, }; pub const ADS_PASSWORD_ENCODE_REQUIRE_SSL = ADS_PASSWORD_ENCODING_ENUM.REQUIRE_SSL; pub const ADS_PASSWORD_ENCODE_CLEAR = ADS_PASSWORD_ENCODING_ENUM.CLEAR; pub const ads_searchpref_info = extern struct { dwSearchPref: ADS_SEARCHPREF_ENUM, vValue: ADSVALUE, dwStatus: ADS_STATUSENUM, }; pub const ads_search_column = extern struct { pszAttrName: ?PWSTR, dwADsType: ADSTYPEENUM, pADsValues: ?*ADSVALUE, dwNumValues: u32, hReserved: ?HANDLE, }; pub const ADS_ATTR_DEF = extern struct { pszAttrName: ?PWSTR, dwADsType: ADSTYPEENUM, dwMinRange: u32, dwMaxRange: u32, fMultiValued: BOOL, }; pub const ADS_CLASS_DEF = extern struct { pszClassName: ?PWSTR, dwMandatoryAttrs: u32, ppszMandatoryAttrs: ?*?PWSTR, optionalAttrs: u32, ppszOptionalAttrs: ?*?*?PWSTR, dwNamingAttrs: u32, ppszNamingAttrs: ?*?*?PWSTR, dwSuperClasses: u32, ppszSuperClasses: ?*?*?PWSTR, fIsContainer: BOOL, }; pub const ADS_SORTKEY = extern struct { pszAttrType: ?PWSTR, pszReserved: ?PWSTR, fReverseorder: BOOLEAN, }; pub const ADS_VLV = extern struct { dwBeforeCount: u32, dwAfterCount: u32, dwOffset: u32, dwContentCount: u32, pszTarget: ?PWSTR, dwContextIDLength: u32, lpContextID: ?*u8, }; pub const ADS_PROPERTY_OPERATION_ENUM = enum(i32) { CLEAR = 1, UPDATE = 2, APPEND = 3, DELETE = 4, }; pub const ADS_PROPERTY_CLEAR = ADS_PROPERTY_OPERATION_ENUM.CLEAR; pub const ADS_PROPERTY_UPDATE = ADS_PROPERTY_OPERATION_ENUM.UPDATE; pub const ADS_PROPERTY_APPEND = ADS_PROPERTY_OPERATION_ENUM.APPEND; pub const ADS_PROPERTY_DELETE = ADS_PROPERTY_OPERATION_ENUM.DELETE; pub const ADS_SYSTEMFLAG_ENUM = enum(i32) { DISALLOW_DELETE = -2147483648, CONFIG_ALLOW_RENAME = 1073741824, CONFIG_ALLOW_MOVE = 536870912, CONFIG_ALLOW_LIMITED_MOVE = 268435456, DOMAIN_DISALLOW_RENAME = 134217728, DOMAIN_DISALLOW_MOVE = 67108864, CR_NTDS_NC = 1, CR_NTDS_DOMAIN = 2, // ATTR_NOT_REPLICATED = 1, this enum value conflicts with CR_NTDS_NC ATTR_IS_CONSTRUCTED = 4, }; pub const ADS_SYSTEMFLAG_DISALLOW_DELETE = ADS_SYSTEMFLAG_ENUM.DISALLOW_DELETE; pub const ADS_SYSTEMFLAG_CONFIG_ALLOW_RENAME = ADS_SYSTEMFLAG_ENUM.CONFIG_ALLOW_RENAME; pub const ADS_SYSTEMFLAG_CONFIG_ALLOW_MOVE = ADS_SYSTEMFLAG_ENUM.CONFIG_ALLOW_MOVE; pub const ADS_SYSTEMFLAG_CONFIG_ALLOW_LIMITED_MOVE = ADS_SYSTEMFLAG_ENUM.CONFIG_ALLOW_LIMITED_MOVE; pub const ADS_SYSTEMFLAG_DOMAIN_DISALLOW_RENAME = ADS_SYSTEMFLAG_ENUM.DOMAIN_DISALLOW_RENAME; pub const ADS_SYSTEMFLAG_DOMAIN_DISALLOW_MOVE = ADS_SYSTEMFLAG_ENUM.DOMAIN_DISALLOW_MOVE; pub const ADS_SYSTEMFLAG_CR_NTDS_NC = ADS_SYSTEMFLAG_ENUM.CR_NTDS_NC; pub const ADS_SYSTEMFLAG_CR_NTDS_DOMAIN = ADS_SYSTEMFLAG_ENUM.CR_NTDS_DOMAIN; pub const ADS_SYSTEMFLAG_ATTR_NOT_REPLICATED = ADS_SYSTEMFLAG_ENUM.CR_NTDS_NC; pub const ADS_SYSTEMFLAG_ATTR_IS_CONSTRUCTED = ADS_SYSTEMFLAG_ENUM.ATTR_IS_CONSTRUCTED; pub const ADS_GROUP_TYPE_ENUM = enum(i32) { GLOBAL_GROUP = 2, DOMAIN_LOCAL_GROUP = 4, // LOCAL_GROUP = 4, this enum value conflicts with DOMAIN_LOCAL_GROUP UNIVERSAL_GROUP = 8, SECURITY_ENABLED = -2147483648, }; pub const ADS_GROUP_TYPE_GLOBAL_GROUP = ADS_GROUP_TYPE_ENUM.GLOBAL_GROUP; pub const ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = ADS_GROUP_TYPE_ENUM.DOMAIN_LOCAL_GROUP; pub const ADS_GROUP_TYPE_LOCAL_GROUP = ADS_GROUP_TYPE_ENUM.DOMAIN_LOCAL_GROUP; pub const ADS_GROUP_TYPE_UNIVERSAL_GROUP = ADS_GROUP_TYPE_ENUM.UNIVERSAL_GROUP; pub const ADS_GROUP_TYPE_SECURITY_ENABLED = ADS_GROUP_TYPE_ENUM.SECURITY_ENABLED; pub const ADS_USER_FLAG_ENUM = enum(i32) { SCRIPT = 1, ACCOUNTDISABLE = 2, HOMEDIR_REQUIRED = 8, LOCKOUT = 16, PASSWD_NOTREQD = 32, PASSWD_CANT_CHANGE = 64, ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128, TEMP_DUPLICATE_ACCOUNT = 256, NORMAL_ACCOUNT = 512, INTERDOMAIN_TRUST_ACCOUNT = 2048, WORKSTATION_TRUST_ACCOUNT = 4096, SERVER_TRUST_ACCOUNT = 8192, DONT_EXPIRE_PASSWD = 65536, MNS_LOGON_ACCOUNT = 131072, SMARTCARD_REQUIRED = 262144, TRUSTED_FOR_DELEGATION = 524288, NOT_DELEGATED = 1048576, USE_DES_KEY_ONLY = 2097152, DONT_REQUIRE_PREAUTH = 4194304, PASSWORD_EXPIRED = 8388608, TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216, }; pub const ADS_UF_SCRIPT = ADS_USER_FLAG_ENUM.SCRIPT; pub const ADS_UF_ACCOUNTDISABLE = ADS_USER_FLAG_ENUM.ACCOUNTDISABLE; pub const ADS_UF_HOMEDIR_REQUIRED = ADS_USER_FLAG_ENUM.HOMEDIR_REQUIRED; pub const ADS_UF_LOCKOUT = ADS_USER_FLAG_ENUM.LOCKOUT; pub const ADS_UF_PASSWD_NOTREQD = ADS_USER_FLAG_ENUM.PASSWD_NOTREQD; pub const ADS_UF_PASSWD_CANT_CHANGE = ADS_USER_FLAG_ENUM.PASSWD_CANT_CHANGE; pub const ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = ADS_USER_FLAG_ENUM.ENCRYPTED_TEXT_PASSWORD_ALLOWED; pub const ADS_UF_TEMP_DUPLICATE_ACCOUNT = ADS_USER_FLAG_ENUM.TEMP_DUPLICATE_ACCOUNT; pub const ADS_UF_NORMAL_ACCOUNT = ADS_USER_FLAG_ENUM.NORMAL_ACCOUNT; pub const ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = ADS_USER_FLAG_ENUM.INTERDOMAIN_TRUST_ACCOUNT; pub const ADS_UF_WORKSTATION_TRUST_ACCOUNT = ADS_USER_FLAG_ENUM.WORKSTATION_TRUST_ACCOUNT; pub const ADS_UF_SERVER_TRUST_ACCOUNT = ADS_USER_FLAG_ENUM.SERVER_TRUST_ACCOUNT; pub const ADS_UF_DONT_EXPIRE_PASSWD = ADS_USER_FLAG_ENUM.DONT_EXPIRE_PASSWD; pub const ADS_UF_MNS_LOGON_ACCOUNT = ADS_USER_FLAG_ENUM.MNS_LOGON_ACCOUNT; pub const ADS_UF_SMARTCARD_REQUIRED = ADS_USER_FLAG_ENUM.SMARTCARD_REQUIRED; pub const ADS_UF_TRUSTED_FOR_DELEGATION = ADS_USER_FLAG_ENUM.TRUSTED_FOR_DELEGATION; pub const ADS_UF_NOT_DELEGATED = ADS_USER_FLAG_ENUM.NOT_DELEGATED; pub const ADS_UF_USE_DES_KEY_ONLY = ADS_USER_FLAG_ENUM.USE_DES_KEY_ONLY; pub const ADS_UF_DONT_REQUIRE_PREAUTH = ADS_USER_FLAG_ENUM.DONT_REQUIRE_PREAUTH; pub const ADS_UF_PASSWORD_EXPIRED = ADS_USER_FLAG_ENUM.PASSWORD_EXPIRED; pub const ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = ADS_USER_FLAG_ENUM.TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION; pub const ADS_RIGHTS_ENUM = enum(i32) { DELETE = 65536, READ_CONTROL = 131072, WRITE_DAC = 262144, WRITE_OWNER = 524288, SYNCHRONIZE = 1048576, ACCESS_SYSTEM_SECURITY = 16777216, GENERIC_READ = -2147483648, GENERIC_WRITE = 1073741824, GENERIC_EXECUTE = 536870912, GENERIC_ALL = 268435456, DS_CREATE_CHILD = 1, DS_DELETE_CHILD = 2, ACTRL_DS_LIST = 4, DS_SELF = 8, DS_READ_PROP = 16, DS_WRITE_PROP = 32, DS_DELETE_TREE = 64, DS_LIST_OBJECT = 128, DS_CONTROL_ACCESS = 256, }; pub const ADS_RIGHT_DELETE = ADS_RIGHTS_ENUM.DELETE; pub const ADS_RIGHT_READ_CONTROL = ADS_RIGHTS_ENUM.READ_CONTROL; pub const ADS_RIGHT_WRITE_DAC = ADS_RIGHTS_ENUM.WRITE_DAC; pub const ADS_RIGHT_WRITE_OWNER = ADS_RIGHTS_ENUM.WRITE_OWNER; pub const ADS_RIGHT_SYNCHRONIZE = ADS_RIGHTS_ENUM.SYNCHRONIZE; pub const ADS_RIGHT_ACCESS_SYSTEM_SECURITY = ADS_RIGHTS_ENUM.ACCESS_SYSTEM_SECURITY; pub const ADS_RIGHT_GENERIC_READ = ADS_RIGHTS_ENUM.GENERIC_READ; pub const ADS_RIGHT_GENERIC_WRITE = ADS_RIGHTS_ENUM.GENERIC_WRITE; pub const ADS_RIGHT_GENERIC_EXECUTE = ADS_RIGHTS_ENUM.GENERIC_EXECUTE; pub const ADS_RIGHT_GENERIC_ALL = ADS_RIGHTS_ENUM.GENERIC_ALL; pub const ADS_RIGHT_DS_CREATE_CHILD = ADS_RIGHTS_ENUM.DS_CREATE_CHILD; pub const ADS_RIGHT_DS_DELETE_CHILD = ADS_RIGHTS_ENUM.DS_DELETE_CHILD; pub const ADS_RIGHT_ACTRL_DS_LIST = ADS_RIGHTS_ENUM.ACTRL_DS_LIST; pub const ADS_RIGHT_DS_SELF = ADS_RIGHTS_ENUM.DS_SELF; pub const ADS_RIGHT_DS_READ_PROP = ADS_RIGHTS_ENUM.DS_READ_PROP; pub const ADS_RIGHT_DS_WRITE_PROP = ADS_RIGHTS_ENUM.DS_WRITE_PROP; pub const ADS_RIGHT_DS_DELETE_TREE = ADS_RIGHTS_ENUM.DS_DELETE_TREE; pub const ADS_RIGHT_DS_LIST_OBJECT = ADS_RIGHTS_ENUM.DS_LIST_OBJECT; pub const ADS_RIGHT_DS_CONTROL_ACCESS = ADS_RIGHTS_ENUM.DS_CONTROL_ACCESS; pub const ADS_ACETYPE_ENUM = enum(i32) { ACCESS_ALLOWED = 0, ACCESS_DENIED = 1, SYSTEM_AUDIT = 2, ACCESS_ALLOWED_OBJECT = 5, ACCESS_DENIED_OBJECT = 6, SYSTEM_AUDIT_OBJECT = 7, SYSTEM_ALARM_OBJECT = 8, ACCESS_ALLOWED_CALLBACK = 9, ACCESS_DENIED_CALLBACK = 10, ACCESS_ALLOWED_CALLBACK_OBJECT = 11, ACCESS_DENIED_CALLBACK_OBJECT = 12, SYSTEM_AUDIT_CALLBACK = 13, SYSTEM_ALARM_CALLBACK = 14, SYSTEM_AUDIT_CALLBACK_OBJECT = 15, SYSTEM_ALARM_CALLBACK_OBJECT = 16, }; pub const ADS_ACETYPE_ACCESS_ALLOWED = ADS_ACETYPE_ENUM.ACCESS_ALLOWED; pub const ADS_ACETYPE_ACCESS_DENIED = ADS_ACETYPE_ENUM.ACCESS_DENIED; pub const ADS_ACETYPE_SYSTEM_AUDIT = ADS_ACETYPE_ENUM.SYSTEM_AUDIT; pub const ADS_ACETYPE_ACCESS_ALLOWED_OBJECT = ADS_ACETYPE_ENUM.ACCESS_ALLOWED_OBJECT; pub const ADS_ACETYPE_ACCESS_DENIED_OBJECT = ADS_ACETYPE_ENUM.ACCESS_DENIED_OBJECT; pub const ADS_ACETYPE_SYSTEM_AUDIT_OBJECT = ADS_ACETYPE_ENUM.SYSTEM_AUDIT_OBJECT; pub const ADS_ACETYPE_SYSTEM_ALARM_OBJECT = ADS_ACETYPE_ENUM.SYSTEM_ALARM_OBJECT; pub const ADS_ACETYPE_ACCESS_ALLOWED_CALLBACK = ADS_ACETYPE_ENUM.ACCESS_ALLOWED_CALLBACK; pub const ADS_ACETYPE_ACCESS_DENIED_CALLBACK = ADS_ACETYPE_ENUM.ACCESS_DENIED_CALLBACK; pub const ADS_ACETYPE_ACCESS_ALLOWED_CALLBACK_OBJECT = ADS_ACETYPE_ENUM.ACCESS_ALLOWED_CALLBACK_OBJECT; pub const ADS_ACETYPE_ACCESS_DENIED_CALLBACK_OBJECT = ADS_ACETYPE_ENUM.ACCESS_DENIED_CALLBACK_OBJECT; pub const ADS_ACETYPE_SYSTEM_AUDIT_CALLBACK = ADS_ACETYPE_ENUM.SYSTEM_AUDIT_CALLBACK; pub const ADS_ACETYPE_SYSTEM_ALARM_CALLBACK = ADS_ACETYPE_ENUM.SYSTEM_ALARM_CALLBACK; pub const ADS_ACETYPE_SYSTEM_AUDIT_CALLBACK_OBJECT = ADS_ACETYPE_ENUM.SYSTEM_AUDIT_CALLBACK_OBJECT; pub const ADS_ACETYPE_SYSTEM_ALARM_CALLBACK_OBJECT = ADS_ACETYPE_ENUM.SYSTEM_ALARM_CALLBACK_OBJECT; pub const ADS_ACEFLAG_ENUM = enum(i32) { INHERIT_ACE = 2, NO_PROPAGATE_INHERIT_ACE = 4, INHERIT_ONLY_ACE = 8, INHERITED_ACE = 16, VALID_INHERIT_FLAGS = 31, SUCCESSFUL_ACCESS = 64, FAILED_ACCESS = 128, }; pub const ADS_ACEFLAG_INHERIT_ACE = ADS_ACEFLAG_ENUM.INHERIT_ACE; pub const ADS_ACEFLAG_NO_PROPAGATE_INHERIT_ACE = ADS_ACEFLAG_ENUM.NO_PROPAGATE_INHERIT_ACE; pub const ADS_ACEFLAG_INHERIT_ONLY_ACE = ADS_ACEFLAG_ENUM.INHERIT_ONLY_ACE; pub const ADS_ACEFLAG_INHERITED_ACE = ADS_ACEFLAG_ENUM.INHERITED_ACE; pub const ADS_ACEFLAG_VALID_INHERIT_FLAGS = ADS_ACEFLAG_ENUM.VALID_INHERIT_FLAGS; pub const ADS_ACEFLAG_SUCCESSFUL_ACCESS = ADS_ACEFLAG_ENUM.SUCCESSFUL_ACCESS; pub const ADS_ACEFLAG_FAILED_ACCESS = ADS_ACEFLAG_ENUM.FAILED_ACCESS; pub const ADS_FLAGTYPE_ENUM = enum(i32) { OBJECT_TYPE_PRESENT = 1, INHERITED_OBJECT_TYPE_PRESENT = 2, }; pub const ADS_FLAG_OBJECT_TYPE_PRESENT = ADS_FLAGTYPE_ENUM.OBJECT_TYPE_PRESENT; pub const ADS_FLAG_INHERITED_OBJECT_TYPE_PRESENT = ADS_FLAGTYPE_ENUM.INHERITED_OBJECT_TYPE_PRESENT; pub const ADS_SD_CONTROL_ENUM = enum(i32) { OWNER_DEFAULTED = 1, GROUP_DEFAULTED = 2, DACL_PRESENT = 4, DACL_DEFAULTED = 8, SACL_PRESENT = 16, SACL_DEFAULTED = 32, DACL_AUTO_INHERIT_REQ = 256, SACL_AUTO_INHERIT_REQ = 512, DACL_AUTO_INHERITED = 1024, SACL_AUTO_INHERITED = 2048, DACL_PROTECTED = 4096, SACL_PROTECTED = 8192, SELF_RELATIVE = 32768, }; pub const ADS_SD_CONTROL_SE_OWNER_DEFAULTED = ADS_SD_CONTROL_ENUM.OWNER_DEFAULTED; pub const ADS_SD_CONTROL_SE_GROUP_DEFAULTED = ADS_SD_CONTROL_ENUM.GROUP_DEFAULTED; pub const ADS_SD_CONTROL_SE_DACL_PRESENT = ADS_SD_CONTROL_ENUM.DACL_PRESENT; pub const ADS_SD_CONTROL_SE_DACL_DEFAULTED = ADS_SD_CONTROL_ENUM.DACL_DEFAULTED; pub const ADS_SD_CONTROL_SE_SACL_PRESENT = ADS_SD_CONTROL_ENUM.SACL_PRESENT; pub const ADS_SD_CONTROL_SE_SACL_DEFAULTED = ADS_SD_CONTROL_ENUM.SACL_DEFAULTED; pub const ADS_SD_CONTROL_SE_DACL_AUTO_INHERIT_REQ = ADS_SD_CONTROL_ENUM.DACL_AUTO_INHERIT_REQ; pub const ADS_SD_CONTROL_SE_SACL_AUTO_INHERIT_REQ = ADS_SD_CONTROL_ENUM.SACL_AUTO_INHERIT_REQ; pub const ADS_SD_CONTROL_SE_DACL_AUTO_INHERITED = ADS_SD_CONTROL_ENUM.DACL_AUTO_INHERITED; pub const ADS_SD_CONTROL_SE_SACL_AUTO_INHERITED = ADS_SD_CONTROL_ENUM.SACL_AUTO_INHERITED; pub const ADS_SD_CONTROL_SE_DACL_PROTECTED = ADS_SD_CONTROL_ENUM.DACL_PROTECTED; pub const ADS_SD_CONTROL_SE_SACL_PROTECTED = ADS_SD_CONTROL_ENUM.SACL_PROTECTED; pub const ADS_SD_CONTROL_SE_SELF_RELATIVE = ADS_SD_CONTROL_ENUM.SELF_RELATIVE; pub const ADS_SD_REVISION_ENUM = enum(i32) { S = 4, }; pub const ADS_SD_REVISION_DS = ADS_SD_REVISION_ENUM.S; pub const ADS_NAME_TYPE_ENUM = enum(i32) { @"1779" = 1, CANONICAL = 2, NT4 = 3, DISPLAY = 4, DOMAIN_SIMPLE = 5, ENTERPRISE_SIMPLE = 6, GUID = 7, UNKNOWN = 8, USER_PRINCIPAL_NAME = 9, CANONICAL_EX = 10, SERVICE_PRINCIPAL_NAME = 11, SID_OR_SID_HISTORY_NAME = 12, }; pub const ADS_NAME_TYPE_1779 = ADS_NAME_TYPE_ENUM.@"1779"; pub const ADS_NAME_TYPE_CANONICAL = ADS_NAME_TYPE_ENUM.CANONICAL; pub const ADS_NAME_TYPE_NT4 = ADS_NAME_TYPE_ENUM.NT4; pub const ADS_NAME_TYPE_DISPLAY = ADS_NAME_TYPE_ENUM.DISPLAY; pub const ADS_NAME_TYPE_DOMAIN_SIMPLE = ADS_NAME_TYPE_ENUM.DOMAIN_SIMPLE; pub const ADS_NAME_TYPE_ENTERPRISE_SIMPLE = ADS_NAME_TYPE_ENUM.ENTERPRISE_SIMPLE; pub const ADS_NAME_TYPE_GUID = ADS_NAME_TYPE_ENUM.GUID; pub const ADS_NAME_TYPE_UNKNOWN = ADS_NAME_TYPE_ENUM.UNKNOWN; pub const ADS_NAME_TYPE_USER_PRINCIPAL_NAME = ADS_NAME_TYPE_ENUM.USER_PRINCIPAL_NAME; pub const ADS_NAME_TYPE_CANONICAL_EX = ADS_NAME_TYPE_ENUM.CANONICAL_EX; pub const ADS_NAME_TYPE_SERVICE_PRINCIPAL_NAME = ADS_NAME_TYPE_ENUM.SERVICE_PRINCIPAL_NAME; pub const ADS_NAME_TYPE_SID_OR_SID_HISTORY_NAME = ADS_NAME_TYPE_ENUM.SID_OR_SID_HISTORY_NAME; pub const ADS_NAME_INITTYPE_ENUM = enum(i32) { DOMAIN = 1, SERVER = 2, GC = 3, }; pub const ADS_NAME_INITTYPE_DOMAIN = ADS_NAME_INITTYPE_ENUM.DOMAIN; pub const ADS_NAME_INITTYPE_SERVER = ADS_NAME_INITTYPE_ENUM.SERVER; pub const ADS_NAME_INITTYPE_GC = ADS_NAME_INITTYPE_ENUM.GC; pub const ADS_OPTION_ENUM = enum(i32) { SERVERNAME = 0, REFERRALS = 1, PAGE_SIZE = 2, SECURITY_MASK = 3, MUTUAL_AUTH_STATUS = 4, QUOTA = 5, PASSWORD_PORTNUMBER = 6, PASSWORD_METHOD = 7, ACCUMULATIVE_MODIFICATION = 8, SKIP_SID_LOOKUP = 9, }; pub const ADS_OPTION_SERVERNAME = ADS_OPTION_ENUM.SERVERNAME; pub const ADS_OPTION_REFERRALS = ADS_OPTION_ENUM.REFERRALS; pub const ADS_OPTION_PAGE_SIZE = ADS_OPTION_ENUM.PAGE_SIZE; pub const ADS_OPTION_SECURITY_MASK = ADS_OPTION_ENUM.SECURITY_MASK; pub const ADS_OPTION_MUTUAL_AUTH_STATUS = ADS_OPTION_ENUM.MUTUAL_AUTH_STATUS; pub const ADS_OPTION_QUOTA = ADS_OPTION_ENUM.QUOTA; pub const ADS_OPTION_PASSWORD_PORTNUMBER = ADS_OPTION_ENUM.PASSWORD_PORTNUMBER; pub const ADS_OPTION_PASSWORD_METHOD = ADS_OPTION_ENUM.PASSWORD_METHOD; pub const ADS_OPTION_ACCUMULATIVE_MODIFICATION = ADS_OPTION_ENUM.ACCUMULATIVE_MODIFICATION; pub const ADS_OPTION_SKIP_SID_LOOKUP = ADS_OPTION_ENUM.SKIP_SID_LOOKUP; pub const ADS_SECURITY_INFO_ENUM = enum(i32) { OWNER = 1, GROUP = 2, DACL = 4, SACL = 8, }; pub const ADS_SECURITY_INFO_OWNER = ADS_SECURITY_INFO_ENUM.OWNER; pub const ADS_SECURITY_INFO_GROUP = ADS_SECURITY_INFO_ENUM.GROUP; pub const ADS_SECURITY_INFO_DACL = ADS_SECURITY_INFO_ENUM.DACL; pub const ADS_SECURITY_INFO_SACL = ADS_SECURITY_INFO_ENUM.SACL; pub const ADS_SETTYPE_ENUM = enum(i32) { FULL = 1, PROVIDER = 2, SERVER = 3, DN = 4, }; pub const ADS_SETTYPE_FULL = ADS_SETTYPE_ENUM.FULL; pub const ADS_SETTYPE_PROVIDER = ADS_SETTYPE_ENUM.PROVIDER; pub const ADS_SETTYPE_SERVER = ADS_SETTYPE_ENUM.SERVER; pub const ADS_SETTYPE_DN = ADS_SETTYPE_ENUM.DN; pub const ADS_FORMAT_ENUM = enum(i32) { WINDOWS = 1, WINDOWS_NO_SERVER = 2, WINDOWS_DN = 3, WINDOWS_PARENT = 4, X500 = 5, X500_NO_SERVER = 6, X500_DN = 7, X500_PARENT = 8, SERVER = 9, PROVIDER = 10, LEAF = 11, }; pub const ADS_FORMAT_WINDOWS = ADS_FORMAT_ENUM.WINDOWS; pub const ADS_FORMAT_WINDOWS_NO_SERVER = ADS_FORMAT_ENUM.WINDOWS_NO_SERVER; pub const ADS_FORMAT_WINDOWS_DN = ADS_FORMAT_ENUM.WINDOWS_DN; pub const ADS_FORMAT_WINDOWS_PARENT = ADS_FORMAT_ENUM.WINDOWS_PARENT; pub const ADS_FORMAT_X500 = ADS_FORMAT_ENUM.X500; pub const ADS_FORMAT_X500_NO_SERVER = ADS_FORMAT_ENUM.X500_NO_SERVER; pub const ADS_FORMAT_X500_DN = ADS_FORMAT_ENUM.X500_DN; pub const ADS_FORMAT_X500_PARENT = ADS_FORMAT_ENUM.X500_PARENT; pub const ADS_FORMAT_SERVER = ADS_FORMAT_ENUM.SERVER; pub const ADS_FORMAT_PROVIDER = ADS_FORMAT_ENUM.PROVIDER; pub const ADS_FORMAT_LEAF = ADS_FORMAT_ENUM.LEAF; pub const ADS_DISPLAY_ENUM = enum(i32) { FULL = 1, VALUE_ONLY = 2, }; pub const ADS_DISPLAY_FULL = ADS_DISPLAY_ENUM.FULL; pub const ADS_DISPLAY_VALUE_ONLY = ADS_DISPLAY_ENUM.VALUE_ONLY; pub const ADS_ESCAPE_MODE_ENUM = enum(i32) { DEFAULT = 1, ON = 2, OFF = 3, OFF_EX = 4, }; pub const ADS_ESCAPEDMODE_DEFAULT = ADS_ESCAPE_MODE_ENUM.DEFAULT; pub const ADS_ESCAPEDMODE_ON = ADS_ESCAPE_MODE_ENUM.ON; pub const ADS_ESCAPEDMODE_OFF = ADS_ESCAPE_MODE_ENUM.OFF; pub const ADS_ESCAPEDMODE_OFF_EX = ADS_ESCAPE_MODE_ENUM.OFF_EX; pub const ADS_PATHTYPE_ENUM = enum(i32) { FILE = 1, FILESHARE = 2, REGISTRY = 3, }; pub const ADS_PATH_FILE = ADS_PATHTYPE_ENUM.FILE; pub const ADS_PATH_FILESHARE = ADS_PATHTYPE_ENUM.FILESHARE; pub const ADS_PATH_REGISTRY = ADS_PATHTYPE_ENUM.REGISTRY; pub const ADS_SD_FORMAT_ENUM = enum(i32) { IID = 1, RAW = 2, HEXSTRING = 3, }; pub const ADS_SD_FORMAT_IID = ADS_SD_FORMAT_ENUM.IID; pub const ADS_SD_FORMAT_RAW = ADS_SD_FORMAT_ENUM.RAW; pub const ADS_SD_FORMAT_HEXSTRING = ADS_SD_FORMAT_ENUM.HEXSTRING; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADs_Value = @import("../zig.zig").Guid.initString("fd8256d0-fd15-11ce-abc4-02608c9e7553"); pub const IID_IADs = &IID_IADs_Value; pub const IADs = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IADs, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Class: fn( self: *const IADs, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GUID: fn( self: *const IADs, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ADsPath: fn( self: *const IADs, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Parent: fn( self: *const IADs, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Schema: fn( self: *const IADs, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInfo: fn( self: *const IADs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetInfo: fn( self: *const IADs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IADs, bstrName: ?BSTR, pvProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Put: fn( self: *const IADs, bstrName: ?BSTR, vProp: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEx: fn( self: *const IADs, bstrName: ?BSTR, pvProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutEx: fn( self: *const IADs, lnControlCode: i32, bstrName: ?BSTR, vProp: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInfoEx: fn( self: *const IADs, vProperties: VARIANT, lnReserved: 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 IADs_get_Name(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).get_Name(@ptrCast(*const IADs, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_get_Class(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).get_Class(@ptrCast(*const IADs, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_get_GUID(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).get_GUID(@ptrCast(*const IADs, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_get_ADsPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).get_ADsPath(@ptrCast(*const IADs, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_get_Parent(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).get_Parent(@ptrCast(*const IADs, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_get_Schema(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).get_Schema(@ptrCast(*const IADs, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_GetInfo(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).GetInfo(@ptrCast(*const IADs, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_SetInfo(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).SetInfo(@ptrCast(*const IADs, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_Get(self: *const T, bstrName: ?BSTR, pvProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).Get(@ptrCast(*const IADs, self), bstrName, pvProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_Put(self: *const T, bstrName: ?BSTR, vProp: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).Put(@ptrCast(*const IADs, self), bstrName, vProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_GetEx(self: *const T, bstrName: ?BSTR, pvProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).GetEx(@ptrCast(*const IADs, self), bstrName, pvProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_PutEx(self: *const T, lnControlCode: i32, bstrName: ?BSTR, vProp: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).PutEx(@ptrCast(*const IADs, self), lnControlCode, bstrName, vProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADs_GetInfoEx(self: *const T, vProperties: VARIANT, lnReserved: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADs.VTable, self.vtable).GetInfoEx(@ptrCast(*const IADs, self), vProperties, lnReserved); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsContainer_Value = @import("../zig.zig").Guid.initString("001677d0-fd16-11ce-abc4-02608c9e7553"); pub const IID_IADsContainer = &IID_IADsContainer_Value; pub const IADsContainer = 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 IADsContainer, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IADsContainer, retval: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Filter: fn( self: *const IADsContainer, pVar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Filter: fn( self: *const IADsContainer, Var: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Hints: fn( self: *const IADsContainer, pvFilter: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Hints: fn( self: *const IADsContainer, vHints: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetObject: fn( self: *const IADsContainer, ClassName: ?BSTR, RelativeName: ?BSTR, ppObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Create: fn( self: *const IADsContainer, ClassName: ?BSTR, RelativeName: ?BSTR, ppObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Delete: fn( self: *const IADsContainer, bstrClassName: ?BSTR, bstrRelativeName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyHere: fn( self: *const IADsContainer, SourceName: ?BSTR, NewName: ?BSTR, ppObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MoveHere: fn( self: *const IADsContainer, SourceName: ?BSTR, NewName: ?BSTR, ppObject: ?*?*IDispatch, ) 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 IADsContainer_get_Count(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).get_Count(@ptrCast(*const IADsContainer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).get__NewEnum(@ptrCast(*const IADsContainer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_get_Filter(self: *const T, pVar: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).get_Filter(@ptrCast(*const IADsContainer, self), pVar); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_put_Filter(self: *const T, Var: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).put_Filter(@ptrCast(*const IADsContainer, self), Var); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_get_Hints(self: *const T, pvFilter: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).get_Hints(@ptrCast(*const IADsContainer, self), pvFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_put_Hints(self: *const T, vHints: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).put_Hints(@ptrCast(*const IADsContainer, self), vHints); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_GetObject(self: *const T, ClassName: ?BSTR, RelativeName: ?BSTR, ppObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).GetObject(@ptrCast(*const IADsContainer, self), ClassName, RelativeName, ppObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_Create(self: *const T, ClassName: ?BSTR, RelativeName: ?BSTR, ppObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).Create(@ptrCast(*const IADsContainer, self), ClassName, RelativeName, ppObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_Delete(self: *const T, bstrClassName: ?BSTR, bstrRelativeName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).Delete(@ptrCast(*const IADsContainer, self), bstrClassName, bstrRelativeName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_CopyHere(self: *const T, SourceName: ?BSTR, NewName: ?BSTR, ppObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).CopyHere(@ptrCast(*const IADsContainer, self), SourceName, NewName, ppObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsContainer_MoveHere(self: *const T, SourceName: ?BSTR, NewName: ?BSTR, ppObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsContainer.VTable, self.vtable).MoveHere(@ptrCast(*const IADsContainer, self), SourceName, NewName, ppObject); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsCollection_Value = @import("../zig.zig").Guid.initString("72b945e0-253b-11cf-a988-00aa006bc149"); pub const IID_IADsCollection = &IID_IADsCollection_Value; pub const IADsCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IADsCollection, ppEnumerator: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IADsCollection, bstrName: ?BSTR, vItem: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IADsCollection, bstrItemToBeRemoved: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetObject: fn( self: *const IADsCollection, bstrName: ?BSTR, pvItem: ?*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 IADsCollection_get__NewEnum(self: *const T, ppEnumerator: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IADsCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IADsCollection, self), ppEnumerator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsCollection_Add(self: *const T, bstrName: ?BSTR, vItem: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsCollection.VTable, self.vtable).Add(@ptrCast(*const IADsCollection, self), bstrName, vItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsCollection_Remove(self: *const T, bstrItemToBeRemoved: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsCollection.VTable, self.vtable).Remove(@ptrCast(*const IADsCollection, self), bstrItemToBeRemoved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsCollection_GetObject(self: *const T, bstrName: ?BSTR, pvItem: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsCollection.VTable, self.vtable).GetObject(@ptrCast(*const IADsCollection, self), bstrName, pvItem); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsMembers_Value = @import("../zig.zig").Guid.initString("451a0030-72ec-11cf-b03b-00aa006e0975"); pub const IID_IADsMembers = &IID_IADsMembers_Value; pub const IADsMembers = 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 IADsMembers, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IADsMembers, ppEnumerator: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Filter: fn( self: *const IADsMembers, pvFilter: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Filter: fn( self: *const IADsMembers, pvFilter: 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 IADsMembers_get_Count(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsMembers.VTable, self.vtable).get_Count(@ptrCast(*const IADsMembers, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsMembers_get__NewEnum(self: *const T, ppEnumerator: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IADsMembers.VTable, self.vtable).get__NewEnum(@ptrCast(*const IADsMembers, self), ppEnumerator); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsMembers_get_Filter(self: *const T, pvFilter: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsMembers.VTable, self.vtable).get_Filter(@ptrCast(*const IADsMembers, self), pvFilter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsMembers_put_Filter(self: *const T, pvFilter: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsMembers.VTable, self.vtable).put_Filter(@ptrCast(*const IADsMembers, self), pvFilter); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPropertyList_Value = @import("../zig.zig").Guid.initString("c6f602b6-8f69-11d0-8528-00c04fd8d503"); pub const IID_IADsPropertyList = &IID_IADsPropertyList_Value; pub const IADsPropertyList = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PropertyCount: fn( self: *const IADsPropertyList, plCount: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Next: fn( self: *const IADsPropertyList, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IADsPropertyList, cElements: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IADsPropertyList, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Item: fn( self: *const IADsPropertyList, varIndex: VARIANT, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyItem: fn( self: *const IADsPropertyList, bstrName: ?BSTR, lnADsType: i32, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutPropertyItem: fn( self: *const IADsPropertyList, varData: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ResetPropertyItem: fn( self: *const IADsPropertyList, varEntry: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PurgePropertyList: fn( self: *const IADsPropertyList, ) 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 IADsPropertyList_get_PropertyCount(self: *const T, plCount: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).get_PropertyCount(@ptrCast(*const IADsPropertyList, self), plCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_Next(self: *const T, pVariant: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).Next(@ptrCast(*const IADsPropertyList, self), pVariant); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_Skip(self: *const T, cElements: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).Skip(@ptrCast(*const IADsPropertyList, self), cElements); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).Reset(@ptrCast(*const IADsPropertyList, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_Item(self: *const T, varIndex: VARIANT, pVariant: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).Item(@ptrCast(*const IADsPropertyList, self), varIndex, pVariant); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_GetPropertyItem(self: *const T, bstrName: ?BSTR, lnADsType: i32, pVariant: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).GetPropertyItem(@ptrCast(*const IADsPropertyList, self), bstrName, lnADsType, pVariant); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_PutPropertyItem(self: *const T, varData: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).PutPropertyItem(@ptrCast(*const IADsPropertyList, self), varData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_ResetPropertyItem(self: *const T, varEntry: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).ResetPropertyItem(@ptrCast(*const IADsPropertyList, self), varEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyList_PurgePropertyList(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyList.VTable, self.vtable).PurgePropertyList(@ptrCast(*const IADsPropertyList, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPropertyEntry_Value = @import("../zig.zig").Guid.initString("05792c8e-941f-11d0-8529-00c04fd8d503"); pub const IID_IADsPropertyEntry = &IID_IADsPropertyEntry_Value; pub const IADsPropertyEntry = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Clear: fn( self: *const IADsPropertyEntry, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IADsPropertyEntry, retval: ?*?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 IADsPropertyEntry, bstrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ADsType: fn( self: *const IADsPropertyEntry, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ADsType: fn( self: *const IADsPropertyEntry, lnADsType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ControlCode: fn( self: *const IADsPropertyEntry, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ControlCode: fn( self: *const IADsPropertyEntry, lnControlCode: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Values: fn( self: *const IADsPropertyEntry, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Values: fn( self: *const IADsPropertyEntry, vValues: 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 IADsPropertyEntry_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).Clear(@ptrCast(*const IADsPropertyEntry, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_get_Name(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).get_Name(@ptrCast(*const IADsPropertyEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_put_Name(self: *const T, bstrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).put_Name(@ptrCast(*const IADsPropertyEntry, self), bstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_get_ADsType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).get_ADsType(@ptrCast(*const IADsPropertyEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_put_ADsType(self: *const T, lnADsType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).put_ADsType(@ptrCast(*const IADsPropertyEntry, self), lnADsType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_get_ControlCode(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).get_ControlCode(@ptrCast(*const IADsPropertyEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_put_ControlCode(self: *const T, lnControlCode: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).put_ControlCode(@ptrCast(*const IADsPropertyEntry, self), lnControlCode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_get_Values(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).get_Values(@ptrCast(*const IADsPropertyEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyEntry_put_Values(self: *const T, vValues: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyEntry.VTable, self.vtable).put_Values(@ptrCast(*const IADsPropertyEntry, self), vValues); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPropertyValue_Value = @import("../zig.zig").Guid.initString("79fa9ad0-a97c-11d0-8534-00c04fd8d503"); pub const IID_IADsPropertyValue = &IID_IADsPropertyValue_Value; pub const IADsPropertyValue = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Clear: fn( self: *const IADsPropertyValue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ADsType: fn( self: *const IADsPropertyValue, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ADsType: fn( self: *const IADsPropertyValue, lnADsType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DNString: fn( self: *const IADsPropertyValue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DNString: fn( self: *const IADsPropertyValue, bstrDNString: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CaseExactString: fn( self: *const IADsPropertyValue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CaseExactString: fn( self: *const IADsPropertyValue, bstrCaseExactString: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CaseIgnoreString: fn( self: *const IADsPropertyValue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CaseIgnoreString: fn( self: *const IADsPropertyValue, bstrCaseIgnoreString: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrintableString: fn( self: *const IADsPropertyValue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PrintableString: fn( self: *const IADsPropertyValue, bstrPrintableString: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NumericString: fn( self: *const IADsPropertyValue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NumericString: fn( self: *const IADsPropertyValue, bstrNumericString: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Boolean: fn( self: *const IADsPropertyValue, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Boolean: fn( self: *const IADsPropertyValue, lnBoolean: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Integer: fn( self: *const IADsPropertyValue, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Integer: fn( self: *const IADsPropertyValue, lnInteger: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OctetString: fn( self: *const IADsPropertyValue, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OctetString: fn( self: *const IADsPropertyValue, vOctetString: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SecurityDescriptor: fn( self: *const IADsPropertyValue, retval: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SecurityDescriptor: fn( self: *const IADsPropertyValue, pSecurityDescriptor: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LargeInteger: fn( self: *const IADsPropertyValue, retval: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LargeInteger: fn( self: *const IADsPropertyValue, pLargeInteger: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UTCTime: fn( self: *const IADsPropertyValue, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UTCTime: fn( self: *const IADsPropertyValue, daUTCTime: f64, ) 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 IADsPropertyValue_Clear(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).Clear(@ptrCast(*const IADsPropertyValue, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_ADsType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_ADsType(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_ADsType(self: *const T, lnADsType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_ADsType(@ptrCast(*const IADsPropertyValue, self), lnADsType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_DNString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_DNString(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_DNString(self: *const T, bstrDNString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_DNString(@ptrCast(*const IADsPropertyValue, self), bstrDNString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_CaseExactString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_CaseExactString(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_CaseExactString(self: *const T, bstrCaseExactString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_CaseExactString(@ptrCast(*const IADsPropertyValue, self), bstrCaseExactString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_CaseIgnoreString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_CaseIgnoreString(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_CaseIgnoreString(self: *const T, bstrCaseIgnoreString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_CaseIgnoreString(@ptrCast(*const IADsPropertyValue, self), bstrCaseIgnoreString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_PrintableString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_PrintableString(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_PrintableString(self: *const T, bstrPrintableString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_PrintableString(@ptrCast(*const IADsPropertyValue, self), bstrPrintableString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_NumericString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_NumericString(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_NumericString(self: *const T, bstrNumericString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_NumericString(@ptrCast(*const IADsPropertyValue, self), bstrNumericString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_Boolean(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_Boolean(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_Boolean(self: *const T, lnBoolean: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_Boolean(@ptrCast(*const IADsPropertyValue, self), lnBoolean); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_Integer(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_Integer(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_Integer(self: *const T, lnInteger: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_Integer(@ptrCast(*const IADsPropertyValue, self), lnInteger); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_OctetString(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_OctetString(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_OctetString(self: *const T, vOctetString: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_OctetString(@ptrCast(*const IADsPropertyValue, self), vOctetString); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_SecurityDescriptor(self: *const T, retval: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_SecurityDescriptor(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_SecurityDescriptor(self: *const T, pSecurityDescriptor: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_SecurityDescriptor(@ptrCast(*const IADsPropertyValue, self), pSecurityDescriptor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_LargeInteger(self: *const T, retval: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_LargeInteger(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_LargeInteger(self: *const T, pLargeInteger: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_LargeInteger(@ptrCast(*const IADsPropertyValue, self), pLargeInteger); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_get_UTCTime(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).get_UTCTime(@ptrCast(*const IADsPropertyValue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue_put_UTCTime(self: *const T, daUTCTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue.VTable, self.vtable).put_UTCTime(@ptrCast(*const IADsPropertyValue, self), daUTCTime); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPropertyValue2_Value = @import("../zig.zig").Guid.initString("306e831c-5bc7-11d1-a3b8-00c04fb950dc"); pub const IID_IADsPropertyValue2 = &IID_IADsPropertyValue2_Value; pub const IADsPropertyValue2 = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetObjectProperty: fn( self: *const IADsPropertyValue2, lnADsType: ?*i32, pvProp: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PutObjectProperty: fn( self: *const IADsPropertyValue2, lnADsType: i32, vProp: 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 IADsPropertyValue2_GetObjectProperty(self: *const T, lnADsType: ?*i32, pvProp: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue2.VTable, self.vtable).GetObjectProperty(@ptrCast(*const IADsPropertyValue2, self), lnADsType, pvProp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPropertyValue2_PutObjectProperty(self: *const T, lnADsType: i32, vProp: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPropertyValue2.VTable, self.vtable).PutObjectProperty(@ptrCast(*const IADsPropertyValue2, self), lnADsType, vProp); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrivateDispatch_Value = @import("../zig.zig").Guid.initString("86ab4bbe-65f6-11d1-8c13-00c04fd8d503"); pub const IID_IPrivateDispatch = &IID_IPrivateDispatch_Value; pub const IPrivateDispatch = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ADSIInitializeDispatchManager: fn( self: *const IPrivateDispatch, dwExtensionId: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ADSIGetTypeInfoCount: fn( self: *const IPrivateDispatch, pctinfo: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ADSIGetTypeInfo: fn( self: *const IPrivateDispatch, itinfo: u32, lcid: u32, pptinfo: ?*?*ITypeInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ADSIGetIDsOfNames: fn( self: *const IPrivateDispatch, riid: ?*const Guid, rgszNames: ?*?*u16, cNames: u32, lcid: u32, rgdispid: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ADSIInvoke: fn( self: *const IPrivateDispatch, dispidMember: i32, riid: ?*const Guid, lcid: u32, wFlags: u16, pdispparams: ?*DISPPARAMS, pvarResult: ?*VARIANT, pexcepinfo: ?*EXCEPINFO, puArgErr: ?*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 IPrivateDispatch_ADSIInitializeDispatchManager(self: *const T, dwExtensionId: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateDispatch.VTable, self.vtable).ADSIInitializeDispatchManager(@ptrCast(*const IPrivateDispatch, self), dwExtensionId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrivateDispatch_ADSIGetTypeInfoCount(self: *const T, pctinfo: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateDispatch.VTable, self.vtable).ADSIGetTypeInfoCount(@ptrCast(*const IPrivateDispatch, self), pctinfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrivateDispatch_ADSIGetTypeInfo(self: *const T, itinfo: u32, lcid: u32, pptinfo: ?*?*ITypeInfo) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateDispatch.VTable, self.vtable).ADSIGetTypeInfo(@ptrCast(*const IPrivateDispatch, self), itinfo, lcid, pptinfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrivateDispatch_ADSIGetIDsOfNames(self: *const T, riid: ?*const Guid, rgszNames: ?*?*u16, cNames: u32, lcid: u32, rgdispid: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateDispatch.VTable, self.vtable).ADSIGetIDsOfNames(@ptrCast(*const IPrivateDispatch, self), riid, rgszNames, cNames, lcid, rgdispid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrivateDispatch_ADSIInvoke(self: *const T, dispidMember: i32, riid: ?*const Guid, lcid: u32, wFlags: u16, pdispparams: ?*DISPPARAMS, pvarResult: ?*VARIANT, pexcepinfo: ?*EXCEPINFO, puArgErr: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateDispatch.VTable, self.vtable).ADSIInvoke(@ptrCast(*const IPrivateDispatch, self), dispidMember, riid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrivateUnknown_Value = @import("../zig.zig").Guid.initString("89126bab-6ead-11d1-8c18-00c04fd8d503"); pub const IID_IPrivateUnknown = &IID_IPrivateUnknown_Value; pub const IPrivateUnknown = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ADSIInitializeObject: fn( self: *const IPrivateUnknown, lpszUserName: ?BSTR, lpszPassword: ?BSTR, lnReserved: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ADSIReleaseObject: fn( self: *const IPrivateUnknown, ) 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 IPrivateUnknown_ADSIInitializeObject(self: *const T, lpszUserName: ?BSTR, lpszPassword: ?BSTR, lnReserved: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateUnknown.VTable, self.vtable).ADSIInitializeObject(@ptrCast(*const IPrivateUnknown, self), lpszUserName, lpszPassword, lnReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrivateUnknown_ADSIReleaseObject(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrivateUnknown.VTable, self.vtable).ADSIReleaseObject(@ptrCast(*const IPrivateUnknown, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsExtension_Value = @import("../zig.zig").Guid.initString("3d35553c-d2b0-11d1-b17b-0000f87593a0"); pub const IID_IADsExtension = &IID_IADsExtension_Value; pub const IADsExtension = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Operate: fn( self: *const IADsExtension, dwCode: u32, varData1: VARIANT, varData2: VARIANT, varData3: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrivateGetIDsOfNames: fn( self: *const IADsExtension, riid: ?*const Guid, rgszNames: ?*?*u16, cNames: u32, lcid: u32, rgDispid: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrivateInvoke: fn( self: *const IADsExtension, dispidMember: i32, riid: ?*const Guid, lcid: u32, wFlags: u16, pdispparams: ?*DISPPARAMS, pvarResult: ?*VARIANT, pexcepinfo: ?*EXCEPINFO, puArgErr: ?*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 IADsExtension_Operate(self: *const T, dwCode: u32, varData1: VARIANT, varData2: VARIANT, varData3: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsExtension.VTable, self.vtable).Operate(@ptrCast(*const IADsExtension, self), dwCode, varData1, varData2, varData3); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsExtension_PrivateGetIDsOfNames(self: *const T, riid: ?*const Guid, rgszNames: ?*?*u16, cNames: u32, lcid: u32, rgDispid: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsExtension.VTable, self.vtable).PrivateGetIDsOfNames(@ptrCast(*const IADsExtension, self), riid, rgszNames, cNames, lcid, rgDispid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsExtension_PrivateInvoke(self: *const T, dispidMember: i32, riid: ?*const Guid, lcid: u32, wFlags: u16, pdispparams: ?*DISPPARAMS, pvarResult: ?*VARIANT, pexcepinfo: ?*EXCEPINFO, puArgErr: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsExtension.VTable, self.vtable).PrivateInvoke(@ptrCast(*const IADsExtension, self), dispidMember, riid, lcid, wFlags, pdispparams, pvarResult, pexcepinfo, puArgErr); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsDeleteOps_Value = @import("../zig.zig").Guid.initString("b2bd0902-8878-11d1-8c21-00c04fd8d503"); pub const IID_IADsDeleteOps = &IID_IADsDeleteOps_Value; pub const IADsDeleteOps = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, DeleteObject: fn( self: *const IADsDeleteOps, lnFlags: 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 IADsDeleteOps_DeleteObject(self: *const T, lnFlags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDeleteOps.VTable, self.vtable).DeleteObject(@ptrCast(*const IADsDeleteOps, self), lnFlags); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsNamespaces_Value = @import("../zig.zig").Guid.initString("28b96ba0-b330-11cf-a9ad-00aa006bc149"); pub const IID_IADsNamespaces = &IID_IADsNamespaces_Value; pub const IADsNamespaces = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DefaultContainer: fn( self: *const IADsNamespaces, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DefaultContainer: fn( self: *const IADsNamespaces, bstrDefaultContainer: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNamespaces_get_DefaultContainer(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNamespaces.VTable, self.vtable).get_DefaultContainer(@ptrCast(*const IADsNamespaces, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNamespaces_put_DefaultContainer(self: *const T, bstrDefaultContainer: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNamespaces.VTable, self.vtable).put_DefaultContainer(@ptrCast(*const IADsNamespaces, self), bstrDefaultContainer); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsClass_Value = @import("../zig.zig").Guid.initString("c8f93dd0-4ae0-11cf-9e73-00aa004a5691"); pub const IID_IADsClass = &IID_IADsClass_Value; pub const IADsClass = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrimaryInterface: fn( self: *const IADsClass, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CLSID: fn( self: *const IADsClass, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CLSID: fn( self: *const IADsClass, bstrCLSID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OID: fn( self: *const IADsClass, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OID: fn( self: *const IADsClass, bstrOID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Abstract: fn( self: *const IADsClass, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Abstract: fn( self: *const IADsClass, fAbstract: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Auxiliary: fn( self: *const IADsClass, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Auxiliary: fn( self: *const IADsClass, fAuxiliary: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MandatoryProperties: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MandatoryProperties: fn( self: *const IADsClass, vMandatoryProperties: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OptionalProperties: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OptionalProperties: fn( self: *const IADsClass, vOptionalProperties: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NamingProperties: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NamingProperties: fn( self: *const IADsClass, vNamingProperties: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DerivedFrom: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DerivedFrom: fn( self: *const IADsClass, vDerivedFrom: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AuxDerivedFrom: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AuxDerivedFrom: fn( self: *const IADsClass, vAuxDerivedFrom: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PossibleSuperiors: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PossibleSuperiors: fn( self: *const IADsClass, vPossibleSuperiors: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Containment: fn( self: *const IADsClass, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Containment: fn( self: *const IADsClass, vContainment: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Container: fn( self: *const IADsClass, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Container: fn( self: *const IADsClass, fContainer: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HelpFileName: fn( self: *const IADsClass, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HelpFileName: fn( self: *const IADsClass, bstrHelpFileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HelpFileContext: fn( self: *const IADsClass, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HelpFileContext: fn( self: *const IADsClass, lnHelpFileContext: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Qualifiers: fn( self: *const IADsClass, ppQualifiers: ?*?*IADsCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_PrimaryInterface(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_PrimaryInterface(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_CLSID(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_CLSID(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_CLSID(self: *const T, bstrCLSID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_CLSID(@ptrCast(*const IADsClass, self), bstrCLSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_OID(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_OID(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_OID(self: *const T, bstrOID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_OID(@ptrCast(*const IADsClass, self), bstrOID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_Abstract(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_Abstract(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_Abstract(self: *const T, fAbstract: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_Abstract(@ptrCast(*const IADsClass, self), fAbstract); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_Auxiliary(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_Auxiliary(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_Auxiliary(self: *const T, fAuxiliary: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_Auxiliary(@ptrCast(*const IADsClass, self), fAuxiliary); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_MandatoryProperties(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_MandatoryProperties(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_MandatoryProperties(self: *const T, vMandatoryProperties: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_MandatoryProperties(@ptrCast(*const IADsClass, self), vMandatoryProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_OptionalProperties(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_OptionalProperties(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_OptionalProperties(self: *const T, vOptionalProperties: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_OptionalProperties(@ptrCast(*const IADsClass, self), vOptionalProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_NamingProperties(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_NamingProperties(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_NamingProperties(self: *const T, vNamingProperties: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_NamingProperties(@ptrCast(*const IADsClass, self), vNamingProperties); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_DerivedFrom(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_DerivedFrom(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_DerivedFrom(self: *const T, vDerivedFrom: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_DerivedFrom(@ptrCast(*const IADsClass, self), vDerivedFrom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_AuxDerivedFrom(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_AuxDerivedFrom(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_AuxDerivedFrom(self: *const T, vAuxDerivedFrom: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_AuxDerivedFrom(@ptrCast(*const IADsClass, self), vAuxDerivedFrom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_PossibleSuperiors(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_PossibleSuperiors(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_PossibleSuperiors(self: *const T, vPossibleSuperiors: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_PossibleSuperiors(@ptrCast(*const IADsClass, self), vPossibleSuperiors); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_Containment(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_Containment(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_Containment(self: *const T, vContainment: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_Containment(@ptrCast(*const IADsClass, self), vContainment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_Container(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_Container(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_Container(self: *const T, fContainer: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_Container(@ptrCast(*const IADsClass, self), fContainer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_HelpFileName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_HelpFileName(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_HelpFileName(self: *const T, bstrHelpFileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_HelpFileName(@ptrCast(*const IADsClass, self), bstrHelpFileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_get_HelpFileContext(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).get_HelpFileContext(@ptrCast(*const IADsClass, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_put_HelpFileContext(self: *const T, lnHelpFileContext: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).put_HelpFileContext(@ptrCast(*const IADsClass, self), lnHelpFileContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsClass_Qualifiers(self: *const T, ppQualifiers: ?*?*IADsCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IADsClass.VTable, self.vtable).Qualifiers(@ptrCast(*const IADsClass, self), ppQualifiers); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsProperty_Value = @import("../zig.zig").Guid.initString("c8f93dd3-4ae0-11cf-9e73-00aa004a5691"); pub const IID_IADsProperty = &IID_IADsProperty_Value; pub const IADsProperty = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OID: fn( self: *const IADsProperty, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OID: fn( self: *const IADsProperty, bstrOID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Syntax: fn( self: *const IADsProperty, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Syntax: fn( self: *const IADsProperty, bstrSyntax: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxRange: fn( self: *const IADsProperty, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxRange: fn( self: *const IADsProperty, lnMaxRange: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinRange: fn( self: *const IADsProperty, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinRange: fn( self: *const IADsProperty, lnMinRange: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MultiValued: fn( self: *const IADsProperty, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MultiValued: fn( self: *const IADsProperty, fMultiValued: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Qualifiers: fn( self: *const IADsProperty, ppQualifiers: ?*?*IADsCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_get_OID(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).get_OID(@ptrCast(*const IADsProperty, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_put_OID(self: *const T, bstrOID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).put_OID(@ptrCast(*const IADsProperty, self), bstrOID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_get_Syntax(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).get_Syntax(@ptrCast(*const IADsProperty, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_put_Syntax(self: *const T, bstrSyntax: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).put_Syntax(@ptrCast(*const IADsProperty, self), bstrSyntax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_get_MaxRange(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).get_MaxRange(@ptrCast(*const IADsProperty, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_put_MaxRange(self: *const T, lnMaxRange: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).put_MaxRange(@ptrCast(*const IADsProperty, self), lnMaxRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_get_MinRange(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).get_MinRange(@ptrCast(*const IADsProperty, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_put_MinRange(self: *const T, lnMinRange: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).put_MinRange(@ptrCast(*const IADsProperty, self), lnMinRange); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_get_MultiValued(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).get_MultiValued(@ptrCast(*const IADsProperty, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_put_MultiValued(self: *const T, fMultiValued: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).put_MultiValued(@ptrCast(*const IADsProperty, self), fMultiValued); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsProperty_Qualifiers(self: *const T, ppQualifiers: ?*?*IADsCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IADsProperty.VTable, self.vtable).Qualifiers(@ptrCast(*const IADsProperty, self), ppQualifiers); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsSyntax_Value = @import("../zig.zig").Guid.initString("c8f93dd2-4ae0-11cf-9e73-00aa004a5691"); pub const IID_IADsSyntax = &IID_IADsSyntax_Value; pub const IADsSyntax = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OleAutoDataType: fn( self: *const IADsSyntax, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OleAutoDataType: fn( self: *const IADsSyntax, lnOleAutoDataType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSyntax_get_OleAutoDataType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSyntax.VTable, self.vtable).get_OleAutoDataType(@ptrCast(*const IADsSyntax, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSyntax_put_OleAutoDataType(self: *const T, lnOleAutoDataType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSyntax.VTable, self.vtable).put_OleAutoDataType(@ptrCast(*const IADsSyntax, self), lnOleAutoDataType); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsLocality_Value = @import("../zig.zig").Guid.initString("a05e03a2-effe-11cf-8abc-00c04fd8d503"); pub const IID_IADsLocality = &IID_IADsLocality_Value; pub const IADsLocality = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsLocality, retval: ?*?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 IADsLocality, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LocalityName: fn( self: *const IADsLocality, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LocalityName: fn( self: *const IADsLocality, bstrLocalityName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalAddress: fn( self: *const IADsLocality, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PostalAddress: fn( self: *const IADsLocality, bstrPostalAddress: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SeeAlso: fn( self: *const IADsLocality, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SeeAlso: fn( self: *const IADsLocality, vSeeAlso: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).get_Description(@ptrCast(*const IADsLocality, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).put_Description(@ptrCast(*const IADsLocality, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_get_LocalityName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).get_LocalityName(@ptrCast(*const IADsLocality, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_put_LocalityName(self: *const T, bstrLocalityName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).put_LocalityName(@ptrCast(*const IADsLocality, self), bstrLocalityName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_get_PostalAddress(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).get_PostalAddress(@ptrCast(*const IADsLocality, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_put_PostalAddress(self: *const T, bstrPostalAddress: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).put_PostalAddress(@ptrCast(*const IADsLocality, self), bstrPostalAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_get_SeeAlso(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).get_SeeAlso(@ptrCast(*const IADsLocality, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLocality_put_SeeAlso(self: *const T, vSeeAlso: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLocality.VTable, self.vtable).put_SeeAlso(@ptrCast(*const IADsLocality, self), vSeeAlso); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsO_Value = @import("../zig.zig").Guid.initString("a1cd2dc6-effe-11cf-8abc-00c04fd8d503"); pub const IID_IADsO = &IID_IADsO_Value; pub const IADsO = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsO, retval: ?*?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 IADsO, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LocalityName: fn( self: *const IADsO, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LocalityName: fn( self: *const IADsO, bstrLocalityName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalAddress: fn( self: *const IADsO, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PostalAddress: fn( self: *const IADsO, bstrPostalAddress: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephoneNumber: fn( self: *const IADsO, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephoneNumber: fn( self: *const IADsO, bstrTelephoneNumber: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FaxNumber: fn( self: *const IADsO, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FaxNumber: fn( self: *const IADsO, bstrFaxNumber: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SeeAlso: fn( self: *const IADsO, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SeeAlso: fn( self: *const IADsO, vSeeAlso: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).get_Description(@ptrCast(*const IADsO, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).put_Description(@ptrCast(*const IADsO, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_get_LocalityName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).get_LocalityName(@ptrCast(*const IADsO, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_put_LocalityName(self: *const T, bstrLocalityName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).put_LocalityName(@ptrCast(*const IADsO, self), bstrLocalityName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_get_PostalAddress(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).get_PostalAddress(@ptrCast(*const IADsO, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_put_PostalAddress(self: *const T, bstrPostalAddress: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).put_PostalAddress(@ptrCast(*const IADsO, self), bstrPostalAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_get_TelephoneNumber(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).get_TelephoneNumber(@ptrCast(*const IADsO, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_put_TelephoneNumber(self: *const T, bstrTelephoneNumber: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).put_TelephoneNumber(@ptrCast(*const IADsO, self), bstrTelephoneNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_get_FaxNumber(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).get_FaxNumber(@ptrCast(*const IADsO, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_put_FaxNumber(self: *const T, bstrFaxNumber: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).put_FaxNumber(@ptrCast(*const IADsO, self), bstrFaxNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_get_SeeAlso(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).get_SeeAlso(@ptrCast(*const IADsO, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsO_put_SeeAlso(self: *const T, vSeeAlso: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsO.VTable, self.vtable).put_SeeAlso(@ptrCast(*const IADsO, self), vSeeAlso); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsOU_Value = @import("../zig.zig").Guid.initString("a2f733b8-effe-11cf-8abc-00c04fd8d503"); pub const IID_IADsOU = &IID_IADsOU_Value; pub const IADsOU = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsOU, retval: ?*?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 IADsOU, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LocalityName: fn( self: *const IADsOU, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LocalityName: fn( self: *const IADsOU, bstrLocalityName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalAddress: fn( self: *const IADsOU, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PostalAddress: fn( self: *const IADsOU, bstrPostalAddress: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephoneNumber: fn( self: *const IADsOU, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephoneNumber: fn( self: *const IADsOU, bstrTelephoneNumber: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FaxNumber: fn( self: *const IADsOU, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FaxNumber: fn( self: *const IADsOU, bstrFaxNumber: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SeeAlso: fn( self: *const IADsOU, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SeeAlso: fn( self: *const IADsOU, vSeeAlso: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BusinessCategory: fn( self: *const IADsOU, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BusinessCategory: fn( self: *const IADsOU, bstrBusinessCategory: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_Description(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_Description(@ptrCast(*const IADsOU, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_LocalityName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_LocalityName(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_LocalityName(self: *const T, bstrLocalityName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_LocalityName(@ptrCast(*const IADsOU, self), bstrLocalityName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_PostalAddress(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_PostalAddress(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_PostalAddress(self: *const T, bstrPostalAddress: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_PostalAddress(@ptrCast(*const IADsOU, self), bstrPostalAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_TelephoneNumber(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_TelephoneNumber(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_TelephoneNumber(self: *const T, bstrTelephoneNumber: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_TelephoneNumber(@ptrCast(*const IADsOU, self), bstrTelephoneNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_FaxNumber(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_FaxNumber(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_FaxNumber(self: *const T, bstrFaxNumber: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_FaxNumber(@ptrCast(*const IADsOU, self), bstrFaxNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_SeeAlso(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_SeeAlso(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_SeeAlso(self: *const T, vSeeAlso: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_SeeAlso(@ptrCast(*const IADsOU, self), vSeeAlso); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_get_BusinessCategory(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).get_BusinessCategory(@ptrCast(*const IADsOU, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOU_put_BusinessCategory(self: *const T, bstrBusinessCategory: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOU.VTable, self.vtable).put_BusinessCategory(@ptrCast(*const IADsOU, self), bstrBusinessCategory); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsDomain_Value = @import("../zig.zig").Guid.initString("00e4c220-fd16-11ce-abc4-02608c9e7553"); pub const IID_IADsDomain = &IID_IADsDomain_Value; pub const IADsDomain = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsWorkgroup: fn( self: *const IADsDomain, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinPasswordLength: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinPasswordLength: fn( self: *const IADsDomain, lnMinPasswordLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinPasswordAge: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinPasswordAge: fn( self: *const IADsDomain, lnMinPasswordAge: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxPasswordAge: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxPasswordAge: fn( self: *const IADsDomain, lnMaxPasswordAge: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxBadPasswordsAllowed: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxBadPasswordsAllowed: fn( self: *const IADsDomain, lnMaxBadPasswordsAllowed: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PasswordHistoryLength: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PasswordHistoryLength: fn( self: *const IADsDomain, lnPasswordHistoryLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PasswordAttributes: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PasswordAttributes: fn( self: *const IADsDomain, lnPasswordAttributes: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AutoUnlockInterval: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AutoUnlockInterval: fn( self: *const IADsDomain, lnAutoUnlockInterval: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LockoutObservationInterval: fn( self: *const IADsDomain, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LockoutObservationInterval: fn( self: *const IADsDomain, lnLockoutObservationInterval: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_IsWorkgroup(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_IsWorkgroup(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_MinPasswordLength(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_MinPasswordLength(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_MinPasswordLength(self: *const T, lnMinPasswordLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_MinPasswordLength(@ptrCast(*const IADsDomain, self), lnMinPasswordLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_MinPasswordAge(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_MinPasswordAge(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_MinPasswordAge(self: *const T, lnMinPasswordAge: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_MinPasswordAge(@ptrCast(*const IADsDomain, self), lnMinPasswordAge); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_MaxPasswordAge(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_MaxPasswordAge(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_MaxPasswordAge(self: *const T, lnMaxPasswordAge: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_MaxPasswordAge(@ptrCast(*const IADsDomain, self), lnMaxPasswordAge); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_MaxBadPasswordsAllowed(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_MaxBadPasswordsAllowed(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_MaxBadPasswordsAllowed(self: *const T, lnMaxBadPasswordsAllowed: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_MaxBadPasswordsAllowed(@ptrCast(*const IADsDomain, self), lnMaxBadPasswordsAllowed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_PasswordHistoryLength(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_PasswordHistoryLength(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_PasswordHistoryLength(self: *const T, lnPasswordHistoryLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_PasswordHistoryLength(@ptrCast(*const IADsDomain, self), lnPasswordHistoryLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_PasswordAttributes(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_PasswordAttributes(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_PasswordAttributes(self: *const T, lnPasswordAttributes: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_PasswordAttributes(@ptrCast(*const IADsDomain, self), lnPasswordAttributes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_AutoUnlockInterval(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_AutoUnlockInterval(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_AutoUnlockInterval(self: *const T, lnAutoUnlockInterval: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_AutoUnlockInterval(@ptrCast(*const IADsDomain, self), lnAutoUnlockInterval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_get_LockoutObservationInterval(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).get_LockoutObservationInterval(@ptrCast(*const IADsDomain, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDomain_put_LockoutObservationInterval(self: *const T, lnLockoutObservationInterval: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDomain.VTable, self.vtable).put_LockoutObservationInterval(@ptrCast(*const IADsDomain, self), lnLockoutObservationInterval); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsComputer_Value = @import("../zig.zig").Guid.initString("efe3cc70-1d9f-11cf-b1f3-02608c9e7553"); pub const IID_IADsComputer = &IID_IADsComputer_Value; pub const IADsComputer = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerID: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Site: fn( self: *const IADsComputer, retval: ?*?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 IADsComputer, retval: ?*?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 IADsComputer, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Location: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Location: fn( self: *const IADsComputer, bstrLocation: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrimaryUser: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PrimaryUser: fn( self: *const IADsComputer, bstrPrimaryUser: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Owner: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Owner: fn( self: *const IADsComputer, bstrOwner: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Division: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Division: fn( self: *const IADsComputer, bstrDivision: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Department: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Department: fn( self: *const IADsComputer, bstrDepartment: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Role: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Role: fn( self: *const IADsComputer, bstrRole: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OperatingSystem: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OperatingSystem: fn( self: *const IADsComputer, bstrOperatingSystem: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OperatingSystemVersion: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OperatingSystemVersion: fn( self: *const IADsComputer, bstrOperatingSystemVersion: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Model: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Model: fn( self: *const IADsComputer, bstrModel: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Processor: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Processor: fn( self: *const IADsComputer, bstrProcessor: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ProcessorCount: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ProcessorCount: fn( self: *const IADsComputer, bstrProcessorCount: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MemorySize: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MemorySize: fn( self: *const IADsComputer, bstrMemorySize: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StorageCapacity: fn( self: *const IADsComputer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StorageCapacity: fn( self: *const IADsComputer, bstrStorageCapacity: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NetAddresses: fn( self: *const IADsComputer, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NetAddresses: fn( self: *const IADsComputer, vNetAddresses: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_ComputerID(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_ComputerID(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Site(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Site(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Description(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Description(@ptrCast(*const IADsComputer, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Location(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Location(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Location(self: *const T, bstrLocation: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Location(@ptrCast(*const IADsComputer, self), bstrLocation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_PrimaryUser(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_PrimaryUser(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_PrimaryUser(self: *const T, bstrPrimaryUser: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_PrimaryUser(@ptrCast(*const IADsComputer, self), bstrPrimaryUser); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Owner(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Owner(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Owner(self: *const T, bstrOwner: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Owner(@ptrCast(*const IADsComputer, self), bstrOwner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Division(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Division(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Division(self: *const T, bstrDivision: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Division(@ptrCast(*const IADsComputer, self), bstrDivision); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Department(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Department(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Department(self: *const T, bstrDepartment: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Department(@ptrCast(*const IADsComputer, self), bstrDepartment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Role(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Role(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Role(self: *const T, bstrRole: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Role(@ptrCast(*const IADsComputer, self), bstrRole); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_OperatingSystem(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_OperatingSystem(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_OperatingSystem(self: *const T, bstrOperatingSystem: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_OperatingSystem(@ptrCast(*const IADsComputer, self), bstrOperatingSystem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_OperatingSystemVersion(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_OperatingSystemVersion(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_OperatingSystemVersion(self: *const T, bstrOperatingSystemVersion: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_OperatingSystemVersion(@ptrCast(*const IADsComputer, self), bstrOperatingSystemVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Model(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Model(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Model(self: *const T, bstrModel: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Model(@ptrCast(*const IADsComputer, self), bstrModel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_Processor(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_Processor(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_Processor(self: *const T, bstrProcessor: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_Processor(@ptrCast(*const IADsComputer, self), bstrProcessor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_ProcessorCount(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_ProcessorCount(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_ProcessorCount(self: *const T, bstrProcessorCount: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_ProcessorCount(@ptrCast(*const IADsComputer, self), bstrProcessorCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_MemorySize(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_MemorySize(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_MemorySize(self: *const T, bstrMemorySize: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_MemorySize(@ptrCast(*const IADsComputer, self), bstrMemorySize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_StorageCapacity(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_StorageCapacity(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_StorageCapacity(self: *const T, bstrStorageCapacity: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_StorageCapacity(@ptrCast(*const IADsComputer, self), bstrStorageCapacity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_get_NetAddresses(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).get_NetAddresses(@ptrCast(*const IADsComputer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputer_put_NetAddresses(self: *const T, vNetAddresses: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputer.VTable, self.vtable).put_NetAddresses(@ptrCast(*const IADsComputer, self), vNetAddresses); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsComputerOperations_Value = @import("../zig.zig").Guid.initString("ef497680-1d9f-11cf-b1f3-02608c9e7553"); pub const IID_IADsComputerOperations = &IID_IADsComputerOperations_Value; pub const IADsComputerOperations = extern struct { pub const VTable = extern struct { base: IADs.VTable, Status: fn( self: *const IADsComputerOperations, ppObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Shutdown: fn( self: *const IADsComputerOperations, bReboot: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputerOperations_Status(self: *const T, ppObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputerOperations.VTable, self.vtable).Status(@ptrCast(*const IADsComputerOperations, self), ppObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsComputerOperations_Shutdown(self: *const T, bReboot: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsComputerOperations.VTable, self.vtable).Shutdown(@ptrCast(*const IADsComputerOperations, self), bReboot); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsGroup_Value = @import("../zig.zig").Guid.initString("27636b00-410f-11cf-b1ff-02608c9e7553"); pub const IID_IADsGroup = &IID_IADsGroup_Value; pub const IADsGroup = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsGroup, retval: ?*?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 IADsGroup, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Members: fn( self: *const IADsGroup, ppMembers: ?*?*IADsMembers, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsMember: fn( self: *const IADsGroup, bstrMember: ?BSTR, bMember: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Add: fn( self: *const IADsGroup, bstrNewItem: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Remove: fn( self: *const IADsGroup, bstrItemToBeRemoved: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsGroup_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsGroup.VTable, self.vtable).get_Description(@ptrCast(*const IADsGroup, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsGroup_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsGroup.VTable, self.vtable).put_Description(@ptrCast(*const IADsGroup, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsGroup_Members(self: *const T, ppMembers: ?*?*IADsMembers) callconv(.Inline) HRESULT { return @ptrCast(*const IADsGroup.VTable, self.vtable).Members(@ptrCast(*const IADsGroup, self), ppMembers); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsGroup_IsMember(self: *const T, bstrMember: ?BSTR, bMember: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsGroup.VTable, self.vtable).IsMember(@ptrCast(*const IADsGroup, self), bstrMember, bMember); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsGroup_Add(self: *const T, bstrNewItem: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsGroup.VTable, self.vtable).Add(@ptrCast(*const IADsGroup, self), bstrNewItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsGroup_Remove(self: *const T, bstrItemToBeRemoved: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsGroup.VTable, self.vtable).Remove(@ptrCast(*const IADsGroup, self), bstrItemToBeRemoved); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsUser_Value = @import("../zig.zig").Guid.initString("3e37e320-17e2-11cf-abc4-02608c9e7553"); pub const IID_IADsUser = &IID_IADsUser_Value; pub const IADsUser = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BadLoginAddress: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BadLoginCount: fn( self: *const IADsUser, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LastLogin: fn( self: *const IADsUser, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LastLogoff: fn( self: *const IADsUser, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LastFailedLogin: fn( self: *const IADsUser, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PasswordLastChanged: fn( self: *const IADsUser, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsUser, retval: ?*?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 IADsUser, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Division: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Division: fn( self: *const IADsUser, bstrDivision: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Department: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Department: fn( self: *const IADsUser, bstrDepartment: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EmployeeID: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EmployeeID: fn( self: *const IADsUser, bstrEmployeeID: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FullName: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FullName: fn( self: *const IADsUser, bstrFullName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FirstName: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FirstName: fn( self: *const IADsUser, bstrFirstName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LastName: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LastName: fn( self: *const IADsUser, bstrLastName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OtherName: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OtherName: fn( self: *const IADsUser, bstrOtherName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NamePrefix: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NamePrefix: fn( self: *const IADsUser, bstrNamePrefix: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NameSuffix: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NameSuffix: fn( self: *const IADsUser, bstrNameSuffix: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Title: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Title: fn( self: *const IADsUser, bstrTitle: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Manager: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Manager: fn( self: *const IADsUser, bstrManager: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephoneHome: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephoneHome: fn( self: *const IADsUser, vTelephoneHome: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephoneMobile: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephoneMobile: fn( self: *const IADsUser, vTelephoneMobile: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephoneNumber: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephoneNumber: fn( self: *const IADsUser, vTelephoneNumber: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephonePager: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephonePager: fn( self: *const IADsUser, vTelephonePager: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_FaxNumber: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_FaxNumber: fn( self: *const IADsUser, vFaxNumber: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OfficeLocations: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OfficeLocations: fn( self: *const IADsUser, vOfficeLocations: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalAddresses: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PostalAddresses: fn( self: *const IADsUser, vPostalAddresses: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalCodes: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PostalCodes: fn( self: *const IADsUser, vPostalCodes: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SeeAlso: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SeeAlso: fn( self: *const IADsUser, vSeeAlso: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AccountDisabled: fn( self: *const IADsUser, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AccountDisabled: fn( self: *const IADsUser, fAccountDisabled: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AccountExpirationDate: fn( self: *const IADsUser, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AccountExpirationDate: fn( self: *const IADsUser, daAccountExpirationDate: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GraceLoginsAllowed: fn( self: *const IADsUser, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GraceLoginsAllowed: fn( self: *const IADsUser, lnGraceLoginsAllowed: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GraceLoginsRemaining: fn( self: *const IADsUser, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GraceLoginsRemaining: fn( self: *const IADsUser, lnGraceLoginsRemaining: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsAccountLocked: fn( self: *const IADsUser, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_IsAccountLocked: fn( self: *const IADsUser, fIsAccountLocked: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoginHours: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoginHours: fn( self: *const IADsUser, vLoginHours: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoginWorkstations: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoginWorkstations: fn( self: *const IADsUser, vLoginWorkstations: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxLogins: fn( self: *const IADsUser, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxLogins: fn( self: *const IADsUser, lnMaxLogins: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxStorage: fn( self: *const IADsUser, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxStorage: fn( self: *const IADsUser, lnMaxStorage: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PasswordExpirationDate: fn( self: *const IADsUser, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PasswordExpirationDate: fn( self: *const IADsUser, daPasswordExpirationDate: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PasswordMinimumLength: fn( self: *const IADsUser, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PasswordMinimumLength: fn( self: *const IADsUser, lnPasswordMinimumLength: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PasswordRequired: fn( self: *const IADsUser, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PasswordRequired: fn( self: *const IADsUser, fPasswordRequired: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RequireUniquePassword: fn( self: *const IADsUser, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RequireUniquePassword: fn( self: *const IADsUser, fRequireUniquePassword: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EmailAddress: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EmailAddress: fn( self: *const IADsUser, bstrEmailAddress: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HomeDirectory: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HomeDirectory: fn( self: *const IADsUser, bstrHomeDirectory: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Languages: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Languages: fn( self: *const IADsUser, vLanguages: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Profile: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Profile: fn( self: *const IADsUser, bstrProfile: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoginScript: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoginScript: fn( self: *const IADsUser, bstrLoginScript: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Picture: fn( self: *const IADsUser, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Picture: fn( self: *const IADsUser, vPicture: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HomePage: fn( self: *const IADsUser, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HomePage: fn( self: *const IADsUser, bstrHomePage: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Groups: fn( self: *const IADsUser, ppGroups: ?*?*IADsMembers, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPassword: fn( self: *const IADsUser, NewPassword: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChangePassword: fn( self: *const IADsUser, bstrOldPassword: ?BSTR, bstrNewPassword: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_BadLoginAddress(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_BadLoginAddress(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_BadLoginCount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_BadLoginCount(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LastLogin(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LastLogin(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LastLogoff(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LastLogoff(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LastFailedLogin(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LastFailedLogin(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_PasswordLastChanged(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_PasswordLastChanged(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Description(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Description(@ptrCast(*const IADsUser, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Division(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Division(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Division(self: *const T, bstrDivision: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Division(@ptrCast(*const IADsUser, self), bstrDivision); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Department(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Department(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Department(self: *const T, bstrDepartment: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Department(@ptrCast(*const IADsUser, self), bstrDepartment); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_EmployeeID(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_EmployeeID(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_EmployeeID(self: *const T, bstrEmployeeID: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_EmployeeID(@ptrCast(*const IADsUser, self), bstrEmployeeID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_FullName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_FullName(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_FullName(self: *const T, bstrFullName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_FullName(@ptrCast(*const IADsUser, self), bstrFullName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_FirstName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_FirstName(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_FirstName(self: *const T, bstrFirstName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_FirstName(@ptrCast(*const IADsUser, self), bstrFirstName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LastName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LastName(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_LastName(self: *const T, bstrLastName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_LastName(@ptrCast(*const IADsUser, self), bstrLastName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_OtherName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_OtherName(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_OtherName(self: *const T, bstrOtherName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_OtherName(@ptrCast(*const IADsUser, self), bstrOtherName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_NamePrefix(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_NamePrefix(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_NamePrefix(self: *const T, bstrNamePrefix: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_NamePrefix(@ptrCast(*const IADsUser, self), bstrNamePrefix); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_NameSuffix(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_NameSuffix(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_NameSuffix(self: *const T, bstrNameSuffix: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_NameSuffix(@ptrCast(*const IADsUser, self), bstrNameSuffix); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Title(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Title(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Title(self: *const T, bstrTitle: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Title(@ptrCast(*const IADsUser, self), bstrTitle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Manager(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Manager(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Manager(self: *const T, bstrManager: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Manager(@ptrCast(*const IADsUser, self), bstrManager); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_TelephoneHome(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_TelephoneHome(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_TelephoneHome(self: *const T, vTelephoneHome: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_TelephoneHome(@ptrCast(*const IADsUser, self), vTelephoneHome); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_TelephoneMobile(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_TelephoneMobile(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_TelephoneMobile(self: *const T, vTelephoneMobile: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_TelephoneMobile(@ptrCast(*const IADsUser, self), vTelephoneMobile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_TelephoneNumber(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_TelephoneNumber(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_TelephoneNumber(self: *const T, vTelephoneNumber: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_TelephoneNumber(@ptrCast(*const IADsUser, self), vTelephoneNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_TelephonePager(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_TelephonePager(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_TelephonePager(self: *const T, vTelephonePager: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_TelephonePager(@ptrCast(*const IADsUser, self), vTelephonePager); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_FaxNumber(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_FaxNumber(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_FaxNumber(self: *const T, vFaxNumber: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_FaxNumber(@ptrCast(*const IADsUser, self), vFaxNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_OfficeLocations(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_OfficeLocations(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_OfficeLocations(self: *const T, vOfficeLocations: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_OfficeLocations(@ptrCast(*const IADsUser, self), vOfficeLocations); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_PostalAddresses(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_PostalAddresses(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_PostalAddresses(self: *const T, vPostalAddresses: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_PostalAddresses(@ptrCast(*const IADsUser, self), vPostalAddresses); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_PostalCodes(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_PostalCodes(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_PostalCodes(self: *const T, vPostalCodes: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_PostalCodes(@ptrCast(*const IADsUser, self), vPostalCodes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_SeeAlso(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_SeeAlso(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_SeeAlso(self: *const T, vSeeAlso: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_SeeAlso(@ptrCast(*const IADsUser, self), vSeeAlso); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_AccountDisabled(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_AccountDisabled(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_AccountDisabled(self: *const T, fAccountDisabled: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_AccountDisabled(@ptrCast(*const IADsUser, self), fAccountDisabled); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_AccountExpirationDate(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_AccountExpirationDate(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_AccountExpirationDate(self: *const T, daAccountExpirationDate: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_AccountExpirationDate(@ptrCast(*const IADsUser, self), daAccountExpirationDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_GraceLoginsAllowed(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_GraceLoginsAllowed(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_GraceLoginsAllowed(self: *const T, lnGraceLoginsAllowed: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_GraceLoginsAllowed(@ptrCast(*const IADsUser, self), lnGraceLoginsAllowed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_GraceLoginsRemaining(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_GraceLoginsRemaining(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_GraceLoginsRemaining(self: *const T, lnGraceLoginsRemaining: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_GraceLoginsRemaining(@ptrCast(*const IADsUser, self), lnGraceLoginsRemaining); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_IsAccountLocked(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_IsAccountLocked(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_IsAccountLocked(self: *const T, fIsAccountLocked: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_IsAccountLocked(@ptrCast(*const IADsUser, self), fIsAccountLocked); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LoginHours(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LoginHours(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_LoginHours(self: *const T, vLoginHours: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_LoginHours(@ptrCast(*const IADsUser, self), vLoginHours); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LoginWorkstations(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LoginWorkstations(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_LoginWorkstations(self: *const T, vLoginWorkstations: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_LoginWorkstations(@ptrCast(*const IADsUser, self), vLoginWorkstations); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_MaxLogins(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_MaxLogins(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_MaxLogins(self: *const T, lnMaxLogins: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_MaxLogins(@ptrCast(*const IADsUser, self), lnMaxLogins); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_MaxStorage(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_MaxStorage(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_MaxStorage(self: *const T, lnMaxStorage: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_MaxStorage(@ptrCast(*const IADsUser, self), lnMaxStorage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_PasswordExpirationDate(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_PasswordExpirationDate(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_PasswordExpirationDate(self: *const T, daPasswordExpirationDate: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_PasswordExpirationDate(@ptrCast(*const IADsUser, self), daPasswordExpirationDate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_PasswordMinimumLength(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_PasswordMinimumLength(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_PasswordMinimumLength(self: *const T, lnPasswordMinimumLength: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_PasswordMinimumLength(@ptrCast(*const IADsUser, self), lnPasswordMinimumLength); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_PasswordRequired(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_PasswordRequired(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_PasswordRequired(self: *const T, fPasswordRequired: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_PasswordRequired(@ptrCast(*const IADsUser, self), fPasswordRequired); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_RequireUniquePassword(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_RequireUniquePassword(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_RequireUniquePassword(self: *const T, fRequireUniquePassword: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_RequireUniquePassword(@ptrCast(*const IADsUser, self), fRequireUniquePassword); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_EmailAddress(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_EmailAddress(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_EmailAddress(self: *const T, bstrEmailAddress: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_EmailAddress(@ptrCast(*const IADsUser, self), bstrEmailAddress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_HomeDirectory(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_HomeDirectory(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_HomeDirectory(self: *const T, bstrHomeDirectory: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_HomeDirectory(@ptrCast(*const IADsUser, self), bstrHomeDirectory); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Languages(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Languages(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Languages(self: *const T, vLanguages: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Languages(@ptrCast(*const IADsUser, self), vLanguages); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Profile(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Profile(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Profile(self: *const T, bstrProfile: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Profile(@ptrCast(*const IADsUser, self), bstrProfile); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_LoginScript(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_LoginScript(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_LoginScript(self: *const T, bstrLoginScript: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_LoginScript(@ptrCast(*const IADsUser, self), bstrLoginScript); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_Picture(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_Picture(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_Picture(self: *const T, vPicture: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_Picture(@ptrCast(*const IADsUser, self), vPicture); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_get_HomePage(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).get_HomePage(@ptrCast(*const IADsUser, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_put_HomePage(self: *const T, bstrHomePage: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).put_HomePage(@ptrCast(*const IADsUser, self), bstrHomePage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_Groups(self: *const T, ppGroups: ?*?*IADsMembers) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).Groups(@ptrCast(*const IADsUser, self), ppGroups); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_SetPassword(self: *const T, NewPassword: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).SetPassword(@ptrCast(*const IADsUser, self), NewPassword); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsUser_ChangePassword(self: *const T, bstrOldPassword: ?BSTR, bstrNewPassword: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsUser.VTable, self.vtable).ChangePassword(@ptrCast(*const IADsUser, self), bstrOldPassword, bstrNewPassword); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPrintQueue_Value = @import("../zig.zig").Guid.initString("b15160d0-1226-11cf-a985-00aa006bc149"); pub const IID_IADsPrintQueue = &IID_IADsPrintQueue_Value; pub const IADsPrintQueue = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrinterPath: fn( self: *const IADsPrintQueue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PrinterPath: fn( self: *const IADsPrintQueue, bstrPrinterPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Model: fn( self: *const IADsPrintQueue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Model: fn( self: *const IADsPrintQueue, bstrModel: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Datatype: fn( self: *const IADsPrintQueue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Datatype: fn( self: *const IADsPrintQueue, bstrDatatype: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrintProcessor: fn( self: *const IADsPrintQueue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PrintProcessor: fn( self: *const IADsPrintQueue, bstrPrintProcessor: ?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 IADsPrintQueue, retval: ?*?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 IADsPrintQueue, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Location: fn( self: *const IADsPrintQueue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Location: fn( self: *const IADsPrintQueue, bstrLocation: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartTime: fn( self: *const IADsPrintQueue, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StartTime: fn( self: *const IADsPrintQueue, daStartTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UntilTime: fn( self: *const IADsPrintQueue, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UntilTime: fn( self: *const IADsPrintQueue, daUntilTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DefaultJobPriority: fn( self: *const IADsPrintQueue, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DefaultJobPriority: fn( self: *const IADsPrintQueue, lnDefaultJobPriority: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Priority: fn( self: *const IADsPrintQueue, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Priority: fn( self: *const IADsPrintQueue, lnPriority: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BannerPage: fn( self: *const IADsPrintQueue, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BannerPage: fn( self: *const IADsPrintQueue, bstrBannerPage: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrintDevices: fn( self: *const IADsPrintQueue, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PrintDevices: fn( self: *const IADsPrintQueue, vPrintDevices: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NetAddresses: fn( self: *const IADsPrintQueue, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NetAddresses: fn( self: *const IADsPrintQueue, vNetAddresses: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_PrinterPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_PrinterPath(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_PrinterPath(self: *const T, bstrPrinterPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_PrinterPath(@ptrCast(*const IADsPrintQueue, self), bstrPrinterPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_Model(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_Model(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_Model(self: *const T, bstrModel: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_Model(@ptrCast(*const IADsPrintQueue, self), bstrModel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_Datatype(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_Datatype(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_Datatype(self: *const T, bstrDatatype: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_Datatype(@ptrCast(*const IADsPrintQueue, self), bstrDatatype); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_PrintProcessor(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_PrintProcessor(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_PrintProcessor(self: *const T, bstrPrintProcessor: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_PrintProcessor(@ptrCast(*const IADsPrintQueue, self), bstrPrintProcessor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_Description(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_Description(@ptrCast(*const IADsPrintQueue, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_Location(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_Location(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_Location(self: *const T, bstrLocation: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_Location(@ptrCast(*const IADsPrintQueue, self), bstrLocation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_StartTime(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_StartTime(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_StartTime(self: *const T, daStartTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_StartTime(@ptrCast(*const IADsPrintQueue, self), daStartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_UntilTime(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_UntilTime(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_UntilTime(self: *const T, daUntilTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_UntilTime(@ptrCast(*const IADsPrintQueue, self), daUntilTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_DefaultJobPriority(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_DefaultJobPriority(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_DefaultJobPriority(self: *const T, lnDefaultJobPriority: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_DefaultJobPriority(@ptrCast(*const IADsPrintQueue, self), lnDefaultJobPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_Priority(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_Priority(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_Priority(self: *const T, lnPriority: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_Priority(@ptrCast(*const IADsPrintQueue, self), lnPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_BannerPage(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_BannerPage(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_BannerPage(self: *const T, bstrBannerPage: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_BannerPage(@ptrCast(*const IADsPrintQueue, self), bstrBannerPage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_PrintDevices(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_PrintDevices(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_PrintDevices(self: *const T, vPrintDevices: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_PrintDevices(@ptrCast(*const IADsPrintQueue, self), vPrintDevices); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_get_NetAddresses(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).get_NetAddresses(@ptrCast(*const IADsPrintQueue, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueue_put_NetAddresses(self: *const T, vNetAddresses: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueue.VTable, self.vtable).put_NetAddresses(@ptrCast(*const IADsPrintQueue, self), vNetAddresses); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPrintQueueOperations_Value = @import("../zig.zig").Guid.initString("124be5c0-156e-11cf-a986-00aa006bc149"); pub const IID_IADsPrintQueueOperations = &IID_IADsPrintQueueOperations_Value; pub const IADsPrintQueueOperations = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const IADsPrintQueueOperations, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrintJobs: fn( self: *const IADsPrintQueueOperations, pObject: ?*?*IADsCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Pause: fn( self: *const IADsPrintQueueOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Resume: fn( self: *const IADsPrintQueueOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Purge: fn( self: *const IADsPrintQueueOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueueOperations_get_Status(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueueOperations.VTable, self.vtable).get_Status(@ptrCast(*const IADsPrintQueueOperations, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueueOperations_PrintJobs(self: *const T, pObject: ?*?*IADsCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueueOperations.VTable, self.vtable).PrintJobs(@ptrCast(*const IADsPrintQueueOperations, self), pObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueueOperations_Pause(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueueOperations.VTable, self.vtable).Pause(@ptrCast(*const IADsPrintQueueOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueueOperations_Resume(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueueOperations.VTable, self.vtable).Resume(@ptrCast(*const IADsPrintQueueOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintQueueOperations_Purge(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintQueueOperations.VTable, self.vtable).Purge(@ptrCast(*const IADsPrintQueueOperations, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPrintJob_Value = @import("../zig.zig").Guid.initString("32fb6780-1ed0-11cf-a988-00aa006bc149"); pub const IID_IADsPrintJob = &IID_IADsPrintJob_Value; pub const IADsPrintJob = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HostPrintQueue: fn( self: *const IADsPrintJob, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_User: fn( self: *const IADsPrintJob, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserPath: fn( self: *const IADsPrintJob, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TimeSubmitted: fn( self: *const IADsPrintJob, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TotalPages: fn( self: *const IADsPrintJob, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Size: fn( self: *const IADsPrintJob, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsPrintJob, retval: ?*?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 IADsPrintJob, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Priority: fn( self: *const IADsPrintJob, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Priority: fn( self: *const IADsPrintJob, lnPriority: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartTime: fn( self: *const IADsPrintJob, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StartTime: fn( self: *const IADsPrintJob, daStartTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UntilTime: fn( self: *const IADsPrintJob, retval: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_UntilTime: fn( self: *const IADsPrintJob, daUntilTime: f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Notify: fn( self: *const IADsPrintJob, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Notify: fn( self: *const IADsPrintJob, bstrNotify: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NotifyPath: fn( self: *const IADsPrintJob, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_NotifyPath: fn( self: *const IADsPrintJob, bstrNotifyPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_HostPrintQueue(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_HostPrintQueue(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_User(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_User(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_UserPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_UserPath(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_TimeSubmitted(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_TimeSubmitted(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_TotalPages(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_TotalPages(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_Size(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_Size(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_Description(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).put_Description(@ptrCast(*const IADsPrintJob, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_Priority(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_Priority(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_put_Priority(self: *const T, lnPriority: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).put_Priority(@ptrCast(*const IADsPrintJob, self), lnPriority); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_StartTime(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_StartTime(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_put_StartTime(self: *const T, daStartTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).put_StartTime(@ptrCast(*const IADsPrintJob, self), daStartTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_UntilTime(self: *const T, retval: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_UntilTime(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_put_UntilTime(self: *const T, daUntilTime: f64) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).put_UntilTime(@ptrCast(*const IADsPrintJob, self), daUntilTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_Notify(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_Notify(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_put_Notify(self: *const T, bstrNotify: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).put_Notify(@ptrCast(*const IADsPrintJob, self), bstrNotify); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_get_NotifyPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).get_NotifyPath(@ptrCast(*const IADsPrintJob, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJob_put_NotifyPath(self: *const T, bstrNotifyPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJob.VTable, self.vtable).put_NotifyPath(@ptrCast(*const IADsPrintJob, self), bstrNotifyPath); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPrintJobOperations_Value = @import("../zig.zig").Guid.initString("9a52db30-1ecf-11cf-a988-00aa006bc149"); pub const IID_IADsPrintJobOperations = &IID_IADsPrintJobOperations_Value; pub const IADsPrintJobOperations = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const IADsPrintJobOperations, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TimeElapsed: fn( self: *const IADsPrintJobOperations, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PagesPrinted: fn( self: *const IADsPrintJobOperations, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Position: fn( self: *const IADsPrintJobOperations, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Position: fn( self: *const IADsPrintJobOperations, lnPosition: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Pause: fn( self: *const IADsPrintJobOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Resume: fn( self: *const IADsPrintJobOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_get_Status(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).get_Status(@ptrCast(*const IADsPrintJobOperations, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_get_TimeElapsed(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).get_TimeElapsed(@ptrCast(*const IADsPrintJobOperations, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_get_PagesPrinted(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).get_PagesPrinted(@ptrCast(*const IADsPrintJobOperations, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_get_Position(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).get_Position(@ptrCast(*const IADsPrintJobOperations, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_put_Position(self: *const T, lnPosition: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).put_Position(@ptrCast(*const IADsPrintJobOperations, self), lnPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_Pause(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).Pause(@ptrCast(*const IADsPrintJobOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPrintJobOperations_Resume(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPrintJobOperations.VTable, self.vtable).Resume(@ptrCast(*const IADsPrintJobOperations, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsService_Value = @import("../zig.zig").Guid.initString("68af66e0-31ca-11cf-a98a-00aa006bc149"); pub const IID_IADsService = &IID_IADsService_Value; pub const IADsService = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HostComputer: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HostComputer: fn( self: *const IADsService, bstrHostComputer: ?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 IADsService, retval: ?*?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 IADsService, bstrDisplayName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Version: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Version: fn( self: *const IADsService, bstrVersion: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ServiceType: fn( self: *const IADsService, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ServiceType: fn( self: *const IADsService, lnServiceType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartType: fn( self: *const IADsService, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StartType: fn( self: *const IADsService, lnStartType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Path: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Path: fn( self: *const IADsService, bstrPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StartupParameters: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StartupParameters: fn( self: *const IADsService, bstrStartupParameters: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ErrorControl: fn( self: *const IADsService, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ErrorControl: fn( self: *const IADsService, lnErrorControl: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LoadOrderGroup: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LoadOrderGroup: fn( self: *const IADsService, bstrLoadOrderGroup: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ServiceAccountName: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ServiceAccountName: fn( self: *const IADsService, bstrServiceAccountName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ServiceAccountPath: fn( self: *const IADsService, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ServiceAccountPath: fn( self: *const IADsService, bstrServiceAccountPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Dependencies: fn( self: *const IADsService, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Dependencies: fn( self: *const IADsService, vDependencies: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_HostComputer(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_HostComputer(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_HostComputer(self: *const T, bstrHostComputer: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_HostComputer(@ptrCast(*const IADsService, self), bstrHostComputer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_DisplayName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_DisplayName(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_DisplayName(self: *const T, bstrDisplayName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_DisplayName(@ptrCast(*const IADsService, self), bstrDisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_Version(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_Version(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_Version(self: *const T, bstrVersion: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_Version(@ptrCast(*const IADsService, self), bstrVersion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_ServiceType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_ServiceType(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_ServiceType(self: *const T, lnServiceType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_ServiceType(@ptrCast(*const IADsService, self), lnServiceType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_StartType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_StartType(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_StartType(self: *const T, lnStartType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_StartType(@ptrCast(*const IADsService, self), lnStartType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_Path(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_Path(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_Path(self: *const T, bstrPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_Path(@ptrCast(*const IADsService, self), bstrPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_StartupParameters(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_StartupParameters(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_StartupParameters(self: *const T, bstrStartupParameters: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_StartupParameters(@ptrCast(*const IADsService, self), bstrStartupParameters); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_ErrorControl(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_ErrorControl(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_ErrorControl(self: *const T, lnErrorControl: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_ErrorControl(@ptrCast(*const IADsService, self), lnErrorControl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_LoadOrderGroup(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_LoadOrderGroup(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_LoadOrderGroup(self: *const T, bstrLoadOrderGroup: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_LoadOrderGroup(@ptrCast(*const IADsService, self), bstrLoadOrderGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_ServiceAccountName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_ServiceAccountName(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_ServiceAccountName(self: *const T, bstrServiceAccountName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_ServiceAccountName(@ptrCast(*const IADsService, self), bstrServiceAccountName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_ServiceAccountPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_ServiceAccountPath(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_ServiceAccountPath(self: *const T, bstrServiceAccountPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_ServiceAccountPath(@ptrCast(*const IADsService, self), bstrServiceAccountPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_get_Dependencies(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).get_Dependencies(@ptrCast(*const IADsService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsService_put_Dependencies(self: *const T, vDependencies: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsService.VTable, self.vtable).put_Dependencies(@ptrCast(*const IADsService, self), vDependencies); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsServiceOperations_Value = @import("../zig.zig").Guid.initString("5d7b33f0-31ca-11cf-a98a-00aa006bc149"); pub const IID_IADsServiceOperations = &IID_IADsServiceOperations_Value; pub const IADsServiceOperations = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const IADsServiceOperations, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Start: fn( self: *const IADsServiceOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IADsServiceOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Pause: fn( self: *const IADsServiceOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Continue: fn( self: *const IADsServiceOperations, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPassword: fn( self: *const IADsServiceOperations, bstrNewPassword: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsServiceOperations_get_Status(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsServiceOperations.VTable, self.vtable).get_Status(@ptrCast(*const IADsServiceOperations, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsServiceOperations_Start(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsServiceOperations.VTable, self.vtable).Start(@ptrCast(*const IADsServiceOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsServiceOperations_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsServiceOperations.VTable, self.vtable).Stop(@ptrCast(*const IADsServiceOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsServiceOperations_Pause(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsServiceOperations.VTable, self.vtable).Pause(@ptrCast(*const IADsServiceOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsServiceOperations_Continue(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsServiceOperations.VTable, self.vtable).Continue(@ptrCast(*const IADsServiceOperations, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsServiceOperations_SetPassword(self: *const T, bstrNewPassword: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsServiceOperations.VTable, self.vtable).SetPassword(@ptrCast(*const IADsServiceOperations, self), bstrNewPassword); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsFileService_Value = @import("../zig.zig").Guid.initString("a89d1900-31ca-11cf-a98a-00aa006bc149"); pub const IID_IADsFileService = &IID_IADsFileService_Value; pub const IADsFileService = extern struct { pub const VTable = extern struct { base: IADsService.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsFileService, retval: ?*?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 IADsFileService, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxUserCount: fn( self: *const IADsFileService, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxUserCount: fn( self: *const IADsFileService, lnMaxUserCount: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADsService.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileService_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileService.VTable, self.vtable).get_Description(@ptrCast(*const IADsFileService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileService_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileService.VTable, self.vtable).put_Description(@ptrCast(*const IADsFileService, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileService_get_MaxUserCount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileService.VTable, self.vtable).get_MaxUserCount(@ptrCast(*const IADsFileService, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileService_put_MaxUserCount(self: *const T, lnMaxUserCount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileService.VTable, self.vtable).put_MaxUserCount(@ptrCast(*const IADsFileService, self), lnMaxUserCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsFileServiceOperations_Value = @import("../zig.zig").Guid.initString("a02ded10-31ca-11cf-a98a-00aa006bc149"); pub const IID_IADsFileServiceOperations = &IID_IADsFileServiceOperations_Value; pub const IADsFileServiceOperations = extern struct { pub const VTable = extern struct { base: IADsServiceOperations.VTable, Sessions: fn( self: *const IADsFileServiceOperations, ppSessions: ?*?*IADsCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Resources: fn( self: *const IADsFileServiceOperations, ppResources: ?*?*IADsCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADsServiceOperations.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileServiceOperations_Sessions(self: *const T, ppSessions: ?*?*IADsCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileServiceOperations.VTable, self.vtable).Sessions(@ptrCast(*const IADsFileServiceOperations, self), ppSessions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileServiceOperations_Resources(self: *const T, ppResources: ?*?*IADsCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileServiceOperations.VTable, self.vtable).Resources(@ptrCast(*const IADsFileServiceOperations, self), ppResources); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsFileShare_Value = @import("../zig.zig").Guid.initString("eb6dcaf0-4b83-11cf-a995-00aa006bc149"); pub const IID_IADsFileShare = &IID_IADsFileShare_Value; pub const IADsFileShare = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CurrentUserCount: fn( self: *const IADsFileShare, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Description: fn( self: *const IADsFileShare, retval: ?*?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 IADsFileShare, bstrDescription: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HostComputer: fn( self: *const IADsFileShare, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HostComputer: fn( self: *const IADsFileShare, bstrHostComputer: ?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 IADsFileShare, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Path: fn( self: *const IADsFileShare, bstrPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MaxUserCount: fn( self: *const IADsFileShare, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MaxUserCount: fn( self: *const IADsFileShare, lnMaxUserCount: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_get_CurrentUserCount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).get_CurrentUserCount(@ptrCast(*const IADsFileShare, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_get_Description(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).get_Description(@ptrCast(*const IADsFileShare, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_put_Description(self: *const T, bstrDescription: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).put_Description(@ptrCast(*const IADsFileShare, self), bstrDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_get_HostComputer(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).get_HostComputer(@ptrCast(*const IADsFileShare, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_put_HostComputer(self: *const T, bstrHostComputer: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).put_HostComputer(@ptrCast(*const IADsFileShare, self), bstrHostComputer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_get_Path(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).get_Path(@ptrCast(*const IADsFileShare, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_put_Path(self: *const T, bstrPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).put_Path(@ptrCast(*const IADsFileShare, self), bstrPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_get_MaxUserCount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).get_MaxUserCount(@ptrCast(*const IADsFileShare, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFileShare_put_MaxUserCount(self: *const T, lnMaxUserCount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFileShare.VTable, self.vtable).put_MaxUserCount(@ptrCast(*const IADsFileShare, self), lnMaxUserCount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsSession_Value = @import("../zig.zig").Guid.initString("398b7da0-4aab-11cf-ae2c-00aa006ebfb9"); pub const IID_IADsSession = &IID_IADsSession_Value; pub const IADsSession = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_User: fn( self: *const IADsSession, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserPath: fn( self: *const IADsSession, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Computer: fn( self: *const IADsSession, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerPath: fn( self: *const IADsSession, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ConnectTime: fn( self: *const IADsSession, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IdleTime: fn( self: *const IADsSession, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSession_get_User(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSession.VTable, self.vtable).get_User(@ptrCast(*const IADsSession, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSession_get_UserPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSession.VTable, self.vtable).get_UserPath(@ptrCast(*const IADsSession, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSession_get_Computer(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSession.VTable, self.vtable).get_Computer(@ptrCast(*const IADsSession, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSession_get_ComputerPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSession.VTable, self.vtable).get_ComputerPath(@ptrCast(*const IADsSession, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSession_get_ConnectTime(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSession.VTable, self.vtable).get_ConnectTime(@ptrCast(*const IADsSession, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSession_get_IdleTime(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSession.VTable, self.vtable).get_IdleTime(@ptrCast(*const IADsSession, self), retval); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsResource_Value = @import("../zig.zig").Guid.initString("34a05b20-4aab-11cf-ae2c-00aa006ebfb9"); pub const IID_IADsResource = &IID_IADsResource_Value; pub const IADsResource = extern struct { pub const VTable = extern struct { base: IADs.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_User: fn( self: *const IADsResource, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserPath: fn( self: *const IADsResource, retval: ?*?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 IADsResource, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LockCount: fn( self: *const IADsResource, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IADs.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsResource_get_User(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsResource.VTable, self.vtable).get_User(@ptrCast(*const IADsResource, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsResource_get_UserPath(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsResource.VTable, self.vtable).get_UserPath(@ptrCast(*const IADsResource, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsResource_get_Path(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsResource.VTable, self.vtable).get_Path(@ptrCast(*const IADsResource, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsResource_get_LockCount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsResource.VTable, self.vtable).get_LockCount(@ptrCast(*const IADsResource, self), retval); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsOpenDSObject_Value = @import("../zig.zig").Guid.initString("ddf2891e-0f9c-11d0-8ad4-00c04fd8d503"); pub const IID_IADsOpenDSObject = &IID_IADsOpenDSObject_Value; pub const IADsOpenDSObject = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, OpenDSObject: fn( self: *const IADsOpenDSObject, lpszDNName: ?BSTR, lpszUserName: ?BSTR, lpszPassword: ?BSTR, lnReserved: i32, ppOleDsObj: ?*?*IDispatch, ) 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 IADsOpenDSObject_OpenDSObject(self: *const T, lpszDNName: ?BSTR, lpszUserName: ?BSTR, lpszPassword: ?BSTR, lnReserved: i32, ppOleDsObj: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOpenDSObject.VTable, self.vtable).OpenDSObject(@ptrCast(*const IADsOpenDSObject, self), lpszDNName, lpszUserName, lpszPassword, lnReserved, ppOleDsObj); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDirectoryObject_Value = @import("../zig.zig").Guid.initString("e798de2c-22e4-11d0-84fe-00c04fd8d503"); pub const IID_IDirectoryObject = &IID_IDirectoryObject_Value; pub const IDirectoryObject = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetObjectInformation: fn( self: *const IDirectoryObject, ppObjInfo: ?*?*ADS_OBJECT_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetObjectAttributes: fn( self: *const IDirectoryObject, pAttributeNames: ?*?PWSTR, dwNumberAttributes: u32, ppAttributeEntries: ?*?*ADS_ATTR_INFO, pdwNumAttributesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetObjectAttributes: fn( self: *const IDirectoryObject, pAttributeEntries: ?*ADS_ATTR_INFO, dwNumAttributes: u32, pdwNumAttributesModified: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDSObject: fn( self: *const IDirectoryObject, pszRDNName: ?PWSTR, pAttributeEntries: ?*ADS_ATTR_INFO, dwNumAttributes: u32, ppObject: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteDSObject: fn( self: *const IDirectoryObject, pszRDNName: ?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 IDirectoryObject_GetObjectInformation(self: *const T, ppObjInfo: ?*?*ADS_OBJECT_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectoryObject.VTable, self.vtable).GetObjectInformation(@ptrCast(*const IDirectoryObject, self), ppObjInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectoryObject_GetObjectAttributes(self: *const T, pAttributeNames: ?*?PWSTR, dwNumberAttributes: u32, ppAttributeEntries: ?*?*ADS_ATTR_INFO, pdwNumAttributesReturned: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectoryObject.VTable, self.vtable).GetObjectAttributes(@ptrCast(*const IDirectoryObject, self), pAttributeNames, dwNumberAttributes, ppAttributeEntries, pdwNumAttributesReturned); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectoryObject_SetObjectAttributes(self: *const T, pAttributeEntries: ?*ADS_ATTR_INFO, dwNumAttributes: u32, pdwNumAttributesModified: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectoryObject.VTable, self.vtable).SetObjectAttributes(@ptrCast(*const IDirectoryObject, self), pAttributeEntries, dwNumAttributes, pdwNumAttributesModified); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectoryObject_CreateDSObject(self: *const T, pszRDNName: ?PWSTR, pAttributeEntries: ?*ADS_ATTR_INFO, dwNumAttributes: u32, ppObject: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectoryObject.VTable, self.vtable).CreateDSObject(@ptrCast(*const IDirectoryObject, self), pszRDNName, pAttributeEntries, dwNumAttributes, ppObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectoryObject_DeleteDSObject(self: *const T, pszRDNName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectoryObject.VTable, self.vtable).DeleteDSObject(@ptrCast(*const IDirectoryObject, self), pszRDNName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDirectorySearch_Value = @import("../zig.zig").Guid.initString("109ba8ec-92f0-11d0-a790-00c04fd8d5a8"); pub const IID_IDirectorySearch = &IID_IDirectorySearch_Value; pub const IDirectorySearch = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetSearchPreference: fn( self: *const IDirectorySearch, pSearchPrefs: ?*ads_searchpref_info, dwNumPrefs: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ExecuteSearch: fn( self: *const IDirectorySearch, pszSearchFilter: ?PWSTR, pAttributeNames: ?*?PWSTR, dwNumberAttributes: u32, phSearchResult: ?*isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AbandonSearch: fn( self: *const IDirectorySearch, phSearchResult: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFirstRow: fn( self: *const IDirectorySearch, hSearchResult: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextRow: fn( self: *const IDirectorySearch, hSearchResult: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreviousRow: fn( self: *const IDirectorySearch, hSearchResult: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNextColumnName: fn( self: *const IDirectorySearch, hSearchHandle: isize, ppszColumnName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetColumn: fn( self: *const IDirectorySearch, hSearchResult: isize, szColumnName: ?PWSTR, pSearchColumn: ?*ads_search_column, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeColumn: fn( self: *const IDirectorySearch, pSearchColumn: ?*ads_search_column, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CloseSearchHandle: fn( self: *const IDirectorySearch, hSearchResult: isize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_SetSearchPreference(self: *const T, pSearchPrefs: ?*ads_searchpref_info, dwNumPrefs: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).SetSearchPreference(@ptrCast(*const IDirectorySearch, self), pSearchPrefs, dwNumPrefs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_ExecuteSearch(self: *const T, pszSearchFilter: ?PWSTR, pAttributeNames: ?*?PWSTR, dwNumberAttributes: u32, phSearchResult: ?*isize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).ExecuteSearch(@ptrCast(*const IDirectorySearch, self), pszSearchFilter, pAttributeNames, dwNumberAttributes, phSearchResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_AbandonSearch(self: *const T, phSearchResult: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).AbandonSearch(@ptrCast(*const IDirectorySearch, self), phSearchResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_GetFirstRow(self: *const T, hSearchResult: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).GetFirstRow(@ptrCast(*const IDirectorySearch, self), hSearchResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_GetNextRow(self: *const T, hSearchResult: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).GetNextRow(@ptrCast(*const IDirectorySearch, self), hSearchResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_GetPreviousRow(self: *const T, hSearchResult: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).GetPreviousRow(@ptrCast(*const IDirectorySearch, self), hSearchResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_GetNextColumnName(self: *const T, hSearchHandle: isize, ppszColumnName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).GetNextColumnName(@ptrCast(*const IDirectorySearch, self), hSearchHandle, ppszColumnName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_GetColumn(self: *const T, hSearchResult: isize, szColumnName: ?PWSTR, pSearchColumn: ?*ads_search_column) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).GetColumn(@ptrCast(*const IDirectorySearch, self), hSearchResult, szColumnName, pSearchColumn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_FreeColumn(self: *const T, pSearchColumn: ?*ads_search_column) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).FreeColumn(@ptrCast(*const IDirectorySearch, self), pSearchColumn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySearch_CloseSearchHandle(self: *const T, hSearchResult: isize) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySearch.VTable, self.vtable).CloseSearchHandle(@ptrCast(*const IDirectorySearch, self), hSearchResult); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDirectorySchemaMgmt_Value = @import("../zig.zig").Guid.initString("75db3b9c-a4d8-11d0-a79c-00c04fd8d5a8"); pub const IID_IDirectorySchemaMgmt = &IID_IDirectorySchemaMgmt_Value; pub const IDirectorySchemaMgmt = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnumAttributes: fn( self: *const IDirectorySchemaMgmt, ppszAttrNames: ?*?PWSTR, dwNumAttributes: u32, ppAttrDefinition: ?*?*ADS_ATTR_DEF, pdwNumAttributes: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateAttributeDefinition: fn( self: *const IDirectorySchemaMgmt, pszAttributeName: ?PWSTR, pAttributeDefinition: ?*ADS_ATTR_DEF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteAttributeDefinition: fn( self: *const IDirectorySchemaMgmt, pszAttributeName: ?PWSTR, pAttributeDefinition: ?*ADS_ATTR_DEF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteAttributeDefinition: fn( self: *const IDirectorySchemaMgmt, pszAttributeName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumClasses: fn( self: *const IDirectorySchemaMgmt, ppszClassNames: ?*?PWSTR, dwNumClasses: u32, ppClassDefinition: ?*?*ADS_CLASS_DEF, pdwNumClasses: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteClassDefinition: fn( self: *const IDirectorySchemaMgmt, pszClassName: ?PWSTR, pClassDefinition: ?*ADS_CLASS_DEF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateClassDefinition: fn( self: *const IDirectorySchemaMgmt, pszClassName: ?PWSTR, pClassDefinition: ?*ADS_CLASS_DEF, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteClassDefinition: fn( self: *const IDirectorySchemaMgmt, pszClassName: ?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 IDirectorySchemaMgmt_EnumAttributes(self: *const T, ppszAttrNames: ?*?PWSTR, dwNumAttributes: u32, ppAttrDefinition: ?*?*ADS_ATTR_DEF, pdwNumAttributes: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).EnumAttributes(@ptrCast(*const IDirectorySchemaMgmt, self), ppszAttrNames, dwNumAttributes, ppAttrDefinition, pdwNumAttributes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_CreateAttributeDefinition(self: *const T, pszAttributeName: ?PWSTR, pAttributeDefinition: ?*ADS_ATTR_DEF) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).CreateAttributeDefinition(@ptrCast(*const IDirectorySchemaMgmt, self), pszAttributeName, pAttributeDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_WriteAttributeDefinition(self: *const T, pszAttributeName: ?PWSTR, pAttributeDefinition: ?*ADS_ATTR_DEF) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).WriteAttributeDefinition(@ptrCast(*const IDirectorySchemaMgmt, self), pszAttributeName, pAttributeDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_DeleteAttributeDefinition(self: *const T, pszAttributeName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).DeleteAttributeDefinition(@ptrCast(*const IDirectorySchemaMgmt, self), pszAttributeName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_EnumClasses(self: *const T, ppszClassNames: ?*?PWSTR, dwNumClasses: u32, ppClassDefinition: ?*?*ADS_CLASS_DEF, pdwNumClasses: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).EnumClasses(@ptrCast(*const IDirectorySchemaMgmt, self), ppszClassNames, dwNumClasses, ppClassDefinition, pdwNumClasses); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_WriteClassDefinition(self: *const T, pszClassName: ?PWSTR, pClassDefinition: ?*ADS_CLASS_DEF) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).WriteClassDefinition(@ptrCast(*const IDirectorySchemaMgmt, self), pszClassName, pClassDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_CreateClassDefinition(self: *const T, pszClassName: ?PWSTR, pClassDefinition: ?*ADS_CLASS_DEF) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).CreateClassDefinition(@ptrCast(*const IDirectorySchemaMgmt, self), pszClassName, pClassDefinition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectorySchemaMgmt_DeleteClassDefinition(self: *const T, pszClassName: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectorySchemaMgmt.VTable, self.vtable).DeleteClassDefinition(@ptrCast(*const IDirectorySchemaMgmt, self), pszClassName); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IADsAggregatee_Value = @import("../zig.zig").Guid.initString("1346ce8c-9039-11d0-8528-00c04fd8d503"); pub const IID_IADsAggregatee = &IID_IADsAggregatee_Value; pub const IADsAggregatee = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ConnectAsAggregatee: fn( self: *const IADsAggregatee, pOuterUnknown: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisconnectAsAggregatee: fn( self: *const IADsAggregatee, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RelinquishInterface: fn( self: *const IADsAggregatee, riid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreInterface: fn( self: *const IADsAggregatee, riid: ?*const 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 IADsAggregatee_ConnectAsAggregatee(self: *const T, pOuterUnknown: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAggregatee.VTable, self.vtable).ConnectAsAggregatee(@ptrCast(*const IADsAggregatee, self), pOuterUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAggregatee_DisconnectAsAggregatee(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAggregatee.VTable, self.vtable).DisconnectAsAggregatee(@ptrCast(*const IADsAggregatee, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAggregatee_RelinquishInterface(self: *const T, riid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAggregatee.VTable, self.vtable).RelinquishInterface(@ptrCast(*const IADsAggregatee, self), riid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAggregatee_RestoreInterface(self: *const T, riid: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAggregatee.VTable, self.vtable).RestoreInterface(@ptrCast(*const IADsAggregatee, self), riid); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IADsAggregator_Value = @import("../zig.zig").Guid.initString("52db5fb0-941f-11d0-8529-00c04fd8d503"); pub const IID_IADsAggregator = &IID_IADsAggregator_Value; pub const IADsAggregator = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ConnectAsAggregator: fn( self: *const IADsAggregator, pAggregatee: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisconnectAsAggregator: fn( self: *const IADsAggregator, ) 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 IADsAggregator_ConnectAsAggregator(self: *const T, pAggregatee: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAggregator.VTable, self.vtable).ConnectAsAggregator(@ptrCast(*const IADsAggregator, self), pAggregatee); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAggregator_DisconnectAsAggregator(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAggregator.VTable, self.vtable).DisconnectAsAggregator(@ptrCast(*const IADsAggregator, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsAccessControlEntry_Value = @import("../zig.zig").Guid.initString("b4f3a14c-9bdd-11d0-852c-00c04fd8d503"); pub const IID_IADsAccessControlEntry = &IID_IADsAccessControlEntry_Value; pub const IADsAccessControlEntry = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AccessMask: fn( self: *const IADsAccessControlEntry, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AccessMask: fn( self: *const IADsAccessControlEntry, lnAccessMask: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AceType: fn( self: *const IADsAccessControlEntry, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AceType: fn( self: *const IADsAccessControlEntry, lnAceType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AceFlags: fn( self: *const IADsAccessControlEntry, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AceFlags: fn( self: *const IADsAccessControlEntry, lnAceFlags: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Flags: fn( self: *const IADsAccessControlEntry, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Flags: fn( self: *const IADsAccessControlEntry, lnFlags: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectType: fn( self: *const IADsAccessControlEntry, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ObjectType: fn( self: *const IADsAccessControlEntry, bstrObjectType: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InheritedObjectType: fn( self: *const IADsAccessControlEntry, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InheritedObjectType: fn( self: *const IADsAccessControlEntry, bstrInheritedObjectType: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Trustee: fn( self: *const IADsAccessControlEntry, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Trustee: fn( self: *const IADsAccessControlEntry, 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 IADsAccessControlEntry_get_AccessMask(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_AccessMask(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_AccessMask(self: *const T, lnAccessMask: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_AccessMask(@ptrCast(*const IADsAccessControlEntry, self), lnAccessMask); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_get_AceType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_AceType(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_AceType(self: *const T, lnAceType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_AceType(@ptrCast(*const IADsAccessControlEntry, self), lnAceType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_get_AceFlags(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_AceFlags(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_AceFlags(self: *const T, lnAceFlags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_AceFlags(@ptrCast(*const IADsAccessControlEntry, self), lnAceFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_get_Flags(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_Flags(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_Flags(self: *const T, lnFlags: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_Flags(@ptrCast(*const IADsAccessControlEntry, self), lnFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_get_ObjectType(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_ObjectType(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_ObjectType(self: *const T, bstrObjectType: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_ObjectType(@ptrCast(*const IADsAccessControlEntry, self), bstrObjectType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_get_InheritedObjectType(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_InheritedObjectType(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_InheritedObjectType(self: *const T, bstrInheritedObjectType: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_InheritedObjectType(@ptrCast(*const IADsAccessControlEntry, self), bstrInheritedObjectType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_get_Trustee(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).get_Trustee(@ptrCast(*const IADsAccessControlEntry, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlEntry_put_Trustee(self: *const T, bstrTrustee: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlEntry.VTable, self.vtable).put_Trustee(@ptrCast(*const IADsAccessControlEntry, self), bstrTrustee); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsAccessControlList_Value = @import("../zig.zig").Guid.initString("b7ee91cc-9bdd-11d0-852c-00c04fd8d503"); pub const IID_IADsAccessControlList = &IID_IADsAccessControlList_Value; pub const IADsAccessControlList = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AclRevision: fn( self: *const IADsAccessControlList, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AclRevision: fn( self: *const IADsAccessControlList, lnAclRevision: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AceCount: fn( self: *const IADsAccessControlList, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AceCount: fn( self: *const IADsAccessControlList, lnAceCount: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddAce: fn( self: *const IADsAccessControlList, pAccessControlEntry: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveAce: fn( self: *const IADsAccessControlList, pAccessControlEntry: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyAccessList: fn( self: *const IADsAccessControlList, ppAccessControlList: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IADsAccessControlList, retval: ?*?*IUnknown, ) 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 IADsAccessControlList_get_AclRevision(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).get_AclRevision(@ptrCast(*const IADsAccessControlList, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_put_AclRevision(self: *const T, lnAclRevision: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).put_AclRevision(@ptrCast(*const IADsAccessControlList, self), lnAclRevision); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_get_AceCount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).get_AceCount(@ptrCast(*const IADsAccessControlList, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_put_AceCount(self: *const T, lnAceCount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).put_AceCount(@ptrCast(*const IADsAccessControlList, self), lnAceCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_AddAce(self: *const T, pAccessControlEntry: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).AddAce(@ptrCast(*const IADsAccessControlList, self), pAccessControlEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_RemoveAce(self: *const T, pAccessControlEntry: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).RemoveAce(@ptrCast(*const IADsAccessControlList, self), pAccessControlEntry); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_CopyAccessList(self: *const T, ppAccessControlList: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).CopyAccessList(@ptrCast(*const IADsAccessControlList, self), ppAccessControlList); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAccessControlList_get__NewEnum(self: *const T, retval: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAccessControlList.VTable, self.vtable).get__NewEnum(@ptrCast(*const IADsAccessControlList, self), retval); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsSecurityDescriptor_Value = @import("../zig.zig").Guid.initString("b8c787ca-9bdd-11d0-852c-00c04fd8d503"); pub const IID_IADsSecurityDescriptor = &IID_IADsSecurityDescriptor_Value; pub const IADsSecurityDescriptor = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Revision: fn( self: *const IADsSecurityDescriptor, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Revision: fn( self: *const IADsSecurityDescriptor, lnRevision: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Control: fn( self: *const IADsSecurityDescriptor, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Control: fn( self: *const IADsSecurityDescriptor, lnControl: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Owner: fn( self: *const IADsSecurityDescriptor, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Owner: fn( self: *const IADsSecurityDescriptor, bstrOwner: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OwnerDefaulted: fn( self: *const IADsSecurityDescriptor, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OwnerDefaulted: fn( self: *const IADsSecurityDescriptor, fOwnerDefaulted: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Group: fn( self: *const IADsSecurityDescriptor, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Group: fn( self: *const IADsSecurityDescriptor, bstrGroup: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_GroupDefaulted: fn( self: *const IADsSecurityDescriptor, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_GroupDefaulted: fn( self: *const IADsSecurityDescriptor, fGroupDefaulted: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DiscretionaryAcl: fn( self: *const IADsSecurityDescriptor, retval: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DiscretionaryAcl: fn( self: *const IADsSecurityDescriptor, pDiscretionaryAcl: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DaclDefaulted: fn( self: *const IADsSecurityDescriptor, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DaclDefaulted: fn( self: *const IADsSecurityDescriptor, fDaclDefaulted: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SystemAcl: fn( self: *const IADsSecurityDescriptor, retval: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SystemAcl: fn( self: *const IADsSecurityDescriptor, pSystemAcl: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SaclDefaulted: fn( self: *const IADsSecurityDescriptor, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SaclDefaulted: fn( self: *const IADsSecurityDescriptor, fSaclDefaulted: i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopySecurityDescriptor: fn( self: *const IADsSecurityDescriptor, ppSecurityDescriptor: ?*?*IDispatch, ) 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 IADsSecurityDescriptor_get_Revision(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_Revision(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_Revision(self: *const T, lnRevision: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_Revision(@ptrCast(*const IADsSecurityDescriptor, self), lnRevision); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_Control(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_Control(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_Control(self: *const T, lnControl: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_Control(@ptrCast(*const IADsSecurityDescriptor, self), lnControl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_Owner(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_Owner(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_Owner(self: *const T, bstrOwner: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_Owner(@ptrCast(*const IADsSecurityDescriptor, self), bstrOwner); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_OwnerDefaulted(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_OwnerDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_OwnerDefaulted(self: *const T, fOwnerDefaulted: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_OwnerDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), fOwnerDefaulted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_Group(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_Group(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_Group(self: *const T, bstrGroup: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_Group(@ptrCast(*const IADsSecurityDescriptor, self), bstrGroup); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_GroupDefaulted(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_GroupDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_GroupDefaulted(self: *const T, fGroupDefaulted: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_GroupDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), fGroupDefaulted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_DiscretionaryAcl(self: *const T, retval: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_DiscretionaryAcl(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_DiscretionaryAcl(self: *const T, pDiscretionaryAcl: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_DiscretionaryAcl(@ptrCast(*const IADsSecurityDescriptor, self), pDiscretionaryAcl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_DaclDefaulted(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_DaclDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_DaclDefaulted(self: *const T, fDaclDefaulted: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_DaclDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), fDaclDefaulted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_SystemAcl(self: *const T, retval: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_SystemAcl(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_SystemAcl(self: *const T, pSystemAcl: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_SystemAcl(@ptrCast(*const IADsSecurityDescriptor, self), pSystemAcl); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_get_SaclDefaulted(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).get_SaclDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_put_SaclDefaulted(self: *const T, fSaclDefaulted: i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).put_SaclDefaulted(@ptrCast(*const IADsSecurityDescriptor, self), fSaclDefaulted); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityDescriptor_CopySecurityDescriptor(self: *const T, ppSecurityDescriptor: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityDescriptor.VTable, self.vtable).CopySecurityDescriptor(@ptrCast(*const IADsSecurityDescriptor, self), ppSecurityDescriptor); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsLargeInteger_Value = @import("../zig.zig").Guid.initString("9068270b-0939-11d1-8be1-00c04fd8d503"); pub const IID_IADsLargeInteger = &IID_IADsLargeInteger_Value; pub const IADsLargeInteger = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HighPart: fn( self: *const IADsLargeInteger, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_HighPart: fn( self: *const IADsLargeInteger, lnHighPart: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_LowPart: fn( self: *const IADsLargeInteger, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_LowPart: fn( self: *const IADsLargeInteger, lnLowPart: 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 IADsLargeInteger_get_HighPart(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLargeInteger.VTable, self.vtable).get_HighPart(@ptrCast(*const IADsLargeInteger, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLargeInteger_put_HighPart(self: *const T, lnHighPart: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLargeInteger.VTable, self.vtable).put_HighPart(@ptrCast(*const IADsLargeInteger, self), lnHighPart); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLargeInteger_get_LowPart(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLargeInteger.VTable, self.vtable).get_LowPart(@ptrCast(*const IADsLargeInteger, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsLargeInteger_put_LowPart(self: *const T, lnLowPart: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsLargeInteger.VTable, self.vtable).put_LowPart(@ptrCast(*const IADsLargeInteger, self), lnLowPart); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsNameTranslate_Value = @import("../zig.zig").Guid.initString("b1b272a3-3625-11d1-a3a4-00c04fb950dc"); pub const IID_IADsNameTranslate = &IID_IADsNameTranslate_Value; pub const IADsNameTranslate = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ChaseReferral: fn( self: *const IADsNameTranslate, lnChaseReferral: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Init: fn( self: *const IADsNameTranslate, lnSetType: i32, bstrADsPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InitEx: fn( self: *const IADsNameTranslate, lnSetType: i32, bstrADsPath: ?BSTR, bstrUserID: ?BSTR, bstrDomain: ?BSTR, bstrPassword: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Set: fn( self: *const IADsNameTranslate, lnSetType: i32, bstrADsPath: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Get: fn( self: *const IADsNameTranslate, lnFormatType: i32, pbstrADsPath: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEx: fn( self: *const IADsNameTranslate, lnFormatType: i32, pvar: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEx: fn( self: *const IADsNameTranslate, lnFormatType: i32, pvar: ?*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 IADsNameTranslate_put_ChaseReferral(self: *const T, lnChaseReferral: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).put_ChaseReferral(@ptrCast(*const IADsNameTranslate, self), lnChaseReferral); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNameTranslate_Init(self: *const T, lnSetType: i32, bstrADsPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).Init(@ptrCast(*const IADsNameTranslate, self), lnSetType, bstrADsPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNameTranslate_InitEx(self: *const T, lnSetType: i32, bstrADsPath: ?BSTR, bstrUserID: ?BSTR, bstrDomain: ?BSTR, bstrPassword: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).InitEx(@ptrCast(*const IADsNameTranslate, self), lnSetType, bstrADsPath, bstrUserID, bstrDomain, bstrPassword); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNameTranslate_Set(self: *const T, lnSetType: i32, bstrADsPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).Set(@ptrCast(*const IADsNameTranslate, self), lnSetType, bstrADsPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNameTranslate_Get(self: *const T, lnFormatType: i32, pbstrADsPath: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).Get(@ptrCast(*const IADsNameTranslate, self), lnFormatType, pbstrADsPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNameTranslate_SetEx(self: *const T, lnFormatType: i32, pvar: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).SetEx(@ptrCast(*const IADsNameTranslate, self), lnFormatType, pvar); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNameTranslate_GetEx(self: *const T, lnFormatType: i32, pvar: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNameTranslate.VTable, self.vtable).GetEx(@ptrCast(*const IADsNameTranslate, self), lnFormatType, pvar); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsCaseIgnoreList_Value = @import("../zig.zig").Guid.initString("7b66b533-4680-11d1-a3b4-00c04fb950dc"); pub const IID_IADsCaseIgnoreList = &IID_IADsCaseIgnoreList_Value; pub const IADsCaseIgnoreList = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_CaseIgnoreList: fn( self: *const IADsCaseIgnoreList, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_CaseIgnoreList: fn( self: *const IADsCaseIgnoreList, vCaseIgnoreList: 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 IADsCaseIgnoreList_get_CaseIgnoreList(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsCaseIgnoreList.VTable, self.vtable).get_CaseIgnoreList(@ptrCast(*const IADsCaseIgnoreList, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsCaseIgnoreList_put_CaseIgnoreList(self: *const T, vCaseIgnoreList: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsCaseIgnoreList.VTable, self.vtable).put_CaseIgnoreList(@ptrCast(*const IADsCaseIgnoreList, self), vCaseIgnoreList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsFaxNumber_Value = @import("../zig.zig").Guid.initString("a910dea9-4680-11d1-a3b4-00c04fb950dc"); pub const IID_IADsFaxNumber = &IID_IADsFaxNumber_Value; pub const IADsFaxNumber = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TelephoneNumber: fn( self: *const IADsFaxNumber, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_TelephoneNumber: fn( self: *const IADsFaxNumber, bstrTelephoneNumber: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Parameters: fn( self: *const IADsFaxNumber, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Parameters: fn( self: *const IADsFaxNumber, vParameters: 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 IADsFaxNumber_get_TelephoneNumber(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFaxNumber.VTable, self.vtable).get_TelephoneNumber(@ptrCast(*const IADsFaxNumber, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFaxNumber_put_TelephoneNumber(self: *const T, bstrTelephoneNumber: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFaxNumber.VTable, self.vtable).put_TelephoneNumber(@ptrCast(*const IADsFaxNumber, self), bstrTelephoneNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFaxNumber_get_Parameters(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFaxNumber.VTable, self.vtable).get_Parameters(@ptrCast(*const IADsFaxNumber, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsFaxNumber_put_Parameters(self: *const T, vParameters: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsFaxNumber.VTable, self.vtable).put_Parameters(@ptrCast(*const IADsFaxNumber, self), vParameters); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsNetAddress_Value = @import("../zig.zig").Guid.initString("b21a50a9-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsNetAddress = &IID_IADsNetAddress_Value; pub const IADsNetAddress = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_AddressType: fn( self: *const IADsNetAddress, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_AddressType: fn( self: *const IADsNetAddress, lnAddressType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Address: fn( self: *const IADsNetAddress, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Address: fn( self: *const IADsNetAddress, vAddress: 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 IADsNetAddress_get_AddressType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNetAddress.VTable, self.vtable).get_AddressType(@ptrCast(*const IADsNetAddress, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNetAddress_put_AddressType(self: *const T, lnAddressType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNetAddress.VTable, self.vtable).put_AddressType(@ptrCast(*const IADsNetAddress, self), lnAddressType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNetAddress_get_Address(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNetAddress.VTable, self.vtable).get_Address(@ptrCast(*const IADsNetAddress, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsNetAddress_put_Address(self: *const T, vAddress: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsNetAddress.VTable, self.vtable).put_Address(@ptrCast(*const IADsNetAddress, self), vAddress); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsOctetList_Value = @import("../zig.zig").Guid.initString("7b28b80f-4680-11d1-a3b4-00c04fb950dc"); pub const IID_IADsOctetList = &IID_IADsOctetList_Value; pub const IADsOctetList = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OctetList: fn( self: *const IADsOctetList, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_OctetList: fn( self: *const IADsOctetList, vOctetList: 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 IADsOctetList_get_OctetList(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOctetList.VTable, self.vtable).get_OctetList(@ptrCast(*const IADsOctetList, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsOctetList_put_OctetList(self: *const T, vOctetList: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsOctetList.VTable, self.vtable).put_OctetList(@ptrCast(*const IADsOctetList, self), vOctetList); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsEmail_Value = @import("../zig.zig").Guid.initString("97af011a-478e-11d1-a3b4-00c04fb950dc"); pub const IID_IADsEmail = &IID_IADsEmail_Value; pub const IADsEmail = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Type: fn( self: *const IADsEmail, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Type: fn( self: *const IADsEmail, lnType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Address: fn( self: *const IADsEmail, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Address: fn( self: *const IADsEmail, bstrAddress: ?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 IADsEmail_get_Type(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsEmail.VTable, self.vtable).get_Type(@ptrCast(*const IADsEmail, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsEmail_put_Type(self: *const T, lnType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsEmail.VTable, self.vtable).put_Type(@ptrCast(*const IADsEmail, self), lnType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsEmail_get_Address(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsEmail.VTable, self.vtable).get_Address(@ptrCast(*const IADsEmail, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsEmail_put_Address(self: *const T, bstrAddress: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsEmail.VTable, self.vtable).put_Address(@ptrCast(*const IADsEmail, self), bstrAddress); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPath_Value = @import("../zig.zig").Guid.initString("b287fcd5-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsPath = &IID_IADsPath_Value; pub const IADsPath = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Type: fn( self: *const IADsPath, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Type: fn( self: *const IADsPath, lnType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_VolumeName: fn( self: *const IADsPath, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_VolumeName: fn( self: *const IADsPath, bstrVolumeName: ?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 IADsPath, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Path: fn( self: *const IADsPath, bstrPath: ?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 IADsPath_get_Type(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPath.VTable, self.vtable).get_Type(@ptrCast(*const IADsPath, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPath_put_Type(self: *const T, lnType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPath.VTable, self.vtable).put_Type(@ptrCast(*const IADsPath, self), lnType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPath_get_VolumeName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPath.VTable, self.vtable).get_VolumeName(@ptrCast(*const IADsPath, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPath_put_VolumeName(self: *const T, bstrVolumeName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPath.VTable, self.vtable).put_VolumeName(@ptrCast(*const IADsPath, self), bstrVolumeName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPath_get_Path(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPath.VTable, self.vtable).get_Path(@ptrCast(*const IADsPath, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPath_put_Path(self: *const T, bstrPath: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPath.VTable, self.vtable).put_Path(@ptrCast(*const IADsPath, self), bstrPath); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsReplicaPointer_Value = @import("../zig.zig").Guid.initString("f60fb803-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsReplicaPointer = &IID_IADsReplicaPointer_Value; pub const IADsReplicaPointer = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ServerName: fn( self: *const IADsReplicaPointer, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ServerName: fn( self: *const IADsReplicaPointer, bstrServerName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReplicaType: fn( self: *const IADsReplicaPointer, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReplicaType: fn( self: *const IADsReplicaPointer, lnReplicaType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReplicaNumber: fn( self: *const IADsReplicaPointer, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReplicaNumber: fn( self: *const IADsReplicaPointer, lnReplicaNumber: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IADsReplicaPointer, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Count: fn( self: *const IADsReplicaPointer, lnCount: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReplicaAddressHints: fn( self: *const IADsReplicaPointer, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ReplicaAddressHints: fn( self: *const IADsReplicaPointer, vReplicaAddressHints: 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 IADsReplicaPointer_get_ServerName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).get_ServerName(@ptrCast(*const IADsReplicaPointer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_put_ServerName(self: *const T, bstrServerName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).put_ServerName(@ptrCast(*const IADsReplicaPointer, self), bstrServerName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_get_ReplicaType(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).get_ReplicaType(@ptrCast(*const IADsReplicaPointer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_put_ReplicaType(self: *const T, lnReplicaType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).put_ReplicaType(@ptrCast(*const IADsReplicaPointer, self), lnReplicaType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_get_ReplicaNumber(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).get_ReplicaNumber(@ptrCast(*const IADsReplicaPointer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_put_ReplicaNumber(self: *const T, lnReplicaNumber: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).put_ReplicaNumber(@ptrCast(*const IADsReplicaPointer, self), lnReplicaNumber); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_get_Count(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).get_Count(@ptrCast(*const IADsReplicaPointer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_put_Count(self: *const T, lnCount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).put_Count(@ptrCast(*const IADsReplicaPointer, self), lnCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_get_ReplicaAddressHints(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).get_ReplicaAddressHints(@ptrCast(*const IADsReplicaPointer, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsReplicaPointer_put_ReplicaAddressHints(self: *const T, vReplicaAddressHints: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsReplicaPointer.VTable, self.vtable).put_ReplicaAddressHints(@ptrCast(*const IADsReplicaPointer, self), vReplicaAddressHints); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsAcl_Value = @import("../zig.zig").Guid.initString("8452d3ab-0869-11d1-a377-00c04fb950dc"); pub const IID_IADsAcl = &IID_IADsAcl_Value; pub const IADsAcl = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ProtectedAttrName: fn( self: *const IADsAcl, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ProtectedAttrName: fn( self: *const IADsAcl, bstrProtectedAttrName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubjectName: fn( self: *const IADsAcl, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SubjectName: fn( self: *const IADsAcl, bstrSubjectName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Privileges: fn( self: *const IADsAcl, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Privileges: fn( self: *const IADsAcl, lnPrivileges: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyAcl: fn( self: *const IADsAcl, ppAcl: ?*?*IDispatch, ) 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 IADsAcl_get_ProtectedAttrName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).get_ProtectedAttrName(@ptrCast(*const IADsAcl, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAcl_put_ProtectedAttrName(self: *const T, bstrProtectedAttrName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).put_ProtectedAttrName(@ptrCast(*const IADsAcl, self), bstrProtectedAttrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAcl_get_SubjectName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).get_SubjectName(@ptrCast(*const IADsAcl, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAcl_put_SubjectName(self: *const T, bstrSubjectName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).put_SubjectName(@ptrCast(*const IADsAcl, self), bstrSubjectName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAcl_get_Privileges(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).get_Privileges(@ptrCast(*const IADsAcl, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAcl_put_Privileges(self: *const T, lnPrivileges: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).put_Privileges(@ptrCast(*const IADsAcl, self), lnPrivileges); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsAcl_CopyAcl(self: *const T, ppAcl: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsAcl.VTable, self.vtable).CopyAcl(@ptrCast(*const IADsAcl, self), ppAcl); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsTimestamp_Value = @import("../zig.zig").Guid.initString("b2f5a901-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsTimestamp = &IID_IADsTimestamp_Value; pub const IADsTimestamp = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_WholeSeconds: fn( self: *const IADsTimestamp, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_WholeSeconds: fn( self: *const IADsTimestamp, lnWholeSeconds: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EventID: fn( self: *const IADsTimestamp, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EventID: fn( self: *const IADsTimestamp, lnEventID: 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 IADsTimestamp_get_WholeSeconds(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTimestamp.VTable, self.vtable).get_WholeSeconds(@ptrCast(*const IADsTimestamp, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTimestamp_put_WholeSeconds(self: *const T, lnWholeSeconds: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTimestamp.VTable, self.vtable).put_WholeSeconds(@ptrCast(*const IADsTimestamp, self), lnWholeSeconds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTimestamp_get_EventID(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTimestamp.VTable, self.vtable).get_EventID(@ptrCast(*const IADsTimestamp, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTimestamp_put_EventID(self: *const T, lnEventID: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTimestamp.VTable, self.vtable).put_EventID(@ptrCast(*const IADsTimestamp, self), lnEventID); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPostalAddress_Value = @import("../zig.zig").Guid.initString("7adecf29-4680-11d1-a3b4-00c04fb950dc"); pub const IID_IADsPostalAddress = &IID_IADsPostalAddress_Value; pub const IADsPostalAddress = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PostalAddress: fn( self: *const IADsPostalAddress, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PostalAddress: fn( self: *const IADsPostalAddress, vPostalAddress: 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 IADsPostalAddress_get_PostalAddress(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPostalAddress.VTable, self.vtable).get_PostalAddress(@ptrCast(*const IADsPostalAddress, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPostalAddress_put_PostalAddress(self: *const T, vPostalAddress: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPostalAddress.VTable, self.vtable).put_PostalAddress(@ptrCast(*const IADsPostalAddress, self), vPostalAddress); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsBackLink_Value = @import("../zig.zig").Guid.initString("fd1302bd-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsBackLink = &IID_IADsBackLink_Value; pub const IADsBackLink = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RemoteID: fn( self: *const IADsBackLink, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_RemoteID: fn( self: *const IADsBackLink, lnRemoteID: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectName: fn( self: *const IADsBackLink, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ObjectName: fn( self: *const IADsBackLink, bstrObjectName: ?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 IADsBackLink_get_RemoteID(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsBackLink.VTable, self.vtable).get_RemoteID(@ptrCast(*const IADsBackLink, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsBackLink_put_RemoteID(self: *const T, lnRemoteID: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsBackLink.VTable, self.vtable).put_RemoteID(@ptrCast(*const IADsBackLink, self), lnRemoteID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsBackLink_get_ObjectName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsBackLink.VTable, self.vtable).get_ObjectName(@ptrCast(*const IADsBackLink, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsBackLink_put_ObjectName(self: *const T, bstrObjectName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsBackLink.VTable, self.vtable).put_ObjectName(@ptrCast(*const IADsBackLink, self), bstrObjectName); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsTypedName_Value = @import("../zig.zig").Guid.initString("b371a349-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsTypedName = &IID_IADsTypedName_Value; pub const IADsTypedName = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectName: fn( self: *const IADsTypedName, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ObjectName: fn( self: *const IADsTypedName, bstrObjectName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Level: fn( self: *const IADsTypedName, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Level: fn( self: *const IADsTypedName, lnLevel: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Interval: fn( self: *const IADsTypedName, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Interval: fn( self: *const IADsTypedName, lnInterval: 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 IADsTypedName_get_ObjectName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTypedName.VTable, self.vtable).get_ObjectName(@ptrCast(*const IADsTypedName, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTypedName_put_ObjectName(self: *const T, bstrObjectName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTypedName.VTable, self.vtable).put_ObjectName(@ptrCast(*const IADsTypedName, self), bstrObjectName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTypedName_get_Level(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTypedName.VTable, self.vtable).get_Level(@ptrCast(*const IADsTypedName, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTypedName_put_Level(self: *const T, lnLevel: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTypedName.VTable, self.vtable).put_Level(@ptrCast(*const IADsTypedName, self), lnLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTypedName_get_Interval(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTypedName.VTable, self.vtable).get_Interval(@ptrCast(*const IADsTypedName, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsTypedName_put_Interval(self: *const T, lnInterval: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsTypedName.VTable, self.vtable).put_Interval(@ptrCast(*const IADsTypedName, self), lnInterval); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsHold_Value = @import("../zig.zig").Guid.initString("b3eb3b37-4080-11d1-a3ac-00c04fb950dc"); pub const IID_IADsHold = &IID_IADsHold_Value; pub const IADsHold = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ObjectName: fn( self: *const IADsHold, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ObjectName: fn( self: *const IADsHold, bstrObjectName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Amount: fn( self: *const IADsHold, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Amount: fn( self: *const IADsHold, lnAmount: 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 IADsHold_get_ObjectName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsHold.VTable, self.vtable).get_ObjectName(@ptrCast(*const IADsHold, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsHold_put_ObjectName(self: *const T, bstrObjectName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsHold.VTable, self.vtable).put_ObjectName(@ptrCast(*const IADsHold, self), bstrObjectName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsHold_get_Amount(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsHold.VTable, self.vtable).get_Amount(@ptrCast(*const IADsHold, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsHold_put_Amount(self: *const T, lnAmount: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsHold.VTable, self.vtable).put_Amount(@ptrCast(*const IADsHold, self), lnAmount); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsObjectOptions_Value = @import("../zig.zig").Guid.initString("46f14fda-232b-11d1-a808-00c04fd8d5a8"); pub const IID_IADsObjectOptions = &IID_IADsObjectOptions_Value; pub const IADsObjectOptions = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetOption: fn( self: *const IADsObjectOptions, lnOption: i32, pvValue: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOption: fn( self: *const IADsObjectOptions, lnOption: i32, vValue: 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 IADsObjectOptions_GetOption(self: *const T, lnOption: i32, pvValue: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsObjectOptions.VTable, self.vtable).GetOption(@ptrCast(*const IADsObjectOptions, self), lnOption, pvValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsObjectOptions_SetOption(self: *const T, lnOption: i32, vValue: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsObjectOptions.VTable, self.vtable).SetOption(@ptrCast(*const IADsObjectOptions, self), lnOption, vValue); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsPathname_Value = @import("../zig.zig").Guid.initString("d592aed4-f420-11d0-a36e-00c04fb950dc"); pub const IID_IADsPathname = &IID_IADsPathname_Value; pub const IADsPathname = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Set: fn( self: *const IADsPathname, bstrADsPath: ?BSTR, lnSetType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayType: fn( self: *const IADsPathname, lnDisplayType: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Retrieve: fn( self: *const IADsPathname, lnFormatType: i32, pbstrADsPath: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNumElements: fn( self: *const IADsPathname, plnNumPathElements: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetElement: fn( self: *const IADsPathname, lnElementIndex: i32, pbstrElement: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddLeafElement: fn( self: *const IADsPathname, bstrLeafElement: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveLeafElement: fn( self: *const IADsPathname, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CopyPath: fn( self: *const IADsPathname, ppAdsPath: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEscapedElement: fn( self: *const IADsPathname, lnReserved: i32, bstrInStr: ?BSTR, pbstrOutStr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_EscapedMode: fn( self: *const IADsPathname, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_EscapedMode: fn( self: *const IADsPathname, lnEscapedMode: 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 IADsPathname_Set(self: *const T, bstrADsPath: ?BSTR, lnSetType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).Set(@ptrCast(*const IADsPathname, self), bstrADsPath, lnSetType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_SetDisplayType(self: *const T, lnDisplayType: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).SetDisplayType(@ptrCast(*const IADsPathname, self), lnDisplayType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_Retrieve(self: *const T, lnFormatType: i32, pbstrADsPath: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).Retrieve(@ptrCast(*const IADsPathname, self), lnFormatType, pbstrADsPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_GetNumElements(self: *const T, plnNumPathElements: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).GetNumElements(@ptrCast(*const IADsPathname, self), plnNumPathElements); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_GetElement(self: *const T, lnElementIndex: i32, pbstrElement: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).GetElement(@ptrCast(*const IADsPathname, self), lnElementIndex, pbstrElement); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_AddLeafElement(self: *const T, bstrLeafElement: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).AddLeafElement(@ptrCast(*const IADsPathname, self), bstrLeafElement); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_RemoveLeafElement(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).RemoveLeafElement(@ptrCast(*const IADsPathname, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_CopyPath(self: *const T, ppAdsPath: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).CopyPath(@ptrCast(*const IADsPathname, self), ppAdsPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_GetEscapedElement(self: *const T, lnReserved: i32, bstrInStr: ?BSTR, pbstrOutStr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).GetEscapedElement(@ptrCast(*const IADsPathname, self), lnReserved, bstrInStr, pbstrOutStr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_get_EscapedMode(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).get_EscapedMode(@ptrCast(*const IADsPathname, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsPathname_put_EscapedMode(self: *const T, lnEscapedMode: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsPathname.VTable, self.vtable).put_EscapedMode(@ptrCast(*const IADsPathname, self), lnEscapedMode); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsADSystemInfo_Value = @import("../zig.zig").Guid.initString("5bb11929-afd1-11d2-9cb9-0000f87a369e"); pub const IID_IADsADSystemInfo = &IID_IADsADSystemInfo_Value; pub const IADsADSystemInfo = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserName: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerName: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SiteName: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DomainShortName: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DomainDNSName: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ForestDNSName: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PDCRoleOwner: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SchemaRoleOwner: fn( self: *const IADsADSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_IsNativeMode: fn( self: *const IADsADSystemInfo, retval: ?*i16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAnyDCName: fn( self: *const IADsADSystemInfo, pszDCName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDCSiteName: fn( self: *const IADsADSystemInfo, szServer: ?BSTR, pszSiteName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RefreshSchemaCache: fn( self: *const IADsADSystemInfo, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetTrees: fn( self: *const IADsADSystemInfo, pvTrees: ?*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 IADsADSystemInfo_get_UserName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_UserName(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_ComputerName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_ComputerName(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_SiteName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_SiteName(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_DomainShortName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_DomainShortName(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_DomainDNSName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_DomainDNSName(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_ForestDNSName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_ForestDNSName(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_PDCRoleOwner(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_PDCRoleOwner(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_SchemaRoleOwner(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_SchemaRoleOwner(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_get_IsNativeMode(self: *const T, retval: ?*i16) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).get_IsNativeMode(@ptrCast(*const IADsADSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_GetAnyDCName(self: *const T, pszDCName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).GetAnyDCName(@ptrCast(*const IADsADSystemInfo, self), pszDCName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_GetDCSiteName(self: *const T, szServer: ?BSTR, pszSiteName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).GetDCSiteName(@ptrCast(*const IADsADSystemInfo, self), szServer, pszSiteName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_RefreshSchemaCache(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).RefreshSchemaCache(@ptrCast(*const IADsADSystemInfo, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsADSystemInfo_GetTrees(self: *const T, pvTrees: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsADSystemInfo.VTable, self.vtable).GetTrees(@ptrCast(*const IADsADSystemInfo, self), pvTrees); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsWinNTSystemInfo_Value = @import("../zig.zig").Guid.initString("6c6d65dc-afd1-11d2-9cb9-0000f87a369e"); pub const IID_IADsWinNTSystemInfo = &IID_IADsWinNTSystemInfo_Value; pub const IADsWinNTSystemInfo = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserName: fn( self: *const IADsWinNTSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ComputerName: fn( self: *const IADsWinNTSystemInfo, retval: ?*?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 IADsWinNTSystemInfo, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PDC: fn( self: *const IADsWinNTSystemInfo, retval: ?*?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 IADsWinNTSystemInfo_get_UserName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsWinNTSystemInfo.VTable, self.vtable).get_UserName(@ptrCast(*const IADsWinNTSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsWinNTSystemInfo_get_ComputerName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsWinNTSystemInfo.VTable, self.vtable).get_ComputerName(@ptrCast(*const IADsWinNTSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsWinNTSystemInfo_get_DomainName(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsWinNTSystemInfo.VTable, self.vtable).get_DomainName(@ptrCast(*const IADsWinNTSystemInfo, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsWinNTSystemInfo_get_PDC(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsWinNTSystemInfo.VTable, self.vtable).get_PDC(@ptrCast(*const IADsWinNTSystemInfo, self), retval); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsDNWithBinary_Value = @import("../zig.zig").Guid.initString("7e99c0a2-f935-11d2-ba96-00c04fb6d0d1"); pub const IID_IADsDNWithBinary = &IID_IADsDNWithBinary_Value; pub const IADsDNWithBinary = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BinaryValue: fn( self: *const IADsDNWithBinary, retval: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BinaryValue: fn( self: *const IADsDNWithBinary, vBinaryValue: VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DNString: fn( self: *const IADsDNWithBinary, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DNString: fn( self: *const IADsDNWithBinary, bstrDNString: ?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 IADsDNWithBinary_get_BinaryValue(self: *const T, retval: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithBinary.VTable, self.vtable).get_BinaryValue(@ptrCast(*const IADsDNWithBinary, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDNWithBinary_put_BinaryValue(self: *const T, vBinaryValue: VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithBinary.VTable, self.vtable).put_BinaryValue(@ptrCast(*const IADsDNWithBinary, self), vBinaryValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDNWithBinary_get_DNString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithBinary.VTable, self.vtable).get_DNString(@ptrCast(*const IADsDNWithBinary, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDNWithBinary_put_DNString(self: *const T, bstrDNString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithBinary.VTable, self.vtable).put_DNString(@ptrCast(*const IADsDNWithBinary, self), bstrDNString); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsDNWithString_Value = @import("../zig.zig").Guid.initString("370df02e-f934-11d2-ba96-00c04fb6d0d1"); pub const IID_IADsDNWithString = &IID_IADsDNWithString_Value; pub const IADsDNWithString = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_StringValue: fn( self: *const IADsDNWithString, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_StringValue: fn( self: *const IADsDNWithString, bstrStringValue: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DNString: fn( self: *const IADsDNWithString, retval: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DNString: fn( self: *const IADsDNWithString, bstrDNString: ?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 IADsDNWithString_get_StringValue(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithString.VTable, self.vtable).get_StringValue(@ptrCast(*const IADsDNWithString, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDNWithString_put_StringValue(self: *const T, bstrStringValue: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithString.VTable, self.vtable).put_StringValue(@ptrCast(*const IADsDNWithString, self), bstrStringValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDNWithString_get_DNString(self: *const T, retval: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithString.VTable, self.vtable).get_DNString(@ptrCast(*const IADsDNWithString, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsDNWithString_put_DNString(self: *const T, bstrDNString: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IADsDNWithString.VTable, self.vtable).put_DNString(@ptrCast(*const IADsDNWithString, self), bstrDNString); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IADsSecurityUtility_Value = @import("../zig.zig").Guid.initString("a63251b2-5f21-474b-ab52-4a8efad10895"); pub const IID_IADsSecurityUtility = &IID_IADsSecurityUtility_Value; pub const IADsSecurityUtility = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetSecurityDescriptor: fn( self: *const IADsSecurityUtility, varPath: VARIANT, lPathFormat: i32, lFormat: i32, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSecurityDescriptor: fn( self: *const IADsSecurityUtility, varPath: VARIANT, lPathFormat: i32, varData: VARIANT, lDataFormat: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConvertSecurityDescriptor: fn( self: *const IADsSecurityUtility, varSD: VARIANT, lDataFormat: i32, lOutFormat: i32, pResult: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SecurityMask: fn( self: *const IADsSecurityUtility, retval: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SecurityMask: fn( self: *const IADsSecurityUtility, lnSecurityMask: 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 IADsSecurityUtility_GetSecurityDescriptor(self: *const T, varPath: VARIANT, lPathFormat: i32, lFormat: i32, pVariant: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityUtility.VTable, self.vtable).GetSecurityDescriptor(@ptrCast(*const IADsSecurityUtility, self), varPath, lPathFormat, lFormat, pVariant); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityUtility_SetSecurityDescriptor(self: *const T, varPath: VARIANT, lPathFormat: i32, varData: VARIANT, lDataFormat: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityUtility.VTable, self.vtable).SetSecurityDescriptor(@ptrCast(*const IADsSecurityUtility, self), varPath, lPathFormat, varData, lDataFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityUtility_ConvertSecurityDescriptor(self: *const T, varSD: VARIANT, lDataFormat: i32, lOutFormat: i32, pResult: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityUtility.VTable, self.vtable).ConvertSecurityDescriptor(@ptrCast(*const IADsSecurityUtility, self), varSD, lDataFormat, lOutFormat, pResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityUtility_get_SecurityMask(self: *const T, retval: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityUtility.VTable, self.vtable).get_SecurityMask(@ptrCast(*const IADsSecurityUtility, self), retval); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IADsSecurityUtility_put_SecurityMask(self: *const T, lnSecurityMask: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IADsSecurityUtility.VTable, self.vtable).put_SecurityMask(@ptrCast(*const IADsSecurityUtility, self), lnSecurityMask); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSOBJECT = extern struct { dwFlags: u32, dwProviderFlags: u32, offsetName: u32, offsetClass: u32, }; pub const DSOBJECTNAMES = extern struct { clsidNamespace: Guid, cItems: u32, aObjects: [1]DSOBJECT, }; pub const DSDISPLAYSPECOPTIONS = extern struct { dwSize: u32, dwFlags: u32, offsetAttribPrefix: u32, offsetUserName: u32, offsetPassword: u32, offsetServer: u32, offsetServerConfigPath: u32, }; pub const DSPROPERTYPAGEINFO = extern struct { offsetString: u32, }; pub const DOMAINDESC = extern struct { pszName: ?PWSTR, pszPath: ?PWSTR, pszNCName: ?PWSTR, pszTrustParent: ?PWSTR, pszObjectClass: ?PWSTR, ulFlags: u32, fDownLevel: BOOL, pdChildList: ?*DOMAINDESC, pdNextSibling: ?*DOMAINDESC, }; pub const DOMAIN_TREE = extern struct { dsSize: u32, dwCount: u32, aDomains: [1]DOMAINDESC, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsBrowseDomainTree_Value = @import("../zig.zig").Guid.initString("7cabcf1e-78f5-11d2-960c-00c04fa31a86"); pub const IID_IDsBrowseDomainTree = &IID_IDsBrowseDomainTree_Value; pub const IDsBrowseDomainTree = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, BrowseTo: fn( self: *const IDsBrowseDomainTree, hwndParent: ?HWND, ppszTargetPath: ?*?PWSTR, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDomains: fn( self: *const IDsBrowseDomainTree, ppDomainTree: ?*?*DOMAIN_TREE, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FreeDomains: fn( self: *const IDsBrowseDomainTree, ppDomainTree: ?*?*DOMAIN_TREE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FlushCachedDomains: fn( self: *const IDsBrowseDomainTree, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetComputer: fn( self: *const IDsBrowseDomainTree, pszComputerName: ?[*:0]const u16, pszUserName: ?[*:0]const u16, pszPassword: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsBrowseDomainTree_BrowseTo(self: *const T, hwndParent: ?HWND, ppszTargetPath: ?*?PWSTR, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsBrowseDomainTree.VTable, self.vtable).BrowseTo(@ptrCast(*const IDsBrowseDomainTree, self), hwndParent, ppszTargetPath, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsBrowseDomainTree_GetDomains(self: *const T, ppDomainTree: ?*?*DOMAIN_TREE, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsBrowseDomainTree.VTable, self.vtable).GetDomains(@ptrCast(*const IDsBrowseDomainTree, self), ppDomainTree, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsBrowseDomainTree_FreeDomains(self: *const T, ppDomainTree: ?*?*DOMAIN_TREE) callconv(.Inline) HRESULT { return @ptrCast(*const IDsBrowseDomainTree.VTable, self.vtable).FreeDomains(@ptrCast(*const IDsBrowseDomainTree, self), ppDomainTree); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsBrowseDomainTree_FlushCachedDomains(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDsBrowseDomainTree.VTable, self.vtable).FlushCachedDomains(@ptrCast(*const IDsBrowseDomainTree, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsBrowseDomainTree_SetComputer(self: *const T, pszComputerName: ?[*:0]const u16, pszUserName: ?[*:0]const u16, pszPassword: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDsBrowseDomainTree.VTable, self.vtable).SetComputer(@ptrCast(*const IDsBrowseDomainTree, self), pszComputerName, pszUserName, pszPassword); } };} pub usingnamespace MethodMixin(@This()); }; pub const LPDSENUMATTRIBUTES = fn( lParam: LPARAM, pszAttributeName: ?[*:0]const u16, pszDisplayName: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const DSCLASSCREATIONINFO = extern struct { dwFlags: u32, clsidWizardDialog: Guid, clsidWizardPrimaryPage: Guid, cWizardExtensions: u32, aWizardExtensions: [1]Guid, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsDisplaySpecifier_Value = @import("../zig.zig").Guid.initString("1ab4a8c0-6a0b-11d2-ad49-00c04fa31a86"); pub const IID_IDsDisplaySpecifier = &IID_IDsDisplaySpecifier_Value; pub const IDsDisplaySpecifier = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetServer: fn( self: *const IDsDisplaySpecifier, pszServer: ?[*:0]const u16, pszUserName: ?[*:0]const u16, pszPassword: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetLanguageID: fn( self: *const IDsDisplaySpecifier, langid: u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDisplaySpecifier: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIconLocation: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, dwFlags: u32, pszBuffer: [*:0]u16, cchBuffer: i32, presid: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIcon: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, dwFlags: u32, cxIcon: i32, cyIcon: i32, ) callconv(@import("std").os.windows.WINAPI) ?HICON, GetFriendlyClassName: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, pszBuffer: [*:0]u16, cchBuffer: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFriendlyAttributeName: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, pszAttributeName: ?[*:0]const u16, pszBuffer: [*:0]u16, cchBuffer: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsClassContainer: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, pszADsPath: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL, GetClassCreationInfo: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, ppdscci: ?*?*DSCLASSCREATIONINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumClassAttributes: fn( self: *const IDsDisplaySpecifier, pszObjectClass: ?[*:0]const u16, pcbEnum: ?LPDSENUMATTRIBUTES, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAttributeADsType: fn( self: *const IDsDisplaySpecifier, pszAttributeName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) ADSTYPEENUM, }; 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 IDsDisplaySpecifier_SetServer(self: *const T, pszServer: ?[*:0]const u16, pszUserName: ?[*:0]const u16, pszPassword: ?[*:0]const u16, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).SetServer(@ptrCast(*const IDsDisplaySpecifier, self), pszServer, pszUserName, pszPassword, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_SetLanguageID(self: *const T, langid: u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).SetLanguageID(@ptrCast(*const IDsDisplaySpecifier, self), langid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetDisplaySpecifier(self: *const T, pszObjectClass: ?[*:0]const u16, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetDisplaySpecifier(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, riid, ppv); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetIconLocation(self: *const T, pszObjectClass: ?[*:0]const u16, dwFlags: u32, pszBuffer: [*:0]u16, cchBuffer: i32, presid: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetIconLocation(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, dwFlags, pszBuffer, cchBuffer, presid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetIcon(self: *const T, pszObjectClass: ?[*:0]const u16, dwFlags: u32, cxIcon: i32, cyIcon: i32) callconv(.Inline) ?HICON { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetIcon(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, dwFlags, cxIcon, cyIcon); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetFriendlyClassName(self: *const T, pszObjectClass: ?[*:0]const u16, pszBuffer: [*:0]u16, cchBuffer: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetFriendlyClassName(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, pszBuffer, cchBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetFriendlyAttributeName(self: *const T, pszObjectClass: ?[*:0]const u16, pszAttributeName: ?[*:0]const u16, pszBuffer: [*:0]u16, cchBuffer: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetFriendlyAttributeName(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, pszAttributeName, pszBuffer, cchBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_IsClassContainer(self: *const T, pszObjectClass: ?[*:0]const u16, pszADsPath: ?[*:0]const u16, dwFlags: u32) callconv(.Inline) BOOL { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).IsClassContainer(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, pszADsPath, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetClassCreationInfo(self: *const T, pszObjectClass: ?[*:0]const u16, ppdscci: ?*?*DSCLASSCREATIONINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetClassCreationInfo(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, ppdscci); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_EnumClassAttributes(self: *const T, pszObjectClass: ?[*:0]const u16, pcbEnum: ?LPDSENUMATTRIBUTES, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).EnumClassAttributes(@ptrCast(*const IDsDisplaySpecifier, self), pszObjectClass, pcbEnum, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsDisplaySpecifier_GetAttributeADsType(self: *const T, pszAttributeName: ?[*:0]const u16) callconv(.Inline) ADSTYPEENUM { return @ptrCast(*const IDsDisplaySpecifier.VTable, self.vtable).GetAttributeADsType(@ptrCast(*const IDsDisplaySpecifier, self), pszAttributeName); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSBROWSEINFOW = extern struct { cbStruct: u32, hwndOwner: ?HWND, pszCaption: ?[*:0]const u16, pszTitle: ?[*:0]const u16, pszRoot: ?[*:0]const u16, pszPath: ?PWSTR, cchPath: u32, dwFlags: u32, pfnCallback: ?BFFCALLBACK, lParam: LPARAM, dwReturnFormat: u32, pUserName: ?[*:0]const u16, pPassword: ?[*:0]const u16, pszObjectClass: ?PWSTR, cchObjectClass: u32, }; pub const DSBROWSEINFOA = extern struct { cbStruct: u32, hwndOwner: ?HWND, pszCaption: ?[*:0]const u8, pszTitle: ?[*:0]const u8, pszRoot: ?[*:0]const u16, pszPath: ?PWSTR, cchPath: u32, dwFlags: u32, pfnCallback: ?BFFCALLBACK, lParam: LPARAM, dwReturnFormat: u32, pUserName: ?[*:0]const u16, pPassword: ?[*:0]const u16, pszObjectClass: ?PWSTR, cchObjectClass: u32, }; pub const DSBITEMW = extern struct { cbStruct: u32, pszADsPath: ?[*:0]const u16, pszClass: ?[*:0]const u16, dwMask: u32, dwState: u32, dwStateMask: u32, szDisplayName: [64]u16, szIconLocation: [260]u16, iIconResID: i32, }; pub const DSBITEMA = extern struct { cbStruct: u32, pszADsPath: ?[*:0]const u16, pszClass: ?[*:0]const u16, dwMask: u32, dwState: u32, dwStateMask: u32, szDisplayName: [64]CHAR, szIconLocation: [260]CHAR, iIconResID: i32, }; pub const DSOP_UPLEVEL_FILTER_FLAGS = extern struct { flBothModes: u32, flMixedModeOnly: u32, flNativeModeOnly: u32, }; pub const DSOP_FILTER_FLAGS = extern struct { Uplevel: DSOP_UPLEVEL_FILTER_FLAGS, flDownlevel: u32, }; pub const DSOP_SCOPE_INIT_INFO = extern struct { cbSize: u32, flType: u32, flScope: u32, FilterFlags: DSOP_FILTER_FLAGS, pwzDcName: ?[*:0]const u16, pwzADsPath: ?[*:0]const u16, hr: HRESULT, }; pub const DSOP_INIT_INFO = extern struct { cbSize: u32, pwzTargetComputer: ?[*:0]const u16, cDsScopeInfos: u32, aDsScopeInfos: ?*DSOP_SCOPE_INIT_INFO, flOptions: u32, cAttributesToFetch: u32, apwzAttributeNames: ?*?PWSTR, }; pub const DS_SELECTION = extern struct { pwzName: ?PWSTR, pwzADsPath: ?PWSTR, pwzClass: ?PWSTR, pwzUPN: ?PWSTR, pvarFetchedAttributes: ?*VARIANT, flScopeType: u32, }; pub const DS_SELECTION_LIST = extern struct { cItems: u32, cFetchedAttributes: u32, aDsSelection: [1]DS_SELECTION, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsObjectPicker_Value = @import("../zig.zig").Guid.initString("0c87e64e-3b7a-11d2-b9e0-00c04fd8dbf7"); pub const IID_IDsObjectPicker = &IID_IDsObjectPicker_Value; pub const IDsObjectPicker = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDsObjectPicker, pInitInfo: ?*DSOP_INIT_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvokeDialog: fn( self: *const IDsObjectPicker, hwndParent: ?HWND, ppdoSelections: ?*?*IDataObject, ) 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 IDsObjectPicker_Initialize(self: *const T, pInitInfo: ?*DSOP_INIT_INFO) callconv(.Inline) HRESULT { return @ptrCast(*const IDsObjectPicker.VTable, self.vtable).Initialize(@ptrCast(*const IDsObjectPicker, self), pInitInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsObjectPicker_InvokeDialog(self: *const T, hwndParent: ?HWND, ppdoSelections: ?*?*IDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IDsObjectPicker.VTable, self.vtable).InvokeDialog(@ptrCast(*const IDsObjectPicker, self), hwndParent, ppdoSelections); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windowsServer2008' const IID_IDsObjectPickerCredentials_Value = @import("../zig.zig").Guid.initString("e2d3ec9b-d041-445a-8f16-4748de8fb1cf"); pub const IID_IDsObjectPickerCredentials = &IID_IDsObjectPickerCredentials_Value; pub const IDsObjectPickerCredentials = extern struct { pub const VTable = extern struct { base: IDsObjectPicker.VTable, SetCredentials: fn( self: *const IDsObjectPickerCredentials, szUserName: ?[*:0]const u16, szPassword: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDsObjectPicker.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsObjectPickerCredentials_SetCredentials(self: *const T, szUserName: ?[*:0]const u16, szPassword: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDsObjectPickerCredentials.VTable, self.vtable).SetCredentials(@ptrCast(*const IDsObjectPickerCredentials, self), szUserName, szPassword); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSQUERYINITPARAMS = extern struct { cbStruct: u32, dwFlags: u32, pDefaultScope: ?PWSTR, pDefaultSaveLocation: ?PWSTR, pUserName: ?PWSTR, pPassword: ?PWSTR, pServer: ?PWSTR, }; pub const DSCOLUMN = extern struct { dwFlags: u32, fmt: i32, cx: i32, idsName: i32, offsetProperty: i32, dwReserved: u32, }; pub const DSQUERYPARAMS = extern struct { cbStruct: u32, dwFlags: u32, hInstance: ?HINSTANCE, offsetQuery: i32, iColumns: i32, dwReserved: u32, aColumns: [1]DSCOLUMN, }; pub const DSQUERYCLASSLIST = extern struct { cbStruct: u32, cClasses: i32, offsetClass: [1]u32, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsAdminCreateObj_Value = @import("../zig.zig").Guid.initString("53554a38-f902-11d2-82b9-00c04f68928b"); pub const IID_IDsAdminCreateObj = &IID_IDsAdminCreateObj_Value; pub const IDsAdminCreateObj = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDsAdminCreateObj, pADsContainerObj: ?*IADsContainer, pADsCopySource: ?*IADs, lpszClassName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateModal: fn( self: *const IDsAdminCreateObj, hwndParent: ?HWND, ppADsObj: ?*?*IADs, ) 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 IDsAdminCreateObj_Initialize(self: *const T, pADsContainerObj: ?*IADsContainer, pADsCopySource: ?*IADs, lpszClassName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminCreateObj.VTable, self.vtable).Initialize(@ptrCast(*const IDsAdminCreateObj, self), pADsContainerObj, pADsCopySource, lpszClassName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminCreateObj_CreateModal(self: *const T, hwndParent: ?HWND, ppADsObj: ?*?*IADs) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminCreateObj.VTable, self.vtable).CreateModal(@ptrCast(*const IDsAdminCreateObj, self), hwndParent, ppADsObj); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsAdminNewObj_Value = @import("../zig.zig").Guid.initString("f2573587-e6fc-11d2-82af-00c04f68928b"); pub const IID_IDsAdminNewObj = &IID_IDsAdminNewObj_Value; pub const IDsAdminNewObj = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetButtons: fn( self: *const IDsAdminNewObj, nCurrIndex: u32, bValid: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPageCounts: fn( self: *const IDsAdminNewObj, pnTotal: ?*i32, pnStartIndex: ?*i32, ) 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 IDsAdminNewObj_SetButtons(self: *const T, nCurrIndex: u32, bValid: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObj.VTable, self.vtable).SetButtons(@ptrCast(*const IDsAdminNewObj, self), nCurrIndex, bValid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObj_GetPageCounts(self: *const T, pnTotal: ?*i32, pnStartIndex: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObj.VTable, self.vtable).GetPageCounts(@ptrCast(*const IDsAdminNewObj, self), pnTotal, pnStartIndex); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsAdminNewObjPrimarySite_Value = @import("../zig.zig").Guid.initString("be2b487e-f904-11d2-82b9-00c04f68928b"); pub const IID_IDsAdminNewObjPrimarySite = &IID_IDsAdminNewObjPrimarySite_Value; pub const IDsAdminNewObjPrimarySite = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateNew: fn( self: *const IDsAdminNewObjPrimarySite, pszName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Commit: fn( self: *const IDsAdminNewObjPrimarySite, ) 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 IDsAdminNewObjPrimarySite_CreateNew(self: *const T, pszName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjPrimarySite.VTable, self.vtable).CreateNew(@ptrCast(*const IDsAdminNewObjPrimarySite, self), pszName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObjPrimarySite_Commit(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjPrimarySite.VTable, self.vtable).Commit(@ptrCast(*const IDsAdminNewObjPrimarySite, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSA_NEWOBJ_DISPINFO = extern struct { dwSize: u32, hObjClassIcon: ?HICON, lpszWizTitle: ?PWSTR, lpszContDisplayName: ?PWSTR, }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsAdminNewObjExt_Value = @import("../zig.zig").Guid.initString("6088eae2-e7bf-11d2-82af-00c04f68928b"); pub const IID_IDsAdminNewObjExt = &IID_IDsAdminNewObjExt_Value; pub const IDsAdminNewObjExt = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDsAdminNewObjExt, pADsContainerObj: ?*IADsContainer, pADsCopySource: ?*IADs, lpszClassName: ?[*:0]const u16, pDsAdminNewObj: ?*IDsAdminNewObj, pDispInfo: ?*DSA_NEWOBJ_DISPINFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddPages: fn( self: *const IDsAdminNewObjExt, lpfnAddPage: ?LPFNSVADDPROPSHEETPAGE, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetObject: fn( self: *const IDsAdminNewObjExt, pADsObj: ?*IADs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WriteData: fn( self: *const IDsAdminNewObjExt, hWnd: ?HWND, uContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnError: fn( self: *const IDsAdminNewObjExt, hWnd: ?HWND, hr: HRESULT, uContext: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSummaryInfo: fn( self: *const IDsAdminNewObjExt, pBstrText: ?*?BSTR, ) 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 IDsAdminNewObjExt_Initialize(self: *const T, pADsContainerObj: ?*IADsContainer, pADsCopySource: ?*IADs, lpszClassName: ?[*:0]const u16, pDsAdminNewObj: ?*IDsAdminNewObj, pDispInfo: ?*DSA_NEWOBJ_DISPINFO) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjExt.VTable, self.vtable).Initialize(@ptrCast(*const IDsAdminNewObjExt, self), pADsContainerObj, pADsCopySource, lpszClassName, pDsAdminNewObj, pDispInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObjExt_AddPages(self: *const T, lpfnAddPage: ?LPFNSVADDPROPSHEETPAGE, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjExt.VTable, self.vtable).AddPages(@ptrCast(*const IDsAdminNewObjExt, self), lpfnAddPage, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObjExt_SetObject(self: *const T, pADsObj: ?*IADs) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjExt.VTable, self.vtable).SetObject(@ptrCast(*const IDsAdminNewObjExt, self), pADsObj); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObjExt_WriteData(self: *const T, hWnd: ?HWND, uContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjExt.VTable, self.vtable).WriteData(@ptrCast(*const IDsAdminNewObjExt, self), hWnd, uContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObjExt_OnError(self: *const T, hWnd: ?HWND, hr: HRESULT, uContext: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjExt.VTable, self.vtable).OnError(@ptrCast(*const IDsAdminNewObjExt, self), hWnd, hr, uContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNewObjExt_GetSummaryInfo(self: *const T, pBstrText: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNewObjExt.VTable, self.vtable).GetSummaryInfo(@ptrCast(*const IDsAdminNewObjExt, self), pBstrText); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDsAdminNotifyHandler_Value = @import("../zig.zig").Guid.initString("e4a2b8b3-5a18-11d2-97c1-00a0c9a06d2d"); pub const IID_IDsAdminNotifyHandler = &IID_IDsAdminNotifyHandler_Value; pub const IDsAdminNotifyHandler = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDsAdminNotifyHandler, pExtraInfo: ?*IDataObject, puEventFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Begin: fn( self: *const IDsAdminNotifyHandler, uEvent: u32, pArg1: ?*IDataObject, pArg2: ?*IDataObject, puFlags: ?*u32, pBstr: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Notify: fn( self: *const IDsAdminNotifyHandler, nItem: u32, uFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, End: fn( self: *const IDsAdminNotifyHandler, ) 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 IDsAdminNotifyHandler_Initialize(self: *const T, pExtraInfo: ?*IDataObject, puEventFlags: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNotifyHandler.VTable, self.vtable).Initialize(@ptrCast(*const IDsAdminNotifyHandler, self), pExtraInfo, puEventFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNotifyHandler_Begin(self: *const T, uEvent: u32, pArg1: ?*IDataObject, pArg2: ?*IDataObject, puFlags: ?*u32, pBstr: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNotifyHandler.VTable, self.vtable).Begin(@ptrCast(*const IDsAdminNotifyHandler, self), uEvent, pArg1, pArg2, puFlags, pBstr); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNotifyHandler_Notify(self: *const T, nItem: u32, uFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNotifyHandler.VTable, self.vtable).Notify(@ptrCast(*const IDsAdminNotifyHandler, self), nItem, uFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDsAdminNotifyHandler_End(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDsAdminNotifyHandler.VTable, self.vtable).End(@ptrCast(*const IDsAdminNotifyHandler, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const ADSPROPINITPARAMS = extern struct { dwSize: u32, dwFlags: u32, hr: HRESULT, pDsObj: ?*IDirectoryObject, pwzCN: ?PWSTR, pWritableAttrs: ?*ADS_ATTR_INFO, }; pub const ADSPROPERROR = extern struct { hwndPage: ?HWND, pszPageTitle: ?PWSTR, pszObjPath: ?PWSTR, pszObjClass: ?PWSTR, hr: HRESULT, pszError: ?PWSTR, }; pub const SCHEDULE_HEADER = extern struct { Type: u32, Offset: u32, }; pub const SCHEDULE = extern struct { Size: u32, Bandwidth: u32, NumberOfSchedules: u32, Schedules: [1]SCHEDULE_HEADER, }; pub const DS_MANGLE_FOR = enum(i32) { UNKNOWN = 0, OBJECT_RDN_FOR_DELETION = 1, OBJECT_RDN_FOR_NAME_CONFLICT = 2, }; pub const DS_MANGLE_UNKNOWN = DS_MANGLE_FOR.UNKNOWN; pub const DS_MANGLE_OBJECT_RDN_FOR_DELETION = DS_MANGLE_FOR.OBJECT_RDN_FOR_DELETION; pub const DS_MANGLE_OBJECT_RDN_FOR_NAME_CONFLICT = DS_MANGLE_FOR.OBJECT_RDN_FOR_NAME_CONFLICT; pub const DS_NAME_FORMAT = enum(i32) { UNKNOWN_NAME = 0, FQDN_1779_NAME = 1, NT4_ACCOUNT_NAME = 2, DISPLAY_NAME = 3, UNIQUE_ID_NAME = 6, CANONICAL_NAME = 7, USER_PRINCIPAL_NAME = 8, CANONICAL_NAME_EX = 9, SERVICE_PRINCIPAL_NAME = 10, SID_OR_SID_HISTORY_NAME = 11, DNS_DOMAIN_NAME = 12, }; pub const DS_UNKNOWN_NAME = DS_NAME_FORMAT.UNKNOWN_NAME; pub const DS_FQDN_1779_NAME = DS_NAME_FORMAT.FQDN_1779_NAME; pub const DS_NT4_ACCOUNT_NAME = DS_NAME_FORMAT.NT4_ACCOUNT_NAME; pub const DS_DISPLAY_NAME = DS_NAME_FORMAT.DISPLAY_NAME; pub const DS_UNIQUE_ID_NAME = DS_NAME_FORMAT.UNIQUE_ID_NAME; pub const DS_CANONICAL_NAME = DS_NAME_FORMAT.CANONICAL_NAME; pub const DS_USER_PRINCIPAL_NAME = DS_NAME_FORMAT.USER_PRINCIPAL_NAME; pub const DS_CANONICAL_NAME_EX = DS_NAME_FORMAT.CANONICAL_NAME_EX; pub const DS_SERVICE_PRINCIPAL_NAME = DS_NAME_FORMAT.SERVICE_PRINCIPAL_NAME; pub const DS_SID_OR_SID_HISTORY_NAME = DS_NAME_FORMAT.SID_OR_SID_HISTORY_NAME; pub const DS_DNS_DOMAIN_NAME = DS_NAME_FORMAT.DNS_DOMAIN_NAME; pub const DS_NAME_FLAGS = enum(i32) { NO_FLAGS = 0, FLAG_SYNTACTICAL_ONLY = 1, FLAG_EVAL_AT_DC = 2, FLAG_GCVERIFY = 4, FLAG_TRUST_REFERRAL = 8, }; pub const DS_NAME_NO_FLAGS = DS_NAME_FLAGS.NO_FLAGS; pub const DS_NAME_FLAG_SYNTACTICAL_ONLY = DS_NAME_FLAGS.FLAG_SYNTACTICAL_ONLY; pub const DS_NAME_FLAG_EVAL_AT_DC = DS_NAME_FLAGS.FLAG_EVAL_AT_DC; pub const DS_NAME_FLAG_GCVERIFY = DS_NAME_FLAGS.FLAG_GCVERIFY; pub const DS_NAME_FLAG_TRUST_REFERRAL = DS_NAME_FLAGS.FLAG_TRUST_REFERRAL; pub const DS_NAME_ERROR = enum(i32) { NO_ERROR = 0, ERROR_RESOLVING = 1, ERROR_NOT_FOUND = 2, ERROR_NOT_UNIQUE = 3, ERROR_NO_MAPPING = 4, ERROR_DOMAIN_ONLY = 5, ERROR_NO_SYNTACTICAL_MAPPING = 6, ERROR_TRUST_REFERRAL = 7, }; pub const DS_NAME_NO_ERROR = DS_NAME_ERROR.NO_ERROR; pub const DS_NAME_ERROR_RESOLVING = DS_NAME_ERROR.ERROR_RESOLVING; pub const DS_NAME_ERROR_NOT_FOUND = DS_NAME_ERROR.ERROR_NOT_FOUND; pub const DS_NAME_ERROR_NOT_UNIQUE = DS_NAME_ERROR.ERROR_NOT_UNIQUE; pub const DS_NAME_ERROR_NO_MAPPING = DS_NAME_ERROR.ERROR_NO_MAPPING; pub const DS_NAME_ERROR_DOMAIN_ONLY = DS_NAME_ERROR.ERROR_DOMAIN_ONLY; pub const DS_NAME_ERROR_NO_SYNTACTICAL_MAPPING = DS_NAME_ERROR.ERROR_NO_SYNTACTICAL_MAPPING; pub const DS_NAME_ERROR_TRUST_REFERRAL = DS_NAME_ERROR.ERROR_TRUST_REFERRAL; pub const DS_SPN_NAME_TYPE = enum(i32) { DNS_HOST = 0, DN_HOST = 1, NB_HOST = 2, DOMAIN = 3, NB_DOMAIN = 4, SERVICE = 5, }; pub const DS_SPN_DNS_HOST = DS_SPN_NAME_TYPE.DNS_HOST; pub const DS_SPN_DN_HOST = DS_SPN_NAME_TYPE.DN_HOST; pub const DS_SPN_NB_HOST = DS_SPN_NAME_TYPE.NB_HOST; pub const DS_SPN_DOMAIN = DS_SPN_NAME_TYPE.DOMAIN; pub const DS_SPN_NB_DOMAIN = DS_SPN_NAME_TYPE.NB_DOMAIN; pub const DS_SPN_SERVICE = DS_SPN_NAME_TYPE.SERVICE; pub const DS_SPN_WRITE_OP = enum(i32) { ADD_SPN_OP = 0, REPLACE_SPN_OP = 1, DELETE_SPN_OP = 2, }; pub const DS_SPN_ADD_SPN_OP = DS_SPN_WRITE_OP.ADD_SPN_OP; pub const DS_SPN_REPLACE_SPN_OP = DS_SPN_WRITE_OP.REPLACE_SPN_OP; pub const DS_SPN_DELETE_SPN_OP = DS_SPN_WRITE_OP.DELETE_SPN_OP; pub const DS_NAME_RESULT_ITEMA = extern struct { status: u32, pDomain: ?PSTR, pName: ?PSTR, }; pub const DS_NAME_RESULTA = extern struct { cItems: u32, rItems: ?*DS_NAME_RESULT_ITEMA, }; pub const DS_NAME_RESULT_ITEMW = extern struct { status: u32, pDomain: ?PWSTR, pName: ?PWSTR, }; pub const DS_NAME_RESULTW = extern struct { cItems: u32, rItems: ?*DS_NAME_RESULT_ITEMW, }; pub const DS_REPSYNCALL_ERROR = enum(i32) { WIN32_ERROR_CONTACTING_SERVER = 0, WIN32_ERROR_REPLICATING = 1, SERVER_UNREACHABLE = 2, }; pub const DS_REPSYNCALL_WIN32_ERROR_CONTACTING_SERVER = DS_REPSYNCALL_ERROR.WIN32_ERROR_CONTACTING_SERVER; pub const DS_REPSYNCALL_WIN32_ERROR_REPLICATING = DS_REPSYNCALL_ERROR.WIN32_ERROR_REPLICATING; pub const DS_REPSYNCALL_SERVER_UNREACHABLE = DS_REPSYNCALL_ERROR.SERVER_UNREACHABLE; pub const DS_REPSYNCALL_EVENT = enum(i32) { ERROR = 0, SYNC_STARTED = 1, SYNC_COMPLETED = 2, FINISHED = 3, }; pub const DS_REPSYNCALL_EVENT_ERROR = DS_REPSYNCALL_EVENT.ERROR; pub const DS_REPSYNCALL_EVENT_SYNC_STARTED = DS_REPSYNCALL_EVENT.SYNC_STARTED; pub const DS_REPSYNCALL_EVENT_SYNC_COMPLETED = DS_REPSYNCALL_EVENT.SYNC_COMPLETED; pub const DS_REPSYNCALL_EVENT_FINISHED = DS_REPSYNCALL_EVENT.FINISHED; pub const DS_REPSYNCALL_SYNCA = extern struct { pszSrcId: ?PSTR, pszDstId: ?PSTR, pszNC: ?PSTR, pguidSrc: ?*Guid, pguidDst: ?*Guid, }; pub const DS_REPSYNCALL_SYNCW = extern struct { pszSrcId: ?PWSTR, pszDstId: ?PWSTR, pszNC: ?PWSTR, pguidSrc: ?*Guid, pguidDst: ?*Guid, }; pub const DS_REPSYNCALL_ERRINFOA = extern struct { pszSvrId: ?PSTR, @"error": DS_REPSYNCALL_ERROR, dwWin32Err: u32, pszSrcId: ?PSTR, }; pub const DS_REPSYNCALL_ERRINFOW = extern struct { pszSvrId: ?PWSTR, @"error": DS_REPSYNCALL_ERROR, dwWin32Err: u32, pszSrcId: ?PWSTR, }; pub const DS_REPSYNCALL_UPDATEA = extern struct { event: DS_REPSYNCALL_EVENT, pErrInfo: ?*DS_REPSYNCALL_ERRINFOA, pSync: ?*DS_REPSYNCALL_SYNCA, }; pub const DS_REPSYNCALL_UPDATEW = extern struct { event: DS_REPSYNCALL_EVENT, pErrInfo: ?*DS_REPSYNCALL_ERRINFOW, pSync: ?*DS_REPSYNCALL_SYNCW, }; pub const DS_SITE_COST_INFO = extern struct { errorCode: u32, cost: u32, }; pub const DS_SCHEMA_GUID_MAPA = extern struct { guid: Guid, guidType: u32, pName: ?PSTR, }; pub const DS_SCHEMA_GUID_MAPW = extern struct { guid: Guid, guidType: u32, pName: ?PWSTR, }; pub const DS_DOMAIN_CONTROLLER_INFO_1A = extern struct { NetbiosName: ?PSTR, DnsHostName: ?PSTR, SiteName: ?PSTR, ComputerObjectName: ?PSTR, ServerObjectName: ?PSTR, fIsPdc: BOOL, fDsEnabled: BOOL, }; pub const DS_DOMAIN_CONTROLLER_INFO_1W = extern struct { NetbiosName: ?PWSTR, DnsHostName: ?PWSTR, SiteName: ?PWSTR, ComputerObjectName: ?PWSTR, ServerObjectName: ?PWSTR, fIsPdc: BOOL, fDsEnabled: BOOL, }; pub const DS_DOMAIN_CONTROLLER_INFO_2A = extern struct { NetbiosName: ?PSTR, DnsHostName: ?PSTR, SiteName: ?PSTR, SiteObjectName: ?PSTR, ComputerObjectName: ?PSTR, ServerObjectName: ?PSTR, NtdsDsaObjectName: ?PSTR, fIsPdc: BOOL, fDsEnabled: BOOL, fIsGc: BOOL, SiteObjectGuid: Guid, ComputerObjectGuid: Guid, ServerObjectGuid: Guid, NtdsDsaObjectGuid: Guid, }; pub const DS_DOMAIN_CONTROLLER_INFO_2W = extern struct { NetbiosName: ?PWSTR, DnsHostName: ?PWSTR, SiteName: ?PWSTR, SiteObjectName: ?PWSTR, ComputerObjectName: ?PWSTR, ServerObjectName: ?PWSTR, NtdsDsaObjectName: ?PWSTR, fIsPdc: BOOL, fDsEnabled: BOOL, fIsGc: BOOL, SiteObjectGuid: Guid, ComputerObjectGuid: Guid, ServerObjectGuid: Guid, NtdsDsaObjectGuid: Guid, }; pub const DS_DOMAIN_CONTROLLER_INFO_3A = extern struct { NetbiosName: ?PSTR, DnsHostName: ?PSTR, SiteName: ?PSTR, SiteObjectName: ?PSTR, ComputerObjectName: ?PSTR, ServerObjectName: ?PSTR, NtdsDsaObjectName: ?PSTR, fIsPdc: BOOL, fDsEnabled: BOOL, fIsGc: BOOL, fIsRodc: BOOL, SiteObjectGuid: Guid, ComputerObjectGuid: Guid, ServerObjectGuid: Guid, NtdsDsaObjectGuid: Guid, }; pub const DS_DOMAIN_CONTROLLER_INFO_3W = extern struct { NetbiosName: ?PWSTR, DnsHostName: ?PWSTR, SiteName: ?PWSTR, SiteObjectName: ?PWSTR, ComputerObjectName: ?PWSTR, ServerObjectName: ?PWSTR, NtdsDsaObjectName: ?PWSTR, fIsPdc: BOOL, fDsEnabled: BOOL, fIsGc: BOOL, fIsRodc: BOOL, SiteObjectGuid: Guid, ComputerObjectGuid: Guid, ServerObjectGuid: Guid, NtdsDsaObjectGuid: Guid, }; pub const DS_KCC_TASKID = enum(i32) { Y = 0, }; pub const DS_KCC_TASKID_UPDATE_TOPOLOGY = DS_KCC_TASKID.Y; pub const DS_REPL_INFO_TYPE = enum(i32) { NEIGHBORS = 0, CURSORS_FOR_NC = 1, METADATA_FOR_OBJ = 2, KCC_DSA_CONNECT_FAILURES = 3, KCC_DSA_LINK_FAILURES = 4, PENDING_OPS = 5, METADATA_FOR_ATTR_VALUE = 6, CURSORS_2_FOR_NC = 7, CURSORS_3_FOR_NC = 8, METADATA_2_FOR_OBJ = 9, METADATA_2_FOR_ATTR_VALUE = 10, METADATA_EXT_FOR_ATTR_VALUE = 11, TYPE_MAX = 12, }; pub const DS_REPL_INFO_NEIGHBORS = DS_REPL_INFO_TYPE.NEIGHBORS; pub const DS_REPL_INFO_CURSORS_FOR_NC = DS_REPL_INFO_TYPE.CURSORS_FOR_NC; pub const DS_REPL_INFO_METADATA_FOR_OBJ = DS_REPL_INFO_TYPE.METADATA_FOR_OBJ; pub const DS_REPL_INFO_KCC_DSA_CONNECT_FAILURES = DS_REPL_INFO_TYPE.KCC_DSA_CONNECT_FAILURES; pub const DS_REPL_INFO_KCC_DSA_LINK_FAILURES = DS_REPL_INFO_TYPE.KCC_DSA_LINK_FAILURES; pub const DS_REPL_INFO_PENDING_OPS = DS_REPL_INFO_TYPE.PENDING_OPS; pub const DS_REPL_INFO_METADATA_FOR_ATTR_VALUE = DS_REPL_INFO_TYPE.METADATA_FOR_ATTR_VALUE; pub const DS_REPL_INFO_CURSORS_2_FOR_NC = DS_REPL_INFO_TYPE.CURSORS_2_FOR_NC; pub const DS_REPL_INFO_CURSORS_3_FOR_NC = DS_REPL_INFO_TYPE.CURSORS_3_FOR_NC; pub const DS_REPL_INFO_METADATA_2_FOR_OBJ = DS_REPL_INFO_TYPE.METADATA_2_FOR_OBJ; pub const DS_REPL_INFO_METADATA_2_FOR_ATTR_VALUE = DS_REPL_INFO_TYPE.METADATA_2_FOR_ATTR_VALUE; pub const DS_REPL_INFO_METADATA_EXT_FOR_ATTR_VALUE = DS_REPL_INFO_TYPE.METADATA_EXT_FOR_ATTR_VALUE; pub const DS_REPL_INFO_TYPE_MAX = DS_REPL_INFO_TYPE.TYPE_MAX; pub const DS_REPL_NEIGHBORW = extern struct { pszNamingContext: ?PWSTR, pszSourceDsaDN: ?PWSTR, pszSourceDsaAddress: ?PWSTR, pszAsyncIntersiteTransportDN: ?PWSTR, dwReplicaFlags: u32, dwReserved: u32, uuidNamingContextObjGuid: Guid, uuidSourceDsaObjGuid: Guid, uuidSourceDsaInvocationID: Guid, uuidAsyncIntersiteTransportObjGuid: Guid, usnLastObjChangeSynced: i64, usnAttributeFilter: i64, ftimeLastSyncSuccess: FILETIME, ftimeLastSyncAttempt: FILETIME, dwLastSyncResult: u32, cNumConsecutiveSyncFailures: u32, }; pub const DS_REPL_NEIGHBORW_BLOB = extern struct { oszNamingContext: u32, oszSourceDsaDN: u32, oszSourceDsaAddress: u32, oszAsyncIntersiteTransportDN: u32, dwReplicaFlags: u32, dwReserved: u32, uuidNamingContextObjGuid: Guid, uuidSourceDsaObjGuid: Guid, uuidSourceDsaInvocationID: Guid, uuidAsyncIntersiteTransportObjGuid: Guid, usnLastObjChangeSynced: i64, usnAttributeFilter: i64, ftimeLastSyncSuccess: FILETIME, ftimeLastSyncAttempt: FILETIME, dwLastSyncResult: u32, cNumConsecutiveSyncFailures: u32, }; pub const DS_REPL_NEIGHBORSW = extern struct { cNumNeighbors: u32, dwReserved: u32, rgNeighbor: [1]DS_REPL_NEIGHBORW, }; pub const DS_REPL_CURSOR = extern struct { uuidSourceDsaInvocationID: Guid, usnAttributeFilter: i64, }; pub const DS_REPL_CURSOR_2 = extern struct { uuidSourceDsaInvocationID: Guid, usnAttributeFilter: i64, ftimeLastSyncSuccess: FILETIME, }; pub const DS_REPL_CURSOR_3W = extern struct { uuidSourceDsaInvocationID: Guid, usnAttributeFilter: i64, ftimeLastSyncSuccess: FILETIME, pszSourceDsaDN: ?PWSTR, }; pub const DS_REPL_CURSOR_BLOB = extern struct { uuidSourceDsaInvocationID: Guid, usnAttributeFilter: i64, ftimeLastSyncSuccess: FILETIME, oszSourceDsaDN: u32, }; pub const DS_REPL_CURSORS = extern struct { cNumCursors: u32, dwReserved: u32, rgCursor: [1]DS_REPL_CURSOR, }; pub const DS_REPL_CURSORS_2 = extern struct { cNumCursors: u32, dwEnumerationContext: u32, rgCursor: [1]DS_REPL_CURSOR_2, }; pub const DS_REPL_CURSORS_3W = extern struct { cNumCursors: u32, dwEnumerationContext: u32, rgCursor: [1]DS_REPL_CURSOR_3W, }; pub const DS_REPL_ATTR_META_DATA = extern struct { pszAttributeName: ?PWSTR, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, }; pub const DS_REPL_ATTR_META_DATA_2 = extern struct { pszAttributeName: ?PWSTR, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, pszLastOriginatingDsaDN: ?PWSTR, }; pub const DS_REPL_ATTR_META_DATA_BLOB = extern struct { oszAttributeName: u32, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, oszLastOriginatingDsaDN: u32, }; pub const DS_REPL_OBJ_META_DATA = extern struct { cNumEntries: u32, dwReserved: u32, rgMetaData: [1]DS_REPL_ATTR_META_DATA, }; pub const DS_REPL_OBJ_META_DATA_2 = extern struct { cNumEntries: u32, dwReserved: u32, rgMetaData: [1]DS_REPL_ATTR_META_DATA_2, }; pub const DS_REPL_KCC_DSA_FAILUREW = extern struct { pszDsaDN: ?PWSTR, uuidDsaObjGuid: Guid, ftimeFirstFailure: FILETIME, cNumFailures: u32, dwLastResult: u32, }; pub const DS_REPL_KCC_DSA_FAILUREW_BLOB = extern struct { oszDsaDN: u32, uuidDsaObjGuid: Guid, ftimeFirstFailure: FILETIME, cNumFailures: u32, dwLastResult: u32, }; pub const DS_REPL_KCC_DSA_FAILURESW = extern struct { cNumEntries: u32, dwReserved: u32, rgDsaFailure: [1]DS_REPL_KCC_DSA_FAILUREW, }; pub const DS_REPL_OP_TYPE = enum(i32) { SYNC = 0, ADD = 1, DELETE = 2, MODIFY = 3, UPDATE_REFS = 4, }; pub const DS_REPL_OP_TYPE_SYNC = DS_REPL_OP_TYPE.SYNC; pub const DS_REPL_OP_TYPE_ADD = DS_REPL_OP_TYPE.ADD; pub const DS_REPL_OP_TYPE_DELETE = DS_REPL_OP_TYPE.DELETE; pub const DS_REPL_OP_TYPE_MODIFY = DS_REPL_OP_TYPE.MODIFY; pub const DS_REPL_OP_TYPE_UPDATE_REFS = DS_REPL_OP_TYPE.UPDATE_REFS; pub const DS_REPL_OPW = extern struct { ftimeEnqueued: FILETIME, ulSerialNumber: u32, ulPriority: u32, OpType: DS_REPL_OP_TYPE, ulOptions: u32, pszNamingContext: ?PWSTR, pszDsaDN: ?PWSTR, pszDsaAddress: ?PWSTR, uuidNamingContextObjGuid: Guid, uuidDsaObjGuid: Guid, }; pub const DS_REPL_OPW_BLOB = extern struct { ftimeEnqueued: FILETIME, ulSerialNumber: u32, ulPriority: u32, OpType: DS_REPL_OP_TYPE, ulOptions: u32, oszNamingContext: u32, oszDsaDN: u32, oszDsaAddress: u32, uuidNamingContextObjGuid: Guid, uuidDsaObjGuid: Guid, }; pub const DS_REPL_PENDING_OPSW = extern struct { ftimeCurrentOpStarted: FILETIME, cNumPendingOps: u32, rgPendingOp: [1]DS_REPL_OPW, }; pub const DS_REPL_VALUE_META_DATA = extern struct { pszAttributeName: ?PWSTR, pszObjectDn: ?PWSTR, cbData: u32, pbData: ?*u8, ftimeDeleted: FILETIME, ftimeCreated: FILETIME, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, }; pub const DS_REPL_VALUE_META_DATA_2 = extern struct { pszAttributeName: ?PWSTR, pszObjectDn: ?PWSTR, cbData: u32, pbData: ?*u8, ftimeDeleted: FILETIME, ftimeCreated: FILETIME, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, pszLastOriginatingDsaDN: ?PWSTR, }; pub const DS_REPL_VALUE_META_DATA_EXT = extern struct { pszAttributeName: ?PWSTR, pszObjectDn: ?PWSTR, cbData: u32, pbData: ?*u8, ftimeDeleted: FILETIME, ftimeCreated: FILETIME, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, pszLastOriginatingDsaDN: ?PWSTR, dwUserIdentifier: u32, dwPriorLinkState: u32, dwCurrentLinkState: u32, }; pub const DS_REPL_VALUE_META_DATA_BLOB = extern struct { oszAttributeName: u32, oszObjectDn: u32, cbData: u32, obData: u32, ftimeDeleted: FILETIME, ftimeCreated: FILETIME, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, oszLastOriginatingDsaDN: u32, }; pub const DS_REPL_VALUE_META_DATA_BLOB_EXT = extern struct { oszAttributeName: u32, oszObjectDn: u32, cbData: u32, obData: u32, ftimeDeleted: FILETIME, ftimeCreated: FILETIME, dwVersion: u32, ftimeLastOriginatingChange: FILETIME, uuidLastOriginatingDsaInvocationID: Guid, usnOriginatingChange: i64, usnLocalChange: i64, oszLastOriginatingDsaDN: u32, dwUserIdentifier: u32, dwPriorLinkState: u32, dwCurrentLinkState: u32, }; pub const DS_REPL_ATTR_VALUE_META_DATA = extern struct { cNumEntries: u32, dwEnumerationContext: u32, rgMetaData: [1]DS_REPL_VALUE_META_DATA, }; pub const DS_REPL_ATTR_VALUE_META_DATA_2 = extern struct { cNumEntries: u32, dwEnumerationContext: u32, rgMetaData: [1]DS_REPL_VALUE_META_DATA_2, }; pub const DS_REPL_ATTR_VALUE_META_DATA_EXT = extern struct { cNumEntries: u32, dwEnumerationContext: u32, rgMetaData: [1]DS_REPL_VALUE_META_DATA_EXT, }; pub const DS_REPL_QUEUE_STATISTICSW = extern struct { ftimeCurrentOpStarted: FILETIME, cNumPendingOps: u32, ftimeOldestSync: FILETIME, ftimeOldestAdd: FILETIME, ftimeOldestMod: FILETIME, ftimeOldestDel: FILETIME, ftimeOldestUpdRefs: FILETIME, }; pub const DSROLE_MACHINE_ROLE = enum(i32) { StandaloneWorkstation = 0, MemberWorkstation = 1, StandaloneServer = 2, MemberServer = 3, BackupDomainController = 4, PrimaryDomainController = 5, }; pub const DsRole_RoleStandaloneWorkstation = DSROLE_MACHINE_ROLE.StandaloneWorkstation; pub const DsRole_RoleMemberWorkstation = DSROLE_MACHINE_ROLE.MemberWorkstation; pub const DsRole_RoleStandaloneServer = DSROLE_MACHINE_ROLE.StandaloneServer; pub const DsRole_RoleMemberServer = DSROLE_MACHINE_ROLE.MemberServer; pub const DsRole_RoleBackupDomainController = DSROLE_MACHINE_ROLE.BackupDomainController; pub const DsRole_RolePrimaryDomainController = DSROLE_MACHINE_ROLE.PrimaryDomainController; pub const DSROLE_SERVER_STATE = enum(i32) { Unknown = 0, Primary = 1, Backup = 2, }; pub const DsRoleServerUnknown = DSROLE_SERVER_STATE.Unknown; pub const DsRoleServerPrimary = DSROLE_SERVER_STATE.Primary; pub const DsRoleServerBackup = DSROLE_SERVER_STATE.Backup; pub const DSROLE_PRIMARY_DOMAIN_INFO_LEVEL = enum(i32) { PrimaryDomainInfoBasic = 1, UpgradeStatus = 2, OperationState = 3, }; pub const DsRolePrimaryDomainInfoBasic = DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.PrimaryDomainInfoBasic; pub const DsRoleUpgradeStatus = DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.UpgradeStatus; pub const DsRoleOperationState = DSROLE_PRIMARY_DOMAIN_INFO_LEVEL.OperationState; pub const DSROLE_PRIMARY_DOMAIN_INFO_BASIC = extern struct { MachineRole: DSROLE_MACHINE_ROLE, Flags: u32, DomainNameFlat: ?PWSTR, DomainNameDns: ?PWSTR, DomainForestName: ?PWSTR, DomainGuid: Guid, }; pub const DSROLE_UPGRADE_STATUS_INFO = extern struct { OperationState: u32, PreviousServerState: DSROLE_SERVER_STATE, }; pub const DSROLE_OPERATION_STATE = enum(i32) { Idle = 0, Active = 1, NeedReboot = 2, }; pub const DsRoleOperationIdle = DSROLE_OPERATION_STATE.Idle; pub const DsRoleOperationActive = DSROLE_OPERATION_STATE.Active; pub const DsRoleOperationNeedReboot = DSROLE_OPERATION_STATE.NeedReboot; pub const DSROLE_OPERATION_STATE_INFO = extern struct { OperationState: DSROLE_OPERATION_STATE, }; pub const DOMAIN_CONTROLLER_INFOA = extern struct { DomainControllerName: ?PSTR, DomainControllerAddress: ?PSTR, DomainControllerAddressType: u32, DomainGuid: Guid, DomainName: ?PSTR, DnsForestName: ?PSTR, Flags: u32, DcSiteName: ?PSTR, ClientSiteName: ?PSTR, }; pub const DOMAIN_CONTROLLER_INFOW = extern struct { DomainControllerName: ?PWSTR, DomainControllerAddress: ?PWSTR, DomainControllerAddressType: u32, DomainGuid: Guid, DomainName: ?PWSTR, DnsForestName: ?PWSTR, Flags: u32, DcSiteName: ?PWSTR, ClientSiteName: ?PWSTR, }; pub const DS_DOMAIN_TRUSTSW = extern struct { NetbiosDomainName: ?PWSTR, DnsDomainName: ?PWSTR, Flags: u32, ParentIndex: u32, TrustType: u32, TrustAttributes: u32, DomainSid: ?PSID, DomainGuid: Guid, }; pub const DS_DOMAIN_TRUSTSA = extern struct { NetbiosDomainName: ?PSTR, DnsDomainName: ?PSTR, Flags: u32, ParentIndex: u32, TrustType: u32, TrustAttributes: u32, DomainSid: ?PSID, DomainGuid: Guid, }; // TODO: this type has a FreeFunc 'DsGetDcCloseW', what can Zig do with this information? pub const GetDcContextHandle = isize; //-------------------------------------------------------------------------------- // Section: Functions (158) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsGetObject( lpszPathName: ?[*:0]const u16, riid: ?*const Guid, ppObject: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsBuildEnumerator( pADsContainer: ?*IADsContainer, ppEnumVariant: ?*?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsFreeEnumerator( pEnumVariant: ?*IEnumVARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsEnumerateNext( pEnumVariant: ?*IEnumVARIANT, cElements: u32, pvar: ?*VARIANT, pcElementsFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsBuildVarArrayStr( lppPathNames: [*]?PWSTR, dwPathNames: u32, pVar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsBuildVarArrayInt( lpdwObjectTypes: ?*u32, dwObjectTypes: u32, pVar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsOpenObject( lpszPathName: ?[*:0]const u16, lpszUserName: ?[*:0]const u16, lpszPassword: ?[*:0]const u16, dwReserved: ADS_AUTHENTICATION_ENUM, riid: ?*const Guid, ppObject: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsGetLastError( lpError: ?*u32, lpErrorBuf: [*:0]u16, dwErrorBufLen: u32, lpNameBuf: [*:0]u16, dwNameBufLen: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsSetLastError( dwErr: u32, pszError: ?[*:0]const u16, pszProvider: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn AllocADsMem( cb: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn FreeADsMem( pMem: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ReallocADsMem( pOldMem: ?*anyopaque, cbOld: u32, cbNew: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn AllocADsStr( pStr: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) ?PWSTR; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn FreeADsStr( pStr: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ReallocADsStr( ppStr: ?*?PWSTR, pStr: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn ADsEncodeBinaryData( pbSrcData: ?*u8, dwSrcLen: u32, ppszDestData: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "ACTIVEDS" fn ADsDecodeBinaryData( szSrcData: ?[*:0]const u16, ppbDestData: ?*?*u8, pdwDestLen: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "ACTIVEDS" fn PropVariantToAdsType( pVariant: ?*VARIANT, dwNumVariant: u32, ppAdsValues: ?*?*ADSVALUE, pdwNumValues: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "ACTIVEDS" fn AdsTypeToPropVariant( pAdsValues: ?*ADSVALUE, dwNumValues: u32, pVariant: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "ACTIVEDS" fn AdsFreeAdsValues( pAdsValues: ?*ADSVALUE, dwNumValues: u32, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn BinarySDToSecurityDescriptor( pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, pVarsec: ?*VARIANT, pszServerName: ?[*:0]const u16, userName: ?[*:0]const u16, passWord: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ACTIVEDS" fn SecurityDescriptorToBinarySD( vVarSecDes: VARIANT, ppSecurityDescriptor: ?*?*SECURITY_DESCRIPTOR, pdwSDLength: ?*u32, pszServerName: ?[*:0]const u16, userName: ?[*:0]const u16, passWord: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsuiext" fn DsBrowseForContainerW( pInfo: ?*DSBROWSEINFOW, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsuiext" fn DsBrowseForContainerA( pInfo: ?*DSBROWSEINFOA, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsuiext" fn DsGetIcon( dwFlags: u32, pszObjectClass: ?[*:0]const u16, cxImage: i32, cyImage: i32, ) callconv(@import("std").os.windows.WINAPI) ?HICON; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsuiext" fn DsGetFriendlyClassName( pszObjectClass: ?[*:0]const u16, pszBuffer: [*:0]u16, cchBuffer: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropCreateNotifyObj( pAppThdDataObj: ?*IDataObject, pwzADsObjName: ?PWSTR, phNotifyObj: ?*?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropGetInitInfo( hNotifyObj: ?HWND, pInitParams: ?*ADSPROPINITPARAMS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropSetHwndWithTitle( hNotifyObj: ?HWND, hPage: ?HWND, ptzTitle: ?*i8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropSetHwnd( hNotifyObj: ?HWND, hPage: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropCheckIfWritable( pwzAttr: ?[*:0]const u16, pWritableAttrs: ?*const ADS_ATTR_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropSendErrorMessage( hNotifyObj: ?HWND, pError: ?*ADSPROPERROR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "dsprop" fn ADsPropShowErrorDialog( hNotifyObj: ?HWND, hPage: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsMakeSpnW( ServiceClass: ?[*:0]const u16, ServiceName: ?[*:0]const u16, InstanceName: ?[*:0]const u16, InstancePort: u16, Referrer: ?[*:0]const u16, pcSpnLength: ?*u32, pszSpn: ?[*:0]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsMakeSpnA( ServiceClass: ?[*:0]const u8, ServiceName: ?[*:0]const u8, InstanceName: ?[*:0]const u8, InstancePort: u16, Referrer: ?[*:0]const u8, pcSpnLength: ?*u32, pszSpn: ?[*:0]u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsCrackSpnA( pszSpn: ?[*:0]const u8, pcServiceClass: ?*u32, ServiceClass: ?[*:0]u8, pcServiceName: ?*u32, ServiceName: ?[*:0]u8, pcInstanceName: ?*u32, InstanceName: ?[*:0]u8, pInstancePort: ?*u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsCrackSpnW( pszSpn: ?[*:0]const u16, pcServiceClass: ?*u32, ServiceClass: ?[*:0]u16, pcServiceName: ?*u32, ServiceName: ?[*:0]u16, pcInstanceName: ?*u32, InstanceName: ?[*:0]u16, pInstancePort: ?*u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsQuoteRdnValueW( cUnquotedRdnValueLength: u32, psUnquotedRdnValue: [*:0]const u16, pcQuotedRdnValueLength: ?*u32, psQuotedRdnValue: [*]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsQuoteRdnValueA( cUnquotedRdnValueLength: u32, psUnquotedRdnValue: [*]const u8, pcQuotedRdnValueLength: ?*u32, psQuotedRdnValue: [*]u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsUnquoteRdnValueW( cQuotedRdnValueLength: u32, psQuotedRdnValue: [*:0]const u16, pcUnquotedRdnValueLength: ?*u32, psUnquotedRdnValue: [*]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsUnquoteRdnValueA( cQuotedRdnValueLength: u32, psQuotedRdnValue: [*]const u8, pcUnquotedRdnValueLength: ?*u32, psUnquotedRdnValue: [*]u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsGetRdnW( ppDN: [*]?PWSTR, pcDN: ?*u32, ppKey: ?*?PWSTR, pcKey: ?*u32, ppVal: ?*?PWSTR, pcVal: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsCrackUnquotedMangledRdnW( pszRDN: [*:0]const u16, cchRDN: u32, pGuid: ?*Guid, peDsMangleFor: ?*DS_MANGLE_FOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsCrackUnquotedMangledRdnA( pszRDN: [*:0]const u8, cchRDN: u32, pGuid: ?*Guid, peDsMangleFor: ?*DS_MANGLE_FOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsIsMangledRdnValueW( pszRdn: [*:0]const u16, cRdn: u32, eDsMangleForDesired: DS_MANGLE_FOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsIsMangledRdnValueA( pszRdn: [*:0]const u8, cRdn: u32, eDsMangleForDesired: DS_MANGLE_FOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsIsMangledDnA( pszDn: ?[*:0]const u8, eDsMangleFor: DS_MANGLE_FOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "DSPARSE" fn DsIsMangledDnW( pszDn: ?[*:0]const u16, eDsMangleFor: DS_MANGLE_FOR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "DSPARSE" fn DsCrackSpn2A( pszSpn: [*:0]const u8, cSpn: u32, pcServiceClass: ?*u32, ServiceClass: ?[*:0]u8, pcServiceName: ?*u32, ServiceName: ?[*:0]u8, pcInstanceName: ?*u32, InstanceName: ?[*:0]u8, pInstancePort: ?*u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "DSPARSE" fn DsCrackSpn2W( pszSpn: [*:0]const u16, cSpn: u32, pcServiceClass: ?*u32, ServiceClass: ?[*:0]u16, pcServiceName: ?*u32, ServiceName: ?[*:0]u16, pcInstanceName: ?*u32, InstanceName: ?[*:0]u16, pInstancePort: ?*u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "DSPARSE" fn DsCrackSpn3W( pszSpn: ?[*:0]const u16, cSpn: u32, pcHostName: ?*u32, HostName: [*:0]u16, pcInstanceName: ?*u32, InstanceName: [*:0]u16, pPortNumber: ?*u16, pcDomainName: ?*u32, DomainName: [*:0]u16, pcRealmName: ?*u32, RealmName: [*:0]u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "DSPARSE" fn DsCrackSpn4W( pszSpn: ?[*:0]const u16, cSpn: u32, pcHostName: ?*u32, HostName: [*:0]u16, pcInstanceName: ?*u32, InstanceName: [*:0]u16, pcPortName: ?*u32, PortName: [*:0]u16, pcDomainName: ?*u32, DomainName: [*:0]u16, pcRealmName: ?*u32, RealmName: [*:0]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindW( DomainControllerName: ?[*:0]const u16, DnsDomainName: ?[*:0]const u16, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindA( DomainControllerName: ?[*:0]const u8, DnsDomainName: ?[*:0]const u8, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindWithCredW( DomainControllerName: ?[*:0]const u16, DnsDomainName: ?[*:0]const u16, AuthIdentity: ?*anyopaque, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindWithCredA( DomainControllerName: ?[*:0]const u8, DnsDomainName: ?[*:0]const u8, AuthIdentity: ?*anyopaque, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindWithSpnW( DomainControllerName: ?[*:0]const u16, DnsDomainName: ?[*:0]const u16, AuthIdentity: ?*anyopaque, ServicePrincipalName: ?[*:0]const u16, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindWithSpnA( DomainControllerName: ?[*:0]const u8, DnsDomainName: ?[*:0]const u8, AuthIdentity: ?*anyopaque, ServicePrincipalName: ?[*:0]const u8, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindWithSpnExW( DomainControllerName: ?[*:0]const u16, DnsDomainName: ?[*:0]const u16, AuthIdentity: ?*anyopaque, ServicePrincipalName: ?[*:0]const u16, BindFlags: u32, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindWithSpnExA( DomainControllerName: ?[*:0]const u8, DnsDomainName: ?[*:0]const u8, AuthIdentity: ?*anyopaque, ServicePrincipalName: ?[*:0]const u8, BindFlags: u32, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindByInstanceW( ServerName: ?[*:0]const u16, Annotation: ?[*:0]const u16, InstanceGuid: ?*Guid, DnsDomainName: ?[*:0]const u16, AuthIdentity: ?*anyopaque, ServicePrincipalName: ?[*:0]const u16, BindFlags: u32, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindByInstanceA( ServerName: ?[*:0]const u8, Annotation: ?[*:0]const u8, InstanceGuid: ?*Guid, DnsDomainName: ?[*:0]const u8, AuthIdentity: ?*anyopaque, ServicePrincipalName: ?[*:0]const u8, BindFlags: u32, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindToISTGW( SiteName: ?[*:0]const u16, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindToISTGA( SiteName: ?[*:0]const u8, phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsBindingSetTimeout( hDS: ?HANDLE, cTimeoutSecs: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsUnBindW( phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsUnBindA( phDS: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsMakePasswordCredentialsW( User: ?[*:0]const u16, Domain: ?[*:0]const u16, Password: ?[*:0]const u16, pAuthIdentity: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsMakePasswordCredentialsA( User: ?[*:0]const u8, Domain: ?[*:0]const u8, Password: ?[*:0]const u8, pAuthIdentity: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreePasswordCredentials( AuthIdentity: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsCrackNamesW( hDS: ?HANDLE, flags: DS_NAME_FLAGS, formatOffered: DS_NAME_FORMAT, formatDesired: DS_NAME_FORMAT, cNames: u32, rpNames: [*]const ?[*:0]const u16, ppResult: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsCrackNamesA( hDS: ?HANDLE, flags: DS_NAME_FLAGS, formatOffered: DS_NAME_FORMAT, formatDesired: DS_NAME_FORMAT, cNames: u32, rpNames: [*]const ?[*:0]const u8, ppResult: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeNameResultW( pResult: ?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeNameResultA( pResult: ?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsGetSpnA( ServiceType: DS_SPN_NAME_TYPE, ServiceClass: ?[*:0]const u8, ServiceName: ?[*:0]const u8, InstancePort: u16, cInstanceNames: u16, pInstanceNames: ?[*]?PSTR, pInstancePorts: ?[*:0]const u16, pcSpn: ?*u32, prpszSpn: ?*?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsGetSpnW( ServiceType: DS_SPN_NAME_TYPE, ServiceClass: ?[*:0]const u16, ServiceName: ?[*:0]const u16, InstancePort: u16, cInstanceNames: u16, pInstanceNames: ?[*]?PWSTR, pInstancePorts: ?[*:0]const u16, pcSpn: ?*u32, prpszSpn: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeSpnArrayA( cSpn: u32, rpszSpn: [*]?PSTR, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeSpnArrayW( cSpn: u32, rpszSpn: [*]?PWSTR, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsWriteAccountSpnA( hDS: ?HANDLE, Operation: DS_SPN_WRITE_OP, pszAccount: ?[*:0]const u8, cSpn: u32, rpszSpn: [*]?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsWriteAccountSpnW( hDS: ?HANDLE, Operation: DS_SPN_WRITE_OP, pszAccount: ?[*:0]const u16, cSpn: u32, rpszSpn: [*]?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsClientMakeSpnForTargetServerW( ServiceClass: ?[*:0]const u16, ServiceName: ?[*:0]const u16, pcSpnLength: ?*u32, pszSpn: [*:0]u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsClientMakeSpnForTargetServerA( ServiceClass: ?[*:0]const u8, ServiceName: ?[*:0]const u8, pcSpnLength: ?*u32, pszSpn: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsServerRegisterSpnA( Operation: DS_SPN_WRITE_OP, ServiceClass: ?[*:0]const u8, UserObjectDN: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsServerRegisterSpnW( Operation: DS_SPN_WRITE_OP, ServiceClass: ?[*:0]const u16, UserObjectDN: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaSyncA( hDS: ?HANDLE, NameContext: ?[*:0]const u8, pUuidDsaSrc: ?*const Guid, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaSyncW( hDS: ?HANDLE, NameContext: ?[*:0]const u16, pUuidDsaSrc: ?*const Guid, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaAddA( hDS: ?HANDLE, NameContext: ?[*:0]const u8, SourceDsaDn: ?[*:0]const u8, TransportDn: ?[*:0]const u8, SourceDsaAddress: ?[*:0]const u8, pSchedule: ?*const SCHEDULE, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaAddW( hDS: ?HANDLE, NameContext: ?[*:0]const u16, SourceDsaDn: ?[*:0]const u16, TransportDn: ?[*:0]const u16, SourceDsaAddress: ?[*:0]const u16, pSchedule: ?*const SCHEDULE, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaDelA( hDS: ?HANDLE, NameContext: ?[*:0]const u8, DsaSrc: ?[*:0]const u8, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaDelW( hDS: ?HANDLE, NameContext: ?[*:0]const u16, DsaSrc: ?[*:0]const u16, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaModifyA( hDS: ?HANDLE, NameContext: ?[*:0]const u8, pUuidSourceDsa: ?*const Guid, TransportDn: ?[*:0]const u8, SourceDsaAddress: ?[*:0]const u8, pSchedule: ?*const SCHEDULE, ReplicaFlags: u32, ModifyFields: u32, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaModifyW( hDS: ?HANDLE, NameContext: ?[*:0]const u16, pUuidSourceDsa: ?*const Guid, TransportDn: ?[*:0]const u16, SourceDsaAddress: ?[*:0]const u16, pSchedule: ?*const SCHEDULE, ReplicaFlags: u32, ModifyFields: u32, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaUpdateRefsA( hDS: ?HANDLE, NameContext: ?[*:0]const u8, DsaDest: ?[*:0]const u8, pUuidDsaDest: ?*const Guid, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaUpdateRefsW( hDS: ?HANDLE, NameContext: ?[*:0]const u16, DsaDest: ?[*:0]const u16, pUuidDsaDest: ?*const Guid, Options: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaSyncAllA( hDS: ?HANDLE, pszNameContext: ?[*:0]const u8, ulFlags: u32, pFnCallBack: isize, pCallbackData: ?*anyopaque, pErrors: ?*?*?*DS_REPSYNCALL_ERRINFOA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaSyncAllW( hDS: ?HANDLE, pszNameContext: ?[*:0]const u16, ulFlags: u32, pFnCallBack: isize, pCallbackData: ?*anyopaque, pErrors: ?*?*?*DS_REPSYNCALL_ERRINFOW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsRemoveDsServerW( hDs: ?HANDLE, ServerDN: ?PWSTR, DomainDN: ?PWSTR, fLastDcInDomain: ?*BOOL, fCommit: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsRemoveDsServerA( hDs: ?HANDLE, ServerDN: ?PSTR, DomainDN: ?PSTR, fLastDcInDomain: ?*BOOL, fCommit: BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsRemoveDsDomainW( hDs: ?HANDLE, DomainDN: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsRemoveDsDomainA( hDs: ?HANDLE, DomainDN: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListSitesA( hDs: ?HANDLE, ppSites: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListSitesW( hDs: ?HANDLE, ppSites: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListServersInSiteA( hDs: ?HANDLE, site: ?[*:0]const u8, ppServers: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListServersInSiteW( hDs: ?HANDLE, site: ?[*:0]const u16, ppServers: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListDomainsInSiteA( hDs: ?HANDLE, site: ?[*:0]const u8, ppDomains: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListDomainsInSiteW( hDs: ?HANDLE, site: ?[*:0]const u16, ppDomains: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListServersForDomainInSiteA( hDs: ?HANDLE, domain: ?[*:0]const u8, site: ?[*:0]const u8, ppServers: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListServersForDomainInSiteW( hDs: ?HANDLE, domain: ?[*:0]const u16, site: ?[*:0]const u16, ppServers: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListInfoForServerA( hDs: ?HANDLE, server: ?[*:0]const u8, ppInfo: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListInfoForServerW( hDs: ?HANDLE, server: ?[*:0]const u16, ppInfo: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListRolesA( hDs: ?HANDLE, ppRoles: ?*?*DS_NAME_RESULTA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsListRolesW( hDs: ?HANDLE, ppRoles: ?*?*DS_NAME_RESULTW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsQuerySitesByCostW( hDS: ?HANDLE, pwszFromSite: ?PWSTR, rgwszToSites: [*]?PWSTR, cToSites: u32, dwFlags: u32, prgSiteInfo: ?*?*DS_SITE_COST_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsQuerySitesByCostA( hDS: ?HANDLE, pszFromSite: ?PSTR, rgszToSites: [*]?PSTR, cToSites: u32, dwFlags: u32, prgSiteInfo: ?*?*DS_SITE_COST_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsQuerySitesFree( rgSiteInfo: ?*DS_SITE_COST_INFO, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsMapSchemaGuidsA( hDs: ?HANDLE, cGuids: u32, rGuids: [*]Guid, ppGuidMap: ?*?*DS_SCHEMA_GUID_MAPA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeSchemaGuidMapA( pGuidMap: ?*DS_SCHEMA_GUID_MAPA, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsMapSchemaGuidsW( hDs: ?HANDLE, cGuids: u32, rGuids: [*]Guid, ppGuidMap: ?*?*DS_SCHEMA_GUID_MAPW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeSchemaGuidMapW( pGuidMap: ?*DS_SCHEMA_GUID_MAPW, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsGetDomainControllerInfoA( hDs: ?HANDLE, DomainName: ?[*:0]const u8, InfoLevel: u32, pcOut: ?*u32, ppInfo: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsGetDomainControllerInfoW( hDs: ?HANDLE, DomainName: ?[*:0]const u16, InfoLevel: u32, pcOut: ?*u32, ppInfo: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeDomainControllerInfoA( InfoLevel: u32, cInfo: u32, pInfo: [*]u8, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsFreeDomainControllerInfoW( InfoLevel: u32, cInfo: u32, pInfo: [*]u8, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaConsistencyCheck( hDS: ?HANDLE, TaskID: DS_KCC_TASKID, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaVerifyObjectsW( hDS: ?HANDLE, NameContext: ?[*:0]const u16, pUuidDsaSrc: ?*const Guid, ulOptions: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaVerifyObjectsA( hDS: ?HANDLE, NameContext: ?[*:0]const u8, pUuidDsaSrc: ?*const Guid, ulOptions: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaGetInfoW( hDS: ?HANDLE, InfoType: DS_REPL_INFO_TYPE, pszObject: ?[*:0]const u16, puuidForSourceDsaObjGuid: ?*Guid, ppInfo: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaGetInfo2W( hDS: ?HANDLE, InfoType: DS_REPL_INFO_TYPE, pszObject: ?[*:0]const u16, puuidForSourceDsaObjGuid: ?*Guid, pszAttributeName: ?[*:0]const u16, pszValue: ?[*:0]const u16, dwFlags: u32, dwEnumerationContext: u32, ppInfo: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsReplicaFreeInfo( InfoType: DS_REPL_INFO_TYPE, pInfo: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsAddSidHistoryW( hDS: ?HANDLE, Flags: u32, SrcDomain: ?[*:0]const u16, SrcPrincipal: ?[*:0]const u16, SrcDomainController: ?[*:0]const u16, SrcDomainCreds: ?*anyopaque, DstDomain: ?[*:0]const u16, DstPrincipal: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsAddSidHistoryA( hDS: ?HANDLE, Flags: u32, SrcDomain: ?[*:0]const u8, SrcPrincipal: ?[*:0]const u8, SrcDomainController: ?[*:0]const u8, SrcDomainCreds: ?*anyopaque, DstDomain: ?[*:0]const u8, DstPrincipal: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsInheritSecurityIdentityW( hDS: ?HANDLE, Flags: u32, SrcPrincipal: ?[*:0]const u16, DstPrincipal: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NTDSAPI" fn DsInheritSecurityIdentityA( hDS: ?HANDLE, Flags: u32, SrcPrincipal: ?[*:0]const u8, DstPrincipal: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsRoleGetPrimaryDomainInformation( lpServer: ?[*:0]const u16, InfoLevel: DSROLE_PRIMARY_DOMAIN_INFO_LEVEL, Buffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsRoleFreeMemory( Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcNameA( ComputerName: ?[*:0]const u8, DomainName: ?[*:0]const u8, DomainGuid: ?*Guid, SiteName: ?[*:0]const u8, Flags: u32, DomainControllerInfo: ?*?*DOMAIN_CONTROLLER_INFOA, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcNameW( ComputerName: ?[*:0]const u16, DomainName: ?[*:0]const u16, DomainGuid: ?*Guid, SiteName: ?[*:0]const u16, Flags: u32, DomainControllerInfo: ?*?*DOMAIN_CONTROLLER_INFOW, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetSiteNameA( ComputerName: ?[*:0]const u8, SiteName: ?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetSiteNameW( ComputerName: ?[*:0]const u16, SiteName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsValidateSubnetNameW( SubnetName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsValidateSubnetNameA( SubnetName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsAddressToSiteNamesW( ComputerName: ?[*:0]const u16, EntryCount: u32, SocketAddresses: [*]SOCKET_ADDRESS, SiteNames: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsAddressToSiteNamesA( ComputerName: ?[*:0]const u8, EntryCount: u32, SocketAddresses: [*]SOCKET_ADDRESS, SiteNames: ?*?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsAddressToSiteNamesExW( ComputerName: ?[*:0]const u16, EntryCount: u32, SocketAddresses: [*]SOCKET_ADDRESS, SiteNames: ?*?*?PWSTR, SubnetNames: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsAddressToSiteNamesExA( ComputerName: ?[*:0]const u8, EntryCount: u32, SocketAddresses: [*]SOCKET_ADDRESS, SiteNames: ?*?*?PSTR, SubnetNames: ?*?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsEnumerateDomainTrustsW( ServerName: ?PWSTR, Flags: u32, Domains: ?*?*DS_DOMAIN_TRUSTSW, DomainCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsEnumerateDomainTrustsA( ServerName: ?PSTR, Flags: u32, Domains: ?*?*DS_DOMAIN_TRUSTSA, DomainCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetForestTrustInformationW( ServerName: ?[*:0]const u16, TrustedDomainName: ?[*:0]const u16, Flags: u32, ForestTrustInfo: ?*?*LSA_FOREST_TRUST_INFORMATION, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsMergeForestTrustInformationW( DomainName: ?[*:0]const u16, NewForestTrustInfo: ?*LSA_FOREST_TRUST_INFORMATION, OldForestTrustInfo: ?*LSA_FOREST_TRUST_INFORMATION, MergedForestTrustInfo: ?*?*LSA_FOREST_TRUST_INFORMATION, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcSiteCoverageW( ServerName: ?[*:0]const u16, EntryCount: ?*u32, SiteNames: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcSiteCoverageA( ServerName: ?[*:0]const u8, EntryCount: ?*u32, SiteNames: ?*?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsDeregisterDnsHostRecordsW( ServerName: ?PWSTR, DnsDomainName: ?PWSTR, DomainGuid: ?*Guid, DsaGuid: ?*Guid, DnsHostName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsDeregisterDnsHostRecordsA( ServerName: ?PSTR, DnsDomainName: ?PSTR, DomainGuid: ?*Guid, DsaGuid: ?*Guid, DnsHostName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcOpenW( DnsName: ?[*:0]const u16, OptionFlags: u32, SiteName: ?[*:0]const u16, DomainGuid: ?*Guid, DnsForestName: ?[*:0]const u16, DcFlags: u32, RetGetDcContext: ?*GetDcContextHandle, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcOpenA( DnsName: ?[*:0]const u8, OptionFlags: u32, SiteName: ?[*:0]const u8, DomainGuid: ?*Guid, DnsForestName: ?[*:0]const u8, DcFlags: u32, RetGetDcContext: ?*GetDcContextHandle, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcNextW( GetDcContextHandle: ?HANDLE, SockAddressCount: ?*u32, SockAddresses: ?*?*SOCKET_ADDRESS, DnsHostName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcNextA( GetDcContextHandle: ?HANDLE, SockAddressCount: ?*u32, SockAddresses: ?*?*SOCKET_ADDRESS, DnsHostName: ?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "NETAPI32" fn DsGetDcCloseW( GetDcContextHandle: GetDcContextHandle, ) callconv(@import("std").os.windows.WINAPI) void; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (69) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const DSBROWSEINFO = thismodule.DSBROWSEINFOA; pub const DSBITEM = thismodule.DSBITEMA; pub const DS_NAME_RESULT_ITEM = thismodule.DS_NAME_RESULT_ITEMA; pub const DS_NAME_RESULT = thismodule.DS_NAME_RESULTA; pub const DS_REPSYNCALL_SYNC = thismodule.DS_REPSYNCALL_SYNCA; pub const DS_REPSYNCALL_ERRINFO = thismodule.DS_REPSYNCALL_ERRINFOA; pub const DS_REPSYNCALL_UPDATE = thismodule.DS_REPSYNCALL_UPDATEA; pub const DS_SCHEMA_GUID_MAP = thismodule.DS_SCHEMA_GUID_MAPA; pub const DS_DOMAIN_CONTROLLER_INFO_1 = thismodule.DS_DOMAIN_CONTROLLER_INFO_1A; pub const DS_DOMAIN_CONTROLLER_INFO_2 = thismodule.DS_DOMAIN_CONTROLLER_INFO_2A; pub const DS_DOMAIN_CONTROLLER_INFO_3 = thismodule.DS_DOMAIN_CONTROLLER_INFO_3A; pub const DOMAIN_CONTROLLER_INFO = thismodule.DOMAIN_CONTROLLER_INFOA; pub const DS_DOMAIN_TRUSTS = thismodule.DS_DOMAIN_TRUSTSA; pub const DsBrowseForContainer = thismodule.DsBrowseForContainerA; pub const DsMakeSpn = thismodule.DsMakeSpnA; pub const DsCrackSpn = thismodule.DsCrackSpnA; pub const DsQuoteRdnValue = thismodule.DsQuoteRdnValueA; pub const DsUnquoteRdnValue = thismodule.DsUnquoteRdnValueA; pub const DsCrackUnquotedMangledRdn = thismodule.DsCrackUnquotedMangledRdnA; pub const DsIsMangledRdnValue = thismodule.DsIsMangledRdnValueA; pub const DsIsMangledDn = thismodule.DsIsMangledDnA; pub const DsCrackSpn2 = thismodule.DsCrackSpn2A; pub const DsBind = thismodule.DsBindA; pub const DsBindWithCred = thismodule.DsBindWithCredA; pub const DsBindWithSpn = thismodule.DsBindWithSpnA; pub const DsBindWithSpnEx = thismodule.DsBindWithSpnExA; pub const DsBindByInstance = thismodule.DsBindByInstanceA; pub const DsBindToISTG = thismodule.DsBindToISTGA; pub const DsUnBind = thismodule.DsUnBindA; pub const DsMakePasswordCredentials = thismodule.DsMakePasswordCredentialsA; pub const DsCrackNames = thismodule.DsCrackNamesA; pub const DsFreeNameResult = thismodule.DsFreeNameResultA; pub const DsGetSpn = thismodule.DsGetSpnA; pub const DsFreeSpnArray = thismodule.DsFreeSpnArrayA; pub const DsWriteAccountSpn = thismodule.DsWriteAccountSpnA; pub const DsClientMakeSpnForTargetServer = thismodule.DsClientMakeSpnForTargetServerA; pub const DsServerRegisterSpn = thismodule.DsServerRegisterSpnA; pub const DsReplicaSync = thismodule.DsReplicaSyncA; pub const DsReplicaAdd = thismodule.DsReplicaAddA; pub const DsReplicaDel = thismodule.DsReplicaDelA; pub const DsReplicaModify = thismodule.DsReplicaModifyA; pub const DsReplicaUpdateRefs = thismodule.DsReplicaUpdateRefsA; pub const DsReplicaSyncAll = thismodule.DsReplicaSyncAllA; pub const DsRemoveDsServer = thismodule.DsRemoveDsServerA; pub const DsRemoveDsDomain = thismodule.DsRemoveDsDomainA; pub const DsListSites = thismodule.DsListSitesA; pub const DsListServersInSite = thismodule.DsListServersInSiteA; pub const DsListDomainsInSite = thismodule.DsListDomainsInSiteA; pub const DsListServersForDomainInSite = thismodule.DsListServersForDomainInSiteA; pub const DsListInfoForServer = thismodule.DsListInfoForServerA; pub const DsListRoles = thismodule.DsListRolesA; pub const DsQuerySitesByCost = thismodule.DsQuerySitesByCostA; pub const DsMapSchemaGuids = thismodule.DsMapSchemaGuidsA; pub const DsFreeSchemaGuidMap = thismodule.DsFreeSchemaGuidMapA; pub const DsGetDomainControllerInfo = thismodule.DsGetDomainControllerInfoA; pub const DsFreeDomainControllerInfo = thismodule.DsFreeDomainControllerInfoA; pub const DsReplicaVerifyObjects = thismodule.DsReplicaVerifyObjectsA; pub const DsAddSidHistory = thismodule.DsAddSidHistoryA; pub const DsInheritSecurityIdentity = thismodule.DsInheritSecurityIdentityA; pub const DsGetDcName = thismodule.DsGetDcNameA; pub const DsGetSiteName = thismodule.DsGetSiteNameA; pub const DsValidateSubnetName = thismodule.DsValidateSubnetNameA; pub const DsAddressToSiteNames = thismodule.DsAddressToSiteNamesA; pub const DsAddressToSiteNamesEx = thismodule.DsAddressToSiteNamesExA; pub const DsEnumerateDomainTrusts = thismodule.DsEnumerateDomainTrustsA; pub const DsGetDcSiteCoverage = thismodule.DsGetDcSiteCoverageA; pub const DsDeregisterDnsHostRecords = thismodule.DsDeregisterDnsHostRecordsA; pub const DsGetDcOpen = thismodule.DsGetDcOpenA; pub const DsGetDcNext = thismodule.DsGetDcNextA; }, .wide => struct { pub const DSBROWSEINFO = thismodule.DSBROWSEINFOW; pub const DSBITEM = thismodule.DSBITEMW; pub const DS_NAME_RESULT_ITEM = thismodule.DS_NAME_RESULT_ITEMW; pub const DS_NAME_RESULT = thismodule.DS_NAME_RESULTW; pub const DS_REPSYNCALL_SYNC = thismodule.DS_REPSYNCALL_SYNCW; pub const DS_REPSYNCALL_ERRINFO = thismodule.DS_REPSYNCALL_ERRINFOW; pub const DS_REPSYNCALL_UPDATE = thismodule.DS_REPSYNCALL_UPDATEW; pub const DS_SCHEMA_GUID_MAP = thismodule.DS_SCHEMA_GUID_MAPW; pub const DS_DOMAIN_CONTROLLER_INFO_1 = thismodule.DS_DOMAIN_CONTROLLER_INFO_1W; pub const DS_DOMAIN_CONTROLLER_INFO_2 = thismodule.DS_DOMAIN_CONTROLLER_INFO_2W; pub const DS_DOMAIN_CONTROLLER_INFO_3 = thismodule.DS_DOMAIN_CONTROLLER_INFO_3W; pub const DOMAIN_CONTROLLER_INFO = thismodule.DOMAIN_CONTROLLER_INFOW; pub const DS_DOMAIN_TRUSTS = thismodule.DS_DOMAIN_TRUSTSW; pub const DsBrowseForContainer = thismodule.DsBrowseForContainerW; pub const DsMakeSpn = thismodule.DsMakeSpnW; pub const DsCrackSpn = thismodule.DsCrackSpnW; pub const DsQuoteRdnValue = thismodule.DsQuoteRdnValueW; pub const DsUnquoteRdnValue = thismodule.DsUnquoteRdnValueW; pub const DsCrackUnquotedMangledRdn = thismodule.DsCrackUnquotedMangledRdnW; pub const DsIsMangledRdnValue = thismodule.DsIsMangledRdnValueW; pub const DsIsMangledDn = thismodule.DsIsMangledDnW; pub const DsCrackSpn2 = thismodule.DsCrackSpn2W; pub const DsBind = thismodule.DsBindW; pub const DsBindWithCred = thismodule.DsBindWithCredW; pub const DsBindWithSpn = thismodule.DsBindWithSpnW; pub const DsBindWithSpnEx = thismodule.DsBindWithSpnExW; pub const DsBindByInstance = thismodule.DsBindByInstanceW; pub const DsBindToISTG = thismodule.DsBindToISTGW; pub const DsUnBind = thismodule.DsUnBindW; pub const DsMakePasswordCredentials = thismodule.DsMakePasswordCredentialsW; pub const DsCrackNames = thismodule.DsCrackNamesW; pub const DsFreeNameResult = thismodule.DsFreeNameResultW; pub const DsGetSpn = thismodule.DsGetSpnW; pub const DsFreeSpnArray = thismodule.DsFreeSpnArrayW; pub const DsWriteAccountSpn = thismodule.DsWriteAccountSpnW; pub const DsClientMakeSpnForTargetServer = thismodule.DsClientMakeSpnForTargetServerW; pub const DsServerRegisterSpn = thismodule.DsServerRegisterSpnW; pub const DsReplicaSync = thismodule.DsReplicaSyncW; pub const DsReplicaAdd = thismodule.DsReplicaAddW; pub const DsReplicaDel = thismodule.DsReplicaDelW; pub const DsReplicaModify = thismodule.DsReplicaModifyW; pub const DsReplicaUpdateRefs = thismodule.DsReplicaUpdateRefsW; pub const DsReplicaSyncAll = thismodule.DsReplicaSyncAllW; pub const DsRemoveDsServer = thismodule.DsRemoveDsServerW; pub const DsRemoveDsDomain = thismodule.DsRemoveDsDomainW; pub const DsListSites = thismodule.DsListSitesW; pub const DsListServersInSite = thismodule.DsListServersInSiteW; pub const DsListDomainsInSite = thismodule.DsListDomainsInSiteW; pub const DsListServersForDomainInSite = thismodule.DsListServersForDomainInSiteW; pub const DsListInfoForServer = thismodule.DsListInfoForServerW; pub const DsListRoles = thismodule.DsListRolesW; pub const DsQuerySitesByCost = thismodule.DsQuerySitesByCostW; pub const DsMapSchemaGuids = thismodule.DsMapSchemaGuidsW; pub const DsFreeSchemaGuidMap = thismodule.DsFreeSchemaGuidMapW; pub const DsGetDomainControllerInfo = thismodule.DsGetDomainControllerInfoW; pub const DsFreeDomainControllerInfo = thismodule.DsFreeDomainControllerInfoW; pub const DsReplicaVerifyObjects = thismodule.DsReplicaVerifyObjectsW; pub const DsAddSidHistory = thismodule.DsAddSidHistoryW; pub const DsInheritSecurityIdentity = thismodule.DsInheritSecurityIdentityW; pub const DsGetDcName = thismodule.DsGetDcNameW; pub const DsGetSiteName = thismodule.DsGetSiteNameW; pub const DsValidateSubnetName = thismodule.DsValidateSubnetNameW; pub const DsAddressToSiteNames = thismodule.DsAddressToSiteNamesW; pub const DsAddressToSiteNamesEx = thismodule.DsAddressToSiteNamesExW; pub const DsEnumerateDomainTrusts = thismodule.DsEnumerateDomainTrustsW; pub const DsGetDcSiteCoverage = thismodule.DsGetDcSiteCoverageW; pub const DsDeregisterDnsHostRecords = thismodule.DsDeregisterDnsHostRecordsW; pub const DsGetDcOpen = thismodule.DsGetDcOpenW; pub const DsGetDcNext = thismodule.DsGetDcNextW; }, .unspecified => if (@import("builtin").is_test) struct { pub const DSBROWSEINFO = *opaque{}; pub const DSBITEM = *opaque{}; pub const DS_NAME_RESULT_ITEM = *opaque{}; pub const DS_NAME_RESULT = *opaque{}; pub const DS_REPSYNCALL_SYNC = *opaque{}; pub const DS_REPSYNCALL_ERRINFO = *opaque{}; pub const DS_REPSYNCALL_UPDATE = *opaque{}; pub const DS_SCHEMA_GUID_MAP = *opaque{}; pub const DS_DOMAIN_CONTROLLER_INFO_1 = *opaque{}; pub const DS_DOMAIN_CONTROLLER_INFO_2 = *opaque{}; pub const DS_DOMAIN_CONTROLLER_INFO_3 = *opaque{}; pub const DOMAIN_CONTROLLER_INFO = *opaque{}; pub const DS_DOMAIN_TRUSTS = *opaque{}; pub const DsBrowseForContainer = *opaque{}; pub const DsMakeSpn = *opaque{}; pub const DsCrackSpn = *opaque{}; pub const DsQuoteRdnValue = *opaque{}; pub const DsUnquoteRdnValue = *opaque{}; pub const DsCrackUnquotedMangledRdn = *opaque{}; pub const DsIsMangledRdnValue = *opaque{}; pub const DsIsMangledDn = *opaque{}; pub const DsCrackSpn2 = *opaque{}; pub const DsBind = *opaque{}; pub const DsBindWithCred = *opaque{}; pub const DsBindWithSpn = *opaque{}; pub const DsBindWithSpnEx = *opaque{}; pub const DsBindByInstance = *opaque{}; pub const DsBindToISTG = *opaque{}; pub const DsUnBind = *opaque{}; pub const DsMakePasswordCredentials = *opaque{}; pub const DsCrackNames = *opaque{}; pub const DsFreeNameResult = *opaque{}; pub const DsGetSpn = *opaque{}; pub const DsFreeSpnArray = *opaque{}; pub const DsWriteAccountSpn = *opaque{}; pub const DsClientMakeSpnForTargetServer = *opaque{}; pub const DsServerRegisterSpn = *opaque{}; pub const DsReplicaSync = *opaque{}; pub const DsReplicaAdd = *opaque{}; pub const DsReplicaDel = *opaque{}; pub const DsReplicaModify = *opaque{}; pub const DsReplicaUpdateRefs = *opaque{}; pub const DsReplicaSyncAll = *opaque{}; pub const DsRemoveDsServer = *opaque{}; pub const DsRemoveDsDomain = *opaque{}; pub const DsListSites = *opaque{}; pub const DsListServersInSite = *opaque{}; pub const DsListDomainsInSite = *opaque{}; pub const DsListServersForDomainInSite = *opaque{}; pub const DsListInfoForServer = *opaque{}; pub const DsListRoles = *opaque{}; pub const DsQuerySitesByCost = *opaque{}; pub const DsMapSchemaGuids = *opaque{}; pub const DsFreeSchemaGuidMap = *opaque{}; pub const DsGetDomainControllerInfo = *opaque{}; pub const DsFreeDomainControllerInfo = *opaque{}; pub const DsReplicaVerifyObjects = *opaque{}; pub const DsAddSidHistory = *opaque{}; pub const DsInheritSecurityIdentity = *opaque{}; pub const DsGetDcName = *opaque{}; pub const DsGetSiteName = *opaque{}; pub const DsValidateSubnetName = *opaque{}; pub const DsAddressToSiteNames = *opaque{}; pub const DsAddressToSiteNamesEx = *opaque{}; pub const DsEnumerateDomainTrusts = *opaque{}; pub const DsGetDcSiteCoverage = *opaque{}; pub const DsDeregisterDnsHostRecords = *opaque{}; pub const DsGetDcOpen = *opaque{}; pub const DsGetDcNext = *opaque{}; } else struct { pub const DSBROWSEINFO = @compileError("'DSBROWSEINFO' requires that UNICODE be set to true or false in the root module"); pub const DSBITEM = @compileError("'DSBITEM' requires that UNICODE be set to true or false in the root module"); pub const DS_NAME_RESULT_ITEM = @compileError("'DS_NAME_RESULT_ITEM' requires that UNICODE be set to true or false in the root module"); pub const DS_NAME_RESULT = @compileError("'DS_NAME_RESULT' requires that UNICODE be set to true or false in the root module"); pub const DS_REPSYNCALL_SYNC = @compileError("'DS_REPSYNCALL_SYNC' requires that UNICODE be set to true or false in the root module"); pub const DS_REPSYNCALL_ERRINFO = @compileError("'DS_REPSYNCALL_ERRINFO' requires that UNICODE be set to true or false in the root module"); pub const DS_REPSYNCALL_UPDATE = @compileError("'DS_REPSYNCALL_UPDATE' requires that UNICODE be set to true or false in the root module"); pub const DS_SCHEMA_GUID_MAP = @compileError("'DS_SCHEMA_GUID_MAP' requires that UNICODE be set to true or false in the root module"); pub const DS_DOMAIN_CONTROLLER_INFO_1 = @compileError("'DS_DOMAIN_CONTROLLER_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const DS_DOMAIN_CONTROLLER_INFO_2 = @compileError("'DS_DOMAIN_CONTROLLER_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const DS_DOMAIN_CONTROLLER_INFO_3 = @compileError("'DS_DOMAIN_CONTROLLER_INFO_3' requires that UNICODE be set to true or false in the root module"); pub const DOMAIN_CONTROLLER_INFO = @compileError("'DOMAIN_CONTROLLER_INFO' requires that UNICODE be set to true or false in the root module"); pub const DS_DOMAIN_TRUSTS = @compileError("'DS_DOMAIN_TRUSTS' requires that UNICODE be set to true or false in the root module"); pub const DsBrowseForContainer = @compileError("'DsBrowseForContainer' requires that UNICODE be set to true or false in the root module"); pub const DsMakeSpn = @compileError("'DsMakeSpn' requires that UNICODE be set to true or false in the root module"); pub const DsCrackSpn = @compileError("'DsCrackSpn' requires that UNICODE be set to true or false in the root module"); pub const DsQuoteRdnValue = @compileError("'DsQuoteRdnValue' requires that UNICODE be set to true or false in the root module"); pub const DsUnquoteRdnValue = @compileError("'DsUnquoteRdnValue' requires that UNICODE be set to true or false in the root module"); pub const DsCrackUnquotedMangledRdn = @compileError("'DsCrackUnquotedMangledRdn' requires that UNICODE be set to true or false in the root module"); pub const DsIsMangledRdnValue = @compileError("'DsIsMangledRdnValue' requires that UNICODE be set to true or false in the root module"); pub const DsIsMangledDn = @compileError("'DsIsMangledDn' requires that UNICODE be set to true or false in the root module"); pub const DsCrackSpn2 = @compileError("'DsCrackSpn2' requires that UNICODE be set to true or false in the root module"); pub const DsBind = @compileError("'DsBind' requires that UNICODE be set to true or false in the root module"); pub const DsBindWithCred = @compileError("'DsBindWithCred' requires that UNICODE be set to true or false in the root module"); pub const DsBindWithSpn = @compileError("'DsBindWithSpn' requires that UNICODE be set to true or false in the root module"); pub const DsBindWithSpnEx = @compileError("'DsBindWithSpnEx' requires that UNICODE be set to true or false in the root module"); pub const DsBindByInstance = @compileError("'DsBindByInstance' requires that UNICODE be set to true or false in the root module"); pub const DsBindToISTG = @compileError("'DsBindToISTG' requires that UNICODE be set to true or false in the root module"); pub const DsUnBind = @compileError("'DsUnBind' requires that UNICODE be set to true or false in the root module"); pub const DsMakePasswordCredentials = @compileError("'DsMakePasswordCredentials' requires that UNICODE be set to true or false in the root module"); pub const DsCrackNames = @compileError("'DsCrackNames' requires that UNICODE be set to true or false in the root module"); pub const DsFreeNameResult = @compileError("'DsFreeNameResult' requires that UNICODE be set to true or false in the root module"); pub const DsGetSpn = @compileError("'DsGetSpn' requires that UNICODE be set to true or false in the root module"); pub const DsFreeSpnArray = @compileError("'DsFreeSpnArray' requires that UNICODE be set to true or false in the root module"); pub const DsWriteAccountSpn = @compileError("'DsWriteAccountSpn' requires that UNICODE be set to true or false in the root module"); pub const DsClientMakeSpnForTargetServer = @compileError("'DsClientMakeSpnForTargetServer' requires that UNICODE be set to true or false in the root module"); pub const DsServerRegisterSpn = @compileError("'DsServerRegisterSpn' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaSync = @compileError("'DsReplicaSync' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaAdd = @compileError("'DsReplicaAdd' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaDel = @compileError("'DsReplicaDel' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaModify = @compileError("'DsReplicaModify' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaUpdateRefs = @compileError("'DsReplicaUpdateRefs' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaSyncAll = @compileError("'DsReplicaSyncAll' requires that UNICODE be set to true or false in the root module"); pub const DsRemoveDsServer = @compileError("'DsRemoveDsServer' requires that UNICODE be set to true or false in the root module"); pub const DsRemoveDsDomain = @compileError("'DsRemoveDsDomain' requires that UNICODE be set to true or false in the root module"); pub const DsListSites = @compileError("'DsListSites' requires that UNICODE be set to true or false in the root module"); pub const DsListServersInSite = @compileError("'DsListServersInSite' requires that UNICODE be set to true or false in the root module"); pub const DsListDomainsInSite = @compileError("'DsListDomainsInSite' requires that UNICODE be set to true or false in the root module"); pub const DsListServersForDomainInSite = @compileError("'DsListServersForDomainInSite' requires that UNICODE be set to true or false in the root module"); pub const DsListInfoForServer = @compileError("'DsListInfoForServer' requires that UNICODE be set to true or false in the root module"); pub const DsListRoles = @compileError("'DsListRoles' requires that UNICODE be set to true or false in the root module"); pub const DsQuerySitesByCost = @compileError("'DsQuerySitesByCost' requires that UNICODE be set to true or false in the root module"); pub const DsMapSchemaGuids = @compileError("'DsMapSchemaGuids' requires that UNICODE be set to true or false in the root module"); pub const DsFreeSchemaGuidMap = @compileError("'DsFreeSchemaGuidMap' requires that UNICODE be set to true or false in the root module"); pub const DsGetDomainControllerInfo = @compileError("'DsGetDomainControllerInfo' requires that UNICODE be set to true or false in the root module"); pub const DsFreeDomainControllerInfo = @compileError("'DsFreeDomainControllerInfo' requires that UNICODE be set to true or false in the root module"); pub const DsReplicaVerifyObjects = @compileError("'DsReplicaVerifyObjects' requires that UNICODE be set to true or false in the root module"); pub const DsAddSidHistory = @compileError("'DsAddSidHistory' requires that UNICODE be set to true or false in the root module"); pub const DsInheritSecurityIdentity = @compileError("'DsInheritSecurityIdentity' requires that UNICODE be set to true or false in the root module"); pub const DsGetDcName = @compileError("'DsGetDcName' requires that UNICODE be set to true or false in the root module"); pub const DsGetSiteName = @compileError("'DsGetSiteName' requires that UNICODE be set to true or false in the root module"); pub const DsValidateSubnetName = @compileError("'DsValidateSubnetName' requires that UNICODE be set to true or false in the root module"); pub const DsAddressToSiteNames = @compileError("'DsAddressToSiteNames' requires that UNICODE be set to true or false in the root module"); pub const DsAddressToSiteNamesEx = @compileError("'DsAddressToSiteNamesEx' requires that UNICODE be set to true or false in the root module"); pub const DsEnumerateDomainTrusts = @compileError("'DsEnumerateDomainTrusts' requires that UNICODE be set to true or false in the root module"); pub const DsGetDcSiteCoverage = @compileError("'DsGetDcSiteCoverage' requires that UNICODE be set to true or false in the root module"); pub const DsDeregisterDnsHostRecords = @compileError("'DsDeregisterDnsHostRecords' requires that UNICODE be set to true or false in the root module"); pub const DsGetDcOpen = @compileError("'DsGetDcOpen' requires that UNICODE be set to true or false in the root module"); pub const DsGetDcNext = @compileError("'DsGetDcNext' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (35) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BFFCALLBACK = @import("../ui/shell.zig").BFFCALLBACK; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const BSTR = @import("../foundation.zig").BSTR; const CHAR = @import("../foundation.zig").CHAR; const DISPPARAMS = @import("../system/com.zig").DISPPARAMS; const DLGPROC = @import("../ui/windows_and_messaging.zig").DLGPROC; const EXCEPINFO = @import("../system/com.zig").EXCEPINFO; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HICON = @import("../ui/windows_and_messaging.zig").HICON; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HKEY = @import("../system/registry.zig").HKEY; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDataObject = @import("../system/com.zig").IDataObject; const IDispatch = @import("../system/com.zig").IDispatch; const IEnumVARIANT = @import("../system/ole.zig").IEnumVARIANT; const IPersist = @import("../system/com.zig").IPersist; const IPropertyBag = @import("../system/com/structured_storage.zig").IPropertyBag; const ITypeInfo = @import("../system/com.zig").ITypeInfo; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const LPARAM = @import("../foundation.zig").LPARAM; const LPFNSVADDPROPSHEETPAGE = @import("../ui/controls.zig").LPFNSVADDPROPSHEETPAGE; const LSA_FOREST_TRUST_INFORMATION = @import("../security/authentication/identity.zig").LSA_FOREST_TRUST_INFORMATION; const PSID = @import("../foundation.zig").PSID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; const SOCKET_ADDRESS = @import("../networking/win_sock.zig").SOCKET_ADDRESS; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; const VARIANT = @import("../system/com.zig").VARIANT; const WPARAM = @import("../foundation.zig").WPARAM; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPCQADDFORMSPROC")) { _ = LPCQADDFORMSPROC; } if (@hasDecl(@This(), "LPCQADDPAGESPROC")) { _ = LPCQADDPAGESPROC; } if (@hasDecl(@This(), "LPCQPAGEPROC")) { _ = LPCQPAGEPROC; } if (@hasDecl(@This(), "LPDSENUMATTRIBUTES")) { _ = LPDSENUMATTRIBUTES; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/networking/active_directory.zig
const std = @import("std"); const assert = std.debug.assert; const mem = std.mem; const Allocator = mem.Allocator; const math = std.math; const maxInt = math.maxInt; const vk = @import("vk.zig"); const glfw = @import("glfw.zig"); const util = @import("util.zig"); const arrayPtr = util.arrayPtr; const emptySlice = util.emptySlice; const geo = @import("geo/geo.zig"); const Vec2 = geo.Vec2; const Vec3 = geo.Vec3; const Vec4 = geo.Vec4; const Rotor3 = geo.Rotor3; const Mat3 = geo.Mat3; const Mat4 = geo.Mat4; const colors = @import("color.zig"); const Color3f = colors.Color3f; const WIDTH = 800; const HEIGHT = 600; const MAX_FRAMES_IN_FLIGHT = 2; const enableValidationLayers = std.debug.runtime_safety; const validationLayers = [_]vk.CString{"VK_LAYER_LUNARG_standard_validation"}; const deviceExtensions = [_]vk.CString{vk.KHR_SWAPCHAIN_EXTENSION_NAME}; const vertexData = [_]Vertex{ Vertex.init(Vec2.init(0.5, -0.5), Color3f.init(1, 0.5, 0)), Vertex.init(Vec2.init(0.5, 0.5), Color3f.init(0, 1, 1)), Vertex.init(Vec2.init(-0.5, 0.5), Color3f.init(0.5, 0, 1)), Vertex.init(Vec2.init(-0.5, 0.5), Color3f.init(0.5, 0, 1)), Vertex.init(Vec2.init(-0.5, -0.5), Color3f.init(0, 1, 1)), Vertex.init(Vec2.init(0.5, -0.5), Color3f.init(1, 0.5, 0)), }; var currentFrame: usize = 0; var instance: vk.Instance = undefined; var callback: vk.DebugReportCallbackEXT = undefined; var surface: vk.SurfaceKHR = undefined; var physicalDevice: vk.PhysicalDevice = undefined; var global_device: vk.Device = undefined; var graphicsQueue: vk.Queue = undefined; var presentQueue: vk.Queue = undefined; var swapChainImages: []vk.Image = undefined; var swapChain: vk.SwapchainKHR = undefined; var swapChainImageFormat: vk.Format = undefined; var swapChainExtent: vk.Extent2D = undefined; var swapChainImageViews: []vk.ImageView = undefined; var renderPass: vk.RenderPass = undefined; var descriptorSetLayouts: [1]vk.DescriptorSetLayout = undefined; var descriptorPool: vk.DescriptorPool = undefined; var descriptorSets: []vk.DescriptorSet = undefined; var uniformBuffers: []vk.Buffer = undefined; var uniformBuffersMemory: []vk.DeviceMemory = undefined; var pipelineLayout: vk.PipelineLayout = undefined; var graphicsPipeline: vk.Pipeline = undefined; var swapChainFramebuffers: []vk.Framebuffer = undefined; var commandPool: vk.CommandPool = undefined; var commandBuffers: []vk.CommandBuffer = undefined; var vertexBuffer: vk.Buffer = undefined; var vertexBufferMemory: vk.DeviceMemory = undefined; var imageAvailableSemaphores: [MAX_FRAMES_IN_FLIGHT]vk.Semaphore = undefined; var renderFinishedSemaphores: [MAX_FRAMES_IN_FLIGHT]vk.Semaphore = undefined; var inFlightFences: [MAX_FRAMES_IN_FLIGHT]vk.Fence = undefined; var startupTimeMillis: u64 = undefined; fn currentTime() f32 { // TODO: This is not monotonic. It will fail on leap years or other // cases where computer time stops or goes backwards. It also can't // handle extremely long run durations and has trouble with hibernation. return @intToFloat(f32, std.time.milliTimestamp() - startupTimeMillis) * 0.001; } const Vertex = extern struct { pos: Vec2, color: Color3f, pub fn init(pos: Vec2, color: Color3f) Vertex { return .{ .pos = pos, .color = color, }; } const BindingDescriptions = [_]vk.VertexInputBindingDescription{.{ .binding = 0, .stride = @sizeOf(Vertex), .inputRate = .VERTEX, }}; const AttributeDescriptions = [_]vk.VertexInputAttributeDescription{ .{ .binding = 0, .location = 0, .format = .R32G32_SFLOAT, .offset = @byteOffsetOf(Vertex, "pos"), }, .{ .binding = 0, .location = 1, .format = .R32G32B32_SFLOAT, .offset = @byteOffsetOf(Vertex, "color"), }, }; }; const UniformBufferObject = extern struct { model: Mat4, view: Mat4, proj: Mat4, }; const QueueFamilyIndices = struct { graphicsFamily: ?u32, presentFamily: ?u32, fn init() QueueFamilyIndices { return .{ .graphicsFamily = null, .presentFamily = null, }; } fn isComplete(self: QueueFamilyIndices) bool { return self.graphicsFamily != null and self.presentFamily != null; } }; const SwapChainSupportDetails = struct { capabilities: vk.SurfaceCapabilitiesKHR, formats: std.ArrayList(vk.SurfaceFormatKHR), presentModes: std.ArrayList(vk.PresentModeKHR), fn init(allocator: *Allocator) SwapChainSupportDetails { return .{ .capabilities = mem.zeroes(vk.SurfaceCapabilitiesKHR), .formats = std.ArrayList(vk.SurfaceFormatKHR).init(allocator), .presentModes = std.ArrayList(vk.PresentModeKHR).init(allocator), }; } fn deinit(self: *SwapChainSupportDetails) void { self.formats.deinit(); self.presentModes.deinit(); } }; pub fn main() !void { startupTimeMillis = std.time.milliTimestamp(); if (glfw.glfwInit() == 0) return error.GlfwInitFailed; defer glfw.glfwTerminate(); glfw.glfwWindowHint(glfw.GLFW_CLIENT_API, glfw.GLFW_NO_API); glfw.glfwWindowHint(glfw.GLFW_RESIZABLE, glfw.GLFW_FALSE); const window = glfw.glfwCreateWindow(WIDTH, HEIGHT, "Zig Vulkan Triangle", null, null) orelse return error.GlfwCreateWindowFailed; defer glfw.glfwDestroyWindow(window); const allocator = std.heap.c_allocator; try initVulkan(allocator, window); while (glfw.glfwWindowShouldClose(window) == 0) { glfw.glfwPollEvents(); try drawFrame(); } try vk.DeviceWaitIdle(global_device); cleanup(); } fn cleanup() void { var i: usize = 0; while (i < MAX_FRAMES_IN_FLIGHT) : (i += 1) { vk.DestroySemaphore(global_device, renderFinishedSemaphores[i], null); vk.DestroySemaphore(global_device, imageAvailableSemaphores[i], null); vk.DestroyFence(global_device, inFlightFences[i], null); } vk.DestroyCommandPool(global_device, commandPool, null); for (swapChainFramebuffers) |framebuffer| { vk.DestroyFramebuffer(global_device, framebuffer, null); } vk.DestroyPipeline(global_device, graphicsPipeline, null); vk.DestroyPipelineLayout(global_device, pipelineLayout, null); vk.DestroyRenderPass(global_device, renderPass, null); for (swapChainImageViews) |imageView| { vk.DestroyImageView(global_device, imageView, null); } vk.DestroySwapchainKHR(global_device, swapChain, null); for (uniformBuffers) |buffer| { vk.DestroyBuffer(global_device, buffer, null); } for (uniformBuffersMemory) |uniformMem| { vk.FreeMemory(global_device, uniformMem, null); } vk.DestroyDescriptorPool(global_device, descriptorPool, null); vk.DestroyDescriptorSetLayout(global_device, descriptorSetLayouts[0], null); vk.DestroyBuffer(global_device, vertexBuffer, null); vk.FreeMemory(global_device, vertexBufferMemory, null); vk.DestroyDevice(global_device, null); if (enableValidationLayers) { DestroyDebugReportCallbackEXT(null); } vk.DestroySurfaceKHR(instance, surface, null); vk.DestroyInstance(instance, null); } fn initVulkan(allocator: *Allocator, window: *glfw.GLFWwindow) !void { try createInstance(allocator); try setupDebugCallback(); try createSurface(window); try pickPhysicalDevice(allocator); try createLogicalDevice(allocator); try createSwapChain(allocator); try createImageViews(allocator); try createRenderPass(); try createDescriptorSetLayout(); try createGraphicsPipeline(allocator); try createFramebuffers(allocator); try createCommandPool(allocator); try createVertexBuffer(allocator); try createUniformBuffers(allocator); try createDescriptorPool(); try createDescriptorSets(allocator); try createCommandBuffers(allocator); try createSyncObjects(); } fn findMemoryType(typeFilter: u32, properties: vk.MemoryPropertyFlags) !u32 { var memProperties = vk.GetPhysicalDeviceMemoryProperties(physicalDevice); var i: u32 = 0; while (i < memProperties.memoryTypeCount) : (i += 1) { if ((typeFilter & (@as(u32, 1) << @intCast(u5, i))) != 0 and memProperties.memoryTypes[i].propertyFlags.hasAllSet(properties)) return i; } return error.NoSuitableMemory; } fn createBuffer(size: vk.DeviceSize, usage: vk.BufferUsageFlags, properties: vk.MemoryPropertyFlags, outBuffer: *vk.Buffer, outBufferMemory: *vk.DeviceMemory) !void { const bufferInfo = vk.BufferCreateInfo{ .size = size, .usage = usage, .sharingMode = .EXCLUSIVE, }; var buffer = try vk.CreateBuffer(global_device, bufferInfo, null); var memRequirements = vk.GetBufferMemoryRequirements(global_device, buffer); const allocInfo = vk.MemoryAllocateInfo{ .allocationSize = memRequirements.size, .memoryTypeIndex = try findMemoryType(memRequirements.memoryTypeBits, properties), }; var bufferMemory = try vk.AllocateMemory(global_device, allocInfo, null); try vk.BindBufferMemory(global_device, buffer, bufferMemory, 0); outBuffer.* = buffer; outBufferMemory.* = bufferMemory; } fn copyBuffer(srcBuffer: vk.Buffer, dstBuffer: vk.Buffer, size: vk.DeviceSize) !void { const allocInfo = vk.CommandBufferAllocateInfo{ .level = .PRIMARY, .commandPool = commandPool, .commandBufferCount = 1, }; var commandBuffer: vk.CommandBuffer = undefined; try vk.AllocateCommandBuffers(global_device, allocInfo, arrayPtr(&commandBuffer)); const beginInfo = vk.CommandBufferBeginInfo{ .flags = .{ .oneTimeSubmit = true }, .pInheritanceInfo = null, }; try vk.BeginCommandBuffer(commandBuffer, beginInfo); const copyRegion = vk.BufferCopy{ .srcOffset = 0, .dstOffset = 0, .size = size, }; vk.CmdCopyBuffer(commandBuffer, srcBuffer, dstBuffer, arrayPtr(&copyRegion)); try vk.EndCommandBuffer(commandBuffer); const submitInfo = vk.SubmitInfo{ .commandBufferCount = 1, .pCommandBuffers = arrayPtr(&commandBuffer), }; try vk.QueueSubmit(graphicsQueue, arrayPtr(&submitInfo), null); try vk.QueueWaitIdle(graphicsQueue); vk.FreeCommandBuffers(global_device, commandPool, arrayPtr(&commandBuffer)); } fn createVertexBuffer(allocator: *Allocator) !void { const bufferSize: vk.DeviceSize = @sizeOf(@TypeOf(vertexData)); var stagingBuffer: vk.Buffer = undefined; var stagingBufferMemory: vk.DeviceMemory = undefined; try createBuffer( bufferSize, .{ .transferSrc = true }, .{ .hostVisible = true, .hostCoherent = true }, &stagingBuffer, &stagingBufferMemory, ); var data: *c_void = undefined; try vk.MapMemory(global_device, stagingBufferMemory, 0, bufferSize, .{}, &data); @memcpy(@ptrCast([*]u8, data), @ptrCast([*]const u8, &vertexData), bufferSize); vk.UnmapMemory(global_device, stagingBufferMemory); try createBuffer( bufferSize, .{ .transferDst = true, .vertexBuffer = true }, .{ .deviceLocal = true }, &vertexBuffer, &vertexBufferMemory, ); try copyBuffer(stagingBuffer, vertexBuffer, bufferSize); vk.DestroyBuffer(global_device, stagingBuffer, null); vk.FreeMemory(global_device, stagingBufferMemory, null); } fn createUniformBuffers(allocator: *Allocator) !void { const bufferSize = @as(vk.DeviceSize, @sizeOf(UniformBufferObject)); uniformBuffers = try allocator.alloc(vk.Buffer, swapChainImages.len); uniformBuffersMemory = try allocator.alloc(vk.DeviceMemory, swapChainImages.len); for (uniformBuffers) |*buffer, i| { try createBuffer( bufferSize, .{ .uniformBuffer = true }, .{ .hostVisible = true, .hostCoherent = true }, buffer, &uniformBuffersMemory[i], ); } } fn createDescriptorPool() !void { const poolSizes = [_]vk.DescriptorPoolSize{.{ .inType = .UNIFORM_BUFFER, .descriptorCount = @intCast(u32, swapChainImages.len), }}; const poolInfo = vk.DescriptorPoolCreateInfo{ .poolSizeCount = poolSizes.len, .pPoolSizes = &poolSizes, .maxSets = @intCast(u32, swapChainImages.len), }; descriptorPool = try vk.CreateDescriptorPool(global_device, poolInfo, null); } fn createDescriptorSets(allocator: *Allocator) !void { const layouts = try allocator.alloc(vk.DescriptorSetLayout, swapChainImages.len); defer allocator.free(layouts); for (layouts) |*layout| layout.* = descriptorSetLayouts[0]; const allocInfo = vk.DescriptorSetAllocateInfo{ .descriptorPool = descriptorPool, .descriptorSetCount = @intCast(u32, layouts.len), .pSetLayouts = layouts.ptr, }; descriptorSets = try allocator.alloc(vk.DescriptorSet, swapChainImages.len); errdefer allocator.free(descriptorSets); try vk.AllocateDescriptorSets(global_device, allocInfo, descriptorSets); for (uniformBuffers) |buffer, i| { const bufferInfo = vk.DescriptorBufferInfo{ .buffer = buffer, .offset = 0, .range = @sizeOf(UniformBufferObject), }; const write = vk.WriteDescriptorSet{ .dstSet = descriptorSets[i], .dstBinding = 0, .dstArrayElement = 0, .descriptorType = .UNIFORM_BUFFER, .descriptorCount = 1, .pBufferInfo = arrayPtr(&bufferInfo), .pImageInfo = undefined, .pTexelBufferView = undefined, }; vk.UpdateDescriptorSets(global_device, arrayPtr(&write), emptySlice(vk.CopyDescriptorSet)); } } fn createCommandBuffers(allocator: *Allocator) !void { commandBuffers = try allocator.alloc(vk.CommandBuffer, swapChainFramebuffers.len); const allocInfo = vk.CommandBufferAllocateInfo{ .commandPool = commandPool, .level = .PRIMARY, .commandBufferCount = @intCast(u32, commandBuffers.len), }; try vk.AllocateCommandBuffers(global_device, allocInfo, commandBuffers); for (commandBuffers) |command_buffer, i| { const beginInfo = vk.CommandBufferBeginInfo{ .flags = .{ .simultaneousUse = true }, .pInheritanceInfo = null, }; try vk.BeginCommandBuffer(commandBuffers[i], beginInfo); const clearColor = vk.ClearValue{ .color = .{ .float32 = .{ 0.2, 0.2, 0.2, 1.0 } } }; const renderPassInfo = vk.RenderPassBeginInfo{ .renderPass = renderPass, .framebuffer = swapChainFramebuffers[i], .renderArea = .{ .offset = .{ .x = 0, .y = 0 }, .extent = swapChainExtent, }, .clearValueCount = 1, .pClearValues = arrayPtr(&clearColor), }; vk.CmdBeginRenderPass(commandBuffers[i], renderPassInfo, .INLINE); { vk.CmdBindPipeline(commandBuffers[i], .GRAPHICS, graphicsPipeline); const offsets = [_]vk.DeviceSize{0}; vk.CmdBindVertexBuffers(commandBuffers[i], 0, arrayPtr(&vertexBuffer), &offsets); vk.CmdBindDescriptorSets(commandBuffers[i], .GRAPHICS, pipelineLayout, 0, arrayPtr(&descriptorSets[i]), emptySlice(u32)); vk.CmdDraw(commandBuffers[i], vertexData.len, 1, 0, 0); } vk.CmdEndRenderPass(commandBuffers[i]); try vk.EndCommandBuffer(commandBuffers[i]); } } fn createSyncObjects() !void { var i: usize = 0; while (i < MAX_FRAMES_IN_FLIGHT) : (i += 1) { imageAvailableSemaphores[i] = try vk.CreateSemaphore(global_device, .{}, null); renderFinishedSemaphores[i] = try vk.CreateSemaphore(global_device, .{}, null); inFlightFences[i] = try vk.CreateFence(global_device, .{ .flags = .{ .signaled = true } }, null); } } fn createCommandPool(allocator: *Allocator) !void { const queueFamilyIndices = try findQueueFamilies(allocator, physicalDevice); const poolInfo = vk.CommandPoolCreateInfo{ .queueFamilyIndex = queueFamilyIndices.graphicsFamily.?, }; commandPool = try vk.CreateCommandPool(global_device, poolInfo, null); } fn createFramebuffers(allocator: *Allocator) !void { swapChainFramebuffers = try allocator.alloc(vk.Framebuffer, swapChainImageViews.len); for (swapChainImageViews) |swap_chain_image_view, i| { const framebufferInfo = vk.FramebufferCreateInfo{ .renderPass = renderPass, .attachmentCount = 1, .pAttachments = arrayPtr(&swap_chain_image_view), .width = swapChainExtent.width, .height = swapChainExtent.height, .layers = 1, }; swapChainFramebuffers[i] = try vk.CreateFramebuffer(global_device, framebufferInfo, null); } } fn createShaderModule(code: []align(@alignOf(u32)) const u8) !vk.ShaderModule { const createInfo = vk.ShaderModuleCreateInfo{ .codeSize = code.len, .pCode = @ptrCast([*]const u32, code.ptr), }; return try vk.CreateShaderModule(global_device, createInfo, null); } fn createGraphicsPipeline(allocator: *Allocator) !void { const vertShaderCode = try std.fs.cwd().readFileAllocAligned(allocator, "shaders\\vert.spv", ~@as(usize, 0), @alignOf(u32)); defer allocator.free(vertShaderCode); const fragShaderCode = try std.fs.cwd().readFileAllocAligned(allocator, "shaders\\frag.spv", ~@as(usize, 0), @alignOf(u32)); defer allocator.free(fragShaderCode); const vertShaderModule = try createShaderModule(vertShaderCode); const fragShaderModule = try createShaderModule(fragShaderCode); const shaderStages = [_]vk.PipelineShaderStageCreateInfo{ .{ .stage = .{ .vertex = true }, .module = vertShaderModule, .pName = "main", }, .{ .stage = .{ .fragment = true }, .module = fragShaderModule, .pName = "main", }, }; const vertexInputInfo = vk.PipelineVertexInputStateCreateInfo{ .vertexBindingDescriptionCount = Vertex.BindingDescriptions.len, .vertexAttributeDescriptionCount = Vertex.AttributeDescriptions.len, .pVertexBindingDescriptions = &Vertex.BindingDescriptions, .pVertexAttributeDescriptions = &Vertex.AttributeDescriptions, }; const inputAssembly = vk.PipelineInputAssemblyStateCreateInfo{ .topology = .TRIANGLE_LIST, .primitiveRestartEnable = vk.FALSE, }; const viewport = vk.Viewport{ .x = 0.0, .y = 0.0, .width = @intToFloat(f32, swapChainExtent.width), .height = @intToFloat(f32, swapChainExtent.height), .minDepth = 0.0, .maxDepth = 1.0, }; const scissor = vk.Rect2D{ .offset = .{ .x = 0, .y = 0 }, .extent = swapChainExtent, }; const viewportState = vk.PipelineViewportStateCreateInfo{ .viewportCount = 1, .pViewports = arrayPtr(&viewport), .scissorCount = 1, .pScissors = arrayPtr(&scissor), }; const rasterizer = vk.PipelineRasterizationStateCreateInfo{ .depthClampEnable = vk.FALSE, .rasterizerDiscardEnable = vk.FALSE, .polygonMode = .FILL, .lineWidth = 1.0, .cullMode = .{ .back = true }, .frontFace = .COUNTER_CLOCKWISE, .depthBiasEnable = vk.FALSE, .depthBiasConstantFactor = 0, .depthBiasClamp = 0, .depthBiasSlopeFactor = 0, }; const multisampling = vk.PipelineMultisampleStateCreateInfo{ .sampleShadingEnable = vk.FALSE, .rasterizationSamples = .{ .t1 = true }, .minSampleShading = 0, .pSampleMask = null, .alphaToCoverageEnable = 0, .alphaToOneEnable = 0, }; const colorBlendAttachment = vk.PipelineColorBlendAttachmentState{ .colorWriteMask = .{ .r = true, .g = true, .b = true, .a = true }, .blendEnable = vk.FALSE, .srcColorBlendFactor = .ZERO, .dstColorBlendFactor = .ZERO, .colorBlendOp = .ADD, .srcAlphaBlendFactor = .ZERO, .dstAlphaBlendFactor = .ZERO, .alphaBlendOp = .ADD, }; const colorBlending = vk.PipelineColorBlendStateCreateInfo{ .logicOpEnable = vk.FALSE, .logicOp = .COPY, .attachmentCount = 1, .pAttachments = arrayPtr(&colorBlendAttachment), .blendConstants = .{ 0, 0, 0, 0 }, }; const pipelineLayoutInfo = vk.PipelineLayoutCreateInfo{ .setLayoutCount = descriptorSetLayouts.len, .pSetLayouts = &descriptorSetLayouts, }; pipelineLayout = try vk.CreatePipelineLayout(global_device, pipelineLayoutInfo, null); const pipelineInfo = vk.GraphicsPipelineCreateInfo{ .stageCount = @intCast(u32, shaderStages.len), .pStages = &shaderStages, .pVertexInputState = &vertexInputInfo, .pInputAssemblyState = &inputAssembly, .pViewportState = &viewportState, .pRasterizationState = &rasterizer, .pMultisampleState = &multisampling, .pColorBlendState = &colorBlending, .layout = pipelineLayout, .renderPass = renderPass, .subpass = 0, .basePipelineHandle = null, .pTessellationState = null, .pDepthStencilState = null, .pDynamicState = null, .basePipelineIndex = 0, }; try vk.CreateGraphicsPipelines( global_device, null, arrayPtr(&pipelineInfo), null, arrayPtr(&graphicsPipeline), ); vk.DestroyShaderModule(global_device, fragShaderModule, null); vk.DestroyShaderModule(global_device, vertShaderModule, null); } fn createRenderPass() !void { const colorAttachment = vk.AttachmentDescription{ .format = swapChainImageFormat, .samples = .{ .t1 = true }, .loadOp = .CLEAR, .storeOp = .STORE, .stencilLoadOp = .DONT_CARE, .stencilStoreOp = .DONT_CARE, .initialLayout = .UNDEFINED, .finalLayout = .PRESENT_SRC_KHR, }; const colorAttachmentRef = vk.AttachmentReference{ .attachment = 0, .layout = .COLOR_ATTACHMENT_OPTIMAL, }; const subpass = vk.SubpassDescription{ .pipelineBindPoint = .GRAPHICS, .colorAttachmentCount = 1, .pColorAttachments = arrayPtr(&colorAttachmentRef), }; const dependency = vk.SubpassDependency{ .srcSubpass = vk.SUBPASS_EXTERNAL, .dstSubpass = 0, .srcStageMask = .{ .colorAttachmentOutput = true }, .srcAccessMask = .{}, .dstStageMask = .{ .colorAttachmentOutput = true }, .dstAccessMask = .{ .colorAttachmentRead = true, .colorAttachmentWrite = true }, }; const renderPassInfo = vk.RenderPassCreateInfo{ .attachmentCount = 1, .pAttachments = arrayPtr(&colorAttachment), .subpassCount = 1, .pSubpasses = arrayPtr(&subpass), .dependencyCount = 1, .pDependencies = arrayPtr(&dependency), }; renderPass = try vk.CreateRenderPass(global_device, renderPassInfo, null); } fn createDescriptorSetLayout() !void { const uboLayoutBindings = [_]vk.DescriptorSetLayoutBinding{.{ .binding = 0, .descriptorType = .UNIFORM_BUFFER, .descriptorCount = 1, .stageFlags = .{ .vertex = true }, .pImmutableSamplers = null, }}; const layoutInfo = vk.DescriptorSetLayoutCreateInfo{ .bindingCount = uboLayoutBindings.len, .pBindings = &uboLayoutBindings, }; descriptorSetLayouts[0] = try vk.CreateDescriptorSetLayout(global_device, layoutInfo, null); } fn createImageViews(allocator: *Allocator) !void { swapChainImageViews = try allocator.alloc(vk.ImageView, swapChainImages.len); errdefer allocator.free(swapChainImageViews); for (swapChainImages) |swap_chain_image, i| { const createInfo = vk.ImageViewCreateInfo{ .image = swap_chain_image, .viewType = .T_2D, .format = swapChainImageFormat, .components = .{ .r = .IDENTITY, .g = .IDENTITY, .b = .IDENTITY, .a = .IDENTITY, }, .subresourceRange = .{ .aspectMask = .{ .color = true }, .baseMipLevel = 0, .levelCount = 1, .baseArrayLayer = 0, .layerCount = 1, }, }; swapChainImageViews[i] = try vk.CreateImageView(global_device, createInfo, null); } } fn chooseSwapSurfaceFormat(availableFormats: []vk.SurfaceFormatKHR) vk.SurfaceFormatKHR { if (availableFormats.len == 1 and availableFormats[0].format == .UNDEFINED) { return .{ .format = .B8G8R8A8_UNORM, .colorSpace = .SRGB_NONLINEAR, }; } for (availableFormats) |availableFormat| { if (availableFormat.format == .B8G8R8A8_UNORM and availableFormat.colorSpace == .SRGB_NONLINEAR) { return availableFormat; } } return availableFormats[0]; } fn chooseSwapPresentMode(availablePresentModes: []vk.PresentModeKHR) vk.PresentModeKHR { var bestMode: vk.PresentModeKHR = .FIFO; for (availablePresentModes) |availablePresentMode| { if (availablePresentMode == .MAILBOX) { return availablePresentMode; } else if (availablePresentMode == .IMMEDIATE) { bestMode = availablePresentMode; } } return bestMode; } fn chooseSwapExtent(capabilities: vk.SurfaceCapabilitiesKHR) vk.Extent2D { if (capabilities.currentExtent.width != maxInt(u32)) { return capabilities.currentExtent; } else { var actualExtent = vk.Extent2D{ .width = WIDTH, .height = HEIGHT, }; actualExtent.width = math.max(capabilities.minImageExtent.width, math.min(capabilities.maxImageExtent.width, actualExtent.width)); actualExtent.height = math.max(capabilities.minImageExtent.height, math.min(capabilities.maxImageExtent.height, actualExtent.height)); return actualExtent; } } fn createSwapChain(allocator: *Allocator) !void { var swapChainSupport = try querySwapChainSupport(allocator, physicalDevice); defer swapChainSupport.deinit(); const surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats.items); const presentMode = chooseSwapPresentMode(swapChainSupport.presentModes.items); const extent = chooseSwapExtent(swapChainSupport.capabilities); var imageCount: u32 = swapChainSupport.capabilities.minImageCount + 1; if (swapChainSupport.capabilities.maxImageCount > 0 and imageCount > swapChainSupport.capabilities.maxImageCount) { imageCount = swapChainSupport.capabilities.maxImageCount; } const indices = try findQueueFamilies(allocator, physicalDevice); const queueFamilyIndices = [_]u32{ indices.graphicsFamily.?, indices.presentFamily.? }; const different_families = indices.graphicsFamily.? != indices.presentFamily.?; var createInfo = vk.SwapchainCreateInfoKHR{ .surface = surface, .minImageCount = imageCount, .imageFormat = surfaceFormat.format, .imageColorSpace = surfaceFormat.colorSpace, .imageExtent = extent, .imageArrayLayers = 1, .imageUsage = .{ .colorAttachment = true }, .imageSharingMode = if (different_families) .CONCURRENT else .EXCLUSIVE, .queueFamilyIndexCount = if (different_families) @as(u32, 2) else @as(u32, 0), .pQueueFamilyIndices = if (different_families) &queueFamilyIndices else &([_]u32{ 0, 0 }), .preTransform = swapChainSupport.capabilities.currentTransform, .compositeAlpha = .{ .opaque = true }, .presentMode = presentMode, .clipped = vk.TRUE, .oldSwapchain = null, }; swapChain = try vk.CreateSwapchainKHR(global_device, createInfo, null); imageCount = try vk.GetSwapchainImagesCountKHR(global_device, swapChain); swapChainImages = try allocator.alloc(vk.Image, imageCount); _ = try vk.GetSwapchainImagesKHR(global_device, swapChain, swapChainImages); swapChainImageFormat = surfaceFormat.format; swapChainExtent = extent; } fn createLogicalDevice(allocator: *Allocator) !void { const indices = try findQueueFamilies(allocator, physicalDevice); var queueCreateInfos = std.ArrayList(vk.DeviceQueueCreateInfo).init(allocator); defer queueCreateInfos.deinit(); const all_queue_families = [_]u32{ indices.graphicsFamily.?, indices.presentFamily.? }; const uniqueQueueFamilies = if (indices.graphicsFamily.? == indices.presentFamily.?) all_queue_families[0..1] else all_queue_families[0..2]; var queuePriority: f32 = 1.0; for (uniqueQueueFamilies) |queueFamily| { const queueCreateInfo = vk.DeviceQueueCreateInfo{ .queueFamilyIndex = queueFamily, .queueCount = 1, .pQueuePriorities = arrayPtr(&queuePriority), }; try queueCreateInfos.append(queueCreateInfo); } var deviceFeatures = mem.zeroes(vk.PhysicalDeviceFeatures); const createInfo = vk.DeviceCreateInfo{ .queueCreateInfoCount = @intCast(u32, queueCreateInfos.items.len), .pQueueCreateInfos = queueCreateInfos.items.ptr, .pEnabledFeatures = &deviceFeatures, .enabledExtensionCount = @intCast(u32, deviceExtensions.len), .ppEnabledExtensionNames = &deviceExtensions, .enabledLayerCount = if (enableValidationLayers) @intCast(u32, validationLayers.len) else 0, .ppEnabledLayerNames = if (enableValidationLayers) &validationLayers else null, }; global_device = try vk.CreateDevice(physicalDevice, createInfo, null); graphicsQueue = vk.GetDeviceQueue(global_device, indices.graphicsFamily.?, 0); presentQueue = vk.GetDeviceQueue(global_device, indices.presentFamily.?, 0); } fn pickPhysicalDevice(allocator: *Allocator) !void { var deviceCount = try vk.EnumeratePhysicalDevicesCount(instance); if (deviceCount == 0) { return error.FailedToFindGPUsWithVulkanSupport; } const devicesBuf = try allocator.alloc(vk.PhysicalDevice, deviceCount); defer allocator.free(devicesBuf); var devices = (try vk.EnumeratePhysicalDevices(instance, devicesBuf)).physicalDevices; physicalDevice = for (devices) |device| { if (try isDeviceSuitable(allocator, device)) { break device; } } else return error.FailedToFindSuitableGPU; } fn findQueueFamilies(allocator: *Allocator, device: vk.PhysicalDevice) !QueueFamilyIndices { var indices = QueueFamilyIndices.init(); var queueFamilyCount = vk.GetPhysicalDeviceQueueFamilyPropertiesCount(device); const queueFamiliesBuf = try allocator.alloc(vk.QueueFamilyProperties, queueFamilyCount); defer allocator.free(queueFamiliesBuf); var queueFamilies = vk.GetPhysicalDeviceQueueFamilyProperties(device, queueFamiliesBuf); var i: u32 = 0; for (queueFamilies) |queueFamily| { if (queueFamily.queueCount > 0 and queueFamily.queueFlags.graphics) { indices.graphicsFamily = i; } var presentSupport = try vk.GetPhysicalDeviceSurfaceSupportKHR(device, i, surface); if (queueFamily.queueCount > 0 and presentSupport != 0) { indices.presentFamily = i; } if (indices.isComplete()) { break; } i += 1; } return indices; } fn isDeviceSuitable(allocator: *Allocator, device: vk.PhysicalDevice) !bool { const indices = try findQueueFamilies(allocator, device); const extensionsSupported = try checkDeviceExtensionSupport(allocator, device); var swapChainAdequate = false; if (extensionsSupported) { var swapChainSupport = try querySwapChainSupport(allocator, device); defer swapChainSupport.deinit(); swapChainAdequate = swapChainSupport.formats.items.len != 0 and swapChainSupport.presentModes.items.len != 0; } return indices.isComplete() and extensionsSupported and swapChainAdequate; } fn querySwapChainSupport(allocator: *Allocator, device: vk.PhysicalDevice) !SwapChainSupportDetails { var details = SwapChainSupportDetails.init(allocator); details.capabilities = try vk.GetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface); var formatCount = try vk.GetPhysicalDeviceSurfaceFormatsCountKHR(device, surface); if (formatCount != 0) { try details.formats.resize(formatCount); _ = try vk.GetPhysicalDeviceSurfaceFormatsKHR(device, surface, details.formats.items); } var presentModeCount = try vk.GetPhysicalDeviceSurfacePresentModesCountKHR(device, surface); if (presentModeCount != 0) { try details.presentModes.resize(presentModeCount); _ = try vk.GetPhysicalDeviceSurfacePresentModesKHR(device, surface, details.presentModes.items); } return details; } fn checkDeviceExtensionSupport(allocator: *Allocator, device: vk.PhysicalDevice) !bool { var extensionCount = try vk.EnumerateDeviceExtensionPropertiesCount(device, null); const availableExtensionsBuf = try allocator.alloc(vk.ExtensionProperties, extensionCount); defer allocator.free(availableExtensionsBuf); var availableExtensions = (try vk.EnumerateDeviceExtensionProperties(device, null, availableExtensionsBuf)).properties; var requiredExtensions = std.HashMap([*:0]const u8, void, hash_cstr, eql_cstr).init(allocator); defer requiredExtensions.deinit(); for (deviceExtensions) |device_ext| { _ = try requiredExtensions.put(device_ext, {}); } for (availableExtensions) |extension| { _ = requiredExtensions.remove(&extension.extensionName); } return requiredExtensions.count() == 0; } fn createSurface(window: *glfw.GLFWwindow) !void { if (glfw.glfwCreateWindowSurface(instance, window, null, &surface) != vk.Result.SUCCESS) { return error.FailedToCreateWindowSurface; } } fn debugCallback( flags: vk.DebugReportFlagsEXT.IntType, objType: vk.DebugReportObjectTypeEXT, obj: u64, location: usize, code: i32, layerPrefix: ?vk.CString, msg: ?vk.CString, userData: ?*c_void, ) callconv(vk.CallConv) vk.Bool32 { std.debug.warn("validation layer: {s}\n", .{msg}); return vk.FALSE; } fn setupDebugCallback() error{FailedToSetUpDebugCallback}!void { if (!enableValidationLayers) return; var createInfo = vk.DebugReportCallbackCreateInfoEXT{ .flags = .{ .errorBit = true, .warning = true }, .pfnCallback = debugCallback, .pUserData = null, }; if (CreateDebugReportCallbackEXT(&createInfo, null, &callback) != .SUCCESS) { return error.FailedToSetUpDebugCallback; } } fn DestroyDebugReportCallbackEXT( pAllocator: ?*const vk.AllocationCallbacks, ) void { const func = @ptrCast(?@TypeOf(vk.vkDestroyDebugReportCallbackEXT), vk.GetInstanceProcAddr( instance, "vkDestroyDebugReportCallbackEXT", )) orelse unreachable; func(instance, callback, pAllocator); } fn CreateDebugReportCallbackEXT( pCreateInfo: *const vk.DebugReportCallbackCreateInfoEXT, pAllocator: ?*const vk.AllocationCallbacks, pCallback: *vk.DebugReportCallbackEXT, ) vk.Result { const func = @ptrCast(?@TypeOf(vk.vkCreateDebugReportCallbackEXT), vk.GetInstanceProcAddr( instance, "vkCreateDebugReportCallbackEXT", )) orelse return .ERROR_EXTENSION_NOT_PRESENT; return func(instance, pCreateInfo, pAllocator, pCallback); } fn createInstance(allocator: *Allocator) !void { if (enableValidationLayers) { if (!(try checkValidationLayerSupport(allocator))) { return error.ValidationLayerRequestedButNotAvailable; } } const appInfo = vk.ApplicationInfo{ .pApplicationName = "Hello Triangle", .applicationVersion = vk.MAKE_VERSION(1, 0, 0), .pEngineName = "No Engine", .engineVersion = vk.MAKE_VERSION(1, 0, 0), .apiVersion = vk.API_VERSION_1_0, }; const extensions = try getRequiredExtensions(allocator); defer allocator.free(extensions); const createInfo = vk.InstanceCreateInfo{ .pApplicationInfo = &appInfo, .enabledExtensionCount = @intCast(u32, extensions.len), .ppEnabledExtensionNames = extensions.ptr, .enabledLayerCount = if (enableValidationLayers) @intCast(u32, validationLayers.len) else 0, .ppEnabledLayerNames = if (enableValidationLayers) &validationLayers else null, }; instance = try vk.CreateInstance(createInfo, null); } /// caller must free returned memory fn getRequiredExtensions(allocator: *Allocator) ![]vk.CString { var glfwExtensionCount: u32 = 0; var glfwExtensions: [*]const vk.CString = glfw.glfwGetRequiredInstanceExtensions(&glfwExtensionCount); var extensions = std.ArrayList(vk.CString).init(allocator); errdefer extensions.deinit(); try extensions.appendSlice(glfwExtensions[0..glfwExtensionCount]); if (enableValidationLayers) { try extensions.append(vk.EXT_DEBUG_REPORT_EXTENSION_NAME); } return extensions.toOwnedSlice(); } fn checkValidationLayerSupport(allocator: *Allocator) !bool { var layerCount = try vk.EnumerateInstanceLayerPropertiesCount(); const layersBuffer = try allocator.alloc(vk.LayerProperties, layerCount); defer allocator.free(layersBuffer); var availableLayers = (try vk.EnumerateInstanceLayerProperties(layersBuffer)).properties; for (validationLayers) |layerName| { var layerFound = false; for (availableLayers) |layerProperties| { if (std.cstr.cmp(layerName, &layerProperties.layerName) == 0) { layerFound = true; break; } } if (!layerFound) { return false; } } return true; } fn drawFrame() !void { _ = try vk.WaitForFences(global_device, inFlightFences[currentFrame .. currentFrame + 1], vk.TRUE, maxInt(u64)); try vk.ResetFences(global_device, inFlightFences[currentFrame .. currentFrame + 1]); var imageIndex = (try vk.AcquireNextImageKHR(global_device, swapChain, maxInt(u64), imageAvailableSemaphores[currentFrame], null)).imageIndex; try updateUniformBuffer(imageIndex); var waitSemaphores = [_]vk.Semaphore{imageAvailableSemaphores[currentFrame]}; var waitStages: [1]vk.PipelineStageFlags align(4) = .{.{ .colorAttachmentOutput = true }}; const signalSemaphores = [_]vk.Semaphore{renderFinishedSemaphores[currentFrame]}; var submitInfo = [_]vk.SubmitInfo{vk.SubmitInfo{ .waitSemaphoreCount = 1, .pWaitSemaphores = &waitSemaphores, .pWaitDstStageMask = &waitStages, .commandBufferCount = 1, .pCommandBuffers = commandBuffers.ptr + imageIndex, .signalSemaphoreCount = 1, .pSignalSemaphores = &signalSemaphores, }}; try vk.QueueSubmit(graphicsQueue, &submitInfo, inFlightFences[currentFrame]); const swapChains = [_]vk.SwapchainKHR{swapChain}; const presentInfo = vk.PresentInfoKHR{ .waitSemaphoreCount = 1, .pWaitSemaphores = &signalSemaphores, .swapchainCount = 1, .pSwapchains = &swapChains, .pImageIndices = arrayPtr(&imageIndex), .pResults = null, }; _ = try vk.QueuePresentKHR(presentQueue, presentInfo); currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT; } var hasDumped = false; fn updateUniformBuffer(index: u32) !void { const time = currentTime(); var ubo = UniformBufferObject{ .model = Mat4.Identity, .view = Mat4.Identity, .proj = Mat4.Identity, }; geo.Generic.setMat3(&ubo.model, Rotor3.aroundZ(time * math.pi * 0.5).toMat3()); ubo.proj = geo.symmetricOrtho(1, -@as(f32, HEIGHT) / @as(f32, WIDTH), -1, 1); if (!hasDumped) { std.debug.warn("proj = {}\n", .{ubo.proj}); hasDumped = true; } var data: *c_void = undefined; try vk.MapMemory(global_device, uniformBuffersMemory[index], 0, @sizeOf(UniformBufferObject), .{}, &data); @memcpy(@ptrCast([*]u8, data), @ptrCast([*]const u8, &ubo), @sizeOf(UniformBufferObject)); vk.UnmapMemory(global_device, uniformBuffersMemory[index]); } fn hash_cstr(a: [*:0]const u8) u32 { // FNV 32-bit hash var h: u32 = 2166136261; var i: usize = 0; while (a[i] != 0) : (i += 1) { h ^= a[i]; h *%= 16777619; } return h; } fn eql_cstr(a: [*:0]const u8, b: [*:0]const u8) bool { return std.cstr.cmp(a, b) == 0; }
src/main.zig
const builtin = @import("builtin"); const std = @import("std"); const json = std.json; const mem = std.mem; const fieldIndex = std.meta.fieldIndex; const TypeId = builtin.TypeId; pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const args = try std.process.argsAlloc(allocator); var parser: json.Parser = undefined; var dump = Dump.init(allocator); for (args[1..]) |arg| { parser = json.Parser.init(allocator, false); const json_text = try std.io.readFileAlloc(allocator, arg); const tree = try parser.parse(json_text); try dump.mergeJson(tree.root); } const stdout = try std.io.getStdOut(); try dump.render(&stdout.outStream().stream); } /// AST source node const Node = struct { file: usize, line: usize, col: usize, fields: []usize, fn hash(n: Node) u32 { var hasher = std.hash.Wyhash.init(0); std.hash.autoHash(&hasher, n.file); std.hash.autoHash(&hasher, n.line); std.hash.autoHash(&hasher, n.col); return @truncate(u32, hasher.final()); } fn eql(a: Node, b: Node) bool { return a.file == b.file and a.line == b.line and a.col == b.col; } }; const Error = struct { src: usize, name: []const u8, fn hash(n: Error) u32 { var hasher = std.hash.Wyhash.init(0); std.hash.autoHash(&hasher, n.src); return @truncate(u32, hasher.final()); } fn eql(a: Error, b: Error) bool { return a.src == b.src; } }; const simple_types = [_][]const u8{ "Type", "Void", "Bool", "NoReturn", "ComptimeFloat", "ComptimeInt", "Undefined", "Null", "AnyFrame", "EnumLiteral", }; const Type = union(builtin.TypeId) { Type, Void, Bool, NoReturn, ComptimeFloat, ComptimeInt, Undefined, Null, AnyFrame, EnumLiteral, Int: Int, Float: usize, // bits Vector: Array, Optional: usize, // payload type index Pointer: Pointer, Array: Array, Struct, // TODO ErrorUnion, // TODO ErrorSet, // TODO Enum, // TODO Union, // TODO Fn, // TODO BoundFn, // TODO ArgTuple, // TODO Opaque, // TODO Frame, // TODO const Int = struct { bits: usize, signed: bool, }; const Pointer = struct { elem: usize, alignment: usize, is_const: bool, is_volatile: bool, allow_zero: bool, host_int_bytes: usize, bit_offset_in_host: usize, }; const Array = struct { elem: usize, len: usize, }; fn hash(t: Type) u32 { var hasher = std.hash.Wyhash.init(0); std.hash.autoHash(&hasher, builtin.TypeId(t)); return @truncate(u32, hasher.final()); } fn eql(a: Type, b: Type) bool { return std.meta.eql(a, b); } }; const Dump = struct { zig_id: ?[]const u8 = null, zig_version: ?[]const u8 = null, root_name: ?[]const u8 = null, targets: std.ArrayList([]const u8), const FileMap = std.StringHashMap(usize); file_list: std.ArrayList([]const u8), file_map: FileMap, const NodeMap = std.HashMap(Node, usize, Node.hash, Node.eql); node_list: std.ArrayList(Node), node_map: NodeMap, const ErrorMap = std.HashMap(Error, usize, Error.hash, Error.eql); error_list: std.ArrayList(Error), error_map: ErrorMap, const TypeMap = std.HashMap(Type, usize, Type.hash, Type.eql); type_list: std.ArrayList(Type), type_map: TypeMap, fn init(allocator: *mem.Allocator) Dump { return Dump{ .targets = std.ArrayList([]const u8).init(allocator), .file_list = std.ArrayList([]const u8).init(allocator), .file_map = FileMap.init(allocator), .node_list = std.ArrayList(Node).init(allocator), .node_map = NodeMap.init(allocator), .error_list = std.ArrayList(Error).init(allocator), .error_map = ErrorMap.init(allocator), .type_list = std.ArrayList(Type).init(allocator), .type_map = TypeMap.init(allocator), }; } fn mergeJson(self: *Dump, root: json.Value) !void { const params = &root.Object.get("params").?.value.Object; const zig_id = params.get("zigId").?.value.String; const zig_version = params.get("zigVersion").?.value.String; const root_name = params.get("rootName").?.value.String; try mergeSameStrings(&self.zig_id, zig_id); try mergeSameStrings(&self.zig_version, zig_version); try mergeSameStrings(&self.root_name, root_name); for (params.get("builds").?.value.Array.toSliceConst()) |json_build| { const target = json_build.Object.get("target").?.value.String; try self.targets.append(target); } // Merge files. If the string matches, it's the same file. const other_files = root.Object.get("files").?.value.Array.toSliceConst(); var other_file_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_files) |other_file, i| { const gop = try self.file_map.getOrPut(other_file.String); if (!gop.found_existing) { gop.kv.value = self.file_list.len; try self.file_list.append(other_file.String); } try other_file_to_mine.putNoClobber(i, gop.kv.value); } // Merge AST nodes. If the file id, line, and column all match, it's the same AST node. const other_ast_nodes = root.Object.get("astNodes").?.value.Array.toSliceConst(); var other_ast_node_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_ast_nodes) |other_ast_node_json, i| { const other_file_id = jsonObjInt(other_ast_node_json, "file"); const other_node = Node{ .line = jsonObjInt(other_ast_node_json, "line"), .col = jsonObjInt(other_ast_node_json, "col"), .file = other_file_to_mine.getValue(other_file_id).?, .fields = ([*]usize)(undefined)[0..0], }; const gop = try self.node_map.getOrPut(other_node); if (!gop.found_existing) { gop.kv.value = self.node_list.len; try self.node_list.append(other_node); } try other_ast_node_to_mine.putNoClobber(i, gop.kv.value); } // convert fields lists for (other_ast_nodes) |other_ast_node_json, i| { const my_node_index = other_ast_node_to_mine.get(i).?.value; const my_node = &self.node_list.toSlice()[my_node_index]; if (other_ast_node_json.Object.get("fields")) |fields_json_kv| { const other_fields = fields_json_kv.value.Array.toSliceConst(); my_node.fields = try self.a().alloc(usize, other_fields.len); for (other_fields) |other_field_index, field_i| { const other_index = @intCast(usize, other_field_index.Integer); my_node.fields[field_i] = other_ast_node_to_mine.get(other_index).?.value; } } } // Merge errors. If the AST Node matches, it's the same error value. const other_errors = root.Object.get("errors").?.value.Array.toSliceConst(); var other_error_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_errors) |other_error_json, i| { const other_src_id = jsonObjInt(other_error_json, "src"); const other_error = Error{ .src = other_ast_node_to_mine.getValue(other_src_id).?, .name = other_error_json.Object.get("name").?.value.String, }; const gop = try self.error_map.getOrPut(other_error); if (!gop.found_existing) { gop.kv.value = self.error_list.len; try self.error_list.append(other_error); } try other_error_to_mine.putNoClobber(i, gop.kv.value); } // Merge types. Now it starts to get advanced. // First we identify all the simple types and merge those. // Example: void, type, noreturn // We can also do integers and floats. const other_types = root.Object.get("types").?.value.Array.toSliceConst(); var other_types_to_mine = std.AutoHashMap(usize, usize).init(self.a()); for (other_types) |other_type_json, i| { const type_kind = jsonObjInt(other_type_json, "kind"); switch (type_kind) { fieldIndex(TypeId, "Int").? => { var signed: bool = undefined; var bits: usize = undefined; if (other_type_json.Object.get("i")) |kv| { signed = true; bits = @intCast(usize, kv.value.Integer); } else if (other_type_json.Object.get("u")) |kv| { signed = false; bits = @intCast(usize, kv.value.Integer); } else { unreachable; } const other_type = Type{ .Int = Type.Int{ .bits = bits, .signed = signed, }, }; try self.mergeOtherType(other_type, i, &other_types_to_mine); }, fieldIndex(TypeId, "Float").? => { const other_type = Type{ .Float = jsonObjInt(other_type_json, "bits"), }; try self.mergeOtherType(other_type, i, &other_types_to_mine); }, else => {}, } inline for (simple_types) |simple_type_name| { if (type_kind == std.meta.fieldIndex(builtin.TypeId, simple_type_name).?) { const other_type = @unionInit(Type, simple_type_name, {}); try self.mergeOtherType(other_type, i, &other_types_to_mine); } } } } fn mergeOtherType( self: *Dump, other_type: Type, other_type_index: usize, other_types_to_mine: *std.AutoHashMap(usize, usize), ) !void { const gop = try self.type_map.getOrPut(other_type); if (!gop.found_existing) { gop.kv.value = self.type_list.len; try self.type_list.append(other_type); } try other_types_to_mine.putNoClobber(other_type_index, gop.kv.value); } fn render(self: *Dump, stream: var) !void { var jw = json.WriteStream(@TypeOf(stream).Child, 10).init(stream); try jw.beginObject(); try jw.objectField("typeKinds"); try jw.beginArray(); inline for (@typeInfo(builtin.TypeId).Enum.fields) |field| { try jw.arrayElem(); try jw.emitString(field.name); } try jw.endArray(); try jw.objectField("params"); try jw.beginObject(); try jw.objectField("zigId"); try jw.emitString(self.zig_id.?); try jw.objectField("zigVersion"); try jw.emitString(self.zig_version.?); try jw.objectField("rootName"); try jw.emitString(self.root_name.?); try jw.objectField("builds"); try jw.beginArray(); for (self.targets.toSliceConst()) |target| { try jw.arrayElem(); try jw.beginObject(); try jw.objectField("target"); try jw.emitString(target); try jw.endObject(); } try jw.endArray(); try jw.endObject(); try jw.objectField("types"); try jw.beginArray(); for (self.type_list.toSliceConst()) |t| { try jw.arrayElem(); try jw.beginObject(); try jw.objectField("kind"); try jw.emitNumber(@enumToInt(builtin.TypeId(t))); switch (t) { .Int => |int| { if (int.signed) { try jw.objectField("i"); } else { try jw.objectField("u"); } try jw.emitNumber(int.bits); }, .Float => |bits| { try jw.objectField("bits"); try jw.emitNumber(bits); }, else => {}, } try jw.endObject(); } try jw.endArray(); try jw.objectField("errors"); try jw.beginArray(); for (self.error_list.toSliceConst()) |zig_error| { try jw.arrayElem(); try jw.beginObject(); try jw.objectField("src"); try jw.emitNumber(zig_error.src); try jw.objectField("name"); try jw.emitString(zig_error.name); try jw.endObject(); } try jw.endArray(); try jw.objectField("astNodes"); try jw.beginArray(); for (self.node_list.toSliceConst()) |node| { try jw.arrayElem(); try jw.beginObject(); try jw.objectField("file"); try jw.emitNumber(node.file); try jw.objectField("line"); try jw.emitNumber(node.line); try jw.objectField("col"); try jw.emitNumber(node.col); if (node.fields.len != 0) { try jw.objectField("fields"); try jw.beginArray(); for (node.fields) |field_node_index| { try jw.arrayElem(); try jw.emitNumber(field_node_index); } try jw.endArray(); } try jw.endObject(); } try jw.endArray(); try jw.objectField("files"); try jw.beginArray(); for (self.file_list.toSliceConst()) |file| { try jw.arrayElem(); try jw.emitString(file); } try jw.endArray(); try jw.endObject(); } fn a(self: Dump) *mem.Allocator { return self.targets.allocator; } fn mergeSameStrings(opt_dest: *?[]const u8, src: []const u8) !void { if (opt_dest.*) |dest| { if (!mem.eql(u8, dest, src)) return error.MismatchedDumps; } else { opt_dest.* = src; } } }; fn jsonObjInt(json_val: json.Value, field: []const u8) usize { const uncasted = json_val.Object.get(field).?.value.Integer; return @intCast(usize, uncasted); }
tools/merge_anal_dumps.zig
const std = @import("std"); const io = std.io; const warn = std.debug.warn; const assert = std.debug.assert; fn jumpForward(prog: []const u8, prog_ptr: usize) usize { var bracket_stack: usize = 1; var ptr: usize = prog_ptr; while (bracket_stack > 0) { ptr += 1; // if (ptr >= prog.len) // expected matching switch (prog[ptr]) { '[' => bracket_stack += 1, ']' => bracket_stack -= 1, else => {}, } } return ptr; } test "jumpForward" { assert(jumpForward("[]", 0) == 1); assert(jumpForward("[[]]", 0) == 3); assert(jumpForward("[[]]", 1) == 2); assert(jumpForward("[[][]]", 0) == 5); assert(jumpForward("[[][]]", 1) == 2); assert(jumpForward("[[][]]", 3) == 4); } fn jumpBackward(prog: []const u8, prog_ptr: usize) usize { var bracket_stack: usize = 1; var ptr: usize = prog_ptr; while (bracket_stack > 0) { ptr -= 1; // if (ptr >= prog.len) // expected matching switch (prog[ptr]) { '[' => bracket_stack -= 1, ']' => bracket_stack += 1, else => {}, } } return ptr; } test "jumpBackward" { assert(jumpBackward("[]", 1) == 0); assert(jumpBackward("[[]]", 3) == 0); assert(jumpBackward("[[]]", 2) == 1); assert(jumpBackward("[[][]]", 5) == 0); assert(jumpBackward("[[][]]", 2) == 1); assert(jumpBackward("[[][]]", 4) == 3); } // TODO: for test: // add out_file and in_file as argument // add caching for jump destinations fn bf(prog: []const u8, mem: []u8) !void { const in_file = io.getStdIn(); const out_file = io.getStdOut(); var mem_ptr: usize = 0; var prog_ptr: usize = 0; while (prog_ptr < prog.len) { switch (prog[prog_ptr]) { '+' => mem[mem_ptr] +%= 1, '-' => mem[mem_ptr] -%= 1, '>' => mem_ptr += 1, '<' => mem_ptr -= 1, '.' => { _ = try out_file.write(mem[mem_ptr..mem_ptr]); // FIXME }, ',' => { _ = try in_file.read(mem[mem_ptr..mem_ptr]); // FIXME }, '[' => if (mem[mem_ptr] == 0) { prog_ptr = jumpForward(prog, prog_ptr); }, ']' => if (mem[mem_ptr] != 0) { prog_ptr = jumpBackward(prog, prog_ptr); }, else => {}, } prog_ptr += 1; } } pub fn main() anyerror!void { std.debug.warn("Zig brainfuck interpreter.\n", .{}); const allocator_impl = std.heap.page_allocator; var arena = std.heap.ArenaAllocator.init(allocator_impl); defer arena.deinit(); const allocator = &arena.allocator; var args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); for (args) |arg, arg_i| { std.debug.warn("{}: {}\n", .{ arg_i, arg }); } const prog_path = args[1]; const cwd = std.fs.cwd(); const prog = try cwd.readFileAlloc(allocator, prog_path, 1024); std.debug.warn("{}\n", .{prog}); defer allocator.free(prog); // const prog = "+[,.]"; // cat var mem = [_]u8{0} ** 1024; try bf(prog, mem[0..]); } test "all instructions once -> no crash" { const prog = "+-><.,[]"; var mem = [_]u8{0} ** 1024; try bf(prog, mem[0..]); } test "add" { std.debug.warn("\n", .{}); comptime var count: usize = 256; inline while (count > 1) { count -= 1; std.debug.warn("{}.", .{count}); const prog = [_]u8{'+'} ** count; var mem = [_]u8{0} ** 1; try bf(&prog, &mem); assert(mem[0] == count); } std.debug.warn("\n", .{}); } test "sub" { std.debug.warn("\n", .{}); comptime var count: usize = 256; inline while (count > 1) { count -= 1; std.debug.warn("{}.", .{count}); const prog = [_]u8{'-'} ** count; var mem = [_]u8{0} ** 1; try bf(&prog, &mem); assert(mem[0] == 256 - count); } std.debug.warn("\n", .{}); } test "add ** 256 = 0" { comptime const count: usize = 256; const prog = [_]u8{'+'} ** count; var mem = [_]u8{0} ** 1; try bf(&prog, &mem); assert(mem[0] == 0); } test "sub ** 256 = 0" { comptime const count: usize = 256; const prog = [_]u8{'-'} ** count; var mem = [_]u8{0} ** 1; try bf(&prog, &mem); assert(mem[0] == 0); } test ">>>" { var mem = [_]u8{0} ** 4; const src = ">>>+++"; try bf(src, &mem); assert(mem[3] == 3); } test "<<<" { var mem = [_]u8{0} ** 4; const src = ">>>>>><<<+++"; try bf(src, &mem); assert(mem[3] == 3); } test "shift right" { std.debug.warn("\n", .{}); comptime var count: usize = 256; inline while (count > 1) { count -= 1; std.debug.warn("{}.", .{count}); const prog = [_]u8{'>'} ** count ++ [_]u8{'+'} ** count; var mem = [_]u8{0} ** 256; try bf(&prog, &mem); assert(mem[count] == count); } std.debug.warn("\n", .{}); } test "shift left" { std.debug.warn("\n", .{}); comptime var count: usize = 256; inline while (count > 1) { count -= 1; std.debug.warn("{}.", .{count}); const prog = [_]u8{'>'} ** 256 ++ [_]u8{'<'} ** count ++ [_]u8{'+'} ** count; var mem = [_]u8{0} ** 256; try bf(&prog, &mem); assert(mem[256 - count] == count); } std.debug.warn("\n", .{}); } test "reset [+]" { var mem = [_]u8{128} ** 1; const prog = "[-]"; try bf(prog, &mem); assert(mem[0] == 0); } test "reset [-]" { var mem = [_]u8{128} ** 1; const prog = "[+]"; try bf(prog, &mem); assert(mem[0] == 0); } test "hallo world" { const prog = "++++++++[>++++[>++>+++>+++>+<<<<-]>+>+>->>+[<]<-]>>.>---.+++++++..+++.>>.<-.<.+++.------.--------.>>+.>++."; var mem = [_]u8{0} ** 1024; try bf(prog, &mem); }
004-brainfuck/src/main.zig
const std = @import("std"); const dbg = std.debug.print; pub fn Encoder(comptime WriterType: type) type { return struct { writer: WriterType, const Self = @This(); pub const Error = WriterType.Error; fn put(self: Self, comptime T: type, val: T) Error!void { if (T == u8) { try self.writer.writeByte(val); } else if (T == u16) { try self.put(u8, @intCast(u8, (val >> 8) & 0xFF)); try self.put(u8, @intCast(u8, val & 0xFF)); } else if (T == u32) { try self.put(u8, @intCast(u8, (val >> 24) & 0xFF)); try self.put(u8, @intCast(u8, (val >> 16) & 0xFF)); try self.put(u8, @intCast(u8, (val >> 8) & 0xFF)); try self.put(u8, @intCast(u8, val & 0xFF)); } } pub fn putArrayHead(self: Self, count: u32) Error!void { if (count <= 15) { try self.put(u8, 0x90 | @intCast(u8, count)); } else if (count <= std.math.maxInt(u16)) { try self.put(u8, 0xdc); try self.put(u16, @intCast(u16, count)); } else { try self.put(u8, 0xdd); try self.put(u32, @intCast(u32, count)); } } pub fn putMapHead(self: Self, count: u32) Error!void { if (count <= 15) { try self.put(u8, 0x80 | @intCast(u8, count)); } else if (count <= std.math.maxInt(u16)) { try self.put(u8, 0xde); try self.put(u16, @intCast(u16, count)); } else { try self.put(u8, 0xdf); try self.put(u32, @intCast(u32, count)); } } pub fn putStr(self: Self, val: []const u8) Error!void { const len = val.len; if (len <= 31) { try self.put(u8, 0xa0 + @intCast(u8, len)); } else if (len <= 0xFF) { try self.put(u8, 0xd9); try self.put(u8, @intCast(u8, len)); } try self.writer.writeAll(val); } pub fn putInt(self: Self, val: anytype) Error!void { const unsigned = comptime switch (@typeInfo(@TypeOf(val))) { .Int => |int| int.signedness == .Unsigned, .ComptimeInt => false, // or val >= 0 but handled below else => unreachable, }; if (unsigned or val >= 0) { if (val <= 0x7f) { try self.put(u8, val); } else if (val <= std.math.maxInt(u8)) { try self.put(u8, 0xcc); try self.put(u8, val); } } else { @panic("aaa"); } } pub fn putBool(self: Self, b: bool) Error!void { try self.put(u8, @as(u8, if (b) 0xc3 else 0xc2)); } }; } pub fn encoder(writer: anytype) Encoder(@TypeOf(writer)) { return .{ .writer = writer }; } pub const ExtHead = struct { kind: i8, size: u32 }; pub const ValueHead = union(enum) { Null, Bool: bool, Int: i64, UInt: u64, Float32: f32, Float64: f64, Array: u32, Map: u32, Str: u32, Bin: u32, Ext: ExtHead, }; pub const Decoder = struct { data: []u8, frame: ?anyframe = null, bytes: u32 = 0, items: usize = 0, const Self = @This(); pub const Error = error{ MalformatedDataError, UnexpectedEOFError, UnexpectedTagError, InvalidDecodeOperation, }; fn getMoreData(self: *Self) Error!void { const bytes = self.data.len; suspend { self.frame = @frame(); } self.frame = null; if (self.data.len <= bytes) { return Error.UnexpectedEOFError; } } // NB: returned slice is only valid until next getMoreData()! fn readBytes(self: *Self, size: usize) Error![]u8 { while (self.data.len < size) { try self.getMoreData(); } var slice = self.data[0..size]; self.data = self.data[size..]; return slice; } // NB: returned slice is only valid until next getMoreData()! fn maybeReadBytes(self: *Self, size: usize) ?[]u8 { if (self.data.len < size) { return null; } var slice = self.data[0..size]; self.data = self.data[size..]; return slice; } // maybe [[[ fn readInt(self: *Self, comptime T: type) ?T { if (@typeInfo(T) != .Int) { @compileError("why u no int???"); } var slice = self.maybeReadBytes(@sizeOf(T)) orelse return null; var out: T = undefined; @memcpy(@ptrCast([*]u8, &out), slice.ptr, @sizeOf(T)); return std.mem.bigToNative(T, out); } fn readFloat(self: *Self, comptime T: type) ?T { const utype = if (T == f32) u32 else if (T == f64) u64 else undefined; var int = self.readInt(utype) orelse return null; return @bitCast(T, int); } fn readFixExt(self: *Self, size: u32) ?ExtHead { var kind = self.readInt(i8) orelse return null; return ExtHead{ .kind = kind, .size = size }; } fn readExt(self: *Self, comptime sizetype: type) ?ExtHead { var size = self.readInt(sizetype) orelse return null; return self.readFixExt(size); } /// ]]| const debugMode = true; pub fn start(self: *Self) Error!void { if (self.bytes > 0 or self.items > 0) { return error.InvalidDecodeOperation; } self.items = 1; } pub fn push(self: *Self) Error!usize { if (self.items == 0) { return error.InvalidDecodeOperation; } var saved = self.items - 1; self.items = 1; return saved; } pub fn pop(self: *Self, saved: usize) Error!void { if (self.bytes != 0 or self.items != 0) { return error.InvalidDecodeOperation; } self.items = saved; } pub fn maybeReadHead(self: *Self) Error!?ValueHead { if (debugMode) { if (self.bytes > 0 or self.items == 0) { return error.InvalidDecodeOperation; } } const first_byte = (self.maybeReadBytes(1) orelse return null)[0]; const val: ValueHead = switch (first_byte) { 0x00...0x7f => .{ .Int = first_byte }, 0x80...0x8f => .{ .Map = (first_byte - 0x80) }, 0x90...0x9f => .{ .Array = (first_byte - 0x90) }, 0xa0...0xbf => .{ .Str = (first_byte - 0xa0) }, 0xc0 => .Null, 0xc1 => return Error.MalformatedDataError, 0xc2 => .{ .Bool = false }, 0xc3 => .{ .Bool = true }, 0xc4 => .{ .Bin = self.readInt(u8) orelse return null }, 0xc5 => .{ .Bin = self.readInt(u16) orelse return null }, 0xc6 => .{ .Bin = self.readInt(u32) orelse return null }, 0xc7 => .{ .Ext = self.readExt(u8) orelse return null }, 0xc8 => .{ .Ext = self.readExt(u16) orelse return null }, 0xc9 => .{ .Ext = self.readExt(u32) orelse return null }, 0xca => .{ .Float32 = self.readFloat(f32) orelse return null }, 0xcb => .{ .Float64 = self.readFloat(f64) orelse return null }, 0xcc => .{ .UInt = self.readInt(u8) orelse return null }, 0xcd => .{ .UInt = self.readInt(u16) orelse return null }, 0xce => .{ .UInt = self.readInt(u32) orelse return null }, 0xcf => .{ .UInt = self.readInt(u64) orelse return null }, 0xd0 => .{ .Int = self.readInt(i8) orelse return null }, 0xd1 => .{ .Int = self.readInt(i16) orelse return null }, 0xd2 => .{ .Int = self.readInt(i32) orelse return null }, 0xd3 => .{ .Int = self.readInt(i64) orelse return null }, 0xd4 => .{ .Ext = self.readFixExt(1) orelse return null }, 0xd5 => .{ .Ext = self.readFixExt(2) orelse return null }, 0xd6 => .{ .Ext = self.readFixExt(4) orelse return null }, 0xd7 => .{ .Ext = self.readFixExt(8) orelse return null }, 0xd8 => .{ .Ext = self.readFixExt(16) orelse return null }, 0xd9 => .{ .Str = self.readInt(u8) orelse return null }, 0xda => .{ .Str = self.readInt(u16) orelse return null }, 0xdb => .{ .Str = self.readInt(u32) orelse return null }, 0xdc => .{ .Array = self.readInt(u16) orelse return null }, 0xdd => .{ .Array = self.readInt(u32) orelse return null }, 0xde => .{ .Map = self.readInt(u16) orelse return null }, 0xdf => .{ .Map = self.readInt(u32) orelse return null }, 0xe0...0xff => .{ .Int = @intCast(i64, first_byte) - 0x100 }, }; var size = itemSize(val); self.items -= 1; self.bytes += size.bytes; self.items += size.items; return val; } pub fn readHead(self: *Self) Error!ValueHead { while (true) { const oldpos = self.data; // oldpos not restored on error, but it should be fatal anyway const attempt = try self.maybeReadHead(); if (attempt) |head| { return head; } else { self.data = oldpos; try self.getMoreData(); } } } // TODO: lol what is generic function? :S pub fn expectArray(self: *Self) Error!u32 { switch (try self.readHead()) { .Array => |size| return size, else => return Error.UnexpectedTagError, } } pub fn expectMap(self: *Self) Error!u32 { switch (try self.readHead()) { .Map => |size| return size, else => return Error.UnexpectedTagError, } } pub fn expectUInt(self: *Self) Error!u64 { switch (try self.readHead()) { .UInt => |val| return val, .Int => |val| { if (val < 0) { return Error.UnexpectedTagError; } return @intCast(u64, val); }, else => return Error.UnexpectedTagError, } } pub fn expectString(self: *Self) Error![]u8 { const size = switch (try self.readHead()) { .Str => |size| size, .Bin => |size| size, else => return Error.UnexpectedTagError, }; while (self.data.len < size) { try self.getMoreData(); } const str = self.data[0..size]; self.data = self.data[size..]; self.bytes -= size; return str; } fn itemSize(head: ValueHead) struct { bytes: u32, items: usize } { return switch (head) { .Str => |size| .{ .bytes = size, .items = 0 }, .Bin => |size| .{ .bytes = size, .items = 0 }, .Ext => |ext| .{ .bytes = ext.size, .items = 0 }, .Array => |size| .{ .bytes = 0, .items = size }, .Map => |size| .{ .bytes = 0, .items = 2 * size }, else => .{ .bytes = 0, .items = 0 }, }; } pub fn skipAhead(self: *Self, skipped: usize) Error!void { var items: usize = skipped; if (self.bytes > 0 or skipped > self.items) { return error.InvalidDecodeOperation; } while (self.bytes > 0 or items > 0) { if (self.bytes > 0) { if (self.data.len == 0) { try self.getMoreData(); } const skip = std.math.min(self.bytes, self.data.len); self.data = self.data[skip..]; self.bytes -= skip; } else if (items > 0) { const head = try self.readHead(); items -= 1; const size = itemSize(head); items += size.items; } } } }; const ArrayList = std.ArrayList; test { const testing = std.testing; const allocator = testing.allocator; var x = ArrayList(u8).init(allocator); defer x.deinit(); var enc = encoder(x.writer()); try enc.startArray(4); try enc.putInt(4); try enc.putInt(200); try testing.expectEqualSlices(u8, &[_]u8{ 0x94, 0x04, 0xcc, 0xc8 }, x.items); var decoder = Decoder{ .data = x.items }; try testing.expectEqual(ValueHead{ .Array = 4 }, try decoder.readHead()); try testing.expectEqual(ValueHead{ .Int = 4 }, try decoder.readHead()); try testing.expectEqual(ValueHead{ .Int = 200 }, try decoder.readHead()); }
src/mpack.zig
const std = @import("std"); pub const core = @import("gen/core.zig"); pub const glsl = @import("gen/glsl.zig"); pub const Builder = struct { allocator: *std.mem.Allocator, generator: u32, id_count: u32 = 0, insns: std.ArrayListUnmanaged(Instruction) = .{}, pub fn init(allocator: *std.mem.Allocator, generator: ?u32) Builder { return .{ .allocator = allocator, .generator = generator orelse 0, }; } pub fn deinit(self: *Builder) void { for (self.insns.items) |insn| { self.allocator.free(insn.operands); } self.insns.deinit(self.allocator); } pub fn newId(self: *Builder) Id { self.id_count += 1; return Id{ .n = self.id_count }; } pub fn writeOperand(operands: *std.ArrayList(Operand), comptime T: type, v: T) !void { switch (T) { Id => return operands.append(.{ .id = v }), u64 => return operands.append(.{ .int = v }), []const u8 => return operands.append(.{ .str = v }), else => {}, } if (comptime std.meta.trait.isTuple(T)) { inline for (std.meta.fields(T)) |field| { try writeOperand(operands, field.field_type, @field(v, field.name)); } return; } if (comptime std.meta.trait.isSlice(T)) { for (v) |v_val| { try writeOperand(v_val); } } switch (@typeInfo(T)) { .Optional => if (v) |v_val| { try writeOperand(v_val); }, .Enum => return operands.append(.{ .int = @enumToInt(v) }), .Union => { try operands.append(.{ .int = @enumToInt(v) }); inline for (std.meta.fields(T)) |field| { if (field.field_type == void) continue; if (v == @field(std.meta.Tag(T), field.name)) { try writeOperand(operands, field.field_type, @field(v, field.name)); } } return; }, .Struct => { try operands.append(.{ .int = v.bitmask() }); inline for (std.meta.fields(T)) |field| { if (field.field_type == bool) continue; if (@field(v, field.name)) |field_value| { try writeOperand(operands, std.meta.Child(field.field_type), field_value); } } return; }, else => @compileError("Cannot handle type '" ++ @typeName(T) ++ "'"), } } pub usingnamespace core.instructions; pub usingnamespace glsl.instructions; pub fn build(self: Builder, buf: *std.ArrayList(u32)) !void { try buf.append(core.magic_number); // Magic try buf.append(core.version); // Version try buf.append(self.generator); // Generator try buf.append(self.id_count + 1); // Bound - this number is greater than the largest ID try buf.append(0); // Reserved for (self.insns.items) |insn| { var nbyte: u16 = 1; for (insn.operands) |op| { nbyte += op.len(); } const start = buf.items.len; try buf.append(@as(u32, nbyte) << 16 | insn.op); for (insn.operands) |op| { try op.write(buf); } std.debug.assert(buf.items.len - start == nbyte); } } }; pub const Instruction = struct { op: u16, operands: []const Operand = &.{}, }; pub const Operand = union(enum) { id: Id, int: u64, str: []const u8, pub fn len(self: Operand) u16 { return switch (self) { .id => 1, .int => |int| @as(u16, 1) + @boolToInt(int >> 32 != 0), // FIXME: no clue if this is right .str => |str| @intCast(u16, ceilToMultiple(str.len + 1, 4)), }; } /// Returns the lowest multiple of `a` which is >= `x`. `a` must be a power of 2. fn ceilToMultiple(x: usize, a: u29) usize { std.debug.assert(std.math.isPowerOfTwo(a)); return ~((~x + 1) & (~@as(usize, a) + 1)) + 1; } pub fn write(self: Operand, buf: *std.ArrayList(u32)) !void { switch (self) { .id => |id| try buf.append(id.n), .int => |int| { // FIXME: no clue if this is right try buf.append(@truncate(u32, int)); if (int >> 32 != 0) { try buf.append(@truncate(u32, int >> 32)); } }, .str => |str| { var word: u32 = 0; for (str) |c, i| { word = @shlExact(word, 8); word |= c; if (i % 4 == 3) { try buf.append(word); word = 0; } } try buf.append(word); // Write any remaining bytes, followed by the 0 sentinel }, } } }; pub const Id = struct { n: u32 }; test "SPIR-V generation" { var b = Builder.init(std.testing.allocator, 1234); defer b.deinit(); try b.capability(.shader); try b.memoryModel(.logical, .glsl450); var buf = std.ArrayList(u32).init(std.testing.allocator); defer buf.deinit(); try b.build(&buf); try std.testing.expectEqualSlices(u32, &.{ // Header core.magic_number, core.version, 1234, 1, 0, // OpCapability Shader 0x0002_0011, 1, // OpMemoryModel Logical GLSL450 0x0003_000e, 0, 1, }, buf.items); }
src/spirv.zig
const std = @import("std"); const builtin = @import("builtin"); const io = std.io; const os = std.os; const fs = std.fs; const windows = os.windows; const posix = os.posix; const Mutex = std.Mutex; const TtyColor = enum { Red, Green, Yellow, Magenta, Cyan, Blue, Reset, }; fn Protected(comptime T: type) type { return struct { const Self = @This(); mutex: Mutex, private_data: T, const HeldMutex = struct { value: *T, held: Mutex.Held, pub fn release(self: HeldMutex) void { self.held.release(); } }; pub fn init(data: T) Self { return Self{ .mutex = Mutex.init(), .private_data = data, }; } pub fn acquire(self: *Self) HeldMutex { return HeldMutex{ .held = self.mutex.acquire(), .value = &self.private_data, }; } }; } const FOREGROUND_BLUE = 1; const FOREGROUND_GREEN = 2; const FOREGROUND_AQUA = 3; const FOREGROUND_RED = 4; const FOREGROUND_MAGENTA = 5; const FOREGROUND_YELLOW = 6; /// different levels of logging pub const Level = enum { const Self = @This(); Trace, Debug, Info, Warn, Error, Fatal, fn toString(self: Self) []const u8 { return switch (self) { Self.Trace => "TRACE", Self.Debug => "DEBUG", Self.Info => "INFO", Self.Warn => "WARN", Self.Error => "ERROR", Self.Fatal => "FATAL", }; } fn color(self: Self) TtyColor { return switch (self) { Self.Trace => TtyColor.Blue, Self.Debug => TtyColor.Cyan, Self.Info => TtyColor.Green, Self.Warn => TtyColor.Yellow, Self.Error => TtyColor.Red, Self.Fatal => TtyColor.Magenta, }; } }; /// a simple thread-safe logger pub const Logger = struct { const Self = @This(); const ProtectedOutStream = Protected(*fs.File.OutStream); file: fs.File, file_stream: fs.File.OutStream, out_stream: ?ProtectedOutStream, default_attrs: windows.WORD, level: Protected(Level), quiet: Protected(bool), use_color: bool, use_bright: bool, /// create `Logger`. pub fn new(file: fs.File, use_color: bool) Self { // TODO handle error var info: windows.CONSOLE_SCREEN_BUFFER_INFO = undefined; if (std.Target.current.os.tag == .windows) { _ = windows.kernel32.GetConsoleScreenBufferInfo(file.handle, &info); } return Self{ .file = file, .file_stream = file.outStream(), .out_stream = undefined, .level = Protected(Level).init(Level.Trace), .quiet = Protected(bool).init(false), .default_attrs = info.wAttributes, .use_color = use_color, .use_bright = true, }; } // can't be done in `Logger.new` because of no copy-elision fn getOutStream(self: *Self) ProtectedOutStream { if (self.out_stream) |out_stream| { return out_stream; } else { self.out_stream = ProtectedOutStream.init(&self.file_stream); return self.out_stream.?; } } fn setTtyColorWindows(self: *Self, color: TtyColor) void { // TODO handle errors const bright = if (self.use_bright) windows.FOREGROUND_INTENSITY else u16(0); _ = windows.SetConsoleTextAttribute(self.file.handle, switch (color) { TtyColor.Red => FOREGROUND_RED | bright, TtyColor.Green => FOREGROUND_GREEN | bright, TtyColor.Yellow => FOREGROUND_YELLOW | bright, TtyColor.Magenta => FOREGROUND_MAGENTA | bright, TtyColor.Cyan => FOREGROUND_AQUA | bright, TtyColor.Blue => FOREGROUND_BLUE | bright, TtyColor.Reset => self.default_attrs, }); } fn setTtyColor(self: *Self, color: TtyColor) !void { if (std.Target.current.os.tag == .windows and !os.supportsAnsiEscapeCodes(self.file.handle)) { self.setTtyColorWindows(color); } else { var out = self.getOutStream(); var out_held = out.acquire(); defer out_held.release(); const bright = if (self.use_bright) "\x1b[1m" else ""; return switch (color) { TtyColor.Red => out_held.value.*.print("{}\x1b[31m", .{bright}), TtyColor.Green => out_held.value.*.print("{}\x1b[32m", .{bright}), TtyColor.Yellow => out_held.value.*.print("{}\x1b[33m", .{bright}), TtyColor.Magenta => out_held.value.*.print("{}\x1b[35m", .{bright}), TtyColor.Cyan => out_held.value.*.print("{}\x1b[36m", .{bright}), TtyColor.Blue => out_held.value.*.print("{}\x1b[34m", .{bright}), TtyColor.Reset => blk: { _ = try out_held.value.*.write("\x1b[0m"); }, }; } } /// enable or disable color. pub fn setColor(self: *Self, use_color: bool) void { self.use_color = use_color; } /// enable or disable bright versions of the colors. pub fn setBright(self: *Self, use_bright: bool) void { self.use_bright = use_bright; } /// Set the minimum logging level. pub fn setLevel(self: *Self, level: Level) void { var held = self.level.acquire(); defer held.release(); held.value.* = level; } /// Outputs to stderr if true. true by default. pub fn setQuiet(self: *Self, quiet: bool) void { var held = self.quiet.acquire(); defer held.release(); held.value.* = quiet; } /// General purpose log function. pub fn log(self: *Self, level: Level, comptime fmt: []const u8, args: var) !void { const level_held = self.level.acquire(); defer level_held.release(); if (@enumToInt(level) < @enumToInt(level_held.value.*)) { return; } var out = self.getOutStream(); var out_held = out.acquire(); defer out_held.release(); var out_stream = out_held.value.*; const quiet_held = self.quiet.acquire(); defer quiet_held.release(); // TODO get filename and number // TODO get time as a string // time includes the year if (!quiet_held.value.*) { if (self.use_color and self.file.isTty()) { try out_stream.print("{} ", .{std.time.timestamp()}); try self.setTtyColor(level.color()); try out_stream.print("[{}]", .{level.toString()}); try self.setTtyColor(TtyColor.Reset); try out_stream.print(": ", .{}); // out_stream.print("\x1b[90m{}:{}:", filename, line); // self.resetTtyColor(); } else { try out_stream.print("{} [{s}]: ", .{ std.time.timestamp(), level.toString() }); } if (args.len > 0) { out_stream.print(fmt, args) catch return; } else { _ = out_stream.write(fmt) catch return; } _ = out_stream.write("\n") catch return; } } /// log at level `Level.Trace`. pub fn logTrace(self: *Self, comptime fmt: []const u8, args: var) void { self.log(Level.Trace, fmt, args) catch return; } /// log at level `Level.Debug`. pub fn logDebug(self: *Self, comptime fmt: []const u8, args: var) void { self.log(Level.Debug, fmt, args) catch return; } /// log at level `Level.Info`. pub fn logInfo(self: *Self, comptime fmt: []const u8, args: var) void { self.log(Level.Info, fmt, args) catch return; } /// log at level `Level.Warn`. pub fn logWarn(self: *Self, comptime fmt: []const u8, args: var) void { self.log(Level.Warn, fmt, args) catch return; } /// log at level `Level.Error`. pub fn logError(self: *Self, comptime fmt: []const u8, args: var) void { self.log(Level.Error, fmt, args) catch return; } /// log at level `Level.Fatal`. pub fn logFatal(self: *Self, comptime fmt: []const u8, args: var) void { self.log(Level.Fatal, fmt, args) catch return; } }; test "log_with_color" { var logger = Logger.new(io.getStdOut(), true); std.debug.warn("\n", .{}); logger.logTrace("hi", .{}); logger.logDebug("hey", .{}); logger.logInfo("hello", .{}); const world = "world"; const num = 12345; logger.logInfo("hello {} {}", .{ world, num }); logger.logWarn("greetings", .{}); logger.logError("salutations", .{}); logger.logFatal("goodbye", .{}); } fn worker(logger: *Logger) void { logger.logTrace("hi", .{}); std.time.sleep(10000); logger.logDebug("hey", .{}); std.time.sleep(10); logger.logInfo("hello", .{}); std.time.sleep(100); logger.logWarn("greetings", .{}); std.time.sleep(1000); logger.logError("salutations", .{}); std.time.sleep(10000); logger.logFatal("goodbye", .{}); std.time.sleep(1000000000); } test "log_thread_safe" { var logger = Logger.new(io.getStdOut(), true); std.debug.warn("\n", .{}); const thread_count = 5; var threads: [thread_count]*std.Thread = undefined; for (threads) |*t| { t.* = try std.Thread.spawn(&logger, worker); } for (threads) |t| { t.wait(); } }
src/index.zig
usingnamespace @import("root").preamble; /// Features that should be enabled in the code for the red black tree pub const Features = struct { enable_iterators_cache: bool, enable_kth_queries: bool, enable_not_associatve_augment: bool, }; /// Config for red black tree. Includes enabled features and callbacks for comparison and augmenting pub const Config = struct { augment_callback: ?type, comparator: type, features: Features, }; /// Color type pub const Color = enum { red, black }; /// Node in the red black tree pub fn Node(comptime features: Features) type { return struct { /// Node's descendants (desc[0] - left, desc[1] - right) desc: [2]?*@This(), /// Node's parent par: ?*@This(), // Number of nodes in the subtree subtree_size: if (features.enable_kth_queries) usize else void, /// Node color color: Color, /// Data for iterator extension iterators: if (features.enable_iterators_cache) [2]?*@This() else void, /// Create empty node fn init() @This() { return .{ .desc = .{ null, null }, .iterators = if (features.enable_iterators_cache) .{ null, null } else {}, .par = null, .subtree_size = if (features.enable_kth_queries) 1 else {}, .color = .red, }; } /// Query direction from parent fn direction(self: *const @This()) u1 { return if (self.par) |parent| @boolToInt(parent.desc[1] == self) else 0; } // If `self` if null, return black color, otherwise return color of `self` fn colorOrBlack(self: ?*const @This()) Color { return (self orelse return .black).color; } // Get node's sibling, or return null if there is none fn sibling(self: *const @This()) ?*@This() { const pos = self.direction(); return if (self.par) |parent| parent.desc[1 - pos] else null; } }; } /// Red black tree itself pub fn Tree(comptime T: type, comptime member_name: []const u8, comptime cfg: Config) type { const NodeType = Node(cfg.features); const enable_iterators_cache = cfg.features.enable_iterators_cache; const enable_kth_queries = cfg.features.enable_kth_queries; // Make sure that comparator type is valid if (!@hasDecl(cfg.comparator, "compare")) { @compileError("Comparator should define \"compare\" function"); } const expected_cmp_type = fn (*const cfg.comparator, *const T, *const T) bool; if (!(@TypeOf(cfg.comparator.compare) == expected_cmp_type)) { @compileError("Invalid type of \"compare\" function"); } // Make sure that augment callback is valid if (cfg.augment_callback) |augment_callback| { if (!@hasDecl(augment_callback, "augment")) { @compileError("Augment callback should define \"augment\" function"); } const expected_augment_callback_type = fn (*const augment_callback, *T) bool; if (!(@TypeOf(augment_callback.augment) == expected_augment_callback_type)) { @compileError("Invalid type of \"augment\" function"); } } return struct { /// Used inside extensions const TreeType = @This(); /// root of the tree root: ?*NodeType, /// comparator used for insertions/deletitions comparator: cfg.comparator, /// callback used for augmenting augment_callback: if (cfg.augment_callback) |callback| callback else void, /// size of the tree, size: usize, /// iterators extension data and functions iterators: if (enable_iterators_cache) struct { ends: [2]?*NodeType, /// First element in a tree pub fn first(self: *const @This()) ?*T { return TreeType.nodeToRefOpt(self.ends[0]); } /// Last element in a tree pub fn last(self: *const @This()) ?*T { return TreeType.nodeToRefOpt(self.ends[1]); } /// Get the next node in left-to-right order pub fn next(_: *const @This(), ref: *T) ?*T { return TreeType.nodeToRefOpt(TreeType.refToNode(ref).iterators[1]); } /// Get the previous node in left-to-right order pub fn prev(_: *const @This(), ref: *T) ?*T { return TreeType.nodeToRefOpt(TreeType.refToNode(ref).iterators[0]); } } else void, /// kth queries extensions kth: if (enable_kth_queries) struct { /// Fix zero sized pointer issue in zig compiler /// "the issue is: kth is a zero-size type, so the pointer to kth is /// itself zero-sized, and therefore has no data" /// Issue in zig lang repository: "https://github.com/ziglang/zig/issues/1530" temp_fix: u8, /// Get subtree size pub fn getSubtreeSize(node: ?*const NodeType) usize { return if (node) |node_nonnull| node_nonnull.subtree_size else 0; } /// Get kth element pub fn at(self: *const @This(), index: usize) ?*T { // Done so that user can write `tree.kth.at(n)` const tree = @fieldParentPtr(TreeType, "kth", self); // The method used here is to perform descent // We keep record of index at which we want to retrive // element in `offset_needed` variable var current_nullable = tree.root; var offset_needed = index; while (current_nullable) |current| { if (getSubtreeSize(current.desc[0]) == offset_needed) { // If left subtree has exactly as many nodes as we need, // current node is node we are searching for // (current node is at <left subtree size> index in its subtree) return nodeToRef(current); } else if (getSubtreeSize(current.desc[0]) > offset_needed) { // If left subtree has more nodes than we need, // nth element should be in the left subtree current_nullable = current.desc[0]; } else { // If `offset_needed` is greater than the amount of nodes in the // right subtree, we need to search in the right subtree // The index is now different, as we want to skip left subtree + // current node offset_needed -= (1 + getSubtreeSize(current.desc[0])); current_nullable = current.desc[1]; } } // Tree is small and there is no nth node return null; } } else void, /// Given the pointer to the element, returns previous element in the tree pub fn right(node: *const T) ?*T { return nodeToRef(refToNode(node).desc[0]); } /// Given the pointer to the element, returns next element in the tree pub fn left(node: *const T) ?*T { return nodeToRef(refToNode(node).desc[1]); } /// Convert reference to red black tree node to reference to T pub fn nodeToRef(node: *NodeType) *T { return @fieldParentPtr(T, member_name, node); } /// Convert reference to T to reference to red black tree node pub fn refToNode(ref: *T) *NodeType { return &@field(ref, member_name); } /// Convert nullable reference to red black tree node to nullable reference to T pub fn nodeToRefOpt(node: ?*NodeType) ?*T { return if (node) |node_nonnull| nodeToRef(node_nonnull) else null; } /// Convert nullable reference to T to nullable reference to red black tree node pub fn refToNodeOpt(ref: ?*T) ?*NodeType { return if (ref) |ref_nonnull| refToNode(ref_nonnull) else null; } // u1 is returned to simplify accesses in `desc` and `neighbours` arrays fn compareNodes(self: *const @This(), l: *NodeType, r: *NodeType) u1 { return @boolToInt(self.comparator.compare(nodeToRef(l), nodeToRef(r))); } /// Call augment callback on a single node fn updateParentAugment(node: *NodeType) bool { if (cfg.augment_callback) |_| { return self.augment_callback.augment(refToNode(node)); } return false; } /// Propogate augment callback fn updatePathAugment(node: *NodeType) void { var current_nullable: ?*NodeType = node; while (current_nullable) |current| { if (!updateParentAugment(current)) { return; } current_nullable = current.par; } } /// Update data used for kth extension locally fn updateParentSubtreeSize(node: *NodeType) bool { if (enable_kth_queries) { var subtree_size: usize = 1; if (node.desc[0]) |l| { subtree_size += l.subtree_size; } if (node.desc[1]) |r| { subtree_size += r.subtree_size; } if (node.subtree_size != subtree_size) { node.subtree_size = subtree_size; // subtree size has changed, propogate to parent return true; } // subtree size has not changed, don't propogate to parent return false; } return false; } /// Propogate subtree sizes updates fn updatePathSubtreeSizes(node: *NodeType) void { var current_nullable: ?*NodeType = node; while (current_nullable) |current| { if (!updateParentSubtreeSize(current)) { return; } current_nullable = current.par; } } /// Rotate subtree at `node` in `dir` direction. Tree is passed because /// root updates might be needed fn rotate(self: *@This(), node: *NodeType, dir: u1) void { const new_top_nullable = node.desc[1 - dir]; const new_top = new_top_nullable.?; const mid = new_top.desc[dir]; const parent = node.par; const pos = node.direction(); node.desc[1 - dir] = mid; if (mid) |mid_nonnull| { mid_nonnull.par = node; } new_top.desc[dir] = node; node.par = new_top; if (parent) |parent_nonnull| { parent_nonnull.desc[pos] = new_top; new_top.par = parent; } else { self.root = new_top; new_top.par = null; new_top.color = .black; } _ = updateParentSubtreeSize(node); _ = updateParentAugment(node); // If augment function is not associative, // we need to call aggregate on parent too if (cfg.features.enable_not_associatve_augment) { _ = updateParentSubtreeSize(new_top); _ = updateParentAugment(new_top); if (parent) |parent_nonnull| { updatePathSubtreeSizes(parent_nonnull); updatePathAugment(parent_nonnull); } } else { _ = updateParentSubtreeSize(new_top); _ = updateParentAugment(new_top); } } fn fixInsertion(self: *@This(), node: *NodeType) void { // Situation we are trying to fix: double red // According to red black tree invariants, only // // G(X) Cast // / \ C - current node (R) - red // P(R) U(X) P - parent (B) - black // / G - grandparent (X) - color unknown // C(R) U - uncle // var current: *NodeType = node; while (current.par) |parent| { // if parent is black, there is no double red. See diagram above. if (parent.color == .black) { break; } const uncle = parent.sibling(); // Root has to be black, and as parent is red, grandparent should exist const grandparent = parent.par.?; const dir = current.direction(); if (NodeType.colorOrBlack(uncle) == .black) { const parent_dir = parent.direction(); if (parent_dir == dir) { // G(B) P(B) // / \ / \ // P(R) U(B) ------> C(R) G(R) // / \ // C(R) U(B) // // If uncle is black, grandparent has to be black, as parent is red. // If grandparent was red, both of its children would have to be black, // but parent is red. // Grandparent color is updated later. Black height on path to B has not // changed // (before: grandparent black and uncle black, now P black and U black) self.rotate(grandparent, 1 - dir); parent.color = .black; } else { // G(B) G(B) C(B) // / \ / \ / \ // P(R) U(B) ----> C(R) U(B) ---> P(R) G(R) // \ / \ // C(R) P(R) U(B) // // Final recoloring of grandparent is done on line 339 as well. // Black height on path to U has not changed // (before: G and U black, after: C and U black) // On the old track in P direction, nothing has changed as well self.rotate(parent, 1 - dir); self.rotate(grandparent, dir); current.color = .black; } grandparent.color = .red; break; } else { // G(B) G(R) <- potential double red fix needed // / \ / \ // P(R) U(R) ----> P(B) U(B) // / / // C(R) C(R) // // The solution for the case in which uncle is red is to "push blackness down". // We recolor parent and uncle to black and grandparent to red. // It is easy to verify that black heights for all nodes have not changed. // The only problem we have encountered is that grandparent's parent is red. // If that is the case, we can have double red again. As such, we continue // fixing by setting `current` to grandparent // If uncle is red, it is not null const uncle_nonnull = uncle.?; parent.color = .black; uncle_nonnull.color = .black; grandparent.color = .red; current = grandparent; } } // We were inserting node, so root is not null self.root.?.color = .black; } /// Attaches node that is not yet in tree to the node in tree fn attachNode(self: *@This(), parent: *NodeType, node: *NodeType, pos: u1) void { parent.desc[pos] = node; node.par = parent; if (enable_iterators_cache) { // parent is a successor/predecessor // next_in_attach_dir has on opposite role, i.e. if parent is predecessor // it will be successor and vice versa // connecting next_in_attach_dir and node using iterators const next_in_attach_dir = parent.iterators[pos]; node.iterators[pos] = next_in_attach_dir; // it may not exist tho, so it would not hurt to check if first/last pointers // shoul be updated if (next_in_attach_dir) |neighbour| { neighbour.iterators[1 - pos] = node; } else { self.iterators.ends[pos] = node; } // connecting parent and node with iterators parent.iterators[pos] = node; node.iterators[1 - pos] = parent; } } /// Helper for `insert` fn insertImpl(self: *@This(), node: *NodeType) void { // See node constructor. All values are zeroed and color is set to .red node.* = NodeType.init(); // Check if node is root if (self.root) |root| { // While doing descent, we remember previous node, so that when current node // becomes null, we will know which node we should attach our new node to var prev: *NodeType = undefined; var current: ?*NodeType = root; // Last direction is remembered in order to determine whether // new node should be left or right child var last_direction: u1 = 0; while (current) |current_nonnull| { // compareNodes already returns direction in which we should go last_direction = self.compareNodes(node, current_nonnull); prev = current_nonnull; current = current_nonnull.desc[last_direction]; } // Attach node to prev. self.attachNode(prev, node, last_direction); self.fixInsertion(node); updatePathSubtreeSizes(prev); updatePathAugment(prev); } else { // If node is root, our job is easy node.color = .black; if (enable_iterators_cache) { self.iterators.ends[0] = node; self.iterators.ends[1] = node; } self.root = node; } self.size += 1; } /// Insert node in tree pub fn insert(self: *@This(), node: *T) void { self.insertImpl(refToNode(node)); } /// Get other node to delete if `node` has two children fn findReplacement(node: *NodeType) *NodeType { // Replacement is only calculated on nodes with two children var current: *NodeType = node.desc[0].?; while (current.desc[1]) |next| { current = next; } return current; } /// Helper for iterators swap. Changes pointers to `node` to pointers to `replacement` fn replaceInIterList( iterators: *[2]?*NodeType, node: *NodeType, replacement: *NodeType, ) void { if (iterators[0] == node) { iterators[0] = replacement; } if (iterators[1] == node) { iterators[1] = replacement; } } /// Second helper for iterators swap. Changes ends of the tree from `node` /// to `replacement` if corresponding element in `iterators` is null. Used to update tree /// iterator chain ends fn updateEndPointers( self: *@This(), iterators: *[2]?*NodeType, replacement: *NodeType, ) void { if (iterators[0]) |l| { l.iterators[1] = replacement; } else { self.iterators.ends[0] = replacement; } if (iterators[1]) |r| { r.iterators[0] = replacement; } else { self.iterators.ends[1] = replacement; } } /// Swap node with replacement found by `findReplacement` /// Does that without relocating node's data fn pointerSwap(self: *@This(), node: *NodeType, replacement: *NodeType) void { // Node should have two children std.debug.assert(node.desc[0] != null); std.debug.assert(node.desc[1] != null); // Swap nodes colors const node_color = node.color; node.color = replacement.color; replacement.color = node_color; // Cache node's pointers const node_parent = node.par; const replacement_parent = replacement.par; const node_children = node.desc; const replacement_children = replacement.desc; // Cache node's positions const node_dir = node.direction(); const replacement_dir = replacement.direction(); // Check out `findReplacement`. Proof left for the reader std.debug.assert(replacement_children[1] == null); // Swap children pointers and set node's parent if (node.desc[0] == replacement) { // Case 1: replacement is left child of node // as findReplacement only // Swap children node.desc = replacement_children; // As `replaced_children` right parent is null (see assert), // only check left children. if (replacement_children[0]) |repl_child| { repl_child.par = node; } // Replacement's left child should be node now // as roles have been exchanged replacement.desc[0] = node; // as node and replacement swapped roles // node's parent is now replacement node.par = replacement; // right child of replacement remains unchanged from node replacement.desc[1] = node_children[1]; if (node_children[1]) |node_child| { node_child.par = replacement; } } else { // Case 2: replacement is not a child of node // swap children replacement.desc = node_children; // They are both not null, as node has two children node_children[0].?.par = replacement; node_children[1].?.par = replacement; node.desc = replacement_children; // Replacement can only have left child. // Update its parent if needed if (replacement_children[0]) |repl_child| { repl_child.par = node; } node.par = replacement_parent; // Replacement parent should exist // As it is down the tree from node replacement_parent.?.desc[replacement_dir] = node; } // Update parent link for replacement replacement.par = node_parent; if (node_parent) |parent| { // Node wasn't root. Change link from parent parent.desc[node_dir] = replacement; } else { // Node was root. Set tree root to replacement self.root = replacement; replacement.par = null; replacement.color = .black; } // Swap iterators if needed if (enable_iterators_cache) { var node_iterators = node.iterators; var replacement_iterators = replacement.iterators; // If something poitned to replacement, it should now point to node // and vise versa replaceInIterList(&node_iterators, replacement, node); replaceInIterList(&replacement_iterators, node, replacement); self.updateEndPointers(&node_iterators, replacement); self.updateEndPointers(&replacement_iterators, node); node.iterators = replacement_iterators; replacement.iterators = node_iterators; } // Swap subtree elements count if needed if (enable_kth_queries) { const node_subtree_size = node.subtree_size; node.subtree_size = replacement.subtree_size; replacement.subtree_size = node_subtree_size; } // Call aggregate updates if needed // Subtree sizes are already updated updatePathAugment(replacement); } /// Ensure that node to delete has at most one child // TODO: add option to use value swap in config fn replaceIfNeeded(self: *@This(), node: *NodeType) void { if (node.desc[0] != null and node.desc[1] != null) { const replacement = findReplacement(node); pointerSwap(self, node, replacement); } } /// Cut from iterators list if enabled fn cutFromIterList(self: *@This(), node: *NodeType) void { if (enable_iterators_cache) { if (node.iterators[0]) |l| { l.iterators[1] = node.iterators[1]; } else { self.iterators.ends[0] = node.iterators[1]; if (node.iterators[1]) |r| { r.iterators[0] = null; } } if (node.iterators[1]) |r| { r.iterators[0] = node.iterators[0]; } else { self.iterators.ends[1] = node.iterators[0]; if (node.iterators[0]) |l| { l.iterators[1] = null; } } } } fn fixDoubleBlack(self: *@This(), node: *NodeType) void { // situation: node is a black leaf // simply deleteing node will harm blackness height rule // // P(X) Cast: // / C - current node P - parent (R) - red (X) - unknown // C(B) S - sibling N - newphew (B) - black // // the solution is to push double black up the tree until fixed // think of current_node as node we want to recolor as red // (removing node has the same effect on black height) var current_node = node; while (current_node.par) |current_node_par| { const current_node_dir = current_node.direction(); var current_node_sibling = current_node.sibling(); // red sibling case. Make it black sibling case // // P(X) S(B) // / \ -----> / \ // C(B) S(R) P(R) Z(B) // / \ / \ // W(B) Z(B) C(B) W(B) // // W and Z should be black, as S is red (check rbtree invariants) // This transformation leaves us with black sibling if (current_node_sibling) |sibling| { if (sibling.color == .red) { self.rotate(current_node_par, current_node_dir); sibling.color = .black; current_node_par.color = .red; current_node_sibling = current_node.sibling(); } } // p subtree at this exact moment // // P(X) // / \ // C(B) S(B) (W is renamed to S) // // sibling should exist, otherwise there are two paths // from parent with different black heights var sibling = current_node_sibling.?; // if both children of sibling are black, and parent is black too, there is easy fix const left_sibling_black = NodeType.colorOrBlack(sibling.desc[0]) == .black; const right_sibling_black = NodeType.colorOrBlack(sibling.desc[1]) == .black; if (left_sibling_black and right_sibling_black) { if (current_node_par.color == .black) { // P(B) P(B) // / \ / \ // C(B) S(B) --------> C(B) S(R) // // if parent is already black, we can't compensate changing S color to red // (which changes black height) locally. Instead we jump to a new iteration // of the loop, requesting to recolor P to red sibling.color = .red; current_node = current_node_par; continue; } else { // P(R) P(B) // / \ / \ // C(B) S(B) --------> C(B) S(R) // // in this case there is no need to fix anything else, as we compensated for // changing S color to R with changing N's color to black. This means that // black height on this path won't change at all. current_node_par.color = .black; sibling.color = .red; return; } } const parent_color = current_node_par.color; // check if red nephew has the same direction from parent if (NodeType.colorOrBlack(sibling.desc[current_node_dir]) == .red) { // P(X) P(X) // / \ / \ // C(B) S(B) C(B) N(B) // / \ -----> / \ // N(R) Z(X) X(B) S(R) // / \ / \ // X(B) Y(B) Y(B) Z(X) // // exercise for the reader: check that black heights // on paths from P to X, Y, and Z remain unchanged // the purpose is to make this case right newphew case // (in which direction of red nephew is opposite to direction of node) self.rotate(sibling, 1 - current_node_dir); sibling.color = .red; // nephew exists and it will be a new subling sibling = current_node.sibling().?; sibling.color = .black; } // P(X) S(P's old color) // / \ / \ // C(B) S(B) -----> P(B) N(B) // / \ / \ // Y(X) N(R) C(B) Y(X) // // The black height on path from P to Y is the same as on path from S to Y in a new // tree. The black height on path from P to N is the same as on path from S to N in // a new tree. We only increased black height on path from P/S to C. But that is // fine, since recoloring C to red or deleting it is our final goal self.rotate(current_node_par, current_node_dir); current_node_par.color = .black; sibling.color = parent_color; if (sibling.desc[1 - current_node_dir]) |nephew| { nephew.color = .black; } return; } } /// Remove helper fn removeImpl(self: *@This(), node: *NodeType) void { // We are only handling deletition of a node with at most one child self.replaceIfNeeded(node); const node_parent_nullable = node.par; // Get node's only child if any var node_child_nullable = node.desc[0]; if (node_child_nullable == null) { node_child_nullable = node.desc[1]; } const node_dir = node.direction(); if (node_child_nullable) |child| { // If child exist and is the only child, it must be red // otherwise if (node_parent_nullable) |parent| { parent.desc[node_dir] = child; child.par = parent; } else { self.root = child; child.par = null; } child.color = .black; self.cutFromIterList(node); // calling augment callback only after all updates if (node_parent_nullable) |parent| { updatePathAugment(parent); updatePathSubtreeSizes(parent); } self.size -= 1; return; } if (node.color == .red) { // if color is red, node is not root, and parent should exist const parent = node_parent_nullable.?; parent.desc[node.direction()] = null; self.cutFromIterList(node); updatePathAugment(parent); updatePathSubtreeSizes(parent); self.size -= 1; return; } if (node_parent_nullable) |parent| { // hard case: double black self.fixDoubleBlack(node); parent.desc[node.direction()] = null; self.cutFromIterList(node); updatePathAugment(parent); updatePathSubtreeSizes(parent); } else { // node is simply root with no children self.root = null; self.cutFromIterList(node); } self.size -= 1; } /// Removes element from the red black tree pub fn remove(self: *@This(), node: *T) void { self.removeImpl(refToNode(node)); } /// Helper for upper and lower bound functions fn boundInDirection( self: *const @This(), comptime Predicate: type, pred: *const Predicate, dir: u1, ) ?*T { comptime { if (!@hasDecl(Predicate, "check")) { @compileError("Predicate type should define \"check\" function"); } const ExpectedPredicateType = fn (*const Predicate, *const T) bool; if (@TypeOf(Predicate.check) != ExpectedPredicateType) { @compileError("Invalid type of check function"); } } var candidate: ?*NodeType = null; var current_nullable = self.root; while (current_nullable) |current| { if (pred.check(nodeToRef(current))) { candidate = current; current_nullable = current.desc[dir]; } else { current_nullable = current.desc[1 - dir]; } } return nodeToRefOpt(candidate); } /// Find the rightmost node for which predicate returns true pub fn upperBound( self: *const @This(), comptime predicate: type, pred: *const predicate, ) ?*T { return self.boundInDirection(predicate, pred, 1); } /// Find the leftmost node for which predicate returns true pub fn lowerBound( self: *const @This(), comptime predicate: type, pred: *const predicate, ) ?*T { return self.boundInDirection(predicate, pred, 0); } /// Initialize empty red black tree pub fn init( comp: cfg.comparator, augment_callback: if (cfg.augment_callback) |callback| callback else void, ) @This() { return .{ .root = null, .iterators = if (enable_iterators_cache) .{ .ends = .{ null, null } } else {}, .comparator = comp, .augment_callback = augment_callback, .size = 0, .kth = if (enable_kth_queries) .{ .temp_fix = 0 } else {}, }; } }; } // TODO: add test to cover augmented cases (which for now may be just plain wrong) test "red black tree" { const features = Features{ .enable_iterators_cache = true, .enable_kth_queries = true, .enable_not_associatve_augment = false, }; const IntTreeNode = struct { val: usize, hook: Node(features) = undefined }; const IntComparator = struct { pub fn compare( self: *const @This(), left: *const IntTreeNode, right: *const IntTreeNode, ) bool { _ = self; return left.val >= right.val; } }; const int_tree_config = Config{ .features = features, .augment_callback = null, .comparator = IntComparator, }; const TreeType = Tree(IntTreeNode, "hook", int_tree_config); var tree = TreeType.init(.{}, {}); const InorderListItem = struct { val: usize, color: Color, }; const generate_inorder = struct { pub fn generateInOrder(node: ?*IntTreeNode, trace: []InorderListItem, pos: usize) usize { if (node) |node_nonnull| { if (node_nonnull.hook.par) |parent| { const cond = parent.desc[node_nonnull.hook.direction()] == &(node_nonnull.hook); std.debug.assert(cond); } var current_pos = pos; current_pos = generateInOrder( TreeType.nodeToRefOpt(node_nonnull.hook.desc[0]), trace, current_pos, ); trace[current_pos].color = node_nonnull.hook.color; trace[current_pos].val = node_nonnull.val; return generateInOrder( TreeType.nodeToRefOpt(node_nonnull.hook.desc[1]), trace, current_pos + 1, ); } return pos; } }.generateInOrder; const verifyInOrder = struct { fn verifyInOrder(trace: []InorderListItem, result: []InorderListItem) bool { for (result) |elem, i| { if (trace[i].color != elem.color or trace[i].val != elem.val) { return false; } } return true; } }.verifyInOrder; // Insertion test var nodes = [_]IntTreeNode{ .{ .val = 7 }, .{ .val = 3 }, .{ .val = 18 }, .{ .val = 10 }, .{ .val = 22 }, .{ .val = 8 }, .{ .val = 11 }, .{ .val = 26 }, .{ .val = 2 }, .{ .val = 6 }, .{ .val = 13 }, }; for (nodes) |*node| { tree.insert(node); } var inorder: [11]InorderListItem = undefined; _ = generate_inorder(TreeType.nodeToRefOpt(tree.root), &inorder, 0); var expected_result = [_]InorderListItem{ .{ .val = 2, .color = .red }, .{ .val = 3, .color = .black }, .{ .val = 6, .color = .red }, .{ .val = 7, .color = .red }, .{ .val = 8, .color = .black }, .{ .val = 10, .color = .black }, .{ .val = 11, .color = .black }, .{ .val = 13, .color = .red }, .{ .val = 18, .color = .red }, .{ .val = 22, .color = .black }, .{ .val = 26, .color = .red }, }; std.testing.expect(verifyInOrder(&inorder, &expected_result)); // Queries test const UpperBoundSearchPredicate = struct { val: usize, fn check(self: *const @This(), node: *const IntTreeNode) bool { return node.val <= self.val; } }; const query = struct { fn query(t: *const TreeType, val: usize) ?*IntTreeNode { const pred = UpperBoundSearchPredicate{ .val = val }; return t.upperBound(UpperBoundSearchPredicate, &pred); } }.query; tree.remove(query(&tree, 18).?); tree.remove(query(&tree, 11).?); tree.remove(query(&tree, 3).?); tree.remove(query(&tree, 10).?); tree.remove(query(&tree, 22).?); std.testing.expect(query(&tree, 16).?.val == 13); std.testing.expect(query(&tree, 0) == null); _ = generate_inorder(TreeType.nodeToRefOpt(tree.root), &inorder, 0); var expected_result2 = [_]InorderListItem{ .{ .val = 2, .color = .black }, .{ .val = 6, .color = .red }, .{ .val = 7, .color = .black }, .{ .val = 8, .color = .black }, .{ .val = 13, .color = .black }, .{ .val = 26, .color = .red }, }; std.testing.expect(verifyInOrder(&inorder, &expected_result2)); std.testing.expect(tree.kth.at(0).?.val == 2); std.testing.expect(tree.kth.at(1).?.val == 6); std.testing.expect(tree.kth.at(2).?.val == 7); std.testing.expect(tree.kth.at(3).?.val == 8); std.testing.expect(tree.kth.at(4).?.val == 13); std.testing.expect(tree.kth.at(5).?.val == 26); std.testing.expect(tree.kth.at(6) == null); // Check size std.testing.expect(tree.size == 6); }
lib/containers/rbtree.zig
const std = @import("std"); const iup = @import("iup.zig"); const MainLoop = iup.MainLoop; const Dialog = iup.Dialog; const Button = iup.Button; const MessageDlg = iup.MessageDlg; const Multiline = iup.Multiline; const Label = iup.Label; const Text = iup.Text; const VBox = iup.VBox; const HBox = iup.HBox; const Menu = iup.Menu; const SubMenu = iup.SubMenu; const Separator = iup.Separator; const Fill = iup.Fill; const Item = iup.Item; const FileDlg = iup.FileDlg; const Toggle = iup.Toggle; const Tabs = iup.Tabs; const ScreenSize = iup.ScreenSize; const Image = iup.Image; const ImageRgb = iup.ImageRgb; const ImageRgba = iup.ImageRgba; pub fn main() !void { try MainLoop.open(); defer MainLoop.close(); var dlg = try create_dialog(); defer dlg.deinit(); try dlg.showXY(.Center, .Center); try MainLoop.beginLoop(); } fn create_dialog() !*Dialog { var tabs1 = Tabs.init() .setTabTitle(0, "TAB A") .setTabTitle(1, "TAB B") .setChildren( .{ VBox.init() .setChildren( .{ Label.init().setTitle("Inside Tab A"), Button.init().setTitle("Button A"), }, ), VBox.init() .setChildren( .{ Label.init().setTitle("Inside Tab B"), Button.init().setTitle("Button B"), }, ), }, ); var tabs2 = Tabs.init() .setTabType(.Left) .setTabTitle(0, "TAB C") .setTabTitle(1, "TAB D") .setChildren( .{ VBox.init() .setChildren( .{ Label.init().setTitle("Inside Tab C"), Button.init().setTitle("Button C"), }, ), VBox.init() .setChildren( .{ Label.init().setTitle("Inside Tab D"), Button.init().setTitle("Button D"), }, ), }, ); return try (Dialog.init() .setTitle("IUP for Zig - Tabs") .setSize(ScreenSize{ .Size = 200 }, ScreenSize{ .Size = 90 }) .setChildren( .{ HBox.init() .setMargin(10, 10) .setGap(10) .setChildren( .{ tabs1, tabs2, }, ), }, ).unwrap()); }
src/tabs_example.zig
//-------------------------------------------------------------------------------- // Section: Types (4) //-------------------------------------------------------------------------------- pub const OPERATION_START_FLAGS = enum(u32) { D = 1, _, pub fn initFlags(o: struct { D: u1 = 0, }) OPERATION_START_FLAGS { return @intToEnum(OPERATION_START_FLAGS, (if (o.D == 1) @enumToInt(OPERATION_START_FLAGS.D) else 0) ); } }; pub const OPERATION_START_TRACE_CURRENT_THREAD = OPERATION_START_FLAGS.D; pub const OPERATION_END_PARAMETERS_FLAGS = enum(u32) { D = 1, _, pub fn initFlags(o: struct { D: u1 = 0, }) OPERATION_END_PARAMETERS_FLAGS { return @intToEnum(OPERATION_END_PARAMETERS_FLAGS, (if (o.D == 1) @enumToInt(OPERATION_END_PARAMETERS_FLAGS.D) else 0) ); } }; pub const OPERATION_END_DISCARD = OPERATION_END_PARAMETERS_FLAGS.D; pub const OPERATION_START_PARAMETERS = extern struct { Version: u32, OperationId: u32, Flags: OPERATION_START_FLAGS, }; pub const OPERATION_END_PARAMETERS = extern struct { Version: u32, OperationId: u32, Flags: OPERATION_END_PARAMETERS_FLAGS, }; //-------------------------------------------------------------------------------- // Section: Functions (2) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows8.0' pub extern "ADVAPI32" fn OperationStart( OperationStartParams: ?*OPERATION_START_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows8.0' pub extern "ADVAPI32" fn OperationEnd( OperationEndParams: ?*OPERATION_END_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (1) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; test { @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/storage/operation_recorder.zig
const std = @import("std"); const Gateway = @import("../Gateway.zig"); const util = @import("../util.zig"); const log = std.log.scoped(.zCord); const Heartbeat = @This(); handler: union(enum) { thread: *ThreadHandler, callback: CallbackHandler, }, pub const Strategy = union(enum) { thread, callback: CallbackHandler, pub const default = Strategy.thread; }; pub const Message = enum { start, ack, stop, deinit, }; pub fn init(gateway: *Gateway, strategy: Strategy) !Heartbeat { return Heartbeat{ .handler = switch (strategy) { .thread => .{ .thread = try ThreadHandler.create(gateway) }, .callback => |cb| .{ .callback = cb }, }, }; } pub fn deinit(self: Heartbeat) void { switch (self.handler) { .thread => |thread| thread.destroy(), .callback => {}, } } pub fn send(self: Heartbeat, msg: Message) void { switch (self.handler) { .thread => |thread| thread.mailbox.putOverwrite(msg), .callback => |cb| cb.func(cb.context, msg), } } pub const CallbackHandler = struct { context: *c_void, func: fn (ctx: *c_void, msg: Message) void, }; const ThreadHandler = struct { allocator: *std.mem.Allocator, mailbox: util.Mailbox(Message), thread: std.Thread, fn create(gateway: *Gateway) !*ThreadHandler { const result = try gateway.allocator.create(ThreadHandler); errdefer gateway.allocator.destroy(result); result.allocator = gateway.allocator; try result.mailbox.init(); errdefer result.mailbox.deinit(); result.thread = try std.Thread.spawn(.{}, handler, .{ result, gateway }); return result; } fn destroy(ctx: *ThreadHandler) void { ctx.mailbox.putOverwrite(.deinit); // Reap the thread ctx.thread.join(); ctx.mailbox.deinit(); ctx.allocator.destroy(ctx); } fn handler(ctx: *ThreadHandler, gateway: *Gateway) void { var active = true; var acked = true; while (true) { if (!active) { switch (ctx.mailbox.get()) { .start => { active = true; acked = true; }, .ack, .stop => {}, .deinit => return, } } else { if (ctx.mailbox.getWithTimeout(gateway.heartbeat_interval_ms * std.time.ns_per_ms)) |msg| { switch (msg) { .start => acked = true, .ack => { log.info("<< ♥", .{}); acked = true; }, .stop => active = false, .deinit => return, } continue; } if (acked) { acked = false; // TODO: actually check this or fix threads + async if (nosuspend gateway.sendCommand(.{ .heartbeat = gateway.seq })) { log.info(">> ♡", .{}); continue; } else |_| { log.info("Heartbeat send failed. Reconnecting...", .{}); } } else { log.info("Missed heartbeat. Reconnecting...", .{}); } gateway.ssl_tunnel.?.shutdown() catch |err| { log.info("Shutdown failed: {}", .{err}); }; active = false; } } } };
src/Gateway/Heartbeat.zig
const std = @import("std"); const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; const Chunk = @import("./chunk.zig").Chunk; const OpCode = @import("./chunk.zig").OpCode; const Value = @import("./value.zig").Value; const compile = @import("./compiler.zig").compile; const Parser = @import("./compiler.zig").Parser; const debug = @import("./debug.zig"); const Obj = @import("./object.zig").Obj; const Table = @import("./table.zig").Table; const FixedCapacityStack = @import("./stack.zig").FixedCapacityStack; const GCAllocator = @import("./memory.zig").GCAllocator; const VMWriter = @import("./writer.zig").VMWriter; const clock = @import("./native.zig").clock; fn add(x: f64, y: f64) f64 { return x + y; } fn sub(x: f64, y: f64) f64 { return x - y; } fn mul(x: f64, y: f64) f64 { return x * y; } fn div(x: f64, y: f64) f64 { return x / y; } const CallFrame = struct { closure: *Obj.Closure, ip: usize, start: usize, }; const FRAMES_MAX = 64; const STACK_MAX = FRAMES_MAX * (std.math.maxInt(u8) + 1); pub const VM = struct { gcAllocatorInstance: GCAllocator, allocator: *Allocator, frames: ArrayList(CallFrame), // NOTE, book uses a fixed size stack stack: FixedCapacityStack(Value), objects: ?*Obj, openUpvalues: ?*Obj.Upvalue, strings: Table, initString: ?*Obj.String, globals: Table, parser: ?*Parser, grayStack: ArrayList(*Obj), outWriter: VMWriter, errWriter: VMWriter, pub fn create() VM { var vm = VM{ .gcAllocatorInstance = undefined, .allocator = undefined, .frames = undefined, .stack = undefined, .objects = null, .openUpvalues = null, .strings = undefined, .initString = null, .globals = undefined, .parser = null, .grayStack = undefined, .outWriter = undefined, .errWriter = undefined, }; return vm; } pub fn init(self: *VM, backingAllocator: *Allocator, outWriter: VMWriter, errWriter: VMWriter) !void { self.gcAllocatorInstance = GCAllocator.init(self, backingAllocator); const allocator = &self.gcAllocatorInstance.allocator; // NOTE, purposely uses the backing allocator to avoid having // growing the grayStack during GC kick off more GC. self.grayStack = std.ArrayList(*Obj).init(backingAllocator); // NOTE, we can tell none of this allocates because none of // these operations can fail, and allocation can always fail // with error.OutOfMemory self.allocator = allocator; self.frames = std.ArrayList(CallFrame).init(allocator); self.strings = Table.init(allocator); self.globals = Table.init(allocator); self.outWriter = outWriter; self.errWriter = errWriter; // These ops all allocate self.stack = try FixedCapacityStack(Value).init(backingAllocator, STACK_MAX); self.initString = try Obj.String.copy(self, "init"); try self.defineNative("clock", clock); } pub fn deinit(self: *VM) void { self.initString = null; self.freeObjects(); self.strings.deinit(); self.globals.deinit(); self.frames.deinit(); self.stack.deinit(); self.grayStack.deinit(); } pub fn freeObjects(self: *VM) void { var object = self.objects; while (object) |o| { const next = o.next; o.destroy(self); object = next; } } pub fn interpret(self: *VM, source: []const u8) !void { // Stack should be empty when we start and when we finish // running std.debug.assert(self.stack.items.len == 0); defer std.debug.assert(self.stack.items.len == 0); errdefer self.resetStack() catch unreachable; const function = try compile(self, source); self.push(function.obj.value()); // NOTE need the function on the stack when we allocate the // closure so that the GC can see it. const closure = try Obj.Closure.create(self, function); _ = self.pop(); self.push(closure.obj.value()); try self.callValue(closure.obj.value(), 0); try self.run(); // Pop the closure we put on the stack above _ = self.pop(); } fn run(self: *VM) !void { while (true) { if (debug.TRACE_EXECUTION) { // Print debugging information try self.printStack(); _ = self.currentChunk().disassembleInstruction(self.currentFrame().ip); } const instruction = self.readByte(); const opCode = @intToEnum(OpCode, instruction); try self.runOp(opCode); if (opCode == .Return and self.frames.items.len == 0) break; } } fn readString(self: *VM) *Obj.String { const constant = self.readByte(); const nameValue = self.currentChunk().constants.items[constant]; return nameValue.asObj().asString(); } fn runOp(self: *VM, opCode: OpCode) !void { switch (opCode) { .Return => { const result = self.pop(); const frame = self.frames.pop(); self.closeUpvalues(&self.stack.items[frame.start]); if (self.frames.items.len == 0) return; try self.stack.resize(frame.start); self.push(result); }, .Pop => { _ = self.pop(); }, .GetLocal => { const slot = self.readByte(); self.push(self.stack.items[self.currentFrame().start + slot]); }, .SetLocal => { const slot = self.readByte(); self.stack.items[self.currentFrame().start + slot] = self.peek(0); }, .GetGlobal => { const name = self.readString(); var value: Value = undefined; if (!self.globals.get(name, &value)) { return self.runtimeError("Undefined variable '{s}'.", .{name.bytes}); } self.push(value); }, .DefineGlobal => { _ = try self.globals.set(self.readString(), self.peek(0)); // NOTE don’t pop until value is in the hash table so // that we don't lose the value if the GC runs during // the set operation _ = self.pop(); }, .SetGlobal => { const name = self.readString(); if (try self.globals.set(name, self.peek(0))) { _ = self.globals.delete(name); return self.runtimeError("Undefined variable '{s}'.", .{name.bytes}); } }, .GetUpvalue => { const slot = self.readByte(); // Upvalues are guaranteed to be filled in by the time we get here self.push(self.currentFrame().closure.upvalues[slot].?.location.*); }, .SetUpvalue => { const slot = self.readByte(); // Upvalues are guaranteed to be filled in by the time we get here self.currentFrame().closure.upvalues[slot].?.location.* = self.peek(0); }, .GetProperty => { const maybeObj = self.peek(0); if (!maybeObj.isObj()) return self.runtimeError("Only instances have properties.", .{}); const obj = maybeObj.asObj(); switch (obj.objType) { .String, .Function, .NativeFunction, .Closure, .Upvalue, .Class, .BoundMethod => { return self.runtimeError("Only instances have properties.", .{}); }, .Instance => { const instance = obj.asInstance(); const name = self.readString(); var value: Value = undefined; if (instance.fields.get(name, &value)) { _ = self.pop(); // Instance. self.push(value); } else { try self.bindMethod(instance.class, name); } }, } }, .SetProperty => { const maybeObj = self.peek(1); if (!maybeObj.isObj()) return self.runtimeError("Only instances have fields.", .{}); const obj = maybeObj.asObj(); switch (obj.objType) { .String, .Function, .NativeFunction, .Closure, .Upvalue, .Class, .BoundMethod => { return self.runtimeError("Only instances have fields.", .{}); }, .Instance => { const instance = obj.asInstance(); _ = try instance.fields.set(self.readString(), self.peek(0)); const value = self.pop(); _ = self.pop(); self.push(value); }, } }, .GetSuper => { const name = self.readString(); const superclass = self.pop().asObj().asClass(); try self.bindMethod(superclass, name); }, .CloseUpvalue => { self.closeUpvalues(&self.stack.items[self.stack.items.len - 2]); _ = self.pop(); }, .Class => { self.push((try Obj.Class.create(self, self.readString())).obj.value()); }, .Inherit => { const maybeObj = self.peek(1); if (!maybeObj.isObj()) return self.runtimeError("Superclass must be a class.", .{}); const obj = maybeObj.asObj(); if (!obj.isClass()) { return self.runtimeError("Superclass must be a class.", .{}); } const superclass = obj.asClass(); const subclass = self.peek(0).asObj().asClass(); for (superclass.methods.entries) |entry| { if (entry.key) |key| _ = try subclass.methods.set(key, entry.value); } _ = self.pop(); // Subclass }, .Method => { try self.defineMethod(self.readString()); }, .Print => { try self.outWriter.print("{}\n", .{self.pop()}); }, .Jump => { const offset = self.readShort(); self.currentFrame().ip += offset; }, .JumpIfFalse => { const offset = self.readShort(); if (self.peek(0).isFalsey()) self.currentFrame().ip += offset; }, .Loop => { const offset = self.readShort(); self.currentFrame().ip -= offset; }, .Call => { const argCount = self.readByte(); try self.callValue(self.peek(argCount), argCount); }, .Invoke => { const method = self.readString(); const argCount = self.readByte(); try self.invoke(method, argCount); }, .SuperInvoke => { const method = self.readString(); const argCount = self.readByte(); const superclass = self.pop().asObj().asClass(); try self.invokeFromClass(superclass, method, argCount); }, .Closure => { const constant = self.readByte(); const value = self.currentChunk().constants.items[constant]; const function = value.asObj().asFunction(); const closure = try Obj.Closure.create(self, function); self.push(closure.obj.value()); for (closure.upvalues) |*upvalue| { const isLocal = self.readByte() != 0; const index = self.readByte(); if (isLocal) { // WARNING if the stack is ever resized, this // pointer into it becomes invalid. We can avoid // this using ensureCapacity when we create the // stack, and by making it an error to grow the // stack past that. Upvalues needing to be able // to point to either the stack or the heap // keeps us from growing the stack. upvalue.* = try self.captureUpvalue(&self.stack.items[self.currentFrame().start + index]); } else { upvalue.* = self.currentFrame().closure.upvalues[index]; } } }, .Constant => { const constant = self.readByte(); const value = self.currentChunk().constants.items[constant]; self.push(value); }, .Nil => self.push(Value.nil()), .True => self.push(Value.fromBool(true)), .False => self.push(Value.fromBool(false)), .Equal => { const b = self.pop(); const a = self.pop(); self.push(Value.fromBool(a.equals(b))); }, .Greater => { const rhs = self.pop(); const lhs = self.pop(); if (!lhs.isNumber() or !rhs.isNumber()) { return self.runtimeError("Operands must be numbers.", .{}); } self.push(Value.fromBool(lhs.asNumber() > rhs.asNumber())); }, .Less => { const rhs = self.pop(); const lhs = self.pop(); if (!lhs.isNumber() or !rhs.isNumber()) { return self.runtimeError("Operands must be numbers.", .{}); } self.push(Value.fromBool(lhs.asNumber() < rhs.asNumber())); }, .Negate => { const value = self.pop(); if (!value.isNumber()) return self.runtimeError("Operand must be a number.", .{}); self.push(Value.fromNumber(-value.asNumber())); }, .Add => { const rhs = self.pop(); const lhs = self.pop(); if (lhs.isObj() and rhs.isObj()) { try self.concatenate(lhs.asObj(), rhs.asObj()); } else if (lhs.isNumber() and rhs.isNumber()) { self.push(Value.fromNumber(lhs.asNumber() + rhs.asNumber())); } else { return self.runtimeError("Operands must be two numbers or two strings.", .{}); } }, .Subtract => try self.binaryNumericOp(sub), .Multiply => try self.binaryNumericOp(mul), .Divide => try self.binaryNumericOp(div), .Not => self.push(Value.fromBool(self.pop().isFalsey())), } } fn binaryNumericOp(self: *VM, comptime op: anytype) !void { const rhs = self.pop(); const lhs = self.pop(); if (!lhs.isNumber() or !rhs.isNumber()) { return self.runtimeError("Operands must be numbers.", .{}); } self.push(Value.fromNumber(op(lhs.asNumber(), rhs.asNumber()))); } fn concatenate(self: *VM, lhs: *Obj, rhs: *Obj) !void { switch (lhs.objType) { .Function, .NativeFunction, .Closure, .Upvalue, .Class, .Instance, .BoundMethod => { try self.runtimeError("Operands must be strings.", .{}); }, .String => switch (rhs.objType) { .Function, .NativeFunction, .Closure, .Upvalue, .Class, .Instance, .BoundMethod => { try self.runtimeError("Operands must be strings.", .{}); }, .String => { // Temporarily put the strings back on the stack so // they're visible to the GC when we allocate self.push(lhs.value()); self.push(rhs.value()); const lhsStr = lhs.asString(); const rhsStr = rhs.asString(); const buffer = try self.allocator.alloc(u8, lhsStr.bytes.len + rhsStr.bytes.len); std.mem.copy(u8, buffer[0..lhsStr.bytes.len], lhsStr.bytes); std.mem.copy(u8, buffer[lhsStr.bytes.len..], rhsStr.bytes); _ = self.pop(); _ = self.pop(); self.push((try Obj.String.create(self, buffer)).obj.value()); }, }, } } fn currentFrame(self: *VM) *CallFrame { return &self.frames.items[self.frames.items.len - 1]; } fn currentChunk(self: *VM) *Chunk { return &self.currentFrame().closure.function.chunk; } fn readByte(self: *VM) u8 { const frame = self.currentFrame(); const byte = self.currentChunk().code.items[frame.ip]; frame.ip += 1; return byte; } fn readShort(self: *VM) u16 { const frame = self.currentFrame(); frame.ip += 2; const items = self.currentChunk().code.items; return (@intCast(u16, items[frame.ip - 2]) << 8) | items[frame.ip - 1]; } pub fn push(self: *VM, value: Value) void { self.stack.append(value); } fn peek(self: *VM, back: usize) Value { return self.stack.items[self.stack.items.len - 1 - back]; } pub fn pop(self: *VM) Value { return self.stack.pop(); } fn call(self: *VM, closure: *Obj.Closure, argCount: usize) !void { if (argCount != closure.function.arity) { const arity = closure.function.arity; return self.runtimeError("Expected {} arguments but got {}.", .{ arity, argCount }); } if (self.frames.items.len == FRAMES_MAX) { return self.runtimeError("Stack overflow.", .{}); } try self.frames.append(CallFrame{ .closure = closure, .ip = 0, // Stack position where this call frame begins // // NOTE, book uses a pointer into the stack called "slots", // but we use an index into the stack instead. Goal was to // make stack resizable, but that ended up being tricky // because upvalues hold pointers into the stack, and // because pushing to the stack is a very hot operation that // needs to be as fast as possible. .start = self.stack.items.len - argCount - 1, }); } fn callValue(self: *VM, callee: Value, argCount: usize) !void { if (!callee.isObj()) return self.runtimeError("Can only call functions and classes.", .{}); const obj = callee.asObj(); switch (obj.objType) { .String, .Function, .Upvalue, .Instance => { return self.runtimeError("Can only call functions and classes.", .{}); }, .Closure => try self.call(obj.asClosure(), argCount), .NativeFunction => { const args = self.stack.items[self.stack.items.len - 1 - argCount ..]; try self.stack.resize(self.stack.items.len - 1 - argCount); const result = obj.asNativeFunction().function(args); self.push(result); }, .BoundMethod => { const bound = obj.asBoundMethod(); self.stack.items[self.stack.items.len - argCount - 1] = bound.receiver; try self.call(bound.method, argCount); }, .Class => { const class = obj.asClass(); const instance = (try Obj.Instance.create(self, class)).obj.value(); self.stack.items[self.stack.items.len - argCount - 1] = instance; var initializer: Value = undefined; if (class.methods.get(self.initString.?, &initializer)) { try self.call(initializer.asObj().asClosure(), argCount); } else if (argCount != 0) { return self.runtimeError("Expected 0 arguments but got {}.", .{argCount}); } }, } } fn invoke(self: *VM, name: *Obj.String, argCount: u8) !void { const receiver = self.peek(argCount).asObj(); if (!receiver.isInstance()) { return self.runtimeError("Only instances have methods.", .{}); } const instance = receiver.asInstance(); var value: Value = undefined; if (instance.fields.get(name, &value)) { self.stack.items[self.stack.items.len - argCount - 1] = value; return self.callValue(value, argCount); } return self.invokeFromClass(instance.class, name, argCount); } fn invokeFromClass(self: *VM, class: *Obj.Class, name: *Obj.String, argCount: u8) !void { var method: Value = undefined; if (!class.methods.get(name, &method)) { return self.runtimeError("Undefined property '{s}'.", .{name.bytes}); } return self.call(method.asObj().asClosure(), argCount); } fn bindMethod(self: *VM, class: *Obj.Class, name: *Obj.String) !void { var method: Value = undefined; if (!class.methods.get(name, &method)) { return self.runtimeError("Undefined property '{s}'.", .{name.bytes}); } const bound = try Obj.BoundMethod.create(self, self.peek(0), method.asObj().asClosure()); _ = self.pop(); self.push(bound.obj.value()); } fn captureUpvalue(self: *VM, local: *Value) !*Obj.Upvalue { var prevUpvalue: ?*Obj.Upvalue = null; var maybeUpvalue = self.openUpvalues; while (maybeUpvalue) |upvalue| { if (@ptrToInt(upvalue.location) <= @ptrToInt(local)) break; prevUpvalue = upvalue; maybeUpvalue = upvalue.next; } if (maybeUpvalue) |upvalue| { if (upvalue.location == local) return upvalue; } const createdUpvalue = try Obj.Upvalue.create(self, local); createdUpvalue.next = maybeUpvalue; if (prevUpvalue) |p| { p.next = createdUpvalue; } else { self.openUpvalues = createdUpvalue; } return createdUpvalue; } fn closeUpvalues(self: *VM, last: *Value) void { while (self.openUpvalues) |openUpvalues| { if (@ptrToInt(openUpvalues.location) < @ptrToInt(last)) break; const upvalue = openUpvalues; upvalue.closed = upvalue.location.*; upvalue.location = &upvalue.closed; self.openUpvalues = upvalue.next; } } fn defineMethod(self: *VM, name: *Obj.String) !void { const method = self.peek(0); const class = self.peek(1).asObj().asClass(); _ = try class.methods.set(name, method); _ = self.pop(); } fn resetStack(self: *VM) !void { try self.stack.resize(0); } fn printStack(self: *VM) !void { std.debug.warn(" ", .{}); for (self.stack.items) |value| { std.debug.warn("[ {} ]", .{value}); } std.debug.warn("\n", .{}); } fn runtimeError(self: *VM, comptime message: []const u8, args: anytype) !void { @setCold(true); try self.errWriter.print(message, args); try self.errWriter.print("\n", .{}); while (self.frames.items.len > 0) { const frame = self.frames.pop(); const function = frame.closure.function; const line = function.chunk.lines.items[frame.ip - 1]; const name = if (function.name) |str| str.bytes else "<script>"; try self.errWriter.print("[line {}] in {s}\n", .{ line, name }); } return error.RuntimeError; } fn defineNative(self: *VM, name: []const u8, function: Obj.NativeFunction.NativeFunctionType) !void { const str = try Obj.String.copy(self, name); // NOTE put str on the stack immediately to make sure it doesn't // get garbage collected when we allocate to create the native // function below. self.push(str.obj.value()); const functionValue = (try Obj.NativeFunction.create(self, function)).obj.value(); self.push(functionValue); _ = try self.globals.set(str, functionValue); _ = self.pop(); _ = self.pop(); } };
src/vm.zig