code
stringlengths
38
801k
repo_path
stringlengths
6
263
const Core = @This(); const std = @import("std"); const xcb = @import("bindings.zig"); pub const Window = @import("Window.zig"); connection: *xcb.Connection, setup: *xcb.Setup, screen: *xcb.Screen, window: *Window, wm_protocols: *xcb.InternAtomReply, wm_delete_window: *xcb.InternAtomReply, allocator: std.mem.Allocator, pub fn init(allocator: std.mem.Allocator) !*Core { var core = try allocator.create(Core); errdefer allocator.destroy(core); core.allocator = allocator; core.connection = try xcb.connect("", null); core.setup = try xcb.getSetup(core.connection); const screen_iter = xcb.setupRootsIterator(core.setup); core.screen = screen_iter.data.?; const wm_protocols_atom = xcb.internAtom(core.connection, true, "WM_PROTOCOLS".len, "WM_PROTOCOLS"); const wm_protocols_reply = xcb.internAtomReply(core.connection, wm_protocols_atom, null); const wm_delete_window_atom = xcb.internAtom(core.connection, false, "WM_DELETE_WINDOW".len, "WM_DELETE_WINDOW"); const wm_delete_window_reply = xcb.internAtomReply(core.connection, wm_delete_window_atom, null); core.wm_protocols = wm_protocols_reply; core.wm_delete_window = wm_delete_window_reply; return core; } pub fn deinit(core: *Core) void { std.c.free(core.wm_protocols); std.c.free(core.wm_delete_window); xcb.disconnect(core.connection); core.allocator.destroy(core); } pub fn createWindow(core: *Core, info: types.WindowInfo) !*Window { var window = try Window.init(core, info); _ = xcb.changeProperty( core.connection, .Replace, window.window, core.wm_protocols.atom, 4, 32, 1, &core.wm_delete_window.atom, ); errdefer window.deinit(); // TODO: Actually support multiple window core.window = window; return window; } pub fn pollEvent(core: *Core) ?Event { _ = xcb.flush(core.connection); var event = xcb.pollForEvent(core.connection); defer if (event) |ev| std.c.free(ev); return core.handleEvent(event); } pub fn waitEvent(core: *Core) ?Event { _ = xcb.flush(core.connection); var event = xcb.waitForEvent(core.connection); defer if (event) |ev| std.c.free(ev); return core.handleEvent(event); } pub fn getKeyDown(core: *Core, key: Key) bool { // Convert key to keysym const keysym: u32 = core.translateKey(key); // Get keysyms from keycode const keyboard_mapping_req = xcb.getKeyboardMapping(core.connection, core.setup.min_keycode, core.setup.max_keycode - core.setup.min_keycode + 1); var keyboard_mapping = xcb.getKeyboardMappingReply(core.connection, keyboard_mapping_req, null); defer std.c.free(keyboard_mapping); const keysyms = xcb.getKeyboardMappingKeysyms(keyboard_mapping); // Convert keysym to keycode var keycode: u8 = 0; var i: usize = 0; while (i < 256) : (i += 1) { if (keysyms[i * keyboard_mapping.keysyms_per_keycode] == keysym) { keycode = @intCast(u8, i + core.setup.min_keycode); break; } } // Get all key states const cookie = xcb.queryKeymap(core.connection); const key_states = xcb.queryKeymapReply(core.connection, cookie, null); defer std.c.free(key_states); // Get the specific key state from keycode return key_states.keys[keycode / 8] & (@intCast(u8, 1) << @intCast(u3, (keycode % 8))) != 0; } const types = @import("../main.zig"); const Event = types.Event; const Button = types.Button; const ScrollDir = types.ScrollDir; const Key = types.Key; inline fn xcbToWindow(window: *Window) types.Window { return types.Window.initFromInternal(window); } inline fn translateButton(core: *Core, but: u8) Button { // Note: xcb headers are docs seem to be confusing here // xproto.h mentions code 2 to be right and 3 to be middle. // But in practice 2 is middle and 3 is right (confusing!) // // This has also been confirmed with glfw enum IDs _ = core; return switch (but) { 1 => .left, 2 => .middle, 3 => .right, else => unreachable, }; } const xk = @import("keys.zig"); inline fn translateKeycode(core: *Core, keycode: u8) Key { const keyboard_mapping_req = xcb.getKeyboardMapping(core.connection, keycode, 1); var keyboard_mapping = xcb.getKeyboardMappingReply(core.connection, keyboard_mapping_req, null); defer std.c.free(keyboard_mapping); const keysyms = xcb.getKeyboardMappingKeysyms(keyboard_mapping); return switch (keysyms[0]) { xk.XK_a => .a, xk.XK_b => .b, xk.XK_c => .c, xk.XK_d => .d, xk.XK_e => .e, xk.XK_f => .f, xk.XK_g => .g, xk.XK_h => .h, xk.XK_i => .i, xk.XK_j => .j, xk.XK_k => .k, xk.XK_l => .l, xk.XK_m => .m, xk.XK_n => .m, xk.XK_o => .o, xk.XK_p => .p, xk.XK_q => .q, xk.XK_r => .r, xk.XK_s => .s, xk.XK_t => .t, xk.XK_u => .u, xk.XK_v => .v, xk.XK_w => .w, xk.XK_x => .x, xk.XK_y => .y, xk.XK_z => .z, xk.XK_0 => .zero, xk.XK_1 => .one, xk.XK_2 => .two, xk.XK_3 => .three, xk.XK_4 => .four, xk.XK_5 => .five, xk.XK_6 => .six, xk.XK_7 => .seven, xk.XK_8 => .eight, xk.XK_9 => .nine, xk.XK_F1 => .f1, xk.XK_F2 => .f2, xk.XK_F3 => .f3, xk.XK_F4 => .f4, xk.XK_F5 => .f5, xk.XK_F6 => .f6, xk.XK_F7 => .f7, xk.XK_F8 => .f8, xk.XK_F9 => .f9, xk.XK_F10 => .f10, xk.XK_F11 => .f11, xk.XK_F12 => .f12, xk.XK_F13 => .f13, xk.XK_F14 => .f14, xk.XK_F15 => .f15, xk.XK_F16 => .f16, xk.XK_F17 => .f17, xk.XK_F18 => .f18, xk.XK_F19 => .f19, xk.XK_F20 => .f20, xk.XK_F21 => .f21, xk.XK_F22 => .f22, xk.XK_F23 => .f23, xk.XK_F24 => .f24, xk.XK_F25 => .f25, xk.XK_KP_Divide => .kp_divide, xk.XK_KP_Multiply => .kp_multiply, xk.XK_KP_Subtract => .kp_subtract, xk.XK_KP_Add => .kp_add, xk.XK_KP_Insert => .kp_0, xk.XK_KP_End => .kp_1, xk.XK_KP_Down => .kp_2, xk.XK_KP_Page_Down => .kp_3, xk.XK_KP_Left => .kp_4, xk.XK_KP_Begin => .kp_5, xk.XK_KP_Right => .kp_6, xk.XK_KP_Home => .kp_7, xk.XK_KP_Up => .kp_8, xk.XK_KP_Page_Up => .kp_9, xk.XK_KP_Delete => .kp_decimal, xk.XK_KP_Equal => .kp_equal, xk.XK_KP_Enter => .kp_enter, xk.XK_Return => .enter, xk.XK_Escape => .escape, xk.XK_Tab => .tab, xk.XK_Shift_L => .left_shift, xk.XK_Shift_R => .right_shift, xk.XK_Control_L => .left_control, xk.XK_Control_R => .right_control, xk.XK_Meta_L, xk.XK_Alt_L => .left_alt, xk.XK_Meta_R, xk.XK_Alt_R, xk.XK_Mode_switch => .right_alt, xk.XK_Super_L => .left_super, xk.XK_Super_R => .right_super, xk.XK_Menu => .menu, xk.XK_Num_Lock => .num_lock, xk.XK_Caps_Lock => .caps_lock, xk.XK_Print => .print, xk.XK_Scroll_Lock => .scroll_lock, xk.XK_Pause => .pause, xk.XK_Delete => .delete, xk.XK_Home => .home, xk.XK_End => .end, xk.XK_Page_Up => .page_up, xk.XK_Page_Down => .page_down, xk.XK_Insert => .insert, xk.XK_Left => .left, xk.XK_Right => .right, xk.XK_Up => .up, xk.XK_Down => .down, xk.XK_BackSpace => .backspace, xk.XK_space => .space, xk.XK_minus => .minus, xk.XK_equal => .equal, xk.XK_bracketleft => .left_bracket, xk.XK_bracketright => .right_bracket, xk.XK_backslash => .backslash, xk.XK_semicolon => .semicolon, xk.XK_apostrophe => .apostrophe, xk.XK_comma => .comma, xk.XK_period => .period, xk.XK_slash => .slash, xk.XK_grave => .grave, else => .unknown, }; } inline fn translateKey(core: *Core, key: Key) u32 { _ = core; return switch (key) { .a => xk.XK_a, .b => xk.XK_b, .c => xk.XK_c, .d => xk.XK_d, .e => xk.XK_e, .f => xk.XK_f, .g => xk.XK_g, .h => xk.XK_h, .i => xk.XK_i, .j => xk.XK_j, .k => xk.XK_k, .l => xk.XK_l, .m => xk.XK_m, .n => xk.XK_n, .o => xk.XK_o, .p => xk.XK_p, .q => xk.XK_q, .r => xk.XK_r, .s => xk.XK_s, .t => xk.XK_t, .u => xk.XK_u, .v => xk.XK_v, .w => xk.XK_w, .x => xk.XK_x, .y => xk.XK_y, .z => xk.XK_z, .zero => xk.XK_0, .one => xk.XK_1, .two => xk.XK_2, .three => xk.XK_3, .four => xk.XK_4, .five => xk.XK_5, .six => xk.XK_6, .seven => xk.XK_7, .eight => xk.XK_8, .nine => xk.XK_9, .f1 => xk.XK_F1, .f2 => xk.XK_F2, .f3 => xk.XK_F3, .f4 => xk.XK_F4, .f5 => xk.XK_F5, .f6 => xk.XK_F6, .f7 => xk.XK_F7, .f8 => xk.XK_F8, .f9 => xk.XK_F9, .f10 => xk.XK_F10, .f11 => xk.XK_F11, .f12 => xk.XK_F12, .f13 => xk.XK_F13, .f14 => xk.XK_F14, .f15 => xk.XK_F15, .f16 => xk.XK_F16, .f17 => xk.XK_F17, .f18 => xk.XK_F18, .f19 => xk.XK_F19, .f20 => xk.XK_F20, .f21 => xk.XK_F21, .f22 => xk.XK_F22, .f23 => xk.XK_F23, .f24 => xk.XK_F24, .f25 => xk.XK_F25, .kp_divide => xk.XK_KP_Divide, .kp_multiply => xk.XK_KP_Multiply, .kp_subtract => xk.XK_KP_Subtract, .kp_add => xk.XK_KP_Add, .kp_0 => xk.XK_KP_Insert, .kp_1 => xk.XK_KP_End, .kp_2 => xk.XK_KP_Down, .kp_3 => xk.XK_KP_Page_Down, .kp_4 => xk.XK_KP_Left, .kp_5 => xk.XK_KP_Begin, .kp_6 => xk.XK_KP_Right, .kp_7 => xk.XK_KP_Home, .kp_8 => xk.XK_KP_Up, .kp_9 => xk.XK_KP_Page_Up, .kp_decimal => xk.XK_KP_Delete, .kp_equal => xk.XK_KP_Equal, .kp_enter => xk.XK_KP_Enter, .@"return" => xk.XK_Return, .escape => xk.XK_Escape, .tab => xk.XK_Tab, .left_shift => xk.XK_Shift_L, .right_shift => xk.XK_Shift_R, .left_control => xk.XK_Control_L, .right_control => xk.XK_Control_R, .left_alt => xk.XK_Alt_L, .right_alt => xk.XK_Alt_R, .left_super => xk.XK_Super_L, .right_super => xk.XK_Super_R, .menu => xk.XK_Menu, .num_lock => xk.XK_Num_Lock, .caps_lock => xk.XK_Caps_Lock, .print => xk.XK_Print, .scroll_lock => xk.XK_Scroll_Lock, .pause => xk.XK_Pause, .delete => xk.XK_Delete, .home => xk.XK_Home, .end => xk.XK_End, .page_up => xk.XK_Page_Up, .page_down => xk.XK_Page_Down, .insert => xk.XK_Insert, .left => xk.XK_Left, .right => xk.XK_Right, .up => xk.XK_Up, .down => xk.XK_Down, .backspace => xk.XK_BackSpace, .space => xk.XK_space, .minus => xk.XK_minus, .equal => xk.XK_equal, .left_bracket => xk.XK_bracketleft, .right_bracket => xk.XK_bracketright, .backslash => xk.XK_backslash, .semicolon => xk.XK_semicolon, .apostrophe => xk.XK_apostrophe, .comma => xk.XK_comma, .period => xk.XK_period, .slash => xk.XK_slash, .grave => xk.XK_grave, .unknown => unreachable, }; } fn handleEvent(core: *Core, event: ?*xcb.GenericEvent) ?Event { if (event) |ev| { switch (xcb.eventResponse(ev)) { .KeyPress => { const kp = @ptrCast(*xcb.KeyPressEvent, ev); return Event{ .window = xcbToWindow(core.window), .ev = .{ .key_press = .{ .key = core.translateKeycode(kp.detail) } }, }; }, .KeyRelease => { const kp = @ptrCast(*xcb.KeyReleaseEvent, ev); const key = core.translateKeycode(kp.detail); if (core.pollEvent()) |next| { if (next.ev == .key_press and next.ev.key_press.key == key) { return null; } } return Event{ .window = xcbToWindow(core.window), .ev = .{ .key_release = .{ .key = key } }, }; }, .ButtonPress => { const bp = @ptrCast(*xcb.ButtonPressEvent, ev); switch (bp.detail) { 1, 2, 3 => return Event{ .window = xcbToWindow(core.window), .ev = .{ .button_press = .{ .button = core.translateButton(bp.detail) } }, }, 4, 5 => return Event{ .window = xcbToWindow(core.window), .ev = .{ .mouse_scroll = .{ .scroll_x = 0, .scroll_y = if (bp.detail == 4) 1 else -1 } }, }, 6, 7 => return Event{ .window = xcbToWindow(core.window), .ev = .{ .mouse_scroll = .{ .scroll_x = if (bp.detail == 6) 1 else -1, .scroll_y = 0 } }, }, else => {}, } }, .ButtonRelease => { const br = @ptrCast(*xcb.ButtonReleaseEvent, ev); switch (br.detail) { 1, 2, 3 => return Event{ .window = xcbToWindow(core.window), .ev = .{ .button_release = .{ .button = core.translateButton(br.detail) } }, }, else => {}, } }, .FocusIn => { const fi = @ptrCast(*xcb.FocusInEvent, ev); if (fi.mode != .grab and fi.mode != .ungrab) { return Event{ .window = xcbToWindow(core.window), .ev = .{ .focus_in = .{} }, }; } }, .FocusOut => { const fo = @ptrCast(*xcb.FocusOutEvent, ev); if (fo.mode != .grab and fo.mode != .ungrab) { return Event{ .window = xcbToWindow(core.window), .ev = .{ .focus_out = .{} }, }; } }, .EnterNotify => { const en = @ptrCast(*xcb.EnterNotifyEvent, ev); return Event{ .window = xcbToWindow(core.window), .ev = .{ .mouse_enter = .{ .x = en.event_x, .y = en.event_y } }, }; }, .LeaveNotify => { const ln = @ptrCast(*xcb.LeaveNotifyEvent, ev); return Event{ .window = xcbToWindow(core.window), .ev = .{ .mouse_leave = .{ .x = ln.event_x, .y = ln.event_y } }, }; }, .MotionNotify => { const mn = @ptrCast(*xcb.MotionNotifyEvent, ev); return Event{ .window = xcbToWindow(core.window), .ev = .{ .mouse_motion = .{ .x = mn.event_x, .y = mn.event_y, } }, }; }, .ConfigureNotify => { const cn = @ptrCast(*xcb.ConfigureNotifyEvent, ev); const window = xcbToWindow(core.window); if (core.window.width != cn.width and core.window.height != cn.height) { core.window.width = cn.width; core.window.height = cn.width; return Event{ .window = window, .ev = .{ .window_resize = .{ .width = cn.width, .height = cn.height, }, }, }; } }, .ClientMessage => { const cm = @ptrCast(*xcb.ClientMessageEvent, event); if (cm.data.data32[0] == core.wm_delete_window.atom) { return Event{ .window = xcbToWindow(core.window), .ev = .{ .quit = .{} }, }; } }, else => {}, } } return null; }
src/xcb/Core.zig
const std = @import("std"); const utils = @import("utils.zig"); usingnamespace @import("header.zig"); usingnamespace @import("frames.zig"); pub const ID3 = struct { header: Header, extended_header: ?ExtendedHeader, frame_headers: FrameHeaderList, file: std.fs.File, allocator: *std.mem.Allocator, const Self = @This(); /// Load the contents of an mp3 file into the ID3 struct pub fn load(allocator: *std.mem.Allocator, filename: []const u8) !Self { var file = try std.fs.openFileAbsolute(filename, .{}); defer file.close(); var id3 = Self{ .header = undefined, .extended_header = null, .frame_headers = undefined, .file = file, .allocator = allocator, }; id3.header = try Header.parseFromFile(&id3.file); id3.extended_header = try ExtendedHeader.parseFromID3(&id3); id3.frame_headers = try FrameHeaderList.parseFromID3(&id3); std.debug.print("ID: {s}\nSize: {}\nVersion: {s}\n", .{ id3.header.id, utils.bytesToInt(u32, &id3.header.size), id3.header.version }); std.debug.print("File size: {}\n", .{id3.file.getEndPos()}); return id3; } pub fn deinit(self: *Self) void { self.frame_headers.deinit(); } /// Save ID3 information to file /// [TODO] The saved file is corrupted and not in proper format. Need to figure /// out how to write frames that have encoding. pub fn save(self: *Self, filename: []const u8) !void { var full_path = try std.fmt.allocPrint(self.allocator, "/home/shintales/GitRepositories/zid3/{s}", .{filename}); var file = try std.fs.createFileAbsolute(full_path, .{}); defer file.close(); _ = try file.write(std.mem.asBytes(&self.header)); for (self.frame_headers.inner_list.items) |frame_header| { _ = try file.write(&frame_header.id); _ = try file.write(&frame_header.size); _ = try file.write(&frame_header.flags); _ = try file.writeAll(frame_header.content); } } /// Get the title of the song pub fn getTitle(self: *Self) []u8 { return self.getTag("TIT2"); } /// Get the artist of the song pub fn getArtist(self: *Self) []u8 { return self.getTag("TPE1"); } /// Get the album song is from pub fn getAlbum(self: *Self) []u8 { return self.getTag("TALB"); } /// Get names of artist listed on album pub fn getAlbumArtist(self: *Self) []u8 { return self.getTag("TPE2"); } /// Get the genre from song pub fn getGenre(self: *Self) []u8 { return self.getTag("TCON"); } /// Get the track number of song pub fn getTrackNum(self: *Self) []u8 { return self.getTag("TRCK"); } /// Get the year song was released pub fn getYear(self: *Self) []u8 { return self.getTag("TYER"); } /// Parse the tag information based on the ID3v2 frame id pub fn getTag(self: *Self, id: []const u8) []u8 { for (self.frame_headers.inner_list.items) |frame_header| { if (std.mem.eql(u8, frame_header.id[0..], id)) { if (frame_header.getTextFrame().encoding == 1) return frame_header.getTextFrame().information[2..]; return frame_header.getTextFrame().information; } } return undefined; } /// Set song title pub fn setTitle(self: *Self, input: []const u8) !void { try self.setTagInformation("TIT2", input); } /// Set artist name pub fn setArtist(self: *Self, input: []const u8) !void { try self.setTagInformation("TPE1", input); } /// Set album name pub fn setAlbum(self: *Self, input: []const u8) !void { try self.setTagInformation("TALB", input); } /// Set album artist name(s) /// List names as comma seperated string pub fn setAlbumArtist(self: *Self, input: []const u8) !void { try self.setTagInformation("TPE2", input); } /// Set genre pub fn setGenre(self: *Self, input: []const u8) !void { try self.setTagInformation("TCON", input); } /// Set track number pub fn setTrackNum(self: *Self, input: []const u8) !void { try self.setTagInformation("TRCK", input); } ///Set year released pub fn setYear(self: *Self, input: []const u8) !void { try self.setTagInformation("TYER", input); } fn setTagInformation(self: *Self, id: []const u8, input: []const u8) !void { for (self.frame_headers.inner_list.items) |_, loc| { var frame_header = &self.frame_headers.inner_list.items[loc]; if (std.mem.eql(u8, frame_header.id[0..], id)) { var preserve = switch (frame_header.getTextFrame().encoding) { 0 => frame_header.content[0..1], 1 => frame_header.content[0..3], else => unreachable, }; frame_header.content = try self.allocator.realloc(frame_header.content, input.len + preserve.len); frame_header.content = try std.mem.concat(self.allocator, u8, &[_][]const u8{ preserve, input }); break; } } } };
src/zid3.zig
const std = @import("std"); pub fn main() anyerror!void { const find = "\n\n"; // The \r are already stripped out const n = 275; const buf = @embedFile("./bigger.txt"); //const buf = @embedFile("./http-requests.txt"); //const n = 55; //const find = "\r\n\r\n"; // The \r are already stripped out var ptrs1: [n][]const u8 = undefined; var ptrs2: [n][]const u8= undefined; var timer = try std.time.Timer.start(); var it1 = std.mem.split(buf, find); var cnt: usize = 0; while (it1.next()) |req| { ptrs1[cnt] = req; cnt += 1; } const t1 = timer.lap(); std.testing.expectEqual(cnt, n); var it2 = split(buf, find); cnt = 0; while (it2.next()) |req| { ptrs2[cnt] = req; cnt += 1; } const t2 = timer.lap(); std.testing.expectEqual(cnt, n); std.testing.expectEqual(ptrs1, ptrs2); timer.reset(); for (ptrs1) |src, i| { const dst = ptrs2[i]; std.testing.expect(std.mem.eql(u8, src, dst)); } const t3 = timer.lap(); for (ptrs1) |src, i| { const dst = ptrs2[i]; std.testing.expect(eql(u8, src, dst)); } const t4 = timer.lap(); var dest: [4096]u8 = undefined; timer.reset(); for (ptrs1) |src, i| { std.mem.copy(u8, &dest, src); } const t5 = timer.lap(); for (ptrs1) |src, i| { copy(u8, &dest, src); } const t6 = timer.lap(); std.log.warn("split std: {}ns", .{t1}); std.log.warn("split SIMD: {}ns", .{t2}); std.log.warn("split diff: {}", .{@intToFloat(f32, t1)/@intToFloat(f32, t2)}); std.log.warn("eql std: {}ns", .{t3}); std.log.warn("eql SIMD: {}ns", .{t4}); std.log.warn("eql diff: {}", .{@intToFloat(f32, t3)/@intToFloat(f32, t4)}); std.log.warn("copy std: {}ns", .{t5}); std.log.warn("copy SIMD: {}ns", .{t6}); std.log.warn("copy diff: {}", .{@intToFloat(f32, t5)/@intToFloat(f32, t6)}); } pub fn copy(comptime T: type, dest: []T, source: []const T) callconv(.Inline) void { const n = 32; // TODO: Adjust based on bitSizeOf T const V = @Vector(n, T); if (source.len < n) return std.mem.copy(T, dest, source); var end: usize = n; while (end < source.len) { const start = end - n; const source_chunk: V = source[start..end][0..n].*; const dest_chunk = &@as(V, dest[start..end][0..n].*); dest_chunk.* = source_chunk; end = std.math.min(end + n, source.len); } } pub fn eql(comptime T: type, a: []const T, b: []const T) callconv(.Inline) bool { const n = 32; const V8x32 = @Vector(n, T); if (a.len != b.len) return false; if (a.ptr == b.ptr) return true; if (a.len < n) { // Too small to fit, fallback to standard eql for (a) |item, index| { if (b[index] != item) return false; } } else { var end: usize = n; while (end < a.len) { const start = end - n; const a_chunk: V8x32 = a[start..end][0..n].*; const b_chunk: V8x32 = b[start..end][0..n].*; if (!@reduce(.And, a_chunk == b_chunk)) { return false; } end = std.math.min(end+n, a.len); } } return true; } pub fn indexOf(comptime T: type, buf: []const u8, delimiter: []const u8) ?usize { return indexOfAnyPos(T, buf, 0, delimiter); } pub fn indexOfAnyPos(comptime T: type, buf: []const T, start_index: usize, delimiter: []const T) ?usize { const n = 32; const k = delimiter.len; const V8x32 = @Vector(n, T); const V1x32 = @Vector(n, u1); const Vbx32 = @Vector(n, bool); const first = @splat(n, delimiter[0]); const last = @splat(n, delimiter[k-1]); if (buf.len < n) { return std.mem.indexOfAnyPos(T, buf, start_index, delimiter); } var end: usize = start_index + n; while (end < buf.len) { const start = end - n; const last_end = std.math.min(end+k-1, buf.len); const last_start = last_end - n; // Look for the first character in the delimter const first_chunk: V8x32 = buf[start..end][0..n].*; const last_chunk: V8x32 = buf[last_start..last_end][0..n].*; const mask = @bitCast(V1x32, first == first_chunk) & @bitCast(V1x32, last == last_chunk); if (@reduce(.Or, mask) != 0) { for (@as([n]bool, @bitCast(Vbx32, mask))) |match, i| { if (match and eql(T, buf[start+i..start+i+k], delimiter)) { return start+i; } } } end = std.math.min(end + n, buf.len); } return null; // Not found } pub fn split(buffer: []const u8, delimiter: []const u8) SplitIterator { return SplitIterator{.buffer=buffer, .delimiter=delimiter}; } pub const SplitIterator = struct { index: ?usize = 0, buffer: []const u8, delimiter: []const u8, /// Returns a slice of the next field, or null if splitting is complete. pub fn next(self: *SplitIterator) ?[]const u8 { const start = self.index orelse return null; const end = if (indexOfAnyPos(u8, self.buffer, start, self.delimiter)) |delim_start| blk: { self.index = delim_start + self.delimiter.len; break :blk delim_start; } else blk: { self.index = null; break :blk self.buffer.len; }; return self.buffer[start..end]; } /// Returns a slice of the remaining bytes. Does not affect iterator state. pub fn rest(self: SplitIterator) []const u8 { const end = self.buffer.len; const start = self.index orelse end; return self.buffer[start..end]; } };
tests/search.zig
pub const NERR_BASE = @as(u32, 2100); pub const NERR_PasswordExpired = @as(u32, 2242); pub const CNLEN = @as(u32, 15); pub const LM20_CNLEN = @as(u32, 15); pub const DNLEN = @as(u32, 15); pub const LM20_DNLEN = @as(u32, 15); pub const UNCLEN = @as(u32, 17); pub const LM20_UNCLEN = @as(u32, 17); pub const LM20_NNLEN = @as(u32, 12); pub const SNLEN = @as(u32, 80); pub const LM20_SNLEN = @as(u32, 15); pub const STXTLEN = @as(u32, 256); pub const LM20_STXTLEN = @as(u32, 63); pub const PATHLEN = @as(u32, 256); pub const LM20_PATHLEN = @as(u32, 256); pub const DEVLEN = @as(u32, 80); pub const LM20_DEVLEN = @as(u32, 8); pub const EVLEN = @as(u32, 16); pub const UNLEN = @as(u32, 256); pub const LM20_UNLEN = @as(u32, 20); pub const GNLEN = @as(u32, 256); pub const LM20_GNLEN = @as(u32, 20); pub const PWLEN = @as(u32, 256); pub const LM20_PWLEN = @as(u32, 14); pub const SHPWLEN = @as(u32, 8); pub const CLTYPE_LEN = @as(u32, 12); pub const MAXCOMMENTSZ = @as(u32, 256); pub const LM20_MAXCOMMENTSZ = @as(u32, 48); pub const QNLEN = @as(u32, 80); pub const LM20_QNLEN = @as(u32, 12); pub const ALERTSZ = @as(u32, 128); pub const NETBIOS_NAME_LEN = @as(u32, 16); pub const MAX_PREFERRED_LENGTH = @as(u32, 4294967295); pub const CRYPT_KEY_LEN = @as(u32, 7); pub const CRYPT_TXT_LEN = @as(u32, 8); pub const ENCRYPTED_PWLEN = @as(u32, 16); pub const SESSION_PWLEN = @as(u32, 24); pub const SESSION_CRYPT_KLEN = @as(u32, 21); pub const PARMNUM_ALL = @as(u32, 0); pub const PARM_ERROR_UNKNOWN = @as(u32, 4294967295); pub const PARM_ERROR_NONE = @as(u32, 0); pub const PARMNUM_BASE_INFOLEVEL = @as(u32, 1000); pub const PLATFORM_ID_DOS = @as(u32, 300); pub const PLATFORM_ID_OS2 = @as(u32, 400); pub const PLATFORM_ID_NT = @as(u32, 500); pub const PLATFORM_ID_OSF = @as(u32, 600); pub const PLATFORM_ID_VMS = @as(u32, 700); pub const MIN_LANMAN_MESSAGE_ID = @as(u32, 2100); pub const MAX_LANMAN_MESSAGE_ID = @as(u32, 5899); pub const NERR_Success = @as(u32, 0); pub const NERR_NetNotStarted = @as(u32, 2102); pub const NERR_UnknownServer = @as(u32, 2103); pub const NERR_ShareMem = @as(u32, 2104); pub const NERR_NoNetworkResource = @as(u32, 2105); pub const NERR_RemoteOnly = @as(u32, 2106); pub const NERR_DevNotRedirected = @as(u32, 2107); pub const NERR_ServerNotStarted = @as(u32, 2114); pub const NERR_ItemNotFound = @as(u32, 2115); pub const NERR_UnknownDevDir = @as(u32, 2116); pub const NERR_RedirectedPath = @as(u32, 2117); pub const NERR_DuplicateShare = @as(u32, 2118); pub const NERR_NoRoom = @as(u32, 2119); pub const NERR_TooManyItems = @as(u32, 2121); pub const NERR_InvalidMaxUsers = @as(u32, 2122); pub const NERR_BufTooSmall = @as(u32, 2123); pub const NERR_RemoteErr = @as(u32, 2127); pub const NERR_LanmanIniError = @as(u32, 2131); pub const NERR_NetworkError = @as(u32, 2136); pub const NERR_WkstaInconsistentState = @as(u32, 2137); pub const NERR_WkstaNotStarted = @as(u32, 2138); pub const NERR_BrowserNotStarted = @as(u32, 2139); pub const NERR_InternalError = @as(u32, 2140); pub const NERR_BadTransactConfig = @as(u32, 2141); pub const NERR_InvalidAPI = @as(u32, 2142); pub const NERR_BadEventName = @as(u32, 2143); pub const NERR_DupNameReboot = @as(u32, 2144); pub const NERR_CfgCompNotFound = @as(u32, 2146); pub const NERR_CfgParamNotFound = @as(u32, 2147); pub const NERR_LineTooLong = @as(u32, 2149); pub const NERR_QNotFound = @as(u32, 2150); pub const NERR_JobNotFound = @as(u32, 2151); pub const NERR_DestNotFound = @as(u32, 2152); pub const NERR_DestExists = @as(u32, 2153); pub const NERR_QExists = @as(u32, 2154); pub const NERR_QNoRoom = @as(u32, 2155); pub const NERR_JobNoRoom = @as(u32, 2156); pub const NERR_DestNoRoom = @as(u32, 2157); pub const NERR_DestIdle = @as(u32, 2158); pub const NERR_DestInvalidOp = @as(u32, 2159); pub const NERR_ProcNoRespond = @as(u32, 2160); pub const NERR_SpoolerNotLoaded = @as(u32, 2161); pub const NERR_DestInvalidState = @as(u32, 2162); pub const NERR_QInvalidState = @as(u32, 2163); pub const NERR_JobInvalidState = @as(u32, 2164); pub const NERR_SpoolNoMemory = @as(u32, 2165); pub const NERR_DriverNotFound = @as(u32, 2166); pub const NERR_DataTypeInvalid = @as(u32, 2167); pub const NERR_ProcNotFound = @as(u32, 2168); pub const NERR_ServiceTableLocked = @as(u32, 2180); pub const NERR_ServiceTableFull = @as(u32, 2181); pub const NERR_ServiceInstalled = @as(u32, 2182); pub const NERR_ServiceEntryLocked = @as(u32, 2183); pub const NERR_ServiceNotInstalled = @as(u32, 2184); pub const NERR_BadServiceName = @as(u32, 2185); pub const NERR_ServiceCtlTimeout = @as(u32, 2186); pub const NERR_ServiceCtlBusy = @as(u32, 2187); pub const NERR_BadServiceProgName = @as(u32, 2188); pub const NERR_ServiceNotCtrl = @as(u32, 2189); pub const NERR_ServiceKillProc = @as(u32, 2190); pub const NERR_ServiceCtlNotValid = @as(u32, 2191); pub const NERR_NotInDispatchTbl = @as(u32, 2192); pub const NERR_BadControlRecv = @as(u32, 2193); pub const NERR_ServiceNotStarting = @as(u32, 2194); pub const NERR_AlreadyLoggedOn = @as(u32, 2200); pub const NERR_NotLoggedOn = @as(u32, 2201); pub const NERR_BadUsername = @as(u32, 2202); pub const NERR_BadPassword = @as(u32, 2203); pub const NERR_UnableToAddName_W = @as(u32, 2204); pub const NERR_UnableToAddName_F = @as(u32, 2205); pub const NERR_UnableToDelName_W = @as(u32, 2206); pub const NERR_UnableToDelName_F = @as(u32, 2207); pub const NERR_LogonsPaused = @as(u32, 2209); pub const NERR_LogonServerConflict = @as(u32, 2210); pub const NERR_LogonNoUserPath = @as(u32, 2211); pub const NERR_LogonScriptError = @as(u32, 2212); pub const NERR_StandaloneLogon = @as(u32, 2214); pub const NERR_LogonServerNotFound = @as(u32, 2215); pub const NERR_LogonDomainExists = @as(u32, 2216); pub const NERR_NonValidatedLogon = @as(u32, 2217); pub const NERR_ACFNotFound = @as(u32, 2219); pub const NERR_GroupNotFound = @as(u32, 2220); pub const NERR_UserNotFound = @as(u32, 2221); pub const NERR_ResourceNotFound = @as(u32, 2222); pub const NERR_GroupExists = @as(u32, 2223); pub const NERR_UserExists = @as(u32, 2224); pub const NERR_ResourceExists = @as(u32, 2225); pub const NERR_NotPrimary = @as(u32, 2226); pub const NERR_ACFNotLoaded = @as(u32, 2227); pub const NERR_ACFNoRoom = @as(u32, 2228); pub const NERR_ACFFileIOFail = @as(u32, 2229); pub const NERR_ACFTooManyLists = @as(u32, 2230); pub const NERR_UserLogon = @as(u32, 2231); pub const NERR_ACFNoParent = @as(u32, 2232); pub const NERR_CanNotGrowSegment = @as(u32, 2233); pub const NERR_SpeGroupOp = @as(u32, 2234); pub const NERR_NotInCache = @as(u32, 2235); pub const NERR_UserInGroup = @as(u32, 2236); pub const NERR_UserNotInGroup = @as(u32, 2237); pub const NERR_AccountUndefined = @as(u32, 2238); pub const NERR_AccountExpired = @as(u32, 2239); pub const NERR_InvalidWorkstation = @as(u32, 2240); pub const NERR_InvalidLogonHours = @as(u32, 2241); pub const NERR_PasswordCantChange = @as(u32, 2243); pub const NERR_PasswordHistConflict = @as(u32, 2244); pub const NERR_PasswordTooShort = @as(u32, 2245); pub const NERR_PasswordTooRecent = @as(u32, 2246); pub const NERR_InvalidDatabase = @as(u32, 2247); pub const NERR_DatabaseUpToDate = @as(u32, 2248); pub const NERR_SyncRequired = @as(u32, 2249); pub const NERR_UseNotFound = @as(u32, 2250); pub const NERR_BadAsgType = @as(u32, 2251); pub const NERR_DeviceIsShared = @as(u32, 2252); pub const NERR_SameAsComputerName = @as(u32, 2253); pub const NERR_NoComputerName = @as(u32, 2270); pub const NERR_MsgAlreadyStarted = @as(u32, 2271); pub const NERR_MsgInitFailed = @as(u32, 2272); pub const NERR_NameNotFound = @as(u32, 2273); pub const NERR_AlreadyForwarded = @as(u32, 2274); pub const NERR_AddForwarded = @as(u32, 2275); pub const NERR_AlreadyExists = @as(u32, 2276); pub const NERR_TooManyNames = @as(u32, 2277); pub const NERR_DelComputerName = @as(u32, 2278); pub const NERR_LocalForward = @as(u32, 2279); pub const NERR_GrpMsgProcessor = @as(u32, 2280); pub const NERR_PausedRemote = @as(u32, 2281); pub const NERR_BadReceive = @as(u32, 2282); pub const NERR_NameInUse = @as(u32, 2283); pub const NERR_MsgNotStarted = @as(u32, 2284); pub const NERR_NotLocalName = @as(u32, 2285); pub const NERR_NoForwardName = @as(u32, 2286); pub const NERR_RemoteFull = @as(u32, 2287); pub const NERR_NameNotForwarded = @as(u32, 2288); pub const NERR_TruncatedBroadcast = @as(u32, 2289); pub const NERR_InvalidDevice = @as(u32, 2294); pub const NERR_WriteFault = @as(u32, 2295); pub const NERR_DuplicateName = @as(u32, 2297); pub const NERR_DeleteLater = @as(u32, 2298); pub const NERR_IncompleteDel = @as(u32, 2299); pub const NERR_MultipleNets = @as(u32, 2300); pub const NERR_NetNameNotFound = @as(u32, 2310); pub const NERR_DeviceNotShared = @as(u32, 2311); pub const NERR_ClientNameNotFound = @as(u32, 2312); pub const NERR_FileIdNotFound = @as(u32, 2314); pub const NERR_ExecFailure = @as(u32, 2315); pub const NERR_TmpFile = @as(u32, 2316); pub const NERR_TooMuchData = @as(u32, 2317); pub const NERR_DeviceShareConflict = @as(u32, 2318); pub const NERR_BrowserTableIncomplete = @as(u32, 2319); pub const NERR_NotLocalDomain = @as(u32, 2320); pub const NERR_IsDfsShare = @as(u32, 2321); pub const NERR_DevInvalidOpCode = @as(u32, 2331); pub const NERR_DevNotFound = @as(u32, 2332); pub const NERR_DevNotOpen = @as(u32, 2333); pub const NERR_BadQueueDevString = @as(u32, 2334); pub const NERR_BadQueuePriority = @as(u32, 2335); pub const NERR_NoCommDevs = @as(u32, 2337); pub const NERR_QueueNotFound = @as(u32, 2338); pub const NERR_BadDevString = @as(u32, 2340); pub const NERR_BadDev = @as(u32, 2341); pub const NERR_InUseBySpooler = @as(u32, 2342); pub const NERR_CommDevInUse = @as(u32, 2343); pub const NERR_InvalidComputer = @as(u32, 2351); pub const NERR_MaxLenExceeded = @as(u32, 2354); pub const NERR_BadComponent = @as(u32, 2356); pub const NERR_CantType = @as(u32, 2357); pub const NERR_TooManyEntries = @as(u32, 2362); pub const NERR_ProfileFileTooBig = @as(u32, 2370); pub const NERR_ProfileOffset = @as(u32, 2371); pub const NERR_ProfileCleanup = @as(u32, 2372); pub const NERR_ProfileUnknownCmd = @as(u32, 2373); pub const NERR_ProfileLoadErr = @as(u32, 2374); pub const NERR_ProfileSaveErr = @as(u32, 2375); pub const NERR_LogOverflow = @as(u32, 2377); pub const NERR_LogFileChanged = @as(u32, 2378); pub const NERR_LogFileCorrupt = @as(u32, 2379); pub const NERR_SourceIsDir = @as(u32, 2380); pub const NERR_BadSource = @as(u32, 2381); pub const NERR_BadDest = @as(u32, 2382); pub const NERR_DifferentServers = @as(u32, 2383); pub const NERR_RunSrvPaused = @as(u32, 2385); pub const NERR_ErrCommRunSrv = @as(u32, 2389); pub const NERR_ErrorExecingGhost = @as(u32, 2391); pub const NERR_ShareNotFound = @as(u32, 2392); pub const NERR_InvalidLana = @as(u32, 2400); pub const NERR_OpenFiles = @as(u32, 2401); pub const NERR_ActiveConns = @as(u32, 2402); pub const NERR_BadPasswordCore = @as(u32, 2403); pub const NERR_DevInUse = @as(u32, 2404); pub const NERR_LocalDrive = @as(u32, 2405); pub const NERR_AlertExists = @as(u32, 2430); pub const NERR_TooManyAlerts = @as(u32, 2431); pub const NERR_NoSuchAlert = @as(u32, 2432); pub const NERR_BadRecipient = @as(u32, 2433); pub const NERR_AcctLimitExceeded = @as(u32, 2434); pub const NERR_InvalidLogSeek = @as(u32, 2440); pub const NERR_BadUasConfig = @as(u32, 2450); pub const NERR_InvalidUASOp = @as(u32, 2451); pub const NERR_LastAdmin = @as(u32, 2452); pub const NERR_DCNotFound = @as(u32, 2453); pub const NERR_LogonTrackingError = @as(u32, 2454); pub const NERR_NetlogonNotStarted = @as(u32, 2455); pub const NERR_CanNotGrowUASFile = @as(u32, 2456); pub const NERR_TimeDiffAtDC = @as(u32, 2457); pub const NERR_PasswordMismatch = @as(u32, 2458); pub const NERR_NoSuchServer = @as(u32, 2460); pub const NERR_NoSuchSession = @as(u32, 2461); pub const NERR_NoSuchConnection = @as(u32, 2462); pub const NERR_TooManyServers = @as(u32, 2463); pub const NERR_TooManySessions = @as(u32, 2464); pub const NERR_TooManyConnections = @as(u32, 2465); pub const NERR_TooManyFiles = @as(u32, 2466); pub const NERR_NoAlternateServers = @as(u32, 2467); pub const NERR_TryDownLevel = @as(u32, 2470); pub const NERR_UPSDriverNotStarted = @as(u32, 2480); pub const NERR_UPSInvalidConfig = @as(u32, 2481); pub const NERR_UPSInvalidCommPort = @as(u32, 2482); pub const NERR_UPSSignalAsserted = @as(u32, 2483); pub const NERR_UPSShutdownFailed = @as(u32, 2484); pub const NERR_BadDosRetCode = @as(u32, 2500); pub const NERR_ProgNeedsExtraMem = @as(u32, 2501); pub const NERR_BadDosFunction = @as(u32, 2502); pub const NERR_RemoteBootFailed = @as(u32, 2503); pub const NERR_BadFileCheckSum = @as(u32, 2504); pub const NERR_NoRplBootSystem = @as(u32, 2505); pub const NERR_RplLoadrNetBiosErr = @as(u32, 2506); pub const NERR_RplLoadrDiskErr = @as(u32, 2507); pub const NERR_ImageParamErr = @as(u32, 2508); pub const NERR_TooManyImageParams = @as(u32, 2509); pub const NERR_NonDosFloppyUsed = @as(u32, 2510); pub const NERR_RplBootRestart = @as(u32, 2511); pub const NERR_RplSrvrCallFailed = @as(u32, 2512); pub const NERR_CantConnectRplSrvr = @as(u32, 2513); pub const NERR_CantOpenImageFile = @as(u32, 2514); pub const NERR_CallingRplSrvr = @as(u32, 2515); pub const NERR_StartingRplBoot = @as(u32, 2516); pub const NERR_RplBootServiceTerm = @as(u32, 2517); pub const NERR_RplBootStartFailed = @as(u32, 2518); pub const NERR_RPL_CONNECTED = @as(u32, 2519); pub const NERR_BrowserConfiguredToNotRun = @as(u32, 2550); pub const NERR_RplNoAdaptersStarted = @as(u32, 2610); pub const NERR_RplBadRegistry = @as(u32, 2611); pub const NERR_RplBadDatabase = @as(u32, 2612); pub const NERR_RplRplfilesShare = @as(u32, 2613); pub const NERR_RplNotRplServer = @as(u32, 2614); pub const NERR_RplCannotEnum = @as(u32, 2615); pub const NERR_RplWkstaInfoCorrupted = @as(u32, 2616); pub const NERR_RplWkstaNotFound = @as(u32, 2617); pub const NERR_RplWkstaNameUnavailable = @as(u32, 2618); pub const NERR_RplProfileInfoCorrupted = @as(u32, 2619); pub const NERR_RplProfileNotFound = @as(u32, 2620); pub const NERR_RplProfileNameUnavailable = @as(u32, 2621); pub const NERR_RplProfileNotEmpty = @as(u32, 2622); pub const NERR_RplConfigInfoCorrupted = @as(u32, 2623); pub const NERR_RplConfigNotFound = @as(u32, 2624); pub const NERR_RplAdapterInfoCorrupted = @as(u32, 2625); pub const NERR_RplInternal = @as(u32, 2626); pub const NERR_RplVendorInfoCorrupted = @as(u32, 2627); pub const NERR_RplBootInfoCorrupted = @as(u32, 2628); pub const NERR_RplWkstaNeedsUserAcct = @as(u32, 2629); pub const NERR_RplNeedsRPLUSERAcct = @as(u32, 2630); pub const NERR_RplBootNotFound = @as(u32, 2631); pub const NERR_RplIncompatibleProfile = @as(u32, 2632); pub const NERR_RplAdapterNameUnavailable = @as(u32, 2633); pub const NERR_RplConfigNotEmpty = @as(u32, 2634); pub const NERR_RplBootInUse = @as(u32, 2635); pub const NERR_RplBackupDatabase = @as(u32, 2636); pub const NERR_RplAdapterNotFound = @as(u32, 2637); pub const NERR_RplVendorNotFound = @as(u32, 2638); pub const NERR_RplVendorNameUnavailable = @as(u32, 2639); pub const NERR_RplBootNameUnavailable = @as(u32, 2640); pub const NERR_RplConfigNameUnavailable = @as(u32, 2641); pub const NERR_DfsInternalCorruption = @as(u32, 2660); pub const NERR_DfsVolumeDataCorrupt = @as(u32, 2661); pub const NERR_DfsNoSuchVolume = @as(u32, 2662); pub const NERR_DfsVolumeAlreadyExists = @as(u32, 2663); pub const NERR_DfsAlreadyShared = @as(u32, 2664); pub const NERR_DfsNoSuchShare = @as(u32, 2665); pub const NERR_DfsNotALeafVolume = @as(u32, 2666); pub const NERR_DfsLeafVolume = @as(u32, 2667); pub const NERR_DfsVolumeHasMultipleServers = @as(u32, 2668); pub const NERR_DfsCantCreateJunctionPoint = @as(u32, 2669); pub const NERR_DfsServerNotDfsAware = @as(u32, 2670); pub const NERR_DfsBadRenamePath = @as(u32, 2671); pub const NERR_DfsVolumeIsOffline = @as(u32, 2672); pub const NERR_DfsNoSuchServer = @as(u32, 2673); pub const NERR_DfsCyclicalName = @as(u32, 2674); pub const NERR_DfsNotSupportedInServerDfs = @as(u32, 2675); pub const NERR_DfsDuplicateService = @as(u32, 2676); pub const NERR_DfsCantRemoveLastServerShare = @as(u32, 2677); pub const NERR_DfsVolumeIsInterDfs = @as(u32, 2678); pub const NERR_DfsInconsistent = @as(u32, 2679); pub const NERR_DfsServerUpgraded = @as(u32, 2680); pub const NERR_DfsDataIsIdentical = @as(u32, 2681); pub const NERR_DfsCantRemoveDfsRoot = @as(u32, 2682); pub const NERR_DfsChildOrParentInDfs = @as(u32, 2683); pub const NERR_DfsInternalError = @as(u32, 2690); pub const NERR_SetupAlreadyJoined = @as(u32, 2691); pub const NERR_SetupNotJoined = @as(u32, 2692); pub const NERR_SetupDomainController = @as(u32, 2693); pub const NERR_DefaultJoinRequired = @as(u32, 2694); pub const NERR_InvalidWorkgroupName = @as(u32, 2695); pub const NERR_NameUsesIncompatibleCodePage = @as(u32, 2696); pub const NERR_ComputerAccountNotFound = @as(u32, 2697); pub const NERR_PersonalSku = @as(u32, 2698); pub const NERR_SetupCheckDNSConfig = @as(u32, 2699); pub const NERR_AlreadyCloudDomainJoined = @as(u32, 2700); pub const NERR_PasswordMustChange = @as(u32, 2701); pub const NERR_AccountLockedOut = @as(u32, 2702); pub const NERR_PasswordTooLong = @as(u32, 2703); pub const NERR_PasswordNotComplexEnough = @as(u32, 2704); pub const NERR_PasswordFilterError = @as(u32, 2705); pub const NERR_NoOfflineJoinInfo = @as(u32, 2709); pub const NERR_BadOfflineJoinInfo = @as(u32, 2710); pub const NERR_CantCreateJoinInfo = @as(u32, 2711); pub const NERR_BadDomainJoinInfo = @as(u32, 2712); pub const NERR_JoinPerformedMustRestart = @as(u32, 2713); pub const NERR_NoJoinPending = @as(u32, 2714); pub const NERR_ValuesNotSet = @as(u32, 2715); pub const NERR_CantVerifyHostname = @as(u32, 2716); pub const NERR_CantLoadOfflineHive = @as(u32, 2717); pub const NERR_ConnectionInsecure = @as(u32, 2718); pub const NERR_ProvisioningBlobUnsupported = @as(u32, 2719); pub const NERR_DS8DCRequired = @as(u32, 2720); pub const NERR_LDAPCapableDCRequired = @as(u32, 2721); pub const NERR_DS8DCNotFound = @as(u32, 2722); pub const NERR_TargetVersionUnsupported = @as(u32, 2723); pub const NERR_InvalidMachineNameForJoin = @as(u32, 2724); pub const NERR_DS9DCNotFound = @as(u32, 2725); pub const NERR_PlainTextSecretsRequired = @as(u32, 2726); pub const NERR_CannotUnjoinAadDomain = @as(u32, 2727); pub const MAX_NERR = @as(u32, 2999); pub const UF_TEMP_DUPLICATE_ACCOUNT = @as(u32, 256); pub const UF_NORMAL_ACCOUNT = @as(u32, 512); pub const UF_INTERDOMAIN_TRUST_ACCOUNT = @as(u32, 2048); pub const UF_WORKSTATION_TRUST_ACCOUNT = @as(u32, 4096); pub const UF_SERVER_TRUST_ACCOUNT = @as(u32, 8192); pub const UF_MNS_LOGON_ACCOUNT = @as(u32, 131072); pub const UF_NO_AUTH_DATA_REQUIRED = @as(u32, 33554432); pub const UF_PARTIAL_SECRETS_ACCOUNT = @as(u32, 67108864); pub const UF_USE_AES_KEYS = @as(u32, 134217728); pub const LG_INCLUDE_INDIRECT = @as(u32, 1); pub const USER_NAME_PARMNUM = @as(u32, 1); pub const USER_PASSWORD_PARMNUM = @as(u32, 3); pub const USER_PASSWORD_AGE_PARMNUM = @as(u32, 4); pub const USER_PRIV_PARMNUM = @as(u32, 5); pub const USER_HOME_DIR_PARMNUM = @as(u32, 6); pub const USER_COMMENT_PARMNUM = @as(u32, 7); pub const USER_FLAGS_PARMNUM = @as(u32, 8); pub const USER_SCRIPT_PATH_PARMNUM = @as(u32, 9); pub const USER_AUTH_FLAGS_PARMNUM = @as(u32, 10); pub const USER_FULL_NAME_PARMNUM = @as(u32, 11); pub const USER_USR_COMMENT_PARMNUM = @as(u32, 12); pub const USER_PARMS_PARMNUM = @as(u32, 13); pub const USER_WORKSTATIONS_PARMNUM = @as(u32, 14); pub const USER_LAST_LOGON_PARMNUM = @as(u32, 15); pub const USER_LAST_LOGOFF_PARMNUM = @as(u32, 16); pub const USER_ACCT_EXPIRES_PARMNUM = @as(u32, 17); pub const USER_MAX_STORAGE_PARMNUM = @as(u32, 18); pub const USER_UNITS_PER_WEEK_PARMNUM = @as(u32, 19); pub const USER_LOGON_HOURS_PARMNUM = @as(u32, 20); pub const USER_PAD_PW_COUNT_PARMNUM = @as(u32, 21); pub const USER_NUM_LOGONS_PARMNUM = @as(u32, 22); pub const USER_LOGON_SERVER_PARMNUM = @as(u32, 23); pub const USER_COUNTRY_CODE_PARMNUM = @as(u32, 24); pub const USER_CODE_PAGE_PARMNUM = @as(u32, 25); pub const USER_PRIMARY_GROUP_PARMNUM = @as(u32, 51); pub const USER_PROFILE = @as(u32, 52); pub const USER_PROFILE_PARMNUM = @as(u32, 52); pub const USER_HOME_DIR_DRIVE_PARMNUM = @as(u32, 53); pub const UNITS_PER_DAY = @as(u32, 24); pub const USER_PRIV_MASK = @as(u32, 3); pub const MAX_PASSWD_LEN = @as(u32, 256); pub const DEF_MIN_PWLEN = @as(u32, 6); pub const DEF_PWUNIQUENESS = @as(u32, 5); pub const DEF_MAX_PWHIST = @as(u32, 8); pub const DEF_MAX_BADPW = @as(u32, 0); pub const VALIDATED_LOGON = @as(u32, 0); pub const PASSWORD_EXPIRED = @as(u32, 2); pub const NON_VALIDATED_LOGON = @as(u32, 3); pub const VALID_LOGOFF = @as(u32, 1); pub const MODALS_MIN_PASSWD_LEN_PARMNUM = @as(u32, 1); pub const MODALS_MAX_PASSWD_AGE_PARMNUM = @as(u32, 2); pub const MODALS_MIN_PASSWD_AGE_PARMNUM = @as(u32, 3); pub const MODALS_FORCE_LOGOFF_PARMNUM = @as(u32, 4); pub const MODALS_PASSWD_HIST_LEN_PARMNUM = @as(u32, 5); pub const MODALS_ROLE_PARMNUM = @as(u32, 6); pub const MODALS_PRIMARY_PARMNUM = @as(u32, 7); pub const MODALS_DOMAIN_NAME_PARMNUM = @as(u32, 8); pub const MODALS_DOMAIN_ID_PARMNUM = @as(u32, 9); pub const MODALS_LOCKOUT_DURATION_PARMNUM = @as(u32, 10); pub const MODALS_LOCKOUT_OBSERVATION_WINDOW_PARMNUM = @as(u32, 11); pub const MODALS_LOCKOUT_THRESHOLD_PARMNUM = @as(u32, 12); pub const GROUPIDMASK = @as(u32, 32768); pub const GROUP_ALL_PARMNUM = @as(u32, 0); pub const GROUP_NAME_PARMNUM = @as(u32, 1); pub const GROUP_COMMENT_PARMNUM = @as(u32, 2); pub const GROUP_ATTRIBUTES_PARMNUM = @as(u32, 3); pub const LOCALGROUP_NAME_PARMNUM = @as(u32, 1); pub const LOCALGROUP_COMMENT_PARMNUM = @as(u32, 2); pub const MAXPERMENTRIES = @as(u32, 64); pub const ACCESS_NONE = @as(u32, 0); pub const ACCESS_GROUP = @as(u32, 32768); pub const ACCESS_AUDIT = @as(u32, 1); pub const ACCESS_SUCCESS_OPEN = @as(u32, 16); pub const ACCESS_SUCCESS_WRITE = @as(u32, 32); pub const ACCESS_SUCCESS_DELETE = @as(u32, 64); pub const ACCESS_SUCCESS_ACL = @as(u32, 128); pub const ACCESS_SUCCESS_MASK = @as(u32, 240); pub const ACCESS_FAIL_OPEN = @as(u32, 256); pub const ACCESS_FAIL_WRITE = @as(u32, 512); pub const ACCESS_FAIL_DELETE = @as(u32, 1024); pub const ACCESS_FAIL_ACL = @as(u32, 2048); pub const ACCESS_FAIL_MASK = @as(u32, 3840); pub const ACCESS_FAIL_SHIFT = @as(u32, 4); pub const ACCESS_RESOURCE_NAME_PARMNUM = @as(u32, 1); pub const ACCESS_ATTR_PARMNUM = @as(u32, 2); pub const ACCESS_COUNT_PARMNUM = @as(u32, 3); pub const ACCESS_ACCESS_LIST_PARMNUM = @as(u32, 4); pub const NET_VALIDATE_PASSWORD_LAST_SET = @as(u32, 1); pub const NET_VALIDATE_BAD_PASSWORD_TIME = @as(u32, 2); pub const NET_VALIDATE_LOCKOUT_TIME = @as(u32, 4); pub const NET_VALIDATE_BAD_PASSWORD_COUNT = @as(u32, 8); pub const NET_VALIDATE_PASSWORD_HISTORY_LENGTH = @as(u32, 16); pub const NET_VALIDATE_PASSWORD_HISTORY = @as(u32, 32); pub const NETLOGON_CONTROL_QUERY = @as(u32, 1); pub const NETLOGON_CONTROL_REPLICATE = @as(u32, 2); pub const NETLOGON_CONTROL_SYNCHRONIZE = @as(u32, 3); pub const NETLOGON_CONTROL_PDC_REPLICATE = @as(u32, 4); pub const NETLOGON_CONTROL_REDISCOVER = @as(u32, 5); pub const NETLOGON_CONTROL_TC_QUERY = @as(u32, 6); pub const NETLOGON_CONTROL_TRANSPORT_NOTIFY = @as(u32, 7); pub const NETLOGON_CONTROL_FIND_USER = @as(u32, 8); pub const NETLOGON_CONTROL_CHANGE_PASSWORD = @as(u32, 9); pub const NETLOGON_CONTROL_TC_VERIFY = @as(u32, 10); pub const NETLOGON_CONTROL_FORCE_DNS_REG = @as(u32, 11); pub const NETLOGON_CONTROL_QUERY_DNS_REG = @as(u32, 12); pub const NETLOGON_CONTROL_QUERY_ENC_TYPES = @as(u32, 13); pub const NETLOGON_CONTROL_UNLOAD_NETLOGON_DLL = @as(u32, 65531); pub const NETLOGON_CONTROL_BACKUP_CHANGE_LOG = @as(u32, 65532); pub const NETLOGON_CONTROL_TRUNCATE_LOG = @as(u32, 65533); pub const NETLOGON_CONTROL_SET_DBFLAG = @as(u32, 65534); pub const NETLOGON_CONTROL_BREAKPOINT = @as(u32, 65535); pub const NETLOGON_REPLICATION_NEEDED = @as(u32, 1); pub const NETLOGON_REPLICATION_IN_PROGRESS = @as(u32, 2); pub const NETLOGON_FULL_SYNC_REPLICATION = @as(u32, 4); pub const NETLOGON_REDO_NEEDED = @as(u32, 8); pub const NETLOGON_HAS_IP = @as(u32, 16); pub const NETLOGON_HAS_TIMESERV = @as(u32, 32); pub const NETLOGON_DNS_UPDATE_FAILURE = @as(u32, 64); pub const NETLOGON_VERIFY_STATUS_RETURNED = @as(u32, 128); pub const ServiceAccountPasswordGUID = Guid.initString("<PASSWORD>"); pub const SERVICE_ACCOUNT_FLAG_LINK_TO_HOST_ONLY = @as(i32, 1); pub const SERVICE_ACCOUNT_FLAG_ADD_AGAINST_RODC = @as(i32, 2); pub const SERVICE_ACCOUNT_FLAG_UNLINK_FROM_HOST_ONLY = @as(i32, 1); pub const SERVICE_ACCOUNT_FLAG_REMOVE_OFFLINE = @as(i32, 2); pub const PRJOB_QSTATUS = @as(u32, 3); pub const PRJOB_DEVSTATUS = @as(u32, 508); pub const PRJOB_COMPLETE = @as(u32, 4); pub const PRJOB_INTERV = @as(u32, 8); pub const PRJOB_ERROR = @as(u32, 16); pub const PRJOB_DESTOFFLINE = @as(u32, 32); pub const PRJOB_DESTPAUSED = @as(u32, 64); pub const PRJOB_NOTIFY = @as(u32, 128); pub const PRJOB_DESTNOPAPER = @as(u32, 256); pub const PRJOB_DELETED = @as(u32, 32768); pub const PRJOB_QS_QUEUED = @as(u32, 0); pub const PRJOB_QS_PAUSED = @as(u32, 1); pub const PRJOB_QS_SPOOLING = @as(u32, 2); pub const PRJOB_QS_PRINTING = @as(u32, 3); pub const JOB_RUN_PERIODICALLY = @as(u32, 1); pub const JOB_EXEC_ERROR = @as(u32, 2); pub const JOB_RUNS_TODAY = @as(u32, 4); pub const JOB_ADD_CURRENT_DATE = @as(u32, 8); pub const JOB_NONINTERACTIVE = @as(u32, 16); pub const LOGFLAGS_FORWARD = @as(u32, 0); pub const LOGFLAGS_BACKWARD = @as(u32, 1); pub const LOGFLAGS_SEEK = @as(u32, 2); pub const ACTION_LOCKOUT = @as(u32, 0); pub const ACTION_ADMINUNLOCK = @as(u32, 1); pub const AE_SRVSTATUS = @as(u32, 0); pub const AE_SESSLOGON = @as(u32, 1); pub const AE_SESSLOGOFF = @as(u32, 2); pub const AE_SESSPWERR = @as(u32, 3); pub const AE_CONNSTART = @as(u32, 4); pub const AE_CONNSTOP = @as(u32, 5); pub const AE_CONNREJ = @as(u32, 6); pub const AE_RESACCESS = @as(u32, 7); pub const AE_RESACCESSREJ = @as(u32, 8); pub const AE_CLOSEFILE = @as(u32, 9); pub const AE_SERVICESTAT = @as(u32, 11); pub const AE_ACLMOD = @as(u32, 12); pub const AE_UASMOD = @as(u32, 13); pub const AE_NETLOGON = @as(u32, 14); pub const AE_NETLOGOFF = @as(u32, 15); pub const AE_NETLOGDENIED = @as(u32, 16); pub const AE_ACCLIMITEXCD = @as(u32, 17); pub const AE_RESACCESS2 = @as(u32, 18); pub const AE_ACLMODFAIL = @as(u32, 19); pub const AE_LOCKOUT = @as(u32, 20); pub const AE_GENERIC_TYPE = @as(u32, 21); pub const AE_SRVSTART = @as(u32, 0); pub const AE_SRVPAUSED = @as(u32, 1); pub const AE_SRVCONT = @as(u32, 2); pub const AE_SRVSTOP = @as(u32, 3); pub const AE_GUEST = @as(u32, 0); pub const AE_USER = @as(u32, 1); pub const AE_ADMIN = @as(u32, 2); pub const AE_NORMAL = @as(u32, 0); pub const AE_USERLIMIT = @as(u32, 0); pub const AE_GENERAL = @as(u32, 0); pub const AE_ERROR = @as(u32, 1); pub const AE_SESSDIS = @as(u32, 1); pub const AE_BADPW = @as(u32, 1); pub const AE_AUTODIS = @as(u32, 2); pub const AE_UNSHARE = @as(u32, 2); pub const AE_ADMINPRIVREQD = @as(u32, 2); pub const AE_ADMINDIS = @as(u32, 3); pub const AE_NOACCESSPERM = @as(u32, 3); pub const AE_ACCRESTRICT = @as(u32, 4); pub const AE_NORMAL_CLOSE = @as(u32, 0); pub const AE_SES_CLOSE = @as(u32, 1); pub const AE_ADMIN_CLOSE = @as(u32, 2); pub const AE_LIM_UNKNOWN = @as(u32, 0); pub const AE_LIM_LOGONHOURS = @as(u32, 1); pub const AE_LIM_EXPIRED = @as(u32, 2); pub const AE_LIM_INVAL_WKSTA = @as(u32, 3); pub const AE_LIM_DISABLED = @as(u32, 4); pub const AE_LIM_DELETED = @as(u32, 5); pub const AE_MOD = @as(u32, 0); pub const AE_DELETE = @as(u32, 1); pub const AE_ADD = @as(u32, 2); pub const AE_UAS_USER = @as(u32, 0); pub const AE_UAS_GROUP = @as(u32, 1); pub const AE_UAS_MODALS = @as(u32, 2); pub const SVAUD_SERVICE = @as(u32, 1); pub const SVAUD_GOODSESSLOGON = @as(u32, 6); pub const SVAUD_BADSESSLOGON = @as(u32, 24); pub const SVAUD_GOODNETLOGON = @as(u32, 96); pub const SVAUD_BADNETLOGON = @as(u32, 384); pub const SVAUD_GOODUSE = @as(u32, 1536); pub const SVAUD_BADUSE = @as(u32, 6144); pub const SVAUD_USERLIST = @as(u32, 8192); pub const SVAUD_PERMISSIONS = @as(u32, 16384); pub const SVAUD_RESOURCE = @as(u32, 32768); pub const SVAUD_LOGONLIM = @as(u32, 65536); pub const AA_AUDIT_ALL = @as(u32, 1); pub const AA_A_OWNER = @as(u32, 4); pub const AA_CLOSE = @as(u32, 8); pub const AA_S_OPEN = @as(u32, 16); pub const AA_S_WRITE = @as(u32, 32); pub const AA_S_CREATE = @as(u32, 32); pub const AA_S_DELETE = @as(u32, 64); pub const AA_S_ACL = @as(u32, 128); pub const AA_F_OPEN = @as(u32, 256); pub const AA_F_WRITE = @as(u32, 512); pub const AA_F_CREATE = @as(u32, 512); pub const AA_F_DELETE = @as(u32, 1024); pub const AA_F_ACL = @as(u32, 2048); pub const AA_A_OPEN = @as(u32, 4096); pub const AA_A_WRITE = @as(u32, 8192); pub const AA_A_CREATE = @as(u32, 8192); pub const AA_A_DELETE = @as(u32, 16384); pub const AA_A_ACL = @as(u32, 32768); pub const ERRLOG_BASE = @as(u32, 3100); pub const NELOG_Internal_Error = @as(u32, 3100); pub const NELOG_Resource_Shortage = @as(u32, 3101); pub const NELOG_Unable_To_Lock_Segment = @as(u32, 3102); pub const NELOG_Unable_To_Unlock_Segment = @as(u32, 3103); pub const NELOG_Uninstall_Service = @as(u32, 3104); pub const NELOG_Init_Exec_Fail = @as(u32, 3105); pub const NELOG_Ncb_Error = @as(u32, 3106); pub const NELOG_Net_Not_Started = @as(u32, 3107); pub const NELOG_Ioctl_Error = @as(u32, 3108); pub const NELOG_System_Semaphore = @as(u32, 3109); pub const NELOG_Init_OpenCreate_Err = @as(u32, 3110); pub const NELOG_NetBios = @as(u32, 3111); pub const NELOG_SMB_Illegal = @as(u32, 3112); pub const NELOG_Service_Fail = @as(u32, 3113); pub const NELOG_Entries_Lost = @as(u32, 3114); pub const NELOG_Init_Seg_Overflow = @as(u32, 3120); pub const NELOG_Srv_No_Mem_Grow = @as(u32, 3121); pub const NELOG_Access_File_Bad = @as(u32, 3122); pub const NELOG_Srvnet_Not_Started = @as(u32, 3123); pub const NELOG_Init_Chardev_Err = @as(u32, 3124); pub const NELOG_Remote_API = @as(u32, 3125); pub const NELOG_Ncb_TooManyErr = @as(u32, 3126); pub const NELOG_Mailslot_err = @as(u32, 3127); pub const NELOG_ReleaseMem_Alert = @as(u32, 3128); pub const NELOG_AT_cannot_write = @as(u32, 3129); pub const NELOG_Cant_Make_Msg_File = @as(u32, 3130); pub const NELOG_Exec_Netservr_NoMem = @as(u32, 3131); pub const NELOG_Server_Lock_Failure = @as(u32, 3132); pub const NELOG_Msg_Shutdown = @as(u32, 3140); pub const NELOG_Msg_Sem_Shutdown = @as(u32, 3141); pub const NELOG_Msg_Log_Err = @as(u32, 3150); pub const NELOG_VIO_POPUP_ERR = @as(u32, 3151); pub const NELOG_Msg_Unexpected_SMB_Type = @as(u32, 3152); pub const NELOG_Wksta_Infoseg = @as(u32, 3160); pub const NELOG_Wksta_Compname = @as(u32, 3161); pub const NELOG_Wksta_BiosThreadFailure = @as(u32, 3162); pub const NELOG_Wksta_IniSeg = @as(u32, 3163); pub const NELOG_Wksta_HostTab_Full = @as(u32, 3164); pub const NELOG_Wksta_Bad_Mailslot_SMB = @as(u32, 3165); pub const NELOG_Wksta_UASInit = @as(u32, 3166); pub const NELOG_Wksta_SSIRelogon = @as(u32, 3167); pub const NELOG_Build_Name = @as(u32, 3170); pub const NELOG_Name_Expansion = @as(u32, 3171); pub const NELOG_Message_Send = @as(u32, 3172); pub const NELOG_Mail_Slt_Err = @as(u32, 3173); pub const NELOG_AT_cannot_read = @as(u32, 3174); pub const NELOG_AT_sched_err = @as(u32, 3175); pub const NELOG_AT_schedule_file_created = @as(u32, 3176); pub const NELOG_Srvnet_NB_Open = @as(u32, 3177); pub const NELOG_AT_Exec_Err = @as(u32, 3178); pub const NELOG_Lazy_Write_Err = @as(u32, 3180); pub const NELOG_HotFix = @as(u32, 3181); pub const NELOG_HardErr_From_Server = @as(u32, 3182); pub const NELOG_LocalSecFail1 = @as(u32, 3183); pub const NELOG_LocalSecFail2 = @as(u32, 3184); pub const NELOG_LocalSecFail3 = @as(u32, 3185); pub const NELOG_LocalSecGeneralFail = @as(u32, 3186); pub const NELOG_NetWkSta_Internal_Error = @as(u32, 3190); pub const NELOG_NetWkSta_No_Resource = @as(u32, 3191); pub const NELOG_NetWkSta_SMB_Err = @as(u32, 3192); pub const NELOG_NetWkSta_VC_Err = @as(u32, 3193); pub const NELOG_NetWkSta_Stuck_VC_Err = @as(u32, 3194); pub const NELOG_NetWkSta_NCB_Err = @as(u32, 3195); pub const NELOG_NetWkSta_Write_Behind_Err = @as(u32, 3196); pub const NELOG_NetWkSta_Reset_Err = @as(u32, 3197); pub const NELOG_NetWkSta_Too_Many = @as(u32, 3198); pub const NELOG_Srv_Thread_Failure = @as(u32, 3204); pub const NELOG_Srv_Close_Failure = @as(u32, 3205); pub const NELOG_ReplUserCurDir = @as(u32, 3206); pub const NELOG_ReplCannotMasterDir = @as(u32, 3207); pub const NELOG_ReplUpdateError = @as(u32, 3208); pub const NELOG_ReplLostMaster = @as(u32, 3209); pub const NELOG_NetlogonAuthDCFail = @as(u32, 3210); pub const NELOG_ReplLogonFailed = @as(u32, 3211); pub const NELOG_ReplNetErr = @as(u32, 3212); pub const NELOG_ReplMaxFiles = @as(u32, 3213); pub const NELOG_ReplMaxTreeDepth = @as(u32, 3214); pub const NELOG_ReplBadMsg = @as(u32, 3215); pub const NELOG_ReplSysErr = @as(u32, 3216); pub const NELOG_ReplUserLoged = @as(u32, 3217); pub const NELOG_ReplBadImport = @as(u32, 3218); pub const NELOG_ReplBadExport = @as(u32, 3219); pub const NELOG_ReplSignalFileErr = @as(u32, 3220); pub const NELOG_DiskFT = @as(u32, 3221); pub const NELOG_ReplAccessDenied = @as(u32, 3222); pub const NELOG_NetlogonFailedPrimary = @as(u32, 3223); pub const NELOG_NetlogonPasswdSetFailed = @as(u32, 3224); pub const NELOG_NetlogonTrackingError = @as(u32, 3225); pub const NELOG_NetlogonSyncError = @as(u32, 3226); pub const NELOG_NetlogonRequireSignOrSealError = @as(u32, 3227); pub const NELOG_UPS_PowerOut = @as(u32, 3230); pub const NELOG_UPS_Shutdown = @as(u32, 3231); pub const NELOG_UPS_CmdFileError = @as(u32, 3232); pub const NELOG_UPS_CannotOpenDriver = @as(u32, 3233); pub const NELOG_UPS_PowerBack = @as(u32, 3234); pub const NELOG_UPS_CmdFileConfig = @as(u32, 3235); pub const NELOG_UPS_CmdFileExec = @as(u32, 3236); pub const NELOG_Missing_Parameter = @as(u32, 3250); pub const NELOG_Invalid_Config_Line = @as(u32, 3251); pub const NELOG_Invalid_Config_File = @as(u32, 3252); pub const NELOG_File_Changed = @as(u32, 3253); pub const NELOG_Files_Dont_Fit = @as(u32, 3254); pub const NELOG_Wrong_DLL_Version = @as(u32, 3255); pub const NELOG_Error_in_DLL = @as(u32, 3256); pub const NELOG_System_Error = @as(u32, 3257); pub const NELOG_FT_ErrLog_Too_Large = @as(u32, 3258); pub const NELOG_FT_Update_In_Progress = @as(u32, 3259); pub const NELOG_Joined_Domain = @as(u32, 3260); pub const NELOG_Joined_Workgroup = @as(u32, 3261); pub const NELOG_OEM_Code = @as(u32, 3299); pub const ERRLOG2_BASE = @as(u32, 5700); pub const NELOG_NetlogonSSIInitError = @as(u32, 5700); pub const NELOG_NetlogonFailedToUpdateTrustList = @as(u32, 5701); pub const NELOG_NetlogonFailedToAddRpcInterface = @as(u32, 5702); pub const NELOG_NetlogonFailedToReadMailslot = @as(u32, 5703); pub const NELOG_NetlogonFailedToRegisterSC = @as(u32, 5704); pub const NELOG_NetlogonChangeLogCorrupt = @as(u32, 5705); pub const NELOG_NetlogonFailedToCreateShare = @as(u32, 5706); pub const NELOG_NetlogonDownLevelLogonFailed = @as(u32, 5707); pub const NELOG_NetlogonDownLevelLogoffFailed = @as(u32, 5708); pub const NELOG_NetlogonNTLogonFailed = @as(u32, 5709); pub const NELOG_NetlogonNTLogoffFailed = @as(u32, 5710); pub const NELOG_NetlogonPartialSyncCallSuccess = @as(u32, 5711); pub const NELOG_NetlogonPartialSyncCallFailed = @as(u32, 5712); pub const NELOG_NetlogonFullSyncCallSuccess = @as(u32, 5713); pub const NELOG_NetlogonFullSyncCallFailed = @as(u32, 5714); pub const NELOG_NetlogonPartialSyncSuccess = @as(u32, 5715); pub const NELOG_NetlogonPartialSyncFailed = @as(u32, 5716); pub const NELOG_NetlogonFullSyncSuccess = @as(u32, 5717); pub const NELOG_NetlogonFullSyncFailed = @as(u32, 5718); pub const NELOG_NetlogonAuthNoDomainController = @as(u32, 5719); pub const NELOG_NetlogonAuthNoTrustLsaSecret = @as(u32, 5720); pub const NELOG_NetlogonAuthNoTrustSamAccount = @as(u32, 5721); pub const NELOG_NetlogonServerAuthFailed = @as(u32, 5722); pub const NELOG_NetlogonServerAuthNoTrustSamAccount = @as(u32, 5723); pub const NELOG_FailedToRegisterSC = @as(u32, 5724); pub const NELOG_FailedToSetServiceStatus = @as(u32, 5725); pub const NELOG_FailedToGetComputerName = @as(u32, 5726); pub const NELOG_DriverNotLoaded = @as(u32, 5727); pub const NELOG_NoTranportLoaded = @as(u32, 5728); pub const NELOG_NetlogonFailedDomainDelta = @as(u32, 5729); pub const NELOG_NetlogonFailedGlobalGroupDelta = @as(u32, 5730); pub const NELOG_NetlogonFailedLocalGroupDelta = @as(u32, 5731); pub const NELOG_NetlogonFailedUserDelta = @as(u32, 5732); pub const NELOG_NetlogonFailedPolicyDelta = @as(u32, 5733); pub const NELOG_NetlogonFailedTrustedDomainDelta = @as(u32, 5734); pub const NELOG_NetlogonFailedAccountDelta = @as(u32, 5735); pub const NELOG_NetlogonFailedSecretDelta = @as(u32, 5736); pub const NELOG_NetlogonSystemError = @as(u32, 5737); pub const NELOG_NetlogonDuplicateMachineAccounts = @as(u32, 5738); pub const NELOG_NetlogonTooManyGlobalGroups = @as(u32, 5739); pub const NELOG_NetlogonBrowserDriver = @as(u32, 5740); pub const NELOG_NetlogonAddNameFailure = @as(u32, 5741); pub const NELOG_RplMessages = @as(u32, 5742); pub const NELOG_RplXnsBoot = @as(u32, 5743); pub const NELOG_RplSystem = @as(u32, 5744); pub const NELOG_RplWkstaTimeout = @as(u32, 5745); pub const NELOG_RplWkstaFileOpen = @as(u32, 5746); pub const NELOG_RplWkstaFileRead = @as(u32, 5747); pub const NELOG_RplWkstaMemory = @as(u32, 5748); pub const NELOG_RplWkstaFileChecksum = @as(u32, 5749); pub const NELOG_RplWkstaFileLineCount = @as(u32, 5750); pub const NELOG_RplWkstaBbcFile = @as(u32, 5751); pub const NELOG_RplWkstaFileSize = @as(u32, 5752); pub const NELOG_RplWkstaInternal = @as(u32, 5753); pub const NELOG_RplWkstaWrongVersion = @as(u32, 5754); pub const NELOG_RplWkstaNetwork = @as(u32, 5755); pub const NELOG_RplAdapterResource = @as(u32, 5756); pub const NELOG_RplFileCopy = @as(u32, 5757); pub const NELOG_RplFileDelete = @as(u32, 5758); pub const NELOG_RplFilePerms = @as(u32, 5759); pub const NELOG_RplCheckConfigs = @as(u32, 5760); pub const NELOG_RplCreateProfiles = @as(u32, 5761); pub const NELOG_RplRegistry = @as(u32, 5762); pub const NELOG_RplReplaceRPLDISK = @as(u32, 5763); pub const NELOG_RplCheckSecurity = @as(u32, 5764); pub const NELOG_RplBackupDatabase = @as(u32, 5765); pub const NELOG_RplInitDatabase = @as(u32, 5766); pub const NELOG_RplRestoreDatabaseFailure = @as(u32, 5767); pub const NELOG_RplRestoreDatabaseSuccess = @as(u32, 5768); pub const NELOG_RplInitRestoredDatabase = @as(u32, 5769); pub const NELOG_NetlogonSessionTypeWrong = @as(u32, 5770); pub const NELOG_RplUpgradeDBTo40 = @as(u32, 5771); pub const NELOG_NetlogonLanmanBdcsNotAllowed = @as(u32, 5772); pub const NELOG_NetlogonNoDynamicDns = @as(u32, 5773); pub const NELOG_NetlogonDynamicDnsRegisterFailure = @as(u32, 5774); pub const NELOG_NetlogonDynamicDnsDeregisterFailure = @as(u32, 5775); pub const NELOG_NetlogonFailedFileCreate = @as(u32, 5776); pub const NELOG_NetlogonGetSubnetToSite = @as(u32, 5777); pub const NELOG_NetlogonNoSiteForClient = @as(u32, 5778); pub const NELOG_NetlogonBadSiteName = @as(u32, 5779); pub const NELOG_NetlogonBadSubnetName = @as(u32, 5780); pub const NELOG_NetlogonDynamicDnsServerFailure = @as(u32, 5781); pub const NELOG_NetlogonDynamicDnsFailure = @as(u32, 5782); pub const NELOG_NetlogonRpcCallCancelled = @as(u32, 5783); pub const NELOG_NetlogonDcSiteCovered = @as(u32, 5784); pub const NELOG_NetlogonDcSiteNotCovered = @as(u32, 5785); pub const NELOG_NetlogonGcSiteCovered = @as(u32, 5786); pub const NELOG_NetlogonGcSiteNotCovered = @as(u32, 5787); pub const NELOG_NetlogonFailedSpnUpdate = @as(u32, 5788); pub const NELOG_NetlogonFailedDnsHostNameUpdate = @as(u32, 5789); pub const NELOG_NetlogonAuthNoUplevelDomainController = @as(u32, 5790); pub const NELOG_NetlogonAuthDomainDowngraded = @as(u32, 5791); pub const NELOG_NetlogonNdncSiteCovered = @as(u32, 5792); pub const NELOG_NetlogonNdncSiteNotCovered = @as(u32, 5793); pub const NELOG_NetlogonDcOldSiteCovered = @as(u32, 5794); pub const NELOG_NetlogonDcSiteNotCoveredAuto = @as(u32, 5795); pub const NELOG_NetlogonGcOldSiteCovered = @as(u32, 5796); pub const NELOG_NetlogonGcSiteNotCoveredAuto = @as(u32, 5797); pub const NELOG_NetlogonNdncOldSiteCovered = @as(u32, 5798); pub const NELOG_NetlogonNdncSiteNotCoveredAuto = @as(u32, 5799); pub const NELOG_NetlogonSpnMultipleSamAccountNames = @as(u32, 5800); pub const NELOG_NetlogonSpnCrackNamesFailure = @as(u32, 5801); pub const NELOG_NetlogonNoAddressToSiteMapping = @as(u32, 5802); pub const NELOG_NetlogonInvalidGenericParameterValue = @as(u32, 5803); pub const NELOG_NetlogonInvalidDwordParameterValue = @as(u32, 5804); pub const NELOG_NetlogonServerAuthFailedNoAccount = @as(u32, 5805); pub const NELOG_NetlogonNoDynamicDnsManual = @as(u32, 5806); pub const NELOG_NetlogonNoSiteForClients = @as(u32, 5807); pub const NELOG_NetlogonDnsDeregAborted = @as(u32, 5808); pub const NELOG_NetlogonRpcPortRequestFailure = @as(u32, 5809); pub const NELOG_NetlogonPartialSiteMappingForClients = @as(u32, 5810); pub const NELOG_NetlogonRemoteDynamicDnsRegisterFailure = @as(u32, 5811); pub const NELOG_NetlogonRemoteDynamicDnsDeregisterFailure = @as(u32, 5812); pub const NELOG_NetlogonRejectedRemoteDynamicDnsRegister = @as(u32, 5813); pub const NELOG_NetlogonRejectedRemoteDynamicDnsDeregister = @as(u32, 5814); pub const NELOG_NetlogonRemoteDynamicDnsUpdateRequestFailure = @as(u32, 5815); pub const NELOG_NetlogonUserValidationReqInitialTimeOut = @as(u32, 5816); pub const NELOG_NetlogonUserValidationReqRecurringTimeOut = @as(u32, 5817); pub const NELOG_NetlogonUserValidationReqWaitInitialWarning = @as(u32, 5818); pub const NELOG_NetlogonUserValidationReqWaitRecurringWarning = @as(u32, 5819); pub const NELOG_NetlogonFailedToAddAuthzRpcInterface = @as(u32, 5820); pub const NELOG_NetLogonFailedToInitializeAuthzRm = @as(u32, 5821); pub const NELOG_NetLogonFailedToInitializeRPCSD = @as(u32, 5822); pub const NELOG_NetlogonMachinePasswdSetSucceeded = @as(u32, 5823); pub const NELOG_NetlogonMsaPasswdSetSucceeded = @as(u32, 5824); pub const NELOG_NetlogonDnsHostNameLowerCasingFailed = @as(u32, 5825); pub const NETLOG_NetlogonNonWindowsSupportsSecureRpc = @as(u32, 5826); pub const NETLOG_NetlogonUnsecureRpcClient = @as(u32, 5827); pub const NETLOG_NetlogonUnsecureRpcTrust = @as(u32, 5828); pub const NETLOG_NetlogonUnsecuredRpcMachineTemporarilyAllowed = @as(u32, 5829); pub const NETLOG_NetlogonUnsecureRpcMachineAllowedBySsdl = @as(u32, 5830); pub const NETLOG_NetlogonUnsecureRpcTrustAllowedBySsdl = @as(u32, 5831); pub const NETSETUP_ACCT_DELETE = @as(u32, 4); pub const NETSETUP_DNS_NAME_CHANGES_ONLY = @as(u32, 4096); pub const NETSETUP_INSTALL_INVOCATION = @as(u32, 262144); pub const NETSETUP_ALT_SAMACCOUNTNAME = @as(u32, 131072); pub const NET_IGNORE_UNSUPPORTED_FLAGS = @as(u32, 1); pub const NETSETUP_PROVISION_PERSISTENTSITE = @as(u32, 32); pub const NETSETUP_PROVISION_CHECK_PWD_ONLY = @as(u32, 2147483648); pub const NETSETUP_PROVISIONING_PARAMS_WIN8_VERSION = @as(u32, 1); pub const NETSETUP_PROVISIONING_PARAMS_CURRENT_VERSION = @as(u32, 2); pub const MSGNAME_NOT_FORWARDED = @as(u32, 0); pub const MSGNAME_FORWARDED_TO = @as(u32, 4); pub const MSGNAME_FORWARDED_FROM = @as(u32, 16); pub const SUPPORTS_ANY = @as(i32, -1); pub const NO_PERMISSION_REQUIRED = @as(u32, 1); pub const ALLOCATE_RESPONSE = @as(u32, 2); pub const USE_SPECIFIC_TRANSPORT = @as(u32, 2147483648); pub const SV_PLATFORM_ID_OS2 = @as(u32, 400); pub const SV_PLATFORM_ID_NT = @as(u32, 500); pub const MAJOR_VERSION_MASK = @as(u32, 15); pub const SV_NODISC = @as(i32, -1); pub const SV_PLATFORM_ID_PARMNUM = @as(u32, 101); pub const SV_NAME_PARMNUM = @as(u32, 102); pub const SV_VERSION_MAJOR_PARMNUM = @as(u32, 103); pub const SV_VERSION_MINOR_PARMNUM = @as(u32, 104); pub const SV_TYPE_PARMNUM = @as(u32, 105); pub const SV_COMMENT_PARMNUM = @as(u32, 5); pub const SV_USERS_PARMNUM = @as(u32, 107); pub const SV_DISC_PARMNUM = @as(u32, 10); pub const SV_HIDDEN_PARMNUM = @as(u32, 16); pub const SV_ANNOUNCE_PARMNUM = @as(u32, 17); pub const SV_ANNDELTA_PARMNUM = @as(u32, 18); pub const SV_USERPATH_PARMNUM = @as(u32, 112); pub const SV_ULIST_MTIME_PARMNUM = @as(u32, 401); pub const SV_GLIST_MTIME_PARMNUM = @as(u32, 402); pub const SV_ALIST_MTIME_PARMNUM = @as(u32, 403); pub const SV_ALERTS_PARMNUM = @as(u32, 11); pub const SV_SECURITY_PARMNUM = @as(u32, 405); pub const SV_NUMADMIN_PARMNUM = @as(u32, 406); pub const SV_LANMASK_PARMNUM = @as(u32, 407); pub const SV_GUESTACC_PARMNUM = @as(u32, 408); pub const SV_CHDEVQ_PARMNUM = @as(u32, 410); pub const SV_CHDEVJOBS_PARMNUM = @as(u32, 411); pub const SV_CONNECTIONS_PARMNUM = @as(u32, 412); pub const SV_SHARES_PARMNUM = @as(u32, 413); pub const SV_OPENFILES_PARMNUM = @as(u32, 414); pub const SV_SESSREQS_PARMNUM = @as(u32, 417); pub const SV_ACTIVELOCKS_PARMNUM = @as(u32, 419); pub const SV_NUMREQBUF_PARMNUM = @as(u32, 420); pub const SV_NUMBIGBUF_PARMNUM = @as(u32, 422); pub const SV_NUMFILETASKS_PARMNUM = @as(u32, 423); pub const SV_ALERTSCHED_PARMNUM = @as(u32, 37); pub const SV_ERRORALERT_PARMNUM = @as(u32, 38); pub const SV_LOGONALERT_PARMNUM = @as(u32, 39); pub const SV_ACCESSALERT_PARMNUM = @as(u32, 40); pub const SV_DISKALERT_PARMNUM = @as(u32, 41); pub const SV_NETIOALERT_PARMNUM = @as(u32, 42); pub const SV_MAXAUDITSZ_PARMNUM = @as(u32, 43); pub const SV_SRVHEURISTICS_PARMNUM = @as(u32, 431); pub const SV_SESSOPENS_PARMNUM = @as(u32, 501); pub const SV_SESSVCS_PARMNUM = @as(u32, 502); pub const SV_OPENSEARCH_PARMNUM = @as(u32, 503); pub const SV_SIZREQBUF_PARMNUM = @as(u32, 504); pub const SV_INITWORKITEMS_PARMNUM = @as(u32, 505); pub const SV_MAXWORKITEMS_PARMNUM = @as(u32, 506); pub const SV_RAWWORKITEMS_PARMNUM = @as(u32, 507); pub const SV_IRPSTACKSIZE_PARMNUM = @as(u32, 508); pub const SV_MAXRAWBUFLEN_PARMNUM = @as(u32, 509); pub const SV_SESSUSERS_PARMNUM = @as(u32, 510); pub const SV_SESSCONNS_PARMNUM = @as(u32, 511); pub const SV_MAXNONPAGEDMEMORYUSAGE_PARMNUM = @as(u32, 512); pub const SV_MAXPAGEDMEMORYUSAGE_PARMNUM = @as(u32, 513); pub const SV_ENABLESOFTCOMPAT_PARMNUM = @as(u32, 514); pub const SV_ENABLEFORCEDLOGOFF_PARMNUM = @as(u32, 515); pub const SV_TIMESOURCE_PARMNUM = @as(u32, 516); pub const SV_ACCEPTDOWNLEVELAPIS_PARMNUM = @as(u32, 517); pub const SV_LMANNOUNCE_PARMNUM = @as(u32, 518); pub const SV_DOMAIN_PARMNUM = @as(u32, 519); pub const SV_MAXCOPYREADLEN_PARMNUM = @as(u32, 520); pub const SV_MAXCOPYWRITELEN_PARMNUM = @as(u32, 521); pub const SV_MINKEEPSEARCH_PARMNUM = @as(u32, 522); pub const SV_MAXKEEPSEARCH_PARMNUM = @as(u32, 523); pub const SV_MINKEEPCOMPLSEARCH_PARMNUM = @as(u32, 524); pub const SV_MAXKEEPCOMPLSEARCH_PARMNUM = @as(u32, 525); pub const SV_THREADCOUNTADD_PARMNUM = @as(u32, 526); pub const SV_NUMBLOCKTHREADS_PARMNUM = @as(u32, 527); pub const SV_SCAVTIMEOUT_PARMNUM = @as(u32, 528); pub const SV_MINRCVQUEUE_PARMNUM = @as(u32, 529); pub const SV_MINFREEWORKITEMS_PARMNUM = @as(u32, 530); pub const SV_XACTMEMSIZE_PARMNUM = @as(u32, 531); pub const SV_THREADPRIORITY_PARMNUM = @as(u32, 532); pub const SV_MAXMPXCT_PARMNUM = @as(u32, 533); pub const SV_OPLOCKBREAKWAIT_PARMNUM = @as(u32, 534); pub const SV_OPLOCKBREAKRESPONSEWAIT_PARMNUM = @as(u32, 535); pub const SV_ENABLEOPLOCKS_PARMNUM = @as(u32, 536); pub const SV_ENABLEOPLOCKFORCECLOSE_PARMNUM = @as(u32, 537); pub const SV_ENABLEFCBOPENS_PARMNUM = @as(u32, 538); pub const SV_ENABLERAW_PARMNUM = @as(u32, 539); pub const SV_ENABLESHAREDNETDRIVES_PARMNUM = @as(u32, 540); pub const SV_MINFREECONNECTIONS_PARMNUM = @as(u32, 541); pub const SV_MAXFREECONNECTIONS_PARMNUM = @as(u32, 542); pub const SV_INITSESSTABLE_PARMNUM = @as(u32, 543); pub const SV_INITCONNTABLE_PARMNUM = @as(u32, 544); pub const SV_INITFILETABLE_PARMNUM = @as(u32, 545); pub const SV_INITSEARCHTABLE_PARMNUM = @as(u32, 546); pub const SV_ALERTSCHEDULE_PARMNUM = @as(u32, 547); pub const SV_ERRORTHRESHOLD_PARMNUM = @as(u32, 548); pub const SV_NETWORKERRORTHRESHOLD_PARMNUM = @as(u32, 549); pub const SV_DISKSPACETHRESHOLD_PARMNUM = @as(u32, 550); pub const SV_MAXLINKDELAY_PARMNUM = @as(u32, 552); pub const SV_MINLINKTHROUGHPUT_PARMNUM = @as(u32, 553); pub const SV_LINKINFOVALIDTIME_PARMNUM = @as(u32, 554); pub const SV_SCAVQOSINFOUPDATETIME_PARMNUM = @as(u32, 555); pub const SV_MAXWORKITEMIDLETIME_PARMNUM = @as(u32, 556); pub const SV_MAXRAWWORKITEMS_PARMNUM = @as(u32, 557); pub const SV_PRODUCTTYPE_PARMNUM = @as(u32, 560); pub const SV_SERVERSIZE_PARMNUM = @as(u32, 561); pub const SV_CONNECTIONLESSAUTODISC_PARMNUM = @as(u32, 562); pub const SV_SHARINGVIOLATIONRETRIES_PARMNUM = @as(u32, 563); pub const SV_SHARINGVIOLATIONDELAY_PARMNUM = @as(u32, 564); pub const SV_MAXGLOBALOPENSEARCH_PARMNUM = @as(u32, 565); pub const SV_REMOVEDUPLICATESEARCHES_PARMNUM = @as(u32, 566); pub const SV_LOCKVIOLATIONRETRIES_PARMNUM = @as(u32, 567); pub const SV_LOCKVIOLATIONOFFSET_PARMNUM = @as(u32, 568); pub const SV_LOCKVIOLATIONDELAY_PARMNUM = @as(u32, 569); pub const SV_MDLREADSWITCHOVER_PARMNUM = @as(u32, 570); pub const SV_CACHEDOPENLIMIT_PARMNUM = @as(u32, 571); pub const SV_CRITICALTHREADS_PARMNUM = @as(u32, 572); pub const SV_RESTRICTNULLSESSACCESS_PARMNUM = @as(u32, 573); pub const SV_ENABLEWFW311DIRECTIPX_PARMNUM = @as(u32, 574); pub const SV_OTHERQUEUEAFFINITY_PARMNUM = @as(u32, 575); pub const SV_QUEUESAMPLESECS_PARMNUM = @as(u32, 576); pub const SV_BALANCECOUNT_PARMNUM = @as(u32, 577); pub const SV_PREFERREDAFFINITY_PARMNUM = @as(u32, 578); pub const SV_MAXFREERFCBS_PARMNUM = @as(u32, 579); pub const SV_MAXFREEMFCBS_PARMNUM = @as(u32, 580); pub const SV_MAXFREELFCBS_PARMNUM = @as(u32, 581); pub const SV_MAXFREEPAGEDPOOLCHUNKS_PARMNUM = @as(u32, 582); pub const SV_MINPAGEDPOOLCHUNKSIZE_PARMNUM = @as(u32, 583); pub const SV_MAXPAGEDPOOLCHUNKSIZE_PARMNUM = @as(u32, 584); pub const SV_SENDSFROMPREFERREDPROCESSOR_PARMNUM = @as(u32, 585); pub const SV_MAXTHREADSPERQUEUE_PARMNUM = @as(u32, 586); pub const SV_CACHEDDIRECTORYLIMIT_PARMNUM = @as(u32, 587); pub const SV_MAXCOPYLENGTH_PARMNUM = @as(u32, 588); pub const SV_ENABLECOMPRESSION_PARMNUM = @as(u32, 590); pub const SV_AUTOSHAREWKS_PARMNUM = @as(u32, 591); pub const SV_AUTOSHARESERVER_PARMNUM = @as(u32, 592); pub const SV_ENABLESECURITYSIGNATURE_PARMNUM = @as(u32, 593); pub const SV_REQUIRESECURITYSIGNATURE_PARMNUM = @as(u32, 594); pub const SV_MINCLIENTBUFFERSIZE_PARMNUM = @as(u32, 595); pub const SV_CONNECTIONNOSESSIONSTIMEOUT_PARMNUM = @as(u32, 596); pub const SV_IDLETHREADTIMEOUT_PARMNUM = @as(u32, 597); pub const SV_ENABLEW9XSECURITYSIGNATURE_PARMNUM = @as(u32, 598); pub const SV_ENFORCEKERBEROSREAUTHENTICATION_PARMNUM = @as(u32, 599); pub const SV_DISABLEDOS_PARMNUM = @as(u32, 600); pub const SV_LOWDISKSPACEMINIMUM_PARMNUM = @as(u32, 601); pub const SV_DISABLESTRICTNAMECHECKING_PARMNUM = @as(u32, 602); pub const SV_ENABLEAUTHENTICATEUSERSHARING_PARMNUM = @as(u32, 603); pub const SVI1_NUM_ELEMENTS = @as(u32, 5); pub const SVI2_NUM_ELEMENTS = @as(u32, 40); pub const SVI3_NUM_ELEMENTS = @as(u32, 44); pub const SV_MAX_CMD_LEN = @as(u32, 256); pub const SW_AUTOPROF_LOAD_MASK = @as(u32, 1); pub const SW_AUTOPROF_SAVE_MASK = @as(u32, 2); pub const SV_MAX_SRV_HEUR_LEN = @as(u32, 32); pub const SV_USERS_PER_LICENSE = @as(u32, 5); pub const SVTI2_REMAP_PIPE_NAMES = @as(u32, 2); pub const SVTI2_SCOPED_NAME = @as(u32, 4); pub const SVTI2_CLUSTER_NAME = @as(u32, 8); pub const SVTI2_CLUSTER_DNN_NAME = @as(u32, 16); pub const SVTI2_UNICODE_TRANSPORT_ADDRESS = @as(u32, 32); pub const SVTI2_RESERVED1 = @as(u32, 4096); pub const SVTI2_RESERVED2 = @as(u32, 8192); pub const SVTI2_RESERVED3 = @as(u32, 16384); pub const SRV_SUPPORT_HASH_GENERATION = @as(u32, 1); pub const SRV_HASH_GENERATION_ACTIVE = @as(u32, 2); pub const SERVICE_INSTALL_STATE = @as(u32, 3); pub const SERVICE_UNINSTALLED = @as(u32, 0); pub const SERVICE_INSTALL_PENDING = @as(u32, 1); pub const SERVICE_UNINSTALL_PENDING = @as(u32, 2); pub const SERVICE_INSTALLED = @as(u32, 3); pub const SERVICE_PAUSE_STATE = @as(u32, 12); pub const LM20_SERVICE_ACTIVE = @as(u32, 0); pub const LM20_SERVICE_CONTINUE_PENDING = @as(u32, 4); pub const LM20_SERVICE_PAUSE_PENDING = @as(u32, 8); pub const LM20_SERVICE_PAUSED = @as(u32, 12); pub const SERVICE_NOT_UNINSTALLABLE = @as(u32, 0); pub const SERVICE_UNINSTALLABLE = @as(u32, 16); pub const SERVICE_NOT_PAUSABLE = @as(u32, 0); pub const SERVICE_PAUSABLE = @as(u32, 32); pub const SERVICE_REDIR_PAUSED = @as(u32, 1792); pub const SERVICE_REDIR_DISK_PAUSED = @as(u32, 256); pub const SERVICE_REDIR_PRINT_PAUSED = @as(u32, 512); pub const SERVICE_REDIR_COMM_PAUSED = @as(u32, 1024); pub const SERVICE_CTRL_INTERROGATE = @as(u32, 0); pub const SERVICE_CTRL_PAUSE = @as(u32, 1); pub const SERVICE_CTRL_CONTINUE = @as(u32, 2); pub const SERVICE_CTRL_UNINSTALL = @as(u32, 3); pub const SERVICE_CTRL_REDIR_DISK = @as(u32, 1); pub const SERVICE_CTRL_REDIR_PRINT = @as(u32, 2); pub const SERVICE_CTRL_REDIR_COMM = @as(u32, 4); pub const SERVICE_IP_NO_HINT = @as(u32, 0); pub const SERVICE_CCP_NO_HINT = @as(u32, 0); pub const SERVICE_IP_QUERY_HINT = @as(u32, 65536); pub const SERVICE_CCP_QUERY_HINT = @as(u32, 65536); pub const SERVICE_IP_CHKPT_NUM = @as(u32, 255); pub const SERVICE_CCP_CHKPT_NUM = @as(u32, 255); pub const SERVICE_IP_WAIT_TIME = @as(u32, 65280); pub const SERVICE_CCP_WAIT_TIME = @as(u32, 65280); pub const SERVICE_IP_WAITTIME_SHIFT = @as(u32, 8); pub const SERVICE_NTIP_WAITTIME_SHIFT = @as(u32, 12); pub const UPPER_HINT_MASK = @as(u32, 65280); pub const LOWER_HINT_MASK = @as(u32, 255); pub const UPPER_GET_HINT_MASK = @as(u32, 267386880); pub const LOWER_GET_HINT_MASK = @as(u32, 65280); pub const SERVICE_NT_MAXTIME = @as(u32, 65535); pub const SERVICE_RESRV_MASK = @as(u32, 131071); pub const SERVICE_MAXTIME = @as(u32, 255); pub const SERVICE_BASE = @as(u32, 3050); pub const SERVICE_UIC_NORMAL = @as(u32, 0); pub const SERVICE_UIC_BADPARMVAL = @as(u32, 3051); pub const SERVICE_UIC_MISSPARM = @as(u32, 3052); pub const SERVICE_UIC_UNKPARM = @as(u32, 3053); pub const SERVICE_UIC_RESOURCE = @as(u32, 3054); pub const SERVICE_UIC_CONFIG = @as(u32, 3055); pub const SERVICE_UIC_SYSTEM = @as(u32, 3056); pub const SERVICE_UIC_INTERNAL = @as(u32, 3057); pub const SERVICE_UIC_AMBIGPARM = @as(u32, 3058); pub const SERVICE_UIC_DUPPARM = @as(u32, 3059); pub const SERVICE_UIC_KILL = @as(u32, 3060); pub const SERVICE_UIC_EXEC = @as(u32, 3061); pub const SERVICE_UIC_SUBSERV = @as(u32, 3062); pub const SERVICE_UIC_CONFLPARM = @as(u32, 3063); pub const SERVICE_UIC_FILE = @as(u32, 3064); pub const SERVICE_UIC_M_NULL = @as(u32, 0); pub const SERVICE_UIC_M_MEMORY = @as(u32, 3070); pub const SERVICE_UIC_M_DISK = @as(u32, 3071); pub const SERVICE_UIC_M_THREADS = @as(u32, 3072); pub const SERVICE_UIC_M_PROCESSES = @as(u32, 3073); pub const SERVICE_UIC_M_SECURITY = @as(u32, 3074); pub const SERVICE_UIC_M_LANROOT = @as(u32, 3075); pub const SERVICE_UIC_M_REDIR = @as(u32, 3076); pub const SERVICE_UIC_M_SERVER = @as(u32, 3077); pub const SERVICE_UIC_M_SEC_FILE_ERR = @as(u32, 3078); pub const SERVICE_UIC_M_FILES = @as(u32, 3079); pub const SERVICE_UIC_M_LOGS = @as(u32, 3080); pub const SERVICE_UIC_M_LANGROUP = @as(u32, 3081); pub const SERVICE_UIC_M_MSGNAME = @as(u32, 3082); pub const SERVICE_UIC_M_ANNOUNCE = @as(u32, 3083); pub const SERVICE_UIC_M_UAS = @as(u32, 3084); pub const SERVICE_UIC_M_SERVER_SEC_ERR = @as(u32, 3085); pub const SERVICE_UIC_M_WKSTA = @as(u32, 3087); pub const SERVICE_UIC_M_ERRLOG = @as(u32, 3088); pub const SERVICE_UIC_M_FILE_UW = @as(u32, 3089); pub const SERVICE_UIC_M_ADDPAK = @as(u32, 3090); pub const SERVICE_UIC_M_LAZY = @as(u32, 3091); pub const SERVICE_UIC_M_UAS_MACHINE_ACCT = @as(u32, 3092); pub const SERVICE_UIC_M_UAS_SERVERS_NMEMB = @as(u32, 3093); pub const SERVICE_UIC_M_UAS_SERVERS_NOGRP = @as(u32, 3094); pub const SERVICE_UIC_M_UAS_INVALID_ROLE = @as(u32, 3095); pub const SERVICE_UIC_M_NETLOGON_NO_DC = @as(u32, 3096); pub const SERVICE_UIC_M_NETLOGON_DC_CFLCT = @as(u32, 3097); pub const SERVICE_UIC_M_NETLOGON_AUTH = @as(u32, 3098); pub const SERVICE_UIC_M_UAS_PROLOG = @as(u32, 3099); pub const SERVICE2_BASE = @as(u32, 5600); pub const SERVICE_UIC_M_NETLOGON_MPATH = @as(u32, 5600); pub const SERVICE_UIC_M_LSA_MACHINE_ACCT = @as(u32, 5601); pub const SERVICE_UIC_M_DATABASE_ERROR = @as(u32, 5602); pub const USE_FLAG_GLOBAL_MAPPING = @as(u32, 65536); pub const USE_LOCAL_PARMNUM = @as(u32, 1); pub const USE_REMOTE_PARMNUM = @as(u32, 2); pub const USE_PASSWORD_PARMNUM = @as(u32, 3); pub const USE_ASGTYPE_PARMNUM = @as(u32, 4); pub const USE_USERNAME_PARMNUM = @as(u32, 5); pub const USE_DOMAINNAME_PARMNUM = @as(u32, 6); pub const USE_FLAGS_PARMNUM = @as(u32, 7); pub const USE_AUTHIDENTITY_PARMNUM = @as(u32, 8); pub const USE_SD_PARMNUM = @as(u32, 9); pub const USE_OPTIONS_PARMNUM = @as(u32, 10); pub const USE_OK = @as(u32, 0); pub const USE_PAUSED = @as(u32, 1); pub const USE_SESSLOST = @as(u32, 2); pub const USE_DISCONN = @as(u32, 2); pub const USE_NETERR = @as(u32, 3); pub const USE_CONN = @as(u32, 4); pub const USE_RECONN = @as(u32, 5); pub const USE_CHARDEV = @as(u32, 2); pub const CREATE_NO_CONNECT = @as(u32, 1); pub const CREATE_BYPASS_CSC = @as(u32, 2); pub const CREATE_CRED_RESET = @as(u32, 4); pub const USE_DEFAULT_CREDENTIALS = @as(u32, 4); pub const CREATE_REQUIRE_CONNECTION_INTEGRITY = @as(u32, 8); pub const CREATE_REQUIRE_CONNECTION_PRIVACY = @as(u32, 16); pub const CREATE_PERSIST_MAPPING = @as(u32, 32); pub const CREATE_WRITE_THROUGH_SEMANTICS = @as(u32, 64); pub const CREATE_GLOBAL_MAPPING = @as(u32, 256); pub const WKSTA_PLATFORM_ID_PARMNUM = @as(u32, 100); pub const WKSTA_COMPUTERNAME_PARMNUM = @as(u32, 1); pub const WKSTA_LANGROUP_PARMNUM = @as(u32, 2); pub const WKSTA_VER_MAJOR_PARMNUM = @as(u32, 4); pub const WKSTA_VER_MINOR_PARMNUM = @as(u32, 5); pub const WKSTA_LOGGED_ON_USERS_PARMNUM = @as(u32, 6); pub const WKSTA_LANROOT_PARMNUM = @as(u32, 7); pub const WKSTA_LOGON_DOMAIN_PARMNUM = @as(u32, 8); pub const WKSTA_LOGON_SERVER_PARMNUM = @as(u32, 9); pub const WKSTA_CHARWAIT_PARMNUM = @as(u32, 10); pub const WKSTA_CHARTIME_PARMNUM = @as(u32, 11); pub const WKSTA_CHARCOUNT_PARMNUM = @as(u32, 12); pub const WKSTA_KEEPCONN_PARMNUM = @as(u32, 13); pub const WKSTA_KEEPSEARCH_PARMNUM = @as(u32, 14); pub const WKSTA_MAXCMDS_PARMNUM = @as(u32, 15); pub const WKSTA_NUMWORKBUF_PARMNUM = @as(u32, 16); pub const WKSTA_MAXWRKCACHE_PARMNUM = @as(u32, 17); pub const WKSTA_SESSTIMEOUT_PARMNUM = @as(u32, 18); pub const WKSTA_SIZERROR_PARMNUM = @as(u32, 19); pub const WKSTA_NUMALERTS_PARMNUM = @as(u32, 20); pub const WKSTA_NUMSERVICES_PARMNUM = @as(u32, 21); pub const WKSTA_NUMCHARBUF_PARMNUM = @as(u32, 22); pub const WKSTA_SIZCHARBUF_PARMNUM = @as(u32, 23); pub const WKSTA_ERRLOGSZ_PARMNUM = @as(u32, 27); pub const WKSTA_PRINTBUFTIME_PARMNUM = @as(u32, 28); pub const WKSTA_SIZWORKBUF_PARMNUM = @as(u32, 29); pub const WKSTA_MAILSLOTS_PARMNUM = @as(u32, 30); pub const WKSTA_NUMDGRAMBUF_PARMNUM = @as(u32, 31); pub const WKSTA_WRKHEURISTICS_PARMNUM = @as(u32, 32); pub const WKSTA_MAXTHREADS_PARMNUM = @as(u32, 33); pub const WKSTA_LOCKQUOTA_PARMNUM = @as(u32, 41); pub const WKSTA_LOCKINCREMENT_PARMNUM = @as(u32, 42); pub const WKSTA_LOCKMAXIMUM_PARMNUM = @as(u32, 43); pub const WKSTA_PIPEINCREMENT_PARMNUM = @as(u32, 44); pub const WKSTA_PIPEMAXIMUM_PARMNUM = @as(u32, 45); pub const WKSTA_DORMANTFILELIMIT_PARMNUM = @as(u32, 46); pub const WKSTA_CACHEFILETIMEOUT_PARMNUM = @as(u32, 47); pub const WKSTA_USEOPPORTUNISTICLOCKING_PARMNUM = @as(u32, 48); pub const WKSTA_USEUNLOCKBEHIND_PARMNUM = @as(u32, 49); pub const WKSTA_USECLOSEBEHIND_PARMNUM = @as(u32, 50); pub const WKSTA_BUFFERNAMEDPIPES_PARMNUM = @as(u32, 51); pub const WKSTA_USELOCKANDREADANDUNLOCK_PARMNUM = @as(u32, 52); pub const WKSTA_UTILIZENTCACHING_PARMNUM = @as(u32, 53); pub const WKSTA_USERAWREAD_PARMNUM = @as(u32, 54); pub const WKSTA_USERAWWRITE_PARMNUM = @as(u32, 55); pub const WKSTA_USEWRITERAWWITHDATA_PARMNUM = @as(u32, 56); pub const WKSTA_USEENCRYPTION_PARMNUM = @as(u32, 57); pub const WKSTA_BUFFILESWITHDENYWRITE_PARMNUM = @as(u32, 58); pub const WKSTA_BUFFERREADONLYFILES_PARMNUM = @as(u32, 59); pub const WKSTA_FORCECORECREATEMODE_PARMNUM = @as(u32, 60); pub const WKSTA_USE512BYTESMAXTRANSFER_PARMNUM = @as(u32, 61); pub const WKSTA_READAHEADTHRUPUT_PARMNUM = @as(u32, 62); pub const WKSTA_OTH_DOMAINS_PARMNUM = @as(u32, 101); pub const TRANSPORT_QUALITYOFSERVICE_PARMNUM = @as(u32, 201); pub const TRANSPORT_NAME_PARMNUM = @as(u32, 202); pub const EVENT_SRV_SERVICE_FAILED = @as(i32, -1073739824); pub const EVENT_SRV_RESOURCE_SHORTAGE = @as(i32, -1073739823); pub const EVENT_SRV_CANT_CREATE_DEVICE = @as(i32, -1073739822); pub const EVENT_SRV_CANT_CREATE_PROCESS = @as(i32, -1073739821); pub const EVENT_SRV_CANT_CREATE_THREAD = @as(i32, -1073739820); pub const EVENT_SRV_UNEXPECTED_DISC = @as(i32, -1073739819); pub const EVENT_SRV_INVALID_REQUEST = @as(i32, -1073739818); pub const EVENT_SRV_CANT_OPEN_NPFS = @as(i32, -1073739817); pub const EVENT_SRV_CANT_GROW_TABLE = @as(i32, -2147481639); pub const EVENT_SRV_CANT_START_SCAVENGER = @as(i32, -1073739814); pub const EVENT_SRV_IRP_STACK_SIZE = @as(i32, -1073739813); pub const EVENT_SRV_NETWORK_ERROR = @as(i32, -2147481636); pub const EVENT_SRV_DISK_FULL = @as(i32, -2147481635); pub const EVENT_SRV_NO_VIRTUAL_MEMORY = @as(i32, -1073739808); pub const EVENT_SRV_NONPAGED_POOL_LIMIT = @as(i32, -1073739807); pub const EVENT_SRV_PAGED_POOL_LIMIT = @as(i32, -1073739806); pub const EVENT_SRV_NO_NONPAGED_POOL = @as(i32, -1073739805); pub const EVENT_SRV_NO_PAGED_POOL = @as(i32, -1073739804); pub const EVENT_SRV_NO_WORK_ITEM = @as(i32, -2147481627); pub const EVENT_SRV_NO_FREE_CONNECTIONS = @as(i32, -2147481626); pub const EVENT_SRV_NO_FREE_RAW_WORK_ITEM = @as(i32, -2147481625); pub const EVENT_SRV_NO_BLOCKING_IO = @as(i32, -2147481624); pub const EVENT_SRV_DOS_ATTACK_DETECTED = @as(i32, -2147481623); pub const EVENT_SRV_TOO_MANY_DOS = @as(i32, -2147481622); pub const EVENT_SRV_OUT_OF_WORK_ITEM_DOS = @as(i32, -2147481621); pub const EVENT_SRV_KEY_NOT_FOUND = @as(i32, -1073739323); pub const EVENT_SRV_KEY_NOT_CREATED = @as(i32, -1073739322); pub const EVENT_SRV_NO_TRANSPORTS_BOUND = @as(i32, -1073739321); pub const EVENT_SRV_CANT_BIND_TO_TRANSPORT = @as(i32, -2147481144); pub const EVENT_SRV_CANT_BIND_DUP_NAME = @as(i32, -1073739319); pub const EVENT_SRV_INVALID_REGISTRY_VALUE = @as(i32, -2147481142); pub const EVENT_SRV_INVALID_SD = @as(i32, -2147481141); pub const EVENT_SRV_CANT_LOAD_DRIVER = @as(i32, -2147481140); pub const EVENT_SRV_CANT_UNLOAD_DRIVER = @as(i32, -2147481139); pub const EVENT_SRV_CANT_MAP_ERROR = @as(i32, -2147481138); pub const EVENT_SRV_CANT_RECREATE_SHARE = @as(i32, -2147481137); pub const EVENT_SRV_CANT_CHANGE_DOMAIN_NAME = @as(i32, -2147481136); pub const EVENT_SRV_TXF_INIT_FAILED = @as(i32, -2147481135); pub const EVENT_RDR_RESOURCE_SHORTAGE = @as(i32, -2147480647); pub const EVENT_RDR_CANT_CREATE_DEVICE = @as(i32, -2147480646); pub const EVENT_RDR_CANT_CREATE_THREAD = @as(i32, -2147480645); pub const EVENT_RDR_CANT_SET_THREAD = @as(i32, -2147480644); pub const EVENT_RDR_INVALID_REPLY = @as(i32, -2147480643); pub const EVENT_RDR_INVALID_SMB = @as(i32, -2147480642); pub const EVENT_RDR_INVALID_LOCK_REPLY = @as(i32, -2147480641); pub const EVENT_RDR_FAILED_UNLOCK = @as(i32, -2147480639); pub const EVENT_RDR_CLOSE_BEHIND = @as(i32, -2147480637); pub const EVENT_RDR_UNEXPECTED_ERROR = @as(i32, -2147480636); pub const EVENT_RDR_TIMEOUT = @as(i32, -2147480635); pub const EVENT_RDR_INVALID_OPLOCK = @as(i32, -2147480634); pub const EVENT_RDR_CONNECTION_REFERENCE = @as(i32, -2147480633); pub const EVENT_RDR_SERVER_REFERENCE = @as(i32, -2147480632); pub const EVENT_RDR_SMB_REFERENCE = @as(i32, -2147480631); pub const EVENT_RDR_ENCRYPT = @as(i32, -2147480630); pub const EVENT_RDR_CONNECTION = @as(i32, -2147480629); pub const EVENT_RDR_MAXCMDS = @as(i32, -2147480627); pub const EVENT_RDR_OPLOCK_SMB = @as(i32, -2147480626); pub const EVENT_RDR_DISPOSITION = @as(i32, -2147480625); pub const EVENT_RDR_CONTEXTS = @as(i32, -2147480624); pub const EVENT_RDR_WRITE_BEHIND_FLUSH_FAILED = @as(i32, -2147480623); pub const EVENT_RDR_AT_THREAD_MAX = @as(i32, -2147480622); pub const EVENT_RDR_CANT_READ_REGISTRY = @as(i32, -2147480621); pub const EVENT_RDR_TIMEZONE_BIAS_TOO_LARGE = @as(i32, -2147480620); pub const EVENT_RDR_PRIMARY_TRANSPORT_CONNECT_FAILED = @as(i32, -2147480619); pub const EVENT_RDR_DELAYED_SET_ATTRIBUTES_FAILED = @as(i32, -2147480618); pub const EVENT_RDR_DELETEONCLOSE_FAILED = @as(i32, -2147480617); pub const EVENT_RDR_CANT_BIND_TRANSPORT = @as(i32, -2147480616); pub const EVENT_RDR_CANT_REGISTER_ADDRESS = @as(i32, -2147480615); pub const EVENT_RDR_CANT_GET_SECURITY_CONTEXT = @as(i32, -2147480614); pub const EVENT_RDR_CANT_BUILD_SMB_HEADER = @as(i32, -2147480613); pub const EVENT_RDR_SECURITY_SIGNATURE_MISMATCH = @as(i32, -2147480612); pub const EVENT_TCPIP6_STARTED = @as(i32, 1073744924); pub const EVENT_STREAMS_STRLOG = @as(i32, -1073737824); pub const EVENT_STREAMS_ALLOCB_FAILURE = @as(i32, -2147479647); pub const EVENT_STREAMS_ALLOCB_FAILURE_CNT = @as(i32, -2147479646); pub const EVENT_STREAMS_ESBALLOC_FAILURE = @as(i32, -2147479645); pub const EVENT_STREAMS_ESBALLOC_FAILURE_CNT = @as(i32, -2147479644); pub const EVENT_TCPIP_CREATE_DEVICE_FAILED = @as(i32, -1073737724); pub const EVENT_TCPIP_NO_RESOURCES_FOR_INIT = @as(i32, -1073737723); pub const EVENT_TCPIP_TOO_MANY_NETS = @as(i32, -1073737639); pub const EVENT_TCPIP_NO_MASK = @as(i32, -1073737638); pub const EVENT_TCPIP_INVALID_ADDRESS = @as(i32, -1073737637); pub const EVENT_TCPIP_INVALID_MASK = @as(i32, -1073737636); pub const EVENT_TCPIP_NO_ADAPTER_RESOURCES = @as(i32, -1073737635); pub const EVENT_TCPIP_DHCP_INIT_FAILED = @as(i32, -2147479458); pub const EVENT_TCPIP_ADAPTER_REG_FAILURE = @as(i32, -1073737633); pub const EVENT_TCPIP_INVALID_DEFAULT_GATEWAY = @as(i32, -2147479456); pub const EVENT_TCPIP_NO_ADDRESS_LIST = @as(i32, -1073737631); pub const EVENT_TCPIP_NO_MASK_LIST = @as(i32, -1073737630); pub const EVENT_TCPIP_NO_BINDINGS = @as(i32, -1073737629); pub const EVENT_TCPIP_IP_INIT_FAILED = @as(i32, -1073737628); pub const EVENT_TCPIP_TOO_MANY_GATEWAYS = @as(i32, -2147479451); pub const EVENT_TCPIP_ADDRESS_CONFLICT1 = @as(i32, -1073737626); pub const EVENT_TCPIP_ADDRESS_CONFLICT2 = @as(i32, -1073737625); pub const EVENT_TCPIP_NTE_CONTEXT_LIST_FAILURE = @as(i32, -1073737624); pub const EVENT_TCPIP_MEDIA_CONNECT = @as(i32, 1073746025); pub const EVENT_TCPIP_MEDIA_DISCONNECT = @as(i32, 1073746026); pub const EVENT_TCPIP_IPV4_UNINSTALLED = @as(i32, 1073746027); pub const EVENT_TCPIP_AUTOCONFIGURED_ADDRESS_LIMIT_REACHED = @as(i32, -2147479444); pub const EVENT_TCPIP_AUTOCONFIGURED_ROUTE_LIMIT_REACHED = @as(i32, -2147479443); pub const EVENT_TCPIP_OUT_OF_ORDER_FRAGMENTS_EXCEEDED = @as(i32, -2147479442); pub const EVENT_TCPIP_INTERFACE_BIND_FAILURE = @as(i32, -1073737617); pub const EVENT_TCPIP_TCP_INIT_FAILED = @as(i32, -1073737599); pub const EVENT_TCPIP_TCP_CONNECT_LIMIT_REACHED = @as(i32, -2147479422); pub const EVENT_TCPIP_TCP_TIME_WAIT_COLLISION = @as(i32, -2147479421); pub const EVENT_TCPIP_TCP_WSD_WS_RESTRICTED = @as(i32, -2147479420); pub const EVENT_TCPIP_TCP_MPP_ATTACKS_DETECTED = @as(i32, -2147479419); pub const EVENT_TCPIP_TCP_CONNECTIONS_PERF_IMPACTED = @as(i32, -2147479418); pub const EVENT_TCPIP_TCP_GLOBAL_EPHEMERAL_PORT_SPACE_EXHAUSTED = @as(i32, -2147479417); pub const EVENT_TCPIP_UDP_LIMIT_REACHED = @as(i32, -2147479383); pub const EVENT_TCPIP_UDP_GLOBAL_EPHEMERAL_PORT_SPACE_EXHAUSTED = @as(i32, -2147479382); pub const EVENT_TCPIP_PCF_MULTICAST_OID_ISSUE = @as(i32, -2147479358); pub const EVENT_TCPIP_PCF_MISSING_CAPABILITY = @as(i32, -2147479357); pub const EVENT_TCPIP_PCF_SET_FILTER_FAILURE = @as(i32, -2147479356); pub const EVENT_TCPIP_PCF_NO_ARP_FILTER = @as(i32, -2147479355); pub const EVENT_TCPIP_PCF_CLEAR_FILTER_FAILURE = @as(i32, -1073737530); pub const EVENT_NBT_CREATE_DRIVER = @as(i32, -1073737524); pub const EVENT_NBT_OPEN_REG_PARAMS = @as(i32, -1073737523); pub const EVENT_NBT_NO_BACKUP_WINS = @as(i32, -2147479346); pub const EVENT_NBT_NO_WINS = @as(i32, -2147479345); pub const EVENT_NBT_BAD_BACKUP_WINS_ADDR = @as(i32, -2147479344); pub const EVENT_NBT_BAD_PRIMARY_WINS_ADDR = @as(i32, -2147479343); pub const EVENT_NBT_NAME_SERVER_ADDRS = @as(i32, -1073737518); pub const EVENT_NBT_CREATE_ADDRESS = @as(i32, -1073737517); pub const EVENT_NBT_CREATE_CONNECTION = @as(i32, -1073737516); pub const EVENT_NBT_NON_OS_INIT = @as(i32, -1073737515); pub const EVENT_NBT_TIMERS = @as(i32, -1073737514); pub const EVENT_NBT_CREATE_DEVICE = @as(i32, -1073737513); pub const EVENT_NBT_NO_DEVICES = @as(i32, -2147479336); pub const EVENT_NBT_OPEN_REG_LINKAGE = @as(i32, -1073737511); pub const EVENT_NBT_READ_BIND = @as(i32, -1073737510); pub const EVENT_NBT_READ_EXPORT = @as(i32, -1073737509); pub const EVENT_NBT_OPEN_REG_NAMESERVER = @as(i32, -2147479332); pub const EVENT_SCOPE_LABEL_TOO_LONG = @as(i32, -2147479331); pub const EVENT_SCOPE_TOO_LONG = @as(i32, -2147479330); pub const EVENT_NBT_DUPLICATE_NAME = @as(i32, -1073737505); pub const EVENT_NBT_NAME_RELEASE = @as(i32, -1073737504); pub const EVENT_NBT_DUPLICATE_NAME_ERROR = @as(i32, -1073737503); pub const EVENT_NBT_NO_RESOURCES = @as(i32, -1073737502); pub const EVENT_NDIS_RESOURCE_CONFLICT = @as(i32, -1073736824); pub const EVENT_NDIS_OUT_OF_RESOURCE = @as(i32, -1073736823); pub const EVENT_NDIS_HARDWARE_FAILURE = @as(i32, -1073736822); pub const EVENT_NDIS_ADAPTER_NOT_FOUND = @as(i32, -1073736821); pub const EVENT_NDIS_INTERRUPT_CONNECT = @as(i32, -1073736820); pub const EVENT_NDIS_DRIVER_FAILURE = @as(i32, -1073736819); pub const EVENT_NDIS_BAD_VERSION = @as(i32, -1073736818); pub const EVENT_NDIS_TIMEOUT = @as(i32, -2147478641); pub const EVENT_NDIS_NETWORK_ADDRESS = @as(i32, -1073736816); pub const EVENT_NDIS_UNSUPPORTED_CONFIGURATION = @as(i32, -1073736815); pub const EVENT_NDIS_INVALID_VALUE_FROM_ADAPTER = @as(i32, -1073736814); pub const EVENT_NDIS_MISSING_CONFIGURATION_PARAMETER = @as(i32, -1073736813); pub const EVENT_NDIS_BAD_IO_BASE_ADDRESS = @as(i32, -1073736812); pub const EVENT_NDIS_RECEIVE_SPACE_SMALL = @as(i32, 1073746837); pub const EVENT_NDIS_ADAPTER_DISABLED = @as(i32, -2147478634); pub const EVENT_NDIS_IO_PORT_CONFLICT = @as(i32, -2147478633); pub const EVENT_NDIS_PORT_OR_DMA_CONFLICT = @as(i32, -2147478632); pub const EVENT_NDIS_MEMORY_CONFLICT = @as(i32, -2147478631); pub const EVENT_NDIS_INTERRUPT_CONFLICT = @as(i32, -2147478630); pub const EVENT_NDIS_DMA_CONFLICT = @as(i32, -2147478629); pub const EVENT_NDIS_INVALID_DOWNLOAD_FILE_ERROR = @as(i32, -1073736804); pub const EVENT_NDIS_MAXRECEIVES_ERROR = @as(i32, -2147478627); pub const EVENT_NDIS_MAXTRANSMITS_ERROR = @as(i32, -2147478626); pub const EVENT_NDIS_MAXFRAMESIZE_ERROR = @as(i32, -2147478625); pub const EVENT_NDIS_MAXINTERNALBUFS_ERROR = @as(i32, -2147478624); pub const EVENT_NDIS_MAXMULTICAST_ERROR = @as(i32, -2147478623); pub const EVENT_NDIS_PRODUCTID_ERROR = @as(i32, -2147478622); pub const EVENT_NDIS_LOBE_FAILUE_ERROR = @as(i32, -2147478621); pub const EVENT_NDIS_SIGNAL_LOSS_ERROR = @as(i32, -2147478620); pub const EVENT_NDIS_REMOVE_RECEIVED_ERROR = @as(i32, -2147478619); pub const EVENT_NDIS_TOKEN_RING_CORRECTION = @as(i32, 1073746854); pub const EVENT_NDIS_ADAPTER_CHECK_ERROR = @as(i32, -1073736793); pub const EVENT_NDIS_RESET_FAILURE_ERROR = @as(i32, -2147478616); pub const EVENT_NDIS_CABLE_DISCONNECTED_ERROR = @as(i32, -2147478615); pub const EVENT_NDIS_RESET_FAILURE_CORRECTION = @as(i32, -2147478614); pub const EVENT_EventlogStarted = @as(i32, -2147477643); pub const EVENT_EventlogStopped = @as(i32, -2147477642); pub const EVENT_EventlogAbnormalShutdown = @as(i32, -2147477640); pub const EVENT_EventLogProductInfo = @as(i32, -2147477639); pub const EVENT_ComputerNameChange = @as(i32, -2147477637); pub const EVENT_DNSDomainNameChange = @as(i32, -2147477636); pub const EVENT_EventlogUptime = @as(i32, -2147477635); pub const EVENT_UP_DRIVER_ON_MP = @as(i32, -1073735724); pub const EVENT_SERVICE_START_FAILED = @as(i32, -1073734824); pub const EVENT_SERVICE_START_FAILED_II = @as(i32, -1073734823); pub const EVENT_SERVICE_START_FAILED_GROUP = @as(i32, -1073734822); pub const EVENT_SERVICE_START_FAILED_NONE = @as(i32, -1073734821); pub const EVENT_CALL_TO_FUNCTION_FAILED = @as(i32, -1073734819); pub const EVENT_CALL_TO_FUNCTION_FAILED_II = @as(i32, -1073734818); pub const EVENT_REVERTED_TO_LASTKNOWNGOOD = @as(i32, -1073734817); pub const EVENT_BAD_ACCOUNT_NAME = @as(i32, -1073734816); pub const EVENT_CONNECTION_TIMEOUT = @as(i32, -1073734815); pub const EVENT_READFILE_TIMEOUT = @as(i32, -1073734814); pub const EVENT_TRANSACT_TIMEOUT = @as(i32, -1073734813); pub const EVENT_TRANSACT_INVALID = @as(i32, -1073734812); pub const EVENT_FIRST_LOGON_FAILED = @as(i32, -1073734811); pub const EVENT_SECOND_LOGON_FAILED = @as(i32, -1073734810); pub const EVENT_INVALID_DRIVER_DEPENDENCY = @as(i32, -1073734809); pub const EVENT_BAD_SERVICE_STATE = @as(i32, -1073734808); pub const EVENT_CIRCULAR_DEPENDENCY_DEMAND = @as(i32, -1073734807); pub const EVENT_CIRCULAR_DEPENDENCY_AUTO = @as(i32, -1073734806); pub const EVENT_DEPEND_ON_LATER_SERVICE = @as(i32, -1073734805); pub const EVENT_DEPEND_ON_LATER_GROUP = @as(i32, -1073734804); pub const EVENT_SEVERE_SERVICE_FAILED = @as(i32, -1073734803); pub const EVENT_SERVICE_START_HUNG = @as(i32, -1073734802); pub const EVENT_SERVICE_EXIT_FAILED = @as(i32, -1073734801); pub const EVENT_SERVICE_EXIT_FAILED_SPECIFIC = @as(i32, -1073734800); pub const EVENT_SERVICE_START_AT_BOOT_FAILED = @as(i32, -1073734799); pub const EVENT_BOOT_SYSTEM_DRIVERS_FAILED = @as(i32, -1073734798); pub const EVENT_RUNNING_LASTKNOWNGOOD = @as(i32, -1073734797); pub const EVENT_TAKE_OWNERSHIP = @as(i32, -1073734796); pub const TITLE_SC_MESSAGE_BOX = @as(i32, -1073734795); pub const EVENT_SERVICE_NOT_INTERACTIVE = @as(i32, -1073734794); pub const EVENT_SERVICE_CRASH = @as(i32, -1073734793); pub const EVENT_SERVICE_RECOVERY_FAILED = @as(i32, -1073734792); pub const EVENT_SERVICE_SCESRV_FAILED = @as(i32, -1073734791); pub const EVENT_SERVICE_CRASH_NO_ACTION = @as(i32, -1073734790); pub const EVENT_SERVICE_CONTROL_SUCCESS = @as(i32, 1073748859); pub const EVENT_SERVICE_STATUS_SUCCESS = @as(i32, 1073748860); pub const EVENT_SERVICE_CONFIG_BACKOUT_FAILED = @as(i32, -1073734787); pub const EVENT_FIRST_LOGON_FAILED_II = @as(i32, -1073734786); pub const EVENT_SERVICE_DIFFERENT_PID_CONNECTED = @as(i32, -2147476609); pub const EVENT_SERVICE_START_TYPE_CHANGED = @as(i32, 1073748864); pub const EVENT_SERVICE_LOGON_TYPE_NOT_GRANTED = @as(i32, -1073734783); pub const EVENT_SERVICE_STOP_SUCCESS_WITH_REASON = @as(i32, 1073748866); pub const EVENT_SERVICE_SHUTDOWN_FAILED = @as(i32, -1073734781); pub const EVENT_COMMAND_NOT_INTERACTIVE = @as(i32, -1073733924); pub const EVENT_COMMAND_START_FAILED = @as(i32, -1073733923); pub const EVENT_BOWSER_OTHER_MASTER_ON_NET = @as(i32, -1073733821); pub const EVENT_BOWSER_PROMOTED_WHILE_ALREADY_MASTER = @as(i32, -2147475644); pub const EVENT_BOWSER_NON_MASTER_MASTER_ANNOUNCE = @as(i32, -2147475643); pub const EVENT_BOWSER_ILLEGAL_DATAGRAM = @as(i32, -2147475642); pub const EVENT_BROWSER_STATUS_BITS_UPDATE_FAILED = @as(i32, -1073733817); pub const EVENT_BROWSER_ROLE_CHANGE_FAILED = @as(i32, -1073733816); pub const EVENT_BROWSER_MASTER_PROMOTION_FAILED = @as(i32, -1073733815); pub const EVENT_BOWSER_NAME_CONVERSION_FAILED = @as(i32, -1073733814); pub const EVENT_BROWSER_OTHERDOMAIN_ADD_FAILED = @as(i32, -1073733813); pub const EVENT_BOWSER_ELECTION_RECEIVED = @as(i32, 8012); pub const EVENT_BOWSER_ELECTION_SENT_GETBLIST_FAILED = @as(i32, 1073749837); pub const EVENT_BOWSER_ELECTION_SENT_FIND_MASTER_FAILED = @as(i32, 1073749838); pub const EVENT_BROWSER_ELECTION_SENT_LANMAN_NT_STARTED = @as(i32, 1073749839); pub const EVENT_BOWSER_ILLEGAL_DATAGRAM_THRESHOLD = @as(i32, -1073733808); pub const EVENT_BROWSER_DEPENDANT_SERVICE_FAILED = @as(i32, -1073733807); pub const EVENT_BROWSER_MASTER_PROMOTION_FAILED_STOPPING = @as(i32, -1073733805); pub const EVENT_BROWSER_MASTER_PROMOTION_FAILED_NO_MASTER = @as(i32, -1073733804); pub const EVENT_BROWSER_SERVER_LIST_FAILED = @as(i32, -2147475627); pub const EVENT_BROWSER_DOMAIN_LIST_FAILED = @as(i32, -2147475626); pub const EVENT_BROWSER_ILLEGAL_CONFIG = @as(i32, -2147475625); pub const EVENT_BOWSER_OLD_BACKUP_FOUND = @as(i32, 1073749848); pub const EVENT_BROWSER_SERVER_LIST_RETRIEVED = @as(i32, 8025); pub const EVENT_BROWSER_DOMAIN_LIST_RETRIEVED = @as(i32, 8026); pub const EVENT_BOWSER_PDC_LOST_ELECTION = @as(i32, 1073749851); pub const EVENT_BOWSER_NON_PDC_WON_ELECTION = @as(i32, 1073749852); pub const EVENT_BOWSER_CANT_READ_REGISTRY = @as(i32, 1073749853); pub const EVENT_BOWSER_MAILSLOT_DATAGRAM_THRESHOLD_EXCEEDED = @as(i32, 1073749854); pub const EVENT_BOWSER_GETBROWSERLIST_THRESHOLD_EXCEEDED = @as(i32, 1073749855); pub const EVENT_BROWSER_BACKUP_STOPPED = @as(i32, -1073733792); pub const EVENT_BROWSER_ELECTION_SENT_LANMAN_NT_STOPPED = @as(i32, 1073749857); pub const EVENT_BROWSER_GETBLIST_RECEIVED_NOT_MASTER = @as(i32, -1073733790); pub const EVENT_BROWSER_ELECTION_SENT_ROLE_CHANGED = @as(i32, 1073749859); pub const EVENT_BROWSER_NOT_STARTED_IPX_CONFIG_MISMATCH = @as(i32, -1073733788); pub const NWSAP_EVENT_KEY_NOT_FOUND = @as(i32, -1073733324); pub const NWSAP_EVENT_WSASTARTUP_FAILED = @as(i32, -1073733323); pub const NWSAP_EVENT_SOCKET_FAILED = @as(i32, -1073733322); pub const NWSAP_EVENT_SETOPTBCAST_FAILED = @as(i32, -1073733321); pub const NWSAP_EVENT_BIND_FAILED = @as(i32, -1073733320); pub const NWSAP_EVENT_GETSOCKNAME_FAILED = @as(i32, -1073733319); pub const NWSAP_EVENT_OPTEXTENDEDADDR_FAILED = @as(i32, -1073733318); pub const NWSAP_EVENT_OPTBCASTINADDR_FAILED = @as(i32, -1073733317); pub const NWSAP_EVENT_CARDMALLOC_FAILED = @as(i32, -1073733316); pub const NWSAP_EVENT_NOCARDS = @as(i32, -1073733315); pub const NWSAP_EVENT_THREADEVENT_FAIL = @as(i32, -1073733314); pub const NWSAP_EVENT_RECVSEM_FAIL = @as(i32, -1073733313); pub const NWSAP_EVENT_SENDEVENT_FAIL = @as(i32, -1073733312); pub const NWSAP_EVENT_STARTRECEIVE_ERROR = @as(i32, -1073733311); pub const NWSAP_EVENT_STARTWORKER_ERROR = @as(i32, -1073733310); pub const NWSAP_EVENT_TABLE_MALLOC_FAILED = @as(i32, -1073733309); pub const NWSAP_EVENT_HASHTABLE_MALLOC_FAILED = @as(i32, -1073733308); pub const NWSAP_EVENT_STARTLPCWORKER_ERROR = @as(i32, -1073733307); pub const NWSAP_EVENT_CREATELPCPORT_ERROR = @as(i32, -1073733306); pub const NWSAP_EVENT_CREATELPCEVENT_ERROR = @as(i32, -1073733305); pub const NWSAP_EVENT_LPCLISTENMEMORY_ERROR = @as(i32, -1073733304); pub const NWSAP_EVENT_LPCHANDLEMEMORY_ERROR = @as(i32, -1073733303); pub const NWSAP_EVENT_BADWANFILTER_VALUE = @as(i32, -1073733302); pub const NWSAP_EVENT_CARDLISTEVENT_FAIL = @as(i32, -1073733301); pub const NWSAP_EVENT_SDMDEVENT_FAIL = @as(i32, -1073733300); pub const NWSAP_EVENT_INVALID_FILTERNAME = @as(i32, -2147475123); pub const NWSAP_EVENT_WANSEM_FAIL = @as(i32, -1073733298); pub const NWSAP_EVENT_WANSOCKET_FAILED = @as(i32, -1073733297); pub const NWSAP_EVENT_WANBIND_FAILED = @as(i32, -1073733296); pub const NWSAP_EVENT_STARTWANWORKER_ERROR = @as(i32, -1073733295); pub const NWSAP_EVENT_STARTWANCHECK_ERROR = @as(i32, -1073733294); pub const NWSAP_EVENT_OPTMAXADAPTERNUM_ERROR = @as(i32, -1073733293); pub const NWSAP_EVENT_WANHANDLEMEMORY_ERROR = @as(i32, -1073733292); pub const NWSAP_EVENT_WANEVENT_ERROR = @as(i32, -1073733291); pub const EVENT_TRANSPORT_RESOURCE_POOL = @as(i32, -2147474647); pub const EVENT_TRANSPORT_RESOURCE_LIMIT = @as(i32, -2147474646); pub const EVENT_TRANSPORT_RESOURCE_SPECIFIC = @as(i32, -2147474645); pub const EVENT_TRANSPORT_REGISTER_FAILED = @as(i32, -1073732820); pub const EVENT_TRANSPORT_BINDING_FAILED = @as(i32, -1073732819); pub const EVENT_TRANSPORT_ADAPTER_NOT_FOUND = @as(i32, -1073732818); pub const EVENT_TRANSPORT_SET_OID_FAILED = @as(i32, -1073732817); pub const EVENT_TRANSPORT_QUERY_OID_FAILED = @as(i32, -1073732816); pub const EVENT_TRANSPORT_TRANSFER_DATA = @as(i32, 1073750833); pub const EVENT_TRANSPORT_TOO_MANY_LINKS = @as(i32, 1073750834); pub const EVENT_TRANSPORT_BAD_PROTOCOL = @as(i32, 1073750835); pub const EVENT_IPX_NEW_DEFAULT_TYPE = @as(i32, 1073751325); pub const EVENT_IPX_SAP_ANNOUNCE = @as(i32, -2147474146); pub const EVENT_IPX_ILLEGAL_CONFIG = @as(i32, -2147474145); pub const EVENT_IPX_INTERNAL_NET_INVALID = @as(i32, -1073732320); pub const EVENT_IPX_NO_FRAME_TYPES = @as(i32, -1073732319); pub const EVENT_IPX_CREATE_DEVICE = @as(i32, -1073732318); pub const EVENT_IPX_NO_ADAPTERS = @as(i32, -1073732317); pub const EVENT_RPCSS_CREATEPROCESS_FAILURE = @as(i32, -1073731824); pub const EVENT_RPCSS_RUNAS_CREATEPROCESS_FAILURE = @as(i32, -1073731823); pub const EVENT_RPCSS_LAUNCH_ACCESS_DENIED = @as(i32, -1073731822); pub const EVENT_RPCSS_DEFAULT_LAUNCH_ACCESS_DENIED = @as(i32, -1073731821); pub const EVENT_RPCSS_RUNAS_CANT_LOGIN = @as(i32, -1073731820); pub const EVENT_RPCSS_START_SERVICE_FAILURE = @as(i32, -1073731819); pub const EVENT_RPCSS_REMOTE_SIDE_ERROR = @as(i32, -1073731818); pub const EVENT_RPCSS_ACTIVATION_ERROR = @as(i32, -1073731817); pub const EVENT_RPCSS_REMOTE_SIDE_ERROR_WITH_FILE = @as(i32, -1073731816); pub const EVENT_RPCSS_REMOTE_SIDE_UNAVAILABLE = @as(i32, -1073731815); pub const EVENT_RPCSS_SERVER_START_TIMEOUT = @as(i32, -1073731814); pub const EVENT_RPCSS_SERVER_NOT_RESPONDING = @as(i32, -1073731813); pub const EVENT_DCOM_ASSERTION_FAILURE = @as(i32, -1073731812); pub const EVENT_DCOM_INVALID_ENDPOINT_DATA = @as(i32, -1073731811); pub const EVENT_DCOM_COMPLUS_DISABLED = @as(i32, -1073731810); pub const EVENT_RPCSS_STOP_SERVICE_FAILURE = @as(i32, -1073731795); pub const EVENT_RPCSS_CREATEDEBUGGERPROCESS_FAILURE = @as(i32, -1073731794); pub const EVENT_DNS_CACHE_START_FAILURE_NO_DLL = @as(i32, -1073730824); pub const EVENT_DNS_CACHE_START_FAILURE_NO_ENTRY = @as(i32, -1073730823); pub const EVENT_DNS_CACHE_START_FAILURE_NO_CONTROL = @as(i32, -1073730822); pub const EVENT_DNS_CACHE_START_FAILURE_NO_DONE_EVENT = @as(i32, -1073730821); pub const EVENT_DNS_CACHE_START_FAILURE_NO_RPC = @as(i32, -1073730820); pub const EVENT_DNS_CACHE_START_FAILURE_NO_SHUTDOWN_NOTIFY = @as(i32, -1073730819); pub const EVENT_DNS_CACHE_START_FAILURE_NO_UPDATE = @as(i32, -1073730818); pub const EVENT_DNS_CACHE_START_FAILURE_LOW_MEMORY = @as(i32, -1073730817); pub const EVENT_DNS_CACHE_NETWORK_PERF_WARNING = @as(i32, -2147472598); pub const EVENT_DNS_CACHE_UNABLE_TO_REACH_SERVER_WARNING = @as(i32, -2147472597); pub const EVENT_DNSAPI_REGISTRATION_FAILED_TIMEOUT = @as(i32, -2147472498); pub const EVENT_DNSAPI_REGISTRATION_FAILED_SERVERFAIL = @as(i32, -2147472497); pub const EVENT_DNSAPI_REGISTRATION_FAILED_NOTSUPP = @as(i32, -2147472496); pub const EVENT_DNSAPI_REGISTRATION_FAILED_REFUSED = @as(i32, -2147472495); pub const EVENT_DNSAPI_REGISTRATION_FAILED_SECURITY = @as(i32, -2147472494); pub const EVENT_DNSAPI_REGISTRATION_FAILED_OTHER = @as(i32, -2147472493); pub const EVENT_DNSAPI_PTR_REGISTRATION_FAILED_TIMEOUT = @as(i32, -2147472492); pub const EVENT_DNSAPI_PTR_REGISTRATION_FAILED_SERVERFAIL = @as(i32, -2147472491); pub const EVENT_DNSAPI_PTR_REGISTRATION_FAILED_NOTSUPP = @as(i32, -2147472490); pub const EVENT_DNSAPI_PTR_REGISTRATION_FAILED_REFUSED = @as(i32, -2147472489); pub const EVENT_DNSAPI_PTR_REGISTRATION_FAILED_SECURITY = @as(i32, -2147472488); pub const EVENT_DNSAPI_PTR_REGISTRATION_FAILED_OTHER = @as(i32, -2147472487); pub const EVENT_DNSAPI_REGISTRATION_FAILED_TIMEOUT_PRIMARY_DN = @as(i32, -2147472486); pub const EVENT_DNSAPI_REGISTRATION_FAILED_SERVERFAIL_PRIMARY_DN = @as(i32, -2147472485); pub const EVENT_DNSAPI_REGISTRATION_FAILED_NOTSUPP_PRIMARY_DN = @as(i32, -2147472484); pub const EVENT_DNSAPI_REGISTRATION_FAILED_REFUSED_PRIMARY_DN = @as(i32, -2147472483); pub const EVENT_DNSAPI_REGISTRATION_FAILED_SECURITY_PRIMARY_DN = @as(i32, -2147472482); pub const EVENT_DNSAPI_REGISTRATION_FAILED_OTHER_PRIMARY_DN = @as(i32, -2147472481); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_TIMEOUT = @as(i32, -2147472468); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_SERVERFAIL = @as(i32, -2147472467); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_NOTSUPP = @as(i32, -2147472466); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_REFUSED = @as(i32, -2147472465); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_SECURITY = @as(i32, -2147472464); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_OTHER = @as(i32, -2147472463); pub const EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_TIMEOUT = @as(i32, -2147472462); pub const EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_SERVERFAIL = @as(i32, -2147472461); pub const EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_NOTSUPP = @as(i32, -2147472460); pub const EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_REFUSED = @as(i32, -2147472459); pub const EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_SECURITY = @as(i32, -2147472458); pub const EVENT_DNSAPI_PTR_DEREGISTRATION_FAILED_OTHER = @as(i32, -2147472457); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_TIMEOUT_PRIMARY_DN = @as(i32, -2147472456); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_SERVERFAIL_PRIMARY_DN = @as(i32, -2147472455); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_NOTSUPP_PRIMARY_DN = @as(i32, -2147472454); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_REFUSED_PRIMARY_DN = @as(i32, -2147472453); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_SECURITY_PRIMARY_DN = @as(i32, -2147472452); pub const EVENT_DNSAPI_DEREGISTRATION_FAILED_OTHER_PRIMARY_DN = @as(i32, -2147472451); pub const EVENT_DNSAPI_REGISTERED_ADAPTER = @as(i32, 1073753024); pub const EVENT_DNSAPI_REGISTERED_PTR = @as(i32, 1073753025); pub const EVENT_DNSAPI_REGISTERED_ADAPTER_PRIMARY_DN = @as(i32, 1073753026); pub const EVENT_TRK_INTERNAL_ERROR = @as(i32, -1073729324); pub const EVENT_TRK_SERVICE_START_SUCCESS = @as(i32, 1073754325); pub const EVENT_TRK_SERVICE_START_FAILURE = @as(i32, -1073729322); pub const EVENT_TRK_SERVICE_CORRUPT_LOG = @as(i32, -1073729321); pub const EVENT_TRK_SERVICE_VOL_QUOTA_EXCEEDED = @as(i32, -2147471144); pub const EVENT_TRK_SERVICE_VOLUME_CREATE = @as(i32, 1073754329); pub const EVENT_TRK_SERVICE_VOLUME_CLAIM = @as(i32, 1073754330); pub const EVENT_TRK_SERVICE_DUPLICATE_VOLIDS = @as(i32, 1073754331); pub const EVENT_TRK_SERVICE_MOVE_QUOTA_EXCEEDED = @as(i32, -2147471140); pub const EVENT_FRS_ERROR = @as(i32, -1073728324); pub const EVENT_FRS_STARTING = @as(i32, 1073755325); pub const EVENT_FRS_STOPPING = @as(i32, 1073755326); pub const EVENT_FRS_STOPPED = @as(i32, 1073755327); pub const EVENT_FRS_STOPPED_FORCE = @as(i32, -1073728320); pub const EVENT_FRS_STOPPED_ASSERT = @as(i32, -1073728319); pub const EVENT_FRS_ASSERT = @as(i32, -1073728318); pub const EVENT_FRS_VOLUME_NOT_SUPPORTED = @as(i32, -1073728317); pub const EVENT_FRS_LONG_JOIN = @as(i32, -2147470140); pub const EVENT_FRS_LONG_JOIN_DONE = @as(i32, -2147470139); pub const EVENT_FRS_CANNOT_COMMUNICATE = @as(i32, -1073728314); pub const EVENT_FRS_DATABASE_SPACE = @as(i32, -1073728313); pub const EVENT_FRS_DISK_WRITE_CACHE_ENABLED = @as(i32, -2147470136); pub const EVENT_FRS_JET_1414 = @as(i32, -1073728311); pub const EVENT_FRS_SYSVOL_NOT_READY = @as(i32, -2147470134); pub const EVENT_FRS_SYSVOL_NOT_READY_PRIMARY = @as(i32, -2147470133); pub const EVENT_FRS_SYSVOL_READY = @as(i32, 1073755340); pub const EVENT_FRS_ACCESS_CHECKS_DISABLED = @as(i32, -2147470131); pub const EVENT_FRS_ACCESS_CHECKS_FAILED_USER = @as(i32, -2147470130); pub const EVENT_FRS_ACCESS_CHECKS_FAILED_UNKNOWN = @as(i32, -1073728305); pub const EVENT_FRS_MOVED_PREEXISTING = @as(i32, -2147470128); pub const EVENT_FRS_CANNOT_START_BACKUP_RESTORE_IN_PROGRESS = @as(i32, -1073728303); pub const EVENT_FRS_STAGING_AREA_FULL = @as(i32, -2147470126); pub const EVENT_FRS_HUGE_FILE = @as(i32, -2147470125); pub const EVENT_FRS_CANNOT_CREATE_UUID = @as(i32, -1073728300); pub const EVENT_FRS_NO_DNS_ATTRIBUTE = @as(i32, -2147470123); pub const EVENT_FRS_NO_SID = @as(i32, -1073728298); pub const NTFRSPRF_OPEN_RPC_BINDING_ERROR_SET = @as(i32, -1073728297); pub const NTFRSPRF_OPEN_RPC_BINDING_ERROR_CONN = @as(i32, -1073728296); pub const NTFRSPRF_OPEN_RPC_CALL_ERROR_SET = @as(i32, -1073728295); pub const NTFRSPRF_OPEN_RPC_CALL_ERROR_CONN = @as(i32, -1073728294); pub const NTFRSPRF_COLLECT_RPC_BINDING_ERROR_SET = @as(i32, -1073728293); pub const NTFRSPRF_COLLECT_RPC_BINDING_ERROR_CONN = @as(i32, -1073728292); pub const NTFRSPRF_COLLECT_RPC_CALL_ERROR_SET = @as(i32, -1073728291); pub const NTFRSPRF_COLLECT_RPC_CALL_ERROR_CONN = @as(i32, -1073728290); pub const NTFRSPRF_VIRTUALALLOC_ERROR_SET = @as(i32, -1073728289); pub const NTFRSPRF_VIRTUALALLOC_ERROR_CONN = @as(i32, -1073728288); pub const NTFRSPRF_REGISTRY_ERROR_SET = @as(i32, -1073728287); pub const NTFRSPRF_REGISTRY_ERROR_CONN = @as(i32, -1073728286); pub const EVENT_FRS_ROOT_NOT_VALID = @as(i32, -1073728285); pub const EVENT_FRS_STAGE_NOT_VALID = @as(i32, -1073728284); pub const EVENT_FRS_OVERLAPS_LOGGING = @as(i32, -1073728283); pub const EVENT_FRS_OVERLAPS_WORKING = @as(i32, -1073728282); pub const EVENT_FRS_OVERLAPS_STAGE = @as(i32, -1073728281); pub const EVENT_FRS_OVERLAPS_ROOT = @as(i32, -1073728280); pub const EVENT_FRS_OVERLAPS_OTHER_STAGE = @as(i32, -1073728279); pub const EVENT_FRS_PREPARE_ROOT_FAILED = @as(i32, -1073728278); pub const EVENT_FRS_BAD_REG_DATA = @as(i32, -2147470101); pub const EVENT_FRS_JOIN_FAIL_TIME_SKEW = @as(i32, -1073728276); pub const EVENT_FRS_RMTCO_TIME_SKEW = @as(i32, -1073728275); pub const EVENT_FRS_CANT_OPEN_STAGE = @as(i32, -1073728274); pub const EVENT_FRS_CANT_OPEN_PREINSTALL = @as(i32, -1073728273); pub const EVENT_FRS_REPLICA_SET_CREATE_FAIL = @as(i32, -1073728272); pub const EVENT_FRS_REPLICA_SET_CREATE_OK = @as(i32, 1073755377); pub const EVENT_FRS_REPLICA_SET_CXTIONS = @as(i32, 1073755378); pub const EVENT_FRS_IN_ERROR_STATE = @as(i32, -1073728269); pub const EVENT_FRS_REPLICA_NO_ROOT_CHANGE = @as(i32, -1073728268); pub const EVENT_FRS_DUPLICATE_IN_CXTION_SYSVOL = @as(i32, -1073728267); pub const EVENT_FRS_DUPLICATE_IN_CXTION = @as(i32, -1073728266); pub const EVENT_FRS_ROOT_HAS_MOVED = @as(i32, -1073728265); pub const EVENT_FRS_ERROR_REPLICA_SET_DELETED = @as(i32, -2147470088); pub const EVENT_FRS_REPLICA_IN_JRNL_WRAP_ERROR = @as(i32, -1073728263); pub const EVENT_FRS_DS_POLL_ERROR_SUMMARY = @as(i32, -2147470086); pub const EVENT_PS_GPC_REGISTER_FAILED = @as(i32, -1073727824); pub const EVENT_PS_NO_RESOURCES_FOR_INIT = @as(i32, -1073727823); pub const EVENT_PS_REGISTER_PROTOCOL_FAILED = @as(i32, -1073727822); pub const EVENT_PS_REGISTER_MINIPORT_FAILED = @as(i32, -1073727821); pub const EVENT_PS_BAD_BESTEFFORT_LIMIT = @as(i32, -2147469548); pub const EVENT_PS_QUERY_OID_GEN_MAXIMUM_FRAME_SIZE = @as(i32, -1073727723); pub const EVENT_PS_QUERY_OID_GEN_MAXIMUM_TOTAL_SIZE = @as(i32, -1073727722); pub const EVENT_PS_QUERY_OID_GEN_LINK_SPEED = @as(i32, -1073727721); pub const EVENT_PS_BINDING_FAILED = @as(i32, -1073727720); pub const EVENT_PS_MISSING_ADAPTER_REGISTRY_DATA = @as(i32, -1073727719); pub const EVENT_PS_REGISTER_ADDRESS_FAMILY_FAILED = @as(i32, -1073727718); pub const EVENT_PS_INIT_DEVICE_FAILED = @as(i32, -1073727717); pub const EVENT_PS_WMI_INSTANCE_NAME_FAILED = @as(i32, -1073727716); pub const EVENT_PS_WAN_LIMITED_BESTEFFORT = @as(i32, -2147469539); pub const EVENT_PS_RESOURCE_POOL = @as(i32, -1073727714); pub const EVENT_PS_ADMISSIONCONTROL_OVERFLOW = @as(i32, -2147469537); pub const EVENT_PS_NETWORK_ADDRESS_FAIL = @as(i32, -1073727712); pub const EXTRA_EXIT_POINT = @as(i32, -1073727524); pub const MISSING_EXIT_POINT = @as(i32, -1073727523); pub const MISSING_VOLUME = @as(i32, -1073727522); pub const EXTRA_VOLUME = @as(i32, -1073727521); pub const EXTRA_EXIT_POINT_DELETED = @as(i32, -1073727520); pub const EXTRA_EXIT_POINT_NOT_DELETED = @as(i32, -1073727519); pub const MISSING_EXIT_POINT_CREATED = @as(i32, -1073727518); pub const MISSING_EXIT_POINT_NOT_CREATED = @as(i32, -1073727517); pub const MISSING_VOLUME_CREATED = @as(i32, -1073727516); pub const MISSING_VOLUME_NOT_CREATED = @as(i32, -1073727515); pub const EXTRA_VOLUME_DELETED = @as(i32, -1073727514); pub const EXTRA_VOLUME_NOT_DELETED = @as(i32, -1073727513); pub const COULD_NOT_VERIFY_VOLUMES = @as(i32, -1073727512); pub const KNOWLEDGE_INCONSISTENCY_DETECTED = @as(i32, -1073727511); pub const PREFIX_MISMATCH = @as(i32, -1073727510); pub const PREFIX_MISMATCH_FIXED = @as(i32, -1073727509); pub const PREFIX_MISMATCH_NOT_FIXED = @as(i32, -1073727508); pub const MACHINE_UNJOINED = @as(i32, -1073727507); pub const DFS_REFERRAL_REQUEST = @as(i32, 1073756142); pub const NOT_A_DFS_PATH = @as(i32, 1073756224); pub const LM_REDIR_FAILURE = @as(i32, 1073756225); pub const DFS_CONNECTION_FAILURE = @as(i32, 1073756226); pub const DFS_REFERRAL_FAILURE = @as(i32, 1073756227); pub const DFS_REFERRAL_SUCCESS = @as(i32, 1073756228); pub const DFS_MAX_DNR_ATTEMPTS = @as(i32, 1073756229); pub const DFS_SPECIAL_REFERRAL_FAILURE = @as(i32, 1073756230); pub const DFS_OPEN_FAILURE = @as(i32, 1073756231); pub const NET_DFS_ENUM = @as(i32, 1073756324); pub const NET_DFS_ENUMEX = @as(i32, 1073756325); pub const DFS_ERROR_CREATE_REPARSEPOINT_FAILURE = @as(i32, -1073727321); pub const DFS_ERROR_UNSUPPORTED_FILESYSTEM = @as(i32, -1073727320); pub const DFS_ERROR_OVERLAPPING_DIRECTORIES = @as(i32, -1073727319); pub const DFS_INFO_ACTIVEDIRECTORY_ONLINE = @as(i32, 1073756332); pub const DFS_ERROR_TOO_MANY_ERRORS = @as(i32, -1073727315); pub const DFS_ERROR_WINSOCKINIT_FAILED = @as(i32, -1073727314); pub const DFS_ERROR_SECURITYINIT_FAILED = @as(i32, -1073727313); pub const DFS_ERROR_THREADINIT_FAILED = @as(i32, -1073727312); pub const DFS_ERROR_SITECACHEINIT_FAILED = @as(i32, -1073727311); pub const DFS_ERROR_ROOTSYNCINIT_FAILED = @as(i32, -1073727310); pub const DFS_ERROR_CREATEEVENT_FAILED = @as(i32, -1073727309); pub const DFS_ERROR_COMPUTERINFO_FAILED = @as(i32, -1073727308); pub const DFS_ERROR_CLUSTERINFO_FAILED = @as(i32, -1073727307); pub const DFS_ERROR_DCINFO_FAILED = @as(i32, -1073727306); pub const DFS_ERROR_PREFIXTABLE_FAILED = @as(i32, -1073727305); pub const DFS_ERROR_HANDLENAMESPACE_FAILED = @as(i32, -1073727304); pub const DFS_ERROR_REGISTERSTORE_FAILED = @as(i32, -1073727303); pub const DFS_ERROR_REFLECTIONENGINE_FAILED = @as(i32, -1073727302); pub const DFS_ERROR_ACTIVEDIRECTORY_OFFLINE = @as(i32, -1073727301); pub const DFS_ERROR_SITESUPPOR_FAILED = @as(i32, -1073727300); pub const DFS_ERROR_DSCONNECT_FAILED = @as(i32, -2147469122); pub const DFS_INFO_DS_RECONNECTED = @as(i32, 1073756353); pub const DFS_ERROR_NO_DFS_DATA = @as(i32, -1073727294); pub const DFS_INFO_FINISH_INIT = @as(i32, 1073756355); pub const DFS_INFO_RECONNECT_DATA = @as(i32, 1073756356); pub const DFS_INFO_FINISH_BUILDING_NAMESPACE = @as(i32, 1073756357); pub const DFS_ERROR_ON_ROOT = @as(i32, -2147469114); pub const DFS_ERROR_MUTLIPLE_ROOTS_NOT_SUPPORTED = @as(i32, -1073727289); pub const DFS_WARN_DOMAIN_REFERRAL_OVERFLOW = @as(i32, -2147469112); pub const DFS_INFO_DOMAIN_REFERRAL_MIN_OVERFLOW = @as(i32, 1073756361); pub const DFS_WARN_INCOMPLETE_MOVE = @as(i32, -2147469110); pub const DFS_ERROR_RESYNCHRONIZE_FAILED = @as(i32, -1073727285); pub const DFS_ERROR_REMOVE_LINK_FAILED = @as(i32, -1073727284); pub const DFS_WARN_METADATA_LINK_TYPE_INCORRECT = @as(i32, -2147469107); pub const DFS_WARN_METADATA_LINK_INFO_INVALID = @as(i32, -2147469106); pub const DFS_ERROR_TARGET_LIST_INCORRECT = @as(i32, -1073727281); pub const DFS_ERROR_LINKS_OVERLAP = @as(i32, -1073727280); pub const DFS_ERROR_LINK_OVERLAP = @as(i32, -1073727279); pub const DFS_ERROR_CREATE_REPARSEPOINT_SUCCESS = @as(i32, 1073756370); pub const DFS_ERROR_DUPLICATE_LINK = @as(i32, -1073727277); pub const DFS_ERROR_TRUSTED_DOMAIN_INFO_FAILED = @as(i32, -1073727276); pub const DFS_INFO_TRUSTED_DOMAIN_INFO_SUCCESS = @as(i32, 1073756373); pub const DFS_ERROR_CROSS_FOREST_TRUST_INFO_FAILED = @as(i32, -1073727274); pub const DFS_INFO_CROSS_FOREST_TRUST_INFO_SUCCESS = @as(i32, 1073756375); pub const DFS_INIT_SUCCESS = @as(i32, 1073756376); pub const DFS_ROOT_SHARE_ACQUIRE_FAILED = @as(i32, -2147469095); pub const DFS_ROOT_SHARE_ACQUIRE_SUCCESS = @as(i32, 1073756378); pub const EVENT_BRIDGE_PROTOCOL_REGISTER_FAILED = @as(i32, -1073727224); pub const EVENT_BRIDGE_MINIPROT_DEVNAME_MISSING = @as(i32, -1073727223); pub const EVENT_BRIDGE_MINIPORT_REGISTER_FAILED = @as(i32, -1073727222); pub const EVENT_BRIDGE_DEVICE_CREATION_FAILED = @as(i32, -1073727221); pub const EVENT_BRIDGE_NO_BRIDGE_MAC_ADDR = @as(i32, -1073727220); pub const EVENT_BRIDGE_MINIPORT_INIT_FAILED = @as(i32, -1073727219); pub const EVENT_BRIDGE_ETHERNET_NOT_OFFERED = @as(i32, -1073727218); pub const EVENT_BRIDGE_THREAD_CREATION_FAILED = @as(i32, -1073727217); pub const EVENT_BRIDGE_THREAD_REF_FAILED = @as(i32, -1073727216); pub const EVENT_BRIDGE_PACKET_POOL_CREATION_FAILED = @as(i32, -1073727215); pub const EVENT_BRIDGE_BUFFER_POOL_CREATION_FAILED = @as(i32, -1073727214); pub const EVENT_BRIDGE_INIT_MALLOC_FAILED = @as(i32, -1073727213); pub const EVENT_BRIDGE_ADAPTER_LINK_SPEED_QUERY_FAILED = @as(i32, -1073727124); pub const EVENT_BRIDGE_ADAPTER_MAC_ADDR_QUERY_FAILED = @as(i32, -1073727123); pub const EVENT_BRIDGE_ADAPTER_FILTER_FAILED = @as(i32, -1073727122); pub const EVENT_BRIDGE_ADAPTER_NAME_QUERY_FAILED = @as(i32, -1073727121); pub const EVENT_BRIDGE_ADAPTER_BIND_FAILED = @as(i32, -1073727120); pub const EVENT_DAV_REDIR_DELAYED_WRITE_FAILED = @as(i32, -2147468848); pub const EVENT_WEBCLIENT_CLOSE_PUT_FAILED = @as(i32, -2147468747); pub const EVENT_WEBCLIENT_CLOSE_DELETE_FAILED = @as(i32, -2147468746); pub const EVENT_WEBCLIENT_CLOSE_PROPPATCH_FAILED = @as(i32, -2147468745); pub const EVENT_WEBCLIENT_SETINFO_PROPPATCH_FAILED = @as(i32, -2147468744); pub const EVENT_WSK_OWNINGTHREAD_PARAMETER_IGNORED = @as(i32, -1073725824); pub const EVENT_WINSOCK_TDI_FILTER_DETECTED = @as(i32, -2147467647); pub const EVENT_WINSOCK_CLOSESOCKET_STUCK = @as(i32, -2147467646); pub const EVENT_EQOS_INFO_MACHINE_POLICY_REFRESH_NO_CHANGE = @as(i32, 1073758324); pub const EVENT_EQOS_INFO_MACHINE_POLICY_REFRESH_WITH_CHANGE = @as(i32, 1073758325); pub const EVENT_EQOS_INFO_USER_POLICY_REFRESH_NO_CHANGE = @as(i32, 1073758326); pub const EVENT_EQOS_INFO_USER_POLICY_REFRESH_WITH_CHANGE = @as(i32, 1073758327); pub const EVENT_EQOS_INFO_TCP_AUTOTUNING_NOT_CONFIGURED = @as(i32, 1073758328); pub const EVENT_EQOS_INFO_TCP_AUTOTUNING_OFF = @as(i32, 1073758329); pub const EVENT_EQOS_INFO_TCP_AUTOTUNING_HIGHLY_RESTRICTED = @as(i32, 1073758330); pub const EVENT_EQOS_INFO_TCP_AUTOTUNING_RESTRICTED = @as(i32, 1073758331); pub const EVENT_EQOS_INFO_TCP_AUTOTUNING_NORMAL = @as(i32, 1073758332); pub const EVENT_EQOS_INFO_APP_MARKING_NOT_CONFIGURED = @as(i32, 1073758333); pub const EVENT_EQOS_INFO_APP_MARKING_IGNORED = @as(i32, 1073758334); pub const EVENT_EQOS_INFO_APP_MARKING_ALLOWED = @as(i32, 1073758335); pub const EVENT_EQOS_INFO_LOCAL_SETTING_DONT_USE_NLA = @as(i32, 1073758336); pub const EVENT_EQOS_URL_QOS_APPLICATION_CONFLICT = @as(i32, 1073758337); pub const EVENT_EQOS_WARNING_TEST_1 = @as(i32, -2147467048); pub const EVENT_EQOS_WARNING_TEST_2 = @as(i32, -2147467047); pub const EVENT_EQOS_WARNING_MACHINE_POLICY_VERSION = @as(i32, -2147467046); pub const EVENT_EQOS_WARNING_USER_POLICY_VERSION = @as(i32, -2147467045); pub const EVENT_EQOS_WARNING_MACHINE_POLICY_PROFILE_NOT_SPECIFIED = @as(i32, -2147467044); pub const EVENT_EQOS_WARNING_USER_POLICY_PROFILE_NOT_SPECIFIED = @as(i32, -2147467043); pub const EVENT_EQOS_WARNING_MACHINE_POLICY_QUOTA_EXCEEDED = @as(i32, -2147467042); pub const EVENT_EQOS_WARNING_USER_POLICY_QUOTA_EXCEEDED = @as(i32, -2147467041); pub const EVENT_EQOS_WARNING_MACHINE_POLICY_CONFLICT = @as(i32, -2147467040); pub const EVENT_EQOS_WARNING_USER_POLICY_CONFLICT = @as(i32, -2147467039); pub const EVENT_EQOS_WARNING_MACHINE_POLICY_NO_FULLPATH_APPNAME = @as(i32, -2147467038); pub const EVENT_EQOS_WARNING_USER_POLICY_NO_FULLPATH_APPNAME = @as(i32, -2147467037); pub const EVENT_EQOS_ERROR_MACHINE_POLICY_REFERESH = @as(i32, -1073725124); pub const EVENT_EQOS_ERROR_USER_POLICY_REFERESH = @as(i32, -1073725123); pub const EVENT_EQOS_ERROR_OPENING_MACHINE_POLICY_ROOT_KEY = @as(i32, -1073725122); pub const EVENT_EQOS_ERROR_OPENING_USER_POLICY_ROOT_KEY = @as(i32, -1073725121); pub const EVENT_EQOS_ERROR_MACHINE_POLICY_KEYNAME_TOO_LONG = @as(i32, -1073725120); pub const EVENT_EQOS_ERROR_USER_POLICY_KEYNAME_TOO_LONG = @as(i32, -1073725119); pub const EVENT_EQOS_ERROR_MACHINE_POLICY_KEYNAME_SIZE_ZERO = @as(i32, -1073725118); pub const EVENT_EQOS_ERROR_USER_POLICY_KEYNAME_SIZE_ZERO = @as(i32, -1073725117); pub const EVENT_EQOS_ERROR_OPENING_MACHINE_POLICY_SUBKEY = @as(i32, -1073725116); pub const EVENT_EQOS_ERROR_OPENING_USER_POLICY_SUBKEY = @as(i32, -1073725115); pub const EVENT_EQOS_ERROR_PROCESSING_MACHINE_POLICY_FIELD = @as(i32, -1073725114); pub const EVENT_EQOS_ERROR_PROCESSING_USER_POLICY_FIELD = @as(i32, -1073725113); pub const EVENT_EQOS_ERROR_SETTING_TCP_AUTOTUNING = @as(i32, -1073725112); pub const EVENT_EQOS_ERROR_SETTING_APP_MARKING = @as(i32, -1073725111); pub const EVENT_WINNAT_SESSION_LIMIT_REACHED = @as(i32, -2147466648); pub const HARDWARE_ADDRESS_LENGTH = @as(u32, 6); pub const NETMAN_VARTYPE_ULONG = @as(u32, 0); pub const NETMAN_VARTYPE_HARDWARE_ADDRESS = @as(u32, 1); pub const NETMAN_VARTYPE_STRING = @as(u32, 2); pub const REPL_ROLE_EXPORT = @as(u32, 1); pub const REPL_ROLE_IMPORT = @as(u32, 2); pub const REPL_ROLE_BOTH = @as(u32, 3); pub const REPL_INTERVAL_INFOLEVEL = @as(u32, 1000); pub const REPL_PULSE_INFOLEVEL = @as(u32, 1001); pub const REPL_GUARDTIME_INFOLEVEL = @as(u32, 1002); pub const REPL_RANDOM_INFOLEVEL = @as(u32, 1003); pub const REPL_INTEGRITY_FILE = @as(u32, 1); pub const REPL_INTEGRITY_TREE = @as(u32, 2); pub const REPL_EXTENT_FILE = @as(u32, 1); pub const REPL_EXTENT_TREE = @as(u32, 2); pub const REPL_EXPORT_INTEGRITY_INFOLEVEL = @as(u32, 1000); pub const REPL_EXPORT_EXTENT_INFOLEVEL = @as(u32, 1001); pub const REPL_UNLOCK_NOFORCE = @as(u32, 0); pub const REPL_UNLOCK_FORCE = @as(u32, 1); pub const REPL_STATE_OK = @as(u32, 0); pub const REPL_STATE_NO_MASTER = @as(u32, 1); pub const REPL_STATE_NO_SYNC = @as(u32, 2); pub const REPL_STATE_NEVER_REPLICATED = @as(u32, 3); pub const NETCFG_E_ALREADY_INITIALIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180512)); pub const NETCFG_E_NOT_INITIALIZED = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180511)); pub const NETCFG_E_IN_USE = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180510)); pub const NETCFG_E_NO_WRITE_LOCK = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180508)); pub const NETCFG_E_NEED_REBOOT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180507)); pub const NETCFG_E_ACTIVE_RAS_CONNECTIONS = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180506)); pub const NETCFG_E_ADAPTER_NOT_FOUND = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180505)); pub const NETCFG_E_COMPONENT_REMOVED_PENDING_REBOOT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180504)); pub const NETCFG_E_MAX_FILTER_LIMIT = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180503)); pub const NETCFG_E_VMSWITCH_ACTIVE_OVER_ADAPTER = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180502)); pub const NETCFG_E_DUPLICATE_INSTANCEID = @import("../zig.zig").typedConst(HRESULT, @as(i32, -2147180501)); pub const NETCFG_S_REBOOT = @import("../zig.zig").typedConst(HRESULT, @as(i32, 303136)); pub const NETCFG_S_DISABLE_QUERY = @import("../zig.zig").typedConst(HRESULT, @as(i32, 303138)); pub const NETCFG_S_STILL_REFERENCED = @import("../zig.zig").typedConst(HRESULT, @as(i32, 303139)); pub const NETCFG_S_CAUSED_SETUP_CHANGE = @import("../zig.zig").typedConst(HRESULT, @as(i32, 303140)); pub const NETCFG_S_COMMIT_NOW = @import("../zig.zig").typedConst(HRESULT, @as(i32, 303141)); pub const WZC_PROFILE_SUCCESS = @as(u32, 0); pub const WZC_PROFILE_XML_ERROR_NO_VERSION = @as(u32, 1); pub const WZC_PROFILE_XML_ERROR_BAD_VERSION = @as(u32, 2); pub const WZC_PROFILE_XML_ERROR_UNSUPPORTED_VERSION = @as(u32, 3); pub const WZC_PROFILE_XML_ERROR_SSID_NOT_FOUND = @as(u32, 4); pub const WZC_PROFILE_XML_ERROR_BAD_SSID = @as(u32, 5); pub const WZC_PROFILE_XML_ERROR_CONNECTION_TYPE = @as(u32, 6); pub const WZC_PROFILE_XML_ERROR_AUTHENTICATION = @as(u32, 7); pub const WZC_PROFILE_XML_ERROR_ENCRYPTION = @as(u32, 8); pub const WZC_PROFILE_XML_ERROR_KEY_PROVIDED_AUTOMATICALLY = @as(u32, 9); pub const WZC_PROFILE_XML_ERROR_1X_ENABLED = @as(u32, 10); pub const WZC_PROFILE_XML_ERROR_EAP_METHOD = @as(u32, 11); pub const WZC_PROFILE_XML_ERROR_BAD_KEY_INDEX = @as(u32, 12); pub const WZC_PROFILE_XML_ERROR_KEY_INDEX_RANGE = @as(u32, 13); pub const WZC_PROFILE_XML_ERROR_BAD_NETWORK_KEY = @as(u32, 14); pub const WZC_PROFILE_CONFIG_ERROR_INVALID_AUTH_FOR_CONNECTION_TYPE = @as(u32, 15); pub const WZC_PROFILE_CONFIG_ERROR_INVALID_ENCRYPTION_FOR_AUTHMODE = @as(u32, 16); pub const WZC_PROFILE_CONFIG_ERROR_KEY_REQUIRED = @as(u32, 17); pub const WZC_PROFILE_CONFIG_ERROR_KEY_INDEX_REQUIRED = @as(u32, 18); pub const WZC_PROFILE_CONFIG_ERROR_KEY_INDEX_NOT_APPLICABLE = @as(u32, 19); pub const WZC_PROFILE_CONFIG_ERROR_1X_NOT_ALLOWED = @as(u32, 20); pub const WZC_PROFILE_CONFIG_ERROR_1X_NOT_ALLOWED_KEY_REQUIRED = @as(u32, 21); pub const WZC_PROFILE_CONFIG_ERROR_1X_NOT_ENABLED_KEY_PROVIDED = @as(u32, 22); pub const WZC_PROFILE_CONFIG_ERROR_EAP_METHOD_REQUIRED = @as(u32, 23); pub const WZC_PROFILE_CONFIG_ERROR_EAP_METHOD_NOT_APPLICABLE = @as(u32, 24); pub const WZC_PROFILE_CONFIG_ERROR_WPA_NOT_SUPPORTED = @as(u32, 25); pub const WZC_PROFILE_CONFIG_ERROR_WPA_ENCRYPTION_NOT_SUPPORTED = @as(u32, 26); pub const WZC_PROFILE_SET_ERROR_DUPLICATE_NETWORK = @as(u32, 27); pub const WZC_PROFILE_SET_ERROR_MEMORY_ALLOCATION = @as(u32, 28); pub const WZC_PROFILE_SET_ERROR_READING_1X_CONFIG = @as(u32, 29); pub const WZC_PROFILE_SET_ERROR_WRITING_1X_CONFIG = @as(u32, 30); pub const WZC_PROFILE_SET_ERROR_WRITING_WZC_CFG = @as(u32, 31); pub const WZC_PROFILE_API_ERROR_NOT_SUPPORTED = @as(u32, 32); pub const WZC_PROFILE_API_ERROR_FAILED_TO_LOAD_XML = @as(u32, 33); pub const WZC_PROFILE_API_ERROR_FAILED_TO_LOAD_SCHEMA = @as(u32, 34); pub const WZC_PROFILE_API_ERROR_XML_VALIDATION_FAILED = @as(u32, 35); pub const WZC_PROFILE_API_ERROR_INTERNAL = @as(u32, 36); pub const RF_ROUTING = @as(u32, 1); pub const RF_ROUTINGV6 = @as(u32, 2); pub const RF_DEMAND_UPDATE_ROUTES = @as(u32, 4); pub const RF_ADD_ALL_INTERFACES = @as(u32, 16); pub const RF_MULTICAST = @as(u32, 32); pub const RF_POWER = @as(u32, 64); pub const MS_ROUTER_VERSION = @as(u32, 1536); pub const ROUTING_DOMAIN_INFO_REVISION_1 = @as(u32, 1); pub const INTERFACE_INFO_REVISION_1 = @as(u32, 1); pub const IR_PROMISCUOUS = @as(u32, 0); pub const IR_PROMISCUOUS_MULTICAST = @as(u32, 1); pub const PROTO_IP_MSDP = @as(u32, 9); pub const PROTO_IP_IGMP = @as(u32, 10); pub const PROTO_IP_BGMP = @as(u32, 11); pub const PROTO_IP_VRRP = @as(u32, 112); pub const PROTO_IP_BOOTP = @as(u32, 9999); pub const PROTO_IPV6_DHCP = @as(u32, 999); pub const PROTO_IP_DNS_PROXY = @as(u32, 10003); pub const PROTO_IP_DHCP_ALLOCATOR = @as(u32, 10004); pub const PROTO_IP_NAT = @as(u32, 10005); pub const PROTO_IP_DIFFSERV = @as(u32, 10008); pub const PROTO_IP_MGM = @as(u32, 10009); pub const PROTO_IP_ALG = @as(u32, 10010); pub const PROTO_IP_H323 = @as(u32, 10011); pub const PROTO_IP_FTP = @as(u32, 10012); pub const PROTO_IP_DTP = @as(u32, 10013); pub const PROTO_TYPE_UCAST = @as(u32, 0); pub const PROTO_TYPE_MCAST = @as(u32, 1); pub const PROTO_TYPE_MS0 = @as(u32, 2); pub const PROTO_TYPE_MS1 = @as(u32, 3); pub const PROTO_VENDOR_MS0 = @as(u32, 0); pub const PROTO_VENDOR_MS1 = @as(u32, 311); pub const PROTO_VENDOR_MS2 = @as(u32, 16383); pub const IPX_PROTOCOL_BASE = @as(u32, 131071); pub const IPX_PROTOCOL_RIP = @as(u32, 131072); pub const RIS_INTERFACE_ADDRESS_CHANGE = @as(u32, 0); pub const RIS_INTERFACE_ENABLED = @as(u32, 1); pub const RIS_INTERFACE_DISABLED = @as(u32, 2); pub const RIS_INTERFACE_MEDIA_PRESENT = @as(u32, 3); pub const RIS_INTERFACE_MEDIA_ABSENT = @as(u32, 4); pub const MRINFO_TUNNEL_FLAG = @as(u32, 1); pub const MRINFO_PIM_FLAG = @as(u32, 4); pub const MRINFO_DOWN_FLAG = @as(u32, 16); pub const MRINFO_DISABLED_FLAG = @as(u32, 32); pub const MRINFO_QUERIER_FLAG = @as(u32, 64); pub const MRINFO_LEAF_FLAG = @as(u32, 128); pub const MFE_NO_ERROR = @as(u32, 0); pub const MFE_REACHED_CORE = @as(u32, 1); pub const MFE_OIF_PRUNED = @as(u32, 5); pub const MFE_PRUNED_UPSTREAM = @as(u32, 4); pub const MFE_OLD_ROUTER = @as(u32, 11); pub const MFE_NOT_FORWARDING = @as(u32, 2); pub const MFE_WRONG_IF = @as(u32, 3); pub const MFE_BOUNDARY_REACHED = @as(u32, 6); pub const MFE_NO_MULTICAST = @as(u32, 7); pub const MFE_IIF = @as(u32, 8); pub const MFE_NO_ROUTE = @as(u32, 9); pub const MFE_NOT_LAST_HOP = @as(u32, 10); pub const MFE_PROHIBITED = @as(u32, 12); pub const MFE_NO_SPACE = @as(u32, 13); pub const ALIGN_SIZE = @as(u32, 8); pub const RTR_INFO_BLOCK_VERSION = @as(u32, 1); pub const TRACE_USE_FILE = @as(u32, 1); pub const TRACE_USE_CONSOLE = @as(u32, 2); pub const TRACE_NO_SYNCH = @as(u32, 4); pub const TRACE_NO_STDINFO = @as(u32, 1); pub const TRACE_USE_MASK = @as(u32, 2); pub const TRACE_USE_MSEC = @as(u32, 4); pub const TRACE_USE_DATE = @as(u32, 8); pub const INVALID_TRACEID = @as(u32, 4294967295); pub const RTUTILS_MAX_PROTOCOL_NAME_LEN = @as(u32, 40); pub const RTUTILS_MAX_PROTOCOL_DLL_LEN = @as(u32, 48); pub const MAX_PROTOCOL_NAME_LEN = @as(u32, 40); pub const MAX_PROTOCOL_DLL_LEN = @as(u32, 48); //-------------------------------------------------------------------------------- // Section: Types (359) //-------------------------------------------------------------------------------- pub const NET_REQUEST_PROVISION_OPTIONS = enum(u32) { R = 1073741824, _, pub fn initFlags(o: struct { R: u1 = 0, }) NET_REQUEST_PROVISION_OPTIONS { return @intToEnum(NET_REQUEST_PROVISION_OPTIONS, (if (o.R == 1) @enumToInt(NET_REQUEST_PROVISION_OPTIONS.R) else 0) ); } }; pub const NETSETUP_PROVISION_ONLINE_CALLER = NET_REQUEST_PROVISION_OPTIONS.R; pub const NET_JOIN_DOMAIN_JOIN_OPTIONS = enum(u32) { JOIN_DOMAIN = 1, ACCT_CREATE = 2, WIN9X_UPGRADE = 16, DOMAIN_JOIN_IF_JOINED = 32, JOIN_UNSECURE = 64, MACHINE_PWD_PASSED = 128, DEFER_SPN_SET = 256, JOIN_DC_ACCOUNT = 512, JOIN_WITH_NEW_NAME = 1024, JOIN_READONLY = 2048, AMBIGUOUS_DC = 4096, NO_NETLOGON_CACHE = 8192, DONT_CONTROL_SERVICES = 16384, SET_MACHINE_NAME = 32768, FORCE_SPN_SET = 65536, NO_ACCT_REUSE = 131072, IGNORE_UNSUPPORTED_FLAGS = 268435456, _, pub fn initFlags(o: struct { JOIN_DOMAIN: u1 = 0, ACCT_CREATE: u1 = 0, WIN9X_UPGRADE: u1 = 0, DOMAIN_JOIN_IF_JOINED: u1 = 0, JOIN_UNSECURE: u1 = 0, MACHINE_PWD_PASSED: u1 = 0, DEFER_SPN_SET: u1 = 0, JOIN_DC_ACCOUNT: u1 = 0, JOIN_WITH_NEW_NAME: u1 = 0, JOIN_READONLY: u1 = 0, AMBIGUOUS_DC: u1 = 0, NO_NETLOGON_CACHE: u1 = 0, DONT_CONTROL_SERVICES: u1 = 0, SET_MACHINE_NAME: u1 = 0, FORCE_SPN_SET: u1 = 0, NO_ACCT_REUSE: u1 = 0, IGNORE_UNSUPPORTED_FLAGS: u1 = 0, }) NET_JOIN_DOMAIN_JOIN_OPTIONS { return @intToEnum(NET_JOIN_DOMAIN_JOIN_OPTIONS, (if (o.JOIN_DOMAIN == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_DOMAIN) else 0) | (if (o.ACCT_CREATE == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.ACCT_CREATE) else 0) | (if (o.WIN9X_UPGRADE == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.WIN9X_UPGRADE) else 0) | (if (o.DOMAIN_JOIN_IF_JOINED == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.DOMAIN_JOIN_IF_JOINED) else 0) | (if (o.JOIN_UNSECURE == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_UNSECURE) else 0) | (if (o.MACHINE_PWD_PASSED == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.MACHINE_PWD_PASSED) else 0) | (if (o.DEFER_SPN_SET == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.DEFER_SPN_SET) else 0) | (if (o.JOIN_DC_ACCOUNT == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_DC_ACCOUNT) else 0) | (if (o.JOIN_WITH_NEW_NAME == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_WITH_NEW_NAME) else 0) | (if (o.JOIN_READONLY == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_READONLY) else 0) | (if (o.AMBIGUOUS_DC == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.AMBIGUOUS_DC) else 0) | (if (o.NO_NETLOGON_CACHE == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.NO_NETLOGON_CACHE) else 0) | (if (o.DONT_CONTROL_SERVICES == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.DONT_CONTROL_SERVICES) else 0) | (if (o.SET_MACHINE_NAME == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.SET_MACHINE_NAME) else 0) | (if (o.FORCE_SPN_SET == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.FORCE_SPN_SET) else 0) | (if (o.NO_ACCT_REUSE == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.NO_ACCT_REUSE) else 0) | (if (o.IGNORE_UNSUPPORTED_FLAGS == 1) @enumToInt(NET_JOIN_DOMAIN_JOIN_OPTIONS.IGNORE_UNSUPPORTED_FLAGS) else 0) ); } }; pub const NETSETUP_JOIN_DOMAIN = NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_DOMAIN; pub const NETSETUP_ACCT_CREATE = NET_JOIN_DOMAIN_JOIN_OPTIONS.ACCT_CREATE; pub const NETSETUP_WIN9X_UPGRADE = NET_JOIN_DOMAIN_JOIN_OPTIONS.WIN9X_UPGRADE; pub const NETSETUP_DOMAIN_JOIN_IF_JOINED = NET_JOIN_DOMAIN_JOIN_OPTIONS.DOMAIN_JOIN_IF_JOINED; pub const NETSETUP_JOIN_UNSECURE = NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_UNSECURE; pub const NETSETUP_MACHINE_PWD_PASSED = NET_JOIN_DOMAIN_JOIN_OPTIONS.MACHINE_PWD_PASSED; pub const NETSETUP_DEFER_SPN_SET = NET_JOIN_DOMAIN_JOIN_OPTIONS.DEFER_SPN_SET; pub const NETSETUP_JOIN_DC_ACCOUNT = NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_DC_ACCOUNT; pub const NETSETUP_JOIN_WITH_NEW_NAME = NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_WITH_NEW_NAME; pub const NETSETUP_JOIN_READONLY = NET_JOIN_DOMAIN_JOIN_OPTIONS.JOIN_READONLY; pub const NETSETUP_AMBIGUOUS_DC = NET_JOIN_DOMAIN_JOIN_OPTIONS.AMBIGUOUS_DC; pub const NETSETUP_NO_NETLOGON_CACHE = NET_JOIN_DOMAIN_JOIN_OPTIONS.NO_NETLOGON_CACHE; pub const NETSETUP_DONT_CONTROL_SERVICES = NET_JOIN_DOMAIN_JOIN_OPTIONS.DONT_CONTROL_SERVICES; pub const NETSETUP_SET_MACHINE_NAME = NET_JOIN_DOMAIN_JOIN_OPTIONS.SET_MACHINE_NAME; pub const NETSETUP_FORCE_SPN_SET = NET_JOIN_DOMAIN_JOIN_OPTIONS.FORCE_SPN_SET; pub const NETSETUP_NO_ACCT_REUSE = NET_JOIN_DOMAIN_JOIN_OPTIONS.NO_ACCT_REUSE; pub const NETSETUP_IGNORE_UNSUPPORTED_FLAGS = NET_JOIN_DOMAIN_JOIN_OPTIONS.IGNORE_UNSUPPORTED_FLAGS; pub const NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS = enum(i32) { REMOTE_ADMIN_PROTOCOL = 2, RPC = 4, SAM_PROTOCOL = 8, UNICODE = 16, LOCAL = 32, }; pub const SUPPORTS_REMOTE_ADMIN_PROTOCOL = NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS.REMOTE_ADMIN_PROTOCOL; pub const SUPPORTS_RPC = NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS.RPC; pub const SUPPORTS_SAM_PROTOCOL = NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS.SAM_PROTOCOL; pub const SUPPORTS_UNICODE = NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS.UNICODE; pub const SUPPORTS_LOCAL = NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS.LOCAL; pub const FORCE_LEVEL_FLAGS = enum(u32) { NOFORCE = 0, FORCE = 1, LOTS_OF_FORCE = 2, }; pub const USE_NOFORCE = FORCE_LEVEL_FLAGS.NOFORCE; pub const USE_FORCE = FORCE_LEVEL_FLAGS.FORCE; pub const USE_LOTS_OF_FORCE = FORCE_LEVEL_FLAGS.LOTS_OF_FORCE; pub const NET_SERVER_TYPE = enum(u32) { WORKSTATION = 1, SERVER = 2, SQLSERVER = 4, DOMAIN_CTRL = 8, DOMAIN_BAKCTRL = 16, TIME_SOURCE = 32, AFP = 64, NOVELL = 128, DOMAIN_MEMBER = 256, PRINTQ_SERVER = 512, DIALIN_SERVER = 1024, XENIX_SERVER = 2048, // SERVER_UNIX = 2048, this enum value conflicts with XENIX_SERVER NT = 4096, WFW = 8192, SERVER_MFPN = 16384, SERVER_NT = 32768, POTENTIAL_BROWSER = 65536, BACKUP_BROWSER = 131072, MASTER_BROWSER = 262144, DOMAIN_MASTER = 524288, SERVER_OSF = 1048576, SERVER_VMS = 2097152, WINDOWS = 4194304, DFS = 8388608, CLUSTER_NT = 16777216, TERMINALSERVER = 33554432, CLUSTER_VS_NT = 67108864, DCE = 268435456, ALTERNATE_XPORT = 536870912, LOCAL_LIST_ONLY = 1073741824, DOMAIN_ENUM = 2147483648, ALL = 4294967295, _, pub fn initFlags(o: struct { WORKSTATION: u1 = 0, SERVER: u1 = 0, SQLSERVER: u1 = 0, DOMAIN_CTRL: u1 = 0, DOMAIN_BAKCTRL: u1 = 0, TIME_SOURCE: u1 = 0, AFP: u1 = 0, NOVELL: u1 = 0, DOMAIN_MEMBER: u1 = 0, PRINTQ_SERVER: u1 = 0, DIALIN_SERVER: u1 = 0, XENIX_SERVER: u1 = 0, NT: u1 = 0, WFW: u1 = 0, SERVER_MFPN: u1 = 0, SERVER_NT: u1 = 0, POTENTIAL_BROWSER: u1 = 0, BACKUP_BROWSER: u1 = 0, MASTER_BROWSER: u1 = 0, DOMAIN_MASTER: u1 = 0, SERVER_OSF: u1 = 0, SERVER_VMS: u1 = 0, WINDOWS: u1 = 0, DFS: u1 = 0, CLUSTER_NT: u1 = 0, TERMINALSERVER: u1 = 0, CLUSTER_VS_NT: u1 = 0, DCE: u1 = 0, ALTERNATE_XPORT: u1 = 0, LOCAL_LIST_ONLY: u1 = 0, DOMAIN_ENUM: u1 = 0, ALL: u1 = 0, }) NET_SERVER_TYPE { return @intToEnum(NET_SERVER_TYPE, (if (o.WORKSTATION == 1) @enumToInt(NET_SERVER_TYPE.WORKSTATION) else 0) | (if (o.SERVER == 1) @enumToInt(NET_SERVER_TYPE.SERVER) else 0) | (if (o.SQLSERVER == 1) @enumToInt(NET_SERVER_TYPE.SQLSERVER) else 0) | (if (o.DOMAIN_CTRL == 1) @enumToInt(NET_SERVER_TYPE.DOMAIN_CTRL) else 0) | (if (o.DOMAIN_BAKCTRL == 1) @enumToInt(NET_SERVER_TYPE.DOMAIN_BAKCTRL) else 0) | (if (o.TIME_SOURCE == 1) @enumToInt(NET_SERVER_TYPE.TIME_SOURCE) else 0) | (if (o.AFP == 1) @enumToInt(NET_SERVER_TYPE.AFP) else 0) | (if (o.NOVELL == 1) @enumToInt(NET_SERVER_TYPE.NOVELL) else 0) | (if (o.DOMAIN_MEMBER == 1) @enumToInt(NET_SERVER_TYPE.DOMAIN_MEMBER) else 0) | (if (o.PRINTQ_SERVER == 1) @enumToInt(NET_SERVER_TYPE.PRINTQ_SERVER) else 0) | (if (o.DIALIN_SERVER == 1) @enumToInt(NET_SERVER_TYPE.DIALIN_SERVER) else 0) | (if (o.XENIX_SERVER == 1) @enumToInt(NET_SERVER_TYPE.XENIX_SERVER) else 0) | (if (o.NT == 1) @enumToInt(NET_SERVER_TYPE.NT) else 0) | (if (o.WFW == 1) @enumToInt(NET_SERVER_TYPE.WFW) else 0) | (if (o.SERVER_MFPN == 1) @enumToInt(NET_SERVER_TYPE.SERVER_MFPN) else 0) | (if (o.SERVER_NT == 1) @enumToInt(NET_SERVER_TYPE.SERVER_NT) else 0) | (if (o.POTENTIAL_BROWSER == 1) @enumToInt(NET_SERVER_TYPE.POTENTIAL_BROWSER) else 0) | (if (o.BACKUP_BROWSER == 1) @enumToInt(NET_SERVER_TYPE.BACKUP_BROWSER) else 0) | (if (o.MASTER_BROWSER == 1) @enumToInt(NET_SERVER_TYPE.MASTER_BROWSER) else 0) | (if (o.DOMAIN_MASTER == 1) @enumToInt(NET_SERVER_TYPE.DOMAIN_MASTER) else 0) | (if (o.SERVER_OSF == 1) @enumToInt(NET_SERVER_TYPE.SERVER_OSF) else 0) | (if (o.SERVER_VMS == 1) @enumToInt(NET_SERVER_TYPE.SERVER_VMS) else 0) | (if (o.WINDOWS == 1) @enumToInt(NET_SERVER_TYPE.WINDOWS) else 0) | (if (o.DFS == 1) @enumToInt(NET_SERVER_TYPE.DFS) else 0) | (if (o.CLUSTER_NT == 1) @enumToInt(NET_SERVER_TYPE.CLUSTER_NT) else 0) | (if (o.TERMINALSERVER == 1) @enumToInt(NET_SERVER_TYPE.TERMINALSERVER) else 0) | (if (o.CLUSTER_VS_NT == 1) @enumToInt(NET_SERVER_TYPE.CLUSTER_VS_NT) else 0) | (if (o.DCE == 1) @enumToInt(NET_SERVER_TYPE.DCE) else 0) | (if (o.ALTERNATE_XPORT == 1) @enumToInt(NET_SERVER_TYPE.ALTERNATE_XPORT) else 0) | (if (o.LOCAL_LIST_ONLY == 1) @enumToInt(NET_SERVER_TYPE.LOCAL_LIST_ONLY) else 0) | (if (o.DOMAIN_ENUM == 1) @enumToInt(NET_SERVER_TYPE.DOMAIN_ENUM) else 0) | (if (o.ALL == 1) @enumToInt(NET_SERVER_TYPE.ALL) else 0) ); } }; pub const SV_TYPE_WORKSTATION = NET_SERVER_TYPE.WORKSTATION; pub const SV_TYPE_SERVER = NET_SERVER_TYPE.SERVER; pub const SV_TYPE_SQLSERVER = NET_SERVER_TYPE.SQLSERVER; pub const SV_TYPE_DOMAIN_CTRL = NET_SERVER_TYPE.DOMAIN_CTRL; pub const SV_TYPE_DOMAIN_BAKCTRL = NET_SERVER_TYPE.DOMAIN_BAKCTRL; pub const SV_TYPE_TIME_SOURCE = NET_SERVER_TYPE.TIME_SOURCE; pub const SV_TYPE_AFP = NET_SERVER_TYPE.AFP; pub const SV_TYPE_NOVELL = NET_SERVER_TYPE.NOVELL; pub const SV_TYPE_DOMAIN_MEMBER = NET_SERVER_TYPE.DOMAIN_MEMBER; pub const SV_TYPE_PRINTQ_SERVER = NET_SERVER_TYPE.PRINTQ_SERVER; pub const SV_TYPE_DIALIN_SERVER = NET_SERVER_TYPE.DIALIN_SERVER; pub const SV_TYPE_XENIX_SERVER = NET_SERVER_TYPE.XENIX_SERVER; pub const SV_TYPE_SERVER_UNIX = NET_SERVER_TYPE.XENIX_SERVER; pub const SV_TYPE_NT = NET_SERVER_TYPE.NT; pub const SV_TYPE_WFW = NET_SERVER_TYPE.WFW; pub const SV_TYPE_SERVER_MFPN = NET_SERVER_TYPE.SERVER_MFPN; pub const SV_TYPE_SERVER_NT = NET_SERVER_TYPE.SERVER_NT; pub const SV_TYPE_POTENTIAL_BROWSER = NET_SERVER_TYPE.POTENTIAL_BROWSER; pub const SV_TYPE_BACKUP_BROWSER = NET_SERVER_TYPE.BACKUP_BROWSER; pub const SV_TYPE_MASTER_BROWSER = NET_SERVER_TYPE.MASTER_BROWSER; pub const SV_TYPE_DOMAIN_MASTER = NET_SERVER_TYPE.DOMAIN_MASTER; pub const SV_TYPE_SERVER_OSF = NET_SERVER_TYPE.SERVER_OSF; pub const SV_TYPE_SERVER_VMS = NET_SERVER_TYPE.SERVER_VMS; pub const SV_TYPE_WINDOWS = NET_SERVER_TYPE.WINDOWS; pub const SV_TYPE_DFS = NET_SERVER_TYPE.DFS; pub const SV_TYPE_CLUSTER_NT = NET_SERVER_TYPE.CLUSTER_NT; pub const SV_TYPE_TERMINALSERVER = NET_SERVER_TYPE.TERMINALSERVER; pub const SV_TYPE_CLUSTER_VS_NT = NET_SERVER_TYPE.CLUSTER_VS_NT; pub const SV_TYPE_DCE = NET_SERVER_TYPE.DCE; pub const SV_TYPE_ALTERNATE_XPORT = NET_SERVER_TYPE.ALTERNATE_XPORT; pub const SV_TYPE_LOCAL_LIST_ONLY = NET_SERVER_TYPE.LOCAL_LIST_ONLY; pub const SV_TYPE_DOMAIN_ENUM = NET_SERVER_TYPE.DOMAIN_ENUM; pub const SV_TYPE_ALL = NET_SERVER_TYPE.ALL; pub const NET_USER_ENUM_FILTER_FLAGS = enum(u32) { TEMP_DUPLICATE_ACCOUNT = 1, NORMAL_ACCOUNT = 2, INTERDOMAIN_TRUST_ACCOUNT = 8, WORKSTATION_TRUST_ACCOUNT = 16, SERVER_TRUST_ACCOUNT = 32, _, pub fn initFlags(o: struct { TEMP_DUPLICATE_ACCOUNT: u1 = 0, NORMAL_ACCOUNT: u1 = 0, INTERDOMAIN_TRUST_ACCOUNT: u1 = 0, WORKSTATION_TRUST_ACCOUNT: u1 = 0, SERVER_TRUST_ACCOUNT: u1 = 0, }) NET_USER_ENUM_FILTER_FLAGS { return @intToEnum(NET_USER_ENUM_FILTER_FLAGS, (if (o.TEMP_DUPLICATE_ACCOUNT == 1) @enumToInt(NET_USER_ENUM_FILTER_FLAGS.TEMP_DUPLICATE_ACCOUNT) else 0) | (if (o.NORMAL_ACCOUNT == 1) @enumToInt(NET_USER_ENUM_FILTER_FLAGS.NORMAL_ACCOUNT) else 0) | (if (o.INTERDOMAIN_TRUST_ACCOUNT == 1) @enumToInt(NET_USER_ENUM_FILTER_FLAGS.INTERDOMAIN_TRUST_ACCOUNT) else 0) | (if (o.WORKSTATION_TRUST_ACCOUNT == 1) @enumToInt(NET_USER_ENUM_FILTER_FLAGS.WORKSTATION_TRUST_ACCOUNT) else 0) | (if (o.SERVER_TRUST_ACCOUNT == 1) @enumToInt(NET_USER_ENUM_FILTER_FLAGS.SERVER_TRUST_ACCOUNT) else 0) ); } }; pub const FILTER_TEMP_DUPLICATE_ACCOUNT = NET_USER_ENUM_FILTER_FLAGS.TEMP_DUPLICATE_ACCOUNT; pub const FILTER_NORMAL_ACCOUNT = NET_USER_ENUM_FILTER_FLAGS.NORMAL_ACCOUNT; pub const FILTER_INTERDOMAIN_TRUST_ACCOUNT = NET_USER_ENUM_FILTER_FLAGS.INTERDOMAIN_TRUST_ACCOUNT; pub const FILTER_WORKSTATION_TRUST_ACCOUNT = NET_USER_ENUM_FILTER_FLAGS.WORKSTATION_TRUST_ACCOUNT; pub const FILTER_SERVER_TRUST_ACCOUNT = NET_USER_ENUM_FILTER_FLAGS.SERVER_TRUST_ACCOUNT; pub const NETSETUP_PROVISION = enum(u32) { DOWNLEVEL_PRIV_SUPPORT = 1, REUSE_ACCOUNT = 2, USE_DEFAULT_PASSWORD = 4, SKIP_ACCOUNT_SEARCH = 8, ROOT_CA_CERTS = 16, _, pub fn initFlags(o: struct { DOWNLEVEL_PRIV_SUPPORT: u1 = 0, REUSE_ACCOUNT: u1 = 0, USE_DEFAULT_PASSWORD: u1 = 0, SKIP_ACCOUNT_SEARCH: u1 = 0, ROOT_CA_CERTS: u1 = 0, }) NETSETUP_PROVISION { return @intToEnum(NETSETUP_PROVISION, (if (o.DOWNLEVEL_PRIV_SUPPORT == 1) @enumToInt(NETSETUP_PROVISION.DOWNLEVEL_PRIV_SUPPORT) else 0) | (if (o.REUSE_ACCOUNT == 1) @enumToInt(NETSETUP_PROVISION.REUSE_ACCOUNT) else 0) | (if (o.USE_DEFAULT_PASSWORD == 1) @enumToInt(NETSETUP_PROVISION.USE_DEFAULT_PASSWORD) else 0) | (if (o.SKIP_ACCOUNT_SEARCH == 1) @enumToInt(NETSETUP_PROVISION.SKIP_ACCOUNT_SEARCH) else 0) | (if (o.ROOT_CA_CERTS == 1) @enumToInt(NETSETUP_PROVISION.ROOT_CA_CERTS) else 0) ); } }; pub const NETSETUP_PROVISION_DOWNLEVEL_PRIV_SUPPORT = NETSETUP_PROVISION.DOWNLEVEL_PRIV_SUPPORT; pub const NETSETUP_PROVISION_REUSE_ACCOUNT = NETSETUP_PROVISION.REUSE_ACCOUNT; pub const NETSETUP_PROVISION_USE_DEFAULT_PASSWORD = NETSETUP_PROVISION.USE_DEFAULT_PASSWORD; pub const NETSETUP_PROVISION_SKIP_ACCOUNT_SEARCH = NETSETUP_PROVISION.SKIP_ACCOUNT_SEARCH; pub const NETSETUP_PROVISION_ROOT_CA_CERTS = NETSETUP_PROVISION.ROOT_CA_CERTS; pub const USER_ACCOUNT_FLAGS = enum(u32) { SCRIPT = 1, ACCOUNTDISABLE = 2, HOMEDIR_REQUIRED = 8, PASSWD_NOTREQD = 32, PASSWD_CANT_CHANGE = 64, LOCKOUT = 16, DONT_EXPIRE_PASSWD = 65536, ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128, NOT_DELEGATED = 1048576, SMARTCARD_REQUIRED = 262144, USE_DES_KEY_ONLY = 2097152, DONT_REQUIRE_PREAUTH = 4194304, TRUSTED_FOR_DELEGATION = 524288, PASSWORD_EXPIRED = 8388608, TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 16777216, _, pub fn initFlags(o: struct { SCRIPT: u1 = 0, ACCOUNTDISABLE: u1 = 0, HOMEDIR_REQUIRED: u1 = 0, PASSWD_NOTREQD: u1 = 0, PASSWD_CANT_CHANGE: u1 = 0, LOCKOUT: u1 = 0, DONT_EXPIRE_PASSWD: u1 = 0, ENCRYPTED_TEXT_PASSWORD_ALLOWED: u1 = 0, NOT_DELEGATED: u1 = 0, SMARTCARD_REQUIRED: u1 = 0, USE_DES_KEY_ONLY: u1 = 0, DONT_REQUIRE_PREAUTH: u1 = 0, TRUSTED_FOR_DELEGATION: u1 = 0, PASSWORD_EXPIRED: u1 = 0, TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION: u1 = 0, }) USER_ACCOUNT_FLAGS { return @intToEnum(USER_ACCOUNT_FLAGS, (if (o.SCRIPT == 1) @enumToInt(USER_ACCOUNT_FLAGS.SCRIPT) else 0) | (if (o.ACCOUNTDISABLE == 1) @enumToInt(USER_ACCOUNT_FLAGS.ACCOUNTDISABLE) else 0) | (if (o.HOMEDIR_REQUIRED == 1) @enumToInt(USER_ACCOUNT_FLAGS.HOMEDIR_REQUIRED) else 0) | (if (o.PASSWD_NOTREQD == 1) @enumToInt(USER_ACCOUNT_FLAGS.PASSWD_NOTREQD) else 0) | (if (o.PASSWD_CANT_CHANGE == 1) @enumToInt(USER_ACCOUNT_FLAGS.PASSWD_CANT_CHANGE) else 0) | (if (o.LOCKOUT == 1) @enumToInt(USER_ACCOUNT_FLAGS.LOCKOUT) else 0) | (if (o.DONT_EXPIRE_PASSWD == 1) @enumToInt(USER_ACCOUNT_FLAGS.DONT_EXPIRE_PASSWD) else 0) | (if (o.ENCRYPTED_TEXT_PASSWORD_ALLOWED == 1) @enumToInt(USER_ACCOUNT_FLAGS.ENCRYPTED_TEXT_PASSWORD_ALLOWED) else 0) | (if (o.NOT_DELEGATED == 1) @enumToInt(USER_ACCOUNT_FLAGS.NOT_DELEGATED) else 0) | (if (o.SMARTCARD_REQUIRED == 1) @enumToInt(USER_ACCOUNT_FLAGS.SMARTCARD_REQUIRED) else 0) | (if (o.USE_DES_KEY_ONLY == 1) @enumToInt(USER_ACCOUNT_FLAGS.USE_DES_KEY_ONLY) else 0) | (if (o.DONT_REQUIRE_PREAUTH == 1) @enumToInt(USER_ACCOUNT_FLAGS.DONT_REQUIRE_PREAUTH) else 0) | (if (o.TRUSTED_FOR_DELEGATION == 1) @enumToInt(USER_ACCOUNT_FLAGS.TRUSTED_FOR_DELEGATION) else 0) | (if (o.PASSWORD_EXPIRED == 1) @enumToInt(USER_ACCOUNT_FLAGS.PASSWORD_EXPIRED) else 0) | (if (o.TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION == 1) @enumToInt(USER_ACCOUNT_FLAGS.TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION) else 0) ); } }; pub const UF_SCRIPT = USER_ACCOUNT_FLAGS.SCRIPT; pub const UF_ACCOUNTDISABLE = USER_ACCOUNT_FLAGS.ACCOUNTDISABLE; pub const UF_HOMEDIR_REQUIRED = USER_ACCOUNT_FLAGS.HOMEDIR_REQUIRED; pub const UF_PASSWD_NOTREQD = USER_ACCOUNT_FLAGS.PASSWD_NOTREQD; pub const UF_PASSWD_CANT_CHANGE = USER_ACCOUNT_FLAGS.PASSWD_CANT_CHANGE; pub const UF_LOCKOUT = USER_ACCOUNT_FLAGS.LOCKOUT; pub const UF_DONT_EXPIRE_PASSWD = USER_ACCOUNT_FLAGS.DONT_EXPIRE_PASSWD; pub const UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = USER_ACCOUNT_FLAGS.ENCRYPTED_TEXT_PASSWORD_ALLOWED; pub const UF_NOT_DELEGATED = USER_ACCOUNT_FLAGS.NOT_DELEGATED; pub const UF_SMARTCARD_REQUIRED = USER_ACCOUNT_FLAGS.SMARTCARD_REQUIRED; pub const UF_USE_DES_KEY_ONLY = USER_ACCOUNT_FLAGS.USE_DES_KEY_ONLY; pub const UF_DONT_REQUIRE_PREAUTH = USER_ACCOUNT_FLAGS.DONT_REQUIRE_PREAUTH; pub const UF_TRUSTED_FOR_DELEGATION = USER_ACCOUNT_FLAGS.TRUSTED_FOR_DELEGATION; pub const UF_PASSWORD_EXPIRED = USER_ACCOUNT_FLAGS.PASSWORD_EXPIRED; pub const UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = USER_ACCOUNT_FLAGS.TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION; pub const AF_OP = enum(u32) { PRINT = 1, COMM = 2, SERVER = 4, ACCOUNTS = 8, _, pub fn initFlags(o: struct { PRINT: u1 = 0, COMM: u1 = 0, SERVER: u1 = 0, ACCOUNTS: u1 = 0, }) AF_OP { return @intToEnum(AF_OP, (if (o.PRINT == 1) @enumToInt(AF_OP.PRINT) else 0) | (if (o.COMM == 1) @enumToInt(AF_OP.COMM) else 0) | (if (o.SERVER == 1) @enumToInt(AF_OP.SERVER) else 0) | (if (o.ACCOUNTS == 1) @enumToInt(AF_OP.ACCOUNTS) else 0) ); } }; pub const AF_OP_PRINT = AF_OP.PRINT; pub const AF_OP_COMM = AF_OP.COMM; pub const AF_OP_SERVER = AF_OP.SERVER; pub const AF_OP_ACCOUNTS = AF_OP.ACCOUNTS; pub const SERVER_INFO_SECURITY = enum(u32) { SHARESECURITY = 0, USERSECURITY = 1, }; pub const SV_SHARESECURITY = SERVER_INFO_SECURITY.SHARESECURITY; pub const SV_USERSECURITY = SERVER_INFO_SECURITY.USERSECURITY; pub const USER_PRIV = enum(u32) { GUEST = 0, USER = 1, ADMIN = 2, }; pub const USER_PRIV_GUEST = USER_PRIV.GUEST; pub const USER_PRIV_USER = USER_PRIV.USER; pub const USER_PRIV_ADMIN = USER_PRIV.ADMIN; pub const USE_INFO_ASG_TYPE = enum(u32) { WILDCARD = 4294967295, DISKDEV = 0, SPOOLDEV = 1, IPC = 3, }; pub const USE_WILDCARD = USE_INFO_ASG_TYPE.WILDCARD; pub const USE_DISKDEV = USE_INFO_ASG_TYPE.DISKDEV; pub const USE_SPOOLDEV = USE_INFO_ASG_TYPE.SPOOLDEV; pub const USE_IPC = USE_INFO_ASG_TYPE.IPC; pub const SERVER_INFO_HIDDEN = enum(u32) { VISIBLE = 0, HIDDEN = 1, }; pub const SV_VISIBLE = SERVER_INFO_HIDDEN.VISIBLE; pub const SV_HIDDEN = SERVER_INFO_HIDDEN.HIDDEN; pub const USER_MODALS_ROLES = enum(u32) { STANDALONE = 0, MEMBER = 1, BACKUP = 2, PRIMARY = 3, }; pub const UAS_ROLE_STANDALONE = USER_MODALS_ROLES.STANDALONE; pub const UAS_ROLE_MEMBER = USER_MODALS_ROLES.MEMBER; pub const UAS_ROLE_BACKUP = USER_MODALS_ROLES.BACKUP; pub const UAS_ROLE_PRIMARY = USER_MODALS_ROLES.PRIMARY; pub const USER_INFO_0 = extern struct { usri0_name: ?PWSTR, }; pub const USER_INFO_1 = extern struct { usri1_name: ?PWSTR, usri1_password: ?PWSTR, usri1_password_age: u32, usri1_priv: USER_PRIV, usri1_home_dir: ?PWSTR, usri1_comment: ?PWSTR, usri1_flags: USER_ACCOUNT_FLAGS, usri1_script_path: ?PWSTR, }; pub const USER_INFO_2 = extern struct { usri2_name: ?PWSTR, usri2_password: ?PWSTR, usri2_password_age: u32, usri2_priv: USER_PRIV, usri2_home_dir: ?PWSTR, usri2_comment: ?PWSTR, usri2_flags: USER_ACCOUNT_FLAGS, usri2_script_path: ?PWSTR, usri2_auth_flags: AF_OP, usri2_full_name: ?PWSTR, usri2_usr_comment: ?PWSTR, usri2_parms: ?PWSTR, usri2_workstations: ?PWSTR, usri2_last_logon: u32, usri2_last_logoff: u32, usri2_acct_expires: u32, usri2_max_storage: u32, usri2_units_per_week: u32, usri2_logon_hours: ?*u8, usri2_bad_pw_count: u32, usri2_num_logons: u32, usri2_logon_server: ?PWSTR, usri2_country_code: u32, usri2_code_page: u32, }; pub const USER_INFO_3 = extern struct { usri3_name: ?PWSTR, usri3_password: ?PWSTR, usri3_password_age: u32, usri3_priv: USER_PRIV, usri3_home_dir: ?PWSTR, usri3_comment: ?PWSTR, usri3_flags: USER_ACCOUNT_FLAGS, usri3_script_path: ?PWSTR, usri3_auth_flags: AF_OP, usri3_full_name: ?PWSTR, usri3_usr_comment: ?PWSTR, usri3_parms: ?PWSTR, usri3_workstations: ?PWSTR, usri3_last_logon: u32, usri3_last_logoff: u32, usri3_acct_expires: u32, usri3_max_storage: u32, usri3_units_per_week: u32, usri3_logon_hours: ?*u8, usri3_bad_pw_count: u32, usri3_num_logons: u32, usri3_logon_server: ?PWSTR, usri3_country_code: u32, usri3_code_page: u32, usri3_user_id: u32, usri3_primary_group_id: u32, usri3_profile: ?PWSTR, usri3_home_dir_drive: ?PWSTR, usri3_password_expired: u32, }; pub const USER_INFO_4 = extern struct { usri4_name: ?PWSTR, usri4_password: ?PWSTR, usri4_password_age: u32, usri4_priv: USER_PRIV, usri4_home_dir: ?PWSTR, usri4_comment: ?PWSTR, usri4_flags: USER_ACCOUNT_FLAGS, usri4_script_path: ?PWSTR, usri4_auth_flags: AF_OP, usri4_full_name: ?PWSTR, usri4_usr_comment: ?PWSTR, usri4_parms: ?PWSTR, usri4_workstations: ?PWSTR, usri4_last_logon: u32, usri4_last_logoff: u32, usri4_acct_expires: u32, usri4_max_storage: u32, usri4_units_per_week: u32, usri4_logon_hours: ?*u8, usri4_bad_pw_count: u32, usri4_num_logons: u32, usri4_logon_server: ?PWSTR, usri4_country_code: u32, usri4_code_page: u32, usri4_user_sid: ?PSID, usri4_primary_group_id: u32, usri4_profile: ?PWSTR, usri4_home_dir_drive: ?PWSTR, usri4_password_expired: u32, }; pub const USER_INFO_10 = extern struct { usri10_name: ?PWSTR, usri10_comment: ?PWSTR, usri10_usr_comment: ?PWSTR, usri10_full_name: ?PWSTR, }; pub const USER_INFO_11 = extern struct { usri11_name: ?PWSTR, usri11_comment: ?PWSTR, usri11_usr_comment: ?PWSTR, usri11_full_name: ?PWSTR, usri11_priv: USER_PRIV, usri11_auth_flags: AF_OP, usri11_password_age: u32, usri11_home_dir: ?PWSTR, usri11_parms: ?PWSTR, usri11_last_logon: u32, usri11_last_logoff: u32, usri11_bad_pw_count: u32, usri11_num_logons: u32, usri11_logon_server: ?PWSTR, usri11_country_code: u32, usri11_workstations: ?PWSTR, usri11_max_storage: u32, usri11_units_per_week: u32, usri11_logon_hours: ?*u8, usri11_code_page: u32, }; pub const USER_INFO_20 = extern struct { usri20_name: ?PWSTR, usri20_full_name: ?PWSTR, usri20_comment: ?PWSTR, usri20_flags: USER_ACCOUNT_FLAGS, usri20_user_id: u32, }; pub const USER_INFO_21 = extern struct { usri21_password: [16]u8, }; pub const USER_INFO_22 = extern struct { usri22_name: ?PWSTR, usri22_password: [16]u8, usri22_password_age: u32, usri22_priv: USER_PRIV, usri22_home_dir: ?PWSTR, usri22_comment: ?PWSTR, usri22_flags: USER_ACCOUNT_FLAGS, usri22_script_path: ?PWSTR, usri22_auth_flags: AF_OP, usri22_full_name: ?PWSTR, usri22_usr_comment: ?PWSTR, usri22_parms: ?PWSTR, usri22_workstations: ?PWSTR, usri22_last_logon: u32, usri22_last_logoff: u32, usri22_acct_expires: u32, usri22_max_storage: u32, usri22_units_per_week: u32, usri22_logon_hours: ?*u8, usri22_bad_pw_count: u32, usri22_num_logons: u32, usri22_logon_server: ?PWSTR, usri22_country_code: u32, usri22_code_page: u32, }; pub const USER_INFO_23 = extern struct { usri23_name: ?PWSTR, usri23_full_name: ?PWSTR, usri23_comment: ?PWSTR, usri23_flags: USER_ACCOUNT_FLAGS, usri23_user_sid: ?PSID, }; pub const USER_INFO_24 = extern struct { usri24_internet_identity: BOOL, usri24_flags: u32, usri24_internet_provider_name: ?PWSTR, usri24_internet_principal_name: ?PWSTR, usri24_user_sid: ?PSID, }; pub const USER_INFO_1003 = extern struct { usri1003_password: ?PWSTR, }; pub const USER_INFO_1005 = extern struct { usri1005_priv: USER_PRIV, }; pub const USER_INFO_1006 = extern struct { usri1006_home_dir: ?PWSTR, }; pub const USER_INFO_1007 = extern struct { usri1007_comment: ?PWSTR, }; pub const USER_INFO_1008 = extern struct { usri1008_flags: USER_ACCOUNT_FLAGS, }; pub const USER_INFO_1009 = extern struct { usri1009_script_path: ?PWSTR, }; pub const USER_INFO_1010 = extern struct { usri1010_auth_flags: AF_OP, }; pub const USER_INFO_1011 = extern struct { usri1011_full_name: ?PWSTR, }; pub const USER_INFO_1012 = extern struct { usri1012_usr_comment: ?PWSTR, }; pub const USER_INFO_1013 = extern struct { usri1013_parms: ?PWSTR, }; pub const USER_INFO_1014 = extern struct { usri1014_workstations: ?PWSTR, }; pub const USER_INFO_1017 = extern struct { usri1017_acct_expires: u32, }; pub const USER_INFO_1018 = extern struct { usri1018_max_storage: u32, }; pub const USER_INFO_1020 = extern struct { usri1020_units_per_week: u32, usri1020_logon_hours: ?*u8, }; pub const USER_INFO_1023 = extern struct { usri1023_logon_server: ?PWSTR, }; pub const USER_INFO_1024 = extern struct { usri1024_country_code: u32, }; pub const USER_INFO_1025 = extern struct { usri1025_code_page: u32, }; pub const USER_INFO_1051 = extern struct { usri1051_primary_group_id: u32, }; pub const USER_INFO_1052 = extern struct { usri1052_profile: ?PWSTR, }; pub const USER_INFO_1053 = extern struct { usri1053_home_dir_drive: ?PWSTR, }; pub const USER_MODALS_INFO_0 = extern struct { usrmod0_min_passwd_len: u32, usrmod0_max_passwd_age: u32, usrmod0_min_passwd_age: u32, usrmod0_force_logoff: u32, usrmod0_password_hist_len: u32, }; pub const USER_MODALS_INFO_1 = extern struct { usrmod1_role: u32, usrmod1_primary: ?PWSTR, }; pub const USER_MODALS_INFO_2 = extern struct { usrmod2_domain_name: ?PWSTR, usrmod2_domain_id: ?PSID, }; pub const USER_MODALS_INFO_3 = extern struct { usrmod3_lockout_duration: u32, usrmod3_lockout_observation_window: u32, usrmod3_lockout_threshold: u32, }; pub const USER_MODALS_INFO_1001 = extern struct { usrmod1001_min_passwd_len: u32, }; pub const USER_MODALS_INFO_1002 = extern struct { usrmod1002_max_passwd_age: u32, }; pub const USER_MODALS_INFO_1003 = extern struct { usrmod1003_min_passwd_age: u32, }; pub const USER_MODALS_INFO_1004 = extern struct { usrmod1004_force_logoff: u32, }; pub const USER_MODALS_INFO_1005 = extern struct { usrmod1005_password_hist_len: u32, }; pub const USER_MODALS_INFO_1006 = extern struct { usrmod1006_role: USER_MODALS_ROLES, }; pub const USER_MODALS_INFO_1007 = extern struct { usrmod1007_primary: ?PWSTR, }; pub const GROUP_INFO_0 = extern struct { grpi0_name: ?PWSTR, }; pub const GROUP_INFO_1 = extern struct { grpi1_name: ?PWSTR, grpi1_comment: ?PWSTR, }; pub const GROUP_INFO_2 = extern struct { grpi2_name: ?PWSTR, grpi2_comment: ?PWSTR, grpi2_group_id: u32, grpi2_attributes: u32, }; pub const GROUP_INFO_3 = extern struct { grpi3_name: ?PWSTR, grpi3_comment: ?PWSTR, grpi3_group_sid: ?PSID, grpi3_attributes: u32, }; pub const GROUP_INFO_1002 = extern struct { grpi1002_comment: ?PWSTR, }; pub const GROUP_INFO_1005 = extern struct { grpi1005_attributes: u32, }; pub const GROUP_USERS_INFO_0 = extern struct { grui0_name: ?PWSTR, }; pub const GROUP_USERS_INFO_1 = extern struct { grui1_name: ?PWSTR, grui1_attributes: u32, }; pub const LOCALGROUP_INFO_0 = extern struct { lgrpi0_name: ?PWSTR, }; pub const LOCALGROUP_INFO_1 = extern struct { lgrpi1_name: ?PWSTR, lgrpi1_comment: ?PWSTR, }; pub const LOCALGROUP_INFO_1002 = extern struct { lgrpi1002_comment: ?PWSTR, }; pub const LOCALGROUP_MEMBERS_INFO_0 = extern struct { lgrmi0_sid: ?PSID, }; pub const LOCALGROUP_MEMBERS_INFO_1 = extern struct { lgrmi1_sid: ?PSID, lgrmi1_sidusage: SID_NAME_USE, lgrmi1_name: ?PWSTR, }; pub const LOCALGROUP_MEMBERS_INFO_2 = extern struct { lgrmi2_sid: ?PSID, lgrmi2_sidusage: SID_NAME_USE, lgrmi2_domainandname: ?PWSTR, }; pub const LOCALGROUP_MEMBERS_INFO_3 = extern struct { lgrmi3_domainandname: ?PWSTR, }; pub const LOCALGROUP_USERS_INFO_0 = extern struct { lgrui0_name: ?PWSTR, }; pub const NET_DISPLAY_USER = extern struct { usri1_name: ?PWSTR, usri1_comment: ?PWSTR, usri1_flags: USER_ACCOUNT_FLAGS, usri1_full_name: ?PWSTR, usri1_user_id: u32, usri1_next_index: u32, }; pub const NET_DISPLAY_MACHINE = extern struct { usri2_name: ?PWSTR, usri2_comment: ?PWSTR, usri2_flags: USER_ACCOUNT_FLAGS, usri2_user_id: u32, usri2_next_index: u32, }; pub const NET_DISPLAY_GROUP = extern struct { grpi3_name: ?PWSTR, grpi3_comment: ?PWSTR, grpi3_group_id: u32, grpi3_attributes: u32, grpi3_next_index: u32, }; pub const ACCESS_INFO_0 = extern struct { acc0_resource_name: ?PWSTR, }; pub const ACCESS_INFO_1 = extern struct { acc1_resource_name: ?PWSTR, acc1_attr: u32, acc1_count: u32, }; pub const ACCESS_INFO_1002 = extern struct { acc1002_attr: u32, }; pub const ACCESS_LIST = extern struct { acl_ugname: ?PWSTR, acl_access: u32, }; pub const NET_VALIDATE_PASSWORD_TYPE = enum(i32) { Authentication = 1, PasswordChange = 2, PasswordReset = 3, }; pub const NetValidateAuthentication = NET_VALIDATE_PASSWORD_TYPE.Authentication; pub const NetValidatePasswordChange = NET_VALIDATE_PASSWORD_TYPE.PasswordChange; pub const NetValidatePasswordReset = NET_VALIDATE_PASSWORD_TYPE.PasswordReset; pub const NET_VALIDATE_PASSWORD_HASH = extern struct { Length: u32, Hash: ?*u8, }; pub const NET_VALIDATE_PERSISTED_FIELDS = extern struct { PresentFields: u32, PasswordLastSet: FILETIME, BadPasswordTime: FILETIME, LockoutTime: FILETIME, BadPasswordCount: u32, PasswordHistoryLength: u32, PasswordHistory: ?*NET_VALIDATE_PASSWORD_HASH, }; pub const NET_VALIDATE_OUTPUT_ARG = extern struct { ChangedPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, ValidationStatus: u32, }; pub const NET_VALIDATE_AUTHENTICATION_INPUT_ARG = extern struct { InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, PasswordMatched: BOOLEAN, }; pub const NET_VALIDATE_PASSWORD_CHANGE_INPUT_ARG = extern struct { InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, ClearPassword: ?PWSTR, UserAccountName: ?PWSTR, HashedPassword: NET_VALIDATE_PASSWORD_HASH, PasswordMatch: BOOLEAN, }; pub const NET_VALIDATE_PASSWORD_RESET_INPUT_ARG = extern struct { InputPersistedFields: NET_VALIDATE_PERSISTED_FIELDS, ClearPassword: ?PWSTR, UserAccountName: ?PWSTR, HashedPassword: NET_VALIDATE_PASSWORD_HASH, PasswordMustChangeAtNextLogon: BOOLEAN, ClearLockout: BOOLEAN, }; pub const NETLOGON_INFO_1 = extern struct { netlog1_flags: u32, netlog1_pdc_connection_status: u32, }; pub const NETLOGON_INFO_2 = extern struct { netlog2_flags: u32, netlog2_pdc_connection_status: u32, netlog2_trusted_dc_name: ?PWSTR, netlog2_tc_connection_status: u32, }; pub const NETLOGON_INFO_3 = extern struct { netlog3_flags: u32, netlog3_logon_attempts: u32, netlog3_reserved1: u32, netlog3_reserved2: u32, netlog3_reserved3: u32, netlog3_reserved4: u32, netlog3_reserved5: u32, }; pub const NETLOGON_INFO_4 = extern struct { netlog4_trusted_dc_name: ?PWSTR, netlog4_trusted_domain_name: ?PWSTR, }; pub const MSA_INFO_LEVEL = enum(i32) { @"0" = 0, Max = 1, }; pub const MsaInfoLevel0 = MSA_INFO_LEVEL.@"0"; pub const MsaInfoLevelMax = MSA_INFO_LEVEL.Max; pub const MSA_INFO_STATE = enum(i32) { NotExist = 1, NotService = 2, CannotInstall = 3, CanInstall = 4, Installed = 5, }; pub const MsaInfoNotExist = MSA_INFO_STATE.NotExist; pub const MsaInfoNotService = MSA_INFO_STATE.NotService; pub const MsaInfoCannotInstall = MSA_INFO_STATE.CannotInstall; pub const MsaInfoCanInstall = MSA_INFO_STATE.CanInstall; pub const MsaInfoInstalled = MSA_INFO_STATE.Installed; pub const MSA_INFO_0 = extern struct { State: MSA_INFO_STATE, }; pub const STD_ALERT = extern struct { alrt_timestamp: u32, alrt_eventname: [17]u16, alrt_servicename: [81]u16, }; pub const ADMIN_OTHER_INFO = extern struct { alrtad_errcode: u32, alrtad_numstrings: u32, }; pub const ERRLOG_OTHER_INFO = extern struct { alrter_errcode: u32, alrter_offset: u32, }; pub const PRINT_OTHER_INFO = extern struct { alrtpr_jobid: u32, alrtpr_status: u32, alrtpr_submitted: u32, alrtpr_size: u32, }; pub const USER_OTHER_INFO = extern struct { alrtus_errcode: u32, alrtus_numstrings: u32, }; pub const MSG_INFO_0 = extern struct { msgi0_name: ?PWSTR, }; pub const MSG_INFO_1 = extern struct { msgi1_name: ?PWSTR, msgi1_forward_flag: u32, msgi1_forward: ?PWSTR, }; pub const TIME_OF_DAY_INFO = extern struct { tod_elapsedt: u32, tod_msecs: u32, tod_hours: u32, tod_mins: u32, tod_secs: u32, tod_hunds: u32, tod_timezone: i32, tod_tinterval: u32, tod_day: u32, tod_month: u32, tod_year: u32, tod_weekday: u32, }; pub const REPL_INFO_0 = extern struct { rp0_role: u32, rp0_exportpath: ?PWSTR, rp0_exportlist: ?PWSTR, rp0_importpath: ?PWSTR, rp0_importlist: ?PWSTR, rp0_logonusername: ?PWSTR, rp0_interval: u32, rp0_pulse: u32, rp0_guardtime: u32, rp0_random: u32, }; pub const REPL_INFO_1000 = extern struct { rp1000_interval: u32, }; pub const REPL_INFO_1001 = extern struct { rp1001_pulse: u32, }; pub const REPL_INFO_1002 = extern struct { rp1002_guardtime: u32, }; pub const REPL_INFO_1003 = extern struct { rp1003_random: u32, }; pub const REPL_EDIR_INFO_0 = extern struct { rped0_dirname: ?PWSTR, }; pub const REPL_EDIR_INFO_1 = extern struct { rped1_dirname: ?PWSTR, rped1_integrity: u32, rped1_extent: u32, }; pub const REPL_EDIR_INFO_2 = extern struct { rped2_dirname: ?PWSTR, rped2_integrity: u32, rped2_extent: u32, rped2_lockcount: u32, rped2_locktime: u32, }; pub const REPL_EDIR_INFO_1000 = extern struct { rped1000_integrity: u32, }; pub const REPL_EDIR_INFO_1001 = extern struct { rped1001_extent: u32, }; pub const REPL_IDIR_INFO_0 = extern struct { rpid0_dirname: ?PWSTR, }; pub const REPL_IDIR_INFO_1 = extern struct { rpid1_dirname: ?PWSTR, rpid1_state: u32, rpid1_mastername: ?PWSTR, rpid1_last_update_time: u32, rpid1_lockcount: u32, rpid1_locktime: u32, }; pub const SERVER_INFO_100 = extern struct { sv100_platform_id: u32, sv100_name: ?PWSTR, }; pub const SERVER_INFO_101 = extern struct { sv101_platform_id: u32, sv101_name: ?PWSTR, sv101_version_major: u32, sv101_version_minor: u32, sv101_type: NET_SERVER_TYPE, sv101_comment: ?PWSTR, }; pub const SERVER_INFO_102 = extern struct { sv102_platform_id: u32, sv102_name: ?PWSTR, sv102_version_major: u32, sv102_version_minor: u32, sv102_type: NET_SERVER_TYPE, sv102_comment: ?PWSTR, sv102_users: u32, sv102_disc: i32, sv102_hidden: SERVER_INFO_HIDDEN, sv102_announce: u32, sv102_anndelta: u32, sv102_licenses: u32, sv102_userpath: ?PWSTR, }; pub const SERVER_INFO_103 = extern struct { sv103_platform_id: u32, sv103_name: ?PWSTR, sv103_version_major: u32, sv103_version_minor: u32, sv103_type: u32, sv103_comment: ?PWSTR, sv103_users: u32, sv103_disc: i32, sv103_hidden: BOOL, sv103_announce: u32, sv103_anndelta: u32, sv103_licenses: u32, sv103_userpath: ?PWSTR, sv103_capabilities: u32, }; pub const SERVER_INFO_402 = extern struct { sv402_ulist_mtime: u32, sv402_glist_mtime: u32, sv402_alist_mtime: u32, sv402_alerts: ?PWSTR, sv402_security: SERVER_INFO_SECURITY, sv402_numadmin: u32, sv402_lanmask: u32, sv402_guestacct: ?PWSTR, sv402_chdevs: u32, sv402_chdevq: u32, sv402_chdevjobs: u32, sv402_connections: u32, sv402_shares: u32, sv402_openfiles: u32, sv402_sessopens: u32, sv402_sessvcs: u32, sv402_sessreqs: u32, sv402_opensearch: u32, sv402_activelocks: u32, sv402_numreqbuf: u32, sv402_sizreqbuf: u32, sv402_numbigbuf: u32, sv402_numfiletasks: u32, sv402_alertsched: u32, sv402_erroralert: u32, sv402_logonalert: u32, sv402_accessalert: u32, sv402_diskalert: u32, sv402_netioalert: u32, sv402_maxauditsz: u32, sv402_srvheuristics: ?PWSTR, }; pub const SERVER_INFO_403 = extern struct { sv403_ulist_mtime: u32, sv403_glist_mtime: u32, sv403_alist_mtime: u32, sv403_alerts: ?PWSTR, sv403_security: SERVER_INFO_SECURITY, sv403_numadmin: u32, sv403_lanmask: u32, sv403_guestacct: ?PWSTR, sv403_chdevs: u32, sv403_chdevq: u32, sv403_chdevjobs: u32, sv403_connections: u32, sv403_shares: u32, sv403_openfiles: u32, sv403_sessopens: u32, sv403_sessvcs: u32, sv403_sessreqs: u32, sv403_opensearch: u32, sv403_activelocks: u32, sv403_numreqbuf: u32, sv403_sizreqbuf: u32, sv403_numbigbuf: u32, sv403_numfiletasks: u32, sv403_alertsched: u32, sv403_erroralert: u32, sv403_logonalert: u32, sv403_accessalert: u32, sv403_diskalert: u32, sv403_netioalert: u32, sv403_maxauditsz: u32, sv403_srvheuristics: ?PWSTR, sv403_auditedevents: u32, sv403_autoprofile: u32, sv403_autopath: ?PWSTR, }; pub const SERVER_INFO_502 = extern struct { sv502_sessopens: u32, sv502_sessvcs: u32, sv502_opensearch: u32, sv502_sizreqbuf: u32, sv502_initworkitems: u32, sv502_maxworkitems: u32, sv502_rawworkitems: u32, sv502_irpstacksize: u32, sv502_maxrawbuflen: u32, sv502_sessusers: u32, sv502_sessconns: u32, sv502_maxpagedmemoryusage: u32, sv502_maxnonpagedmemoryusage: u32, sv502_enablesoftcompat: BOOL, sv502_enableforcedlogoff: BOOL, sv502_timesource: BOOL, sv502_acceptdownlevelapis: BOOL, sv502_lmannounce: BOOL, }; pub const SERVER_INFO_503 = extern struct { sv503_sessopens: u32, sv503_sessvcs: u32, sv503_opensearch: u32, sv503_sizreqbuf: u32, sv503_initworkitems: u32, sv503_maxworkitems: u32, sv503_rawworkitems: u32, sv503_irpstacksize: u32, sv503_maxrawbuflen: u32, sv503_sessusers: u32, sv503_sessconns: u32, sv503_maxpagedmemoryusage: u32, sv503_maxnonpagedmemoryusage: u32, sv503_enablesoftcompat: BOOL, sv503_enableforcedlogoff: BOOL, sv503_timesource: BOOL, sv503_acceptdownlevelapis: BOOL, sv503_lmannounce: BOOL, sv503_domain: ?PWSTR, sv503_maxcopyreadlen: u32, sv503_maxcopywritelen: u32, sv503_minkeepsearch: u32, sv503_maxkeepsearch: u32, sv503_minkeepcomplsearch: u32, sv503_maxkeepcomplsearch: u32, sv503_threadcountadd: u32, sv503_numblockthreads: u32, sv503_scavtimeout: u32, sv503_minrcvqueue: u32, sv503_minfreeworkitems: u32, sv503_xactmemsize: u32, sv503_threadpriority: u32, sv503_maxmpxct: u32, sv503_oplockbreakwait: u32, sv503_oplockbreakresponsewait: u32, sv503_enableoplocks: BOOL, sv503_enableoplockforceclose: BOOL, sv503_enablefcbopens: BOOL, sv503_enableraw: BOOL, sv503_enablesharednetdrives: BOOL, sv503_minfreeconnections: u32, sv503_maxfreeconnections: u32, }; pub const SERVER_INFO_599 = extern struct { sv599_sessopens: u32, sv599_sessvcs: u32, sv599_opensearch: u32, sv599_sizreqbuf: u32, sv599_initworkitems: u32, sv599_maxworkitems: u32, sv599_rawworkitems: u32, sv599_irpstacksize: u32, sv599_maxrawbuflen: u32, sv599_sessusers: u32, sv599_sessconns: u32, sv599_maxpagedmemoryusage: u32, sv599_maxnonpagedmemoryusage: u32, sv599_enablesoftcompat: BOOL, sv599_enableforcedlogoff: BOOL, sv599_timesource: BOOL, sv599_acceptdownlevelapis: BOOL, sv599_lmannounce: BOOL, sv599_domain: ?PWSTR, sv599_maxcopyreadlen: u32, sv599_maxcopywritelen: u32, sv599_minkeepsearch: u32, sv599_maxkeepsearch: u32, sv599_minkeepcomplsearch: u32, sv599_maxkeepcomplsearch: u32, sv599_threadcountadd: u32, sv599_numblockthreads: u32, sv599_scavtimeout: u32, sv599_minrcvqueue: u32, sv599_minfreeworkitems: u32, sv599_xactmemsize: u32, sv599_threadpriority: u32, sv599_maxmpxct: u32, sv599_oplockbreakwait: u32, sv599_oplockbreakresponsewait: u32, sv599_enableoplocks: BOOL, sv599_enableoplockforceclose: BOOL, sv599_enablefcbopens: BOOL, sv599_enableraw: BOOL, sv599_enablesharednetdrives: BOOL, sv599_minfreeconnections: u32, sv599_maxfreeconnections: u32, sv599_initsesstable: u32, sv599_initconntable: u32, sv599_initfiletable: u32, sv599_initsearchtable: u32, sv599_alertschedule: u32, sv599_errorthreshold: u32, sv599_networkerrorthreshold: u32, sv599_diskspacethreshold: u32, sv599_reserved: u32, sv599_maxlinkdelay: u32, sv599_minlinkthroughput: u32, sv599_linkinfovalidtime: u32, sv599_scavqosinfoupdatetime: u32, sv599_maxworkitemidletime: u32, }; pub const SERVER_INFO_598 = extern struct { sv598_maxrawworkitems: u32, sv598_maxthreadsperqueue: u32, sv598_producttype: u32, sv598_serversize: u32, sv598_connectionlessautodisc: u32, sv598_sharingviolationretries: u32, sv598_sharingviolationdelay: u32, sv598_maxglobalopensearch: u32, sv598_removeduplicatesearches: u32, sv598_lockviolationoffset: u32, sv598_lockviolationdelay: u32, sv598_mdlreadswitchover: u32, sv598_cachedopenlimit: u32, sv598_otherqueueaffinity: u32, sv598_restrictnullsessaccess: BOOL, sv598_enablewfw311directipx: BOOL, sv598_queuesamplesecs: u32, sv598_balancecount: u32, sv598_preferredaffinity: u32, sv598_maxfreerfcbs: u32, sv598_maxfreemfcbs: u32, sv598_maxfreelfcbs: u32, sv598_maxfreepagedpoolchunks: u32, sv598_minpagedpoolchunksize: u32, sv598_maxpagedpoolchunksize: u32, sv598_sendsfrompreferredprocessor: BOOL, sv598_cacheddirectorylimit: u32, sv598_maxcopylength: u32, sv598_enablecompression: BOOL, sv598_autosharewks: BOOL, sv598_autoshareserver: BOOL, sv598_enablesecuritysignature: BOOL, sv598_requiresecuritysignature: BOOL, sv598_minclientbuffersize: u32, sv598_serverguid: Guid, sv598_ConnectionNoSessionsTimeout: u32, sv598_IdleThreadTimeOut: u32, sv598_enableW9xsecuritysignature: BOOL, sv598_enforcekerberosreauthentication: BOOL, sv598_disabledos: BOOL, sv598_lowdiskspaceminimum: u32, sv598_disablestrictnamechecking: BOOL, sv598_enableauthenticateusersharing: BOOL, }; pub const SERVER_INFO_1005 = extern struct { sv1005_comment: ?PWSTR, }; pub const SERVER_INFO_1107 = extern struct { sv1107_users: u32, }; pub const SERVER_INFO_1010 = extern struct { sv1010_disc: i32, }; pub const SERVER_INFO_1016 = extern struct { sv1016_hidden: SERVER_INFO_HIDDEN, }; pub const SERVER_INFO_1017 = extern struct { sv1017_announce: u32, }; pub const SERVER_INFO_1018 = extern struct { sv1018_anndelta: u32, }; pub const SERVER_INFO_1501 = extern struct { sv1501_sessopens: u32, }; pub const SERVER_INFO_1502 = extern struct { sv1502_sessvcs: u32, }; pub const SERVER_INFO_1503 = extern struct { sv1503_opensearch: u32, }; pub const SERVER_INFO_1506 = extern struct { sv1506_maxworkitems: u32, }; pub const SERVER_INFO_1509 = extern struct { sv1509_maxrawbuflen: u32, }; pub const SERVER_INFO_1510 = extern struct { sv1510_sessusers: u32, }; pub const SERVER_INFO_1511 = extern struct { sv1511_sessconns: u32, }; pub const SERVER_INFO_1512 = extern struct { sv1512_maxnonpagedmemoryusage: u32, }; pub const SERVER_INFO_1513 = extern struct { sv1513_maxpagedmemoryusage: u32, }; pub const SERVER_INFO_1514 = extern struct { sv1514_enablesoftcompat: BOOL, }; pub const SERVER_INFO_1515 = extern struct { sv1515_enableforcedlogoff: BOOL, }; pub const SERVER_INFO_1516 = extern struct { sv1516_timesource: BOOL, }; pub const SERVER_INFO_1518 = extern struct { sv1518_lmannounce: BOOL, }; pub const SERVER_INFO_1520 = extern struct { sv1520_maxcopyreadlen: u32, }; pub const SERVER_INFO_1521 = extern struct { sv1521_maxcopywritelen: u32, }; pub const SERVER_INFO_1522 = extern struct { sv1522_minkeepsearch: u32, }; pub const SERVER_INFO_1523 = extern struct { sv1523_maxkeepsearch: u32, }; pub const SERVER_INFO_1524 = extern struct { sv1524_minkeepcomplsearch: u32, }; pub const SERVER_INFO_1525 = extern struct { sv1525_maxkeepcomplsearch: u32, }; pub const SERVER_INFO_1528 = extern struct { sv1528_scavtimeout: u32, }; pub const SERVER_INFO_1529 = extern struct { sv1529_minrcvqueue: u32, }; pub const SERVER_INFO_1530 = extern struct { sv1530_minfreeworkitems: u32, }; pub const SERVER_INFO_1533 = extern struct { sv1533_maxmpxct: u32, }; pub const SERVER_INFO_1534 = extern struct { sv1534_oplockbreakwait: u32, }; pub const SERVER_INFO_1535 = extern struct { sv1535_oplockbreakresponsewait: u32, }; pub const SERVER_INFO_1536 = extern struct { sv1536_enableoplocks: BOOL, }; pub const SERVER_INFO_1537 = extern struct { sv1537_enableoplockforceclose: BOOL, }; pub const SERVER_INFO_1538 = extern struct { sv1538_enablefcbopens: BOOL, }; pub const SERVER_INFO_1539 = extern struct { sv1539_enableraw: BOOL, }; pub const SERVER_INFO_1540 = extern struct { sv1540_enablesharednetdrives: BOOL, }; pub const SERVER_INFO_1541 = extern struct { sv1541_minfreeconnections: BOOL, }; pub const SERVER_INFO_1542 = extern struct { sv1542_maxfreeconnections: BOOL, }; pub const SERVER_INFO_1543 = extern struct { sv1543_initsesstable: u32, }; pub const SERVER_INFO_1544 = extern struct { sv1544_initconntable: u32, }; pub const SERVER_INFO_1545 = extern struct { sv1545_initfiletable: u32, }; pub const SERVER_INFO_1546 = extern struct { sv1546_initsearchtable: u32, }; pub const SERVER_INFO_1547 = extern struct { sv1547_alertschedule: u32, }; pub const SERVER_INFO_1548 = extern struct { sv1548_errorthreshold: u32, }; pub const SERVER_INFO_1549 = extern struct { sv1549_networkerrorthreshold: u32, }; pub const SERVER_INFO_1550 = extern struct { sv1550_diskspacethreshold: u32, }; pub const SERVER_INFO_1552 = extern struct { sv1552_maxlinkdelay: u32, }; pub const SERVER_INFO_1553 = extern struct { sv1553_minlinkthroughput: u32, }; pub const SERVER_INFO_1554 = extern struct { sv1554_linkinfovalidtime: u32, }; pub const SERVER_INFO_1555 = extern struct { sv1555_scavqosinfoupdatetime: u32, }; pub const SERVER_INFO_1556 = extern struct { sv1556_maxworkitemidletime: u32, }; pub const SERVER_INFO_1557 = extern struct { sv1557_maxrawworkitems: u32, }; pub const SERVER_INFO_1560 = extern struct { sv1560_producttype: u32, }; pub const SERVER_INFO_1561 = extern struct { sv1561_serversize: u32, }; pub const SERVER_INFO_1562 = extern struct { sv1562_connectionlessautodisc: u32, }; pub const SERVER_INFO_1563 = extern struct { sv1563_sharingviolationretries: u32, }; pub const SERVER_INFO_1564 = extern struct { sv1564_sharingviolationdelay: u32, }; pub const SERVER_INFO_1565 = extern struct { sv1565_maxglobalopensearch: u32, }; pub const SERVER_INFO_1566 = extern struct { sv1566_removeduplicatesearches: BOOL, }; pub const SERVER_INFO_1567 = extern struct { sv1567_lockviolationretries: u32, }; pub const SERVER_INFO_1568 = extern struct { sv1568_lockviolationoffset: u32, }; pub const SERVER_INFO_1569 = extern struct { sv1569_lockviolationdelay: u32, }; pub const SERVER_INFO_1570 = extern struct { sv1570_mdlreadswitchover: u32, }; pub const SERVER_INFO_1571 = extern struct { sv1571_cachedopenlimit: u32, }; pub const SERVER_INFO_1572 = extern struct { sv1572_criticalthreads: u32, }; pub const SERVER_INFO_1573 = extern struct { sv1573_restrictnullsessaccess: u32, }; pub const SERVER_INFO_1574 = extern struct { sv1574_enablewfw311directipx: u32, }; pub const SERVER_INFO_1575 = extern struct { sv1575_otherqueueaffinity: u32, }; pub const SERVER_INFO_1576 = extern struct { sv1576_queuesamplesecs: u32, }; pub const SERVER_INFO_1577 = extern struct { sv1577_balancecount: u32, }; pub const SERVER_INFO_1578 = extern struct { sv1578_preferredaffinity: u32, }; pub const SERVER_INFO_1579 = extern struct { sv1579_maxfreerfcbs: u32, }; pub const SERVER_INFO_1580 = extern struct { sv1580_maxfreemfcbs: u32, }; pub const SERVER_INFO_1581 = extern struct { sv1581_maxfreemlcbs: u32, }; pub const SERVER_INFO_1582 = extern struct { sv1582_maxfreepagedpoolchunks: u32, }; pub const SERVER_INFO_1583 = extern struct { sv1583_minpagedpoolchunksize: u32, }; pub const SERVER_INFO_1584 = extern struct { sv1584_maxpagedpoolchunksize: u32, }; pub const SERVER_INFO_1585 = extern struct { sv1585_sendsfrompreferredprocessor: BOOL, }; pub const SERVER_INFO_1586 = extern struct { sv1586_maxthreadsperqueue: u32, }; pub const SERVER_INFO_1587 = extern struct { sv1587_cacheddirectorylimit: u32, }; pub const SERVER_INFO_1588 = extern struct { sv1588_maxcopylength: u32, }; pub const SERVER_INFO_1590 = extern struct { sv1590_enablecompression: u32, }; pub const SERVER_INFO_1591 = extern struct { sv1591_autosharewks: u32, }; pub const SERVER_INFO_1592 = extern struct { sv1592_autosharewks: u32, }; pub const SERVER_INFO_1593 = extern struct { sv1593_enablesecuritysignature: u32, }; pub const SERVER_INFO_1594 = extern struct { sv1594_requiresecuritysignature: u32, }; pub const SERVER_INFO_1595 = extern struct { sv1595_minclientbuffersize: u32, }; pub const SERVER_INFO_1596 = extern struct { sv1596_ConnectionNoSessionsTimeout: u32, }; pub const SERVER_INFO_1597 = extern struct { sv1597_IdleThreadTimeOut: u32, }; pub const SERVER_INFO_1598 = extern struct { sv1598_enableW9xsecuritysignature: u32, }; pub const SERVER_INFO_1599 = extern struct { sv1598_enforcekerberosreauthentication: BOOLEAN, }; pub const SERVER_INFO_1600 = extern struct { sv1598_disabledos: BOOLEAN, }; pub const SERVER_INFO_1601 = extern struct { sv1598_lowdiskspaceminimum: u32, }; pub const SERVER_INFO_1602 = extern struct { sv_1598_disablestrictnamechecking: BOOL, }; pub const SERVER_TRANSPORT_INFO_0 = extern struct { svti0_numberofvcs: u32, svti0_transportname: ?PWSTR, svti0_transportaddress: ?*u8, svti0_transportaddresslength: u32, svti0_networkaddress: ?PWSTR, }; pub const SERVER_TRANSPORT_INFO_1 = extern struct { svti1_numberofvcs: u32, svti1_transportname: ?PWSTR, svti1_transportaddress: ?*u8, svti1_transportaddresslength: u32, svti1_networkaddress: ?PWSTR, svti1_domain: ?PWSTR, }; pub const SERVER_TRANSPORT_INFO_2 = extern struct { svti2_numberofvcs: u32, svti2_transportname: ?PWSTR, svti2_transportaddress: ?*u8, svti2_transportaddresslength: u32, svti2_networkaddress: ?PWSTR, svti2_domain: ?PWSTR, svti2_flags: u32, }; pub const SERVER_TRANSPORT_INFO_3 = extern struct { svti3_numberofvcs: u32, svti3_transportname: ?PWSTR, svti3_transportaddress: ?*u8, svti3_transportaddresslength: u32, svti3_networkaddress: ?PWSTR, svti3_domain: ?PWSTR, svti3_flags: u32, svti3_passwordlength: u32, svti3_password: [<PASSWORD>, }; pub const SERVICE_INFO_0 = extern struct { svci0_name: ?PWSTR, }; pub const SERVICE_INFO_1 = extern struct { svci1_name: ?PWSTR, svci1_status: u32, svci1_code: u32, svci1_pid: u32, }; pub const SERVICE_INFO_2 = extern struct { svci2_name: ?PWSTR, svci2_status: u32, svci2_code: u32, svci2_pid: u32, svci2_text: ?PWSTR, svci2_specific_error: u32, svci2_display_name: ?PWSTR, }; pub const USE_INFO_0 = extern struct { ui0_local: ?PWSTR, ui0_remote: ?PWSTR, }; pub const USE_INFO_1 = extern struct { ui1_local: ?PWSTR, ui1_remote: ?PWSTR, ui1_password: ?PWSTR, ui1_status: u32, ui1_asg_type: USE_INFO_ASG_TYPE, ui1_refcount: u32, ui1_usecount: u32, }; pub const USE_INFO_2 = extern struct { ui2_local: ?PWSTR, ui2_remote: ?PWSTR, ui2_password: ?PWSTR, ui2_status: u32, ui2_asg_type: USE_INFO_ASG_TYPE, ui2_refcount: u32, ui2_usecount: u32, ui2_username: ?PWSTR, ui2_domainname: ?PWSTR, }; pub const USE_INFO_3 = extern struct { ui3_ui2: USE_INFO_2, ui3_flags: u32, }; pub const USE_INFO_4 = extern struct { ui4_ui3: USE_INFO_3, ui4_auth_identity_length: u32, ui4_auth_identity: ?*u8, }; pub const USE_INFO_5 = extern struct { ui4_ui3: USE_INFO_3, ui4_auth_identity_length: u32, ui4_auth_identity: ?*u8, ui5_security_descriptor_length: u32, ui5_security_descriptor: ?*u8, ui5_use_options_length: u32, ui5_use_options: ?*u8, }; pub const USE_OPTION_GENERIC = extern struct { Tag: u32, Length: u16, Reserved: u16, }; pub const USE_OPTION_DEFERRED_CONNECTION_PARAMETERS = extern struct { Tag: u32, Length: u16, Reserved: u16, }; pub const TRANSPORT_TYPE = enum(i32) { None = 0, Wsk = 1, Quic = 2, }; pub const UseTransportType_None = TRANSPORT_TYPE.None; pub const UseTransportType_Wsk = TRANSPORT_TYPE.Wsk; pub const UseTransportType_Quic = TRANSPORT_TYPE.Quic; pub const TRANSPORT_INFO = extern struct { Type: TRANSPORT_TYPE, SkipCertificateCheck: BOOLEAN, }; pub const USE_OPTION_TRANSPORT_PARAMETERS = extern struct { Tag: u32, Length: u16, Reserved: u16, }; pub const SMB_COMPRESSION_INFO = extern struct { Switch: BOOLEAN, Reserved1: u8, Reserved2: u16, Reserved3: u32, }; pub const SMB_USE_OPTION_COMPRESSION_PARAMETERS = extern struct { Tag: u32, Length: u16, Reserved: u16, }; pub const SMB_TREE_CONNECT_PARAMETERS = extern struct { EABufferOffset: u32, EABufferLen: u32, CreateOptions: u32, TreeConnectAttributes: u32, }; pub const USE_OPTION_PROPERTIES = extern struct { Tag: u32, pInfo: ?*anyopaque, Length: usize, }; pub const WKSTA_INFO_100 = extern struct { wki100_platform_id: u32, wki100_computername: ?PWSTR, wki100_langroup: ?PWSTR, wki100_ver_major: u32, wki100_ver_minor: u32, }; pub const WKSTA_INFO_101 = extern struct { wki101_platform_id: u32, wki101_computername: ?PWSTR, wki101_langroup: ?PWSTR, wki101_ver_major: u32, wki101_ver_minor: u32, wki101_lanroot: ?PWSTR, }; pub const WKSTA_INFO_102 = extern struct { wki102_platform_id: u32, wki102_computername: ?PWSTR, wki102_langroup: ?PWSTR, wki102_ver_major: u32, wki102_ver_minor: u32, wki102_lanroot: ?PWSTR, wki102_logged_on_users: u32, }; pub const WKSTA_INFO_302 = extern struct { wki302_char_wait: u32, wki302_collection_time: u32, wki302_maximum_collection_count: u32, wki302_keep_conn: u32, wki302_keep_search: u32, wki302_max_cmds: u32, wki302_num_work_buf: u32, wki302_siz_work_buf: u32, wki302_max_wrk_cache: u32, wki302_sess_timeout: u32, wki302_siz_error: u32, wki302_num_alerts: u32, wki302_num_services: u32, wki302_errlog_sz: u32, wki302_print_buf_time: u32, wki302_num_char_buf: u32, wki302_siz_char_buf: u32, wki302_wrk_heuristics: ?PWSTR, wki302_mailslots: u32, wki302_num_dgram_buf: u32, }; pub const WKSTA_INFO_402 = extern struct { wki402_char_wait: u32, wki402_collection_time: u32, wki402_maximum_collection_count: u32, wki402_keep_conn: u32, wki402_keep_search: u32, wki402_max_cmds: u32, wki402_num_work_buf: u32, wki402_siz_work_buf: u32, wki402_max_wrk_cache: u32, wki402_sess_timeout: u32, wki402_siz_error: u32, wki402_num_alerts: u32, wki402_num_services: u32, wki402_errlog_sz: u32, wki402_print_buf_time: u32, wki402_num_char_buf: u32, wki402_siz_char_buf: u32, wki402_wrk_heuristics: ?PWSTR, wki402_mailslots: u32, wki402_num_dgram_buf: u32, wki402_max_threads: u32, }; pub const WKSTA_INFO_502 = extern struct { wki502_char_wait: u32, wki502_collection_time: u32, wki502_maximum_collection_count: u32, wki502_keep_conn: u32, wki502_max_cmds: u32, wki502_sess_timeout: u32, wki502_siz_char_buf: u32, wki502_max_threads: u32, wki502_lock_quota: u32, wki502_lock_increment: u32, wki502_lock_maximum: u32, wki502_pipe_increment: u32, wki502_pipe_maximum: u32, wki502_cache_file_timeout: u32, wki502_dormant_file_limit: u32, wki502_read_ahead_throughput: u32, wki502_num_mailslot_buffers: u32, wki502_num_srv_announce_buffers: u32, wki502_max_illegal_datagram_events: u32, wki502_illegal_datagram_event_reset_frequency: u32, wki502_log_election_packets: BOOL, wki502_use_opportunistic_locking: BOOL, wki502_use_unlock_behind: BOOL, wki502_use_close_behind: BOOL, wki502_buf_named_pipes: BOOL, wki502_use_lock_read_unlock: BOOL, wki502_utilize_nt_caching: BOOL, wki502_use_raw_read: BOOL, wki502_use_raw_write: BOOL, wki502_use_write_raw_data: BOOL, wki502_use_encryption: BOOL, wki502_buf_files_deny_write: BOOL, wki502_buf_read_only_files: BOOL, wki502_force_core_create_mode: BOOL, wki502_use_512_byte_max_transfer: BOOL, }; pub const WKSTA_INFO_1010 = extern struct { wki1010_char_wait: u32, }; pub const WKSTA_INFO_1011 = extern struct { wki1011_collection_time: u32, }; pub const WKSTA_INFO_1012 = extern struct { wki1012_maximum_collection_count: u32, }; pub const WKSTA_INFO_1027 = extern struct { wki1027_errlog_sz: u32, }; pub const WKSTA_INFO_1028 = extern struct { wki1028_print_buf_time: u32, }; pub const WKSTA_INFO_1032 = extern struct { wki1032_wrk_heuristics: u32, }; pub const WKSTA_INFO_1013 = extern struct { wki1013_keep_conn: u32, }; pub const WKSTA_INFO_1018 = extern struct { wki1018_sess_timeout: u32, }; pub const WKSTA_INFO_1023 = extern struct { wki1023_siz_char_buf: u32, }; pub const WKSTA_INFO_1033 = extern struct { wki1033_max_threads: u32, }; pub const WKSTA_INFO_1041 = extern struct { wki1041_lock_quota: u32, }; pub const WKSTA_INFO_1042 = extern struct { wki1042_lock_increment: u32, }; pub const WKSTA_INFO_1043 = extern struct { wki1043_lock_maximum: u32, }; pub const WKSTA_INFO_1044 = extern struct { wki1044_pipe_increment: u32, }; pub const WKSTA_INFO_1045 = extern struct { wki1045_pipe_maximum: u32, }; pub const WKSTA_INFO_1046 = extern struct { wki1046_dormant_file_limit: u32, }; pub const WKSTA_INFO_1047 = extern struct { wki1047_cache_file_timeout: u32, }; pub const WKSTA_INFO_1048 = extern struct { wki1048_use_opportunistic_locking: BOOL, }; pub const WKSTA_INFO_1049 = extern struct { wki1049_use_unlock_behind: BOOL, }; pub const WKSTA_INFO_1050 = extern struct { wki1050_use_close_behind: BOOL, }; pub const WKSTA_INFO_1051 = extern struct { wki1051_buf_named_pipes: BOOL, }; pub const WKSTA_INFO_1052 = extern struct { wki1052_use_lock_read_unlock: BOOL, }; pub const WKSTA_INFO_1053 = extern struct { wki1053_utilize_nt_caching: BOOL, }; pub const WKSTA_INFO_1054 = extern struct { wki1054_use_raw_read: BOOL, }; pub const WKSTA_INFO_1055 = extern struct { wki1055_use_raw_write: BOOL, }; pub const WKSTA_INFO_1056 = extern struct { wki1056_use_write_raw_data: BOOL, }; pub const WKSTA_INFO_1057 = extern struct { wki1057_use_encryption: BOOL, }; pub const WKSTA_INFO_1058 = extern struct { wki1058_buf_files_deny_write: BOOL, }; pub const WKSTA_INFO_1059 = extern struct { wki1059_buf_read_only_files: BOOL, }; pub const WKSTA_INFO_1060 = extern struct { wki1060_force_core_create_mode: BOOL, }; pub const WKSTA_INFO_1061 = extern struct { wki1061_use_512_byte_max_transfer: BOOL, }; pub const WKSTA_INFO_1062 = extern struct { wki1062_read_ahead_throughput: u32, }; pub const WKSTA_USER_INFO_0 = extern struct { wkui0_username: ?PWSTR, }; pub const WKSTA_USER_INFO_1 = extern struct { wkui1_username: ?PWSTR, wkui1_logon_domain: ?PWSTR, wkui1_oth_domains: ?PWSTR, wkui1_logon_server: ?PWSTR, }; pub const WKSTA_USER_INFO_1101 = extern struct { wkui1101_oth_domains: ?PWSTR, }; pub const WKSTA_TRANSPORT_INFO_0 = extern struct { wkti0_quality_of_service: u32, wkti0_number_of_vcs: u32, wkti0_transport_name: ?PWSTR, wkti0_transport_address: ?PWSTR, wkti0_wan_ish: BOOL, }; pub const ERROR_LOG = extern struct { el_len: u32, el_reserved: u32, el_time: u32, el_error: u32, el_name: ?PWSTR, el_text: ?PWSTR, el_data: ?*u8, el_data_size: u32, el_nstrings: u32, }; pub const HLOG = extern struct { time: u32, last_flags: u32, offset: u32, rec_offset: u32, }; pub const CONFIG_INFO_0 = extern struct { cfgi0_key: ?PWSTR, cfgi0_data: ?PWSTR, }; pub const AUDIT_ENTRY = extern struct { ae_len: u32, ae_reserved: u32, ae_time: u32, ae_type: u32, ae_data_offset: u32, ae_data_size: u32, }; // WARNING: this type symbol conflicts with a const! pub const AE_SRVSTATUS_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_SESSLOGON_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_SESSLOGOFF_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_SESSPWERR_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_CONNSTART_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_CONNSTOP_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_CONNREJ_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_RESACCESS_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_RESACCESSREJ_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_CLOSEFILE_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_SERVICESTAT_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_ACLMOD_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_UASMOD_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_NETLOGON_CONFLICT_ = usize; // WARNING: this type symbol conflicts with a const! pub const AE_NETLOGOFF_CONFLICT_ = usize; pub const AE_ACCLIM = extern struct { ae_al_compname: u32, ae_al_username: u32, ae_al_resname: u32, ae_al_limit: u32, }; // WARNING: this type symbol conflicts with a const! pub const AE_LOCKOUT_CONFLICT_ = usize; pub const AE_GENERIC = extern struct { ae_ge_msgfile: u32, ae_ge_msgnum: u32, ae_ge_params: u32, ae_ge_param1: u32, ae_ge_param2: u32, ae_ge_param3: u32, ae_ge_param4: u32, ae_ge_param5: u32, ae_ge_param6: u32, ae_ge_param7: u32, ae_ge_param8: u32, ae_ge_param9: u32, }; pub const NETSETUP_NAME_TYPE = enum(i32) { Unknown = 0, Machine = 1, Workgroup = 2, Domain = 3, NonExistentDomain = 4, DnsMachine = 5, }; pub const NetSetupUnknown = NETSETUP_NAME_TYPE.Unknown; pub const NetSetupMachine = NETSETUP_NAME_TYPE.Machine; pub const NetSetupWorkgroup = NETSETUP_NAME_TYPE.Workgroup; pub const NetSetupDomain = NETSETUP_NAME_TYPE.Domain; pub const NetSetupNonExistentDomain = NETSETUP_NAME_TYPE.NonExistentDomain; pub const NetSetupDnsMachine = NETSETUP_NAME_TYPE.DnsMachine; pub const DSREG_JOIN_TYPE = enum(i32) { UNKNOWN_JOIN = 0, DEVICE_JOIN = 1, WORKPLACE_JOIN = 2, }; pub const DSREG_UNKNOWN_JOIN = DSREG_JOIN_TYPE.UNKNOWN_JOIN; pub const DSREG_DEVICE_JOIN = DSREG_JOIN_TYPE.DEVICE_JOIN; pub const DSREG_WORKPLACE_JOIN = DSREG_JOIN_TYPE.WORKPLACE_JOIN; pub const DSREG_USER_INFO = extern struct { pszUserEmail: ?PWSTR, pszUserKeyId: ?PWSTR, pszUserKeyName: ?PWSTR, }; pub const DSREG_JOIN_INFO = extern struct { joinType: DSREG_JOIN_TYPE, pJoinCertificate: ?*const CERT_CONTEXT, pszDeviceId: ?PWSTR, pszIdpDomain: ?PWSTR, pszTenantId: ?PWSTR, pszJoinUserEmail: ?PWSTR, pszTenantDisplayName: ?PWSTR, pszMdmEnrollmentUrl: ?PWSTR, pszMdmTermsOfUseUrl: ?PWSTR, pszMdmComplianceUrl: ?PWSTR, pszUserSettingSyncUrl: ?PWSTR, pUserInfo: ?*DSREG_USER_INFO, }; pub const NET_COMPUTER_NAME_TYPE = enum(i32) { PrimaryComputerName = 0, AlternateComputerNames = 1, AllComputerNames = 2, ComputerNameTypeMax = 3, }; pub const NetPrimaryComputerName = NET_COMPUTER_NAME_TYPE.PrimaryComputerName; pub const NetAlternateComputerNames = NET_COMPUTER_NAME_TYPE.AlternateComputerNames; pub const NetAllComputerNames = NET_COMPUTER_NAME_TYPE.AllComputerNames; pub const NetComputerNameTypeMax = NET_COMPUTER_NAME_TYPE.ComputerNameTypeMax; pub const NETSETUP_PROVISIONING_PARAMS = extern struct { dwVersion: u32, lpDomain: ?[*:0]const u16, lpHostName: ?[*:0]const u16, lpMachineAccountOU: ?[*:0]const u16, lpDcName: ?[*:0]const u16, dwProvisionOptions: NETSETUP_PROVISION, aCertTemplateNames: ?*?PWSTR, cCertTemplateNames: u32, aMachinePolicyNames: ?*?PWSTR, cMachinePolicyNames: u32, aMachinePolicyPaths: ?*?PWSTR, cMachinePolicyPaths: u32, lpNetbiosName: ?PWSTR, lpSiteName: ?PWSTR, lpPrimaryDNSDomain: ?PWSTR, }; pub const NETSETUP_JOIN_STATUS = enum(i32) { UnknownStatus = 0, Unjoined = 1, WorkgroupName = 2, DomainName = 3, }; pub const NetSetupUnknownStatus = NETSETUP_JOIN_STATUS.UnknownStatus; pub const NetSetupUnjoined = NETSETUP_JOIN_STATUS.Unjoined; pub const NetSetupWorkgroupName = NETSETUP_JOIN_STATUS.WorkgroupName; pub const NetSetupDomainName = NETSETUP_JOIN_STATUS.DomainName; pub const AT_INFO = extern struct { JobTime: usize, DaysOfMonth: u32, DaysOfWeek: u8, Flags: u8, Command: ?PWSTR, }; pub const AT_ENUM = extern struct { JobId: u32, JobTime: usize, DaysOfMonth: u32, DaysOfWeek: u8, Flags: u8, Command: ?PWSTR, }; pub const FLAT_STRING = extern struct { MaximumLength: i16, Length: i16, Buffer: [1]CHAR, }; pub const NETWORK_NAME = extern struct { Name: FLAT_STRING, }; pub const HARDWARE_ADDRESS = extern struct { Address: [6]u8, }; const IID_IEnumNetCfgBindingInterface_Value = @import("../zig.zig").Guid.initString("c0e8ae90-306e-11d1-aacf-00805fc1270e"); pub const IID_IEnumNetCfgBindingInterface = &IID_IEnumNetCfgBindingInterface_Value; pub const IEnumNetCfgBindingInterface = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumNetCfgBindingInterface, celt: u32, rgelt: [*]?*INetCfgBindingInterface, pceltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumNetCfgBindingInterface, celt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumNetCfgBindingInterface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumNetCfgBindingInterface, ppenum: ?*?*IEnumNetCfgBindingInterface, ) 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 IEnumNetCfgBindingInterface_Next(self: *const T, celt: u32, rgelt: [*]?*INetCfgBindingInterface, pceltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingInterface.VTable, self.vtable).Next(@ptrCast(*const IEnumNetCfgBindingInterface, self), celt, rgelt, pceltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgBindingInterface_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingInterface.VTable, self.vtable).Skip(@ptrCast(*const IEnumNetCfgBindingInterface, self), celt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgBindingInterface_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingInterface.VTable, self.vtable).Reset(@ptrCast(*const IEnumNetCfgBindingInterface, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgBindingInterface_Clone(self: *const T, ppenum: ?*?*IEnumNetCfgBindingInterface) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingInterface.VTable, self.vtable).Clone(@ptrCast(*const IEnumNetCfgBindingInterface, self), ppenum); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IEnumNetCfgBindingPath_Value = @import("../zig.zig").Guid.initString("c0e8ae91-306e-11d1-aacf-00805fc1270e"); pub const IID_IEnumNetCfgBindingPath = &IID_IEnumNetCfgBindingPath_Value; pub const IEnumNetCfgBindingPath = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumNetCfgBindingPath, celt: u32, rgelt: [*]?*INetCfgBindingPath, pceltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumNetCfgBindingPath, celt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumNetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumNetCfgBindingPath, ppenum: ?*?*IEnumNetCfgBindingPath, ) 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 IEnumNetCfgBindingPath_Next(self: *const T, celt: u32, rgelt: [*]?*INetCfgBindingPath, pceltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingPath.VTable, self.vtable).Next(@ptrCast(*const IEnumNetCfgBindingPath, self), celt, rgelt, pceltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgBindingPath_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingPath.VTable, self.vtable).Skip(@ptrCast(*const IEnumNetCfgBindingPath, self), celt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgBindingPath_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingPath.VTable, self.vtable).Reset(@ptrCast(*const IEnumNetCfgBindingPath, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgBindingPath_Clone(self: *const T, ppenum: ?*?*IEnumNetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgBindingPath.VTable, self.vtable).Clone(@ptrCast(*const IEnumNetCfgBindingPath, self), ppenum); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IEnumNetCfgComponent_Value = @import("../zig.zig").Guid.initString("c0e8ae92-306e-11d1-aacf-00805fc1270e"); pub const IID_IEnumNetCfgComponent = &IID_IEnumNetCfgComponent_Value; pub const IEnumNetCfgComponent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumNetCfgComponent, celt: u32, rgelt: [*]?*INetCfgComponent, pceltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumNetCfgComponent, celt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumNetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumNetCfgComponent, ppenum: ?*?*IEnumNetCfgComponent, ) 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 IEnumNetCfgComponent_Next(self: *const T, celt: u32, rgelt: [*]?*INetCfgComponent, pceltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgComponent.VTable, self.vtable).Next(@ptrCast(*const IEnumNetCfgComponent, self), celt, rgelt, pceltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgComponent_Skip(self: *const T, celt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgComponent.VTable, self.vtable).Skip(@ptrCast(*const IEnumNetCfgComponent, self), celt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgComponent_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgComponent.VTable, self.vtable).Reset(@ptrCast(*const IEnumNetCfgComponent, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumNetCfgComponent_Clone(self: *const T, ppenum: ?*?*IEnumNetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumNetCfgComponent.VTable, self.vtable).Clone(@ptrCast(*const IEnumNetCfgComponent, self), ppenum); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfg_Value = @import("../zig.zig").Guid.initString("c0e8ae93-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfg = &IID_INetCfg_Value; pub const INetCfg = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const INetCfg, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Uninitialize: fn( self: *const INetCfg, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Apply: fn( self: *const INetCfg, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Cancel: fn( self: *const INetCfg, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumComponents: fn( self: *const INetCfg, pguidClass: ?*const Guid, ppenumComponent: ?*?*IEnumNetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FindComponent: fn( self: *const INetCfg, pszwInfId: ?[*:0]const u16, pComponent: ?*?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryNetCfgClass: fn( self: *const INetCfg, pguidClass: ?*const Guid, riid: ?*const Guid, ppvObject: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_Initialize(self: *const T, pvReserved: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).Initialize(@ptrCast(*const INetCfg, self), pvReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_Uninitialize(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).Uninitialize(@ptrCast(*const INetCfg, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_Apply(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).Apply(@ptrCast(*const INetCfg, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).Cancel(@ptrCast(*const INetCfg, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_EnumComponents(self: *const T, pguidClass: ?*const Guid, ppenumComponent: ?*?*IEnumNetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).EnumComponents(@ptrCast(*const INetCfg, self), pguidClass, ppenumComponent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_FindComponent(self: *const T, pszwInfId: ?[*:0]const u16, pComponent: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).FindComponent(@ptrCast(*const INetCfg, self), pszwInfId, pComponent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfg_QueryNetCfgClass(self: *const T, pguidClass: ?*const Guid, riid: ?*const Guid, ppvObject: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfg.VTable, self.vtable).QueryNetCfgClass(@ptrCast(*const INetCfg, self), pguidClass, riid, ppvObject); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgLock_Value = @import("../zig.zig").Guid.initString("c0e8ae9f-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgLock = &IID_INetCfgLock_Value; pub const INetCfgLock = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AcquireWriteLock: fn( self: *const INetCfgLock, cmsTimeout: u32, pszwClientDescription: ?[*:0]const u16, ppszwClientDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseWriteLock: fn( self: *const INetCfgLock, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsWriteLocked: fn( self: *const INetCfgLock, ppszwClientDescription: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgLock_AcquireWriteLock(self: *const T, cmsTimeout: u32, pszwClientDescription: ?[*:0]const u16, ppszwClientDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgLock.VTable, self.vtable).AcquireWriteLock(@ptrCast(*const INetCfgLock, self), cmsTimeout, pszwClientDescription, ppszwClientDescription); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgLock_ReleaseWriteLock(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgLock.VTable, self.vtable).ReleaseWriteLock(@ptrCast(*const INetCfgLock, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgLock_IsWriteLocked(self: *const T, ppszwClientDescription: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgLock.VTable, self.vtable).IsWriteLocked(@ptrCast(*const INetCfgLock, self), ppszwClientDescription); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgBindingInterface_Value = @import("../zig.zig").Guid.initString("c0e8ae94-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgBindingInterface = &IID_INetCfgBindingInterface_Value; pub const INetCfgBindingInterface = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetName: fn( self: *const INetCfgBindingInterface, ppszwInterfaceName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetUpperComponent: fn( self: *const INetCfgBindingInterface, ppnccItem: ?*?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetLowerComponent: fn( self: *const INetCfgBindingInterface, ppnccItem: ?*?*INetCfgComponent, ) 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 INetCfgBindingInterface_GetName(self: *const T, ppszwInterfaceName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingInterface.VTable, self.vtable).GetName(@ptrCast(*const INetCfgBindingInterface, self), ppszwInterfaceName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingInterface_GetUpperComponent(self: *const T, ppnccItem: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingInterface.VTable, self.vtable).GetUpperComponent(@ptrCast(*const INetCfgBindingInterface, self), ppnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingInterface_GetLowerComponent(self: *const T, ppnccItem: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingInterface.VTable, self.vtable).GetLowerComponent(@ptrCast(*const INetCfgBindingInterface, self), ppnccItem); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgBindingPath_Value = @import("../zig.zig").Guid.initString("c0e8ae96-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgBindingPath = &IID_INetCfgBindingPath_Value; pub const INetCfgBindingPath = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, IsSamePathAs: fn( self: *const INetCfgBindingPath, pPath: ?*INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsSubPathOf: fn( self: *const INetCfgBindingPath, pPath: ?*INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsEnabled: fn( self: *const INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Enable: fn( self: *const INetCfgBindingPath, fEnable: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPathToken: fn( self: *const INetCfgBindingPath, ppszwPathToken: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOwner: fn( self: *const INetCfgBindingPath, ppComponent: ?*?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDepth: fn( self: *const INetCfgBindingPath, pcInterfaces: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumBindingInterfaces: fn( self: *const INetCfgBindingPath, ppenumInterface: ?*?*IEnumNetCfgBindingInterface, ) 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 INetCfgBindingPath_IsSamePathAs(self: *const T, pPath: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).IsSamePathAs(@ptrCast(*const INetCfgBindingPath, self), pPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_IsSubPathOf(self: *const T, pPath: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).IsSubPathOf(@ptrCast(*const INetCfgBindingPath, self), pPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_IsEnabled(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).IsEnabled(@ptrCast(*const INetCfgBindingPath, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_Enable(self: *const T, fEnable: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).Enable(@ptrCast(*const INetCfgBindingPath, self), fEnable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_GetPathToken(self: *const T, ppszwPathToken: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).GetPathToken(@ptrCast(*const INetCfgBindingPath, self), ppszwPathToken); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_GetOwner(self: *const T, ppComponent: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).GetOwner(@ptrCast(*const INetCfgBindingPath, self), ppComponent); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_GetDepth(self: *const T, pcInterfaces: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).GetDepth(@ptrCast(*const INetCfgBindingPath, self), pcInterfaces); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgBindingPath_EnumBindingInterfaces(self: *const T, ppenumInterface: ?*?*IEnumNetCfgBindingInterface) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgBindingPath.VTable, self.vtable).EnumBindingInterfaces(@ptrCast(*const INetCfgBindingPath, self), ppenumInterface); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgClass_Value = @import("../zig.zig").Guid.initString("c0e8ae97-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgClass = &IID_INetCfgClass_Value; pub const INetCfgClass = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, FindComponent: fn( self: *const INetCfgClass, pszwInfId: ?[*:0]const u16, ppnccItem: ?*?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumComponents: fn( self: *const INetCfgClass, ppenumComponent: ?*?*IEnumNetCfgComponent, ) 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 INetCfgClass_FindComponent(self: *const T, pszwInfId: ?[*:0]const u16, ppnccItem: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgClass.VTable, self.vtable).FindComponent(@ptrCast(*const INetCfgClass, self), pszwInfId, ppnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgClass_EnumComponents(self: *const T, ppenumComponent: ?*?*IEnumNetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgClass.VTable, self.vtable).EnumComponents(@ptrCast(*const INetCfgClass, self), ppenumComponent); } };} pub usingnamespace MethodMixin(@This()); }; pub const OBO_TOKEN_TYPE = enum(i32) { USER = 1, COMPONENT = 2, SOFTWARE = 3, }; pub const OBO_USER = OBO_TOKEN_TYPE.USER; pub const OBO_COMPONENT = OBO_TOKEN_TYPE.COMPONENT; pub const OBO_SOFTWARE = OBO_TOKEN_TYPE.SOFTWARE; pub const OBO_TOKEN = extern struct { Type: OBO_TOKEN_TYPE, pncc: ?*INetCfgComponent, pszwManufacturer: ?[*:0]const u16, pszwProduct: ?[*:0]const u16, pszwDisplayName: ?[*:0]const u16, fRegistered: BOOL, }; const IID_INetCfgClassSetup_Value = @import("../zig.zig").Guid.initString("c0e8ae9d-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgClassSetup = &IID_INetCfgClassSetup_Value; pub const INetCfgClassSetup = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SelectAndInstall: fn( self: *const INetCfgClassSetup, hwndParent: ?HWND, pOboToken: ?*OBO_TOKEN, ppnccItem: ?*?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Install: fn( self: *const INetCfgClassSetup, pszwInfId: ?[*:0]const u16, pOboToken: ?*OBO_TOKEN, dwSetupFlags: u32, dwUpgradeFromBuildNo: u32, pszwAnswerFile: ?[*:0]const u16, pszwAnswerSections: ?[*:0]const u16, ppnccItem: ?*?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeInstall: fn( self: *const INetCfgClassSetup, pComponent: ?*INetCfgComponent, pOboToken: ?*OBO_TOKEN, pmszwRefs: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgClassSetup_SelectAndInstall(self: *const T, hwndParent: ?HWND, pOboToken: ?*OBO_TOKEN, ppnccItem: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgClassSetup.VTable, self.vtable).SelectAndInstall(@ptrCast(*const INetCfgClassSetup, self), hwndParent, pOboToken, ppnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgClassSetup_Install(self: *const T, pszwInfId: ?[*:0]const u16, pOboToken: ?*OBO_TOKEN, dwSetupFlags: u32, dwUpgradeFromBuildNo: u32, pszwAnswerFile: ?[*:0]const u16, pszwAnswerSections: ?[*:0]const u16, ppnccItem: ?*?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgClassSetup.VTable, self.vtable).Install(@ptrCast(*const INetCfgClassSetup, self), pszwInfId, pOboToken, dwSetupFlags, dwUpgradeFromBuildNo, pszwAnswerFile, pszwAnswerSections, ppnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgClassSetup_DeInstall(self: *const T, pComponent: ?*INetCfgComponent, pOboToken: ?*OBO_TOKEN, pmszwRefs: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgClassSetup.VTable, self.vtable).DeInstall(@ptrCast(*const INetCfgClassSetup, self), pComponent, pOboToken, pmszwRefs); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgClassSetup2_Value = @import("../zig.zig").Guid.initString("c0e8aea0-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgClassSetup2 = &IID_INetCfgClassSetup2_Value; pub const INetCfgClassSetup2 = extern struct { pub const VTable = extern struct { base: INetCfgClassSetup.VTable, UpdateNonEnumeratedComponent: fn( self: *const INetCfgClassSetup2, pIComp: ?*INetCfgComponent, dwSetupFlags: u32, dwUpgradeFromBuildNo: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace INetCfgClassSetup.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgClassSetup2_UpdateNonEnumeratedComponent(self: *const T, pIComp: ?*INetCfgComponent, dwSetupFlags: u32, dwUpgradeFromBuildNo: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgClassSetup2.VTable, self.vtable).UpdateNonEnumeratedComponent(@ptrCast(*const INetCfgClassSetup2, self), pIComp, dwSetupFlags, dwUpgradeFromBuildNo); } };} pub usingnamespace MethodMixin(@This()); }; pub const COMPONENT_CHARACTERISTICS = enum(i32) { VIRTUAL = 1, SOFTWARE_ENUMERATED = 2, PHYSICAL = 4, HIDDEN = 8, NO_SERVICE = 16, NOT_USER_REMOVABLE = 32, MULTIPORT_INSTANCED_ADAPTER = 64, HAS_UI = 128, SINGLE_INSTANCE = 256, FILTER = 1024, DONTEXPOSELOWER = 4096, HIDE_BINDING = 8192, NDIS_PROTOCOL = 16384, FIXED_BINDING = 131072, LW_FILTER = 262144, }; pub const NCF_VIRTUAL = COMPONENT_CHARACTERISTICS.VIRTUAL; pub const NCF_SOFTWARE_ENUMERATED = COMPONENT_CHARACTERISTICS.SOFTWARE_ENUMERATED; pub const NCF_PHYSICAL = COMPONENT_CHARACTERISTICS.PHYSICAL; pub const NCF_HIDDEN = COMPONENT_CHARACTERISTICS.HIDDEN; pub const NCF_NO_SERVICE = COMPONENT_CHARACTERISTICS.NO_SERVICE; pub const NCF_NOT_USER_REMOVABLE = COMPONENT_CHARACTERISTICS.NOT_USER_REMOVABLE; pub const NCF_MULTIPORT_INSTANCED_ADAPTER = COMPONENT_CHARACTERISTICS.MULTIPORT_INSTANCED_ADAPTER; pub const NCF_HAS_UI = COMPONENT_CHARACTERISTICS.HAS_UI; pub const NCF_SINGLE_INSTANCE = COMPONENT_CHARACTERISTICS.SINGLE_INSTANCE; pub const NCF_FILTER = COMPONENT_CHARACTERISTICS.FILTER; pub const NCF_DONTEXPOSELOWER = COMPONENT_CHARACTERISTICS.DONTEXPOSELOWER; pub const NCF_HIDE_BINDING = COMPONENT_CHARACTERISTICS.HIDE_BINDING; pub const NCF_NDIS_PROTOCOL = COMPONENT_CHARACTERISTICS.NDIS_PROTOCOL; pub const NCF_FIXED_BINDING = COMPONENT_CHARACTERISTICS.FIXED_BINDING; pub const NCF_LW_FILTER = COMPONENT_CHARACTERISTICS.LW_FILTER; pub const NCRP_FLAGS = enum(i32) { QUERY_PROPERTY_UI = 1, SHOW_PROPERTY_UI = 2, }; pub const NCRP_QUERY_PROPERTY_UI = NCRP_FLAGS.QUERY_PROPERTY_UI; pub const NCRP_SHOW_PROPERTY_UI = NCRP_FLAGS.SHOW_PROPERTY_UI; const IID_INetCfgComponent_Value = @import("../zig.zig").Guid.initString("c0e8ae99-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgComponent = &IID_INetCfgComponent_Value; pub const INetCfgComponent = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDisplayName: fn( self: *const INetCfgComponent, ppszwDisplayName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetDisplayName: fn( self: *const INetCfgComponent, pszwDisplayName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetHelpText: fn( self: *const INetCfgComponent, pszwHelpText: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetId: fn( self: *const INetCfgComponent, ppszwId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCharacteristics: fn( self: *const INetCfgComponent, pdwCharacteristics: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInstanceGuid: fn( self: *const INetCfgComponent, pGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPnpDevNodeId: fn( self: *const INetCfgComponent, ppszwDevNodeId: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetClassGuid: fn( self: *const INetCfgComponent, pGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBindName: fn( self: *const INetCfgComponent, ppszwBindName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDeviceStatus: fn( self: *const INetCfgComponent, pulStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OpenParamKey: fn( self: *const INetCfgComponent, phkey: ?*?HKEY, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RaisePropertyUi: fn( self: *const INetCfgComponent, hwndParent: ?HWND, dwFlags: u32, punkContext: ?*IUnknown, ) 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 INetCfgComponent_GetDisplayName(self: *const T, ppszwDisplayName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetDisplayName(@ptrCast(*const INetCfgComponent, self), ppszwDisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_SetDisplayName(self: *const T, pszwDisplayName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).SetDisplayName(@ptrCast(*const INetCfgComponent, self), pszwDisplayName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetHelpText(self: *const T, pszwHelpText: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetHelpText(@ptrCast(*const INetCfgComponent, self), pszwHelpText); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetId(self: *const T, ppszwId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetId(@ptrCast(*const INetCfgComponent, self), ppszwId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetCharacteristics(self: *const T, pdwCharacteristics: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetCharacteristics(@ptrCast(*const INetCfgComponent, self), pdwCharacteristics); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetInstanceGuid(self: *const T, pGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetInstanceGuid(@ptrCast(*const INetCfgComponent, self), pGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetPnpDevNodeId(self: *const T, ppszwDevNodeId: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetPnpDevNodeId(@ptrCast(*const INetCfgComponent, self), ppszwDevNodeId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetClassGuid(self: *const T, pGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetClassGuid(@ptrCast(*const INetCfgComponent, self), pGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetBindName(self: *const T, ppszwBindName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetBindName(@ptrCast(*const INetCfgComponent, self), ppszwBindName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_GetDeviceStatus(self: *const T, pulStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).GetDeviceStatus(@ptrCast(*const INetCfgComponent, self), pulStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_OpenParamKey(self: *const T, phkey: ?*?HKEY) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).OpenParamKey(@ptrCast(*const INetCfgComponent, self), phkey); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponent_RaisePropertyUi(self: *const T, hwndParent: ?HWND, dwFlags: u32, punkContext: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponent.VTable, self.vtable).RaisePropertyUi(@ptrCast(*const INetCfgComponent, self), hwndParent, dwFlags, punkContext); } };} pub usingnamespace MethodMixin(@This()); }; pub const SUPPORTS_BINDING_INTERFACE_FLAGS = enum(i32) { LOWER = 1, UPPER = 2, }; pub const NCF_LOWER = SUPPORTS_BINDING_INTERFACE_FLAGS.LOWER; pub const NCF_UPPER = SUPPORTS_BINDING_INTERFACE_FLAGS.UPPER; pub const ENUM_BINDING_PATHS_FLAGS = enum(i32) { ABOVE = 1, BELOW = 2, }; pub const EBP_ABOVE = ENUM_BINDING_PATHS_FLAGS.ABOVE; pub const EBP_BELOW = ENUM_BINDING_PATHS_FLAGS.BELOW; const IID_INetCfgComponentBindings_Value = @import("../zig.zig").Guid.initString("c0e8ae9e-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgComponentBindings = &IID_INetCfgComponentBindings_Value; pub const INetCfgComponentBindings = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, BindTo: fn( self: *const INetCfgComponentBindings, pnccItem: ?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnbindFrom: fn( self: *const INetCfgComponentBindings, pnccItem: ?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SupportsBindingInterface: fn( self: *const INetCfgComponentBindings, dwFlags: u32, pszwInterfaceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsBoundTo: fn( self: *const INetCfgComponentBindings, pnccItem: ?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsBindableTo: fn( self: *const INetCfgComponentBindings, pnccItem: ?*INetCfgComponent, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumBindingPaths: fn( self: *const INetCfgComponentBindings, dwFlags: u32, ppIEnum: ?*?*IEnumNetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MoveBefore: fn( self: *const INetCfgComponentBindings, pncbItemSrc: ?*INetCfgBindingPath, pncbItemDest: ?*INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MoveAfter: fn( self: *const INetCfgComponentBindings, pncbItemSrc: ?*INetCfgBindingPath, pncbItemDest: ?*INetCfgBindingPath, ) 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 INetCfgComponentBindings_BindTo(self: *const T, pnccItem: ?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).BindTo(@ptrCast(*const INetCfgComponentBindings, self), pnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_UnbindFrom(self: *const T, pnccItem: ?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).UnbindFrom(@ptrCast(*const INetCfgComponentBindings, self), pnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_SupportsBindingInterface(self: *const T, dwFlags: u32, pszwInterfaceName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).SupportsBindingInterface(@ptrCast(*const INetCfgComponentBindings, self), dwFlags, pszwInterfaceName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_IsBoundTo(self: *const T, pnccItem: ?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).IsBoundTo(@ptrCast(*const INetCfgComponentBindings, self), pnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_IsBindableTo(self: *const T, pnccItem: ?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).IsBindableTo(@ptrCast(*const INetCfgComponentBindings, self), pnccItem); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_EnumBindingPaths(self: *const T, dwFlags: u32, ppIEnum: ?*?*IEnumNetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).EnumBindingPaths(@ptrCast(*const INetCfgComponentBindings, self), dwFlags, ppIEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_MoveBefore(self: *const T, pncbItemSrc: ?*INetCfgBindingPath, pncbItemDest: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).MoveBefore(@ptrCast(*const INetCfgComponentBindings, self), pncbItemSrc, pncbItemDest); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentBindings_MoveAfter(self: *const T, pncbItemSrc: ?*INetCfgBindingPath, pncbItemDest: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentBindings.VTable, self.vtable).MoveAfter(@ptrCast(*const INetCfgComponentBindings, self), pncbItemSrc, pncbItemDest); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgSysPrep_Value = @import("../zig.zig").Guid.initString("c0e8ae98-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgSysPrep = &IID_INetCfgSysPrep_Value; pub const INetCfgSysPrep = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, HrSetupSetFirstDword: fn( self: *const INetCfgSysPrep, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, dwValue: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrSetupSetFirstString: fn( self: *const INetCfgSysPrep, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, pwszValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrSetupSetFirstStringAsBool: fn( self: *const INetCfgSysPrep, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, fValue: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HrSetupSetFirstMultiSzField: fn( self: *const INetCfgSysPrep, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, pmszValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgSysPrep_HrSetupSetFirstDword(self: *const T, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, dwValue: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgSysPrep.VTable, self.vtable).HrSetupSetFirstDword(@ptrCast(*const INetCfgSysPrep, self), pwszSection, pwszKey, dwValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgSysPrep_HrSetupSetFirstString(self: *const T, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, pwszValue: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgSysPrep.VTable, self.vtable).HrSetupSetFirstString(@ptrCast(*const INetCfgSysPrep, self), pwszSection, pwszKey, pwszValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgSysPrep_HrSetupSetFirstStringAsBool(self: *const T, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, fValue: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgSysPrep.VTable, self.vtable).HrSetupSetFirstStringAsBool(@ptrCast(*const INetCfgSysPrep, self), pwszSection, pwszKey, fValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgSysPrep_HrSetupSetFirstMultiSzField(self: *const T, pwszSection: ?[*:0]const u16, pwszKey: ?[*:0]const u16, pmszValue: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgSysPrep.VTable, self.vtable).HrSetupSetFirstMultiSzField(@ptrCast(*const INetCfgSysPrep, self), pwszSection, pwszKey, pmszValue); } };} pub usingnamespace MethodMixin(@This()); }; pub const NCPNP_RECONFIG_LAYER = enum(i32) { NDIS = 1, TDI = 2, }; pub const NCRL_NDIS = NCPNP_RECONFIG_LAYER.NDIS; pub const NCRL_TDI = NCPNP_RECONFIG_LAYER.TDI; const IID_INetCfgPnpReconfigCallback_Value = @import("../zig.zig").Guid.initString("8d84bd35-e227-11d2-b700-00a0c98a6a85"); pub const IID_INetCfgPnpReconfigCallback = &IID_INetCfgPnpReconfigCallback_Value; pub const INetCfgPnpReconfigCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SendPnpReconfig: fn( self: *const INetCfgPnpReconfigCallback, Layer: NCPNP_RECONFIG_LAYER, pszwUpper: ?[*:0]const u16, pszwLower: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 4? pvData: ?*anyopaque, dwSizeOfData: 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 INetCfgPnpReconfigCallback_SendPnpReconfig(self: *const T, Layer: NCPNP_RECONFIG_LAYER, pszwUpper: ?[*:0]const u16, pszwLower: ?[*:0]const u16, pvData: ?*anyopaque, dwSizeOfData: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgPnpReconfigCallback.VTable, self.vtable).SendPnpReconfig(@ptrCast(*const INetCfgPnpReconfigCallback, self), Layer, pszwUpper, pszwLower, pvData, dwSizeOfData); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgComponentControl_Value = @import("../zig.zig").Guid.initString("932238df-bea1-11d0-9298-00c04fc99dcf"); pub const IID_INetCfgComponentControl = &IID_INetCfgComponentControl_Value; pub const INetCfgComponentControl = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Initialize: fn( self: *const INetCfgComponentControl, pIComp: ?*INetCfgComponent, pINetCfg: ?*INetCfg, fInstalling: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ApplyRegistryChanges: fn( self: *const INetCfgComponentControl, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ApplyPnpChanges: fn( self: *const INetCfgComponentControl, pICallback: ?*INetCfgPnpReconfigCallback, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelChanges: fn( self: *const INetCfgComponentControl, ) 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 INetCfgComponentControl_Initialize(self: *const T, pIComp: ?*INetCfgComponent, pINetCfg: ?*INetCfg, fInstalling: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentControl.VTable, self.vtable).Initialize(@ptrCast(*const INetCfgComponentControl, self), pIComp, pINetCfg, fInstalling); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentControl_ApplyRegistryChanges(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentControl.VTable, self.vtable).ApplyRegistryChanges(@ptrCast(*const INetCfgComponentControl, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentControl_ApplyPnpChanges(self: *const T, pICallback: ?*INetCfgPnpReconfigCallback) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentControl.VTable, self.vtable).ApplyPnpChanges(@ptrCast(*const INetCfgComponentControl, self), pICallback); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentControl_CancelChanges(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentControl.VTable, self.vtable).CancelChanges(@ptrCast(*const INetCfgComponentControl, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const NETWORK_INSTALL_TIME = enum(i32) { RIMARYINSTALL = 1, OSTSYSINSTALL = 2, }; pub const NSF_PRIMARYINSTALL = NETWORK_INSTALL_TIME.RIMARYINSTALL; pub const NSF_POSTSYSINSTALL = NETWORK_INSTALL_TIME.OSTSYSINSTALL; pub const NETWORK_UPGRADE_TYPE = enum(i32) { WIN16_UPGRADE = 16, WIN95_UPGRADE = 32, WINNT_WKS_UPGRADE = 64, WINNT_SVR_UPGRADE = 128, WINNT_SBS_UPGRADE = 256, COMPONENT_UPDATE = 512, }; pub const NSF_WIN16_UPGRADE = NETWORK_UPGRADE_TYPE.WIN16_UPGRADE; pub const NSF_WIN95_UPGRADE = NETWORK_UPGRADE_TYPE.WIN95_UPGRADE; pub const NSF_WINNT_WKS_UPGRADE = NETWORK_UPGRADE_TYPE.WINNT_WKS_UPGRADE; pub const NSF_WINNT_SVR_UPGRADE = NETWORK_UPGRADE_TYPE.WINNT_SVR_UPGRADE; pub const NSF_WINNT_SBS_UPGRADE = NETWORK_UPGRADE_TYPE.WINNT_SBS_UPGRADE; pub const NSF_COMPONENT_UPDATE = NETWORK_UPGRADE_TYPE.COMPONENT_UPDATE; const IID_INetCfgComponentSetup_Value = @import("../zig.zig").Guid.initString("932238e3-bea1-11d0-9298-00c04fc99dcf"); pub const IID_INetCfgComponentSetup = &IID_INetCfgComponentSetup_Value; pub const INetCfgComponentSetup = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Install: fn( self: *const INetCfgComponentSetup, dwSetupFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Upgrade: fn( self: *const INetCfgComponentSetup, dwSetupFlags: u32, dwUpgradeFomBuildNo: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReadAnswerFile: fn( self: *const INetCfgComponentSetup, pszwAnswerFile: ?[*:0]const u16, pszwAnswerSections: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Removing: fn( self: *const INetCfgComponentSetup, ) 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 INetCfgComponentSetup_Install(self: *const T, dwSetupFlags: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentSetup.VTable, self.vtable).Install(@ptrCast(*const INetCfgComponentSetup, self), dwSetupFlags); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentSetup_Upgrade(self: *const T, dwSetupFlags: u32, dwUpgradeFomBuildNo: u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentSetup.VTable, self.vtable).Upgrade(@ptrCast(*const INetCfgComponentSetup, self), dwSetupFlags, dwUpgradeFomBuildNo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentSetup_ReadAnswerFile(self: *const T, pszwAnswerFile: ?[*:0]const u16, pszwAnswerSections: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentSetup.VTable, self.vtable).ReadAnswerFile(@ptrCast(*const INetCfgComponentSetup, self), pszwAnswerFile, pszwAnswerSections); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentSetup_Removing(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentSetup.VTable, self.vtable).Removing(@ptrCast(*const INetCfgComponentSetup, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const DEFAULT_PAGES = enum(i32) { D = 1, }; pub const DPP_ADVANCED = DEFAULT_PAGES.D; const IID_INetCfgComponentPropertyUi_Value = @import("../zig.zig").Guid.initString("932238e0-bea1-11d0-9298-00c04fc99dcf"); pub const IID_INetCfgComponentPropertyUi = &IID_INetCfgComponentPropertyUi_Value; pub const INetCfgComponentPropertyUi = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryPropertyUi: fn( self: *const INetCfgComponentPropertyUi, pUnkReserved: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetContext: fn( self: *const INetCfgComponentPropertyUi, pUnkReserved: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, MergePropPages: fn( self: *const INetCfgComponentPropertyUi, pdwDefPages: ?*u32, pahpspPrivate: ?*?*u8, pcPages: ?*u32, hwndParent: ?HWND, pszStartPage: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ValidateProperties: fn( self: *const INetCfgComponentPropertyUi, hwndSheet: ?HWND, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ApplyProperties: fn( self: *const INetCfgComponentPropertyUi, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelProperties: fn( self: *const INetCfgComponentPropertyUi, ) 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 INetCfgComponentPropertyUi_QueryPropertyUi(self: *const T, pUnkReserved: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentPropertyUi.VTable, self.vtable).QueryPropertyUi(@ptrCast(*const INetCfgComponentPropertyUi, self), pUnkReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentPropertyUi_SetContext(self: *const T, pUnkReserved: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentPropertyUi.VTable, self.vtable).SetContext(@ptrCast(*const INetCfgComponentPropertyUi, self), pUnkReserved); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentPropertyUi_MergePropPages(self: *const T, pdwDefPages: ?*u32, pahpspPrivate: ?*?*u8, pcPages: ?*u32, hwndParent: ?HWND, pszStartPage: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentPropertyUi.VTable, self.vtable).MergePropPages(@ptrCast(*const INetCfgComponentPropertyUi, self), pdwDefPages, pahpspPrivate, pcPages, hwndParent, pszStartPage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentPropertyUi_ValidateProperties(self: *const T, hwndSheet: ?HWND) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentPropertyUi.VTable, self.vtable).ValidateProperties(@ptrCast(*const INetCfgComponentPropertyUi, self), hwndSheet); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentPropertyUi_ApplyProperties(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentPropertyUi.VTable, self.vtable).ApplyProperties(@ptrCast(*const INetCfgComponentPropertyUi, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentPropertyUi_CancelProperties(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentPropertyUi.VTable, self.vtable).CancelProperties(@ptrCast(*const INetCfgComponentPropertyUi, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const BIND_FLAGS1 = enum(i32) { ADD = 1, REMOVE = 2, UPDATE = 4, ENABLE = 16, DISABLE = 32, BINDING_PATH = 256, PROPERTYCHANGE = 512, NET = 65536, NETTRANS = 131072, NETCLIENT = 262144, NETSERVICE = 524288, }; pub const NCN_ADD = BIND_FLAGS1.ADD; pub const NCN_REMOVE = BIND_FLAGS1.REMOVE; pub const NCN_UPDATE = BIND_FLAGS1.UPDATE; pub const NCN_ENABLE = BIND_FLAGS1.ENABLE; pub const NCN_DISABLE = BIND_FLAGS1.DISABLE; pub const NCN_BINDING_PATH = BIND_FLAGS1.BINDING_PATH; pub const NCN_PROPERTYCHANGE = BIND_FLAGS1.PROPERTYCHANGE; pub const NCN_NET = BIND_FLAGS1.NET; pub const NCN_NETTRANS = BIND_FLAGS1.NETTRANS; pub const NCN_NETCLIENT = BIND_FLAGS1.NETCLIENT; pub const NCN_NETSERVICE = BIND_FLAGS1.NETSERVICE; const IID_INetCfgComponentNotifyBinding_Value = @import("../zig.zig").Guid.initString("932238e1-bea1-11d0-9298-00c04fc99dcf"); pub const IID_INetCfgComponentNotifyBinding = &IID_INetCfgComponentNotifyBinding_Value; pub const INetCfgComponentNotifyBinding = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, QueryBindingPath: fn( self: *const INetCfgComponentNotifyBinding, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyBindingPath: fn( self: *const INetCfgComponentNotifyBinding, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath, ) 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 INetCfgComponentNotifyBinding_QueryBindingPath(self: *const T, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentNotifyBinding.VTable, self.vtable).QueryBindingPath(@ptrCast(*const INetCfgComponentNotifyBinding, self), dwChangeFlag, pIPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentNotifyBinding_NotifyBindingPath(self: *const T, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentNotifyBinding.VTable, self.vtable).NotifyBindingPath(@ptrCast(*const INetCfgComponentNotifyBinding, self), dwChangeFlag, pIPath); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgComponentNotifyGlobal_Value = @import("../zig.zig").Guid.initString("932238e2-bea1-11d0-9298-00c04fc99dcf"); pub const IID_INetCfgComponentNotifyGlobal = &IID_INetCfgComponentNotifyGlobal_Value; pub const INetCfgComponentNotifyGlobal = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSupportedNotifications: fn( self: *const INetCfgComponentNotifyGlobal, dwNotifications: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SysQueryBindingPath: fn( self: *const INetCfgComponentNotifyGlobal, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SysNotifyBindingPath: fn( self: *const INetCfgComponentNotifyGlobal, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SysNotifyComponent: fn( self: *const INetCfgComponentNotifyGlobal, dwChangeFlag: u32, pIComp: ?*INetCfgComponent, ) 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 INetCfgComponentNotifyGlobal_GetSupportedNotifications(self: *const T, dwNotifications: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentNotifyGlobal.VTable, self.vtable).GetSupportedNotifications(@ptrCast(*const INetCfgComponentNotifyGlobal, self), dwNotifications); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentNotifyGlobal_SysQueryBindingPath(self: *const T, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentNotifyGlobal.VTable, self.vtable).SysQueryBindingPath(@ptrCast(*const INetCfgComponentNotifyGlobal, self), dwChangeFlag, pIPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentNotifyGlobal_SysNotifyBindingPath(self: *const T, dwChangeFlag: u32, pIPath: ?*INetCfgBindingPath) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentNotifyGlobal.VTable, self.vtable).SysNotifyBindingPath(@ptrCast(*const INetCfgComponentNotifyGlobal, self), dwChangeFlag, pIPath); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentNotifyGlobal_SysNotifyComponent(self: *const T, dwChangeFlag: u32, pIComp: ?*INetCfgComponent) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentNotifyGlobal.VTable, self.vtable).SysNotifyComponent(@ptrCast(*const INetCfgComponentNotifyGlobal, self), dwChangeFlag, pIComp); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgComponentUpperEdge_Value = @import("../zig.zig").Guid.initString("932238e4-bea1-11d0-9298-00c04fc99dcf"); pub const IID_INetCfgComponentUpperEdge = &IID_INetCfgComponentUpperEdge_Value; pub const INetCfgComponentUpperEdge = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInterfaceIdsForAdapter: fn( self: *const INetCfgComponentUpperEdge, pAdapter: ?*INetCfgComponent, pdwNumInterfaces: ?*u32, ppguidInterfaceIds: ?[*]?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AddInterfacesToAdapter: fn( self: *const INetCfgComponentUpperEdge, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RemoveInterfacesFromAdapter: fn( self: *const INetCfgComponentUpperEdge, pAdapter: ?*INetCfgComponent, dwNumInterfaces: u32, pguidInterfaceIds: [*]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 INetCfgComponentUpperEdge_GetInterfaceIdsForAdapter(self: *const T, pAdapter: ?*INetCfgComponent, pdwNumInterfaces: ?*u32, ppguidInterfaceIds: ?[*]?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentUpperEdge.VTable, self.vtable).GetInterfaceIdsForAdapter(@ptrCast(*const INetCfgComponentUpperEdge, self), pAdapter, pdwNumInterfaces, ppguidInterfaceIds); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentUpperEdge_AddInterfacesToAdapter(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentUpperEdge.VTable, self.vtable).AddInterfacesToAdapter(@ptrCast(*const INetCfgComponentUpperEdge, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentUpperEdge_RemoveInterfacesFromAdapter(self: *const T, pAdapter: ?*INetCfgComponent, dwNumInterfaces: u32, pguidInterfaceIds: [*]const Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentUpperEdge.VTable, self.vtable).RemoveInterfacesFromAdapter(@ptrCast(*const INetCfgComponentUpperEdge, self), pAdapter, dwNumInterfaces, pguidInterfaceIds); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetLanConnectionUiInfo_Value = @import("../zig.zig").Guid.initString("c08956a6-1cd3-11d1-b1c5-00805fc1270e"); pub const IID_INetLanConnectionUiInfo = &IID_INetLanConnectionUiInfo_Value; pub const INetLanConnectionUiInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDeviceGuid: fn( self: *const INetLanConnectionUiInfo, pguid: ?*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 INetLanConnectionUiInfo_GetDeviceGuid(self: *const T, pguid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetLanConnectionUiInfo.VTable, self.vtable).GetDeviceGuid(@ptrCast(*const INetLanConnectionUiInfo, self), pguid); } };} pub usingnamespace MethodMixin(@This()); }; pub const tagRASCON_IPUI_FLAGS = enum(i32) { VPN = 1, DEMAND_DIAL = 2, NOT_ADMIN = 4, USE_IPv4_STATICADDRESS = 8, USE_IPv4_NAME_SERVERS = 16, USE_IPv4_REMOTE_GATEWAY = 32, USE_IPv4_EXPLICIT_METRIC = 64, USE_HEADER_COMPRESSION = 128, USE_DISABLE_REGISTER_DNS = 256, USE_PRIVATE_DNS_SUFFIX = 512, ENABLE_NBT = 1024, USE_IPv6_STATICADDRESS = 2048, USE_IPv6_NAME_SERVERS = 4096, USE_IPv6_REMOTE_GATEWAY = 8192, USE_IPv6_EXPLICIT_METRIC = 16384, DISABLE_CLASS_BASED_ROUTE = 32768, }; pub const RCUIF_VPN = tagRASCON_IPUI_FLAGS.VPN; pub const RCUIF_DEMAND_DIAL = tagRASCON_IPUI_FLAGS.DEMAND_DIAL; pub const RCUIF_NOT_ADMIN = tagRASCON_IPUI_FLAGS.NOT_ADMIN; pub const RCUIF_USE_IPv4_STATICADDRESS = tagRASCON_IPUI_FLAGS.USE_IPv4_STATICADDRESS; pub const RCUIF_USE_IPv4_NAME_SERVERS = tagRASCON_IPUI_FLAGS.USE_IPv4_NAME_SERVERS; pub const RCUIF_USE_IPv4_REMOTE_GATEWAY = tagRASCON_IPUI_FLAGS.USE_IPv4_REMOTE_GATEWAY; pub const RCUIF_USE_IPv4_EXPLICIT_METRIC = tagRASCON_IPUI_FLAGS.USE_IPv4_EXPLICIT_METRIC; pub const RCUIF_USE_HEADER_COMPRESSION = tagRASCON_IPUI_FLAGS.USE_HEADER_COMPRESSION; pub const RCUIF_USE_DISABLE_REGISTER_DNS = tagRASCON_IPUI_FLAGS.USE_DISABLE_REGISTER_DNS; pub const RCUIF_USE_PRIVATE_DNS_SUFFIX = tagRASCON_IPUI_FLAGS.USE_PRIVATE_DNS_SUFFIX; pub const RCUIF_ENABLE_NBT = tagRASCON_IPUI_FLAGS.ENABLE_NBT; pub const RCUIF_USE_IPv6_STATICADDRESS = tagRASCON_IPUI_FLAGS.USE_IPv6_STATICADDRESS; pub const RCUIF_USE_IPv6_NAME_SERVERS = tagRASCON_IPUI_FLAGS.USE_IPv6_NAME_SERVERS; pub const RCUIF_USE_IPv6_REMOTE_GATEWAY = tagRASCON_IPUI_FLAGS.USE_IPv6_REMOTE_GATEWAY; pub const RCUIF_USE_IPv6_EXPLICIT_METRIC = tagRASCON_IPUI_FLAGS.USE_IPv6_EXPLICIT_METRIC; pub const RCUIF_DISABLE_CLASS_BASED_ROUTE = tagRASCON_IPUI_FLAGS.DISABLE_CLASS_BASED_ROUTE; pub const RASCON_IPUI = extern struct { guidConnection: Guid, fIPv6Cfg: BOOL, dwFlags: u32, pszwIpAddr: [16]u16, pszwDnsAddr: [16]u16, pszwDns2Addr: [16]u16, pszwWinsAddr: [16]u16, pszwWins2Addr: [16]u16, pszwDnsSuffix: [256]u16, pszwIpv6Addr: [65]u16, dwIpv6PrefixLength: u32, pszwIpv6DnsAddr: [65]u16, pszwIpv6Dns2Addr: [65]u16, dwIPv4InfMetric: u32, dwIPv6InfMetric: u32, }; const IID_INetRasConnectionIpUiInfo_Value = @import("../zig.zig").Guid.initString("faedcf58-31fe-11d1-aad2-00805fc1270e"); pub const IID_INetRasConnectionIpUiInfo = &IID_INetRasConnectionIpUiInfo_Value; pub const INetRasConnectionIpUiInfo = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetUiInfo: fn( self: *const INetRasConnectionIpUiInfo, pInfo: ?*RASCON_IPUI, ) 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 INetRasConnectionIpUiInfo_GetUiInfo(self: *const T, pInfo: ?*RASCON_IPUI) callconv(.Inline) HRESULT { return @ptrCast(*const INetRasConnectionIpUiInfo.VTable, self.vtable).GetUiInfo(@ptrCast(*const INetRasConnectionIpUiInfo, self), pInfo); } };} pub usingnamespace MethodMixin(@This()); }; const IID_INetCfgComponentSysPrep_Value = @import("../zig.zig").Guid.initString("c0e8ae9a-306e-11d1-aacf-00805fc1270e"); pub const IID_INetCfgComponentSysPrep = &IID_INetCfgComponentSysPrep_Value; pub const INetCfgComponentSysPrep = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SaveAdapterParameters: fn( self: *const INetCfgComponentSysPrep, pncsp: ?*INetCfgSysPrep, pszwAnswerSections: ?[*:0]const u16, pAdapterInstanceGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RestoreAdapterParameters: fn( self: *const INetCfgComponentSysPrep, pszwAnswerFile: ?[*:0]const u16, pszwAnswerSection: ?[*:0]const u16, pAdapterInstanceGuid: ?*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 INetCfgComponentSysPrep_SaveAdapterParameters(self: *const T, pncsp: ?*INetCfgSysPrep, pszwAnswerSections: ?[*:0]const u16, pAdapterInstanceGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentSysPrep.VTable, self.vtable).SaveAdapterParameters(@ptrCast(*const INetCfgComponentSysPrep, self), pncsp, pszwAnswerSections, pAdapterInstanceGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn INetCfgComponentSysPrep_RestoreAdapterParameters(self: *const T, pszwAnswerFile: ?[*:0]const u16, pszwAnswerSection: ?[*:0]const u16, pAdapterInstanceGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const INetCfgComponentSysPrep.VTable, self.vtable).RestoreAdapterParameters(@ptrCast(*const INetCfgComponentSysPrep, self), pszwAnswerFile, pszwAnswerSection, pAdapterInstanceGuid); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_NetProvisioning_Value = @import("../zig.zig").Guid.initString("2aa2b5fe-b846-4d07-810c-b21ee45320e3"); pub const CLSID_NetProvisioning = &CLSID_NetProvisioning_Value; const IID_IProvisioningDomain_Value = @import("../zig.zig").Guid.initString("c96fbd50-24dd-11d8-89fb-00904b2ea9c6"); pub const IID_IProvisioningDomain = &IID_IProvisioningDomain_Value; pub const IProvisioningDomain = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Add: fn( self: *const IProvisioningDomain, pszwPathToFolder: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Query: fn( self: *const IProvisioningDomain, pszwDomain: ?[*:0]const u16, pszwLanguage: ?[*:0]const u16, pszwXPathQuery: ?[*:0]const u16, Nodes: ?*?*IXMLDOMNodeList, ) 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 IProvisioningDomain_Add(self: *const T, pszwPathToFolder: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IProvisioningDomain.VTable, self.vtable).Add(@ptrCast(*const IProvisioningDomain, self), pszwPathToFolder); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IProvisioningDomain_Query(self: *const T, pszwDomain: ?[*:0]const u16, pszwLanguage: ?[*:0]const u16, pszwXPathQuery: ?[*:0]const u16, Nodes: ?*?*IXMLDOMNodeList) callconv(.Inline) HRESULT { return @ptrCast(*const IProvisioningDomain.VTable, self.vtable).Query(@ptrCast(*const IProvisioningDomain, self), pszwDomain, pszwLanguage, pszwXPathQuery, Nodes); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IProvisioningProfileWireless_Value = @import("../zig.zig").Guid.initString("c96fbd51-24dd-11d8-89fb-00904b2ea9c6"); pub const IID_IProvisioningProfileWireless = &IID_IProvisioningProfileWireless_Value; pub const IProvisioningProfileWireless = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateProfile: fn( self: *const IProvisioningProfileWireless, bstrXMLWirelessConfigProfile: ?BSTR, bstrXMLConnectionConfigProfile: ?BSTR, pAdapterInstanceGuid: ?*Guid, pulStatus: ?*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 IProvisioningProfileWireless_CreateProfile(self: *const T, bstrXMLWirelessConfigProfile: ?BSTR, bstrXMLConnectionConfigProfile: ?BSTR, pAdapterInstanceGuid: ?*Guid, pulStatus: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IProvisioningProfileWireless.VTable, self.vtable).CreateProfile(@ptrCast(*const IProvisioningProfileWireless, self), bstrXMLWirelessConfigProfile, bstrXMLConnectionConfigProfile, pAdapterInstanceGuid, pulStatus); } };} pub usingnamespace MethodMixin(@This()); }; pub const RTR_TOC_ENTRY = extern struct { InfoType: u32, InfoSize: u32, Count: u32, Offset: u32, }; pub const RTR_INFO_BLOCK_HEADER = extern struct { Version: u32, Size: u32, TocEntriesCount: u32, TocEntry: [1]RTR_TOC_ENTRY, }; pub const WORKERFUNCTION = fn( param0: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const MPR_PROTOCOL_0 = extern struct { dwProtocolId: u32, wszProtocol: [41]u16, wszDLLName: [49]u16, }; //-------------------------------------------------------------------------------- // Section: Functions (175) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserAdd( servername: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserEnum( servername: ?[*:0]const u16, level: u32, filter: NET_USER_ENUM_FILTER_FLAGS, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETAPI32" fn NetUserGetInfo( servername: ?[*:0]const u16, username: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserSetInfo( servername: ?[*:0]const u16, username: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserDel( servername: ?[*:0]const u16, username: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserGetGroups( servername: ?[*:0]const u16, username: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserSetGroups( servername: ?[*:0]const u16, username: ?[*:0]const u16, level: u32, buf: ?*u8, num_entries: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserGetLocalGroups( servername: ?[*:0]const u16, username: ?[*:0]const u16, level: u32, flags: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserModalsGet( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserModalsSet( servername: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUserChangePassword( domainname: ?[*:0]const u16, username: ?[*:0]const u16, oldpassword: ?[*:0]const u16, newpassword: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupAdd( servername: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupAddUser( servername: ?[*:0]const u16, GroupName: ?[*:0]const u16, username: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupGetInfo( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupSetInfo( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupDel( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupDelUser( servername: ?[*:0]const u16, GroupName: ?[*:0]const u16, Username: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupGetUsers( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, ResumeHandle: ?*usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGroupSetUsers( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, buf: ?*u8, totalentries: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupAdd( servername: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetLocalGroupAddMember( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, membersid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resumehandle: ?*usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupGetInfo( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupSetInfo( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupDel( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetLocalGroupDelMember( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, membersid: ?PSID, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupGetMembers( servername: ?[*:0]const u16, localgroupname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resumehandle: ?*usize, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupSetMembers( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, buf: ?*u8, totalentries: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupAddMembers( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, buf: ?*u8, totalentries: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetLocalGroupDelMembers( servername: ?[*:0]const u16, groupname: ?[*:0]const u16, level: u32, buf: ?*u8, totalentries: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetQueryDisplayInformation( ServerName: ?[*:0]const u16, Level: u32, Index: u32, EntriesRequested: u32, PreferredMaximumLength: u32, ReturnedEntryCount: ?*u32, SortedBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGetDisplayInformationIndex( ServerName: ?[*:0]const u16, Level: u32, Prefix: ?[*:0]const u16, Index: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAccessAdd( servername: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAccessEnum( servername: ?[*:0]const u16, BasePath: ?[*:0]const u16, Recursive: u32, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAccessGetInfo( servername: ?[*:0]const u16, resource: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAccessSetInfo( servername: ?[*:0]const u16, resource: ?[*:0]const u16, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAccessDel( servername: ?[*:0]const u16, resource: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAccessGetUserPerms( servername: ?[*:0]const u16, UGname: ?[*:0]const u16, resource: ?[*:0]const u16, Perms: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windowsServer2003' pub extern "NETAPI32" fn NetValidatePasswordPolicy( ServerName: ?[*:0]const u16, Qualifier: ?*anyopaque, ValidationType: NET_VALIDATE_PASSWORD_TYPE, InputArg: ?*anyopaque, OutputArg: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windowsServer2003' pub extern "NETAPI32" fn NetValidatePasswordPolicyFree( OutputArg: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGetDCName( ServerName: ?[*:0]const u16, DomainName: ?[*:0]const u16, Buffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGetAnyDCName( ServerName: ?[*:0]const u16, DomainName: ?[*:0]const u16, Buffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn I_NetLogonControl2( ServerName: ?[*:0]const u16, FunctionCode: u32, QueryLevel: u32, Data: ?*u8, Buffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetAddServiceAccount( ServerName: ?PWSTR, AccountName: ?PWSTR, Password: ?PWSTR, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetRemoveServiceAccount( ServerName: ?PWSTR, AccountName: ?PWSTR, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetEnumerateServiceAccounts( ServerName: ?PWSTR, Flags: u32, AccountsCount: ?*u32, Accounts: ?*?*?*u16, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetIsServiceAccount( ServerName: ?PWSTR, AccountName: ?PWSTR, IsService: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetQueryServiceAccount( ServerName: ?PWSTR, AccountName: ?PWSTR, InfoLevel: u32, Buffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) NTSTATUS; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAlertRaise( AlertType: ?[*:0]const u16, Buffer: ?*anyopaque, BufferSize: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetAlertRaiseEx( AlertType: ?[*:0]const u16, VariableInfo: ?*anyopaque, VariableInfoSize: u32, ServiceName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetMessageNameAdd( servername: ?[*:0]const u16, msgname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetMessageNameEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetMessageNameGetInfo( servername: ?[*:0]const u16, msgname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetMessageNameDel( servername: ?[*:0]const u16, msgname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetMessageBufferSend( servername: ?[*:0]const u16, msgname: ?[*:0]const u16, fromname: ?[*:0]const u16, buf: ?*u8, buflen: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetRemoteTOD( UncServerName: ?[*:0]const u16, BufferPtr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetRemoteComputerSupports( UncServerName: ?[*:0]const u16, OptionsWanted: NET_REMOTE_COMPUTER_SUPPORTS_OPTIONS, OptionsSupported: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplGetInfo( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplSetInfo( servername: ?[*:0]const u16, level: u32, buf: ?*const u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirAdd( servername: ?[*:0]const u16, level: u32, buf: ?*const u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirDel( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resumehandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirGetInfo( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirSetInfo( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, level: u32, buf: ?*const u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirLock( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplExportDirUnlock( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, unlockforce: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplImportDirAdd( servername: ?[*:0]const u16, level: u32, buf: ?*const u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplImportDirDel( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplImportDirEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resumehandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplImportDirGetInfo( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplImportDirLock( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetReplImportDirUnlock( servername: ?[*:0]const u16, dirname: ?[*:0]const u16, unlockforce: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, servertype: NET_SERVER_TYPE, domain: ?[*:0]const u16, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerGetInfo( servername: ?PWSTR, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerSetInfo( servername: ?PWSTR, level: u32, buf: ?*u8, ParmError: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerDiskEnum( servername: ?PWSTR, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerComputerNameAdd( ServerName: ?PWSTR, EmulatedDomainName: ?PWSTR, EmulatedServerName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerComputerNameDel( ServerName: ?PWSTR, EmulatedServerName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerTransportAdd( servername: ?PWSTR, level: u32, bufptr: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerTransportAddEx( servername: ?PWSTR, level: u32, bufptr: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerTransportDel( servername: ?PWSTR, level: u32, bufptr: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetServerTransportEnum( servername: ?PWSTR, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetServiceControl( servername: ?[*:0]const u16, service: ?[*:0]const u16, opcode: u32, arg: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetServiceEnum( servername: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetServiceGetInfo( servername: ?[*:0]const u16, service: ?[*:0]const u16, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetServiceInstall( servername: ?[*:0]const u16, service: ?[*:0]const u16, argc: u32, argv: [*]?PWSTR, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUseAdd( servername: ?*i8, LevelFlags: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUseDel( UncServerName: ?PWSTR, UseName: ?PWSTR, ForceLevelFlags: FORCE_LEVEL_FLAGS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUseEnum( UncServerName: ?PWSTR, LevelFlags: u32, BufPtr: ?*?*u8, PreferedMaximumSize: u32, EntriesRead: ?*u32, TotalEntries: ?*u32, ResumeHandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUseGetInfo( UncServerName: ?PWSTR, UseName: ?PWSTR, LevelFlags: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetWkstaGetInfo( servername: ?PWSTR, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetWkstaSetInfo( servername: ?PWSTR, level: u32, buffer: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetWkstaUserGetInfo( reserved: ?PWSTR, level: u32, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetWkstaUserSetInfo( reserved: ?PWSTR, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetWkstaUserEnum( servername: ?PWSTR, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resumehandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetWkstaTransportAdd( servername: ?*i8, level: u32, buf: ?*u8, parm_err: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetWkstaTransportDel( servername: ?PWSTR, transportname: ?PWSTR, ucond: FORCE_LEVEL_FLAGS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetWkstaTransportEnum( servername: ?*i8, level: u32, bufptr: ?*?*u8, prefmaxlen: u32, entriesread: ?*u32, totalentries: ?*u32, resume_handle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetApiBufferAllocate( ByteCount: u32, Buffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetApiBufferFree( Buffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetApiBufferReallocate( OldBuffer: ?*anyopaque, NewByteCount: u32, NewBuffer: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetApiBufferSize( Buffer: ?*anyopaque, ByteCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetErrorLogClear( UncServerName: ?[*:0]const u16, BackupFile: ?[*:0]const u16, Reserved: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetErrorLogRead( UncServerName: ?[*:0]const u16, Reserved1: ?PWSTR, ErrorLogHandle: ?*HLOG, Offset: u32, Reserved2: ?*u32, Reserved3: u32, OffsetFlag: u32, BufPtr: ?*?*u8, PrefMaxSize: u32, BytesRead: ?*u32, TotalAvailable: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetErrorLogWrite( Reserved1: ?*u8, Code: u32, Component: ?[*:0]const u16, Buffer: ?*u8, NumBytes: u32, MsgBuf: ?*u8, StrCount: u32, Reserved2: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetConfigGet( server: ?[*:0]const u16, component: ?[*:0]const u16, parameter: ?[*:0]const u16, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetConfigGetAll( server: ?[*:0]const u16, component: ?[*:0]const u16, bufptr: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetConfigSet( server: ?[*:0]const u16, reserved1: ?[*:0]const u16, component: ?[*:0]const u16, level: u32, reserved2: u32, buf: ?*u8, reserved3: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetAuditClear( server: ?[*:0]const u16, backupfile: ?[*:0]const u16, service: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetAuditRead( server: ?[*:0]const u16, service: ?[*:0]const u16, auditloghandle: ?*HLOG, offset: u32, reserved1: ?*u32, reserved2: u32, offsetflag: u32, bufptr: ?*?*u8, prefmaxlen: u32, bytesread: ?*u32, totalavailable: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "NETAPI32" fn NetAuditWrite( type: u32, buf: ?*u8, numbytes: u32, service: ?[*:0]const u16, reserved: ?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetJoinDomain( lpServer: ?[*:0]const u16, lpDomain: ?[*:0]const u16, lpMachineAccountOU: ?[*:0]const u16, lpAccount: ?[*:0]const u16, lpPassword: ?[*:0]const u16, fJoinOptions: NET_JOIN_DOMAIN_JOIN_OPTIONS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetUnjoinDomain( lpServer: ?[*:0]const u16, lpAccount: ?[*:0]const u16, lpPassword: ?[*:0]const u16, fUnjoinOptions: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetRenameMachineInDomain( lpServer: ?[*:0]const u16, lpNewMachineName: ?[*:0]const u16, lpAccount: ?[*:0]const u16, lpPassword: ?[*:0]const u16, fRenameOptions: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetValidateName( lpServer: ?[*:0]const u16, lpName: ?[*:0]const u16, lpAccount: ?[*:0]const u16, lpPassword: ?[*:0]const u16, NameType: NETSETUP_NAME_TYPE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGetJoinableOUs( lpServer: ?[*:0]const u16, lpDomain: ?[*:0]const u16, lpAccount: ?[*:0]const u16, lpPassword: ?[*:0]const u16, OUCount: ?*u32, OUs: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETAPI32" fn NetAddAlternateComputerName( Server: ?[*:0]const u16, AlternateName: ?[*:0]const u16, DomainAccount: ?[*:0]const u16, DomainAccountPassword: ?[*:0]const u16, Reserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETAPI32" fn NetRemoveAlternateComputerName( Server: ?[*:0]const u16, AlternateName: ?[*:0]const u16, DomainAccount: ?[*:0]const u16, DomainAccountPassword: ?[*:0]const u16, Reserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETAPI32" fn NetSetPrimaryComputerName( Server: ?[*:0]const u16, PrimaryName: ?[*:0]const u16, DomainAccount: ?[*:0]const u16, DomainAccountPassword: ?[*:0]const u16, Reserved: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "NETAPI32" fn NetEnumerateComputerNames( Server: ?[*:0]const u16, NameType: NET_COMPUTER_NAME_TYPE, Reserved: u32, EntryCount: ?*u32, ComputerNames: ?*?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetProvisionComputerAccount( lpDomain: ?[*:0]const u16, lpMachineName: ?[*:0]const u16, lpMachineAccountOU: ?[*:0]const u16, lpDcName: ?[*:0]const u16, dwOptions: NETSETUP_PROVISION, pProvisionBinData: ?*?*u8, pdwProvisionBinDataSize: ?*u32, pProvisionTextData: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "NETAPI32" fn NetRequestOfflineDomainJoin( // TODO: what to do with BytesParamIndex 1? pProvisionBinData: ?*u8, cbProvisionBinDataSize: u32, dwOptions: NET_REQUEST_PROVISION_OPTIONS, lpWindowsPath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "NETAPI32" fn NetCreateProvisioningPackage( pProvisioningParams: ?*NETSETUP_PROVISIONING_PARAMS, ppPackageBinData: ?*?*u8, pdwPackageBinDataSize: ?*u32, ppPackageTextData: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "NETAPI32" fn NetRequestProvisioningPackageInstall( // TODO: what to do with BytesParamIndex 1? pPackageBinData: ?*u8, dwPackageBinDataSize: u32, dwProvisionOptions: NET_REQUEST_PROVISION_OPTIONS, lpWindowsPath: ?[*:0]const u16, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "NETAPI32" fn NetGetAadJoinInformation( pcszTenantId: ?[*:0]const u16, ppJoinInfo: ?*?*DSREG_JOIN_INFO, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.10240' pub extern "NETAPI32" fn NetFreeAadJoinInformation( pJoinInfo: ?*DSREG_JOIN_INFO, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetGetJoinInformation( lpServer: ?[*:0]const u16, lpNameBuffer: ?*?PWSTR, BufferType: ?*NETSETUP_JOIN_STATUS, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "mstask" fn GetNetScheduleAccountInformation( pwszServerName: ?[*:0]const u16, ccAccount: u32, wszAccount: [*:0]u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "mstask" fn SetNetScheduleAccountInformation( pwszServerName: ?[*:0]const u16, pwszAccount: ?[*:0]const u16, pwszPassword: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetScheduleJobAdd( Servername: ?[*:0]const u16, Buffer: ?*u8, JobId: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetScheduleJobDel( Servername: ?[*:0]const u16, MinJobId: u32, MaxJobId: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetScheduleJobEnum( Servername: ?[*:0]const u16, PointerToBuffer: ?*?*u8, PrefferedMaximumLength: u32, EntriesRead: ?*u32, TotalEntries: ?*u32, ResumeHandle: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "NETAPI32" fn NetScheduleJobGetInfo( Servername: ?[*:0]const u16, JobId: u32, PointerToBuffer: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceRegisterExA( lpszCallerName: ?[*:0]const u8, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceDeregisterA( dwTraceID: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceDeregisterExA( dwTraceID: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceGetConsoleA( dwTraceID: u32, lphConsole: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TracePrintfA( dwTraceID: u32, lpszFormat: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TracePrintfExA( dwTraceID: u32, dwFlags: u32, lpszFormat: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceVprintfExA( dwTraceID: u32, dwFlags: u32, lpszFormat: ?[*:0]const u8, arglist: ?*i8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TracePutsExA( dwTraceID: u32, dwFlags: u32, lpszString: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceDumpExA( dwTraceID: u32, dwFlags: u32, lpbBytes: ?*u8, dwByteCount: u32, dwGroupSize: u32, bAddressPrefix: BOOL, lpszPrefix: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceRegisterExW( lpszCallerName: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceDeregisterW( dwTraceID: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceDeregisterExW( dwTraceID: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceGetConsoleW( dwTraceID: u32, lphConsole: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TracePrintfW( dwTraceID: u32, lpszFormat: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TracePrintfExW( dwTraceID: u32, dwFlags: u32, lpszFormat: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceVprintfExW( dwTraceID: u32, dwFlags: u32, lpszFormat: ?[*:0]const u16, arglist: ?*i8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TracePutsExW( dwTraceID: u32, dwFlags: u32, lpszString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn TraceDumpExW( dwTraceID: u32, dwFlags: u32, lpbBytes: ?*u8, dwByteCount: u32, dwGroupSize: u32, bAddressPrefix: BOOL, lpszPrefix: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn LogErrorA( dwMessageId: u32, cNumberOfSubStrings: u32, plpwsSubStrings: [*]?PSTR, dwErrorCode: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn LogEventA( wEventType: u32, dwMessageId: u32, cNumberOfSubStrings: u32, plpwsSubStrings: [*]?PSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn LogErrorW( dwMessageId: u32, cNumberOfSubStrings: u32, plpwsSubStrings: [*]?PWSTR, dwErrorCode: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn LogEventW( wEventType: u32, dwMessageId: u32, cNumberOfSubStrings: u32, plpwsSubStrings: [*]?PWSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogRegisterA( lpszSource: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "rtutils" fn RouterLogDeregisterA( hLogHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventA( hLogHandle: ?HANDLE, dwEventType: u32, dwMessageId: u32, dwSubStringCount: u32, plpszSubStringArray: ?[*]?PSTR, dwErrorCode: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventDataA( hLogHandle: ?HANDLE, dwEventType: u32, dwMessageId: u32, dwSubStringCount: u32, plpszSubStringArray: ?[*]?PSTR, dwDataBytes: u32, lpDataBytes: ?*u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventStringA( hLogHandle: ?HANDLE, dwEventType: u32, dwMessageId: u32, dwSubStringCount: u32, plpszSubStringArray: [*]?PSTR, dwErrorCode: u32, dwErrorIndex: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventExA( hLogHandle: ?HANDLE, dwEventType: u32, dwErrorCode: u32, dwMessageId: u32, ptszFormat: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventValistExA( hLogHandle: ?HANDLE, dwEventType: u32, dwErrorCode: u32, dwMessageId: u32, ptszFormat: ?[*:0]const u8, arglist: ?*i8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterGetErrorStringA( dwErrorCode: u32, lplpszErrorString: ?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn RouterLogRegisterW( lpszSource: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "rtutils" fn RouterLogDeregisterW( hLogHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventW( hLogHandle: ?HANDLE, dwEventType: u32, dwMessageId: u32, dwSubStringCount: u32, plpszSubStringArray: ?[*]?PWSTR, dwErrorCode: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventDataW( hLogHandle: ?HANDLE, dwEventType: u32, dwMessageId: u32, dwSubStringCount: u32, plpszSubStringArray: ?[*]?PWSTR, dwDataBytes: u32, lpDataBytes: ?*u8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventStringW( hLogHandle: ?HANDLE, dwEventType: u32, dwMessageId: u32, dwSubStringCount: u32, plpszSubStringArray: [*]?PWSTR, dwErrorCode: u32, dwErrorIndex: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventExW( hLogHandle: ?HANDLE, dwEventType: u32, dwErrorCode: u32, dwMessageId: u32, ptszFormat: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterLogEventValistExW( hLogHandle: ?HANDLE, dwEventType: u32, dwErrorCode: u32, dwMessageId: u32, ptszFormat: ?[*:0]const u16, arglist: ?*i8, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn RouterGetErrorStringW( dwErrorCode: u32, lplpwszErrorString: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn RouterAssert( pszFailedAssertion: ?PSTR, pszFileName: ?PSTR, dwLineNumber: u32, pszMessage: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "rtutils" fn MprSetupProtocolEnum( dwTransportId: u32, lplpBuffer: ?*?*u8, lpdwEntriesRead: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "rtutils" fn MprSetupProtocolFree( lpBuffer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (19) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const TraceRegisterEx = thismodule.TraceRegisterExA; pub const TraceDeregister = thismodule.TraceDeregisterA; pub const TraceDeregisterEx = thismodule.TraceDeregisterExA; pub const TraceGetConsole = thismodule.TraceGetConsoleA; pub const TracePrintf = thismodule.TracePrintfA; pub const TracePrintfEx = thismodule.TracePrintfExA; pub const TraceVprintfEx = thismodule.TraceVprintfExA; pub const TracePutsEx = thismodule.TracePutsExA; pub const TraceDumpEx = thismodule.TraceDumpExA; pub const LogError = thismodule.LogErrorA; pub const LogEvent = thismodule.LogEventA; pub const RouterLogRegister = thismodule.RouterLogRegisterA; pub const RouterLogDeregister = thismodule.RouterLogDeregisterA; pub const RouterLogEvent = thismodule.RouterLogEventA; pub const RouterLogEventData = thismodule.RouterLogEventDataA; pub const RouterLogEventString = thismodule.RouterLogEventStringA; pub const RouterLogEventEx = thismodule.RouterLogEventExA; pub const RouterLogEventValistEx = thismodule.RouterLogEventValistExA; pub const RouterGetErrorString = thismodule.RouterGetErrorStringA; }, .wide => struct { pub const TraceRegisterEx = thismodule.TraceRegisterExW; pub const TraceDeregister = thismodule.TraceDeregisterW; pub const TraceDeregisterEx = thismodule.TraceDeregisterExW; pub const TraceGetConsole = thismodule.TraceGetConsoleW; pub const TracePrintf = thismodule.TracePrintfW; pub const TracePrintfEx = thismodule.TracePrintfExW; pub const TraceVprintfEx = thismodule.TraceVprintfExW; pub const TracePutsEx = thismodule.TracePutsExW; pub const TraceDumpEx = thismodule.TraceDumpExW; pub const LogError = thismodule.LogErrorW; pub const LogEvent = thismodule.LogEventW; pub const RouterLogRegister = thismodule.RouterLogRegisterW; pub const RouterLogDeregister = thismodule.RouterLogDeregisterW; pub const RouterLogEvent = thismodule.RouterLogEventW; pub const RouterLogEventData = thismodule.RouterLogEventDataW; pub const RouterLogEventString = thismodule.RouterLogEventStringW; pub const RouterLogEventEx = thismodule.RouterLogEventExW; pub const RouterLogEventValistEx = thismodule.RouterLogEventValistExW; pub const RouterGetErrorString = thismodule.RouterGetErrorStringW; }, .unspecified => if (@import("builtin").is_test) struct { pub const TraceRegisterEx = *opaque{}; pub const TraceDeregister = *opaque{}; pub const TraceDeregisterEx = *opaque{}; pub const TraceGetConsole = *opaque{}; pub const TracePrintf = *opaque{}; pub const TracePrintfEx = *opaque{}; pub const TraceVprintfEx = *opaque{}; pub const TracePutsEx = *opaque{}; pub const TraceDumpEx = *opaque{}; pub const LogError = *opaque{}; pub const LogEvent = *opaque{}; pub const RouterLogRegister = *opaque{}; pub const RouterLogDeregister = *opaque{}; pub const RouterLogEvent = *opaque{}; pub const RouterLogEventData = *opaque{}; pub const RouterLogEventString = *opaque{}; pub const RouterLogEventEx = *opaque{}; pub const RouterLogEventValistEx = *opaque{}; pub const RouterGetErrorString = *opaque{}; } else struct { pub const TraceRegisterEx = @compileError("'TraceRegisterEx' requires that UNICODE be set to true or false in the root module"); pub const TraceDeregister = @compileError("'TraceDeregister' requires that UNICODE be set to true or false in the root module"); pub const TraceDeregisterEx = @compileError("'TraceDeregisterEx' requires that UNICODE be set to true or false in the root module"); pub const TraceGetConsole = @compileError("'TraceGetConsole' requires that UNICODE be set to true or false in the root module"); pub const TracePrintf = @compileError("'TracePrintf' requires that UNICODE be set to true or false in the root module"); pub const TracePrintfEx = @compileError("'TracePrintfEx' requires that UNICODE be set to true or false in the root module"); pub const TraceVprintfEx = @compileError("'TraceVprintfEx' requires that UNICODE be set to true or false in the root module"); pub const TracePutsEx = @compileError("'TracePutsEx' requires that UNICODE be set to true or false in the root module"); pub const TraceDumpEx = @compileError("'TraceDumpEx' requires that UNICODE be set to true or false in the root module"); pub const LogError = @compileError("'LogError' requires that UNICODE be set to true or false in the root module"); pub const LogEvent = @compileError("'LogEvent' requires that UNICODE be set to true or false in the root module"); pub const RouterLogRegister = @compileError("'RouterLogRegister' requires that UNICODE be set to true or false in the root module"); pub const RouterLogDeregister = @compileError("'RouterLogDeregister' requires that UNICODE be set to true or false in the root module"); pub const RouterLogEvent = @compileError("'RouterLogEvent' requires that UNICODE be set to true or false in the root module"); pub const RouterLogEventData = @compileError("'RouterLogEventData' requires that UNICODE be set to true or false in the root module"); pub const RouterLogEventString = @compileError("'RouterLogEventString' requires that UNICODE be set to true or false in the root module"); pub const RouterLogEventEx = @compileError("'RouterLogEventEx' requires that UNICODE be set to true or false in the root module"); pub const RouterLogEventValistEx = @compileError("'RouterLogEventValistEx' requires that UNICODE be set to true or false in the root module"); pub const RouterGetErrorString = @compileError("'RouterGetErrorString' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (18) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const BSTR = @import("../foundation.zig").BSTR; const CERT_CONTEXT = @import("../security/cryptography.zig").CERT_CONTEXT; const CHAR = @import("../foundation.zig").CHAR; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HKEY = @import("../system/registry.zig").HKEY; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IUnknown = @import("../system/com.zig").IUnknown; const IXMLDOMNodeList = @import("../data/xml/ms_xml.zig").IXMLDOMNodeList; const NTSTATUS = @import("../foundation.zig").NTSTATUS; const PSID = @import("../foundation.zig").PSID; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const SID_NAME_USE = @import("../security.zig").SID_NAME_USE; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "WORKERFUNCTION")) { _ = WORKERFUNCTION; } @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/network_management/net_management.zig
const ArrayList = std.ArrayList; const Builder = std.build.Builder; const CrossTarget = std.zig.CrossTarget; const FixedBufferAllocator = std.heap.FixedBufferAllocator; const ImageConverter = @import("assetconverter/image_converter.zig").ImageConverter; const LibExeObjStep = std.build.LibExeObjStep; const Step = std.build.Step; const builtin = std.builtin; const fmt = std.fmt; const fs = std.fs; const std = @import("std"); pub const ImageSourceTarget = @import("assetconverter/image_converter.zig").ImageSourceTarget; const GBALinkerScript = libRoot() ++ "/gba.ld"; const GBALibFile = libRoot() ++ "/gba.zig"; var IsDebugOption: ?bool = null; var UseGDBOption: ?bool = null; const gba_thumb_target = blk: { var target = CrossTarget{ .cpu_arch = std.Target.Cpu.Arch.thumb, .cpu_model = .{ .explicit = &std.Target.arm.cpu.arm7tdmi }, .os_tag = .freestanding, }; target.cpu_features_add.addFeature(@enumToInt(std.Target.arm.Feature.thumb_mode)); break :blk target; }; fn libRoot() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } pub fn addGBAStaticLibrary(b: *Builder, libraryName: []const u8, sourceFile: []const u8, isDebug: bool) *LibExeObjStep { const lib = b.addStaticLibrary(libraryName, sourceFile); lib.setTarget(gba_thumb_target); lib.setLinkerScriptPath(std.build.FileSource{ .path = GBALinkerScript }); lib.setBuildMode(if (isDebug) builtin.Mode.Debug else builtin.Mode.ReleaseFast); return lib; } pub fn createGBALib(b: *Builder, isDebug: bool) *LibExeObjStep { return addGBAStaticLibrary(b, "ZigGBA", GBALibFile, isDebug); } pub fn addGBAExecutable(b: *Builder, romName: []const u8, sourceFile: []const u8) *LibExeObjStep { const isDebug = blk: { if (IsDebugOption) |value| { break :blk value; } else { const newIsDebug = b.option(bool, "debug", "Generate a debug build") orelse false; IsDebugOption = newIsDebug; break :blk newIsDebug; } }; const useGDB = blk: { if (UseGDBOption) |value| { break :blk value; } else { const gdb = b.option(bool, "gdb", "Generate a ELF file for easier debugging with mGBA remote GDB support") orelse false; UseGDBOption = gdb; break :blk gdb; } }; const exe = b.addExecutable(romName, sourceFile); exe.setTarget(gba_thumb_target); exe.setLinkerScriptPath(std.build.FileSource{ .path = GBALinkerScript }); exe.setBuildMode(if (isDebug) builtin.Mode.Debug else builtin.Mode.ReleaseFast); if (useGDB) { exe.install(); } else { _ = exe.installRaw(b.fmt("{s}.gba", .{romName}), .{}); } const gbaLib = createGBALib(b, isDebug); exe.addPackagePath("gba", GBALibFile); exe.linkLibrary(gbaLib); b.default_step.dependOn(&exe.step); return exe; } const Mode4ConvertStep = struct { step: Step, builder: *Builder, images: []const ImageSourceTarget, targetPalettePath: []const u8, pub fn init(b: *Builder, images: []const ImageSourceTarget, targetPalettePath: []const u8) Mode4ConvertStep { return Mode4ConvertStep{ .builder = b, .step = Step.init(.custom, b.fmt("ConvertMode4Image {s}", .{targetPalettePath}), b.allocator, make), .images = images, .targetPalettePath = targetPalettePath, }; } fn make(step: *Step) !void { const self = @fieldParentPtr(Mode4ConvertStep, "step", step); const ImageSourceTargetList = ArrayList(ImageSourceTarget); var fullImages = ImageSourceTargetList.init(self.builder.allocator); defer fullImages.deinit(); for (self.images) |imageSourceTarget| { try fullImages.append(ImageSourceTarget{ .source = self.builder.pathFromRoot(imageSourceTarget.source), .target = self.builder.pathFromRoot(imageSourceTarget.target), }); } const fullTargetPalettePath = self.builder.pathFromRoot(self.targetPalettePath); try ImageConverter.convertMode4Image(self.builder.allocator, fullImages.items, fullTargetPalettePath); } }; pub fn convertMode4Images(libExe: *LibExeObjStep, images: []const ImageSourceTarget, targetPalettePath: []const u8) void { const convertImageStep = libExe.builder.allocator.create(Mode4ConvertStep) catch unreachable; convertImageStep.* = Mode4ConvertStep.init(libExe.builder, images, targetPalettePath); libExe.step.dependOn(&convertImageStep.step); }
GBA/builder.zig
const root = @import("root"); const isUpper = @import("std").ascii.isUpper; const isDigit = @import("std").ascii.isDigit; pub const N64 = struct { pub const Header = packed struct { piBsbDom1LatReg: u8, piBsbDom1PgsReg: u8, piBsbDom1PwdReg: u8, piBsbDom1PgsReg2: u8, initialClockRate: u32, bootAddressOffset: u32, releaseOffset: u32, crc1: u32, crc2: u32, unused1: u64, gameName: [20]u8, unused2: u32, developerId: u32, cartridgeId: u16, countryCode: u16, pub fn setup(comptime gameName: []const u8) Header { var header = Header{ .piBsbDom1LatReg = 0x80, .piBsbDom1PgsReg = 0x37, .piBsbDom1PwdReg = 0x12, .piBsbDom1PgsReg2 = 0x40, .initialClockRate = 0x0, .bootAddressOffset = 0x80001000, .releaseOffset = 0x0, .crc1 = 0x0, .crc2 = 0x0, .gameName = [_]u8{' '} ** 20, .developerId = 0, .cartridgeId = 0, .countryCode = 0, .unused1 = 0, .unused2 = 0, }; comptime { for (gameName) |value, index| { var validChar = isUpper(value) or isDigit(value); if (validChar and index < 20) { header.gameName[index] = value; } else { if (index >= 20) { @compileError("Game name is too long, it needs to be no longer than 20 characters."); } else if (!validChar) { @compileError("Game name needs to be in uppercase, it can use digits."); } } } } return header; } }; }; export nakedcc fn N64main() linksection(".boot") noreturn { asm volatile ( \\.set noat \\addiu $v0, $zero, 0x8 \\lui $at, 0xBFC0 \\sw $v0, 0x7FC($at) ); // call user's main if (@hasDecl(root, "main")) { root.main(); } else { while (true) {} } }
src/n64.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("hwzip", "./src/hwzip.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const lib = b.addStaticLibrary("deflate", "./src/deflate.zig"); lib.setBuildMode(mode); lib.install(); var bits_tests = b.addTest("./src/bits_test.zig"); var bitstream_tests = b.addTest("./src/bits_test.zig"); var deflate_tests = b.addTest("./src/deflate_test.zig"); var huffman_tests = b.addTest("./src/huffman_test.zig"); var hwzip_tests = b.addTest("./src/hwzip_test.zig"); var implode_tests = b.addTest("./src/implode_test.zig"); var lz77_tests = b.addTest("./src/lz77_test.zig"); var reduce_tests = b.addTest("./src/reduce_test.zig"); var shrink_tests = b.addTest("./src/shrink_test.zig"); var zip_tests = b.addTest("./src/zip_test.zig"); bits_tests.setBuildMode(mode); bitstream_tests.setBuildMode(mode); deflate_tests.setBuildMode(mode); huffman_tests.setBuildMode(mode); hwzip_tests.setBuildMode(mode); implode_tests.setBuildMode(mode); lz77_tests.setBuildMode(mode); reduce_tests.setBuildMode(mode); shrink_tests.setBuildMode(mode); zip_tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&bits_tests.step); test_step.dependOn(&bitstream_tests.step); test_step.dependOn(&huffman_tests.step); test_step.dependOn(&lz77_tests.step); test_step.dependOn(&deflate_tests.step); test_step.dependOn(&reduce_tests.step); test_step.dependOn(&shrink_tests.step); test_step.dependOn(&implode_tests.step); test_step.dependOn(&zip_tests.step); test_step.dependOn(b.getInstallStep()); // makes sure hwzip binary is built before hwzip_test test_step.dependOn(&hwzip_tests.step); }
build.zig
const std = @import("std"); const mem = std.mem; const os = std.os; const assert = std.debug.assert; const v = @import("vector_types.zig"); const llvm = @import("llvm_intrinsics.zig"); const c = @import("c_intrinsics.zig"); const string_parsing = @import("string_parsing.zig"); const number_parsing = @import("number_parsing.zig"); const atom_parsing = @import("atom_parsing.zig"); const Logger = @import("Logger.zig"); const cmn = @import("common.zig"); pub const Document = struct { tape: std.ArrayListUnmanaged(u64), string_buf: []u8, string_buf_cap: u32, pub fn init() Document { return .{ .tape = std.ArrayListUnmanaged(u64){}, .string_buf = &[_]u8{}, .string_buf_cap = 0, }; } pub fn allocate(document: *Document, allocator: mem.Allocator, capacity: u32) !void { if (capacity == 0) return; // a pathological input like "[[[[..." would generate capacity tape elements, so // need a capacity of at least capacity + 1, but it is also possible to do // worse with "[7,7,7,7,6,7,7,7,6,7,7,6,[7,7,7,7,6,7,7,7,6,7,7,6,7,7,7,7,7,7,6" //where capacity + 1 tape elements are // generated, see issue https://github.com/simdjson/simdjson/issues/345 const tape_capacity = cmn.ROUNDUP_N(capacity + 3, 64); // a document with only zero-length strings... could have capacity/3 string // and we would need capacity/3 * 5 bytes on the string buffer document.string_buf_cap = cmn.ROUNDUP_N(5 * capacity / 3 + cmn.SIMDJSON_PADDING, 64); errdefer { allocator.free(document.string_buf); document.tape.deinit(allocator); } try document.tape.ensureTotalCapacity(allocator, tape_capacity); document.string_buf = try allocator.alloc(u8, document.string_buf_cap); document.string_buf.len = 0; } pub fn deinit(doc: *Document, allocator: mem.Allocator) void { doc.tape.deinit(allocator); doc.string_buf.len = doc.string_buf_cap; allocator.free(doc.string_buf[0..doc.string_buf_cap]); } }; const BitIndexer = struct { tail: std.ArrayListUnmanaged(u32), // flatten out values in 'bits' assuming that they are are to have values of idx // plus their position in the bitvector, and store these indexes at // base_ptr[base] incrementing base as we go // will potentially store extra values beyond end of valid bits, so base_ptr // needs to be large enough to handle this inline fn write(indexer: *BitIndexer, reader_pos_: u64, bits_: u64) void { var bits = bits_; // In some instances, the next branch is expensive because it is mispredicted. // Unfortunately, in other cases, // it helps tremendously. cmn.print("{b:0>64} | bits", .{@bitReverse(u64, bits_)}); if (bits == 0) { cmn.println("", .{}); return; } const reader_pos = @intCast(i32, reader_pos_ - 64); // this function is always passed last bits so reader_pos will be ahead by 64 const cnt = @popCount(u64, bits); cmn.println(", reader_pos {}", .{reader_pos}); const start_count = indexer.tail.items.len; // Do the first 8 all together { var new_items = indexer.tail.addManyAsArrayAssumeCapacity(8); for (new_items) |*ptr| { ptr.* = @intCast(u32, reader_pos + @ctz(u64, bits)); bits = (bits -% 1) & bits; // std.log.debug("bits {}", .{bits}); } } // Do the next 8 all together (we hope in most cases it won't happen at all // and the branch is easily predicted). if (cnt > 8) { var new_items = indexer.tail.addManyAsArrayAssumeCapacity(8); for (new_items) |*ptr| { ptr.* = @intCast(u32, reader_pos + @ctz(u64, bits)); bits = (bits -% 1) & bits; } } // Most files don't have 16+ structurals per block, so we take several basically guaranteed // branch mispredictions here. 16+ structurals per block means either punctuation ({} [] , // :) // or the start of a value ("abc" true 123) every four characters. if (cnt > 16) { var i: usize = 16; while (true) { indexer.tail.appendAssumeCapacity(@intCast(u32, reader_pos + @ctz(u64, bits))); bits = (bits -% 1) & bits; i += 1; if (i >= cnt) break; } } // std.log.debug("tail.items.len {d} start_count + cnt {d}", .{ indexer.tail.items.len, start_count + cnt }); indexer.tail.shrinkRetainingCapacity(start_count + cnt); } }; const Utf8Checker = struct { err: v.u8x32 = [1]u8{0} ** 32, prev_input_block: v.u8x32 = [1]u8{0} ** 32, prev_incomplete: v.u8x32 = [1]u8{0} ** 32, fn prev(comptime N: u8, chunk: v.u8x32, prev_chunk: v.u8x32) v.u8x32 { return switch (N) { 1 => c._prev1(chunk, prev_chunk), 2 => c._prev2(chunk, prev_chunk), 3 => c._prev3(chunk, prev_chunk), else => unreachable, }; } // zig fmt: off inline fn check_special_cases(input: v.u8x32, prev1: v.u8x32) v.u8x32 { // Bit 0 = Too Short (lead byte/ASCII followed by lead byte/ASCII) // Bit 1 = Too Long (ASCII followed by continuation) // Bit 2 = Overlong 3-byte // Bit 4 = Surrogate // Bit 5 = Overlong 2-byte // Bit 7 = Two Continuations const TOO_SHORT: u8 = 1 << 0; // 11______ 0_______ // 11______ 11______ const TOO_LONG: u8 = 1 << 1; // 0_______ 10______ const OVERLONG_3: u8 = 1 << 2; // 11100000 100_____ const SURROGATE: u8 = 1 << 4; // 11101101 101_____ const OVERLONG_2: u8 = 1 << 5; // 1100000_ 10______ const TWO_CONTS: u8 = 1 << 7; // 10______ 10______ const TOO_LARGE: u8 = 1 << 3; // 11110100 1001____ // 11110100 101_____ // 11110101 1001____ // 11110101 101_____ // 1111011_ 1001____ // 1111011_ 101_____ // 11111___ 1001____ // 11111___ 101_____ const TOO_LARGE_1000: u8 = 1 << 6; // 11110101 1000____ // 1111011_ 1000____ // 11111___ 1000____ const OVERLONG_4: u8 = 1 << 6; // 11110000 1000____ const byte_1_high_0 = prev1 >> @splat(32, @as(u3, 4)); const tbl1 = [16]u8{ // 0_______ ________ <ASCII in byte 1> TOO_LONG, TOO_LONG, TOO_LONG, TOO_LONG, TOO_LONG, TOO_LONG, TOO_LONG, TOO_LONG, // 10______ ________ <continuation in byte 1> TWO_CONTS, TWO_CONTS, TWO_CONTS, TWO_CONTS, // 1100____ ________ <two byte lead in byte 1> TOO_SHORT | OVERLONG_2, // 1101____ ________ <two byte lead in byte 1> TOO_SHORT, // 1110____ ________ <three byte lead in byte 1> TOO_SHORT | OVERLONG_3 | SURROGATE, // 1111____ ________ <four+ byte lead in byte 1> TOO_SHORT | TOO_LARGE | TOO_LARGE_1000 | OVERLONG_4, } ** 2; const byte_1_high = llvm.shuffleEpi8(tbl1, byte_1_high_0); const CARRY: u8 = TOO_SHORT | TOO_LONG | TWO_CONTS; // These all have ____ in byte 1 . const byte_1_low0 = prev1 & @splat(32, @as(u8, 0x0F)); const tbl2 = [16]u8{ // ____0000 ________ CARRY | OVERLONG_3 | OVERLONG_2 | OVERLONG_4, // ____0001 ________ CARRY | OVERLONG_2, // ____001_ ________ CARRY, CARRY, // ____0100 ________ CARRY | TOO_LARGE, // ____0101 ________ CARRY | TOO_LARGE | TOO_LARGE_1000, // ____011_ ________ CARRY | TOO_LARGE | TOO_LARGE_1000, CARRY | TOO_LARGE | TOO_LARGE_1000, // ____1___ ________ CARRY | TOO_LARGE | TOO_LARGE_1000, CARRY | TOO_LARGE | TOO_LARGE_1000, CARRY | TOO_LARGE | TOO_LARGE_1000, CARRY | TOO_LARGE | TOO_LARGE_1000, CARRY | TOO_LARGE | TOO_LARGE_1000, // ____1101 ________ CARRY | TOO_LARGE | TOO_LARGE_1000 | SURROGATE, CARRY | TOO_LARGE | TOO_LARGE_1000, CARRY | TOO_LARGE | TOO_LARGE_1000, } ** 2; const byte_1_low = llvm.shuffleEpi8(tbl2, byte_1_low0); const byte_2_high_0 = input >> @splat(32, @as(u3, 4)); const tbl3 = [16]u8{ // ________ 0_______ <ASCII in byte 2> TOO_SHORT, TOO_SHORT, TOO_SHORT, TOO_SHORT, TOO_SHORT, TOO_SHORT, TOO_SHORT, TOO_SHORT, // ________ 1000____ TOO_LONG | OVERLONG_2 | TWO_CONTS | OVERLONG_3 | TOO_LARGE_1000 | OVERLONG_4, // ________ 1001____ TOO_LONG | OVERLONG_2 | TWO_CONTS | OVERLONG_3 | TOO_LARGE, // ________ 101_____ TOO_LONG | OVERLONG_2 | TWO_CONTS | SURROGATE | TOO_LARGE, TOO_LONG | OVERLONG_2 | TWO_CONTS | SURROGATE | TOO_LARGE, // ________ 11______ TOO_SHORT, TOO_SHORT, TOO_SHORT, TOO_SHORT, } ** 2; const byte_2_high = llvm.shuffleEpi8(tbl3, byte_2_high_0); return (byte_1_high & byte_1_low & byte_2_high); } // zig fmt: on fn check_multibyte_lengths(input: v.u8x32, prev_input: v.u8x32, sc: v.u8x32) v.u8x32 { const prev2 = prev(2, input, prev_input); const prev3 = prev(3, input, prev_input); const must23 = must_be_2_3_continuation(prev2, prev3); // std.log.debug("input {s} prev_input {s} must23 {}", .{ @as([32]u8, input), @as([32]u8, prev_input), must23 }); const must23_80 = must23 & @splat(32, @as(u8, 0x80)); return must23_80 ^ sc; } fn must_be_2_3_continuation(prev2: v.u8x32, prev3: v.u8x32) v.u8x32 { // do unsigned saturating subtraction, then interpret as signed so we can check if > 0 below const is_third_byte = @bitCast( v.i8x32, prev2 -| @splat(32, @as(u8, 0b11100000 - 1)), ); // Only 111_____ will be > 0 const is_fourth_byte = @bitCast( v.i8x32, prev3 -| @splat(32, @as(u8, 0b11110000 - 1)), ); // Only 1111____ will be > 0 // Caller requires a bool (all 1's). All values resulting from the subtraction will be <= 64, so signed comparison is fine. const result = @bitCast(v.i1x32, (is_third_byte | is_fourth_byte) > @splat(32, @as(i8, 0))); return @bitCast(v.u8x32, @as(v.i8x32, result)); } // // Check whether the current bytes are valid UTF-8. // inline fn check_utf8_bytes(checker: *Utf8Checker, input: v.u8x32, prev_input: v.u8x32) void { // Flip prev1...prev3 so we can easily determine if they are 2+, 3+ or 4+ lead bytes // (2, 3, 4-byte leads become large positive numbers instead of small negative numbers) const prev1 = prev(1, input, prev_input); const sc = check_special_cases(input, prev1); checker.err |= check_multibyte_lengths(input, prev_input, sc); } // The only problem that can happen at EOF is that a multibyte character is too short // or a byte value too large in the last bytes: check_special_cases only checks for bytes // too large in the first of two bytes. inline fn check_eof(checker: *Utf8Checker) void { // If the previous block had incomplete UTF-8 characters at the end, an ASCII block can't // possibly finish them. checker.err |= checker.prev_incomplete; } inline fn is_ascii(input: v.u8x64) bool { const bytes: [64]u8 = input; const a: v.u8x32 = bytes[0..32].*; const b: v.u8x32 = bytes[32..64].*; return llvm._mm256_movemask_epi8(a | b) == 0; } inline fn check_next_input(checker: *Utf8Checker, input: v.u8x64) void { // const NUM_CHUNKS = cmn.STEP_SIZE / 32; const NUM_CHUNKS = 2; const chunks = @bitCast([NUM_CHUNKS][32]u8, input); if (is_ascii(input)) { checker.err |= checker.prev_incomplete; } else { // you might think that a for-loop would work, but under Visual Studio, it is not good enough. // static_assert((simd8x64<uint8_t>::NUM_CHUNKS == 2) || (simd8x64<uint8_t>::NUM_CHUNKS == 4), // "We support either two or four chunks per 64-byte block."); if (NUM_CHUNKS == 2) { checker.check_utf8_bytes(chunks[0], checker.prev_input_block); checker.check_utf8_bytes(chunks[1], chunks[0]); } // TODO: NUM_CHUNKS = 4 // else if (NUM_CHUNKS == 4) { // checker.check_utf8_bytes(chunks[0], checker.prev_input_block); // checker.check_utf8_bytes(chunks[1], chunks[0]); // checker.check_utf8_bytes(chunks[2], chunks[1]); // checker.check_utf8_bytes(chunks[3], chunks[2]); // } else unreachable; checker.prev_incomplete = is_incomplete(chunks[NUM_CHUNKS - 1]); checker.prev_input_block = chunks[NUM_CHUNKS - 1]; } } // do not forget to call check_eof! inline fn errors(checker: Utf8Checker) cmn.JsonError!void { const err = @reduce(.Or, checker.err); if (err != 0) return error.UTF8_ERROR; } // // Return nonzero if there are incomplete multibyte characters at the end of the block: // e.g. if there is a 4-byte character, but it's 3 bytes from the end. // inline fn is_incomplete(input: v.u8x32) v.u8x32 { // If the previous input's last 3 bytes match this, they're too short (they ended at EOF): // ... 1111____ 111_____ 11______ const max_array: [32]u8 = .{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0b11110000 - 1, 0b11100000 - 1, 0b11000000 - 1, }; const max_value = @splat(32, max_array[@sizeOf(@TypeOf(max_array)) - @sizeOf(v.u8x32)]); return input -| max_value; } }; const StringBlock = struct { backslash: u64, escaped: u64, quote: u64, in_string: u64, inline fn string_tail(sb: StringBlock) u64 { return sb.in_string ^ sb.quote; } inline fn non_quote_inside_string(sb: StringBlock, mask: u64) u64 { return mask & sb.in_string; } }; const CharacterBlock = struct { whitespace: u64, op: u64, pub fn classify(input_vec: v.u8x64) CharacterBlock { // These lookups rely on the fact that anything < 127 will match the lower 4 bits, which is why // we can't use the generic lookup_16. const whitespace_table: v.u8x32 = [16]u8{ ' ', 100, 100, 100, 17, 100, 113, 2, 100, '\t', '\n', 112, 100, '\r', 100, 100 } ** 2; // The 6 operators (:,[]{}) have these values: // // , 2C // : 3A // [ 5B // { 7B // ] 5D // } 7D // // If you use | 0x20 to turn [ and ] into { and }, the lower 4 bits of each character is unique. // We exploit this, using a simd 4-bit lookup to tell us which character match against, and then // match it (against | 0x20). // // To prevent recognizing other characters, everything else gets compared with 0, which cannot // match due to the | 0x20. // // NOTE: Due to the | 0x20, this ALSO treats <FF> and <SUB> (control characters 0C and 1A) like , // and :. This gets caught in stage 2, which checks the actual character to ensure the right // operators are in the right places. const op_table: v.u8x32 = [16]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, ':', '{', // : = 3A, [ = 5B, { = 7B ',', '}', 0, 0, // , = 2C, ] = 5D, } = 7D } ** 2; // We compute whitespace and op separately. If later code only uses one or the // other, given the fact that all functions are aggressively inlined, we can // hope that useless computations will be omitted. This is namely case when // minifying (we only need whitespace). const in = @bitCast([64]u8, input_vec); const chunk0: v.u8x32 = in[0..32].*; const chunk1: v.u8x32 = in[32..64].*; const wss: [2]v.u8x32 = .{ llvm.shuffleEpi8(whitespace_table, chunk0), llvm.shuffleEpi8(whitespace_table, chunk1), }; const whitespace = input_vec == @bitCast(v.u8x64, wss); // Turn [ and ] into { and } const curlified = input_vec | @splat(64, @as(u8, 0x20)); const ops: [2]v.u8x32 = .{ llvm.shuffleEpi8(op_table, chunk0), llvm.shuffleEpi8(op_table, chunk1), }; const op = curlified == @bitCast(v.u8x64, ops); return .{ .whitespace = @ptrCast(*const u64, &whitespace).*, .op = @ptrCast(*const u64, &op).* }; } pub inline fn scalar(cb: CharacterBlock) u64 { return ~(cb.op | cb.whitespace); } }; const Block = struct { string: StringBlock, characters: CharacterBlock, follows_nonquote_scalar: u64, inline fn structural_start(block: Block) u64 { return block.potential_structural_start() & ~block.string.string_tail(); } inline fn potential_structural_start(block: Block) u64 { return block.characters.op | block.potential_scalar_start(); } inline fn potential_scalar_start(block: Block) u64 { // The term "scalar" refers to anything except structural characters and white space // (so letters, numbers, quotes). // Whenever it is preceded by something that is not a structural element ({,},[,],:, ") nor a white-space // then we know that it is irrelevant structurally. return block.characters.scalar() & ~block.follows_nonquote_scalar; } inline fn non_quote_inside_string(block: Block, mask: u64) u64 { return block.string.non_quote_inside_string(mask); } }; pub const StructuralIndexer = struct { prev_structurals: u64 = 0, unescaped_chars_error: u64 = 0, bit_indexer: BitIndexer, checker: Utf8Checker, pub fn init() !StructuralIndexer { return StructuralIndexer{ .bit_indexer = .{ .tail = std.ArrayListUnmanaged(u32){} }, .checker = .{}, }; } inline fn follows(match: u64, overflow: *u64) u64 { const result = match << 1 | overflow.*; overflow.* = match >> 63; return result; } fn nextBlock(parser: *Parser, input_vec: v.u8x64) Block { const string = parser.nextStringBlock(input_vec); // identifies the white-space and the structurat characters const characters = CharacterBlock.classify(input_vec); // The term "scalar" refers to anything except structural characters and white space // (so letters, numbers, quotes). // We want follows_scalar to mark anything that follows a non-quote scalar (so letters and numbers). // // A terminal quote should either be followed by a structural character (comma, brace, bracket, colon) // or nothing. However, we still want ' "a string"true ' to mark the 't' of 'true' as a potential // pseudo-structural character just like we would if we had ' "a string" true '; otherwise we // may need to add an extra check when parsing strings. // // Performance: there are many ways to skin this cat. const nonquote_scalar = characters.scalar() & ~string.quote; const follows_nonquote_scalar = follows(nonquote_scalar, &parser.prev_scalar); // We are returning a function-local object so either we get a move constructor // or we get copy elision. // if (unescaped & strings.in_string != 0) return error.UnescapedCharacters; return Block{ .string = string, // strings is a function-local object so either it moves or the copy is elided. .characters = characters, .follows_nonquote_scalar = follows_nonquote_scalar, }; } pub fn step(si: *StructuralIndexer, read_buf: [cmn.STEP_SIZE]u8, parser: *Parser, reader_pos: u64) !void { if (cmn.STEP_SIZE == 64) { const block_1 = nextBlock(parser, read_buf); // println("{b:0>64} | characters.op", .{@bitReverse(u64, block_1.characters.op)}); try si.next(read_buf, block_1, reader_pos); // std.log.debug("stream pos {}", .{try stream.getPos()}); } else { const block_1 = nextBlock(parser, read_buf[0..64].*); const block_2 = nextBlock(parser, read_buf[64..128].*); try si.next(read_buf[0..64].*, block_1, reader_pos); try si.next(read_buf[64..128].*, block_2, reader_pos + 64); } try si.checker.errors(); } pub fn finish(si: *StructuralIndexer, parser: *Parser, idx: usize, len: usize, partial: bool) !void { _ = partial; // println("finish idx {}, len {}", .{ idx, len }); si.bit_indexer.write(idx, si.prev_structurals); // TODO partial: // error_code error = scanner.finish(); if (parser.prev_in_string != 0) return error.UNCLOSED_STRING; // // We deliberately break down the next expression so that it is // // human readable. // const bool should_we_exit = partial ? // ((error != SUCCESS) && (error != UNCLOSED_STRING)) // when partial we tolerate UNCLOSED_STRING // : (error != SUCCESS); // if partial is false, we must have SUCCESS // const bool have_unclosed_string = (error == UNCLOSED_STRING); // if (simdjson_unlikely(should_we_exit)) { return error; } if (si.unescaped_chars_error != 0) { return error.UNESCAPED_CHARS; } // parser.n_structural_indexes = uint32_t(indexer.tail - parser.structural_indexes.get()); parser.n_structural_indexes = try std.math.cast(u32, si.bit_indexer.tail.items.len); // *** // * This is related to https://github.com/simdjson/simdjson/issues/906 // * Basically, we want to make sure that if the parsing continues beyond the last (valid) // * structural character, it quickly stops. // * Only three structural characters can be repeated without triggering an error in JSON: [,] and }. // * We repeat the padding character (at 'len'). We don't know what it is, but if the parsing // * continues, then it must be [,] or }. // * Suppose it is ] or }. We backtrack to the first character, what could it be that would // * not trigger an error? It could be ] or } but no, because you can't start a document that way. // * It can't be a comma, a colon or any simple value. So the only way we could continue is // * if the repeated character is [. But if so, the document must start with [. But if the document // * starts with [, it should end with ]. If we enforce that rule, then we would get // * ][[ which is invalid. // **/ var new_inds = parser.indexer.bit_indexer.tail.addManyAsArrayAssumeCapacity(3); new_inds[0] = @intCast(u32, len); new_inds[1] = @intCast(u32, len); new_inds[2] = 0; parser.next_structural_index = 0; // a valid JSON file cannot have zero structural indexes - we should have found something if (parser.indexer.bit_indexer.tail.items.len == 0) { return error.EMPTY; } if (parser.indexer.bit_indexer.tail.items[parser.indexer.bit_indexer.tail.items.len - 1] > len) { return error.UNEXPECTED_ERROR; } // TODO // if (partial) { // // If we have an unclosed string, then the last structural // // will be the quote and we want to make sure to omit it. // if(have_unclosed_string) { // parser.n_structural_indexes--; // // a valid JSON file cannot have zero structural indexes - we should have found something // if (simdjson_unlikely(parser.n_structural_indexes == 0u)) { return CAPACITY; } // } // auto new_structural_indexes = find_next_document_index(parser); // if (new_structural_indexes == 0 && parser.n_structural_indexes > 0) { // return CAPACITY; // If the buffer is partial but the document is incomplete, it's too big to parse. // } // parser.n_structural_indexes = new_structural_indexes; // } si.checker.check_eof(); return si.checker.errors(); } fn lteq(comptime T: type, chunks: [2]v.u8x32, m: T) u64 { const mask = @splat(32, m); const a = chunks[0] <= mask; const b = chunks[1] <= mask; const aint = @as(u64, @ptrCast(*const u32, &a).*); const bint = @as(u64, @ptrCast(*const u32, &b).*) << 32; return aint | bint; } fn next(si: *StructuralIndexer, input_vec: v.u8x64, block: Block, reader_pos: u64) !void { const chunks = @bitCast([2]v.u8x32, input_vec); const unescaped = lteq(u8, chunks, 0x1F); if (cmn.debug) { var input: [cmn.STEP_SIZE]u8 = undefined; std.mem.copy(u8, &input, &@as([64]u8, input_vec)); for (input) |*ch| { if (ch.* == '\n') ch.* = '-'; } cmn.println("{s}", .{input}); } // println("{b:0>64} | block.characters.op", .{@bitReverse(u64, block.characters.op)}); // println("{b:0>64} | block.characters.whitespace", .{@bitReverse(u64, block.characters.whitespace)}); // println("{b:0>64} | block.string.in_string", .{@bitReverse(u64, block.string.in_string)}); // println("{b:0>64} | block.string.backslash", .{@bitReverse(u64, block.string.backslash)}); // println("{b:0>64} | block.string.escaped", .{@bitReverse(u64, block.string.escaped)}); // println("{b:0>64} | block.string.quote", .{@bitReverse(u64, block.string.quote)}); // println("{b:0>64} | unscaped", .{ @bitReverse(u64, unescaped) }); si.checker.check_next_input(input_vec); si.bit_indexer.write(reader_pos, si.prev_structurals); // Output *last* iteration's structurals to the parser si.prev_structurals = block.structural_start(); si.unescaped_chars_error |= block.non_quote_inside_string(unescaped); } }; pub const OpenContainer = struct { tape_index: u32, // where, on the tape, does the scope ([,{) begin count: u32, // how many elements in the scope }; pub const OpenContainerInfo = struct { open_container: OpenContainer, is_array: bool, }; pub const Iterator = struct { parser: *Parser, _next_structural: [*]u32, depth: u32 = 0, log: Logger = .{ .depth = 0 }, pub fn init(parser: *Parser, start_structural_index: usize) Iterator { return .{ .parser = parser, ._next_structural = parser.indexer.bit_indexer.tail.items[start_structural_index..].ptr, }; } inline fn advance(iter: *Iterator) [*]const u8 { defer iter._next_structural += 1; // std.log.debug("advance() next_structural idx {} peek() '{c}'", .{ (@ptrToInt(iter.next_structural) - @ptrToInt(iter.parser.indexer.bit_indexer.tail.items.ptr)) / 4, iter.peek() }); return iter.peek(); } inline fn peek(iter: *Iterator) [*]const u8 { return iter.parser.bytes.ptr + iter._next_structural[0]; } pub inline fn at_beginning(iter: *Iterator) bool { // std.log.debug("at-beginning {*}: {}", .{ iter.next_structural, iter.next_structural[0] }); return iter.next_structural() == iter.parser.indexer.bit_indexer.tail.items.ptr; } pub inline fn next_structural(iter: Iterator) [*]u32 { return iter._next_structural; } inline fn at_eof(iter: *Iterator) bool { // std.log.debug("at-beginning {*}: {}", .{ iter.next_structural, iter.next_structural[0] }); return @ptrToInt(iter._next_structural) == @ptrToInt(iter.parser.indexer.bit_indexer.tail.items.ptr + iter.parser.n_structural_indexes); } const State = enum { object_begin, object_field, object_continue, scope_end, array_begin, array_value, array_continue, document_end, }; pub fn walk_document(iter: *Iterator, visitor: *TapeBuilder) !void { iter.log.start(iter); if (iter.at_eof()) return error.EMPTY; iter.log.start_value(iter, "document"); try visitor.visit_document_start(iter); if (iter.parser.bytes.len == 0) return iter.document_end(visitor); const value = iter.advance(); var state: State = blk: { switch (value[0]) { '{' => { if (iter.peek()[0] == '}') { _ = iter.advance(); iter.log.value(iter, "empty object"); try visitor.visit_empty_object(); } else break :blk .object_begin; }, '[' => { if (iter.peek()[0] == ']') { _ = iter.advance(); iter.log.value(iter, "empty array"); try visitor.visit_empty_array(); } else break :blk .array_begin; }, else => try visitor.visit_root_primitive(iter, value), } break :blk .document_end; }; while (true) { state = switch (state) { .object_begin => try iter.object_begin(visitor), .object_field => try iter.object_field(visitor), .object_continue => try iter.object_continue(visitor), .scope_end => try iter.scope_end(visitor), .array_begin => try iter.array_begin(visitor), .array_value => try iter.array_value(visitor), .array_continue => try iter.array_continue(visitor), .document_end => return try iter.document_end(visitor), }; } } inline fn object_begin(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!State { iter.log.start_value(iter, "object"); iter.depth += 1; // iter.log.line_fmt(iter, "", "depth", "{d}/{d}", .{ iter.depth, iter.parser.max_depth }); if (iter.depth >= iter.parser.max_depth) { iter.log.err(iter, "Exceeded max depth!"); return error.DEPTH_ERROR; } try visitor.visit_object_start(iter); const key = iter.advance(); if (key[0] != '"') { iter.log.err(iter, "Object does not start with a key"); return error.TAPE_ERROR; } iter.increment_count(); try visitor.visit_key(iter, key); return .object_field; } inline fn object_field(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!State { if (iter.advance()[0] != ':') { iter.log.err(iter, "Missing colon after key in object"); return error.TAPE_ERROR; } const value = iter.advance(); switch (value[0]) { '{' => if (iter.peek()[0] == '}') { _ = iter.advance(); iter.log.value(iter, "empty object"); try visitor.visit_empty_object(); } else return .object_begin, '[' => if (iter.peek()[0] == ']') { _ = iter.advance(); iter.log.value(iter, "empty array"); try visitor.visit_empty_array(); } else return .array_begin, else => try visitor.visit_primitive(iter, value), } return .object_continue; } inline fn object_continue(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!State { const value = iter.advance(); // std.log.debug("object_continue() value '{c}'", .{value}); switch (value[0]) { ',' => { iter.increment_count(); const key = iter.advance(); // println("key '{c}'", .{key}); if (key[0] != '"') { iter.log.err(iter, "Key string missing at beginning of field in object"); return error.TAPE_ERROR; } try visitor.visit_key(iter, key); return .object_field; }, '}' => { iter.log.end_value(iter, "object"); _ = try visitor.visit_object_end(iter); return .scope_end; }, else => { iter.log.err(iter, "No comma between object fields"); return error.TAPE_ERROR; }, } unreachable; } inline fn scope_end(iter: *Iterator, _: *TapeBuilder) cmn.Error!State { // std.log.debug("scope_end iter.depth {}", .{iter.depth}); iter.depth -= 1; if (iter.depth == 0) return .document_end; const is_array = iter.parser.open_containers.items(.is_array)[iter.depth]; if (is_array) return .array_continue; return .object_continue; } inline fn array_begin(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!State { iter.log.start_value(iter, "array"); iter.depth += 1; if (iter.depth >= iter.parser.max_depth) { iter.log.err(iter, "Exceeded max depth!"); return error.DEPTH_ERROR; } _ = try visitor.visit_array_start(iter); iter.increment_count(); return .array_value; } inline fn array_value(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!State { const value = iter.advance(); switch (value[0]) { '{' => { if (iter.peek()[0] == '}') { _ = iter.advance(); iter.log.value(iter, "empty object"); try visitor.visit_empty_object(); } else return .object_begin; }, '[' => { if (iter.peek()[0] == ']') { _ = iter.advance(); iter.log.value(iter, "empty array"); try visitor.visit_empty_array(); } else return .array_begin; }, else => try visitor.visit_primitive(iter, value), } return .array_continue; } inline fn array_continue(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!State { switch (iter.advance()[0]) { ',' => { iter.increment_count(); return .array_value; }, ']' => { iter.log.end_value(iter, "array"); try visitor.visit_array_end(iter); return .scope_end; }, else => { iter.log.err(iter, "Missing comma between array values"); return error.TAPE_ERROR; }, } unreachable; } inline fn document_end(iter: *Iterator, visitor: *TapeBuilder) cmn.Error!void { iter.log.end_value(iter, "document"); try visitor.visit_document_end(); iter.parser.next_structural_index = try cmn.ptr_diff( u32, iter._next_structural, iter.parser.indexer.bit_indexer.tail.items.ptr, ); // If we didn't make it to the end, it's an error // std.log.debug("next_structural_index {} n_structural_indexes {}", .{ iter.parser.next_structural_index, iter.parser.n_structural_indexes }); // have to add because there are 3 additional items added to tail in finish() if (!cmn.STREAMING and iter.parser.next_structural_index != iter.parser.n_structural_indexes) { iter.log.err(iter, "More than one JSON value at the root of the document, or extra characters at the end of the JSON!"); return error.TAPE_ERROR; } } inline fn current_container(iter: *Iterator) *OpenContainer { // std.log.debug("current_container iter.parser.open_containers.len {} iter.depth {}", .{ iter.parser.open_containers.items.len, iter.depth }); return &iter.parser.open_containers.items(.open_container)[iter.depth]; } inline fn increment_count(iter: *Iterator) void { // we have a key value pair in the object at parser.dom_parser.depth - 1 iter.current_container().count += 1; } fn root_checkpoint(iter: *Iterator) [*]u32 { return iter.parser.indexer.bit_indexer.tail.items.ptr; } }; pub const TapeType = enum(u8) { ROOT = 'r', START_ARRAY = '[', START_OBJECT = '{', END_ARRAY = ']', END_OBJECT = '}', STRING = '"', INT64 = 'l', UINT64 = 'u', DOUBLE = 'd', TRUE = 't', FALSE = 'f', NULL = 'n', INVALID = 'i', pub inline fn as_u64(tt: TapeType) u64 { return @as(u64, @enumToInt(tt)) << 56; } pub inline fn from_u64(x: u64) TapeType { return std.meta.intToEnum(TapeType, (x & 0xff00000000000000) >> 56) catch .INVALID; } pub inline fn encode_value(tt: TapeType, value: u64) u64 { assert(value <= std.math.maxInt(u56)); return @as(u64, @enumToInt(tt)) << 56 | value; } pub inline fn extract_value(item: u64) u64 { return item & value_mask; } pub const value_mask = 0x00ffffffffffffff; pub const count_mask = 0xffffff; }; pub const TapeBuilder = struct { tape: *std.ArrayListUnmanaged(u64), current_string_buf_loc: [*]u8, pub fn init(doc: *Document) TapeBuilder { return .{ .tape = &doc.tape, .current_string_buf_loc = doc.string_buf.ptr, }; } pub inline fn append(tb: *TapeBuilder, val: u64, tt: TapeType) void { // iter.log.line_fmt(iter, "", "append", "val {} tt {}", .{ val, tt }); tb.tape.appendAssumeCapacity(val | tt.as_u64()); } pub inline fn append2(tb: *TapeBuilder, val: u64, val2: anytype, tt: TapeType) void { tb.append(val, tt); assert(@sizeOf(@TypeOf(val2)) == 8); tb.tape.appendAssumeCapacity(val2); } pub inline fn append_double(tb: *TapeBuilder, val: f64) void { tb.append2(0, @bitCast(u64, val), .DOUBLE); } pub inline fn append_i64(tb: *TapeBuilder, val: u64) void { tb.append2(0, val, .INT64); } pub inline fn append_u64(tb: *TapeBuilder, val: u64) void { tb.append2(0, val, .UINT64); } pub inline fn write(tb: *TapeBuilder, idx: usize, val: u64, tt: TapeType) void { // iter.log.line_fmt(iter, "", "write", "val {} tt {} idx {}", .{ val, tt, idx }); assert(idx < tb.tape.items.len); tb.tape.items[idx] = val | tt.as_u64(); } pub inline fn next_tape_index(tb: TapeBuilder) u32 { return @intCast(u32, tb.tape.items.len); } pub inline fn skip(tb: TapeBuilder) void { _ = tb.tape.addOneAssumeCapacity(); } pub inline fn empty_container(tb: *TapeBuilder, start: TapeType, end: TapeType) void { const start_index = tb.next_tape_index(); tb.append(start_index + 2, start); tb.append(start_index, end); } pub inline fn start_container( tb: TapeBuilder, open_containers: *std.MultiArrayList(OpenContainerInfo), is_array: bool, count: u32, ) void { const tape_idx = tb.next_tape_index(); open_containers.appendAssumeCapacity(.{ .is_array = is_array, .open_container = .{ .tape_index = @intCast(u32, tape_idx), .count = count, }, }); tb.skip(); } pub inline fn end_container(tb: *TapeBuilder, iter: *Iterator, start: TapeType, end: TapeType) void { // Write the ending tape element, pointing at the start location const container = iter.parser.open_containers.items(.open_container)[iter.depth]; defer iter.parser.open_containers.shrinkRetainingCapacity(iter.depth); const start_tape_index = container.tape_index; tb.append(start_tape_index, end); // Write the start tape element, pointing at the end location (and including count) // count can overflow if it exceeds 24 bits... so we saturate // the convention being that a cnt of 0xffffff or more is undetermined in value (>= 0xffffff). const cntsat: u32 = std.math.min(@intCast(u32, container.count), 0xFFFFFF); // iter.log.line_fmt(iter, "", "end_container", "next_tape_index {}", .{tb.next_tape_index()}); tb.write(start_tape_index, tb.next_tape_index() | (@as(u64, cntsat) << 32), start); } inline fn on_start_string(tb: *TapeBuilder, iter: *Iterator) ![*]u8 { // iter.log.line_fmt(iter, "", "start_string", "iter.parser.doc.string_buf.len {}", .{iter.parser.doc.string_buf.len}); tb.append(cmn.ptr_diff(u64, tb.current_string_buf_loc, iter.parser.doc.string_buf.ptr) catch unreachable, .STRING); return tb.current_string_buf_loc + @sizeOf(u32); } inline fn on_end_string(tb: *TapeBuilder, iter: *Iterator, dst: [*]u8) !void { const str_len = try cmn.ptr_diff(u32, dst, tb.current_string_buf_loc + @sizeOf(u32)); // println("str_len {} str '{s}'", .{ str_len, (tb.current_string_buf_loc + 4)[0..str_len] }); // TODO check for overflow in case someone has a crazy string (>=4GB?) // But only add the overflow check when the document itself exceeds 4GB // Currently unneeded because we refuse to parse docs larger or equal to 4GB. // NULL termination is still handy if you expect all your strings to // be NULL terminated? It comes at a small cost // iter.log.line_fmt(iter, "", "on_string_end", "{s}", .{str_start[0..str_len]}); @memcpy(tb.current_string_buf_loc, mem.asBytes(&str_len), @sizeOf(u32)); dst[0] = 0; iter.parser.doc.string_buf.len += str_len + 1 + @sizeOf(u32); // println("buf.len {} buf.cap {}", .{ iter.parser.doc.string_buf.len, iter.parser.doc.string_buf_cap }); assert(iter.parser.doc.string_buf.len <= iter.parser.doc.string_buf_cap); tb.current_string_buf_loc += str_len + 1 + @sizeOf(u32); } inline fn visit_root_primitive(visitor: *TapeBuilder, iter: *Iterator, value: [*]const u8) !void { return switch (value[0]) { '"' => visitor.visit_string(iter, value, false), 't' => visitor.visit_true_atom(iter, value), 'f' => visitor.visit_false_atom(iter, value), 'n' => visitor.visit_null_atom(iter, value), '-', '0'...'9' => visitor.visit_number(iter, value), else => blk: { iter.log.err(iter, "Document starts with a non-value character"); break :blk error.TAPE_ERROR; }, }; } inline fn visit_number(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8) cmn.Error!void { iter.log.value(iter, "number"); try number_parsing.parse_number(value, tb); } inline fn visit_true_atom(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8) cmn.Error!void { iter.log.value(iter, "true"); assert(value[0] == 't'); if (!atom_parsing.is_valid_rue_atom(value + 1)) return error.T_ATOM_ERROR; tb.append(0, TapeType.TRUE); } inline fn visit_false_atom(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8) cmn.Error!void { iter.log.value(iter, "false"); assert(value[0] == 'f'); if (!atom_parsing.is_valid_alse_atom(value + 1)) return error.T_ATOM_ERROR; tb.append(0, TapeType.FALSE); } inline fn visit_null_atom(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8) cmn.Error!void { iter.log.value(iter, "null"); assert(value[0] == 'n'); if (!atom_parsing.is_valid_ull_atom(value + 1)) return error.T_ATOM_ERROR; tb.append(0, TapeType.NULL); } inline fn visit_primitive(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8) !void { return switch (value[0]) { '"' => tb.visit_string(iter, value, false), 't' => tb.visit_true_atom(iter, value), 'f' => tb.visit_false_atom(iter, value), 'n' => tb.visit_null_atom(iter, value), '-', '0'...'9' => tb.visit_number(iter, value), else => |c| blk: { iter.log.err_fmt(iter, "Non-value found when value was expected. Value: '{c}' - (0x{x}:{})", .{ c, c, c }); break :blk error.TAPE_ERROR; }, }; } inline fn visit_string(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8, key: bool) cmn.Error!void { iter.log.value(iter, if (key) "key" else "string"); var dst = try tb.on_start_string(iter); dst = string_parsing.parse_string(value + 1, dst) orelse { iter.log.err(iter, "Invalid escape in string"); return error.STRING_ERROR; }; try tb.on_end_string(iter, dst); } pub inline fn visit_key(tb: *TapeBuilder, iter: *Iterator, value: [*]const u8) !void { return tb.visit_string(iter, value, true); } pub inline fn visit_empty_object(tb: *TapeBuilder) cmn.Error!void { return tb.empty_container(.START_OBJECT, .END_OBJECT); } pub inline fn visit_empty_array(tb: *TapeBuilder) cmn.Error!void { return tb.empty_container(.START_ARRAY, .END_ARRAY); } pub inline fn visit_array_start(tb: *TapeBuilder, iter: *Iterator) !void { return tb.start_container(&iter.parser.open_containers, true, 0); } pub inline fn visit_array_end(tb: *TapeBuilder, iter: *Iterator) !void { return tb.end_container(iter, .START_ARRAY, .END_ARRAY); } pub inline fn visit_object_start(tb: *TapeBuilder, iter: *Iterator) !void { return tb.start_container(&iter.parser.open_containers, false, 0); } pub inline fn visit_object_end(tb: *TapeBuilder, iter: *Iterator) !void { return tb.end_container(iter, .START_OBJECT, .END_OBJECT); } pub inline fn visit_document_start(tb: *TapeBuilder, iter: *Iterator) !void { return tb.start_container(&iter.parser.open_containers, false, 0); } pub inline fn visit_document_end(tb: *TapeBuilder) !void { tb.write(0, tb.next_tape_index(), .ROOT); // iter.log.line_fmt(iter, "?", "document_end", "open_containers.len {} tape.len {}", .{ iter.parser.open_containers.items.len, tb.tape.items.len }); return tb.append(0, .ROOT); } }; pub const Parser = struct { filename: []const u8, allocator: mem.Allocator, prev_escaped: u64 = 0, prev_in_string: u64 = 0, prev_scalar: u64 = 0, next_structural_index: u32 = 0, doc: Document, indexer: StructuralIndexer, open_containers: std.MultiArrayList(OpenContainerInfo), max_depth: u16, n_structural_indexes: u32 = 0, bytes: []u8 = &[_]u8{}, input_len: u32 = 0, pub const Options = struct { max_depth: u16 = cmn.DEFAULT_MAX_DEPTH, }; pub fn initFile(allocator: mem.Allocator, filename: []const u8, options: Options) !Parser { var parser = Parser{ .filename = filename, .allocator = allocator, .doc = Document.init(), .indexer = try StructuralIndexer.init(), .open_containers = std.MultiArrayList(OpenContainerInfo){}, .max_depth = options.max_depth, }; parser.input_len = try parser.read_file(filename); const capacity = parser.input_len; try parser.doc.allocate(allocator, capacity); const max_structures = cmn.ROUNDUP_N(capacity, 64) + 2 + 7; try parser.indexer.bit_indexer.tail.ensureTotalCapacity(allocator, max_structures); try parser.open_containers.ensureTotalCapacity(allocator, options.max_depth); return parser; } const ascii_space = 0x20; pub fn initFixedBuffer(allocator: mem.Allocator, input: []const u8, options: Options) !Parser { var parser = Parser{ .filename = "<fixed buffer>", .allocator = allocator, .doc = Document.init(), .indexer = try StructuralIndexer.init(), .bytes = &[_]u8{}, .open_containers = std.MultiArrayList(OpenContainerInfo){}, .max_depth = options.max_depth, }; parser.input_len = try std.math.cast(u32, input.len); const capacity = parser.input_len; const max_structures = cmn.ROUNDUP_N(capacity, 64) + 2 + 7; const paddedlen = try std.math.add(u32, capacity, cmn.SIMDJSON_PADDING); parser.bytes = try parser.allocator.alloc(u8, paddedlen); mem.copy(u8, parser.bytes, input); // We write spaces in the padded region to avoid having uninitized // garbage. If nothing else, garbage getting read might trigger a // warning in a memory checking. std.mem.set(u8, parser.bytes[capacity..], ascii_space); try parser.doc.allocate(allocator, capacity); try parser.indexer.bit_indexer.tail.ensureTotalCapacity(allocator, max_structures); try parser.open_containers.ensureTotalCapacity(allocator, options.max_depth); return parser; } fn read_file(parser: *Parser, filename: []const u8) !u32 { var f = try std.fs.cwd().openFile(filename, .{ .read = true }); defer f.close(); const len = try std.math.cast(u32, try f.getEndPos()); if (parser.bytes.len < len) { const paddedlen = try std.math.add(u32, len, cmn.SIMDJSON_PADDING); parser.bytes = try parser.allocator.realloc(parser.bytes, paddedlen); const nbytes = try f.read(parser.bytes); if (nbytes < len) return error.IO_ERROR; // We write spaces in the padded region to avoid having uninitized // garbage. If nothing else, garbage getting read might trigger a // warning in a memory checking. std.mem.set(u8, parser.bytes[len..], ascii_space); } return len; } pub fn deinit(parser: *Parser) void { parser.indexer.bit_indexer.tail.deinit(parser.allocator); parser.open_containers.deinit(parser.allocator); parser.doc.deinit(parser.allocator); parser.allocator.free(parser.bytes); } inline fn find_escaped(parser: *Parser, backslash_: u64) u64 { // If there was overflow, pretend the first character isn't a backslash var backslash = backslash_ & ~parser.prev_escaped; const follows_escape = backslash << 1 | parser.prev_escaped; // Get sequences starting on even bits by clearing out the odd series using + const even_bits: u64 = 0x5555555555555555; const odd_sequence_starts = backslash & ~even_bits & ~follows_escape; var sequences_starting_on_even_bits: u64 = undefined; // println("{b:0>64} | prev_escaped a", .{@bitReverse(u64, parser.prev_escaped)}); parser.prev_escaped = @boolToInt(@addWithOverflow(u64, odd_sequence_starts, backslash, &sequences_starting_on_even_bits)); // println("{b:0>64} | prev_escaped b", .{@bitReverse(u64, parser.prev_escaped)}); const invert_mask = sequences_starting_on_even_bits << 1; // The mask we want to return is the *escaped* bits, not escapes. // Mask every other backslashed character as an escaped character // Flip the mask for sequences that start on even bits, to correct them return (even_bits ^ invert_mask) & follows_escape; } inline fn nextStringBlock(parser: *Parser, input_vec: v.u8x64) StringBlock { const backslash_vec = input_vec == @splat(64, @as(u8, '\\')); const backslash = @bitCast(u64, backslash_vec); const escaped = parser.find_escaped(backslash); const quote_vec = input_vec == @splat(64, @as(u8, '"')); const quote = @bitCast(u64, quote_vec) & ~escaped; // // prefix_xor flips on bits inside the string (and flips off the end quote). // // Then we xor with prev_in_string: if we were in a string already, its effect is flipped // (characters inside strings are outside, and characters outside strings are inside). // const ones: v.u64x2 = [1]u64{std.math.maxInt(u64)} ** 2; var in_string = llvm.carrylessMul(.{ quote, 0 }, ones)[0]; // println("{b:0>64} | quote a", .{@bitReverse(u64, quote)}); // println("{b:0>64} | ones[0]", .{@bitReverse(u64, ones[0])}); // println("{b:0>64} | in_string a", .{@bitReverse(u64, in_string)}); // println("{b:0>64} | prev_in_string a", .{@bitReverse(u64, parser.prev_in_string)}); in_string ^= parser.prev_in_string; // println("{b:0>64} | in_string b", .{@bitReverse(u64, in_string)}); // // Check if we're still in a string at the end of the box so the next block will know // // right shift of a signed value expected to be well-defined and standard // compliant as of C++20, <NAME> from Utah U. says this is fine code // // println("{b:0>64} | prev_in_string a", .{@bitReverse(u64, parser.prev_in_string)}); // println("{b:0>64} | @bitCast(i64, in_string) ", .{@bitReverse(i64, @bitCast(i64, in_string))}); // println("{b:0>64} | @bitCast(i64, in_string) >> 63 ", .{@bitReverse(i64, @bitCast(i64, in_string) >> 63)}); // println("{b:0>64} | @bitCast(u64, @bitCast(i64, in_string) >> 63) ", .{@bitReverse(u64, @bitCast(u64, @bitCast(i64, in_string) >> 63))}); parser.prev_in_string = @bitCast(u64, @bitCast(i64, in_string) >> 63); // Use ^ to turn the beginning quote off, and the end quote on. // We are returning a function-local object so either we get a move constructor // or we get copy elision. return StringBlock{ .backslash = backslash, .escaped = escaped, .quote = quote, .in_string = in_string, }; } fn stage1(parser: *Parser) !void { const end_pos = parser.input_len; const end_pos_minus_step = if (end_pos > cmn.STEP_SIZE) end_pos - cmn.STEP_SIZE else 0; var pos: u32 = 0; while (pos < end_pos_minus_step) : (pos += cmn.STEP_SIZE) { // println("i {} pos {}", .{ i, pos }); const read_buf = parser.bytes[pos..][0..cmn.STEP_SIZE]; try parser.indexer.step(read_buf.*, parser, pos); // for (blocks) |block| { // println("{b:0>64} | characters.whitespace", .{@bitReverse(u64, block.characters.whitespace)}); // println("{b:0>64} | characters.op", .{@bitReverse(u64, block.characters.op)}); // println("{b:0>64} | in_string", .{@bitReverse(u64, block.strings.in_string)}); // } } var read_buf = [1]u8{0x20} ** cmn.STEP_SIZE; std.mem.copy(u8, &read_buf, parser.bytes[pos..end_pos]); // std.log.debug("read_buf {d}", .{read_buf}); try parser.indexer.step(read_buf, parser, pos); try parser.indexer.finish(parser, pos + cmn.STEP_SIZE, end_pos, cmn.STREAMING); } fn stage2(parser: *Parser) !void { var iter = Iterator.init(parser, 0); var tb = TapeBuilder.init(&parser.doc); try iter.walk_document(&tb); } pub fn parse(parser: *Parser) !void { try parser.stage1(); return parser.stage2(); } pub fn element(parser: Parser) Element { return .{ .tape = .{ .doc = &parser.doc, .idx = 1 }, }; } }; const Array = struct { tape: TapeRef, pub fn at(a: Array, idx: usize) ?Element { var it = TapeRefIterator.init(a); const target_idx = idx + it.tape.idx + idx; while (true) { if (it.tape.idx == target_idx) return Element{ .tape = .{ .doc = it.tape.doc, .idx = it.tape.idx } }; _ = it.next() orelse break; } return null; } pub inline fn at_pointer(arr: Array, _json_pointer: []const u8) cmn.Error!Element { if (_json_pointer.len == 0) return Element{ .tape = arr.tape } else if (_json_pointer[0] != '/') return error.INVALID_JSON_POINTER; var json_pointer = _json_pointer[1..]; // - means "the append position" or "the element after the end of the array" // We don't support this, because we're returning a real element, not a position. if (json_pointer.len == 1 and json_pointer[0] == '-') return error.INDEX_OUT_OF_BOUNDS; // Read the array index var array_index: usize = 0; var i: usize = 0; while (i < json_pointer.len and json_pointer[i] != '/') : (i += 1) { const digit = json_pointer[i] -% '0'; // Check for non-digit in array index. If it's there, we're trying to get a field in an object if (digit > 9) return error.INCORRECT_TYPE; array_index = array_index * 10 + digit; } // 0 followed by other digits is invalid if (i > 1 and json_pointer[0] == '0') { return error.INVALID_JSON_POINTER; } // "JSON pointer array index has other characters after 0" // Empty string is invalid; so is a "/" with no digits before it if (i == 0) return error.INVALID_JSON_POINTER; // "Empty string in JSON pointer array index" // Get the child var child = arr.at(array_index) orelse return error.INVALID_JSON_POINTER; // If there is a /, we're not done yet, call recursively. if (i < json_pointer.len) { child = try child.at_pointer(json_pointer[i..]); } return child; } }; const Object = struct { tape: TapeRef, pub fn at_key(o: Object, key: []const u8) ?Element { var it = TapeRefIterator.init(o); while (true) { if (it.tape.key_equals(key)) return Element{ .tape = .{ .doc = it.tape.doc, .idx = it.tape.idx + 1 } }; _ = it.next() orelse break; } return null; } pub fn at_pointer(o: Object, _json_pointer: []const u8) cmn.Error!Element { if (_json_pointer.len == 0) // an empty string means that we return the current node return Element{ .tape = o.tape } // copy the current node else if (_json_pointer[0] != '/') // otherwise there is an error return error.INVALID_JSON_POINTER; var json_pointer = _json_pointer[1..]; const slash = mem.indexOfScalar(u8, json_pointer, '/'); const key = json_pointer[0 .. slash orelse json_pointer.len]; // Find the child with the given key var child: Element = undefined; // TODO escapes // // If there is an escape character in the key, unescape it and then get the child. // var escape = mem.indexOfScalar(u8, key, '~'); // if (escape != null) { // // Unescape the key // var unescaped: [0x100]u8 = undefined; // mem.copy(u8, &unescaped, key); // while (true) { // switch (unescaped[escape.? + 1]) { // '0' => unescaped.replace(escape, 2, "~"), // '1' => unescaped.replace(escape, 2, "/"), // else => return error.INVALID_JSON_POINTER, // "Unexpected ~ escape character in JSON pointer"); // } // // escape = unescaped.find('~', escape+1); // escape = mem.indexOfScalar(u8, unescaped[escape.? + 1], '~'); // if (escape != null) break; // } // child = o.at_key(unescaped) catch return child; // } else { // child = o.at_key(key) catch return child; // we do not continue if there was an error // } child = o.at_key(key) orelse return error.INVALID_JSON_POINTER; // If there is a /, we have to recurse and look up more of the path if (slash != null) child = try child.at_pointer(json_pointer[slash.?..]); return child; } }; // TODO rename these const ElementType = enum(u8) { /// Array ARRAY = '[', /// Object OBJECT = '{', /// i64 INT64 = 'l', /// u64: any integer that fits in u64 but *not* i64 UINT64 = 'u', /// double: Any number with a "." or "e" that fits in double. DOUBLE = 'd', /// []const u8 STRING = '"', /// bool BOOL = 't', /// null NULL = 'n', }; const Value = union(ElementType) { NULL, BOOL: bool, INT64: i64, UINT64: u64, DOUBLE: f64, STRING: []const u8, ARRAY: Array, OBJECT: Object, }; const TapeRef = struct { doc: *const Document, idx: usize, pub inline fn is(tr: TapeRef, tt: TapeType) bool { return tr.tape_ref_type() == tt; } pub inline fn tape_ref_type(tr: TapeRef) TapeType { return TapeType.from_u64(tr.current()); } pub inline fn value(tr: TapeRef) u64 { return TapeType.extract_value(tr.current()); } pub inline fn next_value(tr: TapeRef) u64 { return TapeType.extract_value(tr.doc.tape.items[tr.idx + 1]); } pub inline fn after_element(tr: TapeRef) u64 { return switch (tr.tape_ref_type()) { .START_ARRAY, .START_OBJECT => tr.matching_brace_idx(), .UINT64, .INT64, .DOUBLE => tr.idx + 2, else => tr.idx + 1, }; } pub inline fn matching_brace_idx(tr: TapeRef) u32 { const result = @truncate(u32, tr.current()); // std.log.debug("TapeRef matching_brace_idx() for {} {}", .{ tr.tape_ref_type(), result }); return result; } pub inline fn current(tr: TapeRef) u64 { // std.log.debug("TapeRef current() idx {} len {}", .{ tr.idx, tr.doc.tape.items.len }); return tr.doc.tape.items[tr.idx]; } pub inline fn scope_count(tr: TapeRef) u32 { return @truncate(u32, (tr.current() >> 32) & TapeType.count_mask); } pub fn get_string_length(tr: TapeRef) u32 { const string_buf_index = tr.value(); return mem.readIntLittle(u32, (tr.doc.string_buf.ptr + string_buf_index)[0..@sizeOf(u32)]); } pub fn get_c_str(tr: TapeRef) [*:0]const u8 { return @ptrCast([*:0]const u8, tr.doc.string_buf.ptr + tr.value() + @sizeOf(u32)); } pub fn get_as_type(tr: TapeRef, comptime T: type) T { comptime assert(@sizeOf(T) == @sizeOf(u64)); return @bitCast(T, tr.current()); } pub fn get_next_as_type(tr: TapeRef, comptime T: type) T { comptime assert(@sizeOf(T) == @sizeOf(u64)); return @bitCast(T, tr.doc.tape.items[tr.idx + 1]); } pub fn get_string(tr: TapeRef) []const u8 { return tr.get_c_str()[0..tr.get_string_length()]; } pub fn key_equals(tr: TapeRef, string: []const u8) bool { // We use the fact that the key length can be computed quickly // without access to the string buffer. const len = tr.get_string_length(); if (string.len == len) { // TODO: We avoid construction of a temporary string_view instance. return mem.eql(u8, string, tr.get_c_str()[0..len]); } return false; } pub fn element(tr: TapeRef) Element { return .{ .tape = tr.tape }; } }; const TapeRefIterator = struct { tape: TapeRef, end_idx: u64, pub fn init(iter: anytype) TapeRefIterator { const tape = iter.tape; return .{ .tape = .{ .doc = tape.doc, .idx = tape.idx + 1 }, .end_idx = tape.after_element() - 1, }; } pub fn next(tri: *TapeRefIterator) ?Element { tri.tape.idx += 1; tri.tape.idx = tri.tape.after_element(); return if (tri.tape.idx >= tri.end_idx) null else tri.element(); } pub fn element(tri: TapeRefIterator) Element { return .{ .tape = tri.tape }; } }; const Element = struct { tape: TapeRef, pub inline fn at_pointer(ele: Element, json_pointer: []const u8) cmn.Error!Element { return switch (ele.tape.tape_ref_type()) { .START_OBJECT => (try ele.get_object()).at_pointer(json_pointer), .START_ARRAY => (try ele.get_array()).at_pointer(json_pointer), else => if (json_pointer.len != 0) error.INVALID_JSON_POINTER else ele, }; } pub fn at_key(ele: Element, key: []const u8) ?Element { return if (ele.get_as_type(.OBJECT)) |o| o.OBJECT.at_key(key) else |_| null; } pub fn at(ele: Element, idx: usize) ?Element { return if (ele.get_as_type(.ARRAY)) |a| a.ARRAY.at(idx) else |_| null; } pub fn get(ele: Element, out: anytype) cmn.Error!void { const T = @TypeOf(out); const info = @typeInfo(T); switch (info) { .Pointer => { const C = std.meta.Child(T); const child_info = @typeInfo(C); switch (info.Pointer.size) { .One => { switch (child_info) { .Int => out.* = try std.math.cast(C, try if (child_info.Int.signedness == .signed) ele.get_int64() else ele.get_uint64()), .Float => out.* = @floatCast(C, try ele.get_double()), .Bool => out.* = try ele.get_bool(), .Optional => out.* = if (ele.is(.NULL)) null else blk: { var x: std.meta.Child(C) = undefined; try ele.get(&x); break :blk x; }, .Array => try ele.get(@as([]std.meta.Child(C), out)), .Struct => { switch (ele.tape.tape_ref_type()) { .START_OBJECT => { var obj = ele.get_object() catch unreachable; inline for (std.meta.fields(C)) |field| { if (obj.at_key(field.name)) |obj_ele| try obj_ele.get(&@field(out, field.name)); } }, else => return error.INCORRECT_TYPE, } }, .Pointer => if (child_info.Pointer.size == .Slice) { out.* = try ele.get_string(); } else @compileError("unsupported type: " ++ @typeName(T) ++ ". expecting slice"), else => @compileError("unsupported type: " ++ @typeName(T) ++ ". int, float, bool or optional type."), } }, .Slice => { switch (ele.tape.tape_ref_type()) { .STRING => { const string = ele.get_string() catch unreachable; @memcpy( @ptrCast([*]u8, out.ptr), string.ptr, std.math.min(string.len, out.len * @sizeOf(C)), ); }, .START_ARRAY => { var arr = ele.get_array() catch unreachable; var it = TapeRefIterator.init(arr); for (out) |*out_ele| { const arr_ele = Element{ .tape = it.tape }; try arr_ele.get(out_ele); _ = it.next() orelse break; } }, else => return error.INCORRECT_TYPE, } }, else => @compileError("unsupported pointer type: " ++ @typeName(T) ++ ". expecting slice or single item pointer."), } }, else => @compileError("unsupported type: " ++ @typeName(T) ++ ". expecting pointer type."), } } pub fn get_as_type(ele: Element, ele_type: ElementType) cmn.Error!Value { return switch (ele_type) { .OBJECT => Value{ .OBJECT = try ele.get_object() }, .ARRAY => Value{ .ARRAY = try ele.get_array() }, .INT64 => Value{ .INT64 = try ele.get_int64() }, .UINT64 => Value{ .UINT64 = try ele.get_uint64() }, .DOUBLE => Value{ .DOUBLE = try ele.get_double() }, .STRING => Value{ .STRING = try ele.get_string() }, .BOOL => Value{ .BOOL = try ele.get_bool() }, .NULL => if (ele.tape.is(.NULL)) Value{ .NULL = {} } else error.INCORRECT_TYPE, }; } pub fn get_array(ele: Element) !Array { return (try ele.get_tape_type(.START_ARRAY)).ARRAY; } pub fn get_object(ele: Element) !Object { return (try ele.get_tape_type(.START_OBJECT)).OBJECT; } pub fn get_int64(ele: Element) cmn.Error!i64 { return if (!ele.is(.INT64)) if (ele.is(.UINT64)) blk: { const result = ele.next_tape_value(u64); break :blk if (result > std.math.maxInt(i64)) error.NUMBER_OUT_OF_RANGE else @bitCast(i64, result); } else error.INCORRECT_TYPE else ele.next_tape_value(i64); } pub fn get_uint64(ele: Element) cmn.Error!u64 { return if (!ele.is(.UINT64)) if (ele.is(.INT64)) blk: { const result = ele.next_tape_value(i64); break :blk if (result < 0) error.NUMBER_OUT_OF_RANGE else @bitCast(u64, result); } else error.INCORRECT_TYPE else ele.next_tape_value(u64); } pub fn get_double(ele: Element) !f64 { return (try ele.get_tape_type(.DOUBLE)).DOUBLE; } pub fn get_string(ele: Element) ![]const u8 { return (try ele.get_tape_type(.STRING)).STRING; } pub fn get_bool(ele: Element) !bool { return switch (ele.tape.tape_ref_type()) { .TRUE => true, .FALSE => false, else => error.INCORRECT_TYPE, }; } pub fn get_tape_type(ele: Element, comptime tape_type: TapeType) !Value { return switch (ele.tape.tape_ref_type()) { tape_type => ele.as_tape_type(tape_type), else => error.INCORRECT_TYPE, }; } pub fn next_tape_value(ele: Element, comptime T: type) T { comptime assert(@sizeOf(T) == @sizeOf(u64)); return mem.readIntLittle(T, @ptrCast([*]const u8, ele.tape.doc.tape.items.ptr + ele.tape.idx + 1)[0..8]); } pub fn as_tape_type(ele: Element, comptime tape_type: TapeType) !Value { return switch (tape_type) { .ROOT, .END_ARRAY, .END_OBJECT, .INVALID, .NULL, => error.INCORRECT_TYPE, .START_ARRAY => Value{ .ARRAY = .{ .tape = ele.tape } }, .START_OBJECT => Value{ .OBJECT = .{ .tape = ele.tape } }, .STRING => Value{ .STRING = ele.tape.get_string() }, .INT64 => Value{ .INT64 = ele.tape.get_next_as_type(i64) }, .UINT64 => Value{ .UINT64 = ele.tape.get_next_as_type(u64) }, .DOUBLE => Value{ .DOUBLE = ele.tape.get_next_as_type(f64) }, .TRUE => Value{ .BOOL = true }, .FALSE => Value{ .BOOL = false }, }; } pub fn is(ele: Element, ele_type: ElementType) bool { return switch (ele_type) { .OBJECT => ele.tape.is(.START_OBJECT), .ARRAY => ele.tape.is(.START_ARRAY), .STRING => ele.tape.is(.STRING), .INT64 => ele.tape.is(.INT64), .UINT64 => ele.tape.is(.UINT64), .DOUBLE => ele.tape.is(.DOUBLE), .BOOL => ele.tape.is(.TRUE) or ele.tape.is(.FALSE), .NULL => ele.tape.is(.NULL), }; } };
src/dom.zig
const std = @import("std"); const ComputePassEncoder = @import("ComputePassEncoder.zig"); const RenderPassEncoder = @import("RenderPassEncoder.zig"); const CommandBuffer = @import("CommandBuffer.zig"); const QuerySet = @import("QuerySet.zig"); const Buffer = @import("Buffer.zig"); const ImageCopyBuffer = @import("structs.zig").ImageCopyBuffer; const ImageCopyTexture = @import("structs.zig").ImageCopyTexture; const Extent3D = @import("data.zig").Extent3D; const CommandEncoder = @This(); /// The type erased pointer to the CommandEncoder implementation /// Equal to c.WGPUCommandEncoder for NativeInstance. ptr: *anyopaque, vtable: *const VTable, pub const VTable = struct { reference: fn (ptr: *anyopaque) void, release: fn (ptr: *anyopaque) void, beginComputePass: fn (ptr: *anyopaque, descriptor: *const ComputePassEncoder.Descriptor) ComputePassEncoder, beginRenderPass: fn (ptr: *anyopaque, descriptor: *const RenderPassEncoder.Descriptor) RenderPassEncoder, clearBuffer: fn (ptr: *anyopaque, buffer: Buffer, offset: u64, size: u64) void, copyBufferToBuffer: fn (ptr: *anyopaque, source: Buffer, source_offset: u64, destination: Buffer, destination_offset: u64, size: u64) void, copyBufferToTexture: fn (ptr: *anyopaque, source: *const ImageCopyBuffer, destination: *const ImageCopyTexture, copy_size: *const Extent3D) void, copyTextureToBuffer: fn (ptr: *anyopaque, source: *const ImageCopyTexture, destination: *const ImageCopyBuffer, copy_size: *const Extent3D) void, copyTextureToTexture: fn (ptr: *anyopaque, source: *const ImageCopyTexture, destination: *const ImageCopyTexture, copy_size: *const Extent3D) void, finish: fn (ptr: *anyopaque, descriptor: ?*const CommandBuffer.Descriptor) CommandBuffer, injectValidationError: fn (ptr: *anyopaque, message: [*:0]const u8) void, insertDebugMarker: fn (ptr: *anyopaque, marker_label: [*:0]const u8) void, popDebugGroup: fn (ptr: *anyopaque) void, pushDebugGroup: fn (ptr: *anyopaque, group_label: [*:0]const u8) void, resolveQuerySet: fn (ptr: *anyopaque, query_set: QuerySet, first_query: u32, query_count: u32, destination: Buffer, destination_offset: u64) void, setLabel: fn (ptr: *anyopaque, label: [:0]const u8) void, writeBuffer: fn (ptr: *anyopaque, buffer: Buffer, buffer_offset: u64, data: *const u8, size: u64) void, writeTimestamp: fn (ptr: *anyopaque, query_set: QuerySet, query_index: u32) void, }; pub inline fn reference(enc: CommandEncoder) void { enc.vtable.reference(enc.ptr); } pub inline fn release(enc: CommandEncoder) void { enc.vtable.release(enc.ptr); } pub inline fn beginComputePass(enc: CommandEncoder, descriptor: *const ComputePassEncoder.Descriptor) ComputePassEncoder { return enc.vtable.beginComputePass(enc.ptr, descriptor); } pub inline fn beginRenderPass(enc: CommandEncoder, descriptor: *const RenderPassEncoder.Descriptor) RenderPassEncoder { return enc.vtable.beginRenderPass(enc.ptr, descriptor); } pub inline fn clearBuffer(enc: CommandEncoder, buffer: Buffer, offset: u64, size: u64) void { enc.vtable.clearBuffer(enc.ptr, buffer, offset, size); } pub inline fn copyBufferToBuffer( enc: CommandEncoder, source: Buffer, source_offset: u64, destination: Buffer, destination_offset: u64, size: u64, ) void { enc.vtable.copyBufferToBuffer(enc.ptr, source, source_offset, destination, destination_offset, size); } pub inline fn copyBufferToTexture( enc: CommandEncoder, source: *const ImageCopyBuffer, destination: *const ImageCopyTexture, copy_size: *const Extent3D, ) void { enc.vtable.copyBufferToTexture(enc.ptr, source, destination, copy_size); } pub inline fn copyTextureToBuffer( enc: CommandEncoder, source: *const ImageCopyTexture, destination: *const ImageCopyBuffer, copy_size: *const Extent3D, ) void { enc.vtable.copyTextureToBuffer(enc.ptr, source, destination, copy_size); } pub inline fn copyTextureToTexture( enc: CommandEncoder, source: *const ImageCopyTexture, destination: *const ImageCopyTexture, copy_size: *const Extent3D, ) void { enc.vtable.copyTextureToTexture(enc.ptr, source, destination, copy_size); } pub inline fn finish(enc: CommandEncoder, descriptor: ?*const CommandBuffer.Descriptor) CommandBuffer { return enc.vtable.finish(enc.ptr, descriptor); } pub inline fn injectValidationError(enc: CommandEncoder, message: [*:0]const u8) void { enc.vtable.injectValidationError(enc.ptr, message); } pub inline fn insertDebugMarker(enc: CommandEncoder, marker_label: [*:0]const u8) void { enc.vtable.insertDebugMarker(enc.ptr, marker_label); } pub inline fn popDebugGroup(enc: CommandEncoder) void { enc.vtable.popDebugGroup(enc.ptr); } pub inline fn pushDebugGroup(enc: CommandEncoder, group_label: [*:0]const u8) void { enc.vtable.pushDebugGroup(enc.ptr, group_label); } pub inline fn resolveQuerySet( enc: CommandEncoder, query_set: QuerySet, first_query: u32, query_count: u32, destination: Buffer, destination_offset: u64, ) void { enc.vtable.resolveQuerySet(enc.ptr, query_set, first_query, query_count, destination, destination_offset); } pub inline fn setLabel(enc: CommandEncoder, label: [:0]const u8) void { enc.vtable.setLabel(enc.ptr, label); } pub inline fn writeBuffer(pass: RenderPassEncoder, buffer: Buffer, buffer_offset: u64, data: anytype) void { pass.vtable.writeBuffer( pass.ptr, buffer, buffer_offset, @ptrCast(*const u8, &data[0]), @intCast(u64, data.len) * @sizeOf(@TypeOf(std.meta.Elem(data))), ); } pub inline fn writeTimestamp(pass: RenderPassEncoder, query_set: QuerySet, query_index: u32) void { pass.vtable.writeTimestamp(pass.ptr, query_set, query_index); } pub const Descriptor = struct { label: ?[*:0]const u8 = null, }; test { _ = VTable; _ = reference; _ = release; _ = beginComputePass; _ = beginRenderPass; _ = clearBuffer; _ = copyBufferToBuffer; _ = copyBufferToTexture; _ = copyTextureToBuffer; _ = copyTextureToTexture; _ = finish; _ = injectValidationError; _ = insertDebugMarker; _ = popDebugGroup; _ = pushDebugGroup; _ = resolveQuerySet; _ = setLabel; _ = writeBuffer; _ = writeTimestamp; _ = Descriptor; }
gpu/src/CommandEncoder.zig
const std = @import("std"); pub const LispCall = struct { params: std.ArrayList(LispExpr), body: std.ArrayList(LispExpr), }; pub const LispClosure = struct { call: LispCall, interpreter: LispInterpreter, }; pub const LispNativeCall = fn (*LispInterpreter, []LispExpr) anyerror!LispExpr; pub const LispExpr = union(enum) { list: *std.ArrayList(LispExpr), identifier: *std.ArrayList(u8), string: *std.ArrayList(u8), number: isize, t, nil, func: *LispClosure, macro: *LispCall, native_func: usize, native_macro: usize, pub fn deinit(self: LispExpr) void { switch (self) { .list => |list| list.deinit(), .identifier, .string => |string| string.deinit(), .macro => |call| { call.params.deinit(); call.body.deinit(); }, .func => |closure| { closure.call.params.deinit(); closure.call.body.deinit(); closure.interpreter.deinit(); }, .number, .t, .nil, .native_func, .native_macro => {}, } } pub fn format( self: LispExpr, fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { switch (self) { .list => |list| { _ = try writer.write("("); if (list.items.len > 0) { for (list.items[0 .. list.items.len - 1]) |expr| try writer.print("{} ", .{expr}); try writer.print("{}", .{list.items[list.items.len - 1]}); } _ = try writer.write(")"); }, .identifier => |identifier| try writer.print("{s}", .{identifier.items}), .string => |string| { _ = try writer.write("\""); for (string.items) |c| { switch (c) { '"' => _ = try writer.write("\\\""), '\n' => _ = try writer.write("\\n"), '\t' => _ = try writer.write("\\t"), else => try writer.writeByte(c), } } _ = try writer.write("\""); }, .number => |number| try writer.print("{d:}", .{number}), .t => _ = try writer.write("t"), .nil => _ = try writer.write("nil"), .func => |closure| { _ = try writer.write("(func ("); if (closure.call.params.items.len > 0) for (closure.call.params.items) |param| try writer.print("{} ", .{param}); _ = try writer.write(") ("); if (closure.interpreter.scope.count() > 0) { var it = closure.interpreter.scope.iterator(); while (it.next()) |capture| try writer.print("{s}={s} ", .{capture.key, capture.value}); } _ = try writer.write(")"); if (closure.call.body.items.len > 0) for (closure.call.body.items) |expr| try writer.print("\n{}", .{expr}); _ = try writer.write(")"); }, .macro => |call| { _ = try writer.write("(macro ("); if (call.params.items.len > 0) for (call.params.items) |param| try writer.print("{} ", .{param}); _ = try writer.write(")"); if (call.body.items.len > 0) for (call.body.items) |expr| try writer.print("\n{}", .{expr}); _ = try writer.write(")"); }, .native_func => |native_call| try writer.print("func@{}", .{native_call}), .native_macro => |native_call| try writer.print("macro@{}", .{native_call}), } } }; pub const LispInterpreter = struct { allocator: *std.mem.Allocator, heap: std.ArrayList(LispExpr), scope: std.StringHashMap(LispExpr), parent: ?*LispInterpreter, pub fn init(allocator: *std.mem.Allocator, parent: ?*LispInterpreter) LispInterpreter { return LispInterpreter{ .allocator = allocator, .heap = std.ArrayList(LispExpr).init(allocator), .scope = std.StringHashMap(LispExpr).init(allocator), .parent = parent, }; } pub fn deinit(self: *LispInterpreter) void { self.scope.deinit(); for (self.heap.items) |branch| { branch.deinit(); switch (branch) { .number, .t, .nil, .native_func, .native_macro => {}, .list => |list| self.allocator.destroy(list), .identifier, .string => |list| self.allocator.destroy(list), .macro => |call| self.allocator.destroy(call), .func => |closure| self.allocator.destroy(closure), } } self.heap.deinit(); } pub fn eval(self: *LispInterpreter, expr: LispExpr) anyerror!LispExpr { switch (expr) { .number, .t, .nil, .string, .func, .macro, .native_func, .native_macro => return expr, .list => |list| { if (list.items.len == 0) return expr; const called = try self.eval(list.items[0]); switch (called) { .native_macro => |native_call| return try @intToPtr(LispNativeCall, native_call)(self, list.items[1..]), .native_func => |native_call| { var args_list = try std.ArrayList(LispExpr).initCapacity(self.allocator, list.items.len - 1); defer args_list.deinit(); for (list.items[1..]) |arg| try args_list.append(try self.eval(arg)); return try @intToPtr(LispNativeCall, native_call)(self, args_list.items); }, .macro => |macro| { if (macro.params.items.len != list.items.len - 1) return error.InterpreterMacroParameterMismatch; if (macro.body.items.len < 1) return error.InterpreterMacroNoBody; var sub_interpreter = LispInterpreter.init(self.allocator, self); defer sub_interpreter.deinit(); for (macro.params.items) |param, i| switch (param) { .identifier => |identifier| try sub_interpreter.scope.put(identifier.items, list.items[i + 1]), else => return error.InterpreterMacroInvalidParameter, }; for (macro.body.items[0 .. macro.body.items.len - 1]) |body_expr| _ = try sub_interpreter.eval(body_expr); return try self.clone(try sub_interpreter.eval(macro.body.items[macro.body.items.len - 1])); }, .func => |func| { if (func.call.params.items.len != list.items.len - 1) return error.InterpreterFuncParameterMismatch; if (func.call.body.items.len < 1) return error.InterpreterFuncNoBody; var sub_interpreter = LispInterpreter.init(self.allocator, self); defer sub_interpreter.deinit(); var it = func.interpreter.scope.iterator(); while (it.next()) |entry| try sub_interpreter.scope.put(entry.key, try sub_interpreter.clone(entry.value)); for (func.call.params.items) |param, i| switch (param) { .identifier => |identifier| try sub_interpreter.scope.put(identifier.items, try sub_interpreter.eval(list.items[i + 1])), else => return error.InterpreterFuncInvalidParameter, }; for (func.call.body.items[0 .. func.call.body.items.len - 1]) |body_expr| _ = try sub_interpreter.eval(body_expr); return try self.clone(try sub_interpreter.eval(func.call.body.items[func.call.body.items.len - 1])); }, else => return error.InterpreterNoSuchFunction, } }, .identifier => |identifier| { if (self.get(identifier.items)) |value| return value; return error.InterpreterNoSuchIdentifier; }, } } pub fn get(self: LispInterpreter, identifier: []const u8) ?LispExpr { if (self.scope.getEntry(identifier)) |entry| return entry.value; if (self.parent) |real_parent| return real_parent.get(identifier); return null; } pub fn store(self: *LispInterpreter, expr: LispExpr) !LispExpr { switch (expr) { .list, .string, .identifier, .func, .macro => try self.heap.append(expr), .number, .t, .nil, .native_func, .native_macro => return error.StoreNotHeapAllocated, } return expr; } pub fn clone(self: *LispInterpreter, expr: LispExpr) anyerror!LispExpr { switch (expr) { .number, .t, .nil, .native_func, .native_macro => return expr, .string, .identifier => |string| { var copy = try self.allocator.create(std.ArrayList(u8)); errdefer self.allocator.destroy(copy); copy.* = std.ArrayList(u8).init(self.allocator); errdefer copy.deinit(); try copy.appendSlice(string.items); switch (expr) { .string => return self.store(LispExpr{ .string = copy }), .identifier => return self.store(LispExpr{ .identifier = copy }), else => unreachable, } }, .list => |list| { var copy = try self.allocator.create(std.ArrayList(LispExpr)); errdefer self.allocator.destroy(copy); copy.* = try std.ArrayList(LispExpr).initCapacity(self.allocator, list.items.len); errdefer copy.deinit(); for (list.items) |branch| try copy.append(try self.clone(branch)); return self.store(LispExpr{ .list = copy }); }, .macro => |call| { var copy = try self.allocator.create(LispCall); errdefer self.allocator.destroy(copy); copy.params = try std.ArrayList(LispExpr).initCapacity(self.allocator, call.params.items.len); errdefer copy.params.deinit(); for (call.params.items) |branch| try copy.params.append(try self.clone(branch)); copy.body = try std.ArrayList(LispExpr).initCapacity(self.allocator, call.body.items.len); errdefer copy.body.deinit(); for (call.body.items) |branch| try copy.body.append(try self.clone(branch)); return self.store(LispExpr{ .macro = copy }); }, .func => |closure| { var copy = try self.allocator.create(LispClosure); errdefer self.allocator.destroy(copy); copy.call.params = try std.ArrayList(LispExpr).initCapacity(self.allocator, closure.call.params.items.len); errdefer copy.call.params.deinit(); for (closure.call.params.items) |branch| try copy.call.params.append(try self.clone(branch)); copy.call.body = try std.ArrayList(LispExpr).initCapacity(self.allocator, closure.call.body.items.len); errdefer copy.call.body.deinit(); for (closure.call.body.items) |branch| try copy.call.body.append(try self.clone(branch)); copy.interpreter = LispInterpreter.init(self.allocator, null); errdefer copy.interpreter.deinit(); try copy.interpreter.heap.ensureCapacity(closure.interpreter.heap.items.len); for (closure.interpreter.heap.items) |value| try copy.interpreter.heap.append(try self.clone(value)); try copy.interpreter.scope.ensureCapacity(closure.interpreter.scope.count()); var it = closure.interpreter.scope.iterator(); while (it.next()) |entry| try copy.interpreter.scope.put(entry.key, try self.clone(entry.value)); return self.store(LispExpr{ .func = copy }); }, } } };
src/interpret.zig
usingnamespace @import("raylib"); pub fn main() anyerror!void { // Initialization //-------------------------------------------------------------------------------------- const screenWidth = 800; const screenHeight = 450; InitWindow(screenWidth, screenHeight, "raylib-zig [core] example - mouse input"); var ballPosition = Vector2 { .x = -100.0, .y = -100.0 }; var ballColor = DARKBLUE; SetTargetFPS(60); // Set our game to run at 60 frames-per-second //-------------------------------------------------------------------------------------- // Main game loop while (!WindowShouldClose()) // Detect window close button or ESC key { // Update //---------------------------------------------------------------------------------- ballPosition = GetMousePosition(); ballPosition.x = @intToFloat(f32, GetMouseX()); ballPosition.y = @intToFloat(f32, GetMouseY()); if (IsMouseButtonPressed(MouseButton.MOUSE_LEFT_BUTTON)) { ballColor = MAROON; } else if (IsMouseButtonPressed(MouseButton.MOUSE_MIDDLE_BUTTON)) { ballColor = LIME; } else if (IsMouseButtonPressed(MouseButton.MOUSE_RIGHT_BUTTON)) { ballColor = DARKBLUE; } //---------------------------------------------------------------------------------- // Draw //---------------------------------------------------------------------------------- BeginDrawing(); ClearBackground(RAYWHITE); DrawCircle(@floatToInt(c_int, ballPosition.x), @floatToInt(c_int, ballPosition.y), 50, ballColor); //DrawCircleV(ballPosition, 40, ballColor); DrawText("move ball with mouse and click mouse button to change color", 10, 10, 20, DARKGRAY); EndDrawing(); //---------------------------------------------------------------------------------- } // De-Initialization //-------------------------------------------------------------------------------------- CloseWindow(); // Close window and OpenGL context //-------------------------------------------------------------------------------------- }
examples/core/input_mouse.zig
const std = @import("std"); const fs = std.fs; const sort = std.sort; const asc_u32 = sort.asc(u32); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = &gpa.allocator; const input = try fs.cwd().readFileAlloc(allocator, "data/input_10_1.txt", std.math.maxInt(usize)); var lines = std.mem.tokenize(input, "\n"); var vals = std.ArrayList(u32).init(allocator); defer vals.deinit(); try vals.append(0); // Outlet while (lines.next()) |raw_line| { var line = std.mem.trim(u8, raw_line, " \r\n"); if (line.len == 0) break; try vals.append(try std.fmt.parseInt(u32, line, 10)); } sort.sort(u32, vals.items, {}, asc_u32); try vals.append(vals.items[vals.items.len - 1] + 3); // Device { // Solution 1 var changes1: u32 = 0; var changes3: u32 = 0; // Includes last change { var i: usize = 0; while (i < vals.items.len - 1) : (i += 1) { const diff = vals.items[i + 1] - vals.items[i]; std.debug.assert(diff <= 3); if (diff == 1) { changes1 += 1; } else if (diff == 3) { changes3 += 1; } // std.debug.print("{} -> {} - Diff: {} - Changes: (1) = {}, (2) = {}\n", // .{vals.items[i], vals.items[i + 1], diff, changes1, changes3}); }} std.debug.print("Day 10 - Solution 1: {}\n", .{changes1 * changes3}); } { // Solution 2 var choices = std.ArrayList(u64).init(allocator); defer choices.deinit(); try choices.resize(vals.items.len); std.mem.set(u64, choices.items, 0); var i: usize = vals.items.len - 1; choices.items[i] = 1; while (true) { i -= 1; const outlet = vals.items[i]; var j: usize = 1; const end = std.math.min(4, vals.items.len - i); while (j < end) : (j += 1) { const diff = vals.items[i + j] - outlet; if (diff <= 3) { choices.items[i] += choices.items[i + j]; } } if (i == 0) break; } std.debug.print("Day 10 - Solution 2: {}\n", .{choices.items[0]}); } }
2020/src/day_10.zig
const std = @import("std"); // Configure these (required): const human_readable_app_name = "Ziggy"; const app_name = "ziggy"; const package_name = "net.random_projects." ++ app_name; const android_fullscreen = false; const permissions = [_][]const u8{ "android.permission.SET_RELEASE_APP", "android.permission.RECORD_AUDIO", }; // Adjust these to your system: const android_sdk_root = "/usr/local/share/android-sdk"; const android_ndk_root = "/usr/local/share/android-ndk"; const android_build_tools = android_sdk_root ++ "/build-tools/28.0.3"; const keytool = "keytool"; const adb = "adb"; const jarsigner = "jarsigner"; // These are tweakable, but are not required to be touched const apk_file = app_name ++ ".apk"; const android_version = 29; const android_target = android_version; const aapt = android_build_tools ++ "/aapt"; const zipalign = android_build_tools ++ "/zipalign"; const keystore_file = "debug.keystore"; const keystore_alias = "standkey"; const keystore_storepass = "<PASSWORD>"; const keystore_keypass = "<PASSWORD>456"; const android_version_str = blk: { comptime var buf: [std.math.log10(android_version) + 3]u8 = undefined; break :blk std.fmt.bufPrint(&buf, "{d}", .{android_version}) catch unreachable; }; const android_target_str = blk: { comptime var buf: [std.math.log10(android_target) + 3]u8 = undefined; break :blk std.fmt.bufPrint(&buf, "{d}", .{android_target}) catch unreachable; }; fn initAppCommon(b: *std.build.Builder, output_name: []const u8, target: std.zig.CrossTarget, mode: std.builtin.Mode) *std.build.LibExeObjStep { const exe = b.addSharedLibrary(output_name, "./src/main.zig", .{ .versioned = .{ .major = 1, .minor = 0, .patch = 0, }, }); exe.force_pic = true; exe.link_function_sections = true; exe.bundle_compiler_rt = true; exe.strip = (mode == .ReleaseSmall); exe.defineCMacro("ANDROID"); exe.addIncludeDir("./src"); exe.addIncludeDir(android_ndk_root ++ "/sysroot/usr/include"); for (app_libs) |lib| { exe.linkSystemLibrary(lib); } exe.addBuildOption(comptime_int, "android_sdk_version", android_version); exe.addBuildOption(bool, "fullscreen", android_fullscreen); exe.linkLibC(); exe.setBuildMode(mode); exe.setTarget(target); return exe; } pub fn build(b: *std.build.Builder) !void { const aarch64_target = std.zig.CrossTarget.parse(.{ .arch_os_abi = "aarch64-linux", .cpu_features = "baseline+v8a", }) catch unreachable; const arm_target = std.zig.CrossTarget.parse(.{ .arch_os_abi = "arm-linux", .cpu_features = "baseline+v7a", }) catch unreachable; const x86_target = std.zig.CrossTarget.parse(.{ .arch_os_abi = "i386-linux", .cpu_features = "baseline", }) catch unreachable; const x86_64_target = std.zig.CrossTarget.parse(.{ .arch_os_abi = "x86_64-linux", .cpu_features = "baseline", }) catch unreachable; // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const aarch64_exe = initAppCommon(b, app_name, aarch64_target, mode); const arm_exe = initAppCommon(b, app_name, arm_target, mode); const x86_exe = initAppCommon(b, app_name, x86_target, mode); const x86_64_exe = initAppCommon(b, app_name, x86_64_target, mode); aarch64_exe.addLibPath(android_ndk_root ++ "/platforms/android-" ++ android_version_str ++ "/arch-arm64/usr/lib"); arm_exe.addLibPath(android_ndk_root ++ "/platforms/android-" ++ android_version_str ++ "/arch-arm/usr/lib"); x86_exe.addLibPath(android_ndk_root ++ "/platforms/android-" ++ android_version_str ++ "/arch-x86/usr/lib"); x86_64_exe.addLibPath(android_ndk_root ++ "/platforms/android-" ++ android_version_str ++ "/arch-x86_64/usr/lib64"); aarch64_exe.addIncludeDir(android_ndk_root ++ "/sysroot/usr/include/aarch64-linux-android"); aarch64_exe.libc_file = "./libc/arm64.conf"; aarch64_exe.output_dir = "./apk/lib/arm64-v8a"; arm_exe.addIncludeDir(android_ndk_root ++ "/sysroot/usr/include/arm-linux-androideabi"); arm_exe.libc_file = "./libc/arm.conf"; arm_exe.output_dir = "./apk/lib/armeabi"; x86_exe.addIncludeDir(android_ndk_root ++ "/sysroot/usr/include/i686-linux-android"); x86_exe.libc_file = "./libc/x86.conf"; x86_exe.output_dir = "./apk/lib/x86"; x86_64_exe.addIncludeDir(android_ndk_root ++ "/sysroot/usr/include/x86_64-linux-android"); x86_64_exe.libc_file = "./libc/x86_64.conf"; x86_64_exe.output_dir = "./apk/lib/x86_64"; try std.fs.cwd().writeFile("./resources/values/strings.xml", blk: { var buf = std.ArrayList(u8).init(b.allocator); errdefer buf.deinit(); var writer = buf.writer(); try writer.writeAll( \\<?xml version="1.0" encoding="utf-8"?> \\<resources> \\ ); try writer.print( \\ <string name="app_name">{s}</string> \\ <string name="lib_name">{s}</string> \\ <string name="package_name">{s}</string> \\ , .{ human_readable_app_name, app_name, package_name, }); try writer.writeAll( \\</resources> \\ ); break :blk buf.toOwnedSlice(); }); const manifest_step = b.addWriteFile("AndroidManifest.xml", blk: { var buf = std.ArrayList(u8).init(b.allocator); errdefer buf.deinit(); var writer = buf.writer(); @setEvalBranchQuota(1_000_000); try 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}"> \\ , .{package_name}); for (permissions) |perm| { try writer.print( \\ <uses-permission android:name="{s}"/> \\ , .{perm}); } try writer.print( \\ <application android:debuggable="true" android:hasCode="false" android:label="@string/app_name" {s} tools:replace="android:icon,android:theme,android:allowBackup,label" android:icon="@mipmap/icon" android:requestLegacyExternalStorage="true"> \\ <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> \\ , .{ if (android_fullscreen) "android:theme=\"@android:style/Theme.NoTitleBar.Fullscreen\"" else "", }); break :blk buf.toOwnedSlice(); }); std.fs.cwd().deleteFile("ziggy.apk") catch {}; const make_unsigned_apk = b.addSystemCommand(&[_][]const u8{ aapt, "package", "-f", // force overwrite of existing files "-F", // specify the apk file to output "incomplete.apk", "-I", // add an existing package to base include set android_sdk_root ++ "/platforms/android-" ++ android_version_str ++ "/android.jar", "-M", // specify full path to AndroidManifest.xml to include in zip }); make_unsigned_apk.addWriteFileArg(manifest_step, "AndroidManifest.xml"); make_unsigned_apk.addArgs(&[_][]const u8{ "-S", // directory in which to find resources. Multiple directories will be scanned and the first match found (left to right) will take precedence "./resources", "-A", // additional directory in which to find raw asset files "./assets", "-v", "--target-sdk-version", android_target_str, }); make_unsigned_apk.step.dependOn(&aarch64_exe.step); make_unsigned_apk.step.dependOn(&arm_exe.step); make_unsigned_apk.step.dependOn(&x86_64_exe.step); // make_unsigned_apk.step.dependOn(&x86_exe.step); const unpack_apk = b.addSystemCommand(&[_][]const u8{ "unzip", "-o", "incomplete.apk", "-d", "./apk", }); unpack_apk.step.dependOn(&make_unsigned_apk.step); const repack_apk = b.addSystemCommand(&[_][]const u8{ "zip", "-D9r", "../unsigned.apk", ".", }); repack_apk.cwd = "./apk"; repack_apk.step.dependOn(&unpack_apk.step); const sign_apk = b.addSystemCommand(&[_][]const u8{ jarsigner, "-sigalg", "SHA1withRSA", "-digestalg", "SHA1", "-verbose", "-keystore", keystore_file, "-storepass", keystore_storepass, "unsigned.apk", keystore_alias, }); sign_apk.step.dependOn(&repack_apk.step); const align_apk = b.addSystemCommand(&[_][]const u8{ zipalign, "-v", "4", "unsigned.apk", apk_file, }); align_apk.step.dependOn(&sign_apk.step); b.getInstallStep().dependOn(&align_apk.step); const push_apk = b.addSystemCommand(&[_][]const u8{ adb, "install", apk_file, }); push_apk.step.dependOn(&align_apk.step); const push_step = b.step("push", "Installs the APK on the connected android system."); push_step.dependOn(&push_apk.step); const run_apk = b.addSystemCommand(&[_][]const u8{ adb, "shell", "am", "start", "-n", package_name ++ "/android.app.NativeActivity", }); run_apk.step.dependOn(&push_apk.step); const run_step = b.step("run", "Runs the APK on the connected android system."); run_step.dependOn(&run_apk.step); const make_keystore = b.addSystemCommand(&[_][]const u8{ keytool, "-genkey", "-v", "-keystore", keystore_file, "-alias", keystore_alias, "-keyalg", "RSA", "-keysize", "2048", "-validity", "10000", "-storepass", keystore_storepass, "-keypass", keystore_keypass, "-dname", "CN=example.com, OU=ID, O=Example, L=Doe, S=John, C=GB", }); const keystore_step = b.step("keystore", "Creates a new dummy keystore for testing"); keystore_step.dependOn(&make_keystore.step); } const app_libs = [_][]const u8{ "GLESv3", "EGL", "android", "log", };
build.zig
const std = @import("std"); // Parse flags from an ArgIterator according to the provided Flags struct. pub fn parse(comptime Flags: type, args: *std.process.ArgIterator) !Flags { std.debug.assert(args.skip()); return parseIter(Flags, args, argPeek, argNext); } fn argPeek(args: *std.process.ArgIterator) ?[]const u8 { var argsCopy = args.*; return argsCopy.nextPosix() orelse null; } fn argNext(args: *std.process.ArgIterator) ?[]const u8 { return std.process.ArgIterator.nextPosix(args) orelse null; } pub fn parseIter( comptime Flags: type, context: anytype, peek: fn (@TypeOf(context)) ?[]const u8, next: fn (@TypeOf(context)) ?[]const u8, ) !Flags { var flags: Flags = .{}; while (peek(context)) |arg| { if (arg.len < 2 or !std.mem.startsWith(u8, arg, "-")) break; std.debug.assert(arg.ptr == (next(context) orelse unreachable).ptr); if (std.mem.eql(u8, arg, "--")) break; arg_flags: for (arg[1..]) |opt, i| { inline for (std.meta.fields(Flags)) |field| { if (field.name.len != 1) { @compileError("An argument name must be a single character"); } if (opt == field.name[0]) { const T = Unwrap(field.field_type); if (T == bool) { @field(flags, field.name) = true; } else { const flag_arg = if (i + 2 < arg.len) arg[i + 2 ..] else next(context) orelse return error.MissingArgument; if (T == []const u8) { @field(flags, field.name) = flag_arg; } else { @field(flags, field.name) = switch (@typeInfo(T)) { .Int => try std.fmt.parseInt(T, flag_arg, 10), .Float => try std.fmt.parseFloat(T, flag_arg), else => @compileError("Unsupported flag type '" ++ @typeName(field.field_type) ++ "'"), }; } // Ensure we don't try to parse any more flags from this arg break :arg_flags; } break; } } else { return error.InvalidFlag; } } } return flags; } fn Unwrap(comptime T: type) type { return if (@typeInfo(T) == .Optional) std.meta.Child(T) else T; } fn parseTest(comptime Flags: type, args: []const []const u8) !Flags { var argsV = args; return parseIter(Flags, &argsV, testPeek, testNext); } fn testPeek(args: *[]const []const u8) ?[]const u8 { if (args.*.len == 0) return null; return args.*[0]; } fn testNext(args: *[]const []const u8) ?[]const u8 { if (testPeek(args)) |arg| { args.* = args.*[1..]; return arg; } else { return null; } } const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const expectEqualStrings = std.testing.expectEqualStrings; test "bool flag - default" { const flags = try parseTest( struct { b: bool = false }, &.{}, ); try expect(!flags.b); } test "bool flag - specified" { const flags = try parseTest( struct { b: bool = false }, &.{"-b"}, ); try expect(flags.b); } test "string flag - default" { const flags = try parseTest( struct { s: []const u8 = "default value" }, &.{}, ); try expectEqualStrings(flags.s, "default value"); } test "string flag - separated" { const flags = try parseTest( struct { s: []const u8 = "default value" }, &.{ "-s", "separate value" }, ); try expectEqualStrings(flags.s, "separate value"); } test "string flag - combined" { const flags = try parseTest( struct { s: []const u8 = "default value" }, &.{"-scombined value"}, ); try expectEqualStrings(flags.s, "combined value"); } test "int flag - default" { const flags = try parseTest( struct { s: u8 = 7 }, &.{}, ); try expectEqual(flags.s, 7); } test "int flag - separated" { const flags = try parseTest( struct { s: u8 = 7 }, &.{ "-s", "40" }, ); try expectEqual(flags.s, 40); } test "int flag - combined" { const flags = try parseTest( struct { s: u8 = 7 }, &.{"-s70"}, ); try expectEqual(flags.s, 70); } test "float flag - default" { const flags = try parseTest( struct { s: f32 = 9.6 }, &.{}, ); try expectEqual(flags.s, 9.6); } test "float flag - separated" { const flags = try parseTest( struct { s: f32 = 9.6 }, &.{ "-s", "4.2" }, ); try expectEqual(flags.s, 4.2); } test "float flag - combined" { const flags = try parseTest( struct { s: f32 = 9.6 }, &.{"-s0.36"}, ); try expectEqual(flags.s, 0.36); }
src/lib/flag.zig
const std = @import("std"); const glfw = @import("glfw"); const zt = @import("../zt.zig"); const gl = @import("gl"); usingnamespace gl; usingnamespace @import("imgui"); // OpenGL Data var g_GlVersion: GLuint = 0; // Extracted at runtime using GL_MAJOR_VERSION, GL_MINOR_VERSION queries. var g_GlslVersionStringMem: [32]u8 = undefined; // Specified by user or detected based on compile time GL settings. var g_GlslVersionString: []u8 = &g_GlslVersionStringMem; // slice of g_GlslVersionStringMem pub var g_FontTexture: c_uint = 0; var g_ShaderHandle: c_uint = 0; var g_VertHandle: c_uint = 0; var g_FragHandle: c_uint = 0; var g_AttribLocationTex: i32 = 0; var g_AttribLocationProjMtx: i32 = 0; // Uniforms location var g_AttribLocationVtxPos: i32 = 0; var g_AttribLocationVtxUV: i32 = 0; var g_AttribLocationVtxColor: i32 = 0; // Vertex attributes location var g_VboHandle: c_uint = 0; var g_ElementsHandle: c_uint = 0; // Functions pub fn init(glsl_version_opt: ?[:0]const u8) void { var ctx = igCreateContext(null); igSetCurrentContext(ctx); // Query for GL version var major: GLint = undefined; var minor: GLint = undefined; glGetIntegerv(GL_MAJOR_VERSION, &major); glGetIntegerv(GL_MINOR_VERSION, &minor); g_GlVersion = @intCast(GLuint, major * 1000 + minor); // Setup back-end capabilities flags var io = igGetIO(); io.*.BackendRendererName = "imgui_impl_opengl3"; io.*.IniFilename = "workspace"; // Sensible memory-friendly initial mouse position. io.*.MousePos = .{ .x = 0, .y = 0 }; // Store GLSL version string so we can refer to it later in case we recreate shaders. // Note: GLSL version is NOT the same as GL version. Leave this to NULL if unsure. var glsl_version: [:0]const u8 = undefined; if (glsl_version_opt) |value| { glsl_version = value; } else { glsl_version = "#version 130"; } std.debug.assert(glsl_version.len + 2 < g_GlslVersionStringMem.len); std.mem.copy(u8, g_GlslVersionStringMem[0..glsl_version.len], glsl_version); g_GlslVersionStringMem[glsl_version.len] = '\n'; g_GlslVersionStringMem[glsl_version.len + 1] = 0; g_GlslVersionString = g_GlslVersionStringMem[0..glsl_version.len]; // Make a dummy GL call (we don't actually need the result) // IF YOU GET A CRASH HERE: it probably means that you haven't initialized the OpenGL function loader used by this code. // Desktop OpenGL 3/4 need a function loader. See the IMGUI_IMPL_OPENGL_LOADER_xxx explanation above. var current_texture: GLint = undefined; glGetIntegerv(GL_TEXTURE_BINDING_2D, &current_texture); CreateDeviceObjects(); io.*.KeyMap[ImGuiKey_Tab] = glfw.GLFW_KEY_TAB; io.*.KeyMap[ImGuiKey_Home] = glfw.GLFW_KEY_HOME; io.*.KeyMap[ImGuiKey_Insert] = glfw.GLFW_KEY_INSERT; io.*.KeyMap[ImGuiKey_KeyPadEnter] = glfw.GLFW_KEY_KP_ENTER; io.*.KeyMap[ImGuiKey_Escape] = glfw.GLFW_KEY_ESCAPE; io.*.KeyMap[ImGuiKey_Backspace] = glfw.GLFW_KEY_BACKSPACE; io.*.KeyMap[ImGuiKey_End] = glfw.GLFW_KEY_END; io.*.KeyMap[ImGuiKey_Enter] = glfw.GLFW_KEY_ENTER; io.*.KeyMap[ImGuiKey_LeftArrow] = glfw.GLFW_KEY_LEFT; io.*.KeyMap[ImGuiKey_RightArrow] = glfw.GLFW_KEY_RIGHT; io.*.KeyMap[ImGuiKey_UpArrow] = glfw.GLFW_KEY_UP; io.*.KeyMap[ImGuiKey_DownArrow] = glfw.GLFW_KEY_DOWN; io.*.KeyMap[ImGuiKey_PageUp] = glfw.GLFW_KEY_PAGE_UP; io.*.KeyMap[ImGuiKey_PageDown] = glfw.GLFW_KEY_PAGE_DOWN; io.*.KeyMap[ImGuiKey_Space] = glfw.GLFW_KEY_SPACE; io.*.KeyMap[ImGuiKey_V] = glfw.GLFW_KEY_V; io.*.KeyMap[ImGuiKey_X] = glfw.GLFW_KEY_X; io.*.KeyMap[ImGuiKey_Z] = glfw.GLFW_KEY_Z; io.*.KeyMap[ImGuiKey_A] = glfw.GLFW_KEY_A; io.*.KeyMap[ImGuiKey_C] = glfw.GLFW_KEY_C; } pub fn Shutdown() void { DestroyDeviceObjects(); } fn SetupRenderState(draw_data: *ImDrawData, fb_width: c_int, fb_height: c_int, vertex_array_object: GLuint) void { // Setup render state: alpha-blending enabled, no face culling, no depth testing, scissor enabled, polygon fill glEnable(GL_BLEND); glBlendEquation(GL_FUNC_ADD); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glDisable(GL_CULL_FACE); glDisable(GL_DEPTH_TEST); glEnable(GL_SCISSOR_TEST); if (@hasDecl(gl, "glPolygonMode")) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); } // Setup viewport, orthographic projection matrix // Our visible imgui space lies from draw_data.DisplayPos (top left) to draw_data.DisplayPos+data_data.DisplaySize (bottom right). DisplayPos is (0,0) for single viewport apps. glViewport(0, 0, @intCast(GLsizei, fb_width), @intCast(GLsizei, fb_height)); var L = draw_data.DisplayPos.x; var R = draw_data.DisplayPos.x + draw_data.DisplaySize.x; var T = draw_data.DisplayPos.y; var B = draw_data.DisplayPos.y + draw_data.DisplaySize.y; const ortho_projection = [4][4]f32{ [4]f32{ 2.0 / (R - L), 0.0, 0.0, 0.0 }, [4]f32{ 0.0, 2.0 / (T - B), 0.0, 0.0 }, [4]f32{ 0.0, 0.0, -1.0, 0.0 }, [4]f32{ (R + L) / (L - R), (T + B) / (B - T), 0.0, 1.0 }, }; var shader = zt.gl.Shader.from(g_ShaderHandle); shader.bind(); glUniform1i(g_AttribLocationTex, 0); glUniformMatrix4fv(g_AttribLocationProjMtx, 1, GL_FALSE, &ortho_projection[0][0]); if (@hasDecl(gl, "glBindSampler")) { glBindSampler(0, 0); } glBindVertexArray(vertex_array_object); glBindBuffer(GL_ARRAY_BUFFER, g_VboHandle); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g_ElementsHandle); glEnableVertexAttribArray(@intCast(c_uint, g_AttribLocationVtxPos)); glEnableVertexAttribArray(@intCast(c_uint, g_AttribLocationVtxUV)); glEnableVertexAttribArray(@intCast(c_uint, g_AttribLocationVtxColor)); glVertexAttribPointer( @intCast(c_uint, g_AttribLocationVtxPos), 2, GL_FLOAT, GL_FALSE, @sizeOf(ImDrawVert), @intToPtr(?*c_void, @offsetOf(ImDrawVert, "pos")), ); glVertexAttribPointer( @intCast(c_uint, g_AttribLocationVtxUV), 2, GL_FLOAT, GL_FALSE, @sizeOf(ImDrawVert), @intToPtr(?*c_void, @offsetOf(ImDrawVert, "uv")), ); glVertexAttribPointer( @intCast(c_uint, g_AttribLocationVtxColor), 4, GL_UNSIGNED_BYTE, GL_TRUE, @sizeOf(ImDrawVert), @intToPtr(?*c_void, @offsetOf(ImDrawVert, "col")), ); } fn getGLInt(name: GLenum) GLint { var value: GLint = undefined; glGetIntegerv(name, &value); return value; } fn getGLInts(name: GLenum, comptime N: comptime_int) [N]GLint { var value: [N]GLint = undefined; glGetIntegerv(name, &value); return value; } pub fn RenderDrawData(draw_data: *ImDrawData) void { // Avoid rendering when minimized, scale coordinates for retina displays (screen coordinates != framebuffer coordinates) var fb_width = @floatToInt(c_int, draw_data.DisplaySize.x * draw_data.FramebufferScale.x); var fb_height = @floatToInt(c_int, draw_data.DisplaySize.y * draw_data.FramebufferScale.y); if (fb_width <= 0 or fb_height <= 0) return; var vertex_array_object: GLuint = 0; glGenVertexArrays(1, &vertex_array_object); SetupRenderState(draw_data, fb_width, fb_height, vertex_array_object); var clip_off = draw_data.DisplayPos; // (0,0) unless using multi-viewports var clip_scale = draw_data.FramebufferScale; // (1,1) unless using retina display which are often (2,2) if (draw_data.CmdListsCount > 0) { for (draw_data.CmdLists.?[0..@intCast(usize, draw_data.CmdListsCount)]) |cmd_list| { // Upload vertex/index buffers glBufferData(GL_ARRAY_BUFFER, @intCast(GLsizeiptr, cmd_list.*.VtxBuffer.Size * @sizeOf(ImDrawVert)), cmd_list.*.VtxBuffer.Data, GL_STREAM_DRAW); glBufferData(GL_ELEMENT_ARRAY_BUFFER, @intCast(GLsizeiptr, cmd_list.*.IdxBuffer.Size * @sizeOf(ImDrawIdx)), cmd_list.*.IdxBuffer.Data, GL_STREAM_DRAW); for (cmd_list.*.CmdBuffer.Data[0..@intCast(usize, cmd_list.*.CmdBuffer.Size)]) |pcmd| { if (pcmd.UserCallback) |fnPtr| { fnPtr(cmd_list, &pcmd); } else { // Project scissor/clipping rectangles into framebuffer space var clip_rect = ImVec4{ .x = (pcmd.ClipRect.x - clip_off.x) * clip_scale.x, .y = (pcmd.ClipRect.y - clip_off.y) * clip_scale.y, .z = (pcmd.ClipRect.z - clip_off.x) * clip_scale.x, .w = (pcmd.ClipRect.w - clip_off.y) * clip_scale.y, }; if (clip_rect.x < @intToFloat(f32, fb_width) and clip_rect.y < @intToFloat(f32, fb_height) and clip_rect.z >= 0.0 and clip_rect.w >= 0.0) { glScissor(@floatToInt(c_int, clip_rect.x), fb_height - @floatToInt(c_int, clip_rect.w), @floatToInt(c_int, clip_rect.z - clip_rect.x), @floatToInt(c_int, clip_rect.w - clip_rect.y)); // Bind texture, Draw var texture = zt.gl.Texture.from(@intCast(GLuint, @ptrToInt(pcmd.TextureId)), false); texture.bind(); if (g_GlVersion >= 3200) { glDrawElementsBaseVertex( GL_TRIANGLES, @intCast(GLsizei, pcmd.ElemCount), if (@sizeOf(ImDrawIdx) == 2) GL_UNSIGNED_SHORT else GL_UNSIGNED_INT, @intToPtr(?*const c_void, pcmd.IdxOffset * @sizeOf(ImDrawIdx)), @intCast(GLint, pcmd.VtxOffset), ); } else { glDrawElements( GL_TRIANGLES, @intCast(GLsizei, pcmd.ElemCount), if (@sizeOf(ImDrawIdx) == 2) GL_UNSIGNED_SHORT else GL_UNSIGNED_INT, @intToPtr(?*const c_void, pcmd.IdxOffset * @sizeOf(ImDrawIdx)), ); } } } } } } // Destroy the temporary VAO glDeleteVertexArrays(1, &vertex_array_object); glScissor(0, 0, fb_width, fb_height); } fn CreateFontsTexture() bool { // Build texture atlas const io = igGetIO(); var pixels: [*c]u8 = undefined; var width: i32 = undefined; var height: i32 = undefined; ImFontAtlas_GetTexDataAsRGBA32(io.*.Fonts, &pixels, &width, &height, null); // Load as RGBA 32-bit (75% of the memory is wasted, but default font is so small) because it is more likely to be compatible with user's existing shaders. If your ImTextureId represent a higher-level concept than just a GL texture id, consider calling GetTexDataAsAlpha8() instead to save on GPU memory. // Upload texture to graphics system glGenTextures(1, &g_FontTexture); glBindTexture(GL_TEXTURE_2D, g_FontTexture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if (@hasDecl(gl, "GL_UNPACK_ROW_LENGTH")) glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels); // Store our identifier io.*.Fonts.*.TexID = @intToPtr(*c_void, g_FontTexture); return true; } fn DestroyFontsTexture() void { if (g_FontTexture != 0) { const io = igGetIO(); glDeleteTextures(1, &g_FontTexture); io.*.Fonts.*.TexID = null; g_FontTexture = 0; } } fn CreateDeviceObjects() void { // Parse GLSL version string var glsl_version: u32 = 130; const numberPart = g_GlslVersionStringMem["#version ".len..g_GlslVersionString.len]; if (std.fmt.parseInt(u32, numberPart, 10)) |value| { glsl_version = value; } else |_| { std.debug.warn("Couldn't parse glsl version from '{any}', '{any}'\n", .{ g_GlslVersionString, numberPart }); } const vertex_shader_glsl_120 = "uniform mat4 ProjMtx;\n" ++ "attribute vec2 Position;\n" ++ "attribute vec2 UV;\n" ++ "attribute vec4 Color;\n" ++ "varying vec2 Frag_UV;\n" ++ "varying vec4 Frag_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Frag_UV = UV;\n" ++ " Frag_Color = Color;\n" ++ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" ++ "}\n"; const vertex_shader_glsl_130 = "uniform mat4 ProjMtx;\n" ++ "in vec2 Position;\n" ++ "in vec2 UV;\n" ++ "in vec4 Color;\n" ++ "out vec2 Frag_UV;\n" ++ "out vec4 Frag_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Frag_UV = UV;\n" ++ " Frag_Color = Color;\n" ++ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" ++ "}\n"; const vertex_shader_glsl_300_es = "precision mediump float;\n" ++ "layout (location = 0) in vec2 Position;\n" ++ "layout (location = 1) in vec2 UV;\n" ++ "layout (location = 2) in vec4 Color;\n" ++ "uniform mat4 ProjMtx;\n" ++ "out vec2 Frag_UV;\n" ++ "out vec4 Frag_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Frag_UV = UV;\n" ++ " Frag_Color = Color;\n" ++ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" ++ "}\n"; const vertex_shader_glsl_410_core = "layout (location = 0) in vec2 Position;\n" ++ "layout (location = 1) in vec2 UV;\n" ++ "layout (location = 2) in vec4 Color;\n" ++ "uniform mat4 ProjMtx;\n" ++ "out vec2 Frag_UV;\n" ++ "out vec4 Frag_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Frag_UV = UV;\n" ++ " Frag_Color = Color;\n" ++ " gl_Position = ProjMtx * vec4(Position.xy,0,1);\n" ++ "}\n"; const fragment_shader_glsl_120 = "#ifdef GL_ES\n" ++ " precision mediump float;\n" ++ "#endif\n" ++ "uniform sampler2D Texture;\n" ++ "varying vec2 Frag_UV;\n" ++ "varying vec4 Frag_Color;\n" ++ "void main()\n" ++ "{\n" ++ " gl_FragColor = Frag_Color * texture2D(Texture, Frag_UV.st);\n" ++ "}\n"; const fragment_shader_glsl_130 = "uniform sampler2D Texture;\n" ++ "in vec2 Frag_UV;\n" ++ "in vec4 Frag_Color;\n" ++ "out vec4 Out_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" ++ "}\n"; const fragment_shader_glsl_300_es = "precision mediump float;\n" ++ "uniform sampler2D Texture;\n" ++ "in vec2 Frag_UV;\n" ++ "in vec4 Frag_Color;\n" ++ "layout (location = 0) out vec4 Out_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" ++ "}\n"; const fragment_shader_glsl_410_core = "in vec2 Frag_UV;\n" ++ "in vec4 Frag_Color;\n" ++ "uniform sampler2D Texture;\n" ++ "layout (location = 0) out vec4 Out_Color;\n" ++ "void main()\n" ++ "{\n" ++ " Out_Color = Frag_Color * texture(Texture, Frag_UV.st);\n" ++ "}\n"; // Select shaders matching our GLSL versions var vertex_shader: [*]const u8 = undefined; var fragment_shader: [*]const u8 = undefined; if (glsl_version < 130) { vertex_shader = vertex_shader_glsl_120; fragment_shader = fragment_shader_glsl_120; } else if (glsl_version >= 410) { vertex_shader = vertex_shader_glsl_410_core; fragment_shader = fragment_shader_glsl_410_core; } else if (glsl_version == 300) { vertex_shader = vertex_shader_glsl_300_es; fragment_shader = fragment_shader_glsl_300_es; } else { vertex_shader = vertex_shader_glsl_130; fragment_shader = fragment_shader_glsl_130; } // Create shaders const vertex_shader_with_version = [_][*]const u8{ &g_GlslVersionStringMem, vertex_shader }; g_VertHandle = glCreateShader(GL_VERTEX_SHADER); glShaderSource(g_VertHandle, 2, &vertex_shader_with_version, null); glCompileShader(g_VertHandle); const fragment_shader_with_version = [_][*]const u8{ &g_GlslVersionStringMem, fragment_shader }; g_FragHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(g_FragHandle, 2, &fragment_shader_with_version, null); glCompileShader(g_FragHandle); g_ShaderHandle = glCreateProgram(); glAttachShader(g_ShaderHandle, g_VertHandle); glAttachShader(g_ShaderHandle, g_FragHandle); glLinkProgram(g_ShaderHandle); g_AttribLocationTex = glGetUniformLocation(g_ShaderHandle, "Texture"); g_AttribLocationProjMtx = glGetUniformLocation(g_ShaderHandle, "ProjMtx"); g_AttribLocationVtxPos = glGetAttribLocation(g_ShaderHandle, "Position"); g_AttribLocationVtxUV = glGetAttribLocation(g_ShaderHandle, "UV"); g_AttribLocationVtxColor = glGetAttribLocation(g_ShaderHandle, "Color"); // Create buffers glGenBuffers(1, &g_VboHandle); glGenBuffers(1, &g_ElementsHandle); _ = CreateFontsTexture(); } fn DestroyDeviceObjects() void { if (g_VboHandle != 0) { glDeleteBuffers(1, &g_VboHandle); g_VboHandle = 0; } if (g_ElementsHandle != 0) { glDeleteBuffers(1, &g_ElementsHandle); g_ElementsHandle = 0; } if (g_ShaderHandle != 0 and g_VertHandle != 0) { glDetachShader(g_ShaderHandle, g_VertHandle); } if (g_ShaderHandle != 0 and g_FragHandle != 0) { glDetachShader(g_ShaderHandle, g_FragHandle); } if (g_VertHandle != 0) { glDeleteShader(g_VertHandle); g_VertHandle = 0; } if (g_FragHandle != 0) { glDeleteShader(g_FragHandle); g_FragHandle = 0; } if (g_ShaderHandle != 0) { glDeleteProgram(g_ShaderHandle); g_ShaderHandle = 0; } DestroyFontsTexture(); }
src/zt/imguiImplementation.zig
const std = @import("std"); const constants = @import("../constants.zig"); const logger = std.log.scoped(.dx_pixel); const DXPoint = @import("dx_point.zig").DXPoint; const DXPointData = @import("dx_point_data.zig").DXPointData; const DXHeader = @import("dx_header.zig").DXHeader; const DXRecordHeader = @import("dx_record_header.zig").DXRecordHeader; pub fn makeListOfInts(max: usize) []const void { return @as([]const void, &[_]void{}).ptr[0..max]; } pub const DXPixel = struct { point: DXPoint, data: DXPointData, pub fn fromBuffer( allocator: std.mem.Allocator, buffer: []u8, header: DXHeader, record_header: DXRecordHeader, ) !std.ArrayList(DXPixel) { var pixels = try std.ArrayList(DXPixel).initCapacity(allocator, record_header.npix); // Here we read through the point information and data information at the same time. // Each of these are stored in separate segments so we have to keep track // to the pointer in the buffer where they reside. var pixel_cursor: u64 = 0; var data_cursor: u64 = 8 * record_header.npix; logger.debug("Reading {} pixels", .{record_header.npix}); for (makeListOfInts(record_header.npix)) |_| { var point = DXPoint.fromBuffer(buffer[pixel_cursor .. pixel_cursor + 8]) catch |err| { logger.debug("Error reading pixel: {}", .{err}); return err; }; pixel_cursor += 8; // Now the data var point_data = DXPointData.fromBuffer(allocator, buffer[data_cursor..], header) catch |err| { logger.debug("Error reading pixel data: {}", .{err}); return err; }; // Each data element has a variable size in bytes, which we only // know after reading the data. data_cursor += point_data.sizeBytes(); var pixel = DXPixel{ .point = point, .data = point_data, }; try pixels.append(pixel); } return pixels; } pub fn deinit(self: *DXPixel) void { self.point.deinit(); self.data.deinit(); self.* = undefined; } };
zig-dxread/src/models/dx_pixel.zig
// tested on zig 0.8.1 by klardotsh. requires libcurl dev headers and, of // course, linkable objects. // in a more "production-ready" world, // https://github.com/ducdetronquito/requestz is probably the more // zig-ergonomic answer for HTTP(s) stuff, and // https://github.com/MasterQ32/zig-network for raw TCP/UDP stuff. since this // is just a quick PoC, libcurl it is! // it's expected that this "daemon" run before uxncli <rom> does, but after the // fifos are created (mkfifo reqs.fifo; mkfifo.resps.fifo). please // productionize this better than I did. // // thus: // // mkfifo reqs.fifo // mkfifo resps.fifo // zig build -Drelease-safe run const std = @import("std"); const gen_allocator = std.heap.page_allocator; const libcurl = @cImport(@cInclude("curl/curl.h")); const LIBCURL_FALSE = @as(c_long, 0); const LIBCURL_TRUE = @as(c_long, 1); const YAP_VERSIONS = enum { V0 = @as(u16, 0), }; const PROTOCOLS = enum { MALFORMED = 0, UDP, TCP, HTTP, GEMINI, }; fn wrap(result: anytype) !void { switch (@enumToInt(result)) { libcurl.CURLE_OK => return, else => unreachable, } } fn u16be_from_u8s(left: u8, right: u8) u16 { return @as(u16, right) | @as(u16, left) << 8; } pub fn main() anyerror!void { var reqs = try std.fs.cwd().openFile("reqs.fifo", .{ .read = true, .write = false }); defer reqs.close(); var _resps = try std.fs.cwd().openFile("resps.fifo", .{ .read = false, .write = true }); defer _resps.close(); var resps = std.io.bufferedWriter(_resps.writer()); var output = resps.writer(); const reader = reqs.reader(); request: while (true) { var last_char: u8 = undefined; var built = false; var version: ?YAP_VERSIONS = null; var protocol: ?PROTOCOLS = null; var req_id: ?u8 = null; var port: ?u16 = null; // while the HTTP spec says servers should always be able to handle any // length of URL, the practical limit according to The Interwebs seems // to be 2048 characters, in part set by IE way back when // allow one more byte to append \0 var target_buf: [2049:0]u8 = undefined; var target_idx: usize = 0; var target_terminated = false; var varargs_terminated = false; var body_terminated = false; while (reader.readByte()) |c| { if (version == null) { const next_byte = try reader.readByte(); const requested_version = u16be_from_u8s(c, next_byte); version = switch (requested_version) { @enumToInt(YAP_VERSIONS.V0) => YAP_VERSIONS.V0, else => error.InvalidYapVersion, } catch |err| { std.log.err("InvalidYapVersion {d}, resetting", .{requested_version}); continue :request; }; } else if (protocol == null) { protocol = switch (c) { @enumToInt(PROTOCOLS.HTTP) => PROTOCOLS.HTTP, else => error.UnsupportedProtocol, } catch |err| { std.log.err("UnsupportedProtocol {d}, resetting", .{c}); continue :request; }; } else if (req_id == null) { req_id = c; } else if (port == null) { const next_byte = try reader.readByte(); port = u16be_from_u8s(c, next_byte); } else if (!target_terminated) { target_buf[target_idx] = c; if (c == 0) { target_terminated = true; } else { target_idx += 1; } } else if (!varargs_terminated) { // TODO FIXME implement varargs (headers, in HTTP at least) if (c == 0 and last_char == 0) { varargs_terminated = true; last_char = 1; } else if (c == 0) { last_char = c; } } else if (!body_terminated) { // TODO FIXME implement request body if (c == 0 and last_char == 0) { body_terminated = true; last_char = 1; built = true; } else if (c == 0) { last_char = c; } } std.log.debug("current state: (" ++ "version={d}, " ++ "protocol={d}, " ++ "req_id={d}, " ++ "port={d}, " ++ "target='{s}', " ++ "varargs=<unimplemented>, " ++ "body=<unimplemented>" ++ ")", .{ version, protocol, req_id, port, target_buf[0..target_idx] }); if (built) { std.log.debug("BUILT! Ship it.", .{}); const curl = libcurl.curl_easy_init(); if (curl == null) return error.InitFailed; defer libcurl.curl_easy_cleanup(curl); std.log.debug("libcurl initialized", .{}); try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_URL, target_buf[0..])); // TODO should these be configurable? or done at all? try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_VERBOSE, LIBCURL_FALSE)); try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_FOLLOWLOCATION, LIBCURL_TRUE)); try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_TCP_KEEPALIVE, LIBCURL_TRUE)); try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_NOPROGRESS, LIBCURL_TRUE)); // FIXME this is actually wrong, should be a c_long which is a // i64 - not sure if uxnyap protocol should change or if we // should try to truncate the field somehow var http_code: u16 = undefined; try wrap(libcurl.curl_easy_getinfo(curl, ._RESPONSE_CODE, &http_code)); var res_body = std.ArrayList(u8).init(gen_allocator); defer res_body.deinit(); try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_WRITEFUNCTION, writeCallback)); try wrap(libcurl.curl_easy_setopt(curl, .CURLOPT_WRITEDATA, &res_body)); if (libcurl.curl_easy_perform(curl) == .CURLE_OK) { std.log.debug("request complete with status {d}", .{http_code}); try output.writeIntBig(u16, @enumToInt(version.?)); try output.writeIntBig(u8, @enumToInt(protocol.?)); try output.writeIntBig(u8, req_id.?); try output.writeIntBig(u16, http_code); try output.writeIntBig(u16, 0); // just terminate varags, FIXME not implemented try output.writeAll(res_body.items[0..]); // it's known that this needs to change to be binary-safe, // but until then, the protocol says to // double-null-terminate the end of bodies so we're doing // it try output.writeIntBig(u16, 0); } try resps.flush(); continue :request; } } else |err| { switch (err) { error.EndOfStream => { try resps.flush(); std.os.exit(0); }, else => std.log.err("received error: {s}", .{err}), } } } try resps.flush(); } // https://github.com/gaultier/zorrent/blob/095752f5fda62ef21cf3cecb8be3bec434b79277/src/tracker.zig#L263 fn writeCallback( p_contents: *c_void, size: usize, nmemb: usize, p_user_data: *std.ArrayList(u8), ) usize { const contents = @ptrCast([*c]const u8, p_contents); p_user_data.*.appendSlice(contents[0..nmemb]) catch { std.process.exit(1); }; return size * nmemb; }
src/main.zig
const std = @import("std"); const os = std.os; const panic = std.debug.panic; const assert = std.debug.assert; const GLenum = c_uint; const GLuint = c_uint; const GLint = c_int; const GLsizei = c_int; const GLfloat = f32; const GLdouble = f64; const GLchar = u8; const GLboolean = u8; const GLbitfield = c_uint; const GLubyte = u8; const GLsizeiptr = isize; const GLintptr = isize; pub const COLOR = 0x1800; pub const COLOR_ATTACHMENT0 = 0x8CE0; pub const PROJECTION = 0x1701; pub const FRAMEBUFFER_SRGB = 0x8DB9; pub const MULTISAMPLE = 0x809D; pub const TEXTURE_2D_MULTISAMPLE = 0x9100; pub const SRGB8_ALPHA8 = 0x8C43; pub const TRUE = 1; pub const FALSE = 0; pub const DRAW_FRAMEBUFFER = 0x8CA9; pub const COLOR_BUFFER_BIT = 0x00004000; pub const NEAREST = 0x2600; pub const LINEAR = 0x2601; pub const BLEND = 0x0BE2; pub const POINTS = 0x0000; pub const LINES = 0x0001; pub const LINE_LOOP = 0x0002; pub const LINE_STRIP = 0x0003; pub const TRIANGLES = 0x0004; pub const TRIANGLE_STRIP = 0x0005; pub const TRIANGLE_FAN = 0x0006; pub const QUADS = 0x0007; pub const QUAD_STRIP = 0x0008; pub const POLYGON = 0x0009; pub const ZERO = 0; pub const ONE = 1; pub const SRC_COLOR = 0x0300; pub const ONE_MINUS_SRC_COLOR = 0x0301; pub const SRC_ALPHA = 0x0302; pub const ONE_MINUS_SRC_ALPHA = 0x0303; pub const DST_ALPHA = 0x0304; pub const ONE_MINUS_DST_ALPHA = 0x0305; pub const DST_COLOR = 0x0306; pub const ONE_MINUS_DST_COLOR = 0x0307; pub const FUNC_REVERSE_SUBTRACT = 0x800B; pub const FUNC_SUBTRACT = 0x800A; pub const FUNC_ADD = 0x8006; pub const FRAGMENT_SHADER = 0x8B30; pub const VERTEX_SHADER = 0x8B31; pub const TEXTURE_2D = 0x0DE1; pub const RG = 0x8227; pub const RG_INTEGER = 0x8228; pub const R8 = 0x8229; pub const R16 = 0x822A; pub const RG8 = 0x822B; pub const RG16 = 0x822C; pub const R16F = 0x822D; pub const R32F = 0x822E; pub const RG16F = 0x822F; pub const RG32F = 0x8230; pub const R8I = 0x8231; pub const R8UI = 0x8232; pub const R16I = 0x8233; pub const R16UI = 0x8234; pub const R32I = 0x8235; pub const R32UI = 0x8236; pub const RG8I = 0x8237; pub const RG8UI = 0x8238; pub const RG16I = 0x8239; pub const RG16UI = 0x823A; pub const RG32I = 0x823B; pub const RG32UI = 0x823C; pub const RGBA32F = 0x8814; pub const RGB32F = 0x8815; pub const RGBA16F = 0x881A; pub const RGB16F = 0x881B; pub const RGBA32UI = 0x8D70; pub const RGB32UI = 0x8D71; pub const RGBA16UI = 0x8D76; pub const RGB16UI = 0x8D77; pub const RGBA8UI = 0x8D7C; pub const RGB8UI = 0x8D7D; pub const RGBA32I = 0x8D82; pub const RGB32I = 0x8D83; pub const RGBA16I = 0x8D88; pub const RGB16I = 0x8D89; pub const RGBA8I = 0x8D8E; pub const RGB8I = 0x8D8F; pub const RED_INTEGER = 0x8D94; pub const GREEN_INTEGER = 0x8D95; pub const BLUE_INTEGER = 0x8D96; pub const RGB_INTEGER = 0x8D98; pub const RGBA_INTEGER = 0x8D99; pub const BGR_INTEGER = 0x8D9A; pub const BGRA_INTEGER = 0x8D9B; pub const BYTE = 0x1400; pub const UNSIGNED_BYTE = 0x1401; pub const SHORT = 0x1402; pub const UNSIGNED_SHORT = 0x1403; pub const INT = 0x1404; pub const UNSIGNED_INT = 0x1405; pub const FLOAT = 0x1406; pub const READ_ONLY = 0x88B8; pub const WRITE_ONLY = 0x88B9; pub const READ_WRITE = 0x88BA; pub const ATOMIC_COUNTER_BUFFER = 0x92C0; pub const VERTEX_ATTRIB_ARRAY_BARRIER_BIT = 0x00000001; pub const ELEMENT_ARRAY_BARRIER_BIT = 0x00000002; pub const UNIFORM_BARRIER_BIT = 0x00000004; pub const TEXTURE_FETCH_BARRIER_BIT = 0x00000008; pub const SHADER_IMAGE_ACCESS_BARRIER_BIT = 0x00000020; pub const COMMAND_BARRIER_BIT = 0x00000040; pub const PIXEL_BUFFER_BARRIER_BIT = 0x00000080; pub const TEXTURE_UPDATE_BARRIER_BIT = 0x00000100; pub const BUFFER_UPDATE_BARRIER_BIT = 0x00000200; pub const FRAMEBUFFER_BARRIER_BIT = 0x00000400; pub const TRANSFORM_FEEDBACK_BARRIER_BIT = 0x00000800; pub const ATOMIC_COUNTER_BARRIER_BIT = 0x00001000; pub const ALL_BARRIER_BITS = 0xFFFFFFFF; pub const FRAMEBUFFER_BINDING = 0x8CA6; pub const DRAW_FRAMEBUFFER_BINDING = 0x8CA6; pub const RENDERBUFFER_BINDING = 0x8CA7; pub const READ_FRAMEBUFFER = 0x8CA8; pub const READ_FRAMEBUFFER_BINDING = 0x8CAA; pub const STENCIL_INDEX = 0x1901; pub const DEPTH_COMPONENT = 0x1902; pub const RED = 0x1903; pub const GREEN = 0x1904; pub const BLUE = 0x1905; pub const ALPHA = 0x1906; pub const RGB = 0x1907; pub const RGBA = 0x1908; pub const TEXTURE_RECTANGLE = 0x84F5; var wCreateContext: fn (?os.windows.HDC) callconv(.Stdcall) ?os.windows.HGLRC = undefined; var wDeleteContext: fn (?os.windows.HGLRC) callconv(.Stdcall) bool = undefined; var wMakeCurrent: fn (?os.windows.HDC, ?os.windows.HGLRC) callconv(.Stdcall) bool = undefined; var wGetProcAddress: fn (os.windows.LPCSTR) callconv(.Stdcall) ?os.windows.FARPROC = undefined; var wSwapIntervalEXT: fn (i32) callconv(.Stdcall) bool = undefined; pub var clearBufferfv: fn (GLenum, GLint, [*c]const GLfloat) callconv(.Stdcall) void = undefined; pub var matrixLoadIdentityEXT: fn (GLenum) callconv(.Stdcall) void = undefined; pub var matrixOrthoEXT: fn (GLenum, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble, GLdouble) callconv(.Stdcall) void = undefined; pub var enable: fn (GLenum) callconv(.Stdcall) void = undefined; pub var disable: fn (GLenum) callconv(.Stdcall) void = undefined; pub var textureStorage2DMultisample: fn (GLuint, GLsizei, GLenum, GLsizei, GLsizei, GLboolean) callconv(.Stdcall) void = undefined; pub var textureStorage2D: fn (GLuint, GLsizei, GLenum, GLsizei, GLsizei) callconv(.Stdcall) void = undefined; pub var createTextures: fn (GLenum, GLsizei, [*c]GLuint) callconv(.Stdcall) void = undefined; pub var deleteTextures: fn (GLsizei, [*c]const GLuint) callconv(.Stdcall) void = undefined; pub var createFramebuffers: fn (GLsizei, [*c]GLuint) callconv(.Stdcall) void = undefined; pub var deleteFramebuffers: fn (GLsizei, [*c]const GLuint) callconv(.Stdcall) void = undefined; pub var namedFramebufferTexture: fn (GLuint, GLenum, GLuint, GLint) callconv(.Stdcall) void = undefined; pub var blitNamedFramebuffer: fn (GLuint, GLuint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum) callconv(.Stdcall) void = undefined; pub var bindFramebuffer: fn (GLenum, GLuint) callconv(.Stdcall) void = undefined; pub var begin: fn (GLenum) callconv(.Stdcall) void = undefined; pub var end: fn () callconv(.Stdcall) void = undefined; pub var getError: fn () callconv(.Stdcall) GLenum = undefined; pub var pointSize: fn (GLfloat) callconv(.Stdcall) void = undefined; pub var lineWidth: fn (GLfloat) callconv(.Stdcall) void = undefined; pub var blendFunc: fn (GLenum, GLenum) callconv(.Stdcall) void = undefined; pub var blendEquation: fn (GLenum) callconv(.Stdcall) void = undefined; pub var vertex2f: fn (GLfloat, GLfloat) callconv(.Stdcall) void = undefined; pub var vertex2d: fn (GLdouble, GLdouble) callconv(.Stdcall) void = undefined; pub var vertex2i: fn (GLint, GLint) callconv(.Stdcall) void = undefined; pub var color4f: fn (GLfloat, GLfloat, GLfloat, GLfloat) callconv(.Stdcall) void = undefined; pub var color4ub: fn (GLubyte, GLubyte, GLubyte, GLubyte) callconv(.Stdcall) void = undefined; pub var pushMatrix: fn () callconv(.Stdcall) void = undefined; pub var popMatrix: fn () callconv(.Stdcall) void = undefined; pub var rotatef: fn (GLfloat, GLfloat, GLfloat, GLfloat) callconv(.Stdcall) void = undefined; pub var scalef: fn (GLfloat, GLfloat, GLfloat) callconv(.Stdcall) void = undefined; pub var translatef: fn (GLfloat, GLfloat, GLfloat) callconv(.Stdcall) void = undefined; pub var createShaderProgramv: fn (GLenum, GLsizei, [*c]const [*c]const GLchar) callconv(.Stdcall) GLuint = undefined; pub var useProgram: fn (GLuint) callconv(.Stdcall) void = undefined; pub var bindBuffer: fn (GLenum, GLuint) callconv(.Stdcall) void = undefined; pub var bindBufferRange: fn (GLenum, GLuint, GLuint, GLintptr, GLsizeiptr) callconv(.Stdcall) void = undefined; pub var bindBufferBase: fn (GLenum, GLuint, GLuint) callconv(.Stdcall) void = undefined; pub var createBuffers: fn (GLsizei, [*c]GLuint) callconv(.Stdcall) void = undefined; pub var deleteBuffers: fn (GLsizei, [*c]const GLuint) callconv(.Stdcall) void = undefined; pub var namedBufferStorage: fn (GLuint, GLsizeiptr, ?*const c_void, GLbitfield) callconv(.Stdcall) void = undefined; pub var clearTexImage: fn (GLuint, GLint, GLenum, GLenum, ?*const c_void) callconv(.Stdcall) void = undefined; pub var bindImageTexture: fn (GLuint, GLuint, GLint, GLboolean, GLint, GLenum, GLenum) callconv(.Stdcall) void = undefined; pub var deleteProgram: fn (GLuint) callconv(.Stdcall) void = undefined; pub var memoryBarrier: fn (GLbitfield) callconv(.Stdcall) void = undefined; pub var colorMask: fn (GLboolean, GLboolean, GLboolean, GLboolean) void = undefined; pub var getIntegerv: fn (GLenum, [*c]GLint) void = undefined; pub var bindTextureUnit: fn (GLuint, GLuint) callconv(.Stdcall) void = undefined; var opengl32_dll: std.DynLib = undefined; var opengl_context: ?os.windows.HGLRC = null; var hdc: ?os.windows.HDC = null; pub fn init(window: ?os.windows.HWND) void { assert(window != null and opengl_context == null); hdc = os.windows.user32.GetDC(window); var pfd = std.mem.zeroes(os.windows.gdi32.PIXELFORMATDESCRIPTOR); pfd.nSize = @sizeOf(os.windows.gdi32.PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = os.windows.user32.PFD_SUPPORT_OPENGL + os.windows.user32.PFD_DOUBLEBUFFER + os.windows.user32.PFD_DRAW_TO_WINDOW; pfd.iPixelType = os.windows.user32.PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; pfd.cStencilBits = 8; const pixel_format = os.windows.gdi32.ChoosePixelFormat(hdc, &pfd); if (!os.windows.gdi32.SetPixelFormat(hdc, pixel_format, &pfd)) { panic("SetPixelFormat failed.", .{}); } opengl32_dll = std.DynLib.open("/windows/system32/opengl32.dll") catch unreachable; wCreateContext = opengl32_dll.lookup(@TypeOf(wCreateContext), "wglCreateContext").?; wDeleteContext = opengl32_dll.lookup(@TypeOf(wDeleteContext), "wglDeleteContext").?; wMakeCurrent = opengl32_dll.lookup(@TypeOf(wMakeCurrent), "wglMakeCurrent").?; wGetProcAddress = opengl32_dll.lookup(@TypeOf(wGetProcAddress), "wglGetProcAddress").?; opengl_context = wCreateContext(hdc); if (!wMakeCurrent(hdc, opengl_context)) { panic("Failed to create OpenGL context.", .{}); } wSwapIntervalEXT = getProcAddress(@TypeOf(wSwapIntervalEXT), "wglSwapIntervalEXT").?; _ = wSwapIntervalEXT(1); clearBufferfv = getProcAddress(@TypeOf(clearBufferfv), "glClearBufferfv").?; matrixLoadIdentityEXT = getProcAddress(@TypeOf(matrixLoadIdentityEXT), "glMatrixLoadIdentityEXT").?; matrixOrthoEXT = getProcAddress(@TypeOf(matrixOrthoEXT), "glMatrixOrthoEXT").?; enable = getProcAddress(@TypeOf(enable), "glEnable").?; disable = getProcAddress(@TypeOf(disable), "glDisable").?; textureStorage2DMultisample = getProcAddress(@TypeOf(textureStorage2DMultisample), "glTextureStorage2DMultisample").?; textureStorage2D = getProcAddress(@TypeOf(textureStorage2D), "glTextureStorage2D").?; createTextures = getProcAddress(@TypeOf(createTextures), "glCreateTextures").?; deleteTextures = getProcAddress(@TypeOf(deleteTextures), "glDeleteTextures").?; createFramebuffers = getProcAddress(@TypeOf(createFramebuffers), "glCreateFramebuffers").?; deleteFramebuffers = getProcAddress(@TypeOf(deleteFramebuffers), "glDeleteFramebuffers").?; namedFramebufferTexture = getProcAddress(@TypeOf(namedFramebufferTexture), "glNamedFramebufferTexture").?; blitNamedFramebuffer = getProcAddress(@TypeOf(blitNamedFramebuffer), "glBlitNamedFramebuffer").?; bindFramebuffer = getProcAddress(@TypeOf(bindFramebuffer), "glBindFramebuffer").?; begin = getProcAddress(@TypeOf(begin), "glBegin").?; end = getProcAddress(@TypeOf(end), "glEnd").?; getError = getProcAddress(@TypeOf(getError), "glGetError").?; pointSize = getProcAddress(@TypeOf(pointSize), "glPointSize").?; lineWidth = getProcAddress(@TypeOf(lineWidth), "glLineWidth").?; blendFunc = getProcAddress(@TypeOf(blendFunc), "glBlendFunc").?; blendEquation = getProcAddress(@TypeOf(blendEquation), "glBlendEquation").?; vertex2f = getProcAddress(@TypeOf(vertex2f), "glVertex2f").?; vertex2d = getProcAddress(@TypeOf(vertex2d), "glVertex2d").?; vertex2i = getProcAddress(@TypeOf(vertex2i), "glVertex2i").?; color4f = getProcAddress(@TypeOf(color4f), "glColor4f").?; color4ub = getProcAddress(@TypeOf(color4ub), "glColor4ub").?; pushMatrix = getProcAddress(@TypeOf(pushMatrix), "glPushMatrix").?; popMatrix = getProcAddress(@TypeOf(popMatrix), "glPopMatrix").?; rotatef = getProcAddress(@TypeOf(rotatef), "glRotatef").?; scalef = getProcAddress(@TypeOf(scalef), "glScalef").?; translatef = getProcAddress(@TypeOf(translatef), "glTranslatef").?; createShaderProgramv = getProcAddress(@TypeOf(createShaderProgramv), "glCreateShaderProgramv").?; useProgram = getProcAddress(@TypeOf(useProgram), "glUseProgram").?; bindBuffer = getProcAddress(@TypeOf(bindBuffer), "glBindBuffer").?; bindBufferRange = getProcAddress(@TypeOf(bindBufferRange), "glBindBufferRange").?; bindBufferBase = getProcAddress(@TypeOf(bindBufferBase), "glBindBufferBase").?; createBuffers = getProcAddress(@TypeOf(createBuffers), "glCreateBuffers").?; deleteBuffers = getProcAddress(@TypeOf(deleteBuffers), "glDeleteBuffers").?; namedBufferStorage = getProcAddress(@TypeOf(namedBufferStorage), "glNamedBufferStorage").?; clearTexImage = getProcAddress(@TypeOf(clearTexImage), "glClearTexImage").?; bindImageTexture = getProcAddress(@TypeOf(bindImageTexture), "glBindImageTexture").?; deleteProgram = getProcAddress(@TypeOf(deleteProgram), "glDeleteProgram").?; memoryBarrier = getProcAddress(@TypeOf(memoryBarrier), "glMemoryBarrier").?; colorMask = getProcAddress(@TypeOf(colorMask), "glColorMask").?; getIntegerv = getProcAddress(@TypeOf(getIntegerv), "glGetIntegerv").?; bindTextureUnit = getProcAddress(@TypeOf(bindTextureUnit), "glBindTextureUnit").?; } pub fn deinit() void { assert(hdc != null and opengl_context != null); _ = wMakeCurrent(null, null); _ = wDeleteContext(opengl_context); opengl_context = null; } pub fn swapBuffers() void { assert(hdc != null and opengl_context != null); _ = os.windows.gdi32.SwapBuffers(hdc); } fn getProcAddress(comptime T: type, name: [:0]const u8) ?T { if (wGetProcAddress(name.ptr)) |addr| { return @ptrCast(T, addr); } else { return opengl32_dll.lookup(T, name); } }
src/opengl.zig
const std = @import("std"); const zort = @import("main.zig"); const testing = std.testing; pub const items_t = i32; pub const items = [_]i32{ -9, 1, -4, 12, 3, 4 }; pub const expectedASC = [_]i32{ -9, -4, 1, 3, 4, 12 }; pub const expectedDESC = [_]i32{ 12, 4, 3, 1, -4, -9 }; fn asc(a: i32, b: i32) bool { return a < b; } fn desc(a: i32, b: i32) bool { return a > b; } test "bubble" { { var arr = items; zort.bubbleSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.bubbleSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "comb" { { var arr = items; zort.combSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.combSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "heap" { { var arr = items; zort.heapSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.heapSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "insertion" { { var arr = items; zort.insertionSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.insertionSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "merge" { { var arr = items; try zort.mergeSort(items_t, &arr, asc, testing.allocator); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; try zort.mergeSort(items_t, &arr, desc, testing.allocator); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "quick" { { var arr = items; zort.quickSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.quickSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "radix" { return error.SkipZigTest; // { // var arr = items; // try zort.radixSort(items_t, &arr, testing.allocator); // try testing.expectEqualSlices(items_t, &arr, &expectedASC); // } } test "selection" { { var arr = items; zort.selectionSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.selectionSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "shell" { { var arr = items; zort.shellSort(items_t, &arr, asc); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; zort.shellSort(items_t, &arr, desc); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "tim" { { var arr = items; try zort.timSort(items_t, &arr, asc, testing.allocator); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; try zort.timSort(items_t, &arr, desc, testing.allocator); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } } test "twin" { { var arr = items; try zort.twinSort(testing.allocator, items_t, &arr, {}, comptime std.sort.asc(items_t)); try testing.expectEqualSlices(items_t, &arr, &expectedASC); } { var arr = items; try zort.twinSort(testing.allocator, items_t, &arr, {}, comptime std.sort.desc(items_t)); try testing.expectEqualSlices(items_t, &arr, &expectedDESC); } }
src/test.zig
pub const address_book = @import("system/address_book.zig"); pub const antimalware = @import("system/antimalware.zig"); pub const application_installation_and_servicing = @import("system/application_installation_and_servicing.zig"); pub const application_verifier = @import("system/application_verifier.zig"); pub const assessment_tool = @import("system/assessment_tool.zig"); pub const com = @import("system/com.zig"); pub const component_services = @import("system/component_services.zig"); pub const console = @import("system/console.zig"); pub const contacts = @import("system/contacts.zig"); pub const data_exchange = @import("system/data_exchange.zig"); pub const deployment_services = @import("system/deployment_services.zig"); pub const desktop_sharing = @import("system/desktop_sharing.zig"); pub const developer_licensing = @import("system/developer_licensing.zig"); pub const diagnostics = @import("system/diagnostics.zig"); pub const environment = @import("system/environment.zig"); pub const error_reporting = @import("system/error_reporting.zig"); pub const event_collector = @import("system/event_collector.zig"); pub const event_log = @import("system/event_log.zig"); pub const event_notification_service = @import("system/event_notification_service.zig"); pub const group_policy = @import("system/group_policy.zig"); pub const hypervisor = @import("system/hypervisor.zig"); pub const job_objects = @import("system/job_objects.zig"); pub const js = @import("system/js.zig"); pub const kernel = @import("system/kernel.zig"); pub const library_loader = @import("system/library_loader.zig"); pub const mailslots = @import("system/mailslots.zig"); pub const mapi = @import("system/mapi.zig"); pub const memory = @import("system/memory.zig"); pub const mmc = @import("system/mmc.zig"); pub const ole_automation = @import("system/ole_automation.zig"); pub const parental_controls = @import("system/parental_controls.zig"); pub const password_management = @import("system/password_management.zig"); pub const performance = @import("system/performance.zig"); pub const pipes = @import("system/pipes.zig"); pub const power = @import("system/power.zig"); pub const process_status = @import("system/process_status.zig"); pub const properties_system = @import("system/properties_system.zig"); pub const recovery = @import("system/recovery.zig"); pub const registry = @import("system/registry.zig"); pub const remote_assistance = @import("system/remote_assistance.zig"); pub const remote_desktop = @import("system/remote_desktop.zig"); pub const remote_management = @import("system/remote_management.zig"); pub const restart_manager = @import("system/restart_manager.zig"); pub const restore = @import("system/restore.zig"); pub const rpc = @import("system/rpc.zig"); pub const search = @import("system/search.zig"); pub const security_center = @import("system/security_center.zig"); pub const server_backup = @import("system/server_backup.zig"); pub const services = @import("system/services.zig"); pub const settings_management_infrastructure = @import("system/settings_management_infrastructure.zig"); pub const setup_and_migration = @import("system/setup_and_migration.zig"); pub const shutdown = @import("system/shutdown.zig"); pub const stations_and_desktops = @import("system/stations_and_desktops.zig"); pub const subsystem_for_linux = @import("system/subsystem_for_linux.zig"); pub const system_information = @import("system/system_information.zig"); pub const system_services = @import("system/system_services.zig"); pub const task_scheduler = @import("system/task_scheduler.zig"); pub const threading = @import("system/threading.zig"); pub const time = @import("system/time.zig"); pub const tpm_base_services = @import("system/tpm_base_services.zig"); pub const update_agent = @import("system/update_agent.zig"); pub const update_assessment = @import("system/update_assessment.zig"); pub const user_access_logging = @import("system/user_access_logging.zig"); pub const virtual_dos_machines = @import("system/virtual_dos_machines.zig"); pub const win_rt = @import("system/win_rt.zig"); pub const windows_programming = @import("system/windows_programming.zig"); pub const windows_sync = @import("system/windows_sync.zig"); pub const wmi = @import("system/wmi.zig"); test { @import("std").testing.refAllDecls(@This()); }
deps/zigwin32/win32/system.zig
const c = @import("c.zig"); const std = @import("std"); const debug = std.debug; const fmt = std.fmt; const math = std.math; const mem = std.mem; const sort = std.sort; export fn zigNuklearAssert(ok: c_int) callconv(.C) void { debug.assert(ok != 0); } export fn zigNuklearSqrt(x: f32) callconv(.C) f32 { return math.sqrt(x); } export fn zigNuklearSin(x: f32) callconv(.C) f32 { return math.sin(x); } export fn zigNuklearCos(x: f32) callconv(.C) f32 { return math.cos(x); } export fn zigNuklearAcos(x: f32) callconv(.C) f32 { return math.acos(x); } export fn zigNuklearFmod(x: f32, y: f32) callconv(.C) f32 { return @rem(x, y); } export fn zigNuklearFabs(x: f32) callconv(.C) f32 { return math.fabs(x); } export fn zigNuklearDtoa(out: [*]u8, n: f64) callconv(.C) [*]u8 { const res = fmt.bufPrint(out[0..c.NK_MAX_NUMBER_BUFFER], "{}", .{n}) catch unreachable; return out + res.len; } export fn zigNuklearStrlen(str: [*:0]const u8) callconv(.C) c.nk_size { return mem.lenZ(str); } export fn zigNuklearMemcopy(dst: [*]u8, src: [*]const u8, n: c.nk_size) callconv(.C) [*]u8 { @memcpy(dst, src, n); return dst; } export fn zigNuklearMemset(dst: [*]u8, char: c_int, n: c.nk_size) callconv(.C) [*]u8 { @memset(dst, @intCast(u8, char), n); return dst; } const Compare = fn (*const [16]u8, *const [16]u8) callconv(.C) c_int; export fn zigNuklearSort( base: [*][16]u8, nmemb: c.nk_size, size: c.nk_size, cmp: Compare, ) callconv(.C) void { // This only ever sorts stbrp_rect types, which are documented to be 16 bytes. debug.assert(size == 16); sort.sort([16]u8, base[0..nmemb], cmp, struct { fn compare(ctx: Compare, a: [16]u8, b: [16]u8) bool { return ctx(&a, &b) < 0; } }.compare); } export fn zigNuklearStrtod(str: c.struct_nk_slice, end_ptr: ?*c.struct_nk_slice) callconv(.C) f64 { // We don't support setting the end_ptr and nuklear always passes null to us debug.assert(end_ptr == null); return fmt.parseFloat(f64, str.ptr[0..str.len]) catch 0.0; }
src/export.zig
const std = @import("std"); const GitRepoStep = @This(); pub const ShaCheck = enum { none, warn, err, pub fn reportFail(self: ShaCheck, comptime fmt: []const u8, args: anytype) void { switch (self) { .none => unreachable, .warn => std.log.warn(fmt, args), .err => { std.log.err(fmt, args); std.os.exit(0xff); }, } } }; step: std.build.Step, builder: *std.build.Builder, url: []const u8, name: []const u8, branch: ?[]const u8 = null, sha: []const u8, path: []const u8 = null, sha_check: ShaCheck = .warn, fetch_enabled: bool, var cached_default_fetch_option: ?bool = null; pub fn defaultFetchOption(b: *std.build.Builder) bool { if (cached_default_fetch_option) |_| {} else { cached_default_fetch_option = if (b.option(bool, "fetch", "automatically fetch network resources")) |o| o else false; } return cached_default_fetch_option.?; } pub fn create(b: *std.build.Builder, opt: struct { url: []const u8, branch: ?[]const u8 = null, sha: []const u8, path: ?[]const u8 = null, sha_check: ShaCheck = .warn, fetch_enabled: ?bool = null, }) *GitRepoStep { var result = b.allocator.create(GitRepoStep) catch @panic("memory"); const name = std.fs.path.basename(opt.url); result.* = GitRepoStep{ .step = std.build.Step.init(.custom, "clone a git repository", b.allocator, make), .builder = b, .url = opt.url, .name = name, .branch = opt.branch, .sha = opt.sha, .path = if (opt.path) |p| (b.allocator.dupe(u8, p) catch @panic("memory")) else (std.fs.path.resolve(b.allocator, &[_][]const u8{ b.build_root, "dep", name, })) catch @panic("memory"), .sha_check = opt.sha_check, .fetch_enabled = if (opt.fetch_enabled) |fe| fe else defaultFetchOption(b), }; return result; } // TODO: this should be included in std.build, it helps find bugs in build files fn hasDependency(step: *const std.build.Step, dep_candidate: *const std.build.Step) bool { for (step.dependencies.items) |dep| { // TODO: should probably use step.loop_flag to prevent infinite recursion // when a circular reference is encountered, or maybe keep track of // the steps encounterd with a hash set if (dep == dep_candidate or hasDependency(dep, dep_candidate)) return true; } return false; } fn make(step: *std.build.Step) !void { const self = @fieldParentPtr(GitRepoStep, "step", step); std.fs.accessAbsolute(self.path, .{}) catch { const branch_args = if (self.branch) |b| &[2][]const u8{ " -b ", b } else &[2][]const u8{ "", "" }; if (!self.fetch_enabled) { std.debug.print("Error: git repository '{s}' does not exist\n", .{self.path}); std.debug.print(" Use -Dfetch to download it automatically, or run the following to clone it:\n", .{}); std.debug.print(" git clone {s}{s}{s} {s} && git -C {3s} checkout {s} -b fordep\n", .{ self.url, branch_args[0], branch_args[1], self.path, self.sha, }); std.os.exit(1); } { var args = std.ArrayList([]const u8).init(self.builder.allocator); defer args.deinit(); try args.append("git"); try args.append("clone"); try args.append(self.url); // TODO: clone it to a temporary location in case of failure // also, remove that temporary location before running try args.append(self.path); if (self.branch) |branch| { try args.append("-b"); try args.append(branch); } try run(self.builder, args.items); } try run(self.builder, &[_][]const u8{ "git", "-C", self.path, "checkout", self.sha, "-b", "fordep", }); }; try self.checkSha(); } fn checkSha(self: GitRepoStep) !void { if (self.sha_check == .none) return; const result: union(enum) { failed: anyerror, output: []const u8 } = blk: { const result = std.ChildProcess.exec(.{ .allocator = self.builder.allocator, .argv = &[_][]const u8{ "git", "-C", self.path, "rev-parse", "HEAD", }, .cwd = self.builder.build_root, .env_map = self.builder.env_map, }) catch |e| break :blk .{ .failed = e }; try std.io.getStdErr().writer().writeAll(result.stderr); switch (result.term) { .Exited => |code| { if (code == 0) break :blk .{ .output = result.stdout }; break :blk .{ .failed = error.GitProcessNonZeroExit }; }, .Signal => break :blk .{ .failed = error.GitProcessFailedWithSignal }, .Stopped => break :blk .{ .failed = error.GitProcessWasStopped }, .Unknown => break :blk .{ .failed = error.GitProcessFailed }, } }; switch (result) { .failed => |err| { return self.sha_check.reportFail("failed to retreive sha for repository '{s}': {s}", .{ self.name, @errorName(err) }); }, .output => |output| { if (!std.mem.eql(u8, std.mem.trimRight(u8, output, "\n\r"), self.sha)) { return self.sha_check.reportFail("repository '{s}' sha does not match\nexpected: {s}\nactual : {s}\n", .{ self.name, self.sha, output }); } }, } } fn run(builder: *std.build.Builder, argv: []const []const u8) !void { { var msg = std.ArrayList(u8).init(builder.allocator); defer msg.deinit(); const writer = msg.writer(); var prefix: []const u8 = ""; for (argv) |arg| { try writer.print("{s}\"{s}\"", .{ prefix, arg }); prefix = " "; } std.log.info("[RUN] {s}", .{msg.items}); } var child = std.ChildProcess.init(argv, builder.allocator); child.stdin_behavior = .Ignore; child.stdout_behavior = .Inherit; child.stderr_behavior = .Inherit; child.cwd = builder.build_root; child.env_map = builder.env_map; try child.spawn(); const result = try child.wait(); switch (result) { .Exited => |code| if (code != 0) { std.log.err("git clone failed with exit code {}", .{code}); std.os.exit(0xff); }, else => { std.log.err("git clone failed with: {}", .{result}); std.os.exit(0xff); }, } } // Get's the repository path and also verifies that the step requesting the path // is dependent on this step. pub fn getPath(self: *const GitRepoStep, who_wants_to_know: *const std.build.Step) []const u8 { if (!hasDependency(who_wants_to_know, &self.step)) @panic("a step called GitRepoStep.getPath but has not added it as a dependency"); return self.path; }
GitRepoStep.zig
const std = @import("std"); const str = []const u8; const event = std.event; const Thread = std.Thread; const Blake3 = std.crypto.hash.Blake3; const atomic = std.atomic; var Allocator = std.mem.Allocator; const Arena = std.heap.ArenaAllocator; /// A graph with directed edges and weighted vertices and edges pub fn Graph(comptime N: Node, comptime E: Edge) type { const Node = struct { const Self = @This(); weight: *N, src: ?*Node, dest: ?*Node, next: ?*Edge, prev: ?*Edge, pub const Dir = enum(u1) { in, out }; pub fn init(weight: N) Self { return Node{ .weight = weight, .incoming = null, .outgoing = null, }; } pub fn add(weight: N, from: *Node, to: *Node) *Self{ var n = Node.init(weight); n.src = from; n.to = to; } }; const Edge = struct { const Self = @This(); weight: *E, incoming: ?*Edge, outgoing: ?*Edge, pub const Dir = enum(u1) { left, right}; pub fn init(weight: E, src: ?*Node, dest: ?*Node) Self { if (src) |s| if (s.outgoing) |*o| o.*.next = &n; return Edge{ .weight = weight, .src = src, .dest = dest, .next = null, }; } pub fn pushLeft(self: *Edge, next: *Edge) void { if (!self.incoming) { } if ( self.incoming) |*in| { self.*.incoming = &next; next.*.outgoing = &self; } if (self.outgoing) |*out| { } } pub fn push(self: *Edge, edge: *Edge, dir: @This().Dir) void {] switch (Switch.dir) { .in => Edge.pushLeft } } }; const Graph = struct { nodes: [*]Node(N, E), node_co: usize, edge_co: usize, }; return struct { const Self = @This(); nodes: []Node(N, E), edges: [*]Edge(N, E), }; } pub const Directed = enum(u1) { directed = 1, undirected = 0, }; pub const Weighted = enum(u1) { weighted = 1, unweighted = 0, }; pub const GraphType = packed struct { const Self = @This(); weighted: Weighted = Weighted.weighted, directed: Directed = Directed.directed, pub fn init(directed: bool, unweighted: bool) type { return GraphType{.directed = false, .weighted = false}; } pub fn default() type {} pub fn dirWeight() type { return GraphType{}; } pub fn dirUnweighted() GraphType { return GraphType{.weighted = Weighted.unweighted}; } pub fn undirectedDirected() GraphType { return GraphType{.directed = Directed.undirected}; } pub fn undirectedUnweighted() GraphType { return GraphType{.directed = Directed.undirected, .weighted = Weighted.unweighted}; } }; test "GraphType works as intended" { }
src/data/graph.zig
const std = @import("std"); const root = @import("root"); const liu = @import("./lib.zig"); const builtin = @import("builtin"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const wasm = @This(); pub const Obj = enum(u32) { // These are kept up to date with src/wasm.ts jsundefined, jsnull, jsEmptyString, log, info, warn, err, success, U8Array, F32Array, _, pub const objSet = ext.objSet; pub const arrayPush = ext.arrayPush; }; const Watermark = enum(i32) { _ }; const ext = struct { extern fn makeString(message: [*]const u8, length: usize, is_temp: bool) Obj; extern fn makeView(o: Obj, message: ?*const anyopaque, length: usize, is_temp: bool) Obj; extern fn makeArray(is_temp: bool) Obj; extern fn makeObj(is_temp: bool) Obj; extern fn arrayPush(arr: Obj, obj: Obj) void; extern fn objSet(obj: Obj, key: Obj, value: Obj) void; extern fn watermark() Watermark; extern fn setWatermark(watermark: Watermark) void; extern fn deleteObj(obj: Obj) void; extern fn encodeString(idx: Obj) usize; extern fn objLen(idx: Obj) usize; extern fn readBytes(idx: Obj, begin: [*]u8) void; extern fn postMessage(tagIdx: Obj, id: Obj) void; extern fn exit(objIndex: Obj) noreturn; }; pub const watermark = ext.watermark; pub const setWatermark = ext.setWatermark; pub const Lifetime = enum { manual, temp, fn isTemp(self: @This()) bool { return self == .temp; } }; pub const make = struct { pub fn slice(life: Lifetime, data: anytype) Obj { const ptr: ?*const anyopaque = ptr: { switch (@typeInfo(@TypeOf(data))) { .Array => {}, .Pointer => |info| switch (info.size) { .One => switch (@typeInfo(info.child)) { .Array => break :ptr data, else => {}, }, .Many, .C => {}, .Slice => break :ptr data.ptr, }, else => {}, } @compileError("Need to pass a slice or array"); }; const len = data.len; const T = std.meta.Elem(@TypeOf(data)); const is_temp = life.isTemp(); return switch (T) { u8 => ext.makeView(.U8Array, ptr, len, is_temp), f32 => ext.makeView(.F32Array, ptr, len, is_temp), else => unreachable, }; } pub fn fmt(life: Lifetime, comptime format: []const u8, args: anytype) Obj { const mark = liu.TempMark; defer liu.TempMark = mark; const allocResult = std.fmt.allocPrint(liu.Temp, format, args); const data = allocResult catch @panic("failed to print"); return ext.makeString(data.ptr, data.len, life.isTemp()); } pub fn string(life: Lifetime, a: []const u8) Obj { return ext.makeString(a.ptr, a.len, life.isTemp()); } pub fn array(life: Lifetime) Obj { return ext.makeArray(life.isTemp()); } pub fn obj(life: Lifetime) Obj { return ext.makeObj(life.isTemp()); } }; pub fn post(level: Obj, comptime format: []const u8, args: anytype) void { if (builtin.target.cpu.arch != .wasm32) { std.log.info(format, args); return; } const mark = watermark(); defer setWatermark(mark); const object = make.fmt(.temp, format, args); ext.postMessage(level, object); } pub const delete = ext.deleteObj; pub fn deleteMany(obj_slice: []const Obj) void { for (obj_slice) |o| { delete(o); } } pub const out = struct { pub inline fn array() Obj { return wasm.make.array(.temp); } pub inline fn obj() Obj { return wasm.make.obj(.temp); } pub inline fn slice(data: anytype) Obj { return wasm.make.slice(.temp, data); } pub inline fn string(a: []const u8) Obj { return wasm.make.string(.temp, a); } pub inline fn fmt(comptime format: []const u8, args: anytype) Obj { return wasm.make.fmt(.temp, format, args); } }; pub const in = struct { pub fn bytes(byte_object: Obj, alloc: Allocator) ![]u8 { return alignedBytes(byte_object, alloc, null); } pub fn alignedBytes(byte_object: Obj, alloc: Allocator, comptime alignment: ?u29) ![]align(alignment orelse 1) u8 { if (builtin.target.cpu.arch != .wasm32) return &.{}; defer ext.deleteObj(byte_object); const len = ext.objLen(byte_object); const data = try alloc.alignedAlloc(u8, alignment, len); ext.readBytes(byte_object, data.ptr); return data; } pub fn string(string_object: Obj, alloc: Allocator) ![]u8 { if (builtin.target.cpu.arch != .wasm32) return &.{}; defer ext.deleteObj(string_object); const len = ext.encodeString(string_object); const data = try alloc.alloc(u8, len); ext.readBytes(string_object, data.ptr); return data; } }; pub fn exit(msg: []const u8) noreturn { const exit_message = wasm.make.string(.temp, msg); return ext.exit(exit_message); } const CommandBuffer = liu.RingBuffer(root.WasmCommand, 64); var initialized: bool = false; var cmd_bump: liu.Bump = undefined; var commands: CommandBuffer = undefined; const CmdAlloc = cmd_bump.allocator(); pub fn initIfNecessary() void { if (builtin.target.cpu.arch != .wasm32) { return; } if (!initialized) { cmd_bump = liu.Bump.init(4096, liu.Pages); commands = CommandBuffer.init(); initialized = true; } } pub const strip_debug_info = true; pub const have_error_return_tracing = false; pub fn log( comptime message_level: std.log.Level, comptime scope: @Type(.EnumLiteral), comptime fmt: []const u8, args: anytype, ) void { if (builtin.target.cpu.arch != .wasm32) { std.log.defaultLog(message_level, scope, fmt, args); return; } _ = scope; if (@enumToInt(message_level) > @enumToInt(std.log.level)) { return; } const level_obj: Obj = switch (message_level) { .debug => .info, .info => .info, .warn => .warn, .err => .err, }; post(level_obj, fmt ++ "\n", args); } pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { @setCold(true); if (builtin.target.cpu.arch != .wasm32) { std.builtin.default_panic(msg, error_return_trace); } _ = error_return_trace; exit(msg); }
src/liu/wasm.zig
const std = @import("std"); const vkgen = @import("generator/index.zig"); const Step = std.build.Step; const Builder = std.build.Builder; const path = std.fs.path; pub const ResourceGenStep = struct { step: Step, shader_step: *vkgen.ShaderCompileStep, builder: *Builder, full_out_path: []const u8, resources: std.ArrayList(u8), pub fn init(builder: *Builder, out: []const u8) *ResourceGenStep { const self = builder.allocator.create(ResourceGenStep) catch unreachable; self.* = .{ .step = Step.init(.Custom, "resources", builder.allocator, make), .shader_step = vkgen.ShaderCompileStep.init(builder, &[_][]const u8{"glslc", "--target-env=vulkan1.2"}), .builder = builder, .full_out_path = path.join(builder.allocator, &[_][]const u8{ self.builder.build_root, builder.cache_root, out, }) catch unreachable, .resources = std.ArrayList(u8).init(builder.allocator), }; self.step.dependOn(&self.shader_step.step); return self; } pub fn addShader(self: *ResourceGenStep, name: []const u8, source: []const u8) void { self.resources.writer().print( "pub const {} = @embedFile(\"{}\");\n", .{name, self.shader_step.add(source)} ) catch unreachable; } fn make(step: *Step) !void { const self = @fieldParentPtr(ResourceGenStep, "step", step); const cwd = std.fs.cwd(); const dir = path.dirname(self.full_out_path).?; try cwd.makePath(dir); try cwd.writeFile(self.full_out_path, self.resources.items); } }; pub fn build(b: *Builder) void { var test_step = b.step("test", "Run all the tests"); test_step.dependOn(&b.addTest("generator/index.zig").step); const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); const triangle_exe = b.addExecutable("triangle", "examples/triangle.zig"); triangle_exe.setTarget(target); triangle_exe.setBuildMode(mode); triangle_exe.install(); triangle_exe.linkSystemLibrary("c"); triangle_exe.linkSystemLibrary("glfw"); const gen = vkgen.VkGenerateStep.init(b, "examples/vk.xml", "vk.zig"); triangle_exe.step.dependOn(&gen.step); triangle_exe.addPackagePath("vulkan", gen.full_out_path); const res = ResourceGenStep.init(b, "resources.zig"); res.addShader("triangle_vert", "examples/shaders/triangle.vert"); res.addShader("triangle_frag", "examples/shaders/triangle.frag"); triangle_exe.step.dependOn(&res.step); triangle_exe.addPackagePath("resources", res.full_out_path); const triangle_run_cmd = triangle_exe.run(); triangle_run_cmd.step.dependOn(b.getInstallStep()); const triangle_run_step = b.step("run-triangle", "Run the triangle example"); triangle_run_step.dependOn(&triangle_run_cmd.step); }
build.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day23.txt"); pub fn main() !void { var timer = try std.time.Timer.start(); { var burrow = Burrow.init(data, false); print("🎁 Num moves: {}\n", .{try burrow.cost()}); print("Day 23 - part 01 took {:15}ns\n", .{timer.lap()}); timer.reset(); } { var burrow = Burrow.init(data, true); print("🎁 On Cubes: {}\n", .{try burrow.cost()}); print("Day 23 - part 02 took {:15}ns\n", .{timer.lap()}); print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{}); } } const Burrow = struct { rooms : [16]u8, hallway : [11]u8, roomSize : usize, pub fn init(input : []const u8, part2 : bool) @This() { var iterator = std.mem.tokenize(input, "#\r\n. "); var me = @This() { .rooms = [_]u8{'.'} ** 16, .hallway = [_]u8{'.'} ** 11, .roomSize = if (part2) 16 else 8, }; for (me.rooms[0..8]) |*room| { room.* = iterator.next().?[0]; } if (part2) { for (me.rooms[4..8]) |room, i| { me.rooms[12 + i] = room; } // Insert the new rooms. // #D#C#B#A# // #D#B#A#C# me.rooms[4] = 'D'; me.rooms[5] = 'C'; me.rooms[6] = 'B'; me.rooms[7] = 'A'; me.rooms[8] = 'D'; me.rooms[9] = 'B'; me.rooms[10] = 'A'; me.rooms[11] = 'C'; } return me; } pub fn dump(me : *const @This()) void { { var index : u32 = 0; while (index < 13) : (index += 1) { print("#", .{}); } print("\n", .{}); } { print("#", .{}); var index : u32 = 0; for (me.hallway) |p| { print("{c}", .{p}); } print("#\n", .{}); } { print("###", .{}); var index : u32 = 0; for (me.rooms[0..4]) |p| { print("{c}#", .{p}); } print("##\n", .{}); } { var index : usize = 4; while (index < me.roomSize) : (index += 4) { print(" #", .{}); for (me.rooms[index..(index + 4)]) |p| { print("{c}#", .{p}); } print(" \n", .{}); } } { print(" ", .{}); var index : u32 = 0; while (index < 9) : (index += 1) { print("#", .{}); } print(" \n", .{}); } } const Move = struct { room : usize, hallway : usize, }; const Moves = struct { const maxSize : usize = 32; payload : [maxSize]Move, size : usize, pub fn init() @This() { return @This() { .payload = undefined, .size = 0, }; } pub fn append(me : *@This(), room : usize, hallway : usize) void { if (me.size >= maxSize) { unreachable; } me.payload[me.size] = Move { .room = room, .hallway = hallway }; me.size += 1; } pub fn moves(me : *const @This()) []const Move { return me.payload[0..me.size]; } }; fn isLegalMove(me : *const @This(), room : usize, hallway : usize) bool { // We are not allowed to move into the hallway and stop outside a room. if (hallway >= 2 and hallway <= 8 and (hallway % 2) == 0) { return false; } const inRoom = me.rooms[room] != '.'; // We cannot leave the room we are already meant to be in... if (inRoom and targetRoom(me.rooms[room]) == (room % 4)) { // ... unless we are blocking someone who isn't meant to be in our room // in there! // If we're at the bottom of the room we can't be blocking anyone! if (room >= (me.roomSize - 4)) { return false; } var checkRoom = room; while (checkRoom < (me.roomSize - 4)) : (checkRoom += 4) { if (targetRoom(me.rooms[checkRoom + 4]) == (checkRoom % 4)) { return false; } } } else if (me.hallway[hallway] != '.') { const target = targetRoom(me.hallway[hallway]); var index : usize = 0; while (index < me.roomSize) : (index += 4) { const roomValue = me.rooms[target + index]; if (roomValue == '.') { continue; } else if (roomValue != me.hallway[hallway]) { return false; } } } const roomToHallwayTranslation = translateRoomToHallway(room); var lo = std.math.min(roomToHallwayTranslation, hallway); var hi = std.math.max(roomToHallwayTranslation, hallway) + 1; // If we aren't in the room, we need to skip ourselves when checking if the // hallway is clear. if (!inRoom) { if (lo == hallway) { lo += 1; } else { hi -= 1; } } for (me.hallway[lo..hi]) |p, pi| { // If the space is occupied, we cannot move to it or through it. if (p != '.') { return false; } } return true; } fn translateRoomToHallway(room : usize) usize { return 2 + (2 * (room % 4)); } fn targetRoom(p : u8) usize { switch (p) { 'A' => return 0, 'B' => return 1, 'C' => return 2, 'D' => return 3, else => unreachable, } } fn possibleMoves(me : *const @This()) Moves { var moves = Moves.init(); // First we check the top positions in each room for moves. { var index : usize = 0; while (index < me.roomSize) : (index += 4) { for (me.rooms[index..(index + 4)]) |r, ri| { if (index >= 4 and me.rooms[index - 4 + ri] != '.') { continue; } switch (r) { 'A', 'B', 'C', 'D' => { for (me.hallway) |h, hi| { if (me.isLegalMove(ri + index, hi)) { moves.append(ri + index, hi); } } }, '.' => {}, else => unreachable, } } } } for (me.hallway) |h, hi| { switch (h) { 'A', 'B', 'C', 'D' => { var ri = targetRoom(h); var offset : usize = 0; if (me.rooms[ri] == '.' and me.isLegalMove(ri, hi)) { // Check if the full room is empty, if so we'll move to the bottom // position. var index : usize = 4; while (index < me.roomSize) : (index += 4) { if (me.rooms[ri + index] == '.') { offset += 4; } } moves.append(ri + offset, hi); } }, '.' => {}, else => unreachable, } } return moves; } fn moveCost(me : *const @This(), move : Move) usize { var numMoves : usize = (move.room / 4) + 1; const roomToHallwayTranslation = translateRoomToHallway(move.room); numMoves += std.math.max(roomToHallwayTranslation, move.hallway) - std.math.min(roomToHallwayTranslation, move.hallway); const room = me.rooms[move.room]; const hallway = me.hallway[move.hallway]; const p = if (room == '.') hallway else room; switch (p) { 'A' => return numMoves * 1, 'B' => return numMoves * 10, 'C' => return numMoves * 100, 'D' => return numMoves * 1000, else => unreachable, } } fn finished(me : *const @This()) bool { for (me.rooms[0..me.roomSize]) |r, ri| { switch (ri % 4) { 0 => if (r != 'A') return false, 1 => if (r != 'B') return false, 2 => if (r != 'C') return false, 3 => if (r != 'D') return false, else => unreachable, } } return true; } const Potential = struct { burrow : Burrow, theCost : usize, pub fn init(burrow : Burrow, theCost : usize) @This() { return @This() { .burrow = burrow, .theCost = theCost, }; } }; fn cost(me : *const @This()) !usize { var search = std.ArrayList(Potential).init(gpa); var reducer = std.AutoHashMap(Burrow, usize).init(gpa); try search.append(Potential.init(me.*, 0)); var result : ?usize = null; while (search.items.len != 0) { const pop = search.swapRemove(0); var seenAlready = reducer.get(pop.burrow); if (seenAlready == null) { try reducer.put(pop.burrow, pop.theCost); } else { if (seenAlready.? <= pop.theCost) { // Skip processing this one because we've got to this position once // before but with a lower cost. continue; } try reducer.put(pop.burrow, pop.theCost); } // If we've already found at least one result, and it is cheaper than the // current searched result, don't check it any further. if (result != null) { if (result.? <= pop.theCost) { continue; } } const searchResult = try pop.burrow.searchCost(pop.theCost, &search); if (searchResult != null) { if (result == null) { result = searchResult.?; } else { result = std.math.min(result.?, searchResult.?); } } } return result.?; } fn searchCost(me : *const @This(), inputCost : usize, search : *std.ArrayList(Potential)) !?usize { const moves = me.possibleMoves(); var mi : usize = 0; while (mi < moves.size) : (mi += 1) { const move = moves.payload[mi]; var newMe = me.*; const myMoveCost = me.moveCost(move); const moveIntoRoom = newMe.rooms[move.room] == '.'; if (moveIntoRoom) { newMe.rooms[move.room] = newMe.hallway[move.hallway]; newMe.hallway[move.hallway] = '.'; } else { newMe.hallway[move.hallway] = newMe.rooms[move.room]; newMe.rooms[move.room] = '.'; } const totalCost = inputCost + myMoveCost; if (newMe.finished()) { return totalCost; } try search.append(Potential.init(newMe, totalCost)); } return null; } }; test "example" { const input = \\############# \\#...........# \\###B#C#B#D### \\ #A#D#C#A# \\ ######### ; { var burrow = Burrow.init(input, false); const result = try burrow.cost(); try std.testing.expect(result == 12521); } { var burrow = Burrow.init(input, true); const result = try burrow.cost(); try std.testing.expect(result == 44169); } }
src/day23.zig
const std = @import("std"); const warn = std.debug.warn; const testing = std.testing; usingnamespace @import("zetacore"); const HealthComponent = struct { health: usize, }; const EnergyComponent = struct { energy: usize, }; const PositionComponent = struct { x: f32, y: f32, z: f32, }; const VelocityComponent = struct { x: f32, y: f32, z: f32, }; const ECS = @import("zetacore").Schema(u24, .{ HealthComponent, EnergyComponent, PositionComponent, VelocityComponent, }); const PhysicsSystem = struct { const Self = @This(); system: ECS.System, pub fn init() Self { return Self{ .system = ECS.System{ .runFn = run, }, }; } fn run(sys: *ECS.System, world: *ECS.World) !void { var query = try world.queryAOS(struct { pos: *PositionComponent, vel: *VelocityComponent, }); defer query.deinit(); var timer = try std.time.Timer.start(); for (query.items) |q| { q.pos.x += q.vel.x; q.pos.y += q.vel.y; q.pos.z += q.vel.z; } const end = timer.lap(); warn("time: \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); } }; test "generalECSTest" { std.debug.warn("\n", .{}); var world = try ECS.World.init(std.heap.page_allocator); defer world.deinit(); var i: usize = 0; while (i < 10000) : (i += 1) { _ = try world.createEntity(.{ VelocityComponent{ .x = 1.0, .y = 1.0, .z = 1.0 }, PositionComponent{ .x = 0.0, .y = 0.0, .z = 0.0 }, }); } var entity0 = try world.createEntity(.{ HealthComponent{ .health = 20 }, }); var healths1 = try std.heap.page_allocator.alloc(HealthComponent, 10); std.mem.set(HealthComponent, healths1, HealthComponent{ .health = 20 }); try world.createEntities(.{ healths1, }); var physicsSystem = PhysicsSystem.init(); try world.registerSystem(&physicsSystem.system); try world.run(); // Check to make sure that the iteration actually did something var query = try world.queryAOS(struct { pos: *PositionComponent, vel: *VelocityComponent, }); defer query.deinit(); for (query.items) |q| { testing.expectEqual(q.pos.x, q.vel.x); } } test "ecsBench" { warn("\n", .{}); var world = try ECS.World.init(std.heap.page_allocator); defer world.deinit(); var velocities0 = try std.heap.page_allocator.alloc(VelocityComponent, 1000000); std.mem.set(VelocityComponent, velocities0, VelocityComponent{ .x = 1.0, .y = 1.0, .z = 1.0 }); var positions0 = try std.heap.page_allocator.alloc(PositionComponent, 1000000); std.mem.set(PositionComponent, positions0, PositionComponent{ .x = 0.0, .y = 0.0, .z = 0.0 }); var timer = try std.time.Timer.start(); try world.createEntities(.{ positions0, velocities0, }); var end = timer.lap(); warn("create: \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); std.heap.page_allocator.free(velocities0); std.heap.page_allocator.free(positions0); var query = try world.queryAOS(struct { pos: *PositionComponent, vel: *VelocityComponent, }); defer query.deinit(); timer.reset(); for (query.items) |q| { q.pos.x += q.vel.x; q.pos.y += q.vel.y; q.pos.z += q.vel.z; } end = timer.lap(); warn("query_aos (iter): \t{d}\n", .{@intToFloat(f64, end) / 1000000000}); // Check to make sure that the iteration actually did something var query2 = try world.queryAOS(struct { pos: *PositionComponent, vel: *VelocityComponent, }); defer query2.deinit(); for (query2.items) |q| { testing.expectEqual(q.pos.x, q.vel.x); } } test "multiVecStoreTest" { std.debug.warn("\n", .{}); var store = MultiVecStore.init(std.heap.page_allocator); defer store.deinit(); try store.append(u32, 11111); try store.append(u32, 22222); try store.append(u32, 33333); try store.append(PositionComponent, PositionComponent{ .x = 0.0, .y = 0.0, .z = 0.0 }); try store.append(PositionComponent, PositionComponent{ .x = 1.0, .y = 1.0, .z = 1.0 }); try store.append(u32, 44444); try store.append(u32, 55555); testing.expect(store.getIndex(u32, 0) == 11111); testing.expect(store.getIndex(u32, 1) == 22222); testing.expect(store.getIndex(u32, 2) == 33333); testing.expect(store.getIndex(PositionComponent, 3).x == 0.0); testing.expect(store.getIndex(PositionComponent, 4).x == 1.0); testing.expect(store.getIndex(u32, 5) == 44444); testing.expect(store.getIndex(u32, 6) == 55555); store.setIndex(u32, 1, 77777); testing.expect(store.getIndex(u32, 1) == 77777); testing.expect(store.getIndexPtr(u32, 1).* == 77777); var store2 = try MultiVecStore.initCapacity(.{ u32, f32 }, 2, std.heap.page_allocator); defer store2.deinit(); testing.expect(store2.data_len == 16); }
core/test/test.zig
const std = @import("std"); const ArenaAllocator = std.heap.ArenaAllocator; const assert = std.debug.assert; const eql = std.mem.eql; const zig_string = @import("./zig-string.zig"); const String = zig_string.String; test "Basic Usage" { // Use your favorite allocator var arena = ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); // Create your String var myString = String.init(&arena.allocator); defer myString.deinit(); // Use functions provided try myString.concat("🔥 Hello!"); _ = myString.pop(); try myString.concat(", World 🔥"); // Success! assert(myString.cmp("🔥 Hello, World 🔥")); } test "String Tests" { // Allocator for the String const page_allocator = std.heap.page_allocator; var arena = std.heap.ArenaAllocator.init(page_allocator); defer arena.deinit(); // This is how we create the String var myStr = String.init(&arena.allocator); defer myStr.deinit(); // allocate & capacity try myStr.allocate(16); assert(myStr.capacity() == 16); assert(myStr.size == 0); // truncate try myStr.truncate(); assert(myStr.capacity() == myStr.size); assert(myStr.capacity() == 0); // concat try myStr.concat("A"); try myStr.concat("\u{5360}"); try myStr.concat("💯"); try myStr.concat("Hello🔥"); assert(myStr.size == 17); // pop & length assert(myStr.len() == 9); assert(eql(u8, myStr.pop().?, "🔥")); assert(myStr.len() == 8); assert(eql(u8, myStr.pop().?, "o")); assert(myStr.len() == 7); // str & cmp assert(myStr.cmp("A\u{5360}💯Hell")); assert(myStr.cmp(myStr.str())); // charAt assert(eql(u8, myStr.charAt(2).?, "💯")); assert(eql(u8, myStr.charAt(1).?, "\u{5360}")); assert(eql(u8, myStr.charAt(0).?, "A")); // insert try myStr.insert("🔥", 1); assert(eql(u8, myStr.charAt(1).?, "🔥")); assert(myStr.cmp("A🔥\u{5360}💯Hell")); // find assert(myStr.find("🔥").? == 1); assert(myStr.find("💯").? == 3); assert(myStr.find("Hell").? == 4); // remove & removeRange try myStr.removeRange(0, 3); assert(myStr.cmp("💯Hell")); try myStr.remove(myStr.len() - 1); assert(myStr.cmp("💯Hel")); const whitelist = [_]u8 {' ', '\t', '\n', '\r'}; // trimStart try myStr.insert(" ", 0); myStr.trimStart(whitelist[0..]); assert(myStr.cmp("💯Hel")); // trimEnd _ = try myStr.concat("lo💯\n "); myStr.trimEnd(whitelist[0..]); assert(myStr.cmp("💯Hello💯")); // clone var testStr = try myStr.clone(); defer testStr.deinit(); assert(testStr.cmp(myStr.str())); // reverse myStr.reverse(); assert(myStr.cmp("💯olleH💯")); myStr.reverse(); assert(myStr.cmp("💯Hello💯")); // repeat try myStr.repeat(2); assert(myStr.cmp("💯Hello💯💯Hello💯💯Hello💯")); // isEmpty assert(!myStr.isEmpty()); // split assert(eql(u8, myStr.split("💯", 0).?, "")); assert(eql(u8, myStr.split("💯", 1).?, "Hello")); assert(eql(u8, myStr.split("💯", 2).?, "")); assert(eql(u8, myStr.split("💯", 3).?, "Hello")); assert(eql(u8, myStr.split("💯", 5).?, "Hello")); assert(eql(u8, myStr.split("💯", 6).?, "")); var splitStr = String.init(&arena.allocator); defer splitStr.deinit(); try splitStr.concat("variable='value'"); assert(eql(u8, splitStr.split("=", 0).?, "variable")); assert(eql(u8, splitStr.split("=", 1).?, "'value'")); // splitToString var newSplit = try splitStr.splitToString("=", 0); assert(newSplit != null); defer newSplit.?.deinit(); assert(eql(u8, newSplit.?.str(), "variable")); // toLowercase & toUppercase myStr.toUppercase(); assert(myStr.cmp("💯HELLO💯💯HELLO💯💯HELLO💯")); myStr.toLowercase(); assert(myStr.cmp("💯hello💯💯hello💯💯hello💯")); // substr var subStr = try myStr.substr(0, 7); defer subStr.deinit(); assert(subStr.cmp("💯hello💯")); // clear myStr.clear(); assert(myStr.len() == 0); assert(myStr.size == 0); // writer const writer = myStr.writer(); const length = try writer.write("This is a Test!"); assert(length == 15); // owned const mySlice = try myStr.toOwned(); assert(eql(u8, mySlice.?, "This is a Test!")); arena.allocator.free(mySlice.?); // StringIterator var i: usize = 0; var iter = myStr.iterator(); while (iter.next()) |ch| { if (i == 0) { assert(eql(u8, "T", ch)); } i += 1; } assert(i == myStr.len()); }
zig-string-tests.zig
const std = @import("std"); const builtin = @import("builtin"); const event = std.event; const os = std.os; const io = std.io; const fs = std.fs; const mem = std.mem; const process = std.process; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const c = @import("c.zig"); const introspect = @import("introspect.zig"); const ZigCompiler = @import("compilation.zig").ZigCompiler; const Compilation = @import("compilation.zig").Compilation; const Target = std.Target; const errmsg = @import("errmsg.zig"); const LibCInstallation = @import("libc_installation.zig").LibCInstallation; pub const io_mode = .evented; pub const max_src_size = 2 * 1024 * 1024 * 1024; // 2 GiB const usage = \\usage: zig [command] [options] \\ \\Commands: \\ \\ build-exe [source] Create executable from source or object files \\ build-lib [source] Create library from source or object files \\ build-obj [source] Create object from source or assembly \\ fmt [source] Parse file and render in canonical zig format \\ libc [paths_file] Display native libc paths file or validate one \\ targets List available compilation targets \\ version Print version number and exit \\ zen Print zen of zig and exit \\ \\ ; const Command = struct { name: []const u8, exec: async fn (*Allocator, []const []const u8) anyerror!void, }; pub fn main() !void { const allocator = std.heap.c_allocator; const stderr = io.getStdErr().outStream(); const args = try process.argsAlloc(allocator); defer process.argsFree(allocator, args); if (args.len <= 1) { try stderr.writeAll("expected command argument\n\n"); try stderr.writeAll(usage); process.exit(1); } const cmd = args[1]; const cmd_args = args[2..]; if (mem.eql(u8, cmd, "build-exe")) { return buildOutputType(allocator, cmd_args, .Exe); } else if (mem.eql(u8, cmd, "build-lib")) { return buildOutputType(allocator, cmd_args, .Lib); } else if (mem.eql(u8, cmd, "build-obj")) { return buildOutputType(allocator, cmd_args, .Obj); } else if (mem.eql(u8, cmd, "fmt")) { return cmdFmt(allocator, cmd_args); } else if (mem.eql(u8, cmd, "libc")) { return cmdLibC(allocator, cmd_args); } else if (mem.eql(u8, cmd, "targets")) { const info = try std.zig.system.NativeTargetInfo.detect(allocator, .{}); const stdout = io.getStdOut().outStream(); return @import("print_targets.zig").cmdTargets(allocator, cmd_args, stdout, info.target); } else if (mem.eql(u8, cmd, "version")) { return cmdVersion(allocator, cmd_args); } else if (mem.eql(u8, cmd, "zen")) { return cmdZen(allocator, cmd_args); } else if (mem.eql(u8, cmd, "help")) { return cmdHelp(allocator, cmd_args); } else if (mem.eql(u8, cmd, "internal")) { return cmdInternal(allocator, cmd_args); } else { try stderr.print("unknown command: {}\n\n", .{args[1]}); try stderr.writeAll(usage); process.exit(1); } } const usage_build_generic = \\usage: zig build-exe <options> [file] \\ zig build-lib <options> [file] \\ zig build-obj <options> [file] \\ \\General Options: \\ --help Print this help and exit \\ --color [auto|off|on] Enable or disable colored error messages \\ \\Compile Options: \\ --libc [file] Provide a file which specifies libc paths \\ --assembly [source] Add assembly file to build \\ --emit [filetype] Emit a specific file format as compilation output \\ --enable-timing-info Print timing diagnostics \\ --name [name] Override output name \\ --output [file] Override destination path \\ --output-h [file] Override generated header file path \\ --pkg-begin [name] [path] Make package available to import and push current pkg \\ --pkg-end Pop current pkg \\ --mode [mode] Set the build mode \\ debug (default) optimizations off, safety on \\ release-fast optimizations on, safety off \\ release-safe optimizations on, safety on \\ release-small optimize for small binary, safety off \\ --static Output will be statically linked \\ --strip Exclude debug symbols \\ -target [name] <arch><sub>-<os>-<abi> see the targets command \\ --eh-frame-hdr enable C++ exception handling by passing --eh-frame-hdr to linker \\ --verbose-tokenize Turn on compiler debug output for tokenization \\ --verbose-ast-tree Turn on compiler debug output for parsing into an AST (tree view) \\ --verbose-ast-fmt Turn on compiler debug output for parsing into an AST (render source) \\ --verbose-link Turn on compiler debug output for linking \\ --verbose-ir Turn on compiler debug output for Zig IR \\ --verbose-llvm-ir Turn on compiler debug output for LLVM IR \\ --verbose-cimport Turn on compiler debug output for C imports \\ -dirafter [dir] Same as -isystem but do it last \\ -isystem [dir] Add additional search path for other .h files \\ -mllvm [arg] Additional arguments to forward to LLVM's option processing \\ \\Link Options: \\ --ar-path [path] Set the path to ar \\ --each-lib-rpath Add rpath for each used dynamic library \\ --library [lib] Link against lib \\ --forbid-library [lib] Make it an error to link against lib \\ --library-path [dir] Add a directory to the library search path \\ --linker-script [path] Use a custom linker script \\ --object [obj] Add object file to build \\ -rdynamic Add all symbols to the dynamic symbol table \\ -rpath [path] Add directory to the runtime library search path \\ -framework [name] (darwin) link against framework \\ -mios-version-min [ver] (darwin) set iOS deployment target \\ -mmacosx-version-min [ver] (darwin) set Mac OS X deployment target \\ --ver-major [ver] Dynamic library semver major version \\ --ver-minor [ver] Dynamic library semver minor version \\ --ver-patch [ver] Dynamic library semver patch version \\ \\ ; fn buildOutputType(allocator: *Allocator, args: []const []const u8, out_type: Compilation.Kind) !void { const stderr = io.getStdErr().outStream(); var color: errmsg.Color = .Auto; var build_mode: std.builtin.Mode = .Debug; var emit_bin = true; var emit_asm = false; var emit_llvm_ir = false; var emit_h = false; var provided_name: ?[]const u8 = null; var is_dynamic = false; var root_src_file: ?[]const u8 = null; var libc_arg: ?[]const u8 = null; var version: std.builtin.Version = .{ .major = 0, .minor = 0, .patch = 0 }; var linker_script: ?[]const u8 = null; var strip = false; var verbose_tokenize = false; var verbose_ast_tree = false; var verbose_ast_fmt = false; var verbose_link = false; var verbose_ir = false; var verbose_llvm_ir = false; var verbose_cimport = false; var linker_rdynamic = false; var link_eh_frame_hdr = false; var macosx_version_min: ?[]const u8 = null; var ios_version_min: ?[]const u8 = null; var assembly_files = ArrayList([]const u8).init(allocator); defer assembly_files.deinit(); var link_objects = ArrayList([]const u8).init(allocator); defer link_objects.deinit(); var clang_argv_buf = ArrayList([]const u8).init(allocator); defer clang_argv_buf.deinit(); var mllvm_flags = ArrayList([]const u8).init(allocator); defer mllvm_flags.deinit(); var cur_pkg = try CliPkg.init(allocator, "", "", null); defer cur_pkg.deinit(); var system_libs = ArrayList([]const u8).init(allocator); defer system_libs.deinit(); var c_src_files = ArrayList([]const u8).init(allocator); defer c_src_files.deinit(); { var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (mem.startsWith(u8, arg, "-")) { if (mem.eql(u8, arg, "--help")) { try io.getStdOut().writeAll(usage_build_generic); process.exit(0); } else if (mem.eql(u8, arg, "--color")) { if (i + 1 >= args.len) { try stderr.writeAll("expected [auto|on|off] after --color\n"); process.exit(1); } i += 1; const next_arg = args[i]; if (mem.eql(u8, next_arg, "auto")) { color = .Auto; } else if (mem.eql(u8, next_arg, "on")) { color = .On; } else if (mem.eql(u8, next_arg, "off")) { color = .Off; } else { try stderr.print("expected [auto|on|off] after --color, found '{}'\n", .{next_arg}); process.exit(1); } } else if (mem.eql(u8, arg, "--mode")) { if (i + 1 >= args.len) { try stderr.writeAll("expected [Debug|ReleaseSafe|ReleaseFast|ReleaseSmall] after --mode\n"); process.exit(1); } i += 1; const next_arg = args[i]; if (mem.eql(u8, next_arg, "Debug")) { build_mode = .Debug; } else if (mem.eql(u8, next_arg, "ReleaseSafe")) { build_mode = .ReleaseSafe; } else if (mem.eql(u8, next_arg, "ReleaseFast")) { build_mode = .ReleaseFast; } else if (mem.eql(u8, next_arg, "ReleaseSmall")) { build_mode = .ReleaseSmall; } else { try stderr.print("expected [Debug|ReleaseSafe|ReleaseFast|ReleaseSmall] after --mode, found '{}'\n", .{next_arg}); process.exit(1); } } else if (mem.eql(u8, arg, "--name")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after --name\n"); process.exit(1); } i += 1; provided_name = args[i]; } else if (mem.eql(u8, arg, "--ver-major")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after --ver-major\n"); process.exit(1); } i += 1; version.major = try std.fmt.parseInt(u32, args[i], 10); } else if (mem.eql(u8, arg, "--ver-minor")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after --ver-minor\n"); process.exit(1); } i += 1; version.minor = try std.fmt.parseInt(u32, args[i], 10); } else if (mem.eql(u8, arg, "--ver-patch")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after --ver-patch\n"); process.exit(1); } i += 1; version.patch = try std.fmt.parseInt(u32, args[i], 10); } else if (mem.eql(u8, arg, "--linker-script")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after --linker-script\n"); process.exit(1); } i += 1; linker_script = args[i]; } else if (mem.eql(u8, arg, "--libc")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after --libc\n"); process.exit(1); } i += 1; libc_arg = args[i]; } else if (mem.eql(u8, arg, "-mllvm")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after -mllvm\n"); process.exit(1); } i += 1; try clang_argv_buf.append("-mllvm"); try clang_argv_buf.append(args[i]); try mllvm_flags.append(args[i]); } else if (mem.eql(u8, arg, "-mmacosx-version-min")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after -mmacosx-version-min\n"); process.exit(1); } i += 1; macosx_version_min = args[i]; } else if (mem.eql(u8, arg, "-mios-version-min")) { if (i + 1 >= args.len) { try stderr.writeAll("expected parameter after -mios-version-min\n"); process.exit(1); } i += 1; ios_version_min = args[i]; } else if (mem.eql(u8, arg, "-femit-bin")) { emit_bin = true; } else if (mem.eql(u8, arg, "-fno-emit-bin")) { emit_bin = false; } else if (mem.eql(u8, arg, "-femit-asm")) { emit_asm = true; } else if (mem.eql(u8, arg, "-fno-emit-asm")) { emit_asm = false; } else if (mem.eql(u8, arg, "-femit-llvm-ir")) { emit_llvm_ir = true; } else if (mem.eql(u8, arg, "-fno-emit-llvm-ir")) { emit_llvm_ir = false; } else if (mem.eql(u8, arg, "-dynamic")) { is_dynamic = true; } else if (mem.eql(u8, arg, "--strip")) { strip = true; } else if (mem.eql(u8, arg, "--verbose-tokenize")) { verbose_tokenize = true; } else if (mem.eql(u8, arg, "--verbose-ast-tree")) { verbose_ast_tree = true; } else if (mem.eql(u8, arg, "--verbose-ast-fmt")) { verbose_ast_fmt = true; } else if (mem.eql(u8, arg, "--verbose-link")) { verbose_link = true; } else if (mem.eql(u8, arg, "--verbose-ir")) { verbose_ir = true; } else if (mem.eql(u8, arg, "--verbose-llvm-ir")) { verbose_llvm_ir = true; } else if (mem.eql(u8, arg, "--eh-frame-hdr")) { link_eh_frame_hdr = true; } else if (mem.eql(u8, arg, "--verbose-cimport")) { verbose_cimport = true; } else if (mem.eql(u8, arg, "-rdynamic")) { linker_rdynamic = true; } else if (mem.eql(u8, arg, "--pkg-begin")) { if (i + 2 >= args.len) { try stderr.writeAll("expected [name] [path] after --pkg-begin\n"); process.exit(1); } i += 1; const new_pkg_name = args[i]; i += 1; const new_pkg_path = args[i]; var new_cur_pkg = try CliPkg.init(allocator, new_pkg_name, new_pkg_path, cur_pkg); try cur_pkg.children.append(new_cur_pkg); cur_pkg = new_cur_pkg; } else if (mem.eql(u8, arg, "--pkg-end")) { if (cur_pkg.parent) |parent| { cur_pkg = parent; } else { try stderr.writeAll("encountered --pkg-end with no matching --pkg-begin\n"); process.exit(1); } } else if (mem.startsWith(u8, arg, "-l")) { try system_libs.append(arg[2..]); } else { try stderr.print("unrecognized parameter: '{}'", .{arg}); process.exit(1); } } else if (mem.endsWith(u8, arg, ".s")) { try assembly_files.append(arg); } else if (mem.endsWith(u8, arg, ".o") or mem.endsWith(u8, arg, ".obj") or mem.endsWith(u8, arg, ".a") or mem.endsWith(u8, arg, ".lib")) { try link_objects.append(arg); } else if (mem.endsWith(u8, arg, ".c") or mem.endsWith(u8, arg, ".cpp")) { try c_src_files.append(arg); } else if (mem.endsWith(u8, arg, ".zig")) { if (root_src_file) |other| { try stderr.print("found another zig file '{}' after root source file '{}'", .{ arg, other, }); process.exit(1); } else { root_src_file = arg; } } else { try stderr.print("unrecognized file extension of parameter '{}'", .{arg}); } } } if (cur_pkg.parent != null) { try stderr.print("unmatched --pkg-begin\n", .{}); process.exit(1); } const root_name = if (provided_name) |n| n else blk: { if (root_src_file) |file| { const basename = fs.path.basename(file); var it = mem.separate(basename, "."); break :blk it.next() orelse basename; } else { try stderr.writeAll("--name [name] not provided and unable to infer\n"); process.exit(1); } }; if (root_src_file == null and link_objects.len == 0 and assembly_files.len == 0) { try stderr.writeAll("Expected source file argument or at least one --object or --assembly argument\n"); process.exit(1); } if (out_type == Compilation.Kind.Obj and link_objects.len != 0) { try stderr.writeAll("When building an object file, --object arguments are invalid\n"); process.exit(1); } try ZigCompiler.setLlvmArgv(allocator, mllvm_flags.span()); const zig_lib_dir = introspect.resolveZigLibDir(allocator) catch process.exit(1); defer allocator.free(zig_lib_dir); var override_libc: LibCInstallation = undefined; var zig_compiler = try ZigCompiler.init(allocator); defer zig_compiler.deinit(); var comp = try Compilation.create( &zig_compiler, root_name, root_src_file, .{}, out_type, build_mode, !is_dynamic, zig_lib_dir, ); defer comp.destroy(); if (libc_arg) |libc_path| { parseLibcPaths(allocator, &override_libc, libc_path); comp.override_libc = &override_libc; } for (system_libs.span()) |lib| { _ = try comp.addLinkLib(lib, true); } comp.version = version; comp.is_test = false; comp.linker_script = linker_script; comp.clang_argv = clang_argv_buf.span(); comp.strip = strip; comp.verbose_tokenize = verbose_tokenize; comp.verbose_ast_tree = verbose_ast_tree; comp.verbose_ast_fmt = verbose_ast_fmt; comp.verbose_link = verbose_link; comp.verbose_ir = verbose_ir; comp.verbose_llvm_ir = verbose_llvm_ir; comp.verbose_cimport = verbose_cimport; comp.link_eh_frame_hdr = link_eh_frame_hdr; comp.err_color = color; comp.linker_rdynamic = linker_rdynamic; if (macosx_version_min != null and ios_version_min != null) { try stderr.writeAll("-mmacosx-version-min and -mios-version-min options not allowed together\n"); process.exit(1); } if (macosx_version_min) |ver| { comp.darwin_version_min = Compilation.DarwinVersionMin{ .MacOS = ver }; } if (ios_version_min) |ver| { comp.darwin_version_min = Compilation.DarwinVersionMin{ .Ios = ver }; } comp.emit_bin = emit_bin; comp.emit_asm = emit_asm; comp.emit_llvm_ir = emit_llvm_ir; comp.emit_h = emit_h; comp.assembly_files = assembly_files.span(); comp.link_objects = link_objects.span(); comp.start(); processBuildEvents(comp, color); } fn processBuildEvents(comp: *Compilation, color: errmsg.Color) void { const stderr_file = io.getStdErr(); const stderr = stderr_file.outStream(); var count: usize = 0; while (!comp.cancelled) { const build_event = comp.events.get(); count += 1; switch (build_event) { .Ok => { stderr.print("Build {} succeeded\n", .{count}) catch process.exit(1); }, .Error => |err| { stderr.print("Build {} failed: {}\n", .{ count, @errorName(err) }) catch process.exit(1); }, .Fail => |msgs| { stderr.print("Build {} compile errors:\n", .{count}) catch process.exit(1); for (msgs) |msg| { defer msg.destroy(); msg.printToFile(stderr_file, color) catch process.exit(1); } }, } } } pub const usage_fmt = \\usage: zig fmt [file]... \\ \\ Formats the input files and modifies them in-place. \\ Arguments can be files or directories, which are searched \\ recursively. \\ \\Options: \\ --help Print this help and exit \\ --color [auto|off|on] Enable or disable colored error messages \\ --stdin Format code from stdin; output to stdout \\ --check List non-conforming files and exit with an error \\ if the list is non-empty \\ \\ ; const Fmt = struct { seen: event.Locked(SeenMap), any_error: bool, color: errmsg.Color, allocator: *Allocator, const SeenMap = std.StringHashMap(void); }; fn parseLibcPaths(allocator: *Allocator, libc: *LibCInstallation, libc_paths_file: []const u8) void { const stderr = io.getStdErr().outStream(); libc.* = LibCInstallation.parse(allocator, libc_paths_file, stderr) catch |err| { stderr.print("Unable to parse libc path file '{}': {}.\n" ++ "Try running `zig libc` to see an example for the native target.\n", .{ libc_paths_file, @errorName(err), }) catch {}; process.exit(1); }; } fn cmdLibC(allocator: *Allocator, args: []const []const u8) !void { const stderr = io.getStdErr().outStream(); switch (args.len) { 0 => {}, 1 => { var libc_installation: LibCInstallation = undefined; parseLibcPaths(allocator, &libc_installation, args[0]); return; }, else => { try stderr.print("unexpected extra parameter: {}\n", .{args[1]}); process.exit(1); }, } var zig_compiler = try ZigCompiler.init(allocator); defer zig_compiler.deinit(); const libc = zig_compiler.getNativeLibC() catch |err| { stderr.print("unable to find libc: {}\n", .{@errorName(err)}) catch {}; process.exit(1); }; libc.render(io.getStdOut().outStream()) catch process.exit(1); } fn cmdFmt(allocator: *Allocator, args: []const []const u8) !void { const stderr_file = io.getStdErr(); const stderr = stderr_file.outStream(); var color: errmsg.Color = .Auto; var stdin_flag: bool = false; var check_flag: bool = false; var input_files = ArrayList([]const u8).init(allocator); { var i: usize = 0; while (i < args.len) : (i += 1) { const arg = args[i]; if (mem.startsWith(u8, arg, "-")) { if (mem.eql(u8, arg, "--help")) { const stdout = io.getStdOut().outStream(); try stdout.writeAll(usage_fmt); process.exit(0); } else if (mem.eql(u8, arg, "--color")) { if (i + 1 >= args.len) { try stderr.writeAll("expected [auto|on|off] after --color\n"); process.exit(1); } i += 1; const next_arg = args[i]; if (mem.eql(u8, next_arg, "auto")) { color = .Auto; } else if (mem.eql(u8, next_arg, "on")) { color = .On; } else if (mem.eql(u8, next_arg, "off")) { color = .Off; } else { try stderr.print("expected [auto|on|off] after --color, found '{}'\n", .{next_arg}); process.exit(1); } } else if (mem.eql(u8, arg, "--stdin")) { stdin_flag = true; } else if (mem.eql(u8, arg, "--check")) { check_flag = true; } else { try stderr.print("unrecognized parameter: '{}'", .{arg}); process.exit(1); } } else { try input_files.append(arg); } } } if (stdin_flag) { if (input_files.len != 0) { try stderr.writeAll("cannot use --stdin with positional arguments\n"); process.exit(1); } const stdin = io.getStdIn().inStream(); const source_code = try stdin.readAllAlloc(allocator, max_src_size); defer allocator.free(source_code); const tree = std.zig.parse(allocator, source_code) catch |err| { try stderr.print("error parsing stdin: {}\n", .{err}); process.exit(1); }; defer tree.deinit(); var error_it = tree.errors.iterator(0); while (error_it.next()) |parse_error| { const msg = try errmsg.Msg.createFromParseError(allocator, parse_error, tree, "<stdin>"); defer msg.destroy(); try msg.printToFile(io.getStdErr(), color); } if (tree.errors.len != 0) { process.exit(1); } if (check_flag) { const anything_changed = try std.zig.render(allocator, io.null_out_stream, tree); const code: u8 = if (anything_changed) 1 else 0; process.exit(code); } const stdout = io.getStdOut().outStream(); _ = try std.zig.render(allocator, stdout, tree); return; } if (input_files.len == 0) { try stderr.writeAll("expected at least one source file argument\n"); process.exit(1); } var fmt = Fmt{ .allocator = allocator, .seen = event.Locked(Fmt.SeenMap).init(Fmt.SeenMap.init(allocator)), .any_error = false, .color = color, }; var group = event.Group(FmtError!void).init(allocator); for (input_files.span()) |file_path| { try group.call(fmtPath, .{ &fmt, file_path, check_flag }); } try group.wait(); if (fmt.any_error) { process.exit(1); } } const FmtError = error{ SystemResources, OperationAborted, IoPending, BrokenPipe, Unexpected, WouldBlock, FileClosed, DestinationAddressRequired, DiskQuota, FileTooBig, InputOutput, NoSpaceLeft, AccessDenied, OutOfMemory, RenameAcrossMountPoints, ReadOnlyFileSystem, LinkQuotaExceeded, FileBusy, CurrentWorkingDirectoryUnlinked, } || fs.File.OpenError; async fn fmtPath(fmt: *Fmt, file_path_ref: []const u8, check_mode: bool) FmtError!void { const stderr_file = io.getStdErr(); const stderr = stderr_file.outStream(); const file_path = try std.mem.dupe(fmt.allocator, u8, file_path_ref); defer fmt.allocator.free(file_path); { const held = fmt.seen.acquire(); defer held.release(); if (try held.value.put(file_path, {})) |_| return; } const source_code = fs.cwd().readFileAlloc( fmt.allocator, file_path, max_src_size, ) catch |err| switch (err) { error.IsDir, error.AccessDenied => { var dir = try fs.cwd().openDir(file_path, .{ .iterate = true }); defer dir.close(); var group = event.Group(FmtError!void).init(fmt.allocator); var it = dir.iterate(); while (try it.next()) |entry| { if (entry.kind == .Directory or mem.endsWith(u8, entry.name, ".zig")) { const full_path = try fs.path.join(fmt.allocator, &[_][]const u8{ file_path, entry.name }); @panic("TODO https://github.com/ziglang/zig/issues/3777"); // try group.call(fmtPath, .{fmt, full_path, check_mode}); } } return group.wait(); }, else => { // TODO lock stderr printing try stderr.print("unable to open '{}': {}\n", .{ file_path, err }); fmt.any_error = true; return; }, }; defer fmt.allocator.free(source_code); const tree = std.zig.parse(fmt.allocator, source_code) catch |err| { try stderr.print("error parsing file '{}': {}\n", .{ file_path, err }); fmt.any_error = true; return; }; defer tree.deinit(); var error_it = tree.errors.iterator(0); while (error_it.next()) |parse_error| { const msg = try errmsg.Msg.createFromParseError(fmt.allocator, parse_error, tree, file_path); defer fmt.allocator.destroy(msg); try msg.printToFile(stderr_file, fmt.color); } if (tree.errors.len != 0) { fmt.any_error = true; return; } if (check_mode) { const anything_changed = try std.zig.render(fmt.allocator, io.null_out_stream, tree); if (anything_changed) { try stderr.print("{}\n", .{file_path}); fmt.any_error = true; } } else { // TODO make this evented const baf = try io.BufferedAtomicFile.create(fmt.allocator, file_path); defer baf.destroy(); const anything_changed = try std.zig.render(fmt.allocator, baf.stream(), tree); if (anything_changed) { try stderr.print("{}\n", .{file_path}); try baf.finish(); } } } fn cmdVersion(allocator: *Allocator, args: []const []const u8) !void { const stdout = io.getStdOut().outStream(); try stdout.print("{}\n", .{c.ZIG_VERSION_STRING}); } fn cmdHelp(allocator: *Allocator, args: []const []const u8) !void { const stdout = io.getStdOut(); try stdout.writeAll(usage); } pub const info_zen = \\ \\ * Communicate intent precisely. \\ * Edge cases matter. \\ * Favor reading code over writing code. \\ * Only one obvious way to do things. \\ * Runtime crashes are better than bugs. \\ * Compile errors are better than runtime crashes. \\ * Incremental improvements. \\ * Avoid local maximums. \\ * Reduce the amount one must remember. \\ * Minimize energy spent on coding style. \\ * Together we serve end users. \\ \\ ; fn cmdZen(allocator: *Allocator, args: []const []const u8) !void { try io.getStdOut().writeAll(info_zen); } const usage_internal = \\usage: zig internal [subcommand] \\ \\Sub-Commands: \\ build-info Print static compiler build-info \\ \\ ; fn cmdInternal(allocator: *Allocator, args: []const []const u8) !void { const stderr = io.getStdErr().outStream(); if (args.len == 0) { try stderr.writeAll(usage_internal); process.exit(1); } const sub_commands = [_]Command{Command{ .name = "build-info", .exec = cmdInternalBuildInfo, }}; inline for (sub_commands) |sub_command| { if (mem.eql(u8, sub_command.name, args[0])) { var frame = try allocator.create(@Frame(sub_command.exec)); defer allocator.destroy(frame); frame.* = async sub_command.exec(allocator, args[1..]); return await frame; } } try stderr.print("unknown sub command: {}\n\n", .{args[0]}); try stderr.writeAll(usage_internal); } fn cmdInternalBuildInfo(allocator: *Allocator, args: []const []const u8) !void { const stdout = io.getStdOut().outStream(); try stdout.print( \\ZIG_CMAKE_BINARY_DIR {} \\ZIG_CXX_COMPILER {} \\ZIG_LLD_INCLUDE_PATH {} \\ZIG_LLD_LIBRARIES {} \\ZIG_LLVM_CONFIG_EXE {} \\ZIG_DIA_GUIDS_LIB {} \\ , .{ c.ZIG_CMAKE_BINARY_DIR, c.ZIG_CXX_COMPILER, c.ZIG_LLD_INCLUDE_PATH, c.ZIG_LLD_LIBRARIES, c.ZIG_LLVM_CONFIG_EXE, c.ZIG_DIA_GUIDS_LIB, }); } const CliPkg = struct { name: []const u8, path: []const u8, children: ArrayList(*CliPkg), parent: ?*CliPkg, pub fn init(allocator: *mem.Allocator, name: []const u8, path: []const u8, parent: ?*CliPkg) !*CliPkg { var pkg = try allocator.create(CliPkg); pkg.* = CliPkg{ .name = name, .path = path, .children = ArrayList(*CliPkg).init(allocator), .parent = parent, }; return pkg; } pub fn deinit(self: *CliPkg) void { for (self.children.span()) |child| { child.deinit(); } self.children.deinit(); } };
src-self-hosted/main.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const testing = std.testing; const SpinLock = std.SpinLock; const ThreadParker = std.ThreadParker; /// Lock may be held only once. If the same thread /// tries to acquire the same mutex twice, it deadlocks. /// This type supports static initialization and is based off of Golang 1.13 runtime.lock_futex: /// https://github.com/golang/go/blob/master/src/runtime/lock_futex.go /// When an application is built in single threaded release mode, all the functions are /// no-ops. In single threaded debug mode, there is deadlock detection. pub const Mutex = if (builtin.single_threaded) struct { lock: @typeOf(lock_init), const lock_init = if (std.debug.runtime_safety) false else {}; pub const Held = struct { mutex: *Mutex, pub fn release(self: Held) void { if (std.debug.runtime_safety) { self.mutex.lock = false; } } }; pub fn init() Mutex { return Mutex{ .lock = lock_init }; } pub fn deinit(self: *Mutex) void {} pub fn acquire(self: *Mutex) Held { if (std.debug.runtime_safety and self.lock) { @panic("deadlock detected"); } return Held{ .mutex = self }; } } else struct { state: State, // TODO: make this an enum parker: ThreadParker, const State = enum(u32) { Unlocked, Sleeping, Locked, }; /// number of iterations to spin yielding the cpu const SPIN_CPU = 4; /// number of iterations to perform in the cpu yield loop const SPIN_CPU_COUNT = 30; /// number of iterations to spin yielding the thread const SPIN_THREAD = 1; pub fn init() Mutex { return Mutex{ .state = .Unlocked, .parker = ThreadParker.init(), }; } pub fn deinit(self: *Mutex) void { self.parker.deinit(); } pub const Held = struct { mutex: *Mutex, pub fn release(self: Held) void { switch (@atomicRmw(State, &self.mutex.state, .Xchg, .Unlocked, .Release)) { .Locked => {}, .Sleeping => self.mutex.parker.unpark(@ptrCast(*const u32, &self.mutex.state)), .Unlocked => unreachable, // unlocking an unlocked mutex else => unreachable, // should never be anything else } } }; pub fn acquire(self: *Mutex) Held { // Try and speculatively grab the lock. // If it fails, the state is either Locked or Sleeping // depending on if theres a thread stuck sleeping below. var state = @atomicRmw(State, &self.state, .Xchg, .Locked, .Acquire); if (state == .Unlocked) return Held{ .mutex = self }; while (true) { // try and acquire the lock using cpu spinning on failure var spin: usize = 0; while (spin < SPIN_CPU) : (spin += 1) { var value = @atomicLoad(State, &self.state, .Monotonic); while (value == .Unlocked) value = @cmpxchgWeak(State, &self.state, .Unlocked, state, .Acquire, .Monotonic) orelse return Held{ .mutex = self }; SpinLock.yield(SPIN_CPU_COUNT); } // try and acquire the lock using thread rescheduling on failure spin = 0; while (spin < SPIN_THREAD) : (spin += 1) { var value = @atomicLoad(State, &self.state, .Monotonic); while (value == .Unlocked) value = @cmpxchgWeak(State, &self.state, .Unlocked, state, .Acquire, .Monotonic) orelse return Held{ .mutex = self }; std.os.sched_yield() catch std.time.sleep(1); } // failed to acquire the lock, go to sleep until woken up by `Held.release()` if (@atomicRmw(State, &self.state, .Xchg, .Sleeping, .Acquire) == .Unlocked) return Held{ .mutex = self }; state = .Sleeping; self.parker.park(@ptrCast(*const u32, &self.state), @enumToInt(State.Sleeping)); } } }; const TestContext = struct { mutex: *Mutex, data: i128, const incr_count = 10000; }; test "std.Mutex" { var plenty_of_memory = try std.heap.direct_allocator.alloc(u8, 300 * 1024); defer std.heap.direct_allocator.free(plenty_of_memory); var fixed_buffer_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(plenty_of_memory); var a = &fixed_buffer_allocator.allocator; var mutex = Mutex.init(); defer mutex.deinit(); var context = TestContext{ .mutex = &mutex, .data = 0, }; if (builtin.single_threaded) { worker(&context); testing.expect(context.data == TestContext.incr_count); } else { const thread_count = 10; var threads: [thread_count]*std.Thread = undefined; for (threads) |*t| { t.* = try std.Thread.spawn(&context, worker); } for (threads) |t| t.wait(); testing.expect(context.data == thread_count * TestContext.incr_count); } } fn worker(ctx: *TestContext) void { var i: usize = 0; while (i != TestContext.incr_count) : (i += 1) { const held = ctx.mutex.acquire(); defer held.release(); ctx.data += 1; } }
lib/std/mutex.zig
const std = @import("std"); const lola = @import("lola"); const zee_alloc = @import("zee_alloc"); // This is our global object pool that is back-referenced // by the runtime library. pub const ObjectPool = lola.runtime.ObjectPool([_]type{ lola.libs.runtime.LoLaList, lola.libs.runtime.LoLaDictionary, }); var allocator: *std.mem.Allocator = zee_alloc.ZeeAllocDefaults.wasm_allocator; var compile_unit: lola.CompileUnit = undefined; var pool: ObjectPool = undefined; var environment: lola.runtime.Environment = undefined; var vm: lola.runtime.VM = undefined; var is_done: bool = true; pub fn milliTimestamp() usize { return JS.millis(); } const JS = struct { extern fn writeString(data: [*]const u8, len: u32) void; extern fn readString(data: [*]u8, len: usize) usize; extern fn millis() usize; }; const API = struct { fn writeLog(_: void, str: []const u8) !usize { JS.writeString(str.ptr, @intCast(u32, str.len)); return str.len; } var debug_writer = std.io.Writer(void, error{}, writeLog){ .context = {} }; fn writeLogNL(_: void, str: []const u8) !usize { var rest = str; while (std.mem.indexOf(u8, rest, "\n")) |off| { var mid = rest[0..off]; JS.writeString(mid.ptr, @intCast(u32, mid.len)); JS.writeString("\r\n", 2); rest = rest[off + 1 ..]; } JS.writeString(rest.ptr, @intCast(u32, rest.len)); return str.len; } /// debug writer that patches LF into CRLF var debug_writer_lf = std.io.Writer(void, error{}, writeLogNL){ .context = {} }; fn validate(source: []const u8) !void { var diagnostics = lola.compiler.Diagnostics.init(allocator); defer diagnostics.deinit(); // This compiles a piece of source code into a compile unit. // A compile unit is a piece of LoLa IR code with metadata for // all existing functions, debug symbols and so on. It can be loaded into // a environment and be executed. var temp_compile_unit = try lola.compiler.compile(allocator, &diagnostics, "code", source); for (diagnostics.messages.items) |msg| { std.fmt.format(debug_writer_lf, "{}\n", .{msg}) catch unreachable; } if (temp_compile_unit) |*unit| unit.deinit(); } fn initInterpreter(source: []const u8) !void { var diagnostics = lola.compiler.Diagnostics.init(allocator); diagnostics.deinit(); const compile_unit_or_none = try lola.compiler.compile(allocator, &diagnostics, "code", source); for (diagnostics.messages.items) |msg| { std.fmt.format(debug_writer_lf, "{}\n", .{msg}) catch unreachable; } compile_unit = compile_unit_or_none orelse return error.FailedToCompile; errdefer compile_unit.deinit(); pool = ObjectPool.init(allocator); errdefer pool.deinit(); environment = try lola.runtime.Environment.init(allocator, &compile_unit, pool.interface()); errdefer environment.deinit(); try lola.libs.std.install(&environment, allocator); // try lola.libs.runtime.install(&environment, allocator); try environment.installFunction("Print", lola.runtime.Function.initSimpleUser(struct { fn Print(_environment: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.Value { // const allocator = context.get(std.mem.Allocator); for (args) |value, i| { switch (value) { .string => |str| try debug_writer.writeAll(str.contents), else => try debug_writer.print("{}", .{value}), } } try debug_writer.writeAll("\r\n"); return .void; } }.Print)); try environment.installFunction("Write", lola.runtime.Function.initSimpleUser(struct { fn Write(_environment: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.Value { // const allocator = context.get(std.mem.Allocator); for (args) |value, i| { switch (value) { .string => |str| try debug_writer.writeAll(str.contents), else => try debug_writer.print("{}", .{value}), } } return .void; } }.Write)); try environment.installFunction("Read", lola.runtime.Function.initSimpleUser(struct { fn Read(_environment: *const lola.runtime.Environment, context: lola.runtime.Context, args: []const lola.runtime.Value) anyerror!lola.runtime.Value { if (args.len != 0) return error.InvalidArgs; var buffer = std.ArrayList(u8).init(allocator); defer buffer.deinit(); while (true) { var temp: [256]u8 = undefined; const len = JS.readString(&temp, temp.len); if (len == 0) break; try buffer.appendSlice(temp[0..len]); } return lola.runtime.Value.fromString(lola.runtime.String.initFromOwned( allocator, buffer.toOwnedSlice(), )); } }.Read)); vm = try lola.runtime.VM.init(allocator, &environment); errdefer vm.deinit(); is_done = false; } fn deinitInterpreter() void { if (!is_done) { vm.deinit(); environment.deinit(); pool.deinit(); compile_unit.deinit(); } is_done = true; } fn stepInterpreter(steps: u32) !void { if (is_done) return error.InvalidInterpreterState; // Run the virtual machine for up to 150 instructions var result = vm.execute(150) catch |err| { // When the virtua machine panics, we receive a Zig error try std.fmt.format(debug_writer_lf, "\x1B[91mLoLa Panic: {}\x1B[m\n", .{@errorName(err)}); try vm.printStackTrace(debug_writer_lf); return error.LoLaPanic; }; // Prepare a garbage collection cycle: pool.clearUsageCounters(); // Mark all objects currently referenced in the environment try pool.walkEnvironment(environment); // Mark all objects currently referenced in the virtual machine try pool.walkVM(vm); // Delete all objects that are not referenced by our system anymore pool.collectGarbage(); switch (result) { // This means that our script execution has ended and // the top-level code has come to an end .completed => { // deinitialize everything, stop execution deinitInterpreter(); return; }, // This means the VM has exhausted its provided instruction quota // and returned control to the host. .exhausted => {}, // This means the virtual machine was suspended via a async function call. .paused => {}, } } }; export fn initialize() void { // nothing to init atm } export fn malloc(len: usize) [*]u8 { var slice = allocator.alloc(u8, len) catch unreachable; return slice.ptr; } export fn free(mem: [*]u8, len: usize) void { allocator.free(mem[0..len]); } const LoLaError = error{ OutOfMemory, FailedToCompile, SyntaxError, InvalidCode, AlreadyDeclared, TooManyVariables, TooManyLabels, LabelAlreadyDefined, Overflow, NotInLoop, VariableNotFound, InvalidStoreTarget, LoLaPanic, AlreadyExists, InvalidObject, InvalidInterpreterState, }; fn mapError(err: LoLaError) u8 { return switch (err) { error.OutOfMemory => 1, error.FailedToCompile => 2, error.SyntaxError => 3, error.InvalidCode => 3, error.AlreadyDeclared => 3, error.TooManyVariables => 3, error.TooManyLabels => 3, error.LabelAlreadyDefined => 3, error.Overflow => 3, error.NotInLoop => 3, error.VariableNotFound => 3, error.InvalidStoreTarget => 3, error.AlreadyExists => 3, error.LoLaPanic => 4, error.InvalidObject => 5, error.InvalidInterpreterState => 6, }; } export fn validate(source: [*]const u8, source_len: usize) u8 { API.validate(source[0..source_len]) catch |err| return mapError(err); return 0; } export fn initInterpreter(source: [*]const u8, source_len: usize) u8 { API.initInterpreter(source[0..source_len]) catch |err| return mapError(err); return 0; } export fn deinitInterpreter() void { API.deinitInterpreter(); } export fn stepInterpreter(steps: u32) u8 { API.stepInterpreter(steps) catch |err| return mapError(err); return 0; } export fn isInterpreterDone() bool { return is_done; }
src/wasm-compiler/main.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); const Map = struct { const MAX: usize = 22; const OFF: i8 = MAX / 2; cur: [MAX * MAX * MAX * MAX]bool, new: [MAX * MAX * MAX * MAX]bool, w: i8, w2: i8, alloc: std.mem.Allocator, debug: bool, const NB = [_]i8{ -1, 0, 1 }; pub fn index(x: i8, y: i8, z: i8, q: i8) usize { return @intCast(usize, x) + MAX * (@intCast(usize, y) + MAX * (@intCast(usize, z) + MAX * @intCast(usize, q))); } pub fn fromInput(alloc: std.mem.Allocator, inp: [][]const u8) !*Map { var m = try alloc.create(Map); m.alloc = alloc; std.mem.set(bool, m.cur[0..], false); std.mem.set(bool, m.new[0..], false); var size: i8 = @intCast(i8, inp.len); m.w = size; var s2: i8 = size >> 1; m.w2 = s2; var y: i8 = 0; while (y < inp.len) : (y += 1) { var x: i8 = 0; while (x < inp[@intCast(usize, y)].len) : (x += 1) { if (inp[@intCast(usize, y)][@intCast(usize, x)] == '#') { m.Set(OFF - s2 + x, OFF - s2 + y, OFF, OFF); } } } m.Swap(); return m; } pub fn deinit(self: *Map) void { self.alloc.destroy(self); } pub fn Print(self: *Map, iter: i8, part2: bool) void { var xystart: i8 = OFF - (1 + self.w2 + iter); var xyend: i8 = OFF + (2 + self.w2 + iter); var zstart: i8 = OFF - (1 + iter); var zend: i8 = OFF + (1 + iter); var qstart: i8 = OFF; var qend: i8 = OFF; if (part2) { qstart = zstart; qend = zend; } var q: i8 = qstart; while (q <= qend) : (q += 1) { var z: i8 = zstart; while (z <= zend) : (z += 1) { var y: i8 = xystart; std.debug.print("q={} z={}\n", .{ q, z }); while (y <= xyend) : (y += 1) { var x: i8 = xystart; while (x <= xyend) : (x += 1) { const cur = self.Get(x, y, z, q); if (cur) { std.debug.print("#", .{}); self.Set(x, y, z, q); } else { std.debug.print(".", .{}); } } std.debug.print(" ({} {})\n", .{ y, index(11, y, z, q) }); } } std.debug.print("\n", .{}); } } pub fn Set(self: *Map, x: i8, y: i8, z: i8, q: i8) void { self.new[index(x, y, z, q)] = true; } pub fn Get(self: *Map, x: i8, y: i8, z: i8, q: i8) bool { return self.cur[index(x, y, z, q)]; } pub fn Swap(self: *Map) void { const tmp = self.cur; self.cur = self.new; self.new = tmp; } pub fn NeighbourCount(self: *Map, x: i8, y: i8, z: i8, q: i8, part2: bool) usize { var n: usize = 0; var qfirst: usize = 0; var qlast: usize = 3; if (!part2) { qfirst = 1; qlast = 2; } for (NB[qfirst..qlast]) |oq| { for (NB[0..3]) |oz| { for (NB[0..3]) |oy| { for (NB[0..3]) |ox| { if (ox == 0 and oy == 0 and oz == 0 and oq == 0) { continue; } if (self.Get(x + ox, y + oy, z + oz, q + oq)) { n += 1; } } } } } return n; } pub fn Iter(self: *Map, iter: i8, part2: bool) usize { var n: usize = 0; std.mem.set(bool, self.new[0..], false); var xystart: i8 = OFF - (1 + self.w2 + iter); var xyend: i8 = OFF + (2 + self.w2 + iter); var zstart: i8 = OFF - (1 + iter); var zend: i8 = OFF + (1 + iter); var qstart: i8 = OFF; var qend: i8 = OFF; if (part2) { qstart = zstart; qend = zend; } var q: i8 = qstart; while (q <= qend) : (q += 1) { var z: i8 = zstart; while (z <= zend) : (z += 1) { var y: i8 = xystart; while (y <= xyend) : (y += 1) { var x: i8 = xystart; while (x <= xyend) : (x += 1) { const nc = self.NeighbourCount(x, y, z, q, part2); const cur = self.Get(x, y, z, q); var new = false; if ((cur and nc == 2) or nc == 3) { new = true; } if (new) { self.Set(x, y, z, q); n += 1; } } } } } self.Swap(); //self.Print(iter, part2); return n; } pub fn Calc(self: *Map, part2: bool) usize { var r: usize = 0; var i: i8 = 0; while (i < 6) : (i += 1) { r = self.Iter(i, part2); if (self.debug) { std.debug.print("Iter {}: {}\n", .{ i, r }); } } return r; } pub fn Part1(self: *Map) !usize { return self.Calc(false); } pub fn Part2(self: *Map) !usize { return self.Calc(true); } }; test "part1" { const test0 = aoc.readLines(aoc.talloc, aoc.test0file); defer aoc.talloc.free(test0); const test1 = aoc.readLines(aoc.talloc, aoc.test1file); defer aoc.talloc.free(test1); const inp = aoc.readLines(aoc.talloc, aoc.inputfile); defer aoc.talloc.free(inp); var t1m = Map.fromInput(aoc.talloc, test1) catch unreachable; try aoc.assertEq(@as(usize, 112), try t1m.Part1()); t1m.deinit(); t1m = Map.fromInput(aoc.talloc, test1) catch unreachable; defer t1m.deinit(); try aoc.assertEq(@as(usize, 848), try t1m.Part2()); var m = Map.fromInput(aoc.talloc, inp) catch unreachable; try aoc.assertEq(@as(usize, 209), try m.Part1()); m.deinit(); m = Map.fromInput(aoc.talloc, inp) catch unreachable; defer m.deinit(); try aoc.assertEq(@as(usize, 1492), try m.Part2()); } fn day17(inp: []const u8, bench: bool) anyerror!void { const lines = aoc.readLines(aoc.halloc, inp); defer aoc.halloc.free(lines); var m = try Map.fromInput(aoc.halloc, lines); var p1 = m.Part1(); m.deinit(); m = try Map.fromInput(aoc.halloc, lines); defer m.deinit(); var p2 = m.Part2(); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p1, p2 }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day17); }
2020/17/aoc.zig
const std = @import("std"); const math = std.math; const expect = std.testing.expect; pub fn __floorh(x: f16) callconv(.C) f16 { var u = @bitCast(u16, x); const e = @intCast(i16, (u >> 10) & 31) - 15; var m: u16 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 10) { return x; } if (e >= 0) { m = @as(u16, 1023) >> @intCast(u4, e); if (u & m == 0) { return x; } math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 15 != 0) { u += m; } return @bitCast(f16, u & ~m); } else { math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 15 == 0) { return 0.0; } else { return -1.0; } } } pub fn floorf(x: f32) callconv(.C) f32 { var u = @bitCast(u32, x); const e = @intCast(i32, (u >> 23) & 0xFF) - 0x7F; var m: u32 = undefined; // TODO: Shouldn't need this explicit check. if (x == 0.0) { return x; } if (e >= 23) { return x; } if (e >= 0) { m = @as(u32, 0x007FFFFF) >> @intCast(u5, e); if (u & m == 0) { return x; } math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 != 0) { u += m; } return @bitCast(f32, u & ~m); } else { math.doNotOptimizeAway(x + 0x1.0p120); if (u >> 31 == 0) { return 0.0; } else { return -1.0; } } } pub fn floor(x: f64) callconv(.C) f64 { const f64_toint = 1.0 / math.floatEps(f64); const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; var y: f64 = undefined; if (e >= 0x3FF + 52 or x == 0) { return x; } if (u >> 63 != 0) { y = x - f64_toint + f64_toint - x; } else { y = x + f64_toint - f64_toint - x; } if (e <= 0x3FF - 1) { math.doNotOptimizeAway(y); if (u >> 63 != 0) { return -1.0; } else { return 0.0; } } else if (y > 0) { return x + y - 1; } else { return x + y; } } pub fn __floorx(x: f80) callconv(.C) f80 { // TODO: more efficient implementation return @floatCast(f80, floorq(x)); } pub fn floorq(x: f128) callconv(.C) f128 { const f128_toint = 1.0 / math.floatEps(f128); const u = @bitCast(u128, x); const e = (u >> 112) & 0x7FFF; var y: f128 = undefined; if (e >= 0x3FFF + 112 or x == 0) return x; if (u >> 127 != 0) { y = x - f128_toint + f128_toint - x; } else { y = x + f128_toint - f128_toint - x; } if (e <= 0x3FFF - 1) { math.doNotOptimizeAway(y); if (u >> 127 != 0) { return -1.0; } else { return 0.0; } } else if (y > 0) { return x + y - 1; } else { return x + y; } } test "floor16" { try expect(__floorh(1.3) == 1.0); try expect(__floorh(-1.3) == -2.0); try expect(__floorh(0.2) == 0.0); } test "floor32" { try expect(floorf(1.3) == 1.0); try expect(floorf(-1.3) == -2.0); try expect(floorf(0.2) == 0.0); } test "floor64" { try expect(floor(1.3) == 1.0); try expect(floor(-1.3) == -2.0); try expect(floor(0.2) == 0.0); } test "floor128" { try expect(floorq(1.3) == 1.0); try expect(floorq(-1.3) == -2.0); try expect(floorq(0.2) == 0.0); } test "floor16.special" { try expect(__floorh(0.0) == 0.0); try expect(__floorh(-0.0) == -0.0); try expect(math.isPositiveInf(__floorh(math.inf(f16)))); try expect(math.isNegativeInf(__floorh(-math.inf(f16)))); try expect(math.isNan(__floorh(math.nan(f16)))); } test "floor32.special" { try expect(floorf(0.0) == 0.0); try expect(floorf(-0.0) == -0.0); try expect(math.isPositiveInf(floorf(math.inf(f32)))); try expect(math.isNegativeInf(floorf(-math.inf(f32)))); try expect(math.isNan(floorf(math.nan(f32)))); } test "floor64.special" { try expect(floor(0.0) == 0.0); try expect(floor(-0.0) == -0.0); try expect(math.isPositiveInf(floor(math.inf(f64)))); try expect(math.isNegativeInf(floor(-math.inf(f64)))); try expect(math.isNan(floor(math.nan(f64)))); } test "floor128.special" { try expect(floorq(0.0) == 0.0); try expect(floorq(-0.0) == -0.0); try expect(math.isPositiveInf(floorq(math.inf(f128)))); try expect(math.isNegativeInf(floorq(-math.inf(f128)))); try expect(math.isNan(floorq(math.nan(f128)))); }
lib/std/special/compiler_rt/floor.zig
const std = @import("std"); const math = std.math; const expect = std.testing.expect; const trig = @import("trig.zig"); const rem_pio2 = @import("rem_pio2.zig").rem_pio2; const rem_pio2f = @import("rem_pio2f.zig").rem_pio2f; pub fn __cosh(a: f16) callconv(.C) f16 { // TODO: more efficient implementation return @floatCast(f16, cosf(a)); } pub fn cosf(x: f32) callconv(.C) f32 { // Small multiples of pi/2 rounded to double precision. const c1pio2: f64 = 1.0 * math.pi / 2.0; // 0x3FF921FB, 0x54442D18 const c2pio2: f64 = 2.0 * math.pi / 2.0; // 0x400921FB, 0x54442D18 const c3pio2: f64 = 3.0 * math.pi / 2.0; // 0x4012D97C, 0x7F3321D2 const c4pio2: f64 = 4.0 * math.pi / 2.0; // 0x401921FB, 0x54442D18 var ix = @bitCast(u32, x); const sign = ix >> 31 != 0; ix &= 0x7fffffff; if (ix <= 0x3f490fda) { // |x| ~<= pi/4 if (ix < 0x39800000) { // |x| < 2**-12 // raise inexact if x != 0 math.doNotOptimizeAway(x + 0x1p120); return 1.0; } return trig.__cosdf(x); } if (ix <= 0x407b53d1) { // |x| ~<= 5*pi/4 if (ix > 0x4016cbe3) { // |x| ~> 3*pi/4 return -trig.__cosdf(if (sign) x + c2pio2 else x - c2pio2); } else { if (sign) { return trig.__sindf(x + c1pio2); } else { return trig.__sindf(c1pio2 - x); } } } if (ix <= 0x40e231d5) { // |x| ~<= 9*pi/4 if (ix > 0x40afeddf) { // |x| ~> 7*pi/4 return trig.__cosdf(if (sign) x + c4pio2 else x - c4pio2); } else { if (sign) { return trig.__sindf(-x - c3pio2); } else { return trig.__sindf(x - c3pio2); } } } // cos(Inf or NaN) is NaN if (ix >= 0x7f800000) { return x - x; } var y: f64 = undefined; const n = rem_pio2f(x, &y); return switch (n & 3) { 0 => trig.__cosdf(y), 1 => trig.__sindf(-y), 2 => -trig.__cosdf(y), else => trig.__sindf(y), }; } pub fn cos(x: f64) callconv(.C) f64 { var ix = @bitCast(u64, x) >> 32; ix &= 0x7fffffff; // |x| ~< pi/4 if (ix <= 0x3fe921fb) { if (ix < 0x3e46a09e) { // |x| < 2**-27 * sqrt(2) // raise inexact if x!=0 math.doNotOptimizeAway(x + 0x1p120); return 1.0; } return trig.__cos(x, 0); } // cos(Inf or NaN) is NaN if (ix >= 0x7ff00000) { return x - x; } var y: [2]f64 = undefined; const n = rem_pio2(x, &y); return switch (n & 3) { 0 => trig.__cos(y[0], y[1]), 1 => -trig.__sin(y[0], y[1], 1), 2 => -trig.__cos(y[0], y[1]), else => trig.__sin(y[0], y[1], 1), }; } pub fn __cosx(a: f80) callconv(.C) f80 { // TODO: more efficient implementation return @floatCast(f80, cosq(a)); } pub fn cosq(a: f128) callconv(.C) f128 { // TODO: more correct implementation return cos(@floatCast(f64, a)); } test "cos32" { const epsilon = 0.00001; try expect(math.approxEqAbs(f32, cosf(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f32, cosf(0.2), 0.980067, epsilon)); try expect(math.approxEqAbs(f32, cosf(0.8923), 0.627623, epsilon)); try expect(math.approxEqAbs(f32, cosf(1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f32, cosf(-1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f32, cosf(37.45), 0.969132, epsilon)); try expect(math.approxEqAbs(f32, cosf(89.123), 0.400798, epsilon)); } test "cos64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, cos(0.0), 1.0, epsilon)); try expect(math.approxEqAbs(f64, cos(0.2), 0.980067, epsilon)); try expect(math.approxEqAbs(f64, cos(0.8923), 0.627623, epsilon)); try expect(math.approxEqAbs(f64, cos(1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f64, cos(-1.5), 0.070737, epsilon)); try expect(math.approxEqAbs(f64, cos(37.45), 0.969132, epsilon)); try expect(math.approxEqAbs(f64, cos(89.123), 0.40080, epsilon)); } test "cos32.special" { try expect(math.isNan(cosf(math.inf(f32)))); try expect(math.isNan(cosf(-math.inf(f32)))); try expect(math.isNan(cosf(math.nan(f32)))); } test "cos64.special" { try expect(math.isNan(cos(math.inf(f64)))); try expect(math.isNan(cos(-math.inf(f64)))); try expect(math.isNan(cos(math.nan(f64)))); }
lib/std/special/compiler_rt/cos.zig
const std = @import("std"); const mem = std.mem; const math = std.math; const os = std.os; const windows = os.windows; const ws2_32 = windows.ws2_32; pub const FILE_SKIP_COMPLETION_PORT_ON_SUCCESS = 0x1; pub const FILE_SKIP_SET_EVENT_ON_HANDLE = 0x2; pub const CTRL_C_EVENT: windows.DWORD = 0; pub const CTRL_BREAK_EVENT: windows.DWORD = 1; pub const CTRL_CLOSE_EVENT: windows.DWORD = 2; pub const CTRL_LOGOFF_EVENT: windows.DWORD = 5; pub const CTRL_SHUTDOWN_EVENT: windows.DWORD = 6; pub const HANDLER_ROUTINE = fn (dwCtrlType: windows.DWORD) callconv(.C) windows.BOOL; pub const OVERLAPPED_ENTRY = extern struct { lpCompletionKey: windows.ULONG_PTR, lpOverlapped: ?windows.LPOVERLAPPED, Internal: windows.ULONG_PTR, dwNumberOfBytesTransferred: windows.DWORD, }; pub fn loadWinsockExtensionFunction(comptime T: type, sock: ws2_32.SOCKET, guid: windows.GUID) !T { var function: T = undefined; var num_bytes: windows.DWORD = undefined; const rc = ws2_32.WSAIoctl( sock, @import("windows/ws2_32.zig").SIO_GET_EXTENSION_FUNCTION_POINTER, @ptrCast(*const anyopaque, &guid), @sizeOf(windows.GUID), &function, @sizeOf(T), &num_bytes, null, null, ); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAENOTSOCK => error.FileDescriptorNotASocket, else => |err| windows.unexpectedWSAError(err), }; } if (num_bytes != @sizeOf(T)) { return error.ShortRead; } return function; } pub fn SetConsoleCtrlHandler(handler_routine: ?HANDLER_ROUTINE, add: bool) !void { const success = @import("windows/kernel32.zig").SetConsoleCtrlHandler( handler_routine, if (add) windows.TRUE else windows.FALSE, ); if (success == windows.FALSE) { return switch (windows.kernel32.GetLastError()) { else => |err| windows.unexpectedError(err), }; } } pub fn SetFileCompletionNotificationModes(handle: windows.HANDLE, flags: windows.UCHAR) !void { const success = @import("windows/kernel32.zig").SetFileCompletionNotificationModes(handle, flags); if (success == windows.FALSE) { return windows.unexpectedError(windows.kernel32.GetLastError()); } } pub const GetQueuedCompletionStatusError = error{ Aborted, Cancelled, EOF, Timeout, } || os.UnexpectedError; pub fn GetQueuedCompletionStatusEx( completion_port: windows.HANDLE, completion_port_entries: []windows.OVERLAPPED_ENTRY, timeout_ms: ?windows.DWORD, alertable: bool, ) GetQueuedCompletionStatusError!u32 { var num_entries_removed: u32 = 0; const success = @import("windows/kernel32.zig").GetQueuedCompletionStatusEx( completion_port, completion_port_entries.ptr, @intCast(windows.ULONG, completion_port_entries.len), &num_entries_removed, timeout_ms orelse windows.INFINITE, @boolToInt(alertable), ); if (success == windows.FALSE) { return switch (windows.kernel32.GetLastError()) { .ABANDONED_WAIT_0 => error.Aborted, .OPERATION_ABORTED => error.Cancelled, .HANDLE_EOF => error.EOF, .IMEOUT => error.Timeout, else => |err| windows.unexpectedError(err), }; } return num_entries_removed; } pub fn pollBaseSocket(socket: ws2_32.SOCKET, ioctl_code: windows.DWORD) !ws2_32.SOCKET { var base_socket: ws2_32.SOCKET = undefined; var num_bytes: windows.DWORD = 0; const rc = ws2_32.WSAIoctl( socket, ioctl_code, null, 0, @ptrCast([*]u8, &base_socket), @sizeOf(ws2_32.SOCKET), &num_bytes, null, null, ); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAEOPNOTSUPP => error.OperationNotSupported, else => |err| windows.unexpectedWSAError(err), }; } if (num_bytes != @sizeOf(ws2_32.SOCKET)) { return error.ShortRead; } return base_socket; } pub fn getBaseSocket(socket: ws2_32.SOCKET) !ws2_32.SOCKET { const err = if (pollBaseSocket(socket, @import("windows/ws2_32.zig").SIO_BASE_HANDLE)) |base_socket| return base_socket else |err| err; inline for (.{ @import("windows/ws2_32.zig").SIO_BSP_HANDLE_SELECT, @import("windows/ws2_32.zig").SIO_BSP_HANDLE_POLL, @import("windows/ws2_32.zig").SIO_BSP_HANDLE, }) |ioctl_code| { if (pollBaseSocket(socket, ioctl_code)) |base_socket| return base_socket else |_| {} } return err; } pub fn GetAcceptExSockaddrs(socket: ws2_32.SOCKET, buf: []const u8, local_addr_len: u32, remote_addr_len: u32, local_addr: **ws2_32.sockaddr, remote_addr: **ws2_32.sockaddr) !void { const func = try loadWinsockExtensionFunction(@import("windows/ws2_32.zig").GetAcceptExSockaddrs, socket, @import("windows/ws2_32.zig").WSAID_GETACCEPTEXSOCKADDRS); var local_addr_ptr_len = @as(c_int, @sizeOf(ws2_32.sockaddr)); var remote_addr_ptr_len = @as(c_int, @sizeOf(ws2_32.sockaddr)); func( buf.ptr, 0, local_addr_len, remote_addr_len, local_addr, &local_addr_ptr_len, remote_addr, &remote_addr_ptr_len, ); } pub fn AcceptEx(listening_socket: ws2_32.SOCKET, accepted_socket: ws2_32.SOCKET, buf: []u8, local_addr_len: u32, remote_addr_len: u32, num_bytes: *windows.DWORD, overlapped: *windows.OVERLAPPED) !void { const func = try loadWinsockExtensionFunction(@import("windows/ws2_32.zig").AcceptEx, listening_socket, @import("windows/ws2_32.zig").WSAID_ACCEPTEX); const success = func( listening_socket, accepted_socket, buf.ptr, 0, local_addr_len, remote_addr_len, num_bytes, overlapped, ); if (success == windows.FALSE) { return switch (ws2_32.WSAGetLastError()) { .WSAECONNRESET => error.ConnectionResetByPeer, .WSAEFAULT => error.BadAddress, .WSAEINVAL => error.SocketNotListening, .WSAEMFILE => error.ProcessFdQuotaExceeded, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAENOBUFS => error.FileDescriptorNotASocket, .WSAEOPNOTSUPP => error.OperationNotSupported, .WSA_IO_PENDING, .WSAEWOULDBLOCK => error.WouldBlock, else => |err| windows.unexpectedWSAError(err), }; } } pub fn ConnectEx(sock: ws2_32.SOCKET, sock_addr: *const ws2_32.sockaddr, sock_len: ws2_32.socklen_t, overlapped: *windows.OVERLAPPED) !void { const func = try loadWinsockExtensionFunction(@import("windows/ws2_32.zig").ConnectEx, sock, @import("windows/ws2_32.zig").WSAID_CONNECTEX); const success = func(sock, sock_addr, @intCast(c_int, sock_len), null, 0, null, overlapped); if (success == windows.FALSE) { return switch (ws2_32.WSAGetLastError()) { .WSAEADDRINUSE => error.AddressInUse, .WSAEADDRNOTAVAIL => error.AddressNotAvailable, .WSAECONNREFUSED => error.ConnectionRefused, .WSAETIMEDOUT => error.ConnectionTimedOut, .WSAEFAULT => error.BadAddress, .WSAEINVAL => error.NotYetBound, .WSAEISCONN => error.AlreadyConnected, .WSAENOTSOCK => error.NotASocket, .WSAEACCES => error.BroadcastNotEnabled, .WSAENOBUFS => error.SystemResources, .WSAEAFNOSUPPORT => error.AddressFamilyNotSupported, .WSA_IO_PENDING, .WSAEINPROGRESS, .WSAEWOULDBLOCK => error.WouldBlock, .WSAEHOSTUNREACH, .WSAENETUNREACH => error.NetworkUnreachable, else => |err| windows.unexpectedWSAError(err), }; } } pub fn bind_(sock: ws2_32.SOCKET, sock_addr: *const ws2_32.sockaddr, sock_len: ws2_32.socklen_t) !void { const rc = ws2_32.bind(sock, sock_addr, @intCast(c_int, sock_len)); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAEACCES => error.AccessDenied, .WSAEADDRINUSE => error.AddressInUse, .WSAEADDRNOTAVAIL => error.AddressNotAvailable, .WSAEFAULT => error.BadAddress, .WSAEINPROGRESS => error.WouldBlock, .WSAEINVAL => error.AlreadyBound, .WSAENOBUFS => error.NoEphemeralPortsAvailable, .WSAENOTSOCK => error.NotASocket, else => |err| windows.unexpectedWSAError(err), }; } } pub fn listen_(sock: ws2_32.SOCKET, backlog: usize) !void { const rc = ws2_32.listen(sock, @intCast(c_int, backlog)); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAEADDRINUSE => error.AddressInUse, .WSAEISCONN => error.AlreadyConnected, .WSAEINVAL => error.SocketNotBound, .WSAEMFILE, .WSAENOBUFS => error.SystemResources, .WSAENOTSOCK => error.FileDescriptorNotASocket, .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAEINPROGRESS => error.WouldBlock, else => |err| windows.unexpectedWSAError(err), }; } } pub fn connect(sock: ws2_32.SOCKET, sock_addr: *const ws2_32.sockaddr, len: ws2_32.socklen_t) !void { const rc = ws2_32.connect(sock, sock_addr, @intCast(i32, len)); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAEADDRINUSE => error.AddressInUse, .WSAEADDRNOTAVAIL => error.AddressNotAvailable, .WSAECONNREFUSED => error.ConnectionRefused, .WSAETIMEDOUT => error.ConnectionTimedOut, .WSAEFAULT => error.BadAddress, .WSAEINVAL => error.ListeningSocket, .WSAEISCONN => error.AlreadyConnected, .WSAENOTSOCK => error.NotASocket, .WSAEACCES => error.BroadcastNotEnabled, .WSAENOBUFS => error.SystemResources, .WSAEAFNOSUPPORT => error.AddressFamilyNotSupported, .WSAEINPROGRESS, .WSAEWOULDBLOCK => error.WouldBlock, .WSAEHOSTUNREACH, .WSAENETUNREACH => error.NetworkUnreachable, else => |err| windows.unexpectedWSAError(err), }; } } pub fn recv(sock: ws2_32.SOCKET, buf: []u8) !usize { const rc = @import("windows/ws2_32.zig").recv(sock, buf.ptr, @intCast(c_int, buf.len), 0); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSANOTINITIALISED => error.WinsockNotInitialized, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAEFAULT => error.BadBuffer, .WSAENOTCONN => error.SocketNotConnected, .WSAEINTR => error.Cancelled, .WSAEINPROGRESS, .WSAEWOULDBLOCK => error.WouldBlock, .WSAENETRESET => error.NetworkReset, .WSAENOTSOCK => error.NotASocket, .WSAEOPNOTSUPP => error.FlagNotSupported, .WSAESHUTDOWN => error.EndOfFile, .WSAEMSGSIZE => error.MessageTooLarge, .WSAEINVAL => error.SocketNotBound, .WSAECONNABORTED => error.ConnectionAborted, .WSAETIMEDOUT => error.Timeout, .WSAECONNRESET => error.Refused, else => |err| windows.unexpectedWSAError(err), }; } return @intCast(usize, rc); } pub fn getsockopt(comptime T: type, handle: ws2_32.SOCKET, level: c_int, opt: c_int) !T { var val: T = undefined; var val_len: c_int = @sizeOf(T); const result = @import("windows/ws2_32.zig").getsockopt(handle, level, opt, @ptrCast([*]u8, &val), &val_len); if (result == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAEFAULT => error.InvalidParameter, .WSAENOPROTOOPT => error.UnsupportedOption, .WSAENOTSOCK => error.NotASocket, else => |err| windows.unexpectedWSAError(err), }; } return val; } pub fn shutdown(socket: ws2_32.SOCKET, how: c_int) !void { const result = @import("windows/ws2_32.zig").shutdown(socket, how); if (result == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAECONNABORTED => error.ConnectionAborted, .WSAECONNRESET => error.ConnectionResetByPeer, .WSAEINPROGRESS => error.WouldBlock, .WSAEINVAL => error.BadArgument, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAENOTCONN => error.SocketNotConnected, .WSAENOTSOCK => error.FileDescriptorNotASocket, else => |err| windows.unexpectedWSAError(err), }; } } pub const SetSockOptError = error{ /// The socket is already connected, and a specified option cannot be set while the socket is connected. AlreadyConnected, /// The option is not supported by the protocol. InvalidProtocolOption, /// The send and receive timeout values are too big to fit into the timeout fields in the socket structure. TimeoutTooBig, /// Insufficient resources are available in the system to complete the call. SystemResources, NetworkSubsystemFailed, FileDescriptorNotASocket, SocketNotBound, SocketNotConnected, AlreadyShutdown, } || std.os.UnexpectedError; pub fn setsockopt(sock: ws2_32.SOCKET, level: u32, opt: u32, val: ?[]const u8) SetSockOptError!void { const rc = ws2_32.setsockopt(sock, level, opt, if (val) |v| v.ptr else null, if (val) |v| @intCast(ws2_32.socklen_t, v.len) else 0); if (rc == ws2_32.SOCKET_ERROR) { switch (ws2_32.WSAGetLastError()) { .WSANOTINITIALISED => unreachable, .WSAENETDOWN => return error.NetworkSubsystemFailed, .WSAEFAULT => unreachable, .WSAENOTSOCK => return error.FileDescriptorNotASocket, .WSAEINVAL => return error.SocketNotBound, .WSAENOTCONN => return error.SocketNotConnected, .WSAESHUTDOWN => return error.AlreadyShutdown, else => |err| return windows.unexpectedWSAError(err), } } } pub fn WSASendTo(sock: ws2_32.SOCKET, buf: []const u8, flags: windows.DWORD, addr: ?*const ws2_32.sockaddr, addr_len: ws2_32.socklen_t, overlapped: *windows.OVERLAPPED) !void { var wsa_buf = ws2_32.WSABUF{ .len = @truncate(u32, buf.len), .buf = @intToPtr([*]u8, @ptrToInt(buf.ptr)), }; const rc = ws2_32.WSASendTo(sock, @intToPtr([*]ws2_32.WSABUF, @ptrToInt(&wsa_buf)), 1, null, flags, addr, @intCast(c_int, addr_len), @ptrCast(*ws2_32.WSAOVERLAPPED, overlapped), null); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAECONNABORTED => error.ConnectionAborted, .WSAECONNRESET => error.ConnectionResetByPeer, .WSAEFAULT => error.BadBuffer, .WSAEINPROGRESS, .WSAEWOULDBLOCK, .WSA_IO_PENDING => error.WouldBlock, .WSAEINTR => error.Cancelled, .WSAEINVAL => error.SocketNotBound, .WSAEMSGSIZE => error.MessageTooLarge, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAENETRESET => error.NetworkReset, .WSAENOBUFS => error.BufferDeadlock, .WSAENOTCONN => error.SocketNotConnected, .WSAENOTSOCK => error.FileDescriptorNotASocket, .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAESHUTDOWN => error.AlreadyShutdown, .WSAETIMEDOUT => error.Timeout, .WSA_OPERATION_ABORTED => error.OperationAborted, else => |err| windows.unexpectedWSAError(err), }; } } pub fn WSASend(sock: ws2_32.SOCKET, buf: []const u8, flags: windows.DWORD, overlapped: *windows.OVERLAPPED) !void { var wsa_buf = ws2_32.WSABUF{ .len = @truncate(u32, buf.len), .buf = @intToPtr([*]u8, @ptrToInt(buf.ptr)), }; const rc = ws2_32.WSASend(sock, @intToPtr([*]ws2_32.WSABUF, @ptrToInt(&wsa_buf)), 1, null, flags, @ptrCast(*ws2_32.WSAOVERLAPPED, overlapped), null); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAECONNABORTED => error.ConnectionAborted, .WSAECONNRESET => error.ConnectionResetByPeer, .WSAEFAULT => error.BadBuffer, .WSAEINPROGRESS, .WSAEWOULDBLOCK, .WSA_IO_PENDING => error.WouldBlock, .WSAEINTR => error.Cancelled, .WSAEINVAL => error.SocketNotBound, .WSAEMSGSIZE => error.MessageTooLarge, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAENETRESET => error.NetworkReset, .WSAENOBUFS => error.BufferDeadlock, .WSAENOTCONN => error.SocketNotConnected, .WSAENOTSOCK => error.FileDescriptorNotASocket, .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAESHUTDOWN => error.AlreadyShutdown, .WSAETIMEDOUT => error.Timeout, .WSA_OPERATION_ABORTED => error.OperationAborted, else => |err| windows.unexpectedWSAError(err), }; } } pub fn WSARecv(sock: ws2_32.SOCKET, buf: []u8, flags: windows.DWORD, overlapped: *windows.OVERLAPPED) !void { var wsa_flags: windows.DWORD = flags; var wsa_buf = ws2_32.WSABUF{ .len = @truncate(u32, buf.len), .buf = buf.ptr, }; const rc = ws2_32.WSARecv(sock, @intToPtr([*]const ws2_32.WSABUF, @ptrToInt(&wsa_buf)), 1, null, &wsa_flags, @ptrCast(*ws2_32.WSAOVERLAPPED, overlapped), null); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAECONNABORTED => error.ConnectionAborted, .WSAECONNRESET => error.ConnectionResetByPeer, .WSAEDISCON => error.ConnectionClosedByPeer, .WSAEFAULT => error.BadBuffer, .WSAEINPROGRESS, .WSAEWOULDBLOCK, .WSA_IO_PENDING => error.WouldBlock, .WSAEINTR => error.Cancelled, .WSAEINVAL => error.SocketNotBound, .WSAEMSGSIZE => error.MessageTooLarge, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAENETRESET => error.NetworkReset, .WSAENOTCONN => error.SocketNotConnected, .WSAENOTSOCK => error.FileDescriptorNotASocket, .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAESHUTDOWN => error.AlreadyShutdown, .WSAETIMEDOUT => error.Timeout, .WSA_OPERATION_ABORTED => error.OperationAborted, else => |err| windows.unexpectedWSAError(err), }; } } pub fn WSARecvFrom(sock: ws2_32.SOCKET, buf: []u8, flags: windows.DWORD, addr: ?*ws2_32.sockaddr, addr_len: ?*ws2_32.socklen_t, overlapped: *windows.OVERLAPPED) !void { var wsa_flags: windows.DWORD = flags; var wsa_buf = ws2_32.WSABUF{ .len = @truncate(u32, buf.len), .buf = buf.ptr, }; const rc = ws2_32.WSARecvFrom(sock, @intToPtr([*]const ws2_32.WSABUF, @ptrToInt(&wsa_buf)), 1, null, &wsa_flags, addr, addr_len, @ptrCast(*ws2_32.WSAOVERLAPPED, overlapped), null); if (rc == ws2_32.SOCKET_ERROR) { return switch (ws2_32.WSAGetLastError()) { .WSAECONNABORTED => error.ConnectionAborted, .WSAECONNRESET => error.ConnectionResetByPeer, .WSAEDISCON => error.ConnectionClosedByPeer, .WSAEFAULT => error.BadBuffer, .WSAEINPROGRESS, .WSAEWOULDBLOCK, .WSA_IO_PENDING => error.WouldBlock, .WSAEINTR => error.Cancelled, .WSAEINVAL => error.SocketNotBound, .WSAEMSGSIZE => error.MessageTooLarge, .WSAENETDOWN => error.NetworkSubsystemFailed, .WSAENETRESET => error.NetworkReset, .WSAENOTCONN => error.SocketNotConnected, .WSAENOTSOCK => error.FileDescriptorNotASocket, .WSAEOPNOTSUPP => error.OperationNotSupported, .WSAESHUTDOWN => error.AlreadyShutdown, .WSAETIMEDOUT => error.Timeout, .WSA_OPERATION_ABORTED => error.OperationAborted, else => |err| windows.unexpectedWSAError(err), }; } } pub fn ReadFile_(handle: windows.HANDLE, buf: []u8, overlapped: *windows.OVERLAPPED) !void { const len = math.cast(windows.DWORD, buf.len) catch math.maxInt(windows.DWORD); const success = windows.kernel32.ReadFile(handle, buf.ptr, len, null, overlapped); if (success == windows.FALSE) { return switch (windows.kernel32.GetLastError()) { .IO_PENDING => error.WouldBlock, .OPERATION_ABORTED => error.OperationAborted, .BROKEN_PIPE => error.BrokenPipe, .HANDLE_EOF, .NETNAME_DELETED => error.EndOfFile, else => |err| windows.unexpectedError(err), }; } } pub fn WriteFile_(handle: windows.HANDLE, buf: []const u8, overlapped: *windows.OVERLAPPED) !void { const len = math.cast(windows.DWORD, buf.len) catch math.maxInt(windows.DWORD); const success = windows.kernel32.WriteFile(handle, buf.ptr, len, null, overlapped); if (success == windows.FALSE) { return switch (windows.kernel32.GetLastError()) { .IO_PENDING => error.WouldBlock, .OPERATION_ABORTED => error.OperationAborted, .BROKEN_PIPE => error.BrokenPipe, .HANDLE_EOF, .NETNAME_DELETED => error.EndOfFile, else => |err| windows.unexpectedError(err), }; } } pub fn CancelIoEx(handle: windows.HANDLE, overlapped: *windows.OVERLAPPED) !void { const success = windows.kernel32.CancelIoEx(handle, overlapped); if (success == windows.FALSE) { return switch (windows.kernel32.GetLastError()) { .NOT_FOUND => error.RequestNotFound, else => |err| windows.unexpectedError(err), }; } } pub fn GetOverlappedResult_(h: windows.HANDLE, overlapped: *windows.OVERLAPPED, wait: bool) !windows.DWORD { var bytes: windows.DWORD = undefined; if (windows.kernel32.GetOverlappedResult(h, overlapped, &bytes, @boolToInt(wait)) == 0) { return switch (windows.kernel32.GetLastError()) { .IO_INCOMPLETE => if (!wait) error.WouldBlock else unreachable, .OPERATION_ABORTED => error.OperationAborted, else => |err| windows.unexpectedError(err), }; } return bytes; }
os/windows.zig
const std = @import("std"); const wasm3 = @import("wasm3"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var a = &gpa.allocator; var args = try std.process.argsAlloc(a); defer std.process.argsFree(a, args); if (args.len < 2) { std.log.err("Please provide a wasm file on the command line!\n", .{}); std.os.exit(1); } std.log.info("Loading wasm file {s}!\n", .{args[1]}); const kib = 1024; const mib = 1024 * kib; const gib = 1024 * mib; var env = wasm3.Environment.init(); defer env.deinit(); var rt = env.createRuntime(16 * kib, null); defer rt.deinit(); errdefer rt.printError(); var mod_bytes = try std.fs.cwd().readFileAlloc(a, args[1], 512 * kib); defer a.free(mod_bytes); var mod = try env.parseModule(mod_bytes); try rt.loadModule(mod); try mod.linkWasi(); try mod.linkLibrary("libtest", struct { pub fn add(_: *std.mem.Allocator, lh: i32, rh: i32, mul: wasm3.NativePtr(i32)) callconv(.Inline) i32 { mul.write(lh * rh); return lh + rh; } pub fn getArgv0(allocator: *std.mem.Allocator, str: wasm3.NativePtr(u8), max_len: u32) callconv(.Inline) u32 { var in_buf = str.slice(max_len); var arg_iter = std.process.args(); defer arg_iter.deinit(); var first_arg = (arg_iter.next(allocator) orelse return 0) catch return 0; defer allocator.free(first_arg); if (first_arg.len > in_buf.len) return 0; std.mem.copy(u8, in_buf, first_arg); return @truncate(u32, first_arg.len); } }, a); var start_fn = try rt.findFunction("_start"); start_fn.call(void, .{}) catch |e| switch (e) { error.TrapExit => {}, else => return e, }; var add_five_fn = try rt.findFunction("addFive"); const num: i32 = 7; std.debug.warn("Adding 5 to {d}: got {d}!\n", .{ num, try add_five_fn.call(i32, .{num}) }); var alloc_fn = try rt.findFunction("allocBytes"); var print_fn = try rt.findFunction("printStringZ"); const my_string = "Hello, world!"; var buffer_np = try alloc_fn.call(wasm3.NativePtr(u8), .{@as(u32, my_string.len + 1)}); var buffer = buffer_np.slice(my_string.len + 1); std.debug.warn("Allocated buffer!\n{any}\n", .{buffer}); std.mem.copy(u8, buffer, my_string); buffer[my_string.len] = 0; try print_fn.call(void, .{buffer_np}); var optionally_null_np: ?wasm3.NativePtr(u8) = null; try print_fn.call(void, .{optionally_null_np}); }
example/test.zig
const std = @import("std"); const vk = @import("vulkan"); const c = @import("c.zig"); const Allocator = std.mem.Allocator; const required_device_extensions = [_][*:0]const u8{vk.extension_info.khr_swapchain.name}; const BaseDispatch = vk.BaseWrapper(.{ .createInstance = true, }); const InstanceDispatch = vk.InstanceWrapper(.{ .destroyInstance = true, .createDevice = true, .destroySurfaceKHR = true, .enumeratePhysicalDevices = true, .getPhysicalDeviceProperties = true, .enumerateDeviceExtensionProperties = true, .getPhysicalDeviceSurfaceFormatsKHR = true, .getPhysicalDeviceSurfacePresentModesKHR = true, .getPhysicalDeviceSurfaceCapabilitiesKHR = true, .getPhysicalDeviceQueueFamilyProperties = true, .getPhysicalDeviceSurfaceSupportKHR = true, .getPhysicalDeviceMemoryProperties = true, .getDeviceProcAddr = true, }); const DeviceDispatch = vk.DeviceWrapper(.{ .destroyDevice = true, .getDeviceQueue = true, .createSemaphore = true, .createFence = true, .createImageView = true, .destroyImageView = true, .destroySemaphore = true, .destroyFence = true, .getSwapchainImagesKHR = true, .createSwapchainKHR = true, .destroySwapchainKHR = true, .acquireNextImageKHR = true, .deviceWaitIdle = true, .waitForFences = true, .resetFences = true, .queueSubmit = true, .queuePresentKHR = true, .createCommandPool = true, .destroyCommandPool = true, .allocateCommandBuffers = true, .freeCommandBuffers = true, .queueWaitIdle = true, .createShaderModule = true, .destroyShaderModule = true, .createPipelineLayout = true, .destroyPipelineLayout = true, .createRenderPass = true, .destroyRenderPass = true, .createGraphicsPipelines = true, .destroyPipeline = true, .createFramebuffer = true, .destroyFramebuffer = true, .beginCommandBuffer = true, .endCommandBuffer = true, .allocateMemory = true, .freeMemory = true, .createBuffer = true, .destroyBuffer = true, .getBufferMemoryRequirements = true, .mapMemory = true, .unmapMemory = true, .bindBufferMemory = true, .cmdBeginRenderPass = true, .cmdEndRenderPass = true, .cmdBindPipeline = true, .cmdDraw = true, .cmdSetViewport = true, .cmdSetScissor = true, .cmdBindVertexBuffers = true, .cmdCopyBuffer = true, }); pub const GraphicsContext = struct { vkb: BaseDispatch, vki: InstanceDispatch, vkd: DeviceDispatch, instance: vk.Instance, surface: vk.SurfaceKHR, pdev: vk.PhysicalDevice, props: vk.PhysicalDeviceProperties, mem_props: vk.PhysicalDeviceMemoryProperties, dev: vk.Device, graphics_queue: Queue, present_queue: Queue, pub fn init(allocator: Allocator, app_name: [*:0]const u8, window: *c.GLFWwindow) !GraphicsContext { var self: GraphicsContext = undefined; self.vkb = try BaseDispatch.load(c.glfwGetInstanceProcAddress); var glfw_exts_count: u32 = 0; const glfw_exts = c.glfwGetRequiredInstanceExtensions(&glfw_exts_count); const app_info = vk.ApplicationInfo{ .p_application_name = app_name, .application_version = vk.makeApiVersion(0, 0, 0, 0), .p_engine_name = app_name, .engine_version = vk.makeApiVersion(0, 0, 0, 0), .api_version = vk.API_VERSION_1_2, }; self.instance = try self.vkb.createInstance(&.{ .flags = .{}, .p_application_info = &app_info, .enabled_layer_count = 0, .pp_enabled_layer_names = undefined, .enabled_extension_count = glfw_exts_count, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, glfw_exts), }, null); self.vki = try InstanceDispatch.load(self.instance, c.glfwGetInstanceProcAddress); errdefer self.vki.destroyInstance(self.instance, null); self.surface = try createSurface(self.instance, window); errdefer self.vki.destroySurfaceKHR(self.instance, self.surface, null); const candidate = try pickPhysicalDevice(self.vki, self.instance, allocator, self.surface); self.pdev = candidate.pdev; self.props = candidate.props; self.dev = try initializeCandidate(self.vki, candidate); self.vkd = try DeviceDispatch.load(self.dev, self.vki.dispatch.vkGetDeviceProcAddr); errdefer self.vkd.destroyDevice(self.dev, null); self.graphics_queue = Queue.init(self.vkd, self.dev, candidate.queues.graphics_family); self.present_queue = Queue.init(self.vkd, self.dev, candidate.queues.present_family); self.mem_props = self.vki.getPhysicalDeviceMemoryProperties(self.pdev); return self; } pub fn deinit(self: GraphicsContext) void { self.vkd.destroyDevice(self.dev, null); self.vki.destroySurfaceKHR(self.instance, self.surface, null); self.vki.destroyInstance(self.instance, null); } pub fn deviceName(self: GraphicsContext) []const u8 { const len = std.mem.indexOfScalar(u8, &self.props.device_name, 0).?; return self.props.device_name[0..len]; } pub fn findMemoryTypeIndex(self: GraphicsContext, memory_type_bits: u32, flags: vk.MemoryPropertyFlags) !u32 { for (self.mem_props.memory_types[0..self.mem_props.memory_type_count]) |mem_type, i| { if (memory_type_bits & (@as(u32, 1) << @truncate(u5, i)) != 0 and mem_type.property_flags.contains(flags)) { return @truncate(u32, i); } } return error.NoSuitableMemoryType; } pub fn allocate(self: GraphicsContext, requirements: vk.MemoryRequirements, flags: vk.MemoryPropertyFlags) !vk.DeviceMemory { return try self.vkd.allocateMemory(self.dev, &.{ .allocation_size = requirements.size, .memory_type_index = try self.findMemoryTypeIndex(requirements.memory_type_bits, flags), }, null); } }; pub const Queue = struct { handle: vk.Queue, family: u32, fn init(vkd: DeviceDispatch, dev: vk.Device, family: u32) Queue { return .{ .handle = vkd.getDeviceQueue(dev, family, 0), .family = family, }; } }; fn createSurface(instance: vk.Instance, window: *c.GLFWwindow) !vk.SurfaceKHR { var surface: vk.SurfaceKHR = undefined; if (c.glfwCreateWindowSurface(instance, window, null, &surface) != .success) { return error.SurfaceInitFailed; } return surface; } fn initializeCandidate(vki: InstanceDispatch, candidate: DeviceCandidate) !vk.Device { const priority = [_]f32{1}; const qci = [_]vk.DeviceQueueCreateInfo{ .{ .flags = .{}, .queue_family_index = candidate.queues.graphics_family, .queue_count = 1, .p_queue_priorities = &priority, }, .{ .flags = .{}, .queue_family_index = candidate.queues.present_family, .queue_count = 1, .p_queue_priorities = &priority, }, }; const queue_count: u32 = if (candidate.queues.graphics_family == candidate.queues.present_family) 1 else 2; return try vki.createDevice(candidate.pdev, &.{ .flags = .{}, .queue_create_info_count = queue_count, .p_queue_create_infos = &qci, .enabled_layer_count = 0, .pp_enabled_layer_names = undefined, .enabled_extension_count = required_device_extensions.len, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &required_device_extensions), .p_enabled_features = null, }, null); } const DeviceCandidate = struct { pdev: vk.PhysicalDevice, props: vk.PhysicalDeviceProperties, queues: QueueAllocation, }; const QueueAllocation = struct { graphics_family: u32, present_family: u32, }; fn pickPhysicalDevice( vki: InstanceDispatch, instance: vk.Instance, allocator: Allocator, surface: vk.SurfaceKHR, ) !DeviceCandidate { var device_count: u32 = undefined; _ = try vki.enumeratePhysicalDevices(instance, &device_count, null); const pdevs = try allocator.alloc(vk.PhysicalDevice, device_count); defer allocator.free(pdevs); _ = try vki.enumeratePhysicalDevices(instance, &device_count, pdevs.ptr); for (pdevs) |pdev| { if (try checkSuitable(vki, pdev, allocator, surface)) |candidate| { return candidate; } } return error.NoSuitableDevice; } fn checkSuitable( vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: Allocator, surface: vk.SurfaceKHR, ) !?DeviceCandidate { const props = vki.getPhysicalDeviceProperties(pdev); if (!try checkExtensionSupport(vki, pdev, allocator)) { return null; } if (!try checkSurfaceSupport(vki, pdev, surface)) { return null; } if (try allocateQueues(vki, pdev, allocator, surface)) |allocation| { return DeviceCandidate{ .pdev = pdev, .props = props, .queues = allocation, }; } return null; } fn allocateQueues(vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: Allocator, surface: vk.SurfaceKHR) !?QueueAllocation { var family_count: u32 = undefined; vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, null); const families = try allocator.alloc(vk.QueueFamilyProperties, family_count); defer allocator.free(families); vki.getPhysicalDeviceQueueFamilyProperties(pdev, &family_count, families.ptr); var graphics_family: ?u32 = null; var present_family: ?u32 = null; for (families) |properties, i| { const family = @intCast(u32, i); if (graphics_family == null and properties.queue_flags.graphics_bit) { graphics_family = family; } if (present_family == null and (try vki.getPhysicalDeviceSurfaceSupportKHR(pdev, family, surface)) == vk.TRUE) { present_family = family; } } if (graphics_family != null and present_family != null) { return QueueAllocation{ .graphics_family = graphics_family.?, .present_family = present_family.?, }; } return null; } fn checkSurfaceSupport(vki: InstanceDispatch, pdev: vk.PhysicalDevice, surface: vk.SurfaceKHR) !bool { var format_count: u32 = undefined; _ = try vki.getPhysicalDeviceSurfaceFormatsKHR(pdev, surface, &format_count, null); var present_mode_count: u32 = undefined; _ = try vki.getPhysicalDeviceSurfacePresentModesKHR(pdev, surface, &present_mode_count, null); return format_count > 0 and present_mode_count > 0; } fn checkExtensionSupport( vki: InstanceDispatch, pdev: vk.PhysicalDevice, allocator: Allocator, ) !bool { var count: u32 = undefined; _ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, null); const propsv = try allocator.alloc(vk.ExtensionProperties, count); defer allocator.free(propsv); _ = try vki.enumerateDeviceExtensionProperties(pdev, null, &count, propsv.ptr); for (required_device_extensions) |ext| { for (propsv) |props| { const len = std.mem.indexOfScalar(u8, &props.extension_name, 0).?; const prop_ext_name = props.extension_name[0..len]; if (std.mem.eql(u8, std.mem.span(ext), prop_ext_name)) { break; } } else { return false; } } return true; }
examples/graphics_context.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/day10.txt"); 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; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; var numbers = try loadNumbers(allocator, input); defer numbers.deinit(); try numbers.append(0); // need this for part2 const u64asc = comptime std.sort.asc(u64); std.sort.sort(u64, numbers.items, {}, u64asc); try numbers.append(numbers.items[numbers.items.len - 1] + 3); var jolts = numbers.items; var count1: usize = 0; var count2: usize = 0; var count3: usize = 0; var prev: u64 = 0; for (jolts) |jolt, i| { if (i == 0) continue; switch (jolt - prev) { 1 => count1 += 1, 2 => count2 += 1, 3 => count3 += 1, else => unreachable, } prev = jolt; } print("part1: {}\n", .{count1 * count3}); var part2: u64 = 0; var counts = try allocator.alloc(u64, jolts.len); defer allocator.free(counts); std.mem.set(u64, counts, 0); counts[0] = 1; var i: usize = 1; while (i < jolts.len) : (i += 1) { if (jolts[i] - jolts[i - 1] <= 3) { counts[i] += counts[i - 1]; } if (i > 1 and jolts[i] - jolts[i - 2] <= 3) { counts[i] += counts[i - 2]; } if (i > 2 and jolts[i] - jolts[i - 3] <= 3) { counts[i] += counts[i - 3]; } } part2 = counts[jolts.len - 1]; print("part2: {}\n", .{part2}); } const example1 = \\16 \\10 \\15 \\5 \\1 \\11 \\7 \\19 \\6 \\12 \\4 ; const example2 = \\28 \\33 \\18 \\42 \\31 \\14 \\46 \\20 \\48 \\47 \\24 \\23 \\49 \\45 \\19 \\38 \\39 \\11 \\1 \\32 \\25 \\35 \\8 \\17 \\7 \\9 \\4 \\2 \\34 \\10 \\3 ;
src/day10.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/puzzle/day24.txt"); const RegArg = union(enum) { reg: u8, val: i64, }; const Alu = struct { reg: [4]i64 = [_]i64{ 0, 0, 0, 0 }, fn printAlu(self: Alu) void { print("{: >4} {: >4} {: >12} {: >12} ", .{ self.reg[0], self.reg[2], self.reg[1], self.reg[3], }); var x = self.reg[3]; while (x > 0) : (x = @divTrunc(x, 26)) { var k: u8 = @intCast(u8, @mod(x, 26)) + 'A'; print("{c}", .{k}); } print("\n", .{}); } fn get(self: Alu, idx: u8) i64 { return self.reg[idx - 'w']; } fn set(self: *Alu, idx: u8, val: i64) i64 { self.reg[idx - 'w'] = val; return self.reg[idx - 'w']; } fn add(self: *Alu, idx_a: u8, b: RegArg) i64 { var val: i64 = undefined; switch (b) { .reg => |x| val = self.reg[x - 'w'], .val => |x| val = x, } self.reg[idx_a - 'w'] += val; return self.reg[idx_a - 'w']; } fn mul(self: *Alu, idx_a: u8, b: RegArg) i64 { var val: i64 = undefined; switch (b) { .reg => |x| val = self.reg[x - 'w'], .val => |x| val = x, } self.reg[idx_a - 'w'] *= val; return self.reg[idx_a - 'w']; } fn div(self: *Alu, idx_a: u8, b: RegArg) i64 { var val: i64 = undefined; switch (b) { .reg => |x| val = self.reg[x - 'w'], .val => |x| val = x, } self.reg[idx_a - 'w'] = @divTrunc(self.reg[idx_a - 'w'], val); return self.reg[idx_a - 'w']; } fn mod(self: *Alu, idx_a: u8, b: RegArg) i64 { var val: i64 = undefined; switch (b) { .reg => |x| val = self.reg[x - 'w'], .val => |x| val = x, } self.reg[idx_a - 'w'] = @mod(self.reg[idx_a - 'w'], val); return self.reg[idx_a - 'w']; } fn eql(self: *Alu, idx_a: u8, b: RegArg) i64 { var val: i64 = undefined; switch (b) { .reg => |x| val = self.reg[x - 'w'], .val => |x| val = x, } if (self.reg[idx_a - 'w'] == val) { self.reg[idx_a - 'w'] = 1; } else { self.reg[idx_a - 'w'] = 0; } return self.reg[idx_a - 'w']; } }; pub fn main() !void { var lines = tokenize(data, "\r\n"); var alu = Alu{}; // 0, 1, 2, 3,-3, 4,-4,-2, 5, 6,-6,-5,-1,-0 // // var inputs: [14]i64 = [_]i64{ 7, 9, 9, 9, 7, 3, 9, 1, 9, 6, 9, 6, 4, 9 }; var inputs: [14]i64 = [_]i64{ 1, 6, 9, 3, 1, 1, 7, 1, 4, 1, 4, 1, 1, 3 }; var input_idx: u32 = 0; while (lines.next()) |line| { var parts = split(line, " "); var op = parts.next().?; var arg1: u8 = parts.next().?[0]; if (std.mem.eql(u8, op, "inp")) { _ = alu.set(arg1, inputs[input_idx]); input_idx += 1; print("\n", .{}); } else { var arg2: RegArg = undefined; var thing = parts.next().?; if (thing[0] >= 'w' and thing[0] <= 'z') { arg2 = RegArg{ .reg = thing[0] }; } else { arg2 = RegArg{ .val = parseInt(i64, thing, 0) catch unreachable }; } if (std.mem.eql(u8, op, "add")) { _ = alu.add(arg1, arg2); } else if (std.mem.eql(u8, op, "mul")) { _ = alu.mul(arg1, arg2); } else if (std.mem.eql(u8, op, "div")) { _ = alu.div(arg1, arg2); } else if (std.mem.eql(u8, op, "mod")) { _ = alu.mod(arg1, arg2); } else if (std.mem.eql(u8, op, "eql")) { _ = alu.eql(arg1, arg2); } } print("{s: >10} ", .{line}); alu.printAlu(); } } // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc;
src/day24.zig
const std = @import("std"); const parse = @import("parse.zig"); const convertFast = @import("convert_fast.zig").convertFast; const convertEiselLemire = @import("convert_eisel_lemire.zig").convertEiselLemire; const convertSlow = @import("convert_slow.zig").convertSlow; const convertHex = @import("convert_hex.zig").convertHex; const optimize = true; pub const ParseFloatError = error{ InvalidCharacter, }; pub fn parseFloat(comptime T: type, s: []const u8) ParseFloatError!T { if (s.len == 0) { return error.InvalidCharacter; } var i: usize = 0; const negative = s[i] == '-'; if (s[i] == '-' or s[i] == '+') { i += 1; } if (s.len == i) { return error.InvalidCharacter; } const n = parse.parseNumber(T, s[i..], negative) orelse { return parse.parseInfOrNan(T, s[i..], negative) orelse error.InvalidCharacter; }; if (n.hex) { return convertHex(T, n); } if (optimize) { if (convertFast(T, n)) |f| { return f; } if (T == f16 or T == f32 or T == f64) { // If significant digits were truncated, then we can have rounding error // only if `mantissa + 1` produces a different result. We also avoid // redundantly using the Eisel-Lemire algorithm if it was unable to // correctly round on the first pass. if (convertEiselLemire(T, n.exponent, n.mantissa)) |bf| { if (!n.many_digits) { return bf.toFloat(T, n.negative); } if (convertEiselLemire(T, n.exponent, n.mantissa + 1)) |bf2| { if (bf.eql(bf2)) { return bf.toFloat(T, n.negative); } } } } } // Unable to correctly round the float using the Eisel-Lemire algorithm. // Fallback to a slower, but always correct algorithm. return convertSlow(T, s[i..]).toFloat(T, negative); }
lib/std/fmt/parse_float/parse_float.zig
const std = @import("std"); pub fn RaxNode(comptime V: type) type { return struct { key: ?V, layout: union(enum) { Compressed: struct { chars: []u8, next: *Self, }, Branching: []Branch, }, const Self = @This(); pub const Branch = struct { char: u8, child: *Self, }; pub fn initCompressedNode(allocator: *std.mem.Allocator, chars: []const u8, next: *Self) !*Self { const charsCopy = try allocator.alloc(u8, chars.len); errdefer allocator.free(charsCopy); std.mem.copy(u8, charsCopy, chars); var newNode = try allocator.create(Self); newNode.* = .{ .key = null, .layout = .{ .Compressed = .{ .chars = charsCopy, .next = next, }, }, }; return newNode; } pub fn initBranchNode(comptime N: comptime_int, allocator: *std.mem.Allocator, chars: [N]u8, children: [N]*Self) !*Self { var branches = try allocator.alloc(Self.Branch, N); errdefer allocator.free(branches); comptime var i: usize = 0; inline while (i < N) : (i += 1) { branches[i] = .{ .char = chars[i], .child = children[i], }; } var newNode = try allocator.create(Self); newNode.* = .{ .key = null, .layout = .{ .Branching = branches, }, }; return newNode; } pub fn initEmpty(allocator: *std.mem.Allocator) !*Self { var result = try allocator.create(Self); result.* = Self{ .key = null, .layout = .{ .Branching = &[0]Branch{} }, }; return result; } pub fn deinit(self: *Self, allocator: *std.mem.Allocator, deletedNodes: u64) u64 { var newDeletedNodes = 1 + deletedNodes; switch (self.layout) { .Compressed => |c| { allocator.free(c.chars); newDeletedNodes += c.next.deinit(allocator, deletedNodes); }, .Branching => |branches| { for (branches) |*b| newDeletedNodes += b.child.deinit(allocator, deletedNodes); allocator.free(branches); }, } allocator.destroy(self); return newDeletedNodes; } pub fn makeCompressed(self: *Self, allocator: *std.mem.Allocator, s: []const u8) !void { if (self.layout == .Compressed or self.layout.Branching.len != 0) { @panic("tried to call makeCompressed on an unsuitable node"); } const charsSlice = try allocator.alloc(u8, s.len); errdefer allocator.free(charsSlice); std.mem.copy(u8, charsSlice, s); const nextChild = try allocator.create(Self); errdefer allocator.destroy(nextChild); // Initialize the new child nextChild.* = Self{ .key = null, .layout = .{ .Branching = &[0]Branch{} }, }; // Set the current node to Compressed self.layout = .{ .Compressed = .{ .chars = charsSlice, .next = nextChild, }, }; } pub fn removeChild(self: *Self, allocator: *std.mem.Allocator, child: *Self) void { switch (self.layout) { .Compressed => |c| { // TODO: make this debug-only if (c.next != child) { @panic("tried to remove a child that was not present in the parent"); } allocator.free(c.chars); self.layout = .{ .Branching = &[0]Self.Branch{} }; }, .Branching => |branches| { var childIdx = branches.len; for (branches) |b, i| { if (b.child == child) { childIdx = i; break; } } if (childIdx != branches.len) { std.mem.copy(Self.Branch, branches[childIdx..], branches[(childIdx + 1)..]); self.layout.Branching = allocator.shrink(branches, branches.len - 1); } else { @panic("tried to remove a child that was not present in the parent"); } }, } } pub fn size(self: Self) usize { return switch (self.layout) { .Compressed => |c| c.chars.len, .Branching => |b| b.len, }; } }; }
src/simple/node.zig
const std = @import("std"); // Shameless based on the Zig tokenizer: // https://github.com/ziglang/zig/blob/ec63411905ca66dc4dd874b4cde257b0043442e6/lib/std/zig/tokenizer.zig pub const TokenType = enum { const Self = @This(); integer_literal, plus, minus, asterisk, slash, eof, invalid, pub fn lexeme(token_type: Self) ?[]const u8 { return switch (token_type) { .integer_literal, .eof, .invalid => null, .plus => "+", .minus => "-", .asterisk => "*", .slash => "/", }; } pub fn symbol(token_type: Self) []const u8 { return token_type.lexeme() orelse @tagName(token_type); } // Convenience method, first for matching operators pub fn isTokenType(token_type: Self, potential_lexeme: []const u8) bool { const maybe_type_lexeme = token_type.lexeme(); if (maybe_type_lexeme == null) { return false; } const type_lexeme = maybe_type_lexeme.?; return std.mem.eql(u8, type_lexeme, potential_lexeme); } }; pub const Location = struct { start: usize, end: usize, }; pub const Token = struct { const Self = @This(); token_type: TokenType, location: Location, text: ?[]const u8 = null, }; const token_delimitter = " "; pub const Tokenizer = struct { const Self = @This(); token_iter: std.mem.TokenIterator(u8), pub fn init(buffer: [:0]const u8) Self { return Self{ .token_iter = std.mem.tokenize(u8, buffer, token_delimitter), }; } pub fn next(self: *Self) Token { const token_start: usize = self.token_iter.index; const maybe_token_text: ?[]const u8 = self.token_iter.next(); if (maybe_token_text == null) { return Token{ .token_type = .eof, .location = Location{ .start = token_start, .end = undefined, }, }; } var token_text: []const u8 = maybe_token_text.?; for (std.enums.values(TokenType)) |token_type| { if (token_type.isTokenType(token_text)) { return Token{ .token_type = token_type, .location = Location{ .start = token_start, .end = self.token_iter.index }, .text = token_text }; } } return Token{ .token_type = .invalid, .location = Location{ .start = token_start, .end = self.token_iter.index }, .text = token_text }; } }; test "tokenizes operators" { const input_string = "+ * - /"; const expected_values = [_]TokenType{ .plus, .asterisk, .minus, .slash, .eof }; var tokenizer = Tokenizer.init(input_string); for (expected_values) |expected_token| { var token = tokenizer.next(); var index = tokenizer.token_iter.index; var token_text = token.text; if (token_text == null) { std.debug.print("Expected token '{s}', got token '{s}' at index {d}\n", .{ expected_token.symbol(), token.token_type.symbol(), index }); } else { std.debug.print("Expected token '{s}', got token '{s}' at index {d} from text '{s}'\n", .{ expected_token.symbol(), token.token_type.symbol(), index, token.text }); } try std.testing.expect(token.token_type == expected_token); } } test "tokenizes unknown tokens" { const input_string = "@"; const expected_values = [_]TokenType{ .invalid, .eof }; var tokenizer = Tokenizer.init(input_string); for (expected_values) |expected_token| { var token = tokenizer.next(); var index = tokenizer.token_iter.index; var token_text = token.text; if (token_text == null) { std.debug.print("Expected token '{s}', got token '{s}' at index {d}\n", .{ expected_token.symbol(), token.token_type.symbol(), index }); } else { std.debug.print("Expected token '{s}', got token '{s}' at index {d} from text '{s}'\n", .{ expected_token.symbol(), token.token_type.symbol(), index, token.text }); } try std.testing.expect(token.token_type == expected_token); } }
src/tokenizer.zig
const sf = @import("../sfml.zig"); const glsl = sf.graphics.glsl; const Shader = @This(); // Constructor/destructor /// Creates a shader object from shader files, you can omit some shader types by passing null pub fn createFromFile( vertex_shader_path: ?[:0]const u8, geometry_shader_path: ?[:0]const u8, fragment_shader_path: ?[:0]const u8 ) !Shader { const shader = sf.c.sfShader_createFromFile( if (vertex_shader_path) |vsp| @ptrCast([*c]const u8, vsp) else null, if (geometry_shader_path) |gsp| @ptrCast([*c]const u8, gsp) else null, if (fragment_shader_path) |fsp| @ptrCast([*c]const u8, fsp) else null ); if (shader) |s| { return Shader{ ._ptr = s }; } else return sf.Error.nullptrUnknownReason; } /// Create a shader object from glsl code as string, you can omit some shader types by passing null pub fn createFromMemory( vertex_shader: ?[:0]const u8, geometry_shader: ?[:0]const u8, fragment_shader: ?[:0]const u8 ) !Shader { const shader = sf.c.sfShader_createFromMemory( if (vertex_shader) |vs| @ptrCast([*c]const u8, vs) else null, if (geometry_shader) |gs| @ptrCast([*c]const u8, gs) else null, if (fragment_shader) |fs| @ptrCast([*c]const u8, fs) else null ); if (shader) |s| { return Shader{ ._ptr = s }; } else return sf.Error.nullptrUnknownReason; } /// Destroys this shader object pub fn destroy(self: *Shader) void { sf.c.sfShader_destroy(self._ptr); } // Availability /// Checks whether or not shaders can be used in the system pub fn isAvailable() bool { return sf.c.sfShader_isAvailable(); } /// Checks whether or not geometry shaders can be used pub fn isGeometryAvailable() bool { return sf.c.sfShader_isAvailable(); } const CurrentTextureT = struct{}; /// Special value to pass to setUniform to have an uniform of the texture used for drawing /// which cannot be known in advance pub const CurrentTexture: CurrentTextureT = .{}; // Uniform /// Sets an uniform for the shader /// Colors are vectors so if you want to pass a color use .toIVec4() or .toFVec4() /// Pass CurrentTexture if you want to have the drawing texture as an uniform, which cannot be known in advance pub fn setUniform(self: *Shader, name: [:0]const u8, value: anytype) void { const T = @TypeOf(value); switch (T) { f32 => sf.c.sfShader_setFloatUniform(self._ptr, name, value), c_int => sf.c.sfShader_setIntUniform(self._ptr, name, value), bool => sf.c.sfShader_setBoolUniform(self._ptr, name, value), glsl.FVec2 => sf.c.sfShader_setVec2Uniform(self._ptr, name, value._toCSFML()), glsl.FVec3 => sf.c.sfShader_setVec3Uniform(self._ptr, name, value._toCSFML()), glsl.FVec4 => sf.c.sfShader_setVec4Uniform(self._ptr, name, @bitCast(sf.c.sfGlslVec4, value)), glsl.IVec2 => sf.c.sfShader_setIvec2Uniform(self._ptr, name, value._toCSFML()), glsl.IVec3 => sf.c.sfShader_setIvec3Uniform(self._ptr, name, @bitCast(sf.c.sfGlslIvec3, value)), glsl.IVec4 => sf.c.sfShader_setIvec4Uniform(self._ptr, name, @bitCast(sf.c.sfGlslIvec4, value)), glsl.BVec2 => sf.c.sfShader_setBvec2Uniform(self._ptr, name, @bitCast(sf.c.sfGlslBvec2, value)), glsl.BVec3 => sf.c.sfShader_setBvec3Uniform(self._ptr, name, @bitCast(sf.c.sfGlslBvec3, value)), glsl.BVec4 => sf.c.sfShader_setBvec4Uniform(self._ptr, name, @bitCast(sf.c.sfGlslBvec4, value)), glsl.Mat3 => sf.c.sfShader_setMat3Uniform(self._ptr, name, @ptrCast(*const sf.c.sfGlslMat3, @alignCast(4, &value))), glsl.Mat4 => sf.c.sfShader_setMat4Uniform(self._ptr, name, @ptrCast(*const sf.c.sfGlslMat4, @alignCast(4, &value))), sf.graphics.Texture => sf.c.sfShader_setTextureUniform(self._ptr, name, value._get()), CurrentTextureT => sf.c.sfShader_setCurrentTextureUniform(self._ptr, name), []const f32 => sf.c.sfShader_setFloatUniformArray(self._ptr, name, value.ptr, value.len), []const glsl.FVec2 => sf.c.sfShader_setVec2UniformArray(self._ptr, name, @ptrCast(*sf.c.sfGlslVec2, value.ptr), value.len), []const glsl.FVec3 => sf.c.sfShader_setVec3UniformArray(self._ptr, name, @ptrCast(*sf.c.sfGlslVec3, value.ptr), value.len), []const glsl.FVec4 => sf.c.sfShader_setVec4UniformArray(self._ptr, name, @ptrCast(*sf.c.sfGlslVec4, value.ptr), value.len), []const glsl.Mat3 => sf.c.sfShader_setMat3UniformArray(self._ptr, name, @ptrCast(*sf.c.sfGlslMat3, value.ptr), value.len), []const glsl.Mat4 => sf.c.sfShader_setMat4UniformArray(self._ptr, name, @ptrCast(*sf.c.sfGlslVec4, value.ptr), value.len), else => @compileError("Uniform of type \"" ++ @typeName(T) ++ "\" cannot be set inside shader.") } } /// Pointer to the CSFML structure _ptr: *sf.c.sfShader
src/sfml/graphics/Shader.zig
const std = @import("std"); const builtin = @import("builtin"); const is_test = builtin.is_test; const comparesf2 = @import("comparesf2.zig"); const TestVector = struct { a: f32, b: f32, eqReference: c_int, geReference: c_int, gtReference: c_int, leReference: c_int, ltReference: c_int, neReference: c_int, unReference: c_int, }; fn test__cmpsf2(vector: TestVector) bool { if (comparesf2.__eqsf2(vector.a, vector.b) != vector.eqReference) { return false; } if (comparesf2.__gesf2(vector.a, vector.b) != vector.geReference) { return false; } if (comparesf2.__gtsf2(vector.a, vector.b) != vector.gtReference) { return false; } if (comparesf2.__lesf2(vector.a, vector.b) != vector.leReference) { return false; } if (comparesf2.__ltsf2(vector.a, vector.b) != vector.ltReference) { return false; } if (comparesf2.__nesf2(vector.a, vector.b) != vector.neReference) { return false; } if (comparesf2.__unordsf2(vector.a, vector.b) != vector.unReference) { return false; } return true; } const arguments = [_]f32{ std.math.nan(f32), -std.math.inf(f32), -0x1.fffffep127, -0x1.000002p0 - 0x1.000000p0, -0x1.fffffep-1, -0x1.000000p-126, -0x0.fffffep-126, -0x0.000002p-126, -0.0, 0.0, 0x0.000002p-126, 0x0.fffffep-126, 0x1.000000p-126, 0x1.fffffep-1, 0x1.000000p0, 0x1.000002p0, 0x1.fffffep127, std.math.inf(f32), }; fn generateVector(comptime a: f32, comptime b: f32) TestVector { const leResult = if (a < b) -1 else if (a == b) 0 else 1; const geResult = if (a > b) 1 else if (a == b) 0 else -1; const unResult = if (a != a or b != b) 1 else 0; return TestVector{ .a = a, .b = b, .eqReference = leResult, .geReference = geResult, .gtReference = geResult, .leReference = leResult, .ltReference = leResult, .neReference = leResult, .unReference = unResult, }; } const test_vectors = init: { @setEvalBranchQuota(10000); var vectors: [arguments.len * arguments.len]TestVector = undefined; for (arguments[0..]) |arg_i, i| { for (arguments[0..]) |arg_j, j| { vectors[(i * arguments.len) + j] = generateVector(arg_i, arg_j); } } break :init vectors; }; test "compare f32" { for (test_vectors) |vector, i| { std.testing.expect(test__cmpsf2(vector)); } }
lib/std/special/compiler_rt/comparesf2_test.zig
const std = @import("std"); const uefi = std.os.uefi; const uefi_platform = @import("../uefi.zig"); const vfs = @import("../../vfs.zig"); const Node = vfs.Node; var console_scratch: [8192]u8 = undefined; var console_fifo = std.fifo.LinearFifo(u8, .Slice).init(console_scratch[0..]); var keyboard_scratch: [8192]u8 = undefined; var keyboard_fifo = std.fifo.LinearFifo(u8, .Slice).init(keyboard_scratch[0..]); pub var text_in_ex: ?*uefi.protocols.SimpleTextInputExProtocol = null; pub fn init() void { if (uefi.system_table.boot_services.?.locateProtocol(&uefi.protocols.SimpleTextInputExProtocol.guid, null, @ptrCast(*?*c_void, &text_in_ex)) == uefi.Status.Success) { uefi_platform.earlyprintk("Extended text input supported.\n"); } } pub inline fn keyboardHandler() void { if (text_in_ex != null) extendedKeyboardHandler() else basicKeyboardHandler(); } fn basicKeyboardHandler() void { if (uefi.system_table.boot_services.?.checkEvent(uefi.system_table.con_in.?.wait_for_key) != uefi.Status.Success) return; var key: uefi.protocols.InputKey = undefined; if (uefi.system_table.con_in.?.readKeyStroke(&key) != uefi.Status.Success) return; var outbuf: [1]u8 = undefined; var inbuf: [1]u16 = undefined; inbuf[0] = key.unicode_char; _ = std.unicode.utf16leToUtf8(outbuf[0..], inbuf[0..]) catch unreachable; _ = console_fifo.write(outbuf[0..]) catch null; } fn extendedKeyboardHandler() void { if (uefi.system_table.boot_services.?.checkEvent(text_in_ex.?.wait_for_key_ex) != uefi.Status.Success) return; var keydata: uefi.protocols.KeyData = undefined; if (text_in_ex.?.readKeyStrokeEx(&keydata) != uefi.Status.Success) return; var outbuf: [1]u8 = undefined; var inbuf: [1]u16 = undefined; inbuf[0] = keydata.key.unicode_char; _ = std.unicode.utf16leToUtf8(outbuf[0..], inbuf[0..]) catch unreachable; _ = console_fifo.write(outbuf[0..]) catch null; _ = keyboard_fifo.write(std.mem.asBytes(&keydata)) catch null; } pub const ConsoleNode = struct { const ops: Node.Ops = .{ .read = ConsoleNode.read, .write = ConsoleNode.write, }; pub fn init() Node { return Node.init(ConsoleNode.ops, null, Node.Stat{ .type = .character_device, .device_info = .{ .class = .console, .name = "uefi_console" } }, null); } pub fn write(self: *Node, offset: u64, buffer: []const u8) !usize { uefi_platform.earlyprintk(buffer); return buffer.len; } pub fn read(self: *Node, offset: u64, buffer: []u8) !usize { var n = console_fifo.read(buffer); for (buffer[0..n]) |c, i| { if (c == '\r') buffer[i] = '\n'; } uefi_platform.earlyprintk(buffer[0..n]); return if (n == 0) vfs.Error.Again else n; } }; pub const KeyboardNode = struct { const ops: Node.Ops = .{ .read = KeyboardNode.read, }; pub fn init() Node { return Node.init(KeyboardNode.ops, null, Node.Stat{ .type = character_device, .device_info = .{ .class = .keyboard, .name = "uefi_keyboard" } }, null); } pub fn read(self: *Node, offset: u64, buffer: []u8) !usize { var n = keyboard_fifo.read(buffer); return if (n == 0) vfs.Error.Again else n; } };
kernel/platform/uefi/console.zig
const std = @import("std"); const sling = @import("sling.zig"); /// Configure handle skinning and functionality through here! pub const config = struct { /// If you want to change which key is used to drag handles, this is /// your way in. pub var lockKey: sling.input.Key = .lmb; pub var normalColor: sling.math.Vec4 = sling.math.vec4(0.7, 0.9, 0.4, 0.8); pub var hoveredColor: sling.math.Vec4 = sling.math.vec4(0.8, 0.6, 0.3, 0.95); pub var heldColor: sling.math.Vec4 = sling.math.vec4(0.9, 0.9, 0.7, 1.0); pub var mutedColor: sling.math.Vec4 = sling.math.vec4(0.3, 0.5, 0.1, 0.1); pub var blipSize: f32 = 5; pub var handleLength: f32 = 15; pub var padding: f32 = 4; }; var locked: ?usize = null; var mode: ?usize = null; /// Pass in a reference to a vector to get in-world handles to manipulate a point in space. /// You can pass in offset to have the handles placed away from the point that you're editing, /// and a bool to flip the handles in the other direction pub fn positionHandle(vector: *sling.math.Vec2, flipHandles: bool, offset: ?sling.math.Vec2) void { const centerClick: usize = 0; const xClick: usize = 1; const yClick: usize = 2; const callSite = @ptrToInt(vector); const mouse = sling.input.worldMouse; const delta = sling.input.worldMouseDelta; const length = config.handleLength / sling.render.camera.zoom; const size = config.blipSize / sling.render.camera.zoom; const padding = config.padding / sling.render.camera.zoom; const target: sling.math.Vec2 = if (offset != null) vector.add(offset.?) else vector.*; var col = config.normalColor; var xAxisHandle = sling.math.rect( target.x - length - size - padding, target.y - size * 0.5, length, size, ); var yAxisHandle = sling.math.rect( target.x - size * 0.5, target.y - length - size - padding, size, length, ); if (flipHandles) { xAxisHandle.position.x += (length + size + padding) + (padding * 2); yAxisHandle.position.y += (length + size + padding) + (padding * 2); } if (locked) |lockId| { if (lockId == callSite) { col = config.heldColor; if (mode) |modeId| { switch (modeId) { centerClick => { vector.*.x += delta.x; vector.*.y += delta.y; }, xClick => { vector.*.x += delta.x; }, yClick => { vector.*.y += delta.y; }, else => {}, } } if (config.lockKey.released()) { locked = null; mode = null; } } else { col = config.mutedColor; } } else { const clicked = config.lockKey.pressed(); if (mouse.distanceTo(target) < size) { col = config.hoveredColor; if (clicked) { mode = centerClick; locked = callSite; } } if (xAxisHandle.containsPoint(mouse)) { col = config.hoveredColor; if (clicked) { mode = xClick; locked = callSite; } } if (yAxisHandle.containsPoint(mouse)) { col = config.hoveredColor; if (clicked) { mode = yClick; locked = callSite; } } } sling.render.circle(.world, sling.render.debugDepth, target, size, col); sling.render.rectangle(.world, sling.render.debugDepth, xAxisHandle, col, -1); sling.render.rectangle(.world, sling.render.debugDepth, yAxisHandle, col, -1); } /// Pass in a reference to a rectangle to get in-world handles to manipulate a rectangle. pub fn rectangleHandle(rect: *sling.math.Rect) void { positionHandle(&rect.*.position, false, null); positionHandle(&rect.*.size, true, rect.*.position); }
src/handle.zig
const std = @import("std"); const gl = @import("opengl.zig"); const math = std.math; const default_allocator = std.heap.page_allocator; usingnamespace @import("util.zig"); pub const window_name = "genexp002"; pub const window_width = 1920; pub const window_height = 1080; const num_objects = 256; const max_vel = 5.0; pub const GenerativeExperimentState = struct { prng: std.rand.DefaultPrng, positions: []Vec2, colors: []Color, velocities: []Vec2, accelerations: []Vec2, pub fn init() GenerativeExperimentState { return GenerativeExperimentState{ .prng = std.rand.DefaultPrng.init(0), .positions = &[_]Vec2{}, .colors = &[_]Color{}, .velocities = &[_]Vec2{}, .accelerations = &[_]Vec2{}, }; } pub fn deinit(self: GenerativeExperimentState) void { default_allocator.free(self.positions); default_allocator.free(self.colors); default_allocator.free(self.velocities); default_allocator.free(self.accelerations); } }; pub fn setup(genexp: *GenerativeExperimentState) !void { const rand = &genexp.prng.random; gl.lineWidth(5.0); gl.enable(gl.BLEND); gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); genexp.positions = try default_allocator.alloc(Vec2, num_objects); genexp.colors = try default_allocator.alloc(Color, num_objects); genexp.velocities = try default_allocator.alloc(Vec2, num_objects); genexp.accelerations = try default_allocator.alloc(Vec2, num_objects); for (genexp.positions) |*pos| { pos.*.x = 2.0 * rand.float(f32) - 1.0; pos.*.y = 2.0 * rand.float(f32) - 1.0; pos.*.x *= window_width * 0.5; pos.*.y *= window_height * 0.5; } for (genexp.colors) |*color| { color.*.r = rand.int(u8); color.*.g = rand.int(u8); color.*.b = rand.int(u8); color.*.a = 128; } for (genexp.velocities) |*vel| { vel.*.x = 2.0 * rand.float(f32) - 1.0; vel.*.y = 2.0 * rand.float(f32) - 1.0; } } pub fn update(genexp: *GenerativeExperimentState, time: f64, dt: f32) void { const rand = &genexp.prng.random; for (genexp.accelerations) |*accel| { accel.*.x = 2.0 * rand.float(f32) - 1.0; accel.*.y = 2.0 * rand.float(f32) - 1.0; } for (genexp.positions) |pos, i| { if (pos.x < -0.5 * @intToFloat(f32, window_width) or pos.x > 0.5 * @intToFloat(f32, window_width) or pos.y < -0.5 * @intToFloat(f32, window_height) or pos.y > 0.5 * @intToFloat(f32, window_height)) { const f = -1.2; const npos = pos.normalize(); genexp.accelerations[i].x += f * npos.x; genexp.accelerations[i].y += f * npos.y; } } gl.color4f(0.0, 0.0, 0.0, 0.1); gl.begin(gl.QUADS); gl.vertex2i(-window_width / 2, -window_height / 2); gl.vertex2i(window_width / 2, -window_height / 2); gl.vertex2i(window_width / 2, window_height / 2); gl.vertex2i(-window_width / 2, window_height / 2); gl.end(); gl.begin(gl.LINES); for (genexp.velocities) |*vel, i| { vel.*.x += genexp.accelerations[i].x; vel.*.y += genexp.accelerations[i].y; vel.*.x = if (vel.*.x < -max_vel) -max_vel else if (vel.*.x > max_vel) max_vel else vel.*.x; vel.*.y = if (vel.*.y < -max_vel) -max_vel else if (vel.*.y > max_vel) max_vel else vel.*.y; gl.color4ub(genexp.colors[i].r, genexp.colors[i].g, genexp.colors[i].b, 200); gl.vertex2f(genexp.positions[i].x, genexp.positions[i].y); genexp.positions[i].x += vel.*.x; genexp.positions[i].y += vel.*.y; gl.vertex2f(genexp.positions[i].x, genexp.positions[i].y); } gl.end(); }
src/genexp002.zig
usingnamespace @import("pspge.zig"); usingnamespace @import("pspgutypes.zig"); usingnamespace @import("psptypes.zig"); usingnamespace @import("pspdisplay.zig"); test "" { @import("std").meta.refAllDecls(@This()); } //Internals pub const GuCallback = ?fn (c_int) callconv(.C) void; const GuSettings = struct { sig: GuCallback, fin: GuCallback, signal_history: [16]u16, signal_offset: i32, kernel_event_flag: i32, ge_callback_id: i32, swapBuffersCallback: GuSwapBuffersCallback, swapBuffersBehaviour: i32, }; const GuDisplayList = struct { start: [*]u32, current: [*]u32, parent_context: i32, }; const GuContext = struct { list: GuDisplayList, scissor_enable: i32, scissor_start: [2]i32, scissor_end: [2]i32, near_plane: i32, far_plane: i32, depth_offset: i32, fragment_2x: i32, texture_function: i32, texture_proj_map_mode: i32, texture_map_mode: i32, sprite_mode: [4]i32, clear_color: u32, clear_stencil: u32, clear_depth: u32, texture_mode: i32, }; const GuDrawBuffer = struct { pixel_size: i32, frame_width: i32, frame_buffer: ?*c_void, disp_buffer: ?*c_void, depth_buffer: ?*c_void, depth_width: i32, width: i32, height: i32, }; const GuLightSettings = struct { enable: u8, // Light enable typec: u8, // Light type xpos: u8, // X position ypos: u8, // Y position zpos: u8, // Z position xdir: u8, // X direction ydir: u8, // Y direction zdir: u8, // Z direction ambient: u8, // Ambient color diffuse: u8, // Diffuse color specular: u8, // Specular color constant: u8, // Constant attenuation linear: u8, // Linear attenuation quadratic: u8, // Quadratic attenuation exponent: u8, // Light exponent cutoff: u8, // Light cutoff }; var gu_current_frame: u32 = 0; var gu_contexts: [3]GuContext = undefined; var ge_list_executed: [2]i32 = undefined; var ge_edram_address: ?*c_void = null; var gu_settings: GuSettings = undefined; var gu_list: ?*GuDisplayList = null; var gu_curr_context: i32 = 0; var gu_init: i32 = 0; var gu_display_on: i32 = 0; var gu_call_mode: i32 = 0; var gu_states: i32 = 0; var gu_draw_buffer: GuDrawBuffer = undefined; var gu_object_stack: [256]u32 = undefined; var gu_object_stack_depth: i32 = 0; var light_settings: [4]GuLightSettings = [_]GuLightSettings{ GuLightSettings{ .enable = 0x18, .typec = 0x5f, .xpos = 0x63, .ypos = 0x64, .zpos = 0x65, .xdir = 0x6f, .ydir = 0x70, .zdir = 0x71, .ambient = 0x8f, .diffuse = 0x90, .specular = 0x91, .constant = 0x7b, .linear = 0x7c, .quadratic = 0x7d, .exponent = 0x87, .cutoff = 0x8b, }, GuLightSettings{ .enable = 0x19, .typec = 0x60, .xpos = 0x66, .ypos = 0x67, .zpos = 0x68, .xdir = 0x72, .ydir = 0x73, .zdir = 0x74, .ambient = 0x92, .diffuse = 0x93, .specular = 0x94, .constant = 0x7e, .linear = 0x7f, .quadratic = 0x80, .exponent = 0x88, .cutoff = 0x8c, }, GuLightSettings{ .enable = 0x1a, .typec = 0x61, .xpos = 0x69, .ypos = 0x6a, .zpos = 0x6b, .xdir = 0x75, .ydir = 0x76, .zdir = 0x77, .ambient = 0x8f, .diffuse = 0x90, .specular = 0x91, .constant = 0x81, .linear = 0x82, .quadratic = 0x83, .exponent = 0x89, .cutoff = 0x8d, }, GuLightSettings{ .enable = 0x1b, .typec = 0x62, .xpos = 0x6c, .ypos = 0x6d, .zpos = 0x6e, .xdir = 0x78, .ydir = 0x79, .zdir = 0x7a, .ambient = 0x98, .diffuse = 0x99, .specular = 0x9a, .constant = 0x84, .linear = 0x85, .quadratic = 0x86, .exponent = 0x8a, .cutoff = 0x8e, }, }; usingnamespace @import("pspthreadman.zig"); pub export fn callbackSig(id: c_int, arg: ?*c_void) void { @setRuntimeSafety(false); var settings: ?*GuSettings = @intToPtr(?*GuSettings, @ptrToInt(arg)); settings.?.signal_history[@intCast(usize, (settings.?.signal_offset)) & 15] = @intCast(u16, id) & 0xffff; settings.?.signal_offset += 1; if (settings.?.sig != null) settings.?.sig.?(id & 0xffff); _ = sceKernelSetEventFlag(settings.?.kernel_event_flag, 1); } pub export fn callbackFin(id: c_int, arg: ?*c_void) void { @setRuntimeSafety(false); var settings: ?*GuSettings = @intToPtr(?*GuSettings, @ptrToInt(arg)); if (settings.?.fin != null) { settings.?.fin.?(id & 0xffff); } } pub fn resetValues() void { @setRuntimeSafety(false); var i: usize = 0; gu_init = 0; gu_states = 0; gu_current_frame = 0; gu_object_stack_depth = 0; gu_display_on = 0; gu_call_mode = 0; gu_draw_buffer.pixel_size = 1; gu_draw_buffer.frame_width = 0; gu_draw_buffer.frame_buffer = null; gu_draw_buffer.disp_buffer = null; gu_draw_buffer.depth_buffer = null; gu_draw_buffer.depth_width = 0; gu_draw_buffer.width = 480; gu_draw_buffer.height = 272; while (i < 3) : (i += 1) { gu_contexts[i].scissor_enable = 0; gu_contexts[i].scissor_start[0] = 0; gu_contexts[i].scissor_start[1] = 0; gu_contexts[i].scissor_end[0] = 0; gu_contexts[i].scissor_end[1] = 0; gu_contexts[i].near_plane = 0; gu_contexts[i].far_plane = 1; gu_contexts[i].depth_offset = 0; gu_contexts[i].fragment_2x = 0; gu_contexts[i].texture_function = 0; gu_contexts[i].texture_proj_map_mode = 0; gu_contexts[i].texture_map_mode = 0; gu_contexts[i].sprite_mode[0] = 0; gu_contexts[i].sprite_mode[1] = 0; gu_contexts[i].sprite_mode[2] = 0; gu_contexts[i].sprite_mode[3] = 0; gu_contexts[i].clear_color = 0; gu_contexts[i].clear_stencil = 0; gu_contexts[i].clear_depth = 0xffff; gu_contexts[i].texture_mode = 0; } gu_settings.sig = null; gu_settings.fin = null; } pub fn sendCommandi(cmd: c_int, argument: c_int) void { @setRuntimeSafety(false); gu_list.?.current[0] = (@intCast(u32, cmd) << 24) | (@intCast(u32, argument) & 0xffffff); gu_list.?.current += 1; } pub fn sendCommandiStall(cmd: c_int, argument: c_int) void { @setRuntimeSafety(false); sendCommandi(cmd, argument); if (gu_object_stack_depth == 0 and gu_curr_context == 0) { _ = sceGeListUpdateStallAddr(ge_list_executed[0], @ptrCast(*c_void, gu_list.?.current)); } } pub fn sendCommandf(cmd: c_int, argument: f32) void { @setRuntimeSafety(false); sendCommandi(cmd, @bitCast(c_int, argument) >> 8); } //GU IMPLEMENTATION pub fn sceGuAlphaFunc(func: AlphaFunc, value: c_int, mask: c_int) void { @setRuntimeSafety(false); var arg: c_int = @enumToInt(func) | ((value & 0xff) << 8) | ((mask & 0xff) << 16); sendCommandi(219, arg); } pub fn sceGuAmbient(col: u32) void { @setRuntimeSafety(false); sendCommandi(92, (col & 0xffffff)); sendCommandi(93, (col >> 24)); } pub fn sceGuAmbientColor(col: u32) void { @setRuntimeSafety(false); sendCommandi(85, @intCast(c_int, col) & 0xffffff); sendCommandi(88, @intCast(c_int, col) >> 24); } pub fn sceGuBlendFunc(bop: BlendOp, sc: BlendArg, dst: BlendArg, srcfix: c_int, destfix: c_int) void { var op: c_int = @enumToInt(bop); var src: c_int = @enumToInt(sc); var dest: c_int = @enumToInt(dst); @setRuntimeSafety(false); sendCommandi(223, src | (dest << 4) | (op << 8)); sendCommandi(224, srcfix & 0xffffff); sendCommandi(225, destfix & 0xffffff); } pub fn sceGuBreak(a0: c_int) void { @setRuntimeSafety(false); //Does nothing or is broken? } pub fn sceGuContinue() void { @setRuntimeSafety(false); //Does nothing or is broken? } pub fn sceGuCallList(list: ?*const c_void) void { @setRuntimeSafety(false); var list_addr: c_int = @intCast(c_int, @ptrToInt(list)); if (gu_call_mode == 1) { sendCommandi(14, (list_addr >> 16) | 0x110000); sendCommandi(12, list_addr & 0xffff); sendCommandiStall(0, 0); } else { sendCommandi(16, (list_addr >> 8) & 0xf0000); sendCommandiStall(10, list_addr & 0xffffff); } } pub fn sceGuCallMode(mode: c_int) void { @setRuntimeSafety(false); gu_call_mode = mode; } pub fn sceGuCheckList() c_int { return @intCast(c_int, (@ptrToInt(gu_list.?.current) - @ptrToInt(gu_list.?.start))); } pub fn sceGuClearColor(col: c_uint) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].clear_color = col; } pub fn sceGuClearDepth(depth: c_uint) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].clear_depth = depth; } pub fn sceGuClearStencil(stencil: c_uint) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].clear_stencil = stencil; } pub fn sceGuClutLoad(num_blocks: c_int, cbp: ?*const c_void) void { @setRuntimeSafety(false); var a = @intCast(c_int, @ptrToInt(cbp)); sendCommandi(176, (a) & 0xffffff); sendCommandi(177, ((a) >> 8) & 0xf0000); sendCommandi(196, num_blocks); } pub fn sceGuClutMode(cpsm: GuPixelMode, shift: c_int, mask: c_int, a3: c_int) void { @setRuntimeSafety(false); var argument: c_int = @enumToInt(cpsm) | (shift << 2) | (mask << 8) | (a3 << 16); sendCommandi(197, argument); } pub fn sceGuColor(col: c_int) void { @setRuntimeSafety(false); sceGuMaterial(7, col); } pub fn sceGuMaterial(mode: c_int, col: c_int) void { @setRuntimeSafety(false); if (mode & 0x01 != 0) { sendCommandi(85, col & 0xffffff); sendCommandi(88, col >> 24); } if (mode & 0x02 != 0) sendCommandi(86, col & 0xffffff); if (mode & 0x04 != 0) sendCommandi(87, col & 0xffffff); } pub fn sceGuColorFunc(func: ColorFunc, color: c_int, mask: c_int) void { @setRuntimeSafety(false); sendCommandi(216, @enumToInt(func) & 0x03); sendCommandi(217, color & 0xffffff); sendCommandi(218, mask); } pub fn sceGuColorMaterial(components: c_int) void { @setRuntimeSafety(false); sendCommandi(83, components); } pub fn sceGuCopyImage(psm: GuPixelMode, sx: c_int, sy: c_int, width: c_int, height: c_int, srcw: c_int, src: ?*c_void, dx: c_int, dy: c_int, destw: c_int, dest: ?*c_void) void { @setRuntimeSafety(false); var sr = @intCast(c_uint, @ptrToInt(src)); var ds = @intCast(c_uint, @ptrToInt(dest)); sendCommandi(178, @intCast(c_int, (sr) & 0xffffff)); sendCommandi(179, @intCast(c_int, (((sr) & 0xff000000) >> 8)) | srcw); sendCommandi(235, (sy << 10) | sx); sendCommandi(180, @intCast(c_int, (ds) & 0xffffff)); sendCommandi(181, @intCast(c_int, (((ds) & 0xff000000) >> 8)) | destw); sendCommandi(236, (dy << 10) | dx); sendCommandi(238, ((height - 1) << 10) | (width - 1)); if (@enumToInt(psm) ^ 0x03 != 0) { sendCommandi(234, 0); } else { sendCommandi(234, 1); } } pub fn sceGuDepthBuffer(zbp: ?*c_void, zbw: c_int) void { @setRuntimeSafety(false); gu_draw_buffer.depth_buffer = zbp; if (gu_draw_buffer.depth_width != 0 or (gu_draw_buffer.depth_width != zbw)) gu_draw_buffer.depth_width = zbw; sendCommandi(158, @intCast(c_int, (@ptrToInt(zbp))) & 0xffffff); sendCommandi(159, @intCast(c_int, ((@intCast(c_uint, (@ptrToInt(zbp))) & 0xff000000) >> 8)) | zbw); } pub fn sceGuDepthFunc(function: DepthFunc) void { @setRuntimeSafety(false); sendCommandi(222, @enumToInt(function)); } pub fn sceGuDepthMask(mask: c_int) void { @setRuntimeSafety(false); sendCommandi(231, mask); } pub fn sceGuDepthOffset(offset: c_uint) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].depth_offset = @intCast(i32, offset); sceGuDepthRange(gu_contexts[@intCast(usize, gu_curr_context)].near_plane, gu_contexts[@intCast(usize, gu_curr_context)].far_plane); } pub fn sceGuDepthRange(near: c_int, far: c_int) void { @setRuntimeSafety(false); var max = near + far; var val = ((max >> 31) + max); var z: f32 = @bitCast(f32, (val >> 1)); gu_contexts[@intCast(usize, gu_curr_context)].near_plane = near; gu_contexts[@intCast(usize, gu_curr_context)].far_plane = far; sendCommandf(68, z - (@bitCast(f32, near))); sendCommandf(71, z + (@bitCast(f32, gu_contexts[@intCast(usize, gu_curr_context)].depth_offset))); if (near > far) { sendCommandi(214, far); sendCommandi(215, near); } else { sendCommandi(214, near); sendCommandi(215, far); } } pub fn sceGuDisable(state: GuState) void { @setRuntimeSafety(false); switch (state) { .AlphaTest => { sendCommandi(34, 0); }, .DepthTest => { sendCommandi(35, 0); }, .ScissorTest => { gu_contexts[@intCast(usize, gu_curr_context)].scissor_enable = 0; sendCommandi(212, 0); sendCommandi(213, ((gu_draw_buffer.height - 1) << 10) | (gu_draw_buffer.width - 1)); }, .StencilTest => { sendCommandi(36, 0); }, .Blend => { sendCommandi(33, 0); }, .CullFace => { sendCommandi(29, 0); }, .Dither => { sendCommandi(32, 0); }, .Fog => { sendCommandi(31, 0); }, .ClipPlanes => { sendCommandi(28, 0); }, .Texture2D => { sendCommandi(30, 0); }, .Lighting => { sendCommandi(23, 0); }, .Light0 => { sendCommandi(24, 0); }, .Light1 => { sendCommandi(25, 0); }, .Light2 => { sendCommandi(26, 0); }, .Light3 => { sendCommandi(27, 0); }, .LineSmooth => { sendCommandi(37, 0); }, .PatchCullFace => { sendCommandi(38, 0); }, .ColorTest => { sendCommandi(39, 0); }, .ColorLogicOp => { sendCommandi(40, 0); }, .FaceNormalReverse => { sendCommandi(81, 0); }, .PatchFace => { sendCommandi(56, 0); }, .Fragment2X => { gu_contexts[@intCast(usize, gu_curr_context)].fragment_2x = 0; sendCommandi(201, gu_contexts[@intCast(usize, gu_curr_context)].texture_function); }, } var one: u32 = 1; if (@enumToInt(state) < 22) gu_states &= @intCast(i32, ~(one << @intCast(u5, @enumToInt(state)))); } fn drawRegion(x: c_int, y: c_int, width: c_int, height: c_int) void { sendCommandi(21, (y << 10) | x); sendCommandi(22, (((y + height) - 1) << 10) | ((x + width) - 1)); } pub fn sceGuDispBuffer(width: c_int, height: c_int, dispbp: ?*c_void, dispbw: c_int) void { @setRuntimeSafety(false); gu_draw_buffer.width = width; gu_draw_buffer.height = height; gu_draw_buffer.disp_buffer = dispbp; if ((gu_draw_buffer.frame_width != 0) or (gu_draw_buffer.frame_width != dispbw)) gu_draw_buffer.frame_width = dispbw; drawRegion(0, 0, gu_draw_buffer.width, gu_draw_buffer.height); _ = sceDisplaySetMode(0, gu_draw_buffer.width, gu_draw_buffer.height); if (gu_display_on != 0) _ = sceDisplaySetFrameBuf(@intToPtr(*c_void, @ptrToInt(ge_edram_address) + @ptrToInt(gu_draw_buffer.disp_buffer)), dispbw, gu_draw_buffer.pixel_size, @enumToInt(PspDisplaySetBufSync.Nextframe)); } pub fn sceGuDisplay(state: bool) void { if (state) { _ = sceDisplaySetFrameBuf(@intToPtr(*c_void, @ptrToInt(ge_edram_address) + @ptrToInt(gu_draw_buffer.disp_buffer)), gu_draw_buffer.frame_width, gu_draw_buffer.pixel_size, @enumToInt(PspDisplaySetBufSync.Nextframe)); } else { _ = sceDisplaySetFrameBuf(null, 0, 0, @enumToInt(PspDisplaySetBufSync.Nextframe)); } gu_display_on = @boolToInt(state); } pub fn sceGuDrawArray(prim: GuPrimitive, vtype: c_int, count: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { @setRuntimeSafety(false); if (vtype != 0) sendCommandi(18, vtype); if (indices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(indices) >> 8)) & 0xf0000); sendCommandi(2, @intCast(c_int, @ptrToInt(indices)) & 0xffffff); } if (vertices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(vertices) >> 8)) & 0xf0000); sendCommandi(1, @intCast(c_int, @ptrToInt(vertices)) & 0xffffff); } sendCommandiStall(4, (@enumToInt(prim) << 16) | count); } pub fn sceGuDrawArrayN(primitive_type: GuPrimitive, vertex_type: c_int, count: c_int, a3: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { @setRuntimeSafety(false); if (vertex_type != 0) sendCommandi(18, vertex_type); if (indices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(indices) >> 8)) & 0xf0000); sendCommandi(2, @intCast(c_int, @ptrToInt(indices)) & 0xffffff); } if (vertices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(vertices) >> 8)) & 0xf0000); sendCommandi(1, @intCast(c_int, @ptrToInt(vertices)) & 0xffffff); } if (a3 > 0) { var i: usize = @intCast(usize, a3) - 1; while (i >= 0) : (i -= 1) { sendCommandi(4, (@enumToInt(primitive_type) << 16) | count); } sendCommandiStall(4, (@enumToInt(primitive_type) << 16) | count); } } pub fn sceGuDrawBezier(vtype: c_int, ucount: c_int, vcount: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { @setRuntimeSafety(false); if (vtype != 0) sendCommandi(18, vtype); if (indices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(indices) >> 8)) & 0xf0000); sendCommandi(2, @intCast(c_int, @ptrToInt(indices)) & 0xffffff); } if (vertices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(vertices) >> 8)) & 0xf0000); sendCommandi(1, @intCast(c_int, @ptrToInt(vertices)) & 0xffffff); } sendCommandi(5, (vcount << 8) | ucount); } pub fn sceGuDrawBuffer(pix: GuPixelMode, fbp: ?*c_void, fbw: c_int) void { @setRuntimeSafety(false); var psm = @enumToInt(pix); gu_draw_buffer.pixel_size = psm; gu_draw_buffer.frame_width = fbw; gu_draw_buffer.frame_buffer = fbp; if (gu_draw_buffer.depth_buffer != null and gu_draw_buffer.height != 0) gu_draw_buffer.depth_buffer = @intToPtr(*c_void, (@ptrToInt(fbp) + @intCast(usize, ((gu_draw_buffer.height * fbw) << 2)))); if (gu_draw_buffer.depth_width != 0) gu_draw_buffer.depth_width = fbw; sendCommandi(210, psm); sendCommandi(156, @intCast(c_int, @intCast(c_uint, @ptrToInt(gu_draw_buffer.frame_buffer)) & 0xffffff)); sendCommandi(157, @intCast(c_int, ((@intCast(c_uint, @ptrToInt(gu_draw_buffer.frame_buffer)) & 0xff000000) >> 8)) | gu_draw_buffer.frame_width); sendCommandi(158, @intCast(c_int, @intCast(c_uint, @ptrToInt(gu_draw_buffer.depth_buffer)) & 0xffffff)); sendCommandi(159, @intCast(c_int, ((@intCast(c_uint, @ptrToInt(gu_draw_buffer.depth_buffer)) & 0xff000000) >> 8)) | gu_draw_buffer.depth_width); } pub fn sceGuDrawBufferList(psm: GuPixelMode, fbp: ?*c_void, fbw: c_int) void { @setRuntimeSafety(false); sendCommandi(210, @enumToInt(psm)); sendCommandi(156, @intCast(c_int, @ptrToInt(fbp)) & 0xffffff); sendCommandi(157, @intCast(c_int, (@intCast(c_uint, @ptrToInt(fbp)) & 0xff000000) >> 8) | fbw); } pub fn sceGuDrawSpline(vtype: c_int, ucount: c_int, vcount: c_int, uedge: c_int, vedge: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { @setRuntimeSafety(false); if (vtype != 0) sendCommandi(18, vtype); if (indices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(indices) >> 8)) & 0xf0000); sendCommandi(2, @intCast(c_int, @ptrToInt(indices)) & 0xffffff); } if (vertices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(vertices) >> 8)) & 0xf0000); sendCommandi(1, @intCast(c_int, @ptrToInt(vertices)) & 0xffffff); } sendCommandi(6, (vedge << 18) | (uedge << 16) | (vcount << 8) | ucount); } pub fn sceGuEnable(state: GuState) void { @setRuntimeSafety(false); switch (state) { .AlphaTest => { sendCommandi(34, 1); }, .DepthTest => { sendCommandi(35, 1); }, .ScissorTest => { gu_contexts[@intCast(usize, gu_curr_context)].scissor_enable = 1; sendCommandi(212, (gu_contexts[@intCast(usize, gu_curr_context)].scissor_start[1] << 10) | gu_contexts[@intCast(usize, gu_curr_context)].scissor_start[0]); sendCommandi(213, (gu_contexts[@intCast(usize, gu_curr_context)].scissor_end[1] << 10) | gu_contexts[@intCast(usize, gu_curr_context)].scissor_end[0]); }, .StencilTest => { sendCommandi(36, 1); }, .Blend => { sendCommandi(33, 1); }, .CullFace => { sendCommandi(29, 1); }, .Dither => { sendCommandi(32, 1); }, .Fog => { sendCommandi(31, 1); }, .ClipPlanes => { sendCommandi(28, 1); }, .Texture2D => { sendCommandi(30, 1); }, .Lighting => { sendCommandi(23, 1); }, .Light0 => { sendCommandi(24, 1); }, .Light1 => { sendCommandi(25, 1); }, .Light2 => { sendCommandi(26, 1); }, .Light3 => { sendCommandi(27, 1); }, .LineSmooth => { sendCommandi(37, 1); }, .PatchCullFace => { sendCommandi(38, 1); }, .ColorTest => { sendCommandi(39, 1); }, .ColorLogicOp => { sendCommandi(40, 1); }, .FaceNormalReverse => { sendCommandi(81, 1); }, .PatchFace => { sendCommandi(56, 1); }, .Fragment2X => { gu_contexts[@intCast(usize, gu_curr_context)].fragment_2x = 0x10000; sendCommandi(201, 0x10000 | gu_contexts[@intCast(usize, gu_curr_context)].texture_function); }, } var one: u32 = 1; if (@enumToInt(state) < 22) gu_states |= @intCast(i32, (one << @intCast(u5, @enumToInt(state)))); } pub fn sceGuEndObject() void { @setRuntimeSafety(false); var current: [*]u32 = gu_list.?.current; gu_list.?.current = @ptrCast([*]u32, &gu_object_stack[@intCast(usize, gu_object_stack_depth) - 1]); sendCommandi(16, @intCast(c_int, (@ptrToInt(current) >> 8)) & 0xf0000); sendCommandi(9, @intCast(c_int, @ptrToInt(current)) & 0xffffff); gu_list.?.current = current; gu_object_stack_depth -= 1; } pub fn sceGuBeginObject(vtype: c_int, count: c_int, indices: ?*const c_void, vertices: ?*const c_void) void { @setRuntimeSafety(false); if (vtype != 0) sendCommandi(18, vtype); if (indices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(indices) >> 8)) & 0xf0000); sendCommandi(2, @intCast(c_int, @ptrToInt(indices)) & 0xffffff); } if (vertices != null) { sendCommandi(16, @intCast(c_int, (@ptrToInt(vertices) >> 8)) & 0xf0000); sendCommandi(1, @intCast(c_int, @ptrToInt(vertices)) & 0xffffff); } sendCommandi(7, count); gu_object_stack[@intCast(usize, gu_object_stack_depth)] = @intCast(u32, @ptrToInt(gu_list.?.current)); gu_object_stack_depth += 1; sendCommandi(16, 0); sendCommandi(9, 0); } pub fn sceGuFinish() c_int { switch (@intToEnum(GuContextType, gu_curr_context)) { .Direct, .Send => { sendCommandi(15, 0); sendCommandiStall(12, 0); }, .Call => { if (gu_call_mode == 1) { sendCommandi(14, 0x120000); sendCommandi(12, 0); sendCommandiStall(0, 0); } else { sendCommandi(11, 0); } }, } var size: u32 = @ptrToInt(gu_list.?.current) - @ptrToInt(gu_list.?.start); // go to parent list gu_curr_context = gu_list.?.parent_context; gu_list = &gu_contexts[@intCast(usize, gu_curr_context)].list; return @intCast(c_int, size); } pub fn guFinish() void { _ = sceGuFinish(); } pub fn sceGuFinishId(id: c_int) c_int { switch (@intToEnum(GuContextType, gu_curr_context)) { .Direct, .Send => { sendCommandi(15, id & 0xffff); sendCommandiStall(12, 0); }, .Call => { if (gu_call_mode == 1) { sendCommandi(14, 0x120000); sendCommandi(12, 0); sendCommandiStall(0, 0); } else { sendCommandi(11, 0); } }, } var size: u32 = @ptrToInt(gu_list.?.current) - @ptrToInt(gu_list.?.start); // go to parent list gu_curr_context = gu_list.?.parent_context; gu_list = &gu_contexts[@intCast(usize, gu_curr_context)].list; return @intCast(c_int, size); } pub fn sceGuFog(near: f32, far: f32, col: c_uint) void { @setRuntimeSafety(false); var distance: f32 = far - near; if (distance > 0) distance = 1.0 / distance; sendCommandi(207, @intCast(c_int, col & 0xffffff)); sendCommandf(205, far); sendCommandf(206, distance); } pub fn sceGuFrontFace(order: FrontFaceDirection) void { @setRuntimeSafety(false); if (order != FrontFaceDirection.Clockwise) { sendCommandi(155, 0); } else { sendCommandi(155, 1); } } pub fn sceGuGetAllStatus() c_int { return gu_states; } pub fn sceGuGetStatus(state: GuState) c_int { if (state < 22) return (@enumToInt(gu_states) >> @intCast(u5, state)) & 1; return 0; } pub fn sceGuLight(light: c_int, typec: GuLightType, components: GuLightBitFlags, position: [*c]const ScePspFVector3) void { @setRuntimeSafety(false); sendCommandf(light_settings[light].xpos, position.*.x); sendCommandf(light_settings[light].ypos, position.*.y); sendCommandf(light_settings[light].zpos, position.*.z); var kind: c_int = 2; if (@enumToInt(components) != 8) { if ((@enumToInt(components) ^ 6) < 1) { kind = 1; } else { kind = 0; } } sendCommandi(light_settings[light].typec, ((typec & 0x03) << 8) | kind); } pub fn sceGuLightAtt(light: usize, atten0: f32, atten1: f32, atten2: f32) void { @setRuntimeSafety(false); sendCommandf(light_settings[light].constant, atten0); sendCommandf(light_settings[light].linear, atten1); sendCommandf(light_settings[light].quadratic, atten2); } pub fn sceGuLightColor(light: usize, component: GuLightBitFlags, col: c_int) void { @setRuntimeSafety(false); switch (@intToEnum(GuLightBitFlags, component)) { .Ambient => { sendCommandi(light_settings[light].ambient, col & 0xffffff); }, .Diffuse => { sendCommandi(light_settings[light].diffuse, col & 0xffffff); }, .AmbientDiffuse => { sendCommandi(light_settings[light].ambient, col & 0xffffff); sendCommandi(light_settings[light].diffuse, col & 0xffffff); }, .Specular => { sendCommandi(light_settings[light].specular, col & 0xffffff); }, .DiffuseSpecular => { sendCommandi(light_settings[light].diffuse, col & 0xffffff); sendCommandi(light_settings[light].specular, col & 0xffffff); }, else => {}, } } pub fn sceGuLightMode(mode: c_int) void { @setRuntimeSafety(false); sendCommandi(94, mode); } pub fn sceGuLightSpot(light: usize, direction: [*c]const ScePspFVector3, exponent: f32, cutoff: f32) void { @setRuntimeSafety(false); sendCommandf(light_settings[light].exponent, exponent); sendCommandf(light_settings[light].cutoff, cutoff); sendCommandf(light_settings[light].xdir, direction.*.x); sendCommandf(light_settings[light].ydir, direction.*.y); sendCommandf(light_settings[light].zdir, direction.*.z); } pub fn sceGuLogicalOp(op: GuLogicalOperation) void { @setRuntimeSafety(false); sendCommandi(230, @enumToInt(op) & 0x0f); } pub fn sceGuModelColor(emissive: c_int, ambient: c_int, diffuse: c_int, specular: c_int) void { @setRuntimeSafety(false); sendCommandi(84, emissive & 0xffffff); sendCommandi(86, diffuse & 0xffffff); sendCommandi(85, ambient & 0xffffff); sendCommandi(87, specular & 0xffffff); } pub fn sceGuMorphWeight(index: c_int, weight: f32) void { @setRuntimeSafety(false); sendCommandf(44 + index, weight); } pub fn sceGuOffset(x: c_int, y: c_int) void { @setRuntimeSafety(false); sendCommandi(76, x << 4); sendCommandi(77, y << 4); } pub fn sceGuPatchDivide(ulevel: c_int, vlevel: c_int) void { @setRuntimeSafety(false); sendCommandi(54, (vlevel << 8) | ulevel); } pub fn sceGuPatchFrontFace(a0: c_int) void { @setRuntimeSafety(false); sendCommandi(56, a0); } pub fn sceGuPatchPrim(prim: GuPrimitive) void { @setRuntimeSafety(false); switch (prim) { .Points => { sendCommandi(55, 2); }, .LineStrip => { sendCommandi(55, 1); }, .TriangleStrip => { sendCommandi(55, 0); }, else => {}, } } pub fn sceGuPixelMask(mask: c_int) void { @setRuntimeSafety(false); sendCommandi(232, mask & 0xffffff); sendCommandi(233, mask >> 24); } pub fn sceGuScissor(x: c_int, y: c_int, w: c_int, h: c_int) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].scissor_start[0] = x; gu_contexts[@intCast(usize, gu_curr_context)].scissor_start[1] = y; gu_contexts[@intCast(usize, gu_curr_context)].scissor_end[0] = w - 1; gu_contexts[@intCast(usize, gu_curr_context)].scissor_end[1] = h - 1; if (gu_contexts[@intCast(usize, gu_curr_context)].scissor_enable != 0) { sendCommandi(212, (gu_contexts[@intCast(usize, gu_curr_context)].scissor_start[1] << 10) | gu_contexts[@intCast(usize, gu_curr_context)].scissor_start[0]); sendCommandi(213, (gu_contexts[@intCast(usize, gu_curr_context)].scissor_end[1] << 10) | gu_contexts[@intCast(usize, gu_curr_context)].scissor_end[0]); } } pub fn sceGuSendCommandf(cmd: c_int, argument: f32) void { @setRuntimeSafety(false); sendCommandf(cmd, argument); } pub fn sceGuSendCommandi(cmd: c_int, argument: c_int) void { @setRuntimeSafety(false); sendCommandi(cmd, argument); } pub fn sceGuSendList(mode: c_int, list: ?*const c_void, context: [*c]PspGeContext) void { @setRuntimeSafety(false); gu_settings.signal_offset = 0; var args: PspGeListArgs = undefined; args.size = 8; args.context = context; var list_id: i32 = 0; var callback = gu_settings.ge_callback_id; switch (@intToEnum(GuQueueMode, mode)) { .Head => { list_id = sceGeListEnQueueHead(list, null, callback, &args); }, .Tail => { list_id = sceGeListEnQueue(list, null, callback, &args); }, } ge_list_executed[1] = list_id; } pub fn sceGuSetAllStatus(status: c_int) void { @setRuntimeSafety(false); var i: c_int = 0; while (i < 22) : (i += 1) { if ((status >> @intCast(u5, i)) & 1 != 0) { sceGuEnable(i); } else { sceGuDisable(i); } } } pub fn sceGuSetCallback(signal: c_int, callback: ?fn (c_int) callconv(.C) void) GuCallback { var old_callback: GuCallback = undefined; switch (@intToEnum(GuCallbackId, signal)) { .Signal => { old_callback = gu_settings.sig; gu_settings.sig = callback; }, .Finish => { old_callback = gu_settings.fin; gu_settings.fin = callback; }, } return old_callback; } pub fn sceGuSetDither(matrix: *const ScePspIMatrix4) void { @setRuntimeSafety(false); sendCommandi(226, (matrix.x.x & 0x0f) | ((matrix.x.y & 0x0f) << 4) | ((matrix.x.z & 0x0f) << 8) | ((matrix.x.w & 0x0f) << 12)); sendCommandi(227, (matrix.y.x & 0x0f) | ((matrix.y.y & 0x0f) << 4) | ((matrix.y.z & 0x0f) << 8) | ((matrix.y.w & 0x0f) << 12)); sendCommandi(228, (matrix.z.x & 0x0f) | ((matrix.z.y & 0x0f) << 4) | ((matrix.z.z & 0x0f) << 8) | ((matrix.z.w & 0x0f) << 12)); sendCommandi(229, (matrix.w.x & 0x0f) | ((matrix.w.y & 0x0f) << 4) | ((matrix.w.z & 0x0f) << 8) | ((matrix.w.w & 0x0f) << 12)); } pub fn sceGuSetMatrix(typec: c_int, matrix: [*c]ScePspFMatrix4) void { @setRuntimeSafety(false); const fmatrix: [*]f32 = @ptrCast([*]f32, matrix); switch (typec) { 0 => { var i: usize = 0; sendCommandf(62, 0); while (i < 16) : (i += 1) { sendCommandf(63, fmatrix[i]); } }, 1 => { var i: usize = 0; sendCommandf(60, 0); // 4*4 -> 3*4 - view matrix? while (i < 4) : (i += 1) { var j: usize = 0; while (j < 3) : (j += 1) { sendCommandf(61, fmatrix[j + i * 4]); } } }, 2 => { var i: usize = 0; sendCommandf(58, 0); // 4*4 -> 3*4 - view matrix? while (i < 4) : (i += 1) { var j: usize = 0; while (j < 3) : (j += 1) { sendCommandf(59, fmatrix[j + i * 4]); } } }, 3 => { var i: usize = 0; sendCommandf(64, 0); // 4*4 -> 3*4 - view matrix? while (i < 4) : (i += 1) { var j: usize = 0; while (j < 3) : (j += 1) { sendCommandf(65, fmatrix[j + i * 4]); } } }, else => {}, } } pub fn sceGuSetStatus(state: GuState, status: bool) void { @setRuntimeSafety(false); if (status) { sceGuEnable(@enumToInt(state)); } else { sceGuDisable(@enumToInt(state)); } } pub fn sceGuShadeModel(mode: ShadeModel) void { @setRuntimeSafety(false); if (mode == ShadeModel.Smooth) { sendCommandi(80, 1); } else { sendCommandi(80, 0); } } pub fn sceGuSignal(signal: c_int, behavior: GuSignalBehavior) void { @setRuntimeSafety(false); sendCommandi(14, ((signal & 0xff) << 16) | (@enumToInt(behavior) & 0xffff)); sendCommandi(12, 0); if (signal == 3) { sendCommandi(15, 0); sendCommandi(12, 0); } sendCommandiStall(0, 0); } pub fn sceGuSpecular(power: f32) void { @setRuntimeSafety(false); sendCommandf(91, power); } pub fn sceGuStencilFunc(func: StencilFunc, ref: c_int, mask: c_int) void { @setRuntimeSafety(false); sendCommandi(220, @enumToInt(func) | ((ref & 0xff) << 8) | ((mask & 0xff) << 16)); } pub fn sceGuStencilOp(fail: StencilOperation, zfail: StencilOperation, zpass: StencilOperation) void { @setRuntimeSafety(false); sendCommandi(221, @enumToInt(fail) | (@enumToInt(zfail) << 8) | (@enumToInt(zpass) << 16)); } pub fn sceGuSwapBuffers() ?*c_void { @setRuntimeSafety(false); if (gu_settings.swapBuffersCallback != null) { gu_settings.swapBuffersCallback.?(&gu_draw_buffer.disp_buffer, &gu_draw_buffer.frame_buffer); } else { var temp = gu_draw_buffer.disp_buffer; gu_draw_buffer.disp_buffer = gu_draw_buffer.frame_buffer; gu_draw_buffer.frame_buffer = temp; } if (gu_display_on != 0) { _ = sceDisplaySetFrameBuf(@intToPtr(*c_void, @ptrToInt(ge_edram_address) + @ptrToInt(gu_draw_buffer.disp_buffer)), gu_draw_buffer.frame_width, gu_draw_buffer.pixel_size, gu_settings.swapBuffersBehaviour); } gu_current_frame ^= 1; return gu_draw_buffer.frame_buffer; } pub fn guSwapBuffers() void { _ = sceGuSwapBuffers(); } pub fn guSwapBuffersBehaviour(behaviour: c_int) void { @setRuntimeSafety(false); gu_settings.swapBuffersBehaviour = behaviour; } pub fn guSwapBuffersCallback(callback: GuSwapBuffersCallback) void { @setRuntimeSafety(false); gu_settings.swapBuffersCallback = callback; } pub fn sceGuSync(mode: GuSyncMode, what: GuSyncBehavior) c_int { switch (mode) { .Finish => { return sceGeDrawSync(@enumToInt(what)); }, .List => { return sceGeListSync(ge_list_executed[0], @enumToInt(what)); }, .Send => { return sceGeListSync(ge_list_executed[1], @enumToInt(what)); }, else => { return 0; }, } } pub fn guSync(mode: GuSyncMode, what: GuSyncBehavior) void { _ = sceGuSync(mode, what); } pub fn sceGuTerm() void { @setRuntimeSafety(false); _ = sceKernelDeleteEventFlag(gu_settings.kernel_event_flag); _ = sceGeUnsetCallback(gu_settings.ge_callback_id); } pub fn sceGuTexEnvColor(color: c_int) void { @setRuntimeSafety(false); sendCommandi(202, color & 0xffffff); } pub fn sceGuTexFilter(min: TextureFilter, mag: TextureFilter) void { @setRuntimeSafety(false); sendCommandi(198, (@enumToInt(mag) << 8) | @enumToInt(min)); } pub fn sceGuTexFlush() void { @setRuntimeSafety(false); sendCommandf(203, 0.0); } pub fn sceGuTexFunc(tfx: TextureEffect, tcc: TextureColorComponent) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].texture_function = (@enumToInt(tcc) << 8) | @enumToInt(tfx); sendCommandi(201, ((@enumToInt(tcc) << 8) | @enumToInt(tfx)) | gu_contexts[@intCast(usize, gu_curr_context)].fragment_2x); } const tbpcmd_tbl = [_]u8{ 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7 }; const tbwcmd_tbl = [_]u8{ 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf }; const tsizecmd_tbl = [_]u8{ 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf }; fn getExp(val: c_int) c_int { @setRuntimeSafety(false); var v: c_uint = @intCast(c_uint, val); var r: c_uint = ((0xFFFF - v) >> 31) << 4; v >>= @intCast(u5, r); var shift: c_uint = ((0xFF - v) >> 31) << 3; v >>= @intCast(u5, shift); r |= shift; shift = ((0xF - v) >> 31) << 2; v >>= @intCast(u5, shift); r |= shift; shift = ((0x3 - v) >> 31) << 1; return @intCast(c_int, r) | @intCast(c_int, shift) | @intCast(c_int, (v >> @intCast(u5, (shift + 1)))); } pub fn sceGuTexImage(mipmap: c_int, width: c_int, height: c_int, tbw: c_int, tbp: ?*const c_void) void { @setRuntimeSafety(false); sendCommandi(tbpcmd_tbl[@intCast(usize, mipmap)], @intCast(c_int, @ptrToInt(tbp)) & 0xffffff); sendCommandi(tbwcmd_tbl[@intCast(usize, mipmap)], @intCast(c_int, ((@ptrToInt(tbp) >> 8) & 0x0f0000)) | tbw); sendCommandi(tsizecmd_tbl[@intCast(usize, mipmap)], getExp(height) << 8 | getExp(width)); sceGuTexFlush(); } pub fn sceGuTexLevelMode(mode: TextureLevelMode, bias: f32) void { @setRuntimeSafety(false); var offset: c_int = @floatToInt(c_int, bias * 16.0); if (offset >= 128) { offset = 128; } else if (offset < -128) { offset = -128; } sendCommandi(200, ((offset) << 16) | @enumToInt(mode)); } pub fn sceGuTexMapMode(mode: c_int, a1: c_int, a2: c_int) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].texture_map_mode = mode & 0x03; sendCommandi(192, gu_contexts[@intCast(usize, gu_curr_context)].texture_proj_map_mode | (mode & 0x03)); sendCommandi(193, (a2 << 8) | (a1 & 0x03)); } pub fn sceGuTexMode(tpsm: GuPixelMode, maxmips: c_int, a2: c_int, swizzle: c_int) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].texture_mode = @enumToInt(tpsm); sendCommandi(194, (maxmips << 16) | (a2 << 8) | (swizzle)); sendCommandi(195, @enumToInt(tpsm)); sceGuTexFlush(); } pub fn sceGuTexOffset(u: f32, v: f32) void { @setRuntimeSafety(false); sendCommandf(74, u); sendCommandf(75, v); } pub fn sceGuTexProjMapMode(mode: c_int) void { @setRuntimeSafety(false); gu_contexts[@intCast(usize, gu_curr_context)].texture_proj_map_mode = ((mode & 0x03) << 8); sendCommandi(192, ((mode & 0x03) << 8) | gu_contexts[@intCast(usize, gu_curr_context)].texture_map_mode); } pub fn sceGuTexScale(u: f32, v: f32) void { @setRuntimeSafety(false); sendCommandf(72, u); sendCommandf(73, v); } pub fn sceGuTexSlope(slope: f32) void { @setRuntimeSafety(false); sendCommandf(208, slope); } pub fn sceGuTexSync() void { @setRuntimeSafety(false); sendCommandi(204, 0); } pub fn sceGuTexWrap(u: GuTexWrapMode, v: GuTexWrapMode) void { @setRuntimeSafety(false); sendCommandi(199, (@enumToInt(v) << 8) | (@enumToInt(u))); } pub fn sceGuViewport(cx: c_int, cy: c_int, width: c_int, height: c_int) void { @setRuntimeSafety(false); sendCommandf(66, @intToFloat(f32, width >> 1)); sendCommandf(67, @intToFloat(f32, (-height) >> 1)); sendCommandf(69, @intToFloat(f32, cx)); sendCommandf(70, @intToFloat(f32, cy)); } const ge_init_list = [_]c_uint{ 0x01000000, 0x02000000, 0x10000000, 0x12000000, 0x13000000, 0x15000000, 0x16000000, 0x17000000, 0x18000000, 0x19000000, 0x1a000000, 0x1b000000, 0x1c000000, 0x1d000000, 0x1e000000, 0x1f000000, 0x20000000, 0x21000000, 0x22000000, 0x23000000, 0x24000000, 0x25000000, 0x26000000, 0x27000000, 0x28000000, 0x2a000000, 0x2b000000, 0x2c000000, 0x2d000000, 0x2e000000, 0x2f000000, 0x30000000, 0x31000000, 0x32000000, 0x33000000, 0x36000000, 0x37000000, 0x38000000, 0x3a000000, 0x3b000000, 0x3c000000, 0x3d000000, 0x3e000000, 0x3f000000, 0x40000000, 0x41000000, 0x42000000, 0x43000000, 0x44000000, 0x45000000, 0x46000000, 0x47000000, 0x48000000, 0x49000000, 0x4a000000, 0x4b000000, 0x4c000000, 0x4d000000, 0x50000000, 0x51000000, 0x53000000, 0x54000000, 0x55000000, 0x56000000, 0x57000000, 0x58000000, 0x5b000000, 0x5c000000, 0x5d000000, 0x5e000000, 0x5f000000, 0x60000000, 0x61000000, 0x62000000, 0x63000000, 0x64000000, 0x65000000, 0x66000000, 0x67000000, 0x68000000, 0x69000000, 0x6a000000, 0x6b000000, 0x6c000000, 0x6d000000, 0x6e000000, 0x6f000000, 0x70000000, 0x71000000, 0x72000000, 0x73000000, 0x74000000, 0x75000000, 0x76000000, 0x77000000, 0x78000000, 0x79000000, 0x7a000000, 0x7b000000, 0x7c000000, 0x7d000000, 0x7e000000, 0x7f000000, 0x80000000, 0x81000000, 0x82000000, 0x83000000, 0x84000000, 0x85000000, 0x86000000, 0x87000000, 0x88000000, 0x89000000, 0x8a000000, 0x8b000000, 0x8c000000, 0x8d000000, 0x8e000000, 0x8f000000, 0x90000000, 0x91000000, 0x92000000, 0x93000000, 0x94000000, 0x95000000, 0x96000000, 0x97000000, 0x98000000, 0x99000000, 0x9a000000, 0x9b000000, 0x9c000000, 0x9d000000, 0x9e000000, 0x9f000000, 0xa0000000, 0xa1000000, 0xa2000000, 0xa3000000, 0xa4000000, 0xa5000000, 0xa6000000, 0xa7000000, 0xa8040004, 0xa9000000, 0xaa000000, 0xab000000, 0xac000000, 0xad000000, 0xae000000, 0xaf000000, 0xb0000000, 0xb1000000, 0xb2000000, 0xb3000000, 0xb4000000, 0xb5000000, 0xb8000101, 0xb9000000, 0xba000000, 0xbb000000, 0xbc000000, 0xbd000000, 0xbe000000, 0xbf000000, 0xc0000000, 0xc1000000, 0xc2000000, 0xc3000000, 0xc4000000, 0xc5000000, 0xc6000000, 0xc7000000, 0xc8000000, 0xc9000000, 0xca000000, 0xcb000000, 0xcc000000, 0xcd000000, 0xce000000, 0xcf000000, 0xd0000000, 0xd2000000, 0xd3000000, 0xd4000000, 0xd5000000, 0xd6000000, 0xd7000000, 0xd8000000, 0xd9000000, 0xda000000, 0xdb000000, 0xdc000000, 0xdd000000, 0xde000000, 0xdf000000, 0xe0000000, 0xe1000000, 0xe2000000, 0xe3000000, 0xe4000000, 0xe5000000, 0xe6000000, 0xe7000000, 0xe8000000, 0xe9000000, 0xeb000000, 0xec000000, 0xee000000, 0xf0000000, 0xf1000000, 0xf2000000, 0xf3000000, 0xf4000000, 0xf5000000, 0xf6000000, 0xf7000000, 0xf8000000, 0xf9000000, 0x0f000000, 0x0c000000, 0, 0, }; pub fn sceGuInit() void { @setRuntimeSafety(false); var callback: PspGeCallbackData = undefined; callback.signal_func = callbackSig; callback.signal_arg = &gu_settings; callback.finish_func = callbackFin; callback.finish_arg = &gu_settings; gu_settings.ge_callback_id = sceGeSetCallback(&callback); gu_settings.swapBuffersCallback = null; gu_settings.swapBuffersBehaviour = 1; ge_edram_address = sceGeEdramGetAddr(); ge_list_executed[0] = sceGeListEnQueue((@intToPtr(*c_void, @ptrToInt(&ge_init_list) & 0x1fffffff)), null, gu_settings.ge_callback_id, 0); resetValues(); gu_settings.kernel_event_flag = sceKernelCreateEventFlag("SceGuSignal", 512, 3, 0); _ = sceGeListSync(ge_list_executed[0], 0); } pub fn sceGuStart(cont: GuContextType, list: ?*c_void) void { @setRuntimeSafety(false); var local_list: [*]u32 = @intToPtr([*]u32, (@intCast(usize, @ptrToInt(list)) | 0x40000000)); var cid: c_int = @enumToInt(cont); gu_contexts[@intCast(usize, cid)].list.start = local_list; gu_contexts[@intCast(usize, cid)].list.current = local_list; gu_contexts[@intCast(usize, cid)].list.parent_context = gu_curr_context; gu_list = &gu_contexts[@intCast(usize, cid)].list; gu_curr_context = cid; if (cid == 0) { ge_list_executed[0] = sceGeListEnQueue(local_list, local_list, gu_settings.ge_callback_id, 0); gu_settings.signal_offset = 0; } if (gu_init == 0) { var dither_matrix = [_]i32{ -4, 0, -3, 1, 2, -2, 3, -1, -3, 1, -4, 0, 3, -1, 2, -2, }; sceGuSetDither(@ptrCast(*ScePspIMatrix4, &dither_matrix)); sceGuPatchDivide(16, 16); sceGuColorMaterial(@enumToInt(GuLightBitFlags.Ambient) | @enumToInt(GuLightBitFlags.Diffuse) | @enumToInt(GuLightBitFlags.Specular)); sceGuSpecular(1.0); sceGuTexScale(1.0, 1.0); gu_init = 1; } if (gu_curr_context == 0) { if (gu_draw_buffer.frame_width != 0) { sendCommandi(156, @intCast(c_int, @ptrToInt(gu_draw_buffer.frame_buffer)) & 0xffffff); sendCommandi(157, (@intCast(c_int, (@ptrToInt(gu_draw_buffer.frame_buffer) & 0xff000000)) >> 8) | gu_draw_buffer.frame_width); } } } const Vertex = packed struct { color: u32, x: u16, y: u16, z: u16, pad: u16 }; pub fn sceGuClear(flags: c_int) void { @setRuntimeSafety(false); var context: *GuContext = &gu_contexts[@intCast(usize, gu_curr_context)]; var filter: u32 = 0; switch (gu_draw_buffer.pixel_size) { 0 => { filter = context.clear_color & 0xffffff; }, 1 => { filter = (context.clear_color & 0xffffff) | (context.clear_stencil << 31); }, 2 => { filter = (context.clear_color & 0xffffff) | (context.clear_stencil << 28); }, 3 => { filter = (context.clear_color & 0xffffff) | (context.clear_stencil << 24); }, else => { filter = 0; }, } var count: i32 = @divTrunc(gu_draw_buffer.width + 63, 64) * 2; var vertices: [*]Vertex = @ptrCast([*]Vertex, sceGuGetMemory(@intCast(c_uint, count) * @sizeOf(Vertex))); var i: usize = 0; var curr: [*]Vertex = vertices; while (i < count) : (i += 1) { var j: u16 = 0; var k: u16 = 0; j = @intCast(u16, i) >> 1; k = (@intCast(u16, i) & 1); curr[i].color = filter; curr[i].x = (j + k) * 64; curr[i].y = k * @intCast(u16, gu_draw_buffer.height); curr[i].z = @intCast(u16, context.clear_depth); } sendCommandi(211, ((flags & (@enumToInt(ClearBitFlags.ColorBuffer) | @enumToInt(ClearBitFlags.StencilBuffer) | @enumToInt(ClearBitFlags.DepthBuffer))) << 8) | 0x01); sceGuDrawArray(GuPrimitive.Sprites, @enumToInt(VertexTypeFlags.Color8888) | @enumToInt(VertexTypeFlags.Vertex16Bit) | @enumToInt(VertexTypeFlags.Transform2D), @intCast(c_int, count), null, vertices); sendCommandi(211, 0); } pub fn sceGuGetMemory(size: c_uint) *c_void { @setRuntimeSafety(false); var siz = size; siz += 3; siz += (siz >> 31) >> 30; siz = (siz >> 2) << 2; var orig_ptr: [*]u32 = @ptrCast([*]u32, gu_list.?.current); var new_ptr: [*]u32 = @intToPtr([*]u32, (@intCast(c_uint, @ptrToInt(orig_ptr)) + siz + 8)); var lo = (8 << 24) | (@ptrToInt(new_ptr) & 0xffffff); var hi = (16 << 24) | ((@ptrToInt(new_ptr) >> 8) & 0xf0000); orig_ptr[0] = hi; orig_ptr[1] = lo; gu_list.?.current = new_ptr; if (gu_curr_context == 0) { _ = sceGeListUpdateStallAddr(ge_list_executed[0], new_ptr); } return @intToPtr(*c_void, @ptrToInt(orig_ptr + 2)); }
src/psp/sdk/pspguimpl.zig
const std = @import("std"); const zang = @import("zang"); const common = @import("common.zig"); const c = @import("common/c.zig"); const StereoEchoes = @import("modules.zig").StereoEchoes(15000); pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb; pub const AUDIO_SAMPLE_RATE = 48000; pub const AUDIO_BUFFER_SIZE = 1024; pub const DESCRIPTION = \\example_detuned \\ \\Play an instrument with the keyboard. There is a \\random warble added to the note frequencies, which was \\created using white noise and a low-pass filter. \\ \\Press spacebar to cycle through a few modes: \\ \\ 1. wide warble, no echo \\ 2. narrow warble, no echo \\ 3. wide warble, echo \\ 4. narrow warble, echo (here the warble does a good \\ job of avoiding constructive interference from \\ the echo) ; const a4 = 440.0; pub const Instrument = struct { pub const num_outputs = 2; pub const num_temps = 3; pub const Params = struct { sample_rate: f32, freq: f32, freq_warble: []const f32, note_on: bool, }; osc: zang.TriSawOsc, env: zang.Envelope, main_filter: zang.Filter, pub fn init() Instrument { return .{ .osc = zang.TriSawOsc.init(), .env = zang.Envelope.init(), .main_filter = zang.Filter.init(), }; } pub fn paint( self: *Instrument, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { var i: usize = span.start; while (i < span.end) : (i += 1) { temps[0][i] = params.freq * std.math.pow(f32, 2.0, params.freq_warble[i]); } // paint with oscillator into temps[1] zang.zero(span, temps[1]); self.osc.paint(span, .{temps[1]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .freq = zang.buffer(temps[0]), .color = 0.0, }); // output frequency for syncing oscilloscope zang.addInto(span, outputs[1], temps[0]); // slight volume reduction zang.multiplyWithScalar(span, temps[1], 0.75); // combine with envelope zang.zero(span, temps[0]); self.env.paint(span, .{temps[0]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .attack = .{ .cubed = 0.025 }, .decay = .{ .cubed = 0.1 }, .release = .{ .cubed = 1.0 }, .sustain_volume = 0.5, .note_on = params.note_on, }); zang.zero(span, temps[2]); zang.multiply(span, temps[2], temps[1], temps[0]); // add main filter self.main_filter.paint(span, .{outputs[0]}, .{}, note_id_changed, .{ .input = temps[2], .type = .low_pass, .cutoff = zang.constant(zang.cutoffFromFrequency( //params.freq + 400.0, 880.0, params.sample_rate, )), .res = 0.8, }); } }; pub const OuterInstrument = struct { pub const num_outputs = 2; pub const num_temps = 4; pub const Params = struct { sample_rate: f32, freq: f32, note_on: bool, mode: u32, }; noise: zang.Noise, noise_filter: zang.Filter, inner: Instrument, pub fn init() OuterInstrument { return .{ .noise = zang.Noise.init(), .noise_filter = zang.Filter.init(), .inner = Instrument.init(), }; } pub fn paint( self: *OuterInstrument, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { // temps[0] = filtered noise // note: filter frequency is set to 4hz. i wanted to go slower but // unfortunately at below 4, the filter degrades and the output // frequency slowly sinks to zero // (the number is relative to sample rate, so at 96khz it should be at // least 8hz) zang.zero(span, temps[1]); self.noise.paint(span, .{temps[1]}, .{}, note_id_changed, .{ .color = .white }); zang.zero(span, temps[0]); self.noise_filter.paint(span, .{temps[0]}, .{}, note_id_changed, .{ .input = temps[1], .type = .low_pass, .cutoff = zang.constant(zang.cutoffFromFrequency( 4.0, params.sample_rate, )), .res = 0.0, }); if ((params.mode & 1) == 0) { zang.multiplyWithScalar(span, temps[0], 4.0); } self.inner.paint( span, outputs, .{ temps[1], temps[2], temps[3] }, note_id_changed, .{ .sample_rate = params.sample_rate, .freq = params.freq, .freq_warble = temps[0], .note_on = params.note_on, }, ); } }; pub const MainModule = struct { pub const num_outputs = 3; pub const num_temps = 5; pub const output_audio = common.AudioOut{ .stereo = .{ .left = 0, .right = 1 } }; pub const output_visualize = 0; pub const output_sync_oscilloscope = 2; key: ?i32, iq: zang.Notes(OuterInstrument.Params).ImpulseQueue, idgen: zang.IdGenerator, outer: OuterInstrument, trigger: zang.Trigger(OuterInstrument.Params), echoes: StereoEchoes, mode: u32, pub fn init() MainModule { return .{ .key = null, .iq = zang.Notes(OuterInstrument.Params).ImpulseQueue.init(), .idgen = zang.IdGenerator.init(), .outer = OuterInstrument.init(), .trigger = zang.Trigger(OuterInstrument.Params).init(), .echoes = StereoEchoes.init(), .mode = 0, }; } pub fn paint( self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, ) void { // FIXME - here's something missing in the API... what if i want to // pass some "global" params to paintFromImpulses? in other words, // saw that of the fields in OuterInstrument.Params, i only want to set // some of them in the impulse queue. others i just want to pass once, // here. for example i would pass the "mode" field. // FIXME - is the above comment obsolete? zang.zero(span, temps[0]); { var ctr = self.trigger.counter(span, self.iq.consume()); while (self.trigger.next(&ctr)) |result| { self.outer.paint( result.span, .{ temps[0], outputs[2] }, .{ temps[1], temps[2], temps[3], temps[4] }, result.note_id_changed, result.params, ); } } if ((self.mode & 2) == 0) { // avoid the echo effect zang.addInto(span, outputs[0], temps[0]); zang.addInto(span, outputs[1], temps[0]); zang.zero(span, temps[0]); } self.echoes.paint( span, .{ outputs[0], outputs[1] }, .{ temps[1], temps[2], temps[3], temps[4] }, false, .{ .input = temps[0], .feedback_volume = 0.6, .cutoff = 0.1, }, ); } pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool { if (key == c.SDLK_SPACE and down) { self.mode = (self.mode + 1) & 3; return false; } if (common.getKeyRelFreq(key)) |rel_freq| { if (down or (if (self.key) |nh| nh == key else false)) { self.key = if (down) key else null; self.iq.push(impulse_frame, self.idgen.nextId(), .{ .sample_rate = AUDIO_SAMPLE_RATE, .freq = a4 * rel_freq * 0.5, .note_on = down, // note: because i'm passing mode here, a change to mode // take effect until you press a new key .mode = self.mode, }); } return true; } return false; } };
examples/example_detuned.zig
const notes = @import("zang/notes.zig"); pub const IdGenerator = notes.IdGenerator; pub const Impulse = notes.Impulse; pub const Notes = notes.Notes; const trigger = @import("zang/trigger.zig"); pub const ConstantOrBuffer = trigger.ConstantOrBuffer; pub const constant = trigger.constant; pub const buffer = trigger.buffer; pub const Trigger = trigger.Trigger; const mixdown = @import("zang/mixdown.zig"); pub const AudioFormat = mixdown.AudioFormat; pub const mixDown = mixdown.mixDown; const basics = @import("zang/basics.zig"); pub const Span = basics.Span; pub const zero = basics.zero; pub const set = basics.set; pub const copy = basics.copy; pub const add = basics.add; pub const addInto = basics.addInto; pub const addScalar = basics.addScalar; pub const addScalarInto = basics.addScalarInto; pub const multiply = basics.multiply; pub const multiplyWith = basics.multiplyWith; pub const multiplyScalar = basics.multiplyScalar; pub const multiplyWithScalar = basics.multiplyWithScalar; const painter = @import("zang/painter.zig"); pub const PaintCurve = painter.PaintCurve; pub const PaintState = painter.PaintState; pub const Painter = painter.Painter; const delay = @import("zang/delay.zig"); pub const Delay = delay.Delay; const mod_curve = @import("zang/mod_curve.zig"); pub const Curve = mod_curve.Curve; pub const CurveNode = mod_curve.CurveNode; pub const InterpolationFunction = mod_curve.InterpolationFunction; const mod_cycle = @import("zang/mod_cycle.zig"); pub const Cycle = mod_cycle.Cycle; const mod_decimator = @import("zang/mod_decimator.zig"); pub const Decimator = mod_decimator.Decimator; const mod_distortion = @import("zang/mod_distortion.zig"); pub const Distortion = mod_distortion.Distortion; pub const DistortionType = mod_distortion.DistortionType; const mod_envelope = @import("zang/mod_envelope.zig"); pub const Envelope = mod_envelope.Envelope; const mod_filter = @import("zang/mod_filter.zig"); pub const Filter = mod_filter.Filter; pub const FilterType = mod_filter.FilterType; pub const cutoffFromFrequency = mod_filter.cutoffFromFrequency; const mod_gate = @import("zang/mod_gate.zig"); pub const Gate = mod_gate.Gate; const mod_noise = @import("zang/mod_noise.zig"); pub const Noise = mod_noise.Noise; pub const NoiseColor = mod_noise.NoiseColor; const mod_portamento = @import("zang/mod_portamento.zig"); pub const Portamento = mod_portamento.Portamento; const mod_pulseosc = @import("zang/mod_pulseosc.zig"); pub const PulseOsc = mod_pulseosc.PulseOsc; const mod_sampler = @import("zang/mod_sampler.zig"); pub const Sampler = mod_sampler.Sampler; pub const Sample = mod_sampler.Sample; pub const SampleFormat = mod_sampler.SampleFormat; const mod_sineosc = @import("zang/mod_sineosc.zig"); pub const SineOsc = mod_sineosc.SineOsc; const mod_trisawosc = @import("zang/mod_trisawosc.zig"); pub const TriSawOsc = mod_trisawosc.TriSawOsc;
src/zang.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const stdout = std.io.getStdOut().writer(); const stdin = std.io.getStdIn().reader(); const dprint = std.debug.print; pub const Brain = struct { allocator: *Allocator, mem: []u8, dp: usize = 0, // data_pointer // code: []const u8, ip: usize = 0, // instruction pointer input: u8 = 0, output: u8 = 0, const Self = @This(); pub const defaultMemorySize = 30000; pub fn init(allocator: *Allocator, mem_size: usize) !Self { const mem = try allocator.alloc(u8, mem_size); var self = Self{ .allocator = allocator, .mem = mem, // .code = &[_]u8{0}, }; self.clearMemory(); return self; } pub fn initDefault(allocator: *Allocator) !Self { return try init(allocator, defaultMemorySize); } pub fn deinit(self: Self) void { self.allocator.free(self.mem); } pub fn reset(self: *Self) void { self.clearMemory(); // self.resetCode(); self.dp = 0; self.ip = 0; self.input = 0; self.output = 0; } pub fn clearMemory(self: *Self) void { for (self.mem) |*m| { m.* = 0; } } pub const BrainError = error{ DataPointerOverflow, DataPointerUnderflow, DataPointerOutOfBounds, InstructionPointerOutOfBounds, LeftBracketUnmatched, RightBracketUnmatched, InputFailed, OutputFailed, }; pub fn interpret(self: *Self, code: []const u8, n: usize, debug: bool) BrainError!usize { const res = self.run(code, n, debug) catch |err| self.errorHandler(code, err); return res; } pub fn run(self: *Self, code: []const u8, n: usize, debug: bool) BrainError!usize { if (self.ip < 0 or self.ip >= code.len) { return BrainError.InstructionPointerOutOfBounds; } if (self.dp < 0 or self.dp >= self.mem.len) { return BrainError.DataPointerOutOfBounds; } var i: usize = 0; const cond = (n == 0); // 0 means loop forever if (debug) { self.printState(code); while (cond or i < n) : (i += 1) { const offset = try self.execute(code); self.ip = @intCast(usize, @intCast(isize, self.ip) + offset); self.printState(code); if (self.ip == code.len) break; } } else { while (cond or i < n) : (i += 1) { const offset = try self.execute(code); self.ip = @intCast(usize, @intCast(isize, self.ip) + offset); if (self.ip == code.len) break; } } return i; } fn execute(self: *Self, code: []const u8) BrainError!isize { var offset: isize = 1; switch (code[self.ip]) { '>' => { if (self.dp == self.mem.len - 1) return BrainError.DataPointerOverflow; self.dp += 1; }, '<' => { if (self.dp == 0) return BrainError.DataPointerUnderflow; self.dp -= 1; }, '+' => { self.mem[self.dp] +%= 1; }, '-' => { self.mem[self.dp] -%= 1; }, '[' => { // If value of current cell is zero, jump to matching square bracket if (self.mem[self.dp] == 0) { var depth: usize = 1; var ip: usize = self.ip; while (depth != 0) : (offset += 1) { if (ip == code.len - 1) return BrainError.LeftBracketUnmatched; ip += 1; switch (code[ip]) { '[' => depth += 1, ']' => depth -= 1, else => {}, } } } }, ']' => { // If value of current cell is not zero, loop back to matching square bracket if (self.mem[self.dp] != 0) { var depth: usize = 1; var ip: usize = self.ip; while (depth != 0) : (offset -= 1) { if (ip == 0) return BrainError.RightBracketUnmatched; ip -= 1; switch (code[ip]) { '[' => depth -= 1, ']' => depth += 1, else => {}, } } } }, ',' => { // TODO: How to read without 'enter'? const byte = stdin.readByte() catch return BrainError.InputFailed; self.mem[self.dp] = byte; }, '.' => { stdout.print("{c}", .{self.mem[self.dp]}) catch return BrainError.OutputFailed; }, else => {}, // Ignore other characters } return offset; } fn errorHandler(self: Self, code: []const u8, err: BrainError) BrainError { dprint("Error [{s}] (code[{d}]: {c}, mem[{d}]: {x:0>2}, in: {c}, out: {c})", .{ err, self.ip, code[self.ip], self.dp, self.mem[self.dp], self.input, self.output, }); return err; } pub fn printState(self: Self, code: []const u8) void { comptime const radius = 16; dprint("\n[\n", .{}); dprint(" code: ", .{}); var i = if (self.ip < radius) 0 else self.ip - radius; while (i < self.ip + radius) : (i += 1) { if (i < 0) { i = -1; } else if (i > code.len) { break; } else if (i == self.ip) { dprint("({c})", .{code[i]}); } else { dprint("{c}", .{code[i]}); } } dprint("\n", .{}); dprint(" instruction pointer: {d}\n", .{self.ip}); dprint(" memory: ", .{}); var d = if (self.dp < radius) 0 else self.dp - radius; while (d < self.dp + radius) : (d += 1) { if (d < 0) { d = -1; } else if (d > self.mem.len) { break; } else if (d == self.dp) { dprint("({x:0>2})", .{self.mem[d]}); } else { dprint("[{x:0>2}]", .{self.mem[d]}); } } dprint("\n", .{}); dprint(" data pointer: {d}\n", .{self.dp}); dprint(" input: '{c}'\n", .{self.input}); dprint(" output: '{c}'\n", .{self.output}); dprint("]\n", .{}); } }; // Optimizes the code `source` by removing all non-brainfuck characters. // Stores the resulting array in `buffer`. // pub fn brainCodeOptimize(buffer: []u8, source: []const u8) usize { // const slice = if (source.len > self.code.len) source[0..self.code.len] else source; // var i: usize = 0; // for (source) |char| { // switch (char) { // '>', '<', '+', '-', '[', ']', ',', '.' => { // self.code[i] = char; // i += 1; // }, // else => {}, // } // } // return i; // }
src/brain.zig
const Uri = @This(); /// Scheme component of an URI, such as 'https' scheme: ?[]const u8, /// The username of the userinfo component within an URI username: ?[]const u8, /// The password of the userinfo component. /// NOTE: This subcomponent is deprecated and will not be shown /// in the formatter, consider omitting the password. password: ?[]const u8, /// Host component within an URI, such as https://<host> host: ?[]const u8, /// Parsed port comonent of an URI, such as https://host:<port> port: ?u16, /// The path component of an URI: https://<host><path> /// Note: It's possible for the path to be empty. path: []const u8, /// Query component of the URI such as https://<host>?<query> query: ?[]const u8, /// Fragment identifier component, which allows for indirect identification /// of a secondary resource. fragment: ?[]const u8, pub const empty: Uri = .{ .scheme = null, .username = null, .password = null, .host = null, .port = null, .path = &.{}, .query = null, .fragment = null, }; /// Builds query parameters from url's `raw_query` /// Memory is owned by caller /// Each key and value must be freed individually, calling `deinit` on the /// result of this, will do exactly that. pub fn queryParameters(self: Uri, gpa: std.mem.Allocator) DecodeError!KeyValueMap { return decodeQueryString(gpa, self.query orelse return KeyValueMap{ .map = .{} }); } /// Format function according to std's format signature. /// This will format the URI as an URL. /// NOTE: This will *NOT* print out the password component. pub fn format(self: Uri, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = options; _ = fmt; if (self.scheme) |scheme| { try writer.writeAll(scheme); try writer.writeAll("://"); if (self.username) |name| { try writer.writeAll(name); try writer.writeByte('@'); } if (self.host) |host| { try writer.writeAll(host); } if (self.port) |port| { try writer.print(":{d}", .{port}); } } try writer.writeAll(self.path); if (self.query) |query| { try writer.writeByte('?'); try writer.writeAll(query); } if (self.fragment) |fragment| { try writer.writeByte('#'); try writer.writeAll(fragment); } } const std = @import("std"); /// When attempting to parse a buffer into URI components, /// the following errors may occur. pub const ParseError = error{ /// The URI contains a scheme, but is missing a host MissingHost, /// The port was included but could not be parsed, /// or exceeds 65535. InvalidPort, /// Expected a specific character, but instead found a different one InvalidCharacter, }; /// Possible errors when decoding const DecodeError = error{ OutOfMemory, InvalidCharacter }; /// Parses the given payload into URI components. /// All components will be validated against invalid characters pub fn parse(buffer: []const u8) ParseError!Uri { var uri = Uri.empty; if (buffer.len == 0) return uri; var position: usize = 0; if (buffer[0] == '/') { try parsePath(&uri, buffer, true); } else { try parseSchema(&uri, buffer); position += uri.scheme.?.len; try consumePart("://", buffer[position..]); position += 3; position += try parseAuthority(&uri, buffer[position..]); if (position == buffer.len) return uri; if (buffer[position] == '/') { try parsePath(&uri, buffer[position..], false); } else uri.path = ""; } position += uri.path.len; if (position == buffer.len) return uri; if (buffer[position] == '?') { try parseQuery(&uri, buffer[position..]); position += uri.query.?.len + 1; } if (position == buffer.len) return uri; std.debug.assert(buffer[position] == '#'); try parseFragment(&uri, buffer[position..]); return uri; } /// Wrapping map over a map of keys and values /// that provides an easy way to free all its memory. pub const KeyValueMap = struct { /// inner map map: MapType, const MapType = std.StringHashMapUnmanaged([]const u8); /// Frees all memory owned by this `KeyValueMap` pub fn deinit(self: *KeyValueMap, gpa: std.mem.Allocator) void { var it = self.map.iterator(); while (it.next()) |pair| { gpa.free(pair.key_ptr.*); gpa.free(pair.value_ptr.*); } self.map.deinit(gpa); } /// Wrapping method over inner `map`'s `get()` function for easy access pub fn get(self: KeyValueMap, key: []const u8) ?[]const u8 { return self.map.get(key); } /// Wrapping method over inner map's `iterator()` function for easy access pub fn iterator(self: KeyValueMap) MapType.Iterator { return self.map.iterator(); } }; /// Decodes a query string into key-value pairs. This will also /// url-decode and replace %<hex> with its ascii value. /// /// Memory is owned by the caller and as each key and value are allocated due to decoding, /// must be freed individually. Calling `deinit` on the result, will do this. pub fn decodeQueryString(gpa: std.mem.Allocator, data: []const u8) DecodeError!KeyValueMap { var queries = KeyValueMap{ .map = KeyValueMap.MapType{} }; errdefer queries.deinit(gpa); var query = data; if (std.mem.startsWith(u8, query, "?")) { query = query[1..]; } while (query.len > 0) { var key = query; if (std.mem.indexOfScalar(u8, key, '&')) |index| { query = key[index + 1 ..]; key = key[0..index]; } else { query = ""; } if (key.len == 0) continue; var value: []const u8 = undefined; if (std.mem.indexOfScalar(u8, key, '=')) |index| { value = key[index + 1 ..]; key = key[0..index]; } key = try decode(gpa, key); errdefer gpa.free(key); value = try decode(gpa, value); errdefer gpa.free(value); try queries.map.put(gpa, key, value); } return queries; } /// Decodes the given input `value` by decoding the %hex number into ascii /// memory is owned by caller pub fn decode(allocator: std.mem.Allocator, value: []const u8) DecodeError![]const u8 { var perc_counter: usize = 0; var has_plus: bool = false; // find % and + symbols to determine buffer size var i: usize = 0; while (i < value.len) : (i += 1) { switch (value[i]) { '%' => { perc_counter += 1; if (i + 2 > value.len or !std.ascii.isAlNum(value[i + 1]) or !std.ascii.isAlNum(value[i + 2])) { return error.InvalidCharacter; } i += 2; }, '+' => { has_plus = true; }, else => {}, } } // replace url encoded string var buffer = try std.ArrayList(u8).initCapacity(allocator, value.len - 2 * perc_counter); defer buffer.deinit(); // No decoding required, so copy into allocated buffer so the result // can be freed consistantly. if (perc_counter == 0 and !has_plus) { buffer.appendSliceAssumeCapacity(value); return buffer.toOwnedSlice(); } i = 0; while (i < value.len) : (i += 1) { switch (value[i]) { '%' => { const a = try std.fmt.charToDigit(value[i + 1], 16); const b = try std.fmt.charToDigit(value[i + 2], 16); buffer.appendAssumeCapacity(a << 4 | b); i += 2; }, '+' => buffer.appendAssumeCapacity(' '), else => buffer.appendAssumeCapacity(value[i]), } } return buffer.toOwnedSlice(); } /// Sanitizes the given `path` by removing '..' etc. /// This returns a slice from a static buffer and therefore requires no allocations pub fn resolvePath(path: []const u8, buffer: []u8) []const u8 { if (path.len == 0) { buffer[0] = '.'; return buffer[0..1][0..]; } const rooted = path[0] == '/'; const len = path.len; std.mem.copy(u8, buffer, path); var out = BufferUtil.init(buffer, path); var i: usize = 0; var dot: usize = 0; if (rooted) { out.append('/'); i = 1; dot = 1; } while (i < len) { if (path[i] == '/') { // empty path element i += 1; continue; } if (path[i] == '.' and (i + 1 == len or path[i + 1] == '/')) { // . element i += 1; continue; } if (path[i] == '.' and path[i + 1] == '.' and (i + 2 == len or path[i + 2] == '/')) { // .. element, remove '..' bits till last '/' i += 2; if (out.index > dot) { out.index -= 1; while (out.index > dot and out.char() != '/') : (out.index -= 1) {} continue; } if (!rooted) { if (out.index > 0) out.append('/'); out.append('.'); out.append('.'); dot = out.index; continue; } } if (rooted and out.index != 1 or !rooted and out.index != 0) out.append('/'); while (i < len and path[i] != '/') : (i += 1) { out.append(path[i]); } } if (out.index == 0) { buffer[0] = '.'; return buffer[0..1][0..]; } return out.result(); } const BufferUtil = struct { buffer: []u8, index: usize, path: []const u8, fn init(buffer: []u8, path: []const u8) BufferUtil { return .{ .buffer = buffer, .index = 0, .path = path }; } fn append(self: *BufferUtil, c: u8) void { std.debug.assert(self.index < self.buffer.len); if (self.index < self.path.len and self.path[self.index] == c) { self.index += 1; return; } self.buffer[self.index] = c; self.index += 1; } fn char(self: BufferUtil) u8 { return self.buffer[self.index]; } fn result(self: BufferUtil) []const u8 { return self.buffer[0..self.index][0..]; } }; /// From a given buffer, attempts to parse the scheme fn parseSchema(uri: *Uri, buffer: []const u8) error{InvalidCharacter}!void { if (!std.ascii.isAlpha(buffer[0])) return error.InvalidCharacter; for (buffer[1..]) |char, index| { switch (char) { 'a'...'z', 'A'...'Z', '0'...'9', '+', '-', '.' => {}, else => { uri.scheme = buffer[0 .. index + 1]; return; }, } } uri.scheme = buffer; return; } /// Parses the authority and its subcomponents of an URI pub fn parseAuthority(uri: *Uri, buffer: []const u8) ParseError!usize { if (buffer.len == 0) return 0; // get the end of the authority component and also // parse each character to ensure it's a valid character. const end = for (buffer) |char, index| { if (char == '/' or char == '#' or char == '?') break index; } else buffer.len; if (end == 0) return error.MissingHost; const authority = buffer[0..end]; // maybe parse the userinfo subcomponent, in which case this block will // return the remaining slice consisting of the host + port const remaining = if (std.mem.indexOfScalar(u8, authority, '@')) |user_index| blk: { const user_info = authority[0..user_index]; // verify userinfo characters var colon_index: usize = 0; for (user_info) |char, index| { if (char == ':') { uri.username = user_info[0..index]; colon_index = index; continue; } if (!isRegName(char)) return error.InvalidCharacter; } if (colon_index != 0 and colon_index < user_info.len - 1) { uri.password = user_info[colon_index..][1..]; } else if (colon_index == 0) { uri.username = user_info; } break :blk authority[user_index..][1..]; } else authority; if (remaining.len == 0) return error.MissingHost; switch (remaining[0]) { '[' => try parseIpv6(uri, remaining[1..]), else => try parseHost(uri, remaining[0..]), } return end; } /// Parses the host and port where host represents 'reg-name' from the URI spec. /// This will also validate both host and port contain valid characters. fn parseHost(uri: *Uri, buffer: []const u8) !void { const host_end = if (std.mem.lastIndexOfScalar(u8, buffer, ':')) |colon_pos| blk: { const end_port = for (buffer[colon_pos + 1 ..]) |char, index| { if (!std.ascii.isDigit(char)) break index; } else buffer.len - (colon_pos + 1); uri.port = std.fmt.parseInt(u16, buffer[colon_pos + 1 ..][0..end_port], 10) catch return error.InvalidPort; break :blk colon_pos; } else buffer.len; // validate host characters for (buffer[0..host_end]) |char| { if (!isRegName(char) and !isIpv4(char)) return error.InvalidCharacter; } uri.host = buffer[0..host_end]; } /// Parses the host as an ipv6 address and when found, also parses /// and validates the port. fn parseIpv6(uri: *Uri, buffer: []const u8) !void { const end = std.mem.indexOfScalar(u8, buffer, ']') orelse return error.InvalidCharacter; if (end > 39) return error.InvalidCharacter; // IPv6 addresses consist of max 8 16-bit pieces. uri.host = buffer[0..end]; for (uri.host.?) |char| { if (!isLs32(char)) return error.InvalidCharacter; } if (std.mem.indexOfScalarPos(u8, buffer, end, ':')) |colon_pos| { const end_port = for (buffer[colon_pos + 1 ..]) |char, index| { if (!std.ascii.isDigit(char)) break index; } else buffer.len - (colon_pos + 1); uri.port = std.fmt.parseInt(u16, buffer[colon_pos + 1 ..][0..end_port], 10) catch return error.InvalidPort; } } /// Parses the path /// When `is_no_scheme` is true, it will ensure the first segment is non-zero without any colon fn parsePath(uri: *Uri, buffer: []const u8, is_no_scheme: bool) ParseError!void { if (is_no_scheme) { if (buffer.len == 0) return error.InvalidCharacter; if (buffer.len == 1) { if (buffer[0] != '/') return error.InvalidCharacter; uri.path = "/"; return; } if (buffer[1] == ':') return error.InvalidCharacter; } for (buffer) |char, index| { if (char == '?' or char == '#') { uri.path = buffer[0..index]; return; } if (!isPChar(char) and char != '/') { return error.InvalidCharacter; } } uri.path = buffer; } /// Parses the query component of an URI fn parseQuery(uri: *Uri, buffer: []const u8) ParseError!void { std.debug.assert(buffer.len > 0); std.debug.assert(buffer[0] == '?'); for (buffer[1..]) |char, index| { if (char == '#') { uri.query = buffer[0..index]; return; } if (!isPChar(char) and char != '/' and char != '?') { return error.InvalidCharacter; } } uri.query = buffer[1..]; } /// Parses the fragment component of an URI fn parseFragment(uri: *Uri, buffer: []const u8) ParseError!void { std.debug.assert(buffer.len > 0); std.debug.assert(buffer[0] == '#'); for (buffer[1..]) |char| { if (!isPChar(char) and char != '/' and char != '?') { return error.InvalidCharacter; } } uri.fragment = buffer[1..]; } fn consumePart(part: []const u8, buffer: []const u8) error{InvalidCharacter}!void { if (!std.mem.startsWith(u8, buffer, part)) return error.InvalidCharacter; } /// Returns true when Reg-name /// *( unreserved / %<HEX> / sub-delims ) fn isRegName(char: u8) bool { return isUnreserved(char) or char == '%' or isSubDelim(char); } /// Checks if unreserved character /// ALPHA / DIGIT/ [ "-" / "." / "_" / "~" ] fn isUnreserved(char: u8) bool { return std.ascii.isAlNum(char) or switch (char) { '-', '.', '_', '~' => true, else => false, }; } /// Returns true when character is a sub-delim character /// !, $, &, \, (, ), *, *, +, ',', = fn isSubDelim(char: u8) bool { return switch (char) { '!', '$', '&', '\'', '(', ')', '*', '+', ',', '=', => true, else => false, }; } /// Returns true when given char is pchar /// unreserved / pct-encoded / sub-delims / ":" / "@" fn isPChar(char: u8) bool { return switch (char) { '%', ':', '@' => true, else => isUnreserved(char) or isSubDelim(char), }; } fn isLs32(char: u8) bool { return std.ascii.isAlNum(char) or char == ':' or char == '.'; } fn isIpv4(char: u8) bool { return std.ascii.isDigit(char) or char == '.'; } test "Format" { const uri: Uri = .{ .scheme = "https", .username = "user", .password = "<PASSWORD>", .host = "example.com", .port = 8080, .path = "/index.html", .query = "hello=world", .fragment = "header1", }; try std.testing.expectFmt( "https://[email protected]:8080/index.html?hello=world#header1", "{}", .{uri}, ); } test "Scheme" { const cases = .{ .{ "https://", "https" }, .{ "gemini://", "gemini" }, .{ "git://", "git" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.scheme.?); } const error_cases = .{ "htt?s", "gem||", "ha$", }; inline for (error_cases) |case| { try std.testing.expectError(ParseError.InvalidCharacter, parse(case)); } } test "Host" { const cases = .{ .{ "https://exa2ple", "exa2ple" }, .{ "gemini://example.com", "example.com" }, .{ "git://sub.domain.com", "sub.domain.com" }, .{ "https://[2001:db8:0:0:0:0:2:1]", "2001:db8:0:0:0:0:2:1" }, .{ "https://[::ffff:192.168.100.228]", "::ffff:192.168.100.228" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.host.?); } const error_cases = .{ "https://exam|", "gemini://exa\"", "git://sub.example.[om", "https://[::ffff:192.$168.100.228]", }; inline for (error_cases) |case| { try std.testing.expectError(ParseError.InvalidCharacter, parse(case)); } } test "Userinfo" { const cases = .{ .{ "https://user:[email protected]", "user", "password", "host.com" }, .{ "https://[email protected]", "user", "", "host.com" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.username.?); if (uri.password) |password| { try std.testing.expectEqualStrings(case[2], password); } else try std.testing.expectEqualStrings(case[2], ""); try std.testing.expectEqualStrings(case[3], uri.host.?); } const error_cases = .{ "https://us|[email protected]", "https://user@[email protected]", }; inline for (error_cases) |case| { try std.testing.expectError(ParseError.InvalidCharacter, parse(case)); } } test "Path" { const cases = .{ .{ "gemini://example.com:100/hello", "/hello" }, .{ "gemini://example.com/hello/world", "/hello/world" }, .{ "gemini://example.com/../hello", "/../hello" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.path); } } test "Query" { const cases = .{ .{ "gemini://example.com:100/hello?", "" }, .{ "gemini://example.com/?cool=true", "cool=true" }, .{ "gemini://example.com?hello=world", "hello=world" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.query.?); } } test "Fragment" { const cases = .{ .{ "gemini://example.com:100/hello?#hi", "hi" }, .{ "gemini://example.com/#hello", "hello" }, .{ "gemini://example.com#hello-world", "hello-world" }, }; inline for (cases) |case| { const uri = try parse(case[0]); try std.testing.expectEqualStrings(case[1], uri.fragment.?); } } test "Resolve paths" { const cases = .{ // Already clean .{ .input = "", .expected = "." }, .{ .input = "abc", .expected = "abc" }, .{ .input = "abc/def", .expected = "abc/def" }, .{ .input = "a/b/c", .expected = "a/b/c" }, .{ .input = ".", .expected = "." }, .{ .input = "..", .expected = ".." }, .{ .input = "../..", .expected = "../.." }, .{ .input = "../../abc", .expected = "../../abc" }, .{ .input = "/abc", .expected = "/abc" }, .{ .input = "/", .expected = "/" }, // Remove trailing slash .{ .input = "abc/", .expected = "abc" }, .{ .input = "abc/def/", .expected = "abc/def" }, .{ .input = "a/b/c/", .expected = "a/b/c" }, .{ .input = "./", .expected = "." }, .{ .input = "../", .expected = ".." }, .{ .input = "../../", .expected = "../.." }, .{ .input = "/abc/", .expected = "/abc" }, // Remove doubled slash .{ .input = "abc//def//ghi", .expected = "abc/def/ghi" }, .{ .input = "//abc", .expected = "/abc" }, .{ .input = "///abc", .expected = "/abc" }, .{ .input = "//abc//", .expected = "/abc" }, .{ .input = "abc//", .expected = "abc" }, // Remove . elements .{ .input = "abc/./def", .expected = "abc/def" }, .{ .input = "/./abc/def", .expected = "/abc/def" }, .{ .input = "abc/.", .expected = "abc" }, // Remove .. elements .{ .input = "abc/def/ghi/../jkl", .expected = "abc/def/jkl" }, .{ .input = "abc/def/../ghi/../jkl", .expected = "abc/jkl" }, .{ .input = "abc/def/..", .expected = "abc" }, .{ .input = "abc/def/../..", .expected = "." }, .{ .input = "/abc/def/../..", .expected = "/" }, .{ .input = "abc/def/../../..", .expected = ".." }, .{ .input = "/abc/def/../../..", .expected = "/" }, .{ .input = "abc/def/../../../ghi/jkl/../../../mno", .expected = "../../mno" }, // Combinations .{ .input = "abc/./../def", .expected = "def" }, .{ .input = "abc//./../def", .expected = "def" }, .{ .input = "abc/../../././../def", .expected = "../../def" }, }; inline for (cases) |case| { var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; try std.testing.expectEqualStrings(case.expected, resolvePath(case.input, &buf)); } } test "decode url encoded data" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); try std.testing.expectEqualStrings("hello, world", try decode(arena.allocator(), "hello%2C+world")); try std.testing.expectEqualStrings("<EMAIL>", try decode(arena.allocator(), "contact%40example.com")); } test "Retrieve query parameters" { const path = "/example?name=value"; const uri = try parse(path); var query_params = try uri.queryParameters(std.testing.allocator); defer query_params.deinit(std.testing.allocator); try std.testing.expect(query_params.map.contains("name")); try std.testing.expectEqualStrings("value", query_params.get("name") orelse " "); }
src/Uri.zig
const std = @import("std"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const column_size = 31; pub fn main() !void { defer _ = gpa.deinit(); const inputData = try std.fs.cwd().readFileAlloc(alloc, "input", std.math.maxInt(u64)); defer alloc.free(inputData); var map_data = try Map.initCapacity(alloc, 1000); defer deinit_map(map_data); var it = std.mem.split(inputData, "\n"); while (it.next()) |line| { var row = try std.ArrayList(u8).initCapacity(alloc, line.len); // std.debug.print("Line: {}\n", .{line}); for (line) |char| { try row.append(char); } try map_data.append(row); } // print_map(map_data); const p1 = part1(map_data); const p2 = part2(map_data); std.debug.print("{}\n", .{p1}); std.debug.print("{}\n", .{p2}); } const Row = std.ArrayList(u8); const Map = std.ArrayList(Row); fn is_occupied(map: Map, row: usize, col: usize) isize { if ((row < 0 or row >= map.items.len) or (col < 0 or col >= map.items[0].items.len)) { return 0; } return if (map.items[row].items[col] == '#') 1 else 0; } fn p2_is_occupied(map: Map, row: isize, row_dir: isize, col: isize, col_dir: isize) isize { if ((row < 0 or row >= map.items.len) or (col < 0 or col >= map.items[0].items.len)) { return 0; } const urow = @intCast(usize, row); const ucol = @intCast(usize, col); return if (map.items[urow].items[ucol] == '#') 1 else if (map.items[urow].items[ucol] == 'L') 0 else p2_is_occupied(map, row + row_dir, row_dir, col + col_dir, col_dir); } fn neighbors_occupied(map: Map, row: usize, col: usize) isize { return is_occupied(map, row -% 1, col -% 1) + is_occupied(map, row -% 1, col) + is_occupied(map, row -% 1, col +% 1) + is_occupied(map, row, col -% 1) + is_occupied(map, row, col +% 1) + is_occupied(map, row +% 1, col -% 1) + is_occupied(map, row +% 1, col) + is_occupied(map, row +% 1, col +% 1); } fn p2_neighbors_occupied(map: Map, row: usize, col: usize) isize { const irow = @intCast(isize, row); const icol = @intCast(isize, col); return p2_is_occupied(map, irow - 1, -1, icol - 1, -1) + p2_is_occupied(map, irow - 1, -1, icol, 0) + p2_is_occupied(map, irow - 1, -1, icol + 1, 1) + p2_is_occupied(map, irow, 0, icol - 1, -1) + p2_is_occupied(map, irow, 0, icol + 1, 1) + p2_is_occupied(map, irow + 1, 1, icol - 1, -1) + p2_is_occupied(map, irow + 1, 1, icol, 0) + p2_is_occupied(map, irow + 1, 1, icol + 1, 1); } fn clone_map(map: Map) !Map { var new_map = Map.init(map.allocator); for (map.items) |row| { var new_row = Row.init(new_map.allocator); for (row.items) |item| { try new_row.append(item); } try new_map.append(new_row); } return new_map; } fn deinit_map(map: Map) void { for (map.items) |row| { row.deinit(); } map.deinit(); } // TODO? just keep a dirty flag in function rather than check the map fn are_same(map: Map, m2: Map) bool { for (map.items) |row, r| { for (row.items) |item, c| { if (item != m2.items[r].items[c]) { return false; } } } return true; } fn print_map(map: Map) void { for (map.items) |row| { for (row.items) |el| { std.debug.print("{c}", .{el}); } std.debug.print("\n", .{}); } } fn part1(map: Map) !isize { var updated_map = try clone_map(map); defer deinit_map(updated_map); while (true) { // print_map(updated_map); var arena = std.heap.ArenaAllocator.init(map.allocator); defer arena.deinit(); var new_map = Map.init(&arena.allocator); for (updated_map.items) |r| { var new_row = Row.init(&arena.allocator); for (r.items) |c| { try new_row.append(@as(u8, '?')); } try new_map.append(new_row); } for (updated_map.items) |row, r| { for (row.items) |item, c| { const num_occupied_neighbors = neighbors_occupied(updated_map, r, c); switch (item) { 'L' => if (num_occupied_neighbors == 0) { new_map.items[r].items[c] = '#'; } else { new_map.items[r].items[c] = item; }, '#' => if (num_occupied_neighbors >= 4) { new_map.items[r].items[c] = 'L'; } else { new_map.items[r].items[c] = item; }, else => { new_map.items[r].items[c] = item; }, } // std.debug.print("r={}, c={}, value={}, neighbors={}\n", .{r, c, item, num_occupied_neighbors}); } } if (are_same(updated_map, new_map)) { break; } for (updated_map.items) |*row, r| { for (row.items) |*item, c| { item.* = new_map.items[r].items[c]; } } } var count: isize = 0; for (updated_map.items) |row| { for (row.items) |el| { if (el == '#') { count += 1; } } } return count; } fn part2(map: Map) !isize { var updated_map = try clone_map(map); defer deinit_map(updated_map); while (true) { // print_map(updated_map); var arena = std.heap.ArenaAllocator.init(map.allocator); defer arena.deinit(); var new_map = Map.init(&arena.allocator); for (updated_map.items) |r| { var new_row = Row.init(&arena.allocator); for (r.items) |c| { try new_row.append(@as(u8, '?')); } try new_map.append(new_row); } for (updated_map.items) |row, r| { for (row.items) |item, c| { const num_occupied_neighbors = p2_neighbors_occupied(updated_map, r, c); switch (item) { 'L' => if (num_occupied_neighbors == 0) { new_map.items[r].items[c] = '#'; } else { new_map.items[r].items[c] = item; }, '#' => if (num_occupied_neighbors >= 5) { new_map.items[r].items[c] = 'L'; } else { new_map.items[r].items[c] = item; }, else => { new_map.items[r].items[c] = item; }, } // std.debug.print("r={}, c={}, value={}, neighbors={}\n", .{r, c, item, num_occupied_neighbors}); } } if (are_same(updated_map, new_map)) { break; } for (updated_map.items) |*row, r| { for (row.items) |*item, c| { item.* = new_map.items[r].items[c]; } } } var count: isize = 0; for (updated_map.items) |row| { for (row.items) |el| { if (el == '#') { count += 1; } } } return count; }
Day11/day11.zig
const std = @import("std"); const os = std.os; const mem = std.mem; const hashmap_type = std.hash_map.AutoHashMap(i32, []u8); comptime { if (!os.linux.is_the_target) { @compileError("Unsupported OS"); } } const std_inotify_event = extern struct { wd: i32, mask: u32, cookie: u32, len: u32, nameaddr: ?[*]u8, }; pub const inotify_event = struct { wd: i32, mask: u32, cookie: u32, len: u32, name: ?[]u8, }; pub const expanded_inotify_event = struct { event: *inotify_event, watched_name: []u8, }; // Buffer must be evenly divisble by the alignment of inotify_event // for when we @alignCast a buffer ptr later on. fn find_buffer_length() comptime_int { var i_buffer_length: comptime_int = os.PATH_MAX + @sizeOf(std_inotify_event) + 1; while (i_buffer_length % @alignOf(std_inotify_event) != 0) { i_buffer_length += 1; } return i_buffer_length; } pub const buffer_length = find_buffer_length(); pub const inotify = struct { const Self = @This(); event_buffer: [buffer_length]u8 = undefined, event: inotify_event = undefined, expanded_event: expanded_inotify_event = undefined, inotify_fd: i32, hashmap: hashmap_type, pub fn init(allocator: *mem.Allocator) !inotify { return inotify{ .inotify_fd = try os.inotify_init1(0), .hashmap = hashmap_type.init(allocator), }; } pub fn deinit(self: *Self) void { self.hashmap.deinit(); // TODO //self.remove_watch(); for each watched item } pub fn add_watch(self: *Self, filename: []u8, flags: u32) !void { const watchid: i32 = try os.inotify_add_watch(self.inotify_fd, filename, flags); _ = try self.hashmap.put(watchid, filename); } pub fn remove_watch(self: *Self, watch_descriptor: i32) ?hashmap_type.KV { os.inotify_rm_watch(self.inotify_fd, watch_descriptor); return self.hashmap.remove(watch_descriptor); } pub fn next_event(self: *Self) *expanded_inotify_event { const read_result = os.linux.read(self.inotify_fd, &self.event_buffer, self.event_buffer.len); read_event(&self.event_buffer, &self.event); self.expanded_event.event = &self.event; self.expanded_event.watched_name = self.hashmap.getValue(self.event.wd) orelse unreachable; return &self.expanded_event; } }; // ***************************************************************** var event_temp: *std_inotify_event = undefined; pub fn read_event(bufferptr: [*]u8, event: *inotify_event) void { var ptr = @alignCast(@alignOf(std_inotify_event), bufferptr); event_temp = @ptrCast(*std_inotify_event, ptr); var name = @ptrCast([*]u8, &event_temp.nameaddr); const namelen = mem.len(u8, name); event.wd = event_temp.wd; event.mask = event_temp.mask; event.cookie = event_temp.cookie; event.len = event_temp.len; //event.name = name[0..namelen]; event.name = if (event.len != 0) name[0..namelen] else null; }
inotify_bridge.zig
pub const Timestamp = struct { unix_ms: i64 = 0, year: u16 = 0, month: u8 = 0, day: u8 = 0, hours: u8 = 0, minutes: u8 = 0, seconds: u8 = 0, month_name: []const u8 = undefined, day_name: []const u8 = undefined, month_name_array: []const []const u8 = &[_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }, day_name_array: []const []const u8 = &[_][]const u8{ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }, pub fn now() !Timestamp { var ts = Timestamp{}; const ms = std.time.milliTimestamp(); try initFromMs(&ts, ms); return ts; } pub fn milliseconds(ms: i64) !Timestamp { var ts = Timestamp{}; try initFromMs(&ts, ms); return ts; } pub fn isYearLeapYear(self: *Timestamp, year: i64) bool { if ((@mod(year, 400) == 0 or @mod(year, 100) != 0) and (@mod(year, 4) == 0)) { return true; } return false; } pub fn dayOfWeek(ts: *Timestamp) []const u8 { const t: [12]u8 = .{ 0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4 }; const d = ts.day; const m = ts.month; const y = if (m < 3) ts.year - 1 else ts.year; const i: u32 = (y + y / 4 - y / 100 + y / 400 + t[m - 1] + d) % 7; // std.debug.print("dayOfWeek: i={}\n", .{i}); return ts.day_name_array[i]; } fn initFromMs(ts: *Timestamp, ms: i64) !void { if (ms < 0) return error.BadValue; const base_days_per_month = [_]i64{ 31, // January 28, // February (29 days on leap year) 31, // March 30, // April 31, // May 30, // June 31, // July 31, // August 30, // September 31, // October 30, // November 31, // December }; // std.debug.print("\n", .{}); const days = @divFloor(ms, std.time.ms_per_day); // std.debug.print("days={}\n", .{days}); var year0 = @floatToInt(i64, @intToFloat(f32, days) / 365.25); // std.debug.print("year0={}\n", .{year0}); // var days_remaining = days - @floatToInt(i64, @intToFloat(f32, year0) * 365.25); // above formula doesn't work... brute force loop subtract days in each year var days_remaining = days; var y: i64 = 0; while (y < year0) : (y += 1) { if (ts.isYearLeapYear(1970 + y)) days_remaining -= 366 else days_remaining -= 365; } var month0: i64 = 0; for (base_days_per_month) |value, i| { // add one day to february if this year is a leap year const year = 1970 + year0; const days_per_month = if (i == 1 and ts.isYearLeapYear(year)) value + 1 else value; // std.debug.print("days_per_month[{}]={}\n", .{ i, days_per_month }); if (days_per_month > days_remaining) break; days_remaining -= days_per_month; month0 += 1; } // std.debug.print("month0={}\n", .{month0}); const day0: i64 = days_remaining; // std.debug.print("day0={}\n", .{day0}); const hours = @divFloor(ms - (days * std.time.ms_per_day), std.time.ms_per_hour); // std.debug.print("hours={}\n", .{hours}); const minutes = @divFloor(ms - (days * std.time.ms_per_day) - (hours * std.time.ms_per_hour), std.time.ms_per_min); // std.debug.print("minutes={}\n", .{minutes}); const seconds = @divFloor(ms - (days * std.time.ms_per_day) - (hours * std.time.ms_per_hour) - (minutes * std.time.ms_per_min), std.time.ms_per_s); // std.debug.print("seconds={}\n", .{seconds}); ts.unix_ms = ms; ts.year = 1970 + @intCast(u16, year0); ts.month = @intCast(u8, month0) + 1; ts.day = @intCast(u8, day0) + 1; ts.hours = @intCast(u8, hours); ts.minutes = @intCast(u8, minutes); ts.seconds = @intCast(u8, seconds); ts.month_name = ts.month_name_array[@intCast(usize, month0)]; ts.day_name = ts.dayOfWeek(); } pub fn asctime(ts: *Timestamp, buffer: []u8) ![]u8 { return std.fmt.bufPrint(buffer, "{}, {d:0>2} {} {d:0>4} {d:0>2}:{d:0>2}:{d:0>2} GMT", .{ ts.day_name, ts.day, ts.month_name, ts.year, ts.hours, ts.minutes, ts.seconds, }); } }; test "leap year calculation" { const expect = std.testing.expect; var ts = try Timestamp.now(); expect(ts.isYearLeapYear(1900) == false); expect(ts.isYearLeapYear(1992) == true); expect(ts.isYearLeapYear(2000) == true); expect(ts.isYearLeapYear(2001) == false); expect(ts.isYearLeapYear(2019) == false); expect(ts.isYearLeapYear(2020) == true); expect(ts.isYearLeapYear(2021) == false); expect(ts.isYearLeapYear(2024) == true); expect(ts.isYearLeapYear(2100) == false); expect(ts.isYearLeapYear(2400) == true); } test "unixtimestamp 0 is 1970-01-01T00:00:00 UTC" { const expect = std.testing.expect; const ms: i64 = 0; var ts = try Timestamp.milliseconds(ms); expect(ts.year == 1970); expect(ts.month == 1); expect(ts.day == 1); expect(ts.hours == 0); expect(ts.minutes == 0); expect(ts.seconds == 0); var buffer: [32]u8 = undefined; const asctime: []u8 = try ts.asctime(buffer[0..]); std.debug.print("asctime={}\n", .{asctime}); expect(std.mem.eql(u8, asctime, "Thu, 01 Jan 1970 00:00:00 GMT")); } // test "unixtimestamp -2208988800 is 1900-01-01T00:00:00 (UTC)" { // const expect = std.testing.expect; // const ms: i64 = -2208988800 * std.time.ms_per_s; // var ts = Timestamp.milliseconds(ms); // expect(ts.year == 1900); // expect(ts.month == 1); // expect(ts.day == 1); // } // test "timestamp -3304460700 is 1865-04-14T22:15 (UTC)" { // // assassination of president <NAME> // const expect = std.testing.expect; // const ms: i64 = -3304460700 * std.time.ms_per_s; // var ts = Timestamp.milliseconds(ms); // expect(ts.year == 1865); // expect(ts.month == 4); // expect(ts.day == 14); // } test "unix time 1000000000 is 2001-09-09T01:46:40 UTC" { const expect = std.testing.expect; const ms: i64 = 1000000000 * std.time.ms_per_s; var ts = try Timestamp.milliseconds(ms); expect(ts.year == 2001); expect(ts.month == 9); expect(ts.day == 9); expect(ts.hours == 1); expect(ts.minutes == 46); expect(ts.seconds == 40); expect(std.mem.eql(u8, ts.day_name, "Sun")); var buffer: [32]u8 = undefined; const asctime: []u8 = try ts.asctime(buffer[0..]); std.debug.print("asctime={}\n", .{asctime}); expect(std.mem.eql(u8, asctime, "Sun, 09 Sep 2001 01:46:40 GMT")); } test "unix time 1234567890 is 2009-02-13T23:31:30 UTC" { const expect = std.testing.expect; const ms: i64 = 1234567890 * std.time.ms_per_s; var ts = try Timestamp.milliseconds(ms); expect(ts.year == 2009); expect(ts.month == 2); expect(ts.day == 13); expect(ts.hours == 23); expect(ts.minutes == 31); expect(ts.seconds == 30); expect(std.mem.eql(u8, ts.day_name, "Fri")); var buffer: [32]u8 = undefined; const asctime: []u8 = try ts.asctime(buffer[0..]); std.debug.print("asctime={}\n", .{asctime}); expect(std.mem.eql(u8, asctime, "Fri, 13 Feb 2009 23:31:30 GMT")); } test "unix time 1600000000 is 2020-09-13T12:26:40 UTC" { const expect = std.testing.expect; const ms: i64 = 1600000000 * std.time.ms_per_s; var ts = try Timestamp.milliseconds(ms); expect(ts.year == 2020); expect(ts.month == 9); expect(ts.day == 13); expect(ts.hours == 12); expect(ts.minutes == 26); expect(ts.seconds == 40); expect(std.mem.eql(u8, ts.day_name, "Sun")); var buffer: [32]u8 = undefined; const asctime: []u8 = try ts.asctime(buffer[0..]); std.debug.print("asctime={}\n", .{asctime}); expect(std.mem.eql(u8, asctime, "Sun, 13 Sep 2020 12:26:40 GMT")); } // imports const std = @import("std");
98_http_server/timestamp.zig
const std = @import("std"); const generate = @import("generator.zig").generate; const path = std.fs.path; const Builder = std.build.Builder; const Step = std.build.Step; /// build.zig integration for OpenXR binding generation. This step can be used to generate /// OpenXR bindings at compiletime from xr.xml, by providing the path to xr.xml and the output /// path relative to zig-cache. The final package can then be obtained by `package()`, the result /// of which can be added to the project using `std.build.Builder.addPackage`. pub const GenerateStep = struct { step: Step, builder: *Builder, /// The path to xr.xml spec_path: []const u8, /// The package representing the generated bindings. The generated bindings will be placed /// in `package.path`. When using this step, this member should be passed to /// `std.build.Builder.addPackage`, which causes the bindings to become available under the /// name `openxr`. package: std.build.Pkg, /// Initialize a OpenXR generation step, for `builder`. `spec_path` is the path to /// xr.xml, relative to the project root. The generated bindings will be placed at /// `out_path`, which is relative to the zig-cache directory. pub fn init(builder: *Builder, spec_path: []const u8, out_path: []const u8) *GenerateStep { const self = builder.allocator.create(GenerateStep) catch unreachable; const full_out_path = path.join(builder.allocator, &[_][]const u8{ builder.build_root, builder.cache_root, out_path, }) catch unreachable; self.* = .{ .step = Step.init(.Custom, "openxr-generate", builder.allocator, make), .builder = builder, .spec_path = spec_path, .package = .{ .name = "openxr", .path = full_out_path, .dependencies = null, }, }; return self; } /// Initialize a OpenXR generation step for `builder`, by extracting xr.xml from the LunarG installation /// root. Typically, the location of the LunarG SDK root can be retrieved by querying for the OPENXR_SDK /// environment variable, set by activating the environment setup script located in the SDK root. /// `builder` and `out_path` are used in the same manner as `init`. pub fn initFromSdk(builder: *Builder, sdk_path: []const u8, out_path: []const u8) *GenerateStep { const spec_path = std.fs.path.join( builder.allocator, &[_][]const u8{ sdk_path, "share/openxr/registry/xr.xml" }, ) catch unreachable; return init(builder, spec_path, out_path); } /// Internal build function. This reads `xr.xml`, and passes it to `generate`, which then generates /// the final bindings. The resulting generated bindings are not formatted, which is why an ArrayList /// writer is passed instead of a file writer. This is then formatted into standard formatting /// by parsing it and rendering with `std.zig.parse` and `std.zig.render` respectively. fn make(step: *Step) !void { const self = @fieldParentPtr(GenerateStep, "step", step); const cwd = std.fs.cwd(); var out_buffer = std.ArrayList(u8).init(self.builder.allocator); const spec = try cwd.readFileAlloc(self.builder.allocator, self.spec_path, std.math.maxInt(usize)); try generate(self.builder.allocator, spec, out_buffer.writer()); const tree = try std.zig.parse(self.builder.allocator, out_buffer.items); const dir = path.dirname(self.package.path).?; try cwd.makePath(dir); const output_file = cwd.createFile(self.package.path, .{}) catch unreachable; defer output_file.close(); _ = try std.zig.render(self.builder.allocator, output_file.writer(), tree); } };
generator/openxr/build_integration.zig
const std = @import("std"); const zben = @import("zben"); const uri = @import("uri"); const c = @import("c.zig"); const util = @import("util.zig"); const msg = @import("messages.zig"); const log = std.log.scoped(.torrent); const Allocator = std.mem.Allocator; const ConnectionList = std.ArrayList(*PeerConnection); const WorkQueue = std.fifo.LinearFifo(usize, .Dynamic); fn getTorrentContext(handle: anytype) *TorrentContext { return util.cast_from_cptr(*TorrentContext, handle.?.*.data); } export fn onConnectTrackerFwd(connection: ?*c.uv_connect_t, status: i32) void { const tc = getTorrentContext(connection.?.handle); defer tc.allocator.destroy(connection.?); if (status < 0) { log.warn("Error connecting to tracker - {}", .{c.uv_strerror(status)}); return; } tc.onConnectTracker(); } export fn onWriteAnnounceFwd(req: ?*c.uv_write_t, status: i32, buf: ?*c.uv_buf_t) void { std.debug.assert(buf != null); const tc = getTorrentContext(req.?.handle); tc.allocator.free(buf.?.base[0..buf.?.len]); } export fn onReadAnnounceFwd(handle: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { std.debug.assert(buf != null); const tc = getTorrentContext(handle); tc.onReadAnnounce(handle, nread, buf); } export fn tcAllocBuffer(handle: ?*c.uv_handle_t, suggested_size: usize, buf: ?*c.uv_buf_t) void { std.debug.assert(buf != null); std.debug.assert(handle != null); const tc = getTorrentContext(handle); var data = tc.tracker_read_stream.writableWithSize(suggested_size) catch { log.err("Error allocating memory for tracker download", .{}); buf.?.* = c.uv_buf_init(null, 0); return; }; buf.?.* = c.uv_buf_init(data.ptr, @intCast(u32, suggested_size)); } export fn http_ignore(p: ?*c.http_parser) callconv(.C) c_int { return 0; } export fn http_ignore_data(parser: ?*c.http_parser, data: [*c]const u8, len: usize) callconv(.C) c_int { return 0; } export fn http_tracker_parse_body(p: ?*c.http_parser, data: [*c]const u8, len: usize) callconv(.C) c_int { if (p == null) return 1; var as_sized = util.cast_from_cptr(?*c.http_parser_sized, p); const tc = getTorrentContext(as_sized); var parser = zben.Parser.initWithData(tc.allocator, data[0..len]); defer parser.deinit(); var tree = parser.parse() catch return 1; defer tree.deinit(); var peers_blob = switch (tree.root.Dictionary.get("peers") orelse return 1) { .String => |s| s, else => { log.err("Peers returned in non-compact form. TODO: Implement non-compact form", .{}); return 1; }, }; if (@mod(peers_blob.len, msg.COMPACT_PEER_LEN) != 0) return 1; var iter = PeerIter{ .data = peers_blob }; while (iter.next()) |peer| { tc.addPeer(peer); } return 0; } const CompletePiece = struct { index: usize, buffer: []u8, read_length: usize, }; /// Manages an torrent, both uploading and downloading /// as well as writing out to file. Contains all the context /// necessary for a given torrent. /// Note there is no concurrency here so each TorrentContext /// should be managed by at most one `loop` / thread pub const TorrentContext = struct { allocator: *Allocator, peer_id: []const u8, loop: *c.uv_loop_t, torrent: TorrentFile, // Peers we're actively established with connected_peers: ConnectionList, // Peers which we are not connected to inactive_peers: ConnectionList, completed_pieces: std.ArrayList(CompletePiece), to_write_piece: usize = 0, output_file_pipe: c.uv_pipe_t, output_filed: c.uv_file, work_queue: WorkQueue, have_bitfield: PeerConnection.Bitfield, tracker_connection: c.uv_tcp_t, timer: c.uv_timer_t, tracker_read_stream: std.fifo.LinearFifo(u8, .Dynamic), inflight_file_pieces: usize = 0, pub fn init(alloc: *Allocator, peer_id: []const u8) @This() { return .{ .allocator = alloc, .peer_id = peer_id, .loop = undefined, .torrent = undefined, .connected_peers = ConnectionList.init(alloc), .inactive_peers = ConnectionList.init(alloc), .completed_pieces = std.ArrayList(CompletePiece).init(alloc), .output_file_pipe = undefined, .output_filed = undefined, .work_queue = WorkQueue.init(alloc), .have_bitfield = PeerConnection.Bitfield.init(alloc), .tracker_connection = undefined, .timer = undefined, .tracker_read_stream = std.fifo.LinearFifo(u8, .Dynamic).init(alloc), }; } pub fn initWithTorrent(allocator: *Allocator, peer_id: []const u8, torrent: TorrentFile) @This() { return .{ .allocator = allocator, .peer_id = peer_id, .loop = undefined, .torrent = torrent, .connected_peers = ConnectionList.init(allocator), .inactive_peers = ConnectionList.init(allocator), .completed_pieces = std.ArrayList(CompletePiece).init(allocator), .output_file_pipe = undefined, .output_filed = undefined, .work_queue = WorkQueue.init(allocator), .have_bitfield = PeerConnection.Bitfield.init(allocator), .tracker_connection = undefined, .timer = undefined, .tracker_read_stream = std.fifo.LinearFifo(u8, .Dynamic).init(allocator), }; } const Progress = struct { current: usize, total: usize, }; const bitcount_lookup = comptime blk: { var count: [256]u8 = std.mem.zeroes([256]u8); var i: u8 = 1; inline while (true) : (i +%= 1) { count[i] = count[@divTrunc(i, 2)] + (i & 1); if (i == 0) { break; } } break :blk count; }; fn num_pieces(self: @This()) usize { var count: usize = 0; for (self.have_bitfield.items) |item| { count += bitcount_lookup[item]; } return count; } pub fn progress(self: @This()) Progress { const count = self.num_pieces(); return .{ .current = count, .total = self.torrent.info.pieces.len, }; } pub fn validate_hash(self: @This(), data: []const u8, piece: usize) bool { var hash_buffer = [_]u8{undefined} ** 20; std.crypto.hash.Sha1.hash(data, hash_buffer[0..], .{}); return std.mem.eql(u8, hash_buffer[0..], self.torrent.info.pieces[piece][0..]); } pub fn start(self: *@This(), loop: *c.uv_loop_t) !void { const total_pieces = self.torrent.info.pieces.len; const bytes_required = @divTrunc(total_pieces, 8) + 1; try self.have_bitfield.appendNTimes(0, bytes_required); self.loop = loop; _ = c.uv_tcp_init(loop, &self.tracker_connection); _ = c.uv_tcp_nodelay(&self.tracker_connection, 1); self.tracker_connection.data = @ptrCast(?*c_void, self); log.info("TorrentContext starting for {}", .{self.torrent.info.name}); log.info("Torrent File: {}", .{self.torrent}); log.info("Made up of {} {}", .{ self.torrent.info.files.items.len, if (self.torrent.info.files.items.len == 1) "file" else "file", }); for (self.torrent.info.files.items) |item| { log.info("File:{} - Size: {Bi}", .{ item.name, item.length }); } // Open listening torrent port var announce = try uri.parse(self.torrent.announce); const host = announce.host.?; const port = announce.port orelse 80; log.debug("Connecting to Announce at server {}:{}", .{ host, port }); // OK so here we're being a bit lazy and resolving in a blocking manner const list = try std.net.getAddressList(self.allocator, host, port); defer list.deinit(); const addr = list.addrs[0].in; const connect = try self.allocator.create(c.uv_connect_t); _ = c.uv_tcp_connect( connect, &self.tracker_connection, @ptrCast(?*const c.sockaddr, &addr.sa), onConnectTrackerFwd, ); } pub fn onConnectTracker(self: *@This()) void { var announce = uri.parse(self.torrent.announce) catch unreachable; log.debug("Successfully connected to tracker for {}", .{self.torrent.info.name}); log.debug("Sending announce request", .{}); log.debug("URI Path: {}", .{announce.path.?}); const escaped_hash = uri.escapeString(self.allocator, self.torrent.info_hash[0..]) catch unreachable; defer self.allocator.free(escaped_hash); const escaped_peer_id = uri.escapeString(self.allocator, self.peer_id) catch unreachable; defer self.allocator.free(escaped_peer_id); // TODO - fix uploaded/downloaded/left so we can "resume" a torrent const formated_request = std.fmt.allocPrint(self.allocator, msg.TRACKER_GET_REQUEST_FORMAT, .{ announce.path.?, escaped_peer_id[0..], escaped_hash[0..], 6881, 0, 0, self.torrent.info.files.items[0].length, announce.host.?, }) catch unreachable; msg.write(self.allocator, formated_request, &self.tracker_connection, onWriteAnnounceFwd) catch |e| { log.warn("Error connecting to tracker for torrent {s}. Shutting down", .{self.torrent.info.name}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.tracker_connection), null); return; }; msg.read_start(&self.tracker_connection, tcAllocBuffer, onReadAnnounceFwd) catch |e| { log.warn("Error reading from tracker stream for torrent {s}", .{self.torrent.info.name}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.tracker_connection), null); }; } pub fn onReadAnnounce(self: *@This(), handle: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { if (nread < 0) { if (nread == c.UV_EOF) { self.parsePeers(); var i: usize = 0; while (i < self.torrent.info.pieces.len) : (i += 1) { self.work_queue.writeItem(i) catch unreachable; } self.beginDownload(); log.debug("Tracker disconnected. Closing handle", .{}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, handle), null); } } else if (nread > 0) { // we're just going to buffer the tracker info until read is done self.tracker_read_stream.update(@intCast(usize, nread)); } } fn parsePeers(self: *@This()) void { var settings: c.http_parser_settings = undefined; settings.on_message_begin = http_ignore; settings.on_message_complete = http_ignore; settings.on_headers_complete = http_ignore; settings.on_status = http_ignore_data; settings.on_url = http_ignore_data; settings.on_header_field = http_ignore_data; settings.on_header_value = http_ignore_data; settings.on_body = http_tracker_parse_body; settings.on_chunk_header = http_ignore; settings.on_chunk_complete = http_ignore; var http_parser: *c.http_parser = @ptrCast(*c.http_parser, self.allocator.create(c.http_parser_sized) catch unreachable); var as_sized = util.cast_from_cptr(*c.http_parser_sized, http_parser); as_sized.data = @ptrCast(*c_void, self); defer self.allocator.destroy(util.cast_from_cptr(*c.http_parser_sized, http_parser)); c.http_parser_init(http_parser, c.enum_http_parser_type.HTTP_RESPONSE); const data = self.tracker_read_stream.readableSlice(0); // not sure what to do with nparsed const nparsed = c.http_parser_execute(http_parser, &settings, data.ptr, data.len); self.tracker_read_stream.discard(data.len); } pub fn deinit(self: *@This()) void { for (self.connected_peers.items) |peer| { peer.deinit(); self.allocator.destroy(peer); } for (self.inactive_peers.items) |peer| { peer.deinit(); self.allocator.destroy(peer); } self.connected_peers.deinit(); self.inactive_peers.deinit(); self.completed_pieces.deinit(); self.tracker_read_stream.deinit(); self.work_queue.deinit(); self.have_bitfield.deinit(); } /// Adds a peer if it has not already been added /// It is not a failure to re-add a peer /// the duplciate is ignored pub fn addPeer(self: *@This(), peer: Peer) void { const id = peer.id(); for (self.connected_peers.items) |p| { if (p.peer.id() == id) { log.debug("Duplicate peer {} found. Ignoring", .{peer}); return; } } for (self.inactive_peers.items) |p| { if (p.peer.id() == id) { log.debug("Duplicate peer {} found. Ignoring", .{peer}); return; } } const total_pieces = self.torrent.info.pieces.len; const bytes_required = @divTrunc(total_pieces, 8) + 1; log.debug("Bytes length for bitfield is: {}", .{bytes_required}); var pc = self.allocator.create(PeerConnection) catch unreachable; pc.* = .{ .peer = peer, .connection = undefined, .timer = undefined, .torrent = self, .stream_buffer = PeerConnection.Buffer.init(self.allocator), .bitfield = PeerConnection.Bitfield.initCapacity(self.allocator, bytes_required) catch unreachable, .piece_buffer = PeerConnection.Buffer.init(self.allocator), }; pc.bitfield.appendNTimesAssumeCapacity(0, bytes_required); self.inactive_peers.append(pc) catch unreachable; log.debug("Adding unique peer {}", .{peer}); } /// What we need to do: /// 1. connect to a couple new peers /// 2. assign all piece work into the work queue /// 3. set up idler and timer for everyone fn beginDownload(self: *@This()) void { log.debug("Beginning download for {}", .{self.torrent.info.name}); _ = c.uv_timer_init(self.loop, &self.timer); self.timer.data = self; _ = c.uv_timer_start(&self.timer, on_torrent_timer, 100, 100); const name = self.allocator.dupeZ(u8, self.torrent.info.files.items[0].name) catch unreachable; defer self.allocator.free(name); var req: c.uv_fs_t = undefined; self.output_filed = c.uv_fs_open(self.loop, &req, name.ptr, c.O_CREAT | c.O_TRUNC | c.O_RDWR, 0o644, null); _ = c.uv_pipe_init(self.loop, &self.output_file_pipe, 0); self.output_file_pipe.data = self; _ = c.uv_pipe_open(&self.output_file_pipe, self.output_filed); for (self.inactive_peers.items) |peer| { _ = c.uv_tcp_init(self.loop, &peer.connection); _ = c.uv_tcp_nodelay(&peer.connection, 1); peer.connection.data = @ptrCast(?*c_void, peer); var addr: c.sockaddr_in = undefined; const addr_name = std.fmt.allocPrint0(self.allocator, "{}.{}.{}.{}", .{ peer.peer.ip[0], peer.peer.ip[1], peer.peer.ip[2], peer.peer.ip[3], }) catch unreachable; defer self.allocator.free(addr_name); _ = c.uv_ip4_addr(addr_name.ptr, peer.peer.port, &addr); log.debug("Connecting to peer - {}", .{peer.peer}); const connect = self.allocator.create(c.uv_connect_t) catch unreachable; connect.data = @ptrCast(?*c_void, peer); const pc_result = c.uv_tcp_connect( connect, &peer.connection, @ptrCast(?*const c.sockaddr, &addr), on_connect_peer, ); if (pc_result < 0) { self.allocator.destroy(connect); log.debug("Could not create connection to peer {} - {}", .{ peer.peer, c.uv_strerror(pc_result) }); continue; } self.connected_peers.append(peer) catch unreachable; } self.inactive_peers.resize(0) catch unreachable; } pub fn checkFinished(self: *@This()) void { const num_have = self.num_pieces(); const have_all = num_have == self.torrent.info.pieces.len; const work_done = have_all and self.inflight_file_pieces == 0; if (!work_done) { return; } for (self.connected_peers.items) |peer| { if (peer.current_work) |cw| { return; } } for (self.connected_peers.items) |peer| { peer.close(); // peer will destroy itself self.inactive_peers.append(peer) catch unreachable; } _ = self.connected_peers.resize(0) catch unreachable; if (self.to_write_piece >= self.torrent.info.pieces.len) { log.info("Done downloading torrent {s}", .{self.torrent.info.name}); _ = c.uv_timer_stop(&self.timer); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.output_file_pipe), null); } } pub fn dispatchWork(self: *@This()) void { for (self.connected_peers.items) |item| { item.nextPiece(); } } fn sort_by_index(ctx: *const @This(), lhs: CompletePiece, rhs: CompletePiece) bool { return lhs.index < rhs.index; } pub fn writePieces(self: *@This()) void { std.sort.sort(CompletePiece, self.completed_pieces.items, self, sort_by_index); for (self.completed_pieces.items) |item| { const idx = item.index; const byte_idx = @divTrunc(idx, 8); const bit_idx = (7 - @mod(idx, 8)); self.have_bitfield.items[byte_idx] |= (std.math.shl(u8, 1, bit_idx)); } while (self.completed_pieces.items.len > 0 and self.completed_pieces.items[0].index <= self.to_write_piece) { const item = &self.completed_pieces.items[0]; if (item.index < self.to_write_piece) { _ = self.completed_pieces.orderedRemove(0); continue; } log.debug("Writing piece {{index = {}, size = {Bi}}}", .{ item.index, item.read_length }); const data = self.allocator.alloc(u8, item.read_length) catch unreachable; std.mem.copy(u8, data[0..], item.buffer[0..item.read_length]); msg.write(self.allocator, data, &self.output_file_pipe, on_file_write) catch |e| { log.debug("Error writing piece to file - {}", .{e}); self.allocator.free(data); return; }; self.allocator.free(item.buffer); _ = self.completed_pieces.orderedRemove(0); log.debug("Wrote piece {}/{}", .{ self.to_write_piece, self.torrent.info.pieces.len - 1 }); self.to_write_piece += 1; self.inflight_file_pieces += 1; } } }; export fn on_file_write(req: ?*c.uv_write_t, status: i32, buf: ?*c.uv_buf_t) void { const tc = getTorrentContext(req.?.handle); tc.allocator.free(buf.?.base[0..buf.?.len]); tc.inflight_file_pieces -= 1; } export fn on_torrent_timer(timer: ?*c.uv_timer_t) void { const torrent = getTorrentContext(timer); torrent.writePieces(); torrent.dispatchWork(); torrent.checkFinished(); const progress = torrent.progress(); const stdout = std.io.getStdOut(); stdout.writer().print("\rDownloaded {}/{} pieces", .{ progress.current, progress.total }) catch unreachable; } fn get_peer_connection(handle: anytype) *PeerConnection { std.debug.assert(handle != null); return util.cast_from_cptr(*PeerConnection, handle.?.*.data); } /// Metadata about a particular peer /// we are connected to for a particular torrent /// Note: Torrent is NON-OWNING as each /// peer has a reference to the same torrent const PeerConnection = struct { peer: Peer, choked: bool = true, interested: bool = false, hand_shook: bool = false, connection: c.uv_tcp_t, timer: c.uv_timer_t, download_timer: c.uv_timer_t = undefined, torrent: *TorrentContext, // this is read-stream, do we need a write stream? stream_buffer: Buffer, bitfield: Bitfield, piece_buffer: Buffer, current_work: ?WorkData = null, const WorkData = struct { idx: usize, current_offset: usize, awaiting: u8, }; pub const Buffer = std.fifo.LinearFifo(u8, .Dynamic); pub const Bitfield = std.ArrayList(u8); const keep_alive_timeout: usize = 45_000; // 45 seconds const piece_size: u32 = std.math.shl(u32, 1, 14); pub fn init(allocator: *Allocator) @This() {} pub fn deinit(self: *@This()) void { self.stream_buffer.deinit(); self.bitfield.deinit(); self.piece_buffer.deinit(); } pub fn keepAlive(self: *@This()) void { // only send keepalive if we're active if (c.uv_is_active(@ptrCast(?*c.uv_handle_t, &self.connection)) == 0) { return; } const c_keep_alive = @intToPtr([*c]u8, @ptrToInt(msg.KEEP_ALIVE[0..]))[0..msg.KEEP_ALIVE.len]; msg.write(self.torrent.allocator, c_keep_alive, &self.connection, null) catch |e| { log.debug("Could not write keep-alive to peer {}", .{self.peer}); }; } pub fn onConnect(self: *@This(), connection: ?*c.uv_connect_t, status: i32) void { const alloc = self.torrent.allocator; defer alloc.destroy(connection.?); if (status < 0) { log.debug("Error connecting to peer: {} - {s}", .{ self.peer, c.uv_strerror(status), }); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.connection), on_close); return; } log.debug("Successfully connected to peer: {}", .{self.peer}); var handshake = msg.make_handshake( alloc, self.torrent.peer_id, self.torrent.torrent.info_hash, ) catch |e| { log.debug("Error allocating handshake for peer {}", .{self.peer}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.connection), on_close); return; }; msg.write(alloc, handshake, &self.connection, on_write) catch |e| { log.debug("Error sending handshake to peer {}", .{self.peer}); alloc.free(handshake); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.connection), on_close); return; }; msg.read_start(&self.connection, alloc_buffer, on_read_handshake) catch |e| { log.debug("Error reading from stream for peer {}: {}", .{ self.peer, e }); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.connection), on_close); }; } pub fn allocBuffer(self: *@This(), handle: ?*c.uv_handle_t, suggested_size: usize, buf: ?*c.uv_buf_t) void { var data = self.stream_buffer.writableWithSize(suggested_size) catch { log.err("Error allocating buffer on callback", .{}); buf.?.* = c.uv_buf_init(null, 0); return; }; buf.?.* = c.uv_buf_init(data.ptr, @intCast(u32, suggested_size)); } pub fn onWrite(self: *@This(), handle: ?*c.uv_write_t, status: i32, buf: ?*c.uv_buf_t) void { self.torrent.allocator.free(buf.?.base[0..buf.?.len]); } pub fn close(self: *@This()) void { log.debug("Peer is closing...", .{}); _ = c.uv_timer_stop(&self.timer); _ = c.uv_timer_stop(&self.download_timer); if (c.uv_is_active(@ptrCast(?*c.uv_handle_t, &self.connection)) != 0) { _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.connection), on_close); } } pub fn onClose(self: *@This(), handle: ?*c.uv_handle_t) void { log.debug("Successfully closed connection to peer {}", .{self.peer}); _ = c.uv_timer_stop(&self.timer); _ = c.uv_timer_stop(&self.download_timer); if (self.current_work) |cw| { self.torrent.work_queue.writeItem(cw.idx) catch unreachable; } self.current_work = null; self.choked = true; self.interested = false; } pub fn onHandshake(self: *@This(), client: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { log.debug("Got response from peer: {}", .{self.peer}); if (nread < 0) { if (nread == c.UV_EOF) { log.debug("Peer {} disconnected. Closing handle...", .{self.peer}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), on_close); } } else if (nread > 0) { self.stream_buffer.update(@intCast(usize, nread)); const data = self.stream_buffer.readableSlice(0); const handshake = msg.consume_handshake(data, self.torrent.torrent.info_hash) catch { // TODO be better log.warn( "Error validating handshake from peer {}. Got: {x}", .{ self.peer, data }, ); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), on_close); return; }; self.stream_buffer.discard(msg.HANDSHAKE_LENGTH); self.sendUnchoke() catch |e| { log.debug("Error sending unchoke to peer {}", .{self.peer}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), on_close); return; }; self.sendInterested() catch |e| { log.debug("Error sending interested to peer {}", .{self.peer}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), on_close); return; }; self.handleMessages(); msg.read_start(client, alloc_buffer, on_read) catch |e| { log.debug("Error swapping read stream from handshake for peer {}: {}", .{ self.peer, e }); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), on_close); return; }; // setup keepalive timer _ = c.uv_timer_init(self.torrent.loop, &self.timer); self.timer.data = @ptrCast(?*c_void, self); _ = c.uv_timer_start(&self.timer, keep_alive, keep_alive_timeout, keep_alive_timeout); _ = c.uv_timer_init(self.torrent.loop, &self.download_timer); self.download_timer.data = @ptrCast(?*c_void, self); _ = c.uv_timer_start(&self.download_timer, on_download_timer, 30 * 1000, 30 * 1000); } } pub fn onRead(self: *@This(), client: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { if (nread < 0) { if (nread == c.UV_EOF) { log.debug("Peer {} disconnected. Closing handle...", .{self.peer}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, client), on_close); if (self.current_work) |cw| { if (!piece_complete(cw, self.torrent.torrent.info.piece_length)) { self.return_piece(); } } } } else if (nread > 0) { self.stream_buffer.update(@intCast(usize, nread)); log.debug("Received {} more bytes from peer: {}", .{ nread, self.peer }); } self.handleMessages(); } fn sendUnchoke(self: *@This()) !void { var unchoke = msg.make_unchoke(self.torrent.allocator) catch unreachable; errdefer self.torrent.allocator.free(unchoke); try msg.write(self.torrent.allocator, unchoke, &self.connection, on_write); } fn sendInterested(self: *@This()) !void { var interested = msg.make_interested(self.torrent.allocator) catch unreachable; errdefer self.torrent.allocator.free(interested); try msg.write(self.torrent.allocator, interested, &self.connection, on_write); } fn handleMessages(self: *@This()) void { var data = self.stream_buffer.readableSlice(0); log.debug("Total stream to process {} bytes", .{data.len}); //log.debug("Data: {x}", .{data}); var consumed_bytes: usize = 0; const total_bytes = data.len; defer self.stream_buffer.discard(consumed_bytes); while (msg.consume_message(data) catch |e| { log.debug("Error - invalid message received from peer {}", .{self.peer}); _ = c.uv_close(@ptrCast(?*c.uv_handle_t, &self.connection), on_close); return; }) |message| { consumed_bytes += message.total_size; data = data[message.total_size..]; log.debug("Processing msg - {}", .{message.message_type}); switch (message.message_type) { .keep_alive => {}, .choke => { self.choked = true; self.return_piece(); }, .unchoke => { self.choked = false; }, .interested => {}, .not_interested => {}, .have => { const idx = message.number(u32, 0); self.setIdx(idx); }, .bitfield => { // basically a big "have" message std.debug.assert(message.data.len <= self.bitfield.items.len); for (message.data) |byte, i| { self.bitfield.items[i] = byte; } }, .request => { // TODO actually implement uploading }, .cancel => { // we're not uploading so whatever }, .piece => { // Actually save the file const idx = message.number(u32, 0); const offset = message.number(u32, @sizeOf(u32)); var rest = message.data[@sizeOf(u32) + @sizeOf(u32) ..]; if (self.current_work) |*cw| { if (cw.idx != idx) { log.debug( "Got a piece message for wrong piece - got {{idx = {}, offset = {}}} expected {}", .{ idx, offset, cw.idx }, ); continue; } if (rest.len != piece_size) { log.debug( "Got a piece message with incorrect piece size - {b} vs {b}", .{ rest.len, piece_size }, ); } var write_to = self.piece_buffer.writableWithSize(rest.len) catch unreachable; std.mem.copy(u8, write_to, rest); self.piece_buffer.update(rest.len); log.debug("Peer {} Wrote Piece {{idx = {}, offset = {}}}", .{ self.peer, idx, offset }); cw.awaiting -= 1; if (piece_complete(cw.*, self.torrent.torrent.info.piece_length)) { log.debug("Peer {} fully downloaded piece {}", .{ self.peer, cw.idx }); self.send_finished_piece() catch { continue; }; } self.nextPiece(); } else { log.debug( "Got a piece message with no current work for {{idx = {}, offset = {}}}", .{ idx, offset }, ); } }, } } } const max_pipelined_pieces: u8 = 5; fn piece_complete(work: WorkData, length: usize) bool { return work.awaiting == 0 and work.current_offset >= length; } fn send_finished_piece(self: *@This()) !void { self.piece_buffer.realign(); const valid = self.torrent.validate_hash(self.piece_buffer.readableSlice(0), self.current_work.?.idx); if (!valid) { log.debug("Could not validate hash of piece {} from peer {}", .{ self.current_work.?.idx, self.peer }); self.return_piece(); return error.invalid_piece; } self.torrent.completed_pieces.append(.{ .index = self.current_work.?.idx, .buffer = self.piece_buffer.buf, .read_length = self.piece_buffer.readableLength(), }) catch unreachable; self.current_work = null; self.piece_buffer = Buffer.init(self.torrent.allocator); } fn return_piece(self: *@This()) void { if (self.current_work) |cw| { log.debug("Peer {} returning piece {}", .{ self.peer, cw.idx }); self.torrent.work_queue.writeItem(cw.idx) catch unreachable; } self.current_work = null; self.piece_buffer.discard(self.piece_buffer.readableLength()); } fn nextPiece(self: *@This()) void { if (self.choked) { return; } if (self.current_work) |*cw| { // If we're already downloading do nothing log.debug("Peer {} working on piece {}", .{ self.peer, cw.* }); // send 5 at a time, not just 5 then 1 after the other if (cw.awaiting > 0) { return; } while (cw.awaiting < max_pipelined_pieces and cw.current_offset < self.torrent.torrent.info.piece_length) { const amnt = std.math.min(piece_size, self.torrent.torrent.info.piece_length - cw.current_offset); var request = msg.make_request(self.torrent.allocator, cw.idx, cw.current_offset, amnt) catch unreachable; log.debug("Requesting next offset ({})", .{cw.current_offset}); msg.write(self.torrent.allocator, request, &self.connection, on_write) catch |e| { log.debug( "Error requesting {{idx = {}, offset = {}}} from peer {}. Returning piece to queue - {}", .{ cw.idx, cw.current_offset, self.peer, e }, ); self.torrent.work_queue.writeItem(cw.idx) catch unreachable; self.current_work = null; self.piece_buffer.deinit(); self.piece_buffer = Buffer.init(self.torrent.allocator); return; }; cw.awaiting += 1; cw.current_offset += piece_size; } _ = c.uv_timer_again(&self.download_timer); } else { const idx = self.torrent.work_queue.readItem(); if (idx) |i| { log.debug("Grabbing a new piece - index: {}", .{i}); if (!self.hasPiece(i)) { self.torrent.work_queue.writeItem(i) catch unreachable; return; } self.current_work = .{ .idx = i, .current_offset = 0, .awaiting = 0, }; log.debug("Successfully grabbed piece - sending request", .{}); self.nextPiece(); } } } fn setIdx(self: *@This(), idx: usize) void { const byte_idx = @divTrunc(idx, 8); const bit_idx = (7 - @mod(idx, 8)); self.bitfield.items[byte_idx] |= (std.math.shl(u8, 1, bit_idx)); } fn hasPiece(self: @This(), idx: usize) bool { const byte_idx = @divTrunc(idx, 8); const bit_idx = (7 - @mod(idx, 8)); return (self.bitfield.items[byte_idx] & (std.math.shl(u8, 1, bit_idx))) != 0; } pub fn downloadTimerElapsed(self: *@This()) void { self.return_piece(); } }; pub const TorrentFile = struct { announce: []const u8, info: Info, info_hash: []const u8, pub fn deinit(self: *@This()) void { self.info.files.deinit(); } }; pub const Info = struct { name: []const u8, piece_length: usize, pieces: []const [20]u8, files: std.ArrayList(FInfo), }; pub const FInfo = struct { name: []const u8, length: usize, }; /// Generates a peer id for the ZTOR BitTorrent client /// composed of ZTOR followed by 16 random characters /// The string must be freed by the caller pub fn make_peer_id(alloc: *std.mem.Allocator) ![]const u8 { var rnd_buf = [_]u8{undefined} ** 16; try std.crypto.randomBytes(rnd_buf[0..]); return std.fmt.allocPrint(alloc, "ZTOR{s}", .{rnd_buf}); } pub fn make_torrent(alloc: *std.mem.Allocator, tree: zben.BencodeTree) !TorrentFile { const top_level = &tree.root.Dictionary; var torrent: TorrentFile = undefined; torrent.announce = (top_level.get("announce") orelse return error.invalid_dictionary).String; const info = (top_level.get("info") orelse return error.invalid_dictionary).Dictionary; torrent.info.name = (info.get("name") orelse return error.invalid_dictionary).String; torrent.info.piece_length = @intCast(usize, (info.get("piece length") orelse return error.invalid_dictionary).Integer); const str = (info.get("pieces") orelse return error.invalid_dictionary).String; torrent.info.pieces.ptr = @ptrCast([*]const [20]u8, str.ptr); torrent.info.pieces.len = str.len / 20; torrent.info.files = std.ArrayList(FInfo).init(alloc); errdefer torrent.info.files.deinit(); if (info.get("length")) |len| { try torrent.info.files.append(.{ .name = torrent.info.name, .length = @intCast(usize, len.Integer) }); } else if (info.get("files")) |files| { for (files.List.items) |file| { const name = (file.Dictionary.get("path") orelse return error.invalid_dictionary).String; const len = @intCast(usize, (file.Dictionary.get("length") orelse return error.invalid_dictionary).Integer); try torrent.info.files.append(.{ .name = name, .length = @intCast(usize, len) }); } } else { return error.invalid_dictionary; } return torrent; } pub fn calculate_info_hash(data: []const u8, memory: []u8) !void { std.debug.assert(memory.len == 20); var l = zben.Lexer.initWithData(data); var offset: usize = 0; var begin_offset: usize = 0; var end_offset: usize = 0; var nested: usize = 0; var start_found: bool = false; while (l.next()) |token| { switch (token.token_type) { .string => { if (!start_found and std.mem.eql(u8, "info", token.data)) { begin_offset = offset + token.data.len; start_found = true; } }, .end => { if (start_found) { nested -= 1; if (nested == 0) { end_offset = offset + token.data.len; break; } } }, .list_begin, .integer_begin, .dictionary_begin => { if (start_found) { nested += 1; } }, else => {}, } offset += token.data.len; } if (!start_found or end_offset <= begin_offset) { return error.info_not_found; } const info_full = data[begin_offset..end_offset]; log.debug("Full Dump:\n{}", .{info_full[0..]}); log.debug("First char: {s}", .{util.slice_front(info_full)}); log.debug("Last char: {s}", .{util.slice_back(info_full)}); std.crypto.hash.Sha1.hash(info_full[0..], memory[0..], .{}); } pub fn printValue(v: zben.Value) void { switch (v) { .Empty => log.warn("Got an empty value somehow", .{}), .Integer => |i| log.info("Integer: {}", .{i}), .String => |s| log.info("String: {}", .{s}), .List => |l| { log.info("LIST:", .{}); for (l.items) |item| { printValue(item); } }, .Dictionary => |d| { log.info("DICT:", .{}); var iter = d.iterator(); while (iter.next()) |entry| { log.info("KEY: {}", .{entry.key}); printValue(entry.value); } }, } } pub const PeerIter = struct { data: []const u8, const ip_len = 4; const port_len = 2; pub fn next(self: *@This()) ?Peer { if (self.data.len < msg.COMPACT_PEER_LEN) { return null; } var p = Peer{ .ip = undefined, .port = undefined }; std.mem.copy(u8, p.ip[0..], self.data[0..ip_len]); p.port = std.mem.bigToNative(u16, std.mem.bytesToValue(u16, self.data[ip_len .. ip_len + port_len])); self.data = self.data[msg.COMPACT_PEER_LEN..]; return p; } }; /// ipv4 peers only for now /// TODO: ipv6? pub const Peer = struct { ip: [4]u8, port: u16, empty: u16 = 0, // padding out to u64 /// For fast compare we treat the peer as a u64 pub fn id(self: @This()) u64 { return std.mem.bytesToValue(u64, std.mem.asBytes(&self)); } pub fn format(peer: Peer, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print("{}.{}.{}.{}:{}", .{ peer.ip[0], peer.ip[1], peer.ip[2], peer.ip[3], peer.port, }); } }; export fn on_download_timer(handle: ?*c.uv_timer_t) void { std.debug.assert(handle != null); const peer_con = get_peer_connection(handle); peer_con.downloadTimerElapsed(); } export fn keep_alive(handle: ?*c.uv_timer_t) void { std.debug.assert(handle != null); const peer_con = get_peer_connection(handle); peer_con.keepAlive(); } ///// Start handshaking with peer on successful connection export fn on_connect_peer(con: ?*c.uv_connect_t, status: i32) void { std.debug.assert(con != null); const peer_con = get_peer_connection(con.?.handle); peer_con.onConnect(con, status); } ///// Allocates a buffer for libuv to use export fn alloc_buffer(handle: ?*c.uv_handle_t, suggested_size: usize, buf: ?*c.uv_buf_t) void { std.debug.assert(buf != null); std.debug.assert(handle != null); const peer_con = get_peer_connection(handle); peer_con.allocBuffer(handle, suggested_size, buf); } ///// This is a callback after successfully sending bytes down ///// the wire export fn on_write(req: ?*c.uv_write_t, status: i32, buf: ?*c.uv_buf_t) void { std.debug.assert(req != null); const peer_con = get_peer_connection(req.?.handle); peer_con.onWrite(req, status, buf); } export fn on_close(client: ?*c.uv_handle_t) void { std.debug.assert(client != null); const peer_con = get_peer_connection(client); peer_con.onClose(client); } export fn on_read_handshake(client: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { std.debug.assert(buf != null); const peer_con = get_peer_connection(client); peer_con.onHandshake(client, nread, buf); } /// Read data, client should have already gone through handshake callback /// This handles the dispatching of messages export fn on_read(client: ?*c.uv_stream_t, nread: isize, buf: ?*const c.uv_buf_t) void { std.debug.assert(client != null); std.debug.assert(buf != null); const peer_con = get_peer_connection(client); peer_con.onRead(client, nread, buf); }
src/torrent.zig
const std = @import("std"); const options = @import("./options.zig"); const assert = std.debug.assert; const expectEqual = std.testing.expectEqual; const showdown = options.showdown; pub fn PRNG(comptime gen: comptime_int) type { if (showdown) return PSRNG; const Source = switch (gen) { 1, 2 => Gen12, 3, 4 => Gen34, 5, 6 => Gen56, else => unreachable, }; return extern struct { const Self = @This(); src: Source, pub fn next(self: *Self) Output(gen) { return self.src.next(); } }; } pub const PSRNG = extern struct { src: Gen56, const divisor = 0x100000000; pub fn init(seed: u64) PSRNG { return .{ .src = .{ .seed = seed } }; } pub fn next(self: *PSRNG) u32 { return self.src.next(); } pub fn advance(self: *PSRNG, n: usize) void { if (!options.advance) return; var i: usize = 0; while (i < n) : (i += 1) self.src.advance(); } pub fn range(self: *PSRNG, comptime T: type, from: T, to: Bound(T)) T { return @truncate(T, @as(u64, self.src.next()) * (to - from) / divisor + from); } pub fn chance(self: *PSRNG, comptime T: type, numerator: T, denominator: Bound(T)) bool { assert(denominator > 0); return self.range(T, 0, denominator) < numerator; } pub fn newSeed(self: *PSRNG) u64 { return (@as(u64, self.range(u16, 0, 0x10000)) << 48) | (@as(u64, self.range(u16, 0, 0x10000)) << 32) | (@as(u64, self.range(u16, 0, 0x10000)) << 16) | (@as(u64, self.range(u16, 0, 0x10000))); } }; test "PSRNG" { var psrng = PSRNG{ .src = .{ .seed = 0x0001000200030004 } }; try expectEqual(@as(u8, 121), psrng.range(u8, 0, 256)); try expectEqual(false, psrng.chance(u8, 128, 256)); // 226 < 128 } // https://pkmn.cc/pokered/engine/battle/core.asm#L6644-L6693 // https://pkmn.cc/pokecrystal/engine/battle/core.asm#L6922-L6938 pub const Gen12 = extern struct { seed: [10]u8, index: u8 = 0, comptime { assert(@sizeOf(Gen12) == 11); } pub fn percent(p: u8) u8 { return @truncate(u8, (@as(u16, p) * 0xFF) / 100); } pub fn next(self: *Gen12) u8 { const val = 5 *% self.seed[self.index] +% 1; self.seed[self.index] = val; self.index = (self.index + 1) % 10; return val; } }; test "Generation I & II" { const expected = [_]u8{ 6, 11, 16, 21, 26, 31, 36, 41, 46, 51, 31, 56, 81 }; var rng = Gen12{ .seed = .{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } }; for (expected) |e| { try expectEqual(e, rng.next()); } try expectEqual(@as(u8, 16), Gen12.percent(6) + 1); try expectEqual(@as(u8, 16), Gen12.percent(7) - 1); try expectEqual(@as(u8, 128), Gen12.percent(50) + 1); } // https://pkmn.cc/pokeemerald/src/random.c // https://pkmn.cc/pokediamond/arm9/src/math_util.c#L624-L630 pub const Gen34 = extern struct { seed: u32, comptime { assert(@sizeOf(Gen34) == 4); } pub fn next(self: *Gen34) u16 { self.advance(); return @truncate(u16, self.seed >> 16); } pub fn advance(self: *Gen34) void { self.seed = 0x41C64E6D *% self.seed +% 0x00006073; } }; // https://pkmn.cc/PokeFinder/Source/Tests/RNG/LCRNGTest.cpp test "Generation III & IV" { const data = [_][3]u32{ .{ 0x00000000, 5, 0x8E425287 }, .{ 0x00000000, 10, 0xEF2CF4B2 }, .{ 0x80000000, 5, 0x0E425287 }, .{ 0x80000000, 10, 0x6F2CF4B2 }, }; for (data) |d| { var rng = Gen34{ .seed = d[0] }; var i: usize = 0; while (i < d[1]) : (i += 1) { _ = rng.next(); } try expectEqual(d[2], rng.seed); } } pub const Gen56 = extern struct { seed: u64, comptime { assert(@sizeOf(Gen56) == 8); } pub fn next(self: *Gen56) u32 { self.advance(); return @truncate(u32, self.seed >> 32); } pub fn advance(self: *Gen56) void { self.seed = 0x5D588B656C078965 *% self.seed +% 0x0000000000269EC3; } }; // https://pkmn.cc/PokeFinder/Source/Tests/RNG/LCRNG64Test.cpp test "Generation V & VI" { const data = [_][3]u64{ .{ 0x0000000000000000, 5, 0xC83FB970153A9227 }, .{ 0x0000000000000000, 10, 0x67795501267F125A }, .{ 0x8000000000000000, 5, 0x483FB970153A9227 }, .{ 0x8000000000000000, 10, 0xE7795501267F125A }, }; for (data) |d| { var rng = Gen56{ .seed = d[0] }; var i: usize = 0; while (i < d[1]) : (i += 1) { _ = rng.next(); } try expectEqual(d[2], rng.seed); } } pub fn FixedRNG(comptime gen: comptime_int, comptime len: usize) type { const divisor = 0x100000000; return extern struct { const Self = @This(); rolls: [len]Output(gen), index: usize = 0, pub fn next(self: *Self) Output(gen) { if (self.index >= self.rolls.len) @panic("Insufficient number of rolls provided"); const roll = self.rolls[self.index]; self.index += 1; return roll; } pub fn advance(self: *Self, n: usize) void { assert(showdown); var i: usize = 0; while (i < n) : (i += 1) _ = self.next(); } pub fn range(self: *Self, comptime T: type, from: T, to: Bound(T)) T { assert(showdown); return @truncate(T, @as(u64, self.next()) * (to - from) / divisor + from); } pub fn chance( self: *Self, comptime T: type, numerator: T, denominator: Bound(T), ) bool { assert(showdown); assert(denominator > 0); return self.range(T, 0, denominator) < numerator; } pub fn exhausted(self: Self) bool { return self.index == self.rolls.len; } }; } test "FixedRNG" { const Type = if (showdown) u32 else u8; const expected = [_]Type{ 42, 255, 0 }; var rng = FixedRNG(1, expected.len){ .rolls = expected }; for (expected) |e| { try expectEqual(e, rng.next()); } } fn Output(comptime gen: comptime_int) type { if (showdown) return u32; return switch (gen) { 1, 2 => u8, 3, 4 => u16, 5, 6 => u32, else => unreachable, }; } fn Bound(comptime T: type) type { return std.math.IntFittingRange(0, std.math.maxInt(T) + 1); }
src/lib/common/rng.zig
const clz = @import("count0bits.zig"); const testing = @import("std").testing; fn test__clzti2(a: u128, expected: i64) !void { // XXX At high optimization levels this test may be horribly miscompiled if // one of the naked implementations is selected. var nakedClzti2 = clz.__clzti2; var actualClzti2 = @ptrCast(fn (a: i128) callconv(.C) i32, nakedClzti2); var x = @bitCast(i128, a); var result = actualClzti2(x); try testing.expectEqual(expected, result); } test "clzti2" { try test__clzti2(0x00800000_00000000_00000000_00000000, 8); try test__clzti2(0x01000000_00000000_00000000_00000000, 7); try test__clzti2(0x02000000_00000000_00000000_00000000, 6); try test__clzti2(0x03000000_00000000_00000000_00000000, 6); try test__clzti2(0x04000000_00000000_00000000_00000000, 5); try test__clzti2(0x05000000_00000000_00000000_00000000, 5); try test__clzti2(0x06000000_00000000_00000000_00000000, 5); try test__clzti2(0x07000000_00000000_00000000_00000000, 5); try test__clzti2(0x08000000_00000000_00000000_00000000, 4); try test__clzti2(0x09000000_00000000_00000000_00000000, 4); try test__clzti2(0x0A000000_00000000_00000000_00000000, 4); try test__clzti2(0x0B000000_00000000_00000000_00000000, 4); try test__clzti2(0x0C000000_00000000_00000000_00000000, 4); try test__clzti2(0x0D000000_00000000_00000000_00000000, 4); try test__clzti2(0x0E000000_00000000_00000000_00000000, 4); try test__clzti2(0x0F000000_00000000_00000000_00000000, 4); try test__clzti2(0x10000000_00000000_00000000_00000000, 3); try test__clzti2(0x11000000_00000000_00000000_00000000, 3); try test__clzti2(0x12000000_00000000_00000000_00000000, 3); try test__clzti2(0x13000000_00000000_00000000_00000000, 3); try test__clzti2(0x14000000_00000000_00000000_00000000, 3); try test__clzti2(0x15000000_00000000_00000000_00000000, 3); try test__clzti2(0x16000000_00000000_00000000_00000000, 3); try test__clzti2(0x17000000_00000000_00000000_00000000, 3); try test__clzti2(0x18000000_00000000_00000000_00000000, 3); try test__clzti2(0x19000000_00000000_00000000_00000000, 3); try test__clzti2(0x1A000000_00000000_00000000_00000000, 3); try test__clzti2(0x1B000000_00000000_00000000_00000000, 3); try test__clzti2(0x1C000000_00000000_00000000_00000000, 3); try test__clzti2(0x1D000000_00000000_00000000_00000000, 3); try test__clzti2(0x1E000000_00000000_00000000_00000000, 3); try test__clzti2(0x1F000000_00000000_00000000_00000000, 3); try test__clzti2(0x20000000_00000000_00000000_00000000, 2); try test__clzti2(0x21000000_00000000_00000000_00000000, 2); try test__clzti2(0x22000000_00000000_00000000_00000000, 2); try test__clzti2(0x23000000_00000000_00000000_00000000, 2); try test__clzti2(0x24000000_00000000_00000000_00000000, 2); try test__clzti2(0x25000000_00000000_00000000_00000000, 2); try test__clzti2(0x26000000_00000000_00000000_00000000, 2); try test__clzti2(0x27000000_00000000_00000000_00000000, 2); try test__clzti2(0x28000000_00000000_00000000_00000000, 2); try test__clzti2(0x29000000_00000000_00000000_00000000, 2); try test__clzti2(0x2A000000_00000000_00000000_00000000, 2); try test__clzti2(0x2B000000_00000000_00000000_00000000, 2); try test__clzti2(0x2C000000_00000000_00000000_00000000, 2); try test__clzti2(0x2D000000_00000000_00000000_00000000, 2); try test__clzti2(0x2E000000_00000000_00000000_00000000, 2); try test__clzti2(0x2F000000_00000000_00000000_00000000, 2); try test__clzti2(0x30000000_00000000_00000000_00000000, 2); try test__clzti2(0x31000000_00000000_00000000_00000000, 2); try test__clzti2(0x32000000_00000000_00000000_00000000, 2); try test__clzti2(0x33000000_00000000_00000000_00000000, 2); try test__clzti2(0x34000000_00000000_00000000_00000000, 2); try test__clzti2(0x35000000_00000000_00000000_00000000, 2); try test__clzti2(0x36000000_00000000_00000000_00000000, 2); try test__clzti2(0x37000000_00000000_00000000_00000000, 2); try test__clzti2(0x38000000_00000000_00000000_00000000, 2); try test__clzti2(0x39000000_00000000_00000000_00000000, 2); try test__clzti2(0x3A000000_00000000_00000000_00000000, 2); try test__clzti2(0x3B000000_00000000_00000000_00000000, 2); try test__clzti2(0x3C000000_00000000_00000000_00000000, 2); try test__clzti2(0x3D000000_00000000_00000000_00000000, 2); try test__clzti2(0x3E000000_00000000_00000000_00000000, 2); try test__clzti2(0x3F000000_00000000_00000000_00000000, 2); try test__clzti2(0x40000000_00000000_00000000_00000000, 1); try test__clzti2(0x41000000_00000000_00000000_00000000, 1); try test__clzti2(0x42000000_00000000_00000000_00000000, 1); try test__clzti2(0x43000000_00000000_00000000_00000000, 1); try test__clzti2(0x44000000_00000000_00000000_00000000, 1); try test__clzti2(0x45000000_00000000_00000000_00000000, 1); try test__clzti2(0x46000000_00000000_00000000_00000000, 1); try test__clzti2(0x47000000_00000000_00000000_00000000, 1); try test__clzti2(0x48000000_00000000_00000000_00000000, 1); try test__clzti2(0x49000000_00000000_00000000_00000000, 1); try test__clzti2(0x4A000000_00000000_00000000_00000000, 1); try test__clzti2(0x4B000000_00000000_00000000_00000000, 1); try test__clzti2(0x4C000000_00000000_00000000_00000000, 1); try test__clzti2(0x4D000000_00000000_00000000_00000000, 1); try test__clzti2(0x4E000000_00000000_00000000_00000000, 1); try test__clzti2(0x4F000000_00000000_00000000_00000000, 1); try test__clzti2(0x50000000_00000000_00000000_00000000, 1); try test__clzti2(0x51000000_00000000_00000000_00000000, 1); try test__clzti2(0x52000000_00000000_00000000_00000000, 1); try test__clzti2(0x53000000_00000000_00000000_00000000, 1); try test__clzti2(0x54000000_00000000_00000000_00000000, 1); try test__clzti2(0x55000000_00000000_00000000_00000000, 1); try test__clzti2(0x56000000_00000000_00000000_00000000, 1); try test__clzti2(0x57000000_00000000_00000000_00000000, 1); try test__clzti2(0x58000000_00000000_00000000_00000000, 1); try test__clzti2(0x59000000_00000000_00000000_00000000, 1); try test__clzti2(0x5A000000_00000000_00000000_00000000, 1); try test__clzti2(0x5B000000_00000000_00000000_00000000, 1); try test__clzti2(0x5C000000_00000000_00000000_00000000, 1); try test__clzti2(0x5D000000_00000000_00000000_00000000, 1); try test__clzti2(0x5E000000_00000000_00000000_00000000, 1); try test__clzti2(0x5F000000_00000000_00000000_00000000, 1); try test__clzti2(0x60000000_00000000_00000000_00000000, 1); try test__clzti2(0x61000000_00000000_00000000_00000000, 1); try test__clzti2(0x62000000_00000000_00000000_00000000, 1); try test__clzti2(0x63000000_00000000_00000000_00000000, 1); try test__clzti2(0x64000000_00000000_00000000_00000000, 1); try test__clzti2(0x65000000_00000000_00000000_00000000, 1); try test__clzti2(0x66000000_00000000_00000000_00000000, 1); try test__clzti2(0x67000000_00000000_00000000_00000000, 1); try test__clzti2(0x68000000_00000000_00000000_00000000, 1); try test__clzti2(0x69000000_00000000_00000000_00000000, 1); try test__clzti2(0x6A000000_00000000_00000000_00000000, 1); try test__clzti2(0x6B000000_00000000_00000000_00000000, 1); try test__clzti2(0x6C000000_00000000_00000000_00000000, 1); try test__clzti2(0x6D000000_00000000_00000000_00000000, 1); try test__clzti2(0x6E000000_00000000_00000000_00000000, 1); try test__clzti2(0x6F000000_00000000_00000000_00000000, 1); try test__clzti2(0x70000000_00000000_00000000_00000000, 1); try test__clzti2(0x71000000_00000000_00000000_00000000, 1); try test__clzti2(0x72000000_00000000_00000000_00000000, 1); try test__clzti2(0x73000000_00000000_00000000_00000000, 1); try test__clzti2(0x74000000_00000000_00000000_00000000, 1); try test__clzti2(0x75000000_00000000_00000000_00000000, 1); try test__clzti2(0x76000000_00000000_00000000_00000000, 1); try test__clzti2(0x77000000_00000000_00000000_00000000, 1); try test__clzti2(0x78000000_00000000_00000000_00000000, 1); try test__clzti2(0x79000000_00000000_00000000_00000000, 1); try test__clzti2(0x7A000000_00000000_00000000_00000000, 1); try test__clzti2(0x7B000000_00000000_00000000_00000000, 1); try test__clzti2(0x7C000000_00000000_00000000_00000000, 1); try test__clzti2(0x7D000000_00000000_00000000_00000000, 1); try test__clzti2(0x7E000000_00000000_00000000_00000000, 1); try test__clzti2(0x7F000000_00000000_00000000_00000000, 1); try test__clzti2(0x80000000_00000000_00000000_00000000, 0); try test__clzti2(0x81000000_00000000_00000000_00000000, 0); try test__clzti2(0x82000000_00000000_00000000_00000000, 0); try test__clzti2(0x83000000_00000000_00000000_00000000, 0); try test__clzti2(0x84000000_00000000_00000000_00000000, 0); try test__clzti2(0x85000000_00000000_00000000_00000000, 0); try test__clzti2(0x86000000_00000000_00000000_00000000, 0); try test__clzti2(0x87000000_00000000_00000000_00000000, 0); try test__clzti2(0x88000000_00000000_00000000_00000000, 0); try test__clzti2(0x89000000_00000000_00000000_00000000, 0); try test__clzti2(0x8A000000_00000000_00000000_00000000, 0); try test__clzti2(0x8B000000_00000000_00000000_00000000, 0); try test__clzti2(0x8C000000_00000000_00000000_00000000, 0); try test__clzti2(0x8D000000_00000000_00000000_00000000, 0); try test__clzti2(0x8E000000_00000000_00000000_00000000, 0); try test__clzti2(0x8F000000_00000000_00000000_00000000, 0); try test__clzti2(0x90000000_00000000_00000000_00000000, 0); try test__clzti2(0x91000000_00000000_00000000_00000000, 0); try test__clzti2(0x92000000_00000000_00000000_00000000, 0); try test__clzti2(0x93000000_00000000_00000000_00000000, 0); try test__clzti2(0x94000000_00000000_00000000_00000000, 0); try test__clzti2(0x95000000_00000000_00000000_00000000, 0); try test__clzti2(0x96000000_00000000_00000000_00000000, 0); try test__clzti2(0x97000000_00000000_00000000_00000000, 0); try test__clzti2(0x98000000_00000000_00000000_00000000, 0); try test__clzti2(0x99000000_00000000_00000000_00000000, 0); try test__clzti2(0x9A000000_00000000_00000000_00000000, 0); try test__clzti2(0x9B000000_00000000_00000000_00000000, 0); try test__clzti2(0x9C000000_00000000_00000000_00000000, 0); try test__clzti2(0x9D000000_00000000_00000000_00000000, 0); try test__clzti2(0x9E000000_00000000_00000000_00000000, 0); try test__clzti2(0x9F000000_00000000_00000000_00000000, 0); try test__clzti2(0xA0000000_00000000_00000000_00000000, 0); try test__clzti2(0xA1000000_00000000_00000000_00000000, 0); try test__clzti2(0xA2000000_00000000_00000000_00000000, 0); try test__clzti2(0xA3000000_00000000_00000000_00000000, 0); try test__clzti2(0xA4000000_00000000_00000000_00000000, 0); try test__clzti2(0xA5000000_00000000_00000000_00000000, 0); try test__clzti2(0xA6000000_00000000_00000000_00000000, 0); try test__clzti2(0xA7000000_00000000_00000000_00000000, 0); try test__clzti2(0xA8000000_00000000_00000000_00000000, 0); try test__clzti2(0xA9000000_00000000_00000000_00000000, 0); try test__clzti2(0xAA000000_00000000_00000000_00000000, 0); try test__clzti2(0xAB000000_00000000_00000000_00000000, 0); try test__clzti2(0xAC000000_00000000_00000000_00000000, 0); try test__clzti2(0xAD000000_00000000_00000000_00000000, 0); try test__clzti2(0xAE000000_00000000_00000000_00000000, 0); try test__clzti2(0xAF000000_00000000_00000000_00000000, 0); try test__clzti2(0xB0000000_00000000_00000000_00000000, 0); try test__clzti2(0xB1000000_00000000_00000000_00000000, 0); try test__clzti2(0xB2000000_00000000_00000000_00000000, 0); try test__clzti2(0xB3000000_00000000_00000000_00000000, 0); try test__clzti2(0xB4000000_00000000_00000000_00000000, 0); try test__clzti2(0xB5000000_00000000_00000000_00000000, 0); try test__clzti2(0xB6000000_00000000_00000000_00000000, 0); try test__clzti2(0xB7000000_00000000_00000000_00000000, 0); try test__clzti2(0xB8000000_00000000_00000000_00000000, 0); try test__clzti2(0xB9000000_00000000_00000000_00000000, 0); try test__clzti2(0xBA000000_00000000_00000000_00000000, 0); try test__clzti2(0xBB000000_00000000_00000000_00000000, 0); try test__clzti2(0xBC000000_00000000_00000000_00000000, 0); try test__clzti2(0xBD000000_00000000_00000000_00000000, 0); try test__clzti2(0xBE000000_00000000_00000000_00000000, 0); try test__clzti2(0xBF000000_00000000_00000000_00000000, 0); try test__clzti2(0xC0000000_00000000_00000000_00000000, 0); try test__clzti2(0xC1000000_00000000_00000000_00000000, 0); try test__clzti2(0xC2000000_00000000_00000000_00000000, 0); try test__clzti2(0xC3000000_00000000_00000000_00000000, 0); try test__clzti2(0xC4000000_00000000_00000000_00000000, 0); try test__clzti2(0xC5000000_00000000_00000000_00000000, 0); try test__clzti2(0xC6000000_00000000_00000000_00000000, 0); try test__clzti2(0xC7000000_00000000_00000000_00000000, 0); try test__clzti2(0xC8000000_00000000_00000000_00000000, 0); try test__clzti2(0xC9000000_00000000_00000000_00000000, 0); try test__clzti2(0xCA000000_00000000_00000000_00000000, 0); try test__clzti2(0xCB000000_00000000_00000000_00000000, 0); try test__clzti2(0xCC000000_00000000_00000000_00000000, 0); try test__clzti2(0xCD000000_00000000_00000000_00000000, 0); try test__clzti2(0xCE000000_00000000_00000000_00000000, 0); try test__clzti2(0xCF000000_00000000_00000000_00000000, 0); try test__clzti2(0xD0000000_00000000_00000000_00000000, 0); try test__clzti2(0xD1000000_00000000_00000000_00000000, 0); try test__clzti2(0xD2000000_00000000_00000000_00000000, 0); try test__clzti2(0xD3000000_00000000_00000000_00000000, 0); try test__clzti2(0xD4000000_00000000_00000000_00000000, 0); try test__clzti2(0xD5000000_00000000_00000000_00000000, 0); try test__clzti2(0xD6000000_00000000_00000000_00000000, 0); try test__clzti2(0xD7000000_00000000_00000000_00000000, 0); try test__clzti2(0xD8000000_00000000_00000000_00000000, 0); try test__clzti2(0xD9000000_00000000_00000000_00000000, 0); try test__clzti2(0xDA000000_00000000_00000000_00000000, 0); try test__clzti2(0xDB000000_00000000_00000000_00000000, 0); try test__clzti2(0xDC000000_00000000_00000000_00000000, 0); try test__clzti2(0xDD000000_00000000_00000000_00000000, 0); try test__clzti2(0xDE000000_00000000_00000000_00000000, 0); try test__clzti2(0xDF000000_00000000_00000000_00000000, 0); try test__clzti2(0xE0000000_00000000_00000000_00000000, 0); try test__clzti2(0xE1000000_00000000_00000000_00000000, 0); try test__clzti2(0xE2000000_00000000_00000000_00000000, 0); try test__clzti2(0xE3000000_00000000_00000000_00000000, 0); try test__clzti2(0xE4000000_00000000_00000000_00000000, 0); try test__clzti2(0xE5000000_00000000_00000000_00000000, 0); try test__clzti2(0xE6000000_00000000_00000000_00000000, 0); try test__clzti2(0xE7000000_00000000_00000000_00000000, 0); try test__clzti2(0xE8000000_00000000_00000000_00000000, 0); try test__clzti2(0xE9000000_00000000_00000000_00000000, 0); try test__clzti2(0xEA000000_00000000_00000000_00000000, 0); try test__clzti2(0xEB000000_00000000_00000000_00000000, 0); try test__clzti2(0xEC000000_00000000_00000000_00000000, 0); try test__clzti2(0xED000000_00000000_00000000_00000000, 0); try test__clzti2(0xEE000000_00000000_00000000_00000000, 0); try test__clzti2(0xEF000000_00000000_00000000_00000000, 0); try test__clzti2(0xF0000000_00000000_00000000_00000000, 0); try test__clzti2(0xF1000000_00000000_00000000_00000000, 0); try test__clzti2(0xF2000000_00000000_00000000_00000000, 0); try test__clzti2(0xF3000000_00000000_00000000_00000000, 0); try test__clzti2(0xF4000000_00000000_00000000_00000000, 0); try test__clzti2(0xF5000000_00000000_00000000_00000000, 0); try test__clzti2(0xF6000000_00000000_00000000_00000000, 0); try test__clzti2(0xF7000000_00000000_00000000_00000000, 0); try test__clzti2(0xF8000000_00000000_00000000_00000000, 0); try test__clzti2(0xF9000000_00000000_00000000_00000000, 0); try test__clzti2(0xFA000000_00000000_00000000_00000000, 0); try test__clzti2(0xFB000000_00000000_00000000_00000000, 0); try test__clzti2(0xFC000000_00000000_00000000_00000000, 0); try test__clzti2(0xFD000000_00000000_00000000_00000000, 0); try test__clzti2(0xFE000000_00000000_00000000_00000000, 0); try test__clzti2(0xFF000000_00000000_00000000_00000000, 0); try test__clzti2(0x00000000_00000000_00000000_00000000, 128); try test__clzti2(0x00000000_00000000_00000000_00000001, 127); try test__clzti2(0x00000000_00000000_00000000_00000002, 126); try test__clzti2(0x00000000_00000000_00000000_00000004, 125); try test__clzti2(0x00000000_00000000_00000000_00000008, 124); try test__clzti2(0x00000000_00000000_00000000_00000010, 123); try test__clzti2(0x00000000_00000000_00000000_00000020, 122); try test__clzti2(0x00000000_00000000_00000000_00000040, 121); try test__clzti2(0x00000000_00000000_00000000_00000080, 120); try test__clzti2(0x00000000_00000000_00000000_00000100, 119); try test__clzti2(0x00000000_00000000_00000000_00000200, 118); try test__clzti2(0x00000000_00000000_00000000_00000400, 117); try test__clzti2(0x00000000_00000000_00000000_00000800, 116); try test__clzti2(0x00000000_00000000_00000000_00001000, 115); try test__clzti2(0x00000000_00000000_00000000_00002000, 114); try test__clzti2(0x00000000_00000000_00000000_00004000, 113); try test__clzti2(0x00000000_00000000_00000000_00008000, 112); try test__clzti2(0x00000000_00000000_00000000_00010000, 111); try test__clzti2(0x00000000_00000000_00000000_00020000, 110); try test__clzti2(0x00000000_00000000_00000000_00040000, 109); try test__clzti2(0x00000000_00000000_00000000_00080000, 108); try test__clzti2(0x00000000_00000000_00000000_00100000, 107); try test__clzti2(0x00000000_00000000_00000000_00200000, 106); try test__clzti2(0x00000000_00000000_00000000_00400000, 105); try test__clzti2(0x00000000_00000000_00000000_00800000, 104); try test__clzti2(0x00000000_00000000_00000000_01000000, 103); try test__clzti2(0x00000000_00000000_00000000_02000000, 102); try test__clzti2(0x00000000_00000000_00000000_04000000, 101); try test__clzti2(0x00000000_00000000_00000000_08000000, 100); try test__clzti2(0x00000000_00000000_00000000_10000000, 99); try test__clzti2(0x00000000_00000000_00000000_20000000, 98); try test__clzti2(0x00000000_00000000_00000000_40000000, 97); try test__clzti2(0x00000000_00000000_00000000_80000000, 96); try test__clzti2(0x00000000_00000000_00000001_00000000, 95); try test__clzti2(0x00000000_00000000_00000002_00000000, 94); try test__clzti2(0x00000000_00000000_00000004_00000000, 93); try test__clzti2(0x00000000_00000000_00000008_00000000, 92); try test__clzti2(0x00000000_00000000_00000010_00000000, 91); try test__clzti2(0x00000000_00000000_00000020_00000000, 90); try test__clzti2(0x00000000_00000000_00000040_00000000, 89); try test__clzti2(0x00000000_00000000_00000080_00000000, 88); try test__clzti2(0x00000000_00000000_00000100_00000000, 87); try test__clzti2(0x00000000_00000000_00000200_00000000, 86); try test__clzti2(0x00000000_00000000_00000400_00000000, 85); try test__clzti2(0x00000000_00000000_00000800_00000000, 84); try test__clzti2(0x00000000_00000000_00001000_00000000, 83); try test__clzti2(0x00000000_00000000_00002000_00000000, 82); try test__clzti2(0x00000000_00000000_00004000_00000000, 81); try test__clzti2(0x00000000_00000000_00008000_00000000, 80); try test__clzti2(0x00000000_00000000_00010000_00000000, 79); try test__clzti2(0x00000000_00000000_00020000_00000000, 78); try test__clzti2(0x00000000_00000000_00040000_00000000, 77); try test__clzti2(0x00000000_00000000_00080000_00000000, 76); try test__clzti2(0x00000000_00000000_00100000_00000000, 75); try test__clzti2(0x00000000_00000000_00200000_00000000, 74); try test__clzti2(0x00000000_00000000_00400000_00000000, 73); try test__clzti2(0x00000000_00000000_00800000_00000000, 72); try test__clzti2(0x00000000_00000000_01000000_00000000, 71); try test__clzti2(0x00000000_00000000_02000000_00000000, 70); try test__clzti2(0x00000000_00000000_04000000_00000000, 69); try test__clzti2(0x00000000_00000000_08000000_00000000, 68); try test__clzti2(0x00000000_00000000_10000000_00000000, 67); try test__clzti2(0x00000000_00000000_20000000_00000000, 66); try test__clzti2(0x00000000_00000000_40000000_00000000, 65); try test__clzti2(0x00000000_00000000_80000000_00000000, 64); try test__clzti2(0x00000000_00000001_00000000_00000000, 63); try test__clzti2(0x00000000_00000002_00000000_00000000, 62); try test__clzti2(0x00000000_00000004_00000000_00000000, 61); try test__clzti2(0x00000000_00000008_00000000_00000000, 60); try test__clzti2(0x00000000_00000010_00000000_00000000, 59); try test__clzti2(0x00000000_00000020_00000000_00000000, 58); try test__clzti2(0x00000000_00000040_00000000_00000000, 57); try test__clzti2(0x00000000_00000080_00000000_00000000, 56); try test__clzti2(0x00000000_00000100_00000000_00000000, 55); try test__clzti2(0x00000000_00000200_00000000_00000000, 54); try test__clzti2(0x00000000_00000400_00000000_00000000, 53); try test__clzti2(0x00000000_00000800_00000000_00000000, 52); try test__clzti2(0x00000000_00001000_00000000_00000000, 51); try test__clzti2(0x00000000_00002000_00000000_00000000, 50); try test__clzti2(0x00000000_00004000_00000000_00000000, 49); try test__clzti2(0x00000000_00008000_00000000_00000000, 48); try test__clzti2(0x00000000_00010000_00000000_00000000, 47); try test__clzti2(0x00000000_00020000_00000000_00000000, 46); try test__clzti2(0x00000000_00040000_00000000_00000000, 45); try test__clzti2(0x00000000_00080000_00000000_00000000, 44); try test__clzti2(0x00000000_00100000_00000000_00000000, 43); try test__clzti2(0x00000000_00200000_00000000_00000000, 42); try test__clzti2(0x00000000_00400000_00000000_00000000, 41); try test__clzti2(0x00000000_00800000_00000000_00000000, 40); try test__clzti2(0x00000000_01000000_00000000_00000000, 39); try test__clzti2(0x00000000_02000000_00000000_00000000, 38); try test__clzti2(0x00000000_04000000_00000000_00000000, 37); try test__clzti2(0x00000000_08000000_00000000_00000000, 36); try test__clzti2(0x00000000_10000000_00000000_00000000, 35); try test__clzti2(0x00000000_20000000_00000000_00000000, 34); try test__clzti2(0x00000000_40000000_00000000_00000000, 33); try test__clzti2(0x00000000_80000000_00000000_00000000, 32); try test__clzti2(0x00000001_00000000_00000000_00000000, 31); try test__clzti2(0x00000002_00000000_00000000_00000000, 30); try test__clzti2(0x00000004_00000000_00000000_00000000, 29); try test__clzti2(0x00000008_00000000_00000000_00000000, 28); try test__clzti2(0x00000010_00000000_00000000_00000000, 27); try test__clzti2(0x00000020_00000000_00000000_00000000, 26); try test__clzti2(0x00000040_00000000_00000000_00000000, 25); try test__clzti2(0x00000080_00000000_00000000_00000000, 24); try test__clzti2(0x00000100_00000000_00000000_00000000, 23); try test__clzti2(0x00000200_00000000_00000000_00000000, 22); try test__clzti2(0x00000400_00000000_00000000_00000000, 21); try test__clzti2(0x00000800_00000000_00000000_00000000, 20); try test__clzti2(0x00001000_00000000_00000000_00000000, 19); try test__clzti2(0x00002000_00000000_00000000_00000000, 18); try test__clzti2(0x00004000_00000000_00000000_00000000, 17); try test__clzti2(0x00008000_00000000_00000000_00000000, 16); try test__clzti2(0x00010000_00000000_00000000_00000000, 15); try test__clzti2(0x00020000_00000000_00000000_00000000, 14); try test__clzti2(0x00040000_00000000_00000000_00000000, 13); try test__clzti2(0x00080000_00000000_00000000_00000000, 12); try test__clzti2(0x00100000_00000000_00000000_00000000, 11); try test__clzti2(0x00200000_00000000_00000000_00000000, 10); try test__clzti2(0x00400000_00000000_00000000_00000000, 9); }
lib/std/special/compiler_rt/clzti2_test.zig
const std = @import("std"); const meta = std.meta; const trait = meta.trait; const Allocator = std.mem.Allocator; const testing = std.testing; const assert = std.debug.assert; const mustache = @import("../mustache.zig"); const RenderOptions = mustache.options.RenderOptions; /// Partials map from a comptime known type /// It works like a HashMap, but can be initialized from a tuple, slice or Hashmap pub fn PartialsMap(comptime TPartials: type, comptime options: RenderOptions) type { return struct { const Self = @This(); pub const options: RenderOptions = options; pub const Template = switch (options) { .Template => mustache.Template, .Text, .File => []const u8, }; pub fn isEmpty() bool { comptime { return TPartials == void or (trait.isTuple(TPartials) and meta.fields(TPartials).len == 0); } } allocator: if (options != .Template and !isEmpty()) Allocator else void, partials: TPartials, pub usingnamespace switch (options) { .Template => struct { pub fn init(partials: TPartials) Self { return .{ .allocator = {}, .partials = partials, }; } }, .Text, .File => struct { pub fn init(allocator: Allocator, partials: TPartials) Self { return .{ .allocator = if (comptime isEmpty()) {} else allocator, .partials = partials, }; } }, }; pub fn get(self: Self, key: []const u8) ?Self.Template { comptime validatePartials(); if (comptime isValidTuple()) { return self.getFromTuple(key); } else if (comptime isValidIndexable()) { return self.getFromIndexable(key); } else if (comptime isValidMap()) { return self.getFromMap(key); } else if (comptime isEmpty()) { return null; } else { unreachable; } } fn getFromTuple(self: Self, key: []const u8) ?Self.Template { comptime assert(isValidTuple()); if (comptime isPartialsTupleElement(TPartials)) { return if (std.mem.eql(u8, self.partials.@"0", key)) self.partials.@"1" else null; } else { inline for (meta.fields(TPartials)) |_, index| { const item = self.partials[index]; if (std.mem.eql(u8, item.@"0", key)) return item.@"1"; } else { return null; } } } fn getFromIndexable(self: Self, key: []const u8) ?Self.Template { comptime assert(isValidIndexable()); for (self.partials) |item| { if (std.mem.eql(u8, item[0], key)) return item[1]; } return null; } inline fn getFromMap(self: Self, key: []const u8) ?Self.Template { comptime assert(isValidMap()); return self.partials.get(key); } fn validatePartials() void { comptime { if (!isValidTuple() and !isValidIndexable() and !isValidMap() and !isEmpty()) @compileError( std.fmt.comptimePrint( \\Invalid Partials type. \\Expected a HashMap or a tuple containing Key/Value pairs \\Key="[]const u8" and Value="{s}" \\Found: "{s}" , .{ @typeName(Self.Template), @typeName(TPartials) }), ); } } fn isValidTuple() bool { comptime { if (trait.isTuple(TPartials)) { if (isPartialsTupleElement(TPartials)) { return true; } else { inline for (meta.fields(TPartials)) |field| { if (!isPartialsTupleElement(field.field_type)) { return false; } } else { return true; } } } return false; } } fn isValidIndexable() bool { comptime { if (trait.isIndexable(TPartials) and !trait.isTuple(TPartials)) { if (trait.isSingleItemPtr(TPartials) and trait.is(.Array)(meta.Child(TPartials))) { const Array = meta.Child(TPartials); return isPartialsTupleElement(meta.Child(Array)); } else { return isPartialsTupleElement(meta.Child(TPartials)); } } return false; } } fn isPartialsTupleElement(comptime TElement: type) bool { comptime { if (trait.isTuple(TElement)) { const fields = meta.fields(TElement); if (fields.len == 2 and trait.isZigString(fields[0].field_type)) { if (fields[1].field_type == Self.Template) { return true; } else { return trait.isZigString(fields[1].field_type) and trait.isZigString(Self.Template); } } } return false; } } fn isValidMap() bool { comptime { if (trait.is(.Struct)(TPartials) and trait.hasDecls(TPartials, .{ "KV", "get" })) { const KV = @field(TPartials, "KV"); if (trait.is(.Struct)(KV) and trait.hasFields(KV, .{ "key", "value" })) { const kv: KV = undefined; return trait.isZigString(@TypeOf(kv.key)) and (@TypeOf(kv.value) == Self.Template or (trait.isZigString(@TypeOf(kv.value)) and trait.isZigString(Self.Template))); } } return false; } } }; } test "Map single tuple" { var data = .{ "hello", "{{hello}}world" }; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); const hello = map.get("hello"); try testing.expect(hello != null); try testing.expectEqualStrings("{{hello}}world", hello.?); try testing.expect(map.get("wrong") == null); } test "Map empty tuple" { var data = .{}; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); try testing.expect(map.get("wrong") == null); } test "Map void" { var data = {}; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); try testing.expect(map.get("wrong") == null); } test "Map multiple tuple" { var data = .{ .{ "hello", "{{hello}}world" }, .{ "hi", "{{hi}}there" }, }; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); const hello = map.get("hello"); try testing.expect(hello != null); try testing.expectEqualStrings("{{hello}}world", hello.?); const hi = map.get("hi"); try testing.expect(hi != null); try testing.expectEqualStrings("{{hi}}there", hi.?); try testing.expect(map.get("wrong") == null); } test "Map array" { const Tuple = meta.Tuple(&.{ []const u8, []const u8 }); var data = [_]Tuple{ .{ "hello", "{{hello}}world" }, .{ "hi", "{{hi}}there" }, }; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); const hello = map.get("hello"); try testing.expect(hello != null); try testing.expectEqualStrings("{{hello}}world", hello.?); const hi = map.get("hi"); try testing.expect(hi != null); try testing.expectEqualStrings("{{hi}}there", hi.?); try testing.expect(map.get("wrong") == null); } test "Map ref array" { const Tuple = meta.Tuple(&.{ []const u8, []const u8 }); var data = &[_]Tuple{ .{ "hello", "{{hello}}world" }, .{ "hi", "{{hi}}there" }, }; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); const hello = map.get("hello"); try testing.expect(hello != null); try testing.expectEqualStrings("{{hello}}world", hello.?); const hi = map.get("hi"); try testing.expect(hi != null); try testing.expectEqualStrings("{{hi}}there", hi.?); try testing.expect(map.get("wrong") == null); } test "Map slice" { const Tuple = meta.Tuple(&.{ []const u8, []const u8 }); const array = [_]Tuple{ .{ "hello", "{{hello}}world" }, .{ "hi", "{{hi}}there" }, }; const data = array[0..]; const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); const hello = map.get("hello"); try testing.expect(hello != null); try testing.expectEqualStrings("{{hello}}world", hello.?); const hi = map.get("hi"); try testing.expect(hi != null); try testing.expectEqualStrings("{{hi}}there", hi.?); try testing.expect(map.get("wrong") == null); } test "Map hashmap" { var data = std.StringHashMap([]const u8).init(testing.allocator); defer data.deinit(); try data.put("hello", "{{hello}}world"); try data.put("hi", "{{hi}}there"); const dummy_options = RenderOptions{ .Text = .{} }; const DummyMap = PartialsMap(@TypeOf(data), dummy_options); var map = DummyMap.init(testing.allocator, data); const hello = map.get("hello"); try testing.expect(hello != null); try testing.expectEqualStrings("{{hello}}world", hello.?); const hi = map.get("hi"); try testing.expect(hi != null); try testing.expectEqualStrings("{{hi}}there", hi.?); try testing.expect(map.get("wrong") == null); }
src/rendering/partials_map.zig
const std = @import("std"); const serialize = @import("main.zig").serialize; const expect = std.testing.expect; const eql = std.mem.eql; const readIntSliceBig = std.mem.readIntSliceBig; const ArrayList = std.ArrayList; const hasFn = std.meta.trait.hasFn; const implementsDecodeRLP = hasFn("decodeRLP"); const rlpByteListShortHeader = 128; const rlpByteListLongHeader = 183; const rlpListShortHeader = 192; const rlpListLongHeader = 247; // When reading the payload, leading zeros are removed, so there might be a // difference in byte-size between the number of bytes and the target integer. // If so, the bytes have to be extracted into a temporary value. inline fn safeReadSliceIntBig(comptime T: type, payload: []const u8, out: *T) void { // compile time constat to activate the first branch. If // @sizeOf(T) > 1, then it is possible (and necessary) to // shift temp. const log2tgt1 = (@sizeOf(T) > 1); if (log2tgt1 and @sizeOf(T) > payload.len) { var temp: T = 0; var i: usize = 0; while (i < payload.len) : (i += 1) { temp = @shlExact(temp, 8); // payload.len < @sizeOf(T), should not overflow temp |= @as(T, payload[i]); } out.* = temp; } else { out.* = readIntSliceBig(T, payload[0..]); } } // Returns the amount of data consumed from `serialized`. pub fn deserialize(comptime T: type, serialized: []const u8, out: *T) !usize { if (comptime implementsDecodeRLP(T)) { return out.decodeRLP(serialized); } const info = @typeInfo(T); return switch (info) { .Int => { if (serialized[0] < rlpByteListShortHeader) { out.* = serialized[0]; return 1; // consumed the byte } else if (serialized[0] < rlpByteListLongHeader) { // Recover the payload size from the header. const size = @as(usize, serialized[0] - rlpByteListShortHeader); // Special case: empty value, return 0 if (size == 0) { return 1; // consumed the header } if (size > serialized.len + 1) { return error.EOF; } safeReadSliceIntBig(T, serialized[1 .. 1 + size], out); return 1 + size; } else { const size_size = @as(usize, serialized[0] - rlpByteListLongHeader); const size = readIntSliceBig(usize, serialized[1 .. 1 + size_size]); safeReadSliceIntBig(T, serialized[1 + size_size ..], out); return 1 + size_size + size; } }, .Struct => |struc| { if (serialized.len == 0) { return error.EOF; } // A structure is encoded as a list, not // a bitstring. if (serialized[0] < rlpListShortHeader) { return error.NotAnRLPList; } var size: usize = undefined; var offset: usize = 1; if (serialized[0] < rlpListLongHeader) { size = @as(usize, serialized[0] - rlpListShortHeader); } else { const size_size = @as(usize, serialized[0] - rlpListLongHeader); offset += size_size; size = readIntSliceBig(usize, serialized[1..]) / std.math.pow(usize, 256, 8 - size_size); } inline for (struc.fields) |field| { offset += try deserialize(field.field_type, serialized[offset..], &@field(out.*, field.name)); } return offset; }, .Pointer => |ptr| switch (ptr.size) { .Slice => if (ptr.child == u8) { if (serialized[0] < rlpByteListShortHeader) { out.* = serialized[0..1]; return 1; } else if (serialized[0] < rlpByteListLongHeader) { const size = @as(usize, serialized[0] - rlpByteListShortHeader); out.* = serialized[1 .. 1 + size]; return 1 + size; } else { const size_size = @as(usize, serialized[0] - rlpByteListLongHeader); const size = readIntSliceBig(usize, serialized[1 .. 1 + size_size]); out.* = serialized[1 + size_size .. 1 + size_size + size]; return 1 + size + size_size; } } else { if (serialized[0] < rlpByteListShortHeader) { return try deserialize(ptr.child, serialized[0..1], &out.*[0]); } else if (serialized[0] < rlpByteListLongHeader) { const size = @as(usize, serialized[0] - rlpByteListShortHeader); var i: usize = 0; while (i < size) : (i += 1) { i += try deserialize(ptr.child, serialized[1 + i ..], &out.*[i]); } return 1 + size; } else { const size_size = @as(usize, serialized[0] - rlpByteListLongHeader); var size = readIntSliceBig(usize, serialized[1..]) / std.math.pow(usize, 256, 8 - size_size); var i: usize = 0; while (i + 1 < size) : (i += 1) { i += try deserialize(ptr.child, serialized[1 + size_size + i ..], &out.*[i]); } return 1 + size + size_size; } }, else => return error.UnSupportedType, }, .Array => |ary| if (@sizeOf(ary.child) == 1) { if (serialized[0] < rlpByteListShortHeader) { out.*[0] = serialized[0]; return 1; } else if (serialized[0] < rlpByteListLongHeader) { const size = @as(usize, serialized[0] - rlpByteListShortHeader); // The target might be larger than the payload, as 0s are not // stored in the RLP encoding. if (size > out.len) return error.InvalidArrayLength; std.mem.copy(u8, out.*[0..], serialized[1 .. 1 + size]); return 1 + size; } else { const size_size = @as(usize, serialized[0] - rlpByteListLongHeader); const size = readIntSliceBig(usize, serialized[1 .. 1 + size_size]); if (size != out.len) { return error.InvalidArrayLength; } std.mem.copy(u8, out.*[0..], serialized[1 + size_size .. 1 + size_size + size]); return 1 + size + size_size; } } else return error.UnsupportedType, .Optional => |opt| { if (serialized[0] == 0x80) { out.* = null; return 1; } else { var t: opt.child = undefined; const offset = try deserialize(opt.child, serialized[0..], &t); out.* = t; return offset; } }, else => return error.UnsupportedType, }; } test "deserialize an integer" { var consumed: usize = 0; const su8lo = [_]u8{42}; var u8lo: u8 = undefined; consumed = try deserialize(u8, su8lo[0..], &u8lo); try expect(u8lo == 42); try expect(consumed == 1); const su8hi = [_]u8{ 129, 192 }; var u8hi: u8 = undefined; consumed = try deserialize(u8, su8hi[0..], &u8hi); try expect(u8hi == 192); try expect(consumed == su8hi.len); const su16small = [_]u8{ 129, 192 }; var u16small: u16 = undefined; consumed = try deserialize(u16, su16small[0..], &u16small); try expect(u16small == 192); try expect(consumed == su16small.len); const su16long = [_]u8{ 130, 192, 192 }; var u16long: u16 = undefined; consumed = try deserialize(u16, su16long[0..], &u16long); try expect(u16long == 0xc0c0); try expect(consumed == su16long.len); } test "deserialize a structure" { const Person = struct { age: u8, name: []const u8, }; const jc = Person{ .age = 123, .name = "<NAME>" }; var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try serialize(Person, jc, &list); var p: Person = undefined; const consumed = try deserialize(Person, list.items[0..], &p); try expect(consumed == list.items.len); try expect(p.age == jc.age); try expect(eql(u8, p.name, jc.name)); } test "deserialize a string" { const str = "abc"; var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try serialize([]const u8, str, &list); var s: []const u8 = undefined; const consumed = try deserialize([]const u8, list.items[0..], &s); try expect(eql(u8, str, s)); try expect(consumed == list.items.len); } test "deserialize a byte array" { const expected = [_]u8{ 1, 2, 3 }; var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); try serialize(@TypeOf(expected), expected, &list); var out: [3]u8 = undefined; const consumed = try deserialize([3]u8, list.items[0..], &out); try expect(eql(u8, expected[0..], out[0..])); try expect(consumed == list.items.len); } const RLPDecodablePerson = struct { name: []const u8, age: u8, pub fn decodeRLP(self: *RLPDecodablePerson, serialized: []const u8) !usize { if (serialized.len == 0) { return error.EOF; } self.age = serialized[0]; self.name = "freshly deserialized person"; return 1; } }; test "deserialize with custom serializer" { var person: RLPDecodablePerson = undefined; const serialized = [_]u8{42}; const consumed = try deserialize(RLPDecodablePerson, serialized[0..], &person); try expect(person.age == serialized[0]); try expect(consumed == 1); } test "deserialize an optional" { var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); var x: ?u32 = null; try serialize(?u32, x, &list); var y: ?u32 = undefined; _ = try deserialize(?u32, list.items, &y); try expect(y == null); list.clearAndFree(); x = 32; var z: ?u32 = undefined; try serialize(?u32, x, &list); _ = try deserialize(?u32, list.items, &z); try expect(z.? == x.?); }
src/deserialize.zig
const zang = @import("zang"); const note_frequencies = @import("zang-12tet"); const common = @import("common.zig"); const c = @import("common/c.zig"); pub const AUDIO_FORMAT: zang.AudioFormat = .signed16_lsb; pub const AUDIO_SAMPLE_RATE = 48000; pub const AUDIO_BUFFER_SIZE = 1024; pub const DESCRIPTION = \\example_subsong \\ \\Play with the keyboard - a little melody is played \\with each keypress. This demonstrates "notes within \\notes". ; const a4 = 440.0; const InnerInstrument = struct { pub const num_outputs = 1; pub const num_temps = 2; pub const Params = struct { sample_rate: f32, freq: f32, note_on: bool, }; osc: zang.TriSawOsc, env: zang.Envelope, fn init() InnerInstrument { return .{ .osc = zang.TriSawOsc.init(), .env = zang.Envelope.init(), }; } fn paint( self: *InnerInstrument, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { zang.zero(span, temps[0]); self.osc.paint(span, .{temps[0]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .freq = zang.constant(params.freq), .color = 0.0, }); zang.zero(span, temps[1]); self.env.paint(span, .{temps[1]}, .{}, note_id_changed, .{ .sample_rate = params.sample_rate, .attack = .{ .cubed = 0.025 }, .decay = .{ .cubed = 0.1 }, .release = .{ .cubed = 0.15 }, .sustain_volume = 0.5, .note_on = params.note_on, }); zang.multiply(span, outputs[0], temps[0], temps[1]); } }; const MyNoteParams = struct { freq: f32, note_on: bool, }; fn makeNote( t: f32, id: usize, freq: f32, note_on: bool, ) zang.Notes(MyNoteParams).SongEvent { return .{ .t = 0.1 * t, .note_id = id, .params = .{ .freq = freq, .note_on = note_on }, }; } // an example of a custom "module" const SubtrackPlayer = struct { pub const num_outputs = 1; pub const num_temps = 2; pub const Params = struct { sample_rate: f32, freq: f32, note_on: bool, }; pub const BaseFrequency = a4 * note_frequencies.c4; tracker: zang.Notes(MyNoteParams).NoteTracker, instr: InnerInstrument, trigger: zang.Trigger(MyNoteParams), fn init() SubtrackPlayer { const Notes = zang.Notes(MyNoteParams); const f = note_frequencies; return .{ .tracker = Notes.NoteTracker.init(&[_]Notes.SongEvent{ comptime makeNote(0.0, 1, a4 * f.c4, true), comptime makeNote(1.0, 2, a4 * f.ab3, true), comptime makeNote(2.0, 3, a4 * f.g3, true), comptime makeNote(3.0, 4, a4 * f.eb3, true), comptime makeNote(4.0, 5, a4 * f.c3, true), comptime makeNote(5.0, 5, a4 * f.c3, false), }), .instr = InnerInstrument.init(), .trigger = zang.Trigger(MyNoteParams).init(), }; } fn paint( self: *SubtrackPlayer, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, note_id_changed: bool, params: Params, ) void { if (params.note_on and note_id_changed) { self.tracker.reset(); self.trigger.reset(); } const iap = self.tracker.consume(params.sample_rate, span.end - span.start); var ctr = self.trigger.counter(span, iap); while (self.trigger.next(&ctr)) |result| { const new_note = (params.note_on and note_id_changed) or result.note_id_changed; self.instr.paint(result.span, outputs, temps, new_note, .{ .sample_rate = params.sample_rate, .freq = result.params.freq * params.freq / BaseFrequency, .note_on = result.params.note_on, }); } } }; pub const MainModule = struct { pub const num_outputs = 1; pub const num_temps = 2; pub const output_audio = common.AudioOut{ .mono = 0 }; pub const output_visualize = 0; key: ?i32, iq: zang.Notes(SubtrackPlayer.Params).ImpulseQueue, idgen: zang.IdGenerator, player: SubtrackPlayer, trigger: zang.Trigger(SubtrackPlayer.Params), pub fn init() MainModule { return .{ .key = null, .iq = zang.Notes(SubtrackPlayer.Params).ImpulseQueue.init(), .idgen = zang.IdGenerator.init(), .player = SubtrackPlayer.init(), .trigger = zang.Trigger(SubtrackPlayer.Params).init(), }; } pub fn paint( self: *MainModule, span: zang.Span, outputs: [num_outputs][]f32, temps: [num_temps][]f32, ) void { var ctr = self.trigger.counter(span, self.iq.consume()); while (self.trigger.next(&ctr)) |result| { self.player.paint( result.span, outputs, temps, result.note_id_changed, result.params, ); } } pub fn keyEvent(self: *MainModule, key: i32, down: bool, impulse_frame: usize) bool { if (common.getKeyRelFreq(key)) |rel_freq| { if (down or (if (self.key) |nh| nh == key else false)) { self.key = if (down) key else null; self.iq.push(impulse_frame, self.idgen.nextId(), .{ .sample_rate = AUDIO_SAMPLE_RATE, .freq = a4 * rel_freq, .note_on = down, }); } return true; } return false; } };
examples/example_subsong.zig
const std = @import("std"); const Header = @import("lsmtree").Header; const headerSize = @import("lsmtree").headerSize; const expectEqual = std.testing.expectEqual; const Error = error{ InputArrayTooSmall, OutputArrayTooSmall, NoLastKeyOffsetFound }; pub fn toBytes(h: *Header, buf: []u8) !usize { if (buf.len < headerSize()) { return Error.OutputArrayTooSmall; } var offset: usize = 0; std.mem.writeIntSliceLittle(@TypeOf(h.magic_number), buf[offset .. offset + @sizeOf(@TypeOf(h.magic_number))], h.magic_number); offset += @sizeOf(@TypeOf(h.magic_number)); std.mem.writeIntSliceLittle(@TypeOf(h.first_key_offset), buf[offset .. offset + @sizeOf(@TypeOf(h.first_key_offset))], h.first_key_offset); offset += @sizeOf(@TypeOf(h.first_key_offset)); std.mem.writeIntSliceLittle(@TypeOf(h.last_key_offset), buf[offset .. offset + @sizeOf(@TypeOf(h.last_key_offset))], h.last_key_offset); offset += @sizeOf(@TypeOf(h.last_key_offset)); std.mem.copy(u8, buf[offset .. offset + @sizeOf(@TypeOf(h.reserved))], h.reserved[0..]); offset += @sizeOf(@TypeOf(h.reserved)); std.mem.writeIntSliceLittle(@TypeOf(h.total_records), buf[offset .. offset + @sizeOf(@TypeOf(h.total_records))], h.total_records); offset += @sizeOf(@TypeOf(h.total_records)); return offset; } pub fn fromBytes(buf: []u8) !Header { if (buf.len < headerSize()) { return Error.InputArrayTooSmall; } //Magic number var magic = buf[0]; var offset: usize = 1; // offset of the first key in the "keys" chunk. var first_key = std.mem.readIntSliceLittle(usize, buf[offset .. offset + @sizeOf(usize)]); offset += @sizeOf(usize); // offset of the last key in the "keys" chunk. var last_key = std.mem.readIntSliceLittle(usize, buf[offset .. offset + @sizeOf(usize)]); offset += @sizeOf(usize); var header = Header{ .total_records = 0, .reserved = undefined, .last_key_offset = last_key, .first_key_offset = first_key, .magic_number = magic, }; // reserved space std.mem.copy(u8, header.reserved[0..], buf[offset .. offset + @sizeOf(@TypeOf(header.reserved))]); offset += @sizeOf(@TypeOf(header.reserved)); // total records var total_records = std.mem.readIntSliceLittle(usize, buf[offset .. offset + @sizeOf(usize)]); header.total_records = total_records; return header; } test "header.fromBytes" { var header = Header{ .total_records = 10, .last_key_offset = 48, .first_key_offset = 40, }; var alloc = std.testing.allocator; var buf = try alloc.alloc(u8, 512); defer alloc.free(buf); _ = try toBytes(&header, buf); var new_h = try fromBytes(buf); try expectEqual(new_h.magic_number, header.magic_number); try expectEqual(header.total_records, 10); try expectEqual(new_h.total_records, header.total_records); try expectEqual(new_h.reserved, header.reserved); try expectEqual(new_h.last_key_offset, header.last_key_offset); try expectEqual(new_h.first_key_offset, header.first_key_offset); } test "header.toBytes" { var header = Header{ .total_records = 10, .last_key_offset = 48, .first_key_offset = 40, }; var alloc = std.testing.allocator; var buf = try alloc.alloc(u8, 512); defer alloc.free(buf); var total_bytes = try toBytes(&header, buf); try expectEqual(@as(usize, 153), total_bytes); // magic number try expectEqual(@as(u8, 1), buf[0]); //first key try expectEqual(@as(u8, 40), buf[1]); // last key try expectEqual(@as(u8, 48), buf[9]); // reserved data try expectEqual(@as(u8, 0), buf[17]); // total records try expectEqual(@as(u8, 10), buf[145]); }
src/serialize/header.zig
const fmath = @import("index.zig"); pub fn acosh(x: var) -> @typeOf(x) { const T = @typeOf(x); switch (T) { f32 => @inlineCall(acoshf, x), f64 => @inlineCall(acoshd, x), else => @compileError("acosh not implemented for " ++ @typeName(T)), } } // acosh(x) = log(x + sqrt(x * x - 1)) fn acoshf(x: f32) -> f32 { const u = @bitCast(u32, x); const i = u & 0x7FFFFFFF; // |x| < 2, invalid if x < 1 or nan if (i < 0x3F800000 + (1 << 23)) { fmath.log1p(x - 1 + fmath.sqrt((x - 1) * (x - 1) + 2 * (x - 1))) } // |x| < 0x1p12 else if (i < 0x3F800000 + (12 << 23)) { fmath.log(2 * x - 1 / (x + fmath.sqrt(x * x - 1))) } // |x| >= 0x1p12 else { fmath.log(x) + 0.693147180559945309417232121458176568 } } fn acoshd(x: f64) -> f64 { const u = @bitCast(u64, x); const e = (u >> 52) & 0x7FF; // |x| < 2, invalid if x < 1 or nan if (e < 0x3FF + 1) { fmath.log1p(x - 1 + fmath.sqrt((x - 1) * (x - 1) + 2 * (x - 1))) } // |x| < 0x1p26 else if (e < 0x3FF + 26) { fmath.log(2 * x - 1 / (x + fmath.sqrt(x * x - 1))) } // |x| >= 0x1p26 or nan else { fmath.log(x) + 0.693147180559945309417232121458176568 } } test "acosh" { fmath.assert(acosh(f32(1.5)) == acoshf(1.5)); fmath.assert(acosh(f64(1.5)) == acoshd(1.5)); } test "acoshf" { const epsilon = 0.000001; fmath.assert(fmath.approxEq(f32, acoshf(1.5), 0.962424, epsilon)); fmath.assert(fmath.approxEq(f32, acoshf(37.45), 4.315976, epsilon)); fmath.assert(fmath.approxEq(f32, acoshf(89.123), 5.183133, epsilon)); fmath.assert(fmath.approxEq(f32, acoshf(123123.234375), 12.414088, epsilon)); } test "acoshd" { const epsilon = 0.000001; fmath.assert(fmath.approxEq(f64, acoshd(1.5), 0.962424, epsilon)); fmath.assert(fmath.approxEq(f64, acoshd(37.45), 4.315976, epsilon)); fmath.assert(fmath.approxEq(f64, acoshd(89.123), 5.183133, epsilon)); fmath.assert(fmath.approxEq(f64, acoshd(123123.234375), 12.414088, epsilon)); }
src/acosh.zig
const std = @import("std"); const assert = std.debug.assert; pub fn main() !void { var input_file = try std.fs.cwd().openFile("input/08.txt", .{}); defer input_file.close(); var buffered_reader = std.io.bufferedReader(input_file.reader()); const count = try deduceNumbers(buffered_reader.reader()); std.debug.print("sum of all output values: {}\n", .{count}); } const Pattern = u7; fn deduceNumbers(reader: anytype) !u64 { var buf: [1024]u8 = undefined; var sum: u64 = 0; while (try reader.readUntilDelimiterOrEof(&buf, '\n')) |line| { var iter = std.mem.split(u8, line, " "); var pattern_map = [_]Pattern{0} ** 10; var patterns_with_len_5 = try std.BoundedArray(Pattern, 3).init(0); var patterns_with_len_6 = try std.BoundedArray(Pattern, 3).init(0); { var i: u8 = 0; while (i < 10) : (i += 1) { var pattern: Pattern = 0; const raw_pattern = iter.next() orelse return error.MissingData; for (raw_pattern) |c| { pattern |= @as(Pattern, 1) << @intCast(u3, c - 'a'); } assert(raw_pattern.len == @popCount(Pattern, pattern)); switch (raw_pattern.len) { 2 => pattern_map[1] = pattern, 4 => pattern_map[4] = pattern, 3 => pattern_map[7] = pattern, 7 => pattern_map[8] = pattern, 5 => try patterns_with_len_5.append(pattern), 6 => try patterns_with_len_6.append(pattern), else => return error.InvalidData, } } } // Prerequisites const bd = ~pattern_map[1] & pattern_map[4]; const cf = pattern_map[1]; assert(@popCount(Pattern, bd) == 2); assert(@popCount(Pattern, cf) == 2); // Find 3 const index_3 = for (patterns_with_len_5.slice()) |x, i| { if (x & cf == cf) break i; } else return error.DidntFindThree; pattern_map[3] = patterns_with_len_5.swapRemove(index_3); // Find 5 const index_5 = for (patterns_with_len_5.slice()) |x, i| { if (x & bd == bd) break i; } else return error.DidntFindFive; pattern_map[5] = patterns_with_len_5.swapRemove(index_5); // Find 2 pattern_map[2] = patterns_with_len_5.swapRemove(0); // Find 0 const index_0 = for (patterns_with_len_6.slice()) |x, i| { if (x & bd != bd) break i; } else return error.DidntFindZero; pattern_map[0] = patterns_with_len_6.swapRemove(index_0); // Find 9 const index_9 = for (patterns_with_len_6.slice()) |x, i| { if (x & cf == cf) break i; } else return error.DidntFindNine; pattern_map[9] = patterns_with_len_6.swapRemove(index_9); // Find 6 pattern_map[6] = patterns_with_len_6.swapRemove(0); const delimiter = iter.next() orelse return error.WrongFormat; if (!std.mem.eql(u8, "|", delimiter)) return error.WrongFormat; var value: u64 = 0; while (iter.next()) |raw_pattern| { var pattern: Pattern = 0; for (raw_pattern) |c| { pattern |= @as(Pattern, 1) << @intCast(u3, c - 'a'); } const digit = for (pattern_map) |x, i| { if (pattern == x) break i; } else return error.DigitNotFound; value += digit; value *= 10; } sum += value / 10; } return sum; } test "example 1" { const text = \\be cfbegad cbdgef fgaecd cgeb fdcge agebfd fecdb fabcd edb | fdgacbe cefdb cefbgd gcbe \\edbfga begcd cbg gc gcadebf fbgde acbgfd abcde gfcbed gfec | fcgedb cgb dgebacf gc \\fgaebd cg bdaec gdafb agbcfd gdcbef bgcad gfac gcb cdgabef | cg cg fdcagb cbg \\fbegcd cbd adcefb dageb afcb bc aefdc ecdab fgdeca fcdbega | efabcd cedba gadfec cb \\aecbfdg fbg gf bafeg dbefa fcge gcbea fcaegb dgceab fcbdga | gecf egdcabf bgf bfgea \\fgeab ca afcebg bdacfeg cfaedg gcfdb baec bfadeg bafgc acf | gebdcfa ecba ca fadegcb \\dbcfg fgd bdegcaf fgec aegbdf ecdfab fbedc dacgb gdcebf gf | cefg dcbef fcge gbcadfe \\bdfegc cbegaf gecbf dfcage bdacg ed bedf ced adcbefg gebcd | ed bcgafe cdgba cbgef \\egadfb cdbfeg cegd fecab cgb gbdefca cg fgcdab egfdb bfceg | gbdfcae bgc cg cgb \\gcafb gcf dcaebfg ecagb gf abcdeg gaef cafbge fdbac fegbdc | fgae cfgab fg bagce ; var fbs = std.io.fixedBufferStream(text); const count = try deduceNumbers(fbs.reader()); try std.testing.expectEqual(@as(u64, 61229), count); }
src/08_2.zig
const std = @import("std"); const assert = std.debug.assert; const big = std.math.big; const mem = std.mem; const testing = @import("testing.zig"); const limb_bits = @typeInfo(big.Limb).Int.bits; const limb_bytes = limb_bits / 8; /// fromRawBytes decodes a big.int from the data provided. /// /// Based on https://github.com/golang/go/blob/master/src/math/big/nat.go#L1514-L1534 fn fromRawBytes(allocator: *mem.Allocator, data: []const u8) !big.int.Managed { const nb_limbs: usize = (data.len + limb_bytes - 1) / limb_bytes; var limbs = try allocator.alloc(big.Limb, nb_limbs); errdefer allocator.free(limbs); // Loop until we don't have enough bytes for a full limb. // Decode a full limb per iteration. var i: usize = data.len; var k: usize = 0; while (i >= limb_bytes) : (k += 1) { const limb = mem.readIntSliceBig(big.Limb, data[i - limb_bytes .. i]); limbs[k] = limb; i -= limb_bytes; } // Decode the remaining limb. if (i > 0) { var limb: big.Limb = 0; var s: u6 = 0; while (i > 0) : (s += 8) { limb |= @intCast(usize, data[i - 1]) << s; i -= 1; } limbs[k] = limb; } assert(i == 0); const n = big.int.Mutable{ .limbs = limbs, .len = limbs.len, .positive = true, }; return n.toManaged(allocator); } // This is used to make a big.int negative below. const big_one_limbs = [_]big.Limb{1}; const big_one = big.int.Const{ .limbs = &big_one_limbs, .positive = true, }; /// fromBytes decodes a big-endian two's complement value stored in data into a big.int.Managed. /// /// Based on https://github.com/gocql/gocql/blob/5378c8f664e946e421b16a490513675b8419bdc7/marshal.go#L1096-L1108 pub fn fromBytes(allocator: *mem.Allocator, data: []const u8) !big.int.Managed { // Get the raw big.int without worrying about the sign. var n = try fromRawBytes(allocator, data); // Per the spec, a MSB of 1 in the data means it's negative. if (data.len <= 0 or (data[0] & 0x80 == 0)) { return n; } // NOTE(vincent): we have to make a new big.int.Managed to return // because we can't use n to make the subtraction. defer n.deinit(); const shift = data.len * 8; // Capacity is: // * one for the 1 big.int // * how many full limbs are in the data slice // * one more to store the remaining bytes const capacity = big_one.limbs.len + (data.len / limb_bytes) + 1; // Allocate a temporary big.int to hold the shifted value. var tmp = try big.int.Managed.initCapacity(allocator, capacity); defer tmp.deinit(); var tmp_mutable = tmp.toMutable(); // 1 << shift tmp_mutable.shiftLeft(big_one, shift); // res = n - (1 << shift) var res = try big.int.Managed.init(allocator); try res.sub(n.toConst(), tmp_mutable.toConst()); return res; } /// rawBytes encodes n into buf and returns the number of bytes written. /// /// Based on https://github.com/golang/go/blob/master/src/math/big/nat.go#L1478-L1504 fn rawBytes(buf: []u8, n: big.int.Const) !usize { var i: usize = buf.len; for (n.limbs) |v| { var limb = v; var j: usize = 0; while (j < limb_bytes) : (j += 1) { i -= 1; if (i >= 0) { buf[i] = @truncate(u8, limb); } else if (@truncate(u8, limb) != 0) { return error.BufferTooSmall; } limb >>= 8; } } if (i < 0) { i = 0; } while (i < buf.len and buf[i] == 0) { i += 1; } return i; } // Mostly based on https://github.com/gocql/gocql/blob/5378c8f664e946e421b16a490513675b8419bdc7/marshal.go#L1112. pub fn toBytes(allocator: *mem.Allocator, n: big.int.Const) ![]const u8 { // This represents 0. if (n.limbs.len == 1 and n.limbs[0] == 0) { var b = try allocator.alloc(u8, 1); b[0] = 0; return b; } // Handle positive numbers if (n.positive) { var buf = try allocator.alloc(u8, n.limbs.len * 8); errdefer allocator.free(buf); var pos = try rawBytes(buf, n); // This is for §6.23 https://github.com/apache/cassandra/blob/trunk/doc/native_protocol_v5.spec#L1037-L1040 if ((buf[0] & 0x80) > 0) { buf[pos - 1] = 0; return buf[pos - 1 ..]; } return buf[pos..]; } // Handle negative numbers const shift = (n.bitCountTwosComp() / 8 + 1) * 8; // Capacity is: // * one for the 1 big.int // * how many full limbs are in the data slice // * one more to store the remaining bytes const capacity = (shift / limb_bytes) + 1; // Allocate a temporary big.int to hold the shifted value. var tmp = try big.int.Managed.initCapacity(allocator, capacity); defer tmp.deinit(); var tmp_mutable = tmp.toMutable(); // 1 << shift tmp_mutable.shiftLeft(big_one, shift); // n = n + (1 << shift) var n_tmp = try n.toManaged(allocator); defer n_tmp.deinit(); try n_tmp.add(n_tmp.toConst(), tmp_mutable.toConst()); var buf = try allocator.alloc(u8, (n_tmp.len() + 1) * limb_bytes); errdefer allocator.free(buf); var pos = try rawBytes(buf, n_tmp.toConst()); return buf[pos..]; } test "bigint: toBytes" { const testCase = struct { n: []const u8, exp_data: []const u8, }; const testCases = [_]testCase{ testCase{ .n = "3405245950896869895938539859386968968953285938539111111111111111111111111111111111111111122222222222222222222222222222222", .exp_data = "\x01\x51\x97\x29\x61\xfa\xec\x86\x0d\x18\x06\x93\xd0\x53\xba\xb9\x02\xbd\xde\xe9\xfa\xab\x78\xcf\x52\x2e\x43\x1c\x68\xea\x9e\xb8\xeb\x35\x6e\x96\x31\xfc\x4b\x10\xfc\x9d\x0a\x2b\x4c\x1a\x9c\x8e\x38\xe3\x8e", }, testCase{ .n = "-3405245950896869895938539859386968968953285938539111111111111111111111111111111111111111122222222222222222222222222222222", .exp_data = "\xfe\xae\x68\xd6\x9e\x05\x13\x79\xf2\xe7\xf9\x6c\x2f\xac\x45\x46\xfd\x42\x21\x16\x05\x54\x87\x30\xad\xd1\xbc\xe3\x97\x15\x61\x47\x14\xca\x91\x69\xce\x03\xb4\xef\x03\x62\xf5\xd4\xb3\xe5\x63\x71\xc7\x1c\x72", }, }; inline for (testCases) |tc| { var n = try big.int.Managed.init(testing.allocator); defer n.deinit(); try n.setString(10, tc.n); const data = try toBytes(testing.allocator, n.toConst()); defer testing.allocator.free(data); testing.expectEqualSlices(u8, tc.exp_data, data); } } test "bigint: fromBytes" { const testCase = struct { data: []const u8, exp: []const u8, }; const testCases = [_]testCase{ testCase{ .data = "\x01\x51\x97\x29\x61\xfa\xec\x86\x0d\x18\x06\x93\xd0\x53\xba\xb9\x02\xbd\xde\xe9\xfa\xab\x78\xcf\x52\x2e\x43\x1c\x68\xea\x9e\xb8\xeb\x35\x6e\x96\x31\xfc\x4b\x10\xfc\x9d\x0a\x2b\x4c\x1a\x9c\x8e\x38\xe3\x8e", .exp = "3405245950896869895938539859386968968953285938539111111111111111111111111111111111111111122222222222222222222222222222222", }, testCase{ .data = "\xfe\xae\x68\xd6\x9e\x05\x13\x79\xf2\xe7\xf9\x6c\x2f\xac\x45\x46\xfd\x42\x21\x16\x05\x54\x87\x30\xad\xd1\xbc\xe3\x97\x15\x61\x47\x14\xca\x91\x69\xce\x03\xb4\xef\x03\x62\xf5\xd4\xb3\xe5\x63\x71\xc7\x1c\x72", .exp = "-3405245950896869895938539859386968968953285938539111111111111111111111111111111111111111122222222222222222222222222222222", }, }; inline for (testCases) |tc| { var n = try fromBytes(testing.allocator, tc.data); defer n.deinit(); var buf: [1024]u8 = undefined; const formatted_n = try std.fmt.bufPrint(&buf, "{}", .{n}); testing.expectEqualStrings(tc.exp, formatted_n); } }
src/bigint.zig
const std = @import("std"); const fs = std.fs; const fmt = std.fmt; const mem = std.mem; const math = std.math; const process = std.process; const json = std.json; const foxwren = @import("foxwren"); const ValueType = foxwren.ValueType; const Module = foxwren.Module; const Instance = foxwren.Instance; const Store = foxwren.Store; const Memory = foxwren.Memory; const Function = foxwren.Function; const Global = foxwren.Global; const Interpreter = foxwren.Interpreter; const GeneralPurposeAllocator = std.heap.GeneralPurposeAllocator; const ArenaAllocator = std.heap.ArenaAllocator; const StringHashMap = std.hash_map.StringHashMap; const ArrayList = std.ArrayList; const WasmError = foxwren.WasmError; // testrunner // // testrunner is an a program that consumes the foxwren library // and runs the WebAssembly testsuite. // // This allows us to separate out the library code from these // tests but still include the testsuite as part of, say, Github // Actions. // // See https://github.com/WebAssembly/spec/blob/master/interpreter/README.md#s-expression-syntax // for information on the format of the .wast files. var gpa = GeneralPurposeAllocator(.{}){}; fn print(_: *Interpreter) WasmError!void { std.debug.warn("print\n", .{}); } fn print_i32(interp: *Interpreter) WasmError!void { const value = interp.popOperand(i32); std.debug.warn("print_i32: {}\n", .{value}); } fn print_i64(interp: *Interpreter) WasmError!void { const value = interp.popOperand(i64); std.debug.warn("print_i64: {}\n", .{value}); } fn print_f32(interp: *Interpreter) WasmError!void { const value = interp.popOperand(f32); std.debug.warn("print_f32: {}\n", .{value}); } fn print_f64(interp: *Interpreter) WasmError!void { const value = interp.popOperand(f64); std.debug.warn("print_f64: {}\n", .{value}); } fn print_i32_f32(interp: *Interpreter) WasmError!void { const value_f32 = interp.popOperand(f32); const value_i32 = interp.popOperand(i32); std.debug.warn("print_i32_f32: {}, {}\n", .{ value_i32, value_f32 }); } fn print_f64_f64(interp: *Interpreter) WasmError!void { const value_f64_2 = interp.popOperand(f64); const value_f64_1 = interp.popOperand(f64); std.debug.warn("print_f64_f64: {}, {}\n", .{ value_f64_1, value_f64_2 }); } pub fn main() anyerror!void { defer _ = gpa.deinit(); // 1. Get .json file from command line var args = process.args(); _ = args.skip(); const filename = args.nextPosix() orelse return error.NoFilename; std.log.info("testing: {s}", .{filename}); var arena = ArenaAllocator.init(&gpa.allocator); defer _ = arena.deinit(); // 2. Parse json and find .wasm file const json_string = try fs.cwd().readFileAlloc(&arena.allocator, filename, 0xFFFFFFF); const r = try json.parse(Wast, &json.TokenStream.init(json_string), json.ParseOptions{ .allocator = &arena.allocator }); // 2.a. Find the wasm file var wasm_filename: []const u8 = undefined; var program: []const u8 = undefined; var module: Module = undefined; // Initialise a store var store: Store = Store.init(&arena.allocator); const spectest_module = "spectest"; // Init spectest memory const mem_handle = try store.addMemory(1, 2); _ = try store.memory(mem_handle); const spectest_memory_name = "memory"; try store.@"export"(spectest_module[0..], spectest_memory_name[0..], .Mem, mem_handle); // Init spec test table const table_handle = try store.addTable(10, 20); const spectest_table_name = "table"; try store.@"export"(spectest_module[0..], spectest_table_name[0..], .Table, table_handle); // Initiliase spectest globals const i32_handle = try store.addGlobal(Global{ .value = 666, .value_type = .I32, .mutability = .Immutable, }); const i32_name = "global_i32"; try store.@"export"(spectest_module[0..], i32_name[0..], .Global, i32_handle); const i64_handle = try store.addGlobal(Global{ .value = 666, .value_type = .I64, .mutability = .Immutable, }); const i64_name = "global_i64"; try store.@"export"(spectest_module[0..], i64_name[0..], .Global, i64_handle); const f32_handle = try store.addGlobal(Global{ .value = 666, .value_type = .F32, .mutability = .Immutable, }); const f32_name = "global_f32"; try store.@"export"(spectest_module[0..], f32_name[0..], .Global, f32_handle); const f64_handle = try store.addGlobal(Global{ .value = 666, .value_type = .F64, .mutability = .Immutable, }); const f64_name = "global_f64"; try store.@"export"(spectest_module[0..], f64_name[0..], .Global, f64_handle); var print_params = [_]ValueType{.I32} ** 0; var print_results = [_]ValueType{.I32} ** 0; const print_handle = try store.addFunction(Function{ .host_function = .{ .func = print, .params = print_params[0..], .results = print_results[0..], }, }); const print_name = "print"; try store.@"export"(spectest_module[0..], print_name[0..], .Func, print_handle); var print_i32_params = [_]ValueType{.I32} ** 1; var print_i32_results = [_]ValueType{.I32} ** 0; const print_i32_handle = try store.addFunction(Function{ .host_function = .{ .func = print_i32, .params = print_i32_params[0..], .results = print_i32_results[0..], }, }); const print_i32_name = "print_i32"; try store.@"export"(spectest_module[0..], print_i32_name[0..], .Func, print_i32_handle); // print_i64 var print_i64_params = [_]ValueType{.I64} ** 1; var print_i64_results = [_]ValueType{.I64} ** 0; const print_i64_handle = try store.addFunction(Function{ .host_function = .{ .func = print_i64, .params = print_i64_params[0..], .results = print_i64_results[0..], }, }); const print_i64_name = "print_i64"; try store.@"export"(spectest_module[0..], print_i64_name[0..], .Func, print_i64_handle); // export print_f32 var print_f32_params = [_]ValueType{.F32} ** 1; var print_f32_results = [_]ValueType{.F32} ** 0; const print_f32_handle = try store.addFunction(Function{ .host_function = .{ .func = print_f32, .params = print_f32_params[0..], .results = print_f32_results[0..], }, }); const print_f32_name = "print_f32"; try store.@"export"(spectest_module[0..], print_f32_name[0..], .Func, print_f32_handle); // export print_f64 var print_f64_params = [_]ValueType{.F64} ** 1; var print_f64_results = [_]ValueType{.F64} ** 0; const print_f64_handle = try store.addFunction(Function{ .host_function = .{ .func = print_f64, .params = print_f64_params[0..], .results = print_f64_results[0..], }, }); const print_f64_name = "print_f64"; try store.@"export"(spectest_module[0..], print_f64_name[0..], .Func, print_f64_handle); // export print_i32_f32 var print_i32_f32_params: [2]ValueType = [_]ValueType{ .I32, .F32 }; var print_i32_f32_results = [_]ValueType{.F32} ** 0; const print_i32_f32_handle = try store.addFunction(Function{ .host_function = .{ .func = print_i32_f32, .params = print_i32_f32_params[0..], .results = print_i32_f32_results[0..], }, }); const print_i32_f32_name = "print_i32_f32"; try store.@"export"(spectest_module[0..], print_i32_f32_name[0..], .Func, print_i32_f32_handle); // export print_i64_f64 var print_f64_f64_params: [2]ValueType = [_]ValueType{ .F64, .F64 }; var print_f64_f64_results: [0]ValueType = [_]ValueType{}; const print_f64_f64_handle = try store.addFunction(Function{ .host_function = .{ .func = print_f64_f64, .params = print_f64_f64_params[0..], .results = print_f64_f64_results[0..], }, }); const print_f64_f64_name = "print_f64_f64"; try store.@"export"(spectest_module[0..], print_f64_f64_name[0..], .Func, print_f64_f64_handle); var inst: *Instance = undefined; var registered_names = StringHashMap(usize).init(&arena.allocator); for (r.commands) |command| { switch (command) { .module => { wasm_filename = command.module.filename; std.debug.warn("(module): {s}:{} ({s})\n", .{ r.source_filename, command.module.line, wasm_filename }); program = try fs.cwd().readFileAlloc(&arena.allocator, wasm_filename, 0xFFFFFFF); errdefer { std.debug.warn("(module): {s} at {}:{s}\n", .{ r.source_filename, command.module.line, wasm_filename }); } // 4. Initialise our module module = Module.init(&arena.allocator, program); try module.decode(); var new_inst = Instance.init(&arena.allocator, &store, module); const inst_index = try store.addInstance(new_inst); inst = try store.instance(inst_index); try inst.instantiate(inst_index); if (command.module.name) |name| { try registered_names.put(name, inst_index); } }, .assert_return => { const action = command.assert_return.action; const expected = command.assert_return.expected; switch (action) { .invoke => { const field = action.invoke.field; std.debug.warn("(return): {s}:{}\n", .{ r.source_filename, command.assert_return.line }); var instance = inst; if (command.assert_return.action.invoke.module) |name| { if (registered_names.get(name)) |inst_offset| { instance = try store.instance(inst_offset); } } // Allocate input parameters and output results var in = try arena.allocator.alloc(u64, action.invoke.args.len); var out = try arena.allocator.alloc(u64, expected.len); // Initialise input parameters for (action.invoke.args) |value, i| { const arg = try fmt.parseInt(u64, value.value, 10); in[i] = arg; } // Invoke the function instance.invoke(field, in, out, .{}) catch |err| { std.debug.warn("(result) invoke = {s}\n", .{field}); std.debug.warn("Testsuite failure: {s} at {s}:{}\n", .{ field, r.source_filename, command.assert_return.line }); return err; }; for (expected) |result, i| { const value_type = try valueTypeFromString(result.@"type"); if (mem.startsWith(u8, result.value, "nan:")) { if (value_type == .F32 and math.isNan(@bitCast(f32, @truncate(u32, out[i])))) { continue; } if (value_type == .F64 and math.isNan(@bitCast(f64, out[i]))) { continue; } std.debug.warn("(result) invoke = {s}\n", .{field}); std.debug.warn("Testsuite failure: {s} at {s}:{}\n", .{ field, r.source_filename, command.assert_return.line }); std.debug.warn("result[{}], expected: {s}, result: {} ({x})\n", .{ i, "nan", out[i], out[i] }); return error.TestsuiteTestFailureTrapResult; } const result_value = try fmt.parseInt(u64, result.value, 10); // Otherwise errdefer { std.debug.warn("(result) invoke = {s}\n", .{field}); std.debug.warn("Testsuite failure: {s} at {s}:{}\n", .{ field, r.source_filename, command.assert_return.line }); std.debug.warn("result[{}], expected: {s} ({x}), result: {} ({x})\n", .{ i, result.value, result_value, out[i], out[i] }); } if (result_value != out[expected.len - i - 1]) { return error.TestsuiteTestFailureTrapResult; } } }, .get => { const field = action.get.field; std.debug.warn("(return): get {s}:{} ({s})\n", .{ r.source_filename, command.assert_return.line, wasm_filename }); std.debug.warn("(result) get \"{s}\"\n", .{field}); if (action.get.module) |m| { const registered_inst_offset = registered_names.get(m) orelse return error.NotRegistered; const registered_inst = try store.instance(registered_inst_offset); for (registered_inst.module.exports.list.items) |exprt| { if (mem.eql(u8, exprt.name, field)) { const global = try registered_inst.getGlobal(exprt.index); for (expected) |result, j| { if (j > 0) return error.ExpectedOneResult; const result_value = try fmt.parseInt(u64, result.value, 10); if (global.value != result_value) { return error.GlobalUnexpectedValue; } } } } } else { for (inst.module.exports.list.items) |exprt, i| { if (mem.eql(u8, exprt.name, field)) { const global = try inst.getGlobal(i); for (expected) |result, j| { if (j > 0) return error.ExpectedOneResult; const result_value = try fmt.parseInt(u64, result.value, 10); if (global.value != result_value) { return error.GlobalUnexpectedValue; } } } } } }, } }, .assert_trap => { const action = command.assert_trap.action; const expected = command.assert_trap.expected; const trap = command.assert_trap.text; switch (action) { .invoke => { const field = action.invoke.field; std.debug.warn("(trap): {s}:{}\n", .{ r.source_filename, command.assert_trap.line }); errdefer { std.debug.warn("(trap) invoke = {s} at {s}:{}\n", .{ field, r.source_filename, command.assert_trap.line }); } var instance = inst; if (command.assert_trap.action.invoke.module) |name| { if (registered_names.get(name)) |inst_offset| { instance = try store.instance(inst_offset); } } // Allocate input parameters and output results var in = try arena.allocator.alloc(u64, action.invoke.args.len); var out = try arena.allocator.alloc(u64, expected.len); // Initialise input parameters for (action.invoke.args) |value, i| { const arg = try fmt.parseInt(u64, value.value, 10); in[i] = arg; } // Test the result if (mem.eql(u8, trap, "integer divide by zero")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.DivisionByZero => continue, else => return error.TestsuiteExpectedDivideByZero, } } if (mem.eql(u8, trap, "integer overflow")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.Overflow => continue, else => return error.TestsuiteExpectedOverflow, } } if (mem.eql(u8, trap, "invalid conversion to integer")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.InvalidConversion => continue, else => return error.TestsuiteExpectedInvalidConversion, } } if (mem.eql(u8, trap, "out of bounds memory access")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.OutOfBoundsMemoryAccess => continue, else => return error.TestsuiteExpectedOutOfBoundsMemoryAccess, } } if (mem.eql(u8, trap, "indirect call type mismatch")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.IndirectCallTypeMismatch => continue, else => return error.TestsuiteExpectedIndirectCallTypeMismatch, } } if (mem.eql(u8, trap, "undefined element") or mem.eql(u8, trap, "uninitialized element")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.UndefinedElement => continue, error.OutOfBoundsMemoryAccess => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.TestsuiteExpectedUndefinedElement; }, } } if (mem.eql(u8, trap, "uninitialized") or mem.eql(u8, trap, "undefined") or mem.eql(u8, trap, "indirect call")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedTrap; } else |err| switch (err) { error.UndefinedElement => continue, error.OutOfBoundsMemoryAccess => continue, error.IndirectCallTypeMismatch => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.TestsuiteExpectedUnitialized; }, } } if (mem.eql(u8, trap, "unreachable")) { if (instance.invoke(field, in, out, .{})) |_| { return error.TestsuiteExpectedUnreachable; } else |err| switch (err) { error.TrapUnreachable => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.TestsuiteExpectedUnreachable; }, } } }, .get => { std.debug.warn("(trap) get\n", .{}); return error.TrapGetNotImplemented; }, } return error.ExpectedTrapDidntOccur; }, .assert_invalid => { wasm_filename = command.assert_invalid.filename; std.debug.warn("(invalid): {s}:{} ({s})\n", .{ r.source_filename, command.assert_invalid.line, wasm_filename }); program = try fs.cwd().readFileAlloc(&arena.allocator, wasm_filename, 0xFFFFFFF); module = Module.init(&arena.allocator, program); errdefer { std.debug.warn("ERROR (invalid): {s}:{}\n", .{ r.source_filename, command.assert_invalid.line }); } if (module.decode()) |_| { return error.TestsuiteExpectedInvalid; } else |err| switch (err) { error.InvalidAlignment => continue, error.ValidatorPopOperandError => continue, error.MismatchedTypes => continue, error.ValidatorPopControlFrameControlStackEmpty => continue, error.ValidatorPopControlFrameMismatchedSizes => continue, error.ControlStackEmpty => continue, error.ValidatorAttemptToMutateImmutableGlobal => continue, error.ValidatorConstantExpressionRequired => continue, error.ValidatorUnknownGlobal => continue, error.ValidatorInvalidTypeIndex => continue, error.ValidatorMultipleTables => continue, error.ValidatorMultipleMemories => continue, error.LocalGetIndexOutOfBounds => continue, error.LocalSetIndexOutOfBounds => continue, error.ValidatorDataMemoryReferenceInvalid => continue, error.ValidatorUnknownMemory => continue, error.ValidatorMemoryMinGreaterThanMax => continue, error.ValidatorMemoryMinTooLarge => continue, error.ValidatorMemoryMaxTooLarge => continue, error.ValidatorSelect => continue, error.ValidateBrInvalidLabel => continue, error.ValidateBrIfInvalidLabel => continue, error.ValidateBrTableInvalidLabel => continue, error.ValidateBrTableInvalidLabelWrongArity => continue, error.ValidateBrTableInvalidLabelN => continue, error.ValidatorCallInvalidFunctionIndex => continue, error.ValidatorCallIndirectNoTable => continue, error.ValidatorCallIndirectInvalidTypeIndex => continue, error.ValidatorElemUnknownTable => continue, error.ValidatorTableMinGreaterThanMax => continue, error.ValidatorExportUnknownFunction => continue, error.ValidatorExportUnknownTable => continue, error.ValidatorExportUnknownMemory => continue, error.ValidatorExportUnknownGlobal => continue, error.ValidatorDuplicateExportName => continue, error.ValidatorStartFunctionUnknown => continue, error.ValidatorNotStartFunctionType => continue, error.ValidatorElemUnknownFunctionIndex => continue, error.ValidatorElseBranchExpected => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.TestsuiteExpectedInvalidUnexpectedError; }, } }, .assert_malformed => { if (mem.endsWith(u8, command.assert_malformed.filename, ".wat")) continue; wasm_filename = command.assert_malformed.filename; std.debug.warn("(malformed): {s}:{} ({s})\n", .{ r.source_filename, command.assert_malformed.line, wasm_filename }); program = try fs.cwd().readFileAlloc(&arena.allocator, wasm_filename, 0xFFFFFFF); module = Module.init(&arena.allocator, program); const trap = command.assert_malformed.text; errdefer { std.debug.warn("ERROR (malformed): {s}:{}\n", .{ r.source_filename, command.assert_malformed.line }); } if (mem.eql(u8, trap, "unexpected end") or mem.eql(u8, trap, "length out of bounds")) { if (module.decode()) |_| { return error.TestsuiteExpectedUnexpectedEnd; } else |err| switch (err) { error.Overflow => continue, error.UnexpectedEndOfInput => continue, error.FunctionCodeSectionsInconsistent => continue, error.EndOfStream => continue, error.CouldntFindExprEnd => continue, error.ElementsCountMismatch => continue, error.CouldntFindEnd => continue, // test/testsuite/binary.wast:910 bad br_table means we don't find end else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.TestsuiteExpectedUnexpectedEnd; }, } } if (mem.eql(u8, trap, "magic header not detected")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.MagicNumberNotFound => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "unknown binary version")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.UnknownBinaryVersion => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "malformed section id")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.UnknownSectionId => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "integer representation too long")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.InvalidValue => continue, error.ExpectedFuncTypeTag => continue, error.Overflow => continue, error.UnknownSectionId => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "zero flag expected")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.MalformedCallIndirectReserved => continue, error.MalformedMemoryReserved => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "too many locals")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.TooManyLocals => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "function and code section have inconsistent lengths")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.FunctionCodeSectionsInconsistent => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "unexpected end of section or function") or mem.eql(u8, trap, "section size mismatch")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.UnexpectedEndOfInput => continue, error.UnknownSectionId => continue, // if a section declares more elements than it has we might get this error.TypeCountMismatch => continue, error.ImportsCountMismatch => continue, error.TablesCountMismatch => continue, error.MemoriesCountMismatch => continue, error.GlobalsCountMismatch => continue, error.ElementsCountMismatch => continue, error.FunctionsCountMismatch => continue, error.CodesCountMismatch => continue, error.DatasCountMismatch => continue, error.InvalidValue => continue, error.MalformedSectionMismatchedSize => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "malformed import kind")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.InvalidValue => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "integer too large")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.Overflow => continue, error.UnknownSectionId => continue, error.InvalidValue => continue, // test/testsuite/binary.wast:601 I think the test is wrong else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "junk after last section")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.MultipleStartSections => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "malformed mutability")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.InvalidValue => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } if (mem.eql(u8, trap, "malformed UTF-8 encoding")) { if (module.decode()) |_| { return error.ExpectedError; } else |err| switch (err) { error.NameNotUTF8 => continue, else => { std.debug.warn("Unexpected error: {}\n", .{err}); return error.ExpectedError; }, } } return error.ExpectedError; }, .action => { const action = command.action.action; const expected = command.action.expected; switch (action) { .invoke => { const field = action.invoke.field; std.debug.warn("(return): {s}:{}\n", .{ r.source_filename, command.action.line }); // Allocate input parameters and output results var in = try arena.allocator.alloc(u64, action.invoke.args.len); var out = try arena.allocator.alloc(u64, expected.len); // Initialise input parameters for (action.invoke.args) |value, i| { const arg = try fmt.parseInt(u64, value.value, 10); in[i] = arg; } // Invoke the function inst.invoke(field, in, out, .{}) catch |err| { std.debug.warn("(result) invoke = {s}\n", .{field}); std.debug.warn("Testsuite failure: {s} at {s}:{}\n", .{ field, r.source_filename, command.action.line }); return err; }; }, .get => { std.debug.warn("(action) get\n", .{}); return error.ActionGetNotImplemented; }, } }, .assert_unlinkable => { wasm_filename = command.assert_unlinkable.filename; std.debug.warn("(unlinkable): {s}:{} ({s})\n", .{ r.source_filename, command.assert_unlinkable.line, wasm_filename }); program = try fs.cwd().readFileAlloc(&arena.allocator, wasm_filename, 0xFFFFFFF); module = Module.init(&arena.allocator, program); try module.decode(); var new_inst = Instance.init(&arena.allocator, &store, module); const inst_index = try store.addInstance(new_inst); inst = try store.instance(inst_index); if (inst.instantiate(inst_index)) |_| { return error.ExpectedUnlinkable; } else |err| switch (err) { error.ImportedMemoryNotBigEnough => continue, error.ImportedTableNotBigEnough => continue, error.ImportNotFound => continue, error.ImportedFunctionTypeSignatureDoesNotMatch => continue, error.Overflow => continue, error.OutOfBoundsMemoryAccess => continue, error.MismatchedMutability => continue, else => { std.debug.warn("(unlinkable) Unexpected error: {}\n", .{err}); return error.UnexpectedError; }, } }, .assert_uninstantiable => { wasm_filename = command.assert_uninstantiable.filename; std.debug.warn("(uninstantiable): {s}:{} ({s})\n", .{ r.source_filename, command.assert_uninstantiable.line, wasm_filename }); program = try fs.cwd().readFileAlloc(&arena.allocator, wasm_filename, 0xFFFFFFF); module = Module.init(&arena.allocator, program); try module.decode(); var new_inst = Instance.init(&arena.allocator, &store, module); const inst_index = try store.addInstance(new_inst); inst = try store.instance(inst_index); if (inst.instantiate(inst_index)) |_| { return error.ExpectedUninstantiable; } else |err| switch (err) { error.TrapUnreachable => continue, else => { std.debug.warn("(uninstantiable) Unexpected error: {}\n", .{err}); return error.UnexpectedError; }, } }, .register => { std.debug.warn("(register): {s}:{}\n", .{ r.source_filename, command.register.line }); if (command.register.name) |name| { const registered_inst_offset = registered_names.get(name) orelse return error.NotRegistered; const registered_inst = try store.instance(registered_inst_offset); for (registered_inst.module.exports.list.items) |exprt| { switch (exprt.tag) { .Table => { const handle = registered_inst.tableaddrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Table, handle); }, .Func => { const handle = registered_inst.funcaddrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Func, handle); }, .Global => { const handle = registered_inst.globaladdrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Global, handle); }, .Mem => { const handle = registered_inst.memaddrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Mem, handle); }, } } } else { for (inst.module.exports.list.items) |exprt| { switch (exprt.tag) { .Table => { const handle = inst.tableaddrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Table, handle); }, .Func => { const handle = inst.funcaddrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Func, handle); }, .Global => { const handle = inst.globaladdrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Global, handle); }, .Mem => { const handle = inst.memaddrs.items[exprt.index]; try store.@"export"(command.register.as, exprt.name, .Mem, handle); }, } } } }, else => continue, } } } fn valueTypeFromString(s: []const u8) !ValueType { if (mem.eql(u8, s, "i32")) return ValueType.I32; if (mem.eql(u8, s, "i64")) return ValueType.I64; if (mem.eql(u8, s, "f32")) return ValueType.F32; if (mem.eql(u8, s, "f64")) return ValueType.F64; return error.UnknownType; } const Wast = struct { source_filename: []const u8, commands: []const Command, }; const Command = union(enum) { module: struct { comptime @"type": []const u8 = "module", line: usize, name: ?[]const u8 = null, filename: []const u8, }, assert_return: struct { comptime @"type": []const u8 = "assert_return", line: usize, action: Action, expected: []const Value, }, assert_trap: struct { comptime @"type": []const u8 = "assert_trap", line: usize, action: Action, text: []const u8, expected: []const ValueTrap, }, assert_malformed: struct { comptime @"type": []const u8 = "assert_malformed", line: usize, filename: []const u8, text: []const u8, module_type: []const u8, }, assert_invalid: struct { comptime @"type": []const u8 = "assert_invalid", line: usize, filename: []const u8, text: []const u8, module_type: []const u8, }, assert_exhaustion: struct { comptime @"type": []const u8 = "assert_exhaustion", line: usize, action: Action, text: []const u8, expected: []const ValueTrap, }, assert_unlinkable: struct { comptime @"type": []const u8 = "assert_unlinkable", line: usize, filename: []const u8, text: []const u8, module_type: []const u8, }, assert_uninstantiable: struct { comptime @"type": []const u8 = "assert_uninstantiable", line: usize, filename: []const u8, text: []const u8, module_type: []const u8, }, action: struct { comptime @"type": []const u8 = "action", line: usize, action: Action, expected: []const ValueTrap, }, register: struct { comptime @"type": []const u8 = "register", line: usize, name: ?[]const u8 = null, as: []const u8, } }; const Action = union(enum) { invoke: struct { comptime @"type": []const u8 = "invoke", field: []const u8, module: ?[]const u8 = null, args: []const Value, }, get: struct { comptime @"type": []const u8 = "get", field: []const u8, module: ?[]const u8 = null, }, }; // const Action = ; const Value = struct { @"type": []const u8, value: []const u8, }; const ValueTrap = struct { @"type": []const u8, };
test/src/testrunner.zig
const std = @import("../std.zig"); const assert = std.debug.assert; const testing = std.testing; const builtin = @import("builtin"); const Lock = std.event.Lock; const Loop = std.event.Loop; /// This is a value that starts out unavailable, until resolve() is called /// While it is unavailable, functions suspend when they try to get() it, /// and then are resumed when resolve() is called. /// At this point the value remains forever available, and another resolve() is not allowed. pub fn Future(comptime T: type) type { return struct { lock: Lock, data: T, /// TODO make this an enum /// 0 - not started /// 1 - started /// 2 - finished available: u8, const Self = @This(); const Queue = std.atomic.Queue(anyframe); pub fn init(loop: *Loop) Self { return Self{ .lock = Lock.initLocked(loop), .available = 0, .data = undefined, }; } /// Obtain the value. If it's not available, wait until it becomes /// available. /// Thread-safe. pub async fn get(self: *Self) *T { if (@atomicLoad(u8, &self.available, .SeqCst) == 2) { return &self.data; } const held = self.lock.acquire(); held.release(); return &self.data; } /// Gets the data without waiting for it. If it's available, a pointer is /// returned. Otherwise, null is returned. pub fn getOrNull(self: *Self) ?*T { if (@atomicLoad(u8, &self.available, .SeqCst) == 2) { return &self.data; } else { return null; } } /// If someone else has started working on the data, wait for them to complete /// and return a pointer to the data. Otherwise, return null, and the caller /// should start working on the data. /// It's not required to call start() before resolve() but it can be useful since /// this method is thread-safe. pub async fn start(self: *Self) ?*T { const state = @cmpxchgStrong(u8, &self.available, 0, 1, .SeqCst, .SeqCst) orelse return null; switch (state) { 1 => { const held = self.lock.acquire(); held.release(); return &self.data; }, 2 => return &self.data, else => unreachable, } } /// Make the data become available. May be called only once. /// Before calling this, modify the `data` property. pub fn resolve(self: *Self) void { const prev = @atomicRmw(u8, &self.available, .Xchg, 2, .SeqCst); assert(prev == 0 or prev == 1); // resolve() called twice Lock.Held.release(Lock.Held{ .lock = &self.lock }); } }; } test "std.event.Future" { // https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; const allocator = std.heap.direct_allocator; var loop: Loop = undefined; try loop.initMultiThreaded(allocator); defer loop.deinit(); const handle = async testFuture(&loop); loop.run(); } fn testFuture(loop: *Loop) void { var future = Future(i32).init(loop); var a = async waitOnFuture(&future); var b = async waitOnFuture(&future); resolveFuture(&future); // TODO https://github.com/ziglang/zig/issues/3077 //const result = (await a) + (await b); const a_result = await a; const b_result = await b; const result = a_result + b_result; testing.expect(result == 12); } fn waitOnFuture(future: *Future(i32)) i32 { return future.get().*; } fn resolveFuture(future: *Future(i32)) void { future.data = 6; future.resolve(); }
std/event/future.zig
const std = @import("index.zig"); const builtin = @import("builtin"); const Os = builtin.Os; const c = std.c; const math = std.math; const debug = std.debug; const assert = debug.assert; const os = std.os; const mem = std.mem; const Buffer = std.Buffer; const fmt = std.fmt; const File = std.os.File; const is_posix = builtin.os != builtin.Os.windows; const is_windows = builtin.os == builtin.Os.windows; const GetStdIoErrs = os.WindowsGetStdHandleErrs; pub fn getStdErr() GetStdIoErrs!File { const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_ERROR_HANDLE) else if (is_posix) os.posix.STDERR_FILENO else unreachable; return File.openHandle(handle); } pub fn getStdOut() GetStdIoErrs!File { const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_OUTPUT_HANDLE) else if (is_posix) os.posix.STDOUT_FILENO else unreachable; return File.openHandle(handle); } pub fn getStdIn() GetStdIoErrs!File { const handle = if (is_windows) try os.windowsGetStdHandle(os.windows.STD_INPUT_HANDLE) else if (is_posix) os.posix.STDIN_FILENO else unreachable; return File.openHandle(handle); } pub const SeekableStream = @import("io/seekable_stream.zig").SeekableStream; pub fn InStream(comptime ReadError: type) type { return struct { const Self = @This(); pub const Error = ReadError; /// Return the number of bytes read. If the number read is smaller than buf.len, it /// means the stream reached the end. Reaching the end of a stream is not an error /// condition. readFn: fn (self: *Self, buffer: []u8) Error!usize, /// Replaces `buffer` contents by reading from the stream until it is finished. /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and /// the contents read from the stream are lost. pub fn readAllBuffer(self: *Self, buffer: *Buffer, max_size: usize) !void { try buffer.resize(0); var actual_buf_len: usize = 0; while (true) { const dest_slice = buffer.toSlice()[actual_buf_len..]; const bytes_read = try self.readFull(dest_slice); actual_buf_len += bytes_read; if (bytes_read != dest_slice.len) { buffer.shrink(actual_buf_len); return; } const new_buf_size = math.min(max_size, actual_buf_len + os.page_size); if (new_buf_size == actual_buf_len) return error.StreamTooLong; try buffer.resize(new_buf_size); } } /// Allocates enough memory to hold all the contents of the stream. If the allocated /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. pub fn readAllAlloc(self: *Self, allocator: *mem.Allocator, max_size: usize) ![]u8 { var buf = Buffer.initNull(allocator); defer buf.deinit(); try self.readAllBuffer(&buf, max_size); return buf.toOwnedSlice(); } /// Replaces `buffer` contents by reading from the stream until `delimiter` is found. /// Does not include the delimiter in the result. /// If `buffer.len()` would exceed `max_size`, `error.StreamTooLong` is returned and the contents /// read from the stream so far are lost. pub fn readUntilDelimiterBuffer(self: *Self, buffer: *Buffer, delimiter: u8, max_size: usize) !void { try buffer.resize(0); while (true) { var byte: u8 = try self.readByte(); if (byte == delimiter) { return; } if (buffer.len() == max_size) { return error.StreamTooLong; } try buffer.appendByte(byte); } } /// Allocates enough memory to read until `delimiter`. If the allocated /// memory would be greater than `max_size`, returns `error.StreamTooLong`. /// Caller owns returned memory. /// If this function returns an error, the contents from the stream read so far are lost. pub fn readUntilDelimiterAlloc(self: *Self, allocator: *mem.Allocator, delimiter: u8, max_size: usize) ![]u8 { var buf = Buffer.initNull(allocator); defer buf.deinit(); try self.readUntilDelimiterBuffer(&buf, delimiter, max_size); return buf.toOwnedSlice(); } /// Returns 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 fn read(self: *Self, buffer: []u8) Error!usize { return self.readFn(self, buffer); } /// Returns the number of bytes read. If the number read is smaller than buf.len, it /// means the stream reached the end. Reaching the end of a stream is not an error /// condition. pub fn readFull(self: *Self, buffer: []u8) Error!usize { var index: usize = 0; while (index != buffer.len) { const amt = try self.read(buffer[index..]); if (amt == 0) return index; index += amt; } return index; } /// Same as `readFull` but end of stream returns `error.EndOfStream`. pub fn readNoEof(self: *Self, buf: []u8) !void { const amt_read = try self.read(buf); if (amt_read < buf.len) return error.EndOfStream; } /// Reads 1 byte from the stream or returns `error.EndOfStream`. pub fn readByte(self: *Self) !u8 { var result: [1]u8 = undefined; try self.readNoEof(result[0..]); return result[0]; } /// Same as `readByte` except the returned byte is signed. pub fn readByteSigned(self: *Self) !i8 { return @bitCast(i8, try self.readByte()); } /// Reads a native-endian integer pub fn readIntNative(self: *Self, comptime T: type) !T { var bytes: [@sizeOf(T)]u8 = undefined; try self.readNoEof(bytes[0..]); return mem.readIntSliceNative(T, bytes); } /// Reads a foreign-endian integer pub fn readIntForeign(self: *Self, comptime T: type) !T { var bytes: [@sizeOf(T)]u8 = undefined; try self.readNoEof(bytes[0..]); return mem.readIntSliceForeign(T, bytes); } pub fn readIntLittle(self: *Self, comptime T: type) !T { var bytes: [@sizeOf(T)]u8 = undefined; try self.readNoEof(bytes[0..]); return mem.readIntSliceLittle(T, bytes); } pub fn readIntBig(self: *Self, comptime T: type) !T { var bytes: [@sizeOf(T)]u8 = undefined; try self.readNoEof(bytes[0..]); return mem.readIntSliceBig(T, bytes); } pub fn readInt(self: *Self, comptime T: type, endian: builtin.Endian) !T { var bytes: [@sizeOf(T)]u8 = undefined; try self.readNoEof(bytes[0..]); return mem.readIntSlice(T, bytes, endian); } pub fn readVarInt(self: *Self, comptime ReturnType: type, endian: builtin.Endian, size: usize) !ReturnType { assert(size <= @sizeOf(ReturnType)); var bytes_buf: [@sizeOf(ReturnType)]u8 = undefined; const bytes = bytes_buf[0..size]; try self.readNoEof(bytes); return mem.readVarInt(ReturnType, bytes, endian); } pub fn skipBytes(self: *Self, num_bytes: usize) !void { var i: usize = 0; while (i < num_bytes) : (i += 1) { _ = try self.readByte(); } } pub fn readStruct(self: *Self, comptime T: type) !T { // Only extern and packed structs have defined in-memory layout. comptime assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto); var res: [1]T = undefined; try self.readNoEof(@sliceToBytes(res[0..])); return res[0]; } }; } pub fn OutStream(comptime WriteError: type) type { return struct { const Self = @This(); pub const Error = WriteError; writeFn: fn (self: *Self, bytes: []const u8) Error!void, pub fn print(self: *Self, comptime format: []const u8, args: ...) Error!void { return std.fmt.format(self, Error, self.writeFn, format, args); } pub fn write(self: *Self, bytes: []const u8) Error!void { return self.writeFn(self, bytes); } pub fn writeByte(self: *Self, byte: u8) Error!void { const slice = (*[1]u8)(&byte)[0..]; return self.writeFn(self, slice); } pub fn writeByteNTimes(self: *Self, byte: u8, n: usize) Error!void { const slice = (*[1]u8)(&byte)[0..]; var i: usize = 0; while (i < n) : (i += 1) { try self.writeFn(self, slice); } } /// Write a native-endian integer. pub fn writeIntNative(self: *Self, comptime T: type, value: T) Error!void { var bytes: [@sizeOf(T)]u8 = undefined; mem.writeIntNative(T, &bytes, value); return self.writeFn(self, bytes); } /// Write a foreign-endian integer. pub fn writeIntForeign(self: *Self, comptime T: type, value: T) Error!void { var bytes: [@sizeOf(T)]u8 = undefined; mem.writeIntForeign(T, &bytes, value); return self.writeFn(self, bytes); } pub fn writeIntLittle(self: *Self, comptime T: type, value: T) Error!void { var bytes: [@sizeOf(T)]u8 = undefined; mem.writeIntLittle(T, &bytes, value); return self.writeFn(self, bytes); } pub fn writeIntBig(self: *Self, comptime T: type, value: T) Error!void { var bytes: [@sizeOf(T)]u8 = undefined; mem.writeIntBig(T, &bytes, value); return self.writeFn(self, bytes); } pub fn writeInt(self: *Self, comptime T: type, value: T, endian: builtin.Endian) Error!void { var bytes: [@sizeOf(T)]u8 = undefined; mem.writeInt(T, &bytes, value, endian); return self.writeFn(self, bytes); } }; } pub fn writeFile(path: []const u8, data: []const u8) !void { var file = try File.openWrite(path); defer file.close(); try file.write(data); } /// On success, caller owns returned buffer. pub fn readFileAlloc(allocator: *mem.Allocator, path: []const u8) ![]u8 { return readFileAllocAligned(allocator, path, @alignOf(u8)); } /// On success, caller owns returned buffer. pub fn readFileAllocAligned(allocator: *mem.Allocator, path: []const u8, comptime A: u29) ![]align(A) u8 { var file = try File.openRead(path); defer file.close(); const size = try file.getEndPos(); const buf = try allocator.alignedAlloc(u8, A, size); errdefer allocator.free(buf); var adapter = file.inStream(); try adapter.stream.readNoEof(buf[0..size]); return buf; } pub fn BufferedInStream(comptime Error: type) type { return BufferedInStreamCustom(os.page_size, Error); } pub fn BufferedInStreamCustom(comptime buffer_size: usize, comptime Error: type) type { return struct { const Self = @This(); const Stream = InStream(Error); pub stream: Stream, unbuffered_in_stream: *Stream, buffer: [buffer_size]u8, start_index: usize, end_index: usize, pub fn init(unbuffered_in_stream: *Stream) Self { return Self{ .unbuffered_in_stream = unbuffered_in_stream, .buffer = undefined, // Initialize these two fields to buffer_size so that // in `readFn` we treat the state as being able to read // more from the unbuffered stream. If we set them to 0 // and 0, the code would think we already hit EOF. .start_index = buffer_size, .end_index = buffer_size, .stream = Stream{ .readFn = readFn }, }; } fn readFn(in_stream: *Stream, dest: []u8) !usize { const self = @fieldParentPtr(Self, "stream", in_stream); var dest_index: usize = 0; while (true) { const dest_space = dest.len - dest_index; if (dest_space == 0) { return dest_index; } const amt_buffered = self.end_index - self.start_index; if (amt_buffered == 0) { assert(self.end_index <= buffer_size); if (self.end_index == buffer_size) { // we can read more data from the unbuffered stream if (dest_space < buffer_size) { self.start_index = 0; self.end_index = try self.unbuffered_in_stream.read(self.buffer[0..]); } else { // asking for so much data that buffering is actually less efficient. // forward the request directly to the unbuffered stream const amt_read = try self.unbuffered_in_stream.read(dest[dest_index..]); return dest_index + amt_read; } } else { // reading from the unbuffered stream returned less than we asked for // so we cannot read any more data. return dest_index; } } const copy_amount = math.min(dest_space, amt_buffered); const copy_end_index = self.start_index + copy_amount; mem.copy(u8, dest[dest_index..], self.buffer[self.start_index..copy_end_index]); self.start_index = copy_end_index; dest_index += copy_amount; } } }; } /// Creates a stream which supports 'un-reading' data, so that it can be read again. /// This makes look-ahead style parsing much easier. pub fn PeekStream(comptime buffer_size: usize, comptime InStreamError: type) type { return struct { const Self = @This(); pub const Error = InStreamError; pub const Stream = InStream(Error); pub stream: Stream, base: *Stream, // Right now the look-ahead space is statically allocated, but a version with dynamic allocation // is not too difficult to derive from this. buffer: [buffer_size]u8, index: usize, at_end: bool, pub fn init(base: *Stream) Self { return Self{ .base = base, .buffer = undefined, .index = 0, .at_end = false, .stream = Stream{ .readFn = readFn }, }; } pub fn putBackByte(self: *Self, byte: u8) void { self.buffer[self.index] = byte; self.index += 1; } pub fn putBack(self: *Self, bytes: []const u8) void { var pos = bytes.len; while (pos != 0) { pos -= 1; self.putBackByte(bytes[pos]); } } fn readFn(in_stream: *Stream, dest: []u8) Error!usize { const self = @fieldParentPtr(Self, "stream", in_stream); // copy over anything putBack()'d var pos: usize = 0; while (pos < dest.len and self.index != 0) { dest[pos] = self.buffer[self.index - 1]; self.index -= 1; pos += 1; } if (pos == dest.len or self.at_end) { return pos; } // ask the backing stream for more const left = dest.len - pos; const read = try self.base.read(dest[pos..]); assert(read <= left); self.at_end = (read < left); return pos + read; } }; } pub const SliceInStream = struct { const Self = @This(); pub const Error = error{}; pub const Stream = InStream(Error); pub stream: Stream, pos: usize, slice: []const u8, pub fn init(slice: []const u8) Self { return Self{ .slice = slice, .pos = 0, .stream = Stream{ .readFn = readFn }, }; } fn readFn(in_stream: *Stream, dest: []u8) Error!usize { const self = @fieldParentPtr(Self, "stream", in_stream); const size = math.min(dest.len, self.slice.len - self.pos); const end = self.pos + size; mem.copy(u8, dest[0..size], self.slice[self.pos..end]); self.pos = end; return size; } }; /// This is a simple OutStream that writes to a slice, and returns an error /// when it runs out of space. pub const SliceOutStream = struct { pub const Error = error{OutOfSpace}; pub const Stream = OutStream(Error); pub stream: Stream, pub pos: usize, slice: []u8, pub fn init(slice: []u8) SliceOutStream { return SliceOutStream{ .slice = slice, .pos = 0, .stream = Stream{ .writeFn = writeFn }, }; } pub fn getWritten(self: *const SliceOutStream) []const u8 { return self.slice[0..self.pos]; } pub fn reset(self: *SliceOutStream) void { self.pos = 0; } fn writeFn(out_stream: *Stream, bytes: []const u8) Error!void { const self = @fieldParentPtr(SliceOutStream, "stream", out_stream); assert(self.pos <= self.slice.len); const n = if (self.pos + bytes.len <= self.slice.len) bytes.len else self.slice.len - self.pos; std.mem.copy(u8, self.slice[self.pos .. self.pos + n], bytes[0..n]); self.pos += n; if (n < bytes.len) { return Error.OutOfSpace; } } }; test "io.SliceOutStream" { var buf: [255]u8 = undefined; var slice_stream = SliceOutStream.init(buf[0..]); const stream = &slice_stream.stream; try stream.print("{}{}!", "Hello", "World"); debug.assert(mem.eql(u8, "HelloWorld!", slice_stream.getWritten())); } var null_out_stream_state = NullOutStream.init(); pub const null_out_stream = &null_out_stream_state.stream; /// An OutStream that doesn't write to anything. pub const NullOutStream = struct { pub const Error = error{}; pub const Stream = OutStream(Error); pub stream: Stream, pub fn init() NullOutStream { return NullOutStream{ .stream = Stream{ .writeFn = writeFn }, }; } fn writeFn(out_stream: *Stream, bytes: []const u8) Error!void {} }; test "io.NullOutStream" { var null_stream = NullOutStream.init(); const stream = &null_stream.stream; stream.write("yay" ** 10000) catch unreachable; } /// An OutStream that counts how many bytes has been written to it. pub fn CountingOutStream(comptime OutStreamError: type) type { return struct { const Self = @This(); pub const Stream = OutStream(Error); pub const Error = OutStreamError; pub stream: Stream, pub bytes_written: usize, child_stream: *Stream, pub fn init(child_stream: *Stream) Self { return Self{ .stream = Stream{ .writeFn = writeFn }, .bytes_written = 0, .child_stream = child_stream, }; } fn writeFn(out_stream: *Stream, bytes: []const u8) OutStreamError!void { const self = @fieldParentPtr(Self, "stream", out_stream); try self.child_stream.write(bytes); self.bytes_written += bytes.len; } }; } test "io.CountingOutStream" { var null_stream = NullOutStream.init(); var counting_stream = CountingOutStream(NullOutStream.Error).init(&null_stream.stream); const stream = &counting_stream.stream; const bytes = "yay" ** 10000; stream.write(bytes) catch unreachable; debug.assert(counting_stream.bytes_written == bytes.len); } pub fn BufferedOutStream(comptime Error: type) type { return BufferedOutStreamCustom(os.page_size, Error); } pub fn BufferedOutStreamCustom(comptime buffer_size: usize, comptime OutStreamError: type) type { return struct { const Self = @This(); pub const Stream = OutStream(Error); pub const Error = OutStreamError; pub stream: Stream, unbuffered_out_stream: *Stream, buffer: [buffer_size]u8, index: usize, pub fn init(unbuffered_out_stream: *Stream) Self { return Self{ .unbuffered_out_stream = unbuffered_out_stream, .buffer = undefined, .index = 0, .stream = Stream{ .writeFn = writeFn }, }; } pub fn flush(self: *Self) !void { try self.unbuffered_out_stream.write(self.buffer[0..self.index]); self.index = 0; } fn writeFn(out_stream: *Stream, bytes: []const u8) !void { const self = @fieldParentPtr(Self, "stream", out_stream); if (bytes.len >= self.buffer.len) { try self.flush(); return self.unbuffered_out_stream.write(bytes); } var src_index: usize = 0; while (src_index < bytes.len) { const dest_space_left = self.buffer.len - self.index; const copy_amt = math.min(dest_space_left, bytes.len - src_index); mem.copy(u8, self.buffer[self.index..], bytes[src_index .. src_index + copy_amt]); self.index += copy_amt; assert(self.index <= self.buffer.len); if (self.index == self.buffer.len) { try self.flush(); } src_index += copy_amt; } } }; } /// Implementation of OutStream trait for Buffer pub const BufferOutStream = struct { buffer: *Buffer, stream: Stream, pub const Error = error{OutOfMemory}; pub const Stream = OutStream(Error); pub fn init(buffer: *Buffer) BufferOutStream { return BufferOutStream{ .buffer = buffer, .stream = Stream{ .writeFn = writeFn }, }; } fn writeFn(out_stream: *Stream, bytes: []const u8) !void { const self = @fieldParentPtr(BufferOutStream, "stream", out_stream); return self.buffer.append(bytes); } }; pub const BufferedAtomicFile = struct { atomic_file: os.AtomicFile, file_stream: os.File.OutStream, buffered_stream: BufferedOutStream(os.File.WriteError), allocator: *mem.Allocator, pub fn create(allocator: *mem.Allocator, dest_path: []const u8) !*BufferedAtomicFile { // TODO with well defined copy elision we don't need this allocation var self = try allocator.create(BufferedAtomicFile{ .atomic_file = undefined, .file_stream = undefined, .buffered_stream = undefined, .allocator = allocator, }); errdefer allocator.destroy(self); self.atomic_file = try os.AtomicFile.init(dest_path, os.File.default_mode); errdefer self.atomic_file.deinit(); self.file_stream = self.atomic_file.file.outStream(); self.buffered_stream = BufferedOutStream(os.File.WriteError).init(&self.file_stream.stream); return self; } /// always call destroy, even after successful finish() pub fn destroy(self: *BufferedAtomicFile) void { self.atomic_file.deinit(); self.allocator.destroy(self); } pub fn finish(self: *BufferedAtomicFile) !void { try self.buffered_stream.flush(); try self.atomic_file.finish(); } pub fn stream(self: *BufferedAtomicFile) *OutStream(os.File.WriteError) { return &self.buffered_stream.stream; } }; test "import io tests" { comptime { _ = @import("io_test.zig"); } } pub fn readLine(buf: *std.Buffer) ![]u8 { var stdin = try getStdIn(); var stdin_stream = stdin.inStream(); return readLineFrom(&stdin_stream.stream, buf); } /// Reads all characters until the next newline into buf, and returns /// a slice of the characters read (excluding the newline character(s)). pub fn readLineFrom(stream: var, buf: *std.Buffer) ![]u8 { const start = buf.len(); while (true) { const byte = try stream.readByte(); switch (byte) { '\r' => { // trash the following \n _ = try stream.readByte(); return buf.toSlice()[start..]; }, '\n' => return buf.toSlice()[start..], else => try buf.appendByte(byte), } } } test "io.readLineFrom" { var bytes: [128]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; var buf = try std.Buffer.initSize(allocator, 0); var mem_stream = SliceInStream.init( \\Line 1 \\Line 22 \\Line 333 ); const stream = &mem_stream.stream; debug.assert(mem.eql(u8, "Line 1", try readLineFrom(stream, &buf))); debug.assert(mem.eql(u8, "Line 22", try readLineFrom(stream, &buf))); debug.assertError(readLineFrom(stream, &buf), error.EndOfStream); debug.assert(mem.eql(u8, buf.toSlice(), "Line 1Line 22Line 333")); } pub fn readLineSlice(slice: []u8) ![]u8 { var stdin = try getStdIn(); var stdin_stream = stdin.inStream(); return readLineSliceFrom(&stdin_stream.stream, slice); } /// Reads all characters until the next newline into slice, and returns /// a slice of the characters read (excluding the newline character(s)). pub fn readLineSliceFrom(stream: var, slice: []u8) ![]u8 { // We cannot use Buffer.fromOwnedSlice, as it wants to append a null byte // after taking ownership, which would always require an allocation. var buf = std.Buffer{ .list = std.ArrayList(u8).fromOwnedSlice(debug.failing_allocator, slice) }; try buf.resize(0); return try readLineFrom(stream, &buf); } test "io.readLineSliceFrom" { var buf: [7]u8 = undefined; var mem_stream = SliceInStream.init( \\Line 1 \\Line 22 \\Line 333 ); const stream = &mem_stream.stream; debug.assert(mem.eql(u8, "Line 1", try readLineSliceFrom(stream, buf[0..]))); debug.assertError(readLineSliceFrom(stream, buf[0..]), error.OutOfMemory); }
std/io.zig
const std = @import("std"); const builtin = @import("builtin"); const clap = @import("clap"); const version = @import("version"); const zzz = @import("zzz"); const known_folders = @import("known-folders"); const build_options = @import("build_options"); const api = @import("api.zig"); const Project = @import("Project.zig"); const Lockfile = @import("Lockfile.zig"); const Dependency = @import("Dependency.zig"); const DependencyTree = @import("DependencyTree.zig"); usingnamespace @import("common.zig"); const Allocator = std.mem.Allocator; const FetchContext = struct { project_file: std.fs.File, lock_file: std.fs.File, project: *Project, lockfile: Lockfile, dep_tree: *DependencyTree, build_dep_tree: *DependencyTree, fn deinit(self: *FetchContext) void { self.lockfile.save(self.lock_file) catch {}; self.build_dep_tree.destroy(); self.dep_tree.destroy(); self.lockfile.deinit(); self.project.destroy(); // TODO: delete lockfile if it doesn't have anything in it self.lock_file.close(); self.project_file.close(); } }; pub fn fetchImpl(allocator: *Allocator) !FetchContext { const project_file = std.fs.cwd().openFile( "gyro.zzz", .{ .read = true }, ) catch |err| { return if (err == error.FileNotFound) blk: { std.log.err("Missing gyro.zzz project file", .{}); break :blk error.Explained; } else err; }; errdefer project_file.close(); const lock_file = try std.fs.cwd().createFile( "gyro.lock", .{ .truncate = false, .read = true }, ); errdefer lock_file.close(); var project = try Project.fromFile(allocator, project_file); errdefer project.destroy(); var lockfile = try Lockfile.fromFile(allocator, lock_file); errdefer lockfile.deinit(); const dep_tree = try DependencyTree.generate( allocator, &lockfile, project.deps, ); errdefer dep_tree.destroy(); const build_dep_tree = try DependencyTree.generate( allocator, &lockfile, project.build_deps, ); errdefer build_dep_tree.destroy(); try lockfile.fetchAll(); return FetchContext{ .project_file = project_file, .lock_file = lock_file, .project = project, .lockfile = lockfile, .dep_tree = dep_tree, .build_dep_tree = build_dep_tree, }; } pub fn fetch(allocator: *Allocator) !void { var ctx = try fetchImpl(allocator); defer ctx.deinit(); } pub fn update( allocator: *Allocator, in: ?[]const u8, targets: []const []const u8, ) !void { if (in != null or targets.len > 0) { return error.Todo; } try std.fs.cwd().deleteFile("gyro.lock"); try fetch(allocator); } const EnvInfo = struct { zig_exe: []const u8, lib_dir: []const u8, std_dir: []const u8, global_cache_dir: []const u8, version: []const u8, }; pub fn build(allocator: *Allocator, args: *clap.args.OsIterator) !void { var ctx = try fetchImpl(allocator); defer ctx.deinit(); std.fs.cwd().access("build.zig", .{ .read = true }) catch |err| { return if (err == error.FileNotFound) blk: { std.log.err("no build.zig in current working directory", .{}); break :blk error.Explained; } else err; }; var fifo = std.fifo.LinearFifo(u8, .{ .Dynamic = {} }).init(allocator); defer fifo.deinit(); const result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &[_][]const u8{ "zig", "env" }, }); defer { allocator.free(result.stdout); allocator.free(result.stderr); } switch (result.term) { .Exited => |val| { if (val != 0) { std.log.err("zig compiler returned error code: {}", .{val}); return error.Explained; } }, .Signal => |sig| { std.log.err("zig compiler interrupted by signal: {}", .{sig}); return error.Explained; }, else => return error.UnknownTerm, } const parse_opts = std.json.ParseOptions{ .allocator = allocator }; const env = try std.json.parse( EnvInfo, &std.json.TokenStream.init(result.stdout), parse_opts, ); defer std.json.parseFree(EnvInfo, env, parse_opts); const path = try std.fs.path.join( allocator, &[_][]const u8{ env.std_dir, "special" }, ); defer allocator.free(path); var special_dir = try std.fs.openDirAbsolute( path, .{ .access_sub_paths = true }, ); defer special_dir.close(); try special_dir.copyFile( "build_runner.zig", std.fs.cwd(), "build_runner.zig", .{}, ); defer std.fs.cwd().deleteFile("build_runner.zig") catch {}; // TODO: configurable local cache const pkgs = try ctx.build_dep_tree.assemblePkgs(std.build.Pkg{ .name = "gyro", .path = "deps.zig", }); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const b = try std.build.Builder.create( &arena.allocator, env.zig_exe, ".", "zig-cache", env.global_cache_dir, ); defer b.destroy(); const deps_file = try std.fs.cwd().createFile("deps.zig", .{ .truncate = true }); defer deps_file.close(); try ctx.dep_tree.printZig(deps_file.writer()); b.resolveInstallPrefix(null); const runner = b.addExecutable("build", "build_runner.zig"); runner.addPackage(std.build.Pkg{ .name = "@build", .path = "build.zig", .dependencies = pkgs, }); const run_cmd = runner.run(); run_cmd.addArgs(&[_][]const u8{ env.zig_exe, ".", "zig-cache", env.global_cache_dir, }); while (try args.next()) |arg| run_cmd.addArg(arg); b.default_step.dependOn(&run_cmd.step); if (b.validateUserInputDidItFail()) { return error.UserInputFailed; } b.make(&[_][]const u8{"install"}) catch |err| { switch (err) { error.UncleanExit => { std.log.err("Compiler had an unclean exit", .{}); return error.Explained; }, else => return err, } }; } pub fn package( allocator: *Allocator, output_dir: ?[]const u8, names: []const []const u8, ) !void { const file = try std.fs.cwd().openFile("gyro.zzz", .{ .read = true }); defer file.close(); var project = try Project.fromFile(allocator, file); defer project.destroy(); if (project.packages.count() == 0) { std.log.err("there are no packages to package!", .{}); return error.Explained; } var found_not_pkg = false; for (names) |name| if (!project.contains(name)) { std.log.err("{s} is not a package", .{name}); found_not_pkg = true; }; if (found_not_pkg) return error.Explained; var write_dir = try std.fs.cwd().openDir( if (output_dir) |output| output else ".", .{ .iterate = true, .access_sub_paths = true }, ); defer write_dir.close(); var read_dir = try std.fs.cwd().openDir(".", .{ .iterate = true }); defer read_dir.close(); if (names.len > 0) { for (names) |name| try project.get(name).?.bundle(read_dir, write_dir); } else { var it = project.iterator(); while (it.next()) |pkg| try pkg.bundle(read_dir, write_dir); } } fn maybePrintKey( json_key: []const u8, zzz_key: []const u8, root: anytype, writer: anytype, ) !void { if (root.get(json_key)) |val| { switch (val) { .String => |str| try writer.print(" {s}: \"{s}\"\n", .{ zzz_key, str }), else => {}, } } } pub fn init( allocator: *Allocator, link: ?[]const u8, ) !void { const file = std.fs.cwd().createFile("gyro.zzz", .{ .exclusive = true }) catch |err| { return if (err == error.PathAlreadyExists) blk: { std.log.err("gyro.zzz already exists", .{}); break :blk error.Explained; } else err; }; errdefer std.fs.cwd().deleteFile("gyro.zzz") catch {}; defer file.close(); const info = try parseUserRepo(link orelse return); var repo_tree = try api.getGithubRepo(allocator, info.user, info.repo); defer repo_tree.deinit(); var topics_tree = try api.getGithubTopics(allocator, info.user, info.repo); defer topics_tree.deinit(); if (repo_tree.root != .Object or topics_tree.root != .Object) { std.log.err("Invalid JSON response from Github", .{}); return error.Explained; } const repo_root = repo_tree.root.Object; const topics_root = topics_tree.root.Object; const writer = file.writer(); try writer.print( \\pkgs: \\ {s}: \\ version: 0.0.0 \\ , .{try normalizeName(info.repo)}); try maybePrintKey("description", "description", repo_root, writer); // pretty gross ngl if (repo_root.get("license")) |license| { switch (license) { .Object => |obj| { if (obj.get("spdx_id")) |spdx| { switch (spdx) { .String => |id| { try writer.print(" license: {s}\n", .{id}); }, else => {}, } } }, else => {}, } } try maybePrintKey("html_url", "source_url", repo_root, writer); if (topics_root.get("names")) |topics| { switch (topics) { .Array => |arr| { if (arr.items.len > 0) { try writer.print(" tags:\n", .{}); for (arr.items) |topic| { switch (topic) { .String => |str| if (std.mem.indexOf(u8, str, "zig") == null) { try writer.print(" {s}\n", .{str}); }, else => {}, } } } }, else => {}, } } try writer.print( \\ \\ root: src/main.zig \\ files: \\ README.md \\ LICENSE \\ , .{}); } pub fn add( allocator: *Allocator, src_tag: Dependency.SourceType, alias: ?[]const u8, build_deps: bool, root_path: ?[]const u8, to: ?[]const u8, targets: []const []const u8, ) !void { if (src_tag != .pkg and src_tag != .github) { return error.Todo; } // TODO: detect collisions in subpackages (both directions) const repository = build_options.default_repo; var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const file = try std.fs.cwd().createFile("gyro.zzz", .{ .truncate = false, .read = true, .exclusive = false, }); defer file.close(); var project = try Project.fromFile(allocator, file); defer project.destroy(); const dep_list = if (to) |t| if (project.packages.getEntry(t)) |entry| &entry.value.deps else { std.log.err("{s} is not a an exported package", .{t}); return error.Explained; } else if (build_deps) &project.build_deps else &project.deps; // TODO: handle user/pkg in targets // make sure targets are unique for (targets[0 .. targets.len - 1]) |_, i| { for (targets[i + 1 ..]) |_, j| { if (std.mem.eql(u8, targets[i], targets[j])) { std.log.err("duplicated target: {s}", .{targets[i]}); return error.Explained; } } } // ensure all targets are valid for (targets) |target| { for (dep_list.items) |dep| { if (std.mem.eql(u8, target, dep.alias)) { if (to) |t| std.log.err("{s} is already a dependency of {s}", .{ target, t }) else std.log.err("{s} is already a dependency", .{target}); return error.Explained; } } } for (targets) |target| { const info = try parseUserRepo(target); const dep = if (src_tag == .github) blk: { var value_tree = try api.getGithubRepo(&arena.allocator, info.user, info.repo); if (value_tree.root != .Object) { std.log.err("Invalid JSON response from Github", .{}); return error.Explained; } const root_json = value_tree.root.Object; const default_branch = if (root_json.get("default_branch")) |val| switch (val) { .String => |str| str, else => "main", } else "main"; const text_opt = try api.getGithubGyroFile( &arena.allocator, info.user, info.repo, try api.getHeadCommit(&arena.allocator, info.user, info.repo, default_branch), ); const root_file = if (root_path) |rp| rp else if (text_opt) |t| get_root: { const subproject = try Project.fromText(&arena.allocator, t); defer subproject.destroy(); var ret: []const u8 = default_root; if (subproject.packages.count() == 1) ret = if (subproject.packages.iterator().next().?.value.root) |r| try arena.allocator.dupe(u8, r) else default_root; // TODO try other matching methods break :get_root ret; } else default_root; break :blk Dependency{ .alias = try normalizeName(info.repo), .src = .{ .github = .{ .user = info.user, .repo = info.repo, .ref = default_branch, .root = root_file, }, }, }; } else blk: { const latest = try api.getLatest(&arena.allocator, repository, info.user, info.repo, null); var buf = try arena.allocator.alloc(u8, 80); var stream = std.io.fixedBufferStream(buf); try stream.writer().print("^{}", .{latest}); break :blk Dependency{ .alias = info.repo, .src = .{ .pkg = .{ .user = info.user, .name = info.repo, .version = version.Range{ .min = latest, .kind = .caret, }, .repository = build_options.default_repo, .ver_str = stream.getWritten(), }, }, }; }; try dep_list.append(dep); } try project.toFile(file); } pub fn remove( allocator: *Allocator, build_deps: bool, from: ?[]const u8, targets: []const []const u8, ) !void { if (build_deps and from != null) { std.log.err("packages can't have build subdependencies", .{}); return error.Explained; } var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const file = try std.fs.cwd().createFile("gyro.zzz", .{ .truncate = false, .read = true, .exclusive = false, }); defer file.close(); var project = try Project.fromFile(allocator, file); defer project.destroy(); std.log.debug("packages at start: {}", .{project.packages.count()}); const dep_list = if (from) |f| if (project.packages.getEntry(f)) |entry| &entry.value.deps else { std.log.err("{s} is not a an exported package", .{f}); return error.Explained; } else if (build_deps) &project.build_deps else &project.deps; // make sure targets are unique for (targets) |_, i| { var j: usize = i + 1; while (j < targets.len) : (j += 1) { if (std.mem.eql(u8, targets[i], targets[j])) { std.log.err("duplicated target: {s}", .{targets[i]}); return error.Explained; } } } // ensure all targets are valid for (targets) |target| { for (dep_list.items) |dep| { if (std.mem.eql(u8, target, dep.alias)) break; } else { if (from) |f| std.log.err("{s} is not a dependency of {s}", .{ target, f }) else std.log.err("{s} is not a dependency", .{target}); return error.Explained; } } // remove targets for (targets) |target| { for (dep_list.items) |dep, i| { if (std.mem.eql(u8, target, dep.alias)) { std.log.debug("removing target: {s}", .{target}); _ = dep_list.swapRemove(i); break; } } } std.log.debug("packages: {}", .{project.packages.count()}); try project.toFile(file); } pub fn publish(allocator: *Allocator, pkg: ?[]const u8) !void { const client_id = "ea14bba19a49f4cba053"; const scope = "read:user user:email"; const file = std.fs.cwd().openFile("gyro.zzz", .{ .read = true }) catch |err| { if (err == error.FileNotFound) { std.log.err("missing gyro.zzz file", .{}); return error.Explained; } else return err; }; defer file.close(); var project = try Project.fromFile(allocator, file); defer project.destroy(); if (project.packages.count() == 0) { std.log.err("there are no packages to publish!", .{}); return error.Explained; } const name = if (pkg) |p| blk: { if (!project.contains(p)) { std.log.err("{s} is not a package", .{p}); return error.Explained; } break :blk p; } else if (project.packages.count() == 1) project.iterator().next().?.name else { std.log.err("there are multiple packages exported, choose one", .{}); return error.Explained; }; var access_token: ?[]const u8 = std.process.getEnvVarOwned(allocator, "GYRO_ACCESS_TOKEN") catch |err| blk: { if (err == error.EnvironmentVariableNotFound) break :blk null else return err; }; defer if (access_token) |at| allocator.free(at); if (access_token == null) { access_token = blk: { var dir = if (try known_folders.open(allocator, .cache, .{ .access_sub_paths = true })) |d| d else break :blk null; defer dir.close(); const cache_file = dir.openFile("gyro-access-token", .{}) catch |err| { if (err == error.FileNotFound) break :blk null else return err; }; defer cache_file.close(); break :blk try cache_file.reader().readAllAlloc(allocator, std.math.maxInt(usize)); }; } if (access_token == null) { const open_program: []const u8 = switch (builtin.os.tag) { .windows => "explorer", .macos => "open", else => "xdg-open", }; var browser = try std.ChildProcess.init(&.{ open_program, "https://github.com/login/device" }, allocator); defer browser.deinit(); _ = browser.spawnAndWait() catch { try std.io.getStdErr().writer().print("Failed to open your browser, please go to https://github.com/login/device", .{}); }; var device_code_resp = try api.postDeviceCode(allocator, client_id, scope); defer std.json.parseFree(api.DeviceCodeResponse, device_code_resp, .{ .allocator = allocator }); const stderr = std.io.getStdErr().writer(); try stderr.print("enter this code: {s}\nwaiting for github authentication...\n", .{device_code_resp.user_code}); const end_time = device_code_resp.expires_in + @intCast(u64, std.time.timestamp()); const interval_ns = device_code_resp.interval * std.time.ns_per_s; access_token = while (std.time.timestamp() < end_time) : (std.time.sleep(interval_ns)) { if (try api.pollDeviceCode(allocator, client_id, device_code_resp.device_code)) |resp| { if (try known_folders.open(allocator, .cache, .{ .access_sub_paths = true })) |*dir| { defer dir.close(); const cache_file = try dir.createFile("gyro-access-token", .{ .truncate = true }); defer cache_file.close(); try cache_file.writer().writeAll(resp); } break resp; } } else { std.log.err("timed out device polling", .{}); return error.Explained; }; } if (access_token == null) { std.log.err("failed to get access token", .{}); return error.Explained; } try api.postPublish(allocator, access_token.?, project.get(name).?); }
src/commands.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const assert = std.debug.assert; const testing = std.testing; const Loop = std.event.Loop; /// Many producer, many consumer, thread-safe, runtime configurable buffer size. /// When buffer is empty, consumers suspend and are resumed by producers. /// When buffer is full, producers suspend and are resumed by consumers. pub fn Channel(comptime T: type) type { return struct { getters: std.atomic.Queue(GetNode), or_null_queue: std.atomic.Queue(*std.atomic.Queue(GetNode).Node), putters: std.atomic.Queue(PutNode), get_count: usize, put_count: usize, dispatch_lock: u8, // TODO make this a bool need_dispatch: u8, // TODO make this a bool // simple fixed size ring buffer buffer_nodes: []T, buffer_index: usize, buffer_len: usize, const SelfChannel = @This(); const GetNode = struct { tick_node: *Loop.NextTickNode, data: Data, const Data = union(enum) { Normal: Normal, OrNull: OrNull, }; const Normal = struct { ptr: *T, }; const OrNull = struct { ptr: *?T, or_null: *std.atomic.Queue(*std.atomic.Queue(GetNode).Node).Node, }; }; const PutNode = struct { data: T, tick_node: *Loop.NextTickNode, }; const global_event_loop = Loop.instance orelse @compileError("std.event.Channel currently only works with event-based I/O"); /// Call `deinit` to free resources when done. /// `buffer` must live until `deinit` is called. /// For a zero length buffer, use `[0]T{}`. /// TODO https://github.com/ziglang/zig/issues/2765 pub fn init(self: *SelfChannel, buffer: []T) void { self.* = SelfChannel{ .buffer_len = 0, .buffer_nodes = buffer, .buffer_index = 0, .dispatch_lock = 0, .need_dispatch = 0, .getters = std.atomic.Queue(GetNode).init(), .putters = std.atomic.Queue(PutNode).init(), .or_null_queue = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).init(), .get_count = 0, .put_count = 0, }; } /// Must be called when all calls to put and get have suspended and no more calls occur. /// This can be omitted if caller can guarantee that the suspended putters and getters /// do not need to be run to completion. Note that this may leave awaiters hanging. pub fn deinit(self: *SelfChannel) void { while (self.getters.get()) |get_node| { resume get_node.data.tick_node.data; } while (self.putters.get()) |put_node| { resume put_node.data.tick_node.data; } self.* = undefined; } /// puts a data item in the channel. The function returns when the value has been added to the /// buffer, or in the case of a zero size buffer, when the item has been retrieved by a getter. /// Or when the channel is destroyed. pub fn put(self: *SelfChannel, data: T) void { var my_tick_node = Loop.NextTickNode.init(@frame()); var queue_node = std.atomic.Queue(PutNode).Node.init(PutNode{ .tick_node = &my_tick_node, .data = data, }); suspend { self.putters.put(&queue_node); _ = @atomicRmw(usize, &self.put_count, .Add, 1, .SeqCst); self.dispatch(); } } /// await this function to get an item from the channel. If the buffer is empty, the frame will /// complete when the next item is put in the channel. pub async fn get(self: *SelfChannel) T { // TODO https://github.com/ziglang/zig/issues/2765 var result: T = undefined; var my_tick_node = Loop.NextTickNode.init(@frame()); var queue_node = std.atomic.Queue(GetNode).Node.init(GetNode{ .tick_node = &my_tick_node, .data = GetNode.Data{ .Normal = GetNode.Normal{ .ptr = &result }, }, }); suspend { self.getters.put(&queue_node); _ = @atomicRmw(usize, &self.get_count, .Add, 1, .SeqCst); self.dispatch(); } return result; } //pub async fn select(comptime EnumUnion: type, channels: ...) EnumUnion { // assert(@memberCount(EnumUnion) == channels.len); // enum union and channels mismatch // assert(channels.len != 0); // enum unions cannot have 0 fields // if (channels.len == 1) { // const result = await (async channels[0].get() catch unreachable); // return @unionInit(EnumUnion, @memberName(EnumUnion, 0), result); // } //} /// Get an item from the channel. If the buffer is empty and there are no /// puts waiting, this returns `null`. pub fn getOrNull(self: *SelfChannel) ?T { // TODO integrate this function with named return values // so we can get rid of this extra result copy var result: ?T = null; var my_tick_node = Loop.NextTickNode.init(@frame()); var or_null_node = std.atomic.Queue(*std.atomic.Queue(GetNode).Node).Node.init(undefined); var queue_node = std.atomic.Queue(GetNode).Node.init(GetNode{ .tick_node = &my_tick_node, .data = GetNode.Data{ .OrNull = GetNode.OrNull{ .ptr = &result, .or_null = &or_null_node, }, }, }); or_null_node.data = &queue_node; suspend { self.getters.put(&queue_node); _ = @atomicRmw(usize, &self.get_count, .Add, 1, .SeqCst); self.or_null_queue.put(&or_null_node); self.dispatch(); } return result; } fn dispatch(self: *SelfChannel) void { // set the "need dispatch" flag @atomicStore(u8, &self.need_dispatch, 1, .SeqCst); lock: while (true) { // set the lock flag const prev_lock = @atomicRmw(u8, &self.dispatch_lock, .Xchg, 1, .SeqCst); if (prev_lock != 0) return; // clear the need_dispatch flag since we're about to do it @atomicStore(u8, &self.need_dispatch, 0, .SeqCst); while (true) { one_dispatch: { // later we correct these extra subtractions var get_count = @atomicRmw(usize, &self.get_count, .Sub, 1, .SeqCst); var put_count = @atomicRmw(usize, &self.put_count, .Sub, 1, .SeqCst); // transfer self.buffer to self.getters while (self.buffer_len != 0) { if (get_count == 0) break :one_dispatch; const get_node = &self.getters.get().?.data; switch (get_node.data) { GetNode.Data.Normal => |info| { info.ptr.* = self.buffer_nodes[self.buffer_index -% self.buffer_len]; }, GetNode.Data.OrNull => |info| { _ = self.or_null_queue.remove(info.or_null); info.ptr.* = self.buffer_nodes[self.buffer_index -% self.buffer_len]; }, } global_event_loop.onNextTick(get_node.tick_node); self.buffer_len -= 1; get_count = @atomicRmw(usize, &self.get_count, .Sub, 1, .SeqCst); } // direct transfer self.putters to self.getters while (get_count != 0 and put_count != 0) { const get_node = &self.getters.get().?.data; const put_node = &self.putters.get().?.data; switch (get_node.data) { GetNode.Data.Normal => |info| { info.ptr.* = put_node.data; }, GetNode.Data.OrNull => |info| { _ = self.or_null_queue.remove(info.or_null); info.ptr.* = put_node.data; }, } global_event_loop.onNextTick(get_node.tick_node); global_event_loop.onNextTick(put_node.tick_node); get_count = @atomicRmw(usize, &self.get_count, .Sub, 1, .SeqCst); put_count = @atomicRmw(usize, &self.put_count, .Sub, 1, .SeqCst); } // transfer self.putters to self.buffer while (self.buffer_len != self.buffer_nodes.len and put_count != 0) { const put_node = &self.putters.get().?.data; self.buffer_nodes[self.buffer_index] = put_node.data; global_event_loop.onNextTick(put_node.tick_node); self.buffer_index +%= 1; self.buffer_len += 1; put_count = @atomicRmw(usize, &self.put_count, .Sub, 1, .SeqCst); } } // undo the extra subtractions _ = @atomicRmw(usize, &self.get_count, .Add, 1, .SeqCst); _ = @atomicRmw(usize, &self.put_count, .Add, 1, .SeqCst); // All the "get or null" functions should resume now. var remove_count: usize = 0; while (self.or_null_queue.get()) |or_null_node| { remove_count += @boolToInt(self.getters.remove(or_null_node.data)); global_event_loop.onNextTick(or_null_node.data.data.tick_node); } if (remove_count != 0) { _ = @atomicRmw(usize, &self.get_count, .Sub, remove_count, .SeqCst); } // clear need-dispatch flag const need_dispatch = @atomicRmw(u8, &self.need_dispatch, .Xchg, 0, .SeqCst); if (need_dispatch != 0) continue; const my_lock = @atomicRmw(u8, &self.dispatch_lock, .Xchg, 0, .SeqCst); assert(my_lock != 0); // we have to check again now that we unlocked if (@atomicLoad(u8, &self.need_dispatch, .SeqCst) != 0) continue :lock; return; } } } }; } test "std.event.Channel" { // https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/3251 if (builtin.os == .freebsd) return error.SkipZigTest; // TODO provide a way to run tests in evented I/O mode if (!std.io.is_async) return error.SkipZigTest; var channel: Channel(i32) = undefined; channel.init([0]i32{}); defer channel.deinit(); var handle = async testChannelGetter(&channel); var putter = async testChannelPutter(&channel); await handle; await putter; } async fn testChannelGetter(channel: *Channel(i32)) void { const value1 = channel.get(); testing.expect(value1 == 1234); const value2 = channel.get(); testing.expect(value2 == 4567); const value3 = channel.getOrNull(); testing.expect(value3 == null); var last_put = async testPut(channel, 4444); const value4 = channel.getOrNull(); testing.expect(value4.? == 4444); await last_put; } async fn testChannelPutter(channel: *Channel(i32)) void { channel.put(1234); channel.put(4567); } async fn testPut(channel: *Channel(i32), value: i32) void { channel.put(value); }
lib/std/event/channel.zig
const Dylib = @This(); const std = @import("std"); const assert = std.debug.assert; const fs = std.fs; const fmt = std.fmt; const log = std.log.scoped(.dylib); const macho = std.macho; const math = std.math; const mem = std.mem; const fat = @import("fat.zig"); const commands = @import("commands.zig"); const Allocator = mem.Allocator; const Arch = std.Target.Cpu.Arch; const LibStub = @import("../tapi.zig").LibStub; const LoadCommand = commands.LoadCommand; const MachO = @import("../MachO.zig"); file: fs.File, name: []const u8, header: ?macho.mach_header_64 = null, // The actual dylib contents we care about linking with will be embedded at // an offset within a file if we are linking against a fat lib library_offset: u64 = 0, load_commands: std.ArrayListUnmanaged(LoadCommand) = .{}, symtab_cmd_index: ?u16 = null, dysymtab_cmd_index: ?u16 = null, id_cmd_index: ?u16 = null, id: ?Id = null, /// Parsed symbol table represented as hash map of symbols' /// names. We can and should defer creating *Symbols until /// a symbol is referenced by an object file. symbols: std.StringArrayHashMapUnmanaged(void) = .{}, /// Array list of all dependent libs of this dylib. dependent_libs: std.ArrayListUnmanaged(Id) = .{}, pub const Id = struct { name: []const u8, timestamp: u32, current_version: u32, compatibility_version: u32, pub fn default(allocator: *Allocator, name: []const u8) !Id { return Id{ .name = try allocator.dupe(u8, name), .timestamp = 2, .current_version = 0x10000, .compatibility_version = 0x10000, }; } pub fn fromLoadCommand(allocator: *Allocator, lc: commands.GenericCommandWithData(macho.dylib_command)) !Id { const dylib = lc.inner.dylib; const dylib_name = @ptrCast([*:0]const u8, lc.data[dylib.name - @sizeOf(macho.dylib_command) ..]); const name = try allocator.dupe(u8, mem.spanZ(dylib_name)); return Id{ .name = name, .timestamp = dylib.timestamp, .current_version = dylib.current_version, .compatibility_version = dylib.compatibility_version, }; } pub fn deinit(id: *Id, allocator: *Allocator) void { allocator.free(id.name); } const ParseError = fmt.ParseIntError || fmt.BufPrintError; pub fn parseCurrentVersion(id: *Id, version: anytype) ParseError!void { id.current_version = try parseVersion(version); } pub fn parseCompatibilityVersion(id: *Id, version: anytype) ParseError!void { id.compatibility_version = try parseVersion(version); } fn parseVersion(version: anytype) ParseError!u32 { const string = blk: { switch (version) { .int => |int| { var out: u32 = 0; const major = try math.cast(u16, int); out += @intCast(u32, major) << 16; return out; }, .float => |float| { var buf: [256]u8 = undefined; break :blk try fmt.bufPrint(&buf, "{d:.2}", .{float}); }, .string => |string| { break :blk string; }, } }; var out: u32 = 0; var values: [3][]const u8 = undefined; var split = mem.split(u8, string, "."); var count: u4 = 0; while (split.next()) |value| { if (count > 2) { log.warn("malformed version field: {s}", .{string}); return 0x10000; } values[count] = value; count += 1; } if (count > 2) { out += try fmt.parseInt(u8, values[2], 10); } if (count > 1) { out += @intCast(u32, try fmt.parseInt(u8, values[1], 10)) << 8; } out += @intCast(u32, try fmt.parseInt(u16, values[0], 10)) << 16; return out; } }; pub const Error = error{ OutOfMemory, EmptyStubFile, MismatchedCpuArchitecture, UnsupportedCpuArchitecture, } || fs.File.OpenError || std.os.PReadError || Id.ParseError; pub const CreateOpts = struct { syslibroot: ?[]const u8 = null, id: ?Id = null, }; pub fn createAndParseFromPath( allocator: *Allocator, arch: Arch, path: []const u8, opts: CreateOpts, ) Error!?[]Dylib { const file = fs.cwd().openFile(path, .{}) catch |err| switch (err) { error.FileNotFound => return null, else => |e| return e, }; errdefer file.close(); const name = try allocator.dupe(u8, path); errdefer allocator.free(name); var dylib = Dylib{ .name = name, .file = file, }; dylib.parse(allocator, arch) catch |err| switch (err) { error.EndOfStream, error.NotDylib => { try file.seekTo(0); var lib_stub = LibStub.loadFromFile(allocator, file) catch { dylib.deinit(allocator); return null; }; defer lib_stub.deinit(); try dylib.parseFromStub(allocator, arch, lib_stub); }, else => |e| return e, }; if (opts.id) |id| { if (dylib.id.?.current_version < id.compatibility_version) { log.warn("found dylib is incompatible with the required minimum version", .{}); log.warn(" | dylib: {s}", .{id.name}); log.warn(" | required minimum version: {}", .{id.compatibility_version}); log.warn(" | dylib version: {}", .{dylib.id.?.current_version}); // TODO maybe this should be an error and facilitate auto-cleanup? dylib.deinit(allocator); return null; } } var dylibs = std.ArrayList(Dylib).init(allocator); defer dylibs.deinit(); try dylibs.append(dylib); // TODO this should not be performed if the user specifies `-flat_namespace` flag. // See ld64 manpages. try dylib.parseDependentLibs(allocator, arch, &dylibs, opts.syslibroot); return dylibs.toOwnedSlice(); } pub fn deinit(self: *Dylib, allocator: *Allocator) void { for (self.load_commands.items) |*lc| { lc.deinit(allocator); } self.load_commands.deinit(allocator); for (self.symbols.keys()) |key| { allocator.free(key); } self.symbols.deinit(allocator); for (self.dependent_libs.items) |*id| { id.deinit(allocator); } self.dependent_libs.deinit(allocator); allocator.free(self.name); if (self.id) |*id| { id.deinit(allocator); } } pub fn parse(self: *Dylib, allocator: *Allocator, arch: Arch) !void { log.debug("parsing shared library '{s}'", .{self.name}); self.library_offset = try fat.getLibraryOffset(self.file.reader(), arch); try self.file.seekTo(self.library_offset); var reader = self.file.reader(); self.header = try reader.readStruct(macho.mach_header_64); if (self.header.?.filetype != macho.MH_DYLIB) { log.debug("invalid filetype: expected 0x{x}, found 0x{x}", .{ macho.MH_DYLIB, self.header.?.filetype }); return error.NotDylib; } const this_arch: Arch = try fat.decodeArch(self.header.?.cputype, true); if (this_arch != arch) { log.err("mismatched cpu architecture: expected {s}, found {s}", .{ arch, this_arch }); return error.MismatchedCpuArchitecture; } try self.readLoadCommands(allocator, reader); try self.parseId(allocator); try self.parseSymbols(allocator); } fn readLoadCommands(self: *Dylib, allocator: *Allocator, reader: anytype) !void { const should_lookup_reexports = self.header.?.flags & macho.MH_NO_REEXPORTED_DYLIBS == 0; try self.load_commands.ensureCapacity(allocator, self.header.?.ncmds); var i: u16 = 0; while (i < self.header.?.ncmds) : (i += 1) { var cmd = try LoadCommand.read(allocator, reader); switch (cmd.cmd()) { macho.LC_SYMTAB => { self.symtab_cmd_index = i; }, macho.LC_DYSYMTAB => { self.dysymtab_cmd_index = i; }, macho.LC_ID_DYLIB => { self.id_cmd_index = i; }, macho.LC_REEXPORT_DYLIB => { if (should_lookup_reexports) { // Parse install_name to dependent dylib. const id = try Id.fromLoadCommand(allocator, cmd.Dylib); try self.dependent_libs.append(allocator, id); } }, else => { log.debug("Unknown load command detected: 0x{x}.", .{cmd.cmd()}); }, } self.load_commands.appendAssumeCapacity(cmd); } } fn parseId(self: *Dylib, allocator: *Allocator) !void { const index = self.id_cmd_index orelse { log.debug("no LC_ID_DYLIB load command found; using hard-coded defaults...", .{}); self.id = try Id.default(allocator, self.name); return; }; self.id = try Id.fromLoadCommand(allocator, self.load_commands.items[index].Dylib); } fn parseSymbols(self: *Dylib, allocator: *Allocator) !void { const index = self.symtab_cmd_index orelse return; const symtab_cmd = self.load_commands.items[index].Symtab; var symtab = try allocator.alloc(u8, @sizeOf(macho.nlist_64) * symtab_cmd.nsyms); defer allocator.free(symtab); _ = try self.file.preadAll(symtab, symtab_cmd.symoff + self.library_offset); const slice = @alignCast(@alignOf(macho.nlist_64), mem.bytesAsSlice(macho.nlist_64, symtab)); var strtab = try allocator.alloc(u8, symtab_cmd.strsize); defer allocator.free(strtab); _ = try self.file.preadAll(strtab, symtab_cmd.stroff + self.library_offset); for (slice) |sym| { const add_to_symtab = MachO.symbolIsExt(sym) and (MachO.symbolIsSect(sym) or MachO.symbolIsIndr(sym)); if (!add_to_symtab) continue; const sym_name = mem.spanZ(@ptrCast([*:0]const u8, strtab.ptr + sym.n_strx)); const name = try allocator.dupe(u8, sym_name); try self.symbols.putNoClobber(allocator, name, {}); } } fn hasTarget(targets: []const []const u8, target: []const u8) bool { for (targets) |t| { if (mem.eql(u8, t, target)) return true; } return false; } fn addObjCClassSymbols(self: *Dylib, allocator: *Allocator, sym_name: []const u8) !void { const expanded = &[_][]const u8{ try std.fmt.allocPrint(allocator, "_OBJC_CLASS_$_{s}", .{sym_name}), try std.fmt.allocPrint(allocator, "_OBJC_METACLASS_$_{s}", .{sym_name}), }; for (expanded) |sym| { if (self.symbols.contains(sym)) continue; try self.symbols.putNoClobber(allocator, sym, .{}); } } pub fn parseFromStub(self: *Dylib, allocator: *Allocator, arch: Arch, lib_stub: LibStub) !void { if (lib_stub.inner.len == 0) return error.EmptyStubFile; log.debug("parsing shared library from stub '{s}'", .{self.name}); const umbrella_lib = lib_stub.inner[0]; var id = try Id.default(allocator, umbrella_lib.install_name); if (umbrella_lib.current_version) |version| { try id.parseCurrentVersion(version); } if (umbrella_lib.compatibility_version) |version| { try id.parseCompatibilityVersion(version); } self.id = id; const target_string: []const u8 = switch (arch) { .aarch64 => "arm64-macos", .x86_64 => "x86_64-macos", else => unreachable, }; var umbrella_libs = std.StringHashMap(void).init(allocator); defer umbrella_libs.deinit(); for (lib_stub.inner) |stub, stub_index| { if (!hasTarget(stub.targets, target_string)) continue; if (stub_index > 0) { // TODO I thought that we could switch on presence of `parent-umbrella` map; // however, turns out `libsystem_notify.dylib` is fully reexported by `libSystem.dylib` // BUT does not feature a `parent-umbrella` map as the only sublib. Apple's bug perhaps? try umbrella_libs.put(stub.install_name, .{}); } if (stub.exports) |exports| { for (exports) |exp| { if (!hasTarget(exp.targets, target_string)) continue; if (exp.symbols) |symbols| { for (symbols) |sym_name| { if (self.symbols.contains(sym_name)) continue; try self.symbols.putNoClobber(allocator, try allocator.dupe(u8, sym_name), {}); } } if (exp.objc_classes) |classes| { for (classes) |sym_name| { try self.addObjCClassSymbols(allocator, sym_name); } } } } if (stub.reexports) |reexports| { for (reexports) |reexp| { if (!hasTarget(reexp.targets, target_string)) continue; if (reexp.symbols) |symbols| { for (symbols) |sym_name| { if (self.symbols.contains(sym_name)) continue; try self.symbols.putNoClobber(allocator, try allocator.dupe(u8, sym_name), {}); } } if (reexp.objc_classes) |classes| { for (classes) |sym_name| { try self.addObjCClassSymbols(allocator, sym_name); } } } } if (stub.objc_classes) |classes| { for (classes) |sym_name| { try self.addObjCClassSymbols(allocator, sym_name); } } } log.debug("{s}", .{umbrella_lib.install_name}); // TODO track which libs were already parsed in different steps for (lib_stub.inner) |stub| { if (!hasTarget(stub.targets, target_string)) continue; if (stub.reexported_libraries) |reexports| { for (reexports) |reexp| { if (!hasTarget(reexp.targets, target_string)) continue; for (reexp.libraries) |lib| { if (umbrella_libs.contains(lib)) { log.debug(" | {s} <= {s}", .{ lib, umbrella_lib.install_name }); continue; } log.debug(" | {s}", .{lib}); const dep_id = try Id.default(allocator, lib); try self.dependent_libs.append(allocator, dep_id); } } } } } pub fn parseDependentLibs( self: *Dylib, allocator: *Allocator, arch: Arch, out: *std.ArrayList(Dylib), syslibroot: ?[]const u8, ) !void { outer: for (self.dependent_libs.items) |id| { const has_ext = blk: { const basename = fs.path.basename(id.name); break :blk mem.lastIndexOfScalar(u8, basename, '.') != null; }; const extension = if (has_ext) fs.path.extension(id.name) else ""; const without_ext = if (has_ext) blk: { const index = mem.lastIndexOfScalar(u8, id.name, '.') orelse unreachable; break :blk id.name[0..index]; } else id.name; for (&[_][]const u8{ extension, ".tbd" }) |ext| { const with_ext = try std.fmt.allocPrint(allocator, "{s}{s}", .{ without_ext, ext, }); defer allocator.free(with_ext); const full_path = if (syslibroot) |root| try fs.path.join(allocator, &.{ root, with_ext }) else with_ext; defer if (syslibroot) |_| allocator.free(full_path); log.debug("trying dependency at fully resolved path {s}", .{full_path}); const dylibs = (try createAndParseFromPath( allocator, arch, full_path, .{ .id = id, .syslibroot = syslibroot, }, )) orelse { continue; }; defer allocator.free(dylibs); try out.appendSlice(dylibs); continue :outer; } else { log.warn("unable to resolve dependency {s}", .{id.name}); } } }
src/link/MachO/Dylib.zig
const builtin = @import("builtin"); const TypeInfo = builtin.TypeInfo; const std = @import("std"); const testing = std.testing; fn testTypes(comptime types: []const type) !void { inline for (types) |testType| { try testing.expect(testType == @Type(@typeInfo(testType))); } } test "Type.MetaType" { try testing.expect(type == @Type(TypeInfo{ .Type = undefined })); try testTypes(&[_]type{type}); } test "Type.Void" { try testing.expect(void == @Type(TypeInfo{ .Void = undefined })); try testTypes(&[_]type{void}); } test "Type.Bool" { try testing.expect(bool == @Type(TypeInfo{ .Bool = undefined })); try testTypes(&[_]type{bool}); } test "Type.NoReturn" { try testing.expect(noreturn == @Type(TypeInfo{ .NoReturn = undefined })); try testTypes(&[_]type{noreturn}); } test "Type.Int" { try testing.expect(u1 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = 1 } })); try testing.expect(i1 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .signed, .bits = 1 } })); try testing.expect(u8 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = 8 } })); try testing.expect(i8 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .signed, .bits = 8 } })); try testing.expect(u64 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .unsigned, .bits = 64 } })); try testing.expect(i64 == @Type(TypeInfo{ .Int = TypeInfo.Int{ .signedness = .signed, .bits = 64 } })); try testTypes(&[_]type{ u8, u32, i64 }); } test "Type.Float" { try testing.expect(f16 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 16 } })); try testing.expect(f32 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 32 } })); try testing.expect(f64 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 64 } })); try testing.expect(f128 == @Type(TypeInfo{ .Float = TypeInfo.Float{ .bits = 128 } })); try testTypes(&[_]type{ f16, f32, f64, f128 }); } test "Type.Pointer" { try testTypes(&[_]type{ // One Value Pointer Types *u8, *const u8, *volatile u8, *const volatile u8, *align(4) u8, *align(4) const u8, *align(4) volatile u8, *align(4) const volatile u8, *align(8) u8, *align(8) const u8, *align(8) volatile u8, *align(8) const volatile u8, *allowzero u8, *allowzero const u8, *allowzero volatile u8, *allowzero const volatile u8, *allowzero align(4) u8, *allowzero align(4) const u8, *allowzero align(4) volatile u8, *allowzero align(4) const volatile u8, // Many Values Pointer Types [*]u8, [*]const u8, [*]volatile u8, [*]const volatile u8, [*]align(4) u8, [*]align(4) const u8, [*]align(4) volatile u8, [*]align(4) const volatile u8, [*]align(8) u8, [*]align(8) const u8, [*]align(8) volatile u8, [*]align(8) const volatile u8, [*]allowzero u8, [*]allowzero const u8, [*]allowzero volatile u8, [*]allowzero const volatile u8, [*]allowzero align(4) u8, [*]allowzero align(4) const u8, [*]allowzero align(4) volatile u8, [*]allowzero align(4) const volatile u8, // Slice Types []u8, []const u8, []volatile u8, []const volatile u8, []align(4) u8, []align(4) const u8, []align(4) volatile u8, []align(4) const volatile u8, []align(8) u8, []align(8) const u8, []align(8) volatile u8, []align(8) const volatile u8, []allowzero u8, []allowzero const u8, []allowzero volatile u8, []allowzero const volatile u8, []allowzero align(4) u8, []allowzero align(4) const u8, []allowzero align(4) volatile u8, []allowzero align(4) const volatile u8, // C Pointer Types [*c]u8, [*c]const u8, [*c]volatile u8, [*c]const volatile u8, [*c]align(4) u8, [*c]align(4) const u8, [*c]align(4) volatile u8, [*c]align(4) const volatile u8, [*c]align(8) u8, [*c]align(8) const u8, [*c]align(8) volatile u8, [*c]align(8) const volatile u8, }); } test "Type.Array" { try testing.expect([123]u8 == @Type(TypeInfo{ .Array = TypeInfo.Array{ .len = 123, .child = u8, .sentinel = null, }, })); try testing.expect([2]u32 == @Type(TypeInfo{ .Array = TypeInfo.Array{ .len = 2, .child = u32, .sentinel = null, }, })); try testing.expect([2:0]u32 == @Type(TypeInfo{ .Array = TypeInfo.Array{ .len = 2, .child = u32, .sentinel = 0, }, })); try testTypes(&[_]type{ [1]u8, [30]usize, [7]bool }); } test "Type.ComptimeFloat" { try testTypes(&[_]type{comptime_float}); } test "Type.ComptimeInt" { try testTypes(&[_]type{comptime_int}); } test "Type.Undefined" { try testTypes(&[_]type{@TypeOf(undefined)}); } test "Type.Null" { try testTypes(&[_]type{@TypeOf(null)}); } test "@Type create slice with null sentinel" { const Slice = @Type(builtin.TypeInfo{ .Pointer = .{ .size = .Slice, .is_const = true, .is_volatile = false, .is_allowzero = false, .alignment = 8, .child = *i32, .sentinel = null, }, }); try testing.expect(Slice == []align(8) const *i32); } test "@Type picks up the sentinel value from TypeInfo" { try testTypes(&[_]type{ [11:0]u8, [4:10]u8, [*:0]u8, [*:0]const u8, [*:0]volatile u8, [*:0]const volatile u8, [*:0]align(4) u8, [*:0]align(4) const u8, [*:0]align(4) volatile u8, [*:0]align(4) const volatile u8, [*:0]align(8) u8, [*:0]align(8) const u8, [*:0]align(8) volatile u8, [*:0]align(8) const volatile u8, [*:0]allowzero u8, [*:0]allowzero const u8, [*:0]allowzero volatile u8, [*:0]allowzero const volatile u8, [*:0]allowzero align(4) u8, [*:0]allowzero align(4) const u8, [*:0]allowzero align(4) volatile u8, [*:0]allowzero align(4) const volatile u8, [*:5]allowzero align(4) volatile u8, [*:5]allowzero align(4) const volatile u8, [:0]u8, [:0]const u8, [:0]volatile u8, [:0]const volatile u8, [:0]align(4) u8, [:0]align(4) const u8, [:0]align(4) volatile u8, [:0]align(4) const volatile u8, [:0]align(8) u8, [:0]align(8) const u8, [:0]align(8) volatile u8, [:0]align(8) const volatile u8, [:0]allowzero u8, [:0]allowzero const u8, [:0]allowzero volatile u8, [:0]allowzero const volatile u8, [:0]allowzero align(4) u8, [:0]allowzero align(4) const u8, [:0]allowzero align(4) volatile u8, [:0]allowzero align(4) const volatile u8, [:4]allowzero align(4) volatile u8, [:4]allowzero align(4) const volatile u8, }); } test "Type.Optional" { try testTypes(&[_]type{ ?u8, ?*u8, ?[]u8, ?[*]u8, ?[*c]u8, }); } test "Type.ErrorUnion" { try testTypes(&[_]type{ error{}!void, error{Error}!void, }); } test "Type.Opaque" { const Opaque = @Type(.{ .Opaque = .{ .decls = &[_]TypeInfo.Declaration{}, }, }); try testing.expect(Opaque != opaque {}); try testing.expectEqualSlices( TypeInfo.Declaration, &[_]TypeInfo.Declaration{}, @typeInfo(Opaque).Opaque.decls, ); } test "Type.Vector" { try testTypes(&[_]type{ @Vector(0, u8), @Vector(4, u8), @Vector(8, *u8), std.meta.Vector(0, u8), std.meta.Vector(4, u8), std.meta.Vector(8, *u8), }); } test "Type.AnyFrame" { try testTypes(&[_]type{ anyframe, anyframe->u8, anyframe->anyframe->u8, }); } test "Type.EnumLiteral" { try testTypes(&[_]type{ @TypeOf(.Dummy), }); } fn add(a: i32, b: i32) i32 { return a + b; } test "Type.Frame" { try testTypes(&[_]type{ @Frame(add), }); } test "Type.ErrorSet" { // error sets don't compare equal so just check if they compile _ = @Type(@typeInfo(error{})); _ = @Type(@typeInfo(error{A})); _ = @Type(@typeInfo(error{ A, B, C })); } test "Type.Struct" { const A = @Type(@typeInfo(struct { x: u8, y: u32 })); const infoA = @typeInfo(A).Struct; try testing.expectEqual(TypeInfo.ContainerLayout.Auto, infoA.layout); try testing.expectEqualSlices(u8, "x", infoA.fields[0].name); try testing.expectEqual(u8, infoA.fields[0].field_type); try testing.expectEqual(@as(?u8, null), infoA.fields[0].default_value); try testing.expectEqualSlices(u8, "y", infoA.fields[1].name); try testing.expectEqual(u32, infoA.fields[1].field_type); try testing.expectEqual(@as(?u32, null), infoA.fields[1].default_value); try testing.expectEqualSlices(TypeInfo.Declaration, &[_]TypeInfo.Declaration{}, infoA.decls); try testing.expectEqual(@as(bool, false), infoA.is_tuple); var a = A{ .x = 0, .y = 1 }; try testing.expectEqual(@as(u8, 0), a.x); try testing.expectEqual(@as(u32, 1), a.y); a.y += 1; try testing.expectEqual(@as(u32, 2), a.y); const B = @Type(@typeInfo(extern struct { x: u8, y: u32 = 5 })); const infoB = @typeInfo(B).Struct; try testing.expectEqual(TypeInfo.ContainerLayout.Extern, infoB.layout); try testing.expectEqualSlices(u8, "x", infoB.fields[0].name); try testing.expectEqual(u8, infoB.fields[0].field_type); try testing.expectEqual(@as(?u8, null), infoB.fields[0].default_value); try testing.expectEqualSlices(u8, "y", infoB.fields[1].name); try testing.expectEqual(u32, infoB.fields[1].field_type); try testing.expectEqual(@as(?u32, 5), infoB.fields[1].default_value); try testing.expectEqual(@as(usize, 0), infoB.decls.len); try testing.expectEqual(@as(bool, false), infoB.is_tuple); const C = @Type(@typeInfo(packed struct { x: u8 = 3, y: u32 = 5 })); const infoC = @typeInfo(C).Struct; try testing.expectEqual(TypeInfo.ContainerLayout.Packed, infoC.layout); try testing.expectEqualSlices(u8, "x", infoC.fields[0].name); try testing.expectEqual(u8, infoC.fields[0].field_type); try testing.expectEqual(@as(?u8, 3), infoC.fields[0].default_value); try testing.expectEqualSlices(u8, "y", infoC.fields[1].name); try testing.expectEqual(u32, infoC.fields[1].field_type); try testing.expectEqual(@as(?u32, 5), infoC.fields[1].default_value); try testing.expectEqual(@as(usize, 0), infoC.decls.len); try testing.expectEqual(@as(bool, false), infoC.is_tuple); } test "Type.Enum" { const Foo = @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = u8, .fields = &[_]TypeInfo.EnumField{ .{ .name = "a", .value = 1 }, .{ .name = "b", .value = 5 }, }, .decls = &[_]TypeInfo.Declaration{}, .is_exhaustive = true, }, }); try testing.expectEqual(true, @typeInfo(Foo).Enum.is_exhaustive); try testing.expectEqual(@as(u8, 1), @enumToInt(Foo.a)); try testing.expectEqual(@as(u8, 5), @enumToInt(Foo.b)); const Bar = @Type(.{ .Enum = .{ .layout = .Extern, .tag_type = u32, .fields = &[_]TypeInfo.EnumField{ .{ .name = "a", .value = 1 }, .{ .name = "b", .value = 5 }, }, .decls = &[_]TypeInfo.Declaration{}, .is_exhaustive = false, }, }); try testing.expectEqual(false, @typeInfo(Bar).Enum.is_exhaustive); try testing.expectEqual(@as(u32, 1), @enumToInt(Bar.a)); try testing.expectEqual(@as(u32, 5), @enumToInt(Bar.b)); try testing.expectEqual(@as(u32, 6), @enumToInt(@intToEnum(Bar, 6))); } test "Type.Union" { const Untagged = @Type(.{ .Union = .{ .layout = .Auto, .tag_type = null, .fields = &[_]TypeInfo.UnionField{ .{ .name = "int", .field_type = i32, .alignment = @alignOf(f32) }, .{ .name = "float", .field_type = f32, .alignment = @alignOf(f32) }, }, .decls = &[_]TypeInfo.Declaration{}, }, }); var untagged = Untagged{ .int = 1 }; untagged.float = 2.0; untagged.int = 3; try testing.expectEqual(@as(i32, 3), untagged.int); const PackedUntagged = @Type(.{ .Union = .{ .layout = .Packed, .tag_type = null, .fields = &[_]TypeInfo.UnionField{ .{ .name = "signed", .field_type = i32, .alignment = @alignOf(i32) }, .{ .name = "unsigned", .field_type = u32, .alignment = @alignOf(u32) }, }, .decls = &[_]TypeInfo.Declaration{}, }, }); var packed_untagged = PackedUntagged{ .signed = -1 }; try testing.expectEqual(@as(i32, -1), packed_untagged.signed); try testing.expectEqual(~@as(u32, 0), packed_untagged.unsigned); const Tag = @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = u1, .fields = &[_]TypeInfo.EnumField{ .{ .name = "signed", .value = 0 }, .{ .name = "unsigned", .value = 1 }, }, .decls = &[_]TypeInfo.Declaration{}, .is_exhaustive = true, }, }); const Tagged = @Type(.{ .Union = .{ .layout = .Auto, .tag_type = Tag, .fields = &[_]TypeInfo.UnionField{ .{ .name = "signed", .field_type = i32, .alignment = @alignOf(i32) }, .{ .name = "unsigned", .field_type = u32, .alignment = @alignOf(u32) }, }, .decls = &[_]TypeInfo.Declaration{}, }, }); var tagged = Tagged{ .signed = -1 }; try testing.expectEqual(Tag.signed, tagged); tagged = .{ .unsigned = 1 }; try testing.expectEqual(Tag.unsigned, tagged); } test "Type.Union from Type.Enum" { const Tag = @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = u0, .fields = &[_]TypeInfo.EnumField{ .{ .name = "working_as_expected", .value = 0 }, }, .decls = &[_]TypeInfo.Declaration{}, .is_exhaustive = true, }, }); const T = @Type(.{ .Union = .{ .layout = .Auto, .tag_type = Tag, .fields = &[_]TypeInfo.UnionField{ .{ .name = "working_as_expected", .field_type = u32, .alignment = @alignOf(u32) }, }, .decls = &[_]TypeInfo.Declaration{}, }, }); _ = T; _ = @typeInfo(T).Union; } test "Type.Union from regular enum" { const E = enum { working_as_expected = 0 }; const T = @Type(.{ .Union = .{ .layout = .Auto, .tag_type = E, .fields = &[_]TypeInfo.UnionField{ .{ .name = "working_as_expected", .field_type = u32, .alignment = @alignOf(u32) }, }, .decls = &[_]TypeInfo.Declaration{}, }, }); _ = T; _ = @typeInfo(T).Union; } test "Type.Fn" { // wasm doesn't support align attributes on functions if (builtin.arch == .wasm32 or builtin.arch == .wasm64) return error.SkipZigTest; const foo = struct { fn func(a: usize, b: bool) align(4) callconv(.C) usize { return 0; } }.func; const Foo = @Type(@typeInfo(@TypeOf(foo))); const foo_2: Foo = foo; } test "Type.BoundFn" { // wasm doesn't support align attributes on functions if (builtin.arch == .wasm32 or builtin.arch == .wasm64) return error.SkipZigTest; const TestStruct = packed struct { pub fn foo(self: *const @This()) align(4) callconv(.Unspecified) void {} }; const test_instance: TestStruct = undefined; try testing.expect(std.meta.eql( @typeName(@TypeOf(test_instance.foo)), @typeName(@Type(@typeInfo(@TypeOf(test_instance.foo)))), )); }
test/stage1/behavior/type.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); pub fn parts(alloc: std.mem.Allocator, inp: []const u8) ![2]usize { var i: usize = 0; while (inp[i] != '\n') : (i += 1) {} var init = inp[0..i]; i += 2; var middleFor = [_]u5{0} ** 676; while (i < inp.len) : (i += 8) { middleFor[@as(usize, inp[i] - 'A') * 26 + @as(usize, inp[i + 1] - 'A')] = @intCast(u5, inp[i + 6] - 'A'); } var pc = std.AutoHashMap([2]u5, usize).init(alloc); defer pc.deinit(); i = 0; while (i < init.len - 1) : (i += 1) { var pair = [2]u5{ @intCast(u5, init[i] - 'A'), @intCast(u5, init[i + 1] - 'A') }; try pc.put(pair, (pc.get(pair) orelse 0) + 1); } var npc = std.AutoHashMap([2]u5, usize).init(alloc); defer npc.deinit(); var r = [2]usize{ 0, 0 }; var day: usize = 1; while (day <= 40) : (day += 1) { var pit = pc.iterator(); while (pit.next()) |e| { var a = e.key_ptr.*[0]; var b = e.key_ptr.*[1]; var m = middleFor[@as(usize, a) * 26 + b]; try npc.put([2]u5{ a, m }, (npc.get([2]u5{ a, m }) orelse 0) + e.value_ptr.*); try npc.put([2]u5{ m, b }, (npc.get([2]u5{ m, b }) orelse 0) + e.value_ptr.*); } std.mem.swap(std.AutoHashMap([2]u5, usize), &pc, &npc); npc.clearRetainingCapacity(); if (day == 10) { r[0] = mostMinusLeast(pc, init); } } r[1] = mostMinusLeast(pc, init); return r; } fn mostMinusLeast(pairCounts: std.AutoHashMap([2]u5, usize), init: []const u8) usize { var c: [26]usize = [_]usize{0} ** 26; c[init[init.len - 1] - 'A'] += 1; var it = pairCounts.iterator(); while (it.next()) |e| { c[e.key_ptr.*[0]] += e.value_ptr.*; } var min: usize = std.math.maxInt(usize); var max: usize = 0; for (c) |v| { if (v != 0 and min > v) { min = v; } if (max < v) { max = v; } } return max - min; } test "parts" { var t1 = try parts(aoc.talloc, aoc.test1file); try aoc.assertEq(@as(usize, 1588), t1[0]); var r = try parts(aoc.talloc, aoc.inputfile); try aoc.assertEq(@as(usize, 2891), r[0]); try aoc.assertEq(@as(usize, 2188189693529), t1[1]); try aoc.assertEq(@as(usize, 4607749009683), r[1]); } fn day14(inp: []const u8, bench: bool) anyerror!void { var p = try parts(aoc.halloc, inp); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day14); }
2021/14/aoc.zig
const std = @import("../index.zig"); const math = std.math; const mem = std.mem; const io = std.io; const os = std.os; const elf = std.elf; const DW = std.dwarf; const macho = std.macho; const ArrayList = std.ArrayList; const builtin = @import("builtin"); pub const FailingAllocator = @import("failing_allocator.zig").FailingAllocator; pub const failing_allocator = FailingAllocator.init(global_allocator, 0); pub const runtime_safety = switch (builtin.mode) { builtin.Mode.Debug, builtin.Mode.ReleaseSafe => true, builtin.Mode.ReleaseFast, builtin.Mode.ReleaseSmall => false, }; /// Tries to write to stderr, unbuffered, and ignores any error returned. /// Does not append a newline. /// TODO atomic/multithread support var stderr_file: os.File = undefined; var stderr_file_out_stream: io.FileOutStream = undefined; var stderr_stream: ?*io.OutStream(io.FileOutStream.Error) = null; var stderr_mutex = std.Mutex.init(); pub fn warn(comptime fmt: []const u8, args: ...) void { const held = stderr_mutex.acquire(); defer held.release(); const stderr = getStderrStream() catch return; stderr.print(fmt, args) catch return; } pub fn getStderrStream() !*io.OutStream(io.FileOutStream.Error) { if (stderr_stream) |st| { return st; } else { stderr_file = try io.getStdErr(); stderr_file_out_stream = io.FileOutStream.init(&stderr_file); const st = &stderr_file_out_stream.stream; stderr_stream = st; return st; } } var self_debug_info: ?*ElfStackTrace = null; pub fn getSelfDebugInfo() !*ElfStackTrace { if (self_debug_info) |info| { return info; } else { const info = try openSelfDebugInfo(getDebugInfoAllocator()); self_debug_info = info; return info; } } fn wantTtyColor() bool { var bytes: [128]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(bytes[0..]).allocator; return if (std.os.getEnvVarOwned(allocator, "ZIG_DEBUG_COLOR")) |_| true else |_| stderr_file.isTty(); } /// Tries to print the current stack trace to stderr, unbuffered, and ignores any error returned. pub fn dumpCurrentStackTrace(start_addr: ?usize) void { const stderr = getStderrStream() catch return; const debug_info = getSelfDebugInfo() catch |err| { stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return; return; }; writeCurrentStackTrace(stderr, getDebugInfoAllocator(), debug_info, wantTtyColor(), start_addr) catch |err| { stderr.print("Unable to dump stack trace: {}\n", @errorName(err)) catch return; return; }; } /// Tries to print a stack trace to stderr, unbuffered, and ignores any error returned. pub fn dumpStackTrace(stack_trace: *const builtin.StackTrace) void { const stderr = getStderrStream() catch return; const debug_info = getSelfDebugInfo() catch |err| { stderr.print("Unable to dump stack trace: Unable to open debug info: {}\n", @errorName(err)) catch return; return; }; writeStackTrace(stack_trace, stderr, getDebugInfoAllocator(), debug_info, wantTtyColor()) catch |err| { stderr.print("Unable to dump stack trace: {}\n", @errorName(err)) catch return; return; }; } /// This function invokes undefined behavior when `ok` is `false`. /// In Debug and ReleaseSafe modes, calls to this function are always /// generated, and the `unreachable` statement triggers a panic. /// In ReleaseFast and ReleaseSmall modes, calls to this function can be /// optimized away. pub fn assert(ok: bool) void { if (!ok) { // In ReleaseFast test mode, we still want assert(false) to crash, so // we insert an explicit call to @panic instead of unreachable. // TODO we should use `assertOrPanic` in tests and remove this logic. if (builtin.is_test) { @panic("assertion failure"); } else { unreachable; // assertion failure } } } /// TODO: add `==` operator for `error_union == error_set`, and then /// remove this function pub fn assertError(value: var, expected_error: error) void { if (value) { @panic("expected error"); } else |actual_error| { assert(actual_error == expected_error); } } /// Call this function when you want to panic if the condition is not true. /// If `ok` is `false`, this function will panic in every release mode. pub fn assertOrPanic(ok: bool) void { if (!ok) { @panic("assertion failure"); } } pub fn panic(comptime format: []const u8, args: ...) noreturn { @setCold(true); const first_trace_addr = @ptrToInt(@returnAddress()); panicExtra(null, first_trace_addr, format, args); } var panicking: u8 = 0; // TODO make this a bool pub fn panicExtra(trace: ?*const builtin.StackTrace, first_trace_addr: ?usize, comptime format: []const u8, args: ...) noreturn { @setCold(true); if (@atomicRmw(u8, &panicking, builtin.AtomicRmwOp.Xchg, 1, builtin.AtomicOrder.SeqCst) == 1) { // Panicked during a panic. // TODO detect if a different thread caused the panic, because in that case // we would want to return here instead of calling abort, so that the thread // which first called panic can finish printing a stack trace. os.abort(); } const stderr = getStderrStream() catch os.abort(); stderr.print(format ++ "\n", args) catch os.abort(); if (trace) |t| { dumpStackTrace(t); } dumpCurrentStackTrace(first_trace_addr); os.abort(); } const GREEN = "\x1b[32;1m"; const WHITE = "\x1b[37;1m"; const DIM = "\x1b[2m"; const RESET = "\x1b[0m"; pub fn writeStackTrace(stack_trace: *const builtin.StackTrace, out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool) !void { var frame_index: usize = undefined; var frames_left: usize = undefined; if (stack_trace.index < stack_trace.instruction_addresses.len) { frame_index = 0; frames_left = stack_trace.index; } else { frame_index = (stack_trace.index + 1) % stack_trace.instruction_addresses.len; frames_left = stack_trace.instruction_addresses.len; } while (frames_left != 0) : ({ frames_left -= 1; frame_index = (frame_index + 1) % stack_trace.instruction_addresses.len; }) { const return_address = stack_trace.instruction_addresses[frame_index]; try printSourceAtAddress(debug_info, out_stream, return_address, tty_color); } } pub inline fn getReturnAddress(frame_count: usize) usize { var fp = @ptrToInt(@frameAddress()); var i: usize = 0; while (fp != 0 and i < frame_count) { fp = @intToPtr(*const usize, fp).*; i += 1; } return @intToPtr(*const usize, fp + @sizeOf(usize)).*; } pub fn writeCurrentStackTrace(out_stream: var, allocator: *mem.Allocator, debug_info: *ElfStackTrace, tty_color: bool, start_addr: ?usize) !void { const AddressState = union(enum) { NotLookingForStartAddress, LookingForStartAddress: usize, }; // TODO: I want to express like this: //var addr_state = if (start_addr) |addr| AddressState { .LookingForStartAddress = addr } // else AddressState.NotLookingForStartAddress; var addr_state: AddressState = undefined; if (start_addr) |addr| { addr_state = AddressState{ .LookingForStartAddress = addr }; } else { addr_state = AddressState.NotLookingForStartAddress; } var fp = @ptrToInt(@frameAddress()); while (fp != 0) : (fp = @intToPtr(*const usize, fp).*) { const return_address = @intToPtr(*const usize, fp + @sizeOf(usize)).*; switch (addr_state) { AddressState.NotLookingForStartAddress => {}, AddressState.LookingForStartAddress => |addr| { if (return_address == addr) { addr_state = AddressState.NotLookingForStartAddress; } else { continue; } }, } try printSourceAtAddress(debug_info, out_stream, return_address, tty_color); } } pub fn printSourceAtAddress(debug_info: *ElfStackTrace, out_stream: var, address: usize, tty_color: bool) !void { switch (builtin.os) { builtin.Os.windows => return error.UnsupportedDebugInfo, builtin.Os.macosx => { // TODO(bnoordhuis) It's theoretically possible to obtain the // compilation unit from the symbtab but it's not that useful // in practice because the compiler dumps everything in a single // object file. Future improvement: use external dSYM data when // available. const unknown = macho.Symbol{ .name = "???", .address = address, }; const symbol = debug_info.symbol_table.search(address) orelse &unknown; try out_stream.print(WHITE ++ "{}" ++ RESET ++ ": " ++ DIM ++ "0x{x}" ++ " in ??? (???)" ++ RESET ++ "\n", symbol.name, address); }, else => { const compile_unit = findCompileUnit(debug_info, address) catch { if (tty_color) { try out_stream.print("???:?:?: " ++ DIM ++ "0x{x} in ??? (???)" ++ RESET ++ "\n ???\n\n", address); } else { try out_stream.print("???:?:?: 0x{x} in ??? (???)\n ???\n\n", address); } return; }; const compile_unit_name = try compile_unit.die.getAttrString(debug_info, DW.AT_name); if (getLineNumberInfo(debug_info, compile_unit, address - 1)) |line_info| { defer line_info.deinit(); if (tty_color) { try out_stream.print( WHITE ++ "{}:{}:{}" ++ RESET ++ ": " ++ DIM ++ "0x{x} in ??? ({})" ++ RESET ++ "\n", line_info.file_name, line_info.line, line_info.column, address, compile_unit_name, ); if (printLineFromFile(debug_info.allocator(), out_stream, line_info)) { if (line_info.column == 0) { try out_stream.write("\n"); } else { { var col_i: usize = 1; while (col_i < line_info.column) : (col_i += 1) { try out_stream.writeByte(' '); } } try out_stream.write(GREEN ++ "^" ++ RESET ++ "\n"); } } else |err| switch (err) { error.EndOfFile => {}, else => return err, } } else { try out_stream.print( "{}:{}:{}: 0x{x} in ??? ({})\n", line_info.file_name, line_info.line, line_info.column, address, compile_unit_name, ); } } else |err| switch (err) { error.MissingDebugInfo, error.InvalidDebugInfo => { try out_stream.print("0x{x} in ??? ({})\n", address, compile_unit_name); }, else => return err, } }, } } pub fn openSelfDebugInfo(allocator: *mem.Allocator) !*ElfStackTrace { switch (builtin.object_format) { builtin.ObjectFormat.elf => { const st = try allocator.create(ElfStackTrace{ .self_exe_file = undefined, .elf = undefined, .debug_info = undefined, .debug_abbrev = undefined, .debug_str = undefined, .debug_line = undefined, .debug_ranges = null, .abbrev_table_list = ArrayList(AbbrevTableHeader).init(allocator), .compile_unit_list = ArrayList(CompileUnit).init(allocator), }); errdefer allocator.destroy(st); st.self_exe_file = try os.openSelfExe(); errdefer st.self_exe_file.close(); try st.elf.openFile(allocator, &st.self_exe_file); errdefer st.elf.close(); st.debug_info = (try st.elf.findSection(".debug_info")) orelse return error.MissingDebugInfo; st.debug_abbrev = (try st.elf.findSection(".debug_abbrev")) orelse return error.MissingDebugInfo; st.debug_str = (try st.elf.findSection(".debug_str")) orelse return error.MissingDebugInfo; st.debug_line = (try st.elf.findSection(".debug_line")) orelse return error.MissingDebugInfo; st.debug_ranges = (try st.elf.findSection(".debug_ranges")); try scanAllCompileUnits(st); return st; }, builtin.ObjectFormat.macho => { var exe_file = try os.openSelfExe(); defer exe_file.close(); const st = try allocator.create(ElfStackTrace{ .symbol_table = try macho.loadSymbols(allocator, &io.FileInStream.init(&exe_file)) }); errdefer allocator.destroy(st); return st; }, builtin.ObjectFormat.coff => { return error.TodoSupportCoffDebugInfo; }, builtin.ObjectFormat.wasm => { return error.TodoSupportCOFFDebugInfo; }, builtin.ObjectFormat.unknown => { return error.UnknownObjectFormat; }, } } fn printLineFromFile(allocator: *mem.Allocator, out_stream: var, line_info: *const LineInfo) !void { var f = try os.File.openRead(allocator, line_info.file_name); defer f.close(); // TODO fstat and make sure that the file has the correct size var buf: [os.page_size]u8 = undefined; var line: usize = 1; var column: usize = 1; var abs_index: usize = 0; while (true) { const amt_read = try f.read(buf[0..]); const slice = buf[0..amt_read]; for (slice) |byte| { if (line == line_info.line) { try out_stream.writeByte(byte); if (byte == '\n') { return; } } if (byte == '\n') { line += 1; column = 1; } else { column += 1; } } if (amt_read < buf.len) return error.EndOfFile; } } pub const ElfStackTrace = switch (builtin.os) { builtin.Os.macosx => struct { symbol_table: macho.SymbolTable, pub fn close(self: *ElfStackTrace) void { self.symbol_table.deinit(); } }, else => struct { self_exe_file: os.File, elf: elf.Elf, debug_info: *elf.SectionHeader, debug_abbrev: *elf.SectionHeader, debug_str: *elf.SectionHeader, debug_line: *elf.SectionHeader, debug_ranges: ?*elf.SectionHeader, abbrev_table_list: ArrayList(AbbrevTableHeader), compile_unit_list: ArrayList(CompileUnit), pub fn allocator(self: *const ElfStackTrace) *mem.Allocator { return self.abbrev_table_list.allocator; } pub fn readString(self: *ElfStackTrace) ![]u8 { var in_file_stream = io.FileInStream.init(&self.self_exe_file); const in_stream = &in_file_stream.stream; return readStringRaw(self.allocator(), in_stream); } pub fn close(self: *ElfStackTrace) void { self.self_exe_file.close(); self.elf.close(); } }, }; const PcRange = struct { start: u64, end: u64, }; const CompileUnit = struct { version: u16, is_64: bool, die: *Die, index: usize, pc_range: ?PcRange, }; const AbbrevTable = ArrayList(AbbrevTableEntry); const AbbrevTableHeader = struct { // offset from .debug_abbrev offset: u64, table: AbbrevTable, }; const AbbrevTableEntry = struct { has_children: bool, abbrev_code: u64, tag_id: u64, attrs: ArrayList(AbbrevAttr), }; const AbbrevAttr = struct { attr_id: u64, form_id: u64, }; const FormValue = union(enum) { Address: u64, Block: []u8, Const: Constant, ExprLoc: []u8, Flag: bool, SecOffset: u64, Ref: []u8, RefAddr: u64, RefSig8: u64, String: []u8, StrPtr: u64, }; const Constant = struct { payload: []u8, signed: bool, fn asUnsignedLe(self: *const Constant) !u64 { if (self.payload.len > @sizeOf(u64)) return error.InvalidDebugInfo; if (self.signed) return error.InvalidDebugInfo; return mem.readInt(self.payload, u64, builtin.Endian.Little); } }; const Die = struct { tag_id: u64, has_children: bool, attrs: ArrayList(Attr), const Attr = struct { id: u64, value: FormValue, }; fn getAttr(self: *const Die, id: u64) ?*const FormValue { for (self.attrs.toSliceConst()) |*attr| { if (attr.id == id) return &attr.value; } return null; } fn getAttrAddr(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Address => |value| value, else => error.InvalidDebugInfo, }; } fn getAttrSecOffset(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), FormValue.SecOffset => |value| value, else => error.InvalidDebugInfo, }; } fn getAttrUnsignedLe(self: *const Die, id: u64) !u64 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.Const => |value| value.asUnsignedLe(), else => error.InvalidDebugInfo, }; } fn getAttrString(self: *const Die, st: *ElfStackTrace, id: u64) ![]u8 { const form_value = self.getAttr(id) orelse return error.MissingDebugInfo; return switch (form_value.*) { FormValue.String => |value| value, FormValue.StrPtr => |offset| getString(st, offset), else => error.InvalidDebugInfo, }; } }; const FileEntry = struct { file_name: []const u8, dir_index: usize, mtime: usize, len_bytes: usize, }; const LineInfo = struct { line: usize, column: usize, file_name: []u8, allocator: *mem.Allocator, fn deinit(self: *const LineInfo) void { self.allocator.free(self.file_name); } }; const LineNumberProgram = struct { address: usize, file: usize, line: isize, column: usize, is_stmt: bool, basic_block: bool, end_sequence: bool, target_address: usize, include_dirs: []const []const u8, file_entries: *ArrayList(FileEntry), prev_address: usize, prev_file: usize, prev_line: isize, prev_column: usize, prev_is_stmt: bool, prev_basic_block: bool, prev_end_sequence: bool, pub fn init(is_stmt: bool, include_dirs: []const []const u8, file_entries: *ArrayList(FileEntry), target_address: usize) LineNumberProgram { return LineNumberProgram{ .address = 0, .file = 1, .line = 1, .column = 0, .is_stmt = is_stmt, .basic_block = false, .end_sequence = false, .include_dirs = include_dirs, .file_entries = file_entries, .target_address = target_address, .prev_address = 0, .prev_file = undefined, .prev_line = undefined, .prev_column = undefined, .prev_is_stmt = undefined, .prev_basic_block = undefined, .prev_end_sequence = undefined, }; } pub fn checkLineMatch(self: *LineNumberProgram) !?LineInfo { if (self.target_address >= self.prev_address and self.target_address < self.address) { const file_entry = if (self.prev_file == 0) { return error.MissingDebugInfo; } else if (self.prev_file - 1 >= self.file_entries.len) { return error.InvalidDebugInfo; } else &self.file_entries.items[self.prev_file - 1]; const dir_name = if (file_entry.dir_index >= self.include_dirs.len) { return error.InvalidDebugInfo; } else self.include_dirs[file_entry.dir_index]; const file_name = try os.path.join(self.file_entries.allocator, dir_name, file_entry.file_name); errdefer self.file_entries.allocator.free(file_name); return LineInfo{ .line = if (self.prev_line >= 0) @intCast(usize, self.prev_line) else 0, .column = self.prev_column, .file_name = file_name, .allocator = self.file_entries.allocator, }; } self.prev_address = self.address; self.prev_file = self.file; self.prev_line = self.line; self.prev_column = self.column; self.prev_is_stmt = self.is_stmt; self.prev_basic_block = self.basic_block; self.prev_end_sequence = self.end_sequence; return null; } }; fn readStringRaw(allocator: *mem.Allocator, in_stream: var) ![]u8 { var buf = ArrayList(u8).init(allocator); while (true) { const byte = try in_stream.readByte(); if (byte == 0) break; try buf.append(byte); } return buf.toSlice(); } fn getString(st: *ElfStackTrace, offset: u64) ![]u8 { const pos = st.debug_str.offset + offset; try st.self_exe_file.seekTo(pos); return st.readString(); } fn readAllocBytes(allocator: *mem.Allocator, in_stream: var, size: usize) ![]u8 { const buf = try allocator.alloc(u8, size); errdefer allocator.free(buf); if ((try in_stream.read(buf)) < size) return error.EndOfFile; return buf; } fn parseFormValueBlockLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .Block = buf }; } fn parseFormValueBlock(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const block_len = try in_stream.readVarInt(builtin.Endian.Little, usize, size); return parseFormValueBlockLen(allocator, in_stream, block_len); } fn parseFormValueConstant(allocator: *mem.Allocator, in_stream: var, signed: bool, size: usize) !FormValue { return FormValue{ .Const = Constant{ .signed = signed, .payload = try readAllocBytes(allocator, in_stream, size), }, }; } fn parseFormValueDwarfOffsetSize(in_stream: var, is_64: bool) !u64 { return if (is_64) try in_stream.readIntLe(u64) else u64(try in_stream.readIntLe(u32)); } fn parseFormValueTargetAddrSize(in_stream: var) !u64 { return if (@sizeOf(usize) == 4) u64(try in_stream.readIntLe(u32)) else if (@sizeOf(usize) == 8) try in_stream.readIntLe(u64) else unreachable; } fn parseFormValueRefLen(allocator: *mem.Allocator, in_stream: var, size: usize) !FormValue { const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .Ref = buf }; } fn parseFormValueRef(allocator: *mem.Allocator, in_stream: var, comptime T: type) !FormValue { const block_len = try in_stream.readIntLe(T); return parseFormValueRefLen(allocator, in_stream, block_len); } const ParseFormValueError = error{ EndOfStream, InvalidDebugInfo, EndOfFile, OutOfMemory, } || std.os.File.ReadError; fn parseFormValue(allocator: *mem.Allocator, in_stream: var, form_id: u64, is_64: bool) ParseFormValueError!FormValue { return switch (form_id) { DW.FORM_addr => FormValue{ .Address = try parseFormValueTargetAddrSize(in_stream) }, DW.FORM_block1 => parseFormValueBlock(allocator, in_stream, 1), DW.FORM_block2 => parseFormValueBlock(allocator, in_stream, 2), DW.FORM_block4 => parseFormValueBlock(allocator, in_stream, 4), DW.FORM_block => x: { const block_len = try readULeb128(in_stream); return parseFormValueBlockLen(allocator, in_stream, block_len); }, DW.FORM_data1 => parseFormValueConstant(allocator, in_stream, false, 1), DW.FORM_data2 => parseFormValueConstant(allocator, in_stream, false, 2), DW.FORM_data4 => parseFormValueConstant(allocator, in_stream, false, 4), DW.FORM_data8 => parseFormValueConstant(allocator, in_stream, false, 8), DW.FORM_udata, DW.FORM_sdata => { const block_len = try readULeb128(in_stream); const signed = form_id == DW.FORM_sdata; return parseFormValueConstant(allocator, in_stream, signed, block_len); }, DW.FORM_exprloc => { const size = try readULeb128(in_stream); const buf = try readAllocBytes(allocator, in_stream, size); return FormValue{ .ExprLoc = buf }; }, DW.FORM_flag => FormValue{ .Flag = (try in_stream.readByte()) != 0 }, DW.FORM_flag_present => FormValue{ .Flag = true }, DW.FORM_sec_offset => FormValue{ .SecOffset = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_ref1 => parseFormValueRef(allocator, in_stream, u8), DW.FORM_ref2 => parseFormValueRef(allocator, in_stream, u16), DW.FORM_ref4 => parseFormValueRef(allocator, in_stream, u32), DW.FORM_ref8 => parseFormValueRef(allocator, in_stream, u64), DW.FORM_ref_udata => { const ref_len = try readULeb128(in_stream); return parseFormValueRefLen(allocator, in_stream, ref_len); }, DW.FORM_ref_addr => FormValue{ .RefAddr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_ref_sig8 => FormValue{ .RefSig8 = try in_stream.readIntLe(u64) }, DW.FORM_string => FormValue{ .String = try readStringRaw(allocator, in_stream) }, DW.FORM_strp => FormValue{ .StrPtr = try parseFormValueDwarfOffsetSize(in_stream, is_64) }, DW.FORM_indirect => { const child_form_id = try readULeb128(in_stream); return parseFormValue(allocator, in_stream, child_form_id, is_64); }, else => error.InvalidDebugInfo, }; } fn parseAbbrevTable(st: *ElfStackTrace) !AbbrevTable { const in_file = &st.self_exe_file; var in_file_stream = io.FileInStream.init(in_file); const in_stream = &in_file_stream.stream; var result = AbbrevTable.init(st.allocator()); while (true) { const abbrev_code = try readULeb128(in_stream); if (abbrev_code == 0) return result; try result.append(AbbrevTableEntry{ .abbrev_code = abbrev_code, .tag_id = try readULeb128(in_stream), .has_children = (try in_stream.readByte()) == DW.CHILDREN_yes, .attrs = ArrayList(AbbrevAttr).init(st.allocator()), }); const attrs = &result.items[result.len - 1].attrs; while (true) { const attr_id = try readULeb128(in_stream); const form_id = try readULeb128(in_stream); if (attr_id == 0 and form_id == 0) break; try attrs.append(AbbrevAttr{ .attr_id = attr_id, .form_id = form_id, }); } } } /// Gets an already existing AbbrevTable given the abbrev_offset, or if not found, /// seeks in the stream and parses it. fn getAbbrevTable(st: *ElfStackTrace, abbrev_offset: u64) !*const AbbrevTable { for (st.abbrev_table_list.toSlice()) |*header| { if (header.offset == abbrev_offset) { return &header.table; } } try st.self_exe_file.seekTo(st.debug_abbrev.offset + abbrev_offset); try st.abbrev_table_list.append(AbbrevTableHeader{ .offset = abbrev_offset, .table = try parseAbbrevTable(st), }); return &st.abbrev_table_list.items[st.abbrev_table_list.len - 1].table; } fn getAbbrevTableEntry(abbrev_table: *const AbbrevTable, abbrev_code: u64) ?*const AbbrevTableEntry { for (abbrev_table.toSliceConst()) |*table_entry| { if (table_entry.abbrev_code == abbrev_code) return table_entry; } return null; } fn parseDie(st: *ElfStackTrace, abbrev_table: *const AbbrevTable, is_64: bool) !Die { const in_file = &st.self_exe_file; var in_file_stream = io.FileInStream.init(in_file); const in_stream = &in_file_stream.stream; const abbrev_code = try readULeb128(in_stream); const table_entry = getAbbrevTableEntry(abbrev_table, abbrev_code) orelse return error.InvalidDebugInfo; var result = Die{ .tag_id = table_entry.tag_id, .has_children = table_entry.has_children, .attrs = ArrayList(Die.Attr).init(st.allocator()), }; try result.attrs.resize(table_entry.attrs.len); for (table_entry.attrs.toSliceConst()) |attr, i| { result.attrs.items[i] = Die.Attr{ .id = attr.attr_id, .value = try parseFormValue(st.allocator(), in_stream, attr.form_id, is_64), }; } return result; } fn getLineNumberInfo(st: *ElfStackTrace, compile_unit: *const CompileUnit, target_address: usize) !LineInfo { const compile_unit_cwd = try compile_unit.die.getAttrString(st, DW.AT_comp_dir); const in_file = &st.self_exe_file; const debug_line_end = st.debug_line.offset + st.debug_line.size; var this_offset = st.debug_line.offset; var this_index: usize = 0; var in_file_stream = io.FileInStream.init(in_file); const in_stream = &in_file_stream.stream; while (this_offset < debug_line_end) : (this_index += 1) { try in_file.seekTo(this_offset); var is_64: bool = undefined; const unit_length = try readInitialLength(@typeOf(in_stream.readFn).ReturnType.ErrorSet, in_stream, &is_64); if (unit_length == 0) return error.MissingDebugInfo; const next_offset = unit_length + (if (is_64) usize(12) else usize(4)); if (compile_unit.index != this_index) { this_offset += next_offset; continue; } const version = try in_stream.readInt(st.elf.endian, u16); // TODO support 3 and 5 if (version != 2 and version != 4) return error.InvalidDebugInfo; const prologue_length = if (is_64) try in_stream.readInt(st.elf.endian, u64) else try in_stream.readInt(st.elf.endian, u32); const prog_start_offset = (try in_file.getPos()) + prologue_length; const minimum_instruction_length = try in_stream.readByte(); if (minimum_instruction_length == 0) return error.InvalidDebugInfo; if (version >= 4) { // maximum_operations_per_instruction _ = try in_stream.readByte(); } const default_is_stmt = (try in_stream.readByte()) != 0; const line_base = try in_stream.readByteSigned(); const line_range = try in_stream.readByte(); if (line_range == 0) return error.InvalidDebugInfo; const opcode_base = try in_stream.readByte(); const standard_opcode_lengths = try st.allocator().alloc(u8, opcode_base - 1); { var i: usize = 0; while (i < opcode_base - 1) : (i += 1) { standard_opcode_lengths[i] = try in_stream.readByte(); } } var include_directories = ArrayList([]u8).init(st.allocator()); try include_directories.append(compile_unit_cwd); while (true) { const dir = try st.readString(); if (dir.len == 0) break; try include_directories.append(dir); } var file_entries = ArrayList(FileEntry).init(st.allocator()); var prog = LineNumberProgram.init(default_is_stmt, include_directories.toSliceConst(), &file_entries, target_address); while (true) { const file_name = try st.readString(); if (file_name.len == 0) break; const dir_index = try readULeb128(in_stream); const mtime = try readULeb128(in_stream); const len_bytes = try readULeb128(in_stream); try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, .len_bytes = len_bytes, }); } try in_file.seekTo(prog_start_offset); while (true) { const opcode = try in_stream.readByte(); var sub_op: u8 = undefined; // TODO move this to the correct scope and fix the compiler crash if (opcode == DW.LNS_extended_op) { const op_size = try readULeb128(in_stream); if (op_size < 1) return error.InvalidDebugInfo; sub_op = try in_stream.readByte(); switch (sub_op) { DW.LNE_end_sequence => { prog.end_sequence = true; if (try prog.checkLineMatch()) |info| return info; return error.MissingDebugInfo; }, DW.LNE_set_address => { const addr = try in_stream.readInt(st.elf.endian, usize); prog.address = addr; }, DW.LNE_define_file => { const file_name = try st.readString(); const dir_index = try readULeb128(in_stream); const mtime = try readULeb128(in_stream); const len_bytes = try readULeb128(in_stream); try file_entries.append(FileEntry{ .file_name = file_name, .dir_index = dir_index, .mtime = mtime, .len_bytes = len_bytes, }); }, else => { const fwd_amt = math.cast(isize, op_size - 1) catch return error.InvalidDebugInfo; try in_file.seekForward(fwd_amt); }, } } else if (opcode >= opcode_base) { // special opcodes const adjusted_opcode = opcode - opcode_base; const inc_addr = minimum_instruction_length * (adjusted_opcode / line_range); const inc_line = i32(line_base) + i32(adjusted_opcode % line_range); prog.line += inc_line; prog.address += inc_addr; if (try prog.checkLineMatch()) |info| return info; prog.basic_block = false; } else { switch (opcode) { DW.LNS_copy => { if (try prog.checkLineMatch()) |info| return info; prog.basic_block = false; }, DW.LNS_advance_pc => { const arg = try readULeb128(in_stream); prog.address += arg * minimum_instruction_length; }, DW.LNS_advance_line => { const arg = try readILeb128(in_stream); prog.line += arg; }, DW.LNS_set_file => { const arg = try readULeb128(in_stream); prog.file = arg; }, DW.LNS_set_column => { const arg = try readULeb128(in_stream); prog.column = arg; }, DW.LNS_negate_stmt => { prog.is_stmt = !prog.is_stmt; }, DW.LNS_set_basic_block => { prog.basic_block = true; }, DW.LNS_const_add_pc => { const inc_addr = minimum_instruction_length * ((255 - opcode_base) / line_range); prog.address += inc_addr; }, DW.LNS_fixed_advance_pc => { const arg = try in_stream.readInt(st.elf.endian, u16); prog.address += arg; }, DW.LNS_set_prologue_end => {}, else => { if (opcode - 1 >= standard_opcode_lengths.len) return error.InvalidDebugInfo; const len_bytes = standard_opcode_lengths[opcode - 1]; try in_file.seekForward(len_bytes); }, } } } this_offset += next_offset; } return error.MissingDebugInfo; } fn scanAllCompileUnits(st: *ElfStackTrace) !void { const debug_info_end = st.debug_info.offset + st.debug_info.size; var this_unit_offset = st.debug_info.offset; var cu_index: usize = 0; var in_file_stream = io.FileInStream.init(&st.self_exe_file); const in_stream = &in_file_stream.stream; while (this_unit_offset < debug_info_end) { try st.self_exe_file.seekTo(this_unit_offset); var is_64: bool = undefined; const unit_length = try readInitialLength(@typeOf(in_stream.readFn).ReturnType.ErrorSet, in_stream, &is_64); if (unit_length == 0) return; const next_offset = unit_length + (if (is_64) usize(12) else usize(4)); const version = try in_stream.readInt(st.elf.endian, u16); if (version < 2 or version > 5) return error.InvalidDebugInfo; const debug_abbrev_offset = if (is_64) try in_stream.readInt(st.elf.endian, u64) else try in_stream.readInt(st.elf.endian, u32); const address_size = try in_stream.readByte(); if (address_size != @sizeOf(usize)) return error.InvalidDebugInfo; const compile_unit_pos = try st.self_exe_file.getPos(); const abbrev_table = try getAbbrevTable(st, debug_abbrev_offset); try st.self_exe_file.seekTo(compile_unit_pos); const compile_unit_die = try st.allocator().create(try parseDie(st, abbrev_table, is_64)); if (compile_unit_die.tag_id != DW.TAG_compile_unit) return error.InvalidDebugInfo; const pc_range = x: { if (compile_unit_die.getAttrAddr(DW.AT_low_pc)) |low_pc| { if (compile_unit_die.getAttr(DW.AT_high_pc)) |high_pc_value| { const pc_end = switch (high_pc_value.*) { FormValue.Address => |value| value, FormValue.Const => |value| b: { const offset = try value.asUnsignedLe(); break :b (low_pc + offset); }, else => return error.InvalidDebugInfo, }; break :x PcRange{ .start = low_pc, .end = pc_end, }; } else { break :x null; } } else |err| { if (err != error.MissingDebugInfo) return err; break :x null; } }; try st.compile_unit_list.append(CompileUnit{ .version = version, .is_64 = is_64, .pc_range = pc_range, .die = compile_unit_die, .index = cu_index, }); this_unit_offset += next_offset; cu_index += 1; } } fn findCompileUnit(st: *ElfStackTrace, target_address: u64) !*const CompileUnit { var in_file_stream = io.FileInStream.init(&st.self_exe_file); const in_stream = &in_file_stream.stream; for (st.compile_unit_list.toSlice()) |*compile_unit| { if (compile_unit.pc_range) |range| { if (target_address >= range.start and target_address < range.end) return compile_unit; } if (compile_unit.die.getAttrSecOffset(DW.AT_ranges)) |ranges_offset| { var base_address: usize = 0; if (st.debug_ranges) |debug_ranges| { try st.self_exe_file.seekTo(debug_ranges.offset + ranges_offset); while (true) { const begin_addr = try in_stream.readIntLe(usize); const end_addr = try in_stream.readIntLe(usize); if (begin_addr == 0 and end_addr == 0) { break; } if (begin_addr == @maxValue(usize)) { base_address = begin_addr; continue; } if (target_address >= begin_addr and target_address < end_addr) { return compile_unit; } } } } else |err| { if (err != error.MissingDebugInfo) return err; continue; } } return error.MissingDebugInfo; } fn readInitialLength(comptime E: type, in_stream: *io.InStream(E), is_64: *bool) !u64 { const first_32_bits = try in_stream.readIntLe(u32); is_64.* = (first_32_bits == 0xffffffff); if (is_64.*) { return in_stream.readIntLe(u64); } else { if (first_32_bits >= 0xfffffff0) return error.InvalidDebugInfo; return u64(first_32_bits); } } fn readULeb128(in_stream: var) !u64 { var result: u64 = 0; var shift: usize = 0; while (true) { const byte = try in_stream.readByte(); var operand: u64 = undefined; if (@shlWithOverflow(u64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo; result |= operand; if ((byte & 0b10000000) == 0) return result; shift += 7; } } fn readILeb128(in_stream: var) !i64 { var result: i64 = 0; var shift: usize = 0; while (true) { const byte = try in_stream.readByte(); var operand: i64 = undefined; if (@shlWithOverflow(i64, byte & 0b01111111, @intCast(u6, shift), &operand)) return error.InvalidDebugInfo; result |= operand; shift += 7; if ((byte & 0b10000000) == 0) { if (shift < @sizeOf(i64) * 8 and (byte & 0b01000000) != 0) result |= -(i64(1) << @intCast(u6, shift)); return result; } } } /// This should only be used in temporary test programs. pub const global_allocator = &global_fixed_allocator.allocator; var global_fixed_allocator = std.heap.ThreadSafeFixedBufferAllocator.init(global_allocator_mem[0..]); var global_allocator_mem: [100 * 1024]u8 = undefined; // TODO make thread safe var debug_info_allocator: ?*mem.Allocator = null; var debug_info_direct_allocator: std.heap.DirectAllocator = undefined; var debug_info_arena_allocator: std.heap.ArenaAllocator = undefined; fn getDebugInfoAllocator() *mem.Allocator { if (debug_info_allocator) |a| return a; debug_info_direct_allocator = std.heap.DirectAllocator.init(); debug_info_arena_allocator = std.heap.ArenaAllocator.init(&debug_info_direct_allocator.allocator); debug_info_allocator = &debug_info_arena_allocator.allocator; return &debug_info_arena_allocator.allocator; }
std/debug/index.zig
const std = @import("std"); const print = std.debug.print; const panic = std.debug.panic; const expect = std.testing.expect; fn freq(t: f32, f: f32, v: f32) f32 { return f / (t + 0.001 * v); } /// Transform a function of n arguments into a function of type FuncReturnT with /// a single argument, fixing all other arguments according to partial_args, /// except for one undefined value. pub fn partialize( comptime func: anytype, comptime FuncReturnT: type, comptime partial_args: anytype, ) FuncReturnT { // TODO we could also partialize w/ several args, but not sure it is very important // TODO would be better to have partial_args not be a tuple but a real // struct with named fields, so that we could match these fields with // the names of arguments of the function. But we can't access the names // of the arguments function? const FuncT: type = @TypeOf(func); const ReturnT: type = @typeInfo(FuncT).Fn.return_type.?; const ArgsT: type = std.meta.ArgsTuple(FuncT); const PartialArgsT = @TypeOf(partial_args); const fieldsArgs = std.meta.fields(ArgsT); const fieldsPArgs = std.meta.fields(PartialArgsT); if (fieldsArgs.len != fieldsPArgs.len) { panic("Error: not the same number of arguments in func and args.", .{}); } const MissingArgType = @typeInfo(FuncReturnT).Fn.args[0].arg_type.?; if (@typeInfo(FuncReturnT).Fn.args.len != 1) { panic("Error: the returned function should have a single argument.\n", .{}); } return struct { fn apply(missing_arg: MissingArgType) ReturnT { var complete_args: ArgsT = undefined; // iterate over the fields to fill in complete_args var n_found_missing: u32 = 0; inline for (std.meta.fields(ArgsT)) |f, i| { // select field address to fill const field = &@field(complete_args, f.name); if (@typeInfo(fieldsPArgs[i].field_type) != std.builtin.TypeInfo.Undefined) { // if not undefined, simply copy from partial_args field.* = @field(partial_args, f.name); } else { // if undefined, use missing_args field.* = missing_arg; n_found_missing += 1; // print("Missing arg #{} set to {}\n", .{ i, missing_arg }); } } if (n_found_missing == 0) { panic("No argument missing ('undefined' in partial_args).\n", .{}); } else if (n_found_missing > 1) { panic("Too many arguments missing ('undefined' in partial_args).\n", .{}); } return @call(.{ .modifier = .always_inline }, func, complete_args); } }.apply; } /// Given a type like fn (f32, i32, f32) f32, returns /// a tuple type {f32, i32, f32} /// TODO remove! like std.meta.ArgsTuple! // fn partial_args_type(FuncReturnT: T) type { // const missing_args = @typeInfo(FuncReturnT).Fn.args; // const missing_args_fields = [_]std.builtin.TypeInfo.StructField{} ** missing_args.len; // inline for (missing_args_fields) |ma, i| { // // ignore name, because is_tuple? // ma.field_type = missing_args[i].arg_type; // } // const info: std.builtin.TypeInfo = std.builtin.TypeInfo{ // .Struct = .{ // .layout = .Auto, // .fields = &missing_args_fields, // .decls = &[0]std.builtin.TypeInfo.Declaration{}, // .is_tuple = true, // }, // }; // return @Type(info); // } /// Given a like: fn (f32, i32, f32) f32 /// returns: fn ({f32, i32, f32}) f32 /// where the sole argument of the function is a tuple fn partial_func_type(comptime FuncReturnT: type) type { // const ArgsType = partial_args_type(FuncReturnT); const ArgsType = std.meta.ArgsTuple(FuncReturnT); const single_arg = std.builtin.TypeInfo.FnArg{ .is_generic = false, .is_noalias = false, .arg_type = ArgsType, }; const single_arg_array = [1]std.builtin.TypeInfo.FnArg{single_arg}; return @Type(std.builtin.TypeInfo{ .Fn = .{ .calling_convention = .Unspecified, .alignment = 0, .is_generic = false, .is_var_args = false, .args = single_arg_array[0..], .return_type = @typeInfo(FuncReturnT).Fn.return_type.?, }, }); } // TODO broken, but I don't understand why. pub fn partialize_nargs( comptime func: anytype, comptime FuncReturnT: type, comptime partial_args: anytype, comptime PFT: type, // ) partial_func_type(FuncReturnT) { //TODO restore that ) PFT { _ = FuncReturnT; const FuncT: type = @TypeOf(func); const ReturnT = @typeInfo(FuncT).Fn.return_type.?; const ArgsT: type = std.meta.ArgsTuple(FuncT); const PartialArgsT = @TypeOf(partial_args); const fieldsArgs = std.meta.fields(ArgsT); const fieldsPArgs = std.meta.fields(PartialArgsT); if (fieldsArgs.len != fieldsPArgs.len) { panic("Error: not the same number of arguments in func and args.", .{}); } // compute type of argument of the partial function: // a tuple containing the right types, as specified in FuncReturnT // const MissingArgType = std.meta.ArgsTuple(partial_func_type(FuncReturnT)); const MissingArgType = std.meta.ArgsTuple(PFT); return struct { fn apply(missing_arg: MissingArgType) ReturnT { var complete_args: ArgsT = undefined; // iterate over the fields to fill in complete_args comptime var n_found_missing: u32 = 0; inline for (std.meta.fields(ArgsT)) |f, i| { // select field address to fill const field = &@field(complete_args, f.name); if (@typeInfo(fieldsPArgs[i].field_type) != std.builtin.TypeInfo.Undefined) { // if not undefined, simply copy from partial_args field.* = @field(partial_args, f.name); } else { // if undefined, use missing_args // field.* = missing_arg[0][n_found_missing]; // field.* = missing_arg[n_found_missing]; field.* = 3.0; _ = missing_arg; // field.* = missing_arg.@"0".@"0"; n_found_missing += 1; // print("Missing arg #{} set to {}\n", .{ i, missing_arg }); } } if (n_found_missing == 0) { panic("No argument missing ('undefined' in partial_args).\n", .{}); } else if (n_found_missing > 1) { panic("Too many arguments missing ('undefined' in partial_args).\n", .{}); } return @call(.{ .modifier = .always_inline }, func, complete_args); } }.apply; } test "partial functions of 1 arg" { // test with 1st argument const partial_args = .{ undefined, 200.0, 0.5 }; const partial = comptime partialize(freq, fn (f32) f32, partial_args); var i: f32 = 0.0; while (i < 100) : (i += 1) { try expect(partial(i) == freq(i, 200.0, 0.5)); } // test with 2nd argument const partial_args2 = .{ 3.0, undefined, 0.4 }; const partial2 = comptime partialize(freq, fn (f32) f32, partial_args2); i = 0.0; while (i < 100) : (i += 1) { try expect(partial2(i) == freq(3.0, i, 0.4)); } } test "partial functions of several args" { // broken: ./src/partial_functions.zig:161:6: error: expected type 'fn(std.meta.struct:922:38) f32', found 'fn(std.meta.struct:922:38) f32' // const partial_args = .{ undefined, 200.0, undefined }; // const TT = partial_func_type(fn (f32, f32) f32); // // _ = TT; // const partial = comptime partialize_nargs(freq, fn (f32, f32) f32, partial_args, TT); // var i: f32 = 0.0; // while (i < 100) : (i += 1) { // try expect(partial(.{ i, i + 3 }) == freq(i, 200.0, i + 3)); // } // const a = .{ 3.0, 2.0, 1.0 }; // print("{}\n", .{a[1]}); }
src/partial_functions.zig
const build_options = @import("build_options"); usingnamespace if (build_options.vulkan) @import("vulkan.zig") else struct {}; usingnamespace @import("sdl_image.zig"); pub const SDL_INIT_TIMER: u32 = 0x00000001; pub const SDL_INIT_AUDIO: u32 = 0x00000010; pub const SDL_INIT_VIDEO: u32 = 0x00000020; pub const SDL_INIT_JOYSTICK: u32 = 0x00000200; pub const SDL_INIT_HAPTIC: u32 = 0x00001000; pub const SDL_INIT_GAMECONTROLLER: u32 = 0x00002000; pub const SDL_INIT_EVENTS: u32 = 0x00004000; pub const SDL_INIT_SENSOR: u32 = 0x00008000; pub const SDL_INIT_NOPARACHUTE: u32 = 0x00100000; pub const SDL_INIT_EVERYTHING: u32 = SDL_INIT_TIMER | SDL_INIT_AUDIO | SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_JOYSTICK | SDL_INIT_HAPTIC | SDL_INIT_GAMECONTROLLER | SDL_INIT_SENSOR; pub extern fn SDL_Init(flags: u32) c_int; pub extern fn SDL_InitSubSystem(flags: u32) c_int; pub extern fn SDL_QuitSubSystem(flags: u32) void; pub extern fn SDL_WasInit(flags: u32) u32; pub extern fn SDL_Quit() void; const is_big_endian = @import("std").Target.current.endianess == .big; pub const SDL_VERSION = SDL_version{ .major = SDL_MAJOR_VERSION, .minor = SDL_MINOR_VERSION, .patch = SDL_PATCHLEVEL, }; pub fn SDL_VERSIONNUM(X: usize, Y: usize, Z: usize) usize { return (X) * 1000 + (Y) * 100 + (Z); } pub const SDL_COMPILEDVERSION = SDL_VERSIONNUM(SDL_MAJOR_VERSION, SDL_MINOR_VERSION, SDL_PATCHLEVEL); pub fn SDL_VERSION_ATLEAST(X: usize, Y: usize, Z: usize) bool { return SDL_COMPILEDVERSION >= SDL_VERSIONNUM(X, Y, Z); } // // SDL_COMPILE_TIME_ASSERT(SDL_Event, sizeof(SDL_Event) == sizeof(((SDL_Event *)NULL)->padding)); pub const SDL_bool = c_int; pub const SDL_Rect = extern struct { x: c_int, y: c_int, w: c_int, h: c_int, }; pub extern fn SDL_GetCPUCount() c_int; pub extern fn SDL_GetCPUCacheLineSize() c_int; pub extern fn SDL_HasRDTSC() SDL_bool; pub extern fn SDL_HasAltiVec() SDL_bool; pub extern fn SDL_HasMMX() SDL_bool; pub extern fn SDL_Has3DNow() SDL_bool; pub extern fn SDL_HasSSE() SDL_bool; pub extern fn SDL_HasSSE2() SDL_bool; pub extern fn SDL_HasSSE3() SDL_bool; pub extern fn SDL_HasSSE41() SDL_bool; pub extern fn SDL_HasSSE42() SDL_bool; pub extern fn SDL_HasAVX() SDL_bool; pub extern fn SDL_HasAVX2() SDL_bool; pub extern fn SDL_HasAVX512F() SDL_bool; pub extern fn SDL_HasARMSIMD() SDL_bool; pub extern fn SDL_HasNEON() SDL_bool; pub extern fn SDL_GetSystemRAM() c_int; pub extern fn SDL_SIMDGetAlignment() usize; pub extern fn SDL_SIMDAlloc(len: usize) ?*anyopaque; pub extern fn SDL_SIMDRealloc(mem: ?*anyopaque, len: usize) ?*anyopaque; pub extern fn SDL_SIMDFree(ptr: ?*anyopaque) void; pub const SDL_Point = extern struct { x: c_int, y: c_int, }; pub const SDL_FPoint = extern struct { x: f32, y: f32, }; pub const SDL_FRect = extern struct { x: f32, y: f32, w: f32, h: f32, }; pub fn SDL_PointInRect(arg_p: [*c]const SDL_Point, arg_r: [*c]const SDL_Rect) SDL_bool { var p = arg_p; var r = arg_r; return if ((((p.*.x >= r.*.x) and (p.*.x < (r.*.x + r.*.w))) and (p.*.y >= r.*.y)) and (p.*.y < (r.*.y + r.*.h))) @as(c_int, 1) else @as(c_int, 0); } pub fn SDL_RectEmpty(arg_r: [*c]const SDL_Rect) SDL_bool { var r = arg_r; return if ((!(r != null) or (r.*.w <= @as(c_int, 0))) or (r.*.h <= @as(c_int, 0))) @as(c_int, 1) else @as(c_int, 0); } pub fn SDL_RectEquals(arg_a: [*c]const SDL_Rect, arg_b: [*c]const SDL_Rect) SDL_bool { var a = arg_a; var b = arg_b; return if ((((((a != null) and (b != null)) and (a.*.x == b.*.x)) and (a.*.y == b.*.y)) and (a.*.w == b.*.w)) and (a.*.h == b.*.h)) @as(c_int, 1) else @as(c_int, 0); } pub extern fn SDL_HasIntersection(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect) SDL_bool; pub extern fn SDL_IntersectRect(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect, result: [*c]SDL_Rect) SDL_bool; pub extern fn SDL_UnionRect(A: [*c]const SDL_Rect, B: [*c]const SDL_Rect, result: [*c]SDL_Rect) void; pub extern fn SDL_EnclosePoints(points: [*c]const SDL_Point, count: c_int, clip: [*c]const SDL_Rect, result: [*c]SDL_Rect) SDL_bool; pub extern fn SDL_IntersectRectAndLine(rect: [*c]const SDL_Rect, X1: [*c]c_int, Y1: [*c]c_int, X2: [*c]c_int, Y2: [*c]c_int) SDL_bool; pub const SDL_RWops = extern struct { size: ?fn ([*c]SDL_RWops) callconv(.C) i64, seek: ?fn ([*c]SDL_RWops, i64, c_int) callconv(.C) i64, read: ?fn ([*c]SDL_RWops, ?*anyopaque, usize, usize) callconv(.C) usize, write: ?fn ([*c]SDL_RWops, ?*const anyopaque, usize, usize) callconv(.C) usize, close: ?fn ([*c]SDL_RWops) callconv(.C) c_int, type: u32, hidden: Data, const Data = extern union { mem: Memory, unknown: Unknown, pub const Memory = extern struct { base: [*]u8, here: [*]u8, stop: [*]u8, }; pub const Unknown = extern struct { data1: ?*anyopaque, data2: ?*anyopaque, }; // #if defined(__ANDROID__) // struct // { // void *asset; // } androidio; // #elif defined(__WIN32__) // struct // { // SDL_bool append; // void *h; // struct // { // void *data; // size_t size; // size_t left; // } buffer; // } windowsio; // #elif defined(__VITA__) // struct // { // int h; // struct // { // void *data; // size_t size; // size_t left; // } buffer; // } vitaio; // #endif // #ifdef HAVE_STDIO_H // struct // { // SDL_bool autoclose; // FILE *fp; // } stdio; // #endif }; }; pub extern fn SDL_RWFromFile(file: [*c]const u8, mode: [*c]const u8) ?*SDL_RWops; pub extern fn SDL_RWFromFP(fp: ?*anyopaque, autoclose: SDL_bool) ?*SDL_RWops; pub extern fn SDL_RWFromMem(mem: ?*anyopaque, size: c_int) ?*SDL_RWops; pub extern fn SDL_RWFromConstMem(mem: ?*const anyopaque, size: c_int) ?*SDL_RWops; pub extern fn SDL_AllocRW() ?*SDL_RWops; pub extern fn SDL_FreeRW(area: SDL_RWops) void; pub extern fn SDL_RWsize(context: *SDL_RWops) i64; pub extern fn SDL_RWseek(context: *SDL_RWops, offset: i64, whence: c_int) i64; pub extern fn SDL_RWtell(context: *SDL_RWops) i64; pub extern fn SDL_RWread(context: *SDL_RWops, ptr: ?*anyopaque, size: usize, maxnum: usize) usize; pub extern fn SDL_RWwrite(context: *SDL_RWops, ptr: ?*const anyopaque, size: usize, num: usize) usize; pub extern fn SDL_RWclose(context: *SDL_RWops) c_int; pub extern fn SDL_LoadFile_RW(src: *SDL_RWops, datasize: *usize, freesrc: c_int) ?*anyopaque; pub extern fn SDL_LoadFile(file: [*:0]const u8, datasize: *usize) ?*anyopaque; pub extern fn SDL_ReadU8(src: *SDL_RWops) u8; pub extern fn SDL_ReadLE16(src: *SDL_RWops) u16; pub extern fn SDL_ReadBE16(src: *SDL_RWops) u16; pub extern fn SDL_ReadLE32(src: *SDL_RWops) u32; pub extern fn SDL_ReadBE32(src: *SDL_RWops) u32; pub extern fn SDL_ReadLE64(src: *SDL_RWops) u64; pub extern fn SDL_ReadBE64(src: *SDL_RWops) u64; pub extern fn SDL_WriteU8(dst: *SDL_RWops, value: u8) usize; pub extern fn SDL_WriteLE16(dst: *SDL_RWops, value: u16) usize; pub extern fn SDL_WriteBE16(dst: *SDL_RWops, value: u16) usize; pub extern fn SDL_WriteLE32(dst: *SDL_RWops, value: u32) usize; pub extern fn SDL_WriteBE32(dst: *SDL_RWops, value: u32) usize; pub extern fn SDL_WriteLE64(dst: *SDL_RWops, value: u64) usize; pub extern fn SDL_WriteBE64(dst: *SDL_RWops, value: u64) usize; pub const SDL_BLENDMODE_NONE: c_int = 0; pub const SDL_BLENDMODE_BLEND: c_int = 1; pub const SDL_BLENDMODE_ADD: c_int = 2; pub const SDL_BLENDMODE_MOD: c_int = 4; pub const SDL_BLENDMODE_MUL: c_int = 8; pub const SDL_BLENDMODE_INVALID: c_int = 2147483647; pub const SDL_BlendMode = c_uint; pub const SDL_PIXELTYPE_UNKNOWN: c_int = 0; pub const SDL_PIXELTYPE_INDEX1: c_int = 1; pub const SDL_PIXELTYPE_INDEX4: c_int = 2; pub const SDL_PIXELTYPE_INDEX8: c_int = 3; pub const SDL_PIXELTYPE_PACKED8: c_int = 4; pub const SDL_PIXELTYPE_PACKED16: c_int = 5; pub const SDL_PIXELTYPE_PACKED32: c_int = 6; pub const SDL_PIXELTYPE_ARRAYU8: c_int = 7; pub const SDL_PIXELTYPE_ARRAYU16: c_int = 8; pub const SDL_PIXELTYPE_ARRAYU32: c_int = 9; pub const SDL_PIXELTYPE_ARRAYF16: c_int = 10; pub const SDL_PIXELTYPE_ARRAYF32: c_int = 11; pub const SDL_PixelType = c_uint; pub const SDL_BITMAPORDER_NONE: c_int = 0; pub const SDL_BITMAPORDER_4321: c_int = 1; pub const SDL_BITMAPORDER_1234: c_int = 2; pub const SDL_BitmapOrder = c_uint; pub const SDL_PACKEDORDER_NONE: c_int = 0; pub const SDL_PACKEDORDER_XRGB: c_int = 1; pub const SDL_PACKEDORDER_RGBX: c_int = 2; pub const SDL_PACKEDORDER_ARGB: c_int = 3; pub const SDL_PACKEDORDER_RGBA: c_int = 4; pub const SDL_PACKEDORDER_XBGR: c_int = 5; pub const SDL_PACKEDORDER_BGRX: c_int = 6; pub const SDL_PACKEDORDER_ABGR: c_int = 7; pub const SDL_PACKEDORDER_BGRA: c_int = 8; pub const SDL_PackedOrder = c_uint; pub const SDL_ARRAYORDER_NONE: c_int = 0; pub const SDL_ARRAYORDER_RGB: c_int = 1; pub const SDL_ARRAYORDER_RGBA: c_int = 2; pub const SDL_ARRAYORDER_ARGB: c_int = 3; pub const SDL_ARRAYORDER_BGR: c_int = 4; pub const SDL_ARRAYORDER_BGRA: c_int = 5; pub const SDL_ARRAYORDER_ABGR: c_int = 6; pub const SDL_ArrayOrder = c_uint; pub const SDL_PACKEDLAYOUT_NONE: c_int = 0; pub const SDL_PACKEDLAYOUT_332: c_int = 1; pub const SDL_PACKEDLAYOUT_4444: c_int = 2; pub const SDL_PACKEDLAYOUT_1555: c_int = 3; pub const SDL_PACKEDLAYOUT_5551: c_int = 4; pub const SDL_PACKEDLAYOUT_565: c_int = 5; pub const SDL_PACKEDLAYOUT_8888: c_int = 6; pub const SDL_PACKEDLAYOUT_2101010: c_int = 7; pub const SDL_PACKEDLAYOUT_1010102: c_int = 8; pub const SDL_PackedLayout = c_uint; pub const SDL_PIXELFORMAT_UNKNOWN: c_int = 0; pub const SDL_PIXELFORMAT_INDEX1LSB: c_int = 286261504; pub const SDL_PIXELFORMAT_INDEX1MSB: c_int = 287310080; pub const SDL_PIXELFORMAT_INDEX4LSB: c_int = 303039488; pub const SDL_PIXELFORMAT_INDEX4MSB: c_int = 304088064; pub const SDL_PIXELFORMAT_INDEX8: c_int = 318769153; pub const SDL_PIXELFORMAT_RGB332: c_int = 336660481; pub const SDL_PIXELFORMAT_XRGB4444: c_int = 353504258; pub const SDL_PIXELFORMAT_RGB444: c_int = 353504258; pub const SDL_PIXELFORMAT_XBGR4444: c_int = 357698562; pub const SDL_PIXELFORMAT_BGR444: c_int = 357698562; pub const SDL_PIXELFORMAT_XRGB1555: c_int = 353570562; pub const SDL_PIXELFORMAT_RGB555: c_int = 353570562; pub const SDL_PIXELFORMAT_XBGR1555: c_int = 357764866; pub const SDL_PIXELFORMAT_BGR555: c_int = 357764866; pub const SDL_PIXELFORMAT_ARGB4444: c_int = 355602434; pub const SDL_PIXELFORMAT_RGBA4444: c_int = 356651010; pub const SDL_PIXELFORMAT_ABGR4444: c_int = 359796738; pub const SDL_PIXELFORMAT_BGRA4444: c_int = 360845314; pub const SDL_PIXELFORMAT_ARGB1555: c_int = 355667970; pub const SDL_PIXELFORMAT_RGBA5551: c_int = 356782082; pub const SDL_PIXELFORMAT_ABGR1555: c_int = 359862274; pub const SDL_PIXELFORMAT_BGRA5551: c_int = 360976386; pub const SDL_PIXELFORMAT_RGB565: c_int = 353701890; pub const SDL_PIXELFORMAT_BGR565: c_int = 357896194; pub const SDL_PIXELFORMAT_RGB24: c_int = 386930691; pub const SDL_PIXELFORMAT_BGR24: c_int = 390076419; pub const SDL_PIXELFORMAT_XRGB8888: c_int = 370546692; pub const SDL_PIXELFORMAT_RGB888: c_int = 370546692; pub const SDL_PIXELFORMAT_RGBX8888: c_int = 371595268; pub const SDL_PIXELFORMAT_XBGR8888: c_int = 374740996; pub const SDL_PIXELFORMAT_BGR888: c_int = 374740996; pub const SDL_PIXELFORMAT_BGRX8888: c_int = 375789572; pub const SDL_PIXELFORMAT_ARGB8888: c_int = 372645892; pub const SDL_PIXELFORMAT_RGBA8888: c_int = 373694468; pub const SDL_PIXELFORMAT_ABGR8888: c_int = 376840196; pub const SDL_PIXELFORMAT_BGRA8888: c_int = 377888772; pub const SDL_PIXELFORMAT_ARGB2101010: c_int = 372711428; pub const SDL_PIXELFORMAT_YV12: c_int = 842094169; pub const SDL_PIXELFORMAT_IYUV: c_int = 1448433993; pub const SDL_PIXELFORMAT_YUY2: c_int = 844715353; pub const SDL_PIXELFORMAT_UYVY: c_int = 1498831189; pub const SDL_PIXELFORMAT_YVYU: c_int = 1431918169; pub const SDL_PIXELFORMAT_NV12: c_int = 842094158; pub const SDL_PIXELFORMAT_NV21: c_int = 825382478; pub const SDL_PIXELFORMAT_EXTERNAL_OES: c_int = 542328143; pub const SDL_PIXELFORMAT_RGBA32 = if (is_big_endian) SDL_PIXELFORMAT_RGBA8888 else SDL_PIXELFORMAT_ABGR8888; pub const SDL_PIXELFORMAT_ARGB32 = if (is_big_endian) SDL_PIXELFORMAT_ARGB8888 else SDL_PIXELFORMAT_BGRA8888; pub const SDL_PIXELFORMAT_BGRA32 = if (is_big_endian) SDL_PIXELFORMAT_BGRA8888 else SDL_PIXELFORMAT_ARGB8888; pub const SDL_PIXELFORMAT_ABGR32 = if (is_big_endian) SDL_PIXELFORMAT_ABGR8888 else SDL_PIXELFORMAT_RGBA8888; pub const SDL_PixelFormatEnum = c_uint; pub const SDL_Color = extern struct { r: u8, g: u8, b: u8, a: u8, }; pub const SDL_Palette = extern struct { ncolors: c_int, colors: [*c]SDL_Color, version: u32, refcount: c_int, }; pub const SDL_PixelFormat = extern struct { format: u32, palette: [*c]SDL_Palette, BitsPerPixel: u8, BytesPerPixel: u8, padding: [2]u8, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32, Rloss: u8, Gloss: u8, Bloss: u8, Aloss: u8, Rshift: u8, Gshift: u8, Bshift: u8, Ashift: u8, refcount: c_int, next: [*c]SDL_PixelFormat, }; pub extern fn SDL_GetPixelFormatName(format: u32) [*c]const u8; pub extern fn SDL_PixelFormatEnumToMasks(format: u32, bpp: [*c]c_int, Rmask: [*c]u32, Gmask: [*c]u32, Bmask: [*c]u32, Amask: [*c]u32) SDL_bool; pub extern fn SDL_MasksToPixelFormatEnum(bpp: c_int, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) u32; pub extern fn SDL_AllocFormat(pixel_format: u32) [*c]SDL_PixelFormat; pub extern fn SDL_FreeFormat(format: [*c]SDL_PixelFormat) void; pub extern fn SDL_AllocPalette(ncolors: c_int) [*c]SDL_Palette; pub extern fn SDL_SetPixelFormatPalette(format: [*c]SDL_PixelFormat, palette: [*c]SDL_Palette) c_int; pub extern fn SDL_SetPaletteColors(palette: [*c]SDL_Palette, colors: [*c]const SDL_Color, firstcolor: c_int, ncolors: c_int) c_int; pub extern fn SDL_FreePalette(palette: [*c]SDL_Palette) void; pub extern fn SDL_MapRGB(format: [*c]const SDL_PixelFormat, r: u8, g: u8, b: u8) u32; pub extern fn SDL_MapRGBA(format: [*c]const SDL_PixelFormat, r: u8, g: u8, b: u8, a: u8) u32; pub extern fn SDL_GetRGB(pixel: u32, format: [*c]const SDL_PixelFormat, r: [*c]u8, g: [*c]u8, b: [*c]u8) void; pub extern fn SDL_GetRGBA(pixel: u32, format: [*c]const SDL_PixelFormat, r: [*c]u8, g: [*c]u8, b: [*c]u8, a: [*c]u8) void; pub extern fn SDL_CalculateGammaRamp(gamma: f32, ramp: [*c]u16) void; pub const SDL_BlitMap = opaque {}; pub const SDL_Surface = extern struct { flags: u32, format: [*c]SDL_PixelFormat, w: c_int, h: c_int, pitch: c_int, pixels: ?*anyopaque, userdata: ?*anyopaque, locked: c_int, list_blitmap: ?*anyopaque, clip_rect: SDL_Rect, map: ?*SDL_BlitMap, refcount: c_int, }; pub const SDL_blit = ?fn ([*c]SDL_Surface, [*c]SDL_Rect, [*c]SDL_Surface, [*c]SDL_Rect) callconv(.C) c_int; pub const SDL_YUV_CONVERSION_JPEG: c_int = 0; pub const SDL_YUV_CONVERSION_BT601: c_int = 1; pub const SDL_YUV_CONVERSION_BT709: c_int = 2; pub const SDL_YUV_CONVERSION_AUTOMATIC: c_int = 3; pub const SDL_YUV_CONVERSION_MODE = c_uint; pub extern fn SDL_CreateRGBSurface(flags: u32, width: c_int, height: c_int, depth: c_int, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceWithFormat(flags: u32, width: c_int, height: c_int, depth: c_int, format: u32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceFrom(pixels: ?*anyopaque, width: c_int, height: c_int, depth: c_int, pitch: c_int, Rmask: u32, Gmask: u32, Bmask: u32, Amask: u32) [*c]SDL_Surface; pub extern fn SDL_CreateRGBSurfaceWithFormatFrom(pixels: ?*anyopaque, width: c_int, height: c_int, depth: c_int, pitch: c_int, format: u32) [*c]SDL_Surface; pub extern fn SDL_FreeSurface(surface: [*c]SDL_Surface) void; pub extern fn SDL_SetSurfacePalette(surface: [*c]SDL_Surface, palette: [*c]SDL_Palette) c_int; pub extern fn SDL_LockSurface(surface: [*c]SDL_Surface) c_int; pub extern fn SDL_UnlockSurface(surface: [*c]SDL_Surface) void; pub extern fn SDL_LoadBMP_RW(src: [*c]SDL_RWops, freesrc: c_int) [*c]SDL_Surface; pub extern fn SDL_SaveBMP_RW(surface: [*c]SDL_Surface, dst: [*c]SDL_RWops, freedst: c_int) c_int; pub extern fn SDL_SetSurfaceRLE(surface: [*c]SDL_Surface, flag: c_int) c_int; pub extern fn SDL_HasSurfaceRLE(surface: [*c]SDL_Surface) SDL_bool; pub extern fn SDL_SetColorKey(surface: [*c]SDL_Surface, flag: c_int, key: u32) c_int; pub extern fn SDL_HasColorKey(surface: [*c]SDL_Surface) SDL_bool; pub extern fn SDL_GetColorKey(surface: [*c]SDL_Surface, key: [*c]u32) c_int; pub extern fn SDL_SetSurfaceColorMod(surface: [*c]SDL_Surface, r: u8, g: u8, b: u8) c_int; pub extern fn SDL_GetSurfaceColorMod(surface: [*c]SDL_Surface, r: [*c]u8, g: [*c]u8, b: [*c]u8) c_int; pub extern fn SDL_SetSurfaceAlphaMod(surface: [*c]SDL_Surface, alpha: u8) c_int; pub extern fn SDL_GetSurfaceAlphaMod(surface: [*c]SDL_Surface, alpha: [*c]u8) c_int; pub extern fn SDL_SetSurfaceBlendMode(surface: [*c]SDL_Surface, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetSurfaceBlendMode(surface: [*c]SDL_Surface, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_SetClipRect(surface: [*c]SDL_Surface, rect: [*c]const SDL_Rect) SDL_bool; pub extern fn SDL_GetClipRect(surface: [*c]SDL_Surface, rect: [*c]SDL_Rect) void; pub extern fn SDL_DuplicateSurface(surface: [*c]SDL_Surface) [*c]SDL_Surface; pub extern fn SDL_ConvertSurface(src: [*c]SDL_Surface, fmt: [*c]const SDL_PixelFormat, flags: u32) [*c]SDL_Surface; pub extern fn SDL_ConvertSurfaceFormat(src: [*c]SDL_Surface, pixel_format: u32, flags: u32) [*c]SDL_Surface; pub extern fn SDL_ConvertPixels(width: c_int, height: c_int, src_format: u32, src: ?*const anyopaque, src_pitch: c_int, dst_format: u32, dst: ?*anyopaque, dst_pitch: c_int) c_int; pub extern fn SDL_FillRect(dst: [*c]SDL_Surface, rect: [*c]const SDL_Rect, color: u32) c_int; pub extern fn SDL_FillRects(dst: [*c]SDL_Surface, rects: [*c]const SDL_Rect, count: c_int, color: u32) c_int; pub extern fn SDL_UpperBlit(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_LowerBlit(src: [*c]SDL_Surface, srcrect: [*c]SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_SoftStretch(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_SoftStretchLinear(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_UpperBlitScaled(src: [*c]SDL_Surface, srcrect: [*c]const SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_LowerBlitScaled(src: [*c]SDL_Surface, srcrect: [*c]SDL_Rect, dst: [*c]SDL_Surface, dstrect: [*c]SDL_Rect) c_int; pub extern fn SDL_SetYUVConversionMode(mode: SDL_YUV_CONVERSION_MODE) void; pub extern fn SDL_GetYUVConversionMode() SDL_YUV_CONVERSION_MODE; pub extern fn SDL_GetYUVConversionModeForResolution(width: c_int, height: c_int) SDL_YUV_CONVERSION_MODE; pub const SDL_BLENDOPERATION_ADD: c_int = 1; pub const SDL_BLENDOPERATION_SUBTRACT: c_int = 2; pub const SDL_BLENDOPERATION_REV_SUBTRACT: c_int = 3; pub const SDL_BLENDOPERATION_MINIMUM: c_int = 4; pub const SDL_BLENDOPERATION_MAXIMUM: c_int = 5; pub const SDL_BlendOperation = c_uint; pub const SDL_BLENDFACTOR_ZERO: c_int = 1; pub const SDL_BLENDFACTOR_ONE: c_int = 2; pub const SDL_BLENDFACTOR_SRC_COLOR: c_int = 3; pub const SDL_BLENDFACTOR_ONE_MINUS_SRC_COLOR: c_int = 4; pub const SDL_BLENDFACTOR_SRC_ALPHA: c_int = 5; pub const SDL_BLENDFACTOR_ONE_MINUS_SRC_ALPHA: c_int = 6; pub const SDL_BLENDFACTOR_DST_COLOR: c_int = 7; pub const SDL_BLENDFACTOR_ONE_MINUS_DST_COLOR: c_int = 8; pub const SDL_BLENDFACTOR_DST_ALPHA: c_int = 9; pub const SDL_BLENDFACTOR_ONE_MINUS_DST_ALPHA: c_int = 10; pub const SDL_BlendFactor = c_uint; pub extern fn SDL_ComposeCustomBlendMode(srcColorFactor: SDL_BlendFactor, dstColorFactor: SDL_BlendFactor, colorOperation: SDL_BlendOperation, srcAlphaFactor: SDL_BlendFactor, dstAlphaFactor: SDL_BlendFactor, alphaOperation: SDL_BlendOperation) SDL_BlendMode; pub extern fn SDL_SetClipboardText(text: [*c]const u8) c_int; pub extern fn SDL_GetClipboardText() [*c]u8; pub extern fn SDL_HasClipboardText() SDL_bool; pub extern fn SDL_free(data: [*c]const u8) void; pub const SDL_AudioFormat = u16; pub const SDL_AudioCallback = ?fn (?*anyopaque, [*c]u8, c_int) callconv(.C) void; pub const SDL_AudioSpec = extern struct { freq: c_int, format: SDL_AudioFormat, channels: u8, silence: u8, samples: u16, padding: u16, size: u32, callback: SDL_AudioCallback, userdata: ?*anyopaque, }; pub const SDL_AudioFilter = ?fn ([*c]SDL_AudioCVT, SDL_AudioFormat) callconv(.C) void; pub const SDL_AudioCVT = extern struct { needed: c_int, src_format: SDL_AudioFormat, dst_format: SDL_AudioFormat, rate_incr: f64, buf: [*c]u8, len: c_int, len_cvt: c_int, len_mult: c_int, len_ratio: f64, filters: [10]SDL_AudioFilter, filter_index: c_int, }; pub extern fn SDL_GetNumAudioDrivers() c_int; pub extern fn SDL_GetAudioDriver(index: c_int) [*c]const u8; pub extern fn SDL_AudioInit(driver_name: [*c]const u8) c_int; pub extern fn SDL_AudioQuit() void; pub extern fn SDL_GetCurrentAudioDriver() [*c]const u8; pub extern fn SDL_OpenAudio(desired: [*c]SDL_AudioSpec, obtained: [*c]SDL_AudioSpec) c_int; pub const SDL_AudioDeviceID = u32; pub extern fn SDL_GetNumAudioDevices(iscapture: c_int) c_int; pub extern fn SDL_GetAudioDeviceName(index: c_int, iscapture: c_int) [*c]const u8; pub extern fn SDL_GetAudioDeviceSpec(index: c_int, iscapture: c_int, spec: [*c]SDL_AudioSpec) c_int; pub extern fn SDL_OpenAudioDevice(device: [*c]const u8, iscapture: c_int, desired: [*c]const SDL_AudioSpec, obtained: [*c]SDL_AudioSpec, allowed_changes: c_int) SDL_AudioDeviceID; pub const SDL_AUDIO_STOPPED: c_int = 0; pub const SDL_AUDIO_PLAYING: c_int = 1; pub const SDL_AUDIO_PAUSED: c_int = 2; pub const SDL_AudioStatus = c_uint; pub extern fn SDL_GetAudioStatus() SDL_AudioStatus; pub extern fn SDL_GetAudioDeviceStatus(dev: SDL_AudioDeviceID) SDL_AudioStatus; pub extern fn SDL_PauseAudio(pause_on: c_int) void; pub extern fn SDL_PauseAudioDevice(dev: SDL_AudioDeviceID, pause_on: c_int) void; pub extern fn SDL_LoadWAV_RW(src: [*c]SDL_RWops, freesrc: c_int, spec: [*c]SDL_AudioSpec, audio_buf: [*c][*c]u8, audio_len: [*c]u32) [*c]SDL_AudioSpec; pub extern fn SDL_FreeWAV(audio_buf: [*c]u8) void; pub extern fn SDL_BuildAudioCVT(cvt: [*c]SDL_AudioCVT, src_format: SDL_AudioFormat, src_channels: u8, src_rate: c_int, dst_format: SDL_AudioFormat, dst_channels: u8, dst_rate: c_int) c_int; pub extern fn SDL_ConvertAudio(cvt: [*c]SDL_AudioCVT) c_int; pub const _SDL_AudioStream = opaque {}; pub const SDL_AudioStream = _SDL_AudioStream; pub extern fn SDL_NewAudioStream(src_format: SDL_AudioFormat, src_channels: u8, src_rate: c_int, dst_format: SDL_AudioFormat, dst_channels: u8, dst_rate: c_int) ?*SDL_AudioStream; pub extern fn SDL_AudioStreamPut(stream: ?*SDL_AudioStream, buf: ?*const anyopaque, len: c_int) c_int; pub extern fn SDL_AudioStreamGet(stream: ?*SDL_AudioStream, buf: ?*anyopaque, len: c_int) c_int; pub extern fn SDL_AudioStreamAvailable(stream: ?*SDL_AudioStream) c_int; pub extern fn SDL_AudioStreamFlush(stream: ?*SDL_AudioStream) c_int; pub extern fn SDL_AudioStreamClear(stream: ?*SDL_AudioStream) void; pub extern fn SDL_FreeAudioStream(stream: ?*SDL_AudioStream) void; pub extern fn SDL_MixAudio(dst: [*c]u8, src: [*c]const u8, len: u32, volume: c_int) void; pub extern fn SDL_MixAudioFormat(dst: [*c]u8, src: [*c]const u8, format: SDL_AudioFormat, len: u32, volume: c_int) void; pub extern fn SDL_QueueAudio(dev: SDL_AudioDeviceID, data: ?*const anyopaque, len: u32) c_int; pub extern fn SDL_DequeueAudio(dev: SDL_AudioDeviceID, data: ?*anyopaque, len: u32) u32; pub extern fn SDL_GetQueuedAudioSize(dev: SDL_AudioDeviceID) u32; pub extern fn SDL_ClearQueuedAudio(dev: SDL_AudioDeviceID) void; pub extern fn SDL_LockAudio() void; pub extern fn SDL_LockAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_UnlockAudio() void; pub extern fn SDL_UnlockAudioDevice(dev: SDL_AudioDeviceID) void; pub extern fn SDL_CloseAudio() void; pub extern fn SDL_CloseAudioDevice(dev: SDL_AudioDeviceID) void; pub const SDL_DisplayMode = extern struct { format: u32, w: c_int, h: c_int, refresh_rate: c_int, driverdata: ?*anyopaque, }; pub const SDL_Window = opaque {}; pub const SDL_WINDOW_FULLSCREEN: c_int = 1; pub const SDL_WINDOW_OPENGL: c_int = 2; pub const SDL_WINDOW_SHOWN: c_int = 4; pub const SDL_WINDOW_HIDDEN: c_int = 8; pub const SDL_WINDOW_BORDERLESS: c_int = 16; pub const SDL_WINDOW_RESIZABLE: c_int = 32; pub const SDL_WINDOW_MINIMIZED: c_int = 64; pub const SDL_WINDOW_MAXIMIZED: c_int = 128; pub const SDL_WINDOW_MOUSE_GRABBED: c_int = 256; pub const SDL_WINDOW_INPUT_FOCUS: c_int = 512; pub const SDL_WINDOW_MOUSE_FOCUS: c_int = 1024; pub const SDL_WINDOW_FULLSCREEN_DESKTOP: c_int = 4097; pub const SDL_WINDOW_FOREIGN: c_int = 2048; pub const SDL_WINDOW_ALLOW_HIGHDPI: c_int = 8192; pub const SDL_WINDOW_MOUSE_CAPTURE: c_int = 16384; pub const SDL_WINDOW_ALWAYS_ON_TOP: c_int = 32768; pub const SDL_WINDOW_SKIP_TASKBAR: c_int = 65536; pub const SDL_WINDOW_UTILITY: c_int = 131072; pub const SDL_WINDOW_TOOLTIP: c_int = 262144; pub const SDL_WINDOW_POPUP_MENU: c_int = 524288; pub const SDL_WINDOW_KEYBOARD_GRABBED: c_int = 1048576; pub const SDL_WINDOW_VULKAN: c_int = 268435456; pub const SDL_WINDOW_METAL: c_int = 536870912; pub const SDL_WINDOW_INPUT_GRABBED: c_int = 256; pub const SDL_WindowFlags = c_uint; pub const SDL_WINDOWEVENT_NONE: c_int = 0; pub const SDL_WINDOWEVENT_SHOWN: c_int = 1; pub const SDL_WINDOWEVENT_HIDDEN: c_int = 2; pub const SDL_WINDOWEVENT_EXPOSED: c_int = 3; pub const SDL_WINDOWEVENT_MOVED: c_int = 4; pub const SDL_WINDOWEVENT_RESIZED: c_int = 5; pub const SDL_WINDOWEVENT_SIZE_CHANGED: c_int = 6; pub const SDL_WINDOWEVENT_MINIMIZED: c_int = 7; pub const SDL_WINDOWEVENT_MAXIMIZED: c_int = 8; pub const SDL_WINDOWEVENT_RESTORED: c_int = 9; pub const SDL_WINDOWEVENT_ENTER: c_int = 10; pub const SDL_WINDOWEVENT_LEAVE: c_int = 11; pub const SDL_WINDOWEVENT_FOCUS_GAINED: c_int = 12; pub const SDL_WINDOWEVENT_FOCUS_LOST: c_int = 13; pub const SDL_WINDOWEVENT_CLOSE: c_int = 14; pub const SDL_WINDOWEVENT_TAKE_FOCUS: c_int = 15; pub const SDL_WINDOWEVENT_HIT_TEST: c_int = 16; pub const SDL_WindowEventID = c_uint; pub const SDL_DISPLAYEVENT_NONE: c_int = 0; pub const SDL_DISPLAYEVENT_ORIENTATION: c_int = 1; pub const SDL_DISPLAYEVENT_CONNECTED: c_int = 2; pub const SDL_DISPLAYEVENT_DISCONNECTED: c_int = 3; pub const SDL_DisplayEventID = c_uint; pub const SDL_ORIENTATION_UNKNOWN: c_int = 0; pub const SDL_ORIENTATION_LANDSCAPE: c_int = 1; pub const SDL_ORIENTATION_LANDSCAPE_FLIPPED: c_int = 2; pub const SDL_ORIENTATION_PORTRAIT: c_int = 3; pub const SDL_ORIENTATION_PORTRAIT_FLIPPED: c_int = 4; pub const SDL_DisplayOrientation = c_uint; pub const SDL_FLASH_CANCEL: c_int = 0; pub const SDL_FLASH_BRIEFLY: c_int = 1; pub const SDL_FLASH_UNTIL_FOCUSED: c_int = 2; pub const SDL_FlashOperation = c_uint; pub const SDL_GLContext = ?*anyopaque; pub const SDL_GL_RED_SIZE: c_int = 0; pub const SDL_GL_GREEN_SIZE: c_int = 1; pub const SDL_GL_BLUE_SIZE: c_int = 2; pub const SDL_GL_ALPHA_SIZE: c_int = 3; pub const SDL_GL_BUFFER_SIZE: c_int = 4; pub const SDL_GL_DOUBLEBUFFER: c_int = 5; pub const SDL_GL_DEPTH_SIZE: c_int = 6; pub const SDL_GL_STENCIL_SIZE: c_int = 7; pub const SDL_GL_ACCUM_RED_SIZE: c_int = 8; pub const SDL_GL_ACCUM_GREEN_SIZE: c_int = 9; pub const SDL_GL_ACCUM_BLUE_SIZE: c_int = 10; pub const SDL_GL_ACCUM_ALPHA_SIZE: c_int = 11; pub const SDL_GL_STEREO: c_int = 12; pub const SDL_GL_MULTISAMPLEBUFFERS: c_int = 13; pub const SDL_GL_MULTISAMPLESAMPLES: c_int = 14; pub const SDL_GL_ACCELERATED_VISUAL: c_int = 15; pub const SDL_GL_RETAINED_BACKING: c_int = 16; pub const SDL_GL_CONTEXT_MAJOR_VERSION: c_int = 17; pub const SDL_GL_CONTEXT_MINOR_VERSION: c_int = 18; pub const SDL_GL_CONTEXT_EGL: c_int = 19; pub const SDL_GL_CONTEXT_FLAGS: c_int = 20; pub const SDL_GL_CONTEXT_PROFILE_MASK: c_int = 21; pub const SDL_GL_SHARE_WITH_CURRENT_CONTEXT: c_int = 22; pub const SDL_GL_FRAMEBUFFER_SRGB_CAPABLE: c_int = 23; pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR: c_int = 24; pub const SDL_GL_CONTEXT_RESET_NOTIFICATION: c_int = 25; pub const SDL_GL_CONTEXT_NO_ERROR: c_int = 26; pub const SDL_GLattr = c_uint; pub const SDL_GL_CONTEXT_PROFILE_CORE: c_int = 1; pub const SDL_GL_CONTEXT_PROFILE_COMPATIBILITY: c_int = 2; pub const SDL_GL_CONTEXT_PROFILE_ES: c_int = 4; pub const SDL_GLprofile = c_uint; pub const SDL_GL_CONTEXT_DEBUG_FLAG: c_int = 1; pub const SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG: c_int = 2; pub const SDL_GL_CONTEXT_ROBUST_ACCESS_FLAG: c_int = 4; pub const SDL_GL_CONTEXT_RESET_ISOLATION_FLAG: c_int = 8; pub const SDL_GLcontextFlag = c_uint; pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR_NONE: c_int = 0; pub const SDL_GL_CONTEXT_RELEASE_BEHAVIOR_FLUSH: c_int = 1; pub const SDL_GLcontextReleaseFlag = c_uint; pub const SDL_GL_CONTEXT_RESET_NO_NOTIFICATION: c_int = 0; pub const SDL_GL_CONTEXT_RESET_LOSE_CONTEXT: c_int = 1; pub const SDL_GLContextResetNotification = c_uint; pub extern fn SDL_GetNumVideoDrivers() c_int; pub extern fn SDL_GetVideoDriver(index: c_int) [*c]const u8; pub extern fn SDL_VideoInit(driver_name: [*c]const u8) c_int; pub extern fn SDL_VideoQuit() void; pub extern fn SDL_GetCurrentVideoDriver() [*c]const u8; pub extern fn SDL_GetNumVideoDisplays() c_int; pub extern fn SDL_GetDisplayName(displayIndex: c_int) [*c]const u8; pub extern fn SDL_GetDisplayBounds(displayIndex: c_int, rect: [*c]SDL_Rect) c_int; pub extern fn SDL_GetDisplayUsableBounds(displayIndex: c_int, rect: [*c]SDL_Rect) c_int; pub extern fn SDL_GetDisplayDPI(displayIndex: c_int, ddpi: [*c]f32, hdpi: [*c]f32, vdpi: [*c]f32) c_int; pub extern fn SDL_GetDisplayOrientation(displayIndex: c_int) SDL_DisplayOrientation; pub extern fn SDL_GetNumDisplayModes(displayIndex: c_int) c_int; pub extern fn SDL_GetDisplayMode(displayIndex: c_int, modeIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetDesktopDisplayMode(displayIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetCurrentDisplayMode(displayIndex: c_int, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetClosestDisplayMode(displayIndex: c_int, mode: [*c]const SDL_DisplayMode, closest: [*c]SDL_DisplayMode) [*c]SDL_DisplayMode; pub extern fn SDL_GetWindowDisplayIndex(window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowDisplayMode(window: ?*SDL_Window, mode: [*c]const SDL_DisplayMode) c_int; pub extern fn SDL_GetWindowDisplayMode(window: ?*SDL_Window, mode: [*c]SDL_DisplayMode) c_int; pub extern fn SDL_GetWindowPixelFormat(window: ?*SDL_Window) u32; pub extern fn SDL_CreateWindow(title: [*c]const u8, x: c_int, y: c_int, w: c_int, h: c_int, flags: u32) ?*SDL_Window; pub extern fn SDL_CreateWindowFrom(data: ?*const anyopaque) ?*SDL_Window; pub extern fn SDL_GetWindowID(window: ?*SDL_Window) u32; pub extern fn SDL_GetWindowFromID(id: u32) ?*SDL_Window; pub extern fn SDL_GetWindowFlags(window: ?*SDL_Window) u32; pub extern fn SDL_SetWindowTitle(window: ?*SDL_Window, title: [*c]const u8) void; pub extern fn SDL_GetWindowTitle(window: ?*SDL_Window) [*c]const u8; pub extern fn SDL_SetWindowIcon(window: ?*SDL_Window, icon: [*c]SDL_Surface) void; pub extern fn SDL_SetWindowData(window: ?*SDL_Window, name: [*c]const u8, userdata: ?*anyopaque) ?*anyopaque; pub extern fn SDL_GetWindowData(window: ?*SDL_Window, name: [*c]const u8) ?*anyopaque; pub extern fn SDL_SetWindowPosition(window: ?*SDL_Window, x: c_int, y: c_int) void; pub extern fn SDL_GetWindowPosition(window: ?*SDL_Window, x: [*c]c_int, y: [*c]c_int) void; pub extern fn SDL_SetWindowSize(window: ?*SDL_Window, w: c_int, h: c_int) void; pub extern fn SDL_GetWindowSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_GetWindowBordersSize(window: ?*SDL_Window, top: [*c]c_int, left: [*c]c_int, bottom: [*c]c_int, right: [*c]c_int) c_int; pub extern fn SDL_SetWindowMinimumSize(window: ?*SDL_Window, min_w: c_int, min_h: c_int) void; pub extern fn SDL_GetWindowMinimumSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_SetWindowMaximumSize(window: ?*SDL_Window, max_w: c_int, max_h: c_int) void; pub extern fn SDL_GetWindowMaximumSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_SetWindowBordered(window: ?*SDL_Window, bordered: SDL_bool) void; pub extern fn SDL_SetWindowResizable(window: ?*SDL_Window, resizable: SDL_bool) void; pub extern fn SDL_SetWindowAlwaysOnTop(window: ?*SDL_Window, on_top: SDL_bool) void; pub extern fn SDL_ShowWindow(window: ?*SDL_Window) void; pub extern fn SDL_HideWindow(window: ?*SDL_Window) void; pub extern fn SDL_RaiseWindow(window: ?*SDL_Window) void; pub extern fn SDL_MaximizeWindow(window: ?*SDL_Window) void; pub extern fn SDL_MinimizeWindow(window: ?*SDL_Window) void; pub extern fn SDL_RestoreWindow(window: ?*SDL_Window) void; pub extern fn SDL_SetWindowFullscreen(window: ?*SDL_Window, flags: u32) c_int; pub extern fn SDL_GetWindowSurface(window: ?*SDL_Window) [*c]SDL_Surface; pub extern fn SDL_UpdateWindowSurface(window: ?*SDL_Window) c_int; pub extern fn SDL_UpdateWindowSurfaceRects(window: ?*SDL_Window, rects: [*c]const SDL_Rect, numrects: c_int) c_int; pub extern fn SDL_SetWindowGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_SetWindowKeyboardGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_SetWindowMouseGrab(window: ?*SDL_Window, grabbed: SDL_bool) void; pub extern fn SDL_GetWindowGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetWindowKeyboardGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetWindowMouseGrab(window: ?*SDL_Window) SDL_bool; pub extern fn SDL_GetGrabbedWindow() ?*SDL_Window; pub extern fn SDL_SetWindowBrightness(window: ?*SDL_Window, brightness: f32) c_int; pub extern fn SDL_GetWindowBrightness(window: ?*SDL_Window) f32; pub extern fn SDL_SetWindowOpacity(window: ?*SDL_Window, opacity: f32) c_int; pub extern fn SDL_GetWindowOpacity(window: ?*SDL_Window, out_opacity: [*c]f32) c_int; pub extern fn SDL_SetWindowModalFor(modal_window: ?*SDL_Window, parent_window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowInputFocus(window: ?*SDL_Window) c_int; pub extern fn SDL_SetWindowGammaRamp(window: ?*SDL_Window, red: [*c]const u16, green: [*c]const u16, blue: [*c]const u16) c_int; pub extern fn SDL_GetWindowGammaRamp(window: ?*SDL_Window, red: [*c]u16, green: [*c]u16, blue: [*c]u16) c_int; pub const SDL_HITTEST_NORMAL: c_int = 0; pub const SDL_HITTEST_DRAGGABLE: c_int = 1; pub const SDL_HITTEST_RESIZE_TOPLEFT: c_int = 2; pub const SDL_HITTEST_RESIZE_TOP: c_int = 3; pub const SDL_HITTEST_RESIZE_TOPRIGHT: c_int = 4; pub const SDL_HITTEST_RESIZE_RIGHT: c_int = 5; pub const SDL_HITTEST_RESIZE_BOTTOMRIGHT: c_int = 6; pub const SDL_HITTEST_RESIZE_BOTTOM: c_int = 7; pub const SDL_HITTEST_RESIZE_BOTTOMLEFT: c_int = 8; pub const SDL_HITTEST_RESIZE_LEFT: c_int = 9; pub const SDL_HitTestResult = c_uint; pub const SDL_HitTest = ?fn (?*SDL_Window, [*c]const SDL_Point, ?*anyopaque) callconv(.C) SDL_HitTestResult; pub extern fn SDL_SetWindowHitTest(window: ?*SDL_Window, callback: SDL_HitTest, callback_data: ?*anyopaque) c_int; pub extern fn SDL_FlashWindow(window: ?*SDL_Window, operation: SDL_FlashOperation) c_int; pub extern fn SDL_DestroyWindow(window: ?*SDL_Window) void; pub extern fn SDL_IsScreenSaverEnabled() SDL_bool; pub extern fn SDL_EnableScreenSaver() void; pub extern fn SDL_DisableScreenSaver() void; pub extern fn SDL_GL_LoadLibrary(path: [*c]const u8) c_int; pub extern fn SDL_GL_GetProcAddress(proc: [*c]const u8) ?*anyopaque; pub extern fn SDL_GL_UnloadLibrary() void; pub extern fn SDL_GL_ExtensionSupported(extension: [*c]const u8) SDL_bool; pub extern fn SDL_GL_ResetAttributes() void; pub extern fn SDL_GL_SetAttribute(attr: SDL_GLattr, value: c_int) c_int; pub extern fn SDL_GL_GetAttribute(attr: SDL_GLattr, value: [*c]c_int) c_int; pub extern fn SDL_GL_CreateContext(window: ?*SDL_Window) SDL_GLContext; pub extern fn SDL_GL_MakeCurrent(window: ?*SDL_Window, context: SDL_GLContext) c_int; pub extern fn SDL_GL_GetCurrentWindow() ?*SDL_Window; pub extern fn SDL_GL_GetCurrentContext() SDL_GLContext; pub extern fn SDL_GL_GetDrawableSize(window: ?*SDL_Window, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_GL_SetSwapInterval(interval: c_int) c_int; pub extern fn SDL_GL_GetSwapInterval() c_int; pub extern fn SDL_GL_SwapWindow(window: ?*SDL_Window) void; pub extern fn SDL_GL_DeleteContext(context: SDL_GLContext) void; pub const SDL_TouchID = i64; pub const SDL_FingerID = i64; pub const SDL_TOUCH_DEVICE_INVALID: c_int = -1; pub const SDL_TOUCH_DEVICE_DIRECT: c_int = 0; pub const SDL_TOUCH_DEVICE_INDIRECT_ABSOLUTE: c_int = 1; pub const SDL_TOUCH_DEVICE_INDIRECT_RELATIVE: c_int = 2; pub const SDL_TouchDeviceType = c_int; pub const SDL_Finger = extern struct { id: SDL_FingerID, x: f32, y: f32, pressure: f32, }; pub extern fn SDL_GetNumTouchDevices() c_int; pub extern fn SDL_GetTouchDevice(index: c_int) SDL_TouchID; pub extern fn SDL_GetTouchDeviceType(touchID: SDL_TouchID) SDL_TouchDeviceType; pub extern fn SDL_GetNumTouchFingers(touchID: SDL_TouchID) c_int; pub extern fn SDL_GetTouchFinger(touchID: SDL_TouchID, index: c_int) [*c]SDL_Finger; pub const SDL_GestureID = i64; pub extern fn SDL_RecordGesture(touchId: SDL_TouchID) c_int; pub extern fn SDL_SaveAllDollarTemplates(dst: [*c]SDL_RWops) c_int; pub extern fn SDL_SaveDollarTemplate(gestureId: SDL_GestureID, dst: [*c]SDL_RWops) c_int; pub extern fn SDL_LoadDollarTemplates(touchId: SDL_TouchID, src: [*c]SDL_RWops) c_int; pub const SDL_MESSAGEBOX_ERROR: c_int = 16; pub const SDL_MESSAGEBOX_WARNING: c_int = 32; pub const SDL_MESSAGEBOX_INFORMATION: c_int = 64; pub const SDL_MESSAGEBOX_BUTTONS_LEFT_TO_RIGHT: c_int = 128; pub const SDL_MESSAGEBOX_BUTTONS_RIGHT_TO_LEFT: c_int = 256; pub const SDL_MessageBoxFlags = c_uint; pub const SDL_MESSAGEBOX_BUTTON_RETURNKEY_DEFAULT: c_int = 1; pub const SDL_MESSAGEBOX_BUTTON_ESCAPEKEY_DEFAULT: c_int = 2; pub const SDL_MessageBoxButtonFlags = c_uint; pub const SDL_MessageBoxButtonData = extern struct { flags: u32, buttonid: c_int, text: [*c]const u8, }; pub const SDL_MessageBoxColor = extern struct { r: u8, g: u8, b: u8, }; pub const SDL_MESSAGEBOX_COLOR_BACKGROUND: c_int = 0; pub const SDL_MESSAGEBOX_COLOR_TEXT: c_int = 1; pub const SDL_MESSAGEBOX_COLOR_BUTTON_BORDER: c_int = 2; pub const SDL_MESSAGEBOX_COLOR_BUTTON_BACKGROUND: c_int = 3; pub const SDL_MESSAGEBOX_COLOR_BUTTON_SELECTED: c_int = 4; pub const SDL_MESSAGEBOX_COLOR_MAX: c_int = 5; pub const SDL_MessageBoxColorType = c_uint; pub const SDL_MessageBoxColorScheme = extern struct { colors: [5]SDL_MessageBoxColor, }; pub const SDL_MessageBoxData = extern struct { flags: u32, window: ?*SDL_Window, title: [*c]const u8, message: [*c]const u8, numbuttons: c_int, buttons: [*c]const SDL_MessageBoxButtonData, colorScheme: [*c]const SDL_MessageBoxColorScheme, }; pub extern fn SDL_ShowMessageBox(messageboxdata: [*c]const SDL_MessageBoxData, buttonid: [*c]c_int) c_int; pub extern fn SDL_ShowSimpleMessageBox(flags: u32, title: [*c]const u8, message: [*c]const u8, window: ?*SDL_Window) c_int; pub extern fn SDL_OpenURL(url: [*c]const u8) c_int; pub extern fn SDL_GetBasePath() [*c]u8; pub extern fn SDL_GetPrefPath(org: [*c]const u8, app: [*c]const u8) [*c]u8; pub extern fn SDL_GetTicks() u32; pub extern fn SDL_GetTicks64() u64; pub extern fn SDL_GetPerformanceCounter() u64; pub extern fn SDL_GetPerformanceFrequency() u64; pub extern fn SDL_Delay(ms: u32) void; pub const SDL_TimerCallback = ?fn (u32, ?*anyopaque) callconv(.C) u32; pub const SDL_TimerID = c_int; pub extern fn SDL_AddTimer(interval: u32, callback: SDL_TimerCallback, param: ?*anyopaque) SDL_TimerID; pub extern fn SDL_RemoveTimer(id: SDL_TimerID) SDL_bool; pub const SDL_version = extern struct { major: u8, minor: u8, patch: u8, }; pub extern fn SDL_GetVersion(ver: [*c]SDL_version) void; pub extern fn SDL_GetRevision() [*c]const u8; pub extern fn SDL_CreateShapedWindow(title: [*c]const u8, x: c_uint, y: c_uint, w: c_uint, h: c_uint, flags: u32) ?*SDL_Window; pub extern fn SDL_IsShapedWindow(window: ?*const SDL_Window) SDL_bool; pub const ShapeModeDefault: c_int = 0; pub const ShapeModeBinarizeAlpha: c_int = 1; pub const ShapeModeReverseBinarizeAlpha: c_int = 2; pub const ShapeModeColorKey: c_int = 3; pub const WindowShapeMode = c_uint; pub const SDL_WindowShapeParams = extern union { binarizationCutoff: u8, colorKey: SDL_Color, }; pub const SDL_WindowShapeMode = extern struct { mode: WindowShapeMode, parameters: SDL_WindowShapeParams, }; pub extern fn SDL_SetWindowShape(window: ?*SDL_Window, shape: [*c]SDL_Surface, shape_mode: [*c]SDL_WindowShapeMode) c_int; pub extern fn SDL_GetShapedWindowMode(window: ?*SDL_Window, shape_mode: [*c]SDL_WindowShapeMode) c_int; pub const _SDL_Sensor = opaque {}; pub const SDL_Sensor = _SDL_Sensor; pub const SDL_SensorID = i32; pub const SDL_SENSOR_INVALID: c_int = -1; pub const SDL_SENSOR_UNKNOWN: c_int = 0; pub const SDL_SENSOR_ACCEL: c_int = 1; pub const SDL_SENSOR_GYRO: c_int = 2; pub const SDL_SensorType = c_int; pub extern fn SDL_LockSensors() void; pub extern fn SDL_UnlockSensors() void; pub extern fn SDL_NumSensors() c_int; pub extern fn SDL_SensorGetDeviceName(device_index: c_int) [*c]const u8; pub extern fn SDL_SensorGetDeviceType(device_index: c_int) SDL_SensorType; pub extern fn SDL_SensorGetDeviceNonPortableType(device_index: c_int) c_int; pub extern fn SDL_SensorGetDeviceInstanceID(device_index: c_int) SDL_SensorID; pub extern fn SDL_SensorOpen(device_index: c_int) ?*SDL_Sensor; pub extern fn SDL_SensorFromInstanceID(instance_id: SDL_SensorID) ?*SDL_Sensor; pub extern fn SDL_SensorGetName(sensor: ?*SDL_Sensor) [*c]const u8; pub extern fn SDL_SensorGetType(sensor: ?*SDL_Sensor) SDL_SensorType; pub extern fn SDL_SensorGetNonPortableType(sensor: ?*SDL_Sensor) c_int; pub extern fn SDL_SensorGetInstanceID(sensor: ?*SDL_Sensor) SDL_SensorID; pub extern fn SDL_SensorGetData(sensor: ?*SDL_Sensor, data: [*c]f32, num_values: c_int) c_int; pub extern fn SDL_SensorClose(sensor: ?*SDL_Sensor) void; pub extern fn SDL_SensorUpdate() void; pub const SDL_POWERSTATE_UNKNOWN: c_int = 0; pub const SDL_POWERSTATE_ON_BATTERY: c_int = 1; pub const SDL_POWERSTATE_NO_BATTERY: c_int = 2; pub const SDL_POWERSTATE_CHARGING: c_int = 3; pub const SDL_POWERSTATE_CHARGED: c_int = 4; pub const SDL_PowerState = c_uint; pub extern fn SDL_GetPowerInfo(secs: [*c]c_int, pct: [*c]c_int) SDL_PowerState; pub const SDL_SCANCODE_UNKNOWN: c_int = 0; pub const SDL_SCANCODE_A: c_int = 4; pub const SDL_SCANCODE_B: c_int = 5; pub const SDL_SCANCODE_C: c_int = 6; pub const SDL_SCANCODE_D: c_int = 7; pub const SDL_SCANCODE_E: c_int = 8; pub const SDL_SCANCODE_F: c_int = 9; pub const SDL_SCANCODE_G: c_int = 10; pub const SDL_SCANCODE_H: c_int = 11; pub const SDL_SCANCODE_I: c_int = 12; pub const SDL_SCANCODE_J: c_int = 13; pub const SDL_SCANCODE_K: c_int = 14; pub const SDL_SCANCODE_L: c_int = 15; pub const SDL_SCANCODE_M: c_int = 16; pub const SDL_SCANCODE_N: c_int = 17; pub const SDL_SCANCODE_O: c_int = 18; pub const SDL_SCANCODE_P: c_int = 19; pub const SDL_SCANCODE_Q: c_int = 20; pub const SDL_SCANCODE_R: c_int = 21; pub const SDL_SCANCODE_S: c_int = 22; pub const SDL_SCANCODE_T: c_int = 23; pub const SDL_SCANCODE_U: c_int = 24; pub const SDL_SCANCODE_V: c_int = 25; pub const SDL_SCANCODE_W: c_int = 26; pub const SDL_SCANCODE_X: c_int = 27; pub const SDL_SCANCODE_Y: c_int = 28; pub const SDL_SCANCODE_Z: c_int = 29; pub const SDL_SCANCODE_1: c_int = 30; pub const SDL_SCANCODE_2: c_int = 31; pub const SDL_SCANCODE_3: c_int = 32; pub const SDL_SCANCODE_4: c_int = 33; pub const SDL_SCANCODE_5: c_int = 34; pub const SDL_SCANCODE_6: c_int = 35; pub const SDL_SCANCODE_7: c_int = 36; pub const SDL_SCANCODE_8: c_int = 37; pub const SDL_SCANCODE_9: c_int = 38; pub const SDL_SCANCODE_0: c_int = 39; pub const SDL_SCANCODE_RETURN: c_int = 40; pub const SDL_SCANCODE_ESCAPE: c_int = 41; pub const SDL_SCANCODE_BACKSPACE: c_int = 42; pub const SDL_SCANCODE_TAB: c_int = 43; pub const SDL_SCANCODE_SPACE: c_int = 44; pub const SDL_SCANCODE_MINUS: c_int = 45; pub const SDL_SCANCODE_EQUALS: c_int = 46; pub const SDL_SCANCODE_LEFTBRACKET: c_int = 47; pub const SDL_SCANCODE_RIGHTBRACKET: c_int = 48; pub const SDL_SCANCODE_BACKSLASH: c_int = 49; pub const SDL_SCANCODE_NONUSHASH: c_int = 50; pub const SDL_SCANCODE_SEMICOLON: c_int = 51; pub const SDL_SCANCODE_APOSTROPHE: c_int = 52; pub const SDL_SCANCODE_GRAVE: c_int = 53; pub const SDL_SCANCODE_COMMA: c_int = 54; pub const SDL_SCANCODE_PERIOD: c_int = 55; pub const SDL_SCANCODE_SLASH: c_int = 56; pub const SDL_SCANCODE_CAPSLOCK: c_int = 57; pub const SDL_SCANCODE_F1: c_int = 58; pub const SDL_SCANCODE_F2: c_int = 59; pub const SDL_SCANCODE_F3: c_int = 60; pub const SDL_SCANCODE_F4: c_int = 61; pub const SDL_SCANCODE_F5: c_int = 62; pub const SDL_SCANCODE_F6: c_int = 63; pub const SDL_SCANCODE_F7: c_int = 64; pub const SDL_SCANCODE_F8: c_int = 65; pub const SDL_SCANCODE_F9: c_int = 66; pub const SDL_SCANCODE_F10: c_int = 67; pub const SDL_SCANCODE_F11: c_int = 68; pub const SDL_SCANCODE_F12: c_int = 69; pub const SDL_SCANCODE_PRINTSCREEN: c_int = 70; pub const SDL_SCANCODE_SCROLLLOCK: c_int = 71; pub const SDL_SCANCODE_PAUSE: c_int = 72; pub const SDL_SCANCODE_INSERT: c_int = 73; pub const SDL_SCANCODE_HOME: c_int = 74; pub const SDL_SCANCODE_PAGEUP: c_int = 75; pub const SDL_SCANCODE_DELETE: c_int = 76; pub const SDL_SCANCODE_END: c_int = 77; pub const SDL_SCANCODE_PAGEDOWN: c_int = 78; pub const SDL_SCANCODE_RIGHT: c_int = 79; pub const SDL_SCANCODE_LEFT: c_int = 80; pub const SDL_SCANCODE_DOWN: c_int = 81; pub const SDL_SCANCODE_UP: c_int = 82; pub const SDL_SCANCODE_NUMLOCKCLEAR: c_int = 83; pub const SDL_SCANCODE_KP_DIVIDE: c_int = 84; pub const SDL_SCANCODE_KP_MULTIPLY: c_int = 85; pub const SDL_SCANCODE_KP_MINUS: c_int = 86; pub const SDL_SCANCODE_KP_PLUS: c_int = 87; pub const SDL_SCANCODE_KP_ENTER: c_int = 88; pub const SDL_SCANCODE_KP_1: c_int = 89; pub const SDL_SCANCODE_KP_2: c_int = 90; pub const SDL_SCANCODE_KP_3: c_int = 91; pub const SDL_SCANCODE_KP_4: c_int = 92; pub const SDL_SCANCODE_KP_5: c_int = 93; pub const SDL_SCANCODE_KP_6: c_int = 94; pub const SDL_SCANCODE_KP_7: c_int = 95; pub const SDL_SCANCODE_KP_8: c_int = 96; pub const SDL_SCANCODE_KP_9: c_int = 97; pub const SDL_SCANCODE_KP_0: c_int = 98; pub const SDL_SCANCODE_KP_PERIOD: c_int = 99; pub const SDL_SCANCODE_NONUSBACKSLASH: c_int = 100; pub const SDL_SCANCODE_APPLICATION: c_int = 101; pub const SDL_SCANCODE_POWER: c_int = 102; pub const SDL_SCANCODE_KP_EQUALS: c_int = 103; pub const SDL_SCANCODE_F13: c_int = 104; pub const SDL_SCANCODE_F14: c_int = 105; pub const SDL_SCANCODE_F15: c_int = 106; pub const SDL_SCANCODE_F16: c_int = 107; pub const SDL_SCANCODE_F17: c_int = 108; pub const SDL_SCANCODE_F18: c_int = 109; pub const SDL_SCANCODE_F19: c_int = 110; pub const SDL_SCANCODE_F20: c_int = 111; pub const SDL_SCANCODE_F21: c_int = 112; pub const SDL_SCANCODE_F22: c_int = 113; pub const SDL_SCANCODE_F23: c_int = 114; pub const SDL_SCANCODE_F24: c_int = 115; pub const SDL_SCANCODE_EXECUTE: c_int = 116; pub const SDL_SCANCODE_HELP: c_int = 117; pub const SDL_SCANCODE_MENU: c_int = 118; pub const SDL_SCANCODE_SELECT: c_int = 119; pub const SDL_SCANCODE_STOP: c_int = 120; pub const SDL_SCANCODE_AGAIN: c_int = 121; pub const SDL_SCANCODE_UNDO: c_int = 122; pub const SDL_SCANCODE_CUT: c_int = 123; pub const SDL_SCANCODE_COPY: c_int = 124; pub const SDL_SCANCODE_PASTE: c_int = 125; pub const SDL_SCANCODE_FIND: c_int = 126; pub const SDL_SCANCODE_MUTE: c_int = 127; pub const SDL_SCANCODE_VOLUMEUP: c_int = 128; pub const SDL_SCANCODE_VOLUMEDOWN: c_int = 129; pub const SDL_SCANCODE_KP_COMMA: c_int = 133; pub const SDL_SCANCODE_KP_EQUALSAS400: c_int = 134; pub const SDL_SCANCODE_INTERNATIONAL1: c_int = 135; pub const SDL_SCANCODE_INTERNATIONAL2: c_int = 136; pub const SDL_SCANCODE_INTERNATIONAL3: c_int = 137; pub const SDL_SCANCODE_INTERNATIONAL4: c_int = 138; pub const SDL_SCANCODE_INTERNATIONAL5: c_int = 139; pub const SDL_SCANCODE_INTERNATIONAL6: c_int = 140; pub const SDL_SCANCODE_INTERNATIONAL7: c_int = 141; pub const SDL_SCANCODE_INTERNATIONAL8: c_int = 142; pub const SDL_SCANCODE_INTERNATIONAL9: c_int = 143; pub const SDL_SCANCODE_LANG1: c_int = 144; pub const SDL_SCANCODE_LANG2: c_int = 145; pub const SDL_SCANCODE_LANG3: c_int = 146; pub const SDL_SCANCODE_LANG4: c_int = 147; pub const SDL_SCANCODE_LANG5: c_int = 148; pub const SDL_SCANCODE_LANG6: c_int = 149; pub const SDL_SCANCODE_LANG7: c_int = 150; pub const SDL_SCANCODE_LANG8: c_int = 151; pub const SDL_SCANCODE_LANG9: c_int = 152; pub const SDL_SCANCODE_ALTERASE: c_int = 153; pub const SDL_SCANCODE_SYSREQ: c_int = 154; pub const SDL_SCANCODE_CANCEL: c_int = 155; pub const SDL_SCANCODE_CLEAR: c_int = 156; pub const SDL_SCANCODE_PRIOR: c_int = 157; pub const SDL_SCANCODE_RETURN2: c_int = 158; pub const SDL_SCANCODE_SEPARATOR: c_int = 159; pub const SDL_SCANCODE_OUT: c_int = 160; pub const SDL_SCANCODE_OPER: c_int = 161; pub const SDL_SCANCODE_CLEARAGAIN: c_int = 162; pub const SDL_SCANCODE_CRSEL: c_int = 163; pub const SDL_SCANCODE_EXSEL: c_int = 164; pub const SDL_SCANCODE_KP_00: c_int = 176; pub const SDL_SCANCODE_KP_000: c_int = 177; pub const SDL_SCANCODE_THOUSANDSSEPARATOR: c_int = 178; pub const SDL_SCANCODE_DECIMALSEPARATOR: c_int = 179; pub const SDL_SCANCODE_CURRENCYUNIT: c_int = 180; pub const SDL_SCANCODE_CURRENCYSUBUNIT: c_int = 181; pub const SDL_SCANCODE_KP_LEFTPAREN: c_int = 182; pub const SDL_SCANCODE_KP_RIGHTPAREN: c_int = 183; pub const SDL_SCANCODE_KP_LEFTBRACE: c_int = 184; pub const SDL_SCANCODE_KP_RIGHTBRACE: c_int = 185; pub const SDL_SCANCODE_KP_TAB: c_int = 186; pub const SDL_SCANCODE_KP_BACKSPACE: c_int = 187; pub const SDL_SCANCODE_KP_A: c_int = 188; pub const SDL_SCANCODE_KP_B: c_int = 189; pub const SDL_SCANCODE_KP_C: c_int = 190; pub const SDL_SCANCODE_KP_D: c_int = 191; pub const SDL_SCANCODE_KP_E: c_int = 192; pub const SDL_SCANCODE_KP_F: c_int = 193; pub const SDL_SCANCODE_KP_XOR: c_int = 194; pub const SDL_SCANCODE_KP_POWER: c_int = 195; pub const SDL_SCANCODE_KP_PERCENT: c_int = 196; pub const SDL_SCANCODE_KP_LESS: c_int = 197; pub const SDL_SCANCODE_KP_GREATER: c_int = 198; pub const SDL_SCANCODE_KP_AMPERSAND: c_int = 199; pub const SDL_SCANCODE_KP_DBLAMPERSAND: c_int = 200; pub const SDL_SCANCODE_KP_VERTICALBAR: c_int = 201; pub const SDL_SCANCODE_KP_DBLVERTICALBAR: c_int = 202; pub const SDL_SCANCODE_KP_COLON: c_int = 203; pub const SDL_SCANCODE_KP_HASH: c_int = 204; pub const SDL_SCANCODE_KP_SPACE: c_int = 205; pub const SDL_SCANCODE_KP_AT: c_int = 206; pub const SDL_SCANCODE_KP_EXCLAM: c_int = 207; pub const SDL_SCANCODE_KP_MEMSTORE: c_int = 208; pub const SDL_SCANCODE_KP_MEMRECALL: c_int = 209; pub const SDL_SCANCODE_KP_MEMCLEAR: c_int = 210; pub const SDL_SCANCODE_KP_MEMADD: c_int = 211; pub const SDL_SCANCODE_KP_MEMSUBTRACT: c_int = 212; pub const SDL_SCANCODE_KP_MEMMULTIPLY: c_int = 213; pub const SDL_SCANCODE_KP_MEMDIVIDE: c_int = 214; pub const SDL_SCANCODE_KP_PLUSMINUS: c_int = 215; pub const SDL_SCANCODE_KP_CLEAR: c_int = 216; pub const SDL_SCANCODE_KP_CLEARENTRY: c_int = 217; pub const SDL_SCANCODE_KP_BINARY: c_int = 218; pub const SDL_SCANCODE_KP_OCTAL: c_int = 219; pub const SDL_SCANCODE_KP_DECIMAL: c_int = 220; pub const SDL_SCANCODE_KP_HEXADECIMAL: c_int = 221; pub const SDL_SCANCODE_LCTRL: c_int = 224; pub const SDL_SCANCODE_LSHIFT: c_int = 225; pub const SDL_SCANCODE_LALT: c_int = 226; pub const SDL_SCANCODE_LGUI: c_int = 227; pub const SDL_SCANCODE_RCTRL: c_int = 228; pub const SDL_SCANCODE_RSHIFT: c_int = 229; pub const SDL_SCANCODE_RALT: c_int = 230; pub const SDL_SCANCODE_RGUI: c_int = 231; pub const SDL_SCANCODE_MODE: c_int = 257; pub const SDL_SCANCODE_AUDIONEXT: c_int = 258; pub const SDL_SCANCODE_AUDIOPREV: c_int = 259; pub const SDL_SCANCODE_AUDIOSTOP: c_int = 260; pub const SDL_SCANCODE_AUDIOPLAY: c_int = 261; pub const SDL_SCANCODE_AUDIOMUTE: c_int = 262; pub const SDL_SCANCODE_MEDIASELECT: c_int = 263; pub const SDL_SCANCODE_WWW: c_int = 264; pub const SDL_SCANCODE_MAIL: c_int = 265; pub const SDL_SCANCODE_CALCULATOR: c_int = 266; pub const SDL_SCANCODE_COMPUTER: c_int = 267; pub const SDL_SCANCODE_AC_SEARCH: c_int = 268; pub const SDL_SCANCODE_AC_HOME: c_int = 269; pub const SDL_SCANCODE_AC_BACK: c_int = 270; pub const SDL_SCANCODE_AC_FORWARD: c_int = 271; pub const SDL_SCANCODE_AC_STOP: c_int = 272; pub const SDL_SCANCODE_AC_REFRESH: c_int = 273; pub const SDL_SCANCODE_AC_BOOKMARKS: c_int = 274; pub const SDL_SCANCODE_BRIGHTNESSDOWN: c_int = 275; pub const SDL_SCANCODE_BRIGHTNESSUP: c_int = 276; pub const SDL_SCANCODE_DISPLAYSWITCH: c_int = 277; pub const SDL_SCANCODE_KBDILLUMTOGGLE: c_int = 278; pub const SDL_SCANCODE_KBDILLUMDOWN: c_int = 279; pub const SDL_SCANCODE_KBDILLUMUP: c_int = 280; pub const SDL_SCANCODE_EJECT: c_int = 281; pub const SDL_SCANCODE_SLEEP: c_int = 282; pub const SDL_SCANCODE_APP1: c_int = 283; pub const SDL_SCANCODE_APP2: c_int = 284; pub const SDL_SCANCODE_AUDIOREWIND: c_int = 285; pub const SDL_SCANCODE_AUDIOFASTFORWARD: c_int = 286; pub const SDL_NUM_SCANCODES: c_int = 512; pub const SDL_Scancode = c_uint; pub const SDL_Keycode = i32; pub const SDLK_UNKNOWN: c_int = 0; pub const SDLK_RETURN: c_int = 13; pub const SDLK_ESCAPE: c_int = 27; pub const SDLK_BACKSPACE: c_int = 8; pub const SDLK_TAB: c_int = 9; pub const SDLK_SPACE: c_int = 32; pub const SDLK_EXCLAIM: c_int = 33; pub const SDLK_QUOTEDBL: c_int = 34; pub const SDLK_HASH: c_int = 35; pub const SDLK_PERCENT: c_int = 37; pub const SDLK_DOLLAR: c_int = 36; pub const SDLK_AMPERSAND: c_int = 38; pub const SDLK_QUOTE: c_int = 39; pub const SDLK_LEFTPAREN: c_int = 40; pub const SDLK_RIGHTPAREN: c_int = 41; pub const SDLK_ASTERISK: c_int = 42; pub const SDLK_PLUS: c_int = 43; pub const SDLK_COMMA: c_int = 44; pub const SDLK_MINUS: c_int = 45; pub const SDLK_PERIOD: c_int = 46; pub const SDLK_SLASH: c_int = 47; pub const SDLK_0: c_int = 48; pub const SDLK_1: c_int = 49; pub const SDLK_2: c_int = 50; pub const SDLK_3: c_int = 51; pub const SDLK_4: c_int = 52; pub const SDLK_5: c_int = 53; pub const SDLK_6: c_int = 54; pub const SDLK_7: c_int = 55; pub const SDLK_8: c_int = 56; pub const SDLK_9: c_int = 57; pub const SDLK_COLON: c_int = 58; pub const SDLK_SEMICOLON: c_int = 59; pub const SDLK_LESS: c_int = 60; pub const SDLK_EQUALS: c_int = 61; pub const SDLK_GREATER: c_int = 62; pub const SDLK_QUESTION: c_int = 63; pub const SDLK_AT: c_int = 64; pub const SDLK_LEFTBRACKET: c_int = 91; pub const SDLK_BACKSLASH: c_int = 92; pub const SDLK_RIGHTBRACKET: c_int = 93; pub const SDLK_CARET: c_int = 94; pub const SDLK_UNDERSCORE: c_int = 95; pub const SDLK_BACKQUOTE: c_int = 96; pub const SDLK_a: c_int = 97; pub const SDLK_b: c_int = 98; pub const SDLK_c: c_int = 99; pub const SDLK_d: c_int = 100; pub const SDLK_e: c_int = 101; pub const SDLK_f: c_int = 102; pub const SDLK_g: c_int = 103; pub const SDLK_h: c_int = 104; pub const SDLK_i: c_int = 105; pub const SDLK_j: c_int = 106; pub const SDLK_k: c_int = 107; pub const SDLK_l: c_int = 108; pub const SDLK_m: c_int = 109; pub const SDLK_n: c_int = 110; pub const SDLK_o: c_int = 111; pub const SDLK_p: c_int = 112; pub const SDLK_q: c_int = 113; pub const SDLK_r: c_int = 114; pub const SDLK_s: c_int = 115; pub const SDLK_t: c_int = 116; pub const SDLK_u: c_int = 117; pub const SDLK_v: c_int = 118; pub const SDLK_w: c_int = 119; pub const SDLK_x: c_int = 120; pub const SDLK_y: c_int = 121; pub const SDLK_z: c_int = 122; pub const SDLK_CAPSLOCK: c_int = 1073741881; pub const SDLK_F1: c_int = 1073741882; pub const SDLK_F2: c_int = 1073741883; pub const SDLK_F3: c_int = 1073741884; pub const SDLK_F4: c_int = 1073741885; pub const SDLK_F5: c_int = 1073741886; pub const SDLK_F6: c_int = 1073741887; pub const SDLK_F7: c_int = 1073741888; pub const SDLK_F8: c_int = 1073741889; pub const SDLK_F9: c_int = 1073741890; pub const SDLK_F10: c_int = 1073741891; pub const SDLK_F11: c_int = 1073741892; pub const SDLK_F12: c_int = 1073741893; pub const SDLK_PRINTSCREEN: c_int = 1073741894; pub const SDLK_SCROLLLOCK: c_int = 1073741895; pub const SDLK_PAUSE: c_int = 1073741896; pub const SDLK_INSERT: c_int = 1073741897; pub const SDLK_HOME: c_int = 1073741898; pub const SDLK_PAGEUP: c_int = 1073741899; pub const SDLK_DELETE: c_int = 127; pub const SDLK_END: c_int = 1073741901; pub const SDLK_PAGEDOWN: c_int = 1073741902; pub const SDLK_RIGHT: c_int = 1073741903; pub const SDLK_LEFT: c_int = 1073741904; pub const SDLK_DOWN: c_int = 1073741905; pub const SDLK_UP: c_int = 1073741906; pub const SDLK_NUMLOCKCLEAR: c_int = 1073741907; pub const SDLK_KP_DIVIDE: c_int = 1073741908; pub const SDLK_KP_MULTIPLY: c_int = 1073741909; pub const SDLK_KP_MINUS: c_int = 1073741910; pub const SDLK_KP_PLUS: c_int = 1073741911; pub const SDLK_KP_ENTER: c_int = 1073741912; pub const SDLK_KP_1: c_int = 1073741913; pub const SDLK_KP_2: c_int = 1073741914; pub const SDLK_KP_3: c_int = 1073741915; pub const SDLK_KP_4: c_int = 1073741916; pub const SDLK_KP_5: c_int = 1073741917; pub const SDLK_KP_6: c_int = 1073741918; pub const SDLK_KP_7: c_int = 1073741919; pub const SDLK_KP_8: c_int = 1073741920; pub const SDLK_KP_9: c_int = 1073741921; pub const SDLK_KP_0: c_int = 1073741922; pub const SDLK_KP_PERIOD: c_int = 1073741923; pub const SDLK_APPLICATION: c_int = 1073741925; pub const SDLK_POWER: c_int = 1073741926; pub const SDLK_KP_EQUALS: c_int = 1073741927; pub const SDLK_F13: c_int = 1073741928; pub const SDLK_F14: c_int = 1073741929; pub const SDLK_F15: c_int = 1073741930; pub const SDLK_F16: c_int = 1073741931; pub const SDLK_F17: c_int = 1073741932; pub const SDLK_F18: c_int = 1073741933; pub const SDLK_F19: c_int = 1073741934; pub const SDLK_F20: c_int = 1073741935; pub const SDLK_F21: c_int = 1073741936; pub const SDLK_F22: c_int = 1073741937; pub const SDLK_F23: c_int = 1073741938; pub const SDLK_F24: c_int = 1073741939; pub const SDLK_EXECUTE: c_int = 1073741940; pub const SDLK_HELP: c_int = 1073741941; pub const SDLK_MENU: c_int = 1073741942; pub const SDLK_SELECT: c_int = 1073741943; pub const SDLK_STOP: c_int = 1073741944; pub const SDLK_AGAIN: c_int = 1073741945; pub const SDLK_UNDO: c_int = 1073741946; pub const SDLK_CUT: c_int = 1073741947; pub const SDLK_COPY: c_int = 1073741948; pub const SDLK_PASTE: c_int = 1073741949; pub const SDLK_FIND: c_int = 1073741950; pub const SDLK_MUTE: c_int = 1073741951; pub const SDLK_VOLUMEUP: c_int = 1073741952; pub const SDLK_VOLUMEDOWN: c_int = 1073741953; pub const SDLK_KP_COMMA: c_int = 1073741957; pub const SDLK_KP_EQUALSAS400: c_int = 1073741958; pub const SDLK_ALTERASE: c_int = 1073741977; pub const SDLK_SYSREQ: c_int = 1073741978; pub const SDLK_CANCEL: c_int = 1073741979; pub const SDLK_CLEAR: c_int = 1073741980; pub const SDLK_PRIOR: c_int = 1073741981; pub const SDLK_RETURN2: c_int = 1073741982; pub const SDLK_SEPARATOR: c_int = 1073741983; pub const SDLK_OUT: c_int = 1073741984; pub const SDLK_OPER: c_int = 1073741985; pub const SDLK_CLEARAGAIN: c_int = 1073741986; pub const SDLK_CRSEL: c_int = 1073741987; pub const SDLK_EXSEL: c_int = 1073741988; pub const SDLK_KP_00: c_int = 1073742000; pub const SDLK_KP_000: c_int = 1073742001; pub const SDLK_THOUSANDSSEPARATOR: c_int = 1073742002; pub const SDLK_DECIMALSEPARATOR: c_int = 1073742003; pub const SDLK_CURRENCYUNIT: c_int = 1073742004; pub const SDLK_CURRENCYSUBUNIT: c_int = 1073742005; pub const SDLK_KP_LEFTPAREN: c_int = 1073742006; pub const SDLK_KP_RIGHTPAREN: c_int = 1073742007; pub const SDLK_KP_LEFTBRACE: c_int = 1073742008; pub const SDLK_KP_RIGHTBRACE: c_int = 1073742009; pub const SDLK_KP_TAB: c_int = 1073742010; pub const SDLK_KP_BACKSPACE: c_int = 1073742011; pub const SDLK_KP_A: c_int = 1073742012; pub const SDLK_KP_B: c_int = 1073742013; pub const SDLK_KP_C: c_int = 1073742014; pub const SDLK_KP_D: c_int = 1073742015; pub const SDLK_KP_E: c_int = 1073742016; pub const SDLK_KP_F: c_int = 1073742017; pub const SDLK_KP_XOR: c_int = 1073742018; pub const SDLK_KP_POWER: c_int = 1073742019; pub const SDLK_KP_PERCENT: c_int = 1073742020; pub const SDLK_KP_LESS: c_int = 1073742021; pub const SDLK_KP_GREATER: c_int = 1073742022; pub const SDLK_KP_AMPERSAND: c_int = 1073742023; pub const SDLK_KP_DBLAMPERSAND: c_int = 1073742024; pub const SDLK_KP_VERTICALBAR: c_int = 1073742025; pub const SDLK_KP_DBLVERTICALBAR: c_int = 1073742026; pub const SDLK_KP_COLON: c_int = 1073742027; pub const SDLK_KP_HASH: c_int = 1073742028; pub const SDLK_KP_SPACE: c_int = 1073742029; pub const SDLK_KP_AT: c_int = 1073742030; pub const SDLK_KP_EXCLAM: c_int = 1073742031; pub const SDLK_KP_MEMSTORE: c_int = 1073742032; pub const SDLK_KP_MEMRECALL: c_int = 1073742033; pub const SDLK_KP_MEMCLEAR: c_int = 1073742034; pub const SDLK_KP_MEMADD: c_int = 1073742035; pub const SDLK_KP_MEMSUBTRACT: c_int = 1073742036; pub const SDLK_KP_MEMMULTIPLY: c_int = 1073742037; pub const SDLK_KP_MEMDIVIDE: c_int = 1073742038; pub const SDLK_KP_PLUSMINUS: c_int = 1073742039; pub const SDLK_KP_CLEAR: c_int = 1073742040; pub const SDLK_KP_CLEARENTRY: c_int = 1073742041; pub const SDLK_KP_BINARY: c_int = 1073742042; pub const SDLK_KP_OCTAL: c_int = 1073742043; pub const SDLK_KP_DECIMAL: c_int = 1073742044; pub const SDLK_KP_HEXADECIMAL: c_int = 1073742045; pub const SDLK_LCTRL: c_int = 1073742048; pub const SDLK_LSHIFT: c_int = 1073742049; pub const SDLK_LALT: c_int = 1073742050; pub const SDLK_LGUI: c_int = 1073742051; pub const SDLK_RCTRL: c_int = 1073742052; pub const SDLK_RSHIFT: c_int = 1073742053; pub const SDLK_RALT: c_int = 1073742054; pub const SDLK_RGUI: c_int = 1073742055; pub const SDLK_MODE: c_int = 1073742081; pub const SDLK_AUDIONEXT: c_int = 1073742082; pub const SDLK_AUDIOPREV: c_int = 1073742083; pub const SDLK_AUDIOSTOP: c_int = 1073742084; pub const SDLK_AUDIOPLAY: c_int = 1073742085; pub const SDLK_AUDIOMUTE: c_int = 1073742086; pub const SDLK_MEDIASELECT: c_int = 1073742087; pub const SDLK_WWW: c_int = 1073742088; pub const SDLK_MAIL: c_int = 1073742089; pub const SDLK_CALCULATOR: c_int = 1073742090; pub const SDLK_COMPUTER: c_int = 1073742091; pub const SDLK_AC_SEARCH: c_int = 1073742092; pub const SDLK_AC_HOME: c_int = 1073742093; pub const SDLK_AC_BACK: c_int = 1073742094; pub const SDLK_AC_FORWARD: c_int = 1073742095; pub const SDLK_AC_STOP: c_int = 1073742096; pub const SDLK_AC_REFRESH: c_int = 1073742097; pub const SDLK_AC_BOOKMARKS: c_int = 1073742098; pub const SDLK_BRIGHTNESSDOWN: c_int = 1073742099; pub const SDLK_BRIGHTNESSUP: c_int = 1073742100; pub const SDLK_DISPLAYSWITCH: c_int = 1073742101; pub const SDLK_KBDILLUMTOGGLE: c_int = 1073742102; pub const SDLK_KBDILLUMDOWN: c_int = 1073742103; pub const SDLK_KBDILLUMUP: c_int = 1073742104; pub const SDLK_EJECT: c_int = 1073742105; pub const SDLK_SLEEP: c_int = 1073742106; pub const SDLK_APP1: c_int = 1073742107; pub const SDLK_APP2: c_int = 1073742108; pub const SDLK_AUDIOREWIND: c_int = 1073742109; pub const SDLK_AUDIOFASTFORWARD: c_int = 1073742110; pub const SDL_KeyCode = c_uint; pub const KMOD_NONE: c_int = 0; pub const KMOD_LSHIFT: c_int = 1; pub const KMOD_RSHIFT: c_int = 2; pub const KMOD_LCTRL: c_int = 64; pub const KMOD_RCTRL: c_int = 128; pub const KMOD_LALT: c_int = 256; pub const KMOD_RALT: c_int = 512; pub const KMOD_LGUI: c_int = 1024; pub const KMOD_RGUI: c_int = 2048; pub const KMOD_NUM: c_int = 4096; pub const KMOD_CAPS: c_int = 8192; pub const KMOD_MODE: c_int = 16384; pub const KMOD_SCROLL: c_int = 32768; pub const KMOD_CTRL: c_int = 192; pub const KMOD_SHIFT: c_int = 3; pub const KMOD_ALT: c_int = 768; pub const KMOD_GUI: c_int = 3072; pub const SDL_Keymod = c_uint; pub extern fn SDL_SetError(fmt: [*c]const u8, ...) c_int; pub extern fn SDL_GetError() [*c]const u8; pub extern fn SDL_GetErrorMsg(errstr: [*c]u8, maxlen: c_int) [*c]u8; pub extern fn SDL_ClearError() void; pub const SDL_ENOMEM: c_int = 0; pub const SDL_EFREAD: c_int = 1; pub const SDL_EFWRITE: c_int = 2; pub const SDL_EFSEEK: c_int = 3; pub const SDL_UNSUPPORTED: c_int = 4; pub const SDL_LASTERROR: c_int = 5; pub const SDL_errorcode = c_uint; pub extern fn SDL_Error(code: SDL_errorcode) c_int; pub const SDL_RENDERER_SOFTWARE: c_int = 1; pub const SDL_RENDERER_ACCELERATED: c_int = 2; pub const SDL_RENDERER_PRESENTVSYNC: c_int = 4; pub const SDL_RENDERER_TARGETTEXTURE: c_int = 8; pub const SDL_RendererFlags = c_uint; pub const SDL_RendererInfo = extern struct { name: [*c]const u8, flags: u32, num_texture_formats: u32, texture_formats: [16]u32, max_texture_width: c_int, max_texture_height: c_int, }; pub const SDL_ScaleModeNearest: c_int = 0; pub const SDL_ScaleModeLinear: c_int = 1; pub const SDL_ScaleModeBest: c_int = 2; pub const SDL_ScaleMode = c_uint; pub const SDL_TEXTUREACCESS_STATIC: c_int = 0; pub const SDL_TEXTUREACCESS_STREAMING: c_int = 1; pub const SDL_TEXTUREACCESS_TARGET: c_int = 2; pub const SDL_TextureAccess = c_uint; pub const SDL_TEXTUREMODULATE_NONE: c_int = 0; pub const SDL_TEXTUREMODULATE_COLOR: c_int = 1; pub const SDL_TEXTUREMODULATE_ALPHA: c_int = 2; pub const SDL_TextureModulate = c_uint; pub const SDL_FLIP_NONE: c_int = 0; pub const SDL_FLIP_HORIZONTAL: c_int = 1; pub const SDL_FLIP_VERTICAL: c_int = 2; pub const SDL_RendererFlip = c_uint; pub const SDL_Renderer = opaque {}; pub const SDL_Texture = opaque {}; pub const SDL_Vertex = extern struct { position: SDL_FPoint, color: SDL_Color, tex_coord: SDL_FPoint = undefined, }; pub extern fn SDL_GetNumRenderDrivers() c_int; pub extern fn SDL_GetRenderDriverInfo(index: c_int, info: [*c]SDL_RendererInfo) c_int; pub extern fn SDL_CreateWindowAndRenderer(width: c_int, height: c_int, window_flags: u32, window: [*c]?*SDL_Window, renderer: [*c]?*SDL_Renderer) c_int; pub extern fn SDL_CreateRenderer(window: ?*SDL_Window, index: c_int, flags: u32) ?*SDL_Renderer; pub extern fn SDL_CreateSoftwareRenderer(surface: [*c]SDL_Surface) ?*SDL_Renderer; pub extern fn SDL_GetRenderer(window: ?*SDL_Window) ?*SDL_Renderer; pub extern fn SDL_GetRendererInfo(renderer: ?*SDL_Renderer, info: [*c]SDL_RendererInfo) c_int; pub extern fn SDL_GetRendererOutputSize(renderer: ?*SDL_Renderer, w: [*c]c_int, h: [*c]c_int) c_int; pub extern fn SDL_CreateTexture(renderer: ?*SDL_Renderer, format: u32, access: c_int, w: c_int, h: c_int) ?*SDL_Texture; pub extern fn SDL_CreateTextureFromSurface(renderer: ?*SDL_Renderer, surface: [*c]SDL_Surface) ?*SDL_Texture; pub extern fn SDL_QueryTexture(texture: ?*SDL_Texture, format: [*c]u32, access: [*c]c_int, w: [*c]c_int, h: [*c]c_int) c_int; pub extern fn SDL_SetTextureColorMod(texture: ?*SDL_Texture, r: u8, g: u8, b: u8) c_int; pub extern fn SDL_GetTextureColorMod(texture: ?*SDL_Texture, r: [*c]u8, g: [*c]u8, b: [*c]u8) c_int; pub extern fn SDL_SetTextureAlphaMod(texture: ?*SDL_Texture, alpha: u8) c_int; pub extern fn SDL_GetTextureAlphaMod(texture: ?*SDL_Texture, alpha: [*c]u8) c_int; pub extern fn SDL_SetTextureBlendMode(texture: ?*SDL_Texture, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetTextureBlendMode(texture: ?*SDL_Texture, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_SetTextureScaleMode(texture: ?*SDL_Texture, scaleMode: SDL_ScaleMode) c_int; pub extern fn SDL_GetTextureScaleMode(texture: ?*SDL_Texture, scaleMode: [*c]SDL_ScaleMode) c_int; pub extern fn SDL_SetTextureUserData(texture: ?*SDL_Texture, userdata: ?*anyopaque) c_int; pub extern fn SDL_GetTextureUserData(texture: ?*SDL_Texture) ?*anyopaque; pub extern fn SDL_UpdateTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, pixels: ?*const anyopaque, pitch: c_int) c_int; pub extern fn SDL_UpdateYUVTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, Yplane: [*c]const u8, Ypitch: c_int, Uplane: [*c]const u8, Upitch: c_int, Vplane: [*c]const u8, Vpitch: c_int) c_int; pub extern fn SDL_UpdateNVTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, Yplane: [*c]const u8, Ypitch: c_int, UVplane: [*c]const u8, UVpitch: c_int) c_int; pub extern fn SDL_LockTexture(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, pixels: [*c]?*anyopaque, pitch: [*c]c_int) c_int; pub extern fn SDL_LockTextureToSurface(texture: ?*SDL_Texture, rect: [*c]const SDL_Rect, surface: [*c][*c]SDL_Surface) c_int; pub extern fn SDL_UnlockTexture(texture: ?*SDL_Texture) void; pub extern fn SDL_RenderTargetSupported(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_SetRenderTarget(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture) c_int; pub extern fn SDL_GetRenderTarget(renderer: ?*SDL_Renderer) ?*SDL_Texture; pub extern fn SDL_RenderSetLogicalSize(renderer: ?*SDL_Renderer, w: c_int, h: c_int) c_int; pub extern fn SDL_RenderGetLogicalSize(renderer: ?*SDL_Renderer, w: [*c]c_int, h: [*c]c_int) void; pub extern fn SDL_RenderSetIntegerScale(renderer: ?*SDL_Renderer, enable: SDL_bool) c_int; pub extern fn SDL_RenderGetIntegerScale(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_RenderSetViewport(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderGetViewport(renderer: ?*SDL_Renderer, rect: [*c]SDL_Rect) void; pub extern fn SDL_RenderSetClipRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderGetClipRect(renderer: ?*SDL_Renderer, rect: [*c]SDL_Rect) void; pub extern fn SDL_RenderIsClipEnabled(renderer: ?*SDL_Renderer) SDL_bool; pub extern fn SDL_RenderSetScale(renderer: ?*SDL_Renderer, scaleX: f32, scaleY: f32) c_int; pub extern fn SDL_RenderGetScale(renderer: ?*SDL_Renderer, scaleX: [*c]f32, scaleY: [*c]f32) void; pub extern fn SDL_SetRenderDrawColor(renderer: ?*SDL_Renderer, r: u8, g: u8, b: u8, a: u8) c_int; pub extern fn SDL_GetRenderDrawColor(renderer: ?*SDL_Renderer, r: [*c]u8, g: [*c]u8, b: [*c]u8, a: [*c]u8) c_int; pub extern fn SDL_SetRenderDrawBlendMode(renderer: ?*SDL_Renderer, blendMode: SDL_BlendMode) c_int; pub extern fn SDL_GetRenderDrawBlendMode(renderer: ?*SDL_Renderer, blendMode: [*c]SDL_BlendMode) c_int; pub extern fn SDL_RenderClear(renderer: ?*SDL_Renderer) c_int; pub extern fn SDL_RenderDrawPoint(renderer: ?*SDL_Renderer, x: c_int, y: c_int) c_int; pub extern fn SDL_RenderDrawPoints(renderer: ?*SDL_Renderer, points: [*c]const SDL_Point, count: c_int) c_int; pub extern fn SDL_RenderDrawLine(renderer: ?*SDL_Renderer, x1: c_int, y1: c_int, x2: c_int, y2: c_int) c_int; pub extern fn SDL_RenderDrawLines(renderer: ?*SDL_Renderer, points: [*c]const SDL_Point, count: c_int) c_int; pub extern fn SDL_RenderDrawRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderDrawRects(renderer: ?*SDL_Renderer, rects: [*c]const SDL_Rect, count: c_int) c_int; pub extern fn SDL_RenderFillRect(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderFillRects(renderer: ?*SDL_Renderer, rects: [*c]const SDL_Rect, count: c_int) c_int; pub extern fn SDL_RenderCopy(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_Rect) c_int; pub extern fn SDL_RenderCopyEx(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_Rect, angle: f64, center: [*c]const SDL_Point, flip: SDL_RendererFlip) c_int; pub extern fn SDL_RenderDrawPointF(renderer: ?*SDL_Renderer, x: f32, y: f32) c_int; pub extern fn SDL_RenderDrawPointsF(renderer: ?*SDL_Renderer, points: [*c]const SDL_FPoint, count: c_int) c_int; pub extern fn SDL_RenderDrawLineF(renderer: ?*SDL_Renderer, x1: f32, y1: f32, x2: f32, y2: f32) c_int; pub extern fn SDL_RenderDrawLinesF(renderer: ?*SDL_Renderer, points: [*c]const SDL_FPoint, count: c_int) c_int; pub extern fn SDL_RenderDrawRectF(renderer: ?*SDL_Renderer, rect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderDrawRectsF(renderer: ?*SDL_Renderer, rects: [*c]const SDL_FRect, count: c_int) c_int; pub extern fn SDL_RenderFillRectF(renderer: ?*SDL_Renderer, rect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderFillRectsF(renderer: ?*SDL_Renderer, rects: [*c]const SDL_FRect, count: c_int) c_int; pub extern fn SDL_RenderGeometry(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, vertices: [*c]const SDL_Vertex, num_vertices: c_int, indices: [*c]const c_int, num_indices: c_int) c_int; pub extern fn SDL_RenderGeometryRaw(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, xy: [*c]const f32, xy_stride: c_int, color: [*c]const SDL_Color, color_stride: c_int, uv: [*c]const f32, uv_stride: c_int, num_vertices: c_int, indices: [*c]const c_int, num_indices: c_int, size_indices: c_int) c_int; pub extern fn SDL_RenderCopyF(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_FRect) c_int; pub extern fn SDL_RenderCopyExF(renderer: ?*SDL_Renderer, texture: ?*SDL_Texture, srcrect: [*c]const SDL_Rect, dstrect: [*c]const SDL_FRect, angle: f64, center: [*c]const SDL_FPoint, flip: SDL_RendererFlip) c_int; pub extern fn SDL_RenderReadPixels(renderer: ?*SDL_Renderer, rect: [*c]const SDL_Rect, format: u32, pixels: ?*anyopaque, pitch: c_int) c_int; pub extern fn SDL_RenderPresent(renderer: ?*SDL_Renderer) void; pub extern fn SDL_DestroyTexture(texture: ?*SDL_Texture) void; pub extern fn SDL_DestroyRenderer(renderer: ?*SDL_Renderer) void; pub extern fn SDL_RenderFlush(renderer: ?*SDL_Renderer) c_int; pub extern fn SDL_GL_BindTexture(texture: ?*SDL_Texture, texw: [*c]f32, texh: [*c]f32) c_int; pub extern fn SDL_GL_UnbindTexture(texture: ?*SDL_Texture) c_int; pub extern fn SDL_RenderGetMetalLayer(renderer: ?*SDL_Renderer) ?*anyopaque; pub extern fn SDL_RenderGetMetalCommandEncoder(renderer: ?*SDL_Renderer) ?*anyopaque; pub const SDL_Keysym = extern struct { scancode: SDL_Scancode, sym: SDL_Keycode, mod: u16, unused: u32, }; pub extern fn SDL_GetKeyboardFocus() ?*SDL_Window; pub extern fn SDL_GetKeyboardState(numkeys: [*c]c_int) [*c]const u8; pub extern fn SDL_GetModState() SDL_Keymod; pub extern fn SDL_SetModState(modstate: SDL_Keymod) void; pub extern fn SDL_GetKeyFromScancode(scancode: SDL_Scancode) SDL_Keycode; pub extern fn SDL_GetScancodeFromKey(key: SDL_Keycode) SDL_Scancode; pub extern fn SDL_GetScancodeName(scancode: SDL_Scancode) [*c]const u8; pub extern fn SDL_GetScancodeFromName(name: [*c]const u8) SDL_Scancode; pub extern fn SDL_GetKeyName(key: SDL_Keycode) [*c]const u8; pub extern fn SDL_GetKeyFromName(name: [*c]const u8) SDL_Keycode; pub extern fn SDL_StartTextInput() void; pub extern fn SDL_IsTextInputActive() SDL_bool; pub extern fn SDL_StopTextInput() void; pub extern fn SDL_SetTextInputRect(rect: [*c]SDL_Rect) void; pub extern fn SDL_HasScreenKeyboardSupport() SDL_bool; pub extern fn SDL_IsScreenKeyboardShown(window: ?*SDL_Window) SDL_bool; pub const SDL_Joystick = opaque {}; pub const SDL_JoystickGUID = extern struct { data: [16]u8, }; pub const SDL_JoystickID = i32; pub const SDL_JOYSTICK_TYPE_UNKNOWN: c_int = 0; pub const SDL_JOYSTICK_TYPE_GAMECONTROLLER: c_int = 1; pub const SDL_JOYSTICK_TYPE_WHEEL: c_int = 2; pub const SDL_JOYSTICK_TYPE_ARCADE_STICK: c_int = 3; pub const SDL_JOYSTICK_TYPE_FLIGHT_STICK: c_int = 4; pub const SDL_JOYSTICK_TYPE_DANCE_PAD: c_int = 5; pub const SDL_JOYSTICK_TYPE_GUITAR: c_int = 6; pub const SDL_JOYSTICK_TYPE_DRUM_KIT: c_int = 7; pub const SDL_JOYSTICK_TYPE_ARCADE_PAD: c_int = 8; pub const SDL_JOYSTICK_TYPE_THROTTLE: c_int = 9; pub const SDL_JoystickType = c_uint; pub const SDL_JOYSTICK_POWER_UNKNOWN: c_int = -1; pub const SDL_JOYSTICK_POWER_EMPTY: c_int = 0; pub const SDL_JOYSTICK_POWER_LOW: c_int = 1; pub const SDL_JOYSTICK_POWER_MEDIUM: c_int = 2; pub const SDL_JOYSTICK_POWER_FULL: c_int = 3; pub const SDL_JOYSTICK_POWER_WIRED: c_int = 4; pub const SDL_JOYSTICK_POWER_MAX: c_int = 5; pub const SDL_JoystickPowerLevel = c_int; pub extern fn SDL_LockJoysticks() void; pub extern fn SDL_UnlockJoysticks() void; pub extern fn SDL_NumJoysticks() c_int; pub extern fn SDL_JoystickNameForIndex(device_index: c_int) [*c]const u8; pub extern fn SDL_JoystickGetDevicePlayerIndex(device_index: c_int) c_int; pub extern fn SDL_JoystickGetDeviceGUID(device_index: c_int) SDL_JoystickGUID; pub extern fn SDL_JoystickGetDeviceVendor(device_index: c_int) u16; pub extern fn SDL_JoystickGetDeviceProduct(device_index: c_int) u16; pub extern fn SDL_JoystickGetDeviceProductVersion(device_index: c_int) u16; pub extern fn SDL_JoystickGetDeviceType(device_index: c_int) SDL_JoystickType; pub extern fn SDL_JoystickGetDeviceInstanceID(device_index: c_int) SDL_JoystickID; pub extern fn SDL_JoystickOpen(device_index: c_int) ?*SDL_Joystick; pub extern fn SDL_JoystickFromInstanceID(instance_id: SDL_JoystickID) ?*SDL_Joystick; pub extern fn SDL_JoystickFromPlayerIndex(player_index: c_int) ?*SDL_Joystick; pub extern fn SDL_JoystickAttachVirtual(@"type": SDL_JoystickType, naxes: c_int, nbuttons: c_int, nhats: c_int) c_int; pub extern fn SDL_JoystickDetachVirtual(device_index: c_int) c_int; pub extern fn SDL_JoystickIsVirtual(device_index: c_int) SDL_bool; pub extern fn SDL_JoystickSetVirtualAxis(joystick: ?*SDL_Joystick, axis: c_int, value: i16) c_int; pub extern fn SDL_JoystickSetVirtualButton(joystick: ?*SDL_Joystick, button: c_int, value: u8) c_int; pub extern fn SDL_JoystickSetVirtualHat(joystick: ?*SDL_Joystick, hat: c_int, value: u8) c_int; pub extern fn SDL_JoystickName(joystick: ?*SDL_Joystick) [*c]const u8; pub extern fn SDL_JoystickGetPlayerIndex(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickSetPlayerIndex(joystick: ?*SDL_Joystick, player_index: c_int) void; pub extern fn SDL_JoystickGetGUID(joystick: ?*SDL_Joystick) SDL_JoystickGUID; pub extern fn SDL_JoystickGetVendor(joystick: ?*SDL_Joystick) u16; pub extern fn SDL_JoystickGetProduct(joystick: ?*SDL_Joystick) u16; pub extern fn SDL_JoystickGetProductVersion(joystick: ?*SDL_Joystick) u16; pub extern fn SDL_JoystickGetSerial(joystick: ?*SDL_Joystick) [*c]const u8; pub extern fn SDL_JoystickGetType(joystick: ?*SDL_Joystick) SDL_JoystickType; pub extern fn SDL_JoystickGetGUIDString(guid: SDL_JoystickGUID, pszGUID: [*c]u8, cbGUID: c_int) void; pub extern fn SDL_JoystickGetGUIDFromString(pchGUID: [*c]const u8) SDL_JoystickGUID; pub extern fn SDL_JoystickGetAttached(joystick: ?*SDL_Joystick) SDL_bool; pub extern fn SDL_JoystickInstanceID(joystick: ?*SDL_Joystick) SDL_JoystickID; pub extern fn SDL_JoystickNumAxes(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumBalls(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumHats(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickNumButtons(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_JoystickUpdate() void; pub extern fn SDL_JoystickEventState(state: c_int) c_int; pub extern fn SDL_JoystickGetAxis(joystick: ?*SDL_Joystick, axis: c_int) i16; pub extern fn SDL_JoystickGetAxisInitialState(joystick: ?*SDL_Joystick, axis: c_int, state: [*c]i16) SDL_bool; pub extern fn SDL_JoystickGetHat(joystick: ?*SDL_Joystick, hat: c_int) u8; pub extern fn SDL_JoystickGetBall(joystick: ?*SDL_Joystick, ball: c_int, dx: [*c]c_int, dy: [*c]c_int) c_int; pub extern fn SDL_JoystickGetButton(joystick: ?*SDL_Joystick, button: c_int) u8; pub extern fn SDL_JoystickRumble(joystick: ?*SDL_Joystick, low_frequency_rumble: u16, high_frequency_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_JoystickRumbleTriggers(joystick: ?*SDL_Joystick, left_rumble: u16, right_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_JoystickHasLED(joystick: ?*SDL_Joystick) SDL_bool; pub extern fn SDL_JoystickSetLED(joystick: ?*SDL_Joystick, red: u8, green: u8, blue: u8) c_int; pub extern fn SDL_JoystickSendEffect(joystick: ?*SDL_Joystick, data: ?*const anyopaque, size: c_int) c_int; pub extern fn SDL_JoystickClose(joystick: ?*SDL_Joystick) void; pub extern fn SDL_JoystickCurrentPowerLevel(joystick: ?*SDL_Joystick) SDL_JoystickPowerLevel; pub const SDL_Cursor = opaque {}; pub const SDL_SYSTEM_CURSOR_ARROW: c_int = 0; pub const SDL_SYSTEM_CURSOR_IBEAM: c_int = 1; pub const SDL_SYSTEM_CURSOR_WAIT: c_int = 2; pub const SDL_SYSTEM_CURSOR_CROSSHAIR: c_int = 3; pub const SDL_SYSTEM_CURSOR_WAITARROW: c_int = 4; pub const SDL_SYSTEM_CURSOR_SIZENWSE: c_int = 5; pub const SDL_SYSTEM_CURSOR_SIZENESW: c_int = 6; pub const SDL_SYSTEM_CURSOR_SIZEWE: c_int = 7; pub const SDL_SYSTEM_CURSOR_SIZENS: c_int = 8; pub const SDL_SYSTEM_CURSOR_SIZEALL: c_int = 9; pub const SDL_SYSTEM_CURSOR_NO: c_int = 10; pub const SDL_SYSTEM_CURSOR_HAND: c_int = 11; pub const SDL_NUM_SYSTEM_CURSORS: c_int = 12; pub const SDL_SystemCursor = c_uint; pub const SDL_MOUSEWHEEL_NORMAL: c_int = 0; pub const SDL_MOUSEWHEEL_FLIPPED: c_int = 1; pub const SDL_MouseWheelDirection = c_uint; pub extern fn SDL_GetMouseFocus() ?*SDL_Window; pub extern fn SDL_GetMouseState(x: [*c]c_int, y: [*c]c_int) u32; pub extern fn SDL_GetGlobalMouseState(x: [*c]c_int, y: [*c]c_int) u32; pub extern fn SDL_GetRelativeMouseState(x: [*c]c_int, y: [*c]c_int) u32; pub extern fn SDL_WarpMouseInWindow(window: ?*SDL_Window, x: c_int, y: c_int) void; pub extern fn SDL_WarpMouseGlobal(x: c_int, y: c_int) c_int; pub extern fn SDL_SetRelativeMouseMode(enabled: SDL_bool) c_int; pub extern fn SDL_CaptureMouse(enabled: SDL_bool) c_int; pub extern fn SDL_GetRelativeMouseMode() SDL_bool; pub extern fn SDL_CreateCursor(data: [*c]const u8, mask: [*c]const u8, w: c_int, h: c_int, hot_x: c_int, hot_y: c_int) ?*SDL_Cursor; pub extern fn SDL_CreateColorCursor(surface: [*c]SDL_Surface, hot_x: c_int, hot_y: c_int) ?*SDL_Cursor; pub extern fn SDL_CreateSystemCursor(id: SDL_SystemCursor) ?*SDL_Cursor; pub extern fn SDL_SetCursor(cursor: ?*SDL_Cursor) void; pub extern fn SDL_GetCursor() ?*SDL_Cursor; pub extern fn SDL_GetDefaultCursor() ?*SDL_Cursor; pub extern fn SDL_FreeCursor(cursor: ?*SDL_Cursor) void; pub extern fn SDL_ShowCursor(toggle: c_int) c_int; pub const SDL_mutex = opaque {}; pub extern fn SDL_CreateMutex() ?*SDL_mutex; pub extern fn SDL_LockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_TryLockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_UnlockMutex(mutex: ?*SDL_mutex) c_int; pub extern fn SDL_DestroyMutex(mutex: ?*SDL_mutex) void; pub const SDL_semaphore = opaque {}; pub extern fn SDL_CreateSemaphore(initial_value: u32) ?*SDL_semaphore; pub extern fn SDL_DestroySemaphore(sem: ?*SDL_semaphore) void; pub extern fn SDL_SemWait(sem: ?*SDL_semaphore) c_int; pub extern fn SDL_SemTryWait(sem: ?*SDL_semaphore) c_int; pub extern fn SDL_SemWaitTimeout(sem: ?*SDL_semaphore, ms: u32) c_int; pub extern fn SDL_SemPost(sem: ?*SDL_semaphore) c_int; pub extern fn SDL_SemValue(sem: ?*SDL_semaphore) u32; pub const SDL_cond = opaque {}; pub extern fn SDL_CreateCond() ?*SDL_cond; pub extern fn SDL_DestroyCond(cond: ?*SDL_cond) void; pub extern fn SDL_CondSignal(cond: ?*SDL_cond) c_int; pub extern fn SDL_CondBroadcast(cond: ?*SDL_cond) c_int; pub extern fn SDL_CondWait(cond: ?*SDL_cond, mutex: ?*SDL_mutex) c_int; pub extern fn SDL_CondWaitTimeout(cond: ?*SDL_cond, mutex: ?*SDL_mutex, ms: u32) c_int; pub extern fn SDL_LoadObject(sofile: [*c]const u8) ?*anyopaque; pub extern fn SDL_LoadFunction(handle: ?*anyopaque, name: [*c]const u8) ?*anyopaque; pub extern fn SDL_UnloadObject(handle: ?*anyopaque) void; pub const SDL_FIRSTEVENT: c_int = 0; pub const SDL_QUIT: c_int = 256; pub const SDL_APP_TERMINATING: c_int = 257; pub const SDL_APP_LOWMEMORY: c_int = 258; pub const SDL_APP_WILLENTERBACKGROUND: c_int = 259; pub const SDL_APP_DIDENTERBACKGROUND: c_int = 260; pub const SDL_APP_WILLENTERFOREGROUND: c_int = 261; pub const SDL_APP_DIDENTERFOREGROUND: c_int = 262; pub const SDL_LOCALECHANGED: c_int = 263; pub const SDL_DISPLAYEVENT: c_int = 336; pub const SDL_WINDOWEVENT: c_int = 512; pub const SDL_SYSWMEVENT: c_int = 513; pub const SDL_KEYDOWN: c_int = 768; pub const SDL_KEYUP: c_int = 769; pub const SDL_TEXTEDITING: c_int = 770; pub const SDL_TEXTINPUT: c_int = 771; pub const SDL_KEYMAPCHANGED: c_int = 772; pub const SDL_MOUSEMOTION: c_int = 1024; pub const SDL_MOUSEBUTTONDOWN: c_int = 1025; pub const SDL_MOUSEBUTTONUP: c_int = 1026; pub const SDL_MOUSEWHEEL: c_int = 1027; pub const SDL_JOYAXISMOTION: c_int = 1536; pub const SDL_JOYBALLMOTION: c_int = 1537; pub const SDL_JOYHATMOTION: c_int = 1538; pub const SDL_JOYBUTTONDOWN: c_int = 1539; pub const SDL_JOYBUTTONUP: c_int = 1540; pub const SDL_JOYDEVICEADDED: c_int = 1541; pub const SDL_JOYDEVICEREMOVED: c_int = 1542; pub const SDL_CONTROLLERAXISMOTION: c_int = 1616; pub const SDL_CONTROLLERBUTTONDOWN: c_int = 1617; pub const SDL_CONTROLLERBUTTONUP: c_int = 1618; pub const SDL_CONTROLLERDEVICEADDED: c_int = 1619; pub const SDL_CONTROLLERDEVICEREMOVED: c_int = 1620; pub const SDL_CONTROLLERDEVICEREMAPPED: c_int = 1621; pub const SDL_CONTROLLERTOUCHPADDOWN: c_int = 1622; pub const SDL_CONTROLLERTOUCHPADMOTION: c_int = 1623; pub const SDL_CONTROLLERTOUCHPADUP: c_int = 1624; pub const SDL_CONTROLLERSENSORUPDATE: c_int = 1625; pub const SDL_FINGERDOWN: c_int = 1792; pub const SDL_FINGERUP: c_int = 1793; pub const SDL_FINGERMOTION: c_int = 1794; pub const SDL_DOLLARGESTURE: c_int = 2048; pub const SDL_DOLLARRECORD: c_int = 2049; pub const SDL_MULTIGESTURE: c_int = 2050; pub const SDL_CLIPBOARDUPDATE: c_int = 2304; pub const SDL_DROPFILE: c_int = 4096; pub const SDL_DROPTEXT: c_int = 4097; pub const SDL_DROPBEGIN: c_int = 4098; pub const SDL_DROPCOMPLETE: c_int = 4099; pub const SDL_AUDIODEVICEADDED: c_int = 4352; pub const SDL_AUDIODEVICEREMOVED: c_int = 4353; pub const SDL_SENSORUPDATE: c_int = 4608; pub const SDL_RENDER_TARGETS_RESET: c_int = 8192; pub const SDL_RENDER_DEVICE_RESET: c_int = 8193; pub const SDL_USEREVENT: c_int = 32768; pub const SDL_LASTEVENT: c_int = 65535; pub const SDL_EventType = c_uint; pub const SDL_CommonEvent = extern struct { type: u32, timestamp: u32, }; pub const SDL_DisplayEvent = extern struct { type: u32, timestamp: u32, display: u32, event: u8, padding1: u8, padding2: u8, padding3: u8, data1: i32, }; pub const SDL_WindowEvent = extern struct { type: u32, timestamp: u32, windowID: u32, event: u8, padding1: u8, padding2: u8, padding3: u8, data1: i32, data2: i32, }; pub const SDL_KeyboardEvent = extern struct { type: u32, timestamp: u32, windowID: u32, state: u8, repeat: u8, padding2: u8, padding3: u8, keysym: SDL_Keysym, }; pub const SDL_TextEditingEvent = extern struct { type: u32, timestamp: u32, windowID: u32, text: [32]u8, start: i32, length: i32, }; pub const SDL_TextInputEvent = extern struct { type: u32, timestamp: u32, windowID: u32, text: [32]u8, }; pub const SDL_MouseMotionEvent = extern struct { type: u32, timestamp: u32, windowID: u32, which: u32, state: u32, x: i32, y: i32, xrel: i32, yrel: i32, }; pub const SDL_MouseButtonEvent = extern struct { type: u32, timestamp: u32, windowID: u32, which: u32, button: u8, state: u8, clicks: u8, padding1: u8, x: i32, y: i32, }; pub const SDL_MouseWheelEvent = extern struct { type: u32, timestamp: u32, windowID: u32, which: u32, x: i32, y: i32, direction: u32, }; pub const SDL_JoyAxisEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, axis: u8, padding1: u8, padding2: u8, padding3: u8, value: i16, padding4: u16, }; pub const SDL_JoyBallEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, ball: u8, padding1: u8, padding2: u8, padding3: u8, xrel: i16, yrel: i16, }; pub const SDL_JoyHatEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, hat: u8, value: u8, padding1: u8, padding2: u8, }; pub const SDL_JoyButtonEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, button: u8, state: u8, padding1: u8, padding2: u8, }; pub const SDL_JoyDeviceEvent = extern struct { type: u32, timestamp: u32, which: i32, }; pub const SDL_ControllerAxisEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, axis: u8, padding1: u8, padding2: u8, padding3: u8, value: i16, padding4: u16, }; pub const SDL_ControllerButtonEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, button: u8, state: u8, padding1: u8, padding2: u8, }; pub const SDL_ControllerDeviceEvent = extern struct { type: u32, timestamp: u32, which: i32, }; pub const SDL_ControllerTouchpadEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, touchpad: i32, finger: i32, x: f32, y: f32, pressure: f32, }; pub const SDL_ControllerSensorEvent = extern struct { type: u32, timestamp: u32, which: SDL_JoystickID, sensor: i32, data: [3]f32, }; pub const SDL_AudioDeviceEvent = extern struct { type: u32, timestamp: u32, which: u32, iscapture: u8, padding1: u8, padding2: u8, padding3: u8, }; pub const SDL_TouchFingerEvent = extern struct { type: u32, timestamp: u32, touchId: SDL_TouchID, fingerId: SDL_FingerID, x: f32, y: f32, dx: f32, dy: f32, pressure: f32, windowID: u32, }; pub const SDL_MultiGestureEvent = extern struct { type: u32, timestamp: u32, touchId: SDL_TouchID, dTheta: f32, dDist: f32, x: f32, y: f32, numFingers: u16, padding: u16, }; pub const SDL_DollarGestureEvent = extern struct { type: u32, timestamp: u32, touchId: SDL_TouchID, gestureId: SDL_GestureID, numFingers: u32, @"error": f32, x: f32, y: f32, }; pub const SDL_DropEvent = extern struct { type: u32, timestamp: u32, file: [*c]u8, windowID: u32, }; pub const SDL_SensorEvent = extern struct { type: u32, timestamp: u32, which: i32, data: [6]f32, }; pub const SDL_QuitEvent = extern struct { type: u32, timestamp: u32, }; pub const SDL_OSEvent = extern struct { type: u32, timestamp: u32, }; pub const SDL_UserEvent = extern struct { type: u32, timestamp: u32, windowID: u32, code: i32, data1: ?*anyopaque, data2: ?*anyopaque, }; pub const SDL_SysWMmsg = opaque {}; pub const SDL_SysWMEvent = extern struct { type: u32, timestamp: u32, msg: ?*SDL_SysWMmsg, }; pub const SDL_Event = extern union { type: u32, common: SDL_CommonEvent, display: SDL_DisplayEvent, window: SDL_WindowEvent, key: SDL_KeyboardEvent, edit: SDL_TextEditingEvent, text: SDL_TextInputEvent, motion: SDL_MouseMotionEvent, button: SDL_MouseButtonEvent, wheel: SDL_MouseWheelEvent, jaxis: SDL_JoyAxisEvent, jball: SDL_JoyBallEvent, jhat: SDL_JoyHatEvent, jbutton: SDL_JoyButtonEvent, jdevice: SDL_JoyDeviceEvent, caxis: SDL_ControllerAxisEvent, cbutton: SDL_ControllerButtonEvent, cdevice: SDL_ControllerDeviceEvent, ctouchpad: SDL_ControllerTouchpadEvent, csensor: SDL_ControllerSensorEvent, adevice: SDL_AudioDeviceEvent, sensor: SDL_SensorEvent, quit: SDL_QuitEvent, user: SDL_UserEvent, syswm: SDL_SysWMEvent, tfinger: SDL_TouchFingerEvent, mgesture: SDL_MultiGestureEvent, dgesture: SDL_DollarGestureEvent, drop: SDL_DropEvent, padding: [56]u8, }; pub extern fn SDL_PumpEvents() void; pub const SDL_ADDEVENT: c_int = 0; pub const SDL_PEEKEVENT: c_int = 1; pub const SDL_GETEVENT: c_int = 2; pub const SDL_eventaction = c_uint; pub extern fn SDL_PeepEvents(events: [*c]SDL_Event, numevents: c_int, action: SDL_eventaction, minType: u32, maxType: u32) c_int; pub extern fn SDL_HasEvent(@"type": u32) SDL_bool; pub extern fn SDL_HasEvents(minType: u32, maxType: u32) SDL_bool; pub extern fn SDL_FlushEvent(@"type": u32) void; pub extern fn SDL_FlushEvents(minType: u32, maxType: u32) void; pub extern fn SDL_PollEvent(event: [*c]SDL_Event) c_int; pub extern fn SDL_WaitEvent(event: [*c]SDL_Event) c_int; pub extern fn SDL_WaitEventTimeout(event: [*c]SDL_Event, timeout: c_int) c_int; pub extern fn SDL_PushEvent(event: [*c]SDL_Event) c_int; pub const SDL_EventFilter = ?fn (?*anyopaque, [*c]SDL_Event) callconv(.C) c_int; pub extern fn SDL_SetEventFilter(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_GetEventFilter(filter: [*c]SDL_EventFilter, userdata: [*c]?*anyopaque) SDL_bool; pub extern fn SDL_AddEventWatch(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_DelEventWatch(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_FilterEvents(filter: SDL_EventFilter, userdata: ?*anyopaque) void; pub extern fn SDL_EventState(@"type": u32, state: c_int) u8; pub extern fn SDL_RegisterEvents(numevents: c_int) u32; pub const SDL_LOG_CATEGORY_APPLICATION: c_int = 0; pub const SDL_LOG_CATEGORY_ERROR: c_int = 1; pub const SDL_LOG_CATEGORY_ASSERT: c_int = 2; pub const SDL_LOG_CATEGORY_SYSTEM: c_int = 3; pub const SDL_LOG_CATEGORY_AUDIO: c_int = 4; pub const SDL_LOG_CATEGORY_VIDEO: c_int = 5; pub const SDL_LOG_CATEGORY_RENDER: c_int = 6; pub const SDL_LOG_CATEGORY_INPUT: c_int = 7; pub const SDL_LOG_CATEGORY_TEST: c_int = 8; pub const SDL_LOG_CATEGORY_RESERVED1: c_int = 9; pub const SDL_LOG_CATEGORY_RESERVED2: c_int = 10; pub const SDL_LOG_CATEGORY_RESERVED3: c_int = 11; pub const SDL_LOG_CATEGORY_RESERVED4: c_int = 12; pub const SDL_LOG_CATEGORY_RESERVED5: c_int = 13; pub const SDL_LOG_CATEGORY_RESERVED6: c_int = 14; pub const SDL_LOG_CATEGORY_RESERVED7: c_int = 15; pub const SDL_LOG_CATEGORY_RESERVED8: c_int = 16; pub const SDL_LOG_CATEGORY_RESERVED9: c_int = 17; pub const SDL_LOG_CATEGORY_RESERVED10: c_int = 18; pub const SDL_LOG_CATEGORY_CUSTOM: c_int = 19; pub const SDL_LogCategory = c_uint; pub const SDL_LOG_PRIORITY_VERBOSE: c_int = 1; pub const SDL_LOG_PRIORITY_DEBUG: c_int = 2; pub const SDL_LOG_PRIORITY_INFO: c_int = 3; pub const SDL_LOG_PRIORITY_WARN: c_int = 4; pub const SDL_LOG_PRIORITY_ERROR: c_int = 5; pub const SDL_LOG_PRIORITY_CRITICAL: c_int = 6; pub const SDL_NUM_LOG_PRIORITIES: c_int = 7; pub const SDL_LogPriority = c_uint; pub extern fn SDL_LogSetAllPriority(priority: SDL_LogPriority) void; pub extern fn SDL_LogSetPriority(category: c_int, priority: SDL_LogPriority) void; pub extern fn SDL_LogGetPriority(category: c_int) SDL_LogPriority; pub extern fn SDL_LogResetPriorities() void; pub extern fn SDL_Log(fmt: [*c]const u8, ...) void; pub extern fn SDL_LogVerbose(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogDebug(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogInfo(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogWarn(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogError(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogCritical(category: c_int, fmt: [*c]const u8, ...) void; pub extern fn SDL_LogMessage(category: c_int, priority: SDL_LogPriority, fmt: [*c]const u8, ...) void; pub const SDL_LogOutputFunction = ?fn (?*anyopaque, c_int, SDL_LogPriority, [*c]const u8) callconv(.C) void; pub extern fn SDL_LogGetOutputFunction(callback: [*c]SDL_LogOutputFunction, userdata: [*c]?*anyopaque) void; pub extern fn SDL_LogSetOutputFunction(callback: SDL_LogOutputFunction, userdata: ?*anyopaque) void; pub const _SDL_GameController = opaque {}; pub const SDL_GameController = _SDL_GameController; pub const SDL_CONTROLLER_TYPE_UNKNOWN: c_int = 0; pub const SDL_CONTROLLER_TYPE_XBOX360: c_int = 1; pub const SDL_CONTROLLER_TYPE_XBOXONE: c_int = 2; pub const SDL_CONTROLLER_TYPE_PS3: c_int = 3; pub const SDL_CONTROLLER_TYPE_PS4: c_int = 4; pub const SDL_CONTROLLER_TYPE_NINTENDO_SWITCH_PRO: c_int = 5; pub const SDL_CONTROLLER_TYPE_VIRTUAL: c_int = 6; pub const SDL_CONTROLLER_TYPE_PS5: c_int = 7; pub const SDL_CONTROLLER_TYPE_AMAZON_LUNA: c_int = 8; pub const SDL_CONTROLLER_TYPE_GOOGLE_STADIA: c_int = 9; pub const SDL_GameControllerType = c_uint; pub const SDL_CONTROLLER_BINDTYPE_NONE: c_int = 0; pub const SDL_CONTROLLER_BINDTYPE_BUTTON: c_int = 1; pub const SDL_CONTROLLER_BINDTYPE_AXIS: c_int = 2; pub const SDL_CONTROLLER_BINDTYPE_HAT: c_int = 3; pub const SDL_GameControllerBindType = c_uint; const unnamed_2 = extern struct { hat: c_int, hat_mask: c_int, }; const union_unnamed_1 = extern union { button: c_int, axis: c_int, hat: unnamed_2, }; pub const SDL_GameControllerButtonBind = extern struct { bindType: SDL_GameControllerBindType, value: union_unnamed_1, }; pub extern fn SDL_GameControllerAddMappingsFromRW(rw: [*c]SDL_RWops, freerw: c_int) c_int; pub extern fn SDL_GameControllerAddMapping(mappingString: [*c]const u8) c_int; pub extern fn SDL_GameControllerNumMappings() c_int; pub extern fn SDL_GameControllerMappingForIndex(mapping_index: c_int) [*c]u8; pub extern fn SDL_GameControllerMappingForGUID(guid: SDL_JoystickGUID) [*c]u8; pub extern fn SDL_GameControllerMapping(gamecontroller: ?*SDL_GameController) [*c]u8; pub extern fn SDL_IsGameController(joystick_index: c_int) SDL_bool; pub extern fn SDL_GameControllerNameForIndex(joystick_index: c_int) [*c]const u8; pub extern fn SDL_GameControllerTypeForIndex(joystick_index: c_int) SDL_GameControllerType; pub extern fn SDL_GameControllerMappingForDeviceIndex(joystick_index: c_int) [*c]u8; pub extern fn SDL_GameControllerOpen(joystick_index: c_int) ?*SDL_GameController; pub extern fn SDL_GameControllerFromInstanceID(joyid: SDL_JoystickID) ?*SDL_GameController; pub extern fn SDL_GameControllerFromPlayerIndex(player_index: c_int) ?*SDL_GameController; pub extern fn SDL_GameControllerName(gamecontroller: ?*SDL_GameController) [*c]const u8; pub extern fn SDL_GameControllerGetType(gamecontroller: ?*SDL_GameController) SDL_GameControllerType; pub extern fn SDL_GameControllerGetPlayerIndex(gamecontroller: ?*SDL_GameController) c_int; pub extern fn SDL_GameControllerSetPlayerIndex(gamecontroller: ?*SDL_GameController, player_index: c_int) void; pub extern fn SDL_GameControllerGetVendor(gamecontroller: ?*SDL_GameController) u16; pub extern fn SDL_GameControllerGetProduct(gamecontroller: ?*SDL_GameController) u16; pub extern fn SDL_GameControllerGetProductVersion(gamecontroller: ?*SDL_GameController) u16; pub extern fn SDL_GameControllerGetSerial(gamecontroller: ?*SDL_GameController) [*c]const u8; pub extern fn SDL_GameControllerGetAttached(gamecontroller: ?*SDL_GameController) SDL_bool; pub extern fn SDL_GameControllerGetJoystick(gamecontroller: ?*SDL_GameController) ?*SDL_Joystick; pub extern fn SDL_GameControllerEventState(state: c_int) c_int; pub extern fn SDL_GameControllerUpdate() void; pub const SDL_CONTROLLER_AXIS_INVALID: c_int = -1; pub const SDL_CONTROLLER_AXIS_LEFTX: c_int = 0; pub const SDL_CONTROLLER_AXIS_LEFTY: c_int = 1; pub const SDL_CONTROLLER_AXIS_RIGHTX: c_int = 2; pub const SDL_CONTROLLER_AXIS_RIGHTY: c_int = 3; pub const SDL_CONTROLLER_AXIS_TRIGGERLEFT: c_int = 4; pub const SDL_CONTROLLER_AXIS_TRIGGERRIGHT: c_int = 5; pub const SDL_CONTROLLER_AXIS_MAX: c_int = 6; pub const SDL_GameControllerAxis = c_int; pub extern fn SDL_GameControllerGetAxisFromString(str: [*c]const u8) SDL_GameControllerAxis; pub extern fn SDL_GameControllerGetStringForAxis(axis: SDL_GameControllerAxis) [*c]const u8; pub extern fn SDL_GameControllerGetBindForAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerHasAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) SDL_bool; pub extern fn SDL_GameControllerGetAxis(gamecontroller: ?*SDL_GameController, axis: SDL_GameControllerAxis) i16; pub const SDL_CONTROLLER_BUTTON_INVALID: c_int = -1; pub const SDL_CONTROLLER_BUTTON_A: c_int = 0; pub const SDL_CONTROLLER_BUTTON_B: c_int = 1; pub const SDL_CONTROLLER_BUTTON_X: c_int = 2; pub const SDL_CONTROLLER_BUTTON_Y: c_int = 3; pub const SDL_CONTROLLER_BUTTON_BACK: c_int = 4; pub const SDL_CONTROLLER_BUTTON_GUIDE: c_int = 5; pub const SDL_CONTROLLER_BUTTON_START: c_int = 6; pub const SDL_CONTROLLER_BUTTON_LEFTSTICK: c_int = 7; pub const SDL_CONTROLLER_BUTTON_RIGHTSTICK: c_int = 8; pub const SDL_CONTROLLER_BUTTON_LEFTSHOULDER: c_int = 9; pub const SDL_CONTROLLER_BUTTON_RIGHTSHOULDER: c_int = 10; pub const SDL_CONTROLLER_BUTTON_DPAD_UP: c_int = 11; pub const SDL_CONTROLLER_BUTTON_DPAD_DOWN: c_int = 12; pub const SDL_CONTROLLER_BUTTON_DPAD_LEFT: c_int = 13; pub const SDL_CONTROLLER_BUTTON_DPAD_RIGHT: c_int = 14; pub const SDL_CONTROLLER_BUTTON_MISC1: c_int = 15; pub const SDL_CONTROLLER_BUTTON_PADDLE1: c_int = 16; pub const SDL_CONTROLLER_BUTTON_PADDLE2: c_int = 17; pub const SDL_CONTROLLER_BUTTON_PADDLE3: c_int = 18; pub const SDL_CONTROLLER_BUTTON_PADDLE4: c_int = 19; pub const SDL_CONTROLLER_BUTTON_TOUCHPAD: c_int = 20; pub const SDL_CONTROLLER_BUTTON_MAX: c_int = 21; pub const SDL_GameControllerButton = c_int; pub extern fn SDL_GameControllerGetButtonFromString(str: [*c]const u8) SDL_GameControllerButton; pub extern fn SDL_GameControllerGetStringForButton(button: SDL_GameControllerButton) [*c]const u8; pub extern fn SDL_GameControllerGetBindForButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) SDL_GameControllerButtonBind; pub extern fn SDL_GameControllerHasButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) SDL_bool; pub extern fn SDL_GameControllerGetButton(gamecontroller: ?*SDL_GameController, button: SDL_GameControllerButton) u8; pub extern fn SDL_GameControllerGetNumTouchpads(gamecontroller: ?*SDL_GameController) c_int; pub extern fn SDL_GameControllerGetNumTouchpadFingers(gamecontroller: ?*SDL_GameController, touchpad: c_int) c_int; pub extern fn SDL_GameControllerGetTouchpadFinger(gamecontroller: ?*SDL_GameController, touchpad: c_int, finger: c_int, state: [*c]u8, x: [*c]f32, y: [*c]f32, pressure: [*c]f32) c_int; pub extern fn SDL_GameControllerHasSensor(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType) SDL_bool; pub extern fn SDL_GameControllerSetSensorEnabled(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType, enabled: SDL_bool) c_int; pub extern fn SDL_GameControllerIsSensorEnabled(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType) SDL_bool; pub extern fn SDL_GameControllerGetSensorDataRate(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType) f32; pub extern fn SDL_GameControllerGetSensorData(gamecontroller: ?*SDL_GameController, @"type": SDL_SensorType, data: [*c]f32, num_values: c_int) c_int; pub extern fn SDL_GameControllerRumble(gamecontroller: ?*SDL_GameController, low_frequency_rumble: u16, high_frequency_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_GameControllerRumbleTriggers(gamecontroller: ?*SDL_GameController, left_rumble: u16, right_rumble: u16, duration_ms: u32) c_int; pub extern fn SDL_GameControllerHasLED(gamecontroller: ?*SDL_GameController) SDL_bool; pub extern fn SDL_GameControllerSetLED(gamecontroller: ?*SDL_GameController, red: u8, green: u8, blue: u8) c_int; pub extern fn SDL_GameControllerSendEffect(gamecontroller: ?*SDL_GameController, data: ?*const anyopaque, size: c_int) c_int; pub extern fn SDL_GameControllerClose(gamecontroller: ?*SDL_GameController) void; pub const SDL_Haptic = opaque {}; pub const SDL_HapticDirection = extern struct { type: u8, dir: [3]i32, }; pub const SDL_HapticConstant = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, level: i16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticPeriodic = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, period: u16, magnitude: i16, offset: i16, phase: u16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticCondition = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, right_sat: [3]u16, left_sat: [3]u16, right_coeff: [3]i16, left_coeff: [3]i16, deadband: [3]u16, center: [3]i16, }; pub const SDL_HapticRamp = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, start: i16, end: i16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const SDL_HapticLeftRight = extern struct { type: u16, length: u32, large_magnitude: u16, small_magnitude: u16, }; pub const SDL_HapticCustom = extern struct { type: u16, direction: SDL_HapticDirection, length: u32, delay: u16, button: u16, interval: u16, channels: u8, period: u16, samples: u16, data: [*c]u16, attack_length: u16, attack_level: u16, fade_length: u16, fade_level: u16, }; pub const union_SDL_HapticEffect = extern union { type: u16, constant: SDL_HapticConstant, periodic: SDL_HapticPeriodic, condition: SDL_HapticCondition, ramp: SDL_HapticRamp, leftright: SDL_HapticLeftRight, custom: SDL_HapticCustom, }; pub const SDL_HapticEffect = union_SDL_HapticEffect; pub extern fn SDL_NumHaptics() c_int; pub extern fn SDL_HapticName(device_index: c_int) [*c]const u8; pub extern fn SDL_HapticOpen(device_index: c_int) ?*SDL_Haptic; pub extern fn SDL_HapticOpened(device_index: c_int) c_int; pub extern fn SDL_HapticIndex(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_MouseIsHaptic() c_int; pub extern fn SDL_HapticOpenFromMouse() ?*SDL_Haptic; pub extern fn SDL_JoystickIsHaptic(joystick: ?*SDL_Joystick) c_int; pub extern fn SDL_HapticOpenFromJoystick(joystick: ?*SDL_Joystick) ?*SDL_Haptic; pub extern fn SDL_HapticClose(haptic: ?*SDL_Haptic) void; pub extern fn SDL_HapticNumEffects(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticNumEffectsPlaying(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticQuery(haptic: ?*SDL_Haptic) c_uint; pub extern fn SDL_HapticNumAxes(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticEffectSupported(haptic: ?*SDL_Haptic, effect: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticNewEffect(haptic: ?*SDL_Haptic, effect: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticUpdateEffect(haptic: ?*SDL_Haptic, effect: c_int, data: [*c]SDL_HapticEffect) c_int; pub extern fn SDL_HapticRunEffect(haptic: ?*SDL_Haptic, effect: c_int, iterations: u32) c_int; pub extern fn SDL_HapticStopEffect(haptic: ?*SDL_Haptic, effect: c_int) c_int; pub extern fn SDL_HapticDestroyEffect(haptic: ?*SDL_Haptic, effect: c_int) void; pub extern fn SDL_HapticGetEffectStatus(haptic: ?*SDL_Haptic, effect: c_int) c_int; pub extern fn SDL_HapticSetGain(haptic: ?*SDL_Haptic, gain: c_int) c_int; pub extern fn SDL_HapticSetAutocenter(haptic: ?*SDL_Haptic, autocenter: c_int) c_int; pub extern fn SDL_HapticPause(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticUnpause(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticStopAll(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumbleSupported(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumbleInit(haptic: ?*SDL_Haptic) c_int; pub extern fn SDL_HapticRumblePlay(haptic: ?*SDL_Haptic, strength: f32, length: u32) c_int; pub extern fn SDL_HapticRumbleStop(haptic: ?*SDL_Haptic) c_int; pub const SDL_HINT_DEFAULT: c_int = 0; pub const SDL_HINT_NORMAL: c_int = 1; pub const SDL_HINT_OVERRIDE: c_int = 2; pub const SDL_HintPriority = c_uint; pub extern fn SDL_SetHintWithPriority(name: [*c]const u8, value: [*c]const u8, priority: SDL_HintPriority) SDL_bool; pub extern fn SDL_SetHint(name: [*c]const u8, value: [*c]const u8) SDL_bool; pub extern fn SDL_GetHint(name: [*c]const u8) [*c]const u8; pub extern fn SDL_GetHintBoolean(name: [*c]const u8, default_value: SDL_bool) SDL_bool; pub const SDL_HintCallback = ?fn (?*anyopaque, [*c]const u8, [*c]const u8, [*c]const u8) callconv(.C) void; pub extern fn SDL_AddHintCallback(name: [*c]const u8, callback: SDL_HintCallback, userdata: ?*anyopaque) void; pub extern fn SDL_DelHintCallback(name: [*c]const u8, callback: SDL_HintCallback, userdata: ?*anyopaque) void; pub extern fn SDL_ClearHints() void; pub const SDL_Locale = extern struct { language: [*c]const u8, country: [*c]const u8, }; pub extern fn SDL_GetPreferredLocales() [*c]SDL_Locale; pub const SDL_TRUE = @as(c_int, 1); pub const SDL_FALSE = @as(c_int, 0); pub inline fn SDL_static_cast(Type: anytype, Value: anytype) @TypeOf(Type(Value)) { return Type(Value); } pub inline fn SDL_FOURCC(A: anytype, B: anytype, C: anytype, D: anytype) @TypeOf((((SDL_static_cast(u32, SDL_static_cast(u8, A)) << @as(c_int, 0)) | (SDL_static_cast(u32, SDL_static_cast(u8, B)) << @as(c_int, 8))) | (SDL_static_cast(u32, SDL_static_cast(u8, C)) << @as(c_int, 16))) | (SDL_static_cast(u32, SDL_static_cast(u8, D)) << @as(c_int, 24))) { return (((SDL_static_cast(u32, SDL_static_cast(u8, A)) << @as(c_int, 0)) | (SDL_static_cast(u32, SDL_static_cast(u8, B)) << @as(c_int, 8))) | (SDL_static_cast(u32, SDL_static_cast(u8, C)) << @as(c_int, 16))) | (SDL_static_cast(u32, SDL_static_cast(u8, D)) << @as(c_int, 24)); } pub const SDL_CACHELINE_SIZE = @as(c_int, 128); pub const SDL_RWOPS_UNKNOWN = @as(c_uint, 0); pub const SDL_RWOPS_WINFILE = @as(c_uint, 1); pub const SDL_RWOPS_STDFILE = @as(c_uint, 2); pub const SDL_RWOPS_JNIFILE = @as(c_uint, 3); pub const SDL_RWOPS_MEMORY = @as(c_uint, 4); pub const SDL_RWOPS_MEMORY_RO = @as(c_uint, 5); pub const SDL_RWOPS_VITAFILE = @as(c_uint, 6); pub const RW_SEEK_SET = @as(c_int, 0); pub const RW_SEEK_CUR = @as(c_int, 1); pub const RW_SEEK_END = @as(c_int, 2); pub const SDL_ALPHA_OPAQUE = @as(c_int, 255); pub const SDL_ALPHA_TRANSPARENT = @as(c_int, 0); pub inline fn SDL_DEFINE_PIXELFOURCC(A: anytype, B: anytype, C: anytype, D: anytype) @TypeOf(SDL_FOURCC(A, B, C, D)) { return SDL_FOURCC(A, B, C, D); } pub inline fn SDL_DEFINE_PIXELFORMAT(@"type": anytype, order: anytype, layout: anytype, bits: anytype, bytes: anytype) @TypeOf((((((@as(c_int, 1) << @as(c_int, 28)) | (@"type" << @as(c_int, 24))) | (order << @as(c_int, 20))) | (layout << @as(c_int, 16))) | (bits << @as(c_int, 8))) | (bytes << @as(c_int, 0))) { return (((((@as(c_int, 1) << @as(c_int, 28)) | (@"type" << @as(c_int, 24))) | (order << @as(c_int, 20))) | (layout << @as(c_int, 16))) | (bits << @as(c_int, 8))) | (bytes << @as(c_int, 0)); } pub inline fn SDL_PIXELFLAG(X: anytype) @TypeOf((X >> @as(c_int, 28)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 28)) & @as(c_int, 0x0F); } pub inline fn SDL_PIXELTYPE(X: anytype) @TypeOf((X >> @as(c_int, 24)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 24)) & @as(c_int, 0x0F); } pub inline fn SDL_PIXELORDER(X: anytype) @TypeOf((X >> @as(c_int, 20)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 20)) & @as(c_int, 0x0F); } pub inline fn SDL_PIXELLAYOUT(X: anytype) @TypeOf((X >> @as(c_int, 16)) & @as(c_int, 0x0F)) { return (X >> @as(c_int, 16)) & @as(c_int, 0x0F); } pub inline fn SDL_BITSPERPIXEL(X: anytype) @TypeOf((X >> @as(c_int, 8)) & @as(c_int, 0xFF)) { return (X >> @as(c_int, 8)) & @as(c_int, 0xFF); } pub inline fn SDL_BYTESPERPIXEL(X: anytype) @TypeOf(if (SDL_ISPIXELFORMAT_FOURCC(X)) if (((X == SDL_PIXELFORMAT_YUY2) or (X == SDL_PIXELFORMAT_UYVY)) or (X == SDL_PIXELFORMAT_YVYU)) @as(c_int, 2) else @as(c_int, 1) else (X >> @as(c_int, 0)) & @as(c_int, 0xFF)) { return if (SDL_ISPIXELFORMAT_FOURCC(X)) if (((X == SDL_PIXELFORMAT_YUY2) or (X == SDL_PIXELFORMAT_UYVY)) or (X == SDL_PIXELFORMAT_YVYU)) @as(c_int, 2) else @as(c_int, 1) else (X >> @as(c_int, 0)) & @as(c_int, 0xFF); } pub inline fn SDL_ISPIXELFORMAT_INDEXED(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX1) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX4)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_INDEX8)); } pub inline fn SDL_ISPIXELFORMAT_PACKED(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_PACKED32)); } pub inline fn SDL_ISPIXELFORMAT_ARRAY(format: anytype) @TypeOf(!(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32))) { return !(SDL_ISPIXELFORMAT_FOURCC(format) != 0) and (((((SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU8) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYU32)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF16)) or (SDL_PIXELTYPE(format) == SDL_PIXELTYPE_ARRAYF32)); } pub inline fn SDL_ISPIXELFORMAT_ALPHA(format: anytype) @TypeOf(((SDL_ISPIXELFORMAT_PACKED(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) or ((SDL_ISPIXELFORMAT_ARRAY(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA)))) { return ((SDL_ISPIXELFORMAT_PACKED(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_PACKEDORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_PACKEDORDER_BGRA))) or ((SDL_ISPIXELFORMAT_ARRAY(format) != 0) and ((((SDL_PIXELORDER(format) == SDL_ARRAYORDER_ARGB) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_RGBA)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_ABGR)) or (SDL_PIXELORDER(format) == SDL_ARRAYORDER_BGRA))); } pub inline fn SDL_ISPIXELFORMAT_FOURCC(format: anytype) @TypeOf((format != 0) and (SDL_PIXELFLAG(format) != @as(c_int, 1))) { return (format != 0) and (SDL_PIXELFLAG(format) != @as(c_int, 1)); } pub const SDL_Colour = SDL_Color; pub const SDL_SWSURFACE = @as(c_int, 0); pub const SDL_PREALLOC = @as(c_int, 0x00000001); pub const SDL_RLEACCEL = @as(c_int, 0x00000002); pub const SDL_DONTFREE = @as(c_int, 0x00000004); pub const SDL_SIMD_ALIGNED = @as(c_int, 0x00000008); pub inline fn SDL_MUSTLOCK(S: anytype) @TypeOf((S.*.flags & SDL_RLEACCEL) != @as(c_int, 0)) { return (S.*.flags & SDL_RLEACCEL) != @as(c_int, 0); } pub inline fn SDL_LoadBMP(file: anytype) @TypeOf(SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1))) { return SDL_LoadBMP_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1)); } pub inline fn SDL_SaveBMP(surface: anytype, file: anytype) @TypeOf(SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), @as(c_int, 1))) { return SDL_SaveBMP_RW(surface, SDL_RWFromFile(file, "wb"), @as(c_int, 1)); } pub const SDL_BlitSurface = SDL_UpperBlit; pub const SDL_BlitScaled = SDL_UpperBlitScaled; pub const SDL_AUDIO_MASK_BITSIZE = @as(c_int, 0xFF); pub const SDL_AUDIO_MASK_DATATYPE = @as(c_int, 1) << @as(c_int, 8); pub const SDL_AUDIO_MASK_ENDIAN = @as(c_int, 1) << @as(c_int, 12); pub const SDL_AUDIO_MASK_SIGNED = @as(c_int, 1) << @as(c_int, 15); pub inline fn SDL_AUDIO_BITSIZE(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_BITSIZE) { return x & SDL_AUDIO_MASK_BITSIZE; } pub inline fn SDL_AUDIO_ISFLOAT(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_DATATYPE) { return x & SDL_AUDIO_MASK_DATATYPE; } pub inline fn SDL_AUDIO_ISBIGENDIAN(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_ENDIAN) { return x & SDL_AUDIO_MASK_ENDIAN; } pub inline fn SDL_AUDIO_ISSIGNED(x: anytype) @TypeOf(x & SDL_AUDIO_MASK_SIGNED) { return x & SDL_AUDIO_MASK_SIGNED; } pub inline fn SDL_AUDIO_ISINT(x: anytype) @TypeOf(!(SDL_AUDIO_ISFLOAT(x) != 0)) { return !(SDL_AUDIO_ISFLOAT(x) != 0); } pub inline fn SDL_AUDIO_ISLITTLEENDIAN(x: anytype) @TypeOf(!(SDL_AUDIO_ISBIGENDIAN(x) != 0)) { return !(SDL_AUDIO_ISBIGENDIAN(x) != 0); } pub inline fn SDL_AUDIO_ISUNSIGNED(x: anytype) @TypeOf(!(SDL_AUDIO_ISSIGNED(x) != 0)) { return !(SDL_AUDIO_ISSIGNED(x) != 0); } pub const AUDIO_U8 = @as(c_int, 0x0008); pub const AUDIO_S8 = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8008, .hexadecimal); pub const AUDIO_U16LSB = @as(c_int, 0x0010); pub const AUDIO_S16LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8010, .hexadecimal); pub const AUDIO_U16MSB = @as(c_int, 0x1010); pub const AUDIO_S16MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9010, .hexadecimal); pub const AUDIO_U16 = AUDIO_U16LSB; pub const AUDIO_S16 = AUDIO_S16LSB; pub const AUDIO_S32LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8020, .hexadecimal); pub const AUDIO_S32MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9020, .hexadecimal); pub const AUDIO_S32 = AUDIO_S32LSB; pub const AUDIO_F32LSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8120, .hexadecimal); pub const AUDIO_F32MSB = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x9120, .hexadecimal); pub const AUDIO_F32 = AUDIO_F32LSB; pub const AUDIO_U16SYS = AUDIO_U16LSB; pub const AUDIO_S16SYS = AUDIO_S16LSB; pub const AUDIO_S32SYS = AUDIO_S32LSB; pub const AUDIO_F32SYS = AUDIO_F32LSB; pub const SDL_AUDIO_ALLOW_FREQUENCY_CHANGE = @as(c_int, 0x00000001); pub const SDL_AUDIO_ALLOW_FORMAT_CHANGE = @as(c_int, 0x00000002); pub const SDL_AUDIO_ALLOW_CHANNELS_CHANGE = @as(c_int, 0x00000004); pub const SDL_AUDIO_ALLOW_SAMPLES_CHANGE = @as(c_int, 0x00000008); pub const SDL_AUDIO_ALLOW_ANY_CHANGE = ((SDL_AUDIO_ALLOW_FREQUENCY_CHANGE | SDL_AUDIO_ALLOW_FORMAT_CHANGE) | SDL_AUDIO_ALLOW_CHANNELS_CHANGE) | SDL_AUDIO_ALLOW_SAMPLES_CHANGE; pub const SDL_AUDIOCVT_MAX_FILTERS = @as(c_int, 9); pub inline fn SDL_LoadWAV(file: anytype, spec: anytype, audio_buf: anytype, audio_len: anytype) @TypeOf(SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1), spec, audio_buf, audio_len)) { return SDL_LoadWAV_RW(SDL_RWFromFile(file, "rb"), @as(c_int, 1), spec, audio_buf, audio_len); } pub const SDL_MIX_MAXVOLUME = @as(c_int, 128); pub const SDL_WINDOWPOS_UNDEFINED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x1FFF0000, .hexadecimal); pub inline fn SDL_WINDOWPOS_UNDEFINED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_UNDEFINED_MASK | X) { return SDL_WINDOWPOS_UNDEFINED_MASK | X; } pub const SDL_WINDOWPOS_UNDEFINED = SDL_WINDOWPOS_UNDEFINED_DISPLAY(@as(c_int, 0)); pub inline fn SDL_WINDOWPOS_ISUNDEFINED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_UNDEFINED_MASK) { return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_UNDEFINED_MASK; } pub const SDL_WINDOWPOS_CENTERED_MASK = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 0x2FFF0000, .hexadecimal); pub inline fn SDL_WINDOWPOS_CENTERED_DISPLAY(X: anytype) @TypeOf(SDL_WINDOWPOS_CENTERED_MASK | X) { return SDL_WINDOWPOS_CENTERED_MASK | X; } pub const SDL_WINDOWPOS_CENTERED = SDL_WINDOWPOS_CENTERED_DISPLAY(@as(c_int, 0)); pub inline fn SDL_WINDOWPOS_ISCENTERED(X: anytype) @TypeOf((X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_CENTERED_MASK) { return (X & @import("std").zig.c_translation.promoteIntLiteral(c_int, 0xFFFF0000, .hexadecimal)) == SDL_WINDOWPOS_CENTERED_MASK; } pub const SDL_TOUCH_MOUSEID = @import("std").zig.c_translation.cast(u32, -@as(c_int, 1)); pub const SDL_MOUSE_TOUCHID = @import("std").zig.c_translation.cast(i64, -@as(c_int, 1)); pub inline fn SDL_TICKS_PASSED(A: anytype, B: anytype) @TypeOf(@import("std").zig.c_translation.cast(i32, B - A) <= @as(c_int, 0)) { return @import("std").zig.c_translation.cast(i32, B - A) <= @as(c_int, 0); } pub const SDL_MAJOR_VERSION = @as(c_int, 2); pub const SDL_MINOR_VERSION = @as(c_int, 0); pub const SDL_PATCHLEVEL = @as(c_int, 17); pub const SDL_NONSHAPEABLE_WINDOW = -@as(c_int, 1); pub const SDL_INVALID_SHAPE_ARGUMENT = -@as(c_int, 2); pub const SDL_WINDOW_LACKS_SHAPE = -@as(c_int, 3); pub inline fn SDL_SHAPEMODEALPHA(mode: anytype) @TypeOf(((mode == ShapeModeDefault) or (mode == ShapeModeBinarizeAlpha)) or (mode == ShapeModeReverseBinarizeAlpha)) { return ((mode == ShapeModeDefault) or (mode == ShapeModeBinarizeAlpha)) or (mode == ShapeModeReverseBinarizeAlpha); } pub const SDL_STANDARD_GRAVITY = @as(f32, 9.80665); pub const SDLK_SCANCODE_MASK = @as(c_int, 1) << @as(c_int, 30); pub inline fn SDL_SCANCODE_TO_KEYCODE(X: SDL_Scancode) SDL_Keycode { return X | SDLK_SCANCODE_MASK; } pub inline fn SDL_OutOfMemory() c_int { return SDL_Error(SDL_ENOMEM); } pub inline fn SDL_Unsupported() c_int { return SDL_Error(SDL_UNSUPPORTED); } pub inline fn SDL_InvalidParamError(param: anytype) c_int { return SDL_SetError("Parameter '%s' is invalid", param); } pub const SDL_IPHONE_MAX_GFORCE = 5.0; pub const SDL_JOYSTICK_AXIS_MAX = @as(c_int, 32767); pub const SDL_JOYSTICK_AXIS_MIN = -@import("std").zig.c_translation.promoteIntLiteral(c_int, 32768, .decimal); pub const SDL_HAT_CENTERED = @as(c_int, 0x00); pub const SDL_HAT_UP = @as(c_int, 0x01); pub const SDL_HAT_RIGHT = @as(c_int, 0x02); pub const SDL_HAT_DOWN = @as(c_int, 0x04); pub const SDL_HAT_LEFT = @as(c_int, 0x08); pub const SDL_HAT_RIGHTUP = SDL_HAT_RIGHT | SDL_HAT_UP; pub const SDL_HAT_RIGHTDOWN = SDL_HAT_RIGHT | SDL_HAT_DOWN; pub const SDL_HAT_LEFTUP = SDL_HAT_LEFT | SDL_HAT_UP; pub const SDL_HAT_LEFTDOWN = SDL_HAT_LEFT | SDL_HAT_DOWN; pub inline fn SDL_BUTTON(comptime X: c_int) c_int { return @as(c_int, 1) << (X - @as(c_int, 1)); } pub const SDL_BUTTON_LEFT = @as(c_int, 1); pub const SDL_BUTTON_MIDDLE = @as(c_int, 2); pub const SDL_BUTTON_RIGHT = @as(c_int, 3); pub const SDL_BUTTON_X1 = @as(c_int, 4); pub const SDL_BUTTON_X2 = @as(c_int, 5); pub const SDL_BUTTON_LMASK = SDL_BUTTON(SDL_BUTTON_LEFT); pub const SDL_BUTTON_MMASK = SDL_BUTTON(SDL_BUTTON_MIDDLE); pub const SDL_BUTTON_RMASK = SDL_BUTTON(SDL_BUTTON_RIGHT); pub const SDL_BUTTON_X1MASK = SDL_BUTTON(SDL_BUTTON_X1); pub const SDL_BUTTON_X2MASK = SDL_BUTTON(SDL_BUTTON_X2); pub const SDL_MUTEX_TIMEDOUT = @as(c_int, 1); pub const SDL_MUTEX_MAXWAIT = ~@as(u32, 0); pub inline fn SDL_mutexP(m: anytype) c_int { return SDL_LockMutex(m); } pub inline fn SDL_mutexV(m: anytype) c_int { return SDL_UnlockMutex(m); } pub const SDL_RELEASED = @as(c_int, 0); pub const SDL_PRESSED = @as(c_int, 1); pub const SDL_TEXTEDITINGEVENT_TEXT_SIZE = @as(c_int, 32); pub const SDL_TEXTINPUTEVENT_TEXT_SIZE = @as(c_int, 32); pub const SDL_QUERY = -@as(c_int, 1); pub const SDL_IGNORE = @as(c_int, 0); pub const SDL_DISABLE = @as(c_int, 0); pub const SDL_ENABLE = @as(c_int, 1); pub inline fn SDL_GetEventState(@"type": anytype) u8 { return SDL_EventState(@"type", SDL_QUERY); } pub const SDL_MAX_LOG_MESSAGE = @as(c_int, 4096); pub inline fn SDL_GameControllerAddMappingsFromFile(file: anytype) c_int { return SDL_GameControllerAddMappingsFromRW(SDL_RWFromFile(file, "rb"), @as(c_int, 1)); } pub const SDL_HAPTIC_CONSTANT = @as(c_uint, 1) << @as(c_int, 0); pub const SDL_HAPTIC_SINE = @as(c_uint, 1) << @as(c_int, 1); pub const SDL_HAPTIC_LEFTRIGHT = @as(c_uint, 1) << @as(c_int, 2); pub const SDL_HAPTIC_TRIANGLE = @as(c_uint, 1) << @as(c_int, 3); pub const SDL_HAPTIC_SAWTOOTHUP = @as(c_uint, 1) << @as(c_int, 4); pub const SDL_HAPTIC_SAWTOOTHDOWN = @as(c_uint, 1) << @as(c_int, 5); pub const SDL_HAPTIC_RAMP = @as(c_uint, 1) << @as(c_int, 6); pub const SDL_HAPTIC_SPRING = @as(c_uint, 1) << @as(c_int, 7); pub const SDL_HAPTIC_DAMPER = @as(c_uint, 1) << @as(c_int, 8); pub const SDL_HAPTIC_INERTIA = @as(c_uint, 1) << @as(c_int, 9); pub const SDL_HAPTIC_FRICTION = @as(c_uint, 1) << @as(c_int, 10); pub const SDL_HAPTIC_CUSTOM = @as(c_uint, 1) << @as(c_int, 11); pub const SDL_HAPTIC_GAIN = @as(c_uint, 1) << @as(c_int, 12); pub const SDL_HAPTIC_AUTOCENTER = @as(c_uint, 1) << @as(c_int, 13); pub const SDL_HAPTIC_STATUS = @as(c_uint, 1) << @as(c_int, 14); pub const SDL_HAPTIC_PAUSE = @as(c_uint, 1) << @as(c_int, 15); pub const SDL_HAPTIC_POLAR = @as(c_int, 0); pub const SDL_HAPTIC_CARTESIAN = @as(c_int, 1); pub const SDL_HAPTIC_SPHERICAL = @as(c_int, 2); pub const SDL_HAPTIC_STEERING_AXIS = @as(c_int, 3); pub const SDL_HAPTIC_INFINITY = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const SDL_HINT_ACCELEROMETER_AS_JOYSTICK = "SDL_ACCELEROMETER_AS_JOYSTICK"; pub const SDL_HINT_ALLOW_ALT_TAB_WHILE_GRABBED = "SDL_ALLOW_ALT_TAB_WHILE_GRABBED"; pub const SDL_HINT_ALLOW_TOPMOST = "SDL_ALLOW_TOPMOST"; pub const SDL_HINT_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_MAIN_FILE_VERSION"; pub const SDL_HINT_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION = "SDL_ANDROID_APK_EXPANSION_PATCH_FILE_VERSION"; pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE = "SDL_ANDROID_BLOCK_ON_PAUSE"; pub const SDL_HINT_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO = "SDL_ANDROID_BLOCK_ON_PAUSE_PAUSEAUDIO"; pub const SDL_HINT_ANDROID_TRAP_BACK_BUTTON = "SDL_ANDROID_TRAP_BACK_BUTTON"; pub const SDL_HINT_APPLE_TV_CONTROLLER_UI_EVENTS = "SDL_APPLE_TV_CONTROLLER_UI_EVENTS"; pub const SDL_HINT_APPLE_TV_REMOTE_ALLOW_ROTATION = "SDL_APPLE_TV_REMOTE_ALLOW_ROTATION"; pub const SDL_HINT_AUDIO_CATEGORY = "SDL_AUDIO_CATEGORY"; pub const SDL_HINT_AUDIO_DEVICE_APP_NAME = "SDL_AUDIO_DEVICE_APP_NAME"; pub const SDL_HINT_AUDIO_DEVICE_STREAM_NAME = "SDL_AUDIO_DEVICE_STREAM_NAME"; pub const SDL_HINT_AUDIO_DEVICE_STREAM_ROLE = "SDL_AUDIO_DEVICE_STREAM_ROLE"; pub const SDL_HINT_AUDIO_RESAMPLING_MODE = "SDL_AUDIO_RESAMPLING_MODE"; pub const SDL_HINT_AUTO_UPDATE_JOYSTICKS = "SDL_AUTO_UPDATE_JOYSTICKS"; pub const SDL_HINT_AUTO_UPDATE_SENSORS = "SDL_AUTO_UPDATE_SENSORS"; pub const SDL_HINT_BMP_SAVE_LEGACY_FORMAT = "SDL_BMP_SAVE_LEGACY_FORMAT"; pub const SDL_HINT_DISPLAY_USABLE_BOUNDS = "SDL_DISPLAY_USABLE_BOUNDS"; pub const SDL_HINT_EMSCRIPTEN_ASYNCIFY = "SDL_EMSCRIPTEN_ASYNCIFY"; pub const SDL_HINT_EMSCRIPTEN_KEYBOARD_ELEMENT = "SDL_EMSCRIPTEN_KEYBOARD_ELEMENT"; pub const SDL_HINT_ENABLE_STEAM_CONTROLLERS = "SDL_ENABLE_STEAM_CONTROLLERS"; pub const SDL_HINT_EVENT_LOGGING = "SDL_EVENT_LOGGING"; pub const SDL_HINT_FRAMEBUFFER_ACCELERATION = "SDL_FRAMEBUFFER_ACCELERATION"; pub const SDL_HINT_GAMECONTROLLERCONFIG = "SDL_GAMECONTROLLERCONFIG"; pub const SDL_HINT_GAMECONTROLLERCONFIG_FILE = "SDL_GAMECONTROLLERCONFIG_FILE"; pub const SDL_HINT_GAMECONTROLLERTYPE = "SDL_GAMECONTROLLERTYPE"; pub const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES = "SDL_GAMECONTROLLER_IGNORE_DEVICES"; pub const SDL_HINT_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT = "SDL_GAMECONTROLLER_IGNORE_DEVICES_EXCEPT"; pub const SDL_HINT_GAMECONTROLLER_USE_BUTTON_LABELS = "SDL_GAMECONTROLLER_USE_BUTTON_LABELS"; pub const SDL_HINT_GRAB_KEYBOARD = "SDL_GRAB_KEYBOARD"; pub const SDL_HINT_IDLE_TIMER_DISABLED = "SDL_IOS_IDLE_TIMER_DISABLED"; pub const SDL_HINT_IME_INTERNAL_EDITING = "SDL_IME_INTERNAL_EDITING"; pub const SDL_HINT_IOS_HIDE_HOME_INDICATOR = "SDL_IOS_HIDE_HOME_INDICATOR"; pub const SDL_HINT_JOYSTICK_ALLOW_BACKGROUND_EVENTS = "SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS"; pub const SDL_HINT_JOYSTICK_HIDAPI = "SDL_JOYSTICK_HIDAPI"; pub const SDL_HINT_JOYSTICK_HIDAPI_GAMECUBE = "SDL_JOYSTICK_HIDAPI_GAMECUBE"; pub const SDL_HINT_JOYSTICK_HIDAPI_JOY_CONS = "SDL_JOYSTICK_HIDAPI_JOY_CONS"; pub const SDL_HINT_JOYSTICK_HIDAPI_LUNA = "SDL_JOYSTICK_HIDAPI_LUNA"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS4 = "SDL_JOYSTICK_HIDAPI_PS4"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS4_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS4_RUMBLE"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5 = "SDL_JOYSTICK_HIDAPI_PS5"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5_PLAYER_LED = "SDL_JOYSTICK_HIDAPI_PS5_PLAYER_LED"; pub const SDL_HINT_JOYSTICK_HIDAPI_PS5_RUMBLE = "SDL_JOYSTICK_HIDAPI_PS5_RUMBLE"; pub const SDL_HINT_JOYSTICK_HIDAPI_STADIA = "SDL_JOYSTICK_HIDAPI_STADIA"; pub const SDL_HINT_JOYSTICK_HIDAPI_STEAM = "SDL_JOYSTICK_HIDAPI_STEAM"; pub const SDL_HINT_JOYSTICK_HIDAPI_SWITCH = "SDL_JOYSTICK_HIDAPI_SWITCH"; pub const SDL_HINT_JOYSTICK_HIDAPI_SWITCH_HOME_LED = "SDL_JOYSTICK_HIDAPI_SWITCH_HOME_LED"; pub const SDL_HINT_JOYSTICK_HIDAPI_XBOX = "SDL_JOYSTICK_HIDAPI_XBOX"; pub const SDL_HINT_JOYSTICK_RAWINPUT = "SDL_JOYSTICK_RAWINPUT"; pub const SDL_HINT_JOYSTICK_RAWINPUT_CORRELATE_XINPUT = "SDL_JOYSTICK_RAWINPUT_CORRELATE_XINPUT"; pub const SDL_HINT_JOYSTICK_THREAD = "SDL_JOYSTICK_THREAD"; pub const SDL_HINT_KMSDRM_REQUIRE_DRM_MASTER = "SDL_KMSDRM_REQUIRE_DRM_MASTER"; pub const SDL_HINT_LINUX_JOYSTICK_DEADZONES = "SDL_LINUX_JOYSTICK_DEADZONES"; pub const SDL_HINT_MAC_BACKGROUND_APP = "SDL_MAC_BACKGROUND_APP"; pub const SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK = "SDL_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK"; pub const SDL_HINT_MOUSE_DOUBLE_CLICK_RADIUS = "SDL_MOUSE_DOUBLE_CLICK_RADIUS"; pub const SDL_HINT_MOUSE_DOUBLE_CLICK_TIME = "SDL_MOUSE_DOUBLE_CLICK_TIME"; pub const SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH = "SDL_MOUSE_FOCUS_CLICKTHROUGH"; pub const SDL_HINT_MOUSE_NORMAL_SPEED_SCALE = "SDL_MOUSE_NORMAL_SPEED_SCALE"; pub const SDL_HINT_MOUSE_RELATIVE_MODE_WARP = "SDL_MOUSE_RELATIVE_MODE_WARP"; pub const SDL_HINT_MOUSE_RELATIVE_SCALING = "SDL_MOUSE_RELATIVE_SCALING"; pub const SDL_HINT_MOUSE_RELATIVE_SPEED_SCALE = "SDL_MOUSE_RELATIVE_SPEED_SCALE"; pub const SDL_HINT_MOUSE_TOUCH_EVENTS = "SDL_MOUSE_TOUCH_EVENTS"; pub const SDL_HINT_NO_SIGNAL_HANDLERS = "SDL_NO_SIGNAL_HANDLERS"; pub const SDL_HINT_OPENGL_ES_DRIVER = "SDL_OPENGL_ES_DRIVER"; pub const SDL_HINT_ORIENTATIONS = "SDL_IOS_ORIENTATIONS"; pub const SDL_HINT_PREFERRED_LOCALES = "SDL_PREFERRED_LOCALES"; pub const SDL_HINT_QTWAYLAND_CONTENT_ORIENTATION = "SDL_QTWAYLAND_CONTENT_ORIENTATION"; pub const SDL_HINT_QTWAYLAND_WINDOW_FLAGS = "SDL_QTWAYLAND_WINDOW_FLAGS"; pub const SDL_HINT_RENDER_BATCHING = "SDL_RENDER_BATCHING"; pub const SDL_HINT_RENDER_DIRECT3D11_DEBUG = "SDL_RENDER_DIRECT3D11_DEBUG"; pub const SDL_HINT_RENDER_DIRECT3D_THREADSAFE = "SDL_RENDER_DIRECT3D_THREADSAFE"; pub const SDL_HINT_RENDER_DRIVER = "SDL_RENDER_DRIVER"; pub const SDL_HINT_RENDER_LOGICAL_SIZE_MODE = "SDL_RENDER_LOGICAL_SIZE_MODE"; pub const SDL_HINT_RENDER_OPENGL_SHADERS = "SDL_RENDER_OPENGL_SHADERS"; pub const SDL_HINT_RENDER_SCALE_QUALITY = "SDL_RENDER_SCALE_QUALITY"; pub const SDL_HINT_RENDER_VSYNC = "SDL_RENDER_VSYNC"; pub const SDL_HINT_RETURN_KEY_HIDES_IME = "SDL_RETURN_KEY_HIDES_IME"; pub const SDL_HINT_RPI_VIDEO_LAYER = "SDL_RPI_VIDEO_LAYER"; pub const SDL_HINT_THREAD_FORCE_REALTIME_TIME_CRITICAL = "SDL_THREAD_FORCE_REALTIME_TIME_CRITICAL"; pub const SDL_HINT_THREAD_PRIORITY_POLICY = "SDL_THREAD_PRIORITY_POLICY"; pub const SDL_HINT_THREAD_STACK_SIZE = "SDL_THREAD_STACK_SIZE"; pub const SDL_HINT_TIMER_RESOLUTION = "SDL_TIMER_RESOLUTION"; pub const SDL_HINT_TOUCH_MOUSE_EVENTS = "SDL_TOUCH_MOUSE_EVENTS"; pub const SDL_HINT_TV_REMOTE_AS_JOYSTICK = "SDL_TV_REMOTE_AS_JOYSTICK"; pub const SDL_HINT_VIDEO_ALLOW_SCREENSAVER = "SDL_VIDEO_ALLOW_SCREENSAVER"; pub const SDL_HINT_VIDEO_DOUBLE_BUFFER = "SDL_VIDEO_DOUBLE_BUFFER"; pub const SDL_HINT_VIDEO_EXTERNAL_CONTEXT = "SDL_VIDEO_EXTERNAL_CONTEXT"; pub const SDL_HINT_VIDEO_HIGHDPI_DISABLED = "SDL_VIDEO_HIGHDPI_DISABLED"; pub const SDL_HINT_VIDEO_MAC_FULLSCREEN_SPACES = "SDL_VIDEO_MAC_FULLSCREEN_SPACES"; pub const SDL_HINT_VIDEO_MINIMIZE_ON_FOCUS_LOSS = "SDL_VIDEO_MINIMIZE_ON_FOCUS_LOSS"; pub const SDL_HINT_VIDEO_WAYLAND_ALLOW_LIBDECOR = "SDL_VIDEO_WAYLAND_ALLOW_LIBDECOR"; pub const SDL_HINT_VIDEO_WINDOW_SHARE_PIXEL_FORMAT = "SDL_VIDEO_WINDOW_SHARE_PIXEL_FORMAT"; pub const SDL_HINT_VIDEO_WIN_D3DCOMPILER = "SDL_VIDEO_WIN_D3DCOMPILER"; pub const SDL_HINT_VIDEO_X11_FORCE_EGL = "SDL_VIDEO_X11_FORCE_EGL"; pub const SDL_HINT_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR = "SDL_VIDEO_X11_NET_WM_BYPASS_COMPOSITOR"; pub const SDL_HINT_VIDEO_X11_NET_WM_PING = "SDL_VIDEO_X11_NET_WM_PING"; pub const SDL_HINT_VIDEO_X11_WINDOW_VISUALID = "SDL_VIDEO_X11_WINDOW_VISUALID"; pub const SDL_HINT_VIDEO_X11_XINERAMA = "SDL_VIDEO_X11_XINERAMA"; pub const SDL_HINT_VIDEO_X11_XRANDR = "SDL_VIDEO_X11_XRANDR"; pub const SDL_HINT_VIDEO_X11_XVIDMODE = "SDL_VIDEO_X11_XVIDMODE"; pub const SDL_HINT_WAVE_FACT_CHUNK = "SDL_WAVE_FACT_CHUNK"; pub const SDL_HINT_WAVE_RIFF_CHUNK_SIZE = "SDL_WAVE_RIFF_CHUNK_SIZE"; pub const SDL_HINT_WAVE_TRUNCATION = "SDL_WAVE_TRUNCATION"; pub const SDL_HINT_WINDOWS_DISABLE_THREAD_NAMING = "SDL_WINDOWS_DISABLE_THREAD_NAMING"; pub const SDL_HINT_WINDOWS_ENABLE_MESSAGELOOP = "SDL_WINDOWS_ENABLE_MESSAGELOOP"; pub const SDL_HINT_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS = "SDL_WINDOWS_FORCE_MUTEX_CRITICAL_SECTIONS"; pub const SDL_HINT_WINDOWS_FORCE_SEMAPHORE_KERNEL = "SDL_WINDOWS_FORCE_SEMAPHORE_KERNEL"; pub const SDL_HINT_WINDOWS_INTRESOURCE_ICON = "SDL_WINDOWS_INTRESOURCE_ICON"; pub const SDL_HINT_WINDOWS_INTRESOURCE_ICON_SMALL = "SDL_WINDOWS_INTRESOURCE_ICON_SMALL"; pub const SDL_HINT_WINDOWS_NO_CLOSE_ON_ALT_F4 = "SDL_WINDOWS_NO_CLOSE_ON_ALT_F4"; pub const SDL_HINT_WINDOWS_USE_D3D9EX = "SDL_WINDOWS_USE_D3D9EX"; pub const SDL_HINT_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN = "SDL_WINDOW_FRAME_USABLE_WHILE_CURSOR_HIDDEN"; pub const SDL_HINT_WINRT_HANDLE_BACK_BUTTON = "SDL_WINRT_HANDLE_BACK_BUTTON"; pub const SDL_HINT_WINRT_PRIVACY_POLICY_LABEL = "SDL_WINRT_PRIVACY_POLICY_LABEL"; pub const SDL_HINT_WINRT_PRIVACY_POLICY_URL = "SDL_WINRT_PRIVACY_POLICY_URL"; pub const SDL_HINT_X11_FORCE_OVERRIDE_REDIRECT = "SDL_X11_FORCE_OVERRIDE_REDIRECT"; pub const SDL_HINT_XINPUT_ENABLED = "SDL_XINPUT_ENABLED"; pub const SDL_HINT_XINPUT_USE_OLD_JOYSTICK_MAPPING = "SDL_XINPUT_USE_OLD_JOYSTICK_MAPPING"; pub const SDL_HINT_AUDIO_INCLUDE_MONITORS = "SDL_AUDIO_INCLUDE_MONITORS";
src/binding/sdl.zig
const std = @import("std"); const cc = @import("c.zig").c; const Error = @import("errors.zig").Error; const getError = @import("errors.zig").getError; const internal_debug = @import("internal_debug.zig"); /// enum containing all glfw keys pub const Key = enum(c_int) { /// The unknown key unknown = cc.GLFW_KEY_UNKNOWN, /// Printable keys space = cc.GLFW_KEY_SPACE, apostrophe = cc.GLFW_KEY_APOSTROPHE, comma = cc.GLFW_KEY_COMMA, minus = cc.GLFW_KEY_MINUS, period = cc.GLFW_KEY_PERIOD, slash = cc.GLFW_KEY_SLASH, zero = cc.GLFW_KEY_0, one = cc.GLFW_KEY_1, two = cc.GLFW_KEY_2, three = cc.GLFW_KEY_3, four = cc.GLFW_KEY_4, five = cc.GLFW_KEY_5, six = cc.GLFW_KEY_6, seven = cc.GLFW_KEY_7, eight = cc.GLFW_KEY_8, nine = cc.GLFW_KEY_9, semicolon = cc.GLFW_KEY_SEMICOLON, equal = cc.GLFW_KEY_EQUAL, a = cc.GLFW_KEY_A, b = cc.GLFW_KEY_B, c = cc.GLFW_KEY_C, d = cc.GLFW_KEY_D, e = cc.GLFW_KEY_E, f = cc.GLFW_KEY_F, g = cc.GLFW_KEY_G, h = cc.GLFW_KEY_H, i = cc.GLFW_KEY_I, j = cc.GLFW_KEY_J, k = cc.GLFW_KEY_K, l = cc.GLFW_KEY_L, m = cc.GLFW_KEY_M, n = cc.GLFW_KEY_N, o = cc.GLFW_KEY_O, p = cc.GLFW_KEY_P, q = cc.GLFW_KEY_Q, r = cc.GLFW_KEY_R, s = cc.GLFW_KEY_S, t = cc.GLFW_KEY_T, u = cc.GLFW_KEY_U, v = cc.GLFW_KEY_V, w = cc.GLFW_KEY_W, x = cc.GLFW_KEY_X, y = cc.GLFW_KEY_Y, z = cc.GLFW_KEY_Z, left_bracket = cc.GLFW_KEY_LEFT_BRACKET, backslash = cc.GLFW_KEY_BACKSLASH, right_bracket = cc.GLFW_KEY_RIGHT_BRACKET, grave_accent = cc.GLFW_KEY_GRAVE_ACCENT, world_1 = cc.GLFW_KEY_WORLD_1, // non-US #1 world_2 = cc.GLFW_KEY_WORLD_2, // non-US #2 // Function keys escape = cc.GLFW_KEY_ESCAPE, enter = cc.GLFW_KEY_ENTER, tab = cc.GLFW_KEY_TAB, backspace = cc.GLFW_KEY_BACKSPACE, insert = cc.GLFW_KEY_INSERT, delete = cc.GLFW_KEY_DELETE, right = cc.GLFW_KEY_RIGHT, left = cc.GLFW_KEY_LEFT, down = cc.GLFW_KEY_DOWN, up = cc.GLFW_KEY_UP, page_up = cc.GLFW_KEY_PAGE_UP, page_down = cc.GLFW_KEY_PAGE_DOWN, home = cc.GLFW_KEY_HOME, end = cc.GLFW_KEY_END, caps_lock = cc.GLFW_KEY_CAPS_LOCK, scroll_lock = cc.GLFW_KEY_SCROLL_LOCK, num_lock = cc.GLFW_KEY_NUM_LOCK, print_screen = cc.GLFW_KEY_PRINT_SCREEN, pause = cc.GLFW_KEY_PAUSE, F1 = cc.GLFW_KEY_F1, F2 = cc.GLFW_KEY_F2, F3 = cc.GLFW_KEY_F3, F4 = cc.GLFW_KEY_F4, F5 = cc.GLFW_KEY_F5, F6 = cc.GLFW_KEY_F6, F7 = cc.GLFW_KEY_F7, F8 = cc.GLFW_KEY_F8, F9 = cc.GLFW_KEY_F9, F10 = cc.GLFW_KEY_F10, F11 = cc.GLFW_KEY_F11, F12 = cc.GLFW_KEY_F12, F13 = cc.GLFW_KEY_F13, F14 = cc.GLFW_KEY_F14, F15 = cc.GLFW_KEY_F15, F16 = cc.GLFW_KEY_F16, F17 = cc.GLFW_KEY_F17, F18 = cc.GLFW_KEY_F18, F19 = cc.GLFW_KEY_F19, F20 = cc.GLFW_KEY_F20, F21 = cc.GLFW_KEY_F21, F22 = cc.GLFW_KEY_F22, F23 = cc.GLFW_KEY_F23, F24 = cc.GLFW_KEY_F24, F25 = cc.GLFW_KEY_F25, kp_0 = cc.GLFW_KEY_KP_0, kp_1 = cc.GLFW_KEY_KP_1, kp_2 = cc.GLFW_KEY_KP_2, kp_3 = cc.GLFW_KEY_KP_3, kp_4 = cc.GLFW_KEY_KP_4, kp_5 = cc.GLFW_KEY_KP_5, kp_6 = cc.GLFW_KEY_KP_6, kp_7 = cc.GLFW_KEY_KP_7, kp_8 = cc.GLFW_KEY_KP_8, kp_9 = cc.GLFW_KEY_KP_9, kp_decimal = cc.GLFW_KEY_KP_DECIMAL, kp_divide = cc.GLFW_KEY_KP_DIVIDE, kp_multiply = cc.GLFW_KEY_KP_MULTIPLY, kp_subtract = cc.GLFW_KEY_KP_SUBTRACT, kp_add = cc.GLFW_KEY_KP_ADD, kp_enter = cc.GLFW_KEY_KP_ENTER, kp_equal = cc.GLFW_KEY_KP_EQUAL, left_shift = cc.GLFW_KEY_LEFT_SHIFT, left_control = cc.GLFW_KEY_LEFT_CONTROL, left_alt = cc.GLFW_KEY_LEFT_ALT, left_super = cc.GLFW_KEY_LEFT_SUPER, right_shift = cc.GLFW_KEY_RIGHT_SHIFT, right_control = cc.GLFW_KEY_RIGHT_CONTROL, right_alt = cc.GLFW_KEY_RIGHT_ALT, right_super = cc.GLFW_KEY_RIGHT_SUPER, menu = cc.GLFW_KEY_MENU, pub inline fn last() Key { return @intToEnum(Key, cc.GLFW_KEY_LAST); } /// Returns the layout-specific name of the specified printable key. /// /// This function returns the name of the specified printable key, encoded as UTF-8. This is /// typically the character that key would produce without any modifier keys, intended for /// displaying key bindings to the user. For dead keys, it is typically the diacritic it would add /// to a character. /// /// __Do not use this function__ for text input (see input_char). You will break text input for many /// languages even if it happens to work for yours. /// /// If the key is `glfw.key.unknown`, the scancode is used to identify the key, otherwise the /// scancode is ignored. If you specify a non-printable key, or `glfw.key.unknown` and a scancode /// that maps to a non-printable key, this function returns null but does not emit an error. /// /// This behavior allows you to always pass in the arguments in the key callback (see input_key) /// without modification. /// /// The printable keys are: /// /// - `glfw.Key.apostrophe` /// - `glfw.Key.comma` /// - `glfw.Key.minus` /// - `glfw.Key.period` /// - `glfw.Key.slash` /// - `glfw.Key.semicolon` /// - `glfw.Key.equal` /// - `glfw.Key.left_bracket` /// - `glfw.Key.right_bracket` /// - `glfw.Key.backslash` /// - `glfw.Key.world_1` /// - `glfw.Key.world_2` /// - `glfw.Key.0` to `glfw.key.9` /// - `glfw.Key.a` to `glfw.key.z` /// - `glfw.Key.kp_0` to `glfw.key.kp_9` /// - `glfw.Key.kp_decimal` /// - `glfw.Key.kp_divide` /// - `glfw.Key.kp_multiply` /// - `glfw.Key.kp_subtract` /// - `glfw.Key.kp_add` /// - `glfw.Key.kp_equal` /// /// Names for printable keys depend on keyboard layout, while names for non-printable keys are the /// same across layouts but depend on the application language and should be localized along with /// other user interface text. /// /// @param[in] key The key to query, or `glfw.key.unknown`. /// @param[in] scancode The scancode of the key to query. /// @return The UTF-8 encoded, layout-specific name of the key, or null. /// /// Possible errors include glfw.Error.NotInitialized and glfw.Error.PlatformError. /// /// The contents of the returned string may change when a keyboard layout change event is received. /// /// @pointer_lifetime The returned string is allocated and freed by GLFW. You should not free it /// yourself. It is valid until the library is terminated. /// /// @thread_safety This function must only be called from the main thread. /// /// see also: input_key_name pub inline fn getName(self: Key, scancode: isize) Error!?[:0]const u8 { internal_debug.assertInitialized(); const name_opt = cc.glfwGetKeyName(@enumToInt(self), @intCast(c_int, scancode)); getError() catch |err| return switch (err) { Error.PlatformError => err, else => unreachable, }; return if (name_opt) |name| std.mem.span(name) else null; } /// Returns the platform-specific scancode of the specified key. /// /// This function returns the platform-specific scancode of the specified key. /// /// If the key is `glfw.key.UNKNOWN` or does not exist on the keyboard this method will return `-1`. /// /// @param[in] key Any named key (see keys). /// @return The platform-specific scancode for the key. /// /// Possible errors include glfw.Error.NotInitialized, glfw.Error.InvalidEnum and glfw.Error.PlatformError. /// /// @thread_safety This function may be called from any thread. pub inline fn getScancode(self: Key) Error!isize { internal_debug.assertInitialized(); const scancode = cc.glfwGetKeyScancode(@enumToInt(self)); getError() catch |err| return switch (err) { Error.PlatformError => err, else => unreachable, }; return scancode; } }; test "getName" { const glfw = @import("main.zig"); try glfw.init(.{}); defer glfw.terminate(); _ = glfw.Key.a.getName(0) catch |err| std.debug.print("failed to get key name, not supported? error={}\n", .{err}); } test "getScancode" { const glfw = @import("main.zig"); try glfw.init(.{}); defer glfw.terminate(); _ = glfw.Key.a.getScancode() catch |err| std.debug.print("failed to get key scancode, not supported? error={}\n", .{err}); }
glfw/src/key.zig
const std = @import("std"); const mem = std.mem; const Halfwidth = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 8361, hi: u21 = 65518, pub fn init(allocator: *mem.Allocator) !Halfwidth { var instance = Halfwidth{ .allocator = allocator, .array = try allocator.alloc(bool, 57158), }; mem.set(bool, instance.array, false); var index: u21 = 0; instance.array[0] = true; instance.array[57016] = true; instance.array[57017] = true; instance.array[57018] = true; index = 57019; while (index <= 57020) : (index += 1) { instance.array[index] = true; } index = 57021; while (index <= 57030) : (index += 1) { instance.array[index] = true; } instance.array[57031] = true; index = 57032; while (index <= 57076) : (index += 1) { instance.array[index] = true; } index = 57077; while (index <= 57078) : (index += 1) { instance.array[index] = true; } index = 57079; while (index <= 57109) : (index += 1) { instance.array[index] = true; } index = 57113; while (index <= 57118) : (index += 1) { instance.array[index] = true; } index = 57121; while (index <= 57126) : (index += 1) { instance.array[index] = true; } index = 57129; while (index <= 57134) : (index += 1) { instance.array[index] = true; } index = 57137; while (index <= 57139) : (index += 1) { instance.array[index] = true; } instance.array[57151] = true; index = 57152; while (index <= 57155) : (index += 1) { instance.array[index] = true; } index = 57156; while (index <= 57157) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *Halfwidth) void { self.allocator.free(self.array); } // isHalfwidth checks if cp is of the kind Halfwidth. pub fn isHalfwidth(self: Halfwidth, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedEastAsianWidth/Halfwidth.zig
const std = @import("std"); const builtin = @import("builtin"); const File = std.fs.File; const tcflag_t = std.os.tcflag_t; const unsupported_term = [_][]const u8{ "dumb", "cons25", "emacs" }; pub fn isUnsupportedTerm() bool { const env_var = std.os.getenv("TERM") orelse return false; return for (unsupported_term) |t| { if (std.ascii.eqlIgnoreCase(env_var, t)) break true; } else false; } pub fn enableRawMode(fd: File) !std.os.termios { const orig = try std.os.tcgetattr(fd.handle); var raw = orig; // TODO fix hardcoding of linux raw.iflag &= ~(@intCast(tcflag_t, std.os.linux.BRKINT) | @intCast(tcflag_t, std.os.linux.ICRNL) | @intCast(tcflag_t, std.os.linux.INPCK) | @intCast(tcflag_t, std.os.linux.ISTRIP) | @intCast(tcflag_t, std.os.linux.IXON)); raw.oflag &= ~(@intCast(tcflag_t, std.os.linux.OPOST)); raw.cflag |= (@intCast(tcflag_t, std.os.linux.CS8)); raw.lflag &= ~(@intCast(tcflag_t, std.os.linux.ECHO) | @intCast(tcflag_t, std.os.linux.ICANON) | @intCast(tcflag_t, std.os.linux.IEXTEN) | @intCast(tcflag_t, std.os.linux.ISIG)); // FIXME // raw.cc[std.os.VMIN] = 1; // raw.cc[std.os.VTIME] = 0; try std.os.tcsetattr(fd.handle, std.os.TCSA.FLUSH, raw); return orig; } pub fn disableRawMode(fd: File, orig: std.os.termios) void { std.os.tcsetattr(fd.handle, std.os.TCSA.FLUSH, orig) catch {}; } fn getCursorPosition(in: File, out: File) !usize { var buf: [32]u8 = undefined; var reader = in.reader(); // Tell terminal to report cursor to in try out.writeAll("\x1B[6n"); // Read answer const answer = (try reader.readUntilDelimiterOrEof(&buf, 'R')) orelse return error.CursorPos; // Parse answer if (!std.mem.startsWith(u8, "\x1B[", answer)) return error.CursorPos; var iter = std.mem.split(u8, answer[2..], ";"); _ = iter.next() orelse return error.CursorPos; const x = iter.next() orelse return error.CursorPos; return try std.fmt.parseInt(usize, x, 10); } fn getColumnsFallback(in: File, out: File) !usize { var writer = out.writer(); const orig_cursor_pos = try getCursorPosition(in, out); try writer.print("\x1B[999C", .{}); const cols = try getCursorPosition(in, out); try writer.print("\x1B[{}D", .{orig_cursor_pos}); return cols; } pub fn getColumns(in: File, out: File) !usize { switch (builtin.os.tag) { .linux => { var wsz: std.os.linux.winsize = undefined; if (std.os.linux.ioctl(in.handle, std.os.linux.T.IOCGWINSZ, @ptrToInt(&wsz)) == 0) { return wsz.ws_col; } else { return try getColumnsFallback(in, out); } }, else => return try getColumnsFallback(in, out), } } pub fn clearScreen() !void { const stdout = std.io.getStdErr(); try stdout.writeAll("\x1b[H\x1b[2J"); } pub fn beep() !void { const stderr = std.io.getStdErr(); try stderr.writeAll("\x07"); }
src/term.zig
const std = @import("std"); const mem = std.mem; const os = std.os; const fs = std.fs; const net = std.net; const fd_t = os.fd_t; const assert = std.debug.assert; const wl = @import("wl.zig"); const WireConnection = @import("common/WireConnection.zig"); const Buffer = @import("common/Buffer.zig"); const Message = @import("common/Message.zig"); const ObjectMap = @import("common/object_map.zig").ObjectMap; pub const Connection = struct { // TODO: make this not public pub const ObjectData = struct { version: u32, handler: fn (conn: *Connection, msg: Message, fds: *Buffer) void, user_data: usize, }; wire_conn: WireConnection, object_map: ObjectMap(ObjectData, .client), allocator: mem.Allocator, // TODO: explicit error set pub fn init(allocator: mem.Allocator, display_name: ?[]const u8) !Connection { const socket = blk: { if (os.getenv("WAYLAND_SOCKET")) |wayland_socket| { // TODO: unset environment variable const fd = try std.fmt.parseInt(c_int, wayland_socket, 10); const flags = try std.os.fcntl(fd, std.os.F.GETFD, 0); _ = try std.os.fcntl(fd, std.os.F.SETFD, flags | std.os.FD_CLOEXEC); break :blk net.Stream{ .handle = fd, }; } const display_option = display_name orelse os.getenv("WAYLAND_DISPLAY") orelse "wayland-0"; if (display_option.len > 0 and display_option[0] == '/') { break :blk try net.connectUnixSocket(display_option); } const runtime_dir = os.getenv("XDG_RUNTIME_DIR") orelse return error.XdgRuntimeDirNotSet; var buf: [os.PATH_MAX]u8 = undefined; var bufalloc = std.heap.FixedBufferAllocator.init(&buf); const path = fs.path.join(bufalloc.allocator(), &[_][]const u8{ runtime_dir, display_option, }) catch |err| switch (err) { error.OutOfMemory => return error.PathTooLong, }; break :blk try net.connectUnixSocket(path); }; var object_map = ObjectMap(ObjectData, .client).init(allocator); errdefer object_map.deinit(); const display_data = try object_map.createId(1); assert(display_data.id == 1); display_data.object.* = ObjectData{ .version = 1, .handler = wl.Display.defaultHandler, .user_data = 0, }; const conn = Connection{ .wire_conn = WireConnection.init(socket), .object_map = object_map, .allocator = allocator, }; return conn; } pub fn deinit(conn: *Connection) void { conn.object_map.deinit(); conn.wire_conn.socket.close(); } pub fn read(conn: *Connection) !void { try conn.wire_conn.read(); } pub fn flush(conn: *Connection) !void { try conn.wire_conn.flush(); } pub fn dispatch(conn: *Connection) !void { var fds = Buffer.init(); while (conn.wire_conn.in.getMessage()) |msg| { const object_data = conn.object_map.get(msg.id); object_data.?.handler(conn, msg, &fds); } } pub fn getRegistry(conn: *Connection) !wl.Registry { const display = wl.Display{ .id = 1 }; return display.getRegistry(conn); } }; test "Connection" { std.testing.refAllDecls(Connection); } test "Connection: raw request globals" { var conn = try Connection.init(std.testing.allocator, null); defer conn.deinit(); try conn.wire_conn.out.putUInt(1); try conn.wire_conn.out.putUInt((12 << 16) | 1); try conn.wire_conn.out.putUInt(2); try conn.flush(); try conn.read(); } test "Connection: request globals with struct" { var conn = try Connection.init(std.testing.allocator, null); defer conn.deinit(); const registry_data = try conn.object_map.create(); registry_data.object.* = Connection.ObjectData{ .version = 1, .handler = wl.Registry.defaultHandler, .user_data = 0, }; const registry = wl.Registry{ .id = registry_data.id }; const req = wl.Display.Request.GetRegistry{ .registry = registry }; const display_id = 1; try req.marshal(display_id, &conn.wire_conn.out); try conn.flush(); try conn.read(); try conn.dispatch(); } test "Connection: request globals with method" { var conn = try Connection.init(std.testing.allocator, null); defer conn.deinit(); const registry = try conn.getRegistry(); const shm = try registry.bind(&conn, 1, wl.Shm, 1); _ = shm; try conn.flush(); try conn.read(); try conn.dispatch(); }
src/client.zig
const std = @import("std"); const builtin = @import("builtin"); pub fn build(b: *std.build.Builder) !void { b.setPreferredReleaseMode(.ReleaseFast); const target = b.standardTargetOptions(.{}); const mode = b.standardReleaseOptions(); // Main build step const fastfec_cli = b.addExecutable("fastfec", null); fastfec_cli.setTarget(target); fastfec_cli.setBuildMode(mode); fastfec_cli.install(); // Add pcre and curl fastfec_cli.linkLibC(); if (builtin.os.tag == .windows) { fastfec_cli.linkSystemLibrary("ws2_32"); fastfec_cli.linkSystemLibrary("advapi32"); fastfec_cli.linkSystemLibrary("crypt32"); fastfec_cli.linkSystemLibrary("pcre"); fastfec_cli.linkSystemLibrary("libcurl"); fastfec_cli.linkSystemLibraryName("zlib"); } else { fastfec_cli.linkSystemLibrary("libpcre"); fastfec_cli.linkSystemLibrary("curl"); } fastfec_cli.addCSourceFiles(&libSources, &buildOptions); fastfec_cli.addCSourceFiles(&.{ "src/urlopen.c", "src/main.c", }, &buildOptions); // Library build step const fastfec_lib = b.addSharedLibrary("fastfec", null, .unversioned); fastfec_lib.setTarget(target); fastfec_lib.setBuildMode(mode); fastfec_lib.install(); fastfec_lib.linkLibC(); if (builtin.os.tag == .windows) { fastfec_lib.linkSystemLibrary("pcre"); } else { fastfec_lib.linkSystemLibrary("libpcre"); } fastfec_lib.addCSourceFiles(&libSources, &buildOptions); // Test step var prev_test_step: ?*std.build.Step = null; for (tests) |test_file| { const base_file = std.fs.path.basename(test_file); const subtest_exe = b.addExecutable(base_file, null); subtest_exe.linkLibC(); subtest_exe.addCSourceFiles(&testIncludes, &buildOptions); subtest_exe.addCSourceFile(test_file, &buildOptions); // Link PCRE if (builtin.os.tag == .windows) { subtest_exe.linkSystemLibrary("pcre"); } else { subtest_exe.linkSystemLibrary("libpcre"); } const subtest_cmd = subtest_exe.run(); if (prev_test_step != null) { subtest_cmd.step.dependOn(prev_test_step.?); } prev_test_step = &subtest_cmd.step; } const test_steps = prev_test_step.?; const test_step = b.step("test", "Run unit tests"); test_step.dependOn(test_steps); } const libSources = [_][]const u8{ "src/buffer.c", "src/memory.c", "src/encoding.c", "src/csv.c", "src/writer.c", "src/fec.c", }; const tests = [_][]const u8{ "src/buffer_test.c", "src/csv_test.c", "src/writer_test.c" }; const testIncludes = [_][]const u8{ "src/buffer.c", "src/memory.c", "src/encoding.c", "src/csv.c", "src/writer.c", }; const buildOptions = [_][]const u8{ "-std=c11", "-pedantic", "-Wall", "-W", "-Wno-missing-field-initializers", };
build.zig
const std = @import("std"); const assert = std.debug.assert; const tools = @import("tools"); const Vec2 = tools.Vec2; const Map = tools.Map(u8, 250, 250, false); const DEAD = 100; const Kart = struct { p: Vec2, d: Vec2, seq: u32 = 0, fn lessThan(_: void, lhs: Kart, rhs: Kart) bool { return Vec2.lessThan({}, lhs.p, rhs.p); } }; pub fn run(input_text: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const params: struct { tracks: *const Map, init_karts: []const Kart } = blk: { const tracks = try allocator.create(Map); errdefer allocator.destroy(tracks); tracks.bbox = tools.BBox.empty; tracks.default_tile = 0; const karts = try allocator.alloc(Kart, 100); errdefer allocator.free(karts); var nb_kart: usize = 0; var y: i32 = 0; var it = std.mem.tokenize(u8, input_text, "\n\r"); while (it.next()) |line| { for (line) |sq, i| { const p = Vec2{ .x = @intCast(i32, i), .y = y }; switch (sq) { '^' => { tracks.set(p, '|'); karts[nb_kart] = Kart{ .p = p, .d = Vec2{ .x = 0, .y = -1 } }; nb_kart += 1; }, 'v' => { tracks.set(p, '|'); karts[nb_kart] = Kart{ .p = p, .d = Vec2{ .x = 0, .y = 1 } }; nb_kart += 1; }, '<' => { tracks.set(p, '-'); karts[nb_kart] = Kart{ .p = p, .d = Vec2{ .x = -1, .y = 0 } }; nb_kart += 1; }, '>' => { tracks.set(p, '-'); karts[nb_kart] = Kart{ .p = p, .d = Vec2{ .x = 1, .y = 0 } }; nb_kart += 1; }, '|' => tracks.set(p, '|'), '-' => tracks.set(p, '-'), '+' => tracks.set(p, '+'), '\\' => tracks.set(p, '\\'), '/' => tracks.set(p, '/'), ' ' => tracks.set(p, ' '), else => { std.debug.print("unknown char '{c}'\n", .{sq}); return error.UnsupportedInput; }, } } y += 1; } break :blk .{ .tracks = tracks, .init_karts = karts[0..nb_kart] }; }; defer allocator.destroy(params.tracks); defer allocator.free(params.init_karts); //var buf: [5000]u8 = undefined; //std.debug.print("{}\n", .{params.tracks.printToBuf(null, null, null, &buf)}); // part1 (buggué car fait tout les karts en un coup et donc ils pourraient se croiser sans crasher "effet tunnel" -> mais ça passe) const ans1 = ans: { const turns = [_]Vec2.Rot{ .ccw, .none, .cw }; const karts = try allocator.dupe(Kart, params.init_karts); defer allocator.free(karts); while (true) { std.sort.sort(Kart, karts, {}, Kart.lessThan); for (karts[1..]) |it, i| { const prev = karts[i + 1 - 1]; if (it.p.x == prev.p.x and it.p.y == prev.p.y) break :ans it.p; } for (karts) |*it| { it.p = it.p.add(it.d); const sq = params.tracks.at(it.p); switch (sq) { '|' => assert(it.d.x == 0), '-' => assert(it.d.y == 0), '\\' => it.d = Vec2.rotate(it.d, if (it.d.x == 0) .ccw else .cw), '/' => it.d = Vec2.rotate(it.d, if (it.d.x == 0) .cw else .ccw), '+' => { it.d = Vec2.rotate(it.d, turns[it.seq]); it.seq = (it.seq + 1) % @intCast(u32, turns.len); }, else => unreachable, } // std.debug.print("{} {} on '{c}'\n", .{ it.p, it.d, sq }); } } }; // part2 (debuggué , ça passait plus...) const ans2 = ans: { const turns = [_]Vec2.Rot{ .ccw, .none, .cw }; const karts = try allocator.dupe(Kart, params.init_karts); defer allocator.free(karts); while (true) { std.sort.sort(Kart, karts, {}, Kart.lessThan); for (karts) |*it| { if (it.seq == DEAD) continue; it.p = it.p.add(it.d); const sq = params.tracks.at(it.p); switch (sq) { '|' => assert(it.d.x == 0), '-' => assert(it.d.y == 0), '\\' => it.d = Vec2.rotate(it.d, if (it.d.x == 0) .ccw else .cw), '/' => it.d = Vec2.rotate(it.d, if (it.d.x == 0) .cw else .ccw), '+' => { it.d = Vec2.rotate(it.d, turns[it.seq]); it.seq = (it.seq + 1) % @intCast(u32, turns.len); }, else => unreachable, } //std.debug.print("{} {} on '{c}'\n", .{ it.p, it.d, sq }); for (karts) |*other| { if (other == it) continue; if (other.seq == DEAD) continue; if (it.p.x == other.p.x and it.p.y == other.p.y) { it.seq = DEAD; other.seq = DEAD; // std.debug.print("krash@{}\n", .{it.p}); break; } } } var nb_karts: usize = 0; var live: ?Kart = null; for (karts) |it| { if (it.seq != DEAD) { live = it; nb_karts += 1; } } if (nb_karts == 1) break :ans live.?.p; } }; return [_][]const u8{ try std.fmt.allocPrint(allocator, "{}", .{ans1}), try std.fmt.allocPrint(allocator, "{}", .{ans2}), }; } pub const main = tools.defaultMain("2018/input_day13.txt", run);
2018/day13.zig
const std = @import("std"); const renderkit = @import("renderkit"); pub const Mesh = struct { bindings: renderkit.BufferBindings, element_count: c_int, pub fn init(comptime IndexT: type, indices: []IndexT, comptime VertT: type, verts: []VertT) Mesh { var ibuffer = renderkit.createBuffer(IndexT, .{ .type = .index, .content = indices, }); var vbuffer = renderkit.createBuffer(VertT, .{ .content = verts, }); return .{ .bindings = renderkit.BufferBindings.init(ibuffer, &[_]renderkit.Buffer{vbuffer}), .element_count = @intCast(c_int, indices.len), }; } pub fn deinit(self: Mesh) void { renderkit.destroyBuffer(self.bindings.index_buffer); renderkit.destroyBuffer(self.bindings.vert_buffers[0]); } pub fn bindImage(self: *Mesh, image: renderkit.Image, slot: c_uint) void { self.bindings.bindImage(image, slot); } pub fn draw(self: Mesh) void { renderkit.applyBindings(self.bindings); renderkit.draw(0, self.element_count, 1); } }; /// Contains a dynamic vert buffer and a slice of verts pub fn DynamicMesh(comptime IndexT: type, comptime VertT: type) type { return struct { const Self = @This(); bindings: renderkit.BufferBindings, verts: []VertT, element_count: c_int, allocator: std.mem.Allocator, pub fn init(allocator: std.mem.Allocator, vertex_count: usize, indices: []IndexT) !Self { var ibuffer = if (IndexT == void) @as(renderkit.Buffer, 0) else renderkit.createBuffer(IndexT, .{ .type = .index, .content = indices, }); var vertex_buffer = renderkit.createBuffer(VertT, .{ .usage = .stream, .size = @intCast(c_long, vertex_count * @sizeOf(VertT)), }); return Self{ .bindings = renderkit.BufferBindings.init(ibuffer, &[_]renderkit.Buffer{vertex_buffer}), .verts = try allocator.alloc(VertT, vertex_count), .element_count = @intCast(c_int, indices.len), .allocator = allocator, }; } pub fn deinit(self: *Self) void { if (IndexT != void) renderkit.destroyBuffer(self.bindings.index_buffer); renderkit.destroyBuffer(self.bindings.vert_buffers[0]); self.allocator.free(self.verts); } pub fn updateAllVerts(self: *Self) void { renderkit.updateBuffer(VertT, self.bindings.vert_buffers[0], self.verts); // updateBuffer gives us a fresh buffer so make sure we reset our append offset self.bindings.vertex_buffer_offsets[0] = 0; } /// uploads to the GPU the slice up to num_verts pub fn updateVertSlice(self: *Self, num_verts: usize) void { std.debug.assert(num_verts <= self.verts.len); const vert_slice = self.verts[0..num_verts]; renderkit.updateBuffer(VertT, self.bindings.vert_buffers[0], vert_slice); } /// uploads to the GPU the slice from start with num_verts. Records the offset in the BufferBindings allowing you /// to interleave appendVertSlice and draw calls. When calling draw after appendVertSlice /// the base_element is reset to the start of the newly updated data so you would pass in 0 for base_element. pub fn appendVertSlice(self: *Self, start_index: usize, num_verts: usize) void { std.debug.assert(start_index + num_verts <= self.verts.len); const vert_slice = self.verts[start_index .. start_index + num_verts]; self.bindings.vertex_buffer_offsets[0] = renderkit.appendBuffer(VertT, self.bindings.vert_buffers[0], vert_slice); } pub fn bindImage(self: *Self, image: renderkit.Image, slot: c_uint) void { self.bindings.bindImage(image, slot); } pub fn draw(self: Self, base_element: c_int, element_count: c_int) void { renderkit.applyBindings(self.bindings); renderkit.draw(base_element, element_count, 1); } pub fn drawAllVerts(self: Self) void { self.draw(0, @intCast(c_int, self.element_count)); } }; }
gamekit/graphics/mesh.zig
const std = @import("std"); const math = std.math; const Log2Int = math.Log2Int; const is_test = @import("builtin").is_test; pub inline fn fixXfYi(comptime I: type, a: anytype) I { @setRuntimeSafety(is_test); const F = @TypeOf(a); const float_bits = @typeInfo(F).Float.bits; const int_bits = @typeInfo(I).Int.bits; const rep_t = std.meta.Int(.unsigned, float_bits); const sig_bits = math.floatMantissaBits(F); const exp_bits = math.floatExponentBits(F); const fractional_bits = math.floatFractionalBits(F); const implicit_bit = if (F != f80) (@as(rep_t, 1) << sig_bits) else 0; const max_exp = (1 << (exp_bits - 1)); const exp_bias = max_exp - 1; const sig_mask = (@as(rep_t, 1) << sig_bits) - 1; // Break a into sign, exponent, significand const a_rep: rep_t = @bitCast(rep_t, a); const negative = (a_rep >> (float_bits - 1)) != 0; const exponent = @intCast(i32, (a_rep << 1) >> (sig_bits + 1)) - exp_bias; const significand: rep_t = (a_rep & sig_mask) | implicit_bit; // If the exponent is negative, the result rounds to zero. if (exponent < 0) return 0; // If the value is too large for the integer type, saturate. switch (@typeInfo(I).Int.signedness) { .unsigned => { if (negative) return 0; if (@intCast(c_uint, exponent) >= @minimum(int_bits, max_exp)) return math.maxInt(I); }, .signed => if (@intCast(c_uint, exponent) >= @minimum(int_bits - 1, max_exp)) { return if (negative) math.minInt(I) else math.maxInt(I); }, } // If 0 <= exponent < sig_bits, right shift to get the result. // Otherwise, shift left. var result: I = undefined; if (exponent < fractional_bits) { result = @intCast(I, significand >> @intCast(Log2Int(rep_t), fractional_bits - exponent)); } else { result = @intCast(I, significand) << @intCast(Log2Int(I), exponent - fractional_bits); } if ((@typeInfo(I).Int.signedness == .signed) and negative) return ~result +% 1; return result; } // Conversion from f16 pub fn __fixhfsi(a: f16) callconv(.C) i32 { return fixXfYi(i32, a); } pub fn __fixunshfsi(a: f16) callconv(.C) u32 { return fixXfYi(u32, a); } pub fn __fixhfdi(a: f16) callconv(.C) i64 { return fixXfYi(i64, a); } pub fn __fixunshfdi(a: f16) callconv(.C) u64 { return fixXfYi(u64, a); } pub fn __fixhfti(a: f16) callconv(.C) i128 { return fixXfYi(i128, a); } pub fn __fixunshfti(a: f16) callconv(.C) u128 { return fixXfYi(u128, a); } // Conversion from f32 pub fn __fixsfsi(a: f32) callconv(.C) i32 { return fixXfYi(i32, a); } pub fn __fixunssfsi(a: f32) callconv(.C) u32 { return fixXfYi(u32, a); } pub fn __fixsfdi(a: f32) callconv(.C) i64 { return fixXfYi(i64, a); } pub fn __fixunssfdi(a: f32) callconv(.C) u64 { return fixXfYi(u64, a); } pub fn __fixsfti(a: f32) callconv(.C) i128 { return fixXfYi(i128, a); } pub fn __fixunssfti(a: f32) callconv(.C) u128 { return fixXfYi(u128, a); } // Conversion from f64 pub fn __fixdfsi(a: f64) callconv(.C) i32 { return fixXfYi(i32, a); } pub fn __fixunsdfsi(a: f64) callconv(.C) u32 { return fixXfYi(u32, a); } pub fn __fixdfdi(a: f64) callconv(.C) i64 { return fixXfYi(i64, a); } pub fn __fixunsdfdi(a: f64) callconv(.C) u64 { return fixXfYi(u64, a); } pub fn __fixdfti(a: f64) callconv(.C) i128 { return fixXfYi(i128, a); } pub fn __fixunsdfti(a: f64) callconv(.C) u128 { return fixXfYi(u128, a); } // Conversion from f80 pub fn __fixxfsi(a: f80) callconv(.C) i32 { return fixXfYi(i32, a); } pub fn __fixunsxfsi(a: f80) callconv(.C) u32 { return fixXfYi(u32, a); } pub fn __fixxfdi(a: f80) callconv(.C) i64 { return fixXfYi(i64, a); } pub fn __fixunsxfdi(a: f80) callconv(.C) u64 { return fixXfYi(u64, a); } pub fn __fixxfti(a: f80) callconv(.C) i128 { return fixXfYi(i128, a); } pub fn __fixunsxfti(a: f80) callconv(.C) u128 { return fixXfYi(u128, a); } // Conversion from f128 pub fn __fixtfsi(a: f128) callconv(.C) i32 { return fixXfYi(i32, a); } pub fn __fixunstfsi(a: f128) callconv(.C) u32 { return fixXfYi(u32, a); } pub fn __fixtfdi(a: f128) callconv(.C) i64 { return fixXfYi(i64, a); } pub fn __fixunstfdi(a: f128) callconv(.C) u64 { return fixXfYi(u64, a); } pub fn __fixtfti(a: f128) callconv(.C) i128 { return fixXfYi(i128, a); } pub fn __fixunstfti(a: f128) callconv(.C) u128 { return fixXfYi(u128, a); } // Conversion from f32 pub fn __aeabi_f2iz(a: f32) callconv(.AAPCS) i32 { return fixXfYi(i32, a); } pub fn __aeabi_f2uiz(a: f32) callconv(.AAPCS) u32 { return fixXfYi(u32, a); } pub fn __aeabi_f2lz(a: f32) callconv(.AAPCS) i64 { return fixXfYi(i64, a); } pub fn __aeabi_f2ulz(a: f32) callconv(.AAPCS) u64 { return fixXfYi(u64, a); } // Conversion from f64 pub fn __aeabi_d2iz(a: f64) callconv(.AAPCS) i32 { return fixXfYi(i32, a); } pub fn __aeabi_d2uiz(a: f64) callconv(.AAPCS) u32 { return fixXfYi(u32, a); } pub fn __aeabi_d2lz(a: f64) callconv(.AAPCS) i64 { return fixXfYi(i64, a); } pub fn __aeabi_d2ulz(a: f64) callconv(.AAPCS) u64 { return fixXfYi(u64, a); } test { _ = @import("fixXfYi_test.zig"); }
lib/std/special/compiler_rt/fixXfYi.zig
const std = @import("std"); const Async = @import("async.zig"); const SIZE = 10_000_000; pub fn main() void { return Async.run(asyncMain, .{}); } fn asyncMain() void { const arr = Async.allocator.alloc(i32, SIZE) catch @panic("failed to allocate array"); defer Async.allocator.free(arr); std.debug.print("filling\n", .{}); for (arr) |*item, i| { item.* = @intCast(i32, i); } std.debug.print("shuffling\n", .{}); shuffle(arr); std.debug.print("running\n", .{}); var timer = std.time.Timer.start() catch @panic("failed to create os timer"); quickSort(arr); var elapsed = @intToFloat(f64, timer.lap()); var units: []const u8 = "ns"; if (elapsed >= std.time.ns_per_s) { elapsed /= std.time.ns_per_s; units = "s"; } else if (elapsed >= std.time.ns_per_ms) { elapsed /= std.time.ns_per_ms; units = "ms"; } else if (elapsed >= std.time.ns_per_us) { elapsed /= std.time.ns_per_us; units = "us"; } std.debug.print("took {d:.2}{s}\n", .{ elapsed, units }); if (!verify(arr)) { std.debug.panic("array not sorted", .{}); } } fn verify(arr: []const i32) bool { var i: usize = 0; while (true) : (i += 1) { if (i == arr.len - 1) return true; if (arr[i] > arr[i + 1]) return false; } } fn shuffle(arr: []i32) void { var xs: u32 = 0xdeadbeef; for (arr) |_, i| { xs ^= xs << 13; xs ^= xs >> 17; xs ^= xs << 5; const j = xs % (i + 1); std.mem.swap(i32, &arr[i], &arr[j]); } } fn quickSort(arr: []i32) void { if (arr.len <= 32) { insertionSort(arr); } else { const mid = partition(arr); var left = Async.spawn(quickSort, .{arr[0..mid]}); var right = Async.spawn(quickSort, .{arr[mid..]}); left.join(); right.join(); } } fn partition(arr: []i32) usize { const pivot = arr.len - 1; var i: usize = 0; for (arr[0..pivot]) |_, j| { if (arr[j] <= arr[pivot]) { std.mem.swap(i32, &arr[j], &arr[i]); i += 1; } } std.mem.swap(i32, &arr[i], &arr[pivot]); return i; } fn insertionSort(arr: []i32) void { for (arr[1..]) |_, i| { var n = i + 1; while (n > 0 and arr[n] < arr[n - 1]) { std.mem.swap(i32, &arr[n], &arr[n - 1]); n -= 1; } } }
benchmarks/zig/qsort.zig
const std = @import("std"); const assert = std.debug.assert; const render = @import("../RTRenderEngine/RTRenderEngine.zig"); const loadFile = @import("../Files.zig").loadFile; const Matrix = @import("../Mathematics/Mathematics.zig").Matrix; const assets = @import("../Assets/Assets.zig"); const Asset = assets.Asset; const wgi = @import("../WindowGraphicsInput/WindowGraphicsInput.zig"); const image = wgi.image; const Texture2D = render.Texture2D; pub fn getAmbient(file_data: []align(4) const u8, ambient: *[3]f32) void { const scene_file_f32 = std.mem.bytesAsSlice(f32, file_data); ambient.*[0] = scene_file_f32[1]; ambient.*[1] = scene_file_f32[2]; ambient.*[2] = scene_file_f32[3]; } pub fn getClearColour(file_data: []align(4) const u8, c: *[3]f32) void { const scene_file_f32 = std.mem.bytesAsSlice(f32, file_data); c.*[0] = scene_file_f32[4]; c.*[1] = scene_file_f32[5]; c.*[2] = scene_file_f32[6]; } pub fn getAssets(file_data: []align(4) const u8, assets_list: *std.ArrayList(Asset)) !void { const scene_file_u32 = std.mem.bytesAsSlice(u32, file_data); const scene_file_f32 = std.mem.bytesAsSlice(f32, file_data); if (scene_file_u32[0] != 0x1a98fd34) { return error.InvalidMagic; } const num_assets = scene_file_u32[8]; if (num_assets > 10000) { return error.TooManyAssets; } var assets_list_original_size = assets_list.*.items.len; try assets_list.resize(assets_list_original_size + num_assets); errdefer { // Put list back how it was // This cannot fail as we are shrinking the list assets_list.resize(assets_list_original_size) catch unreachable; } var i: u32 = 0; var offset: u32 = 9; while (i < num_assets) { const stringLen = @intCast(u8, scene_file_u32[offset] & 0xff); const asset_file_path = file_data[(offset * 4 + 1)..(offset * 4 + 1 + stringLen)]; assets_list.*.items[assets_list_original_size + i] = try Asset.init(asset_file_path); offset += (1 + stringLen + 3) / 4; i += 1; } } // Returns root object // Assets must be in the ready state // Assets slie must point to the assets loaded by getAssets or the wrong assets will be used pub fn loadSceneFromFile(file_data: []align(4) const u8, assets_list: []Asset, allocator: *std.mem.Allocator) !*render.Object { if (file_data.len % 4 != 0) { return error.InvalidFile; } const scene_file_u32 = std.mem.bytesAsSlice(u32, file_data); const scene_file_f32 = std.mem.bytesAsSlice(f32, file_data); if (scene_file_u32[0] != 0x1a98fd34) { return error.InvalidMagic; } var offset: u32 = 9 + scene_file_u32[7]; var root_object = try allocator.create(render.Object); errdefer allocator.destroy(root_object); root_object.* = render.Object{ .name = "scnrootxxxxxxxxx".*, .name_length = 7, }; // Mesh objects const num_meshes = scene_file_u32[offset]; offset += 1; var meshes = std.ArrayList(?*render.Mesh).init(allocator); defer meshes.deinit(); try meshes.resize(num_meshes); var i: u32 = 0; while (i < num_meshes) : (i += 1) { const asset_index = scene_file_u32[offset]; const modifiable = scene_file_u32[offset + 1] != 0; offset += 2; const asset = &assets_list[asset_index]; if (@intCast(usize, asset_index) < assets_list.len and asset.asset_type == Asset.AssetType.Model) { var mesh = try allocator.create(render.Mesh); errdefer allocator.destroy(mesh); mesh.* = try render.Mesh.initFromAsset(asset, modifiable); asset.ref_count.inc(); errdefer { mesh.*.free(); asset.ref_count.dec(); } meshes.items[i] = mesh; } else { meshes.items[i] = null; } } // Textures (untested) const num_textures = scene_file_u32[offset]; offset += 1; var textures = std.ArrayList(?*Texture2D).init(allocator); defer textures.deinit(); try textures.resize(num_textures); i = 0; while (i < num_textures) : (i += 1) { const asset_index = scene_file_u32[offset]; const modifiable = scene_file_u32[offset + 1] != 0; const smooth_when_magnified = scene_file_u32[offset + 2] != 0; const min_filter = @intToEnum(image.MinFilter, @intCast(i32, std.math.min(5, scene_file_u32[offset + 3]))); offset += 4; const asset = &assets_list[asset_index]; if (@intCast(usize, asset_index) < assets_list.len and (asset.asset_type == Asset.AssetType.Texture or asset.asset_type == Asset.AssetType.RGB10A2Texture)) { var texture = try allocator.create(Texture2D); errdefer allocator.destroy(texture); texture.* = try Texture2D.loadFromAsset(asset); errdefer texture.*.free(); if (asset.asset_type == Asset.AssetType.RGB10A2Texture) { try texture.texture.upload(asset.texture_width.?, asset.texture_height.?, asset.texture_type.?, asset.rgb10a2_data.?); } else { try texture.texture.upload(asset.texture_width.?, asset.texture_height.?, asset.texture_type.?, asset.data.?); } textures.items[i] = texture; } else { textures.items[i] = null; } } // Game objects const num_objects = scene_file_u32[offset]; offset += 1; var objects_list = std.ArrayList(*render.Object).init(allocator); defer objects_list.deinit(); try objects_list.ensureCapacity(num_objects); i = 0; while (i < num_objects) : (i += 1) { var o = try allocator.create(render.Object); errdefer allocator.destroy(o); try objects_list.append(o); o.* = render.Object{}; var name_i: u32 = 0; while (name_i < 16 and file_data[offset * 4 + name_i] != 0) : (name_i += 1) { o.name[name_i] = file_data[offset * 4 + name_i]; } o.name_length = name_i; offset += 4; const parent = scene_file_u32[offset]; const has_mesh_renderer = scene_file_u32[offset + 1] != 0; const has_light = scene_file_u32[offset + 2] != 0; o.inherit_parent_transform = scene_file_u32[offset + 4] != 0; offset += 5; o.*.transform.loadFromSlice(scene_file_f32[offset .. offset + 16]) catch unreachable; offset += 16; if (has_mesh_renderer) { const mesh_index = scene_file_u32[offset]; offset += 1; if (mesh_index < meshes.items.len and meshes.items[mesh_index] != null) { // TODO scene file should have list of mesh renderers // TODO return resource lists to caller var mesh_renderer = try allocator.create(render.MeshRenderer); errdefer allocator.destroy(mesh_renderer); mesh_renderer.* = try render.MeshRenderer.init(meshes.items[mesh_index].?, allocator); o.setMeshRenderer(mesh_renderer); // Materials var j: u32 = 0; while (j < 32) : (j += 1) { const tex = scene_file_u32[offset + 0]; const norm = scene_file_u32[offset + 1]; offset += 2; if (tex < textures.items.len and textures.items[tex] != null) { o.mesh_renderer.?.materials[j].setTexture(textures.items[tex].?); } if (norm < textures.items.len and textures.items[norm] != null) { o.mesh_renderer.?.materials[j].setNormalMap(textures.items[norm].?); } o.mesh_renderer.?.materials[j].specular_size = scene_file_f32[offset + 0]; o.mesh_renderer.?.materials[j].specular_intensity = scene_file_f32[offset + 1]; o.mesh_renderer.?.materials[j].specular_colourisation = scene_file_f32[offset + 2]; o.mesh_renderer.?.materials[j].flat_shading = scene_file_u32[offset + 3] != 0; offset += 4; } } } if (has_light) { const light_type_ = scene_file_u32[offset]; offset += 1; var light_type: render.Light.LightType = undefined; if (light_type_ == 0) { light_type = render.Light.LightType.Point; } else if (light_type_ == 1) { light_type = render.Light.LightType.Spotlight; } else { light_type = render.Light.LightType.Directional; } const r = scene_file_f32[offset]; const g = scene_file_f32[offset + 1]; const b = scene_file_f32[offset + 2]; const cast_shadows = scene_file_f32[offset + 3] != 0; const clip_start = scene_file_f32[offset + 4]; const clip_end = scene_file_f32[offset + 5]; offset += 6; var angle: f32 = 0; if (light_type == render.Light.LightType.Spotlight) { angle = scene_file_f32[offset]; offset += 1; } o.*.light = render.Light{ .light_type = light_type, .angle = angle, .colour = [3]f32{ r, g, b }, .attenuation = 1.0, .cast_realtime_shadows = cast_shadows, .shadow_near = clip_start, .shadow_far = clip_end, .shadow_width = 30.0, .shadow_height = 30.0, }; } if (parent != 0xffffffff and parent < objects_list.items.len - 1) { try objects_list.items[parent].*.addChild(o); } else { try root_object.addChild(o); } } return root_object; }
src/Scene/Scene.zig
const __floatundidf = @import("floatundidf.zig").__floatundidf; const testing = @import("std").testing; fn test__floatundidf(a: u64, expected: f64) !void { const r = __floatundidf(a); try testing.expect(r == expected); } test "floatundidf" { try test__floatundidf(0, 0.0); try test__floatundidf(1, 1.0); try test__floatundidf(2, 2.0); try test__floatundidf(20, 20.0); try test__floatundidf(0x7FFFFF8000000000, 0x1.FFFFFEp+62); try test__floatundidf(0x7FFFFFFFFFFFF800, 0x1.FFFFFFFFFFFFEp+62); try test__floatundidf(0x7FFFFF0000000000, 0x1.FFFFFCp+62); try test__floatundidf(0x7FFFFFFFFFFFF000, 0x1.FFFFFFFFFFFFCp+62); try test__floatundidf(0x8000008000000000, 0x1.000001p+63); try test__floatundidf(0x8000000000000800, 0x1.0000000000001p+63); try test__floatundidf(0x8000010000000000, 0x1.000002p+63); try test__floatundidf(0x8000000000001000, 0x1.0000000000002p+63); try test__floatundidf(0x8000000000000000, 0x1p+63); try test__floatundidf(0x8000000000000001, 0x1p+63); try test__floatundidf(0x0007FB72E8000000, 0x1.FEDCBAp+50); try test__floatundidf(0x0007FB72EA000000, 0x1.FEDCBA8p+50); try test__floatundidf(0x0007FB72EB000000, 0x1.FEDCBACp+50); try test__floatundidf(0x0007FB72EBFFFFFF, 0x1.FEDCBAFFFFFFCp+50); try test__floatundidf(0x0007FB72EC000000, 0x1.FEDCBBp+50); try test__floatundidf(0x0007FB72E8000001, 0x1.FEDCBA0000004p+50); try test__floatundidf(0x0007FB72E6000000, 0x1.FEDCB98p+50); try test__floatundidf(0x0007FB72E7000000, 0x1.FEDCB9Cp+50); try test__floatundidf(0x0007FB72E7FFFFFF, 0x1.FEDCB9FFFFFFCp+50); try test__floatundidf(0x0007FB72E4000001, 0x1.FEDCB90000004p+50); try test__floatundidf(0x0007FB72E4000000, 0x1.FEDCB9p+50); try test__floatundidf(0x023479FD0E092DC0, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DA1, 0x1.1A3CFE870496Dp+57); try test__floatundidf(0x023479FD0E092DB0, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DB8, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DB6, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DBF, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DC1, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DC7, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DC8, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DCF, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DD0, 0x1.1A3CFE870496Ep+57); try test__floatundidf(0x023479FD0E092DD1, 0x1.1A3CFE870496Fp+57); try test__floatundidf(0x023479FD0E092DD8, 0x1.1A3CFE870496Fp+57); try test__floatundidf(0x023479FD0E092DDF, 0x1.1A3CFE870496Fp+57); try test__floatundidf(0x023479FD0E092DE0, 0x1.1A3CFE870496Fp+57); }
lib/std/special/compiler_rt/floatundidf_test.zig
const std = @import("std"); const testing = std.testing; const lexer = @import("zig_lexer.zig"); const Token = lexer.Token; const Lexer = lexer.Lexer; const Id = lexer.Id; test "\\n" { testToken("\n", .Newline); } test "&" { testToken("&", .Ampersand); } test "&=" { testToken("&=", .AmpersandEqual); } test "*" { testToken("*", .Asterisk); } test "**" { testToken("**", .AsteriskAsterisk); } test "*=" { testToken("*=", .AsteriskEqual); } test "*%" { testToken("*%", .AsteriskPercent); } test "*%=" { testToken("*%=", .AsteriskPercentEqual); } test "^" { testToken("^", .Caret); } test "^=" { testToken("^=", .CaretEqual); } test ":" { testToken(":", .Colon); } test "," { testToken(",", .Comma); } test "." { testToken(".", .Period); } test ".." { testToken("..", .Ellipsis2); } test "..." { testToken("...", .Ellipsis3); } test "=" { testToken("=", .Equal); } test "==" { testToken("==", .EqualEqual); } test "=>" { testToken("=>", .EqualAngleBracketRight); } test "!" { testToken("!", .Bang); } test "!=" { testToken("!=", .BangEqual); } test "<" { testToken("<", .AngleBracketLeft); } test "<<" { testToken("<<", .AngleBracketAngleBracketLeft); } test "<<=" { testToken("<<=", .AngleBracketAngleBracketLeftEqual); } test "<=" { testToken("<=", .AngleBracketLeftEqual); } test "{" { testToken("{", .LBrace); } test "[" { testToken("[", .LBracket); } test "(" { testToken("(", .LParen); } test "-" { testToken("-", .Minus); } test "-=" { testToken("-=", .MinusEqual); } test "->" { testToken("->", .MinusAngleBracketRight); } test "-%" { testToken("-%", .MinusPercent); } test "-%=" { testToken("-%=", .MinusPercentEqual); } test "%" { testToken("%", .Percent); } test "%=" { testToken("%=", .PercentEqual); } test "|" { testToken("|", .Pipe); } test "||" { testToken("||", .PipePipe); } test "|=" { testToken("|=", .PipeEqual); } test "+" { testToken("+", .Plus); } test "++" { testToken("++", .PlusPlus); } test "+=" { testToken("+=", .PlusEqual); } test "+%" { testToken("+%", .PlusPercent); } test "+%=" { testToken("+%=", .PlusPercentEqual); } test "[*c]" { testToken("[*c]", .BracketStarCBracket); } test "[*]" { testToken("[*]", .BracketStarBracket); } test "?" { testToken("?", .QuestionMark); } test ">" { testToken(">", .AngleBracketRight); } test ">>" { testToken(">>", .AngleBracketAngleBracketRight); } test ">>=" { testToken(">>=", .AngleBracketAngleBracketRightEqual); } test ">=" { testToken(">=", .AngleBracketRightEqual); } test "}" { testToken("}", .RBrace); } test "]" { testToken("]", .RBracket); } test ")" { testToken(")", .RParen); } test ";" { testToken(";", .Semicolon); } test "/" { testToken("/", .Slash); } test "/=" { testToken("/=", .SlashEqual); } test "~" { testToken("~", .Tilde); } test "align" { testToken("align", .Keyword_align); } test "allowzero" { testToken("allowzero", .Keyword_allowzero); } test "and" { testToken("and", .Keyword_and); } test "asm" { testToken("asm", .Keyword_asm); } test "async" { testToken("async", .Keyword_async); } test "await" { testToken("await", .Keyword_await); } test "break" { testToken("break", .Keyword_break); } test "catch" { testToken("catch", .Keyword_catch); } test "cancel" { testToken("cancel", .Keyword_cancel); } test "comptime" { testToken("comptime", .Keyword_comptime); } test "const" { testToken("const", .Keyword_const); } test "continue" { testToken("continue", .Keyword_continue); } test "defer" { testToken("defer", .Keyword_defer); } test "else" { testToken("else", .Keyword_else); } test "enum" { testToken("enum", .Keyword_enum); } test "errdefer" { testToken("errdefer", .Keyword_errdefer); } test "error" { testToken("error", .Keyword_error); } test "export" { testToken("export", .Keyword_export); } test "extern" { testToken("extern", .Keyword_extern); } test "false" { testToken("false", .Keyword_false); } test "fn" { testToken("fn", .Keyword_fn); } test "for" { testToken("for", .Keyword_for); } test "if" { testToken("if", .Keyword_if); } test "inline" { testToken("inline", .Keyword_inline); } test "nakedcc" { testToken("nakedcc", .Keyword_nakedcc); } test "noalias" { testToken("noalias", .Keyword_noalias); } test "null" { testToken("null", .Keyword_null); } test "or" { testToken("or", .Keyword_or); } test "orelse" { testToken("orelse", .Keyword_orelse); } test "packed" { testToken("packed", .Keyword_packed); } test "promise" { testToken("promise", .Keyword_promise); } test "pub" { testToken("pub", .Keyword_pub); } test "resume" { testToken("resume", .Keyword_resume); } test "return" { testToken("return", .Keyword_return); } test "linksection" { testToken("linksection", .Keyword_linksection); } test "stdcallcc" { testToken("stdcallcc", .Keyword_stdcallcc); } test "struct" { testToken("struct", .Keyword_struct); } test "suspend" { testToken("suspend", .Keyword_suspend); } test "switch" { testToken("switch", .Keyword_switch); } test "test" { testToken("test", .Keyword_test); } test "threadlocal" { testToken("threadlocal", .Keyword_threadlocal); } test "true" { testToken("true", .Keyword_true); } test "try" { testToken("try", .Keyword_try); } test "undefined" { testToken("undefined", .Keyword_undefined); } test "union" { testToken("union", .Keyword_union); } test "unreachable" { testToken("unreachable", .Keyword_unreachable); } test "use" { testToken("use", .Keyword_use); } test "var" { testToken("var", .Keyword_var); } test "volatile" { testToken("volatile", .Keyword_volatile); } test "while" { testToken("while", .Keyword_while); } test "//" { testToken("//", .LineComment); } test "///" { testToken("///", .DocComment); } test "////" { testToken("////", .LineComment); } test "@builtin" { testToken("@builtin", .Builtin); } test "@\"identifier\"" { testToken("@\"identifier\"", .Identifier); } test "#!/usr/bin/env zig" { testToken("#!/usr/bin/env zig", .ShebangLine); } test "#0" { testTokens("#0", [_]Id{ .Invalid, .IntegerLiteral }); } test "+++" { testTokens("+++", [_]Id{ .PlusPlus, .Plus }); } test "0b2" { testTokens("0b2", [_]Id{ .Invalid, .IntegerLiteral }); } test "0o8" { testTokens("0o8", [_]Id{ .Invalid, .IntegerLiteral }); } test "[0..]" { testTokens("[0..]", [_]Id{ .LBracket, .IntegerLiteral, .Ellipsis2, .RBracket }); } fn testToken(buffer: []const u8, id: Id) void { var lex = Lexer.init(buffer); var token = lex.next(); testing.expectEqual(id, token.id); token = lex.next(); testing.expectEqual(Id.Eof, token.id); } fn testTokens(buffer: []const u8, ids: []const Id) void { var lex = Lexer.init(buffer); var token = lex.next(); for (ids) |id| { testing.expectEqual(id, token.id); token = lex.next(); } testing.expectEqual(Id.Eof, token.id); }
zig/zig_lexer.test.zig
const std = @import("std"); const opt = @import("opt.zig"); const Allocator = std.mem.Allocator; const stdout = &std.io.getStdOut().outStream(); const warn = std.debug.warn; pub fn basename(path: []const u8, terminator: []const u8, suffix: ?[]u8, allocator: *Allocator) ![]u8 { if (path.len == 1 and path[0] == '/') { return try concat(allocator, "/", terminator); } const name = std.fs.path.basename(path); var stripped: [*]u8 = undefined; if (suffix) |suf| { if (std.mem.eql(u8, name[name.len - suf.len ..], suf)) { return try concat(allocator, name[0 .. name.len - suf.len], terminator); } } return concat(allocator, name, terminator); } fn concat(allocator: *Allocator, a: []const u8, b: []const u8) ![]u8 { const result = try allocator.alloc(u8, a.len + b.len); std.mem.copy(u8, result, a); std.mem.copy(u8, result[a.len..], b); return result; } const BasenameFlags = enum { Multiple, Suffix, Zero, Help, Version, }; var flags = [_]opt.Flag(BasenameFlags){ .{ .name = BasenameFlags.Help, .long = "help", }, .{ .name = BasenameFlags.Version, .long = "version", }, .{ .name = BasenameFlags.Multiple, .short = 'a', .long = "multiple", }, .{ .name = BasenameFlags.Suffix, .short = 's', .long = "suffix", .mandatory = true, .kind = opt.ArgTypeTag.String, }, .{ .name = BasenameFlags.Zero, .short = 'z', .long = "zero", }, }; pub fn main(args: [][]u8) anyerror!u8 { var multiple: bool = false; var eolchar: []const u8 = "\n"; var suffix: ?[]u8 = null; var it = opt.FlagIterator(BasenameFlags).init(flags[0..], args); while (it.next_flag() catch { return 0; }) |flag| { switch (flag.name) { BasenameFlags.Help => { warn("(help screen here)\n", .{}); return 0; }, BasenameFlags.Version => { warn("(version info here)\n", .{}); return 0; }, BasenameFlags.Multiple => { multiple = true; }, BasenameFlags.Suffix => { multiple = true; suffix = flag.value.String.?; }, BasenameFlags.Zero => { eolchar = ""; }, } } var buffer: [100]u8 = undefined; const allocator = &std.heap.FixedBufferAllocator.init(&buffer).allocator; const first_maybe = it.next_arg(); if (first_maybe) |first| { if (!multiple and suffix == null) { suffix = it.next_arg(); if (it.next_arg()) |arg| { warn("{}: extra operand '{}'\n", .{ args[0], arg }); warn("Try '{} --help' for more information.\n", .{args[0]}); return 1; } } try stdout.print("{}", .{basename(first, eolchar, suffix, allocator)}); if (multiple) { while (it.next_arg()) |arg| { try stdout.print("{}", .{basename(arg, eolchar, suffix, allocator)}); } } } else { warn("{}: missing operand.\n", .{args[0]}); warn("Try '{} --help' for more information.\n", .{args[0]}); return 1; } return 0; } test "simple test" { const expected = "testbasename"; // "touch" file const file = try std.fs.cwd().createFile("/tmp/testbasename", std.fs.File.CreateFlags{ .read = true }); file.close(); var result = try basename("/tmp/testbasename", "", null, std.heap.page_allocator); std.debug.assert(std.mem.eql(u8, result, expected)); }
src/basename.zig
const std = @import("std"); const Mat4 = @This(); pub const identity = Mat4{ .data = [_]f32{ 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, } }; data: [16]f32, pub fn fromValues(values: [16]f32) Mat4 { return Mat4{ .data = values }; } pub fn multiply(a: Mat4, b: Mat4) Mat4 { var out: Mat4 = undefined; var row: usize = 0; while (row < 4) : (row += 1) { var column: usize = 0; while (column < 4) : (column += 1) { const i = row * 4 + column; out.data[i] = a.data[row * 4] * b.data[column] + a.data[row * 4 + 1] * b.data[column + 4] + a.data[row * 4 + 2] * b.data[column + 8] + a.data[row * 4 + 3] * b.data[column + 12]; } } return out; } pub fn multiplyMany(matrices: []const Mat4) Mat4 { var current = matrices[0]; std.debug.assert(matrices.len >= 1); for (matrices[1..]) |matrix| { current = current.multiply(matrix); } return current; } pub fn rotateZ(angle: f32) Mat4 { var out = identity; out.data[0] = std.math.cos(angle); out.data[1] = -std.math.sin(angle); out.data[4] = std.math.sin(angle); out.data[5] = std.math.cos(angle); return out; } pub fn rotateY(angle: f32) Mat4 { var out = identity; out.data[0] = std.math.cos(angle); out.data[2] = -std.math.sin(angle); out.data[8] = std.math.sin(angle); out.data[10] = std.math.cos(angle); return out; } pub fn rotateX(angle: f32) Mat4 { var out = identity; out.data[5] = std.math.cos(angle); out.data[6] = -std.math.sin(angle); out.data[9] = std.math.sin(angle); out.data[10] = std.math.cos(angle); return out; } pub fn scale(x: f32, y: f32, z: f32) Mat4 { var out = identity; out.data[0] = x; out.data[5] = y; out.data[10] = z; return out; } pub fn perspective(fov: f32, aspect: f32, near: f32, far: f32) Mat4 { const fov_rad = fov * std.math.pi / 180.0; const f = 1.0 / std.math.tan(fov_rad / 2.0); const range_inv = 1.0 / (near - far); var out = identity; out.data[0] = f / aspect; out.data[5] = f; out.data[10] = (near + far) * range_inv; out.data[11] = -1; out.data[14] = near * far * range_inv * 2; out.data[15] = 0; return out; } pub fn translate(x: f32, y: f32, z: f32) Mat4 { var out = identity; out.data[12] = x; out.data[13] = y; out.data[14] = z; return out; } pub fn approxEq(a: Mat4, b: Mat4, tolerance: f32) bool { for (a.data) |a_val, i| { const b_val = b.data[i]; if (!std.math.approxEqAbs(f32, a_val, b_val, tolerance)) return false; } return true; } test "multiply" { const a = Mat4.fromValues([_]f32{ 1, 0, 0, 0, 2, 1, 3, 0, 0, 1, 1, 2, 0, 2, 3, 4, }); const b = Mat4.fromValues([_]f32{ 2, 1, 0, 0, 2, 1, 0, 3, 1, 4, 2, 0, 0, 4, 1, 2, }); const result = Mat4.multiply(a, b); const result_many = Mat4.multiplyMany(&[_]Mat4{ a, b }); const expected = Mat4.fromValues([_]f32{ 2, 1, 0, 0, 9, 15, 6, 3, 3, 13, 4, 7, 7, 30, 10, 14, }); try std.testing.expect(Mat4.approxEq(result, expected, 0.01)); try std.testing.expect(Mat4.approxEq(result_many, expected, 0.01)); } test "rotateZ" { const rotation = rotateZ(std.math.pi); const result = multiply(identity, rotation); const result_reverse = multiply(rotation, identity); try std.testing.expect(approxEq(result, rotation, 0.01)); try std.testing.expect(approxEq(result_reverse, rotation, 0.01)); }
src/util/matrix.zig
const std = @import("std"); const print = std.debug.print; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day18.txt"); pub fn main() !void { var timer = try std.time.Timer.start(); print("🎁 Magnitude: {}\n", .{try part01(data)}); print("Day 18 - part 01 took {:15}ns\n", .{timer.lap()}); timer.reset(); print("🎁 Largest magnitude: {}\n", .{try part02(data)}); print("Day 18 - part 02 took {:15}ns\n", .{timer.lap()}); print("❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️❄️\n", .{}); } fn part01(input: []const u8) !i32 { var iterator = std.mem.tokenize(input, "\r\n"); var number = try Number.init(gpa, iterator.next().?); defer { number.deinit(); } while (iterator.next()) |i| { const other = try Number.init(gpa, i); defer { other.deinit(); } try number.add(other); } return number.magnitude(); } fn part02(input: []const u8) !i32 { var iterator1 = std.mem.tokenize(input, "\r\n"); var index1 : u32 = 0; var max : i32 = 0; while (iterator1.next()) |next1| { index1 += 1; var iterator2 = std.mem.tokenize(input, "\r\n"); var index2 : u32 = 0; while (iterator2.next()) |next2| { index2 += 1; if (index1 == index2) { continue; } { const number1 = try Number.init(gpa, next1); defer { number1.deinit(); } var number2 = try Number.init(gpa, next2); defer { number2.deinit(); } try number2.add(number1); max = std.math.max(number2.magnitude(), max); } { var number1 = try Number.init(gpa, next1); defer { number1.deinit(); } const number2 = try Number.init(gpa, next2); defer { number2.deinit(); } try number1.add(number2); max = std.math.max(number1.magnitude(), max); } } } return max; } const Element = struct { lhs : i32, rhs : i32, depth : u8, }; const Number = struct { payload : std.ArrayList(Element), pub fn deinit(me : @This()) void { me.payload.deinit(); } pub fn init(allocator : *std.mem.Allocator, input : []const u8) !@This() { var payload = std.ArrayList(Element).init(allocator); var depth : u8 = 0; var lhs : i32 = -1; var rhs : i32 = -1; var isLhs = true; for (input) |c| { switch (c) { '[' => { // If we are entering another pair and we've got a lhs, we need to // create an element here! if (lhs != -1) { try payload.append(Element { .lhs = lhs, .rhs = rhs, .depth = depth, }); } // Increase the depth as we are entering a pair. depth += 1; // And reset whether we are the lhs of a pair or not (because we are // entering a new pair). isLhs = true; // And reset our stored values. lhs = -1; rhs = -1; }, ']' => { // If we are exiting another pair and we've got a rhs, we need to // create an element here! if (rhs != -1) { try payload.append(Element { .lhs = lhs, .rhs = rhs, .depth = depth, }); } // Decrease the depth as we are exiting a pair. depth -= 1; // And reset whether we are the lhs of a pair or not. isLhs = true; // And reset our stored values. lhs = -1; rhs = -1; }, ',' => { // The comma means the next value we have is our rhs value. isLhs = false; }, else => { var digit = c - '0'; if (isLhs) { // Check we haven't accidentally stored a valid number ih lhs. std.debug.assert(lhs == -1); lhs = digit; } else { // Check we haven't accidentally stored a valid number ih rhs. std.debug.assert(rhs == -1); rhs = digit; } } } } return Number { .payload = payload, }; } fn assert(me : *const @This()) void { for (me.payload.items) |element, i| { std.debug.assert(element.lhs != -1 or element.rhs != -1); if (element.lhs == -1) { const left = me.payload.items[i - 1]; std.debug.assert(i > 0); std.debug.assert(left.rhs != -1); } else if (element.rhs == -1) { const right = me.payload.items[i + 1]; std.debug.assert((i + 1) < me.payload.items.len); std.debug.assert(right.lhs != -1); } } } pub fn reduce(me : *@This()) void { while (true) { var changed = false; me.assert(); for (me.payload.items) |element, i| { // Explode! if (element.depth > 4) { var goLeft : bool = undefined; var sameDepth = false; std.debug.assert(element.lhs != -1); std.debug.assert(element.rhs != -1); // Check if we need to explode our pair into the left or right pairs. if (i > 0 and me.payload.items[i - 1].rhs == -1 and me.payload.items[i - 1].depth + 1 == element.depth) { // Go left! goLeft = true; } else if (i < (me.payload.items.len - 1) and me.payload.items[i + 1].lhs == -1 and me.payload.items[i + 1].depth + 1 == element.depth) { // Go right! goLeft = false; } else if (i < (me.payload.items.len - 1) and element.depth == me.payload.items[i + 1].depth) { // If we get here, it means we have two pairs that are on an equal // depth that are both full, and we need to fold the first one. sameDepth = true; } else { unreachable; } // Propagate our rhs pair value right. var index = i + 1; while (index < me.payload.items.len) : (index += 1) { if (me.payload.items[index].lhs != -1) { me.payload.items[index].lhs += element.rhs; break; } if (me.payload.items[index].rhs != -1) { me.payload.items[index].rhs += element.rhs; break; } } // Propagate our lhs pair value left. index = i; while (index > 0) : (index -= 1) { if (me.payload.items[index - 1].rhs != -1) { me.payload.items[index - 1].rhs += element.lhs; break; } if (me.payload.items[index - 1].lhs != -1) { me.payload.items[index - 1].lhs += element.lhs; break; } } if (sameDepth) { // If we are the same depth, we turn our left pair into a parent // pair instead. me.payload.items[i].lhs = 0; me.payload.items[i].rhs = -1; me.payload.items[i].depth -= 1; } else if (goLeft) { me.payload.items[i - 1].rhs = 0; } else { me.payload.items[i + 1].lhs = 0; } if (!sameDepth) { var removed = me.payload.orderedRemove(i); } changed = true; break; } } if (changed) { continue; } for (me.payload.items) |element, i| { if (element.lhs >= 10) { const newElement = Element { .lhs = @divTrunc(element.lhs, 2), .rhs = @divTrunc(element.lhs + 1, 2), .depth = element.depth + 1, }; if (me.payload.items[i].rhs == -1) { // Replace our own pair since it is now dead. me.payload.items[i] = newElement; } else { // Otherwise insert the new pair for it. me.payload.insert(i, newElement) catch unreachable; // Wipe out our lhs. me.payload.items[i + 1].lhs = -1; } changed = true; break; } if (element.rhs >= 10) { const newElement = Element { .lhs = @divTrunc(element.rhs, 2), .rhs = @divTrunc(element.rhs + 1, 2), .depth = element.depth + 1, }; if (me.payload.items[i].lhs == -1) { // Replace our own pair since it is now dead. me.payload.items[i] = newElement; } else { // Otherwise insert the new pair for it. me.payload.insert(i + 1, newElement) catch unreachable; // Wipe out our rhs. me.payload.items[i].rhs = -1; } changed = true; break; } } if (!changed) { break; } } } pub fn dump(me : *const @This()) void { print("Dump:\n", .{}); var lastDepth : u8 = 0; for (me.payload.items) |element, i| { print("{} = ({}, {}, {})\n", .{i, element.lhs, element.rhs, element.depth}); } } pub fn magnitude(me : *@This()) i32 { while (me.payload.items.len > 1) { for (me.payload.items) |element, i| { if (element.lhs != -1 and element.rhs != -1) { var goLeft : bool = undefined; // Check if we need to explode our pair into the left or right pairs. if (i > 0 and me.payload.items[i - 1].rhs == -1 and me.payload.items[i - 1].depth + 1 == element.depth) { // Go left! goLeft = true; } else if (i < (me.payload.items.len - 1) and me.payload.items[i + 1].lhs == -1 and me.payload.items[i + 1].depth + 1 == element.depth) { // Go right! goLeft = false; } else if ((i < (me.payload.items.len - 1)) and element.depth == me.payload.items[i + 1].depth) { // If we get here, it means we have two pairs that are on an equal // depth that are both full, and we need to fold them together. const other = me.payload.items[i + 1]; if (element.lhs == -1 or element.rhs == -1 or other.lhs == -1 or other.rhs == -1) { continue; } me.payload.items[i].lhs = (3 * element.lhs) + (2 * element.rhs); me.payload.items[i].rhs = (3 * other.lhs) + (2 * other.rhs); me.payload.items[i].depth -= 1; const removed = me.payload.orderedRemove(i + 1); break; } else { continue; } if (goLeft) { me.payload.items[i - 1].rhs = (3 * element.lhs) + (2 * element.rhs); } else { me.payload.items[i + 1].lhs = (3 * element.lhs) + (2 * element.rhs); } const removed = me.payload.orderedRemove(i); break; } } } const element = me.payload.items[0]; std.debug.assert(element.lhs != -1); std.debug.assert(element.rhs != -1); return (3 * element.lhs) + (2 * element.rhs); } pub fn add(me : *@This(), other: Number) !void { for (other.payload.items) |element| { try me.payload.append(element); } for (me.payload.items) |*element| { element.depth += 1; } me.reduce(); } }; test "[[1,2],[[3,4],5]]" { const input = "[[1,2],[[3,4],5]]"; var number = try Number.init(gpa, input); number.reduce(); const magnitude = number.magnitude(); try std.testing.expect(magnitude == 143); } test "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]" { const input = "[[[[0,7],4],[[7,8],[6,0]]],[8,1]]"; var number = try Number.init(gpa, input); number.reduce(); const magnitude = number.magnitude(); try std.testing.expect(magnitude == 1384); } test "example" { const input = \\[[[0,[5,8]],[[1,7],[9,6]]],[[4,[1,2]],[[1,4],2]]] \\[[[5,[2,8]],4],[5,[[9,9],0]]] \\[6,[[[6,2],[5,6]],[[7,6],[4,7]]]] \\[[[6,[0,7]],[0,9]],[4,[9,[9,0]]]] \\[[[7,[6,4]],[3,[1,3]]],[[[5,5],1],9]] \\[[6,[[7,3],[3,2]]],[[[3,8],[5,7]],4]] \\[[[[5,4],[7,7]],8],[[8,3],8]] \\[[9,3],[[9,9],[6,[4,9]]]] \\[[2,[[7,7],7]],[[5,8],[[9,3],[0,2]]]] \\[[[[5,2],5],[8,[3,7]]],[[5,[7,5]],[4,4]]] ; const magnitude = try part01(input); try std.testing.expect(magnitude == 4140); }
src/day18.zig
const std = @import("std"); const builtin = @import("builtin"); const mem = std.mem; const Vector = std.meta.Vector; const Xoodoo = struct { const rcs = [12]u32{ 0x058, 0x038, 0x3c0, 0x0d0, 0x120, 0x014, 0x060, 0x02c, 0x380, 0x0f0, 0x1a0, 0x012 }; const Lane = Vector(4, u32); state: [3]Lane, inline fn asWords(self: *Xoodoo) *[12]u32 { return @ptrCast(*[12]u32, &self.state); } inline fn asBytes(self: *Xoodoo) *[48]u8 { return @ptrCast(*[48]u8, &self.state); } inline fn rot(x: Lane, comptime n: comptime_int) Lane { return (x << @splat(4, @as(u5, n))) | (x >> @splat(4, @as(u5, 32 - n))); } fn permute(self: *Xoodoo) void { var a = self.state[0]; var b = self.state[1]; var c = self.state[2]; inline for (rcs) |rc| { var p = @shuffle(u32, a ^ b ^ c, undefined, [_]i32{ 3, 0, 1, 2 }); var e = rot(p, 5); p = rot(p, 14); e ^= p; a ^= e; b ^= e; c ^= e; b = @shuffle(u32, b, undefined, [_]i32{ 3, 0, 1, 2 }); c = rot(c, 11); a[0] ^= rc; a ^= ~b & c; b ^= ~c & a; c ^= ~a & b; b = rot(b, 1); c = @bitCast(Lane, @shuffle(u8, @bitCast(Vector(16, u8), c), undefined, [_]i32{ 11, 8, 9, 10, 15, 12, 13, 14, 3, 0, 1, 2, 7, 4, 5, 6 })); } self.state[0] = a; self.state[1] = b; self.state[2] = c; } inline fn endianSwapRate(self: *Xoodoo) void { for (self.asWords()[0..4]) |*w| { w.* = mem.littleToNative(u32, w.*); } } inline fn endianSwapAll(self: *Xoodoo) void { for (self.asWords()) |*w| { w.* = mem.littleToNative(u32, w.*); } } fn squeezePermute(self: *Xoodoo) [16]u8 { self.endianSwapRate(); const rate = self.asBytes()[0..16].*; self.endianSwapRate(); self.permute(); return rate; } }; pub const Charm = struct { x: Xoodoo, pub const tag_length = 16; pub const key_length = 32; pub const nonce_length = 16; pub const hash_length = 32; pub fn new(key: [key_length]u8, nonce: ?[nonce_length]u8) Charm { var x = Xoodoo{ .state = undefined }; var bytes = x.asBytes(); if (nonce) |n| { mem.copy(u8, bytes[0..16], n[0..]); } else { mem.set(u8, bytes[0..16], 0); } mem.copy(u8, bytes[16..][0..32], key[0..]); x.endianSwapAll(); x.permute(); return Charm{ .x = x }; } fn xor128(out: *[16]u8, in: *const [16]u8) void { for (out) |*x, i| { x.* ^= in[i]; } } fn equal128(a: [16]u8, b: [16]u8) bool { var d: u8 = 0; for (a) |x, i| { d |= x ^ b[i]; } mem.doNotOptimizeAway(d); return d == 0; } pub fn nonceIncrement(nonce: *[nonce_length]u8, endian: builtin.Endian) void { const next = mem.readInt(u128, nonce, endian) +% 1; mem.writeInt(u128, nonce, next, endian); } pub fn encrypt(charm: *Charm, msg: []u8) [tag_length]u8 { var squeezed: [16]u8 = undefined; var bytes = charm.x.asBytes(); var off: usize = 0; while (off + 16 < msg.len) : (off += 16) { charm.x.endianSwapRate(); mem.copy(u8, squeezed[0..], bytes[0..16]); xor128(bytes[0..16], msg[off..][0..16]); charm.x.endianSwapRate(); xor128(msg[off..][0..16], squeezed[0..]); charm.x.permute(); } const leftover = msg.len - off; var padded = [_]u8{0} ** (16 + 1); mem.copy(u8, padded[0..leftover], msg[off..][0..leftover]); padded[leftover] = 0x80; charm.x.endianSwapRate(); mem.copy(u8, squeezed[0..], bytes[0..16]); xor128(bytes[0..16], padded[0..16]); charm.x.endianSwapRate(); charm.x.asWords()[11] ^= (@as(u32, 1) << 24 | @intCast(u32, leftover) >> 4 << 25 | @as(u32, 1) << 26); xor128(padded[0..16], squeezed[0..]); mem.copy(u8, msg[off..][0..leftover], padded[0..leftover]); charm.x.permute(); return charm.x.squeezePermute(); } pub fn decrypt(charm: *Charm, msg: []u8, expected_tag: [tag_length]u8) !void { var squeezed: [16]u8 = undefined; var bytes = charm.x.asBytes(); var off: usize = 0; while (off + 16 < msg.len) : (off += 16) { charm.x.endianSwapRate(); mem.copy(u8, squeezed[0..], bytes[0..16]); xor128(msg[off..][0..16], squeezed[0..]); xor128(bytes[0..16], msg[off..][0..16]); charm.x.endianSwapRate(); charm.x.permute(); } const leftover = msg.len - off; var padded = [_]u8{0} ** (16 + 1); mem.copy(u8, padded[0..leftover], msg[off..][0..leftover]); charm.x.endianSwapRate(); mem.set(u8, squeezed[0..], 0); mem.copy(u8, squeezed[0..leftover], bytes[0..leftover]); xor128(padded[0..16], squeezed[0..]); padded[leftover] = 0x80; xor128(bytes[0..16], padded[0..16]); charm.x.endianSwapRate(); charm.x.asWords()[11] ^= (@as(u32, 1) << 24 | @intCast(u32, leftover) >> 4 << 25 | @as(u32, 1) << 26); mem.copy(u8, msg[off..][0..leftover], padded[0..leftover]); charm.x.permute(); const tag = charm.x.squeezePermute(); if (!equal128(expected_tag, tag)) { mem.set(u8, msg, 0); return error.AuthenticationFailed; } } pub fn hash(charm: *Charm, msg: []const u8) [hash_length]u8 { var bytes = charm.x.asBytes(); var off: usize = 0; while (off + 16 < msg.len) : (off += 16) { charm.x.endianSwapRate(); xor128(bytes[0..16], msg[off..][0..16]); charm.x.endianSwapRate(); charm.x.permute(); } const leftover = msg.len - off; var padded = [_]u8{0} ** (16 + 1); mem.copy(u8, padded[0..leftover], msg[off..][0..leftover]); padded[leftover] = 0x80; charm.x.endianSwapRate(); xor128(bytes[0..16], padded[0..16]); charm.x.endianSwapRate(); charm.x.asWords()[11] ^= (@as(u32, 1) << 24 | @intCast(u32, leftover) >> 4 << 25); charm.x.permute(); var h: [hash_length]u8 = undefined; mem.copy(u8, h[0..16], charm.x.squeezePermute()[0..]); mem.copy(u8, h[16..32], charm.x.squeezePermute()[0..]); return h; } }; test "charm" { _ = @import("test.zig"); }
src/main.zig
const std = @import("std"); const builtin = @import("builtin"); // clz - count leading zeroes // - clzXi2 for unoptimized little and big endian // - __clzsi2_thumb1: assume a != 0 // - __clzsi2_arm32: assume a != 0 // ctz - count trailing zeroes // - ctzXi2 for unoptimized little and big endian // ffs - find first set // * ffs = (a == 0) => 0, (a != 0) => ctz + 1 // * dont pay for `if (x == 0) return shift;` inside ctz // - ffsXi2 for unoptimized little and big endian inline fn clzXi2(comptime T: type, a: T) i32 { @setRuntimeSafety(builtin.is_test); var x = switch (@bitSizeOf(T)) { 32 => @bitCast(u32, a), 64 => @bitCast(u64, a), 128 => @bitCast(u128, a), else => unreachable, }; var n: T = @bitSizeOf(T); // Count first bit set using binary search, from Hacker's Delight var y: @TypeOf(x) = 0; comptime var shift: u8 = @bitSizeOf(T); inline while (shift > 0) { shift = shift >> 1; y = x >> shift; if (y != 0) { n = n - shift; x = y; } } return @intCast(i32, n - @bitCast(T, x)); } fn __clzsi2_thumb1() callconv(.Naked) void { @setRuntimeSafety(false); // Similar to the generic version with the last two rounds replaced by a LUT asm volatile ( \\ movs r1, #32 \\ lsrs r2, r0, #16 \\ beq 1f \\ subs r1, #16 \\ movs r0, r2 \\ 1: \\ lsrs r2, r0, #8 \\ beq 1f \\ subs r1, #8 \\ movs r0, r2 \\ 1: \\ lsrs r2, r0, #4 \\ beq 1f \\ subs r1, #4 \\ movs r0, r2 \\ 1: \\ ldr r3, =LUT \\ ldrb r0, [r3, r0] \\ subs r0, r1, r0 \\ bx lr \\ .p2align 2 \\ // Number of bits set in the 0-15 range \\ LUT: \\ .byte 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4 ); unreachable; } fn __clzsi2_arm32() callconv(.Naked) void { @setRuntimeSafety(false); asm volatile ( \\ // Assumption: n != 0 \\ // r0: n \\ // r1: count of leading zeros in n + 1 \\ // r2: scratch register for shifted r0 \\ mov r1, #1 \\ \\ // Basic block: \\ // if ((r0 >> SHIFT) == 0) \\ // r1 += SHIFT; \\ // else \\ // r0 >>= SHIFT; \\ // for descending powers of two as SHIFT. \\ lsrs r2, r0, #16 \\ movne r0, r2 \\ addeq r1, #16 \\ \\ lsrs r2, r0, #8 \\ movne r0, r2 \\ addeq r1, #8 \\ \\ lsrs r2, r0, #4 \\ movne r0, r2 \\ addeq r1, #4 \\ \\ lsrs r2, r0, #2 \\ movne r0, r2 \\ addeq r1, #2 \\ \\ // The basic block invariants at this point are (r0 >> 2) == 0 and \\ // r0 != 0. This means 1 <= r0 <= 3 and 0 <= (r0 >> 1) <= 1. \\ // \\ // r0 | (r0 >> 1) == 0 | (r0 >> 1) == 1 | -(r0 >> 1) | 1 - (r0 >> 1)f \\ // ---+----------------+----------------+------------+-------------- \\ // 1 | 1 | 0 | 0 | 1 \\ // 2 | 0 | 1 | -1 | 0 \\ // 3 | 0 | 1 | -1 | 0 \\ // \\ // The r1's initial value of 1 compensates for the 1 here. \\ sub r0, r1, r0, lsr #1 \\ bx lr ); unreachable; } fn clzsi2_generic(a: i32) callconv(.C) i32 { return clzXi2(i32, a); } pub const __clzsi2 = switch (builtin.cpu.arch) { .arm, .armeb, .thumb, .thumbeb => impl: { const use_thumb1 = (builtin.cpu.arch.isThumb() or std.Target.arm.featureSetHas(builtin.cpu.features, .noarm)) and !std.Target.arm.featureSetHas(builtin.cpu.features, .thumb2); if (use_thumb1) { break :impl __clzsi2_thumb1; } // From here on we're either targeting Thumb2 or ARM. else if (!builtin.cpu.arch.isThumb()) { break :impl __clzsi2_arm32; } // Use the generic implementation otherwise. else break :impl clzsi2_generic; }, else => clzsi2_generic, }; pub fn __clzdi2(a: i64) callconv(.C) i32 { return clzXi2(i64, a); } pub fn __clzti2(a: i128) callconv(.C) i32 { return clzXi2(i128, a); } inline fn ctzXi2(comptime T: type, a: T) i32 { @setRuntimeSafety(builtin.is_test); var x = switch (@bitSizeOf(T)) { 32 => @bitCast(u32, a), 64 => @bitCast(u64, a), 128 => @bitCast(u128, a), else => unreachable, }; var n: T = 1; // Number of trailing zeroes as binary search, from Hacker's Delight var mask: @TypeOf(x) = std.math.maxInt(@TypeOf(x)); comptime var shift = @bitSizeOf(T); if (x == 0) return shift; inline while (shift > 1) { shift = shift >> 1; mask = mask >> shift; if ((x & mask) == 0) { n = n + shift; x = x >> shift; } } return @intCast(i32, n - @bitCast(T, (x & 1))); } pub fn __ctzsi2(a: i32) callconv(.C) i32 { return ctzXi2(i32, a); } pub fn __ctzdi2(a: i64) callconv(.C) i32 { return ctzXi2(i64, a); } pub fn __ctzti2(a: i128) callconv(.C) i32 { return ctzXi2(i128, a); } inline fn ffsXi2(comptime T: type, a: T) i32 { @setRuntimeSafety(builtin.is_test); var x = switch (@bitSizeOf(T)) { 32 => @bitCast(u32, a), 64 => @bitCast(u64, a), 128 => @bitCast(u128, a), else => unreachable, }; var n: T = 1; // adapted from Number of trailing zeroes (see ctzXi2) var mask: @TypeOf(x) = std.math.maxInt(@TypeOf(x)); comptime var shift = @bitSizeOf(T); // In contrast to ctz return 0 if (x == 0) return 0; inline while (shift > 1) { shift = shift >> 1; mask = mask >> shift; if ((x & mask) == 0) { n = n + shift; x = x >> shift; } } // return ctz + 1 return @intCast(i32, n - @bitCast(T, (x & 1))) + @as(i32, 1); } pub fn __ffssi2(a: i32) callconv(.C) i32 { return ffsXi2(i32, a); } pub fn __ffsdi2(a: i64) callconv(.C) i32 { return ffsXi2(i64, a); } pub fn __ffsti2(a: i128) callconv(.C) i32 { return ffsXi2(i128, a); } test { _ = @import("clzsi2_test.zig"); _ = @import("clzdi2_test.zig"); _ = @import("clzti2_test.zig"); _ = @import("ctzsi2_test.zig"); _ = @import("ctzdi2_test.zig"); _ = @import("ctzti2_test.zig"); _ = @import("ffssi2_test.zig"); _ = @import("ffsdi2_test.zig"); _ = @import("ffsti2_test.zig"); }
lib/std/special/compiler_rt/count0bits.zig
const neg = @import("negXi2.zig"); const testing = @import("std").testing; fn test__negti2(a: i128, expected: i128) !void { var result = neg.__negti2(a); try testing.expectEqual(expected, result); } test "negdi2" { // TODO ensuring that math.minInt(i128); returns error try test__negti2(-3, 3); try test__negti2(-2, 2); try test__negti2(-1, 1); try test__negti2(0, 0); // special case for 2s complement try test__negti2(1, -1); try test__negti2(2, -2); try test__negti2(3, -3); // max_usable == MAX(i32) == -MIN(i32) // == 170141183460469231731687303715884105727 // == 7fffffffffffffffffffffffffffffff // divTrunc: max_usable / i, i=1,2,3,5,100 // 7fffffffffffffffffffffffffffffff / i try test__negti2(-56713727820156410577229101238628035242, 56713727820156410577229101238628035242); try test__negti2(56713727820156410577229101238628035242, -56713727820156410577229101238628035242); try test__negti2(-34028236692093846346337460743176821145, 34028236692093846346337460743176821145); try test__negti2(34028236692093846346337460743176821145, -34028236692093846346337460743176821145); try test__negti2(-17014118346046923173168730371588410572, 17014118346046923173168730371588410572); try test__negti2(17014118346046923173168730371588410572, -17014118346046923173168730371588410572); // shifting: max_usable >> i, i=0..bitsize-4 // 7fffffffffffffffffffffffffffffff >> i // 7fffffffffffffffffffffffffffffff >> i + 1 // 7fffffffffffffffffffffffffffffff >> i + 3 // 7fffffffffffffffffffffffffffffff >> i + 7 try test__negti2(-170141183460469231731687303715884105727, 170141183460469231731687303715884105727); try test__negti2(170141183460469231731687303715884105727, -170141183460469231731687303715884105727); try test__negti2(-170141183460469231731687303715884105726, 170141183460469231731687303715884105726); try test__negti2(170141183460469231731687303715884105726, -170141183460469231731687303715884105726); try test__negti2(-170141183460469231731687303715884105724, 170141183460469231731687303715884105724); try test__negti2(170141183460469231731687303715884105724, -170141183460469231731687303715884105724); try test__negti2(-170141183460469231731687303715884105720, 170141183460469231731687303715884105720); try test__negti2(170141183460469231731687303715884105720, -170141183460469231731687303715884105720); try test__negti2(-85070591730234615865843651857942052863, 85070591730234615865843651857942052863); try test__negti2(85070591730234615865843651857942052863, -85070591730234615865843651857942052863); try test__negti2(-85070591730234615865843651857942052862, 85070591730234615865843651857942052862); try test__negti2(85070591730234615865843651857942052862, -85070591730234615865843651857942052862); try test__negti2(-85070591730234615865843651857942052860, 85070591730234615865843651857942052860); try test__negti2(85070591730234615865843651857942052860, -85070591730234615865843651857942052860); try test__negti2(-85070591730234615865843651857942052856, 85070591730234615865843651857942052856); try test__negti2(85070591730234615865843651857942052856, -85070591730234615865843651857942052856); try test__negti2(-42535295865117307932921825928971026431, 42535295865117307932921825928971026431); try test__negti2(42535295865117307932921825928971026431, -42535295865117307932921825928971026431); try test__negti2(-42535295865117307932921825928971026430, 42535295865117307932921825928971026430); try test__negti2(42535295865117307932921825928971026430, -42535295865117307932921825928971026430); try test__negti2(-42535295865117307932921825928971026428, 42535295865117307932921825928971026428); try test__negti2(42535295865117307932921825928971026428, -42535295865117307932921825928971026428); try test__negti2(-42535295865117307932921825928971026424, 42535295865117307932921825928971026424); try test__negti2(42535295865117307932921825928971026424, -42535295865117307932921825928971026424); try test__negti2(-21267647932558653966460912964485513215, 21267647932558653966460912964485513215); try test__negti2(21267647932558653966460912964485513215, -21267647932558653966460912964485513215); try test__negti2(-21267647932558653966460912964485513214, 21267647932558653966460912964485513214); try test__negti2(21267647932558653966460912964485513214, -21267647932558653966460912964485513214); try test__negti2(-21267647932558653966460912964485513212, 21267647932558653966460912964485513212); try test__negti2(21267647932558653966460912964485513212, -21267647932558653966460912964485513212); try test__negti2(-21267647932558653966460912964485513208, 21267647932558653966460912964485513208); try test__negti2(21267647932558653966460912964485513208, -21267647932558653966460912964485513208); try test__negti2(-10633823966279326983230456482242756607, 10633823966279326983230456482242756607); try test__negti2(10633823966279326983230456482242756607, -10633823966279326983230456482242756607); try test__negti2(-10633823966279326983230456482242756606, 10633823966279326983230456482242756606); try test__negti2(10633823966279326983230456482242756606, -10633823966279326983230456482242756606); try test__negti2(-10633823966279326983230456482242756604, 10633823966279326983230456482242756604); try test__negti2(10633823966279326983230456482242756604, -10633823966279326983230456482242756604); try test__negti2(-10633823966279326983230456482242756600, 10633823966279326983230456482242756600); try test__negti2(10633823966279326983230456482242756600, -10633823966279326983230456482242756600); try test__negti2(-5316911983139663491615228241121378303, 5316911983139663491615228241121378303); try test__negti2(5316911983139663491615228241121378303, -5316911983139663491615228241121378303); try test__negti2(-5316911983139663491615228241121378302, 5316911983139663491615228241121378302); try test__negti2(5316911983139663491615228241121378302, -5316911983139663491615228241121378302); try test__negti2(-5316911983139663491615228241121378300, 5316911983139663491615228241121378300); try test__negti2(5316911983139663491615228241121378300, -5316911983139663491615228241121378300); try test__negti2(-5316911983139663491615228241121378296, 5316911983139663491615228241121378296); try test__negti2(5316911983139663491615228241121378296, -5316911983139663491615228241121378296); try test__negti2(-2658455991569831745807614120560689151, 2658455991569831745807614120560689151); try test__negti2(2658455991569831745807614120560689151, -2658455991569831745807614120560689151); try test__negti2(-2658455991569831745807614120560689150, 2658455991569831745807614120560689150); try test__negti2(2658455991569831745807614120560689150, -2658455991569831745807614120560689150); try test__negti2(-2658455991569831745807614120560689148, 2658455991569831745807614120560689148); try test__negti2(2658455991569831745807614120560689148, -2658455991569831745807614120560689148); try test__negti2(-2658455991569831745807614120560689144, 2658455991569831745807614120560689144); try test__negti2(2658455991569831745807614120560689144, -2658455991569831745807614120560689144); try test__negti2(-1329227995784915872903807060280344575, 1329227995784915872903807060280344575); try test__negti2(1329227995784915872903807060280344575, -1329227995784915872903807060280344575); try test__negti2(-1329227995784915872903807060280344574, 1329227995784915872903807060280344574); try test__negti2(1329227995784915872903807060280344574, -1329227995784915872903807060280344574); try test__negti2(-1329227995784915872903807060280344572, 1329227995784915872903807060280344572); try test__negti2(1329227995784915872903807060280344572, -1329227995784915872903807060280344572); try test__negti2(-1329227995784915872903807060280344568, 1329227995784915872903807060280344568); try test__negti2(1329227995784915872903807060280344568, -1329227995784915872903807060280344568); try test__negti2(-664613997892457936451903530140172287, 664613997892457936451903530140172287); try test__negti2(664613997892457936451903530140172287, -664613997892457936451903530140172287); try test__negti2(-664613997892457936451903530140172286, 664613997892457936451903530140172286); try test__negti2(664613997892457936451903530140172286, -664613997892457936451903530140172286); try test__negti2(-664613997892457936451903530140172284, 664613997892457936451903530140172284); try test__negti2(664613997892457936451903530140172284, -664613997892457936451903530140172284); try test__negti2(-664613997892457936451903530140172280, 664613997892457936451903530140172280); try test__negti2(664613997892457936451903530140172280, -664613997892457936451903530140172280); try test__negti2(-332306998946228968225951765070086143, 332306998946228968225951765070086143); try test__negti2(332306998946228968225951765070086143, -332306998946228968225951765070086143); try test__negti2(-332306998946228968225951765070086142, 332306998946228968225951765070086142); try test__negti2(332306998946228968225951765070086142, -332306998946228968225951765070086142); try test__negti2(-332306998946228968225951765070086140, 332306998946228968225951765070086140); try test__negti2(332306998946228968225951765070086140, -332306998946228968225951765070086140); try test__negti2(-332306998946228968225951765070086136, 332306998946228968225951765070086136); try test__negti2(332306998946228968225951765070086136, -332306998946228968225951765070086136); try test__negti2(-166153499473114484112975882535043071, 166153499473114484112975882535043071); try test__negti2(166153499473114484112975882535043071, -166153499473114484112975882535043071); try test__negti2(-166153499473114484112975882535043070, 166153499473114484112975882535043070); try test__negti2(166153499473114484112975882535043070, -166153499473114484112975882535043070); try test__negti2(-166153499473114484112975882535043068, 166153499473114484112975882535043068); try test__negti2(166153499473114484112975882535043068, -166153499473114484112975882535043068); try test__negti2(-166153499473114484112975882535043064, 166153499473114484112975882535043064); try test__negti2(166153499473114484112975882535043064, -166153499473114484112975882535043064); try test__negti2(-83076749736557242056487941267521535, 83076749736557242056487941267521535); try test__negti2(83076749736557242056487941267521535, -83076749736557242056487941267521535); try test__negti2(-83076749736557242056487941267521534, 83076749736557242056487941267521534); try test__negti2(83076749736557242056487941267521534, -83076749736557242056487941267521534); try test__negti2(-83076749736557242056487941267521532, 83076749736557242056487941267521532); try test__negti2(83076749736557242056487941267521532, -83076749736557242056487941267521532); try test__negti2(-83076749736557242056487941267521528, 83076749736557242056487941267521528); try test__negti2(83076749736557242056487941267521528, -83076749736557242056487941267521528); try test__negti2(-41538374868278621028243970633760767, 41538374868278621028243970633760767); try test__negti2(41538374868278621028243970633760767, -41538374868278621028243970633760767); try test__negti2(-41538374868278621028243970633760766, 41538374868278621028243970633760766); try test__negti2(41538374868278621028243970633760766, -41538374868278621028243970633760766); try test__negti2(-41538374868278621028243970633760764, 41538374868278621028243970633760764); try test__negti2(41538374868278621028243970633760764, -41538374868278621028243970633760764); try test__negti2(-41538374868278621028243970633760760, 41538374868278621028243970633760760); try test__negti2(41538374868278621028243970633760760, -41538374868278621028243970633760760); try test__negti2(-20769187434139310514121985316880383, 20769187434139310514121985316880383); try test__negti2(20769187434139310514121985316880383, -20769187434139310514121985316880383); try test__negti2(-20769187434139310514121985316880382, 20769187434139310514121985316880382); try test__negti2(20769187434139310514121985316880382, -20769187434139310514121985316880382); try test__negti2(-20769187434139310514121985316880380, 20769187434139310514121985316880380); try test__negti2(20769187434139310514121985316880380, -20769187434139310514121985316880380); try test__negti2(-20769187434139310514121985316880376, 20769187434139310514121985316880376); try test__negti2(20769187434139310514121985316880376, -20769187434139310514121985316880376); try test__negti2(-10384593717069655257060992658440191, 10384593717069655257060992658440191); try test__negti2(10384593717069655257060992658440191, -10384593717069655257060992658440191); try test__negti2(-10384593717069655257060992658440190, 10384593717069655257060992658440190); try test__negti2(10384593717069655257060992658440190, -10384593717069655257060992658440190); try test__negti2(-10384593717069655257060992658440188, 10384593717069655257060992658440188); try test__negti2(10384593717069655257060992658440188, -10384593717069655257060992658440188); try test__negti2(-10384593717069655257060992658440184, 10384593717069655257060992658440184); try test__negti2(10384593717069655257060992658440184, -10384593717069655257060992658440184); try test__negti2(-5192296858534827628530496329220095, 5192296858534827628530496329220095); try test__negti2(5192296858534827628530496329220095, -5192296858534827628530496329220095); try test__negti2(-5192296858534827628530496329220094, 5192296858534827628530496329220094); try test__negti2(5192296858534827628530496329220094, -5192296858534827628530496329220094); try test__negti2(-5192296858534827628530496329220092, 5192296858534827628530496329220092); try test__negti2(5192296858534827628530496329220092, -5192296858534827628530496329220092); try test__negti2(-5192296858534827628530496329220088, 5192296858534827628530496329220088); try test__negti2(5192296858534827628530496329220088, -5192296858534827628530496329220088); try test__negti2(-2596148429267413814265248164610047, 2596148429267413814265248164610047); try test__negti2(2596148429267413814265248164610047, -2596148429267413814265248164610047); try test__negti2(-2596148429267413814265248164610046, 2596148429267413814265248164610046); try test__negti2(2596148429267413814265248164610046, -2596148429267413814265248164610046); try test__negti2(-2596148429267413814265248164610044, 2596148429267413814265248164610044); try test__negti2(2596148429267413814265248164610044, -2596148429267413814265248164610044); try test__negti2(-2596148429267413814265248164610040, 2596148429267413814265248164610040); try test__negti2(2596148429267413814265248164610040, -2596148429267413814265248164610040); try test__negti2(-1298074214633706907132624082305023, 1298074214633706907132624082305023); try test__negti2(1298074214633706907132624082305023, -1298074214633706907132624082305023); try test__negti2(-1298074214633706907132624082305022, 1298074214633706907132624082305022); try test__negti2(1298074214633706907132624082305022, -1298074214633706907132624082305022); try test__negti2(-1298074214633706907132624082305020, 1298074214633706907132624082305020); try test__negti2(1298074214633706907132624082305020, -1298074214633706907132624082305020); try test__negti2(-1298074214633706907132624082305016, 1298074214633706907132624082305016); try test__negti2(1298074214633706907132624082305016, -1298074214633706907132624082305016); try test__negti2(-649037107316853453566312041152511, 649037107316853453566312041152511); try test__negti2(649037107316853453566312041152511, -649037107316853453566312041152511); try test__negti2(-649037107316853453566312041152510, 649037107316853453566312041152510); try test__negti2(649037107316853453566312041152510, -649037107316853453566312041152510); try test__negti2(-649037107316853453566312041152508, 649037107316853453566312041152508); try test__negti2(649037107316853453566312041152508, -649037107316853453566312041152508); try test__negti2(-649037107316853453566312041152504, 649037107316853453566312041152504); try test__negti2(649037107316853453566312041152504, -649037107316853453566312041152504); try test__negti2(-324518553658426726783156020576255, 324518553658426726783156020576255); try test__negti2(324518553658426726783156020576255, -324518553658426726783156020576255); try test__negti2(-324518553658426726783156020576254, 324518553658426726783156020576254); try test__negti2(324518553658426726783156020576254, -324518553658426726783156020576254); try test__negti2(-324518553658426726783156020576252, 324518553658426726783156020576252); try test__negti2(324518553658426726783156020576252, -324518553658426726783156020576252); try test__negti2(-324518553658426726783156020576248, 324518553658426726783156020576248); try test__negti2(324518553658426726783156020576248, -324518553658426726783156020576248); try test__negti2(-162259276829213363391578010288127, 162259276829213363391578010288127); try test__negti2(162259276829213363391578010288127, -162259276829213363391578010288127); try test__negti2(-162259276829213363391578010288126, 162259276829213363391578010288126); try test__negti2(162259276829213363391578010288126, -162259276829213363391578010288126); try test__negti2(-162259276829213363391578010288124, 162259276829213363391578010288124); try test__negti2(162259276829213363391578010288124, -162259276829213363391578010288124); try test__negti2(-162259276829213363391578010288120, 162259276829213363391578010288120); try test__negti2(162259276829213363391578010288120, -162259276829213363391578010288120); try test__negti2(-81129638414606681695789005144063, 81129638414606681695789005144063); try test__negti2(81129638414606681695789005144063, -81129638414606681695789005144063); try test__negti2(-81129638414606681695789005144062, 81129638414606681695789005144062); try test__negti2(81129638414606681695789005144062, -81129638414606681695789005144062); try test__negti2(-81129638414606681695789005144060, 81129638414606681695789005144060); try test__negti2(81129638414606681695789005144060, -81129638414606681695789005144060); try test__negti2(-81129638414606681695789005144056, 81129638414606681695789005144056); try test__negti2(81129638414606681695789005144056, -81129638414606681695789005144056); try test__negti2(-40564819207303340847894502572031, 40564819207303340847894502572031); try test__negti2(40564819207303340847894502572031, -40564819207303340847894502572031); try test__negti2(-40564819207303340847894502572030, 40564819207303340847894502572030); try test__negti2(40564819207303340847894502572030, -40564819207303340847894502572030); try test__negti2(-40564819207303340847894502572028, 40564819207303340847894502572028); try test__negti2(40564819207303340847894502572028, -40564819207303340847894502572028); try test__negti2(-40564819207303340847894502572024, 40564819207303340847894502572024); try test__negti2(40564819207303340847894502572024, -40564819207303340847894502572024); try test__negti2(-20282409603651670423947251286015, 20282409603651670423947251286015); try test__negti2(20282409603651670423947251286015, -20282409603651670423947251286015); try test__negti2(-20282409603651670423947251286014, 20282409603651670423947251286014); try test__negti2(20282409603651670423947251286014, -20282409603651670423947251286014); try test__negti2(-20282409603651670423947251286012, 20282409603651670423947251286012); try test__negti2(20282409603651670423947251286012, -20282409603651670423947251286012); try test__negti2(-20282409603651670423947251286008, 20282409603651670423947251286008); try test__negti2(20282409603651670423947251286008, -20282409603651670423947251286008); try test__negti2(-10141204801825835211973625643007, 10141204801825835211973625643007); try test__negti2(10141204801825835211973625643007, -10141204801825835211973625643007); try test__negti2(-10141204801825835211973625643006, 10141204801825835211973625643006); try test__negti2(10141204801825835211973625643006, -10141204801825835211973625643006); try test__negti2(-10141204801825835211973625643004, 10141204801825835211973625643004); try test__negti2(10141204801825835211973625643004, -10141204801825835211973625643004); try test__negti2(-10141204801825835211973625643000, 10141204801825835211973625643000); try test__negti2(10141204801825835211973625643000, -10141204801825835211973625643000); try test__negti2(-5070602400912917605986812821503, 5070602400912917605986812821503); try test__negti2(5070602400912917605986812821503, -5070602400912917605986812821503); try test__negti2(-5070602400912917605986812821502, 5070602400912917605986812821502); try test__negti2(5070602400912917605986812821502, -5070602400912917605986812821502); try test__negti2(-5070602400912917605986812821500, 5070602400912917605986812821500); try test__negti2(5070602400912917605986812821500, -5070602400912917605986812821500); try test__negti2(-5070602400912917605986812821496, 5070602400912917605986812821496); try test__negti2(5070602400912917605986812821496, -5070602400912917605986812821496); try test__negti2(-2535301200456458802993406410751, 2535301200456458802993406410751); try test__negti2(2535301200456458802993406410751, -2535301200456458802993406410751); try test__negti2(-2535301200456458802993406410750, 2535301200456458802993406410750); try test__negti2(2535301200456458802993406410750, -2535301200456458802993406410750); try test__negti2(-2535301200456458802993406410748, 2535301200456458802993406410748); try test__negti2(2535301200456458802993406410748, -2535301200456458802993406410748); try test__negti2(-2535301200456458802993406410744, 2535301200456458802993406410744); try test__negti2(2535301200456458802993406410744, -2535301200456458802993406410744); try test__negti2(-1267650600228229401496703205375, 1267650600228229401496703205375); try test__negti2(1267650600228229401496703205375, -1267650600228229401496703205375); try test__negti2(-1267650600228229401496703205374, 1267650600228229401496703205374); try test__negti2(1267650600228229401496703205374, -1267650600228229401496703205374); try test__negti2(-1267650600228229401496703205372, 1267650600228229401496703205372); try test__negti2(1267650600228229401496703205372, -1267650600228229401496703205372); try test__negti2(-1267650600228229401496703205368, 1267650600228229401496703205368); try test__negti2(1267650600228229401496703205368, -1267650600228229401496703205368); try test__negti2(-633825300114114700748351602687, 633825300114114700748351602687); try test__negti2(633825300114114700748351602687, -633825300114114700748351602687); try test__negti2(-633825300114114700748351602686, 633825300114114700748351602686); try test__negti2(633825300114114700748351602686, -633825300114114700748351602686); try test__negti2(-633825300114114700748351602684, 633825300114114700748351602684); try test__negti2(633825300114114700748351602684, -633825300114114700748351602684); try test__negti2(-633825300114114700748351602680, 633825300114114700748351602680); try test__negti2(633825300114114700748351602680, -633825300114114700748351602680); try test__negti2(-316912650057057350374175801343, 316912650057057350374175801343); try test__negti2(316912650057057350374175801343, -316912650057057350374175801343); try test__negti2(-316912650057057350374175801342, 316912650057057350374175801342); try test__negti2(316912650057057350374175801342, -316912650057057350374175801342); try test__negti2(-316912650057057350374175801340, 316912650057057350374175801340); try test__negti2(316912650057057350374175801340, -316912650057057350374175801340); try test__negti2(-316912650057057350374175801336, 316912650057057350374175801336); try test__negti2(316912650057057350374175801336, -316912650057057350374175801336); try test__negti2(-158456325028528675187087900671, 158456325028528675187087900671); try test__negti2(158456325028528675187087900671, -158456325028528675187087900671); try test__negti2(-158456325028528675187087900670, 158456325028528675187087900670); try test__negti2(158456325028528675187087900670, -158456325028528675187087900670); try test__negti2(-158456325028528675187087900668, 158456325028528675187087900668); try test__negti2(158456325028528675187087900668, -158456325028528675187087900668); try test__negti2(-158456325028528675187087900664, 158456325028528675187087900664); try test__negti2(158456325028528675187087900664, -158456325028528675187087900664); try test__negti2(-79228162514264337593543950335, 79228162514264337593543950335); try test__negti2(79228162514264337593543950335, -79228162514264337593543950335); try test__negti2(-79228162514264337593543950334, 79228162514264337593543950334); try test__negti2(79228162514264337593543950334, -79228162514264337593543950334); try test__negti2(-79228162514264337593543950332, 79228162514264337593543950332); try test__negti2(79228162514264337593543950332, -79228162514264337593543950332); try test__negti2(-79228162514264337593543950328, 79228162514264337593543950328); try test__negti2(79228162514264337593543950328, -79228162514264337593543950328); try test__negti2(-39614081257132168796771975167, 39614081257132168796771975167); try test__negti2(39614081257132168796771975167, -39614081257132168796771975167); try test__negti2(-39614081257132168796771975166, 39614081257132168796771975166); try test__negti2(39614081257132168796771975166, -39614081257132168796771975166); try test__negti2(-39614081257132168796771975164, 39614081257132168796771975164); try test__negti2(39614081257132168796771975164, -39614081257132168796771975164); try test__negti2(-39614081257132168796771975160, 39614081257132168796771975160); try test__negti2(39614081257132168796771975160, -39614081257132168796771975160); try test__negti2(-19807040628566084398385987583, 19807040628566084398385987583); try test__negti2(19807040628566084398385987583, -19807040628566084398385987583); try test__negti2(-19807040628566084398385987582, 19807040628566084398385987582); try test__negti2(19807040628566084398385987582, -19807040628566084398385987582); try test__negti2(-19807040628566084398385987580, 19807040628566084398385987580); try test__negti2(19807040628566084398385987580, -19807040628566084398385987580); try test__negti2(-19807040628566084398385987576, 19807040628566084398385987576); try test__negti2(19807040628566084398385987576, -19807040628566084398385987576); try test__negti2(-9903520314283042199192993791, 9903520314283042199192993791); try test__negti2(9903520314283042199192993791, -9903520314283042199192993791); try test__negti2(-9903520314283042199192993790, 9903520314283042199192993790); try test__negti2(9903520314283042199192993790, -9903520314283042199192993790); try test__negti2(-9903520314283042199192993788, 9903520314283042199192993788); try test__negti2(9903520314283042199192993788, -9903520314283042199192993788); try test__negti2(-9903520314283042199192993784, 9903520314283042199192993784); try test__negti2(9903520314283042199192993784, -9903520314283042199192993784); try test__negti2(-4951760157141521099596496895, 4951760157141521099596496895); try test__negti2(4951760157141521099596496895, -4951760157141521099596496895); try test__negti2(-4951760157141521099596496894, 4951760157141521099596496894); try test__negti2(4951760157141521099596496894, -4951760157141521099596496894); try test__negti2(-4951760157141521099596496892, 4951760157141521099596496892); try test__negti2(4951760157141521099596496892, -4951760157141521099596496892); try test__negti2(-4951760157141521099596496888, 4951760157141521099596496888); try test__negti2(4951760157141521099596496888, -4951760157141521099596496888); try test__negti2(-2475880078570760549798248447, 2475880078570760549798248447); try test__negti2(2475880078570760549798248447, -2475880078570760549798248447); try test__negti2(-2475880078570760549798248446, 2475880078570760549798248446); try test__negti2(2475880078570760549798248446, -2475880078570760549798248446); try test__negti2(-2475880078570760549798248444, 2475880078570760549798248444); try test__negti2(2475880078570760549798248444, -2475880078570760549798248444); try test__negti2(-2475880078570760549798248440, 2475880078570760549798248440); try test__negti2(2475880078570760549798248440, -2475880078570760549798248440); try test__negti2(-1237940039285380274899124223, 1237940039285380274899124223); try test__negti2(1237940039285380274899124223, -1237940039285380274899124223); try test__negti2(-1237940039285380274899124222, 1237940039285380274899124222); try test__negti2(1237940039285380274899124222, -1237940039285380274899124222); try test__negti2(-1237940039285380274899124220, 1237940039285380274899124220); try test__negti2(1237940039285380274899124220, -1237940039285380274899124220); try test__negti2(-1237940039285380274899124216, 1237940039285380274899124216); try test__negti2(1237940039285380274899124216, -1237940039285380274899124216); try test__negti2(-618970019642690137449562111, 618970019642690137449562111); try test__negti2(618970019642690137449562111, -618970019642690137449562111); try test__negti2(-618970019642690137449562110, 618970019642690137449562110); try test__negti2(618970019642690137449562110, -618970019642690137449562110); try test__negti2(-618970019642690137449562108, 618970019642690137449562108); try test__negti2(618970019642690137449562108, -618970019642690137449562108); try test__negti2(-618970019642690137449562104, 618970019642690137449562104); try test__negti2(618970019642690137449562104, -618970019642690137449562104); try test__negti2(-309485009821345068724781055, 309485009821345068724781055); try test__negti2(309485009821345068724781055, -309485009821345068724781055); try test__negti2(-309485009821345068724781054, 309485009821345068724781054); try test__negti2(309485009821345068724781054, -309485009821345068724781054); try test__negti2(-309485009821345068724781052, 309485009821345068724781052); try test__negti2(309485009821345068724781052, -309485009821345068724781052); try test__negti2(-309485009821345068724781048, 309485009821345068724781048); try test__negti2(309485009821345068724781048, -309485009821345068724781048); try test__negti2(-154742504910672534362390527, 154742504910672534362390527); try test__negti2(154742504910672534362390527, -154742504910672534362390527); try test__negti2(-154742504910672534362390526, 154742504910672534362390526); try test__negti2(154742504910672534362390526, -154742504910672534362390526); try test__negti2(-154742504910672534362390524, 154742504910672534362390524); try test__negti2(154742504910672534362390524, -154742504910672534362390524); try test__negti2(-154742504910672534362390520, 154742504910672534362390520); try test__negti2(154742504910672534362390520, -154742504910672534362390520); try test__negti2(-77371252455336267181195263, 77371252455336267181195263); try test__negti2(77371252455336267181195263, -77371252455336267181195263); try test__negti2(-77371252455336267181195262, 77371252455336267181195262); try test__negti2(77371252455336267181195262, -77371252455336267181195262); try test__negti2(-77371252455336267181195260, 77371252455336267181195260); try test__negti2(77371252455336267181195260, -77371252455336267181195260); try test__negti2(-77371252455336267181195256, 77371252455336267181195256); try test__negti2(77371252455336267181195256, -77371252455336267181195256); try test__negti2(-38685626227668133590597631, 38685626227668133590597631); try test__negti2(38685626227668133590597631, -38685626227668133590597631); try test__negti2(-38685626227668133590597630, 38685626227668133590597630); try test__negti2(38685626227668133590597630, -38685626227668133590597630); try test__negti2(-38685626227668133590597628, 38685626227668133590597628); try test__negti2(38685626227668133590597628, -38685626227668133590597628); try test__negti2(-38685626227668133590597624, 38685626227668133590597624); try test__negti2(38685626227668133590597624, -38685626227668133590597624); try test__negti2(-19342813113834066795298815, 19342813113834066795298815); try test__negti2(19342813113834066795298815, -19342813113834066795298815); try test__negti2(-19342813113834066795298814, 19342813113834066795298814); try test__negti2(19342813113834066795298814, -19342813113834066795298814); try test__negti2(-19342813113834066795298812, 19342813113834066795298812); try test__negti2(19342813113834066795298812, -19342813113834066795298812); try test__negti2(-19342813113834066795298808, 19342813113834066795298808); try test__negti2(19342813113834066795298808, -19342813113834066795298808); try test__negti2(-9671406556917033397649407, 9671406556917033397649407); try test__negti2(9671406556917033397649407, -9671406556917033397649407); try test__negti2(-9671406556917033397649406, 9671406556917033397649406); try test__negti2(9671406556917033397649406, -9671406556917033397649406); try test__negti2(-9671406556917033397649404, 9671406556917033397649404); try test__negti2(9671406556917033397649404, -9671406556917033397649404); try test__negti2(-9671406556917033397649400, 9671406556917033397649400); try test__negti2(9671406556917033397649400, -9671406556917033397649400); try test__negti2(-4835703278458516698824703, 4835703278458516698824703); try test__negti2(4835703278458516698824703, -4835703278458516698824703); try test__negti2(-4835703278458516698824702, 4835703278458516698824702); try test__negti2(4835703278458516698824702, -4835703278458516698824702); try test__negti2(-4835703278458516698824700, 4835703278458516698824700); try test__negti2(4835703278458516698824700, -4835703278458516698824700); try test__negti2(-4835703278458516698824696, 4835703278458516698824696); try test__negti2(4835703278458516698824696, -4835703278458516698824696); try test__negti2(-2417851639229258349412351, 2417851639229258349412351); try test__negti2(2417851639229258349412351, -2417851639229258349412351); try test__negti2(-2417851639229258349412350, 2417851639229258349412350); try test__negti2(2417851639229258349412350, -2417851639229258349412350); try test__negti2(-2417851639229258349412348, 2417851639229258349412348); try test__negti2(2417851639229258349412348, -2417851639229258349412348); try test__negti2(-2417851639229258349412344, 2417851639229258349412344); try test__negti2(2417851639229258349412344, -2417851639229258349412344); try test__negti2(-1208925819614629174706175, 1208925819614629174706175); try test__negti2(1208925819614629174706175, -1208925819614629174706175); try test__negti2(-1208925819614629174706174, 1208925819614629174706174); try test__negti2(1208925819614629174706174, -1208925819614629174706174); try test__negti2(-1208925819614629174706172, 1208925819614629174706172); try test__negti2(1208925819614629174706172, -1208925819614629174706172); try test__negti2(-1208925819614629174706168, 1208925819614629174706168); try test__negti2(1208925819614629174706168, -1208925819614629174706168); try test__negti2(-604462909807314587353087, 604462909807314587353087); try test__negti2(604462909807314587353087, -604462909807314587353087); try test__negti2(-604462909807314587353086, 604462909807314587353086); try test__negti2(604462909807314587353086, -604462909807314587353086); try test__negti2(-604462909807314587353084, 604462909807314587353084); try test__negti2(604462909807314587353084, -604462909807314587353084); try test__negti2(-604462909807314587353080, 604462909807314587353080); try test__negti2(604462909807314587353080, -604462909807314587353080); try test__negti2(-302231454903657293676543, 302231454903657293676543); try test__negti2(302231454903657293676543, -302231454903657293676543); try test__negti2(-302231454903657293676542, 302231454903657293676542); try test__negti2(302231454903657293676542, -302231454903657293676542); try test__negti2(-302231454903657293676540, 302231454903657293676540); try test__negti2(302231454903657293676540, -302231454903657293676540); try test__negti2(-302231454903657293676536, 302231454903657293676536); try test__negti2(302231454903657293676536, -302231454903657293676536); try test__negti2(-151115727451828646838271, 151115727451828646838271); try test__negti2(151115727451828646838271, -151115727451828646838271); try test__negti2(-151115727451828646838270, 151115727451828646838270); try test__negti2(151115727451828646838270, -151115727451828646838270); try test__negti2(-151115727451828646838268, 151115727451828646838268); try test__negti2(151115727451828646838268, -151115727451828646838268); try test__negti2(-151115727451828646838264, 151115727451828646838264); try test__negti2(151115727451828646838264, -151115727451828646838264); try test__negti2(-75557863725914323419135, 75557863725914323419135); try test__negti2(75557863725914323419135, -75557863725914323419135); try test__negti2(-75557863725914323419134, 75557863725914323419134); try test__negti2(75557863725914323419134, -75557863725914323419134); try test__negti2(-75557863725914323419132, 75557863725914323419132); try test__negti2(75557863725914323419132, -75557863725914323419132); try test__negti2(-75557863725914323419128, 75557863725914323419128); try test__negti2(75557863725914323419128, -75557863725914323419128); try test__negti2(-37778931862957161709567, 37778931862957161709567); try test__negti2(37778931862957161709567, -37778931862957161709567); try test__negti2(-37778931862957161709566, 37778931862957161709566); try test__negti2(37778931862957161709566, -37778931862957161709566); try test__negti2(-37778931862957161709564, 37778931862957161709564); try test__negti2(37778931862957161709564, -37778931862957161709564); try test__negti2(-37778931862957161709560, 37778931862957161709560); try test__negti2(37778931862957161709560, -37778931862957161709560); try test__negti2(-18889465931478580854783, 18889465931478580854783); try test__negti2(18889465931478580854783, -18889465931478580854783); try test__negti2(-18889465931478580854782, 18889465931478580854782); try test__negti2(18889465931478580854782, -18889465931478580854782); try test__negti2(-18889465931478580854780, 18889465931478580854780); try test__negti2(18889465931478580854780, -18889465931478580854780); try test__negti2(-18889465931478580854776, 18889465931478580854776); try test__negti2(18889465931478580854776, -18889465931478580854776); try test__negti2(-9444732965739290427391, 9444732965739290427391); try test__negti2(9444732965739290427391, -9444732965739290427391); try test__negti2(-9444732965739290427390, 9444732965739290427390); try test__negti2(9444732965739290427390, -9444732965739290427390); try test__negti2(-9444732965739290427388, 9444732965739290427388); try test__negti2(9444732965739290427388, -9444732965739290427388); try test__negti2(-9444732965739290427384, 9444732965739290427384); try test__negti2(9444732965739290427384, -9444732965739290427384); try test__negti2(-4722366482869645213695, 4722366482869645213695); try test__negti2(4722366482869645213695, -4722366482869645213695); try test__negti2(-4722366482869645213694, 4722366482869645213694); try test__negti2(4722366482869645213694, -4722366482869645213694); try test__negti2(-4722366482869645213692, 4722366482869645213692); try test__negti2(4722366482869645213692, -4722366482869645213692); try test__negti2(-4722366482869645213688, 4722366482869645213688); try test__negti2(4722366482869645213688, -4722366482869645213688); try test__negti2(-2361183241434822606847, 2361183241434822606847); try test__negti2(2361183241434822606847, -2361183241434822606847); try test__negti2(-2361183241434822606846, 2361183241434822606846); try test__negti2(2361183241434822606846, -2361183241434822606846); try test__negti2(-2361183241434822606844, 2361183241434822606844); try test__negti2(2361183241434822606844, -2361183241434822606844); try test__negti2(-2361183241434822606840, 2361183241434822606840); try test__negti2(2361183241434822606840, -2361183241434822606840); try test__negti2(-1180591620717411303423, 1180591620717411303423); try test__negti2(1180591620717411303423, -1180591620717411303423); try test__negti2(-1180591620717411303422, 1180591620717411303422); try test__negti2(1180591620717411303422, -1180591620717411303422); try test__negti2(-1180591620717411303420, 1180591620717411303420); try test__negti2(1180591620717411303420, -1180591620717411303420); try test__negti2(-1180591620717411303416, 1180591620717411303416); try test__negti2(1180591620717411303416, -1180591620717411303416); try test__negti2(-590295810358705651711, 590295810358705651711); try test__negti2(590295810358705651711, -590295810358705651711); try test__negti2(-590295810358705651710, 590295810358705651710); try test__negti2(590295810358705651710, -590295810358705651710); try test__negti2(-590295810358705651708, 590295810358705651708); try test__negti2(590295810358705651708, -590295810358705651708); try test__negti2(-590295810358705651704, 590295810358705651704); try test__negti2(590295810358705651704, -590295810358705651704); try test__negti2(-295147905179352825855, 295147905179352825855); try test__negti2(295147905179352825855, -295147905179352825855); try test__negti2(-295147905179352825854, 295147905179352825854); try test__negti2(295147905179352825854, -295147905179352825854); try test__negti2(-295147905179352825852, 295147905179352825852); try test__negti2(295147905179352825852, -295147905179352825852); try test__negti2(-295147905179352825848, 295147905179352825848); try test__negti2(295147905179352825848, -295147905179352825848); try test__negti2(-147573952589676412927, 147573952589676412927); try test__negti2(147573952589676412927, -147573952589676412927); try test__negti2(-147573952589676412926, 147573952589676412926); try test__negti2(147573952589676412926, -147573952589676412926); try test__negti2(-147573952589676412924, 147573952589676412924); try test__negti2(147573952589676412924, -147573952589676412924); try test__negti2(-147573952589676412920, 147573952589676412920); try test__negti2(147573952589676412920, -147573952589676412920); try test__negti2(-73786976294838206463, 73786976294838206463); try test__negti2(73786976294838206463, -73786976294838206463); try test__negti2(-73786976294838206462, 73786976294838206462); try test__negti2(73786976294838206462, -73786976294838206462); try test__negti2(-73786976294838206460, 73786976294838206460); try test__negti2(73786976294838206460, -73786976294838206460); try test__negti2(-73786976294838206456, 73786976294838206456); try test__negti2(73786976294838206456, -73786976294838206456); try test__negti2(-36893488147419103231, 36893488147419103231); try test__negti2(36893488147419103231, -36893488147419103231); try test__negti2(-36893488147419103230, 36893488147419103230); try test__negti2(36893488147419103230, -36893488147419103230); try test__negti2(-36893488147419103228, 36893488147419103228); try test__negti2(36893488147419103228, -36893488147419103228); try test__negti2(-36893488147419103224, 36893488147419103224); try test__negti2(36893488147419103224, -36893488147419103224); try test__negti2(-18446744073709551615, 18446744073709551615); try test__negti2(18446744073709551615, -18446744073709551615); try test__negti2(-18446744073709551614, 18446744073709551614); try test__negti2(18446744073709551614, -18446744073709551614); try test__negti2(-18446744073709551612, 18446744073709551612); try test__negti2(18446744073709551612, -18446744073709551612); try test__negti2(-18446744073709551608, 18446744073709551608); try test__negti2(18446744073709551608, -18446744073709551608); try test__negti2(-9223372036854775807, 9223372036854775807); try test__negti2(9223372036854775807, -9223372036854775807); try test__negti2(-9223372036854775806, 9223372036854775806); try test__negti2(9223372036854775806, -9223372036854775806); try test__negti2(-9223372036854775804, 9223372036854775804); try test__negti2(9223372036854775804, -9223372036854775804); try test__negti2(-9223372036854775800, 9223372036854775800); try test__negti2(9223372036854775800, -9223372036854775800); try test__negti2(-4611686018427387903, 4611686018427387903); try test__negti2(4611686018427387903, -4611686018427387903); try test__negti2(-4611686018427387902, 4611686018427387902); try test__negti2(4611686018427387902, -4611686018427387902); try test__negti2(-4611686018427387900, 4611686018427387900); try test__negti2(4611686018427387900, -4611686018427387900); try test__negti2(-4611686018427387896, 4611686018427387896); try test__negti2(4611686018427387896, -4611686018427387896); try test__negti2(-2305843009213693951, 2305843009213693951); try test__negti2(2305843009213693951, -2305843009213693951); try test__negti2(-2305843009213693950, 2305843009213693950); try test__negti2(2305843009213693950, -2305843009213693950); try test__negti2(-2305843009213693948, 2305843009213693948); try test__negti2(2305843009213693948, -2305843009213693948); try test__negti2(-2305843009213693944, 2305843009213693944); try test__negti2(2305843009213693944, -2305843009213693944); try test__negti2(-1152921504606846975, 1152921504606846975); try test__negti2(1152921504606846975, -1152921504606846975); try test__negti2(-1152921504606846974, 1152921504606846974); try test__negti2(1152921504606846974, -1152921504606846974); try test__negti2(-1152921504606846972, 1152921504606846972); try test__negti2(1152921504606846972, -1152921504606846972); try test__negti2(-1152921504606846968, 1152921504606846968); try test__negti2(1152921504606846968, -1152921504606846968); try test__negti2(-576460752303423487, 576460752303423487); try test__negti2(576460752303423487, -576460752303423487); try test__negti2(-576460752303423486, 576460752303423486); try test__negti2(576460752303423486, -576460752303423486); try test__negti2(-576460752303423484, 576460752303423484); try test__negti2(576460752303423484, -576460752303423484); try test__negti2(-576460752303423480, 576460752303423480); try test__negti2(576460752303423480, -576460752303423480); try test__negti2(-288230376151711743, 288230376151711743); try test__negti2(288230376151711743, -288230376151711743); try test__negti2(-288230376151711742, 288230376151711742); try test__negti2(288230376151711742, -288230376151711742); try test__negti2(-288230376151711740, 288230376151711740); try test__negti2(288230376151711740, -288230376151711740); try test__negti2(-288230376151711736, 288230376151711736); try test__negti2(288230376151711736, -288230376151711736); try test__negti2(-144115188075855871, 144115188075855871); try test__negti2(144115188075855871, -144115188075855871); try test__negti2(-144115188075855870, 144115188075855870); try test__negti2(144115188075855870, -144115188075855870); try test__negti2(-144115188075855868, 144115188075855868); try test__negti2(144115188075855868, -144115188075855868); try test__negti2(-144115188075855864, 144115188075855864); try test__negti2(144115188075855864, -144115188075855864); try test__negti2(-72057594037927935, 72057594037927935); try test__negti2(72057594037927935, -72057594037927935); try test__negti2(-72057594037927934, 72057594037927934); try test__negti2(72057594037927934, -72057594037927934); try test__negti2(-72057594037927932, 72057594037927932); try test__negti2(72057594037927932, -72057594037927932); try test__negti2(-72057594037927928, 72057594037927928); try test__negti2(72057594037927928, -72057594037927928); try test__negti2(-36028797018963967, 36028797018963967); try test__negti2(36028797018963967, -36028797018963967); try test__negti2(-36028797018963966, 36028797018963966); try test__negti2(36028797018963966, -36028797018963966); try test__negti2(-36028797018963964, 36028797018963964); try test__negti2(36028797018963964, -36028797018963964); try test__negti2(-36028797018963960, 36028797018963960); try test__negti2(36028797018963960, -36028797018963960); try test__negti2(-18014398509481983, 18014398509481983); try test__negti2(18014398509481983, -18014398509481983); try test__negti2(-18014398509481982, 18014398509481982); try test__negti2(18014398509481982, -18014398509481982); try test__negti2(-18014398509481980, 18014398509481980); try test__negti2(18014398509481980, -18014398509481980); try test__negti2(-18014398509481976, 18014398509481976); try test__negti2(18014398509481976, -18014398509481976); try test__negti2(-9007199254740991, 9007199254740991); try test__negti2(9007199254740991, -9007199254740991); try test__negti2(-9007199254740990, 9007199254740990); try test__negti2(9007199254740990, -9007199254740990); try test__negti2(-9007199254740988, 9007199254740988); try test__negti2(9007199254740988, -9007199254740988); try test__negti2(-9007199254740984, 9007199254740984); try test__negti2(9007199254740984, -9007199254740984); try test__negti2(-4503599627370495, 4503599627370495); try test__negti2(4503599627370495, -4503599627370495); try test__negti2(-4503599627370494, 4503599627370494); try test__negti2(4503599627370494, -4503599627370494); try test__negti2(-4503599627370492, 4503599627370492); try test__negti2(4503599627370492, -4503599627370492); try test__negti2(-4503599627370488, 4503599627370488); try test__negti2(4503599627370488, -4503599627370488); try test__negti2(-2251799813685247, 2251799813685247); try test__negti2(2251799813685247, -2251799813685247); try test__negti2(-2251799813685246, 2251799813685246); try test__negti2(2251799813685246, -2251799813685246); try test__negti2(-2251799813685244, 2251799813685244); try test__negti2(2251799813685244, -2251799813685244); try test__negti2(-2251799813685240, 2251799813685240); try test__negti2(2251799813685240, -2251799813685240); try test__negti2(-1125899906842623, 1125899906842623); try test__negti2(1125899906842623, -1125899906842623); try test__negti2(-1125899906842622, 1125899906842622); try test__negti2(1125899906842622, -1125899906842622); try test__negti2(-1125899906842620, 1125899906842620); try test__negti2(1125899906842620, -1125899906842620); try test__negti2(-1125899906842616, 1125899906842616); try test__negti2(1125899906842616, -1125899906842616); try test__negti2(-562949953421311, 562949953421311); try test__negti2(562949953421311, -562949953421311); try test__negti2(-562949953421310, 562949953421310); try test__negti2(562949953421310, -562949953421310); try test__negti2(-562949953421308, 562949953421308); try test__negti2(562949953421308, -562949953421308); try test__negti2(-562949953421304, 562949953421304); try test__negti2(562949953421304, -562949953421304); try test__negti2(-281474976710655, 281474976710655); try test__negti2(281474976710655, -281474976710655); try test__negti2(-281474976710654, 281474976710654); try test__negti2(281474976710654, -281474976710654); try test__negti2(-281474976710652, 281474976710652); try test__negti2(281474976710652, -281474976710652); try test__negti2(-281474976710648, 281474976710648); try test__negti2(281474976710648, -281474976710648); try test__negti2(-140737488355327, 140737488355327); try test__negti2(140737488355327, -140737488355327); try test__negti2(-140737488355326, 140737488355326); try test__negti2(140737488355326, -140737488355326); try test__negti2(-140737488355324, 140737488355324); try test__negti2(140737488355324, -140737488355324); try test__negti2(-140737488355320, 140737488355320); try test__negti2(140737488355320, -140737488355320); try test__negti2(-70368744177663, 70368744177663); try test__negti2(70368744177663, -70368744177663); try test__negti2(-70368744177662, 70368744177662); try test__negti2(70368744177662, -70368744177662); try test__negti2(-70368744177660, 70368744177660); try test__negti2(70368744177660, -70368744177660); try test__negti2(-70368744177656, 70368744177656); try test__negti2(70368744177656, -70368744177656); try test__negti2(-35184372088831, 35184372088831); try test__negti2(35184372088831, -35184372088831); try test__negti2(-35184372088830, 35184372088830); try test__negti2(35184372088830, -35184372088830); try test__negti2(-35184372088828, 35184372088828); try test__negti2(35184372088828, -35184372088828); try test__negti2(-35184372088824, 35184372088824); try test__negti2(35184372088824, -35184372088824); try test__negti2(-17592186044415, 17592186044415); try test__negti2(17592186044415, -17592186044415); try test__negti2(-17592186044414, 17592186044414); try test__negti2(17592186044414, -17592186044414); try test__negti2(-17592186044412, 17592186044412); try test__negti2(17592186044412, -17592186044412); try test__negti2(-17592186044408, 17592186044408); try test__negti2(17592186044408, -17592186044408); try test__negti2(-8796093022207, 8796093022207); try test__negti2(8796093022207, -8796093022207); try test__negti2(-8796093022206, 8796093022206); try test__negti2(8796093022206, -8796093022206); try test__negti2(-8796093022204, 8796093022204); try test__negti2(8796093022204, -8796093022204); try test__negti2(-8796093022200, 8796093022200); try test__negti2(8796093022200, -8796093022200); try test__negti2(-4398046511103, 4398046511103); try test__negti2(4398046511103, -4398046511103); try test__negti2(-4398046511102, 4398046511102); try test__negti2(4398046511102, -4398046511102); try test__negti2(-4398046511100, 4398046511100); try test__negti2(4398046511100, -4398046511100); try test__negti2(-4398046511096, 4398046511096); try test__negti2(4398046511096, -4398046511096); try test__negti2(-2199023255551, 2199023255551); try test__negti2(2199023255551, -2199023255551); try test__negti2(-2199023255550, 2199023255550); try test__negti2(2199023255550, -2199023255550); try test__negti2(-2199023255548, 2199023255548); try test__negti2(2199023255548, -2199023255548); try test__negti2(-2199023255544, 2199023255544); try test__negti2(2199023255544, -2199023255544); try test__negti2(-1099511627775, 1099511627775); try test__negti2(1099511627775, -1099511627775); try test__negti2(-1099511627774, 1099511627774); try test__negti2(1099511627774, -1099511627774); try test__negti2(-1099511627772, 1099511627772); try test__negti2(1099511627772, -1099511627772); try test__negti2(-1099511627768, 1099511627768); try test__negti2(1099511627768, -1099511627768); try test__negti2(-549755813887, 549755813887); try test__negti2(549755813887, -549755813887); try test__negti2(-549755813886, 549755813886); try test__negti2(549755813886, -549755813886); try test__negti2(-549755813884, 549755813884); try test__negti2(549755813884, -549755813884); try test__negti2(-549755813880, 549755813880); try test__negti2(549755813880, -549755813880); try test__negti2(-274877906943, 274877906943); try test__negti2(274877906943, -274877906943); try test__negti2(-274877906942, 274877906942); try test__negti2(274877906942, -274877906942); try test__negti2(-274877906940, 274877906940); try test__negti2(274877906940, -274877906940); try test__negti2(-274877906936, 274877906936); try test__negti2(274877906936, -274877906936); try test__negti2(-137438953471, 137438953471); try test__negti2(137438953471, -137438953471); try test__negti2(-137438953470, 137438953470); try test__negti2(137438953470, -137438953470); try test__negti2(-137438953468, 137438953468); try test__negti2(137438953468, -137438953468); try test__negti2(-137438953464, 137438953464); try test__negti2(137438953464, -137438953464); try test__negti2(-68719476735, 68719476735); try test__negti2(68719476735, -68719476735); try test__negti2(-68719476734, 68719476734); try test__negti2(68719476734, -68719476734); try test__negti2(-68719476732, 68719476732); try test__negti2(68719476732, -68719476732); try test__negti2(-68719476728, 68719476728); try test__negti2(68719476728, -68719476728); try test__negti2(-34359738367, 34359738367); try test__negti2(34359738367, -34359738367); try test__negti2(-34359738366, 34359738366); try test__negti2(34359738366, -34359738366); try test__negti2(-34359738364, 34359738364); try test__negti2(34359738364, -34359738364); try test__negti2(-34359738360, 34359738360); try test__negti2(34359738360, -34359738360); try test__negti2(-17179869183, 17179869183); try test__negti2(17179869183, -17179869183); try test__negti2(-17179869182, 17179869182); try test__negti2(17179869182, -17179869182); try test__negti2(-17179869180, 17179869180); try test__negti2(17179869180, -17179869180); try test__negti2(-17179869176, 17179869176); try test__negti2(17179869176, -17179869176); try test__negti2(-8589934591, 8589934591); try test__negti2(8589934591, -8589934591); try test__negti2(-8589934590, 8589934590); try test__negti2(8589934590, -8589934590); try test__negti2(-8589934588, 8589934588); try test__negti2(8589934588, -8589934588); try test__negti2(-8589934584, 8589934584); try test__negti2(8589934584, -8589934584); try test__negti2(-4294967295, 4294967295); try test__negti2(4294967295, -4294967295); try test__negti2(-4294967294, 4294967294); try test__negti2(4294967294, -4294967294); try test__negti2(-4294967292, 4294967292); try test__negti2(4294967292, -4294967292); try test__negti2(-4294967288, 4294967288); try test__negti2(4294967288, -4294967288); try test__negti2(-2147483647, 2147483647); try test__negti2(2147483647, -2147483647); try test__negti2(-2147483646, 2147483646); try test__negti2(2147483646, -2147483646); try test__negti2(-2147483644, 2147483644); try test__negti2(2147483644, -2147483644); try test__negti2(-2147483640, 2147483640); try test__negti2(2147483640, -2147483640); try test__negti2(-1073741823, 1073741823); try test__negti2(1073741823, -1073741823); try test__negti2(-1073741822, 1073741822); try test__negti2(1073741822, -1073741822); try test__negti2(-1073741820, 1073741820); try test__negti2(1073741820, -1073741820); try test__negti2(-1073741816, 1073741816); try test__negti2(1073741816, -1073741816); try test__negti2(-536870911, 536870911); try test__negti2(536870911, -536870911); try test__negti2(-536870910, 536870910); try test__negti2(536870910, -536870910); try test__negti2(-536870908, 536870908); try test__negti2(536870908, -536870908); try test__negti2(-536870904, 536870904); try test__negti2(536870904, -536870904); try test__negti2(-268435455, 268435455); try test__negti2(268435455, -268435455); try test__negti2(-268435454, 268435454); try test__negti2(268435454, -268435454); try test__negti2(-268435452, 268435452); try test__negti2(268435452, -268435452); try test__negti2(-268435448, 268435448); try test__negti2(268435448, -268435448); try test__negti2(-134217727, 134217727); try test__negti2(134217727, -134217727); try test__negti2(-134217726, 134217726); try test__negti2(134217726, -134217726); try test__negti2(-134217724, 134217724); try test__negti2(134217724, -134217724); try test__negti2(-134217720, 134217720); try test__negti2(134217720, -134217720); try test__negti2(-67108863, 67108863); try test__negti2(67108863, -67108863); try test__negti2(-67108862, 67108862); try test__negti2(67108862, -67108862); try test__negti2(-67108860, 67108860); try test__negti2(67108860, -67108860); try test__negti2(-67108856, 67108856); try test__negti2(67108856, -67108856); try test__negti2(-33554431, 33554431); try test__negti2(33554431, -33554431); try test__negti2(-33554430, 33554430); try test__negti2(33554430, -33554430); try test__negti2(-33554428, 33554428); try test__negti2(33554428, -33554428); try test__negti2(-33554424, 33554424); try test__negti2(33554424, -33554424); try test__negti2(-16777215, 16777215); try test__negti2(16777215, -16777215); try test__negti2(-16777214, 16777214); try test__negti2(16777214, -16777214); try test__negti2(-16777212, 16777212); try test__negti2(16777212, -16777212); try test__negti2(-16777208, 16777208); try test__negti2(16777208, -16777208); try test__negti2(-8388607, 8388607); try test__negti2(8388607, -8388607); try test__negti2(-8388606, 8388606); try test__negti2(8388606, -8388606); try test__negti2(-8388604, 8388604); try test__negti2(8388604, -8388604); try test__negti2(-8388600, 8388600); try test__negti2(8388600, -8388600); try test__negti2(-4194303, 4194303); try test__negti2(4194303, -4194303); try test__negti2(-4194302, 4194302); try test__negti2(4194302, -4194302); try test__negti2(-4194300, 4194300); try test__negti2(4194300, -4194300); try test__negti2(-4194296, 4194296); try test__negti2(4194296, -4194296); try test__negti2(-2097151, 2097151); try test__negti2(2097151, -2097151); try test__negti2(-2097150, 2097150); try test__negti2(2097150, -2097150); try test__negti2(-2097148, 2097148); try test__negti2(2097148, -2097148); try test__negti2(-2097144, 2097144); try test__negti2(2097144, -2097144); try test__negti2(-1048575, 1048575); try test__negti2(1048575, -1048575); try test__negti2(-1048574, 1048574); try test__negti2(1048574, -1048574); try test__negti2(-1048572, 1048572); try test__negti2(1048572, -1048572); try test__negti2(-1048568, 1048568); try test__negti2(1048568, -1048568); try test__negti2(-524287, 524287); try test__negti2(524287, -524287); try test__negti2(-524286, 524286); try test__negti2(524286, -524286); try test__negti2(-524284, 524284); try test__negti2(524284, -524284); try test__negti2(-524280, 524280); try test__negti2(524280, -524280); try test__negti2(-262143, 262143); try test__negti2(262143, -262143); try test__negti2(-262142, 262142); try test__negti2(262142, -262142); try test__negti2(-262140, 262140); try test__negti2(262140, -262140); try test__negti2(-262136, 262136); try test__negti2(262136, -262136); try test__negti2(-131071, 131071); try test__negti2(131071, -131071); try test__negti2(-131070, 131070); try test__negti2(131070, -131070); try test__negti2(-131068, 131068); try test__negti2(131068, -131068); try test__negti2(-131064, 131064); try test__negti2(131064, -131064); try test__negti2(-65535, 65535); try test__negti2(65535, -65535); try test__negti2(-65534, 65534); try test__negti2(65534, -65534); try test__negti2(-65532, 65532); try test__negti2(65532, -65532); try test__negti2(-65528, 65528); try test__negti2(65528, -65528); try test__negti2(-32767, 32767); try test__negti2(32767, -32767); try test__negti2(-32766, 32766); try test__negti2(32766, -32766); try test__negti2(-32764, 32764); try test__negti2(32764, -32764); try test__negti2(-32760, 32760); try test__negti2(32760, -32760); try test__negti2(-16383, 16383); try test__negti2(16383, -16383); try test__negti2(-16382, 16382); try test__negti2(16382, -16382); try test__negti2(-16380, 16380); try test__negti2(16380, -16380); try test__negti2(-16376, 16376); try test__negti2(16376, -16376); try test__negti2(-8191, 8191); try test__negti2(8191, -8191); try test__negti2(-8190, 8190); try test__negti2(8190, -8190); try test__negti2(-8188, 8188); try test__negti2(8188, -8188); try test__negti2(-8184, 8184); try test__negti2(8184, -8184); try test__negti2(-4095, 4095); try test__negti2(4095, -4095); try test__negti2(-4094, 4094); try test__negti2(4094, -4094); try test__negti2(-4092, 4092); try test__negti2(4092, -4092); try test__negti2(-4088, 4088); try test__negti2(4088, -4088); try test__negti2(-2047, 2047); try test__negti2(2047, -2047); try test__negti2(-2046, 2046); try test__negti2(2046, -2046); try test__negti2(-2044, 2044); try test__negti2(2044, -2044); try test__negti2(-2040, 2040); try test__negti2(2040, -2040); try test__negti2(-1023, 1023); try test__negti2(1023, -1023); try test__negti2(-1022, 1022); try test__negti2(1022, -1022); try test__negti2(-1020, 1020); try test__negti2(1020, -1020); try test__negti2(-1016, 1016); try test__negti2(1016, -1016); try test__negti2(-511, 511); try test__negti2(511, -511); try test__negti2(-510, 510); try test__negti2(510, -510); try test__negti2(-508, 508); try test__negti2(508, -508); try test__negti2(-504, 504); try test__negti2(504, -504); try test__negti2(-255, 255); try test__negti2(255, -255); try test__negti2(-254, 254); try test__negti2(254, -254); try test__negti2(-252, 252); try test__negti2(252, -252); try test__negti2(-248, 248); try test__negti2(248, -248); try test__negti2(-127, 127); try test__negti2(127, -127); try test__negti2(-126, 126); try test__negti2(126, -126); try test__negti2(-124, 124); try test__negti2(124, -124); try test__negti2(-120, 120); try test__negti2(120, -120); try test__negti2(-63, 63); try test__negti2(63, -63); try test__negti2(-62, 62); try test__negti2(62, -62); try test__negti2(-60, 60); try test__negti2(60, -60); try test__negti2(-56, 56); try test__negti2(56, -56); try test__negti2(-31, 31); try test__negti2(31, -31); try test__negti2(-30, 30); try test__negti2(30, -30); try test__negti2(-28, 28); try test__negti2(28, -28); try test__negti2(-24, 24); try test__negti2(24, -24); try test__negti2(-15, 15); try test__negti2(15, -15); try test__negti2(-14, 14); try test__negti2(14, -14); try test__negti2(-12, 12); try test__negti2(12, -12); try test__negti2(-8, 8); try test__negti2(8, -8); }
lib/std/special/compiler_rt/negti2_test.zig
test "comptime slice-sentinel in bounds (unterminated)" { // array comptime { var target = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; const slice = target[0..3 :'d']; _ = slice; } // ptr_array comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target = &buf; const slice = target[0..3 :'d']; _ = slice; } // vector_ConstPtrSpecialBaseArray comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = &buf; const slice = target[0..3 :'d']; _ = slice; } // vector_ConstPtrSpecialRef comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..3 :'d']; _ = slice; } // cvector_ConstPtrSpecialBaseArray comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = &buf; const slice = target[0..3 :'d']; _ = slice; } // cvector_ConstPtrSpecialRef comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..3 :'d']; _ = slice; } // slice comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: []u8 = &buf; const slice = target[0..3 :'d']; _ = slice; } } test "comptime slice-sentinel in bounds (end,unterminated)" { // array comptime { var target = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; const slice = target[0..13 :0xff]; _ = slice; } // ptr_array comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target = &buf; const slice = target[0..13 :0xff]; _ = slice; } // vector_ConstPtrSpecialBaseArray comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*]u8 = &buf; const slice = target[0..13 :0xff]; _ = slice; } // vector_ConstPtrSpecialRef comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..13 :0xff]; _ = slice; } // cvector_ConstPtrSpecialBaseArray comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*c]u8 = &buf; const slice = target[0..13 :0xff]; _ = slice; } // cvector_ConstPtrSpecialRef comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..13 :0xff]; _ = slice; } // slice comptime { var buf = [_]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{0xff} ** 10; var target: []u8 = &buf; const slice = target[0..13 :0xff]; _ = slice; } } test "comptime slice-sentinel in bounds (terminated)" { // array comptime { var target = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; const slice = target[0..3 :'d']; _ = slice; } // ptr_array comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target = &buf; const slice = target[0..3 :'d']; _ = slice; } // vector_ConstPtrSpecialBaseArray comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = &buf; const slice = target[0..3 :'d']; _ = slice; } // vector_ConstPtrSpecialRef comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..3 :'d']; _ = slice; } // cvector_ConstPtrSpecialBaseArray comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = &buf; const slice = target[0..3 :'d']; _ = slice; } // cvector_ConstPtrSpecialRef comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..3 :'d']; _ = slice; } // slice comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: []u8 = &buf; const slice = target[0..3 :'d']; _ = slice; } } test "comptime slice-sentinel in bounds (on target sentinel)" { // array comptime { var target = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; const slice = target[0..14 :0]; _ = slice; } // ptr_array comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target = &buf; const slice = target[0..14 :0]; _ = slice; } // vector_ConstPtrSpecialBaseArray comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = &buf; const slice = target[0..14 :0]; _ = slice; } // vector_ConstPtrSpecialRef comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*]u8 = @ptrCast([*]u8, &buf); const slice = target[0..14 :0]; _ = slice; } // cvector_ConstPtrSpecialBaseArray comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = &buf; const slice = target[0..14 :0]; _ = slice; } // cvector_ConstPtrSpecialRef comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: [*c]u8 = @ptrCast([*c]u8, &buf); const slice = target[0..14 :0]; _ = slice; } // slice comptime { var buf = [_:0]u8{ 'a', 'b', 'c', 'd' } ++ [_]u8{undefined} ** 10; var target: []u8 = &buf; const slice = target[0..14 :0]; _ = slice; } }
test/behavior/slice_sentinel_comptime.zig
pub const mach_header = extern struct { magic: u32, cputype: cpu_type_t, cpusubtype: cpu_subtype_t, filetype: u32, ncmds: u32, sizeofcmds: u32, flags: u32, }; pub const mach_header_64 = extern struct { magic: u32, cputype: cpu_type_t, cpusubtype: cpu_subtype_t, filetype: u32, ncmds: u32, sizeofcmds: u32, flags: u32, reserved: u32, }; pub const load_command = extern struct { cmd: u32, cmdsize: u32, }; pub const uuid_command = extern struct { /// LC_UUID cmd: u32, /// sizeof(struct uuid_command) cmdsize: u32, /// the 128-bit uuid uuid: [16]u8, }; /// The entry_point_command is a replacement for thread_command. /// It is used for main executables to specify the location (file offset) /// of main(). If -stack_size was used at link time, the stacksize /// field will contain the stack size needed for the main thread. pub const entry_point_command = struct { /// LC_MAIN only used in MH_EXECUTE filetypes cmd: u32, /// sizeof(struct entry_point_command) cmdsize: u32, /// file (__TEXT) offset of main() entryoff: u64, /// if not zero, initial stack size stacksize: u64, }; /// The symtab_command contains the offsets and sizes of the link-edit 4.3BSD /// "stab" style symbol table information as described in the header files /// <nlist.h> and <stab.h>. pub const symtab_command = extern struct { /// LC_SYMTAB cmd: u32, /// sizeof(struct symtab_command) cmdsize: u32, /// symbol table offset symoff: u32, /// number of symbol table entries nsyms: u32, /// string table offset stroff: u32, /// string table size in bytes strsize: u32, }; /// The linkedit_data_command contains the offsets and sizes of a blob /// of data in the __LINKEDIT segment. const linkedit_data_command = extern struct { /// LC_CODE_SIGNATURE, LC_SEGMENT_SPLIT_INFO, LC_FUNCTION_STARTS, LC_DATA_IN_CODE, LC_DYLIB_CODE_SIGN_DRS or LC_LINKER_OPTIMIZATION_HINT. cmd: u32, /// sizeof(struct linkedit_data_command) cmdsize: u32, /// file offset of data in __LINKEDIT segment dataoff: u32, /// file size of data in __LINKEDIT segment datasize: u32, }; /// The segment load command indicates that a part of this file is to be /// mapped into the task's address space. The size of this segment in memory, /// vmsize, maybe equal to or larger than the amount to map from this file, /// filesize. The file is mapped starting at fileoff to the beginning of /// the segment in memory, vmaddr. The rest of the memory of the segment, /// if any, is allocated zero fill on demand. The segment's maximum virtual /// memory protection and initial virtual memory protection are specified /// by the maxprot and initprot fields. If the segment has sections then the /// section structures directly follow the segment command and their size is /// reflected in cmdsize. pub const segment_command = extern struct { /// LC_SEGMENT cmd: u32, /// includes sizeof section structs cmdsize: u32, /// segment name segname: [16]u8, /// memory address of this segment vmaddr: u32, /// memory size of this segment vmsize: u32, /// file offset of this segment fileoff: u32, /// amount to map from the file filesize: u32, /// maximum VM protection maxprot: vm_prot_t, /// initial VM protection initprot: vm_prot_t, /// number of sections in segment nsects: u32, flags: u32, }; /// The 64-bit segment load command indicates that a part of this file is to be /// mapped into a 64-bit task's address space. If the 64-bit segment has /// sections then section_64 structures directly follow the 64-bit segment /// command and their size is reflected in cmdsize. pub const segment_command_64 = extern struct { /// LC_SEGMENT_64 cmd: u32, /// includes sizeof section_64 structs cmdsize: u32, /// segment name segname: [16]u8, /// memory address of this segment vmaddr: u64, /// memory size of this segment vmsize: u64, /// file offset of this segment fileoff: u64, /// amount to map from the file filesize: u64, /// maximum VM protection maxprot: vm_prot_t, /// initial VM protection initprot: vm_prot_t, /// number of sections in segment nsects: u32, flags: u32, }; /// A segment is made up of zero or more sections. Non-MH_OBJECT files have /// all of their segments with the proper sections in each, and padded to the /// specified segment alignment when produced by the link editor. The first /// segment of a MH_EXECUTE and MH_FVMLIB format file contains the mach_header /// and load commands of the object file before its first section. The zero /// fill sections are always last in their segment (in all formats). This /// allows the zeroed segment padding to be mapped into memory where zero fill /// sections might be. The gigabyte zero fill sections, those with the section /// type S_GB_ZEROFILL, can only be in a segment with sections of this type. /// These segments are then placed after all other segments. /// /// The MH_OBJECT format has all of its sections in one segment for /// compactness. There is no padding to a specified segment boundary and the /// mach_header and load commands are not part of the segment. /// /// Sections with the same section name, sectname, going into the same segment, /// segname, are combined by the link editor. The resulting section is aligned /// to the maximum alignment of the combined sections and is the new section's /// alignment. The combined sections are aligned to their original alignment in /// the combined section. Any padded bytes to get the specified alignment are /// zeroed. /// /// The format of the relocation entries referenced by the reloff and nreloc /// fields of the section structure for mach object files is described in the /// header file <reloc.h>. pub const @"section" = extern struct { /// name of this section sectname: [16]u8, /// segment this section goes in segname: [16]u8, /// memory address of this section addr: u32, /// size in bytes of this section size: u32, /// file offset of this section offset: u32, /// section alignment (power of 2) @"align": u32, /// file offset of relocation entries reloff: u32, /// number of relocation entries nreloc: u32, /// flags (section type and attributes flags: u32, /// reserved (for offset or index) reserved1: u32, /// reserved (for count or sizeof) reserved2: u32, }; pub const section_64 = extern struct { /// name of this section sectname: [16]u8, /// segment this section goes in segname: [16]u8, /// memory address of this section addr: u64, /// size in bytes of this section size: u64, /// file offset of this section offset: u32, /// section alignment (power of 2) @"align": u32, /// file offset of relocation entries reloff: u32, /// number of relocation entries nreloc: u32, /// flags (section type and attributes flags: u32, /// reserved (for offset or index) reserved1: u32, /// reserved (for count or sizeof) reserved2: u32, /// reserved reserved3: u32, }; pub const nlist = extern struct { n_strx: u32, n_type: u8, n_sect: u8, n_desc: i16, n_value: u32, }; pub const nlist_64 = extern struct { n_strx: u32, n_type: u8, n_sect: u8, n_desc: u16, n_value: u64, }; /// After MacOS X 10.1 when a new load command is added that is required to be /// understood by the dynamic linker for the image to execute properly the /// LC_REQ_DYLD bit will be or'ed into the load command constant. If the dynamic /// linker sees such a load command it it does not understand will issue a /// "unknown load command required for execution" error and refuse to use the /// image. Other load commands without this bit that are not understood will /// simply be ignored. pub const LC_REQ_DYLD = 0x80000000; /// segment of this file to be mapped pub const LC_SEGMENT = 0x1; /// link-edit stab symbol table info pub const LC_SYMTAB = 0x2; /// link-edit gdb symbol table info (obsolete) pub const LC_SYMSEG = 0x3; /// thread pub const LC_THREAD = 0x4; /// unix thread (includes a stack) pub const LC_UNIXTHREAD = 0x5; /// load a specified fixed VM shared library pub const LC_LOADFVMLIB = 0x6; /// fixed VM shared library identification pub const LC_IDFVMLIB = 0x7; /// object identification info (obsolete) pub const LC_IDENT = 0x8; /// fixed VM file inclusion (internal use) pub const LC_FVMFILE = 0x9; /// prepage command (internal use) pub const LC_PREPAGE = 0xa; /// dynamic link-edit symbol table info pub const LC_DYSYMTAB = 0xb; /// load a dynamically linked shared library pub const LC_LOAD_DYLIB = 0xc; /// dynamically linked shared lib ident pub const LC_ID_DYLIB = 0xd; /// load a dynamic linker pub const LC_LOAD_DYLINKER = 0xe; /// dynamic linker identification pub const LC_ID_DYLINKER = 0xf; /// modules prebound for a dynamically pub const LC_PREBOUND_DYLIB = 0x10; /// image routines pub const LC_ROUTINES = 0x11; /// sub framework pub const LC_SUB_FRAMEWORK = 0x12; /// sub umbrella pub const LC_SUB_UMBRELLA = 0x13; /// sub client pub const LC_SUB_CLIENT = 0x14; /// sub library pub const LC_SUB_LIBRARY = 0x15; /// two-level namespace lookup hints pub const LC_TWOLEVEL_HINTS = 0x16; /// prebind checksum pub const LC_PREBIND_CKSUM = 0x17; /// load a dynamically linked shared library that is allowed to be missing /// (all symbols are weak imported). pub const LC_LOAD_WEAK_DYLIB = (0x18 | LC_REQ_DYLD); /// 64-bit segment of this file to be mapped pub const LC_SEGMENT_64 = 0x19; /// 64-bit image routines pub const LC_ROUTINES_64 = 0x1a; /// the uuid pub const LC_UUID = 0x1b; /// runpath additions pub const LC_RPATH = (0x1c | LC_REQ_DYLD); /// local of code signature pub const LC_CODE_SIGNATURE = 0x1d; /// local of info to split segments pub const LC_SEGMENT_SPLIT_INFO = 0x1e; /// load and re-export dylib pub const LC_REEXPORT_DYLIB = (0x1f | LC_REQ_DYLD); /// delay load of dylib until first use pub const LC_LAZY_LOAD_DYLIB = 0x20; /// encrypted segment information pub const LC_ENCRYPTION_INFO = 0x21; /// compressed dyld information pub const LC_DYLD_INFO = 0x22; /// compressed dyld information only pub const LC_DYLD_INFO_ONLY = (0x22 | LC_REQ_DYLD); /// load upward dylib pub const LC_LOAD_UPWARD_DYLIB = (0x23 | LC_REQ_DYLD); /// build for MacOSX min OS version pub const LC_VERSION_MIN_MACOSX = 0x24; /// build for iPhoneOS min OS version pub const LC_VERSION_MIN_IPHONEOS = 0x25; /// compressed table of function start addresses pub const LC_FUNCTION_STARTS = 0x26; /// string for dyld to treat like environment variable pub const LC_DYLD_ENVIRONMENT = 0x27; /// replacement for LC_UNIXTHREAD pub const LC_MAIN = (0x28 | LC_REQ_DYLD); /// table of non-instructions in __text pub const LC_DATA_IN_CODE = 0x29; /// source version used to build binary pub const LC_SOURCE_VERSION = 0x2A; /// Code signing DRs copied from linked dylibs pub const LC_DYLIB_CODE_SIGN_DRS = 0x2B; /// 64-bit encrypted segment information pub const LC_ENCRYPTION_INFO_64 = 0x2C; /// linker options in MH_OBJECT files pub const LC_LINKER_OPTION = 0x2D; /// optimization hints in MH_OBJECT files pub const LC_LINKER_OPTIMIZATION_HINT = 0x2E; /// build for AppleTV min OS version pub const LC_VERSION_MIN_TVOS = 0x2F; /// build for Watch min OS version pub const LC_VERSION_MIN_WATCHOS = 0x30; /// arbitrary data included within a Mach-O file pub const LC_NOTE = 0x31; /// build for platform min OS version pub const LC_BUILD_VERSION = 0x32; /// the mach magic number pub const MH_MAGIC = 0xfeedface; /// NXSwapInt(MH_MAGIC) pub const MH_CIGAM = 0xcefaedfe; /// the 64-bit mach magic number pub const MH_MAGIC_64 = 0xfeedfacf; /// NXSwapInt(MH_MAGIC_64) pub const MH_CIGAM_64 = 0xcffaedfe; /// relocatable object file pub const MH_OBJECT = 0x1; /// demand paged executable file pub const MH_EXECUTE = 0x2; /// fixed VM shared library file pub const MH_FVMLIB = 0x3; /// core file pub const MH_CORE = 0x4; /// preloaded executable file pub const MH_PRELOAD = 0x5; /// dynamically bound shared library pub const MH_DYLIB = 0x6; /// dynamic link editor pub const MH_DYLINKER = 0x7; /// dynamically bound bundle file pub const MH_BUNDLE = 0x8; /// shared library stub for static linking only, no section contents pub const MH_DYLIB_STUB = 0x9; /// companion file with only debug sections pub const MH_DSYM = 0xa; /// x86_64 kexts pub const MH_KEXT_BUNDLE = 0xb; // Constants for the flags field of the mach_header /// the object file has no undefined references pub const MH_NOUNDEFS = 0x1; /// the object file is the output of an incremental link against a base file and can't be link edited again pub const MH_INCRLINK = 0x2; /// the object file is input for the dynamic linker and can't be staticly link edited again pub const MH_DYLDLINK = 0x4; /// the object file's undefined references are bound by the dynamic linker when loaded. pub const MH_BINDATLOAD = 0x8; /// the file has its dynamic undefined references prebound. pub const MH_PREBOUND = 0x10; /// the file has its read-only and read-write segments split pub const MH_SPLIT_SEGS = 0x20; /// the shared library init routine is to be run lazily via catching memory faults to its writeable segments (obsolete) pub const MH_LAZY_INIT = 0x40; /// the image is using two-level name space bindings pub const MH_TWOLEVEL = 0x80; /// the executable is forcing all images to use flat name space bindings pub const MH_FORCE_FLAT = 0x100; /// this umbrella guarantees no multiple defintions of symbols in its sub-images so the two-level namespace hints can always be used. pub const MH_NOMULTIDEFS = 0x200; /// do not have dyld notify the prebinding agent about this executable pub const MH_NOFIXPREBINDING = 0x400; /// the binary is not prebound but can have its prebinding redone. only used when MH_PREBOUND is not set. pub const MH_PREBINDABLE = 0x800; /// indicates that this binary binds to all two-level namespace modules of its dependent libraries. only used when MH_PREBINDABLE and MH_TWOLEVEL are both set. pub const MH_ALLMODSBOUND = 0x1000; /// safe to divide up the sections into sub-sections via symbols for dead code stripping pub const MH_SUBSECTIONS_VIA_SYMBOLS = 0x2000; /// the binary has been canonicalized via the unprebind operation pub const MH_CANONICAL = 0x4000; /// the final linked image contains external weak symbols pub const MH_WEAK_DEFINES = 0x8000; /// the final linked image uses weak symbols pub const MH_BINDS_TO_WEAK = 0x10000; /// When this bit is set, all stacks in the task will be given stack execution privilege. Only used in MH_EXECUTE filetypes. pub const MH_ALLOW_STACK_EXECUTION = 0x20000; /// When this bit is set, the binary declares it is safe for use in processes with uid zero pub const MH_ROOT_SAFE = 0x40000; /// When this bit is set, the binary declares it is safe for use in processes when issetugid() is true pub const MH_SETUID_SAFE = 0x80000; /// When this bit is set on a dylib, the static linker does not need to examine dependent dylibs to see if any are re-exported pub const MH_NO_REEXPORTED_DYLIBS = 0x100000; /// When this bit is set, the OS will load the main executable at a random address. Only used in MH_EXECUTE filetypes. pub const MH_PIE = 0x200000; /// Only for use on dylibs. When linking against a dylib that has this bit set, the static linker will automatically not create a LC_LOAD_DYLIB load command to the dylib if no symbols are being referenced from the dylib. pub const MH_DEAD_STRIPPABLE_DYLIB = 0x400000; /// Contains a section of type S_THREAD_LOCAL_VARIABLES pub const MH_HAS_TLV_DESCRIPTORS = 0x800000; /// When this bit is set, the OS will run the main executable with a non-executable heap even on platforms (e.g. i386) that don't require it. Only used in MH_EXECUTE filetypes. pub const MH_NO_HEAP_EXECUTION = 0x1000000; /// The code was linked for use in an application extension. pub const MH_APP_EXTENSION_SAFE = 0x02000000; /// The external symbols listed in the nlist symbol table do not include all the symbols listed in the dyld info. pub const MH_NLIST_OUTOFSYNC_WITH_DYLDINFO = 0x04000000; /// The flags field of a section structure is separated into two parts a section /// type and section attributes. The section types are mutually exclusive (it /// can only have one type) but the section attributes are not (it may have more /// than one attribute). /// 256 section types pub const SECTION_TYPE = 0x000000ff; /// 24 section attributes pub const SECTION_ATTRIBUTES = 0xffffff00; /// regular section pub const S_REGULAR = 0x0; /// zero fill on demand section pub const S_ZEROFILL = 0x1; /// section with only literal C string pub const S_CSTRING_LITERALS = 0x2; /// section with only 4 byte literals pub const S_4BYTE_LITERALS = 0x3; /// section with only 8 byte literals pub const S_8BYTE_LITERALS = 0x4; /// section with only pointers to pub const S_LITERAL_POINTERS = 0x5; /// if any of these bits set, a symbolic debugging entry pub const N_STAB = 0xe0; /// private external symbol bit pub const N_PEXT = 0x10; /// mask for the type bits pub const N_TYPE = 0x0e; /// external symbol bit, set for external symbols pub const N_EXT = 0x01; /// global symbol: name,,NO_SECT,type,0 pub const N_GSYM = 0x20; /// procedure name (f77 kludge): name,,NO_SECT,0,0 pub const N_FNAME = 0x22; /// procedure: name,,n_sect,linenumber,address pub const N_FUN = 0x24; /// static symbol: name,,n_sect,type,address pub const N_STSYM = 0x26; /// .lcomm symbol: name,,n_sect,type,address pub const N_LCSYM = 0x28; /// begin nsect sym: 0,,n_sect,0,address pub const N_BNSYM = 0x2e; /// AST file path: name,,NO_SECT,0,0 pub const N_AST = 0x32; /// emitted with gcc2_compiled and in gcc source pub const N_OPT = 0x3c; /// register sym: name,,NO_SECT,type,register pub const N_RSYM = 0x40; /// src line: 0,,n_sect,linenumber,address pub const N_SLINE = 0x44; /// end nsect sym: 0,,n_sect,0,address pub const N_ENSYM = 0x4e; /// structure elt: name,,NO_SECT,type,struct_offset pub const N_SSYM = 0x60; /// source file name: name,,n_sect,0,address pub const N_SO = 0x64; /// object file name: name,,0,0,st_mtime pub const N_OSO = 0x66; /// local sym: name,,NO_SECT,type,offset pub const N_LSYM = 0x80; /// include file beginning: name,,NO_SECT,0,sum pub const N_BINCL = 0x82; /// #included file name: name,,n_sect,0,address pub const N_SOL = 0x84; /// compiler parameters: name,,NO_SECT,0,0 pub const N_PARAMS = 0x86; /// compiler version: name,,NO_SECT,0,0 pub const N_VERSION = 0x88; /// compiler -O level: name,,NO_SECT,0,0 pub const N_OLEVEL = 0x8A; /// parameter: name,,NO_SECT,type,offset pub const N_PSYM = 0xa0; /// include file end: name,,NO_SECT,0,0 pub const N_EINCL = 0xa2; /// alternate entry: name,,n_sect,linenumber,address pub const N_ENTRY = 0xa4; /// left bracket: 0,,NO_SECT,nesting level,address pub const N_LBRAC = 0xc0; /// deleted include file: name,,NO_SECT,0,sum pub const N_EXCL = 0xc2; /// right bracket: 0,,NO_SECT,nesting level,address pub const N_RBRAC = 0xe0; /// begin common: name,,NO_SECT,0,0 pub const N_BCOMM = 0xe2; /// end common: name,,n_sect,0,0 pub const N_ECOMM = 0xe4; /// end common (local name): 0,,n_sect,0,address pub const N_ECOML = 0xe8; /// second stab entry with length information pub const N_LENG = 0xfe; /// If a segment contains any sections marked with S_ATTR_DEBUG then all /// sections in that segment must have this attribute. No section other than /// a section marked with this attribute may reference the contents of this /// section. A section with this attribute may contain no symbols and must have /// a section type S_REGULAR. The static linker will not copy section contents /// from sections with this attribute into its output file. These sections /// generally contain DWARF debugging info. /// a debug section pub const S_ATTR_DEBUG = 0x02000000; pub const cpu_type_t = integer_t; pub const cpu_subtype_t = integer_t; pub const integer_t = c_int; pub const vm_prot_t = c_int; /// CPU type targeting 64-bit Intel-based Macs pub const CPU_TYPE_X86_64: cpu_type_t = 0x01000007; /// CPU type targeting 64-bit ARM-based Macs pub const CPU_TYPE_ARM64: cpu_type_t = 0x0100000C; /// All Intel-based Macs pub const CPU_SUBTYPE_X86_64_ALL: cpu_subtype_t = 0x3; /// All ARM-based Macs pub const CPU_SUBTYPE_ARM_ALL: cpu_subtype_t = 0x0;
lib/std/macho.zig
const std = @import("std"); const runtime_spec = @import("runtime_spec.zig"); const syscall = @import("syscall.zig"); pub fn realpathAllocZ(alloc: *std.mem.Allocator, pathname: []const u8) ![:0]u8 { var buf: [std.fs.MAX_PATH_BYTES]u8 = undefined; return alloc.dupeZ(u8, try std.fs.cwd().realpath(pathname, buf[0..])); } pub fn mkdirs(pathname: []const u8, mode: u32) std.os.MakeDirError!void { if (std.os.access(pathname, std.os.F_OK)) |_| { return; } else |_| {} try mkdirs(std.fs.path.dirname(pathname).?, mode); try std.os.mkdir(pathname, mode); } pub fn ptrZtoSlice(ptr: [*:0]u8) [:0]u8 { return ptr[0..std.mem.lenZ(ptr) :0]; } pub fn JsonLoader(comptime T: type) type { return struct { const Self = @This(); parseOption: std.json.ParseOptions, value: T, pub fn init(alloc: *std.mem.Allocator, slice: []const u8) !Self { var option = std.json.ParseOptions{ .allocator = alloc }; return Self{ .parseOption = option, .value = try std.json.parse(T, &std.json.TokenStream.init(slice), option), }; } pub fn initFromFile(alloc: *std.mem.Allocator, path: []const u8) !Self { var file = try std.fs.cwd().openFile(path, .{}); var content = try file.readToEndAlloc(alloc, 65535); defer alloc.free(content); return Self.init(alloc, content); } pub fn deinit(self: *Self) void { std.json.parseFree(T, self.value, self.parseOption); } }; } fn waitPidfd(pidfd: i32, timeout: i32) !bool { const exited = try syscall.poll(&[_]std.os.pollfd{.{ .fd = pidfd, .events = std.os.POLL.IN, .revents = 0, }}, 1, timeout); return exited != 0; } pub const Process = struct { id: std.os.pid_t, fd: std.os.fd_t, detach: bool, pub fn wait(self: *const Process) !void { if (!self.detach) { _ = try waitPidfd(self.fd, -1); } } pub fn createPidFile(self: *const Process, pid_file: []const u8) !void { var f = try std.fs.createFileAbsolute(pid_file, .{ .exclusive = true, .mode = 0o644 }); defer f.close(); try std.fmt.format(f.writer(), "{}", .{self.id}); } }; pub fn fork(detach: bool) !?Process { const ppidfd = try syscall.pidfd_open(std.os.linux.getpid(), 0); var pidfd: i32 = -1; var cloneArgs = syscall.clone_args{ .flags = syscall.CLONE.PIDFD, .pidfd = @ptrToInt(&pidfd), .child_tid = 0, .parent_tid = 0, .exit_signal = 0, .stack = 0, .stack_size = 0, .tls = 0, .set_tid = 0, .set_tid_size = 0, .cgroup = 0, }; const pid = try syscall.clone3(&cloneArgs); if (pid != 0) { return Process{ .id = pid, .fd = pidfd, .detach = detach }; } if (!detach) { _ = try std.os.prctl(.SET_PDEATHSIG, .{std.os.linux.SIG.KILL}); if (try waitPidfd(ppidfd, 0)) { std.os.exit(0); } } return null; } pub const Namespace = enum(usize) { pid = syscall.CLONE.NEWPID, network = syscall.CLONE.NEWNET, ipc = syscall.CLONE.NEWIPC, uts = syscall.CLONE.NEWUTS, mount = syscall.CLONE.NEWNS, }; pub fn setupNamespace(namespace: Namespace, config: []runtime_spec.LinuxNamespace) !void { for (config) |namespace_config| { if (std.mem.eql(u8, @tagName(namespace), namespace_config.type)) { if (namespace_config.path) |path| { const fd = try std.os.open(path, std.os.O.RDONLY | std.os.O.CLOEXEC, 0); defer std.os.close(fd); try syscall.setns(fd, @enumToInt(namespace)); } else { try syscall.unshare(@enumToInt(namespace)); } return; } } return; } const SpecError = error{UnknowNamespace}; pub fn validateSpec(spec: *const runtime_spec.Spec) SpecError!void { for (spec.linux.namespaces) |namespace_config| { var valid = false; inline for (@typeInfo(Namespace).Enum.fields) |filed| { if (std.mem.eql(u8, filed.name, namespace_config.type)) { valid = true; } } if (!valid) { return error.UnknowNamespace; } } return; }
src/utils.zig
const std = @import("std"); const c = @import("c.zig"); const shaderc = @import("shaderc.zig"); const Scene = @import("scene.zig").Scene; // This struct runs a raytracing kernel which uses an encoded scene and // tape to evaluate generic scenes. This is slower than compiling a // scene-specific kernel, but is much more efficient to update (because // you only need to modify the scene storage buffer). pub const Preview = struct { const Self = @This(); alloc: *std.mem.Allocator, initialized: bool = false, // GPU handles device: c.WGPUDeviceId, queue: c.WGPUQueueId, bind_group: c.WGPUBindGroupId, bind_group_layout: c.WGPUBindGroupLayoutId, uniform_buf: c.WGPUBufferId, // owned by the parent Renderer scene_buf: c.WGPUBufferId, scene_buf_len: usize, image_buf: c.WGPUBufferId, // owned by the parent Renderer image_buf_size: u32, compute_pipeline: c.WGPUComputePipelineId, pub fn init( alloc: *std.mem.Allocator, scene: Scene, device: c.WGPUDeviceId, uniform_buf: c.WGPUBufferId, image_buf: c.WGPUBufferId, image_buf_size: u32, ) !Self { var arena = std.heap.ArenaAllocator.init(alloc); const tmp_alloc: *std.mem.Allocator = &arena.allocator; defer arena.deinit(); // This is the only available queue right now const queue = c.wgpu_device_get_default_queue(device); // Build the shaders using shaderc const comp_name = "shaders/preview.comp"; const comp_spv = try shaderc.build_shader_from_file(tmp_alloc, comp_name); const comp_shader = c.wgpu_device_create_shader_module( device, &(c.WGPUShaderModuleDescriptor){ .label = comp_name, .bytes = comp_spv.ptr, .length = comp_spv.len, .flags = c.WGPUShaderFlags_VALIDATION, }, ); defer c.wgpu_shader_module_destroy(comp_shader); //////////////////////////////////////////////////////////////////////////// // Bind groups const bind_group_layout_entries = [_]c.WGPUBindGroupLayoutEntry{ (c.WGPUBindGroupLayoutEntry){ // Uniforms buffer .binding = 0, .visibility = c.WGPUShaderStage_COMPUTE, .ty = c.WGPUBindingType_UniformBuffer, .has_dynamic_offset = false, .min_buffer_binding_size = 0, .multisampled = undefined, .filtering = undefined, .view_dimension = undefined, .texture_component_type = undefined, .storage_texture_format = undefined, .count = undefined, }, (c.WGPUBindGroupLayoutEntry){ // Image buffer .binding = 1, .visibility = c.WGPUShaderStage_COMPUTE, .ty = c.WGPUBindingType_StorageBuffer, .has_dynamic_offset = false, .min_buffer_binding_size = 0, .multisampled = undefined, .filtering = undefined, .view_dimension = undefined, .texture_component_type = undefined, .storage_texture_format = undefined, .count = undefined, }, (c.WGPUBindGroupLayoutEntry){ // Scene buffer .binding = 2, .visibility = c.WGPUShaderStage_COMPUTE, .ty = c.WGPUBindingType_StorageBuffer, .has_dynamic_offset = false, .min_buffer_binding_size = 0, .multisampled = undefined, .filtering = undefined, .view_dimension = undefined, .texture_component_type = undefined, .storage_texture_format = undefined, .count = undefined, }, }; const bind_group_layout = c.wgpu_device_create_bind_group_layout( device, &(c.WGPUBindGroupLayoutDescriptor){ .label = "bind group layout", .entries = &bind_group_layout_entries, .entries_length = bind_group_layout_entries.len, }, ); const bind_group_layouts = [_]c.WGPUBindGroupId{bind_group_layout}; //////////////////////////////////////////////////////////////////////// // Render pipelines const pipeline_layout = c.wgpu_device_create_pipeline_layout( device, &(c.WGPUPipelineLayoutDescriptor){ .label = "", .bind_group_layouts = &bind_group_layouts, .bind_group_layouts_length = bind_group_layouts.len, }, ); defer c.wgpu_pipeline_layout_destroy(pipeline_layout); const compute_pipeline = c.wgpu_device_create_compute_pipeline( device, &(c.WGPUComputePipelineDescriptor){ .label = "preview pipeline", .layout = pipeline_layout, .compute_stage = (c.WGPUProgrammableStageDescriptor){ .module = comp_shader, .entry_point = "main", }, }, ); //////////////////////////////////////////////////////////////////////// var out = Self{ .alloc = alloc, .device = device, .queue = queue, .bind_group = undefined, // assigned in upload_scene() below .bind_group_layout = bind_group_layout, .scene_buf = undefined, // assigned in upload_scene() below .scene_buf_len = 0, .uniform_buf = uniform_buf, .image_buf = image_buf, .image_buf_size = image_buf_size, .compute_pipeline = compute_pipeline, }; try out.upload_scene(scene); out.initialized = true; return out; } pub fn bind(self: *Self, image_buf: c.WGPUBufferId, image_buf_size: u32) void { self.image_buf = image_buf; self.image_buf_size = image_buf_size; self.rebuild_bind_group(); } pub fn deinit(self: *Self) void { c.wgpu_bind_group_destroy(self.bind_group); c.wgpu_bind_group_layout_destroy(self.bind_group_layout); c.wgpu_buffer_destroy(self.scene_buf, true); c.wgpu_compute_pipeline_destroy(self.compute_pipeline); } fn rebuild_bind_group(self: *Self) void { if (self.initialized) { c.wgpu_bind_group_destroy(self.bind_group); } // Rebuild the bind group as well const bind_group_entries = [_]c.WGPUBindGroupEntry{ (c.WGPUBindGroupEntry){ .binding = 0, .buffer = self.uniform_buf, .offset = 0, .size = @sizeOf(c.rayUniforms), .sampler = 0, // None .texture_view = 0, // None }, (c.WGPUBindGroupEntry){ .binding = 1, .buffer = self.image_buf, .offset = 0, .size = self.image_buf_size, .sampler = 0, // None .texture_view = 0, // None }, (c.WGPUBindGroupEntry){ .binding = 2, .buffer = self.scene_buf, .offset = 0, .size = self.scene_buf_len, .sampler = 0, // None .texture_view = 0, // None }, }; self.bind_group = c.wgpu_device_create_bind_group( self.device, &(c.WGPUBindGroupDescriptor){ .label = "bind group", .layout = self.bind_group_layout, .entries = &bind_group_entries, .entries_length = bind_group_entries.len, }, ); } // Copies the scene from self.scene to the GPU, rebuilding the bind // group if the buffer has been resized (which would invalidate it) pub fn upload_scene(self: *Self, scene: Scene) !void { const encoded = try scene.encode(); defer self.alloc.free(encoded); const scene_buf_len = encoded.len * @sizeOf(c.vec4); if (scene_buf_len > self.scene_buf_len) { if (self.initialized) { c.wgpu_buffer_destroy(self.scene_buf, true); } self.scene_buf = c.wgpu_device_create_buffer( self.device, &(c.WGPUBufferDescriptor){ .label = "raytrace scene", .size = scene_buf_len, .usage = c.WGPUBufferUsage_STORAGE | c.WGPUBufferUsage_COPY_DST, .mapped_at_creation = false, }, ); self.scene_buf_len = scene_buf_len; self.rebuild_bind_group(); } c.wgpu_queue_write_buffer( self.queue, self.scene_buf, 0, @ptrCast([*c]const u8, encoded.ptr), encoded.len * @sizeOf(c.vec4), ); } pub fn render( self: *Self, _: bool, nt: u32, cmd_encoder: c.WGPUCommandEncoderId, ) !void { const cpass = c.wgpu_command_encoder_begin_compute_pass( cmd_encoder, &(c.WGPUComputePassDescriptor){ .label = "" }, ); c.wgpu_compute_pass_set_pipeline(cpass, self.compute_pipeline); c.wgpu_compute_pass_set_bind_group(cpass, 0, self.bind_group, null, 0); c.wgpu_compute_pass_dispatch(cpass, nt, 1, 1); c.wgpu_compute_pass_end_pass(cpass); } };
src/preview.zig
const std = @import("std"); const zfetch = @import("zfetch"); const json = @import("json"); const string = []const u8; const Config = struct { token: string, user: string, repo: string, commit: string, title: string, body: string, tag: string, path: string, draft: bool, prerelease: bool, }; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var arena = std.heap.ArenaAllocator.init(gpa.allocator()); defer arena.deinit(); const alloc = arena.allocator(); var config: Config = .{ .token = "", .user = "", .repo = "", .commit = "", .title = "", .body = "", .tag = "", .path = "", .draft = false, .prerelease = false, }; var envmap = try std.process.getEnvMap(alloc); defer envmap.deinit(); if (envmap.get("GITHUB_TOKEN")) |env| config.token = env; var argiter = std.process.args(); defer argiter.deinit(); var argi: usize = 0; while (argiter.next(alloc)) |item| : (argi += 1) { if (argi == 0) continue; const data = try item; // zig fmt: off if (std.mem.eql(u8, data, "-t")) { config.token = try argiter.next(alloc).?; continue; } if (std.mem.eql(u8, data, "-u")) { config.user = try argiter.next(alloc).?; continue; } if (std.mem.eql(u8, data, "-r")) { config.repo = try argiter.next(alloc).?; continue; } if (std.mem.eql(u8, data, "-c")) { config.commit = try argiter.next(alloc).?; continue; } if (std.mem.eql(u8, data, "-n")) { config.title = try argiter.next(alloc).?; continue; } if (std.mem.eql(u8, data, "-b")) { config.body = try argiter.next(alloc).?; continue; } if (std.mem.eql(u8, data, "-draft")) { config.draft = true; continue; } if (std.mem.eql(u8, data, "-prerelease")) { config.prerelease = true; continue; } // zig fmt: on config.tag = data; config.path = try argiter.next(alloc).?; break; } std.debug.assert(config.token.len > 0); std.debug.assert(config.user.len > 0); std.debug.assert(config.repo.len > 0); std.debug.assert(config.tag.len > 0); std.debug.assert(config.path.len > 0); if (config.title.len == 0) config.title = config.tag; if (config.commit.len == 0) config.commit = try rev_HEAD(alloc); const url = try std.fmt.allocPrint(alloc, "https://api.github.com/repos/{s}/{s}/releases", .{ config.user, config.repo }); var req = try fetchJson(alloc, config.token, .POST, url, .{ .tag_name = config.tag, .target_commitish = config.commit, .name = config.title, .body = config.body, .draft = config.draft, .prerelease = config.prerelease, }); defer req.deinit(); const stdout = std.io.getStdOut().writer(); try stdout.print("info: creating release: {s} @ {s}:{s}\n", .{ config.title, config.tag, config.commit }); std.testing.expectEqual(@as(u16, 201), req.status.code) catch std.os.exit(1); const reader = req.reader(); const body_content = try reader.readAllAlloc(alloc, std.math.maxInt(usize)); const val = try json.parse(alloc, body_content); var upload_url = val.getT("upload_url", .String).?; upload_url = upload_url[0..std.mem.indexOfScalar(u8, upload_url, '{').?]; const dir = try std.fs.cwd().openDir(config.path, .{ .iterate = true }); var iter = dir.iterate(); while (try iter.next()) |item| { var arena2 = std.heap.ArenaAllocator.init(alloc); defer arena2.deinit(); const alloc2 = arena2.allocator(); if (item.kind != .File) continue; try stdout.print("--> Uploading: {s}\n", .{item.name}); const path = try std.fs.path.join(alloc2, &.{ config.path, item.name }); const file = try std.fs.cwd().openFile(path, .{}); const contents = try file.reader().readAllAlloc(alloc2, std.math.maxInt(usize)); const actualupurl = try std.mem.concat(alloc2, u8, &.{ upload_url, "?name=", item.name }); var upreq = try fetchRaw(alloc2, config.token, .POST, actualupurl, contents); std.testing.expectEqual(@as(u16, 201), upreq.status.code) catch { std.log.debug("{s}", .{upreq.reader().readAllAlloc(alloc2, std.math.maxInt(usize))}); }; } } /// Returns the result of running `git rev-parse HEAD` pub fn rev_HEAD(alloc: std.mem.Allocator) !string { const max = std.math.maxInt(usize); const dirg = try std.fs.cwd().openDir(".git", .{}); const h = std.mem.trim(u8, try dirg.readFileAlloc(alloc, "HEAD", max), "\n"); const r = std.mem.trim(u8, try dirg.readFileAlloc(alloc, h[5..], max), "\n"); return r; } fn fetchJson(allocator: std.mem.Allocator, token: string, method: zfetch.Method, url: string, body: anytype) !*zfetch.Request { var headers = zfetch.Headers.init(allocator); defer headers.deinit(); try headers.appendValue("Accept", "application/vnd.github.v3+json"); try headers.appendValue("Authorization", try std.mem.join(allocator, " ", &.{ "token", token })); try headers.appendValue("Content-Type", "application/json"); var req = try zfetch.Request.init(allocator, url, null); try req.do(method, headers, try stringifyAlloc(allocator, .{}, body)); return req; } fn fetchRaw(allocator: std.mem.Allocator, token: string, method: zfetch.Method, url: string, body: []const u8) !*zfetch.Request { var headers = zfetch.Headers.init(allocator); defer headers.deinit(); try headers.appendValue("Accept", "application/vnd.github.v3+json"); try headers.appendValue("Authorization", try std.mem.join(allocator, " ", &.{ "token", token })); try headers.appendValue("Content-Type", "application/octet-stream"); try headers.appendValue("Content-Length", try std.fmt.allocPrint(allocator, "{d}", .{body.len})); var req = try zfetch.Request.init(allocator, url, null); try req.do(method, headers, body); return req; } // Same as `stringify` but accepts an Allocator and stores result in dynamically allocated memory instead of using a Writer. // Caller owns returned memory. pub fn stringifyAlloc(allocator: std.mem.Allocator, options: std.json.StringifyOptions, value: anytype) !string { var list = std.ArrayList(u8).init(allocator); defer list.deinit(); try std.json.stringify(value, options, list.writer()); return list.toOwnedSlice(); }
src/main.zig