code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const ErasedPtr = @import("../ecs/utils.zig").ErasedPtr; /// Simple cache for resources of a given type. If any resource has a deinit method it will be called when clear /// or remove is called. Implementing a "loader" which is passed to "load" is a struct with one method: /// - load(self: @This()) *T. pub fn Cache(comptime T: type) type { return struct { const Self = @This(); safe_deinit: fn (*@This()) void, resources: std.AutoHashMap(u32, *T), allocator: ?std.mem.Allocator = null, pub fn initPtr(allocator: std.mem.Allocator) *@This() { var cache = allocator.create(@This()) catch unreachable; cache.safe_deinit = struct { fn deinit(self: *Self) void { self.clear(); self.resources.deinit(); self.allocator.?.destroy(self); } }.deinit; cache.resources = std.AutoHashMap(u32, *T).init(allocator); cache.allocator = allocator; return cache; } pub fn init(allocator: std.mem.Allocator) @This() { return .{ .safe_deinit = struct { fn deinit(self: *Self) void { self.clear(); self.resources.deinit(); } }.deinit, .resources = std.AutoHashMap(u32, *T).init(allocator), }; } pub fn deinit(self: *@This()) void { self.safe_deinit(self); } pub fn load(self: *@This(), id: u32, comptime loader: anytype) @typeInfo(@TypeOf(@field(loader, "load"))).BoundFn.return_type.? { if (self.resources.get(id)) |resource| { return resource; } var resource = loader.load(); _ = self.resources.put(id, resource) catch unreachable; return resource; } pub fn contains(self: *@This(), id: u32) bool { return self.resources.contains(id); } pub fn remove(self: *@This(), id: u32) void { if (self.resources.fetchRemove(id)) |kv| { if (@hasDecl(T, "deinit")) { @call(.{ .modifier = .always_inline }, @field(kv.value, "deinit"), .{}); } } } pub fn clear(self: *@This()) void { // optionally deinit any resources that have a deinit method if (@hasDecl(T, "deinit")) { var iter = self.resources.iterator(); while (iter.next()) |kv| { @call(.{ .modifier = .always_inline }, @field(kv.value_ptr.*, "deinit"), .{}); } } self.resources.clearAndFree(); } pub fn size(self: @This()) usize { return self.resources.count(); } }; } test "cache" { const utils = @import("../ecs/utils.zig"); const Thing = struct { fart: i32, pub fn deinit(self: *@This()) void { std.testing.allocator.destroy(self); } }; const ThingLoadArgs = struct { pub fn load(self: @This()) *Thing { _ = self; return std.testing.allocator.create(Thing) catch unreachable; } }; var cache = Cache(Thing).init(std.testing.allocator); defer cache.deinit(); _ = cache.load(utils.hashString("my/id"), ThingLoadArgs{}); _ = cache.load(utils.hashString("another/id"), ThingLoadArgs{}); try std.testing.expectEqual(cache.size(), 2); cache.remove(utils.hashString("my/id")); try std.testing.expectEqual(cache.size(), 1); cache.clear(); try std.testing.expectEqual(cache.size(), 0); }
src/resources/cache.zig
const std = @import("std"); const ArrayList = std.ArrayList; const crypto = std.crypto; const debug = std.debug; const fmt = std.fmt; const mem = std.mem; const unicode = std.unicode; const c = @cImport({ @cInclude("argon2.h"); }); const id = "com.alamlintang.lappland"; pub const Error = error{OutOfMemory}; pub fn generateDiceware( allocator: *mem.Allocator, user_name: []const u8, site_name: []const u8, counter: u8, word_count: u4, password: []const u8, ) Error![]u8 { debug.assert(word_count >= 5 and word_count <= 10); var salt = [_]u8{0} ** 64; var key = [_]u8{0} ** 32; var seed = [_]u8{0} ** 64; defer crypto.utils.secureZero(u8, &key); defer crypto.utils.secureZero(u8, &seed); try generateSalt(allocator, user_name, &salt); try generateKey(&salt, password, &key); try generateSeed(allocator, site_name, counter, key, &seed); return generatePassphrase(allocator, &seed, word_count); } pub fn utf8CountCodepoints(s: []const u8) error{InvalidUtf8}!usize { var i: usize = 0; var utf8 = (try std.unicode.Utf8View.init(s)).iterator(); while (utf8.nextCodepoint()) |_| i += 1; return i; } fn generateKey(salt: []const u8, password: []const u8, output: []u8) Error!void { const iterations = 16; const memory_usage = 16384; // in KiB const parallelism = 1; switch (c.argon2i_hash_raw( iterations, memory_usage, parallelism, password.ptr, password.len, salt.ptr, salt.len, output.ptr, output.len, )) { c.ARGON2_MEMORY_ALLOCATION_ERROR => return error.OutOfMemory, c.ARGON2_OK => return, else => unreachable, } } fn generatePassphrase(allocator: *mem.Allocator, seed: []const u8, word_count: u4) Error![]u8 { const istanbul = switch (word_count) { 5 => &[_]u8{ 13, 13, 12, 13, 13 }, 6 => &[_]u8{ 11, 11, 10, 10, 11, 11 }, 7 => &[_]u8{ 9, 9, 9, 10, 9, 9, 9 }, 8 => &[_]u8{ 8, 8, 8, 8, 8, 8, 8, 8 }, 9 => &[_]u8{ 7, 7, 7, 7, 8, 7, 7, 7, 7}, 10 => &[_]u8{ 6, 6, 6, 7, 7, 7, 7, 6, 6, 6 }, else => unreachable, }; var romania = try allocator.alloc([]const u8, word_count); defer allocator.free(romania); { var para: usize = 0; var mexer: usize = 0; for (romania) |*roman, index| { mexer += istanbul[index % istanbul.len]; roman.* = seed[para..mexer]; para = mexer; } } var neverland = try allocator.alloc([5]u8, word_count); defer allocator.free(neverland); for (neverland) |*never| mem.set(u8, &never.*, 1); for (romania) |roman, index| { var para: usize = roman.len - 5; var i: usize = 0; while (para > 0) : ({ para -= 1; i += 1; }) neverland[index][i % neverland[index].len] += 1; } for (neverland) |*never, index| { var para: usize = 0; var mexer: usize = 0; for (never) |*ever| { var javier: u8 = 0; mexer += ever.*; for (romania[index][para..mexer]) |roman| javier +%= roman; ever.* = javier; para = mexer; } } for (neverland) |*never| { for (never) |*ever| { // 6 faces on a dice. ever.* %= 6; // Change from 0-5 to 1-6. ever.* += 1; // Turn the number into an ASCII representation of said number. ever.* += 0x30; } } var output = try ArrayList(u8).initCapacity(allocator, 1 << 8); defer output.deinit(); const wordlist = @embedFile("../thirdparty/eff_large_wordlist.txt"); for (neverland) |never, index0| { var indicator: usize = 0; for (never) |ever, index1| { while (true) { if (wordlist[indicator] != ever) { while (wordlist[indicator] != '\n') : (indicator += 1) {} indicator += 1 + index1; } else { indicator += 1; break; } } } indicator += 1; while (wordlist[indicator] != '\n') : (indicator += 1) output.appendAssumeCapacity(wordlist[indicator]); // If it's processing the final word, avoid putting the space character at the end of the // string array. if (index0 == neverland.len - 1) break; output.appendAssumeCapacity(' '); } return output.toOwnedSlice(); } fn generateSalt(allocator: *mem.Allocator, user_name: []const u8, output: []u8) Error!void { const user_name_len = utf8CountCodepoints(user_name) catch unreachable; const buf = try fmt.allocPrint(allocator, "{}{}{}", .{ id, user_name_len, user_name }); defer allocator.free(buf); crypto.hash.Blake3.hash(buf, output, .{}); } fn generateSeed( allocator: *mem.Allocator, site_name: []const u8, counter: u8, key: [32]u8, output: []u8, ) Error!void { var hash = [_]u8{0} ** 64; const site_name_len = utf8CountCodepoints(site_name) catch unreachable; const buf = try fmt.allocPrint(allocator, "{}{}{}{}", .{ id, site_name_len, site_name, counter }); defer allocator.free(buf); crypto.hash.Blake3.hash(buf, &hash, .{}); crypto.hash.Blake3.hash(&hash, output, .{ .key = key }); }
src/algorithm.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const nvg = @import("nanovg"); const gui = @import("../gui.zig"); const Rect = @import("../geometry.zig").Rect; const ListView = @This(); widget: gui.Widget, allocator: *Allocator, vertical_scrollbar: *gui.Scrollbar, horizontal_scrollbar: *gui.Scrollbar, model: Model, const Self = @This(); const item_h: f32 = 20; pub const Model = struct { ctx: usize, countFn: fn (ctx: usize) usize, getFn: fn (ctx: usize, i: usize) []const u8, isSelectedFn: fn (ctx: usize, i: usize) bool, selectFn: fn (ctx: usize, i: usize) void, swapFn: fn (ctx: usize, i: usize, j: usize) void, deleteFn: fn (ctx: usize, i: usize) void, }; pub fn init(allocator: *Allocator, rect: Rect(f32), model: Model) !*Self { var self = try allocator.create(Self); self.* = Self{ .widget = gui.Widget.init(allocator, rect), .allocator = allocator, .vertical_scrollbar = try gui.Scrollbar.init(allocator, rect, .vertical), .horizontal_scrollbar = try gui.Scrollbar.init(allocator, rect, .horizontal), .model = model, }; self.widget.onResizeFn = onResize; self.widget.onMouseMoveFn = onMouseMove; self.widget.onMouseDownFn = onMouseDown; self.widget.onMouseUpFn = onMouseUp; self.widget.drawFn = draw; try self.widget.addChild(&self.vertical_scrollbar.widget); try self.widget.addChild(&self.horizontal_scrollbar.widget); self.updateLayout(); return self; } pub fn deinit(self: *Self) void { self.vertical_scrollbar.deinit(); self.horizontal_scrollbar.deinit(); self.widget.deinit(); self.allocator.destroy(self); } fn onResize(widget: *gui.Widget, event: *const gui.ResizeEvent) void { _ = event; const self = @fieldParentPtr(Self, "widget", widget); self.updateLayout(); } fn updateLayout(self: *Self) void { const button_size = 16; const rect = self.widget.relative_rect; self.vertical_scrollbar.widget.relative_rect.x = rect.w - button_size; self.vertical_scrollbar.widget.setSize(button_size, rect.h + 1 - button_size); self.horizontal_scrollbar.widget.relative_rect.y = rect.h - button_size; self.horizontal_scrollbar.widget.setSize(rect.w + 1 - button_size, button_size); const content_w = rect.w - button_size - 2; const content_h = rect.h - button_size - 2; self.horizontal_scrollbar.setMaxValue(512 - content_w - 1); self.vertical_scrollbar.setMaxValue(512 - content_h - 1); } fn onMouseMove(widget: *gui.Widget, event: *const gui.MouseEvent) void { _ = event; const self = @fieldParentPtr(Self, "widget", widget); _ = self; } fn onMouseDown(widget: *gui.Widget, event: *const gui.MouseEvent) void { if (event.button == .left) { const self = @fieldParentPtr(Self, "widget", widget); //const rect = widget.getRect(); const i = @floatToInt(usize, event.y / item_h); self.model.selectFn(self.model.ctx, i); } } fn onMouseUp(widget: *gui.Widget, event: *const gui.MouseEvent) void { _ = event; const self = @fieldParentPtr(Self, "widget", widget); _ = self; } fn draw(widget: *gui.Widget) void { const self = @fieldParentPtr(Self, "widget", widget); const rect = widget.relative_rect; // background nvg.beginPath(); nvg.rect(rect.x + 1, rect.y + 1, rect.w - 2, rect.h - 2); nvg.fillColor(gui.theme_colors.light); nvg.fill(); nvg.fontFace("guifont"); nvg.fontSize(gui.pixelsToPoints(9)); var text_align = @enumToInt(nvg.TextAlign.middle); var x = rect.x; text_align |= @enumToInt(nvg.TextAlign.left); x += 5; nvg.textAlign(@intToEnum(nvg.TextAlign, text_align)); nvg.fillColor(nvg.rgb(0, 0, 0)); const len = self.model.countFn(self.model.ctx); var i: usize = 0; while (i < len) : (i += 1) { const y = rect.y + 1 + @intToFloat(f32, i) * item_h; const is_selected = self.model.isSelectedFn(self.model.ctx, i); if (is_selected) { nvg.beginPath(); nvg.rect(rect.x + 1, y, rect.w - 2, item_h); nvg.fillColor(nvg.rgb(90, 140, 240)); nvg.fill(); nvg.fillColor(gui.theme_colors.light); } else { nvg.fillColor(nvg.rgb(0, 0, 0)); } const name = self.model.getFn(self.model.ctx, i); _ = nvg.text(x, y + 0.5 * item_h, name); } // border nvg.beginPath(); nvg.rect(rect.x + 0.5, rect.y + 0.5, rect.w - 1, rect.h - 1); nvg.strokeColor(gui.theme_colors.border); nvg.stroke(); // corner between scrollbars nvg.beginPath(); nvg.rect(rect.x + rect.w - 15, rect.y + rect.h - 15, 14, 14); nvg.fillColor(gui.theme_colors.background); nvg.fill(); widget.drawChildren(); }
src/gui/widgets/ListView.zig
const std = @import("std"); const debug = std.debug; const log = std.log; const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const TailQueue = std.TailQueue; const ArrayList = std.ArrayList; const Instruction = @import("instruction.zig").Instruction; const Orientation = enum(u1) { left_to_right, right_to_left, const Self = @This(); pub fn flip(self: Self) Self { return switch (self) { .left_to_right => Orientation.right_to_left, .right_to_left => Orientation.left_to_right, }; } }; /// Naive approach. Does not scale, so it cannot be used for part 2. Only used for testing in the end. pub const Deck = struct { const Self = @This(); /// The type of a single card. const Node = TailQueue(u16).Node; /// All cards. cards: TailQueue(u16), /// Backing store for cards; internal only. `cards` has pointers to `nodes`. nodes: ArrayList(Node), /// If we traverse the cards, do we go left->right or right->left. orientation: Orientation, /// we need to some allocations as well allocator: Allocator, pub fn init(allocator: Allocator, count: usize) !Self { var self = Self{ .cards = TailQueue(u16){}, .nodes = undefined, .orientation = Orientation.left_to_right, .allocator = allocator, }; { var nodes = try ArrayList(Node).initCapacity(allocator, count); self.nodes = nodes; } var i: u16 = 0; while (i < count) : (i += 1) { self.nodes.appendAssumeCapacity(Node{ .data = i }); // self.nodes must never resize self.cards.append(&self.nodes.items[self.nodes.items.len - 1]); } return self; } pub fn deinit(self: *Self) void { self.nodes.deinit(); } pub const Iterator = struct { current: ?*Node, orientation: Orientation, pub fn next(it: *Iterator) ?u16 { if (it.current) |node| { it.current = switch (it.orientation) { .left_to_right => node.next, .right_to_left => node.prev, }; return node.data; } return null; } }; /// Return an iterator that walks the deck without consuming. pub fn iterator(self: Self) Iterator { return Iterator{ .current = switch (self.orientation) { .left_to_right => self.cards.first, .right_to_left => self.cards.last, }, .orientation = self.orientation, }; } pub fn get_card(self: Self, pos: usize) ?usize { var it = self.iterator(); var i: usize = 0; while (it.next()) |number| { if (i == pos) { return number; } i += 1; } return null; } /// Return the position of `needle` in the card stack. pub fn find_card(self: Self, needle: usize) ?usize { var it = self.iterator(); var i: usize = 0; while (it.next()) |number| { if (number == needle) { return i; } i += 1; } return null; } /// To deal into new stack, create a new stack of cards by dealing the top /// card of the deck onto the top of the new stack repeatedly until you run /// out of cards. /// /// Complexity: O(1) pub fn deal_into_new(self: *Self) void { log.debug("deal into new stack", .{}); self.orientation = self.orientation.flip(); } /// To cut N cards, take the top N cards off the top of the deck and move /// them as a single unit to the bottom of the deck, retaining their order. /// /// Complexity: O(N) pub fn cut_n(self: *Self, n: i64) void { const pos_n = if (n >= 0) @intCast(usize, n) else @intCast(usize, self.cards.len - @intCast(usize, (-1) * n)); log.debug("cut {d} -> cut {d}", .{ n, pos_n }); debug.assert(pos_n < self.cards.len); // 0 1 2 3 4 5 6 7 8 9 Your deck // 3 4 5 6 7 8 9 Your deck // 0 1 2 Cut cards // 3 4 5 6 7 8 9 Your deck // 0 1 2 Cut cards // 3 4 5 6 7 8 9 0 1 2 Your deck var it = self.iterator(); var i: usize = 0; // go to node pos while (i < pos_n - 1) : (i += 1) { _ = it.next(); } var node = it.current.?; switch (self.orientation) { .left_to_right => { self.cards.last.?.next = self.cards.first; self.cards.first.?.prev = self.cards.last; self.cards.first = node.next; self.cards.first.?.prev = null; self.cards.last = node; self.cards.last.?.next = null; }, .right_to_left => { // same code as in left-to-right, but due to symmetry replace simultaneously: // * next <-> prev // * first <-> last self.cards.first.?.prev = self.cards.last; self.cards.last.?.next = self.cards.first; self.cards.last = node.prev; self.cards.last.?.next = null; self.cards.first = node; self.cards.first.?.prev = null; }, } } /// To deal with increment N, start by clearing enough space on your table /// to lay out all of the cards individually in a long line. Deal the top /// card into the leftmost position. Then, move N positions to the right /// and deal the next card there. If you would move into a position past /// the end of the space on your table, wrap around and keep counting from /// the leftmost card again. Continue this process until you run out of /// cards. pub fn deal_with_increment(self: *Self, n: i64) !void { log.debug("deal with increment {d}", .{n}); const count = self.cards.len; var current_nodes = try ArrayList(Node).initCapacity(self.allocator, count); defer current_nodes.deinit(); { var it = self.iterator(); // works for all orientations while (it.next()) |actual| { current_nodes.appendAssumeCapacity(Node{ .data = actual }); } } var new_nodes = try ArrayList(Node).initCapacity(self.allocator, count); new_nodes.expandToCapacity(); { // now do the actual work var src_idx: usize = 0; var target_idx: usize = 0; while (src_idx < count) : (src_idx += 1) { new_nodes.items[target_idx] = current_nodes.items[src_idx]; target_idx = @intCast(usize, @mod(@intCast(i64, target_idx) + n, @intCast(i64, count))); } } // just copy the references var new_cards = TailQueue(u16){}; { var i: usize = 0; while (i < count) : (i += 1) { new_cards.append(&new_nodes.items[i]); } } // update self.cards = new_cards; self.nodes.deinit(); self.nodes = new_nodes; self.orientation = Orientation.left_to_right; } pub fn apply_instructions(self: *Self, instructions: []const Instruction) !void { for (instructions) |item| { switch (item) { .deal_into => { self.deal_into_new(); }, .cut_n => { self.cut_n(item.cut_n); }, .deal_inc => { try self.deal_with_increment(item.deal_inc); }, } } } }; const testing = std.testing; const expectEqual = testing.expectEqual; const expectEqualSlices = testing.expectEqualSlices; test "init a new non-empty Deck" { var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); try expectEqual(@as(usize, 10), deck.nodes.items.len); try expectEqual(@as(usize, 10), deck.cards.len); try expectEqual(@as(u16, 0), deck.cards.first.?.data); try expectEqual(@as(u16, 1), deck.cards.first.?.next.?.data); try expectEqual(@as(u16, 2), deck.cards.first.?.next.?.next.?.data); try expectEqual(@as(u16, 9), deck.cards.last.?.data); } test "iterator left to right" { var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); var it = deck.iterator(); var card_number: u16 = 0; while (it.next()) |actual| { try expectEqual(card_number, actual); card_number += 1; } try expectEqual(deck.cards.len, card_number); } test "deal_into_new" { var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); deck.deal_into_new(); { var it = deck.iterator(); var card_number: u16 = 10; while (it.next()) |actual| { card_number -= 1; try expectEqual(card_number, actual); } try expectEqual(@as(u16, 0), card_number); } // test idempotence deck.deal_into_new(); { var card_number: u16 = 0; var it = deck.iterator(); while (it.next()) |actual| { try expectEqual(card_number, actual); card_number += 1; } try expectEqual(deck.cards.len, card_number); } } test "cut 3: left to right" { var expectedCards = [_]u16{ 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 }; var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); deck.cut_n(3); var actualCards: [10]u16 = undefined; { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); // flip and check again deck.deal_into_new(); mem.reverse(u16, expectedCards[0..]); { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); } test "cut 3: right to left" { var expectedCards = [_]u16{ 3, 4, 5, 6, 7, 8, 9, 0, 1, 2 }; var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); // reverse cards because we go from right to left { var it = deck.cards.first; while (it) |node| : (it = node.next) { node.data = 9 - node.data; } } deck.orientation = .right_to_left; deck.cut_n(3); var actualCards: [10]u16 = undefined; { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); // flip and check again deck.deal_into_new(); mem.reverse(u16, expectedCards[0..]); { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); } test "cut -4: left to right" { var expectedCards = [_]u16{ 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 }; var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); deck.cut_n(-4); var actualCards: [10]u16 = undefined; { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); // flip and check again deck.deal_into_new(); mem.reverse(u16, expectedCards[0..]); { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); } test "cut -4: right to left" { var expectedCards = [_]u16{ 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 }; var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); // reverse cards because we go from right to left { var it = deck.cards.first; while (it) |node| : (it = node.next) { node.data = 9 - node.data; } } deck.orientation = .right_to_left; deck.cut_n(-4); var actualCards: [10]u16 = undefined; { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); // flip and check again deck.deal_into_new(); mem.reverse(u16, expectedCards[0..]); { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); } test "deal with increment 3: left to right" { var expectedCards = [_]u16{ 0, 7, 4, 1, 8, 5, 2, 9, 6, 3 }; var deck = try Deck.init(testing.allocator, 10); defer deck.deinit(); try deck.deal_with_increment(3); var actualCards: [10]u16 = undefined; { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); // flip and check again deck.deal_into_new(); mem.reverse(u16, expectedCards[0..]); { var it = deck.iterator(); var i: usize = 0; while (it.next()) |actual| { actualCards[i] = actual; i += 1; } } try expectEqualSlices(u16, expectedCards[0..], actualCards[0..]); }
day22/src/deck.zig
const std = @import("std"); const print = std.debug.print; const fmt = std.fmt; const testing = std.testing; const mem = std.mem; fn getChar(i: u8) u8 { return if (i < 33 or i == 127) ' ' else i; } fn tableRows() [32][4]u8 { var rows: [32][4]u8 = undefined; var i: u8 = 0; while (i <= 31) : (i += 1) { rows[i][0] = i; rows[i][1] = i + 32; rows[i][2] = i + 64; rows[i][3] = i + 96; } return rows; } fn bodyRow(allocator: mem.Allocator, tableRow: [4]u8) ![]const u8 { var formattedBlocks: [4][]const u8 = undefined; for (tableRow) |n, i| { formattedBlocks[i] = try formatBlock(allocator, n); } return try mem.join(allocator, " | ", formattedBlocks[0..]); } fn headerRow() []const u8 { return ("Dec Hex Oct C" ++ " | ") ** 3 ++ "Dec Hex Oct C"; } fn formatBlock(allocator: mem.Allocator, n: u8) ![]const u8 { return try fmt.allocPrint( allocator, "{d:>3} {x:>4} {o:>4} {c}", .{ n, n, n, getChar(n) }, ); } fn asciiTable(allocator: mem.Allocator) ![]const u8 { var formattedTableRows: [33][]const u8 = undefined; formattedTableRows[0] = headerRow(); for (tableRows()) |row, i| { formattedTableRows[i + 1] = try bodyRow(allocator, row); } return try mem.join(allocator, "\n", formattedTableRows[0..]); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); print("{s}\n", .{asciiTable(allocator)}); } test "create body row" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const expOne = " 0 0 0 | 32 20 40 | 64 40 100 @ | 96 60 140 `"; const expTwo = " 22 16 26 | 54 36 66 6 | 86 56 126 V | 118 76 166 v"; const exampleOneResult = try bodyRow(allocator, [_]u8{ 0, 32, 64, 96 }); const exampleTwoResult = try bodyRow(allocator, [_]u8{ 22, 54, 86, 118 }); try testing.expectEqualStrings(expOne, exampleOneResult); try testing.expectEqualStrings(expTwo, exampleTwoResult); } test "format block" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const one = " 0 0 0 "; const two = " 32 20 40 "; const three = " 64 40 100 @"; const blockOne = try formatBlock(allocator, 0); const blockTwo = try formatBlock(allocator, 32); const blockThree = try formatBlock(allocator, 64); try testing.expectEqualStrings(one, blockOne); try testing.expectEqualStrings(two, blockTwo); try testing.expectEqualStrings(three, blockThree); } test "getting table rows" { const expRows = [4][4]u8{ [_]u8{ 0, 32, 64, 96 }, [_]u8{ 1, 33, 65, 97 }, [_]u8{ 2, 34, 66, 98 }, [_]u8{ 3, 35, 67, 99 }, }; // We just test the first 4 rows. const rows = tableRows()[0..4]; try testing.expectEqual(expRows, rows.*); } test "getting character from u8" { try testing.expect(getChar(0) == ' '); try testing.expect(getChar(31) == ' '); try testing.expect(getChar(65) == 'A'); try testing.expect(getChar(126) == '~'); try testing.expect(getChar(127) == ' '); }
src/main.zig
const std = @import("std"); const page_alloc = @import("page_alloc.zig"); // modules const builtin = std.builtin; const debug = std.debug; const math = std.math; const mem = std.mem; const os = std.os; const testing = std.testing; // functions const assert = debug.assert; // types const Mutex = std.Mutex; // constants" const page_size = mem.page_size; pub const Error = error{OutOfMemory}; /// A page-aligned pointer to a chunk of `size` bytes pub fn ChunkPointer(comptime size: usize) type { return *align(page_size) [size]u8; } /// A trait to determine if a type is a chunk allocator. /// Chunk allocators must support the following decls: /// T.chunk_size: const usize /// T.allocChunk: const fn(*T) Error!ChunkPointer(T.chunk_size) /// T.freeChunk: const fn(*T, [*]u8) void pub fn isChunkAllocator(comptime T: type) bool { comptime { return @hasDecl(T, "chunk_size") and @TypeOf(T.chunk_size) == usize and @hasDecl(T, "allocChunk") and @TypeOf(T.allocChunk) == fn (*T) Error!ChunkPointer(T.chunk_size) and @hasDecl(T, "freeChunk") and @TypeOf(T.freeChunk) == fn (*T, [*]u8) void; } } /// Linked list data format for the free list of chunks. /// Chunks in the free list can be reinterpreted as this. pub const ChunkHeader = struct { next: ?*ChunkHeader }; /// An allocator that allocates large chunks from the operating system. /// If the chunk size is smaller than the OS memory map granularity, /// os allocations will be broken up into chunks and stored into a free list. /// This allocator never decommits memory, it only grows. pub fn ThreadsafeChunkAllocator(comptime in_chunk_size: usize) type { if (!math.isPowerOfTwo(in_chunk_size)) @compileError("Chunk size must be a power of two"); if (in_chunk_size < page_size) @compileError("Chunk size must be greater than or equal to page size"); return struct { /// The size of a chunk. All chunks are exactly this size, with no waste. pub const chunk_size = in_chunk_size; /// A pointer to a data chunk of constant size pub const ChunkPtr = ChunkPointer(chunk_size); /// The granularity of direct allocation, as reported by the OS. /// This may be larger or smaller than the chunk size. /// It will always be greater than or equal to page_size. /// This value does not change after initialization. allocation_granularity_bytes: usize, /// Lock protecting mutable state /// Allocation and free from this allocator incurs locking cost. lock: Mutex, /// The total number of bytes that are currently in use. /// protected by lock total_in_use_bytes: usize, /// The total number of bytes that are currently in use. /// protected by lock total_free_list_bytes: usize, /// The head of a free list of chunks. /// Reinterpret chunks as ChunkHeader to follow list. /// protected by lock first_free_chunk: ?*ChunkHeader, /// Initialize a chunk allocator. Queries the OS to get allocation granularity. /// This allocator is meant to be global and everlasting. It cannot release /// virtual address space. Once initialized, this allocator cannot be disposed. pub fn init() @This() { return @This(){ .allocation_granularity_bytes = page_alloc.findAllocationGranularity(), .lock = Mutex.init(), .total_in_use_bytes = 0, .total_free_list_bytes = 0, .first_free_chunk = null, }; } /// Adds freed chunks for the requested number of freed bytes to the allocator. /// Errors: /// OutOfMemory -> No memory was seeded, the system is entirely out /// PartialOutOfMemory -> Some memory was seeded but not as much as requested pub fn seed(self: *@This(), num_bytes: usize) (Error || error{PartialOutOfMemory})!void { assert(math.isPowerOfTwo(num_bytes)); const granule_size = math.max(self.allocation_granularity_bytes, chunk_size); const actual_bytes = math.max(num_bytes, granule_size); var new_tail_chunk: ?*ChunkHeader = null; var new_head_chunk: ?*ChunkHeader = null; var remaining_bytes = actual_bytes; var allocation_size = actual_bytes; // Try to allocate the requested amount. If an allocation fails, // try to make multiple smaller allocations. while (remaining_bytes > 0 and allocation_size >= granule_size) { if (page_alloc.alloc(allocation_size)) |new_bytes| { // link the chunks together in the new allocation const head = @ptrCast(*ChunkHeader, new_bytes); var tail = head; var offset = chunk_size; while (offset < allocation_size) : (offset += chunk_size) { const next_tail = @ptrCast(*ChunkHeader, @alignCast(page_size, new_bytes + offset)); tail.next = next_tail; tail = next_tail; } // link into the larger list if (new_tail_chunk == null) new_tail_chunk = tail; tail.next = new_head_chunk; new_head_chunk = head; remaining_bytes -= allocation_size; } else |err| { // try a smaller allocation allocation_size = allocation_size / 2; } } // link the new chunks if (new_tail_chunk) |tail| { const locked = self.lock.acquire(); defer locked.release(); // link tail.next = self.first_free_chunk; self.first_free_chunk = new_head_chunk; // update stats self.total_free_list_bytes += actual_bytes - remaining_bytes; } if (remaining_bytes == 0) { return; } else if (remaining_bytes < actual_bytes) { return error.PartialOutOfMemory; } else { return error.OutOfMemory; } } /// Allocates and returns a single chunk. If the free list is empty, /// attempts to alloc from the OS. pub fn allocChunk(self: *@This()) Error!ChunkPtr { // Fast path: see if we can grab an available free chunk { const locked = self.lock.acquire(); defer locked.release(); // claim bytes as in use. If an error occurs // we will reset this at the end self.total_in_use_bytes += chunk_size; if (self.first_free_chunk) |chunk| { // claim the bytes self.total_free_list_bytes -= chunk_size; // return a free chunk self.first_free_chunk = chunk.next; return @intToPtr(ChunkPtr, @ptrToInt(chunk)); } } // No free chunk available. Try to map. Not locked here. if (self.mapNewChunk()) |chunk| { return chunk; } else |err| { assert(err == error.OutOfMemory); // try to quick alloc a chunk again, another thread may have // added more to the linked list const locked = self.lock.acquire(); defer locked.release(); if (self.first_free_chunk) |chunk| { // claim the bytes self.total_free_list_bytes -= chunk_size; // return a free chunk self.first_free_chunk = chunk.next; return @intToPtr(ChunkPtr, @ptrToInt(chunk)); } // couldn't get the bytes, unclaim them for stats self.total_in_use_bytes -= chunk_size; // otherwise no chunks left, return the error. return err; } } /// Maps and returns a new chunk. If the allocation granularity is larger than the chunk size, /// adds extra chunks to the internal list. fn mapNewChunk(self: *@This()) Error!ChunkPtr { if (self.allocation_granularity_bytes > chunk_size) { // must be power of two chunks assert(self.allocation_granularity_bytes >= 2 * chunk_size); const new_chunks = try page_alloc.alloc(self.allocation_granularity_bytes); const first_chunk = @ptrCast(ChunkPtr, new_chunks); const second_chunk = @ptrCast(*ChunkHeader, @alignCast(page_size, new_chunks + chunk_size)); // link all chunks starting at the second chunk together. // we don't need the lock because these chunks aren't published. var last_chunk = second_chunk; var offset = chunk_size + chunk_size; while (offset < self.allocation_granularity_bytes) : (offset += chunk_size) { const next_chunk = @ptrCast(*ChunkHeader, @alignCast(page_size, new_chunks + offset)); last_chunk.next = next_chunk; last_chunk = next_chunk; } const total_new_bytes: usize = offset - chunk_size; // link our prepared list into the actual list { const locked = self.lock.acquire(); defer locked.release(); // update stats self.total_free_list_bytes += total_new_bytes; // total_in_use_bytes has already been updated by the caller // link list last_chunk.next = self.first_free_chunk; self.first_free_chunk = second_chunk; } // return the first chunk return first_chunk; } else { const new_chunk = try page_alloc.alloc(chunk_size); return @ptrCast(ChunkPtr, new_chunk); } } /// Returns a chunk to the free list. This chunk remains committed and available. pub fn freeChunk(self: *@This(), chunk_ptr: [*]u8) void { const chunk = @ptrCast(*ChunkHeader, @alignCast(page_size, chunk_ptr)); { const locked = self.lock.acquire(); defer locked.release(); // update stats self.total_free_list_bytes += chunk_size; self.total_in_use_bytes -= chunk_size; // link list chunk.next = self.first_free_chunk; self.first_free_chunk = chunk; } } /// Return a bunch of chunks to the free list. pub fn freeChunks(self: *@This(), free_head: *ChunkHeader, free_tail: *ChunkHeader, num_chunks: usize) void { const byte_swing = @as(usize, num_chunks) * chunk_size; const locked = self.lock.acquire(); defer locked.release(); free_tail.next = self.first_free_chunk; self.first_free_chunk = free_head; self.total_free_list_bytes += byte_swing; self.total_in_use_bytes -= byte_swing; } }; } test "Lazy Allocator" { const chunk_size: usize = 16 * 1024; var allocator = ThreadsafeChunkAllocator(chunk_size).init(); testing.expect(isChunkAllocator(@TypeOf(allocator))); testing.expectEqual(@as(usize, 0), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 0), allocator.total_in_use_bytes); const chunk1 = try allocator.allocChunk(); testing.expectEqual(allocator.allocation_granularity_bytes - chunk_size, allocator.total_free_list_bytes); testing.expectEqual(chunk_size, allocator.total_in_use_bytes); allocator.freeChunk(chunk1); testing.expectEqual(allocator.allocation_granularity_bytes, allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 0), allocator.total_in_use_bytes); const chunk2 = try allocator.allocChunk(); testing.expectEqual(allocator.allocation_granularity_bytes - chunk_size, allocator.total_free_list_bytes); testing.expectEqual(chunk_size, allocator.total_in_use_bytes); testing.expectEqual(chunk1, chunk2); while (allocator.first_free_chunk != null) { _ = try allocator.allocChunk(); } testing.expectEqual(@as(usize, 0), allocator.total_free_list_bytes); testing.expectEqual(allocator.allocation_granularity_bytes, allocator.total_in_use_bytes); } test "Seed Allocator" { var allocator = ThreadsafeChunkAllocator(16 * 1024).init(); testing.expectEqual(@as(usize, 0), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 0), allocator.total_in_use_bytes); testing.expect(allocator.first_free_chunk == null); try allocator.seed(16 * 1024 * 4); testing.expectEqual(@as(usize, 16 * 1024 * 4), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 0), allocator.total_in_use_bytes); testing.expect(allocator.first_free_chunk != null); const chunk1 = try allocator.allocChunk(); testing.expectEqual(@as(usize, 16 * 1024 * 3), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 1), allocator.total_in_use_bytes); testing.expect(allocator.first_free_chunk != null); const chunk2 = try allocator.allocChunk(); testing.expectEqual(@as(usize, 16 * 1024 * 2), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 2), allocator.total_in_use_bytes); testing.expect(allocator.first_free_chunk != null); allocator.freeChunk(chunk2); testing.expectEqual(@as(usize, 16 * 1024 * 3), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 1), allocator.total_in_use_bytes); testing.expect(allocator.first_free_chunk != null); const chunk3 = try allocator.allocChunk(); testing.expectEqual(@as(usize, 16 * 1024 * 2), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 2), allocator.total_in_use_bytes); testing.expectEqual(chunk2, chunk3); testing.expect(allocator.first_free_chunk != null); const chunk4 = try allocator.allocChunk(); testing.expectEqual(@as(usize, 16 * 1024 * 1), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 3), allocator.total_in_use_bytes); testing.expect(allocator.first_free_chunk != null); const chunk5 = try allocator.allocChunk(); testing.expectEqual(@as(usize, 16 * 1024 * 0), allocator.total_free_list_bytes); testing.expectEqual(@as(usize, 16 * 1024 * 4), allocator.total_in_use_bytes); assert(allocator.first_free_chunk == null); }
chunk_alloc.zig
const cpu = @import("cpu.zig"); // commands to send to serial devices const Command = enum(u8) { LineEnableDLab = 0x80, }; /// ports for talking to serial devices pub const Port = enum(u16) { const Self = @This(); Com1 = 0x3F8, Com2 = 0x2F8, Com3 = 0x3E8, Com4 = 0x2E8, fn data(self: Self) u16 { return @enumToInt(self); } fn fifo(self: Self) u16 { return @enumToInt(self) + 2; } fn line(self: Self) u16 { return @enumToInt(self) + 3; } fn modem(self: Self) u16 { return @enumToInt(self) + 4; } fn status(self: Self) u16 { return @enumToInt(self) + 5; } // sets speed of data being sent fn configureBaud(self: Self, divisor: u16) void { cpu.io.write(self.line(), Command.LineEnableDLab); cpu.io.write(self.data(), @truncate(u8, divisor >> 8)); cpu.io.write(self.data(), @truncate(u8, divisor)); } // configures properties of the given serial port fn configureLine(self: Self) void { // data length of 8 bits, no parity bits, // one stop bit, and break control disabled cpu.io.write(port.line(), 0x03); } // configure the port's fifo queues fn configureFifo(self: Self) void { // enable FIFO, clear reciever and transmission queues, // and use 14 bytes as the queue size cpu.io.write(self.fifo(), 0xC7); } // tell port we are ready to send data fn configureModem(self: Self) void { // set RTS and DTR cpu.io.write(self.modem(), 0x03); } /// set thing up to use this port pub fn init(self: Self, baud_rate: u16) void { self.configureBaud(baud_rate); self.configureLine(); self.configureFifo(); self.configureModem(); } // is there data to be read on this port? fn isEmpty(self: Self) bool { return (cpu.io.read(self.status()) and 0x20) != 0; } pub fn putChar(self: Self, char: u8) void { while (!self.isEmpty()) { asm volatile ("pause"); } cpu.io.write(self.data(), char); } pub fn write(self: Self, str: []const u8) void { for (str) |char| { self.putChar(char); } } };
osmium/driver/serial.zig
pub const LoadedImageProtocol = @import("protocols/loaded_image_protocol.zig").LoadedImageProtocol; pub const loaded_image_device_path_protocol_guid = @import("protocols/loaded_image_protocol.zig").loaded_image_device_path_protocol_guid; pub const AcpiDevicePath = @import("protocols/device_path_protocol.zig").AcpiDevicePath; pub const BiosBootSpecificationDevicePath = @import("protocols/device_path_protocol.zig").BiosBootSpecificationDevicePath; pub const DevicePath = @import("protocols/device_path_protocol.zig").DevicePath; pub const DevicePathProtocol = @import("protocols/device_path_protocol.zig").DevicePathProtocol; pub const DevicePathType = @import("protocols/device_path_protocol.zig").DevicePathType; pub const EndDevicePath = @import("protocols/device_path_protocol.zig").EndDevicePath; pub const HardwareDevicePath = @import("protocols/device_path_protocol.zig").HardwareDevicePath; pub const MediaDevicePath = @import("protocols/device_path_protocol.zig").MediaDevicePath; pub const MessagingDevicePath = @import("protocols/device_path_protocol.zig").MessagingDevicePath; pub const SimpleFileSystemProtocol = @import("protocols/simple_file_system_protocol.zig").SimpleFileSystemProtocol; pub const FileProtocol = @import("protocols/file_protocol.zig").FileProtocol; pub const FileInfo = @import("protocols/file_protocol.zig").FileInfo; pub const InputKey = @import("protocols/simple_text_input_ex_protocol.zig").InputKey; pub const KeyData = @import("protocols/simple_text_input_ex_protocol.zig").KeyData; pub const KeyState = @import("protocols/simple_text_input_ex_protocol.zig").KeyState; pub const SimpleTextInputProtocol = @import("protocols/simple_text_input_protocol.zig").SimpleTextInputProtocol; pub const SimpleTextInputExProtocol = @import("protocols/simple_text_input_ex_protocol.zig").SimpleTextInputExProtocol; pub const SimpleTextOutputMode = @import("protocols/simple_text_output_protocol.zig").SimpleTextOutputMode; pub const SimpleTextOutputProtocol = @import("protocols/simple_text_output_protocol.zig").SimpleTextOutputProtocol; pub const SimplePointerMode = @import("protocols/simple_pointer_protocol.zig").SimplePointerMode; pub const SimplePointerProtocol = @import("protocols/simple_pointer_protocol.zig").SimplePointerProtocol; pub const SimplePointerState = @import("protocols/simple_pointer_protocol.zig").SimplePointerState; pub const AbsolutePointerMode = @import("protocols/absolute_pointer_protocol.zig").AbsolutePointerMode; pub const AbsolutePointerProtocol = @import("protocols/absolute_pointer_protocol.zig").AbsolutePointerProtocol; pub const AbsolutePointerState = @import("protocols/absolute_pointer_protocol.zig").AbsolutePointerState; pub const GraphicsOutputBltPixel = @import("protocols/graphics_output_protocol.zig").GraphicsOutputBltPixel; pub const GraphicsOutputBltOperation = @import("protocols/graphics_output_protocol.zig").GraphicsOutputBltOperation; pub const GraphicsOutputModeInformation = @import("protocols/graphics_output_protocol.zig").GraphicsOutputModeInformation; pub const GraphicsOutputProtocol = @import("protocols/graphics_output_protocol.zig").GraphicsOutputProtocol; pub const GraphicsOutputProtocolMode = @import("protocols/graphics_output_protocol.zig").GraphicsOutputProtocolMode; pub const GraphicsPixelFormat = @import("protocols/graphics_output_protocol.zig").GraphicsPixelFormat; pub const PixelBitmask = @import("protocols/graphics_output_protocol.zig").PixelBitmask; pub const EdidDiscoveredProtocol = @import("protocols/edid_discovered_protocol.zig").EdidDiscoveredProtocol; pub const EdidActiveProtocol = @import("protocols/edid_active_protocol.zig").EdidActiveProtocol; pub const EdidOverrideProtocol = @import("protocols/edid_override_protocol.zig").EdidOverrideProtocol; pub const EdidOverrideProtocolAttributes = @import("protocols/edid_override_protocol.zig").EdidOverrideProtocolAttributes; pub const SimpleNetworkProtocol = @import("protocols/simple_network_protocol.zig").SimpleNetworkProtocol; pub const MacAddress = @import("protocols/simple_network_protocol.zig").MacAddress; pub const SimpleNetworkMode = @import("protocols/simple_network_protocol.zig").SimpleNetworkMode; pub const SimpleNetworkReceiveFilter = @import("protocols/simple_network_protocol.zig").SimpleNetworkReceiveFilter; pub const SimpleNetworkState = @import("protocols/simple_network_protocol.zig").SimpleNetworkState; pub const NetworkStatistics = @import("protocols/simple_network_protocol.zig").NetworkStatistics; pub const SimpleNetworkInterruptStatus = @import("protocols/simple_network_protocol.zig").SimpleNetworkInterruptStatus; pub const ManagedNetworkServiceBindingProtocol = @import("protocols/managed_network_service_binding_protocol.zig").ManagedNetworkServiceBindingProtocol; pub const ManagedNetworkProtocol = @import("protocols/managed_network_protocol.zig").ManagedNetworkProtocol; pub const ManagedNetworkConfigData = @import("protocols/managed_network_protocol.zig").ManagedNetworkConfigData; pub const ManagedNetworkCompletionToken = @import("protocols/managed_network_protocol.zig").ManagedNetworkCompletionToken; pub const ManagedNetworkReceiveData = @import("protocols/managed_network_protocol.zig").ManagedNetworkReceiveData; pub const ManagedNetworkTransmitData = @import("protocols/managed_network_protocol.zig").ManagedNetworkTransmitData; pub const ManagedNetworkFragmentData = @import("protocols/managed_network_protocol.zig").ManagedNetworkFragmentData; pub const Ip6ServiceBindingProtocol = @import("protocols/ip6_service_binding_protocol.zig").Ip6ServiceBindingProtocol; pub const Ip6Protocol = @import("protocols/ip6_protocol.zig").Ip6Protocol; pub const Ip6ModeData = @import("protocols/ip6_protocol.zig").Ip6ModeData; pub const Ip6ConfigData = @import("protocols/ip6_protocol.zig").Ip6ConfigData; pub const Ip6Address = @import("protocols/ip6_protocol.zig").Ip6Address; pub const Ip6AddressInfo = @import("protocols/ip6_protocol.zig").Ip6AddressInfo; pub const Ip6RouteTable = @import("protocols/ip6_protocol.zig").Ip6RouteTable; pub const Ip6NeighborState = @import("protocols/ip6_protocol.zig").Ip6NeighborState; pub const Ip6NeighborCache = @import("protocols/ip6_protocol.zig").Ip6NeighborCache; pub const Ip6IcmpType = @import("protocols/ip6_protocol.zig").Ip6IcmpType; pub const Ip6CompletionToken = @import("protocols/ip6_protocol.zig").Ip6CompletionToken; pub const Ip6ConfigProtocol = @import("protocols/ip6_config_protocol.zig").Ip6ConfigProtocol; pub const Ip6ConfigDataType = @import("protocols/ip6_config_protocol.zig").Ip6ConfigDataType; pub const Udp6ServiceBindingProtocol = @import("protocols/udp6_service_binding_protocol.zig").Udp6ServiceBindingProtocol; pub const Udp6Protocol = @import("protocols/udp6_protocol.zig").Udp6Protocol; pub const Udp6ConfigData = @import("protocols/udp6_protocol.zig").Udp6ConfigData; pub const Udp6CompletionToken = @import("protocols/udp6_protocol.zig").Udp6CompletionToken; pub const Udp6ReceiveData = @import("protocols/udp6_protocol.zig").Udp6ReceiveData; pub const Udp6TransmitData = @import("protocols/udp6_protocol.zig").Udp6TransmitData; pub const Udp6SessionData = @import("protocols/udp6_protocol.zig").Udp6SessionData; pub const Udp6FragmentData = @import("protocols/udp6_protocol.zig").Udp6FragmentData; pub const hii = @import("protocols/hii.zig"); pub const HIIDatabaseProtocol = @import("protocols/hii_database_protocol.zig").HIIDatabaseProtocol; pub const HIIPopupProtocol = @import("protocols/hii_popup_protocol.zig").HIIPopupProtocol; pub const HIIPopupStyle = @import("protocols/hii_popup_protocol.zig").HIIPopupStyle; pub const HIIPopupType = @import("protocols/hii_popup_protocol.zig").HIIPopupType; pub const HIIPopupSelection = @import("protocols/hii_popup_protocol.zig").HIIPopupSelection; pub const RNGProtocol = @import("protocols/rng_protocol.zig").RNGProtocol; pub const ShellParametersProtocol = @import("protocols/shell_parameters_protocol.zig").ShellParametersProtocol;
lib/std/os/uefi/protocols.zig
const std = @import("std"); const c = @import("./c.zig").c; const SAMPLE_RATE = 48000; const CHANNELS = 2; const BIT_DEPTH = 16; const DEVICE_SAMPLES = 1024; // high enough not to crackle, low enough to not have much delay pub const OpusFile = struct { pub const Error = error{ OpenMemoryFailed, ReadFailed, EndOfFile, }; of: *c.OggOpusFile, fn load(data: []const u8) Error!OpusFile { var err: c_int = undefined; var of: *c.OggOpusFile = c.op_open_memory(data.ptr, data.len, &err).?; if (err != 0) { return Error.OpenMemoryFailed; } errdefer c.op_free(of); return OpusFile{ .of = of }; } fn deinit(self: *OpusFile) void { c.op_free(self.of); } fn decode(self: *OpusFile, buf: []f32, count: usize) Error!usize { const ret = c.op_read_float_stereo(self.of, buf.ptr, @intCast(c_int, count)); if (ret < 0) { return Error.ReadFailed; } else if (ret == 0) { return Error.EndOfFile; } return @intCast(usize, ret) * CHANNELS; } fn rewind(self: *OpusFile) void { _ = c.op_pcm_seek(self.of, 0); } }; pub const AudioDevice = struct { pub const Error = error{ DeviceOpenFailed, }; pub const PlayHandle = usize; pub const PlayOptions = struct { volume: f32 = 1.0, loop: bool = false, }; const PlayBuffer = struct { file: OpusFile, opt: PlayOptions, deletePending: bool = false, sampleDelay: usize = 0, // skip N samples /// Will arithmetically add samples to the output buffer pub fn addSamples(self: *PlayBuffer, bufOut: []f32) !void { var buf: [DEVICE_SAMPLES * CHANNELS]f32 = undefined; var writtenI: usize = std.math.min(buf.len, self.sampleDelay); self.sampleDelay -= writtenI; while (writtenI != bufOut.len) { // Decode const want = std.math.min(buf.len, bufOut.len - writtenI); const got = self.file.decode(&buf, want) catch |e| { if (e == OpusFile.Error.EndOfFile) { if (self.opt.loop) { self.file.rewind(); } else { self.deletePending = true; self.file.deinit(); } return; } return e; }; // Apply volume and add var i: usize = 0; while (i < got) : (i += 1) { bufOut[writtenI + i] += buf[i] * self.opt.volume; } writtenI += got; } } }; const PlayBufferMap = std.AutoHashMap(PlayHandle, PlayBuffer); alloc: *std.mem.Allocator, playbackIncrement: usize = 0, device: c.SDL_AudioDeviceID, sounds: PlayBufferMap, lastSampleCallTick: u32, pub fn openDefault(alloc: *std.mem.Allocator) (Error || std.mem.Allocator.Error)!*AudioDevice { var audioDevice = try alloc.create(AudioDevice); audioDevice.alloc = alloc; audioDevice.playbackIncrement = 0; audioDevice.sounds = PlayBufferMap.init(alloc); audioDevice.lastSampleCallTick = c.SDL_GetTicks(); const audioSpec = c.SDL_AudioSpec{ .freq = SAMPLE_RATE, .format = c.AUDIO_F32, .channels = CHANNELS, .samples = DEVICE_SAMPLES, .userdata = audioDevice, .callback = sdlAudioCallback, .silence = 0, .size = 0, .padding = 0, }; audioDevice.device = c.SDL_OpenAudioDevice(null, 0, &audioSpec, null, 0); if (audioDevice.device == 0) { return Error.DeviceOpenFailed; } c.SDL_PauseAudioDevice(audioDevice.device, 0); return audioDevice; } pub fn deinit(self: *AudioDevice) void { c.SDL_PauseAudioDevice(self.device, 0); c.SDL_CloseAudioDevice(self.device); self.sounds.deinit(); self.alloc.destroy(self); } pub fn play(self: *AudioDevice, filedata: []const u8, options: PlayOptions) !PlayHandle { const sampleDelay = @divTrunc((c.SDL_GetTicks() - self.lastSampleCallTick) * SAMPLE_RATE * CHANNELS, 1000); var file = try OpusFile.load(filedata); self.playbackIncrement += 1; c.SDL_LockAudioDevice(self.device); try self.sounds.put(self.playbackIncrement, PlayBuffer{ .file = file, .opt = options, .sampleDelay = sampleDelay, }); c.SDL_UnlockAudioDevice(self.device); return self.playbackIncrement; } pub fn stop(self: *AudioDevice, handle: PlayHandle) void { c.SDL_LockAudioDevice(self.device); var s = self.sounds.get(handle); if (s != null) { s.file.deinit(); self.sounds.remove(handle); } c.SDL_UnlockAudioDevice(self.device); } // https://wiki.libsdl.org/SDL_AudioSpec#remarks fn sdlAudioCallback(userdata: ?*c_void, stream: [*c]u8, len: c_int) callconv(.C) void { const self = @ptrCast(*AudioDevice, @alignCast(@alignOf(*AudioDevice), userdata.?)); var buf = @ptrCast([*c]f32, @alignCast(@alignOf(f32), stream))[0..@intCast(usize, @divTrunc(len, 4))]; self.lastSampleCallTick = c.SDL_GetTicks(); // Mix std.mem.set(f32, buf, 0); var soundIter = self.sounds.iterator(); while (soundIter.next()) |kv| { kv.value_ptr.addSamples(buf) catch continue; if (kv.value_ptr.deletePending) { _ = self.sounds.remove(kv.key_ptr.*); } } } };
src/audio.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const Value = @import("value.zig").Value; const Type = @import("type.zig").Type; const TypedValue = @import("TypedValue.zig"); const assert = std.debug.assert; const ir = @import("ir.zig"); const zir = @import("zir.zig"); const Module = @import("Module.zig"); const Inst = ir.Inst; const Body = ir.Body; const trace = @import("tracy.zig").trace; const Scope = Module.Scope; const InnerError = Module.InnerError; const Decl = Module.Decl; pub fn analyzeInst(mod: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Inst { switch (old_inst.tag) { .alloc => return analyzeInstAlloc(mod, scope, old_inst.castTag(.alloc).?), .alloc_inferred => return analyzeInstAllocInferred(mod, scope, old_inst.castTag(.alloc_inferred).?), .arg => return analyzeInstArg(mod, scope, old_inst.castTag(.arg).?), .bitcast_ref => return analyzeInstBitCastRef(mod, scope, old_inst.castTag(.bitcast_ref).?), .bitcast_result_ptr => return analyzeInstBitCastResultPtr(mod, scope, old_inst.castTag(.bitcast_result_ptr).?), .block => return analyzeInstBlock(mod, scope, old_inst.castTag(.block).?, false), .block_comptime => return analyzeInstBlock(mod, scope, old_inst.castTag(.block_comptime).?, true), .block_flat => return analyzeInstBlockFlat(mod, scope, old_inst.castTag(.block_flat).?, false), .block_comptime_flat => return analyzeInstBlockFlat(mod, scope, old_inst.castTag(.block_comptime_flat).?, true), .@"break" => return analyzeInstBreak(mod, scope, old_inst.castTag(.@"break").?), .breakpoint => return analyzeInstBreakpoint(mod, scope, old_inst.castTag(.breakpoint).?), .breakvoid => return analyzeInstBreakVoid(mod, scope, old_inst.castTag(.breakvoid).?), .call => return analyzeInstCall(mod, scope, old_inst.castTag(.call).?), .coerce_result_block_ptr => return analyzeInstCoerceResultBlockPtr(mod, scope, old_inst.castTag(.coerce_result_block_ptr).?), .coerce_result_ptr => return analyzeInstCoerceResultPtr(mod, scope, old_inst.castTag(.coerce_result_ptr).?), .coerce_to_ptr_elem => return analyzeInstCoerceToPtrElem(mod, scope, old_inst.castTag(.coerce_to_ptr_elem).?), .compileerror => return analyzeInstCompileError(mod, scope, old_inst.castTag(.compileerror).?), .@"const" => return analyzeInstConst(mod, scope, old_inst.castTag(.@"const").?), .dbg_stmt => return analyzeInstDbgStmt(mod, scope, old_inst.castTag(.dbg_stmt).?), .declref => return analyzeInstDeclRef(mod, scope, old_inst.castTag(.declref).?), .declref_str => return analyzeInstDeclRefStr(mod, scope, old_inst.castTag(.declref_str).?), .declval => return analyzeInstDeclVal(mod, scope, old_inst.castTag(.declval).?), .declval_in_module => return analyzeInstDeclValInModule(mod, scope, old_inst.castTag(.declval_in_module).?), .ensure_result_used => return analyzeInstEnsureResultUsed(mod, scope, old_inst.castTag(.ensure_result_used).?), .ensure_result_non_error => return analyzeInstEnsureResultNonError(mod, scope, old_inst.castTag(.ensure_result_non_error).?), .ensure_indexable => return analyzeInstEnsureIndexable(mod, scope, old_inst.castTag(.ensure_indexable).?), .ref => return analyzeInstRef(mod, scope, old_inst.castTag(.ref).?), .ret_ptr => return analyzeInstRetPtr(mod, scope, old_inst.castTag(.ret_ptr).?), .ret_type => return analyzeInstRetType(mod, scope, old_inst.castTag(.ret_type).?), .single_const_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.single_const_ptr_type).?, false, .One), .single_mut_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.single_mut_ptr_type).?, true, .One), .many_const_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.many_const_ptr_type).?, false, .Many), .many_mut_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.many_mut_ptr_type).?, true, .Many), .c_const_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.c_const_ptr_type).?, false, .C), .c_mut_ptr_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.c_mut_ptr_type).?, true, .C), .const_slice_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.const_slice_type).?, false, .Slice), .mut_slice_type => return analyzeInstSimplePtrType(mod, scope, old_inst.castTag(.mut_slice_type).?, true, .Slice), .ptr_type => return analyzeInstPtrType(mod, scope, old_inst.castTag(.ptr_type).?), .store => return analyzeInstStore(mod, scope, old_inst.castTag(.store).?), .str => return analyzeInstStr(mod, scope, old_inst.castTag(.str).?), .int => { const big_int = old_inst.castTag(.int).?.positionals.int; return mod.constIntBig(scope, old_inst.src, Type.initTag(.comptime_int), big_int); }, .inttype => return analyzeInstIntType(mod, scope, old_inst.castTag(.inttype).?), .loop => return analyzeInstLoop(mod, scope, old_inst.castTag(.loop).?), .param_type => return analyzeInstParamType(mod, scope, old_inst.castTag(.param_type).?), .ptrtoint => return analyzeInstPtrToInt(mod, scope, old_inst.castTag(.ptrtoint).?), .fieldptr => return analyzeInstFieldPtr(mod, scope, old_inst.castTag(.fieldptr).?), .deref => return analyzeInstDeref(mod, scope, old_inst.castTag(.deref).?), .as => return analyzeInstAs(mod, scope, old_inst.castTag(.as).?), .@"asm" => return analyzeInstAsm(mod, scope, old_inst.castTag(.@"asm").?), .@"unreachable" => return analyzeInstUnreachable(mod, scope, old_inst.castTag(.@"unreachable").?, true), .unreach_nocheck => return analyzeInstUnreachable(mod, scope, old_inst.castTag(.unreach_nocheck).?, false), .@"return" => return analyzeInstRet(mod, scope, old_inst.castTag(.@"return").?), .returnvoid => return analyzeInstRetVoid(mod, scope, old_inst.castTag(.returnvoid).?), .@"fn" => return analyzeInstFn(mod, scope, old_inst.castTag(.@"fn").?), .@"export" => return analyzeInstExport(mod, scope, old_inst.castTag(.@"export").?), .primitive => return analyzeInstPrimitive(mod, scope, old_inst.castTag(.primitive).?), .fntype => return analyzeInstFnType(mod, scope, old_inst.castTag(.fntype).?), .intcast => return analyzeInstIntCast(mod, scope, old_inst.castTag(.intcast).?), .bitcast => return analyzeInstBitCast(mod, scope, old_inst.castTag(.bitcast).?), .floatcast => return analyzeInstFloatCast(mod, scope, old_inst.castTag(.floatcast).?), .elemptr => return analyzeInstElemPtr(mod, scope, old_inst.castTag(.elemptr).?), .add => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.add).?), .addwrap => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.addwrap).?), .sub => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.sub).?), .subwrap => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.subwrap).?), .mul => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.mul).?), .mulwrap => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.mulwrap).?), .div => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.div).?), .mod_rem => return analyzeInstArithmetic(mod, scope, old_inst.castTag(.mod_rem).?), .array_cat => return analyzeInstArrayCat(mod, scope, old_inst.castTag(.array_cat).?), .array_mul => return analyzeInstArrayMul(mod, scope, old_inst.castTag(.array_mul).?), .bitand => return analyzeInstBitwise(mod, scope, old_inst.castTag(.bitand).?), .bitnot => return analyzeInstBitNot(mod, scope, old_inst.castTag(.bitnot).?), .bitor => return analyzeInstBitwise(mod, scope, old_inst.castTag(.bitor).?), .xor => return analyzeInstBitwise(mod, scope, old_inst.castTag(.xor).?), .shl => return analyzeInstShl(mod, scope, old_inst.castTag(.shl).?), .shr => return analyzeInstShr(mod, scope, old_inst.castTag(.shr).?), .cmp_lt => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_lt).?, .lt), .cmp_lte => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_lte).?, .lte), .cmp_eq => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_eq).?, .eq), .cmp_gte => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_gte).?, .gte), .cmp_gt => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_gt).?, .gt), .cmp_neq => return analyzeInstCmp(mod, scope, old_inst.castTag(.cmp_neq).?, .neq), .condbr => return analyzeInstCondBr(mod, scope, old_inst.castTag(.condbr).?), .isnull => return analyzeInstIsNonNull(mod, scope, old_inst.castTag(.isnull).?, true), .isnonnull => return analyzeInstIsNonNull(mod, scope, old_inst.castTag(.isnonnull).?, false), // a comment .iserr => return analyzeInstIsErr(mod, scope, old_inst.castTag(.iserr).?), // another comment .boolnot => return analyzeInstBoolNot(mod, scope, old_inst.castTag(.boolnot).?), .typeof => return analyzeInstTypeOf(mod, scope, old_inst.castTag(.typeof).?), .optional_type => return analyzeInstOptionalType(mod, scope, old_inst.castTag(.optional_type).?), .unwrap_optional_safe => return analyzeInstUnwrapOptional(mod, scope, old_inst.castTag(.unwrap_optional_safe).?, true), .unwrap_optional_unsafe => return analyzeInstUnwrapOptional(mod, scope, old_inst.castTag(.unwrap_optional_unsafe).?, false), .unwrap_err_safe => return analyzeInstUnwrapErr(mod, scope, old_inst.castTag(.unwrap_err_safe).?, true), .unwrap_err_unsafe => return analyzeInstUnwrapErr(mod, scope, old_inst.castTag(.unwrap_err_unsafe).?, false), .unwrap_err_code => return analyzeInstUnwrapErrCode(mod, scope, old_inst.castTag(.unwrap_err_code).?), .ensure_err_payload_void => return analyzeInstEnsureErrPayloadVoid(mod, scope, old_inst.castTag(.ensure_err_payload_void).?), .array_type => return analyzeInstArrayType(mod, scope, old_inst.castTag(.array_type).?), .array_type_sentinel => return analyzeInstArrayTypeSentinel(mod, scope, old_inst.castTag(.array_type_sentinel).?), .enum_literal => return analyzeInstEnumLiteral(mod, scope, old_inst.castTag(.enum_literal).?), .merge_error_sets => return analyzeInstMergeErrorSets(mod, scope, old_inst.castTag(.merge_error_sets).?), .error_union_type => return analyzeInstErrorUnionType(mod, scope, old_inst.castTag(.error_union_type).?), .anyframe_type => return analyzeInstAnyframeType(mod, scope, old_inst.castTag(.anyframe_type).?), .error_set => return analyzeInstErrorSet(mod, scope, old_inst.castTag(.error_set).?), .slice => return analyzeInstSlice(mod, scope, old_inst.castTag(.slice).?), .slice_start => return analyzeInstSliceStart(mod, scope, old_inst.castTag(.slice_start).?), } }
tests/samples/count/zir_sema.zig/zir_sema.zig
const wlr = @import("../wlroots.zig"); const wayland = @import("wayland"); const wl = wayland.server.wl; pub const XdgDecorationManagerV1 = extern struct { global: *wl.Global, decorations: wl.list.Head(XdgToplevelDecorationV1, "link"), server_destroy: wl.Listener(*wl.Server), events: extern struct { new_toplevel_decoration: wl.Signal(*XdgToplevelDecorationV1), destroy: wl.Signal(*XdgDecorationManagerV1), }, data: usize, extern fn wlr_xdg_decoration_manager_v1_create(server: *wl.Server) ?*XdgDecorationManagerV1; pub fn create(server: *wl.Server) !*XdgDecorationManagerV1 { return wlr_xdg_decoration_manager_v1_create(server) orelse error.OutOfMemory; } }; pub const XdgToplevelDecorationV1 = extern struct { pub const Mode = extern enum { none = 0, client_side = 1, server_side = 2, }; pub const Configure = extern struct { /// XdgToplevelDecorationV1.configure_list link: wl.list.Link, surface_configure: *wlr.XdgSurface.Configure, mode: Mode, }; resource: *wl.Resource, surface: *wlr.XdgSurface, manager: *XdgDecorationManagerV1, /// XdgDecorationManagerV1.decorations link: wl.list.Link, added: bool, current_mode: Mode, client_pending_mode: Mode, server_pending_mode: Mode, configure_list: wl.list.Head(XdgToplevelDecorationV1.Configure, "link"), events: extern struct { destroy: wl.Signal(*XdgToplevelDecorationV1), request_mode: wl.Signal(*XdgToplevelDecorationV1), }, surface_destroy: wl.Listener(*wlr.XdgSurface), surface_configure: wl.Listener(*wlr.XdgSurface.Configure), surface_ack_configure: wl.Listener(*wlr.XdgSurface.Configure), surface_commit: wl.Listener(*wlr.Surface), data: usize, extern fn wlr_xdg_toplevel_decoration_v1_set_mode(decoration: *XdgToplevelDecorationV1, mode: Mode) u32; pub const setMode = wlr_xdg_toplevel_decoration_v1_set_mode; };
src/types/xdg_decoration_v1.zig
const std = @import("std"); const fmt = std.fmt; /// A parser that consumes one full reply and discards it. It's written as a /// dedicated parser because it doesn't require recursion to consume the right /// amount of input and, given the fact that the type doesn't "peel away", /// recursion would look unbounded to the type system. /// It can also be used to consume just one attribute element by claiming to /// have found a map instead. This trick is used by the root parser in the /// initial setup of both `parse` and `parseAlloc`. pub const VoidParser = struct { pub fn discardOne(tag: u8, msg: anytype) !void { // When we start, we have one item to consume. // As we inspect it, we might discover that it's a container, requiring // us to increase our items count. var foundError = false; var itemTag = tag; var itemsToConsume: usize = 1; while (itemsToConsume > 0) { itemsToConsume -= 1; switch (itemTag) { else => std.debug.panic("Found `{c}` in the *VOID* parser's switch." ++ " Probably a bug in a type that implements `Redis.Parser`.", .{itemTag}), '_' => try msg.skipBytes(2, .{}), // `_\r\n` '#' => try msg.skipBytes(3, .{}), // `#t\r\n`, `#t\r\n` '$', '=', '!' => { // Lenght-prefixed string if (itemTag == '!') { foundError = true; } // 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; } } var size = try fmt.parseInt(usize, buf[0..end], 10); try msg.skipBytes(1 + size + 2, .{}); }, ':', ',', '+', '-' => { // Simple element with final `\r\n` if (itemTag == '-') { foundError = true; } var ch = try msg.readByte(); while (ch != '\n') ch = try msg.readByte(); }, '|' => { // Attributes are metadata that precedes a proper reply // item and do not count towards the original // `itemsToConsume` count. Consume the attribute element // without counting the current item as consumed. // 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); size *= 2; // Add all the new items to the pile that needs to be // consumed, plus the one that we did not consume this // loop. itemsToConsume += size + 1; }, '*', '%' => { // Lists, Maps // 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); // Maps advertize the number of field-value pairs, // so we double the amount in that case. if (tag == '%') size *= 2; itemsToConsume += size; }, } // If we still have items to consume, read the next tag. if (itemsToConsume > 0) itemTag = try msg.readByte(); } if (foundError) return error.GotErrorReply; } };
src/parser/void.zig
const c = @cImport({ @cInclude("cfl_button.h"); }); const widget = @import("widget.zig"); const enums = @import("enums.zig"); pub const Button = struct { inner: ?*c.Fl_Button, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Button { const ptr = c.Fl_Button_new(x, y, w, h, title); if (ptr == null) unreachable; return Button{ .inner = ptr, }; } pub fn raw(self: *Button) ?*c.Fl_Button { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Button) Button { return Button{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) Button { return Button{ .inner = @ptrCast(?*c.Fl_Button, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) Button { return Button{ .inner = @ptrCast(?*c.Fl_Button, ptr), }; } pub fn toVoidPtr(self: *Button) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const Button) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn handle(self: *Button, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Button_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Button, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Button_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } pub fn shortcut(self: *const Button) i32 { return c.Fl_Button_shortcut(self.inner); } pub fn setShortcut(self: *Button, shrtct: i32) void { c.Fl_Button_set_shortcut(self.inner, shrtct); } pub fn clear(self: *Button) void { c.Fl_Button_clear(self.inner); } pub fn value(self: *const Button) bool { return c.Fl_Button_value(self.inner) != 0; } pub fn setValue(self: *Button, flag: bool) void { c.Fl_Button_set_value(self.inner, @boolToInt(flag)); } pub fn setDownBox(self: *Button, f: enums.BoxType) void { c.Fl_Button_set_down_box(self.inner, f); } pub fn downBox(self: *const Button) enums.BoxType { return c.Fl_Button_down_box(self.inner); } }; pub const RadioButton = struct { inner: ?*c.Fl_Radio_Button, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) RadioButton { const ptr = c.Fl_Radio_Button_new(x, y, w, h, title); if (ptr == null) unreachable; return RadioButton{ .inner = ptr, }; } pub fn raw(self: *RadioButton) ?*c.Fl_RadioButton { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_RadioButton) RadioButton { return RadioButton{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) RadioButton { return RadioButton{ .inner = @ptrCast(?*c.Fl_RadioButton, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) RadioButton { return RadioButton{ .inner = @ptrCast(?*c.Fl_RadioButton, ptr), }; } pub fn toVoidPtr(self: *RadioButton) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const RadioButton) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asButton(self: *const RadioButton) Button { return Button{ .inner = @ptrCast(?*c.Fl_Button, self.inner), }; } pub fn handle(self: *RadioButton, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Radio_Button_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *RadioButton, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Radio_Button_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const CheckButton = struct { inner: ?*c.Fl_Check_Button, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) CheckButton { const ptr = c.Fl_Check_Button_new(x, y, w, h, title); if (ptr == null) unreachable; return CheckButton{ .inner = ptr, }; } pub fn raw(self: *CheckButton) ?*c.Fl_CheckButton { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_CheckButton) CheckButton { return CheckButton{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) CheckButton { return CheckButton{ .inner = @ptrCast(?*c.Fl_CheckButton, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) CheckButton { return CheckButton{ .inner = @ptrCast(?*c.Fl_CheckButton, ptr), }; } pub fn toVoidPtr(self: *CheckButton) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const CheckButton) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asButton(self: *const CheckButton) Button { return Button{ .inner = @ptrCast(?*c.Fl_Button, self.inner), }; } pub fn handle(self: *CheckButton, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Check_Button_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *CheckButton, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Check_Button_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; pub const RoundButton = struct { inner: ?*c.Fl_Round_Button, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) RoundButton { const ptr = c.Fl_Round_Button_new(x, y, w, h, title); if (ptr == null) unreachable; return RoundButton{ .inner = ptr, }; } pub fn raw(self: *RoundButton) ?*c.Fl_RoundButton { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_RoundButton) RoundButton { return RoundButton{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) RoundButton { return RoundButton{ .inner = @ptrCast(?*c.Fl_RoundButton, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) RoundButton { return RoundButton{ .inner = @ptrCast(?*c.Fl_RoundButton, ptr), }; } pub fn toVoidPtr(self: *RoundButton) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const RoundButton) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asButton(self: *const RoundButton) Button { return Button{ .inner = @ptrCast(?*c.Fl_Button, self.inner), }; } pub fn handle(self: *RoundButton, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Round_Button_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *RoundButton, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Round_Button_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; test "" { @import("std").testing.refAllDecls(@This()); }
src/button.zig
const std = @import("std"); const assert = std.debug.assert; const builtin = @import("builtin"); const net = std.net; const os = std.os; const IO_Uring = os.linux.IO_Uring; const io_uring_cqe = os.linux.io_uring_cqe; const Event = packed struct { fd: i32, op: Op, }; const Op = enum(u32) { Accept, Recv, Send, }; const port = 3001; const kernel_backlog = 512; const max_connections = 4096; const max_buffer = 1000; var buffers: [max_connections][max_buffer]u8 = undefined; pub fn main() !void { if (builtin.os.tag != .linux) return error.LinuxRequired; const address = try net.Address.parseIp4("127.0.0.1", port); const domain = address.any.family; const socket_type = os.SOCK.STREAM | os.SOCK.CLOEXEC; const protocol = os.IPPROTO.TCP; const server = try os.socket(domain, socket_type, protocol); errdefer os.close(server); try os.setsockopt(server, os.SOL.SOCKET, os.SO.REUSEADDR, &std.mem.toBytes(@as(c_int, 1))); try os.bind(server, &address.any, address.getOsSockLen()); try os.listen(server, kernel_backlog); std.debug.print("net: echo server: io_uring: listening on {}...\n", .{address}); var ring = try IO_Uring.init(512, 0); defer ring.deinit(); var cqes: [512]io_uring_cqe = undefined; var accept_addr: os.sockaddr = undefined; var accept_addr_len: os.socklen_t = @sizeOf(@TypeOf(accept_addr)); for (buffers) |_, index| { buffers[index] = [_]u8{0} ** max_buffer; } try accept(&ring, server, &accept_addr, &accept_addr_len); while (true) { const count = try ring.copy_cqes(cqes[0..], 0); var i: usize = 0; while (i < count) : (i += 1) { const cqe = cqes[i]; if (cqe.res < 0) { switch (-cqe.res) { os.E.PIPE => std.debug.print("EPIPE {}\n", .{cqe}), os.E.CONNRESET => std.debug.print("ECONNRESET {}\n", .{cqe}), else => std.debug.print("ERROR {}\n", .{cqe}), } os.exit(1); } const event = @bitCast(Event, cqe.user_data); switch (event.op) { .Accept => { try accept(&ring, server, &accept_addr, &accept_addr_len); try recv(&ring, cqe.res); }, .Recv => { if (cqe.res != 0) { const size = @intCast(usize, cqe.res); try send(&ring, event.fd, size); } }, .Send => { try recv(&ring, event.fd); }, } } _ = try ring.submit_and_wait(1); } } fn accept(ring: *IO_Uring, fd: os.fd_t, addr: *os.sockaddr, addr_len: *os.socklen_t) !void { var user_data = get_user_data(fd, .Accept); _ = try ring.accept(user_data, fd, addr, addr_len, 0); } fn recv(ring: *IO_Uring, fd: os.fd_t) !void { var user_data = get_user_data(fd, .Recv); _ = try ring.recv(user_data, fd, get_buffer(fd)[0..], os.MSG.NOSIGNAL); } fn send(ring: *IO_Uring, fd: os.fd_t, size: usize) !void { var user_data = get_user_data(fd, .Send); _ = try ring.send(user_data, fd, get_buffer(fd)[0..size], os.MSG.NOSIGNAL); } fn get_buffer(fd: os.fd_t) []u8 { return buffers[@intCast(usize, fd)][0..]; } fn get_user_data(fd: os.fd_t, op: Op) u64 { var event: Event = .{ .fd = fd, .op = op }; var user_data = @bitCast(u64, event); return user_data; }
demos/io_uring/net_io_uring.zig
const DaisyChain = @import("DaisyChain.zig"); const CTC = @This(); channels: [NumChannels]Channel = [_]Channel{.{}} ** NumChannels, // reset the CTC chip pub fn reset(self: *CTC) void { for (self.channels) |*chn| { chn.control = Ctrl.RESET; chn.constant = 0; chn.down_counter = 0; chn.waiting_for_trigger = false; chn.trigger_edge = false; chn.prescaler_mask = 0x0F; chn.intr.reset(); } } // perform an IO request pub fn iorq(self: *CTC, in_pins: u64) u64 { var pins = in_pins; // check for chip-enabled and IO requested if ((pins & (CE|IORQ|M1)) == (CE|IORQ)) { const chn_index: u2 = @truncate(u2, pins >> CS0PinShift); if (0 != (pins & RD)) { // an IO read request pins = self.ioRead(chn_index, pins); } else { // an IO write request pins = self.ioWrite(chn_index, pins); } } return pins; } // execute one clock tick pub fn tick(self: *CTC, in_pins: u64) u64 { var pins = in_pins & ~(ZCTO0|ZCTO1|ZCTO2); for (self.channels) |*chn, i| { const chn_index = @truncate(u2, i); // check if externally triggered if (chn.waiting_for_trigger or ((chn.control & Ctrl.MODE) == Ctrl.MODE_COUNTER)) { const trg: bool = (0 != (pins & (CLKTRG0 << chn_index))); if (trg != chn.ext_trigger) { chn.ext_trigger = trg; // rising/falling edge trigger if (chn.trigger_edge == trg) { pins = self.activeEdge(chn_index, pins); } } } else if ((chn.control & (Ctrl.MODE|Ctrl.RESET|Ctrl.CONST_FOLLOWS)) == Ctrl.MODE_TIMER) { // handle timer mode downcounting chn.prescaler -%= 1; if (0 == (chn.prescaler & chn.prescaler_mask)) { // prescaler has reached zero, tick the down counter chn.down_counter -%= 1; if (0 == chn.down_counter) { pins = self.counterZero(chn_index, pins); } } } } return pins; } // call once per CPU machine cycle to handle interrupts pub fn int(self: *CTC, in_pins: u64) u64 { var pins = in_pins; for (self.channels) |*chn| { pins = chn.intr.tick(pins); } return pins; } // set data pins in pin mask pub fn setData(pins: u64, data: u8) u64 { return (pins & ~DataPinMask) | (@as(u64, data) << DataPinShift); } // get data pins in pin mask pub fn getData(pins: u64) u8 { return @truncate(u8, pins >> DataPinShift); } // data bus pins shared with CPU pub const D0: u64 = 1<<16; pub const D1: u64 = 1<<17; pub const D2: u64 = 1<<18; pub const D3: u64 = 1<<19; pub const D4: u64 = 1<<20; pub const D5: u64 = 1<<21; pub const D6: u64 = 1<<22; pub const D7: u64 = 1<<23; pub const DataPinShift = 16; pub const DataPinMask: u64 = 0xFF0000; // control pins shared with CPU pub const M1: u64 = 1<<24; // machine cycle 1 pub const IORQ: u64 = 1<<26; // IO request pub const RD: u64 = 1<<27; // read request // CTC specific pins, starting at pin 40 pub const CE: u64 = 1<<40; // chip enable pub const CS0: u64 = 1<<41; // channel select 0 pub const CS1: u64 = 1<<42; // channel select 1 pub const CLKTRG0: u64 = 1<<43; // clock/timer trigger 0 pub const CLKTRG1: u64 = 1<<44; // clock/timer trigger 1 pub const CLKTRG2: u64 = 1<<45; // clock/timer trigger 2 pub const CLKTRG3: u64 = 1<<46; // click/timer trigger 3 pub const ZCTO0: u64 = 1<<47; // zero count / timeout 0 pub const ZCTO1: u64 = 1<<48; // zero count / timeout 1 pub const ZCTO2: u64 = 1<<49; // zero count / timeout 2 const CS0PinShift = 41; // control register bits pub const Ctrl = struct { pub const EI: u8 = 1<<7; // 1: interrupt enabled, 0: interrupt disabled pub const MODE: u8 = 1<<6; // 1: counter mode, 0: timer mode pub const MODE_COUNTER: u8 = 1<<6; pub const MODE_TIMER: u8 = 0; pub const PRESCALER: u8 = 1<<5; // 1: prescale value 256, 0: prescale value 16 pub const PRESCALER_256: u8 = 1<<5; pub const PRESCALER_16: u8 = 0; pub const EDGE: u8 = 1<<4; // 1: rising edge, 0: falling edge pub const EDGE_RISING: u8 = 1<<4; pub const EDGE_FALLING: u8 = 0; pub const TRIGGER: u8 = 1<<3; // 1: CLK/TRG pulse starts timer, 0: trigger when time constant loaded pub const TRIGGER_WAIT: u8 = 1<<3; pub const TRIGGER_AUTO: u8 = 0; pub const CONST_FOLLOWS: u8 = 1<<2; // 1: time constant follows, 0: no time constant follows pub const RESET: u8 = 1<<1; // 1: software reset, 0: continue operation pub const CONTROL: u8 = 1<<0; // 1: control, 0: vector pub const VECTOR: u8 = 0; }; // CTC channel state pub const NumChannels = 4; pub const Channel = struct { control: u8 = Ctrl.RESET, constant: u8 = 0, down_counter: u8 = 0, prescaler: u8 = 0, trigger_edge: bool = false, waiting_for_trigger: bool = false, ext_trigger: bool = false, prescaler_mask: u8 = 0x0F, intr: DaisyChain = .{}, }; // read from CTC channel fn ioRead(self: *CTC, chn_index: u2, pins: u64) u64 { return setData(pins, self.channels[chn_index].down_counter); } // write to CTC channel fn ioWrite(self: *CTC, chn_index: u2, in_pins: u64) u64 { var pins = in_pins; const data = getData(pins); const chn = &self.channels[chn_index]; if (0 != (chn.control & Ctrl.CONST_FOLLOWS)) { // timer constant following control word chn.control &= ~(Ctrl.CONST_FOLLOWS|Ctrl.RESET); chn.constant = data; if ((chn.control & Ctrl.MODE) == Ctrl.MODE_TIMER) { if ((chn.control & Ctrl.TRIGGER) == Ctrl.TRIGGER_WAIT) { chn.waiting_for_trigger = true; } else { chn.down_counter = chn.constant; } } else { chn.down_counter = chn.constant; } } else if (0 != (data & Ctrl.CONTROL)) { // a new control word const old_ctrl = chn.control; chn.control = data; chn.trigger_edge = ((data & Ctrl.EDGE) == Ctrl.EDGE_RISING); if ((chn.control & Ctrl.PRESCALER) == Ctrl.PRESCALER_16) { chn.prescaler_mask = 0x0F; } else { chn.prescaler_mask = 0xFF; } // changing the Trigger Slope triggers an 'active edge' */ if ((old_ctrl & Ctrl.EDGE) != (chn.control & Ctrl.EDGE)) { pins = self.activeEdge(chn_index, pins); } } else { // the interrupt vector for the entire CTC must be written // to channel 0, the vectors for the following channels // are then computed from the base vector plus 2 bytes per channel // if (0 == chn_index) { for (self.channels) |*c, i| { c.intr.vector = (data & 0xF8) +% 2*@truncate(u8,i); } } } return pins; } // Issue an 'active edge' on a channel, this happens when a CLKTRG pin // is triggered, or when reprogramming the Z80CTC_CTRL_EDGE control bit. // // This results in: // - if the channel is in timer mode and waiting for trigger, // the waiting flag is cleared and timing starts // - if the channel is in counter mode, the counter decrements // fn activeEdge(self: *CTC, chn_index: u3, in_pins: u64) u64 { var pins = in_pins; const chn = &self.channels[chn_index]; if ((chn.control & Ctrl.MODE) == Ctrl.MODE_COUNTER) { // counter mode chn.down_counter -%= 1; if (0 == chn.down_counter) { pins = self.counterZero(chn_index, pins); } } else if (chn.waiting_for_trigger) { // timer mode and waiting for trigger chn.waiting_for_trigger = false; chn.down_counter = chn.constant; } return pins; } // called when the downcounter reaches zero, request interrupt, // trigger ZCTO pin and reload downcounter // fn counterZero(self: *CTC, chn_index: u3, in_pins: u64) u64 { var pins = in_pins; const chn = &self.channels[chn_index]; // if down counter has reached zero, trigger interrupt and ZCTO pin if (0 != (chn.control & Ctrl.EI)) { // interrupt enabled, request an interrupt chn.intr.irq(); } // last channel doesn't have a ZCTO pin if (chn_index < 3) { // set ZCTO pin pins |= ZCTO0 << chn_index; } // reload down counter chn.down_counter = chn.constant; return pins; } //== TESTS ===================================================================== const expect = @import("std").testing.expect; test "ctc intvector" { var ctc = CTC{ }; var pins = setData(0, 0xE0); pins = ctc.ioWrite(0, pins); try expect(0xE0 == ctc.channels[0].intr.vector); try expect(0xE2 == ctc.channels[1].intr.vector); try expect(0xE4 == ctc.channels[2].intr.vector); try expect(0xE6 == ctc.channels[3].intr.vector); } test "ctc timer" { var ctc = CTC{}; var pins: u64 = 0; const chn = &ctc.channels[1]; // write control word const ctrl = Ctrl.EI|Ctrl.MODE_TIMER|Ctrl.PRESCALER_16|Ctrl.TRIGGER_AUTO|Ctrl.CONST_FOLLOWS|Ctrl.CONTROL; pins = setData(pins, ctrl); pins = ctc.ioWrite(1, pins); try expect(ctrl == ctc.channels[1].control); // write timer constant pins = setData(pins, 10); pins = ctc.ioWrite(1, pins); try expect(0 == (chn.control & Ctrl.CONST_FOLLOWS)); try expect(10 == chn.constant); try expect(10 == chn.down_counter); var r: usize = 0; while (r < 3): (r += 1) { var i: usize = 0; while (i < 160): (i += 1) { pins = ctc.tick(pins); if (i != 159) { try expect(0 == (pins & ZCTO1)); } } try expect(0 != (pins & ZCTO1)); try expect(10 == chn.down_counter); } } test "ctc timer wait trigger" { var ctc = CTC{}; var pins: u64 = 0; const chn = &ctc.channels[1]; // enable interrupt, mode timer, prescaler 16, trigger-wait, trigger-rising-edge, const follows const ctrl = Ctrl.EI|Ctrl.MODE_TIMER|Ctrl.PRESCALER_16|Ctrl.TRIGGER_WAIT|Ctrl.EDGE_RISING|Ctrl.CONST_FOLLOWS|Ctrl.CONTROL; pins = setData(pins, ctrl); pins = ctc.ioWrite(1, pins); try expect(chn.control == ctrl); // write timer constant pins = setData(pins, 10); pins = ctc.ioWrite(1, pins); try expect(0 == (chn.control & Ctrl.CONST_FOLLOWS)); try expect(10 == chn.constant); // tick the CTC without starting the timer { var i: usize = 0; while (i < 300): (i += 1) { pins = ctc.tick(pins); try expect(0 == (pins & ZCTO1)); } } // now start the timer on next tick pins |= CLKTRG1; pins = ctc.tick(pins); var r: usize = 0; while (r < 3): (r += 1) { var i: usize = 0; while (i < 160): (i += 1) { pins = ctc.tick(pins); if (i != 159) { try expect(0 == (pins & ZCTO1)); } else { try expect(0 != (pins & ZCTO1)); try expect(10 == chn.down_counter); } } } } test "ctc counter" { var ctc = CTC{}; var pins: u64 = 0; const chn = &ctc.channels[1]; // enable interrupt, mode counter, trigger-rising-edge, const follows const ctrl = Ctrl.EI|Ctrl.MODE_COUNTER|Ctrl.EDGE_RISING|Ctrl.CONST_FOLLOWS|Ctrl.CONTROL; pins = setData(pins, ctrl); pins = ctc.ioWrite(1, pins); try expect(ctc.channels[1].control == ctrl); // write counter constant pins = setData(pins, 10); pins = ctc.ioWrite(1, pins); try expect(0 == (chn.control & Ctrl.CONST_FOLLOWS)); try expect(10 == chn.constant); // trigger the CLKTRG1 pin var r: usize = 0; while (r < 3): (r += 1) { var i: usize = 0; while (i < 10): (i += 1) { pins |= CLKTRG1; pins = ctc.tick(pins); if (i != 9) { try expect(0 == (pins & ZCTO1)); } else { try expect(0 != (pins & ZCTO1)); try expect(10 == chn.down_counter); } pins &= ~CLKTRG1; pins = ctc.tick(pins); } } }
src/emu/CTC.zig
const std = @import("std"); const Memory = @This(); pages: std.ArrayListUnmanaged(*[65536]u8), allocator: *std.mem.Allocator, context: ?*c_void, const page_size = 65536; pub fn init(allocator: *std.mem.Allocator, context: ?*c_void, initial_pages: u16) !Memory { var result = Memory{ .allocator = allocator, .pages = .{}, .context = context }; try result.grow(initial_pages); return result; } pub fn deinit(self: *Memory) void { for (self.pages.items) |page| { self.allocator.destroy(page); } self.pages.deinit(self.allocator); self.* = undefined; } pub fn pageCount(self: Memory) u16 { return @intCast(u16, self.pages.items.len); } pub fn ext(self: Memory, comptime T: type) *T { return @ptrCast(*T, @alignCast(@alignOf(T), self.context)); } pub fn grow(self: *Memory, additional_pages: u16) !void { const new_page_count = self.pageCount() + additional_pages; if (new_page_count > 65536) { return error.OutOfMemory; } try self.pages.ensureCapacity(self.allocator, new_page_count); var i: u16 = 0; while (i < additional_pages) : (i += 1) { const page = try self.allocator.alloc(u8, page_size); self.pages.appendAssumeCapacity(@ptrCast(*[page_size]u8, page.ptr)); } } pub fn load(self: Memory, comptime T: type, start: u32, offset: u32) !T { const Int = std.meta.Int(.unsigned, @bitSizeOf(T)); const idx = try std.math.add(u32, start, offset); const bytes = try self.pageChunk(idx); // TODO: handle split byte boundary return @bitCast(T, std.mem.readIntLittle(Int, bytes[0..@sizeOf(T)])); } pub fn store(self: Memory, comptime T: type, start: u32, offset: u32, value: T) !void { const Int = std.meta.Int(.unsigned, @bitSizeOf(T)); const idx = try std.math.add(u32, start, offset); const bytes = try self.pageChunk(idx); // TODO: handle split byte boundary std.mem.writeIntLittle(Int, bytes[0..@sizeOf(T)], @bitCast(Int, value)); } fn pageChunk(self: Memory, idx: u32) ![]u8 { const page_num = idx / page_size; const offset = idx % page_size; if (page_num >= self.pageCount()) { std.log.info("{} > {}", .{ page_num, self.pageCount() }); return error.OutOfBounds; } const page = self.pages.items[page_num]; return page[offset..]; } pub fn get(self: Memory, ptr: anytype) !@TypeOf(ptr).Pointee { return self.load(@TypeOf(ptr).Pointee, @enumToInt(ptr), 0); } pub fn iterBytes(self: Memory, ptr: P(u8), size: u32) ByteIterator { return .{ .memory = self, .ptr = ptr, .remaining = size, }; } const ByteIterator = struct { memory: Memory, ptr: P(u8), remaining: u32, pub fn next(iter: *ByteIterator) !?[]u8 { if (iter.remaining == 0) { return null; } const bytes = try iter.memory.pageChunk(@enumToInt(iter.ptr)); const size = @intCast(u17, bytes.len); if (size >= iter.remaining) { defer iter.remaining = 0; return bytes[0..iter.remaining]; } else { iter.remaining -= size; iter.ptr = try iter.ptr.add(size); return bytes; } } }; pub fn set(self: Memory, ptr: anytype, value: @TypeOf(ptr).Pointee) !void { return self.store(@TypeOf(ptr).Pointee, @enumToInt(ptr), 0, value); } pub fn setMany(self: Memory, ptr: anytype, values: []const @TypeOf(ptr).Pointee) !void { for (values) |value, i| { try self.set(try ptr.add(@intCast(u32, i)), value); } } pub fn P(comptime T: type) type { return enum(u32) { _, const Self = @This(); pub const Pointee = T; pub const stride = @sizeOf(T); pub fn init(addr: u32) Self { return @intToEnum(Self, addr); } pub fn add(self: Self, change: u32) !Self { return init(try std.math.add(u32, @enumToInt(self), try std.math.mul(u32, change, stride))); } pub fn sub(self: Self, change: u32) !Self { return init(try std.math.sub(u32, @enumToInt(self), try std.math.mul(u32, change, stride))); } }; } test "grow" { var mem = try Memory.init(std.testing.allocator, null, 1); defer mem.deinit(); try std.testing.expectEqual(@as(u16, 1), mem.pageCount()); try mem.grow(1); try std.testing.expectEqual(@as(u16, 2), mem.pageCount()); } test "get/set" { var mem = try Memory.init(std.testing.allocator, null, 1); defer mem.deinit(); try std.testing.expectEqual(@as(u16, 1), mem.pageCount()); const ptr1 = P(u32).init(1234); const ptr2 = P(u32).init(4321); try mem.set(ptr1, 69); try mem.set(ptr2, 420); try std.testing.expectEqual(@as(u32, 69), try mem.get(ptr1)); try std.testing.expectEqual(@as(u32, 420), try mem.get(ptr2)); }
src/Memory.zig
const std = @import("std"); const alka = @import("alka.zig"); const m = alka.math; const utils = @import("core/utils.zig"); const UniqueList = utils.UniqueList; const alog = std.log.scoped(.alka_gui); /// Error Set pub const Error = error{ GUIisAlreadyInitialized, GUIisNotInitialized, InvalidCanvasID } || alka.Error; pub const Events = struct { pub const State = enum { none, entered, onhover, exited }; state: State = State.none, update: ?fn (self: *Element, deltatime: f32) anyerror!void = null, fixed: ?fn (self: *Element, fixedtime: f32) anyerror!void = null, draw: ?fn (self: *Element) anyerror!void = null, onCreate: ?fn (self: *Element) anyerror!void = null, onDestroy: ?fn (self: *Element) anyerror!void = null, onEnter: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f) anyerror!void = null, onHover: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f) anyerror!void = null, /// State does not matter onClick: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) anyerror!void = null, onPressed: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) anyerror!void = null, onDown: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) anyerror!void = null, onReleased: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f, button: alka.input.Mouse) anyerror!void = null, onExit: ?fn (self: *Element, position: m.Vec2f, relativepos: m.Vec2f) anyerror!void = null, }; pub const Element = struct { id: ?u64 = null, transform: m.Transform2D = undefined, colour: alka.Colour = undefined, events: Events = Events{}, /// Initializes the element /// DO NOT USE MANUALLY pub fn init(id: u64, tr: m.Transform2D, colour: alka.Colour) Element { return Element{ .id = id, .transform = tr, .colour = colour, }; } /// Deinitializes the element /// DO NOT USE MANUALLY pub fn deinit(self: *Element) void { self.id = null; } }; const Canvas = struct { const CElement = struct { element: Element = undefined, original_transform: m.Transform2D = undefined, }; /// Iterator pub const Iterator = struct { parent: *Canvas = undefined, index: usize = undefined, pub fn next(it: *Iterator) ?*Element { if (it.index >= it.parent.elements.items.len) return null; var result = &it.parent.elements.items[it.index]; it.index += 1; return if (result.data != null and result.data.?.element.id != null) &result.data.?.element else null; } /// Reset the iterator pub fn reset(it: *Iterator) void { it.index = 0; } }; alloc: *std.mem.Allocator = undefined, id: ?u64 = null, transform: m.Transform2D = undefined, colour: alka.Colour = undefined, elements: UniqueList(CElement) = undefined, fn calculateElementTransform(canvas: m.Transform2D, tr: m.Transform2D) m.Transform2D { const newpos = canvas.getOriginated().add(tr.getOriginated()); const newsize = tr.size; const newrot: f32 = canvas.rotation + tr.rotation; return m.Transform2D{ .position = newpos, .size = newsize, .rotation = newrot }; } /// Initializes the canvas pub fn init(alloc: *std.mem.Allocator, id: u64, tr: m.Transform2D, colour: alka.Colour) Error!Canvas { return Canvas{ .alloc = alloc, .id = id, .transform = tr, .colour = colour, .elements = try UniqueList(CElement).init(alloc, 1), }; } /// Deinitializes the canvas /// also destroys the elements /// can return `anyerror` pub fn deinit(self: *Canvas) !void { var it = self.elements.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var element = &self.elements.items[it.index - 1].data.?.element; if (element.events.onDestroy) |fun| try fun(element); element.deinit(); } } self.elements.deinit(); self.id = null; } /// Is the given transform inside of the canvas? pub fn isInside(self: Canvas, tr: m.Transform2D) bool { const otr = self.transform; const o0 = tr.getOriginated(); const o1 = otr.getOriginated(); const b0 = o0.x < o1.x + otr.size.x; const b1 = o0.y < o1.y + otr.size.y; const b2 = o0.x + tr.size.x > o1.x; const b3 = o0.y + tr.size.y > o1.y; return b0 and b1 and b2 and b3; } /// Creates a element /// NOTE: If element is not inside the canvas, it'll not /// call these for that element: update, fixed, draw /// can return `anyerror` pub fn createElement(self: *Canvas, id: u64, transform: m.Transform2D, colour: alka.Colour, events: Events) !*Element { var element = Element.init( id, calculateElementTransform(self.transform, transform), colour, ); element.events = events; try self.elements.append(id, CElement{ .element = element, .original_transform = transform }); var ptr = try self.elements.getPtr(id); if (ptr.element.events.onCreate) |fun| try fun(&ptr.element); return &ptr.element; } /// Returns the READ-ONLY element pub fn getElement(self: Canvas, id: u64) Error!Element { const con = try self.elements.get(id); return con.element; } /// Returns the MUTABLE element pub fn getElementPtr(self: *Canvas, id: u64) Error!*Element { var ptr = try self.elements.getPtr(id); return &ptr.element; } /// Destroys a element /// can return `anyerror` pub fn destroyElement(self: *Canvas, id: u64) !void { var element = try self.elements.getPtr(id); if (element.element.events.onDestroy) |fun| try fun(&element.element); element.element.deinit(); if (!self.elements.remove(id)) return Error.InvalidCanvasID; } /// Update the canvas /// can return `anyerror` pub fn update(self: Canvas, dt: f32) !void { var mlist: [alka.input.Info.max_mouse_count]alka.input.Info.BindingManager = undefined; var mlist_index: u8 = 0; { var i: u8 = 0; while (i < alka.input.Info.max_mouse_count) : (i += 1) { var l = alka.getInput().mouse_list[i]; if (l.mouse != .Invalid) { mlist[mlist_index] = l; mlist_index += 1; } } } const cam = alka.getCamera2DPushed(); const mpos = alka.getMousePosition(); //const mpos = cam.worldToScreen(alka.getMousePosition()); //alog.debug("mpos: {d:.0}:{d:.0}", .{ mpos.x, mpos.y }); var it = self.elements.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var celement = &self.elements.items[it.index - 1].data.?; var element = &celement.element; if (element.events.update) |fun| try fun(element, dt); element.transform = calculateElementTransform(self.transform, celement.original_transform); if (!self.isInside(element.transform)) continue; const tr = element.transform; const pos = cam.worldToScreen(tr.getOriginated()); const size = cam.worldToScreen(tr.size); //alog.debug("pos: {d:.0}:{d:.0}", .{ pos.x, pos.y }); const aabb = blk: { const rect = m.Rectangle{ .position = pos, .size = size, }; const res = rect.aabb( m.Rectangle{ .position = mpos, .size = m.Vec2f{ .x = 2, .y = 2 }, }, ); break :blk res; }; const mrpos = blk: { var mp = m.Vec2f.sub(mpos, pos); if (mp.x < 0) mp.x = 0; if (mp.y < 0) mp.y = 0; break :blk mp; }; switch (element.events.state) { Events.State.none => { if (aabb) { element.events.state = .entered; } }, Events.State.entered => { if (element.events.onEnter) |fun| try fun(element, mpos, mrpos); element.events.state = .onhover; }, Events.State.onhover => { if (!aabb) { element.events.state = .exited; } else { if (element.events.onHover) |fun| try fun(element, mpos, mrpos); var i: u8 = 0; while (i < mlist_index) : (i += 1) { var l = alka.getInput().mouse_list[i]; if (l.mouse != .Invalid) { switch (l.status) { .none => {}, .pressed => { if (element.events.onClick) |mfun| try mfun(element, mpos, mrpos, l.mouse); if (element.events.onPressed) |mfun| try mfun(element, mpos, mrpos, l.mouse); }, .down => { if (element.events.onClick) |mfun| try mfun(element, mpos, mrpos, l.mouse); if (element.events.onDown) |mfun| try mfun(element, mpos, mrpos, l.mouse); }, .released => { if (element.events.onClick) |mfun| try mfun(element, mpos, mrpos, l.mouse); if (element.events.onReleased) |mfun| try mfun(element, mpos, mrpos, l.mouse); }, } } } } }, Events.State.exited => { if (element.events.onExit) |fun| try fun(element, mpos, mrpos); element.events.state = .none; }, } } } } /// (fixed) Update the canvas /// can return `anyerror` pub fn fixed(self: Canvas, dt: f32) !void { var it = self.elements.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var celement = &self.elements.items[it.index - 1].data.?; var element = &celement.element; if (element.events.fixed) |fun| try fun(element, dt); element.transform = calculateElementTransform(self.transform, celement.original_transform); if (!self.isInside(element.transform)) continue; } } } /// Draw the canvas /// can return `anyerror` pub fn draw(self: Canvas) !void { var it = self.elements.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var celement = &self.elements.items[it.index - 1].data.?; var element = &celement.element; element.transform = calculateElementTransform(self.transform, celement.original_transform); if (!self.isInside(element.transform)) continue; if (element.events.draw) |fun| try fun(element); } } return alka.drawRectangleAdv( self.transform.getRectangleNoOrigin(), self.transform.origin, m.deg2radf(self.transform.rotation), self.colour, ); } /// Draw the canvas lines pub fn drawLines(self: Canvas, col: alka.Colour) Error!void { return alka.drawRectangleLinesAdv( self.transform.getRectangleNoOrigin(), self.transform.origin, m.deg2radf(self.transform.rotation), col, ); } /// Returns the original transform of the element /// NOTE: READ-ONLY pub fn getTransform(self: Canvas, id: u64) Error!m.Transform2D { const con = try self.elements.get(id); return con.original_transform; } /// Returns the original transform of the element /// NOTE: MUTABLE pub fn getTransformPtr(self: *Canvas, id: u64) Error!*m.Transform2D { var ptr = try self.elements.getPtr(id); return &ptr.original_transform; } /// Returns the iterator pub fn iterator(self: *Canvas) Iterator { return Iterator{ .parent = self, .index = 0, }; } }; const Private = struct { const CCanvas = struct { canvas: Canvas = undefined, original_transform: m.Transform2D = undefined, }; alloc: *std.mem.Allocator = undefined, canvas: UniqueList(CCanvas) = undefined, is_initialized: bool = false, }; var p = Private{}; /// Initializes the GUI interface pub fn init(alloc: *std.mem.Allocator) Error!void { if (p.is_initialized) return Error.GUIisAlreadyInitialized; p.alloc = alloc; p.canvas = try UniqueList(Private.CCanvas).init(p.alloc, 0); p.is_initialized = true; alog.info("fully initialized!", .{}); } /// Deinitializes the GUI interface /// also destroys the elements /// can return `anyerror` pub fn deinit() !void { if (!p.is_initialized) return Error.GUIisNotInitialized; var it = p.canvas.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var canvas = &p.canvas.items[it.index - 1].data.?.canvas; try canvas.deinit(); } } p.canvas.deinit(); p = Private{}; p.is_initialized = false; alog.info("fully deinitialized!", .{}); } /// Creates a canvas pub fn createCanvas(id: u64, tr: m.Transform2D, col: alka.Colour) Error!*Canvas { if (!p.is_initialized) return Error.GUIisNotInitialized; var canvas = try Canvas.init(p.alloc, id, tr, col); try p.canvas.append(id, Private.CCanvas{ .canvas = canvas, .original_transform = tr }); var ptr = try p.canvas.getPtr(id); return &ptr.canvas; } /// Returns the READ-ONLY canvas pub fn getCanvas(id: u64) Error!Canvas { if (!p.is_initialized) return Error.GUIisNotInitialized; const con = try p.canvas.get(id); return con.canvas; } /// Returns the MUTABLE canvas pub fn getCanvasPtr(id: u64) Error!*Canvas { if (!p.is_initialized) return Error.GUIisNotInitialized; var ptr = try p.canvas.getPtr(id); return &ptr.canvas; } /// Destroys a canvas /// can return `anyerror` pub fn destroyCanvas(id: u64) !void { if (!p.is_initialized) return Error.GUIisNotInitialized; var ptr = try p.canvas.getPtr(id); var canvas = &ptr.canvas; try canvas.deinit(); if (!p.canvas.remove(id)) return Error.InvalidCanvasID; } /// Update the canvases /// can return `anyerror` pub fn update(dt: f32) !void { var it = p.canvas.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var canvas = &p.canvas.items[it.index - 1].data.?.canvas; if (canvas.id != null) try canvas.update(dt); } } } /// (fixed) Update the canvases /// can return `anyerror` pub fn fixed(dt: f32) !void { var it = p.canvas.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var canvas = &p.canvas.items[it.index - 1].data.?.canvas; if (canvas.id != null) try canvas.fixed(dt); } } } /// Draw the canvases /// can return `anyerror` pub fn draw() !void { var it = p.canvas.iterator(); while (it.next()) |entry| { if (entry.data != null) { // .next() increases the index by 1 // so we need '- 1' to get the current entry var canvas = &p.canvas.items[it.index - 1].data.?.canvas; if (canvas.id != null) try canvas.draw(); } } }
src/gui.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const assert = std.debug.assert; const testing = std.testing; const mustache = @import("../mustache.zig"); const TemplateOptions = mustache.options.TemplateOptions; const ref_counter = @import("ref_counter.zig"); const File = std.fs.File; pub fn FileReader(comptime options: TemplateOptions) type { const read_buffer_size = switch (options.source) { .Stream => |stream| stream.read_buffer_size, .String => return void, }; const RefCounter = ref_counter.RefCounter(options); const RefCountedSlice = ref_counter.RefCountedSlice(options); return struct { const Self = @This(); pub const OpenError = std.fs.File.OpenError; pub const Error = Allocator.Error || std.fs.File.ReadError; file: File, eof: bool = false, pub fn init(absolute_path: []const u8) OpenError!Self { var file = try std.fs.openFileAbsolute(absolute_path, .{}); return Self{ .file = file, }; } pub fn read(self: *Self, allocator: Allocator, prepend: []const u8) Error!RefCountedSlice { var buffer = try allocator.alloc(u8, read_buffer_size + prepend.len); errdefer allocator.free(buffer); if (prepend.len > 0) { std.mem.copy(u8, buffer, prepend); } var size = try self.file.read(buffer[prepend.len..]); if (size < read_buffer_size) { const full_size = prepend.len + size; assert(full_size < buffer.len); buffer = allocator.shrink(buffer, full_size); self.eof = true; } else { self.eof = false; } return RefCountedSlice{ .slice = buffer, .ref_counter = try RefCounter.create(allocator, buffer), }; } pub fn deinit(self: *Self) void { self.file.close(); } pub inline fn finished(self: *Self) bool { return self.eof; } }; } test "FileReader.Slices" { const allocator = testing.allocator; // Test the FileReader slicing mechanism // In a real use case, the read_buffer_len is much larger than the amount needed to produce a token // So we can parse many tokens on a single read, and read a new slice containing only the last unparsed bytes // // Just 5 chars in our test const SlicedReader = FileReader(.{ .source = .{ .Stream = .{ .read_buffer_size = 5 } }, .output = .Parse }); // // Block index // First slice | Second slice // Block index | | | Third slice // ↓ ↓ ↓ ↓ ↓ const content_text = "{{name}}Just static"; // Creating a temp file const path = try std.fs.selfExeDirPathAlloc(allocator); defer allocator.free(path); const absolute_file_path = try std.fs.path.join(allocator, &.{ path, "file_reader_slices.tmp" }); defer allocator.free(absolute_file_path); var file = try std.fs.createFileAbsolute(absolute_file_path, .{ .truncate = true }); try file.writeAll(content_text); file.close(); defer std.fs.deleteFileAbsolute(absolute_file_path) catch {}; var reader = try SlicedReader.init(absolute_file_path); defer reader.deinit(); var slice: []const u8 = &.{}; try testing.expectEqualStrings("", slice); // First read // We got a slice with "read_buffer_len" size to parse var result_1 = try reader.read(allocator, slice); defer result_1.ref_counter.unRef(allocator); slice = result_1.slice; try testing.expectEqual(false, reader.finished()); try testing.expectEqual(@as(usize, 5), slice.len); try testing.expectEqualStrings("{{nam", slice); // Second read, // The parser produces the first token "{{" and reaches the EOF of this slice // We need more data, the previous slice was parsed until the block_index = 2, // so we expect the next read to return the remaining bytes plus new 5 bytes read var result_2 = try reader.read(allocator, slice[2..]); defer result_2.ref_counter.unRef(allocator); slice = result_2.slice; try testing.expectEqual(false, reader.finished()); try testing.expectEqualStrings("name}}Ju", slice); // Third read, // We parsed a next token '}}' at block_index = 6, // so we need another slice var result_3 = try reader.read(allocator, slice[6..]); defer result_3.ref_counter.unRef(allocator); slice = result_3.slice; try testing.expectEqual(false, reader.finished()); try testing.expectEqualStrings("Just st", slice); // Last read, // Nothing was parsed, var result_4 = try reader.read(allocator, slice); defer result_4.ref_counter.unRef(allocator); slice = result_4.slice; try testing.expectEqual(true, reader.finished()); try testing.expectEqualStrings("Just static", slice); // After that, EOF var result_5 = try reader.read(allocator, slice); defer result_5.ref_counter.unRef(allocator); slice = result_5.slice; try testing.expectEqual(true, reader.finished()); try testing.expectEqualStrings("Just static", slice); }
src/parsing/file_reader.zig
const std = @import("std"); const builtin = @import("builtin"); const allocators = @import("allocators.zig"); const temp_alloc = allocators.temp_arena.allocator(); const languages = @import("languages.zig"); const lua = @import("lua.zig"); //[[!! quiet() fs.put_file_contents('limp.bc.lua', string.dump(load_file('limp.lua'))) !! 1 ]] const limp_core = @embedFile("limp.bc.lua"); pub const Section = struct { text: []const u8 = &[_]u8{}, indent: []const u8 = &[_]u8{}, newline_style: []const u8 = &[_]u8{}, limp_header: []const u8 = &[_]u8{}, raw_program: []const u8 = &[_]u8{}, clean_program: []const u8 = &[_]u8{}, limp_footer: []const u8 = &[_]u8{}, limp_output: []const u8 = &[_]u8{}, }; pub const ProcessResult = enum(u8) { up_to_date, modified, ignore, }; pub const Processor = struct { comment_tokens: languages.LangTokens, limp_tokens: languages.LangTokens, file_path: []const u8, file_contents: []const u8, parsed_sections: std.ArrayListUnmanaged(Section), processed_sections: std.ArrayListUnmanaged(Section), pub fn init(comment_tokens: languages.LangTokens, limp_tokens: languages.LangTokens) Processor { return Processor{ .comment_tokens = comment_tokens, .limp_tokens = limp_tokens, .file_path = &[_]u8{}, .file_contents = &[_]u8{}, .parsed_sections = std.ArrayListUnmanaged(Section){}, .processed_sections = std.ArrayListUnmanaged(Section){}, }; } fn countNewlines(buf: []const u8) i64 { var newline_count: i64 = 0; var search_start_loc: usize = 0; while (std.mem.indexOfAnyPos(u8, buf, search_start_loc, "\r\n")) |end_of_line| { if (std.mem.startsWith(u8, buf[end_of_line..], "\r\n")) { search_start_loc = end_of_line + 2; } else { search_start_loc = end_of_line + 1; } newline_count += 1; } return newline_count; } fn detectFileNewlineStyle(file_contents: []const u8) []const u8 { const min_lines_to_examine = 50; var search_start_loc: usize = 0; var num_cr: usize = 0; var num_lf: usize = 0; var num_crlf: usize = 0; while (true) { if (std.mem.indexOfAnyPos(u8, file_contents, search_start_loc, "\r\n")) |end_of_line| { if (std.mem.startsWith(u8, file_contents[end_of_line..], "\r\n")) { search_start_loc = end_of_line + 2; num_crlf += 1; if (num_crlf > min_lines_to_examine) { return "\r\n"; } } else if (file_contents[end_of_line] == '\n') { search_start_loc = end_of_line + 1; num_lf += 1; if (num_lf > min_lines_to_examine) { return "\n"; } } else { search_start_loc = end_of_line + 1; num_cr += 1; if (num_cr > min_lines_to_examine) { return "\n"; } } } else { if (num_lf == 0 and num_cr == 0 and num_crlf == 0) { return if (builtin.os.tag == .windows) "\r\n" else "\n"; } else if (num_lf >= num_cr) { if (num_lf >= num_crlf) { return "\n"; } else { return "\r\n"; } } else if (num_crlf >= num_cr) { return "\r\n"; } else { return "\r"; } } } } fn detectNewlineStyleAndIndent(section: *Section, file_newline_style: []const u8) void { if (std.mem.lastIndexOfAny(u8, section.text, "\r\n")) |end_of_line| { if (section.text[end_of_line] == '\n') { if (end_of_line > 0 and section.text[end_of_line - 1] == '\r') { section.newline_style = "\r\n"; } else { section.newline_style = "\n"; } } else { section.newline_style = "\r"; } section.indent = section.text[end_of_line + 1 ..]; } else { section.newline_style = file_newline_style; section.indent = section.text; } } fn parseRawProgram(section: *Section, newlines_seen: i64, full_line_prefix: []const u8) !i64 { var raw_program = section.raw_program; var remaining = try temp_alloc.alloc(u8, raw_program.len + @intCast(u64, newlines_seen) * section.newline_style.len); section.clean_program = remaining; const newline_style = section.newline_style; { // add newlines at the beginning so that lua will report the right line number var line: i64 = 0; while (line < newlines_seen) { std.mem.copy(u8, remaining, newline_style); remaining = remaining[newline_style.len..]; line += 1; } } var program_newlines: i64 = 0; while (std.mem.indexOfAny(u8, raw_program, "\r\n")) |end_of_line| { var start_of_line: usize = undefined; if (std.mem.startsWith(u8, raw_program[end_of_line..], "\r\n")) { start_of_line = end_of_line + 2; } else { start_of_line = end_of_line + 1; } std.mem.copy(u8, remaining, raw_program[0..start_of_line]); remaining = remaining[start_of_line..]; program_newlines += 1; raw_program = raw_program[start_of_line..]; if (section.indent.len == 0 or std.mem.startsWith(u8, raw_program, section.indent)) { if (std.mem.startsWith(u8, raw_program[section.indent.len..], full_line_prefix)) { raw_program = raw_program[(section.indent.len + full_line_prefix.len)..]; } } } std.mem.copy(u8, remaining, raw_program); remaining = remaining[raw_program.len..]; section.clean_program = section.clean_program[0 .. section.clean_program.len - remaining.len]; return program_newlines; } pub fn parse(self: *Processor, file_path: []const u8, file_contents: []const u8) !void { self.file_path = file_path; self.file_contents = file_contents; const file_newline_style = detectFileNewlineStyle(file_contents); const comment_opener = self.comment_tokens.opener; const comment_closer = self.comment_tokens.closer; const comment_line_prefix = self.comment_tokens.line_prefix; const limp_opener = self.limp_tokens.opener; const limp_closer = self.limp_tokens.closer; const limp_line_prefix = self.limp_tokens.line_prefix; var limp_header = try temp_alloc.alloc(u8, comment_opener.len + limp_opener.len); std.mem.copy(u8, limp_header, comment_opener); std.mem.copy(u8, limp_header[comment_opener.len..], limp_opener); var full_line_prefix = try temp_alloc.alloc(u8, comment_line_prefix.len + limp_line_prefix.len); std.mem.copy(u8, full_line_prefix, comment_line_prefix); std.mem.copy(u8, full_line_prefix[comment_line_prefix.len..], limp_line_prefix); var initial_bytes_of_closers = [2]u8{ limp_closer[0], comment_closer[0] }; var newlines_seen: i64 = 0; var remaining = file_contents; while (std.mem.indexOf(u8, remaining, limp_header)) |opener_loc| { var section = Section{}; section.text = remaining[0..opener_loc]; newlines_seen += countNewlines(section.text); detectNewlineStyleAndIndent(&section, file_newline_style); section.limp_header = limp_header; // find the end of the limp program, and parse the number of generated lines (if present) var closer_search_loc = opener_loc + limp_header.len; while (std.mem.indexOfAnyPos(u8, remaining, closer_search_loc, &initial_bytes_of_closers)) |potential_closer_loc| { var potential_closer = remaining[potential_closer_loc..]; if (std.mem.startsWith(u8, potential_closer, limp_closer)) { // next up should be the number of generated lines const limp_closer_loc = potential_closer_loc; const limp_closer_len = limp_closer.len; section.raw_program = remaining[opener_loc + limp_header.len .. limp_closer_loc]; newlines_seen += try parseRawProgram(&section, newlines_seen, full_line_prefix); if (std.mem.indexOfPos(u8, remaining, limp_closer_loc + limp_closer_len, comment_closer)) |closer_loc| { const output_loc = closer_loc + comment_closer.len; const line_count_loc = limp_closer_loc + limp_closer.len; const line_count_str_raw = remaining[line_count_loc..closer_loc]; newlines_seen += countNewlines(line_count_str_raw); const line_count_str = std.mem.trim(u8, line_count_str_raw, &std.ascii.spaces); var lines_remaining = std.fmt.parseUnsigned(i64, line_count_str, 0) catch 0; // TODO error message newlines_seen += lines_remaining; var end_loc = output_loc; while (lines_remaining > 0) : (lines_remaining -= 1) { if (std.mem.indexOfAnyPos(u8, remaining, end_loc, "\r\n")) |end_of_line| { if (std.mem.startsWith(u8, remaining[end_of_line..], "\r\n")) { end_loc = end_of_line + 2; } else { end_loc = end_of_line + 1; } } if (end_loc >= remaining.len) break; } section.limp_footer = remaining[limp_closer_loc..output_loc]; section.limp_output = remaining[output_loc..end_loc]; remaining = remaining[end_loc..]; } else { // EOF before closer was found - file truncation or corruption? section.limp_footer = remaining[limp_closer_loc..]; remaining = ""; } break; } else if (std.mem.startsWith(u8, potential_closer, comment_closer)) { // there are no generated lines const closer_loc = potential_closer_loc; const closer_len = comment_closer.len; section.raw_program = remaining[opener_loc + limp_header.len .. closer_loc]; newlines_seen += try parseRawProgram(&section, newlines_seen, full_line_prefix); section.limp_footer = remaining[closer_loc .. closer_loc + closer_len]; remaining = remaining[closer_loc + closer_len ..]; break; } else { closer_search_loc = potential_closer_loc + 1; } } else { // EOF before closer was found - file truncation or corruption? section.raw_program = remaining[opener_loc + limp_header.len ..]; newlines_seen += try parseRawProgram(&section, newlines_seen, full_line_prefix); remaining = ""; } try self.parsed_sections.append(temp_alloc, section); } if (remaining.len > 0) { try self.parsed_sections.append(temp_alloc, .{ .text = remaining }); } } pub fn isProcessable(self: *Processor) bool { switch (self.parsed_sections.items.len) { 2...std.math.maxInt(usize) => return true, 1 => return self.parsed_sections.items[0].limp_header.len > 0, else => return false, } } pub fn process(self: *Processor) !ProcessResult { const l = lua.State.init(); defer l.deinit(); return self.processInner(l) catch |err| switch (err) { error.LuaRuntimeError => { const msg = l.getString(1, "(trace not available)"); std.io.getStdErr().writer().print("{s}\n", .{msg}) catch {}; return .ignore; }, error.LuaSyntaxError => { const msg = l.getString(1, "(details not available)"); std.io.getStdErr().writer().print("{s}\n", .{msg}) catch {}; return .ignore; }, else => return err, }; } fn processInner(self: *Processor, l: lua.State) !ProcessResult { const initializers = [_]lua.c.lua_CFunction{ lua.registerStdLib, lua.fs.registerFsLib, lua.util.registerUtilLib, }; try l.callAll(&initializers); // belua::time_module, try l.setGlobalString("file_path", self.file_path); try l.setGlobalString("file_name", std.fs.path.basename(self.file_path)); try l.setGlobalString("file_dir", std.fs.path.dirname(self.file_path) orelse ""); //try l.setGlobalString("file_contents", self.file_contents); try l.setGlobalString("comment_begin", self.comment_tokens.opener); try l.setGlobalString("comment_end", self.comment_tokens.closer); try l.setGlobalString("comment_line_prefix", self.comment_tokens.line_prefix); try l.execute(limp_core, "@LIMP core"); try self.processed_sections.ensureTotalCapacity(temp_alloc, self.parsed_sections.items.len); self.processed_sections.items.len = 0; var modified = false; for (self.parsed_sections.items) |section, i| { if (section.limp_header.len == 0) { try self.processed_sections.append(temp_alloc, section); continue; } try l.setGlobalString("last_generated_data", section.limp_output); try l.setGlobalString("base_indent", section.indent); try l.setGlobalString("nl_style", section.newline_style); var limp_name = try std.fmt.allocPrintZ(temp_alloc, "@{s} LIMP {d}", .{ self.file_path, i }); try l.execute(section.clean_program, limp_name); try l.pushGlobal("_finish"); try l.call(0, 1); var raw_output = l.getString(-1, ""); l.setTop(0); // make sure output ends with a newline var output = try temp_alloc.alloc(u8, raw_output.len + section.newline_style.len); std.mem.copy(u8, output, raw_output); if (std.mem.endsWith(u8, raw_output, section.newline_style)) { output.len = raw_output.len; } else { std.mem.copy(u8, output[raw_output.len..], section.newline_style); } var line_count: i32 = 0; var search_start_loc: usize = 0; while (search_start_loc < output.len) { if (std.mem.indexOfAnyPos(u8, output, search_start_loc, "\r\n")) |end_of_line| { line_count += 1; if (std.mem.startsWith(u8, output[end_of_line..], "\r\n")) { search_start_loc = end_of_line + 2; } else { search_start_loc = end_of_line + 1; } } else break; } var limp_footer = try std.fmt.allocPrintZ(temp_alloc, "{s} {d} {s}", .{ self.limp_tokens.closer, line_count, self.comment_tokens.closer }); try self.processed_sections.append(temp_alloc, .{ .text = section.text, .indent = section.indent, .newline_style = section.newline_style, .limp_header = section.limp_header, .raw_program = section.raw_program, .clean_program = section.clean_program, .limp_footer = limp_footer, .limp_output = output, }); if (!modified and !std.mem.eql(u8, section.limp_output, output)) { modified = true; } } return if (modified) .modified else .up_to_date; // TODO depfile // if (!depfile_path_.empty()) { // SV write_depfile = "if write_depfile then write_depfile() end"sv; // context.execute(write_depfile, "@" + path_.filename().string() + " write depfile"); // } } pub fn write(self: *Processor, writer: std.fs.File.Writer) !void { for (self.processed_sections.items) |section| { try writer.writeAll(section.text); try writer.writeAll(section.limp_header); try writer.writeAll(section.raw_program); try writer.writeAll(section.limp_footer); try writer.writeAll(section.limp_output); } } };
limp/processor.zig
const std = @import("std"); const utils = @import("utils.zig"); const ID3 = @import("zid3.zig").ID3; const FrameTypes = union { text: TextFrame, link: UrlLinkFrame, comment: CommentFrame, }; pub const FrameHeader = struct { id: [4]u8, size: [4]u8, flags: [2]u8, content: []u8, const Self = @This(); fn parseFromID3(id3: *ID3) !?FrameHeader { var frame_header: [10]u8 = undefined; _ = try id3.file.read(frame_header[0..10]); var id = frame_header[0..4].*; var size = frame_header[4..8].*; var flags = frame_header[8..10].*; const content = try id3.allocator.alloc(u8, utils.bytesToInt(u32, &size)); _ = try id3.file.read(content); return switch (id[0]) { 'T', 'W', 'C', 'A', 'P' => FrameHeader{ .id = id, .size = size, .flags = flags, .content = content, }, else => null, }; } pub fn getTextFrame(self: *const Self) TextFrame { return .{ .encoding = self.content[0], .information = self.content[1..], }; } pub fn getFrame(self: *const Self) FrameTypes { return switch (self.id[0]) { 'T' => getTextFrame(), else => unreachable, }; } }; pub const FrameHeaderList = struct { allocator: *std.mem.Allocator, inner_list: std.ArrayList(FrameHeader), const Self = @This(); pub fn init(allocator: *std.mem.Allocator) FrameHeaderList { return .{ .allocator = allocator, .inner_list = std.ArrayList(FrameHeader).init(allocator), }; } pub fn parseFromID3(id3: *ID3) !FrameHeaderList { var frame_headers = FrameHeaderList.init(id3.allocator); const end_position = utils.bytesToInt(u24, &id3.header.size); var current_position = try id3.file.getPos(); while (current_position < end_position) : (current_position = try id3.file.getPos()) { const frame_header = try FrameHeader.parseFromID3(id3); if (frame_header != null) try frame_headers.inner_list.append(frame_header.?); } return frame_headers; } pub fn deinit(self: *Self) void { for (self.inner_list.items) |frame_header| { self.allocator.free(frame_header.content); } self.inner_list.deinit(); } }; const TextFrame = struct { encoding: u8, information: []u8, }; const UrlLinkFrame = struct { url: []u8 }; const CommentFrame = struct { encoding: u8, language: [3]u8, //Short content descrip. <text string according to encoding> $00 (00) description: []u8, //The actual text <full text string according to encoding> text: []u8, }; const PictureFrame = struct { encoding: u8, mime_type: []u8, picture_type: u8, description: []u8, picture_data: []u8, };
src/frames.zig
const std = @import("std"); const expect = std.testing.expect; pub const DynamicInput = struct { time: f32, value: f32, }; pub const SimInputs = struct { time_slice_length: f32, starting_temp: f32, set_point_temp: f32, cold_water_temp: f32, solar_irradiance: []DynamicInput, stc_panel_area: f32, stc_panel_count: u32, stc_efficiency: f32, specific_heat: f32, aux_heat_power: []DynamicInput, aux_efficiency: f32, hot_water_demand: []DynamicInput, tank_volume: u32, tank_loss_coefficient: f32, end_time: f32, }; pub const TimeTemp = struct { time: f32, temp: f32, }; // This struct keeps track of state associated with the // dynamic input lists const Slicer = struct { const Self = @This(); cur_time: f32, cur_val: f32, index: u32, arr: []DynamicInput, time_slice: f32, pub fn init(arr: []DynamicInput, time_slice: f32) Self { return Self{ .cur_time = 0, .cur_val = arr[0].value, .index = 1, .arr = arr, .time_slice = time_slice, }; } // This function returns the aggregate of 'value x time' // through the whole time slice. There may be multiple // values that span a single time slice, or one value may // span the whole slice. pub fn getNextSlice(self: *Slicer) f32 { var total: f32 = 0; var prev_time = self.cur_time; var end_time = self.cur_time + self.time_slice; while (self.arr.len > self.index and self.arr[self.index].time <= end_time) : (self.index += 1) { // Advance the current time self.cur_time = self.arr[self.index].time; // Add the value up to the current time total += (self.cur_time - prev_time) * self.cur_val; // Advance the value and update prev_time self.cur_val = self.arr[self.index].value; prev_time = self.cur_time; } if (self.cur_time < end_time) { total += (end_time - self.cur_time) * self.cur_val; self.cur_time = end_time; } return total; } }; fn calcTemp( inputs: SimInputs, prev_temp: f32, irradiance_slicer: *Slicer, power_slicer: *Slicer, demand_slicer: *Slicer ) f32 { const loss_percent = inputs.tank_loss_coefficient * inputs.time_slice_length; const p1 = (1 - loss_percent) * prev_temp; // The 'dt' value is included in the slicer calculation const qs = irradiance_slicer.getNextSlice() * inputs.stc_efficiency * inputs.stc_panel_area * @intToFloat(f32, inputs.stc_panel_count); const qh = inputs.aux_efficiency * power_slicer.getNextSlice(); const p2 = (qs + qh) / (inputs.specific_heat * @intToFloat(f32, inputs.tank_volume)); const delta_temp = inputs.set_point_temp - inputs.cold_water_temp; const demand = demand_slicer.getNextSlice(); const p3 = (delta_temp * demand) / @intToFloat(f32, inputs.tank_volume); return p1 + p2 - p3; } fn inRange(num: f32, low: f32, high: f32) bool { return num >= low and num <= high; } pub fn simulate(inputs: SimInputs, allocator: *std.mem.Allocator) ![]TimeTemp { // Check inputs try expect(inputs.set_point_temp >= inputs.cold_water_temp); try expect(inputs.end_time >= inputs.time_slice_length); try expect(inRange(inputs.stc_efficiency, 0, 1)); try expect(inRange(inputs.aux_efficiency, 0, 1)); try expect(inRange(inputs.tank_loss_coefficient, 0, 1)); try expect(inputs.time_slice_length > 0); try expect(inputs.solar_irradiance.len > 0); try expect(inputs.solar_irradiance[0].time == 0.0); try expect(inputs.aux_heat_power.len > 0); try expect(inputs.aux_heat_power[0].time == 0.0); try expect(inputs.hot_water_demand.len > 0); try expect(inputs.hot_water_demand[0].time == 0.0); var output = std.ArrayList(TimeTemp).init(allocator); // The starting time is always 0 try output.append(TimeTemp{ .time = 0.0, .temp = inputs.starting_temp }); var irradiance_slicer = Slicer.init(inputs.solar_irradiance, inputs.time_slice_length); var power_slicer = Slicer.init(inputs.aux_heat_power, inputs.time_slice_length); var demand_slicer = Slicer.init(inputs.hot_water_demand, inputs.time_slice_length); var cur_time: f32 = inputs.time_slice_length; var prev_temp: f32 = inputs.starting_temp; // TODO: Because of inaccuracies in floating point arithmetic, // the 'cur_time' will be slightly over 'end_time' when they // should be equal. while (cur_time <= inputs.end_time) : (cur_time += inputs.time_slice_length) { const temp = calcTemp(inputs, prev_temp, &irradiance_slicer, &power_slicer, &demand_slicer); try output.append(TimeTemp{ .time = cur_time, .temp = temp, }); prev_temp = temp; } // No need for deinit() because the caller now owns this return output.toOwnedSlice(); } // Tests var test_irradiance = [_]DynamicInput{ DynamicInput{ .time = 0, .value = 1.361 } }; var test_power = [_]DynamicInput{ DynamicInput{ .time = 0, .value = 0 } }; var test_demand = [_]DynamicInput{ DynamicInput{ .time = 0, .value = 500 } }; const test_inputs = SimInputs{ .time_slice_length = 0.1, .starting_temp = 60, .set_point_temp = 60, .cold_water_temp = 10, .solar_irradiance = test_irradiance[0..], .stc_panel_area = 3, .stc_panel_count = 100, .stc_efficiency = 0.5, .specific_heat = 0.0012, .aux_heat_power = test_power[0..], .aux_efficiency = 0.75, .hot_water_demand = test_demand[0..], .tank_volume = 10000, .tank_loss_coefficient = 0.001, .end_time = 1, }; const test_allocator = std.testing.allocator; test "basic inputs" { var inputs = test_inputs; const output = try simulate(inputs, test_allocator); defer test_allocator.free(output); try expect(output[0].temp == 60.0); try expect(output[1].temp == 61.445248); try expect(output[9].temp == 73.002037); } test "smaller interval than time slice" { var inputs = test_inputs; var demand = [_]DynamicInput{ DynamicInput{ .time = 0, .value = 100 }, DynamicInput{ .time = 0.025, .value = 200 }, DynamicInput{ .time = 0.05, .value = 500 }, DynamicInput{ .time = 0.10, .value = 1000 }, }; inputs.hot_water_demand = demand[0..]; const output = try simulate(inputs, test_allocator); defer test_allocator.free(output); try expect(output[0].temp == 60.0); try expect(output[1].temp == 61.532749); try expect(output[9].temp == 71.090156); } test "different irradiance values" { var inputs = test_inputs; var irradiance = [_]DynamicInput{ DynamicInput{ .time = 0.0, .value = 0.500 }, DynamicInput{ .time = 0.1, .value = 0.635 }, DynamicInput{ .time = 0.2, .value = 0.723 }, DynamicInput{ .time = 0.3, .value = 0.811 }, DynamicInput{ .time = 0.4, .value = 0.976 }, DynamicInput{ .time = 0.5, .value = 1.034 }, DynamicInput{ .time = 0.6, .value = 0.976 }, DynamicInput{ .time = 0.7, .value = 0.811 }, DynamicInput{ .time = 0.2, .value = 0.723 }, DynamicInput{ .time = 0.1, .value = 0.635 }, }; inputs.solar_irradiance = irradiance[0..]; const output = try simulate(inputs, test_allocator); defer test_allocator.free(output); try expect(output[0].temp == 60.0); try expect(output[1].temp == 60.368999); try expect(output[3].temp == 61.554371); try expect(output[5].temp == 63.275730); try expect(output[7].temp == 64.065475); try expect(output[9].temp == 65.140099); } test "using the auxiliary water heater" { var inputs = test_inputs; var power = [_]DynamicInput{ DynamicInput{ .time = 0.0, .value = 100 }, }; inputs.aux_heat_power = power[0..]; const output = try simulate(inputs, test_allocator); defer test_allocator.free(output); try expect(output[0].temp == 60.0); try expect(output[1].temp == 62.070248); try expect(output[5].temp == 70.349167); try expect(output[9].temp == 78.624779); } test "smaller tank" { var inputs = test_inputs; inputs.tank_volume = 5000; const output = try simulate(inputs, test_allocator); defer test_allocator.free(output); try expect(output[0].temp == 60.0); try expect(output[1].temp == 62.896500); try expect(output[6].temp == 77.374649); try expect(output[9].temp == 86.058060); }
src/simulator.zig
pub const WNODE_FLAG_ALL_DATA = @as(u32, 1); pub const WNODE_FLAG_SINGLE_INSTANCE = @as(u32, 2); pub const WNODE_FLAG_SINGLE_ITEM = @as(u32, 4); pub const WNODE_FLAG_EVENT_ITEM = @as(u32, 8); pub const WNODE_FLAG_FIXED_INSTANCE_SIZE = @as(u32, 16); pub const WNODE_FLAG_TOO_SMALL = @as(u32, 32); pub const WNODE_FLAG_INSTANCES_SAME = @as(u32, 64); pub const WNODE_FLAG_STATIC_INSTANCE_NAMES = @as(u32, 128); pub const WNODE_FLAG_INTERNAL = @as(u32, 256); pub const WNODE_FLAG_USE_TIMESTAMP = @as(u32, 512); pub const WNODE_FLAG_PERSIST_EVENT = @as(u32, 1024); pub const WNODE_FLAG_EVENT_REFERENCE = @as(u32, 8192); pub const WNODE_FLAG_ANSI_INSTANCENAMES = @as(u32, 16384); pub const WNODE_FLAG_METHOD_ITEM = @as(u32, 32768); pub const WNODE_FLAG_PDO_INSTANCE_NAMES = @as(u32, 65536); pub const WNODE_FLAG_TRACED_GUID = @as(u32, 131072); pub const WNODE_FLAG_LOG_WNODE = @as(u32, 262144); pub const WNODE_FLAG_USE_GUID_PTR = @as(u32, 524288); pub const WNODE_FLAG_USE_MOF_PTR = @as(u32, 1048576); pub const WNODE_FLAG_NO_HEADER = @as(u32, 2097152); pub const WNODE_FLAG_SEND_DATA_BLOCK = @as(u32, 4194304); pub const WNODE_FLAG_VERSIONED_PROPERTIES = @as(u32, 8388608); pub const WNODE_FLAG_SEVERITY_MASK = @as(u32, 4278190080); pub const WMIREG_FLAG_EXPENSIVE = @as(u32, 1); pub const WMIREG_FLAG_INSTANCE_LIST = @as(u32, 4); pub const WMIREG_FLAG_INSTANCE_BASENAME = @as(u32, 8); pub const WMIREG_FLAG_INSTANCE_PDO = @as(u32, 32); pub const WMIREG_FLAG_REMOVE_GUID = @as(u32, 65536); pub const WMIREG_FLAG_RESERVED1 = @as(u32, 131072); pub const WMIREG_FLAG_RESERVED2 = @as(u32, 262144); pub const WMIREG_FLAG_TRACED_GUID = @as(u32, 524288); pub const WMIREG_FLAG_TRACE_CONTROL_GUID = @as(u32, 4096); pub const WMIREG_FLAG_EVENT_ONLY_GUID = @as(u32, 64); pub const WMI_GUIDTYPE_TRACECONTROL = @as(u32, 0); pub const WMI_GUIDTYPE_TRACE = @as(u32, 1); pub const WMI_GUIDTYPE_DATA = @as(u32, 2); pub const WMI_GUIDTYPE_EVENT = @as(u32, 3); pub const WMIGUID_QUERY = @as(u32, 1); pub const WMIGUID_SET = @as(u32, 2); pub const WMIGUID_NOTIFICATION = @as(u32, 4); pub const WMIGUID_READ_DESCRIPTION = @as(u32, 8); pub const WMIGUID_EXECUTE = @as(u32, 16); pub const TRACELOG_CREATE_REALTIME = @as(u32, 32); pub const TRACELOG_CREATE_ONDISK = @as(u32, 64); pub const TRACELOG_GUID_ENABLE = @as(u32, 128); pub const TRACELOG_ACCESS_KERNEL_LOGGER = @as(u32, 256); pub const TRACELOG_LOG_EVENT = @as(u32, 512); pub const TRACELOG_CREATE_INPROC = @as(u32, 512); pub const TRACELOG_ACCESS_REALTIME = @as(u32, 1024); pub const TRACELOG_REGISTER_GUIDS = @as(u32, 2048); pub const TRACELOG_JOIN_GROUP = @as(u32, 4096); pub const WMI_GLOBAL_LOGGER_ID = @as(u32, 1); pub const MAX_PAYLOAD_PREDICATES = @as(u32, 8); pub const EventTraceGuid = Guid.initString("68fdd900-4a3e-11d1-84f4-0000f80464e3"); pub const SystemTraceControlGuid = Guid.initString("9e814aad-3204-11d2-9a82-006008a86939"); pub const EventTraceConfigGuid = Guid.initString("01853a65-418f-4f36-aefc-dc0f1d2fd235"); pub const DefaultTraceSecurityGuid = Guid.initString("0811c1af-7a07-4a06-82ed-869455cdf713"); pub const PrivateLoggerNotificationGuid = Guid.initString("3595ab5c-042a-4c8e-b942-2d059bfeb1b1"); pub const SystemIoFilterProviderGuid = Guid.initString("fbd09363-9e22-4661-b8bf-e7a34b535b8c"); pub const SystemObjectProviderGuid = Guid.initString("febd7460-3d1d-47eb-af49-c9eeb1e146f2"); pub const SystemPowerProviderGuid = Guid.initString("c134884a-32d5-4488-80e5-14ed7abb8269"); pub const SystemHypervisorProviderGuid = Guid.initString("bafa072a-918a-4bed-b622-bc152097098f"); pub const SystemLockProviderGuid = Guid.initString("721ddfd3-dacc-4e1e-b26a-a2cb31d4705a"); pub const SystemConfigProviderGuid = Guid.initString("fef3a8b6-318d-4b67-a96a-3b0f6b8f18fe"); pub const SystemCpuProviderGuid = Guid.initString("c6c5265f-eae8-4650-aae4-9d48603d8510"); pub const SystemSchedulerProviderGuid = Guid.initString("599a2a76-4d91-4910-9ac7-7d33f2e97a6c"); pub const SystemProfileProviderGuid = Guid.initString("bfeb0324-1cee-496f-a409-2ac2b48a6322"); pub const SystemIoProviderGuid = Guid.initString("3d5c43e3-0f1c-4202-b817-174c0070dc79"); pub const SystemMemoryProviderGuid = Guid.initString("82958ca9-b6cd-47f8-a3a8-03ae85a4bc24"); pub const SystemRegistryProviderGuid = Guid.initString("16156bd9-fab4-4cfa-a232-89d1099058e3"); pub const SystemProcessProviderGuid = Guid.initString("151f55dc-467d-471f-83b5-5f889d46ff66"); pub const SystemAlpcProviderGuid = Guid.initString("fcb9baaf-e529-4980-92e9-ced1a6aadfdf"); pub const SystemSyscallProviderGuid = Guid.initString("434286f7-6f1b-45bb-b37e-95f623046c7c"); pub const SystemInterruptProviderGuid = Guid.initString("d4bbee17-b545-4888-858b-744169015b25"); pub const SystemTimerProviderGuid = Guid.initString("4f061568-e215-499f-ab2e-eda0ae890a5b"); pub const MAX_MOF_FIELDS = @as(u32, 16); pub const SYSTEM_EVENT_TYPE = @as(u32, 1); pub const EVENT_TRACE_TYPE_INFO = @as(u32, 0); pub const EVENT_TRACE_TYPE_START = @as(u32, 1); pub const EVENT_TRACE_TYPE_END = @as(u32, 2); pub const EVENT_TRACE_TYPE_STOP = @as(u32, 2); pub const EVENT_TRACE_TYPE_DC_START = @as(u32, 3); pub const EVENT_TRACE_TYPE_DC_END = @as(u32, 4); pub const EVENT_TRACE_TYPE_EXTENSION = @as(u32, 5); pub const EVENT_TRACE_TYPE_REPLY = @as(u32, 6); pub const EVENT_TRACE_TYPE_DEQUEUE = @as(u32, 7); pub const EVENT_TRACE_TYPE_RESUME = @as(u32, 7); pub const EVENT_TRACE_TYPE_CHECKPOINT = @as(u32, 8); pub const EVENT_TRACE_TYPE_SUSPEND = @as(u32, 8); pub const EVENT_TRACE_TYPE_WINEVT_SEND = @as(u32, 9); pub const EVENT_TRACE_TYPE_WINEVT_RECEIVE = @as(u32, 240); pub const TRACE_LEVEL_NONE = @as(u32, 0); pub const TRACE_LEVEL_CRITICAL = @as(u32, 1); pub const TRACE_LEVEL_FATAL = @as(u32, 1); pub const TRACE_LEVEL_ERROR = @as(u32, 2); pub const TRACE_LEVEL_WARNING = @as(u32, 3); pub const TRACE_LEVEL_INFORMATION = @as(u32, 4); pub const TRACE_LEVEL_VERBOSE = @as(u32, 5); pub const TRACE_LEVEL_RESERVED6 = @as(u32, 6); pub const TRACE_LEVEL_RESERVED7 = @as(u32, 7); pub const TRACE_LEVEL_RESERVED8 = @as(u32, 8); pub const TRACE_LEVEL_RESERVED9 = @as(u32, 9); pub const EVENT_TRACE_TYPE_LOAD = @as(u32, 10); pub const EVENT_TRACE_TYPE_TERMINATE = @as(u32, 11); pub const EVENT_TRACE_TYPE_IO_READ = @as(u32, 10); pub const EVENT_TRACE_TYPE_IO_WRITE = @as(u32, 11); pub const EVENT_TRACE_TYPE_IO_READ_INIT = @as(u32, 12); pub const EVENT_TRACE_TYPE_IO_WRITE_INIT = @as(u32, 13); pub const EVENT_TRACE_TYPE_IO_FLUSH = @as(u32, 14); pub const EVENT_TRACE_TYPE_IO_FLUSH_INIT = @as(u32, 15); pub const EVENT_TRACE_TYPE_IO_REDIRECTED_INIT = @as(u32, 16); pub const EVENT_TRACE_TYPE_MM_TF = @as(u32, 10); pub const EVENT_TRACE_TYPE_MM_DZF = @as(u32, 11); pub const EVENT_TRACE_TYPE_MM_COW = @as(u32, 12); pub const EVENT_TRACE_TYPE_MM_GPF = @as(u32, 13); pub const EVENT_TRACE_TYPE_MM_HPF = @as(u32, 14); pub const EVENT_TRACE_TYPE_MM_AV = @as(u32, 15); pub const EVENT_TRACE_TYPE_SEND = @as(u32, 10); pub const EVENT_TRACE_TYPE_RECEIVE = @as(u32, 11); pub const EVENT_TRACE_TYPE_CONNECT = @as(u32, 12); pub const EVENT_TRACE_TYPE_DISCONNECT = @as(u32, 13); pub const EVENT_TRACE_TYPE_RETRANSMIT = @as(u32, 14); pub const EVENT_TRACE_TYPE_ACCEPT = @as(u32, 15); pub const EVENT_TRACE_TYPE_RECONNECT = @as(u32, 16); pub const EVENT_TRACE_TYPE_CONNFAIL = @as(u32, 17); pub const EVENT_TRACE_TYPE_COPY_TCP = @as(u32, 18); pub const EVENT_TRACE_TYPE_COPY_ARP = @as(u32, 19); pub const EVENT_TRACE_TYPE_ACKFULL = @as(u32, 20); pub const EVENT_TRACE_TYPE_ACKPART = @as(u32, 21); pub const EVENT_TRACE_TYPE_ACKDUP = @as(u32, 22); pub const EVENT_TRACE_TYPE_GUIDMAP = @as(u32, 10); pub const EVENT_TRACE_TYPE_CONFIG = @as(u32, 11); pub const EVENT_TRACE_TYPE_SIDINFO = @as(u32, 12); pub const EVENT_TRACE_TYPE_SECURITY = @as(u32, 13); pub const EVENT_TRACE_TYPE_DBGID_RSDS = @as(u32, 64); pub const EVENT_TRACE_TYPE_REGCREATE = @as(u32, 10); pub const EVENT_TRACE_TYPE_REGOPEN = @as(u32, 11); pub const EVENT_TRACE_TYPE_REGDELETE = @as(u32, 12); pub const EVENT_TRACE_TYPE_REGQUERY = @as(u32, 13); pub const EVENT_TRACE_TYPE_REGSETVALUE = @as(u32, 14); pub const EVENT_TRACE_TYPE_REGDELETEVALUE = @as(u32, 15); pub const EVENT_TRACE_TYPE_REGQUERYVALUE = @as(u32, 16); pub const EVENT_TRACE_TYPE_REGENUMERATEKEY = @as(u32, 17); pub const EVENT_TRACE_TYPE_REGENUMERATEVALUEKEY = @as(u32, 18); pub const EVENT_TRACE_TYPE_REGQUERYMULTIPLEVALUE = @as(u32, 19); pub const EVENT_TRACE_TYPE_REGSETINFORMATION = @as(u32, 20); pub const EVENT_TRACE_TYPE_REGFLUSH = @as(u32, 21); pub const EVENT_TRACE_TYPE_REGKCBCREATE = @as(u32, 22); pub const EVENT_TRACE_TYPE_REGKCBDELETE = @as(u32, 23); pub const EVENT_TRACE_TYPE_REGKCBRUNDOWNBEGIN = @as(u32, 24); pub const EVENT_TRACE_TYPE_REGKCBRUNDOWNEND = @as(u32, 25); pub const EVENT_TRACE_TYPE_REGVIRTUALIZE = @as(u32, 26); pub const EVENT_TRACE_TYPE_REGCLOSE = @as(u32, 27); pub const EVENT_TRACE_TYPE_REGSETSECURITY = @as(u32, 28); pub const EVENT_TRACE_TYPE_REGQUERYSECURITY = @as(u32, 29); pub const EVENT_TRACE_TYPE_REGCOMMIT = @as(u32, 30); pub const EVENT_TRACE_TYPE_REGPREPARE = @as(u32, 31); pub const EVENT_TRACE_TYPE_REGROLLBACK = @as(u32, 32); pub const EVENT_TRACE_TYPE_REGMOUNTHIVE = @as(u32, 33); pub const EVENT_TRACE_TYPE_CONFIG_CPU = @as(u32, 10); pub const EVENT_TRACE_TYPE_CONFIG_PHYSICALDISK = @as(u32, 11); pub const EVENT_TRACE_TYPE_CONFIG_LOGICALDISK = @as(u32, 12); pub const EVENT_TRACE_TYPE_CONFIG_NIC = @as(u32, 13); pub const EVENT_TRACE_TYPE_CONFIG_VIDEO = @as(u32, 14); pub const EVENT_TRACE_TYPE_CONFIG_SERVICES = @as(u32, 15); pub const EVENT_TRACE_TYPE_CONFIG_POWER = @as(u32, 16); pub const EVENT_TRACE_TYPE_CONFIG_NETINFO = @as(u32, 17); pub const EVENT_TRACE_TYPE_CONFIG_OPTICALMEDIA = @as(u32, 18); pub const EVENT_TRACE_TYPE_CONFIG_IRQ = @as(u32, 21); pub const EVENT_TRACE_TYPE_CONFIG_PNP = @as(u32, 22); pub const EVENT_TRACE_TYPE_CONFIG_IDECHANNEL = @as(u32, 23); pub const EVENT_TRACE_TYPE_CONFIG_NUMANODE = @as(u32, 24); pub const EVENT_TRACE_TYPE_CONFIG_PLATFORM = @as(u32, 25); pub const EVENT_TRACE_TYPE_CONFIG_PROCESSORGROUP = @as(u32, 26); pub const EVENT_TRACE_TYPE_CONFIG_PROCESSORNUMBER = @as(u32, 27); pub const EVENT_TRACE_TYPE_CONFIG_DPI = @as(u32, 28); pub const EVENT_TRACE_TYPE_CONFIG_CI_INFO = @as(u32, 29); pub const EVENT_TRACE_TYPE_CONFIG_MACHINEID = @as(u32, 30); pub const EVENT_TRACE_TYPE_CONFIG_DEFRAG = @as(u32, 31); pub const EVENT_TRACE_TYPE_CONFIG_MOBILEPLATFORM = @as(u32, 32); pub const EVENT_TRACE_TYPE_CONFIG_DEVICEFAMILY = @as(u32, 33); pub const EVENT_TRACE_TYPE_CONFIG_FLIGHTID = @as(u32, 34); pub const EVENT_TRACE_TYPE_CONFIG_PROCESSOR = @as(u32, 35); pub const EVENT_TRACE_TYPE_CONFIG_VIRTUALIZATION = @as(u32, 36); pub const EVENT_TRACE_TYPE_CONFIG_BOOT = @as(u32, 37); pub const EVENT_TRACE_TYPE_OPTICAL_IO_READ = @as(u32, 55); pub const EVENT_TRACE_TYPE_OPTICAL_IO_WRITE = @as(u32, 56); pub const EVENT_TRACE_TYPE_OPTICAL_IO_FLUSH = @as(u32, 57); pub const EVENT_TRACE_TYPE_OPTICAL_IO_READ_INIT = @as(u32, 58); pub const EVENT_TRACE_TYPE_OPTICAL_IO_WRITE_INIT = @as(u32, 59); pub const EVENT_TRACE_TYPE_OPTICAL_IO_FLUSH_INIT = @as(u32, 60); pub const EVENT_TRACE_TYPE_FLT_PREOP_INIT = @as(u32, 96); pub const EVENT_TRACE_TYPE_FLT_POSTOP_INIT = @as(u32, 97); pub const EVENT_TRACE_TYPE_FLT_PREOP_COMPLETION = @as(u32, 98); pub const EVENT_TRACE_TYPE_FLT_POSTOP_COMPLETION = @as(u32, 99); pub const EVENT_TRACE_TYPE_FLT_PREOP_FAILURE = @as(u32, 100); pub const EVENT_TRACE_TYPE_FLT_POSTOP_FAILURE = @as(u32, 101); pub const EVENT_TRACE_FLAG_DEBUG_EVENTS = @as(u32, 4194304); pub const EVENT_TRACE_FLAG_EXTENSION = @as(u32, 2147483648); pub const EVENT_TRACE_FLAG_FORWARD_WMI = @as(u32, 1073741824); pub const EVENT_TRACE_FLAG_ENABLE_RESERVE = @as(u32, 536870912); pub const EVENT_TRACE_FILE_MODE_NONE = @as(u32, 0); pub const EVENT_TRACE_FILE_MODE_SEQUENTIAL = @as(u32, 1); pub const EVENT_TRACE_FILE_MODE_CIRCULAR = @as(u32, 2); pub const EVENT_TRACE_FILE_MODE_APPEND = @as(u32, 4); pub const EVENT_TRACE_REAL_TIME_MODE = @as(u32, 256); pub const EVENT_TRACE_DELAY_OPEN_FILE_MODE = @as(u32, 512); pub const EVENT_TRACE_BUFFERING_MODE = @as(u32, 1024); pub const EVENT_TRACE_PRIVATE_LOGGER_MODE = @as(u32, 2048); pub const EVENT_TRACE_ADD_HEADER_MODE = @as(u32, 4096); pub const EVENT_TRACE_USE_GLOBAL_SEQUENCE = @as(u32, 16384); pub const EVENT_TRACE_USE_LOCAL_SEQUENCE = @as(u32, 32768); pub const EVENT_TRACE_RELOG_MODE = @as(u32, 65536); pub const EVENT_TRACE_USE_PAGED_MEMORY = @as(u32, 16777216); pub const EVENT_TRACE_FILE_MODE_NEWFILE = @as(u32, 8); pub const EVENT_TRACE_FILE_MODE_PREALLOCATE = @as(u32, 32); pub const EVENT_TRACE_NONSTOPPABLE_MODE = @as(u32, 64); pub const EVENT_TRACE_SECURE_MODE = @as(u32, 128); pub const EVENT_TRACE_USE_KBYTES_FOR_SIZE = @as(u32, 8192); pub const EVENT_TRACE_PRIVATE_IN_PROC = @as(u32, 131072); pub const EVENT_TRACE_MODE_RESERVED = @as(u32, 1048576); pub const EVENT_TRACE_NO_PER_PROCESSOR_BUFFERING = @as(u32, 268435456); pub const EVENT_TRACE_SYSTEM_LOGGER_MODE = @as(u32, 33554432); pub const EVENT_TRACE_ADDTO_TRIAGE_DUMP = @as(u32, 2147483648); pub const EVENT_TRACE_STOP_ON_HYBRID_SHUTDOWN = @as(u32, 4194304); pub const EVENT_TRACE_PERSIST_ON_HYBRID_SHUTDOWN = @as(u32, 8388608); pub const EVENT_TRACE_INDEPENDENT_SESSION_MODE = @as(u32, 134217728); pub const EVENT_TRACE_COMPRESSED_MODE = @as(u32, 67108864); pub const EVENT_TRACE_CONTROL_INCREMENT_FILE = @as(u32, 4); pub const EVENT_TRACE_CONTROL_CONVERT_TO_REALTIME = @as(u32, 5); pub const TRACE_MESSAGE_PERFORMANCE_TIMESTAMP = @as(u32, 16); pub const TRACE_MESSAGE_POINTER32 = @as(u32, 64); pub const TRACE_MESSAGE_POINTER64 = @as(u32, 128); pub const TRACE_MESSAGE_FLAG_MASK = @as(u32, 65535); pub const EVENT_TRACE_USE_PROCTIME = @as(u32, 1); pub const EVENT_TRACE_USE_NOCPUTIME = @as(u32, 2); pub const TRACE_HEADER_FLAG_USE_TIMESTAMP = @as(u32, 512); pub const TRACE_HEADER_FLAG_TRACED_GUID = @as(u32, 131072); pub const TRACE_HEADER_FLAG_LOG_WNODE = @as(u32, 262144); pub const TRACE_HEADER_FLAG_USE_GUID_PTR = @as(u32, 524288); pub const TRACE_HEADER_FLAG_USE_MOF_PTR = @as(u32, 1048576); pub const SYSTEM_ALPC_KW_GENERAL = @as(u64, 1); pub const SYSTEM_CONFIG_KW_SYSTEM = @as(u64, 1); pub const SYSTEM_CONFIG_KW_GRAPHICS = @as(u64, 2); pub const SYSTEM_CONFIG_KW_STORAGE = @as(u64, 4); pub const SYSTEM_CONFIG_KW_NETWORK = @as(u64, 8); pub const SYSTEM_CONFIG_KW_SERVICES = @as(u64, 16); pub const SYSTEM_CONFIG_KW_PNP = @as(u64, 32); pub const SYSTEM_CONFIG_KW_OPTICAL = @as(u64, 64); pub const SYSTEM_CPU_KW_CONFIG = @as(u64, 1); pub const SYSTEM_CPU_KW_CACHE_FLUSH = @as(u64, 2); pub const SYSTEM_CPU_KW_SPEC_CONTROL = @as(u64, 4); pub const SYSTEM_HYPERVISOR_KW_PROFILE = @as(u64, 1); pub const SYSTEM_HYPERVISOR_KW_CALLOUTS = @as(u64, 2); pub const SYSTEM_HYPERVISOR_KW_VTL_CHANGE = @as(u64, 4); pub const SYSTEM_INTERRUPT_KW_GENERAL = @as(u64, 1); pub const SYSTEM_INTERRUPT_KW_CLOCK_INTERRUPT = @as(u64, 2); pub const SYSTEM_INTERRUPT_KW_DPC = @as(u64, 4); pub const SYSTEM_INTERRUPT_KW_DPC_QUEUE = @as(u64, 8); pub const SYSTEM_INTERRUPT_KW_WDF_DPC = @as(u64, 16); pub const SYSTEM_INTERRUPT_KW_WDF_INTERRUPT = @as(u64, 32); pub const SYSTEM_INTERRUPT_KW_IPI = @as(u64, 64); pub const SYSTEM_IO_KW_DISK = @as(u64, 1); pub const SYSTEM_IO_KW_DISK_INIT = @as(u64, 2); pub const SYSTEM_IO_KW_FILENAME = @as(u64, 4); pub const SYSTEM_IO_KW_SPLIT = @as(u64, 8); pub const SYSTEM_IO_KW_FILE = @as(u64, 16); pub const SYSTEM_IO_KW_OPTICAL = @as(u64, 32); pub const SYSTEM_IO_KW_OPTICAL_INIT = @as(u64, 64); pub const SYSTEM_IO_KW_DRIVERS = @as(u64, 128); pub const SYSTEM_IO_KW_CC = @as(u64, 256); pub const SYSTEM_IO_KW_NETWORK = @as(u64, 512); pub const SYSTEM_IOFILTER_KW_GENERAL = @as(u64, 1); pub const SYSTEM_IOFILTER_KW_INIT = @as(u64, 2); pub const SYSTEM_IOFILTER_KW_FASTIO = @as(u64, 4); pub const SYSTEM_IOFILTER_KW_FAILURE = @as(u64, 8); pub const SYSTEM_LOCK_KW_SPINLOCK = @as(u64, 1); pub const SYSTEM_LOCK_KW_SPINLOCK_COUNTERS = @as(u64, 2); pub const SYSTEM_LOCK_KW_SYNC_OBJECTS = @as(u64, 4); pub const SYSTEM_MEMORY_KW_GENERAL = @as(u64, 1); pub const SYSTEM_MEMORY_KW_HARD_FAULTS = @as(u64, 2); pub const SYSTEM_MEMORY_KW_ALL_FAULTS = @as(u64, 4); pub const SYSTEM_MEMORY_KW_POOL = @as(u64, 8); pub const SYSTEM_MEMORY_KW_MEMINFO = @as(u64, 16); pub const SYSTEM_MEMORY_KW_PFSECTION = @as(u64, 32); pub const SYSTEM_MEMORY_KW_MEMINFO_WS = @as(u64, 64); pub const SYSTEM_MEMORY_KW_HEAP = @as(u64, 128); pub const SYSTEM_MEMORY_KW_WS = @as(u64, 256); pub const SYSTEM_MEMORY_KW_CONTMEM_GEN = @as(u64, 512); pub const SYSTEM_MEMORY_KW_VIRTUAL_ALLOC = @as(u64, 1024); pub const SYSTEM_MEMORY_KW_FOOTPRINT = @as(u64, 2048); pub const SYSTEM_MEMORY_KW_SESSION = @as(u64, 4096); pub const SYSTEM_MEMORY_KW_REFSET = @as(u64, 8192); pub const SYSTEM_MEMORY_KW_VAMAP = @as(u64, 16384); pub const SYSTEM_MEMORY_KW_NONTRADEABLE = @as(u64, 32768); pub const SYSTEM_OBJECT_KW_GENERAL = @as(u64, 1); pub const SYSTEM_OBJECT_KW_HANDLE = @as(u64, 2); pub const SYSTEM_POWER_KW_GENERAL = @as(u64, 1); pub const SYSTEM_POWER_KW_HIBER_RUNDOWN = @as(u64, 2); pub const SYSTEM_POWER_KW_PROCESSOR_IDLE = @as(u64, 4); pub const SYSTEM_POWER_KW_IDLE_SELECTION = @as(u64, 8); pub const SYSTEM_POWER_KW_PPM_EXIT_LATENCY = @as(u64, 16); pub const SYSTEM_PROCESS_KW_GENERAL = @as(u64, 1); pub const SYSTEM_PROCESS_KW_INSWAP = @as(u64, 2); pub const SYSTEM_PROCESS_KW_FREEZE = @as(u64, 4); pub const SYSTEM_PROCESS_KW_PERF_COUNTER = @as(u64, 8); pub const SYSTEM_PROCESS_KW_WAKE_COUNTER = @as(u64, 16); pub const SYSTEM_PROCESS_KW_WAKE_DROP = @as(u64, 32); pub const SYSTEM_PROCESS_KW_WAKE_EVENT = @as(u64, 64); pub const SYSTEM_PROCESS_KW_DEBUG_EVENTS = @as(u64, 128); pub const SYSTEM_PROCESS_KW_DBGPRINT = @as(u64, 256); pub const SYSTEM_PROCESS_KW_JOB = @as(u64, 512); pub const SYSTEM_PROCESS_KW_WORKER_THREAD = @as(u64, 1024); pub const SYSTEM_PROCESS_KW_THREAD = @as(u64, 2048); pub const SYSTEM_PROCESS_KW_LOADER = @as(u64, 4096); pub const SYSTEM_PROFILE_KW_GENERAL = @as(u64, 1); pub const SYSTEM_PROFILE_KW_PMC_PROFILE = @as(u64, 2); pub const SYSTEM_REGISTRY_KW_GENERAL = @as(u64, 1); pub const SYSTEM_REGISTRY_KW_HIVE = @as(u64, 2); pub const SYSTEM_REGISTRY_KW_NOTIFICATION = @as(u64, 4); pub const SYSTEM_SCHEDULER_KW_XSCHEDULER = @as(u64, 1); pub const SYSTEM_SCHEDULER_KW_DISPATCHER = @as(u64, 2); pub const SYSTEM_SCHEDULER_KW_KERNEL_QUEUE = @as(u64, 4); pub const SYSTEM_SCHEDULER_KW_SHOULD_YIELD = @as(u64, 8); pub const SYSTEM_SCHEDULER_KW_ANTI_STARVATION = @as(u64, 16); pub const SYSTEM_SCHEDULER_KW_LOAD_BALANCER = @as(u64, 32); pub const SYSTEM_SCHEDULER_KW_AFFINITY = @as(u64, 64); pub const SYSTEM_SCHEDULER_KW_PRIORITY = @as(u64, 128); pub const SYSTEM_SCHEDULER_KW_IDEAL_PROCESSOR = @as(u64, 256); pub const SYSTEM_SCHEDULER_KW_CONTEXT_SWITCH = @as(u64, 512); pub const SYSTEM_SCHEDULER_KW_COMPACT_CSWITCH = @as(u64, 1024); pub const SYSTEM_SYSCALL_KW_GENERAL = @as(u64, 1); pub const SYSTEM_TIMER_KW_GENERAL = @as(u64, 1); pub const SYSTEM_TIMER_KW_CLOCK_TIMER = @as(u64, 2); pub const SYSTEM_MEMORY_POOL_FILTER_ID = @as(u32, 1); pub const ETW_NULL_TYPE_VALUE = @as(u32, 0); pub const ETW_OBJECT_TYPE_VALUE = @as(u32, 1); pub const ETW_STRING_TYPE_VALUE = @as(u32, 2); pub const ETW_SBYTE_TYPE_VALUE = @as(u32, 3); pub const ETW_BYTE_TYPE_VALUE = @as(u32, 4); pub const ETW_INT16_TYPE_VALUE = @as(u32, 5); pub const ETW_UINT16_TYPE_VALUE = @as(u32, 6); pub const ETW_INT32_TYPE_VALUE = @as(u32, 7); pub const ETW_UINT32_TYPE_VALUE = @as(u32, 8); pub const ETW_INT64_TYPE_VALUE = @as(u32, 9); pub const ETW_UINT64_TYPE_VALUE = @as(u32, 10); pub const ETW_CHAR_TYPE_VALUE = @as(u32, 11); pub const ETW_SINGLE_TYPE_VALUE = @as(u32, 12); pub const ETW_DOUBLE_TYPE_VALUE = @as(u32, 13); pub const ETW_BOOLEAN_TYPE_VALUE = @as(u32, 14); pub const ETW_DECIMAL_TYPE_VALUE = @as(u32, 15); pub const ETW_GUID_TYPE_VALUE = @as(u32, 101); pub const ETW_ASCIICHAR_TYPE_VALUE = @as(u32, 102); pub const ETW_ASCIISTRING_TYPE_VALUE = @as(u32, 103); pub const ETW_COUNTED_STRING_TYPE_VALUE = @as(u32, 104); pub const ETW_POINTER_TYPE_VALUE = @as(u32, 105); pub const ETW_SIZET_TYPE_VALUE = @as(u32, 106); pub const ETW_HIDDEN_TYPE_VALUE = @as(u32, 107); pub const ETW_BOOL_TYPE_VALUE = @as(u32, 108); pub const ETW_COUNTED_ANSISTRING_TYPE_VALUE = @as(u32, 109); pub const ETW_REVERSED_COUNTED_STRING_TYPE_VALUE = @as(u32, 110); pub const ETW_REVERSED_COUNTED_ANSISTRING_TYPE_VALUE = @as(u32, 111); pub const ETW_NON_NULL_TERMINATED_STRING_TYPE_VALUE = @as(u32, 112); pub const ETW_REDUCED_ANSISTRING_TYPE_VALUE = @as(u32, 113); pub const ETW_REDUCED_STRING_TYPE_VALUE = @as(u32, 114); pub const ETW_SID_TYPE_VALUE = @as(u32, 115); pub const ETW_VARIANT_TYPE_VALUE = @as(u32, 116); pub const ETW_PTVECTOR_TYPE_VALUE = @as(u32, 117); pub const ETW_WMITIME_TYPE_VALUE = @as(u32, 118); pub const ETW_DATETIME_TYPE_VALUE = @as(u32, 119); pub const ETW_REFRENCE_TYPE_VALUE = @as(u32, 120); pub const TRACE_PROVIDER_FLAG_LEGACY = @as(u32, 1); pub const TRACE_PROVIDER_FLAG_PRE_ENABLE = @as(u32, 2); pub const ENABLE_TRACE_PARAMETERS_VERSION = @as(u32, 1); pub const ENABLE_TRACE_PARAMETERS_VERSION_2 = @as(u32, 2); pub const EVENT_MIN_LEVEL = @as(u32, 0); pub const EVENT_MAX_LEVEL = @as(u32, 255); pub const EVENT_ACTIVITY_CTRL_GET_ID = @as(u32, 1); pub const EVENT_ACTIVITY_CTRL_SET_ID = @as(u32, 2); pub const EVENT_ACTIVITY_CTRL_CREATE_ID = @as(u32, 3); pub const EVENT_ACTIVITY_CTRL_GET_SET_ID = @as(u32, 4); pub const EVENT_ACTIVITY_CTRL_CREATE_SET_ID = @as(u32, 5); pub const MAX_EVENT_DATA_DESCRIPTORS = @as(u32, 128); pub const MAX_EVENT_FILTER_DATA_SIZE = @as(u32, 1024); pub const MAX_EVENT_FILTER_PAYLOAD_SIZE = @as(u32, 4096); pub const MAX_EVENT_FILTER_EVENT_NAME_SIZE = @as(u32, 4096); pub const MAX_EVENT_FILTERS_COUNT = @as(u32, 13); pub const MAX_EVENT_FILTER_PID_COUNT = @as(u32, 8); pub const MAX_EVENT_FILTER_EVENT_ID_COUNT = @as(u32, 64); pub const EVENT_FILTER_TYPE_NONE = @as(u32, 0); pub const EVENT_FILTER_TYPE_SCHEMATIZED = @as(u32, 2147483648); pub const EVENT_FILTER_TYPE_SYSTEM_FLAGS = @as(u32, 2147483649); pub const EVENT_FILTER_TYPE_TRACEHANDLE = @as(u32, 2147483650); pub const EVENT_FILTER_TYPE_PID = @as(u32, 2147483652); pub const EVENT_FILTER_TYPE_EXECUTABLE_NAME = @as(u32, 2147483656); pub const EVENT_FILTER_TYPE_PACKAGE_ID = @as(u32, 2147483664); pub const EVENT_FILTER_TYPE_PACKAGE_APP_ID = @as(u32, 2147483680); pub const EVENT_FILTER_TYPE_PAYLOAD = @as(u32, 2147483904); pub const EVENT_FILTER_TYPE_EVENT_ID = @as(u32, 2147484160); pub const EVENT_FILTER_TYPE_EVENT_NAME = @as(u32, 2147484672); pub const EVENT_FILTER_TYPE_STACKWALK = @as(u32, 2147487744); pub const EVENT_FILTER_TYPE_STACKWALK_NAME = @as(u32, 2147491840); pub const EVENT_FILTER_TYPE_STACKWALK_LEVEL_KW = @as(u32, 2147500032); pub const EVENT_FILTER_TYPE_CONTAINER = @as(u32, 2147516416); pub const EVENT_DATA_DESCRIPTOR_TYPE_NONE = @as(u32, 0); pub const EVENT_DATA_DESCRIPTOR_TYPE_EVENT_METADATA = @as(u32, 1); pub const EVENT_DATA_DESCRIPTOR_TYPE_PROVIDER_METADATA = @as(u32, 2); pub const EVENT_DATA_DESCRIPTOR_TYPE_TIMESTAMP_OVERRIDE = @as(u32, 3); pub const EVENT_WRITE_FLAG_NO_FAULTING = @as(u32, 1); pub const EVENT_WRITE_FLAG_INPRIVATE = @as(u32, 2); pub const EVENT_HEADER_EXT_TYPE_RELATED_ACTIVITYID = @as(u32, 1); pub const EVENT_HEADER_EXT_TYPE_SID = @as(u32, 2); pub const EVENT_HEADER_EXT_TYPE_TS_ID = @as(u32, 3); pub const EVENT_HEADER_EXT_TYPE_INSTANCE_INFO = @as(u32, 4); pub const EVENT_HEADER_EXT_TYPE_STACK_TRACE32 = @as(u32, 5); pub const EVENT_HEADER_EXT_TYPE_STACK_TRACE64 = @as(u32, 6); pub const EVENT_HEADER_EXT_TYPE_PEBS_INDEX = @as(u32, 7); pub const EVENT_HEADER_EXT_TYPE_PMC_COUNTERS = @as(u32, 8); pub const EVENT_HEADER_EXT_TYPE_PSM_KEY = @as(u32, 9); pub const EVENT_HEADER_EXT_TYPE_EVENT_KEY = @as(u32, 10); pub const EVENT_HEADER_EXT_TYPE_EVENT_SCHEMA_TL = @as(u32, 11); pub const EVENT_HEADER_EXT_TYPE_PROV_TRAITS = @as(u32, 12); pub const EVENT_HEADER_EXT_TYPE_PROCESS_START_KEY = @as(u32, 13); pub const EVENT_HEADER_EXT_TYPE_CONTROL_GUID = @as(u32, 14); pub const EVENT_HEADER_EXT_TYPE_QPC_DELTA = @as(u32, 15); pub const EVENT_HEADER_EXT_TYPE_CONTAINER_ID = @as(u32, 16); pub const EVENT_HEADER_EXT_TYPE_STACK_KEY32 = @as(u32, 17); pub const EVENT_HEADER_EXT_TYPE_STACK_KEY64 = @as(u32, 18); pub const EVENT_HEADER_EXT_TYPE_MAX = @as(u32, 19); pub const EVENT_HEADER_PROPERTY_XML = @as(u32, 1); pub const EVENT_HEADER_PROPERTY_FORWARDED_XML = @as(u32, 2); pub const EVENT_HEADER_PROPERTY_LEGACY_EVENTLOG = @as(u32, 4); pub const EVENT_HEADER_PROPERTY_RELOGGABLE = @as(u32, 8); pub const EVENT_HEADER_FLAG_EXTENDED_INFO = @as(u32, 1); pub const EVENT_HEADER_FLAG_PRIVATE_SESSION = @as(u32, 2); pub const EVENT_HEADER_FLAG_STRING_ONLY = @as(u32, 4); pub const EVENT_HEADER_FLAG_TRACE_MESSAGE = @as(u32, 8); pub const EVENT_HEADER_FLAG_NO_CPUTIME = @as(u32, 16); pub const EVENT_HEADER_FLAG_32_BIT_HEADER = @as(u32, 32); pub const EVENT_HEADER_FLAG_64_BIT_HEADER = @as(u32, 64); pub const EVENT_HEADER_FLAG_DECODE_GUID = @as(u32, 128); pub const EVENT_HEADER_FLAG_CLASSIC_HEADER = @as(u32, 256); pub const EVENT_HEADER_FLAG_PROCESSOR_INDEX = @as(u32, 512); pub const EVENT_ENABLE_PROPERTY_SID = @as(u32, 1); pub const EVENT_ENABLE_PROPERTY_TS_ID = @as(u32, 2); pub const EVENT_ENABLE_PROPERTY_STACK_TRACE = @as(u32, 4); pub const EVENT_ENABLE_PROPERTY_PSM_KEY = @as(u32, 8); pub const EVENT_ENABLE_PROPERTY_IGNORE_KEYWORD_0 = @as(u32, 16); pub const EVENT_ENABLE_PROPERTY_PROVIDER_GROUP = @as(u32, 32); pub const EVENT_ENABLE_PROPERTY_ENABLE_KEYWORD_0 = @as(u32, 64); pub const EVENT_ENABLE_PROPERTY_PROCESS_START_KEY = @as(u32, 128); pub const EVENT_ENABLE_PROPERTY_EVENT_KEY = @as(u32, 256); pub const EVENT_ENABLE_PROPERTY_EXCLUDE_INPRIVATE = @as(u32, 512); pub const EVENT_ENABLE_PROPERTY_ENABLE_SILOS = @as(u32, 1024); pub const EVENT_ENABLE_PROPERTY_SOURCE_CONTAINER_TRACKING = @as(u32, 2048); pub const PROCESS_TRACE_MODE_REAL_TIME = @as(u32, 256); pub const PROCESS_TRACE_MODE_RAW_TIMESTAMP = @as(u32, 4096); pub const PROCESS_TRACE_MODE_EVENT_RECORD = @as(u32, 268435456); pub const CLSID_TraceRelogger = Guid.initString("7b40792d-05ff-44c4-9058-f440c71f17d4"); //-------------------------------------------------------------------------------- // Section: Types (108) //-------------------------------------------------------------------------------- pub const TRACE_MESSAGE_FLAGS = enum(u32) { COMPONENTID = 4, GUID = 2, SEQUENCE = 1, SYSTEMINFO = 32, TIMESTAMP = 8, _, pub fn initFlags(o: struct { COMPONENTID: u1 = 0, GUID: u1 = 0, SEQUENCE: u1 = 0, SYSTEMINFO: u1 = 0, TIMESTAMP: u1 = 0, }) TRACE_MESSAGE_FLAGS { return @intToEnum(TRACE_MESSAGE_FLAGS, (if (o.COMPONENTID == 1) @enumToInt(TRACE_MESSAGE_FLAGS.COMPONENTID) else 0) | (if (o.GUID == 1) @enumToInt(TRACE_MESSAGE_FLAGS.GUID) else 0) | (if (o.SEQUENCE == 1) @enumToInt(TRACE_MESSAGE_FLAGS.SEQUENCE) else 0) | (if (o.SYSTEMINFO == 1) @enumToInt(TRACE_MESSAGE_FLAGS.SYSTEMINFO) else 0) | (if (o.TIMESTAMP == 1) @enumToInt(TRACE_MESSAGE_FLAGS.TIMESTAMP) else 0) ); } }; pub const TRACE_MESSAGE_COMPONENTID = TRACE_MESSAGE_FLAGS.COMPONENTID; pub const TRACE_MESSAGE_GUID = TRACE_MESSAGE_FLAGS.GUID; pub const TRACE_MESSAGE_SEQUENCE = TRACE_MESSAGE_FLAGS.SEQUENCE; pub const TRACE_MESSAGE_SYSTEMINFO = TRACE_MESSAGE_FLAGS.SYSTEMINFO; pub const TRACE_MESSAGE_TIMESTAMP = TRACE_MESSAGE_FLAGS.TIMESTAMP; pub const ENABLECALLBACK_ENABLED_STATE = enum(u32) { DISABLE_PROVIDER = 0, ENABLE_PROVIDER = 1, CAPTURE_STATE = 2, }; pub const EVENT_CONTROL_CODE_DISABLE_PROVIDER = ENABLECALLBACK_ENABLED_STATE.DISABLE_PROVIDER; pub const EVENT_CONTROL_CODE_ENABLE_PROVIDER = ENABLECALLBACK_ENABLED_STATE.ENABLE_PROVIDER; pub const EVENT_CONTROL_CODE_CAPTURE_STATE = ENABLECALLBACK_ENABLED_STATE.CAPTURE_STATE; pub const EVENT_TRACE_CONTROL = enum(u32) { FLUSH = 3, QUERY = 0, STOP = 1, UPDATE = 2, }; pub const EVENT_TRACE_CONTROL_FLUSH = EVENT_TRACE_CONTROL.FLUSH; pub const EVENT_TRACE_CONTROL_QUERY = EVENT_TRACE_CONTROL.QUERY; pub const EVENT_TRACE_CONTROL_STOP = EVENT_TRACE_CONTROL.STOP; pub const EVENT_TRACE_CONTROL_UPDATE = EVENT_TRACE_CONTROL.UPDATE; pub const EVENT_TRACE_FLAG = enum(u32) { ALPC = 1048576, CSWITCH = 16, DBGPRINT = 262144, DISK_FILE_IO = 512, DISK_IO = 256, DISK_IO_INIT = 1024, DISPATCHER = 2048, DPC = 32, DRIVER = 8388608, FILE_IO = 33554432, FILE_IO_INIT = 67108864, IMAGE_LOAD = 4, INTERRUPT = 64, JOB = 524288, MEMORY_HARD_FAULTS = 8192, MEMORY_PAGE_FAULTS = 4096, NETWORK_TCPIP = 65536, NO_SYSCONFIG = 268435456, PROCESS = 1, PROCESS_COUNTERS = 8, PROFILE = 16777216, REGISTRY = 131072, SPLIT_IO = 2097152, SYSTEMCALL = 128, THREAD = 2, VAMAP = 32768, VIRTUAL_ALLOC = 16384, _, pub fn initFlags(o: struct { ALPC: u1 = 0, CSWITCH: u1 = 0, DBGPRINT: u1 = 0, DISK_FILE_IO: u1 = 0, DISK_IO: u1 = 0, DISK_IO_INIT: u1 = 0, DISPATCHER: u1 = 0, DPC: u1 = 0, DRIVER: u1 = 0, FILE_IO: u1 = 0, FILE_IO_INIT: u1 = 0, IMAGE_LOAD: u1 = 0, INTERRUPT: u1 = 0, JOB: u1 = 0, MEMORY_HARD_FAULTS: u1 = 0, MEMORY_PAGE_FAULTS: u1 = 0, NETWORK_TCPIP: u1 = 0, NO_SYSCONFIG: u1 = 0, PROCESS: u1 = 0, PROCESS_COUNTERS: u1 = 0, PROFILE: u1 = 0, REGISTRY: u1 = 0, SPLIT_IO: u1 = 0, SYSTEMCALL: u1 = 0, THREAD: u1 = 0, VAMAP: u1 = 0, VIRTUAL_ALLOC: u1 = 0, }) EVENT_TRACE_FLAG { return @intToEnum(EVENT_TRACE_FLAG, (if (o.ALPC == 1) @enumToInt(EVENT_TRACE_FLAG.ALPC) else 0) | (if (o.CSWITCH == 1) @enumToInt(EVENT_TRACE_FLAG.CSWITCH) else 0) | (if (o.DBGPRINT == 1) @enumToInt(EVENT_TRACE_FLAG.DBGPRINT) else 0) | (if (o.DISK_FILE_IO == 1) @enumToInt(EVENT_TRACE_FLAG.DISK_FILE_IO) else 0) | (if (o.DISK_IO == 1) @enumToInt(EVENT_TRACE_FLAG.DISK_IO) else 0) | (if (o.DISK_IO_INIT == 1) @enumToInt(EVENT_TRACE_FLAG.DISK_IO_INIT) else 0) | (if (o.DISPATCHER == 1) @enumToInt(EVENT_TRACE_FLAG.DISPATCHER) else 0) | (if (o.DPC == 1) @enumToInt(EVENT_TRACE_FLAG.DPC) else 0) | (if (o.DRIVER == 1) @enumToInt(EVENT_TRACE_FLAG.DRIVER) else 0) | (if (o.FILE_IO == 1) @enumToInt(EVENT_TRACE_FLAG.FILE_IO) else 0) | (if (o.FILE_IO_INIT == 1) @enumToInt(EVENT_TRACE_FLAG.FILE_IO_INIT) else 0) | (if (o.IMAGE_LOAD == 1) @enumToInt(EVENT_TRACE_FLAG.IMAGE_LOAD) else 0) | (if (o.INTERRUPT == 1) @enumToInt(EVENT_TRACE_FLAG.INTERRUPT) else 0) | (if (o.JOB == 1) @enumToInt(EVENT_TRACE_FLAG.JOB) else 0) | (if (o.MEMORY_HARD_FAULTS == 1) @enumToInt(EVENT_TRACE_FLAG.MEMORY_HARD_FAULTS) else 0) | (if (o.MEMORY_PAGE_FAULTS == 1) @enumToInt(EVENT_TRACE_FLAG.MEMORY_PAGE_FAULTS) else 0) | (if (o.NETWORK_TCPIP == 1) @enumToInt(EVENT_TRACE_FLAG.NETWORK_TCPIP) else 0) | (if (o.NO_SYSCONFIG == 1) @enumToInt(EVENT_TRACE_FLAG.NO_SYSCONFIG) else 0) | (if (o.PROCESS == 1) @enumToInt(EVENT_TRACE_FLAG.PROCESS) else 0) | (if (o.PROCESS_COUNTERS == 1) @enumToInt(EVENT_TRACE_FLAG.PROCESS_COUNTERS) else 0) | (if (o.PROFILE == 1) @enumToInt(EVENT_TRACE_FLAG.PROFILE) else 0) | (if (o.REGISTRY == 1) @enumToInt(EVENT_TRACE_FLAG.REGISTRY) else 0) | (if (o.SPLIT_IO == 1) @enumToInt(EVENT_TRACE_FLAG.SPLIT_IO) else 0) | (if (o.SYSTEMCALL == 1) @enumToInt(EVENT_TRACE_FLAG.SYSTEMCALL) else 0) | (if (o.THREAD == 1) @enumToInt(EVENT_TRACE_FLAG.THREAD) else 0) | (if (o.VAMAP == 1) @enumToInt(EVENT_TRACE_FLAG.VAMAP) else 0) | (if (o.VIRTUAL_ALLOC == 1) @enumToInt(EVENT_TRACE_FLAG.VIRTUAL_ALLOC) else 0) ); } }; pub const EVENT_TRACE_FLAG_ALPC = EVENT_TRACE_FLAG.ALPC; pub const EVENT_TRACE_FLAG_CSWITCH = EVENT_TRACE_FLAG.CSWITCH; pub const EVENT_TRACE_FLAG_DBGPRINT = EVENT_TRACE_FLAG.DBGPRINT; pub const EVENT_TRACE_FLAG_DISK_FILE_IO = EVENT_TRACE_FLAG.DISK_FILE_IO; pub const EVENT_TRACE_FLAG_DISK_IO = EVENT_TRACE_FLAG.DISK_IO; pub const EVENT_TRACE_FLAG_DISK_IO_INIT = EVENT_TRACE_FLAG.DISK_IO_INIT; pub const EVENT_TRACE_FLAG_DISPATCHER = EVENT_TRACE_FLAG.DISPATCHER; pub const EVENT_TRACE_FLAG_DPC = EVENT_TRACE_FLAG.DPC; pub const EVENT_TRACE_FLAG_DRIVER = EVENT_TRACE_FLAG.DRIVER; pub const EVENT_TRACE_FLAG_FILE_IO = EVENT_TRACE_FLAG.FILE_IO; pub const EVENT_TRACE_FLAG_FILE_IO_INIT = EVENT_TRACE_FLAG.FILE_IO_INIT; pub const EVENT_TRACE_FLAG_IMAGE_LOAD = EVENT_TRACE_FLAG.IMAGE_LOAD; pub const EVENT_TRACE_FLAG_INTERRUPT = EVENT_TRACE_FLAG.INTERRUPT; pub const EVENT_TRACE_FLAG_JOB = EVENT_TRACE_FLAG.JOB; pub const EVENT_TRACE_FLAG_MEMORY_HARD_FAULTS = EVENT_TRACE_FLAG.MEMORY_HARD_FAULTS; pub const EVENT_TRACE_FLAG_MEMORY_PAGE_FAULTS = EVENT_TRACE_FLAG.MEMORY_PAGE_FAULTS; pub const EVENT_TRACE_FLAG_NETWORK_TCPIP = EVENT_TRACE_FLAG.NETWORK_TCPIP; pub const EVENT_TRACE_FLAG_NO_SYSCONFIG = EVENT_TRACE_FLAG.NO_SYSCONFIG; pub const EVENT_TRACE_FLAG_PROCESS = EVENT_TRACE_FLAG.PROCESS; pub const EVENT_TRACE_FLAG_PROCESS_COUNTERS = EVENT_TRACE_FLAG.PROCESS_COUNTERS; pub const EVENT_TRACE_FLAG_PROFILE = EVENT_TRACE_FLAG.PROFILE; pub const EVENT_TRACE_FLAG_REGISTRY = EVENT_TRACE_FLAG.REGISTRY; pub const EVENT_TRACE_FLAG_SPLIT_IO = EVENT_TRACE_FLAG.SPLIT_IO; pub const EVENT_TRACE_FLAG_SYSTEMCALL = EVENT_TRACE_FLAG.SYSTEMCALL; pub const EVENT_TRACE_FLAG_THREAD = EVENT_TRACE_FLAG.THREAD; pub const EVENT_TRACE_FLAG_VAMAP = EVENT_TRACE_FLAG.VAMAP; pub const EVENT_TRACE_FLAG_VIRTUAL_ALLOC = EVENT_TRACE_FLAG.VIRTUAL_ALLOC; // TODO: this type has a FreeFunc 'TdhCloseDecodingHandle', what can Zig do with this information? pub const TDH_HANDLE = isize; pub const WNODE_HEADER = extern struct { BufferSize: u32, ProviderId: u32, Anonymous1: extern union { HistoricalContext: u64, Anonymous: extern struct { Version: u32, Linkage: u32, }, }, Anonymous2: extern union { CountLost: u32, KernelHandle: ?HANDLE, TimeStamp: LARGE_INTEGER, }, Guid: Guid, ClientContext: u32, Flags: u32, }; pub const OFFSETINSTANCEDATAANDLENGTH = extern struct { OffsetInstanceData: u32, LengthInstanceData: u32, }; pub const WNODE_ALL_DATA = extern struct { WnodeHeader: WNODE_HEADER, DataBlockOffset: u32, InstanceCount: u32, OffsetInstanceNameOffsets: u32, Anonymous: extern union { FixedInstanceSize: u32, OffsetInstanceDataAndLength: [1]OFFSETINSTANCEDATAANDLENGTH, }, }; pub const WNODE_SINGLE_INSTANCE = extern struct { WnodeHeader: WNODE_HEADER, OffsetInstanceName: u32, InstanceIndex: u32, DataBlockOffset: u32, SizeDataBlock: u32, VariableData: [1]u8, }; pub const WNODE_SINGLE_ITEM = extern struct { WnodeHeader: WNODE_HEADER, OffsetInstanceName: u32, InstanceIndex: u32, ItemId: u32, DataBlockOffset: u32, SizeDataItem: u32, VariableData: [1]u8, }; pub const WNODE_METHOD_ITEM = extern struct { WnodeHeader: WNODE_HEADER, OffsetInstanceName: u32, InstanceIndex: u32, MethodId: u32, DataBlockOffset: u32, SizeDataBlock: u32, VariableData: [1]u8, }; pub const WNODE_EVENT_ITEM = extern struct { WnodeHeader: WNODE_HEADER, }; pub const WNODE_EVENT_REFERENCE = extern struct { WnodeHeader: WNODE_HEADER, TargetGuid: Guid, TargetDataBlockSize: u32, Anonymous: extern union { TargetInstanceIndex: u32, TargetInstanceName: [1]u16, }, }; pub const WNODE_TOO_SMALL = extern struct { WnodeHeader: WNODE_HEADER, SizeNeeded: u32, }; pub const WMIREGGUIDW = extern struct { Guid: Guid, Flags: u32, InstanceCount: u32, Anonymous: extern union { InstanceNameList: u32, BaseNameOffset: u32, Pdo: usize, InstanceInfo: usize, }, }; pub const WMIREGINFOW = extern struct { BufferSize: u32, NextWmiRegInfo: u32, RegistryPath: u32, MofResourceName: u32, GuidCount: u32, WmiRegGuid: [1]WMIREGGUIDW, }; pub const WMIDPREQUESTCODE = enum(i32) { GET_ALL_DATA = 0, GET_SINGLE_INSTANCE = 1, SET_SINGLE_INSTANCE = 2, SET_SINGLE_ITEM = 3, ENABLE_EVENTS = 4, DISABLE_EVENTS = 5, ENABLE_COLLECTION = 6, DISABLE_COLLECTION = 7, REGINFO = 8, EXECUTE_METHOD = 9, CAPTURE_STATE = 10, }; pub const WMI_GET_ALL_DATA = WMIDPREQUESTCODE.GET_ALL_DATA; pub const WMI_GET_SINGLE_INSTANCE = WMIDPREQUESTCODE.GET_SINGLE_INSTANCE; pub const WMI_SET_SINGLE_INSTANCE = WMIDPREQUESTCODE.SET_SINGLE_INSTANCE; pub const WMI_SET_SINGLE_ITEM = WMIDPREQUESTCODE.SET_SINGLE_ITEM; pub const WMI_ENABLE_EVENTS = WMIDPREQUESTCODE.ENABLE_EVENTS; pub const WMI_DISABLE_EVENTS = WMIDPREQUESTCODE.DISABLE_EVENTS; pub const WMI_ENABLE_COLLECTION = WMIDPREQUESTCODE.ENABLE_COLLECTION; pub const WMI_DISABLE_COLLECTION = WMIDPREQUESTCODE.DISABLE_COLLECTION; pub const WMI_REGINFO = WMIDPREQUESTCODE.REGINFO; pub const WMI_EXECUTE_METHOD = WMIDPREQUESTCODE.EXECUTE_METHOD; pub const WMI_CAPTURE_STATE = WMIDPREQUESTCODE.CAPTURE_STATE; pub const ETW_COMPRESSION_RESUMPTION_MODE = enum(i32) { Restart = 0, NoDisable = 1, NoRestart = 2, }; pub const EtwCompressionModeRestart = ETW_COMPRESSION_RESUMPTION_MODE.Restart; pub const EtwCompressionModeNoDisable = ETW_COMPRESSION_RESUMPTION_MODE.NoDisable; pub const EtwCompressionModeNoRestart = ETW_COMPRESSION_RESUMPTION_MODE.NoRestart; pub const EVENT_TRACE_HEADER = extern struct { Size: u16, Anonymous1: extern union { FieldTypeFlags: u16, Anonymous: extern struct { HeaderType: u8, MarkerFlags: u8, }, }, Anonymous2: extern union { Version: u32, Class: extern struct { Type: u8, Level: u8, Version: u16, }, }, ThreadId: u32, ProcessId: u32, TimeStamp: LARGE_INTEGER, Anonymous3: extern union { Guid: Guid, GuidPtr: u64, }, Anonymous4: extern union { Anonymous1: extern struct { KernelTime: u32, UserTime: u32, }, ProcessorTime: u64, Anonymous2: extern struct { ClientContext: u32, Flags: u32, }, }, }; pub const EVENT_INSTANCE_HEADER = extern struct { Size: u16, Anonymous1: extern union { FieldTypeFlags: u16, Anonymous: extern struct { HeaderType: u8, MarkerFlags: u8, }, }, Anonymous2: extern union { Version: u32, Class: extern struct { Type: u8, Level: u8, Version: u16, }, }, ThreadId: u32, ProcessId: u32, TimeStamp: LARGE_INTEGER, RegHandle: u64, InstanceId: u32, ParentInstanceId: u32, Anonymous3: extern union { Anonymous1: extern struct { KernelTime: u32, UserTime: u32, }, ProcessorTime: u64, Anonymous2: extern struct { EventId: u32, Flags: u32, }, }, ParentRegHandle: u64, }; pub const MOF_FIELD = extern struct { DataPtr: u64, Length: u32, DataType: u32, }; pub const TRACE_LOGFILE_HEADER = extern struct { BufferSize: u32, Anonymous1: extern union { Version: u32, VersionDetail: extern struct { MajorVersion: u8, MinorVersion: u8, SubVersion: u8, SubMinorVersion: u8, }, }, ProviderVersion: u32, NumberOfProcessors: u32, EndTime: LARGE_INTEGER, TimerResolution: u32, MaximumFileSize: u32, LogFileMode: u32, BuffersWritten: u32, Anonymous2: extern union { LogInstanceGuid: Guid, Anonymous: extern struct { StartBuffers: u32, PointerSize: u32, EventsLost: u32, CpuSpeedInMHz: u32, }, }, LoggerName: ?PWSTR, LogFileName: ?PWSTR, TimeZone: TIME_ZONE_INFORMATION, BootTime: LARGE_INTEGER, PerfFreq: LARGE_INTEGER, StartTime: LARGE_INTEGER, ReservedFlags: u32, BuffersLost: u32, }; pub const TRACE_LOGFILE_HEADER32 = extern struct { BufferSize: u32, Anonymous1: extern union { Version: u32, VersionDetail: extern struct { MajorVersion: u8, MinorVersion: u8, SubVersion: u8, SubMinorVersion: u8, }, }, ProviderVersion: u32, NumberOfProcessors: u32, EndTime: LARGE_INTEGER, TimerResolution: u32, MaximumFileSize: u32, LogFileMode: u32, BuffersWritten: u32, Anonymous2: extern union { LogInstanceGuid: Guid, Anonymous: extern struct { StartBuffers: u32, PointerSize: u32, EventsLost: u32, CpuSpeedInMHz: u32, }, }, LoggerName: u32, LogFileName: u32, TimeZone: TIME_ZONE_INFORMATION, BootTime: LARGE_INTEGER, PerfFreq: LARGE_INTEGER, StartTime: LARGE_INTEGER, ReservedFlags: u32, BuffersLost: u32, }; pub const TRACE_LOGFILE_HEADER64 = extern struct { BufferSize: u32, Anonymous1: extern union { Version: u32, VersionDetail: extern struct { MajorVersion: u8, MinorVersion: u8, SubVersion: u8, SubMinorVersion: u8, }, }, ProviderVersion: u32, NumberOfProcessors: u32, EndTime: LARGE_INTEGER, TimerResolution: u32, MaximumFileSize: u32, LogFileMode: u32, BuffersWritten: u32, Anonymous2: extern union { LogInstanceGuid: Guid, Anonymous: extern struct { StartBuffers: u32, PointerSize: u32, EventsLost: u32, CpuSpeedInMHz: u32, }, }, LoggerName: u64, LogFileName: u64, TimeZone: TIME_ZONE_INFORMATION, BootTime: LARGE_INTEGER, PerfFreq: LARGE_INTEGER, StartTime: LARGE_INTEGER, ReservedFlags: u32, BuffersLost: u32, }; pub const EVENT_INSTANCE_INFO = extern struct { RegHandle: ?HANDLE, InstanceId: u32, }; pub const EVENT_TRACE_PROPERTIES = extern struct { Wnode: WNODE_HEADER, BufferSize: u32, MinimumBuffers: u32, MaximumBuffers: u32, MaximumFileSize: u32, LogFileMode: u32, FlushTimer: u32, EnableFlags: EVENT_TRACE_FLAG, Anonymous: extern union { AgeLimit: i32, FlushThreshold: i32, }, NumberOfBuffers: u32, FreeBuffers: u32, EventsLost: u32, BuffersWritten: u32, LogBuffersLost: u32, RealTimeBuffersLost: u32, LoggerThreadId: ?HANDLE, LogFileNameOffset: u32, LoggerNameOffset: u32, }; pub const EVENT_TRACE_PROPERTIES_V2 = extern struct { Wnode: WNODE_HEADER, BufferSize: u32, MinimumBuffers: u32, MaximumBuffers: u32, MaximumFileSize: u32, LogFileMode: u32, FlushTimer: u32, EnableFlags: EVENT_TRACE_FLAG, Anonymous1: extern union { AgeLimit: i32, FlushThreshold: i32, }, NumberOfBuffers: u32, FreeBuffers: u32, EventsLost: u32, BuffersWritten: u32, LogBuffersLost: u32, RealTimeBuffersLost: u32, LoggerThreadId: ?HANDLE, LogFileNameOffset: u32, LoggerNameOffset: u32, Anonymous2: extern union { Anonymous: extern struct { _bitfield: u32, }, V2Control: u32, }, FilterDescCount: u32, FilterDesc: ?*EVENT_FILTER_DESCRIPTOR, Anonymous3: extern union { Anonymous: extern struct { _bitfield: u32, }, V2Options: u64, }, }; pub const TRACE_GUID_REGISTRATION = extern struct { Guid: ?*const Guid, RegHandle: ?HANDLE, }; pub const TRACE_GUID_PROPERTIES = extern struct { Guid: Guid, GuidType: u32, LoggerId: u32, EnableLevel: u32, EnableFlags: u32, IsEnable: BOOLEAN, }; pub const ETW_BUFFER_CONTEXT = extern struct { Anonymous: extern union { Anonymous: extern struct { ProcessorNumber: u8, Alignment: u8, }, ProcessorIndex: u16, }, LoggerId: u16, }; pub const TRACE_ENABLE_INFO = extern struct { IsEnabled: u32, Level: u8, Reserved1: u8, LoggerId: u16, EnableProperty: u32, Reserved2: u32, MatchAnyKeyword: u64, MatchAllKeyword: u64, }; pub const TRACE_PROVIDER_INSTANCE_INFO = extern struct { NextOffset: u32, EnableCount: u32, Pid: u32, Flags: u32, }; pub const TRACE_GUID_INFO = extern struct { InstanceCount: u32, Reserved: u32, }; pub const PROFILE_SOURCE_INFO = extern struct { NextEntryOffset: u32, Source: u32, MinInterval: u32, MaxInterval: u32, Reserved: u64, Description: [1]u16, }; pub const ETW_PMC_COUNTER_OWNER_TYPE = enum(i32) { Free = 0, Untagged = 1, Tagged = 2, TaggedWithSource = 3, }; pub const EtwPmcOwnerFree = ETW_PMC_COUNTER_OWNER_TYPE.Free; pub const EtwPmcOwnerUntagged = ETW_PMC_COUNTER_OWNER_TYPE.Untagged; pub const EtwPmcOwnerTagged = ETW_PMC_COUNTER_OWNER_TYPE.Tagged; pub const EtwPmcOwnerTaggedWithSource = ETW_PMC_COUNTER_OWNER_TYPE.TaggedWithSource; pub const ETW_PMC_COUNTER_OWNER = extern struct { OwnerType: ETW_PMC_COUNTER_OWNER_TYPE, ProfileSource: u32, OwnerTag: u32, }; pub const ETW_PMC_COUNTER_OWNERSHIP_STATUS = extern struct { ProcessorNumber: u32, NumberOfCounters: u32, CounterOwners: [1]ETW_PMC_COUNTER_OWNER, }; pub const EVENT_TRACE = extern struct { Header: EVENT_TRACE_HEADER, InstanceId: u32, ParentInstanceId: u32, ParentGuid: Guid, MofData: ?*anyopaque, MofLength: u32, Anonymous: extern union { ClientContext: u32, BufferContext: ETW_BUFFER_CONTEXT, }, }; pub const PEVENT_TRACE_BUFFER_CALLBACKW = fn( Logfile: ?*EVENT_TRACE_LOGFILEW, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PEVENT_TRACE_BUFFER_CALLBACKA = fn( Logfile: ?*EVENT_TRACE_LOGFILEA, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PEVENT_CALLBACK = fn( pEvent: ?*EVENT_TRACE, ) callconv(@import("std").os.windows.WINAPI) void; pub const PEVENT_RECORD_CALLBACK = fn( EventRecord: ?*EVENT_RECORD, ) callconv(@import("std").os.windows.WINAPI) void; pub const WMIDPREQUEST = fn( RequestCode: WMIDPREQUESTCODE, RequestContext: ?*anyopaque, BufferSize: ?*u32, Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const EVENT_TRACE_LOGFILEW = extern struct { LogFileName: ?PWSTR, LoggerName: ?PWSTR, CurrentTime: i64, BuffersRead: u32, Anonymous1: extern union { LogFileMode: u32, ProcessTraceMode: u32, }, CurrentEvent: EVENT_TRACE, LogfileHeader: TRACE_LOGFILE_HEADER, BufferCallback: ?PEVENT_TRACE_BUFFER_CALLBACKW, BufferSize: u32, Filled: u32, EventsLost: u32, Anonymous2: extern union { EventCallback: ?PEVENT_CALLBACK, EventRecordCallback: ?PEVENT_RECORD_CALLBACK, }, IsKernelTrace: u32, Context: ?*anyopaque, }; pub const EVENT_TRACE_LOGFILEA = extern struct { LogFileName: ?PSTR, LoggerName: ?PSTR, CurrentTime: i64, BuffersRead: u32, Anonymous1: extern union { LogFileMode: u32, ProcessTraceMode: u32, }, CurrentEvent: EVENT_TRACE, LogfileHeader: TRACE_LOGFILE_HEADER, BufferCallback: ?PEVENT_TRACE_BUFFER_CALLBACKA, BufferSize: u32, Filled: u32, EventsLost: u32, Anonymous2: extern union { EventCallback: ?PEVENT_CALLBACK, EventRecordCallback: ?PEVENT_RECORD_CALLBACK, }, IsKernelTrace: u32, Context: ?*anyopaque, }; pub const ENABLE_TRACE_PARAMETERS_V1 = extern struct { Version: u32, EnableProperty: u32, ControlFlags: u32, SourceId: Guid, EnableFilterDesc: ?*EVENT_FILTER_DESCRIPTOR, }; pub const ENABLE_TRACE_PARAMETERS = extern struct { Version: u32, EnableProperty: u32, ControlFlags: u32, SourceId: Guid, EnableFilterDesc: ?*EVENT_FILTER_DESCRIPTOR, FilterDescCount: u32, }; pub const TRACE_QUERY_INFO_CLASS = enum(i32) { TraceGuidQueryList = 0, TraceGuidQueryInfo = 1, TraceGuidQueryProcess = 2, TraceStackTracingInfo = 3, TraceSystemTraceEnableFlagsInfo = 4, TraceSampledProfileIntervalInfo = 5, TraceProfileSourceConfigInfo = 6, TraceProfileSourceListInfo = 7, TracePmcEventListInfo = 8, TracePmcCounterListInfo = 9, TraceSetDisallowList = 10, TraceVersionInfo = 11, TraceGroupQueryList = 12, TraceGroupQueryInfo = 13, TraceDisallowListQuery = 14, TraceInfoReserved15 = 15, TracePeriodicCaptureStateListInfo = 16, TracePeriodicCaptureStateInfo = 17, TraceProviderBinaryTracking = 18, TraceMaxLoggersQuery = 19, TraceLbrConfigurationInfo = 20, TraceLbrEventListInfo = 21, TraceMaxPmcCounterQuery = 22, TraceStreamCount = 23, TraceStackCachingInfo = 24, TracePmcCounterOwners = 25, TraceUnifiedStackCachingInfo = 26, MaxTraceSetInfoClass = 27, }; pub const TraceGuidQueryList = TRACE_QUERY_INFO_CLASS.TraceGuidQueryList; pub const TraceGuidQueryInfo = TRACE_QUERY_INFO_CLASS.TraceGuidQueryInfo; pub const TraceGuidQueryProcess = TRACE_QUERY_INFO_CLASS.TraceGuidQueryProcess; pub const TraceStackTracingInfo = TRACE_QUERY_INFO_CLASS.TraceStackTracingInfo; pub const TraceSystemTraceEnableFlagsInfo = TRACE_QUERY_INFO_CLASS.TraceSystemTraceEnableFlagsInfo; pub const TraceSampledProfileIntervalInfo = TRACE_QUERY_INFO_CLASS.TraceSampledProfileIntervalInfo; pub const TraceProfileSourceConfigInfo = TRACE_QUERY_INFO_CLASS.TraceProfileSourceConfigInfo; pub const TraceProfileSourceListInfo = TRACE_QUERY_INFO_CLASS.TraceProfileSourceListInfo; pub const TracePmcEventListInfo = TRACE_QUERY_INFO_CLASS.TracePmcEventListInfo; pub const TracePmcCounterListInfo = TRACE_QUERY_INFO_CLASS.TracePmcCounterListInfo; pub const TraceSetDisallowList = TRACE_QUERY_INFO_CLASS.TraceSetDisallowList; pub const TraceVersionInfo = TRACE_QUERY_INFO_CLASS.TraceVersionInfo; pub const TraceGroupQueryList = TRACE_QUERY_INFO_CLASS.TraceGroupQueryList; pub const TraceGroupQueryInfo = TRACE_QUERY_INFO_CLASS.TraceGroupQueryInfo; pub const TraceDisallowListQuery = TRACE_QUERY_INFO_CLASS.TraceDisallowListQuery; pub const TraceInfoReserved15 = TRACE_QUERY_INFO_CLASS.TraceInfoReserved15; pub const TracePeriodicCaptureStateListInfo = TRACE_QUERY_INFO_CLASS.TracePeriodicCaptureStateListInfo; pub const TracePeriodicCaptureStateInfo = TRACE_QUERY_INFO_CLASS.TracePeriodicCaptureStateInfo; pub const TraceProviderBinaryTracking = TRACE_QUERY_INFO_CLASS.TraceProviderBinaryTracking; pub const TraceMaxLoggersQuery = TRACE_QUERY_INFO_CLASS.TraceMaxLoggersQuery; pub const TraceLbrConfigurationInfo = TRACE_QUERY_INFO_CLASS.TraceLbrConfigurationInfo; pub const TraceLbrEventListInfo = TRACE_QUERY_INFO_CLASS.TraceLbrEventListInfo; pub const TraceMaxPmcCounterQuery = TRACE_QUERY_INFO_CLASS.TraceMaxPmcCounterQuery; pub const TraceStreamCount = TRACE_QUERY_INFO_CLASS.TraceStreamCount; pub const TraceStackCachingInfo = TRACE_QUERY_INFO_CLASS.TraceStackCachingInfo; pub const TracePmcCounterOwners = TRACE_QUERY_INFO_CLASS.TracePmcCounterOwners; pub const TraceUnifiedStackCachingInfo = TRACE_QUERY_INFO_CLASS.TraceUnifiedStackCachingInfo; pub const MaxTraceSetInfoClass = TRACE_QUERY_INFO_CLASS.MaxTraceSetInfoClass; pub const CLASSIC_EVENT_ID = extern struct { EventGuid: Guid, Type: u8, Reserved: [7]u8, }; pub const TRACE_STACK_CACHING_INFO = extern struct { Enabled: BOOLEAN, CacheSize: u32, BucketCount: u32, }; pub const TRACE_PROFILE_INTERVAL = extern struct { Source: u32, Interval: u32, }; pub const TRACE_VERSION_INFO = extern struct { EtwTraceProcessingVersion: u32, Reserved: u32, }; pub const TRACE_PERIODIC_CAPTURE_STATE_INFO = extern struct { CaptureStateFrequencyInSeconds: u32, ProviderCount: u16, Reserved: u16, }; pub const ETW_PROCESS_HANDLE_INFO_TYPE = enum(i32) { PartitionInformation = 1, PartitionInformationV2 = 2, LastDroppedTimes = 3, ProcessHandleInfoMax = 4, }; pub const EtwQueryPartitionInformation = ETW_PROCESS_HANDLE_INFO_TYPE.PartitionInformation; pub const EtwQueryPartitionInformationV2 = ETW_PROCESS_HANDLE_INFO_TYPE.PartitionInformationV2; pub const EtwQueryLastDroppedTimes = ETW_PROCESS_HANDLE_INFO_TYPE.LastDroppedTimes; pub const EtwQueryProcessHandleInfoMax = ETW_PROCESS_HANDLE_INFO_TYPE.ProcessHandleInfoMax; pub const ETW_TRACE_PARTITION_INFORMATION = extern struct { PartitionId: Guid, ParentId: Guid, QpcOffsetFromRoot: i64, PartitionType: u32, }; pub const ETW_TRACE_PARTITION_INFORMATION_V2 = extern struct { QpcOffsetFromRoot: i64, PartitionType: u32, PartitionId: ?PWSTR, ParentId: ?PWSTR, }; pub const EVENT_DATA_DESCRIPTOR = extern struct { Ptr: u64, Size: u32, Anonymous: extern union { Reserved: u32, Anonymous: extern struct { Type: u8, Reserved1: u8, Reserved2: u16, }, }, }; pub const EVENT_DESCRIPTOR = extern struct { Id: u16, Version: u8, Channel: u8, Level: u8, Opcode: u8, Task: u16, Keyword: u64, }; pub const EVENT_FILTER_DESCRIPTOR = extern struct { Ptr: u64, Size: u32, Type: u32, }; pub const EVENT_FILTER_HEADER = extern struct { Id: u16, Version: u8, Reserved: [5]u8, InstanceId: u64, Size: u32, NextOffset: u32, }; pub const EVENT_FILTER_EVENT_ID = extern struct { FilterIn: BOOLEAN, Reserved: u8, Count: u16, Events: [1]u16, }; pub const EVENT_FILTER_EVENT_NAME = extern struct { MatchAnyKeyword: u64, MatchAllKeyword: u64, Level: u8, FilterIn: BOOLEAN, NameCount: u16, Names: [1]u8, }; pub const EVENT_FILTER_LEVEL_KW = extern struct { MatchAnyKeyword: u64, MatchAllKeyword: u64, Level: u8, FilterIn: BOOLEAN, }; pub const EVENT_INFO_CLASS = enum(i32) { EventProviderBinaryTrackInfo = 0, EventProviderSetReserved1 = 1, EventProviderSetTraits = 2, EventProviderUseDescriptorType = 3, MaxEventInfo = 4, }; pub const EventProviderBinaryTrackInfo = EVENT_INFO_CLASS.EventProviderBinaryTrackInfo; pub const EventProviderSetReserved1 = EVENT_INFO_CLASS.EventProviderSetReserved1; pub const EventProviderSetTraits = EVENT_INFO_CLASS.EventProviderSetTraits; pub const EventProviderUseDescriptorType = EVENT_INFO_CLASS.EventProviderUseDescriptorType; pub const MaxEventInfo = EVENT_INFO_CLASS.MaxEventInfo; pub const PENABLECALLBACK = fn( SourceId: ?*const Guid, IsEnabled: ENABLECALLBACK_ENABLED_STATE, Level: u8, MatchAnyKeyword: u64, MatchAllKeyword: u64, FilterData: ?*EVENT_FILTER_DESCRIPTOR, CallbackContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const EVENT_HEADER_EXTENDED_DATA_ITEM = extern struct { Reserved1: u16, ExtType: u16, Anonymous: extern struct { _bitfield: u16, }, DataSize: u16, DataPtr: u64, }; pub const EVENT_EXTENDED_ITEM_INSTANCE = extern struct { InstanceId: u32, ParentInstanceId: u32, ParentGuid: Guid, }; pub const EVENT_EXTENDED_ITEM_RELATED_ACTIVITYID = extern struct { RelatedActivityId: Guid, }; pub const EVENT_EXTENDED_ITEM_TS_ID = extern struct { SessionId: u32, }; pub const EVENT_EXTENDED_ITEM_STACK_TRACE32 = extern struct { MatchId: u64, Address: [1]u32, }; pub const EVENT_EXTENDED_ITEM_STACK_TRACE64 = extern struct { MatchId: u64, Address: [1]u64, }; pub const EVENT_EXTENDED_ITEM_STACK_KEY32 = extern struct { MatchId: u64, StackKey: u32, Padding: u32, }; pub const EVENT_EXTENDED_ITEM_STACK_KEY64 = extern struct { MatchId: u64, StackKey: u64, }; pub const EVENT_EXTENDED_ITEM_PEBS_INDEX = extern struct { PebsIndex: u64, }; pub const EVENT_EXTENDED_ITEM_PMC_COUNTERS = extern struct { Counter: [1]u64, }; pub const EVENT_EXTENDED_ITEM_PROCESS_START_KEY = extern struct { ProcessStartKey: u64, }; pub const EVENT_EXTENDED_ITEM_EVENT_KEY = extern struct { Key: u64, }; pub const EVENT_HEADER = extern struct { Size: u16, HeaderType: u16, Flags: u16, EventProperty: u16, ThreadId: u32, ProcessId: u32, TimeStamp: LARGE_INTEGER, ProviderId: Guid, EventDescriptor: EVENT_DESCRIPTOR, Anonymous: extern union { Anonymous: extern struct { KernelTime: u32, UserTime: u32, }, ProcessorTime: u64, }, ActivityId: Guid, }; pub const EVENT_RECORD = extern struct { EventHeader: EVENT_HEADER, BufferContext: ETW_BUFFER_CONTEXT, ExtendedDataCount: u16, UserDataLength: u16, ExtendedData: ?*EVENT_HEADER_EXTENDED_DATA_ITEM, UserData: ?*anyopaque, UserContext: ?*anyopaque, }; pub const ETW_PROVIDER_TRAIT_TYPE = enum(i32) { TypeGroup = 1, DecodeGuid = 2, TypeMax = 3, }; pub const EtwProviderTraitTypeGroup = ETW_PROVIDER_TRAIT_TYPE.TypeGroup; pub const EtwProviderTraitDecodeGuid = ETW_PROVIDER_TRAIT_TYPE.DecodeGuid; pub const EtwProviderTraitTypeMax = ETW_PROVIDER_TRAIT_TYPE.TypeMax; pub const EVENTSECURITYOPERATION = enum(i32) { SetDACL = 0, SetSACL = 1, AddDACL = 2, AddSACL = 3, Max = 4, }; pub const EventSecuritySetDACL = EVENTSECURITYOPERATION.SetDACL; pub const EventSecuritySetSACL = EVENTSECURITYOPERATION.SetSACL; pub const EventSecurityAddDACL = EVENTSECURITYOPERATION.AddDACL; pub const EventSecurityAddSACL = EVENTSECURITYOPERATION.AddSACL; pub const EventSecurityMax = EVENTSECURITYOPERATION.Max; pub const EVENT_MAP_ENTRY = extern struct { OutputOffset: u32, Anonymous: extern union { Value: u32, InputOffset: u32, }, }; pub const MAP_FLAGS = enum(i32) { MANIFEST_VALUEMAP = 1, MANIFEST_BITMAP = 2, MANIFEST_PATTERNMAP = 4, WBEM_VALUEMAP = 8, WBEM_BITMAP = 16, WBEM_FLAG = 32, WBEM_NO_MAP = 64, }; pub const EVENTMAP_INFO_FLAG_MANIFEST_VALUEMAP = MAP_FLAGS.MANIFEST_VALUEMAP; pub const EVENTMAP_INFO_FLAG_MANIFEST_BITMAP = MAP_FLAGS.MANIFEST_BITMAP; pub const EVENTMAP_INFO_FLAG_MANIFEST_PATTERNMAP = MAP_FLAGS.MANIFEST_PATTERNMAP; pub const EVENTMAP_INFO_FLAG_WBEM_VALUEMAP = MAP_FLAGS.WBEM_VALUEMAP; pub const EVENTMAP_INFO_FLAG_WBEM_BITMAP = MAP_FLAGS.WBEM_BITMAP; pub const EVENTMAP_INFO_FLAG_WBEM_FLAG = MAP_FLAGS.WBEM_FLAG; pub const EVENTMAP_INFO_FLAG_WBEM_NO_MAP = MAP_FLAGS.WBEM_NO_MAP; pub const MAP_VALUETYPE = enum(i32) { ULONG = 0, STRING = 1, }; pub const EVENTMAP_ENTRY_VALUETYPE_ULONG = MAP_VALUETYPE.ULONG; pub const EVENTMAP_ENTRY_VALUETYPE_STRING = MAP_VALUETYPE.STRING; pub const EVENT_MAP_INFO = extern struct { NameOffset: u32, Flag: MAP_FLAGS, EntryCount: u32, Anonymous: extern union { MapEntryValueType: MAP_VALUETYPE, FormatStringOffset: u32, }, MapEntryArray: [1]EVENT_MAP_ENTRY, }; pub const _TDH_IN_TYPE = enum(i32) { NULL = 0, UNICODESTRING = 1, ANSISTRING = 2, INT8 = 3, UINT8 = 4, INT16 = 5, UINT16 = 6, INT32 = 7, UINT32 = 8, INT64 = 9, UINT64 = 10, FLOAT = 11, DOUBLE = 12, BOOLEAN = 13, BINARY = 14, GUID = 15, POINTER = 16, FILETIME = 17, SYSTEMTIME = 18, SID = 19, HEXINT32 = 20, HEXINT64 = 21, MANIFEST_COUNTEDSTRING = 22, MANIFEST_COUNTEDANSISTRING = 23, RESERVED24 = 24, MANIFEST_COUNTEDBINARY = 25, COUNTEDSTRING = 300, COUNTEDANSISTRING = 301, REVERSEDCOUNTEDSTRING = 302, REVERSEDCOUNTEDANSISTRING = 303, NONNULLTERMINATEDSTRING = 304, NONNULLTERMINATEDANSISTRING = 305, UNICODECHAR = 306, ANSICHAR = 307, SIZET = 308, HEXDUMP = 309, WBEMSID = 310, }; pub const TDH_INTYPE_NULL = _TDH_IN_TYPE.NULL; pub const TDH_INTYPE_UNICODESTRING = _TDH_IN_TYPE.UNICODESTRING; pub const TDH_INTYPE_ANSISTRING = _TDH_IN_TYPE.ANSISTRING; pub const TDH_INTYPE_INT8 = _TDH_IN_TYPE.INT8; pub const TDH_INTYPE_UINT8 = _TDH_IN_TYPE.UINT8; pub const TDH_INTYPE_INT16 = _TDH_IN_TYPE.INT16; pub const TDH_INTYPE_UINT16 = _TDH_IN_TYPE.UINT16; pub const TDH_INTYPE_INT32 = _TDH_IN_TYPE.INT32; pub const TDH_INTYPE_UINT32 = _TDH_IN_TYPE.UINT32; pub const TDH_INTYPE_INT64 = _TDH_IN_TYPE.INT64; pub const TDH_INTYPE_UINT64 = _TDH_IN_TYPE.UINT64; pub const TDH_INTYPE_FLOAT = _TDH_IN_TYPE.FLOAT; pub const TDH_INTYPE_DOUBLE = _TDH_IN_TYPE.DOUBLE; pub const TDH_INTYPE_BOOLEAN = _TDH_IN_TYPE.BOOLEAN; pub const TDH_INTYPE_BINARY = _TDH_IN_TYPE.BINARY; pub const TDH_INTYPE_GUID = _TDH_IN_TYPE.GUID; pub const TDH_INTYPE_POINTER = _TDH_IN_TYPE.POINTER; pub const TDH_INTYPE_FILETIME = _TDH_IN_TYPE.FILETIME; pub const TDH_INTYPE_SYSTEMTIME = _TDH_IN_TYPE.SYSTEMTIME; pub const TDH_INTYPE_SID = _TDH_IN_TYPE.SID; pub const TDH_INTYPE_HEXINT32 = _TDH_IN_TYPE.HEXINT32; pub const TDH_INTYPE_HEXINT64 = _TDH_IN_TYPE.HEXINT64; pub const TDH_INTYPE_MANIFEST_COUNTEDSTRING = _TDH_IN_TYPE.MANIFEST_COUNTEDSTRING; pub const TDH_INTYPE_MANIFEST_COUNTEDANSISTRING = _TDH_IN_TYPE.MANIFEST_COUNTEDANSISTRING; pub const TDH_INTYPE_RESERVED24 = _TDH_IN_TYPE.RESERVED24; pub const TDH_INTYPE_MANIFEST_COUNTEDBINARY = _TDH_IN_TYPE.MANIFEST_COUNTEDBINARY; pub const TDH_INTYPE_COUNTEDSTRING = _TDH_IN_TYPE.COUNTEDSTRING; pub const TDH_INTYPE_COUNTEDANSISTRING = _TDH_IN_TYPE.COUNTEDANSISTRING; pub const TDH_INTYPE_REVERSEDCOUNTEDSTRING = _TDH_IN_TYPE.REVERSEDCOUNTEDSTRING; pub const TDH_INTYPE_REVERSEDCOUNTEDANSISTRING = _TDH_IN_TYPE.REVERSEDCOUNTEDANSISTRING; pub const TDH_INTYPE_NONNULLTERMINATEDSTRING = _TDH_IN_TYPE.NONNULLTERMINATEDSTRING; pub const TDH_INTYPE_NONNULLTERMINATEDANSISTRING = _TDH_IN_TYPE.NONNULLTERMINATEDANSISTRING; pub const TDH_INTYPE_UNICODECHAR = _TDH_IN_TYPE.UNICODECHAR; pub const TDH_INTYPE_ANSICHAR = _TDH_IN_TYPE.ANSICHAR; pub const TDH_INTYPE_SIZET = _TDH_IN_TYPE.SIZET; pub const TDH_INTYPE_HEXDUMP = _TDH_IN_TYPE.HEXDUMP; pub const TDH_INTYPE_WBEMSID = _TDH_IN_TYPE.WBEMSID; pub const _TDH_OUT_TYPE = enum(i32) { NULL = 0, STRING = 1, DATETIME = 2, BYTE = 3, UNSIGNEDBYTE = 4, SHORT = 5, UNSIGNEDSHORT = 6, INT = 7, UNSIGNEDINT = 8, LONG = 9, UNSIGNEDLONG = 10, FLOAT = 11, DOUBLE = 12, BOOLEAN = 13, GUID = 14, HEXBINARY = 15, HEXINT8 = 16, HEXINT16 = 17, HEXINT32 = 18, HEXINT64 = 19, PID = 20, TID = 21, PORT = 22, IPV4 = 23, IPV6 = 24, SOCKETADDRESS = 25, CIMDATETIME = 26, ETWTIME = 27, XML = 28, ERRORCODE = 29, WIN32ERROR = 30, NTSTATUS = 31, HRESULT = 32, CULTURE_INSENSITIVE_DATETIME = 33, JSON = 34, UTF8 = 35, PKCS7_WITH_TYPE_INFO = 36, CODE_POINTER = 37, DATETIME_UTC = 38, REDUCEDSTRING = 300, NOPRINT = 301, }; pub const TDH_OUTTYPE_NULL = _TDH_OUT_TYPE.NULL; pub const TDH_OUTTYPE_STRING = _TDH_OUT_TYPE.STRING; pub const TDH_OUTTYPE_DATETIME = _TDH_OUT_TYPE.DATETIME; pub const TDH_OUTTYPE_BYTE = _TDH_OUT_TYPE.BYTE; pub const TDH_OUTTYPE_UNSIGNEDBYTE = _TDH_OUT_TYPE.UNSIGNEDBYTE; pub const TDH_OUTTYPE_SHORT = _TDH_OUT_TYPE.SHORT; pub const TDH_OUTTYPE_UNSIGNEDSHORT = _TDH_OUT_TYPE.UNSIGNEDSHORT; pub const TDH_OUTTYPE_INT = _TDH_OUT_TYPE.INT; pub const TDH_OUTTYPE_UNSIGNEDINT = _TDH_OUT_TYPE.UNSIGNEDINT; pub const TDH_OUTTYPE_LONG = _TDH_OUT_TYPE.LONG; pub const TDH_OUTTYPE_UNSIGNEDLONG = _TDH_OUT_TYPE.UNSIGNEDLONG; pub const TDH_OUTTYPE_FLOAT = _TDH_OUT_TYPE.FLOAT; pub const TDH_OUTTYPE_DOUBLE = _TDH_OUT_TYPE.DOUBLE; pub const TDH_OUTTYPE_BOOLEAN = _TDH_OUT_TYPE.BOOLEAN; pub const TDH_OUTTYPE_GUID = _TDH_OUT_TYPE.GUID; pub const TDH_OUTTYPE_HEXBINARY = _TDH_OUT_TYPE.HEXBINARY; pub const TDH_OUTTYPE_HEXINT8 = _TDH_OUT_TYPE.HEXINT8; pub const TDH_OUTTYPE_HEXINT16 = _TDH_OUT_TYPE.HEXINT16; pub const TDH_OUTTYPE_HEXINT32 = _TDH_OUT_TYPE.HEXINT32; pub const TDH_OUTTYPE_HEXINT64 = _TDH_OUT_TYPE.HEXINT64; pub const TDH_OUTTYPE_PID = _TDH_OUT_TYPE.PID; pub const TDH_OUTTYPE_TID = _TDH_OUT_TYPE.TID; pub const TDH_OUTTYPE_PORT = _TDH_OUT_TYPE.PORT; pub const TDH_OUTTYPE_IPV4 = _TDH_OUT_TYPE.IPV4; pub const TDH_OUTTYPE_IPV6 = _TDH_OUT_TYPE.IPV6; pub const TDH_OUTTYPE_SOCKETADDRESS = _TDH_OUT_TYPE.SOCKETADDRESS; pub const TDH_OUTTYPE_CIMDATETIME = _TDH_OUT_TYPE.CIMDATETIME; pub const TDH_OUTTYPE_ETWTIME = _TDH_OUT_TYPE.ETWTIME; pub const TDH_OUTTYPE_XML = _TDH_OUT_TYPE.XML; pub const TDH_OUTTYPE_ERRORCODE = _TDH_OUT_TYPE.ERRORCODE; pub const TDH_OUTTYPE_WIN32ERROR = _TDH_OUT_TYPE.WIN32ERROR; pub const TDH_OUTTYPE_NTSTATUS = _TDH_OUT_TYPE.NTSTATUS; pub const TDH_OUTTYPE_HRESULT = _TDH_OUT_TYPE.HRESULT; pub const TDH_OUTTYPE_CULTURE_INSENSITIVE_DATETIME = _TDH_OUT_TYPE.CULTURE_INSENSITIVE_DATETIME; pub const TDH_OUTTYPE_JSON = _TDH_OUT_TYPE.JSON; pub const TDH_OUTTYPE_UTF8 = _TDH_OUT_TYPE.UTF8; pub const TDH_OUTTYPE_PKCS7_WITH_TYPE_INFO = _TDH_OUT_TYPE.PKCS7_WITH_TYPE_INFO; pub const TDH_OUTTYPE_CODE_POINTER = _TDH_OUT_TYPE.CODE_POINTER; pub const TDH_OUTTYPE_DATETIME_UTC = _TDH_OUT_TYPE.DATETIME_UTC; pub const TDH_OUTTYPE_REDUCEDSTRING = _TDH_OUT_TYPE.REDUCEDSTRING; pub const TDH_OUTTYPE_NOPRINT = _TDH_OUT_TYPE.NOPRINT; pub const PROPERTY_FLAGS = enum(i32) { Struct = 1, ParamLength = 2, ParamCount = 4, WBEMXmlFragment = 8, ParamFixedLength = 16, ParamFixedCount = 32, HasTags = 64, HasCustomSchema = 128, }; pub const PropertyStruct = PROPERTY_FLAGS.Struct; pub const PropertyParamLength = PROPERTY_FLAGS.ParamLength; pub const PropertyParamCount = PROPERTY_FLAGS.ParamCount; pub const PropertyWBEMXmlFragment = PROPERTY_FLAGS.WBEMXmlFragment; pub const PropertyParamFixedLength = PROPERTY_FLAGS.ParamFixedLength; pub const PropertyParamFixedCount = PROPERTY_FLAGS.ParamFixedCount; pub const PropertyHasTags = PROPERTY_FLAGS.HasTags; pub const PropertyHasCustomSchema = PROPERTY_FLAGS.HasCustomSchema; pub const EVENT_PROPERTY_INFO = extern struct { Flags: PROPERTY_FLAGS, NameOffset: u32, Anonymous1: extern union { pub const _customSchemaType = extern struct { InType: u16, OutType: u16, CustomSchemaOffset: u32, }; pub const _nonStructType = extern struct { InType: u16, OutType: u16, MapNameOffset: u32, }; pub const _structType = extern struct { StructStartIndex: u16, NumOfStructMembers: u16, padding: u32, }; nonStructType: _nonStructType, structType: _structType, customSchemaType: _customSchemaType, }, Anonymous2: extern union { count: u16, countPropertyIndex: u16, }, Anonymous3: extern union { length: u16, lengthPropertyIndex: u16, }, Anonymous4: extern union { Reserved: u32, Anonymous: extern struct { _bitfield: u32, }, }, }; pub const DECODING_SOURCE = enum(i32) { XMLFile = 0, Wbem = 1, WPP = 2, Tlg = 3, Max = 4, }; pub const DecodingSourceXMLFile = DECODING_SOURCE.XMLFile; pub const DecodingSourceWbem = DECODING_SOURCE.Wbem; pub const DecodingSourceWPP = DECODING_SOURCE.WPP; pub const DecodingSourceTlg = DECODING_SOURCE.Tlg; pub const DecodingSourceMax = DECODING_SOURCE.Max; pub const TEMPLATE_FLAGS = enum(i32) { EVENT_DATA = 1, USER_DATA = 2, CONTROL_GUID = 4, }; pub const TEMPLATE_EVENT_DATA = TEMPLATE_FLAGS.EVENT_DATA; pub const TEMPLATE_USER_DATA = TEMPLATE_FLAGS.USER_DATA; pub const TEMPLATE_CONTROL_GUID = TEMPLATE_FLAGS.CONTROL_GUID; pub const TRACE_EVENT_INFO = extern struct { ProviderGuid: Guid, EventGuid: Guid, EventDescriptor: EVENT_DESCRIPTOR, DecodingSource: DECODING_SOURCE, ProviderNameOffset: u32, LevelNameOffset: u32, ChannelNameOffset: u32, KeywordsNameOffset: u32, TaskNameOffset: u32, OpcodeNameOffset: u32, EventMessageOffset: u32, ProviderMessageOffset: u32, BinaryXMLOffset: u32, BinaryXMLSize: u32, Anonymous1: extern union { EventNameOffset: u32, ActivityIDNameOffset: u32, }, Anonymous2: extern union { EventAttributesOffset: u32, RelatedActivityIDNameOffset: u32, }, PropertyCount: u32, TopLevelPropertyCount: u32, Anonymous3: extern union { Flags: TEMPLATE_FLAGS, Anonymous: extern struct { _bitfield: u32, }, }, EventPropertyInfoArray: [1]EVENT_PROPERTY_INFO, }; pub const PROPERTY_DATA_DESCRIPTOR = extern struct { PropertyName: u64, ArrayIndex: u32, Reserved: u32, }; pub const PAYLOAD_OPERATOR = enum(i32) { EQ = 0, NE = 1, LE = 2, GT = 3, LT = 4, GE = 5, BETWEEN = 6, NOTBETWEEN = 7, MODULO = 8, CONTAINS = 20, DOESNTCONTAIN = 21, IS = 30, ISNOT = 31, INVALID = 32, }; pub const PAYLOADFIELD_EQ = PAYLOAD_OPERATOR.EQ; pub const PAYLOADFIELD_NE = PAYLOAD_OPERATOR.NE; pub const PAYLOADFIELD_LE = PAYLOAD_OPERATOR.LE; pub const PAYLOADFIELD_GT = PAYLOAD_OPERATOR.GT; pub const PAYLOADFIELD_LT = PAYLOAD_OPERATOR.LT; pub const PAYLOADFIELD_GE = PAYLOAD_OPERATOR.GE; pub const PAYLOADFIELD_BETWEEN = PAYLOAD_OPERATOR.BETWEEN; pub const PAYLOADFIELD_NOTBETWEEN = PAYLOAD_OPERATOR.NOTBETWEEN; pub const PAYLOADFIELD_MODULO = PAYLOAD_OPERATOR.MODULO; pub const PAYLOADFIELD_CONTAINS = PAYLOAD_OPERATOR.CONTAINS; pub const PAYLOADFIELD_DOESNTCONTAIN = PAYLOAD_OPERATOR.DOESNTCONTAIN; pub const PAYLOADFIELD_IS = PAYLOAD_OPERATOR.IS; pub const PAYLOADFIELD_ISNOT = PAYLOAD_OPERATOR.ISNOT; pub const PAYLOADFIELD_INVALID = PAYLOAD_OPERATOR.INVALID; pub const PAYLOAD_FILTER_PREDICATE = extern struct { FieldName: ?PWSTR, CompareOp: u16, Value: ?PWSTR, }; pub const PROVIDER_FILTER_INFO = extern struct { Id: u8, Version: u8, MessageOffset: u32, Reserved: u32, PropertyCount: u32, EventPropertyInfoArray: [1]EVENT_PROPERTY_INFO, }; pub const EVENT_FIELD_TYPE = enum(i32) { KeywordInformation = 0, LevelInformation = 1, ChannelInformation = 2, TaskInformation = 3, OpcodeInformation = 4, InformationMax = 5, }; pub const EventKeywordInformation = EVENT_FIELD_TYPE.KeywordInformation; pub const EventLevelInformation = EVENT_FIELD_TYPE.LevelInformation; pub const EventChannelInformation = EVENT_FIELD_TYPE.ChannelInformation; pub const EventTaskInformation = EVENT_FIELD_TYPE.TaskInformation; pub const EventOpcodeInformation = EVENT_FIELD_TYPE.OpcodeInformation; pub const EventInformationMax = EVENT_FIELD_TYPE.InformationMax; pub const PROVIDER_FIELD_INFO = extern struct { NameOffset: u32, DescriptionOffset: u32, Value: u64, }; pub const PROVIDER_FIELD_INFOARRAY = extern struct { NumberOfElements: u32, FieldType: EVENT_FIELD_TYPE, FieldInfoArray: [1]PROVIDER_FIELD_INFO, }; pub const TRACE_PROVIDER_INFO = extern struct { ProviderGuid: Guid, SchemaSource: u32, ProviderNameOffset: u32, }; pub const PROVIDER_ENUMERATION_INFO = extern struct { NumberOfProviders: u32, Reserved: u32, TraceProviderInfoArray: [1]TRACE_PROVIDER_INFO, }; pub const PROVIDER_EVENT_INFO = extern struct { NumberOfEvents: u32, Reserved: u32, EventDescriptorsArray: [1]EVENT_DESCRIPTOR, }; pub const TDH_CONTEXT_TYPE = enum(i32) { WPP_TMFFILE = 0, WPP_TMFSEARCHPATH = 1, WPP_GMT = 2, POINTERSIZE = 3, PDB_PATH = 4, MAXIMUM = 5, }; pub const TDH_CONTEXT_WPP_TMFFILE = TDH_CONTEXT_TYPE.WPP_TMFFILE; pub const TDH_CONTEXT_WPP_TMFSEARCHPATH = TDH_CONTEXT_TYPE.WPP_TMFSEARCHPATH; pub const TDH_CONTEXT_WPP_GMT = TDH_CONTEXT_TYPE.WPP_GMT; pub const TDH_CONTEXT_POINTERSIZE = TDH_CONTEXT_TYPE.POINTERSIZE; pub const TDH_CONTEXT_PDB_PATH = TDH_CONTEXT_TYPE.PDB_PATH; pub const TDH_CONTEXT_MAXIMUM = TDH_CONTEXT_TYPE.MAXIMUM; pub const TDH_CONTEXT = extern struct { ParameterValue: u64, ParameterType: TDH_CONTEXT_TYPE, ParameterSize: u32, }; const CLSID_CTraceRelogger_Value = @import("../../zig.zig").Guid.initString("7b40792d-05ff-44c4-9058-f440c71f17d4"); pub const CLSID_CTraceRelogger = &CLSID_CTraceRelogger_Value; // TODO: this type is limited to platform 'windows6.1' const IID_ITraceEvent_Value = @import("../../zig.zig").Guid.initString("8cc97f40-9028-4ff3-9b62-7d1f79ca7bcb"); pub const IID_ITraceEvent = &IID_ITraceEvent_Value; pub const ITraceEvent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Clone: fn( self: *const ITraceEvent, NewEvent: ?*?*ITraceEvent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUserContext: fn( self: *const ITraceEvent, UserContext: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetEventRecord: fn( self: *const ITraceEvent, EventRecord: ?*?*EVENT_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPayload: fn( self: *const ITraceEvent, Payload: [*:0]u8, PayloadSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetEventDescriptor: fn( self: *const ITraceEvent, EventDescriptor: ?*const EVENT_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProcessId: fn( self: *const ITraceEvent, ProcessId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProcessorIndex: fn( self: *const ITraceEvent, ProcessorIndex: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetThreadId: fn( self: *const ITraceEvent, ThreadId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetThreadTimes: fn( self: *const ITraceEvent, KernelTime: u32, UserTime: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetActivityId: fn( self: *const ITraceEvent, ActivityId: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetTimeStamp: fn( self: *const ITraceEvent, TimeStamp: ?*LARGE_INTEGER, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetProviderId: fn( self: *const ITraceEvent, ProviderId: ?*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 ITraceEvent_Clone(self: *const T, NewEvent: ?*?*ITraceEvent) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).Clone(@ptrCast(*const ITraceEvent, self), NewEvent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_GetUserContext(self: *const T, UserContext: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).GetUserContext(@ptrCast(*const ITraceEvent, self), UserContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_GetEventRecord(self: *const T, EventRecord: ?*?*EVENT_RECORD) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).GetEventRecord(@ptrCast(*const ITraceEvent, self), EventRecord); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetPayload(self: *const T, Payload: [*:0]u8, PayloadSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetPayload(@ptrCast(*const ITraceEvent, self), Payload, PayloadSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetEventDescriptor(self: *const T, EventDescriptor: ?*const EVENT_DESCRIPTOR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetEventDescriptor(@ptrCast(*const ITraceEvent, self), EventDescriptor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetProcessId(self: *const T, ProcessId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetProcessId(@ptrCast(*const ITraceEvent, self), ProcessId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetProcessorIndex(self: *const T, ProcessorIndex: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetProcessorIndex(@ptrCast(*const ITraceEvent, self), ProcessorIndex); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetThreadId(self: *const T, ThreadId: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetThreadId(@ptrCast(*const ITraceEvent, self), ThreadId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetThreadTimes(self: *const T, KernelTime: u32, UserTime: u32) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetThreadTimes(@ptrCast(*const ITraceEvent, self), KernelTime, UserTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetActivityId(self: *const T, ActivityId: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetActivityId(@ptrCast(*const ITraceEvent, self), ActivityId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetTimeStamp(self: *const T, TimeStamp: ?*LARGE_INTEGER) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetTimeStamp(@ptrCast(*const ITraceEvent, self), TimeStamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEvent_SetProviderId(self: *const T, ProviderId: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEvent.VTable, self.vtable).SetProviderId(@ptrCast(*const ITraceEvent, self), ProviderId); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITraceEventCallback_Value = @import("../../zig.zig").Guid.initString("3ed25501-593f-43e9-8f38-3ab46f5a4a52"); pub const IID_ITraceEventCallback = &IID_ITraceEventCallback_Value; pub const ITraceEventCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnBeginProcessTrace: fn( self: *const ITraceEventCallback, HeaderEvent: ?*ITraceEvent, Relogger: ?*ITraceRelogger, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnFinalizeProcessTrace: fn( self: *const ITraceEventCallback, Relogger: ?*ITraceRelogger, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnEvent: fn( self: *const ITraceEventCallback, Event: ?*ITraceEvent, Relogger: ?*ITraceRelogger, ) 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 ITraceEventCallback_OnBeginProcessTrace(self: *const T, HeaderEvent: ?*ITraceEvent, Relogger: ?*ITraceRelogger) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEventCallback.VTable, self.vtable).OnBeginProcessTrace(@ptrCast(*const ITraceEventCallback, self), HeaderEvent, Relogger); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEventCallback_OnFinalizeProcessTrace(self: *const T, Relogger: ?*ITraceRelogger) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEventCallback.VTable, self.vtable).OnFinalizeProcessTrace(@ptrCast(*const ITraceEventCallback, self), Relogger); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceEventCallback_OnEvent(self: *const T, Event: ?*ITraceEvent, Relogger: ?*ITraceRelogger) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceEventCallback.VTable, self.vtable).OnEvent(@ptrCast(*const ITraceEventCallback, self), Event, Relogger); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_ITraceRelogger_Value = @import("../../zig.zig").Guid.initString("f754ad43-3bcc-4286-8009-9c5da214e84e"); pub const IID_ITraceRelogger = &IID_ITraceRelogger_Value; pub const ITraceRelogger = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AddLogfileTraceStream: fn( self: *const ITraceRelogger, LogfileName: ?BSTR, UserContext: ?*anyopaque, TraceHandle: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddRealtimeTraceStream: fn( self: *const ITraceRelogger, LoggerName: ?BSTR, UserContext: ?*anyopaque, TraceHandle: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RegisterCallback: fn( self: *const ITraceRelogger, Callback: ?*ITraceEventCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Inject: fn( self: *const ITraceRelogger, Event: ?*ITraceEvent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateEventInstance: fn( self: *const ITraceRelogger, TraceHandle: u64, Flags: u32, Event: ?*?*ITraceEvent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessTrace: fn( self: *const ITraceRelogger, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOutputFilename: fn( self: *const ITraceRelogger, LogfileName: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCompressionMode: fn( self: *const ITraceRelogger, CompressionMode: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Cancel: fn( self: *const ITraceRelogger, ) 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 ITraceRelogger_AddLogfileTraceStream(self: *const T, LogfileName: ?BSTR, UserContext: ?*anyopaque, TraceHandle: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).AddLogfileTraceStream(@ptrCast(*const ITraceRelogger, self), LogfileName, UserContext, TraceHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_AddRealtimeTraceStream(self: *const T, LoggerName: ?BSTR, UserContext: ?*anyopaque, TraceHandle: ?*u64) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).AddRealtimeTraceStream(@ptrCast(*const ITraceRelogger, self), LoggerName, UserContext, TraceHandle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_RegisterCallback(self: *const T, Callback: ?*ITraceEventCallback) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).RegisterCallback(@ptrCast(*const ITraceRelogger, self), Callback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_Inject(self: *const T, Event: ?*ITraceEvent) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).Inject(@ptrCast(*const ITraceRelogger, self), Event); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_CreateEventInstance(self: *const T, TraceHandle: u64, Flags: u32, Event: ?*?*ITraceEvent) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).CreateEventInstance(@ptrCast(*const ITraceRelogger, self), TraceHandle, Flags, Event); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_ProcessTrace(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).ProcessTrace(@ptrCast(*const ITraceRelogger, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_SetOutputFilename(self: *const T, LogfileName: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).SetOutputFilename(@ptrCast(*const ITraceRelogger, self), LogfileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_SetCompressionMode(self: *const T, CompressionMode: BOOLEAN) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).SetCompressionMode(@ptrCast(*const ITraceRelogger, self), CompressionMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn ITraceRelogger_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const ITraceRelogger.VTable, self.vtable).Cancel(@ptrCast(*const ITraceRelogger, self)); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (80) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn StartTraceW( TraceHandle: ?*u64, InstanceName: ?[*:0]const u16, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn StartTraceA( TraceHandle: ?*u64, InstanceName: ?[*:0]const u8, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn StopTraceW( TraceHandle: u64, InstanceName: ?[*:0]const u16, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn StopTraceA( TraceHandle: u64, InstanceName: ?[*:0]const u8, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn QueryTraceW( TraceHandle: u64, InstanceName: ?[*:0]const u16, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn QueryTraceA( TraceHandle: u64, InstanceName: ?[*:0]const u8, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn UpdateTraceW( TraceHandle: u64, InstanceName: ?[*:0]const u16, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn UpdateTraceA( TraceHandle: u64, InstanceName: ?[*:0]const u8, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn FlushTraceW( TraceHandle: u64, InstanceName: ?[*:0]const u16, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn FlushTraceA( TraceHandle: u64, InstanceName: ?[*:0]const u8, Properties: ?*EVENT_TRACE_PROPERTIES, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn ControlTraceW( TraceHandle: u64, InstanceName: ?[*:0]const u16, Properties: ?*EVENT_TRACE_PROPERTIES, ControlCode: EVENT_TRACE_CONTROL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn ControlTraceA( TraceHandle: u64, InstanceName: ?[*:0]const u8, Properties: ?*EVENT_TRACE_PROPERTIES, ControlCode: EVENT_TRACE_CONTROL, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn QueryAllTracesW( PropertyArray: [*]?*EVENT_TRACE_PROPERTIES, PropertyArrayCount: u32, LoggerCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn QueryAllTracesA( PropertyArray: [*]?*EVENT_TRACE_PROPERTIES, PropertyArrayCount: u32, LoggerCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn EnableTrace( Enable: u32, EnableFlag: u32, EnableLevel: u32, ControlGuid: ?*const Guid, TraceHandle: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EnableTraceEx( ProviderId: ?*const Guid, SourceId: ?*const Guid, TraceHandle: u64, IsEnabled: u32, Level: u8, MatchAnyKeyword: u64, MatchAllKeyword: u64, EnableProperty: u32, EnableFilterDesc: ?*EVENT_FILTER_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "ADVAPI32" fn EnableTraceEx2( TraceHandle: u64, ProviderId: ?*const Guid, ControlCode: u32, Level: u8, MatchAnyKeyword: u64, MatchAllKeyword: u64, Timeout: u32, EnableParameters: ?*ENABLE_TRACE_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EnumerateTraceGuidsEx( TraceQueryInfoClass: TRACE_QUERY_INFO_CLASS, // TODO: what to do with BytesParamIndex 2? InBuffer: ?*anyopaque, InBufferSize: u32, // TODO: what to do with BytesParamIndex 4? OutBuffer: ?*anyopaque, OutBufferSize: u32, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "ADVAPI32" fn TraceSetInformation( SessionHandle: u64, InformationClass: TRACE_QUERY_INFO_CLASS, // TODO: what to do with BytesParamIndex 3? TraceInformation: ?*anyopaque, InformationLength: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "ADVAPI32" fn TraceQueryInformation( SessionHandle: u64, InformationClass: TRACE_QUERY_INFO_CLASS, // TODO: what to do with BytesParamIndex 3? TraceInformation: ?*anyopaque, InformationLength: u32, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn CreateTraceInstanceId( RegHandle: ?HANDLE, InstInfo: ?*EVENT_INSTANCE_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn TraceEvent( TraceHandle: u64, EventTrace: ?*EVENT_TRACE_HEADER, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn TraceEventInstance( TraceHandle: u64, EventTrace: ?*EVENT_INSTANCE_HEADER, InstInfo: ?*EVENT_INSTANCE_INFO, ParentInstInfo: ?*EVENT_INSTANCE_INFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn RegisterTraceGuidsW( RequestAddress: ?WMIDPREQUEST, RequestContext: ?*anyopaque, ControlGuid: ?*const Guid, GuidCount: u32, TraceGuidReg: ?[*]TRACE_GUID_REGISTRATION, MofImagePath: ?[*:0]const u16, MofResourceName: ?[*:0]const u16, RegistrationHandle: ?*u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn RegisterTraceGuidsA( RequestAddress: ?WMIDPREQUEST, RequestContext: ?*anyopaque, ControlGuid: ?*const Guid, GuidCount: u32, TraceGuidReg: ?[*]TRACE_GUID_REGISTRATION, MofImagePath: ?[*:0]const u8, MofResourceName: ?[*:0]const u8, RegistrationHandle: ?*u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn EnumerateTraceGuids( GuidPropertiesArray: [*]?*TRACE_GUID_PROPERTIES, PropertyArrayCount: u32, GuidCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn UnregisterTraceGuids( RegistrationHandle: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn GetTraceLoggerHandle( Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u64; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn GetTraceEnableLevel( TraceHandle: u64, ) callconv(@import("std").os.windows.WINAPI) u8; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn GetTraceEnableFlags( TraceHandle: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn OpenTraceW( Logfile: ?*EVENT_TRACE_LOGFILEW, ) callconv(@import("std").os.windows.WINAPI) u64; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn ProcessTrace( HandleArray: [*]u64, HandleCount: u32, StartTime: ?*FILETIME, EndTime: ?*FILETIME, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn CloseTrace( TraceHandle: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "ADVAPI32" fn QueryTraceProcessingHandle( ProcessingHandle: u64, InformationClass: ETW_PROCESS_HANDLE_INFO_TYPE, InBuffer: ?*anyopaque, InBufferSize: u32, OutBuffer: ?*anyopaque, OutBufferSize: u32, ReturnLength: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn OpenTraceA( Logfile: ?*EVENT_TRACE_LOGFILEA, ) callconv(@import("std").os.windows.WINAPI) u64; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn SetTraceCallback( pGuid: ?*const Guid, EventCallback: ?PEVENT_CALLBACK, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "ADVAPI32" fn RemoveTraceCallback( pGuid: ?*const Guid, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn TraceMessage( LoggerHandle: u64, MessageFlags: TRACE_MESSAGE_FLAGS, MessageGuid: ?*const Guid, MessageNumber: u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "ADVAPI32" fn TraceMessageVa( LoggerHandle: u64, MessageFlags: TRACE_MESSAGE_FLAGS, MessageGuid: ?*const Guid, MessageNumber: u16, MessageArgList: ?*i8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventRegister( ProviderId: ?*const Guid, EnableCallback: ?PENABLECALLBACK, CallbackContext: ?*anyopaque, RegHandle: ?*u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventUnregister( RegHandle: u64, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "ADVAPI32" fn EventSetInformation( RegHandle: u64, InformationClass: EVENT_INFO_CLASS, // TODO: what to do with BytesParamIndex 3? EventInformation: ?*anyopaque, InformationLength: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventEnabled( RegHandle: u64, EventDescriptor: ?*const EVENT_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) BOOLEAN; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventProviderEnabled( RegHandle: u64, Level: u8, Keyword: u64, ) callconv(@import("std").os.windows.WINAPI) BOOLEAN; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventWrite( RegHandle: u64, EventDescriptor: ?*const EVENT_DESCRIPTOR, UserDataCount: u32, UserData: ?[*]EVENT_DATA_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventWriteTransfer( RegHandle: u64, EventDescriptor: ?*const EVENT_DESCRIPTOR, ActivityId: ?*const Guid, RelatedActivityId: ?*const Guid, UserDataCount: u32, UserData: ?[*]EVENT_DATA_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "ADVAPI32" fn EventWriteEx( RegHandle: u64, EventDescriptor: ?*const EVENT_DESCRIPTOR, Filter: u64, Flags: u32, ActivityId: ?*const Guid, RelatedActivityId: ?*const Guid, UserDataCount: u32, UserData: ?[*]EVENT_DATA_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventWriteString( RegHandle: u64, Level: u8, Keyword: u64, String: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventActivityIdControl( ControlCode: u32, ActivityId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventAccessControl( Guid: ?*Guid, Operation: u32, Sid: ?PSID, Rights: u32, AllowOrDeny: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventAccessQuery( Guid: ?*Guid, // TODO: what to do with BytesParamIndex 2? Buffer: ?*SECURITY_DESCRIPTOR, BufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "ADVAPI32" fn EventAccessRemove( Guid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.1' pub extern "tdh" fn TdhCreatePayloadFilter( ProviderGuid: ?*const Guid, EventDescriptor: ?*const EVENT_DESCRIPTOR, EventMatchANY: BOOLEAN, PayloadPredicateCount: u32, PayloadPredicates: [*]PAYLOAD_FILTER_PREDICATE, PayloadFilter: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.1' pub extern "tdh" fn TdhDeletePayloadFilter( PayloadFilter: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.1' pub extern "tdh" fn TdhAggregatePayloadFilters( PayloadFilterCount: u32, PayloadFilterPtrs: [*]?*anyopaque, EventMatchALLFlags: ?[*]BOOLEAN, EventFilterDescriptor: ?*EVENT_FILTER_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.1' pub extern "tdh" fn TdhCleanupPayloadEventFilterDescriptor( EventFilterDescriptor: ?*EVENT_FILTER_DESCRIPTOR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhGetEventInformation( Event: ?*EVENT_RECORD, TdhContextCount: u32, TdhContext: ?[*]TDH_CONTEXT, // TODO: what to do with BytesParamIndex 4? Buffer: ?*TRACE_EVENT_INFO, BufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhGetEventMapInformation( pEvent: ?*EVENT_RECORD, pMapName: ?PWSTR, // TODO: what to do with BytesParamIndex 3? pBuffer: ?*EVENT_MAP_INFO, pBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhGetPropertySize( pEvent: ?*EVENT_RECORD, TdhContextCount: u32, pTdhContext: ?[*]TDH_CONTEXT, PropertyDataCount: u32, pPropertyData: [*]PROPERTY_DATA_DESCRIPTOR, pPropertySize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhGetProperty( pEvent: ?*EVENT_RECORD, TdhContextCount: u32, pTdhContext: ?[*]TDH_CONTEXT, PropertyDataCount: u32, pPropertyData: [*]PROPERTY_DATA_DESCRIPTOR, BufferSize: u32, // TODO: what to do with BytesParamIndex 5? pBuffer: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhEnumerateProviders( // TODO: what to do with BytesParamIndex 1? pBuffer: ?*PROVIDER_ENUMERATION_INFO, pBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "tdh" fn TdhEnumerateProvidersForDecodingSource( filter: DECODING_SOURCE, // TODO: what to do with BytesParamIndex 2? buffer: ?*PROVIDER_ENUMERATION_INFO, bufferSize: u32, bufferRequired: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhQueryProviderFieldInformation( pGuid: ?*Guid, EventFieldValue: u64, EventFieldType: EVENT_FIELD_TYPE, // TODO: what to do with BytesParamIndex 4? pBuffer: ?*PROVIDER_FIELD_INFOARRAY, pBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "TDH" fn TdhEnumerateProviderFieldInformation( pGuid: ?*Guid, EventFieldType: EVENT_FIELD_TYPE, // TODO: what to do with BytesParamIndex 3? pBuffer: ?*PROVIDER_FIELD_INFOARRAY, pBufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "tdh" fn TdhEnumerateProviderFilters( Guid: ?*Guid, TdhContextCount: u32, TdhContext: ?[*]TDH_CONTEXT, FilterCount: ?*u32, // TODO: what to do with BytesParamIndex 5? Buffer: ?*?*PROVIDER_FILTER_INFO, BufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "TDH" fn TdhLoadManifest( Manifest: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "TDH" fn TdhLoadManifestFromMemory( // TODO: what to do with BytesParamIndex 1? pData: ?*const anyopaque, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "TDH" fn TdhUnloadManifest( Manifest: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "TDH" fn TdhUnloadManifestFromMemory( // TODO: what to do with BytesParamIndex 1? pData: ?*const anyopaque, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "TDH" fn TdhFormatProperty( EventInfo: ?*TRACE_EVENT_INFO, MapInfo: ?*EVENT_MAP_INFO, PointerSize: u32, PropertyInType: u16, PropertyOutType: u16, PropertyLength: u16, UserDataLength: u16, // TODO: what to do with BytesParamIndex 6? UserData: ?*u8, BufferSize: ?*u32, // TODO: what to do with BytesParamIndex 8? Buffer: ?[*]u16, UserDataConsumed: ?*u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhOpenDecodingHandle( Handle: ?*TDH_HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhSetDecodingParameter( Handle: TDH_HANDLE, TdhContext: ?*TDH_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhGetDecodingParameter( Handle: TDH_HANDLE, TdhContext: ?*TDH_CONTEXT, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhGetWppProperty( Handle: TDH_HANDLE, EventRecord: ?*EVENT_RECORD, PropertyName: ?PWSTR, BufferSize: ?*u32, // TODO: what to do with BytesParamIndex 3? Buffer: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhGetWppMessage( Handle: TDH_HANDLE, EventRecord: ?*EVENT_RECORD, BufferSize: ?*u32, // TODO: what to do with BytesParamIndex 2? Buffer: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhCloseDecodingHandle( Handle: TDH_HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "tdh" fn TdhLoadManifestFromBinary( BinaryPath: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.1' pub extern "TDH" fn TdhEnumerateManifestProviderEvents( ProviderGuid: ?*Guid, // TODO: what to do with BytesParamIndex 2? Buffer: ?*PROVIDER_EVENT_INFO, BufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.1' pub extern "TDH" fn TdhGetManifestEventInformation( ProviderGuid: ?*Guid, EventDescriptor: ?*EVENT_DESCRIPTOR, // TODO: what to do with BytesParamIndex 3? Buffer: ?*TRACE_EVENT_INFO, BufferSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "ADVAPI32" fn CveEventWrite( CveId: ?[*:0]const u16, AdditionalDetails: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) i32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (11) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { pub const PEVENT_TRACE_BUFFER_CALLBACK = thismodule.PEVENT_TRACE_BUFFER_CALLBACKA; pub const EVENT_TRACE_LOGFILE = thismodule.EVENT_TRACE_LOGFILEA; pub const StartTrace = thismodule.StartTraceA; pub const StopTrace = thismodule.StopTraceA; pub const QueryTrace = thismodule.QueryTraceA; pub const UpdateTrace = thismodule.UpdateTraceA; pub const FlushTrace = thismodule.FlushTraceA; pub const ControlTrace = thismodule.ControlTraceA; pub const QueryAllTraces = thismodule.QueryAllTracesA; pub const RegisterTraceGuids = thismodule.RegisterTraceGuidsA; pub const OpenTrace = thismodule.OpenTraceA; }, .wide => struct { pub const PEVENT_TRACE_BUFFER_CALLBACK = thismodule.PEVENT_TRACE_BUFFER_CALLBACKW; pub const EVENT_TRACE_LOGFILE = thismodule.EVENT_TRACE_LOGFILEW; pub const StartTrace = thismodule.StartTraceW; pub const StopTrace = thismodule.StopTraceW; pub const QueryTrace = thismodule.QueryTraceW; pub const UpdateTrace = thismodule.UpdateTraceW; pub const FlushTrace = thismodule.FlushTraceW; pub const ControlTrace = thismodule.ControlTraceW; pub const QueryAllTraces = thismodule.QueryAllTracesW; pub const RegisterTraceGuids = thismodule.RegisterTraceGuidsW; pub const OpenTrace = thismodule.OpenTraceW; }, .unspecified => if (@import("builtin").is_test) struct { pub const PEVENT_TRACE_BUFFER_CALLBACK = *opaque{}; pub const EVENT_TRACE_LOGFILE = *opaque{}; pub const StartTrace = *opaque{}; pub const StopTrace = *opaque{}; pub const QueryTrace = *opaque{}; pub const UpdateTrace = *opaque{}; pub const FlushTrace = *opaque{}; pub const ControlTrace = *opaque{}; pub const QueryAllTraces = *opaque{}; pub const RegisterTraceGuids = *opaque{}; pub const OpenTrace = *opaque{}; } else struct { pub const PEVENT_TRACE_BUFFER_CALLBACK = @compileError("'PEVENT_TRACE_BUFFER_CALLBACK' requires that UNICODE be set to true or false in the root module"); pub const EVENT_TRACE_LOGFILE = @compileError("'EVENT_TRACE_LOGFILE' requires that UNICODE be set to true or false in the root module"); pub const StartTrace = @compileError("'StartTrace' requires that UNICODE be set to true or false in the root module"); pub const StopTrace = @compileError("'StopTrace' requires that UNICODE be set to true or false in the root module"); pub const QueryTrace = @compileError("'QueryTrace' requires that UNICODE be set to true or false in the root module"); pub const UpdateTrace = @compileError("'UpdateTrace' requires that UNICODE be set to true or false in the root module"); pub const FlushTrace = @compileError("'FlushTrace' requires that UNICODE be set to true or false in the root module"); pub const ControlTrace = @compileError("'ControlTrace' requires that UNICODE be set to true or false in the root module"); pub const QueryAllTraces = @compileError("'QueryAllTraces' requires that UNICODE be set to true or false in the root module"); pub const RegisterTraceGuids = @compileError("'RegisterTraceGuids' requires that UNICODE be set to true or false in the root module"); pub const OpenTrace = @compileError("'OpenTrace' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (13) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOLEAN = @import("../../foundation.zig").BOOLEAN; const BSTR = @import("../../foundation.zig").BSTR; const FILETIME = @import("../../foundation.zig").FILETIME; const HANDLE = @import("../../foundation.zig").HANDLE; const HRESULT = @import("../../foundation.zig").HRESULT; const IUnknown = @import("../../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../../foundation.zig").LARGE_INTEGER; 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 TIME_ZONE_INFORMATION = @import("../../system/time.zig").TIME_ZONE_INFORMATION; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PEVENT_TRACE_BUFFER_CALLBACKW")) { _ = PEVENT_TRACE_BUFFER_CALLBACKW; } if (@hasDecl(@This(), "PEVENT_TRACE_BUFFER_CALLBACKA")) { _ = PEVENT_TRACE_BUFFER_CALLBACKA; } if (@hasDecl(@This(), "PEVENT_CALLBACK")) { _ = PEVENT_CALLBACK; } if (@hasDecl(@This(), "PEVENT_RECORD_CALLBACK")) { _ = PEVENT_RECORD_CALLBACK; } if (@hasDecl(@This(), "WMIDPREQUEST")) { _ = WMIDPREQUEST; } if (@hasDecl(@This(), "PENABLECALLBACK")) { _ = PENABLECALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/diagnostics/etw.zig
const std = @import("std"); const testing = std.testing; const input_file = "input02.txt"; const PasswordPolicy = struct { pos_1: u32, pos_2: u32, char: u8, }; fn parsePasswordPolicy(policy: []const u8) !PasswordPolicy { var iter = std.mem.split(policy, " "); const pos_1_pos_2 = iter.next() orelse return error.FormatError; const char = iter.next() orelse return error.FormatError; var iter_pos_1_pos_2 = std.mem.split(pos_1_pos_2, "-"); const pos_1 = iter_pos_1_pos_2.next() orelse return error.FormatError; const pos_2 = iter_pos_1_pos_2.next() orelse return error.FormatError; return PasswordPolicy{ .pos_1 = try std.fmt.parseInt(u32, pos_1, 10), .pos_2 = try std.fmt.parseInt(u32, pos_2, 10), .char = if (char.len == 1) char[0] else return error.CharacterTooLong, }; } test "parsePasswordPolicy" { const policy = "1-3 a"; const parsed = try parsePasswordPolicy(policy); try testing.expectEqual(parsed.pos_1, 1); try testing.expectEqual(parsed.pos_2, 3); try testing.expectEqual(parsed.char, 'a'); } const Line = struct { policy: PasswordPolicy, password: []const u8, pub fn isValid(self: Line) bool { const pos_1_match = self.password[self.policy.pos_1 - 1] == self.policy.char; const pos_2_match = self.password[self.policy.pos_2 - 1] == self.policy.char; return pos_1_match != pos_2_match; } }; fn parseLine(line: []const u8) !Line { var iter = std.mem.split(line, ":"); const policy = iter.next() orelse return error.FormatError; const password = iter.next() orelse return error.FormatError; return Line{ .policy = try parsePasswordPolicy(policy), .password = password[1..], }; } test "parseLine" { const line = "1-3 a: abcde"; const parsed = try parseLine(line); try testing.expectEqualSlices(u8, parsed.password, "<PASSWORD>"); try testing.expectEqual(parsed.policy.pos_1, 1); try testing.expectEqual(parsed.policy.pos_2, 3); try testing.expectEqual(parsed.policy.char, 'a'); } pub fn main() !void { var file = try std.fs.cwd().openFile(input_file, .{}); defer file.close(); var valid_passwords: u32 = 0; const reader = file.reader(); var buf: [1024]u8 = undefined; while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { const parsed = try parseLine(line); if (parsed.isValid()) valid_passwords += 1; } std.debug.print("valid passwords: {}\n", .{valid_passwords}); }
src/02_2.zig
const AtomicOrder = @import("builtin").AtomicOrder; const Vector = @import("vector.zig").Vector(f32); const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const warn = std.debug.warn; const allocator = std.heap.page_allocator; const Math= std.math; const json = std.json; const ArrayList = std.ArrayList; const SELF_INTERSECTION_THRESHOLD: f32 = 0.001; const Ray = struct { point: Vector, vector: Vector, }; const ObjectType = enum { Plane, Sphere, }; const Scene = struct { const Camera = struct { point: Vector, vector: Vector, fov: f32, }; camera: Camera, const Object = struct { @"type": ObjectType, point: Vector, color: Vector, specular: f32, lambert: f32, ambient: f32, radius: f32 = 0.0, normal: Vector = Vector.new(0.0, 0.0, 0.0), }; objects: []const Object, lights: []const Vector, checker: []const Vector, }; fn closer(a: ?f32, b: ?f32) bool { if (a !=null and b != null) return (a.? > SELF_INTERSECTION_THRESHOLD and a.? < b.?); if (a == null and b == null) return false; return a orelse 0.0 > SELF_INTERSECTION_THRESHOLD; } const IntersectionResult = struct { distance: ?f32, object: ?Scene.Object, }; fn intersect_scene(ray: Ray, scene: Scene) IntersectionResult { var closest = IntersectionResult{ .distance = null, .object = null }; for (scene.objects) |object| { var distance = object_intersection(object, ray); if (closer(distance, closest.distance)) { closest = IntersectionResult{ .distance = distance, .object = object }; } } return closest; } fn object_intersection(object: Scene.Object, ray: Ray) ?f32 { return switch (object.type) { ObjectType.Sphere => blk: { const eye_to_center = object.point.subtract(ray.point); const v = eye_to_center.dot_product(ray.vector); const eo_dot = eye_to_center.dot_product(eye_to_center); const discriminant = (object.radius * object.radius) - eo_dot + (v * v); if (discriminant < 0.0) { return null; } const distance = v - Math.sqrt(discriminant); if (distance > SELF_INTERSECTION_THRESHOLD) { return distance; } break :blk null; }, ObjectType.Plane => blk: { const neg_norm = object.normal.negate(); const denom = neg_norm.dot_product(ray.vector); if (denom <= 0.0) { return null; } const interm = object.point.subtract(ray.point); break :blk interm.dot_product(neg_norm) / denom; }, else => null }; } fn plane_color_at(point_at_time: Vector, plane: Scene.Object, scene: Scene) Vector { // Point from plane origin // This is a complete hack to make up for my sad lack of lin alg. knowledge const from_origin = point_at_time.subtract(plane.point); const width = 2.0; var px = Vector.new(0.0, 1.0, 0.0); var py = Vector.new(0.0, 0.0, 1.0); if (plane.normal.z != 0.0) { py = Vector.new(1.0, 0.0, 1.0); } if (plane.normal.y != 0.0) { px = Vector.new(0.0, 0.0, 1.0); py = Vector.new(1.0, 0.0, 0.0); } const cx = px.dot_product(from_origin); const cy = py.dot_product(from_origin); const x_cond = (cx < 0.0 and @rem(cx, width) < -width / 2.0) or (cx > 0.0 and @rem(cx, width) < width / 2.0); const y_cond = (cy < 0.0 and @rem(cy, width) < -width / 2.0) or (cy > 0.0 and @rem(cy, width) < width / 2.0); if ((x_cond and !y_cond) or (y_cond and !x_cond)) { return scene.checker[0].scale(1.0); } return scene.checker[1].scale(1.0); } fn get_normal(object: Scene.Object, pos: Vector) Vector { return switch (object.type) { ObjectType.Sphere => pos.subtract(object.point).unit(), ObjectType.Plane => object.normal.unit(), else => Vector.new(0.0, 0.0, 0.0), }; } fn surface( ray: Ray, scene: Scene, object: Scene.Object, point_at_time: Vector, normal: Vector, depth: usize, ) Vector { var lambert = object.lambert; var specular = object.specular; var ambient = object.ambient; var b = switch (object.type) { ObjectType.Sphere => object.color.scale(1.0), ObjectType.Plane => plane_color_at(point_at_time, object, scene), }; var c = Vector.zero(); var lambert_amount: f32 = 0.0; if (lambert > 0.0) { for (scene.lights) |light| { if (!is_light_visible(point_at_time, scene, light)) { continue; } const contribution = light.subtract(point_at_time).unit().dot_product(normal); if (contribution > 0.0) { lambert_amount += contribution; } } } if (specular > 0.0) { const reflected_ray = Ray{ .point = point_at_time, .vector = ray.vector.reflect_through(normal), }; const reflected_color = trace(reflected_ray, scene, depth + 1); if (reflected_color != null) { c = c.add(reflected_color.?.scale(specular)); } } lambert_amount = min(lambert_amount, 1.0); return c.add3(b.scale(lambert_amount * lambert), b.scale(ambient)); } fn is_light_visible(point: Vector, scene: Scene, light: Vector) bool { const point_to_light_vector = light.subtract(point); const distance_to_light = point_to_light_vector.length(); const ray = Ray { .point = point, .vector = point_to_light_vector.unit(), }; const res = intersect_scene(ray, scene); return if (res.distance != null) res.distance.? > distance_to_light else true; } fn min(a: f32, b: f32) f32 { return if (a > b) b else a; } fn trace(ray: Ray, scene: Scene, depth: usize) ?Vector { if (depth > 20) { return null; } var dist_object = intersect_scene(ray, scene); return if (dist_object.distance) |distance| ( if (dist_object.object) |collision| blk: { const point_in_time = ray.point.add(ray.vector.scale(distance)); break :blk surface( ray, scene, collision, point_in_time, get_normal(collision, point_in_time), depth ); } else Vector.zero() ) else Vector.zero(); } const Sample = struct { color: Vector, x: u32, y: u32, }; fn f(v: var) f32 { return @intToFloat(f32, v); } fn u(v: var) u32 { return @floatToInt(u32, v); } fn log(comptime fmt: []const u8, args: var) void { if (std.Target.current.os.tag == .linux) { std.debug.warn("\n", .{}); std.debug.warn(fmt, args); } } fn render_rect(scene: Scene, canvas_width: u32, canvas_height: u32, x: u32, y: u32, width: u32, height: u32, index: u32) !void { const quality: f32 = 100.0; const clamp = Math.clamp; // var r = std.rand.DefaultPrng.init(seed); const w = @intToFloat(f32, width); const h = @intToFloat(f32, height); const camera = scene.camera; const eye_vector = camera.vector.subtract(camera.point).unit(); const vp_right = eye_vector.cross_product(Vector.up()).unit(); const vp_up = vp_right.cross_product(eye_vector).unit(); const fov_radians = Math.pi * (camera.fov / 2.0) / 180.0; const height_width_ratio = f(canvas_height) / f(canvas_width); //f(height) / f(width); const half_width = Math.tan(fov_radians); const half_height = height_width_ratio * half_width; const camera_width = half_width * 2.0; const camera_height = half_height * 2.0; const pixel_width = camera_width / f(canvas_width);//(f(width) - 1.0); const pixel_height = camera_height / f(canvas_height);//(f(height) - 1.0); var ray = Ray{ .point = camera.point, .vector = Vector.up(), }; var num = u(Math.round(w * h / 10000.0 * quality)); const new_samples = 1; const sample_area = w * h / f(new_samples); const columns = @round(w / Math.sqrt(sample_area)); const rows = @ceil(f(new_samples) / columns); const cell_width = w / columns; const cell_height = h / rows; // if ((width * height <= 100)) { if (index > 10) { var i: u32 = 0; const the_x = f(x + rand.?.random.uintLessThan(u32, u(cell_width))); const the_y = f(y + rand.?.random.uintLessThan(u32, u(cell_height))); // const the_x = f(x) + 0.5 * cell_width; // const the_y = f(y) + 0.5 * cell_height; const x_comp = vp_right.scale((the_x * pixel_width) - half_width); const y_comp = vp_up.scale((the_y * pixel_height) - half_height); ray.vector = eye_vector.add3(x_comp, y_comp).unit(); const color = trace(ray, scene, 0) orelse Vector.new(0.0, 0.0, 0.0); fill_rect(x, y, width, height, color, 5); } else { if (width > height) { var w_split: u32 = u(@floor(w * 0.5)); render_rect(scene, canvas_width, canvas_height, x, y, w_split, height, index + 1) catch unreachable; render_rect(scene, canvas_width, canvas_height, x + w_split, y, width - w_split, height, index + 1) catch unreachable; } else { var h_split: u32 = u(@floor(h * 0.5)); render_rect(scene, canvas_width, canvas_height, x, y, width, h_split, index + 1) catch unreachable; render_rect(scene, canvas_width, canvas_height, x, y + h_split, width, height - h_split, index + 1) catch unreachable; } } } fn fill_rect(x: u32, y: u32, w: u32, h: u32, color: Vector, resolution: u32) void { log("fill_rect({d}, {d}, {d}, {d})", .{x, y, w, h}); const clamp = Math.clamp; global_count += 1; if (std.Target.current.os.tag != .linux) { canvasFillStyle(u(color.x), u(color.y), u(color.z), 10); } else { log("canvasFillStyle({d}, {d}, {d}, {d});", .{u(color.x), u(color.y), u(color.z), 10}); } if (rand == null) { return; } const center_x = x + rand.?.random.uintLessThan(u32, w); const center_y = y + rand.?.random.uintLessThan(u32, h); const radius = Math.min(center_y, Math.min(center_x, resolution)); log("radius {d}", .{radius}); if (std.Target.current.os.tag != .linux) { canvasFillRect(center_x - radius, center_y - radius, radius, radius); } else { log("canvasFillRect({d}, {d}, {d}, {d});", .{center_x - radius, center_y - radius, radius, radius}); } } var global_count: u32 = 0; fn render(x: i32, y: i32, t: u32, width: u32, height: u32) !void { global_count = 0; var ft = f(t) / 1000; var scene = Scene{ .camera = Scene.Camera{ .point = Vector{ .x = f(x), .y = f(y), .z = 7 }, .vector = Vector{ .x = 0, .y = 0, .z = 0 }, .fov = 70 }, .objects = &[_]Scene.Object{ Scene.Object{ .type = ObjectType.Sphere, .point = Vector{ .x = Math.sin(ft) * 3.0, .y = Math.sin(ft) * 2.0, .z = Math.cos(ft) * 3.0 }, .color = Vector{ .x = 0, .y = 0, .z = 0 }, .specular = 0.699999988079071, .lambert = 0.5, .ambient = 0.30000001192092896, .radius = 1, .normal = Vector{ .x = 0, .y = 0, .z = 0 } }, Scene.Object{ .type = ObjectType.Sphere, .point = Vector{ .x = Math.sin(ft) * -3.0, .y = Math.cos(ft) * -3.0, .z = Math.cos(ft) * -2.0 }, .color = Vector{ .x = 0, .y = 0, .z = 0 }, .specular = 0.699999988079071, .lambert = 0.5, .ambient = 0.30000001192092896, .radius = 1, .normal = Vector{ .x = 0, .y = 0, .z = 0 } }, Scene.Object{ .type = ObjectType.Sphere, .point = Vector{ .x = 0, .y = 0, .z = 0 }, .color = Vector{ .x = 255, .y = 255, .z = 255 }, .specular = 0.25, .lambert = 0.7200000286102295, .ambient = 0.25999999046325684, .radius = 1.5, .normal = Vector{ .x = 0, .y = 0, .z = 0 } }, Scene.Object{ .type = ObjectType.Plane, .point = Vector{ .x = 0, .y = 5, .z = 0 }, .color = Vector{ .x = 200, .y = 200, .z = 200 }, .specular = 0, .lambert = 0.8999999761581421, .ambient = 0.20000000298023224, .radius = 0, .normal = Vector{ .x = 0, .y = -1, .z = 0 } }, Scene.Object{ .type = ObjectType.Plane, .point = Vector{ .x = 0, .y = -5, .z = 0 }, .color = Vector{ .x = 100, .y = 100, .z = 100 }, .specular = 0, .lambert = 0.8999999761581421, .ambient = 0.20000000298023224, .radius = 0, .normal = Vector{ .x = 0, .y = 1, .z = 0 } }, Scene.Object{ .type = ObjectType.Plane, .point = Vector{ .x = -5, .y = 0, .z = 0 }, .color = Vector{ .x = 100, .y = 100, .z = 100 }, .specular = 0, .lambert = 0.8999999761581421, .ambient = 0.20000000298023224, .radius = 0, .normal = Vector{ .x = 1, .y = 0, .z = 0 } }, Scene.Object{ .type = ObjectType.Plane, .point = Vector{ .x = 5, .y = 0, .z = 0 }, .color = Vector{ .x = 100, .y = 100, .z = 100 }, .specular = 0, .lambert = 0.8999999761581421, .ambient = 0.20000000298023224, .radius = 0, .normal = Vector{ .x = -1, .y = 0, .z = 0 } }, Scene.Object{ .type = ObjectType.Plane, .point = Vector{ .x = 0, .y = 0, .z = -12 }, .color = Vector{ .x = 100, .y = 100, .z = 100 }, .specular = 0, .lambert = 0.8999999761581421, .ambient = 0.20000000298023224, .radius = 0, .normal = Vector{ .x = 0, .y = 0, .z = 1 } }, Scene.Object{ .type = ObjectType.Plane, .point = Vector{ .x = 0, .y = 0, .z = 12 }, .color = Vector{ .x = 100, .y = 100, .z = 100 }, .specular = 0, .lambert = 0.8999999761581421, .ambient = 0.20000000298023224, .radius = 0, .normal = Vector{ .x = 0, .y = 0, .z = -1 } } }, .lights = &[_]Vector{ Vector{ .x = 3, .y = 3, .z = 5 } }, .checker = &[_]Vector{ Vector{ .x = 50, .y = 0, .z = 89 }, Vector{ .x = 92, .y = 209, .z = 92 } } }; //fill_rect(canvasMemoryPointer.?.ptr, width, 0, 0, 10, 10, Vector{.x = 100, .y = 200, .z = 50}); try render_rect(scene, width, height, 0, 0, width, height, 0); log("total count {d} ", .{ global_count }); } extern fn canvasFillRect(x: u32, y: u32, w: u32, h: u32) void; extern fn canvasFillStyle(r: u32, g: u32, b: u32, a: u32) void; var rand : ?std.rand.Xoroshiro128 = null; export fn setSeed(seed: u32) void { rand = std.rand.Xoroshiro128.init(seed); } export fn binding(x: i32, y: i32, t: u32, width: u32, height: u32) void { @fence(AtomicOrder.SeqCst); render(x, y, t, width, height) catch unreachable; // canvasFillStyle(10, 100, 200, 255); // canvasFillRect(10, 10, 100, 100); } const testing = std.testing; test "json.parse" { log("--------------------", .{}); setSeed(1412150); var result = render(0, 0, 0, 640, 480) catch unreachable; log("count {d}", .{ global_count }); // just testing if it fails // testing.expect(result.len == 3145728); //testing.expectEqual(result.len, 8000); }
zig/lib.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day21.txt"); pub fn main() !void { var timer = try std.time.Timer.start(); var board = try Board.init(data); print("🎁 Score: {}\n", .{board.part1()}); print("Day 21 - part 01 took {:15}ns\n", .{timer.lap()}); timer.reset(); print("🎁 Score: {}\n", .{board.part2()}); print("Day 21 - part 02 took {:15}ns\n", .{timer.lap()}); print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{}); } const Board = struct { player1 : u16, player2 : u16, pub fn init(input : []const u8) !@This() { var iterator = std.mem.tokenize(input, " \r\n"); var discard = iterator.next().?; discard = iterator.next().?; discard = iterator.next().?; discard = iterator.next().?; var player1 = try std.fmt.parseInt(u8, iterator.next().?, 10); discard = iterator.next().?; discard = iterator.next().?; discard = iterator.next().?; discard = iterator.next().?; var player2 = try std.fmt.parseInt(u8, iterator.next().?, 10); // -1 because the board is [1..10] but we count that as [0..10) so we can // use integer modulus to wrap the numbers. return Board { .player1 = player1 - 1, .player2 = player2 - 1, }; } fn roll(nextRoll : *u16, diceRolls : *u16) u16 { // +1 because the dice goes from [1..100] but we store it as [0..100) to use // integer modulus for the wrapping. const myRoll = nextRoll.* + 1; nextRoll.* += 1; nextRoll.* %= 100; diceRolls.* += 1; return myRoll; } pub fn part1(me : *const @This()) u32 { var player1 = me.player1; var player2 = me.player2; var player1Turn = true; var player1Score : u16 = 0; var player2Score : u16 = 0; var nextRoll : u16 = 0; var diceRolls : u16 = 0; while (player1Score < 1000 and player2Score < 1000) { var score = roll(&nextRoll, &diceRolls) + roll(&nextRoll, &diceRolls) + roll(&nextRoll, &diceRolls); if (player1Turn) { player1 += score; player1 %= 10; player1Score += player1 + 1; } else { player2 += score; player2 %= 10; player2Score += player2 + 1; } player1Turn = !player1Turn; } var score : u32 = std.math.min(player1Score, player2Score); return diceRolls * score; } fn dump(scores : [31]u64) void { print("Scores [", .{}); for (scores) |score| { print("{}, ", .{score}); } print("]\n", .{}); } pub fn part2(me : *const @This()) u64 { var state = Part2State.init(me.player1, me.player2); var result = state.play(); return std.math.max(result.player1Score, result.player2Score); } }; const Pair = struct { player1Score : u64, player2Score : u64, pub fn init() @This() { return Pair { .player1Score = 0, .player2Score = 0, }; } }; const Part2State = struct { player1Turn : bool, player1 : u16, player2 : u16, player1Score : u64, player2Score : u64, winMultiplier : u64, pub fn init(player1 : u16, player2 : u16) @This() { return Part2State { .player1Turn = true, .player1 = player1, .player2 = player2, .player1Score = 0, .player2Score = 0, .winMultiplier = 1, }; } pub fn play(me : *@This()) Pair { // These are the chances that any given 3 x rolls will end up on a given // result. const rollProbabilities = [10]u8 {0, 0, 0, 1, 3, 6, 7, 6, 3, 1}; var wins = Pair.init(); var index : u16 = 3; while (index < 10) : (index += 1) { var newState = me.*; // For each of the given chances that three rolls in [1..3], we increase // our multiplier for the win of the new state by that. For instance, we // can only roll 1, 1, 1 once, whereas we could roll 2, 1, 1 or 1, 2, 1 // or 1, 1, 2 (all moving our score on by 4 positions). newState.winMultiplier *= rollProbabilities[index]; if (newState.player1Turn) { newState.player1 += index; newState.player1 %= 10; newState.player1Score += newState.player1 + 1; } else { newState.player2 += index; newState.player2 %= 10; newState.player2Score += newState.player2 + 1; } if (newState.player1Turn and newState.player1Score >= 21) { wins.player1Score += newState.winMultiplier; } else if (!newState.player1Turn and newState.player2Score >= 21) { wins.player2Score += newState.winMultiplier; } else { newState.player1Turn = !newState.player1Turn; const result = newState.play(); wins.player1Score += result.player1Score; wins.player2Score += result.player2Score; } } return wins; } }; test "example" { const input = \\Player 1 starting position: 4 \\Player 2 starting position: 8 ; var board = try Board.init(input); try std.testing.expect(board.part1() == 739785); try std.testing.expect(board.part2() == 444356092776315); }
src/day21.zig
pub const WINBIO_MAX_STRING_LEN = @as(u32, 256); pub const WINBIO_SCP_VERSION_1 = @as(u32, 1); pub const WINBIO_SCP_RANDOM_SIZE_V1 = @as(u32, 32); pub const WINBIO_SCP_DIGEST_SIZE_V1 = @as(u32, 32); pub const WINBIO_SCP_CURVE_FIELD_SIZE_V1 = @as(u32, 32); pub const WINBIO_SCP_PUBLIC_KEY_SIZE_V1 = @as(u32, 65); pub const WINBIO_SCP_PRIVATE_KEY_SIZE_V1 = @as(u32, 32); pub const WINBIO_SCP_SIGNATURE_SIZE_V1 = @as(u32, 64); pub const WINBIO_SCP_ENCRYPTION_BLOCK_SIZE_V1 = @as(u32, 16); pub const WINBIO_SCP_ENCRYPTION_KEY_SIZE_V1 = @as(u32, 32); pub const WINBIO_BIR_ALIGN_SIZE = @as(u32, 8); //-------------------------------------------------------------------------------- // Section: Types (178) //-------------------------------------------------------------------------------- pub const WINBIO_SETTING_SOURCE = enum(u32) { INVALID = 0, DEFAULT = 1, LOCAL = 3, POLICY = 2, }; pub const WINBIO_SETTING_SOURCE_INVALID = WINBIO_SETTING_SOURCE.INVALID; pub const WINBIO_SETTING_SOURCE_DEFAULT = WINBIO_SETTING_SOURCE.DEFAULT; pub const WINBIO_SETTING_SOURCE_LOCAL = WINBIO_SETTING_SOURCE.LOCAL; pub const WINBIO_SETTING_SOURCE_POLICY = WINBIO_SETTING_SOURCE.POLICY; pub const WINBIO_COMPONENT = enum(u32) { SENSOR = 1, ENGINE = 2, STORAGE = 3, }; pub const WINBIO_COMPONENT_SENSOR = WINBIO_COMPONENT.SENSOR; pub const WINBIO_COMPONENT_ENGINE = WINBIO_COMPONENT.ENGINE; pub const WINBIO_COMPONENT_STORAGE = WINBIO_COMPONENT.STORAGE; pub const WINBIO_POOL = enum(u32) { SYSTEM = 1, PRIVATE = 2, }; pub const WINBIO_POOL_SYSTEM = WINBIO_POOL.SYSTEM; pub const WINBIO_POOL_PRIVATE = WINBIO_POOL.PRIVATE; pub const _WINIBIO_SENSOR_CONTEXT = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const _WINIBIO_ENGINE_CONTEXT = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const _WINIBIO_STORAGE_CONTEXT = extern struct { placeholder: usize, // TODO: why is this type empty? }; pub const WINBIO_VERSION = extern struct { MajorVersion: u32, MinorVersion: u32, }; pub const WINBIO_IDENTITY = extern struct { Type: u32, Value: extern union { Null: u32, Wildcard: u32, TemplateGuid: Guid, AccountSid: extern struct { Size: u32, Data: [68]u8, }, SecureId: [32]u8, }, }; pub const WINBIO_SECURE_CONNECTION_PARAMS = extern struct { PayloadSize: u32, Version: u16, Flags: u16, }; pub const WINBIO_SECURE_CONNECTION_DATA = extern struct { Size: u32, Version: u16, Flags: u16, ModelCertificateSize: u32, IntermediateCA1Size: u32, IntermediateCA2Size: u32, }; pub const WINBIO_BIR_DATA = extern struct { Size: u32, Offset: u32, }; pub const WINBIO_BIR = extern struct { HeaderBlock: WINBIO_BIR_DATA, StandardDataBlock: WINBIO_BIR_DATA, VendorDataBlock: WINBIO_BIR_DATA, SignatureBlock: WINBIO_BIR_DATA, }; pub const WINBIO_REGISTERED_FORMAT = extern struct { Owner: u16, Type: u16, }; pub const WINBIO_BIR_HEADER = extern struct { ValidFields: u16, HeaderVersion: u8, PatronHeaderVersion: u8, DataFlags: u8, Type: u32, Subtype: u8, Purpose: u8, DataQuality: i8, CreationDate: LARGE_INTEGER, ValidityPeriod: extern struct { BeginDate: LARGE_INTEGER, EndDate: LARGE_INTEGER, }, BiometricDataFormat: WINBIO_REGISTERED_FORMAT, ProductId: WINBIO_REGISTERED_FORMAT, }; pub const WINBIO_BDB_ANSI_381_HEADER = extern struct { RecordLength: u64, FormatIdentifier: u32, VersionNumber: u32, ProductId: WINBIO_REGISTERED_FORMAT, CaptureDeviceId: u16, ImageAcquisitionLevel: u16, HorizontalScanResolution: u16, VerticalScanResolution: u16, HorizontalImageResolution: u16, VerticalImageResolution: u16, ElementCount: u8, ScaleUnits: u8, PixelDepth: u8, ImageCompressionAlg: u8, Reserved: u16, }; pub const WINBIO_BDB_ANSI_381_RECORD = extern struct { BlockLength: u32, HorizontalLineLength: u16, VerticalLineLength: u16, Position: u8, CountOfViews: u8, ViewNumber: u8, ImageQuality: u8, ImpressionType: u8, Reserved: u8, }; pub const WINBIO_SECURE_BUFFER_HEADER_V1 = extern struct { Type: u32, Size: u32, Flags: u32, ValidationTag: u64, }; pub const WINBIO_EVENT = extern struct { Type: u32, Parameters: extern union { Unclaimed: extern struct { UnitId: u32, RejectDetail: u32, }, UnclaimedIdentify: extern struct { UnitId: u32, Identity: WINBIO_IDENTITY, SubFactor: u8, RejectDetail: u32, }, Error: extern struct { ErrorCode: HRESULT, }, }, }; pub const WINBIO_PRESENCE_PROPERTIES = extern union { FacialFeatures: extern struct { BoundingBox: RECT, Distance: i32, OpaqueEngineData: extern struct { AdapterId: Guid, Data: [77]u32, }, }, Iris: extern struct { EyeBoundingBox_1: RECT, EyeBoundingBox_2: RECT, PupilCenter_1: POINT, PupilCenter_2: POINT, Distance: i32, }, }; pub const WINBIO_PRESENCE = extern struct { Factor: u32, SubFactor: u8, Status: HRESULT, RejectDetail: u32, Identity: WINBIO_IDENTITY, TrackingId: u64, Ticket: u64, Properties: WINBIO_PRESENCE_PROPERTIES, Authorization: extern struct { Size: u32, Data: [32]u8, }, }; pub const WINBIO_BSP_SCHEMA = extern struct { BiometricFactor: u32, BspId: Guid, Description: [256]u16, Vendor: [256]u16, Version: WINBIO_VERSION, }; pub const WINBIO_UNIT_SCHEMA = extern struct { UnitId: u32, PoolType: u32, BiometricFactor: u32, SensorSubType: u32, Capabilities: u32, DeviceInstanceId: [256]u16, Description: [256]u16, Manufacturer: [256]u16, Model: [256]u16, SerialNumber: [256]u16, FirmwareVersion: WINBIO_VERSION, }; pub const WINBIO_STORAGE_SCHEMA = extern struct { BiometricFactor: u32, DatabaseId: Guid, DataFormat: Guid, Attributes: u32, FilePath: [256]u16, ConnectionString: [256]u16, }; pub const WINBIO_EXTENDED_SENSOR_INFO = extern struct { GenericSensorCapabilities: u32, Factor: u32, Specific: extern union { Null: u32, FacialFeatures: extern struct { FrameSize: RECT, FrameOffset: POINT, MandatoryOrientation: u32, HardwareInfo: extern struct { ColorSensorId: [260]u16, InfraredSensorId: [260]u16, InfraredSensorRotationAngle: u32, }, }, Fingerprint: extern struct { Reserved: u32, }, Iris: extern struct { FrameSize: RECT, FrameOffset: POINT, MandatoryOrientation: u32, }, Voice: extern struct { Reserved: u32, }, }, }; pub const WINBIO_EXTENDED_ENGINE_INFO = extern struct { GenericEngineCapabilities: u32, Factor: u32, Specific: extern union { Null: u32, FacialFeatures: extern struct { Capabilities: u32, EnrollmentRequirements: extern struct { Null: u32, }, }, Fingerprint: extern struct { Capabilities: u32, EnrollmentRequirements: extern struct { GeneralSamples: u32, Center: u32, TopEdge: u32, BottomEdge: u32, LeftEdge: u32, RightEdge: u32, }, }, Iris: extern struct { Capabilities: u32, EnrollmentRequirements: extern struct { Null: u32, }, }, Voice: extern struct { Capabilities: u32, EnrollmentRequirements: extern struct { Null: u32, }, }, }, }; pub const WINBIO_EXTENDED_STORAGE_INFO = extern struct { GenericStorageCapabilities: u32, Factor: u32, Specific: extern union { Null: u32, FacialFeatures: extern struct { Capabilities: u32, }, Fingerprint: extern struct { Capabilities: u32, }, Iris: extern struct { Capabilities: u32, }, Voice: extern struct { Capabilities: u32, }, }, }; pub const WINBIO_EXTENDED_ENROLLMENT_STATUS = extern struct { TemplateStatus: HRESULT, RejectDetail: u32, PercentComplete: u32, Factor: u32, SubFactor: u8, Specific: extern union { Null: u32, FacialFeatures: extern struct { BoundingBox: RECT, Distance: i32, OpaqueEngineData: extern struct { AdapterId: Guid, Data: [77]u32, }, }, Fingerprint: extern struct { GeneralSamples: u32, Center: u32, TopEdge: u32, BottomEdge: u32, LeftEdge: u32, RightEdge: u32, }, Iris: extern struct { EyeBoundingBox_1: RECT, EyeBoundingBox_2: RECT, PupilCenter_1: POINT, PupilCenter_2: POINT, Distance: i32, GridPointCompletionPercent: u32, GridPointIndex: u16, Point3D: extern struct { X: f64, Y: f64, Z: f64, }, StopCaptureAndShowCriticalFeedback: BOOL, }, Voice: extern struct { Reserved: u32, }, }, }; pub const WINBIO_EXTENDED_UNIT_STATUS = extern struct { Availability: u32, ReasonCode: u32, }; pub const WINBIO_FP_BU_STATE = extern struct { SensorAttached: BOOL, CreationResult: HRESULT, }; pub const WINBIO_ANTI_SPOOF_POLICY_ACTION = enum(i32) { DISABLE = 0, ENABLE = 1, REMOVE = 2, }; pub const WINBIO_ANTI_SPOOF_DISABLE = WINBIO_ANTI_SPOOF_POLICY_ACTION.DISABLE; pub const WINBIO_ANTI_SPOOF_ENABLE = WINBIO_ANTI_SPOOF_POLICY_ACTION.ENABLE; pub const WINBIO_ANTI_SPOOF_REMOVE = WINBIO_ANTI_SPOOF_POLICY_ACTION.REMOVE; pub const WINBIO_POLICY_SOURCE = enum(i32) { UNKNOWN = 0, DEFAULT = 1, LOCAL = 2, ADMIN = 3, }; pub const WINBIO_POLICY_UNKNOWN = WINBIO_POLICY_SOURCE.UNKNOWN; pub const WINBIO_POLICY_DEFAULT = WINBIO_POLICY_SOURCE.DEFAULT; pub const WINBIO_POLICY_LOCAL = WINBIO_POLICY_SOURCE.LOCAL; pub const WINBIO_POLICY_ADMIN = WINBIO_POLICY_SOURCE.ADMIN; pub const WINBIO_ANTI_SPOOF_POLICY = extern struct { Action: WINBIO_ANTI_SPOOF_POLICY_ACTION, Source: WINBIO_POLICY_SOURCE, }; pub const WINBIO_CREDENTIAL_TYPE = enum(i32) { PASSWORD = 1, ALL = -1, }; pub const WINBIO_CREDENTIAL_PASSWORD = <PASSWORD>CREDENTIAL_<PASSWORD>.PASSWORD; pub const WINBIO_CREDENTIAL_ALL = WINBIO_CREDENTIAL_TYPE.ALL; pub const WINBIO_CREDENTIAL_FORMAT = enum(i32) { GENERIC = 1, PACKED = 2, PROTECTED = 3, }; pub const WINBIO_PASSWORD_GENERIC = WINBIO_CREDENTIAL_FORMAT.GENERIC; pub const WINBIO_PASSWORD_PACKED = WINBIO_CREDENTIAL_FORMAT.PACKED; pub const WINBIO_PASSWORD_PROTECTED = WINBIO_CREDENTIAL_FORMAT.PROTECTED; pub const WINBIO_CREDENTIAL_STATE = enum(i32) { NOT_SET = 1, SET = 2, }; pub const WINBIO_CREDENTIAL_NOT_SET = WINBIO_CREDENTIAL_STATE.NOT_SET; pub const WINBIO_CREDENTIAL_SET = WINBIO_CREDENTIAL_STATE.SET; pub const WINBIO_EXTENDED_ENROLLMENT_PARAMETERS = extern struct { Size: usize, SubFactor: u8, }; pub const WINBIO_ACCOUNT_POLICY = extern struct { Identity: WINBIO_IDENTITY, AntiSpoofBehavior: WINBIO_ANTI_SPOOF_POLICY_ACTION, }; pub const WINBIO_PROTECTION_POLICY = extern struct { Version: u32, Identity: WINBIO_IDENTITY, DatabaseId: Guid, UserState: u64, PolicySize: usize, Policy: [128]u8, }; pub const WINBIO_GESTURE_METADATA = extern struct { Size: usize, BiometricType: u32, MatchType: u32, ProtectionType: u32, }; pub const WINBIO_ASYNC_NOTIFICATION_METHOD = enum(i32) { NONE = 0, CALLBACK = 1, MESSAGE = 2, MAXIMUM_VALUE = 3, }; pub const WINBIO_ASYNC_NOTIFY_NONE = WINBIO_ASYNC_NOTIFICATION_METHOD.NONE; pub const WINBIO_ASYNC_NOTIFY_CALLBACK = WINBIO_ASYNC_NOTIFICATION_METHOD.CALLBACK; pub const WINBIO_ASYNC_NOTIFY_MESSAGE = WINBIO_ASYNC_NOTIFICATION_METHOD.MESSAGE; pub const WINBIO_ASYNC_NOTIFY_MAXIMUM_VALUE = WINBIO_ASYNC_NOTIFICATION_METHOD.MAXIMUM_VALUE; pub const WINBIO_ASYNC_RESULT = extern struct { SessionHandle: u32, Operation: u32, SequenceNumber: u64, TimeStamp: i64, ApiStatus: HRESULT, UnitId: u32, UserData: ?*c_void, Parameters: extern union { Verify: extern struct { Match: BOOLEAN, RejectDetail: u32, }, Identify: extern struct { Identity: WINBIO_IDENTITY, SubFactor: u8, RejectDetail: u32, }, EnrollBegin: extern struct { SubFactor: u8, }, EnrollCapture: extern struct { RejectDetail: u32, }, EnrollCommit: extern struct { Identity: WINBIO_IDENTITY, IsNewTemplate: BOOLEAN, }, EnumEnrollments: extern struct { Identity: WINBIO_IDENTITY, SubFactorCount: usize, SubFactorArray: ?*u8, }, CaptureSample: extern struct { Sample: ?*WINBIO_BIR, SampleSize: usize, RejectDetail: u32, }, DeleteTemplate: extern struct { Identity: WINBIO_IDENTITY, SubFactor: u8, }, GetProperty: extern struct { PropertyType: u32, PropertyId: u32, Identity: WINBIO_IDENTITY, SubFactor: u8, PropertyBufferSize: usize, PropertyBuffer: ?*c_void, }, SetProperty: extern struct { PropertyType: u32, PropertyId: u32, Identity: WINBIO_IDENTITY, SubFactor: u8, PropertyBufferSize: usize, PropertyBuffer: ?*c_void, }, GetEvent: extern struct { Event: WINBIO_EVENT, }, ControlUnit: extern struct { Component: WINBIO_COMPONENT, ControlCode: u32, OperationStatus: u32, SendBuffer: ?*u8, SendBufferSize: usize, ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: usize, }, EnumServiceProviders: extern struct { BspCount: usize, BspSchemaArray: ?*WINBIO_BSP_SCHEMA, }, EnumBiometricUnits: extern struct { UnitCount: usize, UnitSchemaArray: ?*WINBIO_UNIT_SCHEMA, }, EnumDatabases: extern struct { StorageCount: usize, StorageSchemaArray: ?*WINBIO_STORAGE_SCHEMA, }, VerifyAndReleaseTicket: extern struct { Match: BOOLEAN, RejectDetail: u32, Ticket: u64, }, IdentifyAndReleaseTicket: extern struct { Identity: WINBIO_IDENTITY, SubFactor: u8, RejectDetail: u32, Ticket: u64, }, EnrollSelect: extern struct { SelectorValue: u64, }, MonitorPresence: extern struct { ChangeType: u32, PresenceCount: usize, PresenceArray: ?*WINBIO_PRESENCE, }, GetProtectionPolicy: extern struct { Identity: WINBIO_IDENTITY, Policy: WINBIO_PROTECTION_POLICY, }, NotifyUnitStatusChange: extern struct { ExtendedStatus: WINBIO_EXTENDED_UNIT_STATUS, }, }, }; pub const PWINBIO_ASYNC_COMPLETION_CALLBACK = fn( AsyncResult: ?*WINBIO_ASYNC_RESULT, ) callconv(@import("std").os.windows.WINAPI) void; pub const PWINBIO_VERIFY_CALLBACK = fn( VerifyCallbackContext: ?*c_void, OperationStatus: HRESULT, UnitId: u32, Match: BOOLEAN, RejectDetail: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PWINBIO_IDENTIFY_CALLBACK = fn( IdentifyCallbackContext: ?*c_void, OperationStatus: HRESULT, UnitId: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, RejectDetail: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PWINBIO_LOCATE_SENSOR_CALLBACK = fn( LocateCallbackContext: ?*c_void, OperationStatus: HRESULT, UnitId: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PWINBIO_ENROLL_CAPTURE_CALLBACK = fn( EnrollCallbackContext: ?*c_void, OperationStatus: HRESULT, RejectDetail: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const PWINBIO_EVENT_CALLBACK = fn( EventCallbackContext: ?*c_void, OperationStatus: HRESULT, Event: ?*WINBIO_EVENT, ) callconv(@import("std").os.windows.WINAPI) void; pub const PWINBIO_CAPTURE_CALLBACK = fn( CaptureCallbackContext: ?*c_void, OperationStatus: HRESULT, UnitId: u32, // TODO: what to do with BytesParamIndex 4? Sample: ?*WINBIO_BIR, SampleSize: usize, RejectDetail: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const WINBIO_STORAGE_RECORD = extern struct { Identity: ?*WINBIO_IDENTITY, SubFactor: u8, IndexVector: ?*u32, IndexElementCount: usize, TemplateBlob: ?*u8, TemplateBlobSize: usize, PayloadBlob: ?*u8, PayloadBlobSize: usize, }; pub const WINBIO_PIPELINE = extern struct { SensorHandle: ?HANDLE, EngineHandle: ?HANDLE, StorageHandle: ?HANDLE, SensorInterface: ?*WINBIO_SENSOR_INTERFACE, EngineInterface: ?*WINBIO_ENGINE_INTERFACE, StorageInterface: ?*WINBIO_STORAGE_INTERFACE, SensorContext: ?*_WINIBIO_SENSOR_CONTEXT, EngineContext: ?*_WINIBIO_ENGINE_CONTEXT, StorageContext: ?*_WINIBIO_STORAGE_CONTEXT, FrameworkInterface: ?*WINBIO_FRAMEWORK_INTERFACE, }; pub const WINBIO_ADAPTER_INTERFACE_VERSION = extern struct { MajorVersion: u16, MinorVersion: u16, }; pub const PIBIO_SENSOR_ATTACH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_DETACH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_CLEAR_CONTEXT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_QUERY_STATUS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Status: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_RESET_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_SET_MODE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Mode: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_SET_INDICATOR_STATUS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, IndicatorStatus: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_GET_INDICATOR_STATUS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, IndicatorStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_START_CAPTURE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Purpose: u8, Overlapped: ?*?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_FINISH_CAPTURE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_EXPORT_SENSOR_DATA_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SampleBuffer: ?*?*WINBIO_BIR, SampleSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_CANCEL_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_PUSH_DATA_TO_ENGINE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Purpose: u8, Flags: u8, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_CONTROL_UNIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ControlCode: u32, // TODO: what to do with BytesParamIndex 3? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 5? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_CONTROL_UNIT_PRIVILEGED_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ControlCode: u32, // TODO: what to do with BytesParamIndex 3? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 5? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_NOTIFY_POWER_CHANGE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, PowerEventType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_PIPELINE_INIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_PIPELINE_CLEANUP_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_ACTIVATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_DEACTIVATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_QUERY_EXTENDED_INFO_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? SensorInfo: ?*WINBIO_EXTENDED_SENSOR_INFO, SensorInfoSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_QUERY_CALIBRATION_FORMATS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, FormatArray: [*]Guid, FormatArraySize: usize, FormatCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_SET_CALIBRATION_FORMAT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Format: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_ACCEPT_CALIBRATION_DATA_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? CalibrationBuffer: ?*u8, CalibrationBufferSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_ASYNC_IMPORT_RAW_BUFFER_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? RawBufferAddress: ?*u8, RawBufferSize: usize, ResultBufferAddress: ?*?*u8, ResultBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_ASYNC_IMPORT_SECURE_BUFFER_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SecureBufferIdentifier: Guid, // TODO: what to do with BytesParamIndex 3? MetadataBufferAddress: ?*u8, MetadataBufferSize: usize, ResultBufferAddress: ?*?*u8, ResultBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_QUERY_PRIVATE_SENSOR_TYPE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? TypeInfoBufferAddress: ?*u8, TypeInfoBufferSize: usize, TypeInfoDataSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_CONNECT_SECURE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ConnectionParams: ?*const WINBIO_SECURE_CONNECTION_PARAMS, ConnectionData: ?*?*WINBIO_SECURE_CONNECTION_DATA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_START_CAPTURE_EX_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Purpose: u8, // TODO: what to do with BytesParamIndex 3? Nonce: ?*const u8, NonceSize: usize, Flags: u8, Overlapped: ?*?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_START_NOTIFY_WAKE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Overlapped: ?*?*OVERLAPPED, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_SENSOR_FINISH_NOTIFY_WAKE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Reason: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WINBIO_SENSOR_INTERFACE = extern struct { Version: WINBIO_ADAPTER_INTERFACE_VERSION, Type: u32, Size: usize, AdapterId: Guid, Attach: ?PIBIO_SENSOR_ATTACH_FN, Detach: ?PIBIO_SENSOR_DETACH_FN, ClearContext: ?PIBIO_SENSOR_CLEAR_CONTEXT_FN, QueryStatus: ?PIBIO_SENSOR_QUERY_STATUS_FN, Reset: ?PIBIO_SENSOR_RESET_FN, SetMode: ?PIBIO_SENSOR_SET_MODE_FN, SetIndicatorStatus: ?PIBIO_SENSOR_SET_INDICATOR_STATUS_FN, GetIndicatorStatus: ?PIBIO_SENSOR_GET_INDICATOR_STATUS_FN, StartCapture: ?PIBIO_SENSOR_START_CAPTURE_FN, FinishCapture: ?PIBIO_SENSOR_FINISH_CAPTURE_FN, ExportSensorData: ?PIBIO_SENSOR_EXPORT_SENSOR_DATA_FN, Cancel: ?PIBIO_SENSOR_CANCEL_FN, PushDataToEngine: ?PIBIO_SENSOR_PUSH_DATA_TO_ENGINE_FN, ControlUnit: ?PIBIO_SENSOR_CONTROL_UNIT_FN, ControlUnitPrivileged: ?PIBIO_SENSOR_CONTROL_UNIT_PRIVILEGED_FN, NotifyPowerChange: ?PIBIO_SENSOR_NOTIFY_POWER_CHANGE_FN, PipelineInit: ?PIBIO_SENSOR_PIPELINE_INIT_FN, PipelineCleanup: ?PIBIO_SENSOR_PIPELINE_CLEANUP_FN, Activate: ?PIBIO_SENSOR_ACTIVATE_FN, Deactivate: ?PIBIO_SENSOR_DEACTIVATE_FN, QueryExtendedInfo: ?PIBIO_SENSOR_QUERY_EXTENDED_INFO_FN, QueryCalibrationFormats: ?PIBIO_SENSOR_QUERY_CALIBRATION_FORMATS_FN, SetCalibrationFormat: ?PIBIO_SENSOR_SET_CALIBRATION_FORMAT_FN, AcceptCalibrationData: ?PIBIO_SENSOR_ACCEPT_CALIBRATION_DATA_FN, AsyncImportRawBuffer: ?PIBIO_SENSOR_ASYNC_IMPORT_RAW_BUFFER_FN, AsyncImportSecureBuffer: ?PIBIO_SENSOR_ASYNC_IMPORT_SECURE_BUFFER_FN, QueryPrivateSensorType: ?PIBIO_SENSOR_QUERY_PRIVATE_SENSOR_TYPE_FN, ConnectSecure: ?PIBIO_SENSOR_CONNECT_SECURE_FN, StartCaptureEx: ?PIBIO_SENSOR_START_CAPTURE_EX_FN, StartNotifyWake: ?PIBIO_SENSOR_START_NOTIFY_WAKE_FN, FinishNotifyWake: ?PIBIO_SENSOR_FINISH_NOTIFY_WAKE_FN, }; pub const PWINBIO_QUERY_SENSOR_INTERFACE_FN = fn( SensorInterface: ?*?*WINBIO_SENSOR_INTERFACE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_ATTACH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_DETACH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CLEAR_CONTEXT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_PREFERRED_FORMAT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, StandardFormat: ?*WINBIO_REGISTERED_FORMAT, VendorFormat: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_INDEX_VECTOR_SIZE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, IndexElementCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_HASH_ALGORITHMS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, AlgorithmCount: ?*usize, AlgorithmBufferSize: ?*usize, // TODO: what to do with BytesParamIndex 2? AlgorithmBuffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_SET_HASH_ALGORITHM_FN = fn( Pipeline: ?*WINBIO_PIPELINE, AlgorithmBufferSize: usize, AlgorithmBuffer: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_SAMPLE_HINT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SampleHint: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_ACCEPT_SAMPLE_DATA_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? SampleBuffer: ?*WINBIO_BIR, SampleSize: usize, Purpose: u8, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_EXPORT_ENGINE_DATA_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Flags: u8, // TODO: what to do with BytesParamIndex 3? SampleBuffer: ?*?*WINBIO_BIR, SampleSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_VERIFY_FEATURE_SET_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, Match: ?*BOOLEAN, // TODO: what to do with BytesParamIndex 5? PayloadBlob: ?*?*u8, PayloadBlobSize: ?*usize, // TODO: what to do with BytesParamIndex 7? HashValue: ?*?*u8, HashSize: ?*usize, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_IDENTIFY_FEATURE_SET_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: ?*u8, // TODO: what to do with BytesParamIndex 4? PayloadBlob: ?*?*u8, PayloadBlobSize: ?*usize, // TODO: what to do with BytesParamIndex 6? HashValue: ?*?*u8, HashSize: ?*usize, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CREATE_ENROLLMENT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_UPDATE_ENROLLMENT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_GET_ENROLLMENT_STATUS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_GET_ENROLLMENT_HASH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? HashValue: ?*?*u8, HashSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CHECK_FOR_DUPLICATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: ?*u8, Duplicate: ?*BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_COMMIT_ENROLLMENT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, // TODO: what to do with BytesParamIndex 4? PayloadBlob: ?*u8, PayloadBlobSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_DISCARD_ENROLLMENT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CONTROL_UNIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ControlCode: u32, // TODO: what to do with BytesParamIndex 3? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 5? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CONTROL_UNIT_PRIVILEGED_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ControlCode: u32, // TODO: what to do with BytesParamIndex 3? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 5? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_NOTIFY_POWER_CHANGE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, PowerEventType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_RESERVED_1_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_PIPELINE_INIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_PIPELINE_CLEANUP_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_ACTIVATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_DEACTIVATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_EXTENDED_INFO_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? EngineInfo: ?*WINBIO_EXTENDED_ENGINE_INFO, EngineInfoSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_IDENTIFY_ALL_FN = fn( Pipeline: ?*WINBIO_PIPELINE, PresenceCount: ?*usize, PresenceArray: ?*?*WINBIO_PRESENCE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_SET_ENROLLMENT_SELECTOR_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SelectorValue: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_SET_ENROLLMENT_PARAMETERS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Parameters: ?*WINBIO_EXTENDED_ENROLLMENT_PARAMETERS, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_EXTENDED_ENROLLMENT_STATUS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? EnrollmentStatus: ?*WINBIO_EXTENDED_ENROLLMENT_STATUS, EnrollmentStatusSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_REFRESH_CACHE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_SELECT_CALIBRATION_FORMAT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, FormatArray: [*]Guid, FormatCount: usize, SelectedFormat: ?*Guid, MaxBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_QUERY_CALIBRATION_DATA_FN = fn( Pipeline: ?*WINBIO_PIPELINE, DiscardAndRepeatCapture: ?*BOOLEAN, // TODO: what to do with BytesParamIndex 4? CalibrationBuffer: ?*u8, CalibrationBufferSize: ?*usize, MaxBufferSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_SET_ACCOUNT_POLICY_FN = fn( Pipeline: ?*WINBIO_PIPELINE, PolicyItemArray: [*]WINBIO_ACCOUNT_POLICY, PolicyItemCount: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CREATE_KEY_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Key: [*:0]const u8, KeySize: usize, // TODO: what to do with BytesParamIndex 4? KeyIdentifier: ?*u8, KeyIdentifierSize: usize, ResultSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_IDENTIFY_FEATURE_SET_SECURE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Nonce: [*:0]const u8, NonceSize: usize, KeyIdentifier: [*:0]const u8, KeyIdentifierSize: usize, Identity: ?*WINBIO_IDENTITY, SubFactor: ?*u8, RejectDetail: ?*u32, Authorization: ?*?*u8, AuthorizationSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_ACCEPT_PRIVATE_SENSOR_TYPE_INFO_FN = fn( Pipeline: ?*WINBIO_PIPELINE, TypeInfoBufferAddress: [*:0]const u8, TypeInfoBufferSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_CREATE_ENROLLMENT_AUTHENTICATED_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Nonce: ?*?*u8, NonceSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_ENGINE_IDENTIFY_FEATURE_SET_AUTHENTICATED_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? Nonce: ?*const u8, NonceSize: usize, Identity: ?*WINBIO_IDENTITY, SubFactor: ?*u8, RejectDetail: ?*u32, Authentication: ?*?*u8, AuthenticationSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WINBIO_ENGINE_INTERFACE = extern struct { Version: WINBIO_ADAPTER_INTERFACE_VERSION, Type: u32, Size: usize, AdapterId: Guid, Attach: ?PIBIO_ENGINE_ATTACH_FN, Detach: ?PIBIO_ENGINE_DETACH_FN, ClearContext: ?PIBIO_ENGINE_CLEAR_CONTEXT_FN, QueryPreferredFormat: ?PIBIO_ENGINE_QUERY_PREFERRED_FORMAT_FN, QueryIndexVectorSize: ?PIBIO_ENGINE_QUERY_INDEX_VECTOR_SIZE_FN, QueryHashAlgorithms: ?PIBIO_ENGINE_QUERY_HASH_ALGORITHMS_FN, SetHashAlgorithm: ?PIBIO_ENGINE_SET_HASH_ALGORITHM_FN, QuerySampleHint: ?PIBIO_ENGINE_QUERY_SAMPLE_HINT_FN, AcceptSampleData: ?PIBIO_ENGINE_ACCEPT_SAMPLE_DATA_FN, ExportEngineData: ?PIBIO_ENGINE_EXPORT_ENGINE_DATA_FN, VerifyFeatureSet: ?PIBIO_ENGINE_VERIFY_FEATURE_SET_FN, IdentifyFeatureSet: ?PIBIO_ENGINE_IDENTIFY_FEATURE_SET_FN, CreateEnrollment: ?PIBIO_ENGINE_CREATE_ENROLLMENT_FN, UpdateEnrollment: ?PIBIO_ENGINE_UPDATE_ENROLLMENT_FN, GetEnrollmentStatus: ?PIBIO_ENGINE_GET_ENROLLMENT_STATUS_FN, GetEnrollmentHash: ?PIBIO_ENGINE_GET_ENROLLMENT_HASH_FN, CheckForDuplicate: ?PIBIO_ENGINE_CHECK_FOR_DUPLICATE_FN, CommitEnrollment: ?PIBIO_ENGINE_COMMIT_ENROLLMENT_FN, DiscardEnrollment: ?PIBIO_ENGINE_DISCARD_ENROLLMENT_FN, ControlUnit: ?PIBIO_ENGINE_CONTROL_UNIT_FN, ControlUnitPrivileged: ?PIBIO_ENGINE_CONTROL_UNIT_PRIVILEGED_FN, NotifyPowerChange: ?PIBIO_ENGINE_NOTIFY_POWER_CHANGE_FN, Reserved_1: ?PIBIO_ENGINE_RESERVED_1_FN, PipelineInit: ?PIBIO_ENGINE_PIPELINE_INIT_FN, PipelineCleanup: ?PIBIO_ENGINE_PIPELINE_CLEANUP_FN, Activate: ?PIBIO_ENGINE_ACTIVATE_FN, Deactivate: ?PIBIO_ENGINE_DEACTIVATE_FN, QueryExtendedInfo: ?PIBIO_ENGINE_QUERY_EXTENDED_INFO_FN, IdentifyAll: ?PIBIO_ENGINE_IDENTIFY_ALL_FN, SetEnrollmentSelector: ?PIBIO_ENGINE_SET_ENROLLMENT_SELECTOR_FN, SetEnrollmentParameters: ?PIBIO_ENGINE_SET_ENROLLMENT_PARAMETERS_FN, QueryExtendedEnrollmentStatus: ?PIBIO_ENGINE_QUERY_EXTENDED_ENROLLMENT_STATUS_FN, RefreshCache: ?PIBIO_ENGINE_REFRESH_CACHE_FN, SelectCalibrationFormat: ?PIBIO_ENGINE_SELECT_CALIBRATION_FORMAT_FN, QueryCalibrationData: ?PIBIO_ENGINE_QUERY_CALIBRATION_DATA_FN, SetAccountPolicy: ?PIBIO_ENGINE_SET_ACCOUNT_POLICY_FN, CreateKey: ?PIBIO_ENGINE_CREATE_KEY_FN, IdentifyFeatureSetSecure: ?PIBIO_ENGINE_IDENTIFY_FEATURE_SET_SECURE_FN, AcceptPrivateSensorTypeInfo: ?PIBIO_ENGINE_ACCEPT_PRIVATE_SENSOR_TYPE_INFO_FN, CreateEnrollmentAuthenticated: ?PIBIO_ENGINE_CREATE_ENROLLMENT_AUTHENTICATED_FN, IdentifyFeatureSetAuthenticated: ?PIBIO_ENGINE_IDENTIFY_FEATURE_SET_AUTHENTICATED_FN, }; pub const PWINBIO_QUERY_ENGINE_INTERFACE_FN = fn( EngineInterface: ?*?*WINBIO_ENGINE_INTERFACE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_ATTACH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_DETACH_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_CLEAR_CONTEXT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_CREATE_DATABASE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, DatabaseId: ?*Guid, Factor: u32, Format: ?*Guid, FilePath: ?[*:0]const u16, ConnectString: ?[*:0]const u16, IndexElementCount: usize, InitialSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_ERASE_DATABASE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, DatabaseId: ?*Guid, FilePath: ?[*:0]const u16, ConnectString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_OPEN_DATABASE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, DatabaseId: ?*Guid, FilePath: ?[*:0]const u16, ConnectString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_CLOSE_DATABASE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_GET_DATA_FORMAT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Format: ?*Guid, Version: ?*WINBIO_VERSION, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_GET_DATABASE_SIZE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, AvailableRecordCount: ?*usize, TotalRecordCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_ADD_RECORD_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RecordContents: ?*WINBIO_STORAGE_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_DELETE_RECORD_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_QUERY_BY_SUBJECT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_QUERY_BY_CONTENT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SubFactor: u8, IndexVector: [*]u32, IndexElementCount: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_GET_RECORD_COUNT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RecordCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_FIRST_RECORD_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_NEXT_RECORD_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_GET_CURRENT_RECORD_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RecordContents: ?*WINBIO_STORAGE_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_CONTROL_UNIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ControlCode: u32, // TODO: what to do with BytesParamIndex 3? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 5? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_CONTROL_UNIT_PRIVILEGED_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ControlCode: u32, // TODO: what to do with BytesParamIndex 3? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 5? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_NOTIFY_POWER_CHANGE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, PowerEventType: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_PIPELINE_INIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_PIPELINE_CLEANUP_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_ACTIVATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_DEACTIVATE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_QUERY_EXTENDED_INFO_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? StorageInfo: ?*WINBIO_EXTENDED_STORAGE_INFO, StorageInfoSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_NOTIFY_DATABASE_CHANGE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RecordsAdded: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_RESERVED_1_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, Reserved1: ?*u64, Reserved2: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_RESERVED_2_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_UPDATE_RECORD_BEGIN_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, RecordContents: ?*WINBIO_STORAGE_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_STORAGE_UPDATE_RECORD_COMMIT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RecordContents: ?*WINBIO_STORAGE_RECORD, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WINBIO_STORAGE_INTERFACE = extern struct { Version: WINBIO_ADAPTER_INTERFACE_VERSION, Type: u32, Size: usize, AdapterId: Guid, Attach: ?PIBIO_STORAGE_ATTACH_FN, Detach: ?PIBIO_STORAGE_DETACH_FN, ClearContext: ?PIBIO_STORAGE_CLEAR_CONTEXT_FN, CreateDatabase: ?PIBIO_STORAGE_CREATE_DATABASE_FN, EraseDatabase: ?PIBIO_STORAGE_ERASE_DATABASE_FN, OpenDatabase: ?PIBIO_STORAGE_OPEN_DATABASE_FN, CloseDatabase: ?PIBIO_STORAGE_CLOSE_DATABASE_FN, GetDataFormat: ?PIBIO_STORAGE_GET_DATA_FORMAT_FN, GetDatabaseSize: ?PIBIO_STORAGE_GET_DATABASE_SIZE_FN, AddRecord: ?PIBIO_STORAGE_ADD_RECORD_FN, DeleteRecord: ?PIBIO_STORAGE_DELETE_RECORD_FN, QueryBySubject: ?PIBIO_STORAGE_QUERY_BY_SUBJECT_FN, QueryByContent: ?PIBIO_STORAGE_QUERY_BY_CONTENT_FN, GetRecordCount: ?PIBIO_STORAGE_GET_RECORD_COUNT_FN, FirstRecord: ?PIBIO_STORAGE_FIRST_RECORD_FN, NextRecord: ?PIBIO_STORAGE_NEXT_RECORD_FN, GetCurrentRecord: ?PIBIO_STORAGE_GET_CURRENT_RECORD_FN, ControlUnit: ?PIBIO_STORAGE_CONTROL_UNIT_FN, ControlUnitPrivileged: ?PIBIO_STORAGE_CONTROL_UNIT_PRIVILEGED_FN, NotifyPowerChange: ?PIBIO_STORAGE_NOTIFY_POWER_CHANGE_FN, PipelineInit: ?PIBIO_STORAGE_PIPELINE_INIT_FN, PipelineCleanup: ?PIBIO_STORAGE_PIPELINE_CLEANUP_FN, Activate: ?PIBIO_STORAGE_ACTIVATE_FN, Deactivate: ?PIBIO_STORAGE_DEACTIVATE_FN, QueryExtendedInfo: ?PIBIO_STORAGE_QUERY_EXTENDED_INFO_FN, NotifyDatabaseChange: ?PIBIO_STORAGE_NOTIFY_DATABASE_CHANGE_FN, Reserved1: ?PIBIO_STORAGE_RESERVED_1_FN, Reserved2: ?PIBIO_STORAGE_RESERVED_2_FN, UpdateRecordBegin: ?PIBIO_STORAGE_UPDATE_RECORD_BEGIN_FN, UpdateRecordCommit: ?PIBIO_STORAGE_UPDATE_RECORD_COMMIT_FN, }; pub const PWINBIO_QUERY_STORAGE_INTERFACE_FN = fn( StorageInterface: ?*?*WINBIO_STORAGE_INTERFACE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_SET_UNIT_STATUS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? ExtendedStatus: ?*WINBIO_EXTENDED_UNIT_STATUS, ExtendedStatusSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_CLEAR_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_BEGIN_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RequiredCapacity: usize, MaxBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_NEXT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? BufferAddress: ?*u8, BufferSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_END_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_BEGIN_FN = fn( Pipeline: ?*WINBIO_PIPELINE, RequiredCapacity: ?*usize, MaxBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_NEXT_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? BufferAddress: ?*u8, BufferSize: usize, ReturnedDataSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_END_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_1_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Reserved1: usize, Reserved2: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_2_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Reserved1: ?*u8, Reserved2: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_3_FN = fn( Pipeline: ?*WINBIO_PIPELINE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_ALLOCATE_MEMORY_FN = fn( Pipeline: ?*WINBIO_PIPELINE, AllocationSize: usize, Address: ?*?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_FREE_MEMORY_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Address: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_GET_PROPERTY_FN = fn( Pipeline: ?*WINBIO_PIPELINE, PropertyType: u32, PropertyId: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, PropertyBuffer: ?*?*c_void, PropertyBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_LOCK_AND_VALIDATE_SECURE_BUFFER_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SecureBufferIdentifier: Guid, SecureBufferAddress: ?*?*c_void, SecureBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_RELEASE_SECURE_BUFFER_FN = fn( Pipeline: ?*WINBIO_PIPELINE, SecureBufferIdentifier: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_QUERY_AUTHORIZED_ENROLLMENTS_FN = fn( Pipeline: ?*WINBIO_PIPELINE, Identity: ?*WINBIO_IDENTITY, SecureIdentityCount: ?*usize, SecureIdentities: ?*?*WINBIO_IDENTITY, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PIBIO_FRAMEWORK_VSM_DECRYPT_SAMPLE_FN = fn( Pipeline: ?*WINBIO_PIPELINE, // TODO: what to do with BytesParamIndex 2? Authentication: ?*const u8, AuthenticationSize: usize, // TODO: what to do with BytesParamIndex 4? Iv: ?*const u8, IvSize: usize, // TODO: what to do with BytesParamIndex 6? EncryptedData: ?*u8, EncryptedDataSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const WINBIO_FRAMEWORK_INTERFACE = extern struct { Version: WINBIO_ADAPTER_INTERFACE_VERSION, Type: u32, Size: usize, AdapterId: Guid, SetUnitStatus: ?PIBIO_FRAMEWORK_SET_UNIT_STATUS_FN, VsmStorageAttach: ?PIBIO_STORAGE_ATTACH_FN, VsmStorageDetach: ?PIBIO_STORAGE_DETACH_FN, VsmStorageClearContext: ?PIBIO_STORAGE_CLEAR_CONTEXT_FN, VsmStorageCreateDatabase: ?PIBIO_STORAGE_CREATE_DATABASE_FN, VsmStorageOpenDatabase: ?PIBIO_STORAGE_OPEN_DATABASE_FN, VsmStorageCloseDatabase: ?PIBIO_STORAGE_CLOSE_DATABASE_FN, VsmStorageDeleteRecord: ?PIBIO_STORAGE_DELETE_RECORD_FN, VsmStorageNotifyPowerChange: ?PIBIO_STORAGE_NOTIFY_POWER_CHANGE_FN, VsmStoragePipelineInit: ?PIBIO_STORAGE_PIPELINE_INIT_FN, VsmStoragePipelineCleanup: ?PIBIO_STORAGE_PIPELINE_CLEANUP_FN, VsmStorageActivate: ?PIBIO_STORAGE_ACTIVATE_FN, VsmStorageDeactivate: ?PIBIO_STORAGE_DEACTIVATE_FN, VsmStorageQueryExtendedInfo: ?PIBIO_STORAGE_QUERY_EXTENDED_INFO_FN, VsmStorageCacheClear: ?PIBIO_FRAMEWORK_VSM_CACHE_CLEAR_FN, VsmStorageCacheImportBegin: ?PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_BEGIN_FN, VsmStorageCacheImportNext: ?PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_NEXT_FN, VsmStorageCacheImportEnd: ?PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_END_FN, VsmStorageCacheExportBegin: ?PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_BEGIN_FN, VsmStorageCacheExportNext: ?PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_NEXT_FN, VsmStorageCacheExportEnd: ?PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_END_FN, VsmSensorAttach: ?PIBIO_SENSOR_ATTACH_FN, VsmSensorDetach: ?PIBIO_SENSOR_DETACH_FN, VsmSensorClearContext: ?PIBIO_SENSOR_CLEAR_CONTEXT_FN, VsmSensorPushDataToEngine: ?PIBIO_SENSOR_PUSH_DATA_TO_ENGINE_FN, VsmSensorNotifyPowerChange: ?PIBIO_SENSOR_NOTIFY_POWER_CHANGE_FN, VsmSensorPipelineInit: ?PIBIO_SENSOR_PIPELINE_INIT_FN, VsmSensorPipelineCleanup: ?PIBIO_SENSOR_PIPELINE_CLEANUP_FN, VsmSensorActivate: ?PIBIO_SENSOR_ACTIVATE_FN, VsmSensorDeactivate: ?PIBIO_SENSOR_DEACTIVATE_FN, VsmSensorAsyncImportRawBuffer: ?PIBIO_SENSOR_ASYNC_IMPORT_RAW_BUFFER_FN, VsmSensorAsyncImportSecureBuffer: ?PIBIO_SENSOR_ASYNC_IMPORT_SECURE_BUFFER_FN, Reserved1: ?PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_1_FN, Reserved2: ?PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_2_FN, Reserved3: ?PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_3_FN, Reserved4: ?PIBIO_STORAGE_RESERVED_1_FN, Reserved5: ?PIBIO_STORAGE_RESERVED_2_FN, AllocateMemory: ?PIBIO_FRAMEWORK_ALLOCATE_MEMORY_FN, FreeMemory: ?PIBIO_FRAMEWORK_FREE_MEMORY_FN, GetProperty: ?PIBIO_FRAMEWORK_GET_PROPERTY_FN, LockAndValidateSecureBuffer: ?PIBIO_FRAMEWORK_LOCK_AND_VALIDATE_SECURE_BUFFER_FN, ReleaseSecureBuffer: ?PIBIO_FRAMEWORK_RELEASE_SECURE_BUFFER_FN, QueryAuthorizedEnrollments: ?PIBIO_FRAMEWORK_VSM_QUERY_AUTHORIZED_ENROLLMENTS_FN, DecryptSample: ?PIBIO_FRAMEWORK_VSM_DECRYPT_SAMPLE_FN, }; //-------------------------------------------------------------------------------- // Section: Functions (52) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnumServiceProviders( Factor: u32, BspSchemaArray: ?*?*WINBIO_BSP_SCHEMA, BspCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnumBiometricUnits( Factor: u32, UnitSchemaArray: ?*?*WINBIO_UNIT_SCHEMA, UnitCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnumDatabases( Factor: u32, StorageSchemaArray: ?*?*WINBIO_STORAGE_SCHEMA, StorageCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioAsyncOpenFramework( NotificationMethod: WINBIO_ASYNC_NOTIFICATION_METHOD, TargetWindow: ?HWND, MessageCode: u32, CallbackRoutine: ?PWINBIO_ASYNC_COMPLETION_CALLBACK, UserData: ?*c_void, AsynchronousOpen: BOOL, FrameworkHandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioCloseFramework( FrameworkHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioAsyncEnumServiceProviders( FrameworkHandle: u32, Factor: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioAsyncEnumBiometricUnits( FrameworkHandle: u32, Factor: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioAsyncEnumDatabases( FrameworkHandle: u32, Factor: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioAsyncMonitorFrameworkChanges( FrameworkHandle: u32, ChangeTypes: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioOpenSession( Factor: u32, PoolType: WINBIO_POOL, Flags: u32, UnitArray: ?[*]u32, UnitCount: usize, DatabaseId: ?*Guid, SessionHandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.0' pub extern "winbio" fn WinBioAsyncOpenSession( Factor: u32, PoolType: WINBIO_POOL, Flags: u32, UnitArray: ?[*]u32, UnitCount: usize, DatabaseId: ?*Guid, NotificationMethod: WINBIO_ASYNC_NOTIFICATION_METHOD, TargetWindow: ?HWND, MessageCode: u32, CallbackRoutine: ?PWINBIO_ASYNC_COMPLETION_CALLBACK, UserData: ?*c_void, AsynchronousOpen: BOOL, SessionHandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioCloseSession( SessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioVerify( SessionHandle: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, UnitId: ?*u32, Match: ?*u8, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioVerifyWithCallback( SessionHandle: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, VerifyCallback: ?PWINBIO_VERIFY_CALLBACK, VerifyCallbackContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioIdentify( SessionHandle: u32, UnitId: ?*u32, Identity: ?*WINBIO_IDENTITY, SubFactor: ?*u8, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioIdentifyWithCallback( SessionHandle: u32, IdentifyCallback: ?PWINBIO_IDENTIFY_CALLBACK, IdentifyCallbackContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioWait( SessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioCancel( SessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioLocateSensor( SessionHandle: u32, UnitId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioLocateSensorWithCallback( SessionHandle: u32, LocateCallback: ?PWINBIO_LOCATE_SENSOR_CALLBACK, LocateCallbackContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnrollBegin( SessionHandle: u32, SubFactor: u8, UnitId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "winbio" fn WinBioEnrollSelect( SessionHandle: u32, SelectorValue: u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnrollCapture( SessionHandle: u32, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnrollCaptureWithCallback( SessionHandle: u32, EnrollCallback: ?PWINBIO_ENROLL_CAPTURE_CALLBACK, EnrollCallbackContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnrollCommit( SessionHandle: u32, Identity: ?*WINBIO_IDENTITY, IsNewTemplate: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnrollDiscard( SessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioEnumEnrollments( SessionHandle: u32, UnitId: u32, Identity: ?*WINBIO_IDENTITY, SubFactorArray: ?*?*u8, SubFactorCount: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioRegisterEventMonitor( SessionHandle: u32, EventMask: u32, EventCallback: ?PWINBIO_EVENT_CALLBACK, EventCallbackContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioUnregisterEventMonitor( SessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "winbio" fn WinBioMonitorPresence( SessionHandle: u32, UnitId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioCaptureSample( SessionHandle: u32, Purpose: u8, Flags: u8, UnitId: ?*u32, Sample: ?*?*WINBIO_BIR, SampleSize: ?*usize, RejectDetail: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioCaptureSampleWithCallback( SessionHandle: u32, Purpose: u8, Flags: u8, CaptureCallback: ?PWINBIO_CAPTURE_CALLBACK, CaptureCallbackContext: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioDeleteTemplate( SessionHandle: u32, UnitId: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioLockUnit( SessionHandle: u32, UnitId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioUnlockUnit( SessionHandle: u32, UnitId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioControlUnit( SessionHandle: u32, UnitId: u32, Component: WINBIO_COMPONENT, ControlCode: u32, // TODO: what to do with BytesParamIndex 5? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 7? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioControlUnitPrivileged( SessionHandle: u32, UnitId: u32, Component: WINBIO_COMPONENT, ControlCode: u32, // TODO: what to do with BytesParamIndex 5? SendBuffer: ?*u8, SendBufferSize: usize, // TODO: what to do with BytesParamIndex 7? ReceiveBuffer: ?*u8, ReceiveBufferSize: usize, ReceiveDataSize: ?*usize, OperationStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioGetProperty( SessionHandle: u32, PropertyType: u32, PropertyId: u32, UnitId: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, PropertyBuffer: ?*?*c_void, PropertyBufferSize: ?*usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "winbio" fn WinBioSetProperty( SessionHandle: u32, PropertyType: u32, PropertyId: u32, UnitId: u32, Identity: ?*WINBIO_IDENTITY, SubFactor: u8, // TODO: what to do with BytesParamIndex 7? PropertyBuffer: ?*c_void, PropertyBufferSize: usize, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioFree( Address: ?*c_void, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows8.1' pub extern "winbio" fn WinBioSetCredential( Type: WINBIO_CREDENTIAL_TYPE, // TODO: what to do with BytesParamIndex 2? Credential: ?*u8, CredentialSize: usize, Format: WINBIO_CREDENTIAL_FORMAT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioRemoveCredential( Identity: WINBIO_IDENTITY, Type: WINBIO_CREDENTIAL_TYPE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioRemoveAllCredentials( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioRemoveAllDomainCredentials( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioGetCredentialState( Identity: WINBIO_IDENTITY, Type: WINBIO_CREDENTIAL_TYPE, CredentialState: ?*WINBIO_CREDENTIAL_STATE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioLogonIdentifiedUser( SessionHandle: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "winbio" fn WinBioGetEnrolledFactors( AccountOwner: ?*WINBIO_IDENTITY, EnrolledFactors: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioGetEnabledSetting( Value: ?*u8, Source: ?*WINBIO_SETTING_SOURCE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioGetLogonSetting( Value: ?*u8, Source: ?*WINBIO_SETTING_SOURCE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioGetDomainLogonSetting( Value: ?*u8, Source: ?*WINBIO_SETTING_SOURCE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioAcquireFocus( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "winbio" fn WinBioReleaseFocus( ) 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 (11) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const LARGE_INTEGER = @import("../system/system_services.zig").LARGE_INTEGER; const OVERLAPPED = @import("../system/system_services.zig").OVERLAPPED; const POINT = @import("../foundation.zig").POINT; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PWINBIO_ASYNC_COMPLETION_CALLBACK")) { _ = PWINBIO_ASYNC_COMPLETION_CALLBACK; } if (@hasDecl(@This(), "PWINBIO_VERIFY_CALLBACK")) { _ = PWINBIO_VERIFY_CALLBACK; } if (@hasDecl(@This(), "PWINBIO_IDENTIFY_CALLBACK")) { _ = PWINBIO_IDENTIFY_CALLBACK; } if (@hasDecl(@This(), "PWINBIO_LOCATE_SENSOR_CALLBACK")) { _ = PWINBIO_LOCATE_SENSOR_CALLBACK; } if (@hasDecl(@This(), "PWINBIO_ENROLL_CAPTURE_CALLBACK")) { _ = PWINBIO_ENROLL_CAPTURE_CALLBACK; } if (@hasDecl(@This(), "PWINBIO_EVENT_CALLBACK")) { _ = PWINBIO_EVENT_CALLBACK; } if (@hasDecl(@This(), "PWINBIO_CAPTURE_CALLBACK")) { _ = PWINBIO_CAPTURE_CALLBACK; } if (@hasDecl(@This(), "PIBIO_SENSOR_ATTACH_FN")) { _ = PIBIO_SENSOR_ATTACH_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_DETACH_FN")) { _ = PIBIO_SENSOR_DETACH_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_CLEAR_CONTEXT_FN")) { _ = PIBIO_SENSOR_CLEAR_CONTEXT_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_QUERY_STATUS_FN")) { _ = PIBIO_SENSOR_QUERY_STATUS_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_RESET_FN")) { _ = PIBIO_SENSOR_RESET_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_SET_MODE_FN")) { _ = PIBIO_SENSOR_SET_MODE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_SET_INDICATOR_STATUS_FN")) { _ = PIBIO_SENSOR_SET_INDICATOR_STATUS_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_GET_INDICATOR_STATUS_FN")) { _ = PIBIO_SENSOR_GET_INDICATOR_STATUS_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_START_CAPTURE_FN")) { _ = PIBIO_SENSOR_START_CAPTURE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_FINISH_CAPTURE_FN")) { _ = PIBIO_SENSOR_FINISH_CAPTURE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_EXPORT_SENSOR_DATA_FN")) { _ = PIBIO_SENSOR_EXPORT_SENSOR_DATA_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_CANCEL_FN")) { _ = PIBIO_SENSOR_CANCEL_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_PUSH_DATA_TO_ENGINE_FN")) { _ = PIBIO_SENSOR_PUSH_DATA_TO_ENGINE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_CONTROL_UNIT_FN")) { _ = PIBIO_SENSOR_CONTROL_UNIT_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_CONTROL_UNIT_PRIVILEGED_FN")) { _ = PIBIO_SENSOR_CONTROL_UNIT_PRIVILEGED_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_NOTIFY_POWER_CHANGE_FN")) { _ = PIBIO_SENSOR_NOTIFY_POWER_CHANGE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_PIPELINE_INIT_FN")) { _ = PIBIO_SENSOR_PIPELINE_INIT_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_PIPELINE_CLEANUP_FN")) { _ = PIBIO_SENSOR_PIPELINE_CLEANUP_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_ACTIVATE_FN")) { _ = PIBIO_SENSOR_ACTIVATE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_DEACTIVATE_FN")) { _ = PIBIO_SENSOR_DEACTIVATE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_QUERY_EXTENDED_INFO_FN")) { _ = PIBIO_SENSOR_QUERY_EXTENDED_INFO_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_QUERY_CALIBRATION_FORMATS_FN")) { _ = PIBIO_SENSOR_QUERY_CALIBRATION_FORMATS_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_SET_CALIBRATION_FORMAT_FN")) { _ = PIBIO_SENSOR_SET_CALIBRATION_FORMAT_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_ACCEPT_CALIBRATION_DATA_FN")) { _ = PIBIO_SENSOR_ACCEPT_CALIBRATION_DATA_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_ASYNC_IMPORT_RAW_BUFFER_FN")) { _ = PIBIO_SENSOR_ASYNC_IMPORT_RAW_BUFFER_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_ASYNC_IMPORT_SECURE_BUFFER_FN")) { _ = PIBIO_SENSOR_ASYNC_IMPORT_SECURE_BUFFER_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_QUERY_PRIVATE_SENSOR_TYPE_FN")) { _ = PIBIO_SENSOR_QUERY_PRIVATE_SENSOR_TYPE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_CONNECT_SECURE_FN")) { _ = PIBIO_SENSOR_CONNECT_SECURE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_START_CAPTURE_EX_FN")) { _ = PIBIO_SENSOR_START_CAPTURE_EX_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_START_NOTIFY_WAKE_FN")) { _ = PIBIO_SENSOR_START_NOTIFY_WAKE_FN; } if (@hasDecl(@This(), "PIBIO_SENSOR_FINISH_NOTIFY_WAKE_FN")) { _ = PIBIO_SENSOR_FINISH_NOTIFY_WAKE_FN; } if (@hasDecl(@This(), "PWINBIO_QUERY_SENSOR_INTERFACE_FN")) { _ = PWINBIO_QUERY_SENSOR_INTERFACE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_ATTACH_FN")) { _ = PIBIO_ENGINE_ATTACH_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_DETACH_FN")) { _ = PIBIO_ENGINE_DETACH_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CLEAR_CONTEXT_FN")) { _ = PIBIO_ENGINE_CLEAR_CONTEXT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_PREFERRED_FORMAT_FN")) { _ = PIBIO_ENGINE_QUERY_PREFERRED_FORMAT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_INDEX_VECTOR_SIZE_FN")) { _ = PIBIO_ENGINE_QUERY_INDEX_VECTOR_SIZE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_HASH_ALGORITHMS_FN")) { _ = PIBIO_ENGINE_QUERY_HASH_ALGORITHMS_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_SET_HASH_ALGORITHM_FN")) { _ = PIBIO_ENGINE_SET_HASH_ALGORITHM_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_SAMPLE_HINT_FN")) { _ = PIBIO_ENGINE_QUERY_SAMPLE_HINT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_ACCEPT_SAMPLE_DATA_FN")) { _ = PIBIO_ENGINE_ACCEPT_SAMPLE_DATA_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_EXPORT_ENGINE_DATA_FN")) { _ = PIBIO_ENGINE_EXPORT_ENGINE_DATA_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_VERIFY_FEATURE_SET_FN")) { _ = PIBIO_ENGINE_VERIFY_FEATURE_SET_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_IDENTIFY_FEATURE_SET_FN")) { _ = PIBIO_ENGINE_IDENTIFY_FEATURE_SET_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CREATE_ENROLLMENT_FN")) { _ = PIBIO_ENGINE_CREATE_ENROLLMENT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_UPDATE_ENROLLMENT_FN")) { _ = PIBIO_ENGINE_UPDATE_ENROLLMENT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_GET_ENROLLMENT_STATUS_FN")) { _ = PIBIO_ENGINE_GET_ENROLLMENT_STATUS_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_GET_ENROLLMENT_HASH_FN")) { _ = PIBIO_ENGINE_GET_ENROLLMENT_HASH_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CHECK_FOR_DUPLICATE_FN")) { _ = PIBIO_ENGINE_CHECK_FOR_DUPLICATE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_COMMIT_ENROLLMENT_FN")) { _ = PIBIO_ENGINE_COMMIT_ENROLLMENT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_DISCARD_ENROLLMENT_FN")) { _ = PIBIO_ENGINE_DISCARD_ENROLLMENT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CONTROL_UNIT_FN")) { _ = PIBIO_ENGINE_CONTROL_UNIT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CONTROL_UNIT_PRIVILEGED_FN")) { _ = PIBIO_ENGINE_CONTROL_UNIT_PRIVILEGED_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_NOTIFY_POWER_CHANGE_FN")) { _ = PIBIO_ENGINE_NOTIFY_POWER_CHANGE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_RESERVED_1_FN")) { _ = PIBIO_ENGINE_RESERVED_1_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_PIPELINE_INIT_FN")) { _ = PIBIO_ENGINE_PIPELINE_INIT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_PIPELINE_CLEANUP_FN")) { _ = PIBIO_ENGINE_PIPELINE_CLEANUP_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_ACTIVATE_FN")) { _ = PIBIO_ENGINE_ACTIVATE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_DEACTIVATE_FN")) { _ = PIBIO_ENGINE_DEACTIVATE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_EXTENDED_INFO_FN")) { _ = PIBIO_ENGINE_QUERY_EXTENDED_INFO_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_IDENTIFY_ALL_FN")) { _ = PIBIO_ENGINE_IDENTIFY_ALL_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_SET_ENROLLMENT_SELECTOR_FN")) { _ = PIBIO_ENGINE_SET_ENROLLMENT_SELECTOR_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_SET_ENROLLMENT_PARAMETERS_FN")) { _ = PIBIO_ENGINE_SET_ENROLLMENT_PARAMETERS_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_EXTENDED_ENROLLMENT_STATUS_FN")) { _ = PIBIO_ENGINE_QUERY_EXTENDED_ENROLLMENT_STATUS_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_REFRESH_CACHE_FN")) { _ = PIBIO_ENGINE_REFRESH_CACHE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_SELECT_CALIBRATION_FORMAT_FN")) { _ = PIBIO_ENGINE_SELECT_CALIBRATION_FORMAT_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_QUERY_CALIBRATION_DATA_FN")) { _ = PIBIO_ENGINE_QUERY_CALIBRATION_DATA_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_SET_ACCOUNT_POLICY_FN")) { _ = PIBIO_ENGINE_SET_ACCOUNT_POLICY_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CREATE_KEY_FN")) { _ = PIBIO_ENGINE_CREATE_KEY_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_IDENTIFY_FEATURE_SET_SECURE_FN")) { _ = PIBIO_ENGINE_IDENTIFY_FEATURE_SET_SECURE_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_ACCEPT_PRIVATE_SENSOR_TYPE_INFO_FN")) { _ = PIBIO_ENGINE_ACCEPT_PRIVATE_SENSOR_TYPE_INFO_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_CREATE_ENROLLMENT_AUTHENTICATED_FN")) { _ = PIBIO_ENGINE_CREATE_ENROLLMENT_AUTHENTICATED_FN; } if (@hasDecl(@This(), "PIBIO_ENGINE_IDENTIFY_FEATURE_SET_AUTHENTICATED_FN")) { _ = PIBIO_ENGINE_IDENTIFY_FEATURE_SET_AUTHENTICATED_FN; } if (@hasDecl(@This(), "PWINBIO_QUERY_ENGINE_INTERFACE_FN")) { _ = PWINBIO_QUERY_ENGINE_INTERFACE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_ATTACH_FN")) { _ = PIBIO_STORAGE_ATTACH_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_DETACH_FN")) { _ = PIBIO_STORAGE_DETACH_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_CLEAR_CONTEXT_FN")) { _ = PIBIO_STORAGE_CLEAR_CONTEXT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_CREATE_DATABASE_FN")) { _ = PIBIO_STORAGE_CREATE_DATABASE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_ERASE_DATABASE_FN")) { _ = PIBIO_STORAGE_ERASE_DATABASE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_OPEN_DATABASE_FN")) { _ = PIBIO_STORAGE_OPEN_DATABASE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_CLOSE_DATABASE_FN")) { _ = PIBIO_STORAGE_CLOSE_DATABASE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_GET_DATA_FORMAT_FN")) { _ = PIBIO_STORAGE_GET_DATA_FORMAT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_GET_DATABASE_SIZE_FN")) { _ = PIBIO_STORAGE_GET_DATABASE_SIZE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_ADD_RECORD_FN")) { _ = PIBIO_STORAGE_ADD_RECORD_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_DELETE_RECORD_FN")) { _ = PIBIO_STORAGE_DELETE_RECORD_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_QUERY_BY_SUBJECT_FN")) { _ = PIBIO_STORAGE_QUERY_BY_SUBJECT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_QUERY_BY_CONTENT_FN")) { _ = PIBIO_STORAGE_QUERY_BY_CONTENT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_GET_RECORD_COUNT_FN")) { _ = PIBIO_STORAGE_GET_RECORD_COUNT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_FIRST_RECORD_FN")) { _ = PIBIO_STORAGE_FIRST_RECORD_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_NEXT_RECORD_FN")) { _ = PIBIO_STORAGE_NEXT_RECORD_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_GET_CURRENT_RECORD_FN")) { _ = PIBIO_STORAGE_GET_CURRENT_RECORD_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_CONTROL_UNIT_FN")) { _ = PIBIO_STORAGE_CONTROL_UNIT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_CONTROL_UNIT_PRIVILEGED_FN")) { _ = PIBIO_STORAGE_CONTROL_UNIT_PRIVILEGED_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_NOTIFY_POWER_CHANGE_FN")) { _ = PIBIO_STORAGE_NOTIFY_POWER_CHANGE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_PIPELINE_INIT_FN")) { _ = PIBIO_STORAGE_PIPELINE_INIT_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_PIPELINE_CLEANUP_FN")) { _ = PIBIO_STORAGE_PIPELINE_CLEANUP_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_ACTIVATE_FN")) { _ = PIBIO_STORAGE_ACTIVATE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_DEACTIVATE_FN")) { _ = PIBIO_STORAGE_DEACTIVATE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_QUERY_EXTENDED_INFO_FN")) { _ = PIBIO_STORAGE_QUERY_EXTENDED_INFO_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_NOTIFY_DATABASE_CHANGE_FN")) { _ = PIBIO_STORAGE_NOTIFY_DATABASE_CHANGE_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_RESERVED_1_FN")) { _ = PIBIO_STORAGE_RESERVED_1_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_RESERVED_2_FN")) { _ = PIBIO_STORAGE_RESERVED_2_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_UPDATE_RECORD_BEGIN_FN")) { _ = PIBIO_STORAGE_UPDATE_RECORD_BEGIN_FN; } if (@hasDecl(@This(), "PIBIO_STORAGE_UPDATE_RECORD_COMMIT_FN")) { _ = PIBIO_STORAGE_UPDATE_RECORD_COMMIT_FN; } if (@hasDecl(@This(), "PWINBIO_QUERY_STORAGE_INTERFACE_FN")) { _ = PWINBIO_QUERY_STORAGE_INTERFACE_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_SET_UNIT_STATUS_FN")) { _ = PIBIO_FRAMEWORK_SET_UNIT_STATUS_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_CLEAR_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_CLEAR_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_BEGIN_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_BEGIN_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_NEXT_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_NEXT_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_END_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_IMPORT_END_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_BEGIN_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_BEGIN_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_NEXT_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_NEXT_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_END_FN")) { _ = PIBIO_FRAMEWORK_VSM_CACHE_EXPORT_END_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_1_FN")) { _ = PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_1_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_2_FN")) { _ = PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_2_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_3_FN")) { _ = PIBIO_FRAMEWORK_VSM_STORAGE_RESERVED_3_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_ALLOCATE_MEMORY_FN")) { _ = PIBIO_FRAMEWORK_ALLOCATE_MEMORY_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_FREE_MEMORY_FN")) { _ = PIBIO_FRAMEWORK_FREE_MEMORY_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_GET_PROPERTY_FN")) { _ = PIBIO_FRAMEWORK_GET_PROPERTY_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_LOCK_AND_VALIDATE_SECURE_BUFFER_FN")) { _ = PIBIO_FRAMEWORK_LOCK_AND_VALIDATE_SECURE_BUFFER_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_RELEASE_SECURE_BUFFER_FN")) { _ = PIBIO_FRAMEWORK_RELEASE_SECURE_BUFFER_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_QUERY_AUTHORIZED_ENROLLMENTS_FN")) { _ = PIBIO_FRAMEWORK_VSM_QUERY_AUTHORIZED_ENROLLMENTS_FN; } if (@hasDecl(@This(), "PIBIO_FRAMEWORK_VSM_DECRYPT_SAMPLE_FN")) { _ = PIBIO_FRAMEWORK_VSM_DECRYPT_SAMPLE_FN; } @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/devices/biometric_framework.zig
const std = @import("std"); const Sequence = @import("../sequence.zig").Sequence; const utils = @import("../utils.zig"); pub fn FastaReader(comptime A: type) type { return struct { const Self = @This(); allocator: std.mem.Allocator, source: *std.io.StreamSource, reader: std.io.BufferedReader(4096, std.io.StreamSource.Reader), bytes_read: u64, bytes_total: u64, identifier: std.ArrayList(u8), data: std.ArrayList(u8), pub fn init(allocator: std.mem.Allocator, source: *std.io.StreamSource) Self { const stream = source.seekableStream(); return Self{ .allocator = allocator, .bytes_read = 0, .bytes_total = stream.getEndPos() catch 0, .source = source, .reader = std.io.bufferedReader(source.reader()), .identifier = std.ArrayList(u8).init(allocator), .data = std.ArrayList(u8).init(allocator), }; } pub fn deinit(self: *Self) void { self.identifier.deinit(); self.data.deinit(); } pub fn next(self: *Self) !?Sequence(A) { var buffer: [4096]u8 = undefined; while (try self.reader.reader().readUntilDelimiterOrEof(&buffer, '\n')) |line| { if (line.len == 0) continue; self.bytes_read += line.len + 1; switch (line[0]) { '>' => { if (self.identifier.items.len > 0) { const seq = try self.publish(); try self.identifier.appendSlice(line[1..]); return seq; } else { try self.identifier.appendSlice(line[1..]); } }, ';' => { // ignore comment }, else => { // ensure upper case for (line) |*letter| { if (letter.* >= 'a' and letter.* <= 'z') { letter.* -= ('a' - 'A'); } } try self.data.appendSlice(line); }, } } return self.publish(); } fn publish(self: *Self) !?Sequence(A) { if (self.identifier.items.len == 0) return null; if (self.data.items.len == 0) return null; // build this sequence const sequence = try Sequence(A).init(self.allocator, self.identifier.items, self.data.items); // reset self.identifier.clearRetainingCapacity(); self.data.clearRetainingCapacity(); return sequence; } }; } const DNA = @import("../bio/bio.zig").alphabet.DNA; test "reads fasta" { const allocator = std.testing.allocator; const fasta = \\>Seq1 \\;comment2 \\;comment2 \\TGGCGAA \\ATTGGG \\ \\>Seq2 \\TTTTT \\CAGTC \\>Seq3 \\actgc ; var source = std.io.StreamSource{ .const_buffer = std.io.fixedBufferStream(fasta) }; var reader = FastaReader(DNA).init(allocator, &source); defer reader.deinit(); var seq: Sequence(DNA) = undefined; seq = (try reader.next()).?; try std.testing.expectEqualStrings(seq.identifier, "Seq1"); try std.testing.expectEqualStrings(seq.data, "TGGCGAAATTGGG"); seq.deinit(); seq = (try reader.next()).?; try std.testing.expectEqualStrings(seq.identifier, "Seq2"); try std.testing.expectEqualStrings(seq.data, "TTTTTCAGTC"); seq.deinit(); seq = (try reader.next()).?; try std.testing.expectEqualStrings(seq.identifier, "Seq3"); try std.testing.expectEqualStrings(seq.data, "ACTGC"); seq.deinit(); try std.testing.expect((try reader.next()) == null); try std.testing.expect((try reader.next()) == null); }
src/io/fasta_reader.zig
const std = @import("std"); const Module = @import("module.zig"); const Op = @import("op.zig"); const Execution = @import("execution.zig"); const Memory = @import("Memory.zig"); const Instance = @This(); module: *const Module, allocator: *std.mem.Allocator, memory: Memory, exports: std.StringHashMap(Export), funcs: []const Func, globals: []Op.Fixval, // TODO: revisit if wasm ever becomes multi-threaded mutex: std.Thread.Mutex, pub fn init(module: *const Module, allocator: *std.mem.Allocator, context: ?*c_void, comptime Imports: type) !Instance { var exports = std.StringHashMap(Export).init(allocator); errdefer exports.deinit(); for (module.@"export") |exp| { try exports.putNoClobber(exp.field, .{ .Func = exp.index }); } var funcs = std.ArrayList(Func).init(allocator); errdefer funcs.deinit(); const karen = ImportManager(Imports); for (module.post_process.?.import_funcs) |import_func| { const type_idx = @enumToInt(import_func.type_idx); const func_type = module.@"type"[type_idx]; const lookup = karen.get(import_func.module, import_func.field) orelse return error.ImportNotFound; if (!std.meta.eql(lookup.return_type, func_type.return_type)) { return error.ImportSignatureMismatch; } if (!std.mem.eql(Module.Type.Value, lookup.param_types, func_type.param_types)) { return error.ImportSignatureMismatch; } try funcs.append(.{ .func_type = type_idx, .params = func_type.param_types, .result = func_type.return_type, .locals = &[0]Module.Type.Value{}, .kind = .{ .imported = .{ .func = lookup.func, .frame_size = lookup.frame_size }, }, }); } for (module.code) |code, i| { const type_idx = @enumToInt(module.function[i].type_idx); const func_type = module.@"type"[type_idx]; try funcs.append(.{ .func_type = type_idx, .params = func_type.param_types, .result = func_type.return_type, .locals = code.locals, .kind = .{ .instrs = code.body }, }); } var globals = try allocator.alloc(Op.Fixval, module.global.len); errdefer allocator.free(globals); for (module.global) |global, i| { globals[i] = switch (global.type.content_type) { .I32 => .{ .I32 = global.init.i32_const }, .I64 => .{ .I64 = global.init.i64_const }, .F32 => .{ .F32 = global.init.f32_const }, .F64 => .{ .F64 = global.init.f64_const }, }; } const initial = if (module.memory.len > 0) @intCast(u16, module.memory[0].limits.initial) else 0; var memory = try Memory.init(allocator, context, initial); errdefer memory.deinit(); for (module.data) |data| { // TODO: add validation in processing const offset = switch (data.offset) { .i32_const => |num| num, .global_get => @panic("I don't know"), else => unreachable, }; const addr = Memory.P(u8).init(@enumToInt(data.index) + @intCast(u32, offset)); try memory.setMany(addr, data.data); } return Instance{ .module = module, .mutex = .{}, .memory = memory, .exports = exports, .funcs = funcs.toOwnedSlice(), .globals = globals, .allocator = allocator, }; } pub fn deinit(self: *Instance) void { self.allocator.free(self.funcs); self.allocator.free(self.globals); self.memory.deinit(); self.exports.deinit(); self.* = undefined; } pub fn call(self: *Instance, name: []const u8, params: anytype) !?Value { const lock = self.mutex.acquire(); defer lock.release(); const exp = self.exports.get(name) orelse return error.ExportNotFound; if (exp != .Func) { return error.ExportNotAFunction; } const func_id = exp.Func; const func = self.funcs[func_id]; if (params.len != func.params.len) { return error.TypeSignatureMismatch; } var converted_params: [params.len]Op.Fixval = undefined; inline for ([_]void{{}} ** params.len) |_, i| { const param_type: Module.Type.Value = switch (@TypeOf(params[i])) { i32, u32 => .I32, i64, u64 => .I64, f32 => .F32, f64 => .F64, else => @compileError("Unsupported type"), }; if (param_type != func.params[i]) return error.TypeSignatureMismatch; converted_params[i] = switch (@TypeOf(params[i])) { i32 => .{ .I32 = params[i] }, i64 => .{ .I64 = params[i] }, u32 => .{ .U32 = params[i] }, u64 => .{ .U64 = params[i] }, f32 => .{ .F32 = params[i] }, f64 => .{ .F64 = params[i] }, else => @compileError("Unsupported type"), }; } var stack: [1 << 10]Op.Fixval = undefined; const result = try Execution.run(self, &stack, func_id, converted_params[0..params.len]); if (result) |res| { return switch (func.result.?) { .I32 => Value{ .I32 = res.I32 }, .I64 => Value{ .I64 = res.I64 }, .F32 => Value{ .F32 = res.F32 }, .F64 => Value{ .F64 = res.F64 }, }; } else { return null; } } pub fn getGlobal(self: Instance, idx: usize) Value { const raw = self.globals[idx]; return switch (self.module.global[idx].type.content_type) { .I32 => Value{ .I32 = raw.I32 }, .I64 => Value{ .I64 = raw.I64 }, .F32 => Value{ .F32 = raw.F32 }, .F64 => Value{ .F64 = raw.F64 }, }; } pub const Value = union(Module.Type.Value) { I32: i32, I64: i64, F32: f32, F64: f64, }; pub const Export = union(enum) { Func: usize, Table: usize, Memory: usize, Global: usize, }; pub fn ImportManager(comptime Imports: type) type { const V = struct { func: ImportFunc, frame_size: usize, param_types: []const Module.Type.Value, return_type: ?Module.Type.Value, }; const KV = struct { @"0": []const u8, @"1": V, }; const helpers = struct { fn Unwrapped(comptime T: type) type { return switch (@typeInfo(T)) { .ErrorUnion => |eu_info| Unwrapped(eu_info.payload), .Enum => |e_info| if (e_info.is_exhaustive) @compileError("Enum must be exhaustive") else e_info.tag_type, .Struct => { return std.meta.Int(.unsigned, @bitSizeOf(T)); }, else => T, }; } fn shim(comptime func: anytype) ImportFunc { return struct { fn unwrap(raw: anytype) !Unwrapped(@TypeOf(raw)) { const T = @TypeOf(raw); return switch (@typeInfo(T)) { .ErrorUnion => unwrap(try raw), .Enum => @enumToInt(raw), .Struct => @bitCast(Unwrapped(T), raw), else => raw, }; } pub fn shimmed(ctx: *Execution, params: []const Op.Fixval) Op.WasmTrap!?Op.Fixval { var args: std.meta.ArgsTuple(@TypeOf(func)) = undefined; args[0] = ctx.memory; inline for (std.meta.fields(@TypeOf(args))) |f, i| { if (i == 0) continue; const raw_value = switch (Unwrapped(f.field_type)) { i32 => params[i - 1].I32, i64 => params[i - 1].I64, u32 => params[i - 1].U32, u64 => params[i - 1].U64, f32 => params[i - 1].F32, f64 => params[i - 1].F64, else => @compileError("Signature not supported"), }; args[i] = switch (@typeInfo(f.field_type)) { .Enum => @intToEnum(f.field_type, raw_value), .Struct => @bitCast(f.field_type, raw_value), else => raw_value, }; } // TODO: move async call to where this is being invoked // const fixval_len = std.math.divCeil(comptime_int, @sizeOf(@Frame(func)), @sizeOf(Op.Fixval)) catch unreachable; // const frame_loc = ctx.pushOpaque(fixval_len) catch unreachable; // const frame = @ptrCast(*@Frame(func), frame_loc); // comptime const opts = std.builtin.CallOptions{ .modifier = .async_kw }; // frame.* = @call(opts, func, args); // const result = nosuspend await frame; const result = try unwrap(@call(.{}, func, args)); return switch (@TypeOf(result)) { void => null, i32 => Op.Fixval{ .I32 = result }, i64 => Op.Fixval{ .I64 = result }, u32 => Op.Fixval{ .U32 = result }, u64 => Op.Fixval{ .U64 = result }, f32 => Op.Fixval{ .F32 = result }, f64 => Op.Fixval{ .F64 = result }, else => @compileError("Signature not supported"), }; } }.shimmed; } fn mapType(comptime T: type) ?Module.Type.Value { return switch (Unwrapped(T)) { void => null, i32, u32 => .I32, i64, u64 => .I64, f32 => .F32, f64 => .F64, else => @compileError("Type '" ++ @typeName(T) ++ "' not supported"), }; } }; const sep = "\x00\x00"; var kvs: []const KV = &[0]KV{}; inline for (std.meta.declarations(Imports)) |decl| { if (decl.is_pub) { inline for (std.meta.declarations(decl.data.Type)) |decl2| { if (decl2.is_pub) { const func = @field(decl.data.Type, decl2.name); const fn_info = @typeInfo(@TypeOf(func)).Fn; const shimmed = helpers.shim(func); kvs = kvs ++ [1]KV{.{ .@"0" = decl.name ++ sep ++ decl2.name, .@"1" = .{ .func = shimmed, .frame_size = @sizeOf(@Frame(shimmed)), .param_types = params: { var param_types: [fn_info.args.len - 1]Module.Type.Value = undefined; for (param_types) |*param, i| { param.* = helpers.mapType(fn_info.args[i + 1].arg_type.?).?; } break :params &param_types; }, .return_type = helpers.mapType(fn_info.return_type.?), }, }}; } } } } const map = if (kvs.len > 0) std.ComptimeStringMap(V, kvs) else {}; return struct { pub fn get(module: []const u8, field: []const u8) ?V { if (kvs.len == 0) return null; var buffer: [1 << 10]u8 = undefined; var fbs = std.io.fixedBufferStream(&buffer); fbs.writer().writeAll(module) catch return null; fbs.writer().writeAll(sep) catch return null; fbs.writer().writeAll(field) catch return null; return map.get(fbs.getWritten()); } }; } const ImportFunc = fn (ctx: *Execution, params: []const Op.Fixval) Op.WasmTrap!?Op.Fixval; pub const Func = struct { func_type: usize, params: []const Module.Type.Value, result: ?Module.Type.Value, locals: []const Module.Type.Value, kind: union(enum) { imported: struct { func: ImportFunc, frame_size: usize, }, instrs: []const Module.Instr, }, }; test "" { _ = call; }
src/instance.zig
/// Generic Matrix4x4 Type, right handed column major pub fn Generic(comptime T: type) type { switch (T) { f16, f32, f64, f128, i16, i32, i64, i128 => { return struct { const Self = @This(); m0: T = 0, m4: T = 0, m8: T = 0, m12: T = 0, m1: T = 0, m5: T = 0, m9: T = 0, m13: T = 0, m2: T = 0, m6: T = 0, m10: T = 0, m14: T = 0, m3: T = 0, m7: T = 0, m11: T = 0, m15: T = 0, /// Returns identity matrix pub fn identity() Self { return .{ .m0 = 1, .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = 1, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = 1, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 1, }; } /// Multiplies the matrices, returns the result pub fn mul(left: Self, right: Self) Self { return .{ .m0 = left.m0 * right.m0 + left.m1 * right.m4 + left.m2 * right.m8 + left.m3 * right.m12, .m1 = left.m0 * right.m1 + left.m1 * right.m5 + left.m2 * right.m9 + left.m3 * right.m13, .m2 = left.m0 * right.m2 + left.m1 * right.m6 + left.m2 * right.m10 + left.m3 * right.m14, .m3 = left.m0 * right.m3 + left.m1 * right.m7 + left.m2 * right.m11 + left.m3 * right.m15, .m4 = left.m4 * right.m0 + left.m5 * right.m4 + left.m6 * right.m8 + left.m7 * right.m12, .m5 = left.m4 * right.m1 + left.m5 * right.m5 + left.m6 * right.m9 + left.m7 * right.m13, .m6 = left.m4 * right.m2 + left.m5 * right.m6 + left.m6 * right.m10 + left.m7 * right.m14, .m7 = left.m4 * right.m3 + left.m5 * right.m7 + left.m6 * right.m11 + left.m7 * right.m15, .m8 = left.m8 * right.m0 + left.m9 * right.m4 + left.m10 * right.m8 + left.m11 * right.m12, .m9 = left.m8 * right.m1 + left.m9 * right.m5 + left.m10 * right.m9 + left.m11 * right.m13, .m10 = left.m8 * right.m2 + left.m9 * right.m6 + left.m10 * right.m10 + left.m11 * right.m14, .m11 = left.m8 * right.m3 + left.m9 * right.m7 + left.m10 * right.m11 + left.m11 * right.m15, .m12 = left.m12 * right.m0 + left.m13 * right.m4 + left.m14 * right.m8 + left.m15 * right.m12, .m13 = left.m12 * right.m1 + left.m13 * right.m5 + left.m14 * right.m9 + left.m15 * right.m13, .m14 = left.m12 * right.m2 + left.m13 * right.m6 + left.m14 * right.m10 + left.m15 * right.m14, .m15 = left.m12 * right.m3 + left.m13 * right.m7 + left.m14 * right.m11 + left.m15 * right.m15, }; } /// Returns an translation matrix pub fn translate(x: T, y: T, z: T) Self { return Self{ .m0 = 1, .m4 = 0, .m8 = 0, .m12 = x, .m1 = 0, .m5 = 1, .m9 = 0, .m13 = y, .m2 = 0, .m6 = 0, .m10 = 1, .m14 = z, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 1, }; } /// Returns an scaled matrix pub fn scale(x: T, y: T, z: T) Self { return Self{ .m0 = x, .m4 = 0, .m8 = 0, .m12 = 0, .m1 = 0, .m5 = y, .m9 = 0, .m13 = 0, .m2 = 0, .m6 = 0, .m10 = z, .m14 = 0, .m3 = 0, .m7 = 0, .m11 = 0, .m15 = 1, }; } /// Invert provided matrix pub fn invert(self: Self) Self { // Cache the matrix values (speed optimization) const a00 = self.m0; const a01 = self.m1; const a02 = self.m2; const a03 = self.m3; const a10 = self.m4; const a11 = self.m5; const a12 = self.m6; const a13 = self.m7; const a20 = self.m8; const a21 = self.m9; const a22 = self.m10; const a23 = self.m11; const a30 = self.m12; const a31 = self.m13; const a32 = self.m14; const a33 = self.m15; const b00 = a00 * a11 - a01 * a10; const b01 = a00 * a12 - a02 * a10; const b02 = a00 * a13 - a03 * a10; const b03 = a01 * a12 - a02 * a11; const b04 = a01 * a13 - a03 * a11; const b05 = a02 * a13 - a03 * a12; const b06 = a20 * a31 - a21 * a30; const b07 = a20 * a32 - a22 * a30; const b08 = a20 * a33 - a23 * a30; const b09 = a21 * a32 - a22 * a31; const b10 = a21 * a33 - a23 * a31; const b11 = a22 * a33 - a23 * a32; // Calculate the invert determinant (inlined to avoid double-caching) const invDet: T = 1 / (b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06); return Self{ .m0 = (a11 * b11 - a12 * b10 + a13 * b09) * invDet, .m1 = (-a01 * b11 + a02 * b10 - a03 * b09) * invDet, .m2 = (a31 * b05 - a32 * b04 + a33 * b03) * invDet, .m3 = (-a21 * b05 + a22 * b04 - a23 * b03) * invDet, .m4 = (-a10 * b11 + a12 * b08 - a13 * b07) * invDet, .m5 = (a00 * b11 - a02 * b08 + a03 * b07) * invDet, .m6 = (-a30 * b05 + a32 * b02 - a33 * b01) * invDet, .m7 = (a20 * b05 - a22 * b02 + a23 * b01) * invDet, .m8 = (a10 * b10 - a11 * b08 + a13 * b06) * invDet, .m9 = (-a00 * b10 + a01 * b08 - a03 * b06) * invDet, .m10 = (a30 * b04 - a31 * b02 + a33 * b00) * invDet, .m11 = (-a20 * b04 + a21 * b02 - a23 * b00) * invDet, .m12 = (-a10 * b09 + a11 * b07 - a12 * b06) * invDet, .m13 = (a00 * b09 - a01 * b07 + a02 * b06) * invDet, .m14 = (-a30 * b03 + a31 * b01 - a32 * b00) * invDet, .m15 = (a20 * b03 - a21 * b01 + a22 * b00) * invDet, }; } /// Returns perspective projection matrix pub fn frustum(left: T, right: T, bottom: T, top: T, near: T, far: T) Self { const rl = right - left; const tb = top - bottom; const _fn = far - near; return Self{ .m0 = (near * 2) / rl, .m1 = 0, .m2 = 0, .m3 = 0, .m4 = 0, .m5 = (near * 2) / tb, .m6 = 0, .m7 = 0, .m8 = (right + left) / rl, .m9 = (top + bottom) / tb, .m10 = -(far + near) / _fn, .m11 = -1, .m12 = 0, .m13 = 0, .m14 = -(far * near * 2) / _fn, .m15 = 0, }; } /// Returns perspective projection matrix /// NOTE: Angle should be provided in radians pub fn perspective(fovy: T, aspect: T, near: T, far: T) Self { const top = near * tan(fovy * 0.5); const right = top * aspect; return Self.frustum(-right, right, -top, top, near, far); } /// Returns orthographic projection matrix pub fn ortho(left: T, right: T, bottom: T, top: T, near: T, far: T) Self { const rl = right - left; const tb = top - bottom; const _fn = far - near; return .{ .m0 = 2 / rl, .m1 = 0, .m2 = 0, .m3 = 0, .m4 = 0, .m5 = 2 / tb, .m6 = 0, .m7 = 0, .m8 = 0, .m9 = 0, .m10 = -2 / _fn, .m11 = 0, .m12 = -(left + right) / rl, .m13 = -(top + bottom) / tb, .m14 = -(far + near) / _fn, .m15 = 1, }; } /// Create rotation matrix from axis and angle /// NOTE: Angle should be provided in radians pub fn rotate(x0: T, y0: T, z0: T, angle: T) Self { var x = x0; var y = y0; var z = z0; var len = @sqrt(x * x + y * y + z * z); if ((len != 1) and (len != 0)) { len = 1 / len; x *= len; y *= len; z *= len; } const sinres = @sin(angle); const cosres = @cos(angle); const t = 1.0 - cosres; return Self{ .m0 = x * x * t + cosres, .m1 = y * x * t + z * sinres, .m2 = z * x * t - y * sinres, .m3 = 0, .m4 = x * y * t - z * sinres, .m5 = y * y * t + cosres, .m6 = z * y * t + x * sinres, .m7 = 0, .m8 = x * z * t + y * sinres, .m9 = y * z * t - x * sinres, .m10 = z * z * t + cosres, .m11 = 0, .m12 = 0, .m13 = 0, .m14 = 0, .m15 = 1, }; } /// Converts the matrix into the array(column major) pub fn toArray(self: Self) [16]T { return [16]T{ self.m0, self.m1, self.m2, self.m3, self.m4, self.m5, self.m6, self.m7, self.m8, self.m9, self.m10, self.m11, self.m12, self.m13, self.m14, self.m15, }; } }; }, else => @compileError("Matrix4x4 not implemented for " ++ @typeName(T)), } }
src/core/math/mat4x4.zig
const std = @import("std"); const io = std.io; const Allocator = std.mem.Allocator; pub fn main() anyerror!void { var buf: [4000]u8 = undefined; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var code = try Code.init(alloc); defer code.deinit(); var stream = io.bufferedReader(io.getStdIn().reader()); var rd = stream.reader(); while (try rd.readUntilDelimiterOrEof(&buf, '\n')) |line| { try parseCode(line, &code, Code.append); } var vm = try VM.init(alloc, code.items()); defer vm.deinit(); // Part 1: while (vm.step() and vm.hits[vm.pc] != 1) {} std.log.info("Repeat(1) = {}", .{vm.accum}); vm.reset(); // Part 2 (sort of brute force): while (true) { const pc = vm.pc; const accum = vm.accum; // Update the instruction according to the rules: replace any jmp with // a nop and any nop with a jmp to find the faulty instruction. var c = &code.code.items[vm.pc]; const orig = c.*; c.* = switch (c.*) { .nop => |n| .{ .jmp = n }, .jmp => |n| .{ .nop = n }, .acc => orig, }; // Test if modifying the instruction at the PC causes the program to // terminate. while (vm.step() and vm.hits[vm.pc] != 1) {} if (vm.pc == vm.code.len) { // If the PC is after the end of the code, then the program exited // successfully. std.log.info("Patched instruction {} {} -> {}", .{ vm.pc + 1, orig, c.* }); std.log.info("Final = {}", .{vm.accum}); break; } c.* = orig; // Reset hit counters and put pc and accum back at their values up until // this run. Step over the instruction when we're done since we know the // program still loops. vm.reset(); vm.pc = pc; vm.accum = accum; _ = vm.step(); } } const Code = struct { const ArrayList = std.ArrayList(Op); code: ArrayList, pub fn init(allocator: *Allocator) !Code { return Code{ .code = ArrayList.init(allocator), }; } pub fn deinit(self: *Code) void { self.code.deinit(); } fn items(self: Code) []const Op { return self.code.items; } fn append(self: *Code, op: Op) anyerror!void { try self.code.append(op); } }; const Op = union(enum) { acc: i32, jmp: i32, nop: i32, }; const ParseError = error{ InvalidInstr, MissingArg, }; pub fn parseCode(data: []const u8, ctx: anytype, next: fn (@TypeOf(ctx), Op) anyerror!void) !void { var iter = std.mem.tokenize(data, " \n"); const eql = std.mem.eql; while (iter.next()) |tok| { var n: i32 = undefined; if (iter.next()) |num| { n = try std.fmt.parseInt(i32, num, 10); } else { return ParseError.MissingArg; } if (eql(u8, "acc", tok)) { try next(ctx, .{ .acc = n }); } else if (eql(u8, "jmp", tok)) { try next(ctx, .{ .jmp = n }); } else if (eql(u8, "nop", tok)) { try next(ctx, .{ .nop = n }); } else { return ParseError.InvalidInstr; } } } const VM = struct { allocator: *Allocator, pc: usize = 0, code: []const Op, hits: []usize, accum: i64 = 0, const Error = error{InvalidPC}; pub fn init(allocator: *Allocator, code: []const Op) !VM { var self = VM{ .allocator = allocator, .code = code, .hits = try allocator.alloc(usize, code.len), }; for (self.hits) |*h| h.* = 0; return self; } pub fn deinit(self: *VM) void { self.allocator.free(self.hits); } pub fn reset(self: *VM) void { self.pc = 0; self.accum = 0; for (self.hits) |*h| h.* = 0; } pub fn step(self: *VM) bool { if (self.pc == self.code.len) { return false; } self.hits[self.pc] += 1; switch (self.code[self.pc]) { .acc => |num| self.accum += num, .jmp => |rel| { @setRuntimeSafety(false); self.pc = @intCast(usize, @intCast(i64, self.pc) + rel); return self.pc != self.code.len; }, .nop => {}, } self.pc += 1; return self.pc != self.code.len; } }; test "VM loop test" { var code = try Code.init(std.testing.allocator); defer code.deinit(); try parseCode( @embedFile("sample"), &code, Code.append, ); var vm = try VM.init(std.testing.allocator, code.items()); defer vm.deinit(); while (vm.step() and vm.hits[vm.pc] == 0) {} std.testing.expectEqual(@intCast(i64, 5), vm.accum); }
day8/src/main.zig
const std = @import("std"); const mem = std.mem; const unicode = std.unicode; const Context = @import("../../Context.zig"); const Ziglyph = @import("../../ziglyph.zig").Ziglyph; const GraphemeIterator = @import("../../zigstr/GraphemeIterator.zig"); const Self = @This(); allocator: *mem.Allocator, context: *Context, giter: ?GraphemeIterator, ziglyph: Ziglyph, pub fn new(ctx: *Context) !Self { return Self{ .allocator = ctx.allocator, .context = ctx, .giter = null, .ziglyph = try Ziglyph.new(ctx), }; } /// AmbiguousWidth determines the width of ambiguous characters according to the context. In an /// East Asian context, the width of ambiguous code points should be 2 (full), and 1 (half) /// in non-East Asian contexts. The most common use case is `half`. pub const AmbiguousWidth = enum(u2) { half = 1, full = 2, }; /// codePointWidth returns how many cells (or columns) wide `cp` should be when rendered in a /// fixed-width font. pub fn codePointWidth(self: Self, cp: u21, am_width: AmbiguousWidth) !i8 { const ambiguous = try self.context.getAmbiguous(); const enclosing = try self.context.getEnclosing(); const format = try self.context.getFormat(); const fullwidth = try self.context.getFullwidth(); const nonspacing = try self.context.getNonspacing(); const regional = try self.context.getRegional(); const wide = try self.context.getWide(); if (cp == 0x000 or cp == 0x0005 or cp == 0x0007 or (cp >= 0x000A and cp <= 0x000F)) { // Control. return 0; } else if (cp == 0x0008) { // backspace return -1; } else if (cp == 0x00AD) { // soft-hyphen return 1; } else if (cp == 0x2E3A) { // two-em dash return 2; } else if (cp == 0x2E3B) { // three-em dash return 3; } else if (enclosing.isEnclosingMark(cp) or nonspacing.isNonspacingMark(cp)) { // Combining Marks. return 0; } else if (format.isFormat(cp) and (!(cp >= 0x0600 and cp <= 0x0605) and cp != 0x061C and cp != 0x06DD and cp != 0x08E2)) { // Format except Arabic. return 0; } else if ((cp >= 0x1160 and cp <= 0x11FF) or (cp >= 0x2060 and cp <= 0x206F) or (cp >= 0xFFF0 and cp <= 0xFFF8) or (cp >= 0xE0000 and cp <= 0xE0FFF)) { // Hangul syllable and ignorable. return 0; } else if ((cp >= 0x3400 and cp <= 0x4DBF) or (cp >= 0x4E00 and cp <= 0x9FFF) or (cp >= 0xF900 and cp <= 0xFAFF) or (cp >= 0x20000 and cp <= 0x2FFFD) or (cp >= 0x30000 and cp <= 0x3FFFD)) { return 2; } else if (wide.isWide(cp) or fullwidth.isFullwidth(cp)) { return 2; } else if (regional.isRegionalIndicator(cp)) { return 2; } else if (ambiguous.isAmbiguous(cp)) { return @enumToInt(am_width); } else { return 1; } } /// strWidth returns how many cells (or columns) wide `str` should be when rendered in a /// fixed-width font. pub fn strWidth(self: *Self, str: []const u8, am_width: AmbiguousWidth) !usize { var total: isize = 0; if (self.giter == null) { self.giter = try GraphemeIterator.new(self.context, str); } else { try self.giter.?.reinit(str); } var giter = self.giter.?; const extpic = try self.context.getExtPic(); while (try giter.next()) |gc| { var cp_iter = (try unicode.Utf8View.init(gc.bytes)).iterator(); while (cp_iter.nextCodepoint()) |cp| { var w = try self.codePointWidth(cp, am_width); if (w != 0) { if (extpic.isExtendedPictographic(cp)) { if (cp_iter.nextCodepoint()) |ncp| { if (ncp == 0xFE0E) w = 1; // Emoji text sequence. } } total += w; break; } } } return if (total > 0) @intCast(usize, total) else 0; } const expectEqual = std.testing.expectEqual; test "Grapheme Width" { var ctx = Context.init(std.testing.allocator); defer ctx.deinit(); var width = try new(&ctx); expectEqual(@as(i8, -1), try width.codePointWidth(0x0008, .half)); // \b DEL expectEqual(@as(i8, 0), try width.codePointWidth(0x0000, .half)); // null expectEqual(@as(i8, 0), try width.codePointWidth(0x0005, .half)); // Cf expectEqual(@as(i8, 0), try width.codePointWidth(0x0007, .half)); // \a BEL expectEqual(@as(i8, 0), try width.codePointWidth(0x000A, .half)); // \n LF expectEqual(@as(i8, 0), try width.codePointWidth(0x000B, .half)); // \v VT expectEqual(@as(i8, 0), try width.codePointWidth(0x000C, .half)); // \f FF expectEqual(@as(i8, 0), try width.codePointWidth(0x000D, .half)); // \r CR expectEqual(@as(i8, 0), try width.codePointWidth(0x000E, .half)); // SQ expectEqual(@as(i8, 0), try width.codePointWidth(0x000F, .half)); // SI expectEqual(@as(i8, 0), try width.codePointWidth(0x070F, .half)); // Cf expectEqual(@as(i8, 1), try width.codePointWidth(0x0603, .half)); // Cf Arabic expectEqual(@as(i8, 1), try width.codePointWidth(0x00AD, .half)); // soft-hyphen expectEqual(@as(i8, 2), try width.codePointWidth(0x2E3A, .half)); // two-em dash expectEqual(@as(i8, 3), try width.codePointWidth(0x2E3B, .half)); // three-em dash expectEqual(@as(i8, 1), try width.codePointWidth(0x00BD, .half)); // ambiguous halfwidth expectEqual(@as(i8, 2), try width.codePointWidth(0x00BD, .full)); // ambiguous fullwidth expectEqual(@as(i8, 1), try width.codePointWidth('é', .half)); expectEqual(@as(i8, 2), try width.codePointWidth('😊', .half)); expectEqual(@as(i8, 2), try width.codePointWidth('统', .half)); expectEqual(@as(usize, 5), try width.strWidth("Hello\r\n", .half)); expectEqual(@as(usize, 1), try width.strWidth("\u{0065}\u{0301}", .half)); expectEqual(@as(usize, 2), try width.strWidth("\u{1F476}\u{1F3FF}\u{0308}\u{200D}\u{1F476}\u{1F3FF}", .half)); expectEqual(@as(usize, 8), try width.strWidth("Hello 😊", .half)); expectEqual(@as(usize, 8), try width.strWidth("Héllo 😊", .half)); expectEqual(@as(usize, 8), try width.strWidth("Héllo :)", .half)); expectEqual(@as(usize, 8), try width.strWidth("Héllo 🇪🇸", .half)); expectEqual(@as(usize, 2), try width.strWidth("\u{26A1}", .half)); // Lone emoji expectEqual(@as(usize, 1), try width.strWidth("\u{26A1}\u{FE0E}", .half)); // Text sequence expectEqual(@as(usize, 2), try width.strWidth("\u{26A1}\u{FE0F}", .half)); // Presentation sequence }
src/components/aggregate/Width.zig
const std = @import("std"); const Board = @import("types/Board.zig"); const Move = @import("types/Move.zig"); const MoveList = @import("types/MoveList.zig"); //const console = @import("utils/console.zig"); pub fn perft(board: *Board, depth: usize, root: bool) u64 { var leaf_count: u64 = 0; var move_list = MoveList{}; var move_list_iterator = MoveList.Iterator{ .iter = &move_list.list }; const num_moves = board.generateLegalMoves(&move_list_iterator); if (depth == 1) { return num_moves; } if (root) { comptime const num_threads: usize = 8; var results = [_]u64{0} ** num_threads; var move_num = std.atomic.Int(usize).init(0); var perft_data = PerftData{ .board = board, .remaining_depth = depth - 1, .move_list = &move_list.list, .num_moves = num_moves, .move_num = &move_num, .results = &results, }; var threads: [num_threads]*std.Thread = undefined; var thread_num: usize = 0; while (thread_num < num_threads) : (thread_num += 1) { var thread_data = ThreadData{ .thread_index = thread_num, .perft_data = &perft_data, }; threads[thread_num] = std.Thread.spawn(thread_data, getAndPerftMove) catch |err| { unreachable; }; } thread_num = 0; while (thread_num < num_threads) : (thread_num += 1) { threads[thread_num].wait(); leaf_count += perft_data.results[thread_num]; } } else { var move_num: usize = 0; while (move_num < num_moves) { const move = move_list.list[move_num]; move_num += 1; var child = board.*; child.makeMove(move); //var old_leaf_count = leaf_count; leaf_count += perft(&child, depth - 1, false); //if (root) { // console.println("Move: {}, Nodes: {}", .{ move.toString(), leaf_count - old_leaf_count }); //} } } return leaf_count; } fn getAndPerftMove(context: ThreadData) void { var perft_data = context.perft_data; var leaf_count: u64 = 0; while (true) { const next_move_index = perft_data.move_num.fetchAdd(1); if (next_move_index >= perft_data.num_moves) { break; } const move = perft_data.move_list[next_move_index]; var child = perft_data.board.*; child.makeMove(move); leaf_count += perft(&child, perft_data.remaining_depth, false); } perft_data.results[context.thread_index] = leaf_count; } const PerftData = struct { board: *Board, remaining_depth: usize, move_list: [*]Move, num_moves: usize, move_num: *std.atomic.Int(usize), results: [*]u64, }; const ThreadData = struct { thread_index: usize, perft_data: *PerftData, };
src/perft.zig
pub const INCLUDED_FCI = @as(u32, 1); pub const _A_NAME_IS_UTF = @as(u32, 128); pub const _A_EXEC = @as(u32, 64); pub const INCLUDED_TYPES_FCI_FDI = @as(u32, 1); pub const CB_MAX_DISK = @as(i32, 2147483647); pub const CB_MAX_FILENAME = @as(u32, 256); pub const CB_MAX_CABINET_NAME = @as(u32, 256); pub const CB_MAX_CAB_PATH = @as(u32, 256); pub const CB_MAX_DISK_NAME = @as(u32, 256); pub const INCLUDED_FDI = @as(u32, 1); //-------------------------------------------------------------------------------- // Section: Types (34) //-------------------------------------------------------------------------------- pub const FDICREATE_CPU_TYPE = enum(u32) { @"286" = 0, @"386" = 1, }; pub const cpu80286 = FDICREATE_CPU_TYPE.@"286"; pub const cpu80386 = FDICREATE_CPU_TYPE.@"386"; pub const ERF = extern struct { erfOper: i32, erfType: i32, fError: BOOL, }; pub const FCIERROR = enum(i32) { NONE = 0, OPEN_SRC = 1, READ_SRC = 2, ALLOC_FAIL = 3, TEMP_FILE = 4, BAD_COMPR_TYPE = 5, CAB_FILE = 6, USER_ABORT = 7, MCI_FAIL = 8, CAB_FORMAT_LIMIT = 9, }; pub const FCIERR_NONE = FCIERROR.NONE; pub const FCIERR_OPEN_SRC = FCIERROR.OPEN_SRC; pub const FCIERR_READ_SRC = FCIERROR.READ_SRC; pub const FCIERR_ALLOC_FAIL = FCIERROR.ALLOC_FAIL; pub const FCIERR_TEMP_FILE = FCIERROR.TEMP_FILE; pub const FCIERR_BAD_COMPR_TYPE = FCIERROR.BAD_COMPR_TYPE; pub const FCIERR_CAB_FILE = FCIERROR.CAB_FILE; pub const FCIERR_USER_ABORT = FCIERROR.USER_ABORT; pub const FCIERR_MCI_FAIL = FCIERROR.MCI_FAIL; pub const FCIERR_CAB_FORMAT_LIMIT = FCIERROR.CAB_FORMAT_LIMIT; pub const CCAB = extern struct { cb: u32, cbFolderThresh: u32, cbReserveCFHeader: u32, cbReserveCFFolder: u32, cbReserveCFData: u32, iCab: i32, iDisk: i32, fFailOnIncompressible: i32, setID: u16, szDisk: [256]CHAR, szCab: [256]CHAR, szCabPath: [256]CHAR, }; pub const PFNFCIALLOC = fn( cb: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PFNFCIFREE = fn( memory: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFNFCIOPEN = fn( pszFile: ?PSTR, oflag: i32, pmode: i32, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) isize; pub const PFNFCIREAD = fn( hf: isize, memory: ?*anyopaque, cb: u32, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNFCIWRITE = fn( hf: isize, memory: ?*anyopaque, cb: u32, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNFCICLOSE = fn( hf: isize, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNFCISEEK = fn( hf: isize, dist: i32, seektype: i32, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNFCIDELETE = fn( pszFile: ?PSTR, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNFCIGETNEXTCABINET = fn( pccab: ?*CCAB, cbPrevCab: u32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFNFCIFILEPLACED = fn( pccab: ?*CCAB, pszFile: ?PSTR, cbFile: i32, fContinuation: BOOL, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNFCIGETOPENINFO = fn( pszName: ?PSTR, pdate: ?*u16, ptime: ?*u16, pattribs: ?*u16, err: ?*i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) isize; pub const PFNFCISTATUS = fn( typeStatus: u32, cb1: u32, cb2: u32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNFCIGETTEMPFILE = fn( // TODO: what to do with BytesParamIndex 1? pszTempName: ?PSTR, cbTempName: i32, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const FDIERROR = enum(i32) { NONE = 0, CABINET_NOT_FOUND = 1, NOT_A_CABINET = 2, UNKNOWN_CABINET_VERSION = 3, CORRUPT_CABINET = 4, ALLOC_FAIL = 5, BAD_COMPR_TYPE = 6, MDI_FAIL = 7, TARGET_FILE = 8, RESERVE_MISMATCH = 9, WRONG_CABINET = 10, USER_ABORT = 11, EOF = 12, }; pub const FDIERROR_NONE = FDIERROR.NONE; pub const FDIERROR_CABINET_NOT_FOUND = FDIERROR.CABINET_NOT_FOUND; pub const FDIERROR_NOT_A_CABINET = FDIERROR.NOT_A_CABINET; pub const FDIERROR_UNKNOWN_CABINET_VERSION = FDIERROR.UNKNOWN_CABINET_VERSION; pub const FDIERROR_CORRUPT_CABINET = FDIERROR.CORRUPT_CABINET; pub const FDIERROR_ALLOC_FAIL = FDIERROR.ALLOC_FAIL; pub const FDIERROR_BAD_COMPR_TYPE = FDIERROR.BAD_COMPR_TYPE; pub const FDIERROR_MDI_FAIL = FDIERROR.MDI_FAIL; pub const FDIERROR_TARGET_FILE = FDIERROR.TARGET_FILE; pub const FDIERROR_RESERVE_MISMATCH = FDIERROR.RESERVE_MISMATCH; pub const FDIERROR_WRONG_CABINET = FDIERROR.WRONG_CABINET; pub const FDIERROR_USER_ABORT = FDIERROR.USER_ABORT; pub const FDIERROR_EOF = FDIERROR.EOF; pub const FDICABINETINFO = extern struct { cbCabinet: i32, cFolders: u16, cFiles: u16, setID: u16, iCabinet: u16, fReserve: BOOL, hasprev: BOOL, hasnext: BOOL, }; pub const FDIDECRYPTTYPE = enum(i32) { NEW_CABINET = 0, NEW_FOLDER = 1, DECRYPT = 2, }; pub const fdidtNEW_CABINET = FDIDECRYPTTYPE.NEW_CABINET; pub const fdidtNEW_FOLDER = FDIDECRYPTTYPE.NEW_FOLDER; pub const fdidtDECRYPT = FDIDECRYPTTYPE.DECRYPT; pub const FDIDECRYPT = extern struct { fdidt: FDIDECRYPTTYPE, pvUser: ?*anyopaque, Anonymous: extern union { cabinet: extern struct { pHeaderReserve: ?*anyopaque, cbHeaderReserve: u16, setID: u16, iCabinet: i32, }, folder: extern struct { pFolderReserve: ?*anyopaque, cbFolderReserve: u16, iFolder: u16, }, decrypt: extern struct { pDataReserve: ?*anyopaque, cbDataReserve: u16, pbData: ?*anyopaque, cbData: u16, fSplit: BOOL, cbPartial: u16, }, }, }; pub const PFNALLOC = fn( cb: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub const PFNFREE = fn( pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const PFNOPEN = fn( pszFile: ?PSTR, oflag: i32, pmode: i32, ) callconv(@import("std").os.windows.WINAPI) isize; pub const PFNREAD = fn( hf: isize, // TODO: what to do with BytesParamIndex 2? pv: ?*anyopaque, cb: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNWRITE = fn( hf: isize, // TODO: what to do with BytesParamIndex 2? pv: ?*anyopaque, cb: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub const PFNCLOSE = fn( hf: isize, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNSEEK = fn( hf: isize, dist: i32, seektype: i32, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PFNFDIDECRYPT = fn( pfdid: ?*FDIDECRYPT, ) callconv(@import("std").os.windows.WINAPI) i32; pub const FDINOTIFICATION = extern struct { cb: i32, psz1: ?PSTR, psz2: ?PSTR, psz3: ?PSTR, pv: ?*anyopaque, hf: isize, date: u16, time: u16, attribs: u16, setID: u16, iCabinet: u16, iFolder: u16, fdie: FDIERROR, }; pub const FDINOTIFICATIONTYPE = enum(i32) { CABINET_INFO = 0, PARTIAL_FILE = 1, COPY_FILE = 2, CLOSE_FILE_INFO = 3, NEXT_CABINET = 4, ENUMERATE = 5, }; pub const fdintCABINET_INFO = FDINOTIFICATIONTYPE.CABINET_INFO; pub const fdintPARTIAL_FILE = FDINOTIFICATIONTYPE.PARTIAL_FILE; pub const fdintCOPY_FILE = FDINOTIFICATIONTYPE.COPY_FILE; pub const fdintCLOSE_FILE_INFO = FDINOTIFICATIONTYPE.CLOSE_FILE_INFO; pub const fdintNEXT_CABINET = FDINOTIFICATIONTYPE.NEXT_CABINET; pub const fdintENUMERATE = FDINOTIFICATIONTYPE.ENUMERATE; pub const PFNFDINOTIFY = fn( fdint: FDINOTIFICATIONTYPE, pfdin: ?*FDINOTIFICATION, ) callconv(@import("std").os.windows.WINAPI) isize; pub const FDISPILLFILE = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { ach: [2]CHAR, cbFile: i32, }, .X86 => packed struct { ach: [2]CHAR, cbFile: i32, }, }; //-------------------------------------------------------------------------------- // Section: Functions (10) //-------------------------------------------------------------------------------- pub extern "Cabinet" fn FCICreate( perf: ?*ERF, pfnfcifp: ?PFNFCIFILEPLACED, pfna: ?PFNFCIALLOC, pfnf: ?PFNFCIFREE, pfnopen: ?PFNFCIOPEN, pfnread: ?PFNFCIREAD, pfnwrite: ?PFNFCIWRITE, pfnclose: ?PFNFCICLOSE, pfnseek: ?PFNFCISEEK, pfndelete: ?PFNFCIDELETE, pfnfcigtf: ?PFNFCIGETTEMPFILE, pccab: ?*CCAB, pv: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "Cabinet" fn FCIAddFile( hfci: ?*anyopaque, pszSourceFile: ?PSTR, pszFileName: ?PSTR, fExecute: BOOL, pfnfcignc: ?PFNFCIGETNEXTCABINET, pfnfcis: ?PFNFCISTATUS, pfnfcigoi: ?PFNFCIGETOPENINFO, typeCompress: u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "Cabinet" fn FCIFlushCabinet( hfci: ?*anyopaque, fGetNextCab: BOOL, pfnfcignc: ?PFNFCIGETNEXTCABINET, pfnfcis: ?PFNFCISTATUS, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "Cabinet" fn FCIFlushFolder( hfci: ?*anyopaque, pfnfcignc: ?PFNFCIGETNEXTCABINET, pfnfcis: ?PFNFCISTATUS, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "Cabinet" fn FCIDestroy( hfci: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "Cabinet" fn FDICreate( pfnalloc: ?PFNALLOC, pfnfree: ?PFNFREE, pfnopen: ?PFNOPEN, pfnread: ?PFNREAD, pfnwrite: ?PFNWRITE, pfnclose: ?PFNCLOSE, pfnseek: ?PFNSEEK, cpuType: FDICREATE_CPU_TYPE, perf: ?*ERF, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows5.0' pub extern "Cabinet" fn FDIIsCabinet( hfdi: ?*anyopaque, hf: isize, pfdici: ?*FDICABINETINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "Cabinet" fn FDICopy( hfdi: ?*anyopaque, pszCabinet: ?PSTR, pszCabPath: ?PSTR, flags: i32, pfnfdin: ?PFNFDINOTIFY, pfnfdid: ?PFNFDIDECRYPT, pvUser: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "Cabinet" fn FDIDestroy( hfdi: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "Cabinet" fn FDITruncateCabinet( hfdi: ?*anyopaque, pszCabinetName: ?PSTR, iFolderToDelete: u16, ) 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 (3) //-------------------------------------------------------------------------------- const BOOL = @import("../foundation.zig").BOOL; const CHAR = @import("../foundation.zig").CHAR; const PSTR = @import("../foundation.zig").PSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNFCIALLOC")) { _ = PFNFCIALLOC; } if (@hasDecl(@This(), "PFNFCIFREE")) { _ = PFNFCIFREE; } if (@hasDecl(@This(), "PFNFCIOPEN")) { _ = PFNFCIOPEN; } if (@hasDecl(@This(), "PFNFCIREAD")) { _ = PFNFCIREAD; } if (@hasDecl(@This(), "PFNFCIWRITE")) { _ = PFNFCIWRITE; } if (@hasDecl(@This(), "PFNFCICLOSE")) { _ = PFNFCICLOSE; } if (@hasDecl(@This(), "PFNFCISEEK")) { _ = PFNFCISEEK; } if (@hasDecl(@This(), "PFNFCIDELETE")) { _ = PFNFCIDELETE; } if (@hasDecl(@This(), "PFNFCIGETNEXTCABINET")) { _ = PFNFCIGETNEXTCABINET; } if (@hasDecl(@This(), "PFNFCIFILEPLACED")) { _ = PFNFCIFILEPLACED; } if (@hasDecl(@This(), "PFNFCIGETOPENINFO")) { _ = PFNFCIGETOPENINFO; } if (@hasDecl(@This(), "PFNFCISTATUS")) { _ = PFNFCISTATUS; } if (@hasDecl(@This(), "PFNFCIGETTEMPFILE")) { _ = PFNFCIGETTEMPFILE; } if (@hasDecl(@This(), "PFNALLOC")) { _ = PFNALLOC; } if (@hasDecl(@This(), "PFNFREE")) { _ = PFNFREE; } if (@hasDecl(@This(), "PFNOPEN")) { _ = PFNOPEN; } if (@hasDecl(@This(), "PFNREAD")) { _ = PFNREAD; } if (@hasDecl(@This(), "PFNWRITE")) { _ = PFNWRITE; } if (@hasDecl(@This(), "PFNCLOSE")) { _ = PFNCLOSE; } if (@hasDecl(@This(), "PFNSEEK")) { _ = PFNSEEK; } if (@hasDecl(@This(), "PFNFDIDECRYPT")) { _ = PFNFDIDECRYPT; } if (@hasDecl(@This(), "PFNFDINOTIFY")) { _ = PFNFDINOTIFY; } @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/cabinets.zig
const std = @import("std"); const Token = union(enum) { Identifier: []const u8, Bool: bool, String: []const u8, Integer: i64, OpenBracket: void, CloseBracket: void, Equals_Sign: void, EOF: void, }; const Tokenizer = struct { data: []const u8, col: u64 = 0, line: u64 = 1, i: u64 = 0, /// Lex next token without consuming it pub fn peekToken(self: *Tokenizer) !Token { var tmp = self.*; return tmp.nextToken(); } pub fn nextToken(self: *Tokenizer) !Token { // Skip whitespace and check for EOF { var skip_whitespace = true; var skip_comment = false; while (skip_whitespace) { if (self.i >= self.data.len) { return Token{ .EOF = undefined }; } var c = self.data[self.i]; if (c == '#') { skip_comment = true; self.step(1); } else if (c == '\n') { self.col = 0; self.line += 1; self.i += 1; skip_comment = false; } else if (c == ' ' or c == '\r' or c == '\t') { self.step(1); } else { if (skip_comment) self.step(1) else skip_whitespace = false; } } } var state: Token = switch (self.data[self.i]) { '[' => val: { self.step(1); break :val Token{ .OpenBracket = undefined }; }, ']' => val: { self.step(1); break :val Token{ .CloseBracket = undefined }; }, '=' => val: { self.step(1); break :val Token{ .Equals_Sign = undefined }; }, '"' => val: { // Parse string literal // skip first quote char self.step(1); // TODO(may): Handle \r\n if ((self.i < self.data.len - 1) and self.data[self.i] == '\n') { self.step(1); } const start = self.i; while ((self.i < self.data.len) and self.data[self.i] != '"') { if (self.data[self.i] == '\n') { self.i += 1; self.line += 1; self.col = 0; } else { self.step(1); } } else { if (self.i >= self.data.len) { return error.StringNotClosed; } } defer self.step(1); // skip the quote at the end break :val Token{ .String = self.data[start..self.i] }; }, '0'...'9' => val: { var number = self.data[self.i] - '0'; self.step(1); while ((self.i < self.data.len) and (self.data[self.i] >= '0' and self.data[self.i] <= '9')) : (self.step(1)) { number *= 10; number += self.data[self.i] - '0'; } break :val Token{ .Integer = number }; }, else => val: { // Parse boolean if (caseInsensitiveStartsWith("true", self.data[self.i..])) { self.step(4); break :val Token{ .Bool = true }; } else if (caseInsensitiveStartsWith("false", self.data[self.i..])) { self.step(5); break :val Token{ .Bool = false }; } // Parse identifier // TODO: break on [,],",WHITESPACE const start = self.i; var c = self.data[self.i]; while ((self.i < self.data.len)) : (c = self.data[self.i]) { if (isWhitespace(c)) break; if (c == '[') break; if (c == ']') break; if (c == '"') break; if (c == '=') break; self.step(1); } break :val Token{ .Identifier = self.data[start..self.i] }; }, }; return state; } /// Check if b starts with a fn caseInsensitiveStartsWith(prefix: []const u8, str: []const u8) bool { if (str.len - prefix.len >= 0) { return caseInsensitiveCompare(prefix, str[0..prefix.len]); } else { return false; } } fn caseInsensitiveCompare(a: []const u8, b: []const u8) bool { if (a.len != b.len) return false; for (a) |c, i| { var c1 = if (c >= 'A' and c <= 'Z') c + 32 else c; var c2 = if (c >= 'A' and c <= 'Z') b[i] + 32 else b[i]; if (c1 != c2) return false; } return true; } fn isWhitespace(c: u8) bool { return c == ' ' or c == '\r' or c == '\n' or c == '\t'; } /// Returns true if next is a line ending e.g. \n or \r\n /// Returns false if not next is not a line ending or no data left fn isLineEnding(self: *Tokenizer) bool { if (self.i >= self.data.len) return false; return (self.data[self.i] == '\n'); } /// Increases both col and index value fn step(self: *Tokenizer, count: u32) void { self.i += count; self.col += count; } }; pub const Value = union(enum) { Bool: bool, String: []const u8, Integer: i64, Table: Table, }; pub const Table = struct { const Item_Type = std.StringHashMap(Value); name: []const u8, items: Item_Type, pub fn init(allocator: std.mem.Allocator, name: []const u8) Table { return .{ .name = name, .items = Item_Type.init(allocator), }; } pub fn deinit(self: *Table) void { var iterator = self.items.valueIterator(); while (iterator.next()) |item| { if (item.* == Value.Table) { item.Table.deinit(); } } self.items.deinit(); } }; pub const Parser = struct { allocator: std.mem.Allocator, tokenizer: Tokenizer, pub fn init(allocator: std.mem.Allocator, data: []const u8) Parser { return .{ .allocator = allocator, .tokenizer = Tokenizer{ .data = data }, }; } pub fn parse(self: *Parser) !Table { var result = Table.init(self.allocator, ""); errdefer result.deinit(); var state: enum { Key_Or_Header, Equals_Sign, Value, } = .Key_Or_Header; var name: []const u8 = undefined; var value: Value = undefined; var current_table = &result; while (true) { var token = try self.tokenizer.nextToken(); if (token == .EOF) { if (state == .Equals_Sign) { return error.Expected_Equals_Sign; } else if (state == .Value) { return error.Expected_Value; } else { break; } } switch (state) { .Key_Or_Header => { if (token == .Identifier) { name = token.Identifier; state = .Equals_Sign; } else if (token == .OpenBracket) { token = try self.tokenizer.nextToken(); if (token != .Identifier) { return error.Expected_Identifier; } name = token.Identifier; token = try self.tokenizer.nextToken(); if (token != .CloseBracket) { return error.Expected_Closing_Bracket; } value = Value{ .Table = Table.init(self.allocator, name) }; try result.items.put(name, value); current_table = &(result.items.getPtr(name) orelse unreachable).Table; } else { std.debug.print("\n\n{}\n\n", .{token}); return error.Expected_Key_Or_Value; } }, .Equals_Sign => { if (token != .Equals_Sign) { return error.Expected_Equals_Sign; } else { state = .Value; } }, .Value => { if (token == .String) { value = Value{ .String = token.String }; try current_table.items.put(name, value); state = .Key_Or_Header; } else if (token == .Bool) { value = Value{ .Bool = token.Bool }; try current_table.items.put(name, value); state = .Key_Or_Header; } else if (token == .Integer) { value = Value{ .Integer = token.Integer }; try current_table.items.put(name, value); state = .Key_Or_Header; } else { return error.Expected_Value; } }, } } return result; } }; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; test "Simple Tokenizer Test" { var test_string = \\tstring = "hello" # Here is a Comment \\tbool = true \\b = false \\[htest] \\s="#" ; var tokenizer = Tokenizer{ .data = test_string }; // 1. Line var token = try tokenizer.nextToken(); try expectEqual(Token.Identifier, token); try expectEqualStrings("tstring", token.Identifier); token = try tokenizer.nextToken(); try expectEqual(Token.Equals_Sign, token); token = try tokenizer.nextToken(); try expectEqual(Token.String, token); try expectEqualStrings("hello", token.String); try expectEqual(@as(u64, 1), tokenizer.line); try expectEqual(@as(u64, 17), tokenizer.col); // Tokenizer should be on the \n // 2. Line token = try tokenizer.nextToken(); try expectEqual(Token.Identifier, token); try expectEqualStrings("tbool", token.Identifier); token = try tokenizer.nextToken(); try expectEqual(Token.Equals_Sign, token); token = try tokenizer.nextToken(); try expectEqual(Token.Bool, token); try expectEqual(true, token.Bool); try expectEqual(@as(u64, 2), tokenizer.line); try expectEqual(@as(u64, 14), tokenizer.col); // Tokenizer should be on the \n // 3. Line token = try tokenizer.nextToken(); try expectEqual(Token.Identifier, token); try expectEqualStrings("b", token.Identifier); token = try tokenizer.nextToken(); try expectEqual(Token.Equals_Sign, token); token = try tokenizer.nextToken(); try expectEqual(Token.Bool, token); try expectEqual(false, token.Bool); try expectEqual(@as(u64, 3), tokenizer.line); try expectEqual(@as(u64, 15), tokenizer.col); // Tokenizer should be on the \n // 4. Line token = try tokenizer.nextToken(); try expectEqual(Token.OpenBracket, token); token = try tokenizer.nextToken(); try expectEqual(Token.Identifier, token); try expectEqualStrings("htest", token.Identifier); token = try tokenizer.nextToken(); try expectEqual(Token.CloseBracket, token); try expectEqual(@as(u64, 4), tokenizer.line); try expectEqual(@as(u64, 7), tokenizer.col); // Tokenizer should be on the \n // 5. Line token = try tokenizer.nextToken(); try expectEqual(Token.Identifier, token); try expectEqualStrings("s", token.Identifier); token = try tokenizer.nextToken(); try expectEqual(Token.Equals_Sign, token); token = try tokenizer.nextToken(); try expectEqual(Token.String, token); try expectEqualStrings("#", token.String); token = try tokenizer.nextToken(); try expectEqual(Token.EOF, token); } fn range(comptime n: comptime_int) [n]void { return undefined; } test "Peek Token Test" { const test_string = \\some = "value" ; var tokenizer = Tokenizer{ .data = test_string }; for (range(5)) |_| { var token = try tokenizer.peekToken(); try expectEqual(Token.Identifier, token); } try expectEqual(@as(u64, 0), tokenizer.i); try expectEqual(@as(u64, 1), tokenizer.line); try expectEqual(@as(u64, 0), tokenizer.col); } test "Multiline String Tokenizer Test" { const test_string = \\tstring = "hello \\world" \\tstring2 = " \\hello world" \\tstring3 = " \\ \\" ; var tokenizer = Tokenizer{ .data = test_string }; var token = try tokenizer.nextToken(); token = try tokenizer.nextToken(); token = try tokenizer.nextToken(); try expectEqual(Token.String, token); try expectEqualStrings("hello\nworld", token.String); token = try tokenizer.nextToken(); token = try tokenizer.nextToken(); token = try tokenizer.nextToken(); try expectEqual(Token.String, token); try expectEqualStrings("hello world", token.String); token = try tokenizer.nextToken(); token = try tokenizer.nextToken(); token = try tokenizer.nextToken(); try expectEqual(Token.String, token); try expectEqualStrings("\n", token.String); } test "Simple Parser Test" { const test_string = \\tstring = "hello" \\tbool = true \\[header] \\some_string = "Thats a string" #dwadw ; var parser = Parser.init(std.testing.allocator, test_string); var result = try parser.parse(); defer result.deinit(); try expectEqual(@as(u32, 3), result.items.count()); try expectEqualStrings("hello", result.items.get("tstring").?.String); try expectEqual(true, result.items.get("tbool").?.Bool); var header_table = result.items.get("header").?.Table; try expectEqual(@as(usize, 1), header_table.items.count()); try expectEqualStrings("Thats a string", header_table.items.get("some_string").?.String); } test "Simple Parser Error Test" { const test_string = \\ [jwad] \\ waddaw = 12 \\ tstring = \\ # some comment ; var parser = Parser.init(std.testing.allocator, test_string); var result = parser.parse(); try std.testing.expectError(error.Expected_Value, result); } test "Parser Application Test" { const test_string = \\ # This is the general configuration. \\ path = "example_program" # Relative to this file \\ continue_on_fail = true \\ \\ [Green_Test] \\ input = "-some -program -arguments" \\ output = "-some -program -arguments" \\ output_err = "error_output" \\ exit_code = 69 \\ \\ [Failing_Test] \\ input = "ARG2" \\ output = "OUT2" \\ output_err = "OUT_ERR2" \\ exit_code = 222 ; var parser = Parser.init(std.testing.allocator, test_string); var result = try parser.parse(); defer result.deinit(); try expectEqual(@as(usize, 4), result.items.count()); // TODO(may): test the rest of the stuff... }
src/toml.zig
const std = @import("std"); const testing = std.testing; const meta = std.meta; const Allocator = std.mem.Allocator; pub fn List(comptime T: type) type { return struct { const Node = struct { prev: ?*this, next: ?*this, data: *T, const this = @This(); fn default(allocator: *Allocator) !*this { var data = try allocator.create(T); var node = try allocator.create(this); node.prev = null; node.next = null; node.data = data; std.log.warn("node data: {*}", .{node}); return node; } fn find(self: *this, data: *const T) ?*this { std.log.info("called once", .{}); if (self.data.* == data.*) return self; if (self.next == null) return null; return self.next.?.find(data); } // fn deinit(self: *this) void { // allocator.destroy(self.data); // } }; head: *Node, tail: *Node, len: u32, allocator: *Allocator, const Self = @This(); fn init(allocator: *Allocator) !Self { return Self{ .head = try Node.default(allocator), .tail = try Node.default(allocator), .allocator = allocator, .len = 0, }; } fn deinit(self: *Self) void { // self.head.deinit(); self.allocator.destroy(self.head); // self.tail.deinit(); self.allocator.destroy(self.tail); } fn push_front(self: *Self, data: T) !void { if (self.len == 0) { self.head.data.* = data; self.tail.prev = self.head; self.head.next = self.tail; } else { var node = try Node.default(self.allocator); node.data.* = data; self.head.prev = node; node.next = self.head; self.head = node; } self.len += 1; } fn find(self: *Self, data: T) ?*Node { if (self.len == 0) return null; return self.head.find(&data); } fn insert_after(self: *Self, data: T, key: *Node) !void { var node = try Node.default(self.allocator); node.data.* = data; node.next = key.next; key.next = node; node.prev = key; self.len += 1; } }; } test "List Constructor and destructor test" { var anera = std.heap.ArenaAllocator.init(std.heap.page_allocator); const Uint32List = List(u32); var list = try Uint32List.init(&anera.allocator); defer list.deinit(); } test "push_front test" { var anera = std.heap.ArenaAllocator.init(std.heap.page_allocator); const Uint32List = List(u32); var list = try Uint32List.init(&anera.allocator); defer list.deinit(); try list.push_front(1); try list.push_front(1); var a: u32 = 1; try std.testing.expect(list.find(a) != null); }
src/main.zig
const std = @import("std"); const json = std.json; const zomb = @import("zomb"); pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var input_file_contents = std.ArrayList(u8).init(gpa.allocator()); defer input_file_contents.deinit(); { const args = try std.process.argsAlloc(gpa.allocator()); defer std.process.argsFree(gpa.allocator(), args); const path: []const u8 = if (args.len >= 2) args[1] else "example/test.zomb"; const file = try std.fs.cwd().openFile(path, .{ .read = true }); defer file.close(); std.log.info("Reading from {s}", .{path}); const max_file_size = if (args.len >= 3) try std.fmt.parseUnsigned(usize, args[2], 10) else 100_000_000; try file.reader().readAllArrayList(&input_file_contents, max_file_size); } var zomb_parser = zomb.Parser.init(input_file_contents.items, std.heap.page_allocator); defer zomb_parser.deinit(); const z = try zomb_parser.parse(std.heap.page_allocator); defer z.deinit(); var output_file = try std.fs.cwd().createFile("example/zomb.json", .{}); defer output_file.close(); var jsonWriter = json.writeStream(output_file.writer(), zomb.max_nested_depth); jsonWriter.whitespace = json.StringifyOptions.Whitespace{}; try zombValueToJson(zomb.ZValue{ .Object = z.map }, &jsonWriter); } fn zombValueToJson(value_: zomb.ZValue, jw_: anytype) anyerror!void { switch (value_) { .Object => |hash_map| { try jw_.beginObject(); var iter = hash_map.iterator(); while (iter.next()) |entry| { const key = entry.key_ptr.*; try jw_.objectField(key); const val = entry.value_ptr.*; try zombValueToJson(val, jw_); } try jw_.endObject(); }, .Array => |array_list| { try jw_.beginArray(); for (array_list.items) |item| { try jw_.arrayElem(); try zombValueToJson(item, jw_); } try jw_.endArray(); }, .String => |slice| { try jw_.emitString(slice.items); }, } }
example/zomb2json.zig
const std = @import("std"); const tvg = @import("tinyvg.zig"); pub const Header = struct { version: u8, scale: tvg.Scale, color_encoding: tvg.ColorEncoding, coordinate_range: tvg.Range, width: u32, height: u32, }; const Point = tvg.Point; const Rectangle = tvg.Rectangle; const Line = tvg.Line; const Path = tvg.Path; const StyleType = tvg.StyleType; const Style = tvg.Style; const Gradient = tvg.Gradient; pub const DrawCommand = union(enum) { fill_polygon: FillPolygon, fill_rectangles: FillRectangles, fill_path: FillPath, draw_lines: DrawLines, draw_line_loop: DrawLineSegments, draw_line_strip: DrawLineSegments, draw_line_path: DrawPath, outline_fill_polygon: OutlineFillPolygon, outline_fill_rectangles: OutlineFillRectangles, outline_fill_path: OutlineFillPath, pub const FillPolygon = struct { style: Style, vertices: []Point, }; pub const FillRectangles = struct { style: Style, rectangles: []Rectangle, }; pub const FillPath = struct { style: Style, path: Path, }; pub const OutlineFillPolygon = struct { fill_style: Style, line_style: Style, line_width: f32, vertices: []Point, }; pub const OutlineFillRectangles = struct { fill_style: Style, line_style: Style, line_width: f32, rectangles: []Rectangle, }; pub const OutlineFillPath = struct { fill_style: Style, line_style: Style, line_width: f32, path: Path, }; pub const DrawLines = struct { style: Style, line_width: f32, lines: []Line, }; pub const DrawLineSegments = struct { style: Style, line_width: f32, vertices: []Point, }; pub const DrawPath = struct { style: Style, line_width: f32, path: Path, }; }; pub const ParseError = error{ EndOfStream, InvalidData, OutOfMemory }; pub const ParseHeaderError = ParseError || error{ UnsupportedColorFormat, UnsupportedVersion }; pub fn Parser(comptime Reader: type) type { return struct { const Self = @This(); reader: Reader, allocator: std.mem.Allocator, temp_buffer: std.ArrayList(u8), end_of_document: bool = false, header: Header, color_table: []tvg.Color, pub fn init(allocator: std.mem.Allocator, reader: Reader) (Reader.Error || ParseHeaderError)!Self { var actual_magic_number: [2]u8 = undefined; reader.readNoEof(&actual_magic_number) catch return error.InvalidData; if (!std.mem.eql(u8, &actual_magic_number, &tvg.magic_number)) return error.InvalidData; const version = reader.readByte() catch return error.InvalidData; var self = Self{ .allocator = allocator, .reader = reader, .temp_buffer = std.ArrayList(u8).init(allocator), .header = undefined, .color_table = undefined, }; switch (version) { 1 => { const ScaleAndFlags = packed struct { scale: u4, color_encoding: u2, coordinate_range: u2, }; comptime { if (@sizeOf(ScaleAndFlags) != 1) @compileError("Invalid range!"); } const scale_and_flags = @bitCast(ScaleAndFlags, try reader.readByte()); const scale = @intToEnum(tvg.Scale, scale_and_flags.scale); const color_encoding = @intToEnum(tvg.ColorEncoding, scale_and_flags.color_encoding); const range = @intToEnum(tvg.Range, scale_and_flags.coordinate_range); const width: u32 = switch (range) { .reduced => mapZeroToMax(try reader.readIntLittle(u8)), .default => mapZeroToMax(try reader.readIntLittle(u16)), .enhanced => std.math.cast(u32, mapZeroToMax(try reader.readIntLittle(u32))) catch return error.InvalidData, }; const height: u32 = switch (range) { .reduced => mapZeroToMax(try reader.readIntLittle(u8)), .default => mapZeroToMax(try reader.readIntLittle(u16)), .enhanced => std.math.cast(u32, mapZeroToMax(try reader.readIntLittle(u32))) catch return error.InvalidData, }; const color_count = try self.readUInt(); self.color_table = try allocator.alloc(tvg.Color, color_count); errdefer allocator.free(self.color_table); for (self.color_table) |*c| { c.* = switch (color_encoding) { .u8888 => tvg.Color{ .r = @intToFloat(f32, try reader.readIntLittle(u8)) / 255.0, .g = @intToFloat(f32, try reader.readIntLittle(u8)) / 255.0, .b = @intToFloat(f32, try reader.readIntLittle(u8)) / 255.0, .a = @intToFloat(f32, try reader.readIntLittle(u8)) / 255.0, }, .u565 => blk: { const rgb = try reader.readIntLittle(u16); break :blk tvg.Color{ .r = @intToFloat(f32, (rgb & 0x1F) >> 0) / 31.0, .g = @intToFloat(f32, (rgb & 0x3F) >> 5) / 63.0, .b = @intToFloat(f32, (rgb & 0x1F) >> 11) / 31.0, .a = 1.0, }; }, .f32 => tvg.Color{ // TODO: Verify if this is platform independently correct: .r = @bitCast(f32, try reader.readIntLittle(u32)), .g = @bitCast(f32, try reader.readIntLittle(u32)), .b = @bitCast(f32, try reader.readIntLittle(u32)), .a = @bitCast(f32, try reader.readIntLittle(u32)), }, .custom => return error.UnsupportedColorFormat, }; } self.header = Header{ .version = version, .scale = scale, .width = width, .height = height, .color_encoding = color_encoding, .coordinate_range = range, }; }, else => return error.UnsupportedVersion, } return self; } pub fn deinit(self: *Self) void { self.temp_buffer.deinit(); self.allocator.free(self.color_table); self.* = undefined; } fn setTempStorage(self: *Self, comptime T: type, length: usize) ![]T { try self.temp_buffer.resize(@sizeOf(T) * length); var items = @alignCast(@alignOf(T), std.mem.bytesAsSlice(T, self.temp_buffer.items)); std.debug.assert(items.len == length); return items; } fn setDualTempStorage( self: *Self, comptime T1: type, length1: usize, comptime T2: type, length2: usize, ) !struct { first: []T1, second: []T2 } { const offset_second_buffer = std.mem.alignForward(@sizeOf(T1) * length1, @alignOf(T2)); try self.temp_buffer.resize(offset_second_buffer + @sizeOf(T2) * length2); var result = .{ .first = @alignCast(@alignOf(T1), std.mem.bytesAsSlice(T1, self.temp_buffer.items[0..offset_second_buffer])), .second = @alignCast(@alignOf(T2), std.mem.bytesAsSlice(T2, self.temp_buffer.items[offset_second_buffer..])), }; std.debug.assert(result.first.len == length1); std.debug.assert(result.second.len == length2); return result; } fn ValAndSize(comptime T: type) type { return struct { data: T, count: usize }; } fn checkInit(comptime T: type, comptime fields: []const []const u8) void { inline for (fields) |fld| { if (!@hasField(T, fld)) @compileError("Invalid field"); } if (fields.len != std.meta.fields(T).len) { @compileError("Uninitialized type"); } } fn readFillHeader(self: *Self, primary_style_type: tvg.StyleType, comptime T: type, comptime uninit_field: []const u8) (Reader.Error || ParseError)!ValAndSize(T) { checkInit(T, &[_][]const u8{ "style", uninit_field }); var value: T = undefined; const count = @as(usize, try self.readUInt()) + 1; value.style = try self.readStyle(primary_style_type); return ValAndSize(T){ .data = value, .count = count }; } fn readLineHeader(self: *Self, primary_style_type: tvg.StyleType, comptime T: type, comptime uninit_field: []const u8) (Reader.Error || ParseError)!ValAndSize(T) { checkInit(T, &[_][]const u8{ "style", "line_width", uninit_field }); var value: T = undefined; const count = @as(usize, try self.readUInt()) + 1; value.style = try self.readStyle(primary_style_type); value.line_width = try self.readUnit(); return ValAndSize(T){ .data = value, .count = count }; } fn readOutlineFillHeader(self: *Self, primary_style_type: tvg.StyleType, comptime T: type, comptime uninit_field: []const u8) (Reader.Error || ParseError)!ValAndSize(T) { checkInit(T, &[_][]const u8{ "fill_style", "line_style", "line_width", uninit_field }); var value: T = undefined; const count_and_grad = @bitCast(CountAndStyleTag, try self.readByte()); const count = count_and_grad.getCount(); value.fill_style = try self.readStyle(primary_style_type); value.line_style = try self.readStyle(try count_and_grad.getStyleType()); value.line_width = try self.readUnit(); return ValAndSize(T){ .data = value, .count = count }; } pub fn next(self: *Self) (Reader.Error || ParseError)!?DrawCommand { if (self.end_of_document) return null; const command_byte = try self.reader.readByte(); const primary_style_type = std.meta.intToEnum(tvg.StyleType, @truncate(u2, command_byte >> 6)) catch return error.InvalidData; const command = @intToEnum(tvg.Command, @truncate(u6, command_byte)); return switch (command) { .end_of_document => { self.end_of_document = true; return null; }, .fill_polygon => blk: { var data = try self.readFillHeader(primary_style_type, DrawCommand.FillPolygon, "vertices"); data.data.vertices = try self.setTempStorage(Point, data.count); for (data.data.vertices) |*pt| { pt.x = try self.readUnit(); pt.y = try self.readUnit(); } break :blk DrawCommand{ .fill_polygon = data.data }; }, .fill_rectangles => blk: { var data = try self.readFillHeader(primary_style_type, DrawCommand.FillRectangles, "rectangles"); data.data.rectangles = try self.setTempStorage(Rectangle, data.count); for (data.data.rectangles) |*rect| { rect.x = try self.readUnit(); rect.y = try self.readUnit(); rect.width = try self.readUnit(); rect.height = try self.readUnit(); if (rect.width <= 0 or rect.height <= 0) return error.InvalidData; } break :blk DrawCommand{ .fill_rectangles = data.data }; }, .fill_path => blk: { var data = try self.readFillHeader(primary_style_type, DrawCommand.FillPath, "path"); data.data.path = try self.readPath(data.count); break :blk DrawCommand{ .fill_path = data.data }; }, .draw_lines => blk: { var data = try self.readLineHeader(primary_style_type, DrawCommand.DrawLines, "lines"); data.data.lines = try self.setTempStorage(Line, data.count); for (data.data.lines) |*line| { line.start.x = try self.readUnit(); line.start.y = try self.readUnit(); line.end.x = try self.readUnit(); line.end.y = try self.readUnit(); } break :blk DrawCommand{ .draw_lines = data.data }; }, .draw_line_loop => blk: { var data = try self.readLineHeader(primary_style_type, DrawCommand.DrawLineSegments, "vertices"); data.data.vertices = try self.setTempStorage(Point, data.count); for (data.data.vertices) |*point| { point.x = try self.readUnit(); point.y = try self.readUnit(); } break :blk DrawCommand{ .draw_line_loop = data.data }; }, .draw_line_strip => blk: { var data = try self.readLineHeader(primary_style_type, DrawCommand.DrawLineSegments, "vertices"); data.data.vertices = try self.setTempStorage(Point, data.count); for (data.data.vertices) |*point| { point.x = try self.readUnit(); point.y = try self.readUnit(); } break :blk DrawCommand{ .draw_line_strip = data.data }; }, .draw_line_path => blk: { var data = try self.readLineHeader(primary_style_type, DrawCommand.DrawPath, "path"); data.data.path = try self.readPath(data.count); break :blk DrawCommand{ .draw_line_path = data.data }; }, .outline_fill_polygon => blk: { var data = try self.readOutlineFillHeader(primary_style_type, DrawCommand.OutlineFillPolygon, "vertices"); data.data.vertices = try self.setTempStorage(Point, data.count); for (data.data.vertices) |*pt| { pt.x = try self.readUnit(); pt.y = try self.readUnit(); } break :blk DrawCommand{ .outline_fill_polygon = data.data }; }, .outline_fill_rectangles => blk: { var data = try self.readOutlineFillHeader(primary_style_type, DrawCommand.OutlineFillRectangles, "rectangles"); data.data.rectangles = try self.setTempStorage(Rectangle, data.count); for (data.data.rectangles) |*rect| { rect.x = try self.readUnit(); rect.y = try self.readUnit(); rect.width = try self.readUnit(); rect.height = try self.readUnit(); if (rect.width <= 0 or rect.height <= 0) return error.InvalidData; } break :blk DrawCommand{ .outline_fill_rectangles = data.data }; }, .outline_fill_path => blk: { var data = try self.readOutlineFillHeader(primary_style_type, DrawCommand.OutlineFillPath, "path"); data.data.path = try self.readPath(data.count); break :blk DrawCommand{ .outline_fill_path = data.data }; }, _ => { return error.InvalidData; }, }; } fn readPath(self: *Self, path_length: usize) !Path { var segment_lengths: [1024]usize = undefined; std.debug.assert(path_length <= segment_lengths.len); var total_node_count: usize = 0; { var i: usize = 0; while (i < path_length) : (i += 1) { segment_lengths[i] = @as(usize, try self.readUInt()) + 1; total_node_count += segment_lengths[i]; } } const buffers = try self.setDualTempStorage( Path.Segment, path_length, Path.Node, total_node_count, ); var segment_start: usize = 0; for (buffers.first) |*segment, i| { const segment_len = segment_lengths[i]; segment.start.x = try self.readUnit(); segment.start.y = try self.readUnit(); var commands = buffers.second[segment_start..][0..segment_len]; for (commands) |*node| { node.* = try self.readNode(); } segment.commands = commands; segment_start += segment_len; } std.debug.assert(buffers.first.len == path_length); std.debug.assert(segment_start == total_node_count); return Path{ .segments = buffers.first, }; } fn readNode(self: Self) !Path.Node { const Tag = packed struct { type: Path.Type, padding0: u1 = 0, has_line_width: bool, padding1: u3 = 0, }; const tag = @bitCast(Tag, try self.readByte()); var line_width: ?f32 = if (tag.has_line_width) try self.readUnit() else null; const PathNode = Path.Node; return switch (tag.type) { .line => PathNode{ .line = PathNode.NodeData(Point).init(line_width, .{ .x = try self.readUnit(), .y = try self.readUnit(), }) }, .horiz => PathNode{ .horiz = PathNode.NodeData(f32).init(line_width, try self.readUnit()) }, .vert => PathNode{ .vert = PathNode.NodeData(f32).init(line_width, try self.readUnit()) }, .bezier => PathNode{ .bezier = PathNode.NodeData(PathNode.Bezier).init(line_width, PathNode.Bezier{ .c0 = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, .c1 = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, .p1 = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, }) }, .arc_circle => blk: { var flags = try self.readByte(); break :blk PathNode{ .arc_circle = PathNode.NodeData(PathNode.ArcCircle).init(line_width, PathNode.ArcCircle{ .radius = try self.readUnit(), .large_arc = (flags & 1) != 0, .sweep = (flags & 2) != 0, .target = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, }) }; }, .arc_ellipse => blk: { var flags = try self.readByte(); break :blk PathNode{ .arc_ellipse = PathNode.NodeData(PathNode.ArcEllipse).init(line_width, PathNode.ArcEllipse{ .radius_x = try self.readUnit(), .radius_y = try self.readUnit(), .rotation = try self.readUnit(), .large_arc = (flags & 1) != 0, .sweep = (flags & 2) != 0, .target = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, }) }; }, .quadratic_bezier => PathNode{ .quadratic_bezier = PathNode.NodeData(PathNode.QuadraticBezier).init(line_width, PathNode.QuadraticBezier{ .c = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, .p1 = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }, }) }, .close => PathNode{ .close = PathNode.NodeData(void).init(line_width, {}) }, }; } fn readStyle(self: Self, kind: StyleType) !Style { return switch (kind) { .flat => Style{ .flat = try self.readUInt() }, .linear => Style{ .linear = try self.readGradient() }, .radial => Style{ .radial = try self.readGradient() }, }; } fn readGradient(self: Self) !Gradient { var grad: Gradient = undefined; grad.point_0 = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }; grad.point_1 = Point{ .x = try self.readUnit(), .y = try self.readUnit(), }; grad.color_0 = try self.readUInt(); grad.color_1 = try self.readUInt(); if (grad.color_0 >= self.color_table.len) return error.InvalidData; if (grad.color_1 >= self.color_table.len) return error.InvalidData; return grad; } fn readUInt(self: Self) error{InvalidData}!u32 { var byte_count: u8 = 0; var result: u32 = 0; while (true) { const byte = self.reader.readByte() catch return error.InvalidData; // check for too long *and* out of range in a single check if (byte_count == 4 and (byte & 0xF0) != 0) return error.InvalidData; const val = @as(u32, (byte & 0x7F)) << @intCast(u5, (7 * byte_count)); result |= val; if ((byte & 0x80) == 0) break; byte_count += 1; std.debug.assert(byte_count <= 5); } return result; } fn readUnit(self: Self) !f32 { switch (self.header.coordinate_range) { .reduced => return @intToEnum(tvg.Unit, try self.reader.readIntLittle(i8)).toFloat(self.header.scale), .default => return @intToEnum(tvg.Unit, try self.reader.readIntLittle(i16)).toFloat(self.header.scale), .enhanced => return @intToEnum(tvg.Unit, try self.reader.readIntLittle(i32)).toFloat(self.header.scale), } } fn readByte(self: Self) !u8 { return try self.reader.readByte(); } fn readU16(self: Self) !u16 { return try self.reader.readIntLittle(u16); } }; } const CountAndStyleTag = packed struct { const Self = @This(); raw_count: u6, style_kind: u2, pub fn getCount(self: Self) usize { return @as(usize, self.raw_count) + 1; } pub fn getStyleType(self: Self) !StyleType { return convertStyleType(self.style_kind); } }; fn convertStyleType(value: u2) !StyleType { return switch (value) { @enumToInt(StyleType.flat) => StyleType.flat, @enumToInt(StyleType.linear) => StyleType.linear, @enumToInt(StyleType.radial) => StyleType.radial, else => error.InvalidData, }; } fn MapZeroToMax(comptime T: type) type { const info = @typeInfo(T).Int; return std.meta.Int(.unsigned, info.bits + 1); } fn mapZeroToMax(value: anytype) MapZeroToMax(@TypeOf(value)) { return if (value == 0) std.math.maxInt(@TypeOf(value)) + 1 else value; } test "mapZeroToMax" { try std.testing.expectEqual(@as(u9, 256), mapZeroToMax(@as(u8, 0))); try std.testing.expectEqual(@as(u17, 65536), mapZeroToMax(@as(u16, 0))); } // test "readUInt" { // const T = struct { // fn run(seq: []const u8) !u32 { // var stream = std.io.fixedBufferStream(seq); // return try readUInt(stream.reader()); // } // }; // std.testing.expectEqual(@as(u32, 0x00), try T.run(&[_]u8{0x00})); // std.testing.expectEqual(@as(u32, 0x40), try T.run(&[_]u8{0x40})); // std.testing.expectEqual(@as(u32, 0x80), try T.run(&[_]u8{ 0x80, 0x01 })); // std.testing.expectEqual(@as(u32, 0x100000), try T.run(&[_]u8{ 0x80, 0x80, 0x40 })); // std.testing.expectEqual(@as(u32, 0x8000_0000), try T.run(&[_]u8{ 0x80, 0x80, 0x80, 0x80, 0x08 })); // std.testing.expectError(error.InvalidData, T.run(&[_]u8{ 0x80, 0x80, 0x80, 0x80, 0x10 })); // out of range // std.testing.expectError(error.InvalidData, T.run(&[_]u8{ 0x80, 0x80, 0x80, 0x80, 0x80, 0x10 })); // too long // } test "coverage test" { var source_buf: [2048]u8 = undefined; var stream = std.io.fixedBufferStream(&source_buf); @import("ground-truth").writeEverything(stream.writer(), .default) catch unreachable; try stream.seekTo(0); var parser = try Parser(@TypeOf(stream).Reader).init(std.testing.allocator, stream.reader()); defer parser.deinit(); while (try parser.next()) |node| { _ = node; } }
src/lib/parsing.zig
const std = @import("std"); const debug = std.debug; const math = std.math; const mem = std.mem; pub const Patch = struct { offset: usize, replacement: []const u8, }; pub fn patch(memory: []u8, patchs: []const Patch) void { for (patchs) |p| mem.copy(u8, memory[p.offset..], p.replacement); } pub const PatchIterator = struct { old: []const u8, new: []const u8, i: usize = 0, pub fn next(it: *PatchIterator) ?Patch { const end_it = math.min(it.old.len, it.new.len); const chunk_size = @sizeOf(u256); while (it.i + chunk_size <= end_it) : (it.i += chunk_size) { const new_chunk = @ptrCast(*align(1) const u256, it.new[it.i..][0..chunk_size]).*; const old_chunk = @ptrCast(*align(1) const u256, it.old[it.i..][0..chunk_size]).*; if (new_chunk != old_chunk) break; } while (it.i < end_it) : (it.i += 1) { if (it.new[it.i] != it.old[it.i]) break; } const start = it.i; while (it.i < end_it) : (it.i += 1) { if (it.new[it.i] == it.old[it.i]) break; } const end = if (it.i == it.old.len) it.new.len else it.i; if (start == end) return null; return Patch{ .offset = start, .replacement = it.new[start..end], }; } }; pub const Version = enum { red, blue, yellow, gold, silver, crystal, ruby, sapphire, emerald, fire_red, leaf_green, diamond, pearl, platinum, heart_gold, soul_silver, black, white, black2, white2, x, y, omega_ruby, alpha_sapphire, sun, moon, ultra_sun, ultra_moon, pub fn humanString(version: Version) []const u8 { return switch (version) { .red => "Red", .blue => "Blue", .yellow => "Yellow", .gold => "Gold", .silver => "Silver", .crystal => "Crystal", .ruby => "Ruby", .sapphire => "Sapphire", .emerald => "Emerald", .fire_red => "Fire Red", .leaf_green => "Leaf Green", .diamond => "Diamond", .pearl => "Pearl", .platinum => "Platinum", .heart_gold => "Heart Gold", .soul_silver => "Soul Silver", .black => "Black", .white => "White", .black2 => "Black 2", .white2 => "White 2", .x => "X", .y => "Y", .omega_ruby => "Omega Ruby", .alpha_sapphire => "Alpha Sapphire", .sun => "Sun", .moon => "Moon", .ultra_sun => "Ultra Sun", .ultra_moon => "Ultra Moon", }; } }; pub const PartyType = enum(u8) { none = 0b00, item = 0b10, moves = 0b01, both = 0b11, pub fn haveItem(t: PartyType) bool { return t == .item or t == .both; } pub fn haveMoves(t: PartyType) bool { return t == .moves or t == .both; } }; pub const Stats = extern struct { hp: u8, attack: u8, defense: u8, speed: u8, sp_attack: u8, sp_defense: u8, comptime { std.debug.assert(@sizeOf(Stats) == 6); } }; pub const MoveCategory = enum(u8) { physical = 0x00, status = 0x01, special = 0x02, }; pub const GrowthRate = enum(u8) { medium_fast = 0x00, erratic = 0x01, fluctuating = 0x02, medium_slow = 0x03, fast = 0x04, slow = 0x05, }; pub const EggGroup = enum(u8) { invalid = 0x00, // TODO: Figure out if there is a 0x00 egg group monster = 0x01, water1 = 0x02, bug = 0x03, flying = 0x04, field = 0x05, fairy = 0x06, grass = 0x07, human_like = 0x08, water3 = 0x09, mineral = 0x0A, amorphous = 0x0B, water2 = 0x0C, ditto = 0x0D, dragon = 0x0E, undiscovered = 0x0F, _, }; pub const ColorKind = enum(u7) { red = 0x00, blue = 0x01, yellow = 0x02, green = 0x03, black = 0x04, brown = 0x05, purple = 0x06, gray = 0x07, white = 0x08, pink = 0x09, green2 = 0x0A, }; pub const Color = packed struct { color: ColorKind, flip: bool, }; // Common between gen3-4 pub const EvoMethod = enum(u8) { unused = 0x00, friend_ship = 0x01, friend_ship_during_day = 0x02, friend_ship_during_night = 0x03, level_up = 0x04, trade = 0x05, trade_holding_item = 0x06, use_item = 0x07, attack_gth_defense = 0x08, attack_eql_defense = 0x09, attack_lth_defense = 0x0A, personality_value1 = 0x0B, personality_value2 = 0x0C, level_up_may_spawn_pokemon = 0x0D, level_up_spawn_if_cond = 0x0E, beauty = 0x0F, use_item_on_male = 0x10, use_item_on_female = 0x11, level_up_holding_item_during_daytime = 0x12, level_up_holding_item_during_the_night = 0x13, level_up_knowning_move = 0x14, level_up_with_other_pokemon_in_party = 0x15, level_up_male = 0x16, level_up_female = 0x17, level_up_in_special_magnetic_field = 0x18, level_up_near_moss_rock = 0x19, level_up_near_ice_rock = 0x1A, _, }; // TODO: Figure out if the this have the same layout in all games that have it. // They probably have, so let's assume that for now and if a bug // is ever encountered related to this, we figure it out. pub const EvYield = packed struct { hp: u2, attack: u2, defense: u2, speed: u2, sp_attack: u2, sp_defense: u2, comptime { std.debug.assert(@sizeOf(EvYield) == 2); } }; pub const TypeEffectiveness = packed struct { attacker: u8, defender: u8, multiplier: u8, };
src/core/common.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Node = @import("./node.zig").Node; pub fn PriorityQueue(comptime T: type, comptime cmp: fn (T, T) std.math.Order) type { return struct { capacity: usize, tail: usize, items: []T, allocator: Allocator, const Self = @This(); pub fn init(allocator: Allocator, capacity: usize) !*Self { var q: *Self = try allocator.create(Self); errdefer allocator.destroy(q); q.* = .{ .capacity = capacity, .tail = 0, .allocator = allocator, .items = try allocator.alloc(T, capacity), }; return q; } pub fn deinit(self: *Self) void { self.allocator.free(self.items); self.allocator.destroy(self); } pub fn empty(self: *const Self) bool { return self.tail == 0; } pub fn full(self: *const Self) bool { return self.tail == self.capacity; } pub fn size(self: *const Self) usize { return self.tail; } fn minChild(self: *const Self, first: usize, last: usize) usize { const left = 2 * first; const right = left + 1; if (right <= last and cmp(self.items[right - 1], self.items[left - 1]) == .lt) { return right; } else { return left; } } fn fixHeap(self: *Self, first: usize, last: usize) void { var found = false; var parent = first; var great = self.minChild(parent, last); while (parent <= last / 2 and !found) { if (cmp(self.items[parent - 1], self.items[great - 1]) == .gt) { std.mem.swap(T, &self.items[parent - 1], &self.items[great - 1]); parent = great; great = self.minChild(parent, last); } else { found = true; } } } pub fn enqueue(self: *Self, x: T) error{Full}!void { if (self.full()) { return error.Full; } else { // insert node at the end var current_index = self.tail + 1; self.tail += 1; self.items[current_index - 1] = x; // bubble up while (current_index > 1 and cmp(self.items[current_index - 1], self.items[current_index / 2 - 1]) == .lt) { std.mem.swap(T, &self.items[current_index - 1], &self.items[current_index / 2 - 1]); current_index /= 2; } } } pub fn dequeue(self: *Self) ?T { if (self.empty()) { return null; } else { // get root node const item = self.items[0]; // move last node to front self.tail -= 1; self.items[0] = self.items[self.tail]; // push it down self.fixHeap(1, self.tail); // return it return item; } } }; } // test PriorityQueue with numbers fn i32Compare(a: i32, b: i32) std.math.Order { if (a < b) { return .lt; } else if (a > b) { return .gt; } else { return .eq; } } const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectError = std.testing.expectError; test "PriorityQueue.init" { var pq = try PriorityQueue(i32, i32Compare).init(std.testing.allocator, 10); defer pq.deinit(); try expectEqual(@as(usize, 10), pq.capacity); try expectEqual(@as(usize, 0), pq.size()); try expect(pq.empty()); try expect(!pq.full()); } test "PriorityQueue operations" { var pq = try PriorityQueue(i32, i32Compare).init(std.testing.allocator, 10); defer pq.deinit(); const nums = [_]i32{5, 3, 6, 7, 10, 8}; var sorted = nums; std.sort.sort(i32, &sorted, {}, comptime std.sort.asc(i32)); for (nums) |n| { try pq.enqueue(n); } try expectEqual(nums.len, pq.size()); for (sorted) |n| { try expectEqual(n, pq.dequeue().?); } try expect(pq.empty()); } test "full and empty PriorityQueue" { var pq = try PriorityQueue(i32, i32Compare).init(std.testing.allocator, 10); defer pq.deinit(); var i: i32 = 0; while (i < pq.capacity) : (i += 1) { try pq.enqueue(i); } try expect(pq.full()); try expectError(error.Full, pq.enqueue(50)); while (!pq.empty()) { _ = pq.dequeue(); } try expectEqual(@as(?i32, null), pq.dequeue()); }
src/zig/src/pq.zig
const std = @import("std"); const Logind = @import("systemd.zig").Logind; const backend = @import("../backend.zig"); const epoll = @import("../../epoll.zig"); const Dispatchable = @import("../../epoll.zig").Dispatchable; const c = @cImport({ @cInclude("libudev.h"); @cInclude("dirent.h"); @cInclude("libinput.h"); }); pub var global_logind: *Logind = undefined; pub const Input = struct { udev_context: ?*c.udev, context: ?*c.struct_libinput, fd: c_int, dispatchable: Dispatchable, pub fn create(l: *Logind) !Input { global_logind = l; var udev_context = c.udev_new(); var ctx = c.libinput_udev_create_context(&input_interface, null, udev_context); if (ctx == null) { return error.UdevCreateContextFailed; } if (c.libinput_udev_assign_seat(ctx, "seat0") == -1) { return error.UdevAssignSeatFailed; } var fd = c.libinput_get_fd(ctx); return Input{ .udev_context = udev_context, .context = ctx, .fd = fd, .dispatchable = Dispatchable{ .impl = dispatch, }, }; } pub fn deinit(self: *Input) void { _ = c.libinput_unref(self.context); } fn getFd(self: *Input) i32 { return c.libinput_get_fd(self.context); } pub fn addToEpoll(self: *Input) !void { try epoll.addFd(self.getFd(), &self.dispatchable); } }; const EventType = c.enum_libinput_event_type; pub fn dispatch(dispatchable: *Dispatchable, event_type: usize) anyerror!void { var input = @fieldParentPtr(Input, "dispatchable", dispatchable); _ = c.libinput_dispatch(input.context); while (c.libinput_get_event(input.context)) |event| { var input_event_type = c.libinput_event_get_type(event); switch (input_event_type) { EventType.LIBINPUT_EVENT_DEVICE_ADDED => { var device = c.libinput_event_get_device(event); var name = c.libinput_device_get_name(device); std.debug.warn("Added device: {s}\n", .{std.mem.span(name)}); _ = c.libinput_device_ref(device); var seat = c.libinput_device_get_seat(device); _ = c.libinput_seat_ref(seat); }, EventType.LIBINPUT_EVENT_DEVICE_REMOVED => std.debug.warn("device removed\n", .{}), EventType.LIBINPUT_EVENT_KEYBOARD_KEY => { var keyboard_event = c.libinput_event_get_keyboard_event(event); var key = c.libinput_event_keyboard_get_key(keyboard_event); var state = @intCast(u32, @enumToInt(c.libinput_event_keyboard_get_key_state(keyboard_event))); var time = c.libinput_event_keyboard_get_time(keyboard_event); if (backend.BACKEND_FNS.keyboard) |keyboard_fn| { try keyboard_fn(time, key, state); } }, EventType.LIBINPUT_EVENT_POINTER_BUTTON => { var mouse_button_event = c.libinput_event_get_pointer_event(event); var button = c.libinput_event_pointer_get_button(mouse_button_event); var state = @intCast(u32, @enumToInt(c.libinput_event_pointer_get_button_state(mouse_button_event))); var time = c.libinput_event_pointer_get_time(mouse_button_event); if (backend.BACKEND_FNS.mouseClick) |mouseClick| { try mouseClick(time, button, state); } }, EventType.LIBINPUT_EVENT_POINTER_MOTION => { var pointer_event = c.libinput_event_get_pointer_event(event); var dx = c.libinput_event_pointer_get_dx(pointer_event); var dy = c.libinput_event_pointer_get_dy(pointer_event); var time = c.libinput_event_pointer_get_time(pointer_event); if (backend.BACKEND_FNS.mouseMove) |mouseMove| { try mouseMove(time, dx, dy); } }, EventType.LIBINPUT_EVENT_POINTER_AXIS => { var pointer_event = c.libinput_event_get_pointer_event(event); var vertical = @intToEnum(c.enum_libinput_pointer_axis, c.LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL); var has_vertical = c.libinput_event_pointer_has_axis(pointer_event, vertical); if (has_vertical != 0) { var value = c.libinput_event_pointer_get_axis_value(pointer_event, vertical); var time = c.libinput_event_pointer_get_time(pointer_event); if (backend.BACKEND_FNS.mouseAxis) |mouseAxis| { try mouseAxis(time, c.LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL, value); } } }, else => std.debug.warn("unhandled event\n", .{}), } c.libinput_event_destroy(event); _ = c.libinput_dispatch(input.context); } } pub fn open(path: [*c]const u8, flags: c_int, user_data: ?*c_void) callconv(.C) c_int { var fd = global_logind.open(path) catch |e| { return -1; }; return fd; } pub fn close(fd: c_int, user_data: ?*c_void) callconv(.C) void { var x = global_logind.close(fd) catch |e| { return; }; return; } const input_interface = c.struct_libinput_interface{ .open_restricted = open, .close_restricted = close, };
src/backend/drm/input.zig
const c = @import("c.zig"); const m = @import("math/math.zig"); const std = @import("std"); const alogg = std.log.scoped(.nil_core_gl); /// Error set pub const Error = std.mem.Allocator.Error; // DEF /// Buffer bits pub const BufferBit = enum { depth, stencil, colour }; /// Buffer types pub const BufferType = enum { array, elementarray }; /// Draw types pub const DrawType = enum { static, dynamic, stream }; /// Draw modes pub const DrawMode = enum { points = 0x0000, lines = 0x0001, lineloop = 0x0002, linestrip = 0x0003, triangles = 0x0004, trianglestrip = 0x0005, trianglefan = 0x0006, }; /// Shader types pub const ShaderType = enum { vertex, fragment, geometry }; /// Texture types pub const TextureType = enum { t2D, }; // zig fmt: off /// Texture formats pub const TextureFormat = enum { rg, rg8, rgb, rgb8, rgb32f, rgba, rgba8, rgba32f, red, alpha }; // zig fmt: on /// Texture paramater types pub const TextureParamaterType = enum { min_filter, mag_filter, wrap_s, wrap_t, wrap_r, texture0, }; /// Texture paramater pub const TextureParamater = enum { filter_linear, filter_nearest, filter_mipmap_linear, filter_mipmap_nearest, wrap_repeat, wrap_mirrored_repeat, wrap_clamp_to_edge, wrap_clamp_to_border, }; // ENDDEF // COMMON /// Sets the glfw opengl profile pub fn setProfile() void { c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MAJOR, 3); c.glfwWindowHint(c.GLFW_CONTEXT_VERSION_MINOR, 3); c.glfwWindowHint(c.GLFW_OPENGL_PROFILE, c.GLFW_OPENGL_CORE_PROFILE); } /// Initializes OpenGL(GLAD) pub fn init() void { _ = c.gladLoaderLoadGL(); c.glPixelStorei(c.GL_UNPACK_ALIGNMENT, 1); } /// Deinitializes OpenGL(GLAD) pub fn deinit() void { c.gladLoaderUnloadGL(); } /// Specifies the red, green, blue, and alpha values used by clearBuffers to clear the colour buffers. /// Values are clamped to the range [0,1]. pub fn clearColour(r: f32, g: f32, b: f32, a: f32) void { c.glClearColor(r, g, b, a); } /// Clear buffers to preset values pub fn clearBuffers(comptime bit: BufferBit) void { c.glClear(pdecideBufferBit(bit)); } /// Set the viewport pub fn viewport(x: i32, y: i32, w: i32, h: i32) void { c.glViewport(x, y, w, h); } /// Set the ortho pub fn ortho(l: f32, r: f32, b: f32, t: f32, nr: f32, fr: f32) void { c.glOrtho(l, r, b, t, nr, fr); } /// Render primitives from array data pub fn drawArrays(mode: DrawMode, first: i32, count: i32) void { c.glDrawArrays(@enumToInt(mode), first, count); } /// Render primitives from array data pub fn drawElements(mode: DrawMode, size: i32, comptime typ: type, indices: ?*const c_void) void { const t = comptime pdecideGLTYPE(typ); c.glDrawElements(@enumToInt(mode), size, t, indices); } /// Enables/Disables the blending pub fn setBlending(status: bool) void { if (status) { c.glEnable(c.GL_BLEND); c.glBlendFunc(c.GL_SRC_ALPHA, c.GL_ONE_MINUS_SRC_ALPHA); } else c.glDisable(c.GL_BLEND); } // ENDCOMMON // BUFFERS /// Generate vertex array object names pub fn vertexArraysGen(n: i32, arrays: [*]u32) void { c.glGenVertexArrays(n, arrays); } /// Delete vertex array objects pub fn vertexArraysDelete(n: i32, arrays: [*]const u32) void { c.glDeleteVertexArrays(n, arrays); } /// Generate buffer object names pub fn buffersGen(n: i32, arrays: [*]u32) void { c.glGenBuffers(n, arrays); } /// Delete named buffer objects pub fn buffersDelete(n: i32, arrays: [*]const u32) void { c.glDeleteBuffers(n, arrays); } /// Bind a vertex array object pub fn vertexArrayBind(array: u32) void { c.glBindVertexArray(array); } /// Bind a named buffer object pub fn bufferBind(comptime target: BufferType, buffer: u32) void { c.glBindBuffer(pdecideBufferType(target), buffer); } /// Creates and initializes a buffer object's data store pub fn bufferData(comptime target: BufferType, size: u32, data: ?*const c_void, comptime usage: DrawType) void { c.glBufferData(pdecideBufferType(target), size, data, pdecideDrawType(usage)); } /// Updates a subset of a buffer object's data store pub fn bufferSubData(comptime target: BufferType, offset: i32, size: u32, data: ?*const c_void) void { c.glBufferSubData(pdecideBufferType(target), offset, size, data); } // ENDBUFFERS // SHADER /// Creates a shader pub fn shaderCreateBasic(comptime typ: ShaderType) u32 { return c.glCreateShader(pdecideShaderType(typ)); } /// Deletes the shader pub fn shaderDelete(sh: u32) void { c.glDeleteShader(sh); } /// Compiles the shader source with given shader type pub fn shaderCompile(alloc: *std.mem.Allocator, source: []const u8, comptime typ: ShaderType) Error!u32 { var result: u32 = shaderCreateBasic(typ); c.glShaderSource(result, 1, @ptrCast([*]const [*]const u8, &source), null); c.glCompileShader(result); var fuck: i32 = 0; c.glGetShaderiv(result, c.GL_COMPILE_STATUS, &fuck); if (fuck == 0) { var len: i32 = 0; c.glGetShaderiv(result, c.GL_INFO_LOG_LENGTH, &len); var msg = try alloc.alloc(u8, @intCast(usize, len)); c.glGetShaderInfoLog(result, len, &len, @ptrCast([*c]u8, msg)); alogg.emerg("{s}: {s}", .{ source, msg }); shaderDelete(result); alloc.free(msg); @panic("unable to compile shader!"); } return result; } /// Creates a program object pub fn shaderProgramCreateBasic() u32 { return c.glCreateProgram(); } /// Creates a program object from vertex and fragment source pub fn shaderProgramCreate(alloc: *std.mem.Allocator, vertex: []const u8, fragment: []const u8) Error!u32 { const vx = try shaderCompile(alloc, vertex, ShaderType.vertex); const fg = try shaderCompile(alloc, fragment, ShaderType.fragment); defer { shaderDelete(vx); shaderDelete(fg); } const result = shaderProgramCreateBasic(); shaderAttach(result, vx); shaderAttach(result, fg); shaderProgramLink(result); shaderProgramValidate(result); return result; } /// Deletes a program object pub fn shaderProgramDelete(pr: u32) void { c.glDeleteProgram(pr); } /// Installs a program object as part of current rendering state pub fn shaderProgramUse(pr: u32) void { c.glUseProgram(pr); } /// Attaches a shader object to a program object pub fn shaderAttach(pr: u32, sh: u32) void { c.glAttachShader(pr, sh); } /// Links a program object pub fn shaderProgramLink(pr: u32) void { c.glLinkProgram(pr); } /// Validates a program object pub fn shaderProgramValidate(pr: u32) void { c.glValidateProgram(pr); } /// Get uniform location from shader object pub fn shaderProgramGetUniformLocation(sh: u32, name: []const u8) i32 { return c.glGetUniformLocation(sh, @ptrCast([*c]const u8, name)); } /// Sets the int data pub fn shaderProgramSetInt(loc: i32, value: i32) void { c.glUniform1i(loc, value); } /// Sets the float data pub fn shaderProgramSetFloat(loc: i32, value: f32) void { c.glUniform1f(loc, value); } /// Sets the vec2 data pub fn shaderProgramSetVec2f(loc: i32, value: m.Vec2f) void { shaderProgramSetVec2fV(loc, @ptrCast([*]const f32, &value.toArray())); } /// Sets the vec3 data pub fn shaderProgramSetVec3f(loc: i32, value: m.Vec3f) void { shaderProgramSetVec3fV(loc, @ptrCast([*]const f32, &value.toArray())); } /// Sets the matrix data pub fn shaderProgramSetMat4x4f(loc: i32, value: m.Mat4x4f) void { shaderProgramSetMat4x4fV(loc, @ptrCast([*]const f32, &value.toArray())); } /// Sets the vec2 data pub fn shaderProgramSetVec2fV(loc: i32, value: [*]const f32) void { c.glUniform2fv(loc, 1, value); } /// Sets the vec3 data pub fn shaderProgramSetVec3fV(loc: i32, value: [*]const f32) void { c.glUniform3fv(loc, 1, value); } /// Sets the matrix data pub fn shaderProgramSetMat4x4fV(loc: i32, data: [*]const f32) void { c.glUniformMatrix4fv(loc, 1, c.GL_FALSE, data); } /// Enable or disable a generic vertex attribute array pub fn shaderProgramSetVertexAttribArray(index: u32, status: bool) void { if (status) { c.glEnableVertexAttribArray(index); } else { c.glDisableVertexAttribArray(index); } } /// Define an array of generic vertex attribute data pub fn shaderProgramSetVertexAttribPointer(index: u32, size: i32, comptime typ: type, normalize: bool, stride: i32, ptr: ?*const c_void) void { const t = comptime pdecideGLTYPE(typ); c.glVertexAttribPointer(index, size, t, if (normalize) c.GL_TRUE else c.GL_FALSE, stride, ptr); } // ENDSHADER // TEXTURE /// Generate texture names pub fn texturesGen(count: i32, textures: [*]u32) void { c.glGenTextures(count, textures); } /// Delete named textures pub fn texturesDelete(count: i32, textures: [*]const u32) void { c.glDeleteTextures(count, textures); } /// Generate mipmaps for a specified texture target pub fn texturesGenMipmap(comptime target: TextureType) void { c.glGenerateMipmap(pdecideTextureType(target)); } /// Bind a named texture to a texturing target pub fn textureBind(comptime target: TextureType, texture: u32) void { c.glBindTexture(pdecideTextureType(target), texture); } /// Specify a two-dimensional texture image pub fn textureTexImage2D(comptime target: TextureType, level: i32, comptime internalformat: TextureFormat, width: i32, height: i32, border: i32, comptime format: TextureFormat, comptime typ: type, data: ?*c_void) void { c.glTexImage2D(pdecideTextureType(target), level, @intCast(i32, pdecideTextureFormat(internalformat)), width, height, border, pdecideTextureFormat(format), pdecideGLTYPE(typ), data); } /// Set texture parameters pub fn textureTexParameteri(comptime target: TextureType, comptime pname: TextureParamaterType, comptime param: TextureParamater) void { c.glTexParameteri(pdecideTextureType(target), pdecideTextureParamType(pname), pdecideTextureParam(param)); } /// Set the active texture pub fn textureActive(comptime texture: TextureParamaterType) void { c.glActiveTexture(pdecideTextureParamType(texture)); } // ENDTEXTURE // PRIVATE /// Decides the buffer bit type from given BufferBit fn pdecideBufferBit(comptime typ: BufferBit) u32 { switch (typ) { BufferBit.depth => return c.GL_DEPTH_BUFFER_BIT, BufferBit.stencil => return c.GL_STENCIL_BUFFER_BIT, BufferBit.colour => return c.GL_COLOR_BUFFER_BIT, } } /// Decides the buffer type from given BufferType fn pdecideBufferType(comptime typ: BufferType) u32 { switch (typ) { BufferType.array => return c.GL_ARRAY_BUFFER, BufferType.elementarray => return c.GL_ELEMENT_ARRAY_BUFFER, } } /// Decides the draw type from given DrawType fn pdecideDrawType(comptime typ: DrawType) u32 { switch (typ) { DrawType.static => return c.GL_STATIC_DRAW, DrawType.dynamic => return c.GL_DYNAMIC_DRAW, DrawType.stream => return c.GL_STREAM_DRAW, } } /// Decides the Shader type from given ShaderType fn pdecideShaderType(comptime typ: ShaderType) u32 { switch (typ) { ShaderType.vertex => return c.GL_VERTEX_SHADER, ShaderType.fragment => return c.GL_FRAGMENT_SHADER, ShaderType.geometry => return c.GL_GEOMETRY_SHADER, } } /// Decides the Texture type from given TextureType fn pdecideTextureType(comptime typ: TextureType) u32 { switch (typ) { TextureType.t2D => return c.GL_TEXTURE_2D, } } /// Decides the Texture format from given TextureFormat fn pdecideTextureFormat(comptime typ: TextureFormat) u32 { switch (typ) { TextureFormat.rg => return c.GL_RG, TextureFormat.rg8 => return c.GL_RG8, TextureFormat.rgb => return c.GL_RGB, TextureFormat.rgb8 => return c.GL_RGB8, TextureFormat.rgb32f => return c.GL_RGB32F, TextureFormat.rgba => return c.GL_RGBA, TextureFormat.rgba8 => return c.GL_RGBA8, TextureFormat.rgba32f => return c.GL_RGBA32F, TextureFormat.red => return c.GL_RED, TextureFormat.alpha => return c.GL_ALPHA, } } /// Decides the Texture parameter type from given TextureParamaterType fn pdecideTextureParamType(comptime typ: TextureParamaterType) u32 { switch (typ) { TextureParamaterType.min_filter => return c.GL_TEXTURE_MIN_FILTER, TextureParamaterType.mag_filter => return c.GL_TEXTURE_MAG_FILTER, TextureParamaterType.wrap_s => return c.GL_TEXTURE_WRAP_S, TextureParamaterType.wrap_t => return c.GL_TEXTURE_WRAP_T, TextureParamaterType.wrap_r => return c.GL_TEXTURE_WRAP_R, TextureParamaterType.texture0 => return c.GL_TEXTURE0, } } /// Decides the Texture parameter from given TextureParamater fn pdecideTextureParam(comptime typ: TextureParamater) i32 { switch (typ) { TextureParamater.filter_linear => return c.GL_LINEAR, TextureParamater.filter_nearest => return c.GL_NEAREST, TextureParamater.filter_mipmap_linear => return c.GL_LINEAR_MIPMAP_LINEAR, TextureParamater.filter_mipmap_nearest => return c.GL_LINEAR_MIPMAP_NEAREST, TextureParamater.wrap_repeat => return c.GL_REPEAT, TextureParamater.wrap_mirrored_repeat => return c.GL_MIRRORED_REPEAT, TextureParamater.wrap_clamp_to_edge => return c.GL_CLAMP_TO_EDGE, TextureParamater.wrap_clamp_to_border => return c.GL_CLAMP_TO_BORDER, } } /// Decides the GL_TYPE from given zig type fn pdecideGLTYPE(comptime typ: type) u32 { switch (typ) { u8 => return c.GL_UNSIGNED_BYTE, u32 => return c.GL_UNSIGNED_INT, i32 => return c.GL_INT, f32 => return c.GL_FLOAT, else => @compileError("Unknown gl type"), } } // ENDPRIVATE
src/core/gl.zig
const std = @import("index.zig"); const debug = std.debug; const mem = std.mem; const Allocator = mem.Allocator; const assert = debug.assert; const ArrayList = std.ArrayList; const fmt = std.fmt; /// A buffer that allocates memory and maintains a null byte at the end. pub const Buffer = struct { list: ArrayList(u8), /// Must deinitialize with deinit. pub fn init(allocator: *Allocator, m: []const u8) !Buffer { var self = try initSize(allocator, m.len); mem.copy(u8, self.list.items, m); return self; } /// Must deinitialize with deinit. pub fn initSize(allocator: *Allocator, size: usize) !Buffer { var self = initNull(allocator); try self.resize(size); return self; } /// Must deinitialize with deinit. /// None of the other operations are valid until you do one of these: /// * ::replaceContents /// * ::resize pub fn initNull(allocator: *Allocator) Buffer { return Buffer{ .list = ArrayList(u8).init(allocator) }; } /// Must deinitialize with deinit. pub fn initFromBuffer(buffer: *const Buffer) !Buffer { return Buffer.init(buffer.list.allocator, buffer.toSliceConst()); } /// Buffer takes ownership of the passed in slice. The slice must have been /// allocated with `allocator`. /// Must deinitialize with deinit. pub fn fromOwnedSlice(allocator: *Allocator, slice: []u8) !Buffer { var self = Buffer{ .list = ArrayList(u8).fromOwnedSlice(allocator, slice) }; try self.list.append(0); return self; } /// The caller owns the returned memory. The Buffer becomes null and /// is safe to `deinit`. pub fn toOwnedSlice(self: *Buffer) []u8 { const allocator = self.list.allocator; const result = allocator.shrink(u8, self.list.items, self.len()); self.* = initNull(allocator); return result; } pub fn deinit(self: *Buffer) void { self.list.deinit(); } pub fn toSlice(self: *const Buffer) []u8 { return self.list.toSlice()[0..self.len()]; } pub fn toSliceConst(self: *const Buffer) []const u8 { return self.list.toSliceConst()[0..self.len()]; } pub fn shrink(self: *Buffer, new_len: usize) void { assert(new_len <= self.len()); self.list.shrink(new_len + 1); self.list.items[self.len()] = 0; } pub fn resize(self: *Buffer, new_len: usize) !void { try self.list.resize(new_len + 1); self.list.items[self.len()] = 0; } pub fn isNull(self: *const Buffer) bool { return self.list.len == 0; } pub fn len(self: *const Buffer) usize { return self.list.len - 1; } pub fn append(self: *Buffer, m: []const u8) !void { const old_len = self.len(); try self.resize(old_len + m.len); mem.copy(u8, self.list.toSlice()[old_len..], m); } pub fn appendByte(self: *Buffer, byte: u8) !void { const old_len = self.len(); try self.resize(old_len + 1); self.list.toSlice()[old_len] = byte; } pub fn eql(self: *const Buffer, m: []const u8) bool { return mem.eql(u8, self.toSliceConst(), m); } pub fn startsWith(self: *const Buffer, m: []const u8) bool { if (self.len() < m.len) return false; return mem.eql(u8, self.list.items[0..m.len], m); } pub fn endsWith(self: *const Buffer, m: []const u8) bool { const l = self.len(); if (l < m.len) return false; const start = l - m.len; return mem.eql(u8, self.list.items[start..l], m); } pub fn replaceContents(self: *Buffer, m: []const u8) !void { try self.resize(m.len); mem.copy(u8, self.list.toSlice(), m); } /// For passing to C functions. pub fn ptr(self: *const Buffer) [*]u8 { return self.list.items.ptr; } }; test "simple Buffer" { const cstr = @import("cstr.zig"); var buf = try Buffer.init(debug.global_allocator, ""); assert(buf.len() == 0); try buf.append("hello"); try buf.append(" "); try buf.append("world"); assert(buf.eql("hello world")); assert(mem.eql(u8, cstr.toSliceConst(buf.toSliceConst().ptr), buf.toSliceConst())); var buf2 = try Buffer.initFromBuffer(&buf); assert(buf.eql(buf2.toSliceConst())); assert(buf.startsWith("hell")); assert(buf.endsWith("orld")); try buf2.resize(4); assert(buf.startsWith(buf2.toSlice())); }
std/buffer.zig
const std = @import("std"); const os = std.os; const io = std.io; const mem = std.mem; const Buffer = std.Buffer; const llvm = @import("llvm.zig"); const c = @import("c.zig"); const builtin = @import("builtin"); const Target = @import("target.zig").Target; const warn = std.debug.warn; const Token = std.zig.Token; const ArrayList = std.ArrayList; const errmsg = @import("errmsg.zig"); pub const Module = struct { allocator: *mem.Allocator, name: Buffer, root_src_path: ?[]const u8, module: llvm.ModuleRef, context: llvm.ContextRef, builder: llvm.BuilderRef, target: Target, build_mode: builtin.Mode, zig_lib_dir: []const u8, version_major: u32, version_minor: u32, version_patch: u32, linker_script: ?[]const u8, cache_dir: []const u8, libc_lib_dir: ?[]const u8, libc_static_lib_dir: ?[]const u8, libc_include_dir: ?[]const u8, msvc_lib_dir: ?[]const u8, kernel32_lib_dir: ?[]const u8, dynamic_linker: ?[]const u8, out_h_path: ?[]const u8, is_test: bool, each_lib_rpath: bool, strip: bool, is_static: bool, linker_rdynamic: bool, clang_argv: []const []const u8, llvm_argv: []const []const u8, lib_dirs: []const []const u8, rpath_list: []const []const u8, assembly_files: []const []const u8, link_objects: []const []const u8, windows_subsystem_windows: bool, windows_subsystem_console: bool, link_libs_list: ArrayList(*LinkLib), libc_link_lib: ?*LinkLib, err_color: errmsg.Color, verbose_tokenize: bool, verbose_ast_tree: bool, verbose_ast_fmt: bool, verbose_cimport: bool, verbose_ir: bool, verbose_llvm_ir: bool, verbose_link: bool, darwin_frameworks: []const []const u8, darwin_version_min: DarwinVersionMin, test_filters: []const []const u8, test_name_prefix: ?[]const u8, emit_file_type: Emit, kind: Kind, pub const DarwinVersionMin = union(enum) { None, MacOS: []const u8, Ios: []const u8, }; pub const Kind = enum { Exe, Lib, Obj, }; pub const LinkLib = struct { name: []const u8, path: ?[]const u8, /// the list of symbols we depend on from this lib symbols: ArrayList([]u8), provided_explicitly: bool, }; pub const Emit = enum { Binary, Assembly, LlvmIr, }; pub fn create( allocator: *mem.Allocator, name: []const u8, root_src_path: ?[]const u8, target: *const Target, kind: Kind, build_mode: builtin.Mode, zig_lib_dir: []const u8, cache_dir: []const u8, ) !*Module { var name_buffer = try Buffer.init(allocator, name); errdefer name_buffer.deinit(); const context = c.LLVMContextCreate() orelse return error.OutOfMemory; errdefer c.LLVMContextDispose(context); const module = c.LLVMModuleCreateWithNameInContext(name_buffer.ptr(), context) orelse return error.OutOfMemory; errdefer c.LLVMDisposeModule(module); const builder = c.LLVMCreateBuilderInContext(context) orelse return error.OutOfMemory; errdefer c.LLVMDisposeBuilder(builder); const module_ptr = try allocator.create(Module{ .allocator = allocator, .name = name_buffer, .root_src_path = root_src_path, .module = module, .context = context, .builder = builder, .target = target.*, .kind = kind, .build_mode = build_mode, .zig_lib_dir = zig_lib_dir, .cache_dir = cache_dir, .version_major = 0, .version_minor = 0, .version_patch = 0, .verbose_tokenize = false, .verbose_ast_tree = false, .verbose_ast_fmt = false, .verbose_cimport = false, .verbose_ir = false, .verbose_llvm_ir = false, .verbose_link = false, .linker_script = null, .libc_lib_dir = null, .libc_static_lib_dir = null, .libc_include_dir = null, .msvc_lib_dir = null, .kernel32_lib_dir = null, .dynamic_linker = null, .out_h_path = null, .is_test = false, .each_lib_rpath = false, .strip = false, .is_static = false, .linker_rdynamic = false, .clang_argv = [][]const u8{}, .llvm_argv = [][]const u8{}, .lib_dirs = [][]const u8{}, .rpath_list = [][]const u8{}, .assembly_files = [][]const u8{}, .link_objects = [][]const u8{}, .windows_subsystem_windows = false, .windows_subsystem_console = false, .link_libs_list = ArrayList(*LinkLib).init(allocator), .libc_link_lib = null, .err_color = errmsg.Color.Auto, .darwin_frameworks = [][]const u8{}, .darwin_version_min = DarwinVersionMin.None, .test_filters = [][]const u8{}, .test_name_prefix = null, .emit_file_type = Emit.Binary, }); errdefer allocator.destroy(module_ptr); return module_ptr; } fn dump(self: *Module) void { c.LLVMDumpModule(self.module); } pub fn destroy(self: *Module) void { c.LLVMDisposeBuilder(self.builder); c.LLVMDisposeModule(self.module); c.LLVMContextDispose(self.context); self.name.deinit(); self.allocator.destroy(self); } pub fn build(self: *Module) !void { if (self.llvm_argv.len != 0) { var c_compatible_args = try std.cstr.NullTerminated2DArray.fromSlices(self.allocator, [][]const []const u8{ [][]const u8{"zig (LLVM option parsing)"}, self.llvm_argv, }); defer c_compatible_args.deinit(); c.ZigLLVMParseCommandLineOptions(self.llvm_argv.len + 1, c_compatible_args.ptr); } const root_src_path = self.root_src_path orelse @panic("TODO handle null root src path"); const root_src_real_path = os.path.real(self.allocator, root_src_path) catch |err| { try printError("unable to get real path '{}': {}", root_src_path, err); return err; }; errdefer self.allocator.free(root_src_real_path); const source_code = io.readFileAlloc(self.allocator, root_src_real_path) catch |err| { try printError("unable to open '{}': {}", root_src_real_path, err); return err; }; errdefer self.allocator.free(source_code); warn("====input:====\n"); warn("{}", source_code); warn("====parse:====\n"); var tree = try std.zig.parse(self.allocator, source_code); defer tree.deinit(); var stderr_file = try std.io.getStdErr(); var stderr_file_out_stream = std.io.FileOutStream.init(&stderr_file); const out_stream = &stderr_file_out_stream.stream; warn("====fmt:====\n"); _ = try std.zig.render(self.allocator, out_stream, &tree); warn("====ir:====\n"); warn("TODO\n\n"); warn("====llvm ir:====\n"); self.dump(); } pub fn link(self: *Module, out_file: ?[]const u8) !void { warn("TODO link"); return error.Todo; } pub fn addLinkLib(self: *Module, name: []const u8, provided_explicitly: bool) !*LinkLib { const is_libc = mem.eql(u8, name, "c"); if (is_libc) { if (self.libc_link_lib) |libc_link_lib| { return libc_link_lib; } } for (self.link_libs_list.toSliceConst()) |existing_lib| { if (mem.eql(u8, name, existing_lib.name)) { return existing_lib; } } const link_lib = try self.allocator.create(LinkLib{ .name = name, .path = null, .provided_explicitly = provided_explicitly, .symbols = ArrayList([]u8).init(self.allocator), }); try self.link_libs_list.append(link_lib); if (is_libc) { self.libc_link_lib = link_lib; } return link_lib; } }; fn printError(comptime format: []const u8, args: ...) !void { var stderr_file = try std.io.getStdErr(); var stderr_file_out_stream = std.io.FileOutStream.init(&stderr_file); const out_stream = &stderr_file_out_stream.stream; try out_stream.print(format, args); }
src-self-hosted/module.zig
const std = @import("std"); const DocumentStore = @import("document_store.zig"); const ast = std.zig.ast; const types = @import("types.zig"); const offsets = @import("offsets.zig"); const log = std.log.scoped(.analysis); /// Get a declaration's doc comment node pub fn getDocCommentNode(tree: *ast.Tree, node: *ast.Node) ?*ast.Node.DocComment { if (node.castTag(.FnProto)) |func| { return func.getDocComments(); } else if (node.castTag(.VarDecl)) |var_decl| { return var_decl.getDocComments(); } else if (node.castTag(.ContainerField)) |field| { return field.doc_comments; } else if (node.castTag(.ErrorTag)) |tag| { return tag.doc_comments; } return null; } /// Gets a declaration's doc comments, caller must free memory when a value is returned /// Like: ///```zig ///var comments = getFunctionDocComments(allocator, tree, func); ///defer if (comments) |comments_pointer| allocator.free(comments_pointer); ///``` pub fn getDocComments( allocator: *std.mem.Allocator, tree: *ast.Tree, node: *ast.Node, format: types.MarkupContent.Kind, ) !?[]const u8 { if (getDocCommentNode(tree, node)) |doc_comment_node| { return try collectDocComments(allocator, tree, doc_comment_node, format); } return null; } pub fn collectDocComments( allocator: *std.mem.Allocator, tree: *ast.Tree, doc_comments: *ast.Node.DocComment, format: types.MarkupContent.Kind, ) ![]const u8 { var lines = std.ArrayList([]const u8).init(allocator); defer lines.deinit(); var curr_line_tok = doc_comments.first_line; while (true) : (curr_line_tok += 1) { switch (tree.token_ids[curr_line_tok]) { .LineComment => continue, .DocComment, .ContainerDocComment => { try lines.append(std.mem.trim(u8, tree.tokenSlice(curr_line_tok)[3..], &std.ascii.spaces)); }, else => break, } } return try std.mem.join(allocator, if (format == .Markdown) " \n" else "\n", lines.items); } /// Gets a function signature (keywords, name, return value) pub fn getFunctionSignature(tree: *ast.Tree, func: *ast.Node.FnProto) []const u8 { const start = tree.token_locs[func.firstToken()].start; const end = tree.token_locs[switch (func.return_type) { .Explicit, .InferErrorSet => |node| node.lastToken(), .Invalid => |r_paren| r_paren, }].end; return tree.source[start..end]; } /// Gets a function snippet insert text pub fn getFunctionSnippet(allocator: *std.mem.Allocator, tree: *ast.Tree, func: *ast.Node.FnProto, skip_self_param: bool) ![]const u8 { const name_tok = func.getNameToken() orelse unreachable; var buffer = std.ArrayList(u8).init(allocator); try buffer.ensureCapacity(128); try buffer.appendSlice(tree.tokenSlice(name_tok)); try buffer.append('('); var buf_stream = buffer.writer(); for (func.paramsConst()) |param, param_num| { if (skip_self_param and param_num == 0) continue; if (param_num != @boolToInt(skip_self_param)) try buffer.appendSlice(", ${") else try buffer.appendSlice("${"); try buf_stream.print("{}:", .{param_num + 1}); if (param.comptime_token) |_| { try buffer.appendSlice("comptime "); } if (param.noalias_token) |_| { try buffer.appendSlice("noalias "); } if (param.name_token) |name_token| { try buffer.appendSlice(tree.tokenSlice(name_token)); try buffer.appendSlice(": "); } switch (param.param_type) { .any_type => try buffer.appendSlice("anytype"), .type_expr => |type_expr| { var curr_tok = type_expr.firstToken(); var end_tok = type_expr.lastToken(); while (curr_tok <= end_tok) : (curr_tok += 1) { const id = tree.token_ids[curr_tok]; const is_comma = id == .Comma; if (curr_tok == end_tok and is_comma) continue; try buffer.appendSlice(tree.tokenSlice(curr_tok)); if (is_comma or id == .Keyword_const) try buffer.append(' '); } }, } try buffer.append('}'); } try buffer.append(')'); return buffer.toOwnedSlice(); } /// Gets a function signature (keywords, name, return value) pub fn getVariableSignature(tree: *ast.Tree, var_decl: *ast.Node.VarDecl) []const u8 { const start = tree.token_locs[var_decl.firstToken()].start; const end = tree.token_locs[var_decl.semicolon_token].start; return tree.source[start..end]; } // analysis.getContainerFieldSignature(handle.tree, field) pub fn getContainerFieldSignature(tree: *ast.Tree, field: *ast.Node.ContainerField) []const u8 { const start = tree.token_locs[field.firstToken()].start; const end = tree.token_locs[field.lastToken()].end; return tree.source[start..end]; } /// The type node is "type" fn typeIsType(tree: *ast.Tree, node: *ast.Node) bool { if (node.castTag(.Identifier)) |ident| { return std.mem.eql(u8, tree.tokenSlice(ident.token), "type"); } return false; } pub fn isTypeFunction(tree: *ast.Tree, func: *ast.Node.FnProto) bool { switch (func.return_type) { .Explicit => |node| return typeIsType(tree, node), .InferErrorSet, .Invalid => return false, } } pub fn isGenericFunction(tree: *ast.Tree, func: *ast.Node.FnProto) bool { for (func.paramsConst()) |param| { if (param.param_type == .any_type or param.comptime_token != null) { return true; } } return false; } // STYLE pub fn isCamelCase(name: []const u8) bool { return !std.ascii.isUpper(name[0]) and std.mem.indexOf(u8, name[0..(name.len - 1)], "_") == null; } pub fn isPascalCase(name: []const u8) bool { return std.ascii.isUpper(name[0]) and std.mem.indexOf(u8, name[0..(name.len - 1)], "_") == null; } // ANALYSIS ENGINE pub fn getDeclNameToken(tree: *ast.Tree, node: *ast.Node) ?ast.TokenIndex { switch (node.tag) { .VarDecl => { const vari = node.castTag(.VarDecl).?; return vari.name_token; }, .FnProto => { const func = node.castTag(.FnProto).?; return func.getNameToken(); }, .ContainerField => { const field = node.castTag(.ContainerField).?; return field.name_token; }, .ErrorTag => { const tag = node.castTag(.ErrorTag).?; return tag.name_token; }, // We need identifier for captures and error set tags .Identifier => { const ident = node.castTag(.Identifier).?; return ident.token; }, .TestDecl => { const decl = node.castTag(.TestDecl).?; return (decl.name.castTag(.StringLiteral) orelse return null).token; }, else => {}, } return null; } fn getDeclName(tree: *ast.Tree, node: *ast.Node) ?[]const u8 { const name = tree.tokenSlice(getDeclNameToken(tree, node) orelse return null); return switch (node.tag) { .TestDecl => name[1 .. name.len - 1], else => name, }; } fn isContainerDecl(decl_handle: DeclWithHandle) bool { return switch (decl_handle.decl.*) { .ast_node => |inner_node| inner_node.tag == .ContainerDecl or inner_node.tag == .Root, else => false, }; } fn resolveVarDeclAliasInternal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, node_handle: NodeWithHandle, root: bool, ) error{OutOfMemory}!?DeclWithHandle { const handle = node_handle.handle; if (node_handle.node.castTag(.Identifier)) |ident| { return try lookupSymbolGlobal(store, arena, handle, handle.tree.tokenSlice(ident.token), handle.tree.token_locs[ident.token].start); } if (node_handle.node.cast(ast.Node.SimpleInfixOp)) |infix_op| { if (node_handle.node.tag != .Period) return null; const container_node = if (infix_op.lhs.castTag(.BuiltinCall)) |builtin_call| block: { if (!std.mem.eql(u8, handle.tree.tokenSlice(builtin_call.builtin_token), "@import")) return null; const inner_node = (try resolveTypeOfNode(store, arena, .{ .node = infix_op.lhs, .handle = handle })) orelse return null; std.debug.assert(inner_node.type.data.other.tag == .Root); break :block NodeWithHandle{ .node = inner_node.type.data.other, .handle = inner_node.handle }; } else if (try resolveVarDeclAliasInternal(store, arena, .{ .node = infix_op.lhs, .handle = handle }, false)) |decl_handle| block: { if (decl_handle.decl.* != .ast_node) return null; const resolved = (try resolveTypeOfNode(store, arena, .{ .node = decl_handle.decl.ast_node, .handle = decl_handle.handle })) orelse return null; const resolved_node = switch (resolved.type.data) { .other => |n| n, else => return null, }; if (resolved_node.tag != .ContainerDecl and resolved_node.tag != .Root) return null; break :block NodeWithHandle{ .node = resolved_node, .handle = resolved.handle }; } else return null; if (try lookupSymbolContainer(store, arena, container_node, handle.tree.tokenSlice(infix_op.rhs.firstToken()), false)) |inner_decl| { if (root) return inner_decl; return inner_decl; } } return null; } /// Resolves variable declarations consisting of chains of imports and field accesses of containers, ending with the same name as the variable decl's name /// Examples: ///```zig /// const decl = @import("decl-file.zig").decl; /// const other = decl.middle.other; ///``` pub fn resolveVarDeclAlias(store: *DocumentStore, arena: *std.heap.ArenaAllocator, decl_handle: NodeWithHandle) !?DeclWithHandle { const decl = decl_handle.node; const handle = decl_handle.handle; if (decl.castTag(.VarDecl)) |var_decl| { const base_expr = var_decl.getInitNode() orelse return null; if (handle.tree.token_ids[var_decl.mut_token] != .Keyword_const) return null; if (base_expr.cast(ast.Node.SimpleInfixOp)) |infix_op| { if (base_expr.tag != .Period) return null; const name = handle.tree.tokenSlice(infix_op.rhs.firstToken()); if (!std.mem.eql(u8, handle.tree.tokenSlice(var_decl.name_token), name)) return null; return try resolveVarDeclAliasInternal(store, arena, .{ .node = base_expr, .handle = handle }, true); } } return null; } fn findReturnStatementInternal( tree: *ast.Tree, fn_decl: *ast.Node.FnProto, base_node: *ast.Node, already_found: *bool, ) ?*ast.Node.ControlFlowExpression { var result: ?*ast.Node.ControlFlowExpression = null; var child_idx: usize = 0; while (base_node.iterate(child_idx)) |child_node| : (child_idx += 1) { if (child_node.castTag(.Return)) |cfe| { // If we are calling ourselves recursively, ignore this return. if (cfe.getRHS()) |rhs| { if (rhs.castTag(.Call)) |call_node| { if (call_node.lhs.tag == .Identifier) { if (std.mem.eql(u8, getDeclName(tree, call_node.lhs).?, getDeclName(tree, &fn_decl.base).?)) { continue; } } } } if (already_found.*) return null; already_found.* = true; result = cfe; continue; } result = findReturnStatementInternal(tree, fn_decl, child_node, already_found); } return result; } fn findReturnStatement(tree: *ast.Tree, fn_decl: *ast.Node.FnProto) ?*ast.Node.ControlFlowExpression { var already_found = false; return findReturnStatementInternal(tree, fn_decl, fn_decl.getBodyNode().?, &already_found); } /// Resolves the return type of a function pub fn resolveReturnType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, fn_decl: *ast.Node.FnProto, handle: *DocumentStore.Handle, bound_type_params: *BoundTypeParams, ) !?TypeWithHandle { if (isTypeFunction(handle.tree, fn_decl) and fn_decl.getBodyNode() != null) { // If this is a type function and it only contains a single return statement that returns // a container declaration, we will return that declaration. const ret = findReturnStatement(handle.tree, fn_decl) orelse return null; if (ret.getRHS()) |rhs| { return try resolveTypeOfNodeInternal(store, arena, .{ .node = rhs, .handle = handle, }, bound_type_params); } return null; } return switch (fn_decl.return_type) { .InferErrorSet => |return_type| block: { const child_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = return_type, .handle = handle, }, bound_type_params)) orelse return null; const child_type_node = switch (child_type.type.data) { .other => |n| n, else => return null, }; break :block TypeWithHandle{ .type = .{ .data = .{ .error_union = child_type_node }, .is_type_val = false }, .handle = child_type.handle }; }, .Explicit => |return_type| ((try resolveTypeOfNodeInternal(store, arena, .{ .node = return_type, .handle = handle, }, bound_type_params)) orelse return null).instanceTypeVal(), .Invalid => null, }; } /// Resolves the child type of an optional type fn resolveUnwrapOptionalType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, opt: TypeWithHandle, bound_type_params: *BoundTypeParams, ) !?TypeWithHandle { const opt_node = switch (opt.type.data) { .other => |n| n, else => return null, }; if (opt_node.cast(ast.Node.SimplePrefixOp)) |prefix_op| { if (opt_node.tag == .OptionalType) { return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = prefix_op.rhs, .handle = opt.handle, }, bound_type_params)) orelse return null).instanceTypeVal(); } } return null; } fn resolveUnwrapErrorType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, rhs: TypeWithHandle, bound_type_params: *BoundTypeParams, ) !?TypeWithHandle { const rhs_node = switch (rhs.type.data) { .other => |n| n, .error_union => |n| return TypeWithHandle{ .type = .{ .data = .{ .other = n }, .is_type_val = rhs.type.is_type_val }, .handle = rhs.handle, }, .primitive, .slice, .pointer => return null, }; if (rhs_node.cast(ast.Node.SimpleInfixOp)) |infix_op| { if (rhs_node.tag == .ErrorUnion) { return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = infix_op.rhs, .handle = rhs.handle, }, bound_type_params)) orelse return null).instanceTypeVal(); } } return null; } /// Resolves the child type of a deref type fn resolveDerefType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, deref: TypeWithHandle, bound_type_params: *BoundTypeParams, ) !?TypeWithHandle { const deref_node = switch (deref.type.data) { .other => |n| n, else => return null, }; if (deref_node.castTag(.PtrType)) |ptr_type| { switch (deref.handle.tree.token_ids[ptr_type.op_token]) { .Asterisk => { return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = ptr_type.rhs, .handle = deref.handle, }, bound_type_params)) orelse return null).instanceTypeVal(); }, .LBracket, .AsteriskAsterisk => return null, else => unreachable, } } return null; } /// Resolves bracket access type (both slicing and array access) fn resolveBracketAccessType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, lhs: TypeWithHandle, rhs: enum { Single, Range }, bound_type_params: *BoundTypeParams, ) !?TypeWithHandle { const lhs_node = switch (lhs.type.data) { .other => |n| n, else => return null, }; if (lhs_node.castTag(.SliceType)) |slice_type| { if (rhs == .Single) return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = slice_type.rhs, .handle = lhs.handle, }, bound_type_params)) orelse return null).instanceTypeVal(); return lhs; } else if (lhs_node.castTag(.ArrayType)) |array_type| { if (rhs == .Single) return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = array_type.rhs, .handle = lhs.handle, }, bound_type_params)) orelse return null).instanceTypeVal(); return TypeWithHandle{ .type = .{ .data = .{ .slice = array_type.rhs }, .is_type_val = false }, .handle = lhs.handle, }; } else if (lhs_node.castTag(.PtrType)) |ptr_type| { if (ptr_type.rhs.castTag(.ArrayType)) |child_arr| { if (rhs == .Single) { return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = child_arr.rhs, .handle = lhs.handle, }, bound_type_params)) orelse return null).instanceTypeVal(); } return lhs; } } return null; } /// Called to remove one level of pointerness before a field access pub fn resolveFieldAccessLhsType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, lhs: TypeWithHandle, bound_type_params: *BoundTypeParams, ) !TypeWithHandle { return (try resolveDerefType(store, arena, lhs, bound_type_params)) orelse lhs; } pub const BoundTypeParams = std.AutoHashMap(*const ast.Node.FnProto.ParamDecl, TypeWithHandle); fn allDigits(str: []const u8) bool { for (str) |c| { if (!std.ascii.isDigit(c)) return false; } return true; } pub fn isTypeIdent(tree: *ast.Tree, token_idx: ast.TokenIndex) bool { const PrimitiveTypes = std.ComptimeStringMap(void, .{ .{"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"}, .{"anyframe"}, }); const text = tree.tokenSlice(token_idx); if (PrimitiveTypes.has(text)) return true; if (text.len > 1 and (text[0] == 'u' or text[0] == 'i') and allDigits(text[1..])) return true; return false; } /// Resolves the type of a node pub fn resolveTypeOfNodeInternal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, node_handle: NodeWithHandle, bound_type_params: *BoundTypeParams, ) error{OutOfMemory}!?TypeWithHandle { const node = node_handle.node; const handle = node_handle.handle; switch (node.tag) { .VarDecl => { const vari = node.castTag(.VarDecl).?; if (vari.getTypeNode()) |type_node| block: { return ((try resolveTypeOfNodeInternal( store, arena, .{ .node = type_node, .handle = handle }, bound_type_params, )) orelse break :block).instanceTypeVal(); } const init_node = vari.getInitNode() orelse return null; return try resolveTypeOfNodeInternal(store, arena, .{ .node = init_node, .handle = handle }, bound_type_params); }, .Identifier => { if (isTypeIdent(handle.tree, node.firstToken())) { return TypeWithHandle{ .type = .{ .data = .primitive, .is_type_val = true }, .handle = handle, }; } if (try lookupSymbolGlobal(store, arena, handle, handle.tree.getNodeSource(node), handle.tree.token_locs[node.firstToken()].start)) |child| { switch (child.decl.*) { .ast_node => |n| { if (n == node) return null; if (n.castTag(.VarDecl)) |var_decl| { if (var_decl.getInitNode()) |init_node| if (init_node == node) return null; } }, else => {}, } return try child.resolveType(store, arena, bound_type_params); } return null; }, .ContainerField => { const field = node.castTag(.ContainerField).?; return ((try resolveTypeOfNodeInternal( store, arena, .{ .node = field.type_expr orelse return null, .handle = handle }, bound_type_params, )) orelse return null).instanceTypeVal(); }, .Call => { const call = node.castTag(.Call).?; const decl = (try resolveTypeOfNodeInternal( store, arena, .{ .node = call.lhs, .handle = handle }, bound_type_params, )) orelse return null; if (decl.type.is_type_val) return null; const decl_node = switch (decl.type.data) { .other => |n| n, else => return null, }; if (decl_node.castTag(.FnProto)) |fn_decl| { var has_self_param: u8 = 0; if (call.lhs.cast(ast.Node.SimpleInfixOp)) |lhs_infix_op| { if (call.lhs.tag == .Period) { has_self_param = 1; } } // Bidn type params to the expressions passed in the calls. const param_len = std.math.min(call.params_len + has_self_param, fn_decl.params_len); for (fn_decl.paramsConst()) |*decl_param, param_idx| { if (param_idx < has_self_param) continue; if (param_idx >= param_len) break; const type_param = switch (decl_param.param_type) { .type_expr => |type_node| typeIsType(decl.handle.tree, type_node), else => false, }; if (!type_param) continue; const call_param_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = call.paramsConst()[param_idx - has_self_param], .handle = handle, }, bound_type_params)) orelse continue; if (!call_param_type.type.is_type_val) continue; _ = try bound_type_params.put(decl_param, call_param_type); } return try resolveReturnType(store, arena, fn_decl, decl.handle, bound_type_params); } return null; }, .Comptime => { const ct = node.castTag(.Comptime).?; return try resolveTypeOfNodeInternal(store, arena, .{ .node = ct.expr, .handle = handle }, bound_type_params); }, .GroupedExpression => { const grouped = node.castTag(.GroupedExpression).?; return try resolveTypeOfNodeInternal(store, arena, .{ .node = grouped.expr, .handle = handle }, bound_type_params); }, .StructInitializer => { const struct_init = node.castTag(.StructInitializer).?; return ((try resolveTypeOfNodeInternal( store, arena, .{ .node = struct_init.lhs, .handle = handle }, bound_type_params, )) orelse return null).instanceTypeVal(); }, .ErrorSetDecl => { return TypeWithHandle.typeVal(node_handle); }, .Slice => { const slice = node.castTag(.Slice).?; const left_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = slice.lhs, .handle = handle, }, bound_type_params)) orelse return null; return try resolveBracketAccessType(store, arena, left_type, .Range, bound_type_params); }, .Deref, .UnwrapOptional => { const suffix = node.cast(ast.Node.SimpleSuffixOp).?; const left_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = suffix.lhs, .handle = handle, }, bound_type_params)) orelse return null; return switch (node.tag) { .UnwrapOptional => try resolveUnwrapOptionalType(store, arena, left_type, bound_type_params), .Deref => try resolveDerefType(store, arena, left_type, bound_type_params), else => unreachable, }; }, .ArrayAccess => { const arr_acc = node.castTag(.ArrayAccess).?; const left_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = arr_acc.lhs, .handle = handle, }, bound_type_params)) orelse return null; return try resolveBracketAccessType(store, arena, left_type, .Single, bound_type_params); }, .Period => { const infix_op = node.cast(ast.Node.SimpleInfixOp).?; const rhs_str = nodeToString(handle.tree, infix_op.rhs) orelse return null; // If we are accessing a pointer type, remove one pointerness level :) const left_type = try resolveFieldAccessLhsType( store, arena, (try resolveTypeOfNodeInternal(store, arena, .{ .node = infix_op.lhs, .handle = handle, }, bound_type_params)) orelse return null, bound_type_params, ); const left_type_node = switch (left_type.type.data) { .other => |n| n, else => return null, }; if (try lookupSymbolContainer( store, arena, .{ .node = left_type_node, .handle = left_type.handle }, rhs_str, !left_type.type.is_type_val, )) |child| { return try child.resolveType(store, arena, bound_type_params); } else return null; }, .OrElse => { const infix_op = node.cast(ast.Node.SimpleInfixOp).?; const left_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = infix_op.lhs, .handle = handle, }, bound_type_params)) orelse return null; return try resolveUnwrapOptionalType(store, arena, left_type, bound_type_params); }, .Catch => { const infix_op = node.cast(ast.Node.Catch).?; const left_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = infix_op.lhs, .handle = handle, }, bound_type_params)) orelse return null; return try resolveUnwrapErrorType(store, arena, left_type, bound_type_params); }, .ErrorUnion => return TypeWithHandle.typeVal(node_handle), .SliceType, .ArrayType, .OptionalType, .PtrType, => return TypeWithHandle.typeVal(node_handle), .Try => { const prefix_op = node.cast(ast.Node.SimplePrefixOp).?; const rhs_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = prefix_op.rhs, .handle = handle, }, bound_type_params)) orelse return null; return try resolveUnwrapErrorType(store, arena, rhs_type, bound_type_params); }, .AddressOf => { const prefix_op = node.cast(ast.Node.SimplePrefixOp).?; const rhs_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = prefix_op.rhs, .handle = handle, }, bound_type_params)) orelse return null; const rhs_node = switch (rhs_type.type.data) { .other => |n| n, else => return null, }; return TypeWithHandle{ .type = .{ .data = .{ .pointer = rhs_node }, .is_type_val = false }, .handle = rhs_type.handle, }; }, .BuiltinCall => { const builtin_call = node.castTag(.BuiltinCall).?; const call_name = handle.tree.tokenSlice(builtin_call.builtin_token); if (std.mem.eql(u8, call_name, "@This")) { if (builtin_call.params_len != 0) return null; return innermostContainer(handle, handle.tree.token_locs[builtin_call.firstToken()].start); } const cast_map = std.ComptimeStringMap(void, .{ .{"@as"}, .{"@bitCast"}, .{"@fieldParentPtr"}, .{"@floatCast"}, .{"@floatToInt"}, .{"@intCast"}, .{"@intToEnum"}, .{"@intToFloat"}, .{"@intToPtr"}, .{"@truncate"}, .{"@ptrCast"}, }); if (cast_map.has(call_name)) { if (builtin_call.params_len < 1) return null; return ((try resolveTypeOfNodeInternal(store, arena, .{ .node = builtin_call.paramsConst()[0], .handle = handle, }, bound_type_params)) orelse return null).instanceTypeVal(); } // Almost the same as the above, return a type value though. // TODO Do peer type resolution, we just keep the first for now. if (std.mem.eql(u8, call_name, "@TypeOf")) { if (builtin_call.params_len < 1) return null; var resolved_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = builtin_call.paramsConst()[0], .handle = handle, }, bound_type_params)) orelse return null; if (resolved_type.type.is_type_val) return null; resolved_type.type.is_type_val = true; return resolved_type; } if (!std.mem.eql(u8, call_name, "@import")) return null; if (builtin_call.params_len < 1) return null; const import_param = builtin_call.paramsConst()[0]; if (import_param.tag != .StringLiteral) return null; const import_str = handle.tree.tokenSlice(import_param.castTag(.StringLiteral).?.token); const new_handle = (store.resolveImport(handle, import_str[1 .. import_str.len - 1]) catch |err| { log.debug("Error {} while processing import {s}", .{ err, import_str }); return null; }) orelse return null; return TypeWithHandle.typeVal(.{ .node = &new_handle.tree.root_node.base, .handle = new_handle }); }, .ContainerDecl => { const container = node.castTag(.ContainerDecl).?; const kind = handle.tree.token_ids[container.kind_token]; return TypeWithHandle.typeVal(node_handle); }, .FnProto => { // This is a function type if (node.castTag(.FnProto).?.getNameToken() == null) { return TypeWithHandle.typeVal(node_handle); } return TypeWithHandle{ .type = .{ .data = .{ .other = node }, .is_type_val = false }, .handle = handle, }; }, .MultilineStringLiteral, .StringLiteral => return TypeWithHandle{ .type = .{ .data = .{ .other = node }, .is_type_val = false }, .handle = handle, }, else => {}, } return null; } // TODO Reorganize this file, perhaps split into a couple as well // TODO Make this better, nested levels of type vals pub const Type = struct { data: union(enum) { pointer: *ast.Node, slice: *ast.Node, error_union: *ast.Node, other: *ast.Node, primitive, }, /// If true, the type `type`, the attached data is the value of the type value. is_type_val: bool, }; pub const TypeWithHandle = struct { type: Type, handle: *DocumentStore.Handle, pub fn typeVal(node_handle: NodeWithHandle) TypeWithHandle { return .{ .type = .{ .data = .{ .other = node_handle.node }, .is_type_val = true, }, .handle = node_handle.handle, }; } fn instanceTypeVal(self: TypeWithHandle) ?TypeWithHandle { if (!self.type.is_type_val) return null; return TypeWithHandle{ .type = .{ .data = self.type.data, .is_type_val = false }, .handle = self.handle, }; } fn isRoot(self: TypeWithHandle) bool { switch (self.type.data) { .other => |n| return n.tag == .Root, else => return false, } } fn isContainer(self: TypeWithHandle, container_kind_tok: std.zig.Token.Id) bool { switch (self.type.data) { .other => |n| { if (n.castTag(.ContainerDecl)) |cont| { return self.handle.tree.token_ids[cont.kind_token] == container_kind_tok; } return false; }, else => return false, } } pub fn isStructType(self: TypeWithHandle) bool { return self.isContainer(.Keyword_struct) or self.isRoot(); } pub fn isNamespace(self: TypeWithHandle) bool { if (!self.isStructType()) return false; var idx: usize = 0; while (self.type.data.other.iterate(idx)) |child| : (idx += 1) { if (child.tag == .ContainerField) return false; } return true; } pub fn isEnumType(self: TypeWithHandle) bool { return self.isContainer(.Keyword_enum); } pub fn isUnionType(self: TypeWithHandle) bool { return self.isContainer(.Keyword_union); } pub fn isOpaqueType(self: TypeWithHandle) bool { return self.isContainer(.Keyword_opaque); } pub fn isTypeFunc(self: TypeWithHandle) bool { switch (self.type.data) { .other => |n| { if (n.castTag(.FnProto)) |fn_proto| { return isTypeFunction(self.handle.tree, fn_proto); } return false; }, else => return false, } } pub fn isGenericFunc(self: TypeWithHandle) bool { switch (self.type.data) { .other => |n| { if (n.castTag(.FnProto)) |fn_proto| { return isGenericFunction(self.handle.tree, fn_proto); } return false; }, else => return false, } } pub fn isFunc(self: TypeWithHandle) bool { switch (self.type.data) { .other => |n| { return n.tag == .FnProto; }, else => return false, } } }; pub fn resolveTypeOfNode(store: *DocumentStore, arena: *std.heap.ArenaAllocator, node_handle: NodeWithHandle) error{OutOfMemory}!?TypeWithHandle { var bound_type_params = BoundTypeParams.init(&arena.allocator); return resolveTypeOfNodeInternal(store, arena, node_handle, &bound_type_params); } fn maybeCollectImport(tree: *ast.Tree, builtin_call: *ast.Node.BuiltinCall, arr: *std.ArrayList([]const u8)) !void { if (!std.mem.eql(u8, tree.tokenSlice(builtin_call.builtin_token), "@import")) return; if (builtin_call.params_len > 1) return; const import_param = builtin_call.paramsConst()[0]; if (import_param.tag != .StringLiteral) return; const import_str = tree.tokenSlice(import_param.castTag(.StringLiteral).?.token); try arr.append(import_str[1 .. import_str.len - 1]); } /// Collects all imports we can find into a slice of import paths (without quotes). /// The import paths are valid as long as the tree is. pub fn collectImports(import_arr: *std.ArrayList([]const u8), tree: *ast.Tree) !void { // TODO: Currently only detects `const smth = @import("string literal")<.SomeThing>;` for (tree.root_node.decls()) |decl| { if (decl.tag != .VarDecl) continue; const var_decl = decl.castTag(.VarDecl).?; const init_node = var_decl.getInitNode() orelse continue; switch (init_node.tag) { .BuiltinCall => { const builtin_call = init_node.castTag(.BuiltinCall).?; try maybeCollectImport(tree, builtin_call, import_arr); }, .Period => { const infix_op = init_node.cast(ast.Node.SimpleInfixOp).?; if (infix_op.lhs.tag != .BuiltinCall) continue; try maybeCollectImport(tree, infix_op.lhs.castTag(.BuiltinCall).?, import_arr); }, else => {}, } } } pub const NodeWithHandle = struct { node: *ast.Node, handle: *DocumentStore.Handle, }; pub const FieldAccessReturn = struct { original: TypeWithHandle, unwrapped: ?TypeWithHandle = null, }; pub fn getFieldAccessType( store: *DocumentStore, arena: *std.heap.ArenaAllocator, handle: *DocumentStore.Handle, source_index: usize, tokenizer: *std.zig.Tokenizer, ) !?FieldAccessReturn { var current_type = TypeWithHandle.typeVal(.{ .node = undefined, .handle = handle, }); // TODO Actually bind params here when calling functions instead of just skipping args. var bound_type_params = BoundTypeParams.init(&arena.allocator); while (true) { const tok = tokenizer.next(); switch (tok.id) { .Eof => return FieldAccessReturn{ .original = current_type, .unwrapped = try resolveDerefType(store, arena, current_type, &bound_type_params), }, .Identifier => { if (try lookupSymbolGlobal(store, arena, current_type.handle, tokenizer.buffer[tok.loc.start..tok.loc.end], source_index)) |child| { current_type = (try child.resolveType(store, arena, &bound_type_params)) orelse return null; } else return null; }, .Period => { const after_period = tokenizer.next(); switch (after_period.id) { .Eof => return FieldAccessReturn{ .original = current_type, .unwrapped = try resolveDerefType(store, arena, current_type, &bound_type_params), }, .Identifier => { if (after_period.loc.end == tokenizer.buffer.len) { return FieldAccessReturn{ .original = current_type, .unwrapped = try resolveDerefType(store, arena, current_type, &bound_type_params), }; } current_type = try resolveFieldAccessLhsType(store, arena, current_type, &bound_type_params); const current_type_node = switch (current_type.type.data) { .other => |n| n, else => return null, }; if (try lookupSymbolContainer( store, arena, .{ .node = current_type_node, .handle = current_type.handle }, tokenizer.buffer[after_period.loc.start..after_period.loc.end], !current_type.type.is_type_val, )) |child| { current_type = (try child.resolveType(store, arena, &bound_type_params)) orelse return null; } else return null; }, .QuestionMark => { current_type = (try resolveUnwrapOptionalType(store, arena, current_type, &bound_type_params)) orelse return null; }, else => { log.debug("Unrecognized token {} after period.", .{after_period.id}); return null; }, } }, .PeriodAsterisk => { current_type = (try resolveDerefType(store, arena, current_type, &bound_type_params)) orelse return null; }, .LParen => { const current_type_node = switch (current_type.type.data) { .other => |n| n, else => return null, }; // Can't call a function type, we need a function type instance. if (current_type.type.is_type_val) return null; if (current_type_node.castTag(.FnProto)) |func| { if (try resolveReturnType(store, arena, func, current_type.handle, &bound_type_params)) |ret| { current_type = ret; // Skip to the right paren var paren_count: usize = 1; var next = tokenizer.next(); while (next.id != .Eof) : (next = tokenizer.next()) { if (next.id == .RParen) { paren_count -= 1; if (paren_count == 0) break; } else if (next.id == .LParen) { paren_count += 1; } } else return null; } else return null; } else return null; }, .LBracket => { var brack_count: usize = 1; var next = tokenizer.next(); var is_range = false; while (next.id != .Eof) : (next = tokenizer.next()) { if (next.id == .RBracket) { brack_count -= 1; if (brack_count == 0) break; } else if (next.id == .LBracket) { brack_count += 1; } else if (next.id == .Ellipsis2 and brack_count == 1) { is_range = true; } } else return null; current_type = (try resolveBracketAccessType(store, arena, current_type, if (is_range) .Range else .Single, &bound_type_params)) orelse return null; }, else => { log.debug("Unimplemented token: {}", .{tok.id}); return null; }, } } return FieldAccessReturn{ .original = current_type, .unwrapped = try resolveDerefType(store, arena, current_type, &bound_type_params), }; } pub fn isNodePublic(tree: *ast.Tree, node: *ast.Node) bool { switch (node.tag) { .VarDecl => { const var_decl = node.castTag(.VarDecl).?; return var_decl.getVisibToken() != null; }, .FnProto => { const func = node.castTag(.FnProto).?; return func.getVisibToken() != null; }, else => return true, } } pub fn nodeToString(tree: *ast.Tree, node: *ast.Node) ?[]const u8 { switch (node.tag) { .ContainerField => { const field = node.castTag(.ContainerField).?; return tree.tokenSlice(field.name_token); }, .ErrorTag => { const tag = node.castTag(.ErrorTag).?; return tree.tokenSlice(tag.name_token); }, .Identifier => { const field = node.castTag(.Identifier).?; return tree.tokenSlice(field.token); }, .FnProto => { const func = node.castTag(.FnProto).?; if (func.getNameToken()) |name_token| { return tree.tokenSlice(name_token); } }, else => { log.debug("INVALID: {}", .{node.tag}); }, } return null; } fn nodeContainsSourceIndex(tree: *ast.Tree, node: *ast.Node, source_index: usize) bool { const first_token = tree.token_locs[node.firstToken()]; const last_token = tree.token_locs[node.lastToken()]; return source_index >= first_token.start and source_index <= last_token.end; } pub fn getImportStr(tree: *ast.Tree, source_index: usize) ?[]const u8 { var node = &tree.root_node.base; var child_idx: usize = 0; while (node.iterate(child_idx)) |child| { if (!nodeContainsSourceIndex(tree, child, source_index)) { child_idx += 1; continue; } if (child.castTag(.BuiltinCall)) |builtin_call| blk: { const call_name = tree.tokenSlice(builtin_call.builtin_token); if (!std.mem.eql(u8, call_name, "@import")) break :blk; if (builtin_call.params_len != 1) break :blk; const import_param = builtin_call.paramsConst()[0]; const import_str_node = import_param.castTag(.StringLiteral) orelse break :blk; const import_str = tree.tokenSlice(import_str_node.token); return import_str[1 .. import_str.len - 1]; } node = child; child_idx = 0; } return null; } pub const SourceRange = std.zig.Token.Loc; pub const PositionContext = union(enum) { builtin: SourceRange, comment, string_literal: SourceRange, field_access: SourceRange, var_access: SourceRange, global_error_set, enum_literal, pre_label, label: bool, other, empty, pub fn range(self: PositionContext) ?SourceRange { return switch (self) { .builtin => |r| r, .comment => null, .string_literal => |r| r, .field_access => |r| r, .var_access => |r| r, .enum_literal => null, .pre_label => null, .label => null, .other => null, .empty => null, .global_error_set => null, }; } }; const StackState = struct { ctx: PositionContext, stack_id: enum { Paren, Bracket, Global }, }; fn peek(arr: *std.ArrayList(StackState)) !*StackState { if (arr.items.len == 0) { try arr.append(.{ .ctx = .empty, .stack_id = .Global }); } return &arr.items[arr.items.len - 1]; } fn tokenRangeAppend(prev: SourceRange, token: std.zig.Token) SourceRange { return .{ .start = prev.start, .end = token.loc.end, }; } const DocumentPosition = @import("offsets.zig").DocumentPosition; pub fn documentPositionContext(arena: *std.heap.ArenaAllocator, document: types.TextDocument, doc_position: DocumentPosition) !PositionContext { const line = doc_position.line; var tokenizer = std.zig.Tokenizer.init(line[0..doc_position.line_index]); var stack = try std.ArrayList(StackState).initCapacity(&arena.allocator, 8); while (true) { const tok = tokenizer.next(); // Early exits. switch (tok.id) { .Invalid, .Invalid_ampersands => { // Single '@' do not return a builtin token so we check this on our own. if (line[doc_position.line_index - 1] == '@') { return PositionContext{ .builtin = .{ .start = doc_position.line_index - 1, .end = doc_position.line_index, }, }; } return .other; }, .LineComment, .DocComment, .ContainerDocComment => return .comment, .Eof => break, else => {}, } // State changes var curr_ctx = try peek(&stack); switch (tok.id) { .StringLiteral, .MultilineStringLiteralLine => curr_ctx.ctx = .{ .string_literal = tok.loc }, .Identifier => switch (curr_ctx.ctx) { .empty, .pre_label => curr_ctx.ctx = .{ .var_access = tok.loc }, .label => |filled| if (!filled) { curr_ctx.ctx = .{ .label = true }; } else { curr_ctx.ctx = .{ .var_access = tok.loc }; }, else => {}, }, .Builtin => switch (curr_ctx.ctx) { .empty, .pre_label => curr_ctx.ctx = .{ .builtin = tok.loc }, else => {}, }, .Period, .PeriodAsterisk => switch (curr_ctx.ctx) { .empty, .pre_label => curr_ctx.ctx = .enum_literal, .enum_literal => curr_ctx.ctx = .empty, .field_access => {}, .other => {}, .global_error_set => {}, else => curr_ctx.ctx = .{ .field_access = tokenRangeAppend(curr_ctx.ctx.range().?, tok), }, }, .Keyword_break, .Keyword_continue => curr_ctx.ctx = .pre_label, .Colon => if (curr_ctx.ctx == .pre_label) { curr_ctx.ctx = .{ .label = false }; } else { curr_ctx.ctx = .empty; }, .QuestionMark => switch (curr_ctx.ctx) { .field_access => {}, else => curr_ctx.ctx = .empty, }, .LParen => try stack.append(.{ .ctx = .empty, .stack_id = .Paren }), .LBracket => try stack.append(.{ .ctx = .empty, .stack_id = .Bracket }), .RParen => { _ = stack.pop(); if (curr_ctx.stack_id != .Paren) { (try peek(&stack)).ctx = .empty; } }, .RBracket => { _ = stack.pop(); if (curr_ctx.stack_id != .Bracket) { (try peek(&stack)).ctx = .empty; } }, .Keyword_error => curr_ctx.ctx = .global_error_set, else => curr_ctx.ctx = .empty, } switch (curr_ctx.ctx) { .field_access => |r| curr_ctx.ctx = .{ .field_access = tokenRangeAppend(r, tok), }, else => {}, } } return block: { if (stack.popOrNull()) |state| break :block state.ctx; break :block .empty; }; } fn addOutlineNodes(allocator: *std.mem.Allocator, tree: *ast.Tree, child: *ast.Node, context: *GetDocumentSymbolsContext) anyerror!void { switch (child.tag) { .StringLiteral, .IntegerLiteral, .BuiltinCall, .Call, .Identifier, .Add, .AddWrap, .ArrayCat, .ArrayMult, .Assign, .AssignBitAnd, .AssignBitOr, .AssignBitShiftLeft, .AssignBitShiftRight, .AssignBitXor, .AssignDiv, .AssignSub, .AssignSubWrap, .AssignMod, .AssignAdd, .AssignAddWrap, .AssignMul, .AssignMulWrap, .BangEqual, .BitAnd, .BitOr, .BitShiftLeft, .BitShiftRight, .BitXor, .BoolAnd, .BoolOr, .Div, .EqualEqual, .ErrorUnion, .GreaterOrEqual, .GreaterThan, .LessOrEqual, .LessThan, .MergeErrorSets, .Mod, .Mul, .MulWrap, .Period, .Range, .Sub, .SubWrap, .OrElse, .AddressOf, .Await, .BitNot, .BoolNot, .OptionalType, .Negation, .NegationWrap, .Resume, .Try, .ArrayType, .ArrayTypeSentinel, .PtrType, .SliceType, .Slice, .Deref, .UnwrapOptional, .ArrayAccess, .Return, .Break, .Continue, .ArrayInitializerDot, .SwitchElse, .SwitchCase, .For, .EnumLiteral, .PointerIndexPayload, .StructInitializerDot, .PointerPayload, .While, .Switch, .Else, .BoolLiteral, .NullLiteral, .Defer, .StructInitializer, .FieldInitializer, .If, .MultilineStringLiteral, .UndefinedLiteral, .AnyType, .Block, .ErrorSetDecl, => return, .ContainerDecl => { const decl = child.castTag(.ContainerDecl).?; for (decl.fieldsAndDecls()) |cchild| try addOutlineNodes(allocator, tree, cchild, context); return; }, else => {}, } try getDocumentSymbolsInternal(allocator, tree, child, context); } const GetDocumentSymbolsContext = struct { prev_loc: offsets.TokenLocation = .{ .line = 0, .column = 0, .offset = 0, }, symbols: *std.ArrayList(types.DocumentSymbol), encoding: offsets.Encoding, }; fn getDocumentSymbolsInternal(allocator: *std.mem.Allocator, tree: *ast.Tree, node: *ast.Node, context: *GetDocumentSymbolsContext) anyerror!void { const name = getDeclName(tree, node) orelse return; if (name.len == 0) return; const start_loc = context.prev_loc.add(try offsets.tokenRelativeLocation(tree, context.prev_loc.offset, node.firstToken(), context.encoding)); const end_loc = start_loc.add(try offsets.tokenRelativeLocation(tree, start_loc.offset, node.lastToken(), context.encoding)); context.prev_loc = end_loc; const range = types.Range{ .start = .{ .line = @intCast(i64, start_loc.line), .character = @intCast(i64, start_loc.column), }, .end = .{ .line = @intCast(i64, end_loc.line), .character = @intCast(i64, end_loc.column), }, }; (try context.symbols.addOne()).* = .{ .name = name, .kind = switch (node.tag) { .FnProto => .Function, .VarDecl => .Variable, .ContainerField => .Field, else => .Variable, }, .range = range, .selectionRange = range, .detail = "", .children = ch: { var children = std.ArrayList(types.DocumentSymbol).init(allocator); var child_context = GetDocumentSymbolsContext{ .prev_loc = start_loc, .symbols = &children, .encoding = context.encoding, }; var index: usize = 0; while (node.iterate(index)) |child| : (index += 1) { try addOutlineNodes(allocator, tree, child, &child_context); } break :ch children.items; }, }; } pub fn getDocumentSymbols(allocator: *std.mem.Allocator, tree: *ast.Tree, encoding: offsets.Encoding) ![]types.DocumentSymbol { var symbols = try std.ArrayList(types.DocumentSymbol).initCapacity(allocator, tree.root_node.decls_len); var context = GetDocumentSymbolsContext{ .symbols = &symbols, .encoding = encoding, }; for (tree.root_node.decls()) |node| { try getDocumentSymbolsInternal(allocator, tree, node, &context); } return symbols.items; } pub const Declaration = union(enum) { ast_node: *ast.Node, param_decl: *ast.Node.FnProto.ParamDecl, pointer_payload: struct { node: *ast.Node.PointerPayload, condition: *ast.Node, }, array_payload: struct { identifier: *ast.Node, array_expr: *ast.Node, }, switch_payload: struct { node: *ast.Node.PointerPayload, switch_expr: *ast.Node, items: []const *ast.Node, }, label_decl: *ast.Node, // .id is While, For or Block (firstToken will be the label) }; pub const DeclWithHandle = struct { decl: *Declaration, handle: *DocumentStore.Handle, pub fn nameToken(self: DeclWithHandle) ast.TokenIndex { const tree = self.handle.tree; return switch (self.decl.*) { .ast_node => |n| getDeclNameToken(tree, n).?, .param_decl => |p| p.name_token.?, .pointer_payload => |pp| pp.node.value_symbol.firstToken(), .array_payload => |ap| ap.identifier.firstToken(), .switch_payload => |sp| sp.node.value_symbol.firstToken(), .label_decl => |ld| ld.firstToken(), }; } pub fn location(self: DeclWithHandle, encoding: offsets.Encoding) !offsets.TokenLocation { const tree = self.handle.tree; return try offsets.tokenRelativeLocation(tree, 0, self.nameToken(), encoding); } fn isPublic(self: DeclWithHandle) bool { return switch (self.decl.*) { .ast_node => |node| isNodePublic(self.handle.tree, node), else => true, }; } pub fn resolveType(self: DeclWithHandle, store: *DocumentStore, arena: *std.heap.ArenaAllocator, bound_type_params: *BoundTypeParams) !?TypeWithHandle { return switch (self.decl.*) { .ast_node => |node| try resolveTypeOfNodeInternal(store, arena, .{ .node = node, .handle = self.handle }, bound_type_params), .param_decl => |param_decl| switch (param_decl.param_type) { .type_expr => |type_node| { if (typeIsType(self.handle.tree, type_node)) { var bound_param_it = bound_type_params.iterator(); while (bound_param_it.next()) |entry| { if (entry.key == param_decl) return entry.value; } return null; } else if (type_node.castTag(.Identifier)) |type_ident| { if (param_decl.name_token) |name_tok| { if (std.mem.eql(u8, self.handle.tree.tokenSlice(type_ident.firstToken()), self.handle.tree.tokenSlice(name_tok))) return null; } } return ((try resolveTypeOfNodeInternal( store, arena, .{ .node = type_node, .handle = self.handle }, bound_type_params, )) orelse return null).instanceTypeVal(); }, else => null, }, .pointer_payload => |pay| try resolveUnwrapOptionalType( store, arena, (try resolveTypeOfNodeInternal(store, arena, .{ .node = pay.condition, .handle = self.handle, }, bound_type_params)) orelse return null, bound_type_params, ), .array_payload => |pay| try resolveBracketAccessType( store, arena, (try resolveTypeOfNodeInternal(store, arena, .{ .node = pay.array_expr, .handle = self.handle, }, bound_type_params)) orelse return null, .Single, bound_type_params, ), .label_decl => return null, .switch_payload => |pay| { if (pay.items.len == 0) return null; // TODO Peer type resolution, we just use the first item for now. const switch_expr_type = (try resolveTypeOfNodeInternal(store, arena, .{ .node = pay.switch_expr, .handle = self.handle, }, bound_type_params)) orelse return null; if (!switch_expr_type.isUnionType()) return null; if (pay.items[0].castTag(.EnumLiteral)) |enum_lit| { const scope = findContainerScope(.{ .node = switch_expr_type.type.data.other, .handle = switch_expr_type.handle }) orelse return null; if (scope.decls.getEntry(self.handle.tree.tokenSlice(enum_lit.name))) |candidate| { switch (candidate.value) { .ast_node => |node| { if (node.castTag(.ContainerField)) |container_field| { if (container_field.type_expr) |type_expr| { return ((try resolveTypeOfNodeInternal( store, arena, .{ .node = type_expr, .handle = switch_expr_type.handle }, bound_type_params, )) orelse return null).instanceTypeVal(); } } }, else => {}, } return null; } } return null; }, }; } }; fn findContainerScope(container_handle: NodeWithHandle) ?*Scope { const container = container_handle.node; const handle = container_handle.handle; if (container.tag != .ContainerDecl and container.tag != .Root and container.tag != .ErrorSetDecl) { return null; } // Find the container scope. var container_scope: ?*Scope = null; for (handle.document_scope.scopes) |*scope| { switch (scope.*.data) { .container => |node| if (node == container) { container_scope = scope; break; }, else => {}, } } return container_scope; } fn iterateSymbolsContainerInternal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, container_handle: NodeWithHandle, orig_handle: *DocumentStore.Handle, comptime callback: anytype, context: anytype, instance_access: bool, use_trail: *std.ArrayList(*ast.Node.Use), ) error{OutOfMemory}!void { const container = container_handle.node; const handle = container_handle.handle; const is_enum = if (container.castTag(.ContainerDecl)) |cont_decl| handle.tree.token_ids[cont_decl.kind_token] == .Keyword_enum else false; if (findContainerScope(container_handle)) |container_scope| { var decl_it = container_scope.decls.iterator(); while (decl_it.next()) |entry| { switch (entry.value) { .ast_node => |node| { if (node.tag == .ContainerField) { if (!instance_access and !is_enum) continue; if (instance_access and is_enum) continue; } }, .label_decl => continue, else => {}, } const decl = DeclWithHandle{ .decl = &entry.value, .handle = handle }; if (handle != orig_handle and !decl.isPublic()) continue; try callback(context, decl); } for (container_scope.uses) |use| { if (handle != orig_handle and use.visib_token == null) continue; if (std.mem.indexOfScalar(*ast.Node.Use, use_trail.items, use) != null) continue; try use_trail.append(use); const use_expr = (try resolveTypeOfNode(store, arena, .{ .node = use.expr, .handle = handle })) orelse continue; const use_expr_node = switch (use_expr.type.data) { .other => |n| n, else => continue, }; try iterateSymbolsContainerInternal(store, arena, .{ .node = use_expr_node, .handle = use_expr.handle }, orig_handle, callback, context, false, use_trail); } } } pub fn iterateSymbolsContainer( store: *DocumentStore, arena: *std.heap.ArenaAllocator, container_handle: NodeWithHandle, orig_handle: *DocumentStore.Handle, comptime callback: anytype, context: anytype, instance_access: bool, ) error{OutOfMemory}!void { var use_trail = std.ArrayList(*ast.Node.Use).init(&arena.allocator); return try iterateSymbolsContainerInternal(store, arena, container_handle, orig_handle, callback, context, instance_access, &use_trail); } pub fn iterateLabels( handle: *DocumentStore.Handle, source_index: usize, comptime callback: anytype, context: anytype, ) error{OutOfMemory}!void { for (handle.document_scope.scopes) |scope| { if (source_index >= scope.range.start and source_index < scope.range.end) { var decl_it = scope.decls.iterator(); while (decl_it.next()) |entry| { switch (entry.value) { .label_decl => {}, else => continue, } try callback(context, DeclWithHandle{ .decl = &entry.value, .handle = handle }); } } if (scope.range.start >= source_index) return; } } fn iterateSymbolsGlobalInternal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, handle: *DocumentStore.Handle, source_index: usize, comptime callback: anytype, context: anytype, use_trail: *std.ArrayList(*ast.Node.Use), ) error{OutOfMemory}!void { for (handle.document_scope.scopes) |scope| { if (source_index >= scope.range.start and source_index < scope.range.end) { var decl_it = scope.decls.iterator(); while (decl_it.next()) |entry| { if (entry.value == .ast_node and entry.value.ast_node.tag == .ContainerField) continue; if (entry.value == .label_decl) continue; try callback(context, DeclWithHandle{ .decl = &entry.value, .handle = handle }); } for (scope.uses) |use| { if (std.mem.indexOfScalar(*ast.Node.Use, use_trail.items, use) != null) continue; try use_trail.append(use); const use_expr = (try resolveTypeOfNode(store, arena, .{ .node = use.expr, .handle = handle })) orelse continue; const use_expr_node = switch (use_expr.type.data) { .other => |n| n, else => continue, }; try iterateSymbolsContainerInternal(store, arena, .{ .node = use_expr_node, .handle = use_expr.handle }, handle, callback, context, false, use_trail); } } if (scope.range.start >= source_index) return; } } pub fn iterateSymbolsGlobal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, handle: *DocumentStore.Handle, source_index: usize, comptime callback: anytype, context: anytype, ) error{OutOfMemory}!void { var use_trail = std.ArrayList(*ast.Node.Use).init(&arena.allocator); return try iterateSymbolsGlobalInternal(store, arena, handle, source_index, callback, context, &use_trail); } pub fn innermostContainer(handle: *DocumentStore.Handle, source_index: usize) TypeWithHandle { var current = handle.document_scope.scopes[0].data.container; if (handle.document_scope.scopes.len == 1) return TypeWithHandle.typeVal(.{ .node = current, .handle = handle }); for (handle.document_scope.scopes[1..]) |scope| { if (source_index >= scope.range.start and source_index < scope.range.end) { switch (scope.data) { .container => |node| current = node, else => {}, } } if (scope.range.start > source_index) break; } return TypeWithHandle.typeVal(.{ .node = current, .handle = handle }); } fn resolveUse( store: *DocumentStore, arena: *std.heap.ArenaAllocator, uses: []const *ast.Node.Use, symbol: []const u8, handle: *DocumentStore.Handle, use_trail: *std.ArrayList(*ast.Node.Use), ) error{OutOfMemory}!?DeclWithHandle { for (uses) |use| { if (std.mem.indexOfScalar(*ast.Node.Use, use_trail.items, use) != null) continue; try use_trail.append(use); const use_expr = (try resolveTypeOfNode(store, arena, .{ .node = use.expr, .handle = handle })) orelse continue; const use_expr_node = switch (use_expr.type.data) { .other => |n| n, else => continue, }; if (try lookupSymbolContainerInternal(store, arena, .{ .node = use_expr_node, .handle = use_expr.handle }, symbol, false, use_trail)) |candidate| { if (candidate.handle != handle and !candidate.isPublic()) { continue; } return candidate; } } return null; } pub fn lookupLabel( handle: *DocumentStore.Handle, symbol: []const u8, source_index: usize, ) error{OutOfMemory}!?DeclWithHandle { for (handle.document_scope.scopes) |scope| { if (source_index >= scope.range.start and source_index < scope.range.end) { if (scope.decls.getEntry(symbol)) |candidate| { switch (candidate.value) { .label_decl => {}, else => continue, } return DeclWithHandle{ .decl = &candidate.value, .handle = handle, }; } } if (scope.range.start > source_index) return null; } return null; } fn lookupSymbolGlobalInternal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, handle: *DocumentStore.Handle, symbol: []const u8, source_index: usize, use_trail: *std.ArrayList(*ast.Node.Use), ) error{OutOfMemory}!?DeclWithHandle { for (handle.document_scope.scopes) |scope| { if (source_index >= scope.range.start and source_index < scope.range.end) { if (scope.decls.getEntry(symbol)) |candidate| { switch (candidate.value) { .ast_node => |node| { if (node.tag == .ContainerField) continue; }, .label_decl => continue, else => {}, } return DeclWithHandle{ .decl = &candidate.value, .handle = handle, }; } if (try resolveUse(store, arena, scope.uses, symbol, handle, use_trail)) |result| return result; } if (scope.range.start > source_index) return null; } return null; } pub fn lookupSymbolGlobal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, handle: *DocumentStore.Handle, symbol: []const u8, source_index: usize, ) error{OutOfMemory}!?DeclWithHandle { var use_trail = std.ArrayList(*ast.Node.Use).init(&arena.allocator); return try lookupSymbolGlobalInternal(store, arena, handle, symbol, source_index, &use_trail); } fn lookupSymbolContainerInternal( store: *DocumentStore, arena: *std.heap.ArenaAllocator, container_handle: NodeWithHandle, symbol: []const u8, /// If true, we are looking up the symbol like we are accessing through a field access /// of an instance of the type, otherwise as a field access of the type value itself. instance_access: bool, use_trail: *std.ArrayList(*ast.Node.Use), ) error{OutOfMemory}!?DeclWithHandle { const container = container_handle.node; const handle = container_handle.handle; const is_enum = if (container.castTag(.ContainerDecl)) |cont_decl| handle.tree.token_ids[cont_decl.kind_token] == .Keyword_enum else false; if (findContainerScope(container_handle)) |container_scope| { if (container_scope.decls.getEntry(symbol)) |candidate| { switch (candidate.value) { .ast_node => |node| { if (node.tag == .ContainerField) { if (!instance_access and !is_enum) return null; if (instance_access and is_enum) return null; } }, .label_decl => unreachable, else => {}, } return DeclWithHandle{ .decl = &candidate.value, .handle = handle }; } if (try resolveUse(store, arena, container_scope.uses, symbol, handle, use_trail)) |result| return result; return null; } return null; } pub fn lookupSymbolContainer( store: *DocumentStore, arena: *std.heap.ArenaAllocator, container_handle: NodeWithHandle, symbol: []const u8, /// If true, we are looking up the symbol like we are accessing through a field access /// of an instance of the type, otherwise as a field access of the type value itself. instance_access: bool, ) error{OutOfMemory}!?DeclWithHandle { var use_trail = std.ArrayList(*ast.Node.Use).init(&arena.allocator); return try lookupSymbolContainerInternal(store, arena, container_handle, symbol, instance_access, &use_trail); } pub const DocumentScope = struct { scopes: []Scope, error_completions: []types.CompletionItem, enum_completions: []types.CompletionItem, pub fn debugPrint(self: DocumentScope) void { for (self.scopes) |scope| { log.debug( \\-------------------------- \\Scope {}, range: [{}, {}) \\ {} usingnamespaces \\Decls: , .{ scope.data, scope.range.start, scope.range.end, scope.uses.len, }); var decl_it = scope.decls.iterator(); var idx: usize = 0; while (decl_it.next()) |name_decl| : (idx += 1) { if (idx != 0) log.debug(", ", .{}); } log.debug("{s}", .{name_decl.key}); log.debug("\n--------------------------\n", .{}); } } pub fn deinit(self: DocumentScope, allocator: *std.mem.Allocator) void { for (self.scopes) |*scope| { scope.decls.deinit(); allocator.free(scope.uses); allocator.free(scope.tests); } allocator.free(self.scopes); for (self.error_completions) |item| if (item.documentation) |doc| allocator.free(doc.value); allocator.free(self.error_completions); for (self.enum_completions) |item| if (item.documentation) |doc| allocator.free(doc.value); allocator.free(self.enum_completions); } }; pub const Scope = struct { pub const Data = union(enum) { container: *ast.Node, // .id is ContainerDecl or Root or ErrorSetDecl function: *ast.Node, // .id is FnProto block: *ast.Node, // .id is Block other, }; range: SourceRange, decls: std.StringHashMap(Declaration), tests: []const *ast.Node, uses: []const *ast.Node.Use, data: Data, }; pub fn makeDocumentScope(allocator: *std.mem.Allocator, tree: *ast.Tree) !DocumentScope { var scopes = std.ArrayListUnmanaged(Scope){}; var error_completions = std.ArrayListUnmanaged(types.CompletionItem){}; var enum_completions = std.ArrayListUnmanaged(types.CompletionItem){}; errdefer { scopes.deinit(allocator); for (error_completions.items) |item| if (item.documentation) |doc| allocator.free(doc.value); error_completions.deinit(allocator); for (enum_completions.items) |item| if (item.documentation) |doc| allocator.free(doc.value); enum_completions.deinit(allocator); } try makeScopeInternal(allocator, &scopes, &error_completions, &enum_completions, tree, &tree.root_node.base); return DocumentScope{ .scopes = scopes.toOwnedSlice(allocator), .error_completions = error_completions.toOwnedSlice(allocator), .enum_completions = enum_completions.toOwnedSlice(allocator), }; } fn nodeSourceRange(tree: *ast.Tree, node: *ast.Node) SourceRange { return SourceRange{ .start = tree.token_locs[node.firstToken()].start, .end = tree.token_locs[node.lastToken()].end, }; } // TODO Possibly collect all imports to diff them on changes // as well fn makeScopeInternal( allocator: *std.mem.Allocator, scopes: *std.ArrayListUnmanaged(Scope), error_completions: *std.ArrayListUnmanaged(types.CompletionItem), enum_completions: *std.ArrayListUnmanaged(types.CompletionItem), tree: *ast.Tree, node: *ast.Node, ) error{OutOfMemory}!void { if (node.tag == .Root or node.tag == .ContainerDecl or node.tag == .ErrorSetDecl) { const ast_decls = switch (node.tag) { .ContainerDecl => node.castTag(.ContainerDecl).?.fieldsAndDeclsConst(), .Root => node.castTag(.Root).?.declsConst(), .ErrorSetDecl => node.castTag(.ErrorSetDecl).?.declsConst(), else => unreachable, }; (try scopes.addOne(allocator)).* = .{ .range = nodeSourceRange(tree, node), .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .{ .container = node }, }; const scope_idx = scopes.items.len - 1; var uses = std.ArrayList(*ast.Node.Use).init(allocator); var tests = std.ArrayList(*ast.Node).init(allocator); errdefer { scopes.items[scope_idx].decls.deinit(); uses.deinit(); tests.deinit(); } for (ast_decls) |decl| { if (decl.castTag(.Use)) |use| { try uses.append(use); continue; } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, decl); const name = getDeclName(tree, decl) orelse continue; if (decl.tag == .TestDecl) { try tests.append(decl); continue; } if (node.tag == .ErrorSetDecl) { (try error_completions.addOne(allocator)).* = .{ .label = name, .kind = .Constant, .documentation = if (try getDocComments(allocator, tree, decl, .Markdown)) |docs| .{ .kind = .Markdown, .value = docs } else null, }; } if (decl.castTag(.ContainerField)) |field| { const empty_field = field.type_expr == null and field.value_expr == null; if (empty_field and node.tag == .Root) { continue; } if (node.castTag(.ContainerDecl)) |container| { const kind = tree.token_ids[container.kind_token]; if (empty_field and (kind == .Keyword_struct or (kind == .Keyword_union and container.init_arg_expr == .None))) { continue; } if (!std.mem.eql(u8, name, "_")) { (try enum_completions.addOne(allocator)).* = .{ .label = name, .kind = .Constant, .documentation = if (try getDocComments(allocator, tree, decl, .Markdown)) |docs| .{ .kind = .Markdown, .value = docs } else null, }; } } } if (try scopes.items[scope_idx].decls.fetchPut(name, .{ .ast_node = decl })) |existing| { // TODO Record a redefinition error. } } scopes.items[scope_idx].tests = tests.toOwnedSlice(); scopes.items[scope_idx].uses = uses.toOwnedSlice(); return; } switch (node.tag) { .FnProto => { const func = node.castTag(.FnProto).?; (try scopes.addOne(allocator)).* = .{ .range = nodeSourceRange(tree, node), .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .{ .function = node }, }; var scope_idx = scopes.items.len - 1; errdefer scopes.items[scope_idx].decls.deinit(); for (func.params()) |*param| { if (param.name_token) |name_tok| { if (try scopes.items[scope_idx].decls.fetchPut(tree.tokenSlice(name_tok), .{ .param_decl = param })) |existing| { // TODO Record a redefinition error } } } if (func.getBodyNode()) |body| { try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, body); } return; }, .TestDecl => { return try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, node.castTag(.TestDecl).?.body_node); }, .LabeledBlock => { const block = node.castTag(.LabeledBlock).?; std.debug.assert(tree.token_ids[block.label] == .Identifier); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[block.lbrace].start, .end = tree.token_locs[block.rbrace].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); try scope.decls.putNoClobber(tree.tokenSlice(block.label), .{ .label_decl = node, }); (try scopes.addOne(allocator)).* = .{ .range = nodeSourceRange(tree, node), .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .{ .block = node }, }; var scope_idx = scopes.items.len - 1; var uses = std.ArrayList(*ast.Node.Use).init(allocator); errdefer { scopes.items[scope_idx].decls.deinit(); uses.deinit(); } var child_idx: usize = 0; while (node.iterate(child_idx)) |child_node| : (child_idx += 1) { if (child_node.castTag(.Use)) |use| { try uses.append(use); continue; } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, child_node); if (child_node.castTag(.VarDecl)) |var_decl| { const name = tree.tokenSlice(var_decl.name_token); if (try scopes.items[scope_idx].decls.fetchPut(name, .{ .ast_node = child_node })) |existing| { // TODO Record a redefinition error. } } } scopes.items[scope_idx].uses = uses.toOwnedSlice(); return; }, .Block => { const block = node.castTag(.Block).?; (try scopes.addOne(allocator)).* = .{ .range = nodeSourceRange(tree, node), .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .{ .block = node }, }; var scope_idx = scopes.items.len - 1; var uses = std.ArrayList(*ast.Node.Use).init(allocator); errdefer { scopes.items[scope_idx].decls.deinit(); uses.deinit(); } var child_idx: usize = 0; while (node.iterate(child_idx)) |child_node| : (child_idx += 1) { if (child_node.castTag(.Use)) |use| { try uses.append(use); continue; } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, child_node); if (child_node.castTag(.VarDecl)) |var_decl| { const name = tree.tokenSlice(var_decl.name_token); if (try scopes.items[scope_idx].decls.fetchPut(name, .{ .ast_node = child_node })) |existing| { // TODO Record a redefinition error. } } } scopes.items[scope_idx].uses = uses.toOwnedSlice(); return; }, .Comptime => { return try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, node.castTag(.Comptime).?.expr); }, .If => { const if_node = node.castTag(.If).?; if (if_node.payload) |payload| { std.debug.assert(payload.tag == .PointerPayload); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[payload.firstToken()].start, .end = tree.token_locs[if_node.body.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); const ptr_payload = payload.castTag(.PointerPayload).?; std.debug.assert(ptr_payload.value_symbol.tag == .Identifier); const name = tree.tokenSlice(ptr_payload.value_symbol.firstToken()); try scope.decls.putNoClobber(name, .{ .pointer_payload = .{ .node = ptr_payload, .condition = if_node.condition, }, }); } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, if_node.body); if (if_node.@"else") |else_node| { if (else_node.payload) |payload| { std.debug.assert(payload.tag == .Payload); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[payload.firstToken()].start, .end = tree.token_locs[else_node.body.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); const err_payload = payload.castTag(.Payload).?; std.debug.assert(err_payload.error_symbol.tag == .Identifier); const name = tree.tokenSlice(err_payload.error_symbol.firstToken()); try scope.decls.putNoClobber(name, .{ .ast_node = payload }); } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, else_node.body); } }, .While => { const while_node = node.castTag(.While).?; if (while_node.label) |label| { std.debug.assert(tree.token_ids[label] == .Identifier); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[while_node.while_token].start, .end = tree.token_locs[while_node.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); try scope.decls.putNoClobber(tree.tokenSlice(label), .{ .label_decl = node, }); } if (while_node.payload) |payload| { std.debug.assert(payload.tag == .PointerPayload); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[payload.firstToken()].start, .end = tree.token_locs[while_node.body.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); const ptr_payload = payload.castTag(.PointerPayload).?; std.debug.assert(ptr_payload.value_symbol.tag == .Identifier); const name = tree.tokenSlice(ptr_payload.value_symbol.firstToken()); try scope.decls.putNoClobber(name, .{ .pointer_payload = .{ .node = ptr_payload, .condition = while_node.condition, }, }); } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, while_node.body); if (while_node.@"else") |else_node| { if (else_node.payload) |payload| { std.debug.assert(payload.tag == .Payload); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[payload.firstToken()].start, .end = tree.token_locs[else_node.body.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); const err_payload = payload.castTag(.Payload).?; std.debug.assert(err_payload.error_symbol.tag == .Identifier); const name = tree.tokenSlice(err_payload.error_symbol.firstToken()); try scope.decls.putNoClobber(name, .{ .ast_node = payload }); } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, else_node.body); } }, .For => { const for_node = node.castTag(.For).?; if (for_node.label) |label| { std.debug.assert(tree.token_ids[label] == .Identifier); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[for_node.for_token].start, .end = tree.token_locs[for_node.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); try scope.decls.putNoClobber(tree.tokenSlice(label), .{ .label_decl = node, }); } std.debug.assert(for_node.payload.tag == .PointerIndexPayload); const ptr_idx_payload = for_node.payload.castTag(.PointerIndexPayload).?; std.debug.assert(ptr_idx_payload.value_symbol.tag == .Identifier); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[ptr_idx_payload.firstToken()].start, .end = tree.token_locs[for_node.body.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); const value_name = tree.tokenSlice(ptr_idx_payload.value_symbol.firstToken()); try scope.decls.putNoClobber(value_name, .{ .array_payload = .{ .identifier = ptr_idx_payload.value_symbol, .array_expr = for_node.array_expr, }, }); if (ptr_idx_payload.index_symbol) |index_symbol| { std.debug.assert(index_symbol.tag == .Identifier); const index_name = tree.tokenSlice(index_symbol.firstToken()); if (try scope.decls.fetchPut(index_name, .{ .ast_node = index_symbol })) |existing| { // TODO Record a redefinition error } } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, for_node.body); if (for_node.@"else") |else_node| { std.debug.assert(else_node.payload == null); try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, else_node.body); } }, .Switch => { const switch_node = node.castTag(.Switch).?; for (switch_node.casesConst()) |case| { if (case.*.castTag(.SwitchCase)) |case_node| { if (case_node.payload) |payload| { std.debug.assert(payload.tag == .PointerPayload); var scope = try scopes.addOne(allocator); scope.* = .{ .range = .{ .start = tree.token_locs[payload.firstToken()].start, .end = tree.token_locs[case_node.expr.lastToken()].end, }, .decls = std.StringHashMap(Declaration).init(allocator), .uses = &[0]*ast.Node.Use{}, .tests = &[0]*ast.Node{}, .data = .other, }; errdefer scope.decls.deinit(); const ptr_payload = payload.castTag(.PointerPayload).?; std.debug.assert(ptr_payload.value_symbol.tag == .Identifier); const name = tree.tokenSlice(ptr_payload.value_symbol.firstToken()); try scope.decls.putNoClobber(name, .{ .switch_payload = .{ .node = ptr_payload, .switch_expr = switch_node.expr, .items = case_node.itemsConst(), }, }); } try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, case_node.expr); } } }, .VarDecl => { const var_decl = node.castTag(.VarDecl).?; if (var_decl.getTypeNode()) |type_node| { try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, type_node); } if (var_decl.getInitNode()) |init_node| { try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, init_node); } }, else => { var child_idx: usize = 0; while (node.iterate(child_idx)) |child_node| : (child_idx += 1) { try makeScopeInternal(allocator, scopes, error_completions, enum_completions, tree, child_node); } }, } }
src/analysis.zig
const std = @import("std"); const link = @import("../link.zig"); const Module = @import("../Module.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; /// Maps a name from Zig source to C. This will always give the same output for /// any given input. fn map(allocator: *std.mem.Allocator, name: []const u8) ![]const u8 { return allocator.dupe(u8, name); } fn renderType(file: *C, writer: std.ArrayList(u8).Writer, T: Type, src: usize) !void { if (T.tag() == .usize) { file.need_stddef = true; try writer.writeAll("size_t"); } else { switch (T.zigTypeTag()) { .NoReturn => { file.need_noreturn = true; try writer.writeAll("noreturn void"); }, .Void => try writer.writeAll("void"), .Int => { if (T.tag() == .u8) { file.need_stdint = true; try writer.writeAll("uint8_t"); } else { return file.fail(src, "TODO implement int types", .{}); } }, else => |e| return file.fail(src, "TODO implement type {}", .{e}), } } } fn renderFunctionSignature(file: *C, writer: std.ArrayList(u8).Writer, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; try renderType(file, writer, tv.ty.fnReturnType(), decl.src()); const name = try map(file.allocator, mem.spanZ(decl.name)); defer file.allocator.free(name); try writer.print(" {}(", .{name}); if (tv.ty.fnParamLen() == 0) try writer.writeAll("void)") else return file.fail(decl.src(), "TODO implement parameters", .{}); } pub fn generate(file: *C, decl: *Decl) !void { switch (decl.typed_value.most_recent.typed_value.ty.zigTypeTag()) { .Fn => try genFn(file, decl), .Array => try genArray(file, decl), else => |e| return file.fail(decl.src(), "TODO {}", .{e}), } } fn genArray(file: *C, decl: *Decl) !void { const tv = decl.typed_value.most_recent.typed_value; // TODO: prevent inline asm constants from being emitted const name = try map(file.allocator, mem.span(decl.name)); defer file.allocator.free(name); if (tv.val.cast(Value.Payload.Bytes)) |payload| if (tv.ty.arraySentinel()) |sentinel| if (sentinel.toUnsignedInt() == 0) try file.constants.writer().print("const char *const {} = \"{}\";\n", .{ name, payload.data }) else return file.fail(decl.src(), "TODO byte arrays with non-zero sentinels", .{}) else return file.fail(decl.src(), "TODO byte arrays without sentinels", .{}) else return file.fail(decl.src(), "TODO non-byte arrays", .{}); } fn genFn(file: *C, decl: *Decl) !void { const writer = file.main.writer(); const tv = decl.typed_value.most_recent.typed_value; try renderFunctionSignature(file, writer, decl); try writer.writeAll(" {"); const func: *Module.Fn = tv.val.cast(Value.Payload.Function).?.func; const instructions = func.analysis.success.instructions; if (instructions.len > 0) { for (instructions) |inst| { try writer.writeAll("\n\t"); switch (inst.tag) { .assembly => try genAsm(file, inst.castTag(.assembly).?, decl), .call => try genCall(file, inst.castTag(.call).?, decl), .ret => try genRet(file, inst.castTag(.ret).?, decl, tv.ty.fnReturnType()), .retvoid => try file.main.writer().print("return;", .{}), else => |e| return file.fail(decl.src(), "TODO implement C codegen for {}", .{e}), } } try writer.writeAll("\n"); } try writer.writeAll("}\n\n"); } fn genRet(file: *C, inst: *Inst.UnOp, decl: *Decl, expected_return_type: Type) !void { const writer = file.main.writer(); const ret_value = inst.operand; const value = ret_value.value().?; if (expected_return_type.eql(ret_value.ty)) return file.fail(decl.src(), "TODO return {}", .{expected_return_type}) else if (expected_return_type.isInt() and ret_value.ty.tag() == .comptime_int) if (value.intFitsInType(expected_return_type, file.options.target)) if (expected_return_type.intInfo(file.options.target).bits <= 64) try writer.print("return {};", .{value.toUnsignedInt()}) else return file.fail(decl.src(), "TODO return ints > 64 bits", .{}) else return file.fail(decl.src(), "comptime int {} does not fit in {}", .{ value.toUnsignedInt(), expected_return_type }) else return file.fail(decl.src(), "return type mismatch: expected {}, found {}", .{ expected_return_type, ret_value.ty }); } fn genCall(file: *C, inst: *Inst.Call, decl: *Decl) !void { const writer = file.main.writer(); const header = file.header.writer(); if (inst.func.castTag(.constant)) |func_inst| { if (func_inst.val.cast(Value.Payload.Function)) |func_val| { const target = func_val.func.owner_decl; const target_ty = target.typed_value.most_recent.typed_value.ty; const ret_ty = target_ty.fnReturnType().tag(); if (target_ty.fnReturnType().hasCodeGenBits() and inst.base.isUnused()) { try writer.print("(void)", .{}); } const tname = mem.spanZ(target.name); if (file.called.get(tname) == null) { try file.called.put(tname, void{}); try renderFunctionSignature(file, header, target); try header.writeAll(";\n"); } try writer.print("{}();", .{tname}); } else { return file.fail(decl.src(), "TODO non-function call target?", .{}); } if (inst.args.len != 0) { return file.fail(decl.src(), "TODO function arguments", .{}); } } else { return file.fail(decl.src(), "TODO non-constant call inst?", .{}); } } fn genAsm(file: *C, as: *Inst.Assembly, decl: *Decl) !void { 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]; if (arg.castTag(.constant)) |c| { if (c.val.tag() == .int_u64) { try writer.writeAll("register "); try renderType(file, writer, arg.ty, decl.src()); try writer.print(" {}_constant __asm__(\"{}\") = {};\n\t", .{ reg, reg, c.val.toUnsignedInt() }); } else { return file.fail(decl.src(), "TODO inline asm {} args", .{c.val.tag()}); } } else { return file.fail(decl.src(), "TODO non-constant inline asm args", .{}); } } else { return file.fail(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 file.fail(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(", "); } if (arg.castTag(.constant)) |c| { try writer.print("\"\"({}_constant)", .{reg}); } else { // This is blocked by the earlier test unreachable; } } else { // This is blocked by the earlier test unreachable; } } } try writer.writeAll(");"); }
src-self-hosted/codegen/c.zig
const kernel = @import("kernel.zig"); const TODO = kernel.TODO; const log = kernel.log.scoped(.Scheduler); const Virtual = kernel.Virtual; pub const Context = kernel.arch.Context; pub fn new_fn() noreturn { while (true) { log.debug("new process", .{}); } } pub var lock: kernel.arch.Spinlock = undefined; var thread_pool: [8192]Thread = undefined; var thread_id: u64 = 0; pub fn yield(context: *Context) noreturn { const current_cpu = kernel.arch.get_current_cpu().?; if (current_cpu.spinlock_count > 0) { @panic("spins active when yielding"); } kernel.arch.disable_interrupts(); lock.acquire(); var old_address_space: *kernel.Virtual.AddressSpace = undefined; if (lock.were_interrupts_enabled) @panic("ffff"); if (current_cpu.current_thread) |current_thread| { current_thread.context = context; old_address_space = current_thread.address_space; } else { old_address_space = &kernel.address_space; } const new_thread = pick_thread(); new_thread.time_slices += 1; // TODO: idle //log.debug("RSP: 0x{x}", .{context.rsp}); //log.debug("Stack top: 0x{x}", .{new_thread.kernel_stack_base.value + new_thread.kernel_stack_size}); //kernel.assert(@src(), context.rsp < new_thread.kernel_stack_base.value + new_thread.kernel_stack_size); //kernel.arch.next_timer(1); kernel.arch.switch_context(new_thread.context, new_thread.address_space, new_thread.kernel_stack.value, new_thread, old_address_space); } pub const Thread = struct { privilege_level: PrivilegeLevel, type: Type, kernel_stack: Virtual.Address, kernel_stack_base: Virtual.Address, kernel_stack_size: u64, user_stack_base: Virtual.Address, user_stack_reserve: u64, user_stack_commit: u64, id: u64, context: *kernel.arch.Context, time_slices: u64, last_known_execution_address: u64, address_space: *Virtual.AddressSpace, const PrivilegeLevel = enum(u1) { kernel = 0, user = 1, }; // TODO: idle thread const Type = enum(u1) { normal = 0, idle = 1, }; pub const EntryPoint = struct { start_address: u64, argument: u64, }; pub fn spawn(privilege_level: PrivilegeLevel, entry_point: EntryPoint) *Thread { // TODO: lock const new_thread_id = thread_id; const thread_index = new_thread_id % thread_pool.len; var thread = &thread_pool[thread_index]; thread_id += 1; log.debug("here", .{}); // TODO: should we always use the same address space for kernel tasks? thread.address_space = switch (privilege_level) { .kernel => &kernel.address_space, .user => Virtual.AddressSpace.new_for_user() orelse unreachable, }; var kernel_stack_size: u64 = 0x5000; const user_stack_reserve: u64 = switch (privilege_level) { .kernel => kernel_stack_size, .user => 0x400000, }; const user_stack_commit: u64 = switch (privilege_level) { .kernel => 0, .user => 0x10000, }; var user_stack: Virtual.Address = undefined; // TODO: implemented idle thread const kernel_stack = kernel.address_space.allocate(kernel_stack_size) orelse @panic("unable to allocate the kernel stack"); log.debug("Kernel stack: 0x{x}", .{kernel_stack.value}); user_stack = switch (privilege_level) { .kernel => kernel_stack, .user => blk: { // TODO: lock const user_stack_physical_address = kernel.Physical.Memory.allocate_pages(kernel.bytes_to_pages(user_stack_reserve, true)) orelse unreachable; const user_stack_physical_region = kernel.Physical.Memory.Region.new(user_stack_physical_address, user_stack_reserve); const user_stack_base_virtual_address = kernel.Virtual.Address.new(0x5000_0000_0000); user_stack_physical_region.map(thread.address_space, user_stack_base_virtual_address, kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .read_write, .user })); break :blk user_stack_base_virtual_address; }, }; thread.privilege_level = privilege_level; log.debug("Thread privilege: {}", .{thread.privilege_level}); thread.kernel_stack_base = kernel_stack; thread.kernel_stack_size = kernel_stack_size; thread.user_stack_base = switch (privilege_level) { .kernel => Virtual.Address.new(0), .user => user_stack, }; log.debug("USB: 0x{x}", .{thread.user_stack_base.value}); thread.user_stack_reserve = user_stack_reserve; thread.user_stack_commit = user_stack_commit; thread.id = new_thread_id; thread.type = .normal; kernel.assert(@src(), thread.type == .normal); if (thread.type != .idle) { log.debug("Creating arch-specific thread initialization", .{}); // TODO: hack thread.context = switch (privilege_level) { .kernel => kernel.arch.Context.new(thread, entry_point), .user => blk: { var kernel_entry_point_virtual_address_page = Virtual.Address.new(entry_point.start_address); kernel_entry_point_virtual_address_page.page_align_backward(); const offset = entry_point.start_address - kernel_entry_point_virtual_address_page.value; log.debug("Offset: 0x{x}", .{offset}); const entry_point_physical_address_page = kernel.address_space.translate_address(kernel_entry_point_virtual_address_page) orelse @panic("unable to retrieve pa"); const user_entry_point_virtual_address_page = kernel.Virtual.Address.new(0x6000_0000_0000); thread.address_space.map(entry_point_physical_address_page, user_entry_point_virtual_address_page, kernel.Virtual.AddressSpace.Flags.from_flags(&.{ .user, .read_write })); const user_entry_point_virtual_address = kernel.Virtual.Address.new(user_entry_point_virtual_address_page.value + offset); break :blk kernel.arch.Context.new(thread, EntryPoint{ .start_address = user_entry_point_virtual_address.value, .argument = entry_point.argument, }); }, }; } return thread; } pub fn terminate(thread: *Thread) void { _ = thread; TODO(@src()); } }; fn pick_thread() *Thread { const current_cpu = kernel.arch.get_current_cpu().?; const current_thread_id = if (current_cpu.current_thread) |current_thread| current_thread.id else 0; kernel.assert(@src(), current_thread_id < thread_id); //const next_thread_index = kernel.arch.read_timestamp() % thread_id; const next_thread_index = 0; const new_thread = &thread_pool[next_thread_index]; return new_thread; } fn user_space() callconv(.Naked) noreturn { asm volatile ("mov $0x43, %%rax"); asm volatile ("mov %%rax, %%gs"); asm volatile ("mov %%gs, %%rdi"); asm volatile ("syscall"); unreachable; } fn test_thread(arg: u64) void { while (true) { log.debug("THREAD {}", .{arg}); } } pub fn test_threads(thread_count: u64) void { var thread_i: u64 = 0; while (thread_i < thread_count) : (thread_i += 1) { _ = Thread.spawn(.kernel, Thread.EntryPoint{ .start_address = @ptrToInt(test_thread), .argument = thread_i, }); } } pub fn test_userspace() void { _ = Thread.spawn(.user, Thread.EntryPoint{ .start_address = @ptrToInt(user_space), .argument = 2, }); } pub fn init() void { //test_threads(1); test_userspace(); }
src/kernel/scheduler.zig
const std = @import("../index.zig"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const mem = std.mem; pub fn InStream(comptime ReadError: type) type { return struct.{ const Self = @This(); pub const Error = ReadError; /// Return the number of bytes read. It may be less than buffer.len. /// If the number of bytes read is 0, it means end of stream. /// End of stream is not an error condition. readFn: async<*Allocator> fn (self: *Self, buffer: []u8) Error!usize, /// Return the number of bytes read. It may be less than buffer.len. /// If the number of bytes read is 0, it means end of stream. /// End of stream is not an error condition. pub async fn read(self: *Self, buffer: []u8) !usize { return await (async self.readFn(self, buffer) catch unreachable); } /// Return the number of bytes read. If it is less than buffer.len /// it means end of stream. pub async fn readFull(self: *Self, buffer: []u8) !usize { var index: usize = 0; while (index != buf.len) { const amt_read = try await (async self.read(buf[index..]) catch unreachable); if (amt_read == 0) return index; index += amt_read; } return index; } /// Same as `readFull` but end of stream returns `error.EndOfStream`. pub async fn readNoEof(self: *Self, buf: []u8) !void { const amt_read = try await (async self.readFull(buf[index..]) catch unreachable); if (amt_read < buf.len) return error.EndOfStream; } pub async fn readIntLe(self: *Self, comptime T: type) !T { return await (async self.readInt(builtin.Endian.Little, T) catch unreachable); } pub async fn readIntBe(self: *Self, comptime T: type) !T { return await (async self.readInt(builtin.Endian.Big, T) catch unreachable); } pub async fn readInt(self: *Self, endian: builtin.Endian, comptime T: type) !T { var bytes: [@sizeOf(T)]u8 = undefined; try await (async self.readNoEof(bytes[0..]) catch unreachable); return mem.readInt(bytes, T, endian); } pub async fn readStruct(self: *Self, comptime T: type, ptr: *T) !void { // Only extern and packed structs have defined in-memory layout. comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto); return await (async self.readNoEof(@sliceToBytes((*[1]T)(ptr)[0..])) catch unreachable); } }; } pub fn OutStream(comptime WriteError: type) type { return struct.{ const Self = @This(); pub const Error = WriteError; writeFn: async<*Allocator> fn (self: *Self, buffer: []u8) Error!void, }; }
std/event/io.zig
const std = @import("std"); const list_tests = @import("list_tests.zig"); const heap = std.heap; const mem = std.mem; const CustomList = @import("list.zig").CustomList; const testList = list_tests.testList; // How to fuzz 101: // You have made changes to the list and want to fuzz it? Firstm run the // fuzzer in release-safe mode: // `zig test src/imut_test.zig --release-safe` // // We run in release fast, because fuzzing will take a while otherwise. If // If this test pass, then you've made changes without breaking the list // implementation. // If a failure occured, you have a couple of options depending on the // failure. // // # The test failed // If the fuzz test failed, then it should automatically print the test // case that broke. Just copy that test case into "list_testsz.zig", // ensure that is passes and then run the fuzzer again. // // # Segfault or other unexpected exits // If the implementation segfaults, then a test case wont be printed // automatically. You'll have to play around with some of the option // varibles in the fuzz test itself. // * If it crases imidiatly, then you can set `print_only_on_failure` to // `false`. This will make the fuzzer print all test cases during execution. // Just wait for it to finish and copy up to the start of the last test // block into this file (the test cases might not have been printed // completely. Just fix any syntax errors when you paste). If your terminal // emulator prints test cases two slowly, consider piping the test // cases to a file (`zig test src/imut_test.zig --release-fast >dump`) // * If crashing takes a while, then printing all test cases won't be an // option. In this case, try ajusting `fuzz_iterations`, `node_sizes`, // `max_slice_sizes` and `max_actions` to be smaller, so that you can // hit your failing test case faster. You can also try setting // `print_params` to `true`. This will only print the parameters passed // to the `fuzz` funtion. When you then hit you test case, just // go back, and run `fuzz` only with the parameters printed last. test "fuzz" { // Set this to false and each fuzz test will be printed to stdout // regardless of wether the test passed or not. This is useful when // a test case segfaults. const print_only_on_failure = true; // This will print the parameters sent to fuzz const print_params = false; // The number of fuzz tests to be run for each configurations. // Each iteration is its own seed. const fuzz_iterations = 25; // The node sizes to test const node_sizes = [_]usize{ 2, 3, 4, 8, 16, 32, 64, 128 }; // The maximum size of slices generated during fuzzing const max_slice_sizes = [_]usize{ 2, 8, 32, 128, 512, 2048, 4096 * 2 }; // The maximum number of actions generated const max_actions = [_]usize{ 2, 4, 8, 16, 32, 64, 128 }; const seeder = &std.rand.DefaultPrng.init(0).random; const alloc_buf = try heap.direct_allocator.alloc(u8, 1024 * 1024 * 512); defer heap.direct_allocator.free(alloc_buf); var buf: [1024 * 1024 * 2]u8 = undefined; const stdout = try std.io.getStdOut(); for (max_actions) |max_act| { for (max_slice_sizes) |max_slice_size| { inline for (node_sizes) |node_size| { var fuzz_i: usize = 0; while (fuzz_i < fuzz_iterations) : (fuzz_i += 1) { const allocator = &heap.FixedBufferAllocator.init(alloc_buf).allocator; var sos = std.io.SliceOutStream.init(&buf); const stream = if (print_only_on_failure) &sos.stream else &stdout.outStream().stream; const seed = seeder.int(usize); if (print_params) debug.warn("{} {} {} {}\n", node_size, max_slice_size, max_act, seed); fuzz(allocator, node_size, max_slice_size, max_act, seed, stream) catch |err| { try stdout.write("\n"); try stdout.write(sos.getWritten()); return err; }; } } } } } const Action = union(enum) { FromSlice: []const u8, Append: u8, AppendSlice: []const u8, AppendList, Insert: Insert, InsertSlice: InsertSlice, //InsertList: usize, Remove: usize, RemoveItems: RemoveItems, Slice: Slice, const Insert = struct { index: usize, item: u8, }; const InsertSlice = struct { index: usize, items: []const u8, }; const RemoveItems = struct { i: usize, len: usize, }; const Slice = struct { start: usize, end: usize, }; }; fn randSlice(allocator: *mem.Allocator, max: usize, rand: *std.rand.Random) ![]const u8 { const len = rand.uintLessThanBiased(usize, max + 1); const res = try allocator.alloc(u8, len); for (res) |*item| { item.* = rand.intRangeLessThanBiased(u8, 'a', 'z' + 1); } return res; } fn createActions(allocator: *mem.Allocator, max_slice_size: usize, max_actions: usize, seed: usize) ![]const Action { const rand = &std.rand.DefaultPrng.init(seed).random; const len = rand.intRangeLessThanBiased(usize, 1, max_actions + 1); const res = try allocator.alloc(Action, len); var curr_len: usize = 0; for (res) |*action| { try_again: while (true) { const Enum = @TagType(Action); const Tag = @TagType(Enum); const enum_info = @typeInfo(Enum); const kind_int = rand.uintLessThanBiased(usize, enum_info.Enum.fields.len); switch (@intToEnum(Enum, @intCast(Tag, kind_int))) { .FromSlice => { const items = try randSlice(allocator, max_slice_size, rand); action.* = Action{ .FromSlice = items, }; curr_len = items.len; }, .Append => { action.* = Action{ .Append = rand.intRangeLessThanBiased(u8, 'a', 'z' + 1), }; curr_len += 1; }, .AppendSlice => { const items = try randSlice(allocator, max_slice_size, rand); action.* = Action{ .AppendSlice = items, }; curr_len += items.len; }, .AppendList => { action.* = Action.AppendList; curr_len += curr_len; }, .Insert => { action.* = Action{ .Insert = Action.Insert{ .index = rand.uintLessThanBiased(usize, curr_len + 1), .item = rand.intRangeLessThanBiased(u8, 'a', 'z' + 1), }, }; curr_len += 1; }, .InsertSlice => { const items = try randSlice(allocator, max_slice_size, rand); action.* = Action{ .InsertSlice = Action.InsertSlice{ .index = rand.uintLessThanBiased(usize, curr_len + 1), .items = items, }, }; curr_len += items.len; }, //.InsertList => { // action.* = Action{ // .InsertList = rand.uintLessThanBiased(usize, curr_len + 1), // }; // curr_len += curr_len; //}, .Remove => { if (curr_len == 0) continue :try_again; action.* = Action{ .Remove = rand.uintLessThanBiased(usize, curr_len), }; curr_len -= 1; }, .RemoveItems => { if (curr_len == 0) continue :try_again; const i = rand.uintLessThanBiased(usize, curr_len); const l = rand.intRangeLessThanBiased(usize, i, curr_len + 1) - i; action.* = Action{ .RemoveItems = Action.RemoveItems{ .i = i, .len = l, }, }; curr_len -= l; }, .Slice => { const start = rand.uintLessThanBiased(usize, curr_len + 1); const end = rand.intRangeLessThanBiased(usize, start, curr_len + 1); action.* = Action{ .Slice = Action.Slice{ .start = start, .end = end, }, }; curr_len = end - start; }, } break; } } return res; } fn fuzz(allocator: *mem.Allocator, comptime node_size: usize, max_slice_size: usize, max_actions: usize, seed: usize, stream: var) !void { const actions = try createActions(allocator, max_slice_size, max_actions, seed); var l = CustomList(u8, node_size){ .allocator = allocator }; var cmp = std.ArrayList(u8).init(allocator); try stream.print("test \"fuzz case {}-{}-{}-{}\" {{\n", node_size, max_slice_size, max_actions, seed); defer stream.print("}}\n\n") catch {}; try stream.print(" var buf: [1024 * 1024 * 5]u8 = undefined;\n"); try stream.print(" const allocator = &heap.FixedBufferAllocator.init(&buf).allocator;\n"); try stream.print(" var l = CustomList(u8, {}){{ .allocator = allocator }};\n", node_size); try stream.print(" var cmp = std.ArrayList(u8).init(allocator);\n\n"); for (actions) |action| { switch (action) { .FromSlice => |items| { try stream.print(" l = try CustomList(u8, {}).fromSlice(allocator, \"{}\");\n", node_size, items); try stream.print(" try cmp.resize(0);\n"); try stream.print(" try cmp.appendSlice(\"{}\");\n", items); l = try CustomList(u8, node_size).fromSlice(allocator, items); try cmp.resize(0); try cmp.appendSlice(items); }, .Append => |item| { try stream.print(" l = try l.append('{c}');\n", item); try stream.print(" try cmp.append('{c}');\n", item); l = try l.append(item); try cmp.append(item); }, .AppendSlice => |items| { try stream.print(" l = try l.appendSlice(\"{}\");\n", items); try stream.print(" try cmp.appendSlice(\"{}\");\n", items); l = try l.appendSlice(items); try cmp.appendSlice(items); }, .AppendList => { try stream.print(" l = try l.appendList(l);\n"); try stream.print(" try cmp.appendSlice(cmp.items);\n"); l = try l.appendList(l); try cmp.appendSlice(cmp.items); }, .Insert => |insert| { try stream.print(" l = try l.insert({}, '{c}');\n", insert.index, insert.item); try stream.print(" try cmp.insert({}, '{c}');\n", insert.index, insert.item); l = try l.insert(insert.index, insert.item); try cmp.insert(insert.index, insert.item); }, .InsertSlice => |insert| { try stream.print(" l = try l.insertSlice({}, \"{}\");\n", insert.index, insert.items); try stream.print(" try cmp.insertSlice({}, \"{}\");\n", insert.index, insert.items); l = try l.insertSlice(insert.index, insert.items); try cmp.insertSlice(insert.index, insert.items); }, //.InsertList => |index| { // l = try l.insertList(index, l); // try cmp.insertSlice(index, cmp.items); //}, .Remove => |remove| { try stream.print(" l = try l.remove({});\n", remove); try stream.print(" _ = cmp.orderedRemove({});\n", remove); l = try l.remove(remove); _ = cmp.orderedRemove(remove); }, .RemoveItems => |remove| { try stream.print(" l = try l.removeItems({}, {});\n", remove.i, remove.len); try stream.print(" {{"); try stream.print(" const slice = cmp.toOwnedSlice();"); try stream.print(" const first = slice[0..{}];", remove.i); try stream.print(" const last = slice[{}..];", remove.i + remove.len); try stream.print(" try cmp.appendSlice(first);"); try stream.print(" try cmp.appendSlice(last);"); try stream.print(" }}"); l = try l.removeItems(remove.i, remove.len); const slice = cmp.toOwnedSlice(); const first = slice[0..remove.i]; const last = slice[remove.i + remove.len ..]; try cmp.appendSlice(first); try cmp.appendSlice(last); }, .Slice => |slice| { try stream.print(" l = try l.slice({}, {});\n", slice.start, slice.end); try stream.print(" try cmp.appendSlice(cmp.toOwnedSlice()[{}..{}]);\n", slice.start, slice.end); l = try l.slice(slice.start, slice.end); try cmp.appendSlice(cmp.toOwnedSlice()[slice.start..slice.end]); }, } try stream.print(" try testList(l, cmp.items);\n\n"); try testList(l, cmp.items); } }
src/core/list_fuzz.zig
const std = @import("std"); const gpa = std.heap.c_allocator; const zuri = @import("zuri"); const iguanatls = @import("iguanatls"); const u = @import("./../util/index.zig"); // // pub const Zpm = struct { pub const Package = struct { author: []const u8, name: []const u8, tags: [][]const u8, git: []const u8, root_file: ?[]const u8, description: []const u8, }; }; pub fn execute(args: [][]u8) !void { const url = try zuri.Uri.parse("https://zpm.random-projects.net:443/api/packages", true); const sock = try std.net.tcpConnectToHost(gpa, url.host.name, url.port.?); defer sock.close(); var client = try iguanatls.client_connect(.{ .reader = sock.reader(), .writer = sock.writer(), .cert_verifier = .none, .temp_allocator = gpa, .ciphersuites = iguanatls.ciphersuites.all, }, url.host.name); defer client.close_notify() catch {}; const w = client.writer(); try w.print("GET {s} HTTP/1.1\r\n", .{url.path}); try w.print("Host: {s}:{}\r\n", .{url.host.name, url.port.?}); try w.writeAll("Accept: application/json; charset=UTF-8\r\n"); try w.writeAll("Connection: close\r\n"); try w.writeAll("\r\n"); const r = client.reader(); var buf: [1]u8 = undefined; const data = &std.ArrayList(u8).init(gpa); while (true) { const len = try r.read(&buf); if (len == 0) { break; } try data.appendSlice(buf[0..len]); } const index = std.mem.indexOf(u8, data.items, "\r\n\r\n").?; const html_contents = data.items[index..]; var stream = std.json.TokenStream.init(html_contents[4..]); const res = try std.json.parse([]Zpm.Package, &stream, .{ .allocator = gpa, }); const found = blk: { for (res) |pkg| { if (std.mem.eql(u8, pkg.name, args[0])) { break :blk pkg; } } u.assert(false, "no package with name '{s}' found", .{args[0]}); unreachable; }; u.assert(found.root_file != null, "package must have an entry point to be able to be added to your dependencies", .{}); const self_module = try u.ModFile.init(gpa, "zig.mod"); for (self_module.deps) |dep| { if (std.mem.eql(u8, dep.name, found.name)) { u.assert(false, "dependency with name '{s}' already exists in your dependencies", .{found.name}); } } const file = try std.fs.cwd().openFile("zig.mod", .{ .read=true, .write=true }); try file.seekTo(try file.getEndPos()); const file_w = file.writer(); try file_w.print("\n", .{}); try file_w.print(" - src: git {s}\n", .{found.git}); try file_w.print(" name: {s}\n", .{found.name}); try file_w.print(" main: {s}\n", .{found.root_file.?[1..]}); std.log.info("Successfully added package {s} by {s}", .{found.name, found.author}); }
src/cmd/zpm_add.zig
const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64); const inf128 = @bitCast(f128, @as(u128, 0x7fff000000000000) << 64); const __multf3 = @import("mulXf3.zig").__multf3; // return true if equal // use two 64-bit integers intead of one 128-bit integer // because 128-bit integer constant can't be assigned directly fn compareResultLD(result: f128, expectedHi: u64, expectedLo: u64) bool { const rep = @bitCast(u128, result); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expectedHi and lo == expectedLo) { return true; } // test other possible NaN representation(signal NaN) if (expectedHi == 0x7fff800000000000 and expectedLo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return true; } } return false; } fn test__multf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void { const x = __multf3(a, b); if (compareResultLD(x, expected_hi, expected_lo)) return; @panic("__multf3 test failure"); } fn makeNaN128(rand: u64) f128 { const int_result = @as(u128, 0x7fff000000000000 | (rand & 0xffffffffffff)) << 64; const float_result = @bitCast(f128, int_result); return float_result; } test "multf3" { // qNaN * any = qNaN try test__multf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN * any = NaN const a = makeNaN128(0x800030000000); try test__multf3(a, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf * any = inf try test__multf3(inf128, 0x1.23456789abcdefp+5, 0x7fff000000000000, 0x0); // any * any try test__multf3( @bitCast(f128, @as(u128, 0x40042eab345678439abcdefea5678234)), @bitCast(f128, @as(u128, 0x3ffeedcb34a235253948765432134675)), 0x400423e7f9e3c9fc, 0xd906c2c2a85777c4, ); try test__multf3( @bitCast(f128, @as(u128, 0x3fcd353e45674d89abacc3a2ebf3ff50)), @bitCast(f128, @as(u128, 0x3ff6ed8764648369535adf4be3214568)), 0x3fc52a163c6223fc, 0xc94c4bf0430768b4, ); try test__multf3( 0x1.234425696abcad34a35eeffefdcbap+456, 0x451.ed98d76e5d46e5f24323dff21ffp+600, 0x44293a91de5e0e94, 0xe8ed17cc2cdf64ac, ); try test__multf3( @bitCast(f128, @as(u128, 0x3f154356473c82a9fabf2d22ace345df)), @bitCast(f128, @as(u128, 0x3e38eda98765476743ab21da23d45679)), 0x3d4f37c1a3137cae, 0xfc6807048bc2836a, ); try test__multf3(0x1.23456734245345p-10000, 0x1.edcba524498724p-6497, 0x0, 0x0); // Denormal operands. try test__multf3( 0x0.0000000000000000000000000001p-16382, 0x1.p16383, 0x3f90000000000000, 0x0, ); try test__multf3( 0x1.p16383, 0x0.0000000000000000000000000001p-16382, 0x3f90000000000000, 0x0, ); }
lib/std/special/compiler_rt/mulXf3_test.zig
const std = @import("std"); const string = []const u8; const builtin = @import("builtin"); const zigmod = @import("../lib.zig"); const u = @import("index.zig"); const yaml = @import("./yaml.zig"); const common = @import("./../common.zig"); // // pub const Module = struct { alloc: std.mem.Allocator, is_sys_lib: bool, id: string, name: string, main: string, c_include_dirs: []const string = &.{}, c_source_flags: []const string = &.{}, c_source_files: []const string = &.{}, only_os: []const string = &.{}, except_os: []const string = &.{}, yaml: ?yaml.Mapping, deps: []Module, clean_path: string, dep: ?zigmod.Dep, for_build: bool = false, pub fn from(alloc: std.mem.Allocator, dep: zigmod.Dep, modpath: string, options: *common.CollectOptions) !Module { var moddeps = std.ArrayList(Module).init(alloc); defer moddeps.deinit(); for (dep.deps) |*d| { if (try common.get_module_from_dep(d, modpath, options)) |founddep| { try moddeps.append(founddep); } } return Module{ .alloc = alloc, .is_sys_lib = false, .id = if (dep.id.len > 0) dep.id else try u.random_string(alloc, 48), .name = dep.name, .main = dep.main, .c_include_dirs = dep.c_include_dirs, .c_source_flags = dep.c_source_flags, .c_source_files = dep.c_source_files, .deps = moddeps.toOwnedSlice(), .clean_path = try dep.clean_path(), .only_os = dep.only_os, .except_os = dep.except_os, .yaml = dep.yaml, .dep = dep, .for_build = dep.for_build, }; } pub fn eql(self: Module, another: Module) bool { return std.mem.eql(u8, self.id, another.id); } pub fn get_hash(self: Module, cdpath: string) !string { const file_list_1 = try u.file_list(self.alloc, try std.mem.concat(self.alloc, u8, &.{ cdpath, "/", self.clean_path })); var file_list_2 = std.ArrayList(string).init(self.alloc); defer file_list_2.deinit(); for (file_list_1) |item| { const _a = u.trim_prefix(item, cdpath); const _b = u.trim_prefix(_a, self.clean_path); if (_b[0] == '.') continue; try file_list_2.append(_b); } std.sort.sort(string, file_list_2.items, void{}, struct { pub fn lt(context: void, lhs: string, rhs: string) bool { _ = context; return std.mem.lessThan(u8, lhs, rhs); } }.lt); const h = &std.crypto.hash.Blake3.init(.{}); for (file_list_2.items) |item| { const abs_path = try std.fs.path.join(self.alloc, &.{ cdpath, self.clean_path, item }); const file = try std.fs.cwd().openFile(abs_path, .{}); defer file.close(); const input = try file.reader().readAllAlloc(self.alloc, u.mb * 100); h.update(input); } var out: [32]u8 = undefined; h.final(&out); const hex = try std.fmt.allocPrint(self.alloc, "blake3-{x}", .{std.fmt.fmtSliceHexLower(out[0..])}); return hex; } pub fn is_for_this(self: Module) bool { const os = @tagName(builtin.os.tag); if (self.only_os.len > 0) { return u.list_contains(self.only_os, os); } if (self.except_os.len > 0) { return !u.list_contains(self.except_os, os); } return true; } pub fn has_no_zig_deps(self: Module) bool { for (self.deps) |d| { if (d.main.len > 0) { return false; } } return true; } pub fn has_syslib_deps(self: Module) bool { for (self.deps) |d| { if (d.is_sys_lib) { return true; } } return false; } pub fn has_vcpkg_deps(self: Module) bool { for (self.deps) |d| { const dd = d.dep orelse continue; if (dd.vcpkg) { return true; } } return false; } pub fn short_id(self: Module) string { return u.slice(u8, self.id, 0, 12); } };
src/util/module.zig
const std = @import("std"); /// Processes are run by the Scheduler. They use a similar pattern to Allocators in that they are created and /// added as fields in a parent struct, your actual process that will be run. pub const Process = struct { const State = enum(u8) { uninitialized, running, paused, succeeded, failed, aborted, finished }; updateFn: fn (self: *Process) void, startFn: ?fn (self: *Process) void = null, abortedFn: ?fn (self: *Process) void = null, failedFn: ?fn (self: *Process) void = null, succeededFn: ?fn (self: *Process) void = null, deinit: fn (self: *Process, allocator: std.mem.Allocator) void = undefined, state: State = .uninitialized, stopped: bool = false, next: ?*Process = null, pub fn getParent(self: *Process, comptime T: type) *T { return @fieldParentPtr(T, "process", self); } /// Terminates a process with success if it's still alive pub fn succeed(self: *Process) void { if (self.alive()) self.state = .succeeded; } /// Terminates a process with errors if it's still alive pub fn fail(self: *Process) void { if (self.alive()) self.state = .failed; } /// Stops a process if it's in a running state pub fn pause(self: *Process) void { if (self.state == .running) self.state = .paused; } /// Restarts a process if it's paused pub fn unpause(self: *Process) void { if (self.state == .paused) self.state = .running; } /// Aborts a process if it's still alive pub fn abort(self: *Process, immediately: bool) void { if (self.alive()) { self.state = .aborted; if (immediately) { self.tick(); } } } /// Returns true if a process is either running or paused pub fn alive(self: Process) bool { return self.state == .running or self.state == .paused; } /// Returns true if a process is already terminated pub fn dead(self: Process) bool { return self.state == .finished; } pub fn rejected(self: Process) bool { return self.stopped; } /// Updates a process and its internal state pub fn tick(self: *Process) void { switch (self.state) { .uninitialized => { if (self.startFn) |func| func(self); self.state = .running; }, .running => { self.updateFn(self); }, else => {}, } // if it's dead, it must be notified and removed immediately switch (self.state) { .succeeded => { if (self.succeededFn) |func| func(self); self.state = .finished; }, .failed => { if (self.failedFn) |func| func(self); self.state = .finished; self.stopped = true; }, .aborted => { if (self.abortedFn) |func| func(self); self.state = .finished; self.stopped = true; }, else => {}, } } };
src/process/process.zig
const std = @import("std"); const assert = std.debug.assert; const Computer = @import("./computer.zig").Computer; pub const Network = struct { const SIZE: usize = 50; pub const NAT = struct { xcur: i64, ycur: i64, xprv: i64, yprv: i64, count: usize, pub fn init() NAT { var self = NAT{ .xcur = -2, .ycur = -2, .xprv = -1, .yprv = -1, .count = 0, }; return self; } }; computers: [SIZE]Computer, nat: NAT, pub fn init(prg: []const u8) Network { var self = Network{ .computers = undefined, .nat = NAT.init(), }; std.debug.warn("Initializing network of {} computers...\n", .{SIZE}); var j: usize = 0; while (j < SIZE) : (j += 1) { self.computers[j] = Computer.init(true); self.computers[j].parse(prg); } return self; } pub fn deinit(self: *Network) void { var j: usize = 0; while (j < SIZE) : (j += 1) { self.computers[j].deinit(); } } pub fn run(self: *Network, once: bool) i64 { std.debug.warn("Running network of {} computers...\n", .{SIZE}); var j: usize = 0; j = 0; while (j < SIZE) : (j += 1) { self.computers[j].clear(); const input = @intCast(i64, j); // std.debug.warn("C {} enqueue {}\n",.{ j, input}); self.computers[j].enqueueInput(input); } var result: i64 = 0; main: while (true) { // std.debug.warn("MAIN LOOP\n", .{}); while (true) { var cycles: usize = 0; j = 0; while (j < SIZE) : (j += 1) { // std.debug.warn("C {} run\n",.{ j}); cycles += self.computers[j].run(); } // std.debug.warn("CYCLES {}\n",.{ cycles}); if (cycles == 0) break; } j = 0; while (j < SIZE) : (j += 1) { var got: [3]i64 = undefined; var p: usize = 0; while (true) { if (p >= 3) { var d = @intCast(usize, got[0]); const x = got[1]; const y = got[2]; if (d == 255) { // std.debug.warn("Got packet for NAT: {} {}\n",.{ x, y}); self.nat.count += 1; self.nat.xcur = x; self.nat.ycur = y; if (once) { result = self.nat.ycur; break :main; } } else { // std.debug.warn("C {} enqueue {} - {}\n",.{ d, x, y}); self.computers[d].enqueueInput(x); self.computers[d].enqueueInput(y); } p = 0; break; // ???? } const output = self.computers[j].getOutput(); if (output == null) break; got[p] = output.?; p += 1; // std.debug.warn("C {} output {}\n",.{ j, output.?}); } } var enqueued: usize = 0; j = 0; while (j < SIZE) : (j += 1) { if (!self.computers[j].inputs.empty()) continue; // std.debug.warn("C {} enqueue -1\n",.{ j}); self.computers[j].enqueueInput(-1); enqueued += 1; } if (enqueued == SIZE) { // std.debug.warn("NETWORK IDLE\n", .{}); if (self.nat.count > 0) { std.debug.warn("Sending packet from NAT: {} {}\n", .{ self.nat.xcur, self.nat.ycur }); if (self.nat.ycur == self.nat.yprv) { // std.debug.warn("REPEATED: {}\n",.{ self.nat.ycur}); result = self.nat.ycur; break :main; } self.nat.xprv = self.nat.xcur; self.nat.yprv = self.nat.ycur; self.computers[0].enqueueInput(self.nat.xcur); self.computers[0].enqueueInput(self.nat.ycur); } } } return result; } };
2019/p23/network.zig
const std = @import("std"); const auto_detect = @import("build/auto-detect.zig"); fn sdkRoot() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } /// This file encodes a instance of an Android SDK interface. const Sdk = @This(); /// The builder instance associated with this object. b: *Builder, /// A set of tools that run on the build host that are required to complete the /// project build. Must be created with the `hostTools()` function that passes in /// the correct relpath to the package. host_tools: HostTools, /// The configuration for all non-shipped system tools. /// Contains the normal default config for each tool. system_tools: SystemTools = .{}, /// Contains paths to each required input folder. folders: UserConfig, versions: ToolchainVersions, /// Initializes the android SDK. /// It requires some input on which versions of the tool chains should be used pub fn init(b: *Builder, user_config: ?UserConfig, versions: ToolchainVersions) *Sdk { const actual_user_config = user_config orelse auto_detect.findUserConfig(b, versions) catch |err| @panic(@errorName(err)); const system_tools = blk: { const exe = if (std.builtin.os.tag == .windows) ".exe" else ""; const zipalign = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", versions.build_tools_version, "zipalign" ++ exe }) catch unreachable; const aapt = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "build-tools", versions.build_tools_version, "aapt" ++ exe }) catch unreachable; const adb = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.android_sdk_root, "platform-tools", "adb" ++ exe }) catch unreachable; const jarsigner = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.java_home, "bin", "jarsigner" ++ exe }) catch unreachable; const keytool = std.fs.path.join(b.allocator, &[_][]const u8{ actual_user_config.java_home, "bin", "keytool" ++ exe }) catch unreachable; break :blk SystemTools{ .zipalign = zipalign, .aapt = aapt, .adb = adb, .jarsigner = jarsigner, .keytool = keytool, }; }; // Compiles all required additional tools for toolchain. const host_tools = blk: { const zip_add = b.addExecutable("zip_add", sdkRoot() ++ "/tools/zip_add.zig"); zip_add.addCSourceFile(sdkRoot() ++ "/vendor/kuba-zip/zip.c", &[_][]const u8{ "-std=c99", "-fno-sanitize=undefined", }); zip_add.addIncludeDir(sdkRoot() ++ "/vendor/kuba-zip"); zip_add.linkLibC(); break :blk HostTools{ .zip_add = zip_add, }; }; const sdk = b.allocator.create(Sdk) catch @panic("out of memory"); sdk.* = Sdk{ .b = b, .host_tools = host_tools, .system_tools = system_tools, .folders = actual_user_config, .versions = versions, }; return sdk; } pub const ToolchainVersions = struct { android_sdk_version: u16 = 28, build_tools_version: []const u8 = "28.0.3", ndk_version: []const u8 = "21.1.6352462", pub fn androidSdkString(self: ToolchainVersions, buf: *[5]u8) []u8 { return std.fmt.bufPrint(buf, "{d}", .{self.android_sdk_version}) catch unreachable; } }; pub const UserConfig = struct { android_sdk_root: []const u8 = "", android_ndk_root: []const u8 = "", java_home: []const u8 = "", }; /// Configuration of the Android toolchain. pub const Config = struct { /// Path to the SDK root folder. /// Example: `/home/ziggy/android-sdk`. sdk_root: []const u8, /// Path to the NDK root folder. /// Example: `/home/ziggy/android-sdk/ndk/21.1.6352462`. ndk_root: []const u8, /// Path to the build tools folder. /// Example: `/home/ziggy/android-sdk/build-tools/28.0.3`. build_tools: []const u8, /// A key store. This is required when an APK is created and signed. /// If you don't care for production code, just use the default here /// and it will work. This needs to be changed to a *proper* key store /// when you want to publish the app. key_store: KeyStore = KeyStore{ .file = "zig-cache/", .alias = "default", .password = "<PASSWORD>", }, }; /// A resource that will be packed into the appliation. pub const Resource = struct { /// This is the relative path to the resource root path: []const u8, /// This is the content of the file. content: std.build.FileSource, }; /// Configuration of an application. pub const AppConfig = struct { /// The display name of the application. This is shown to the users. display_name: []const u8, /// Application name, only lower case letters and underscores are allowed. app_name: []const u8, /// Java package name, usually the reverse top level domain + app name. /// Only lower case letters, dots and underscores are allowed. package_name: []const u8, /// The android version which is embedded in the manifset. /// This is usually the same version as of the SDK that was used, but might also be /// overridden for a specific app. target_sdk_version: ?u16 = null, /// The resource directory that will contain the manifest and other app resources. /// This should be a distinct directory per app. resources: []const Resource = &[_]Resource{}, /// If true, the app will be started in "fullscreen" mode, this means that /// navigation buttons as well as the top bar are not shown. /// This is usually relevant for games. fullscreen: bool = false, /// One or more asset directories. Each directory will be added into the app assets. asset_directories: []const []const u8 = &[_][]const u8{}, permissions: []const []const u8 = &[_][]const u8{ //"android.permission.SET_RELEASE_APP", //"android.permission.RECORD_AUDIO", }, }; /// One of the legal targets android can be built for. pub const Target = enum { aarch64, arm, x86, x86_64, }; pub const KeyStore = struct { file: []const u8, alias: []const u8, password: []const u8, }; pub const HostTools = struct { zip_add: *std.build.LibExeObjStep, }; /// Configuration of the binary paths to all tools that are not included in the android SDK. pub const SystemTools = struct { //keytool: []const u8 = "keytool", //adb: []const u8 = "adb", //jarsigner: []const u8 = "/usr/lib/jvm/java-11-openjdk/bin/jarsigner", mkdir: []const u8 = "mkdir", rm: []const u8 = "rm", zipalign: []const u8 = "zipalign", aapt: []const u8 = "aapt", adb: []const u8 = "adb", jarsigner: []const u8 = "jarsigner", keytool: []const u8 = "keytool", }; /// The configuration which targets a app should be built for. pub const AppTargetConfig = struct { aarch64: bool = true, arm: bool = false, // re-enable when https://github.com/ziglang/zig/issues/8885 is resolved x86_64: bool = true, x86: bool = false, }; pub const CreateAppStep = struct { sdk: *Sdk, first_step: *std.build.Step, final_step: *std.build.Step, libraries: []const *std.build.LibExeObjStep, build_options: *BuildOptionStep, apk_file: std.build.FileSource, package_name: []const u8, pub fn getAndroidPackage(self: @This(), name: []const u8) std.build.Pkg { return self.sdk.b.dupePkg(std.build.Pkg{ .name = name, .path = .{ .path = sdkRoot() ++ "/src/android-support.zig" }, .dependencies = &[_]std.build.Pkg{ self.build_options.getPackage("build_options"), }, }); } pub fn install(self: @This()) *Step { return self.sdk.installApp(self.apk_file); } pub fn run(self: @This()) *Step { return self.sdk.startApp(self.package_name); } }; /// Instantiates the full build pipeline to create an APK file. /// pub fn createApp( sdk: *Sdk, apk_file: []const u8, src_file: []const u8, app_config: AppConfig, mode: std.builtin.Mode, targets: AppTargetConfig, key_store: KeyStore, ) CreateAppStep { const write_xml_step = sdk.b.addWriteFile("strings.xml", blk: { var buf = std.ArrayList(u8).init(sdk.b.allocator); errdefer buf.deinit(); var writer = buf.writer(); writer.writeAll( \\<?xml version="1.0" encoding="utf-8"?> \\<resources> \\ ) catch unreachable; writer.print( \\ <string name="app_name">{s}</string> \\ <string name="lib_name">{s}</string> \\ <string name="package_name">{s}</string> \\ , .{ app_config.display_name, app_config.app_name, app_config.package_name, }) catch unreachable; writer.writeAll( \\</resources> \\ ) catch unreachable; break :blk buf.toOwnedSlice(); }); const manifest_step = sdk.b.addWriteFile("AndroidManifest.xml", blk: { var buf = std.ArrayList(u8).init(sdk.b.allocator); errdefer buf.deinit(); var writer = buf.writer(); @setEvalBranchQuota(1_000_000); writer.print( \\<?xml version="1.0" encoding="utf-8" standalone="no"?><manifest xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" package="{s}"> \\ , .{app_config.package_name}) catch unreachable; for (app_config.permissions) |perm| { writer.print( \\ <uses-permission android:name="{s}"/> \\ , .{perm}) catch unreachable; } if (app_config.fullscreen) { writer.writeAll( \\ <application android:debuggable="true" android:hasCode="false" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar.Fullscreen" tools:replace="android:icon,android:theme,android:allowBackup,label" android:icon="@mipmap/icon" > \\ <activity android:configChanges="keyboardHidden|orientation" android:name="android.app.NativeActivity"> \\ <meta-data android:name="android.app.lib_name" android:value="@string/lib_name"/> \\ <intent-filter> \\ <action android:name="android.intent.action.MAIN"/> \\ <category android:name="android.intent.category.LAUNCHER"/> \\ </intent-filter> \\ </activity> \\ </application> \\</manifest> \\ ) catch unreachable; } else { writer.writeAll( \\ <application android:debuggable="true" android:hasCode="false" android:label="@string/app_name" tools:replace="android:icon,android:theme,android:allowBackup,label" android:icon="@mipmap/icon"> \\ <activity android:configChanges="keyboardHidden|orientation" android:name="android.app.NativeActivity"> \\ <meta-data android:name="android.app.lib_name" android:value="@string/lib_name"/> \\ <intent-filter> \\ <action android:name="android.intent.action.MAIN"/> \\ <category android:name="android.intent.category.LAUNCHER"/> \\ </intent-filter> \\ </activity> \\ </application> \\</manifest> \\ ) catch unreachable; } break :blk buf.toOwnedSlice(); }); const resource_dir_step = CreateResourceDirectory.create(sdk.b); for (app_config.resources) |res| { resource_dir_step.add(res); } resource_dir_step.add(Resource{ .path = "values/strings.xml", .content = write_xml_step.getFileSource("strings.xml").?, }); const sdk_version = sdk.versions.android_sdk_version; const target_sdk_version = app_config.target_sdk_version orelse sdk.versions.android_sdk_version; const root_jar = std.fs.path.resolve(sdk.b.allocator, &[_][]const u8{ sdk.folders.android_sdk_root, "platforms", sdk.b.fmt("android-{d}", .{sdk_version}), "android.jar", }) catch unreachable; const make_unsigned_apk = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.aapt, "package", "-f", // force overwrite of existing files "-F", // specify the apk file to output sdk.b.pathFromRoot(apk_file), "-I", // add an existing package to base include set root_jar, }); make_unsigned_apk.addArg("-M"); // specify full path to AndroidManifest.xml to include in zip make_unsigned_apk.addFileSourceArg(manifest_step.getFileSource("AndroidManifest.xml").?); make_unsigned_apk.addArg("-S"); // directory in which to find resources. Multiple directories will be scanned and the first match found (left to right) will take precedence make_unsigned_apk.addFileSourceArg(resource_dir_step.getOutputDirectory()); make_unsigned_apk.addArgs(&[_][]const u8{ "-v", "--target-sdk-version", sdk.b.fmt("{d}", .{target_sdk_version}), }); for (app_config.asset_directories) |dir| { make_unsigned_apk.addArg("-A"); // additional directory in which to find raw asset files make_unsigned_apk.addArg(sdk.b.pathFromRoot(dir)); } var libs = std.ArrayList(*std.build.LibExeObjStep).init(sdk.b.allocator); defer libs.deinit(); const build_options = BuildOptionStep.create(sdk.b); build_options.add([]const u8, "app_name", app_config.app_name); build_options.add(u16, "android_sdk_version", app_config.target_sdk_version orelse sdk.versions.android_sdk_version); build_options.add(bool, "fullscreen", app_config.fullscreen); const sign_step = sdk.signApk(apk_file, key_store); inline for (std.meta.fields(AppTargetConfig)) |fld| { const target_name = @field(Target, fld.name); if (@field(targets, fld.name)) { const step = sdk.compileAppLibrary( src_file, app_config, mode, target_name, // build_options.getPackage("build_options"), ); libs.append(step) catch unreachable; const so_dir = switch (target_name) { .aarch64 => "lib/arm64-v8a/", .arm => "lib/armeabi/", .x86_64 => "lib/x86_64/", .x86 => "lib/x86/", }; const copy_to_zip = CopyToZipStep.create(sdk, apk_file, so_dir, step.getOutputSource()); copy_to_zip.step.dependOn(&make_unsigned_apk.step); // enforces creation of APK before the execution sign_step.dependOn(&copy_to_zip.step); } } // const compress_step = compressApk(b, android_config, apk_file, "zig-out/demo.packed.apk"); // compress_step.dependOn(sign_step); return CreateAppStep{ .sdk = sdk, .first_step = &make_unsigned_apk.step, .final_step = sign_step, .libraries = libs.toOwnedSlice(), .build_options = build_options, .package_name = sdk.b.dupe(app_config.package_name), .apk_file = (std.build.FileSource{ .path = apk_file }).dupe(sdk.b), }; } const CreateResourceDirectory = struct { const Self = @This(); builder: *std.build.Builder, step: std.build.Step, resources: std.ArrayList(Resource), directory: std.build.GeneratedFile, pub fn create(b: *std.build.Builder) *Self { const self = b.allocator.create(Self) catch @panic("out of memory"); self.* = Self{ .builder = b, .step = Step.init(.custom, "populate resource directory", b.allocator, CreateResourceDirectory.make), .directory = .{ .step = &self.step }, .resources = std.ArrayList(Resource).init(b.allocator), }; return self; } pub fn add(self: *Self, resource: Resource) void { self.resources.append(Resource{ .path = self.builder.dupe(resource.path), .content = resource.content.dupe(self.builder), }) catch @panic("out of memory"); resource.content.addStepDependencies(&self.step); } pub fn getOutputDirectory(self: *Self) std.build.FileSource { return .{ .generated = &self.directory }; } fn make(step: *Step) !void { const self = @fieldParentPtr(Self, "step", step); // if (std.fs.path.dirname(strings_xml)) |dir| { // std.fs.cwd().makePath(dir) catch unreachable; // } var cacher = createCacheBuilder(self.builder); for (self.resources.items) |res| { cacher.addBytes(res.path); try cacher.addFile(res.content); } const root = try cacher.createAndGetDir(); for (self.resources.items) |res| { if (std.fs.path.dirname(res.path)) |folder| { try root.dir.makePath(folder); } const src_path = res.content.getPath(self.builder); try std.fs.Dir.copyFile( std.fs.cwd(), src_path, root.dir, res.path, .{}, ); } self.directory.path = root.path; } }; const CopyToZipStep = struct { step: Step, sdk: *Sdk, target_dir: []const u8, input_file: std.build.FileSource, apk_file: []const u8, fn create(sdk: *Sdk, apk_file: []const u8, target_dir: []const u8, input_file: std.build.FileSource) *CopyToZipStep { std.debug.assert(target_dir[target_dir.len - 1] == '/'); const self = sdk.b.allocator.create(CopyToZipStep) catch unreachable; self.* = CopyToZipStep{ .step = Step.init(.custom, "copy to zip", sdk.b.allocator, make), .target_dir = target_dir, .input_file = input_file, .sdk = sdk, .apk_file = sdk.b.pathFromRoot(apk_file), }; self.step.dependOn(&sdk.host_tools.zip_add.step); input_file.addStepDependencies(&self.step); return self; } // id: Id, name: []const u8, allocator: *Allocator, makeFn: fn (*Step) anyerror!void fn make(step: *Step) !void { const self = @fieldParentPtr(CopyToZipStep, "step", step); const output_path = self.input_file.getPath(self.sdk.b); var zip_name = std.mem.concat(self.sdk.b.allocator, u8, &[_][]const u8{ self.target_dir, std.fs.path.basename(output_path), }) catch unreachable; const args = [_][]const u8{ self.sdk.host_tools.zip_add.getOutputSource().getPath(self.sdk.b), self.apk_file, output_path, zip_name, }; _ = try self.sdk.b.execFromStep(&args, &self.step); } }; /// Compiles a single .so file for the given platform. /// Note that this function assumes your build script only uses a single `android_config`! pub fn compileAppLibrary( sdk: Sdk, src_file: []const u8, app_config: AppConfig, mode: std.builtin.Mode, target: Target, // build_options: std.build.Pkg, ) *std.build.LibExeObjStep { switch (target) { .arm => @panic("compiling android apps to arm not supported right now. see: https://github.com/ziglang/zig/issues/8885"), .x86 => @panic("compiling android apps to x86 not supported right now. see https://github.com/ziglang/zig/issues/7935"), else => {}, } const ndk_root = sdk.b.pathFromRoot(sdk.folders.android_ndk_root); const exe = sdk.b.addSharedLibrary(app_config.app_name, src_file, .unversioned); exe.force_pic = true; exe.link_function_sections = true; exe.bundle_compiler_rt = true; exe.strip = (mode == .ReleaseSmall); exe.defineCMacro("ANDROID", null); const include_dir = std.fs.path.resolve(sdk.b.allocator, &[_][]const u8{ ndk_root, "sysroot/usr/include" }) catch unreachable; exe.addIncludeDir(include_dir); exe.linkLibC(); for (app_libs) |lib| { exe.linkSystemLibraryName(lib); } exe.setBuildMode(mode); const TargetConfig = struct { lib_dir: []const u8, include_dir: []const u8, out_dir: []const u8, target: std.zig.CrossTarget, }; const config: TargetConfig = switch (target) { .aarch64 => TargetConfig{ .lib_dir = "arch-arm64/usr/lib", .include_dir = "aarch64-linux-android", .out_dir = "arm64-v8a", .target = zig_targets.aarch64, }, .arm => TargetConfig{ .lib_dir = "arch-arm/usr/lib", .include_dir = "arm-linux-androideabi", .out_dir = "armeabi", .target = zig_targets.arm, }, .x86 => TargetConfig{ .lib_dir = "arch-x86/usr/lib", .include_dir = "i686-linux-android", .out_dir = "x86", .target = zig_targets.x86, }, .x86_64 => TargetConfig{ .lib_dir = "arch-x86_64/usr/lib64", .include_dir = "x86_64-linux-android", .out_dir = "x86_64", .target = zig_targets.x86_64, }, }; const lib_dir_root = sdk.b.fmt("{s}/platforms/android-{d}", .{ ndk_root, sdk.versions.android_sdk_version, }); const libc_path = std.fs.path.resolve(sdk.b.allocator, &[_][]const u8{ sdk.b.cache_root, "android-libc", sdk.b.fmt("android-{d}-{s}.conf", .{ sdk.versions.android_sdk_version, config.out_dir }), }) catch unreachable; const lib_dir = std.fs.path.resolve(sdk.b.allocator, &[_][]const u8{ lib_dir_root, config.lib_dir }) catch unreachable; exe.setTarget(config.target); exe.addLibPath(lib_dir); exe.addIncludeDir(std.fs.path.resolve(sdk.b.allocator, &[_][]const u8{ include_dir, config.include_dir }) catch unreachable); exe.libc_file = std.build.FileSource{ .path = libc_path }; // write libc file: createLibCFile(exe.libc_file.?.path, include_dir, include_dir, lib_dir) catch unreachable; return exe; } fn createLibCFile(path: []const u8, include_dir: []const u8, sys_include_dir: []const u8, crt_dir: []const u8) !void { if (std.fs.path.dirname(path)) |dir| { try std.fs.cwd().makePath(dir); } var f = try std.fs.cwd().createFile(path, .{}); defer f.close(); var writer = f.writer(); try writer.print("include_dir={s}\n", .{include_dir}); try writer.print("sys_include_dir={s}\n", .{sys_include_dir}); try writer.print("crt_dir={s}\n", .{crt_dir}); try writer.writeAll("msvc_lib_dir=\n"); try writer.writeAll("kernel32_lib_dir=\n"); try writer.writeAll("gcc_dir=\n"); } pub fn compressApk(sdk: Sdk, input_apk_file: []const u8, output_apk_file: []const u8) *Step { const temp_folder = sdk.b.pathFromRoot("zig-cache/apk-compress-folder"); const mkdir_cmd = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.mkdir, temp_folder, }); const unpack_apk = sdk.b.addSystemCommand(&[_][]const u8{ "unzip", "-o", sdk.builder.pathFromRoot(input_apk_file), "-d", temp_folder, }); unpack_apk.step.dependOn(&mkdir_cmd.step); const repack_apk = sdk.b.addSystemCommand(&[_][]const u8{ "zip", "-D9r", sdk.builder.pathFromRoot(output_apk_file), ".", }); repack_apk.cwd = temp_folder; repack_apk.step.dependOn(&unpack_apk.step); const rmdir_cmd = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.rm, "-rf", temp_folder, }); rmdir_cmd.step.dependOn(&repack_apk.step); return &rmdir_cmd.step; } pub fn signApk(sdk: Sdk, apk_file: []const u8, key_store: KeyStore) *Step { const sign_apk = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.jarsigner, "-sigalg", "SHA1withRSA", "-digestalg", "SHA1", "-verbose", "-keystore", key_store.file, "-storepass", key_store.password, sdk.b.pathFromRoot(apk_file), key_store.alias, }); return &sign_apk.step; } pub fn alignApk(sdk: Sdk, input_apk_file: []const u8, output_apk_file: []const u8) *Step { const step = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.zipalign, "-v", "4", sdk.builder.pathFromRoot(input_apk_file), sdk.builder.pathFromRoot(output_apk_file), }); return &step.step; } pub fn installApp(sdk: Sdk, apk_file: std.build.FileSource) *Step { const step = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.adb, "install" }); step.addFileSourceArg(apk_file); return &step.step; } pub fn startApp(sdk: Sdk, package_name: []const u8) *Step { const step = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.adb, "shell", "am", "start", "-n", sdk.b.fmt("{s}/android.app.NativeActivity", .{package_name}), }); return &step.step; } /// Configuration for a signing key. pub const KeyConfig = struct { pub const Algorithm = enum { RSA }; key_algorithm: Algorithm = .RSA, key_size: u32 = 2048, // bits validity: u32 = 10_000, // days distinguished_name: []const u8 = "CN=example.com, OU=ID, O=Example, L=Doe, S=John, C=GB", }; /// A build step that initializes a new key store from the given configuration. /// `android_config.key_store` must be non-`null` as it is used to initialize the key store. pub fn initKeystore(sdk: Sdk, key_store: KeyStore, key_config: KeyConfig) *Step { const step = sdk.b.addSystemCommand(&[_][]const u8{ sdk.system_tools.keytool, "-genkey", "-v", "-keystore", key_store.file, "-alias", key_store.alias, "-keyalg", @tagName(key_config.key_algorithm), "-keysize", sdk.b.fmt("{d}", .{key_config.key_size}), "-validity", sdk.b.fmt("{d}", .{key_config.validity}), "-storepass", key_store.password, "-keypass", key_store.password, "-dname", key_config.distinguished_name, }); return &step.step; } const Builder = std.build.Builder; const Step = std.build.Step; const android_os = .linux; const android_abi = .android; const zig_targets = struct { const aarch64 = std.zig.CrossTarget{ .cpu_arch = .aarch64, .os_tag = android_os, .abi = android_abi, .cpu_model = .baseline, .cpu_features_add = std.Target.aarch64.featureSet(&.{.v8a}), }; const arm = std.zig.CrossTarget{ .cpu_arch = .arm, .os_tag = android_os, .abi = android_abi, .cpu_model = .baseline, .cpu_features_add = std.Target.arm.featureSet(&.{.v7a}), }; const x86 = std.zig.CrossTarget{ .cpu_arch = .i386, .os_tag = android_os, .abi = android_abi, .cpu_model = .baseline, }; const x86_64 = std.zig.CrossTarget{ .cpu_arch = .x86_64, .os_tag = android_os, .abi = android_abi, .cpu_model = .baseline, }; }; const app_libs = [_][]const u8{ "GLESv2", "EGL", "android", "log", }; const BuildOptionStep = struct { const Self = @This(); step: Step, builder: *std.build.Builder, file_content: std.ArrayList(u8), package_file: std.build.GeneratedFile, pub fn create(b: *Builder) *Self { const options = b.allocator.create(Self) catch @panic("out of memory"); options.* = Self{ .builder = b, .step = Step.init(.custom, "render build options", b.allocator, make), .file_content = std.ArrayList(u8).init(b.allocator), .package_file = std.build.GeneratedFile{ .step = &options.step }, }; return options; } pub fn getPackage(self: *Self, name: []const u8) std.build.Pkg { return self.builder.dupePkg(std.build.Pkg{ .name = name, .path = .{ .generated = &self.package_file }, }); } pub fn add(self: *Self, comptime T: type, name: []const u8, value: T) void { const out = self.file_content.writer(); switch (T) { []const []const u8 => { out.print("pub const {}: []const []const u8 = &[_][]const u8{{\n", .{std.zig.fmtId(name)}) catch unreachable; for (value) |slice| { out.print(" \"{}\",\n", .{std.zig.fmtEscapes(slice)}) catch unreachable; } out.writeAll("};\n") catch unreachable; return; }, [:0]const u8 => { out.print("pub const {}: [:0]const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable; return; }, []const u8 => { out.print("pub const {}: []const u8 = \"{}\";\n", .{ std.zig.fmtId(name), std.zig.fmtEscapes(value) }) catch unreachable; return; }, ?[:0]const u8 => { out.print("pub const {}: ?[:0]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable; if (value) |payload| { out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable; } else { out.writeAll("null;\n") catch unreachable; } return; }, ?[]const u8 => { out.print("pub const {}: ?[]const u8 = ", .{std.zig.fmtId(name)}) catch unreachable; if (value) |payload| { out.print("\"{}\";\n", .{std.zig.fmtEscapes(payload)}) catch unreachable; } else { out.writeAll("null;\n") catch unreachable; } return; }, std.builtin.Version => { out.print( \\pub const {}: @import("std").builtin.Version = .{{ \\ .major = {d}, \\ .minor = {d}, \\ .patch = {d}, \\}}; \\ , .{ std.zig.fmtId(name), value.major, value.minor, value.patch, }) catch unreachable; }, std.SemanticVersion => { out.print( \\pub const {}: @import("std").SemanticVersion = .{{ \\ .major = {d}, \\ .minor = {d}, \\ .patch = {d}, \\ , .{ std.zig.fmtId(name), value.major, value.minor, value.patch, }) catch unreachable; if (value.pre) |some| { out.print(" .pre = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable; } if (value.build) |some| { out.print(" .build = \"{}\",\n", .{std.zig.fmtEscapes(some)}) catch unreachable; } out.writeAll("};\n") catch unreachable; return; }, else => {}, } switch (@typeInfo(T)) { .Enum => |enum_info| { out.print("pub const {} = enum {{\n", .{std.zig.fmtId(@typeName(T))}) catch unreachable; inline for (enum_info.fields) |field| { out.print(" {},\n", .{std.zig.fmtId(field.name)}) catch unreachable; } out.writeAll("};\n") catch unreachable; }, else => {}, } out.print("pub const {}: {s} = {};\n", .{ std.zig.fmtId(name), @typeName(T), value }) catch unreachable; } fn make(step: *Step) !void { const self = @fieldParentPtr(Self, "step", step); var cacher = createCacheBuilder(self.builder); cacher.addBytes(self.file_content.items); const root_path = try cacher.createAndGetPath(); self.package_file.path = try std.fs.path.join(self.builder.allocator, &[_][]const u8{ root_path, "build_options.zig", }); try std.fs.cwd().writeFile(self.package_file.path.?, self.file_content.items); } }; fn createCacheBuilder(b: *std.build.Builder) CacheBuilder { return CacheBuilder.init(b, "android-sdk"); } const CacheBuilder = struct { const Self = @This(); builder: *std.build.Builder, hasher: std.crypto.hash.Sha1, subdir: ?[]const u8, pub fn init(builder: *std.build.Builder, subdir: ?[]const u8) Self { return Self{ .builder = builder, .hasher = std.crypto.hash.Sha1.init(.{}), .subdir = if (subdir) |s| builder.dupe(s) else null, }; } pub fn addBytes(self: *Self, bytes: []const u8) void { self.hasher.update(bytes); } pub fn addFile(self: *Self, file: std.build.FileSource) !void { const path = file.getPath(self.builder); const data = try std.fs.cwd().readFileAlloc(self.builder.allocator, path, 1 << 32); // 4 GB defer self.builder.allocator.free(data); self.addBytes(data); } fn createPath(self: *Self) ![]const u8 { var hash: [20]u8 = undefined; self.hasher.final(&hash); const path = if (self.subdir) |subdir| try std.fmt.allocPrint( self.builder.allocator, "{s}/{s}/o/{}", .{ self.builder.cache_root, subdir, std.fmt.fmtSliceHexLower(&hash), }, ) else try std.fmt.allocPrint( self.builder.allocator, "{s}/o/{}", .{ self.builder.cache_root, std.fmt.fmtSliceHexLower(&hash), }, ); return path; } pub const DirAndPath = struct { dir: std.fs.Dir, path: []const u8, }; pub fn createAndGetDir(self: *Self) !DirAndPath { const path = try self.createPath(); return DirAndPath{ .path = path, .dir = try std.fs.cwd().makeOpenPath(path, .{}), }; } pub fn createAndGetPath(self: *Self) ![]const u8 { const path = try self.createPath(); try std.fs.cwd().makePath(path); return path; } };
Sdk.zig
const std = @import("std"); const opt = @import("opt.zig"); const stdout = &std.io.getStdOut().outStream(); const stdin = &std.io.getStdIn().inStream(); const VERSION = "0.0.1"; const BUFSIZE: usize = 4096; const MAXLEN: usize = 39; const ZIGUANA = \\ . \ . . \\ . \ _.--._ /| \\ . .'()..()`. / / \\ ( `-.__.-' ) ( ( . \\ . \ / \ \ \\ . \ / ) ) . \\ .' -.__.- `.-.-'_.' \\ . .' /-____-\ `.-' . \\ \ /-.____.-\ /-. \\ \ \`-.__.-'/ /\|\| . \\ .' `. .' `. \\ |/\/\| |/\/\| \\jro ; const ZigsayFlags = enum { Help, Version, }; var flags = [_]opt.Flag(ZigsayFlags){ .{ .name = ZigsayFlags.Help, .long = "help", .short = 'h', }, .{ .name = ZigsayFlags.Version, .long = "version", .short = 'v', }, }; fn read_stdin(allocator: *std.mem.Allocator) ![]u8 { // initialize read and input buffer var read_buffer: [BUFSIZE]u8 = undefined; var input_buffer = std.ArrayList(u8).init(allocator); defer input_buffer.deinit(); // read input into read_buffer, appending to input_buffer var size = try stdin.readAll(&read_buffer); while (size > 0) : (size = try stdin.readAll(&read_buffer)) { try input_buffer.insertSlice(input_buffer.items.len, read_buffer[0..size]); } return input_buffer.toOwnedSlice(); } fn concat(words: [][]u8, allocator: *std.mem.Allocator) ![]u8 { // initialize line buffer var result_buffer = std.ArrayList(u8).init(allocator); defer result_buffer.deinit(); for (words) |word, i| { if (i != 0) try result_buffer.append(' '); try result_buffer.insertSlice(result_buffer.items.len, word); } return result_buffer.toOwnedSlice(); } fn wrap(s: []u8, allocator: *std.mem.Allocator) ![][]u8 { // initialize result list var result = std.ArrayList([]u8).init(allocator); defer result.deinit(); // initialize line buffer var line_buffer = std.ArrayList(u8).init(allocator); defer line_buffer.deinit(); // initialize iterator and word and line start var iterator: usize = 0; var word_start: usize = 0; // push words into line buffer, and line buffer into result list while (iterator < s.len) : (iterator += 1) { if ((iterator + 1 == s.len and !std.fmt.isWhiteSpace(s[iterator])) or (iterator + 1 < s.len and std.fmt.isWhiteSpace(s[iterator + 1]))) { if (word_start != iterator + 1) { // end of word, not a leading whitespace if (line_buffer.items.len > 0 and line_buffer.items.len + (iterator - word_start + 2) > MAXLEN) { // new line, since we cant fit more words try result.append(line_buffer.toOwnedSlice()); try line_buffer.resize(0); } if (line_buffer.items.len > 0) try line_buffer.append(' '); try line_buffer.insertSlice(line_buffer.items.len, s[word_start..(iterator + 1)]); // word appended is larger than MAXLEN characters, append parts now if (line_buffer.items.len > MAXLEN) { var line = line_buffer.toOwnedSlice(); var blk: usize = 0; while (line.len - blk * MAXLEN >= MAXLEN) : (blk += 1) try result.append(line[blk * MAXLEN .. (blk + 1) * MAXLEN]); try line_buffer.resize(0); // fix ownedSlice() try line_buffer.insertSlice(line_buffer.items.len, line[blk * MAXLEN ..]); } } // start new word word_start = iterator + 2; iterator = iterator + 1; } } if (line_buffer.items.len > 0) { try result.append(line_buffer.toOwnedSlice()); } return result.toOwnedSlice(); } fn print_repeat(symbol: u8, count: usize, full_line: bool, allocator: *std.mem.Allocator) !void { if (full_line) try stdout.print(" ", .{}); var i: usize = 0; while (i < count) : (i += 1) try stdout.print("{c}", .{symbol}); if (full_line) try stdout.print(" \n", .{}); } fn print_dialog_box(lines: [][]u8, allocator: *std.mem.Allocator) !void { var max_len: usize = 0; for (lines) |line| max_len = if (line.len > max_len) line.len else max_len; try print_repeat('_', max_len + 2, true, allocator); for (lines) |line, i| { var start_char: u8 = '|'; var end_char: u8 = '|'; if (lines.len == 1) { start_char = '<'; end_char = '>'; } else if (i == 0) { start_char = '/'; end_char = '\\'; } else if (i + 1 == lines.len) { start_char = '\\'; end_char = '/'; } try stdout.print("{c} {} ", .{ start_char, line }); if (line.len < max_len) try print_repeat(' ', max_len - line.len, false, allocator); try stdout.print("{c}\n", .{end_char}); } try print_repeat('-', max_len + 2, true, allocator); } pub fn zigsay(input: []u8, allocator: *std.mem.Allocator) !void { // necessary due to Ziguana drawing being too long @setEvalBranchQuota(1500); // wrap to create dialogue box var wrapped_input = try wrap(input, allocator); // print dialog box try print_dialog_box(wrapped_input, allocator); // print Ziguana's body try stdout.print(ZIGUANA, .{}); } pub fn main(args: [][]u8) anyerror!u8 { // parse arguments var it = opt.FlagIterator(ZigsayFlags).init(flags[0..], args); while (it.next_flag() catch { return 0; }) |flag| { switch (flag.name) { ZigsayFlags.Help => { std.debug.warn("usage: cowsay [INPUT or will read from stdin]\n", .{}); return 0; }, ZigsayFlags.Version => { std.debug.warn("version: {}\n", .{VERSION}); return 0; }, } } // create allocator var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; // read from stdin or merge arguments var input = if (args.len == 1) try read_stdin(allocator) else try concat(args[1..], allocator); // call function zigsay(input, allocator) catch |err| { std.debug.warn("Error: {}\n", .{err}); return 1; }; return 0; }
src/zigsay.zig
pub const DIRECTSOUND_VERSION = @as(u32, 1792); pub const _FACDS = @as(u32, 2168); pub const CLSID_DirectSound = Guid.initString("47d4d946-62e8-11cf-93bc-444553540000"); pub const CLSID_DirectSound8 = Guid.initString("3901cc3f-84b5-4fa4-ba35-aa8172b8a09b"); pub const CLSID_DirectSoundCapture = Guid.initString("b0210780-89cd-11d0-af08-00a0c925cd16"); pub const CLSID_DirectSoundCapture8 = Guid.initString("e4bcac13-7f99-4908-9a8e-74e3bf24b6e1"); pub const CLSID_DirectSoundFullDuplex = Guid.initString("fea4300c-7959-4147-b26a-2377b9e7a91d"); pub const DSDEVID_DefaultPlayback = Guid.initString("def00000-9c6d-47ed-aaf1-4dda8f2b5c03"); pub const DSDEVID_DefaultCapture = Guid.initString("def00001-9c6d-47ed-aaf1-4dda8f2b5c03"); pub const DSDEVID_DefaultVoicePlayback = Guid.initString("def00002-9c6d-47ed-aaf1-4dda8f2b5c03"); pub const DSDEVID_DefaultVoiceCapture = Guid.initString("def00003-9c6d-47ed-aaf1-4dda8f2b5c03"); pub const DSFX_LOCHARDWARE = @as(u32, 1); pub const DSFX_LOCSOFTWARE = @as(u32, 2); pub const DSCFX_LOCHARDWARE = @as(u32, 1); pub const DSCFX_LOCSOFTWARE = @as(u32, 2); pub const DSCFXR_LOCHARDWARE = @as(u32, 16); pub const DSCFXR_LOCSOFTWARE = @as(u32, 32); pub const GUID_All_Objects = Guid.initString("aa114de5-c262-4169-a1c8-23d698cc73b5"); pub const KSPROPERTY_SUPPORT_GET = @as(u32, 1); pub const KSPROPERTY_SUPPORT_SET = @as(u32, 2); pub const DSFXGARGLE_WAVE_TRIANGLE = @as(u32, 0); pub const DSFXGARGLE_WAVE_SQUARE = @as(u32, 1); pub const DSFXGARGLE_RATEHZ_MIN = @as(u32, 1); pub const DSFXGARGLE_RATEHZ_MAX = @as(u32, 1000); pub const DSFXCHORUS_WAVE_TRIANGLE = @as(u32, 0); pub const DSFXCHORUS_WAVE_SIN = @as(u32, 1); pub const DSFXCHORUS_WETDRYMIX_MIN = @as(f32, 0); pub const DSFXCHORUS_WETDRYMIX_MAX = @as(f32, 100); pub const DSFXCHORUS_DEPTH_MIN = @as(f32, 0); pub const DSFXCHORUS_DEPTH_MAX = @as(f32, 100); pub const DSFXCHORUS_FEEDBACK_MIN = @as(f32, -99); pub const DSFXCHORUS_FEEDBACK_MAX = @as(f32, 99); pub const DSFXCHORUS_FREQUENCY_MIN = @as(f32, 0); pub const DSFXCHORUS_FREQUENCY_MAX = @as(f32, 10); pub const DSFXCHORUS_DELAY_MIN = @as(f32, 0); pub const DSFXCHORUS_DELAY_MAX = @as(f32, 20); pub const DSFXCHORUS_PHASE_MIN = @as(u32, 0); pub const DSFXCHORUS_PHASE_MAX = @as(u32, 4); pub const DSFXCHORUS_PHASE_NEG_180 = @as(u32, 0); pub const DSFXCHORUS_PHASE_NEG_90 = @as(u32, 1); pub const DSFXCHORUS_PHASE_ZERO = @as(u32, 2); pub const DSFXCHORUS_PHASE_90 = @as(u32, 3); pub const DSFXCHORUS_PHASE_180 = @as(u32, 4); pub const DSFXFLANGER_WAVE_TRIANGLE = @as(u32, 0); pub const DSFXFLANGER_WAVE_SIN = @as(u32, 1); pub const DSFXFLANGER_WETDRYMIX_MIN = @as(f32, 0); pub const DSFXFLANGER_WETDRYMIX_MAX = @as(f32, 100); pub const DSFXFLANGER_FREQUENCY_MIN = @as(f32, 0); pub const DSFXFLANGER_FREQUENCY_MAX = @as(f32, 10); pub const DSFXFLANGER_DEPTH_MIN = @as(f32, 0); pub const DSFXFLANGER_DEPTH_MAX = @as(f32, 100); pub const DSFXFLANGER_PHASE_MIN = @as(u32, 0); pub const DSFXFLANGER_PHASE_MAX = @as(u32, 4); pub const DSFXFLANGER_FEEDBACK_MIN = @as(f32, -99); pub const DSFXFLANGER_FEEDBACK_MAX = @as(f32, 99); pub const DSFXFLANGER_DELAY_MIN = @as(f32, 0); pub const DSFXFLANGER_DELAY_MAX = @as(f32, 4); pub const DSFXFLANGER_PHASE_NEG_180 = @as(u32, 0); pub const DSFXFLANGER_PHASE_NEG_90 = @as(u32, 1); pub const DSFXFLANGER_PHASE_ZERO = @as(u32, 2); pub const DSFXFLANGER_PHASE_90 = @as(u32, 3); pub const DSFXFLANGER_PHASE_180 = @as(u32, 4); pub const DSFXECHO_WETDRYMIX_MIN = @as(f32, 0); pub const DSFXECHO_WETDRYMIX_MAX = @as(f32, 100); pub const DSFXECHO_FEEDBACK_MIN = @as(f32, 0); pub const DSFXECHO_FEEDBACK_MAX = @as(f32, 100); pub const DSFXECHO_LEFTDELAY_MIN = @as(f32, 1); pub const DSFXECHO_LEFTDELAY_MAX = @as(f32, 2000); pub const DSFXECHO_RIGHTDELAY_MIN = @as(f32, 1); pub const DSFXECHO_RIGHTDELAY_MAX = @as(f32, 2000); pub const DSFXECHO_PANDELAY_MIN = @as(u32, 0); pub const DSFXECHO_PANDELAY_MAX = @as(u32, 1); pub const DSFXDISTORTION_GAIN_MIN = @as(f32, -60); pub const DSFXDISTORTION_GAIN_MAX = @as(f32, 0); pub const DSFXDISTORTION_EDGE_MIN = @as(f32, 0); pub const DSFXDISTORTION_EDGE_MAX = @as(f32, 100); pub const DSFXDISTORTION_POSTEQCENTERFREQUENCY_MIN = @as(f32, 100); pub const DSFXDISTORTION_POSTEQCENTERFREQUENCY_MAX = @as(f32, 8000); pub const DSFXDISTORTION_POSTEQBANDWIDTH_MIN = @as(f32, 100); pub const DSFXDISTORTION_POSTEQBANDWIDTH_MAX = @as(f32, 8000); pub const DSFXDISTORTION_PRELOWPASSCUTOFF_MIN = @as(f32, 100); pub const DSFXDISTORTION_PRELOWPASSCUTOFF_MAX = @as(f32, 8000); pub const DSFXCOMPRESSOR_GAIN_MIN = @as(f32, -60); pub const DSFXCOMPRESSOR_GAIN_MAX = @as(f32, 60); pub const DSFXCOMPRESSOR_ATTACK_MIN = @as(f32, 1.0e-02); pub const DSFXCOMPRESSOR_ATTACK_MAX = @as(f32, 500); pub const DSFXCOMPRESSOR_RELEASE_MIN = @as(f32, 50); pub const DSFXCOMPRESSOR_RELEASE_MAX = @as(f32, 3000); pub const DSFXCOMPRESSOR_THRESHOLD_MIN = @as(f32, -60); pub const DSFXCOMPRESSOR_THRESHOLD_MAX = @as(f32, 0); pub const DSFXCOMPRESSOR_RATIO_MIN = @as(f32, 1); pub const DSFXCOMPRESSOR_RATIO_MAX = @as(f32, 100); pub const DSFXCOMPRESSOR_PREDELAY_MIN = @as(f32, 0); pub const DSFXCOMPRESSOR_PREDELAY_MAX = @as(f32, 4); pub const DSFXPARAMEQ_CENTER_MIN = @as(f32, 80); pub const DSFXPARAMEQ_CENTER_MAX = @as(f32, 16000); pub const DSFXPARAMEQ_BANDWIDTH_MIN = @as(f32, 1); pub const DSFXPARAMEQ_BANDWIDTH_MAX = @as(f32, 36); pub const DSFXPARAMEQ_GAIN_MIN = @as(f32, -15); pub const DSFXPARAMEQ_GAIN_MAX = @as(f32, 15); pub const DSFX_I3DL2REVERB_ROOM_MIN = @as(i32, -10000); pub const DSFX_I3DL2REVERB_ROOM_MAX = @as(u32, 0); pub const DSFX_I3DL2REVERB_ROOM_DEFAULT = @as(i32, -1000); pub const DSFX_I3DL2REVERB_ROOMHF_MIN = @as(i32, -10000); pub const DSFX_I3DL2REVERB_ROOMHF_MAX = @as(u32, 0); pub const DSFX_I3DL2REVERB_ROOMHF_DEFAULT = @as(i32, -100); pub const DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MIN = @as(f32, 0); pub const DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_MAX = @as(f32, 10); pub const DSFX_I3DL2REVERB_ROOMROLLOFFFACTOR_DEFAULT = @as(f32, 0); pub const DSFX_I3DL2REVERB_DECAYTIME_MIN = @as(f32, 1.0e-01); pub const DSFX_I3DL2REVERB_DECAYTIME_MAX = @as(f32, 20); pub const DSFX_I3DL2REVERB_DECAYTIME_DEFAULT = @as(f32, 1.49e+00); pub const DSFX_I3DL2REVERB_DECAYHFRATIO_MIN = @as(f32, 1.0e-01); pub const DSFX_I3DL2REVERB_DECAYHFRATIO_MAX = @as(f32, 2); pub const DSFX_I3DL2REVERB_DECAYHFRATIO_DEFAULT = @as(f32, 8.3e-01); pub const DSFX_I3DL2REVERB_REFLECTIONS_MIN = @as(i32, -10000); pub const DSFX_I3DL2REVERB_REFLECTIONS_MAX = @as(u32, 1000); pub const DSFX_I3DL2REVERB_REFLECTIONS_DEFAULT = @as(i32, -2602); pub const DSFX_I3DL2REVERB_REFLECTIONSDELAY_MIN = @as(f32, 0); pub const DSFX_I3DL2REVERB_REFLECTIONSDELAY_MAX = @as(f32, 3.0e-01); pub const DSFX_I3DL2REVERB_REFLECTIONSDELAY_DEFAULT = @as(f32, 7.0e-03); pub const DSFX_I3DL2REVERB_REVERB_MIN = @as(i32, -10000); pub const DSFX_I3DL2REVERB_REVERB_MAX = @as(u32, 2000); pub const DSFX_I3DL2REVERB_REVERB_DEFAULT = @as(u32, 200); pub const DSFX_I3DL2REVERB_REVERBDELAY_MIN = @as(f32, 0); pub const DSFX_I3DL2REVERB_REVERBDELAY_MAX = @as(f32, 1.0e-01); pub const DSFX_I3DL2REVERB_REVERBDELAY_DEFAULT = @as(f32, 1.1e-02); pub const DSFX_I3DL2REVERB_DIFFUSION_MIN = @as(f32, 0); pub const DSFX_I3DL2REVERB_DIFFUSION_MAX = @as(f32, 100); pub const DSFX_I3DL2REVERB_DIFFUSION_DEFAULT = @as(f32, 100); pub const DSFX_I3DL2REVERB_DENSITY_MIN = @as(f32, 0); pub const DSFX_I3DL2REVERB_DENSITY_MAX = @as(f32, 100); pub const DSFX_I3DL2REVERB_DENSITY_DEFAULT = @as(f32, 100); pub const DSFX_I3DL2REVERB_HFREFERENCE_MIN = @as(f32, 20); pub const DSFX_I3DL2REVERB_HFREFERENCE_MAX = @as(f32, 20000); pub const DSFX_I3DL2REVERB_HFREFERENCE_DEFAULT = @as(f32, 5000); pub const DSFX_I3DL2REVERB_QUALITY_MIN = @as(u32, 0); pub const DSFX_I3DL2REVERB_QUALITY_MAX = @as(u32, 3); pub const DSFX_I3DL2REVERB_QUALITY_DEFAULT = @as(u32, 2); pub const DSFX_WAVESREVERB_INGAIN_MIN = @as(f32, -96); pub const DSFX_WAVESREVERB_INGAIN_MAX = @as(f32, 0); pub const DSFX_WAVESREVERB_INGAIN_DEFAULT = @as(f32, 0); pub const DSFX_WAVESREVERB_REVERBMIX_MIN = @as(f32, -96); pub const DSFX_WAVESREVERB_REVERBMIX_MAX = @as(f32, 0); pub const DSFX_WAVESREVERB_REVERBMIX_DEFAULT = @as(f32, 0); pub const DSFX_WAVESREVERB_REVERBTIME_MIN = @as(f32, 1.0e-03); pub const DSFX_WAVESREVERB_REVERBTIME_MAX = @as(f32, 3000); pub const DSFX_WAVESREVERB_REVERBTIME_DEFAULT = @as(f32, 1000); pub const DSFX_WAVESREVERB_HIGHFREQRTRATIO_MIN = @as(f32, 1.0e-03); pub const DSFX_WAVESREVERB_HIGHFREQRTRATIO_MAX = @as(f32, 9.99e-01); pub const DSFX_WAVESREVERB_HIGHFREQRTRATIO_DEFAULT = @as(f32, 1.0e-03); pub const DSCFX_AEC_MODE_PASS_THROUGH = @as(u32, 0); pub const DSCFX_AEC_MODE_HALF_DUPLEX = @as(u32, 1); pub const DSCFX_AEC_MODE_FULL_DUPLEX = @as(u32, 2); pub const DSCFX_AEC_STATUS_HISTORY_UNINITIALIZED = @as(u32, 0); pub const DSCFX_AEC_STATUS_HISTORY_CONTINUOUSLY_CONVERGED = @as(u32, 1); pub const DSCFX_AEC_STATUS_HISTORY_PREVIOUSLY_DIVERGED = @as(u32, 2); pub const DSCFX_AEC_STATUS_CURRENTLY_CONVERGED = @as(u32, 8); pub const DS_NO_VIRTUALIZATION = @import("../../zig.zig").typedConst(HRESULT, @as(i32, 142082058)); pub const DSCAPS_PRIMARYMONO = @as(u32, 1); pub const DSCAPS_PRIMARYSTEREO = @as(u32, 2); pub const DSCAPS_PRIMARY8BIT = @as(u32, 4); pub const DSCAPS_PRIMARY16BIT = @as(u32, 8); pub const DSCAPS_CONTINUOUSRATE = @as(u32, 16); pub const DSCAPS_EMULDRIVER = @as(u32, 32); pub const DSCAPS_CERTIFIED = @as(u32, 64); pub const DSCAPS_SECONDARYMONO = @as(u32, 256); pub const DSCAPS_SECONDARYSTEREO = @as(u32, 512); pub const DSCAPS_SECONDARY8BIT = @as(u32, 1024); pub const DSCAPS_SECONDARY16BIT = @as(u32, 2048); pub const DSSCL_NORMAL = @as(u32, 1); pub const DSSCL_PRIORITY = @as(u32, 2); pub const DSSCL_EXCLUSIVE = @as(u32, 3); pub const DSSCL_WRITEPRIMARY = @as(u32, 4); pub const DSSPEAKER_DIRECTOUT = @as(u32, 0); pub const DSSPEAKER_HEADPHONE = @as(u32, 1); pub const DSSPEAKER_MONO = @as(u32, 2); pub const DSSPEAKER_QUAD = @as(u32, 3); pub const DSSPEAKER_STEREO = @as(u32, 4); pub const DSSPEAKER_SURROUND = @as(u32, 5); pub const DSSPEAKER_5POINT1 = @as(u32, 6); pub const DSSPEAKER_7POINT1 = @as(u32, 7); pub const DSSPEAKER_7POINT1_SURROUND = @as(u32, 8); pub const DSSPEAKER_5POINT1_SURROUND = @as(u32, 9); pub const DSSPEAKER_7POINT1_WIDE = @as(u32, 7); pub const DSSPEAKER_5POINT1_BACK = @as(u32, 6); pub const DSSPEAKER_GEOMETRY_MIN = @as(u32, 5); pub const DSSPEAKER_GEOMETRY_NARROW = @as(u32, 10); pub const DSSPEAKER_GEOMETRY_WIDE = @as(u32, 20); pub const DSSPEAKER_GEOMETRY_MAX = @as(u32, 180); pub const DSBCAPS_PRIMARYBUFFER = @as(u32, 1); pub const DSBCAPS_STATIC = @as(u32, 2); pub const DSBCAPS_LOCHARDWARE = @as(u32, 4); pub const DSBCAPS_LOCSOFTWARE = @as(u32, 8); pub const DSBCAPS_CTRL3D = @as(u32, 16); pub const DSBCAPS_CTRLFREQUENCY = @as(u32, 32); pub const DSBCAPS_CTRLPAN = @as(u32, 64); pub const DSBCAPS_CTRLVOLUME = @as(u32, 128); pub const DSBCAPS_CTRLPOSITIONNOTIFY = @as(u32, 256); pub const DSBCAPS_CTRLFX = @as(u32, 512); pub const DSBCAPS_STICKYFOCUS = @as(u32, 16384); pub const DSBCAPS_GLOBALFOCUS = @as(u32, 32768); pub const DSBCAPS_GETCURRENTPOSITION2 = @as(u32, 65536); pub const DSBCAPS_MUTE3DATMAXDISTANCE = @as(u32, 131072); pub const DSBCAPS_LOCDEFER = @as(u32, 262144); pub const DSBCAPS_TRUEPLAYPOSITION = @as(u32, 524288); pub const DSBPLAY_LOOPING = @as(u32, 1); pub const DSBPLAY_LOCHARDWARE = @as(u32, 2); pub const DSBPLAY_LOCSOFTWARE = @as(u32, 4); pub const DSBPLAY_TERMINATEBY_TIME = @as(u32, 8); pub const DSBPLAY_TERMINATEBY_DISTANCE = @as(u64, 16); pub const DSBPLAY_TERMINATEBY_PRIORITY = @as(u64, 32); pub const DSBSTATUS_PLAYING = @as(u32, 1); pub const DSBSTATUS_BUFFERLOST = @as(u32, 2); pub const DSBSTATUS_LOOPING = @as(u32, 4); pub const DSBSTATUS_LOCHARDWARE = @as(u32, 8); pub const DSBSTATUS_LOCSOFTWARE = @as(u32, 16); pub const DSBSTATUS_TERMINATED = @as(u32, 32); pub const DSBLOCK_FROMWRITECURSOR = @as(u32, 1); pub const DSBLOCK_ENTIREBUFFER = @as(u32, 2); pub const DSBFREQUENCY_ORIGINAL = @as(u32, 0); pub const DSBFREQUENCY_MIN = @as(u32, 100); pub const DSBFREQUENCY_MAX = @as(u32, 200000); pub const DSBPAN_LEFT = @as(i32, -10000); pub const DSBPAN_CENTER = @as(u32, 0); pub const DSBPAN_RIGHT = @as(u32, 10000); pub const DSBVOLUME_MIN = @as(i32, -10000); pub const DSBVOLUME_MAX = @as(u32, 0); pub const DSBSIZE_MIN = @as(u32, 4); pub const DSBSIZE_MAX = @as(u32, 268435455); pub const DSBSIZE_FX_MIN = @as(u32, 150); pub const DSBNOTIFICATIONS_MAX = @as(u32, 100000); pub const DS3DMODE_NORMAL = @as(u32, 0); pub const DS3DMODE_HEADRELATIVE = @as(u32, 1); pub const DS3DMODE_DISABLE = @as(u32, 2); pub const DS3D_IMMEDIATE = @as(u32, 0); pub const DS3D_DEFERRED = @as(u32, 1); pub const DS3D_DEFAULTDISTANCEFACTOR = @as(f32, 1); pub const DS3D_MINROLLOFFFACTOR = @as(f32, 0); pub const DS3D_MAXROLLOFFFACTOR = @as(f32, 10); pub const DS3D_DEFAULTROLLOFFFACTOR = @as(f32, 1); pub const DS3D_MINDOPPLERFACTOR = @as(f32, 0); pub const DS3D_MAXDOPPLERFACTOR = @as(f32, 10); pub const DS3D_DEFAULTDOPPLERFACTOR = @as(f32, 1); pub const DS3D_DEFAULTMINDISTANCE = @as(f32, 1); pub const DS3D_DEFAULTMAXDISTANCE = @as(f32, 1.0e+09); pub const DS3D_MINCONEANGLE = @as(u32, 0); pub const DS3D_MAXCONEANGLE = @as(u32, 360); pub const DS3D_DEFAULTCONEANGLE = @as(u32, 360); pub const DS3D_DEFAULTCONEOUTSIDEVOLUME = @as(u32, 0); pub const DSCCAPS_EMULDRIVER = @as(u32, 32); pub const DSCCAPS_CERTIFIED = @as(u32, 64); pub const DSCCAPS_MULTIPLECAPTURE = @as(u32, 1); pub const DSCBCAPS_WAVEMAPPED = @as(u32, 2147483648); pub const DSCBCAPS_CTRLFX = @as(u32, 512); pub const DSCBLOCK_ENTIREBUFFER = @as(u32, 1); pub const DSCBSTATUS_CAPTURING = @as(u32, 1); pub const DSCBSTATUS_LOOPING = @as(u32, 2); pub const DSCBSTART_LOOPING = @as(u32, 1); pub const DSBPN_OFFSETSTOP = @as(u32, 4294967295); pub const DS_CERTIFIED = @as(u32, 0); pub const DS_UNCERTIFIED = @as(u32, 1); pub const DS3DALG_NO_VIRTUALIZATION = Guid.initString("c241333f-1c1b-11d2-94f5-00c04fc28aca"); pub const DS3DALG_HRTF_FULL = Guid.initString("c2413340-1c1b-11d2-94f5-00c04fc28aca"); pub const DS3DALG_HRTF_LIGHT = Guid.initString("c2413342-1c1b-11d2-94f5-00c04fc28aca"); pub const GUID_DSFX_STANDARD_GARGLE = Guid.initString("dafd8210-5711-4b91-9fe3-f75b7ae279bf"); pub const GUID_DSFX_STANDARD_CHORUS = Guid.initString("efe6629c-81f7-4281-bd91-c9d604a95af6"); pub const GUID_DSFX_STANDARD_FLANGER = Guid.initString("efca3d92-dfd8-4672-a603-7420894bad98"); pub const GUID_DSFX_STANDARD_ECHO = Guid.initString("ef3e932c-d40b-4f51-8ccf-3f98f1b29d5d"); pub const GUID_DSFX_STANDARD_DISTORTION = Guid.initString("ef114c90-cd1d-484e-96e5-09cfaf912a21"); pub const GUID_DSFX_STANDARD_COMPRESSOR = Guid.initString("ef011f79-4000-406d-87af-bffb3fc39d57"); pub const GUID_DSFX_STANDARD_PARAMEQ = Guid.initString("120ced89-3bf4-4173-a132-3cb406cf3231"); pub const GUID_DSFX_STANDARD_I3DL2REVERB = Guid.initString("ef985e71-d5c7-42d4-ba4d-2d073e2e96f4"); pub const GUID_DSFX_WAVES_REVERB = Guid.initString("87fc0268-9a55-4360-95aa-004a1d9de26c"); pub const GUID_DSCFX_CLASS_AEC = Guid.initString("bf963d80-c559-11d0-8a2b-00a0c9255ac1"); pub const GUID_DSCFX_MS_AEC = Guid.initString("cdebb919-379a-488a-8765-f53cfd36de40"); pub const GUID_DSCFX_SYSTEM_AEC = Guid.initString("1c22c56d-9879-4f5b-a389-27996ddc2810"); pub const GUID_DSCFX_CLASS_NS = Guid.initString("e07f903f-62fd-4e60-8cdd-dea7236665b5"); pub const GUID_DSCFX_MS_NS = Guid.initString("11c5c73b-66e9-4ba1-a0ba-e814c6eed92d"); pub const GUID_DSCFX_SYSTEM_NS = Guid.initString("5ab0882e-7274-4516-877d-4eee99ba4fd0"); pub const DSFXR_PRESENT = @as(i32, 0); pub const DSFXR_LOCHARDWARE = @as(i32, 1); pub const DSFXR_LOCSOFTWARE = @as(i32, 2); pub const DSFXR_UNALLOCATED = @as(i32, 3); pub const DSFXR_FAILED = @as(i32, 4); pub const DSFXR_UNKNOWN = @as(i32, 5); pub const DSFXR_SENDLOOP = @as(i32, 6); pub const DSFX_I3DL2_MATERIAL_PRESET_SINGLEWINDOW = @as(i32, 0); pub const DSFX_I3DL2_MATERIAL_PRESET_DOUBLEWINDOW = @as(i32, 1); pub const DSFX_I3DL2_MATERIAL_PRESET_THINDOOR = @as(i32, 2); pub const DSFX_I3DL2_MATERIAL_PRESET_THICKDOOR = @as(i32, 3); pub const DSFX_I3DL2_MATERIAL_PRESET_WOODWALL = @as(i32, 4); pub const DSFX_I3DL2_MATERIAL_PRESET_BRICKWALL = @as(i32, 5); pub const DSFX_I3DL2_MATERIAL_PRESET_STONEWALL = @as(i32, 6); pub const DSFX_I3DL2_MATERIAL_PRESET_CURTAIN = @as(i32, 7); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_DEFAULT = @as(i32, 0); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_GENERIC = @as(i32, 1); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PADDEDCELL = @as(i32, 2); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_ROOM = @as(i32, 3); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_BATHROOM = @as(i32, 4); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_LIVINGROOM = @as(i32, 5); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_STONEROOM = @as(i32, 6); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_AUDITORIUM = @as(i32, 7); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CONCERTHALL = @as(i32, 8); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CAVE = @as(i32, 9); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_ARENA = @as(i32, 10); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_HANGAR = @as(i32, 11); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CARPETEDHALLWAY = @as(i32, 12); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_HALLWAY = @as(i32, 13); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_STONECORRIDOR = @as(i32, 14); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_ALLEY = @as(i32, 15); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_FOREST = @as(i32, 16); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_CITY = @as(i32, 17); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_MOUNTAINS = @as(i32, 18); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_QUARRY = @as(i32, 19); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PLAIN = @as(i32, 20); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PARKINGLOT = @as(i32, 21); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_SEWERPIPE = @as(i32, 22); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_UNDERWATER = @as(i32, 23); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_SMALLROOM = @as(i32, 24); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMROOM = @as(i32, 25); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEROOM = @as(i32, 26); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_MEDIUMHALL = @as(i32, 27); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_LARGEHALL = @as(i32, 28); pub const DSFX_I3DL2_ENVIRONMENT_PRESET_PLATE = @as(i32, 29); //-------------------------------------------------------------------------------- // Section: Types (48) //-------------------------------------------------------------------------------- pub const DSCAPS = extern struct { dwSize: u32, dwFlags: u32, dwMinSecondarySampleRate: u32, dwMaxSecondarySampleRate: u32, dwPrimaryBuffers: u32, dwMaxHwMixingAllBuffers: u32, dwMaxHwMixingStaticBuffers: u32, dwMaxHwMixingStreamingBuffers: u32, dwFreeHwMixingAllBuffers: u32, dwFreeHwMixingStaticBuffers: u32, dwFreeHwMixingStreamingBuffers: u32, dwMaxHw3DAllBuffers: u32, dwMaxHw3DStaticBuffers: u32, dwMaxHw3DStreamingBuffers: u32, dwFreeHw3DAllBuffers: u32, dwFreeHw3DStaticBuffers: u32, dwFreeHw3DStreamingBuffers: u32, dwTotalHwMemBytes: u32, dwFreeHwMemBytes: u32, dwMaxContigFreeHwMemBytes: u32, dwUnlockTransferRateHwBuffers: u32, dwPlayCpuOverheadSwBuffers: u32, dwReserved1: u32, dwReserved2: u32, }; pub const DSBCAPS = extern struct { dwSize: u32, dwFlags: u32, dwBufferBytes: u32, dwUnlockTransferRate: u32, dwPlayCpuOverhead: u32, }; pub const DSEFFECTDESC = extern struct { dwSize: u32, dwFlags: u32, guidDSFXClass: Guid, dwReserved1: usize, dwReserved2: usize, }; pub const DSCEFFECTDESC = extern struct { dwSize: u32, dwFlags: u32, guidDSCFXClass: Guid, guidDSCFXInstance: Guid, dwReserved1: u32, dwReserved2: u32, }; pub const DSBUFFERDESC = extern struct { dwSize: u32, dwFlags: u32, dwBufferBytes: u32, dwReserved: u32, lpwfxFormat: ?*WAVEFORMATEX, guid3DAlgorithm: Guid, }; pub const DSBUFFERDESC1 = extern struct { dwSize: u32, dwFlags: u32, dwBufferBytes: u32, dwReserved: u32, lpwfxFormat: ?*WAVEFORMATEX, }; pub const DS3DBUFFER = extern struct { dwSize: u32, vPosition: D3DVECTOR, vVelocity: D3DVECTOR, dwInsideConeAngle: u32, dwOutsideConeAngle: u32, vConeOrientation: D3DVECTOR, lConeOutsideVolume: i32, flMinDistance: f32, flMaxDistance: f32, dwMode: u32, }; pub const DS3DLISTENER = extern struct { dwSize: u32, vPosition: D3DVECTOR, vVelocity: D3DVECTOR, vOrientFront: D3DVECTOR, vOrientTop: D3DVECTOR, flDistanceFactor: f32, flRolloffFactor: f32, flDopplerFactor: f32, }; pub const DSCCAPS = extern struct { dwSize: u32, dwFlags: u32, dwFormats: u32, dwChannels: u32, }; pub const DSCBUFFERDESC1 = extern struct { dwSize: u32, dwFlags: u32, dwBufferBytes: u32, dwReserved: u32, lpwfxFormat: ?*WAVEFORMATEX, }; pub const DSCBUFFERDESC = extern struct { dwSize: u32, dwFlags: u32, dwBufferBytes: u32, dwReserved: u32, lpwfxFormat: ?*WAVEFORMATEX, dwFXCount: u32, lpDSCFXDesc: ?*DSCEFFECTDESC, }; pub const DSCBCAPS = extern struct { dwSize: u32, dwFlags: u32, dwBufferBytes: u32, dwReserved: u32, }; pub const DSBPOSITIONNOTIFY = extern struct { dwOffset: u32, hEventNotify: ?HANDLE, }; pub const LPDSENUMCALLBACKA = fn( param0: ?*Guid, param1: ?[*:0]const u8, param2: ?[*:0]const u8, param3: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const LPDSENUMCALLBACKW = fn( param0: ?*Guid, param1: ?[*:0]const u16, param2: ?[*:0]const u16, param3: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; const IID_IDirectSound_Value = @import("../../zig.zig").Guid.initString("279afa83-4981-11ce-a521-0020af0be560"); pub const IID_IDirectSound = &IID_IDirectSound_Value; pub const IDirectSound = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateSoundBuffer: fn( self: *const IDirectSound, pcDSBufferDesc: ?*DSBUFFERDESC, ppDSBuffer: ?*?*IDirectSoundBuffer, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectSound, pDSCaps: ?*DSCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DuplicateSoundBuffer: fn( self: *const IDirectSound, pDSBufferOriginal: ?*IDirectSoundBuffer, ppDSBufferDuplicate: ?*?*IDirectSoundBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCooperativeLevel: fn( self: *const IDirectSound, hwnd: ?HWND, dwLevel: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Compact: fn( self: *const IDirectSound, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSpeakerConfig: fn( self: *const IDirectSound, pdwSpeakerConfig: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSpeakerConfig: fn( self: *const IDirectSound, dwSpeakerConfig: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectSound, pcGuidDevice: ?*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 IDirectSound_CreateSoundBuffer(self: *const T, pcDSBufferDesc: ?*DSBUFFERDESC, ppDSBuffer: ?*?*IDirectSoundBuffer, pUnkOuter: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).CreateSoundBuffer(@ptrCast(*const IDirectSound, self), pcDSBufferDesc, ppDSBuffer, pUnkOuter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_GetCaps(self: *const T, pDSCaps: ?*DSCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectSound, self), pDSCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_DuplicateSoundBuffer(self: *const T, pDSBufferOriginal: ?*IDirectSoundBuffer, ppDSBufferDuplicate: ?*?*IDirectSoundBuffer) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).DuplicateSoundBuffer(@ptrCast(*const IDirectSound, self), pDSBufferOriginal, ppDSBufferDuplicate); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_SetCooperativeLevel(self: *const T, hwnd: ?HWND, dwLevel: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).SetCooperativeLevel(@ptrCast(*const IDirectSound, self), hwnd, dwLevel); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_Compact(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).Compact(@ptrCast(*const IDirectSound, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_GetSpeakerConfig(self: *const T, pdwSpeakerConfig: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).GetSpeakerConfig(@ptrCast(*const IDirectSound, self), pdwSpeakerConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_SetSpeakerConfig(self: *const T, dwSpeakerConfig: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).SetSpeakerConfig(@ptrCast(*const IDirectSound, self), dwSpeakerConfig); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound_Initialize(self: *const T, pcGuidDevice: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound.VTable, self.vtable).Initialize(@ptrCast(*const IDirectSound, self), pcGuidDevice); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSound8_Value = @import("../../zig.zig").Guid.initString("c50a7e93-f395-4834-9ef6-7fa99de50966"); pub const IID_IDirectSound8 = &IID_IDirectSound8_Value; pub const IDirectSound8 = extern struct { pub const VTable = extern struct { base: IDirectSound.VTable, VerifyCertification: fn( self: *const IDirectSound8, pdwCertified: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDirectSound.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound8_VerifyCertification(self: *const T, pdwCertified: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound8.VTable, self.vtable).VerifyCertification(@ptrCast(*const IDirectSound8, self), pdwCertified); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundBuffer_Value = @import("../../zig.zig").Guid.initString("279afa85-4981-11ce-a521-0020af0be560"); pub const IID_IDirectSoundBuffer = &IID_IDirectSoundBuffer_Value; pub const IDirectSoundBuffer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCaps: fn( self: *const IDirectSoundBuffer, pDSBufferCaps: ?*DSBCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCurrentPosition: fn( self: *const IDirectSoundBuffer, pdwCurrentPlayCursor: ?*u32, pdwCurrentWriteCursor: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormat: fn( self: *const IDirectSoundBuffer, // TODO: what to do with BytesParamIndex 1? pwfxFormat: ?*WAVEFORMATEX, dwSizeAllocated: u32, pdwSizeWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVolume: fn( self: *const IDirectSoundBuffer, plVolume: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPan: fn( self: *const IDirectSoundBuffer, plPan: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFrequency: fn( self: *const IDirectSoundBuffer, pdwFrequency: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const IDirectSoundBuffer, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectSoundBuffer, pDirectSound: ?*IDirectSound, pcDSBufferDesc: ?*DSBUFFERDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectSoundBuffer, dwOffset: u32, dwBytes: u32, ppvAudioPtr1: ?*?*anyopaque, pdwAudioBytes1: ?*u32, ppvAudioPtr2: ?*?*anyopaque, pdwAudioBytes2: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Play: fn( self: *const IDirectSoundBuffer, dwReserved1: u32, dwPriority: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetCurrentPosition: fn( self: *const IDirectSoundBuffer, dwNewPosition: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFormat: fn( self: *const IDirectSoundBuffer, pcfxFormat: ?*WAVEFORMATEX, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVolume: fn( self: *const IDirectSoundBuffer, lVolume: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPan: fn( self: *const IDirectSoundBuffer, lPan: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFrequency: fn( self: *const IDirectSoundBuffer, dwFrequency: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IDirectSoundBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectSoundBuffer, // TODO: what to do with BytesParamIndex 1? pvAudioPtr1: ?*anyopaque, dwAudioBytes1: u32, // TODO: what to do with BytesParamIndex 3? pvAudioPtr2: ?*anyopaque, dwAudioBytes2: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Restore: fn( self: *const IDirectSoundBuffer, ) 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 IDirectSoundBuffer_GetCaps(self: *const T, pDSBufferCaps: ?*DSBCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectSoundBuffer, self), pDSBufferCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_GetCurrentPosition(self: *const T, pdwCurrentPlayCursor: ?*u32, pdwCurrentWriteCursor: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetCurrentPosition(@ptrCast(*const IDirectSoundBuffer, self), pdwCurrentPlayCursor, pdwCurrentWriteCursor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_GetFormat(self: *const T, pwfxFormat: ?*WAVEFORMATEX, dwSizeAllocated: u32, pdwSizeWritten: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetFormat(@ptrCast(*const IDirectSoundBuffer, self), pwfxFormat, dwSizeAllocated, pdwSizeWritten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_GetVolume(self: *const T, plVolume: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetVolume(@ptrCast(*const IDirectSoundBuffer, self), plVolume); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_GetPan(self: *const T, plPan: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetPan(@ptrCast(*const IDirectSoundBuffer, self), plPan); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_GetFrequency(self: *const T, pdwFrequency: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetFrequency(@ptrCast(*const IDirectSoundBuffer, self), pdwFrequency); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_GetStatus(self: *const T, pdwStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).GetStatus(@ptrCast(*const IDirectSoundBuffer, self), pdwStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_Initialize(self: *const T, pDirectSound: ?*IDirectSound, pcDSBufferDesc: ?*DSBUFFERDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).Initialize(@ptrCast(*const IDirectSoundBuffer, self), pDirectSound, pcDSBufferDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_Lock(self: *const T, dwOffset: u32, dwBytes: u32, ppvAudioPtr1: ?*?*anyopaque, pdwAudioBytes1: ?*u32, ppvAudioPtr2: ?*?*anyopaque, pdwAudioBytes2: ?*u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).Lock(@ptrCast(*const IDirectSoundBuffer, self), dwOffset, dwBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_Play(self: *const T, dwReserved1: u32, dwPriority: u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).Play(@ptrCast(*const IDirectSoundBuffer, self), dwReserved1, dwPriority, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_SetCurrentPosition(self: *const T, dwNewPosition: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).SetCurrentPosition(@ptrCast(*const IDirectSoundBuffer, self), dwNewPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_SetFormat(self: *const T, pcfxFormat: ?*WAVEFORMATEX) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).SetFormat(@ptrCast(*const IDirectSoundBuffer, self), pcfxFormat); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_SetVolume(self: *const T, lVolume: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).SetVolume(@ptrCast(*const IDirectSoundBuffer, self), lVolume); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_SetPan(self: *const T, lPan: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).SetPan(@ptrCast(*const IDirectSoundBuffer, self), lPan); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_SetFrequency(self: *const T, dwFrequency: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).SetFrequency(@ptrCast(*const IDirectSoundBuffer, self), dwFrequency); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).Stop(@ptrCast(*const IDirectSoundBuffer, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_Unlock(self: *const T, pvAudioPtr1: ?*anyopaque, dwAudioBytes1: u32, pvAudioPtr2: ?*anyopaque, dwAudioBytes2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).Unlock(@ptrCast(*const IDirectSoundBuffer, self), pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer_Restore(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer.VTable, self.vtable).Restore(@ptrCast(*const IDirectSoundBuffer, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundBuffer8_Value = @import("../../zig.zig").Guid.initString("6825a449-7524-4d82-920f-50e36ab3ab1e"); pub const IID_IDirectSoundBuffer8 = &IID_IDirectSoundBuffer8_Value; pub const IDirectSoundBuffer8 = extern struct { pub const VTable = extern struct { base: IDirectSoundBuffer.VTable, SetFX: fn( self: *const IDirectSoundBuffer8, dwEffectsCount: u32, pDSFXDesc: ?[*]DSEFFECTDESC, pdwResultCodes: ?[*]u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AcquireResources: fn( self: *const IDirectSoundBuffer8, dwFlags: u32, dwEffectsCount: u32, pdwResultCodes: [*]u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetObjectInPath: fn( self: *const IDirectSoundBuffer8, rguidObject: ?*const Guid, dwIndex: u32, rguidInterface: ?*const Guid, ppObject: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDirectSoundBuffer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer8_SetFX(self: *const T, dwEffectsCount: u32, pDSFXDesc: ?[*]DSEFFECTDESC, pdwResultCodes: ?[*]u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer8.VTable, self.vtable).SetFX(@ptrCast(*const IDirectSoundBuffer8, self), dwEffectsCount, pDSFXDesc, pdwResultCodes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer8_AcquireResources(self: *const T, dwFlags: u32, dwEffectsCount: u32, pdwResultCodes: [*]u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer8.VTable, self.vtable).AcquireResources(@ptrCast(*const IDirectSoundBuffer8, self), dwFlags, dwEffectsCount, pdwResultCodes); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundBuffer8_GetObjectInPath(self: *const T, rguidObject: ?*const Guid, dwIndex: u32, rguidInterface: ?*const Guid, ppObject: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundBuffer8.VTable, self.vtable).GetObjectInPath(@ptrCast(*const IDirectSoundBuffer8, self), rguidObject, dwIndex, rguidInterface, ppObject); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSound3DListener_Value = @import("../../zig.zig").Guid.initString("279afa84-4981-11ce-a521-0020af0be560"); pub const IID_IDirectSound3DListener = &IID_IDirectSound3DListener_Value; pub const IDirectSound3DListener = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetAllParameters: fn( self: *const IDirectSound3DListener, pListener: ?*DS3DLISTENER, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDistanceFactor: fn( self: *const IDirectSound3DListener, pflDistanceFactor: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDopplerFactor: fn( self: *const IDirectSound3DListener, pflDopplerFactor: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOrientation: fn( self: *const IDirectSound3DListener, pvOrientFront: ?*D3DVECTOR, pvOrientTop: ?*D3DVECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPosition: fn( self: *const IDirectSound3DListener, pvPosition: ?*D3DVECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetRolloffFactor: fn( self: *const IDirectSound3DListener, pflRolloffFactor: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVelocity: fn( self: *const IDirectSound3DListener, pvVelocity: ?*D3DVECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllParameters: fn( self: *const IDirectSound3DListener, pcListener: ?*DS3DLISTENER, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDistanceFactor: fn( self: *const IDirectSound3DListener, flDistanceFactor: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDopplerFactor: fn( self: *const IDirectSound3DListener, flDopplerFactor: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOrientation: fn( self: *const IDirectSound3DListener, xFront: f32, yFront: f32, zFront: f32, xTop: f32, yTop: f32, zTop: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPosition: fn( self: *const IDirectSound3DListener, x: f32, y: f32, z: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetRolloffFactor: fn( self: *const IDirectSound3DListener, flRolloffFactor: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVelocity: fn( self: *const IDirectSound3DListener, x: f32, y: f32, z: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommitDeferredSettings: fn( self: *const IDirectSound3DListener, ) 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 IDirectSound3DListener_GetAllParameters(self: *const T, pListener: ?*DS3DLISTENER) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSound3DListener, self), pListener); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_GetDistanceFactor(self: *const T, pflDistanceFactor: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetDistanceFactor(@ptrCast(*const IDirectSound3DListener, self), pflDistanceFactor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_GetDopplerFactor(self: *const T, pflDopplerFactor: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetDopplerFactor(@ptrCast(*const IDirectSound3DListener, self), pflDopplerFactor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_GetOrientation(self: *const T, pvOrientFront: ?*D3DVECTOR, pvOrientTop: ?*D3DVECTOR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetOrientation(@ptrCast(*const IDirectSound3DListener, self), pvOrientFront, pvOrientTop); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_GetPosition(self: *const T, pvPosition: ?*D3DVECTOR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetPosition(@ptrCast(*const IDirectSound3DListener, self), pvPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_GetRolloffFactor(self: *const T, pflRolloffFactor: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetRolloffFactor(@ptrCast(*const IDirectSound3DListener, self), pflRolloffFactor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_GetVelocity(self: *const T, pvVelocity: ?*D3DVECTOR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).GetVelocity(@ptrCast(*const IDirectSound3DListener, self), pvVelocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetAllParameters(self: *const T, pcListener: ?*DS3DLISTENER, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSound3DListener, self), pcListener, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetDistanceFactor(self: *const T, flDistanceFactor: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetDistanceFactor(@ptrCast(*const IDirectSound3DListener, self), flDistanceFactor, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetDopplerFactor(self: *const T, flDopplerFactor: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetDopplerFactor(@ptrCast(*const IDirectSound3DListener, self), flDopplerFactor, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetOrientation(self: *const T, xFront: f32, yFront: f32, zFront: f32, xTop: f32, yTop: f32, zTop: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetOrientation(@ptrCast(*const IDirectSound3DListener, self), xFront, yFront, zFront, xTop, yTop, zTop, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetPosition(self: *const T, x: f32, y: f32, z: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetPosition(@ptrCast(*const IDirectSound3DListener, self), x, y, z, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetRolloffFactor(self: *const T, flRolloffFactor: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetRolloffFactor(@ptrCast(*const IDirectSound3DListener, self), flRolloffFactor, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_SetVelocity(self: *const T, x: f32, y: f32, z: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).SetVelocity(@ptrCast(*const IDirectSound3DListener, self), x, y, z, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DListener_CommitDeferredSettings(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DListener.VTable, self.vtable).CommitDeferredSettings(@ptrCast(*const IDirectSound3DListener, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSound3DBuffer_Value = @import("../../zig.zig").Guid.initString("279afa86-4981-11ce-a521-0020af0be560"); pub const IID_IDirectSound3DBuffer = &IID_IDirectSound3DBuffer_Value; pub const IDirectSound3DBuffer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetAllParameters: fn( self: *const IDirectSound3DBuffer, pDs3dBuffer: ?*DS3DBUFFER, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConeAngles: fn( self: *const IDirectSound3DBuffer, pdwInsideConeAngle: ?*u32, pdwOutsideConeAngle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConeOrientation: fn( self: *const IDirectSound3DBuffer, pvOrientation: ?*D3DVECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetConeOutsideVolume: fn( self: *const IDirectSound3DBuffer, plConeOutsideVolume: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMaxDistance: fn( self: *const IDirectSound3DBuffer, pflMaxDistance: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMinDistance: fn( self: *const IDirectSound3DBuffer, pflMinDistance: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetMode: fn( self: *const IDirectSound3DBuffer, pdwMode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPosition: fn( self: *const IDirectSound3DBuffer, pvPosition: ?*D3DVECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVelocity: fn( self: *const IDirectSound3DBuffer, pvVelocity: ?*D3DVECTOR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetAllParameters: fn( self: *const IDirectSound3DBuffer, pcDs3dBuffer: ?*DS3DBUFFER, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetConeAngles: fn( self: *const IDirectSound3DBuffer, dwInsideConeAngle: u32, dwOutsideConeAngle: u32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetConeOrientation: fn( self: *const IDirectSound3DBuffer, x: f32, y: f32, z: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetConeOutsideVolume: fn( self: *const IDirectSound3DBuffer, lConeOutsideVolume: i32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMaxDistance: fn( self: *const IDirectSound3DBuffer, flMaxDistance: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMinDistance: fn( self: *const IDirectSound3DBuffer, flMinDistance: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMode: fn( self: *const IDirectSound3DBuffer, dwMode: u32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPosition: fn( self: *const IDirectSound3DBuffer, x: f32, y: f32, z: f32, dwApply: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetVelocity: fn( self: *const IDirectSound3DBuffer, x: f32, y: f32, z: f32, dwApply: 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 IDirectSound3DBuffer_GetAllParameters(self: *const T, pDs3dBuffer: ?*DS3DBUFFER) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSound3DBuffer, self), pDs3dBuffer); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetConeAngles(self: *const T, pdwInsideConeAngle: ?*u32, pdwOutsideConeAngle: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetConeAngles(@ptrCast(*const IDirectSound3DBuffer, self), pdwInsideConeAngle, pdwOutsideConeAngle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetConeOrientation(self: *const T, pvOrientation: ?*D3DVECTOR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetConeOrientation(@ptrCast(*const IDirectSound3DBuffer, self), pvOrientation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetConeOutsideVolume(self: *const T, plConeOutsideVolume: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetConeOutsideVolume(@ptrCast(*const IDirectSound3DBuffer, self), plConeOutsideVolume); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetMaxDistance(self: *const T, pflMaxDistance: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetMaxDistance(@ptrCast(*const IDirectSound3DBuffer, self), pflMaxDistance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetMinDistance(self: *const T, pflMinDistance: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetMinDistance(@ptrCast(*const IDirectSound3DBuffer, self), pflMinDistance); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetMode(self: *const T, pdwMode: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetMode(@ptrCast(*const IDirectSound3DBuffer, self), pdwMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetPosition(self: *const T, pvPosition: ?*D3DVECTOR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetPosition(@ptrCast(*const IDirectSound3DBuffer, self), pvPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_GetVelocity(self: *const T, pvVelocity: ?*D3DVECTOR) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).GetVelocity(@ptrCast(*const IDirectSound3DBuffer, self), pvVelocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetAllParameters(self: *const T, pcDs3dBuffer: ?*DS3DBUFFER, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSound3DBuffer, self), pcDs3dBuffer, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetConeAngles(self: *const T, dwInsideConeAngle: u32, dwOutsideConeAngle: u32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetConeAngles(@ptrCast(*const IDirectSound3DBuffer, self), dwInsideConeAngle, dwOutsideConeAngle, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetConeOrientation(self: *const T, x: f32, y: f32, z: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetConeOrientation(@ptrCast(*const IDirectSound3DBuffer, self), x, y, z, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetConeOutsideVolume(self: *const T, lConeOutsideVolume: i32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetConeOutsideVolume(@ptrCast(*const IDirectSound3DBuffer, self), lConeOutsideVolume, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetMaxDistance(self: *const T, flMaxDistance: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetMaxDistance(@ptrCast(*const IDirectSound3DBuffer, self), flMaxDistance, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetMinDistance(self: *const T, flMinDistance: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetMinDistance(@ptrCast(*const IDirectSound3DBuffer, self), flMinDistance, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetMode(self: *const T, dwMode: u32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetMode(@ptrCast(*const IDirectSound3DBuffer, self), dwMode, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetPosition(self: *const T, x: f32, y: f32, z: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetPosition(@ptrCast(*const IDirectSound3DBuffer, self), x, y, z, dwApply); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSound3DBuffer_SetVelocity(self: *const T, x: f32, y: f32, z: f32, dwApply: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSound3DBuffer.VTable, self.vtable).SetVelocity(@ptrCast(*const IDirectSound3DBuffer, self), x, y, z, dwApply); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundCapture_Value = @import("../../zig.zig").Guid.initString("b0210781-89cd-11d0-af08-00a0c925cd16"); pub const IID_IDirectSoundCapture = &IID_IDirectSoundCapture_Value; pub const IDirectSoundCapture = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateCaptureBuffer: fn( self: *const IDirectSoundCapture, pcDSCBufferDesc: ?*DSCBUFFERDESC, ppDSCBuffer: ?*?*IDirectSoundCaptureBuffer, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCaps: fn( self: *const IDirectSoundCapture, pDSCCaps: ?*DSCCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectSoundCapture, pcGuidDevice: ?*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 IDirectSoundCapture_CreateCaptureBuffer(self: *const T, pcDSCBufferDesc: ?*DSCBUFFERDESC, ppDSCBuffer: ?*?*IDirectSoundCaptureBuffer, pUnkOuter: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCapture.VTable, self.vtable).CreateCaptureBuffer(@ptrCast(*const IDirectSoundCapture, self), pcDSCBufferDesc, ppDSCBuffer, pUnkOuter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCapture_GetCaps(self: *const T, pDSCCaps: ?*DSCCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCapture.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectSoundCapture, self), pDSCCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCapture_Initialize(self: *const T, pcGuidDevice: ?*const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCapture.VTable, self.vtable).Initialize(@ptrCast(*const IDirectSoundCapture, self), pcGuidDevice); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundCaptureBuffer_Value = @import("../../zig.zig").Guid.initString("b0210782-89cd-11d0-af08-00a0c925cd16"); pub const IID_IDirectSoundCaptureBuffer = &IID_IDirectSoundCaptureBuffer_Value; pub const IDirectSoundCaptureBuffer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetCaps: fn( self: *const IDirectSoundCaptureBuffer, pDSCBCaps: ?*DSCBCAPS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCurrentPosition: fn( self: *const IDirectSoundCaptureBuffer, pdwCapturePosition: ?*u32, pdwReadPosition: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFormat: fn( self: *const IDirectSoundCaptureBuffer, // TODO: what to do with BytesParamIndex 1? pwfxFormat: ?*WAVEFORMATEX, dwSizeAllocated: u32, pdwSizeWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const IDirectSoundCaptureBuffer, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Initialize: fn( self: *const IDirectSoundCaptureBuffer, pDirectSoundCapture: ?*IDirectSoundCapture, pcDSCBufferDesc: ?*DSCBUFFERDESC, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Lock: fn( self: *const IDirectSoundCaptureBuffer, dwOffset: u32, dwBytes: u32, ppvAudioPtr1: ?*?*anyopaque, pdwAudioBytes1: ?*u32, ppvAudioPtr2: ?*?*anyopaque, pdwAudioBytes2: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Start: fn( self: *const IDirectSoundCaptureBuffer, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Stop: fn( self: *const IDirectSoundCaptureBuffer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Unlock: fn( self: *const IDirectSoundCaptureBuffer, // TODO: what to do with BytesParamIndex 1? pvAudioPtr1: ?*anyopaque, dwAudioBytes1: u32, // TODO: what to do with BytesParamIndex 3? pvAudioPtr2: ?*anyopaque, dwAudioBytes2: 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 IDirectSoundCaptureBuffer_GetCaps(self: *const T, pDSCBCaps: ?*DSCBCAPS) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).GetCaps(@ptrCast(*const IDirectSoundCaptureBuffer, self), pDSCBCaps); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_GetCurrentPosition(self: *const T, pdwCapturePosition: ?*u32, pdwReadPosition: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).GetCurrentPosition(@ptrCast(*const IDirectSoundCaptureBuffer, self), pdwCapturePosition, pdwReadPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_GetFormat(self: *const T, pwfxFormat: ?*WAVEFORMATEX, dwSizeAllocated: u32, pdwSizeWritten: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).GetFormat(@ptrCast(*const IDirectSoundCaptureBuffer, self), pwfxFormat, dwSizeAllocated, pdwSizeWritten); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_GetStatus(self: *const T, pdwStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).GetStatus(@ptrCast(*const IDirectSoundCaptureBuffer, self), pdwStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_Initialize(self: *const T, pDirectSoundCapture: ?*IDirectSoundCapture, pcDSCBufferDesc: ?*DSCBUFFERDESC) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).Initialize(@ptrCast(*const IDirectSoundCaptureBuffer, self), pDirectSoundCapture, pcDSCBufferDesc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_Lock(self: *const T, dwOffset: u32, dwBytes: u32, ppvAudioPtr1: ?*?*anyopaque, pdwAudioBytes1: ?*u32, ppvAudioPtr2: ?*?*anyopaque, pdwAudioBytes2: ?*u32, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).Lock(@ptrCast(*const IDirectSoundCaptureBuffer, self), dwOffset, dwBytes, ppvAudioPtr1, pdwAudioBytes1, ppvAudioPtr2, pdwAudioBytes2, dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_Start(self: *const T, dwFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).Start(@ptrCast(*const IDirectSoundCaptureBuffer, self), dwFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_Stop(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).Stop(@ptrCast(*const IDirectSoundCaptureBuffer, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer_Unlock(self: *const T, pvAudioPtr1: ?*anyopaque, dwAudioBytes1: u32, pvAudioPtr2: ?*anyopaque, dwAudioBytes2: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer.VTable, self.vtable).Unlock(@ptrCast(*const IDirectSoundCaptureBuffer, self), pvAudioPtr1, dwAudioBytes1, pvAudioPtr2, dwAudioBytes2); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundCaptureBuffer8_Value = @import("../../zig.zig").Guid.initString("00990df4-0dbb-4872-833e-6d303e80aeb6"); pub const IID_IDirectSoundCaptureBuffer8 = &IID_IDirectSoundCaptureBuffer8_Value; pub const IDirectSoundCaptureBuffer8 = extern struct { pub const VTable = extern struct { base: IDirectSoundCaptureBuffer.VTable, GetObjectInPath: fn( self: *const IDirectSoundCaptureBuffer8, rguidObject: ?*const Guid, dwIndex: u32, rguidInterface: ?*const Guid, ppObject: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFXStatus: fn( self: *const IDirectSoundCaptureBuffer8, dwEffectsCount: u32, pdwFXStatus: [*]u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDirectSoundCaptureBuffer.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer8_GetObjectInPath(self: *const T, rguidObject: ?*const Guid, dwIndex: u32, rguidInterface: ?*const Guid, ppObject: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer8.VTable, self.vtable).GetObjectInPath(@ptrCast(*const IDirectSoundCaptureBuffer8, self), rguidObject, dwIndex, rguidInterface, ppObject); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureBuffer8_GetFXStatus(self: *const T, dwEffectsCount: u32, pdwFXStatus: [*]u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureBuffer8.VTable, self.vtable).GetFXStatus(@ptrCast(*const IDirectSoundCaptureBuffer8, self), dwEffectsCount, pdwFXStatus); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundNotify_Value = @import("../../zig.zig").Guid.initString("b0210783-89cd-11d0-af08-00a0c925cd16"); pub const IID_IDirectSoundNotify = &IID_IDirectSoundNotify_Value; pub const IDirectSoundNotify = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetNotificationPositions: fn( self: *const IDirectSoundNotify, dwPositionNotifies: u32, pcPositionNotifies: [*]DSBPOSITIONNOTIFY, ) 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 IDirectSoundNotify_SetNotificationPositions(self: *const T, dwPositionNotifies: u32, pcPositionNotifies: [*]DSBPOSITIONNOTIFY) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundNotify.VTable, self.vtable).SetNotificationPositions(@ptrCast(*const IDirectSoundNotify, self), dwPositionNotifies, pcPositionNotifies); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXGargle = extern struct { dwRateHz: u32, dwWaveShape: u32, }; const IID_IDirectSoundFXGargle_Value = @import("../../zig.zig").Guid.initString("d616f352-d622-11ce-aac5-0020af0b99a3"); pub const IID_IDirectSoundFXGargle = &IID_IDirectSoundFXGargle_Value; pub const IDirectSoundFXGargle = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXGargle, pcDsFxGargle: ?*DSFXGargle, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXGargle, pDsFxGargle: ?*DSFXGargle, ) 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 IDirectSoundFXGargle_SetAllParameters(self: *const T, pcDsFxGargle: ?*DSFXGargle) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXGargle.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXGargle, self), pcDsFxGargle); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXGargle_GetAllParameters(self: *const T, pDsFxGargle: ?*DSFXGargle) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXGargle.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXGargle, self), pDsFxGargle); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXChorus = extern struct { fWetDryMix: f32, fDepth: f32, fFeedback: f32, fFrequency: f32, lWaveform: i32, fDelay: f32, lPhase: i32, }; const IID_IDirectSoundFXChorus_Value = @import("../../zig.zig").Guid.initString("880842e3-145f-43e6-a934-a71806e50547"); pub const IID_IDirectSoundFXChorus = &IID_IDirectSoundFXChorus_Value; pub const IDirectSoundFXChorus = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXChorus, pcDsFxChorus: ?*DSFXChorus, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXChorus, pDsFxChorus: ?*DSFXChorus, ) 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 IDirectSoundFXChorus_SetAllParameters(self: *const T, pcDsFxChorus: ?*DSFXChorus) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXChorus.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXChorus, self), pcDsFxChorus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXChorus_GetAllParameters(self: *const T, pDsFxChorus: ?*DSFXChorus) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXChorus.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXChorus, self), pDsFxChorus); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXFlanger = extern struct { fWetDryMix: f32, fDepth: f32, fFeedback: f32, fFrequency: f32, lWaveform: i32, fDelay: f32, lPhase: i32, }; const IID_IDirectSoundFXFlanger_Value = @import("../../zig.zig").Guid.initString("903e9878-2c92-4072-9b2c-ea68f5396783"); pub const IID_IDirectSoundFXFlanger = &IID_IDirectSoundFXFlanger_Value; pub const IDirectSoundFXFlanger = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXFlanger, pcDsFxFlanger: ?*DSFXFlanger, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXFlanger, pDsFxFlanger: ?*DSFXFlanger, ) 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 IDirectSoundFXFlanger_SetAllParameters(self: *const T, pcDsFxFlanger: ?*DSFXFlanger) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXFlanger.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXFlanger, self), pcDsFxFlanger); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXFlanger_GetAllParameters(self: *const T, pDsFxFlanger: ?*DSFXFlanger) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXFlanger.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXFlanger, self), pDsFxFlanger); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXEcho = extern struct { fWetDryMix: f32, fFeedback: f32, fLeftDelay: f32, fRightDelay: f32, lPanDelay: i32, }; const IID_IDirectSoundFXEcho_Value = @import("../../zig.zig").Guid.initString("8bd28edf-50db-4e92-a2bd-445488d1ed42"); pub const IID_IDirectSoundFXEcho = &IID_IDirectSoundFXEcho_Value; pub const IDirectSoundFXEcho = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXEcho, pcDsFxEcho: ?*DSFXEcho, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXEcho, pDsFxEcho: ?*DSFXEcho, ) 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 IDirectSoundFXEcho_SetAllParameters(self: *const T, pcDsFxEcho: ?*DSFXEcho) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXEcho.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXEcho, self), pcDsFxEcho); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXEcho_GetAllParameters(self: *const T, pDsFxEcho: ?*DSFXEcho) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXEcho.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXEcho, self), pDsFxEcho); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXDistortion = extern struct { fGain: f32, fEdge: f32, fPostEQCenterFrequency: f32, fPostEQBandwidth: f32, fPreLowpassCutoff: f32, }; const IID_IDirectSoundFXDistortion_Value = @import("../../zig.zig").Guid.initString("8ecf4326-455f-4d8b-bda9-8d5d3e9e3e0b"); pub const IID_IDirectSoundFXDistortion = &IID_IDirectSoundFXDistortion_Value; pub const IDirectSoundFXDistortion = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXDistortion, pcDsFxDistortion: ?*DSFXDistortion, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXDistortion, pDsFxDistortion: ?*DSFXDistortion, ) 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 IDirectSoundFXDistortion_SetAllParameters(self: *const T, pcDsFxDistortion: ?*DSFXDistortion) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXDistortion.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXDistortion, self), pcDsFxDistortion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXDistortion_GetAllParameters(self: *const T, pDsFxDistortion: ?*DSFXDistortion) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXDistortion.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXDistortion, self), pDsFxDistortion); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXCompressor = extern struct { fGain: f32, fAttack: f32, fRelease: f32, fThreshold: f32, fRatio: f32, fPredelay: f32, }; const IID_IDirectSoundFXCompressor_Value = @import("../../zig.zig").Guid.initString("4bbd1154-62f6-4e2c-a15c-d3b6c417f7a0"); pub const IID_IDirectSoundFXCompressor = &IID_IDirectSoundFXCompressor_Value; pub const IDirectSoundFXCompressor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXCompressor, pcDsFxCompressor: ?*DSFXCompressor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXCompressor, pDsFxCompressor: ?*DSFXCompressor, ) 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 IDirectSoundFXCompressor_SetAllParameters(self: *const T, pcDsFxCompressor: ?*DSFXCompressor) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXCompressor.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXCompressor, self), pcDsFxCompressor); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXCompressor_GetAllParameters(self: *const T, pDsFxCompressor: ?*DSFXCompressor) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXCompressor.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXCompressor, self), pDsFxCompressor); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXParamEq = extern struct { fCenter: f32, fBandwidth: f32, fGain: f32, }; const IID_IDirectSoundFXParamEq_Value = @import("../../zig.zig").Guid.initString("c03ca9fe-fe90-4204-8078-82334cd177da"); pub const IID_IDirectSoundFXParamEq = &IID_IDirectSoundFXParamEq_Value; pub const IDirectSoundFXParamEq = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXParamEq, pcDsFxParamEq: ?*DSFXParamEq, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXParamEq, pDsFxParamEq: ?*DSFXParamEq, ) 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 IDirectSoundFXParamEq_SetAllParameters(self: *const T, pcDsFxParamEq: ?*DSFXParamEq) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXParamEq.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXParamEq, self), pcDsFxParamEq); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXParamEq_GetAllParameters(self: *const T, pDsFxParamEq: ?*DSFXParamEq) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXParamEq.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXParamEq, self), pDsFxParamEq); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXI3DL2Reverb = extern struct { lRoom: i32, lRoomHF: i32, flRoomRolloffFactor: f32, flDecayTime: f32, flDecayHFRatio: f32, lReflections: i32, flReflectionsDelay: f32, lReverb: i32, flReverbDelay: f32, flDiffusion: f32, flDensity: f32, flHFReference: f32, }; const IID_IDirectSoundFXI3DL2Reverb_Value = @import("../../zig.zig").Guid.initString("4b166a6a-0d66-43f3-80e3-ee6280dee1a4"); pub const IID_IDirectSoundFXI3DL2Reverb = &IID_IDirectSoundFXI3DL2Reverb_Value; pub const IDirectSoundFXI3DL2Reverb = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXI3DL2Reverb, pcDsFxI3DL2Reverb: ?*DSFXI3DL2Reverb, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXI3DL2Reverb, pDsFxI3DL2Reverb: ?*DSFXI3DL2Reverb, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetPreset: fn( self: *const IDirectSoundFXI3DL2Reverb, dwPreset: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPreset: fn( self: *const IDirectSoundFXI3DL2Reverb, pdwPreset: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetQuality: fn( self: *const IDirectSoundFXI3DL2Reverb, lQuality: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetQuality: fn( self: *const IDirectSoundFXI3DL2Reverb, plQuality: ?*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 IDirectSoundFXI3DL2Reverb_SetAllParameters(self: *const T, pcDsFxI3DL2Reverb: ?*DSFXI3DL2Reverb) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXI3DL2Reverb.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXI3DL2Reverb, self), pcDsFxI3DL2Reverb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXI3DL2Reverb_GetAllParameters(self: *const T, pDsFxI3DL2Reverb: ?*DSFXI3DL2Reverb) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXI3DL2Reverb.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXI3DL2Reverb, self), pDsFxI3DL2Reverb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXI3DL2Reverb_SetPreset(self: *const T, dwPreset: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXI3DL2Reverb.VTable, self.vtable).SetPreset(@ptrCast(*const IDirectSoundFXI3DL2Reverb, self), dwPreset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXI3DL2Reverb_GetPreset(self: *const T, pdwPreset: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXI3DL2Reverb.VTable, self.vtable).GetPreset(@ptrCast(*const IDirectSoundFXI3DL2Reverb, self), pdwPreset); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXI3DL2Reverb_SetQuality(self: *const T, lQuality: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXI3DL2Reverb.VTable, self.vtable).SetQuality(@ptrCast(*const IDirectSoundFXI3DL2Reverb, self), lQuality); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXI3DL2Reverb_GetQuality(self: *const T, plQuality: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXI3DL2Reverb.VTable, self.vtable).GetQuality(@ptrCast(*const IDirectSoundFXI3DL2Reverb, self), plQuality); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSFXWavesReverb = extern struct { fInGain: f32, fReverbMix: f32, fReverbTime: f32, fHighFreqRTRatio: f32, }; const IID_IDirectSoundFXWavesReverb_Value = @import("../../zig.zig").Guid.initString("46858c3a-0dc6-45e3-b760-d4eef16cb325"); pub const IID_IDirectSoundFXWavesReverb = &IID_IDirectSoundFXWavesReverb_Value; pub const IDirectSoundFXWavesReverb = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundFXWavesReverb, pcDsFxWavesReverb: ?*DSFXWavesReverb, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundFXWavesReverb, pDsFxWavesReverb: ?*DSFXWavesReverb, ) 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 IDirectSoundFXWavesReverb_SetAllParameters(self: *const T, pcDsFxWavesReverb: ?*DSFXWavesReverb) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXWavesReverb.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundFXWavesReverb, self), pcDsFxWavesReverb); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundFXWavesReverb_GetAllParameters(self: *const T, pDsFxWavesReverb: ?*DSFXWavesReverb) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFXWavesReverb.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundFXWavesReverb, self), pDsFxWavesReverb); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSCFXAec = extern struct { fEnable: BOOL, fNoiseFill: BOOL, dwMode: u32, }; const IID_IDirectSoundCaptureFXAec_Value = @import("../../zig.zig").Guid.initString("ad74143d-903d-4ab7-8066-28d363036d65"); pub const IID_IDirectSoundCaptureFXAec = &IID_IDirectSoundCaptureFXAec_Value; pub const IDirectSoundCaptureFXAec = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundCaptureFXAec, pDscFxAec: ?*DSCFXAec, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundCaptureFXAec, pDscFxAec: ?*DSCFXAec, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const IDirectSoundCaptureFXAec, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IDirectSoundCaptureFXAec, ) 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 IDirectSoundCaptureFXAec_SetAllParameters(self: *const T, pDscFxAec: ?*DSCFXAec) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXAec.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundCaptureFXAec, self), pDscFxAec); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureFXAec_GetAllParameters(self: *const T, pDscFxAec: ?*DSCFXAec) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXAec.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundCaptureFXAec, self), pDscFxAec); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureFXAec_GetStatus(self: *const T, pdwStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXAec.VTable, self.vtable).GetStatus(@ptrCast(*const IDirectSoundCaptureFXAec, self), pdwStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureFXAec_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXAec.VTable, self.vtable).Reset(@ptrCast(*const IDirectSoundCaptureFXAec, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const DSCFXNoiseSuppress = extern struct { fEnable: BOOL, }; const IID_IDirectSoundCaptureFXNoiseSuppress_Value = @import("../../zig.zig").Guid.initString("ed311e41-fbae-4175-9625-cd0854f693ca"); pub const IID_IDirectSoundCaptureFXNoiseSuppress = &IID_IDirectSoundCaptureFXNoiseSuppress_Value; pub const IDirectSoundCaptureFXNoiseSuppress = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetAllParameters: fn( self: *const IDirectSoundCaptureFXNoiseSuppress, pcDscFxNoiseSuppress: ?*DSCFXNoiseSuppress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAllParameters: fn( self: *const IDirectSoundCaptureFXNoiseSuppress, pDscFxNoiseSuppress: ?*DSCFXNoiseSuppress, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IDirectSoundCaptureFXNoiseSuppress, ) 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 IDirectSoundCaptureFXNoiseSuppress_SetAllParameters(self: *const T, pcDscFxNoiseSuppress: ?*DSCFXNoiseSuppress) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXNoiseSuppress.VTable, self.vtable).SetAllParameters(@ptrCast(*const IDirectSoundCaptureFXNoiseSuppress, self), pcDscFxNoiseSuppress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureFXNoiseSuppress_GetAllParameters(self: *const T, pDscFxNoiseSuppress: ?*DSCFXNoiseSuppress) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXNoiseSuppress.VTable, self.vtable).GetAllParameters(@ptrCast(*const IDirectSoundCaptureFXNoiseSuppress, self), pDscFxNoiseSuppress); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDirectSoundCaptureFXNoiseSuppress_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundCaptureFXNoiseSuppress.VTable, self.vtable).Reset(@ptrCast(*const IDirectSoundCaptureFXNoiseSuppress, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IDirectSoundFullDuplex_Value = @import("../../zig.zig").Guid.initString("edcb4c7a-daab-4216-a42e-6c50596ddc1d"); pub const IID_IDirectSoundFullDuplex = &IID_IDirectSoundFullDuplex_Value; pub const IDirectSoundFullDuplex = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const IDirectSoundFullDuplex, pCaptureGuid: ?*const Guid, pRenderGuid: ?*const Guid, lpDscBufferDesc: ?*DSCBUFFERDESC, lpDsBufferDesc: ?*DSBUFFERDESC, hWnd: ?HWND, dwLevel: u32, lplpDirectSoundCaptureBuffer8: ?*?*IDirectSoundCaptureBuffer8, lplpDirectSoundBuffer8: ?*?*IDirectSoundBuffer8, ) 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 IDirectSoundFullDuplex_Initialize(self: *const T, pCaptureGuid: ?*const Guid, pRenderGuid: ?*const Guid, lpDscBufferDesc: ?*DSCBUFFERDESC, lpDsBufferDesc: ?*DSBUFFERDESC, hWnd: ?HWND, dwLevel: u32, lplpDirectSoundCaptureBuffer8: ?*?*IDirectSoundCaptureBuffer8, lplpDirectSoundBuffer8: ?*?*IDirectSoundBuffer8) callconv(.Inline) HRESULT { return @ptrCast(*const IDirectSoundFullDuplex.VTable, self.vtable).Initialize(@ptrCast(*const IDirectSoundFullDuplex, self), pCaptureGuid, pRenderGuid, lpDscBufferDesc, lpDsBufferDesc, hWnd, dwLevel, lplpDirectSoundCaptureBuffer8, lplpDirectSoundBuffer8); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (10) //-------------------------------------------------------------------------------- pub extern "DSOUND" fn DirectSoundCreate( pcGuidDevice: ?*const Guid, ppDS: ?*?*IDirectSound, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundEnumerateA( pDSEnumCallback: ?LPDSENUMCALLBACKA, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundEnumerateW( pDSEnumCallback: ?LPDSENUMCALLBACKW, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundCaptureCreate( pcGuidDevice: ?*const Guid, ppDSC: ?*?*IDirectSoundCapture, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundCaptureEnumerateA( pDSEnumCallback: ?LPDSENUMCALLBACKA, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundCaptureEnumerateW( pDSEnumCallback: ?LPDSENUMCALLBACKW, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundCreate8( pcGuidDevice: ?*const Guid, ppDS8: ?*?*IDirectSound8, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundCaptureCreate8( pcGuidDevice: ?*const Guid, ppDSC8: ?*?*IDirectSoundCapture, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn DirectSoundFullDuplexCreate( pcGuidCaptureDevice: ?*const Guid, pcGuidRenderDevice: ?*const Guid, pcDSCBufferDesc: ?*DSCBUFFERDESC, pcDSBufferDesc: ?*DSBUFFERDESC, hWnd: ?HWND, dwLevel: u32, ppDSFD: ?*?*IDirectSoundFullDuplex, ppDSCBuffer8: ?*?*IDirectSoundCaptureBuffer8, ppDSBuffer8: ?*?*IDirectSoundBuffer8, pUnkOuter: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "DSOUND" fn GetDeviceID( pGuidSrc: ?*const Guid, pGuidDest: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (3) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { pub const LPDSENUMCALLBACK = thismodule.LPDSENUMCALLBACKA; pub const DirectSoundEnumerate = thismodule.DirectSoundEnumerateA; pub const DirectSoundCaptureEnumerate = thismodule.DirectSoundCaptureEnumerateA; }, .wide => struct { pub const LPDSENUMCALLBACK = thismodule.LPDSENUMCALLBACKW; pub const DirectSoundEnumerate = thismodule.DirectSoundEnumerateW; pub const DirectSoundCaptureEnumerate = thismodule.DirectSoundCaptureEnumerateW; }, .unspecified => if (@import("builtin").is_test) struct { pub const LPDSENUMCALLBACK = *opaque{}; pub const DirectSoundEnumerate = *opaque{}; pub const DirectSoundCaptureEnumerate = *opaque{}; } else struct { pub const LPDSENUMCALLBACK = @compileError("'LPDSENUMCALLBACK' requires that UNICODE be set to true or false in the root module"); pub const DirectSoundEnumerate = @compileError("'DirectSoundEnumerate' requires that UNICODE be set to true or false in the root module"); pub const DirectSoundCaptureEnumerate = @compileError("'DirectSoundCaptureEnumerate' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (10) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const D3DVECTOR = @import("../../graphics/direct3d.zig").D3DVECTOR; const HANDLE = @import("../../foundation.zig").HANDLE; const HRESULT = @import("../../foundation.zig").HRESULT; const HWND = @import("../../foundation.zig").HWND; const IUnknown = @import("../../system/com.zig").IUnknown; const PSTR = @import("../../foundation.zig").PSTR; const PWSTR = @import("../../foundation.zig").PWSTR; const WAVEFORMATEX = @import("../../media/audio.zig").WAVEFORMATEX; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "LPDSENUMCALLBACKA")) { _ = LPDSENUMCALLBACKA; } if (@hasDecl(@This(), "LPDSENUMCALLBACKW")) { _ = LPDSENUMCALLBACKW; } @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/media/audio/direct_sound.zig
const std = @import("std"); const builtin = @import("builtin"); const unicode = @import("unicode.zig"); pub const Utf8ToUtf32 = unicode.Utf8ToUtf32; pub const UnicodeError = unicode.Error; pub const AnsiEscProcessor = @import("AnsiEscProcessor.zig"); pub const Guid = @import("guid.zig"); pub const ToString = @import("ToString.zig"); pub const Cksum = @import("Cksum.zig"); pub const Error = error { Unknown, OutOfBounds, NotEnoughSource, NotEnoughDestination, }; // NOTE: DO NOT TRY TO REMOVE INLINE ON THESE, WILL BREAK LOW KERNEL pub fn Ki(x: usize) callconv(.Inline) usize { return x << 10; } pub fn Mi(x: usize) callconv(.Inline) usize { return x << 20; } pub fn Gi(x: usize) callconv(.Inline) usize { return x << 30; } pub fn Ti(x: usize) callconv(.Inline) usize { return x << 40; } pub fn align_down(value: usize, align_by: usize) usize { return value & (~align_by +% 1); } pub fn align_up(value: usize, align_by: usize) usize { return align_down(value +% align_by -% 1, align_by); } pub fn padding(value: usize, align_by: usize) callconv(.Inline) usize { return -%value & (align_by - 1); } pub fn div_round_up(comptime Type: type, n: Type, d: Type) callconv(.Inline) Type { return n / d + (if (n % d != 0) @as(Type, 1) else @as(Type, 0)); } test "div_round_up" { try std.testing.expectEqual(@as(u8, 0), div_round_up(u8, 0, 2)); try std.testing.expectEqual(@as(u8, 1), div_round_up(u8, 1, 2)); try std.testing.expectEqual(@as(u8, 1), div_round_up(u8, 2, 2)); try std.testing.expectEqual(@as(u8, 2), div_round_up(u8, 3, 2)); try std.testing.expectEqual(@as(u8, 2), div_round_up(u8, 4, 2)); } pub fn isspace(c: u8) bool { return c == ' ' or c == '\n' or c == '\t' or c == '\r'; } pub fn stripped_string_size(str: []const u8) callconv(.Inline) usize { var stripped_size: usize = 0; for (str) |c, i| { if (!isspace(c)) stripped_size = i + 1; } return stripped_size; } pub fn zero_init(comptime Type: type) Type { const Traits = @typeInfo(Type); comptime var CastThrough = Type; switch (Traits) { std.builtin.TypeId.Int => { CastThrough = Type; }, std.builtin.TypeId.Bool => { return false; }, std.builtin.TypeId.Struct => |struct_type| { if (struct_type.layout != std.builtin.TypeInfo.ContainerLayout.Packed) { @compileError("Struct must be packed!"); } var struct_var: Type = undefined; inline for (struct_type.fields) |field| { @field(struct_var, field.name) = zero_init(field.field_type); } return struct_var; }, else => CastThrough = std.meta.IntType(.unsigned, @sizeOf(Type) * 8), } return @bitCast(Type, @intCast(CastThrough, 0)); } pub fn packed_bit_size(comptime Type: type) comptime_int { const Traits = @typeInfo(Type); switch (Traits) { std.builtin.TypeId.Int => |int_type| { return int_type.bits; }, std.builtin.TypeId.Bool => { return 1; }, std.builtin.TypeId.Array => |array_type| { return packed_bit_size(array_type.child) * array_type.len; }, std.builtin.TypeId.Struct => |struct_type| { if (struct_type.layout != std.builtin.TypeInfo.ContainerLayout.Packed) { @compileError("Struct must be packed!"); } comptime var total_size: comptime_int = 0; inline for (struct_type.fields) |field| { total_size += packed_bit_size(field.field_type); } return total_size; }, else => { @compileLog("Unsupported Type is ", @typeName(Type)); @compileError("Unsupported Type"); } } } /// @intToEnum can't be used to test if a value is a valid Enum, so this wraps /// it and gives that functionality. pub fn int_to_enum(comptime EnumType: type, value: std.meta.Tag(EnumType)) ?EnumType { const type_info = @typeInfo(EnumType).Enum; inline for (type_info.fields) |*field| { if (@intCast(type_info.tag_type, field.value) == value) { return @intToEnum(EnumType, value); } } return null; } pub fn valid_enum(comptime EnumType: type, value: EnumType) bool { return int_to_enum(EnumType, @bitCast(std.meta.Tag(EnumType), value)) != null; } test "int_to_enum" { const assert = std.debug.assert; const Abc = enum(u8) { A = 0, B = 1, C = 12, }; // Check with Literals assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 0)).? == Abc.A); assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 1)).? == Abc.B); assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 2)) == null); assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 11)) == null); assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 12)).? == Abc.C); assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 13)) == null); assert(int_to_enum(Abc, @intCast(std.meta.Tag(Abc), 0xFF)) == null); // Check with Variable var x: std.meta.Tag(Abc) = 0; assert(int_to_enum(Abc, x).? == Abc.A); x = 0xFF; assert(int_to_enum(Abc, x) == null); // valid_enum assert(valid_enum(Abc, @intToEnum(Abc, @as(u8, 0)))); // TODO: This is a workaround bitcast of a const Enum causing a compiler assert // Looks like it's related to https://github.com/ziglang/zig/issues/1036 var invalid_enum_value: u8 = 4; assert(!valid_enum(Abc, @ptrCast(*const Abc, &invalid_enum_value).*)); // assert(valid_enum(Abc, @bitCast(Abc, @as(u8, 4)))); } pub fn enum_name(comptime EnumType: type, value: EnumType) ?[]const u8 { const type_info = @typeInfo(EnumType).Enum; inline for (type_info.fields) |*field| { var enum_value = @ptrCast(*const type_info.tag_type, &value).*; if (@intCast(type_info.tag_type, field.value) == enum_value) { return field.name; } } return null; } pub fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; } pub fn min(comptime T: type, a: T, b: T) T { return if (a < b) a else b; } /// Returns true if the contents of the slices `a` and `b` are the same. pub fn memory_compare(a: []const u8, b: []const u8) callconv(.Inline) bool { if (a.len != b.len) return false; for (a[0..]) |value, i| { if (value != b[i]) return false; } return true; } /// Copy contents from `source` to `destination`. /// /// If `source.len != destination.len` then the copy is truncated. pub fn memory_copy_truncate(destination: []u8, source: []const u8) callconv(.Inline) usize { const size = min(usize, destination.len, source.len); for (destination[0..size]) |*ptr, i| { ptr.* = source[i]; } return size; } pub fn memory_copy_error(destination: []u8, source: []const u8) callconv(.Inline) Error!usize { if (destination.len < source.len) { return Error.NotEnoughDestination; } const size = source.len; for (destination[0..size]) |*ptr, i| { ptr.* = source[i]; } return size; } pub fn memory_copy_anyptr(destination: []u8, source: anytype) callconv(.Inline) void { const s = @ptrCast([*]const u8, source); for (destination[0..]) |*ptr, i| { ptr.* = s[i]; } } /// Set all the elements of `destination` to `value`. pub fn memory_set(destination: []u8, value: u8) callconv(.Inline) void { for (destination[0..]) |*ptr| { ptr.* = value; } } pub fn max_of_int(comptime T: type) T { const Traits = @typeInfo(T); return if (Traits.Int.signedness == .signed) (1 << (Traits.Int.bits - 1)) - 1 else @as(T, 0) -% 1; } test "max_of_int" { try std.testing.expect(max_of_int(u16) == 0xffff); try std.testing.expect(max_of_int(i16) == 0x7fff); } pub fn add_signed_to_unsigned( comptime uT: type, a: uT, comptime iT: type, b: iT) ?uT { var result: uT = undefined; if (@addWithOverflow(uT, a, @bitCast(uT, b), &result)) { if (b > 0 and result < a) { return null; } } else if (b < 0 and result > a) { return null; } return result; } pub fn add_isize_to_usize(a: usize, b: isize) callconv(.Inline) ?usize { return add_signed_to_unsigned(usize, a, isize, b); } test "add_signed_to_unsigned" { try std.testing.expect(add_isize_to_usize(0, 0).? == 0); try std.testing.expect(add_isize_to_usize(0, 10).? == 10); try std.testing.expect(add_isize_to_usize(0, -10) == null); const max_usize = max_of_int(usize); try std.testing.expect(add_isize_to_usize(max_usize, 0).? == max_usize); try std.testing.expect(add_isize_to_usize(max_usize, -10).? == max_usize - 10); try std.testing.expect(add_isize_to_usize(max_usize, 10) == null); } pub fn string_length(bytes: []const u8) callconv(.Inline) usize { for (bytes[0..]) |*ptr, i| { if (ptr.* == 0) { return i; } } return bytes.len; } pub fn cstring_length(cstr: [*:0]const u8) usize { var i: usize = 0; while (cstr[i] != 0) { i += 1; } return i; } pub fn cstring_to_slice(cstr: [*:0]const u8) []const u8 { return @ptrCast([*]const u8, cstr)[0..cstring_length(cstr) + 1]; } pub fn cstring_to_string(cstr: [*:0]const u8) []const u8 { return @ptrCast([*]const u8, cstr)[0..cstring_length(cstr)]; } pub fn int_log2(comptime Type: type, value: Type) Type { return @sizeOf(Type) * 8 - 1 - @clz(Type, value); } fn test_int_log2(value: usize, expected: usize) !void { try std.testing.expectEqual(expected, int_log2(usize, value)); } test "int_log2" { try test_int_log2(1, 0); try test_int_log2(2, 1); try test_int_log2(4, 2); try test_int_log2(8, 3); try test_int_log2(16, 4); try test_int_log2(32, 5); try test_int_log2(64, 6); try test_int_log2(128, 7); } pub fn hex_char_len(comptime Type: type, value: Type) Type { if (value == 0) { return 1; } return int_log2(Type, value) / 4 + 1; } fn test_hex_char_len(value: usize, expected: usize) !void { try std.testing.expectEqual(expected, hex_char_len(usize, value)); } test "hex_char_len" { try test_hex_char_len(0x0, 1); try test_hex_char_len(0x1, 1); try test_hex_char_len(0xf, 1); try test_hex_char_len(0x10, 2); try test_hex_char_len(0x11, 2); try test_hex_char_len(0xff, 2); try test_hex_char_len(0x100, 3); try test_hex_char_len(0x101, 3); } pub fn int_bit_size(comptime Type: type) usize { return @typeInfo(Type).Int.bits; } pub fn IntLog2Type(comptime Type: type) type { return @Type(std.builtin.TypeInfo{.Int = std.builtin.TypeInfo.Int{ .signedness = .unsigned, .bits = int_log2(usize, int_bit_size(Type)), }}); } fn test_IntLog2Type(comptime Type: type, expected: usize) !void { try std.testing.expectEqual(expected, int_bit_size(IntLog2Type(Type))); } test "Log2Int" { try test_IntLog2Type(u2, 1); try test_IntLog2Type(u32, 5); try test_IntLog2Type(u64, 6); } pub const UsizeLog2Type = IntLog2Type(usize); pub fn select_nibble(comptime Type: type, value: Type, which: usize) u4 { return @intCast(u4, (value >> (@intCast(IntLog2Type(Type), which) * 4)) & 0xf); } fn test_select_nibble(comptime Type: type, value: Type, which: usize, expected: u4) !void { try std.testing.expectEqual(expected, select_nibble(Type, value, which)); } test "select_nibble" { try test_select_nibble(u8, 0xaf, 0, 0xf); try test_select_nibble(u8, 0xaf, 1, 0xa); try test_select_nibble(u16, 0x1234, 0, 0x4); try test_select_nibble(u16, 0x1234, 1, 0x3); try test_select_nibble(u16, 0x1234, 2, 0x2); try test_select_nibble(u16, 0x1234, 3, 0x1); } pub fn PackedArray(comptime T: type, count: usize) type { const Traits = @typeInfo(T); const T2 = switch (Traits) { std.builtin.TypeId.Int => T, std.builtin.TypeId.Bool => u1, std.builtin.TypeId.Enum => |enum_type| enum_type.tag_type, else => @compileError("Invalid Type"), }; const is_enum = switch (Traits) { std.builtin.TypeId.Enum => true, else => false, }; return struct { const Self = @This(); const len = count; const Type = T; const InnerType = T2; const type_bit_size = int_bit_size(InnerType); const Word = usize; const word_bit_size = int_bit_size(Word); const WordShiftType = IntLog2Type(Word); const values_per_word = word_bit_size / type_bit_size; const word_count = align_up(count * type_bit_size, word_bit_size) / word_bit_size; const mask: Word = (1 << type_bit_size) - 1; contents: [word_count]Word = undefined, pub fn get(self: *const Self, index: usize) Error!Type { if (index >= len) { return Error.OutOfBounds; } const array_index = index / values_per_word; const shift = @intCast(WordShiftType, (index % values_per_word) * type_bit_size); const inner_value = @intCast(InnerType, (self.contents[array_index] >> shift) & mask); if (is_enum) { return @intToEnum(Type, inner_value); } else { return @bitCast(Type, inner_value); } } pub fn set(self: *Self, index: usize, value: Type) Error!void { if (index >= len) { return Error.OutOfBounds; } const array_index = index / values_per_word; const shift = @intCast(WordShiftType, (index % values_per_word) * type_bit_size); self.contents[array_index] = (self.contents[array_index] & ~(mask << shift)) | (@intCast(Word, @bitCast(InnerType, value)) << shift); } pub fn reset(self: *Self) void { for (self.contents[0..]) |*ptr| { ptr.* = 0; } } }; } fn test_PackedBoolArray(comptime size: usize) !void { var pa: PackedArray(bool, size) = undefined; pa.reset(); // Make sure get works try std.testing.expectEqual(false, try pa.get(0)); try std.testing.expectEqual(false, try pa.get(1)); try std.testing.expectEqual(false, try pa.get(size - 3)); try std.testing.expectEqual(false, try pa.get(size - 2)); try std.testing.expectEqual(false, try pa.get(size - 1)); // Set and unset the first bit and check it try pa.set(0, true); try std.testing.expectEqual(true, try pa.get(0)); try pa.set(0, false); try std.testing.expectEqual(false, try pa.get(0)); // Set a spot near the end try pa.set(size - 2, true); try std.testing.expectEqual(false, try pa.get(0)); try std.testing.expectEqual(false, try pa.get(1)); try std.testing.expectEqual(false, try pa.get(size - 3)); try std.testing.expectEqual(true, try pa.get(size - 2)); try std.testing.expectEqual(false, try pa.get(size - 1)); // Invalid Operations try std.testing.expectError(Error.OutOfBounds, pa.get(size)); try std.testing.expectError(Error.OutOfBounds, pa.get(size + 100)); try std.testing.expectError(Error.OutOfBounds, pa.set(size, true)); try std.testing.expectError(Error.OutOfBounds, pa.set(size + 100, true)); } test "PackedArray" { try test_PackedBoolArray(5); try test_PackedBoolArray(8); try test_PackedBoolArray(13); try test_PackedBoolArray(400); // Int Type { var pa: PackedArray(u7, 9) = undefined; pa.reset(); try pa.set(0, 13); try std.testing.expectEqual(@as(u7, 13), try pa.get(0)); try pa.set(1, 12); try std.testing.expectEqual(@as(u7, 12), try pa.get(1)); try std.testing.expectEqual(@as(u7, 13), try pa.get(0)); try pa.set(8, 47); try std.testing.expectEqual(@as(u7, 47), try pa.get(8)); } // Enum Type { const Type = enum (u2) { a, b, c, d, }; var pa: PackedArray(Type, 9) = undefined; pa.reset(); try pa.set(0, .a); try std.testing.expectEqual(Type.a, try pa.get(0)); try pa.set(1, .b); try std.testing.expectEqual(Type.b, try pa.get(1)); try std.testing.expectEqual(Type.a, try pa.get(0)); try pa.set(8, .d); try std.testing.expectEqual(Type.d, try pa.get(8)); } } pub fn pow2_round_up(comptime Type: type, value: Type) Type { if (value < 3) { return value; } else { return @intCast(Type, 1) << @intCast(IntLog2Type(Type), (int_log2(Type, value - 1) + 1)); } } test "pow2_round_up" { try std.testing.expectEqual(@as(u8, 0), pow2_round_up(u8, 0)); try std.testing.expectEqual(@as(u8, 1), pow2_round_up(u8, 1)); try std.testing.expectEqual(@as(u8, 2), pow2_round_up(u8, 2)); try std.testing.expectEqual(@as(u8, 4), pow2_round_up(u8, 3)); try std.testing.expectEqual(@as(u8, 4), pow2_round_up(u8, 4)); try std.testing.expectEqual(@as(u8, 8), pow2_round_up(u8, 5)); try std.testing.expectEqual(@as(u8, 8), pow2_round_up(u8, 6)); try std.testing.expectEqual(@as(u8, 8), pow2_round_up(u8, 7)); try std.testing.expectEqual(@as(u8, 8), pow2_round_up(u8, 8)); try std.testing.expectEqual(@as(u8, 16), pow2_round_up(u8, 9)); try std.testing.expectEqual(@as(u8, 16), pow2_round_up(u8, 16)); try std.testing.expectEqual(@as(u8, 32), pow2_round_up(u8, 17)); } pub fn make_slice(comptime Type: type, ptr: [*]Type, len: usize) callconv(.Inline) []Type { var slice: []Type = undefined; slice.ptr = ptr; slice.len = len; return slice; } pub fn to_bytes(value: anytype) callconv(.Inline) []u8 { const Type = @TypeOf(value); const Traits = @typeInfo(Type); switch (Traits) { std.builtin.TypeId.Pointer => |pointer_type| { const count = switch (pointer_type.size) { .One => 1, .Slice => value.len, else => { @compileLog("Unsupported Type is ", @typeName(Type)); @compileError("Unsupported Type"); } }; return make_slice(u8, @ptrCast([*]u8, value), @sizeOf(pointer_type.child) * count); }, else => { @compileLog("Unsupported Type is ", @typeName(Type)); @compileError("Unsupported Type"); } } } pub fn make_const_slice( comptime Type: type, ptr: [*]const Type, len: usize) callconv(.Inline) []const Type { var slice: []const Type = undefined; slice.ptr = ptr; slice.len = len; return slice; } pub fn to_const_bytes(value: anytype) callconv(.Inline) []const u8 { const Type = @TypeOf(value); const Traits = @typeInfo(Type); switch (Traits) { std.builtin.TypeId.Pointer => |pointer_type| { const count = switch (pointer_type.size) { .One => 1, .Slice => value.len, else => { @compileLog("Unsupported Type is ", @typeName(Type)); @compileError("Unsupported Type"); } }; return make_const_slice(u8, @ptrCast([*]const u8, value), @sizeOf(pointer_type.child) * count); }, else => { @compileLog("Unsupported Type is ", @typeName(Type)); @compileError("Unsupported Type"); } } } /// What to discard if there is no more room. const CircularBufferDiscard = enum { DiscardNewest, DiscardOldest, }; pub fn CircularBuffer( comptime Type: type, len_arg: usize, discard: CircularBufferDiscard) type { return struct { const Self = @This(); const max_len = len_arg; contents: [max_len]Type = undefined, start: usize = 0, len: usize = 0, pub fn reset(self: *Self) void { self.start = 0; self.len = 0; } fn wrapped_offset(pos: usize, offset: usize) callconv(.Inline) usize { return (pos + offset) % max_len; } fn increment(pos: *usize) callconv(.Inline) void { pos.* = wrapped_offset(pos.*, 1); } pub fn push(self: *Self, value: Type) void { if (self.len == max_len) { if (discard == .DiscardNewest) { return; } else { // DiscardOldest increment(&self.start); } } else { self.len += 1; } self.contents[wrapped_offset(self.start, self.len - 1)] = value; } pub fn pop(self: *Self) ?Type { if (self.len == 0) return null; self.len -= 1; defer increment(&self.start); return self.contents[self.start]; } pub fn get(self: *const Self, offset: usize) ?Type { if (offset >= self.len) return null; return self.contents[wrapped_offset(self.start, offset)]; } pub fn peek_start(self: *const Self) ?Type { return self.get(0); } pub fn peek_end(self: *const Self) ?Type { if (self.len == 0) return null; return self.get(self.len - 1); } }; } fn test_circular_buffer(comptime discard: CircularBufferDiscard) !void { var buffer = CircularBuffer(usize, 4, discard){}; const nil: ?usize = null; // Empty try std.testing.expectEqual(@as(usize, 0), buffer.len); try std.testing.expectEqual(nil, buffer.pop()); try std.testing.expectEqual(nil, buffer.peek_start()); try std.testing.expectEqual(nil, buffer.get(0)); try std.testing.expectEqual(nil, buffer.peek_end()); // Push Some Values buffer.push(1); try std.testing.expectEqual(@as(usize, 1), buffer.len); try std.testing.expectEqual(@as(usize, 1), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 1), buffer.peek_end().?); buffer.push(2); try std.testing.expectEqual(@as(usize, 2), buffer.peek_end().?); buffer.push(3); try std.testing.expectEqual(@as(usize, 3), buffer.peek_end().?); try std.testing.expectEqual(@as(usize, 3), buffer.len); // Test get try std.testing.expectEqual(@as(usize, 1), buffer.get(0).?); try std.testing.expectEqual(@as(usize, 2), buffer.get(1).?); try std.testing.expectEqual(@as(usize, 3), buffer.get(2).?); try std.testing.expectEqual(nil, buffer.get(3)); // Pop The Values try std.testing.expectEqual(@as(usize, 1), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 1), buffer.pop().?); try std.testing.expectEqual(@as(usize, 2), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 2), buffer.pop().?); try std.testing.expectEqual(@as(usize, 3), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 3), buffer.pop().?); // It's empty again try std.testing.expectEqual(@as(usize, 0), buffer.len); try std.testing.expectEqual(nil, buffer.pop()); try std.testing.expectEqual(nil, buffer.peek_start()); try std.testing.expectEqual(nil, buffer.get(0)); try std.testing.expectEqual(nil, buffer.peek_end()); // Fill it past capacity buffer.push(5); try std.testing.expectEqual(@as(usize, 5), buffer.peek_end().?); buffer.push(4); try std.testing.expectEqual(@as(usize, 4), buffer.peek_end().?); buffer.push(3); try std.testing.expectEqual(@as(usize, 3), buffer.peek_end().?); buffer.push(2); try std.testing.expectEqual(@as(usize, 2), buffer.peek_end().?); buffer.push(1); if (discard == .DiscardOldest) { try std.testing.expectEqual(@as(usize, 1), buffer.peek_end().?); } try std.testing.expectEqual(@as(usize, 4), buffer.len); // Test get var index: usize = 0; if (discard == .DiscardNewest) { try std.testing.expectEqual(@as(usize, 5), buffer.get(index).?); index += 1; } try std.testing.expectEqual(@as(usize, 4), buffer.get(index).?); index += 1; try std.testing.expectEqual(@as(usize, 3), buffer.get(index).?); index += 1; try std.testing.expectEqual(@as(usize, 2), buffer.get(index).?); index += 1; if (discard == .DiscardOldest) { try std.testing.expectEqual(@as(usize, 1), buffer.get(index).?); index += 1; } try std.testing.expectEqual(nil, buffer.get(index)); // Pop The Values if (discard == .DiscardNewest) { try std.testing.expectEqual(@as(usize, 5), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 5), buffer.pop().?); } try std.testing.expectEqual(@as(usize, 4), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 4), buffer.pop().?); try std.testing.expectEqual(@as(usize, 3), buffer.pop().?); try std.testing.expectEqual(@as(usize, 2), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 2), buffer.pop().?); if (discard == .DiscardOldest) { try std.testing.expectEqual(@as(usize, 1), buffer.peek_start().?); try std.testing.expectEqual(@as(usize, 1), buffer.pop().?); } // It's empty yet again try std.testing.expectEqual(@as(usize, 0), buffer.len); try std.testing.expectEqual(nil, buffer.pop()); try std.testing.expectEqual(nil, buffer.peek_start()); try std.testing.expectEqual(nil, buffer.get(0)); try std.testing.expectEqual(nil, buffer.peek_end()); } test "CircularBuffer(.DiscardNewest)" { try test_circular_buffer(.DiscardNewest); } test "CircularBuffer(.DiscardOldest)" { try test_circular_buffer(.DiscardOldest); } pub fn nibble_char(value: u4) u8 { return if (value < 10) '0' + @intCast(u8, value) else 'a' + @intCast(u8, value - 10); } /// Insert a hex byte to into a buffer. pub fn byte_buffer(buffer: []u8, value: u8) void { buffer[0] = nibble_char(@intCast(u4, value >> 4)); buffer[1] = nibble_char(@intCast(u4, value % 0x10)); } /// Simple Pseudo-random number generator /// See https://en.wikipedia.org/wiki/Linear_congruential_generator pub fn Rand(comptime Type: type) type { return struct { const Self = @This(); const a: u64 = 6364136223846793005; const c: u64 = 1442695040888963407; seed: u64, pub fn get(self: *Self) Type { self.seed = a *% self.seed +% c; return @truncate(Type, self.seed); } }; } test "Rand" { var r = Rand(u64){.seed = 0}; try std.testing.expectEqual(@as(u64, 1442695040888963407), r.get()); try std.testing.expectEqual(@as(u64, 1876011003808476466), r.get()); try std.testing.expectEqual(@as(u64, 11166244414315200793), r.get()); } pub fn starts_with(what: []const u8, prefix: []const u8) bool { if (what.len < prefix.len) return false; for (what[0..prefix.len]) |value, i| { if (value != prefix[i]) return false; } return true; } pub fn ends_with(what: []const u8, postfix: []const u8) bool { if (what.len < postfix.len) return false; for (what[what.len - postfix.len..]) |value, i| { if (value != postfix[i]) return false; } return true; } pub const Point = struct { x: u32 = 0, y: u32 = 0, };
libs/utils/utils.zig
pub const Color = struct{ rgb: Value, }; /// Value is the alpha-premultiplied red, green, blue and alpha values /// for the color. Each value ranges within [0, 0xffff], but is represented /// by a uint32 so that multiplying by a blend factor up to 0xffff will not /// overflow. /// /// An alpha-premultiplied color component c has been scaled by alpha (a), /// so has valid values 0 <= c <= a. pub const Value = struct{ r: u32, g: u32, b: u32, a: u32, }; /// Model can convert any Color to one from its own color model. The conversion /// may be lossy. pub const Model = struct{ convert: fn (c: ModelType) Color, }; /// RGBA represents a traditional 32-bit alpha-premultiplied color, having 8 /// bits for each of red, green, blue and alpha. /// /// An alpha-premultiplied color component C has been scaled by alpha (A), so /// has valid values 0 <= C <= A. pub const RGBA = struct{ r: u8, g: u8, b: u8, a: u8, fn toColor(c: RGBA) Color { return Color{ .rgb = c.toValue() }; } fn toValue(c: RGBA) Value { var r: u32 = c.r; r |= r << 8; var g: u32 = c.g; g |= g << 8; var b: u32 = c.b; b |= b << 8; var a: u32 = c.a; a |= a << 8; return Value{ .r = r, .g = g, .b = b, .a = a, }; } }; /// RGBA64 represents a 64-bit alpha-premultiplied color, having 16 bits for /// each of red, green, blue and alpha. /// An alpha-premultiplied color component C has been scaled by alpha (A), so /// has valid values 0 <= C <= A. pub const RGBA64 = struct{ r: u16, g: u16, b: u16, a: u16, fn toColor(c: RGBA64) Value { return Color{ .rgb = c.toValue }; } fn toValue(c: RGBA64) Value { return Value{ .r = c.r, .g = c.g, .b = c.b, .a = c.a, }; } }; /// NRGBA represents a non-alpha-premultiplied 32-bit color. pub const NRGBA = struct{ r: u8, g: u8, b: u8, a: u8, fn toColor(c: NBRGBA) Value { var r: u32 = c.r; var g: u32 = c.g; var b: u32 = c.b; var a: u32 = c.a; r |= r << 8; r *= a; r /= 0xff; g |= g << 8; g *= a; g /= 0xff; b |= b << 8; b *= a; b /= 0xff; a |= a << 8; return Value{ .r = r, .g = g, .b = b, .a = a, }; } }; pub const NBRGBA64 = struct{ r: u16, g: u16, b: u16, a: u16, fn toColor(c: NBRGBA64) Value { var r: u32 = c.r; var g: u32 = c.g; var b: u32 = c.b; var a: u32 = c.a; r |= r << 8; r *= a; r /= 0xffff; g |= g << 8; g *= a; g /= 0xffff; b |= b << 8; b *= a; b /= 0xffff; return Value{ .r = r, .g = g, .b = b, .a = a, }; } }; /// Alpha represents an 8-bit alpha color. pub const Alpha = struct{ a: u8, fn toColor(c: Alpha) Color { return Color{ .rgb = c.toValue() }; } fn toValue(c: Alpha) Value { var a: u32 = c.a; a |= a << 8; return Value{ .r = a, .g = a, .b = a, .a = a, }; } }; pub const Alpha16 = struct{ a: u16, fn toColor(c: Alpha16) Color { return Color{ .rgb = c.toValue() }; } fn toValue(c: Alpha16) Value { var a: u32 = c.a; a |= a << 8; return Value{ .r = a, .g = a, .b = a, .a = a, }; } }; /// Gray represents an 8-bit grayscale color. pub const Gray = struct{ y: u8, fn toColor(c: Gray) Value { var y: u32 = c.y; y |= y << 8; return Value{ .r = y, .g = y, .b = y, .a = 0xffff, }; } }; pub const Gray16 = struct{ y: u16, fn toColor(c: Gray16) Value { var y: u32 = c.y; return Value{ .r = y, .g = y, .b = y, .a = 0xffff, }; } }; pub const RGBAModel = Model{ .convert = ModelType.rgbaModel }; pub const RGBA64Model = Model{ .convert = ModelType.rgba64Model }; pub const NRGBAModel = Model{ .convert = ModelType.nrgbaModel }; pub const NRGBA64Model = Model{ .convert = ModelType.nrgba64Model }; pub const Alpha16Model = Model{ .convert = ModelType.alpha16Model }; pub const GrayModel = Model{ .convert = ModelType.grayModel }; pub const Gray16Model = Model{ .convert = ModelType.gray16Model }; pub const ModelType = union(enum){ rgba: RGBA, rgba64: RGBA64, nrgba: NRGBA, nrgba64: NBRGBA64, alpha: Alpha, alpha16: Alpha16, gray: Gray, gray16: Gray16, color: Color, pub fn rgbaModel(m: ModelType) Color { return switch (m) { ModelType.rgba => |c| c.toColor(), ModelType.color => |c| { const model = RGBA{ .r = @intCast(u8, c.rgb.r >> 8), .g = @intCast(u8, c.rgb.g >> 8), .b = @intCast(u8, c.rgb.b >> 8), .a = @intCast(u8, c.rgb.a >> 8), }; return model.toColor(); }, else => unreachable, }; } pub fn rgba64Model(m: ModelType) Color { return switch (m) { ModelType.rgba64 => |c| c.toColor(), ModelType.color => |c| { const model = RGBA64{ .r = c.rgb.r, .g = c.rgb.g, .b = c.rgb.b, .a = c.rgb.a, }; return model.toColor(); }, else => unreachable, }; } pub fn nrgbaModel(m: ModelType) Color { return switch (m) { ModelType.nrgba => |c| c.toColor(), ModelType.color => |c| { if (c.rgb.a == 0xffff) { const model = NRGBA{ .r = @intCast(u8, c.rgb.r >> 8), .g = @intCast(u8, c.rgb.g >> 8), .b = @intCast(u8, c.rgb.b >> 8), .a = 0xff, }; return model.toColor(); } if (c.rgb.a == 0) { const model = NRGBA{ .r = 0, .g = 0, .b = 0, .a = 0, }; return model.toColor(); } var r = (c.rgb.r * 0xffff) / c.rgb.a; var g = (c.rgb.g * 0xffff) / c.rgb.a; var b = (c.rgb.b * 0xffff) / c.rgb.a; const model = NRGBA{ .r = @intCast(u8, r >> 8), .g = @intCast(u8, g >> 8), .b = @intCast(u8, b >> 8), .a = @intCast(u8, c.rgb.a >> 8), }; return model.toColor(); }, else => unreachable, }; } pub fn nrgba64Model(m: ModelType) Color { return switch (m) { ModelType.nrgba64 => |c| c.toColor(), ModelType.color => |c| { if (c.rgb.a == 0xffff) { const model = NRGBA64{ .r = c.rgb.r, .g = c.rgb.g, .b = c.rgb.b, .a = 0xff, }; return model.toColor(); } if (c.rgb.a == 0) { const model = NRGBA64{ .r = 0, .g = 0, .b = 0, .a = 0, }; return model.toColor(); } var r = (c.rgb.r * 0xffff) / c.rgb.a; var g = (c.rgb.g * 0xffff) / c.rgb.a; var b = (c.rgb.b * 0xffff) / c.rgb.a; const model = NRGBA64{ .r = r, .g = g, .b = b, .a = c.rgb.a, }; return model.toColor(); }, else => unreachable, }; } pub fn alphaModel(m: ModelType) Color { return switch (m) { ModelType.alpha => |c| c.toColor(), ModelType.color => |c| { const model = Alpha{ .a = @intCast(u8, c.rgb.a >> 8) }; return model.toColor(); }, else => unreachable, }; } pub fn alpha16Model(m: ModelType) Color { return switch (m) { ModelType.alpha16 => |c| c.toColor(), ModelType.color => |c| { const model = Alpha16{ .a = @intCast(u16, c.rgb.a) }; return model.toColor(); }, else => unreachable, }; } pub fn grayModel(m: ModelType) Color { return switch (m) { ModelType.gray => |c| c.toColor(), ModelType.color => |c| { // These coefficients (the fractions 0.299, 0.587 and 0.114) are the same // as those given by the JFIF specification and used by func RGBToYCbCr in // ycbcr.go. // // Note that 19595 + 38470 + 7471 equals 65536. // // The 24 is 16 + 8. The 16 is the same as used in RGBToYCbCr. The 8 is // because the return value is 8 bit color, not 16 bit color. const y = (19595 * c.rgb.r + 38470 * c.rgb.g + 7471 * c.rgb.b + 1 << 15) >> 24; const model = Gray{ .y = @intCast(u8, y) }; return model.toColor(); }, else => unreachable, }; } pub fn gray16Model(m: ModelType) Color { return switch (m) { ModelType.gray16 => |c| c.toColor(), ModelType.color => |c| { // These coefficients (the fractions 0.299, 0.587 and 0.114) are the same // as those given by the JFIF specification and used by func RGBToYCbCr in // ycbcr.go. // // Note that 19595 + 38470 + 7471 equals 65536. const y = (19595 * c.rgb.r + 38470 * c.rgb.g + 7471 * c.rgb.b + 1 << 15) >> 16; const model = Gray16{ .y = @intCast(u16, y) }; return model.toColor(); }, else => unreachable, }; } }; pub const Black = Gray{ .y = 0 }; pub const White = Gray{ .y = 0xffff }; pub const Transparent = Alpha{ .a = 0 }; pub const Opaque = Alpha16{ .a = 0xffff }; /// sqDiff returns the squared-difference of x and y, shifted by 2 so that /// adding four of those won't overflow a uint32. /// /// x and y are both assumed to be in the range [0, 0xffff]. fn sqDiff(x: u32, y: u32) u32 { // The canonical code of this function looks as follows: // // var d uint32 // if x > y { // d = x - y // } else { // d = y - x // } // return (d * d) >> 2 // // Language spec guarantees the following properties of unsigned integer // values operations with respect to overflow/wrap around: // // > For unsigned integer values, the operations +, -, *, and << are // > computed modulo 2n, where n is the bit width of the unsigned // > integer's type. Loosely speaking, these unsigned integer operations // > discard high bits upon overflow, and programs may rely on ``wrap // > around''. // // Considering these properties and the fact that this function is // called in the hot paths (x,y loops), it is reduced to the below code const d = x - y; return (d * d) >> 2; }
src/image/color/index.zig
usingnamespace @cImport({ @cInclude("roaring.h"); }); const std = @import("std"); /// pub const RoaringError = error { /// allocation_failed, /// frozen_view_failed, /// deserialize_failed, }; // Ensure 1:1 equivalence of roaring_bitmap_t and Bitmap comptime { if (@sizeOf(Bitmap) != @sizeOf(roaring_bitmap_t)) { @compileError("Bitmap and roaring_bitmap_t are not the same size"); } } /// This struct reimplements CRoaring's roaring_bitmap_t type /// and can be @ptrCast to and from it. /// (almost) all methods from the roaring_bitmap_t type should be available here. pub const Bitmap = extern struct { high_low_container: roaring_array_t, //=========================== Type conversions ===========================// /// Performs conversions: /// * *roaring_bitmap_t => *Bitmap /// * *const roaring_bitmap_t => *const Bitmap /// * *Bitmap => *roaring_bitmap_t /// * *const Bitmap => *const roaring_bitmap_t /// This should be a pure type-system operation and not produce any /// runtime instructions. /// You can use this function if you get a raw *roaring_bitmap_t from /// somewhere and want to "convert" it into a *Bitmap. Or vice-versa. /// Important: this is simply casting the pointer, not producing any kind /// of copy, make sure you own the memory and know what other pointers /// to the same data are out there. pub fn conv(bitmap: anytype) convType(@TypeOf(bitmap)) { return @ptrCast(convType(@TypeOf(bitmap)), bitmap); } // Support function for conversion. Given an input type, produces the // appropriate target type. fn convType(comptime T: type) type { // We'll just grab the type info, swap out the child field and be done // This way const/non-const are handled automatically var info = @typeInfo(T); info.Pointer.child = switch (info.Pointer.child) { roaring_bitmap_t => Bitmap, Bitmap => roaring_bitmap_t, else => unreachable // don't call this with anything else }; return @Type(info); // turn the modified TypeInfo into a type } //============================= Create/free =============================// // Helper function to ensure null bitmaps turn into errors fn checkNewBitmap(bitmap: ?*roaring_bitmap_t) RoaringError!*Bitmap { if (bitmap) |b| { return conv(b); } else { return RoaringError.allocation_failed; } } /// Dynamically allocates a new bitmap (initially empty). /// Returns an error if the allocation fails. /// Client is responsible for calling `free()`. pub fn create() RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_create() ); } /// Dynamically allocates a new bitmap (initially empty). /// Returns an error if the allocation fails. /// Capacity is a performance hint for how many "containers" the data will need. /// Client is responsible for calling `free()`. pub fn createWithCapacity(capacity: u32) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_create_with_capacity(capacity) ); } /// pub fn free(self: *Bitmap) void { roaring_bitmap_free(conv(self)); } /// pub fn fromRange(min: u64, max: u64, step: u32) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_from_range(min, max, step) ); } /// pub fn fromSlice(vals: []u32) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_of_ptr(vals.len, vals.ptr) ); } /// pub fn getCopyOnWrite(self: *const Bitmap) bool { return roaring_bitmap_get_copy_on_write(conv(self)); } /// Whether you want to use copy-on-write. /// Saves memory and avoids copies, but needs more care in a threaded context. /// Most users should ignore this flag. /// /// Note: If you do turn this flag to 'true', enabling COW, then ensure that you /// do so for all of your bitmaps, since interactions between bitmaps with and /// without COW is unsafe. pub fn setCopyOnWrite(self: *Bitmap, value: bool) void { roaring_bitmap_set_copy_on_write(conv(self), value); } /// Copies a bitmap (this does memory allocation). /// The caller is responsible for memory management. pub fn copy(self: *const Bitmap) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_copy(conv(self)) ); } /// Copies a bitmap from src to dest. It is assumed that the pointer dest /// is to an already allocated bitmap. The content of the dest bitmap is /// freed/deleted. /// /// It might be preferable and simpler to call roaring_bitmap_copy except /// that roaring_bitmap_overwrite can save on memory allocations. pub fn overwrite(dest: *Bitmap, src: *const Bitmap) bool { return roaring_bitmap_overwrite(conv(dest), conv(src)); } //=========================== Add/remove/test ===========================// /// pub fn add(self: *Bitmap, x: u32) void { roaring_bitmap_add(conv(self), x); } /// pub fn addMany(self: *Bitmap, vals: []u32) void { roaring_bitmap_add_many(conv(self), vals.len, vals.ptr); } /// Add value x /// Returns true if a new value was added, false if the value already existed. pub fn addChecked(self: *Bitmap, x: u32) bool { return roaring_bitmap_add_checked(conv(self), x); } /// Add all values in range [min, max] pub fn addRangeClosed(self: *Bitmap, start: u32, end: u32) void { roaring_bitmap_add_range_closed(conv(self), start, end); } /// Add all values in range [min, max) pub fn addRange(self: *Bitmap, start: u64, end: u64) void { roaring_bitmap_add_range(conv(self), start, end); } /// pub fn remove(self: *Bitmap, x: u32) void { roaring_bitmap_remove(conv(self), x); } /// Remove value x /// Returns true if a new value was removed, false if the value was not existing. pub fn removeChecked(self: *Bitmap, x: u32) bool { return roaring_bitmap_remove_checked(conv(self), x); } /// Remove multiple values pub fn removeMany(self: *Bitmap, vals: []u32) void { roaring_bitmap_remove_many(conv(self), vals.len, vals.ptr); } /// Remove all values in range [min, max) pub fn removeRange(self: *Bitmap, min: u64, max: u64) void { roaring_bitmap_remove_range(conv(self), min, max); } /// Remove all values in range [min, max] pub fn removeRangeClosed(self: *Bitmap, min: u32, max: u32) void { roaring_bitmap_remove_range_closed(conv(self), min, max); } /// pub fn clear(self: *Bitmap) void { roaring_bitmap_clear(conv(self)); } /// pub fn contains(self: *const Bitmap, x: u32) bool { return roaring_bitmap_contains(conv(self), x); } /// Check whether a range of values from range_start (included) /// to range_end (excluded) is present pub fn containsRange(self: *const Bitmap, start: u64, end: u64) bool { return roaring_bitmap_contains_range(conv(self), start, end); } /// pub fn empty(self: *const Bitmap) bool { return roaring_bitmap_is_empty(conv(self)); } //========================== Bitwise operations ==========================// /// pub fn _and(a: *const Bitmap, b: *const Bitmap) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_and(conv(a), conv(b)) ); } /// pub fn _andInPlace(a: *Bitmap, b: *const Bitmap) void { roaring_bitmap_and_inplace(conv(a), conv(b)); } /// pub fn _andCardinality(a: *const Bitmap, b: *const Bitmap) u64 { return roaring_bitmap_and_cardinality(conv(a), conv(b)); } /// pub fn intersect(a: *const Bitmap, b: *const Bitmap) bool { return roaring_bitmap_intersect(conv(a), conv(b)); } /// pub fn jaccardIndex(a: *const Bitmap, b: *const Bitmap) f64 { return roaring_bitmap_jaccard_index(conv(a), conv(b)); } /// pub fn _or(a: *const Bitmap, b: *const Bitmap) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_or(conv(a), conv(b)) ); } /// pub fn _orInPlace(a: *Bitmap, b: *const Bitmap) void { roaring_bitmap_or_inplace(conv(a), conv(b)); } /// pub fn _orMany(bitmaps: []*const Bitmap) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_or_many( @intCast(u32, bitmaps.len), @ptrCast([*c][*c]const roaring_bitmap_t, bitmaps.ptr) ) ); } /// pub fn _orManyHeap(bitmaps: []*const Bitmap) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_or_many_heap( @intCast(u32, bitmaps.len), @ptrCast([*c][*c]const roaring_bitmap_t, bitmaps.ptr) ) ); } /// pub fn _orCardinality(a: *const Bitmap, b: *const Bitmap) usize { return roaring_bitmap_or_cardinality(conv(a), conv(b)); } /// pub fn _xor(a: *const Bitmap, b: *const Bitmap) RoaringError!*Bitmap { return checkNewBitmap( roaring_bitmap_xor(conv(a), conv(b)) ); } /// pub fn _xorInPlace(a: *Bitmap, b: *const Bitmap) void { roaring_bitmap_xor_inplace(conv(a), conv(b)); } /// pub fn _xorCardinality(a: *const Bitmap, b: *const Bitmap) usize { return roaring_bitmap_xor_cardinality(conv(a), conv(b)); } /// pub fn _xorMany(bitmaps: []*const Bitmap) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_xor_many( @intCast(u32, bitmaps.len), @ptrCast([*c][*c]const roaring_bitmap_t, bitmaps.ptr) )); } /// pub fn _andnot(a: *const Bitmap, b: *const Bitmap) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_andnot(conv(a), conv(b))); } /// pub fn _andnotInPlace(a: *Bitmap, b: *const Bitmap) void { roaring_bitmap_andnot_inplace(conv(a), conv(b)); } /// pub fn _andnotCardinality(a: *const Bitmap, b: *const Bitmap) usize { return roaring_bitmap_andnot_cardinality(conv(a), conv(b)); } /// pub fn flip(self: *const Bitmap, start: u64, end: u64) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_flip(conv(self), start, end)); } /// pub fn flipInPlace(self: *Bitmap, start: u64, end: u64) void { roaring_bitmap_flip_inplace(conv(self), start, end); } //======================= Lazy bitwise operations =======================// /// (For expert users who seek high performance.) /// /// Computes the union between two bitmaps and returns new bitmap. The caller is /// responsible for memory management. /// /// The lazy version defers some computations such as the maintenance of the /// cardinality counts. Thus you must call `roaring_bitmap_repair_after_lazy()` /// after executing "lazy" computations. /// /// It is safe to repeatedly call roaring_bitmap_lazy_or_inplace on the result. /// /// `bitsetconversion` is a flag which determines whether container-container /// operations force a bitset conversion. pub fn _orLazy(a: *const Bitmap, b: *const Bitmap, convert: bool) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_lazy_or(conv(a), conv(b), convert)); } /// (For expert users who seek high performance.) /// /// Inplace version of roaring_bitmap_lazy_or, modifies r1. /// /// `bitsetconversion` is a flag which determines whether container-container /// operations force a bitset conversion. pub fn _orLazyInPlace(a: *Bitmap, b: *const Bitmap, convert: bool) void { roaring_bitmap_lazy_or_inplace(conv(a), conv(b), convert); } /// Computes the symmetric difference between two bitmaps and returns new bitmap. /// The caller is responsible for memory management. /// /// The lazy version defers some computations such as the maintenance of the /// cardinality counts. Thus you must call `roaring_bitmap_repair_after_lazy()` /// after executing "lazy" computations. /// /// It is safe to repeatedly call `roaring_bitmap_lazy_xor_inplace()` on /// the result. pub fn _xorLazy(a: *const Bitmap, b: *const Bitmap) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_lazy_xor(conv(a), conv(b))); } /// (For expert users who seek high performance.) /// /// Inplace version of roaring_bitmap_lazy_xor, modifies r1. r1 != r2 pub fn _xorLazyInPlace(a: *Bitmap, b: *const Bitmap) void { roaring_bitmap_lazy_xor_inplace(conv(a), conv(b)); } /// (For expert users who seek high performance.) /// /// Execute maintenance on a bitmap created from `roaring_bitmap_lazy_or()` /// or modified with `roaring_bitmap_lazy_or_inplace()`. pub fn repairAfterLazy(a: *Bitmap) void { roaring_bitmap_repair_after_lazy(conv(a)); } //============================ Serialization ============================// /// pub fn serialize(self: *const Bitmap, buf: []u8) usize { return roaring_bitmap_serialize(conv(self), buf.ptr); } /// pub fn deserialize(buf: []const u8) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_deserialize(buf.ptr)); } /// pub fn sizeInBytes(self: *const Bitmap) usize { return roaring_bitmap_size_in_bytes(conv(self)); } /// pub fn portableSerialize(self: *const Bitmap, buf: []u8) usize { return roaring_bitmap_portable_serialize(conv(self), buf.ptr); } /// pub fn portableDeserialize(buf: []const u8) RoaringError!*Bitmap { return checkNewBitmap(roaring_bitmap_portable_deserialize(buf.ptr)); } /// pub fn portableDeserializeSafe(buf: []const u8) RoaringError! *Bitmap { if (roaring_bitmap_portable_deserialize_safe(buf.ptr, buf.len)) |b| { return conv(b); } else { return RoaringError.deserialize_failed; } } /// pub fn portableDeserializeSize(buf: []const u8) usize { return roaring_bitmap_portable_deserialize_size(buf.ptr, buf.len); } /// pub fn portableSizeInBytes(self: *const Bitmap) usize { return roaring_bitmap_portable_size_in_bytes(conv(self)); } //========================= Frozen functionality =========================// /// pub fn frozenSizeInBytes(self: *const Bitmap) usize { return roaring_bitmap_frozen_size_in_bytes(conv(self)); } /// pub fn frozenSerialize(self: *const Bitmap, buf: []u8) void { roaring_bitmap_frozen_serialize(conv(self), buf.ptr); } /// Returns a read-only Bitmap, backed by the bytes in `buf`. You must not /// free or alter the bytes in `buf` while the view bitmap is alive. /// `buf` must be 32-byte aligned and exactly the length that was reported /// by `frozenSizeInBytes`. pub fn frozenView(buf: []align(32)u8) RoaringError ! *const Bitmap { return conv( roaring_bitmap_frozen_view(buf.ptr, buf.len) orelse return RoaringError.frozen_view_failed ); } //============================== Comparison ==============================// /// pub fn eql(a: *const Bitmap, b: *const Bitmap) bool { return roaring_bitmap_equals(conv(a), conv(b)); } /// Return true if all the elements of r1 are also in r2. pub fn isSubset(a: *const Bitmap, b: *const Bitmap) bool { return roaring_bitmap_is_subset(conv(a), conv(b)); } /// Return true if all the elements of r1 are also in r2, and r2 is strictly /// greater than r1. pub fn isStrictSubset(a: *const Bitmap, b: *const Bitmap) bool { return roaring_bitmap_is_strict_subset(conv(a), conv(b)); } //============================ Miscellaneous ============================// /// pub fn cardinality(self: *const Bitmap) u64 { return roaring_bitmap_get_cardinality(conv(self)); } /// Returns the number of elements in the range [range_start, range_end). pub fn cardinalityRange(self: *const Bitmap, start: u64, end: u64) u64 { return roaring_bitmap_range_cardinality(conv(self), start, end); } /// pub fn minimum(self: *const Bitmap) u32 { return roaring_bitmap_minimum(conv(self)); } /// pub fn maximum(self: *const Bitmap) u32 { return roaring_bitmap_maximum(conv(self)); } /// Selects the element at index 'rank' where the smallest element is at index 0. /// If the size of the roaring bitmap is strictly greater than rank, then this /// function returns true and sets element to the element of given rank. /// Otherwise, it returns false. pub fn select(self: *const Bitmap, rnk: u32, element: *u32) bool { return roaring_bitmap_select(conv(self), rnk, element); } /// Returns the number of integers that are smaller or equal to x. /// Thus if x is the first element, this function will return 1. If /// x is smaller than the smallest element, this function will return 0. /// /// The indexing convention differs between `select` and `rank`: /// `select` refers to the smallest value as having index 0, whereas `rank` /// returns 1 when ranking the smallest value. pub fn rank(self: *const Bitmap, x: u32) u64 { return roaring_bitmap_rank(conv(self), x); } /// Describe the inner structure of the bitmap. pub fn printfDescribe(self: *const Bitmap) void { roaring_bitmap_printf_describe(conv(self)); } /// pub fn printf(self: *const Bitmap) void { roaring_bitmap_printf(conv(self)); } //============================= Optimization =============================// /// Remove run-length encoding even when it is more space efficient. /// Return whether a change was applied. pub fn removeRunCompression(self: *Bitmap) bool { return roaring_bitmap_remove_run_compression(conv(self)); } /// Convert array and bitmap containers to run containers when it is more /// efficient; also convert from run containers when more space efficient. /// /// Returns true if the result has at least one run container. /// Additional savings might be possible by calling `shrinkToFit()`. pub fn runOptimize(self: *Bitmap) bool { return roaring_bitmap_run_optimize(conv(self)); } /// If needed, reallocate memory to shrink the memory usage. /// Returns the number of bytes saved. pub fn shrinkToFit(self: *Bitmap) usize { return roaring_bitmap_shrink_to_fit(conv(self)); } //============================== Iteration ==============================// /// const Iterator = struct { i: roaring_uint32_iterator_t, /// pub fn hasValue(self: Iterator) bool { return self.i.has_value; } /// pub fn currentValue(self: Iterator) u32 { return self.i.current_value; } /// pub fn next(self: *Iterator) bool { return roaring_advance_uint32_iterator(&self.i); } /// pub fn previous(self: *Iterator) bool { return roaring_previous_uint32_iterator(&self.i); } /// pub fn moveEqualOrLarger(self: *Iterator, x: u32) bool { return roaring_move_uint32_iterator_equalorlarger(&self.i, x); } /// pub fn read(self: *Iterator, buf: []u32) u32 { return roaring_read_uint32_iterator(&self.i, buf.ptr, @intCast(u32, buf.len)); } }; /// pub fn iterator(self: *const Bitmap) Iterator { var ret: Iterator = undefined; roaring_init_iterator(conv(self), &ret.i); return ret; } }; /// Helper function to get properly aligned and sized buffers for /// frozenSerialize/frozenView pub fn allocForFrozen(allocator: *std.mem.Allocator, len: usize) ![]align(32)u8 { // The buffer must be 32-byte aligned and sized exactly return allocator.allocAdvanced(u8, 32, // alignment len, std.mem.Allocator.Exact.exact ); }
src/roaring.zig
const std = @import("std"); const assert = std.debug.assert; const main = @import("main.zig"); const c = main.c; const renderer = @import("renderer.zig"); pub var ctx: *c.mu_Context = undefined; pub fn init(allocator: *std.mem.Allocator) !void { ctx = try allocator.create(c.mu_Context); c.mu_init(ctx); ctx.text_width = textWidthWrapper; ctx.text_height = textHeightWrapper; } pub fn deinit() void {} /// What creates the UI layout and elements pub fn processFrame() void { c.mu_begin(ctx); processMainWindow(); c.mu_end(ctx); } pub fn draw() void { var cmd: ?*c.mu_Command = null; while (c.mu_next_command(ctx, &cmd) != 0) { if (cmd == null) { break; // No commands } switch (cmd.?.type) { c.MU_COMMAND_TEXT => { const text_orig: [*]u8 = @ptrCast([*]u8, &cmd.?.text.str); var text_len: u16 = 0; { var char_idx: u16 = 0; while (text_orig[char_idx] != 0) : (char_idx += 1) {} text_len = char_idx; } renderer.drawText(text_orig[0..text_len], cmd.?.text.pos, cmd.?.text.color); }, c.MU_COMMAND_RECT => { renderer.drawRect(cmd.?.rect.rect, cmd.?.rect.color); }, c.MU_COMMAND_ICON => { const icon_id = @intCast(u32, cmd.?.icon.id); renderer.drawIcon(icon_id, cmd.?.icon.rect, cmd.?.icon.color); }, c.MU_COMMAND_CLIP => { renderer.rectClip(cmd.?.clip.rect); }, else => {}, } } } fn textWidthWrapper(font: c.mu_Font, text: [*c]const u8, text_len: c_int) callconv(.C) c_int { if (text_len < -1) { return 0; } const text_len_u = if (text_len == -1) std.mem.len(text) else @intCast(u32, text_len); const text_arr: []const u8 = text[0..text_len_u]; return @intCast(c_int, renderer.textWidth(text_arr)); } fn textHeightWrapper(font: c.mu_Font) callconv(.C) c_int { return @intCast(c_int, renderer.textHeight()); } fn processMainWindow() void { const width: u16 = renderer.win_width(); const height: u16 = renderer.win_height(); // Flags for a full screen window const window_flags = c.MU_OPT_NOINTERACT | c.MU_OPT_NORESIZE | c.MU_OPT_NOCLOSE | c.MU_OPT_NOTITLE; const text_padding_y: u16 = 2; const text_padding_x: u16 = 10; if (c.mu_begin_window_ex(ctx, "Main Window", c.mu_rect(0, 0, 0, 0), window_flags) != 0) { // Make window fill screen const container: *c.mu_Container = c.mu_get_current_container(ctx); container.rect.w = width; container.rect.h = height; c.mu_layout_row(ctx, 2, &[_]i32{ 120, -1 }, renderer.textHeight() + text_padding_y); c.mu_label(ctx, "First:"); if (c.mu_button(ctx, "Button1") != 0) { std.debug.print("Button1 pressed\n", .{}); } c.mu_label(ctx, "Second:"); if (c.mu_button(ctx, "Button2") != 0) { c.mu_open_popup(ctx, "My Popup"); } const popup_name = "My Popup"; const popup_content = "Hello world!"; if (c.mu_begin_popup(ctx, popup_name) != 0) { c.mu_layout_row(ctx, 1, &[_]i32{renderer.textWidth(popup_content) + text_padding_x}, renderer.textHeight() + text_padding_y); c.mu_label(ctx, popup_content); c.mu_end_popup(ctx); } c.mu_end_window(ctx); } }
src/gui.zig
const std = @import("std"); fn sign(v: anytype) @TypeOf(v) { if (v < 0) return -1; if (v > 0) return 1; return 0; } pub const Point = struct { x: isize, y: isize, }; pub fn Canvas( comptime Framebuffer: type, comptime Pixel: type, comptime setPixelImpl: fn (Framebuffer, x: isize, y: isize, col: Pixel) void, ) type { return struct { const Self = @This(); framebuffer: Framebuffer, pub fn init(fb: Framebuffer) Self { return Self{ .framebuffer = fb, }; } /// Sets a pixel on the framebuffer. pub fn setPixel(self: *Self, x: isize, y: isize, color: Pixel) void { setPixelImpl(self.framebuffer, x, y, color); } /// Draws a line from (x0, y0) to (x1, y1). pub fn drawLine(self: *Self, x0: isize, y0: isize, x1: isize, y1: isize, color: Pixel) void { // taken from https://de.wikipedia.org/wiki/Bresenham-Algorithmus var dx = x1 - x0; var dy = y1 - y0; const incx = sign(dx); const incy = sign(dy); if (dx < 0) { dx = -dx; } if (dy < 0) { dy = -dy; } var deltaslowdirection: isize = undefined; var deltafastdirection: isize = undefined; var pdx: isize = undefined; var pdy: isize = undefined; var ddx: isize = undefined; var ddy: isize = undefined; if (dx > dy) { pdx = incx; pdy = 0; ddx = incx; ddy = incy; deltaslowdirection = dy; deltafastdirection = dx; } else { pdx = 0; pdy = incy; ddx = incx; ddy = incy; deltaslowdirection = dx; deltafastdirection = dy; } var x = x0; var y = y0; var err = @divTrunc(deltafastdirection, 2); self.setPixel(x, y, color); var t: isize = 0; while (t < deltafastdirection) : (t += 1) { err -= deltaslowdirection; if (err < 0) { err += deltafastdirection; x += ddx; y += ddy; } else { x += pdx; y += pdy; } self.setPixel(x, y, color); } } /// Draws a circle at local (x0, y0) with the given radius. pub fn drawCircle(self: *Self, x0: isize, y0: isize, radius: usize, color: Pixel) void { // taken from https://de.wikipedia.org/wiki/Bresenham-Algorithmus const iradius = @intCast(isize, radius); var f = 1 - iradius; var ddF_x: isize = 0; var ddF_y: isize = -2 * iradius; var x: isize = 0; var y: isize = iradius; self.setPixel(x0, y0 + iradius, color); self.setPixel(x0, y0 - iradius, color); self.setPixel(x0 + iradius, y0, color); self.setPixel(x0 - iradius, y0, color); while (x < y) { if (f >= 0) { y -= 1; ddF_y += 2; f += ddF_y; } x += 1; ddF_x += 2; f += ddF_x + 1; self.setPixel(x0 + x, y0 + y, color); self.setPixel(x0 - x, y0 + y, color); self.setPixel(x0 + x, y0 - y, color); self.setPixel(x0 - x, y0 - y, color); self.setPixel(x0 + y, y0 + x, color); self.setPixel(x0 - y, y0 + x, color); self.setPixel(x0 + y, y0 - x, color); self.setPixel(x0 - y, y0 - x, color); } } /// Draws the outline of a rectangle. pub fn drawRectangle(self: *Self, x: isize, y: isize, width: usize, height: usize, color: Pixel) void { var i: isize = undefined; const iwidth = @intCast(isize, width) - 1; const iheight = @intCast(isize, height) - 1; // top i = 0; while (i <= iwidth) : (i += 1) { self.setPixel(x + i, y, color); } // bottom i = 0; while (i <= iwidth) : (i += 1) { self.setPixel(x + i, y + iheight, color); } // left i = 1; while (i < iheight) : (i += 1) { self.setPixel(x, y + i, color); } // right i = 1; while (i < iheight) : (i += 1) { self.setPixel(x + iwidth, y + i, color); } } /// Fills a rectangle area. pub fn fillRectangle(self: *Self, x: isize, y: isize, width: usize, height: usize, color: Pixel) void { const xlimit = x + @intCast(isize, width); const ylimit = y + @intCast(isize, height); var py = y; while (py < ylimit) : (py += 1) { var px = x; while (px < xlimit) : (px += 1) { self.setPixel(px, py, color); } } } pub fn drawPolygon(self: *Self, offset_x: isize, offset_y: isize, color: Pixel, points: []const Point) void { std.debug.assert(points.len >= 3); var j = points.len - 1; for (points) |pt0, i| { defer j = i; const pt1 = points[j]; self.drawLine( offset_x + pt0.x, offset_y + pt0.y, offset_x + pt1.x, offset_y + pt1.y, color, ); } } pub fn fillPolygon(self: *Self, offset_x: isize, offset_y: isize, color: Pixel, comptime PointType: type, points: []const PointType) void { std.debug.assert(points.len >= 3); var min_x: isize = std.math.maxInt(isize); var min_y: isize = std.math.maxInt(isize); var max_x: isize = std.math.minInt(isize); var max_y: isize = std.math.minInt(isize); for (points) |pt| { min_x = std.math.min(min_x, pt.x); min_y = std.math.min(min_y, pt.y); max_x = std.math.max(max_x, pt.x); max_y = std.math.max(max_y, pt.y); } // std.debug.print("limits: {} {} {} {}\n", .{ min_x, min_y, max_x, max_y }); // std.time.sleep(1_000_000_000); var y: isize = min_y; while (y <= max_y) : (y += 1) { var x: isize = min_x; while (x <= max_x) : (x += 1) { var inside = false; const p = Point{ .x = x, .y = y }; // free after https://stackoverflow.com/a/17490923 var j = points.len - 1; for (points) |p0, i| { defer j = i; const p1 = points[j]; if ((p0.y > p.y) != (p1.y > p.y) and @intToFloat(f32, p.x) < @intToFloat(f32, (p1.x - p0.x) * (p.y - p0.y)) / @intToFloat(f32, (p1.y - p0.y)) + @intToFloat(f32, p0.x)) { inside = !inside; } } if (inside) { self.setPixel(offset_x + x, offset_y + y, color); } } } } /// Copies pixels from a source rectangle (src_x, src_y, width, height) into the framebuffer at (dest_x, dest_y, width, height). pub fn copyRectangle( self: *Self, dest_x: isize, dest_y: isize, src_x: isize, src_y: isize, width: usize, height: usize, comptime enable_transparency: bool, source: anytype, comptime getPixelImpl: fn (@TypeOf(source), x: isize, y: isize) if (enable_transparency) ?Pixel else Pixel, ) void { const iwidth = @intCast(isize, width); const iheight = @intCast(isize, height); _ = iwidth; var dy: isize = 0; while (dy < iheight) : (dy += 1) { var dx: isize = 0; while (dx < width) : (dx += 1) { const pixel = getPixelImpl(source, src_x + dx, src_y + dy); if (enable_transparency) { if (pixel) |pix| { self.setPixel(dest_x + dx, dest_y + dy, pix); } } else { self.setPixel(dest_x + dx, dest_y + dy, pixel); } } } } /// Copies pixels from a source rectangle into the framebuffer with the destination rectangle. /// No pixel interpolation is done pub fn copyRectangleStretched( self: *Self, dest_x: isize, dest_y: isize, dest_width: usize, dest_height: usize, src_x: isize, src_y: isize, src_width: usize, src_height: usize, comptime enable_transparency: bool, bitmap: anytype, comptime getPixelImpl: fn (@TypeOf(bitmap), x: isize, y: isize) if (enable_transparency) ?Pixel else Pixel, ) void { const iwidth = @intCast(isize, dest_width); const iheight = @intCast(isize, dest_height); _ = src_y; var dy: isize = 0; while (dy < iheight) : (dy += 1) { var dx: isize = 0; while (dx < iwidth) : (dx += 1) { var sx = src_x + @floatToInt(isize, std.math.round(@intToFloat(f32, src_width - 1) * @intToFloat(f32, dx) / @intToFloat(f32, dest_width - 1))); var sy = src_x + @floatToInt(isize, std.math.round(@intToFloat(f32, src_height - 1) * @intToFloat(f32, dy) / @intToFloat(f32, dest_height - 1))); const pixel = getPixelImpl(bitmap, sx, sy); if (enable_transparency) { if (pixel) |pix| { self.setPixel(dest_x + dx, dest_y + dy, pix); } } else { self.setPixel(dest_x + dx, dest_y + dy, pixel); } } } } }; } comptime { const T = Canvas(void, void, struct { fn h(fb: void, x: isize, y: isize, pix: void) void { _ = fb; _ = x; _ = y; _ = pix; } }.h); std.testing.refAllDecls(T); }
painterz.zig
const std = @import("std"); const expect = std.testing.expect; const builtin = @import("builtin"); const native_arch = builtin.target.cpu.arch; fn derp() align(@sizeOf(usize) * 2) i32 { return 1234; } fn noop1() align(1) void {} fn noop4() align(4) void {} test "function alignment" { // function alignment is a compile error on wasm32/wasm64 if (native_arch == .wasm32 or native_arch == .wasm64) return error.SkipZigTest; try expect(derp() == 1234); try expect(@TypeOf(noop1) == fn () align(1) void); try expect(@TypeOf(noop4) == fn () align(4) void); noop1(); noop4(); } var baz: packed struct { a: u32, b: u32, } = undefined; test "packed struct alignment" { try expect(@TypeOf(&baz.b) == *align(1) u32); } const blah: packed struct { a: u3, b: u3, c: u2, } = undefined; test "bit field alignment" { try expect(@TypeOf(&blah.b) == *align(1:3:1) const u3); } test "implicitly decreasing fn alignment" { // function alignment is a compile error on wasm32/wasm64 if (native_arch == .wasm32 or native_arch == .wasm64) return error.SkipZigTest; try testImplicitlyDecreaseFnAlign(alignedSmall, 1234); try testImplicitlyDecreaseFnAlign(alignedBig, 5678); } fn testImplicitlyDecreaseFnAlign(ptr: fn () align(1) i32, answer: i32) !void { try expect(ptr() == answer); } fn alignedSmall() align(8) i32 { return 1234; } fn alignedBig() align(16) i32 { return 5678; } test "@alignCast functions" { // function alignment is a compile error on wasm32/wasm64 if (native_arch == .wasm32 or native_arch == .wasm64) return error.SkipZigTest; if (native_arch == .thumb) return error.SkipZigTest; try expect(fnExpectsOnly1(simple4) == 0x19); } fn fnExpectsOnly1(ptr: fn () align(1) i32) i32 { return fnExpects4(@alignCast(4, ptr)); } fn fnExpects4(ptr: fn () align(4) i32) i32 { return ptr(); } fn simple4() align(4) i32 { return 0x19; } test "generic function with align param" { // function alignment is a compile error on wasm32/wasm64 if (native_arch == .wasm32 or native_arch == .wasm64) return error.SkipZigTest; if (native_arch == .thumb) return error.SkipZigTest; try expect(whyWouldYouEverDoThis(1) == 0x1); try expect(whyWouldYouEverDoThis(4) == 0x1); try expect(whyWouldYouEverDoThis(8) == 0x1); } fn whyWouldYouEverDoThis(comptime align_bytes: u8) align(align_bytes) u8 { _ = align_bytes; return 0x1; } test "@ptrCast preserves alignment of bigger source" { var x: u32 align(16) = 1234; const ptr = @ptrCast(*u8, &x); try expect(@TypeOf(ptr) == *align(16) u8); } test "runtime known array index has best alignment possible" { // take full advantage of over-alignment var array align(4) = [_]u8{ 1, 2, 3, 4 }; try expect(@TypeOf(&array[0]) == *align(4) u8); try expect(@TypeOf(&array[1]) == *u8); try expect(@TypeOf(&array[2]) == *align(2) u8); try expect(@TypeOf(&array[3]) == *u8); // because align is too small but we still figure out to use 2 var bigger align(2) = [_]u64{ 1, 2, 3, 4 }; try expect(@TypeOf(&bigger[0]) == *align(2) u64); try expect(@TypeOf(&bigger[1]) == *align(2) u64); try expect(@TypeOf(&bigger[2]) == *align(2) u64); try expect(@TypeOf(&bigger[3]) == *align(2) u64); // because pointer is align 2 and u32 align % 2 == 0 we can assume align 2 var smaller align(2) = [_]u32{ 1, 2, 3, 4 }; var runtime_zero: usize = 0; comptime try expect(@TypeOf(smaller[runtime_zero..]) == []align(2) u32); comptime try expect(@TypeOf(smaller[runtime_zero..].ptr) == [*]align(2) u32); try testIndex(smaller[runtime_zero..].ptr, 0, *align(2) u32); try testIndex(smaller[runtime_zero..].ptr, 1, *align(2) u32); try testIndex(smaller[runtime_zero..].ptr, 2, *align(2) u32); try testIndex(smaller[runtime_zero..].ptr, 3, *align(2) u32); // has to use ABI alignment because index known at runtime only try testIndex2(array[runtime_zero..].ptr, 0, *u8); try testIndex2(array[runtime_zero..].ptr, 1, *u8); try testIndex2(array[runtime_zero..].ptr, 2, *u8); try testIndex2(array[runtime_zero..].ptr, 3, *u8); } fn testIndex(smaller: [*]align(2) u32, index: usize, comptime T: type) !void { comptime try expect(@TypeOf(&smaller[index]) == T); } fn testIndex2(ptr: [*]align(4) u8, index: usize, comptime T: type) !void { comptime try expect(@TypeOf(&ptr[index]) == T); } test "alignstack" { try expect(fnWithAlignedStack() == 1234); } fn fnWithAlignedStack() i32 { @setAlignStack(256); return 1234; } test "alignment of function with c calling convention" { var runtime_nothing = nothing; const casted1 = @ptrCast(*const u8, runtime_nothing); const casted2 = @ptrCast(fn () callconv(.C) void, casted1); casted2(); } fn nothing() callconv(.C) void {} const DefaultAligned = struct { nevermind: u32, badguy: i128, }; test "read 128-bit field from default aligned struct in stack memory" { var default_aligned = DefaultAligned{ .nevermind = 1, .badguy = 12, }; try expect((@ptrToInt(&default_aligned.badguy) % 16) == 0); try expect(12 == default_aligned.badguy); } var default_aligned_global = DefaultAligned{ .nevermind = 1, .badguy = 12, }; test "read 128-bit field from default aligned struct in global memory" { try expect((@ptrToInt(&default_aligned_global.badguy) % 16) == 0); try expect(12 == default_aligned_global.badguy); } test "struct field explicit alignment" { const S = struct { const Node = struct { next: *Node, massive_byte: u8 align(64), }; }; var node: S.Node = undefined; node.massive_byte = 100; try expect(node.massive_byte == 100); comptime try expect(@TypeOf(&node.massive_byte) == *align(64) u8); try expect(@ptrToInt(&node.massive_byte) % 64 == 0); } test "align(@alignOf(T)) T does not force resolution of T" { const S = struct { const A = struct { a: *align(@alignOf(A)) A, }; fn doTheTest() void { suspend { resume @frame(); } _ = bar(@Frame(doTheTest)); } fn bar(comptime T: type) *align(@alignOf(T)) T { ok = true; return undefined; } var ok = false; }; _ = async S.doTheTest(); try expect(S.ok); } test "align(N) on functions" { // function alignment is a compile error on wasm32/wasm64 if (native_arch == .wasm32 or native_arch == .wasm64) return error.SkipZigTest; if (native_arch == .thumb) return error.SkipZigTest; try expect((@ptrToInt(overaligned_fn) & (0x1000 - 1)) == 0); } fn overaligned_fn() align(0x1000) i32 { return 42; }
test/behavior/align_stage1.zig
const builtin = @import("builtin"); const std = @import("std"); const expect = std.testing.expect; const mem = std.mem; const maxInt = std.math.maxInt; const native_endian = builtin.target.cpu.arch.endian(); test "pointer reinterpret const float to int" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO // The hex representation is 0x3fe3333333333303. const float: f64 = 5.99999999999994648725e-01; const float_ptr = &float; const int_ptr = @ptrCast(*const i32, float_ptr); const int_val = int_ptr.*; if (native_endian == .Little) try expect(int_val == 0x33333303) else try expect(int_val == 0x3fe33333); } test "@floatToInt" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO try testFloatToInts(); comptime try testFloatToInts(); } fn testFloatToInts() !void { try expectFloatToInt(f16, 255.1, u8, 255); try expectFloatToInt(f16, 127.2, i8, 127); try expectFloatToInt(f16, -128.2, i8, -128); } fn expectFloatToInt(comptime F: type, f: F, comptime I: type, i: I) !void { try expect(@floatToInt(I, f) == i); } test "implicit cast from [*]T to ?*anyopaque" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var a = [_]u8{ 3, 2, 1 }; var runtime_zero: usize = 0; incrementVoidPtrArray(a[runtime_zero..].ptr, 3); try expect(std.mem.eql(u8, &a, &[_]u8{ 4, 3, 2 })); } fn incrementVoidPtrArray(array: ?*anyopaque, len: usize) void { var n: usize = 0; while (n < len) : (n += 1) { @ptrCast([*]u8, array.?)[n] += 1; } } test "compile time int to ptr of function" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend == .stage2_llvm and builtin.cpu.arch == .aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO try foobar(FUNCTION_CONSTANT); } pub const FUNCTION_CONSTANT = @intToPtr(PFN_void, maxInt(usize)); pub const PFN_void = *const fn (*anyopaque) callconv(.C) void; fn foobar(func: PFN_void) !void { try std.testing.expect(@ptrToInt(func) == maxInt(usize)); } test "implicit ptr to *anyopaque" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var a: u32 = 1; var ptr: *align(@alignOf(u32)) anyopaque = &a; var b: *u32 = @ptrCast(*u32, ptr); try expect(b.* == 1); var ptr2: ?*align(@alignOf(u32)) anyopaque = &a; var c: *u32 = @ptrCast(*u32, ptr2.?); try expect(c.* == 1); } const A = struct { a: i32, }; test "return null from fn() anyerror!?&T" { const a = returnNullFromOptionalTypeErrorRef(); const b = returnNullLitFromOptionalTypeErrorRef(); try expect((try a) == null and (try b) == null); } fn returnNullFromOptionalTypeErrorRef() anyerror!?*A { const a: ?*A = null; return a; } fn returnNullLitFromOptionalTypeErrorRef() anyerror!?*A { return null; } test "peer type resolution: [0]u8 and []const u8" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO try expect(peerTypeEmptyArrayAndSlice(true, "hi").len == 0); try expect(peerTypeEmptyArrayAndSlice(false, "hi").len == 1); comptime { try expect(peerTypeEmptyArrayAndSlice(true, "hi").len == 0); try expect(peerTypeEmptyArrayAndSlice(false, "hi").len == 1); } } fn peerTypeEmptyArrayAndSlice(a: bool, slice: []const u8) []const u8 { if (a) { return &[_]u8{}; } return slice[0..1]; } test "implicitly cast from [N]T to ?[]const T" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO try expect(mem.eql(u8, castToOptionalSlice().?, "hi")); comptime try expect(mem.eql(u8, castToOptionalSlice().?, "hi")); } fn castToOptionalSlice() ?[]const u8 { return "hi"; } test "cast u128 to f128 and back" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO comptime try testCast128(); try testCast128(); } fn testCast128() !void { try expect(cast128Int(cast128Float(0x7fff0000000000000000000000000000)) == 0x7fff0000000000000000000000000000); } fn cast128Int(x: f128) u128 { return @bitCast(u128, x); } fn cast128Float(x: u128) f128 { return @bitCast(f128, x); } test "implicit cast from *[N]T to ?[*]T" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var x: ?[*]u16 = null; var y: [4]u16 = [4]u16{ 0, 1, 2, 3 }; x = &y; try expect(std.mem.eql(u16, x.?[0..4], y[0..4])); x.?[0] = 8; y[3] = 6; try expect(std.mem.eql(u16, x.?[0..4], y[0..4])); } test "implicit cast from *T to ?*anyopaque" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var a: u8 = 1; incrementVoidPtrValue(&a); try std.testing.expect(a == 2); } fn incrementVoidPtrValue(value: ?*anyopaque) void { @ptrCast(*u8, value.?).* += 1; } test "implicit cast *[0]T to E![]const u8" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var x = @as(anyerror![]const u8, &[0]u8{}); try expect((x catch unreachable).len == 0); } var global_array: [4]u8 = undefined; test "cast from array reference to fn: comptime fn ptr" { const f = @ptrCast(*const fn () callconv(.C) void, &global_array); try expect(@ptrToInt(f) == @ptrToInt(&global_array)); } test "cast from array reference to fn: runtime fn ptr" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var f = @ptrCast(*const fn () callconv(.C) void, &global_array); try expect(@ptrToInt(f) == @ptrToInt(&global_array)); } test "*const [N]null u8 to ?[]const u8" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { var a = "Hello"; var b: ?[]const u8 = a; try expect(mem.eql(u8, b.?, "Hello")); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "cast between [*c]T and ?[*:0]T on fn parameter" { const S = struct { const Handler = ?fn ([*c]const u8) callconv(.C) void; fn addCallback(handler: Handler) void { _ = handler; } fn myCallback(cstr: ?[*:0]const u8) callconv(.C) void { _ = cstr; } fn doTheTest() void { addCallback(myCallback); } }; S.doTheTest(); } var global_struct: struct { f0: usize } = undefined; test "assignment to optional pointer result loc" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO var foo: struct { ptr: ?*anyopaque } = .{ .ptr = &global_struct }; try expect(foo.ptr.? == @ptrCast(*anyopaque, &global_struct)); } test "cast between *[N]void and []void" { var a: [4]void = undefined; var b: []void = &a; try expect(b.len == 4); } test "peer resolve arrays of different size to const slice" { try expect(mem.eql(u8, boolToStr(true), "true")); try expect(mem.eql(u8, boolToStr(false), "false")); comptime try expect(mem.eql(u8, boolToStr(true), "true")); comptime try expect(mem.eql(u8, boolToStr(false), "false")); } fn boolToStr(b: bool) []const u8 { return if (b) "true" else "false"; } test "cast f16 to wider types" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { var x: f16 = 1234.0; try expect(@as(f32, 1234.0) == x); try expect(@as(f64, 1234.0) == x); try expect(@as(f128, 1234.0) == x); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "cast f128 to narrower types" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO const S = struct { fn doTheTest() !void { var x: f128 = 1234.0; try expect(@as(f16, 1234.0) == @floatCast(f16, x)); try expect(@as(f32, 1234.0) == @floatCast(f32, x)); try expect(@as(f64, 1234.0) == @floatCast(f64, x)); } }; try S.doTheTest(); comptime try S.doTheTest(); } test "peer type resolution: unreachable, null, slice" { if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO const S = struct { fn doTheTest(num: usize, word: []const u8) !void { const result = switch (num) { 0 => null, 1 => word, else => unreachable, }; try expect(mem.eql(u8, result.?, "hi")); } }; try S.doTheTest(1, "hi"); } test "cast i8 fn call peers to i32 result" { const S = struct { fn doTheTest() !void { var cond = true; const value: i32 = if (cond) smallBoi() else bigBoi(); try expect(value == 123); } fn smallBoi() i8 { return 123; } fn bigBoi() i16 { return 1234; } }; try S.doTheTest(); comptime try S.doTheTest(); }
test/behavior/cast_llvm.zig
const expect = @import("std").testing.expect; const pi = @import("std").math.pi; const e = @import("std").math.e; test "@sqrt" { comptime testSqrt(); testSqrt(); } fn testSqrt() void { { var a: f16 = 4; expect(@sqrt(f16, a) == 2); } { var a: f32 = 9; expect(@sqrt(f32, a) == 3); } { var a: f64 = 25; expect(@sqrt(f64, a) == 5); } { const a: comptime_float = 25.0; expect(@sqrt(comptime_float, a) == 5.0); } // Waiting on a c.zig implementation //{ // var a: f128 = 49; // expect(@sqrt(f128, a) == 7); //} } test "@sin" { comptime testSin(); testSin(); } fn testSin() void { // TODO - this is actually useful and should be implemented // (all the trig functions for f16) // but will probably wait till self-hosted //{ // var a: f16 = pi; // expect(@sin(f16, a/2) == 1); //} { var a: f32 = 0; expect(@sin(f32, a) == 0); } { var a: f64 = 0; expect(@sin(f64, a) == 0); } // TODO //{ // var a: f16 = pi; // expect(@sqrt(f128, a/2) == 1); //} } test "@cos" { comptime testCos(); testCos(); } fn testCos() void { { var a: f32 = 0; expect(@cos(f32, a) == 1); } { var a: f64 = 0; expect(@cos(f64, a) == 1); } } test "@exp" { comptime testExp(); testExp(); } fn testExp() void { { var a: f32 = 0; expect(@exp(f32, a) == 1); } { var a: f64 = 0; expect(@exp(f64, a) == 1); } } test "@exp2" { comptime testExp2(); testExp2(); } fn testExp2() void { { var a: f32 = 2; expect(@exp2(f32, a) == 4); } { var a: f64 = 2; expect(@exp2(f64, a) == 4); } } test "@ln" { // Old musl (and glibc?), and our current math.ln implementation do not return 1 // so also accept those values. comptime testLn(); testLn(); } fn testLn() void { { var a: f32 = e; expect(@ln(f32, a) == 1 or @ln(f32, a) == @bitCast(f32, u32(0x3f7fffff))); } { var a: f64 = e; expect(@ln(f64, a) == 1 or @ln(f64, a) == @bitCast(f64, u64(0x3ff0000000000000))); } } test "@log2" { comptime testLog2(); testLog2(); } fn testLog2() void { { var a: f32 = 4; expect(@log2(f32, a) == 2); } { var a: f64 = 4; expect(@log2(f64, a) == 2); } } test "@log10" { comptime testLog10(); testLog10(); } fn testLog10() void { { var a: f32 = 100; expect(@log10(f32, a) == 2); } { var a: f64 = 1000; expect(@log10(f64, a) == 3); } } test "@fabs" { comptime testFabs(); testFabs(); } fn testFabs() void { { var a: f32 = -2.5; var b: f32 = 2.5; expect(@fabs(f32, a) == 2.5); expect(@fabs(f32, b) == 2.5); } { var a: f64 = -2.5; var b: f64 = 2.5; expect(@fabs(f64, a) == 2.5); expect(@fabs(f64, b) == 2.5); } } test "@floor" { comptime testFloor(); testFloor(); } fn testFloor() void { { var a: f32 = 2.1; expect(@floor(f32, a) == 2); } { var a: f64 = 3.5; expect(@floor(f64, a) == 3); } } test "@ceil" { comptime testCeil(); testCeil(); } fn testCeil() void { { var a: f32 = 2.1; expect(@ceil(f32, a) == 3); } { var a: f64 = 3.5; expect(@ceil(f64, a) == 4); } } test "@trunc" { comptime testTrunc(); testTrunc(); } fn testTrunc() void { { var a: f32 = 2.1; expect(@trunc(f32, a) == 2); } { var a: f64 = -3.5; expect(@trunc(f64, a) == -3); } } // This is waiting on library support for the Windows build (not sure why the other's don't need it) //test "@nearbyInt" { // comptime testNearbyInt(); // testNearbyInt(); //} //fn testNearbyInt() void { // { // var a: f32 = 2.1; // expect(@nearbyInt(f32, a) == 2); // } // { // var a: f64 = -3.75; // expect(@nearbyInt(f64, a) == -4); // } //}
test/stage1/behavior/floatop.zig
const clap = @import("clap"); const std = @import("std"); const ston = @import("ston"); const util = @import("util"); const common = @import("common.zig"); const format = @import("format.zig"); const gen3 = @import("gen3.zig"); const gen4 = @import("gen4.zig"); const gen5 = @import("gen5.zig"); const rom = @import("rom.zig"); const fmt = std.fmt; const fs = std.fs; const heap = std.heap; const io = std.io; const log = std.log; const math = std.math; const mem = std.mem; const path = fs.path; const gba = rom.gba; const nds = rom.nds; const bit = util.bit; const lu128 = rom.int.lu128; const lu16 = rom.int.lu16; const lu32 = rom.int.lu32; const lu64 = rom.int.lu64; const Program = @This(); allocator: mem.Allocator, patch: PatchOption, no_output: bool, replace: bool, abort_on_first_warning: bool, out: []const u8, game: Game, old_bytes: std.ArrayListUnmanaged(u8), const PatchOption = enum { none, live, full, }; pub const main = util.generateMain(Program); pub const version = "0.0.0"; pub const description = \\Applies changes to Pokémon roms. \\ ; pub const params = &[_]clap.Param(clap.Help){ clap.parseParam("-a, --abort-on-first-warning Abort execution on the first warning emitted. ") catch unreachable, clap.parseParam("-h, --help Display this help text and exit. ") catch unreachable, clap.parseParam("-n, --no-output Don't output the file. ") catch unreachable, clap.parseParam("-o, --output <FILE> Override destination path. ") catch unreachable, clap.parseParam("-p, --patch <none|live|full> Output patch data to stdout when not 'none'. 'live' = patch after each line. 'full' = patch when done.") catch unreachable, clap.parseParam("-r, --replace Replace output file if it already exists. ") catch unreachable, clap.parseParam("-v, --version Output version information and exit. ") catch unreachable, clap.parseParam("<ROM> The rom to apply the changes to. ") catch unreachable, }; pub fn init(allocator: mem.Allocator, args: anytype) !Program { const pos = args.positionals(); const file_name = if (pos.len > 0) pos[0] else return error.MissingFile; const patch_arg = args.option("--patch") orelse "none"; const patch = std.meta.stringToEnum(PatchOption, patch_arg) orelse { log.err("--patch does not support '{s}'", .{patch_arg}); return error.InvalidArgument; }; var game = blk: { const file = try fs.cwd().openFile(file_name, .{}); defer file.close(); const gen3_error = if (gen3.Game.fromFile(file, allocator)) |game| { break :blk Game{ .gen3 = game }; } else |err| err; try file.seekTo(0); const nds_rom = try allocator.create(nds.Rom); errdefer allocator.destroy(nds_rom); nds_rom.* = nds.Rom.fromFile(file, allocator) catch |nds_error| { log.err("Failed to load '{s}' as a gen3 game: {}", .{ file_name, gen3_error }); log.err("Failed to load '{s}' as a gen4/gen5 game: {}", .{ file_name, nds_error }); return error.InvalidRom; }; errdefer nds_rom.deinit(); const gen4_error = if (gen4.Game.fromRom(allocator, nds_rom)) |game| { break :blk Game{ .gen4 = game }; } else |err| err; const gen5_error = if (gen5.Game.fromRom(allocator, nds_rom)) |game| { break :blk Game{ .gen5 = game }; } else |err| err; log.err("Successfully loaded '{s}' as a nds rom.", .{file_name}); log.err("Failed to load '{s}' as a gen4 game: {}", .{ file_name, gen4_error }); log.err("Failed to load '{s}' as a gen5 game: {}", .{ file_name, gen5_error }); return error.InvalidRom; }; errdefer game.deinit(); // When --patch is passed, we store a copy of the games old state, so that we // can generate binary patches between old and new versions. var old_bytes = std.ArrayListUnmanaged(u8){}; errdefer old_bytes.deinit(allocator); if (patch != .none) try old_bytes.appendSlice(allocator, game.data()); return Program{ .allocator = allocator, .no_output = args.flag("--no-output"), .replace = args.flag("--replace"), .abort_on_first_warning = args.flag("--abort-on-first-warning"), .out = args.option("--output") orelse try fmt.allocPrint(allocator, "{s}.modified", .{path.basename(file_name)}), .patch = patch, .game = game, .old_bytes = old_bytes, }; } pub fn run( program: *Program, comptime Reader: type, comptime Writer: type, stdio: util.CustomStdIoStreams(Reader, Writer), ) anyerror!void { try format.io(program.allocator, stdio.in, std.io.null_writer, .{ .program = program, .out = stdio.out, }, useGame); if (program.patch == .full) { var it = common.PatchIterator{ .old = program.old_bytes.items, .new = program.game.data(), }; while (it.next()) |p| { try stdio.out.print("[{}]={x}\n", .{ p.offset, fmt.fmtSliceHexLower(p.replacement), }); } } if (program.no_output) return; const out_file = try fs.cwd().createFile(program.out, .{ .exclusive = !program.replace, .truncate = false, }); try program.game.apply(); try program.game.write(out_file.writer()); const len = program.game.data().len; try out_file.setEndPos(len); } const Game = union(enum) { gen3: gen3.Game, gen4: gen4.Game, gen5: gen5.Game, fn data(game: Game) []const u8 { return switch (game) { .gen3 => |g| g.data, .gen4 => |g| g.rom.data.items, .gen5 => |g| g.rom.data.items, }; } fn apply(game: *Game) !void { switch (game.*) { .gen3 => |*g| try g.apply(), .gen4 => |*g| try g.apply(), .gen5 => |*g| try g.apply(), } } fn write(game: Game, writer: anytype) !void { switch (game) { .gen3 => |g| try g.write(writer), .gen4 => |g| try g.rom.write(writer), .gen5 => |g| try g.rom.write(writer), } } fn deinit(game: Game) void { switch (game) { .gen3 => |g| g.deinit(), .gen4 => |g| { g.rom.deinit(); g.allocator.destroy(g.rom); g.deinit(); }, .gen5 => |g| { g.rom.deinit(); g.allocator.destroy(g.rom); g.deinit(); }, } } }; fn useGame(ctx: anytype, game: format.Game) !void { const program = ctx.program; switch (program.game) { .gen3 => |*gen3_game| try applyGen3(gen3_game, game), .gen4 => |*gen4_game| try applyGen4(gen4_game.*, game), .gen5 => |*gen5_game| try applyGen5(gen5_game.*, game), } if (program.patch == .live) { try program.game.apply(); var it = common.PatchIterator{ .old = program.old_bytes.items, .new = program.game.data(), }; while (it.next()) |p| { try ctx.out.print("[{}]={x}\n", .{ p.offset, fmt.fmtSliceHexLower(p.replacement), }); try program.old_bytes.resize(program.allocator, math.max( program.old_bytes.items.len, p.offset + p.replacement.len, )); common.patch(program.old_bytes.items, &[_]common.Patch{p}); } try ctx.out.context.flush(); } } fn applyGen3(game: *gen3.Game, parsed: format.Game) !void { switch (parsed) { .version => |v| { if (v != game.version) return error.VersionDontMatch; }, .game_title => |title| { if (!mem.eql(u8, title, game.header.game_title.span())) return error.GameTitleDontMatch; }, .gamecode => |code| { if (!mem.eql(u8, code, &game.header.gamecode)) return error.GameCodeDontMatch; }, .starters => |starter| { if (starter.index >= game.starters.len) return error.Error; game.starters[starter.index].* = lu16.init(starter.value); game.starters_repeat[starter.index].* = lu16.init(starter.value); }, .text_delays => |delay| { if (delay.index >= game.text_delays.len) return error.Error; game.text_delays[delay.index] = delay.value; }, .trainers => |trainers| { if (trainers.index >= game.trainers.len) return error.Error; const trainer = &game.trainers[trainers.index]; const party = &game.trainer_parties[trainers.index]; switch (trainers.value) { .class => |class| trainer.class = class, .encounter_music => |encounter_music| trainer.encounter_music.music = try math.cast(u7, encounter_music), .trainer_picture => |trainer_picture| trainer.trainer_picture = trainer_picture, .party_type => |party_type| trainer.party_type = party_type, .party_size => |party_size| party.size = party_size, .name => |str| try applyGen3String(&trainer.name, str), .items => |items| { if (items.index >= trainer.items.len) return error.OutOfBound; trainer.items[items.index] = lu16.init(items.value); }, .party => |members| { if (members.index >= party.size) return error.Error; const member = &party.members[members.index]; switch (members.value) { .level => |level| member.base.level = lu16.init(level), .species => |species| member.base.species = lu16.init(species), .item => |item| member.item = lu16.init(item), .moves => |moves| { if (moves.index >= member.moves.len) return error.IndexOutOfBound; member.moves[moves.index] = lu16.init(moves.value); }, .ability => return error.DidNotConsumeData, } }, } }, .moves => |moves| { if (moves.index >= math.min(game.move_names.len, game.moves.len)) return error.Error; const move = &game.moves[moves.index]; const move_name = &game.move_names[moves.index]; switch (moves.value) { .name => |str| try applyGen3String(move_name, str), .effect => |effect| move.effect = effect, .power => |power| move.power = power, .type => |_type| move.type = _type, .accuracy => |accuracy| move.accuracy = accuracy, .pp => |pp| move.pp = pp, .target => |target| move.target = target, .priority => |priority| move.priority = priority, .category => |category| move.category = category, .description => return error.IndexOutOfBound, } }, .pokemons => |pokemons| { if (pokemons.index >= game.pokemons.len) return error.Error; const pokemon = &game.pokemons[pokemons.index]; switch (pokemons.value) { .stats => |stats| format.setField(&pokemon.stats, stats), .ev_yield => |ev_yield| format.setField(&pokemon.ev_yield, ev_yield), .items => |items| { if (items.index >= pokemon.items.len) return error.IndexOutOfBound; pokemon.items[items.index] = lu16.init(items.value); }, .types => |types| { if (types.index >= pokemon.types.len) return error.IndexOutOfBound; pokemon.types[types.index] = types.value; }, .egg_groups => |egg_groups| { if (egg_groups.index >= pokemon.egg_groups.len) return error.IndexOutOfBound; pokemon.egg_groups[egg_groups.index] = egg_groups.value; }, .abilities => |abilities| { if (abilities.index >= pokemon.abilities.len) return error.IndexOutOfBound; pokemon.abilities[abilities.index] = abilities.value; }, .moves => |moves| { if (pokemons.index >= game.level_up_learnset_pointers.len) return error.IndexOutOfBound; const ptr = &game.level_up_learnset_pointers[pokemons.index]; const lvl_up_moves = try ptr.toSliceZ2(game.data, gen3.LevelUpMove.term); if (moves.index >= lvl_up_moves.len) return error.IndexOutOfBound; const lvl_up_move = &lvl_up_moves[moves.index]; switch (moves.value) { .id => |id| lvl_up_move.id = try math.cast(u9, id), .level => |level| lvl_up_move.level = try math.cast(u7, level), } }, .evos => |evos| { if (pokemons.index >= game.evolutions.len) return error.IndexOutOfBound; const evolutions = &game.evolutions[pokemons.index]; if (evos.index >= evolutions.len) return error.IndexOutOfBound; const evolution = &evolutions[evos.index]; switch (evos.value) { .method => |method| evolution.method = switch (method) { .attack_eql_defense => .attack_eql_defense, .attack_gth_defense => .attack_gth_defense, .attack_lth_defense => .attack_lth_defense, .beauty => .beauty, .friend_ship => .friend_ship, .friend_ship_during_day => .friend_ship_during_day, .friend_ship_during_night => .friend_ship_during_night, .level_up => .level_up, .level_up_female => .level_up_female, .level_up_holding_item_during_daytime => .level_up_holding_item_during_daytime, .level_up_holding_item_during_the_night => .level_up_holding_item_during_the_night, .level_up_in_special_magnetic_field => .level_up_in_special_magnetic_field, .level_up_knowning_move => .level_up_knowning_move, .level_up_male => .level_up_male, .level_up_may_spawn_pokemon => .level_up_may_spawn_pokemon, .level_up_near_ice_rock => .level_up_near_ice_rock, .level_up_near_moss_rock => .level_up_near_moss_rock, .level_up_spawn_if_cond => .level_up_spawn_if_cond, .level_up_with_other_pokemon_in_party => .level_up_with_other_pokemon_in_party, .personality_value1 => .personality_value1, .personality_value2 => .personality_value2, .trade => .trade, .trade_holding_item => .trade_holding_item, .unused => .unused, .use_item => .use_item, .use_item_on_female => .use_item_on_female, .use_item_on_male => .use_item_on_male, .unknown_0x02, .unknown_0x03, .trade_with_pokemon, => return error.DidNotConsumeData, }, .param => |param| evolution.param = lu16.init(param), .target => |target| evolution.target = lu16.init(target), } }, .color => |color| pokemon.color.color = color, .catch_rate => |catch_rate| pokemon.catch_rate = catch_rate, .base_exp_yield => |base_exp_yield| pokemon.base_exp_yield = try math.cast(u8, base_exp_yield), .gender_ratio => |gender_ratio| pokemon.gender_ratio = gender_ratio, .egg_cycles => |egg_cycles| pokemon.egg_cycles = egg_cycles, .base_friendship => |base_friendship| pokemon.base_friendship = base_friendship, .growth_rate => |growth_rate| pokemon.growth_rate = growth_rate, .tms, .hms => |ms| { const is_tms = pokemons.value == .tms; const len = if (is_tms) game.tms.len else game.hms.len; if (ms.index >= len) return error.Error; const index = ms.index + game.tms.len * @boolToInt(!is_tms); const learnset = &game.machine_learnsets[pokemons.index]; learnset.* = lu64.init(bit.setTo(u64, learnset.value(), @intCast(u6, index), ms.value)); }, .name => |str| { if (pokemons.index >= game.pokemon_names.len) return error.Error; try applyGen3String(&game.pokemon_names[pokemons.index], str); }, .pokedex_entry => |entry| { if (pokemons.index == 0 or pokemons.index - 1 >= game.species_to_national_dex.len) return error.Error; game.species_to_national_dex[pokemons.index - 1] = lu16.init(entry); }, } }, .abilities => |abilities| { if (abilities.index >= game.ability_names.len) return error.Error; const ability_name = &game.ability_names[abilities.index]; switch (abilities.value) { .name => |str| try applyGen3String(ability_name, str), } }, .types => |types| { if (types.index >= game.type_names.len) return error.Error; const type_name = &game.type_names[types.index]; switch (types.value) { .name => |str| try applyGen3String(type_name, str), } }, .tms, .hms => |ms| { const pick = switch (parsed) { .tms => game.tms, .hms => game.hms, else => unreachable, }; if (ms.index >= pick.len) return error.IndexOutOfBound; pick[ms.index] = lu16.init(ms.value); }, .items => |items| { if (items.index >= game.items.len) return error.Error; const item = &game.items[items.index]; switch (items.value) { .price => |price| item.price = lu16.init(try math.cast(u16, price)), .battle_effect => |battle_effect| item.battle_effect = battle_effect, .name => |str| try applyGen3String(&item.name, str), .description => |str| { const desc_small = try item.description.toSliceZ(game.data); const desc = try item.description.toSlice(game.data, desc_small.len + 1); applyGen3String(desc, str) catch unreachable; }, .pocket => |pocket| switch (game.version) { .ruby, .sapphire, .emerald => item.pocket = gen3.Pocket{ .rse = switch (pocket) { .none => .none, .items => .items, .key_items => .key_items, .poke_balls => .poke_balls, .tms_hms => .tms_hms, .berries => .berries, }, }, .fire_red, .leaf_green => item.pocket = gen3.Pocket{ .frlg = switch (pocket) { .none => .none, .items => .items, .key_items => .key_items, .poke_balls => .poke_balls, .tms_hms => .tms_hms, .berries => .berries, }, }, else => unreachable, }, } }, .pokedex => |pokedex| { switch (game.version) { .emerald => { if (pokedex.index >= game.pokedex.emerald.len) return error.Error; const entry = &game.pokedex.emerald[pokedex.index]; switch (pokedex.value) { .height => |height| entry.height = lu16.init(try math.cast(u16, height)), .weight => |weight| entry.weight = lu16.init(try math.cast(u16, weight)), .category => return error.DidNotConsumeData, } }, .ruby, .sapphire, .fire_red, .leaf_green, => { if (pokedex.index >= game.pokedex.rsfrlg.len) return error.Error; const entry = &game.pokedex.rsfrlg[pokedex.index]; switch (pokedex.value) { .height => |height| entry.height = lu16.init(try math.cast(u16, height)), .weight => |weight| entry.weight = lu16.init(try math.cast(u16, weight)), .category => return error.DidNotConsumeData, } }, else => unreachable, } }, .maps => |maps| { if (maps.index >= game.map_headers.len) return error.Error; const header = &game.map_headers[maps.index]; switch (maps.value) { .music => |music| header.music = lu16.init(music), .cave => |cave| header.cave = cave, .weather => |weather| header.weather = weather, .type => |_type| header.map_type = _type, .escape_rope => |escape_rope| header.escape_rope = escape_rope, .battle_scene => |battle_scene| header.map_battle_scene = battle_scene, .allow_cycling => |allow_cycling| header.flags.allow_cycling = allow_cycling, .allow_escaping => |allow_escaping| header.flags.allow_escaping = allow_escaping, .allow_running => |allow_running| header.flags.allow_running = allow_running, .show_map_name => |show_map_name| header.flags.show_map_name = show_map_name, } }, .wild_pokemons => |pokemons| { if (pokemons.index >= game.wild_pokemon_headers.len) return error.Error; const header = &game.wild_pokemon_headers[pokemons.index]; switch (pokemons.value) { .grass_0 => |area| { const land = try header.land.toPtr(game.data); const wilds = try land.wild_pokemons.toPtr(game.data); try applyGen3Area(area, &land.encounter_rate, wilds); }, .surf_0 => |area| { const surf = try header.surf.toPtr(game.data); const wilds = try surf.wild_pokemons.toPtr(game.data); try applyGen3Area(area, &surf.encounter_rate, wilds); }, .rock_smash => |area| { const rock = try header.rock_smash.toPtr(game.data); const wilds = try rock.wild_pokemons.toPtr(game.data); try applyGen3Area(area, &rock.encounter_rate, wilds); }, .fishing_0 => |area| { const fish = try header.fishing.toPtr(game.data); const wilds = try fish.wild_pokemons.toPtr(game.data); try applyGen3Area(area, &fish.encounter_rate, wilds); }, .grass_1, .grass_2, .grass_3, .grass_4, .grass_5, .grass_6, .dark_grass_0, .dark_grass_1, .dark_grass_2, .dark_grass_3, .rustling_grass_0, .rustling_grass_1, .rustling_grass_2, .rustling_grass_3, .surf_1, .surf_2, .surf_3, .ripple_surf_0, .ripple_surf_1, .ripple_surf_2, .ripple_surf_3, .fishing_1, .fishing_2, .fishing_3, .ripple_fishing_0, .ripple_fishing_1, .ripple_fishing_2, .ripple_fishing_3, => return error.DidNotConsumeData, } }, .static_pokemons => |pokemons| { if (pokemons.index >= game.static_pokemons.len) return error.Error; const static_mon = game.static_pokemons[pokemons.index]; switch (pokemons.value) { .species => |species| static_mon.species.* = lu16.init(species), .level => |level| static_mon.level.* = try math.cast(u8, level), } }, .given_pokemons => |pokemons| { if (pokemons.index >= game.given_pokemons.len) return error.Error; const given_mon = game.given_pokemons[pokemons.index]; switch (pokemons.value) { .species => |species| given_mon.species.* = lu16.init(species), .level => |level| given_mon.level.* = try math.cast(u8, level), } }, .pokeball_items => |items| { if (items.index >= game.pokeball_items.len) return error.OutOfBound; const given_item = game.pokeball_items[items.index]; switch (items.value) { .item => |item| given_item.item.* = lu16.init(item), .amount => |amount| given_item.amount.* = lu16.init(amount), } }, .text => |texts| { if (texts.index >= game.text.len) return error.Error; const text_ptr = game.text[texts.index]; const text_slice = try text_ptr.toSliceZ(game.data); // Slice to include the sentinel inside the slice. const text = text_slice[0 .. text_slice.len + 1]; try applyGen3String(text, texts.value); }, .hidden_hollows, .instant_text, => return error.DidNotConsumeData, } } fn applyGen3Area(area: format.WildArea, rate: *u8, wilds: []gen3.WildPokemon) !void { switch (area) { .encounter_rate => |encounter_rate| rate.* = try math.cast(u8, encounter_rate), .pokemons => |pokemons| { if (pokemons.index >= wilds.len) return error.IndexOutOfBound; const wild = &wilds[pokemons.index]; switch (pokemons.value) { .min_level => |min_level| wild.min_level = min_level, .max_level => |max_level| wild.max_level = max_level, .species => |species| wild.species = lu16.init(species), } }, } } fn applyGen3String(out: []u8, str: []const u8) !void { var fbs = io.fixedBufferStream(str); var unescape = util.escape.default.unescapingReader(fbs.reader()); try gen3.encodings.encode(.en_us, unescape.reader(), out); } fn applyGen4(game: gen4.Game, parsed: format.Game) !void { const header = game.rom.header(); switch (parsed) { .version => |v| { if (v != game.info.version) return error.VersionDontMatch; }, .game_title => |game_title| { if (!mem.eql(u8, game_title, header.game_title.span())) return error.GameTitleDontMatch; }, .gamecode => |gamecode| { if (!mem.eql(u8, gamecode, &header.gamecode)) return error.GameCodeDontMatch; }, .instant_text => |instant_text| { if (instant_text) common.patch(game.owned.arm9, game.info.instant_text_patch); }, .starters => |starters| { if (starters.index >= game.ptrs.starters.len) return error.Error; game.ptrs.starters[starters.index].* = lu16.init(starters.value); }, .trainers => |trainers| { if (trainers.index >= game.ptrs.trainers.len) return error.Error; const trainer = &game.ptrs.trainers[trainers.index]; switch (trainers.value) { .class => |class| trainer.class = class, .party_size => |party_size| trainer.party_size = party_size, .party_type => |party_type| trainer.party_type = party_type, .items => |items| { if (items.index >= trainer.items.len) return error.IndexOutOfBound; trainer.items[items.index] = lu16.init(items.value); }, .party => |party| { if (trainers.index >= game.owned.trainer_parties.len) return error.Error; if (party.index >= trainer.party_size) return error.Error; const member = &game.owned.trainer_parties[trainers.index][party.index]; switch (party.value) { .ability => |ability| member.base.gender_ability.ability = ability, .level => |level| member.base.level = lu16.init(level), .species => |species| member.base.species = lu16.init(species), .item => |item| member.item = lu16.init(item), .moves => |moves| { if (moves.index >= member.moves.len) return error.IndexOutOfBound; member.moves[moves.index] = lu16.init(moves.value); }, } }, .encounter_music, .trainer_picture, .name, => return error.DidNotConsumeData, } }, .moves => |moves| { if (moves.index >= game.ptrs.moves.len) return error.Error; const descriptions = game.owned.text.move_descriptions; const names = game.owned.text.move_names; const move = &game.ptrs.moves[moves.index]; switch (moves.value) { .description => |str| try applyGen4String(descriptions, moves.index, str), .name => |str| try applyGen4String(names, moves.index, str), .power => |power| move.power = power, .type => |_type| move.type = _type, .accuracy => |accuracy| move.accuracy = accuracy, .pp => |pp| move.pp = pp, .category => |category| move.category = category, .effect, .priority, .target, => return error.DidNotConsumeData, } }, .items => |items| { const descriptions = game.owned.text.item_descriptions; const names = game.owned.text.item_names; switch (items.value) { .description => |str| return applyGen4String(descriptions, items.index, str), .name => |str| return applyGen4String(names, items.index, str), .price, .battle_effect, .pocket, => {}, } if (items.index >= game.ptrs.items.len) return error.IndexOutOfBound; const item = &game.ptrs.items[items.index]; switch (items.value) { .description, .name => unreachable, .price => |price| item.price = lu16.init(try math.cast(u16, price)), .battle_effect => |battle_effect| item.battle_effect = battle_effect, .pocket => |pocket| item.pocket.pocket = switch (pocket) { .items => .items, .key_items => .key_items, .tms_hms => .tms_hms, .berries => .berries, .poke_balls => .poke_balls, .none => return error.DidNotConsumeData, }, } }, .pokedex => |pokedex| { switch (pokedex.value) { .height => |height| { if (pokedex.index >= game.ptrs.pokedex_heights.len) return error.Error; game.ptrs.pokedex_heights[pokedex.index] = lu32.init(height); }, .weight => |weight| { if (pokedex.index >= game.ptrs.pokedex_weights.len) return error.Error; game.ptrs.pokedex_weights[pokedex.index] = lu32.init(weight); }, .category => return error.DidNotConsumeData, } }, .abilities => |abilities| { const names = game.owned.text.ability_names; switch (abilities.value) { .name => |str| try applyGen4String(names, abilities.index, str), } }, .types => |types| { const names = game.owned.text.type_names; switch (types.value) { .name => |str| try applyGen4String(names, types.index, str), } }, .pokemons => |pokemons| { if (pokemons.index >= game.ptrs.pokemons.len) return error.Error; const names = game.owned.text.pokemon_names; const pokemon = &game.ptrs.pokemons[pokemons.index]; switch (pokemons.value) { .stats => |stats| format.setField(&pokemon.stats, stats), .ev_yield => |ev_yield| format.setField(&pokemon.ev_yield, ev_yield), .items => |items| { if (items.index >= pokemon.items.len) return error.IndexOutOfBound; pokemon.items[items.index] = lu16.init(items.value); }, .types => |types| { if (types.index >= pokemon.types.len) return error.IndexOutOfBound; pokemon.types[types.index] = types.value; }, .egg_groups => |egg_groups| { if (egg_groups.index >= pokemon.egg_groups.len) return error.IndexOutOfBound; pokemon.egg_groups[egg_groups.index] = egg_groups.value; }, .abilities => |abilities| { if (abilities.index >= pokemon.abilities.len) return error.IndexOutOfBound; pokemon.abilities[abilities.index] = abilities.value; }, .catch_rate => |catch_rate| pokemon.catch_rate = catch_rate, .base_exp_yield => |base_exp_yield| pokemon.base_exp_yield = try math.cast(u8, base_exp_yield), .gender_ratio => |gender_ratio| pokemon.gender_ratio = gender_ratio, .egg_cycles => |egg_cycles| pokemon.egg_cycles = egg_cycles, .base_friendship => |base_friendship| pokemon.base_friendship = base_friendship, .growth_rate => |growth_rate| pokemon.growth_rate = growth_rate, .color => |color| pokemon.color.color = color, .name => |str| try applyGen4String(names, pokemons.index, str), .tms, .hms => |ms| { const is_tms = pokemons.value == .tms; const len = if (is_tms) game.ptrs.tms.len else game.ptrs.hms.len; if (ms.index >= len) return error.Error; const index = ms.index + game.ptrs.tms.len * @boolToInt(!is_tms); const learnset = &pokemon.machine_learnset; learnset.* = lu128.init(bit.setTo(u128, learnset.value(), @intCast(u7, index), ms.value)); }, .moves => |moves| { const bytes = game.ptrs.level_up_moves.fileData(.{ .i = @intCast(u32, pokemons.index) }); const rem = bytes.len % @sizeOf(gen4.LevelUpMove); const lvl_up_moves = mem.bytesAsSlice(gen4.LevelUpMove, bytes[0 .. bytes.len - rem]); if (moves.index >= lvl_up_moves.len) return error.IndexOutOfBound; const lvl_up_move = &lvl_up_moves[moves.index]; switch (moves.value) { .id => |id| lvl_up_move.id = try math.cast(u9, id), .level => |level| lvl_up_move.level = try math.cast(u7, level), } }, .evos => |evos| { if (pokemons.index >= game.ptrs.evolutions.len) return error.IndexOutOfBound; const evolutions = &game.ptrs.evolutions[pokemons.index].items; if (evos.index >= evolutions.len) return error.IndexOutOfBound; const evolution = &evolutions[evos.index]; switch (evos.value) { .method => |method| evolution.method = switch (method) { .attack_eql_defense => .attack_eql_defense, .attack_gth_defense => .attack_gth_defense, .attack_lth_defense => .attack_lth_defense, .beauty => .beauty, .friend_ship => .friend_ship, .friend_ship_during_day => .friend_ship_during_day, .friend_ship_during_night => .friend_ship_during_night, .level_up => .level_up, .level_up_female => .level_up_female, .level_up_holding_item_during_daytime => .level_up_holding_item_during_daytime, .level_up_holding_item_during_the_night => .level_up_holding_item_during_the_night, .level_up_in_special_magnetic_field => .level_up_in_special_magnetic_field, .level_up_knowning_move => .level_up_knowning_move, .level_up_male => .level_up_male, .level_up_may_spawn_pokemon => .level_up_may_spawn_pokemon, .level_up_near_ice_rock => .level_up_near_ice_rock, .level_up_near_moss_rock => .level_up_near_moss_rock, .level_up_spawn_if_cond => .level_up_spawn_if_cond, .level_up_with_other_pokemon_in_party => .level_up_with_other_pokemon_in_party, .personality_value1 => .personality_value1, .personality_value2 => .personality_value2, .trade => .trade, .trade_holding_item => .trade_holding_item, .unused => .unused, .use_item => .use_item, .use_item_on_female => .use_item_on_female, .use_item_on_male => .use_item_on_male, .unknown_0x02, .unknown_0x03, .trade_with_pokemon, => return error.DidNotConsumeData, }, .param => |param| evolution.param = lu16.init(param), .target => |target| evolution.target = lu16.init(target), } }, .pokedex_entry => |pokedex_entry| { if (pokemons.index == 0 or pokemons.index - 1 >= game.ptrs.species_to_national_dex.len) return error.Error; game.ptrs.species_to_national_dex[pokemons.index - 1] = lu16.init(pokedex_entry); }, } }, .tms, .hms => |ms| { const pick = switch (parsed) { .tms => game.ptrs.tms, .hms => game.ptrs.hms, else => unreachable, }; if (ms.index >= pick.len) return error.IndexOutOfBound; pick[ms.index] = lu16.init(ms.value); }, .wild_pokemons => |pokemons| { const wild_pokemons = game.ptrs.wild_pokemons; switch (game.info.version) { .diamond, .pearl, .platinum, => { if (pokemons.index >= wild_pokemons.dppt.len) return error.IndexOutOfBound; const wilds = &wild_pokemons.dppt[pokemons.index]; switch (pokemons.value) { .grass_0 => |grass| switch (grass) { .encounter_rate => |encounter_rate| wilds.grass_rate = lu32.init(encounter_rate), .pokemons => |mons| { if (mons.index >= wilds.grass.len) return error.IndexOutOfBound; const mon = &wilds.grass[mons.index]; switch (mons.value) { .min_level => |min_level| mon.level = min_level, .max_level => |max_level| mon.level = max_level, .species => |species| mon.species = lu16.init(species), } }, }, .grass_1 => |area| try applyDpptReplacement(area, &wilds.swarm_replace), .grass_2 => |area| try applyDpptReplacement(area, &wilds.day_replace), .grass_3 => |area| try applyDpptReplacement(area, &wilds.night_replace), .grass_4 => |area| try applyDpptReplacement(area, &wilds.radar_replace), .grass_5 => |area| try applyDpptReplacement(area, &wilds.unknown_replace), .grass_6 => |area| try applyDpptReplacement(area, &wilds.gba_replace), .surf_0 => |area| try applyDpptSea(area, &wilds.surf), .surf_1 => |area| try applyDpptSea(area, &wilds.sea_unknown), .fishing_0 => |area| try applyDpptSea(area, &wilds.old_rod), .fishing_1 => |area| try applyDpptSea(area, &wilds.good_rod), .fishing_2 => |area| try applyDpptSea(area, &wilds.super_rod), .dark_grass_0, .dark_grass_1, .dark_grass_2, .dark_grass_3, .rustling_grass_0, .rustling_grass_1, .rustling_grass_2, .rustling_grass_3, .surf_2, .surf_3, .ripple_surf_0, .ripple_surf_1, .ripple_surf_2, .ripple_surf_3, .fishing_3, .ripple_fishing_0, .ripple_fishing_1, .ripple_fishing_2, .ripple_fishing_3, .rock_smash, => return error.DidNotConsumeData, } }, .heart_gold, .soul_silver, => { if (pokemons.index >= wild_pokemons.hgss.len) return error.IndexOutOfBound; const wilds = &wild_pokemons.hgss[pokemons.index]; switch (pokemons.value) { .grass_0 => |area| try applyHgssGrass(area, wilds, &wilds.grass_morning), .grass_1 => |area| try applyHgssGrass(area, wilds, &wilds.grass_day), .grass_2 => |area| try applyHgssGrass(area, wilds, &wilds.grass_night), .surf_0 => |area| try applyHgssSea(area, &wilds.sea_rates[0], &wilds.surf), .surf_1 => |area| try applyHgssSea(area, &wilds.sea_rates[1], &wilds.sea_unknown), .fishing_0 => |area| try applyHgssSea(area, &wilds.sea_rates[2], &wilds.old_rod), .fishing_1 => |area| try applyHgssSea(area, &wilds.sea_rates[3], &wilds.good_rod), .fishing_2 => |area| try applyHgssSea(area, &wilds.sea_rates[4], &wilds.super_rod), .grass_3, .grass_4, .grass_5, .grass_6, .dark_grass_0, .dark_grass_1, .dark_grass_2, .dark_grass_3, .rustling_grass_0, .rustling_grass_1, .rustling_grass_2, .rustling_grass_3, .surf_2, .surf_3, .ripple_surf_0, .ripple_surf_1, .ripple_surf_2, .ripple_surf_3, .fishing_3, .ripple_fishing_0, .ripple_fishing_1, .ripple_fishing_2, .ripple_fishing_3, .rock_smash, => return error.DidNotConsumeData, } }, else => unreachable, } }, .static_pokemons => |pokemons| { if (pokemons.index >= game.ptrs.static_pokemons.len) return error.Error; const static_mon = game.ptrs.static_pokemons[pokemons.index]; switch (pokemons.value) { .species => |species| static_mon.species.* = lu16.init(species), .level => |level| static_mon.level.* = lu16.init(level), } }, .given_pokemons => |pokemons| { if (pokemons.index >= game.ptrs.given_pokemons.len) return error.Error; const given_mon = game.ptrs.given_pokemons[pokemons.index]; switch (pokemons.value) { .species => |species| given_mon.species.* = lu16.init(species), .level => |level| given_mon.level.* = lu16.init(level), } }, .pokeball_items => |items| { if (items.index >= game.ptrs.pokeball_items.len) return error.Error; const given_item = game.ptrs.pokeball_items[items.index]; switch (items.value) { .item => |item| given_item.item.* = lu16.init(item), .amount => |amount| given_item.amount.* = lu16.init(amount), } }, .hidden_hollows, .text, .maps, .text_delays, => return error.DidNotConsumeData, } } fn applyHgssGrass(area: format.WildArea, wilds: *gen4.HgssWildPokemons, grass: *[12]lu16) !void { switch (area) { .encounter_rate => |encounter_rate| wilds.grass_rate = try math.cast(u8, encounter_rate), .pokemons => |pokemons| { if (pokemons.index >= grass.len) return error.Error; switch (pokemons.value) { .min_level => |min_level| wilds.grass_levels[pokemons.index] = min_level, .max_level => |max_level| wilds.grass_levels[pokemons.index] = max_level, .species => |species| grass[pokemons.index] = lu16.init(species), } }, } } fn applyHgssSea(area: format.WildArea, rate: *u8, sea: []gen4.HgssWildPokemons.Sea) !void { switch (area) { .encounter_rate => |encounter_rate| rate.* = try math.cast(u8, encounter_rate), .pokemons => |pokemons| { if (pokemons.index >= sea.len) return error.IndexOutOfBound; const mon = &sea[pokemons.index]; switch (pokemons.value) { .species => |species| mon.species = lu16.init(species), .min_level => |min_level| mon.min_level = min_level, .max_level => |max_level| mon.max_level = max_level, } }, } } fn applyDpptReplacement(area: format.WildArea, replacements: []gen4.DpptWildPokemons.Replacement) !void { switch (area) { .pokemons => |pokemons| { if (pokemons.index >= replacements.len) return error.IndexOutOfBound; const replacement = &replacements[pokemons.index]; switch (pokemons.value) { .species => |species| replacement.species = lu16.init(species), .min_level, .max_level, => return error.DidNotConsumeData, } }, .encounter_rate => return error.DidNotConsumeData, } } fn applyDpptSea(area: format.WildArea, sea: *gen4.DpptWildPokemons.Sea) !void { switch (area) { .encounter_rate => |encounter_rate| sea.rate = lu32.init(encounter_rate), .pokemons => |pokemons| { if (pokemons.index >= sea.mons.len) return error.IndexOutOfBound; const mon = &sea.mons[pokemons.index]; switch (pokemons.value) { .species => |species| mon.species = lu16.init(species), .min_level => |min_level| mon.min_level = min_level, .max_level => |max_level| mon.max_level = max_level, } }, } } fn applyGen4String(strs: gen4.StringTable, index: usize, value: []const u8) !void { if (strs.number_of_strings <= index) return error.Error; const buf = strs.get(index); const writer = io.fixedBufferStream(buf).writer(); try util.escape.default.unescapeWrite(writer, value); // Null terminate, if we didn't fill the buffer if (writer.context.pos < buf.len) buf[writer.context.pos] = 0; } fn applyGen5(game: gen5.Game, parsed: format.Game) !void { const header = game.rom.header(); switch (parsed) { .version => |v| { if (v != game.info.version) return error.VersionDontMatch; }, .game_title => |game_title| { if (!mem.eql(u8, game_title, header.game_title.span())) return error.GameTitleDontMatch; }, .gamecode => |gamecode| { if (!mem.eql(u8, gamecode, &header.gamecode)) return error.GameCodeDontMatch; }, .instant_text => |instant_text| { if (instant_text) common.patch(game.owned.arm9, game.info.instant_text_patch); }, .starters => |starters| { if (starters.index >= game.ptrs.starters.len) return error.Error; for (game.ptrs.starters[starters.index]) |starter| starter.* = lu16.init(starters.value); }, .trainers => |trainers| { if (trainers.index == 0 or trainers.index - 1 >= game.ptrs.trainers.len) return error.Error; const names = game.owned.text.trainer_names; const trainer = &game.ptrs.trainers[trainers.index - 1]; switch (trainers.value) { .class => |class| trainer.class = class, .name => |str| try applyGen5String(names, trainers.index, str), .items => |items| { if (items.index >= trainer.items.len) return error.IndexOutOfBound; trainer.items[items.index] = lu16.init(items.value); }, .party_size => |party_size| trainer.party_size = party_size, .party_type => |party_type| trainer.party_type = party_type, .party => |party| { if (trainers.index >= game.owned.trainer_parties.len) return error.Error; if (party.index >= trainer.party_size) return error.Error; const member = &game.owned.trainer_parties[trainers.index][party.index]; switch (party.value) { .ability => |ability| member.base.gender_ability.ability = ability, .level => |level| member.base.level = level, .species => |species| member.base.species = lu16.init(species), .item => |item| member.item = lu16.init(item), .moves => |moves| { if (moves.index >= member.moves.len) return error.IndexOutOfBound; member.moves[moves.index] = lu16.init(moves.value); }, } }, .encounter_music, .trainer_picture, => return error.DidNotConsumeData, } }, .pokemons => |pokemons| { if (pokemons.index >= game.ptrs.pokemons.fat.len) return error.Error; const names = game.owned.text.pokemon_names; const pokemon = try game.ptrs.pokemons.fileAs(.{ .i = pokemons.index }, gen5.BasePokemon); switch (pokemons.value) { .stats => |stats| format.setField(&pokemon.stats, stats), .ev_yield => |ev_yield| format.setField(&pokemon.ev_yield, ev_yield), .items => |items| { if (items.index >= pokemon.items.len) return error.IndexOutOfBound; pokemon.items[items.index] = lu16.init(items.value); }, .types => |types| { if (types.index >= pokemon.types.len) return error.IndexOutOfBound; pokemon.types[types.index] = types.value; }, .egg_groups => |egg_groups| { if (egg_groups.index >= pokemon.egg_groups.len) return error.IndexOutOfBound; pokemon.egg_groups[egg_groups.index] = egg_groups.value; }, .abilities => |abilities| { if (abilities.index >= pokemon.abilities.len) return error.IndexOutOfBound; pokemon.abilities[abilities.index] = abilities.value; }, .catch_rate => |catch_rate| pokemon.catch_rate = catch_rate, .gender_ratio => |gender_ratio| pokemon.gender_ratio = gender_ratio, .egg_cycles => |egg_cycles| pokemon.egg_cycles = egg_cycles, .base_friendship => |base_friendship| pokemon.base_friendship = base_friendship, .base_exp_yield => |base_exp_yield| pokemon.base_exp_yield = lu16.init(base_exp_yield), .growth_rate => |growth_rate| pokemon.growth_rate = growth_rate, .color => |color| pokemon.color.color = color, .name => |str| try applyGen5String(names, pokemons.index, str), .tms, .hms => |ms| { const is_tms = pokemons.value == .tms; const len = if (is_tms) game.ptrs.tms1.len + game.ptrs.tms2.len else game.ptrs.hms.len; if (ms.index >= len) return error.Error; const index = if (is_tms) ms.index else ms.index + game.ptrs.tms1.len + game.ptrs.tms2.len; const learnset = &pokemon.machine_learnset; learnset.* = lu128.init(bit.setTo(u128, learnset.value(), @intCast(u7, index), ms.value)); }, .moves => |moves| { const bytes = game.ptrs.level_up_moves.fileData(.{ .i = pokemons.index }); const rem = bytes.len % @sizeOf(gen5.LevelUpMove); const lvl_up_moves = mem.bytesAsSlice(gen5.LevelUpMove, bytes[0 .. bytes.len - rem]); if (moves.index >= lvl_up_moves.len) return error.IndexOutOfBound; const lvl_up_move = &lvl_up_moves[moves.index]; switch (moves.value) { .id => |id| lvl_up_move.id = lu16.init(id), .level => |level| lvl_up_move.level = lu16.init(level), } }, .evos => |evos| { if (pokemons.index >= game.ptrs.evolutions.len) return error.Error; const evolutions = &game.ptrs.evolutions[pokemons.index].items; if (evos.index >= evolutions.len) return error.IndexOutOfBound; const evolution = &evolutions[evos.index]; switch (evos.value) { .method => |method| evolution.method = switch (method) { .attack_eql_defense => .attack_eql_defense, .attack_gth_defense => .attack_gth_defense, .attack_lth_defense => .attack_lth_defense, .beauty => .beauty, .friend_ship => .friend_ship, .level_up => .level_up, .level_up_female => .level_up_female, .level_up_holding_item_during_daytime => .level_up_holding_item_during_daytime, .level_up_holding_item_during_the_night => .level_up_holding_item_during_the_night, .level_up_in_special_magnetic_field => .level_up_in_special_magnetic_field, .level_up_knowning_move => .level_up_knowning_move, .level_up_male => .level_up_male, .level_up_may_spawn_pokemon => .level_up_may_spawn_pokemon, .level_up_near_ice_rock => .level_up_near_ice_rock, .level_up_near_moss_rock => .level_up_near_moss_rock, .level_up_spawn_if_cond => .level_up_spawn_if_cond, .level_up_with_other_pokemon_in_party => .level_up_with_other_pokemon_in_party, .personality_value1 => .personality_value1, .personality_value2 => .personality_value2, .trade => .trade, .trade_holding_item => .trade_holding_item, .unused => .unused, .use_item => .use_item, .use_item_on_female => .use_item_on_female, .use_item_on_male => .use_item_on_male, .unknown_0x02 => .unknown_0x02, .unknown_0x03 => .unknown_0x03, .trade_with_pokemon => .trade_with_pokemon, .friend_ship_during_day, .friend_ship_during_night, => return error.DidNotConsumeData, }, .param => |param| evolution.param = lu16.init(param), .target => |target| evolution.target = lu16.init(target), } }, .pokedex_entry => |pokedex_entry| { if (pokemons.index != pokedex_entry) return error.TryingToChangeReadOnlyField; }, } }, .tms => |tms| { if (tms.index >= game.ptrs.tms1.len + game.ptrs.tms2.len) return error.IndexOutOfBound; if (tms.index < game.ptrs.tms1.len) { game.ptrs.tms1[tms.index] = lu16.init(tms.value); } else { game.ptrs.tms2[tms.index - game.ptrs.tms1.len] = lu16.init(tms.value); } }, .hms => |hms| { if (hms.index >= game.ptrs.hms.len) return error.IndexOutOfBound; game.ptrs.hms[hms.index] = lu16.init(hms.value); }, .items => |items| { if (items.index >= game.ptrs.items.len) return error.IndexOutOfBound; const descriptions = game.owned.text.item_descriptions; const item = &game.ptrs.items[items.index]; switch (items.value) { .price => |price| item.price = lu16.init(try math.cast(u16, price / 10)), .battle_effect => |battle_effect| item.battle_effect = battle_effect, .description => |str| try applyGen5String(descriptions, items.index, str), .name => |str| { const names_on_ground = game.owned.text.item_names_on_the_ground; const item_names = game.owned.text.item_names; if (items.index >= item_names.keys.len) return error.Error; const old_name = item_names.getSpan(items.index); // Here, we also applies the item name to the item_names_on_the_ground // table. The way we do this is to search for the item name in the // ground string, and if it exists, we replace it and apply this new // string applyGen5StringReplace(names_on_ground, items.index, old_name, str) catch {}; try applyGen5String(item_names, items.index, str); }, .pocket => |pocket| item.pocket.pocket = switch (pocket) { .items => .items, .key_items => .key_items, .poke_balls => .poke_balls, .tms_hms => .tms_hms, .berries, .none, => return error.DidNotConsumeData, }, } }, .pokedex => |pokedex| { const names = game.owned.text.pokedex_category_names; switch (pokedex.value) { .category => |category| try applyGen5String(names, pokedex.index, category), .height, .weight, => return error.DidNotConsumeData, } }, .moves => |moves| { if (moves.index >= game.ptrs.moves.len) return error.IndexOutOfBound; const names = game.owned.text.move_names; const descriptions = game.owned.text.move_descriptions; const move = &game.ptrs.moves[moves.index]; switch (moves.value) { .description => |str| try applyGen5String(descriptions, moves.index, str), .name => |str| try applyGen5String(names, moves.index, str), .effect => |effect| move.effect = lu16.init(effect), .power => |power| move.power = power, .type => |_type| move.type = _type, .accuracy => |accuracy| move.accuracy = accuracy, .pp => |pp| move.pp = pp, .target => |target| move.target = target, .priority => |priority| move.priority = priority, .category => |category| move.category = category, } }, .abilities => |abilities| { const names = game.owned.text.ability_names; switch (abilities.value) { .name => |str| try applyGen5String(names, abilities.index, str), } }, .types => |types| { const names = game.owned.text.type_names; switch (types.value) { .name => |str| try applyGen5String(names, types.index, str), } }, .maps => |maps| { if (maps.index >= game.ptrs.map_headers.len) return error.Error; const map_header = &game.ptrs.map_headers[maps.index]; switch (maps.value) { .music => |music| map_header.music = lu16.init(music), .battle_scene => |battle_scene| map_header.battle_scene = battle_scene, .allow_cycling, .allow_escaping, .allow_running, .show_map_name, .weather, .cave, .type, .escape_rope, => return error.DidNotConsumeData, } }, .wild_pokemons => |pokemons| { if (pokemons.index >= game.ptrs.wild_pokemons.fat.len) return error.Error; const file = nds.fs.File{ .i = pokemons.index }; const wilds = game.ptrs.wild_pokemons.fileAs(file, [4]gen5.WildPokemons) catch try game.ptrs.wild_pokemons.fileAs(file, [1]gen5.WildPokemons); switch (pokemons.value) { .grass_0 => |area| try applyGen5Area(area, "grass", 0, 0, wilds), .grass_1 => |area| try applyGen5Area(area, "grass", 1, 0, wilds), .grass_2 => |area| try applyGen5Area(area, "grass", 2, 0, wilds), .grass_3 => |area| try applyGen5Area(area, "grass", 3, 0, wilds), .dark_grass_0 => |area| try applyGen5Area(area, "dark_grass", 0, 1, wilds), .dark_grass_1 => |area| try applyGen5Area(area, "dark_grass", 1, 1, wilds), .dark_grass_2 => |area| try applyGen5Area(area, "dark_grass", 2, 1, wilds), .dark_grass_3 => |area| try applyGen5Area(area, "dark_grass", 3, 1, wilds), .rustling_grass_0 => |area| try applyGen5Area(area, "rustling_grass", 0, 2, wilds), .rustling_grass_1 => |area| try applyGen5Area(area, "rustling_grass", 1, 2, wilds), .rustling_grass_2 => |area| try applyGen5Area(area, "rustling_grass", 2, 2, wilds), .rustling_grass_3 => |area| try applyGen5Area(area, "rustling_grass", 3, 2, wilds), .surf_0 => |area| try applyGen5Area(area, "surf", 0, 3, wilds), .surf_1 => |area| try applyGen5Area(area, "surf", 1, 3, wilds), .surf_2 => |area| try applyGen5Area(area, "surf", 2, 3, wilds), .surf_3 => |area| try applyGen5Area(area, "surf", 3, 3, wilds), .ripple_surf_0 => |area| try applyGen5Area(area, "ripple_surf", 0, 4, wilds), .ripple_surf_1 => |area| try applyGen5Area(area, "ripple_surf", 1, 4, wilds), .ripple_surf_2 => |area| try applyGen5Area(area, "ripple_surf", 2, 4, wilds), .ripple_surf_3 => |area| try applyGen5Area(area, "ripple_surf", 3, 4, wilds), .fishing_0 => |area| try applyGen5Area(area, "fishing", 0, 5, wilds), .fishing_1 => |area| try applyGen5Area(area, "fishing", 1, 5, wilds), .fishing_2 => |area| try applyGen5Area(area, "fishing", 2, 5, wilds), .fishing_3 => |area| try applyGen5Area(area, "fishing", 3, 5, wilds), .ripple_fishing_0 => |area| try applyGen5Area(area, "ripple_fishing", 0, 6, wilds), .ripple_fishing_1 => |area| try applyGen5Area(area, "ripple_fishing", 1, 6, wilds), .ripple_fishing_2 => |area| try applyGen5Area(area, "ripple_fishing", 2, 6, wilds), .ripple_fishing_3 => |area| try applyGen5Area(area, "ripple_fishing", 3, 6, wilds), .grass_4, .grass_5, .grass_6, .rock_smash, => return error.DidNotConsumeData, } }, .static_pokemons => |pokemons| { if (pokemons.index >= game.ptrs.static_pokemons.len) return error.Error; const static_mon = game.ptrs.static_pokemons[pokemons.index]; switch (pokemons.value) { .species => |species| static_mon.species.* = lu16.init(species), .level => |level| static_mon.level.* = lu16.init(level), } }, .given_pokemons => |pokemons| { if (pokemons.index >= game.ptrs.given_pokemons.len) return error.Error; const given_mon = game.ptrs.given_pokemons[pokemons.index]; switch (pokemons.value) { .species => |species| given_mon.species.* = lu16.init(species), .level => |level| given_mon.level.* = lu16.init(level), } }, .pokeball_items => |items| { if (items.index >= game.ptrs.pokeball_items.len) return error.IndexOutOfBound; const given_item = game.ptrs.pokeball_items[items.index]; switch (items.value) { .item => |item| given_item.item.* = lu16.init(item), .amount => |amount| given_item.amount.* = lu16.init(amount), } }, .hidden_hollows => |hidden_hollows| if (game.ptrs.hidden_hollows) |hollows| { if (hidden_hollows.index >= hollows.len) return error.Error; const hollow = &hollows[hidden_hollows.index]; switch (hidden_hollows.value) { .groups => |groups| { if (groups.index >= hollow.pokemons.len) return error.Error; const group = &hollow.pokemons[groups.index]; switch (groups.value) { .pokemons => |pokemons| { if (pokemons.index >= group.species.len) return error.IndexOutOfBound; switch (pokemons.value) { .species => |species| group.species[pokemons.index] = lu16.init(species), } }, } }, .items => |items| { if (items.index >= hollow.items.len) return error.DidNotConsumeData; hollow.items[items.index] = lu16.init(items.value); }, } } else { return error.DidNotConsumeData; }, .text_delays, .text, => return error.DidNotConsumeData, } } fn applyGen5Area( area: format.WildArea, comptime field: []const u8, wild_index: usize, rate_index: usize, wilds: []gen5.WildPokemons, ) !void { if (wilds.len <= wild_index) return error.DidNotConsumeData; switch (area) { .encounter_rate => |encounter_rate| { wilds[wild_index].rates[rate_index] = try math.cast(u8, encounter_rate); }, .pokemons => |pokemons| { const wild_area = &@field(wilds[wild_index], field); if (pokemons.index >= wild_area.len) return error.Error; const wild = &wild_area[pokemons.index]; switch (pokemons.value) { .min_level => |min_level| wild.min_level = min_level, .max_level => |max_level| wild.max_level = max_level, .species => |species| wild.species.setSpecies(try math.cast(u10, species)), } }, } } fn applyGen5StringReplace( strs: gen5.StringTable, index: usize, search_for: []const u8, replace_with: []const u8, ) !void { if (strs.keys.len <= index) return error.Error; const str = strs.getSpan(index); const i = mem.indexOf(u8, str, search_for) orelse return; const before = str[0..i]; const after = str[i + search_for.len ..]; var buf: [1024]u8 = undefined; const writer = io.fixedBufferStream(&buf).writer(); try writer.writeAll(before); try util.escape.default.unescapeWrite(writer, replace_with); try writer.writeAll(after); _ = writer.write("\x00") catch undefined; const written = writer.context.getWritten(); const copy_into = strs.get(index); if (copy_into.len < written.len) return error.Error; mem.copy(u8, copy_into, written); // Null terminate, if we didn't fill the buffer if (written.len < copy_into.len) buf[written.len] = 0; } fn applyGen5String(strs: gen5.StringTable, index: usize, value: []const u8) !void { if (strs.keys.len <= index) return error.Error; const buf = strs.get(index); const writer = io.fixedBufferStream(buf).writer(); try util.escape.default.unescapeWrite(writer, value); // Null terminate, if we didn't fill the buffer if (writer.context.pos < buf.len) buf[writer.context.pos] = 0; }
src/core/tm35-apply.zig
const std = @import("std"); pub const Fixbuf = @compileError("Please use std.BoundedArray instead"); pub fn errSetContains(comptime ErrorSet: type, err: anyerror) bool { inline for (comptime std.meta.fields(ErrorSet)) |e| { if (err == @field(ErrorSet, e.name)) { return true; } } return false; } pub fn ReturnOf(comptime func: anytype) type { return switch (@typeInfo(@TypeOf(func))) { .Fn, .BoundFn => |fn_info| fn_info.return_type.?, else => unreachable, }; } pub fn ErrorOf(comptime func: anytype) type { const return_type = ReturnOf(func); return switch (@typeInfo(return_type)) { .ErrorUnion => |eu_info| eu_info.error_set, else => unreachable, }; } pub fn Mailbox(comptime T: type) type { return struct { const Self = @This(); value: ?T, mutex: std.Thread.Mutex, reset_event: std.Thread.ResetEvent, pub fn init(self: *Self) !void { try self.reset_event.init(); errdefer self.reset_event.deinit(); self.value = null; self.mutex = .{}; } pub fn deinit(self: *Self) void { self.reset_event.deinit(); } pub fn get(self: *Self) T { self.reset_event.wait(); self.mutex.lock(); defer self.mutex.unlock(); self.reset_event.reset(); defer self.value = null; return self.value.?; } pub fn getWithTimeout(self: *Self, timeout_ns: u64) ?T { _ = self.reset_event.timedWait(timeout_ns); self.mutex.lock(); defer self.mutex.unlock(); self.reset_event.reset(); defer self.value = null; return self.value; } pub fn putOverwrite(self: *Self, value: T) void { self.mutex.lock(); defer self.mutex.unlock(); self.value = value; self.reset_event.set(); } }; }
src/util.zig
const std = @import("std"); const assert = std.debug.assert; // Indexing pub inline fn generateVertexRemap( destination: []u32, indices: ?[]const u32, comptime T: type, vertices: []const T, ) usize { return meshopt_generateVertexRemap( destination.ptr, if (indices) |ind| ind.ptr else null, if (indices) |ind| ind.len else vertices.len, vertices.ptr, vertices.len, @sizeOf(T), ); } pub inline fn remapVertexBuffer( comptime T: type, destination: []T, vertices: []const T, remap: []const u32, ) void { assert(destination.len >= vertices.len); meshopt_remapVertexBuffer( destination.ptr, vertices.ptr, vertices.len, @sizeOf(T), remap.ptr, ); } pub inline fn remapIndexBuffer( destination: []u32, indices: ?[]const u32, remap: []const u32, ) void { meshopt_remapIndexBuffer( destination.ptr, if (indices) |ind| ind.ptr else null, if (indices) |ind| ind.len else remap.len, remap.ptr, ); } // Vertex cache optimization pub inline fn optimizeVertexCache( destination: []u32, indices: []const u32, vertex_count: usize, ) void { assert(destination.len >= indices.len); meshopt_optimizeVertexCache( destination.ptr, indices.ptr, indices.len, vertex_count, ); } pub const VertexCacheStatistics = extern struct { vertices_transformed: u32, warps_executed: u32, acmr: f32, atvr: f32, }; pub inline fn analyzeVertexCache( indices: []const u32, vertex_count: usize, cache_size: u32, warp_size: u32, primgroup_size: u32, ) VertexCacheStatistics { return meshopt_analyzeVertexCache( indices.ptr, indices.len, vertex_count, cache_size, warp_size, primgroup_size, ); } // Overdraw optimization pub inline fn optimizeOverdraw( destination: []u32, indices: []const u32, comptime T: type, vertices: []const T, threshold: f32, ) void { assert(destination.len >= indices.len); meshopt_optimizeOverdraw( destination.ptr, indices.ptr, indices.len, vertices.ptr, vertices.len, @sizeOf(T), threshold, ); } pub const OverdrawStatistics = extern struct { pixels_covered: u32, pixels_shaded: u32, overdraw: f32, }; pub inline fn analyzeOverdraw( indices: []const u32, comptime T: type, vertices: []const T, ) OverdrawStatistics { return meshopt_analyzeOverdraw(indices.ptr, indices.len, vertices.ptr, vertices.len, @sizeOf(T)); } // Vertex fetch optimization pub inline fn optimizeVertexFetch( comptime T: type, destination: []T, indices: []u32, vertices: []const T, ) usize { assert(destination.len >= vertices.len); return meshopt_optimizeVertexFetch( destination.ptr, indices.ptr, indices.len, vertices.ptr, vertices.len, @sizeOf(T), ); } pub const VertexFetchStatistics = extern struct { bytes_fetched: u32, overfetch: f32, }; pub inline fn analyzeVertexFetch( indices: []const u32, vertex_count: usize, vertex_size: usize, ) VertexFetchStatistics { return meshopt_analyzeVertexFetch(indices.ptr, indices.len, vertex_count, vertex_size); } // Mesh shading pub inline fn buildMeshletsBound(index_count: usize, max_vertices: usize, max_triangles: usize) usize { return meshopt_buildMeshletsBound(index_count, max_vertices, max_triangles); } pub const Meshlet = extern struct { vertex_offset: u32, triangle_offset: u32, vertex_count: u32, triangle_count: u32, }; pub inline fn buildMeshlets( meshlets: []Meshlet, meshlet_vertices: []u32, meshlet_triangles: []u8, indices: []const u32, comptime T: type, vertices: []const T, max_vertices: usize, max_triangles: usize, cone_weight: f32, ) usize { return meshopt_buildMeshlets( meshlets.ptr, meshlet_vertices.ptr, meshlet_triangles.ptr, indices.ptr, indices.len, vertices.ptr, vertices.len, @sizeOf(T), max_vertices, max_triangles, cone_weight, ); } extern fn meshopt_generateVertexRemap( destination: [*]u32, indices: ?[*]const u32, index_count: usize, vertices: *const anyopaque, vertex_count: usize, vertex_size: usize, ) usize; extern fn meshopt_remapVertexBuffer( destination: *anyopaque, vertices: *const anyopaque, vertex_count: usize, vertex_size: usize, remap: [*]const u32, ) void; extern fn meshopt_remapIndexBuffer( destination: [*]u32, indices: ?[*]const u32, index_count: usize, remap: [*]const u32, ) void; extern fn meshopt_optimizeVertexCache( destination: [*]u32, indices: [*]const u32, index_count: usize, vertex_count: usize, ) void; extern fn meshopt_analyzeVertexCache( indices: [*]const u32, index_count: usize, vertex_count: usize, cache_size: u32, warp_size: u32, primgroup_size: u32, ) VertexCacheStatistics; extern fn meshopt_optimizeOverdraw( destination: [*]u32, indices: [*]const u32, index_count: usize, vertices: *const anyopaque, vertex_count: usize, vertex_size: usize, threshold: f32, ) void; extern fn meshopt_analyzeOverdraw( indices: [*]const u32, index_count: usize, vertices: *const anyopaque, vertex_count: usize, vertex_size: usize, ) OverdrawStatistics; extern fn meshopt_optimizeVertexFetch( destination: *anyopaque, indices: [*]u32, index_count: usize, vertices: *const anyopaque, vertex_count: usize, vertex_size: usize, ) usize; extern fn meshopt_analyzeVertexFetch( indices: [*]const u32, index_count: usize, vertex_count: usize, vertex_size: usize, ) VertexFetchStatistics; extern fn meshopt_buildMeshletsBound( index_count: usize, max_vertices: usize, max_triangles: usize, ) usize; extern fn meshopt_buildMeshlets( meshlets: [*]Meshlet, meshlet_vertices: [*]u32, meshlet_triangles: [*]u8, indices: [*]const u32, index_count: usize, vertices: *const anyopaque, vertex_count: usize, vertex_size: usize, max_vertices: usize, max_triangles: usize, cone_weight: f32, ) usize;
libs/zmesh/src/meshoptimizer.zig
const std = @import("std"); const builtin = @import("builtin"); const examples = .{ "events", "window", "input", "wasm", }; const web_install_dir = std.build.InstallDir{ .custom = "www" }; fn getRoot() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } pub fn createApplication(b: *std.build.Builder, name: []const u8, path: []const u8, target: std.zig.CrossTarget) *std.build.LibExeObjStep { const lib = std.build.Pkg{ .name = "winzigo", .source = .{ .path = "src/main.zig" }, }; if (target.toTarget().cpu.arch == .wasm32) { const application = b.addSharedLibrary("application", "src/mains/wasm.zig/", .unversioned); application.setTarget(target); application.addPackage(.{ .name = "app", .source = .{ .path = path }, .dependencies = &.{lib}, }); application.install(); application.install_step.?.dest_dir = web_install_dir; const install_winzigo_js = b.addInstallFileWithDir( .{ .path = getRoot() ++ "/src/wasm/winzigo.js" }, web_install_dir, "winzigo.js", ); application.install_step.?.step.dependOn(&install_winzigo_js.step); const install_template_html = b.addInstallFileWithDir( .{ .path = getRoot() ++ "/www/template.html" }, web_install_dir, "application.html", ); application.install_step.?.step.dependOn(&install_template_html.step); return application; } else { const application = b.addExecutable(name, "src/mains/native.zig"); application.setTarget(target); application.linkLibC(); application.linkSystemLibrary("xcb"); application.addPackage(.{ .name = "app", .source = .{ .path = path }, .dependencies = &.{lib}, }); application.install(); return application; } } pub fn build(b: *std.build.Builder) void { const is_wasm = b.option(bool, "wasm", "Equivalent to -Dtarget=wasm32-freestanding-none") orelse false; const target = if (is_wasm) std.zig.CrossTarget{ .cpu_arch = .wasm32, .os_tag = .freestanding, .abi = .none, } else b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const no_serve = b.option(bool, "no-serve", "Do not serve with http server (WASM-only)") orelse false; const no_launch = b.option(bool, "no-launch", "Do not launch the browser (WASM-only)") orelse false; inline for (examples) |eg| { const example = createApplication(b, eg, "examples/" ++ eg ++ ".zig", target); example.setBuildMode(mode); const make_step = b.step("make-" ++ eg, "Build the " ++ eg ++ " example"); make_step.dependOn(&example.install_step.?.step); if (target.toTarget().cpu.arch == .wasm32) { const http_server = b.addExecutable("http-server", "tools/http-server.zig"); http_server.addPackage(.{ .name = "apple_pie", .source = .{ .path = "deps/apple_pie/src/apple_pie.zig" }, }); const launch = b.addSystemCommand(&.{ switch (builtin.os.tag) { .macos, .windows => "open", else => "xdg-open", // Assume linux-like }, "http://127.0.0.1:8000/application.html", }); launch.step.dependOn(&example.install_step.?.step); const serve = http_server.run(); serve.addArg("application"); if (no_launch) { serve.step.dependOn(&example.install_step.?.step); } else { serve.step.dependOn(&launch.step); } serve.cwd = b.getInstallPath(web_install_dir, ""); const run_step = b.step("run-" ++ eg, "Run the " ++ eg ++ "example"); if (no_serve) { run_step.dependOn(&example.install_step.?.step); } else { run_step.dependOn(&serve.step); } } else { const run_cmd = example.run(); run_cmd.step.dependOn(&example.install_step.?.step); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run-" ++ eg, "Run the " ++ eg ++ " example"); run_step.dependOn(&run_cmd.step); } } }
build.zig
const std = @import("std"); // Implements URI parsing roughly adhere to https://tools.ietf.org/html/rfc3986 // Does not do perfect grammar and character class checking, but should be robust against // "wild" URIs /// Stores separate parts of a URI. pub const UriComponents = struct { scheme: ?[]const u8, user: ?[]const u8, password: ?[]const u8, host: ?[]const u8, port: ?u16, path: ?[]const u8, query: ?[]const u8, fragment: ?[]const u8, }; /// Applies URI encoding and replaces all reserved characters with their respective %XX code. pub fn escapeString(allocator: *std.mem.Allocator, input: []const u8) error{OutOfMemory}![]const u8 { var outsize: usize = 0; for (input) |c| { outsize += if (isUnreserved(c)) @as(usize, 1) else 3; } var output = try allocator.alloc(u8, outsize); var outptr: usize = 0; for (input) |c| { if (isUnreserved(c)) { output[outptr] = c; outptr += 1; } else { var buf: [2]u8 = undefined; _ = std.fmt.bufPrint(&buf, "{X:0>2}", .{c}) catch unreachable; output[outptr + 0] = '%'; output[outptr + 1] = buf[0]; output[outptr + 2] = buf[1]; outptr += 3; } } return output; } /// Parses a URI string and unescapes all %XX where XX is a valid hex number. Otherwise, verbatim copies /// them to the output. pub fn unescapeString(allocator: *std.mem.Allocator, input: []const u8) error{OutOfMemory}![]const u8 { var outsize: usize = 0; var inptr: usize = 0; while (inptr < input.len) { if (input[inptr] == '%') { inptr += 1; if (inptr + 2 <= input.len) { _ = std.fmt.parseInt(u8, input[inptr..][0..2], 16) catch { outsize += 3; inptr += 2; continue; }; inptr += 2; outsize += 1; } } else { inptr += 1; outsize += 1; } } var output = try allocator.alloc(u8, outsize); var outptr: usize = 0; inptr = 0; while (inptr < input.len) { if (input[inptr] == '%') { inptr += 1; if (inptr + 2 <= input.len) { const value = std.fmt.parseInt(u8, input[inptr..][0..2], 16) catch { output[outptr + 0] = input[inptr + 0]; output[outptr + 1] = input[inptr + 1]; inptr += 2; outptr += 2; continue; }; output[outptr] = value; inptr += 2; outptr += 1; } } else { output[outptr] = input[inptr]; inptr += 1; outptr += 1; } } return output; } pub const ParseError = error{ UnexpectedCharacter, InvalidFormat, InvalidPort }; /// Parses the URI or returns an error. /// The return value will have unescaped pub fn parse(text: []const u8) ParseError!UriComponents { var uri = UriComponents{ .scheme = null, .user = null, .password = <PASSWORD>, .host = null, .port = null, .path = null, .query = null, .fragment = null, }; var reader = SliceReader{ .slice = text }; uri.scheme = reader.readWhile(isSchemeChar); // after the scheme, a ':' must appear if (reader.get()) |c| { if (c != ':') return error.UnexpectedCharacter; } else { return error.InvalidFormat; } if (reader.peekPrefix("//")) { // authority part std.debug.assert(reader.get().? == '/'); std.debug.assert(reader.get().? == '/'); const authority = reader.readUntil(isAuthoritySeparator); if (authority.len == 0) return error.InvalidFormat; var start_of_host: usize = 0; if (std.mem.indexOf(u8, authority, "@")) |index| { start_of_host = index + 1; const user_info = authority[0..index]; if (std.mem.indexOf(u8, user_info, ":")) |idx| { uri.user = user_info[0..idx]; if (idx < user_info.len - 1) { // empty password is also "<PASSWORD>" uri.password = <PASSWORD>_info[idx + 1 ..]; } } else { uri.user = user_info; uri.password = <PASSWORD>; } } var end_of_host: usize = authority.len; if (authority[start_of_host] == '[') { // IPv6 end_of_host = std.mem.lastIndexOf(u8, authority, "]") orelse return error.InvalidFormat; end_of_host += 1; if (std.mem.lastIndexOf(u8, authority, ":")) |index| { if (index >= end_of_host) { // if not part of the V6 address field end_of_host = std.math.min(end_of_host, index); uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort; } } } else if (std.mem.lastIndexOf(u8, authority, ":")) |index| { if (index >= start_of_host) { // if not part of the userinfo field end_of_host = std.math.min(end_of_host, index); uri.port = std.fmt.parseInt(u16, authority[index + 1 ..], 10) catch return error.InvalidPort; } } uri.host = authority[start_of_host..end_of_host]; } uri.path = reader.readUntil(isPathSeparator); if ((reader.peek() orelse 0) == '?') { // query part std.debug.assert(reader.get().? == '?'); uri.query = reader.readUntil(isQuerySeparator); } if ((reader.peek() orelse 0) == '#') { // fragment part std.debug.assert(reader.get().? == '#'); uri.fragment = reader.readUntilEof(); } return uri; } const SliceReader = struct { const Self = @This(); slice: []const u8, offset: usize = 0, fn get(self: *Self) ?u8 { if (self.offset >= self.slice.len) return null; const c = self.slice[self.offset]; self.offset += 1; return c; } fn peek(self: Self) ?u8 { if (self.offset >= self.slice.len) return null; return self.slice[self.offset]; } fn readWhile(self: *Self, predicate: fn (u8) bool) []const u8 { const start = self.offset; var end = start; while (end < self.slice.len and predicate(self.slice[end])) { end += 1; } self.offset = end; return self.slice[start..end]; } fn readUntil(self: *Self, predicate: fn (u8) bool) []const u8 { const start = self.offset; var end = start; while (end < self.slice.len and !predicate(self.slice[end])) { end += 1; } self.offset = end; return self.slice[start..end]; } fn readUntilEof(self: *Self) []const u8 { const start = self.offset; self.offset = self.slice.len; return self.slice[start..]; } fn peekPrefix(self: Self, prefix: []const u8) bool { if (self.offset + prefix.len > self.slice.len) return false; return std.mem.eql(u8, self.slice[self.offset..][0..prefix.len], prefix); } }; /// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) fn isSchemeChar(c: u8) bool { return switch (c) { 'A'...'Z', 'a'...'z', '0'...'9', '+', '-', '.' => true, else => false, }; } fn isAuthoritySeparator(c: u8) bool { return switch (c) { '/', '?', '#' => true, else => false, }; } /// reserved = gen-delims / sub-delims fn isReserved(c: u8) bool { return isGenLimit(c) or isSubLimit(c); } /// gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" fn isGenLimit(c: u8) bool { return switch (c) { ':', ',', '?', '#', '[', ']', '@' => true, else => false, }; } /// sub-delims = "!" / "$" / "&" / "'" / "(" / ")" /// / "*" / "+" / "," / ";" / "=" fn isSubLimit(c: u8) bool { return switch (c) { '!', '$', '&', '\'', '(', ')', '*', '+', ',', ';', '=' => true, else => false, }; } /// unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" fn isUnreserved(c: u8) bool { return switch (c) { 'A'...'Z', 'a'...'z', '0'...'9', '-', '.', '_', '~' => true, else => false, }; } fn isPathSeparator(c: u8) bool { return switch (c) { '?', '#' => true, else => false, }; } fn isQuerySeparator(c: u8) bool { return switch (c) { '#' => true, else => false, }; } test "should fail gracefully" { std.testing.expectEqual(@as(ParseError!UriComponents, error.InvalidFormat), parse("foobar://")); } test "scheme" { std.testing.expectEqualSlices(u8, "http", (try parse("http:_")).scheme.?); std.testing.expectEqualSlices(u8, "scheme-mee", (try parse("scheme-mee:_")).scheme.?); std.testing.expectEqualSlices(u8, "a.b.c", (try parse("a.b.c:_")).scheme.?); std.testing.expectEqualSlices(u8, "ab+", (try parse("ab+:_")).scheme.?); std.testing.expectEqualSlices(u8, "X+++", (try parse("X+++:_")).scheme.?); std.testing.expectEqualSlices(u8, "Y+-.", (try parse("Y+-.:_")).scheme.?); } test "authority" { std.testing.expectEqualSlices(u8, "hostname", (try parse("scheme://hostname")).host.?); std.testing.expectEqualSlices(u8, "hostname", (try parse("scheme://userinfo@hostname")).host.?); std.testing.expectEqualSlices(u8, "userinfo", (try parse("scheme://userinfo@hostname")).user.?); std.testing.expectEqual(@as(?[]const u8, null), (try parse("scheme://userinfo@hostname")).password); std.testing.expectEqualSlices(u8, "hostname", (try parse("scheme://user:password@hostname")).host.?); std.testing.expectEqualSlices(u8, "user", (try parse("scheme://user:password@hostname")).user.?); std.testing.expectEqualSlices(u8, "password", (try parse("scheme://user:password@hostname")).password.?); std.testing.expectEqualSlices(u8, "hostname", (try parse("scheme://hostname:0")).host.?); std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://hostname:1234")).port.?); std.testing.expectEqualSlices(u8, "hostname", (try parse("scheme://userinfo@hostname:1234")).host.?); std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://userinfo@hostname:1234")).port.?); std.testing.expectEqualSlices(u8, "userinfo", (try parse("scheme://userinfo@hostname:1234")).user.?); std.testing.expectEqual(@as(?[]const u8, null), (try parse("scheme://userinfo@hostname:1234")).password); std.testing.expectEqualSlices(u8, "hostname", (try parse("scheme://user:password@hostname:1234")).host.?); std.testing.expectEqual(@as(u16, 1234), (try parse("scheme://user:password@hostname:1234")).port.?); std.testing.expectEqualSlices(u8, "user", (try parse("scheme://user:password@hostname:1234")).user.?); std.testing.expectEqualSlices(u8, "password", (try parse("scheme://user:password@hostname:1234")).password.?); } test "authority.password" { std.testing.expectEqualSlices(u8, "username", (try parse("scheme://username@a")).user.?); std.testing.expectEqual(@as(?[]const u8, null), (try parse("scheme://username@a")).password); std.testing.expectEqualSlices(u8, "username", (try parse("scheme://username:@a")).user.?); std.testing.expectEqual(@as(?[]const u8, null), (try parse("scheme://username:@a")).password); std.testing.expectEqualSlices(u8, "username", (try parse("scheme://username:password@a")).user.?); std.testing.expectEqualSlices(u8, "password", (try parse("scheme://username:password@a")).password.?); std.testing.expectEqualSlices(u8, "username", (try parse("scheme://username::@a")).user.?); std.testing.expectEqualSlices(u8, ":", (try parse("scheme://username::@a")).password.?); } fn testAuthorityHost(comptime hostlist: anytype) !void { inline for (hostlist) |hostname| { std.testing.expectEqualSlices(u8, hostname, (try parse("scheme://" ++ hostname)).host.?); } } test "authority.dns-names" { try testAuthorityHost(.{ "a", "a.b", "example.com", "www.example.com", "example.org.", "www.example.org.", "xn--nw2a.xn--j6w193g", // internationalization! "fe80--1ff-fe23-4567-890as3.ipv6-literal.net", }); // still allowed… } test "authority.IPv4" { try testAuthorityHost(.{ "127.0.0.1", "255.255.255.255", "0.0.0.0", "8.8.8.8", "1.2.3.4", "192.168.0.1", "10.42.0.0", }); } test "authority.IPv6" { try testAuthorityHost(.{ "[2001:db8:0:0:0:0:2:1]", "[200fdf8:f53e:61e4::18:1]", "[2001:db8:0000:1:1:1:1:1]", "[2001:db8:0:1:1:1:1:1]", "[0:0:0:0:0:0:0:0]", "[0:0:0:0:0:0:0:1]", "[::1]", "[::]", "[2001:db8:85a3:8d3:1319:8a2e:370:7348]", "[fe80::1ff:fe23:4567:890a%25eth2]", "[fefd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:fe23:4567:890a]", "[fefd00:c2b6:b24b:be67:2827:688d:e6a1:6a3b:fe23:4567:890a%253]", "[fefc00:e968:6179::de52:7100:fe23:4567:890a]", }); } test "RFC example 1" { const uri = "foo://example.com:8042/over/there?name=ferret#nose"; std.testing.expectEqual(UriComponents{ .scheme = uri[0..3], .user = null, .password = <PASSWORD>, .host = uri[6..17], .port = 8042, .path = uri[22..33], .query = uri[34..45], .fragment = uri[46..50], }, try parse(uri)); } test "RFX example 2" { const uri = "urn:example:animal:ferret:nose"; std.testing.expectEqual(UriComponents{ .scheme = uri[0..3], .user = null, .password = null, .host = null, .port = null, .path = uri[4..], .query = null, .fragment = null, }, try parse(uri)); } // source: // https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Examples test "Examples from wikipedia" { // these should all parse const list = [_][]const u8{ "https://<EMAIL>.<EMAIL>@www.example.com:123/forum/questions/?tag=networking&order=newest#top", "ldap://[2001:db8::7]/c=GB?objectClass?one", "mailto:<EMAIL>", "news:comp.infosystems.www.servers.unix", "tel:+1-816-555-1212", "telnet://192.0.2.16:80/", "urn:oasis:names:specification:docbook:dtd:xml:4.1.2", "http://a/b/c/d;p?q", }; for (list) |uri| { _ = try parse(uri); } } // source: // https://tools.ietf.org/html/rfc3986#section-5.4.1 test "Examples from RFC3986" { // these should all parse const list = [_][]const u8{ "http://a/b/c/g", "http://a/b/c/g", "http://a/b/c/g/", "http://a/g", "http://g", "http://a/b/c/d;p?y", "http://a/b/c/g?y", "http://a/b/c/d;p?q#s", "http://a/b/c/g#s", "http://a/b/c/g?y#s", "http://a/b/c/;x", "http://a/b/c/g;x", "http://a/b/c/g;x?y#s", "http://a/b/c/d;p?q", "http://a/b/c/", "http://a/b/c/", "http://a/b/", "http://a/b/", "http://a/b/g", "http://a/", "http://a/", "http://a/g", }; for (list) |uri| { _ = try parse(uri); } } test "Special test" { // This is for all of you code readers ♥ _ = try parse("https://www.youtube.com/watch?v=dQw4w9WgXcQ&feature=youtu.be&t=0"); } test "URI escaping" { const input = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad"; const expected = "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad"; const actual = try escapeString(std.testing.allocator, input); defer std.testing.allocator.free(actual); std.testing.expectEqualSlices(u8, expected, actual); } test "URI unescaping" { const input = "%5C%C3%B6%2F%20%C3%A4%C3%B6%C3%9F%20~~.adas-https%3A%2F%2Fcanvas%3A123%2F%23ads%26%26sad"; const expected = "\\ö/ äöß ~~.adas-https://canvas:123/#ads&&sad"; const actual = try unescapeString(std.testing.allocator, input); defer std.testing.allocator.free(actual); std.testing.expectEqualSlices(u8, expected, actual); }
uri.zig
const std = @import("std"); const Source = @import("context.zig").Source; const PrintHelper = @import("print_helper.zig").PrintHelper; const Module = @import("parse.zig").Module; const Expression = @import("parse.zig").Expression; const Statement = @import("parse.zig").Statement; const Local = @import("parse.zig").Local; const Scope = @import("parse.zig").Scope; const State = struct { source: Source, modules: []const Module, module: Module, helper: PrintHelper, pub fn print(self: *State, comptime fmt: []const u8, args: var) !void { try self.helper.print(self, fmt, args); } pub fn printArgValue(self: *State, comptime arg_format: []const u8, arg: var) !void { @compileError("unknown arg_format: \"" ++ arg_format ++ "\""); } fn indent(self: *State, indentation: usize) !void { var i: usize = 0; while (i < indentation) : (i += 1) { try self.print(" ", .{}); } } fn printStatement(self: *State, statement: Statement, indentation: usize) !void { try self.indent(indentation); switch (statement) { .let_assignment => |x| { try self.print("LET {str} =\n", .{self.module.info.?.locals[x.local_index].name}); try self.printExpression(x.expression, indentation + 1); }, .output => |expression| { try self.print("OUT\n", .{}); try self.printExpression(expression, indentation + 1); }, .feedback => |expression| { try self.print("FEEDBACK\n", .{}); try self.printExpression(expression, indentation + 1); }, } } fn printExpression(self: *State, expression: *const Expression, indentation: usize) std.os.WriteError!void { try self.indent(indentation); switch (expression.inner) { .call => |call| { try self.print("call (\n", .{}); try self.printExpression(call.field_expr, indentation + 1); try self.indent(indentation); try self.print(") (\n", .{}); for (call.args) |arg| { try self.indent(indentation + 1); try self.print("{str}:\n", .{arg.param_name}); try self.printExpression(arg.value, indentation + 2); } try self.indent(indentation); try self.print(")\n", .{}); }, .local => |local_index| try self.print("{str}\n", .{self.module.info.?.locals[local_index].name}), .track_call => |track_call| { try self.print("track_call (\n", .{}); try self.printExpression(track_call.track_expr, indentation + 1); try self.printExpression(track_call.speed, indentation + 1); try self.print(") (\n", .{}); for (track_call.scope.statements.items) |statement| { try self.printStatement(statement, indentation + 1); } try self.indent(indentation); try self.print(")\n", .{}); }, .delay => |delay| { try self.print("delay {usize} (\n", .{delay.num_samples}); for (delay.scope.statements.items) |statement| { try self.printStatement(statement, indentation + 1); } try self.indent(indentation); try self.print(")\n", .{}); }, .feedback => try self.print("feedback\n", .{}), .literal_boolean => |v| try self.print("{bool}\n", .{v}), .literal_number => |v| try self.print("{number_literal}\n", .{v}), .literal_enum_value => |v| { try self.print("'{str}'\n", .{v.label}); if (v.payload) |payload| { try self.printExpression(payload, indentation + 1); } }, .literal_curve => |curve_index| try self.print("(curve {usize})\n", .{curve_index}), .literal_track => |track_index| try self.print("(track {usize})\n", .{track_index}), .literal_module => |module_index| try self.print("(module {usize})\n", .{module_index}), .name => |token| try self.print("(name){str}\n", .{self.source.getString(token.source_range)}), .un_arith => |m| { try self.print("{auto}\n", .{m.op}); try self.printExpression(m.a, indentation + 1); }, .bin_arith => |m| { try self.print("{auto}\n", .{m.op}); try self.printExpression(m.a, indentation + 1); try self.printExpression(m.b, indentation + 1); }, } } }; pub fn parsePrintModule(out: std.io.StreamSource.OutStream, source: Source, modules: []const Module, module_index: usize, module: Module) !void { var self: State = .{ .source = source, .modules = modules, .module = module, .helper = PrintHelper.init(out), }; if (module.info) |info| { try self.print("module {usize}\n", .{module_index}); for (info.scope.statements.items) |statement| { try self.printStatement(statement, 1); } } else { try self.print("module {usize} (builtin {str}.{str})\n", .{ module_index, module.zig_package_name.?, module.builtin_name.? }); } try self.print("\n", .{}); self.helper.finish(); }
src/zangscript/parse_print.zig
const std = @import("std"); const ansi = @import("ansi-term"); const os = std.os; const fs = std.fs; const ControlCode = union(enum) { newline, backspace, end_of_file, escape, left, right, up, down, character: u8, fn fromReader(reader: anytype) !ControlCode { const byte = try reader.readByte(); switch (byte) { 'q' => return .end_of_file, '\x1b' => { const bracket = try reader.readByte(); const code = try reader.readByte(); if (bracket == '[') { switch (code) { 'A' => return .up, 'B' => return .down, 'C' => return .right, 'D' => return .left, else => return error.UnimplementedControlCode, } } return .escape; }, '\r' => return .newline, 127 => return .backspace, else => |char| return ControlCode{ .character = char }, } unreachable; } }; const Readline = struct { const Self = @This(); termios: os.termios, tty: fs.File, cursor: ansi.Cursor, prompt: []const u8, output: []u8, index: usize, line_legth: usize, pub fn init(tty: fs.File, promt: []const u8, output: []u8) !Self { const original_termios = try initTerminal(tty); return Self{ .termios = original_termios, .tty = tty, .cursor = ansi.Cursor{ .x = 0, .y = 0 }, .prompt = promt, .output = output, .index = 0, .line_legth = 0, }; } pub fn deinit(self: *Self) !void { try restoreTerminal(self.tty, self.termios); } pub fn start(self: *Self) !?usize { try self.refreshScreen(); const writer = self.tty.writer(); while (true) { const code = try ControlCode.fromReader(self.tty.reader()); switch (code) { .escape, .end_of_file => return null, .backspace => { if (self.index > 0) { self.index -= 1; try self.refreshScreen(); } }, .newline => { try writer.writeAll("\r\n"); break; }, .up => {}, .down => {}, .left => { const cursor = try ansi.getCursor(writer, self.tty); if (cursor.x > self.prompt.len + 1) { try ansi.cursorBackward(writer, 1); if (self.index > 0) self.index -= 1; } //> | }, .right => { const cursor = try ansi.getCursor(writer, self.tty); if (cursor.x <= self.index + self.prompt.len) { try ansi.cursorForward(writer, 1); self.index += 1; } }, .character => |char| { if (self.line_legth + 1 >= self.output.len) { return error.LineLengthExceeded; } if (self.line_legth == self.index) { self.output[self.line_legth] = char; } else { var i: usize = self.line_legth; while (i > self.index) : (i -= 1) { self.output[i] = self.output[i - 1]; } self.output[self.index] = char; } self.index += 1; self.line_legth += 1; try self.refreshScreen(); }, } } return self.line_legth; } fn moveCursor(self: *Self, new_x: i32, new_y: i32) !void { if (new_x < 0) { self.cursor.x = 0; } else { self.cursor.x = @intCast(u16, new_x); } if (new_y < 0) { self.cursor.y = 0; } else { self.cursor.y = @intCast(u16, new_y); } try ansi.setCursor(self.tty.writer(), self.cursor.x, self.cursor.y); } fn moveCursorRel(self: *Self, x: i32, y: i32) !void { try self.moveCursor(self.cursor.x + x, self.cursor.y + y); } fn refreshScreen(self: *Self) !void { const writer = self.tty.writer(); const cursor = try ansi.getCursor(writer, self.tty); try writer.print("\x1b[{};1H", .{cursor.y}); try writer.writeAll("\x1b[2K"); try writer.writeAll(self.prompt); try writer.writeAll(self.output[0..self.line_legth]); self.cursor = try ansi.getCursor(writer, self.tty); } }; fn initTerminal(tty: fs.File) !os.termios { const cooked_termios = try os.tcgetattr(tty.handle); errdefer restoreTerminal(tty, cooked_termios) catch {}; var raw = cooked_termios; raw.lflag &= ~@as( os.system.tcflag_t, os.system.ECHO | os.system.ICANON | os.system.ISIG | os.system.IEXTEN, ); raw.iflag &= ~@as( os.system.tcflag_t, os.system.IXON | os.system.ICRNL | os.system.BRKINT | os.system.INPCK | os.system.ISTRIP, ); raw.oflag &= ~@as(os.system.tcflag_t, os.system.OPOST); raw.cflag |= os.system.CS8; raw.cc[os.system.V.TIME] = 0; raw.cc[os.system.V.MIN] = 1; try os.tcsetattr(tty.handle, .FLUSH, raw); return cooked_termios; } fn restoreTerminal(tty: fs.File, original_state: os.termios) !void { const writer = tty.writer(); try writer.writeAll("\x1B[0m"); // Atribute reset try os.tcsetattr(tty.handle, .FLUSH, original_state); } pub fn readline(allocator: std.mem.Allocator, prompt: []const u8, output: []u8) !?usize { _ = output; _ = prompt; _ = allocator; var tty = try fs.cwd().openFile("/dev/tty", .{ .mode = .read_write }); defer tty.close(); var rl = try Readline.init(tty, prompt, output); defer rl.deinit() catch {}; return try rl.start(); }
src/lib.zig
const std = @import("std"); /// The version information for this library. This is hardcoded for now but /// in the future we will parse this from configure.ac. pub const Version = struct { pub const major = "2"; pub const minor = "9"; pub const micro = "12"; pub fn number() []const u8 { comptime { return major ++ "0" ++ minor ++ "0" ++ micro; } } pub fn string() []const u8 { comptime { return "\"" ++ number() ++ "\""; } } pub fn dottedString() []const u8 { comptime { return "\"" ++ major ++ "." ++ minor ++ "." ++ micro ++ "\""; } } }; /// This is the type returned by create. pub const Library = struct { step: *std.build.LibExeObjStep, pub fn link(self: Library, other: *std.build.LibExeObjStep) void { other.addIncludeDir(include_dir); other.addIncludeDir(override_include_dir); other.linkLibrary(self.step); } }; /// Compile-time options for the library. These mostly correspond to /// options exposed by the native build system used by the library. pub const Options = struct { // These options are all defined in libxml2's configure.c and correspond // to `--with-X` options for `./configure`. Their defaults are properly set. c14n: bool = true, catalog: bool = true, debug: bool = true, docb: bool = true, // docbook ftp: bool = true, history: bool = true, html: bool = true, iconv: bool = true, icu: bool = false, iso8859x: bool = true, mem_debug: bool = false, minimum: bool = true, output: bool = true, pattern: bool = true, push: bool = true, reader: bool = true, regexp: bool = true, run_debug: bool = false, sax1: bool = true, schemas: bool = true, schematron: bool = true, thread: bool = true, thread_alloc: bool = false, tree: bool = true, valid: bool = true, writer: bool = true, xinclude: bool = true, xpath: bool = true, xptr: bool = true, modules: bool = true, lzma: bool = true, zlib: bool = true, }; /// Create this library. This is the primary API users of build.zig should /// use to link this library to their application. On the resulting Library, /// call the link function and given your own application step. pub fn create( b: *std.build.Builder, target: std.zig.CrossTarget, mode: std.builtin.Mode, opts: Options, ) !Library { const ret = b.addStaticLibrary("xml2", null); ret.setTarget(target); ret.setBuildMode(mode); var flags = std.ArrayList([]const u8).init(b.allocator); defer flags.deinit(); try flags.appendSlice(&.{ // Version info, hardcoded "-DLIBXML_VERSION=" ++ Version.number(), "-DLIBXML_VERSION_STRING=" ++ Version.string(), "-DLIBXML_VERSION_EXTRA=\"\"", "-DLIBXML_DOTTED_VERSION=" ++ Version.dottedString(), // These might now always be true (particularly Windows) but for // now we just set them all. We should do some detection later. "-DSEND_ARG2_CAST=", "-DGETHOSTBYNAME_ARG_CAST=", "-DGETHOSTBYNAME_ARG_CAST_CONST=", // Always on "-DLIBXML_STATIC=1", "-DLIBXML_AUTOMATA_ENABLED=1", "-DWITHOUT_TRIO=1", }); if (!target.isWindows()) { try flags.appendSlice(&.{ "-DHAVE_ARPA_INET_H=1", "-DHAVE_ARPA_NAMESER_H=1", "-DHAVE_DL_H=1", "-DHAVE_NETDB_H=1", "-DHAVE_NETINET_IN_H=1", "-DHAVE_PTHREAD_H=1", "-DHAVE_SHLLOAD=1", "-DHAVE_SYS_DIR_H=1", "-DHAVE_SYS_MMAN_H=1", "-DHAVE_SYS_NDIR_H=1", "-DHAVE_SYS_SELECT_H=1", "-DHAVE_SYS_SOCKET_H=1", "-DHAVE_SYS_TIMEB_H=1", "-DHAVE_SYS_TIME_H=1", "-DHAVE_SYS_TYPES_H=1", }); } // Option-specific changes if (opts.history) { try flags.appendSlice(&.{ "-DHAVE_LIBHISTORY=1", "-DHAVE_LIBREADLINE=1", }); } if (opts.mem_debug) { try flags.append("-DDEBUG_MEMORY_LOCATION=1"); } if (opts.regexp) { try flags.append("-DLIBXML_UNICODE_ENABLED=1"); } if (opts.run_debug) { try flags.append("-DLIBXML_DEBUG_RUNTIME=1"); } if (opts.thread) { try flags.append("-DHAVE_LIBPTHREAD=1"); } // Enable our `./configure` options. For bool-type fields we translate // it to the `LIBXML_{field}_ENABLED` C define where field is uppercased. inline for (std.meta.fields(@TypeOf(opts))) |field| { if (field.field_type == bool and @field(opts, field.name)) { var nameBuf: [32]u8 = undefined; const name = std.ascii.upperString(&nameBuf, field.name); const define = try std.fmt.allocPrint(b.allocator, "-DLIBXML_{s}_ENABLED=1", .{name}); try flags.append(define); } } // C files ret.addCSourceFiles(srcs, flags.items); if (opts.sax1) { ret.addCSourceFile(root() ++ "libxml2/DOCBparser.c", flags.items); } ret.addIncludeDir(include_dir); ret.addIncludeDir(override_include_dir); ret.linkLibC(); return Library{ .step = ret }; } fn root() []const u8 { return (std.fs.path.dirname(@src().file) orelse unreachable) ++ "/"; } /// Directories with our includes. const include_dir = root() ++ "libxml2/include"; const override_include_dir = root() ++ "include"; const srcs = &.{ root() ++ "libxml2/buf.c", root() ++ "libxml2/c14n.c", root() ++ "libxml2/catalog.c", root() ++ "libxml2/chvalid.c", root() ++ "libxml2/debugXML.c", root() ++ "libxml2/dict.c", root() ++ "libxml2/encoding.c", root() ++ "libxml2/entities.c", root() ++ "libxml2/error.c", root() ++ "libxml2/globals.c", root() ++ "libxml2/hash.c", root() ++ "libxml2/HTMLparser.c", root() ++ "libxml2/HTMLtree.c", root() ++ "libxml2/legacy.c", root() ++ "libxml2/list.c", root() ++ "libxml2/nanoftp.c", root() ++ "libxml2/nanohttp.c", root() ++ "libxml2/parser.c", root() ++ "libxml2/parserInternals.c", root() ++ "libxml2/pattern.c", root() ++ "libxml2/relaxng.c", root() ++ "libxml2/SAX.c", root() ++ "libxml2/SAX2.c", root() ++ "libxml2/schematron.c", root() ++ "libxml2/threads.c", root() ++ "libxml2/tree.c", root() ++ "libxml2/uri.c", root() ++ "libxml2/valid.c", root() ++ "libxml2/xinclude.c", root() ++ "libxml2/xlink.c", root() ++ "libxml2/xmlIO.c", root() ++ "libxml2/xmlmemory.c", root() ++ "libxml2/xmlmodule.c", root() ++ "libxml2/xmlreader.c", root() ++ "libxml2/xmlregexp.c", root() ++ "libxml2/xmlsave.c", root() ++ "libxml2/xmlschemas.c", root() ++ "libxml2/xmlschemastypes.c", root() ++ "libxml2/xmlstring.c", root() ++ "libxml2/xmlunicode.c", root() ++ "libxml2/xmlwriter.c", root() ++ "libxml2/xpath.c", root() ++ "libxml2/xpointer.c", root() ++ "libxml2/xzlib.c", };
libxml2.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; 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); const names = [_][]const u8{ "Tester", "Sensor" }; // part 1 and 2. var computers: [names.len]Computer = undefined; for (computers) |*c, i| { c.* = Computer{ .name = names[i], .memory = try allocator.alloc(Computer.Data, 10000), }; } defer for (computers) |c| { allocator.free(c.memory); }; const inputs = [names.len]Computer.Data{ 1, 2 }; var outputs: [names.len]Computer.Data = undefined; for (computers) |*c| { c.boot(boot_image); trace("starting {}\n", c.name); _ = async c.run(); } var num_halted: usize = 0; while (num_halted < computers.len) { num_halted = 0; for (computers) |*c, i| { if (c.is_halted()) { num_halted += 1; continue; } if (c.io_mode == .input) { c.io_port = inputs[i]; trace("wrting input to {} = {}\n", .{ c.name, c.io_port }); } else if (c.io_mode == .output) { trace("{} outputs {}\n", .{ c.name, c.io_port }); outputs[i] = c.io_port; } trace("resuming {}\n", c.name); resume c.io_runframe; } } return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{outputs[0]}), try std.fmt.allocPrint(allocator, "{}", .{outputs[1]}), }; } pub const main = tools.defaultMain("2019/day09.txt", run);
2019/day09.zig
const std = @import("std"); const vectorized = @import("algorithms.zig"); const Vector = std.meta.Vector; const print = std.debug.print; const assert = std.debug.assert; pub fn main() !void { const T = u8; const num_items = 1_000_000; var items: [num_items]T align(32) = undefined; var default_prng = std.rand.DefaultPrng.init(42); var rnd = default_prng.random(); for (items) |*v| { v.* = rnd.intRangeAtMost(T, 0, 199); } const Test = enum { min, max, indexOfScalar, eql }; // modify this to test another function const current_test = Test.eql; print("Testing {s}(" ++ @typeName(T) ++ "):\n", .{@tagName(current_test)}); for ([_]usize{ 1, 5, 50, 500, 5000, 50000, 500_000 }) |find_index, i| { const find_value: T = 200 + @intCast(T, i); items[find_index - 1] = find_value; for (items[0..find_index]) |v, j| { items[j + find_index] = v; } var speed1: u64 = undefined; var speed2: u64 = undefined; switch (current_test) { .min => { checkResult1(T, std.mem.min, vectorized.min, items[0..find_index]); speed1 = timeIt1(T, find_index, comptime std.mem.min, items[0..find_index]); speed2 = timeIt1(T, find_index, vectorized.min, items[0..find_index]); }, .max => { checkResult1(T, std.mem.max, vectorized.max, items[0..find_index]); speed1 = timeIt1(T, find_index, comptime std.mem.max, items[0..find_index]); speed2 = timeIt1(T, find_index, vectorized.max, items[0..find_index]); }, .eql => { checkResult2(T, std.mem.eql, vectorized.eql, items[0..find_index], items[find_index..][0..find_index]); speed1 = timeIt2(T, find_index, comptime std.mem.eql, items[0..find_index], items[find_index..][0..find_index]); speed2 = timeIt2(T, find_index, comptime vectorized.eql, items[0..find_index], items[find_index..][0..find_index]); }, .indexOfScalar => { checkResult2opt(T, std.mem.indexOfScalar, vectorized.indexOfScalar, items[0..find_index], find_value); speed1 = timeIt2(T, find_index, comptime std.mem.indexOfScalar, items[0..find_index], find_value); speed2 = timeIt2(T, find_index, comptime vectorized.indexOfScalar, items[0..find_index], find_value); }, } print("items scanned: {}\n", .{find_index}); print("std.mem: {} MB/s\n", .{speed1}); print("vectorized: {} MB/s\n", .{speed2}); print("------------------------\n", .{}); } } // Returns megabytes processed per second. fn timeIt2(comptime T: type, bytes_scanned: u64, comptime func: anytype, arg1: anytype, arg2: anytype) u64 { const milliseconds_in_ns = 1_000_000; var iterations: u64 = 1; var elapsed_ns = elapsedIter2(T, iterations, comptime func, arg1, arg2); while (elapsed_ns < 100 * milliseconds_in_ns) { iterations *= 2; elapsed_ns = elapsedIter2(T, iterations, comptime func, arg1, arg2); } iterations = std.math.max(1, iterations * 800 * milliseconds_in_ns / elapsed_ns); elapsed_ns = elapsedIter2(T, iterations, comptime func, arg1, arg2); return 1_000 * @sizeOf(T) * bytes_scanned * iterations / elapsed_ns; } fn elapsedIter2(comptime T: type, iterations: u64, comptime func: anytype, arg1: anytype, arg2: anytype) u64 { var timer = std.time.Timer.start() catch unreachable; var i: u64 = 0; while (i < iterations) : (i += 1) { const result = func(T, arg1, arg2); std.mem.doNotOptimizeAway(&result); } return timer.lap(); } fn timeIt1(comptime T: type, bytes_scanned: u64, comptime func: anytype, arg1: anytype) u64 { const milliseconds_in_ns = 1_000_000; var iterations: u64 = 1; var elapsed_ns = elapsedIter1(T, iterations, comptime func, arg1); while (elapsed_ns < 100 * milliseconds_in_ns) { iterations *= 2; elapsed_ns = elapsedIter1(T, iterations, comptime func, arg1); } iterations = std.math.max(1, iterations * 800 * milliseconds_in_ns / elapsed_ns); elapsed_ns = elapsedIter1(T, iterations, comptime func, arg1); return 1_000 * @sizeOf(T) * bytes_scanned * iterations / elapsed_ns; } fn elapsedIter1(comptime T: type, iterations: u64, comptime func: anytype, arg1: anytype) u64 { var timer = std.time.Timer.start() catch unreachable; var i: u64 = 0; while (i < iterations) : (i += 1) { const result = func(T, arg1); std.mem.doNotOptimizeAway(&result); } return timer.lap(); } fn checkResult1(comptime T: type, comptime func_std: anytype, func_vec: anytype, arg1: anytype) void { const res_std = func_std(T, arg1); const res_vec = func_vec(T, arg1); if (res_std != res_vec) print("Error: std.mem returned {d}, vectorized returned {d}\n", .{ res_std, res_vec }); } fn checkResult2(comptime T: type, comptime func_std: anytype, func_vec: anytype, arg1: anytype, arg2: anytype) void { const res_std = func_std(T, arg1, arg2); const res_vec = func_vec(T, arg1, arg2); if (res_std != res_vec) print("Error: std.mem returned {d}, vectorized returned {d}\n", .{ res_std, res_vec }); } fn checkResult2opt(comptime T: type, comptime func_std: anytype, func_vec: anytype, arg1: anytype, arg2: anytype) void { const res_std = func_std(T, arg1, arg2).?; const res_vec = func_vec(T, arg1, arg2).?; if (res_std != res_vec) print("Error: std.mem returned {d}, vectorized returned {d}\n", .{ res_std, res_vec }); }
src/main.zig
const std = @import("std"); const zblz = @import("blz.zig"); const cblz = @cImport(@cInclude("blz.h")); const heap = std.heap; const debug = std.debug; const mem = std.mem; const io = std.io; const os = std.os; pub fn main() !void { var direct_allocator = heap.DirectAllocator.init(); defer direct_allocator.deinit(); var global = heap.ArenaAllocator.init(&direct_allocator.allocator); defer global.deinit(); var stdout_handle = try io.getStdOut(); var stdout_file_stream = io.FileOutStream.init(&stdout_handle); var stdout = &stdout_file_stream.stream; // NOTE: Do we want to use another allocator for arguments? Does it matter? Idk. const args = try os.argsAlloc(&global.allocator); defer os.argsFree(&global.allocator, args); if (args.len < 2) { debug.warn("No file was provided.\n"); return error.NoFileInArguments; } for (args[1..]) |arg| { var arena = heap.ArenaAllocator.init(&direct_allocator.allocator); defer arena.deinit(); const allocator = &arena.allocator; var file = os.File.openRead(allocator, arg) catch |err| { debug.warn("Couldn't open {}.\n", arg); return err; }; defer file.close(); const bytes = try allocator.alloc(u8, try file.getEndPos()); const read = try file.read(bytes); const bytes2 = try mem.dupe(allocator, u8, bytes); debug.assert(read == bytes.len); const zdecoded = try @noInlineCall(zblz.decode, bytes2, allocator); const cdecoded = blk: { var out_len: c_uint = undefined; const res = cblz.BLZ_Decode(&bytes[0], c_uint(bytes.len), &out_len).?; break :blk res[0..out_len]; }; defer heap.c_allocator.free(cdecoded); debug.assert(mem.eql(u8, zdecoded, cdecoded)); const zencoded_best = try @noInlineCall(zblz.encode, cdecoded, zblz.Mode.Best, false, allocator); const cencoded_best = blk: { var out_len: c_uint = undefined; const res = cblz.BLZ_Encode(&cdecoded[0], c_uint(cdecoded.len), &out_len, cblz.BLZ_BEST).?; break :blk res[0..out_len]; }; defer heap.c_allocator.free(cencoded_best); debug.assert(mem.eql(u8, zencoded_best, cencoded_best)); const zencoded_normal = try @noInlineCall(zblz.encode, cdecoded, zblz.Mode.Normal, false, allocator); const cencoded_normal = blk: { var out_len: c_uint = undefined; const res = cblz.BLZ_Encode(&cdecoded[0], c_uint(cdecoded.len), &out_len, cblz.BLZ_NORMAL).?; break :blk res[0..out_len]; }; defer heap.c_allocator.free(cencoded_normal); debug.assert(mem.eql(u8, zencoded_normal, cencoded_normal)); } }
lib/blz/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const int = i64; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day05.txt"); const Point = struct { x: int, y: int }; const VentLine = struct { start: Point, end: Point, }; const VentMap = struct { map: Map(Point, int) = Map(Point, int).init(gpa), overlaps: int = 0, pub fn mark(self: *VentMap, x: int, y: int) void { const pt = Point{ .x = x, .y = y }; const result = self.map.getOrPut(pt) catch unreachable; if (result.found_existing) { if (result.value_ptr.* == 1) { self.overlaps += 1; } result.value_ptr.* += 1; } else { result.value_ptr.* = 1; } } }; pub fn main() !void { var vents = blk: { var vents = List(VentLine).init(gpa); var lines = tokenize(u8, data, "\r\n"); while (lines.next()) |line| { if (line.len == 0) {continue;} var parts = tokenize(u8, line, " ,->"); vents.append(.{ .start = .{ .x = try parseInt(int, parts.next().?, 10), .y = try parseInt(int, parts.next().?, 10), }, .end = .{ .x = try parseInt(int, parts.next().?, 10), .y = try parseInt(int, parts.next().?, 10), }, }) catch unreachable; assert(parts.next() == null); } break :blk vents.toOwnedSlice(); }; var map: VentMap = .{}; for (vents) |it| { if (it.start.x == it.end.x) { // horizontal line var curr_y = min(it.start.y, it.end.y); const end_y = max(it.start.y, it.end.y); while (curr_y <= end_y) : (curr_y += 1) { map.mark(it.start.x, curr_y); } } else if (it.start.y == it.end.y) { // vertical line var curr_x = min(it.start.x, it.end.x); const end_x = max(it.start.x, it.end.x); while (curr_x <= end_x) : (curr_x += 1) { map.mark(curr_x, it.start.y); } } } const part1 = map.overlaps; for (vents) |it| { if (it.start.x != it.end.x and it.start.y != it.end.y) { // diagonal line var curr_x = it.start.x; var end_x = it.end.x; var x_incr: int = if (curr_x < end_x) 1 else -1; var curr_y = it.start.y; var end_y = it.end.y; var y_incr: int = if (curr_y < end_y) 1 else -1; assert(end_x == curr_x + (end_y - curr_y) * y_incr * x_incr); while (curr_y - y_incr != end_y) : ({ curr_x += x_incr; curr_y += y_incr; }) { map.mark(curr_x, curr_y); } } } const part2 = map.overlaps; print("part1={}, part2={}\n", .{part1, part2}); } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const strEql = std.mem.eql; const strToEnum = std.meta.stringToEnum; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day05.zig
const std = @import("std"); const pike = @import("pike"); const mem = std.mem; pub const Counter = struct { const Self = @This(); state: isize = 0, event: Event = .{}, pub fn add(self: *Self, delta: isize) void { var state = @atomicLoad(isize, &self.state, .Monotonic); var new_state: isize = undefined; while (true) { new_state = state + delta; state = @cmpxchgWeak( isize, &self.state, state, new_state, .Monotonic, .Monotonic, ) orelse break; } if (new_state == 0) { self.event.notify(); } } pub fn wait(self: *Self) void { while (@atomicLoad(isize, &self.state, .Monotonic) != 0) { self.event.wait(); } } }; pub fn Queue(comptime T: type, comptime capacity: comptime_int) type { return struct { const Self = @This(); const Reader = struct { task: pike.Task, dead: bool = false, }; const Writer = struct { next: ?*Writer = null, tail: ?*Writer = null, task: pike.Task, dead: bool = false, }; lock: std.Mutex = .{}, items: [capacity]T = undefined, dead: bool = false, head: usize = 0, tail: usize = 0, reader: ?*Reader = null, writers: ?*Writer = null, pub fn close(self: *Self) void { const held = self.lock.acquire(); if (self.dead) { held.release(); return; } self.dead = true; const maybe_reader = blk: { if (self.reader) |reader| { self.reader = null; break :blk reader; } break :blk null; }; var maybe_writers = blk: { if (self.writers) |writers| { self.writers = null; break :blk writers; } break :blk null; }; held.release(); if (maybe_reader) |reader| { reader.dead = true; pike.dispatch(&reader.task, .{}); } while (maybe_writers) |writer| { writer.dead = true; maybe_writers = writer.next; pike.dispatch(&writer.task, .{}); } } pub fn pending(self: *Self) usize { const held = self.lock.acquire(); defer held.release(); return self.tail -% self.head; } pub fn push(self: *Self, item: T) !void { while (true) { const held = self.lock.acquire(); if (self.dead) { held.release(); return error.AlreadyShutdown; } if (self.tail -% self.head < capacity) { self.items[self.tail % capacity] = item; self.tail +%= 1; const maybe_reader = blk: { if (self.reader) |reader| { self.reader = null; break :blk reader; } break :blk null; }; held.release(); if (maybe_reader) |reader| { pike.dispatch(&reader.task, .{}); } return; } var writer = Writer{ .task = pike.Task.init(@frame()) }; suspend { if (self.writers) |writers| { writers.tail.?.next = &writer; } else { self.writers = &writer; } self.writers.?.tail = &writer; held.release(); } if (writer.dead) return error.OperationCancelled; } } pub fn pop(self: *Self, dst: []T) !usize { while (true) { const held = self.lock.acquire(); const count = self.tail -% self.head; if (count != 0) { var i: usize = 0; while (i < count) : (i += 1) { dst[i] = self.items[(self.head +% i) % capacity]; } self.head = self.tail; var maybe_writers = blk: { if (self.writers) |writers| { self.writers = null; break :blk writers; } break :blk null; }; held.release(); while (maybe_writers) |writer| { maybe_writers = writer.next; pike.dispatch(&writer.task, .{}); } return count; } if (self.dead) { held.release(); return error.AlreadyShutdown; } var reader = Reader{ .task = pike.Task.init(@frame()) }; suspend { self.reader = &reader; held.release(); } if (reader.dead) return error.OperationCancelled; } } }; } // pub fn Queue(comptime T: type, comptime capacity: comptime_int) type { // return struct { // items: [capacity]T = undefined, // reader: Event = .{}, // writer: Event = .{}, // dead: bool = false, // head: usize = 0, // tail: usize = 0, // const Self = @This(); // pub fn pending(self: *const Self) usize { // const head = @atomicLoad(usize, &self.head, .Acquire); // return self.tail -% head; // } // pub fn push(self: *Self, item: T) !void { // while (true) { // if (@atomicLoad(bool, &self.dead, .Monotonic)) { // return error.OperationCancelled; // } // const head = @atomicLoad(usize, &self.head, .Acquire); // if (self.tail -% head < capacity) { // self.items[self.tail % capacity] = item; // @atomicStore(usize, &self.tail, self.tail +% 1, .Release); // self.reader.notify(); // return; // } // self.writer.wait(); // } // } // pub fn pop(self: *Self, dst: []T) !usize { // while (true) { // const tail = @atomicLoad(usize, &self.tail, .Acquire); // const popped = tail -% self.head; // if (popped != 0) { // var i: usize = 0; // while (i < popped) : (i += 1) { // dst[i] = self.items[(self.head +% i) % capacity]; // } // @atomicStore(usize, &self.head, tail, .Release); // self.writer.notify(); // return popped; // } // if (@atomicLoad(bool, &self.dead, .Monotonic)) { // return error.OperationCancelled; // } // self.reader.wait(); // } // } // pub fn close(self: *Self) void { // if (@atomicRmw(bool, &self.dead, .Xchg, true, .Monotonic)) { // return; // } // self.reader.notify(); // self.writer.notify(); // } // }; // } pub const Event = struct { state: ?*pike.Task = null, var notified: pike.Task = undefined; pub fn wait(self: *Event) void { var task = pike.Task.init(@frame()); suspend { var state = @atomicLoad(?*pike.Task, &self.state, .Monotonic); while (true) { const new_state = if (state == &notified) null else if (state == null) &task else unreachable; state = @cmpxchgWeak( ?*pike.Task, &self.state, state, new_state, .Release, .Monotonic, ) orelse { if (new_state == null) pike.dispatch(&task, .{}); break; }; } } } pub fn notify(self: *Event) void { var state = @atomicLoad(?*pike.Task, &self.state, .Monotonic); while (true) { if (state == &notified) return; const new_state = if (state == null) &notified else null; state = @cmpxchgWeak( ?*pike.Task, &self.state, state, new_state, .Acquire, .Monotonic, ) orelse { if (state) |task| pike.dispatch(task, .{}); break; }; } } }; /// Async-friendly Mutex ported from Zig's standard library to be compatible /// with scheduling methods exposed by pike. pub const Mutex = struct { mutex: std.Mutex = .{}, head: usize = UNLOCKED, const UNLOCKED = 0; const LOCKED = 1; const Waiter = struct { // forced Waiter alignment to ensure it doesn't clash with LOCKED next: ?*Waiter align(2), tail: *Waiter, task: pike.Task, }; pub fn initLocked() Mutex { return Mutex{ .head = LOCKED }; } pub fn acquire(self: *Mutex) Held { const held = self.mutex.acquire(); // self.head transitions from multiple stages depending on the value: // UNLOCKED -> LOCKED: // acquire Mutex ownership when theres no waiters // LOCKED -> <Waiter head ptr>: // Mutex is already owned, enqueue first Waiter // <head ptr> -> <head ptr>: // Mutex is owned with pending waiters. Push our waiter to the queue. if (self.head == UNLOCKED) { self.head = LOCKED; held.release(); return Held{ .lock = self }; } var waiter: Waiter = undefined; waiter.next = null; waiter.tail = &waiter; const head = switch (self.head) { UNLOCKED => unreachable, LOCKED => null, else => @intToPtr(*Waiter, self.head), }; if (head) |h| { h.tail.next = &waiter; h.tail = &waiter; } else { self.head = @ptrToInt(&waiter); } suspend { waiter.task = pike.Task.init(@frame()); held.release(); } return Held{ .lock = self }; } pub const Held = struct { lock: *Mutex, pub fn release(self: Held) void { const waiter = blk: { const held = self.lock.mutex.acquire(); defer held.release(); // self.head goes through the reverse transition from acquire(): // <head ptr> -> <new head ptr>: // pop a waiter from the queue to give Mutex ownership when theres still others pending // <head ptr> -> LOCKED: // pop the laster waiter from the queue, while also giving it lock ownership when awaken // LOCKED -> UNLOCKED: // last lock owner releases lock while no one else is waiting for it switch (self.lock.head) { UNLOCKED => unreachable, // Mutex unlocked while unlocking LOCKED => { self.lock.head = UNLOCKED; break :blk null; }, else => { const waiter = @intToPtr(*Waiter, self.lock.head); self.lock.head = if (waiter.next == null) LOCKED else @ptrToInt(waiter.next); if (waiter.next) |next| next.tail = waiter.tail; break :blk waiter; }, } }; if (waiter) |w| { pike.dispatch(&w.task, .{}); } } }; };
sync.zig
const std = @import("std"); const testing = std.testing; // Convenience-function to initiate a bounded-array without inital size of 0, removing the error-case brough by .init(size) pub fn initBoundedArray(comptime T: type, comptime capacity: usize) std.BoundedArray(T, capacity) { return std.BoundedArray(T, capacity).init(0) catch unreachable; } /// Att! This adds a terminating zero at current .slice().len if there's capacity. /// Capacity must be > 0 /// If not sufficient capacity: return null? pub fn boundedArrayAsCstr(comptime capacity: usize, array: *std.BoundedArray(u8, capacity)) ![*]u8 { std.debug.assert(capacity > 0); if (array.constSlice().len >= capacity) return error.Overflow; array.buffer[array.constSlice().len] = 0; return array.slice().ptr; } test "boundedArrayAsCstr" { // { // Fails at compile-time, capacity==0 is invalid // var str = initBoundedArray(u8, 0); // var c_str = boundedArrayAsCstr(str.buffer.len, &str); // try testing.expect(c_str[0] == 0); // } { var str = initBoundedArray(u8, 1); try str.appendSlice("A"); try testing.expect(str.slice()[0] == 'A'); try str.resize(0); var c_str = try boundedArrayAsCstr(str.buffer.len, &str); try testing.expect(c_str[0] == 0); } { var str = initBoundedArray(u8, 1); try str.appendSlice("A"); try testing.expect(str.slice()[0] == 'A'); try testing.expectError(error.Overflow, boundedArrayAsCstr(str.buffer.len, &str)); } { var str = initBoundedArray(u8, 2); try str.appendSlice("AB"); try testing.expect(str.slice()[0] == 'A'); try testing.expect(str.slice()[1] == 'B'); try str.resize(1); try testing.expect(str.slice().ptr[1] == 'B'); var c_str = try boundedArrayAsCstr(str.buffer.len, &str); try testing.expect(c_str[0] == 'A'); try testing.expect(c_str[1] == 0); } } /// UTILITY: Returns a slice from <from> up to <to> or slice.len pub fn sliceUpTo(comptime T: type, slice: []T, from: usize, to: usize) []T { return slice[from..std.math.min(slice.len, to)]; } pub fn constSliceUpTo(comptime T: type, slice: []const T, from: usize, to: usize) []const T { return slice[from..std.math.min(slice.len, to)]; } // TODO: Are there any stdlib-variants of this? pub fn addUnsignedSigned(comptime UnsignedType: type, comptime SignedType: type, base: UnsignedType, delta: SignedType) !UnsignedType { if (delta >= 0) { return std.math.add(UnsignedType, base, std.math.absCast(delta)); } else { return std.math.sub(UnsignedType, base, std.math.absCast(delta)); } } test "addUnsignedSigned" { try testing.expect((try addUnsignedSigned(u64, i64, 1, 1)) == 2); try testing.expect((try addUnsignedSigned(u64, i64, 1, -1)) == 0); try testing.expectError(error.Overflow, addUnsignedSigned(u64, i64, 0, -1)); try testing.expectError(error.Overflow, addUnsignedSigned(u64, i64, std.math.maxInt(u64), 1)); }
src/utils.zig
const macro = @import("pspmacros.zig"); comptime { asm (macro.import_module_start("sceAtrac3plus", "0x00090000", "25")); asm (macro.import_function("sceAtrac3plus", "0xD1F59FDB", "sceAtracStartEntry")); asm (macro.import_function("sceAtrac3plus", "0xD5C28CC0", "sceAtracEndEntry")); asm (macro.import_function("sceAtrac3plus", "0x780F88D1", "sceAtracGetAtracID")); asm (macro.import_function("sceAtrac3plus", "0x61EB33F5", "sceAtracReleaseAtracID")); asm (macro.import_function("sceAtrac3plus", "0x0E2A73AB", "sceAtracSetData")); asm (macro.import_function("sceAtrac3plus", "0x3F6E26B5", "sceAtracSetHalfwayBuffer")); asm (macro.import_function("sceAtrac3plus", "0x7A20E7AF", "sceAtracSetDataAndGetID")); asm (macro.import_function("sceAtrac3plus", "0x0FAE370E", "sceAtracSetHalfwayBufferAndGetID")); asm (macro.import_function("sceAtrac3plus", "0x6A8C3CD5", "sceAtracDecodeData_stub")); asm (macro.import_function("sceAtrac3plus", "0x9AE849A7", "sceAtracGetRemainFrame")); asm (macro.import_function("sceAtrac3plus", "0x5D268707", "sceAtracGetStreamDataInfo")); asm (macro.import_function("sceAtrac3plus", "0x7DB31251", "sceAtracAddStreamData")); asm (macro.import_function("sceAtrac3plus", "0x83E85EA0", "sceAtracGetSecondBufferInfo")); asm (macro.import_function("sceAtrac3plus", "0x83BF7AFD", "sceAtracSetSecondBuffer")); asm (macro.import_function("sceAtrac3plus", "0xE23E3A35", "sceAtracGetNextDecodePosition")); asm (macro.import_function("sceAtrac3plus", "0xA2BBA8BE", "sceAtracGetSoundSample")); asm (macro.import_function("sceAtrac3plus", "0x31668BAA", "sceAtracGetChannel")); asm (macro.import_function("sceAtrac3plus", "0xD6A5F2F7", "sceAtracGetMaxSample")); asm (macro.import_function("sceAtrac3plus", "0x36FAABFB", "sceAtracGetNextSample")); asm (macro.import_function("sceAtrac3plus", "0xA554A158", "sceAtracGetBitrate")); asm (macro.import_function("sceAtrac3plus", "0xFAA4F89B", "sceAtracGetLoopStatus")); asm (macro.import_function("sceAtrac3plus", "0x868120B5", "sceAtracSetLoopNum")); asm (macro.import_function("sceAtrac3plus", "0xCA3CA3D2", "sceAtracGetBufferInfoForReseting")); asm (macro.import_function("sceAtrac3plus", "0x644E5607", "sceAtracResetPlayPosition")); asm (macro.import_function("sceAtrac3plus", "0xE88F759B", "sceAtracGetInternalErrorInfo")); asm (macro.generic_abi_wrapper("sceAtracDecodeData", 5)); }
src/psp/nids/pspatrac3.zig
const std = @import("std"); const stdx = @import("stdx"); const uv = @import("uv"); const gl = @import("gl"); const ma = @import("miniaudio"); const GLint = gl.GLint; const GLsizei = gl.GLsizei; const GLclampf = gl.GLclampf; const GLenum = gl.GLenum; const log = stdx.log.scoped(.lib_mock); extern fn unitTraceC(fn_name_ptr: *const u8, fn_name_len: usize) void; /// Since lib_mock is compiled as a static lib, it would use a different reference to the global mocks var /// if we called unitTrace directly. Instead, call into an exported c function. fn unitTrace(loc: std.builtin.SourceLocation) void { unitTraceC(&loc.fn_name[0], loc.fn_name.len); } // Mocked out external deps. export fn glViewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) void { _ = x; _ = y; _ = width; _ = height; } export fn glClearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) void { _ = red; _ = green; _ = blue; _ = alpha; } export fn glDisable(cap: GLenum) void { _ = cap; } export fn glEnable(cap: GLenum) void { _ = cap; } export fn glGetIntegerv(pname: GLenum, params: [*c]GLint) void { _ = pname; _ = params; } export fn glBlendFunc(sfactor: GLenum, dfactor: GLenum) void { _ = sfactor; _ = dfactor; } export fn lyon_init() void {} export fn lyon_deinit() void {} export fn glDeleteBuffers() void {} export fn glDeleteVertexArrays() void {} export fn glDeleteTextures() void {} export fn glUniformMatrix4fv() void {} export fn glGetUniformLocation() void {} export fn glUniform1i() void {} export fn glBufferData() void {} export fn glDrawElements() void {} export fn glTexSubImage2D() void {} export fn glScissor() void {} export fn glBlendEquation() void {} export fn SDL_GL_DeleteContext() void {} export fn SDL_DestroyWindow() void {} export fn SDL_CaptureMouse() void {} export fn v8__Persistent__Reset() void {} export fn v8__Boolean__New() void {} export fn stbtt_GetGlyphBitmapBox() void {} export fn stbtt_MakeGlyphBitmap() void {} export fn v8__HandleScope__CONSTRUCT() void {} export fn v8__TryCatch__CONSTRUCT() void {} export fn v8__Value__IsAsyncFunction() void {} export fn v8__Function__Call() void {} export fn v8__Function__New__DEFAULT2() void {} export fn v8__ObjectTemplate__SetInternalFieldCount() void {} export fn v8__ObjectTemplate__NewInstance() void {} export fn v8__Object__SetInternalField() void {} export fn v8__Promise__Then2() void {} export fn v8__TryCatch__DESTRUCT() void {} export fn v8__HandleScope__DESTRUCT() void {} export fn v8__Object__GetInternalField() void {} export fn v8__External__Value() void {} export fn v8__Value__Uint32Value() void {} export fn v8__Persistent__New() void {} export fn v8__Value__NumberValue() void {} export fn v8__Persistent__SetWeakFinalizer() void {} export fn v8__WeakCallbackInfo__GetParameter() void {} export fn curl_slist_free_all() void {} export fn v8__Promise__Resolver__New() void {} export fn v8__Promise__Resolver__GetPromise() void {} export fn uv_timer_init(loop: *uv.uv_loop_t, timer: *uv.uv_timer_t) c_int { _ = loop; _ = timer; return 0; } export fn uv_async_send(async_: *uv.uv_async_t) c_int { _ = async_; return 0; } export fn TLS_server_method() void {} export fn SSL_CTX_new() void {} export fn OPENSSL_init_ssl() void {} export fn OPENSSL_init_crypto() void {} export fn SSL_CTX_set_options() void {} export fn SSL_CTX_use_PrivateKey_file() void {} export fn SSL_CTX_set_cipher_list() void {} export fn SSL_CTX_set_ciphersuites() void {} export fn SSL_CTX_use_certificate_chain_file() void {} export fn h2o_get_alpn_protocols() void {} export fn h2o_ssl_register_alpn_protocols() void {} export fn v8__FunctionTemplate__GetFunction() void {} export fn v8__Function__NewInstance() void {} export fn uv_timer_start(handle: *uv.uv_timer_t, cb: uv.uv_timer_cb, timeout: u64, repeat: u64) c_int { _ = handle; _ = cb; _ = timeout; _ = repeat; return 0; } export fn h2o_strdup() void {} export fn h2o_set_header_by_str() void {} export fn h2o_start_response() void {} export fn h2o_send() void {} export fn v8__FunctionCallbackInfo__Length() void {} export fn v8__FunctionCallbackInfo__INDEX() void {} export fn v8__ArrayBufferView__Buffer() void {} export fn v8__ArrayBuffer__GetBackingStore() void {} export fn std__shared_ptr__v8__BackingStore__get() void {} export fn v8__BackingStore__ByteLength() void {} export fn v8__BackingStore__Data() void {} export fn std__shared_ptr__v8__BackingStore__reset() void {} export fn v8__Value__IsObject() void {} export fn v8__Object__Get() void {} export fn v8__Object__Set() void {} export fn v8__External__New() void {} export fn v8__ObjectTemplate__New__DEFAULT() void {} export fn v8__String__NewFromUtf8() void {} export fn v8__TryCatch__HasCaught() void {} export fn v8__TryCatch__Message() void {} export fn v8__Message__GetSourceLine() void {} export fn v8__Message__GetStartColumn() void {} export fn v8__Message__GetEndColumn() void {} export fn v8__TryCatch__StackTrace() void {} export fn v8__TryCatch__Exception() void {} export fn v8__Value__ToString() void {} export fn v8__String__Utf8Length() void {} export fn v8__String__WriteUtf8() void {} export fn SDL_InitSubSystem() void {} export fn SDL_GetError() void {} export fn SDL_GetWindowID() void {} export fn stbi_load_from_memory() void {} export fn stbi_failure_reason() void {} export fn stbi_image_free() void {} export fn glGenTextures() void {} export fn glBindTexture() void {} export fn glTexParameteri() void {} export fn glTexImage2D() void {} export fn curl_slist_append() void {} export fn curl_easy_setopt() void {} export fn curl_easy_perform() void {} export fn curl_easy_getinfo() void {} export fn curl_easy_init() void {} export fn curl_multi_add_handle() void {} export fn uv_tcp_init() void {} export fn uv_strerror() void {} export fn uv_ip4_addr() void {} export fn uv_tcp_bind() void {} export fn uv_listen() void {} export fn uv_pipe_init() void {} export fn uv_read_start() void {} export fn uv_spawn() void {} export fn h2o_config_register_host() void {} export fn h2o_context_init() void {} export fn h2o_context_request_shutdown() void {} export fn uv_close() void {} export fn uv_accept() void {} export fn h2o_uv_socket_create() void {} export fn h2o_accept() void {} export fn uv_handle_get_type() void {} export fn h2o_config_register_path() void {} export fn h2o_create_handler() void {} export fn v8__Integer__NewFromUnsigned() void {} export fn v8__FunctionCallbackInfo__Data() void {} export fn v8__Object__New() void {} export fn v8__Exception__Error() void {} export fn v8__Isolate__ThrowException() void {} export fn SDL_GL_CreateContext() void {} export fn glGetString() void {} export fn SDL_GL_MakeCurrent() void {} export fn SDL_GL_SetAttribute() void {} export fn SDL_CreateWindow() void {} export fn glActiveTexture() void {} export fn stbtt_GetGlyphKernAdvance() void {} export fn lyon_new_builder() void {} export fn lyon_begin() void {} export fn lyon_cubic_bezier_to() void {} export fn lyon_end() void {} export fn lyon_build_stroke() void {} export fn lyon_quadratic_bezier_to() void {} export fn lyon_add_polygon() void {} export fn lyon_build_fill() void {} export fn v8__Number__New() void {} export fn v8__Promise__Resolver__Resolve() void {} export fn v8__Promise__Resolver__Reject() void {} export fn v8__Value__BooleanValue() void {} export fn glBindVertexArray() void {} export fn glBindBuffer() void {} export fn glEnableVertexAttribArray() void {} export fn glCreateShader() void {} export fn glShaderSource() void {} export fn glCompileShader() void {} export fn glGetShaderiv() void {} export fn glGetShaderInfoLog() void {} export fn glDeleteShader() void {} export fn glCreateProgram() void {} export fn glAttachShader() void {} export fn glLinkProgram() void {} export fn glGetProgramiv() void {} export fn glGetProgramInfoLog() void {} export fn glDeleteProgram() void {} export fn glDetachShader() void {} export fn glGenVertexArrays() void {} export fn glGenFramebuffers() void {} export fn glBindFramebuffer() void {} export fn glTexImage2DMultisample() void {} export fn glFramebufferTexture2D() void {} export fn glGenBuffers() void {} export fn glVertexAttribPointer() void {} export fn stbtt_InitFont() void {} export fn lyon_line_to() void {} export fn v8__Array__New2() void {} export fn v8__ArrayBuffer__NewBackingStore() void {} export fn v8__BackingStore__TO_SHARED_PTR() void {} export fn v8__ArrayBuffer__New2() void {} export fn v8__Uint8Array__New() void {} export fn glUseProgram() void {} export fn h2o_config_init() void {} export fn v8__Message__GetStackTrace() void {} export fn v8__StackTrace__GetFrameCount() void {} export fn v8__StackTrace__GetFrame() void {} export fn v8__StackFrame__GetFunctionName() void {} export fn v8__StackFrame__GetScriptNameOrSourceURL() void {} export fn v8__StackFrame__GetLineNumber() void {} export fn v8__StackFrame__GetColumn() void {} export fn v8__Isolate__CreateParams__SIZEOF() void {} export fn v8__TryCatch__SIZEOF() void {} export fn v8__PromiseRejectMessage__SIZEOF() void {} export fn v8__Platform__NewDefaultPlatform() void {} export fn v8__V8__InitializePlatform() void {} export fn v8__V8__Initialize() void {} export fn v8__Isolate__CreateParams__CONSTRUCT() void {} export fn v8__ArrayBuffer__Allocator__NewDefaultAllocator() void {} export fn v8__Isolate__New() void {} export fn v8__Isolate__Enter() void {} export fn v8__Context__Enter() void {} export fn v8__Platform__PumpMessageLoop() void {} export fn v8__Context__Exit() void {} export fn v8__Isolate__Exit() void {} export fn v8__Isolate__Dispose() void {} export fn v8__ArrayBuffer__Allocator__DELETE() void {} export fn v8__V8__Dispose() void {} export fn v8__V8__ShutdownPlatform() void {} export fn v8__Message__GetScriptResourceName() void {} export fn v8__V8__DisposePlatform() void {} export fn v8__Platform__DELETE() void {} export fn v8__V8__GetVersion() void {} export fn h2o__tokens() void {} export fn h2o_globalconf_size() void {} export fn h2o_hostconf_size() void {} export fn h2o_httpclient_ctx_size() void {} export fn h2o_context_size() void {} export fn h2o_accept_ctx_size() void {} export fn h2o_socket_size() void {} export fn uv_loop_init(loop: *uv.uv_loop_t) c_int { _ = loop; return 0; } export fn uv_async_init() void {} export fn uv_run() void {} export fn curl_global_cleanup() void {} export fn SDL_PollEvent() void {} export fn curl_global_init() void {} export fn curl_share_init() void {} export fn curl_share_setopt() void {} export fn curl_multi_init() void {} export fn curl_multi_setopt() void {} export fn uv_poll_start() void {} export fn uv_poll_stop() void {} export fn uv_timer_stop() void {} export fn uv_backend_fd() void {} export fn v8__Isolate__SetPromiseRejectCallback() void {} export fn v8__Isolate__SetMicrotasksPolicy() void {} export fn v8__Isolate__SetCaptureStackTraceForUncaughtExceptions() void {} export fn v8__Isolate__AddMessageListenerWithErrorLevel() void {} export fn v8__FunctionTemplate__New__DEFAULT() void {} export fn v8__FunctionTemplate__InstanceTemplate() void {} export fn v8__FunctionTemplate__PrototypeTemplate() void {} export fn v8__FunctionTemplate__SetClassName() void {} export fn v8__ObjectTemplate__New() void {} export fn v8__ScriptOrigin__CONSTRUCT() void {} export fn v8__Isolate__GetCurrentContext() void {} export fn v8__Script__Compile() void {} export fn v8__Script__Run() void {} export fn curl_easy_cleanup() void {} export fn curl_multi_cleanup() void {} export fn curl_share_cleanup() void {} export fn v8__TryCatch__SetVerbose() void {} export fn SDL_Delay() void {} export fn v8__Promise__State() void {} export fn v8__Isolate__PerformMicrotaskCheckpoint() void {} export fn v8__Context__New() void {} export fn uv_poll_init_socket() void {} export fn curl_multi_assign() void {} export fn v8__Undefined() void {} export fn v8__Null() void {} export fn v8__False() void {} export fn v8__True() void {} export fn uv_backend_timeout() void {} export fn v8__PromiseRejectMessage__GetPromise() void {} export fn v8__Object__GetIsolate() void {} export fn v8__Object__GetCreationContext() void {} export fn v8__PromiseRejectMessage__GetEvent() void {} export fn v8__PromiseRejectMessage__GetValue() void {} export fn v8__Object__GetIdentityHash() void {} export fn v8__FunctionTemplate__New__DEFAULT3() void {} export fn v8__Template__Set() void {} export fn v8__Template__SetAccessorProperty__DEFAULT() void {} export fn curl_multi_socket_action() void {} export fn curl_multi_strerror() void {} export fn curl_multi_info_read() void {} export fn v8__FunctionCallbackInfo__GetReturnValue() void {} export fn v8__ReturnValue__Set() void {} export fn curl_multi_remove_handle() void {} export fn v8__FunctionCallbackInfo__This() void {} export fn v8__Integer__Value() void {} export fn v8__Value__IsFunction() void {} export fn v8__Value__IsArray() void {} export fn v8__Array__Length() void {} export fn v8__Object__GetIndex() void {} export fn v8__Value__InstanceOf() void {} export fn v8__Value__IsUint8Array() void {} export fn v8__Object__GetOwnPropertyNames() void {} export fn v8__Integer__New() void {} export fn SDL_MinimizeWindow() void {} export fn SDL_MaximizeWindow() void {} export fn SDL_RestoreWindow() void {} export fn SDL_SetWindowFullscreen() void {} export fn SDL_SetWindowPosition() void {} export fn SDL_RaiseWindow() void {} export fn v8__Value__Int32Value() void {} export fn curl_easy_strerror() void {} export fn uv_walk() void {} export fn uv_stop() void {} export fn uv_loop_size() void {} export fn uv_loop_close() void {} export fn uv_fs_event_init() void {} export fn uv_fs_event_start() void {} export fn v8__Message__Get() void {} export fn v8__Isolate__TerminateExecution() void {} export fn v8__Isolate__IsExecutionTerminating() void {} export fn v8__StackTrace__CurrentStackTrace__STATIC() void {} export fn h2o_timer_unlink() void {} export fn h2o_config_dispose() void {} export fn v8__Context__Global() void {} export fn h2o_context_dispose() void {} export fn uv_is_closing() void {} export fn SDL_GL_GetDrawableSize() void {} export fn SDL_SetWindowSize() void {} export fn SDL_GetWindowSize() void {} export fn SDL_SetWindowTitle() void {} export fn SDL_GetWindowTitle() void {} export fn v8__ScriptCompiler__Source__CONSTRUCT() void {} export fn v8__ScriptCompiler__Source__CONSTRUCT2() void {} export fn v8__ScriptCompiler__Source__DESTRUCT() void {} export fn v8__ScriptCompiler__Source__SIZEOF() void {} export fn v8__Context__GetIsolate() void {} export fn v8__ScriptOrigin__CONSTRUCT2() void {} export fn v8__Context__GetEmbedderData() void {} export fn v8__Context__SetEmbedderData() void {} export fn v8__Module__Evaluate() void {} export fn v8__Module__GetException() void {} export fn v8__ScriptCompiler__CompileModule() void {} export fn v8__Module__GetStatus() void {} export fn v8__Module__InstantiateModule() void {} export fn v8__Module__ScriptId() void {} export fn v8__Exception__GetStackTrace() void {} export fn v8__TryCatch__ReThrow() void {} export fn v8__ScriptCompiler__CachedData__SIZEOF() void {} export fn v8__Message__GetLineNumber() void {} export fn v8__Object__SetAlignedPointerInInternalField() void {} export fn ma_sound_uninit() void {} export fn ma_sound_start() void {} export fn v8__WeakCallbackInfo__GetInternalField() void {} export fn ma_sound_is_playing() void {} export fn ma_sound_init_from_data_source() void {} export fn ma_sound_at_end() void {} export fn ma_result_description() void {} export fn ma_engine_init() ma.ma_result { unitTrace(@src()); return 0; } export fn v8__Isolate__LowMemoryNotification() void {} export fn ma_decoder_uninit() void {} export fn ma_decoder_init_memory() void {} export fn ma_decoder_config_init_default() void {} export fn ma_sound_set_pan() void {} export fn ma_sound_set_volume() void {} export fn ma_sound_set_pitch() void {} export fn ma_sound_get_volume() void {} export fn ma_sound_get_pitch() void {} export fn ma_sound_get_pan() void {} export fn ma_volume_db_to_linear() void {} export fn ma_volume_linear_to_db() void {} export fn v8__HeapStatistics__SIZEOF() void {} export fn ma_data_source_seek_to_pcm_frame() void {} export fn ma_sound_stop() void {} export fn ma_engine_listener_get_position() void {} export fn ma_engine_listener_get_velocity() void {} export fn ma_engine_listener_get_world_up() void {} export fn ma_engine_listener_set_direction() void {} export fn ma_engine_listener_set_position() void {} export fn ma_engine_listener_set_velocity() void {} export fn v8__Value__IsString() void {} export fn ma_engine_listener_set_world_up() void {} export fn v8__BigInt__Uint64Value() void {} export fn ma_sound_set_velocity() void {} export fn ma_engine_listener_get_direction() void {} export fn ma_sound_set_position() void {} export fn v8__BigInt__NewFromUnsigned() void {} export fn ma_sound_set_looping() void {} export fn ma_sound_set_direction() void {} export fn ma_sound_is_looping() void {} export fn ma_sound_get_velocity() void {} export fn ma_sound_get_position() void {} export fn ma_sound_get_length_in_pcm_frames() void {} export fn ma_sound_get_direction() void {} export fn ma_sound_get_data_format() void {} export fn ma_sound_get_cursor_in_pcm_frames() void {} export fn v8__Value__IsBigInt() void {} export fn SDL_PushEvent() void {} export fn v8__Function__GetName() void {} export fn v8__Value__IsNullOrUndefined() void {} export fn v8__base__SetDcheckFunction() void {} export fn v8__JSON__Parse() void {} export fn SDL_GL_GetProcAddress() void {} export fn uv_tcp_getsockname() void {} export fn SDL_free() void {} export fn SDL_SetClipboardText() void {} export fn SDL_GetClipboardText() void {} export fn GetProcessTimes() void {} export fn FT_Init_FreeType() c_int { return 0; } export fn FT_Error_String() void {} export fn FT_Get_Kerning() void {} export fn glUniform4fv() void {} export fn glUniform2fv() void {} export fn FT_Load_Glyph() void {} export fn FT_New_Memory_Face() void {} export fn FT_Render_Glyph() void {} export fn FT_Set_Pixel_Sizes() void {} export fn stbi_write_bmp() void {} export fn SDL_Vulkan_GetVkGetInstanceProcAddr() void {} export fn SDL_Vulkan_GetInstanceExtensions() void {} export fn SDL_Vulkan_GetDrawableSize() void {} export fn SDL_Vulkan_CreateSurface() void {} export fn vkEnumeratePhysicalDevices() void {} export fn vkGetPhysicalDeviceFeatures() void {} export fn vkCreateInstance() void {} export fn vkCreateDevice() void {} export fn vkEnumerateInstanceLayerProperties() void {} export fn vkGetPhysicalDeviceQueueFamilyProperties() void {} export fn vkGetPhysicalDeviceSurfaceSupportKHR() void {} export fn vkEnumerateDeviceExtensionProperties() void {} export fn vkGetPhysicalDeviceSurfaceCapabilitiesKHR() void {} export fn vkGetPhysicalDeviceSurfaceFormatsKHR() void {} export fn vkGetPhysicalDeviceSurfacePresentModesKHR() void {} export fn vkGetDeviceQueue() void {} export fn vkAllocateDescriptorSets() void {} export fn vkUpdateDescriptorSets() void {} export fn vkGetSwapchainImagesKHR() void {} export fn vkCreateSwapchainKHR() void {} export fn vkCreateCommandPool() void {} export fn vkAllocateCommandBuffers() void {} export fn vkCreateRenderPass() void {} export fn vkCreateSampler() void {} export fn vkDestroyDevice() void {} export fn vkDestroySurfaceKHR() void {} export fn vkDestroyInstance() void {} export fn vkMapMemory() void {} export fn vkDestroyBuffer() void {} export fn vkFreeMemory() void {} export fn vkUnmapMemory() void {} export fn vkCmdSetScissor() void {} export fn vkCreateImageView() void {} export fn vkCreateImage() void {} export fn vkGetImageMemoryRequirements() void {} export fn vkAllocateMemory() void {} export fn vkBindImageMemory() void {} export fn vkCreateSemaphore() void {} export fn vkCreateFence() void {} export fn vkCreateFramebuffer() void {} export fn vkCreateDescriptorSetLayout() void {} export fn vkCreateDescriptorPool() void {} export fn vkCreateBuffer() void {} export fn vkGetBufferMemoryRequirements() void {} export fn vkBindBufferMemory() void {} export fn vkCmdPipelineBarrier() void {} export fn vkCmdCopyBufferToImage() void {} export fn vkGetPhysicalDeviceMemoryProperties() void {} export fn vkCreatePipelineLayout() void {} export fn vkCreateGraphicsPipelines() void {} export fn vkDestroyShaderModule() void {} export fn vkCmdBindPipeline() void {} export fn vkCmdBindDescriptorSets() void {} export fn vkCmdPushConstants() void {} export fn vkCmdDrawIndexed() void {} export fn vkBeginCommandBuffer() void {} export fn vkEndCommandBuffer() void {} export fn vkQueueSubmit() void {} export fn vkQueueWaitIdle() void {} export fn vkFreeCommandBuffers() void {} export fn vkCreateShaderModule() void {}
test/lib_mock.zig
const std = @import("std"); const stdx = @import("stdx"); const t = stdx.testing; const log = stdx.log.scoped(.parser_simple_test); const _parser = @import("parser.zig"); const Parser = _parser.Parser; const DebugInfo = _parser.DebugInfo; const ParseConfig = _parser.ParseConfig; const _grammar = @import("grammar.zig"); const Grammar = _grammar.Grammar; const builder = @import("builder.zig"); const grammars = @import("grammars.zig"); const _ast = @import("ast.zig"); test "Parse zig simple" { const src = \\const std = @import("std"); \\ \\pub fn main() !void { \\ const stdout = std.io.getStdOut().writer(); \\ try stdout.print("Hello, {s}!\n", .{"world"}); \\} ; var str_buf = std.ArrayList(u8).init(t.alloc); defer str_buf.deinit(); var grammar: Grammar = undefined; try builder.initGrammar(&grammar, t.alloc, grammars.ZigGrammar); defer grammar.deinit(); var parser = Parser.init(t.alloc, &grammar); defer parser.deinit(); var debug: DebugInfo = undefined; debug.init(t.alloc); defer debug.deinit(); const Config: ParseConfig = .{ .is_incremental = false }; var res = parser.parseDebug(Config, src, &debug); defer res.deinit(); if (!res.success) { str_buf.clearRetainingCapacity(); res.ast.formatContextAtToken(str_buf.writer(), res.err_token_id); log.warn("{s}", .{str_buf.items}); str_buf.clearRetainingCapacity(); debug.formatMaxCallStack(Config, &res.ast, str_buf.writer()); log.warn("{s}", .{str_buf.items}); try t.fail(); } // buf.clearRetainingCapacity(); // zig_parser.tokenizer.formatTokens(buf.writer()); // log.warn("{s}", .{buf.items}); // buf.clearRetainingCapacity(); // ast.formatTree(buf.writer()); // log.warn("{s}", .{buf.items}); const ast = res.ast; const stmts = ast.getChildNodeList(ast.mb_root.?, 0); try t.eq(stmts.len, 2); try t.eqStr(ast.getNodeTagName(stmts[0]), "VariableDecl"); try t.eqStr(ast.getNodeTagName(stmts[1]), "FunctionDecl"); } // test "Parse Typescript" { // const ts = // \\type Item = { // \\ title: string, // \\ data: any, // \\} // \\function do(arg: string): Item { // \\ if (arg == 'foo') { // \\ return 123; // \\ } // \\} // ; // }
parser/parser_simple.test.zig
const std = @import("index.zig"); const HashMap = std.HashMap; const mem = std.mem; const Allocator = mem.Allocator; const assert = std.debug.assert; /// BufMap copies keys and values before they go into the map, and /// frees them when they get removed. pub const BufMap = struct.{ hash_map: BufMapHashMap, const BufMapHashMap = HashMap([]const u8, []const u8, mem.hash_slice_u8, mem.eql_slice_u8); pub fn init(allocator: *Allocator) BufMap { var self = BufMap.{ .hash_map = BufMapHashMap.init(allocator) }; return self; } pub fn deinit(self: *const BufMap) void { var it = self.hash_map.iterator(); while (true) { const entry = it.next() orelse break; self.free(entry.key); self.free(entry.value); } self.hash_map.deinit(); } pub fn set(self: *BufMap, key: []const u8, value: []const u8) !void { self.delete(key); const key_copy = try self.copy(key); errdefer self.free(key_copy); const value_copy = try self.copy(value); errdefer self.free(value_copy); _ = try self.hash_map.put(key_copy, value_copy); } pub fn get(self: *const BufMap, key: []const u8) ?[]const u8 { const entry = self.hash_map.get(key) orelse return null; return entry.value; } pub fn delete(self: *BufMap, key: []const u8) void { const entry = self.hash_map.remove(key) orelse return; self.free(entry.key); self.free(entry.value); } pub fn count(self: *const BufMap) usize { return self.hash_map.count(); } pub fn iterator(self: *const BufMap) BufMapHashMap.Iterator { return self.hash_map.iterator(); } fn free(self: *const BufMap, value: []const u8) void { self.hash_map.allocator.free(value); } fn copy(self: *const BufMap, value: []const u8) ![]const u8 { return mem.dupe(self.hash_map.allocator, u8, value); } }; test "BufMap" { var direct_allocator = std.heap.DirectAllocator.init(); defer direct_allocator.deinit(); var bufmap = BufMap.init(&direct_allocator.allocator); defer bufmap.deinit(); try bufmap.set("x", "1"); assert(mem.eql(u8, bufmap.get("x").?, "1")); assert(1 == bufmap.count()); try bufmap.set("x", "2"); assert(mem.eql(u8, bufmap.get("x").?, "2")); assert(1 == bufmap.count()); try bufmap.set("x", "3"); assert(mem.eql(u8, bufmap.get("x").?, "3")); assert(1 == bufmap.count()); bufmap.delete("x"); assert(0 == bufmap.count()); }
std/buf_map.zig
const std = @import("std"); const assert = std.debug.assert; const log = std.log; const os = std.os; const pam = @import("pam.zig"); pub const Connection = struct { read_fd: os.fd_t, write_fd: os.fd_t, pub fn reader(conn: Connection) std.fs.File.Reader { const file = std.fs.File{ .handle = conn.read_fd }; return file.reader(); } pub fn writer(conn: Connection) std.fs.File.Writer { const file = std.fs.File{ .handle = conn.write_fd }; return file.writer(); } }; pub fn fork_child() !Connection { const parent_to_child = try os.pipe(); const child_to_parent = try os.pipe(); const pid = try os.fork(); if (pid == 0) { // We are the child os.close(parent_to_child[1]); os.close(child_to_parent[0]); run(.{ .read_fd = parent_to_child[0], .write_fd = child_to_parent[1], }); } else { // We are the parent os.close(parent_to_child[0]); os.close(child_to_parent[1]); return Connection{ .read_fd = child_to_parent[0], .write_fd = parent_to_child[1], }; } } /// Maximum password size in bytes. pub const password_size_max = 1024; var password: std.BoundedArray(u8, password_size_max) = .{ .buffer = undefined }; pub fn run(conn: Connection) noreturn { const conv: pam.Conv = .{ .conv = converse, .appdata_ptr = null, }; var pamh: *pam.Handle = undefined; { const pw = getpwuid(os.linux.getuid()) orelse { log.err("failed to get name of current user", .{}); os.exit(1); }; const result = pam.start("waylock", pw.pw_name, &conv, &pamh); if (result != .success) { log.err("failed to initialize PAM: {s}", .{result.description()}); os.exit(1); } } while (true) { read_password(conn) catch |err| { log.err("failed to read password from pipe: {s}", .{@errorName(err)}); os.exit(1); }; const auth_result = pamh.authenticate(0); std.crypto.utils.secureZero(u8, &password.buffer); password.len = 0; if (auth_result == .success) { log.debug("PAM authentication succeeded", .{}); conn.writer().writeByte(@boolToInt(true)) catch |err| { log.err("failed to notify parent of success: {s}", .{@errorName(err)}); os.exit(1); }; // We don't need to prevent unlocking if this fails. Failure just // means that some extra things like Kerberos might not work without // user intervention. const setcred_result = pamh.setcred(pam.flags.reinitialize_cred); if (setcred_result != .success) { log.err("PAM failed to reinitialize credentials: {s}", .{ setcred_result.description(), }); } const end_result = pamh.end(setcred_result); if (end_result != .success) { log.err("PAM deinitialization failed: {s}", .{end_result}); } os.exit(0); } else { log.err("PAM authentication failed: {s}", .{auth_result.description()}); conn.writer().writeByte(@boolToInt(false)) catch |err| { log.err("failed to notify parent of failure: {s}", .{@errorName(err)}); os.exit(1); }; if (auth_result == .abort) { const end_result = pamh.end(auth_result); if (end_result != .success) { log.err("PAM deinitialization failed: {s}", .{end_result}); } os.exit(1); } } } } fn read_password(conn: Connection) !void { assert(password.len == 0); const reader = conn.reader(); const length = try reader.readIntNative(u32); try password.resize(length); try reader.readNoEof(password.slice()); } fn converse( num_msg: c_int, msg: [*]*const pam.Message, resp: *[*]pam.Response, _: ?*anyopaque, ) callconv(.C) pam.Result { const ally = std.heap.raw_c_allocator; const count = @intCast(usize, num_msg); const responses = ally.alloc(pam.Response, count) catch { return .buf_err; }; for (msg[0..count]) |message, i| { switch (message.msg_style) { .prompt_echo_off => { responses[i] = .{ .resp = ally.dupeZ(u8, password.slice()) catch { return .buf_err; }, }; }, .prompt_echo_on, .error_msg, .text_info => { log.warn("ignoring PAM message: msg_style={s} msg='{s}'", .{ @tagName(message.msg_style), message.msg, }); }, } } resp.* = responses.ptr; return .success; } // TODO: upstream these to the zig standard library pub const passwd = extern struct { pw_name: [*:0]const u8, pw_passwd: [*:0]const u8, pw_uid: os.uid_t, pw_gid: os.gid_t, pw_change: os.time_t, pw_class: [*:0]const u8, pw_gecos: [*:0]const u8, pw_dir: [*:0]const u8, pw_shell: [*:0]const u8, pw_expire: os.time_t, }; pub extern fn getpwuid(uid: os.uid_t) ?*passwd;
src/auth.zig
const builtin = @import("builtin"); pub use @import("errno.zig"); const std = @import("../../index.zig"); const c = std.c; const assert = std.debug.assert; const maxInt = std.math.maxInt; pub const Kevent = c.Kevent; pub const CTL_KERN = 1; pub const CTL_DEBUG = 5; pub const KERN_PROC_ARGS = 48; // struct: process argv/env pub const KERN_PROC_PATHNAME = 5; // path to executable pub const PATH_MAX = 1024; pub const STDIN_FILENO = 0; pub const STDOUT_FILENO = 1; pub const STDERR_FILENO = 2; pub const PROT_NONE = 0; pub const PROT_READ = 1; pub const PROT_WRITE = 2; pub const PROT_EXEC = 4; pub const CLOCK_REALTIME = 0; pub const CLOCK_VIRTUAL = 1; pub const CLOCK_PROF = 2; pub const CLOCK_MONOTONIC = 3; pub const CLOCK_THREAD_CPUTIME_ID = 0x20000000; pub const CLOCK_PROCESS_CPUTIME_ID = 0x40000000; pub const MAP_FAILED = maxInt(usize); pub const MAP_SHARED = 0x0001; pub const MAP_PRIVATE = 0x0002; pub const MAP_REMAPDUP = 0x0004; pub const MAP_FIXED = 0x0010; pub const MAP_RENAME = 0x0020; pub const MAP_NORESERVE = 0x0040; pub const MAP_INHERIT = 0x0080; pub const MAP_HASSEMAPHORE = 0x0200; pub const MAP_TRYFIXED = 0x0400; pub const MAP_WIRED = 0x0800; pub const MAP_FILE = 0x0000; pub const MAP_NOSYNC = 0x0800; pub const MAP_ANON = 0x1000; pub const MAP_ANONYMOUS = MAP_ANON; pub const MAP_STACK = 0x2000; pub const WNOHANG = 0x00000001; pub const WUNTRACED = 0x00000002; pub const WSTOPPED = WUNTRACED; pub const WCONTINUED = 0x00000010; pub const WNOWAIT = 0x00010000; pub const WEXITED = 0x00000020; pub const WTRAPPED = 0x00000040; pub const SA_ONSTACK = 0x0001; pub const SA_RESTART = 0x0002; pub const SA_RESETHAND = 0x0004; pub const SA_NOCLDSTOP = 0x0008; pub const SA_NODEFER = 0x0010; pub const SA_NOCLDWAIT = 0x0020; pub const SA_SIGINFO = 0x0040; pub const SIGHUP = 1; pub const SIGINT = 2; pub const SIGQUIT = 3; pub const SIGILL = 4; pub const SIGTRAP = 5; pub const SIGABRT = 6; pub const SIGIOT = SIGABRT; pub const SIGEMT = 7; pub const SIGFPE = 8; pub const SIGKILL = 9; pub const SIGBUS = 10; pub const SIGSEGV = 11; pub const SIGSYS = 12; pub const SIGPIPE = 13; pub const SIGALRM = 14; pub const SIGTERM = 15; pub const SIGURG = 16; pub const SIGSTOP = 17; pub const SIGTSTP = 18; pub const SIGCONT = 19; pub const SIGCHLD = 20; pub const SIGTTIN = 21; pub const SIGTTOU = 22; pub const SIGIO = 23; pub const SIGXCPU = 24; pub const SIGXFSZ = 25; pub const SIGVTALRM = 26; pub const SIGPROF = 27; pub const SIGWINCH = 28; pub const SIGINFO = 29; pub const SIGUSR1 = 30; pub const SIGUSR2 = 31; pub const SIGPWR = 32; pub const SIGRTMIN = 33; pub const SIGRTMAX = 63; // access function pub const F_OK = 0; // test for existence of file pub const X_OK = 1; // test for execute or search permission pub const W_OK = 2; // test for write permission pub const R_OK = 4; // test for read permission pub const O_RDONLY = 0x0000; pub const O_WRONLY = 0x0001; pub const O_RDWR = 0x0002; pub const O_ACCMODE = 0x0003; pub const O_CREAT = 0x0200; pub const O_EXCL = 0x0800; pub const O_NOCTTY = 0x8000; pub const O_TRUNC = 0x0400; pub const O_APPEND = 0x0008; pub const O_NONBLOCK = 0x0004; pub const O_DSYNC = 0x00010000; pub const O_SYNC = 0x0080; pub const O_RSYNC = 0x00020000; pub const O_DIRECTORY = 0x00080000; pub const O_NOFOLLOW = 0x00000100; pub const O_CLOEXEC = 0x00400000; pub const O_ASYNC = 0x0040; pub const O_DIRECT = 0x00080000; pub const O_LARGEFILE = 0; pub const O_NOATIME = 0; pub const O_PATH = 0; pub const O_TMPFILE = 0; pub const O_NDELAY = O_NONBLOCK; pub const F_DUPFD = 0; pub const F_GETFD = 1; pub const F_SETFD = 2; pub const F_GETFL = 3; pub const F_SETFL = 4; pub const F_GETOWN = 5; pub const F_SETOWN = 6; pub const F_GETLK = 7; pub const F_SETLK = 8; pub const F_SETLKW = 9; pub const SEEK_SET = 0; pub const SEEK_CUR = 1; pub const SEEK_END = 2; pub const SIG_BLOCK = 1; pub const SIG_UNBLOCK = 2; pub const SIG_SETMASK = 3; pub const SOCK_STREAM = 1; pub const SOCK_DGRAM = 2; pub const SOCK_RAW = 3; pub const SOCK_RDM = 4; pub const SOCK_SEQPACKET = 5; pub const SOCK_CLOEXEC = 0x10000000; pub const SOCK_NONBLOCK = 0x20000000; pub const PROTO_ip = 0; pub const PROTO_icmp = 1; pub const PROTO_igmp = 2; pub const PROTO_ggp = 3; pub const PROTO_ipencap = 4; pub const PROTO_tcp = 6; pub const PROTO_egp = 8; pub const PROTO_pup = 12; pub const PROTO_udp = 17; pub const PROTO_xns_idp = 22; pub const PROTO_iso_tp4 = 29; pub const PROTO_ipv6 = 41; pub const PROTO_ipv6_route = 43; pub const PROTO_ipv6_frag = 44; pub const PROTO_rsvp = 46; pub const PROTO_gre = 47; pub const PROTO_esp = 50; pub const PROTO_ah = 51; pub const PROTO_ipv6_icmp = 58; pub const PROTO_ipv6_nonxt = 59; pub const PROTO_ipv6_opts = 60; pub const PROTO_encap = 98; pub const PROTO_pim = 103; pub const PROTO_raw = 255; pub const PF_UNSPEC = 0; pub const PF_LOCAL = 1; pub const PF_UNIX = PF_LOCAL; pub const PF_FILE = PF_LOCAL; pub const PF_INET = 2; pub const PF_APPLETALK = 16; pub const PF_INET6 = 24; pub const PF_DECnet = 12; pub const PF_KEY = 29; pub const PF_ROUTE = 34; pub const PF_SNA = 11; pub const PF_MPLS = 33; pub const PF_CAN = 35; pub const PF_BLUETOOTH = 31; pub const PF_ISDN = 26; pub const PF_MAX = 37; pub const AF_UNSPEC = PF_UNSPEC; pub const AF_LOCAL = PF_LOCAL; pub const AF_UNIX = AF_LOCAL; pub const AF_FILE = AF_LOCAL; pub const AF_INET = PF_INET; pub const AF_APPLETALK = PF_APPLETALK; pub const AF_INET6 = PF_INET6; pub const AF_KEY = PF_KEY; pub const AF_ROUTE = PF_ROUTE; pub const AF_SNA = PF_SNA; pub const AF_MPLS = PF_MPLS; pub const AF_CAN = PF_CAN; pub const AF_BLUETOOTH = PF_BLUETOOTH; pub const AF_ISDN = PF_ISDN; pub const AF_MAX = PF_MAX; pub const DT_UNKNOWN = 0; pub const DT_FIFO = 1; pub const DT_CHR = 2; pub const DT_DIR = 4; pub const DT_BLK = 6; pub const DT_REG = 8; pub const DT_LNK = 10; pub const DT_SOCK = 12; pub const DT_WHT = 14; /// add event to kq (implies enable) pub const EV_ADD = 0x0001; /// delete event from kq pub const EV_DELETE = 0x0002; /// enable event pub const EV_ENABLE = 0x0004; /// disable event (not reported) pub const EV_DISABLE = 0x0008; /// only report one occurrence pub const EV_ONESHOT = 0x0010; /// clear event state after reporting pub const EV_CLEAR = 0x0020; /// force immediate event output /// ... with or without EV_ERROR /// ... use KEVENT_FLAG_ERROR_EVENTS /// on syscalls supporting flags pub const EV_RECEIPT = 0x0040; /// disable event after reporting pub const EV_DISPATCH = 0x0080; pub const EVFILT_READ = 0; pub const EVFILT_WRITE = 1; /// attached to aio requests pub const EVFILT_AIO = 2; /// attached to vnodes pub const EVFILT_VNODE = 3; /// attached to struct proc pub const EVFILT_PROC = 4; /// attached to struct proc pub const EVFILT_SIGNAL = 5; /// timers pub const EVFILT_TIMER = 6; /// Filesystem events pub const EVFILT_FS = 7; /// On input, NOTE_TRIGGER causes the event to be triggered for output. pub const NOTE_TRIGGER = 0x08000000; /// low water mark pub const NOTE_LOWAT = 0x00000001; /// vnode was removed pub const NOTE_DELETE = 0x00000001; /// data contents changed pub const NOTE_WRITE = 0x00000002; /// size increased pub const NOTE_EXTEND = 0x00000004; /// attributes changed pub const NOTE_ATTRIB = 0x00000008; /// link count changed pub const NOTE_LINK = 0x00000010; /// vnode was renamed pub const NOTE_RENAME = 0x00000020; /// vnode access was revoked pub const NOTE_REVOKE = 0x00000040; /// process exited pub const NOTE_EXIT = 0x80000000; /// process forked pub const NOTE_FORK = 0x40000000; /// process exec'd pub const NOTE_EXEC = 0x20000000; /// mask for signal & exit status pub const NOTE_PDATAMASK = 0x000fffff; pub const NOTE_PCTRLMASK = 0xf0000000; pub const TIOCCBRK = 0x2000747a; pub const TIOCCDTR = 0x20007478; pub const TIOCCONS = 0x80047462; pub const TIOCDCDTIMESTAMP = 0x40107458; pub const TIOCDRAIN = 0x2000745e; pub const TIOCEXCL = 0x2000740d; pub const TIOCEXT = 0x80047460; pub const TIOCFLAG_CDTRCTS = 0x10; pub const TIOCFLAG_CLOCAL = 0x2; pub const TIOCFLAG_CRTSCTS = 0x4; pub const TIOCFLAG_MDMBUF = 0x8; pub const TIOCFLAG_SOFTCAR = 0x1; pub const TIOCFLUSH = 0x80047410; pub const TIOCGETA = 0x402c7413; pub const TIOCGETD = 0x4004741a; pub const TIOCGFLAGS = 0x4004745d; pub const TIOCGLINED = 0x40207442; pub const TIOCGPGRP = 0x40047477; pub const TIOCGQSIZE = 0x40047481; pub const TIOCGRANTPT = 0x20007447; pub const TIOCGSID = 0x40047463; pub const TIOCGSIZE = 0x40087468; pub const TIOCGWINSZ = 0x40087468; pub const TIOCMBIC = 0x8004746b; pub const TIOCMBIS = 0x8004746c; pub const TIOCMGET = 0x4004746a; pub const TIOCMSET = 0x8004746d; pub const TIOCM_CAR = 0x40; pub const TIOCM_CD = 0x40; pub const TIOCM_CTS = 0x20; pub const TIOCM_DSR = 0x100; pub const TIOCM_DTR = 0x2; pub const TIOCM_LE = 0x1; pub const TIOCM_RI = 0x80; pub const TIOCM_RNG = 0x80; pub const TIOCM_RTS = 0x4; pub const TIOCM_SR = 0x10; pub const TIOCM_ST = 0x8; pub const TIOCNOTTY = 0x20007471; pub const TIOCNXCL = 0x2000740e; pub const TIOCOUTQ = 0x40047473; pub const TIOCPKT = 0x80047470; pub const TIOCPKT_DATA = 0x0; pub const TIOCPKT_DOSTOP = 0x20; pub const TIOCPKT_FLUSHREAD = 0x1; pub const TIOCPKT_FLUSHWRITE = 0x2; pub const TIOCPKT_IOCTL = 0x40; pub const TIOCPKT_NOSTOP = 0x10; pub const TIOCPKT_START = 0x8; pub const TIOCPKT_STOP = 0x4; pub const TIOCPTMGET = 0x40287446; pub const TIOCPTSNAME = 0x40287448; pub const TIOCRCVFRAME = 0x80087445; pub const TIOCREMOTE = 0x80047469; pub const TIOCSBRK = 0x2000747b; pub const TIOCSCTTY = 0x20007461; pub const TIOCSDTR = 0x20007479; pub const TIOCSETA = 0x802c7414; pub const TIOCSETAF = 0x802c7416; pub const TIOCSETAW = 0x802c7415; pub const TIOCSETD = 0x8004741b; pub const TIOCSFLAGS = 0x8004745c; pub const TIOCSIG = 0x2000745f; pub const TIOCSLINED = 0x80207443; pub const TIOCSPGRP = 0x80047476; pub const TIOCSQSIZE = 0x80047480; pub const TIOCSSIZE = 0x80087467; pub const TIOCSTART = 0x2000746e; pub const TIOCSTAT = 0x80047465; pub const TIOCSTI = 0x80017472; pub const TIOCSTOP = 0x2000746f; pub const TIOCSWINSZ = 0x80087467; pub const TIOCUCNTL = 0x80047466; pub const TIOCXMTFRAME = 0x80087444; pub const sockaddr = c.sockaddr; pub const sockaddr_in = c.sockaddr_in; pub const sockaddr_in6 = c.sockaddr_in6; fn unsigned(s: i32) u32 { return @bitCast(u32, s); } fn signed(s: u32) i32 { return @bitCast(i32, s); } pub fn WEXITSTATUS(s: i32) i32 { return signed((unsigned(s) >> 8) & 0xff); } pub fn WTERMSIG(s: i32) i32 { return signed(unsigned(s) & 0x7f); } pub fn WSTOPSIG(s: i32) i32 { return WEXITSTATUS(s); } pub fn WIFEXITED(s: i32) bool { return WTERMSIG(s) == 0; } pub fn WIFCONTINUED(s: i32) bool { return ((s & 0x7f) == 0xffff); } pub fn WIFSTOPPED(s: i32) bool { return ((s & 0x7f != 0x7f) and !WIFCONTINUED(s)); } pub fn WIFSIGNALED(s: i32) bool { return !WIFSTOPPED(s) and !WIFCONTINUED(s) and !WIFEXITED(s); } pub const winsize = extern struct { ws_row: u16, ws_col: u16, ws_xpixel: u16, ws_ypixel: u16, }; /// Get the errno from a syscall return value, or 0 for no error. pub fn getErrno(r: usize) usize { const signed_r = @bitCast(isize, r); return if (signed_r > -4096 and signed_r < 0) @intCast(usize, -signed_r) else 0; } pub fn dup2(old: i32, new: i32) usize { return errnoWrap(c.dup2(old, new)); } pub fn chdir(path: [*]const u8) usize { return errnoWrap(c.chdir(path)); } pub fn execve(path: [*]const u8, argv: [*]const ?[*]const u8, envp: [*]const ?[*]const u8) usize { return errnoWrap(c.execve(path, argv, envp)); } pub fn fork() usize { return errnoWrap(c.fork()); } pub fn access(path: [*]const u8, mode: u32) usize { return errnoWrap(c.access(path, mode)); } pub fn getcwd(buf: [*]u8, size: usize) usize { return if (c.getcwd(buf, size) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } pub fn getdents(fd: i32, dirp: [*]u8, count: usize) usize { return errnoWrap(@bitCast(isize, c.getdents(fd, drip, count))); } pub fn getdirentries(fd: i32, buf_ptr: [*]u8, buf_len: usize, basep: *i64) usize { return errnoWrap(@bitCast(isize, c.getdirentries(fd, buf_ptr, buf_len, basep))); } pub fn realpath(noalias filename: [*]const u8, noalias resolved_name: [*]u8) usize { return if (c.realpath(filename, resolved_name) == null) @bitCast(usize, -isize(c._errno().*)) else 0; } pub fn isatty(fd: i32) bool { return c.isatty(fd) != 0; } pub fn readlink(noalias path: [*]const u8, noalias buf_ptr: [*]u8, buf_len: usize) usize { return errnoWrap(c.readlink(path, buf_ptr, buf_len)); } pub fn mkdir(path: [*]const u8, mode: u32) usize { return errnoWrap(c.mkdir(path, mode)); } pub fn mmap(address: ?[*]u8, length: usize, prot: usize, flags: u32, fd: i32, offset: isize) usize { const ptr_result = c.mmap( @ptrCast(?*c_void, address), length, @bitCast(c_int, @intCast(c_uint, prot)), @bitCast(c_int, c_uint(flags)), fd, offset, ); const isize_result = @bitCast(isize, @ptrToInt(ptr_result)); return errnoWrap(isize_result); } pub fn munmap(address: usize, length: usize) usize { return errnoWrap(c.munmap(@intToPtr(*c_void, address), length)); } pub fn read(fd: i32, buf: [*]u8, nbyte: usize) usize { return errnoWrap(c.read(fd, @ptrCast(*c_void, buf), nbyte)); } pub fn rmdir(path: [*]const u8) usize { return errnoWrap(c.rmdir(path)); } pub fn symlink(existing: [*]const u8, new: [*]const u8) usize { return errnoWrap(c.symlink(existing, new)); } pub fn pread(fd: i32, buf: [*]u8, nbyte: usize, offset: u64) usize { return errnoWrap(c.pread(fd, @ptrCast(*c_void, buf), nbyte, offset)); } pub fn preadv(fd: i32, iov: [*]const iovec, count: usize, offset: usize) usize { return errnoWrap(c.preadv(fd, @ptrCast(*const c_void, iov), @intCast(c_int, count), offset)); } pub fn pipe(fd: *[2]i32) usize { return pipe2(fd, 0); } pub fn pipe2(fd: *[2]i32, flags: u32) usize { comptime assert(i32.bit_count == c_int.bit_count); return errnoWrap(c.pipe2(@ptrCast(*[2]c_int, fd), flags)); } pub fn write(fd: i32, buf: [*]const u8, nbyte: usize) usize { return errnoWrap(c.write(fd, @ptrCast(*const c_void, buf), nbyte)); } pub fn pwrite(fd: i32, buf: [*]const u8, nbyte: usize, offset: u64) usize { return errnoWrap(c.pwrite(fd, @ptrCast(*const c_void, buf), nbyte, offset)); } pub fn pwritev(fd: i32, iov: [*]const iovec_const, count: usize, offset: usize) usize { return errnoWrap(c.pwritev(fd, @ptrCast(*const c_void, iov), @intCast(c_int, count), offset)); } pub fn rename(old: [*]const u8, new: [*]const u8) usize { return errnoWrap(c.rename(old, new)); } pub fn open(path: [*]const u8, flags: u32, mode: usize) usize { return errnoWrap(c.open(path, @bitCast(c_int, flags), mode)); } pub fn create(path: [*]const u8, perm: usize) usize { return arch.syscall2(SYS_creat, @ptrToInt(path), perm); } pub fn openat(dirfd: i32, path: [*]const u8, flags: usize, mode: usize) usize { return errnoWrap(c.openat(@bitCast(usize, isize(dirfd)), @ptrToInt(path), flags, mode)); } pub fn close(fd: i32) usize { return errnoWrap(c.close(fd)); } pub fn lseek(fd: i32, offset: isize, whence: c_int) usize { return errnoWrap(c.lseek(fd, offset, whence)); } pub fn exit(code: i32) noreturn { c.exit(code); } pub fn kill(pid: i32, sig: i32) usize { return errnoWrap(c.kill(pid, sig)); } pub fn unlink(path: [*]const u8) usize { return errnoWrap(c.unlink(path)); } pub fn waitpid(pid: i32, status: *i32, options: u32) usize { comptime assert(i32.bit_count == c_int.bit_count); return errnoWrap(c.waitpid(pid, @ptrCast(*c_int, status), @bitCast(c_int, options))); } pub fn nanosleep(req: *const timespec, rem: ?*timespec) usize { return errnoWrap(c.nanosleep(req, rem)); } pub fn clock_gettime(clk_id: i32, tp: *timespec) usize { return errnoWrap(c.clock_gettime(clk_id, tp)); } pub fn clock_getres(clk_id: i32, tp: *timespec) usize { return errnoWrap(c.clock_getres(clk_id, tp)); } pub fn setuid(uid: u32) usize { return errnoWrap(c.setuid(uid)); } pub fn setgid(gid: u32) usize { return errnoWrap(c.setgid(gid)); } pub fn setreuid(ruid: u32, euid: u32) usize { return errnoWrap(c.setreuid(ruid, euid)); } pub fn setregid(rgid: u32, egid: u32) usize { return errnoWrap(c.setregid(rgid, egid)); } const NSIG = 32; pub const SIG_ERR = @intToPtr(extern fn (i32) void, maxInt(usize)); pub const SIG_DFL = @intToPtr(extern fn (i32) void, 0); pub const SIG_IGN = @intToPtr(extern fn (i32) void, 1); /// Renamed from `sigaction` to `Sigaction` to avoid conflict with the syscall. pub const Sigaction = extern struct { /// signal handler __sigaction_u: extern union { __sa_handler: extern fn (i32) void, __sa_sigaction: extern fn (i32, *__siginfo, usize) void, }, /// see signal options sa_flags: u32, /// signal mask to apply sa_mask: sigset_t, }; pub const _SIG_WORDS = 4; pub const _SIG_MAXSIG = 128; pub inline fn _SIG_IDX(sig: usize) usize { return sig - 1; } pub inline fn _SIG_WORD(sig: usize) usize { return_SIG_IDX(sig) >> 5; } pub inline fn _SIG_BIT(sig: usize) usize { return 1 << (_SIG_IDX(sig) & 31); } pub inline fn _SIG_VALID(sig: usize) usize { return sig <= _SIG_MAXSIG and sig > 0; } pub const sigset_t = extern struct { __bits: [_SIG_WORDS]u32, }; pub fn raise(sig: i32) usize { return errnoWrap(c.raise(sig)); } pub const Stat = c.Stat; pub const dirent = c.dirent; pub const timespec = c.timespec; pub fn fstat(fd: i32, buf: *c.Stat) usize { return errnoWrap(c.fstat(fd, buf)); } pub const iovec = extern struct { iov_base: [*]u8, iov_len: usize, }; pub const iovec_const = extern struct { iov_base: [*]const u8, iov_len: usize, }; // TODO avoid libc dependency pub fn kqueue() usize { return errnoWrap(c.kqueue()); } // TODO avoid libc dependency pub fn kevent(kq: i32, changelist: []const Kevent, eventlist: []Kevent, timeout: ?*const timespec) usize { return errnoWrap(c.kevent( kq, changelist.ptr, @intCast(c_int, changelist.len), eventlist.ptr, @intCast(c_int, eventlist.len), timeout, )); } // TODO avoid libc dependency pub fn sysctl(name: [*]c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) usize { return errnoWrap(c.sysctl(name, namelen, oldp, oldlenp, newp, newlen)); } // TODO avoid libc dependency pub fn sysctlbyname(name: [*]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) usize { return errnoWrap(c.sysctlbyname(name, oldp, oldlenp, newp, newlen)); } // TODO avoid libc dependency pub fn sysctlnametomib(name: [*]const u8, mibp: ?*c_int, sizep: ?*usize) usize { return errnoWrap(c.sysctlnametomib(name, wibp, sizep)); } // TODO avoid libc dependency /// Takes the return value from a syscall and formats it back in the way /// that the kernel represents it to libc. Errno was a mistake, let's make /// it go away forever. fn errnoWrap(value: isize) usize { return @bitCast(usize, if (value == -1) -isize(c._errno().*) else value); }
std/os/netbsd/index.zig
const std = @import("std"); const Impulse = @import("notes.zig").Impulse; const Notes = @import("notes.zig").Notes; const MyNoteParams = struct { note_on: bool, }; test "PolyphonyDispatcher: 5 note-ons with 3 slots" { const iap = Notes(MyNoteParams).ImpulsesAndParamses { .impulses = &[_]Impulse { .{ .frame = 100, .note_id = 1, .event_id = 1 }, .{ .frame = 200, .note_id = 2, .event_id = 2 }, .{ .frame = 300, .note_id = 3, .event_id = 3 }, .{ .frame = 400, .note_id = 4, .event_id = 4 }, .{ .frame = 500, .note_id = 5, .event_id = 5 }, }, .paramses = &[_]MyNoteParams { .{ .note_on = true }, .{ .note_on = true }, .{ .note_on = true }, .{ .note_on = true }, .{ .note_on = true }, }, }; var pd = Notes(MyNoteParams).PolyphonyDispatcher(3).init(); const result = pd.dispatch(iap); std.testing.expectEqual(@as(usize, 1), result[0].impulses[0].note_id); std.testing.expectEqual(@as(usize, 2), result[1].impulses[0].note_id); std.testing.expectEqual(@as(usize, 3), result[2].impulses[0].note_id); std.testing.expectEqual(@as(usize, 4), result[0].impulses[1].note_id); std.testing.expectEqual(@as(usize, 5), result[1].impulses[1].note_id); std.testing.expectEqual(@as(usize, 2), result[0].impulses.len); std.testing.expectEqual(@as(usize, 2), result[1].impulses.len); std.testing.expectEqual(@as(usize, 1), result[2].impulses.len); } test "PolyphonyDispatcher: single note on and off" { const iap = Notes(MyNoteParams).ImpulsesAndParamses { .impulses = &[_]Impulse { .{ .frame = 100, .note_id = 1, .event_id = 1 }, .{ .frame = 200, .note_id = 1, .event_id = 2 }, .{ .frame = 300, .note_id = 2, .event_id = 3 }, .{ .frame = 400, .note_id = 2, .event_id = 4 }, .{ .frame = 500, .note_id = 3, .event_id = 5 }, }, .paramses = &[_]MyNoteParams { .{ .note_on = true }, .{ .note_on = false }, .{ .note_on = true }, .{ .note_on = false }, .{ .note_on = true }, }, }; var pd = Notes(MyNoteParams).PolyphonyDispatcher(3).init(); const result = pd.dispatch(iap); std.testing.expectEqual(@as(usize, 1), result[0].impulses[0].note_id); std.testing.expectEqual(@as(usize, 1), result[0].impulses[1].note_id); std.testing.expectEqual(@as(usize, 2), result[1].impulses[0].note_id); std.testing.expectEqual(@as(usize, 2), result[1].impulses[1].note_id); std.testing.expectEqual(@as(usize, 3), result[2].impulses[0].note_id); std.testing.expectEqual(@as(usize, 2), result[0].impulses.len); std.testing.expectEqual(@as(usize, 2), result[1].impulses.len); std.testing.expectEqual(@as(usize, 1), result[2].impulses.len); } test "PolyphonyDispatcher: reuse least recently released slot" { const iap = Notes(MyNoteParams).ImpulsesAndParamses { .impulses = &[_]Impulse { .{ .frame = 100, .note_id = 1, .event_id = 1 }, .{ .frame = 200, .note_id = 2, .event_id = 2 }, .{ .frame = 300, .note_id = 3, .event_id = 3 }, .{ .frame = 400, .note_id = 3, .event_id = 4 }, .{ .frame = 500, .note_id = 2, .event_id = 5 }, .{ .frame = 600, .note_id = 1, .event_id = 6 }, .{ .frame = 700, .note_id = 4, .event_id = 7 }, }, .paramses = &[_]MyNoteParams { .{ .note_on = true }, .{ .note_on = true }, .{ .note_on = true }, .{ .note_on = false }, .{ .note_on = false }, .{ .note_on = false }, .{ .note_on = true }, }, }; var pd = Notes(MyNoteParams).PolyphonyDispatcher(3).init(); const result = pd.dispatch(iap); std.testing.expectEqual(@as(usize, 1), result[0].impulses[0].note_id); std.testing.expectEqual(@as(usize, 2), result[1].impulses[0].note_id); std.testing.expectEqual(@as(usize, 3), result[2].impulses[0].note_id); std.testing.expectEqual(@as(usize, 3), result[2].impulses[1].note_id); std.testing.expectEqual(@as(usize, 2), result[1].impulses[1].note_id); std.testing.expectEqual(@as(usize, 1), result[0].impulses[1].note_id); // slot 0 is the least recent note-on. // slot 2 is the least recent note-off. this is what we want std.testing.expectEqual(@as(usize, 4), result[2].impulses[2].note_id); std.testing.expectEqual(@as(usize, 2), result[0].impulses.len); std.testing.expectEqual(@as(usize, 2), result[1].impulses.len); std.testing.expectEqual(@as(usize, 3), result[2].impulses.len); }
src/zang/notes_test.zig
const std = @import("std"); pub fn Parser(comptime num_columns: usize) type { return struct { pub const Note = union(enum) { idle: void, freq: f32, off: void, }; pub const Token = union(enum) { word: []const u8, number: f32, notes: [num_columns]Note, fn isWord(token: Token, word: []const u8) bool { return switch (token) { .word => |s| std.mem.eql(u8, word, s), else => false, }; } }; a4: f32, contents: []const u8, index: usize, line_index: usize, fn parseNote(parser: *@This()) ?f32 { if (parser.index + 3 > parser.contents.len) { return null; } const letter = parser.contents[parser.index]; const modifier = parser.contents[parser.index + 1]; const octave = parser.contents[parser.index + 2]; const offset = if (octave >= '0' and octave <= '9') @intCast(i32, octave - '0') * 12 - 57 else return null; const semitone: i32 = blk: { if (letter == 'C' and modifier == '-') break :blk 0; if (letter == 'C' and modifier == '#') break :blk 1; if (letter == 'D' and modifier == '-') break :blk 2; if (letter == 'D' and modifier == '#') break :blk 3; if (letter == 'E' and modifier == '-') break :blk 4; if (letter == 'F' and modifier == '-') break :blk 5; if (letter == 'F' and modifier == '#') break :blk 6; if (letter == 'G' and modifier == '-') break :blk 7; if (letter == 'G' and modifier == '#') break :blk 8; if (letter == 'A' and modifier == '-') break :blk 9; if (letter == 'A' and modifier == '#') break :blk 10; if (letter == 'B' and modifier == '-') break :blk 11; return null; }; parser.index += 3; const exp = @intToFloat(f32, offset + semitone) / 12.0; return parser.a4 * std.math.pow(f32, 2.0, exp); } pub fn eat(parser: *@This(), prefix: []const u8) bool { const contents = parser.contents[parser.index..]; if (!std.mem.startsWith(u8, contents, prefix)) { return false; } parser.index += prefix.len; return true; } pub fn parseToken(parser: *@This()) !?Token { while (true) { if (parser.eat(" ")) { // pass } else if (parser.eat("\n")) { parser.line_index += 1; } else if (parser.eat("#")) { const contents = parser.contents[parser.index..]; if (std.mem.indexOfScalar(u8, contents, '\n')) |pos| { parser.line_index += 1; parser.index += pos + 1; } else { parser.index = parser.contents.len; } } else { break; } } if (parser.index >= parser.contents.len) { return null; } const ch = parser.contents[parser.index]; if (ch == '|') { parser.index += 1; var notes = [1]Note{.idle} ** num_columns; var col: usize = 0; while (true) : (col += 1) { if (col >= num_columns) { return error.SyntaxError; } if (parseNote(parser)) |freq| { notes[col] = .{ .freq = freq }; } else if (parser.eat("off")) { notes[col] = .off; } else if (parser.eat(" ")) { // pass } else { break; } if (parser.index < parser.contents.len and (parser.contents[parser.index] == ' ' or parser.contents[parser.index] == '|')) { parser.index += 1; } else { break; } } if (parser.index < parser.contents.len) { if (parser.contents[parser.index] == '\n') { parser.line_index += 1; parser.index += 1; } else { return error.SyntaxError; } } return Token { .notes = notes }; } if ( (ch >= 'a' and ch <= 'z') or (ch >= 'A' and ch <= 'Z') or ch == '_' ) { const start = parser.index; parser.index += 1; while (parser.index < parser.contents.len) { const ch2 = parser.contents[parser.index]; if ( (ch2 >= 'a' and ch2 <= 'z') or (ch2 >= 'A' and ch2 <= 'Z') or (ch2 >= '0' and ch2 <= '9') or ch2 == '_' ) { parser.index += 1; } else { break; } } return Token { .word = parser.contents[start..parser.index] }; } if (ch >= '0' and ch <= '9') { const start = parser.index; var dot = false; parser.index += 1; while (parser.index < parser.contents.len) { const ch2 = parser.contents[parser.index]; if (ch2 == '.') { if (dot) { break; } else { dot = true; parser.index += 1; } } else if (ch2 >= '0' and ch2 <= '9') { parser.index += 1; } else { break; } } const number = try std.fmt.parseFloat(f32, parser.contents[start..parser.index]); return Token { .number = number }; } return error.SyntaxError; } fn requireToken(parser: *@This()) !Token { return (try parser.parseToken()) orelse error.UnexpectedEof; } fn requireNumber(parser: *@This()) !f32 { return switch (try parser.requireToken()) { .number => |n| n, else => error.ExpectedNumber, }; } }; }
examples/common/songparse1.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../input/day12.txt"); const Facing = enum(u2) { East, South, West, North, }; pub fn main() !void { var east: isize = 0; var north: isize = 0; var facing: Facing = .East; var lines = std.mem.tokenize(input, "\r\n"); while (lines.next()) |line| { const num = try std.fmt.parseUnsigned(usize, line[1..], 10); const inum = @intCast(isize, num); switch (line[0]) { 'N' => north += inum, 'S' => north -= inum, 'E' => east += inum, 'W' => east -= inum, 'L' => facing = @intToEnum(Facing, @enumToInt(facing) -% @intCast(u2, num / 90)), 'R' => facing = @intToEnum(Facing, @enumToInt(facing) +% @intCast(u2, num / 90)), 'F' => { switch (facing) { .North => north += inum, .South => north -= inum, .East => east += inum, .West => east -= inum, } }, else => unreachable } } print("part1: {}\n", .{(try std.math.absInt(north)) + (try std.math.absInt(east))}); east = 0; north = 0; var w_east: isize = 10; var w_north: isize = 1; lines.index = 0; while (lines.next()) |line| { const num = try std.fmt.parseUnsigned(usize, line[1..], 10); const inum = @intCast(isize, num); switch (line[0]) { 'N' => w_north += inum, 'S' => w_north -= inum, 'E' => w_east += inum, 'W' => w_east -= inum, 'L' => { var i: usize = 0; while (i < num) : (i += 90) { var tmp = w_east; w_east = -w_north; w_north = tmp; } }, 'R' => { var i: usize = 0; while (i < num) : (i += 90) { var tmp = w_east; w_east = w_north; w_north = -tmp; } }, 'F' => { east += inum * w_east; north += inum * w_north; }, else => unreachable } } print("part2: {}\n", .{(try std.math.absInt(north)) + (try std.math.absInt(east))}); } const example = \\F10 \\N3 \\F7 \\R90 \\F11 ;
src/day12.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; const print = std.debug.print; const input = @embedFile("../input/day09.txt"); const input_preamble_len = 25; fn loadNumbers(allocator: *Allocator, string: []const u8) !ArrayList(u64) { var numbers = ArrayList(u64).init(allocator); var tokens = std.mem.tokenize(string, "\r\n"); while (tokens.next()) |token| { try numbers.append(try std.fmt.parseUnsigned(u64, token, 10)); } return numbers; } fn checkPreamble(preamble: []u64, sum: u64) bool { var i: usize = 0; while (i < preamble.len - 1) : (i += 1) { var j: usize = i + 1; while (j < preamble.len) : (j += 1) { if (preamble[i] + preamble[j] == sum) { return true; } } } return false; } fn findInvalid(numbers: []u64, preamble_len: usize) usize { for (numbers[preamble_len..]) |num, i| { if (!checkPreamble(numbers[i..i + preamble_len], num)) { return preamble_len + i; } } return 0; } fn findRange(numbers: []u64, invalid: u64) u64 { var i: usize = 0; while (i < numbers.len - 1) : (i += 1) { var sum = numbers[i]; var smallest = numbers[i]; var largest = numbers[i]; var j: usize = i + 1; while (sum < invalid) : (j += 1) { sum += numbers[j]; smallest = std.math.min(smallest, numbers[j]); largest = std.math.max(largest, numbers[j]); } if (sum == invalid) { return smallest + largest; } } return 0; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; var numbers = try loadNumbers(allocator, input); defer numbers.deinit(); const i = findInvalid(numbers.items, input_preamble_len); print("part1: {}\n", .{numbers.items[i]}); print("part2: {}\n", .{findRange(numbers.items[0..i], numbers.items[i])}); } const example_preamble_len = 5; const example = \\35 \\20 \\15 \\25 \\47 \\40 \\62 \\55 \\65 \\95 \\102 \\117 \\150 \\182 \\127 \\219 \\299 \\277 \\309 \\576 ;
src/day09.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const StringHashMap = std.StringHashMap; const BufSet = std.BufSet; const Buffer = std.Buffer; const fixedBufferStream = std.io.fixedBufferStream; const assert = std.debug.assert; const OrbitMapParseError = error{FormatError}; const OrbitMap = struct { alloc: *Allocator, map: StringHashMap(BufSet), const Self = @This(); pub fn init(allocator: *Allocator) Self { return Self{ .alloc = allocator, .map = StringHashMap(BufSet).init(alloc), }; } pub fn fromStream(allocator: *Allocator, stream: anytype) !Self { var map = StringHashMap(BufSet).init(allocator); var result = Self{ .alloc = allocator, .map = map, }; while (stream.readUntilDelimiterAlloc(allocator, '\n', 1024)) |line| { var iter = std.mem.split(line, ")"); const orbitee = iter.next() orelse return error.FormatError; const orbiter = iter.next() orelse return error.FormatError; try result.insertOrbit(orbitee, orbiter); } else |e| switch (e) { error.EndOfStream => {}, else => return e, } return result; } pub fn insertOrbit(self: *Self, orbitee: []const u8, orbiter: []const u8) !void { if (self.map.get(orbitee) == null) { _ = try self.map.put(orbitee, BufSet.init(self.alloc)); } if (self.map.get(orbiter) == null) { _ = try self.map.put(orbiter, BufSet.init(self.alloc)); } try self.map.get(orbitee).?.value.put(orbiter); } pub fn count(self: *Self, body: []const u8, orbits: usize) usize { var result: usize = orbits; if (self.map.get(body)) |kv| { var iter = kv.value.iterator(); while (iter.next()) |set_kv| { result += self.count(set_kv.key, orbits + 1); } } return result; } }; test "count orbits" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var mem_stream = fixedBufferStream( \\COM)B \\B)C \\C)D \\D)E \\E)F \\B)G \\G)H \\D)I \\E)J \\J)K \\K)L \\ ); var reader = mem_stream.reader(); var orbit_map = try OrbitMap.fromStream(allocator, reader); assert(orbit_map.count("COM", 0) == 42); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); const input_file = try std.fs.cwd().openFile("input06.txt", .{}); var input_stream = input_file.reader(); var orbit_map = try OrbitMap.fromStream(allocator, input_stream); std.debug.warn("total orbits: {}\n", .{orbit_map.count("COM", 0)}); }
zig/06.zig
const std = @import("std"); const assert = std.debug.assert; const koino = @import("koino"); const MenuItem = struct { input_file_name: []const u8, output_file_name: []const u8, header: []const u8, }; const menu_items = [_]MenuItem{ MenuItem{ .input_file_name = "documentation/README.md", .output_file_name = "website/docs/language.htm", .header = "Language Reference", }, MenuItem{ .input_file_name = "documentation/standard-library.md", .output_file_name = "website/docs/standard-library.htm", .header = "Standard Library", }, MenuItem{ .input_file_name = "documentation/runtime-library.md", .output_file_name = "website/docs/runtime-library.htm", .header = "Runtime Library", }, MenuItem{ .input_file_name = "documentation/ir.md", .output_file_name = "website/docs/intermediate-language.htm", .header = "IR", }, MenuItem{ .input_file_name = "documentation/modules.md", .output_file_name = "website/docs/module-binary.htm", .header = "Module Format", }, }; pub fn main() !u8 { @setEvalBranchQuota(1500); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var args = try std.process.argsWithAllocator(allocator); args.deinit(); _ = args.next() orelse return 1; // exe name const version_name = args.next(); for (menu_items) |current_file, current_index| { const options = koino.Options{ .extensions = .{ .table = true, .autolink = true, .strikethrough = true, }, }; var infile = try std.fs.cwd().openFile(current_file.input_file_name, .{}); defer infile.close(); var markdown = try infile.reader().readAllAlloc(allocator, 1024 * 1024 * 1024); defer allocator.free(markdown); var output = try markdownToHtml(allocator, options, markdown); defer allocator.free(output); var outfile = try std.fs.cwd().createFile(current_file.output_file_name, .{}); defer outfile.close(); try outfile.writeAll( \\<!DOCTYPE html> \\<html lang="en"> \\ \\<head> \\ <meta charset="utf-8"> \\ <meta name="viewport" content="width=device-width, initial-scale=1"> \\ <title>LoLa Documentation</title> \\ <link rel="icon" \\ href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAgklEQVR4AWMYWuD7EllJIM4G4g4g5oIJ/odhOJ8wToOxSTXgNxDHoeiBMfA4+wGShjyYOCkG/IGqWQziEzYAoUAeiF9D5U+DxEg14DRU7jWIT5IBIOdCxf+A+CQZAAoopEB7QJwBCBwHiip8UYmRdrAlDpIMgApwQZNnNii5Dq0MBgCxxycBnwEd+wAAAABJRU5ErkJggg=="> \\ <link rel="stylesheet" href="../documentation.css" /> \\</head> \\ \\<body class="canvas"> \\ <div class="flex-main"> \\ <div class="flex-filler"></div> \\ <div class="flex-left sidebar"> \\ <nav> \\ <div class="logo"> \\ <img src="../img/logo.png" /> \\ </div> \\ <div id="sectPkgs" class=""> \\ <h2><span>Documents</span></h2> \\ <ul id="listPkgs" class="packages"> ); for (menu_items) |menu, i| { var is_current = (current_index == i); var current_class = if (is_current) @as([]const u8, "class=\"active\"") else ""; try outfile.writer().print( \\<li><a href="{s}" {s}>{s}</a></li> \\ , .{ std.fs.path.basename(menu.output_file_name), current_class, menu.header, }); } var version_name_str = @as(?[]const u8, version_name) orelse @as([]const u8, "development"); try outfile.writer().print( \\ </ul> \\ </div> \\ <div id="sectInfo" class=""> \\ <h2><span>LoLa Version</span></h2> \\ <p class="str" id="tdZigVer">{s}</p> \\ </div> \\ </nav> \\ </div> \\ <div class="flex-right"> \\ <div class="wrap"> \\ <section class="docs"> , .{ version_name_str, }); try outfile.writer().writeAll(output); try outfile.writeAll( \\ </section> \\ </div> \\ <div class="flex-filler"></div> \\ </div> \\ </div> \\</body> \\ \\</html> \\ ); } return 0; } fn markdownToHtmlInternal(resultAllocator: std.mem.Allocator, internalAllocator: std.mem.Allocator, options: koino.Options, markdown: []const u8) ![]u8 { var p = try koino.parser.Parser.init(internalAllocator, options); try p.feed(markdown); var doc = try p.finish(); p.deinit(); defer doc.deinit(); var buffer = std.ArrayList(u8).init(resultAllocator); defer buffer.deinit(); try koino.html.print(buffer.writer(), internalAllocator, p.options, doc); return buffer.toOwnedSlice(); } pub fn markdownToHtml(allocator: std.mem.Allocator, options: koino.Options, markdown: []const u8) ![]u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); return markdownToHtmlInternal(allocator, arena.allocator(), options, markdown); }
src/tools/render-md-page.zig
const std = @import("std"); pub const KeyboardError = error{ BadStartBit, BadStopBit, ParityError, UnknownKeyCode, }; pub const KeyboardLayout = enum { Uk105Key, Us104Key, Jis109Key, AzertyKey, Dvorak104Key, }; const Uk105KeyImpl = @import("keycode/layouts/uk105.zig"); const Us104KeyImpl = @import("keycode/layouts/us104.zig"); const Jis109KeyImpl = @import("keycode/layouts/jis109.zig"); const AzertyKeyImpl = @import("keycode/layouts/azerty.zig"); const Dvorak104KeyImpl = @import("keycode/layouts/dvorak104.zig"); pub const ScancodeSet = enum { ScancodeSet1, ScancodeSet2, }; const ScancodeSet1Impl = @import("keycode/scancodes/scancode_set1.zig"); const ScancodeSet2Impl = @import("keycode/scancodes/scancode_set2.zig"); pub const Keyboard = struct { register: u16 = 0, num_bits: u4 = 0, decode_state: DecodeState = .Start, handle_ctrl: HandleControl, modifiers: Modifiers = .{}, scancode_set: ScancodeSet, keyboard_layout: KeyboardLayout, /// Make a new Keyboard object with the given layout. pub fn init(scancode_set: ScancodeSet, keyboard_layout: KeyboardLayout, handle_ctrl: HandleControl) Keyboard { return .{ .handle_ctrl = handle_ctrl, .scancode_set = scancode_set, .keyboard_layout = keyboard_layout, }; } /// Change the Ctrl key mapping. pub fn setCtrlHandling(self: *Keyboard, new_value: HandleControl) void { self.handle_ctrl = new_value; } /// Get the current Ctrl key mapping. pub fn getCtrlHandling(self: *Keyboard) HandleControl { return self.handle_ctrl; } /// Clears the bit register. /// /// Call this when there is a timeout reading data from the keyboard. pub fn clear(self: *Keyboard) void { self.register = 0; self.num_bits = 0; self.decode_state = .Start; } /// Processes a 16-bit word from the keyboard. /// /// * The start bit (0) must be in bit 0. /// * The data octet must be in bits 1..8, with the LSB in bit 1 and the /// MSB in bit 8. /// * The parity bit must be in bit 9. /// * The stop bit (1) must be in bit 10. pub fn addWord(self: *Keyboard, word: u16) KeyboardError!?KeyEvent { return self.addByte(try checkWord(word)); } /// Processes an 8-bit byte from the keyboard. /// /// We assume the start, stop and parity bits have been processed and verified. pub fn addByte(self: *Keyboard, byte: u8) KeyboardError!?KeyEvent { return switch (self.scancode_set) { .ScancodeSet1 => ScancodeSet1Impl.advanceState(&self.decode_state, byte), .ScancodeSet2 => ScancodeSet2Impl.advanceState(&self.decode_state, byte), }; } /// Shift a bit into the register. /// /// Call this /or/ call `add_word` - don't call both. /// Until the last bit is added you get null returned. pub fn addBit(self: *Keyboard, bit: u1) KeyboardError!?KeyEvent { self.register |= @as(u16, bit) << self.num_bits; self.num_bits += 1; if (self.num_bits == KEYCODE_BITS) { const word = self.register; self.register = 0; self.num_bits = 0; return self.addWord(word); } else { return null; } } /// Processes a `KeyEvent` returned from `add_bit`, `add_byte` or `add_word` /// and produces a decoded key. /// /// For example, the KeyEvent for pressing the '5' key on your keyboard /// gives a DecodedKey of unicode character '5', unless the shift key is /// held in which case you get the unicode character '%'. pub fn processKeyevent(self: *Keyboard, ev: KeyEvent) ?DecodedKey { switch (ev.state) { .Up => { switch (ev.code) { .ShiftLeft => self.modifiers.lshift = false, .ShiftRight => self.modifiers.rshift = false, .ControlLeft => self.modifiers.lctrl = false, .ControlRight => self.modifiers.rctrl = false, .AltRight => self.modifiers.alt_gr = false, else => {}, } }, .Down => { switch (ev.code) { .ShiftLeft => self.modifiers.lshift = true, .ShiftRight => self.modifiers.rshift = true, .ControlLeft => self.modifiers.lctrl = true, .ControlRight => self.modifiers.rctrl = true, .AltRight => self.modifiers.alt_gr = true, .CapsLock => self.modifiers.capslock = !self.modifiers.capslock, .NumpadLock => self.modifiers.numlock = !self.modifiers.numlock, else => { return switch (self.keyboard_layout) { .Uk105Key => Uk105KeyImpl.mapKeycode(ev.code, self.modifiers, self.handle_ctrl), .Us104Key => Us104KeyImpl.mapKeycode(ev.code, self.modifiers, self.handle_ctrl), .Jis109Key => Jis109KeyImpl.mapKeycode(ev.code, self.modifiers, self.handle_ctrl), .AzertyKey => AzertyKeyImpl.mapKeycode(ev.code, self.modifiers, self.handle_ctrl), .Dvorak104Key => Dvorak104KeyImpl.mapKeycode(ev.code, self.modifiers, self.handle_ctrl), }; }, } }, } return null; } fn getBit(word: u16, offset: u4) bool { return ((word >> offset) & 0x0001) != 0; } fn hasEvenNumberOfBits(data: u8) bool { return @popCount(u8, data) % 2 == 0; } /// Check 11-bit word has 1 start bit, 1 stop bit and an odd parity bit. fn checkWord(word: u16) !u8 { if (getBit(word, 0)) return error.BadStartBit; if (!getBit(word, 10)) return error.BadStopBit; const data = @truncate(u8, (word >> 1)); // Needs odd parity if (hasEvenNumberOfBits(data) != getBit(word, 9)) { return error.ParityError; } return data; } comptime { std.testing.refAllDecls(@This()); } }; /// Keycodes that can be generated by a keyboard. pub const KeyCode = enum { AltLeft, AltRight, ArrowDown, ArrowLeft, ArrowRight, ArrowUp, BackSlash, Backspace, BackTick, BracketSquareLeft, BracketSquareRight, CapsLock, Comma, ControlLeft, ControlRight, Delete, End, Enter, Escape, Equals, F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, Fullstop, Home, Insert, Key1, Key2, Key3, Key4, Key5, Key6, Key7, Key8, Key9, Key0, Menus, Minus, Numpad0, Numpad1, Numpad2, Numpad3, Numpad4, Numpad5, Numpad6, Numpad7, Numpad8, Numpad9, NumpadEnter, NumpadLock, NumpadSlash, NumpadStar, NumpadMinus, NumpadPeriod, NumpadPlus, PageDown, PageUp, PauseBreak, PrintScreen, ScrollLock, SemiColon, ShiftLeft, ShiftRight, Slash, Spacebar, Tab, Quote, WindowsLeft, WindowsRight, A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, /// Not on US keyboards HashTilde, // Scan code set 1 unique codes PrevTrack, NextTrack, Mute, Calculator, Play, Stop, VolumeDown, VolumeUp, WWWHome, // Sent when the keyboard boots PowerOnTestOk, }; pub const KeyState = enum { Up, Down, }; /// Options for how we can handle what happens when the Ctrl key is held down and a letter is pressed. pub const HandleControl = enum { /// If either Ctrl key is held down, convert the letters A through Z into /// Unicode chars U+0001 through U+001A. If the Ctrl keys are not held /// down, letters go through normally. MapLettersToUnicode, /// Don't do anything special - send through the Ctrl key up/down events, /// and leave the letters as letters. Ignore, }; pub const KeyEvent = struct { code: KeyCode, state: KeyState, }; pub const Modifiers = struct { lshift: bool = false, rshift: bool = false, lctrl: bool = false, rctrl: bool = false, numlock: bool = true, capslock: bool = false, alt_gr: bool = false, pub inline fn isShifted(modifiers: Modifiers) bool { return modifiers.lshift or modifiers.rshift; } pub inline fn isCtrl(modifiers: Modifiers) bool { return modifiers.lctrl or modifiers.rctrl; } pub inline fn isCaps(modifiers: Modifiers) bool { return modifiers.isShifted() != modifiers.capslock; } comptime { std.testing.refAllDecls(@This()); } }; pub const DecodedKeyType = enum { RawKey, Unicode, }; pub const DecodedKey = union(DecodedKeyType) { RawKey: KeyCode, Unicode: []const u8, }; pub const DecodeState = enum { Start, Extended, Release, ExtendedRelease, }; const KEYCODE_BITS: u8 = 11; comptime { std.testing.refAllDecls(@This()); } test "f9" { var keyboard = Keyboard.init(.ScancodeSet2, .Us104Key, .MapLettersToUnicode); // start try std.testing.expect((try keyboard.addBit(0)) == null); // 8 data bits (LSB first) try std.testing.expect((try keyboard.addBit(1)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); try std.testing.expect((try keyboard.addBit(0)) == null); // parity try std.testing.expect((try keyboard.addBit(0)) == null); // stop const result = try keyboard.addBit(1); try std.testing.expect(result != null); try std.testing.expectEqual(KeyEvent{ .code = .F9, .state = .Down }, result.?); } test "f9 word" { var keyboard = Keyboard.init(.ScancodeSet2, .Us104Key, .MapLettersToUnicode); const result = try keyboard.addWord(0x0402); try std.testing.expect(result != null); try std.testing.expectEqual(KeyEvent{ .code = .F9, .state = .Down }, result.?); } test "f9 byte" { var keyboard = Keyboard.init(.ScancodeSet2, .Us104Key, .MapLettersToUnicode); const result = try keyboard.addByte(0x01); try std.testing.expect(result != null); try std.testing.expectEqual(KeyEvent{ .code = .F9, .state = .Down }, result.?); } test "keyup keydown" { var keyboard = Keyboard.init(.ScancodeSet2, .Us104Key, .MapLettersToUnicode); var kv = try keyboard.addByte(0x01); try std.testing.expect(kv != null); try std.testing.expectEqual(KeyEvent{ .code = .F9, .state = .Down }, kv.?); kv = try keyboard.addByte(0x01); try std.testing.expect(kv != null); try std.testing.expectEqual(KeyEvent{ .code = .F9, .state = .Down }, kv.?); kv = try keyboard.addByte(0xF0); try std.testing.expect(kv == null); kv = try keyboard.addByte(0x01); try std.testing.expect(kv != null); try std.testing.expectEqual(KeyEvent{ .code = .F9, .state = .Up }, kv.?); } test "shift" { var keyboard = Keyboard.init(.ScancodeSet2, .Us104Key, .MapLettersToUnicode); // A with shift held var dk = keyboard.processKeyevent(KeyEvent{ .code = .ShiftLeft, .state = .Down }); try std.testing.expect(dk == null); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Down }); try std.testing.expect(dk != null); try std.testing.expectEqualStrings("A", dk.?.Unicode); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Up }); try std.testing.expect(dk == null); dk = keyboard.processKeyevent(KeyEvent{ .code = .ShiftLeft, .state = .Up }); try std.testing.expect(dk == null); // A with no shift dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Down }); try std.testing.expect(dk != null); try std.testing.expectEqualStrings("a", dk.?.Unicode); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Up }); try std.testing.expect(dk == null); // A with right shift held dk = keyboard.processKeyevent(KeyEvent{ .code = .ShiftRight, .state = .Down }); try std.testing.expect(dk == null); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Down }); try std.testing.expect(dk != null); try std.testing.expectEqualStrings("A", dk.?.Unicode); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Up }); try std.testing.expect(dk == null); dk = keyboard.processKeyevent(KeyEvent{ .code = .ShiftRight, .state = .Up }); try std.testing.expect(dk == null); // Caps lock on dk = keyboard.processKeyevent(KeyEvent{ .code = .CapsLock, .state = .Down }); try std.testing.expect(dk == null); dk = keyboard.processKeyevent(KeyEvent{ .code = .CapsLock, .state = .Up }); try std.testing.expect(dk == null); // Letters are now caps dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Down }); try std.testing.expect(dk != null); try std.testing.expectEqualStrings("A", dk.?.Unicode); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Up }); try std.testing.expect(dk == null); // Unless you press shift dk = keyboard.processKeyevent(KeyEvent{ .code = .ShiftLeft, .state = .Down }); try std.testing.expect(dk == null); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Down }); try std.testing.expect(dk != null); try std.testing.expectEqualStrings("a", dk.?.Unicode); dk = keyboard.processKeyevent(KeyEvent{ .code = .A, .state = .Up }); try std.testing.expect(dk == null); }
src/pc_keyboard.zig
pub const Rect = struct { x: i32, y: i32, width: i32, height: i32, }; pub const Coord = struct { x: i32, y: i32, pub fn plus(a: Coord, b: Coord) Coord { return Coord{ .x = a.x + b.x, .y = a.y + b.y, }; } pub fn minus(a: Coord, b: Coord) Coord { return Coord{ .x = a.x - b.x, .y = a.y - b.y, }; } pub fn scaled(a: Coord, s: i32) Coord { return Coord{ .x = a.x * s, .y = a.y * s, }; } pub fn scaledDivTrunc(a: Coord, s: i32) Coord { return Coord{ .x = @divTrunc(a.x, s), .y = @divTrunc(a.y, s), }; } pub fn negated(a: Coord) Coord { return Coord{ .x = -a.x, .y = -a.y, }; } pub fn abs(a: Coord) Coord { return Coord{ .x = if (a.x < 0) -a.x else a.x, .y = if (a.y < 0) -a.y else a.y, }; } pub fn signumed(a: Coord) Coord { return Coord{ .x = sign(a.x), .y = sign(a.y), }; } /// How many orthogonal steps to get from a to b. pub fn distanceOrtho(a: Coord, b: Coord) i32 { return b.minus(a).magnitudeOrtho(); } pub fn magnitudeOrtho(a: Coord) i32 { const abs_vec = a.abs(); return abs_vec.x + abs_vec.y; } /// How many diagonal or orthogonal steps to get from a to b. pub fn distanceDiag(a: Coord, b: Coord) i32 { return b.minus(a).magnitudeDiag(); } pub fn magnitudeDiag(a: Coord) i32 { const abs_delta = a.abs(); return if (abs_delta.x < abs_delta.y) abs_delta.y else abs_delta.x; } /// Returns true iff at least one dimension is 0. pub fn isOrthogonalOrZero(a: Coord) bool { return a.x * a.y == 0; } /// Euclidean distance squared. pub fn magnitudeSquared(a: Coord) i32 { return a.x * a.x + a.y * a.y; } pub fn equals(a: Coord, b: Coord) bool { return a.x == b.x and a.y == b.y; } }; pub fn makeCoord(x: i32, y: i32) Coord { return Coord{ .x = x, .y = y, }; } pub fn isCardinalDirection(direction: Coord) bool { return isScaledCardinalDirection(direction, 1); } pub fn isScaledCardinalDirection(direction: Coord, scale: i32) bool { return direction.isOrthogonalOrZero() and direction.magnitudeSquared() == scale * scale; } /// rotation is a number 0 <= r < 8 /// representing the number of 45 degree clockwise turns from right. /// assert(isCardinalDirection(direction)). pub fn directionToRotation(direction: Coord) u3 { return @as(u3, directionToCardinalIndex(direction)) * 2; } /// index in .{right, down, left, up}. /// assert(isCardinalDirection(direction)). pub fn directionToCardinalIndex(direction: Coord) u2 { if (direction.x == 1 and direction.y == 0) return 0; if (direction.x == 0 and direction.y == 1) return 1; if (direction.x == -1 and direction.y == 0) return 2; if (direction.x == 0 and direction.y == -1) return 3; unreachable; } pub fn sign(x: i32) i32 { if (x > 0) return 1; if (x == 0) return 0; return -1; } /// Quadratic version of bezier2. pub fn bezier3( x0: Coord, x1: Coord, x2: Coord, s: i32, max_s: i32, ) Coord { return bezier2( bezier2(x0, x1, s, max_s), bezier2(x1, x2, s, max_s), s, max_s, ); } /// This is linear interpolation. /// Normally max_s is fixed at 1.0, but we're too cool for floats. pub fn bezier2( x0: Coord, x1: Coord, s: i32, max_s: i32, ) Coord { return x0.scaled(max_s - s).plus(x1.scaled(s)).scaledDivTrunc(max_s); }
src/core/geometry.zig
const std = @import("std"); const gemini = @import("gemtext.zig"); const Fragment = gemini.Fragment; const FragmentType = gemini.FragmentType; const Parser = gemini.Parser; const TextLines = gemini.TextLines; const Preformatted = gemini.Preformatted; const Link = gemini.Link; const Heading = gemini.Heading; const Document = gemini.Document; const renderer = gemini.renderer; fn testDocumentRendering(expected: []const u8, fragments: []const Fragment) !void { var buffer: [4096]u8 = undefined; var stream = std.io.fixedBufferStream(&buffer); try renderer.gemtext(fragments, stream.writer()); try std.testing.expectEqualStrings(expected, stream.getWritten()); } test "render empty line" { try testDocumentRendering("\r\n", &[_]Fragment{ Fragment{ .empty = {}, }, }); } test "render multiple lines" { try testDocumentRendering("\r\n\r\n", &[_]Fragment{ Fragment{ .empty = {} }, Fragment{ .empty = {} }, }); } test "render paragraph line" { try testDocumentRendering("Hello, World!\r\n", &[_]Fragment{ Fragment{ .paragraph = "Hello, World!", }, }); } test "render preformatted text (no alt text)" { try testDocumentRendering("```\r\nint main() {\r\n return 0;\r\n}\r\n```\r\n", &[_]Fragment{ Fragment{ .preformatted = Preformatted{ .alt_text = null, .text = TextLines{ .lines = &[_][:0]const u8{ "int main() {", " return 0;", "}", }, }, }, }, }); } test "render preformatted text (with alt text)" { try testDocumentRendering("```c\r\nint main() {\r\n return 0;\r\n}\r\n```\r\n", &[_]Fragment{ Fragment{ .preformatted = Preformatted{ .alt_text = "c", .text = TextLines{ .lines = &[_][:0]const u8{ "int main() {", " return 0;", "}", }, }, }, }, }); } test "render quote text lines" { try testDocumentRendering("> Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.\r\n> - <NAME>\r\n", &[_]Fragment{ Fragment{ .quote = TextLines{ .lines = &[_][:0]const u8{ "Two things are infinite: the universe and human stupidity; and I'm not sure about the universe.", "- <NAME>", }, } }, }); } test "render link lines" { try testDocumentRendering("=> gemini://kristall.random-projects.net/\r\n=> gemini://kristall.random-projects.net/ Kristall Small-Internet Browser\r\n", &[_]Fragment{ Fragment{ .link = Link{ .href = "gemini://kristall.random-projects.net/", .title = null, }, }, Fragment{ .link = Link{ .href = "gemini://kristall.random-projects.net/", .title = "Kristall Small-Internet Browser", }, }, }); } test "render headings" { try testDocumentRendering("# Heading 1\r\n## Heading 2\r\n### Heading 3\r\n", &[_]Fragment{ Fragment{ .heading = Heading{ .level = .h1, .text = "Heading 1" } }, Fragment{ .heading = Heading{ .level = .h2, .text = "Heading 2" } }, Fragment{ .heading = Heading{ .level = .h3, .text = "Heading 3" } }, }); } fn expectEqualLines(expected: TextLines, actual: TextLines) !void { try std.testing.expectEqual(expected.lines.len, actual.lines.len); for (expected.lines) |line, i| { try std.testing.expectEqualStrings(line, actual.lines[i]); } } fn expectFragmentEqual(expected_opt: ?Fragment, actual_opt: ?Fragment) !void { if (expected_opt == null) { try std.testing.expect(actual_opt == null); return; } const expected = expected_opt.?; const actual = actual_opt.?; try std.testing.expectEqual(@as(FragmentType, expected), @as(FragmentType, actual)); switch (expected) { .empty => {}, .paragraph => |paragraph| try std.testing.expectEqualStrings(paragraph, actual.paragraph), .preformatted => |preformatted| { if (preformatted.alt_text) |alt_text| try std.testing.expectEqualStrings(alt_text, actual.preformatted.alt_text.?); try expectEqualLines(preformatted.text, actual.preformatted.text); }, .quote => |quote| try expectEqualLines(quote, actual.quote), .link => |link| { if (link.title) |title| try std.testing.expectEqualStrings(title, actual.link.title.?); try std.testing.expectEqualStrings(link.href, actual.link.href); }, .list => |list| try expectEqualLines(list, actual.list), .heading => |heading| { try std.testing.expectEqual(heading.level, actual.heading.level); try std.testing.expectEqualStrings(heading.text, actual.heading.text); }, } } fn testFragmentParsing(fragment: ?Fragment, text: []const u8) !void { // duplicate the passed in text to clear it later. const dupe_text = try std.testing.allocator.dupe(u8, text); defer std.testing.allocator.free(dupe_text); var parser = Parser.init(std.testing.allocator); defer parser.deinit(); var got_fragment = false; var offset: usize = 0; while (offset < dupe_text.len) { var res = try parser.feed(std.testing.allocator, dupe_text[offset..]); offset += res.consumed; if (res.fragment) |*frag| { defer frag.free(std.testing.allocator); try std.testing.expectEqual(false, got_fragment); // Clear the input text to make sure we didn't accidently pass a reference to our input slice std.mem.set(u8, dupe_text, '?'); try expectFragmentEqual(fragment, frag.*); got_fragment = true; break; } } try std.testing.expectEqual(text.len, offset); if (try parser.finalize(std.testing.allocator)) |*frag| { defer frag.free(std.testing.allocator); try std.testing.expectEqual(false, got_fragment); // Clear the input text to make sure we didn't accidently pass a reference to our input slice std.mem.set(u8, dupe_text, '?'); try expectFragmentEqual(fragment, frag.*); } else { if (fragment != null) { try std.testing.expectEqual(true, got_fragment); } else { try std.testing.expectEqual(false, got_fragment); } } } test "parse incomplete fragment" { var parser = Parser.init(std.testing.allocator); defer parser.deinit(); try std.testing.expectEqual(Parser.Result{ .consumed = 8, .fragment = null }, try parser.feed(std.testing.allocator, "12345678")); try std.testing.expectEqual(Parser.Result{ .consumed = 8, .fragment = null }, try parser.feed(std.testing.allocator, "12345678")); try std.testing.expectEqual(Parser.Result{ .consumed = 8, .fragment = null }, try parser.feed(std.testing.allocator, "12345678")); try std.testing.expectEqual(Parser.Result{ .consumed = 8, .fragment = null }, try parser.feed(std.testing.allocator, "12345678")); } test "parse empty line" { try testFragmentParsing(null, ""); try testFragmentParsing(Fragment{ .empty = {} }, "\r\n"); } test "parse normal paragraph" { try testFragmentParsing(Fragment{ .paragraph = "Hello World!" }, "Hello World!"); try testFragmentParsing(Fragment{ .paragraph = "Hello World!" }, "Hello World!\r\n"); } test "parse heading line" { try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h1, .text = "Hello World!" } }, "#Hello World!"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h1, .text = "Hello World!" } }, "#Hello World!\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h1, .text = "Hello World!" } }, "# Hello World!"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h1, .text = "Hello World!" } }, "# Hello World!\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h2, .text = "Hello World!" } }, "##Hello World!"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h2, .text = "Hello World!" } }, "##Hello World!\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h2, .text = "Hello World!" } }, "## Hello World!"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h2, .text = "Hello World!" } }, "## Hello World!\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h3, .text = "Hello World!" } }, "###Hello World!"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h3, .text = "Hello World!" } }, "###Hello World!\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h3, .text = "Hello World!" } }, "### Hello World!"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h3, .text = "Hello World!" } }, "### Hello World!\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h3, .text = "#H1" } }, "####H1\r\n"); try testFragmentParsing(Fragment{ .heading = Heading{ .level = .h3, .text = "#H1" } }, "####H1\r\n"); } test "parse link (no title)" { const fragment = Fragment{ .link = Link{ .href = "gemini://circumlunar.space/", .title = null, }, }; try testFragmentParsing(fragment, "=>gemini://circumlunar.space/"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/\r\n"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/\r\n"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ "); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ \r\n"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ "); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ \r\n"); } test "parse link (with title)" { const fragment = Fragment{ .link = Link{ .href = "gemini://circumlunar.space/", .title = "This is a link!", }, }; try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link!"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link!\r\n"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link!"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link!\r\n"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link! "); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link! \r\n"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link! "); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link! \r\n"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link!"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link!\r\n"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link!"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link!\r\n"); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link! "); try testFragmentParsing(fragment, "=>gemini://circumlunar.space/ This is a link! \r\n"); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link! "); try testFragmentParsing(fragment, "=> gemini://circumlunar.space/ This is a link! \r\n"); } test "parse list block" { const list_0 = Fragment{ .list = TextLines{ .lines = &[_][:0]const u8{ "item 0", }, }, }; const list_3 = Fragment{ .list = TextLines{ .lines = &[_][:0]const u8{ "item 1", "item 2", "item 3", }, }, }; try testFragmentParsing(list_0, "* item 0"); try testFragmentParsing(list_0, "* item 0\r\n"); try testFragmentParsing(list_0, "* item 0 "); try testFragmentParsing(list_0, "* item 0 \r\n"); try testFragmentParsing(list_3, "* item 1\r\n* item 2\r\n* item 3"); try testFragmentParsing(list_3, "* item 1\r\n* item 2\r\n* item 3\r\n"); } test "parse quote block" { const quote_0 = Fragment{ .quote = TextLines{ .lines = &[_][:0]const u8{ "item 0", }, }, }; const quote_3 = Fragment{ .quote = TextLines{ .lines = &[_][:0]const u8{ "item 1", "item 2", "item 3", }, }, }; try testFragmentParsing(quote_0, ">item 0"); try testFragmentParsing(quote_0, ">item 0\r\n"); try testFragmentParsing(quote_0, "> item 0"); try testFragmentParsing(quote_0, "> item 0\r\n"); try testFragmentParsing(quote_0, ">item 0 "); try testFragmentParsing(quote_0, ">item 0 \r\n"); try testFragmentParsing(quote_0, "> item 0 "); try testFragmentParsing(quote_0, "> item 0 \r\n"); try testFragmentParsing(quote_3, ">item 1\r\n>item 2\r\n>item 3"); try testFragmentParsing(quote_3, ">item 1\r\n>item 2\r\n>item 3\r\n"); } test "parse preformatted blocks (no alt text)" { const empty_block = Fragment{ .preformatted = Preformatted{ .alt_text = null, .text = TextLines{ .lines = &[_][:0]const u8{}, }, }, }; const single_line_block = Fragment{ .preformatted = Preformatted{ .alt_text = null, .text = TextLines{ .lines = &[_][:0]const u8{ " hello world ", }, }, }, }; const c_code_block = Fragment{ .preformatted = Preformatted{ .alt_text = null, .text = TextLines{ .lines = &[_][:0]const u8{ "int main() {", " return 0;", "}", }, }, }, }; try testFragmentParsing(empty_block, "```"); try testFragmentParsing(empty_block, "```\r\n```"); try testFragmentParsing(empty_block, "```\r\n```\r\n"); try testFragmentParsing(single_line_block, "```\r\n hello world "); try testFragmentParsing(single_line_block, "```\r\n hello world \r\n```"); try testFragmentParsing(single_line_block, "```\r\n hello world \r\n```\r\n"); try testFragmentParsing(c_code_block, "```\r\nint main() {\r\n return 0;\r\n}"); try testFragmentParsing(c_code_block, "```\r\nint main() {\r\n return 0;\r\n}\r\n```"); try testFragmentParsing(c_code_block, "```\r\nint main() {\r\n return 0;\r\n}\r\n```\r\n"); } test "parse preformatted blocks (with alt text)" { const empty_block = Fragment{ .preformatted = Preformatted{ .alt_text = "alt", .text = TextLines{ .lines = &[_][:0]const u8{}, }, }, }; const single_line_block = Fragment{ .preformatted = Preformatted{ .alt_text = "alt", .text = TextLines{ .lines = &[_][:0]const u8{ " hello world ", }, }, }, }; const c_code_block = Fragment{ .preformatted = Preformatted{ .alt_text = "alt", .text = TextLines{ .lines = &[_][:0]const u8{ "int main() {", " return 0;", "}", }, }, }, }; try testFragmentParsing(empty_block, "```alt"); try testFragmentParsing(empty_block, "```alt\r\n```"); try testFragmentParsing(empty_block, "```alt\r\n```\r\n"); try testFragmentParsing(empty_block, "``` alt"); try testFragmentParsing(empty_block, "```alt "); try testFragmentParsing(empty_block, "``` alt "); try testFragmentParsing(empty_block, "``` alt "); try testFragmentParsing(single_line_block, "```alt\r\n hello world "); try testFragmentParsing(single_line_block, "```alt\r\n hello world \r\n```"); try testFragmentParsing(single_line_block, "```alt\r\n hello world \r\n```\r\n"); try testFragmentParsing(c_code_block, "```alt\r\nint main() {\r\n return 0;\r\n}"); try testFragmentParsing(c_code_block, "```alt\r\nint main() {\r\n return 0;\r\n}\r\n```"); try testFragmentParsing(c_code_block, "```alt\r\nint main() {\r\n return 0;\r\n}\r\n```\r\n"); } fn testSequenceParsing(expected_sequence: []const Fragment, text: []const u8) !void { // duplicate the passed in text to clear it later. const dupe_text = try std.testing.allocator.dupe(u8, text); defer std.testing.allocator.free(dupe_text); var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var actual_sequence = std.ArrayList(Fragment).init(std.testing.allocator); defer actual_sequence.deinit(); { var parser = Parser.init(std.testing.allocator); defer parser.deinit(); var offset: usize = 0; while (offset < dupe_text.len) { var res = try parser.feed(&arena.allocator, dupe_text[offset..]); offset += res.consumed; if (res.fragment) |frag| { try actual_sequence.append(frag); } } try std.testing.expectEqual(text.len, offset); if (try parser.finalize(&arena.allocator)) |frag| { try actual_sequence.append(frag); } } // Clear the input text to make sure we didn't accidently pass a reference to our input slice std.mem.set(u8, dupe_text, '?'); try std.testing.expectEqual(expected_sequence.len, actual_sequence.items.len); for (expected_sequence) |expected, i| { try expectFragmentEqual(expected, actual_sequence.items[i]); } } test "basic sequence parsing" { try testSequenceParsing( &[_]Fragment{ Fragment{ .paragraph = "Hello" }, Fragment{ .paragraph = "World!" }, }, \\Hello \\World! , ); try testSequenceParsing( &[_]Fragment{ Fragment{ .empty = {} }, Fragment{ .paragraph = "World!" }, }, \\ \\World! \\ , ); try testSequenceParsing( &[_]Fragment{ Fragment{ .heading = Heading{ .level = .h1, .text = "Heading" } }, Fragment{ .paragraph = "This is a bullet list:" }, Fragment{ .list = TextLines{ .lines = &[_][:0]const u8{ "Tortillias", "Cheese Dip", "Spicy Dip", } } }, }, \\# Heading \\This is a bullet list: \\* Tortillias \\* Cheese Dip \\* Spicy Dip \\ , ); } test "sequenc hand over between block types" { // these are all possible permutations of list, quote and preformatted // this tests the proper hand over and termination between all block types const sequence_permutations = [_][3]usize{ [3]usize{ 0, 1, 2 }, [3]usize{ 1, 0, 2 }, [3]usize{ 2, 0, 1 }, [3]usize{ 0, 2, 1 }, [3]usize{ 1, 2, 0 }, [3]usize{ 2, 1, 0 }, }; const fragment_src = [3]Fragment{ Fragment{ .quote = TextLines{ .lines = &[_][:0]const u8{ "ein", "stein", "said", }, }, }, Fragment{ .preformatted = Preformatted{ .alt_text = null, .text = TextLines{ .lines = &[_][:0]const u8{ "int main() {", " return 0;", "}", }, }, }, }, Fragment{ .list = TextLines{ .lines = &[_][:0]const u8{ "philly", "cheese", "steak", }, }, }, }; const text_src = [3][]const u8{ "> ein\r\n>stein\r\n> said \r\n", "```\r\nint main() {\r\n return 0;\r\n}\r\n```\r\n", "* philly \r\n* cheese \r\n* steak\r\n", }; inline for (sequence_permutations) |permutation| { const expected_sequence = [_]Fragment{ Fragment{ .paragraph = "---" }, fragment_src[permutation[0]], fragment_src[permutation[1]], fragment_src[permutation[2]], Fragment{ .paragraph = "---" }, }; const text_rendering = "---\r\n" ++ text_src[permutation[0]] ++ text_src[permutation[1]] ++ text_src[permutation[2]] ++ "---\r\n"; try testSequenceParsing(&expected_sequence, text_rendering); } } test "Parse examples from the spec" { const spec_examples = \\Text lines should be presented to the user, after being wrapped to the appropriate width for the client's viewport (see below). Text lines may be presented to the user in a visually pleasing manner for general reading, the precise meaning of which is at the client's discretion. For example, variable width fonts may be used, spacing may be normalised, with spaces between sentences being made wider than spacing between words, and other such typographical niceties may be applied. Clients may permit users to customise the appearance of text lines by altering the font, font size, text and background colour, etc. Authors should not expect to exercise any control over the precise rendering of their text lines, only of their actual textual content. Content such as ASCII art, computer source code, etc. which may appear incorrectly when treated as such should be enclosed between preformatting toggle lines (see 5.4.3). \\Authors who insist on hard-wrapping their content MUST be aware that the content will display neatly on clients whose display device is as wide as the hard-wrapped length or wider, but will appear with irregular line widths on narrower clients. \\ \\=> gemini://example.org/ \\=> gemini://example.org/ An example link \\=> gemini://example.org/foo Another example link at the same host \\=> foo/bar/baz.txt A relative link \\=> gopher://example.org:70/1 A gopher link \\``` \\=>[<whitespace>]<URL>[<whitespace><USER-FRIENDLY LINK NAME>] \\``` \\# Appendix 1. Full two digit status codes \\## 10 INPUT \\### 5.5.3 Quote lines \\* <whitespa0ce> is any non-zero number of consecutive spaces or tabs \\* Square brackets indicate that the enclosed content is optional. \\* <URL> is a URL, which may be absolute or relative. ; var document = try Document.parseString(std.testing.allocator, spec_examples); defer document.deinit(); } fn terminateWithCrLf(comptime input_literal: [:0]const u8) [:0]const u8 { @setEvalBranchQuota(20 * input_literal.len); comptime var result: [:0]const u8 = ""; comptime var iter = std.mem.split(u8, input_literal, "\n"); inline while (comptime iter.next()) |line| { result = result ++ line ++ "\r\n"; } return result; } const document_text = terminateWithCrLf( // heading, h1 \\# Introduction // paragraph \\This is a basic text line \\And this is another one // list \\* And we can also do \\* some nice \\* lists // empty \\ \\or empty lines! // heading, h2 \\## Code Example // preformatted \\```c \\int main() { \\ return 0; \\} \\``` // heading, h3 \\### Quotes \\we can also quote Einstein // quote \\> This is a small step for a ziguana \\> but a great step for zig-kind! // link + title \\=> ftp://ftp.scene.org/pub/ Demoscene Archives // link - title \\=> ftp://ftp.scene.org/pub/ ); fn testDocumentFormatter(expected: []const u8, comptime renderer_name: []const u8) !void { var output_buffer: [4096]u8 = undefined; var input_stream = std.io.fixedBufferStream(document_text); var output_stream = std.io.fixedBufferStream(&output_buffer); var document = try Document.parse(std.testing.allocator, input_stream.reader()); defer document.deinit(); try @field(renderer, renderer_name)(document.fragments.items, output_stream.writer()); try std.testing.expectEqualStrings(expected, output_stream.getWritten()); } test "parse and render canonical document" { try testDocumentFormatter(document_text, "gemtext"); } test "render html" { const document_html = terminateWithCrLf( \\<h1>Introduction</h1> \\<p>This is a basic text line</p> \\<p>And this is another one</p> \\<ul> \\<li>And we can also do</li> \\<li>some nice</li> \\<li>lists</li> \\</ul> \\<p>&nbsp;</p> \\<p>or empty lines!</p> \\<h2>Code Example</h1> \\<pre alt="c">int main() { \\ return 0; \\}</pre> \\<h3>Quotes</h1> \\<p>we can also quote Einstein</p> \\<blockquote>This is a small step for a ziguana<br> \\but a great step for zig-kind!</blockquote> \\<p><a href="ftp://ftp.scene.org/pub/">Demoscene Archives</a></p> \\<p><a href="ftp://ftp.scene.org/pub/">ftp://ftp.scene.org/pub/</a></p> ); try testDocumentFormatter(document_html, "html"); } test "render markdown" { const document_markdown = terminateWithCrLf( \\# Introduction \\ \\This is a basic text line \\ \\And this is another one \\ \\- And we can also do \\- some nice \\- lists \\ \\&nbsp; \\ \\or empty lines! \\ \\## Code Example \\ \\```c \\int main() { \\ return 0; \\} \\``` \\ \\### Quotes \\ \\we can also quote Einstein \\ \\> This is a small step for a ziguana \\> but a great step for zig-kind! \\ \\[Demoscene Archives](ftp://ftp.scene.org/pub/) \\ \\ftp://ftp.scene.org/pub/ ); try testDocumentFormatter(document_markdown, "markdown"); } test "render rtf" { const document_rtf = terminateWithCrLf( //\\{\rtf1\ansi{\fonttbl{\f0\fswiss}{\f1\fmodern Courier New{\*\falt Monospace};}} \\{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs36 Introduction\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 This is a basic text line\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 And this is another one\par} \\{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab And we can also do\par} \\{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab some nice\par} \\{\pard \ql \f0 \sa0 \li360 \fi-360 \bullet \tx360\tab lists\sa180\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 \par} \\{\pard \ql \f0 \sa180 \li0 \fi0 or empty lines!\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs32 Code Example\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 \f1 int main() \{\line \\ return 0;\line \\\}\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 \b \fs28 Quotes\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 we can also quote Einstein\par} \\{\pard \ql \f0 \sa180 \li720 \fi0 This is a small step for a ziguana\line \\but a great step for zig-kind!\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 {\field{\*\fldinst{HYPERLINK "ftp://ftp.scene.org/pub/"}}{\fldrslt{\ul Demoscene Archives}}}\par} \\{\pard \ql \f0 \sa180 \li0 \fi0 {\field{\*\fldinst{HYPERLINK "ftp://ftp.scene.org/pub/"}}{\fldrslt{\ul ftp://ftp.scene.org/pub/}}}\par} //\\} ); try testDocumentFormatter(document_rtf, "rtf"); }
src/tests.zig
const std = @import("std"); const VM = @import("./vm.zig").VM; const _obj = @import("./obj.zig"); const _value = @import("./value.zig"); const utils = @import("./utils.zig"); const memory = @import("./memory.zig"); const _compiler = @import("./compiler.zig"); const Value = _value.Value; const valueToString = _value.valueToString; const copyString = _obj.copyString; const ObjString = _obj.ObjString; const ObjTypeDef = _obj.ObjTypeDef; const ObjFunction = _obj.ObjFunction; const ObjList = _obj.ObjList; const ObjUserData = _obj.ObjUserData; const UserData = _obj.UserData; const Compiler = _compiler.Compiler; // Stack manipulation /// Push a Value to the stack export fn bz_push(self: *VM, value: *Value) void { self.push(value.*); } /// Pop a Value from the stack and returns it export fn bz_pop(self: *VM) *Value { self.stack_top -= 1; return @ptrCast(*Value, self.stack_top); } /// Peeks at the stack at [distance] from the stack top export fn bz_peek(self: *VM, distance: u32) *Value { return @ptrCast(*Value, self.stack_top - 1 - distance); } // Value manipulations /// Push a boolean value on the stack export fn bz_pushBool(self: *VM, value: bool) void { self.push(Value{ .Boolean = value }); } /// Push a float value on the stack export fn bz_pushNum(self: *VM, value: f64) void { self.push(Value{ .Number = value }); } /// Push null on the stack export fn bz_pushNull(self: *VM) void { self.push(Value{ .Null = null }); } /// Push void on the stack export fn bz_pushVoid(self: *VM) void { self.push(Value{ .Void = null }); } /// Push string on the stack export fn bz_pushString(self: *VM, value: *ObjString) void { self.push(value.toValue()); } /// Push list on the stack export fn bz_pushList(self: *VM, value: *ObjList) void { self.push(value.toValue()); } /// Converts a value to a boolean export fn bz_valueToBool(value: *Value) bool { return value.Boolean; } /// Converts a value to a string export fn bz_valueToString(value: *Value) ?[*:0]const u8 { if (value.* != .Obj or value.Obj.obj_type != .String) { return null; } return utils.toCString(std.heap.c_allocator, ObjString.cast(value.Obj).?.string); } /// Converts a value to a number export fn bz_valueToNumber(value: *Value) f64 { return value.Number; } // Obj manipulations /// Converts a c string to a *ObjString export fn bz_string(vm: *VM, string: [*:0]const u8) ?*ObjString { return copyString(vm, utils.toSlice(string)) catch null; } // Other stuff // Type helpers // TODO: should always return the same instance /// Returns the [bool] type export fn bz_boolType() ?*ObjTypeDef { var bool_type: ?*ObjTypeDef = std.heap.c_allocator.create(ObjTypeDef) catch null; if (bool_type == null) { return null; } bool_type.?.* = ObjTypeDef{ .def_type = .Bool, .optional = false }; return bool_type; } /// Returns the [str] type export fn bz_stringType() ?*ObjTypeDef { var bool_type: ?*ObjTypeDef = std.heap.c_allocator.create(ObjTypeDef) catch null; if (bool_type == null) { return null; } bool_type.?.* = ObjTypeDef{ .def_type = .String, .optional = false }; return bool_type; } /// Returns the [void] type export fn bz_voidType() ?*ObjTypeDef { var void_type: ?*ObjTypeDef = std.heap.c_allocator.create(ObjTypeDef) catch null; if (void_type == null) { return null; } void_type.?.* = ObjTypeDef{ .def_type = .Void, .optional = false }; return void_type; } /// Creates a function type with no argument. Argument should be added with [bz_addFunctionArgument] export fn bz_newFunctionType(vm: *VM, name: [*:0]const u8, return_type: ?*ObjTypeDef) ?*ObjTypeDef { // TODO: this obj is not in the GC var function_type: ?*ObjTypeDef = std.heap.c_allocator.create(ObjTypeDef) catch null; if (function_type == null) { return null; } var function_def = ObjFunction.FunctionDef{ // If oom, empty string should not fail .name = (bz_string(vm, name) orelse bz_string(vm, @ptrCast([*:0]const u8, ""))).?, .return_type = return_type orelse bz_voidType().?, .parameters = std.StringArrayHashMap(*ObjTypeDef).init(std.heap.c_allocator), .has_defaults = std.StringArrayHashMap(bool).init(std.heap.c_allocator), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Function = function_def }; function_type.?.* = .{ .def_type = .Function, .resolved_type = resolved_type }; return function_type; } /// Adds a argument to a function definition. Returns false if could not add it. export fn bz_addFunctionArgument(function_type: *ObjTypeDef, name: [*:0]const u8, arg_type: *ObjTypeDef) bool { function_type.resolved_type.?.Function.parameters.put(utils.toSlice(name), arg_type) catch { return false; }; return true; } export fn bz_allocated(self: *VM) usize { return self.bytes_allocated; } export fn bz_collect(self: *VM) bool { memory.collectGarbage(self) catch { return false; }; return true; } export fn bz_newList(vm: *VM, of_type: *ObjTypeDef) ?*ObjList { var list_def: ObjList.ListDef = ObjList.ListDef.init( vm.allocator, of_type, ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; var list_def_type: *ObjTypeDef = _obj.allocateObject(vm, ObjTypeDef, ObjTypeDef{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }) catch { return null; }; return _obj.allocateObject( vm, ObjList, ObjList.init(vm.allocator, list_def_type), ) catch { return null; }; } export fn bz_listAppend(self: *ObjList, value: *Value) bool { self.rawAppend(value.*) catch { return false; }; return true; } export fn bz_valueToList(value: *Value) *ObjList { return ObjList.cast(value.Obj).?; } export fn bz_listGet(self: *ObjList, index: usize) *Value { return &self.items.items[index]; } export fn bz_listLen(self: *ObjList) usize { return self.items.items.len; } export fn bz_newUserData(vm: *VM, userdata: *UserData) ?*ObjUserData { return _obj.allocateObject( vm, ObjUserData, ObjUserData{ .userdata = userdata }, ) catch { return null; }; } export fn bz_throw(vm: *VM, value: *Value) void { vm.push(value.*); } export fn bz_throwString(vm: *VM, message: [*:0]const u8) void { bz_pushString(vm, bz_string(vm, message) orelse { _ = std.io.getStdErr().write(utils.toSlice(message)) catch unreachable; std.os.exit(1); }); } export fn bz_newVM(self: *VM) ?*VM { var vm = self.allocator.create(VM) catch { return null; }; vm.* = VM.init(self.allocator, self.strings) catch { return null; }; return vm; } export fn bz_deinitVM(self: *VM) void { self.deinit(); } export fn bz_compile(self: *VM, source: [*:0]const u8, file_name: [*:0]const u8) ?*ObjFunction { var imports = std.StringHashMap(Compiler.ScriptImport).init(self.allocator); var strings = std.StringHashMap(*ObjString).init(self.allocator); var compiler = Compiler.init(self.allocator, self.strings, &imports, false); defer { imports.deinit(); compiler.deinit(); strings.deinit(); } if (compiler.compile(utils.toSlice(source), utils.toSlice(file_name), false) catch null) |function| { return function; } else { return null; } } export fn bz_interpret(self: *VM, function: *ObjFunction) bool { self.interpret(function, null) catch { return false; }; return true; }
src/buzz_api.zig
const stdx = @import("stdx"); const vk = @import("vk"); const gvk = @import("graphics.zig"); const log = stdx.log.scoped(.buffer); pub fn createVertexBuffer(physical: vk.VkPhysicalDevice, device: vk.VkDevice, size: vk.VkDeviceSize, buf: *vk.VkBuffer, buf_mem: *vk.VkDeviceMemory) void { createBuffer(physical, device, size, vk.VK_BUFFER_USAGE_VERTEX_BUFFER_BIT, // HOST_COHERENT_BIT forces writes to flush. vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, buf, buf_mem ); } pub fn createIndexBuffer(physical: vk.VkPhysicalDevice, device: vk.VkDevice, size: vk.VkDeviceSize, buf: *vk.VkBuffer, buf_mem: *vk.VkDeviceMemory) void { createBuffer(physical, device, size, vk.VK_BUFFER_USAGE_INDEX_BUFFER_BIT, vk.VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | vk.VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, buf, buf_mem, ); } pub fn createBuffer(physical: vk.VkPhysicalDevice, device: vk.VkDevice, size: vk.VkDeviceSize, usage: vk.VkBufferUsageFlags, properties: vk.VkMemoryPropertyFlags, buffer: *vk.VkBuffer, buffer_memory: *vk.VkDeviceMemory) void { const create_info = vk.VkBufferCreateInfo{ .sType = vk.VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO, .size = size, .usage = usage, .sharingMode = vk.VK_SHARING_MODE_EXCLUSIVE, .queueFamilyIndexCount = 0, .pQueueFamilyIndices = null, .pNext = null, .flags = 0, }; var res = vk.createBuffer(device, &create_info, null, buffer); vk.assertSuccess(res); var mem_requirements: vk.VkMemoryRequirements = undefined; vk.getBufferMemoryRequirements(device, buffer.*, &mem_requirements); const alloc_info = vk.VkMemoryAllocateInfo{ .sType = vk.VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, .allocationSize = mem_requirements.size, .memoryTypeIndex = gvk.memory.findMemoryType(physical, mem_requirements.memoryTypeBits, properties), .pNext = null, }; res = vk.allocateMemory(device, &alloc_info, null, buffer_memory); vk.assertSuccess(res); res = vk.bindBufferMemory(device, buffer.*, buffer_memory.*, 0); vk.assertSuccess(res); }
graphics/src/backend/vk/buffer.zig
usingnamespace @import("../bits/linux.zig"); pub fn syscall0(number: SYS) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), : "memory", "cc" ); } pub fn syscall1(number: SYS, arg1: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), : "memory", "cc" ); } pub fn syscall2(number: SYS, arg1: usize, arg2: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), : "memory", "cc" ); } pub fn syscall3(number: SYS, arg1: usize, arg2: usize, arg3: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), : "memory", "cc" ); } pub fn syscall4(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), [arg4] "{x3}" (arg4), : "memory", "cc" ); } pub fn syscall5(number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), [arg4] "{x3}" (arg4), [arg5] "{x4}" (arg5), : "memory", "cc" ); } pub fn syscall6( number: SYS, arg1: usize, arg2: usize, arg3: usize, arg4: usize, arg5: usize, arg6: usize, ) usize { return asm volatile ("svc #0" : [ret] "={x0}" (-> usize), : [number] "{x8}" (@enumToInt(number)), [arg1] "{x0}" (arg1), [arg2] "{x1}" (arg2), [arg3] "{x2}" (arg3), [arg4] "{x3}" (arg4), [arg5] "{x4}" (arg5), [arg6] "{x5}" (arg6), : "memory", "cc" ); } /// This matches the libc clone function. pub extern fn clone(func: fn (arg: usize) callconv(.C) u8, stack: usize, flags: u32, arg: usize, ptid: *i32, tls: usize, ctid: *i32) usize; pub const restore = restore_rt; pub fn restore_rt() callconv(.Naked) void { return asm volatile ("svc #0" : : [number] "{x8}" (@enumToInt(SYS.rt_sigreturn)), : "memory", "cc" ); }
lib/std/os/linux/arm64.zig
const root = @import("root"); const std = @import("std.zig"); const builtin = std.builtin; const assert = std.debug.assert; const uefi = std.os.uefi; var argc_argv_ptr: [*]usize = undefined; const start_sym_name = if (builtin.arch.isMIPS()) "__start" else "_start"; comptime { if (builtin.output_mode == .Lib and builtin.link_mode == .Dynamic) { if (builtin.os.tag == .windows and !@hasDecl(root, "_DllMainCRTStartup")) { @export(_DllMainCRTStartup, .{ .name = "_DllMainCRTStartup" }); } } else if (builtin.output_mode == .Exe or @hasDecl(root, "main")) { if (builtin.link_libc and @hasDecl(root, "main")) { if (@typeInfo(@TypeOf(root.main)).Fn.calling_convention != .C) { @export(main, .{ .name = "main", .linkage = .Weak }); } } else if (builtin.os.tag == .windows) { if (!@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup")) { @export(WinStartup, .{ .name = "wWinMainCRTStartup" }); } else if (@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup") and !@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup")) { @compileError("WinMain not supported; declare wWinMain or main instead"); } else if (@hasDecl(root, "wWinMain") and !@hasDecl(root, "wWinMainCRTStartup") and !@hasDecl(root, "WinMain") and !@hasDecl(root, "WinMainCRTStartup")) { @export(wWinMainCRTStartup, .{ .name = "wWinMainCRTStartup" }); } } else if (builtin.os.tag == .uefi) { if (!@hasDecl(root, "EfiMain")) @export(EfiMain, .{ .name = "EfiMain" }); } else if (builtin.arch.isWasm() and builtin.os.tag == .freestanding) { if (!@hasDecl(root, start_sym_name)) @export(wasm_freestanding_start, .{ .name = start_sym_name }); } else if (builtin.os.tag != .other and builtin.os.tag != .freestanding) { if (!@hasDecl(root, start_sym_name)) @export(_start, .{ .name = start_sym_name }); } } } fn _DllMainCRTStartup( hinstDLL: std.os.windows.HINSTANCE, fdwReason: std.os.windows.DWORD, lpReserved: std.os.windows.LPVOID, ) callconv(std.os.windows.WINAPI) std.os.windows.BOOL { if (!builtin.single_threaded and !builtin.link_libc) { _ = @import("start_windows_tls.zig"); } if (@hasDecl(root, "DllMain")) { return root.DllMain(hinstDLL, fdwReason, lpReserved); } return std.os.windows.TRUE; } fn wasm_freestanding_start() callconv(.C) void { // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. _ = @call(.{ .modifier = .always_inline }, callMain, .{}); } fn EfiMain(handle: uefi.Handle, system_table: *uefi.tables.SystemTable) callconv(.C) usize { uefi.handle = handle; uefi.system_table = system_table; switch (@typeInfo(@TypeOf(root.main)).Fn.return_type.?) { noreturn => { root.main(); }, void => { root.main(); return 0; }, usize => { return root.main(); }, uefi.Status => { return @enumToInt(root.main()); }, else => @compileError("expected return type of main to be 'void', 'noreturn', 'usize', or 'std.os.uefi.Status'"), } } fn _start() callconv(.Naked) noreturn { if (builtin.os.tag == .wasi) { // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. std.os.wasi.proc_exit(@call(.{ .modifier = .always_inline }, callMain, .{})); } switch (builtin.arch) { .x86_64 => { argc_argv_ptr = asm volatile ( \\ xor %%rbp, %%rbp : [argc] "={rsp}" (-> [*]usize) ); }, .i386 => { argc_argv_ptr = asm volatile ( \\ xor %%ebp, %%ebp : [argc] "={esp}" (-> [*]usize) ); }, .aarch64, .aarch64_be, .arm, .armeb => { argc_argv_ptr = asm volatile ( \\ mov fp, #0 \\ mov lr, #0 : [argc] "={sp}" (-> [*]usize) ); }, .riscv64 => { argc_argv_ptr = asm volatile ( \\ li s0, 0 \\ li ra, 0 : [argc] "={sp}" (-> [*]usize) ); }, .mips, .mipsel => { // The lr is already zeroed on entry, as specified by the ABI. argc_argv_ptr = asm volatile ( \\ move $fp, $0 : [argc] "={sp}" (-> [*]usize) ); }, .powerpc64le => { // Setup the initial stack frame and clear the back chain pointer. // TODO: Support powerpc64 (big endian) on ELFv2. argc_argv_ptr = asm volatile ( \\ mr 4, 1 \\ li 0, 0 \\ stdu 0, -32(1) \\ mtlr 0 : [argc] "={r4}" (-> [*]usize) : : "r0" ); }, .sparcv9 => { // argc is stored after a register window (16 registers) plus stack bias argc_argv_ptr = asm ( \\ mov %%g0, %%i6 \\ add %%o6, 2175, %[argc] : [argc] "=r" (-> [*]usize) ); }, else => @compileError("unsupported arch"), } // If LLVM inlines stack variables into _start, they will overwrite // the command line argument data. @call(.{ .modifier = .never_inline }, posixCallMainAndExit, .{}); } fn WinStartup() callconv(std.os.windows.WINAPI) noreturn { @setAlignStack(16); if (!builtin.single_threaded) { _ = @import("start_windows_tls.zig"); } std.debug.maybeEnableSegfaultHandler(); std.os.windows.kernel32.ExitProcess(initEventLoopAndCallMain()); } fn wWinMainCRTStartup() callconv(std.os.windows.WINAPI) noreturn { @setAlignStack(16); if (!builtin.single_threaded) { _ = @import("start_windows_tls.zig"); } std.debug.maybeEnableSegfaultHandler(); const result: std.os.windows.INT = initEventLoopAndCallWinMain(); std.os.windows.kernel32.ExitProcess(@bitCast(std.os.windows.UINT, result)); } // TODO https://github.com/ziglang/zig/issues/265 fn posixCallMainAndExit() noreturn { @setAlignStack(16); const argc = argc_argv_ptr[0]; const argv = @ptrCast([*][*:0]u8, argc_argv_ptr + 1); const envp_optional = @ptrCast([*:null]?[*:0]u8, @alignCast(@alignOf(usize), argv + argc + 1)); var envp_count: usize = 0; while (envp_optional[envp_count]) |_| : (envp_count += 1) {} const envp = @ptrCast([*][*:0]u8, envp_optional)[0..envp_count]; if (builtin.os.tag == .linux) { // Find the beginning of the auxiliary vector const auxv = @ptrCast([*]std.elf.Auxv, @alignCast(@alignOf(usize), envp.ptr + envp_count + 1)); std.os.linux.elf_aux_maybe = auxv; // Do this as early as possible, the aux vector is needed if (builtin.position_independent_executable) { @import("os/linux/start_pie.zig").apply_relocations(); } // Initialize the TLS area. We do a runtime check here to make sure // this code is truly being statically executed and not inside a dynamic // loader, otherwise this would clobber the thread ID register. const is_dynamic = @import("dynamic_library.zig").get_DYNAMIC() != null; if (!is_dynamic) { std.os.linux.tls.initStaticTLS(); } // TODO This is disabled because what should we do when linking libc and this code // does not execute? And also it's causing a test failure in stack traces in release modes. //// Linux ignores the stack size from the ELF file, and instead always does 8 MiB. A further //// problem is that it uses PROT_GROWSDOWN which prevents stores to addresses too far down //// the stack and requires "probing". So here we allocate our own stack. //const wanted_stack_size = gnu_stack_phdr.p_memsz; //assert(wanted_stack_size % std.mem.page_size == 0); //// Allocate an extra page as the guard page. //const total_size = wanted_stack_size + std.mem.page_size; //const new_stack = std.os.mmap( // null, // total_size, // std.os.PROT_READ | std.os.PROT_WRITE, // std.os.MAP_PRIVATE | std.os.MAP_ANONYMOUS, // -1, // 0, //) catch @panic("out of memory"); //std.os.mprotect(new_stack[0..std.mem.page_size], std.os.PROT_NONE) catch {}; //std.os.exit(@call(.{.stack = new_stack}, callMainWithArgs, .{argc, argv, envp})); } std.os.exit(@call(.{ .modifier = .always_inline }, callMainWithArgs, .{ argc, argv, envp })); } fn callMainWithArgs(argc: usize, argv: [*][*:0]u8, envp: [][*:0]u8) u8 { std.os.argv = argv[0..argc]; std.os.environ = envp; std.debug.maybeEnableSegfaultHandler(); return initEventLoopAndCallMain(); } fn main(c_argc: i32, c_argv: [*][*:0]u8, c_envp: [*:null]?[*:0]u8) callconv(.C) i32 { var env_count: usize = 0; while (c_envp[env_count] != null) : (env_count += 1) {} const envp = @ptrCast([*][*:0]u8, c_envp)[0..env_count]; return @call(.{ .modifier = .always_inline }, callMainWithArgs, .{ @intCast(usize, c_argc), c_argv, envp }); } // General error message for a malformed return type const bad_main_ret = "expected return type of main to be 'void', '!void', 'noreturn', 'u8', or '!u8'"; // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. inline fn initEventLoopAndCallMain() u8 { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { std.log.err("{}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return 1; }; defer loop.deinit(); var result: u8 = undefined; var frame: @Frame(callMainAsync) = undefined; _ = @asyncCall(&frame, &result, callMainAsync, .{loop}); loop.run(); return result; } } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. return @call(.{ .modifier = .always_inline }, callMain, .{}); } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. // TODO This function is duplicated from initEventLoopAndCallMain instead of using generics // because it is working around stage1 compiler bugs. inline fn initEventLoopAndCallWinMain() std.os.windows.INT { if (std.event.Loop.instance) |loop| { if (!@hasDecl(root, "event_loop")) { loop.init() catch |err| { std.log.err("{}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return 1; }; defer loop.deinit(); var result: u8 = undefined; var frame: @Frame(callMainAsync) = undefined; _ = @asyncCall(&frame, &result, callMainAsync, .{loop}); loop.run(); return result; } } // This is marked inline because for some reason LLVM in release mode fails to inline it, // and we want fewer call frames in stack traces. return @call(.{ .modifier = .always_inline }, call_wWinMain, .{}); } fn callMainAsync(loop: *std.event.Loop) callconv(.Async) u8 { // This prevents the event loop from terminating at least until main() has returned. // TODO This shouldn't be needed here; it should be in the event loop code. loop.beginOneEvent(); defer loop.finishOneEvent(); return callMain(); } // This is not marked inline because it is called with @asyncCall when // there is an event loop. pub fn callMain() u8 { 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.signedness == .signed) { @compileError(bad_main_ret); } return root.main(); }, .ErrorUnion => { const result = root.main() catch |err| { std.log.err("{}", .{@errorName(err)}); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } return 1; }; switch (@typeInfo(@TypeOf(result))) { .Void => return 0, .Int => |info| { if (info.bits != 8 or info.signedness == .signed) { @compileError(bad_main_ret); } return result; }, else => @compileError(bad_main_ret), } }, else => @compileError(bad_main_ret), } } pub fn call_wWinMain() std.os.windows.INT { const MAIN_HINSTANCE = @typeInfo(@TypeOf(root.wWinMain)).Fn.args[0].arg_type.?; const hInstance = @ptrCast(MAIN_HINSTANCE, std.os.windows.kernel32.GetModuleHandleW(null).?); const lpCmdLine = std.os.windows.kernel32.GetCommandLineW(); // There's no (documented) way to get the nCmdShow parameter, so we're // using this fairly standard default. const nCmdShow = std.os.windows.user32.SW_SHOW; // second parameter hPrevInstance, MSDN: "This parameter is always NULL" return root.wWinMain(hInstance, null, lpCmdLine, nCmdShow); }
lib/std/start.zig
const std = @import("std"); pub const Token = @This(); pub const Op = @import("./token/op.zig").Op; pub const Kwd = @import("./token/kw.zig").Kwd; pub const Symbol = @import("./token/sym.zig"); pub const Tag = Symbol.Tag; pub const Val = Symbol.Val; const Ast = @import("./Ast.zig"); const Parser = @import("./Parser.zig"); pos: usize, ty: Token.Type = .start, pub fn start() Token { return Token{ .pos = 0, .ty = Token.Type.start}; } pub fn end() Token { return Token{ .pos = 0, .ty = Token.Type.end}; } pub fn symb(pos: usize, symbl: Symbol) Token { return Token { .pos = pos, .ty = Token.Type{.sym = symbl}}; } // pub fn tag(pos: usize, comptime t: Tag) Token { // return Token { .pos = pos, .ty = Type{.sym = Symbol.fromTag(t)}}; // } pub fn val(pos: usize, comptime valu: Val) Token { return Token { .pos = pos, .ty = Type{.sym = Symbol.fromVal(valu)}}; } pub fn op(pos: usize, opr: Op) Token { return Token { .pos = pos, .ty = Token.Type{.op = opr}}; } pub fn print(token: Token) void { var value: []const u8 = ""; var val_tag: []const u8 = ""; switch (token.ty) { .sym => |s| if (s.val) |vl| { value = vl.valStr(); val_tag = vl.tagStr(); }, else => {} } const fstr = "\x1b[32;1mToken \x1b[0m[\x1b[32mpos:\x1b[0m {d}, \x1b[33mtype:\x1b[0m {s}, \x1b[34mval:\x1b[0m ({s} = {s})]"; const args = .{ token.pos, @tagName(token.ty), val_tag, value}; var bf: [4096]u8 = undefined; var res = std.fmt.bufPrint(&bf, fstr, args) catch ""; // std.fmt.allocPrint(std.testing.allocator, fstr, args) catch std.debug.print(fstr, args); std.io.getStdOut().writer().writeAll(res) catch std.debug.print("{s}", .{res}); } pub const Type = union(enum) { op: Op, kwd: Kwd, sym: Symbol, start, end, unknown, }; pub const Lexer = struct { inp: []const u8 = "", }; pub const Loc = struct { row: usize, col: usize, }; pub const Span = struct { start: usize, end: usize, };
lib/idla/src/Token.zig
const std = @import("../../std.zig"); const math = std.math; const Limb = std.math.big.Limb; const limb_bits = @typeInfo(Limb).Int.bits; const DoubleLimb = std.math.big.DoubleLimb; const SignedDoubleLimb = std.math.big.SignedDoubleLimb; const Log2Limb = std.math.big.Log2Limb; const Allocator = std.mem.Allocator; const mem = std.mem; const maxInt = std.math.maxInt; const minInt = std.math.minInt; const assert = std.debug.assert; const debug_safety = false; /// Returns the number of limbs needed to store `scalar`, which must be a /// primitive integer value. pub fn calcLimbLen(scalar: anytype) usize { const T = @TypeOf(scalar); switch (@typeInfo(T)) { .Int => |info| { const UT = if (info.is_signed) std.meta.Int(false, info.bits - 1) else T; return @sizeOf(UT) / @sizeOf(Limb); }, .ComptimeInt => { const w_value = if (scalar < 0) -scalar else scalar; return @divFloor(math.log2(w_value), limb_bits) + 1; }, else => @compileError("parameter must be a primitive integer type"), } } pub fn calcToStringLimbsBufferLen(a_len: usize, base: u8) usize { if (math.isPowerOfTwo(base)) return 0; return a_len + 2 + a_len + calcDivLimbsBufferLen(a_len, 1); } pub fn calcDivLimbsBufferLen(a_len: usize, b_len: usize) usize { return calcMulLimbsBufferLen(a_len, b_len, 2) * 4; } pub fn calcMulLimbsBufferLen(a_len: usize, b_len: usize, aliases: usize) usize { return aliases * math.max(a_len, b_len); } pub fn calcSetStringLimbsBufferLen(base: u8, string_len: usize) usize { const limb_count = calcSetStringLimbCount(base, string_len); return calcMulLimbsBufferLen(limb_count, limb_count, 2); } pub fn calcSetStringLimbCount(base: u8, string_len: usize) usize { return (string_len + (limb_bits / base - 1)) / (limb_bits / base); } pub fn calcPowLimbsBufferLen(a_bit_count: usize, y: usize) usize { // The 2 accounts for the minimum space requirement for llmulacc return 2 + (a_bit_count * y + (limb_bits - 1)) / limb_bits; } /// a + b * c + *carry, sets carry to the overflow bits pub fn addMulLimbWithCarry(a: Limb, b: Limb, c: Limb, carry: *Limb) Limb { @setRuntimeSafety(debug_safety); var r1: Limb = undefined; // r1 = a + *carry const c1: Limb = @boolToInt(@addWithOverflow(Limb, a, carry.*, &r1)); // r2 = b * c const bc = @as(DoubleLimb, math.mulWide(Limb, b, c)); const r2 = @truncate(Limb, bc); const c2 = @truncate(Limb, bc >> limb_bits); // r1 = r1 + r2 const c3: Limb = @boolToInt(@addWithOverflow(Limb, r1, r2, &r1)); // This never overflows, c1, c3 are either 0 or 1 and if both are 1 then // c2 is at least <= maxInt(Limb) - 2. carry.* = c1 + c2 + c3; return r1; } /// A arbitrary-precision big integer, with a fixed set of mutable limbs. pub const Mutable = struct { /// Raw digits. These are: /// /// * Little-endian ordered /// * limbs.len >= 1 /// * Zero is represented as limbs.len == 1 with limbs[0] == 0. /// /// Accessing limbs directly should be avoided. /// These are allocated limbs; the `len` field tells the valid range. limbs: []Limb, len: usize, positive: bool, pub fn toConst(self: Mutable) Const { return .{ .limbs = self.limbs[0..self.len], .positive = self.positive, }; } /// Asserts that the allocator owns the limbs memory. If this is not the case, /// use `toConst().toManaged()`. pub fn toManaged(self: Mutable, allocator: *Allocator) Managed { return .{ .allocator = allocator, .limbs = self.limbs, .metadata = if (self.positive) self.len & ~Managed.sign_bit else self.len | Managed.sign_bit, }; } /// `value` is a primitive integer type. /// Asserts the value fits within the provided `limbs_buffer`. /// Note: `calcLimbLen` can be used to figure out how big an array to allocate for `limbs_buffer`. pub fn init(limbs_buffer: []Limb, value: anytype) Mutable { limbs_buffer[0] = 0; var self: Mutable = .{ .limbs = limbs_buffer, .len = 1, .positive = true, }; self.set(value); return self; } /// Copies the value of a Const to an existing Mutable so that they both have the same value. /// Asserts the value fits in the limbs buffer. pub fn copy(self: *Mutable, other: Const) void { if (self.limbs.ptr != other.limbs.ptr) { mem.copy(Limb, self.limbs[0..], other.limbs[0..other.limbs.len]); } self.positive = other.positive; self.len = other.limbs.len; } /// Efficiently swap an Mutable with another. This swaps the limb pointers and a full copy is not /// performed. The address of the limbs field will not be the same after this function. pub fn swap(self: *Mutable, other: *Mutable) void { mem.swap(Mutable, self, other); } pub fn dump(self: Mutable) void { for (self.limbs[0..self.len]) |limb| { std.debug.warn("{x} ", .{limb}); } std.debug.warn("capacity={} positive={}\n", .{ self.limbs.len, self.positive }); } /// Clones an Mutable and returns a new Mutable with the same value. The new Mutable is a deep copy and /// can be modified separately from the original. /// Asserts that limbs is big enough to store the value. pub fn clone(other: Mutable, limbs: []Limb) Mutable { mem.copy(Limb, limbs, other.limbs[0..other.len]); return .{ .limbs = limbs, .len = other.len, .positive = other.positive, }; } pub fn negate(self: *Mutable) void { self.positive = !self.positive; } /// Modify to become the absolute value pub fn abs(self: *Mutable) void { self.positive = true; } /// Sets the Mutable to value. Value must be an primitive integer type. /// Asserts the value fits within the limbs buffer. /// Note: `calcLimbLen` can be used to figure out how big the limbs buffer /// needs to be to store a specific value. pub fn set(self: *Mutable, value: anytype) void { const T = @TypeOf(value); switch (@typeInfo(T)) { .Int => |info| { const UT = if (info.is_signed) std.meta.Int(false, info.bits - 1) else T; const needed_limbs = @sizeOf(UT) / @sizeOf(Limb); assert(needed_limbs <= self.limbs.len); // value too big self.len = 0; self.positive = value >= 0; var w_value: UT = if (value < 0) @intCast(UT, -value) else @intCast(UT, value); if (info.bits <= limb_bits) { self.limbs[0] = @as(Limb, w_value); self.len += 1; } else { var i: usize = 0; while (w_value != 0) : (i += 1) { self.limbs[i] = @truncate(Limb, w_value); self.len += 1; // TODO: shift == 64 at compile-time fails. Fails on u128 limbs. w_value >>= limb_bits / 2; w_value >>= limb_bits / 2; } } }, .ComptimeInt => { comptime var w_value = if (value < 0) -value else value; const req_limbs = @divFloor(math.log2(w_value), limb_bits) + 1; assert(req_limbs <= self.limbs.len); // value too big self.len = req_limbs; self.positive = value >= 0; if (w_value <= maxInt(Limb)) { self.limbs[0] = w_value; } else { const mask = (1 << limb_bits) - 1; comptime var i = 0; inline while (w_value != 0) : (i += 1) { self.limbs[i] = w_value & mask; w_value >>= limb_bits / 2; w_value >>= limb_bits / 2; } } }, else => @compileError("cannot set Mutable using type " ++ @typeName(T)), } } /// Set self from the string representation `value`. /// /// `value` must contain only digits <= `base` and is case insensitive. Base prefixes are /// not allowed (e.g. 0x43 should simply be 43). Underscores in the input string are /// ignored and can be used as digit separators. /// /// Asserts there is enough memory for the value in `self.limbs`. An upper bound on number of limbs can /// be determined with `calcSetStringLimbCount`. /// Asserts the base is in the range [2, 16]. /// /// Returns an error if the value has invalid digits for the requested base. /// /// `limbs_buffer` is used for temporary storage. The size required can be found with /// `calcSetStringLimbsBufferLen`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn setString( self: *Mutable, base: u8, value: []const u8, limbs_buffer: []Limb, allocator: ?*Allocator, ) error{InvalidCharacter}!void { assert(base >= 2 and base <= 16); var i: usize = 0; var positive = true; if (value.len > 0 and value[0] == '-') { positive = false; i += 1; } const ap_base: Const = .{ .limbs = &[_]Limb{base}, .positive = true }; self.set(0); for (value[i..]) |ch| { if (ch == '_') { continue; } const d = try std.fmt.charToDigit(ch, base); const ap_d: Const = .{ .limbs = &[_]Limb{d}, .positive = true }; self.mul(self.toConst(), ap_base, limbs_buffer, allocator); self.add(self.toConst(), ap_d); } self.positive = positive; } /// r = a + scalar /// /// r and a may be aliases. /// scalar is a primitive integer type. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `math.max(a.limbs.len, calcLimbLen(scalar)) + 1`. pub fn addScalar(r: *Mutable, a: Const, scalar: anytype) void { var limbs: [calcLimbLen(scalar)]Limb = undefined; const operand = init(&limbs, scalar).toConst(); return add(r, a, operand); } /// r = a + b /// /// r, a and b may be aliases. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. pub fn add(r: *Mutable, a: Const, b: Const) void { if (a.eqZero()) { r.copy(b); return; } else if (b.eqZero()) { r.copy(a); return; } if (a.limbs.len == 1 and b.limbs.len == 1 and a.positive == b.positive) { if (!@addWithOverflow(Limb, a.limbs[0], b.limbs[0], &r.limbs[0])) { r.len = 1; r.positive = a.positive; return; } } if (a.positive != b.positive) { if (a.positive) { // (a) + (-b) => a - b r.sub(a, b.abs()); } else { // (-a) + (b) => b - a r.sub(b, a.abs()); } } else { if (a.limbs.len >= b.limbs.len) { lladd(r.limbs[0..], a.limbs[0..a.limbs.len], b.limbs[0..b.limbs.len]); r.normalize(a.limbs.len + 1); } else { lladd(r.limbs[0..], b.limbs[0..b.limbs.len], a.limbs[0..a.limbs.len]); r.normalize(b.limbs.len + 1); } r.positive = a.positive; } } /// r = a - b /// /// r, a and b may be aliases. /// /// Asserts the result fits in `r`. An upper bound on the number of limbs needed by /// r is `math.max(a.limbs.len, b.limbs.len) + 1`. The +1 is not needed if both operands are positive. pub fn sub(r: *Mutable, a: Const, b: Const) void { if (a.positive != b.positive) { if (a.positive) { // (a) - (-b) => a + b r.add(a, b.abs()); } else { // (-a) - (b) => -(a + b) r.add(a.abs(), b); r.positive = false; } } else { if (a.positive) { // (a) - (b) => a - b if (a.order(b) != .lt) { llsub(r.limbs[0..], a.limbs[0..a.limbs.len], b.limbs[0..b.limbs.len]); r.normalize(a.limbs.len); r.positive = true; } else { llsub(r.limbs[0..], b.limbs[0..b.limbs.len], a.limbs[0..a.limbs.len]); r.normalize(b.limbs.len); r.positive = false; } } else { // (-a) - (-b) => -(a - b) if (a.order(b) == .lt) { llsub(r.limbs[0..], a.limbs[0..a.limbs.len], b.limbs[0..b.limbs.len]); r.normalize(a.limbs.len); r.positive = false; } else { llsub(r.limbs[0..], b.limbs[0..b.limbs.len], a.limbs[0..a.limbs.len]); r.normalize(b.limbs.len); r.positive = true; } } } } /// rma = a * b /// /// `rma` may alias with `a` or `b`. /// `a` and `b` may alias with each other. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `a.limbs.len + b.limbs.len + 1`. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcMulLimbsBufferLen`. pub fn mul(rma: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?*Allocator) void { var buf_index: usize = 0; const a_copy = if (rma.limbs.ptr == a.limbs.ptr) blk: { const start = buf_index; mem.copy(Limb, limbs_buffer[buf_index..], a.limbs); buf_index += a.limbs.len; break :blk a.toMutable(limbs_buffer[start..buf_index]).toConst(); } else a; const b_copy = if (rma.limbs.ptr == b.limbs.ptr) blk: { const start = buf_index; mem.copy(Limb, limbs_buffer[buf_index..], b.limbs); buf_index += b.limbs.len; break :blk b.toMutable(limbs_buffer[start..buf_index]).toConst(); } else b; return rma.mulNoAlias(a_copy, b_copy, allocator); } /// rma = a * b /// /// `rma` may not alias with `a` or `b`. /// `a` and `b` may alias with each other. /// /// Asserts the result fits in `rma`. An upper bound on the number of limbs needed by /// rma is given by `a.limbs.len + b.limbs.len + 1`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. pub fn mulNoAlias(rma: *Mutable, a: Const, b: Const, allocator: ?*Allocator) void { assert(rma.limbs.ptr != a.limbs.ptr); // illegal aliasing assert(rma.limbs.ptr != b.limbs.ptr); // illegal aliasing if (a.limbs.len == 1 and b.limbs.len == 1) { if (!@mulWithOverflow(Limb, a.limbs[0], b.limbs[0], &rma.limbs[0])) { rma.len = 1; rma.positive = (a.positive == b.positive); return; } } mem.set(Limb, rma.limbs[0 .. a.limbs.len + b.limbs.len + 1], 0); llmulacc(allocator, rma.limbs, a.limbs, b.limbs); rma.normalize(a.limbs.len + b.limbs.len); rma.positive = (a.positive == b.positive); } /// q = a / b (rem r) /// /// a / b are floored (rounded towards 0). /// q may alias with a or b. /// /// Asserts there is enough memory to store q and r. /// The upper bound for r limb count is a.limbs.len. /// The upper bound for q limb count is given by `a.limbs.len + b.limbs.len + 1`. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcDivLimbsBufferLen`. pub fn divFloor( q: *Mutable, r: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?*Allocator, ) void { div(q, r, a, b, limbs_buffer, allocator); // Trunc -> Floor. if (!q.positive) { const one: Const = .{ .limbs = &[_]Limb{1}, .positive = true }; q.sub(q.toConst(), one); r.add(q.toConst(), one); } r.positive = b.positive; } /// q = a / b (rem r) /// /// a / b are truncated (rounded towards -inf). /// q may alias with a or b. /// /// Asserts there is enough memory to store q and r. /// The upper bound for r limb count is a.limbs.len. /// The upper bound for q limb count is given by `calcQuotientLimbLen`. This accounts /// for temporary space used by the division algorithm. /// /// If `allocator` is provided, it will be used for temporary storage to improve /// multiplication performance. `error.OutOfMemory` is handled with a fallback algorithm. /// /// `limbs_buffer` is used for temporary storage. The amount required is given by `calcDivLimbsBufferLen`. pub fn divTrunc( q: *Mutable, r: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?*Allocator, ) void { div(q, r, a, b, limbs_buffer, allocator); r.positive = a.positive; } /// r = a << shift, in other words, r = a * 2^shift /// /// r and a may alias. /// /// Asserts there is enough memory to fit the result. The upper bound Limb count is /// `a.limbs.len + (shift / (@sizeOf(Limb) * 8))`. pub fn shiftLeft(r: *Mutable, a: Const, shift: usize) void { llshl(r.limbs[0..], a.limbs[0..a.limbs.len], shift); r.normalize(a.limbs.len + (shift / limb_bits) + 1); r.positive = a.positive; } /// r = a >> shift /// r and a may alias. /// /// Asserts there is enough memory to fit the result. The upper bound Limb count is /// `a.limbs.len - (shift / (@sizeOf(Limb) * 8))`. pub fn shiftRight(r: *Mutable, a: Const, shift: usize) void { if (a.limbs.len <= shift / limb_bits) { r.len = 1; r.positive = true; r.limbs[0] = 0; return; } const r_len = llshr(r.limbs[0..], a.limbs[0..a.limbs.len], shift); r.len = a.limbs.len - (shift / limb_bits); r.positive = a.positive; } /// r = a | b /// r may alias with a or b. /// /// a and b are zero-extended to the longer of a or b. /// /// Asserts that r has enough limbs to store the result. Upper bound is `math.max(a.limbs.len, b.limbs.len)`. pub fn bitOr(r: *Mutable, a: Const, b: Const) void { if (a.limbs.len > b.limbs.len) { llor(r.limbs[0..], a.limbs[0..a.limbs.len], b.limbs[0..b.limbs.len]); r.len = a.limbs.len; } else { llor(r.limbs[0..], b.limbs[0..b.limbs.len], a.limbs[0..a.limbs.len]); r.len = b.limbs.len; } } /// r = a & b /// r may alias with a or b. /// /// Asserts that r has enough limbs to store the result. Upper bound is `math.min(a.limbs.len, b.limbs.len)`. pub fn bitAnd(r: *Mutable, a: Const, b: Const) void { if (a.limbs.len > b.limbs.len) { lland(r.limbs[0..], a.limbs[0..a.limbs.len], b.limbs[0..b.limbs.len]); r.normalize(b.limbs.len); } else { lland(r.limbs[0..], b.limbs[0..b.limbs.len], a.limbs[0..a.limbs.len]); r.normalize(a.limbs.len); } } /// r = a ^ b /// r may alias with a or b. /// /// Asserts that r has enough limbs to store the result. Upper bound is `math.max(a.limbs.len, b.limbs.len)`. pub fn bitXor(r: *Mutable, a: Const, b: Const) void { if (a.limbs.len > b.limbs.len) { llxor(r.limbs[0..], a.limbs[0..a.limbs.len], b.limbs[0..b.limbs.len]); r.normalize(a.limbs.len); } else { llxor(r.limbs[0..], b.limbs[0..b.limbs.len], a.limbs[0..a.limbs.len]); r.normalize(b.limbs.len); } } /// rma may alias x or y. /// x and y may alias each other. /// Asserts that `rma` has enough limbs to store the result. Upper bound is /// `math.min(x.limbs.len, y.limbs.len)`. /// /// `limbs_buffer` is used for temporary storage during the operation. When this function returns, /// it will have the same length as it had when the function was called. pub fn gcd(rma: *Mutable, x: Const, y: Const, limbs_buffer: *std.ArrayList(Limb)) !void { const prev_len = limbs_buffer.items.len; defer limbs_buffer.shrink(prev_len); const x_copy = if (rma.limbs.ptr == x.limbs.ptr) blk: { const start = limbs_buffer.items.len; try limbs_buffer.appendSlice(x.limbs); break :blk x.toMutable(limbs_buffer.items[start..]).toConst(); } else x; const y_copy = if (rma.limbs.ptr == y.limbs.ptr) blk: { const start = limbs_buffer.items.len; try limbs_buffer.appendSlice(y.limbs); break :blk y.toMutable(limbs_buffer.items[start..]).toConst(); } else y; return gcdLehmer(rma, x_copy, y_copy, limbs_buffer); } /// q = a ^ b /// /// r may not alias a. /// /// Asserts that `r` has enough limbs to store the result. Upper bound is /// `calcPowLimbsBufferLen(a.bitCountAbs(), b)`. /// /// `limbs_buffer` is used for temporary storage. /// The amount required is given by `calcPowLimbsBufferLen`. pub fn pow(r: *Mutable, a: Const, b: u32, limbs_buffer: []Limb) !void { assert(r.limbs.ptr != a.limbs.ptr); // illegal aliasing // Handle all the trivial cases first switch (b) { 0 => { // a^0 = 1 return r.set(1); }, 1 => { // a^1 = a return r.copy(a); }, else => {}, } if (a.eqZero()) { // 0^b = 0 return r.set(0); } else if (a.limbs.len == 1 and a.limbs[0] == 1) { // 1^b = 1 and -1^b = ±1 r.set(1); r.positive = a.positive or (b & 1) == 0; return; } // Here a>1 and b>1 const needed_limbs = calcPowLimbsBufferLen(a.bitCountAbs(), b); assert(r.limbs.len >= needed_limbs); assert(limbs_buffer.len >= needed_limbs); llpow(r.limbs, a.limbs, b, limbs_buffer); r.normalize(needed_limbs); r.positive = a.positive or (b & 1) == 0; } /// rma may not alias x or y. /// x and y may alias each other. /// Asserts that `rma` has enough limbs to store the result. Upper bound is given by `calcGcdNoAliasLimbLen`. /// /// `limbs_buffer` is used for temporary storage during the operation. pub fn gcdNoAlias(rma: *Mutable, x: Const, y: Const, limbs_buffer: *std.ArrayList(Limb)) !void { assert(rma.limbs.ptr != x.limbs.ptr); // illegal aliasing assert(rma.limbs.ptr != y.limbs.ptr); // illegal aliasing return gcdLehmer(rma, x, y, allocator); } fn gcdLehmer(result: *Mutable, xa: Const, ya: Const, limbs_buffer: *std.ArrayList(Limb)) !void { var x = try xa.toManaged(limbs_buffer.allocator); defer x.deinit(); x.abs(); var y = try ya.toManaged(limbs_buffer.allocator); defer y.deinit(); y.abs(); if (x.toConst().order(y.toConst()) == .lt) { x.swap(&y); } var t_big = try Managed.init(limbs_buffer.allocator); defer t_big.deinit(); var r = try Managed.init(limbs_buffer.allocator); defer r.deinit(); var tmp_x = try Managed.init(limbs_buffer.allocator); defer tmp_x.deinit(); while (y.len() > 1) { assert(x.isPositive() and y.isPositive()); assert(x.len() >= y.len()); var xh: SignedDoubleLimb = x.limbs[x.len() - 1]; var yh: SignedDoubleLimb = if (x.len() > y.len()) 0 else y.limbs[x.len() - 1]; var A: SignedDoubleLimb = 1; var B: SignedDoubleLimb = 0; var C: SignedDoubleLimb = 0; var D: SignedDoubleLimb = 1; while (yh + C != 0 and yh + D != 0) { const q = @divFloor(xh + A, yh + C); const qp = @divFloor(xh + B, yh + D); if (q != qp) { break; } var t = A - q * C; A = C; C = t; t = B - q * D; B = D; D = t; t = xh - q * yh; xh = yh; yh = t; } if (B == 0) { // t_big = x % y, r is unused try r.divTrunc(&t_big, x.toConst(), y.toConst()); assert(t_big.isPositive()); x.swap(&y); y.swap(&t_big); } else { var storage: [8]Limb = undefined; const Ap = fixedIntFromSignedDoubleLimb(A, storage[0..2]).toConst(); const Bp = fixedIntFromSignedDoubleLimb(B, storage[2..4]).toConst(); const Cp = fixedIntFromSignedDoubleLimb(C, storage[4..6]).toConst(); const Dp = fixedIntFromSignedDoubleLimb(D, storage[6..8]).toConst(); // t_big = Ax + By try r.mul(x.toConst(), Ap); try t_big.mul(y.toConst(), Bp); try t_big.add(r.toConst(), t_big.toConst()); // u = Cx + Dy, r as u try tmp_x.copy(x.toConst()); try x.mul(tmp_x.toConst(), Cp); try r.mul(y.toConst(), Dp); try r.add(x.toConst(), r.toConst()); x.swap(&t_big); y.swap(&r); } } // euclidean algorithm assert(x.toConst().order(y.toConst()) != .lt); while (!y.toConst().eqZero()) { try t_big.divTrunc(&r, x.toConst(), y.toConst()); x.swap(&y); y.swap(&r); } result.copy(x.toConst()); } /// Truncates by default. fn div(quo: *Mutable, rem: *Mutable, a: Const, b: Const, limbs_buffer: []Limb, allocator: ?*Allocator) void { assert(!b.eqZero()); // division by zero assert(quo != rem); // illegal aliasing if (a.orderAbs(b) == .lt) { // quo may alias a so handle rem first rem.copy(a); rem.positive = a.positive == b.positive; quo.positive = true; quo.len = 1; quo.limbs[0] = 0; return; } // Handle trailing zero-words of divisor/dividend. These are not handled in the following // algorithms. const a_zero_limb_count = blk: { var i: usize = 0; while (i < a.limbs.len) : (i += 1) { if (a.limbs[i] != 0) break; } break :blk i; }; const b_zero_limb_count = blk: { var i: usize = 0; while (i < b.limbs.len) : (i += 1) { if (b.limbs[i] != 0) break; } break :blk i; }; const ab_zero_limb_count = math.min(a_zero_limb_count, b_zero_limb_count); if (b.limbs.len - ab_zero_limb_count == 1) { lldiv1(quo.limbs[0..], &rem.limbs[0], a.limbs[ab_zero_limb_count..a.limbs.len], b.limbs[b.limbs.len - 1]); quo.normalize(a.limbs.len - ab_zero_limb_count); quo.positive = (a.positive == b.positive); rem.len = 1; rem.positive = true; } else { // x and y are modified during division const sep_len = calcMulLimbsBufferLen(a.limbs.len, b.limbs.len, 2); const x_limbs = limbs_buffer[0 * sep_len ..][0..sep_len]; const y_limbs = limbs_buffer[1 * sep_len ..][0..sep_len]; const t_limbs = limbs_buffer[2 * sep_len ..][0..sep_len]; const mul_limbs_buf = limbs_buffer[3 * sep_len ..][0..sep_len]; var x: Mutable = .{ .limbs = x_limbs, .positive = a.positive, .len = a.limbs.len - ab_zero_limb_count, }; var y: Mutable = .{ .limbs = y_limbs, .positive = b.positive, .len = b.limbs.len - ab_zero_limb_count, }; // Shrink x, y such that the trailing zero limbs shared between are removed. mem.copy(Limb, x.limbs, a.limbs[ab_zero_limb_count..a.limbs.len]); mem.copy(Limb, y.limbs, b.limbs[ab_zero_limb_count..b.limbs.len]); divN(quo, rem, &x, &y, t_limbs, mul_limbs_buf, allocator); quo.positive = (a.positive == b.positive); } if (ab_zero_limb_count != 0) { rem.shiftLeft(rem.toConst(), ab_zero_limb_count * limb_bits); } } /// Handbook of Applied Cryptography, 14.20 /// /// x = qy + r where 0 <= r < y fn divN( q: *Mutable, r: *Mutable, x: *Mutable, y: *Mutable, tmp_limbs: []Limb, mul_limb_buf: []Limb, allocator: ?*Allocator, ) void { assert(y.len >= 2); assert(x.len >= y.len); assert(q.limbs.len >= x.len + y.len - 1); // See 3.2 var backup_tmp_limbs: [3]Limb = undefined; const t_limbs = if (tmp_limbs.len < 3) &backup_tmp_limbs else tmp_limbs; var tmp: Mutable = .{ .limbs = t_limbs, .len = 1, .positive = true, }; tmp.limbs[0] = 0; // Normalize so y > limb_bits / 2 (i.e. leading bit is set) and even var norm_shift = @clz(Limb, y.limbs[y.len - 1]); if (norm_shift == 0 and y.toConst().isOdd()) { norm_shift = limb_bits; } x.shiftLeft(x.toConst(), norm_shift); y.shiftLeft(y.toConst(), norm_shift); const n = x.len - 1; const t = y.len - 1; // 1. q.len = n - t + 1; q.positive = true; mem.set(Limb, q.limbs[0..q.len], 0); // 2. tmp.shiftLeft(y.toConst(), limb_bits * (n - t)); while (x.toConst().order(tmp.toConst()) != .lt) { q.limbs[n - t] += 1; x.sub(x.toConst(), tmp.toConst()); } // 3. var i = n; while (i > t) : (i -= 1) { // 3.1 if (x.limbs[i] == y.limbs[t]) { q.limbs[i - t - 1] = maxInt(Limb); } else { const num = (@as(DoubleLimb, x.limbs[i]) << limb_bits) | @as(DoubleLimb, x.limbs[i - 1]); const z = @intCast(Limb, num / @as(DoubleLimb, y.limbs[t])); q.limbs[i - t - 1] = if (z > maxInt(Limb)) maxInt(Limb) else @as(Limb, z); } // 3.2 tmp.limbs[0] = if (i >= 2) x.limbs[i - 2] else 0; tmp.limbs[1] = if (i >= 1) x.limbs[i - 1] else 0; tmp.limbs[2] = x.limbs[i]; tmp.normalize(3); while (true) { // 2x1 limb multiplication unrolled against single-limb q[i-t-1] var carry: Limb = 0; r.limbs[0] = addMulLimbWithCarry(0, if (t >= 1) y.limbs[t - 1] else 0, q.limbs[i - t - 1], &carry); r.limbs[1] = addMulLimbWithCarry(0, y.limbs[t], q.limbs[i - t - 1], &carry); r.limbs[2] = carry; r.normalize(3); if (r.toConst().orderAbs(tmp.toConst()) != .gt) { break; } q.limbs[i - t - 1] -= 1; } // 3.3 tmp.set(q.limbs[i - t - 1]); tmp.mul(tmp.toConst(), y.toConst(), mul_limb_buf, allocator); tmp.shiftLeft(tmp.toConst(), limb_bits * (i - t - 1)); x.sub(x.toConst(), tmp.toConst()); if (!x.positive) { tmp.shiftLeft(y.toConst(), limb_bits * (i - t - 1)); x.add(x.toConst(), tmp.toConst()); q.limbs[i - t - 1] -= 1; } } // Denormalize q.normalize(q.len); r.shiftRight(x.toConst(), norm_shift); r.normalize(r.len); } /// Normalize a possible sequence of leading zeros. /// /// [1, 2, 3, 4, 0] -> [1, 2, 3, 4] /// [1, 2, 0, 0, 0] -> [1, 2] /// [0, 0, 0, 0, 0] -> [0] fn normalize(r: *Mutable, length: usize) void { r.len = llnormalize(r.limbs[0..length]); } }; /// A arbitrary-precision big integer, with a fixed set of immutable limbs. pub const Const = struct { /// Raw digits. These are: /// /// * Little-endian ordered /// * limbs.len >= 1 /// * Zero is represented as limbs.len == 1 with limbs[0] == 0. /// /// Accessing limbs directly should be avoided. limbs: []const Limb, positive: bool, /// The result is an independent resource which is managed by the caller. pub fn toManaged(self: Const, allocator: *Allocator) Allocator.Error!Managed { const limbs = try allocator.alloc(Limb, math.max(Managed.default_capacity, self.limbs.len)); mem.copy(Limb, limbs, self.limbs); return Managed{ .allocator = allocator, .limbs = limbs, .metadata = if (self.positive) self.limbs.len & ~Managed.sign_bit else self.limbs.len | Managed.sign_bit, }; } /// Asserts `limbs` is big enough to store the value. pub fn toMutable(self: Const, limbs: []Limb) Mutable { mem.copy(Limb, limbs, self.limbs[0..self.limbs.len]); return .{ .limbs = limbs, .positive = self.positive, .len = self.limbs.len, }; } pub fn dump(self: Const) void { for (self.limbs[0..self.limbs.len]) |limb| { std.debug.warn("{x} ", .{limb}); } std.debug.warn("positive={}\n", .{self.positive}); } pub fn abs(self: Const) Const { return .{ .limbs = self.limbs, .positive = true, }; } pub fn isOdd(self: Const) bool { return self.limbs[0] & 1 != 0; } pub fn isEven(self: Const) bool { return !self.isOdd(); } /// Returns the number of bits required to represent the absolute value of an integer. pub fn bitCountAbs(self: Const) usize { return (self.limbs.len - 1) * limb_bits + (limb_bits - @clz(Limb, self.limbs[self.limbs.len - 1])); } /// Returns the number of bits required to represent the integer in twos-complement form. /// /// If the integer is negative the value returned is the number of bits needed by a signed /// integer to represent the value. If positive the value is the number of bits for an /// unsigned integer. Any unsigned integer will fit in the signed integer with bitcount /// one greater than the returned value. /// /// e.g. -127 returns 8 as it will fit in an i8. 127 returns 7 since it fits in a u7. pub fn bitCountTwosComp(self: Const) usize { var bits = self.bitCountAbs(); // If the entire value has only one bit set (e.g. 0b100000000) then the negation in twos // complement requires one less bit. if (!self.positive) block: { bits += 1; if (@popCount(Limb, self.limbs[self.limbs.len - 1]) == 1) { for (self.limbs[0 .. self.limbs.len - 1]) |limb| { if (@popCount(Limb, limb) != 0) { break :block; } } bits -= 1; } } return bits; } pub fn fitsInTwosComp(self: Const, is_signed: bool, bit_count: usize) bool { if (self.eqZero()) { return true; } if (!is_signed and !self.positive) { return false; } const req_bits = self.bitCountTwosComp() + @boolToInt(self.positive and is_signed); return bit_count >= req_bits; } /// Returns whether self can fit into an integer of the requested type. pub fn fits(self: Const, comptime T: type) bool { const info = @typeInfo(T).Int; return self.fitsInTwosComp(info.is_signed, info.bits); } /// Returns the approximate size of the integer in the given base. Negative values accommodate for /// the minus sign. This is used for determining the number of characters needed to print the /// value. It is inexact and may exceed the given value by ~1-2 bytes. /// TODO See if we can make this exact. pub fn sizeInBaseUpperBound(self: Const, base: usize) usize { const bit_count = @as(usize, @boolToInt(!self.positive)) + self.bitCountAbs(); return (bit_count / math.log2(base)) + 2; } pub const ConvertError = error{ NegativeIntoUnsigned, TargetTooSmall, }; /// Convert self to type T. /// /// Returns an error if self cannot be narrowed into the requested type without truncation. pub fn to(self: Const, comptime T: type) ConvertError!T { switch (@typeInfo(T)) { .Int => |info| { const UT = std.meta.Int(false, info.bits); if (self.bitCountTwosComp() > info.bits) { return error.TargetTooSmall; } var r: UT = 0; if (@sizeOf(UT) <= @sizeOf(Limb)) { r = @intCast(UT, self.limbs[0]); } else { for (self.limbs[0..self.limbs.len]) |_, ri| { const limb = self.limbs[self.limbs.len - ri - 1]; r <<= limb_bits; r |= limb; } } if (!info.is_signed) { return if (self.positive) @intCast(T, r) else error.NegativeIntoUnsigned; } else { if (self.positive) { return @intCast(T, r); } else { if (math.cast(T, r)) |ok| { return -ok; } else |_| { return minInt(T); } } } }, else => @compileError("cannot convert Const to type " ++ @typeName(T)), } } /// To allow `std.fmt.format` to work with this type. /// If the integer is larger than `pow(2, 64 * @sizeOf(usize) * 8), this function will fail /// to print the string, printing "(BigInt)" instead of a number. /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory. /// See `toString` and `toStringAlloc` for a way to print big integers without failure. pub fn format( self: Const, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { comptime var radix = 10; comptime var uppercase = false; if (fmt.len == 0 or comptime mem.eql(u8, fmt, "d")) { radix = 10; uppercase = false; } else if (comptime mem.eql(u8, fmt, "b")) { radix = 2; uppercase = false; } else if (comptime mem.eql(u8, fmt, "x")) { radix = 16; uppercase = false; } else if (comptime mem.eql(u8, fmt, "X")) { radix = 16; uppercase = true; } else { @compileError("Unknown format string: '" ++ fmt ++ "'"); } var limbs: [128]Limb = undefined; const needed_limbs = calcDivLimbsBufferLen(self.limbs.len, 1); if (needed_limbs > limbs.len) return out_stream.writeAll("(BigInt)"); // This is the inverse of calcDivLimbsBufferLen const available_len = (limbs.len / 3) - 2; const biggest: Const = .{ .limbs = &([1]Limb{math.maxInt(Limb)} ** available_len), .positive = false, }; var buf: [biggest.sizeInBaseUpperBound(radix)]u8 = undefined; const len = self.toString(&buf, radix, uppercase, &limbs); return out_stream.writeAll(buf[0..len]); } /// Converts self to a string in the requested base. /// Caller owns returned memory. /// Asserts that `base` is in the range [2, 16]. /// See also `toString`, a lower level function than this. pub fn toStringAlloc(self: Const, allocator: *Allocator, base: u8, uppercase: bool) Allocator.Error![]u8 { assert(base >= 2); assert(base <= 16); if (self.eqZero()) { return allocator.dupe(u8, "0"); } const string = try allocator.alloc(u8, self.sizeInBaseUpperBound(base)); errdefer allocator.free(string); const limbs = try allocator.alloc(Limb, calcToStringLimbsBufferLen(self.limbs.len, base)); defer allocator.free(limbs); return allocator.shrink(string, self.toString(string, base, uppercase, limbs)); } /// Converts self to a string in the requested base. /// Asserts that `base` is in the range [2, 16]. /// `string` is a caller-provided slice of at least `sizeInBaseUpperBound` bytes, /// where the result is written to. /// Returns the length of the string. /// `limbs_buffer` is caller-provided memory for `toString` to use as a working area. It must have /// length of at least `calcToStringLimbsBufferLen`. /// In the case of power-of-two base, `limbs_buffer` is ignored. /// See also `toStringAlloc`, a higher level function than this. pub fn toString(self: Const, string: []u8, base: u8, uppercase: bool, limbs_buffer: []Limb) usize { assert(base >= 2); assert(base <= 16); if (self.eqZero()) { string[0] = '0'; return 1; } var digits_len: usize = 0; // Power of two: can do a single pass and use masks to extract digits. if (math.isPowerOfTwo(base)) { const base_shift = math.log2_int(Limb, base); outer: for (self.limbs[0..self.limbs.len]) |limb| { var shift: usize = 0; while (shift < limb_bits) : (shift += base_shift) { const r = @intCast(u8, (limb >> @intCast(Log2Limb, shift)) & @as(Limb, base - 1)); const ch = std.fmt.digitToChar(r, uppercase); string[digits_len] = ch; digits_len += 1; // If we hit the end, it must be all zeroes from here. if (digits_len == string.len) break :outer; } } // Always will have a non-zero digit somewhere. while (string[digits_len - 1] == '0') { digits_len -= 1; } } else { // Non power-of-two: batch divisions per word size. const digits_per_limb = math.log(Limb, base, maxInt(Limb)); var limb_base: Limb = 1; var j: usize = 0; while (j < digits_per_limb) : (j += 1) { limb_base *= base; } const b: Const = .{ .limbs = &[_]Limb{limb_base}, .positive = true }; var q: Mutable = .{ .limbs = limbs_buffer[0 .. self.limbs.len + 2], .positive = true, // Make absolute by ignoring self.positive. .len = self.limbs.len, }; mem.copy(Limb, q.limbs, self.limbs); var r: Mutable = .{ .limbs = limbs_buffer[q.limbs.len..][0..self.limbs.len], .positive = true, .len = 1, }; r.limbs[0] = 0; const rest_of_the_limbs_buf = limbs_buffer[q.limbs.len + r.limbs.len ..]; while (q.len >= 2) { // Passing an allocator here would not be helpful since this division is destroying // information, not creating it. [TODO citation needed] q.divTrunc(&r, q.toConst(), b, rest_of_the_limbs_buf, null); var r_word = r.limbs[0]; var i: usize = 0; while (i < digits_per_limb) : (i += 1) { const ch = std.fmt.digitToChar(@intCast(u8, r_word % base), uppercase); r_word /= base; string[digits_len] = ch; digits_len += 1; } } { assert(q.len == 1); var r_word = q.limbs[0]; while (r_word != 0) { const ch = std.fmt.digitToChar(@intCast(u8, r_word % base), uppercase); r_word /= base; string[digits_len] = ch; digits_len += 1; } } } if (!self.positive) { string[digits_len] = '-'; digits_len += 1; } const s = string[0..digits_len]; mem.reverse(u8, s); return s.len; } /// Returns `math.Order.lt`, `math.Order.eq`, `math.Order.gt` if /// `|a| < |b|`, `|a| == |b|`, or `|a| > |b|` respectively. pub fn orderAbs(a: Const, b: Const) math.Order { if (a.limbs.len < b.limbs.len) { return .lt; } if (a.limbs.len > b.limbs.len) { return .gt; } var i: usize = a.limbs.len - 1; while (i != 0) : (i -= 1) { if (a.limbs[i] != b.limbs[i]) { break; } } if (a.limbs[i] < b.limbs[i]) { return .lt; } else if (a.limbs[i] > b.limbs[i]) { return .gt; } else { return .eq; } } /// Returns `math.Order.lt`, `math.Order.eq`, `math.Order.gt` if `a < b`, `a == b` or `a > b` respectively. pub fn order(a: Const, b: Const) math.Order { if (a.positive != b.positive) { return if (a.positive) .gt else .lt; } else { const r = orderAbs(a, b); return if (a.positive) r else switch (r) { .lt => math.Order.gt, .eq => math.Order.eq, .gt => math.Order.lt, }; } } /// Same as `order` but the right-hand operand is a primitive integer. pub fn orderAgainstScalar(lhs: Const, scalar: anytype) math.Order { var limbs: [calcLimbLen(scalar)]Limb = undefined; const rhs = Mutable.init(&limbs, scalar); return order(lhs, rhs.toConst()); } /// Returns true if `a == 0`. pub fn eqZero(a: Const) bool { return a.limbs.len == 1 and a.limbs[0] == 0; } /// Returns true if `|a| == |b|`. pub fn eqAbs(a: Const, b: Const) bool { return orderAbs(a, b) == .eq; } /// Returns true if `a == b`. pub fn eq(a: Const, b: Const) bool { return order(a, b) == .eq; } }; /// An arbitrary-precision big integer along with an allocator which manages the memory. /// /// Memory is allocated as needed to ensure operations never overflow. The range /// is bounded only by available memory. pub const Managed = struct { pub const sign_bit: usize = 1 << (@typeInfo(usize).Int.bits - 1); /// Default number of limbs to allocate on creation of a `Managed`. pub const default_capacity = 4; /// Allocator used by the Managed when requesting memory. allocator: *Allocator, /// Raw digits. These are: /// /// * Little-endian ordered /// * limbs.len >= 1 /// * Zero is represent as Managed.len() == 1 with limbs[0] == 0. /// /// Accessing limbs directly should be avoided. limbs: []Limb, /// High bit is the sign bit. If set, Managed is negative, else Managed is positive. /// The remaining bits represent the number of limbs used by Managed. metadata: usize, /// Creates a new `Managed`. `default_capacity` limbs will be allocated immediately. /// The integer value after initializing is `0`. pub fn init(allocator: *Allocator) !Managed { return initCapacity(allocator, default_capacity); } pub fn toMutable(self: Managed) Mutable { return .{ .limbs = self.limbs, .positive = self.isPositive(), .len = self.len(), }; } pub fn toConst(self: Managed) Const { return .{ .limbs = self.limbs[0..self.len()], .positive = self.isPositive(), }; } /// Creates a new `Managed` with value `value`. /// /// This is identical to an `init`, followed by a `set`. pub fn initSet(allocator: *Allocator, value: anytype) !Managed { var s = try Managed.init(allocator); try s.set(value); return s; } /// Creates a new Managed with a specific capacity. If capacity < default_capacity then the /// default capacity will be used instead. /// The integer value after initializing is `0`. pub fn initCapacity(allocator: *Allocator, capacity: usize) !Managed { return Managed{ .allocator = allocator, .metadata = 1, .limbs = block: { const limbs = try allocator.alloc(Limb, math.max(default_capacity, capacity)); limbs[0] = 0; break :block limbs; }, }; } /// Returns the number of limbs currently in use. pub fn len(self: Managed) usize { return self.metadata & ~sign_bit; } /// Returns whether an Managed is positive. pub fn isPositive(self: Managed) bool { return self.metadata & sign_bit == 0; } /// Sets the sign of an Managed. pub fn setSign(self: *Managed, positive: bool) void { if (positive) { self.metadata &= ~sign_bit; } else { self.metadata |= sign_bit; } } /// Sets the length of an Managed. /// /// If setLen is used, then the Managed must be normalized to suit. pub fn setLen(self: *Managed, new_len: usize) void { self.metadata &= sign_bit; self.metadata |= new_len; } pub fn setMetadata(self: *Managed, positive: bool, length: usize) void { self.metadata = if (positive) length & ~sign_bit else length | sign_bit; } /// Ensures an Managed has enough space allocated for capacity limbs. If the Managed does not have /// sufficient capacity, the exact amount will be allocated. This occurs even if the requested /// capacity is only greater than the current capacity by one limb. pub fn ensureCapacity(self: *Managed, capacity: usize) !void { if (capacity <= self.limbs.len) { return; } self.limbs = try self.allocator.realloc(self.limbs, capacity); } /// Frees all associated memory. pub fn deinit(self: *Managed) void { self.allocator.free(self.limbs); self.* = undefined; } /// Returns a `Managed` with the same value. The returned `Managed` is a deep copy and /// can be modified separately from the original, and its resources are managed /// separately from the original. pub fn clone(other: Managed) !Managed { return other.cloneWithDifferentAllocator(other.allocator); } pub fn cloneWithDifferentAllocator(other: Managed, allocator: *Allocator) !Managed { return Managed{ .allocator = allocator, .metadata = other.metadata, .limbs = block: { var limbs = try allocator.alloc(Limb, other.len()); mem.copy(Limb, limbs[0..], other.limbs[0..other.len()]); break :block limbs; }, }; } /// Copies the value of the integer to an existing `Managed` so that they both have the same value. /// Extra memory will be allocated if the receiver does not have enough capacity. pub fn copy(self: *Managed, other: Const) !void { if (self.limbs.ptr == other.limbs.ptr) return; try self.ensureCapacity(other.limbs.len); mem.copy(Limb, self.limbs[0..], other.limbs[0..other.limbs.len]); self.setMetadata(other.positive, other.limbs.len); } /// Efficiently swap a `Managed` with another. This swaps the limb pointers and a full copy is not /// performed. The address of the limbs field will not be the same after this function. pub fn swap(self: *Managed, other: *Managed) void { mem.swap(Managed, self, other); } /// Debugging tool: prints the state to stderr. pub fn dump(self: Managed) void { for (self.limbs[0..self.len()]) |limb| { std.debug.warn("{x} ", .{limb}); } std.debug.warn("capacity={} positive={}\n", .{ self.limbs.len, self.isPositive() }); } /// Negate the sign. pub fn negate(self: *Managed) void { self.metadata ^= sign_bit; } /// Make positive. pub fn abs(self: *Managed) void { self.metadata &= ~sign_bit; } pub fn isOdd(self: Managed) bool { return self.limbs[0] & 1 != 0; } pub fn isEven(self: Managed) bool { return !self.isOdd(); } /// Returns the number of bits required to represent the absolute value of an integer. pub fn bitCountAbs(self: Managed) usize { return self.toConst().bitCountAbs(); } /// Returns the number of bits required to represent the integer in twos-complement form. /// /// If the integer is negative the value returned is the number of bits needed by a signed /// integer to represent the value. If positive the value is the number of bits for an /// unsigned integer. Any unsigned integer will fit in the signed integer with bitcount /// one greater than the returned value. /// /// e.g. -127 returns 8 as it will fit in an i8. 127 returns 7 since it fits in a u7. pub fn bitCountTwosComp(self: Managed) usize { return self.toConst().bitCountTwosComp(); } pub fn fitsInTwosComp(self: Managed, is_signed: bool, bit_count: usize) bool { return self.toConst().fitsInTwosComp(is_signed, bit_count); } /// Returns whether self can fit into an integer of the requested type. pub fn fits(self: Managed, comptime T: type) bool { return self.toConst().fits(T); } /// Returns the approximate size of the integer in the given base. Negative values accommodate for /// the minus sign. This is used for determining the number of characters needed to print the /// value. It is inexact and may exceed the given value by ~1-2 bytes. pub fn sizeInBaseUpperBound(self: Managed, base: usize) usize { return self.toConst().sizeInBaseUpperBound(base); } /// Sets an Managed to value. Value must be an primitive integer type. pub fn set(self: *Managed, value: anytype) Allocator.Error!void { try self.ensureCapacity(calcLimbLen(value)); var m = self.toMutable(); m.set(value); self.setMetadata(m.positive, m.len); } pub const ConvertError = Const.ConvertError; /// Convert self to type T. /// /// Returns an error if self cannot be narrowed into the requested type without truncation. pub fn to(self: Managed, comptime T: type) ConvertError!T { return self.toConst().to(T); } /// Set self from the string representation `value`. /// /// `value` must contain only digits <= `base` and is case insensitive. Base prefixes are /// not allowed (e.g. 0x43 should simply be 43). Underscores in the input string are /// ignored and can be used as digit separators. /// /// Returns an error if memory could not be allocated or `value` has invalid digits for the /// requested base. /// /// self's allocator is used for temporary storage to boost multiplication performance. pub fn setString(self: *Managed, base: u8, value: []const u8) !void { if (base < 2 or base > 16) return error.InvalidBase; try self.ensureCapacity(calcSetStringLimbCount(base, value.len)); const limbs_buffer = try self.allocator.alloc(Limb, calcSetStringLimbsBufferLen(base, value.len)); defer self.allocator.free(limbs_buffer); var m = self.toMutable(); try m.setString(base, value, limbs_buffer, self.allocator); self.setMetadata(m.positive, m.len); } /// Converts self to a string in the requested base. Memory is allocated from the provided /// allocator and not the one present in self. pub fn toString(self: Managed, allocator: *Allocator, base: u8, uppercase: bool) ![]u8 { if (base < 2 or base > 16) return error.InvalidBase; return self.toConst().toStringAlloc(self.allocator, base, uppercase); } /// To allow `std.fmt.format` to work with `Managed`. /// If the integer is larger than `pow(2, 64 * @sizeOf(usize) * 8), this function will fail /// to print the string, printing "(BigInt)" instead of a number. /// This is because the rendering algorithm requires reversing a string, which requires O(N) memory. /// See `toString` and `toStringAlloc` for a way to print big integers without failure. pub fn format( self: Managed, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { return self.toConst().format(fmt, options, out_stream); } /// Returns math.Order.lt, math.Order.eq, math.Order.gt if |a| < |b|, |a| == /// |b| or |a| > |b| respectively. pub fn orderAbs(a: Managed, b: Managed) math.Order { return a.toConst().orderAbs(b.toConst()); } /// Returns math.Order.lt, math.Order.eq, math.Order.gt if a < b, a == b or a /// > b respectively. pub fn order(a: Managed, b: Managed) math.Order { return a.toConst().order(b.toConst()); } /// Returns true if a == 0. pub fn eqZero(a: Managed) bool { return a.toConst().eqZero(); } /// Returns true if |a| == |b|. pub fn eqAbs(a: Managed, b: Managed) bool { return a.toConst().eqAbs(b.toConst()); } /// Returns true if a == b. pub fn eq(a: Managed, b: Managed) bool { return a.toConst().eq(b.toConst()); } /// Normalize a possible sequence of leading zeros. /// /// [1, 2, 3, 4, 0] -> [1, 2, 3, 4] /// [1, 2, 0, 0, 0] -> [1, 2] /// [0, 0, 0, 0, 0] -> [0] pub fn normalize(r: *Managed, length: usize) void { assert(length > 0); assert(length <= r.limbs.len); var j = length; while (j > 0) : (j -= 1) { if (r.limbs[j - 1] != 0) { break; } } // Handle zero r.setLen(if (j != 0) j else 1); } /// r = a + scalar /// /// r and a may be aliases. /// scalar is a primitive integer type. /// /// Returns an error if memory could not be allocated. pub fn addScalar(r: *Managed, a: Const, scalar: anytype) Allocator.Error!void { try r.ensureCapacity(math.max(a.limbs.len, calcLimbLen(scalar)) + 1); var m = r.toMutable(); m.addScalar(a, scalar); r.setMetadata(m.positive, m.len); } /// r = a + b /// /// r, a and b may be aliases. /// /// Returns an error if memory could not be allocated. pub fn add(r: *Managed, a: Const, b: Const) Allocator.Error!void { try r.ensureCapacity(math.max(a.limbs.len, b.limbs.len) + 1); var m = r.toMutable(); m.add(a, b); r.setMetadata(m.positive, m.len); } /// r = a - b /// /// r, a and b may be aliases. /// /// Returns an error if memory could not be allocated. pub fn sub(r: *Managed, a: Const, b: Const) !void { try r.ensureCapacity(math.max(a.limbs.len, b.limbs.len) + 1); var m = r.toMutable(); m.sub(a, b); r.setMetadata(m.positive, m.len); } /// rma = a * b /// /// rma, a and b may be aliases. However, it is more efficient if rma does not alias a or b. /// If rma aliases a or b, then caller must call `rma.ensureMulCapacity` prior to calling `mul`. /// /// Returns an error if memory could not be allocated. /// /// rma's allocator is used for temporary storage to speed up the multiplication. pub fn mul(rma: *Managed, a: Const, b: Const) !void { var alias_count: usize = 0; if (rma.limbs.ptr == a.limbs.ptr) alias_count += 1; if (rma.limbs.ptr == b.limbs.ptr) alias_count += 1; assert(alias_count == 0 or rma.limbs.len >= a.limbs.len + b.limbs.len + 1); try rma.ensureMulCapacity(a, b); var m = rma.toMutable(); if (alias_count == 0) { m.mulNoAlias(a, b, rma.allocator); } else { const limb_count = calcMulLimbsBufferLen(a.limbs.len, b.limbs.len, alias_count); const limbs_buffer = try rma.allocator.alloc(Limb, limb_count); defer rma.allocator.free(limbs_buffer); m.mul(a, b, limbs_buffer, rma.allocator); } rma.setMetadata(m.positive, m.len); } pub fn ensureMulCapacity(rma: *Managed, a: Const, b: Const) !void { try rma.ensureCapacity(a.limbs.len + b.limbs.len + 1); } /// q = a / b (rem r) /// /// a / b are floored (rounded towards 0). /// /// Returns an error if memory could not be allocated. /// /// q's allocator is used for temporary storage to speed up the multiplication. pub fn divFloor(q: *Managed, r: *Managed, a: Const, b: Const) !void { try q.ensureCapacity(a.limbs.len + b.limbs.len + 1); try r.ensureCapacity(a.limbs.len); var mq = q.toMutable(); var mr = r.toMutable(); const limbs_buffer = try q.allocator.alloc(Limb, calcDivLimbsBufferLen(a.limbs.len, b.limbs.len)); defer q.allocator.free(limbs_buffer); mq.divFloor(&mr, a, b, limbs_buffer, q.allocator); q.setMetadata(mq.positive, mq.len); r.setMetadata(mr.positive, mr.len); } /// q = a / b (rem r) /// /// a / b are truncated (rounded towards -inf). /// /// Returns an error if memory could not be allocated. /// /// q's allocator is used for temporary storage to speed up the multiplication. pub fn divTrunc(q: *Managed, r: *Managed, a: Const, b: Const) !void { try q.ensureCapacity(a.limbs.len + b.limbs.len + 1); try r.ensureCapacity(a.limbs.len); var mq = q.toMutable(); var mr = r.toMutable(); const limbs_buffer = try q.allocator.alloc(Limb, calcDivLimbsBufferLen(a.limbs.len, b.limbs.len)); defer q.allocator.free(limbs_buffer); mq.divTrunc(&mr, a, b, limbs_buffer, q.allocator); q.setMetadata(mq.positive, mq.len); r.setMetadata(mr.positive, mr.len); } /// r = a << shift, in other words, r = a * 2^shift pub fn shiftLeft(r: *Managed, a: Managed, shift: usize) !void { try r.ensureCapacity(a.len() + (shift / limb_bits) + 1); var m = r.toMutable(); m.shiftLeft(a.toConst(), shift); r.setMetadata(m.positive, m.len); } /// r = a >> shift pub fn shiftRight(r: *Managed, a: Managed, shift: usize) !void { if (a.len() <= shift / limb_bits) { r.metadata = 1; r.limbs[0] = 0; return; } try r.ensureCapacity(a.len() - (shift / limb_bits)); var m = r.toMutable(); m.shiftRight(a.toConst(), shift); r.setMetadata(m.positive, m.len); } /// r = a | b /// /// a and b are zero-extended to the longer of a or b. pub fn bitOr(r: *Managed, a: Managed, b: Managed) !void { try r.ensureCapacity(math.max(a.len(), b.len())); var m = r.toMutable(); m.bitOr(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); } /// r = a & b pub fn bitAnd(r: *Managed, a: Managed, b: Managed) !void { try r.ensureCapacity(math.min(a.len(), b.len())); var m = r.toMutable(); m.bitAnd(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); } /// r = a ^ b pub fn bitXor(r: *Managed, a: Managed, b: Managed) !void { try r.ensureCapacity(math.max(a.len(), b.len())); var m = r.toMutable(); m.bitXor(a.toConst(), b.toConst()); r.setMetadata(m.positive, m.len); } /// rma may alias x or y. /// x and y may alias each other. /// /// rma's allocator is used for temporary storage to boost multiplication performance. pub fn gcd(rma: *Managed, x: Managed, y: Managed) !void { try rma.ensureCapacity(math.min(x.len(), y.len())); var m = rma.toMutable(); var limbs_buffer = std.ArrayList(Limb).init(rma.allocator); defer limbs_buffer.deinit(); try m.gcd(x.toConst(), y.toConst(), &limbs_buffer); rma.setMetadata(m.positive, m.len); } pub fn pow(rma: *Managed, a: Managed, b: u32) !void { const needed_limbs = calcPowLimbsBufferLen(a.bitCountAbs(), b); const limbs_buffer = try rma.allocator.alloc(Limb, needed_limbs); defer rma.allocator.free(limbs_buffer); if (rma.limbs.ptr == a.limbs.ptr) { var m = try Managed.initCapacity(rma.allocator, needed_limbs); errdefer m.deinit(); var m_mut = m.toMutable(); try m_mut.pow(a.toConst(), b, limbs_buffer); m.setMetadata(m_mut.positive, m_mut.len); rma.deinit(); rma.swap(&m); } else { try rma.ensureCapacity(needed_limbs); var rma_mut = rma.toMutable(); try rma_mut.pow(a.toConst(), b, limbs_buffer); rma.setMetadata(rma_mut.positive, rma_mut.len); } } }; /// Knuth 4.3.1, Algorithm M. /// /// r MUST NOT alias any of a or b. fn llmulacc(opt_allocator: ?*Allocator, r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); const a_norm = a[0..llnormalize(a)]; const b_norm = b[0..llnormalize(b)]; var x = a_norm; var y = b_norm; if (a_norm.len > b_norm.len) { x = b_norm; y = a_norm; } assert(r.len >= x.len + y.len + 1); // 48 is a pretty abitrary size chosen based on performance of a factorial program. if (x.len > 48) { if (opt_allocator) |allocator| { llmulacc_karatsuba(allocator, r, x, y) catch |err| switch (err) { error.OutOfMemory => {}, // handled below }; } } // Basecase multiplication var i: usize = 0; while (i < x.len) : (i += 1) { llmulDigit(r[i..], y, x[i]); } } /// Knuth 4.3.1, Algorithm M. /// /// r MUST NOT alias any of a or b. fn llmulacc_karatsuba(allocator: *Allocator, r: []Limb, x: []const Limb, y: []const Limb) error{OutOfMemory}!void { @setRuntimeSafety(debug_safety); assert(r.len >= x.len + y.len + 1); const split = @divFloor(x.len, 2); var x0 = x[0..split]; var x1 = x[split..x.len]; var y0 = y[0..split]; var y1 = y[split..y.len]; var tmp = try allocator.alloc(Limb, x1.len + y1.len + 1); defer allocator.free(tmp); mem.set(Limb, tmp, 0); llmulacc(allocator, tmp, x1, y1); var length = llnormalize(tmp); _ = llaccum(r[split..], tmp[0..length]); _ = llaccum(r[split * 2 ..], tmp[0..length]); mem.set(Limb, tmp[0..length], 0); llmulacc(allocator, tmp, x0, y0); length = llnormalize(tmp); _ = llaccum(r[0..], tmp[0..length]); _ = llaccum(r[split..], tmp[0..length]); const x_cmp = llcmp(x1, x0); const y_cmp = llcmp(y1, y0); if (x_cmp * y_cmp == 0) { return; } const x0_len = llnormalize(x0); const x1_len = llnormalize(x1); var j0 = try allocator.alloc(Limb, math.max(x0_len, x1_len)); defer allocator.free(j0); if (x_cmp == 1) { llsub(j0, x1[0..x1_len], x0[0..x0_len]); } else { llsub(j0, x0[0..x0_len], x1[0..x1_len]); } const y0_len = llnormalize(y0); const y1_len = llnormalize(y1); var j1 = try allocator.alloc(Limb, math.max(y0_len, y1_len)); defer allocator.free(j1); if (y_cmp == 1) { llsub(j1, y1[0..y1_len], y0[0..y0_len]); } else { llsub(j1, y0[0..y0_len], y1[0..y1_len]); } const j0_len = llnormalize(j0); const j1_len = llnormalize(j1); if (x_cmp == y_cmp) { mem.set(Limb, tmp[0..length], 0); llmulacc(allocator, tmp, j0, j1); length = llnormalize(tmp); llsub(r[split..], r[split..], tmp[0..length]); } else { llmulacc(allocator, r[split..], j0, j1); } } // r = r + a fn llaccum(r: []Limb, a: []const Limb) Limb { @setRuntimeSafety(debug_safety); assert(r.len != 0 and a.len != 0); assert(r.len >= a.len); var i: usize = 0; var carry: Limb = 0; while (i < a.len) : (i += 1) { var c: Limb = 0; c += @boolToInt(@addWithOverflow(Limb, r[i], a[i], &r[i])); c += @boolToInt(@addWithOverflow(Limb, r[i], carry, &r[i])); carry = c; } while ((carry != 0) and i < r.len) : (i += 1) { carry = @boolToInt(@addWithOverflow(Limb, r[i], carry, &r[i])); } return carry; } /// Returns -1, 0, 1 if |a| < |b|, |a| == |b| or |a| > |b| respectively for limbs. pub fn llcmp(a: []const Limb, b: []const Limb) i8 { @setRuntimeSafety(debug_safety); const a_len = llnormalize(a); const b_len = llnormalize(b); if (a_len < b_len) { return -1; } if (a_len > b_len) { return 1; } var i: usize = a_len - 1; while (i != 0) : (i -= 1) { if (a[i] != b[i]) { break; } } if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } else { return 0; } } fn llmulDigit(acc: []Limb, y: []const Limb, xi: Limb) void { @setRuntimeSafety(debug_safety); if (xi == 0) { return; } var carry: Limb = 0; var a_lo = acc[0..y.len]; var a_hi = acc[y.len..]; var j: usize = 0; while (j < a_lo.len) : (j += 1) { a_lo[j] = @call(.{ .modifier = .always_inline }, addMulLimbWithCarry, .{ a_lo[j], y[j], xi, &carry }); } j = 0; while ((carry != 0) and (j < a_hi.len)) : (j += 1) { carry = @boolToInt(@addWithOverflow(Limb, a_hi[j], carry, &a_hi[j])); } } /// returns the min length the limb could be. fn llnormalize(a: []const Limb) usize { @setRuntimeSafety(debug_safety); var j = a.len; while (j > 0) : (j -= 1) { if (a[j - 1] != 0) { break; } } // Handle zero return if (j != 0) j else 1; } /// Knuth 4.3.1, Algorithm S. fn llsub(r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); assert(a.len > b.len or (a.len == b.len and a[a.len - 1] >= b[b.len - 1])); assert(r.len >= a.len); var i: usize = 0; var borrow: Limb = 0; while (i < b.len) : (i += 1) { var c: Limb = 0; c += @boolToInt(@subWithOverflow(Limb, a[i], b[i], &r[i])); c += @boolToInt(@subWithOverflow(Limb, r[i], borrow, &r[i])); borrow = c; } while (i < a.len) : (i += 1) { borrow = @boolToInt(@subWithOverflow(Limb, a[i], borrow, &r[i])); } assert(borrow == 0); } /// Knuth 4.3.1, Algorithm A. fn lladd(r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(a.len != 0 and b.len != 0); assert(a.len >= b.len); assert(r.len >= a.len + 1); var i: usize = 0; var carry: Limb = 0; while (i < b.len) : (i += 1) { var c: Limb = 0; c += @boolToInt(@addWithOverflow(Limb, a[i], b[i], &r[i])); c += @boolToInt(@addWithOverflow(Limb, r[i], carry, &r[i])); carry = c; } while (i < a.len) : (i += 1) { carry = @boolToInt(@addWithOverflow(Limb, a[i], carry, &r[i])); } r[i] = carry; } /// Knuth 4.3.1, Exercise 16. fn lldiv1(quo: []Limb, rem: *Limb, a: []const Limb, b: Limb) void { @setRuntimeSafety(debug_safety); assert(a.len > 1 or a[0] >= b); assert(quo.len >= a.len); rem.* = 0; for (a) |_, ri| { const i = a.len - ri - 1; const pdiv = ((@as(DoubleLimb, rem.*) << limb_bits) | a[i]); if (pdiv == 0) { quo[i] = 0; rem.* = 0; } else if (pdiv < b) { quo[i] = 0; rem.* = @truncate(Limb, pdiv); } else if (pdiv == b) { quo[i] = 1; rem.* = 0; } else { quo[i] = @truncate(Limb, @divTrunc(pdiv, b)); rem.* = @truncate(Limb, pdiv - (quo[i] *% b)); } } } fn llshl(r: []Limb, a: []const Limb, shift: usize) void { @setRuntimeSafety(debug_safety); assert(a.len >= 1); assert(r.len >= a.len + (shift / limb_bits) + 1); const limb_shift = shift / limb_bits + 1; const interior_limb_shift = @intCast(Log2Limb, shift % limb_bits); var carry: Limb = 0; var i: usize = 0; while (i < a.len) : (i += 1) { const src_i = a.len - i - 1; const dst_i = src_i + limb_shift; const src_digit = a[src_i]; r[dst_i] = carry | @call(.{ .modifier = .always_inline }, math.shr, .{ Limb, src_digit, limb_bits - @intCast(Limb, interior_limb_shift), }); carry = (src_digit << interior_limb_shift); } r[limb_shift - 1] = carry; mem.set(Limb, r[0 .. limb_shift - 1], 0); } fn llshr(r: []Limb, a: []const Limb, shift: usize) void { @setRuntimeSafety(debug_safety); assert(a.len >= 1); assert(r.len >= a.len - (shift / limb_bits)); const limb_shift = shift / limb_bits; const interior_limb_shift = @intCast(Log2Limb, shift % limb_bits); var carry: Limb = 0; var i: usize = 0; while (i < a.len - limb_shift) : (i += 1) { const src_i = a.len - i - 1; const dst_i = src_i - limb_shift; const src_digit = a[src_i]; r[dst_i] = carry | (src_digit >> interior_limb_shift); carry = @call(.{ .modifier = .always_inline }, math.shl, .{ Limb, src_digit, limb_bits - @intCast(Limb, interior_limb_shift), }); } } fn llor(r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(r.len >= a.len); assert(a.len >= b.len); var i: usize = 0; while (i < b.len) : (i += 1) { r[i] = a[i] | b[i]; } while (i < a.len) : (i += 1) { r[i] = a[i]; } } fn lland(r: []Limb, a: []const Limb, b: []const Limb) void { @setRuntimeSafety(debug_safety); assert(r.len >= b.len); assert(a.len >= b.len); var i: usize = 0; while (i < b.len) : (i += 1) { r[i] = a[i] & b[i]; } } fn llxor(r: []Limb, a: []const Limb, b: []const Limb) void { assert(r.len >= a.len); assert(a.len >= b.len); var i: usize = 0; while (i < b.len) : (i += 1) { r[i] = a[i] ^ b[i]; } while (i < a.len) : (i += 1) { r[i] = a[i]; } } /// Knuth 4.6.3 fn llpow(r: []Limb, a: []const Limb, b: u32, tmp_limbs: []Limb) void { var tmp1: []Limb = undefined; var tmp2: []Limb = undefined; // Multiplication requires no aliasing between the operand and the result // variable, use the output limbs and another temporary set to overcome this // limitation. // The initial assignment makes the result end in `r` so an extra memory // copy is saved, each 1 flips the index twice so it's a no-op so count the // 0. const b_leading_zeros = @intCast(u5, @clz(u32, b)); const exp_zeros = @popCount(u32, ~b) - b_leading_zeros; if (exp_zeros & 1 != 0) { tmp1 = tmp_limbs; tmp2 = r; } else { tmp1 = r; tmp2 = tmp_limbs; } const a_norm = a[0..llnormalize(a)]; mem.copy(Limb, tmp1, a_norm); mem.set(Limb, tmp1[a_norm.len..], 0); // Scan the exponent as a binary number, from left to right, dropping the // most significant bit set. const exp_bits = @intCast(u5, 31 - b_leading_zeros); var exp = @bitReverse(u32, b) >> 1 + b_leading_zeros; var i: u5 = 0; while (i < exp_bits) : (i += 1) { // Square { mem.set(Limb, tmp2, 0); const op = tmp1[0..llnormalize(tmp1)]; llmulacc(null, tmp2, op, op); mem.swap([]Limb, &tmp1, &tmp2); } // Multiply by a if (exp & 1 != 0) { mem.set(Limb, tmp2, 0); llmulacc(null, tmp2, tmp1[0..llnormalize(tmp1)], a_norm); mem.swap([]Limb, &tmp1, &tmp2); } exp >>= 1; } } // Storage must live for the lifetime of the returned value fn fixedIntFromSignedDoubleLimb(A: SignedDoubleLimb, storage: []Limb) Mutable { assert(storage.len >= 2); const A_is_positive = A >= 0; const Au = @intCast(DoubleLimb, if (A < 0) -A else A); storage[0] = @truncate(Limb, Au); storage[1] = @truncate(Limb, Au >> limb_bits); return .{ .limbs = storage[0..2], .positive = A_is_positive, .len = 2, }; } test "" { _ = @import("int_test.zig"); }
lib/std/math/big/int.zig
const std = @import("index.zig"); const debug = std.debug; const mem = std.mem; const u1 = @IntType(false, 1); const u256 = @IntType(false, 256); // A single token slice into the parent string. // // Use `token.slice()` on the input at the current position to get the current slice. pub const Token = struct { id: Id, // How many bytes do we skip before counting offset: u1, // Whether string contains a \uXXXX sequence and cannot be zero-copied string_has_escape: bool, // Whether number is simple and can be represented by an integer (i.e. no `.` or `e`) number_is_integer: bool, // How many bytes from the current position behind the start of this token is. count: usize, pub const Id = enum { ObjectBegin, ObjectEnd, ArrayBegin, ArrayEnd, String, Number, True, False, Null, }; pub fn init(id: Id, count: usize, offset: u1) Token { return Token{ .id = id, .offset = offset, .string_has_escape = false, .number_is_integer = true, .count = count, }; } pub fn initString(count: usize, has_unicode_escape: bool) Token { return Token{ .id = Id.String, .offset = 0, .string_has_escape = has_unicode_escape, .number_is_integer = true, .count = count, }; } pub fn initNumber(count: usize, number_is_integer: bool) Token { return Token{ .id = Id.Number, .offset = 0, .string_has_escape = false, .number_is_integer = number_is_integer, .count = count, }; } // A marker token is a zero-length pub fn initMarker(id: Id) Token { return Token{ .id = id, .offset = 0, .string_has_escape = false, .number_is_integer = true, .count = 0, }; } // Slice into the underlying input string. pub fn slice(self: *const Token, input: []const u8, i: usize) []const u8 { return input[i + self.offset - self.count .. i + self.offset]; } }; // A small streaming JSON parser. This accepts input one byte at a time and returns tokens as // they are encountered. No copies or allocations are performed during parsing and the entire // parsing state requires ~40-50 bytes of stack space. // // Conforms strictly to RFC8529. // // For a non-byte based wrapper, consider using TokenStream instead. pub const StreamingParser = struct { // Current state state: State, // How many bytes we have counted for the current token count: usize, // What state to follow after parsing a string (either property or value string) after_string_state: State, // What state to follow after parsing a value (either top-level or value end) after_value_state: State, // If we stopped now, would the complete parsed string to now be a valid json string complete: bool, // Current token flags to pass through to the next generated, see Token. string_has_escape: bool, number_is_integer: bool, // Bit-stack for nested object/map literals (max 255 nestings). stack: u256, stack_used: u8, const object_bit = 0; const array_bit = 1; const max_stack_size = @maxValue(u8); pub fn init() StreamingParser { var p: StreamingParser = undefined; p.reset(); return p; } pub fn reset(p: *StreamingParser) void { p.state = State.TopLevelBegin; p.count = 0; // Set before ever read in main transition function p.after_string_state = undefined; p.after_value_state = State.ValueEnd; // handle end of values normally p.stack = 0; p.stack_used = 0; p.complete = false; p.string_has_escape = false; p.number_is_integer = true; } pub const State = enum { // These must be first with these explicit values as we rely on them for indexing the // bit-stack directly and avoiding a branch. ObjectSeparator = 0, ValueEnd = 1, TopLevelBegin, TopLevelEnd, ValueBegin, ValueBeginNoClosing, String, StringUtf8Byte3, StringUtf8Byte2, StringUtf8Byte1, StringEscapeCharacter, StringEscapeHexUnicode4, StringEscapeHexUnicode3, StringEscapeHexUnicode2, StringEscapeHexUnicode1, Number, NumberMaybeDotOrExponent, NumberMaybeDigitOrDotOrExponent, NumberFractionalRequired, NumberFractional, NumberMaybeExponent, NumberExponent, NumberExponentDigitsRequired, NumberExponentDigits, TrueLiteral1, TrueLiteral2, TrueLiteral3, FalseLiteral1, FalseLiteral2, FalseLiteral3, FalseLiteral4, NullLiteral1, NullLiteral2, NullLiteral3, // Only call this function to generate array/object final state. pub fn fromInt(x: var) State { debug.assert(x == 0 or x == 1); const T = @TagType(State); return @intToEnum(State, @intCast(T, x)); } }; pub const Error = error{ InvalidTopLevel, TooManyNestedItems, TooManyClosingItems, InvalidValueBegin, InvalidValueEnd, UnbalancedBrackets, UnbalancedBraces, UnexpectedClosingBracket, UnexpectedClosingBrace, InvalidNumber, InvalidSeparator, InvalidLiteral, InvalidEscapeCharacter, InvalidUnicodeHexSymbol, InvalidUtf8Byte, InvalidTopLevelTrailing, InvalidControlCharacter, }; // Give another byte to the parser and obtain any new tokens. This may (rarely) return two // tokens. token2 is always null if token1 is null. // // There is currently no error recovery on a bad stream. pub fn feed(p: *StreamingParser, c: u8, token1: *?Token, token2: *?Token) Error!void { token1.* = null; token2.* = null; p.count += 1; // unlikely if (try p.transition(c, token1)) { _ = try p.transition(c, token2); } } // Perform a single transition on the state machine and return any possible token. fn transition(p: *StreamingParser, c: u8, token: *?Token) Error!bool { switch (p.state) { State.TopLevelBegin => switch (c) { '{' => { p.stack <<= 1; p.stack |= object_bit; p.stack_used += 1; p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { p.stack <<= 1; p.stack |= array_bit; p.stack_used += 1; p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.number_is_integer = true; p.state = State.Number; p.after_value_state = State.TopLevelEnd; p.count = 0; }, '0' => { p.number_is_integer = true; p.state = State.NumberMaybeDotOrExponent; p.after_value_state = State.TopLevelEnd; p.count = 0; }, '1'...'9' => { p.number_is_integer = true; p.state = State.NumberMaybeDigitOrDotOrExponent; p.after_value_state = State.TopLevelEnd; p.count = 0; }, '"' => { p.state = State.String; p.after_value_state = State.TopLevelEnd; // We don't actually need the following since after_value_state should override. p.after_string_state = State.ValueEnd; p.string_has_escape = false; p.count = 0; }, 't' => { p.state = State.TrueLiteral1; p.after_value_state = State.TopLevelEnd; p.count = 0; }, 'f' => { p.state = State.FalseLiteral1; p.after_value_state = State.TopLevelEnd; p.count = 0; }, 'n' => { p.state = State.NullLiteral1; p.after_value_state = State.TopLevelEnd; p.count = 0; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidTopLevel; }, }, State.TopLevelEnd => switch (c) { 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidTopLevelTrailing; }, }, State.ValueBegin => switch (c) { // NOTE: These are shared in ValueEnd as well, think we can reorder states to // be a bit clearer and avoid this duplication. '}' => { // unlikely if (p.stack & 1 != object_bit) { return error.UnexpectedClosingBracket; } if (p.stack_used == 0) { return error.TooManyClosingItems; } p.state = State.ValueBegin; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; switch (p.stack_used) { 0 => { p.complete = true; p.state = State.TopLevelEnd; }, else => { p.state = State.ValueEnd; }, } token.* = Token.initMarker(Token.Id.ObjectEnd); }, ']' => { if (p.stack & 1 != array_bit) { return error.UnexpectedClosingBrace; } if (p.stack_used == 0) { return error.TooManyClosingItems; } p.state = State.ValueBegin; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; switch (p.stack_used) { 0 => { p.complete = true; p.state = State.TopLevelEnd; }, else => { p.state = State.ValueEnd; }, } token.* = Token.initMarker(Token.Id.ArrayEnd); }, '{' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= object_bit; p.stack_used += 1; p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= array_bit; p.stack_used += 1; p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.state = State.Number; p.count = 0; }, '0' => { p.state = State.NumberMaybeDotOrExponent; p.count = 0; }, '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; p.count = 0; }, '"' => { p.state = State.String; p.count = 0; }, 't' => { p.state = State.TrueLiteral1; p.count = 0; }, 'f' => { p.state = State.FalseLiteral1; p.count = 0; }, 'n' => { p.state = State.NullLiteral1; p.count = 0; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidValueBegin; }, }, // TODO: A bit of duplication here and in the following state, redo. State.ValueBeginNoClosing => switch (c) { '{' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= object_bit; p.stack_used += 1; p.state = State.ValueBegin; p.after_string_state = State.ObjectSeparator; token.* = Token.initMarker(Token.Id.ObjectBegin); }, '[' => { if (p.stack_used == max_stack_size) { return error.TooManyNestedItems; } p.stack <<= 1; p.stack |= array_bit; p.stack_used += 1; p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; token.* = Token.initMarker(Token.Id.ArrayBegin); }, '-' => { p.state = State.Number; p.count = 0; }, '0' => { p.state = State.NumberMaybeDotOrExponent; p.count = 0; }, '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; p.count = 0; }, '"' => { p.state = State.String; p.count = 0; }, 't' => { p.state = State.TrueLiteral1; p.count = 0; }, 'f' => { p.state = State.FalseLiteral1; p.count = 0; }, 'n' => { p.state = State.NullLiteral1; p.count = 0; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidValueBegin; }, }, State.ValueEnd => switch (c) { ',' => { p.after_string_state = State.fromInt(p.stack & 1); p.state = State.ValueBeginNoClosing; }, ']' => { if (p.stack_used == 0) { return error.UnbalancedBrackets; } p.state = State.ValueEnd; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; if (p.stack_used == 0) { p.complete = true; p.state = State.TopLevelEnd; } token.* = Token.initMarker(Token.Id.ArrayEnd); }, '}' => { if (p.stack_used == 0) { return error.UnbalancedBraces; } p.state = State.ValueEnd; p.after_string_state = State.fromInt(p.stack & 1); p.stack >>= 1; p.stack_used -= 1; if (p.stack_used == 0) { p.complete = true; p.state = State.TopLevelEnd; } token.* = Token.initMarker(Token.Id.ObjectEnd); }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidValueEnd; }, }, State.ObjectSeparator => switch (c) { ':' => { p.state = State.ValueBegin; p.after_string_state = State.ValueEnd; }, 0x09, 0x0A, 0x0D, 0x20 => { // whitespace }, else => { return error.InvalidSeparator; }, }, State.String => switch (c) { 0x00...0x1F => { return error.InvalidControlCharacter; }, '"' => { p.state = p.after_string_state; if (p.after_value_state == State.TopLevelEnd) { p.state = State.TopLevelEnd; p.complete = true; } token.* = Token.initString(p.count - 1, p.string_has_escape); }, '\\' => { p.state = State.StringEscapeCharacter; }, 0x20, 0x21, 0x23...0x5B, 0x5D...0x7F => { // non-control ascii }, 0xC0...0xDF => { p.state = State.StringUtf8Byte1; }, 0xE0...0xEF => { p.state = State.StringUtf8Byte2; }, 0xF0...0xFF => { p.state = State.StringUtf8Byte3; }, else => { return error.InvalidUtf8Byte; }, }, State.StringUtf8Byte3 => switch (c >> 6) { 0b10 => p.state = State.StringUtf8Byte2, else => return error.InvalidUtf8Byte, }, State.StringUtf8Byte2 => switch (c >> 6) { 0b10 => p.state = State.StringUtf8Byte1, else => return error.InvalidUtf8Byte, }, State.StringUtf8Byte1 => switch (c >> 6) { 0b10 => p.state = State.String, else => return error.InvalidUtf8Byte, }, State.StringEscapeCharacter => switch (c) { // NOTE: '/' is allowed as an escaped character but it also is allowed // as unescaped according to the RFC. There is a reported errata which suggests // removing the non-escaped variant but it makes more sense to simply disallow // it as an escape code here. // // The current JSONTestSuite tests rely on both of this behaviour being present // however, so we default to the status quo where both are accepted until this // is further clarified. '"', '\\', '/', 'b', 'f', 'n', 'r', 't' => { p.string_has_escape = true; p.state = State.String; }, 'u' => { p.string_has_escape = true; p.state = State.StringEscapeHexUnicode4; }, else => { return error.InvalidEscapeCharacter; }, }, State.StringEscapeHexUnicode4 => switch (c) { '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode3; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode3 => switch (c) { '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode2; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode2 => switch (c) { '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.StringEscapeHexUnicode1; }, else => return error.InvalidUnicodeHexSymbol, }, State.StringEscapeHexUnicode1 => switch (c) { '0'...'9', 'A'...'F', 'a'...'f' => { p.state = State.String; }, else => return error.InvalidUnicodeHexSymbol, }, State.Number => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { '0' => { p.state = State.NumberMaybeDotOrExponent; }, '1'...'9' => { p.state = State.NumberMaybeDigitOrDotOrExponent; }, else => { return error.InvalidNumber; }, } }, State.NumberMaybeDotOrExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { '.' => { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.NumberMaybeDigitOrDotOrExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { '.' => { p.number_is_integer = false; p.state = State.NumberFractionalRequired; }, 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, '0'...'9' => { // another digit }, else => { p.state = p.after_value_state; token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.NumberFractionalRequired => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { '0'...'9' => { p.state = State.NumberFractional; }, else => { return error.InvalidNumber; }, } }, State.NumberFractional => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { '0'...'9' => { // another digit }, 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.NumberMaybeExponent => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { 'e', 'E' => { p.number_is_integer = false; p.state = State.NumberExponent; }, else => { p.state = p.after_value_state; token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.NumberExponent => switch (c) { '-', '+' => { p.complete = false; p.state = State.NumberExponentDigitsRequired; }, '0'...'9' => { p.complete = p.after_value_state == State.TopLevelEnd; p.state = State.NumberExponentDigits; }, else => { return error.InvalidNumber; }, }, State.NumberExponentDigitsRequired => switch (c) { '0'...'9' => { p.complete = p.after_value_state == State.TopLevelEnd; p.state = State.NumberExponentDigits; }, else => { return error.InvalidNumber; }, }, State.NumberExponentDigits => { p.complete = p.after_value_state == State.TopLevelEnd; switch (c) { '0'...'9' => { // another digit }, else => { p.state = p.after_value_state; token.* = Token.initNumber(p.count, p.number_is_integer); return true; }, } }, State.TrueLiteral1 => switch (c) { 'r' => p.state = State.TrueLiteral2, else => return error.InvalidLiteral, }, State.TrueLiteral2 => switch (c) { 'u' => p.state = State.TrueLiteral3, else => return error.InvalidLiteral, }, State.TrueLiteral3 => switch (c) { 'e' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; token.* = Token.init(Token.Id.True, p.count + 1, 1); }, else => { return error.InvalidLiteral; }, }, State.FalseLiteral1 => switch (c) { 'a' => p.state = State.FalseLiteral2, else => return error.InvalidLiteral, }, State.FalseLiteral2 => switch (c) { 'l' => p.state = State.FalseLiteral3, else => return error.InvalidLiteral, }, State.FalseLiteral3 => switch (c) { 's' => p.state = State.FalseLiteral4, else => return error.InvalidLiteral, }, State.FalseLiteral4 => switch (c) { 'e' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; token.* = Token.init(Token.Id.False, p.count + 1, 1); }, else => { return error.InvalidLiteral; }, }, State.NullLiteral1 => switch (c) { 'u' => p.state = State.NullLiteral2, else => return error.InvalidLiteral, }, State.NullLiteral2 => switch (c) { 'l' => p.state = State.NullLiteral3, else => return error.InvalidLiteral, }, State.NullLiteral3 => switch (c) { 'l' => { p.state = p.after_value_state; p.complete = p.state == State.TopLevelEnd; token.* = Token.init(Token.Id.Null, p.count + 1, 1); }, else => { return error.InvalidLiteral; }, }, } return false; } }; // A small wrapper over a StreamingParser for full slices. Returns a stream of json Tokens. pub const TokenStream = struct { i: usize, slice: []const u8, parser: StreamingParser, token: ?Token, pub fn init(slice: []const u8) TokenStream { return TokenStream{ .i = 0, .slice = slice, .parser = StreamingParser.init(), .token = null, }; } pub fn next(self: *TokenStream) !?Token { if (self.token) |token| { self.token = null; return token; } var t1: ?Token = undefined; var t2: ?Token = undefined; while (self.i < self.slice.len) { try self.parser.feed(self.slice[self.i], &t1, &t2); self.i += 1; if (t1) |token| { self.token = t2; return token; } } if (self.i > self.slice.len) { try self.parser.feed(' ', &t1, &t2); self.i += 1; if (t1) |token| { return token; } } return null; } }; fn checkNext(p: *TokenStream, id: Token.Id) void { const token = (p.next() catch unreachable).?; debug.assert(token.id == id); } test "token" { const s = \\{ \\ "Image": { \\ "Width": 800, \\ "Height": 600, \\ "Title": "View from 15th Floor", \\ "Thumbnail": { \\ "Url": "http://www.example.com/image/481989943", \\ "Height": 125, \\ "Width": 100 \\ }, \\ "Animated" : false, \\ "IDs": [116, 943, 234, 38793] \\ } \\} ; var p = TokenStream.init(s); checkNext(&p, Token.Id.ObjectBegin); checkNext(&p, Token.Id.String); // Image checkNext(&p, Token.Id.ObjectBegin); checkNext(&p, Token.Id.String); // Width checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.String); // Height checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.String); // Title checkNext(&p, Token.Id.String); checkNext(&p, Token.Id.String); // Thumbnail checkNext(&p, Token.Id.ObjectBegin); checkNext(&p, Token.Id.String); // Url checkNext(&p, Token.Id.String); checkNext(&p, Token.Id.String); // Height checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.String); // Width checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.ObjectEnd); checkNext(&p, Token.Id.String); // Animated checkNext(&p, Token.Id.False); checkNext(&p, Token.Id.String); // IDs checkNext(&p, Token.Id.ArrayBegin); checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.Number); checkNext(&p, Token.Id.ArrayEnd); checkNext(&p, Token.Id.ObjectEnd); checkNext(&p, Token.Id.ObjectEnd); debug.assert((try p.next()) == null); } // Validate a JSON string. This does not limit number precision so a decoder may not necessarily // be able to decode the string even if this returns true. pub fn validate(s: []const u8) bool { var p = StreamingParser.init(); for (s) |c, i| { var token1: ?Token = undefined; var token2: ?Token = undefined; p.feed(c, &token1, &token2) catch |err| { return false; }; } return p.complete; } test "json validate" { debug.assert(validate("{}")); } const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const ArrayList = std.ArrayList; const HashMap = std.HashMap; pub const ValueTree = struct { arena: ArenaAllocator, root: Value, pub fn deinit(self: *ValueTree) void { self.arena.deinit(); } }; pub const ObjectMap = HashMap([]const u8, Value, mem.hash_slice_u8, mem.eql_slice_u8); pub const Value = union(enum) { Null, Bool: bool, Integer: i64, Float: f64, String: []const u8, Array: ArrayList(Value), Object: ObjectMap, pub fn dump(self: *const Value) void { switch (self.*) { Value.Null => { debug.warn("null"); }, Value.Bool => |inner| { debug.warn("{}", inner); }, Value.Integer => |inner| { debug.warn("{}", inner); }, Value.Float => |inner| { debug.warn("{.5}", inner); }, Value.String => |inner| { debug.warn("\"{}\"", inner); }, Value.Array => |inner| { var not_first = false; debug.warn("["); for (inner.toSliceConst()) |value| { if (not_first) { debug.warn(","); } not_first = true; value.dump(); } debug.warn("]"); }, Value.Object => |inner| { var not_first = false; debug.warn("{{"); var it = inner.iterator(); while (it.next()) |entry| { if (not_first) { debug.warn(","); } not_first = true; debug.warn("\"{}\":", entry.key); entry.value.dump(); } debug.warn("}}"); }, } } pub fn dumpIndent(self: *const Value, indent: usize) void { if (indent == 0) { self.dump(); } else { self.dumpIndentLevel(indent, 0); } } fn dumpIndentLevel(self: *const Value, indent: usize, level: usize) void { switch (self.*) { Value.Null => { debug.warn("null"); }, Value.Bool => |inner| { debug.warn("{}", inner); }, Value.Integer => |inner| { debug.warn("{}", inner); }, Value.Float => |inner| { debug.warn("{.5}", inner); }, Value.String => |inner| { debug.warn("\"{}\"", inner); }, Value.Array => |inner| { var not_first = false; debug.warn("[\n"); for (inner.toSliceConst()) |value| { if (not_first) { debug.warn(",\n"); } not_first = true; padSpace(level + indent); value.dumpIndentLevel(indent, level + indent); } debug.warn("\n"); padSpace(level); debug.warn("]"); }, Value.Object => |inner| { var not_first = false; debug.warn("{{\n"); var it = inner.iterator(); while (it.next()) |entry| { if (not_first) { debug.warn(",\n"); } not_first = true; padSpace(level + indent); debug.warn("\"{}\": ", entry.key); entry.value.dumpIndentLevel(indent, level + indent); } debug.warn("\n"); padSpace(level); debug.warn("}}"); }, } } fn padSpace(indent: usize) void { var i: usize = 0; while (i < indent) : (i += 1) { debug.warn(" "); } } }; // A non-stream JSON parser which constructs a tree of Value's. pub const Parser = struct { allocator: *Allocator, state: State, copy_strings: bool, // Stores parent nodes and un-combined Values. stack: ArrayList(Value), const State = enum { ObjectKey, ObjectValue, ArrayValue, Simple, }; pub fn init(allocator: *Allocator, copy_strings: bool) Parser { return Parser{ .allocator = allocator, .state = State.Simple, .copy_strings = copy_strings, .stack = ArrayList(Value).init(allocator), }; } pub fn deinit(p: *Parser) void { p.stack.deinit(); } pub fn reset(p: *Parser) void { p.state = State.Simple; p.stack.shrink(0); } pub fn parse(p: *Parser, input: []const u8) !ValueTree { var s = TokenStream.init(input); var arena = ArenaAllocator.init(p.allocator); errdefer arena.deinit(); while (try s.next()) |token| { try p.transition(&arena.allocator, input, s.i - 1, token); } debug.assert(p.stack.len == 1); return ValueTree{ .arena = arena, .root = p.stack.at(0), }; } // Even though p.allocator exists, we take an explicit allocator so that allocation state // can be cleaned up on error correctly during a `parse` on call. fn transition(p: *Parser, allocator: *Allocator, input: []const u8, i: usize, token: *const Token) !void { switch (p.state) { State.ObjectKey => switch (token.id) { Token.Id.ObjectEnd => { if (p.stack.len == 1) { return; } var value = p.stack.pop(); try p.pushToParent(value); }, Token.Id.String => { try p.stack.append(try p.parseString(allocator, token, input, i)); p.state = State.ObjectValue; }, else => { unreachable; }, }, State.ObjectValue => { var object = &p.stack.items[p.stack.len - 2].Object; var key = p.stack.items[p.stack.len - 1].String; switch (token.id) { Token.Id.ObjectBegin => { try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { _ = try object.put(key, try p.parseString(allocator, token, input, i)); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.Number => { _ = try object.put(key, try p.parseNumber(token, input, i)); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.True => { _ = try object.put(key, Value{ .Bool = true }); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.False => { _ = try object.put(key, Value{ .Bool = false }); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.Null => { _ = try object.put(key, Value.Null); _ = p.stack.pop(); p.state = State.ObjectKey; }, Token.Id.ObjectEnd, Token.Id.ArrayEnd => { unreachable; }, } }, State.ArrayValue => { var array = &p.stack.items[p.stack.len - 1].Array; switch (token.id) { Token.Id.ArrayEnd => { if (p.stack.len == 1) { return; } var value = p.stack.pop(); try p.pushToParent(value); }, Token.Id.ObjectBegin => { try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { try array.append(try p.parseString(allocator, token, input, i)); }, Token.Id.Number => { try array.append(try p.parseNumber(token, input, i)); }, Token.Id.True => { try array.append(Value{ .Bool = true }); }, Token.Id.False => { try array.append(Value{ .Bool = false }); }, Token.Id.Null => { try array.append(Value.Null); }, Token.Id.ObjectEnd => { unreachable; }, } }, State.Simple => switch (token.id) { Token.Id.ObjectBegin => { try p.stack.append(Value{ .Object = ObjectMap.init(allocator) }); p.state = State.ObjectKey; }, Token.Id.ArrayBegin => { try p.stack.append(Value{ .Array = ArrayList(Value).init(allocator) }); p.state = State.ArrayValue; }, Token.Id.String => { try p.stack.append(try p.parseString(allocator, token, input, i)); }, Token.Id.Number => { try p.stack.append(try p.parseNumber(token, input, i)); }, Token.Id.True => { try p.stack.append(Value{ .Bool = true }); }, Token.Id.False => { try p.stack.append(Value{ .Bool = false }); }, Token.Id.Null => { try p.stack.append(Value.Null); }, Token.Id.ObjectEnd, Token.Id.ArrayEnd => { unreachable; }, }, } } fn pushToParent(p: *Parser, value: *const Value) !void { switch (p.stack.at(p.stack.len - 1)) { // Object Parent -> [ ..., object, <key>, value ] Value.String => |key| { _ = p.stack.pop(); var object = &p.stack.items[p.stack.len - 1].Object; _ = try object.put(key, value); p.state = State.ObjectKey; }, // Array Parent -> [ ..., <array>, value ] Value.Array => |*array| { try array.append(value.*); p.state = State.ArrayValue; }, else => { unreachable; }, } } fn parseString(p: *Parser, allocator: *Allocator, token: *const Token, input: []const u8, i: usize) !Value { // TODO: We don't strictly have to copy values which do not contain any escape // characters if flagged with the option. const slice = token.slice(input, i); return Value{ .String = try mem.dupe(p.allocator, u8, slice) }; } fn parseNumber(p: *Parser, token: *const Token, input: []const u8, i: usize) !Value { return if (token.number_is_integer) Value{ .Integer = try std.fmt.parseInt(i64, token.slice(input, i), 10) } else @panic("TODO: fmt.parseFloat not yet implemented"); } }; test "json parser dynamic" { var p = Parser.init(debug.global_allocator, false); defer p.deinit(); const s = \\{ \\ "Image": { \\ "Width": 800, \\ "Height": 600, \\ "Title": "View from 15th Floor", \\ "Thumbnail": { \\ "Url": "http://www.example.com/image/481989943", \\ "Height": 125, \\ "Width": 100 \\ }, \\ "Animated" : false, \\ "IDs": [116, 943, 234, 38793] \\ } \\} ; var tree = try p.parse(s); defer tree.deinit(); var root = tree.root; var image = root.Object.get("Image").?.value; const width = image.Object.get("Width").?.value; debug.assert(width.Integer == 800); const height = image.Object.get("Height").?.value; debug.assert(height.Integer == 600); const title = image.Object.get("Title").?.value; debug.assert(mem.eql(u8, title.String, "View from 15th Floor")); const animated = image.Object.get("Animated").?.value; debug.assert(animated.Bool == false); }
std/json.zig