code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const mem = std.mem; const c = @import("./c.zig"); const glfw = @import("./main.zig"); /// Opaque window object. pub const Window = struct { const Self = @This(); handle: *c.GLFWwindow, pub const ClientApi = enum(i32) { OpenGLApi = c.GLFW_OPENGL_API, OpenGLESApi = c.GLFW_OPENGL_ES_API, NoApi = c.GLFW_NO_API, }; pub const ContextCreationApi = enum(i32) { NativeContextApi = c.GLFW_NATIVE_CONTEXT_API, EGLContextApi = c.GLFW_EGL_CONTEXT_API, OSMesaContextApi = c.GLFW_OSMESA_CONTEXT_API, }; pub const ContextRobustness = enum(i32) { NoRobustness = c.GLFW_NO_ROBUSTNESS, NoResetNotification = c.GLFW_NO_RESET_NOTIFICATION, LoseContextOnReset = c.GLFW_LOSE_CONTEXT_ON_RESET, }; pub const ContextReleaseBehavior = enum(i32) { AnyReleaseBehavior = c.GLFW_ANY_RELEASE_BEHAVIOR, ReleaseBehaviorFlush = c.GLFW_RELEASE_BEHAVIOR_FLUSH, ReleaseBehaviorNone = c.GLFW_RELEASE_BEHAVIOR_NONE, }; pub const OpenGLProfile = enum(i32) { OpenGLAnyProfile = c.GLFW_OPENGL_ANY_PROFILE, OpenGLCompatProfile = c.GLFW_OPENGL_COMPAT_PROFILE, OpenGLCoreProfile = c.GLFW_OPENGL_CORE_PROFILE, }; pub const HintName = enum(i32) { Resizable = c.GLFW_RESIZABLE, Visible = c.GLFW_VISIBLE, Decorated = c.GLFW_DECORATED, DepthBits = c.GLFW_DEPTH_BITS, Focused = c.GLFW_FOCUSED, AutoIconify = c.GLFW_AUTO_ICONIFY, Floating = c.GLFW_FLOATING, Maximized = c.GLFW_MAXIMIZED, CenterCursor = c.GLFW_CENTER_CURSOR, TransparentFramebuffer = c.GLFW_TRANSPARENT_FRAMEBUFFER, FocusOnShow = c.GLFW_FOCUS_ON_SHOW, ScaleToMonitor = c.GLFW_SCALE_TO_MONITOR, RedBits = c.GLFW_RED_BITS, GreenBits = c.GLFW_GREEN_BITS, BlueBits = c.GLFW_BLUE_BITS, AlphaBits = c.GLFW_ALPHA_BITS, AccumRedBits = c.GLFW_ACCUM_RED_BITS, AccumGreenBits = c.GLFW_ACCUM_GREEN_BITS, AccumBlueBits = c.GLFW_ACCUM_BLUE_BITS, AccumAlphaBits = c.GLFW_ACCUM_ALPHA_BITS, AuxBuffers = c.GLFW_AUX_BUFFERS, Stereo = c.GLFW_STEREO, StencilBits = c.GLFW_STENCIL_BITS, Samples = c.GLFW_SAMPLES, SRGBCapable = c.GLFW_SRGB_CAPABLE, DoubleBuffer = c.GLFW_DOUBLEBUFFER, RefreshRate = c.GLFW_REFRESH_RATE, ClientApi = c.GLFW_CLIENT_API, ContextCreationApi = c.GLFW_CONTEXT_CREATION_API, ContextVersionMajor = c.GLFW_CONTEXT_VERSION_MAJOR, ContextVersionMinor = c.GLFW_CONTEXT_VERSION_MINOR, OpenGLForwardCompat = c.GLFW_OPENGL_FORWARD_COMPAT, OpenGLDebugContext = c.GLFW_OPENGL_DEBUG_CONTEXT, OpenGLProfile = c.GLFW_OPENGL_PROFILE, ContextRobustness = c.GLFW_CONTEXT_ROBUSTNESS, ContextReleaseBehavior = c.GLFW_CONTEXT_RELEASE_BEHAVIOR, ContextNoError = c.GLFW_CONTEXT_NO_ERROR, CocoaRetinaFramebuffer = c.GLFW_COCOA_RETINA_FRAMEBUFFER, CocoaFrameName = c.GLFW_COCOA_FRAME_NAME, CocoaGraphicsSwitching = c.GLFW_COCOA_GRAPHICS_SWITCHING, X11ClassName = c.GLFW_X11_CLASS_NAME, X11InstanceName = c.GLFW_X11_INSTANCE_NAME, }; pub const Hint = union(HintName) { ContextNoError: bool, Resizable: bool, Visible: bool, Decorated: bool, Focused: bool, AutoIconify: bool, Floating: bool, Maximized: bool, CenterCursor: bool, TransparentFramebuffer: bool, FocusOnShow: bool, ScaleToMonitor: bool, RedBits: ?i32, GreenBits: ?i32, BlueBits: ?i32, AlphaBits: ?i32, DepthBits: ?i32, StencilBits: ?i32, AccumRedBits: ?i32, AccumGreenBits: ?i32, AccumBlueBits: ?i32, AccumAlphaBits: ?i32, AuxBuffers: ?i32, Samples: ?i32, RefreshRate: ?i32, Stereo: bool, SRGBCapable: bool, DoubleBuffer: bool, ClientApi: ClientApi, ContextCreationApi: ContextCreationApi, ContextVersionMajor: i32, ContextVersionMinor: i32, ContextRobustness: ContextRobustness, ContextReleaseBehavior: ContextReleaseBehavior, OpenGLForwardCompat: bool, OpenGLDebugContext: bool, OpenGLProfile: OpenGLProfile, CocoaRetinaFramebuffer: bool, CocoaFrameName: [:0]const u8, CocoaGraphicsSwitching: bool, X11ClassName: [:0]const u8, X11InstanceName: [:0]const u8, }; pub fn defaultHints() void { c.glfwDefaultWindowHints(); glfw.getError() catch |err| switch (err) { .NotInitialized => return err, else => unreachable, }; } /// This function sets hints for the next call to `Window.init`. The hints, /// once set, retain their values until changed by a call to this function /// or `Window.defaultHints`, or until the library is terminated. /// /// This function does not check whether the specified hint values are /// valid. If you set hints to invalid values this will instead be reported /// by the next call to `Window.init`. /// /// Some hints are platform specific. These may be set on any platform but /// they will only affect their specific platform. Other platforms will /// ignore them. Setting these hints requires no platform specific headers /// or functions. pub fn setHint(hint: Hint) !void { switch (hint) { .ContextNoError => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .Resizable => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .Visible => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .Decorated => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .Focused => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .AutoIconify => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .Floating => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .Maximized => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .CenterCursor => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .TransparentFramebuffer => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .FocusOnShow => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .ScaleToMonitor => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .RedBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .GreenBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .BlueBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .AlphaBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .DepthBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .StencilBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .AccumRedBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .AccumGreenBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .AccumBlueBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .AccumAlphaBits => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .AuxBuffers => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .Samples => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .RefreshRate => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .Stereo => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .SRGBCapable => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .DoubleBuffer => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .ClientApi => |value| c.glfwWindowHint(@enumToInt(hint), @enumToInt(value)), .ContextCreationApi => |value| c.glfwWindowHint(@enumToInt(hint), @enumToInt(value)), .ContextVersionMajor => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .ContextVersionMinor => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWInt(value)), .ContextRobustness => |value| c.glfwWindowHint(@enumToInt(hint), @enumToInt(value)), .ContextReleaseBehavior => |value| c.glfwWindowHint(@enumToInt(hint), @enumToInt(value)), .OpenGLForwardCompat => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .OpenGLDebugContext => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .OpenGLProfile => |value| c.glfwWindowHint(@enumToInt(hint), @enumToInt(value)), .CocoaRetinaFramebuffer => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .CocoaFrameName => |value| c.glfwWindowHintString(@enumToInt(hint), value.ptr), .CocoaGraphicsSwitching => |value| c.glfwWindowHint(@enumToInt(hint), toGLFWBool(value)), .X11ClassName => |value| c.glfwWindowHintString(@enumToInt(hint), value.ptr), .X11InstanceName => |value| c.glfwWindowHintString(@enumToInt(hint), value.ptr), } glfw.getError() catch |err| switch (err) { error.NotInitialized => return err, else => unreachable, }; } pub const AttributeName = enum(i32) { Focused = c.GLFW_FOCUSED, Iconified = c.GLFW_ICONIFIED, Maximized = c.GLFW_MAXIMIZED, Hovered = c.GLFW_HOVERED, Visible = c.GLFW_VISIBLE, Resizable = c.GLFW_RESIZABLE, Decorated = c.GLFW_DECORATED, AutoIconify = c.GLFW_AUTO_ICONIFY, Floating = c.GFLW_FLOATING, TransparentFramebuffer = c.GLFW_TRANSPARENT_FRAMEBUFFER, FocusOnShow = c.GLFW_FOCUS_ON_SHOW, ClientApi = c.GLFW_CLIENT_API, ContextCreationApi = c.GLFW_CONTEXT_CREATION_API, ContextVersionMajor = c.GLFW_CONTEXT_VERSION_MAJOR, ContextVersionMinor = c.GLFW_CONTEXT_VERSION_MINOR, ContextRevision = c.GLFW_CONTEXT_REVISION, OpenGLForwardCompat = c.GLFW_OPENGL_FORWARD_COMPAT, OpenGLDebugContext = c.GLFW_OPENGGL_DEBUG_CONTEXT, OpenGLProfile = c.GLFW_OPENGL_PROFILE, ContextReleaseBehavior = c.GLFW_CONTEXT_RELEASE_BEHAVIOR, ContextNoError = c.GLFW_CONTEXT_NO_ERROR, ContextRobustness = c.GLFW_CONTEXT_ROBUSTNESS, }; pub const Attribute = union(AttributeName) { Focused: bool, Iconified: bool, Maximized: bool, Hovered: bool, Visible: bool, Resizable: bool, Decorated: bool, AutoIconify: bool, Floating: bool, TransparentFramebuffer: bool, FocusOnShow: bool, ClientApi: ClientApi, ContextCreationApi: ContextCreationApi, ContextVersionMajor: i32, ContextVersionMinor: i32, ContextRevision: i32, OpenGLForwardCompat: bool, OpenGLDebugContext: bool, OpenGLProfile: OpenGLProfile, ContextReleaseBehavior: ContextReleaseBehavior, ContextNoError: bool, ContextRobustness: ContextRobustness, }; /// This function returns the value of an attribute of the specified window /// or its OpenGL or OpenGL ES context. pub fn getAttrib(self: Self, attrib: AttributeName) !Attribute { var attribute = blk: { switch (attrib) { .Focused => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Focused = value == c.GLFW_TRUE }; }, .Iconified => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Iconified = value == c.GLFW_TRUE }; }, .Maximized => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Maximized = value == c.GLFW_TRUE }; }, .Hovered => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Hovered = value == c.GLFW_TRUE }; }, .Visible => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Visible = value == c.GLFW_TRUE }; }, .Resizable => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Resizable = value == c.GLFW_TRUE }; }, .Decorated => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Decorated = value == c.GLFW_TRUE }; }, .AutoIconify => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .AutoIconify = value == c.GLFW_TRUE }; }, .Floating => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .Floating = value == c.GLFW_TRUE }; }, .TransparentFramebuffer => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .TransparentFramebuffer = value == c.GLFW_TRUE }; }, .FocusOnShow => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .FocusOnShow = value == c.GLFW_TRUE }; }, .ClientApi => { var value = @intToEnum(ClientApi, c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib))); break :blk Attribute{ .ClientApi = value, }; }, .ContextCreationApi => { var value = @intToEnum(ContextCreationApi, c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib))); break :blk Attribute{ .ContextCreationApi = value, }; }, .ContextVersionMajor => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .ContextVersionMajor = value, }; }, .ContextVersionMinor => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .ContextVersionMinor = value, }; }, .ContextRevision => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .ContextRevision = value, }; }, .OpenGLForwardCompat => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .OpenGLForwardCompat = value == c.GLFW_TRUE }; }, .OpenGLDebugContext => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .OpenGLDebugContext = value == c.GLFW_TRUE }; }, .OpenGLProfile => { var value = @intToEnum(OpenGLProfile, c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib))); break :blk Attribute{ .OpenGLProfile = value, }; }, .ContextReleaseBehavior => { var value = @intToEnum(ContextReleaseBehavior, c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib))); break :blk Attribute{ .ContextReleaseBehavior = value, }; }, .ContextNoError => { var value = c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib)); break :blk Attribute{ .ContextNoError = value == c.GLFW_TRUE }; }, .ContextRobustness => { var value = @intToEnum(ContextRobustness, c.glfwGetWindowAttrib(self.handle, @enumToInt(attrib))); break :blk Attribute{ .ContextRobustness = value, }; }, } }; glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return attribute; } /// This function sets the value of an attribute of the specified window. /// /// The supported attributes are `Decorated`, `Resizable`, `Floating`, /// `AutoIconify` and `FocusOnShow`. /// /// Some of these attributes are ignored for full screen windows. The new /// value will take effect if the window is later made windowed. /// /// Some of these attributes are ignored for windowed mode windows. The new /// value will take effect if the window is later made full screen. pub fn setAttrib(self: *Self, attribute: Attribute) !void { switch (attribute) { Resizable => |value| c.glfwSetWindowAttrib(self.handle, @enumToInt(attribute), toGLFWBool(value)), Decorated => |value| c.glfwSetWindowAttrib(self.handle, @enumToInt(attribute), toGLFWBool(value)), AutoIconify => |value| c.glfwSetWindowAttrib(self.handle, @enumToInt(attribute), toGLFWBool(value)), Floating => |value| c.glfwSetWindowAttrib(self.handle, @enumToInt(attribute), toGLFWBool(value)), FocusOnShow => |value| c.glfwSetWindowAttrib(self.handle, @enumToInt(attribute), toGLFWBool(value)), else => std.debug.panic("unsupported attribute in setter"), } glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } inline fn toGLFWBool(value: bool) i32 { return if (value) c.GLFW_TRUE else c.GLFW_FALSE; } inline fn toGLFWInt(value: ?i32) i32 { return if (value) |v| v else c.GLFW_DONT_CARE; } /// This function creates a window and its associated OpenGL or OpenGL ES /// context. Most of the options controlling how the window and its context /// should be created are specified with window hints. /// /// Successful creation does not change which context is current. Before you /// can use the newly created context, you need to make it current. For /// information about the share parameter, see Context object sharing. /// /// The created window, framebuffer and context may differ from what you /// requested, as not all parameters and hints are hard constraints. This /// includes the size of the window, especially for full screen windows. To /// query the actual attributes of the created window, framebuffer and /// context, see `WIndow.getAttrib`, `Window.getSize` and /// `Window.getFramebufferSize`. /// /// To create a full screen window, you need to specify the monitor the /// window will cover. If no monitor is specified, the window will be /// windowed mode. Unless you have a way for the user to choose a specific /// monitor, it is recommended that you pick the primary monitor. For more /// information on how to query connected monitors, see Retrieving monitors. /// /// For full screen windows, the specified size becomes the resolution of /// the window's desired video mode. As long as a full screen window is not /// iconified, the supported video mode most closely matching the desired /// video mode is set for the specified monitor. For more information about /// full screen windows, including the creation of so called windowed full /// screen or borderless full screen windows, see "Windowed full screen" /// windows. /// /// Once you have created the window, you can switch it between windowed and /// full screen mode with REPLACEME(glfwSetWindowMonitor). This will not affect its /// OpenGL or OpenGL ES context. /// /// By default, newly created windows use the placement recommended by the /// window system. To create the window at a specific position, make it /// initially invisible using the `Visible` window hint, set its position /// and then show it. /// /// As long as at least one full screen window is not iconified, the /// screensaver is prohibited from starting. /// /// Window systems put limits on window sizes. Very large or very small /// window dimensions may be overridden by the window system on creation. /// Check the actual size after creation. /// /// The swap interval is not set during window creation and the initial value may vary depending on driver settings and defaults. pub fn init(width: i32, height: i32, title: [:0]const u8, monitor: ?glfw.Monitor, share: ?glfw.Window) !Self { var handle = c.glfwCreateWindow(width, height, title.ptr, if (monitor) |m| m.handle else null, if (share) |s| s.handle else null); if (handle == null) { glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.InvalidValue, glfw.Error.ApiUnavailable, glfw.Error.VersionUnavailable, glfw.Error.FormatUnavailable, glfw.Error.PlatformError => return err, else => unreachable, }; } return Self{ .handle = handle.? }; } /// This function destroys the specified window and its context. On calling /// this function, no further callbacks will be called for that window. /// /// If the context of the specified window is current on the main thread, it /// is detached before being destroyed. pub fn deinit(self: *Self) void { c.glfwDestroyWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => std.debug.panic("cannot handle: {}\n", .{err}), else => unreachable, }; } /// This function returns the value of the close flag of the specified /// window. pub fn shouldClose(self: Self) !bool { var result = c.glfwWindowShouldClose(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized => return err, else => unreachable, }; return result == c.GLFW_TRUE; } /// This function sets the value of the close flag of the specified window. /// This can be used to override the user's attempt to close the window, or /// to signal that it should be closed. pub fn setShouldClose(self: *Self, value: bool) !void { c.glfwSetWindowShouldClose(self.handle, toGLFWBool(value)); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized => return err, else => unreachable, }; } /// This function sets the window title, encoded as UTF-8, of the specified /// window. pub fn setTitle(self: *Self, title: [:0]const u8) !void { c.glfwSetWindowTitle(self.handle, title.ptr); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function sets the icon of the specified window. If passed an array /// of candidate images, those of or closest to the sizes desired by the /// system are selected. If no images are specified, the window reverts to /// its default icon. /// /// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight /// bits per channel with the red channel first. They are arranged /// canonically as packed sequential rows, starting from the top-left /// corner. /// /// The desired image sizes varies depending on platform and system /// settings. The selected images will be rescaled as needed. Good sizes /// include 16x16, 32x32 and 48x48. pub fn setIcon(self: *Self, icon: glfw.Image) !void { return self.setIcons(&[1]glfw.Image{icon}); } /// This function sets the icon of the specified window. If passed an array /// of candidate images, those of or closest to the sizes desired by the /// system are selected. If no images are specified, the window reverts to /// its default icon. /// /// The pixels are 32-bit, little-endian, non-premultiplied RGBA, i.e. eight /// bits per channel with the red channel first. They are arranged /// canonically as packed sequential rows, starting from the top-left /// corner. /// /// The desired image sizes varies depending on platform and system /// settings. The selected images will be rescaled as needed. Good sizes /// include 16x16, 32x32 and 48x48. pub fn setIcons(self: *Self, icons: []glfw.Image) !void { c.glfwSetWindowIcon(self.handle, @intCast(i32, icons.len), icons.ptr); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } pub const Position = struct { x: i32, y: i32, }; /// This function retrieves the position, in screen coordinates, of the /// upper-left corner of the content area of the specified window. pub fn getPos(self: Self) !Position { var position: Position = undefined; c.glfwGetWindowPos(self.handle, &position.x, &position.y); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return position; } /// This function sets the position, in screen coordinates, of the /// upper-left corner of the content area of the specified windowed mode /// window. If the window is a full screen window, this function does /// nothing. /// /// Do not use this function to move an already visible window unless you /// have very good reasons for doing so, as it will confuse and annoy the /// user. /// /// The window manager may put limits on what positions are allowed. GLFW /// cannot and should not override these limits. pub fn setPos(self: *Self, position: Position) !void { c.glfwSetWindowPos(self.handle, position.x, position.y); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function retrieves the size, in screen coordinates, of the content /// area of the specified window. If you wish to retrieve the size of the /// framebuffer of the window in pixels, see `Window.getFramebufferSize`. pub fn getSize(self: Self) !glfw.Size { var size: glfw.Size = undefined; c.glfwGetWindowSize(self.handle, &size.width, &size.height); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return size; } /// This function sets the size, in screen coordinates, of the content area /// of the specified window. /// /// For full screen windows, this function updates the resolution of its /// desired video mode and switches to the video mode closest to it, without /// affecting the window's context. As the context is unaffected, the bit /// depths of the framebuffer remain unchanged. /// /// If you wish to update the refresh rate of the desired video mode in /// addition to its resolution, see REPLACEME(glfwSetWindowMonitor). /// /// The window manager may put limits on what sizes are allowed. GLFW cannot /// and should not override these limits. pub fn setSize(self: Self, size: glfw.Size) !void { c.glfwSetWindowSize(self.handle, size.width, size.height); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function sets the size limits of the content area of the specified /// window. If the window is full screen, the size limits only take effect /// once it is made windowed. If the window is not resizable, this function /// does nothing. /// /// The size limits are applied immediately to a windowed mode window and /// may cause it to be resized. /// /// The maximum dimensions must be greater than or equal to the minimum /// dimensions and all must be greater than or equal to zero. pub fn setSizeLimits(self: *Self, min: ?glfw.Size, max: ?glfw.Size) !void { var minwidth: i32 = if (min) |m| m.width else c.GLFW_DONT_CARE; var minheight: i32 = if (min) |m| m.height else c.GLFW_DONT_CARE; var maxwidth: i32 = if (max) |m| m.width else c.GLFW_DONT_CARE; var maxheight: i32 = if (max) |m| m.height else c.GLFW_DONT_CARE; c.glfwSetWindowSizeLimits(self.handle, minwidth, minheight, maxwidth, maxheight); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function sets the required aspect ratio of the content area of the /// specified window. If the window is full screen, the aspect ratio only /// takes effect once it is made windowed. If the window is not resizable, /// this function does nothing. /// /// The aspect ratio is specified as a numerator and a denominator and both /// values must be greater than zero. For example, the common 16:9 aspect /// ratio is specified as 16 and 9, respectively. /// /// If the aspect is `null`, then the aspect ratio limit is disabled. pub fn setAspectRatio(self: *Self, aspect: ?glfw.Size) !void { if (aspect) |a| { c.glfwSetWindowAspectRatio(self.handle, a.width, a.height); } else { c.glfwSetWindowAspectRatio(self.handle, c.GLFW_DONT_CARE, c.GLFW_DONT_CARE); } glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function retrieves the size, in pixels, of the framebuffer of the /// specified window. If you wish to retrieve the size of the window in /// screen coordinates, see `Window.getSize`. pub fn getFramebufferSize(self: Self) !glfw.Size { var framebufferSize: glfw.Size = undefined; c.glfwGetFramebufferSize(self.handle, &framebufferSize.width, &framebufferSize.height); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return framebufferSize; } /// This function retrieves the size, in screen coordinates, of each edge of /// the frame of the specified window. This size includes the title bar, if /// the window has one. The size of the frame may vary depending on the /// window-related hints used to create it. /// /// Because this function retrieves the size of each window frame edge and /// not the offset along a particular coordinate axis, the retrieved values /// will always be zero or positive. pub fn getFrameSize(self: Self) !glfw.Bounds { var frameSize: glfw.Bounds = undefined; c.glfwGetWindowFrameSize(self.handle, &frameSize.left, &frameSize.top, &frameSize.right, &frameSize.bottom); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return frameSize; } /// This function retrieves the content scale for the specified window. The /// content scale is the ratio between the current DPI and the platform's /// default DPI. This is especially important for text and any UI elements. /// If the pixel dimensions of your UI scaled by this look appropriate on /// your machine then it should appear at a reasonable size on other /// machines regardless of their DPI and scaling settings. This relies on /// the system DPI and scaling settings being somewhat correct. /// /// On systems where each monitors can have its own content scale, the /// window content scale will depend on which monitor the system considers /// the window to be on. pub fn getContentScale(self: Self) !glfw.Scale { var scale: glfw.Scale = undefined; c.glfwGetWindowContentScale(self.handle, &scale.x, &scale.y); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return scale; } /// This function returns the opacity of the window, including any /// decorations. /// /// The opacity (or alpha) value is a positive finite number between zero /// and one, where zero is fully transparent and one is fully opaque. If the /// system does not support whole window transparency, this function always /// returns one. pub fn getOpacity(self: Self) !f32 { var opacity = c.glfwGetWindowOpacity(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; return opacity; } /// This function sets the opacity of the window, including any decorations. /// /// The opacity (or alpha) value is a positive finite number between zero /// and one, where zero is fully transparent and one is fully opaque. /// /// The initial opacity value for newly created windows is one. /// /// A window created with framebuffer transparency may not use whole window /// transparency. The results of doing this are undefined. pub fn setOpacity(self: *Self, opacity: f32) !void { c.glfwSetWindowOpacity(self.handle, opacity); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function iconifies (minimizes) the specified window if it was /// previously restored. If the window is already iconified, this function /// does nothing. /// /// If the specified window is a full screen window, the original monitor /// resolution is restored until the window is restored. pub fn iconify(self: *Self) !void { c.glfwIconifyWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function restores the specified window if it was previously /// iconified (minimized) or maximized. If the window is already restored, /// this function does nothing. /// /// If the specified window is a full screen window, the resolution chosen /// for the window is restored on the selected monitor. pub fn restore(self: *Self) !void { c.glfwRestoreWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function maximizes the specified window if it was previously not /// maximized. If the window is already maximized, this function does /// nothing. /// /// If the specified window is a full screen window, this function does /// nothing. pub fn maximize(self: *Self) !void { c.glfwMaximizeWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function makes the specified window visible if it was previously /// hidden. If the window is already visible or is in full screen mode, this /// function does nothing. /// /// By default, windowed mode windows are focused when shown Set the /// `FocusOnShow` window hint to change this behavior for all newly created /// windows, or change the behavior for an existing window with /// `Window.setAttrib`. pub fn show(self: *Self) !void { c.glfwShowWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function hides the specified window if it was previously visible. /// If the window is already hidden or is in full screen mode, this function /// does nothing. pub fn hide(self: *Self) !void { c.glfwHideWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function brings the specified window to front and sets input focus. /// The window should already be visible and not iconified. /// /// By default, both windowed and full screen mode windows are focused when /// initially created. Set the GLFW_FOCUSED to disable this behavior. /// /// Also by default, windowed mode windows are focused when shown with /// `Window.show`. Set the `FocusOnShow` window hint to disable this /// behavior. /// /// Do not use this function to steal focus from other applications unless /// you are certain that is what the user wants. Focus stealing can be /// extremely disruptive. /// /// For a less disruptive way of getting the user's attention, see attention /// requests. pub fn focus(self: *Self) !void { c.glfwFocusWindow(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function requests user attention to the specified window. On /// platforms where this is not supported, attention is requested to the /// application as a whole. /// /// Once the user has given attention, usually by focusing the window or /// application, the system will end the request automatically. pub fn requestAttention(self: *Self) !void { c.glfwRequestWindowAttention(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function returns the handle of the monitor that the specified /// window is in full screen on. pub fn getMonitor(self: Self) !?glfw.Monitor { var handle = c.glfwGetWindowMonitor(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; if (handle) |h| { return glfw.Monitor{ .handle = h }; } else { return null; } } /// This function sets the monitor that the window uses for full screen mode /// or, if the monitor is `null`, makes it windowed mode. /// /// When setting a monitor, this function updates the width, height and /// refresh rate of the desired video mode and switches to the video mode /// closest to it. The window position is ignored when setting a monitor. /// /// When the monitor is `null`, the position and size are used to place the /// window content area. The refresh rate is ignored when no monitor is /// specified. /// /// If you only wish to update the resolution of a full screen window or the /// size of a windowed mode window, see `Window.setSize`. /// /// When a window transitions from full screen to windowed mode, this /// function restores any previous window settings such as whether it is /// decorated, floating, resizable, has size or aspect ratio limits, etc. pub fn setMonitor(self: *Self, monitor: ?glfw.Monitor, position: glfw.Position, size: glfw.Size, refreshRate: ?i32) !void { c.glfwSetWindowMonitor(self.handle, if (monitor) |m| m.handle else null, position.x, position.y, size.width, size.height, if (refreshRate) |rr| rr else c.GLFW_DONT_CARE); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError => return err, else => unreachable, }; } /// This function sets the user-defined pointer of the specified window. The /// current value is retained until the window is destroyed. The initial /// value is `null`. pub fn setUserPointer(self: *Self, comptime T: type, pointer: ?*T) !void { c.glfwSetWindowUserPointer(self.handle, if (pointer) |ptr| @ptrToInt(ptr) else null); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized => return err, else => unreachable, }; } /// This function returns the current value of the user-defined pointer of /// the specified window. The initial value is `null`. pub fn getUserPointer(self: Self, comptime T: type) !?*T { var ptr = c.glfwGetWindowUserPointer(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized => return err, else => unreachable, }; if (ptr) |pointer| { return @intToPtr(*T, pointer); } else { return null; } } /// This function swaps the front and back buffers of the specified window /// when rendering with OpenGL or OpenGL ES. If the swap interval is greater /// than zero, the GPU driver waits the specified number of screen updates /// before swapping the buffers. /// /// The specified window must have an OpenGL or OpenGL ES context. /// Specifying a window without a context will generate a `NoWindowContext` /// error. /// /// This function does not apply to Vulkan. If you are rendering with /// Vulkan, see vkQueuePresentKHR instead. pub fn swapBuffers(self: *Self) !void { c.glfwSwapBuffers(self.handle); glfw.getError() catch |err| switch (err) { glfw.Error.NotInitialized, glfw.Error.PlatformError, glfw.Error.NoWindowContext => return err, else => unreachable, }; } };
src/window.zig
const std = @import("std"); const graphics = @import("didot-graphics"); const Allocator = std.mem.Allocator; const runtime_safety = @import("builtin").mode == .Debug or @import("builtin").mode == .ReleaseSafe; pub const AssetType = enum(u8) { Mesh, Texture, Shader }; pub const AssetStream = struct { readFn: fn(data: usize, buffer: []u8) callconv(if (std.io.is_async) .Async else .Unspecified) anyerror!usize, writeFn: ?fn (data: usize, buffer: []const u8) anyerror!usize = null, seekToFn: fn (data: usize, pos: u64) anyerror!void, getPosFn: fn (data: usize) anyerror!u64, getEndPosFn: fn (data: usize) anyerror!u64, closeFn: fn (data: usize) callconv(if (std.io.is_async) .Async else .Unspecified) void, data: usize, pub fn bufferStream(constBuf: []const u8) !AssetStream { const Data = struct { buffer: []const u8, pos: usize }; const BufferAssetStream = struct { pub fn read(ptr: usize, buffer: []u8) !usize { const data = @intToPtr(*Data, ptr); const end = std.math.min(data.pos + buffer.len, data.buffer.len); const len = end - data.pos; std.mem.copy(u8, buffer, data.buffer[data.pos..end]); data.pos += len; return len; } pub fn seekTo(ptr: usize, pos: u64) !void { const data = @intToPtr(*Data, ptr); if (pos >= data.buffer.len) return error.OutOfBounds; data.pos = @intCast(usize, pos); } pub fn getPos(ptr: usize) !u64 { const data = @intToPtr(*Data, ptr); return data.pos; } pub fn getEndPos(ptr: usize) !u64 { const data = @intToPtr(*Data, ptr); return data.buffer.len; } pub fn close(ptr: usize) void { std.heap.page_allocator.destroy(@intToPtr(*Data, ptr)); } }; var data = try std.heap.page_allocator.create(Data); data.* = Data { .buffer = constBuf, .pos = 0 }; return AssetStream { .readFn = BufferAssetStream.read, .closeFn = BufferAssetStream.close, .seekToFn = BufferAssetStream.seekTo, .getPosFn = BufferAssetStream.getPos, .getEndPosFn = BufferAssetStream.getEndPos, .data = @ptrToInt(data) }; } pub fn fileStreamPath(path: []const u8) !AssetStream { return fileStream(try std.fs.cwd().openFile(path, .{ .read = true })); } pub fn fileStream(streamFile: std.fs.File) !AssetStream { const File = std.fs.File; const FileAssetStream = struct { pub fn read(ptr: usize, buffer: []u8) !usize { const file = @intToPtr(*File, ptr); return try file.read(buffer); } pub fn write(ptr: usize, buffer: []const u8) !usize { const file = @intToPtr(*File, ptr); return try file.write(buffer); } pub fn seekTo(ptr: usize, pos: u64) !void { const file = @intToPtr(*File, ptr); try file.seekTo(pos); } pub fn getPos(ptr: usize) !u64 { const file = @intToPtr(*File, ptr); return try file.getPos(); } pub fn getEndPos(ptr: usize) !u64 { const file = @intToPtr(*File, ptr); return try file.getEndPos(); } pub fn close(ptr: usize) void { const file = @intToPtr(*File, ptr); file.close(); std.heap.page_allocator.destroy(file); } }; const dupe = try std.heap.page_allocator.create(File); dupe.* = streamFile; return AssetStream { .readFn = FileAssetStream.read, .writeFn = FileAssetStream.write, .closeFn = FileAssetStream.close, .seekToFn = FileAssetStream.seekTo, .getPosFn = FileAssetStream.getPos, .getEndPosFn = FileAssetStream.getEndPos, .data = @ptrToInt(dupe) }; } pub const Reader = std.io.Reader(*AssetStream, anyerror, read); pub const Writer = std.io.Writer(*AssetStream, anyerror, write); pub const SeekableStream = std.io.SeekableStream(*AssetStream, anyerror, anyerror, seekTo, seekBy, getPos, getEndPos); pub fn read(self: *AssetStream, buffer: []u8) !usize { if (std.io.is_async) { var buf = try std.heap.page_allocator.alignedAlloc(u8, 16, @frameSize(self.readFn)); defer std.heap.page_allocator.free(buf); var result: anyerror!usize = undefined; return try await @asyncCall(buf, &result, self.readFn, .{self.data, buffer}); } else { return try self.readFn(self.data, buffer); } } pub fn seekTo(self: *AssetStream, pos: u64) !void { return try self.seekToFn(self.data, pos); } pub fn seekBy(self: *AssetStream, pos: i64) !void { return try self.seekTo(@intCast(u64, @intCast(i64, try self.getPos()) + pos)); } pub fn getPos(self: *AssetStream) !u64 { return try self.getPosFn(self.data); } pub fn getEndPos(self: *AssetStream) !u64 { return try self.getEndPosFn(self.data); } pub fn write(self: *AssetStream, buffer: []const u8) !usize { if (self.writeFn) |func| { return try func(self.data, buffer); } else { return error.Unimplemented; } } pub fn reader(self: *AssetStream) Reader { return .{ .context = self }; } pub fn writer(self: *AssetStream) Writer { return .{ .context = self }; } pub fn seekableStream(self: *AssetStream) SeekableStream { return .{ .context = self }; } pub fn deinit(self: *AssetStream) void { if (std.io.is_async) { var buf = try std.heap.page_allocator.alignedAlloc(u8, 16, @frameSize(self.closeFn)); defer std.heap.page_allocator.free(buf); var result: anyerror!void = undefined; try await @asyncCall(buf, &result, self.closeFn, .{self.data}); } else { return try self.closeFn(self.data); } } }; pub const AsssetStreamType = union(enum) { Buffer: []const u8, File: []const u8, //Http: []const u8 // TODO! }; pub const AssetHandle = struct { manager: *AssetManager, key: []const u8, pub fn getPointer(self: *const AssetHandle, allocator: Allocator) anyerror!usize { const asset = self.manager.getAsset(self.key).?; if (asset.objectPtr == 0) { std.log.scoped(.didot).debug("Load asset {s}", .{self.key}); } return try asset.getPointer(allocator); } pub fn get(self: *const AssetHandle, comptime T: type, allocator: Allocator) !*T { return @intToPtr(*T, try self.getPointer(allocator)); } }; pub const Asset = struct { /// Pointer to object objectPtr: usize = 0, /// Allocator for the asset itself and the object allocator: ?Allocator = null, /// If the function is null, the asset is already loaded and unloadable is false. /// Otherwise this method must called, objectPtr must be set to the function result /// and must have been allocated on the given Allocator (or duped if not). /// That internal behaviour is handled with the get() function loader: ?fn(allocator: Allocator, ptr: usize, stream: *AssetStream) callconv(if (std.io.is_async) .Async else .Unspecified) anyerror!usize = null, /// Optional data that can be used by the loader. loaderData: usize = 0, loaderFrameBuffer: []align(16) u8 = undefined, loaderFrameResult: anyerror!usize = undefined, loaderFrame: ?anyframe->anyerror!usize = null, objectType: AssetType, /// If true, after loading the asset, loader is not set to null /// (making it re-usable) and unload() can be called. If false, loader is /// set to null and cannot be unloaded. unloadable: bool = true, /// Used for the loader stream: AssetStream = undefined, pub fn preload(self: *Asset, allocator: Allocator) !void { if (std.io.is_async) { if (self.loader) |loader| { self.loaderFrameBuffer = try allocator.alignedAlloc(u8, 16, @frameSize(loader)); self.loaderFrame = @asyncCall(self.loaderFrameBuffer, &self.loaderFrameResult, loader, .{allocator, self.loaderData, &self.stream}); } else { return error.NoLoader; } } else { std.log.scoped(.asset).debug("preload() called althought I/O is blocking.", .{}); } } /// Allocator must be the same as the one used to create loaderData and must be the same for all calls to this function pub fn getPointer(self: *Asset, allocator: Allocator) anyerror!usize { if (self.objectPtr == 0) { if (std.io.is_async) { if (self.loaderFrame == null) { try self.preload(allocator); } self.objectPtr = try await self.loaderFrame.?; // TODO: use lock self.loaderFrame = null; allocator.free(self.loaderFrameBuffer); } else { if (self.loader) |loader| { self.objectPtr = try loader(allocator, self.loaderData, &self.stream); } else { return error.NoLoader; } } if (!self.unloadable) { // if it cannot be reloaded, we can destroy loaderData if (self.loaderData != 0) { allocator.destroy(@intToPtr(*u8, self.loaderData)); self.loaderData = 0; } //self.loader = null; } } return self.objectPtr; } /// Temporarily unload the asset until it is needed again pub fn unload(self: *Asset) void { if (self.unloadable and self.objectPtr != 0) { // todo: add unloader optional function to Asset if (self.allocator) |alloc| { alloc.destroy(@intToPtr(*u8, self.objectPtr)); } self.objectPtr = 0; } } pub fn deinit(self: *Asset) void { if (self.allocator) |alloc| { if (self.objectPtr != 0) { alloc.destroy(@intToPtr(*u8, self.objectPtr)); self.objectPtr = 0; } if (self.loaderData != 0) { alloc.destroy(@intToPtr(*u8, self.loaderData)); self.loaderData = 0; } //alloc.destroy(self); } } }; pub const AssetError = error { UnexpectedType }; const AssetMap = std.StringHashMap(Asset); const TextureAsset = @import("didot-graphics").TextureAsset; const MeshAsset = @import("didot-models").MeshAsset; const textureExtensions = [_][]const u8 {".png", ".bmp"}; const meshExtensions = [_][]const u8 {".obj"}; pub const AssetManager = struct { assets: AssetMap, allocator: Allocator, pub fn init(allocator: Allocator) AssetManager { return AssetManager { .assets = AssetMap.init(allocator), .allocator = allocator }; } fn assetFromExtension(allocator: Allocator, ext: []const u8) !?Asset { inline for (textureExtensions) |expected| { if (std.mem.eql(u8, ext, expected)) { return try TextureAsset.init2D(allocator, expected[1..]); } } inline for (meshExtensions) |expected| { if (std.mem.eql(u8, ext, expected)) { return try MeshAsset.init(allocator, expected[1..]); } } return null; } pub fn loadFromBundle(self: *AssetManager, bundle: std.fs.File, allocator: Allocator) !void { const compression = try bundle.reader().readByte(u8); comptime var compressionType = 0; inline while (compressionType < 1) : (compressionType += 1) { if (compression == compressionType) { var stream = switch (compressionType) { 0 => bundle, // no compression 1 => try std.compress.zlib.zlibStream(allocator, bundle.reader()) // zlib (deflate) compression }; const reader = stream.reader(); const entries = try reader.readIntLittle(u64); var i: u64 = 0; while (i < entries) : (i += 1) { const pathLength = try reader.readIntLittle(u32); const dataLength = try reader.readIntLittle(u32); var path = try allocator.alloc(u8, pathLength); _ = try reader.readAll(path); // read the path var data = try allocator.alloc(u8, dataLength); _ = try reader.readAll(data); var asset: ?Asset = try assetFromExtension(allocator, std.fs.path.extension(path)); if (asset) |ast| { ast.stream = try AssetStream.bufferStream(data); try self.put(path, ast); } else { std.log.warn("No corresponding asset type for bundled {s}", .{ path }); } } } } } pub fn autoLoad(self: *AssetManager, allocator: Allocator) !void { var dir = try std.fs.cwd().openDir("assets", .{ .iterate = true }); defer dir.close(); var walker = try dir.walk(allocator); defer walker.deinit(); while (try walker.next()) |entry| { if (entry.kind == .File) { var asset: ?Asset = try assetFromExtension(allocator, std.fs.path.extension(entry.basename)); if (asset) |*ast| { std.log.info("{s}", .{ entry.path }); const file = try dir.openFile(entry.path, .{}); ast.stream = try AssetStream.fileStream(file); var handle = try allocator.dupe(u8, entry.path); for (handle[0..handle.len]) |*elem| { if (elem.* == '\\') { elem.* = '/'; } } try self.put(handle, ast.*); } else { std.log.warn("No corresponding asset type for {s}", .{ entry.path }); } } } } pub fn comptimeAutoLoad(self: *AssetManager, allocator: Allocator) !void { if (false) { inline for (@typeInfo(@import("didot-assets-embed")).Struct.decls) |decl| { const value = @field(@import("didot-assets-embed"), decl.name); const ext = std.fs.path.extension(decl.name); var asset: ?Asset = null; inline for (textureExtensions) |expected| { if (std.mem.eql(u8, ext, expected)) { asset = try TextureAsset.init2D(allocator, expected[1..]); } } if (asset) |*ast| { ast.stream = try AssetStream.bufferStream(value); try self.put(decl.name, ast.*); } else { std.log.warn("No corresponding asset type for {s}", .{decl.name}); } } } } /// The returned pointer should only be temporarily used due to map resizes. pub fn getAsset(self: *AssetManager, key: []const u8) ?*Asset { if (self.assets.getEntry(key)) |entry| { // TODO: asynchronously start loading the asset return entry.value_ptr; } else { return null; } } /// Stable handle to an asset pub fn get(self: *AssetManager, key: []const u8) ?AssetHandle { if (self.assets.get(key) != null) { return AssetHandle { .manager = self, .key = key }; } else { return null; } } /// Checks whether an asset's type match the 'expected argument'. /// For performance reasons, isType always return true in ReleaseSmall and ReleaseFast modes. pub fn isType(self: *AssetManager, key: []const u8, expected: AssetType) bool { if (runtime_safety) { if (self.assets.get(key)) |asset| { return asset.objectType == expected; } else { return false; } } else { return true; } } /// Get the asset and asserts its type match the 'expected' argument. /// For performance reasons, getExpected only does the check on ReleaseSafe and Debug modes. pub fn getExpected(self: *AssetManager, key: []const u8, expected: AssetType) anyerror!?usize { if (self.assets.get(key)) |*asset| { if (runtime_safety and asset.objectType != expected) { return AssetError.UnexpectedType; } const value = try asset.getPointer(self.allocator); try self.assets.put(key, asset.*); return value; } else { return null; } } /// Retrieve an asset from the asset manager, loading it if it wasn't already. pub fn getObject(self: *AssetManager, key: []const u8) anyerror!?usize { if (self.assets.get(key)) |*asset| { const value = try asset.getPointer(self.allocator); try self.assets.put(key, asset.*); return value; } else { return null; } } /// Whether the asset manager has an asset with the following key. pub fn has(self: *AssetManager, key: []const u8) bool { return self.assets.get(key) != null; } /// Put the following asset with the following key in the asset manager. pub fn put(self: *AssetManager, key: []const u8, asset: Asset) !void { try self.assets.put(key, asset); } /// De-init all the assets in this asset manager. pub fn deinit(self: *AssetManager) void { var iterator = self.assets.valueIterator(); while (iterator.next()) |item| { item.deinit(); } self.assets.deinit(); } }; comptime { std.testing.refAllDecls(AssetManager); std.testing.refAllDecls(Asset); }
didot-objects/assets.zig
const std = @import("std"); const expect = std.testing.expect; const assert = std.debug.assert; const print = std.debug.print; ///A singly linked list pub fn SinglyList(comptime T: type) type { return struct { const Self = @This(); const Node = struct { data: T, next: ?*Node, }; pub const Iterator = struct { head: ?*Node, cursor: ?*Node, size: usize, pub fn next(it: *Iterator) ?T { if (it.cursor) |current_node| { it.advancePointer(); return current_node.data; } return null; } ///get the current element pointed to by the iterator pub fn current(it: Iterator) T { return it.cursor.?.data; } pub fn reset(it: *Iterator) void { it.cursor = it.head; } fn advancePointer(it: *Iterator) void { // self.cursor = self.cursor.?.next; it.cursor = it.cursor.?.next; } ///position returns the Node at a given index. ///The index parameter is an integer value greater than 0 .ie index >= 1 fn position(it: *Iterator, index: usize) ?*Node { //it.size + 1 to account for the end .ie null case const end = it.size + 1; assert(index > 0 and index <= end); var count: usize = 0; //index - 1 because we're are zero counting while (count < index - 1) : (count += 1) { it.advancePointer(); } if (it.cursor) |cursor| { //reset it.cursor so that next call to position() starts from cursor it.reset(); return cursor; } else { return null; } } }; head: ?*Node = null, allocator: std.mem.Allocator, size: usize = 0, ///iterator takes const Self so that it doesn't modify the actual data structure ///when changes are made to the data structure you need to call iterator again ///for a new Iterator that contains the canges made to the data structure pub fn iterator(self: Self) Iterator { return .{ .head = self.head, .cursor = self.head, .size = self.size }; } pub fn init(allocator: std.mem.Allocator) Self { return .{ .allocator = allocator }; } fn createNode(self: *Self, value: T) !*Node { var new_node = try self.allocator.create(Node); new_node.data = value; new_node.next = null; return new_node; } fn isEmpty(self: Self) bool { return if (self.head == null) true else false; } fn increaseSize(self: *Self) void { self.size += 1; } fn decreaseSize(self: *Self) void { self.size -= 1; } ///Traverse list in linear time to the end and append value pub fn append(self: *Self, value: T) !void { var new_node = try self.createNode(value); //if head alread has some nodes traverse to insert position if (self.head) |node| { var head_node = node; while (head_node.next) |next_head| : (head_node = next_head) {} else { //add new_node as the next node of the last node head_node.next = new_node; new_node.next = null; } } else { //if new_node is the first node then head points to the new_node self.head = new_node; new_node.next = null; } self.increaseSize(); } pub fn appendAfter(self: *Self, index: usize, value: T) !void { assert(!self.isEmpty()); var it = self.iterator(); var node_at_index = it.position(index).?; var new_node = try self.createNode(value); new_node.next = node_at_index.next orelse null; node_at_index.next = new_node; self.increaseSize(); } pub fn prepend(self: *Self, value: T) !void { var new_node = try self.createNode(value); if (self.head) |head| { //put new node before head new_node.next = head; //if a node goes before head ,then head has to be updated to point to the beginning of the list //let head point to new_node since new_node is at the beginning of the list self.head = new_node; } else { //when list is empty new_node.next = null; self.head = new_node; } self.increaseSize(); } pub fn prependBefore(self: *Self, index: usize, value: T) !void { assert(!self.isEmpty()); var it = self.iterator(); var node_before_index = it.position(index - 1).?; var new_node = try self.createNode(value); new_node.next = node_before_index.next; node_before_index.next = new_node; self.increaseSize(); } pub fn removeFirst(self: *Self) void { assert(!self.isEmpty()); var current_head = self.head.?; var new_head = current_head.next orelse null; self.head = new_head; self.freeNode(current_head); self.decreaseSize(); } pub fn remove(self: *Self, index: usize) void { assert(!self.isEmpty()); var it = self.iterator(); var node_before_delete_node = it.position(index - 1).?; const delete_node = node_before_delete_node.next.?; node_before_delete_node.next = delete_node.next; self.freeNode(delete_node); self.decreaseSize(); } pub fn deinit(self: *Self) void { while (self.head) |delete_head| { self.head = delete_head.next; self.allocator.destroy(delete_head); } self.head = undefined; self.size = 0; } fn freeNode(self: *Self, node: *Node) void { self.allocator.destroy(node); } }; } fn debugPrint(comptime message: []const u8, args: anytype) void { print("\n" ++ message ++ "\n", .{args}); } fn display(self: anytype) void { // const Fields = comptime std.meta.fieldNames(@TypeOf(self)); // if (!std.mem.eql(u8, Fields[0], "head")) { //and !(Fields.field_type == ?*Node) // @compileError("Display expects a head field as the second file in " ++ @typeName(@TypeOf(self)) ++ " but found " ++ Fields[0]); // } // @compileLog("declarations in self are ", @typeInfo(@TypeOf(std.meta.declarations(@TypeOf(self))[1].data))); // @compileLog("declarations in self are ", std.meta.fieldInfo(@TypeOf(self), .head).field_type); if (!@hasDecl(@TypeOf(self), "Node")) { @compileError("self must be a doubly or singly linked list with a private Node data type"); } if (!@hasField(@TypeOf(self), "head")) { @compileError("display expects a head field in " ++ @typeName(@TypeOf(self)) ++ " but found none"); } // const self_head_field_info = std.meta.fieldInfo(@TypeOf(self), .head); // if (self_head_field_info.field_type == // std.meta.fieldInfo(@TypeOf(std.meta.declarations(@TypeOf(self))[1]), .head).field_type) // { // @compileError("head field must be of type " ++ std.meta.declarations(@TypeOf(self))[1].data.Type); // } if (self.head) |node| { print("\n[ head ==> {} ", .{node.data}); var current_head = node; while (current_head.next) |next_node| : (current_head = next_node) { print("next ==> {} ", .{next_node.data}); } else { print("end ]\n", .{}); } } else { print("\nList is empty []\n", .{}); } } test "SinglyList" { var singlylist = SinglyList(u8).init(std.testing.allocator); defer singlylist.deinit(); try singlylist.append(3); try expect(singlylist.head.?.data == 3); try singlylist.append(6); try singlylist.append(9); try expect(singlylist.head.?.next.?.next.?.data == 9); try singlylist.prepend(1); try expect(singlylist.head.?.data == 1); try singlylist.prependBefore(2, 2); try expect(singlylist.head.?.next.?.data == 2); try singlylist.appendAfter(3, 4); try expect(singlylist.head.?.next.?.next.?.next.?.data == 4); singlylist.removeFirst(); try expect(singlylist.head.?.data == 2); singlylist.remove(5); try expect(singlylist.head.?.next.?.next.?.next.?.data == 6); //test iterator var it = singlylist.iterator(); // debugPrint("SinglyList{}", .{}); // while (it.next()) |node| { // debugPrint("node -> {}", .{node.data}); // } // display(singlylist); try expect(it.position(2).?.data == 3); try singlylist.prepend(0); it = singlylist.iterator(); try expect(it.position(1).?.data == 0); try expect(it.position(6) == null); } //TODO: if and when needed implement appendAfter/prependBefore/remove ///A circular singly linked list pub fn SinglyCircularList(comptime T: type) type { return struct { const Self = @This(); const Node = struct { data: T, next: *Node, }; pub const Iterator = struct { cursor: ?*Node, end: ?*Node, state: enum { stop, move } = .move, pub fn next(it: *Iterator) ?T { if (it.state == .stop or it.cursor == null) { //reset Iterator so the next call to next() works .ie begin a new iteration it.reset(); return null; } it.advanceCursor(); if (it.cursor == it.end) { //stop looping because we started at the end and have gotten there again it.stop(); return it.end.?.data; } return it.cursor.?.data; } pub fn stop(it: *Iterator) void { it.state = .stop; } ///get the current element pointed to by the iterator pub fn current(it: Iterator) T { return it.cursor.?.data; } pub fn reset(it: *Iterator) void { it.cursor = it.end; it.state = .move; } ///rotate/circulate the circular list endlessly ///call stop() if you want to stop rotating pub fn rotate(it: *Iterator) ?T { if (it.state == .stop or it.cursor == null) { //reset Iterator so the next call to rotate works it.reset(); return null; } //Since cursor starst at the end move to the head before retreiving cursor it.advanceCursor(); return it.cursor.?.data; } fn advanceCursor(it: *Iterator) void { it.cursor = it.cursor.?.next; } fn position(it: *Iterator, index: usize) ?*Node { //circular doesn't need to assert index <= end because there is no end var count: usize = 0; while (count < index) : (count += 1) { it.advanceCursor(); } if (it.cursor) |cursor| { //reset it.cursor so that next call to position() starts from cursor it.reset(); return cursor; } else { return null; } } }; allocator: std.mem.Allocator, cursor: ?*Node = null, //cursor points to the last node so that the next is the frist node ///iterator takes const Self so that it doesn't modify the actual data structure ///when changes are made to the data structure you need to call iterator again ///for a new Iterator that contains the canges made to the data structure pub fn iterator(self: Self) Iterator { return .{ .cursor = self.cursor, .end = self.cursor }; } pub fn init(allocator: std.mem.Allocator) Self { return .{ .allocator = allocator }; } pub fn isEmpty(self: Self) bool { return if (self.cursor == null) true else false; } pub fn first(self: Self) T { assert(!self.isEmpty()); return self.cursor.?.next.data; } pub fn last(self: Self) T { assert(!self.isEmpty()); return self.cursor.?.data; } pub fn advanceCursor(it: *Self) void { it.cursor = it.cursor.?.next; } pub fn prepend(self: *Self, value: T) !void { var new_node = try self.allocator.create(Node); new_node.data = value; if (self.cursor) |cursor| { var current_cursor = cursor; new_node.next = current_cursor.next; current_cursor.next = new_node; } else { //If there is no node in the list new_node.next = new_node; self.cursor = new_node; } } pub fn append(self: *Self, value: T) !void { if (self.cursor) |cursor| { var new_node = try self.allocator.create(Node); new_node.data = value; var current_node = cursor; new_node.next = current_node.next; current_node.next = new_node; //cursor should point to the last node self.cursor = new_node; } else { try self.prepend(value); } } pub fn removeFirst(self: *Self) void { var remove_node = self.cursor.?.next; if (remove_node == self.cursor) { // removing the only node so that list is empty self.cursor = null; } else { // link out the old node self.cursor.?.next = remove_node.next; } self.allocator.destroy(remove_node); } ///Empty the list of all its nodes pub fn empty(self: Self) void { var cursor = self.cursor.?; var next_node = cursor.next; while (next_node != cursor) { const current_next_node = next_node.next; self.allocator.destroy(next_node); next_node = current_next_node; } self.allocator.destroy(cursor); } pub fn display(self: *Self) void { assert(!self.isEmpty()); var itr = self.iterator(); print("\n[ first ==> ", .{}); while (itr.next()) |next_node| { print(" |{}| ", .{next_node}); } print(" <== rear ]\n", .{}); } pub fn deinit(self: Self) void { empty(self); } }; } test "SinglyCircularList" { var circularlist = SinglyCircularList(u8).init(std.testing.allocator); defer circularlist.deinit(); try circularlist.prepend(0); try circularlist.prepend(1); try circularlist.prepend(2); try expect(circularlist.first() == 2); try expect(circularlist.last() == 0); circularlist.advanceCursor(); try expect(circularlist.first() == 1); try expect(circularlist.last() == 2); circularlist.advanceCursor(); try circularlist.prepend(3); try expect(circularlist.first() == 3); try expect(circularlist.last() == 1); try circularlist.append(9); try expect(circularlist.last() == 9); //test displaying and iterating over SinglyCircularList // circularlist.display(); var it = circularlist.iterator(); try expect(it.position(2).?.data == 0); try expect(it.position(4).?.data == 1); // var count: usize = 0; // while (it.rotate()) |node| : (count += 1) { // debugPrint("node {}", .{node.data}); // if (count == 10) break; // } } pub fn List(comptime T: type) type { return struct { const Self = @This(); const Node = struct { data: T, next: ?*Node, previous: ?*Node, }; head: ?*Node = null, tail: ?*Node = null, size: usize = 0, allocator: std.mem.Allocator, pub fn init(allocator: std.mem.Allocator) Self { return .{ .allocator = allocator }; } fn createNode(self: *const Self, value: T) !*Node { var new_node = try self.allocator.create(Node); new_node.data = value; new_node.next = null; new_node.previous = null; return new_node; } fn traverseToEnd(current_head: *Node) *Node { var head = current_head; while (current_head.next) |next_head| : (head = next_head) {} return head; } pub fn append(self: *Self, value: T) !void { var new_node = try self.createNode(value); if (self.tail) |tail_node| { new_node.previous = tail_node; new_node.next = null; tail_node.next = new_node; } else { self.head = new_node; } self.tail = new_node; self.size += 1; } fn traverseTo(current_head: *Node, value: T) !*Node { var head = current_head; while (head.next) |next_head| : (head = next_head) { const node_with_value = next_head; if (node_with_value.data == value) { return node_with_value; } } else { return error.NoNodeWithSpecifiedValue; } } pub fn appendAfter(self: *Self, after: T, value: T) !void { if (self.head) |node| { if (node.data == after) { var current_head = node; var new_node = try self.createNode(value); new_node.next = current_head.next; new_node.previous = current_head; current_head.next = new_node; return; } //if after is not the first node var node_with_value = try traverseTo(node, after); //if node_with_value next isn't the tail or end if (node_with_value.next) |node_after_node_with_value| { var new_node = try self.createNode(value); new_node.next = node_after_node_with_value; new_node.previous = node_with_value; node_after_node_with_value.previous = new_node; node_with_value.next = new_node; } else { try self.append(value); } } } fn isEmpty(self: Self) bool { return if (self.head == null) true else false; } pub fn prepend(self: *Self, value: T) !void { if (self.head) |node| { var new_node = try self.createNode(value); new_node.next = node; node.previous = new_node; self.head = new_node; self.size += 1; } else { try self.append(value); } } pub fn prependBefore(self: *Self, before: T, value: T) !void { assert(!self.isEmpty()); const node = self.head.?; if (node.data == before) { try self.prepend(value); } var node_with_value = try traverseTo(node, before); var new_node = try self.createNode(value); new_node.next = node_with_value; new_node.previous = node_with_value.previous; node_with_value.previous.?.next = new_node; node_with_value.previous = new_node; } pub fn find(self: *Self, value: T) ?*Node { if (self.head) |node| { return traverseTo(node, value) catch null; } return null; } pub fn removeFirst(self: *Self) void { assert(!self.isEmpty()); var current_head = self.head.?; if (current_head.next) |next_head| { var new_head = next_head; new_head.previous = null; self.head = new_head; } else { //if after removing the current_head there are no more nodes self.head = null; self.tail = null; } self.freeNode(current_head); } pub fn removeLast(self: *Self) void { var current_tail = self.tail.?; var new_tail = current_tail.previous; current_tail.previous.?.next = null; self.tail = new_tail; self.freeNode(current_tail); } pub fn remove(self: *Self, value: T) !void { assert(!self.isEmpty()); const node = self.head.?; const remove_node = try traverseTo(node, value); var node_to_remove = remove_node; node_to_remove.previous.?.next = remove_node.next; node_to_remove.next.?.previous = remove_node.previous; self.freeNode(remove_node); } fn freeNode(self: *Self, memory: anytype) void { self.allocator.destroy(memory); } pub fn deinit(self: *Self) void { while (self.tail) |node| { self.tail = node.previous; self.allocator.destroy(node); } self.head = undefined; self.tail = undefined; } }; } test "List" { var list = List(u8).init(std.testing.allocator); defer list.deinit(); try list.append(2); try list.append(4); try expect(list.head.?.data == 2); try expect(list.tail.?.data == 4); try expect(list.size == 2); try list.prepend(1); try expect(list.head.?.data == 1); try expect(list.tail.?.data == 4 and list.size == 3); try list.prependBefore(4, 3); try expect(list.head.?.next.?.next.?.data == 3); try list.appendAfter(4, 5); try expect(list.head.?.next.?.next.?.next.?.next.?.data == 5); try list.append(6); try expect(list.tail.?.data == 6); const found_data = list.find(3); try expect(found_data.?.data == 3); list.removeFirst(); try expect(list.head.?.data == 2); list.removeLast(); try expect(list.tail.?.data == 5); try list.remove(4); const find_4 = list.find(4); try expect(find_4 == null); try list.prepend(1); try expect(list.head.?.data == 1); try expect(list.tail.?.data == 5); }
src/linked_list.zig
const std = @import( "std" ); const Mutex = std.Thread.Mutex; const ArrayList = std.ArrayList; const Allocator = std.mem.Allocator; usingnamespace @import( "../core/core.zig" ); usingnamespace @import( "../core/glz.zig" ); usingnamespace @import( "../time/cursor.zig" ); usingnamespace @import( "../sim.zig" ); pub fn DotsPaintable( comptime N: usize, comptime P: usize ) type { return struct { const Self = @This(); axes: [2]*const Axis, tCursor: *const VerticalCursor, size_LPX: f64, rgba: [4]GLfloat, pendingFramesMutex: Mutex, pendingFrames: ArrayList( *DotsFrame(P) ), frames: ArrayList( *DotsFrame(P) ), allocator: *Allocator, prog: DotsProgram, vao: GLuint, painter: Painter, simListener: SimListener(N,P) = SimListener(N,P) { .handleFrameFn = handleFrame, }, pub fn init( name: []const u8, axes: [2]*const Axis, tCursor: *const VerticalCursor, allocator: *Allocator ) Self { return Self { .axes = axes, .tCursor = tCursor, .size_LPX = 15, .rgba = [4]GLfloat { 1.0, 0.0, 0.0, 1.0 }, .pendingFramesMutex = Mutex {}, .pendingFrames = ArrayList( *DotsFrame(P) ).init( allocator ), .frames = ArrayList( *DotsFrame(P) ).init( allocator ), .allocator = allocator, .prog = undefined, .vao = 0, .painter = Painter { .name = name, .glInitFn = glInit, .glPaintFn = glPaint, .glDeinitFn = glDeinit, }, }; } /// Called on simulator thread fn handleFrame( simListener: *SimListener(N,P), simFrame: *const SimFrame(N,P) ) !void { const self = @fieldParentPtr( Self, "simListener", simListener ); var frame = try self.allocator.create( DotsFrame(P) ); frame.t = simFrame.t; // TODO: Check that N >= 2 var p = @as( usize, 0 ); while ( p < P ) : ( p += 1 ) { frame.xs[ p*2 + 0 ] = @floatCast( GLfloat, simFrame.xs[ p*N + 0 ] ); frame.xs[ p*2 + 1 ] = @floatCast( GLfloat, simFrame.xs[ p*N + 1 ] ); } { const held = self.pendingFramesMutex.acquire( ); defer held.release( ); try self.pendingFrames.append( frame ); } } fn glInit( painter: *Painter, pc: *const PainterContext ) !void { const self = @fieldParentPtr( Self, "painter", painter ); self.prog = try DotsProgram.glCreate( ); glGenVertexArrays( 1, &self.vao ); glBindVertexArray( self.vao ); if ( self.prog.inCoords >= 0 ) { const inCoords = @intCast( GLuint, self.prog.inCoords ); glEnableVertexAttribArray( inCoords ); glVertexAttribPointer( inCoords, 2, GL_FLOAT, GL_FALSE, 0, null ); } } fn glPaint( painter: *Painter, pc: *const PainterContext ) !void { const self = @fieldParentPtr( Self, "painter", painter ); { const held = self.pendingFramesMutex.acquire( ); defer held.release( ); for ( self.pendingFrames.items ) |frame| { const frameIndex = findFrameIndexAfter( self.frames.items, frame.t ); try self.frames.insert( frameIndex, frame ); } self.pendingFrames.items.len = 0; } if ( P > 0 ) { const frameIndexAfter = findFrameIndexAfter( self.frames.items, self.tCursor.cursor ); if ( frameIndexAfter >= 1 ) { const frameIndexAtOrBefore = frameIndexAfter - 1; var frame = self.frames.items[ frameIndexAtOrBefore ]; const size_PX = @floatCast( f32, self.size_LPX * pc.lpxToPx ); const bounds = axisBounds( 2, self.axes ); glzEnablePremultipliedAlphaBlending( ); glEnable( GL_VERTEX_PROGRAM_POINT_SIZE ); glUseProgram( self.prog.program ); glzUniformInterval2( self.prog.XY_BOUNDS, bounds ); glUniform1f( self.prog.SIZE_PX, size_PX ); glUniform4fv( self.prog.RGBA, 1, &self.rgba ); glBindVertexArray( self.vao ); if ( self.prog.inCoords >= 0 ) { // TODO: What's the point of a VAO if we have to do this every time? // TODO: Maybe separate VAO for each frame? const inCoords = @intCast( GLuint, self.prog.inCoords ); glBindBuffer( GL_ARRAY_BUFFER, frame.glBuffer( ) ); glEnableVertexAttribArray( inCoords ); glVertexAttribPointer( inCoords, 2, GL_FLOAT, GL_FALSE, 0, null ); } glDrawArrays( GL_POINTS, 0, P ); } } } fn findFrameIndexAfter( frames: []const *DotsFrame(P), t: f64 ) usize { var lo = @as( usize, 0 ); var hi = frames.len; while ( lo < hi ) { const mid = @divTrunc( lo + hi, 2 ); if ( frames[ mid ].t > t ) { hi = mid; } else { lo = mid + 1; } } return hi; } fn glDeinit( painter: *Painter ) void { const self = @fieldParentPtr( Self, "painter", painter ); glDeleteProgram( self.prog.program ); glDeleteVertexArrays( 1, &self.vao ); { const held = self.pendingFramesMutex.acquire( ); defer held.release( ); for ( self.pendingFrames.items ) |frame| { frame.glDeinit( ); } } for ( self.frames.items ) |frame| { frame.glDeinit( ); } } pub fn deinit( self: *Self ) void { { const held = self.pendingFramesMutex.acquire( ); defer held.release( ); for ( self.pendingFrames.items ) |frame| { self.allocator.destroy( frame ); } self.pendingFrames.deinit( ); } for ( self.frames.items ) |frame| { self.allocator.destroy( frame ); } self.frames.deinit( ); } }; } fn DotsFrame( comptime P: usize ) type { return struct { const Self = @This(); t: f64, xs: [2*P]GLfloat, _glBuffer: GLuint = 0, _glValid: bool = false, pub fn glBuffer( self: *Self ) GLuint { // FIXME: No idea why "if valid else" works but "if !valid" doesn't if ( self._glValid ) { } else { glGenBuffers( 1, &self._glBuffer ); glBindBuffer( GL_ARRAY_BUFFER, self._glBuffer ); glzBufferData( GL_ARRAY_BUFFER, GLfloat, &self.xs, GL_STATIC_DRAW ); self._glValid = true; } return self._glBuffer; } pub fn glDeinit( self: *Self ) void { if ( self._glValid ) { glDeleteBuffers( 1, &self._glBuffer ); self._glBuffer = 0; self._glValid = false; } } }; } const DotsProgram = struct { program: GLuint, XY_BOUNDS: GLint, SIZE_PX: GLint, RGBA: GLint, /// x_XAXIS, y_YAXIS inCoords: GLint, pub fn glCreate( ) !DotsProgram { const vertSource = \\#version 150 core \\ \\vec2 start2D( vec4 interval2D ) \\{ \\ return interval2D.xy; \\} \\ \\vec2 span2D( vec4 interval2D ) \\{ \\ return interval2D.zw; \\} \\ \\vec2 coordsToNdc2D( vec2 coords, vec4 bounds ) \\{ \\ vec2 frac = ( coords - start2D( bounds ) ) / span2D( bounds ); \\ return ( -1.0 + 2.0*frac ); \\} \\ \\uniform vec4 XY_BOUNDS; \\uniform float SIZE_PX; \\ \\// x_XAXIS, y_YAXIS \\in vec2 inCoords; \\ \\void main( void ) { \\ vec2 xy_XYAXIS = inCoords.xy; \\ gl_Position = vec4( coordsToNdc2D( xy_XYAXIS, XY_BOUNDS ), 0.0, 1.0 ); \\ gl_PointSize = SIZE_PX; \\} ; const fragSource = \\#version 150 core \\precision lowp float; \\ \\const float FEATHER_PX = 0.9; \\ \\uniform float SIZE_PX; \\uniform vec4 RGBA; \\ \\out vec4 outRgba; \\ \\void main( void ) { \\ vec2 xy_NPC = -1.0 + 2.0*gl_PointCoord; \\ float r_NPC = sqrt( dot( xy_NPC, xy_NPC ) ); \\ \\ float pxToNpc = 2.0 / SIZE_PX; \\ float rOuter_NPC = 1.0 - 0.5*pxToNpc; \\ float rInner_NPC = rOuter_NPC - FEATHER_PX*pxToNpc; \\ float mask = smoothstep( rOuter_NPC, rInner_NPC, r_NPC ); \\ \\ float alpha = mask * RGBA.a; \\ outRgba = vec4( alpha*RGBA.rgb, alpha ); \\} ; const program = try glzCreateProgram( vertSource, fragSource ); return DotsProgram { .program = program, .XY_BOUNDS = glGetUniformLocation( program, "XY_BOUNDS" ), .SIZE_PX = glGetUniformLocation( program, "SIZE_PX" ), .RGBA = glGetUniformLocation( program, "RGBA" ), .inCoords = glGetAttribLocation( program, "inCoords" ), }; } };
src/space/dots.zig
const std = @import("std"); const panic = std.debug.panic; const utils = @import("lib/utils.zig"); const print = utils.print; const puts = utils.puts; const print_e = utils.print_e; const puts_e = utils.puts_e; const putskv_e = utils.putskv_e; const puts_fn = utils.puts_fn; const strEq = utils.strEq; const allocator = std.heap.page_allocator; const types = @import("lib/types.zig"); const List = types.List; const Node = types.Node; const json = @import("lib/json.zig"); // -------------------------------- const TokenKind = enum { KW, SYM, INT, STR, IDENT, }; const Token = struct { kind: TokenKind, _str: [64]u8, const Self = @This(); fn create(kind: TokenKind, str: []const u8) !*Self { var obj = try allocator.create(Self); obj.kind = kind; utils.strcpy(&obj._str, str); return obj; } fn kindEq(self: *Self, kind: TokenKind) bool { return self.kind == kind; } pub fn getStr(self: *Self) []const u8 { const len = utils.strlen(&self._str); return self._str[0..len]; } fn strEq(self: *Self, str: []const u8) bool { return utils.strEq(self.getStr(), str); } fn is(self: *Self, kind: TokenKind, str: []const u8) bool { return self.kindEq(kind) and self.strEq(str); } }; // -------------------------------- const NUM_TOKEN_MAX = 1024; var tokens: [NUM_TOKEN_MAX]*Token = undefined; var numTokens: usize = 0; var pos: usize = 0; // -------------------------------- fn strToTokenKind(kind_str: []const u8) TokenKind { if (strEq(kind_str, "kw")) { return TokenKind.KW; } else if (strEq(kind_str, "sym")) { return TokenKind.SYM; } else if (strEq(kind_str, "int")) { return TokenKind.INT; } else if (strEq(kind_str, "str")) { return TokenKind.STR; } else if (strEq(kind_str, "ident")) { return TokenKind.IDENT; } else { panic("must not happen ({})", .{kind_str}); } } fn addToken(line: []const u8, ti: usize) !void { const sep_i = utils.indexOf(line[0..], ':', 1); if (sep_i == -1) { panic("Must contain colon as a separator", .{}); } var kind_str: [8]u8 = undefined; var str: [64]u8 = undefined; utils.substring(&kind_str, line[0..], 0, @intCast(usize, sep_i)); utils.substring(&str, line[0..], @intCast(usize, sep_i) + 1, line.len); const kind = strToTokenKind(utils.strTrim(&kind_str)); const t: *Token = try Token.create(kind, str[0..]); tokens[ti] = t; } fn getLineSize(rest: []const u8) usize { const i = utils.indexOf(rest, '\n', 0); if (0 <= i) { return @intCast(usize, i) + 1; } else { return rest.len; } } fn readTokens(src: []const u8) !void { puts_fn("readTokens"); var src_pos: usize = 0; var ti: usize = 0; while (src_pos < src.len) { const rest = src[src_pos..]; const line_size = getLineSize(rest); var line: [256]u8 = undefined; if (rest[line_size - 1] == '\n') { utils.substring(&line, rest, 0, line_size - 1); } else { utils.substring(&line, rest, 0, line_size); } try addToken(line[0..], ti); ti += 1; src_pos += line_size; } numTokens = ti; } // -------------------------------- fn isEnd() bool { return numTokens <= pos; } fn peek(offset: usize) *Token { return tokens[pos + offset]; } fn assertToken(kind: TokenKind, str: []const u8) void { const t = peek(0); if (!t.kindEq(kind)) { panic("Unexpected kind ({})", .{t}); } if (!t.strEq(str)) { panic("Unexpected str ({}) ({})", .{ str, t }); } } fn consumeKw(str: []const u8) void { assertToken(TokenKind.KW, str); pos += 1; } fn consumeSym(str: []const u8) void { assertToken(TokenKind.SYM, str); pos += 1; } fn newlist() *List { return List.init(); } // -------------------------------- fn parseArg() *Node { puts_fn("parseArg"); const t = peek(0); switch (t.kind) { .INT => { pos += 1; const n = utils.parseInt(t.getStr()); return Node.initInt(n); }, .IDENT => { pos += 1; return Node.initStr(t.getStr()); }, else => { panic("unexpected token ({})", .{t}); }, } } fn parseArgsFirst() ?*Node { // puts_fn("parseArgsFirst"); const t = peek(0); if (t.is(TokenKind.SYM, ")")) { return null; } return parseArg(); } fn parseArgsRest() ?*Node { // puts_fn("parseArgsRest"); const t = peek(0); if (t.is(TokenKind.SYM, ")")) { return null; } consumeSym(","); return parseArg(); } fn parseArgs() *List { puts_fn("parseArgs"); const args = newlist(); const firstArgOpt = parseArgsFirst(); if (firstArgOpt) |firstArg| { args.add(firstArg); } else { return args; } while (true) { const restArgOpt = parseArgsRest(); if (restArgOpt) |restArg| { args.add(restArg); } else { break; } } return args; } fn parseFunc() *List { puts_fn("parseFunc"); consumeKw("func"); const fn_name = peek(0).getStr(); pos += 1; consumeSym("("); const args = parseArgs(); consumeSym(")"); consumeSym("{"); const stmts = newlist(); while (true) { const t = peek(0); if (t.strEq("}")) { break; } if (t.strEq("var")) { stmts.addList(parseVar()); } else { stmts.addList(parseStmt()); } } consumeSym("}"); const func = newlist(); func.addStr("func"); func.addStr(fn_name); func.addList(args); func.addList(stmts); return func; } fn parseVarDeclare() *List { puts_fn("parseVarDeclare"); const t = peek(0); pos += 1; const var_name = t.getStr(); consumeSym(";"); const stmt = newlist(); stmt.addStr("var"); stmt.addStr(var_name); return stmt; } fn parseVarInit() *List { const t = peek(0); pos += 1; const var_name = t.getStr(); consumeSym("="); const expr = parseExpr(); consumeSym(";"); const stmt = newlist(); stmt.addStr("var"); stmt.addStr(var_name); stmt.add(expr); return stmt; } fn parseVar() *List { puts_fn("parseVar"); consumeKw("var"); const t = peek(1); if (t.is(TokenKind.SYM, ";")) { return parseVarDeclare(); } else { return parseVarInit(); } } fn parseExprRight(exprL: *Node) *Node { puts_fn("parseExprRight"); const t = peek(0); if (t.is(TokenKind.SYM, ";") or t.is(TokenKind.SYM, ")")) { return exprL; } const exprEls = newlist(); if (t.is(TokenKind.SYM, "+")) { consumeSym("+"); const exprR = parseExpr(); exprEls.addStr("+"); exprEls.add(exprL); exprEls.add(exprR); } else if (t.is(TokenKind.SYM, "*")) { consumeSym("*"); const exprR = parseExpr(); exprEls.addStr("*"); exprEls.add(exprL); exprEls.add(exprR); } else if (t.is(TokenKind.SYM, "==")) { consumeSym("=="); const exprR = parseExpr(); exprEls.addStr("eq"); exprEls.add(exprL); exprEls.add(exprR); } else if (t.is(TokenKind.SYM, "!=")) { consumeSym("!="); const exprR = parseExpr(); exprEls.addStr("neq"); exprEls.add(exprL); exprEls.add(exprR); } else { putskv_e("t", t); panic("not_yet_impl", .{}); } return Node.initList(exprEls); } fn parseExpr() *Node { puts_fn("parseExpr"); const tl: *Token = peek(0); if (tl.is(TokenKind.SYM, "(")) { consumeSym("("); const exprL = parseExpr(); consumeSym(")"); return parseExprRight(exprL); } switch (tl.kind) { .INT => { pos += 1; const n = utils.parseInt(tl.getStr()); const exprL = Node.initInt(n); return parseExprRight(exprL); }, .IDENT => { pos += 1; const exprL = Node.initStr(tl.getStr()); return parseExprRight(exprL); }, else => { panic("not_yet_impl", .{}); }, } } fn parseSet() *List { puts_fn("parseSet"); consumeKw("set"); const t = peek(0); pos += 1; const var_name = t.getStr(); consumeSym("="); const expr = parseExpr(); consumeSym(";"); const stmt = newlist(); stmt.addStr("set"); stmt.addStr(var_name); stmt.add(expr); return stmt; } fn parseFuncall() *List { puts_fn("parseFuncall"); const t = peek(0); pos += 1; const fn_name = t.getStr(); consumeSym("("); const args = parseArgs(); consumeSym(")"); const list = newlist(); list.addStr(fn_name); list.addListAll(args); return list; } fn parseCall() *List { puts_fn("parseCall"); consumeKw("call"); const funcall = parseFuncall(); consumeSym(";"); const ret = newlist(); ret.addStr("call"); ret.addListAll(funcall); return ret; } fn parseCallSet() *List { puts_fn("parseCallSet"); consumeKw("call_set"); const t = peek(0); pos += 1; const var_name = t.getStr(); consumeSym("="); const funcall = parseFuncall(); consumeSym(";"); const stmt = newlist(); stmt.addStr("call_set"); stmt.addStr(var_name); stmt.addList(funcall); return stmt; } fn parseReturn() *List { puts_fn("parseReturn"); consumeKw("return"); const expr = parseExpr(); consumeSym(";"); const stmt = newlist(); stmt.addStr("return"); stmt.add(expr); return stmt; } fn parseWhile() *List { puts_fn("parseWhile"); consumeKw("while"); consumeSym("("); const expr = parseExpr(); consumeSym(")"); consumeSym("{"); const stmts = parseStmts(); consumeSym("}"); const stmt = newlist(); stmt.addStr("while"); stmt.add(expr); stmt.addList(stmts); return stmt; } fn parseWhenClause() *List { // puts_fn("parseWhenClause") const t = peek(0); if (t.is(TokenKind.SYM, "}")) { return List.empty(); } consumeSym("("); const expr = parseExpr(); consumeSym(")"); consumeSym("{"); const stmts = parseStmts(); consumeSym("}"); const list = newlist(); list.add(expr); var i: usize = 0; while (i < stmts.len) : (i += 1) { const stmt = stmts.get(i).getList(); list.addList(stmt); } return list; } fn parseCase() *List { puts_fn("parseCase"); consumeKw("case"); consumeSym("{"); const whenClauses = newlist(); while (true) { const whenClause = parseWhenClause(); if (whenClause.len == 0) { break; } whenClauses.addList(whenClause); } consumeSym("}"); const stmt = newlist(); stmt.addStr("case"); var i: usize = 0; while (i < whenClauses.len) : (i += 1) { const whenClause = whenClauses.get(i).getList(); stmt.addList(whenClause); } return stmt; } fn parseVmComment() *List { puts_fn("parseVmComment"); consumeKw("_cmt"); consumeSym("("); const t = peek(0); pos += 1; const cmt = t.getStr(); consumeSym(")"); consumeSym(";"); const ret = newlist(); ret.addStr("_cmt"); ret.addStr(cmt); return ret; } fn parseStmt() *List { puts_fn("parseStmt"); const t = peek(0); if (t.is(TokenKind.SYM, "}")) { return List.empty(); } if (t.strEq("set")) { return parseSet(); } else if (t.strEq("call")) { return parseCall(); } else if (t.strEq("call_set")) { return parseCallSet(); } else if (t.strEq("return")) { return parseReturn(); } else if (t.strEq("while")) { return parseWhile(); } else if (t.strEq("case")) { return parseCase(); } else if (t.strEq("_cmt")) { return parseVmComment(); } else { putskv_e("pos", pos); putskv_e("t", t); panic("Unexpected token", .{}); } } fn parseStmts() *List { const stmts = newlist(); while (!isEnd()) { const stmt = parseStmt(); if (stmt.len == 0) { break; } stmts.addList(stmt); } return stmts; } fn parseTopStmt() *List { puts_fn("parseTopStmt"); const t = tokens[pos]; if (strEq(t.getStr(), "func")) { return parseFunc(); } else { panic("Unexpected tokens: pos({}) kind({}) str({})", .{ pos, t.kind, t.getStr() }); } } fn parseTopStmts() *List { puts_fn("parseTopStmts"); const top_stmts = newlist(); top_stmts.addStr("top_stmts"); while (!isEnd()) { top_stmts.addList(parseTopStmt()); } return top_stmts; } pub fn main() !void { var buf: [20000]u8 = undefined; const src = utils.readStdinAll(&buf); try readTokens(src); const top_stmts = parseTopStmts(); json.printAsJson(top_stmts); }
vgparser.zig
const std = @import("std"); const daemon = @import("daemon.zig"); const fs = std.fs; const os = std.os; const mem = std.mem; const Logger = @import("logger.zig").Logger; const helpers = @import("helpers.zig"); const ProcessStats = @import("process_stats.zig").ProcessStats; const util = @import("util.zig"); const prettyMemoryUsage = util.prettyMemoryUsage; pub const Context = struct { allocator: *std.mem.Allocator, args_it: std.process.ArgIterator, tries: usize = 0, pub fn init(allocator: *std.mem.Allocator, args_it: std.process.ArgIterator) Context { return Context{ .allocator = allocator, .args_it = args_it, }; } pub fn checkDaemon(self: *Context) anyerror!std.fs.File { if (self.tries >= 3) return error.SpawnFail; self.tries += 1; const sock_path = try helpers.getPathFor(self.allocator, .Sock); std.debug.warn("connecting to socket ({})...\n", .{sock_path}); return std.net.connectUnixSocket(sock_path) catch |err| { std.debug.warn("failed (error: {}), starting and retrying (try {})...", .{ err, self.tries }); try self.spawnDaemon(); // assuming spawning doesn't take more than a second std.time.sleep(1 * std.time.ns_per_s); return try self.checkDaemon(); }; } fn spawnDaemon(self: @This()) !void { std.debug.warn("Spawning tsusu daemon...\n", .{}); const data_dir = try helpers.fetchDataDir(self.allocator); std.fs.cwd().makePath(data_dir) catch |err| { if (err != error.PathAlreadyExists) return err; }; var pid = try std.os.fork(); if (pid < 0) { return error.ForkFail; } if (pid > 0) { return; } _ = umask(0); const daemon_pid = os.linux.getpid(); const pidpath = try helpers.getPathFor(self.allocator, .Pid); const logpath = try helpers.getPathFor(self.allocator, .Log); var pidfile = try std.fs.cwd().createFile(pidpath, .{ .truncate = false }); try pidfile.seekFromEnd(0); var stream = pidfile.outStream(); try stream.print("{}", .{daemon_pid}); pidfile.close(); var logfile = try std.fs.cwd().createFile(logpath, .{ .truncate = false, }); var logstream = logfile.outStream(); var logger = Logger(std.fs.File.OutStream).init(logstream, "[d]"); _ = try setsid(); try std.os.chdir("/"); std.os.close(std.os.STDIN_FILENO); std.os.close(std.os.STDOUT_FILENO); std.os.close(std.os.STDERR_FILENO); // redirect stdout and stderr to logfile std.os.dup2(logfile.handle, std.os.STDOUT_FILENO) catch |err| { logger.info("Failed to dup2 stdout to logfile: {}", .{err}); }; std.os.dup2(logfile.handle, std.os.STDERR_FILENO) catch |err| { logger.info("Failed to dup2 stderr to logfile: {}", .{err}); }; // TODO: better way to express that we want to delete pidpath // on any scenario. since we exit() at the end, no defer blocks // actually run daemon.main(&logger) catch |daemon_err| { std.os.unlink(pidpath) catch |err| {}; // do nothing on errors logfile.close(); return daemon_err; }; std.os.unlink(pidpath) catch |err| {}; // do nothing on errors logfile.close(); std.os.exit(0); } }; // TODO upstream mode_t to linux bits x86_64 const mode_t = u32; fn umask(mode: mode_t) mode_t { const rc = os.system.syscall1(os.system.SYS.umask, @bitCast(usize, @as(isize, mode))); return @intCast(mode_t, rc); } fn setsid() !std.os.pid_t { const rc = os.system.syscall0(os.system.SYS.setsid); switch (std.os.errno(rc)) { 0 => return @intCast(std.os.pid_t, rc), std.os.EPERM => return error.PermissionFail, else => |err| return std.os.unexpectedErrno(err), } } pub const Mode = enum { Destroy, Start, Stop, Help, List, Noop, Logs, }; fn getMode(mode_arg: []const u8) !Mode { if (std.mem.eql(u8, mode_arg, "noop")) return .Noop; if (std.mem.eql(u8, mode_arg, "destroy") or std.mem.eql(u8, mode_arg, "delete")) return .Destroy; if (std.mem.eql(u8, mode_arg, "start")) return .Start; if (std.mem.eql(u8, mode_arg, "stop")) return .Stop; if (std.mem.eql(u8, mode_arg, "help")) return .Help; if (std.mem.eql(u8, mode_arg, "list")) return .List; if (std.mem.eql(u8, mode_arg, "logs")) return .Logs; return error.UnknownMode; } pub fn printServices(msg: []const u8) !void { std.debug.warn("name | state\t\tpid\tcpu\tmemory\n", .{}); var it = std.mem.split(msg, ";"); while (it.next()) |service_line| { if (service_line.len == 0) break; var serv_it = std.mem.split(service_line, ","); const name = serv_it.next().?; const state_str = serv_it.next().?; const state = try std.fmt.parseInt(u8, state_str, 10); std.debug.warn("{} | ", .{name}); std.debug.warn("'{}'\n", .{service_line}); switch (state) { 0 => std.debug.warn("not running\t\t0\t0%\t0kb", .{}), 1 => { const pid = try std.fmt.parseInt(std.os.pid_t, serv_it.next().?, 10); // we can calculate cpu and ram usage since the service // is currently running var proc_stats = ProcessStats.init(); const stats = try proc_stats.fetchAllStats(pid); var buffer: [128]u8 = undefined; const pretty_memory_usage = try prettyMemoryUsage(&buffer, stats.memory_usage); std.debug.warn("running\t\t{}\t{d:.1}%\t{}", .{ pid, stats.cpu_usage, pretty_memory_usage }); }, 2 => { const exit_code = try std.fmt.parseInt(u32, serv_it.next().?, 10); std.debug.warn("exited (code {})\t\t0%\t0kb", .{exit_code}); }, 3 => { const exit_code = try std.fmt.parseInt(u32, serv_it.next().?, 10); const remaining_ns = try std.fmt.parseInt(i64, serv_it.next().?, 10); std.debug.warn("restarting (code {}, comes in {}ms)\t\t0%\t0kb", .{ exit_code, @divTrunc(remaining_ns, std.time.ns_per_ms), }); }, else => unreachable, } std.debug.warn("\n", .{}); } } fn stopCommand(ctx: *Context, in_stream: anytype, out_stream: anytype) !void { const name = try (ctx.args_it.next(ctx.allocator) orelse @panic("expected name")); std.debug.warn("stopping '{}'\n", .{name}); try out_stream.print("stop;{}!", .{name}); const list_msg = try in_stream.readUntilDelimiterAlloc(ctx.allocator, '!', 1024); defer ctx.allocator.free(list_msg); try printServices(list_msg); } fn watchCommand(ctx: *Context, in_stream: anytype, out_stream: anytype) !void { const name = try (ctx.args_it.next(ctx.allocator) orelse @panic("expected name")); std.debug.warn("watching '{}'\n", .{name}); try out_stream.print("logs;{}!", .{name}); while (true) { const msg = try in_stream.readUntilDelimiterAlloc(ctx.allocator, '!', 65535); defer ctx.allocator.free(msg); // TODO handle when service is stopped var it = std.mem.split(msg, ";"); _ = it.next(); const service = it.next().?; const stream = it.next().?; const data = it.next().?; std.debug.warn("{} from {}: {}", .{ service, stream, data }); } } pub fn main() anyerror!void { // every time we start, we check if we have a daemon running. var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; var args_it = std.process.args(); _ = args_it.skip(); const mode_arg = try (args_it.next(allocator) orelse @panic("expected mode")); const mode = try getMode(mode_arg); // switch for things that don't depend on an existing daemon switch (mode) { .Destroy => { // TODO use sock first (send STOP command), THEN, if it fails, TERM const pidpath = try helpers.getPathFor(allocator, .Pid); //const sockpath = try helpers.getPathFor(allocator, .Sock); var pidfile = std.fs.cwd().openFile(pidpath, .{}) catch |err| { std.debug.warn("Failed to open PID file ({}). is the daemon running?\n", .{err}); return; }; var stream = pidfile.inStream(); const pid_str = try stream.readAllAlloc(allocator, 20); defer allocator.free(pid_str); const pid_int = std.fmt.parseInt(os.pid_t, pid_str, 10) catch |err| { std.debug.warn("Failed to parse pid '{}': {}\n", .{ pid_str, err }); return; }; try std.os.kill(pid_int, std.os.SIGINT); std.debug.warn("sent SIGINT to pid {}\n", .{pid_int}); return; }, else => {}, } var ctx = Context.init(allocator, args_it); const sock = try ctx.checkDaemon(); defer sock.close(); var in_stream = sock.inStream(); var out_stream = sock.outStream(); std.debug.warn("[c] sock fd to server: {}\n", .{sock.handle}); const helo_msg = try in_stream.readUntilDelimiterAlloc(ctx.allocator, '!', 6); if (!std.mem.eql(u8, helo_msg, "helo")) { std.debug.warn("invalid helo, expected helo, got {}\n", .{helo_msg}); return error.InvalidHello; } std.debug.warn("[c]first msg (should be helo): {} '{}'\n", .{ helo_msg.len, helo_msg }); var buf = try ctx.allocator.alloc(u8, 1024); switch (mode) { .Noop => {}, .List => { _ = try sock.write("list!"); const msg = try in_stream.readUntilDelimiterAlloc(ctx.allocator, '!', 1024); defer ctx.allocator.free(msg); if (msg.len == 0) { std.debug.warn("<no services>\n", .{}); return; } try printServices(msg); }, .Start => { try out_stream.print("start;{}", .{ try (ctx.args_it.next(allocator) orelse @panic("expected name")), }); const path = ctx.args_it.next(allocator); if (path != null) { try out_stream.print(";{}", .{try path.?}); } try out_stream.print("!", .{}); const msg = try in_stream.readUntilDelimiterAlloc(ctx.allocator, '!', 1024); defer ctx.allocator.free(msg); try printServices(msg); }, .Stop => try stopCommand(&ctx, in_stream, out_stream), .Logs => try watchCommand(&ctx, in_stream, out_stream), else => std.debug.warn("TODO implement mode {}\n", .{mode}), } }
src/main.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const synchsafe = @import("synchsafe.zig"); const latin1 = @import("latin1.zig"); const fmtUtf8SliceEscapeUpper = @import("util.zig").fmtUtf8SliceEscapeUpper; const unsynch = @import("unsynch.zig"); const _metadata = @import("metadata.zig"); const AllID3v2Metadata = _metadata.AllID3v2Metadata; const ID3v2Metadata = _metadata.ID3v2Metadata; pub const id3v2_identifier = "ID3"; pub const id3v2_footer_identifier = "3DI"; pub const ID3Header = struct { major_version: u8, revision_num: u8, flags: u8, /// Includes the size of the extended header, the padding, and the frames /// after unsynchronization. Does not include the header or the footer (if /// present). size: synchsafe.DecodedType(u32), pub const len: usize = 10; pub fn read(reader: anytype) !ID3Header { return readWithIdentifier(reader, id3v2_identifier); } pub fn readFooter(reader: anytype) !ID3Header { return readWithIdentifier(reader, id3v2_footer_identifier); } fn readWithIdentifier(reader: anytype, comptime identifier: []const u8) !ID3Header { assert(identifier.len == 3); const header = try reader.readBytesNoEof(ID3Header.len); if (!std.mem.eql(u8, header[0..3], identifier)) { return error.InvalidIdentifier; } const synchsafe_size = std.mem.readIntSliceBig(u32, header[6..10]); return ID3Header{ .major_version = header[3], .revision_num = header[4], .flags = header[5], .size = synchsafe.decode(u32, synchsafe_size), }; } pub fn compressed(self: *const ID3Header) bool { return self.major_version <= 2 and self.flags & (1 << 6) != 0; } pub fn hasExtendedHeader(self: *const ID3Header) bool { return self.major_version >= 3 and self.flags & (1 << 6) != 0; } pub fn hasFooter(self: *const ID3Header) bool { return self.major_version >= 4 and self.flags & (1 << 4) != 0; } pub fn experimental(self: *const ID3Header) bool { return self.major_version >= 3 and self.flags & (1 << 5) != 0; } pub fn unsynchronised(self: *const ID3Header) bool { return self.flags & (1 << 7) != 0; } }; pub const FrameHeader = struct { id: [4]u8, size: u32, raw_size: u32, status_flags: u8, format_flags: u8, pub fn len(major_version: u8) usize { return switch (major_version) { 0...2 => 6, else => 10, }; } pub fn read(reader: anytype, major_version: u8) !FrameHeader { switch (major_version) { 0...2 => { const header = try reader.readBytesNoEof(6); var size = std.mem.readIntSliceBig(u24, header[3..6]); return FrameHeader{ .id = [_]u8{ header[0], header[1], header[2], '\x00' }, .size = size, .raw_size = size, .status_flags = 0, .format_flags = 0, }; }, else => { const header = try reader.readBytesNoEof(10); const raw_size = std.mem.readIntSliceBig(u32, header[4..8]); const size = if (major_version >= 4) synchsafe.decode(u32, raw_size) else raw_size; return FrameHeader{ .id = [_]u8{ header[0], header[1], header[2], header[3] }, .size = size, .raw_size = raw_size, .status_flags = header[8], .format_flags = header[9], }; }, } } pub fn idSlice(self: *const FrameHeader, major_version: u8) []const u8 { return switch (major_version) { 0...2 => self.id[0..3], else => self.id[0..], }; } pub fn validate(self: *const FrameHeader, major_version: u8, max_size: usize) !void { // TODO: ffmpeg doesn't have this check--it allows 0 sized frames to be read //const invalid_length_min: usize = if (self.has_data_length_indicator()) 4 else 0; //if (self.size <= invalid_length_min) return error.FrameTooShort; if (self.size > max_size) return error.FrameTooLong; for (self.idSlice(major_version)) |c, i| switch (c) { 'A'...'Z', '0'...'9' => {}, else => { // This is a hack to allow for v2.2 (3 char) ids to be read in v2.3 tags // which are apparently from an iTunes encoding bug. // TODO: document that frame ids might be nul teriminated in this case // or come up with a less hacky solution const is_id3v2_2_id_in_v2_3_frame = major_version == 3 and i == 3 and c == '\x00'; if (!is_id3v2_2_id_in_v2_3_frame) { return error.InvalidFrameID; } }, }; } /// Returns true if all values are zero, which is indicative that /// the frame header is part of padding after the tag. pub fn couldBePadding(self: *const FrameHeader) bool { if (!std.mem.eql(u8, &self.id, &[_]u8{ 0, 0, 0, 0 })) return false; if (self.raw_size != 0) return false; if (self.status_flags != 0) return false; if (self.format_flags != 0) return false; return true; } pub fn unsynchronised(self: *const FrameHeader) bool { return self.format_flags & @as(u8, 1 << 1) != 0; } pub fn hasDataLengthIndicator(self: *const FrameHeader) bool { return self.format_flags & @as(u8, 1) != 0; } pub fn skipData(self: FrameHeader, unsynch_capable_reader: anytype, seekable_stream: anytype, full_unsynch: bool) !void { if (full_unsynch) { // if the tag is full unsynch, then we need to skip while reading try unsynch_capable_reader.skipBytes(self.size, .{}); } else { // if the tag is not full unsynch, then we can just skip without reading try seekable_stream.seekBy(self.size); } } pub fn skipDataFromPos(self: FrameHeader, start_pos: usize, unsynch_capable_reader: anytype, seekable_stream: anytype, full_unsynch: bool) !void { try seekable_stream.seekTo(start_pos); return self.skipData(unsynch_capable_reader, seekable_stream, full_unsynch); } }; pub const TextEncoding = enum(u8) { iso_8859_1 = 0, utf16_with_bom = 1, utf16_no_bom = 2, utf8 = 3, pub fn fromByte(byte: u8) error{InvalidTextEncodingByte}!TextEncoding { return std.meta.intToEnum(TextEncoding, byte) catch error.InvalidTextEncodingByte; } pub fn charSize(encoding: TextEncoding) u8 { return switch (encoding) { .iso_8859_1, .utf8 => 1, .utf16_with_bom, .utf16_no_bom => 2, }; } }; pub const EncodedTextIterator = struct { text_bytes: []u8, index: ?usize, encoding: TextEncoding, raw_text_data: []const u8, /// Buffer for UTF-8 data when converting from UTF-16 /// TODO: Is this actually useful performance-wise? utf8_buf: []u8, allocator: Allocator, const Self = @This(); const u16_align = @alignOf(u16); pub const Options = struct { encoding: TextEncoding, text_data_size: usize, frame_is_unsynch: bool, }; pub fn init(allocator: Allocator, reader: anytype, options: Options) !Self { // always align to u16 just so that UTF-16 data is easy to work with // but alignCast it back to u8 so that it's also easy to work with non-UTF-16 data var raw_text_data = @alignCast(1, try allocator.allocWithOptions(u8, options.text_data_size, u16_align, null)); errdefer allocator.free(raw_text_data); try reader.readNoEof(raw_text_data); var text_bytes = raw_text_data; if (options.frame_is_unsynch) { // This is safe since unsynch decoding is guaranteed to // never shift the beginning of the slice, so the alignment // can't change text_bytes = unsynch.decodeInPlace(text_bytes); } if (options.encoding.charSize() == 2) { if (text_bytes.len % 2 != 0) { // there could be an erroneous trailing single char nul-terminator // or garbage. if so, just ignore it and pretend it doesn't exist text_bytes.len -= 1; } } // If the text is latin1, then convert it to UTF-8 if (options.encoding == .iso_8859_1) { var utf8_text = try latin1.latin1ToUtf8Alloc(allocator, text_bytes); // the utf8 data is now the raw_text_data allocator.free(raw_text_data); raw_text_data = utf8_text; text_bytes = utf8_text; } const utf8_buf = switch (options.encoding.charSize()) { 1 => &[_]u8{}, // In the worst case, a single UTF-16 u16 can take up 3 bytes when // converted to UTF-8 (e.g. 0xFFFF as UTF-16 is 0xEF 0xBF 0xBF as UTF-8) // UTF-16 len * 3 should therefore be large enough to always store any // conversion. 2 => try allocator.alloc(u8, text_bytes.len / 2 * 3), else => unreachable, }; errdefer allocator.free(utf8_buf); return Self{ .allocator = allocator, .text_bytes = text_bytes, .encoding = options.encoding, .index = 0, .utf8_buf = utf8_buf, .raw_text_data = raw_text_data, }; } pub fn deinit(self: *Self) void { self.allocator.free(self.raw_text_data); self.allocator.free(self.utf8_buf); } pub const TerminatorType = enum { optional, required, }; pub fn next(self: *Self, terminator: TerminatorType) error{ InvalidUTF16BOM, InvalidUTF16Data }!?[]const u8 { // The idea here is that we want to handle lists of null-terminated // values but also potentially malformed single values, i.e. // a zero length text with no null-termination const start = self.index orelse return null; const end: usize = end: { switch (self.encoding.charSize()) { 1 => { const delimiter: u8 = 0; if (std.mem.indexOfScalarPos(u8, self.text_bytes, start, delimiter)) |delim_start| { self.index = delim_start + 1; while (self.index.? < self.text_bytes.len and self.text_bytes[self.index.?] == delimiter) { self.index.? += 1; } break :end delim_start; } }, 2 => { var bytes_as_utf16 = @alignCast(u16_align, std.mem.bytesAsSlice(u16, self.text_bytes)); const delimiter: u16 = 0; if (std.mem.indexOfScalarPos(u16, bytes_as_utf16, start / 2, delimiter)) |delim_start| { self.index = index: { var index_past_all_delimeters = delim_start + 1; while (index_past_all_delimeters < bytes_as_utf16.len and bytes_as_utf16[index_past_all_delimeters] == delimiter) { index_past_all_delimeters += 1; } break :index index_past_all_delimeters * 2; }; break :end delim_start * 2; } }, else => unreachable, } const is_first_value_or_more_to_read = start == 0 or start < self.text_bytes.len; if (terminator == .optional or is_first_value_or_more_to_read) { self.index = null; break :end self.text_bytes.len; } else { // if a terminator is required and we're not at the start, // then the lack of a null-terminator should return null immediately // since there's no value to be read, i.e. "a\x00" should not give // "a" and then "" return null; } }; const utf8_val = try self.nextToUtf8(self.text_bytes[start..end]); return utf8_val; } /// Always returns UTF-8. /// When converting from UTF-16, the returned data is temporary /// and will be overwritten on subsequent calls to `next`. fn nextToUtf8(self: Self, val_bytes: []u8) error{ InvalidUTF16BOM, InvalidUTF16Data }![]const u8 { if (self.encoding.charSize() == 2) { var bytes_as_utf16 = @alignCast(u16_align, std.mem.bytesAsSlice(u16, val_bytes)); var val_no_bom = bytes_as_utf16; if (self.encoding == .utf16_with_bom) { // If it's zero-length and missing the BOM then that's // ok, there seem to be some encoders that encode empty // COMM descriptions this way. It's against what the spec // says, but oh well. if (bytes_as_utf16.len == 0) { return val_bytes[0..0]; } // if this is big endian, then swap everything to little endian // TODO: I feel like this probably won't handle big endian native architectures correctly if (bytes_as_utf16[0] == 0xFFFE) { for (bytes_as_utf16) |c, i| { bytes_as_utf16[i] = @byteSwap(u16, c); } } // check for byte order mark and skip it if (bytes_as_utf16[0] != 0xFEFF) { return error.InvalidUTF16BOM; } val_no_bom = bytes_as_utf16[1..]; } const utf8_end = std.unicode.utf16leToUtf8(self.utf8_buf, val_no_bom) catch return error.InvalidUTF16Data; return self.utf8_buf[0..utf8_end]; } return val_bytes; } }; pub fn skip(reader: anytype, seekable_stream: anytype) !void { const header = ID3Header.read(reader) catch { try seekable_stream.seekTo(0); return; }; return seekable_stream.seekBy(header.size); } pub const TextFrame = struct { size_remaining: usize, encoding: TextEncoding, }; pub fn readTextFrameCommon(unsynch_capable_reader: anytype, frame_header: *FrameHeader) !TextFrame { var text_data_size = frame_header.size; if (frame_header.hasDataLengthIndicator()) { if (text_data_size < 4) { return error.UnexpectedTextDataEnd; } //const frame_data_length_raw = try unsynch_capable_reader.readIntBig(u32); //const frame_data_length = synchsafe.decode(u32, frame_data_length_raw); try unsynch_capable_reader.skipBytes(4, .{}); text_data_size -= 4; } if (text_data_size == 0) { return error.UnexpectedTextDataEnd; } const encoding_byte = try unsynch_capable_reader.readByte(); const encoding = try TextEncoding.fromByte(encoding_byte); text_data_size -= 1; return TextFrame{ .size_remaining = text_data_size, .encoding = encoding, }; } /// On error, seekable_stream cursor position will be wherever the error happened, it is /// up to the caller to determine what to do from there pub fn readFrame(allocator: Allocator, unsynch_capable_reader: anytype, seekable_stream: anytype, metadata_id3v2_container: *ID3v2Metadata, frame_header: *FrameHeader, remaining_tag_size: usize, full_unsynch: bool) !void { _ = allocator; const id3_major_version = metadata_id3v2_container.header.major_version; var metadata = &metadata_id3v2_container.metadata; var metadata_map = &metadata.map; var user_defined_map = &metadata_id3v2_container.user_defined; var comments_map = &metadata_id3v2_container.comments; var unsynchronized_lyrics_map = &metadata_id3v2_container.unsynchronized_lyrics; // this is technically not valid AFAIK but ffmpeg seems to accept // it without failing the parse, so just skip it // TODO: zero sized T-type frames? would ffprobe output that? if (frame_header.size == 0) { return error.ZeroSizeFrame; } // sometimes v2.4 encoders don't use synchsafe integers for their frame sizes // so we need to double check if (id3_major_version >= 4) { const cur_pos = try seekable_stream.getPos(); frame_header.size = best_guess_size: { const was_raw_size_synchsafe = synchsafe.areIntBytesSynchsafe(u32, frame_header.raw_size); // If the raw integer's bytes weren't even synchsafe to begin with, // then we can assume that the raw integer is going to be more correct // than the synchsafe decoded version. if (!was_raw_size_synchsafe) { break :best_guess_size frame_header.raw_size; } // The synchsafe decoded integer will always be equal to or smaller // than the raw version, so if we hit EOF or padding, then we can assume // that the raw version won't give us anything better, and therefore we // should use the synchsafe decoded version. const after_frame_synchsafe = cur_pos + frame_header.size; seekable_stream.seekTo(after_frame_synchsafe) catch { break :best_guess_size frame_header.size; }; const next_frame_header_synchsafe = FrameHeader.read(unsynch_capable_reader, id3_major_version) catch { break :best_guess_size frame_header.size; }; // If the synchsafe decoded version gives us a valid header // or a header that could be part of padding, then we should definitely // use the synchsafe version. if (next_frame_header_synchsafe.validate(id3_major_version, remaining_tag_size)) { break :best_guess_size frame_header.size; } else |_| {} if (next_frame_header_synchsafe.couldBePadding()) { break :best_guess_size frame_header.size; } // At this point, we know that the synchsafe-decoded version will not // give us a valid header afterwards, so we can assume that the raw size // is at least worth trying. We need to check that the raw size // won't give EOF while reading the frame, though, since we don't // want to invoke a false-positive EOF. // // TODO: This needs to be thought through more. 'Trying' the raw size // could lead to larger reads than necessary when the raw size doesn't // lead to EOF. It's an edge case of an edge case, but there's probably // something better that can be done about it. const after_frame_u32 = cur_pos + frame_header.raw_size; seekable_stream.seekTo(after_frame_u32) catch { break :best_guess_size frame_header.size; }; break :best_guess_size frame_header.raw_size; }; try seekable_stream.seekTo(cur_pos); } // Treat as NUL terminated because some v2.3 tags will (erroneously) use v2.2 IDs // with a NUL as the 4th char, and we should handle those as NUL terminated const id = std.mem.sliceTo(frame_header.idSlice(id3_major_version), '\x00'); // TODO: I think it's possible for a ID3v2.4 frame that has the unsynch flag set // to need more comprehensive decoding to ensure that we always read the full // frame correctly. Right now we do the unsynch decoding in the EncodedTextIterator // which means for COMM/USLT frames we don't decode the language characters. // This isn't a huge problem since any language string that needs decoding // will be invalid, but it might be best to handle that edge case anyway. if (frame_header.id[0] == 'T') { const text_frame = try readTextFrameCommon(unsynch_capable_reader, frame_header); const is_user_defined = std.mem.eql(u8, id, if (id.len == 3) "TXX" else "TXXX"); // we can handle this as a special case if (text_frame.size_remaining == 0) { // if this is a user-defined frame, then there's no way it's valid, // since there has to be a nul terminator between the name and the value if (is_user_defined) { return error.InvalidUserDefinedTextFrame; } return metadata_map.put(id, ""); } const max_size_remaining = (try seekable_stream.getEndPos()) - (try seekable_stream.getPos()); if (text_frame.size_remaining > max_size_remaining) { return error.EndOfStream; } if (is_user_defined) { var text_iterator = try EncodedTextIterator.init(allocator, unsynch_capable_reader, .{ .text_data_size = text_frame.size_remaining, .encoding = text_frame.encoding, .frame_is_unsynch = frame_header.unsynchronised(), }); defer text_iterator.deinit(); const field = (try text_iterator.next(.required)) orelse return error.UnexpectedTextDataEnd; const entry = try user_defined_map.getOrPutEntry(field); const value = (try text_iterator.next(.optional)) orelse return error.UnexpectedTextDataEnd; try user_defined_map.appendToEntry(entry, value); // The spec somewhat explicitly says that the following should not happen, // but TagLib does not follow it and I think it makes some sense to // not entirely drop the information if there are TXXX frames that // have values that are encoded as a null-terminated list (a la other // text identification frames) // // Here's the relevant portions of the spec: // - ID3v2.2 (https://id3.org/id3v2-00): // > If the textstring is followed by a termination ($00 (00)) all // > the following information should be ignored and not be displayed. // - ID3v2.3 (https://id3.org/id3v2.3.0#Text_information_frames) // > If the textstring is followed by a termination ($00 (00)) all // > the following information should be ignored and not be displayed. // - ID3v2.4 (https://id3.org/id3v2.4.0-frames) // > 4.2.6. User defined text information frame // > This frame is intended for one-string text information // // TODO: Should this actually be here? while (try text_iterator.next(.required)) |text| { try user_defined_map.appendToEntry(entry, text); } } else { // From section 4.2 of https://id3.org/id3v2.4.0-frames: // > All text information frames supports multiple strings, // > stored as a null separated list, where null is reperesented // > by the termination code for the charater encoding. // // This technically only applies to 2.4, but we do it unconditionally // to accomidate buggy encoders that encode 2.3 as if it were 2.4. // TODO: Is this behavior for 2.3 and 2.2 okay? var text_iterator = try EncodedTextIterator.init(allocator, unsynch_capable_reader, .{ .text_data_size = text_frame.size_remaining, .encoding = text_frame.encoding, .frame_is_unsynch = frame_header.unsynchronised(), }); defer text_iterator.deinit(); const entry = try metadata_map.getOrPutEntry(id); while (try text_iterator.next(.required)) |text| { try metadata_map.appendToEntry(entry, text); } } } else if (std.mem.eql(u8, id, if (id.len == 3) "ULT" else "USLT")) { var text_frame = try readTextFrameCommon(unsynch_capable_reader, frame_header); if (text_frame.size_remaining < 3) { return error.UnexpectedTextDataEnd; } const language = try unsynch_capable_reader.readBytesNoEof(3); text_frame.size_remaining -= 3; const max_size_remaining = (try seekable_stream.getEndPos()) - (try seekable_stream.getPos()); if (text_frame.size_remaining > max_size_remaining) { return error.EndOfStream; } var text_iterator = try EncodedTextIterator.init(allocator, unsynch_capable_reader, .{ .text_data_size = text_frame.size_remaining, .encoding = text_frame.encoding, .frame_is_unsynch = frame_header.unsynchronised(), }); defer text_iterator.deinit(); const description = (try text_iterator.next(.required)) orelse return error.UnexpectedTextDataEnd; const entries = try unsynchronized_lyrics_map.getOrPutIndexesEntries(&language, description); const value = (try text_iterator.next(.optional)) orelse return error.UnexpectedTextDataEnd; try unsynchronized_lyrics_map.appendToEntries(entries, value); } else if (std.mem.eql(u8, id, if (id.len == 3) "COM" else "COMM")) { var text_frame = try readTextFrameCommon(unsynch_capable_reader, frame_header); if (text_frame.size_remaining < 3) { return error.UnexpectedTextDataEnd; } const language = try unsynch_capable_reader.readBytesNoEof(3); text_frame.size_remaining -= 3; const max_size_remaining = (try seekable_stream.getEndPos()) - (try seekable_stream.getPos()); if (text_frame.size_remaining > max_size_remaining) { return error.EndOfStream; } var text_iterator = try EncodedTextIterator.init(allocator, unsynch_capable_reader, .{ .text_data_size = text_frame.size_remaining, .encoding = text_frame.encoding, .frame_is_unsynch = frame_header.unsynchronised(), }); defer text_iterator.deinit(); const description = (try text_iterator.next(.required)) orelse return error.UnexpectedTextDataEnd; const entries = try comments_map.getOrPutIndexesEntries(&language, description); const value = (try text_iterator.next(.optional)) orelse return error.UnexpectedTextDataEnd; try comments_map.appendToEntries(entries, value); } else { try frame_header.skipData(unsynch_capable_reader, seekable_stream, full_unsynch); } } pub fn read(allocator: Allocator, reader: anytype, seekable_stream: anytype) !ID3v2Metadata { const start_offset = try seekable_stream.getPos(); const id3_header = try ID3Header.read(reader); const footer_size = if (id3_header.hasFooter()) ID3Header.len else 0; const end_offset = start_offset + ID3Header.len + id3_header.size + footer_size; if (end_offset > try seekable_stream.getEndPos()) { return error.EndOfStream; } var metadata_id3v2_container = ID3v2Metadata.init(allocator, id3_header, start_offset, end_offset); errdefer metadata_id3v2_container.deinit(); var metadata = &metadata_id3v2_container.metadata; // ID3v2.2 compression should just be skipped according to the spec if (id3_header.compressed()) { try seekable_stream.seekTo(end_offset); return metadata_id3v2_container; } // Unsynchronisation is weird. As I understand it: // // For ID3v2.3: // - Either *all* of a tag has been unsynched or none of it has (the tag header // itself has an 'unsynch' flag) // - The full tag size is the final size (after unsynchronization), but all data // within the tag is set *before* synchronization, so that means all // extra bytes added by unsynchronization must be skipped during decoding // + The spec is fairly unclear about the order of operations here, but this // seems to be the case for all of the unsynch 2.3 files in my collection // - Frame sizes are not written as synchsafe integers, so the size itself must // be decoded and extra bytes must be ignored while reading it // This means that for ID3v2.3, unsynch tags should discard all extra bytes while // reading the tag (i.e. if a frame size is 4, you should read *at least* 4 bytes, // skipping over any extra bytes added by unsynchronization; the decoded size // will match the given frame size) // // For ID3v2.4: // - Frame headers use synchsafe integers and therefore the frame headers // are guaranteed to be synchsafe. // - ID3v2.4 doesn't have a tag-wide 'unsynch' flag and instead frames have // an 'unsynch' flag. // - ID3v2.4 spec states: 'size descriptor [contains] the size of // the data in the final frame, after encryption, compression and // unsynchronisation' // This means that for ID3v2.4, unsynch frames should be read using the given size // and then decoded (i.e. if size is 4, you should read 4 bytes and then decode them; // the decoded size could end up being smaller) const tag_unsynch = id3_header.unsynchronised(); const should_read_and_then_decode = id3_header.major_version >= 4; const should_read_unsynch = tag_unsynch and !should_read_and_then_decode; var unsynch_reader = unsynch.unsynchCapableReader(should_read_unsynch, reader); var unsynch_capable_reader = unsynch_reader.reader(); // Slightly hacky solution for trailing garbage/padding bytes at the end of the tag. Instead of // trying to read a tag that we know is invalid (since frame size has to be > 0 // excluding the header), we can stop reading once there's not enough space left for // a valid tag to be read. const tag_end_with_enough_space_for_valid_frame: usize = metadata.end_offset - FrameHeader.len(id3_header.major_version); // Skip past extended header if it exists if (id3_header.hasExtendedHeader()) { const extended_header_size: u32 = try unsynch_capable_reader.readIntBig(u32); // In ID3v2.4, extended header size is a synchsafe integer and includes the size bytes // in its reported size. In earlier versions, it is not synchsafe and excludes the size bytes. const remaining_extended_header_size = remaining: { if (id3_header.major_version >= 4) { const synchsafe_extended_header_size = synchsafe.decode(u32, extended_header_size); if (synchsafe_extended_header_size < 4) { return error.InvalidExtendedHeaderSize; } break :remaining synchsafe_extended_header_size - 4; } break :remaining extended_header_size; }; if ((try seekable_stream.getPos()) + remaining_extended_header_size > tag_end_with_enough_space_for_valid_frame) { return error.InvalidExtendedHeaderSize; } try seekable_stream.seekBy(remaining_extended_header_size); } var cur_pos = try seekable_stream.getPos(); while (cur_pos < tag_end_with_enough_space_for_valid_frame) : (cur_pos = try seekable_stream.getPos()) { var frame_header = try FrameHeader.read(unsynch_capable_reader, id3_header.major_version); var frame_data_start_pos = try seekable_stream.getPos(); // It's possible for full unsynch tags to advance the position more than // the frame header length since the header itself is decoded while it's // read. If we read such that `frame_data_start_pos > metadata.end_offset`, // then treat it as 0 remaining size. var remaining_tag_size = std.math.sub(usize, metadata.end_offset, frame_data_start_pos) catch 0; // validate frame_header and bail out if its too crazy frame_header.validate(id3_header.major_version, remaining_tag_size) catch { try seekable_stream.seekTo(metadata.end_offset); break; }; readFrame(allocator, unsynch_capable_reader, seekable_stream, &metadata_id3v2_container, &frame_header, remaining_tag_size, unsynch_reader.unsynch) catch |e| switch (e) { // Errors within the frame can be recovered from by skipping the frame error.InvalidTextEncodingByte, error.ZeroSizeFrame, error.InvalidUTF16BOM, error.UnexpectedTextDataEnd, error.InvalidUserDefinedTextFrame, error.InvalidUTF16Data, => { // This is a bit weird, but go back to the start of the frame and then // skip forward. This ensures that we correctly skip the frame in all // circumstances (partially read, full unsynch, etc) try frame_header.skipDataFromPos(frame_data_start_pos, unsynch_capable_reader, seekable_stream, unsynch_reader.unsynch); continue; }, else => |err| return err, }; } if (id3_header.hasFooter()) { _ = try ID3Header.readFooter(reader); } return metadata_id3v2_container; } /// Expects the seekable_stream position to be at the end of the footer that is being read. pub fn readFromFooter(allocator: Allocator, reader: anytype, seekable_stream: anytype) !ID3v2Metadata { var end_pos = try seekable_stream.getPos(); if (end_pos < ID3Header.len) { return error.EndOfStream; } try seekable_stream.seekBy(-@intCast(i64, ID3Header.len)); const footer = try ID3Header.readFooter(reader); // header len + size + footer len const full_tag_size = ID3Header.len + footer.size + ID3Header.len; if (end_pos < full_tag_size) { return error.EndOfStream; } const start_of_header = end_pos - full_tag_size; try seekable_stream.seekTo(start_of_header); return read(allocator, reader, seekable_stream); } /// Untested, probably no real reason to keep around /// TODO: probably remove pub fn readAll(allocator: Allocator, reader: anytype, seekable_stream: anytype) !AllID3v2Metadata { var metadata_buf = std.ArrayList(ID3v2Metadata).init(allocator); errdefer { for (metadata_buf.items) |*meta| { meta.deinit(); } metadata_buf.deinit(); } var is_duplicate_tag = false; while (true) : (is_duplicate_tag = true) { var id3v2_meta = read(allocator, reader, seekable_stream) catch |e| switch (e) { error.EndOfStream, error.InvalidIdentifier => |err| { if (is_duplicate_tag) { break; } else { return err; } }, else => |err| return err, }; errdefer id3v2_meta.deinit(); try metadata_buf.append(id3v2_meta); } return AllID3v2Metadata{ .allocator = allocator, .tags = metadata_buf.toOwnedSlice(), }; } fn testTextIterator(comptime encoding: TextEncoding, input: []const u8, expected_strings: []const []const u8) !void { var fbs = std.io.fixedBufferStream(input); var text_iterator = try EncodedTextIterator.init(std.testing.allocator, fbs.reader(), .{ .text_data_size = input.len, .encoding = encoding, .frame_is_unsynch = false, }); defer text_iterator.deinit(); var num_texts: usize = 0; while (try text_iterator.next(.required)) |text| { if (num_texts >= expected_strings.len) { std.debug.print("Unexpected value past the expected values: '{s}'\n", .{fmtUtf8SliceEscapeUpper(text)}); return error.TooManyValues; } const expected_string = expected_strings[num_texts]; try std.testing.expectEqualStrings(expected_string, text); num_texts += 1; } try std.testing.expectEqual(expected_strings.len, num_texts); } test "UTF-8 EncodedTextIterator null terminated lists" { try testTextIterator(.utf8, "", &[_][]const u8{""}); try testTextIterator(.utf8, "\x00", &[_][]const u8{""}); try testTextIterator(.utf8, "hello", &[_][]const u8{"hello"}); try testTextIterator(.utf8, "hello\x00", &[_][]const u8{"hello"}); // empty values past the first are ignored try testTextIterator(.utf8, "hello\x00\x00", &[_][]const u8{"hello"}); // but non-empty ones are not try testTextIterator(.utf8, "hello\x00world\x00", &[_][]const u8{ "hello", "world" }); // TODO: Re-evaluate the test cases below, I'm not sure what the best // thing to do is for this sort of thing try testTextIterator(.utf8, "hello\x00world", &[_][]const u8{ "hello", "world" }); try testTextIterator(.utf8, "\x00world", &[_][]const u8{ "", "world" }); } test "UTF-16 EncodedTextIterator null terminated lists" { try testTextIterator(.utf16_with_bom, &[_]u8{ '\xFF', '\xFE', '\x00', '\x00' }, &[_][]const u8{""}); try testTextIterator(.utf16_with_bom, &[_]u8{ '\xFF', '\xFE' }, &[_][]const u8{""}); try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("\x00")), &[_][]const u8{""}); try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("hello")), &[_][]const u8{"hello"}); try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("hello\x00")), &[_][]const u8{"hello"}); try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("hello\x00\x00")), &[_][]const u8{"hello"}); try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("hello\x00world\x00")), &[_][]const u8{ "hello", "world" }); // TODO: Re-evaluate the test cases below, I'm not sure what the best // thing to do is for this sort of thing try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("hello\x00world")), &[_][]const u8{ "hello", "world" }); try testTextIterator(.utf16_no_bom, std.mem.sliceAsBytes(std.unicode.utf8ToUtf16LeStringLiteral("\x00world")), &[_][]const u8{ "", "world" }); // Allow missing BOM if the string is zero-length try testTextIterator(.utf16_with_bom, &[_]u8{ '\x00', '\x00' }, &[_][]const u8{""}); }
src/id3v2.zig
const std = @import("std"); const c = @import("internal/c.zig"); const internal = @import("internal/internal.zig"); const log = std.log.scoped(.git); const git = @import("git.zig"); pub const PackBuilder = opaque { pub fn deinit(self: *PackBuilder) void { log.debug("PackBuilder.deinit called", .{}); c.git_packbuilder_free(@ptrCast(*c.git_packbuilder, self)); log.debug("PackBuilder freed successfully", .{}); } /// Set number of threads to spawn /// /// By default, libgit2 won't spawn any threads at all; when set to 0, libgit2 will autodetect the number of CPUs. pub fn setThreads(self: *PackBuilder, n: c_uint) c_uint { log.debug("PackBuilder.setThreads called, n: {}", .{n}); const ret = c.git_packbuilder_set_threads( @ptrCast(*c.git_packbuilder, self), n, ); log.debug("set number of threads to: {}", .{ret}); return ret; } /// Get the total number of objects the packbuilder will write out pub fn objectCount(self: *PackBuilder) usize { log.debug("PackBuilder.objectCount called", .{}); const ret = c.git_packbuilder_object_count(@ptrCast(*c.git_packbuilder, self)); log.debug("number of objects: {}", .{ret}); return ret; } /// Get the number of objects the packbuilder has already written out pub fn writtenCount(self: *PackBuilder) usize { log.debug("PackBuilder.writtenCount called", .{}); const ret = c.git_packbuilder_written(@ptrCast(*c.git_packbuilder, self)); log.debug("number of written objects: {}", .{ret}); return ret; } /// Insert a single object /// /// For an optimal pack it's mandatory to insert objects in recency order, commits followed by trees and blobs. pub fn insert(self: *PackBuilder, id: *const git.Oid, name: [:0]const u8) !void { // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.hex_buffer_size]u8 = undefined; const slice = try id.formatHex(&buf); log.debug("PackBuilder.insert called, id: {s}, name: {s}", .{ slice, name, }); } try internal.wrapCall("git_packbuilder_insert", .{ @ptrCast(*c.git_packbuilder, self), @ptrCast(*const c.git_oid, id), name.ptr, }); log.debug("successfully inserted object", .{}); } /// Recursively insert an object and its referenced objects /// /// Insert the object as well as any object it references. pub fn insertRecursive(self: *PackBuilder, id: *const git.Oid, name: [:0]const u8) !void { // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.hex_buffer_size]u8 = undefined; const slice = try id.formatHex(&buf); log.debug("PackBuilder.insertRecursive called, id: {s}, name: {s}", .{ slice, name, }); } try internal.wrapCall("git_packbuilder_insert_recur", .{ @ptrCast(*c.git_packbuilder, self), @ptrCast(*const c.git_oid, id), name.ptr, }); log.debug("successfully inserted object", .{}); } /// Insert a root tree object /// /// This will add the tree as well as all referenced trees and blobs. pub fn insertTree(self: *PackBuilder, id: *const git.Oid) !void { // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.hex_buffer_size]u8 = undefined; const slice = try id.formatHex(&buf); log.debug("PackBuilder.insertTree called, id: {s}", .{ slice, }); } try internal.wrapCall("git_packbuilder_insert_tree", .{ @ptrCast(*c.git_packbuilder, self), @ptrCast(*const c.git_oid, id), }); log.debug("successfully inserted root tree", .{}); } /// Insert a commit object /// /// This will add a commit as well as the completed referenced tree. pub fn insertCommit(self: *PackBuilder, id: *const git.Oid) !void { // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.hex_buffer_size]u8 = undefined; const slice = try id.formatHex(&buf); log.debug("PackBuilder.insertCommit called, id: {s}", .{ slice, }); } try internal.wrapCall("git_packbuilder_insert_commit", .{ @ptrCast(*c.git_packbuilder, self), @ptrCast(*const c.git_oid, id), }); log.debug("successfully inserted commit", .{}); } /// Insert objects as given by the walk /// /// Those commits and all objects they reference will be inserted into the packbuilder. pub fn insertWalk(self: *PackBuilder, walk: *git.RevWalk) !void { log.debug("PackBuilder.insertWalk called, walk: {*}", .{walk}); try internal.wrapCall("git_packbuilder_insert_walk", .{ @ptrCast(*c.git_packbuilder, self), @ptrCast(*c.git_revwalk, walk), }); log.debug("successfully inserted walk", .{}); } /// Write the contents of the packfile to an in-memory buffer /// /// The contents of the buffer will become a valid packfile, even though there will be no attached index pub fn writeToBuffer(self: *PackBuilder) !git.Buf { log.debug("PackBuilder.writeToBuffer called", .{}); var buf: git.Buf = .{}; try internal.wrapCall("git_packbuilder_write_buf", .{ @ptrCast(*c.git_buf, &buf), @ptrCast(*c.git_packbuilder, self), }); log.debug("successfully wrote packfile to buffer", .{}); return buf; } /// Write the new pack and corresponding index file to path. /// /// ## Parameters /// * `path` - Path to the directory where the packfile and index should be stored, or `null` for default location /// * `mode` - Permissions to use creating a packfile or 0 for defaults pub fn writeToFile(self: *PackBuilder, path: ?[:0]const u8, mode: c_uint) !void { log.debug("PackBuilder.writeToFile called, path: {s}, mode: {o}", .{ path, mode }); const path_c = if (path) |str| str.ptr else null; try internal.wrapCall("git_packbuilder_write", .{ @ptrCast(*c.git_packbuilder, self), path_c, mode, null, null, }); log.debug("successfully wrote packfile to file", .{}); } /// Write the new pack and corresponding index file to path. /// /// ## Parameters /// * `path` - Path to the directory where the packfile and index should be stored, or `null` for default location /// * `mode` - Permissions to use creating a packfile or 0 for defaults /// * `callback_fn` - Function to call with progress information from the indexer /// /// ## Callback Parameters /// * `stats` - State of the transfer pub fn writeToFileCallback( self: *PackBuilder, path: ?[:0]const u8, mode: c_uint, comptime callback_fn: fn (stats: *const git.IndexerProgress) c_int, ) !void { const cb = struct { pub fn cb( stats: *const git.IndexerProgress, _: *u8, ) c_int { return callback_fn(stats); } }.cb; var dummy_data: u8 = undefined; return self.writeToFileCallbackWithUserData(path, mode, &dummy_data, cb); } /// Write the new pack and corresponding index file to path. /// /// ## Parameters /// * `path` - Path to the directory where the packfile and index should be stored, or `null` for default location /// * `mode` - Permissions to use creating a packfile or 0 for defaults /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - Function to call with progress information from the indexer /// /// ## Callback Parameters /// * `stats` - State of the transfer /// * `user_data_ptr` - The user data pub fn writeToFileCallbackWithUserData( self: *PackBuilder, path: ?[:0]const u8, mode: c_uint, user_data: anytype, comptime callback_fn: fn ( stats: *const git.IndexerProgress, user_data_ptr: @TypeOf(user_data), ) c_int, ) !void { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( stats: *const c.git_indexer_progress, payload: ?*anyopaque, ) callconv(.C) c_int { return callback_fn(@ptrCast(*const git.IndexerProgress, stats), @ptrCast(UserDataType, payload)); } }.cb; log.debug("PackBuilder.writeToFileCallbackWithUserData called, path: {s}, mode: {o}", .{ path, mode }); const path_c = if (path) |str| str.ptr else null; try internal.wrapCall("git_packbuilder_write", .{ @ptrCast(*c.git_packbuilder, self), path_c, mode, cb, user_data, }); log.debug("successfully wrote packfile to file", .{}); } /// Get the packfile's hash /// /// A packfile's name is derived from the sorted hashing of all object names. /// This is only correct after the packfile has been written. pub fn hash(self: *PackBuilder) *const git.Oid { log.debug("PackBuilder.hash called", .{}); const ret = @ptrCast( *const git.Oid, c.git_packbuilder_hash(@ptrCast(*c.git_packbuilder, self)), ); // This check is to prevent formating the oid when we are not going to print anything if (@enumToInt(std.log.Level.debug) <= @enumToInt(std.log.level)) { var buf: [git.Oid.hex_buffer_size]u8 = undefined; if (ret.formatHex(&buf)) |slice| { log.debug("packfile hash: {s}", .{slice}); } else |_| {} } return ret; } /// Create the new pack and pass each object to the callback /// /// Return non-zero from the callback to terminate the iteration /// /// ## Parameters /// * `callback_fn` - The callback to call with each packed object's buffer /// /// ## Callback Parameters /// * `object_data` - Slice of the objects data pub fn foreach( self: *PackBuilder, comptime callback_fn: fn (object_data: []u8) c_int, ) !void { const cb = struct { pub fn cb( object_data: []u8, _: *u8, ) c_int { return callback_fn(object_data); } }.cb; var dummy_data: u8 = undefined; return self.foreachWithUserData(&dummy_data, cb); } /// Create the new pack and pass each object to the callback /// /// Return non-zero from the callback to terminate the iteration /// /// ## Parameters /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - The callback to call with each packed object's buffer /// /// ## Callback Parameters /// * `object_data` - Slice of the objects data /// * `user_data_ptr` - The user data pub fn foreachWithUserData( self: *PackBuilder, user_data: anytype, comptime callback_fn: fn ( object_data: []u8, user_data_ptr: @TypeOf(user_data), ) c_int, ) !void { const UserDataType = @TypeOf(user_data); const cb = struct { pub fn cb( ptr: ?*anyopaque, len: usize, payload: ?*anyopaque, ) callconv(.C) c_int { return callback_fn( @ptrCast([*]u8, ptr)[0..len], @ptrCast(UserDataType, payload), ); } }.cb; log.debug("PackBuilder.foreachWithUserData called", .{}); try internal.wrapCall("git_packbuilder_foreach", .{ @ptrCast(*c.git_packbuilder, self), cb, user_data, }); } /// Set the callbacks for a packbuilder /// /// ## Parameters /// * `callback_fn` - Function to call with progress information during pack building. /// Be aware that this is called inline with pack building operations, so performance may be affected. pub fn setCallbacks( self: *PackBuilder, comptime callback_fn: fn ( stage: PackbuilderStage, current: u32, total: u32, ) void, ) void { const cb = struct { pub fn cb( stage: PackbuilderStage, current: u32, total: u32, _: *u8, ) void { callback_fn(stage, current, total); } }.cb; var dummy_data: u8 = undefined; return self.setCallbacksWithUserData(&dummy_data, cb); } /// Set the callbacks for a packbuilder /// /// ## Parameters /// * `user_data` - Pointer to user data to be passed to the callback /// * `callback_fn` - Function to call with progress information during pack building. /// Be aware that this is called inline with pack building operations, so performance may be affected. pub fn setCallbacksWithUserData( self: *PackBuilder, user_data: anytype, comptime callback_fn: fn ( stage: PackbuilderStage, current: u32, total: u32, user_data_ptr: @TypeOf(user_data), ) void, ) void { const UserDataType = @TypeOf(user_data); // fn (c_int, u32, u32, ?*anyopaque) callconv(.C) c_int const cb = struct { pub fn cb( stage: c_int, current: u32, total: u32, payload: ?*anyopaque, ) callconv(.C) c_int { callback_fn( @intToEnum(PackbuilderStage, stage), current, total, @ptrCast(UserDataType, payload), ); return 0; } }.cb; log.debug("PackBuilder.setCallbacksWithUserData called", .{}); _ = c.git_packbuilder_set_callbacks( @ptrCast(*c.git_packbuilder, self), cb, user_data, ); } comptime { std.testing.refAllDecls(@This()); } }; /// Stages that are reported by the packbuilder progress callback. pub const PackbuilderStage = enum(c_uint) { adding_objects = 0, deltafication = 1, }; comptime { std.testing.refAllDecls(@This()); }
src/pack.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const mem = std.mem; const Allocator = mem.Allocator; const StringHashMap = std.StringHashMap; const Chunk = @import("./chunk.zig").Chunk; const VM = @import("./vm.zig").VM; const Compiler = @import("./compiler.zig").Compiler; const _memory = @import("./memory.zig"); const _value = @import("./value.zig"); const Token = @import("./token.zig").Token; const Config = @import("./config.zig").Config; const Value = _value.Value; const HashableValue = _value.HashableValue; const ValueType = _value.ValueType; const valueToHashable = _value.valueToHashable; const hashableToValue = _value.hashableToValue; const valueToString = _value.valueToString; const valueEql = _value.valueEql; const valueIs = _value.valueIs; const valueTypeEql = _value.valueTypeEql; const allocate = _memory.allocate; const allocateMany = _memory.allocateMany; const free = _memory.free; const freeMany = _memory.freeMany; const markObj = _memory.markObj; const markValue = _memory.markValue; const collectGarbage = _memory.collectGarbage; pub const ObjType = enum { String, Type, UpValue, Closure, Function, ObjectInstance, Object, List, Map, Enum, EnumInstance, Bound, Native, UserData, }; pub fn allocateObject(vm: *VM, comptime T: type, data: T) !*T { var before: usize = vm.bytes_allocated; var obj: *T = try allocate(vm, T); obj.* = data; var object: *Obj = switch (T) { ObjString => ObjString.toObj(obj), ObjTypeDef => ObjTypeDef.toObj(obj), ObjUpValue => ObjUpValue.toObj(obj), ObjClosure => ObjClosure.toObj(obj), ObjFunction => ObjFunction.toObj(obj), ObjObjectInstance => ObjObjectInstance.toObj(obj), ObjObject => ObjObject.toObj(obj), ObjList => ObjList.toObj(obj), ObjMap => ObjMap.toObj(obj), ObjEnum => ObjEnum.toObj(obj), ObjEnumInstance => ObjEnumInstance.toObj(obj), ObjBoundMethod => ObjBoundMethod.toObj(obj), ObjNative => ObjNative.toObj(obj), ObjUserData => ObjUserData.toObj(obj), else => {}, }; if (Config.debug_gc) { std.debug.print("allocated {*} {*}\n", .{ obj, object }); std.debug.print("(from {}) {} allocated, total {}\n", .{ before, @sizeOf(T), vm.bytes_allocated }); } // Add new object at start of vm.objects linked list object.next = vm.objects; vm.objects = object; return obj; } pub fn allocateString(vm: *VM, chars: []const u8) !*ObjString { if (vm.strings.get(chars)) |interned| { return interned; } else { var string: *ObjString = try allocateObject(vm, ObjString, ObjString{ .string = chars }); vm.push(Value{ .Obj = string.toObj() }); try vm.strings.put(chars, string); _ = vm.pop(); return string; } } pub fn copyString(vm: *VM, chars: []const u8) !*ObjString { if (vm.strings.get(chars)) |interned| { return interned; } var copy: []u8 = try allocateMany(vm, u8, chars.len); mem.copy(u8, copy, chars); return try allocateString(vm, copy); } pub fn copyStringRaw(strings: *std.StringHashMap(*ObjString), allocator: Allocator, chars: []const u8, owned: bool) !*ObjString { if (strings.get(chars)) |interned| { return interned; } var copy: []u8 = undefined; if (!owned) { copy = try allocator.alloc(u8, chars.len); mem.copy(u8, copy, chars); } var obj_string: *ObjString = try allocator.create(ObjString); obj_string.* = ObjString{ .string = if (owned) chars else copy, }; try strings.put(chars, obj_string); return obj_string; } pub const Obj = struct { const Self = @This(); obj_type: ObjType, is_marked: bool = false, next: ?*Obj = null, pub fn is(self: *Self, type_def: *ObjTypeDef) bool { return switch (self.obj_type) { .String => type_def.def_type == .String, .Type, .Object, .Enum => type_def.def_type == .Type, .ObjectInstance => type_def.def_type == .Object and ObjObjectInstance.cast(self).?.is(null, type_def), .EnumInstance => type_def.def_type == .Enum and ObjEnumInstance.cast(self).?.enum_ref.type_def == type_def, .Function => function: { const function: *ObjFunction = ObjFunction.cast(self).?; break :function function.type_def.eql(type_def); }, .UpValue => upvalue: { const upvalue: *ObjUpValue = ObjUpValue.cast(self).?; break :upvalue valueIs( Value{ .Obj = type_def.toObj() }, upvalue.closed orelse upvalue.location.*, ); }, .Closure => ObjClosure.cast(self).?.function.toObj().is(type_def), .List => ObjList.cast(self).?.type_def.eql(type_def), .Map => ObjMap.cast(self).?.type_def.eql(type_def), .Bound => bound: { const bound: *ObjBoundMethod = ObjBoundMethod.cast(self).?; break :bound valueIs( Value{ .Obj = type_def.toObj() }, Value{ .Obj = if (bound.closure) |cls| cls.function.toObj() else bound.native.?.toObj() }, ); }, .UserData, .Native => unreachable, // TODO: we don't know how to embark NativeFn type at runtime yet }; } pub fn typeEql(self: *Self, type_def: *ObjTypeDef) bool { return switch (self.obj_type) { .String => type_def.def_type == .String, .Type => type_def.def_type == .Type, .UpValue => uv: { var upvalue: *ObjUpValue = ObjUpValue.cast(self).?; break :uv valueTypeEql(upvalue.closed orelse upvalue.location.*, type_def); }, .EnumInstance => ei: { var instance: *ObjEnumInstance = ObjEnumInstance.cast(self).?; break :ei type_def.def_type == .EnumInstance and instance.enum_ref.type_def.eql(type_def.resolved_type.?.EnumInstance); }, .ObjectInstance => oi: { var instance: *ObjObjectInstance = ObjObjectInstance.cast(self).?; break :oi type_def.def_type == .ObjectInstance and instance.is(null, type_def.resolved_type.?.ObjectInstance); }, .Enum => ObjEnum.cast(self).?.type_def.eql(type_def), .Object => ObjObject.cast(self).?.type_def.eql(type_def), .Function => ObjFunction.cast(self).?.type_def.eql(type_def), .Closure => ObjClosure.cast(self).?.function.type_def.eql(type_def), .Bound => bound: { var bound = ObjBoundMethod.cast(self).?; break :bound if (bound.closure) |cls| cls.function.type_def.eql(type_def) else unreachable; // TODO }, .List => ObjList.cast(self).?.type_def.eql(type_def), .Map => ObjMap.cast(self).?.type_def.eql(type_def), .UserData, .Native => unreachable, // TODO }; } pub fn eql(self: *Self, other: *Self) bool { if (self.obj_type != other.obj_type) { return false; } switch (self.obj_type) { .String => { // return mem.eql(u8, ObjString.cast(self).?.string, ObjString.cast(other).?.string); // since string are interned this should be enough return self == other; }, .Type => { const self_type: *ObjTypeDef = ObjTypeDef.cast(self).?; const other_type: *ObjTypeDef = ObjTypeDef.cast(other).?; return self_type.optional == other_type.optional and self_type.eql(other_type); }, .UpValue => { const self_upvalue: *ObjUpValue = ObjUpValue.cast(self).?; const other_upvalue: *ObjUpValue = ObjUpValue.cast(other).?; return valueEql(self_upvalue.closed orelse self_upvalue.location.*, other_upvalue.closed orelse other_upvalue.location.*); }, .EnumInstance => { const self_enum_instance: *ObjEnumInstance = ObjEnumInstance.cast(self).?; const other_enum_instance: *ObjEnumInstance = ObjEnumInstance.cast(other).?; return self_enum_instance.enum_ref == other_enum_instance.enum_ref and self_enum_instance.case == other_enum_instance.case; }, .Bound, .Closure, .Function, .ObjectInstance, .Object, .List, .Map, .Enum, .Native, .UserData, => { return self == other; }, } } }; // 1 = return value on stack, 0 = no return value, -1 = error pub const NativeFn = fn (vm: *VM) c_int; /// Native function pub const ObjNative = struct { const Self = @This(); obj: Obj = .{ .obj_type = .Native }, // TODO: issue is list.member which separate its type definition from its runtime creation // type_def: *ObjTypeDef, native: NativeFn, pub fn mark(_: *Self, _: *VM) void {} pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Native) { return null; } return @fieldParentPtr(Self, "obj", obj); } }; pub const UserData = opaque {}; /// User data, type around an opaque pointer pub const ObjUserData = struct { const Self = @This(); obj: Obj = .{ .obj_type = .UserData }, userdata: *UserData, pub fn mark(_: *Self, _: *VM) void {} pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Native) { return null; } return @fieldParentPtr(Self, "obj", obj); } }; /// A String pub const ObjString = struct { const Self = @This(); var members: ?std.StringArrayHashMap(*ObjNative) = null; var memberDefs: ?std.StringHashMap(*ObjTypeDef) = null; obj: Obj = .{ .obj_type = .String }, /// The actual string string: []const u8, pub fn mark(_: *Self, _: *VM) void {} pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .String) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub fn concat(self: *Self, vm: *VM, other: *Self) !*Self { var new_string: std.ArrayList(u8) = std.ArrayList(u8).init(vm.allocator); try new_string.appendSlice(self.string); try new_string.appendSlice(other.string); return copyString(vm, new_string.items); } pub fn len(vm: *VM) c_int { var str: *Self = Self.cast(vm.peek(0).Obj).?; vm.push(Value{ .Number = @intToFloat(f64, str.string.len) }); return 1; } pub fn byte(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(1).Obj).?; var index: f64 = vm.peek(0).Number; if (index < 0 or index >= @intToFloat(f64, self.string.len)) { var err: ?*ObjString = copyString(vm, "Out of bound access to str") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; } vm.push(Value{ .Number = @intToFloat(f64, self.string[@floatToInt(usize, index)]) }); return 1; } pub fn indexOf(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(1).Obj).?; var needle: *Self = Self.cast(vm.peek(0).Obj).?; var index = std.mem.indexOf(u8, self.string, needle.string); vm.push(if (index) |uindex| Value{ .Number = @intToFloat(f64, uindex) } else Value{ .Null = false }); return 1; } pub fn sub(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(2).Obj).?; var start: f64 = vm.peek(1).Number; var upto_value: Value = vm.peek(0); var upto: ?f64 = if (upto_value == .Number) upto_value.Number else null; if (start < 0 or start >= @intToFloat(f64, self.string.len)) { var err: ?*ObjString = copyString(vm, "`start` is out of bound") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; } if (upto != null and upto.? < 0) { var err: ?*ObjString = copyString(vm, "`len` must greater or equal to 0") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; } const limit: usize = if (upto != null and @floatToInt(usize, start + upto.?) < self.string.len) @floatToInt(usize, start + upto.?) else self.string.len; var substr: []const u8 = self.string[@floatToInt(usize, start)..limit]; vm.push( (copyString(vm, substr) catch { var err: ?*ObjString = copyString(vm, "Could not get sub string") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }).toValue(), ); return 1; } pub fn split(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(1).Obj).?; var separator: *Self = Self.cast(vm.peek(0).Obj).?; // std.mem.split(u8, self.string, separator.string); var list_def: ObjList.ListDef = ObjList.ListDef.init( vm.allocator, allocateObject(vm, ObjTypeDef, ObjTypeDef{ .def_type = .String, }) catch { var err: ?*ObjString = copyString(vm, "Could not split string") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }, ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; // TODO: reuse already allocated similar typedef var list_def_type: *ObjTypeDef = allocateObject(vm, ObjTypeDef, ObjTypeDef{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }) catch { var err: ?*ObjString = copyString(vm, "Could not split string") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; var list: *ObjList = allocateObject( vm, ObjList, ObjList.init(vm.allocator, list_def_type), ) catch { var err: ?*ObjString = copyString(vm, "Could not split string") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; var it = std.mem.split(u8, self.string, separator.string); while (it.next()) |fragment| { var fragment_str: ?*ObjString = copyString(vm, fragment) catch { var err: ?*ObjString = copyString(vm, "Could not split string") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; list.rawAppend(fragment_str.?.toValue()) catch { var err: ?*ObjString = copyString(vm, "Could not split string") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; } vm.push(list.toValue()); return 1; } pub fn next(self: *Self, vm: *VM, str_index: ?f64) !?f64 { if (str_index) |index| { if (index < 0 or index >= @intToFloat(f64, self.string.len)) { try vm.throw(VM.Error.OutOfBound, (try copyString(vm, "Out of bound access to str")).toValue()); } return if (index + 1 >= @intToFloat(f64, self.string.len)) null else index + 1; } else { return if (self.string.len > 0) @intToFloat(f64, 0) else null; } } // TODO: find a way to return the same ObjNative pointer for the same type of Lists pub fn member(vm: *VM, method: []const u8) !?*ObjNative { if (Self.members) |umembers| { if (umembers.get(method)) |umethod| { return umethod; } } Self.members = Self.members orelse std.StringArrayHashMap(*ObjNative).init(vm.allocator); var nativeFn: ?NativeFn = null; if (mem.eql(u8, method, "len")) { nativeFn = len; } else if (mem.eql(u8, method, "byte")) { nativeFn = byte; } else if (mem.eql(u8, method, "indexOf")) { nativeFn = indexOf; } else if (mem.eql(u8, method, "split")) { nativeFn = split; } else if (mem.eql(u8, method, "sub")) { nativeFn = sub; } if (nativeFn) |unativeFn| { var native: *ObjNative = try allocateObject( vm, ObjNative, .{ .native = unativeFn, }, ); try Self.members.?.put(method, native); return native; } return null; } pub fn memberDef(compiler: *Compiler, method: []const u8) !?*ObjTypeDef { if (Self.memberDefs) |umembers| { if (umembers.get(method)) |umethod| { return umethod; } } Self.memberDefs = Self.memberDefs orelse std.StringHashMap(*ObjTypeDef).init(compiler.allocator); if (mem.eql(u8, method, "len")) { // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "len", false), .parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator), .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .def_type = .Number }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try Self.memberDefs.?.put("len", native_type); return native_type; } else if (mem.eql(u8, method, "byte")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put("at", try compiler.getTypeDef(.{ .def_type = .Number })); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "byte", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .def_type = .Number }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try Self.memberDefs.?.put("byte", native_type); return native_type; } else if (mem.eql(u8, method, "indexOf")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put("needle", try compiler.getTypeDef(.{ .def_type = .String })); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "indexOf", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef( .{ .def_type = .Number, .optional = true, }, ), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try Self.memberDefs.?.put("indexOf", native_type); return native_type; } else if (mem.eql(u8, method, "split")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put("separator", try compiler.getTypeDef(.{ .def_type = .String })); var list_def: ObjList.ListDef = ObjList.ListDef.init( compiler.allocator, try compiler.getTypeDef(ObjTypeDef{ .def_type = .String, }), ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "split", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(ObjTypeDef{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try Self.memberDefs.?.put("split", native_type); return native_type; } else if (mem.eql(u8, method, "sub")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put( "start", try compiler.getTypeDef( .{ .def_type = .Number, }, ), ); try parameters.put( "len", try compiler.getTypeDef( .{ .def_type = .Number, .optional = true, }, ), ); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "sub", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(ObjTypeDef{ .def_type = .String }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try Self.memberDefs.?.put("sub", native_type); return native_type; } return null; } }; /// Upvalue pub const ObjUpValue = struct { const Self = @This(); obj: Obj = .{ .obj_type = .UpValue }, /// Slot on the stack location: *Value, closed: ?Value, next: ?*ObjUpValue = null, pub fn init(slot: *Value) Self { return Self{ .closed = null, .location = slot, .next = null }; } pub fn mark(self: *Self, vm: *VM) !void { if (self.closed) |uclosed| { try markValue(vm, uclosed); } } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .UpValue) { return null; } return @fieldParentPtr(Self, "obj", obj); } }; /// Closure pub const ObjClosure = struct { const Self = @This(); obj: Obj = .{ .obj_type = .Closure }, function: *ObjFunction, upvalues: std.ArrayList(*ObjUpValue), // Pointer to the global with which the function was declared // TODO: can those be collected by gc? globals: *std.ArrayList(Value), pub fn init(allocator: Allocator, vm: *VM, function: *ObjFunction) !Self { return Self{ .globals = &vm.globals, .function = function, .upvalues = try std.ArrayList(*ObjUpValue).initCapacity(allocator, function.upvalue_count), }; } pub fn mark(self: *Self, vm: *VM) !void { try markObj(vm, self.function.toObj()); for (self.upvalues.items) |upvalue| { try markObj(vm, upvalue.toObj()); } } pub fn deinit(self: *Self) void { self.upvalues.deinit(); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Closure) { return null; } return @fieldParentPtr(Self, "obj", obj); } }; /// Function pub const ObjFunction = struct { const Self = @This(); pub const FunctionType = enum { Function, Method, Script, // Imported script ScriptEntryPoint, // main script EntryPoint, // main function Catch, Test, Anonymous, Extern, }; obj: Obj = .{ .obj_type = .Function }, type_def: *ObjTypeDef = undefined, // Undefined because function initialization is in several steps name: *ObjString, chunk: Chunk, upvalue_count: u8 = 0, pub fn init(allocator: Allocator, name: *ObjString) !Self { return Self{ .name = name, .chunk = Chunk.init(allocator), }; } pub fn deinit(self: *Self) void { self.chunk.deinit(); } pub fn mark(self: *Self, vm: *VM) !void { try markObj(vm, self.name.toObj()); try markObj(vm, self.type_def.toObj()); for (self.chunk.constants.items) |constant| { try markValue(vm, constant); } } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Function) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub const FunctionDef = struct { name: *ObjString, return_type: *ObjTypeDef, parameters: std.StringArrayHashMap(*ObjTypeDef), has_defaults: std.StringArrayHashMap(bool), function_type: FunctionType = .Function, lambda: bool = false, }; }; /// Object instance pub const ObjObjectInstance = struct { const Self = @This(); obj: Obj = .{ .obj_type = .ObjectInstance }, /// Object object: *ObjObject, /// Fields value fields: StringHashMap(Value), pub fn init(allocator: Allocator, object: *ObjObject) Self { return Self{ .object = object, .fields = StringHashMap(Value).init(allocator), }; } pub fn mark(self: *Self, vm: *VM) !void { try markObj(vm, self.object.toObj()); var it = self.fields.iterator(); while (it.next()) |kv| { try markValue(vm, kv.value_ptr.*); } } pub fn deinit(self: *Self) void { self.fields.deinit(); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .ObjectInstance) { return null; } return @fieldParentPtr(Self, "obj", obj); } fn is(self: *Self, instance_type: ?*ObjTypeDef, type_def: *ObjTypeDef) bool { const object_def: *ObjTypeDef = instance_type orelse self.object.type_def; if (type_def.def_type != .Object) { return false; } return object_def == type_def or (object_def.resolved_type.?.Object.super != null and self.is(object_def.resolved_type.?.Object.super.?, type_def)); } }; /// Object pub const ObjObject = struct { const Self = @This(); obj: Obj = .{ .obj_type = .Object }, type_def: *ObjTypeDef, /// Object name name: *ObjString, /// Object methods methods: StringHashMap(*ObjClosure), /// Object fields default values fields: StringHashMap(Value), /// Object static fields static_fields: StringHashMap(Value), /// Optional super class super: ?*ObjObject = null, pub fn init(allocator: Allocator, name: *ObjString, type_def: *ObjTypeDef) Self { return Self{ .name = name, .methods = StringHashMap(*ObjClosure).init(allocator), .fields = StringHashMap(Value).init(allocator), .static_fields = StringHashMap(Value).init(allocator), .type_def = type_def, }; } pub fn mark(self: *Self, vm: *VM) !void { try markObj(vm, self.name.toObj()); var it = self.methods.iterator(); while (it.next()) |kv| { try markObj(vm, kv.value_ptr.*.toObj()); } var it2 = self.fields.iterator(); while (it2.next()) |kv| { try markValue(vm, kv.value_ptr.*); } var it3 = self.static_fields.iterator(); while (it3.next()) |kv| { try markValue(vm, kv.value_ptr.*); } if (self.super) |super| { try markObj(vm, super.toObj()); } } pub fn deinit(self: *Self) void { self.methods.deinit(); self.fields.deinit(); self.static_fields.deinit(); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Object) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub const ObjectDef = struct { const ObjectDefSelf = @This(); name: *ObjString, // TODO: Do i need to have two maps ? fields: StringHashMap(*ObjTypeDef), fields_defaults: StringHashMap(void), static_fields: StringHashMap(*ObjTypeDef), methods: StringHashMap(*ObjTypeDef), // When we have placeholders we don't know if they are properties or methods // That information is available only when the placeholder is resolved // It's not an issue since: // - we use OP_GET_PROPERTY for both // - OP_SET_PROPERTY for a method will ultimately fail // - OP_INVOKE on a field will ultimately fail // TODO: but we can have field which are functions and then we don't know what's what placeholders: StringHashMap(*ObjTypeDef), static_placeholders: StringHashMap(*ObjTypeDef), super: ?*ObjTypeDef = null, inheritable: bool = false, pub fn init(allocator: Allocator, name: *ObjString) ObjectDefSelf { return ObjectDefSelf{ .name = name, .fields = StringHashMap(*ObjTypeDef).init(allocator), .static_fields = StringHashMap(*ObjTypeDef).init(allocator), .fields_defaults = StringHashMap(void).init(allocator), .methods = StringHashMap(*ObjTypeDef).init(allocator), .placeholders = StringHashMap(*ObjTypeDef).init(allocator), .static_placeholders = StringHashMap(*ObjTypeDef).init(allocator), }; } pub fn deinit(self: *ObjectDefSelf) void { self.fields.deinit(); self.static_fields.deinit(); self.fields_defaults.deinit(); self.methods.deinit(); self.placeholders.deinit(); self.static_placeholders.deinit(); } }; }; /// List pub const ObjList = struct { const Self = @This(); obj: Obj = .{ .obj_type = .List }, type_def: *ObjTypeDef, /// List items items: std.ArrayList(Value), methods: std.StringHashMap(*ObjNative), pub fn init(allocator: Allocator, type_def: *ObjTypeDef) Self { return Self{ .items = std.ArrayList(Value).init(allocator), .type_def = type_def, .methods = std.StringHashMap(*ObjNative).init(allocator), }; } pub fn mark(self: *Self, vm: *VM) !void { for (self.items.items) |value| { try markValue(vm, value); } try markObj(vm, self.type_def.toObj()); var it = self.methods.iterator(); while (it.next()) |kv| { try markObj(vm, kv.value_ptr.*.toObj()); } } pub fn deinit(self: *Self) void { self.items.deinit(); self.methods.deinit(); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .List) { return null; } return @fieldParentPtr(Self, "obj", obj); } // TODO: find a way to return the same ObjNative pointer for the same type of Lists pub fn member(self: *Self, vm: *VM, method: []const u8) !?*ObjNative { if (self.methods.get(method)) |native| { return native; } var nativeFn: ?NativeFn = null; if (mem.eql(u8, method, "append")) { nativeFn = append; } else if (mem.eql(u8, method, "len")) { nativeFn = len; } else if (mem.eql(u8, method, "next")) { nativeFn = next; } else if (mem.eql(u8, method, "remove")) { nativeFn = remove; } else if (mem.eql(u8, method, "sub")) { nativeFn = sub; } else if (mem.eql(u8, method, "indexOf")) { nativeFn = indexOf; } else if (mem.eql(u8, method, "join")) { nativeFn = join; } if (nativeFn) |unativeFn| { var native: *ObjNative = try allocateObject( vm, ObjNative, .{ .native = unativeFn, }, ); try self.methods.put(method, native); return native; } return null; } pub fn rawAppend(self: *Self, value: Value) !void { try self.items.append(value); } fn append(vm: *VM) c_int { var list_value: Value = vm.peek(1); var list: *ObjList = ObjList.cast(list_value.Obj).?; var value: Value = vm.peek(0); list.rawAppend(value) catch |err| { const messageValue: Value = (copyString(vm, "Could not append to list") catch { std.debug.print("Could not append to list", .{}); std.os.exit(1); }).toValue(); vm.throw(err, messageValue) catch { std.debug.print("Could not append to list", .{}); std.os.exit(1); }; return -1; }; vm.push(list_value); return 1; } fn len(vm: *VM) c_int { var list: *ObjList = ObjList.cast(vm.peek(0).Obj).?; vm.push(Value{ .Number = @intToFloat(f64, list.items.items.len) }); return 1; } pub fn remove(vm: *VM) c_int { var list: *ObjList = ObjList.cast(vm.peek(1).Obj).?; var list_index: f64 = vm.peek(0).Number; if (list_index < 0 or list_index >= @intToFloat(f64, list.items.items.len)) { vm.push(Value{ .Null = false }); return 1; } vm.push(list.items.orderedRemove(@floatToInt(usize, list_index))); return 1; } pub fn indexOf(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(1).Obj).?; var needle: Value = vm.peek(0); var index: ?usize = 0; var i: usize = 0; for (self.items.items) |item| { if (valueEql(needle, item)) { index = i; break; } i += 1; } vm.push(if (index) |uindex| Value{ .Number = @intToFloat(f64, uindex) } else Value{ .Null = false }); return 1; } pub fn join(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(1).Obj).?; var separator: *ObjString = ObjString.cast(vm.peek(0).Obj).?; var result = std.ArrayList(u8).init(vm.allocator); defer result.deinit(); for (self.items.items) |item, i| { var el_str = valueToString(vm.allocator, item) catch { var err: ?*ObjString = copyString(vm, "could not stringify element") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; defer vm.allocator.free(el_str); result.appendSlice(el_str) catch { var err: ?*ObjString = copyString(vm, "could not join list") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; if (i + 1 < self.items.items.len) { result.appendSlice(separator.string) catch { var err: ?*ObjString = copyString(vm, "could not join list") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; } } vm.push( Value{ .Obj = (copyString(vm, result.items) catch { var err: ?*ObjString = copyString(vm, "could not join list") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }).toObj(), }, ); return 1; } pub fn sub(vm: *VM) c_int { var self: *Self = Self.cast(vm.peek(2).Obj).?; var start: f64 = vm.peek(1).Number; var upto_value: Value = vm.peek(0); var upto: ?f64 = if (upto_value == .Number) upto_value.Number else null; if (start < 0 or start >= @intToFloat(f64, self.items.items.len)) { var err: ?*ObjString = copyString(vm, "`start` is out of bound") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; } if (upto != null and upto.? < 0) { var err: ?*ObjString = copyString(vm, "`len` must greater or equal to 0") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; } const limit: usize = if (upto != null and @floatToInt(usize, start + upto.?) < self.items.items.len) @floatToInt(usize, start + upto.?) else self.items.items.len; var substr: []Value = self.items.items[@floatToInt(usize, start)..limit]; var list = allocateObject(vm, ObjList, ObjList{ .type_def = self.type_def, .methods = self.methods.clone() catch { var err: ?*ObjString = copyString(vm, "Could not get sub list") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }, .items = std.ArrayList(Value).init(vm.allocator), }) catch { var err: ?*ObjString = copyString(vm, "Could not get sub list") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; list.items.appendSlice(substr) catch { var err: ?*ObjString = copyString(vm, "Could not get sub list") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; vm.push(list.toValue()); return 1; } pub fn rawNext(self: *Self, vm: *VM, list_index: ?f64) !?f64 { if (list_index) |index| { if (index < 0 or index >= @intToFloat(f64, self.items.items.len)) { try vm.throw(VM.Error.OutOfBound, (try copyString(vm, "Out of bound access to list")).toValue()); } return if (index + 1 >= @intToFloat(f64, self.items.items.len)) null else index + 1; } else { return if (self.items.items.len > 0) @intToFloat(f64, 0) else null; } } fn next(vm: *VM) c_int { var list_value: Value = vm.peek(1); var list: *ObjList = ObjList.cast(list_value.Obj).?; var list_index: Value = vm.peek(0); var next_index: ?f64 = list.rawNext(vm, if (list_index == .Null) null else list_index.Number) catch |err| { // TODO: should we distinguish NativeFn and ExternFn ? std.debug.print("{}\n", .{err}); std.os.exit(1); }; vm.push(if (next_index) |unext_index| Value{ .Number = unext_index } else Value{ .Null = null }); return 1; } pub const ListDef = struct { const SelfListDef = @This(); item_type: *ObjTypeDef, methods: std.StringHashMap(*ObjTypeDef), pub fn init(allocator: Allocator, item_type: *ObjTypeDef) SelfListDef { return .{ .item_type = item_type, .methods = std.StringHashMap(*ObjTypeDef).init(allocator), }; } pub fn deinit(self: *SelfListDef) void { self.methods.deinit(); } pub fn member(obj_list: *ObjTypeDef, compiler: *Compiler, method: []const u8) !?*ObjTypeDef { var self = obj_list.resolved_type.?.List; if (self.methods.get(method)) |native_def| { return native_def; } if (mem.eql(u8, method, "append")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the list. // `value` arg is of item_type try parameters.put("value", self.item_type); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "append", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = obj_list, }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef(ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type }); try self.methods.put("append", native_type); return native_type; } else if (mem.eql(u8, method, "remove")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the list. var at_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Number, .optional = false, }, ); try parameters.put("at", at_type); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "remove", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .optional = true, .def_type = self.item_type.def_type, .resolved_type = self.item_type.resolved_type, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("remove", native_type); return native_type; } else if (mem.eql(u8, method, "len")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "len", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Number, }, ), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("len", native_type); return native_type; } else if (mem.eql(u8, method, "next")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the list. // `key` arg is number try parameters.put( "key", try compiler.getTypeDef( ObjTypeDef{ .def_type = .Number, .optional = true, }, ), ); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "next", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), // When reached end of list, returns null .return_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Number, .optional = true, }, ), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("next", native_type); return native_type; } else if (mem.eql(u8, method, "sub")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put( "start", try compiler.getTypeDef( .{ .def_type = .Number, }, ), ); try parameters.put( "len", try compiler.getTypeDef( .{ .def_type = .Number, .optional = true, }, ), ); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "sub", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = obj_list, }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("sub", native_type); return native_type; } else if (mem.eql(u8, method, "indexOf")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put("needle", self.item_type); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "indexOf", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef( .{ .def_type = self.item_type.def_type, .optional = true, .resolved_type = self.item_type.resolved_type, }, ), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("indexOf", native_type); return native_type; } else if (mem.eql(u8, method, "join")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the string. try parameters.put("separator", try compiler.getTypeDef(.{ .def_type = .String })); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "join", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(ObjTypeDef{ .def_type = .String, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("join", native_type); return native_type; } return null; } }; }; /// Map pub const ObjMap = struct { const Self = @This(); obj: Obj = .{ .obj_type = .Map }, type_def: *ObjTypeDef, // We need an ArrayHashMap for `next` // In order to use a regular HashMap, we would have to hack are away around it to implement next map: std.AutoArrayHashMap(HashableValue, Value), methods: std.StringHashMap(*ObjNative), pub fn init(allocator: Allocator, type_def: *ObjTypeDef) Self { return .{ .type_def = type_def, .map = std.AutoArrayHashMap(HashableValue, Value).init(allocator), .methods = std.StringHashMap(*ObjNative).init(allocator), }; } pub fn member(self: *Self, vm: *VM, method: []const u8) !?*ObjNative { if (self.methods.get(method)) |native| { return native; } var nativeFn: ?NativeFn = null; if (mem.eql(u8, method, "remove")) { nativeFn = remove; } else if (mem.eql(u8, method, "size")) { nativeFn = size; } else if (mem.eql(u8, method, "keys")) { nativeFn = keys; } else if (mem.eql(u8, method, "values")) { nativeFn = values; } if (nativeFn) |unativeFn| { var native: *ObjNative = try allocateObject( vm, ObjNative, .{ .native = unativeFn, }, ); try self.methods.put(method, native); return native; } return null; } pub fn mark(self: *Self, vm: *VM) !void { var it = self.map.iterator(); while (it.next()) |kv| { try markValue(vm, hashableToValue(kv.key_ptr.*)); try markValue(vm, kv.value_ptr.*); } try markObj(vm, self.type_def.toObj()); } fn size(vm: *VM) c_int { var map: *ObjMap = ObjMap.cast(vm.peek(0).Obj).?; vm.push(Value{ .Number = @intToFloat(f64, map.map.count()) }); return 1; } pub fn remove(vm: *VM) c_int { var map: *ObjMap = ObjMap.cast(vm.peek(1).Obj).?; var map_key: HashableValue = valueToHashable(vm.peek(0)); if (map.map.fetchOrderedRemove(map_key)) |removed| { vm.push(removed.value); } else { vm.push(Value{ .Null = false }); } return 1; } pub fn keys(vm: *VM) c_int { var self: *ObjMap = ObjMap.cast(vm.peek(0).Obj).?; var map_keys: []HashableValue = self.map.keys(); var result = std.ArrayList(Value).init(vm.allocator); for (map_keys) |key| { result.append(hashableToValue(key)) catch { var err: ?*ObjString = copyString(vm, "could not get map keys") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; } var list_def: ObjList.ListDef = ObjList.ListDef.init( vm.allocator, self.type_def.resolved_type.?.Map.key_type, ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; var list_def_type: *ObjTypeDef = allocateObject(vm, ObjTypeDef, ObjTypeDef{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }) catch { var err: ?*ObjString = copyString(vm, "could not get map keys") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; var list = allocateObject( vm, ObjList, ObjList.init(vm.allocator, list_def_type), ) catch { var err: ?*ObjString = copyString(vm, "could not get map keys") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; list.items.deinit(); list.items = result; vm.push(list.toValue()); return 1; } pub fn values(vm: *VM) c_int { var self: *ObjMap = ObjMap.cast(vm.peek(0).Obj).?; var map_values: []Value = self.map.values(); var result = std.ArrayList(Value).init(vm.allocator); result.appendSlice(map_values) catch { var err: ?*ObjString = copyString(vm, "could not get map values") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; var list_def: ObjList.ListDef = ObjList.ListDef.init( vm.allocator, self.type_def.resolved_type.?.Map.value_type, ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; var list_def_type: *ObjTypeDef = allocateObject(vm, ObjTypeDef, ObjTypeDef{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }) catch { var err: ?*ObjString = copyString(vm, "could not get map values") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; var list = allocateObject( vm, ObjList, ObjList.init(vm.allocator, list_def_type), ) catch { var err: ?*ObjString = copyString(vm, "could not get map values") catch null; vm.throw(VM.Error.OutOfBound, if (err) |uerr| uerr.toValue() else Value{ .Boolean = false }) catch unreachable; return -1; }; list.items.deinit(); list.items = result; vm.push(list.toValue()); return 1; } pub fn rawNext(self: *Self, key: ?HashableValue) ?HashableValue { const map_keys: []HashableValue = self.map.keys(); if (key) |ukey| { const index: usize = self.map.getIndex(ukey).?; if (index < map_keys.len - 1) { return map_keys[index + 1]; } else { return null; } } else { return if (map_keys.len > 0) map_keys[0] else null; } } pub fn deinit(self: *Self) void { self.map.deinit(); self.methods.deinit(); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Map) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub const MapDef = struct { const SelfMapDef = @This(); key_type: *ObjTypeDef, value_type: *ObjTypeDef, methods: std.StringHashMap(*ObjTypeDef), pub fn init(allocator: Allocator, key_type: *ObjTypeDef, value_type: *ObjTypeDef) SelfMapDef { return .{ .key_type = key_type, .value_type = value_type, .methods = std.StringHashMap(*ObjTypeDef).init(allocator), }; } pub fn deinit(self: *SelfMapDef) void { self.methods.deinit(); } pub fn member(obj_list: *ObjTypeDef, compiler: *Compiler, method: []const u8) !?*ObjTypeDef { var self = obj_list.resolved_type.?.Map; if (self.methods.get(method)) |native_def| { return native_def; } if (mem.eql(u8, method, "size")) { var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "size", false), .parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator), .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .def_type = .Number, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("size", native_type); return native_type; } else if (mem.eql(u8, method, "remove")) { var parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator); // We omit first arg: it'll be OP_SWAPed in and we already parsed it // It's always the list. try parameters.put("at", self.key_type); var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "remove", false), .parameters = parameters, .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .optional = true, .def_type = self.value_type.def_type, .resolved_type = self.value_type.resolved_type, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("remove", native_type); return native_type; } else if (mem.eql(u8, method, "keys")) { var list_def: ObjList.ListDef = ObjList.ListDef.init( compiler.allocator, self.key_type, ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "keys", false), .parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator), .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("keys", native_type); return native_type; } else if (mem.eql(u8, method, "values")) { var list_def: ObjList.ListDef = ObjList.ListDef.init( compiler.allocator, self.value_type, ); var list_def_union: ObjTypeDef.TypeUnion = .{ .List = list_def, }; var method_def = ObjFunction.FunctionDef{ .name = try copyStringRaw(compiler.strings, compiler.allocator, "values", false), .parameters = std.StringArrayHashMap(*ObjTypeDef).init(compiler.allocator), .has_defaults = std.StringArrayHashMap(bool).init(compiler.allocator), .return_type = try compiler.getTypeDef(.{ .def_type = .List, .optional = false, .resolved_type = list_def_union, }), }; var resolved_type: ObjTypeDef.TypeUnion = .{ .Native = method_def }; var native_type = try compiler.getTypeDef( ObjTypeDef{ .def_type = .Native, .resolved_type = resolved_type, }, ); try self.methods.put("values", native_type); return native_type; } return null; } }; }; /// Enum pub const ObjEnum = struct { const Self = @This(); obj: Obj = .{ .obj_type = .Enum }, /// Used to allow type checking at runtime type_def: *ObjTypeDef, name: *ObjString, cases: std.ArrayList(Value), pub fn init(allocator: Allocator, def: *ObjTypeDef) Self { return Self{ .type_def = def, .name = def.resolved_type.?.Enum.name, .cases = std.ArrayList(Value).init(allocator), }; } pub fn mark(self: *Self, vm: *VM) !void { try markObj(vm, self.name.toObj()); try markObj(vm, self.type_def.toObj()); try markObj(vm, self.name.toObj()); for (self.cases.items) |case| { try markValue(vm, case); } } pub fn rawNext(self: *Self, vm: *VM, enum_case: ?*ObjEnumInstance) !?*ObjEnumInstance { if (enum_case) |case| { assert(case.enum_ref == self); if (case.case == self.cases.items.len - 1) { return null; } return try allocateObject(vm, ObjEnumInstance, ObjEnumInstance{ .enum_ref = self, .case = @intCast(u8, case.case + 1), }); } else { return try allocateObject(vm, ObjEnumInstance, ObjEnumInstance{ .enum_ref = self, .case = 0, }); } } pub fn deinit(self: *Self) void { self.cases.deinit(); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Enum) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub const EnumDef = struct { const EnumDefSelf = @This(); name: *ObjString, enum_type: *ObjTypeDef, cases: std.ArrayList([]const u8), pub fn init(allocator: Allocator, name: *ObjString, enum_type: *ObjTypeDef) EnumDefSelf { return EnumDefSelf{ .name = name, .cases = std.ArrayList([]const u8).init(allocator), .enum_type = enum_type, }; } pub fn deinit(self: *EnumDefSelf) void { self.cases.deinit(); } }; }; pub const ObjEnumInstance = struct { const Self = @This(); obj: Obj = .{ .obj_type = .EnumInstance }, enum_ref: *ObjEnum, case: u8, pub fn mark(self: *Self, vm: *VM) !void { try markObj(vm, self.enum_ref.toObj()); } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .EnumInstance) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub fn value(self: *Self) Value { return self.enum_ref.cases.items[self.case]; } }; /// Bound pub const ObjBoundMethod = struct { const Self = @This(); obj: Obj = .{ .obj_type = .Bound }, receiver: Value, closure: ?*ObjClosure = null, native: ?*ObjNative = null, pub fn mark(self: *Self, vm: *VM) !void { try markValue(vm, self.receiver); if (self.closure) |closure| { try markObj(vm, closure.toObj()); } if (self.native) |native| { try markObj(vm, native.toObj()); } } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Bound) { return null; } return @fieldParentPtr(Self, "obj", obj); } }; /// Type pub const ObjTypeDef = struct { const Self = @This(); // TODO: merge this with ObjType pub const Type = enum { Bool, Number, String, ObjectInstance, Object, Enum, EnumInstance, List, Map, Function, Type, // Something that holds a type, not an actual type Void, Native, Placeholder, // Used in first-pass when we refer to a not yet parsed type }; pub const TypeUnion = union(Type) { // For those type checking is obvious, the value is a placeholder Bool: bool, Number: bool, String: bool, Type: bool, Void: bool, // For those we check that the value is an instance of, because those are user defined types ObjectInstance: *ObjTypeDef, EnumInstance: *ObjTypeDef, // Those are never equal Object: ObjObject.ObjectDef, Enum: ObjEnum.EnumDef, // For those we compare definitions, so we own those structs, we don't use actual Obj because we don't want the data, only the types List: ObjList.ListDef, Map: ObjMap.MapDef, Function: ObjFunction.FunctionDef, Native: ObjFunction.FunctionDef, Placeholder: PlaceholderDef, }; obj: Obj = .{ .obj_type = .Type }, /// True means its an optional (e.g `str?`) optional: bool = false, def_type: Type, /// Used when the type is not a basic type resolved_type: ?TypeUnion = null, pub fn cloneOptional(self: *Self, compiler: *Compiler) !*ObjTypeDef { return compiler.getTypeDef( .{ .optional = true, .def_type = self.def_type, .resolved_type = self.resolved_type, }, ); } pub fn deinit(_: *Self) void { std.debug.print("ObjTypeDef.deinit not implemented\n", .{}); } pub fn mark(self: *Self, vm: *VM) !void { if (self.resolved_type) |resolved| { if (resolved == .ObjectInstance) { try markObj(vm, resolved.ObjectInstance.toObj()); } else if (resolved == .EnumInstance) { try markObj(vm, resolved.EnumInstance.toObj()); } } } /// Beware: allocates a string, caller owns it pub fn toString(self: Self, allocator: Allocator) (Allocator.Error || std.fmt.BufPrintError)![]const u8 { var type_str: std.ArrayList(u8) = std.ArrayList(u8).init(allocator); switch (self.def_type) { .Bool => try type_str.appendSlice("bool"), .Number => try type_str.appendSlice("num"), .String => try type_str.appendSlice("str"), // TODO: Find a key for vm.getTypeDef which is unique for each class even with the same name .Object => { try type_str.appendSlice("{ObjectDef}"); try type_str.appendSlice(self.resolved_type.?.Object.name.string); }, .Enum => { try type_str.appendSlice("{EnumDef}"); try type_str.appendSlice(self.resolved_type.?.Enum.name.string); }, .ObjectInstance => try type_str.appendSlice(self.resolved_type.?.ObjectInstance.resolved_type.?.Object.name.string), .EnumInstance => try type_str.appendSlice(self.resolved_type.?.EnumInstance.resolved_type.?.Enum.name.string), .List => { var list_type = try self.resolved_type.?.List.item_type.toString(allocator); defer allocator.free(list_type); try type_str.append('['); try type_str.appendSlice(list_type); try type_str.append(']'); }, .Map => { var key_type = try self.resolved_type.?.Map.key_type.toString(allocator); defer allocator.free(key_type); var value_type = try self.resolved_type.?.Map.value_type.toString(allocator); defer allocator.free(value_type); try type_str.append('{'); try type_str.appendSlice(key_type); try type_str.append(','); try type_str.appendSlice(value_type); try type_str.append('}'); }, .Function => { var function_def = self.resolved_type.?.Function; try type_str.appendSlice("Function("); try type_str.appendSlice(function_def.name.string); try type_str.appendSlice("("); var it = function_def.parameters.iterator(); while (it.next()) |kv| { var param_type = try kv.value_ptr.*.toString(allocator); defer allocator.free(param_type); try type_str.appendSlice(param_type); try type_str.append(','); } try type_str.append(')'); if (function_def.return_type.def_type != Type.Void) { var return_type = try self.resolved_type.?.Function.return_type.toString(allocator); defer allocator.free(return_type); try type_str.appendSlice(") > "); try type_str.appendSlice(return_type); } }, .Type => try type_str.appendSlice("type"), .Void => try type_str.appendSlice("void"), .Placeholder => { try type_str.appendSlice("{PlaceholderDef}"); }, .Native => { try type_str.appendSlice("Native("); var ref: []u8 = try allocator.alloc(u8, 30); defer allocator.free(ref); ref = try std.fmt.bufPrint(ref, "{x}", .{@ptrToInt(&self)}); try type_str.appendSlice(ref); try type_str.appendSlice(")"); }, } if (self.optional) { try type_str.append('?'); } return type_str.items; } pub fn toObj(self: *Self) *Obj { return &self.obj; } pub fn toValue(self: *Self) Value { return Value{ .Obj = self.toObj() }; } pub fn toInstance(self: *Self) Self { return switch (self.def_type) { .Object => object: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .ObjectInstance = self }; break :object Self{ .optional = self.optional, .def_type = .ObjectInstance, .resolved_type = resolved_type, }; }, .Enum => enum_instance: { var resolved_type: ObjTypeDef.TypeUnion = ObjTypeDef.TypeUnion{ .EnumInstance = self }; break :enum_instance Self{ .optional = self.optional, .def_type = .EnumInstance, .resolved_type = resolved_type, }; }, else => self.*, }; } pub fn cast(obj: *Obj) ?*Self { if (obj.obj_type != .Type) { return null; } return @fieldParentPtr(Self, "obj", obj); } pub fn instanceEqlTypeUnion(a: *ObjTypeDef, b: *ObjTypeDef) bool { assert(a.def_type == .Object); assert(b.def_type == .Object); return a == b or (b.resolved_type.?.Object.super != null and instanceEqlTypeUnion(a, b.resolved_type.?.Object.super.?)); } // Compare two type definitions pub fn eqlTypeUnion(a: TypeUnion, b: TypeUnion) bool { if (@as(Type, a) != @as(Type, b)) { return false; } return switch (a) { .Bool, .Number, .String, .Type, .Void => return true, .ObjectInstance => { return a.ObjectInstance.eql(b.ObjectInstance) or instanceEqlTypeUnion(a.ObjectInstance, b.ObjectInstance); }, .EnumInstance => return a.EnumInstance.eql(b.EnumInstance), .Object, .Enum => false, // Thore are never equal even if definition is the same .List => return a.List.item_type.eql(b.List.item_type), .Map => return a.Map.key_type.eql(b.Map.key_type) and a.Map.value_type.eql(b.Map.value_type), .Function => { // Compare return types if (!a.Function.return_type.eql(b.Function.return_type)) { return false; } // Compare arity if (a.Function.parameters.count() != b.Function.parameters.count()) { return false; } // Compare parameters (we ignore argument names and only compare types) const a_keys: [][]const u8 = a.Function.parameters.keys(); const b_keys: [][]const u8 = b.Function.parameters.keys(); if (a_keys.len != b_keys.len) { return false; } for (a_keys) |_, index| { if (!a.Function.parameters.get(a_keys[index]).? .eql(b.Function.parameters.get(b_keys[index]).?)) { return false; } } return true; }, .Placeholder => a.Placeholder.eql(b.Placeholder), .Native => { // Compare return types if (a.Native.return_type.eql(b.Native.return_type)) { return false; } // Compare arity if (a.Native.parameters.count() != b.Native.parameters.count()) { return false; } // Compare parameters var it = a.Native.parameters.iterator(); while (it.next()) |kv| { if (b.Native.parameters.get(kv.key_ptr.*)) |value| { if (!kv.value_ptr.*.eql(value)) { return false; } } else { return false; } } return true; }, }; } // Compare two type definitions pub fn eql(self: *Self, other: *Self) bool { const type_eql: bool = self.def_type == other.def_type and ((self.resolved_type == null and other.resolved_type == null) or eqlTypeUnion(self.resolved_type.?, other.resolved_type.?)); // zig fmt: off return self == other or (self.optional and other.def_type == .Void) // Void is equal to any optional type or ( (type_eql or other.def_type == .Placeholder or self.def_type == .Placeholder) and (self.optional or !other.optional) ); // zig fmt: on } }; // TODO: use ArrayList writer instead of std.fmt.bufPrint pub fn objToString(allocator: Allocator, buf: []u8, obj: *Obj) (Allocator.Error || std.fmt.BufPrintError)![]u8 { return switch (obj.obj_type) { .String => try std.fmt.bufPrint(buf, "{s}", .{ObjString.cast(obj).?.string}), .Type => { // TODO: no use for typedef.toString to allocate a buffer var type_def: *ObjTypeDef = ObjTypeDef.cast(obj).?; var type_str: []const u8 = try type_def.toString(allocator); defer allocator.free(type_str); return try std.fmt.bufPrint(buf, "type: 0x{x} `{s}`", .{ @ptrToInt(type_def), type_str, }); }, .UpValue => { var upvalue: *ObjUpValue = ObjUpValue.cast(obj).?; var upvalue_str: []const u8 = try valueToString(allocator, upvalue.closed orelse upvalue.location.*); defer allocator.free(upvalue_str); return try std.fmt.bufPrint(buf, "upvalue: 0x{x} `{s}`", .{ @ptrToInt(upvalue), upvalue_str, }); }, .Closure => try std.fmt.bufPrint(buf, "closure: 0x{x} `{s}`", .{ @ptrToInt(ObjClosure.cast(obj).?), ObjClosure.cast(obj).?.function.name.string, }), .Function => try std.fmt.bufPrint(buf, "function: 0x{x} `{s}`", .{ @ptrToInt(ObjFunction.cast(obj).?), ObjFunction.cast(obj).?.name.string, }), .ObjectInstance => try std.fmt.bufPrint(buf, "object instance: 0x{x} `{s}`", .{ @ptrToInt(ObjObjectInstance.cast(obj).?), ObjObjectInstance.cast(obj).?.object.name.string, }), .Object => try std.fmt.bufPrint(buf, "object: 0x{x} `{s}`", .{ @ptrToInt(ObjObject.cast(obj).?), ObjObject.cast(obj).?.name.string, }), .List => { var list: *ObjList = ObjList.cast(obj).?; var type_str: []const u8 = try list.type_def.resolved_type.?.List.item_type.toString(allocator); defer allocator.free(type_str); return try std.fmt.bufPrint(buf, "list: 0x{x} [{s}]", .{ @ptrToInt(list), type_str }); }, .Map => { var map: *ObjMap = ObjMap.cast(obj).?; var key_type_str: []const u8 = try map.type_def.resolved_type.?.Map.key_type.toString(allocator); defer allocator.free(key_type_str); var value_type_str: []const u8 = try map.type_def.resolved_type.?.Map.value_type.toString(allocator); defer allocator.free(value_type_str); return try std.fmt.bufPrint(buf, "map: 0x{x} {{{s}, {s}}}", .{ @ptrToInt(map), key_type_str, value_type_str, }); }, .Enum => try std.fmt.bufPrint(buf, "enum: 0x{x} `{s}`", .{ @ptrToInt(ObjEnum.cast(obj).?), ObjEnum.cast(obj).?.name.string, }), .EnumInstance => enum_instance: { var instance: *ObjEnumInstance = ObjEnumInstance.cast(obj).?; var enum_: *ObjEnum = instance.enum_ref; break :enum_instance try std.fmt.bufPrint(buf, "{s}.{s}", .{ enum_.name.string, enum_.type_def.resolved_type.?.Enum.cases.items[instance.case], }); }, .Bound => { var bound: *ObjBoundMethod = ObjBoundMethod.cast(obj).?; var receiver_str: []const u8 = try valueToString(allocator, bound.receiver); defer allocator.free(receiver_str); if (bound.closure) |closure| { var closure_name: []const u8 = closure.function.name.string; return try std.fmt.bufPrint(buf, "bound method: {s} to {s}", .{ receiver_str, closure_name }); } else { assert(bound.native != null); return try std.fmt.bufPrint(buf, "bound method: {s} to native 0x{}", .{ receiver_str, @ptrToInt(bound.native.?) }); } }, .Native => { var native: *ObjNative = ObjNative.cast(obj).?; return try std.fmt.bufPrint(buf, "native: 0x{x}", .{@ptrToInt(native)}); }, .UserData => { var userdata: *ObjUserData = ObjUserData.cast(obj).?; return try std.fmt.bufPrint(buf, "userdata: 0x{x}", .{@ptrToInt(userdata)}); }, }; } pub const PlaceholderDef = struct { const Self = @This(); // TODO: are relations enough and booleans useless? const PlaceholderRelation = enum { Call, Subscript, Key, FieldAccess, Assignment, }; name: ?*ObjString = null, // Assumption made by the code referencing the value callable: ?bool = null, // Function, Object or Class subscriptable: ?bool = null, // Array or Map field_accessible: ?bool = null, // Object, Class or Enum assignable: ?bool = null, // Not a Function, Object, Class or Enum resolved_parameters: ?std.StringArrayHashMap(*ObjTypeDef) = null, // Maybe we resolved argument list but we don't know yet if Object/Class or Function resolved_def_type: ?ObjTypeDef.Type = null, // Meta type // TODO: do we ever infer that much that we can build an actual type? resolved_type: ?*ObjTypeDef = null, // Actual type where: Token, // Where the placeholder was created // When accessing/calling/subscrit/assign a placeholder we produce another. We keep them linked so we // can trace back the root of the unknown type. parent: ?*ObjTypeDef = null, // What's the relation with the parent? parent_relation: ?PlaceholderRelation = null, // Children adds themselves here children: std.ArrayList(*ObjTypeDef), pub fn init(allocator: Allocator, where: Token) Self { return Self{ .where = where.clone(), .children = std.ArrayList(*ObjTypeDef).init(allocator) }; } pub fn deinit(self: *Self) void { self.children.deinit(); } pub fn link(parent: *ObjTypeDef, child: *ObjTypeDef, relation: PlaceholderRelation) !void { assert(parent.def_type == .Placeholder); assert(child.def_type == .Placeholder); child.resolved_type.?.Placeholder.parent = parent; try parent.resolved_type.?.Placeholder.children.append(child); child.resolved_type.?.Placeholder.parent_relation = relation; } pub fn eql(a: Self, b: Self) bool { if (a.resolved_parameters != null and b.resolved_parameters != null) { var it = a.resolved_parameters.?.iterator(); while (it.next()) |kv| { if (b.resolved_parameters.?.get(kv.key_ptr.*)) |b_arg_type| { return b_arg_type.eql(kv.value_ptr.*); } else { return false; } } } return ((a.callable != null and b.callable != null and a.callable.? == b.callable.?) or a.callable == null or b.callable == null) and ((a.subscriptable != null and b.subscriptable != null and a.subscriptable.? == b.subscriptable.?) or a.subscriptable == null or b.subscriptable == null) and ((a.field_accessible != null and b.field_accessible != null and a.field_accessible.? == b.field_accessible.?) or a.field_accessible == null or b.subscriptable == null) and ((a.assignable != null and b.assignable != null and a.assignable.? == b.assignable.?) or a.assignable == null or b.subscriptable == null) and ((a.resolved_def_type != null and b.resolved_def_type != null and a.resolved_def_type.? == b.resolved_def_type.?) or a.resolved_def_type == null or b.resolved_def_type == null) and ((a.resolved_type != null and b.resolved_type != null and a.resolved_type.?.eql(b.resolved_type.?)) or a.resolved_type == null or b.subscriptable == null); } pub fn enrich(one: *Self, other: *Self) !void { one.callable = one.callable orelse other.callable; other.callable = one.callable orelse other.callable; one.subscriptable = one.subscriptable orelse other.subscriptable; other.subscriptable = one.subscriptable orelse other.subscriptable; one.field_accessible = one.field_accessible orelse other.field_accessible; other.field_accessible = one.field_accessible orelse other.field_accessible; one.assignable = one.assignable orelse other.assignable; other.assignable = one.assignable orelse other.assignable; one.resolved_def_type = one.resolved_def_type orelse other.resolved_def_type; other.resolved_def_type = one.resolved_def_type orelse other.resolved_def_type; one.resolved_type = one.resolved_type orelse other.resolved_type; other.resolved_type = one.resolved_type orelse other.resolved_type; if (other.resolved_parameters) |parameters| { one.resolved_parameters = try parameters.clone(); } else if (one.resolved_parameters) |parameters| { other.resolved_parameters = try parameters.clone(); } } // TODO: zig bug here pub fn isBasicType(self: Self, basic_type: ObjTypeDef.Type) bool { return (self.resolved_def_type != null and self.resolved_def_type.? == basic_type) or (self.resolved_type != null and self.resolved_type.?.def_type == basic_type); } pub fn isAssignable(self: *Self) bool { if (self.assignable == null) { return true; } return self.assignable.? and (self.resolved_def_type == null // TODO: method actually but right now we have no way to distinguish them or self.resolved_def_type.? != .Function or self.resolved_def_type.? != .Object) and (self.resolved_type == null // TODO: method actually but right now we have no way to distinguish them or self.resolved_type.?.def_type != .Function or self.resolved_type.?.def_type != .Object); } pub fn isCallable(self: *Self) bool { if (self.callable == null) { return true; } return self.callable.? and (self.resolved_def_type == null or self.resolved_def_type.? == .Function) and (self.resolved_type == null or self.resolved_type.?.def_type == .Function); } pub fn isFieldAccessible(self: *Self) bool { if (self.field_accessible == null) { return true; } return self.field_accessible.? and (self.resolved_def_type == null or self.resolved_def_type.? == .Object or self.resolved_def_type.? == .Enum or self.resolved_def_type.? == .EnumInstance or self.resolved_def_type.? == .ObjectInstance) and (self.resolved_type == null or self.resolved_type.?.def_type == .Object or self.resolved_type.?.def_type == .Enum or self.resolved_type.?.def_type == .EnumInstance or self.resolved_type.?.def_type == .ObjectInstance); } pub fn isSubscriptable(self: *Self) bool { if (self.subscriptable == null) { return true; } // zig fmt: off return self.subscriptable.? and (self.resolved_def_type == null or self.resolved_def_type.? == .List or self.resolved_def_type.? == .Map or self.resolved_def_type.? == .String) and (self.resolved_type == null or self.resolved_type.?.def_type == .List or self.resolved_type.?.def_type == .Map or self.resolved_type.?.def_type == .String); // zig fmt: on } pub fn isIterable(self: *Self) bool { return (self.resolved_def_type == null or self.resolved_def_type.? == .List or self.resolved_def_type.? == .Map or self.resolved_def_type.? == .Enum) and (self.resolved_type == null or self.resolved_type.?.def_type == .List or self.resolved_type.?.def_type == .Map or self.resolved_type.?.def_type == .Enum); } pub fn couldBeList(self: *Self) bool { return self.isSubscriptable() and (self.resolved_def_type == null or self.resolved_def_type.? == .List) and (self.resolved_type == null or self.resolved_type.?.def_type == .List); } pub fn couldBeMap(self: *Self) bool { return self.isSubscriptable() and (self.resolved_def_type == null or self.resolved_def_type.? == .Map) and (self.resolved_type == null or self.resolved_type.?.def_type == .Map); } pub fn couldBeObject(self: *Self) bool { return self.isFieldAccessible() and (self.resolved_def_type == null or self.resolved_def_type.? == .Object) and (self.resolved_type == null or self.resolved_type.?.def_type == .Object); } pub fn isCoherent(self: *Self) bool { if (self.resolved_def_type != null and self.resolved_type != null and @as(ObjTypeDef.Type, self.resolved_type.?.def_type) != self.resolved_def_type.?) { return false; } // Nothing can be called and subscrited if ((self.callable orelse false) and (self.subscriptable orelse false)) { return false; } // Nothing with fields can be subscrited if ((self.field_accessible orelse false) and (self.subscriptable orelse false)) { return false; } // `and` because we checked for compatibility earlier and those function will return true if the flag is null return self.isCallable() and self.isSubscriptable() and self.isFieldAccessible() and self.isAssignable(); } };
src/obj.zig
const std = @import("../std.zig"); const builtin = std.builtin; const mem = std.mem; const debug = std.debug; /// Counter mode. /// /// This mode creates a key stream by encrypting an incrementing counter using a block cipher, and adding it to the source material. /// /// Important: the counter mode doesn't provide authenticated encryption: the ciphertext can be trivially modified without this being detected. /// As a result, applications should generally never use it directly, but only in a construction that includes a MAC. pub fn ctr(comptime BlockCipher: anytype, block_cipher: BlockCipher, dst: []u8, src: []const u8, iv: [BlockCipher.block_length]u8, endian: comptime builtin.Endian) void { debug.assert(dst.len >= src.len); const block_length = BlockCipher.block_length; var counter: [BlockCipher.block_length]u8 = undefined; var counterInt = mem.readInt(u128, &iv, endian); var i: usize = 0; const parallel_count = BlockCipher.block.parallel.optimal_parallel_blocks; const wide_block_length = parallel_count * 16; if (src.len >= wide_block_length) { var counters: [parallel_count * 16]u8 = undefined; while (i + wide_block_length <= src.len) : (i += wide_block_length) { comptime var j = 0; inline while (j < parallel_count) : (j += 1) { mem.writeInt(u128, counters[j * 16 .. j * 16 + 16], counterInt, endian); counterInt +%= 1; } block_cipher.xorWide(parallel_count, dst[i .. i + wide_block_length][0..wide_block_length], src[i .. i + wide_block_length][0..wide_block_length], counters); } } while (i + block_length <= src.len) : (i += block_length) { mem.writeInt(u128, &counter, counterInt, endian); counterInt +%= 1; block_cipher.xor(dst[i .. i + block_length][0..block_length], src[i .. i + block_length][0..block_length], counter); } if (i < src.len) { mem.writeInt(u128, &counter, counterInt, endian); var pad = [_]u8{0} ** block_length; mem.copy(u8, &pad, src[i..]); block_cipher.xor(&pad, &pad, counter); mem.copy(u8, dst[i..], pad[0 .. src.len - i]); } }
lib/std/crypto/modes.zig
const std = @import("std"); const gpa = std.heap.c_allocator; const builtin = std.builtin; const u = @import("index.zig"); const yaml = @import("./yaml.zig"); // // pub const Module = struct { is_sys_lib: bool, id: []const u8, name: []const u8, main: []const u8, c_include_dirs: [][]const u8, c_source_flags: [][]const u8, c_source_files: [][]const u8, only_os: [][]const u8, except_os: [][]const u8, yaml: ?yaml.Mapping, deps: []Module, clean_path: []const u8, pub fn from(dep: u.Dep) !Module { return Module{ .is_sys_lib = false, .id = dep.id, .name = dep.name, .main = dep.main, .c_include_dirs = dep.c_include_dirs, .c_source_flags = dep.c_source_flags, .c_source_files = dep.c_source_files, .deps = &[_]Module{}, .clean_path = try dep.clean_path(), .only_os = dep.only_os, .except_os = dep.except_os, .yaml = dep.yaml, }; } pub fn eql(self: Module, another: Module) bool { return std.mem.eql(u8, self.id, another.id) or std.mem.eql(u8, self.clean_path, another.clean_path); } pub fn get_hash(self: Module, cdpath: []const u8) ![]const u8 { const file_list_1 = &std.ArrayList([]const u8).init(gpa); try u.file_list(try u.concat(&.{ cdpath, "/", self.clean_path }), file_list_1); const file_list_2 = &std.ArrayList([]const u8).init(gpa); for (file_list_1.items) |item| { const _a = u.trim_prefix(item, cdpath)[1..]; const _b = u.trim_prefix(_a, self.clean_path)[1..]; if (_b[0] == '.') continue; try file_list_2.append(_b); } std.sort.sort([]const u8, file_list_2.items, void{}, struct { pub fn lt(context: void, lhs: []const u8, rhs: []const u8) bool { return std.mem.lessThan(u8, lhs, rhs); } }.lt); const h = &std.crypto.hash.Blake3.init(.{}); for (file_list_2.items) |item| { const abs_path = try u.concat(&.{ cdpath, "/", self.clean_path, "/", item }); const file = try std.fs.cwd().openFile(abs_path, .{}); defer file.close(); const input = try file.reader().readAllAlloc(gpa, u.mb * 100); h.update(input); } var out: [32]u8 = undefined; h.final(&out); const hex = try std.fmt.allocPrint(gpa, "blake3-{x}", .{std.fmt.fmtSliceHexLower(out[0..])}); return hex; } pub fn is_for_this(self: Module) bool { const os = @tagName(builtin.os.tag); if (self.only_os.len > 0) { return u.list_contains(self.only_os, os); } if (self.except_os.len > 0) { return !u.list_contains(self.except_os, os); } return true; } pub fn has_no_zig_deps(self: Module) bool { for (self.deps) |d| { if (d.main.len > 0) { return false; } } return true; } };
src/util/module.zig
const std = @import("std"); const lex = @import("zua").lex; // Code for generating a potentially huge collection of // files containing the source of every string literal token // in the corpus provided in @import("build_options").fuzzed_lex_inputs_dir // and outputting them to @import("build_options").fuzzed_strings_gen_dir // // This is a building block for use later with fuzzed_strings.zig, // after minimizing/generating outputs with https://github.com/squeek502/fuzzing-lua const build_options = @import("build_options"); const inputs_dir_path = build_options.fuzzed_lex_inputs_dir; const outputs_dir_path = build_options.fuzzed_strings_gen_dir; pub fn main() !void { var allocator = std.testing.allocator; // clean the outputs dir std.fs.cwd().deleteTree(outputs_dir_path) catch |err| switch (err) { error.NotDir => {}, else => |e| return e, }; try std.fs.cwd().makePath(outputs_dir_path); var inputs_dir = try std.fs.cwd().openDir(inputs_dir_path, .{ .iterate = true }); defer inputs_dir.close(); var outputs_dir = try std.fs.cwd().openDir(outputs_dir_path, .{}); defer outputs_dir.close(); var n: usize = 0; var inputs_iterator = inputs_dir.iterate(); while (try inputs_iterator.next()) |entry| { if (entry.kind != .File) continue; const contents = try inputs_dir.readFileAlloc(allocator, entry.name, std.math.maxInt(usize)); defer allocator.free(contents); var lexer = lex.Lexer.init(contents, "fuzz"); while (true) { const token = lexer.next() catch { break; }; if (token.id == lex.Token.Id.eof) break; if (token.id != lex.Token.Id.string) continue; try outputs_dir.writeFile(entry.name, contents[token.start..token.end]); n += 1; if (n % 100 == 0) { std.debug.print("{}...\r", .{n}); } } } std.debug.print("{} files written to '{s}'\n", .{ n, outputs_dir_path }); }
test/fuzzed_strings_gen.zig
const std = @import("std"); const mem = std.mem; const Allocator = std.mem.Allocator; const ArrayListUnmanaged = std.ArrayListUnmanaged; const Value = @import("value.zig").Value; const Type = @import("type.zig").Type; const TypedValue = @import("TypedValue.zig"); const assert = std.debug.assert; const BigIntConst = std.math.big.int.Const; const BigIntMutable = std.math.big.int.Mutable; const Target = std.Target; const Package = @import("Package.zig"); const link = @import("link.zig"); const ir = @import("ir.zig"); const zir = @import("zir.zig"); const Module = @This(); const Inst = ir.Inst; /// General-purpose allocator. allocator: *Allocator, /// Pointer to externally managed resource. root_pkg: *Package, /// Module owns this resource. root_scope: *Scope.ZIRModule, bin_file: link.ElfFile, bin_file_dir: std.fs.Dir, bin_file_path: []const u8, /// It's rare for a decl to be exported, so we save memory by having a sparse map of /// Decl pointers to details about them being exported. /// The Export memory is owned by the `export_owners` table; the slice itself is owned by this table. decl_exports: std.AutoHashMap(*Decl, []*Export), /// This models the Decls that perform exports, so that `decl_exports` can be updated when a Decl /// is modified. Note that the key of this table is not the Decl being exported, but the Decl that /// is performing the export of another Decl. /// This table owns the Export memory. export_owners: std.AutoHashMap(*Decl, []*Export), /// Maps fully qualified namespaced names to the Decl struct for them. decl_table: std.AutoHashMap(Decl.Hash, *Decl), optimize_mode: std.builtin.Mode, link_error_flags: link.ElfFile.ErrorFlags = link.ElfFile.ErrorFlags{}, work_queue: std.fifo.LinearFifo(WorkItem, .Dynamic), /// We optimize memory usage for a compilation with no compile errors by storing the /// error messages and mapping outside of `Decl`. /// The ErrorMsg memory is owned by the decl, using Module's allocator. /// Note that a Decl can succeed but the Fn it represents can fail. In this case, /// a Decl can have a failed_decls entry but have analysis status of success. failed_decls: std.AutoHashMap(*Decl, *ErrorMsg), /// Using a map here for consistency with the other fields here. /// The ErrorMsg memory is owned by the `Scope.ZIRModule`, using Module's allocator. failed_files: std.AutoHashMap(*Scope.ZIRModule, *ErrorMsg), /// Using a map here for consistency with the other fields here. /// The ErrorMsg memory is owned by the `Export`, using Module's allocator. failed_exports: std.AutoHashMap(*Export, *ErrorMsg), /// Incrementing integer used to compare against the corresponding Decl /// field to determine whether a Decl's status applies to an ongoing update, or a /// previous analysis. generation: u32 = 0, /// Candidates for deletion. After a semantic analysis update completes, this list /// contains Decls that need to be deleted if they end up having no references to them. deletion_set: std.ArrayListUnmanaged(*Decl) = std.ArrayListUnmanaged(*Decl){}, pub const WorkItem = union(enum) { /// Write the machine code for a Decl to the output file. codegen_decl: *Decl, /// Decl has been determined to be outdated; perform semantic analysis again. re_analyze_decl: *Decl, }; pub const Export = struct { options: std.builtin.ExportOptions, /// Byte offset into the file that contains the export directive. src: usize, /// Represents the position of the export, if any, in the output file. link: link.ElfFile.Export, /// The Decl that performs the export. Note that this is *not* the Decl being exported. owner_decl: *Decl, /// The Decl being exported. Note this is *not* the Decl performing the export. exported_decl: *Decl, status: enum { in_progress, failed, /// Indicates that the failure was due to a temporary issue, such as an I/O error /// when writing to the output file. Retrying the export may succeed. failed_retryable, complete, }, }; pub const Decl = struct { /// This name is relative to the containing namespace of the decl. It uses a null-termination /// to save bytes, since there can be a lot of decls in a compilation. The null byte is not allowed /// in symbol names, because executable file formats use null-terminated strings for symbol names. /// All Decls have names, even values that are not bound to a zig namespace. This is necessary for /// mapping them to an address in the output file. /// Memory owned by this decl, using Module's allocator. name: [*:0]const u8, /// The direct parent container of the Decl. This field will need to get more fleshed out when /// self-hosted supports proper struct types and Zig AST => ZIR. /// Reference to externally owned memory. scope: *Scope.ZIRModule, /// Byte offset into the source file that contains this declaration. /// This is the base offset that src offsets within this Decl are relative to. src: usize, /// The most recent value of the Decl after a successful semantic analysis. typed_value: union(enum) { never_succeeded: void, most_recent: TypedValue.Managed, }, /// Represents the "shallow" analysis status. For example, for decls that are functions, /// the function type is analyzed with this set to `in_progress`, however, the semantic /// analysis of the function body is performed with this value set to `success`. Functions /// have their own analysis status field. analysis: enum { /// Semantic analysis for this Decl is running right now. This state detects dependency loops. in_progress, /// This Decl might be OK but it depends on another one which did not successfully complete /// semantic analysis. dependency_failure, /// Semantic analysis failure. /// There will be a corresponding ErrorMsg in Module.failed_decls. sema_failure, /// There will be a corresponding ErrorMsg in Module.failed_decls. codegen_failure, /// There will be a corresponding ErrorMsg in Module.failed_decls. /// This indicates the failure was something like running out of disk space, /// and attempting codegen again may succeed. codegen_failure_retryable, /// Everything is done. During an update, this Decl may be out of date, depending /// on its dependencies. The `generation` field can be used to determine if this /// completion status occurred before or after a given update. complete, /// A Module update is in progress, and this Decl has been flagged as being known /// to require re-analysis. outdated, }, /// This flag is set when this Decl is added to a check_for_deletion set, and cleared /// when removed. deletion_flag: bool, /// An integer that can be checked against the corresponding incrementing /// generation field of Module. This is used to determine whether `complete` status /// represents pre- or post- re-analysis. generation: u32, /// Represents the position of the code in the output file. /// This is populated regardless of semantic analysis and code generation. link: link.ElfFile.TextBlock = link.ElfFile.TextBlock.empty, contents_hash: Hash, /// The shallow set of other decls whose typed_value could possibly change if this Decl's /// typed_value is modified. dependants: ArrayListUnmanaged(*Decl) = ArrayListUnmanaged(*Decl){}, /// The shallow set of other decls whose typed_value changing indicates that this Decl's /// typed_value may need to be regenerated. dependencies: ArrayListUnmanaged(*Decl) = ArrayListUnmanaged(*Decl){}, pub fn destroy(self: *Decl, allocator: *Allocator) void { allocator.free(mem.spanZ(self.name)); if (self.typedValueManaged()) |tvm| { tvm.deinit(allocator); } self.dependants.deinit(allocator); self.dependencies.deinit(allocator); allocator.destroy(self); } pub const Hash = [16]u8; /// If the name is small enough, it is used directly as the hash. /// If it is long, blake3 hash is computed. pub fn hashSimpleName(name: []const u8) Hash { var out: Hash = undefined; if (name.len <= Hash.len) { mem.copy(u8, &out, name); mem.set(u8, out[name.len..], 0); } else { std.crypto.Blake3.hash(name, &out); } return out; } /// Must generate unique bytes with no collisions with other decls. /// The point of hashing here is only to limit the number of bytes of /// the unique identifier to a fixed size (16 bytes). pub fn fullyQualifiedNameHash(self: Decl) Hash { // Right now we only have ZIRModule as the source. So this is simply the // relative name of the decl. return hashSimpleName(mem.spanZ(self.name)); } pub fn typedValue(self: *Decl) error{AnalysisFail}!TypedValue { const tvm = self.typedValueManaged() orelse return error.AnalysisFail; return tvm.typed_value; } pub fn value(self: *Decl) error{AnalysisFail}!Value { return (try self.typedValue()).val; } pub fn dump(self: *Decl) void { const loc = std.zig.findLineColumn(self.scope.source.bytes, self.src); std.debug.warn("{}:{}:{} name={} status={}", .{ self.scope.sub_file_path, loc.line + 1, loc.column + 1, mem.spanZ(self.name), @tagName(self.analysis), }); if (self.typedValueManaged()) |tvm| { std.debug.warn(" ty={} val={}", .{ tvm.typed_value.ty, tvm.typed_value.val }); } std.debug.warn("\n", .{}); } fn typedValueManaged(self: *Decl) ?*TypedValue.Managed { switch (self.typed_value) { .most_recent => |*x| return x, .never_succeeded => return null, } } fn removeDependant(self: *Decl, other: *Decl) void { for (self.dependants.items) |item, i| { if (item == other) { _ = self.dependants.swapRemove(i); return; } } unreachable; } fn removeDependency(self: *Decl, other: *Decl) void { for (self.dependencies.items) |item, i| { if (item == other) { _ = self.dependencies.swapRemove(i); return; } } unreachable; } }; /// Fn struct memory is owned by the Decl's TypedValue.Managed arena allocator. pub const Fn = struct { /// This memory owned by the Decl's TypedValue.Managed arena allocator. fn_type: Type, analysis: union(enum) { /// The value is the source instruction. queued: *zir.Inst.Fn, in_progress: *Analysis, /// There will be a corresponding ErrorMsg in Module.failed_decls sema_failure, /// This Fn might be OK but it depends on another Decl which did not successfully complete /// semantic analysis. dependency_failure, success: Body, }, owner_decl: *Decl, /// This memory is temporary and points to stack memory for the duration /// of Fn analysis. pub const Analysis = struct { inner_block: Scope.Block, /// TODO Performance optimization idea: instead of this inst_table, /// use a field in the zir.Inst instead to track corresponding instructions inst_table: std.AutoHashMap(*zir.Inst, *Inst), needed_inst_capacity: usize, }; }; pub const Scope = struct { tag: Tag, pub fn cast(base: *Scope, comptime T: type) ?*T { if (base.tag != T.base_tag) return null; return @fieldParentPtr(T, "base", base); } /// Asserts the scope has a parent which is a DeclAnalysis and /// returns the arena Allocator. pub fn arena(self: *Scope) *Allocator { switch (self.tag) { .block => return self.cast(Block).?.arena, .decl => return &self.cast(DeclAnalysis).?.arena.allocator, .zir_module => return &self.cast(ZIRModule).?.contents.module.arena.allocator, } } /// Asserts the scope has a parent which is a DeclAnalysis and /// returns the Decl. pub fn decl(self: *Scope) ?*Decl { return switch (self.tag) { .block => self.cast(Block).?.decl, .decl => self.cast(DeclAnalysis).?.decl, .zir_module => null, }; } /// Asserts the scope has a parent which is a ZIRModule and /// returns it. pub fn namespace(self: *Scope) *ZIRModule { switch (self.tag) { .block => return self.cast(Block).?.decl.scope, .decl => return self.cast(DeclAnalysis).?.decl.scope, .zir_module => return self.cast(ZIRModule).?, } } pub fn dumpInst(self: *Scope, inst: *Inst) void { const zir_module = self.namespace(); const loc = std.zig.findLineColumn(zir_module.source.bytes, inst.src); std.debug.warn("{}:{}:{}: {}: ty={}\n", .{ zir_module.sub_file_path, loc.line + 1, loc.column + 1, @tagName(inst.tag), inst.ty, }); } pub const Tag = enum { zir_module, block, decl, }; pub const ZIRModule = struct { pub const base_tag: Tag = .zir_module; base: Scope = Scope{ .tag = base_tag }, /// Relative to the owning package's root_src_dir. /// Reference to external memory, not owned by ZIRModule. sub_file_path: []const u8, source: union(enum) { unloaded: void, bytes: [:0]const u8, }, contents: union { not_available: void, module: *zir.Module, }, status: enum { never_loaded, unloaded_success, unloaded_parse_failure, unloaded_sema_failure, loaded_sema_failure, loaded_success, }, pub fn unload(self: *ZIRModule, allocator: *Allocator) void { switch (self.status) { .never_loaded, .unloaded_parse_failure, .unloaded_sema_failure, .unloaded_success, => {}, .loaded_success => { self.contents.module.deinit(allocator); allocator.destroy(self.contents.module); self.status = .unloaded_success; }, .loaded_sema_failure => { self.contents.module.deinit(allocator); allocator.destroy(self.contents.module); self.status = .unloaded_sema_failure; }, } switch (self.source) { .bytes => |bytes| { allocator.free(bytes); self.source = .{ .unloaded = {} }; }, .unloaded => {}, } } pub fn deinit(self: *ZIRModule, allocator: *Allocator) void { self.unload(allocator); self.* = undefined; } pub fn dumpSrc(self: *ZIRModule, src: usize) void { const loc = std.zig.findLineColumn(self.source.bytes, src); std.debug.warn("{}:{}:{}\n", .{ self.sub_file_path, loc.line + 1, loc.column + 1 }); } }; /// This is a temporary structure, references to it are valid only /// during semantic analysis of the block. pub const Block = struct { pub const base_tag: Tag = .block; base: Scope = Scope{ .tag = base_tag }, func: *Fn, decl: *Decl, instructions: ArrayListUnmanaged(*Inst), /// Points to the arena allocator of DeclAnalysis arena: *Allocator, }; /// This is a temporary structure, references to it are valid only /// during semantic analysis of the decl. pub const DeclAnalysis = struct { pub const base_tag: Tag = .decl; base: Scope = Scope{ .tag = base_tag }, decl: *Decl, arena: std.heap.ArenaAllocator, }; }; pub const Body = struct { instructions: []*Inst, }; pub const AllErrors = struct { arena: std.heap.ArenaAllocator.State, list: []const Message, pub const Message = struct { src_path: []const u8, line: usize, column: usize, byte_offset: usize, msg: []const u8, }; pub fn deinit(self: *AllErrors, allocator: *Allocator) void { self.arena.promote(allocator).deinit(); } fn add( arena: *std.heap.ArenaAllocator, errors: *std.ArrayList(Message), sub_file_path: []const u8, source: []const u8, simple_err_msg: ErrorMsg, ) !void { const loc = std.zig.findLineColumn(source, simple_err_msg.byte_offset); try errors.append(.{ .src_path = try arena.allocator.dupe(u8, sub_file_path), .msg = try arena.allocator.dupe(u8, simple_err_msg.msg), .byte_offset = simple_err_msg.byte_offset, .line = loc.line, .column = loc.column, }); } }; pub const InitOptions = struct { target: std.Target, root_pkg: *Package, output_mode: std.builtin.OutputMode, bin_file_dir: ?std.fs.Dir = null, bin_file_path: []const u8, link_mode: ?std.builtin.LinkMode = null, object_format: ?std.builtin.ObjectFormat = null, optimize_mode: std.builtin.Mode = .Debug, }; pub fn init(gpa: *Allocator, options: InitOptions) !Module { const root_scope = try gpa.create(Scope.ZIRModule); errdefer gpa.destroy(root_scope); root_scope.* = .{ .sub_file_path = options.root_pkg.root_src_path, .source = .{ .unloaded = {} }, .contents = .{ .not_available = {} }, .status = .never_loaded, }; const bin_file_dir = options.bin_file_dir orelse std.fs.cwd(); var bin_file = try link.openBinFilePath(gpa, bin_file_dir, options.bin_file_path, .{ .target = options.target, .output_mode = options.output_mode, .link_mode = options.link_mode orelse .Static, .object_format = options.object_format orelse options.target.getObjectFormat(), }); errdefer bin_file.deinit(); return Module{ .allocator = gpa, .root_pkg = options.root_pkg, .root_scope = root_scope, .bin_file_dir = bin_file_dir, .bin_file_path = options.bin_file_path, .bin_file = bin_file, .optimize_mode = options.optimize_mode, .decl_table = std.AutoHashMap(Decl.Hash, *Decl).init(gpa), .decl_exports = std.AutoHashMap(*Decl, []*Export).init(gpa), .export_owners = std.AutoHashMap(*Decl, []*Export).init(gpa), .failed_decls = std.AutoHashMap(*Decl, *ErrorMsg).init(gpa), .failed_files = std.AutoHashMap(*Scope.ZIRModule, *ErrorMsg).init(gpa), .failed_exports = std.AutoHashMap(*Export, *ErrorMsg).init(gpa), .work_queue = std.fifo.LinearFifo(WorkItem, .Dynamic).init(gpa), }; } pub fn deinit(self: *Module) void { self.bin_file.deinit(); const allocator = self.allocator; self.deletion_set.deinit(allocator); self.work_queue.deinit(); { var it = self.decl_table.iterator(); while (it.next()) |kv| { kv.value.destroy(allocator); } self.decl_table.deinit(); } { var it = self.failed_decls.iterator(); while (it.next()) |kv| { kv.value.destroy(allocator); } self.failed_decls.deinit(); } { var it = self.failed_files.iterator(); while (it.next()) |kv| { kv.value.destroy(allocator); } self.failed_files.deinit(); } { var it = self.failed_exports.iterator(); while (it.next()) |kv| { kv.value.destroy(allocator); } self.failed_exports.deinit(); } { var it = self.decl_exports.iterator(); while (it.next()) |kv| { const export_list = kv.value; allocator.free(export_list); } self.decl_exports.deinit(); } { var it = self.export_owners.iterator(); while (it.next()) |kv| { freeExportList(allocator, kv.value); } self.export_owners.deinit(); } { self.root_scope.deinit(allocator); allocator.destroy(self.root_scope); } self.* = undefined; } fn freeExportList(allocator: *Allocator, export_list: []*Export) void { for (export_list) |exp| { allocator.destroy(exp); } allocator.free(export_list); } pub fn target(self: Module) std.Target { return self.bin_file.options.target; } /// Detect changes to source files, perform semantic analysis, and update the output files. pub fn update(self: *Module) !void { self.generation += 1; // TODO Use the cache hash file system to detect which source files changed. // Here we simulate a full cache miss. // Analyze the root source file now. // Source files could have been loaded for any reason; to force a refresh we unload now. self.root_scope.unload(self.allocator); self.analyzeRoot(self.root_scope) catch |err| switch (err) { error.AnalysisFail => { assert(self.totalErrorCount() != 0); }, else => |e| return e, }; try self.performAllTheWork(); // Process the deletion set. while (self.deletion_set.popOrNull()) |decl| { if (decl.dependants.items.len != 0) { decl.deletion_flag = false; continue; } try self.deleteDecl(decl); } // If there are any errors, we anticipate the source files being loaded // to report error messages. Otherwise we unload all source files to save memory. if (self.totalErrorCount() == 0) { self.root_scope.unload(self.allocator); } try self.bin_file.flush(); self.link_error_flags = self.bin_file.error_flags; } /// Having the file open for writing is problematic as far as executing the /// binary is concerned. This will remove the write flag, or close the file, /// or whatever is needed so that it can be executed. /// After this, one must call` makeFileWritable` before calling `update`. pub fn makeBinFileExecutable(self: *Module) !void { return self.bin_file.makeExecutable(); } pub fn makeBinFileWritable(self: *Module) !void { return self.bin_file.makeWritable(self.bin_file_dir, self.bin_file_path); } pub fn totalErrorCount(self: *Module) usize { return self.failed_decls.size + self.failed_files.size + self.failed_exports.size + @boolToInt(self.link_error_flags.no_entry_point_found); } pub fn getAllErrorsAlloc(self: *Module) !AllErrors { var arena = std.heap.ArenaAllocator.init(self.allocator); errdefer arena.deinit(); var errors = std.ArrayList(AllErrors.Message).init(self.allocator); defer errors.deinit(); { var it = self.failed_files.iterator(); while (it.next()) |kv| { const scope = kv.key; const err_msg = kv.value; const source = try self.getSource(scope); try AllErrors.add(&arena, &errors, scope.sub_file_path, source, err_msg.*); } } { var it = self.failed_decls.iterator(); while (it.next()) |kv| { const decl = kv.key; const err_msg = kv.value; const source = try self.getSource(decl.scope); try AllErrors.add(&arena, &errors, decl.scope.sub_file_path, source, err_msg.*); } } { var it = self.failed_exports.iterator(); while (it.next()) |kv| { const decl = kv.key.owner_decl; const err_msg = kv.value; const source = try self.getSource(decl.scope); try AllErrors.add(&arena, &errors, decl.scope.sub_file_path, source, err_msg.*); } } if (self.link_error_flags.no_entry_point_found) { try errors.append(.{ .src_path = self.root_pkg.root_src_path, .line = 0, .column = 0, .byte_offset = 0, .msg = try std.fmt.allocPrint(&arena.allocator, "no entry point found", .{}), }); } assert(errors.items.len == self.totalErrorCount()); return AllErrors{ .list = try arena.allocator.dupe(AllErrors.Message, errors.items), .arena = arena.state, }; } const InnerError = error{ OutOfMemory, AnalysisFail }; pub fn performAllTheWork(self: *Module) error{OutOfMemory}!void { while (self.work_queue.readItem()) |work_item| switch (work_item) { .codegen_decl => |decl| switch (decl.analysis) { .in_progress => unreachable, .outdated => unreachable, .sema_failure, .codegen_failure, .dependency_failure, => continue, .complete, .codegen_failure_retryable => { if (decl.typed_value.most_recent.typed_value.val.cast(Value.Payload.Function)) |payload| { switch (payload.func.analysis) { .queued => self.analyzeFnBody(decl, payload.func) catch |err| switch (err) { error.AnalysisFail => { if (payload.func.analysis == .queued) { payload.func.analysis = .dependency_failure; } continue; }, else => |e| return e, }, .in_progress => unreachable, .sema_failure, .dependency_failure => continue, .success => {}, } } assert(decl.typed_value.most_recent.typed_value.ty.hasCodeGenBits()); self.bin_file.updateDecl(self, decl) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => { decl.analysis = .dependency_failure; }, else => { try self.failed_decls.ensureCapacity(self.failed_decls.size + 1); self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create( self.allocator, decl.src, "unable to codegen: {}", .{@errorName(err)}, )); decl.analysis = .codegen_failure_retryable; }, }; }, }, .re_analyze_decl => |decl| switch (decl.analysis) { .in_progress => unreachable, .sema_failure, .codegen_failure, .dependency_failure, .complete, .codegen_failure_retryable, => continue, .outdated => { const zir_module = self.getSrcModule(decl.scope) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { try self.failed_decls.ensureCapacity(self.failed_decls.size + 1); self.failed_decls.putAssumeCapacityNoClobber(decl, try ErrorMsg.create( self.allocator, decl.src, "unable to load source file '{}': {}", .{ decl.scope.sub_file_path, @errorName(err) }, )); decl.analysis = .codegen_failure_retryable; continue; }, }; const decl_name = mem.spanZ(decl.name); // We already detected deletions, so we know this will be found. const src_decl = zir_module.findDecl(decl_name).?; self.reAnalyzeDecl(decl, src_decl) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => continue, }; }, }, }; } fn declareDeclDependency(self: *Module, depender: *Decl, dependee: *Decl) !void { try depender.dependencies.ensureCapacity(self.allocator, depender.dependencies.items.len + 1); try dependee.dependants.ensureCapacity(self.allocator, dependee.dependants.items.len + 1); for (depender.dependencies.items) |item| { if (item == dependee) break; // Already in the set. } else { depender.dependencies.appendAssumeCapacity(dependee); } for (dependee.dependants.items) |item| { if (item == depender) break; // Already in the set. } else { dependee.dependants.appendAssumeCapacity(depender); } } fn getSource(self: *Module, root_scope: *Scope.ZIRModule) ![:0]const u8 { switch (root_scope.source) { .unloaded => { const source = try self.root_pkg.root_src_dir.readFileAllocOptions( self.allocator, root_scope.sub_file_path, std.math.maxInt(u32), 1, 0, ); root_scope.source = .{ .bytes = source }; return source; }, .bytes => |bytes| return bytes, } } fn getSrcModule(self: *Module, root_scope: *Scope.ZIRModule) !*zir.Module { switch (root_scope.status) { .never_loaded, .unloaded_success => { try self.failed_files.ensureCapacity(self.failed_files.size + 1); const source = try self.getSource(root_scope); var keep_zir_module = false; const zir_module = try self.allocator.create(zir.Module); defer if (!keep_zir_module) self.allocator.destroy(zir_module); zir_module.* = try zir.parse(self.allocator, source); defer if (!keep_zir_module) zir_module.deinit(self.allocator); if (zir_module.error_msg) |src_err_msg| { self.failed_files.putAssumeCapacityNoClobber( root_scope, try ErrorMsg.create(self.allocator, src_err_msg.byte_offset, "{}", .{src_err_msg.msg}), ); root_scope.status = .unloaded_parse_failure; return error.AnalysisFail; } root_scope.status = .loaded_success; root_scope.contents = .{ .module = zir_module }; keep_zir_module = true; return zir_module; }, .unloaded_parse_failure, .unloaded_sema_failure, => return error.AnalysisFail, .loaded_success, .loaded_sema_failure => return root_scope.contents.module, } } fn analyzeRoot(self: *Module, root_scope: *Scope.ZIRModule) !void { switch (root_scope.status) { .never_loaded => { const src_module = try self.getSrcModule(root_scope); // Here we ensure enough queue capacity to store all the decls, so that later we can use // appendAssumeCapacity. try self.work_queue.ensureUnusedCapacity(src_module.decls.len); for (src_module.decls) |decl| { if (decl.cast(zir.Inst.Export)) |export_inst| { _ = try self.resolveDecl(&root_scope.base, &export_inst.base); } } }, .unloaded_parse_failure, .unloaded_sema_failure, .unloaded_success, .loaded_sema_failure, .loaded_success, => { const src_module = try self.getSrcModule(root_scope); var exports_to_resolve = std.ArrayList(*zir.Inst).init(self.allocator); defer exports_to_resolve.deinit(); // Keep track of the decls that we expect to see in this file so that // we know which ones have been deleted. var deleted_decls = std.AutoHashMap(*Decl, void).init(self.allocator); defer deleted_decls.deinit(); try deleted_decls.ensureCapacity(self.decl_table.size); { var it = self.decl_table.iterator(); while (it.next()) |kv| { deleted_decls.putAssumeCapacityNoClobber(kv.value, {}); } } for (src_module.decls) |src_decl| { const name_hash = Decl.hashSimpleName(src_decl.name); if (self.decl_table.get(name_hash)) |kv| { const decl = kv.value; deleted_decls.removeAssertDiscard(decl); const new_contents_hash = Decl.hashSimpleName(src_decl.contents); //std.debug.warn("'{}' contents: '{}'\n", .{ src_decl.name, src_decl.contents }); if (!mem.eql(u8, &new_contents_hash, &decl.contents_hash)) { //std.debug.warn("'{}' {x} => {x}\n", .{ src_decl.name, decl.contents_hash, new_contents_hash }); try self.markOutdatedDecl(decl); decl.contents_hash = new_contents_hash; } } else if (src_decl.cast(zir.Inst.Export)) |export_inst| { try exports_to_resolve.append(&export_inst.base); } } { // Handle explicitly deleted decls from the source code. Not to be confused // with when we delete decls because they are no longer referenced. var it = deleted_decls.iterator(); while (it.next()) |kv| { //std.debug.warn("noticed '{}' deleted from source\n", .{kv.key.name}); try self.deleteDecl(kv.key); } } for (exports_to_resolve.items) |export_inst| { _ = try self.resolveDecl(&root_scope.base, export_inst); } }, } } fn deleteDecl(self: *Module, decl: *Decl) !void { try self.deletion_set.ensureCapacity(self.allocator, self.deletion_set.items.len + decl.dependencies.items.len); //std.debug.warn("deleting decl '{}'\n", .{decl.name}); const name_hash = decl.fullyQualifiedNameHash(); self.decl_table.removeAssertDiscard(name_hash); // Remove itself from its dependencies, because we are about to destroy the decl pointer. for (decl.dependencies.items) |dep| { dep.removeDependant(decl); if (dep.dependants.items.len == 0) { // We don't recursively perform a deletion here, because during the update, // another reference to it may turn up. assert(!dep.deletion_flag); dep.deletion_flag = true; self.deletion_set.appendAssumeCapacity(dep); } } // Anything that depends on this deleted decl certainly needs to be re-analyzed. for (decl.dependants.items) |dep| { dep.removeDependency(decl); if (dep.analysis != .outdated) { // TODO Move this failure possibility to the top of the function. try self.markOutdatedDecl(dep); } } if (self.failed_decls.remove(decl)) |entry| { entry.value.destroy(self.allocator); } self.deleteDeclExports(decl); self.bin_file.freeDecl(decl); decl.destroy(self.allocator); } /// Delete all the Export objects that are caused by this Decl. Re-analysis of /// this Decl will cause them to be re-created (or not). fn deleteDeclExports(self: *Module, decl: *Decl) void { const kv = self.export_owners.remove(decl) orelse return; for (kv.value) |exp| { if (self.decl_exports.get(exp.exported_decl)) |decl_exports_kv| { // Remove exports with owner_decl matching the regenerating decl. const list = decl_exports_kv.value; var i: usize = 0; var new_len = list.len; while (i < new_len) { if (list[i].owner_decl == decl) { mem.copyBackwards(*Export, list[i..], list[i + 1 .. new_len]); new_len -= 1; } else { i += 1; } } decl_exports_kv.value = self.allocator.shrink(list, new_len); if (new_len == 0) { self.decl_exports.removeAssertDiscard(exp.exported_decl); } } self.bin_file.deleteExport(exp.link); self.allocator.destroy(exp); } self.allocator.free(kv.value); } fn analyzeFnBody(self: *Module, decl: *Decl, func: *Fn) !void { // Use the Decl's arena for function memory. var arena = decl.typed_value.most_recent.arena.?.promote(self.allocator); defer decl.typed_value.most_recent.arena.?.* = arena.state; var analysis: Fn.Analysis = .{ .inner_block = .{ .func = func, .decl = decl, .instructions = .{}, .arena = &arena.allocator, }, .needed_inst_capacity = 0, .inst_table = std.AutoHashMap(*zir.Inst, *Inst).init(self.allocator), }; defer analysis.inner_block.instructions.deinit(self.allocator); defer analysis.inst_table.deinit(); const fn_inst = func.analysis.queued; func.analysis = .{ .in_progress = &analysis }; try self.analyzeBody(&analysis.inner_block.base, fn_inst.positionals.body); func.analysis = .{ .success = .{ .instructions = try arena.allocator.dupe(*Inst, analysis.inner_block.instructions.items), }, }; } fn reAnalyzeDecl(self: *Module, decl: *Decl, old_inst: *zir.Inst) InnerError!void { switch (decl.analysis) { .in_progress => unreachable, .dependency_failure, .sema_failure, .codegen_failure, .codegen_failure_retryable, .complete, => return, .outdated => {}, // Decl re-analysis } //std.debug.warn("re-analyzing {}\n", .{decl.name}); decl.src = old_inst.src; // The exports this Decl performs will be re-discovered, so we remove them here // prior to re-analysis. self.deleteDeclExports(decl); // Dependencies will be re-discovered, so we remove them here prior to re-analysis. for (decl.dependencies.items) |dep| { dep.removeDependant(decl); if (dep.dependants.items.len == 0) { // We don't perform a deletion here, because this Decl or another one // may end up referencing it before the update is complete. assert(!dep.deletion_flag); dep.deletion_flag = true; try self.deletion_set.append(self.allocator, dep); } } decl.dependencies.shrink(self.allocator, 0); var decl_scope: Scope.DeclAnalysis = .{ .decl = decl, .arena = std.heap.ArenaAllocator.init(self.allocator), }; errdefer decl_scope.arena.deinit(); const typed_value = self.analyzeInstConst(&decl_scope.base, old_inst) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => { switch (decl.analysis) { .in_progress => decl.analysis = .dependency_failure, else => {}, } decl.generation = self.generation; return error.AnalysisFail; }, }; const arena_state = try decl_scope.arena.allocator.create(std.heap.ArenaAllocator.State); arena_state.* = decl_scope.arena.state; var prev_type_has_bits = false; var type_changed = true; if (decl.typedValueManaged()) |tvm| { prev_type_has_bits = tvm.typed_value.ty.hasCodeGenBits(); type_changed = !tvm.typed_value.ty.eql(typed_value.ty); tvm.deinit(self.allocator); } decl.typed_value = .{ .most_recent = .{ .typed_value = typed_value, .arena = arena_state, }, }; decl.analysis = .complete; decl.generation = self.generation; if (typed_value.ty.hasCodeGenBits()) { // We don't fully codegen the decl until later, but we do need to reserve a global // offset table index for it. This allows us to codegen decls out of dependency order, // increasing how many computations can be done in parallel. try self.bin_file.allocateDeclIndexes(decl); try self.work_queue.writeItem(.{ .codegen_decl = decl }); } else if (prev_type_has_bits) { self.bin_file.freeDecl(decl); } // If the decl is a function, and the type is the same, we do not need // to chase the dependants. if (type_changed or typed_value.val.tag() != .function) { for (decl.dependants.items) |dep| { switch (dep.analysis) { .in_progress => unreachable, .outdated => continue, // already queued for update .dependency_failure, .sema_failure, .codegen_failure, .codegen_failure_retryable, .complete, => if (dep.generation != self.generation) { try self.markOutdatedDecl(dep); }, } } } } fn markOutdatedDecl(self: *Module, decl: *Decl) !void { //std.debug.warn("mark {} outdated\n", .{decl.name}); try self.work_queue.writeItem(.{ .re_analyze_decl = decl }); if (self.failed_decls.remove(decl)) |entry| { entry.value.destroy(self.allocator); } decl.analysis = .outdated; } fn resolveDecl(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Decl { const hash = Decl.hashSimpleName(old_inst.name); if (self.decl_table.get(hash)) |kv| { const decl = kv.value; try self.reAnalyzeDecl(decl, old_inst); return decl; } else if (old_inst.cast(zir.Inst.DeclVal)) |decl_val| { // This is just a named reference to another decl. return self.analyzeDeclVal(scope, decl_val); } else { const new_decl = blk: { try self.decl_table.ensureCapacity(self.decl_table.size + 1); const new_decl = try self.allocator.create(Decl); errdefer self.allocator.destroy(new_decl); const name = try mem.dupeZ(self.allocator, u8, old_inst.name); errdefer self.allocator.free(name); new_decl.* = .{ .name = name, .scope = scope.namespace(), .src = old_inst.src, .typed_value = .{ .never_succeeded = {} }, .analysis = .in_progress, .deletion_flag = false, .contents_hash = Decl.hashSimpleName(old_inst.contents), .link = link.ElfFile.TextBlock.empty, .generation = 0, }; self.decl_table.putAssumeCapacityNoClobber(hash, new_decl); break :blk new_decl; }; var decl_scope: Scope.DeclAnalysis = .{ .decl = new_decl, .arena = std.heap.ArenaAllocator.init(self.allocator), }; errdefer decl_scope.arena.deinit(); const typed_value = self.analyzeInstConst(&decl_scope.base, old_inst) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.AnalysisFail => { switch (new_decl.analysis) { .in_progress => new_decl.analysis = .dependency_failure, else => {}, } new_decl.generation = self.generation; return error.AnalysisFail; }, }; const arena_state = try decl_scope.arena.allocator.create(std.heap.ArenaAllocator.State); arena_state.* = decl_scope.arena.state; new_decl.typed_value = .{ .most_recent = .{ .typed_value = typed_value, .arena = arena_state, }, }; new_decl.analysis = .complete; new_decl.generation = self.generation; if (typed_value.ty.hasCodeGenBits()) { // We don't fully codegen the decl until later, but we do need to reserve a global // offset table index for it. This allows us to codegen decls out of dependency order, // increasing how many computations can be done in parallel. try self.bin_file.allocateDeclIndexes(new_decl); try self.work_queue.writeItem(.{ .codegen_decl = new_decl }); } return new_decl; } } /// Declares a dependency on the decl. fn resolveCompleteDecl(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Decl { const decl = try self.resolveDecl(scope, old_inst); switch (decl.analysis) { .in_progress => unreachable, .outdated => unreachable, .dependency_failure, .sema_failure, .codegen_failure, .codegen_failure_retryable, => return error.AnalysisFail, .complete => {}, } if (scope.decl()) |scope_decl| { try self.declareDeclDependency(scope_decl, decl); } return decl; } fn resolveInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Inst { if (scope.cast(Scope.Block)) |block| { if (block.func.analysis.in_progress.inst_table.get(old_inst)) |kv| { return kv.value; } } const decl = try self.resolveCompleteDecl(scope, old_inst); const decl_ref = try self.analyzeDeclRef(scope, old_inst.src, decl); return self.analyzeDeref(scope, old_inst.src, decl_ref, old_inst.src); } fn requireRuntimeBlock(self: *Module, scope: *Scope, src: usize) !*Scope.Block { return scope.cast(Scope.Block) orelse return self.fail(scope, src, "instruction illegal outside function body", .{}); } fn resolveInstConst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!TypedValue { const new_inst = try self.resolveInst(scope, old_inst); const val = try self.resolveConstValue(scope, new_inst); return TypedValue{ .ty = new_inst.ty, .val = val, }; } fn resolveConstValue(self: *Module, scope: *Scope, base: *Inst) !Value { return (try self.resolveDefinedValue(scope, base)) orelse return self.fail(scope, base.src, "unable to resolve comptime value", .{}); } fn resolveDefinedValue(self: *Module, scope: *Scope, base: *Inst) !?Value { if (base.value()) |val| { if (val.isUndef()) { return self.fail(scope, base.src, "use of undefined value here causes undefined behavior", .{}); } return val; } return null; } fn resolveConstString(self: *Module, scope: *Scope, old_inst: *zir.Inst) ![]u8 { const new_inst = try self.resolveInst(scope, old_inst); const wanted_type = Type.initTag(.const_slice_u8); const coerced_inst = try self.coerce(scope, wanted_type, new_inst); const val = try self.resolveConstValue(scope, coerced_inst); return val.toAllocatedBytes(scope.arena()); } fn resolveType(self: *Module, scope: *Scope, old_inst: *zir.Inst) !Type { const new_inst = try self.resolveInst(scope, old_inst); const wanted_type = Type.initTag(.@"type"); const coerced_inst = try self.coerce(scope, wanted_type, new_inst); const val = try self.resolveConstValue(scope, coerced_inst); return val.toType(); } fn analyzeExport(self: *Module, scope: *Scope, export_inst: *zir.Inst.Export) InnerError!void { try self.decl_exports.ensureCapacity(self.decl_exports.size + 1); try self.export_owners.ensureCapacity(self.export_owners.size + 1); const symbol_name = try self.resolveConstString(scope, export_inst.positionals.symbol_name); const exported_decl = try self.resolveCompleteDecl(scope, export_inst.positionals.value); const typed_value = exported_decl.typed_value.most_recent.typed_value; switch (typed_value.ty.zigTypeTag()) { .Fn => {}, else => return self.fail( scope, export_inst.positionals.value.src, "unable to export type '{}'", .{typed_value.ty}, ), } const new_export = try self.allocator.create(Export); errdefer self.allocator.destroy(new_export); const owner_decl = scope.decl().?; new_export.* = .{ .options = .{ .name = symbol_name }, .src = export_inst.base.src, .link = .{}, .owner_decl = owner_decl, .exported_decl = exported_decl, .status = .in_progress, }; // Add to export_owners table. const eo_gop = self.export_owners.getOrPut(owner_decl) catch unreachable; if (!eo_gop.found_existing) { eo_gop.kv.value = &[0]*Export{}; } eo_gop.kv.value = try self.allocator.realloc(eo_gop.kv.value, eo_gop.kv.value.len + 1); eo_gop.kv.value[eo_gop.kv.value.len - 1] = new_export; errdefer eo_gop.kv.value = self.allocator.shrink(eo_gop.kv.value, eo_gop.kv.value.len - 1); // Add to exported_decl table. const de_gop = self.decl_exports.getOrPut(exported_decl) catch unreachable; if (!de_gop.found_existing) { de_gop.kv.value = &[0]*Export{}; } de_gop.kv.value = try self.allocator.realloc(de_gop.kv.value, de_gop.kv.value.len + 1); de_gop.kv.value[de_gop.kv.value.len - 1] = new_export; errdefer de_gop.kv.value = self.allocator.shrink(de_gop.kv.value, de_gop.kv.value.len - 1); self.bin_file.updateDeclExports(self, exported_decl, de_gop.kv.value) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { try self.failed_exports.ensureCapacity(self.failed_exports.size + 1); self.failed_exports.putAssumeCapacityNoClobber(new_export, try ErrorMsg.create( self.allocator, export_inst.base.src, "unable to export: {}", .{@errorName(err)}, )); new_export.status = .failed_retryable; }, }; } /// TODO should not need the cast on the last parameter at the callsites fn addNewInstArgs( self: *Module, block: *Scope.Block, src: usize, ty: Type, comptime T: type, args: Inst.Args(T), ) !*Inst { const inst = try self.addNewInst(block, src, ty, T); inst.args = args; return &inst.base; } fn addNewInst(self: *Module, block: *Scope.Block, src: usize, ty: Type, comptime T: type) !*T { const inst = try block.arena.create(T); inst.* = .{ .base = .{ .tag = T.base_tag, .ty = ty, .src = src, }, .args = undefined, }; try block.instructions.append(self.allocator, &inst.base); return inst; } fn constInst(self: *Module, scope: *Scope, src: usize, typed_value: TypedValue) !*Inst { const const_inst = try scope.arena().create(Inst.Constant); const_inst.* = .{ .base = .{ .tag = Inst.Constant.base_tag, .ty = typed_value.ty, .src = src, }, .val = typed_value.val, }; return &const_inst.base; } fn constStr(self: *Module, scope: *Scope, src: usize, str: []const u8) !*Inst { const ty_payload = try scope.arena().create(Type.Payload.Array_u8_Sentinel0); ty_payload.* = .{ .len = str.len }; const bytes_payload = try scope.arena().create(Value.Payload.Bytes); bytes_payload.* = .{ .data = str }; return self.constInst(scope, src, .{ .ty = Type.initPayload(&ty_payload.base), .val = Value.initPayload(&bytes_payload.base), }); } fn constType(self: *Module, scope: *Scope, src: usize, ty: Type) !*Inst { return self.constInst(scope, src, .{ .ty = Type.initTag(.type), .val = try ty.toValue(scope.arena()), }); } fn constVoid(self: *Module, scope: *Scope, src: usize) !*Inst { return self.constInst(scope, src, .{ .ty = Type.initTag(.void), .val = Value.initTag(.the_one_possible_value), }); } fn constUndef(self: *Module, scope: *Scope, src: usize, ty: Type) !*Inst { return self.constInst(scope, src, .{ .ty = ty, .val = Value.initTag(.undef), }); } fn constBool(self: *Module, scope: *Scope, src: usize, v: bool) !*Inst { return self.constInst(scope, src, .{ .ty = Type.initTag(.bool), .val = ([2]Value{ Value.initTag(.bool_false), Value.initTag(.bool_true) })[@boolToInt(v)], }); } fn constIntUnsigned(self: *Module, scope: *Scope, src: usize, ty: Type, int: u64) !*Inst { const int_payload = try scope.arena().create(Value.Payload.Int_u64); int_payload.* = .{ .int = int }; return self.constInst(scope, src, .{ .ty = ty, .val = Value.initPayload(&int_payload.base), }); } fn constIntSigned(self: *Module, scope: *Scope, src: usize, ty: Type, int: i64) !*Inst { const int_payload = try scope.arena().create(Value.Payload.Int_i64); int_payload.* = .{ .int = int }; return self.constInst(scope, src, .{ .ty = ty, .val = Value.initPayload(&int_payload.base), }); } fn constIntBig(self: *Module, scope: *Scope, src: usize, ty: Type, big_int: BigIntConst) !*Inst { const val_payload = if (big_int.positive) blk: { if (big_int.to(u64)) |x| { return self.constIntUnsigned(scope, src, ty, x); } else |err| switch (err) { error.NegativeIntoUnsigned => unreachable, error.TargetTooSmall => {}, // handled below } const big_int_payload = try scope.arena().create(Value.Payload.IntBigPositive); big_int_payload.* = .{ .limbs = big_int.limbs }; break :blk &big_int_payload.base; } else blk: { if (big_int.to(i64)) |x| { return self.constIntSigned(scope, src, ty, x); } else |err| switch (err) { error.NegativeIntoUnsigned => unreachable, error.TargetTooSmall => {}, // handled below } const big_int_payload = try scope.arena().create(Value.Payload.IntBigNegative); big_int_payload.* = .{ .limbs = big_int.limbs }; break :blk &big_int_payload.base; }; return self.constInst(scope, src, .{ .ty = ty, .val = Value.initPayload(val_payload), }); } fn analyzeInstConst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!TypedValue { const new_inst = try self.analyzeInst(scope, old_inst); return TypedValue{ .ty = new_inst.ty, .val = try self.resolveConstValue(scope, new_inst), }; } fn analyzeInst(self: *Module, scope: *Scope, old_inst: *zir.Inst) InnerError!*Inst { switch (old_inst.tag) { .breakpoint => return self.analyzeInstBreakpoint(scope, old_inst.cast(zir.Inst.Breakpoint).?), .call => return self.analyzeInstCall(scope, old_inst.cast(zir.Inst.Call).?), .compileerror => return self.analyzeInstCompileError(scope, old_inst.cast(zir.Inst.CompileError).?), .declref => return self.analyzeInstDeclRef(scope, old_inst.cast(zir.Inst.DeclRef).?), .declval => return self.analyzeInstDeclVal(scope, old_inst.cast(zir.Inst.DeclVal).?), .str => { const bytes = old_inst.cast(zir.Inst.Str).?.positionals.bytes; // The bytes references memory inside the ZIR module, which can get deallocated // after semantic analysis is complete. We need the memory to be in the Decl's arena. const arena_bytes = try scope.arena().dupe(u8, bytes); return self.constStr(scope, old_inst.src, arena_bytes); }, .int => { const big_int = old_inst.cast(zir.Inst.Int).?.positionals.int; return self.constIntBig(scope, old_inst.src, Type.initTag(.comptime_int), big_int); }, .ptrtoint => return self.analyzeInstPtrToInt(scope, old_inst.cast(zir.Inst.PtrToInt).?), .fieldptr => return self.analyzeInstFieldPtr(scope, old_inst.cast(zir.Inst.FieldPtr).?), .deref => return self.analyzeInstDeref(scope, old_inst.cast(zir.Inst.Deref).?), .as => return self.analyzeInstAs(scope, old_inst.cast(zir.Inst.As).?), .@"asm" => return self.analyzeInstAsm(scope, old_inst.cast(zir.Inst.Asm).?), .@"unreachable" => return self.analyzeInstUnreachable(scope, old_inst.cast(zir.Inst.Unreachable).?), .@"return" => return self.analyzeInstRet(scope, old_inst.cast(zir.Inst.Return).?), .@"fn" => return self.analyzeInstFn(scope, old_inst.cast(zir.Inst.Fn).?), .@"export" => { try self.analyzeExport(scope, old_inst.cast(zir.Inst.Export).?); return self.constVoid(scope, old_inst.src); }, .primitive => return self.analyzeInstPrimitive(scope, old_inst.cast(zir.Inst.Primitive).?), .ref => return self.analyzeInstRef(scope, old_inst.cast(zir.Inst.Ref).?), .fntype => return self.analyzeInstFnType(scope, old_inst.cast(zir.Inst.FnType).?), .intcast => return self.analyzeInstIntCast(scope, old_inst.cast(zir.Inst.IntCast).?), .bitcast => return self.analyzeInstBitCast(scope, old_inst.cast(zir.Inst.BitCast).?), .elemptr => return self.analyzeInstElemPtr(scope, old_inst.cast(zir.Inst.ElemPtr).?), .add => return self.analyzeInstAdd(scope, old_inst.cast(zir.Inst.Add).?), .cmp => return self.analyzeInstCmp(scope, old_inst.cast(zir.Inst.Cmp).?), .condbr => return self.analyzeInstCondBr(scope, old_inst.cast(zir.Inst.CondBr).?), .isnull => return self.analyzeInstIsNull(scope, old_inst.cast(zir.Inst.IsNull).?), .isnonnull => return self.analyzeInstIsNonNull(scope, old_inst.cast(zir.Inst.IsNonNull).?), } } fn analyzeInstCompileError(self: *Module, scope: *Scope, inst: *zir.Inst.CompileError) InnerError!*Inst { return self.fail(scope, inst.base.src, "{}", .{inst.positionals.msg}); } fn analyzeInstBreakpoint(self: *Module, scope: *Scope, inst: *zir.Inst.Breakpoint) InnerError!*Inst { const b = try self.requireRuntimeBlock(scope, inst.base.src); return self.addNewInstArgs(b, inst.base.src, Type.initTag(.void), Inst.Breakpoint, Inst.Args(Inst.Breakpoint){}); } fn analyzeInstRef(self: *Module, scope: *Scope, inst: *zir.Inst.Ref) InnerError!*Inst { const decl = try self.resolveCompleteDecl(scope, inst.positionals.operand); return self.analyzeDeclRef(scope, inst.base.src, decl); } fn analyzeInstDeclRef(self: *Module, scope: *Scope, inst: *zir.Inst.DeclRef) InnerError!*Inst { const decl_name = try self.resolveConstString(scope, inst.positionals.name); // This will need to get more fleshed out when there are proper structs & namespaces. const zir_module = scope.namespace(); const src_decl = zir_module.contents.module.findDecl(decl_name) orelse return self.fail(scope, inst.positionals.name.src, "use of undeclared identifier '{}'", .{decl_name}); const decl = try self.resolveCompleteDecl(scope, src_decl); return self.analyzeDeclRef(scope, inst.base.src, decl); } fn analyzeDeclVal(self: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Decl { const decl_name = inst.positionals.name; // This will need to get more fleshed out when there are proper structs & namespaces. const zir_module = scope.namespace(); const src_decl = zir_module.contents.module.findDecl(decl_name) orelse return self.fail(scope, inst.base.src, "use of undeclared identifier '{}'", .{decl_name}); const decl = try self.resolveCompleteDecl(scope, src_decl); return decl; } fn analyzeInstDeclVal(self: *Module, scope: *Scope, inst: *zir.Inst.DeclVal) InnerError!*Inst { const decl = try self.analyzeDeclVal(scope, inst); const ptr = try self.analyzeDeclRef(scope, inst.base.src, decl); return self.analyzeDeref(scope, inst.base.src, ptr, inst.base.src); } fn analyzeDeclRef(self: *Module, scope: *Scope, src: usize, decl: *Decl) InnerError!*Inst { const decl_tv = try decl.typedValue(); const ty_payload = try scope.arena().create(Type.Payload.SingleConstPointer); ty_payload.* = .{ .pointee_type = decl_tv.ty }; const val_payload = try scope.arena().create(Value.Payload.DeclRef); val_payload.* = .{ .decl = decl }; return self.constInst(scope, src, .{ .ty = Type.initPayload(&ty_payload.base), .val = Value.initPayload(&val_payload.base), }); } fn analyzeInstCall(self: *Module, scope: *Scope, inst: *zir.Inst.Call) InnerError!*Inst { const func = try self.resolveInst(scope, inst.positionals.func); if (func.ty.zigTypeTag() != .Fn) return self.fail(scope, inst.positionals.func.src, "type '{}' not a function", .{func.ty}); const cc = func.ty.fnCallingConvention(); if (cc == .Naked) { // TODO add error note: declared here return self.fail( scope, inst.positionals.func.src, "unable to call function with naked calling convention", .{}, ); } const call_params_len = inst.positionals.args.len; const fn_params_len = func.ty.fnParamLen(); if (func.ty.fnIsVarArgs()) { if (call_params_len < fn_params_len) { // TODO add error note: declared here return self.fail( scope, inst.positionals.func.src, "expected at least {} arguments, found {}", .{ fn_params_len, call_params_len }, ); } return self.fail(scope, inst.base.src, "TODO implement support for calling var args functions", .{}); } else if (fn_params_len != call_params_len) { // TODO add error note: declared here return self.fail( scope, inst.positionals.func.src, "expected {} arguments, found {}", .{ fn_params_len, call_params_len }, ); } if (inst.kw_args.modifier == .compile_time) { return self.fail(scope, inst.base.src, "TODO implement comptime function calls", .{}); } if (inst.kw_args.modifier != .auto) { return self.fail(scope, inst.base.src, "TODO implement call with modifier {}", .{inst.kw_args.modifier}); } // TODO handle function calls of generic functions const fn_param_types = try self.allocator.alloc(Type, fn_params_len); defer self.allocator.free(fn_param_types); func.ty.fnParamTypes(fn_param_types); const casted_args = try scope.arena().alloc(*Inst, fn_params_len); for (inst.positionals.args) |src_arg, i| { const uncasted_arg = try self.resolveInst(scope, src_arg); casted_args[i] = try self.coerce(scope, fn_param_types[i], uncasted_arg); } const b = try self.requireRuntimeBlock(scope, inst.base.src); return self.addNewInstArgs(b, inst.base.src, Type.initTag(.void), Inst.Call, Inst.Args(Inst.Call){ .func = func, .args = casted_args, }); } fn analyzeInstFn(self: *Module, scope: *Scope, fn_inst: *zir.Inst.Fn) InnerError!*Inst { const fn_type = try self.resolveType(scope, fn_inst.positionals.fn_type); const new_func = try scope.arena().create(Fn); new_func.* = .{ .fn_type = fn_type, .analysis = .{ .queued = fn_inst }, .owner_decl = scope.decl().?, }; const fn_payload = try scope.arena().create(Value.Payload.Function); fn_payload.* = .{ .func = new_func }; return self.constInst(scope, fn_inst.base.src, .{ .ty = fn_type, .val = Value.initPayload(&fn_payload.base), }); } fn analyzeInstFnType(self: *Module, scope: *Scope, fntype: *zir.Inst.FnType) InnerError!*Inst { const return_type = try self.resolveType(scope, fntype.positionals.return_type); if (return_type.zigTypeTag() == .NoReturn and fntype.positionals.param_types.len == 0 and fntype.kw_args.cc == .Unspecified) { return self.constType(scope, fntype.base.src, Type.initTag(.fn_noreturn_no_args)); } if (return_type.zigTypeTag() == .NoReturn and fntype.positionals.param_types.len == 0 and fntype.kw_args.cc == .Naked) { return self.constType(scope, fntype.base.src, Type.initTag(.fn_naked_noreturn_no_args)); } if (return_type.zigTypeTag() == .Void and fntype.positionals.param_types.len == 0 and fntype.kw_args.cc == .C) { return self.constType(scope, fntype.base.src, Type.initTag(.fn_ccc_void_no_args)); } return self.fail(scope, fntype.base.src, "TODO implement fntype instruction more", .{}); } fn analyzeInstPrimitive(self: *Module, scope: *Scope, primitive: *zir.Inst.Primitive) InnerError!*Inst { return self.constInst(scope, primitive.base.src, primitive.positionals.tag.toTypedValue()); } fn analyzeInstAs(self: *Module, scope: *Scope, as: *zir.Inst.As) InnerError!*Inst { const dest_type = try self.resolveType(scope, as.positionals.dest_type); const new_inst = try self.resolveInst(scope, as.positionals.value); return self.coerce(scope, dest_type, new_inst); } fn analyzeInstPtrToInt(self: *Module, scope: *Scope, ptrtoint: *zir.Inst.PtrToInt) InnerError!*Inst { const ptr = try self.resolveInst(scope, ptrtoint.positionals.ptr); if (ptr.ty.zigTypeTag() != .Pointer) { return self.fail(scope, ptrtoint.positionals.ptr.src, "expected pointer, found '{}'", .{ptr.ty}); } // TODO handle known-pointer-address const b = try self.requireRuntimeBlock(scope, ptrtoint.base.src); const ty = Type.initTag(.usize); return self.addNewInstArgs(b, ptrtoint.base.src, ty, Inst.PtrToInt, Inst.Args(Inst.PtrToInt){ .ptr = ptr }); } fn analyzeInstFieldPtr(self: *Module, scope: *Scope, fieldptr: *zir.Inst.FieldPtr) InnerError!*Inst { const object_ptr = try self.resolveInst(scope, fieldptr.positionals.object_ptr); const field_name = try self.resolveConstString(scope, fieldptr.positionals.field_name); const elem_ty = switch (object_ptr.ty.zigTypeTag()) { .Pointer => object_ptr.ty.elemType(), else => return self.fail(scope, fieldptr.positionals.object_ptr.src, "expected pointer, found '{}'", .{object_ptr.ty}), }; switch (elem_ty.zigTypeTag()) { .Array => { if (mem.eql(u8, field_name, "len")) { const len_payload = try scope.arena().create(Value.Payload.Int_u64); len_payload.* = .{ .int = elem_ty.arrayLen() }; const ref_payload = try scope.arena().create(Value.Payload.RefVal); ref_payload.* = .{ .val = Value.initPayload(&len_payload.base) }; return self.constInst(scope, fieldptr.base.src, .{ .ty = Type.initTag(.single_const_pointer_to_comptime_int), .val = Value.initPayload(&ref_payload.base), }); } else { return self.fail( scope, fieldptr.positionals.field_name.src, "no member named '{}' in '{}'", .{ field_name, elem_ty }, ); } }, else => return self.fail(scope, fieldptr.base.src, "type '{}' does not support field access", .{elem_ty}), } } fn analyzeInstIntCast(self: *Module, scope: *Scope, intcast: *zir.Inst.IntCast) InnerError!*Inst { const dest_type = try self.resolveType(scope, intcast.positionals.dest_type); const new_inst = try self.resolveInst(scope, intcast.positionals.value); const dest_is_comptime_int = switch (dest_type.zigTypeTag()) { .ComptimeInt => true, .Int => false, else => return self.fail( scope, intcast.positionals.dest_type.src, "expected integer type, found '{}'", .{ dest_type, }, ), }; switch (new_inst.ty.zigTypeTag()) { .ComptimeInt, .Int => {}, else => return self.fail( scope, intcast.positionals.value.src, "expected integer type, found '{}'", .{new_inst.ty}, ), } if (dest_is_comptime_int or new_inst.value() != null) { return self.coerce(scope, dest_type, new_inst); } return self.fail(scope, intcast.base.src, "TODO implement analyze widen or shorten int", .{}); } fn analyzeInstBitCast(self: *Module, scope: *Scope, inst: *zir.Inst.BitCast) InnerError!*Inst { const dest_type = try self.resolveType(scope, inst.positionals.dest_type); const operand = try self.resolveInst(scope, inst.positionals.operand); return self.bitcast(scope, dest_type, operand); } fn analyzeInstElemPtr(self: *Module, scope: *Scope, inst: *zir.Inst.ElemPtr) InnerError!*Inst { const array_ptr = try self.resolveInst(scope, inst.positionals.array_ptr); const uncasted_index = try self.resolveInst(scope, inst.positionals.index); const elem_index = try self.coerce(scope, Type.initTag(.usize), uncasted_index); if (array_ptr.ty.isSinglePointer() and array_ptr.ty.elemType().zigTypeTag() == .Array) { if (array_ptr.value()) |array_ptr_val| { if (elem_index.value()) |index_val| { // Both array pointer and index are compile-time known. const index_u64 = index_val.toUnsignedInt(); // @intCast here because it would have been impossible to construct a value that // required a larger index. const elem_ptr = try array_ptr_val.elemPtr(scope.arena(), @intCast(usize, index_u64)); const type_payload = try scope.arena().create(Type.Payload.SingleConstPointer); type_payload.* = .{ .pointee_type = array_ptr.ty.elemType().elemType() }; return self.constInst(scope, inst.base.src, .{ .ty = Type.initPayload(&type_payload.base), .val = elem_ptr, }); } } } return self.fail(scope, inst.base.src, "TODO implement more analyze elemptr", .{}); } fn analyzeInstAdd(self: *Module, scope: *Scope, inst: *zir.Inst.Add) InnerError!*Inst { const lhs = try self.resolveInst(scope, inst.positionals.lhs); const rhs = try self.resolveInst(scope, inst.positionals.rhs); if (lhs.ty.zigTypeTag() == .Int and rhs.ty.zigTypeTag() == .Int) { if (lhs.value()) |lhs_val| { if (rhs.value()) |rhs_val| { // TODO is this a performance issue? maybe we should try the operation without // resorting to BigInt first. var lhs_space: Value.BigIntSpace = undefined; var rhs_space: Value.BigIntSpace = undefined; const lhs_bigint = lhs_val.toBigInt(&lhs_space); const rhs_bigint = rhs_val.toBigInt(&rhs_space); const limbs = try scope.arena().alloc( std.math.big.Limb, std.math.max(lhs_bigint.limbs.len, rhs_bigint.limbs.len) + 1, ); var result_bigint = BigIntMutable{ .limbs = limbs, .positive = undefined, .len = undefined }; result_bigint.add(lhs_bigint, rhs_bigint); const result_limbs = result_bigint.limbs[0..result_bigint.len]; if (!lhs.ty.eql(rhs.ty)) { return self.fail(scope, inst.base.src, "TODO implement peer type resolution", .{}); } const val_payload = if (result_bigint.positive) blk: { const val_payload = try scope.arena().create(Value.Payload.IntBigPositive); val_payload.* = .{ .limbs = result_limbs }; break :blk &val_payload.base; } else blk: { const val_payload = try scope.arena().create(Value.Payload.IntBigNegative); val_payload.* = .{ .limbs = result_limbs }; break :blk &val_payload.base; }; return self.constInst(scope, inst.base.src, .{ .ty = lhs.ty, .val = Value.initPayload(val_payload), }); } } } return self.fail(scope, inst.base.src, "TODO implement more analyze add", .{}); } fn analyzeInstDeref(self: *Module, scope: *Scope, deref: *zir.Inst.Deref) InnerError!*Inst { const ptr = try self.resolveInst(scope, deref.positionals.ptr); return self.analyzeDeref(scope, deref.base.src, ptr, deref.positionals.ptr.src); } fn analyzeDeref(self: *Module, scope: *Scope, src: usize, ptr: *Inst, ptr_src: usize) InnerError!*Inst { const elem_ty = switch (ptr.ty.zigTypeTag()) { .Pointer => ptr.ty.elemType(), else => return self.fail(scope, ptr_src, "expected pointer, found '{}'", .{ptr.ty}), }; if (ptr.value()) |val| { return self.constInst(scope, src, .{ .ty = elem_ty, .val = try val.pointerDeref(scope.arena()), }); } return self.fail(scope, src, "TODO implement runtime deref", .{}); } fn analyzeInstAsm(self: *Module, scope: *Scope, assembly: *zir.Inst.Asm) InnerError!*Inst { const return_type = try self.resolveType(scope, assembly.positionals.return_type); const asm_source = try self.resolveConstString(scope, assembly.positionals.asm_source); const output = if (assembly.kw_args.output) |o| try self.resolveConstString(scope, o) else null; const inputs = try scope.arena().alloc([]const u8, assembly.kw_args.inputs.len); const clobbers = try scope.arena().alloc([]const u8, assembly.kw_args.clobbers.len); const args = try scope.arena().alloc(*Inst, assembly.kw_args.args.len); for (inputs) |*elem, i| { elem.* = try self.resolveConstString(scope, assembly.kw_args.inputs[i]); } for (clobbers) |*elem, i| { elem.* = try self.resolveConstString(scope, assembly.kw_args.clobbers[i]); } for (args) |*elem, i| { const arg = try self.resolveInst(scope, assembly.kw_args.args[i]); elem.* = try self.coerce(scope, Type.initTag(.usize), arg); } const b = try self.requireRuntimeBlock(scope, assembly.base.src); return self.addNewInstArgs(b, assembly.base.src, return_type, Inst.Assembly, Inst.Args(Inst.Assembly){ .asm_source = asm_source, .is_volatile = assembly.kw_args.@"volatile", .output = output, .inputs = inputs, .clobbers = clobbers, .args = args, }); } fn analyzeInstCmp(self: *Module, scope: *Scope, inst: *zir.Inst.Cmp) InnerError!*Inst { const lhs = try self.resolveInst(scope, inst.positionals.lhs); const rhs = try self.resolveInst(scope, inst.positionals.rhs); const op = inst.positionals.op; const is_equality_cmp = switch (op) { .eq, .neq => true, else => false, }; const lhs_ty_tag = lhs.ty.zigTypeTag(); const rhs_ty_tag = rhs.ty.zigTypeTag(); if (is_equality_cmp and lhs_ty_tag == .Null and rhs_ty_tag == .Null) { // null == null, null != null return self.constBool(scope, inst.base.src, op == .eq); } else if (is_equality_cmp and ((lhs_ty_tag == .Null and rhs_ty_tag == .Optional) or rhs_ty_tag == .Null and lhs_ty_tag == .Optional)) { // comparing null with optionals const opt_operand = if (lhs_ty_tag == .Optional) lhs else rhs; if (opt_operand.value()) |opt_val| { const is_null = opt_val.isNull(); return self.constBool(scope, inst.base.src, if (op == .eq) is_null else !is_null); } const b = try self.requireRuntimeBlock(scope, inst.base.src); switch (op) { .eq => return self.addNewInstArgs( b, inst.base.src, Type.initTag(.bool), Inst.IsNull, Inst.Args(Inst.IsNull){ .operand = opt_operand }, ), .neq => return self.addNewInstArgs( b, inst.base.src, Type.initTag(.bool), Inst.IsNonNull, Inst.Args(Inst.IsNonNull){ .operand = opt_operand }, ), else => unreachable, } } else if (is_equality_cmp and ((lhs_ty_tag == .Null and rhs.ty.isCPtr()) or (rhs_ty_tag == .Null and lhs.ty.isCPtr()))) { return self.fail(scope, inst.base.src, "TODO implement C pointer cmp", .{}); } else if (lhs_ty_tag == .Null or rhs_ty_tag == .Null) { const non_null_type = if (lhs_ty_tag == .Null) rhs.ty else lhs.ty; return self.fail(scope, inst.base.src, "comparison of '{}' with null", .{non_null_type}); } else if (is_equality_cmp and ((lhs_ty_tag == .EnumLiteral and rhs_ty_tag == .Union) or (rhs_ty_tag == .EnumLiteral and lhs_ty_tag == .Union))) { return self.fail(scope, inst.base.src, "TODO implement equality comparison between a union's tag value and an enum literal", .{}); } else if (lhs_ty_tag == .ErrorSet and rhs_ty_tag == .ErrorSet) { if (!is_equality_cmp) { return self.fail(scope, inst.base.src, "{} operator not allowed for errors", .{@tagName(op)}); } return self.fail(scope, inst.base.src, "TODO implement equality comparison between errors", .{}); } else if (lhs.ty.isNumeric() and rhs.ty.isNumeric()) { // This operation allows any combination of integer and float types, regardless of the // signed-ness, comptime-ness, and bit-width. So peer type resolution is incorrect for // numeric types. return self.cmpNumeric(scope, inst.base.src, lhs, rhs, op); } return self.fail(scope, inst.base.src, "TODO implement more cmp analysis", .{}); } fn analyzeInstIsNull(self: *Module, scope: *Scope, inst: *zir.Inst.IsNull) InnerError!*Inst { const operand = try self.resolveInst(scope, inst.positionals.operand); return self.analyzeIsNull(scope, inst.base.src, operand, true); } fn analyzeInstIsNonNull(self: *Module, scope: *Scope, inst: *zir.Inst.IsNonNull) InnerError!*Inst { const operand = try self.resolveInst(scope, inst.positionals.operand); return self.analyzeIsNull(scope, inst.base.src, operand, false); } fn analyzeInstCondBr(self: *Module, scope: *Scope, inst: *zir.Inst.CondBr) InnerError!*Inst { const uncasted_cond = try self.resolveInst(scope, inst.positionals.condition); const cond = try self.coerce(scope, Type.initTag(.bool), uncasted_cond); if (try self.resolveDefinedValue(scope, cond)) |cond_val| { const body = if (cond_val.toBool()) &inst.positionals.true_body else &inst.positionals.false_body; try self.analyzeBody(scope, body.*); return self.constVoid(scope, inst.base.src); } const parent_block = try self.requireRuntimeBlock(scope, inst.base.src); var true_block: Scope.Block = .{ .func = parent_block.func, .decl = parent_block.decl, .instructions = .{}, .arena = parent_block.arena, }; defer true_block.instructions.deinit(self.allocator); try self.analyzeBody(&true_block.base, inst.positionals.true_body); var false_block: Scope.Block = .{ .func = parent_block.func, .decl = parent_block.decl, .instructions = .{}, .arena = parent_block.arena, }; defer false_block.instructions.deinit(self.allocator); try self.analyzeBody(&false_block.base, inst.positionals.false_body); return self.addNewInstArgs(parent_block, inst.base.src, Type.initTag(.void), Inst.CondBr, Inst.Args(Inst.CondBr){ .condition = cond, .true_body = .{ .instructions = try scope.arena().dupe(*Inst, true_block.instructions.items) }, .false_body = .{ .instructions = try scope.arena().dupe(*Inst, false_block.instructions.items) }, }); } fn wantSafety(self: *Module, scope: *Scope) bool { return switch (self.optimize_mode) { .Debug => true, .ReleaseSafe => true, .ReleaseFast => false, .ReleaseSmall => false, }; } fn analyzeInstUnreachable(self: *Module, scope: *Scope, unreach: *zir.Inst.Unreachable) InnerError!*Inst { const b = try self.requireRuntimeBlock(scope, unreach.base.src); if (self.wantSafety(scope)) { // TODO Once we have a panic function to call, call it here instead of this. _ = try self.addNewInstArgs(b, unreach.base.src, Type.initTag(.void), Inst.Breakpoint, {}); } return self.addNewInstArgs(b, unreach.base.src, Type.initTag(.noreturn), Inst.Unreach, {}); } fn analyzeInstRet(self: *Module, scope: *Scope, inst: *zir.Inst.Return) InnerError!*Inst { const b = try self.requireRuntimeBlock(scope, inst.base.src); return self.addNewInstArgs(b, inst.base.src, Type.initTag(.noreturn), Inst.Ret, {}); } fn analyzeBody(self: *Module, scope: *Scope, body: zir.Module.Body) !void { if (scope.cast(Scope.Block)) |b| { const analysis = b.func.analysis.in_progress; analysis.needed_inst_capacity += body.instructions.len; try analysis.inst_table.ensureCapacity(analysis.needed_inst_capacity); for (body.instructions) |src_inst| { const new_inst = try self.analyzeInst(scope, src_inst); analysis.inst_table.putAssumeCapacityNoClobber(src_inst, new_inst); } } else { for (body.instructions) |src_inst| { _ = try self.analyzeInst(scope, src_inst); } } } fn analyzeIsNull( self: *Module, scope: *Scope, src: usize, operand: *Inst, invert_logic: bool, ) InnerError!*Inst { return self.fail(scope, src, "TODO implement analysis of isnull and isnotnull", .{}); } /// Asserts that lhs and rhs types are both numeric. fn cmpNumeric( self: *Module, scope: *Scope, src: usize, lhs: *Inst, rhs: *Inst, op: std.math.CompareOperator, ) !*Inst { assert(lhs.ty.isNumeric()); assert(rhs.ty.isNumeric()); const lhs_ty_tag = lhs.ty.zigTypeTag(); const rhs_ty_tag = rhs.ty.zigTypeTag(); if (lhs_ty_tag == .Vector and rhs_ty_tag == .Vector) { if (lhs.ty.arrayLen() != rhs.ty.arrayLen()) { return self.fail(scope, src, "vector length mismatch: {} and {}", .{ lhs.ty.arrayLen(), rhs.ty.arrayLen(), }); } return self.fail(scope, src, "TODO implement support for vectors in cmpNumeric", .{}); } else if (lhs_ty_tag == .Vector or rhs_ty_tag == .Vector) { return self.fail(scope, src, "mixed scalar and vector operands to comparison operator: '{}' and '{}'", .{ lhs.ty, rhs.ty, }); } if (lhs.value()) |lhs_val| { if (rhs.value()) |rhs_val| { return self.constBool(scope, src, Value.compare(lhs_val, op, rhs_val)); } } // TODO handle comparisons against lazy zero values // Some values can be compared against zero without being runtime known or without forcing // a full resolution of their value, for example `@sizeOf(@Frame(function))` is known to // always be nonzero, and we benefit from not forcing the full evaluation and stack frame layout // of this function if we don't need to. // It must be a runtime comparison. const b = try self.requireRuntimeBlock(scope, src); // For floats, emit a float comparison instruction. const lhs_is_float = switch (lhs_ty_tag) { .Float, .ComptimeFloat => true, else => false, }; const rhs_is_float = switch (rhs_ty_tag) { .Float, .ComptimeFloat => true, else => false, }; if (lhs_is_float and rhs_is_float) { // Implicit cast the smaller one to the larger one. const dest_type = x: { if (lhs_ty_tag == .ComptimeFloat) { break :x rhs.ty; } else if (rhs_ty_tag == .ComptimeFloat) { break :x lhs.ty; } if (lhs.ty.floatBits(self.target()) >= rhs.ty.floatBits(self.target())) { break :x lhs.ty; } else { break :x rhs.ty; } }; const casted_lhs = try self.coerce(scope, dest_type, lhs); const casted_rhs = try self.coerce(scope, dest_type, rhs); return self.addNewInstArgs(b, src, dest_type, Inst.Cmp, Inst.Args(Inst.Cmp){ .lhs = casted_lhs, .rhs = casted_rhs, .op = op, }); } // For mixed unsigned integer sizes, implicit cast both operands to the larger integer. // For mixed signed and unsigned integers, implicit cast both operands to a signed // integer with + 1 bit. // For mixed floats and integers, extract the integer part from the float, cast that to // a signed integer with mantissa bits + 1, and if there was any non-integral part of the float, // add/subtract 1. const lhs_is_signed = if (lhs.value()) |lhs_val| lhs_val.compareWithZero(.lt) else (lhs.ty.isFloat() or lhs.ty.isSignedInt()); const rhs_is_signed = if (rhs.value()) |rhs_val| rhs_val.compareWithZero(.lt) else (rhs.ty.isFloat() or rhs.ty.isSignedInt()); const dest_int_is_signed = lhs_is_signed or rhs_is_signed; var dest_float_type: ?Type = null; var lhs_bits: usize = undefined; if (lhs.value()) |lhs_val| { if (lhs_val.isUndef()) return self.constUndef(scope, src, Type.initTag(.bool)); const is_unsigned = if (lhs_is_float) x: { var bigint_space: Value.BigIntSpace = undefined; var bigint = try lhs_val.toBigInt(&bigint_space).toManaged(self.allocator); defer bigint.deinit(); const zcmp = lhs_val.orderAgainstZero(); if (lhs_val.floatHasFraction()) { switch (op) { .eq => return self.constBool(scope, src, false), .neq => return self.constBool(scope, src, true), else => {}, } if (zcmp == .lt) { try bigint.addScalar(bigint.toConst(), -1); } else { try bigint.addScalar(bigint.toConst(), 1); } } lhs_bits = bigint.toConst().bitCountTwosComp(); break :x (zcmp != .lt); } else x: { lhs_bits = lhs_val.intBitCountTwosComp(); break :x (lhs_val.orderAgainstZero() != .lt); }; lhs_bits += @boolToInt(is_unsigned and dest_int_is_signed); } else if (lhs_is_float) { dest_float_type = lhs.ty; } else { const int_info = lhs.ty.intInfo(self.target()); lhs_bits = int_info.bits + @boolToInt(!int_info.signed and dest_int_is_signed); } var rhs_bits: usize = undefined; if (rhs.value()) |rhs_val| { if (rhs_val.isUndef()) return self.constUndef(scope, src, Type.initTag(.bool)); const is_unsigned = if (rhs_is_float) x: { var bigint_space: Value.BigIntSpace = undefined; var bigint = try rhs_val.toBigInt(&bigint_space).toManaged(self.allocator); defer bigint.deinit(); const zcmp = rhs_val.orderAgainstZero(); if (rhs_val.floatHasFraction()) { switch (op) { .eq => return self.constBool(scope, src, false), .neq => return self.constBool(scope, src, true), else => {}, } if (zcmp == .lt) { try bigint.addScalar(bigint.toConst(), -1); } else { try bigint.addScalar(bigint.toConst(), 1); } } rhs_bits = bigint.toConst().bitCountTwosComp(); break :x (zcmp != .lt); } else x: { rhs_bits = rhs_val.intBitCountTwosComp(); break :x (rhs_val.orderAgainstZero() != .lt); }; rhs_bits += @boolToInt(is_unsigned and dest_int_is_signed); } else if (rhs_is_float) { dest_float_type = rhs.ty; } else { const int_info = rhs.ty.intInfo(self.target()); rhs_bits = int_info.bits + @boolToInt(!int_info.signed and dest_int_is_signed); } const dest_type = if (dest_float_type) |ft| ft else blk: { const max_bits = std.math.max(lhs_bits, rhs_bits); const casted_bits = std.math.cast(u16, max_bits) catch |err| switch (err) { error.Overflow => return self.fail(scope, src, "{} exceeds maximum integer bit count", .{max_bits}), }; break :blk try self.makeIntType(scope, dest_int_is_signed, casted_bits); }; const casted_lhs = try self.coerce(scope, dest_type, lhs); const casted_rhs = try self.coerce(scope, dest_type, lhs); return self.addNewInstArgs(b, src, dest_type, Inst.Cmp, Inst.Args(Inst.Cmp){ .lhs = casted_lhs, .rhs = casted_rhs, .op = op, }); } fn makeIntType(self: *Module, scope: *Scope, signed: bool, bits: u16) !Type { if (signed) { const int_payload = try scope.arena().create(Type.Payload.IntSigned); int_payload.* = .{ .bits = bits }; return Type.initPayload(&int_payload.base); } else { const int_payload = try scope.arena().create(Type.Payload.IntUnsigned); int_payload.* = .{ .bits = bits }; return Type.initPayload(&int_payload.base); } } fn coerce(self: *Module, scope: *Scope, dest_type: Type, inst: *Inst) !*Inst { // If the types are the same, we can return the operand. if (dest_type.eql(inst.ty)) return inst; const in_memory_result = coerceInMemoryAllowed(dest_type, inst.ty); if (in_memory_result == .ok) { return self.bitcast(scope, dest_type, inst); } // *[N]T to []T if (inst.ty.isSinglePointer() and dest_type.isSlice() and (!inst.ty.pointerIsConst() or dest_type.pointerIsConst())) { const array_type = inst.ty.elemType(); const dst_elem_type = dest_type.elemType(); if (array_type.zigTypeTag() == .Array and coerceInMemoryAllowed(dst_elem_type, array_type.elemType()) == .ok) { return self.coerceArrayPtrToSlice(scope, dest_type, inst); } } // comptime_int to fixed-width integer if (inst.ty.zigTypeTag() == .ComptimeInt and dest_type.zigTypeTag() == .Int) { // The representation is already correct; we only need to make sure it fits in the destination type. const val = inst.value().?; // comptime_int always has comptime known value if (!val.intFitsInType(dest_type, self.target())) { return self.fail(scope, inst.src, "type {} cannot represent integer value {}", .{ inst.ty, val }); } return self.constInst(scope, inst.src, .{ .ty = dest_type, .val = val }); } // integer widening if (inst.ty.zigTypeTag() == .Int and dest_type.zigTypeTag() == .Int) { const src_info = inst.ty.intInfo(self.target()); const dst_info = dest_type.intInfo(self.target()); if (src_info.signed == dst_info.signed and dst_info.bits >= src_info.bits) { if (inst.value()) |val| { return self.constInst(scope, inst.src, .{ .ty = dest_type, .val = val }); } else { return self.fail(scope, inst.src, "TODO implement runtime integer widening", .{}); } } else { return self.fail(scope, inst.src, "TODO implement more int widening {} to {}", .{ inst.ty, dest_type }); } } return self.fail(scope, inst.src, "TODO implement type coercion from {} to {}", .{ inst.ty, dest_type }); } fn bitcast(self: *Module, scope: *Scope, dest_type: Type, inst: *Inst) !*Inst { if (inst.value()) |val| { // Keep the comptime Value representation; take the new type. return self.constInst(scope, inst.src, .{ .ty = dest_type, .val = val }); } // TODO validate the type size and other compile errors const b = try self.requireRuntimeBlock(scope, inst.src); return self.addNewInstArgs(b, inst.src, dest_type, Inst.BitCast, Inst.Args(Inst.BitCast){ .operand = inst }); } fn coerceArrayPtrToSlice(self: *Module, scope: *Scope, dest_type: Type, inst: *Inst) !*Inst { if (inst.value()) |val| { // The comptime Value representation is compatible with both types. return self.constInst(scope, inst.src, .{ .ty = dest_type, .val = val }); } return self.fail(scope, inst.src, "TODO implement coerceArrayPtrToSlice runtime instruction", .{}); } fn fail(self: *Module, scope: *Scope, src: usize, comptime format: []const u8, args: var) InnerError { @setCold(true); const err_msg = try ErrorMsg.create(self.allocator, src, format, args); return self.failWithOwnedErrorMsg(scope, src, err_msg); } fn failWithOwnedErrorMsg(self: *Module, scope: *Scope, src: usize, err_msg: *ErrorMsg) InnerError { { errdefer err_msg.destroy(self.allocator); try self.failed_decls.ensureCapacity(self.failed_decls.size + 1); try self.failed_files.ensureCapacity(self.failed_files.size + 1); } switch (scope.tag) { .decl => { const decl = scope.cast(Scope.DeclAnalysis).?.decl; decl.analysis = .sema_failure; self.failed_decls.putAssumeCapacityNoClobber(decl, err_msg); }, .block => { const block = scope.cast(Scope.Block).?; block.func.analysis = .sema_failure; self.failed_decls.putAssumeCapacityNoClobber(block.decl, err_msg); }, .zir_module => { const zir_module = scope.cast(Scope.ZIRModule).?; zir_module.status = .loaded_sema_failure; self.failed_files.putAssumeCapacityNoClobber(zir_module, err_msg); }, } return error.AnalysisFail; } const InMemoryCoercionResult = enum { ok, no_match, }; fn coerceInMemoryAllowed(dest_type: Type, src_type: Type) InMemoryCoercionResult { if (dest_type.eql(src_type)) return .ok; // TODO: implement more of this function return .no_match; } pub const ErrorMsg = struct { byte_offset: usize, msg: []const u8, pub fn create(allocator: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !*ErrorMsg { const self = try allocator.create(ErrorMsg); errdefer allocator.destroy(self); self.* = try init(allocator, byte_offset, format, args); return self; } /// Assumes the ErrorMsg struct and msg were both allocated with allocator. pub fn destroy(self: *ErrorMsg, allocator: *Allocator) void { self.deinit(allocator); allocator.destroy(self); } pub fn init(allocator: *Allocator, byte_offset: usize, comptime format: []const u8, args: var) !ErrorMsg { return ErrorMsg{ .byte_offset = byte_offset, .msg = try std.fmt.allocPrint(allocator, format, args), }; } pub fn deinit(self: *ErrorMsg, allocator: *Allocator) void { allocator.free(self.msg); self.* = undefined; } };
src-self-hosted/Module.zig
const std = @import("std"); const libcurl = @import("lib/zig-libcurl/libcurl.zig"); const libssh2 = @import("lib/zig-libssh2/libssh2.zig"); const zlib = @import("lib/zig-zlib/zlib.zig"); const mbedtls = @import("lib/zig-mbedtls/mbedtls.zig"); 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 _zlib = zlib.create(b, target, mode); const _mbedtls = mbedtls.create(b, target, mode); const _libssh2 = libssh2.create(b, target, mode); const _libcurl = try libcurl.create(b, target, mode); _mbedtls.link(_libssh2.step); _libssh2.link(_libcurl.step); _mbedtls.link(_libcurl.step); _zlib.link(_libcurl.step, .{}); _libcurl.step.install(); const exe = b.addExecutable("main", "src/main.zig"); _libcurl.link(exe, .{ .import_name = "curl" }); const tests = b.addTest("src/main.zig"); tests.setBuildMode(mode); tests.setTarget(target); _libcurl.link(tests, .{}); _zlib.link(tests, .{}); _mbedtls.link(tests); _libssh2.link(tests); _zlib.link(exe, .{}); _mbedtls.link(exe); _libssh2.link(exe); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const exe_tests = b.addTest("src/main.zig"); exe_tests.setTarget(target); exe_tests.setBuildMode(mode); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); }
build.zig
const std = @import("../index.zig"); const math = std.math; const assert = std.debug.assert; pub fn atan(x: var) @typeOf(x) { const T = @typeOf(x); return switch (T) { f32 => atan32(x), f64 => atan64(x), else => @compileError("atan not implemented for " ++ @typeName(T)), }; } fn atan32(x_: f32) f32 { const atanhi = []const f32 { 4.6364760399e-01, // atan(0.5)hi 7.8539812565e-01, // atan(1.0)hi 9.8279368877e-01, // atan(1.5)hi 1.5707962513e+00, // atan(inf)hi }; const atanlo = []const f32 { 5.0121582440e-09, // atan(0.5)lo 3.7748947079e-08, // atan(1.0)lo 3.4473217170e-08, // atan(1.5)lo 7.5497894159e-08, // atan(inf)lo }; const aT = []const f32 { 3.3333328366e-01, -1.9999158382e-01, 1.4253635705e-01, -1.0648017377e-01, 6.1687607318e-02, }; var x = x_; var ix: u32 = @bitCast(u32, x); const sign = ix >> 31; ix &= 0x7FFFFFFF; // |x| >= 2^26 if (ix >= 0x4C800000) { if (math.isNan(x)) { return x; } else { const z = atanhi[3] + 0x1.0p-120; return if (sign != 0) -z else z; } } var id: ?usize = undefined; // |x| < 0.4375 if (ix < 0x3EE00000) { // |x| < 2^(-12) if (ix < 0x39800000) { if (ix < 0x00800000) { math.forceEval(x * x); } return x; } id = null; } else { x = math.fabs(x); // |x| < 1.1875 if (ix < 0x3F980000) { // 7/16 <= |x| < 11/16 if (ix < 0x3F300000) { id = 0; x = (2.0 * x - 1.0) / (2.0 + x); } // 11/16 <= |x| < 19/16 else { id = 1; x = (x - 1.0) / (x + 1.0); } } else { // |x| < 2.4375 if (ix < 0x401C0000) { id = 2; x = (x - 1.5) / (1.0 + 1.5 * x); } // 2.4375 <= |x| < 2^26 else { id = 3; x = -1.0 / x; } } } const z = x * x; const w = z * z; const s1 = z * (aT[0] + w * (aT[2] + w * aT[4])); const s2 = w * (aT[1] + w * aT[3]); if (id) |id_value| { const zz = atanhi[id_value] - ((x * (s1 + s2) - atanlo[id_value]) - x); return if (sign != 0) -zz else zz; } else { return x - x * (s1 + s2); } } fn atan64(x_: f64) f64 { const atanhi = []const f64 { 4.63647609000806093515e-01, // atan(0.5)hi 7.85398163397448278999e-01, // atan(1.0)hi 9.82793723247329054082e-01, // atan(1.5)hi 1.57079632679489655800e+00, // atan(inf)hi }; const atanlo = []const f64 { 2.26987774529616870924e-17, // atan(0.5)lo 3.06161699786838301793e-17, // atan(1.0)lo 1.39033110312309984516e-17, // atan(1.5)lo 6.12323399573676603587e-17, // atan(inf)lo }; const aT = []const f64 { 3.33333333333329318027e-01, -1.99999999998764832476e-01, 1.42857142725034663711e-01, -1.11111104054623557880e-01, 9.09088713343650656196e-02, -7.69187620504482999495e-02, 6.66107313738753120669e-02, -5.83357013379057348645e-02, 4.97687799461593236017e-02, -3.65315727442169155270e-02, 1.62858201153657823623e-02, }; var x = x_; var ux = @bitCast(u64, x); var ix = u32(ux >> 32); const sign = ix >> 31; ix &= 0x7FFFFFFF; // |x| >= 2^66 if (ix >= 0x44100000) { if (math.isNan(x)) { return x; } else { const z = atanhi[3] + 0x1.0p-120; return if (sign != 0) -z else z; } } var id: ?usize = undefined; // |x| < 0.4375 if (ix < 0x3DFC0000) { // |x| < 2^(-27) if (ix < 0x3E400000) { if (ix < 0x00100000) { math.forceEval(f32(x)); } return x; } id = null; } else { x = math.fabs(x); // |x| < 1.1875 if (ix < 0x3FF30000) { // 7/16 <= |x| < 11/16 if (ix < 0x3FE60000) { id = 0; x = (2.0 * x - 1.0) / (2.0 + x); } // 11/16 <= |x| < 19/16 else { id = 1; x = (x - 1.0) / (x + 1.0); } } else { // |x| < 2.4375 if (ix < 0x40038000) { id = 2; x = (x - 1.5) / (1.0 + 1.5 * x); } // 2.4375 <= |x| < 2^66 else { id = 3; x = -1.0 / x; } } } const z = x * x; const w = z * z; const s1 = z * (aT[0] + w * (aT[2] + w * (aT[4] + w * (aT[6] + w * (aT[8] + w * aT[10]))))); const s2 = w * (aT[1] + w * (aT[3] + w * (aT[5] + w * (aT[7] + w * aT[9])))); if (id) |id_value| { const zz = atanhi[id_value] - ((x * (s1 + s2) - atanlo[id_value]) - x); return if (sign != 0) -zz else zz; } else { return x - x * (s1 + s2); } } test "math.atan" { assert(@bitCast(u32, atan(f32(0.2))) == @bitCast(u32, atan32(0.2))); assert(atan(f64(0.2)) == atan64(0.2)); } test "math.atan32" { const epsilon = 0.000001; assert(math.approxEq(f32, atan32(0.2), 0.197396, epsilon)); assert(math.approxEq(f32, atan32(-0.2), -0.197396, epsilon)); assert(math.approxEq(f32, atan32(0.3434), 0.330783, epsilon)); assert(math.approxEq(f32, atan32(0.8923), 0.728545, epsilon)); assert(math.approxEq(f32, atan32(1.5), 0.982794, epsilon)); } test "math.atan64" { const epsilon = 0.000001; assert(math.approxEq(f64, atan64(0.2), 0.197396, epsilon)); assert(math.approxEq(f64, atan64(-0.2), -0.197396, epsilon)); assert(math.approxEq(f64, atan64(0.3434), 0.330783, epsilon)); assert(math.approxEq(f64, atan64(0.8923), 0.728545, epsilon)); assert(math.approxEq(f64, atan64(1.5), 0.982794, epsilon)); } test "math.atan32.special" { const epsilon = 0.000001; assert(atan32(0.0) == 0.0); assert(atan32(-0.0) == -0.0); assert(math.approxEq(f32, atan32(math.inf(f32)), math.pi / 2.0, epsilon)); assert(math.approxEq(f32, atan32(-math.inf(f32)), -math.pi / 2.0, epsilon)); } test "math.atan64.special" { const epsilon = 0.000001; assert(atan64(0.0) == 0.0); assert(atan64(-0.0) == -0.0); assert(math.approxEq(f64, atan64(math.inf(f64)), math.pi / 2.0, epsilon)); assert(math.approxEq(f64, atan64(-math.inf(f64)), -math.pi / 2.0, epsilon)); }
std/math/atan.zig
const std = @import("std"); const c = @cImport({ @cInclude("yaml.h"); }); const u = @import("./index.zig"); // // const Array = [][]const u8; pub const Document = struct { mapping: Mapping, }; pub const Item = union(enum) { event: c.yaml_event_t, kv: Key, mapping: Mapping, sequence: []Item, document: Document, string: []const u8, }; pub const Key = struct { key: []const u8, value: Value, }; pub const Value = union(enum) { string: []const u8, mapping: Mapping, sequence: []Item, }; pub const Mapping = struct { items: []Key, pub fn get(self: Mapping, k: []const u8) ?Value { for (self.items) |item| { if (std.mem.eql(u8, item.key, k)) { return item.value; } } return null; } pub fn get_string(self: Mapping, k: []const u8) []const u8 { return if (self.get(k)) |v| v.string else ""; } pub fn get_string_array(self: Mapping, alloc: *std.mem.Allocator, k: []const u8) ![][]const u8 { const list = &std.ArrayList([]const u8).init(alloc); if (self.get(k)) |val| { if (val == .sequence) { for (val.sequence) |item, i| { if (item != .string) { continue; } try list.append(item.string); } } } return list.items; } }; // // pub fn parse(alloc: *std.mem.Allocator, input: []const u8) !Document { var parser: c.yaml_parser_t = undefined; _ = c.yaml_parser_initialize(&parser); const lines = try u.split(input, "\n"); _ = c.yaml_parser_set_input_string(&parser, input.ptr, input.len); var all_events = std.ArrayList(Item).init(alloc); var event: c.yaml_event_t = undefined; while (true) { const p = c.yaml_parser_parse(&parser, &event); if (p == 0) { break; } const et = @enumToInt(event.type); try all_events.append(.{.event = event}); c.yaml_event_delete(&event); if (et == c.YAML_STREAM_END_EVENT) { break; } } c.yaml_parser_delete(&parser); var l: usize = all_events.items.len; while (true) { try condense_event_list(&all_events, lines); if (l == all_events.items.len) { break; } l = all_events.items.len; } u.assert(all_events.items.len == 1, "failure parsing zig.mod. please report an issue at https://github.com/nektro/zigmod/issues/new that contains the text of your zig.mod.", .{}); return all_events.items[0].document; } fn get_event_string(event: c.yaml_event_t, lines: Array) []const u8 { const sm = event.start_mark; const em = event.end_mark; return lines[sm.line][sm.column..em.column]; } fn condense_event_list(list: *std.ArrayList(Item), lines: Array) !void { var i: usize = 0; var new_list = std.ArrayList(Item).init(list.allocator); while (i < list.items.len) : (i += 1) { if (try condense_event_list_key(list.items, i, &new_list, lines)) |len| { i += len; continue; } if (try condense_event_list_mapping(list.items, i, &new_list, lines)) |len| { i += len; continue; } if (try condense_event_list_sequence(list.items, i, &new_list, lines)) |len| { i += len; continue; } if (try condense_event_list_document(list.items, i, &new_list, lines)) |len| { i += len; continue; } try new_list.append(list.items[i]); } list.* = new_list; } fn condense_event_list_key(from: []Item, at: usize, to: *std.ArrayList(Item), lines: Array) !?usize { if (at >= from.len-1) { return null; } const t = from[at]; const n = from[at+1]; if (!(t == .event and @enumToInt(t.event.type) == c.YAML_SCALAR_EVENT)) { return null; } if (n == .event and @enumToInt(n.event.type) == c.YAML_SCALAR_EVENT) { try to.append(Item{ .kv = Key{ .key = get_event_string(t.event, lines), .value = Value{ .string = get_event_string(n.event, lines) }, }, }); return 0+2-1; } if (n == .sequence) { try to.append(Item{ .kv = Key{ .key = get_event_string(t.event, lines), .value = Value{ .sequence = n.sequence }, }, }); return 0+2-1; } return null; } fn condense_event_list_mapping(from: []Item, at: usize, to: *std.ArrayList(Item), lines: Array) !?usize { if (!(from[at] == .event and @enumToInt(from[at].event.type) == c.YAML_MAPPING_START_EVENT)) { return null; } var i: usize = 1; while (true) : (i += 1) { const ele = from[at+i]; if (ele == .event and @enumToInt(ele.event.type) == c.YAML_MAPPING_END_EVENT) { break; } if (ele == .event) { return null; } } const keys = &std.ArrayList(Key).init(to.allocator); for (from[at+1..at+i]) |item| { switch (item) { .kv => { try keys.append(item.kv); }, else => unreachable, } } try to.append(Item{ .mapping = Mapping{ .items = keys.items }, }); return 0+i; } fn condense_event_list_sequence(from: []Item, at: usize, to: *std.ArrayList(Item), lines: Array) !?usize { if (!(from[at] == .event and @enumToInt(from[at].event.type) == c.YAML_SEQUENCE_START_EVENT)) { return null; } var i: usize = 1; while (true) : (i += 1) { const ele = from[at+i]; if (ele == .event) { if (@enumToInt(ele.event.type) == c.YAML_SEQUENCE_END_EVENT) { break; } if (@enumToInt(ele.event.type) == c.YAML_SCALAR_EVENT) { continue; } return null; } } const result = &std.ArrayList(Item).init(to.allocator); for (from[at+1..at+i]) |item| { try result.append(switch (item) { .mapping => item, .event => Item{ .string = get_event_string(item.event, lines) }, else => unreachable, }); } try to.append(Item{ .sequence = result.items, }); return 0+i; } fn condense_event_list_document(from: []Item, at: usize, to: *std.ArrayList(Item), lines: Array) !?usize { if (from.len < at+4) { return null; } if (!(from[at] == .event and @enumToInt(from[at].event.type) == c.YAML_STREAM_START_EVENT)) { return null; } if (!(from[at+1] == .event and @enumToInt(from[at+1].event.type) == c.YAML_DOCUMENT_START_EVENT)) { return null; } if (!(from[at+2] == .mapping)) { return null; } if (!(from[at+3] == .event and @enumToInt(from[at+3].event.type) == c.YAML_DOCUMENT_END_EVENT)) { return null; } if (!(from[at+4] == .event and @enumToInt(from[at+4].event.type) == c.YAML_STREAM_END_EVENT)) { return null; } try to.append(Item{ .document = Document{ .mapping = from[at+2].mapping, }, }); return 0+5-1; }
src/util/yaml.zig
pub const WER_FAULT_REPORTING_NO_UI = @as(u32, 32); pub const WER_FAULT_REPORTING_FLAG_NO_HEAP_ON_QUEUE = @as(u32, 64); pub const WER_FAULT_REPORTING_DISABLE_SNAPSHOT_CRASH = @as(u32, 128); pub const WER_FAULT_REPORTING_DISABLE_SNAPSHOT_HANG = @as(u32, 256); pub const WER_FAULT_REPORTING_CRITICAL = @as(u32, 512); pub const WER_FAULT_REPORTING_DURABLE = @as(u32, 1024); pub const WER_MAX_TOTAL_PARAM_LENGTH = @as(u32, 1720); pub const WER_MAX_PREFERRED_MODULES = @as(u32, 128); pub const WER_MAX_PREFERRED_MODULES_BUFFER = @as(u32, 256); pub const WER_P0 = @as(u32, 0); pub const WER_P1 = @as(u32, 1); pub const WER_P2 = @as(u32, 2); pub const WER_P3 = @as(u32, 3); pub const WER_P4 = @as(u32, 4); pub const WER_P5 = @as(u32, 5); pub const WER_P6 = @as(u32, 6); pub const WER_P7 = @as(u32, 7); pub const WER_P8 = @as(u32, 8); pub const WER_P9 = @as(u32, 9); pub const WER_FILE_COMPRESSED = @as(u32, 4); pub const WER_SUBMIT_BYPASS_POWER_THROTTLING = @as(u32, 16384); pub const WER_SUBMIT_BYPASS_NETWORK_COST_THROTTLING = @as(u32, 32768); pub const WER_DUMP_MASK_START = @as(u32, 1); pub const WER_DUMP_NOHEAP_ONQUEUE = @as(u32, 1); pub const WER_DUMP_AUXILIARY = @as(u32, 2); pub const WER_MAX_REGISTERED_ENTRIES = @as(u32, 512); pub const WER_MAX_REGISTERED_METADATA = @as(u32, 8); pub const WER_MAX_REGISTERED_DUMPCOLLECTION = @as(u32, 4); pub const WER_METADATA_KEY_MAX_LENGTH = @as(u32, 64); pub const WER_METADATA_VALUE_MAX_LENGTH = @as(u32, 128); pub const WER_MAX_SIGNATURE_NAME_LENGTH = @as(u32, 128); pub const WER_MAX_EVENT_NAME_LENGTH = @as(u32, 64); pub const WER_MAX_PARAM_LENGTH = @as(u32, 260); pub const WER_MAX_PARAM_COUNT = @as(u32, 10); pub const WER_MAX_FRIENDLY_EVENT_NAME_LENGTH = @as(u32, 128); pub const WER_MAX_APPLICATION_NAME_LENGTH = @as(u32, 128); pub const WER_MAX_DESCRIPTION_LENGTH = @as(u32, 512); pub const WER_MAX_BUCKET_ID_STRING_LENGTH = @as(u32, 260); pub const WER_MAX_LOCAL_DUMP_SUBPATH_LENGTH = @as(u32, 64); pub const WER_MAX_REGISTERED_RUNTIME_EXCEPTION_MODULES = @as(u32, 16); //-------------------------------------------------------------------------------- // Section: Types (34) //-------------------------------------------------------------------------------- pub const WER_FILE = enum(u32) { ANONYMOUS_DATA = 2, DELETE_WHEN_DONE = 1, _, pub fn initFlags(o: struct { ANONYMOUS_DATA: u1 = 0, DELETE_WHEN_DONE: u1 = 0, }) WER_FILE { return @intToEnum(WER_FILE, (if (o.ANONYMOUS_DATA == 1) @enumToInt(WER_FILE.ANONYMOUS_DATA) else 0) | (if (o.DELETE_WHEN_DONE == 1) @enumToInt(WER_FILE.DELETE_WHEN_DONE) else 0) ); } }; pub const WER_FILE_ANONYMOUS_DATA = WER_FILE.ANONYMOUS_DATA; pub const WER_FILE_DELETE_WHEN_DONE = WER_FILE.DELETE_WHEN_DONE; pub const WER_SUBMIT_FLAGS = enum(u32) { ADD_REGISTERED_DATA = 16, HONOR_RECOVERY = 1, HONOR_RESTART = 2, NO_ARCHIVE = 256, NO_CLOSE_UI = 64, NO_QUEUE = 128, OUTOFPROCESS = 32, OUTOFPROCESS_ASYNC = 1024, QUEUE = 4, SHOW_DEBUG = 8, START_MINIMIZED = 512, BYPASS_DATA_THROTTLING = 2048, ARCHIVE_PARAMETERS_ONLY = 4096, REPORT_MACHINE_ID = 8192, _, pub fn initFlags(o: struct { ADD_REGISTERED_DATA: u1 = 0, HONOR_RECOVERY: u1 = 0, HONOR_RESTART: u1 = 0, NO_ARCHIVE: u1 = 0, NO_CLOSE_UI: u1 = 0, NO_QUEUE: u1 = 0, OUTOFPROCESS: u1 = 0, OUTOFPROCESS_ASYNC: u1 = 0, QUEUE: u1 = 0, SHOW_DEBUG: u1 = 0, START_MINIMIZED: u1 = 0, BYPASS_DATA_THROTTLING: u1 = 0, ARCHIVE_PARAMETERS_ONLY: u1 = 0, REPORT_MACHINE_ID: u1 = 0, }) WER_SUBMIT_FLAGS { return @intToEnum(WER_SUBMIT_FLAGS, (if (o.ADD_REGISTERED_DATA == 1) @enumToInt(WER_SUBMIT_FLAGS.ADD_REGISTERED_DATA) else 0) | (if (o.HONOR_RECOVERY == 1) @enumToInt(WER_SUBMIT_FLAGS.HONOR_RECOVERY) else 0) | (if (o.HONOR_RESTART == 1) @enumToInt(WER_SUBMIT_FLAGS.HONOR_RESTART) else 0) | (if (o.NO_ARCHIVE == 1) @enumToInt(WER_SUBMIT_FLAGS.NO_ARCHIVE) else 0) | (if (o.NO_CLOSE_UI == 1) @enumToInt(WER_SUBMIT_FLAGS.NO_CLOSE_UI) else 0) | (if (o.NO_QUEUE == 1) @enumToInt(WER_SUBMIT_FLAGS.NO_QUEUE) else 0) | (if (o.OUTOFPROCESS == 1) @enumToInt(WER_SUBMIT_FLAGS.OUTOFPROCESS) else 0) | (if (o.OUTOFPROCESS_ASYNC == 1) @enumToInt(WER_SUBMIT_FLAGS.OUTOFPROCESS_ASYNC) else 0) | (if (o.QUEUE == 1) @enumToInt(WER_SUBMIT_FLAGS.QUEUE) else 0) | (if (o.SHOW_DEBUG == 1) @enumToInt(WER_SUBMIT_FLAGS.SHOW_DEBUG) else 0) | (if (o.START_MINIMIZED == 1) @enumToInt(WER_SUBMIT_FLAGS.START_MINIMIZED) else 0) | (if (o.BYPASS_DATA_THROTTLING == 1) @enumToInt(WER_SUBMIT_FLAGS.BYPASS_DATA_THROTTLING) else 0) | (if (o.ARCHIVE_PARAMETERS_ONLY == 1) @enumToInt(WER_SUBMIT_FLAGS.ARCHIVE_PARAMETERS_ONLY) else 0) | (if (o.REPORT_MACHINE_ID == 1) @enumToInt(WER_SUBMIT_FLAGS.REPORT_MACHINE_ID) else 0) ); } }; pub const WER_SUBMIT_ADD_REGISTERED_DATA = WER_SUBMIT_FLAGS.ADD_REGISTERED_DATA; pub const WER_SUBMIT_HONOR_RECOVERY = WER_SUBMIT_FLAGS.HONOR_RECOVERY; pub const WER_SUBMIT_HONOR_RESTART = WER_SUBMIT_FLAGS.HONOR_RESTART; pub const WER_SUBMIT_NO_ARCHIVE = WER_SUBMIT_FLAGS.NO_ARCHIVE; pub const WER_SUBMIT_NO_CLOSE_UI = WER_SUBMIT_FLAGS.NO_CLOSE_UI; pub const WER_SUBMIT_NO_QUEUE = WER_SUBMIT_FLAGS.NO_QUEUE; pub const WER_SUBMIT_OUTOFPROCESS = WER_SUBMIT_FLAGS.OUTOFPROCESS; pub const WER_SUBMIT_OUTOFPROCESS_ASYNC = WER_SUBMIT_FLAGS.OUTOFPROCESS_ASYNC; pub const WER_SUBMIT_QUEUE = WER_SUBMIT_FLAGS.QUEUE; pub const WER_SUBMIT_SHOW_DEBUG = WER_SUBMIT_FLAGS.SHOW_DEBUG; pub const WER_SUBMIT_START_MINIMIZED = WER_SUBMIT_FLAGS.START_MINIMIZED; pub const WER_SUBMIT_BYPASS_DATA_THROTTLING = WER_SUBMIT_FLAGS.BYPASS_DATA_THROTTLING; pub const WER_SUBMIT_ARCHIVE_PARAMETERS_ONLY = WER_SUBMIT_FLAGS.ARCHIVE_PARAMETERS_ONLY; pub const WER_SUBMIT_REPORT_MACHINE_ID = WER_SUBMIT_FLAGS.REPORT_MACHINE_ID; pub const WER_FAULT_REPORTING = enum(u32) { FLAG_DISABLE_THREAD_SUSPENSION = 4, FLAG_NOHEAP = 1, FLAG_QUEUE = 2, FLAG_QUEUE_UPLOAD = 8, ALWAYS_SHOW_UI = 16, _, pub fn initFlags(o: struct { FLAG_DISABLE_THREAD_SUSPENSION: u1 = 0, FLAG_NOHEAP: u1 = 0, FLAG_QUEUE: u1 = 0, FLAG_QUEUE_UPLOAD: u1 = 0, ALWAYS_SHOW_UI: u1 = 0, }) WER_FAULT_REPORTING { return @intToEnum(WER_FAULT_REPORTING, (if (o.FLAG_DISABLE_THREAD_SUSPENSION == 1) @enumToInt(WER_FAULT_REPORTING.FLAG_DISABLE_THREAD_SUSPENSION) else 0) | (if (o.FLAG_NOHEAP == 1) @enumToInt(WER_FAULT_REPORTING.FLAG_NOHEAP) else 0) | (if (o.FLAG_QUEUE == 1) @enumToInt(WER_FAULT_REPORTING.FLAG_QUEUE) else 0) | (if (o.FLAG_QUEUE_UPLOAD == 1) @enumToInt(WER_FAULT_REPORTING.FLAG_QUEUE_UPLOAD) else 0) | (if (o.ALWAYS_SHOW_UI == 1) @enumToInt(WER_FAULT_REPORTING.ALWAYS_SHOW_UI) else 0) ); } }; pub const WER_FAULT_REPORTING_FLAG_DISABLE_THREAD_SUSPENSION = WER_FAULT_REPORTING.FLAG_DISABLE_THREAD_SUSPENSION; pub const WER_FAULT_REPORTING_FLAG_NOHEAP = WER_FAULT_REPORTING.FLAG_NOHEAP; pub const WER_FAULT_REPORTING_FLAG_QUEUE = WER_FAULT_REPORTING.FLAG_QUEUE; pub const WER_FAULT_REPORTING_FLAG_QUEUE_UPLOAD = WER_FAULT_REPORTING.FLAG_QUEUE_UPLOAD; pub const WER_FAULT_REPORTING_ALWAYS_SHOW_UI = WER_FAULT_REPORTING.ALWAYS_SHOW_UI; // TODO: this type has a FreeFunc 'WerReportCloseHandle', what can Zig do with this information? pub const HREPORT = isize; // TODO: this type has a FreeFunc 'WerStoreClose', what can Zig do with this information? pub const HREPORTSTORE = isize; pub const WER_REPORT_UI = enum(i32) { AdditionalDataDlgHeader = 1, IconFilePath = 2, ConsentDlgHeader = 3, ConsentDlgBody = 4, OnlineSolutionCheckText = 5, OfflineSolutionCheckText = 6, CloseText = 7, CloseDlgHeader = 8, CloseDlgBody = 9, CloseDlgButtonText = 10, Max = 11, }; pub const WerUIAdditionalDataDlgHeader = WER_REPORT_UI.AdditionalDataDlgHeader; pub const WerUIIconFilePath = WER_REPORT_UI.IconFilePath; pub const WerUIConsentDlgHeader = WER_REPORT_UI.ConsentDlgHeader; pub const WerUIConsentDlgBody = WER_REPORT_UI.ConsentDlgBody; pub const WerUIOnlineSolutionCheckText = WER_REPORT_UI.OnlineSolutionCheckText; pub const WerUIOfflineSolutionCheckText = WER_REPORT_UI.OfflineSolutionCheckText; pub const WerUICloseText = WER_REPORT_UI.CloseText; pub const WerUICloseDlgHeader = WER_REPORT_UI.CloseDlgHeader; pub const WerUICloseDlgBody = WER_REPORT_UI.CloseDlgBody; pub const WerUICloseDlgButtonText = WER_REPORT_UI.CloseDlgButtonText; pub const WerUIMax = WER_REPORT_UI.Max; pub const WER_REGISTER_FILE_TYPE = enum(i32) { UserDocument = 1, Other = 2, Max = 3, }; pub const WerRegFileTypeUserDocument = WER_REGISTER_FILE_TYPE.UserDocument; pub const WerRegFileTypeOther = WER_REGISTER_FILE_TYPE.Other; pub const WerRegFileTypeMax = WER_REGISTER_FILE_TYPE.Max; pub const WER_FILE_TYPE = enum(i32) { Microdump = 1, Minidump = 2, Heapdump = 3, UserDocument = 4, Other = 5, Triagedump = 6, CustomDump = 7, AuxiliaryDump = 8, EtlTrace = 9, Max = 10, }; pub const WerFileTypeMicrodump = WER_FILE_TYPE.Microdump; pub const WerFileTypeMinidump = WER_FILE_TYPE.Minidump; pub const WerFileTypeHeapdump = WER_FILE_TYPE.Heapdump; pub const WerFileTypeUserDocument = WER_FILE_TYPE.UserDocument; pub const WerFileTypeOther = WER_FILE_TYPE.Other; pub const WerFileTypeTriagedump = WER_FILE_TYPE.Triagedump; pub const WerFileTypeCustomDump = WER_FILE_TYPE.CustomDump; pub const WerFileTypeAuxiliaryDump = WER_FILE_TYPE.AuxiliaryDump; pub const WerFileTypeEtlTrace = WER_FILE_TYPE.EtlTrace; pub const WerFileTypeMax = WER_FILE_TYPE.Max; pub const WER_SUBMIT_RESULT = enum(i32) { ReportQueued = 1, ReportUploaded = 2, ReportDebug = 3, ReportFailed = 4, Disabled = 5, ReportCancelled = 6, DisabledQueue = 7, ReportAsync = 8, CustomAction = 9, Throttled = 10, ReportUploadedCab = 11, StorageLocationNotFound = 12, SubmitResultMax = 13, }; pub const WerReportQueued = WER_SUBMIT_RESULT.ReportQueued; pub const WerReportUploaded = WER_SUBMIT_RESULT.ReportUploaded; pub const WerReportDebug = WER_SUBMIT_RESULT.ReportDebug; pub const WerReportFailed = WER_SUBMIT_RESULT.ReportFailed; pub const WerDisabled = WER_SUBMIT_RESULT.Disabled; pub const WerReportCancelled = WER_SUBMIT_RESULT.ReportCancelled; pub const WerDisabledQueue = WER_SUBMIT_RESULT.DisabledQueue; pub const WerReportAsync = WER_SUBMIT_RESULT.ReportAsync; pub const WerCustomAction = WER_SUBMIT_RESULT.CustomAction; pub const WerThrottled = WER_SUBMIT_RESULT.Throttled; pub const WerReportUploadedCab = WER_SUBMIT_RESULT.ReportUploadedCab; pub const WerStorageLocationNotFound = WER_SUBMIT_RESULT.StorageLocationNotFound; pub const WerSubmitResultMax = WER_SUBMIT_RESULT.SubmitResultMax; pub const WER_REPORT_TYPE = enum(i32) { NonCritical = 0, Critical = 1, ApplicationCrash = 2, ApplicationHang = 3, Kernel = 4, Invalid = 5, }; pub const WerReportNonCritical = WER_REPORT_TYPE.NonCritical; pub const WerReportCritical = WER_REPORT_TYPE.Critical; pub const WerReportApplicationCrash = WER_REPORT_TYPE.ApplicationCrash; pub const WerReportApplicationHang = WER_REPORT_TYPE.ApplicationHang; pub const WerReportKernel = WER_REPORT_TYPE.Kernel; pub const WerReportInvalid = WER_REPORT_TYPE.Invalid; pub const WER_REPORT_INFORMATION = extern struct { dwSize: u32, hProcess: ?HANDLE, wzConsentKey: [64]u16, wzFriendlyEventName: [128]u16, wzApplicationName: [128]u16, wzApplicationPath: [260]u16, wzDescription: [512]u16, hwndParent: ?HWND, }; pub const WER_REPORT_INFORMATION_V3 = extern struct { dwSize: u32, hProcess: ?HANDLE, wzConsentKey: [64]u16, wzFriendlyEventName: [128]u16, wzApplicationName: [128]u16, wzApplicationPath: [260]u16, wzDescription: [512]u16, hwndParent: ?HWND, wzNamespacePartner: [64]u16, wzNamespaceGroup: [64]u16, }; pub const WER_DUMP_CUSTOM_OPTIONS = extern struct { dwSize: u32, dwMask: u32, dwDumpFlags: u32, bOnlyThisThread: BOOL, dwExceptionThreadFlags: u32, dwOtherThreadFlags: u32, dwExceptionThreadExFlags: u32, dwOtherThreadExFlags: u32, dwPreferredModuleFlags: u32, dwOtherModuleFlags: u32, wzPreferredModuleList: [256]u16, }; pub const WER_DUMP_CUSTOM_OPTIONS_V2 = extern struct { dwSize: u32, dwMask: u32, dwDumpFlags: u32, bOnlyThisThread: BOOL, dwExceptionThreadFlags: u32, dwOtherThreadFlags: u32, dwExceptionThreadExFlags: u32, dwOtherThreadExFlags: u32, dwPreferredModuleFlags: u32, dwOtherModuleFlags: u32, wzPreferredModuleList: [256]u16, dwPreferredModuleResetFlags: u32, dwOtherModuleResetFlags: u32, }; pub const WER_REPORT_INFORMATION_V4 = extern struct { dwSize: u32, hProcess: ?HANDLE, wzConsentKey: [64]u16, wzFriendlyEventName: [128]u16, wzApplicationName: [128]u16, wzApplicationPath: [260]u16, wzDescription: [512]u16, hwndParent: ?HWND, wzNamespacePartner: [64]u16, wzNamespaceGroup: [64]u16, rgbApplicationIdentity: [16]u8, hSnapshot: ?HANDLE, hDeleteFilesImpersonationToken: ?HANDLE, }; pub const WER_REPORT_INFORMATION_V5 = extern struct { dwSize: u32, hProcess: ?HANDLE, wzConsentKey: [64]u16, wzFriendlyEventName: [128]u16, wzApplicationName: [128]u16, wzApplicationPath: [260]u16, wzDescription: [512]u16, hwndParent: ?HWND, wzNamespacePartner: [64]u16, wzNamespaceGroup: [64]u16, rgbApplicationIdentity: [16]u8, hSnapshot: ?HANDLE, hDeleteFilesImpersonationToken: ?HANDLE, submitResultMax: WER_SUBMIT_RESULT, }; pub const WER_DUMP_CUSTOM_OPTIONS_V3 = extern struct { dwSize: u32, dwMask: u32, dwDumpFlags: u32, bOnlyThisThread: BOOL, dwExceptionThreadFlags: u32, dwOtherThreadFlags: u32, dwExceptionThreadExFlags: u32, dwOtherThreadExFlags: u32, dwPreferredModuleFlags: u32, dwOtherModuleFlags: u32, wzPreferredModuleList: [256]u16, dwPreferredModuleResetFlags: u32, dwOtherModuleResetFlags: u32, pvDumpKey: ?*anyopaque, hSnapshot: ?HANDLE, dwThreadID: u32, }; pub const WER_EXCEPTION_INFORMATION = extern struct { pExceptionPointers: ?*EXCEPTION_POINTERS, bClientPointers: BOOL, }; pub const WER_CONSENT = enum(i32) { NotAsked = 1, Approved = 2, Denied = 3, AlwaysPrompt = 4, Max = 5, }; pub const WerConsentNotAsked = WER_CONSENT.NotAsked; pub const WerConsentApproved = WER_CONSENT.Approved; pub const WerConsentDenied = WER_CONSENT.Denied; pub const WerConsentAlwaysPrompt = WER_CONSENT.AlwaysPrompt; pub const WerConsentMax = WER_CONSENT.Max; pub const WER_DUMP_TYPE = enum(i32) { None = 0, MicroDump = 1, MiniDump = 2, HeapDump = 3, TriageDump = 4, Max = 5, }; pub const WerDumpTypeNone = WER_DUMP_TYPE.None; pub const WerDumpTypeMicroDump = WER_DUMP_TYPE.MicroDump; pub const WerDumpTypeMiniDump = WER_DUMP_TYPE.MiniDump; pub const WerDumpTypeHeapDump = WER_DUMP_TYPE.HeapDump; pub const WerDumpTypeTriageDump = WER_DUMP_TYPE.TriageDump; pub const WerDumpTypeMax = WER_DUMP_TYPE.Max; pub const WER_RUNTIME_EXCEPTION_INFORMATION = extern struct { dwSize: u32, hProcess: ?HANDLE, hThread: ?HANDLE, exceptionRecord: EXCEPTION_RECORD, context: CONTEXT, pwszReportId: ?[*:0]const u16, bIsFatal: BOOL, dwReserved: u32, }; pub const PFN_WER_RUNTIME_EXCEPTION_EVENT = fn( pContext: ?*anyopaque, pExceptionInformation: ?*const WER_RUNTIME_EXCEPTION_INFORMATION, pbOwnershipClaimed: ?*BOOL, pwszEventName: [*:0]u16, pchSize: ?*u32, pdwSignatureCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_WER_RUNTIME_EXCEPTION_EVENT_SIGNATURE = fn( pContext: ?*anyopaque, pExceptionInformation: ?*const WER_RUNTIME_EXCEPTION_INFORMATION, dwIndex: u32, pwszName: [*:0]u16, pchName: ?*u32, pwszValue: [*:0]u16, pchValue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const PFN_WER_RUNTIME_EXCEPTION_DEBUGGER_LAUNCH = fn( pContext: ?*anyopaque, pExceptionInformation: ?*const WER_RUNTIME_EXCEPTION_INFORMATION, pbIsCustomDebugger: ?*BOOL, pwszDebuggerLaunch: [*:0]u16, pchDebuggerLaunch: ?*u32, pbIsDebuggerAutolaunch: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub const REPORT_STORE_TYPES = enum(i32) { USER_ARCHIVE = 0, USER_QUEUE = 1, MACHINE_ARCHIVE = 2, MACHINE_QUEUE = 3, INVALID = 4, }; pub const E_STORE_USER_ARCHIVE = REPORT_STORE_TYPES.USER_ARCHIVE; pub const E_STORE_USER_QUEUE = REPORT_STORE_TYPES.USER_QUEUE; pub const E_STORE_MACHINE_ARCHIVE = REPORT_STORE_TYPES.MACHINE_ARCHIVE; pub const E_STORE_MACHINE_QUEUE = REPORT_STORE_TYPES.MACHINE_QUEUE; pub const E_STORE_INVALID = REPORT_STORE_TYPES.INVALID; pub const WER_REPORT_PARAMETER = extern struct { Name: [129]u16, Value: [260]u16, }; pub const WER_REPORT_SIGNATURE = extern struct { EventName: [65]u16, Parameters: [10]WER_REPORT_PARAMETER, }; pub const WER_REPORT_METADATA_V2 = extern struct { Signature: WER_REPORT_SIGNATURE, BucketId: Guid, ReportId: Guid, CreationTime: FILETIME, SizeInBytes: u64, CabId: [260]u16, ReportStatus: u32, ReportIntegratorId: Guid, NumberOfFiles: u32, SizeOfFileNames: u32, FileNames: ?PWSTR, }; pub const WER_REPORT_METADATA_V3 = extern struct { Signature: WER_REPORT_SIGNATURE, BucketId: Guid, ReportId: Guid, CreationTime: FILETIME, SizeInBytes: u64, CabId: [260]u16, ReportStatus: u32, ReportIntegratorId: Guid, NumberOfFiles: u32, SizeOfFileNames: u32, FileNames: ?PWSTR, FriendlyEventName: [128]u16, ApplicationName: [128]u16, ApplicationPath: [260]u16, Description: [512]u16, BucketIdString: [260]u16, LegacyBucketId: u64, }; pub const WER_REPORT_METADATA_V1 = extern struct { Signature: WER_REPORT_SIGNATURE, BucketId: Guid, ReportId: Guid, CreationTime: FILETIME, SizeInBytes: u64, }; pub const EFaultRepRetVal = enum(i32) { Ok = 0, OkManifest = 1, OkQueued = 2, Err = 3, ErrNoDW = 4, ErrTimeout = 5, LaunchDebugger = 6, OkHeadless = 7, ErrAnotherInstance = 8, ErrNoMemory = 9, ErrDoubleFault = 10, }; pub const frrvOk = EFaultRepRetVal.Ok; pub const frrvOkManifest = EFaultRepRetVal.OkManifest; pub const frrvOkQueued = EFaultRepRetVal.OkQueued; pub const frrvErr = EFaultRepRetVal.Err; pub const frrvErrNoDW = EFaultRepRetVal.ErrNoDW; pub const frrvErrTimeout = EFaultRepRetVal.ErrTimeout; pub const frrvLaunchDebugger = EFaultRepRetVal.LaunchDebugger; pub const frrvOkHeadless = EFaultRepRetVal.OkHeadless; pub const frrvErrAnotherInstance = EFaultRepRetVal.ErrAnotherInstance; pub const frrvErrNoMemory = EFaultRepRetVal.ErrNoMemory; pub const frrvErrDoubleFault = EFaultRepRetVal.ErrDoubleFault; pub const pfn_REPORTFAULT = fn( param0: ?*EXCEPTION_POINTERS, param1: u32, ) callconv(@import("std").os.windows.WINAPI) EFaultRepRetVal; pub const pfn_ADDEREXCLUDEDAPPLICATIONA = fn( param0: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) EFaultRepRetVal; pub const pfn_ADDEREXCLUDEDAPPLICATIONW = fn( param0: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) EFaultRepRetVal; //-------------------------------------------------------------------------------- // Section: Functions (41) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportCreate( pwzEventType: ?[*:0]const u16, repType: WER_REPORT_TYPE, pReportInformation: ?*WER_REPORT_INFORMATION, phReportHandle: ?*HREPORT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportSetParameter( hReportHandle: HREPORT, dwparamID: u32, pwzName: ?[*:0]const u16, pwzValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportAddFile( hReportHandle: HREPORT, pwzPath: ?[*:0]const u16, repFileType: WER_FILE_TYPE, dwFileFlags: WER_FILE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportSetUIOption( hReportHandle: HREPORT, repUITypeID: WER_REPORT_UI, pwzValue: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportSubmit( hReportHandle: HREPORT, consent: WER_CONSENT, dwFlags: WER_SUBMIT_FLAGS, pSubmitResult: ?*WER_SUBMIT_RESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportAddDump( hReportHandle: HREPORT, hProcess: ?HANDLE, hThread: ?HANDLE, dumpType: WER_DUMP_TYPE, pExceptionParam: ?*WER_EXCEPTION_INFORMATION, pDumpCustomOptions: ?*WER_DUMP_CUSTOM_OPTIONS, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerReportCloseHandle( hReportHandle: HREPORT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WerRegisterFile( pwzFile: ?[*:0]const u16, regFileType: WER_REGISTER_FILE_TYPE, dwFlags: WER_FILE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WerUnregisterFile( pwzFilePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WerRegisterMemoryBlock( pvAddress: ?*anyopaque, dwSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WerUnregisterMemoryBlock( pvAddress: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "KERNEL32" fn WerRegisterExcludedMemoryBlock( address: ?*const anyopaque, size: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "KERNEL32" fn WerUnregisterExcludedMemoryBlock( address: ?*const anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "KERNEL32" fn WerRegisterCustomMetadata( key: ?[*:0]const u16, value: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "KERNEL32" fn WerUnregisterCustomMetadata( key: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "KERNEL32" fn WerRegisterAdditionalProcess( processId: u32, captureExtraInfoForThreadId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "KERNEL32" fn WerUnregisterAdditionalProcess( processId: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "KERNEL32" fn WerRegisterAppLocalDump( localAppDataRelativePath: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.16299' pub extern "KERNEL32" fn WerUnregisterAppLocalDump( ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WerSetFlags( dwFlags: WER_FAULT_REPORTING, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "KERNEL32" fn WerGetFlags( hProcess: ?HANDLE, pdwFlags: ?*WER_FAULT_REPORTING, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerAddExcludedApplication( pwzExeName: ?[*:0]const u16, bAllUsers: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wer" fn WerRemoveExcludedApplication( pwzExeName: ?[*:0]const u16, bAllUsers: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "KERNEL32" fn WerRegisterRuntimeExceptionModule( pwszOutOfProcessCallbackDll: ?[*:0]const u16, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.1' pub extern "KERNEL32" fn WerUnregisterRuntimeExceptionModule( pwszOutOfProcessCallbackDll: ?[*:0]const u16, pContext: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "wer" fn WerStoreOpen( repStoreType: REPORT_STORE_TYPES, phReportStore: ?*HREPORTSTORE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "wer" fn WerStoreClose( hReportStore: HREPORTSTORE, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "wer" fn WerStoreGetFirstReportKey( hReportStore: HREPORTSTORE, ppszReportKey: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "wer" fn WerStoreGetNextReportKey( hReportStore: HREPORTSTORE, ppszReportKey: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "wer" fn WerStoreQueryReportMetadataV2( hReportStore: HREPORTSTORE, pszReportKey: ?[*:0]const u16, pReportMetadata: ?*WER_REPORT_METADATA_V2, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "wer" fn WerStoreQueryReportMetadataV3( hReportStore: HREPORTSTORE, pszReportKey: ?[*:0]const u16, pReportMetadata: ?*WER_REPORT_METADATA_V3, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows10.0.15063' pub extern "wer" fn WerFreeString( pwszStr: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "wer" fn WerStorePurge( ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "wer" fn WerStoreGetReportCount( hReportStore: HREPORTSTORE, pdwReportCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "wer" fn WerStoreGetSizeOnDisk( hReportStore: HREPORTSTORE, pqwSizeInBytes: ?*u64, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "wer" fn WerStoreQueryReportMetadataV1( hReportStore: HREPORTSTORE, pszReportKey: ?[*:0]const u16, pReportMetadata: ?*WER_REPORT_METADATA_V1, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "wer" fn WerStoreUploadReport( hReportStore: HREPORTSTORE, pszReportKey: ?[*:0]const u16, dwFlags: u32, pSubmitResult: ?*WER_SUBMIT_RESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "faultrep" fn ReportFault( pep: ?*EXCEPTION_POINTERS, dwOpt: u32, ) callconv(@import("std").os.windows.WINAPI) EFaultRepRetVal; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "faultrep" fn AddERExcludedApplicationA( szApplication: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.1.2600' pub extern "faultrep" fn AddERExcludedApplicationW( wszApplication: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "faultrep" fn WerReportHang( hwndHungApp: ?HWND, pwzHungApplicationName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (2) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const pfn_ADDEREXCLUDEDAPPLICATION = thismodule.pfn_ADDEREXCLUDEDAPPLICATIONA; pub const AddERExcludedApplication = thismodule.AddERExcludedApplicationA; }, .wide => struct { pub const pfn_ADDEREXCLUDEDAPPLICATION = thismodule.pfn_ADDEREXCLUDEDAPPLICATIONW; pub const AddERExcludedApplication = thismodule.AddERExcludedApplicationW; }, .unspecified => if (@import("builtin").is_test) struct { pub const pfn_ADDEREXCLUDEDAPPLICATION = *opaque{}; pub const AddERExcludedApplication = *opaque{}; } else struct { pub const pfn_ADDEREXCLUDEDAPPLICATION = @compileError("'pfn_ADDEREXCLUDEDAPPLICATION' requires that UNICODE be set to true or false in the root module"); pub const AddERExcludedApplication = @compileError("'AddERExcludedApplication' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (11) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const CONTEXT = @import("../system/diagnostics/debug.zig").CONTEXT; const EXCEPTION_POINTERS = @import("../system/diagnostics/debug.zig").EXCEPTION_POINTERS; const EXCEPTION_RECORD = @import("../system/diagnostics/debug.zig").EXCEPTION_RECORD; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFN_WER_RUNTIME_EXCEPTION_EVENT")) { _ = PFN_WER_RUNTIME_EXCEPTION_EVENT; } if (@hasDecl(@This(), "PFN_WER_RUNTIME_EXCEPTION_EVENT_SIGNATURE")) { _ = PFN_WER_RUNTIME_EXCEPTION_EVENT_SIGNATURE; } if (@hasDecl(@This(), "PFN_WER_RUNTIME_EXCEPTION_DEBUGGER_LAUNCH")) { _ = PFN_WER_RUNTIME_EXCEPTION_DEBUGGER_LAUNCH; } if (@hasDecl(@This(), "pfn_REPORTFAULT")) { _ = pfn_REPORTFAULT; } if (@hasDecl(@This(), "pfn_ADDEREXCLUDEDAPPLICATIONA")) { _ = pfn_ADDEREXCLUDEDAPPLICATIONA; } if (@hasDecl(@This(), "pfn_ADDEREXCLUDEDAPPLICATIONW")) { _ = pfn_ADDEREXCLUDEDAPPLICATIONW; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/system/error_reporting.zig
const std = @import("std"); const fmt = std.fmt; /// It's a fixed length buffer, useful for parsing strings /// without requiring an allocator. pub fn FixBuf(comptime size: usize) type { return struct { buf: [size]u8, len: usize, const Self = @This(); /// Returns a slice pointing to the contents in the buffer. pub fn toSlice(self: *const Self) []const u8 { return self.buf[0..self.len]; } pub const Redis = struct { pub const Parser = struct { pub fn parse(tag: u8, comptime rootParser: type, msg: anytype) !Self { switch (tag) { else => return error.UnsupportedConversion, '-', '!' => { try rootParser.parseFromTag(void, tag, msg); return error.GotErrorReply; }, '+', '(' => { var res: Self = undefined; var ch = try msg.readByte(); for (res.buf) |*elem, i| { if (ch == '\r') { res.len = i; try msg.skipBytes(1, .{}); return res; } elem.* = ch; ch = try msg.readByte(); } if (ch != '\r') return error.BufTooSmall; try msg.skipBytes(1, .{}); return res; }, '$' => { // TODO: write real implementation var buf: [100]u8 = undefined; var end: usize = 0; for (buf) |*elem, i| { const ch = try msg.readByte(); elem.* = ch; if (ch == '\r') { end = i; break; } } try msg.skipBytes(1, .{}); const respSize = try fmt.parseInt(usize, buf[0..end], 10); if (respSize > size) return error.BufTooSmall; var res: Self = undefined; res.len = respSize; _ = try msg.readNoEof(res.buf[0..respSize]); try msg.skipBytes(2, .{}); return res; }, } } pub fn destroy(self: Self, comptime rootParser: type, allocator: *std.mem.Allocator) void {} pub fn parseAlloc(tag: u8, comptime _: type, msg: anytype) !Self { return parse(tag, _, msg); } }; }; }; } test "docs" { @import("std").meta.refAllDecls(@This()); @import("std").meta.refAllDecls(FixBuf(42)); }
src/types/fixbuf.zig
const std = @import("std"); const Answer = struct { @"0": u32, @"1": u32 }; const Point = struct { x: usize, y: usize }; const Neighbors = struct { items: [8]Point, len: usize }; fn displace(i: usize, ii: i32) i32 { return @intCast(i32, i) + ii; } const Grid = struct { const Self = @This(); items: []u32, height: usize, width: usize, num_flashes: u32, step_num: u32, sync_flash: ?u32, allocator: *std.mem.Allocator, pub fn init(height: usize, width: usize, allocator: *std.mem.Allocator) !Self { const items = try allocator.alloc(u32, height * width); std.mem.set(u32, items, 0); return Self{ .items = items, .height = height, .width = width, .num_flashes = 0, .step_num = 0, .sync_flash = null, .allocator = allocator, }; } pub fn deinit(self: Self) void { self.allocator.free(self.items); } pub fn ix(self: Self, row: usize, col: usize) *u32 { std.debug.assert(col < self.width); return &self.items[row * self.width + col]; } pub fn step(self: *Self) void { var num_flashes_before = self.num_flashes; { var i: usize = 0; while (i < self.height) : (i += 1) { var j: usize = 0; while (j < self.width) : (j += 1) { self.charge(i, j); } } } { var i: usize = 0; while (i < self.height) : (i += 1) { var j: usize = 0; while (j < self.width) : (j += 1) { self.ix(i, j).* %= 10; } } } self.step_num += 1; var num_flashes_this_step = self.num_flashes - num_flashes_before; if (num_flashes_this_step == self.width * self.height) { self.sync_flash = self.sync_flash orelse self.step_num; } } pub fn charge(self: *Self, row: usize, col: usize) void { if (self.ix(row, col).* != 10) { self.ix(row, col).* += 1; if (self.ix(row, col).* == 10) { self.flash(row, col); self.num_flashes += 1; } } } pub fn flash(self: *Self, row: usize, col: usize) void { const neighbor_coords = self.neighbors(row, col); var i: usize = 0; while (i < neighbor_coords.len) : (i += 1) { self.charge(neighbor_coords.items[i].y, neighbor_coords.items[i].x); } } pub fn neighbors(self: Self, row: usize, col: usize) Neighbors { var num_neighbors: usize = 0; var neighbor_coords = [_]Point{undefined} ** 8; for ([_]i32{ -1, 0, 1 }) |i| { for ([_]i32{ -1, 0, 1 }) |j| { if (i == 0 and j == 0) { continue; } if (self.in_bounds(displace(row, i), displace(col, j))) { neighbor_coords[num_neighbors] = Point{ .x = @intCast(usize, displace(col, j)), .y = @intCast(usize, displace(row, i)) }; num_neighbors += 1; } } } return Neighbors{ .items = neighbor_coords, .len = num_neighbors }; } pub fn in_bounds(self: Self, row: i32, col: i32) bool { return 0 <= row and @intCast(usize, row) < self.height and 0 <= col and @intCast(usize, col) < self.width; } }; fn run(filename: []const u8) !Answer { const file = try std.fs.cwd().openFile(filename, .{ .read = true }); defer file.close(); var reader = std.io.bufferedReader(file.reader()).reader(); var buffer: [4096]u8 = undefined; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var grid = try Grid.init(10, 10, &gpa.allocator); defer grid.deinit(); try file.seekTo(0); var i: usize = 0; while (try reader.readUntilDelimiterOrEof(&buffer, '\n')) |line| : (i += 1) { for (line) |c, j| { grid.ix(i, j).* = c - '0'; } } i = 0; while (i < 100) : (i += 1) { grid.step(); } const num_flashes = grid.num_flashes; while (grid.sync_flash == null) { grid.step(); } return Answer{ .@"0" = num_flashes, .@"1" = grid.sync_flash.? }; } pub fn main() !void { const answer = try run("inputs/" ++ @typeName(@This()) ++ ".txt"); std.debug.print("{d}\n", .{answer.@"0"}); std.debug.print("{d}\n", .{answer.@"1"}); } test { const answer = try run("test-inputs/" ++ @typeName(@This()) ++ ".txt"); try std.testing.expectEqual(@as(u32, 1656), answer.@"0"); try std.testing.expectEqual(@as(u32, 195), answer.@"1"); }
src/day11.zig
const std = @import("std"); const builtin = @import("builtin"); const build_options = @import("build_options"); pub const enable = if (builtin.is_test) false else build_options.enable_tracy; pub const enable_allocation = enable and build_options.enable_tracy_allocation; pub const enable_callstack = enable and build_options.enable_tracy_callstack; // TODO: make this configurable const callstack_depth = 10; const ___tracy_c_zone_context = extern struct { id: u32, active: c_int, pub inline fn end(self: @This()) void { ___tracy_emit_zone_end(self); } pub inline fn addText(self: @This(), text: []const u8) void { ___tracy_emit_zone_text(self, text.ptr, text.len); } pub inline fn setName(self: @This(), name: []const u8) void { ___tracy_emit_zone_name(self, name.ptr, name.len); } pub inline fn setColor(self: @This(), color: u32) void { ___tracy_emit_zone_color(self, color); } pub inline fn setValue(self: @This(), value: u64) void { ___tracy_emit_zone_value(self, value); } }; pub const Ctx = if (enable) ___tracy_c_zone_context else struct { pub inline fn end(self: @This()) void { _ = self; } pub inline fn addText(self: @This(), text: []const u8) void { _ = self; _ = text; } pub inline fn setName(self: @This(), name: []const u8) void { _ = self; _ = name; } pub inline fn setColor(self: @This(), color: u32) void { _ = self; _ = color; } pub inline fn setValue(self: @This(), value: u64) void { _ = self; _ = value; } }; pub inline fn trace(comptime src: std.builtin.SourceLocation) Ctx { if (!enable) return .{}; if (enable_callstack) { return ___tracy_emit_zone_begin_callstack(&.{ .name = null, .function = src.fn_name.ptr, .file = src.file.ptr, .line = src.line, .color = 0, }, callstack_depth, 1); } else { return ___tracy_emit_zone_begin(&.{ .name = null, .function = src.fn_name.ptr, .file = src.file.ptr, .line = src.line, .color = 0, }, 1); } } pub inline fn traceNamed(comptime src: std.builtin.SourceLocation, comptime name: [:0]const u8) Ctx { if (!enable) return .{}; if (enable_callstack) { return ___tracy_emit_zone_begin_callstack(&.{ .name = name.ptr, .function = src.fn_name.ptr, .file = src.file.ptr, .line = src.line, .color = 0, }, callstack_depth, 1); } else { return ___tracy_emit_zone_begin(&.{ .name = name.ptr, .function = src.fn_name.ptr, .file = src.file.ptr, .line = src.line, .color = 0, }, 1); } } pub fn tracyAllocator(allocator: std.mem.Allocator) TracyAllocator(null) { return TracyAllocator(null).init(allocator); } pub fn TracyAllocator(comptime name: ?[:0]const u8) type { return struct { parent_allocator: std.mem.Allocator, const Self = @This(); pub fn init(parent_allocator: std.mem.Allocator) Self { return .{ .parent_allocator = parent_allocator, }; } pub fn allocator(self: *Self) std.mem.Allocator { return std.mem.Allocator.init(self, allocFn, resizeFn, freeFn); } fn allocFn(self: *Self, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) std.mem.Allocator.Error![]u8 { const result = self.parent_allocator.rawAlloc(len, ptr_align, len_align, ret_addr); if (result) |data| { if (data.len != 0) { if (name) |n| { allocNamed(data.ptr, data.len, n); } else { alloc(data.ptr, data.len); } } } else |_| { messageColor("allocation failed", 0xFF0000); } return result; } fn resizeFn(self: *Self, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize { if (self.parent_allocator.rawResize(buf, buf_align, new_len, len_align, ret_addr)) |resized_len| { if (name) |n| { freeNamed(buf.ptr, n); allocNamed(buf.ptr, resized_len, n); } else { free(buf.ptr); alloc(buf.ptr, resized_len); } return resized_len; } // during normal operation the compiler hits this case thousands of times due to this // emitting messages for it is both slow and causes clutter return null; } fn freeFn(self: *Self, buf: []u8, buf_align: u29, ret_addr: usize) void { self.parent_allocator.rawFree(buf, buf_align, ret_addr); // this condition is to handle free being called on an empty slice that was never even allocated // example case: `std.process.getSelfExeSharedLibPaths` can return `&[_][:0]u8{}` if (buf.len != 0) { if (name) |n| { freeNamed(buf.ptr, n); } else { free(buf.ptr); } } } }; } // This function only accepts comptime known strings, see `messageCopy` for runtime strings pub inline fn message(comptime msg: [:0]const u8) void { if (!enable) return; ___tracy_emit_messageL(msg.ptr, if (enable_callstack) callstack_depth else 0); } // This function only accepts comptime known strings, see `messageColorCopy` for runtime strings pub inline fn messageColor(comptime msg: [:0]const u8, color: u32) void { if (!enable) return; ___tracy_emit_messageLC(msg.ptr, color, if (enable_callstack) callstack_depth else 0); } pub inline fn messageCopy(msg: []const u8) void { if (!enable) return; ___tracy_emit_message(msg.ptr, msg.len, if (enable_callstack) callstack_depth else 0); } pub inline fn messageColorCopy(msg: [:0]const u8, color: u32) void { if (!enable) return; ___tracy_emit_messageC(msg.ptr, msg.len, color, if (enable_callstack) callstack_depth else 0); } pub inline fn frameMark() void { if (!enable) return; ___tracy_emit_frame_mark(null); } pub inline fn frameMarkNamed(comptime name: [:0]const u8) void { if (!enable) return; ___tracy_emit_frame_mark(name.ptr); } pub inline fn namedFrame(comptime name: [:0]const u8) Frame(name) { frameMarkStart(name); return .{}; } pub fn Frame(comptime name: [:0]const u8) type { return struct { pub fn end(_: @This()) void { frameMarkEnd(name); } }; } inline fn frameMarkStart(comptime name: [:0]const u8) void { if (!enable) return; ___tracy_emit_frame_mark_start(name.ptr); } inline fn frameMarkEnd(comptime name: [:0]const u8) void { if (!enable) return; ___tracy_emit_frame_mark_end(name.ptr); } extern fn ___tracy_emit_frame_mark_start(name: [*:0]const u8) void; extern fn ___tracy_emit_frame_mark_end(name: [*:0]const u8) void; inline fn alloc(ptr: [*]u8, len: usize) void { if (!enable) return; if (enable_callstack) { ___tracy_emit_memory_alloc_callstack(ptr, len, callstack_depth, 0); } else { ___tracy_emit_memory_alloc(ptr, len, 0); } } inline fn allocNamed(ptr: [*]u8, len: usize, comptime name: [:0]const u8) void { if (!enable) return; if (enable_callstack) { ___tracy_emit_memory_alloc_callstack_named(ptr, len, callstack_depth, 0, name.ptr); } else { ___tracy_emit_memory_alloc_named(ptr, len, 0, name.ptr); } } inline fn free(ptr: [*]u8) void { if (!enable) return; if (enable_callstack) { ___tracy_emit_memory_free_callstack(ptr, callstack_depth, 0); } else { ___tracy_emit_memory_free(ptr, 0); } } inline fn freeNamed(ptr: [*]u8, comptime name: [:0]const u8) void { if (!enable) return; if (enable_callstack) { ___tracy_emit_memory_free_callstack_named(ptr, callstack_depth, 0, name.ptr); } else { ___tracy_emit_memory_free_named(ptr, 0, name.ptr); } } extern fn ___tracy_emit_zone_begin( srcloc: *const ___tracy_source_location_data, active: c_int, ) ___tracy_c_zone_context; extern fn ___tracy_emit_zone_begin_callstack( srcloc: *const ___tracy_source_location_data, depth: c_int, active: c_int, ) ___tracy_c_zone_context; extern fn ___tracy_emit_zone_text(ctx: ___tracy_c_zone_context, txt: [*]const u8, size: usize) void; extern fn ___tracy_emit_zone_name(ctx: ___tracy_c_zone_context, txt: [*]const u8, size: usize) void; extern fn ___tracy_emit_zone_color(ctx: ___tracy_c_zone_context, color: u32) void; extern fn ___tracy_emit_zone_value(ctx: ___tracy_c_zone_context, value: u64) void; extern fn ___tracy_emit_zone_end(ctx: ___tracy_c_zone_context) void; extern fn ___tracy_emit_memory_alloc(ptr: *const anyopaque, size: usize, secure: c_int) void; extern fn ___tracy_emit_memory_alloc_callstack(ptr: *const anyopaque, size: usize, depth: c_int, secure: c_int) void; extern fn ___tracy_emit_memory_free(ptr: *const anyopaque, secure: c_int) void; extern fn ___tracy_emit_memory_free_callstack(ptr: *const anyopaque, depth: c_int, secure: c_int) void; extern fn ___tracy_emit_memory_alloc_named(ptr: *const anyopaque, size: usize, secure: c_int, name: [*:0]const u8) void; extern fn ___tracy_emit_memory_alloc_callstack_named(ptr: *const anyopaque, size: usize, depth: c_int, secure: c_int, name: [*:0]const u8) void; extern fn ___tracy_emit_memory_free_named(ptr: *const anyopaque, secure: c_int, name: [*:0]const u8) void; extern fn ___tracy_emit_memory_free_callstack_named(ptr: *const anyopaque, depth: c_int, secure: c_int, name: [*:0]const u8) void; extern fn ___tracy_emit_message(txt: [*]const u8, size: usize, callstack: c_int) void; extern fn ___tracy_emit_messageL(txt: [*:0]const u8, callstack: c_int) void; extern fn ___tracy_emit_messageC(txt: [*]const u8, size: usize, color: u32, callstack: c_int) void; extern fn ___tracy_emit_messageLC(txt: [*:0]const u8, color: u32, callstack: c_int) void; extern fn ___tracy_emit_frame_mark(name: ?[*:0]const u8) void; const ___tracy_source_location_data = extern struct { name: ?[*:0]const u8, function: [*:0]const u8, file: [*:0]const u8, line: u32, color: u32, };
src/tracy.zig
const std = @import("std"); const assert = std.debug.assert; const c = @import("c.zig"); const translate = @import("translate.zig"); const tb = @import("tigerbeetle/src/tigerbeetle.zig"); const Account = tb.Account; const AccountFlags = tb.AccountFlags; const Transfer = tb.Transfer; const TransferFlags = tb.TransferFlags; const Commit = tb.Commit; const CommitFlags = tb.CommitFlags; const CreateAccountsResult = tb.CreateAccountsResult; const CreateTransfersResult = tb.CreateTransfersResult; const CommitTransfersResult = tb.CommitTransfersResult; const StateMachine = @import("tigerbeetle/src/state_machine.zig").StateMachine; const Operation = StateMachine.Operation; const MessageBus = @import("tigerbeetle/src/message_bus.zig").MessageBusClient; const IO = @import("tigerbeetle/src/io.zig").IO; const config = @import("tigerbeetle/src/config.zig"); const vsr = @import("tigerbeetle/src/vsr.zig"); const Header = vsr.Header; const Client = vsr.Client(StateMachine, MessageBus); pub const log_level: std.log.Level = .info; /// N-API will call this constructor automatically to register the module. export fn napi_register_module_v1(env: c.napi_env, exports: c.napi_value) c.napi_value { translate.register_function(env, exports, "init", init) catch return null; translate.register_function(env, exports, "deinit", deinit) catch return null; translate.register_function(env, exports, "request", request) catch return null; translate.register_function(env, exports, "raw_request", raw_request) catch return null; translate.register_function(env, exports, "tick", tick) catch return null; translate.u32_into_object( env, exports, "tick_ms", config.tick_ms, "failed to add tick_ms to exports", ) catch return null; const allocator = std.heap.c_allocator; var global = Globals.init(allocator, env) catch { std.log.emerg("Failed to initialise environment.\n", .{}); return null; }; errdefer global.deinit(); // Tie the global state to this Node.js environment. This allows us to be thread safe. // See https://nodejs.org/api/n-api.html#n_api_environment_life_cycle_apis. // A cleanup function is registered as well that Node will call when the environment // is torn down. Be careful not to call this function again as it will overwrite the global // state. translate.set_instance_data( env, @ptrCast(*c_void, @alignCast(@alignOf(u8), global)), Globals.destroy, ) catch { global.deinit(); return null; }; return exports; } const Globals = struct { allocator: *std.mem.Allocator, io: IO, napi_undefined: c.napi_value, pub fn init(allocator: *std.mem.Allocator, env: c.napi_env) !*Globals { const self = try allocator.create(Globals); errdefer allocator.destroy(self); self.allocator = allocator; // Be careful to size the SQ ring to only a few SQE entries and to share a single IO // instance across multiple clients to stay under kernel limits: // // The memory required by io_uring is accounted under the rlimit memlocked option, which can // be quite low on some setups (64K). The default is usually enough for most use cases, but // bigger rings or things like registered buffers deplete it quickly. Root isn't under this // restriction, but regular users are. // // Check `/etc/security/limits.conf` for user settings, or `/etc/systemd/user.conf` and // `/etc/systemd/system.conf` for systemd setups. self.io = IO.init(32, 0) catch { return translate.throw(env, "Failed to initialize io_uring"); }; errdefer self.io.deinit(); if (c.napi_get_undefined(env, &self.napi_undefined) != .napi_ok) { return translate.throw(env, "Failed to capture the value of \"undefined\"."); } return self; } pub fn deinit(self: *Globals) void { self.io.deinit(); self.allocator.destroy(self); } pub fn destroy(env: c.napi_env, data: ?*c_void, hint: ?*c_void) callconv(.C) void { const self = globalsCast(data.?); self.deinit(); } }; fn globalsCast(globals_raw: *c_void) *Globals { return @ptrCast(*Globals, @alignCast(@alignOf(Globals), globals_raw)); } const Context = struct { io: *IO, addresses: []std.net.Address, message_bus: MessageBus, client: Client, fn create( env: c.napi_env, allocator: *std.mem.Allocator, io: *IO, cluster: u32, addresses_raw: []const u8, ) !c.napi_value { const context = try allocator.create(Context); errdefer allocator.destroy(context); context.io = io; context.addresses = try vsr.parse_addresses(allocator, addresses_raw); errdefer allocator.free(context.addresses); assert(context.addresses.len > 0); const client_id = std.crypto.random.int(u128); context.message_bus = try MessageBus.init( allocator, cluster, context.addresses, client_id, context.io, ); errdefer context.message_bus.deinit(); context.client = try Client.init( allocator, client_id, cluster, @intCast(u8, context.addresses.len), &context.message_bus, ); errdefer context.client.deinit(); context.message_bus.set_on_message(*Client, &context.client, Client.on_message); return try translate.create_external(env, context); } }; fn contextCast(context_raw: *c_void) !*Context { return @ptrCast(*Context, @alignCast(@alignOf(Context), context_raw)); } fn validate_timestamp(env: c.napi_env, object: c.napi_value) !u64 { const timestamp = try translate.u64_from_object(env, object, "timestamp"); if (timestamp != 0) { return translate.throw( env, "Timestamp should be set as 0 as this will be set correctly by the Server.", ); } return timestamp; } fn decode_from_object(comptime T: type, env: c.napi_env, object: c.napi_value) !T { return switch (T) { Commit => Commit{ .id = try translate.u128_from_object(env, object, "id"), .reserved = try translate.bytes_from_object(env, object, 32, "reserved"), .code = try translate.u32_from_object(env, object, "code"), .flags = @bitCast(CommitFlags, try translate.u32_from_object(env, object, "flags")), .timestamp = try validate_timestamp(env, object), }, Transfer => Transfer{ .id = try translate.u128_from_object(env, object, "id"), .debit_account_id = try translate.u128_from_object(env, object, "debit_account_id"), .credit_account_id = try translate.u128_from_object(env, object, "credit_account_id"), .user_data = try translate.u128_from_object(env, object, "user_data"), .reserved = try translate.bytes_from_object(env, object, 32, "reserved"), .timeout = try translate.u64_from_object(env, object, "timeout"), .code = try translate.u32_from_object(env, object, "code"), .flags = @bitCast(TransferFlags, try translate.u32_from_object(env, object, "flags")), .amount = try translate.u64_from_object(env, object, "amount"), .timestamp = try validate_timestamp(env, object), }, Account => Account{ .id = try translate.u128_from_object(env, object, "id"), .user_data = try translate.u128_from_object(env, object, "user_data"), .reserved = try translate.bytes_from_object(env, object, 48, "reserved"), .unit = try translate.u16_from_object(env, object, "unit"), .code = try translate.u16_from_object(env, object, "code"), .flags = @bitCast(AccountFlags, try translate.u32_from_object(env, object, "flags")), .debits_reserved = try translate.u64_from_object(env, object, "debits_reserved"), .debits_accepted = try translate.u64_from_object(env, object, "debits_accepted"), .credits_reserved = try translate.u64_from_object(env, object, "credits_reserved"), .credits_accepted = try translate.u64_from_object(env, object, "credits_accepted"), .timestamp = try validate_timestamp(env, object), }, u128 => try translate.u128_from_value(env, object, "lookup"), else => unreachable, }; } pub fn decode_events( env: c.napi_env, array: c.napi_value, operation: Operation, output: []u8, ) !usize { return switch (operation) { .create_accounts => try decode_events_from_array(env, array, Account, output), .create_transfers => try decode_events_from_array(env, array, Transfer, output), .commit_transfers => try decode_events_from_array(env, array, Commit, output), .lookup_accounts => try decode_events_from_array(env, array, u128, output), .lookup_transfers => try decode_events_from_array(env, array, u128, output), else => unreachable, }; } fn decode_events_from_array( env: c.napi_env, array: c.napi_value, comptime T: type, output: []u8, ) !usize { const array_length = try translate.array_length(env, array); if (array_length < 1) return translate.throw(env, "Batch must contain at least one event."); const body_length = @sizeOf(T) * array_length; if (@sizeOf(Header) + body_length > config.message_size_max) { return translate.throw(env, "Batch is larger than the maximum message size."); } // We take a slice on `output` to ensure that its length is a multiple of @sizeOf(T) to prevent // a safety-checked runtime panic from `bytesAsSlice` for non-multiple sizes. var results = std.mem.bytesAsSlice(T, output[0..body_length]); var i: u32 = 0; while (i < array_length) : (i += 1) { const entry = try translate.array_element(env, array, i); results[i] = try decode_from_object(T, env, entry); } return body_length; } fn encode_napi_results_array( comptime Result: type, env: c.napi_env, data: []const u8, ) !c.napi_value { const results = std.mem.bytesAsSlice(Result, data); const napi_array = try translate.create_array( env, @intCast(u32, results.len), "Failed to allocate array for results.", ); switch (Result) { CreateAccountsResult, CreateTransfersResult, CommitTransfersResult => { var i: u32 = 0; while (i < results.len) : (i += 1) { const result = results[i]; const napi_object = try translate.create_object( env, "Failed to create result object", ); try translate.u32_into_object( env, napi_object, "index", result.index, "Failed to set property \"index\" of result.", ); try translate.u32_into_object( env, napi_object, "code", @enumToInt(result.result), "Failed to set property \"code\" of result.", ); try translate.set_array_element( env, napi_array, i, napi_object, "Failed to set element in results array.", ); } }, Account => { var i: u32 = 0; while (i < results.len) : (i += 1) { const result = results[i]; const napi_object = try translate.create_object( env, "Failed to create account lookup result object.", ); try translate.u128_into_object( env, napi_object, "id", result.id, "Failed to set property \"id\" of account lookup result.", ); try translate.u128_into_object( env, napi_object, "user_data", result.user_data, "Failed to set property \"user_data\" of account lookup result.", ); try translate.byte_slice_into_object( env, napi_object, "reserved", &result.reserved, "Failed to set property \"reserved\" of account lookup result.", ); try translate.u32_into_object( env, napi_object, "unit", @intCast(u32, result.unit), "Failed to set property \"unit\" of account lookup result.", ); try translate.u32_into_object( env, napi_object, "code", @intCast(u32, result.code), "Failed to set property \"code\" of account lookup result.", ); try translate.u32_into_object( env, napi_object, "flags", @bitCast(u32, result.flags), "Failed to set property \"flags\" of account lookup result.", ); try translate.u64_into_object( env, napi_object, "debits_reserved", result.debits_reserved, "Failed to set property \"debits_reserved\" of account lookup result.", ); try translate.u64_into_object( env, napi_object, "debits_accepted", result.debits_accepted, "Failed to set property \"debits_accepted\" of account lookup result.", ); try translate.u64_into_object( env, napi_object, "credits_reserved", result.credits_reserved, "Failed to set property \"credits_reserved\" of account lookup result.", ); try translate.u64_into_object( env, napi_object, "credits_accepted", result.credits_accepted, "Failed to set property \"credits_accepted\" of account lookup result.", ); try translate.u64_into_object( env, napi_object, "timestamp", result.timestamp, "Failed to set property \"timestamp\" of account lookup result.", ); try translate.set_array_element( env, napi_array, i, napi_object, "Failed to set element in results array.", ); } }, Transfer => { var i: u32 = 0; while (i < results.len) : (i += 1) { const result = results[i]; const napi_object = try translate.create_object( env, "Failed to create transfer lookup result object.", ); try translate.u128_into_object( env, napi_object, "id", result.id, "Failed to set property \"id\" of transfer lookup result.", ); try translate.u128_into_object( env, napi_object, "debit_account_id", result.debit_account_id, "Failed to set property \"debit_account_id\" of transfer lookup result.", ); try translate.u128_into_object( env, napi_object, "credit_account_id", result.credit_account_id, "Failed to set property \"credit_account_id\" of transfer lookup result.", ); try translate.u128_into_object( env, napi_object, "user_data", result.user_data, "Failed to set property \"user_data\" of transfer lookup result.", ); try translate.byte_slice_into_object( env, napi_object, "reserved", &result.reserved, "Failed to set property \"reserved\" of transfer lookup result.", ); try translate.u64_into_object( env, napi_object, "timeout", result.timeout, "Failed to set property \"timeout\" of transfer lookup result.", ); try translate.u32_into_object( env, napi_object, "code", @intCast(u32, result.code), "Failed to set property \"code\" of transfer lookup result.", ); try translate.u32_into_object( env, napi_object, "flags", @bitCast(u32, result.flags), "Failed to set property \"flags\" of transfer lookup result.", ); try translate.u64_into_object( env, napi_object, "amount", result.amount, "Failed to set property \"amount\" of transfer lookup result.", ); try translate.u64_into_object( env, napi_object, "timestamp", result.timestamp, "Failed to set property \"timestamp\" of transfer lookup result.", ); try translate.set_array_element( env, napi_array, i, napi_object, "Failed to set element in results array.", ); } }, else => unreachable, } return napi_array; } /// Add-on code fn init(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value { var argc: usize = 1; var argv: [1]c.napi_value = undefined; if (c.napi_get_cb_info(env, info, &argc, &argv, null, null) != .napi_ok) { translate.throw(env, "Failed to get args.") catch return null; } if (argc != 1) translate.throw( env, "Function init() must receive 1 argument exactly.", ) catch return null; const cluster = translate.u32_from_object(env, argv[0], "cluster_id") catch return null; const addresses = translate.slice_from_object( env, argv[0], "replica_addresses", ) catch return null; const allocator = std.heap.c_allocator; const globals_raw = translate.globals(env) catch return null; const globals = globalsCast(globals_raw.?); const context = Context.create(env, allocator, &globals.io, cluster, addresses) catch { // TODO: switch on err and provide more detailed messages translate.throw(env, "Failed to initialize Client.") catch return null; }; return context; } /// This function decodes and validates an array of Node objects, one-by-one, directly into an /// available message before requesting the client to send it. fn request(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value { var argc: usize = 4; var argv: [4]c.napi_value = undefined; if (c.napi_get_cb_info(env, info, &argc, &argv, null, null) != .napi_ok) { translate.throw(env, "Failed to get args.") catch return null; } if (argc != 4) translate.throw( env, "Function request() requires 4 arguments exactly.", ) catch return null; const context_raw = translate.value_external( env, argv[0], "Failed to get Client Context pointer.", ) catch return null; const context = contextCast(context_raw.?) catch return null; const operation_int = translate.u32_from_value(env, argv[1], "operation") catch return null; if (operation_int >= @typeInfo(Operation).Enum.fields.len) { translate.throw(env, "Unknown operation.") catch return null; } const message = context.client.get_message() orelse { translate.throw( env, "Too many requests outstanding.", ) catch return null; }; defer context.client.unref(message); const operation = @intToEnum(Operation, @intCast(u8, operation_int)); const body_length = decode_events( env, argv[2], operation, message.buffer[@sizeOf(Header)..], ) catch |err| switch (err) { error.ExceptionThrown => return null, }; // This will create a reference (in V8) to the user's JS callback that we must eventually also // free in order to avoid a leak. We therefore do this last to ensure we cannot fail after // taking this reference. const user_data = translate.user_data_from_value(env, argv[3]) catch return null; context.client.request(@bitCast(u128, user_data), on_result, operation, message, body_length); return null; } /// The batch has already been encoded into a byte slice. This means that we only have to do one /// copy directly into an available message. No validation of the encoded data is performed except /// that it will fit into the message buffer. fn raw_request(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value { var argc: usize = 4; var argv: [4]c.napi_value = undefined; if (c.napi_get_cb_info(env, info, &argc, &argv, null, null) != .napi_ok) { translate.throw(env, "Failed to get args.") catch return null; } if (argc != 4) translate.throw( env, "Function request() requires 4 arguments exactly.", ) catch return null; const context_raw = translate.value_external( env, argv[0], "Failed to get Client Context pointer.", ) catch return null; const context = contextCast(context_raw.?) catch return null; const operation_int = translate.u32_from_value(env, argv[1], "operation") catch return null; if (operation_int >= @typeInfo(Operation).Enum.fields.len) { translate.throw(env, "Unknown operation.") catch return null; } const operation = @intToEnum(Operation, @intCast(u8, operation_int)); const message = context.client.get_message() orelse { translate.throw( env, "Too many requests outstanding.", ) catch return null; }; defer context.client.unref(message); const body_length = translate.bytes_from_buffer( env, argv[2], message.buffer[@sizeOf(Header)..], "raw_batch", ) catch |err| switch (err) { error.ExceptionThrown => return null, }; // This will create a reference (in V8) to the user's JS callback that we must eventually also // free in order to avoid a leak. We therefore do this last to ensure we cannot fail after // taking this reference. const user_data = translate.user_data_from_value(env, argv[3]) catch return null; context.client.request(@bitCast(u128, user_data), on_result, operation, message, body_length); return null; } fn create_client_error(env: c.napi_env, client_error: Client.Error) !c.napi_value { return switch (client_error) { error.TooManyOutstandingRequests => try translate.create_error( env, "Too many outstanding requests - message pool exhausted.", ), }; } fn on_result(user_data: u128, operation: Operation, results: Client.Error![]const u8) void { // A reference to the user's JS callback was made in `request` or `raw_request`. This MUST be // cleaned up regardless of the result of this function. const env = @bitCast(translate.UserData, user_data).env; const callback_reference = @bitCast(translate.UserData, user_data).callback_reference; defer translate.delete_reference(env, callback_reference) catch { std.log.warn("on_result: Failed to delete reference to user's JS callback.", .{}); }; const napi_callback = translate.reference_value( env, callback_reference, "Failed to get callback reference.", ) catch return; const scope = translate.scope( env, "Failed to get \"this\" for results callback.", ) catch return; const globals_raw = translate.globals(env) catch return; const globals = globalsCast(globals_raw.?); const argc: usize = 2; var argv: [argc]c.napi_value = undefined; if (results) |value| { const napi_results = switch (operation) { .reserved, .init, .register => { translate.throw(env, "Reserved operation.") catch return; }, .create_accounts => encode_napi_results_array( CreateAccountsResult, env, value, ) catch return, .create_transfers => encode_napi_results_array( CreateTransfersResult, env, value, ) catch return, .commit_transfers => encode_napi_results_array( CommitTransfersResult, env, value, ) catch return, .lookup_accounts => encode_napi_results_array(Account, env, value) catch return, .lookup_transfers => encode_napi_results_array(Transfer, env, value) catch return, }; argv[0] = globals.napi_undefined; argv[1] = napi_results; } else |err| { argv[0] = create_client_error(env, err) catch { translate.throw(env, "Failed to create Node Error.") catch return; }; argv[1] = globals.napi_undefined; } translate.call_function(env, scope, napi_callback, argc, argv[0..]) catch { translate.throw(env, "Failed to call JS results callback.") catch return; }; } fn tick(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value { var argc: usize = 1; var argv: [1]c.napi_value = undefined; if (c.napi_get_cb_info(env, info, &argc, &argv, null, null) != .napi_ok) { translate.throw(env, "Failed to get args.") catch return null; } const allocator = std.heap.c_allocator; if (argc != 1) translate.throw( env, "Function tick() requires 1 argument exactly.", ) catch return null; const context_raw = translate.value_external( env, argv[0], "Failed to get Client Context pointer.", ) catch return null; const context = contextCast(context_raw.?) catch return null; context.client.tick(); context.io.tick() catch |err| switch (err) { // TODO exhaustive switch else => { translate.throw(env, "Failed to tick IO.") catch return null; }, }; return null; } fn deinit(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value { var argc: usize = 1; var argv: [1]c.napi_value = undefined; if (c.napi_get_cb_info(env, info, &argc, &argv, null, null) != .napi_ok) { translate.throw(env, "Failed to get args.") catch return null; } if (argc != 1) translate.throw( env, "Function deinit() requires 1 argument exactly.", ) catch return null; const context_raw = translate.value_external( env, argv[0], "Failed to get Client Context pointer.", ) catch return null; const context = contextCast(context_raw.?) catch return null; context.client.deinit(); context.message_bus.deinit(); return null; }
src/node.zig
const std = @import("std"); const assert = std.debug.assert; const Camera = @import("Camera.zig"); const Renderer = @import("Renderer.zig"); const Mesh = @import("Mesh.zig"); const Material = @import("Material.zig"); const zp = @import("../../zplay.zig"); const Texture2D = zp.graphics.texture.Texture2D; const gltf = zp.deps.gltf; const alg = zp.deps.alg; const Vec2 = alg.Vec2; const Vec3 = alg.Vec3; const Vec4 = alg.Vec4; const Mat4 = alg.Mat4; const Quat = alg.Quat; const Self = @This(); pub const Error = error{ NoRootNode, }; /// materials materials: std.ArrayList(Material) = undefined, /// meshes meshes: std.ArrayList(Mesh) = undefined, transforms: std.ArrayList(Mat4) = undefined, material_indices: std.ArrayList(u32) = undefined, /// generated textures generated_textures: std.ArrayList(Texture2D) = undefined, /// loaded textures loaded_textures: std.ArrayList(Texture2D) = undefined, /// load gltf model file /// WARNING: Model won't deallocate default texture, /// cause it might be used somewhere else, /// user's code knows better what to do with it. pub fn fromGLTF(allocator: std.mem.Allocator, filename: [:0]const u8, merge_meshes: bool, default_textre: ?Texture2D) !Self { var data: *gltf.Data = try gltf.loadFile(filename, null); defer gltf.free(data); var self = Self{ .materials = std.ArrayList(Material).initCapacity(allocator, 1) catch unreachable, .meshes = std.ArrayList(Mesh).initCapacity(allocator, 1) catch unreachable, .transforms = std.ArrayList(Mat4).initCapacity(allocator, 1) catch unreachable, .material_indices = std.ArrayList(u32).initCapacity(allocator, 1) catch unreachable, .generated_textures = std.ArrayList(Texture2D).initCapacity(allocator, 1) catch unreachable, .loaded_textures = std.ArrayList(Texture2D).initCapacity(allocator, 1) catch unreachable, }; // load vertex attributes assert(data.scenes_count > 0); assert(data.scene.*.nodes_count > 0); var root_node: ?*gltf.Node = blk: { var i: u32 = 0; while (i < data.scene.*.nodes_count) : (i += 1) { const node = @ptrCast(*gltf.Node, data.scene.*.nodes[i]); if (node.mesh != null) { break :blk node; } } // return first node by default break :blk @ptrCast(*gltf.Node, data.scene.*.nodes[0]); }; if (root_node == null) { return error.NoRootNode; } self.parseNode( allocator, data, root_node.?, Mat4.identity(), merge_meshes, ); // load images var i: u32 = 0; while (i < data.images_count) : (i += 1) { var image = @ptrCast(*gltf.Image, &data.images[i]); if (image.buffer_view != null) { var buffer_data = @ptrCast([*]const u8, image.buffer_view.*.buffer.*.data.?); var image_data = buffer_data + image.buffer_view.*.offset; self.loaded_textures.append(try Texture2D.fromFileData( allocator, image_data[0..image.buffer_view.*.size], false, .{}, )) catch unreachable; } else { var buf: [64]u8 = undefined; const dirname = std.fs.path.dirname(filename); const image_path = std.fmt.bufPrintZ( &buf, "{s}{s}{s}", .{ dirname, std.fs.path.sep_str, image.uri }, ) catch unreachable; self.loaded_textures.append(try Texture2D.fromFilePath( allocator, image_path, false, .{}, )) catch unreachable; } } // default pixel data if (default_textre == null) { self.generated_textures.append(try Texture2D.fromPixelData( allocator, &.{ 255, 255, 255, 255 }, 1, 1, .{}, )) catch unreachable; } // load materials var default_tex = if (default_textre) |tex| tex else self.generated_textures.items[0]; self.materials.append(Material.init(.{ .phong = .{ .diffuse_map = default_tex, .specular_map = default_tex, .shiness = 32, }, })) catch unreachable; i = 0; MATERIAL_LOOP: while (i < data.materials_count) : (i += 1) { var material = &data.materials[i]; assert(material.has_pbr_metallic_roughness > 0); // TODO PBR materials const pbrm = material.pbr_metallic_roughness; const base_color_texture = pbrm.base_color_texture; var image_idx: u32 = 0; while (image_idx < data.images_count) : (image_idx += 1) { const image = &data.images[image_idx]; if (base_color_texture.texture != null and base_color_texture.texture.*.image.*.uri == image.uri) { self.materials.append(Material.init(.{ .single_texture = self.loaded_textures.items[image_idx], })) catch unreachable; continue :MATERIAL_LOOP; } } const base_color = pbrm.base_color_factor; self.generated_textures.append(try Texture2D.fromPixelData( allocator, &.{ @floatToInt(u8, base_color[0] * 255), @floatToInt(u8, base_color[1] * 255), @floatToInt(u8, base_color[2] * 255), @floatToInt(u8, base_color[3] * 255), }, 1, 1, .{}, )) catch unreachable; self.materials.append(Material.init(.{ .single_texture = self.generated_textures.items[self.generated_textures.items.len - 1], })) catch unreachable; } // TODO load skins // TODO load animations // setup meshes' vertex buffer for (self.meshes.items) |m| { m.setup(); } return self; } /// deallocate resources pub fn deinit(self: Self) void { self.materials.deinit(); for (self.meshes.items) |m| { m.deinit(); } self.meshes.deinit(); self.transforms.deinit(); self.material_indices.deinit(); for (self.generated_textures.items) |t| { t.deinit(); } self.generated_textures.deinit(); for (self.loaded_textures.items) |t| { t.deinit(); } self.loaded_textures.deinit(); } fn parseNode( self: *Self, allocator: std.mem.Allocator, data: *gltf.Data, node: *gltf.Node, parent_transform: Mat4, merge_meshes: bool, ) void { // load transform matrix var transform = Mat4.identity(); if (node.has_matrix > 0) { transform = Mat4.fromSlice(&node.matrix).mult(transform); } else { if (node.has_scale > 0) { transform = Mat4.fromScale(Vec3.fromSlice(&node.scale)).mult(transform); } if (node.has_rotation > 0) { var quat = Quat.new( node.rotation[3], node.rotation[0], node.rotation[1], node.rotation[2], ); transform = quat.toMat4().mult(transform); } if (node.has_translation > 0) { transform = Mat4.fromTranslate(Vec3.fromSlice(&node.translation)).mult(transform); } } transform = parent_transform.mult(transform); // load meshes if (node.mesh != null) { var i: u32 = 0; while (i < node.mesh.*.primitives_count) : (i += 1) { const primitive = @ptrCast(*gltf.Primitive, &node.mesh.*.primitives[i]); const primtype = gltf.getPrimitiveType(primitive); // get material index const material_index = blk: { var index: u32 = 0; while (index < data.materials_count) : (index += 1) { const material = @ptrCast([*c]gltf.Material, &data.materials[index]); if (material == primitive.material) { break :blk index + 1; } } break :blk 0; }; var mergable_mesh: ?*Mesh = null; if (merge_meshes) { // TODO: there maybe more conditions // find mergable mesh, following conditions must be met: // 1. same primitive type // 2. same transform matrix // 3. same material mergable_mesh = for (self.meshes.items) |*m, idx| { if (m.primitive_type == primtype and self.transforms.items[idx].eql(transform) and self.material_indices.items[idx] == material_index) { break m; } } else null; } if (mergable_mesh) |m| { // merge into existing mesh gltf.appendMeshPrimitive( primitive, &m.indices.?, &m.positions, &m.normals.?, &m.texcoords.?, null, ); } else { // allocate new mesh var positions = std.ArrayList(Vec3).init(allocator); var indices = std.ArrayList(u32).init(allocator); var normals = std.ArrayList(Vec3).init(allocator); var texcoords = std.ArrayList(Vec2).init(allocator); gltf.appendMeshPrimitive( primitive, &indices, &positions, &normals, &texcoords, null, ); self.meshes.append(Mesh.fromArrayLists( primtype, positions, indices, normals, texcoords, null, null, true, )) catch unreachable; self.transforms.append(transform) catch unreachable; self.material_indices.append(material_index) catch unreachable; } } } // parse node's children var i: u32 = 0; while (i < node.children_count) : (i += 1) { self.parseNode( allocator, data, @ptrCast(*gltf.Node, node.children[i]), transform, merge_meshes, ); } } /// draw model using renderer pub fn render( self: Self, renderer: Renderer, model: Mat4, projection: Mat4, camera: ?Camera, material: ?Material, instance_count: ?u32, ) !void { for (self.meshes.items) |m, i| { try renderer.renderMesh( m, model.mult(self.transforms.items[i]), projection, camera, if (material) |mr| mr else self.materials.items[self.material_indices.items[i]], instance_count, ); } }
src/graphics/3d/Model.zig
const std = @import("std"); const zzz = @import("zzz"); const version = @import("version"); const Package = @import("Package.zig"); const Dependency = @import("Dependency.zig"); const utils = @import("utils.zig"); const ThreadSafeArenaAllocator = @import("ThreadSafeArenaAllocator.zig"); const Allocator = std.mem.Allocator; const Self = @This(); allocator: Allocator, arena: *ThreadSafeArenaAllocator, base_dir: []const u8, text: []const u8, owns_text: bool, packages: std.StringHashMap(Package), deps: std.ArrayList(Dependency), build_deps: std.ArrayList(Dependency), pub const Iterator = struct { inner: std.StringHashMapUnmanaged(Package).Iterator, pub fn next(self: *Iterator) ?*Package { return if (self.inner.next()) |entry| &entry.value_ptr.* else null; } }; fn create( arena: *ThreadSafeArenaAllocator, base_dir: []const u8, text: []const u8, owns_text: bool, ) !*Self { const allocator = arena.child_allocator; const ret = try allocator.create(Self); errdefer allocator.destroy(ret); ret.* = Self{ .allocator = arena.child_allocator, .arena = arena, .base_dir = base_dir, .text = text, .owns_text = owns_text, .packages = std.StringHashMap(Package).init(allocator), .deps = std.ArrayList(Dependency).init(allocator), .build_deps = std.ArrayList(Dependency).init(allocator), }; errdefer ret.deinit(); if (std.mem.indexOf(u8, ret.text, "\r\n") != null) { std.log.err("gyro.zzz requires LF line endings, not CRLF", .{}); return error.Explained; } var tree = zzz.ZTree(1, 1000){}; var root = try tree.appendText(ret.text); if (utils.zFindChild(root, "pkgs")) |pkgs| { var it = utils.ZChildIterator.init(pkgs); while (it.next()) |node| { const name = try utils.zGetString(node); const ver_str = (try utils.zFindString(node, "version")) orelse { std.log.err("missing version string in package", .{}); return error.Explained; }; const ver = version.Semver.parse(allocator, ver_str) catch |err| { std.log.err("failed to parse version string '{s}', must be <major>.<minor>.<patch>: {}", .{ ver_str, err }); return error.Explained; }; const res = try ret.packages.getOrPut(name); if (res.found_existing) { std.log.err("duplicate exported packages {s}", .{name}); return error.Explained; } res.value_ptr.* = try Package.init( allocator, name, ver, ret, ); try res.value_ptr.fillFromZNode(node); } } inline for (.{ "deps", "build_deps" }) |deps_field| { if (utils.zFindChild(root, deps_field)) |deps| { var it = utils.ZChildIterator.init(deps); while (it.next()) |dep_node| { var dep = try Dependency.fromZNode(ret.arena, dep_node); for (ret.deps.items) |other| { if (std.mem.eql(u8, dep.alias, other.alias)) { std.log.err("'{s}' alias in 'deps' is declared multiple times", .{dep.alias}); return error.Explained; } } else { if (dep.src == .local) { const resolved = try std.fs.path.resolve( allocator, &.{ base_dir, dep.src.local.path }, ); defer allocator.free(resolved); dep.src.local.path = try std.fs.path.relative(ret.arena.allocator(), ".", resolved); } try @field(ret, deps_field).append(dep); } } } } return ret; } fn deinit(self: *Self) void { var it = self.packages.iterator(); while (it.next()) |entry| { entry.value_ptr.deinit(); _ = self.packages.remove(entry.key_ptr.*); } self.deps.deinit(); self.build_deps.deinit(); self.packages.deinit(); if (self.owns_text) self.allocator.free(self.text); } pub fn destroy(self: *Self) void { self.deinit(); self.allocator.destroy(self); } pub fn fromUnownedText(arena: *ThreadSafeArenaAllocator, base_dir: []const u8, text: []const u8) !*Self { return try Self.create(arena, base_dir, text, false); } pub fn fromFile(arena: *ThreadSafeArenaAllocator, base_dir: []const u8, file: std.fs.File) !*Self { return Self.create( arena, base_dir, try file.reader().readAllAlloc(arena.child_allocator, std.math.maxInt(usize)), true, ); } pub fn fromDirPath( arena: *ThreadSafeArenaAllocator, base_dir: []const u8, ) !*Self { var dir = try std.fs.cwd().openDir(base_dir, .{}); defer dir.close(); const file = try dir.openFile("gyro.zzz", .{}); defer file.close(); return Self.fromFile(arena, base_dir, file); } pub fn write(self: Self, writer: anytype) !void { var tree = zzz.ZTree(1, 1000){}; var root = try tree.addNode(null, .Null); var arena = ThreadSafeArenaAllocator.init(self.allocator); defer arena.deinit(); if (self.packages.count() > 0) { var pkgs = try tree.addNode(root, .{ .String = "pkgs" }); var it = self.packages.iterator(); while (it.next()) |entry| _ = try entry.value_ptr.addToZNode(&arena, &tree, pkgs); } if (self.deps.items.len > 0) { var deps = try tree.addNode(root, .{ .String = "deps" }); for (self.deps.items) |dep| try dep.addToZNode(&arena, &tree, deps, false); } if (self.build_deps.items.len > 0) { var build_deps = try tree.addNode(root, .{ .String = "build_deps" }); for (self.build_deps.items) |dep| try dep.addToZNode(&arena, &tree, build_deps, false); } try root.stringifyPretty(writer); } pub fn toFile(self: *Self, file: std.fs.File) !void { try file.setEndPos(0); try file.seekTo(0); try self.write(file.writer()); } pub fn contains(self: Self, name: []const u8) bool { return self.packages.contains(name); } pub fn get(self: Self, name: []const u8) ?*Package { return if (self.packages.getEntry(name)) |entry| &entry.value_ptr.* else null; } pub fn iterator(self: Self) Iterator { return Iterator{ .inner = self.packages.iterator() }; }
src/Project.zig
const std = @import("std"); const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; test "basic invocations" { const foo = struct { fn foo() i32 { return 1234; } }.foo; try expect(@call(.{}, foo, .{}) == 1234); comptime { // modifiers that allow comptime calls try expect(@call(.{}, foo, .{}) == 1234); try expect(@call(.{ .modifier = .no_async }, foo, .{}) == 1234); try expect(@call(.{ .modifier = .always_tail }, foo, .{}) == 1234); try expect(@call(.{ .modifier = .always_inline }, foo, .{}) == 1234); } { // comptime call without comptime keyword const result = @call(.{ .modifier = .compile_time }, foo, .{}) == 1234; comptime try expect(result); } { // call of non comptime-known function var alias_foo = foo; try expect(@call(.{ .modifier = .no_async }, alias_foo, .{}) == 1234); try expect(@call(.{ .modifier = .never_tail }, alias_foo, .{}) == 1234); try expect(@call(.{ .modifier = .never_inline }, alias_foo, .{}) == 1234); } } test "tuple parameters" { const add = struct { fn add(a: i32, b: i32) i32 { return a + b; } }.add; var a: i32 = 12; var b: i32 = 34; try expect(@call(.{}, add, .{ a, 34 }) == 46); try expect(@call(.{}, add, .{ 12, b }) == 46); try expect(@call(.{}, add, .{ a, b }) == 46); try expect(@call(.{}, add, .{ 12, 34 }) == 46); comptime try expect(@call(.{}, add, .{ 12, 34 }) == 46); { const separate_args0 = .{ a, b }; const separate_args1 = .{ a, 34 }; const separate_args2 = .{ 12, 34 }; const separate_args3 = .{ 12, b }; try expect(@call(.{ .modifier = .always_inline }, add, separate_args0) == 46); try expect(@call(.{ .modifier = .always_inline }, add, separate_args1) == 46); try expect(@call(.{ .modifier = .always_inline }, add, separate_args2) == 46); try expect(@call(.{ .modifier = .always_inline }, add, separate_args3) == 46); } } test "comptime call with bound function as parameter" { const S = struct { fn ReturnType(func: anytype) type { return switch (@typeInfo(@TypeOf(func))) { .BoundFn => |info| info, else => unreachable, }.return_type orelse void; } fn call_me_maybe() ?i32 { return 123; } }; var inst: S = undefined; try expectEqual(?i32, S.ReturnType(inst.call_me_maybe)); }
test/behavior/call_stage1.zig
const mem = @import("../mem.zig"); const math = @import("../math/index.zig"); const endian = @import("../endian.zig"); const debug = @import("../debug/index.zig"); const builtin = @import("builtin"); const htest = @import("test.zig"); pub const Sha3_224 = Keccak(224, 0x06); pub const Sha3_256 = Keccak(256, 0x06); pub const Sha3_384 = Keccak(384, 0x06); pub const Sha3_512 = Keccak(512, 0x06); fn Keccak(comptime bits: usize, comptime delim: u8) type { return struct { const Self = this; const block_size = 200; const digest_size = bits / 8; s: [200]u8, offset: usize, rate: usize, pub fn init() Self { var d: Self = undefined; d.reset(); return d; } pub fn reset(d: *Self) void { mem.set(u8, d.s[0..], 0); d.offset = 0; d.rate = 200 - (bits / 4); } pub fn hash(b: []const u8, out: []u8) void { var d = Self.init(); d.update(b); d.final(out); } pub fn update(d: *Self, b: []const u8) void { var ip: usize = 0; var len = b.len; var rate = d.rate - d.offset; var offset = d.offset; // absorb while (len >= rate) { for (d.s[offset .. offset + rate]) |*r, i| r.* ^= b[ip..][i]; keccak_f(1600, d.s[0..]); ip += rate; len -= rate; rate = d.rate; offset = 0; } for (d.s[offset .. offset + len]) |*r, i| r.* ^= b[ip..][i]; d.offset = offset + len; } pub fn final(d: *Self, out: []u8) void { // padding d.s[d.offset] ^= delim; d.s[d.rate - 1] ^= 0x80; keccak_f(1600, d.s[0..]); // squeeze var op: usize = 0; var len: usize = bits / 8; while (len >= d.rate) { mem.copy(u8, out[op..], d.s[0..d.rate]); keccak_f(1600, d.s[0..]); op += d.rate; len -= d.rate; } mem.copy(u8, out[op..], d.s[0..len]); } }; } const RC = []const u64{ 0x0000000000000001, 0x0000000000008082, 0x800000000000808a, 0x8000000080008000, 0x000000000000808b, 0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008a, 0x0000000000000088, 0x0000000080008009, 0x000000008000000a, 0x000000008000808b, 0x800000000000008b, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800a, 0x800000008000000a, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008, }; const ROTC = []const usize{ 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 2, 14, 27, 41, 56, 8, 25, 43, 62, 18, 39, 61, 20, 44, }; const PIL = []const usize{ 10, 7, 11, 17, 18, 3, 5, 16, 8, 21, 24, 4, 15, 23, 19, 13, 12, 2, 20, 14, 22, 9, 6, 1, }; const M5 = []const usize{ 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, }; fn keccak_f(comptime F: usize, d: []u8) void { debug.assert(d.len == F / 8); const B = F / 25; const no_rounds = comptime x: { break :x 12 + 2 * math.log2(B); }; var s = []const u64{0} ** 25; var t = []const u64{0} ** 1; var c = []const u64{0} ** 5; for (s) |*r, i| { r.* = mem.readIntLE(u64, d[8 * i .. 8 * i + 8]); } comptime var x: usize = 0; comptime var y: usize = 0; for (RC[0..no_rounds]) |round| { // theta x = 0; inline while (x < 5) : (x += 1) { c[x] = s[x] ^ s[x + 5] ^ s[x + 10] ^ s[x + 15] ^ s[x + 20]; } x = 0; inline while (x < 5) : (x += 1) { t[0] = c[M5[x + 4]] ^ math.rotl(u64, c[M5[x + 1]], usize(1)); y = 0; inline while (y < 5) : (y += 1) { s[x + y * 5] ^= t[0]; } } // rho+pi t[0] = s[1]; x = 0; inline while (x < 24) : (x += 1) { c[0] = s[PIL[x]]; s[PIL[x]] = math.rotl(u64, t[0], ROTC[x]); t[0] = c[0]; } // chi y = 0; inline while (y < 5) : (y += 1) { x = 0; inline while (x < 5) : (x += 1) { c[x] = s[x + y * 5]; } x = 0; inline while (x < 5) : (x += 1) { s[x + y * 5] = c[x] ^ (~c[M5[x + 1]] & c[M5[x + 2]]); } } // iota s[0] ^= round; } for (s) |r, i| { mem.writeInt(d[8 * i .. 8 * i + 8], r, builtin.Endian.Little); } } test "sha3-224 single" { htest.assertEqualHash(Sha3_224, "6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", ""); htest.assertEqualHash(Sha3_224, "e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", "abc"); htest.assertEqualHash(Sha3_224, "543e6868e1666c1a643630df77367ae5a62a85070a51c14cbf665cbc", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-224 streaming" { var h = Sha3_224.init(); var out: [28]u8 = undefined; h.final(out[0..]); htest.assertEqual("6b4e03423667dbb73b6e15454f0eb1abd4597f9a1b078e3f5b5a6bc7", out[0..]); h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual("e642824c3f8cf24ad09234ee7d3c766fc9a3a5168d0c94ad73b46fdf", out[0..]); } test "sha3-256 single" { htest.assertEqualHash(Sha3_256, "a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", ""); htest.assertEqualHash(Sha3_256, "3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", "abc"); htest.assertEqualHash(Sha3_256, "916f6061fe879741ca6469b43971dfdb28b1a32dc36cb3254e812be27aad1d18", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-256 streaming" { var h = Sha3_256.init(); var out: [32]u8 = undefined; h.final(out[0..]); htest.assertEqual("a7ffc6f8bf1ed76651c14756a061d662f580ff4de43b49fa82d80a4b80f8434a", out[0..]); h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual("3a985da74fe225b2045c172d6bd390bd855f086e3e9d525b46bfe24511431532", out[0..]); } test "sha3-256 aligned final" { var block = []u8{0} ** Sha3_256.block_size; var out: [Sha3_256.digest_size]u8 = undefined; var h = Sha3_256.init(); h.update(block); h.final(out[0..]); } test "sha3-384 single" { const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004"; htest.assertEqualHash(Sha3_384, h1, ""); const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25"; htest.assertEqualHash(Sha3_384, h2, "abc"); const h3 = "79407d3b5916b59c3e30b09822974791c313fb9ecc849e406f23592d04f625dc8c709b98b43b3852b337216179aa7fc7"; htest.assertEqualHash(Sha3_384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-384 streaming" { var h = Sha3_384.init(); var out: [48]u8 = undefined; const h1 = "0c63a75b845e4f7d01107d852e4c2485c51a50aaaa94fc61995e71bbee983a2ac3713831264adb47fb6bd1e058d5f004"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "ec01498288516fc926459f58e2c6ad8df9b473cb0fc08c2596da7cf0e49be4b298d88cea927ac7f539f1edf228376d25"; h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); } test "sha3-512 single" { const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; htest.assertEqualHash(Sha3_512, h1, ""); const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"; htest.assertEqualHash(Sha3_512, h2, "abc"); const h3 = "afebb2ef542e6579c50cad06d2e578f9f8dd6881d7dc824d26360feebf18a4fa73e3261122948efcfd492e74e82e2189ed0fb440d187f382270cb455f21dd185"; htest.assertEqualHash(Sha3_512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha3-512 streaming" { var h = Sha3_512.init(); var out: [64]u8 = undefined; const h1 = "a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "b751850b1a57168a5693cd924b6b096e08f621827444f70d884f5d0240d2712e10e116e9192af3c91a7ec57647e3934057340b4cf408d5a56592f8274eec53f0"; h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); } test "sha3-512 aligned final" { var block = []u8{0} ** Sha3_512.block_size; var out: [Sha3_512.digest_size]u8 = undefined; var h = Sha3_512.init(); h.update(block); h.final(out[0..]); }
std/crypto/sha3.zig
const std = @import("std"); const print = std.debug.print; usingnamespace @import("value.zig"); usingnamespace @import("chunk.zig"); usingnamespace @import("scanner.zig"); usingnamespace @import("parser.zig"); usingnamespace @import("heap.zig"); pub const ArrayListOfLocal = std.ArrayList(Local); pub const Local = struct { name: Token, depth: i32, isCaptured: bool, fn init(name: Token, depth: i32) Local { return Local{ .name = name, .depth = depth }; } }; const Upvalue = struct { index: usize, isLocal: bool, }; pub const FunctionType = enum { TYPE_FUNCTION, TYPE_SCRIPT }; const ArrayListOfUpvalue = std.ArrayList(Upvalue); pub const Compiler = struct { function: ?*ObjFunction, functionType: FunctionType, enclosing: ?*Compiler, upvalues: ArrayListOfUpvalue, locals: ArrayListOfLocal, scopeDepth: i32, allocator: *std.mem.Allocator, pub fn init(allocator: *std.mem.Allocator) !*Compiler { var res = try allocator.create(Compiler); res.allocator = allocator; res.locals = ArrayListOfLocal.init(allocator); res.upvalues = ArrayListOfUpvalue.init(allocator); return res; } pub fn deinit(self: *Compiler) void { self.locals.deinit(); self.upvalues.deinit(); self.allocator.destroy(self); } pub fn beginScope(self: *Compiler) void { self.scopeDepth += 1; } pub fn endScope(self: *Compiler) !void { self.scopeDepth -= 1; while (current.?.locals.items.len > 0 and current.?.locals.items[current.?.locals.items.len - 1].depth > current.?.scopeDepth) { if (self.locals.items[self.locals.items.len - 1].isCaptured) { try parser.emitOpCode(OpCode.OP_CLOSE_UPVALUE); } else { try parser.emitOpCode(OpCode.OP_POP); } _ = current.?.locals.pop(); } } pub fn addLocal(self: *Compiler, name: Token) !void { try self.locals.append(Local{ .name = name, .depth = -1, .isCaptured = false, }); // 本地变量默认是未初始化变量 } pub fn resolveLocal(self: *Compiler, name: Token) i32 { if (self.locals.items.len == 0) return -1; var i: usize = self.locals.items.len - 1; while (i >= 0) { const local = self.locals.items[i]; if (Token.equal(name, local.name)) { return @intCast(i32, i); } if (@subWithOverflow(usize, i, 1, &i)) { if (local.depth == -1) { parser.error0("Cann't read local variable in its own initializer."); } break; } } return -1; } pub fn resolveUpvalue(self: *Compiler, name: Token) anyerror!i32 { if (self.enclosing) |enclosing| { const local = enclosing.resolveLocal(name); if (local != -1) { // 该变量需要移动到heap上 self.enclosing.?.locals.items[@intCast(usize, local)].isCaptured = true; return @intCast(i32, try self.addUpvalue(@intCast(usize, local), true)); } const upvalue = try enclosing.resolveUpvalue(name); if (upvalue != -1) { return @intCast(i32, try self.addUpvalue(@intCast(usize, upvalue), false)); } } return -1; } fn addUpvalue(self: *Compiler, index: usize, isLocal: bool) !usize { const upvalueCount = self.function.?.upvalueCount; var i: usize = 0; while (i < upvalueCount) : (i += 1) { const upvalue = self.upvalues.items[i]; if (upvalue.index == index and upvalue.isLocal == isLocal) { return i; } } try self.upvalues.append(Upvalue{ .index = index, .isLocal = isLocal }); self.function.?.upvalueCount += 1; return upvalueCount; } pub fn endCompiler(self: *Compiler) !*ObjFunction { try parser.emitReturn(); const function = self.function; if (!parser.hadError) { if (function.?.name) |name| { try currentChunk().disassembleChunk(name.chars); } else { try currentChunk().disassembleChunk("<script>"); } } current = self.enclosing; //defer self.deinit(); return function.?; } // 标记本地变量初始化 pub fn makeInitialized(self: *Compiler) void { if (self.scopeDepth == 0) return; self.locals.items[self.locals.items.len - 1].depth = self.scopeDepth; } }; pub var current: ?*Compiler = null; pub var compilingChunk: *Chunk = undefined; pub fn currentChunk() *Chunk { return current.?.function.?.chunk; } pub fn initCompiler(allocator: *std.mem.Allocator, ft: FunctionType) !void { const compiler = try Compiler.init(allocator); compiler.enclosing = current; compiler.scopeDepth = 0; compiler.function = null; compiler.functionType = ft; compiler.function = try heap.newFunction(); current = compiler; if (ft != FunctionType.TYPE_SCRIPT) { current.?.function.?.name = try heap.copyString(parser.previous.literal); } var local = Local{ .depth = 0, .name = Token{ .tokenType = TokenType.TOKEN_FUN, .line = 0, .literal = "", }, .isCaptured = false, }; try current.?.locals.append(local); } pub fn compile(allocator: *std.mem.Allocator, source: []const u8) !?*ObjFunction { Scanner.init(source); try initCompiler(allocator, FunctionType.TYPE_SCRIPT); parser = Parser.init(); parser.advance(); while (!parser.match(TokenType.TOKEN_EOF)) { try parser.declaration(); } const function = try current.?.endCompiler(); return if (parser.hadError) null else function; }
zvm/src/compiler.zig
const std = @import("std.zig"); const builtin = std.builtin; const root = @import("root"); //! std.log is standardized interface for logging which allows for the logging //! of programs and libraries using this interface to be formatted and filtered //! by the implementer of the root.log function. //! //! The scope parameter should be used to give context to the logging. For //! example, a library called 'libfoo' might use .libfoo as its scope. //! //! An example root.log might look something like this: //! //! ``` //! const std = @import("std"); //! //! // Set the log level to warning //! pub const log_level: std.log.Level = .warn; //! //! // Define root.log to override the std implementation //! pub fn log( //! comptime level: std.log.Level, //! comptime scope: @TypeOf(.EnumLiteral), //! comptime format: []const u8, //! args: anytype, //! ) void { //! // Ignore all non-critical logging from sources other than //! // .my_project and .nice_library //! const scope_prefix = "(" ++ switch (scope) { //! .my_project, .nice_library => @tagName(scope), //! else => if (@enumToInt(level) <= @enumToInt(std.log.Level.crit)) //! @tagName(scope) //! else //! return, //! } ++ "): "; //! //! const prefix = "[" ++ @tagName(level) ++ "] " ++ scope_prefix; //! //! // Print the message to stderr, silently ignoring any errors //! const held = std.debug.getStderrMutex().acquire(); //! defer held.release(); //! const stderr = std.io.getStdErr().writer(); //! nosuspend stderr.print(prefix ++ format ++ "\n", args) catch return; //! } //! //! pub fn main() void { //! // Won't be printed as log_level is .warn //! std.log.info(.my_project, "Starting up.", .{}); //! std.log.err(.nice_library, "Something went very wrong, sorry.", .{}); //! // Won't be printed as it gets filtered out by our log function //! std.log.err(.lib_that_logs_too_much, "Added 1 + 1", .{}); //! } //! ``` //! Which produces the following output: //! ``` //! [err] (nice_library): Something went very wrong, sorry. //! ``` pub const Level = enum { /// Emergency: a condition that cannot be handled, usually followed by a /// panic. emerg, /// Alert: a condition that should be corrected immediately (e.g. database /// corruption). alert, /// Critical: A bug has been detected or something has gone wrong and it /// will have an effect on the operation of the program. crit, /// Error: A bug has been detected or something has gone wrong but it is /// recoverable. err, /// Warning: it is uncertain if something has gone wrong or not, but the /// circumstances would be worth investigating. warn, /// Notice: non-error but significant conditions. notice, /// Informational: general messages about the state of the program. info, /// Debug: messages only useful for debugging. debug, }; /// The default log level is based on build mode. Note that in ReleaseSmall /// builds the default level is emerg but no messages will be stored/logged /// by the default logger to save space. pub const default_level: Level = switch (builtin.mode) { .Debug => .debug, .ReleaseSafe => .notice, .ReleaseFast => .err, .ReleaseSmall => .emerg, }; /// The current log level. This is set to root.log_level if present, otherwise /// log.default_level. pub const level: Level = if (@hasDecl(root, "log_level")) root.log_level else default_level; fn log( comptime message_level: Level, comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { if (@enumToInt(message_level) <= @enumToInt(level)) { if (@hasDecl(root, "log")) { root.log(message_level, scope, format, args); } else if (builtin.mode != .ReleaseSmall) { const held = std.debug.getStderrMutex().acquire(); defer held.release(); const stderr = std.io.getStdErr().writer(); nosuspend stderr.print(format ++ "\n", args) catch return; } } } /// Log an emergency message to stderr. This log level is intended to be used /// for conditions that cannot be handled and is usually followed by a panic. pub fn emerg( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { @setCold(true); log(.emerg, scope, format, args); } /// Log an alert message to stderr. This log level is intended to be used for /// conditions that should be corrected immediately (e.g. database corruption). pub fn alert( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { @setCold(true); log(.alert, scope, format, args); } /// Log a critical message to stderr. This log level is intended to be used /// when a bug has been detected or something has gone wrong and it will have /// an effect on the operation of the program. pub fn crit( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { @setCold(true); log(.crit, scope, format, args); } /// Log an error message to stderr. This log level is intended to be used when /// a bug has been detected or something has gone wrong but it is recoverable. pub fn err( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { @setCold(true); log(.err, scope, format, args); } /// Log a warning message to stderr. This log level is intended to be used if /// it is uncertain whether something has gone wrong or not, but the /// circumstances would be worth investigating. pub fn warn( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { log(.warn, scope, format, args); } /// Log a notice message to stderr. This log level is intended to be used for /// non-error but significant conditions. pub fn notice( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { log(.notice, scope, format, args); } /// Log an info message to stderr. This log level is intended to be used for /// general messages about the state of the program. pub fn info( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { log(.info, scope, format, args); } /// Log a debug message to stderr. This log level is intended to be used for /// messages which are only useful for debugging. pub fn debug( comptime scope: @Type(.EnumLiteral), comptime format: []const u8, args: anytype, ) void { log(.debug, scope, format, args); }
lib/std/log.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = 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/day10.txt"); pub fn main() !void { var lines = tokenize(data, "\r\n"); var score: u64 = 0; var completion = ArrayList(u64).init(gpa); defer completion.deinit(); while (lines.next()) |line| { var stack = ArrayList(u8).init(gpa); defer stack.deinit(); loop: for (line) |char| { switch (char) { '(', '[', '{', '<' => try stack.append(char), ')', ']', '}', '>' => { var x = stack.pop(); if (char == ')' and x != '(') { score += 3; break :loop; } if (char == ']' and x != '[') { score += 57; break :loop; } if (char == '}' and x != '{') { score += 1197; break :loop; } if (char == '>' and x != '<') { score += 25137; break :loop; } }, else => {}, } } else { var s: u64 = 0; while (stack.popOrNull()) |x| { s *= 5; switch (x) { '(' => s += 1, '[' => s += 2, '{' => s += 3, '<' => s += 4, else => {}, } } try completion.append(s); } } sort(u64, completion.items, {}, comptime asc(u64)); print("{}\n", .{score}); print("{}\n", .{completion.items[completion.items.len / 2]}); } // 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/day10.zig
const std = @import("std"); const panic = std.debug.panic; // Vulkan, GLFW usingnamespace @import("c.zig"); // Errors const ApplicationError = error { GlfwInitError, VkCreateInstanceError, }; // Constants const width = 800; const height = 600; // Variables var window: ?*GLFWwindow = null; var instance: VkInstance = undefined; // Initialise glfw and vulkan, run, and exit pub fn main() !void { try initWindow(); try initVulkan(); defer cleanup(); mainLoop(); } // Create the glfw window fn initWindow() !void { const ok = glfwInit(); if (ok == 0) { return ApplicationError.GlfwInitError; } glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); window = glfwCreateWindow(width, height, "Vulkan", null, null); } fn initVulkan() !void { try createInstance(); } // Run the program fn mainLoop() void { while (glfwWindowShouldClose(window) == 0) { glfwPollEvents(); } } // Deinit any resources fn cleanup() void { vkDestroyInstance(instance, null); glfwDestroyWindow(window); glfwTerminate(); } // Initialise the vulkan instance fn createInstance() !void { const appInfo = VkApplicationInfo{ .sType = .VK_STRUCTURE_TYPE_APPLICATION_INFO, .pApplicationName = "Hello Triangle", .applicationVersion = _VK_MAKE_VERSION(1, 0, 0), .pEngineName = "No Engine", .engineVersion = _VK_MAKE_VERSION(1, 0, 0), .apiVersion = _VK_API_VERSION_1_0, .pNext = null, }; var glfwExtensionCount: u32 = undefined; const glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); const createInfo = VkInstanceCreateInfo{ .sType = .VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, .pApplicationInfo = &appInfo, .enabledExtensionCount = glfwExtensionCount, .ppEnabledExtensionNames = glfwExtensions, // Defaults .enabledLayerCount = 0, .pNext = null, .flags = 0, .ppEnabledLayerNames = 0, }; if (vkCreateInstance(&createInfo, null, &instance) != .VK_SUCCESS) { return ApplicationError.VkCreateInstanceError; } }
src/01_instance_creation.zig
const std = @import("std"); // A blocking SPSC queue, used so that threads can sleep while waiting // for another thread to pass them data. pub fn BlockingQueue(comptime T: type) type { return struct { inner: std.atomic.Queue(T), event: std.Thread.ResetEvent, alloc: *std.mem.Allocator, pub const Self = @This(); pub fn init(alloc: *std.mem.Allocator) Self { var event: std.Thread.ResetEvent = undefined; std.Thread.ResetEvent.init(&event) catch |err| { std.debug.panic("Failed to initialize event: {s}\n", .{err}); }; return .{ .inner = std.atomic.Queue(T).init(), .event = event, .alloc = alloc, }; } pub fn put(self: *Self, i: T) !void { const node = try self.alloc.create(std.atomic.Queue(T).Node); node.* = .{ .prev = undefined, .next = undefined, .data = i, }; self.inner.put(node); self.event.set(); } pub fn get(self: *Self) T { self.event.wait(); const node = self.inner.get() orelse std.debug.panic("Could not get node", .{}); defer self.alloc.destroy(node); self.check_flag(); return node.data; } fn check_flag(self: *Self) void { const lock = self.inner.mutex.acquire(); defer lock.release(); // Manually check the state of the queue, as isEmpty() would // also try to lock the mutex, causing a deadlock if (self.inner.head == null) { self.event.reset(); } } pub fn try_get(self: *Self) ?T { if (self.inner.get()) |node| { defer self.alloc.destroy(node); self.check_flag(); return node.data; } return null; } }; }
src/blocking_queue.zig
const std = @import("std"); const mem = std.mem; const meta = std.meta; const net = std.net; usingnamespace @import("../frame.zig"); usingnamespace @import("../primitive_types.zig"); const testing = @import("../testing.zig"); /// PREPARE is sent to prepare a CQL query for later execution (through EXECUTE). /// /// Described in the protocol spec at §4.1.5 pub const PrepareFrame = struct { const Self = @This(); query: []const u8, keyspace: ?[]const u8, const FlagWithKeyspace = 0x01; pub fn write(self: Self, protocol_version: ProtocolVersion, pw: *PrimitiveWriter) !void { _ = try pw.writeLongString(self.query); if (!protocol_version.is(5)) { return; } if (self.keyspace) |ks| { _ = try pw.writeInt(u32, FlagWithKeyspace); _ = try pw.writeString(ks); } else { _ = try pw.writeInt(u32, 0); } } pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !Self { var frame = Self{ .query = undefined, .keyspace = null, }; frame.query = try pr.readLongString(allocator); if (!protocol_version.is(5)) { return frame; } const flags = try pr.readInt(u32); if (flags & FlagWithKeyspace == FlagWithKeyspace) { frame.keyspace = try pr.readString(allocator); } return frame; } }; test "prepare frame" { var arena = testing.arenaAllocator(); defer arena.deinit(); // read const exp = "\x04\x00\x00\xc0\x09\x00\x00\x00\x32\x00\x00\x00\x2e\x53\x45\x4c\x45\x43\x54\x20\x61\x67\x65\x2c\x20\x6e\x61\x6d\x65\x20\x66\x72\x6f\x6d\x20\x66\x6f\x6f\x62\x61\x72\x2e\x75\x73\x65\x72\x20\x77\x68\x65\x72\x65\x20\x69\x64\x20\x3d\x20\x3f"; const raw_frame = try testing.readRawFrame(&arena.allocator, exp); checkHeader(Opcode.Prepare, exp.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try PrepareFrame.read(&arena.allocator, raw_frame.header.version, &pr); testing.expectEqualStrings("SELECT age, name from foobar.user where id = ?", frame.query); testing.expect(frame.keyspace == null); // write testing.expectSameRawFrame(frame, raw_frame.header, exp); }
src/frames/prepare.zig
const zort = @import("zort"); const std = @import("std"); const testing = std.testing; const Str = []const u8; const INPUT_ITEMS = 10_000_000; const RUNS = 10; const BenchResult = struct { command: Str, mean: u64, times: [RUNS]u64, }; pub fn main() !void { const args = try std.process.argsAlloc(testing.allocator); defer std.process.argsFree(testing.allocator, args); // generate random data const rand_engine = std.rand.DefaultPrng.init(@intCast(u64, std.time.milliTimestamp())).random(); var arr = try std.ArrayList(usize).initCapacity(testing.allocator, INPUT_ITEMS); defer arr.deinit(); std.debug.print("Generating random data ({d} items)... ", .{INPUT_ITEMS}); var i: usize = 0; while (i < INPUT_ITEMS) : (i += 1) { arr.appendAssumeCapacity(rand_engine.intRangeAtMostBiased(usize, 0, INPUT_ITEMS)); } std.debug.print("Done. ", .{}); var results = std.ArrayList(BenchResult).init(std.testing.allocator); defer results.deinit(); for (args[1..]) |arg| { std.debug.print("\nStarting {s} sort...", .{arg}); var result: BenchResult = undefined; i = 0; while (i < RUNS) : (i += 1) { var items = try testing.allocator.dupe(usize, arr.items); if (std.mem.eql(u8, arg, "bubble")) result.times[i] = try bench(zort.bubbleSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "quick")) result.times[i] = try bench(zort.quickSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "insertion")) result.times[i] = try bench(zort.insertionSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "selection")) result.times[i] = try bench(zort.selectionSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "comb")) result.times[i] = try bench(zort.combSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "shell")) result.times[i] = try bench(zort.shellSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "heap")) result.times[i] = try bench(zort.heapSort, .{ usize, items, asc }) else if (std.mem.eql(u8, arg, "merge")) result.times[i] = try errbench( zort.mergeSort, .{ usize, items, asc, testing.allocator }, ) else if (std.mem.eql(u8, arg, "radix")) result.times[i] = try errbench( zort.radixSort, .{ usize, items, testing.allocator }, ) else if (std.mem.eql(u8, arg, "tim")) result.times[i] = try errbench( zort.timSort, .{ usize, items, asc, testing.allocator }, ) else if (std.mem.eql(u8, arg, "twin")) result.times[i] = try errbench( zort.twinSort, .{ std.testing.allocator, usize, items, {}, comptime std.sort.asc(usize) }, ) else if (std.mem.eql(u8, arg, "std_block_merge")) result.times[i] = try bench( std.sort.sort, .{ usize, items, {}, comptime std.sort.asc(usize) }, ) else if (std.mem.eql(u8, arg, "std_insertion")) result.times[i] = try bench( std.sort.insertionSort, .{ usize, items, {}, comptime std.sort.asc(usize) }, ) else std.debug.panic("{s} is not a valid argument", .{arg}); std.debug.print("\r{s:<20} round: {d:>2}/{d:<10} time: {d} ms", .{ arg, i + 1, RUNS, result.times[i] }); } var sum: usize = 0; for (result.times) |time| { sum += time; } result.command = try std.fmt.allocPrint(testing.allocator, "{s} {s}", .{ args[0], arg }); result.mean = sum / RUNS; try results.append(result); } try writeMermaid(results); } fn asc(a: usize, b: usize) bool { return a < b; } fn bench(func: anytype, args: anytype) anyerror!u64 { var timer = try std.time.Timer.start(); @call(.{}, func, args); return timer.read() / std.time.ns_per_ms; } fn errbench(func: anytype, args: anytype) anyerror!u64 { var timer = try std.time.Timer.start(); try @call(.{}, func, args); return timer.read() / std.time.ns_per_ms; } fn writeMermaid(results: std.ArrayList(BenchResult)) !void { const stdout = std.io.getStdOut().writer(); const header = \\ \\You can paste the following code snippet to the README.md file: \\ \\```mermaid \\gantt \\ title Sorting 10 million items \\ dateFormat x \\ axisFormat %S.%L ; try stdout.print("\n{s}\n", .{header}); for (results.items) |res| { try stdout.print(" {s} : 0,{d}\n", .{ res.command, res.mean }); } _ = try stdout.write("```\n"); }
benchmark/run_bench.zig
const std = @import("std"); const prot = @import("../protocols.zig"); const out = @import("../output.zig"); const Context = @import("../client.zig").Context; const Object = @import("../client.zig").Object; const dmabuf = @import("../dmabuf_params.zig"); fn bind(context: *Context, wl_registry: Object, name: u32, name_string: []u8, version: u32, new_id: u32) anyerror!void { std.debug.warn("bind for {s} ({}) with id {} at version {}\n", .{ name_string, name, new_id, version }); if (name >= out.OUTPUT_BASE and name < (out.OUTPUTS.entries.len + out.OUTPUT_BASE)) { if (out.OUTPUTS.getAtIndex(name - out.OUTPUT_BASE)) |output| { if (std.mem.eql(u8, name_string, "wl_output\x00")) { var wl_output = prot.new_wl_output(new_id, context, @ptrToInt(output)); wl_output.version = version; context.client.wl_output_id = wl_output.id; try prot.wl_output_send_geometry(wl_output, 0, 0, 267, 200, @enumToInt(prot.wl_output_subpixel.none), "unknown", "unknown", @enumToInt(prot.wl_output_transform.normal)); try prot.wl_output_send_mode(wl_output, @enumToInt(prot.wl_output_mode.current), output.getWidth(), output.getHeight(), 60000); try prot.wl_output_send_scale(wl_output, 1); try prot.wl_output_send_done(wl_output); try context.register(wl_output); return; } } else { return error.NoSuchOutputInUseToBind; } } switch (name) { 1 => { if (std.mem.eql(u8, name_string, "wl_compositor\x00")) { var wl_compositor = prot.new_wl_compositor(new_id, context, 0); wl_compositor.version = version; context.client.wl_compositor_id = wl_compositor.id; try context.register(wl_compositor); return; } }, 2 => { if (std.mem.eql(u8, name_string, "wl_subcompositor\x00")) { var wl_subcompositor = prot.new_wl_subcompositor(new_id, context, 0); wl_subcompositor.version = version; context.client.wl_subcompositor_id = wl_subcompositor.id; try context.register(wl_subcompositor); return; } }, 3 => { if (std.mem.eql(u8, name_string, "wl_seat\x00")) { var wl_seat = prot.new_wl_seat(new_id, context, 0); wl_seat.version = version; try prot.wl_seat_send_capabilities(wl_seat, @enumToInt(prot.wl_seat_capability.pointer) | @enumToInt(prot.wl_seat_capability.keyboard)); if (context.client.wl_seat_id == null) { context.client.wl_seat_id = wl_seat.id; } try context.register(wl_seat); return; } }, 4 => { if (std.mem.eql(u8, name_string, "xdg_wm_base\x00")) { var xdg_wm_base = prot.new_xdg_wm_base(new_id, context, 0); xdg_wm_base.version = version; context.client.xdg_wm_base_id = xdg_wm_base.id; try context.register(xdg_wm_base); return; } }, 6 => { if (std.mem.eql(u8, name_string, "wl_data_device_manager\x00")) { var wl_data_device_manager = prot.new_wl_data_device_manager(new_id, context, 0); wl_data_device_manager.version = version; context.client.wl_data_device_manager_id = wl_data_device_manager.id; try context.register(wl_data_device_manager); return; } }, 7 => {}, 8 => { if (std.mem.eql(u8, name_string, "wl_shm\x00")) { var wl_shm = prot.new_wl_shm(new_id, context, 0); wl_shm.version = version; context.client.wl_shm_id = wl_shm.id; try prot.wl_shm_send_format(wl_shm, @enumToInt(prot.wl_shm_format.argb8888)); try prot.wl_shm_send_format(wl_shm, @enumToInt(prot.wl_shm_format.xrgb8888)); try context.register(wl_shm); return; } }, 9 => {}, 10 => { var zwp_linux_dmabuf = prot.new_zwp_linux_dmabuf_v1(new_id, context, 0); zwp_linux_dmabuf.version = version; context.client.zwp_linux_dmabuf_id = zwp_linux_dmabuf.id; try prot.zwp_linux_dmabuf_v1_send_modifier(zwp_linux_dmabuf, dmabuf.DRM_FORMAT_XRGB8888, 0x0, 0x0); try prot.zwp_linux_dmabuf_v1_send_modifier(zwp_linux_dmabuf, dmabuf.DRM_FORMAT_XRGB8888, 16777216, 0x1); try prot.zwp_linux_dmabuf_v1_send_modifier(zwp_linux_dmabuf, dmabuf.DRM_FORMAT_XRGB8888, 16777216, 0x2); try context.register(zwp_linux_dmabuf); return; }, 11 => { std.debug.warn("name: {s}\n", .{name_string}); if (std.mem.eql(u8, name_string, "fw_control\x00\x00")) { var fw_control = prot.new_fw_control(new_id, context, 0); fw_control.version = version; context.client.fw_control_id = fw_control.id; try context.register(fw_control); return; } }, else => return error.NoSuchGlobal, } return error.ProtocolNotSupported; } pub fn init() void { prot.WL_REGISTRY.bind = bind; }
src/implementations/wl_registry.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const bog = @import("bog.zig"); const Token = bog.Token; const TokenIndex = Token.Index; pub const Tree = struct { tokens: []const Token, nodes: []const *Node, /// not owned by the tree source: []const u8, arena: std.heap.ArenaAllocator.State, gpa: Allocator, pub fn deinit(self: *Tree) void { self.gpa.free(self.tokens); self.arena.promote(self.gpa).deinit(); } pub const render = @import("render.zig").render; }; pub const Node = struct { id: Id, pub const Id = enum { Decl, Fn, Discard, Identifier, This, Prefix, Infix, TypeInfix, Range, Suffix, Literal, Import, Error, Tagged, List, Tuple, Map, Block, Grouped, MapItem, Try, Catch, If, For, While, Match, MatchCatchAll, MatchLet, MatchCase, Jump, FormatString, pub fn Type(tag: Id) type { return switch (tag) { .Decl => Decl, .Fn => Fn, .Discard, .Identifier, .This => SingleToken, .Prefix => Prefix, .Infix => Infix, .TypeInfix => TypeInfix, .Range => Range, .Suffix => Suffix, .Literal => Literal, .Import => Import, .Error => Error, .Tagged => Tagged, .List, .Tuple, .Map => ListTupleMap, .Block => Block, .Grouped => Grouped, .MapItem => MapItem, .Try => Try, .Catch => Catch, .If => If, .For => For, .While => While, .Match => Match, .MatchCatchAll => MatchCatchAll, .MatchLet => MatchLet, .MatchCase => MatchCase, .Jump => Jump, .FormatString => FormatString, }; } }; pub fn firstToken(node: *Node) TokenIndex { return switch (node.id) { .Decl => @fieldParentPtr(Node.Decl, "base", node).let_const, .Fn => @fieldParentPtr(Node.Fn, "base", node).fn_tok, .Identifier, .Discard, .This => @fieldParentPtr(Node.SingleToken, "base", node).tok, .Prefix => @fieldParentPtr(Node.Prefix, "base", node).tok, .Infix => @fieldParentPtr(Node.Infix, "base", node).lhs.firstToken(), .Range => { const range = @fieldParentPtr(Node.Range, "base", node); if (range.start) |some| return some.firstToken(); return range.colon_1; }, .TypeInfix => @fieldParentPtr(Node.TypeInfix, "base", node).lhs.firstToken(), .Suffix => @fieldParentPtr(Node.Suffix, "base", node).l_tok, .Literal => { const lit = @fieldParentPtr(Node.Literal, "base", node); return if (lit.kind != .none) lit.tok else lit.tok - 1; }, .Import => @fieldParentPtr(Node.Import, "base", node).tok, .Error => @fieldParentPtr(Node.Error, "base", node).tok, .Tagged => @fieldParentPtr(Node.Tagged, "base", node).at, .List, .Tuple, .Map => @fieldParentPtr(Node.ListTupleMap, "base", node).l_tok, .Block => @fieldParentPtr(Node.Block, "base", node).stmts[0].firstToken(), .Grouped => @fieldParentPtr(Node.Grouped, "base", node).l_tok, .MapItem => { const map = @fieldParentPtr(Node.MapItem, "base", node); if (map.key) |some| return some.firstToken(); return map.value.firstToken(); }, .Try => @fieldParentPtr(Node.Try, "base", node).tok, .Catch => @fieldParentPtr(Node.Catch, "base", node).tok, .If => @fieldParentPtr(Node.If, "base", node).if_tok, .For => @fieldParentPtr(Node.For, "base", node).for_tok, .While => @fieldParentPtr(Node.While, "base", node).while_tok, .Match => @fieldParentPtr(Node.Match, "base", node).match_tok, .MatchCatchAll => @fieldParentPtr(Node.Jump, "base", node).tok, .MatchLet => @fieldParentPtr(Node.MatchLet, "base", node).let_const, .MatchCase => @fieldParentPtr(Node.MatchCase, "base", node).items[0].firstToken(), .Jump => @fieldParentPtr(Node.Jump, "base", node).tok, .FormatString => @fieldParentPtr(Node.FormatString, "base", node).format[0], }; } pub fn lastToken(node: *Node) TokenIndex { return switch (node.id) { .Decl => @fieldParentPtr(Node.Decl, "base", node).value.lastToken(), .Fn => @fieldParentPtr(Node.Fn, "base", node).body.lastToken(), .Identifier, .Discard, .This => @fieldParentPtr(Node.SingleToken, "base", node).tok, .Prefix => @fieldParentPtr(Node.Prefix, "base", node).rhs.lastToken(), .Infix => @fieldParentPtr(Node.Infix, "base", node).rhs.lastToken(), .TypeInfix => @fieldParentPtr(Node.TypeInfix, "base", node).type_tok, .Range => { const range = @fieldParentPtr(Node.Range, "base", node); if (range.step) |some| return some.firstToken(); if (range.colon_2) |some| return some; if (range.end) |some| return some.firstToken(); return range.colon_1; }, .Suffix => @fieldParentPtr(Node.Suffix, "base", node).r_tok, .Literal => @fieldParentPtr(Node.Literal, "base", node).tok, .Import => @fieldParentPtr(Node.Import, "base", node).r_paren, .Error => { const err = @fieldParentPtr(Node.Error, "base", node); if (err.capture) |some| return some.lastToken(); return err.tok; }, .Tagged => { const tagged = @fieldParentPtr(Node.Tagged, "base", node); if (tagged.capture) |some| return some.lastToken(); return tagged.name; }, .List, .Tuple, .Map => @fieldParentPtr(Node.ListTupleMap, "base", node).r_tok, .Block => { const block = @fieldParentPtr(Node.Block, "base", node); return block.stmts[block.stmts.len - 1].lastToken(); }, .Grouped => @fieldParentPtr(Node.Grouped, "base", node).r_tok, .MapItem => @fieldParentPtr(Node.MapItem, "base", node).value.lastToken(), .Try => { const try_node = @fieldParentPtr(Node.Try, "base", node); return try_node.catches[try_node.catches.len - 1].lastToken(); }, .Catch => @fieldParentPtr(Node.Catch, "base", node).expr.lastToken(), .If => { const if_node = @fieldParentPtr(Node.If, "base", node); if (if_node.else_body) |some| return some.lastToken(); return if_node.if_body.lastToken(); }, .For => @fieldParentPtr(Node.For, "base", node).body.lastToken(), .While => @fieldParentPtr(Node.While, "base", node).body.lastToken(), .Match => { const match = @fieldParentPtr(Node.Match, "base", node); return match.cases[match.cases.len - 1].lastToken(); }, .MatchCatchAll => @fieldParentPtr(Node.MatchCatchAll, "base", node).expr.lastToken(), .MatchLet => @fieldParentPtr(Node.MatchLet, "base", node).expr.lastToken(), .MatchCase => @fieldParentPtr(Node.MatchCase, "base", node).expr.lastToken(), .Jump => { const jump = @fieldParentPtr(Node.Jump, "base", node); switch (jump.op) { .Return => |n| return if (n) |some| some.lastToken() else jump.tok, .Break, .Continue => return jump.tok, } }, .FormatString => { const fmt_str = @fieldParentPtr(Node.FormatString, "base", node); return fmt_str.format[fmt_str.format.len - 1]; }, }; } pub fn cast(base: *Node, comptime id: Id) ?*id.Type() { if (base.id == id) { return @fieldParentPtr(id.Type(), "base", base); } return null; } pub const Decl = struct { base: Node = .{ .id = .Decl }, capture: *Node, value: *Node, let_const: TokenIndex, eq_tok: TokenIndex, }; pub const Fn = struct { base: Node = .{ .id = .Fn }, params: []*Node, body: *Node, fn_tok: TokenIndex, r_paren: TokenIndex, }; pub const SingleToken = struct { base: Node, tok: TokenIndex, }; pub const Prefix = struct { base: Node = .{ .id = .Prefix }, op: Op, tok: TokenIndex, rhs: *Node, pub const Op = enum { bool_not, bit_not, minus, plus, }; }; pub const TypeInfix = struct { base: Node = .{ .id = .TypeInfix }, op: enum { is, as, }, lhs: *Node, tok: TokenIndex, type_tok: TokenIndex, }; pub const Infix = struct { base: Node = .{ .id = .Infix }, op: enum { bool_or, bool_and, less_than, less_than_equal, greater_than, greater_than_equal, equal, not_equal, in, bit_and, bit_or, bit_xor, l_shift, r_shift, add, sub, mul, div, div_floor, mod, pow, append, // assignment ops assign, add_assign, sub_assign, mul_assign, pow_assign, div_assign, div_floor_assign, mod_assign, l_shift_assign, r_shift_assign, bit_and_assign, bit_or_assign, bit_x_or_assign, }, tok: TokenIndex, lhs: *Node, rhs: *Node, }; pub const Range = struct { base: Node = .{ .id = .Range }, start: ?*Node, end: ?*Node, step: ?*Node, colon_1: TokenIndex, colon_2: ?TokenIndex, }; pub const Suffix = struct { base: Node = .{ .id = .Suffix }, lhs: *Node, op: union(enum) { call: []*Node, subscript: *Node, member, }, l_tok: TokenIndex, r_tok: TokenIndex, }; pub const Literal = struct { base: Node = .{ .id = .Literal }, kind: enum { str, num, int, True, False, none, }, tok: TokenIndex, }; pub const Import = struct { base: Node = .{ .id = .Import }, tok: TokenIndex, str_tok: TokenIndex, r_paren: TokenIndex, }; pub const Error = struct { base: Node = .{ .id = .Error }, tok: TokenIndex, capture: ?*Node, }; pub const Tagged = struct { base: Node = .{ .id = .Tagged }, at: TokenIndex, name: TokenIndex, capture: ?*Node, }; pub const ListTupleMap = struct { base: Node, values: []*Node, l_tok: TokenIndex, r_tok: TokenIndex, }; pub const Block = struct { base: Node, stmts: []*Node, }; pub const Grouped = struct { base: Node = .{ .id = .Grouped }, expr: *Node, l_tok: TokenIndex, r_tok: TokenIndex, }; pub const MapItem = struct { base: Node = .{ .id = .MapItem }, key: ?*Node, colon: ?TokenIndex, value: *Node, }; pub const If = struct { base: Node = .{ .id = .If }, cond: *Node, if_body: *Node, else_body: ?*Node, capture: ?*Node, let_const: ?TokenIndex, eq_tok: ?TokenIndex, else_tok: ?TokenIndex, if_tok: TokenIndex, r_paren: TokenIndex, }; pub const For = struct { base: Node = .{ .id = .For }, capture: ?*Node, cond: *Node, body: *Node, let_const: ?TokenIndex, in_tok: ?TokenIndex, for_tok: TokenIndex, r_paren: TokenIndex, }; pub const While = struct { base: Node = .{ .id = .While }, cond: *Node, body: *Node, capture: ?*Node, let_const: ?TokenIndex, eq_tok: ?TokenIndex, while_tok: TokenIndex, r_paren: TokenIndex, }; pub const Match = struct { base: Node = .{ .id = .Match }, expr: *Node, cases: []*Node, match_tok: TokenIndex, r_paren: TokenIndex, }; pub const MatchCatchAll = struct { base: Node = .{ .id = .MatchCatchAll }, expr: *Node, tok: TokenIndex, eq_arr: TokenIndex, }; pub const MatchLet = struct { base: Node = .{ .id = .MatchLet }, capture: *Node, expr: *Node, let_const: TokenIndex, eq_arr: TokenIndex, }; pub const MatchCase = struct { base: Node = .{ .id = .MatchCase }, items: []*Node, expr: *Node, eq_arr: TokenIndex, }; pub const Try = struct { base: Node = .{ .id = .Try }, tok: TokenIndex, expr: *Node, catches: []*Node, }; pub const Catch = struct { base: Node = .{ .id = .Catch }, tok: TokenIndex, let_const: ?TokenIndex, capture: ?*Node, expr: *Node, }; pub const Jump = struct { base: Node = .{ .id = .Jump }, tok: TokenIndex, op: union(enum) { Break, Continue, Return: ?*Node, }, }; pub const FormatString = struct { base: Node = .{ .id = .FormatString }, format: []TokenIndex, args: []*Node, }; };
src/ast.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const kernel = @import("__trig.zig"); const __rem_pio2 = @import("__rem_pio2.zig").__rem_pio2; const __rem_pio2f = @import("__rem_pio2f.zig").__rem_pio2f; /// Returns the tangent of the radian value x. /// /// Special Cases: /// - tan(+-0) = +-0 /// - tan(+-inf) = nan /// - tan(nan) = nan pub fn tan(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => tan32(x), f64 => tan64(x), else => @compileError("tan not implemented for " ++ @typeName(T)), }; } fn tan32(x: f32) f32 { // Small multiples of pi/2 rounded to double precision. const t1pio2: f64 = 1.0 * math.pi / 2.0; // 0x3FF921FB, 0x54442D18 const t2pio2: f64 = 2.0 * math.pi / 2.0; // 0x400921FB, 0x54442D18 const t3pio2: f64 = 3.0 * math.pi / 2.0; // 0x4012D97C, 0x7F3321D2 const t4pio2: 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 and underflow if subnormal math.doNotOptimizeAway(if (ix < 0x00800000) x / 0x1p120 else x + 0x1p120); return x; } return kernel.__tandf(x, false); } if (ix <= 0x407b53d1) { // |x| ~<= 5*pi/4 if (ix <= 0x4016cbe3) { // |x| ~<= 3pi/4 return kernel.__tandf((if (sign) x + t1pio2 else x - t1pio2), true); } else { return kernel.__tandf((if (sign) x + t2pio2 else x - t2pio2), false); } } if (ix <= 0x40e231d5) { // |x| ~<= 9*pi/4 if (ix <= 0x40afeddf) { // |x| ~<= 7*pi/4 return kernel.__tandf((if (sign) x + t3pio2 else x - t3pio2), true); } else { return kernel.__tandf((if (sign) x + t4pio2 else x - t4pio2), false); } } // tan(Inf or NaN) is NaN if (ix >= 0x7f800000) { return x - x; } var y: f64 = undefined; const n = __rem_pio2f(x, &y); return kernel.__tandf(y, n & 1 != 0); } fn tan64(x: f64) f64 { var ix = @bitCast(u64, x) >> 32; ix &= 0x7fffffff; // |x| ~< pi/4 if (ix <= 0x3fe921fb) { if (ix < 0x3e400000) { // |x| < 2**-27 // raise inexact if x!=0 and underflow if subnormal math.doNotOptimizeAway(if (ix < 0x00100000) x / 0x1p120 else x + 0x1p120); return x; } return kernel.__tan(x, 0.0, false); } // tan(Inf or NaN) is NaN if (ix >= 0x7ff00000) { return x - x; } var y: [2]f64 = undefined; const n = __rem_pio2(x, &y); return kernel.__tan(y[0], y[1], n & 1 != 0); } test "math.tan" { try expect(tan(@as(f32, 0.0)) == tan32(0.0)); try expect(tan(@as(f64, 0.0)) == tan64(0.0)); } test "math.tan32" { const epsilon = 0.00001; try expect(math.approxEqAbs(f32, tan32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, tan32(0.2), 0.202710, epsilon)); try expect(math.approxEqAbs(f32, tan32(0.8923), 1.240422, epsilon)); try expect(math.approxEqAbs(f32, tan32(1.5), 14.101420, epsilon)); try expect(math.approxEqAbs(f32, tan32(37.45), -0.254397, epsilon)); try expect(math.approxEqAbs(f32, tan32(89.123), 2.285852, epsilon)); } test "math.tan64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, tan64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, tan64(0.2), 0.202710, epsilon)); try expect(math.approxEqAbs(f64, tan64(0.8923), 1.240422, epsilon)); try expect(math.approxEqAbs(f64, tan64(1.5), 14.101420, epsilon)); try expect(math.approxEqAbs(f64, tan64(37.45), -0.254397, epsilon)); try expect(math.approxEqAbs(f64, tan64(89.123), 2.2858376, epsilon)); } test "math.tan32.special" { try expect(tan32(0.0) == 0.0); try expect(tan32(-0.0) == -0.0); try expect(math.isNan(tan32(math.inf(f32)))); try expect(math.isNan(tan32(-math.inf(f32)))); try expect(math.isNan(tan32(math.nan(f32)))); } test "math.tan64.special" { try expect(tan64(0.0) == 0.0); try expect(tan64(-0.0) == -0.0); try expect(math.isNan(tan64(math.inf(f64)))); try expect(math.isNan(tan64(-math.inf(f64)))); try expect(math.isNan(tan64(math.nan(f64)))); }
lib/std/math/tan.zig
const std = @import("std"); const stdout = std.io.getStdOut().writer(); const print = stdout.print; const dp = std.debug.print; const os = std.os; const Allocator = std.mem.Allocator; const funcs = @import("funcs.zig"); const proc = std.ChildProcess; const eql = std.mem.eql; const len = std.mem.len; const assert = std.debug.assert; const expect = std.testing.expect; const ArrayList = std.ArrayList; // this compile-errors on 0.7.1-0.8.0 // https://github.com/ziglang/zig/issues/6682 // pub const io_mode = .evented; const Str = []const u8; const Status = enum { ahead, behind, staged, added, modified, removed, stashed, untracked, conflicted, renamed, unknown, }; const STATUS_LEN = 11; // hand-counted. Waiting for enum arrays. const GitStatus = struct { state: Str, branch: Str, status: [STATUS_LEN]u32, stash: std.StringHashMap(u32), }; const Shell = enum { zsh, bash, unknown, }; const AheadBehind = struct { ahead: u32 = 0, behind: u32 = 0, }; pub const Escapes = struct { o: [:0]const u8 = undefined, c: [:0]const u8 = undefined, pub fn init(open: [:0]const u8, close: [:0]const u8) Escapes { return Escapes{ .o = open, .c = close }; } }; pub const C = .{ .reset = "\x1b[00m", .bold = "\x1b[01m", .italic = "\x1b[03m", .underline = "\x1b[04m", .reverse = "\x1b[07m", .italic_off = "\x1b[23m", .underline_off = "\x1b[24m", .reverse_off = "\x1b[27m", .black = "\x1b[30m", .red = "\x1b[31m", .green = "\x1b[32m", .yellow = "\x1b[33m", .blue = "\x1b[34m", .magenta = "\x1b[35m", .cyan = "\x1b[36m", .white = "\x1b[37m", .default = "\x1b[39m", }; pub var A: *Allocator = undefined; pub var E: Escapes = undefined; pub var CWD: Str = undefined; fn concatStringArray(lists: []const []Str) ![]Str { return try std.mem.concat(A, Str, lists); } fn gitCmd(args: []Str, workingdir: Str) !proc.ExecResult { var gitcmd = [_]Str{ "git", "-C", workingdir }; var cmd_parts = [_][]Str{ &gitcmd, args }; var cmd = try concatStringArray(&cmd_parts); return try run(cmd); } fn run(argv: []const Str) !proc.ExecResult { return try proc.exec(.{ .allocator = A, .argv = argv, .max_output_bytes = std.math.maxInt(u32), }); } fn getState(dir: Str) !Str { // Return a code for the current repo state. // // Possible states: // R - rebase // M - merge // C - cherry-pick // B - bisect // V - revert // // The code returned will indicate multiple states (if that's possible?) // or the empty string if the repo is in a normal state. // Unfortunately there's no porcelain to check for various git states. // Determining state is done by checking for the existence of files within // the git repository. Reference for possible checks: // https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh const checks = .{ .{ .filename = "rebase-merge", .code = "R" }, .{ .filename = "rebase-apply", .code = "R" }, .{ .filename = "MERGE_HEAD", .code = "M" }, .{ .filename = "CHERRY_PICK_HEAD", .code = "C" }, .{ .filename = "BISECT_LOG", .code = "B" }, .{ .filename = "REVERT_HEAD", .code = "V" }, }; var cmd = [_]Str{ "rev-parse", "--git-dir" }; var result = try gitCmd(&cmd, dir); if (result.term.Exited != 0) return error.GetGitDirFailed; var git_dir = strip(result.stdout); var state_set = std.BufSet.init(A); inline for (checks) |check| { var path = try std.fs.path.join(A, &[_]Str{ git_dir, check.filename }); if (exists(path)) try state_set.insert(check.code); } var list = std.ArrayList(Str).init(A); var it = state_set.iterator(); while (it.next()) |entry| { try list.append(entry.*); } return std.mem.join(A, "", list.items); // sort later, not a good use of time // std.sort.sort(u8, state_set) } fn access(pth: Str, flags: std.fs.File.OpenFlags) !void { try std.fs.cwd().access(pth, flags); } fn exists(pth: Str) bool { access(pth, .{}) catch return false; return true; } fn strip(s: Str) Str { return std.mem.trim(u8, s, " \t\n"); } fn getBranch(dir: Str) !Str { var cmd1 = [_]Str{ "symbolic-ref", "HEAD", "--short" }; var result = try gitCmd(&cmd1, dir); if (result.term.Exited == 0) return strip(result.stdout); var cmd2 = [_]Str{ "describe", "--all", "--contains", "--always", "HEAD" }; result = try gitCmd(&cmd2, dir); return strip(result.stdout); } fn getRepoStashCounts(dir: Str) !std.StringHashMap(u32) { var cmd = [_]Str{ "stash", "list", "-z" }; var result = try gitCmd(&cmd, dir); if (result.term.Exited != 0) std.log.err("Couldn't get stash list ({})", .{result.term.Exited}); var lines = slurpSplit(&result.stdout, "\x00"); return parseRepoStash(lines); } fn getBranchNameFromStashLine(line: Str) Str { var parts = slurpSplit(&line, ":"); if (parts.len <= 1) return ""; var part = parts[1]; if (std.mem.eql(u8, part, " autostash")) return "-autostash"; var wordstart = std.mem.lastIndexOf(u8, part, " ") orelse 0; var result = part[wordstart + 1 ..]; return result; } test "get branch name from status line" { A = std.testing.allocator; var line: Str = "stash@{1}: WIP on master: 8dbbdc4 commit one"; var result = getBranchNameFromStashLine(line); expect(std.mem.eql(u8, result, "master")); line = "stash@{1}: autostash"; result = getBranchNameFromStashLine(line); expect(std.mem.eql(u8, result, "-autostash")); } fn parseRepoStash(stashlines: []Str) !std.StringHashMap(u32) { // stash output looks like: // stash@{0}: On (no branch): push file to stash // stash@{1}: WIP on master: 8dbbdc4 commit one // stash@{2}: autostash // // https://www.git-scm.com/docs/git-stash//Documentation/git-stash.txt-listltoptionsgt var result = std.StringHashMap(u32).init(A); for (stashlines) |line| { var branch = getBranchNameFromStashLine(line); var entry = try result.getOrPutValue(branch, 0); entry.value_ptr.* += 1; } return result; } test "parse repo stash" { A = std.testing.allocator; var lines = [_]Str{ "stash@{0}: On (no branch): push file to stash", "stash@{1}: WIP on master: 8dbbdc4 commit one", "stash@{2}: autostash", }; var result = try parseRepoStash(&lines); var val = result.get("master") orelse 0; expect(val == 1); val = result.get("-autostash") orelse 0; expect(val == 1); } fn formatStashes(status: GitStatus) Str { // Return a Str like "1A" for one stash on current branch and one autostash // todo: also display count of all stashes? var branch_count = status.stash.get(status.branch) orelse 0; var autostash_count = status.stash.get("-autostash") orelse 0; var count = if (branch_count == 0) "" else intToStr(branch_count) catch ""; var autostash = if (autostash_count > 0) "A" else ""; var str = std.mem.concat(A, u8, &[_]Str{ count, autostash }) catch ""; return str; } fn parseCode(statusCode: Str) Status { // see https://git-scm.com/docs/git-status//_short_format for meaning of codes if (eql(u8, statusCode, "??")) return Status.untracked; var index = statusCode[0]; var worktree = statusCode[1]; if (index == 'R') { return Status.renamed; } else if (index != ' ') { if (worktree != ' ') { return Status.conflicted; } else { return Status.staged; } } return switch (worktree) { 'A' => Status.added, 'M' => Status.modified, 'D' => Status.removed, else => Status.unknown, }; } test "parse codes" { var s: Status = parseCode(" M"); assert(s == Status.modified); s = parseCode("??"); assert(s == Status.untracked); } fn parseStatusLines(lines: []Str) [STATUS_LEN]u32 { var codes: [STATUS_LEN]u32 = [_]u32{0} ** STATUS_LEN; if (lines.len == 0) return codes; var skip = false; for (lines) |line| { if (skip) { skip = false; continue; } if (std.mem.eql(u8, strip(line), "")) continue; var code = line[0..2]; var c = parseCode(code); if (c == Status.renamed) { // renamed files have two lines of status, skip the next line codes[@enumToInt(Status.staged)] += 1; skip = true; } else { codes[@enumToInt(c)] += 1; } } return codes; } test "parse lines" { var lines = [_]Str{ " M repo_status.zig", " M todo.txt", "?? .gitignore", "?? repo_status", "?? test", "?? test.nim", "?? test.zig", }; var codes = parseStatusLines(&lines); var i = @enumToInt(Status.modified); assert(codes[i] == 2); assert(2 == 2); } fn parseAheadBehind(source: Str) AheadBehind { var result = AheadBehind{}; var bracketPos = std.mem.indexOf(u8, source, "[") orelse return result; if (std.mem.indexOfPos(u8, source, bracketPos + 1, "ahead ")) |aheadPos| result.ahead = strToInt(source[aheadPos + 6 ..]); if (std.mem.indexOfPos(u8, source, bracketPos + 1, "behind ")) |behindPos| result.behind = strToInt(source[behindPos + 7 ..]); return result; } test "parse ahead/behind" { var source = "## master...origin/master [ahead 3, behind 2]"; var result = parseAheadBehind(source); expect(result.ahead == 3); expect(result.behind == 2); var source2 = "## master...origin/master"; result = parseAheadBehind(source2); expect(result.ahead == 0); expect(result.behind == 0); var source3 = "## master...origin/master [ahead 3]"; result = parseAheadBehind(source3); expect(result.ahead == 3); expect(result.behind == 0); } fn strToInt(source: Str) u32 { // source should be a slice pointing to the right position in the string // find the integer at the start of 'source', return 0 if no digits found var it = std.mem.tokenize(source, ", ]"); var val = it.next() orelse return 0; return std.fmt.parseInt(u32, val, 10) catch return 0; } test "parse digits from string" { var str = "123]"; var digit = strToInt(str); expect(digit == 123); } fn intToStr(i: u32) !Str { var buffer = try A.create([10]u8); var stream = std.io.fixedBufferStream(buffer); try std.fmt.formatIntValue(i, "", .{}, stream.writer()); return stream.getWritten(); } test "test string to integer" { A = std.testing.allocator; expect(std.mem.eql(u8, try intToStr(5), "5")); expect(std.mem.eql(u8, try intToStr(9), "9")); expect(std.mem.eql(u8, try intToStr(123), "123")); } fn slurpSplit(source: *const Str, delim: Str) []Str { var lines = std.mem.split(source.*, delim); var finalLines = std.ArrayList(Str).init(A); // defer finalLines.deinit(); while (lines.next()) |line| { var stripped_line = strip(line); if (std.mem.eql(u8, stripped_line, "")) continue; finalLines.append(line) catch |err| { dp("Error when appending: {}", .{err}); }; } return finalLines.toOwnedSlice(); } test "slurp split" { var lines: Str = \\ abc \\ def ; var result = slurpSplit(&lines, "\n"); expect(std.mem.eql(u8, result[0], " abc")); expect(std.mem.eql(u8, result[1], " def")); var str: Str = "a:b"; result = slurpSplit(&str, ":"); expect(std.mem.eql(u8, result[0], "a")); expect(std.mem.eql(u8, result[1], "b")); } // example git status output // g s -zb | tr '\0' '\n' // ## master...origin/master [ahead 1] // M repo_status.zig // M todo.txt // ?? .gitignore // ?? repo_status // ?? test // ?? test.nim // ?? test.zig fn parseStatus(status_txt: *Str) [STATUS_LEN]u32 { var slice = slurpSplit(status_txt, "\x00"); var status = parseStatusLines(slice[1..]); var ahead_behind = parseAheadBehind(slice[0]); status[@enumToInt(Status.ahead)] = ahead_behind.ahead; status[@enumToInt(Status.behind)] = ahead_behind.behind; return status; } test "parse status" { var lines = \\## master...origin/master [ahead 1] \\ M repo_status.zig \\ M todo.txt \\?? .gitignore \\?? repo_status \\?? test \\?? test.nim \\?? test.zig ; A = std.testing.allocator; var buffer: [300]u8 = undefined; _ = std.mem.replace(u8, lines, "\n", "\x00", buffer[0..]); var x: Str = &buffer; var status = parseStatus(&x); expect(status[@enumToInt(Status.untracked)] == 5); } fn getStatus(dir: Str) ![STATUS_LEN]u32 { // get and parse status codes var cmd = [_]Str{ "status", "-zb" }; var result = try gitCmd(&cmd, dir); if (result.term.Exited != 0) return error.GitStatusFailed; return parseStatus(&result.stdout); } pub fn isGitRepo(dir: Str) bool { var cmd = [_]Str{ "rev-parse", "--is-inside-work-tree" }; var result = gitCmd(&cmd, dir) catch |err| { std.log.err("Couldn't read git repo at {s}. Err: {s}", .{ dir, err }); return false; }; return result.term.Exited == 0; } fn styleWrite(esc: Escapes, color: Str, value: Str) !void { try print("{s}{s}{s}{s}{s}{s}{s}", .{ esc.o, color, esc.c, value, esc.o, C.default, esc.c, }); } pub fn writeStatusStr(esc: Escapes, status: GitStatus) !void { // o, c = e[shell].o.replace('{', '{{'), e[shell].c.replace('}', '}}') const format = .{ // using arrays over tuples failed .{ .color = C.green, .token = @as(Str, "↑"), .status = Status.ahead }, .{ .color = C.red, .token = @as(Str, "↓"), .status = Status.behind }, .{ .color = C.green, .token = @as(Str, "●"), .status = Status.staged }, .{ .color = C.yellow, .token = @as(Str, "+"), .status = Status.modified }, .{ .color = C.red, .token = @as(Str, "-"), .status = Status.removed }, .{ .color = C.cyan, .token = @as(Str, "…"), .status = Status.untracked }, .{ .color = C.blue, .token = @as(Str, "⚑"), .status = Status.stashed }, .{ .color = C.red, .token = @as(Str, "✖"), .status = Status.conflicted }, }; // print state if (!std.mem.eql(u8, status.state, "")) { try styleWrite(esc, C.magenta, status.state); try print(" ", .{}); } // print branch try styleWrite(esc, C.yellow, status.branch); // print stats var printed_space = false; inline for (format) |f| { var skip = false; var str: Str = undefined; if (f.status == Status.stashed) { str = formatStashes(status); } else { var num = status.status[@enumToInt(f.status)]; str = if (num == 0) "" else try intToStr(num); } if (!std.mem.eql(u8, str, "")) { if (!printed_space) { try print(" ", .{}); printed_space = true; } var strings = [_]Str{ f.token, str }; var temp = try std.mem.concat(A, u8, &strings); try styleWrite(esc, f.color, temp); } } } pub fn getFullRepoStatus(dir: Str) !GitStatus { var branch = async getBranch(dir); var status = async getStatus(dir); var state = async getState(dir); var stash = async getRepoStashCounts(dir); return GitStatus{ .state = try await state, .branch = try await branch, .status = try await status, .stash = try await stash, }; } pub fn main() !u8 { // allocator setup var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); A = &arena.allocator; var dir: Str = "."; var shellstr: Str = ""; if (std.os.argv.len == 3) shellstr = std.mem.spanZ(std.os.argv[1]); if (std.os.argv.len > 1) dir = std.mem.spanZ(std.os.argv[std.os.argv.len - 1]); if (std.os.argv.len > 3) { dp("Usage: repo_status [zsh|bash] [directory]\n", .{}); return 3; } // get the specified shell and initialize escape codes var shell = Shell.unknown; if (std.mem.eql(u8, shellstr, "zsh")) { shell = Shell.zsh; } else if (std.mem.eql(u8, shellstr, "bash")) { shell = Shell.bash; } else if (!std.mem.eql(u8, shellstr, "")) { dp("Unknown shell: '{s}'\n", .{shellstr}); return 3; } switch (shell) { .zsh => { E = Escapes.init("%{", "%}"); }, .bash => { E = Escapes.init("\\[", "\\]"); }, else => { E = Escapes.init("", ""); }, } if (!isGitRepo(dir)) return 2; // specific error code for 'not a repository' var status = try getFullRepoStatus(dir); try writeStatusStr(E, status); return 0; }
repo_status.zig
const std = @import("std"); const expect = std.testing.expect; const test_allocator = std.testing.allocator; const Allocator = std.mem.Allocator; const Direction = enum { forward, up, down }; const Step = struct { dir: Direction, distance: u64, pub fn parse(str: []const u8) !Step { var iter = std.mem.split(u8, str, " "); const s = iter.next().?; const dir = if (std.mem.eql(u8, s, "forward")) Direction.forward else if (std.mem.eql(u8, s, "up")) Direction.up else if (std.mem.eql(u8, s, "down")) Direction.down else unreachable; const value = try std.fmt.parseInt(u64, iter.next().?, 10); return Step{ .dir = dir, .distance = value }; } }; const Course = struct { steps: []Step, allocator: Allocator, pub fn load(allocator: Allocator, str: []const u8) !Course { var list = std.ArrayList(Step).init(allocator); defer list.deinit(); var iter = std.mem.split(u8, str, "\n"); while (iter.next()) |line| { if (line.len != 0) { const s = try Step.parse(line); try list.append(s); } } return Course{ .allocator = allocator, .steps = list.toOwnedSlice() }; } pub fn deinit(self: *const Course) void { self.allocator.free(self.steps); } pub fn follow(self: *const Course) u64 { var distance: u64 = 0; var depth: u64 = 0; for (self.steps) |step| { switch (step.dir) { Direction.up => depth = depth - step.distance, Direction.down => depth = depth + step.distance, Direction.forward => distance = distance + step.distance, } } return distance * depth; } pub fn followAim(self: *const Course) u64 { var distance: u64 = 0; var depth: u64 = 0; var aim: u64 = 0; for (self.steps) |step| { switch (step.dir) { Direction.up => aim = aim - step.distance, Direction.down => aim = aim + step.distance, Direction.forward => { distance = distance + step.distance; depth = depth + (step.distance * aim); }, } } return distance * depth; } }; pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const str = @embedFile("../input.txt"); var c = try Course.load(allocator, str); defer c.deinit(); const stdout = std.io.getStdOut().writer(); const part1 = c.follow(); try stdout.print("Part 1: {d}\n", .{part1}); const part2 = c.followAim(); try stdout.print("Part 2: {d}\n", .{part2}); } test "basic test" { const str = @embedFile("../test.txt"); var c = try Course.load(test_allocator, str); defer c.deinit(); try expect(150 == c.follow()); try expect(900 == c.followAim()); }
day02/src/main.zig
//-------------------------------------------------------------------------------- // Section: Types (16) //-------------------------------------------------------------------------------- pub const GESTURECONFIG_ID = enum(u32) { BEGIN = 1, END = 2, ZOOM = 3, PAN = 4, ROTATE = 5, TWOFINGERTAP = 6, PRESSANDTAP = 7, // ROLLOVER = 7, this enum value conflicts with PRESSANDTAP _, pub fn initFlags(o: struct { BEGIN: u1 = 0, END: u1 = 0, ZOOM: u1 = 0, PAN: u1 = 0, ROTATE: u1 = 0, TWOFINGERTAP: u1 = 0, PRESSANDTAP: u1 = 0, }) GESTURECONFIG_ID { return @intToEnum(GESTURECONFIG_ID, (if (o.BEGIN == 1) @enumToInt(GESTURECONFIG_ID.BEGIN) else 0) | (if (o.END == 1) @enumToInt(GESTURECONFIG_ID.END) else 0) | (if (o.ZOOM == 1) @enumToInt(GESTURECONFIG_ID.ZOOM) else 0) | (if (o.PAN == 1) @enumToInt(GESTURECONFIG_ID.PAN) else 0) | (if (o.ROTATE == 1) @enumToInt(GESTURECONFIG_ID.ROTATE) else 0) | (if (o.TWOFINGERTAP == 1) @enumToInt(GESTURECONFIG_ID.TWOFINGERTAP) else 0) | (if (o.PRESSANDTAP == 1) @enumToInt(GESTURECONFIG_ID.PRESSANDTAP) else 0) ); } }; pub const GID_BEGIN = GESTURECONFIG_ID.BEGIN; pub const GID_END = GESTURECONFIG_ID.END; pub const GID_ZOOM = GESTURECONFIG_ID.ZOOM; pub const GID_PAN = GESTURECONFIG_ID.PAN; pub const GID_ROTATE = GESTURECONFIG_ID.ROTATE; pub const GID_TWOFINGERTAP = GESTURECONFIG_ID.TWOFINGERTAP; pub const GID_PRESSANDTAP = GESTURECONFIG_ID.PRESSANDTAP; pub const GID_ROLLOVER = GESTURECONFIG_ID.PRESSANDTAP; pub const TOUCHEVENTF_FLAGS = enum(u32) { MOVE = 1, DOWN = 2, UP = 4, INRANGE = 8, PRIMARY = 16, NOCOALESCE = 32, PEN = 64, PALM = 128, _, pub fn initFlags(o: struct { MOVE: u1 = 0, DOWN: u1 = 0, UP: u1 = 0, INRANGE: u1 = 0, PRIMARY: u1 = 0, NOCOALESCE: u1 = 0, PEN: u1 = 0, PALM: u1 = 0, }) TOUCHEVENTF_FLAGS { return @intToEnum(TOUCHEVENTF_FLAGS, (if (o.MOVE == 1) @enumToInt(TOUCHEVENTF_FLAGS.MOVE) else 0) | (if (o.DOWN == 1) @enumToInt(TOUCHEVENTF_FLAGS.DOWN) else 0) | (if (o.UP == 1) @enumToInt(TOUCHEVENTF_FLAGS.UP) else 0) | (if (o.INRANGE == 1) @enumToInt(TOUCHEVENTF_FLAGS.INRANGE) else 0) | (if (o.PRIMARY == 1) @enumToInt(TOUCHEVENTF_FLAGS.PRIMARY) else 0) | (if (o.NOCOALESCE == 1) @enumToInt(TOUCHEVENTF_FLAGS.NOCOALESCE) else 0) | (if (o.PEN == 1) @enumToInt(TOUCHEVENTF_FLAGS.PEN) else 0) | (if (o.PALM == 1) @enumToInt(TOUCHEVENTF_FLAGS.PALM) else 0) ); } }; pub const TOUCHEVENTF_MOVE = TOUCHEVENTF_FLAGS.MOVE; pub const TOUCHEVENTF_DOWN = TOUCHEVENTF_FLAGS.DOWN; pub const TOUCHEVENTF_UP = TOUCHEVENTF_FLAGS.UP; pub const TOUCHEVENTF_INRANGE = TOUCHEVENTF_FLAGS.INRANGE; pub const TOUCHEVENTF_PRIMARY = TOUCHEVENTF_FLAGS.PRIMARY; pub const TOUCHEVENTF_NOCOALESCE = TOUCHEVENTF_FLAGS.NOCOALESCE; pub const TOUCHEVENTF_PEN = TOUCHEVENTF_FLAGS.PEN; pub const TOUCHEVENTF_PALM = TOUCHEVENTF_FLAGS.PALM; pub const TOUCHINPUTMASKF_MASK = enum(u32) { TIMEFROMSYSTEM = 1, EXTRAINFO = 2, CONTACTAREA = 4, _, pub fn initFlags(o: struct { TIMEFROMSYSTEM: u1 = 0, EXTRAINFO: u1 = 0, CONTACTAREA: u1 = 0, }) TOUCHINPUTMASKF_MASK { return @intToEnum(TOUCHINPUTMASKF_MASK, (if (o.TIMEFROMSYSTEM == 1) @enumToInt(TOUCHINPUTMASKF_MASK.TIMEFROMSYSTEM) else 0) | (if (o.EXTRAINFO == 1) @enumToInt(TOUCHINPUTMASKF_MASK.EXTRAINFO) else 0) | (if (o.CONTACTAREA == 1) @enumToInt(TOUCHINPUTMASKF_MASK.CONTACTAREA) else 0) ); } }; pub const TOUCHINPUTMASKF_TIMEFROMSYSTEM = TOUCHINPUTMASKF_MASK.TIMEFROMSYSTEM; pub const TOUCHINPUTMASKF_EXTRAINFO = TOUCHINPUTMASKF_MASK.EXTRAINFO; pub const TOUCHINPUTMASKF_CONTACTAREA = TOUCHINPUTMASKF_MASK.CONTACTAREA; pub const REGISTER_TOUCH_WINDOW_FLAGS = enum(u32) { FINETOUCH = 1, WANTPALM = 2, }; pub const TWF_FINETOUCH = REGISTER_TOUCH_WINDOW_FLAGS.FINETOUCH; pub const TWF_WANTPALM = REGISTER_TOUCH_WINDOW_FLAGS.WANTPALM; pub const HGESTUREINFO = *opaque{}; pub const HTOUCHINPUT = *opaque{}; const CLSID_InertiaProcessor_Value = Guid.initString("abb27087-4ce0-4e58-a0cb-e24df96814be"); pub const CLSID_InertiaProcessor = &CLSID_InertiaProcessor_Value; const CLSID_ManipulationProcessor_Value = Guid.initString("597d4fb0-47fd-4aff-89b9-c6cfae8cf08e"); pub const CLSID_ManipulationProcessor = &CLSID_ManipulationProcessor_Value; pub const MANIPULATION_PROCESSOR_MANIPULATIONS = enum(i32) { NONE = 0, TRANSLATE_X = 1, TRANSLATE_Y = 2, SCALE = 4, ROTATE = 8, ALL = 15, }; pub const MANIPULATION_NONE = MANIPULATION_PROCESSOR_MANIPULATIONS.NONE; pub const MANIPULATION_TRANSLATE_X = MANIPULATION_PROCESSOR_MANIPULATIONS.TRANSLATE_X; pub const MANIPULATION_TRANSLATE_Y = MANIPULATION_PROCESSOR_MANIPULATIONS.TRANSLATE_Y; pub const MANIPULATION_SCALE = MANIPULATION_PROCESSOR_MANIPULATIONS.SCALE; pub const MANIPULATION_ROTATE = MANIPULATION_PROCESSOR_MANIPULATIONS.ROTATE; pub const MANIPULATION_ALL = MANIPULATION_PROCESSOR_MANIPULATIONS.ALL; // TODO: this type is limited to platform 'windows6.1' const IID__IManipulationEvents_Value = Guid.initString("4f62c8da-9c53-4b22-93df-927a862bbb03"); pub const IID__IManipulationEvents = &IID__IManipulationEvents_Value; pub const _IManipulationEvents = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, ManipulationStarted: fn( self: *const _IManipulationEvents, x: f32, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ManipulationDelta: fn( self: *const _IManipulationEvents, x: f32, y: f32, translationDeltaX: f32, translationDeltaY: f32, scaleDelta: f32, expansionDelta: f32, rotationDelta: f32, cumulativeTranslationX: f32, cumulativeTranslationY: f32, cumulativeScale: f32, cumulativeExpansion: f32, cumulativeRotation: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ManipulationCompleted: fn( self: *const _IManipulationEvents, x: f32, y: f32, cumulativeTranslationX: f32, cumulativeTranslationY: f32, cumulativeScale: f32, cumulativeExpansion: f32, cumulativeRotation: f32, ) 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 _IManipulationEvents_ManipulationStarted(self: *const T, x: f32, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const _IManipulationEvents.VTable, self.vtable).ManipulationStarted(@ptrCast(*const _IManipulationEvents, self), x, y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _IManipulationEvents_ManipulationDelta(self: *const T, x: f32, y: f32, translationDeltaX: f32, translationDeltaY: f32, scaleDelta: f32, expansionDelta: f32, rotationDelta: f32, cumulativeTranslationX: f32, cumulativeTranslationY: f32, cumulativeScale: f32, cumulativeExpansion: f32, cumulativeRotation: f32) callconv(.Inline) HRESULT { return @ptrCast(*const _IManipulationEvents.VTable, self.vtable).ManipulationDelta(@ptrCast(*const _IManipulationEvents, self), x, y, translationDeltaX, translationDeltaY, scaleDelta, expansionDelta, rotationDelta, cumulativeTranslationX, cumulativeTranslationY, cumulativeScale, cumulativeExpansion, cumulativeRotation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn _IManipulationEvents_ManipulationCompleted(self: *const T, x: f32, y: f32, cumulativeTranslationX: f32, cumulativeTranslationY: f32, cumulativeScale: f32, cumulativeExpansion: f32, cumulativeRotation: f32) callconv(.Inline) HRESULT { return @ptrCast(*const _IManipulationEvents.VTable, self.vtable).ManipulationCompleted(@ptrCast(*const _IManipulationEvents, self), x, y, cumulativeTranslationX, cumulativeTranslationY, cumulativeScale, cumulativeExpansion, cumulativeRotation); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IInertiaProcessor_Value = Guid.initString("18b00c6d-c5ee-41b1-90a9-9d4a929095ad"); pub const IID_IInertiaProcessor = &IID_IInertiaProcessor_Value; pub const IInertiaProcessor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialOriginX: fn( self: *const IInertiaProcessor, x: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialOriginX: fn( self: *const IInertiaProcessor, x: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialOriginY: fn( self: *const IInertiaProcessor, y: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialOriginY: fn( self: *const IInertiaProcessor, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialVelocityX: fn( self: *const IInertiaProcessor, x: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialVelocityX: fn( self: *const IInertiaProcessor, x: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialVelocityY: fn( self: *const IInertiaProcessor, y: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialVelocityY: fn( self: *const IInertiaProcessor, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialAngularVelocity: fn( self: *const IInertiaProcessor, velocity: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialAngularVelocity: fn( self: *const IInertiaProcessor, velocity: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialExpansionVelocity: fn( self: *const IInertiaProcessor, velocity: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialExpansionVelocity: fn( self: *const IInertiaProcessor, velocity: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialRadius: fn( self: *const IInertiaProcessor, radius: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialRadius: fn( self: *const IInertiaProcessor, radius: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BoundaryLeft: fn( self: *const IInertiaProcessor, left: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BoundaryLeft: fn( self: *const IInertiaProcessor, left: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BoundaryTop: fn( self: *const IInertiaProcessor, top: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BoundaryTop: fn( self: *const IInertiaProcessor, top: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BoundaryRight: fn( self: *const IInertiaProcessor, right: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BoundaryRight: fn( self: *const IInertiaProcessor, right: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BoundaryBottom: fn( self: *const IInertiaProcessor, bottom: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_BoundaryBottom: fn( self: *const IInertiaProcessor, bottom: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ElasticMarginLeft: fn( self: *const IInertiaProcessor, left: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ElasticMarginLeft: fn( self: *const IInertiaProcessor, left: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ElasticMarginTop: fn( self: *const IInertiaProcessor, top: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ElasticMarginTop: fn( self: *const IInertiaProcessor, top: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ElasticMarginRight: fn( self: *const IInertiaProcessor, right: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ElasticMarginRight: fn( self: *const IInertiaProcessor, right: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ElasticMarginBottom: fn( self: *const IInertiaProcessor, bottom: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_ElasticMarginBottom: fn( self: *const IInertiaProcessor, bottom: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredDisplacement: fn( self: *const IInertiaProcessor, displacement: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredDisplacement: fn( self: *const IInertiaProcessor, displacement: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredRotation: fn( self: *const IInertiaProcessor, rotation: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredRotation: fn( self: *const IInertiaProcessor, rotation: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredExpansion: fn( self: *const IInertiaProcessor, expansion: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredExpansion: fn( self: *const IInertiaProcessor, expansion: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredDeceleration: fn( self: *const IInertiaProcessor, deceleration: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredDeceleration: fn( self: *const IInertiaProcessor, deceleration: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredAngularDeceleration: fn( self: *const IInertiaProcessor, deceleration: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredAngularDeceleration: fn( self: *const IInertiaProcessor, deceleration: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DesiredExpansionDeceleration: fn( self: *const IInertiaProcessor, deceleration: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_DesiredExpansionDeceleration: fn( self: *const IInertiaProcessor, deceleration: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_InitialTimestamp: fn( self: *const IInertiaProcessor, timestamp: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_InitialTimestamp: fn( self: *const IInertiaProcessor, timestamp: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IInertiaProcessor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Process: fn( self: *const IInertiaProcessor, completed: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessTime: fn( self: *const IInertiaProcessor, timestamp: u32, completed: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Complete: fn( self: *const IInertiaProcessor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompleteTime: fn( self: *const IInertiaProcessor, timestamp: 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 IInertiaProcessor_get_InitialOriginX(self: *const T, x: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialOriginX(@ptrCast(*const IInertiaProcessor, self), x); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialOriginX(self: *const T, x: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialOriginX(@ptrCast(*const IInertiaProcessor, self), x); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialOriginY(self: *const T, y: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialOriginY(@ptrCast(*const IInertiaProcessor, self), y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialOriginY(self: *const T, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialOriginY(@ptrCast(*const IInertiaProcessor, self), y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialVelocityX(self: *const T, x: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialVelocityX(@ptrCast(*const IInertiaProcessor, self), x); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialVelocityX(self: *const T, x: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialVelocityX(@ptrCast(*const IInertiaProcessor, self), x); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialVelocityY(self: *const T, y: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialVelocityY(@ptrCast(*const IInertiaProcessor, self), y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialVelocityY(self: *const T, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialVelocityY(@ptrCast(*const IInertiaProcessor, self), y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialAngularVelocity(self: *const T, velocity: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialAngularVelocity(@ptrCast(*const IInertiaProcessor, self), velocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialAngularVelocity(self: *const T, velocity: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialAngularVelocity(@ptrCast(*const IInertiaProcessor, self), velocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialExpansionVelocity(self: *const T, velocity: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialExpansionVelocity(@ptrCast(*const IInertiaProcessor, self), velocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialExpansionVelocity(self: *const T, velocity: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialExpansionVelocity(@ptrCast(*const IInertiaProcessor, self), velocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialRadius(self: *const T, radius: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialRadius(@ptrCast(*const IInertiaProcessor, self), radius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialRadius(self: *const T, radius: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialRadius(@ptrCast(*const IInertiaProcessor, self), radius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_BoundaryLeft(self: *const T, left: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_BoundaryLeft(@ptrCast(*const IInertiaProcessor, self), left); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_BoundaryLeft(self: *const T, left: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_BoundaryLeft(@ptrCast(*const IInertiaProcessor, self), left); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_BoundaryTop(self: *const T, top: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_BoundaryTop(@ptrCast(*const IInertiaProcessor, self), top); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_BoundaryTop(self: *const T, top: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_BoundaryTop(@ptrCast(*const IInertiaProcessor, self), top); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_BoundaryRight(self: *const T, right: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_BoundaryRight(@ptrCast(*const IInertiaProcessor, self), right); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_BoundaryRight(self: *const T, right: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_BoundaryRight(@ptrCast(*const IInertiaProcessor, self), right); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_BoundaryBottom(self: *const T, bottom: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_BoundaryBottom(@ptrCast(*const IInertiaProcessor, self), bottom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_BoundaryBottom(self: *const T, bottom: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_BoundaryBottom(@ptrCast(*const IInertiaProcessor, self), bottom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_ElasticMarginLeft(self: *const T, left: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_ElasticMarginLeft(@ptrCast(*const IInertiaProcessor, self), left); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_ElasticMarginLeft(self: *const T, left: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_ElasticMarginLeft(@ptrCast(*const IInertiaProcessor, self), left); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_ElasticMarginTop(self: *const T, top: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_ElasticMarginTop(@ptrCast(*const IInertiaProcessor, self), top); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_ElasticMarginTop(self: *const T, top: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_ElasticMarginTop(@ptrCast(*const IInertiaProcessor, self), top); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_ElasticMarginRight(self: *const T, right: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_ElasticMarginRight(@ptrCast(*const IInertiaProcessor, self), right); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_ElasticMarginRight(self: *const T, right: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_ElasticMarginRight(@ptrCast(*const IInertiaProcessor, self), right); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_ElasticMarginBottom(self: *const T, bottom: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_ElasticMarginBottom(@ptrCast(*const IInertiaProcessor, self), bottom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_ElasticMarginBottom(self: *const T, bottom: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_ElasticMarginBottom(@ptrCast(*const IInertiaProcessor, self), bottom); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_DesiredDisplacement(self: *const T, displacement: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_DesiredDisplacement(@ptrCast(*const IInertiaProcessor, self), displacement); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_DesiredDisplacement(self: *const T, displacement: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_DesiredDisplacement(@ptrCast(*const IInertiaProcessor, self), displacement); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_DesiredRotation(self: *const T, rotation: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_DesiredRotation(@ptrCast(*const IInertiaProcessor, self), rotation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_DesiredRotation(self: *const T, rotation: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_DesiredRotation(@ptrCast(*const IInertiaProcessor, self), rotation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_DesiredExpansion(self: *const T, expansion: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_DesiredExpansion(@ptrCast(*const IInertiaProcessor, self), expansion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_DesiredExpansion(self: *const T, expansion: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_DesiredExpansion(@ptrCast(*const IInertiaProcessor, self), expansion); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_DesiredDeceleration(self: *const T, deceleration: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_DesiredDeceleration(@ptrCast(*const IInertiaProcessor, self), deceleration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_DesiredDeceleration(self: *const T, deceleration: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_DesiredDeceleration(@ptrCast(*const IInertiaProcessor, self), deceleration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_DesiredAngularDeceleration(self: *const T, deceleration: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_DesiredAngularDeceleration(@ptrCast(*const IInertiaProcessor, self), deceleration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_DesiredAngularDeceleration(self: *const T, deceleration: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_DesiredAngularDeceleration(@ptrCast(*const IInertiaProcessor, self), deceleration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_DesiredExpansionDeceleration(self: *const T, deceleration: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_DesiredExpansionDeceleration(@ptrCast(*const IInertiaProcessor, self), deceleration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_DesiredExpansionDeceleration(self: *const T, deceleration: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_DesiredExpansionDeceleration(@ptrCast(*const IInertiaProcessor, self), deceleration); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_get_InitialTimestamp(self: *const T, timestamp: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).get_InitialTimestamp(@ptrCast(*const IInertiaProcessor, self), timestamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_put_InitialTimestamp(self: *const T, timestamp: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).put_InitialTimestamp(@ptrCast(*const IInertiaProcessor, self), timestamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).Reset(@ptrCast(*const IInertiaProcessor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_Process(self: *const T, completed: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).Process(@ptrCast(*const IInertiaProcessor, self), completed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_ProcessTime(self: *const T, timestamp: u32, completed: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).ProcessTime(@ptrCast(*const IInertiaProcessor, self), timestamp, completed); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_Complete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).Complete(@ptrCast(*const IInertiaProcessor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IInertiaProcessor_CompleteTime(self: *const T, timestamp: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IInertiaProcessor.VTable, self.vtable).CompleteTime(@ptrCast(*const IInertiaProcessor, self), timestamp); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.1' const IID_IManipulationProcessor_Value = Guid.initString("a22ac519-8300-48a0-bef4-f1be8737dba4"); pub const IID_IManipulationProcessor = &IID_IManipulationProcessor_Value; pub const IManipulationProcessor = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SupportedManipulations: fn( self: *const IManipulationProcessor, manipulations: ?*MANIPULATION_PROCESSOR_MANIPULATIONS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SupportedManipulations: fn( self: *const IManipulationProcessor, manipulations: MANIPULATION_PROCESSOR_MANIPULATIONS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PivotPointX: fn( self: *const IManipulationProcessor, pivotPointX: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PivotPointX: fn( self: *const IManipulationProcessor, pivotPointX: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PivotPointY: fn( self: *const IManipulationProcessor, pivotPointY: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PivotPointY: fn( self: *const IManipulationProcessor, pivotPointY: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PivotRadius: fn( self: *const IManipulationProcessor, pivotRadius: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_PivotRadius: fn( self: *const IManipulationProcessor, pivotRadius: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CompleteManipulation: fn( self: *const IManipulationProcessor, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessDown: fn( self: *const IManipulationProcessor, manipulatorId: u32, x: f32, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessMove: fn( self: *const IManipulationProcessor, manipulatorId: u32, x: f32, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessUp: fn( self: *const IManipulationProcessor, manipulatorId: u32, x: f32, y: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessDownWithTime: fn( self: *const IManipulationProcessor, manipulatorId: u32, x: f32, y: f32, timestamp: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessMoveWithTime: fn( self: *const IManipulationProcessor, manipulatorId: u32, x: f32, y: f32, timestamp: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ProcessUpWithTime: fn( self: *const IManipulationProcessor, manipulatorId: u32, x: f32, y: f32, timestamp: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVelocityX: fn( self: *const IManipulationProcessor, velocityX: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetVelocityY: fn( self: *const IManipulationProcessor, velocityY: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetExpansionVelocity: fn( self: *const IManipulationProcessor, expansionVelocity: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAngularVelocity: fn( self: *const IManipulationProcessor, angularVelocity: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_MinimumScaleRotateRadius: fn( self: *const IManipulationProcessor, minRadius: ?*f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_MinimumScaleRotateRadius: fn( self: *const IManipulationProcessor, minRadius: f32, ) 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 IManipulationProcessor_get_SupportedManipulations(self: *const T, manipulations: ?*MANIPULATION_PROCESSOR_MANIPULATIONS) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).get_SupportedManipulations(@ptrCast(*const IManipulationProcessor, self), manipulations); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_put_SupportedManipulations(self: *const T, manipulations: MANIPULATION_PROCESSOR_MANIPULATIONS) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).put_SupportedManipulations(@ptrCast(*const IManipulationProcessor, self), manipulations); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_get_PivotPointX(self: *const T, pivotPointX: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).get_PivotPointX(@ptrCast(*const IManipulationProcessor, self), pivotPointX); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_put_PivotPointX(self: *const T, pivotPointX: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).put_PivotPointX(@ptrCast(*const IManipulationProcessor, self), pivotPointX); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_get_PivotPointY(self: *const T, pivotPointY: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).get_PivotPointY(@ptrCast(*const IManipulationProcessor, self), pivotPointY); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_put_PivotPointY(self: *const T, pivotPointY: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).put_PivotPointY(@ptrCast(*const IManipulationProcessor, self), pivotPointY); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_get_PivotRadius(self: *const T, pivotRadius: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).get_PivotRadius(@ptrCast(*const IManipulationProcessor, self), pivotRadius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_put_PivotRadius(self: *const T, pivotRadius: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).put_PivotRadius(@ptrCast(*const IManipulationProcessor, self), pivotRadius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_CompleteManipulation(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).CompleteManipulation(@ptrCast(*const IManipulationProcessor, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_ProcessDown(self: *const T, manipulatorId: u32, x: f32, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).ProcessDown(@ptrCast(*const IManipulationProcessor, self), manipulatorId, x, y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_ProcessMove(self: *const T, manipulatorId: u32, x: f32, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).ProcessMove(@ptrCast(*const IManipulationProcessor, self), manipulatorId, x, y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_ProcessUp(self: *const T, manipulatorId: u32, x: f32, y: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).ProcessUp(@ptrCast(*const IManipulationProcessor, self), manipulatorId, x, y); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_ProcessDownWithTime(self: *const T, manipulatorId: u32, x: f32, y: f32, timestamp: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).ProcessDownWithTime(@ptrCast(*const IManipulationProcessor, self), manipulatorId, x, y, timestamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_ProcessMoveWithTime(self: *const T, manipulatorId: u32, x: f32, y: f32, timestamp: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).ProcessMoveWithTime(@ptrCast(*const IManipulationProcessor, self), manipulatorId, x, y, timestamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_ProcessUpWithTime(self: *const T, manipulatorId: u32, x: f32, y: f32, timestamp: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).ProcessUpWithTime(@ptrCast(*const IManipulationProcessor, self), manipulatorId, x, y, timestamp); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_GetVelocityX(self: *const T, velocityX: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).GetVelocityX(@ptrCast(*const IManipulationProcessor, self), velocityX); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_GetVelocityY(self: *const T, velocityY: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).GetVelocityY(@ptrCast(*const IManipulationProcessor, self), velocityY); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_GetExpansionVelocity(self: *const T, expansionVelocity: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).GetExpansionVelocity(@ptrCast(*const IManipulationProcessor, self), expansionVelocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_GetAngularVelocity(self: *const T, angularVelocity: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).GetAngularVelocity(@ptrCast(*const IManipulationProcessor, self), angularVelocity); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_get_MinimumScaleRotateRadius(self: *const T, minRadius: ?*f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).get_MinimumScaleRotateRadius(@ptrCast(*const IManipulationProcessor, self), minRadius); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IManipulationProcessor_put_MinimumScaleRotateRadius(self: *const T, minRadius: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IManipulationProcessor.VTable, self.vtable).put_MinimumScaleRotateRadius(@ptrCast(*const IManipulationProcessor, self), minRadius); } };} pub usingnamespace MethodMixin(@This()); }; pub const TOUCHINPUT = extern struct { x: i32, y: i32, hSource: ?HANDLE, dwID: u32, dwFlags: TOUCHEVENTF_FLAGS, dwMask: TOUCHINPUTMASKF_MASK, dwTime: u32, dwExtraInfo: usize, cxContact: u32, cyContact: u32, }; pub const GESTUREINFO = extern struct { cbSize: u32, dwFlags: u32, dwID: u32, hwndTarget: ?HWND, ptsLocation: POINTS, dwInstanceID: u32, dwSequenceID: u32, ullArguments: u64, cbExtraArgs: u32, }; pub const GESTURENOTIFYSTRUCT = extern struct { cbSize: u32, dwFlags: u32, hwndTarget: ?HWND, ptsLocation: POINTS, dwInstanceID: u32, }; pub const GESTURECONFIG = extern struct { dwID: GESTURECONFIG_ID, dwWant: u32, dwBlock: u32, }; //-------------------------------------------------------------------------------- // Section: Functions (10) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn GetTouchInputInfo( hTouchInput: ?HTOUCHINPUT, cInputs: u32, pInputs: [*]TOUCHINPUT, cbSize: i32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn CloseTouchInputHandle( hTouchInput: ?HTOUCHINPUT, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn RegisterTouchWindow( hwnd: ?HWND, ulFlags: REGISTER_TOUCH_WINDOW_FLAGS, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn UnregisterTouchWindow( hwnd: ?HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn IsTouchWindow( hwnd: ?HWND, pulFlags: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn GetGestureInfo( hGestureInfo: ?HGESTUREINFO, pGestureInfo: ?*GESTUREINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn GetGestureExtraArgs( hGestureInfo: ?HGESTUREINFO, cbExtraArgs: u32, // TODO: what to do with BytesParamIndex 1? pExtraArgs: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn CloseGestureInfoHandle( hGestureInfo: ?HGESTUREINFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn SetGestureConfig( hwnd: ?HWND, dwReserved: u32, cIDs: u32, pGestureConfig: [*]GESTURECONFIG, cbSize: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.1' pub extern "USER32" fn GetGestureConfig( hwnd: ?HWND, dwReserved: u32, dwFlags: u32, pcIDs: ?*u32, pGestureConfig: [*]GESTURECONFIG, cbSize: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (7) //-------------------------------------------------------------------------------- const Guid = @import("../../zig.zig").Guid; const BOOL = @import("../../foundation.zig").BOOL; const HANDLE = @import("../../foundation.zig").HANDLE; const HRESULT = @import("../../foundation.zig").HRESULT; const HWND = @import("../../foundation.zig").HWND; const IUnknown = @import("../../system/com.zig").IUnknown; const POINTS = @import("../../foundation.zig").POINTS; test { @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/ui/input/touch.zig
const std = @import("std"); const print = std.debug.print; pub fn main() anyerror!void { const allocator = std.heap.page_allocator; var file = try std.fs.cwd().openFile( "./inputs/day12.txt", .{ .read = true, }, ); var reader = std.io.bufferedReader(file.reader()).reader(); try part1(@TypeOf(reader), allocator, reader); try file.seekTo(0); try part2(@TypeOf(reader), allocator, reader); } fn part1(comptime Reader: type, allocator: *std.mem.Allocator, reader: Reader) !void { var number = std.ArrayList(u8).init(allocator); defer number.deinit(); var sum: isize = 0; while (reader.readByte()) |c| { if (std.ascii.isDigit(c) or (c == '-' and number.items.len == 0)) { try number.append(c); } else if (number.items.len > 0) { sum += try std.fmt.parseInt(isize, number.items, 10); number.clearRetainingCapacity(); } } else |err| { if (err != error.EndOfStream) { return err; } } print("Part 1: {d}\n", .{sum}); } fn part2(comptime Reader: type, allocator: *std.mem.Allocator, reader: Reader) !void { var json = std.ArrayList(u8).init(allocator); defer json.deinit(); try reader.readAllArrayList(&json, 50_000); var parser = std.json.Parser.init(allocator, false); defer parser.deinit(); var value_tree = try parser.parse(json.items); defer value_tree.deinit(); var todo = std.ArrayList(std.json.Value).init(allocator); defer todo.deinit(); try todo.append(value_tree.root); var sum: i64 = 0; while (todo.popOrNull()) |node| { switch (node) { .Null => {}, .Bool => {}, .Integer => |x| { sum += x; }, .Float => |_| unreachable, .NumberString => |_| unreachable, .String => |_| {}, .Array => |nodes| { try todo.appendSlice(nodes.items); }, .Object => |map| { var candidates = std.ArrayList(std.json.Value).init(allocator); defer candidates.deinit(); var is_red = false; for (map.values()) |v| { if (v == .String) { if (std.mem.eql(u8, v.String, "red")) { is_red = true; break; } } try candidates.append(v); } if (!is_red) { try todo.appendSlice(candidates.items); } }, } } print("Part 2: {d}\n", .{sum}); }
src/day12.zig
const std = @import("std"); const debug = std.debug; const fmt = std.fmt; const mem = std.mem; pub fn main() !void { var guard = try most_slepful_boy(); var minute = try most_slepful_minute(guard); var result = guard * minute; debug.assert(result == 87681); debug.warn("04-1 {}\n", result); } fn most_slepful_minute(guard: u32) !u32 { var current_guard: u32 = 0; var last_slep_min: u32 = 0; var minutes = []u32{0} ** 60; for (lines) |l| { var event_type = Line.get_event_type(l); switch (event_type) { Event.Begin => { current_guard = try Line.get_guard(l); last_slep_min = 0; if (current_guard == guard) { //Line.print(l); } }, Event.Slep => { last_slep_min = l.min; if (current_guard == guard) { //Line.print(l); } }, Event.Wek => { if (current_guard == guard) { //Line.print(l); var m: u32 = last_slep_min; while (m < l.min) { //debug.warn("{}\n", m); minutes[m] += 1; m += 1; } } }, else => unreachable, } } var most_slepful: u32 = 0; for (minutes) |sleps, m| { if (sleps > minutes[most_slepful]) { most_slepful = @intCast(u32, m); } } return most_slepful; } fn most_slepful_boy() !u32 { var current_guard: u32 = 0; var last_slep_min: u32 = 0; const biggest_boy: u32 = 3559; var slep_counts = []u32{0} ** (biggest_boy + 1); for (lines) |l| { //Line.print(l); var event_type = Line.get_event_type(l); switch (event_type) { Event.Begin => { current_guard = try Line.get_guard(l); last_slep_min = 0; }, Event.Slep => { last_slep_min = l.min; }, Event.Wek => { var slep_amt = l.min - last_slep_min; //debug.warn(" Slep: {}\n", slep_amt); slep_counts[current_guard] += slep_amt; //debug.warn(" TOTAL: {}\n", slep_counts[current_guard]); }, else => unreachable, } } var most_slepful: u32 = 0; for (slep_counts) |sleps, guard| { // todo: can there be a tie? if (sleps > slep_counts[most_slepful]) { most_slepful = @intCast(u32, guard); } } //debug.warn("Most slepful boy is {} with {} minutes\n", most_slepful, slep_counts[most_slepful]); return most_slepful; } const Event = enum { Begin, Slep, Wek, }; const Line = struct { y: u32, mon: u32, d: u32, h: u32, min: u32, s: []const u8, pub fn print(self: Line) void { debug.warn("[{}-{}-{} {}:{}] {}\n", self.y, self.mon, self.d, self.h, self.min, self.s); } pub fn get_event_type(self: Line) Event { return switch(self.s[0]) { 'G' => Event.Begin, 'f' => Event.Slep, 'w' => Event.Wek, else => unreachable, }; } pub fn get_guard(self: Line) !u32 { debug.assert(self.s[6] == '#'); return try get_int(self.s, usize(7)); } fn get_int(s: []const u8, start_pos: usize) !u32 { var pos = start_pos; debug.assert(is_digit(s[pos])); var encountered_non_digit = false; for (s[start_pos..]) |c, i| { if (!is_digit(c)) { encountered_non_digit = true; pos += i; break; } } if (encountered_non_digit) { return try fmt.parseInt(u32, s[start_pos..pos], 10); } else { return try fmt.parseInt(u32, s[start_pos..], 10); } } fn is_digit(char: u8) bool { if (char >= '0' and char <= '9') { return true; } return false; } }; inline fn line(y: u32, mon: u32, d: u32, h: u32, min: u32, s: []const u8) Line { return Line { .y = y, .mon = mon, .d = d, .h = h, .min = min, .s = s, }; } const lines = comptime block: { break :block []Line { line(1518, 03, 11, 00, 04, "Guard #1499 begins shift"), line(1518, 03, 11, 00, 33, "falls asleep"), line(1518, 03, 11, 00, 54, "wakes up"), line(1518, 03, 12, 00, 03, "Guard #2657 begins shift"), line(1518, 03, 12, 00, 21, "falls asleep"), line(1518, 03, 12, 00, 29, "wakes up"), line(1518, 03, 12, 00, 35, "falls asleep"), line(1518, 03, 12, 00, 47, "wakes up"), line(1518, 03, 13, 00, 04, "Guard #3449 begins shift"), line(1518, 03, 13, 00, 27, "falls asleep"), line(1518, 03, 13, 00, 55, "wakes up"), line(1518, 03, 14, 00, 02, "Guard #1033 begins shift"), line(1518, 03, 14, 00, 22, "falls asleep"), line(1518, 03, 14, 00, 50, "wakes up"), line(1518, 03, 14, 00, 56, "falls asleep"), line(1518, 03, 14, 00, 57, "wakes up"), line(1518, 03, 15, 00, 01, "Guard #1033 begins shift"), line(1518, 03, 15, 00, 29, "falls asleep"), line(1518, 03, 15, 00, 56, "wakes up"), line(1518, 03, 15, 23, 50, "Guard #1811 begins shift"), line(1518, 03, 16, 00, 03, "falls asleep"), line(1518, 03, 16, 00, 44, "wakes up"), line(1518, 03, 16, 00, 48, "falls asleep"), line(1518, 03, 16, 00, 59, "wakes up"), line(1518, 03, 16, 23, 57, "Guard #2657 begins shift"), line(1518, 03, 17, 00, 48, "falls asleep"), line(1518, 03, 17, 00, 54, "wakes up"), line(1518, 03, 17, 23, 57, "Guard #241 begins shift"), line(1518, 03, 18, 00, 29, "falls asleep"), line(1518, 03, 18, 00, 32, "wakes up"), line(1518, 03, 18, 23, 49, "Guard #3449 begins shift"), line(1518, 03, 19, 00, 04, "falls asleep"), line(1518, 03, 19, 00, 19, "wakes up"), line(1518, 03, 19, 00, 29, "falls asleep"), line(1518, 03, 19, 00, 34, "wakes up"), line(1518, 03, 19, 23, 58, "Guard #241 begins shift"), line(1518, 03, 20, 00, 37, "falls asleep"), line(1518, 03, 20, 00, 59, "wakes up"), line(1518, 03, 20, 23, 58, "Guard #73 begins shift"), line(1518, 03, 21, 00, 22, "falls asleep"), line(1518, 03, 21, 00, 27, "wakes up"), line(1518, 03, 21, 00, 39, "falls asleep"), line(1518, 03, 21, 00, 40, "wakes up"), line(1518, 03, 21, 00, 46, "falls asleep"), line(1518, 03, 21, 00, 57, "wakes up"), line(1518, 03, 21, 23, 57, "Guard #1811 begins shift"), line(1518, 03, 22, 00, 46, "falls asleep"), line(1518, 03, 22, 00, 58, "wakes up"), line(1518, 03, 22, 23, 50, "Guard #3361 begins shift"), line(1518, 03, 23, 00, 00, "falls asleep"), line(1518, 03, 23, 00, 28, "wakes up"), line(1518, 03, 23, 00, 47, "falls asleep"), line(1518, 03, 23, 00, 49, "wakes up"), line(1518, 03, 24, 00, 02, "Guard #1033 begins shift"), line(1518, 03, 24, 00, 26, "falls asleep"), line(1518, 03, 24, 00, 28, "wakes up"), line(1518, 03, 24, 00, 41, "falls asleep"), line(1518, 03, 24, 00, 42, "wakes up"), line(1518, 03, 24, 00, 51, "falls asleep"), line(1518, 03, 24, 00, 58, "wakes up"), line(1518, 03, 24, 23, 47, "Guard #2411 begins shift"), line(1518, 03, 25, 00, 00, "falls asleep"), line(1518, 03, 25, 00, 30, "wakes up"), line(1518, 03, 25, 23, 58, "Guard #1033 begins shift"), line(1518, 03, 26, 00, 10, "falls asleep"), line(1518, 03, 26, 00, 56, "wakes up"), line(1518, 03, 26, 23, 57, "Guard #1091 begins shift"), line(1518, 03, 27, 00, 18, "falls asleep"), line(1518, 03, 27, 00, 30, "wakes up"), line(1518, 03, 27, 00, 34, "falls asleep"), line(1518, 03, 27, 00, 44, "wakes up"), line(1518, 03, 28, 00, 03, "Guard #241 begins shift"), line(1518, 03, 28, 00, 10, "falls asleep"), line(1518, 03, 28, 00, 44, "wakes up"), line(1518, 03, 29, 00, 01, "Guard #2579 begins shift"), line(1518, 03, 30, 00, 03, "Guard #1811 begins shift"), line(1518, 03, 30, 00, 37, "falls asleep"), line(1518, 03, 30, 00, 48, "wakes up"), line(1518, 03, 30, 00, 54, "falls asleep"), line(1518, 03, 30, 00, 59, "wakes up"), line(1518, 03, 30, 23, 58, "Guard #1867 begins shift"), line(1518, 03, 31, 23, 58, "Guard #3203 begins shift"), line(1518, 04, 01, 00, 16, "falls asleep"), line(1518, 04, 01, 00, 46, "wakes up"), line(1518, 04, 02, 00, 01, "Guard #2099 begins shift"), line(1518, 04, 02, 00, 42, "falls asleep"), line(1518, 04, 02, 00, 53, "wakes up"), line(1518, 04, 03, 00, 04, "Guard #313 begins shift"), line(1518, 04, 03, 00, 06, "falls asleep"), line(1518, 04, 03, 00, 58, "wakes up"), line(1518, 04, 04, 00, 02, "Guard #983 begins shift"), line(1518, 04, 04, 00, 22, "falls asleep"), line(1518, 04, 04, 00, 30, "wakes up"), line(1518, 04, 05, 00, 01, "Guard #2099 begins shift"), line(1518, 04, 05, 00, 26, "falls asleep"), line(1518, 04, 05, 00, 31, "wakes up"), line(1518, 04, 05, 23, 57, "Guard #2617 begins shift"), line(1518, 04, 06, 00, 08, "falls asleep"), line(1518, 04, 06, 00, 09, "wakes up"), line(1518, 04, 06, 00, 15, "falls asleep"), line(1518, 04, 06, 00, 55, "wakes up"), line(1518, 04, 07, 00, 01, "Guard #1291 begins shift"), line(1518, 04, 07, 00, 14, "falls asleep"), line(1518, 04, 07, 00, 40, "wakes up"), line(1518, 04, 07, 00, 48, "falls asleep"), line(1518, 04, 07, 00, 51, "wakes up"), line(1518, 04, 07, 00, 55, "falls asleep"), line(1518, 04, 07, 00, 57, "wakes up"), line(1518, 04, 08, 00, 03, "Guard #2411 begins shift"), line(1518, 04, 08, 00, 12, "falls asleep"), line(1518, 04, 08, 00, 28, "wakes up"), line(1518, 04, 08, 23, 51, "Guard #3559 begins shift"), line(1518, 04, 09, 00, 05, "falls asleep"), line(1518, 04, 09, 00, 39, "wakes up"), line(1518, 04, 09, 00, 45, "falls asleep"), line(1518, 04, 09, 00, 46, "wakes up"), line(1518, 04, 10, 00, 00, "Guard #1811 begins shift"), line(1518, 04, 10, 00, 22, "falls asleep"), line(1518, 04, 10, 00, 48, "wakes up"), line(1518, 04, 10, 00, 53, "falls asleep"), line(1518, 04, 10, 00, 59, "wakes up"), line(1518, 04, 10, 23, 52, "Guard #3559 begins shift"), line(1518, 04, 11, 00, 01, "falls asleep"), line(1518, 04, 11, 00, 25, "wakes up"), line(1518, 04, 11, 00, 42, "falls asleep"), line(1518, 04, 11, 00, 53, "wakes up"), line(1518, 04, 11, 23, 57, "Guard #3499 begins shift"), line(1518, 04, 12, 00, 37, "falls asleep"), line(1518, 04, 12, 00, 50, "wakes up"), line(1518, 04, 12, 23, 54, "Guard #2099 begins shift"), line(1518, 04, 13, 00, 00, "falls asleep"), line(1518, 04, 13, 00, 35, "wakes up"), line(1518, 04, 13, 00, 43, "falls asleep"), line(1518, 04, 13, 00, 46, "wakes up"), line(1518, 04, 14, 00, 01, "Guard #3559 begins shift"), line(1518, 04, 14, 00, 13, "falls asleep"), line(1518, 04, 14, 00, 51, "wakes up"), line(1518, 04, 14, 23, 58, "Guard #3203 begins shift"), line(1518, 04, 15, 00, 17, "falls asleep"), line(1518, 04, 15, 00, 23, "wakes up"), line(1518, 04, 15, 23, 46, "Guard #313 begins shift"), line(1518, 04, 16, 00, 01, "falls asleep"), line(1518, 04, 16, 00, 59, "wakes up"), line(1518, 04, 17, 00, 00, "Guard #1291 begins shift"), line(1518, 04, 17, 00, 18, "falls asleep"), line(1518, 04, 17, 00, 47, "wakes up"), line(1518, 04, 17, 00, 53, "falls asleep"), line(1518, 04, 17, 00, 59, "wakes up"), line(1518, 04, 18, 00, 00, "Guard #1091 begins shift"), line(1518, 04, 18, 00, 06, "falls asleep"), line(1518, 04, 18, 00, 44, "wakes up"), line(1518, 04, 18, 23, 56, "Guard #3109 begins shift"), line(1518, 04, 19, 00, 44, "falls asleep"), line(1518, 04, 19, 00, 49, "wakes up"), line(1518, 04, 19, 00, 55, "falls asleep"), line(1518, 04, 19, 00, 58, "wakes up"), line(1518, 04, 19, 23, 58, "Guard #1291 begins shift"), line(1518, 04, 20, 00, 28, "falls asleep"), line(1518, 04, 20, 00, 45, "wakes up"), line(1518, 04, 20, 23, 54, "Guard #73 begins shift"), line(1518, 04, 21, 00, 00, "falls asleep"), line(1518, 04, 21, 00, 30, "wakes up"), line(1518, 04, 21, 00, 46, "falls asleep"), line(1518, 04, 21, 00, 49, "wakes up"), line(1518, 04, 21, 23, 56, "Guard #1811 begins shift"), line(1518, 04, 22, 00, 11, "falls asleep"), line(1518, 04, 22, 00, 49, "wakes up"), line(1518, 04, 22, 23, 57, "Guard #2099 begins shift"), line(1518, 04, 23, 00, 12, "falls asleep"), line(1518, 04, 23, 00, 17, "wakes up"), line(1518, 04, 23, 00, 22, "falls asleep"), line(1518, 04, 23, 00, 57, "wakes up"), line(1518, 04, 24, 00, 04, "Guard #3361 begins shift"), line(1518, 04, 24, 00, 34, "falls asleep"), line(1518, 04, 24, 00, 58, "wakes up"), line(1518, 04, 25, 00, 00, "Guard #3203 begins shift"), line(1518, 04, 25, 00, 44, "falls asleep"), line(1518, 04, 25, 00, 52, "wakes up"), line(1518, 04, 26, 00, 00, "Guard #241 begins shift"), line(1518, 04, 26, 00, 18, "falls asleep"), line(1518, 04, 26, 00, 40, "wakes up"), line(1518, 04, 26, 23, 58, "Guard #3109 begins shift"), line(1518, 04, 27, 00, 24, "falls asleep"), line(1518, 04, 27, 00, 39, "wakes up"), line(1518, 04, 27, 00, 43, "falls asleep"), line(1518, 04, 27, 00, 44, "wakes up"), line(1518, 04, 28, 00, 02, "Guard #1811 begins shift"), line(1518, 04, 28, 00, 33, "falls asleep"), line(1518, 04, 28, 00, 43, "wakes up"), line(1518, 04, 28, 23, 51, "Guard #73 begins shift"), line(1518, 04, 29, 00, 01, "falls asleep"), line(1518, 04, 29, 00, 24, "wakes up"), line(1518, 04, 30, 00, 02, "Guard #1499 begins shift"), line(1518, 04, 30, 00, 47, "falls asleep"), line(1518, 04, 30, 00, 49, "wakes up"), line(1518, 05, 01, 00, 01, "Guard #1499 begins shift"), line(1518, 05, 01, 00, 09, "falls asleep"), line(1518, 05, 01, 00, 25, "wakes up"), line(1518, 05, 01, 00, 49, "falls asleep"), line(1518, 05, 01, 00, 58, "wakes up"), line(1518, 05, 01, 23, 59, "Guard #3109 begins shift"), line(1518, 05, 02, 00, 19, "falls asleep"), line(1518, 05, 02, 00, 48, "wakes up"), line(1518, 05, 02, 23, 53, "Guard #241 begins shift"), line(1518, 05, 03, 00, 04, "falls asleep"), line(1518, 05, 03, 00, 52, "wakes up"), line(1518, 05, 03, 23, 56, "Guard #3559 begins shift"), line(1518, 05, 04, 00, 19, "falls asleep"), line(1518, 05, 04, 00, 22, "wakes up"), line(1518, 05, 04, 00, 48, "falls asleep"), line(1518, 05, 04, 00, 59, "wakes up"), line(1518, 05, 04, 23, 58, "Guard #2657 begins shift"), line(1518, 05, 05, 00, 32, "falls asleep"), line(1518, 05, 05, 00, 34, "wakes up"), line(1518, 05, 05, 00, 43, "falls asleep"), line(1518, 05, 05, 00, 55, "wakes up"), line(1518, 05, 05, 23, 58, "Guard #3499 begins shift"), line(1518, 05, 06, 00, 06, "falls asleep"), line(1518, 05, 06, 00, 11, "wakes up"), line(1518, 05, 07, 00, 04, "Guard #1091 begins shift"), line(1518, 05, 07, 00, 16, "falls asleep"), line(1518, 05, 07, 00, 35, "wakes up"), line(1518, 05, 07, 00, 38, "falls asleep"), line(1518, 05, 07, 00, 48, "wakes up"), line(1518, 05, 07, 00, 52, "falls asleep"), line(1518, 05, 07, 00, 56, "wakes up"), line(1518, 05, 08, 00, 01, "Guard #1033 begins shift"), line(1518, 05, 08, 00, 08, "falls asleep"), line(1518, 05, 08, 00, 11, "wakes up"), line(1518, 05, 08, 00, 19, "falls asleep"), line(1518, 05, 08, 00, 49, "wakes up"), line(1518, 05, 08, 00, 52, "falls asleep"), line(1518, 05, 08, 00, 55, "wakes up"), line(1518, 05, 08, 23, 56, "Guard #2099 begins shift"), line(1518, 05, 09, 00, 34, "falls asleep"), line(1518, 05, 09, 00, 49, "wakes up"), line(1518, 05, 10, 00, 00, "Guard #73 begins shift"), line(1518, 05, 10, 00, 19, "falls asleep"), line(1518, 05, 10, 00, 29, "wakes up"), line(1518, 05, 11, 00, 02, "Guard #1811 begins shift"), line(1518, 05, 11, 00, 10, "falls asleep"), line(1518, 05, 11, 00, 58, "wakes up"), line(1518, 05, 11, 23, 50, "Guard #3109 begins shift"), line(1518, 05, 12, 00, 05, "falls asleep"), line(1518, 05, 12, 00, 54, "wakes up"), line(1518, 05, 13, 00, 00, "Guard #1499 begins shift"), line(1518, 05, 13, 00, 10, "falls asleep"), line(1518, 05, 13, 00, 33, "wakes up"), line(1518, 05, 14, 00, 01, "Guard #1291 begins shift"), line(1518, 05, 14, 00, 17, "falls asleep"), line(1518, 05, 14, 00, 37, "wakes up"), line(1518, 05, 15, 00, 03, "Guard #241 begins shift"), line(1518, 05, 15, 00, 19, "falls asleep"), line(1518, 05, 15, 00, 49, "wakes up"), line(1518, 05, 16, 00, 00, "Guard #983 begins shift"), line(1518, 05, 16, 00, 20, "falls asleep"), line(1518, 05, 16, 00, 23, "wakes up"), line(1518, 05, 16, 00, 28, "falls asleep"), line(1518, 05, 16, 00, 58, "wakes up"), line(1518, 05, 17, 00, 00, "Guard #241 begins shift"), line(1518, 05, 17, 00, 15, "falls asleep"), line(1518, 05, 17, 00, 23, "wakes up"), line(1518, 05, 17, 23, 58, "Guard #3499 begins shift"), line(1518, 05, 18, 00, 35, "falls asleep"), line(1518, 05, 18, 00, 40, "wakes up"), line(1518, 05, 18, 23, 53, "Guard #3109 begins shift"), line(1518, 05, 19, 00, 04, "falls asleep"), line(1518, 05, 19, 00, 16, "wakes up"), line(1518, 05, 19, 00, 29, "falls asleep"), line(1518, 05, 19, 00, 57, "wakes up"), line(1518, 05, 20, 00, 02, "Guard #1033 begins shift"), line(1518, 05, 20, 00, 36, "falls asleep"), line(1518, 05, 20, 00, 59, "wakes up"), line(1518, 05, 20, 23, 57, "Guard #1811 begins shift"), line(1518, 05, 21, 00, 28, "falls asleep"), line(1518, 05, 21, 00, 31, "wakes up"), line(1518, 05, 22, 00, 04, "Guard #313 begins shift"), line(1518, 05, 22, 00, 28, "falls asleep"), line(1518, 05, 22, 00, 30, "wakes up"), line(1518, 05, 22, 23, 59, "Guard #2617 begins shift"), line(1518, 05, 23, 00, 11, "falls asleep"), line(1518, 05, 23, 00, 14, "wakes up"), line(1518, 05, 23, 00, 21, "falls asleep"), line(1518, 05, 23, 00, 24, "wakes up"), line(1518, 05, 23, 23, 56, "Guard #1811 begins shift"), line(1518, 05, 24, 00, 17, "falls asleep"), line(1518, 05, 24, 00, 57, "wakes up"), line(1518, 05, 24, 23, 56, "Guard #983 begins shift"), line(1518, 05, 25, 00, 29, "falls asleep"), line(1518, 05, 25, 00, 59, "wakes up"), line(1518, 05, 26, 00, 02, "Guard #919 begins shift"), line(1518, 05, 26, 00, 06, "falls asleep"), line(1518, 05, 26, 00, 11, "wakes up"), line(1518, 05, 26, 00, 40, "falls asleep"), line(1518, 05, 26, 00, 46, "wakes up"), line(1518, 05, 26, 00, 54, "falls asleep"), line(1518, 05, 26, 00, 56, "wakes up"), line(1518, 05, 27, 00, 00, "Guard #3499 begins shift"), line(1518, 05, 27, 00, 26, "falls asleep"), line(1518, 05, 27, 00, 53, "wakes up"), line(1518, 05, 28, 00, 03, "Guard #3449 begins shift"), line(1518, 05, 28, 00, 11, "falls asleep"), line(1518, 05, 28, 00, 14, "wakes up"), line(1518, 05, 28, 00, 41, "falls asleep"), line(1518, 05, 28, 00, 43, "wakes up"), line(1518, 05, 28, 00, 52, "falls asleep"), line(1518, 05, 28, 00, 54, "wakes up"), line(1518, 05, 28, 23, 56, "Guard #2657 begins shift"), line(1518, 05, 29, 00, 09, "falls asleep"), line(1518, 05, 29, 00, 34, "wakes up"), line(1518, 05, 30, 00, 04, "Guard #1499 begins shift"), line(1518, 05, 30, 00, 14, "falls asleep"), line(1518, 05, 30, 00, 53, "wakes up"), line(1518, 05, 31, 00, 02, "Guard #2657 begins shift"), line(1518, 05, 31, 00, 33, "falls asleep"), line(1518, 05, 31, 00, 40, "wakes up"), line(1518, 05, 31, 00, 50, "falls asleep"), line(1518, 05, 31, 00, 56, "wakes up"), line(1518, 06, 01, 00, 02, "Guard #2657 begins shift"), line(1518, 06, 01, 00, 39, "falls asleep"), line(1518, 06, 01, 00, 48, "wakes up"), line(1518, 06, 01, 23, 59, "Guard #241 begins shift"), line(1518, 06, 02, 00, 09, "falls asleep"), line(1518, 06, 02, 00, 38, "wakes up"), line(1518, 06, 02, 23, 59, "Guard #241 begins shift"), line(1518, 06, 03, 00, 36, "falls asleep"), line(1518, 06, 03, 00, 48, "wakes up"), line(1518, 06, 03, 00, 55, "falls asleep"), line(1518, 06, 03, 00, 56, "wakes up"), line(1518, 06, 03, 23, 46, "Guard #313 begins shift"), line(1518, 06, 04, 00, 01, "falls asleep"), line(1518, 06, 04, 00, 32, "wakes up"), line(1518, 06, 05, 00, 00, "Guard #983 begins shift"), line(1518, 06, 05, 00, 21, "falls asleep"), line(1518, 06, 05, 00, 43, "wakes up"), line(1518, 06, 05, 00, 47, "falls asleep"), line(1518, 06, 05, 00, 52, "wakes up"), line(1518, 06, 05, 00, 56, "falls asleep"), line(1518, 06, 05, 00, 59, "wakes up"), line(1518, 06, 06, 00, 03, "Guard #2657 begins shift"), line(1518, 06, 06, 00, 12, "falls asleep"), line(1518, 06, 06, 00, 24, "wakes up"), line(1518, 06, 06, 23, 59, "Guard #3499 begins shift"), line(1518, 06, 07, 00, 15, "falls asleep"), line(1518, 06, 07, 00, 34, "wakes up"), line(1518, 06, 07, 00, 39, "falls asleep"), line(1518, 06, 07, 00, 59, "wakes up"), line(1518, 06, 08, 00, 02, "Guard #1811 begins shift"), line(1518, 06, 08, 00, 14, "falls asleep"), line(1518, 06, 08, 00, 48, "wakes up"), line(1518, 06, 08, 00, 53, "falls asleep"), line(1518, 06, 08, 00, 54, "wakes up"), line(1518, 06, 08, 23, 47, "Guard #241 begins shift"), line(1518, 06, 09, 00, 02, "falls asleep"), line(1518, 06, 09, 00, 16, "wakes up"), line(1518, 06, 09, 00, 45, "falls asleep"), line(1518, 06, 09, 00, 53, "wakes up"), line(1518, 06, 10, 00, 00, "Guard #919 begins shift"), line(1518, 06, 10, 00, 34, "falls asleep"), line(1518, 06, 10, 00, 48, "wakes up"), line(1518, 06, 10, 00, 53, "falls asleep"), line(1518, 06, 10, 00, 57, "wakes up"), line(1518, 06, 11, 00, 02, "Guard #919 begins shift"), line(1518, 06, 11, 00, 14, "falls asleep"), line(1518, 06, 11, 00, 44, "wakes up"), line(1518, 06, 12, 00, 00, "Guard #3499 begins shift"), line(1518, 06, 12, 00, 13, "falls asleep"), line(1518, 06, 12, 00, 44, "wakes up"), line(1518, 06, 13, 00, 00, "Guard #3499 begins shift"), line(1518, 06, 13, 00, 26, "falls asleep"), line(1518, 06, 13, 00, 43, "wakes up"), line(1518, 06, 14, 00, 00, "Guard #3499 begins shift"), line(1518, 06, 14, 00, 08, "falls asleep"), line(1518, 06, 14, 00, 48, "wakes up"), line(1518, 06, 14, 23, 50, "Guard #983 begins shift"), line(1518, 06, 15, 00, 03, "falls asleep"), line(1518, 06, 15, 00, 22, "wakes up"), line(1518, 06, 15, 00, 27, "falls asleep"), line(1518, 06, 15, 00, 44, "wakes up"), line(1518, 06, 15, 00, 53, "falls asleep"), line(1518, 06, 15, 00, 58, "wakes up"), line(1518, 06, 15, 23, 59, "Guard #1499 begins shift"), line(1518, 06, 16, 00, 24, "falls asleep"), line(1518, 06, 16, 00, 29, "wakes up"), line(1518, 06, 16, 00, 44, "falls asleep"), line(1518, 06, 16, 00, 56, "wakes up"), line(1518, 06, 17, 00, 00, "Guard #983 begins shift"), line(1518, 06, 17, 00, 15, "falls asleep"), line(1518, 06, 17, 00, 25, "wakes up"), line(1518, 06, 17, 00, 31, "falls asleep"), line(1518, 06, 17, 00, 45, "wakes up"), line(1518, 06, 17, 00, 48, "falls asleep"), line(1518, 06, 17, 00, 53, "wakes up"), line(1518, 06, 18, 00, 00, "Guard #1499 begins shift"), line(1518, 06, 18, 00, 28, "falls asleep"), line(1518, 06, 18, 00, 55, "wakes up"), line(1518, 06, 19, 00, 00, "Guard #1499 begins shift"), line(1518, 06, 19, 00, 14, "falls asleep"), line(1518, 06, 19, 00, 37, "wakes up"), line(1518, 06, 19, 00, 45, "falls asleep"), line(1518, 06, 19, 00, 57, "wakes up"), line(1518, 06, 19, 23, 57, "Guard #2411 begins shift"), line(1518, 06, 20, 00, 27, "falls asleep"), line(1518, 06, 20, 00, 43, "wakes up"), line(1518, 06, 20, 00, 47, "falls asleep"), line(1518, 06, 20, 00, 52, "wakes up"), line(1518, 06, 20, 23, 57, "Guard #3361 begins shift"), line(1518, 06, 21, 00, 17, "falls asleep"), line(1518, 06, 21, 00, 23, "wakes up"), line(1518, 06, 22, 00, 02, "Guard #2411 begins shift"), line(1518, 06, 22, 00, 22, "falls asleep"), line(1518, 06, 22, 00, 48, "wakes up"), line(1518, 06, 22, 23, 59, "Guard #2657 begins shift"), line(1518, 06, 23, 00, 10, "falls asleep"), line(1518, 06, 23, 00, 40, "wakes up"), line(1518, 06, 24, 00, 04, "Guard #1033 begins shift"), line(1518, 06, 24, 00, 12, "falls asleep"), line(1518, 06, 24, 00, 28, "wakes up"), line(1518, 06, 25, 00, 00, "Guard #3499 begins shift"), line(1518, 06, 25, 00, 18, "falls asleep"), line(1518, 06, 25, 00, 41, "wakes up"), line(1518, 06, 25, 23, 59, "Guard #241 begins shift"), line(1518, 06, 26, 00, 06, "falls asleep"), line(1518, 06, 26, 00, 21, "wakes up"), line(1518, 06, 26, 00, 29, "falls asleep"), line(1518, 06, 26, 00, 37, "wakes up"), line(1518, 06, 26, 00, 45, "falls asleep"), line(1518, 06, 26, 00, 53, "wakes up"), line(1518, 06, 26, 23, 59, "Guard #983 begins shift"), line(1518, 06, 27, 00, 35, "falls asleep"), line(1518, 06, 27, 00, 37, "wakes up"), line(1518, 06, 27, 00, 46, "falls asleep"), line(1518, 06, 27, 00, 58, "wakes up"), line(1518, 06, 28, 00, 04, "Guard #2657 begins shift"), line(1518, 06, 28, 00, 20, "falls asleep"), line(1518, 06, 28, 00, 37, "wakes up"), line(1518, 06, 28, 23, 59, "Guard #2657 begins shift"), line(1518, 06, 29, 00, 46, "falls asleep"), line(1518, 06, 29, 00, 51, "wakes up"), line(1518, 06, 29, 23, 59, "Guard #1811 begins shift"), line(1518, 06, 30, 00, 39, "falls asleep"), line(1518, 06, 30, 00, 52, "wakes up"), line(1518, 06, 30, 00, 56, "falls asleep"), line(1518, 06, 30, 00, 59, "wakes up"), line(1518, 06, 30, 23, 49, "Guard #241 begins shift"), line(1518, 07, 01, 00, 05, "falls asleep"), line(1518, 07, 01, 00, 36, "wakes up"), line(1518, 07, 01, 00, 40, "falls asleep"), line(1518, 07, 01, 00, 47, "wakes up"), line(1518, 07, 01, 23, 51, "Guard #3109 begins shift"), line(1518, 07, 02, 00, 00, "falls asleep"), line(1518, 07, 02, 00, 43, "wakes up"), line(1518, 07, 02, 23, 57, "Guard #1811 begins shift"), line(1518, 07, 03, 00, 07, "falls asleep"), line(1518, 07, 03, 00, 19, "wakes up"), line(1518, 07, 03, 00, 22, "falls asleep"), line(1518, 07, 03, 00, 47, "wakes up"), line(1518, 07, 04, 00, 03, "Guard #2411 begins shift"), line(1518, 07, 04, 00, 22, "falls asleep"), line(1518, 07, 04, 00, 48, "wakes up"), line(1518, 07, 04, 23, 59, "Guard #2099 begins shift"), line(1518, 07, 05, 00, 11, "falls asleep"), line(1518, 07, 05, 00, 13, "wakes up"), line(1518, 07, 05, 00, 39, "falls asleep"), line(1518, 07, 05, 00, 51, "wakes up"), line(1518, 07, 05, 23, 58, "Guard #3361 begins shift"), line(1518, 07, 06, 00, 46, "falls asleep"), line(1518, 07, 06, 00, 59, "wakes up"), line(1518, 07, 07, 00, 02, "Guard #2099 begins shift"), line(1518, 07, 07, 00, 29, "falls asleep"), line(1518, 07, 07, 00, 34, "wakes up"), line(1518, 07, 07, 23, 57, "Guard #983 begins shift"), line(1518, 07, 08, 00, 36, "falls asleep"), line(1518, 07, 08, 00, 37, "wakes up"), line(1518, 07, 08, 00, 45, "falls asleep"), line(1518, 07, 08, 00, 59, "wakes up"), line(1518, 07, 09, 00, 00, "Guard #3361 begins shift"), line(1518, 07, 09, 00, 38, "falls asleep"), line(1518, 07, 09, 00, 45, "wakes up"), line(1518, 07, 09, 00, 53, "falls asleep"), line(1518, 07, 09, 00, 57, "wakes up"), line(1518, 07, 09, 23, 59, "Guard #3499 begins shift"), line(1518, 07, 10, 00, 22, "falls asleep"), line(1518, 07, 10, 00, 50, "wakes up"), line(1518, 07, 11, 00, 04, "Guard #3559 begins shift"), line(1518, 07, 11, 00, 14, "falls asleep"), line(1518, 07, 11, 00, 49, "wakes up"), line(1518, 07, 11, 00, 55, "falls asleep"), line(1518, 07, 11, 00, 56, "wakes up"), line(1518, 07, 11, 23, 57, "Guard #2617 begins shift"), line(1518, 07, 12, 00, 29, "falls asleep"), line(1518, 07, 12, 00, 37, "wakes up"), line(1518, 07, 12, 23, 50, "Guard #2099 begins shift"), line(1518, 07, 13, 00, 01, "falls asleep"), line(1518, 07, 13, 00, 32, "wakes up"), line(1518, 07, 14, 00, 04, "Guard #2579 begins shift"), line(1518, 07, 14, 23, 57, "Guard #2617 begins shift"), line(1518, 07, 15, 00, 38, "falls asleep"), line(1518, 07, 15, 00, 53, "wakes up"), line(1518, 07, 15, 00, 57, "falls asleep"), line(1518, 07, 15, 00, 59, "wakes up"), line(1518, 07, 15, 23, 57, "Guard #2657 begins shift"), line(1518, 07, 16, 00, 09, "falls asleep"), line(1518, 07, 16, 00, 20, "wakes up"), line(1518, 07, 16, 00, 42, "falls asleep"), line(1518, 07, 16, 00, 56, "wakes up"), line(1518, 07, 16, 23, 57, "Guard #983 begins shift"), line(1518, 07, 17, 00, 06, "falls asleep"), line(1518, 07, 17, 00, 41, "wakes up"), line(1518, 07, 17, 00, 45, "falls asleep"), line(1518, 07, 17, 00, 59, "wakes up"), line(1518, 07, 17, 23, 47, "Guard #1091 begins shift"), line(1518, 07, 18, 00, 03, "falls asleep"), line(1518, 07, 18, 00, 18, "wakes up"), line(1518, 07, 18, 23, 53, "Guard #3499 begins shift"), line(1518, 07, 19, 00, 02, "falls asleep"), line(1518, 07, 19, 00, 43, "wakes up"), line(1518, 07, 20, 00, 00, "Guard #241 begins shift"), line(1518, 07, 20, 00, 13, "falls asleep"), line(1518, 07, 20, 00, 30, "wakes up"), line(1518, 07, 21, 00, 00, "Guard #919 begins shift"), line(1518, 07, 21, 00, 17, "falls asleep"), line(1518, 07, 21, 00, 31, "wakes up"), line(1518, 07, 21, 23, 47, "Guard #2099 begins shift"), line(1518, 07, 22, 00, 01, "falls asleep"), line(1518, 07, 22, 00, 23, "wakes up"), line(1518, 07, 22, 00, 35, "falls asleep"), line(1518, 07, 22, 00, 47, "wakes up"), line(1518, 07, 23, 00, 04, "Guard #2617 begins shift"), line(1518, 07, 23, 00, 33, "falls asleep"), line(1518, 07, 23, 00, 52, "wakes up"), line(1518, 07, 24, 00, 03, "Guard #823 begins shift"), line(1518, 07, 25, 00, 03, "Guard #1033 begins shift"), line(1518, 07, 25, 00, 29, "falls asleep"), line(1518, 07, 25, 00, 45, "wakes up"), line(1518, 07, 25, 00, 49, "falls asleep"), line(1518, 07, 25, 00, 57, "wakes up"), line(1518, 07, 26, 00, 00, "Guard #3499 begins shift"), line(1518, 07, 26, 00, 38, "falls asleep"), line(1518, 07, 26, 00, 43, "wakes up"), line(1518, 07, 26, 00, 50, "falls asleep"), line(1518, 07, 26, 00, 51, "wakes up"), line(1518, 07, 26, 23, 57, "Guard #1867 begins shift"), line(1518, 07, 27, 23, 50, "Guard #2099 begins shift"), line(1518, 07, 28, 00, 04, "falls asleep"), line(1518, 07, 28, 00, 41, "wakes up"), line(1518, 07, 29, 00, 00, "Guard #1811 begins shift"), line(1518, 07, 29, 00, 40, "falls asleep"), line(1518, 07, 29, 00, 50, "wakes up"), line(1518, 07, 29, 00, 53, "falls asleep"), line(1518, 07, 29, 00, 59, "wakes up"), line(1518, 07, 30, 00, 04, "Guard #3109 begins shift"), line(1518, 07, 30, 00, 06, "falls asleep"), line(1518, 07, 30, 00, 22, "wakes up"), line(1518, 07, 30, 00, 30, "falls asleep"), line(1518, 07, 30, 00, 37, "wakes up"), line(1518, 07, 30, 00, 43, "falls asleep"), line(1518, 07, 30, 00, 55, "wakes up"), line(1518, 07, 31, 00, 01, "Guard #3499 begins shift"), line(1518, 07, 31, 00, 10, "falls asleep"), line(1518, 07, 31, 00, 34, "wakes up"), line(1518, 07, 31, 00, 41, "falls asleep"), line(1518, 07, 31, 00, 44, "wakes up"), line(1518, 08, 01, 00, 03, "Guard #1291 begins shift"), line(1518, 08, 01, 00, 21, "falls asleep"), line(1518, 08, 01, 00, 52, "wakes up"), line(1518, 08, 01, 23, 56, "Guard #1033 begins shift"), line(1518, 08, 02, 00, 18, "falls asleep"), line(1518, 08, 02, 00, 38, "wakes up"), line(1518, 08, 02, 23, 59, "Guard #3361 begins shift"), line(1518, 08, 03, 00, 49, "falls asleep"), line(1518, 08, 03, 00, 59, "wakes up"), line(1518, 08, 04, 00, 00, "Guard #1033 begins shift"), line(1518, 08, 04, 00, 33, "falls asleep"), line(1518, 08, 04, 00, 45, "wakes up"), line(1518, 08, 04, 00, 57, "falls asleep"), line(1518, 08, 04, 00, 59, "wakes up"), line(1518, 08, 04, 23, 53, "Guard #1091 begins shift"), line(1518, 08, 05, 00, 01, "falls asleep"), line(1518, 08, 05, 00, 27, "wakes up"), line(1518, 08, 05, 23, 52, "Guard #3449 begins shift"), line(1518, 08, 06, 00, 00, "falls asleep"), line(1518, 08, 06, 00, 11, "wakes up"), line(1518, 08, 06, 00, 20, "falls asleep"), line(1518, 08, 06, 00, 42, "wakes up"), line(1518, 08, 06, 00, 51, "falls asleep"), line(1518, 08, 06, 00, 55, "wakes up"), line(1518, 08, 07, 00, 00, "Guard #1499 begins shift"), line(1518, 08, 07, 00, 27, "falls asleep"), line(1518, 08, 07, 00, 55, "wakes up"), line(1518, 08, 08, 00, 04, "Guard #241 begins shift"), line(1518, 08, 08, 00, 11, "falls asleep"), line(1518, 08, 08, 00, 28, "wakes up"), line(1518, 08, 08, 00, 41, "falls asleep"), line(1518, 08, 08, 00, 54, "wakes up"), line(1518, 08, 09, 00, 03, "Guard #3109 begins shift"), line(1518, 08, 09, 00, 28, "falls asleep"), line(1518, 08, 09, 00, 34, "wakes up"), line(1518, 08, 09, 00, 38, "falls asleep"), line(1518, 08, 09, 00, 45, "wakes up"), line(1518, 08, 10, 00, 00, "Guard #3109 begins shift"), line(1518, 08, 10, 00, 12, "falls asleep"), line(1518, 08, 10, 00, 38, "wakes up"), line(1518, 08, 10, 00, 45, "falls asleep"), line(1518, 08, 10, 00, 49, "wakes up"), line(1518, 08, 10, 23, 57, "Guard #3203 begins shift"), line(1518, 08, 11, 00, 19, "falls asleep"), line(1518, 08, 11, 00, 32, "wakes up"), line(1518, 08, 11, 00, 48, "falls asleep"), line(1518, 08, 11, 00, 52, "wakes up"), line(1518, 08, 12, 00, 04, "Guard #2657 begins shift"), line(1518, 08, 12, 00, 13, "falls asleep"), line(1518, 08, 12, 00, 58, "wakes up"), line(1518, 08, 13, 00, 04, "Guard #2099 begins shift"), line(1518, 08, 13, 00, 21, "falls asleep"), line(1518, 08, 13, 00, 59, "wakes up"), line(1518, 08, 13, 23, 50, "Guard #2099 begins shift"), line(1518, 08, 14, 00, 01, "falls asleep"), line(1518, 08, 14, 00, 39, "wakes up"), line(1518, 08, 15, 00, 00, "Guard #823 begins shift"), line(1518, 08, 16, 00, 00, "Guard #3361 begins shift"), line(1518, 08, 16, 00, 29, "falls asleep"), line(1518, 08, 16, 00, 36, "wakes up"), line(1518, 08, 16, 23, 46, "Guard #313 begins shift"), line(1518, 08, 17, 00, 02, "falls asleep"), line(1518, 08, 17, 00, 28, "wakes up"), line(1518, 08, 17, 00, 43, "falls asleep"), line(1518, 08, 17, 00, 48, "wakes up"), line(1518, 08, 18, 00, 01, "Guard #241 begins shift"), line(1518, 08, 18, 00, 29, "falls asleep"), line(1518, 08, 18, 00, 35, "wakes up"), line(1518, 08, 19, 00, 02, "Guard #1033 begins shift"), line(1518, 08, 19, 00, 32, "falls asleep"), line(1518, 08, 19, 00, 50, "wakes up"), line(1518, 08, 20, 00, 03, "Guard #3499 begins shift"), line(1518, 08, 20, 00, 37, "falls asleep"), line(1518, 08, 20, 00, 42, "wakes up"), line(1518, 08, 20, 23, 48, "Guard #3559 begins shift"), line(1518, 08, 21, 00, 04, "falls asleep"), line(1518, 08, 21, 00, 53, "wakes up"), line(1518, 08, 21, 23, 58, "Guard #313 begins shift"), line(1518, 08, 22, 00, 11, "falls asleep"), line(1518, 08, 22, 00, 12, "wakes up"), line(1518, 08, 22, 00, 31, "falls asleep"), line(1518, 08, 22, 00, 33, "wakes up"), line(1518, 08, 23, 00, 04, "Guard #3203 begins shift"), line(1518, 08, 23, 00, 36, "falls asleep"), line(1518, 08, 23, 00, 59, "wakes up"), line(1518, 08, 24, 00, 01, "Guard #2657 begins shift"), line(1518, 08, 24, 00, 16, "falls asleep"), line(1518, 08, 24, 00, 35, "wakes up"), line(1518, 08, 25, 00, 02, "Guard #1291 begins shift"), line(1518, 08, 25, 00, 11, "falls asleep"), line(1518, 08, 25, 00, 18, "wakes up"), line(1518, 08, 25, 00, 22, "falls asleep"), line(1518, 08, 25, 00, 31, "wakes up"), line(1518, 08, 25, 00, 35, "falls asleep"), line(1518, 08, 25, 00, 45, "wakes up"), line(1518, 08, 25, 23, 58, "Guard #1033 begins shift"), line(1518, 08, 26, 00, 15, "falls asleep"), line(1518, 08, 26, 00, 35, "wakes up"), line(1518, 08, 27, 00, 00, "Guard #1291 begins shift"), line(1518, 08, 27, 00, 31, "falls asleep"), line(1518, 08, 27, 00, 36, "wakes up"), line(1518, 08, 27, 00, 47, "falls asleep"), line(1518, 08, 27, 00, 54, "wakes up"), line(1518, 08, 28, 00, 03, "Guard #983 begins shift"), line(1518, 08, 28, 00, 45, "falls asleep"), line(1518, 08, 28, 00, 46, "wakes up"), line(1518, 08, 29, 00, 02, "Guard #2657 begins shift"), line(1518, 08, 29, 00, 24, "falls asleep"), line(1518, 08, 29, 00, 29, "wakes up"), line(1518, 08, 29, 00, 44, "falls asleep"), line(1518, 08, 29, 00, 59, "wakes up"), line(1518, 08, 30, 00, 03, "Guard #983 begins shift"), line(1518, 08, 30, 00, 26, "falls asleep"), line(1518, 08, 30, 00, 58, "wakes up"), line(1518, 08, 31, 00, 01, "Guard #2411 begins shift"), line(1518, 08, 31, 00, 22, "falls asleep"), line(1518, 08, 31, 00, 33, "wakes up"), line(1518, 08, 31, 00, 47, "falls asleep"), line(1518, 08, 31, 00, 58, "wakes up"), line(1518, 09, 01, 00, 02, "Guard #3109 begins shift"), line(1518, 09, 01, 00, 45, "falls asleep"), line(1518, 09, 01, 00, 51, "wakes up"), line(1518, 09, 01, 23, 57, "Guard #2617 begins shift"), line(1518, 09, 02, 00, 27, "falls asleep"), line(1518, 09, 02, 00, 49, "wakes up"), line(1518, 09, 02, 00, 56, "falls asleep"), line(1518, 09, 02, 00, 57, "wakes up"), line(1518, 09, 02, 23, 56, "Guard #3203 begins shift"), line(1518, 09, 03, 00, 20, "falls asleep"), line(1518, 09, 03, 00, 56, "wakes up"), line(1518, 09, 04, 00, 03, "Guard #2099 begins shift"), line(1518, 09, 04, 00, 33, "falls asleep"), line(1518, 09, 04, 00, 41, "wakes up"), line(1518, 09, 04, 23, 46, "Guard #2657 begins shift"), line(1518, 09, 05, 00, 04, "falls asleep"), line(1518, 09, 05, 00, 51, "wakes up"), line(1518, 09, 05, 23, 50, "Guard #3559 begins shift"), line(1518, 09, 06, 00, 03, "falls asleep"), line(1518, 09, 06, 00, 39, "wakes up"), line(1518, 09, 07, 00, 01, "Guard #3499 begins shift"), line(1518, 09, 07, 00, 36, "falls asleep"), line(1518, 09, 07, 00, 41, "wakes up"), line(1518, 09, 08, 00, 04, "Guard #1291 begins shift"), line(1518, 09, 08, 00, 25, "falls asleep"), line(1518, 09, 08, 00, 26, "wakes up"), line(1518, 09, 09, 00, 02, "Guard #1091 begins shift"), line(1518, 09, 09, 00, 06, "falls asleep"), line(1518, 09, 09, 00, 30, "wakes up"), line(1518, 09, 09, 23, 58, "Guard #241 begins shift"), line(1518, 09, 10, 00, 31, "falls asleep"), line(1518, 09, 10, 00, 34, "wakes up"), line(1518, 09, 10, 00, 39, "falls asleep"), line(1518, 09, 10, 00, 56, "wakes up"), line(1518, 09, 10, 23, 59, "Guard #2411 begins shift"), line(1518, 09, 11, 00, 20, "falls asleep"), line(1518, 09, 11, 00, 41, "wakes up"), line(1518, 09, 11, 23, 57, "Guard #73 begins shift"), line(1518, 09, 12, 00, 21, "falls asleep"), line(1518, 09, 12, 00, 29, "wakes up"), line(1518, 09, 12, 00, 48, "falls asleep"), line(1518, 09, 12, 00, 59, "wakes up"), line(1518, 09, 13, 00, 01, "Guard #2099 begins shift"), line(1518, 09, 13, 00, 21, "falls asleep"), line(1518, 09, 13, 00, 43, "wakes up"), line(1518, 09, 13, 00, 47, "falls asleep"), line(1518, 09, 13, 00, 56, "wakes up"), line(1518, 09, 13, 23, 56, "Guard #1499 begins shift"), line(1518, 09, 14, 00, 10, "falls asleep"), line(1518, 09, 14, 00, 56, "wakes up"), line(1518, 09, 15, 00, 03, "Guard #313 begins shift"), line(1518, 09, 15, 00, 38, "falls asleep"), line(1518, 09, 15, 00, 59, "wakes up"), line(1518, 09, 15, 23, 58, "Guard #2617 begins shift"), line(1518, 09, 16, 00, 19, "falls asleep"), line(1518, 09, 16, 00, 34, "wakes up"), line(1518, 09, 17, 00, 03, "Guard #313 begins shift"), line(1518, 09, 17, 00, 21, "falls asleep"), line(1518, 09, 17, 00, 59, "wakes up"), line(1518, 09, 17, 23, 59, "Guard #1291 begins shift"), line(1518, 09, 18, 00, 15, "falls asleep"), line(1518, 09, 18, 00, 57, "wakes up"), line(1518, 09, 18, 23, 48, "Guard #3559 begins shift"), line(1518, 09, 19, 00, 05, "falls asleep"), line(1518, 09, 19, 00, 48, "wakes up"), line(1518, 09, 19, 23, 56, "Guard #3109 begins shift"), line(1518, 09, 20, 00, 32, "falls asleep"), line(1518, 09, 20, 00, 43, "wakes up"), line(1518, 09, 20, 00, 55, "falls asleep"), line(1518, 09, 20, 00, 58, "wakes up"), line(1518, 09, 21, 00, 02, "Guard #2099 begins shift"), line(1518, 09, 21, 00, 28, "falls asleep"), line(1518, 09, 21, 00, 42, "wakes up"), line(1518, 09, 22, 00, 03, "Guard #3559 begins shift"), line(1518, 09, 22, 00, 08, "falls asleep"), line(1518, 09, 22, 00, 19, "wakes up"), line(1518, 09, 22, 23, 59, "Guard #2657 begins shift"), line(1518, 09, 23, 00, 06, "falls asleep"), line(1518, 09, 23, 00, 58, "wakes up"), line(1518, 09, 24, 00, 01, "Guard #241 begins shift"), line(1518, 09, 24, 00, 12, "falls asleep"), line(1518, 09, 24, 00, 14, "wakes up"), line(1518, 09, 24, 00, 32, "falls asleep"), line(1518, 09, 24, 00, 53, "wakes up"), line(1518, 09, 24, 00, 56, "falls asleep"), line(1518, 09, 24, 00, 59, "wakes up"), line(1518, 09, 25, 00, 00, "Guard #1091 begins shift"), line(1518, 09, 25, 00, 25, "falls asleep"), line(1518, 09, 25, 00, 34, "wakes up"), line(1518, 09, 25, 00, 49, "falls asleep"), line(1518, 09, 25, 00, 55, "wakes up"), line(1518, 09, 25, 23, 56, "Guard #3361 begins shift"), line(1518, 09, 26, 00, 20, "falls asleep"), line(1518, 09, 26, 00, 50, "wakes up"), line(1518, 09, 26, 23, 59, "Guard #3109 begins shift"), line(1518, 09, 27, 00, 27, "falls asleep"), line(1518, 09, 27, 00, 40, "wakes up"), line(1518, 09, 28, 00, 04, "Guard #3559 begins shift"), line(1518, 09, 28, 00, 18, "falls asleep"), line(1518, 09, 28, 00, 48, "wakes up"), line(1518, 09, 28, 23, 56, "Guard #1811 begins shift"), line(1518, 09, 29, 00, 22, "falls asleep"), line(1518, 09, 29, 00, 42, "wakes up"), line(1518, 09, 30, 00, 00, "Guard #3499 begins shift"), line(1518, 09, 30, 00, 39, "falls asleep"), line(1518, 09, 30, 00, 44, "wakes up"), line(1518, 09, 30, 00, 57, "falls asleep"), line(1518, 09, 30, 00, 58, "wakes up"), line(1518, 09, 30, 23, 50, "Guard #313 begins shift"), line(1518, 10, 01, 00, 05, "falls asleep"), line(1518, 10, 01, 00, 20, "wakes up"), line(1518, 10, 01, 23, 58, "Guard #2411 begins shift"), line(1518, 10, 02, 00, 15, "falls asleep"), line(1518, 10, 02, 00, 23, "wakes up"), line(1518, 10, 03, 00, 00, "Guard #313 begins shift"), line(1518, 10, 03, 00, 29, "falls asleep"), line(1518, 10, 03, 00, 32, "wakes up"), line(1518, 10, 03, 00, 39, "falls asleep"), line(1518, 10, 03, 00, 47, "wakes up"), line(1518, 10, 03, 00, 50, "falls asleep"), line(1518, 10, 03, 00, 59, "wakes up"), line(1518, 10, 03, 23, 59, "Guard #2657 begins shift"), line(1518, 10, 04, 00, 33, "falls asleep"), line(1518, 10, 04, 00, 40, "wakes up"), line(1518, 10, 04, 00, 49, "falls asleep"), line(1518, 10, 04, 00, 53, "wakes up"), line(1518, 10, 05, 00, 03, "Guard #3499 begins shift"), line(1518, 10, 05, 00, 15, "falls asleep"), line(1518, 10, 05, 00, 53, "wakes up"), line(1518, 10, 06, 00, 03, "Guard #3499 begins shift"), line(1518, 10, 06, 00, 36, "falls asleep"), line(1518, 10, 06, 00, 55, "wakes up"), line(1518, 10, 07, 00, 00, "Guard #1811 begins shift"), line(1518, 10, 07, 00, 32, "falls asleep"), line(1518, 10, 07, 00, 44, "wakes up"), line(1518, 10, 07, 23, 59, "Guard #2411 begins shift"), line(1518, 10, 08, 00, 13, "falls asleep"), line(1518, 10, 08, 00, 47, "wakes up"), line(1518, 10, 08, 00, 53, "falls asleep"), line(1518, 10, 08, 00, 56, "wakes up"), line(1518, 10, 08, 23, 58, "Guard #1811 begins shift"), line(1518, 10, 09, 00, 10, "falls asleep"), line(1518, 10, 09, 00, 59, "wakes up"), line(1518, 10, 09, 23, 56, "Guard #3559 begins shift"), line(1518, 10, 10, 00, 25, "falls asleep"), line(1518, 10, 10, 00, 49, "wakes up"), line(1518, 10, 11, 00, 02, "Guard #2657 begins shift"), line(1518, 10, 11, 00, 29, "falls asleep"), line(1518, 10, 11, 00, 41, "wakes up"), line(1518, 10, 11, 23, 58, "Guard #2099 begins shift"), line(1518, 10, 12, 00, 26, "falls asleep"), line(1518, 10, 12, 00, 38, "wakes up"), line(1518, 10, 13, 00, 04, "Guard #1091 begins shift"), line(1518, 10, 13, 00, 43, "falls asleep"), line(1518, 10, 13, 00, 55, "wakes up"), line(1518, 10, 13, 23, 52, "Guard #2657 begins shift"), line(1518, 10, 14, 00, 05, "falls asleep"), line(1518, 10, 14, 00, 44, "wakes up"), line(1518, 10, 14, 23, 56, "Guard #2099 begins shift"), line(1518, 10, 15, 00, 24, "falls asleep"), line(1518, 10, 15, 00, 40, "wakes up"), line(1518, 10, 15, 00, 46, "falls asleep"), line(1518, 10, 15, 00, 47, "wakes up"), line(1518, 10, 16, 00, 00, "Guard #2657 begins shift"), line(1518, 10, 16, 00, 45, "falls asleep"), line(1518, 10, 16, 00, 50, "wakes up"), line(1518, 10, 17, 00, 01, "Guard #3203 begins shift"), line(1518, 10, 17, 00, 26, "falls asleep"), line(1518, 10, 17, 00, 42, "wakes up"), line(1518, 10, 18, 00, 02, "Guard #2657 begins shift"), line(1518, 10, 18, 00, 15, "falls asleep"), line(1518, 10, 18, 00, 38, "wakes up"), line(1518, 10, 18, 00, 42, "falls asleep"), line(1518, 10, 18, 00, 48, "wakes up"), line(1518, 10, 19, 00, 04, "Guard #3203 begins shift"), line(1518, 10, 19, 00, 21, "falls asleep"), line(1518, 10, 19, 00, 48, "wakes up"), line(1518, 10, 20, 00, 04, "Guard #3203 begins shift"), line(1518, 10, 20, 00, 23, "falls asleep"), line(1518, 10, 20, 00, 36, "wakes up"), line(1518, 10, 20, 00, 52, "falls asleep"), line(1518, 10, 20, 00, 53, "wakes up"), line(1518, 10, 21, 00, 00, "Guard #983 begins shift"), line(1518, 10, 21, 00, 15, "falls asleep"), line(1518, 10, 21, 00, 33, "wakes up"), line(1518, 10, 21, 23, 57, "Guard #919 begins shift"), line(1518, 10, 22, 00, 33, "falls asleep"), line(1518, 10, 22, 00, 36, "wakes up"), line(1518, 10, 22, 23, 52, "Guard #313 begins shift"), line(1518, 10, 23, 00, 04, "falls asleep"), line(1518, 10, 23, 00, 08, "wakes up"), line(1518, 10, 24, 00, 01, "Guard #3109 begins shift"), line(1518, 10, 24, 00, 26, "falls asleep"), line(1518, 10, 24, 00, 29, "wakes up"), line(1518, 10, 24, 00, 43, "falls asleep"), line(1518, 10, 24, 00, 47, "wakes up"), line(1518, 10, 24, 23, 56, "Guard #2657 begins shift"), line(1518, 10, 25, 00, 08, "falls asleep"), line(1518, 10, 25, 00, 54, "wakes up"), line(1518, 10, 26, 00, 02, "Guard #1291 begins shift"), line(1518, 10, 26, 00, 09, "falls asleep"), line(1518, 10, 26, 00, 45, "wakes up"), line(1518, 10, 27, 00, 01, "Guard #1291 begins shift"), line(1518, 10, 27, 00, 08, "falls asleep"), line(1518, 10, 27, 00, 53, "wakes up"), line(1518, 10, 27, 23, 59, "Guard #2617 begins shift"), line(1518, 10, 28, 00, 08, "falls asleep"), line(1518, 10, 28, 00, 36, "wakes up"), line(1518, 10, 28, 00, 57, "falls asleep"), line(1518, 10, 28, 00, 58, "wakes up"), line(1518, 10, 28, 23, 58, "Guard #241 begins shift"), line(1518, 10, 29, 00, 16, "falls asleep"), line(1518, 10, 29, 00, 49, "wakes up"), line(1518, 10, 29, 23, 50, "Guard #983 begins shift"), line(1518, 10, 30, 00, 05, "falls asleep"), line(1518, 10, 30, 00, 07, "wakes up"), line(1518, 10, 31, 00, 00, "Guard #919 begins shift"), line(1518, 10, 31, 00, 09, "falls asleep"), line(1518, 10, 31, 00, 11, "wakes up"), line(1518, 10, 31, 00, 49, "falls asleep"), line(1518, 10, 31, 00, 56, "wakes up"), line(1518, 10, 31, 23, 57, "Guard #983 begins shift"), line(1518, 11, 01, 00, 21, "falls asleep"), line(1518, 11, 01, 00, 31, "wakes up"), line(1518, 11, 01, 00, 37, "falls asleep"), line(1518, 11, 01, 00, 46, "wakes up"), line(1518, 11, 01, 00, 53, "falls asleep"), line(1518, 11, 01, 00, 57, "wakes up"), line(1518, 11, 02, 00, 03, "Guard #3559 begins shift"), line(1518, 11, 02, 00, 14, "falls asleep"), line(1518, 11, 02, 00, 29, "wakes up"), line(1518, 11, 02, 23, 59, "Guard #73 begins shift"), line(1518, 11, 03, 00, 53, "falls asleep"), line(1518, 11, 03, 00, 55, "wakes up"), line(1518, 11, 03, 23, 56, "Guard #1291 begins shift"), line(1518, 11, 04, 00, 22, "falls asleep"), line(1518, 11, 04, 00, 57, "wakes up"), line(1518, 11, 04, 23, 56, "Guard #3499 begins shift"), line(1518, 11, 05, 00, 29, "falls asleep"), line(1518, 11, 05, 00, 37, "wakes up"), line(1518, 11, 05, 23, 48, "Guard #73 begins shift"), line(1518, 11, 06, 00, 04, "falls asleep"), line(1518, 11, 06, 00, 22, "wakes up"), line(1518, 11, 07, 00, 01, "Guard #73 begins shift"), line(1518, 11, 07, 00, 17, "falls asleep"), line(1518, 11, 07, 00, 29, "wakes up"), line(1518, 11, 07, 23, 52, "Guard #3559 begins shift"), line(1518, 11, 08, 00, 00, "falls asleep"), line(1518, 11, 08, 00, 13, "wakes up"), line(1518, 11, 08, 00, 20, "falls asleep"), line(1518, 11, 08, 00, 51, "wakes up"), line(1518, 11, 08, 23, 58, "Guard #2617 begins shift"), line(1518, 11, 09, 00, 35, "falls asleep"), line(1518, 11, 09, 00, 39, "wakes up"), line(1518, 11, 09, 23, 57, "Guard #2099 begins shift"), line(1518, 11, 10, 00, 34, "falls asleep"), line(1518, 11, 10, 00, 35, "wakes up"), line(1518, 11, 10, 00, 50, "falls asleep"), line(1518, 11, 10, 00, 53, "wakes up"), line(1518, 11, 10, 00, 57, "falls asleep"), line(1518, 11, 10, 00, 58, "wakes up"), line(1518, 11, 10, 23, 49, "Guard #241 begins shift"), line(1518, 11, 11, 00, 04, "falls asleep"), line(1518, 11, 11, 00, 39, "wakes up"), line(1518, 11, 12, 00, 04, "Guard #2411 begins shift"), line(1518, 11, 12, 00, 37, "falls asleep"), line(1518, 11, 12, 00, 42, "wakes up"), line(1518, 11, 12, 23, 49, "Guard #3449 begins shift"), line(1518, 11, 13, 00, 05, "falls asleep"), line(1518, 11, 13, 00, 27, "wakes up"), line(1518, 11, 13, 23, 49, "Guard #1811 begins shift"), line(1518, 11, 14, 00, 01, "falls asleep"), line(1518, 11, 14, 00, 31, "wakes up"), line(1518, 11, 14, 23, 47, "Guard #1291 begins shift"), line(1518, 11, 15, 00, 05, "falls asleep"), line(1518, 11, 15, 00, 57, "wakes up"), line(1518, 11, 15, 23, 59, "Guard #3109 begins shift"), line(1518, 11, 16, 00, 22, "falls asleep"), line(1518, 11, 16, 00, 47, "wakes up"), line(1518, 11, 16, 23, 56, "Guard #919 begins shift"), line(1518, 11, 17, 00, 48, "falls asleep"), line(1518, 11, 17, 00, 49, "wakes up"), line(1518, 11, 17, 00, 56, "falls asleep"), line(1518, 11, 17, 00, 58, "wakes up"), line(1518, 11, 17, 23, 59, "Guard #1811 begins shift"), line(1518, 11, 18, 00, 26, "falls asleep"), line(1518, 11, 18, 00, 32, "wakes up"), line(1518, 11, 19, 00, 02, "Guard #3109 begins shift"), line(1518, 11, 19, 00, 50, "falls asleep"), line(1518, 11, 19, 00, 57, "wakes up"), line(1518, 11, 19, 23, 56, "Guard #2617 begins shift"), line(1518, 11, 20, 00, 09, "falls asleep"), line(1518, 11, 20, 00, 26, "wakes up"), line(1518, 11, 20, 00, 46, "falls asleep"), line(1518, 11, 20, 00, 54, "wakes up"), line(1518, 11, 21, 00, 04, "Guard #3499 begins shift"), line(1518, 11, 21, 00, 36, "falls asleep"), line(1518, 11, 21, 00, 48, "wakes up"), line(1518, 11, 22, 00, 02, "Guard #3499 begins shift"), line(1518, 11, 22, 00, 39, "falls asleep"), line(1518, 11, 22, 00, 40, "wakes up"), line(1518, 11, 22, 23, 56, "Guard #3499 begins shift"), line(1518, 11, 23, 00, 28, "falls asleep"), line(1518, 11, 23, 00, 42, "wakes up"), }; };
2018/day_04_1.zig
const c = @import("../../c_global.zig").c_imp; const std = @import("std"); // dross-zig const tx = @import("../renderer/texture.zig"); const Texture = tx.Texture; const fnt = @import("../renderer/font/font.zig"); const Font = fnt.Font; const fs = @import("../utils/file_loader.zig"); // ------------------------------------------------ // ----------------------------------------- // - ResourceHandler - // ----------------------------------------- /// The allocator used by the ResourceHandler. var resource_allocator: *std.mem.Allocator = undefined; var texture_map: std.StringHashMap(*Texture) = undefined; var font_map: std.StringHashMap(*Font) = undefined; pub const ResourceHandler = struct { /// Builds the ResourceHandler and allocates and required memory. /// Comment: The ResourceHandler will be owned by the engine, and /// all resources allocated by the resource handler are owned /// by the ResourceHandler. pub fn new(allocator: *std.mem.Allocator) void { resource_allocator = allocator; // Initialize the cache maps texture_map = std.StringHashMap(*Texture).init(allocator); font_map = std.StringHashMap(*Font).init(allocator); } /// Frees the ResourceHandler and deallocates and required memory. pub fn free() void { var texture_iter = texture_map.iterator(); var font_iter = font_map.iterator(); while (texture_iter.next()) |entry| { unloadTexture(entry.key); } while (font_iter.next()) |entry| { unloadFont(entry.key); } font_map.deinit(); texture_map.deinit(); } /// Loads a texture at the given `path` (relative to build/executable). /// Comment: All resources allocated by the resource handler are owned /// by the ResourceHandler. The returned Texture pointer is owned and /// released by the ResourceHandler. pub fn loadTexture(name: []const u8, path: []const u8) !?*Texture { var texture: *Texture = Texture.new(resource_allocator, name, path) catch |err| { std.debug.print("[Resource Handler]: Error occurred when loading texture({s})! {}\n", .{ path, err }); return err; }; try texture_map.put(name, texture); return texture; } /// Unloads a texture with the name `name`, if found in map. /// Will be called automatically at end of application, but /// can be used when switching scenes. pub fn unloadTexture(name: []const u8) void { var texture_entry = texture_map.remove(name); Texture.free(resource_allocator, texture_entry.?.value); } /// Loads a font at the given `path` (relative to build/executable). /// Comment: All resources allocated by the resource handler are owned /// by the ResourceHandler. The returned font pointer is owned and /// released by the ResourceHandler. pub fn loadFont(name: []const u8, path: [*c]const u8) ?*Font { var font: *Font = Font.new(resource_allocator, path) catch |err| { std.debug.print("[Resource Handler]: Error occurred when loading font({s})! {}\n", .{ path, err }); return null; }; font_map.put(name, font) catch |err| { std.debug.print("[Resource Handler]: Error occurred while adding font({s}) to map!\n", .{path}); return null; }; return font; } /// Unloads a font with the name `name`, if found in map. /// Will be called automatically at the end of the application's /// lifetime, but can be used anytime. /// NOTE(devon): Be careful of dangling pointers. pub fn unloadFont(name: []const u8) void { var font_entry = font_map.remove(name); Font.free(resource_allocator, font_entry.?.value); } };
src/core/resource_handler.zig
const std = @import("std"); const assert = std.debug.assert; const c = @import("c.zig").c; const window = &@import("Window.zig").window; var key_callback: ?fn (i32, i32, i32, i32) void = null; fn key_callback_f(w: ?*c.GLFWwindow, key: c_int, scancode: c_int, action: c_int, mods: c_int) callconv(.C) void { if (key_callback != null) { (key_callback.?)(key, scancode, action, mods); } } pub fn setKeyCallback(clbk: fn (i32, i32, i32, i32) void) void { key_callback = clbk; _ = c.glfwSetKeyCallback(window.*, key_callback_f); } pub fn getMousePosition() [2]i32 { var xpos: f64 = 0.0; var ypos: f64 = 0.0; c.glfwGetCursorPos(window.*, &xpos, &ypos); return [2]i32{ @floatToInt(i32, xpos), @floatToInt(i32, ypos), }; } var mouse_button_callback: ?fn (i32, i32, i32) void = null; fn mouse_button_callback_f(w: ?*c.GLFWwindow, button: c_int, action: c_int, mods: c_int) callconv(.C) void { if (mouse_button_callback != null) { (mouse_button_callback.?)(button, action, mods); } } pub fn setMouseButtonCallback(clbk: fn (i32, i32, i32) void) void { mouse_button_callback = clbk; _ = c.glfwSetMouseButtonCallback(window.*, mouse_button_callback_f); } var mouse_scroll_callback: ?fn (i32, i32) void = null; fn mouse_scroll_callback_f(w: ?*c.GLFWwindow, x: f64, y: f64) callconv(.C) void { if (mouse_scroll_callback != null) { (mouse_scroll_callback.?)(@floatToInt(i32, x), @floatToInt(i32, y)); } } pub fn setMouseScrollCallback(clbk: fn (i32, i32) void) void { mouse_scroll_callback = clbk; _ = c.glfwSetScrollCallback(window.*, mouse_scroll_callback_f); } pub fn setCursorEnabled(enabled: bool) void { if (enabled) { c.glfwSetInputMode(window.*, c.GLFW_CURSOR, c.GLFW_CURSOR_NORMAL); } else { c.glfwSetInputMode(window.*, c.GLFW_CURSOR, c.GLFW_CURSOR_DISABLED); } } pub fn isKeyDown(key: c_int) bool { return c.glfwGetKey(window.*, key) == c.GLFW_PRESS; }
src/WindowGraphicsInput/Input.zig
const std = @import("std"); const io = @import("io.zig"); allocator: *std.mem.Allocator, loop: *io.EventLoop, sigf: io.SignalFile, listener: io.Listener, quit: io.Flag, group: io.WaitGroup, const Server = @This(); pub fn init(allocator: *std.mem.Allocator, loop: *io.EventLoop) !Server { const sigf = try loop.signalOpen(&.{ .int, .hup }); errdefer sigf.close(); const addr = try std.net.Address.resolveIp("::", 8080); const listener = try loop.listen(addr, .{ .backlog = 100, .reuseaddr = true }); errdefer listener.close(); return Server{ .allocator = allocator, .loop = loop, .sigf = sigf, .listener = listener, .quit = loop.flag(), .group = loop.waitGroup(), }; } pub fn deinit(self: Server) void { self.listener.close(); self.sigf.close(); } pub fn mainLoop(self: *Server) !void { var sig_future = io.future(&async self.sigf.capture()); var sock_frame: @Frame(io.Listener.accept) = undefined; while (true) { sock_frame = async self.listener.accept(); var sock_future = io.future(&sock_frame); switch (self.loop.any(.{ .sig = &sig_future, .sock = &sock_future })) { .sig => |sig| { _ = try sig; break; }, .sock => |conn| { self.group.add(1); try self.loop.runDetached(self.allocator, clientTask, .{ self, try conn }); }, } } std.debug.assert(self.quit.set()); std.debug.print("Exiting\n", .{}); self.group.wait(); } fn clientTask(self: *Server, conn: io.Listener.Connection) void { defer self.group.done(); self.handleClient(conn) catch |err| { std.debug.print("Error in client '{}': {s}\n", .{ conn.addr, @errorName(err) }); if (@errorReturnTrace()) |trace| { std.debug.dumpStackTrace(trace.*); } }; } fn handleClient(self: *Server, conn: io.Listener.Connection) !void { defer conn.sock.close(); std.debug.print("{} connected\n", .{conn.addr}); defer std.debug.print("{} disconnected\n", .{conn.addr}); const r = std.io.bufferedReader(conn.sock.reader()).reader(); const w = conn.sock.writer(); var buf = std.ArrayList(u8).init(self.allocator); defer buf.deinit(); var read_frame: @Frame(@TypeOf(r).readUntilDelimiterArrayList) = undefined; while (true) { read_frame = async r.readUntilDelimiterArrayList(&buf, '\n', 1 << 20); var read_future = io.future(&read_frame); switch (self.loop.any(.{ .quit = &self.quit, .read = &read_future })) { .quit => return, .read => |res| { res catch |err| switch (err) { error.WouldBlock => unreachable, // Not a non-blocking socket error.EndOfStream => return, else => |e| return e, }; try buf.append('\n'); try w.writeAll(buf.items); }, } } }
src/Server.zig
const std = @import("std"); const opcode = @import("opcode.zig"); pub const Disassembler = struct { const InStream = std.io.InStream(std.os.File.ReadError); const OutStream = std.io.OutStream(std.os.File.WriteError); input: *InStream, output: *OutStream, buffer: ?u8, pub fn init(input: *InStream, output: *OutStream) Disassembler { return Disassembler{ .input = input, .output = output, .buffer = null, }; } pub fn disassemble(self: *Disassembler) !void { const byte = self.buffer orelse try self.input.readByte(); self.buffer = null; switch (byte) { @enumToInt(opcode.Opcode.NOP) => try self.output.print("nop\n"), @enumToInt(opcode.Opcode.LD_A_n) => try self.output.print("ld a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_B_n) => try self.output.print("ld b,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_C_n) => try self.output.print("ld c,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_D_n) => try self.output.print("ld d,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_E_n) => try self.output.print("ld e,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_H_n) => try self.output.print("ld h,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_L_n) => try self.output.print("ld l,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_A_A) => try self.output.print("ld a,a\n"), @enumToInt(opcode.Opcode.LD_A_B) => try self.output.print("ld a,b\n"), @enumToInt(opcode.Opcode.LD_A_C) => try self.output.print("ld a,c\n"), @enumToInt(opcode.Opcode.LD_A_D) => try self.output.print("ld a,d\n"), @enumToInt(opcode.Opcode.LD_A_E) => try self.output.print("ld a,e\n"), @enumToInt(opcode.Opcode.LD_A_H) => try self.output.print("ld a,h\n"), @enumToInt(opcode.Opcode.LD_A_L) => try self.output.print("ld a,l\n"), @enumToInt(opcode.Opcode.LD_A_HL) => try self.output.print("ld a,(hl)\n"), @enumToInt(opcode.Opcode.LD_B_B) => try self.output.print("ld b,b\n"), @enumToInt(opcode.Opcode.LD_B_C) => try self.output.print("ld b,c\n"), @enumToInt(opcode.Opcode.LD_B_D) => try self.output.print("ld b,d\n"), @enumToInt(opcode.Opcode.LD_B_E) => try self.output.print("ld b,e\n"), @enumToInt(opcode.Opcode.LD_B_H) => try self.output.print("ld b,h\n"), @enumToInt(opcode.Opcode.LD_B_L) => try self.output.print("ld b,l\n"), @enumToInt(opcode.Opcode.LD_B_HL) => try self.output.print("ld b,(hl)\n"), @enumToInt(opcode.Opcode.LD_C_B) => try self.output.print("ld c,b\n"), @enumToInt(opcode.Opcode.LD_C_C) => try self.output.print("ld c,c\n"), @enumToInt(opcode.Opcode.LD_C_D) => try self.output.print("ld c,d\n"), @enumToInt(opcode.Opcode.LD_C_E) => try self.output.print("ld c,e\n"), @enumToInt(opcode.Opcode.LD_C_H) => try self.output.print("ld c,h\n"), @enumToInt(opcode.Opcode.LD_C_L) => try self.output.print("ld c,l\n"), @enumToInt(opcode.Opcode.LD_C_HL) => try self.output.print("ld c,(hl)\n"), @enumToInt(opcode.Opcode.LD_D_B) => try self.output.print("ld d,b\n"), @enumToInt(opcode.Opcode.LD_D_C) => try self.output.print("ld d,c\n"), @enumToInt(opcode.Opcode.LD_D_D) => try self.output.print("ld d,d\n"), @enumToInt(opcode.Opcode.LD_D_E) => try self.output.print("ld d,e\n"), @enumToInt(opcode.Opcode.LD_D_H) => try self.output.print("ld d,h\n"), @enumToInt(opcode.Opcode.LD_D_L) => try self.output.print("ld d,l\n"), @enumToInt(opcode.Opcode.LD_D_HL) => try self.output.print("ld d,(hl)\n"), @enumToInt(opcode.Opcode.LD_E_B) => try self.output.print("ld e,b\n"), @enumToInt(opcode.Opcode.LD_E_C) => try self.output.print("ld e,c\n"), @enumToInt(opcode.Opcode.LD_E_D) => try self.output.print("ld e,d\n"), @enumToInt(opcode.Opcode.LD_E_E) => try self.output.print("ld e,e\n"), @enumToInt(opcode.Opcode.LD_E_H) => try self.output.print("ld e,h\n"), @enumToInt(opcode.Opcode.LD_E_L) => try self.output.print("ld e,l\n"), @enumToInt(opcode.Opcode.LD_E_HL) => try self.output.print("ld e,(hl)\n"), @enumToInt(opcode.Opcode.LD_H_B) => try self.output.print("ld h,b\n"), @enumToInt(opcode.Opcode.LD_H_C) => try self.output.print("ld h,c\n"), @enumToInt(opcode.Opcode.LD_H_D) => try self.output.print("ld h,d\n"), @enumToInt(opcode.Opcode.LD_H_E) => try self.output.print("ld h,e\n"), @enumToInt(opcode.Opcode.LD_H_H) => try self.output.print("ld h,h\n"), @enumToInt(opcode.Opcode.LD_H_L) => try self.output.print("ld h,l\n"), @enumToInt(opcode.Opcode.LD_H_HL) => try self.output.print("ld h,(hl)\n"), @enumToInt(opcode.Opcode.LD_L_B) => try self.output.print("ld l,b\n"), @enumToInt(opcode.Opcode.LD_L_C) => try self.output.print("ld l,c\n"), @enumToInt(opcode.Opcode.LD_L_D) => try self.output.print("ld l,d\n"), @enumToInt(opcode.Opcode.LD_L_E) => try self.output.print("ld l,e\n"), @enumToInt(opcode.Opcode.LD_L_H) => try self.output.print("ld l,h\n"), @enumToInt(opcode.Opcode.LD_L_L) => try self.output.print("ld l,l\n"), @enumToInt(opcode.Opcode.LD_L_HL) => try self.output.print("ld l,(hl)\n"), @enumToInt(opcode.Opcode.LD_HL_B) => try self.output.print("ld (hl),b\n"), @enumToInt(opcode.Opcode.LD_HL_C) => try self.output.print("ld (hl),c\n"), @enumToInt(opcode.Opcode.LD_HL_D) => try self.output.print("ld (hl),d\n"), @enumToInt(opcode.Opcode.LD_HL_E) => try self.output.print("ld (hl),e\n"), @enumToInt(opcode.Opcode.LD_HL_H) => try self.output.print("ld (hl),h\n"), @enumToInt(opcode.Opcode.LD_HL_L) => try self.output.print("ld (hl),l\n"), @enumToInt(opcode.Opcode.LD_HL_n) => try self.output.print("ld (hl),${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_A_BC) => try self.output.print("ld a,(bc)\n"), @enumToInt(opcode.Opcode.LD_A_DE) => try self.output.print("ld a,(de)\n"), @enumToInt(opcode.Opcode.LD_A_nn) => try self.output.print("ld a,(${x})\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.LD_B_A) => try self.output.print("ld b,a\n"), @enumToInt(opcode.Opcode.LD_C_A) => try self.output.print("ld c,a\n"), @enumToInt(opcode.Opcode.LD_D_A) => try self.output.print("ld d,a\n"), @enumToInt(opcode.Opcode.LD_E_A) => try self.output.print("ld e,a\n"), @enumToInt(opcode.Opcode.LD_H_A) => try self.output.print("ld h,a\n"), @enumToInt(opcode.Opcode.LD_L_A) => try self.output.print("ld l,a\n"), @enumToInt(opcode.Opcode.LD_BC_A) => try self.output.print("ld (bc),a\n"), @enumToInt(opcode.Opcode.LD_DE_A) => try self.output.print("ld (de),a\n"), @enumToInt(opcode.Opcode.LD_HL_A) => try self.output.print("ld (hl),a\n"), @enumToInt(opcode.Opcode.LD_nn_A) => try self.output.print("ld (${x}),a\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.LD_A_mem_C) => try self.output.print("ld a,($FF00 + c)\n"), @enumToInt(opcode.Opcode.LD_mem_C_A) => try self.output.print("ld ($FF00 + c),a\n"), @enumToInt(opcode.Opcode.LDD_A_HL) => try self.output.print("ldd a,(hl)\n"), @enumToInt(opcode.Opcode.LDD_HL_A) => try self.output.print("ldd (hl),a\n"), @enumToInt(opcode.Opcode.LDI_A_HL) => try self.output.print("ldi a,(hl)\n"), @enumToInt(opcode.Opcode.LDI_HL_A) => try self.output.print("ldi (hl),a\n"), @enumToInt(opcode.Opcode.LDH_n_A) => try self.output.print("ld ${x},a\n", u16(0xFF00) | try self.input.readByte()), @enumToInt(opcode.Opcode.LDH_A_n) => try self.output.print("ld a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.LD_BC_nn) => try self.output.print("ld bc,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.LD_DE_nn) => try self.output.print("ld de,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.LD_HL_nn) => try self.output.print("ld hl,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.LD_SP_nn) => try self.output.print("ld sp,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.LD_SP_HL) => try self.output.print("ld sp,hl\n"), @enumToInt(opcode.Opcode.LDHL_SP_n) => try self.output.print("ld hl,sp+${x}\n", try self.input.readByteSigned()), @enumToInt(opcode.Opcode.LD_nn_SP) => try self.output.print("ld (${x}),sp\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.PUSH_AF) => try self.output.print("push af\n"), @enumToInt(opcode.Opcode.PUSH_BC) => try self.output.print("push bc\n"), @enumToInt(opcode.Opcode.PUSH_DE) => try self.output.print("push de\n"), @enumToInt(opcode.Opcode.PUSH_HL) => try self.output.print("push hl\n"), @enumToInt(opcode.Opcode.POP_AF) => try self.output.print("pop af\n"), @enumToInt(opcode.Opcode.POP_BC) => try self.output.print("pop bc\n"), @enumToInt(opcode.Opcode.POP_DE) => try self.output.print("pop de\n"), @enumToInt(opcode.Opcode.POP_HL) => try self.output.print("pop hl\n"), @enumToInt(opcode.Opcode.ADD_A_A) => try self.output.print("add a,a\n"), @enumToInt(opcode.Opcode.ADD_A_B) => try self.output.print("add a,b\n"), @enumToInt(opcode.Opcode.ADD_A_C) => try self.output.print("add a,c\n"), @enumToInt(opcode.Opcode.ADD_A_D) => try self.output.print("add a,d\n"), @enumToInt(opcode.Opcode.ADD_A_E) => try self.output.print("add a,e\n"), @enumToInt(opcode.Opcode.ADD_A_H) => try self.output.print("add a,h\n"), @enumToInt(opcode.Opcode.ADD_A_L) => try self.output.print("add a,l\n"), @enumToInt(opcode.Opcode.ADD_A_HL) => try self.output.print("add a,(hl)\n"), @enumToInt(opcode.Opcode.ADD_A_n) => try self.output.print("add a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.ADC_A_A) => try self.output.print("adc a,a\n"), @enumToInt(opcode.Opcode.ADC_A_B) => try self.output.print("adc a,b\n"), @enumToInt(opcode.Opcode.ADC_A_C) => try self.output.print("adc a,c\n"), @enumToInt(opcode.Opcode.ADC_A_D) => try self.output.print("adc a,d\n"), @enumToInt(opcode.Opcode.ADC_A_E) => try self.output.print("adc a,e\n"), @enumToInt(opcode.Opcode.ADC_A_H) => try self.output.print("adc a,h\n"), @enumToInt(opcode.Opcode.ADC_A_L) => try self.output.print("adc a,l\n"), @enumToInt(opcode.Opcode.ADC_A_HL) => try self.output.print("adc a,(hl)\n"), @enumToInt(opcode.Opcode.ADC_A_n) => try self.output.print("adc a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.SUB_A_A) => try self.output.print("sub a,a\n"), @enumToInt(opcode.Opcode.SUB_A_B) => try self.output.print("sub a,b\n"), @enumToInt(opcode.Opcode.SUB_A_C) => try self.output.print("sub a,c\n"), @enumToInt(opcode.Opcode.SUB_A_D) => try self.output.print("sub a,d\n"), @enumToInt(opcode.Opcode.SUB_A_E) => try self.output.print("sub a,e\n"), @enumToInt(opcode.Opcode.SUB_A_H) => try self.output.print("sub a,h\n"), @enumToInt(opcode.Opcode.SUB_A_L) => try self.output.print("sub a,l\n"), @enumToInt(opcode.Opcode.SUB_A_HL) => try self.output.print("sub a,(hl)\n"), @enumToInt(opcode.Opcode.SUB_A_n) => try self.output.print("sub a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.SBC_A_A) => try self.output.print("sbc a,a\n"), @enumToInt(opcode.Opcode.SBC_A_B) => try self.output.print("sbc a,b\n"), @enumToInt(opcode.Opcode.SBC_A_C) => try self.output.print("sbc a,c\n"), @enumToInt(opcode.Opcode.SBC_A_D) => try self.output.print("sbc a,d\n"), @enumToInt(opcode.Opcode.SBC_A_E) => try self.output.print("sbc a,e\n"), @enumToInt(opcode.Opcode.SBC_A_H) => try self.output.print("sbc a,h\n"), @enumToInt(opcode.Opcode.SBC_A_L) => try self.output.print("sbc a,l\n"), @enumToInt(opcode.Opcode.SBC_A_HL) => try self.output.print("sbc a,(hl)\n"), @enumToInt(opcode.Opcode.SBC_A_n) => try self.output.print("sbc a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.AND_A_A) => try self.output.print("and a,a\n"), @enumToInt(opcode.Opcode.AND_A_B) => try self.output.print("and a,b\n"), @enumToInt(opcode.Opcode.AND_A_C) => try self.output.print("and a,c\n"), @enumToInt(opcode.Opcode.AND_A_D) => try self.output.print("and a,d\n"), @enumToInt(opcode.Opcode.AND_A_E) => try self.output.print("and a,e\n"), @enumToInt(opcode.Opcode.AND_A_H) => try self.output.print("and a,h\n"), @enumToInt(opcode.Opcode.AND_A_L) => try self.output.print("and a,l\n"), @enumToInt(opcode.Opcode.AND_A_HL) => try self.output.print("and a,(hl)\n"), @enumToInt(opcode.Opcode.AND_A_n) => try self.output.print("and a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.OR_A_A) => try self.output.print("or a,a\n"), @enumToInt(opcode.Opcode.OR_A_B) => try self.output.print("or a,b\n"), @enumToInt(opcode.Opcode.OR_A_C) => try self.output.print("or a,c\n"), @enumToInt(opcode.Opcode.OR_A_D) => try self.output.print("or a,d\n"), @enumToInt(opcode.Opcode.OR_A_E) => try self.output.print("or a,e\n"), @enumToInt(opcode.Opcode.OR_A_H) => try self.output.print("or a,h\n"), @enumToInt(opcode.Opcode.OR_A_L) => try self.output.print("or a,l\n"), @enumToInt(opcode.Opcode.OR_A_HL) => try self.output.print("or a,(hl)\n"), @enumToInt(opcode.Opcode.OR_A_n) => try self.output.print("or a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.XOR_A_A) => try self.output.print("xor a,a\n"), @enumToInt(opcode.Opcode.XOR_A_B) => try self.output.print("xor a,b\n"), @enumToInt(opcode.Opcode.XOR_A_C) => try self.output.print("xor a,c\n"), @enumToInt(opcode.Opcode.XOR_A_D) => try self.output.print("xor a,d\n"), @enumToInt(opcode.Opcode.XOR_A_E) => try self.output.print("xor a,e\n"), @enumToInt(opcode.Opcode.XOR_A_H) => try self.output.print("xor a,h\n"), @enumToInt(opcode.Opcode.XOR_A_L) => try self.output.print("xor a,l\n"), @enumToInt(opcode.Opcode.XOR_A_HL) => try self.output.print("xor a,(hl)\n"), @enumToInt(opcode.Opcode.XOR_A_n) => try self.output.print("xor a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.CP_A_A) => try self.output.print("cp a,a\n"), @enumToInt(opcode.Opcode.CP_A_B) => try self.output.print("cp a,b\n"), @enumToInt(opcode.Opcode.CP_A_C) => try self.output.print("cp a,c\n"), @enumToInt(opcode.Opcode.CP_A_D) => try self.output.print("cp a,d\n"), @enumToInt(opcode.Opcode.CP_A_E) => try self.output.print("cp a,e\n"), @enumToInt(opcode.Opcode.CP_A_H) => try self.output.print("cp a,h\n"), @enumToInt(opcode.Opcode.CP_A_L) => try self.output.print("cp a,l\n"), @enumToInt(opcode.Opcode.CP_A_HL) => try self.output.print("cp a,(hl)\n"), @enumToInt(opcode.Opcode.CP_A_n) => try self.output.print("cp a,${x}\n", try self.input.readByte()), @enumToInt(opcode.Opcode.INC_A) => try self.output.print("inc a\n"), @enumToInt(opcode.Opcode.INC_B) => try self.output.print("inc b\n"), @enumToInt(opcode.Opcode.INC_C) => try self.output.print("inc c\n"), @enumToInt(opcode.Opcode.INC_D) => try self.output.print("inc d\n"), @enumToInt(opcode.Opcode.INC_E) => try self.output.print("inc e\n"), @enumToInt(opcode.Opcode.INC_H) => try self.output.print("inc h\n"), @enumToInt(opcode.Opcode.INC_L) => try self.output.print("inc l\n"), @enumToInt(opcode.Opcode.INC_mem_HL) => try self.output.print("inc (hl)\n"), @enumToInt(opcode.Opcode.DEC_A) => try self.output.print("dec a\n"), @enumToInt(opcode.Opcode.DEC_B) => try self.output.print("dec b\n"), @enumToInt(opcode.Opcode.DEC_C) => try self.output.print("dec c\n"), @enumToInt(opcode.Opcode.DEC_D) => try self.output.print("dec d\n"), @enumToInt(opcode.Opcode.DEC_E) => try self.output.print("dec e\n"), @enumToInt(opcode.Opcode.DEC_H) => try self.output.print("dec h\n"), @enumToInt(opcode.Opcode.DEC_L) => try self.output.print("dec l\n"), @enumToInt(opcode.Opcode.DEC_mem_HL) => try self.output.print("dec (hl)\n"), @enumToInt(opcode.Opcode.ADD_HL_BC) => try self.output.print("add hl,bc\n"), @enumToInt(opcode.Opcode.ADD_HL_DE) => try self.output.print("add hl,de\n"), @enumToInt(opcode.Opcode.ADD_HL_HL) => try self.output.print("add hl,hl\n"), @enumToInt(opcode.Opcode.ADD_HL_SP) => try self.output.print("add hl,sp\n"), @enumToInt(opcode.Opcode.ADD_SP_n) => try self.output.print("add hl,${x}\n", self.input.readByteSigned()), @enumToInt(opcode.Opcode.INC_BC) => try self.output.print("inc bc\n"), @enumToInt(opcode.Opcode.INC_DE) => try self.output.print("inc de\n"), @enumToInt(opcode.Opcode.INC_HL) => try self.output.print("inc hl\n"), @enumToInt(opcode.Opcode.INC_SP) => try self.output.print("inc sp\n"), @enumToInt(opcode.Opcode.DEC_BC) => try self.output.print("dec bc\n"), @enumToInt(opcode.Opcode.DEC_DE) => try self.output.print("dec de\n"), @enumToInt(opcode.Opcode.DEC_HL) => try self.output.print("dec hl\n"), @enumToInt(opcode.Opcode.DEC_SP) => try self.output.print("dec sp\n"), @enumToInt(opcode.Opcode.DAA) => try self.output.print("daa\n"), @enumToInt(opcode.Opcode.CPL) => try self.output.print("cpl\n"), @enumToInt(opcode.Opcode.CCF) => try self.output.print("ccf\n"), @enumToInt(opcode.Opcode.SCF) => try self.output.print("scf\n"), @enumToInt(opcode.Opcode.HALT) => try self.output.print("halt\n"), @enumToInt(opcode.Opcode.STOP_FIRST_BYTE) => { const second_byte = try self.input.readByte(); if (second_byte != 0) { self.buffer = second_byte; try self.output.print("${x}\n", @enumToInt(opcode.Opcode.STOP_FIRST_BYTE)); } else { try self.output.print("stop\n"); } }, @enumToInt(opcode.Opcode.DI) => try self.output.print("di\n"), @enumToInt(opcode.Opcode.EI) => try self.output.print("ei\n"), @enumToInt(opcode.Opcode.RLCA) => try self.output.print("rlca\n"), @enumToInt(opcode.Opcode.RLA) => try self.output.print("rla\n"), @enumToInt(opcode.Opcode.RRCA) => try self.output.print("rrca\n"), @enumToInt(opcode.Opcode.RRA) => try self.output.print("rra\n"), @enumToInt(opcode.Opcode.JP_nn) => try self.output.print("jp ${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.JP_NZ_nn) => try self.output.print("jp nz,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.JP_Z_nn) => try self.output.print("jp z,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.JP_NC_nn) => try self.output.print("jp nc,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.JP_C_nn) => try self.output.print("jp c,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.JP_HL) => try self.output.print("jp (HL)\n"), @enumToInt(opcode.Opcode.JR_n) => try self.output.print("jr ${x}\n", try self.input.readByteSigned()), @enumToInt(opcode.Opcode.JR_NZ_n) => try self.output.print("jr nz,${x}\n", try self.input.readByteSigned()), @enumToInt(opcode.Opcode.JR_Z_n) => try self.output.print("jr z,${x}\n", try self.input.readByteSigned()), @enumToInt(opcode.Opcode.JR_NC_n) => try self.output.print("jr nc,${x}\n", try self.input.readByteSigned()), @enumToInt(opcode.Opcode.JR_C_n) => try self.output.print("jr c,${x}\n", try self.input.readByteSigned()), @enumToInt(opcode.Opcode.CALL_nn) => try self.output.print("call ${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.CALL_NZ_nn) => try self.output.print("call nz,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.CALL_Z_nn) => try self.output.print("call z,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.CALL_NC_nn) => try self.output.print("call nc,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.CALL_C_nn) => try self.output.print("call c,${x}\n", try self.input.readIntLittle(u16)), @enumToInt(opcode.Opcode.RST_00) => try self.output.print("rst $00\n"), @enumToInt(opcode.Opcode.RST_08) => try self.output.print("rst $08\n"), @enumToInt(opcode.Opcode.RST_10) => try self.output.print("rst $10\n"), @enumToInt(opcode.Opcode.RST_18) => try self.output.print("rst $18\n"), @enumToInt(opcode.Opcode.RST_20) => try self.output.print("rst $20\n"), @enumToInt(opcode.Opcode.RST_28) => try self.output.print("rst $28\n"), @enumToInt(opcode.Opcode.RST_30) => try self.output.print("rst $30\n"), @enumToInt(opcode.Opcode.RST_38) => try self.output.print("rst $38\n"), @enumToInt(opcode.Opcode.RET) => try self.output.print("ret\n"), @enumToInt(opcode.Opcode.RET_NZ) => try self.output.print("ret nz\n"), @enumToInt(opcode.Opcode.RET_Z) => try self.output.print("ret z\n"), @enumToInt(opcode.Opcode.RET_NC) => try self.output.print("ret nc\n"), @enumToInt(opcode.Opcode.RET_C) => try self.output.print("ret c\n"), @enumToInt(opcode.Opcode.RETI) => try self.output.print("reti\n"), @enumToInt(opcode.Opcode.MISC) => { const next_byte = try self.input.readByte(); switch (next_byte) { @enumToInt(opcode.MiscOpcode.SWAP_A) => try self.output.print("swap a\n"), @enumToInt(opcode.MiscOpcode.SWAP_B) => try self.output.print("swap b\n"), @enumToInt(opcode.MiscOpcode.SWAP_C) => try self.output.print("swap c\n"), @enumToInt(opcode.MiscOpcode.SWAP_D) => try self.output.print("swap d\n"), @enumToInt(opcode.MiscOpcode.SWAP_E) => try self.output.print("swap e\n"), @enumToInt(opcode.MiscOpcode.SWAP_H) => try self.output.print("swap h\n"), @enumToInt(opcode.MiscOpcode.SWAP_L) => try self.output.print("swap l\n"), @enumToInt(opcode.MiscOpcode.SWAP_HL) => try self.output.print("swap (hl)\n"), @enumToInt(opcode.MiscOpcode.RLC_A) => try self.output.print("rlc a\n"), @enumToInt(opcode.MiscOpcode.RLC_B) => try self.output.print("rlc b\n"), @enumToInt(opcode.MiscOpcode.RLC_C) => try self.output.print("rlc c\n"), @enumToInt(opcode.MiscOpcode.RLC_D) => try self.output.print("rlc d\n"), @enumToInt(opcode.MiscOpcode.RLC_E) => try self.output.print("rlc e\n"), @enumToInt(opcode.MiscOpcode.RLC_H) => try self.output.print("rlc h\n"), @enumToInt(opcode.MiscOpcode.RLC_L) => try self.output.print("rlc l\n"), @enumToInt(opcode.MiscOpcode.RLC_HL) => try self.output.print("rlc (hl)\n"), @enumToInt(opcode.MiscOpcode.RL_A) => try self.output.print("rl a\n"), @enumToInt(opcode.MiscOpcode.RL_B) => try self.output.print("rl b\n"), @enumToInt(opcode.MiscOpcode.RL_C) => try self.output.print("rl c\n"), @enumToInt(opcode.MiscOpcode.RL_D) => try self.output.print("rl d\n"), @enumToInt(opcode.MiscOpcode.RL_E) => try self.output.print("rl e\n"), @enumToInt(opcode.MiscOpcode.RL_H) => try self.output.print("rl h\n"), @enumToInt(opcode.MiscOpcode.RL_L) => try self.output.print("rl l\n"), @enumToInt(opcode.MiscOpcode.RL_HL) => try self.output.print("rl (hl)\n"), @enumToInt(opcode.MiscOpcode.RRC_A) => try self.output.print("rrc a\n"), @enumToInt(opcode.MiscOpcode.RRC_B) => try self.output.print("rrc b\n"), @enumToInt(opcode.MiscOpcode.RRC_C) => try self.output.print("rrc c\n"), @enumToInt(opcode.MiscOpcode.RRC_D) => try self.output.print("rrc d\n"), @enumToInt(opcode.MiscOpcode.RRC_E) => try self.output.print("rrc e\n"), @enumToInt(opcode.MiscOpcode.RRC_H) => try self.output.print("rrc h\n"), @enumToInt(opcode.MiscOpcode.RRC_L) => try self.output.print("rrc l\n"), @enumToInt(opcode.MiscOpcode.RRC_HL) => try self.output.print("rrc (hl)\n"), @enumToInt(opcode.MiscOpcode.RR_A) => try self.output.print("rr a\n"), @enumToInt(opcode.MiscOpcode.RR_B) => try self.output.print("rr b\n"), @enumToInt(opcode.MiscOpcode.RR_C) => try self.output.print("rr c\n"), @enumToInt(opcode.MiscOpcode.RR_D) => try self.output.print("rr d\n"), @enumToInt(opcode.MiscOpcode.RR_E) => try self.output.print("rr e\n"), @enumToInt(opcode.MiscOpcode.RR_H) => try self.output.print("rr h\n"), @enumToInt(opcode.MiscOpcode.RR_L) => try self.output.print("rr l\n"), @enumToInt(opcode.MiscOpcode.RR_HL) => try self.output.print("rr (hl)\n"), @enumToInt(opcode.MiscOpcode.SLA_A) => try self.output.print("sla a\n"), @enumToInt(opcode.MiscOpcode.SLA_B) => try self.output.print("sla b\n"), @enumToInt(opcode.MiscOpcode.SLA_C) => try self.output.print("sla c\n"), @enumToInt(opcode.MiscOpcode.SLA_D) => try self.output.print("sla d\n"), @enumToInt(opcode.MiscOpcode.SLA_E) => try self.output.print("sla e\n"), @enumToInt(opcode.MiscOpcode.SLA_H) => try self.output.print("sla h\n"), @enumToInt(opcode.MiscOpcode.SLA_L) => try self.output.print("sla l\n"), @enumToInt(opcode.MiscOpcode.SLA_HL) => try self.output.print("sla (hl)\n"), @enumToInt(opcode.MiscOpcode.SRA_A) => try self.output.print("sra a\n"), @enumToInt(opcode.MiscOpcode.SRA_B) => try self.output.print("sra b\n"), @enumToInt(opcode.MiscOpcode.SRA_C) => try self.output.print("sra c\n"), @enumToInt(opcode.MiscOpcode.SRA_D) => try self.output.print("sra d\n"), @enumToInt(opcode.MiscOpcode.SRA_E) => try self.output.print("sra e\n"), @enumToInt(opcode.MiscOpcode.SRA_H) => try self.output.print("sra h\n"), @enumToInt(opcode.MiscOpcode.SRA_L) => try self.output.print("sra l\n"), @enumToInt(opcode.MiscOpcode.SRA_HL) => try self.output.print("sra (hl)\n"), @enumToInt(opcode.MiscOpcode.SRL_A) => try self.output.print("srl a\n"), @enumToInt(opcode.MiscOpcode.SRL_B) => try self.output.print("srl b\n"), @enumToInt(opcode.MiscOpcode.SRL_C) => try self.output.print("srl c\n"), @enumToInt(opcode.MiscOpcode.SRL_D) => try self.output.print("srl d\n"), @enumToInt(opcode.MiscOpcode.SRL_E) => try self.output.print("srl e\n"), @enumToInt(opcode.MiscOpcode.SRL_H) => try self.output.print("srl h\n"), @enumToInt(opcode.MiscOpcode.SRL_L) => try self.output.print("srl l\n"), @enumToInt(opcode.MiscOpcode.SRL_HL) => try self.output.print("srl (hl)\n"), @enumToInt(opcode.MiscOpcode.BIT_A) => try self.output.print("bit ${x},a\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_B) => try self.output.print("bit ${x},b\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_C) => try self.output.print("bit ${x},c\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_D) => try self.output.print("bit ${x},d\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_E) => try self.output.print("bit ${x},e\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_H) => try self.output.print("bit ${x},h\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_L) => try self.output.print("bit ${x},l\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.BIT_HL) => try self.output.print("bit ${x},(hl)\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_A) => try self.output.print("set ${x},a\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_B) => try self.output.print("set ${x},b\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_C) => try self.output.print("set ${x},c\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_D) => try self.output.print("set ${x},d\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_E) => try self.output.print("set ${x},e\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_H) => try self.output.print("set ${x},h\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_L) => try self.output.print("set ${x},l\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.SET_HL) => try self.output.print("set ${x},(hl)\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_A) => try self.output.print("res ${x},a\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_B) => try self.output.print("res ${x},b\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_C) => try self.output.print("res ${x},c\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_D) => try self.output.print("res ${x},d\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_E) => try self.output.print("res ${x},e\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_H) => try self.output.print("res ${x},h\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_L) => try self.output.print("res ${x},l\n", try self.input.readByte()), @enumToInt(opcode.MiscOpcode.RES_HL) => try self.output.print("res ${x},(hl)\n", try self.input.readByte()), else => try self.output.print("${x}\n", next_byte), } }, else => try self.output.print("${x}\n", byte), } } }; test "Disassembler" { var test_rom_file = try std.os.File.openRead("testdata/sprite_priority.gb"); defer test_rom_file.close(); var stdout = try std.io.getStdOut(); var buffered_in_stream = std.io.BufferedInStream(std.os.File.ReadError).init(&test_rom_file.inStream().stream); var buffered_out_stream = std.io.BufferedOutStream(std.os.File.WriteError).init(&stdout.outStream().stream); var disassembler = Disassembler.init(&buffered_in_stream.stream, &buffered_out_stream.stream); while (true) { disassembler.disassemble() catch |err| { if (err == error.EndOfStream) { break; } else { return err; } }; } }
src/disassembler.zig
const std = @import("std"); const mem = std.mem; const math = std.math; const Allocator = mem.Allocator; const ArrayList = std.ArrayList; const vm = @import("vecmath_j.zig"); const Vec3 = vm.Vec3; const camera = @import("camera.zig"); const Camera = camera.Camera; const Ray = camera.Ray; const HitRecord = camera.HitRecord; const util = @import("utils.zig"); const Random = std.rand.DefaultPrng; pub const ScatterResult = struct { scatterRay : Ray, attenuation : Vec3 }; // unlike the rtiaw book, i'm going with an ubershader approach pub const Material = struct { const Self = @This(); metalness : f32, glassness : f32, ior : f32, albedo: Vec3, roughness: f32, pub fn makeLambertian( albedo : Vec3 ) Material { return .{ .glassness = 0.0, .ior = 1.0, .metalness = 0.0, .albedo = albedo, .roughness = 0.9 }; } pub fn makeMetallic( albedo : Vec3, roughness : f32 ) Material { return .{ .glassness = 0.0, .ior = 1.0, .metalness = 1.0, .albedo = albedo, .roughness = roughness }; } pub fn makeGlass( albedo : Vec3, ior : f32 ) Material { return .{ .glassness = 1.0, .ior = ior, .metalness = 0.0, .albedo = albedo, .roughness = 0.9 }; } pub fn scatter( self : Self, rng: *Random, ray_in: Ray, hit : HitRecord ) ?ScatterResult { // todo probability if (self.glassness > 0.5 ) { // dialectric glass const unit_dir = Vec3.normalize( ray_in.dir ); const ray_ior : f32 = if (hit.front_face) (1.0/self.ior) else self.ior; const cos_theta = math.min( Vec3.dot( Vec3.mul_s( unit_dir, -1.0), hit.normal ), 1.0 ); const sin_theta = math.sqrt( 1.0 - cos_theta*cos_theta ); const cannot_refract = (ray_ior * sin_theta) > 1.0; const scatter_dir = if ((cannot_refract) or (reflectance_schlick( cos_theta, ray_ior ) > rng.random().float( f32 ) )) Vec3.reflect( unit_dir, hit.normal ) else Vec3.refract( unit_dir, hit.normal, ray_ior ); //const refracted = Vec3.refract( unit_dir, hit.normal, ray_ior ); return ScatterResult { .scatterRay = Ray { .orig = hit.point, .dir = scatter_dir }, .attenuation = self.albedo //.attenuation = Vec3.init (1.0, 1.0, 1.0 ) }; } else if (self.metalness > 0.5 ) { // dialectric metal const reflected = Vec3.reflect( Vec3.normalize( ray_in.dir ), hit.normal ); return ScatterResult { .scatterRay = Ray { .orig = hit.point, .dir = Vec3.add( reflected, Vec3.mul_s( util.randomUnitVector( rng ), self.roughness) ) }, .attenuation = self.albedo }; } else { // lambertian var scatter_dir = Vec3.add( hit.normal, util.randomUnitVector( rng ) ); if (Vec3.checkZero(scatter_dir)) { scatter_dir = hit.normal; } return ScatterResult { .scatterRay = Ray { .orig = hit.point, .dir = scatter_dir }, .attenuation = self.albedo }; } } pub inline fn reflectance_schlick( cosine : f32, ref_idx : f32 ) f32 { const r00 = (1.0-ref_idx) / ( 1.0 + ref_idx); const r0 = r00*r00; return r0 + (1.0-r0) * math.pow( f32, 1.0 - cosine, 5.0 ); } };
src/material.zig
const std = @import("std"); const mem = std.mem; const meta = std.meta; const net = std.net; const ArrayList = std.ArrayList; usingnamespace @import("../frame.zig"); usingnamespace @import("../primitive_types.zig"); const sm = @import("../string_map.zig"); const testing = @import("../testing.zig"); /// Structure of a query in a BATCH frame const BatchQuery = struct { const Self = @This(); query_string: ?[]const u8, query_id: ?[]const u8, values: Values, pub fn write(self: Self, pw: *PrimitiveWriter) !void { if (self.query_string) |query_string| { _ = try pw.writeByte(0); _ = try pw.writeLongString(query_string); } else if (self.query_id) |query_id| { _ = try pw.writeByte(1); _ = try pw.writeShortBytes(query_id); } switch (self.values) { .Normal => |normal_values| { _ = try pw.writeInt(u16, @intCast(u16, normal_values.len)); for (normal_values) |value| { _ = try pw.writeValue(value); } }, .Named => |named_values| { _ = try pw.writeInt(u16, @intCast(u16, named_values.len)); for (named_values) |v| { _ = try pw.writeString(v.name); _ = try pw.writeValue(v.value); } }, } } pub fn read(allocator: *mem.Allocator, pr: *PrimitiveReader) !BatchQuery { var query = Self{ .query_string = null, .query_id = null, .values = undefined, }; const kind = try pr.readByte(); switch (kind) { 0 => query.query_string = try pr.readLongString(allocator), 1 => query.query_id = try pr.readShortBytes(allocator), else => return error.InvalidQueryKind, } var list = std.ArrayList(Value).init(allocator); errdefer list.deinit(); const n_values = try pr.readInt(u16); var j: usize = 0; while (j < @as(usize, n_values)) : (j += 1) { const value = try pr.readValue(allocator); _ = try list.append(value); } query.values = Values{ .Normal = list.toOwnedSlice() }; return query; } }; /// BATCH is sent to execute a list of queries (prepared or not) as a batch. /// /// Described in the protocol spec at §4.1.7 pub const BatchFrame = struct { const Self = @This(); batch_type: BatchType, queries: []BatchQuery, consistency_level: Consistency, serial_consistency_level: ?Consistency, timestamp: ?u64, keyspace: ?[]const u8, now_in_seconds: ?u32, const FlagWithSerialConsistency: u32 = 0x0010; const FlagWithDefaultTimestamp: u32 = 0x0020; const FlagWithNamedValues: u32 = 0x0040; // NOTE(vincent): the spec says this is broken so it's not implemented const FlagWithKeyspace: u32 = 0x0080; const FlagWithNowInSeconds: u32 = 0x100; pub fn write(self: Self, protocol_version: ProtocolVersion, pw: *PrimitiveWriter) !void { _ = try pw.writeInt(u8, @intCast(u8, @enumToInt(self.batch_type))); // Write the queries _ = try pw.writeInt(u16, @intCast(u16, self.queries.len)); for (self.queries) |query| { _ = try query.write(pw); } // Write the consistency _ = try pw.writeConsistency(self.consistency_level); // Build the flags value var flags: u32 = 0; if (self.serial_consistency_level != null) { flags |= FlagWithSerialConsistency; } if (self.timestamp != null) { flags |= FlagWithDefaultTimestamp; } if (protocol_version.is(5)) { if (self.keyspace != null) { flags |= FlagWithKeyspace; } if (self.now_in_seconds != null) { flags |= FlagWithNowInSeconds; } } if (protocol_version.is(5)) { _ = try pw.writeInt(u32, flags); } else { _ = try pw.writeInt(u8, @intCast(u8, flags)); } // Write the remaining body } pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !Self { var frame = Self{ .batch_type = undefined, .queries = undefined, .consistency_level = undefined, .serial_consistency_level = null, .timestamp = null, .keyspace = null, .now_in_seconds = null, }; frame.batch_type = @intToEnum(BatchType, try pr.readByte()); frame.queries = &[_]BatchQuery{}; // Read all queries in the batch var queries = std.ArrayList(BatchQuery).init(allocator); errdefer queries.deinit(); const n = try pr.readInt(u16); var i: usize = 0; while (i < @as(usize, n)) : (i += 1) { const query = try BatchQuery.read(allocator, pr); _ = try queries.append(query); } frame.queries = queries.toOwnedSlice(); // Read the rest of the frame frame.consistency_level = try pr.readConsistency(); // The size of the flags bitmask depends on the protocol version. var flags: u32 = 0; if (protocol_version.is(5)) { flags = try pr.readInt(u32); } else { flags = try pr.readInt(u8); } if (flags & FlagWithSerialConsistency == FlagWithSerialConsistency) { const consistency_level = try pr.readConsistency(); if (consistency_level != .Serial and consistency_level != .LocalSerial) { return error.InvalidSerialConsistency; } frame.serial_consistency_level = consistency_level; } if (flags & FlagWithDefaultTimestamp == FlagWithDefaultTimestamp) { const timestamp = try pr.readInt(u64); if (timestamp < 0) { return error.InvalidNegativeTimestamp; } frame.timestamp = timestamp; } if (!protocol_version.is(5)) { return frame; } // The following flags are only valid with protocol v5 if (flags & FlagWithKeyspace == FlagWithKeyspace) { frame.keyspace = try pr.readString(allocator); } if (flags & FlagWithNowInSeconds == FlagWithNowInSeconds) { frame.now_in_seconds = try pr.readInt(u32); } return frame; } }; test "batch frame: query type string" { var arena = testing.arenaAllocator(); defer arena.deinit(); // read const exp = "\x04\x00\x00\xc0\x0d\x00\x00\x00\xcc\x00\x00\x03\x00\x00\x00\x00\x3b\x49\x4e\x53\x45\x52\x54\x20\x49\x4e\x54\x4f\x20\x66\x6f\x6f\x62\x61\x72\x2e\x75\x73\x65\x72\x28\x69\x64\x2c\x20\x6e\x61\x6d\x65\x29\x20\x76\x61\x6c\x75\x65\x73\x28\x75\x75\x69\x64\x28\x29\x2c\x20\x27\x76\x69\x6e\x63\x65\x6e\x74\x27\x29\x00\x00\x00\x00\x00\x00\x3b\x49\x4e\x53\x45\x52\x54\x20\x49\x4e\x54\x4f\x20\x66\x6f\x6f\x62\x61\x72\x2e\x75\x73\x65\x72\x28\x69\x64\x2c\x20\x6e\x61\x6d\x65\x29\x20\x76\x61\x6c\x75\x65\x73\x28\x75\x75\x69\x64\x28\x29\x2c\x20\x27\x76\x69\x6e\x63\x65\x6e\x74\x27\x29\x00\x00\x00\x00\x00\x00\x3b\x49\x4e\x53\x45\x52\x54\x20\x49\x4e\x54\x4f\x20\x66\x6f\x6f\x62\x61\x72\x2e\x75\x73\x65\x72\x28\x69\x64\x2c\x20\x6e\x61\x6d\x65\x29\x20\x76\x61\x6c\x75\x65\x73\x28\x75\x75\x69\x64\x28\x29\x2c\x20\x27\x76\x69\x6e\x63\x65\x6e\x74\x27\x29\x00\x00\x00\x00\x00"; const raw_frame = try testing.readRawFrame(&arena.allocator, exp); checkHeader(Opcode.Batch, exp.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try BatchFrame.read(&arena.allocator, raw_frame.header.version, &pr); testing.expectEqual(BatchType.Logged, frame.batch_type); testing.expectEqual(@as(usize, 3), frame.queries.len); for (frame.queries) |query| { const exp_query = "INSERT INTO foobar.user(id, name) values(uuid(), 'vincent')"; testing.expectEqualStrings(exp_query, query.query_string.?); testing.expect(query.query_id == null); testing.expect(query.values == .Normal); testing.expectEqual(@as(usize, 0), query.values.Normal.len); } testing.expectEqual(Consistency.Any, frame.consistency_level); testing.expect(frame.serial_consistency_level == null); testing.expect(frame.timestamp == null); testing.expect(frame.keyspace == null); testing.expect(frame.now_in_seconds == null); // write testing.expectSameRawFrame(frame, raw_frame.header, exp); } test "batch frame: query type prepared" { var arena = testing.arenaAllocator(); defer arena.deinit(); // read const exp = "\x04\x00\x01\x00\x0d\x00\x00\x00\xa2\x00\x00\x03\x01\x00\x10\x88\xb7\xd6\x81\x8b\x2d\x8d\x97\xfc\x41\xc1\x34\x7b\x27\xde\x65\x00\x02\x00\x00\x00\x10\x3a\x9a\xab\x41\x68\x24\x4a\xef\x9d\xf5\x72\xc7\x84\xab\xa2\x57\x00\x00\x00\x07\x56\x69\x6e\x63\x65\x6e\x74\x01\x00\x10\x88\xb7\xd6\x81\x8b\x2d\x8d\x97\xfc\x41\xc1\x34\x7b\x27\xde\x65\x00\x02\x00\x00\x00\x10\xed\x54\xb0\x6d\xcc\xb2\x43\x51\x96\x51\x74\x5e\xee\xae\xd2\xfe\x00\x00\x00\x07\x56\x69\x6e\x63\x65\x6e\x74\x01\x00\x10\x88\xb7\xd6\x81\x8b\x2d\x8d\x97\xfc\x41\xc1\x34\x7b\x27\xde\x65\x00\x02\x00\x00\x00\x10\x79\xdf\x8a\x28\x5a\x60\x47\x19\x9b\x42\x84\xea\x69\x10\x1a\xe6\x00\x00\x00\x07\x56\x69\x6e\x63\x65\x6e\x74\x00\x00\x00"; const raw_frame = try testing.readRawFrame(&arena.allocator, exp); checkHeader(Opcode.Batch, exp.len, raw_frame.header); var pr = PrimitiveReader.init(); pr.reset(raw_frame.body); const frame = try BatchFrame.read(&arena.allocator, raw_frame.header.version, &pr); testing.expectEqual(BatchType.Logged, frame.batch_type); const expUUIDs = &[_][]const u8{ "\x3a\x9a\xab\x41\x68\x24\x4a\xef\x9d\xf5\x72\xc7\x84\xab\xa2\x57", "\xed\x54\xb0\x6d\xcc\xb2\x43\x51\x96\x51\x74\x5e\xee\xae\xd2\xfe", "\x79\xdf\x8a\x28\x5a\x60\x47\x19\x9b\x42\x84\xea\x69\x10\x1a\xe6", }; testing.expectEqual(@as(usize, 3), frame.queries.len); var i: usize = 0; for (frame.queries) |query| { testing.expect(query.query_string == null); const exp_query_id = "\x88\xb7\xd6\x81\x8b\x2d\x8d\x97\xfc\x41\xc1\x34\x7b\x27\xde\x65"; testing.expectEqualSlices(u8, exp_query_id, query.query_id.?); testing.expect(query.values == .Normal); testing.expectEqual(@as(usize, 2), query.values.Normal.len); const value1 = query.values.Normal[0]; testing.expectEqualSlices(u8, expUUIDs[i], value1.Set); const value2 = query.values.Normal[1]; testing.expectEqualStrings("Vincent", value2.Set); i += 1; } testing.expectEqual(Consistency.Any, frame.consistency_level); testing.expect(frame.serial_consistency_level == null); testing.expect(frame.timestamp == null); testing.expect(frame.keyspace == null); testing.expect(frame.now_in_seconds == null); // write testing.expectSameRawFrame(frame, raw_frame.header, exp); }
src/frames/batch.zig
const std = @import("std"); const debug = std.debug; const Dir = std.fs.Dir; const Allocator = std.mem.Allocator; usingnamespace @import("../c.zig"); var allocator = std.heap.page_allocator; const ShaderCompileErr = error{SeeLog}; fn ShaderTypeStr(comptime shaderType: GLenum) []const u8 { return switch (shaderType) { GL_VERTEX_SHADER => "Vertex", GL_FRAGMENT_SHADER => "Fragment", GL_COMPUTE_SHADER => "Compute", GL_GEOMETRY_SHADER => "Geometry", GL_TESS_CONTROL_SHADER => "Tesselation Control", GL_TESS_EVALUATION_SHADER => "Tesselation Evaluation", else => return "Unknown", }; } // return needs to be cleaned up with glDeleteShader fn CompileShader(relativePath: []const u8, comptime shaderType: GLenum) !GLuint { var compileResult: GLint = GL_FALSE; debug.warn("Compiling {s} Shader {s}...\n", .{ ShaderTypeStr(shaderType), relativePath }); const cwd: Dir = std.fs.cwd(); const shaderFile = try cwd.openFile(relativePath, .{}); defer shaderFile.close(); var shaderCode = try allocator.alloc(u8, try shaderFile.getEndPos()); defer allocator.free(shaderCode); const shaderObject: GLuint = glCreateShader(shaderType); _ = try shaderFile.read(shaderCode); const shaderSrcPtr: ?[*]const u8 = shaderCode.ptr; glShaderSource(shaderObject, 1, &shaderSrcPtr, 0); glCompileShader(shaderObject); glGetShaderiv(shaderObject, GL_COMPILE_STATUS, &compileResult); if (compileResult == GL_FALSE) { var errLogLength: GLint = 0; glGetShaderiv(shaderObject, GL_INFO_LOG_LENGTH, &errLogLength); var errLog = try allocator.alloc(u8, @intCast(usize, errLogLength)); glGetShaderInfoLog(shaderObject, errLogLength, &errLogLength, errLog.ptr); //this line segfaults? debug.warn("{s}\n", .{errLog[0..@intCast(usize, errLogLength)]}); return ShaderCompileErr.SeeLog; } else { debug.warn("{s} shader {s} compiled successfully.\n", .{ ShaderTypeStr(shaderType), relativePath }); } return shaderObject; } pub const Shader = struct { gl_id: GLuint, pub fn init(vertFile: []const u8, fragFile: []const u8) ?Shader { // vert shader: build, compile, link const vertShaderObject = CompileShader(vertFile, GL_VERTEX_SHADER) catch |err| { debug.warn("Unable to compile {s} shader with path {s}, error: {}\n", .{ ShaderTypeStr(GL_VERTEX_SHADER), vertFile, err }); return null; }; defer glDeleteShader(vertShaderObject); // fragment shader: build, compile, link const fragShaderObject = CompileShader(fragFile, GL_FRAGMENT_SHADER) catch |err| { debug.warn("Unable to compile {s} shader with path {s}, error: {}\n", .{ ShaderTypeStr(GL_FRAGMENT_SHADER), fragFile, err }); return null; }; defer glDeleteShader(fragShaderObject); // link shaders debug.warn("Linking shader programs {s} and {s}...\n", .{ vertFile, fragFile }); const shaderObject: GLuint = glCreateProgram(); glAttachShader(shaderObject, vertShaderObject); glAttachShader(shaderObject, fragShaderObject); glLinkProgram(shaderObject); var compileResult: GLint = GL_FALSE; glGetProgramiv(shaderObject, GL_LINK_STATUS, &compileResult); if (compileResult == GL_FALSE) { var errLogLength: GLint = 0; glGetProgramiv(shaderObject, GL_INFO_LOG_LENGTH, &errLogLength); var errLog: []u8 = undefined; glGetProgramInfoLog(shaderObject, errLogLength, &errLogLength, &errLog[0]); debug.warn("{s}\n", .{errLog[0..@intCast(usize, errLogLength)]}); return null; } debug.warn("Shader program {s} and {s} linked successfully.\n", .{ vertFile, fragFile }); return Shader{ .gl_id = shaderObject }; } // pub fn PushUniform( };
src/presentation/Shader.zig
const std = @import("std"); // Reference for implementation: // https://danielmangum.com/posts/non-local-jumps-riscv/ const c = @cImport({ @cInclude("setjmp.h"); }); export fn setjmp(env: *c.jmp_buf) c_int { // Note: // - This implementation is 32-bit only: sw stores 32 bits and offset // between fields is 4 bytes. // - This implementation assumes that there are no floating-point registers. // // TODO: Update for 64-bit and float/double when required. // Querying CPU info: @import("builtin").target.cpu.arch, etc. comptime { std.debug.assert(@import("builtin").cpu.arch == .riscv32); } // Store the required registers to env. // jmp_buf is basically an array of register-sized values. // We store the contents of all the registers we need to there. // a0 is the pointer to the jmp_buf. _ = asm volatile ( \\sw ra, 0(a0) \\sw sp, 4(a0) \\sw s0, 8(a0) \\sw s1, 12(a0) \\sw s2, 16(a0) \\sw s3, 20(a0) \\sw s4, 24(a0) \\sw s5, 28(a0) \\sw s6, 32(a0) \\sw s7, 36(a0) \\sw s8, 40(a0) \\sw s9, 44(a0) \\sw s10, 48(a0) \\sw s11, 52(a0) : : [env] "{a0}" (env), : "memory" ); // 0 is returned when initially calling setjmp(). // when longjmp() jumps to the caller of setjmp(), it sets the return value // register to the status value passed to longjmp(). return 0; } export fn longjmp(env: *c.jmp_buf, status: c_int) noreturn { // Load the required registers from env, set the return value to status (or // 1 if it is 0), then perform a return. // The return will use the return address we put in ra, which is the return // address for the original setjmp() call. _ = asm volatile ( \\lw ra, 0(a0) \\lw sp, 4(a0) \\lw s0, 8(a0) \\lw s1, 12(a0) \\lw s2, 16(a0) \\lw s3, 20(a0) \\lw s4, 24(a0) \\lw s5, 28(a0) \\lw s6, 32(a0) \\lw s7, 36(a0) \\lw s8, 40(a0) \\lw s9, 44(a0) \\lw s10, 48(a0) \\lw s11, 52(a0) \\seqz a0, a1 \\add a0, a0, a1 \\ret : : [env] "{a0}" (env), [status] "{a1}" (status), : "ra", "sp", "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7", "s8", "s9", "s10", "s11" ); unreachable; }
src/libc/setjmp.zig
const std = @import("std"); //^^^ storage.modifier.zig // ^ keyword.operator.assignment.zig // ^^^^^^^ keyword.control.import.zig // ^ punctuation.section.parens.begin.zig // ^^^^^ string.quoted.double.zig // ^ punctuation.section.parens.end.zig // ^ punctuation.terminator.zig pub fn main() !void { //^ storage.modifier.zig // ^^ storage.type.function.zig // ^^^^ entity.name.function // ^ punctuation.section.parens.begin.zig // ^ punctuation.section.parens.end.zig // ^ keyword.operator.zig // ^^^^ storage.type.zig // ^ punctuation.section.braces.begin.zig // If this program is run without stdout attached, exit with an error. // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ comment.line.zig const stdout_file = std.io.getStdOut(); // ^^^^^ storage.modifier.zig // ^ keyword.operator.assignment.zig // ^^^^^^^^^ variable.function.zig // ^ punctuation.section.parens.begin.zig // ^ punctuation.section.parens.end.zig // ^ punctuation.terminator.zig try stdout_file.writeAll("Hello, world!\n"); // ^^^ keyword.control.conditional.zig // ^^^^^^^^ variable.function.zig // ^ punctuation.section.parens.begin.zig // ^^^^^^^^^^^^^^^^^ string.quoted.double.zig // ^^ constant.character.escape.newline.zig // ^ punctuation.section.parens.end.zig } const var extern packed export pub noalias inline comptime nakedcc stdcallcc volatile align linksection threadlocal const as = 2; // <- storage.modifier.zig // ^ constant.numeric.integer.zig // ^ punctuation.terminator.zig union struct enum error asd { .asd = asd, } fn dump( // ^^ storage.type.function.zig // ^^^^ entity.name.function // ^ punctuation.section.parens.begin.zig value: var.asda.ad.asd, // ^^^^^ variable.parameter.zig // ^ punctuation.separator.zig // ^^^^^^^^^^^^^^^ storage.type.zig // NYI some arg asdasd: Baddad ) void { // <- punctuation.section.parens.end.zig // ^^^ storage.type.zig // ^ punctuation.section.braces.begin.zig } // <- punctuation.section.braces.end.zig "for" // ^^^^^ string.quoted.double.zig break return continue asm defer errdefer unreachable if else switch and or try catch orelse async await suspend resume cancel noasync while for null undefined fn usingnamespace test bool f16 f32 f64 f128 void noreturn type anyerror anytype promise anyframe i2 u2 i3 u3 i4 u4 i5 u5 i6 u6 i7 u7 i8 u8 i16 u16 u29 i29 i32 u32 i64 u64 i128 u128 isize usize .i368 .i686 .i23 c_short c_ushort c_int c_uint c_long c_ulong c_longlong c_ulonglong c_longdouble c_void true false a + b //^ keyword.operator.arithmetic.zig a += b //^^ keyword.operator.assignment.zig a +% b //^^ keyword.operator.arithmetic.zig a +%= b //^^^ keyword.operator.assignment.zig a - b //^ keyword.operator.arithmetic.zig a -= b //^^ keyword.operator.assignment.zig a -% b a -%= b -a -%a a * b a *= b a *% b a *%= b a / b a /= b a % b a %= b a << b //^^ keyword.operator.logical.zig a <<= b //^^^ keyword.operator.logical.zig a & b a &= b //^^ keyword.operator.assignment.zig a | b a |= b a ^ b a ^= b ~a a orelse b a.? a catch b a catch |err| b a and b a or b !a a == b a == null a != b a > b a >= b a < b a <= b a ++ b a ** b a.* &a a || b test "numbers" { 123 // ^^^ constant.numeric.integer.zig 123.123 // ^^^^^^^ constant.numeric.float.zig 123.123e123 // ^^^^^^^^^^^ constant.numeric.float.zig 123.123E123 // ^^^^^^^^^^^ constant.numeric.float.zig 1e3 // ^^^ constant.numeric.float.zig 0x123 // ^^^^^ constant.numeric.integer.hexadecimal.zig 0x123.123 // ^^^^^^^^^ constant.numeric.float.hexadecimal.zig 0x123.123p123 // ^^^^^^^^^^^^^ constant.numeric.float.hexadecimal.zig 0o123 // ^^^^^ constant.numeric.integer.octal.zig 0b1 // ^^^ constant.numeric.integer.binary.zig 1_234_567; // ^^^^^^^^^ constant.numeric.integer.zig 0xff00_00ff; // ^^^^^^^^^^^ constant.numeric.integer.hexadecimal.zig 0b10000000_10101010; 0b1000_0000_1010_1010; 0x123_190.109_038_018p102; // ^^^^^^^^^^^^^^^^^^^^^^^^^ constant.numeric.float.hexadecimal.zig 3.14159_26535_89793; // ^^^^^^^^^^^^^^^^^^^ constant.numeric.float.zig 123.i812; // ^^^^^^^^ -constant.numeric a.111; var x: i123 = 0x7A; // ^^^^ storage.type.zig var x: usize = 0x7A; // ^^^^^ storage.type.zig } slice[0..2] // ^^ keyword.operator.other.zig /// TODO blah blah // ^^^^^^^^^^^^^^^ comment.line.documentation.zig // TODO blah blah // ^^^^^^^^^^^^^^^ comment.line.todo.zig "adsfjioasdjfoiad" c"adsfjioasdjfoiad" // <- string.quoted.double.zig // ^^^^^^^^^^^^^^^^ string.quoted.double.zig '\a' // ^^^^ string.quoted.single.zig // ^^ string.quoted.single.zig invalid.illegal.character.zig const \\ adsjfaf23n9 // <- storage.modifier.zig // ^^^^^^^^^^^^^^^ string.quoted.other.zig "ad//sd" // ^^^^^ string.quoted.double.zig -comment const v = fn(aas, 2342, 23) as; fn foo(a:as) i32 { // <- storage.type.function.zig // ^^^ entity.name.function // ^ punctuation.section.parens.begin.zig // ^ variable.parameter.zig // ^ punctuation.separator.zig // ^^ storage.type.zig // ^ punctuation.section.parens.end.zig // ^^^ storage.type.zig // ^ punctuation.section.braces.begin.zig } // <- punctuation.section.braces.end.zig fn foo() A![]Foo { // ^ storage.type.zig // ^ keyword.operator.zig // ^^^ storage.type.zig } extern fn bar() as as void; extern fn foobar() void; errdefer |err| std.debug.assert(err == error.Overflow); // <- keyword.control.zig // ^ keyword.operator.bitwise.zig // ^ keyword.operator.bitwise.zig // ^ punctuation.section.parens.begin.zig // ^^ keyword.operator.logical.zig // ^^^^^ storage.type.error.zig // ^ punctuation.accessor.zig // ^^^^^^^^ entity.name.error.zig // ^ punctuation.section.parens.end.zig // ^ punctuation.terminator.zig test "strings" { c\\ adsjfafsdjkl \x11 \u1245 \U123456 extern fn bar() void; c\\ adsjfafsdjkl \ \\ \ \xdeadbeef extern fn foobar() void; \\ adsjfafsdjkl pub fn barfoo(); fn \\ adsjfafsdjkl } "hello \x1 \n \t \\ \r 1m ' \\ \a \" \u{11}" extern fn foobarfoo() void; "\"hello\"" 'a' 'ab' '\'' '\a\naa' '\a' '\aaasas' '\n' // ^^ string.quoted.single.zig constant.character.escape.newline.zig '💩'; } fn(i13i,Foo) Bar; // ^^ storage.type.function.zig // ^ punctuation.section.parens.begin.zig // ^^^^ meta.function.parameters.zig storage.type.zig // ^ meta.function.parameters.zig punctuation.separator.zig // ^^^ meta.function.parameters.zig storage.type.zig // ^ meta.function.parameters.zig punctuation.section.parens.end.zig // ^^^ storage.type.zig foo = bar; @"overloaded" = 89; // ^^^^^^^^^^^^ string.quoted.double.zig // ^ keyword.operator.assignment.zig @cImport // <- keyword.control.import.zig @cInclude @import @exampleBuiltin // <- support.function.zig typo@cImport // ^^^^^^^^ keyword.control.import.zig *const asasd // <- keyword.operator.arithmetic.zig //^^^^ storage.modifier.zig *const [N:0]u8 ?[]T and *[N]T .{ .x = 13, .y = 67, } var i: Number = .{.int = 42}; pub extern "hellas" export fn @"eeeasla"(as: FN) userdata; pub extern "hellas" export fn hello(as: as) AA!OO { anyframe->U } pub extern "ole32" stdcallcc fn CoTaskMemFree(pv: *const LPVOID, asda: asdsad, sacz: @"zxc", asd: asd) oop!asd; pub stdcallcc fn CoUninitialize() A![]; ident pub const Foo = extern struct { fn_call() }; asda: extern struct { }; const Err = error { }; { : Bar, } (asdasd) const Bar = struct { field: Foo = 234"asas", comptime field: Bad = Fasd {}, field: var }; const Boof = union(enum) { }; const Bad = enum(u8) { Dummy, _ }; var as: Bad = Bad(u8) { pub stdcallcc fn CoUninitialize() void; }; blk: { // <- entity.name.label.zig break :blk val1; // ^^^^^ keyword.control.zig // ^^^ entity.name.label.zig // ^ punctuation.terminator.zig var f = Bar { // ^^^ storage.modifier.zig // ^ keyword.operator.assignment.zig // ^^^ storage.type.zig // ^ punctuation.section.braces.begin.zig .val = 9 } } extern fn f2(s: *const *volatile u8) Error!GenericType(s) { } var asd: *const asd!asdads = 0; var ba = 0; blk: while () : (sas) { error.asdasd; } const asas: u8asd; addsaad const alignment = blk: { const a = comptime meta.alignment(P); const b: a = fn() A!A; a = 23; if (a > 0) break :blk a; break :blk 1; }; std.debug.warn(run_qemu.getEnvMap() .get("PATH")); ///Given a pointer to a single item, returns a slice of the underlying bytes, preserving constness. pub fn asBytes(ptr: var) asdsa!AsBytesReturnType(@typeOf(ptr)) { const P = @typeOf(ptr); return @ptrCast(AsBytesReturnType(P), ptr); } pub const LARGE_INTEGER = extern struct { // <- storage.modifier.zig // ^^^^^ storage.modifier.zig // ^^^^^^^^^^^^^ entity.name.struct.zig // ^ keyword.operator.assignment.zig // ^^^^^^ storage.modifier.zig // ^^^^^^ storage.type.struct.zig // ^ punctuation.section.braces.begin.zig _u2: extern struct { // ^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^^^^^^ storage.modifier.zig // ^^^^^^ storage.type.struct.zig // ^ punctuation.section.braces.begin.zig LowPart: fn(a, b, c)d, // ^^^^^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^^ storage.type.function.zig // ^ punctuation.section.parens.begin.zig // ^ meta.function.parameters.zig storage.type.zig // ^ meta.function.parameters.zig punctuation.separator.zig // ^ meta.function.parameters.zig storage.type.zig // ^ meta.function.parameters.zig punctuation.separator.zig // ^ meta.function.parameters.zig storage.type.zig // ^ meta.function.parameters.zig punctuation.section.parens.end.zig // ^ storage.type.zig // ^ punctuation.separator.zig HighPart: LONG, // ^^^^^^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^^^^ storage.type.zig // ^ punctuation.separator.zig }, // ^ punctuation.section.braces.end.zig // ^ punctuation.separator.zig QuadPart: LONGLONG, // ^^^^^^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^^^^^^^^ storage.type.zig }; pub const GUID = extern struct { // ^^^^^ storage.modifier.zig // ^^^^ entity.name.struct.zig // ^ keyword.operator.assignment.zig // ^^^^^^ storage.modifier.zig // ^^^^^^ storage.type.struct.zig // ^ punctuation.section.braces.begin.zig Data1: c_ulong, // ^^^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^^^^^^^ storage.type.zig // ^ punctuation.separator.zig Data2: c_ushort, Data3: c_ushort, Data4: [8]u8, // ^^^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^ punctuation.separator.zig }; pub async fn function() Error!ReturnType { // ^^^^^ keyword.control.async.zig // ^^ storage.type.function.zig // ^^^^^^^^ entity.name.function } pub async fn function(arg: Int, arg: I) !ReturnType { } test "enum literals" { const color1: Color = .Auto; // ^^^^^ storage.modifier.zig // ^^^^^^ variable.other.member.zig // ^ punctuation.separator.zig // ^^^^^ storage.type.zig // ^ keyword.operator.assignment.zig // ^^^^^ constant.language.enum const color2 = Color.Auto; // ^^^^ -constant.language.enum const color2 = .{x}.Auto; // ^^^^ -constant.language.enum assert(color1 == color2); const color = Color.On; const result = switch (color) { .Auto => false, // ^^^^^ constant.language.enum // ^ keyword.operator.assignment.zig // ^ keyword.operator.logical.zig // ^^^^^ constant.language.zig .On => true, // ^^^ constant.language.enum .Off => false, // ^^^^ constant.language.enum }; assert(result); } test "fully anonymous list literal" { const args = .{ @as(u32, 1234), @as(f64, 12.34)}); assert(args.@"0" == 1234); // ^^^ string.quoted.double.zig assert(args.@"1" == 12.34); // ^^^ string.quoted.double.zig }
Syntaxes/syntax_test.zig
const std = @import("std"); const io = std.io; const fmt = std.fmt; const dns = @import("../dns.zig"); const InError = io.SliceInStream.Error; const OutError = io.SliceOutStream.Error; const Type = dns.Type; pub const SOAData = struct { mname: dns.Name, rname: dns.Name, serial: u32, refresh: u32, retry: u32, expire: u32, minimum: u32, }; pub const MXData = struct { preference: u16, exchange: dns.Name, }; pub const SRVData = struct { priority: u16, weight: u16, port: u16, target: dns.Name, }; /// DNS RDATA representation to a "native-r" type for nicer usage. pub const DNSRData = union(Type) { A: std.net.Address, AAAA: std.net.Address, NS: dns.Name, MD: dns.Name, MF: dns.Name, CNAME: dns.Name, SOA: SOAData, MB: dns.Name, MG: dns.Name, MR: dns.Name, // ???? NULL: void, // TODO WKS bit map WKS: struct { addr: u32, proto: u8, // how to define bit map? align(8)? }, PTR: dns.Name, // TODO replace by Name? HINFO: struct { cpu: []const u8, os: []const u8, }, MINFO: struct { rmailbx: dns.Name, emailbx: dns.Name, }, MX: MXData, TXT: [][]const u8, SRV: SRVData, pub fn size(self: @This()) usize { return switch (self) { .A => 4, .AAAA => 16, .NS, .MD, .MF, .MB, .MG, .MR, .CNAME, .PTR => |name| name.size(), else => @panic("TODO"), }; } /// Format the RData into a prettier version of it. /// For example, A rdata would be formatted to its ipv4 address. pub fn format(self: @This(), comptime f: []const u8, options: fmt.FormatOptions, writer: anytype) !void { if (f.len != 0) { @compileError("Unknown format character: '" ++ f ++ "'"); } switch (self) { .A, .AAAA => |addr| return fmt.format(writer, "{}", .{addr}), .NS, .MD, .MF, .MB, .MG, .MR, .CNAME, .PTR => |name| return fmt.format(writer, "{}", .{name}), .SOA => |soa| return fmt.format(writer, "{} {} {} {} {} {} {}", .{ soa.mname, soa.rname, soa.serial, soa.refresh, soa.retry, soa.expire, soa.minimum, }), .MX => |mx| return fmt.format(writer, "{} {}", .{ mx.preference, mx.exchange }), .SRV => |srv| return fmt.format(writer, "{} {} {} {}", .{ srv.priority, srv.weight, srv.port, srv.target, }), else => return fmt.format(writer, "TODO support {}", .{@tagName(self)}), } return fmt.format(writer, "{}"); } }; /// Deserialize a given Resource's RDATA information. Requires the original /// Packet for allocation for memory ownership. pub fn deserializeRData( pkt_const: dns.Packet, resource: dns.Resource, ) !DNSRData { var pkt = pkt_const; var in = dns.FixedStream{ .buffer = resource.opaque_rdata, .pos = 0 }; var deserializer = dns.DNSDeserializer.init(in.reader()); var rdata = switch (resource.rr_type) { .A => blk: { var ip4addr: [4]u8 = undefined; for (ip4addr) |_, i| { ip4addr[i] = try deserializer.deserialize(u8); } break :blk DNSRData{ .A = std.net.Address.initIp4(ip4addr, 0), }; }, .AAAA => blk: { var ip6_addr: [16]u8 = undefined; for (ip6_addr) |byte, i| { ip6_addr[i] = try deserializer.deserialize(u8); } break :blk DNSRData{ .AAAA = std.net.Address.initIp6(ip6_addr, 0, 0, 0), }; }, .NS => DNSRData{ .NS = try pkt.deserializeName(&deserializer) }, .CNAME => DNSRData{ .CNAME = try pkt.deserializeName(&deserializer) }, .PTR => DNSRData{ .PTR = try pkt.deserializeName(&deserializer) }, .MX => blk: { break :blk DNSRData{ .MX = MXData{ .preference = try deserializer.deserialize(u16), .exchange = try pkt.deserializeName(&deserializer), }, }; }, .MD => DNSRData{ .MD = try pkt.deserializeName(&deserializer) }, .MF => DNSRData{ .MF = try pkt.deserializeName(&deserializer) }, .SOA => blk: { var mname = try pkt.deserializeName(&deserializer); var rname = try pkt.deserializeName(&deserializer); var serial = try deserializer.deserialize(u32); var refresh = try deserializer.deserialize(u32); var retry = try deserializer.deserialize(u32); var expire = try deserializer.deserialize(u32); var minimum = try deserializer.deserialize(u32); break :blk DNSRData{ .SOA = SOAData{ .mname = mname, .rname = rname, .serial = serial, .refresh = refresh, .retry = retry, .expire = expire, .minimum = minimum, }, }; }, .SRV => blk: { const priority = try deserializer.deserialize(u16); const weight = try deserializer.deserialize(u16); const port = try deserializer.deserialize(u16); var target = try pkt.deserializeName(&deserializer); break :blk DNSRData{ .SRV = .{ .priority = priority, .weight = weight, .port = port, .target = target, }, }; }, else => { return error.InvalidRData; }, }; return rdata; } /// Serialize a given DNSRData into []u8 pub fn serializeRData( rdata: DNSRData, serializer: anytype, ) !void { switch (rdata) { .A => |addr| try serializer.serialize(addr.in.addr), .AAAA => |addr| try serializer.serialize(addr.in6.addr), .NS, .MD, .MF, .MB, .MG, .MR, .CNAME, .PTR => |name| try serializer.serialize(name), .SOA => |soa_data| blk: { try serializer.serialize(soa_data.mname); try serializer.serialize(soa_data.rname); try serializer.serialize(soa_data.serial); try serializer.serialize(soa_data.refresh); try serializer.serialize(soa_data.retry); try serializer.serialize(soa_data.expire); try serializer.serialize(soa_data.minimum); }, .MX => |mxdata| blk: { try serializer.serialize(mxdata.preference); try serializer.serialize(mxdata.exchange); }, .SRV => |srv| blk: { try serializer.serialize(srv.priority); try serializer.serialize(srv.weight); try serializer.serialize(srv.port); try serializer.serialize(srv.target); }, else => return error.NotImplemented, } }
src/pkg/dns/rdata.zig
const std = @import("std"); const webgpu = @import("./webgpu.zig"); pub const CommandBuffer = struct { pub const VTable = struct { destroy_fn: fn(*CommandBuffer) void, }; __vtable: *const VTable, device: *webgpu.Device, pub inline fn destroy(command_buffer: *CommandBuffer) void { command_buffer.__vtable.destroy_fn(command_buffer); } }; pub const CommandEncoder = struct { pub const VTable = struct { destroy_fn: fn(*CommandEncoder) void, begin_compute_pass_fn: fn(*CommandEncoder, webgpu.ComputePassDescriptor) BeginComputePassError!*ComputePassEncoder, begin_render_pass_fn: fn(*CommandEncoder, webgpu.RenderPassDescriptor) BeginRenderPassError!*RenderPassEncoder, clear_buffer_fn: fn(*CommandEncoder, *webgpu.Buffer, usize, usize) ClearBufferError!void, copy_buffer_to_buffer_fn: fn(*CommandEncoder, *webgpu.Buffer, usize, *webgpu.Buffer, usize, usize) CopyBufferToBufferError!void, copy_buffer_to_texture_fn: fn(*CommandEncoder, webgpu.ImageCopyBuffer, webgpu.ImageCopyTexture, webgpu.Extend3D) CopyBufferToTextureError!void, copy_texture_to_buffer_fn: fn(*CommandEncoder, webgpu.ImageCopyTexture, webgpu.ImageCopyBuffer, webgpu.Extend3D) CopyTextureToBufferError!void, copy_texture_to_texture_fn: fn(*CommandEncoder, webgpu.ImageCopyTexture, webgpu.ImageCopyTexture, webgpu.Extend3D) CopyTextureToTextureError!void, finish_fn: fn(*CommandEncoder, webgpu.CommandBufferDescriptor) FinishError!*CommandBuffer, insert_debug_marker_fn: fn(*CommandEncoder, [:0]const u8) void, pop_debug_group_fn: fn(*CommandEncoder) void, push_debug_group_fn: fn(*CommandEncoder, [:0]const u8) void, resolve_query_set_fn: fn(*CommandEncoder, *webgpu.QuerySet, u32, u32, *webgpu.Buffer, u64) ResolveQuerySetError!void, write_timestamp_fn: fn(*CommandEncoder, *webgpu.QuerySet, u32) WriteTimestampError!void, }; __vtable: *const VTable, device: *webgpu.Device, pub inline fn destroy(command_encoder: *CommandEncoder) void { command_encoder.__vtable.destroy_fn(command_encoder); } pub const BeginComputePassError = error { OutOfMemory, Failed, }; pub inline fn beginComputePass(command_encoder: *CommandEncoder, descriptor: webgpu.ComputePassDescriptor) BeginComputePassError!*ComputePassEncoder { return command_encoder.__vtable.begin_compute_pass_fn(command_encoder, descriptor); } pub const BeginRenderPassError = error { OutOfMemory, Failed, }; pub inline fn beginRenderPass(command_encoder: *CommandEncoder, descriptor: webgpu.RenderPassDescriptor) BeginRenderPassError!*RenderPassEncoder { return command_encoder.__vtable.begin_render_pass_fn(command_encoder, descriptor); } pub const ClearBufferError = error { Failed, }; pub inline fn clearBuffer(command_encoder: *CommandEncoder, buffer: *webgpu.Buffer, offset: usize, size: usize) ClearBufferError!void { return command_encoder.__vtable.clear_buffer_fn(command_encoder, buffer, offset, size); } pub const CopyBufferToBufferError = error { Failed, }; pub inline fn copyBufferToBuffer(command_encoder: *CommandEncoder, source: *webgpu.Buffer, source_offset: usize, destination: *webgpu.Buffer, destination_offset: usize, size: usize) CopyBufferToBufferError!void { return command_encoder.__vtable.copy_buffer_to_buffer_fn(command_encoder, source, source_offset, destination, destination_offset, size); } pub const CopyBufferToTextureError = error { Failed, }; pub inline fn copyBufferToTexture(command_encoder: *CommandEncoder, source: webgpu.ImageCopyBuffer, destination: webgpu.ImageCopyTexture, copy_size: webgpu.Extend3D) CopyBufferToTextureError!void { return command_encoder.__vtable.copy_buffer_to_texture_fn(command_encoder, source, destination, copy_size); } pub const CopyTextureToBufferError = error { Failed, }; pub inline fn copyTextureToBuffer(command_encoder: *CommandEncoder, source: webgpu.ImageCopyTexture, destination: webgpu.ImageCopyBuffer, copy_size: webgpu.Extend3D) CopyTextureToBufferError!void { return command_encoder.__vtable.copy_texture_to_buffer_fn(command_encoder, source, destination, copy_size); } pub const CopyTextureToTextureError = error { Failed, }; pub inline fn copyTextureToTexture(command_encoder: *CommandEncoder, source: webgpu.ImageCopyTexture, destination: webgpu.ImageCopyTexture, copy_size: webgpu.Extend3D) CopyTextureToTextureError!void { return command_encoder.__vtable.copy_texture_to_texture_fn(command_encoder, source, destination, copy_size); } pub const FinishError = error { OutOfMemory, Failed, }; pub inline fn finish(command_encoder: *CommandEncoder) FinishError!CommandBuffer { return command_encoder.__vtable.finish_fn(command_encoder); } pub inline fn insertDebugMarker(command_encoder: *CommandEncoder, marker_label: [:0]const u8) void { command_encoder.__vtable.insert_debug_marker_fn(command_encoder, marker_label); } pub inline fn popDebugGroup(command_encoder: *CommandEncoder) void { command_encoder.__vtable.pop_debug_group_fn(command_encoder); } pub inline fn pushDebugGroup(command_encoder: *CommandEncoder, group_label: [:0]const u8) void { command_encoder.__vtable.push_debug_group_fn(command_encoder, group_label); } pub const ResolveQuerySetError = error { Failed, }; pub inline fn resolveQuerySet(command_encoder: *CommandEncoder, query_set: *webgpu.QuerySet, first_query: u32, query_count: u32, destination: *webgpu.Buffer, destination_offset: u64) ResolveQuerySetError!void { return command_encoder.__vtable.resolve_query_set_fn(command_encoder, query_set, first_query, query_count, destination, destination_offset); } pub const WriteTimestampError = error { Failed, }; pub inline fn writeTimestamp(command_encoder: *CommandEncoder, query_set: *webgpu.QuerySet, query_index: u32) WriteTimestampError!void { return command_encoder.__vtable.write_timestamp_fn(command_encoder, query_set, query_index); } }; pub const ComputePassEncoder = struct { pub const VTable = struct { destroy_fn: fn(*ComputePassEncoder) void, begin_pipeline_statistics_query_fn: fn(*ComputePassEncoder, *webgpu.QuerySet, u32) BeginPipelineStatisticsQueryError!void, dispatch_fn: fn(*ComputePassEncoder, u32, u32, u32) DispatchError!void, dispatch_indirect_fn: fn(*ComputePassEncoder, *webgpu.Buffer, u64) DispatchIndirectError!void, end_pass_fn: fn(*ComputePassEncoder) EndPassError!void, end_pipeline_statistics_query_fn: fn(*ComputePassEncoder) EndPipelineStatisticsQueryError!void, insert_debug_marker_fn: fn(*ComputePassEncoder, [:0]const u8) void, pop_debug_group_fn: fn(*ComputePassEncoder) void, push_debug_group_fn: fn(*ComputePassEncoder, [:0]const u8) void, set_bind_group_fn: fn(*ComputePassEncoder, u32, *webgpu.BindGroup, []const u32) SetBindGroupError!void, set_pipeline_fn: fn(*ComputePassEncoder, *webgpu.ComputePipeline) SetPipelineError!void, }; __vtable: *const VTable, device: *webgpu.Device, pub inline fn destroy(compute_pass_encoder: *ComputePassEncoder) void { compute_pass_encoder.__vtable.destroy_fn(compute_pass_encoder); } pub const BeginPipelineStatisticsQueryError = error { Failed, }; pub inline fn beginPipelineStatisticsQuery(compute_pass_encoder: *ComputePassEncoder, query_set: *webgpu.QuerySet, query_index: u32) BeginPipelineStatisticsQueryError!void { return compute_pass_encoder.__vtable.begin_pipeline_statistics_query_fn(compute_pass_encoder, query_set, query_index); } pub const DispatchError = error { Failed, }; pub inline fn dispatch(compute_pass_encoder: *ComputePassEncoder, x: u32, y: u32, z: u32) DispatchError!void { return compute_pass_encoder.__vtable.dispatch_fn(compute_pass_encoder, x, y, z); } pub const DispatchIndirectError = error { Failed, }; pub inline fn dispatchIndirect(compute_pass_encoder: *ComputePassEncoder, indirect_buffer: *webgpu.Buffer, indirect_offset: u64) DispatchIndirectError!void { return compute_pass_encoder.__vtable.dispatch_indirect_fn(compute_pass_encoder, indirect_buffer, indirect_offset); } pub const EndPassError = error { Failed }; pub inline fn endPass(compute_pass_encoder: *ComputePassEncoder) EndPassError!void { return compute_pass_encoder.__vtable.end_pass_fn(compute_pass_encoder); } pub const EndPipelineStatisticsQueryError = error { Failed, }; pub inline fn endPipelineStatisticsQuery(compute_pass_encoder: *ComputePassEncoder) EndPipelineStatisticsQueryError!void { return compute_pass_encoder.__vtable.end_pipeline_statistics_query_fn(compute_pass_encoder); } pub inline fn insertDebugMarker(compute_pass_encoder: *ComputePassEncoder, marker_label: [:0]const u8) void { compute_pass_encoder.__vtable.insert_debug_marker_fn(compute_pass_encoder, marker_label); } pub inline fn popDebugGroup(compute_pass_encoder: *ComputePassEncoder) void { compute_pass_encoder.__vtable.pop_debug_group_fn(compute_pass_encoder); } pub inline fn pushDebugGroup(compute_pass_encoder: *ComputePassEncoder, group_label: [:0]const u8) void { compute_pass_encoder.__vtable.push_debug_group_fn(compute_pass_encoder, group_label); } pub const SetBindGroupError = error { Failed, }; pub inline fn setBindGroup(compute_pass_encoder: *ComputePassEncoder, group_index: u32, group: *webgpu.BindGroup, dynamic_offets: []const u32) SetBindGroupError!void { return compute_pass_encoder.__vtable.set_bind_group_fn(compute_pass_encoder, group_index, group, dynamic_offets); } pub const SetPipelineError = error { Failed, }; pub inline fn setPipeline(compute_pass_encoder: *ComputePassEncoder, pipeline: *webgpu.ComputePipeline) SetPipelineError!void { compute_pass_encoder.__vtable.set_pipeline_fn(compute_pass_encoder, pipeline); } }; pub const RenderBundle = struct { pub const VTable = struct { destroy_fn: fn(*RenderBundle) void, }; __vtable: *const VTable, device: *webgpu.Device, pub inline fn destroy(render_bundle: *RenderBundle) void { render_bundle.__vtable.destroy_fn(render_bundle); } }; pub const RenderBundleEncoder = struct { pub const VTable = struct { destroy_fn: fn(*RenderBundleEncoder) void, draw_fn: fn(*RenderBundleEncoder, u32, u32, u32, u32) void, draw_indexed_fn: fn(*RenderBundleEncoder, u32, u32, u32, u32, u32) void, draw_indexed_indirect_fn: fn(*RenderBundleEncoder, *webgpu.Buffer, u64) void, draw_indirect_fn: fn(*RenderBundleEncoder, *webgpu.Buffer, u64) void, finish_fn: fn(*RenderBundleEncoder) FinishError!*RenderBundle, insert_debug_marker_fn: fn(*RenderBundleEncoder, [:0]const u8) void, pop_debug_group_fn: fn(*RenderBundleEncoder) void, push_debug_group_fn: fn(*RenderBundleEncoder, [:0]const u8) void, set_bind_group_fn: fn(*RenderBundleEncoder, u32, *webgpu.BindGroup, []const u32) void, set_index_buffer_fn: fn(*RenderBundleEncoder, *webgpu.Buffer, webgpu.IndexFormat, u64, u64) void, set_pipeline_fn: fn(*RenderBundleEncoder, *webgpu.RenderPipeline) void, set_vertex_buffer_fn: fn(*RenderBundleEncoder, u32, *webgpu.Buffer, u64, u64) void, }; __vtable: *const VTable, device: *webgpu.Device, pub inline fn destroy(render_bundle_encoder: *RenderBundleEncoder) void { return render_bundle_encoder.__vtable.destroy_fn(render_bundle_encoder); } pub inline fn draw(render_bundle_encoder: *RenderBundleEncoder, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32) void { return render_bundle_encoder.__vtable.draw_fn(render_bundle_encoder, vertex_count, instance_count, first_vertex, first_instance); } pub inline fn drawIndexed(render_bundle_encoder: *RenderBundleEncoder, index_count: u32, instance_count: u32, first_index: u32, base_vertex: u32, first_instance: u32) void { return render_bundle_encoder.__vtable.draw_indexed_fn(render_bundle_encoder, index_count, instance_count, first_index, base_vertex, first_instance); } pub inline fn drawIndexedIndirect(render_bundle_encoder: *RenderBundleEncoder, indirect_buffer: *webgpu.Buffer, indirect_offset: u64) void { return render_bundle_encoder.__vtable.draw_indexed_indirect_fn(render_bundle_encoder, indirect_buffer, indirect_offset); } pub inline fn drawIndirect(render_bundle_encoder: *RenderBundleEncoder, indirect_buffer: *webgpu.Buffer, indirect_offset: u64) void { return render_bundle_encoder.__vtable.draw_indirect_fn(render_bundle_encoder, indirect_buffer, indirect_offset); } pub const FinishError = error { OutOfMemory, }; pub inline fn finish(render_bundle_encoder: *RenderBundleEncoder) FinishError!*RenderBundle { return render_bundle_encoder.__vtable.finish_fn(render_bundle_encoder); } pub inline fn insertDebugMarker(render_bundle_encoder: *RenderBundleEncoder, marker_label: [:0]const u8) void { return render_bundle_encoder.__vtable.insert_debug_marker_fn(render_bundle_encoder, marker_label); } pub inline fn popDebugGroup(render_bundle_encoder: *RenderBundleEncoder) void { return render_bundle_encoder.__vtable.pop_debug_group_fn(render_bundle_encoder); } pub inline fn pushDebugGroup(render_bundle_encoder: *RenderBundleEncoder, group_label: [:0]const u8) void { return render_bundle_encoder.__vtable.push_debug_group_fn(render_bundle_encoder, group_label); } pub inline fn setBindGroup(render_bundle_encoder: *RenderBundleEncoder, group_index: u32, group: *webgpu.BindGroup, dynamic_offsets: []const u32) void { return render_bundle_encoder.__vtable.set_bind_group_fn(render_bundle_encoder, group_index, group, dynamic_offsets); } pub inline fn setIndexBuffer(render_bundle_encoder: *RenderBundleEncoder, buffer: *webgpu.Buffer, format: webgpu.IndexFormat, offset: u64, size: u64) void { return render_bundle_encoder.__vtable.set_index_buffer_fn(render_bundle_encoder, buffer, format, offset, size); } pub inline fn setPipeline(render_bundle_encoder: *RenderBundleEncoder, pipeline: *webgpu.RenderPipeline) void { return render_bundle_encoder.__vtable.set_pipeline_fn(render_bundle_encoder, pipeline); } pub inline fn setVertexBuffer(render_bundle_encoder: *RenderBundleEncoder, slot: u32, buffer: *webgpu.Buffer, offset: u64, size: u64) void { return render_bundle_encoder.__vtable.set_vertex_buffer_fn(render_bundle_encoder, slot, buffer, offset, size); } }; pub const RenderPassEncoder = struct { pub const VTable = struct { destroy_fn: fn(*RenderPassEncoder) void, begin_occlusion_query_fn: fn(*RenderPassEncoder, u32) void, begin_pipeline_statistics_query_fn: fn(*RenderPassEncoder, *webgpu.QuerySet, u32) void, draw_fn: fn(*RenderPassEncoder, u32, u32, u32, u32) void, draw_indexed_fn: fn(*RenderPassEncoder, u32, u32, u32, u32, u32) void, draw_indexed_indirect_fn: fn(*RenderPassEncoder, *webgpu.Buffer, u64) void, draw_indirect_fn: fn(*RenderPassEncoder, *webgpu.Buffer, u64) void, end_occlusion_query_fn: fn(*RenderPassEncoder) void, end_pipeline_statistics_query_fn: fn(*RenderPassEncoder) void, execute_bundles_fn: fn(*RenderPassEncoder, []*RenderBundle) void, insert_debug_marker_fn: fn(*RenderPassEncoder, [:0]const u8) void, pop_debug_group_fn: fn(*RenderPassEncoder) void, push_debug_group_fn: fn(*RenderPassEncoder, [:0]const u8) void, set_bind_group_fn: fn(*RenderPassEncoder, u32, *webgpu.BindGroup, []const u32) void, set_blend_constant_fn: fn(*RenderPassEncoder, webgpu.Color) void, set_index_buffer_fn: fn(*RenderPassEncoder, *webgpu.Buffer, webgpu.IndexFormat, u64, u64) void, set_pipeline_fn: fn(*RenderPassEncoder, *webgpu.RenderPipeline) void, set_scissor_rect_fn: fn(*RenderPassEncoder, u32, u32, u32, u32) void, set_stencil_reference_fn: fn(*RenderPassEncoder, u32) void, set_vertex_buffer_fn: fn(*RenderPassEncoder, u32, *webgpu.Buffer, u64, u64) void, set_viewport_fn: fn(*RenderPassEncoder, f32, f32, f32, f32, f32, f32) void, }; __vtable: *const VTable, device: *webgpu.Device, pub inline fn destroy(render_pass_encoder: *RenderPassEncoder) void { render_pass_encoder.__vtable.destroy_fn(render_pass_encoder); } pub inline fn beginOcclusionQuery(render_pass_encoder: *RenderPassEncoder, query_index: u32) void { return render_pass_encoder.__vtable.begin_occlusion_query_fn(render_pass_encoder, query_index); } pub inline fn beginPipelineStatisticsQuery(render_pass_encoder: *RenderPassEncoder, query_set: *webgpu.QuerySet, query_index: u32) void { return render_pass_encoder.__vtable.begin_pipeline_statistics_query_fn(render_pass_encoder, query_set, query_index); } pub inline fn draw(render_pass_encoder: *RenderPassEncoder, vertex_count: u32, instance_count: u32, first_vertex: u32, first_instance: u32) void { return render_pass_encoder.__vtable.draw_fn(render_pass_encoder, vertex_count, instance_count, first_vertex, first_instance); } pub inline fn drawIndexed(render_pass_encoder: *RenderPassEncoder, index_count: u32, instance_count: u32, first_index: u32, base_vertex: u32, first_instance: u32) void { return render_pass_encoder.__vtable.draw_indexed_fn(render_pass_encoder, index_count, instance_count, first_index, base_vertex, first_instance); } pub inline fn drawIndexedIndirect(render_pass_encoder: *RenderPassEncoder, indirect_buffer: *webgpu.Buffer, indirect_offset: u64) void { return render_pass_encoder.__vtable.draw_indexed_indirect_fn(render_pass_encoder, indirect_buffer, indirect_offset); } pub inline fn drawIndirect(render_pass_encoder: *RenderPassEncoder, indirect_buffer: *webgpu.Buffer, indirect_offset: u64) void { return render_pass_encoder.__vtable.draw_indirect_fn(render_pass_encoder, indirect_buffer, indirect_offset); } pub inline fn endOcclusionQuery(render_pass_encoder: *RenderPassEncoder) void { return render_pass_encoder.__vtable.end_occlusion_query_fn(render_pass_encoder); } pub inline fn endPipelineStatisticsQuery(render_pass_encoder: *RenderPassEncoder) void { return render_pass_encoder.__vtable.end_pipeline_statistics_query_fn(render_pass_encoder); } pub inline fn executeBundles(render_pass_encoder: *RenderPassEncoder, bundles: []RenderBundle) void { return render_pass_encoder.__vtable.execute_bundles_fn(render_pass_encoder, bundles); } pub inline fn insertDebugMarker(render_pass_encoder: *RenderPassEncoder, marker_label: [:0]const u8) void { return render_pass_encoder.__vtable.insert_debug_marker_fn(render_pass_encoder, marker_label); } pub inline fn popDebugGroup(render_pass_encoder: *RenderPassEncoder) void { return render_pass_encoder.__vtable.pop_debug_group_fn(render_pass_encoder); } pub inline fn pushDebugGroup(render_pass_encoder: *RenderPassEncoder, group_label: [:0]const u8) void { return render_pass_encoder.__vtable.push_debug_group_fn(render_pass_encoder, group_label); } pub inline fn setBindGroup(render_pass_encoder: *RenderPassEncoder, group_index: u32, group: *webgpu.BindGroup, dynamic_offsets: []const u32) void { return render_pass_encoder.__vtable.set_bind_group_fn(render_pass_encoder, group_index, group, dynamic_offsets); } pub inline fn setBlendConstant(render_pass_encoder: *RenderPassEncoder, color: webgpu.Color) void { return render_pass_encoder.__vtable.set_blend_constant_fn(render_pass_encoder, color); } pub inline fn setIndexBuffer(render_pass_encoder: *RenderPassEncoder, buffer: *webgpu.Buffer, format: webgpu.IndexFormat, offset: u64, size: u64) void { return render_pass_encoder.__vtable.set_index_buffer_fn(render_pass_encoder, buffer, format, offset, size); } pub inline fn setPipeline(render_pass_encoder: *RenderPassEncoder, pipeline: *webgpu.RenderPipeline) void { return render_pass_encoder.__vtable.set_pipeline_fn(render_pass_encoder, pipeline); } pub inline fn setScissorRect(render_pass_encoder: *RenderPassEncoder, x: u32, y: u32, width: u32, height: u32) void { return render_pass_encoder.__vtable.set_scissor_rect_fn(render_pass_encoder, x, y, width, height); } pub inline fn setStencilReference(render_pass_encoder: *RenderPassEncoder, reference: u32) void { return render_pass_encoder.__vtable.set_stencil_reference_fn(render_pass_encoder, reference); } pub inline fn setVertexBuffer(render_pass_encoder: *RenderPassEncoder, slot: u32, buffer: *webgpu.Buffer, offset: u64, size: u64) void { return render_pass_encoder.__vtable.set_vertex_buffer_fn(render_pass_encoder, slot, buffer, offset, size); } pub inline fn setViewport(render_pass_encoder: *RenderPassEncoder, x: f32, y: f32, width: f32, height: f32, min_depth: f32, max_depth: f32) void { return render_pass_encoder.__vtable.set_viewport_fn(render_pass_encoder, x, y, width, height, min_depth, max_depth); } };
src/command.zig
const std = @import("std"); const Builder = std.build.Builder; const CrossTarget = std.build.CrossTarget; const LibExeObjStep = std.build.LibExeObjStep; const Pkg = std.build.Pkg; pub fn build(b: *Builder) void { const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const nk = Nuklear.init(b, .{ .include_default_font = true, .include_font_backing = true, .include_vertex_buffer_output = true, .zero_command_memory = true, .keystate_based_input = true, }); const test_step = b.step("test", "Run library tests"); const tests = b.addTest("nuklear.zig"); test_step.dependOn(&tests.step); nk.addTo(tests, .{}); const examples_step = b.step("examples", ""); const examples = b.addExecutable("examples", "examples/main.zig"); examples_step.dependOn(&examples.step); nk.addTo(examples, .{}); examples.linkSystemLibrary("c"); examples.linkSystemLibrary("GL"); examples.linkSystemLibrary("glfw"); examples.linkSystemLibrary("GLU"); examples.install(); for ([_]*LibExeObjStep{ tests, examples, nk.lib }) |obj| { obj.setBuildMode(mode); obj.setTarget(target); } } const Nuklear = @This(); options: Options, lib: *LibExeObjStep, pub const Options = struct { include_fixed_types: bool = false, include_default_allocator: bool = false, include_stdio: bool = false, include_std_varargs: bool = false, include_vertex_buffer_output: bool = false, include_font_backing: bool = false, include_default_font: bool = false, include_command_userdata: bool = false, button_trigger_on_release: bool = false, zero_command_memory: bool = false, uint_draw_index: bool = false, keystate_based_input: bool = false, buffer_default_initial_size: ?usize = null, max_number_buffer: ?usize = null, input_max: ?usize = null, fn defineMacros(opts: Options, lib: *LibExeObjStep) void { const b = lib.builder; if (opts.include_fixed_types) lib.defineCMacro("NK_INCLUDE_FIXED_TYPES"); if (opts.include_default_allocator) lib.defineCMacro("NK_INCLUDE_DEFAULT_ALLOCATOR"); if (opts.include_stdio) lib.defineCMacro("NK_INCLUDE_STANDARD_IO"); if (opts.include_std_varargs) lib.defineCMacro("NK_INCLUDE_STANDARD_VARARGS"); if (opts.include_vertex_buffer_output) lib.defineCMacro("NK_INCLUDE_VERTEX_BUFFER_OUTPUT"); if (opts.include_font_backing) lib.defineCMacro("NK_INCLUDE_FONT_BAKING"); if (opts.include_default_font) lib.defineCMacro("NK_INCLUDE_DEFAULT_FONT"); if (opts.include_command_userdata) lib.defineCMacro("NK_INCLUDE_COMMAND_USERDATA"); if (opts.button_trigger_on_release) lib.defineCMacro("NK_BUTTON_TRIGGER_ON_RELEASE"); if (opts.zero_command_memory) lib.defineCMacro("NK_ZERO_COMMAND_MEMORY"); if (opts.uint_draw_index) lib.defineCMacro("NK_UINT_DRAW_INDEX"); if (opts.keystate_based_input) lib.defineCMacro("NK_KEYSTATE_BASED_INPUT"); if (opts.buffer_default_initial_size) |size| lib.defineCMacro(b.fmt("NK_BUFFER_DEFAULT_INITIAL_SIZE={}", .{size})); if (opts.max_number_buffer) |number| lib.defineCMacro(b.fmt("NK_MAX_NUMBER_BUFFER={}", .{number})); if (opts.input_max) |number| lib.defineCMacro(b.fmt("NK_INPUT_MAX={}", .{number})); } }; pub fn init(b: *Builder, opts: Options) Nuklear { const lib = b.addStaticLibrary("zig-nuklear", null); lib.addCSourceFile(dir() ++ "/src/c/nuklear.c", &.{}); opts.defineMacros(lib); return .{ .lib = lib, .options = opts }; } pub const AddToOptions = struct { package_name: []const u8 = "nuklear", }; pub fn addTo(nk: Nuklear, lib: *LibExeObjStep, opt: AddToOptions) void { lib.addIncludeDir(include_dir); lib.addPackagePath(opt.package_name, pkg_path); lib.linkLibrary(nk.lib); nk.options.defineMacros(lib); lib.step.dependOn(&nk.lib.step); } pub const pkg_path = dir() ++ "/nuklear.zig"; pub const include_dir = dir() ++ "/src/c"; fn dir() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; }
build.zig
const std = @import("std"); const build = std.build; const Builder = build.Builder; const FileSource = build.FileSource; const GeneratedFile = build.GeneratedFile; const InstallDir = build.InstallDir; const Step = build.Step; const fs = std.fs; const File = fs.File; const Self = @This(); pub const base_id = .custom; const Recipe = fn (*Builder, inputs: []File, output: File) anyerror!void; step: Step, builder: *Builder, recipe: Recipe, input_sources: []FileSource, output_dir: InstallDir, output_name: []const u8, output_file: GeneratedFile, pub fn create(builder: *Builder, recipe: Recipe, input_sources: []FileSource, output_dir: InstallDir, output_name: []const u8) *Self { const self = builder.allocator.create(Self) catch unreachable; self.* = .{ .step = Step.init(base_id, builder.fmt("file recipe", .{}), builder.allocator, make), .builder = builder, .recipe = recipe, .input_sources = builder.allocator.alloc(FileSource, input_sources.len) catch unreachable, .output_dir = output_dir, .output_name = builder.dupe(output_name), .output_file = .{ .step = &self.step }, }; for (input_sources) |source, i| { self.input_sources[i] = source.dupe(builder); source.addStepDependencies(&self.step); } return self; } pub fn getOutputSource(self: *const Self) FileSource { return FileSource{ .generated = &self.output_file }; } fn make(step: *Step) !void { const self = @fieldParentPtr(Self, "step", step); const builder = self.builder; var input_files = try builder.allocator.alloc(File, self.input_sources.len); defer builder.allocator.free(input_files); var files_opened: usize = 0; for (self.input_sources) |source, i| { input_files[i] = try fs.cwd().openFile(source.getPath(builder), .{}); files_opened += 1; } defer while (files_opened > 0) { input_files[files_opened - 1].close(); files_opened -= 1; }; try fs.cwd().makePath(builder.getInstallPath(self.output_dir, "")); const output_path = builder.getInstallPath(self.output_dir, self.output_name); var output_file = try fs.cwd().createFile(output_path, .{}); defer output_file.close(); try self.recipe(builder, input_files, output_file); self.output_file.path = output_path; } test { std.testing.refAllDecls(Self); }
src/build/FileRecipeStep.zig
const std = @import("std"); const c = @cImport({ @cInclude("xkbcommon/xkbcommon.h"); @cInclude("stdlib.h"); }); pub const Xkb = struct { context: *c.xkb_context, keymap: ?*c.xkb_keymap, state: ?*c.xkb_state, const Self = @This(); pub const FdSize = struct { fd: i32, size: usize, }; pub fn getKeymap(self: *Self) !FdSize { var xdg_runtime_dir = std.os.getenv("XDG_RUNTIME_DIR") orelse return error.NoXdgRuntimeDir; var filename: [128]u8 = [_]u8{0} ** 128; var random = "/XXXXXX"; std.mem.copy(u8, filename[0..filename.len], xdg_runtime_dir); if (xdg_runtime_dir.len >= filename.len - 1) { return error.FilenameBufferTooSmall; } std.mem.copy(u8, filename[xdg_runtime_dir.len..], random); if (self.keymap) |keymap| { var keymap_as_string = c.xkb_keymap_get_as_string(keymap, c.enum_xkb_keymap_format.XKB_KEYMAP_FORMAT_TEXT_V1); if (keymap_as_string) |string| { defer c.free(string); var size = std.mem.len(string) + 1; var keymap_string: []u8 = undefined; keymap_string.ptr = string; keymap_string.len = size; var fd: i32 = c.mkstemp(&filename[0]); // O_CLOEXEC? try std.os.ftruncate(fd, size); var data = try std.os.mmap(null, @intCast(usize, size), std.os.linux.PROT_READ | std.os.linux.PROT_WRITE, std.os.linux.MAP_SHARED, fd, 0); std.mem.copy(u8, data, keymap_string); std.os.munmap(data); return FdSize{ .fd = fd, .size = size, }; } return error.FailedToGetKeymapAsString; } return error.NoKeymap; } pub fn updateKey(self: *Self, keycode: u32, state: u32) void { var direction = if (state == 1) c.enum_xkb_key_direction.XKB_KEY_DOWN else c.enum_xkb_key_direction.XKB_KEY_UP; _ = c.xkb_state_update_key(self.state, keycode + 8, direction); } pub fn serializeDepressed(self: *Self) u32 { return c.xkb_state_serialize_mods(self.state, c.enum_xkb_state_component.XKB_STATE_MODS_DEPRESSED); } pub fn serializeLatched(self: *Self) u32 { return c.xkb_state_serialize_mods(self.state, c.enum_xkb_state_component.XKB_STATE_MODS_LATCHED); } pub fn serializeLocked(self: *Self) u32 { return c.xkb_state_serialize_mods(self.state, c.enum_xkb_state_component.XKB_STATE_MODS_LOCKED); } pub fn serializeGroup(self: *Self) u32 { return c.xkb_state_serialize_mods(self.state, c.enum_xkb_state_component.XKB_STATE_LAYOUT_EFFECTIVE); } }; pub fn init() !Xkb { var flags = c.enum_xkb_context_flags.XKB_CONTEXT_NO_FLAGS; var context = try newContext(flags); var keymap = try newKeymapFromNames(context, "evdev\x00", "apple\x00", "gb\x00", "\x00", "\x00"); var state = try newState(keymap); return Xkb{ .context = context, .keymap = keymap, .state = state, }; } fn newContext(flags: c.enum_xkb_context_flags) !*c.xkb_context { return c.xkb_context_new(flags) orelse error.XkbContextCreationFailed; } fn newKeymapFromNames(context: *c.xkb_context, rules: []const u8, model: []const u8, layout: []const u8, variant: []const u8, options: []const u8) !*c.xkb_keymap { var names = c.xkb_rule_names{ .rules = &rules[0], .model = &model[0], .layout = &layout[0], .variant = &variant[0], .options = &options[0], }; var flags = c.enum_xkb_keymap_compile_flags.XKB_KEYMAP_COMPILE_NO_FLAGS; return c.xkb_keymap_new_from_names(context, &names, flags) orelse error.XkbKeymapCreationFailed; } fn newState(keymap: *c.xkb_keymap) !*c.xkb_state { return c.xkb_state_new(keymap) orelse error.XkbStateCreationFailed; }
src/xkb.zig
const std = @import("std"); const builtin = @import("builtin"); pub extern fn __divdf3(a: f64, b: f64) f64 { @setRuntimeSafety(builtin.is_test); const Z = @IntType(false, f64.bit_count); const SignedZ = @IntType(true, f64.bit_count); const typeWidth = f64.bit_count; const significandBits = std.math.floatMantissaBits(f64); const exponentBits = std.math.floatExponentBits(f64); const signBit = (@as(Z, 1) << (significandBits + exponentBits)); const maxExponent = ((1 << exponentBits) - 1); const exponentBias = (maxExponent >> 1); const implicitBit = (@as(Z, 1) << significandBits); const quietBit = implicitBit >> 1; const significandMask = implicitBit - 1; const absMask = signBit - 1; const exponentMask = absMask ^ significandMask; const qnanRep = exponentMask | quietBit; const infRep = @bitCast(Z, std.math.inf(f64)); const aExponent = @truncate(u32, (@bitCast(Z, a) >> significandBits) & maxExponent); const bExponent = @truncate(u32, (@bitCast(Z, b) >> significandBits) & maxExponent); const quotientSign: Z = (@bitCast(Z, a) ^ @bitCast(Z, b)) & signBit; var aSignificand: Z = @bitCast(Z, a) & significandMask; var bSignificand: Z = @bitCast(Z, b) & significandMask; var scale: i32 = 0; // Detect if a or b is zero, denormal, infinity, or NaN. if (aExponent -% 1 >= maxExponent -% 1 or bExponent -% 1 >= maxExponent -% 1) { const aAbs: Z = @bitCast(Z, a) & absMask; const bAbs: Z = @bitCast(Z, b) & absMask; // NaN / anything = qNaN if (aAbs > infRep) return @bitCast(f64, @bitCast(Z, a) | quietBit); // anything / NaN = qNaN if (bAbs > infRep) return @bitCast(f64, @bitCast(Z, b) | quietBit); if (aAbs == infRep) { // infinity / infinity = NaN if (bAbs == infRep) { return @bitCast(f64, qnanRep); } // infinity / anything else = +/- infinity else { return @bitCast(f64, aAbs | quotientSign); } } // anything else / infinity = +/- 0 if (bAbs == infRep) return @bitCast(f64, quotientSign); if (aAbs == 0) { // zero / zero = NaN if (bAbs == 0) { return @bitCast(f64, qnanRep); } // zero / anything else = +/- zero else { return @bitCast(f64, quotientSign); } } // anything else / zero = +/- infinity if (bAbs == 0) return @bitCast(f64, infRep | quotientSign); // one or both of a or b is denormal, the other (if applicable) is a // normal number. Renormalize one or both of a and b, and set scale to // include the necessary exponent adjustment. if (aAbs < implicitBit) scale +%= normalize(f64, &aSignificand); if (bAbs < implicitBit) scale -%= normalize(f64, &bSignificand); } // Or in the implicit significand bit. (If we fell through from the // denormal path it was already set by normalize( ), but setting it twice // won't hurt anything.) aSignificand |= implicitBit; bSignificand |= implicitBit; var quotientExponent: i32 = @bitCast(i32, aExponent -% bExponent) +% scale; // Align the significand of b as a Q31 fixed-point number in the range // [1, 2.0) and get a Q32 approximate reciprocal using a small minimax // polynomial approximation: reciprocal = 3/4 + 1/sqrt(2) - b/2. This // is accurate to about 3.5 binary digits. const q31b: u32 = @truncate(u32, bSignificand >> 21); var recip32 = @as(u32, 0x7504f333) -% q31b; // Now refine the reciprocal estimate using a Newton-Raphson iteration: // // x1 = x0 * (2 - x0 * b) // // This doubles the number of correct binary digits in the approximation // with each iteration, so after three iterations, we have about 28 binary // digits of accuracy. var correction32: u32 = undefined; correction32 = @truncate(u32, ~(@as(u64, recip32) *% q31b >> 32) +% 1); recip32 = @truncate(u32, @as(u64, recip32) *% correction32 >> 31); correction32 = @truncate(u32, ~(@as(u64, recip32) *% q31b >> 32) +% 1); recip32 = @truncate(u32, @as(u64, recip32) *% correction32 >> 31); correction32 = @truncate(u32, ~(@as(u64, recip32) *% q31b >> 32) +% 1); recip32 = @truncate(u32, @as(u64, recip32) *% correction32 >> 31); // recip32 might have overflowed to exactly zero in the preceding // computation if the high word of b is exactly 1.0. This would sabotage // the full-width final stage of the computation that follows, so we adjust // recip32 downward by one bit. recip32 -%= 1; // We need to perform one more iteration to get us to 56 binary digits; // The last iteration needs to happen with extra precision. const q63blo: u32 = @truncate(u32, bSignificand << 11); var correction: u64 = undefined; var reciprocal: u64 = undefined; correction = ~(@as(u64, recip32) *% q31b +% (@as(u64, recip32) *% q63blo >> 32)) +% 1; const cHi = @truncate(u32, correction >> 32); const cLo = @truncate(u32, correction); reciprocal = @as(u64, recip32) *% cHi +% (@as(u64, recip32) *% cLo >> 32); // We already adjusted the 32-bit estimate, now we need to adjust the final // 64-bit reciprocal estimate downward to ensure that it is strictly smaller // than the infinitely precise exact reciprocal. Because the computation // of the Newton-Raphson step is truncating at every step, this adjustment // is small; most of the work is already done. reciprocal -%= 2; // The numerical reciprocal is accurate to within 2^-56, lies in the // interval [0.5, 1.0), and is strictly smaller than the true reciprocal // of b. Multiplying a by this reciprocal thus gives a numerical q = a/b // in Q53 with the following properties: // // 1. q < a/b // 2. q is in the interval [0.5, 2.0) // 3. the error in q is bounded away from 2^-53 (actually, we have a // couple of bits to spare, but this is all we need). // We need a 64 x 64 multiply high to compute q, which isn't a basic // operation in C, so we need to be a little bit fussy. var quotient: Z = undefined; var quotientLo: Z = undefined; wideMultiply(Z, aSignificand << 2, reciprocal, &quotient, &quotientLo); // Two cases: quotient is in [0.5, 1.0) or quotient is in [1.0, 2.0). // In either case, we are going to compute a residual of the form // // r = a - q*b // // We know from the construction of q that r satisfies: // // 0 <= r < ulp(q)*b // // if r is greater than 1/2 ulp(q)*b, then q rounds up. Otherwise, we // already have the correct result. The exact halfway case cannot occur. // We also take this time to right shift quotient if it falls in the [1,2) // range and adjust the exponent accordingly. var residual: Z = undefined; if (quotient < (implicitBit << 1)) { residual = (aSignificand << 53) -% quotient *% bSignificand; quotientExponent -%= 1; } else { quotient >>= 1; residual = (aSignificand << 52) -% quotient *% bSignificand; } const writtenExponent = quotientExponent +% exponentBias; if (writtenExponent >= maxExponent) { // If we have overflowed the exponent, return infinity. return @bitCast(f64, infRep | quotientSign); } else if (writtenExponent < 1) { if (writtenExponent == 0) { // Check whether the rounded result is normal. const round = @boolToInt((residual << 1) > bSignificand); // Clear the implicit bit. var absResult = quotient & significandMask; // Round. absResult += round; if ((absResult & ~significandMask) != 0) { // The rounded result is normal; return it. return @bitCast(f64, absResult | quotientSign); } } // Flush denormals to zero. In the future, it would be nice to add // code to round them correctly. return @bitCast(f64, quotientSign); } else { const round = @boolToInt((residual << 1) > bSignificand); // Clear the implicit bit var absResult = quotient & significandMask; // Insert the exponent absResult |= @bitCast(Z, @as(SignedZ, writtenExponent)) << significandBits; // Round absResult +%= round; // Insert the sign and return return @bitCast(f64, absResult | quotientSign); } } fn wideMultiply(comptime Z: type, a: Z, b: Z, hi: *Z, lo: *Z) void { @setRuntimeSafety(builtin.is_test); switch (Z) { u32 => { // 32x32 --> 64 bit multiply const product = @as(u64, a) * @as(u64, b); hi.* = @truncate(u32, product >> 32); lo.* = @truncate(u32, product); }, u64 => { const S = struct { fn loWord(x: u64) u64 { return @truncate(u32, x); } fn hiWord(x: u64) u64 { return @truncate(u32, x >> 32); } }; // 64x64 -> 128 wide multiply for platforms that don't have such an operation; // many 64-bit platforms have this operation, but they tend to have hardware // floating-point, so we don't bother with a special case for them here. // Each of the component 32x32 -> 64 products const plolo: u64 = S.loWord(a) * S.loWord(b); const plohi: u64 = S.loWord(a) * S.hiWord(b); const philo: u64 = S.hiWord(a) * S.loWord(b); const phihi: u64 = S.hiWord(a) * S.hiWord(b); // Sum terms that contribute to lo in a way that allows us to get the carry const r0: u64 = S.loWord(plolo); const r1: u64 = S.hiWord(plolo) +% S.loWord(plohi) +% S.loWord(philo); lo.* = r0 +% (r1 << 32); // Sum terms contributing to hi with the carry from lo hi.* = S.hiWord(plohi) +% S.hiWord(philo) +% S.hiWord(r1) +% phihi; }, u128 => { const Word_LoMask = @as(u64, 0x00000000ffffffff); const Word_HiMask = @as(u64, 0xffffffff00000000); const Word_FullMask = @as(u64, 0xffffffffffffffff); const S = struct { fn Word_1(x: u128) u64 { return @truncate(u32, x >> 96); } fn Word_2(x: u128) u64 { return @truncate(u32, x >> 64); } fn Word_3(x: u128) u64 { return @truncate(u32, x >> 32); } fn Word_4(x: u128) u64 { return @truncate(u32, x); } }; // 128x128 -> 256 wide multiply for platforms that don't have such an operation; // many 64-bit platforms have this operation, but they tend to have hardware // floating-point, so we don't bother with a special case for them here. const product11: u64 = S.Word_1(a) * S.Word_1(b); const product12: u64 = S.Word_1(a) * S.Word_2(b); const product13: u64 = S.Word_1(a) * S.Word_3(b); const product14: u64 = S.Word_1(a) * S.Word_4(b); const product21: u64 = S.Word_2(a) * S.Word_1(b); const product22: u64 = S.Word_2(a) * S.Word_2(b); const product23: u64 = S.Word_2(a) * S.Word_3(b); const product24: u64 = S.Word_2(a) * S.Word_4(b); const product31: u64 = S.Word_3(a) * S.Word_1(b); const product32: u64 = S.Word_3(a) * S.Word_2(b); const product33: u64 = S.Word_3(a) * S.Word_3(b); const product34: u64 = S.Word_3(a) * S.Word_4(b); const product41: u64 = S.Word_4(a) * S.Word_1(b); const product42: u64 = S.Word_4(a) * S.Word_2(b); const product43: u64 = S.Word_4(a) * S.Word_3(b); const product44: u64 = S.Word_4(a) * S.Word_4(b); const sum0: u128 = @as(u128, product44); const sum1: u128 = @as(u128, product34) +% @as(u128, product43); const sum2: u128 = @as(u128, product24) +% @as(u128, product33) +% @as(u128, product42); const sum3: u128 = @as(u128, product14) +% @as(u128, product23) +% @as(u128, product32) +% @as(u128, product41); const sum4: u128 = @as(u128, product13) +% @as(u128, product22) +% @as(u128, product31); const sum5: u128 = @as(u128, product12) +% @as(u128, product21); const sum6: u128 = @as(u128, product11); const r0: u128 = (sum0 & Word_FullMask) +% ((sum1 & Word_LoMask) << 32); const r1: u128 = (sum0 >> 64) +% ((sum1 >> 32) & Word_FullMask) +% (sum2 & Word_FullMask) +% ((sum3 << 32) & Word_HiMask); lo.* = r0 +% (r1 << 64); hi.* = (r1 >> 64) +% (sum1 >> 96) +% (sum2 >> 64) +% (sum3 >> 32) +% sum4 +% (sum5 << 32) +% (sum6 << 64); }, else => @compileError("unsupported"), } } fn normalize(comptime T: type, significand: *@IntType(false, T.bit_count)) i32 { @setRuntimeSafety(builtin.is_test); const Z = @IntType(false, T.bit_count); const significandBits = std.math.floatMantissaBits(T); const implicitBit = @as(Z, 1) << significandBits; const shift = @clz(Z, significand.*) - @clz(Z, implicitBit); significand.* <<= @intCast(std.math.Log2Int(Z), shift); return 1 - shift; } test "import divdf3" { _ = @import("divdf3_test.zig"); }
lib/std/special/compiler_rt/divdf3.zig
const mem = @import("../mem.zig"); const math = @import("../math.zig"); const endian = @import("../endian.zig"); const debug = @import("../debug.zig"); const builtin = @import("builtin"); const htest = @import("test.zig"); ///////////////////// // Sha224 + Sha256 const RoundParam256 = struct { a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u32, }; fn Rp256(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u32) RoundParam256 { return RoundParam256{ .a = a, .b = b, .c = c, .d = d, .e = e, .f = f, .g = g, .h = h, .i = i, .k = k, }; } const Sha2Params32 = struct { iv0: u32, iv1: u32, iv2: u32, iv3: u32, iv4: u32, iv5: u32, iv6: u32, iv7: u32, out_len: usize, }; const Sha224Params = Sha2Params32{ .iv0 = 0xC1059ED8, .iv1 = 0x367CD507, .iv2 = 0x3070DD17, .iv3 = 0xF70E5939, .iv4 = 0xFFC00B31, .iv5 = 0x68581511, .iv6 = 0x64F98FA7, .iv7 = 0xBEFA4FA4, .out_len = 224, }; const Sha256Params = Sha2Params32{ .iv0 = 0x6A09E667, .iv1 = 0xBB67AE85, .iv2 = 0x3C6EF372, .iv3 = 0xA54FF53A, .iv4 = 0x510E527F, .iv5 = 0x9B05688C, .iv6 = 0x1F83D9AB, .iv7 = 0x5BE0CD19, .out_len = 256, }; pub const Sha224 = Sha2_32(Sha224Params); pub const Sha256 = Sha2_32(Sha256Params); fn Sha2_32(comptime params: Sha2Params32) type { return struct { const Self = @This(); pub const block_length = 64; pub const digest_length = params.out_len / 8; s: [8]u32, // Streaming Cache buf: [64]u8, buf_len: u8, total_len: u64, pub fn init() Self { var d: Self = undefined; d.reset(); return d; } pub fn reset(d: *Self) void { d.s[0] = params.iv0; d.s[1] = params.iv1; d.s[2] = params.iv2; d.s[3] = params.iv3; d.s[4] = params.iv4; d.s[5] = params.iv5; d.s[6] = params.iv6; d.s[7] = params.iv7; d.buf_len = 0; d.total_len = 0; } pub fn hash(b: []const u8, out: []u8) void { var d = Self.init(); d.update(b); d.final(out); } pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. if (d.buf_len != 0 and d.buf_len + b.len > 64) { off += 64 - d.buf_len; mem.copy(u8, d.buf[d.buf_len..], b[0..off]); d.round(d.buf[0..]); d.buf_len = 0; } // Full middle blocks. while (off + 64 <= b.len) : (off += 64) { d.round(b[off .. off + 64]); } // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= params.out_len / 8); // The buffer here will never be completely full. mem.set(u8, d.buf[d.buf_len..], 0); // Append padding bits. d.buf[d.buf_len] = 0x80; d.buf_len += 1; // > 448 mod 512 so need to add an extra round to wrap around. if (64 - d.buf_len < 8) { d.round(d.buf[0..]); mem.set(u8, d.buf[0..], 0); } // Append message length. var i: usize = 1; var len = d.total_len >> 5; d.buf[63] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 8) : (i += 1) { d.buf[63 - i] = @intCast(u8, len & 0xff); len >>= 8; } d.round(d.buf[0..]); // May truncate for possible 224 output const rr = d.s[0 .. params.out_len / 32]; for (rr) |s, j| { // TODO https://github.com/ziglang/zig/issues/863 mem.writeIntSliceBig(u32, out[4 * j .. 4 * j + 4], s); } } fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 64); var s: [64]u32 = undefined; var i: usize = 0; while (i < 16) : (i += 1) { s[i] = 0; s[i] |= @as(u32, b[i * 4 + 0]) << 24; s[i] |= @as(u32, b[i * 4 + 1]) << 16; s[i] |= @as(u32, b[i * 4 + 2]) << 8; s[i] |= @as(u32, b[i * 4 + 3]) << 0; } while (i < 64) : (i += 1) { s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u32, s[i - 15], @as(u32, 7)) ^ math.rotr(u32, s[i - 15], @as(u32, 18)) ^ (s[i - 15] >> 3)) +% (math.rotr(u32, s[i - 2], @as(u32, 17)) ^ math.rotr(u32, s[i - 2], @as(u32, 19)) ^ (s[i - 2] >> 10)); } var v: [8]u32 = [_]u32{ d.s[0], d.s[1], d.s[2], d.s[3], d.s[4], d.s[5], d.s[6], d.s[7], }; const round0 = comptime [_]RoundParam256{ Rp256(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x71374491), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCF), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA5), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25B), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B01), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A7), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C1), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC6), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DC), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C8), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF3), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x14292967), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A85), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B2138), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D13), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A7354), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C85), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A1), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664B), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A3), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD6990624), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E3585), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA070), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C08), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774C), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4A), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3), Rp256(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE), Rp256(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F), Rp256(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814), Rp256(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC70208), Rp256(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA), Rp256(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEB), Rp256(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7), Rp256(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2), }; inline for (round0) |r| { v[r.h] = v[r.h] +% (math.rotr(u32, v[r.e], @as(u32, 6)) ^ math.rotr(u32, v[r.e], @as(u32, 11)) ^ math.rotr(u32, v[r.e], @as(u32, 25))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i]; v[r.d] = v[r.d] +% v[r.h]; v[r.h] = v[r.h] +% (math.rotr(u32, v[r.a], @as(u32, 2)) ^ math.rotr(u32, v[r.a], @as(u32, 13)) ^ math.rotr(u32, v[r.a], @as(u32, 22))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c])); } d.s[0] +%= v[0]; d.s[1] +%= v[1]; d.s[2] +%= v[2]; d.s[3] +%= v[3]; d.s[4] +%= v[4]; d.s[5] +%= v[5]; d.s[6] +%= v[6]; d.s[7] +%= v[7]; } }; } test "sha224 single" { htest.assertEqualHash(Sha224, "d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", ""); htest.assertEqualHash(Sha224, "23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", "abc"); htest.assertEqualHash(Sha224, "c97ca9a559850ce97a04a96def6d99a9e0e0e2ab14e6b8df265fc0b3", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha224 streaming" { var h = Sha224.init(); var out: [28]u8 = undefined; h.final(out[0..]); htest.assertEqual("d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", out[0..]); h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual("23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", out[0..]); } test "sha256 single" { htest.assertEqualHash(Sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ""); htest.assertEqualHash(Sha256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc"); htest.assertEqualHash(Sha256, "cf5b16a778af8380036ce59e7b0492370b249b11e8f07a51afac45037afee9d1", "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha256 streaming" { var h = Sha256.init(); var out: [32]u8 = undefined; h.final(out[0..]); htest.assertEqual("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", out[0..]); h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", out[0..]); } test "sha256 aligned final" { var block = [_]u8{0} ** Sha256.block_length; var out: [Sha256.digest_length]u8 = undefined; var h = Sha256.init(); h.update(block); h.final(out[0..]); } ///////////////////// // Sha384 + Sha512 const RoundParam512 = struct { a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u64, }; fn Rp512(a: usize, b: usize, c: usize, d: usize, e: usize, f: usize, g: usize, h: usize, i: usize, k: u64) RoundParam512 { return RoundParam512{ .a = a, .b = b, .c = c, .d = d, .e = e, .f = f, .g = g, .h = h, .i = i, .k = k, }; } const Sha2Params64 = struct { iv0: u64, iv1: u64, iv2: u64, iv3: u64, iv4: u64, iv5: u64, iv6: u64, iv7: u64, out_len: usize, }; const Sha384Params = Sha2Params64{ .iv0 = 0xCBBB9D5DC1059ED8, .iv1 = 0x629A292A367CD507, .iv2 = 0x9159015A3070DD17, .iv3 = 0x152FECD8F70E5939, .iv4 = 0x67332667FFC00B31, .iv5 = 0x8EB44A8768581511, .iv6 = 0xDB0C2E0D64F98FA7, .iv7 = 0x47B5481DBEFA4FA4, .out_len = 384, }; const Sha512Params = Sha2Params64{ .iv0 = 0x6A09E667F3BCC908, .iv1 = 0xBB67AE8584CAA73B, .iv2 = 0x3C6EF372FE94F82B, .iv3 = 0xA54FF53A5F1D36F1, .iv4 = 0x510E527FADE682D1, .iv5 = 0x9B05688C2B3E6C1F, .iv6 = 0x1F83D9ABFB41BD6B, .iv7 = 0x5BE0CD19137E2179, .out_len = 512, }; pub const Sha384 = Sha2_64(Sha384Params); pub const Sha512 = Sha2_64(Sha512Params); fn Sha2_64(comptime params: Sha2Params64) type { return struct { const Self = @This(); pub const block_length = 128; pub const digest_length = params.out_len / 8; s: [8]u64, // Streaming Cache buf: [128]u8, buf_len: u8, total_len: u128, pub fn init() Self { var d: Self = undefined; d.reset(); return d; } pub fn reset(d: *Self) void { d.s[0] = params.iv0; d.s[1] = params.iv1; d.s[2] = params.iv2; d.s[3] = params.iv3; d.s[4] = params.iv4; d.s[5] = params.iv5; d.s[6] = params.iv6; d.s[7] = params.iv7; d.buf_len = 0; d.total_len = 0; } pub fn hash(b: []const u8, out: []u8) void { var d = Self.init(); d.update(b); d.final(out); } pub fn update(d: *Self, b: []const u8) void { var off: usize = 0; // Partial buffer exists from previous update. Copy into buffer then hash. if (d.buf_len != 0 and d.buf_len + b.len > 128) { off += 128 - d.buf_len; mem.copy(u8, d.buf[d.buf_len..], b[0..off]); d.round(d.buf[0..]); d.buf_len = 0; } // Full middle blocks. while (off + 128 <= b.len) : (off += 128) { d.round(b[off .. off + 128]); } // Copy any remainder for next pass. mem.copy(u8, d.buf[d.buf_len..], b[off..]); d.buf_len += @intCast(u8, b[off..].len); d.total_len += b.len; } pub fn final(d: *Self, out: []u8) void { debug.assert(out.len >= params.out_len / 8); // The buffer here will never be completely full. mem.set(u8, d.buf[d.buf_len..], 0); // Append padding bits. d.buf[d.buf_len] = 0x80; d.buf_len += 1; // > 896 mod 1024 so need to add an extra round to wrap around. if (128 - d.buf_len < 16) { d.round(d.buf[0..]); mem.set(u8, d.buf[0..], 0); } // Append message length. var i: usize = 1; var len = d.total_len >> 5; d.buf[127] = @intCast(u8, d.total_len & 0x1f) << 3; while (i < 16) : (i += 1) { d.buf[127 - i] = @intCast(u8, len & 0xff); len >>= 8; } d.round(d.buf[0..]); // May truncate for possible 384 output const rr = d.s[0 .. params.out_len / 64]; for (rr) |s, j| { // TODO https://github.com/ziglang/zig/issues/863 mem.writeIntSliceBig(u64, out[8 * j .. 8 * j + 8], s); } } fn round(d: *Self, b: []const u8) void { debug.assert(b.len == 128); var s: [80]u64 = undefined; var i: usize = 0; while (i < 16) : (i += 1) { s[i] = 0; s[i] |= @as(u64, b[i * 8 + 0]) << 56; s[i] |= @as(u64, b[i * 8 + 1]) << 48; s[i] |= @as(u64, b[i * 8 + 2]) << 40; s[i] |= @as(u64, b[i * 8 + 3]) << 32; s[i] |= @as(u64, b[i * 8 + 4]) << 24; s[i] |= @as(u64, b[i * 8 + 5]) << 16; s[i] |= @as(u64, b[i * 8 + 6]) << 8; s[i] |= @as(u64, b[i * 8 + 7]) << 0; } while (i < 80) : (i += 1) { s[i] = s[i - 16] +% s[i - 7] +% (math.rotr(u64, s[i - 15], @as(u64, 1)) ^ math.rotr(u64, s[i - 15], @as(u64, 8)) ^ (s[i - 15] >> 7)) +% (math.rotr(u64, s[i - 2], @as(u64, 19)) ^ math.rotr(u64, s[i - 2], @as(u64, 61)) ^ (s[i - 2] >> 6)); } var v: [8]u64 = [_]u64{ d.s[0], d.s[1], d.s[2], d.s[3], d.s[4], d.s[5], d.s[6], d.s[7], }; const round0 = comptime [_]RoundParam512{ Rp512(0, 1, 2, 3, 4, 5, 6, 7, 0, 0x428A2F98D728AE22), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 1, 0x7137449123EF65CD), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 2, 0xB5C0FBCFEC4D3B2F), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 3, 0xE9B5DBA58189DBBC), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 4, 0x3956C25BF348B538), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 5, 0x59F111F1B605D019), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 6, 0x923F82A4AF194F9B), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 7, 0xAB1C5ED5DA6D8118), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 8, 0xD807AA98A3030242), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 9, 0x12835B0145706FBE), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 10, 0x243185BE4EE4B28C), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 11, 0x550C7DC3D5FFB4E2), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 12, 0x72BE5D74F27B896F), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 13, 0x80DEB1FE3B1696B1), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 14, 0x9BDC06A725C71235), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 15, 0xC19BF174CF692694), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 16, 0xE49B69C19EF14AD2), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 17, 0xEFBE4786384F25E3), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 18, 0x0FC19DC68B8CD5B5), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 19, 0x240CA1CC77AC9C65), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 20, 0x2DE92C6F592B0275), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 21, 0x4A7484AA6EA6E483), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 22, 0x5CB0A9DCBD41FBD4), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 23, 0x76F988DA831153B5), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 24, 0x983E5152EE66DFAB), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 25, 0xA831C66D2DB43210), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 26, 0xB00327C898FB213F), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 27, 0xBF597FC7BEEF0EE4), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 28, 0xC6E00BF33DA88FC2), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 29, 0xD5A79147930AA725), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 30, 0x06CA6351E003826F), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 31, 0x142929670A0E6E70), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 32, 0x27B70A8546D22FFC), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 33, 0x2E1B21385C26C926), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 34, 0x4D2C6DFC5AC42AED), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 35, 0x53380D139D95B3DF), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 36, 0x650A73548BAF63DE), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 37, 0x766A0ABB3C77B2A8), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 38, 0x81C2C92E47EDAEE6), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 39, 0x92722C851482353B), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 40, 0xA2BFE8A14CF10364), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 41, 0xA81A664BBC423001), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 42, 0xC24B8B70D0F89791), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 43, 0xC76C51A30654BE30), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 44, 0xD192E819D6EF5218), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 45, 0xD69906245565A910), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 46, 0xF40E35855771202A), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 47, 0x106AA07032BBD1B8), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 48, 0x19A4C116B8D2D0C8), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 49, 0x1E376C085141AB53), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 50, 0x2748774CDF8EEB99), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 51, 0x34B0BCB5E19B48A8), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 52, 0x391C0CB3C5C95A63), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 53, 0x4ED8AA4AE3418ACB), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 54, 0x5B9CCA4F7763E373), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 55, 0x682E6FF3D6B2B8A3), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 56, 0x748F82EE5DEFB2FC), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 57, 0x78A5636F43172F60), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 58, 0x84C87814A1F0AB72), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 59, 0x8CC702081A6439EC), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 60, 0x90BEFFFA23631E28), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 61, 0xA4506CEBDE82BDE9), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 62, 0xBEF9A3F7B2C67915), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 63, 0xC67178F2E372532B), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 64, 0xCA273ECEEA26619C), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 65, 0xD186B8C721C0C207), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 66, 0xEADA7DD6CDE0EB1E), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 67, 0xF57D4F7FEE6ED178), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 68, 0x06F067AA72176FBA), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 69, 0x0A637DC5A2C898A6), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 70, 0x113F9804BEF90DAE), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 71, 0x1B710B35131C471B), Rp512(0, 1, 2, 3, 4, 5, 6, 7, 72, 0x28DB77F523047D84), Rp512(7, 0, 1, 2, 3, 4, 5, 6, 73, 0x32CAAB7B40C72493), Rp512(6, 7, 0, 1, 2, 3, 4, 5, 74, 0x3C9EBE0A15C9BEBC), Rp512(5, 6, 7, 0, 1, 2, 3, 4, 75, 0x431D67C49C100D4C), Rp512(4, 5, 6, 7, 0, 1, 2, 3, 76, 0x4CC5D4BECB3E42B6), Rp512(3, 4, 5, 6, 7, 0, 1, 2, 77, 0x597F299CFC657E2A), Rp512(2, 3, 4, 5, 6, 7, 0, 1, 78, 0x5FCB6FAB3AD6FAEC), Rp512(1, 2, 3, 4, 5, 6, 7, 0, 79, 0x6C44198C4A475817), }; inline for (round0) |r| { v[r.h] = v[r.h] +% (math.rotr(u64, v[r.e], @as(u64, 14)) ^ math.rotr(u64, v[r.e], @as(u64, 18)) ^ math.rotr(u64, v[r.e], @as(u64, 41))) +% (v[r.g] ^ (v[r.e] & (v[r.f] ^ v[r.g]))) +% r.k +% s[r.i]; v[r.d] = v[r.d] +% v[r.h]; v[r.h] = v[r.h] +% (math.rotr(u64, v[r.a], @as(u64, 28)) ^ math.rotr(u64, v[r.a], @as(u64, 34)) ^ math.rotr(u64, v[r.a], @as(u64, 39))) +% ((v[r.a] & (v[r.b] | v[r.c])) | (v[r.b] & v[r.c])); } d.s[0] +%= v[0]; d.s[1] +%= v[1]; d.s[2] +%= v[2]; d.s[3] +%= v[3]; d.s[4] +%= v[4]; d.s[5] +%= v[5]; d.s[6] +%= v[6]; d.s[7] +%= v[7]; } }; } test "sha384 single" { const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"; htest.assertEqualHash(Sha384, h1, ""); const h2 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"; htest.assertEqualHash(Sha384, h2, "abc"); const h3 = "09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712fcc7c71a557e2db966c3e9fa91746039"; htest.assertEqualHash(Sha384, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha384 streaming" { var h = Sha384.init(); var out: [48]u8 = undefined; const h1 = "38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7"; h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); } test "sha512 single" { const h1 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; htest.assertEqualHash(Sha512, h1, ""); const h2 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; htest.assertEqualHash(Sha512, h2, "abc"); const h3 = "8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909"; htest.assertEqualHash(Sha512, h3, "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu"); } test "sha512 streaming" { var h = Sha512.init(); var out: [64]u8 = undefined; const h1 = "cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"; h.final(out[0..]); htest.assertEqual(h1, out[0..]); const h2 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f"; h.reset(); h.update("abc"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); h.reset(); h.update("a"); h.update("b"); h.update("c"); h.final(out[0..]); htest.assertEqual(h2, out[0..]); } test "sha512 aligned final" { var block = [_]u8{0} ** Sha512.block_length; var out: [Sha512.digest_length]u8 = undefined; var h = Sha512.init(); h.update(block); h.final(out[0..]); }
lib/std/crypto/sha2.zig
const std = @import("../std.zig"); const Allocator = std.mem.Allocator; /// This allocator is used in front of another allocator and logs to the provided stream /// on every call to the allocator. Stream errors are ignored. /// If https://github.com/ziglang/zig/issues/2586 is implemented, this API can be improved. pub fn LoggingAllocator(comptime OutStreamType: type) type { return struct { allocator: Allocator, parent_allocator: *Allocator, out_stream: OutStreamType, const Self = @This(); pub fn init(parent_allocator: *Allocator, out_stream: OutStreamType) Self { return Self{ .allocator = Allocator{ .allocFn = alloc, .resizeFn = resize, }, .parent_allocator = parent_allocator, .out_stream = out_stream, }; } fn alloc( allocator: *Allocator, len: usize, ptr_align: u29, len_align: u29, ra: usize, ) error{OutOfMemory}![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); self.out_stream.print("alloc : {}", .{len}) catch {}; const result = self.parent_allocator.allocFn(self.parent_allocator, len, ptr_align, len_align, ra); if (result) |buff| { self.out_stream.print(" success!\n", .{}) catch {}; } else |err| { self.out_stream.print(" failure!\n", .{}) catch {}; } return result; } fn resize( allocator: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ra: usize, ) error{OutOfMemory}!usize { const self = @fieldParentPtr(Self, "allocator", allocator); if (new_len == 0) { self.out_stream.print("free : {}\n", .{buf.len}) catch {}; } else if (new_len <= buf.len) { self.out_stream.print("shrink: {} to {}\n", .{ buf.len, new_len }) catch {}; } else { self.out_stream.print("expand: {} to {}", .{ buf.len, new_len }) catch {}; } if (self.parent_allocator.resizeFn(self.parent_allocator, buf, buf_align, new_len, len_align, ra)) |resized_len| { if (new_len > buf.len) { self.out_stream.print(" success!\n", .{}) catch {}; } return resized_len; } else |e| { std.debug.assert(new_len > buf.len); self.out_stream.print(" failure!\n", .{}) catch {}; return e; } } }; } pub fn loggingAllocator( parent_allocator: *Allocator, out_stream: anytype, ) LoggingAllocator(@TypeOf(out_stream)) { return LoggingAllocator(@TypeOf(out_stream)).init(parent_allocator, out_stream); } test "LoggingAllocator" { var log_buf: [255]u8 = undefined; var fbs = std.io.fixedBufferStream(&log_buf); var allocator_buf: [10]u8 = undefined; var fixedBufferAllocator = std.mem.validationWrap(std.heap.FixedBufferAllocator.init(&allocator_buf)); const allocator = &loggingAllocator(&fixedBufferAllocator.allocator, fbs.outStream()).allocator; var a = try allocator.alloc(u8, 10); a = allocator.shrink(a, 5); std.testing.expect(a.len == 5); std.testing.expectError(error.OutOfMemory, allocator.resize(a, 20)); allocator.free(a); std.testing.expectEqualSlices(u8, \\alloc : 10 success! \\shrink: 10 to 5 \\expand: 5 to 20 failure! \\free : 5 \\ , fbs.getWritten()); }
lib/std/heap/logging_allocator.zig
const std = @import("std"); const Builder = std.build.Builder; const ft_root = thisDir() ++ "/upstream/freetype"; const ft_include_path = ft_root ++ "/include"; pub fn build(b: *std.build.Builder) !void { const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); const dedicated_tests = b.addTest("src/main.zig"); dedicated_tests.setBuildMode(mode); dedicated_tests.setTarget(target); dedicated_tests.addPackage(pkg); link(b, dedicated_tests, .{}); const main_tests = b.addTest("test/main.zig"); main_tests.setBuildMode(mode); main_tests.setTarget(target); main_tests.addPackage(pkg); link(b, main_tests, .{ .custom_config_path = "./test/ft" }); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&dedicated_tests.step); test_step.dependOn(&main_tests.step); inline for ([_][]const u8{ "single-glyph", "glyph-to-svg", }) |example| { const example_exe = b.addExecutable("example-" ++ example, "examples/" ++ example ++ ".zig"); example_exe.setBuildMode(mode); example_exe.setTarget(target); example_exe.addPackage(pkg); link(b, example_exe, .{}); example_exe.install(); const example_compile_step = b.step("example-" ++ example, "Compile '" ++ example ++ "' example"); example_compile_step.dependOn(b.getInstallStep()); const example_run_cmd = example_exe.run(); example_run_cmd.step.dependOn(b.getInstallStep()); const example_run_step = b.step("run-example-" ++ example, "Run '" ++ example ++ "' example"); example_run_step.dependOn(&example_run_cmd.step); } } pub const Options = struct { /// the path you specify freetype options /// via `ftoptions.h` and `ftmodule.h` /// e.g `test/ft/` custom_config_path: ?[]const u8 = null, }; pub const pkg = std.build.Pkg{ .name = "freetype", .source = .{ .path = thisDir() ++ "/src/main.zig" }, }; pub fn link(b: *Builder, step: *std.build.LibExeObjStep, options: Options) void { const lib = buildLibrary(b, step, options); step.linkLibrary(lib); if (options.custom_config_path) |path| step.addIncludePath(path); step.addIncludePath(ft_include_path); } pub fn buildLibrary(b: *Builder, step: *std.build.LibExeObjStep, options: Options) *std.build.LibExeObjStep { const main_abs = ft_root ++ "/src/base/ftbase.c"; // TODO(build-system): https://github.com/hexops/mach/issues/229#issuecomment-1100958939 ensureDependencySubmodule(b.allocator, "upstream") catch unreachable; const lib = b.addStaticLibrary("freetype", main_abs); lib.defineCMacro("FT2_BUILD_LIBRARY", "1"); lib.setBuildMode(step.build_mode); lib.setTarget(step.target); lib.linkLibC(); lib.addIncludePath(ft_include_path); if (options.custom_config_path) |path| lib.addIncludePath(path); const target = (std.zig.system.NativeTargetInfo.detect(b.allocator, step.target) catch unreachable).target; if (target.os.tag == .windows) { lib.addCSourceFile(ft_root ++ "/builds/windows/ftsystem.c", &.{}); lib.addCSourceFile(ft_root ++ "/builds/windows/ftdebug.c", &.{}); } else { lib.addCSourceFile(ft_root ++ "/src/base/ftsystem.c", &.{}); lib.addCSourceFile(ft_root ++ "/src/base/ftdebug.c", &.{}); } if (target.os.tag.isBSD() or target.os.tag == .linux) { lib.defineCMacro("HAVE_UNISTD_H", "1"); lib.defineCMacro("HAVE_FCNTL_H", "1"); lib.addCSourceFile(ft_root ++ "/builds/unix/ftsystem.c", &.{}); if (target.os.tag == .macos) { lib.addCSourceFile(ft_root ++ "/src/base/ftmac.c", &.{}); } } lib.addCSourceFiles(freetype_base_sources, &.{}); lib.install(); return lib; } fn thisDir() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } fn ensureDependencySubmodule(allocator: std.mem.Allocator, path: []const u8) !void { if (std.process.getEnvVarOwned(allocator, "NO_ENSURE_SUBMODULES")) |no_ensure_submodules| { if (std.mem.eql(u8, no_ensure_submodules, "true")) return; } else |_| {} var child = std.ChildProcess.init(&.{ "git", "submodule", "update", "--init", path }, allocator); child.cwd = thisDir(); child.stderr = std.io.getStdErr(); child.stdout = std.io.getStdOut(); _ = try child.spawnAndWait(); } const freetype_base_sources = &[_][]const u8{ ft_root ++ "/src/autofit/autofit.c", ft_root ++ "/src/base/ftbbox.c", ft_root ++ "/src/base/ftbdf.c", ft_root ++ "/src/base/ftbitmap.c", ft_root ++ "/src/base/ftcid.c", ft_root ++ "/src/base/ftfstype.c", ft_root ++ "/src/base/ftgasp.c", ft_root ++ "/src/base/ftglyph.c", ft_root ++ "/src/base/ftgxval.c", ft_root ++ "/src/base/ftinit.c", ft_root ++ "/src/base/ftmm.c", ft_root ++ "/src/base/ftotval.c", ft_root ++ "/src/base/ftpatent.c", ft_root ++ "/src/base/ftpfr.c", ft_root ++ "/src/base/ftstroke.c", ft_root ++ "/src/base/ftsynth.c", ft_root ++ "/src/base/fttype1.c", ft_root ++ "/src/base/ftwinfnt.c", ft_root ++ "/src/bdf/bdf.c", ft_root ++ "/src/bzip2/ftbzip2.c", ft_root ++ "/src/cache/ftcache.c", ft_root ++ "/src/cff/cff.c", ft_root ++ "/src/cid/type1cid.c", ft_root ++ "/src/gzip/ftgzip.c", ft_root ++ "/src/lzw/ftlzw.c", ft_root ++ "/src/pcf/pcf.c", ft_root ++ "/src/pfr/pfr.c", ft_root ++ "/src/psaux/psaux.c", ft_root ++ "/src/pshinter/pshinter.c", ft_root ++ "/src/psnames/psnames.c", ft_root ++ "/src/raster/raster.c", ft_root ++ "/src/sdf/sdf.c", ft_root ++ "/src/sfnt/sfnt.c", ft_root ++ "/src/smooth/smooth.c", ft_root ++ "/src/svg/svg.c", ft_root ++ "/src/truetype/truetype.c", ft_root ++ "/src/type1/type1.c", ft_root ++ "/src/type42/type42.c", ft_root ++ "/src/winfonts/winfnt.c", };
freetype/build.zig
const std = @import("../../../std.zig"); const pid_t = linux.pid_t; const uid_t = linux.uid_t; const clock_t = linux.clock_t; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; const linux = std.os.linux; const sockaddr = linux.sockaddr; const socklen_t = linux.socklen_t; const iovec = linux.iovec; const iovec_const = linux.iovec_const; pub const SYS_read = 0; pub const SYS_write = 1; pub const SYS_open = 2; pub const SYS_close = 3; pub const SYS_stat = 4; pub const SYS_fstat = 5; pub const SYS_lstat = 6; pub const SYS_poll = 7; pub const SYS_lseek = 8; pub const SYS_mmap = 9; pub const SYS_mprotect = 10; pub const SYS_munmap = 11; pub const SYS_brk = 12; pub const SYS_rt_sigaction = 13; pub const SYS_rt_sigprocmask = 14; pub const SYS_rt_sigreturn = 15; pub const SYS_ioctl = 16; pub const SYS_pread = 17; pub const SYS_pwrite = 18; pub const SYS_readv = 19; pub const SYS_writev = 20; pub const SYS_access = 21; pub const SYS_pipe = 22; pub const SYS_select = 23; pub const SYS_sched_yield = 24; pub const SYS_mremap = 25; pub const SYS_msync = 26; pub const SYS_mincore = 27; pub const SYS_madvise = 28; pub const SYS_shmget = 29; pub const SYS_shmat = 30; pub const SYS_shmctl = 31; pub const SYS_dup = 32; pub const SYS_dup2 = 33; pub const SYS_pause = 34; pub const SYS_nanosleep = 35; pub const SYS_getitimer = 36; pub const SYS_alarm = 37; pub const SYS_setitimer = 38; pub const SYS_getpid = 39; pub const SYS_sendfile = 40; pub const SYS_socket = 41; pub const SYS_connect = 42; pub const SYS_accept = 43; pub const SYS_sendto = 44; pub const SYS_recvfrom = 45; pub const SYS_sendmsg = 46; pub const SYS_recvmsg = 47; pub const SYS_shutdown = 48; pub const SYS_bind = 49; pub const SYS_listen = 50; pub const SYS_getsockname = 51; pub const SYS_getpeername = 52; pub const SYS_socketpair = 53; pub const SYS_setsockopt = 54; pub const SYS_getsockopt = 55; pub const SYS_clone = 56; pub const SYS_fork = 57; pub const SYS_vfork = 58; pub const SYS_execve = 59; pub const SYS_exit = 60; pub const SYS_wait4 = 61; pub const SYS_kill = 62; pub const SYS_uname = 63; pub const SYS_semget = 64; pub const SYS_semop = 65; pub const SYS_semctl = 66; pub const SYS_shmdt = 67; pub const SYS_msgget = 68; pub const SYS_msgsnd = 69; pub const SYS_msgrcv = 70; pub const SYS_msgctl = 71; pub const SYS_fcntl = 72; pub const SYS_flock = 73; pub const SYS_fsync = 74; pub const SYS_fdatasync = 75; pub const SYS_truncate = 76; pub const SYS_ftruncate = 77; pub const SYS_getdents = 78; pub const SYS_getcwd = 79; pub const SYS_chdir = 80; pub const SYS_fchdir = 81; pub const SYS_rename = 82; pub const SYS_mkdir = 83; pub const SYS_rmdir = 84; pub const SYS_creat = 85; pub const SYS_link = 86; pub const SYS_unlink = 87; pub const SYS_symlink = 88; pub const SYS_readlink = 89; pub const SYS_chmod = 90; pub const SYS_fchmod = 91; pub const SYS_chown = 92; pub const SYS_fchown = 93; pub const SYS_lchown = 94; pub const SYS_umask = 95; pub const SYS_gettimeofday = 96; pub const SYS_getrlimit = 97; pub const SYS_getrusage = 98; pub const SYS_sysinfo = 99; pub const SYS_times = 100; pub const SYS_ptrace = 101; pub const SYS_getuid = 102; pub const SYS_syslog = 103; pub const SYS_getgid = 104; pub const SYS_setuid = 105; pub const SYS_setgid = 106; pub const SYS_geteuid = 107; pub const SYS_getegid = 108; pub const SYS_setpgid = 109; pub const SYS_getppid = 110; pub const SYS_getpgrp = 111; pub const SYS_setsid = 112; pub const SYS_setreuid = 113; pub const SYS_setregid = 114; pub const SYS_getgroups = 115; pub const SYS_setgroups = 116; pub const SYS_setresuid = 117; pub const SYS_getresuid = 118; pub const SYS_setresgid = 119; pub const SYS_getresgid = 120; pub const SYS_getpgid = 121; pub const SYS_setfsuid = 122; pub const SYS_setfsgid = 123; pub const SYS_getsid = 124; pub const SYS_capget = 125; pub const SYS_capset = 126; pub const SYS_rt_sigpending = 127; pub const SYS_rt_sigtimedwait = 128; pub const SYS_rt_sigqueueinfo = 129; pub const SYS_rt_sigsuspend = 130; pub const SYS_sigaltstack = 131; pub const SYS_utime = 132; pub const SYS_mknod = 133; pub const SYS_uselib = 134; pub const SYS_personality = 135; pub const SYS_ustat = 136; pub const SYS_statfs = 137; pub const SYS_fstatfs = 138; pub const SYS_sysfs = 139; pub const SYS_getpriority = 140; pub const SYS_setpriority = 141; pub const SYS_sched_setparam = 142; pub const SYS_sched_getparam = 143; pub const SYS_sched_setscheduler = 144; pub const SYS_sched_getscheduler = 145; pub const SYS_sched_get_priority_max = 146; pub const SYS_sched_get_priority_min = 147; pub const SYS_sched_rr_get_interval = 148; pub const SYS_mlock = 149; pub const SYS_munlock = 150; pub const SYS_mlockall = 151; pub const SYS_munlockall = 152; pub const SYS_vhangup = 153; pub const SYS_modify_ldt = 154; pub const SYS_pivot_root = 155; pub const SYS__sysctl = 156; pub const SYS_prctl = 157; pub const SYS_arch_prctl = 158; pub const SYS_adjtimex = 159; pub const SYS_setrlimit = 160; pub const SYS_chroot = 161; pub const SYS_sync = 162; pub const SYS_acct = 163; pub const SYS_settimeofday = 164; pub const SYS_mount = 165; pub const SYS_umount2 = 166; pub const SYS_swapon = 167; pub const SYS_swapoff = 168; pub const SYS_reboot = 169; pub const SYS_sethostname = 170; pub const SYS_setdomainname = 171; pub const SYS_iopl = 172; pub const SYS_ioperm = 173; pub const SYS_create_module = 174; pub const SYS_init_module = 175; pub const SYS_delete_module = 176; pub const SYS_get_kernel_syms = 177; pub const SYS_query_module = 178; pub const SYS_quotactl = 179; pub const SYS_nfsservctl = 180; pub const SYS_getpmsg = 181; pub const SYS_putpmsg = 182; pub const SYS_afs_syscall = 183; pub const SYS_tuxcall = 184; pub const SYS_security = 185; pub const SYS_gettid = 186; pub const SYS_readahead = 187; pub const SYS_setxattr = 188; pub const SYS_lsetxattr = 189; pub const SYS_fsetxattr = 190; pub const SYS_getxattr = 191; pub const SYS_lgetxattr = 192; pub const SYS_fgetxattr = 193; pub const SYS_listxattr = 194; pub const SYS_llistxattr = 195; pub const SYS_flistxattr = 196; pub const SYS_removexattr = 197; pub const SYS_lremovexattr = 198; pub const SYS_fremovexattr = 199; pub const SYS_tkill = 200; pub const SYS_time = 201; pub const SYS_futex = 202; pub const SYS_sched_setaffinity = 203; pub const SYS_sched_getaffinity = 204; pub const SYS_set_thread_area = 205; pub const SYS_io_setup = 206; pub const SYS_io_destroy = 207; pub const SYS_io_getevents = 208; pub const SYS_io_submit = 209; pub const SYS_io_cancel = 210; pub const SYS_get_thread_area = 211; pub const SYS_lookup_dcookie = 212; pub const SYS_epoll_create = 213; pub const SYS_epoll_ctl_old = 214; pub const SYS_epoll_wait_old = 215; pub const SYS_remap_file_pages = 216; pub const SYS_getdents64 = 217; pub const SYS_set_tid_address = 218; pub const SYS_restart_syscall = 219; pub const SYS_semtimedop = 220; pub const SYS_fadvise64 = 221; pub const SYS_timer_create = 222; pub const SYS_timer_settime = 223; pub const SYS_timer_gettime = 224; pub const SYS_timer_getoverrun = 225; pub const SYS_timer_delete = 226; pub const SYS_clock_settime = 227; pub const SYS_clock_gettime = 228; pub const SYS_clock_getres = 229; pub const SYS_clock_nanosleep = 230; pub const SYS_exit_group = 231; pub const SYS_epoll_wait = 232; pub const SYS_epoll_ctl = 233; pub const SYS_tgkill = 234; pub const SYS_utimes = 235; pub const SYS_vserver = 236; pub const SYS_mbind = 237; pub const SYS_set_mempolicy = 238; pub const SYS_get_mempolicy = 239; pub const SYS_mq_open = 240; pub const SYS_mq_unlink = 241; pub const SYS_mq_timedsend = 242; pub const SYS_mq_timedreceive = 243; pub const SYS_mq_notify = 244; pub const SYS_mq_getsetattr = 245; pub const SYS_kexec_load = 246; pub const SYS_waitid = 247; pub const SYS_add_key = 248; pub const SYS_request_key = 249; pub const SYS_keyctl = 250; pub const SYS_ioprio_set = 251; pub const SYS_ioprio_get = 252; pub const SYS_inotify_init = 253; pub const SYS_inotify_add_watch = 254; pub const SYS_inotify_rm_watch = 255; pub const SYS_migrate_pages = 256; pub const SYS_openat = 257; pub const SYS_mkdirat = 258; pub const SYS_mknodat = 259; pub const SYS_fchownat = 260; pub const SYS_futimesat = 261; pub const SYS_newfstatat = 262; pub const SYS_fstatat = 262; pub const SYS_unlinkat = 263; pub const SYS_renameat = 264; pub const SYS_linkat = 265; pub const SYS_symlinkat = 266; pub const SYS_readlinkat = 267; pub const SYS_fchmodat = 268; pub const SYS_faccessat = 269; pub const SYS_pselect6 = 270; pub const SYS_ppoll = 271; pub const SYS_unshare = 272; pub const SYS_set_robust_list = 273; pub const SYS_get_robust_list = 274; pub const SYS_splice = 275; pub const SYS_tee = 276; pub const SYS_sync_file_range = 277; pub const SYS_vmsplice = 278; pub const SYS_move_pages = 279; pub const SYS_utimensat = 280; pub const SYS_epoll_pwait = 281; pub const SYS_signalfd = 282; pub const SYS_timerfd_create = 283; pub const SYS_eventfd = 284; pub const SYS_fallocate = 285; pub const SYS_timerfd_settime = 286; pub const SYS_timerfd_gettime = 287; pub const SYS_accept4 = 288; pub const SYS_signalfd4 = 289; pub const SYS_eventfd2 = 290; pub const SYS_epoll_create1 = 291; pub const SYS_dup3 = 292; pub const SYS_pipe2 = 293; pub const SYS_inotify_init1 = 294; pub const SYS_preadv = 295; pub const SYS_pwritev = 296; pub const SYS_rt_tgsigqueueinfo = 297; pub const SYS_perf_event_open = 298; pub const SYS_recvmmsg = 299; pub const SYS_fanotify_init = 300; pub const SYS_fanotify_mark = 301; pub const SYS_prlimit64 = 302; pub const SYS_name_to_handle_at = 303; pub const SYS_open_by_handle_at = 304; pub const SYS_clock_adjtime = 305; pub const SYS_syncfs = 306; pub const SYS_sendmmsg = 307; pub const SYS_setns = 308; pub const SYS_getcpu = 309; pub const SYS_process_vm_readv = 310; pub const SYS_process_vm_writev = 311; pub const SYS_kcmp = 312; pub const SYS_finit_module = 313; pub const SYS_sched_setattr = 314; pub const SYS_sched_getattr = 315; pub const SYS_renameat2 = 316; pub const SYS_seccomp = 317; pub const SYS_getrandom = 318; pub const SYS_memfd_create = 319; pub const SYS_kexec_file_load = 320; pub const SYS_bpf = 321; pub const SYS_execveat = 322; pub const SYS_userfaultfd = 323; pub const SYS_membarrier = 324; pub const SYS_mlock2 = 325; pub const SYS_copy_file_range = 326; pub const SYS_preadv2 = 327; pub const SYS_pwritev2 = 328; pub const SYS_pkey_mprotect = 329; pub const SYS_pkey_alloc = 330; pub const SYS_pkey_free = 331; pub const SYS_statx = 332; pub const SYS_io_pgetevents = 333; pub const SYS_rseq = 334; pub const SYS_pidfd_send_signal = 424; pub const SYS_io_uring_setup = 425; pub const SYS_io_uring_enter = 426; pub const SYS_io_uring_register = 427; pub const SYS_open_tree = 428; pub const SYS_move_mount = 429; pub const SYS_fsopen = 430; pub const SYS_fsconfig = 431; pub const SYS_fsmount = 432; pub const SYS_fspick = 433; pub const SYS_pidfd_open = 434; pub const SYS_clone3 = 435; pub const O_CREAT = 0o100; pub const O_EXCL = 0o200; pub const O_NOCTTY = 0o400; pub const O_TRUNC = 0o1000; pub const O_APPEND = 0o2000; pub const O_NONBLOCK = 0o4000; pub const O_DSYNC = 0o10000; pub const O_SYNC = 0o4010000; pub const O_RSYNC = 0o4010000; pub const O_DIRECTORY = 0o200000; pub const O_NOFOLLOW = 0o400000; pub const O_CLOEXEC = 0o2000000; pub const O_ASYNC = 0o20000; pub const O_DIRECT = 0o40000; pub const O_LARGEFILE = 0; pub const O_NOATIME = 0o1000000; pub const O_PATH = 0o10000000; pub const O_TMPFILE = 0o20200000; pub const O_NDELAY = O_NONBLOCK; pub const F_DUPFD = 0; pub const F_GETFD = 1; pub const F_SETFD = 2; pub const F_GETFL = 3; pub const F_SETFL = 4; pub const F_SETOWN = 8; pub const F_GETOWN = 9; pub const F_SETSIG = 10; pub const F_GETSIG = 11; pub const F_GETLK = 5; pub const F_SETLK = 6; pub const F_SETLKW = 7; pub const F_SETOWN_EX = 15; pub const F_GETOWN_EX = 16; pub const F_GETOWNER_UIDS = 17; /// only give out 32bit addresses pub const MAP_32BIT = 0x40; /// stack-like segment pub const MAP_GROWSDOWN = 0x0100; /// ETXTBSY pub const MAP_DENYWRITE = 0x0800; /// mark it as an executable pub const MAP_EXECUTABLE = 0x1000; /// pages are locked pub const MAP_LOCKED = 0x2000; /// don't check for reservations pub const MAP_NORESERVE = 0x4000; pub const VDSO_CGT_SYM = "__vdso_clock_gettime"; pub const VDSO_CGT_VER = "LINUX_2.6"; pub const VDSO_GETCPU_SYM = "__vdso_getcpu"; pub const VDSO_GETCPU_VER = "LINUX_2.6"; pub const ARCH_SET_GS = 0x1001; pub const ARCH_SET_FS = 0x1002; pub const ARCH_GET_FS = 0x1003; pub const ARCH_GET_GS = 0x1004; pub const REG_R8 = 0; pub const REG_R9 = 1; pub const REG_R10 = 2; pub const REG_R11 = 3; pub const REG_R12 = 4; pub const REG_R13 = 5; pub const REG_R14 = 6; pub const REG_R15 = 7; pub const REG_RDI = 8; pub const REG_RSI = 9; pub const REG_RBP = 10; pub const REG_RBX = 11; pub const REG_RDX = 12; pub const REG_RAX = 13; pub const REG_RCX = 14; pub const REG_RSP = 15; pub const REG_RIP = 16; pub const REG_EFL = 17; pub const REG_CSGSFS = 18; pub const REG_ERR = 19; pub const REG_TRAPNO = 20; pub const REG_OLDMASK = 21; pub const REG_CR2 = 22; pub const msghdr = extern struct { msg_name: ?*sockaddr, msg_namelen: socklen_t, msg_iov: [*]iovec, msg_iovlen: i32, __pad1: i32, msg_control: ?*c_void, msg_controllen: socklen_t, __pad2: socklen_t, msg_flags: i32, }; pub const msghdr_const = extern struct { msg_name: ?*const sockaddr, msg_namelen: socklen_t, msg_iov: [*]iovec_const, msg_iovlen: i32, __pad1: i32, msg_control: ?*c_void, msg_controllen: socklen_t, __pad2: socklen_t, msg_flags: i32, }; pub const off_t = i64; /// Renamed to Stat to not conflict with the stat function. /// atime, mtime, and ctime have functions to return `timespec`, /// because although this is a POSIX API, the layout and names of /// the structs are inconsistent across operating systems, and /// in C, macros are used to hide the differences. Here we use /// methods to accomplish this. pub const Stat = extern struct { dev: u64, ino: u64, nlink: usize, mode: u32, uid: u32, gid: u32, __pad0: u32, rdev: u64, size: off_t, blksize: isize, blocks: i64, atim: timespec, mtim: timespec, ctim: timespec, __unused: [3]isize, pub fn atime(self: Stat) timespec { return self.atim; } pub fn mtime(self: Stat) timespec { return self.mtim; } pub fn ctime(self: Stat) timespec { return self.ctim; } }; pub const timespec = extern struct { tv_sec: isize, tv_nsec: isize, }; pub const timeval = extern struct { tv_sec: isize, tv_usec: isize, }; pub const timezone = extern struct { tz_minuteswest: i32, tz_dsttime: i32, }; pub const Elf_Symndx = u32; pub const greg_t = usize; pub const gregset_t = [23]greg_t; pub const fpstate = extern struct { cwd: u16, swd: u16, ftw: u16, fop: u16, rip: usize, rdp: usize, mxcsr: u32, mxcr_mask: u32, st: [8]extern struct { significand: [4]u16, exponent: u16, padding: [3]u16 = undefined, }, xmm: [16]extern struct { element: [4]u32, }, padding: [24]u32 = undefined, }; pub const fpregset_t = *fpstate; pub const sigcontext = extern struct { r8: usize, r9: usize, r10: usize, r11: usize, r12: usize, r13: usize, r14: usize, r15: usize, rdi: usize, rsi: usize, rbp: usize, rbx: usize, rdx: usize, rax: usize, rcx: usize, rsp: usize, rip: usize, eflags: usize, cs: u16, gs: u16, fs: u16, pad0: u16 = undefined, err: usize, trapno: usize, oldmask: usize, cr2: usize, fpstate: *fpstate, reserved1: [8]usize = undefined, }; pub const mcontext_t = extern struct { gregs: gregset_t, fpregs: fpregset_t, reserved1: [8]usize = undefined, }; pub const ucontext_t = extern struct { flags: usize, link: *ucontext_t, stack: stack_t, mcontext: mcontext_t, sigmask: sigset_t, fpregs_mem: [64]usize, };
lib/std/os/bits/linux/x86_64.zig
const std = @import("index.zig"); const debug = std.debug; const assert = debug.assert; const mem = std.mem; const Allocator = mem.Allocator; /// Generic doubly linked list. pub fn LinkedList(comptime T: type) type { return struct { const Self = @This(); /// Node inside the linked list wrapping the actual data. pub const Node = struct { prev: ?*Node, next: ?*Node, data: T, pub fn init(data: T) Node { return Node{ .prev = null, .next = null, .data = data, }; } }; first: ?*Node, last: ?*Node, len: usize, /// Initialize a linked list. /// /// Returns: /// An empty linked list. pub fn init() Self { return Self{ .first = null, .last = null, .len = 0, }; } /// Insert a new node after an existing one. /// /// Arguments: /// node: Pointer to a node in the list. /// new_node: Pointer to the new node to insert. pub fn insertAfter(list: *Self, node: *Node, new_node: *Node) void { new_node.prev = node; if (node.next) |next_node| { // Intermediate node. new_node.next = next_node; next_node.prev = new_node; } else { // Last element of the list. new_node.next = null; list.last = new_node; } node.next = new_node; list.len += 1; } /// Insert a new node before an existing one. /// /// Arguments: /// node: Pointer to a node in the list. /// new_node: Pointer to the new node to insert. pub fn insertBefore(list: *Self, node: *Node, new_node: *Node) void { new_node.next = node; if (node.prev) |prev_node| { // Intermediate node. new_node.prev = prev_node; prev_node.next = new_node; } else { // First element of the list. new_node.prev = null; list.first = new_node; } node.prev = new_node; list.len += 1; } /// Concatenate list2 onto the end of list1, removing all entries from the former. /// /// Arguments: /// list1: the list to concatenate onto /// list2: the list to be concatenated pub fn concatByMoving(list1: *Self, list2: *Self) void { const l2_first = list2.first orelse return; if (list1.last) |l1_last| { l1_last.next = list2.first; l2_first.prev = list1.last; list1.len += list2.len; } else { // list1 was empty list1.first = list2.first; list1.len = list2.len; } list1.last = list2.last; list2.first = null; list2.last = null; list2.len = 0; } /// Insert a new node at the end of the list. /// /// Arguments: /// new_node: Pointer to the new node to insert. pub fn append(list: *Self, new_node: *Node) void { if (list.last) |last| { // Insert after last. list.insertAfter(last, new_node); } else { // Empty list. list.prepend(new_node); } } /// Insert a new node at the beginning of the list. /// /// Arguments: /// new_node: Pointer to the new node to insert. pub fn prepend(list: *Self, new_node: *Node) void { if (list.first) |first| { // Insert before first. list.insertBefore(first, new_node); } else { // Empty list. list.first = new_node; list.last = new_node; new_node.prev = null; new_node.next = null; list.len = 1; } } /// Remove a node from the list. /// /// Arguments: /// node: Pointer to the node to be removed. pub fn remove(list: *Self, node: *Node) void { if (node.prev) |prev_node| { // Intermediate node. prev_node.next = node.next; } else { // First element of the list. list.first = node.next; } if (node.next) |next_node| { // Intermediate node. next_node.prev = node.prev; } else { // Last element of the list. list.last = node.prev; } list.len -= 1; assert(list.len == 0 or (list.first != null and list.last != null)); } /// Remove and return the last node in the list. /// /// Returns: /// A pointer to the last node in the list. pub fn pop(list: *Self) ?*Node { const last = list.last orelse return null; list.remove(last); return last; } /// Remove and return the first node in the list. /// /// Returns: /// A pointer to the first node in the list. pub fn popFirst(list: *Self) ?*Node { const first = list.first orelse return null; list.remove(first); return first; } /// Allocate a new node. /// /// Arguments: /// allocator: Dynamic memory allocator. /// /// Returns: /// A pointer to the new node. pub fn allocateNode(list: *Self, allocator: *Allocator) !*Node { return allocator.create(Node); } /// Deallocate a node. /// /// Arguments: /// node: Pointer to the node to deallocate. /// allocator: Dynamic memory allocator. pub fn destroyNode(list: *Self, node: *Node, allocator: *Allocator) void { allocator.destroy(node); } /// Allocate and initialize a node and its data. /// /// Arguments: /// data: The data to put inside the node. /// allocator: Dynamic memory allocator. /// /// Returns: /// A pointer to the new node. pub fn createNode(list: *Self, data: T, allocator: *Allocator) !*Node { var node = try list.allocateNode(allocator); node.* = Node.init(data); return node; } }; } test "basic linked list test" { const allocator = debug.global_allocator; var list = LinkedList(u32).init(); var one = try list.createNode(1, allocator); var two = try list.createNode(2, allocator); var three = try list.createNode(3, allocator); var four = try list.createNode(4, allocator); var five = try list.createNode(5, allocator); defer { list.destroyNode(one, allocator); list.destroyNode(two, allocator); list.destroyNode(three, allocator); list.destroyNode(four, allocator); list.destroyNode(five, allocator); } list.append(two); // {2} list.append(five); // {2, 5} list.prepend(one); // {1, 2, 5} list.insertBefore(five, four); // {1, 2, 4, 5} list.insertAfter(two, three); // {1, 2, 3, 4, 5} // Traverse forwards. { var it = list.first; var index: u32 = 1; while (it) |node| : (it = node.next) { assert(node.data == index); index += 1; } } // Traverse backwards. { var it = list.last; var index: u32 = 1; while (it) |node| : (it = node.prev) { assert(node.data == (6 - index)); index += 1; } } var first = list.popFirst(); // {2, 3, 4, 5} var last = list.pop(); // {2, 3, 4} list.remove(three); // {2, 4} assert(list.first.?.data == 2); assert(list.last.?.data == 4); assert(list.len == 2); } test "linked list concatenation" { const allocator = debug.global_allocator; var list1 = LinkedList(u32).init(); var list2 = LinkedList(u32).init(); var one = try list1.createNode(1, allocator); defer list1.destroyNode(one, allocator); var two = try list1.createNode(2, allocator); defer list1.destroyNode(two, allocator); var three = try list1.createNode(3, allocator); defer list1.destroyNode(three, allocator); var four = try list1.createNode(4, allocator); defer list1.destroyNode(four, allocator); var five = try list1.createNode(5, allocator); defer list1.destroyNode(five, allocator); list1.append(one); list1.append(two); list2.append(three); list2.append(four); list2.append(five); list1.concatByMoving(&list2); assert(list1.last == five); assert(list1.len == 5); assert(list2.first == null); assert(list2.last == null); assert(list2.len == 0); // Traverse forwards. { var it = list1.first; var index: u32 = 1; while (it) |node| : (it = node.next) { assert(node.data == index); index += 1; } } // Traverse backwards. { var it = list1.last; var index: u32 = 1; while (it) |node| : (it = node.prev) { assert(node.data == (6 - index)); index += 1; } } // Swap them back, this verifies that concating to an empty list works. list2.concatByMoving(&list1); // Traverse forwards. { var it = list2.first; var index: u32 = 1; while (it) |node| : (it = node.next) { assert(node.data == index); index += 1; } } // Traverse backwards. { var it = list2.last; var index: u32 = 1; while (it) |node| : (it = node.prev) { assert(node.data == (6 - index)); index += 1; } } }
std/linked_list.zig
const io = @import("io.zig"); const idt = @import("idt.zig"); const Terminal = @import("tty.zig"); fn sendCommand(cmd: u8) void { // Wait until the keyboard is ready and the command buffer is empty while ((io.in(u8, 0x64) & 0x2) != 0) {} io.out(u8, 0x60, cmd); } pub fn init() void { // Register IRQ handler for IRQ-Keyboard (1) idt.setIRQHandler(1, kbdIrqHandler); idt.setIRQHandler(12, mouseIrqHandler); // Empty keyboard buffer while ((io.in(u8, 0x64) & 0x1) != 0) { _ = io.in(u8, 0x60); } // Activate the keyboard sendCommand(0xF4); idt.enableIRQ(1); vga.print("Keyboard initialized\n", .{}); } pub const KeyEvent = struct { set: ScancodeSet, scancode: u16, char: ?u8, }; var foo: u32 = 0; var lastKeyPress: ?KeyEvent = null; pub fn getKey() ?KeyEvent { _ = @atomicLoad(u32, &foo, .SeqCst); var copy = lastKeyPress; lastKeyPress = null; return copy; } const ScancodeSet = enum { default, extended0, extended1, }; const ScancodeInfo = packed struct { unused: u8, lowerCase: u8, upperCase: u8, graphCase: u8, }; const scancodeTableDefault = @bitCast([128]ScancodeInfo, @ptrCast(*const [512]u8, @embedFile("stdkbd_default.bin")).*); var isShiftPressed = false; var isAltPressed = false; var isControlPressed = false; var isGraphPressed = false; fn pushScancode(set: ScancodeSet, scancode: u16, isRelease: bool) void { if (set == .default) { switch (scancode) { 29 => isControlPressed = !isRelease, 42 => isShiftPressed = !isRelease, 56 => isAltPressed = !isRelease, else => {}, } } else if (set == .extended0) { switch (scancode) { 56 => isGraphPressed = !isRelease, else => {}, } } if (!isRelease) { var keyinfo = if (scancode < 128 and set == .default) scancodeTableDefault[scancode] else ScancodeInfo{ .unused = undefined, .lowerCase = 0, .upperCase = 0, .graphCase = 0, }; var chr = if (isGraphPressed) keyinfo.graphCase else if (isShiftPressed) keyinfo.upperCase else keyinfo.lowerCase; lastKeyPress = KeyEvent{ .set = set, .scancode = scancode, .char = if (chr != 0) chr else null, }; } vga.print("[kbd:{}/{}/{}]", .{ set, scancode, if (isRelease) "R" else "P" }); } pub const FKey = enum { F1, F2, F3, F4, F5, F6, F7, F8, F9, F10, F11, F12, }; const IrqState = enum { default, receiveE0, receiveE1_Byte0, receiveE1_Byte1, }; var irqState: IrqState = .default; var e1Byte0: u8 = undefined; fn kbdIrqHandler(cpu: *idt.CpuState) *idt.CpuState { var newCpu = cpu; const inputData = io.in(u8, 0x60); irqState = switch (irqState) { .default => switch (inputData) { 0xE0 => IrqState.receiveE0, 0xE1 => IrqState.receiveE1_Byte0, else => blk: { const scancode = inputData & 0x7F; const isRelease = (inputData & 0x80 != 0); switch (scancode) { 59...68, 87, 88 => { if (isRelease) return cpu; // TODO: Implement this // return @import("root").handleFKey(cpu, switch (scancode) { // 59 => FKey.F1, // 60 => FKey.F2, // 61 => FKey.F3, // 62 => FKey.F4, // 63 => FKey.F5, // 64 => FKey.F6, // 65 => FKey.F7, // 66 => FKey.F8, // 67 => FKey.F9, // 68 => FKey.F10, // 87 => FKey.F11, // 88 => FKey.F12, // else => unreachable, // }); pushScancode(.default, scancode, isRelease); }, else => pushScancode(.default, scancode, isRelease), } break :blk IrqState.default; }, }, .receiveE0 => switch (inputData) { // these are "fake shifts" 0x2A, 0x36 => IrqState.default, else => blk: { pushScancode(.extended0, inputData & 0x7F, (inputData & 0x80 != 0)); break :blk IrqState.default; }, }, .receiveE1_Byte0 => blk: { e1Byte0 = inputData; break :blk .receiveE1_Byte1; }, .receiveE1_Byte1 => blk: { const scancode = (@as(u16, inputData) << 8) | e1Byte0; pushScancode(.extended1, scancode, (inputData & 0x80) != 0); break :blk .default; }, }; return newCpu; } fn mouseIrqHandler(cpu: *idt.CpuState) *idt.CpuState { @panic("EEK, A MOUSE!"); }
src/kernel/arch/x86/boot/keyboard.zig
const std = @import("std"); usingnamespace @import("imgui"); const colors = @import("../colors.zig"); const history = @import("../history.zig"); const ts = @import("../tilescript.zig"); // helper to maintain state during a drag selection var shift_dragged = false; var dragged = false; var prev_mouse_pos: ImVec2 = undefined; pub fn drawWindows(state: *ts.AppState) void { // if the alt key is dont dont allow scrolling with the mouse since we will be zooming var window_flags = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysHorizontalScrollbar; if (igGetIO().KeyAlt) window_flags |= ImGuiWindowFlags_NoScrollWithMouse; if (igBegin("Input Map", null, window_flags)) { draw(state, true); } igEnd(); if (state.prefs.windows.post_processed_map) { if (igBegin("Post Processed Map", &state.prefs.windows.post_processed_map, window_flags)) { draw(state, false); } igEnd(); } } fn draw(state: *ts.AppState, input_map: bool) void { var pos = ogGetCursorScreenPos(); const map_size = state.mapSize(); ogAddRectFilled(igGetWindowDrawList(), pos, map_size, colors.colorRgb(0, 0, 0)); _ = igInvisibleButton("##input_map_button", map_size); const is_hovered = igIsItemHovered(ImGuiHoveredFlags_None); if (input_map) { drawInputMap(state, pos); } else { drawPostProcessedMap(state, pos); } if (is_hovered) { handleInput(state, pos, input_map); } else if (input_map) { // only set dragged to false if we are drawing the input_map since it is the one that accepts input dragged = false; } // draw a rect over the current tile if (is_hovered and !shift_dragged) { var tile = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), pos); const tl = ImVec2{ .x = pos.x + @intToFloat(f32, tile.x) * state.map_rect_size, .y = pos.y + @intToFloat(f32, tile.y) * state.map_rect_size }; ogAddQuad(igGetWindowDrawList(), tl, state.map_rect_size, colors.rule_result_selected_outline, 1); } } fn drawInputMap(state: *ts.AppState, origin: ImVec2) void { var y: usize = 0; while (y < state.map.h) : (y += 1) { var x: usize = 0; while (x < state.map.w) : (x += 1) { const tile = state.map.data[x + y * state.map.w]; if (tile == 0) continue; const offset_x = @intToFloat(f32, x) * state.map_rect_size; const offset_y = @intToFloat(f32, y) * state.map_rect_size; var tl = ImVec2{ .x = origin.x + offset_x, .y = origin.y + offset_y }; ts.drawBrush(state.map_rect_size, tile - 1, tl); } } } fn drawPostProcessedMap(state: *ts.AppState, origin: ImVec2) void { var y: usize = 0; while (y < state.map.h) : (y += 1) { var x: usize = 0; while (x < state.map.w) : (x += 1) { const tile = state.processed_map_data[x + y * state.map.w]; if (tile == 0) continue; const offset_x = @intToFloat(f32, x) * state.map_rect_size; const offset_y = @intToFloat(f32, y) * state.map_rect_size; var tl = ImVec2{ .x = origin.x + offset_x, .y = origin.y + offset_y }; ts.drawBrush(state.map_rect_size, tile - 1, tl); } } } fn handleInput(state: *ts.AppState, origin: ImVec2, input_map: bool) void { // scrolling via drag with alt or super key down if (igIsMouseDragging(ImGuiMouseButton_Left, 0) and (igGetIO().KeyAlt or igGetIO().KeySuper)) { var scroll_delta = ImVec2{}; igGetMouseDragDelta(&scroll_delta, 0, 0); igSetScrollXFloat(igGetScrollX() - scroll_delta.x); igSetScrollYFloat(igGetScrollY() - scroll_delta.y); igResetMouseDragDelta(ImGuiMouseButton_Left); syncScrollPosition(state, input_map); return; } // zoom with alt + mouse wheel if (igGetIO().KeyAlt and igGetIO().MouseWheel != 0) { if (igGetIO().MouseWheel > 0) { if (state.prefs.tile_size_multiplier > 1) { state.prefs.tile_size_multiplier -= 1; } } else if (state.prefs.tile_size_multiplier < 4) { state.prefs.tile_size_multiplier += 1; } state.map_rect_size = @intToFloat(f32, state.map.tile_size * state.prefs.tile_size_multiplier); igGetIO().MouseWheel = 0; return; } if (igGetIO().MouseWheel != 0 or igGetIO().MouseWheelH != 0) { syncScrollPosition(state, input_map); } if (state.object_edit_mode) { return; } // box selection with left/right mouse + shift if (ogIsAnyMouseDragging() and igGetIO().KeyShift) { var drag_delta = ogGetAnyMouseDragDelta(); var tile1 = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); drag_delta.x += origin.x; drag_delta.y += origin.y; var tile2 = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), drag_delta); const min_x = @intToFloat(f32, std.math.min(tile1.x, tile2.x)) * state.map_rect_size + origin.x; const min_y = @intToFloat(f32, std.math.max(tile1.y, tile2.y)) * state.map_rect_size + state.map_rect_size + origin.y; const max_x = @intToFloat(f32, std.math.max(tile1.x, tile2.x)) * state.map_rect_size + state.map_rect_size + origin.x; const max_y = @intToFloat(f32, std.math.min(tile1.y, tile2.y)) * state.map_rect_size + origin.y; const color = if (igIsMouseDragging(ImGuiMouseButton_Left, 0)) colors.colorRgb(255, 255, 255) else colors.colorRgb(220, 0, 0); ImDrawList_AddQuad(igGetWindowDrawList(), .{ .x = min_x, .y = max_y }, .{ .x = max_x, .y = max_y }, .{ .x = max_x, .y = min_y }, .{ .x = min_x, .y = min_y }, color, 2); shift_dragged = true; } else if ((igIsMouseReleased(ImGuiMouseButton_Left) or igIsMouseReleased(ImGuiMouseButton_Right)) and shift_dragged) { shift_dragged = false; var drag_delta = if (igIsMouseReleased(ImGuiMouseButton_Left)) ogGetMouseDragDelta(ImGuiMouseButton_Left, 0) else ogGetMouseDragDelta(ImGuiMouseButton_Right, 0); var tile1 = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); drag_delta.x += origin.x; drag_delta.y += origin.y; var tile2 = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), drag_delta); const min_x = std.math.min(tile1.x, tile2.x); var min_y = std.math.min(tile1.y, tile2.y); const max_x = std.math.max(tile1.x, tile2.x); const max_y = std.math.max(tile1.y, tile2.y); // undo support const start_index = min_x + min_y * state.map.w; const end_index = max_x + max_y * state.map.w; history.push(state.map.data[start_index .. end_index + 1]); // either set the tile to a brush or 0 depending on mouse button const tile_value = if (igIsMouseReleased(ImGuiMouseButton_Left)) state.selected_brush_index + 1 else 0; while (min_y <= max_y) : (min_y += 1) { var x = min_x; while (x <= max_x) : (x += 1) { state.map.setTile(x, min_y, @intCast(u8, tile_value)); } } history.commit(); state.map_data_dirty = true; } else if (igIsMouseDown(ImGuiMouseButton_Left) and !igGetIO().KeyShift) { var tile = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); // if the mouse down last frame, get last mouse pos and ensure we dont skip tiles when drawing if (dragged) { commitInBetweenTiles(state, tile.x, tile.y, origin, @intCast(u8, state.selected_brush_index + 1)); } dragged = true; prev_mouse_pos = igGetIO().MousePos; const index = tile.x + tile.y * state.map.w; history.push(state.map.data[index .. index + 1]); state.map.setTile(tile.x, tile.y, @intCast(u8, state.selected_brush_index + 1)); state.map_data_dirty = true; } else if (igIsMouseDown(ImGuiMouseButton_Right)) { var tile = ts.tileIndexUnderMouse(@floatToInt(usize, state.map_rect_size), origin); // if the mouse down last frame, get last mouse pos and ensure we dont skip tiles when drawing if (dragged) { commitInBetweenTiles(state, tile.x, tile.y, origin, 0); } dragged = true; prev_mouse_pos = igGetIO().MousePos; const index = tile.x + tile.y * state.map.w; history.push(state.map.data[index .. index + 1]); state.map.setTile(tile.x, tile.y, 0); state.map_data_dirty = true; } else if (igIsMouseReleased(ImGuiMouseButton_Left) or igIsMouseReleased(ImGuiMouseButton_Right)) { dragged = false; history.commit(); } } /// syncs the scroll position between the input map, post processed map and output maps fn syncScrollPosition(state: *ts.AppState, input_map: bool) void { const new_scroll_x = igGetScrollX(); const new_scroll_y = igGetScrollY(); // sync scroll position with the opposite map window if it is visible var needs_sync = (input_map and state.prefs.windows.post_processed_map) or !input_map; if (needs_sync) { _ = igBegin(if (input_map) "Post Processed Map" else "Input Map", &needs_sync, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysHorizontalScrollbar); igSetScrollXFloat(new_scroll_x); igSetScrollYFloat(new_scroll_y); igEnd(); } if (igBegin("Output Map", null, ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_AlwaysHorizontalScrollbar)) { igSetScrollXFloat(new_scroll_x); igSetScrollYFloat(new_scroll_y); } igEnd(); } fn commitInBetweenTiles(state: *ts.AppState, tile_x: usize, tile_y: usize, origin: ImVec2, color: u8) void { var prev_tile = ts.tileIndexUnderPos(prev_mouse_pos, @floatToInt(usize, state.map_rect_size), origin); const abs_x = std.math.absInt(@intCast(i32, tile_x) - @intCast(i32, prev_tile.x)) catch unreachable; const abs_y = std.math.absInt(@intCast(i32, tile_y) - @intCast(i32, prev_tile.y)) catch unreachable; if (abs_x <= 1 and abs_y <= 1) { return; } bresenham(state, @intToFloat(f32, prev_tile.x), @intToFloat(f32, prev_tile.y), @intToFloat(f32, tile_x), @intToFloat(f32, tile_y), color); } /// fill in all the tiles between the two mouse positions using bresenham's line algo fn bresenham(state: *ts.AppState, in_x1: f32, in_y1: f32, in_x2: f32, in_y2: f32, color: u8) void { var x1 = in_x1; var y1 = in_y1; var x2 = in_x2; var y2 = in_y2; const steep = std.math.absFloat(y2 - y1) > std.math.absFloat(x2 - x1); if (steep) { std.mem.swap(f32, &x1, &y1); std.mem.swap(f32, &x2, &y2); } if (x1 > x2) { std.mem.swap(f32, &x1, &x2); std.mem.swap(f32, &y1, &y2); } const dx: f32 = x2 - x1; const dy: f32 = std.math.absFloat(y2 - y1); var err: f32 = dx / 2.0; var ystep: i32 = if (y1 < y2) 1 else -1; var y: i32 = @floatToInt(i32, y1); const maxX: i32 = @floatToInt(i32, x2); var x: i32 = @floatToInt(i32, x1); while (x <= maxX) : (x += 1) { if (steep) { const index = @intCast(usize, y) + @intCast(usize, x) * state.map.w; history.push(state.map.data[index .. index + 1]); state.map.setTile(@intCast(usize, y), @intCast(usize, x), color); } else { const index = @intCast(usize, x) + @intCast(usize, y) * state.map.w; history.push(state.map.data[index .. index + 1]); state.map.setTile(@intCast(usize, x), @intCast(usize, y), color); } err -= dy; if (err < 0) { y += ystep; err += dx; } } }
tilescript/windows/maps.zig
pub const L2_REASON_CODE_DOT11_AC_BASE = @as(u32, 131072); pub const L2_REASON_CODE_DOT11_MSM_BASE = @as(u32, 196608); pub const L2_REASON_CODE_DOT11_SECURITY_BASE = @as(u32, 262144); pub const L2_REASON_CODE_ONEX_BASE = @as(u32, 327680); pub const L2_REASON_CODE_DOT3_AC_BASE = @as(u32, 393216); pub const L2_REASON_CODE_DOT3_MSM_BASE = @as(u32, 458752); pub const L2_REASON_CODE_PROFILE_BASE = @as(u32, 524288); pub const L2_REASON_CODE_IHV_BASE = @as(u32, 589824); pub const L2_REASON_CODE_WIMAX_BASE = @as(u32, 655360); pub const L2_REASON_CODE_RESERVED_BASE = @as(u32, 720896); pub const WLAN_REASON_CODE_SUCCESS = @as(u32, 0); pub const WLAN_REASON_CODE_UNKNOWN = @as(u32, 65537); pub const WLAN_REASON_CODE_RANGE_SIZE = @as(u32, 65536); pub const WLAN_REASON_CODE_BASE = @as(u32, 131072); pub const WLAN_REASON_CODE_AC_BASE = @as(u32, 131072); pub const WLAN_REASON_CODE_AC_CONNECT_BASE = @as(u32, 163840); pub const WLAN_REASON_CODE_AC_END = @as(u32, 196607); pub const WLAN_REASON_CODE_PROFILE_BASE = @as(u32, 524288); pub const WLAN_REASON_CODE_PROFILE_CONNECT_BASE = @as(u32, 557056); pub const WLAN_REASON_CODE_PROFILE_END = @as(u32, 589823); pub const WLAN_REASON_CODE_MSM_BASE = @as(u32, 196608); pub const WLAN_REASON_CODE_MSM_CONNECT_BASE = @as(u32, 229376); pub const WLAN_REASON_CODE_MSM_END = @as(u32, 262143); pub const WLAN_REASON_CODE_MSMSEC_BASE = @as(u32, 262144); pub const WLAN_REASON_CODE_MSMSEC_CONNECT_BASE = @as(u32, 294912); pub const WLAN_REASON_CODE_MSMSEC_END = @as(u32, 327679); pub const WLAN_REASON_CODE_RESERVED_BASE = @as(u32, 720896); pub const WLAN_REASON_CODE_RESERVED_END = @as(u32, 786431); pub const L2_PROFILE_MAX_NAME_LENGTH = @as(u32, 256); pub const L2_NOTIFICATION_SOURCE_NONE = @as(u32, 0); pub const L2_NOTIFICATION_SOURCE_DOT3_AUTO_CONFIG = @as(u32, 1); pub const L2_NOTIFICATION_SOURCE_SECURITY = @as(u32, 2); pub const L2_NOTIFICATION_SOURCE_ONEX = @as(u32, 4); pub const L2_NOTIFICATION_SOURCE_WLAN_ACM = @as(u32, 8); pub const L2_NOTIFICATION_SOURCE_WLAN_MSM = @as(u32, 16); pub const L2_NOTIFICATION_SOURCE_WLAN_SECURITY = @as(u32, 32); pub const L2_NOTIFICATION_SOURCE_WLAN_IHV = @as(u32, 64); pub const L2_NOTIFICATION_SOURCE_WLAN_HNWK = @as(u32, 128); pub const L2_NOTIFICATION_SOURCE_WCM = @as(u32, 256); pub const L2_NOTIFICATION_SOURCE_WCM_CSP = @as(u32, 512); pub const L2_NOTIFICATION_SOURCE_WFD = @as(u32, 1024); pub const L2_NOTIFICATION_SOURCE_WLAN_DEVICE_SERVICE = @as(u32, 2048); pub const L2_NOTIFICATION_SOURCE_ALL = @as(u32, 65535); pub const L2_NOTIFICATION_CODE_PUBLIC_BEGIN = @as(u32, 0); pub const L2_NOTIFICATION_CODE_GROUP_SIZE = @as(u32, 4096); pub const L2_REASON_CODE_GROUP_SIZE = @as(u32, 65536); pub const L2_REASON_CODE_GEN_BASE = @as(u32, 65536); pub const L2_REASON_CODE_SUCCESS = @as(u32, 0); pub const L2_REASON_CODE_UNKNOWN = @as(u32, 65537); pub const L2_REASON_CODE_PROFILE_MISSING = @as(u32, 1); pub const DOT11_BSSID_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_HESSID_LENGTH = @as(u32, 6); pub const DOT11_RATE_SET_MAX_LENGTH = @as(u32, 126); pub const DOT11_WFD_SERVICE_NAME_MAX_LENGTH = @as(u32, 255); pub const DOT11_WFD_APS2_SERVICE_TYPE_MAX_LENGTH = @as(u32, 21); pub const DOT11_WFD_ASP2_INSTANCE_NAME_MAX_LENGTH = @as(u32, 63); pub const DOT11_WFD_SERVICE_INFORMATION_MAX_LENGTH = @as(u32, 65535); pub const DOT11_MAX_REQUESTED_SERVICE_INFORMATION_LENGTH = @as(u32, 255); pub const DOT11_WFD_SESSION_INFO_MAX_LENGTH = @as(u32, 144); pub const NDIS_PACKET_TYPE_802_11_DIRECTED_DATA = @as(u32, 1); pub const NDIS_PACKET_TYPE_802_11_BROADCAST_DATA = @as(u32, 8); pub const NDIS_PACKET_TYPE_802_11_MULTICAST_DATA = @as(u32, 2); pub const NDIS_PACKET_TYPE_802_11_ALL_MULTICAST_DATA = @as(u32, 4); pub const NDIS_PACKET_TYPE_802_11_PROMISCUOUS_DATA = @as(u32, 32); pub const DOT11_MAX_PDU_SIZE = @as(u32, 2346); pub const DOT11_MIN_PDU_SIZE = @as(u32, 256); pub const DOT11_MAX_NUM_DEFAULT_KEY = @as(u32, 4); pub const DOT11_MAX_NUM_DEFAULT_KEY_MFP = @as(u32, 6); pub const OID_DOT11_NDIS_START = @as(u32, 218170112); pub const OID_DOT11_OFFLOAD_CAPABILITY = @as(u32, 218170112); pub const DOT11_HW_WEP_SUPPORTED_TX = @as(u32, 1); pub const DOT11_HW_WEP_SUPPORTED_RX = @as(u32, 2); pub const DOT11_HW_FRAGMENTATION_SUPPORTED = @as(u32, 4); pub const DOT11_HW_DEFRAGMENTATION_SUPPORTED = @as(u32, 8); pub const DOT11_HW_MSDU_AUTH_SUPPORTED_TX = @as(u32, 16); pub const DOT11_HW_MSDU_AUTH_SUPPORTED_RX = @as(u32, 32); pub const DOT11_CONF_ALGO_WEP_RC4 = @as(u32, 1); pub const DOT11_CONF_ALGO_TKIP = @as(u32, 2); pub const DOT11_AUTH_ALGO_MICHAEL = @as(u32, 1); pub const OID_DOT11_CURRENT_OFFLOAD_CAPABILITY = @as(u32, 218170113); pub const OID_DOT11_WEP_OFFLOAD = @as(u32, 218170114); pub const OID_DOT11_WEP_UPLOAD = @as(u32, 218170115); pub const OID_DOT11_DEFAULT_WEP_OFFLOAD = @as(u32, 218170116); pub const OID_DOT11_DEFAULT_WEP_UPLOAD = @as(u32, 218170117); pub const OID_DOT11_MPDU_MAX_LENGTH = @as(u32, 218170118); pub const OID_DOT11_OPERATION_MODE_CAPABILITY = @as(u32, 218170119); pub const DOT11_OPERATION_MODE_UNKNOWN = @as(u32, 0); pub const DOT11_OPERATION_MODE_STATION = @as(u32, 1); pub const DOT11_OPERATION_MODE_AP = @as(u32, 2); pub const DOT11_OPERATION_MODE_EXTENSIBLE_STATION = @as(u32, 4); pub const DOT11_OPERATION_MODE_EXTENSIBLE_AP = @as(u32, 8); pub const DOT11_OPERATION_MODE_WFD_DEVICE = @as(u32, 16); pub const DOT11_OPERATION_MODE_WFD_GROUP_OWNER = @as(u32, 32); pub const DOT11_OPERATION_MODE_WFD_CLIENT = @as(u32, 64); pub const DOT11_OPERATION_MODE_MANUFACTURING = @as(u32, 1073741824); pub const DOT11_OPERATION_MODE_NETWORK_MONITOR = @as(u32, 2147483648); pub const OID_DOT11_CURRENT_OPERATION_MODE = @as(u32, 218170120); pub const OID_DOT11_CURRENT_PACKET_FILTER = @as(u32, 218170121); pub const DOT11_PACKET_TYPE_DIRECTED_CTRL = @as(u32, 1); pub const DOT11_PACKET_TYPE_DIRECTED_MGMT = @as(u32, 2); pub const DOT11_PACKET_TYPE_DIRECTED_DATA = @as(u32, 4); pub const DOT11_PACKET_TYPE_MULTICAST_CTRL = @as(u32, 8); pub const DOT11_PACKET_TYPE_MULTICAST_MGMT = @as(u32, 16); pub const DOT11_PACKET_TYPE_MULTICAST_DATA = @as(u32, 32); pub const DOT11_PACKET_TYPE_BROADCAST_CTRL = @as(u32, 64); pub const DOT11_PACKET_TYPE_BROADCAST_MGMT = @as(u32, 128); pub const DOT11_PACKET_TYPE_BROADCAST_DATA = @as(u32, 256); pub const DOT11_PACKET_TYPE_PROMISCUOUS_CTRL = @as(u32, 512); pub const DOT11_PACKET_TYPE_PROMISCUOUS_MGMT = @as(u32, 1024); pub const DOT11_PACKET_TYPE_PROMISCUOUS_DATA = @as(u32, 2048); pub const DOT11_PACKET_TYPE_ALL_MULTICAST_CTRL = @as(u32, 4096); pub const DOT11_PACKET_TYPE_ALL_MULTICAST_MGMT = @as(u32, 8192); pub const DOT11_PACKET_TYPE_ALL_MULTICAST_DATA = @as(u32, 16384); pub const OID_DOT11_ATIM_WINDOW = @as(u32, 218170122); pub const OID_DOT11_SCAN_REQUEST = @as(u32, 218170123); pub const OID_DOT11_CURRENT_PHY_TYPE = @as(u32, 218170124); pub const DOT11_PHY_TYPE_LIST_REVISION_1 = @as(u32, 1); pub const OID_DOT11_JOIN_REQUEST = @as(u32, 218170125); pub const DOT11_CAPABILITY_INFO_ESS = @as(u32, 1); pub const DOT11_CAPABILITY_INFO_IBSS = @as(u32, 2); pub const DOT11_CAPABILITY_INFO_CF_POLLABLE = @as(u32, 4); pub const DOT11_CAPABILITY_INFO_CF_POLL_REQ = @as(u32, 8); pub const DOT11_CAPABILITY_INFO_PRIVACY = @as(u32, 16); pub const DOT11_CAPABILITY_SHORT_PREAMBLE = @as(u32, 32); pub const DOT11_CAPABILITY_PBCC = @as(u32, 64); pub const DOT11_CAPABILITY_CHANNEL_AGILITY = @as(u32, 128); pub const DOT11_CAPABILITY_SHORT_SLOT_TIME = @as(u32, 1024); pub const DOT11_CAPABILITY_DSSSOFDM = @as(u32, 8192); pub const OID_DOT11_START_REQUEST = @as(u32, 218170126); pub const OID_DOT11_UPDATE_IE = @as(u32, 218170127); pub const OID_DOT11_RESET_REQUEST = @as(u32, 218170128); pub const OID_DOT11_NIC_POWER_STATE = @as(u32, 218170129); pub const OID_DOT11_OPTIONAL_CAPABILITY = @as(u32, 218170130); pub const OID_DOT11_CURRENT_OPTIONAL_CAPABILITY = @as(u32, 218170131); pub const OID_DOT11_STATION_ID = @as(u32, 218170132); pub const OID_DOT11_MEDIUM_OCCUPANCY_LIMIT = @as(u32, 218170133); pub const OID_DOT11_CF_POLLABLE = @as(u32, 218170134); pub const OID_DOT11_CFP_PERIOD = @as(u32, 218170135); pub const OID_DOT11_CFP_MAX_DURATION = @as(u32, 218170136); pub const OID_DOT11_POWER_MGMT_MODE = @as(u32, 218170137); pub const DOT11_POWER_SAVE_LEVEL_MAX_PSP = @as(u32, 1); pub const DOT11_POWER_SAVE_LEVEL_FAST_PSP = @as(u32, 2); pub const OID_DOT11_OPERATIONAL_RATE_SET = @as(u32, 218170138); pub const OID_DOT11_BEACON_PERIOD = @as(u32, 218170139); pub const OID_DOT11_DTIM_PERIOD = @as(u32, 218170140); pub const OID_DOT11_WEP_ICV_ERROR_COUNT = @as(u32, 218170141); pub const OID_DOT11_MAC_ADDRESS = @as(u32, 218170142); pub const OID_DOT11_RTS_THRESHOLD = @as(u32, 218170143); pub const OID_DOT11_SHORT_RETRY_LIMIT = @as(u32, 218170144); pub const OID_DOT11_LONG_RETRY_LIMIT = @as(u32, 218170145); pub const OID_DOT11_FRAGMENTATION_THRESHOLD = @as(u32, 218170146); pub const OID_DOT11_MAX_TRANSMIT_MSDU_LIFETIME = @as(u32, 218170147); pub const OID_DOT11_MAX_RECEIVE_LIFETIME = @as(u32, 218170148); pub const OID_DOT11_COUNTERS_ENTRY = @as(u32, 218170149); pub const OID_DOT11_SUPPORTED_PHY_TYPES = @as(u32, 218170150); pub const OID_DOT11_CURRENT_REG_DOMAIN = @as(u32, 218170151); pub const DOT11_REG_DOMAIN_OTHER = @as(u32, 0); pub const DOT11_REG_DOMAIN_FCC = @as(u32, 16); pub const DOT11_REG_DOMAIN_DOC = @as(u32, 32); pub const DOT11_REG_DOMAIN_ETSI = @as(u32, 48); pub const DOT11_REG_DOMAIN_SPAIN = @as(u32, 49); pub const DOT11_REG_DOMAIN_FRANCE = @as(u32, 50); pub const DOT11_REG_DOMAIN_MKK = @as(u32, 64); pub const OID_DOT11_TEMP_TYPE = @as(u32, 218170152); pub const OID_DOT11_CURRENT_TX_ANTENNA = @as(u32, 218170153); pub const OID_DOT11_DIVERSITY_SUPPORT = @as(u32, 218170154); pub const OID_DOT11_CURRENT_RX_ANTENNA = @as(u32, 218170155); pub const OID_DOT11_SUPPORTED_POWER_LEVELS = @as(u32, 218170156); pub const OID_DOT11_CURRENT_TX_POWER_LEVEL = @as(u32, 218170157); pub const OID_DOT11_HOP_TIME = @as(u32, 218170158); pub const OID_DOT11_CURRENT_CHANNEL_NUMBER = @as(u32, 218170159); pub const OID_DOT11_MAX_DWELL_TIME = @as(u32, 218170160); pub const OID_DOT11_CURRENT_DWELL_TIME = @as(u32, 218170161); pub const OID_DOT11_CURRENT_SET = @as(u32, 218170162); pub const OID_DOT11_CURRENT_PATTERN = @as(u32, 218170163); pub const OID_DOT11_CURRENT_INDEX = @as(u32, 218170164); pub const OID_DOT11_CURRENT_CHANNEL = @as(u32, 218170165); pub const OID_DOT11_CCA_MODE_SUPPORTED = @as(u32, 218170166); pub const DOT11_CCA_MODE_ED_ONLY = @as(u32, 1); pub const DOT11_CCA_MODE_CS_ONLY = @as(u32, 2); pub const DOT11_CCA_MODE_ED_and_CS = @as(u32, 4); pub const DOT11_CCA_MODE_CS_WITH_TIMER = @as(u32, 8); pub const DOT11_CCA_MODE_HRCS_AND_ED = @as(u32, 16); pub const OID_DOT11_CURRENT_CCA_MODE = @as(u32, 218170167); pub const OID_DOT11_ED_THRESHOLD = @as(u32, 218170168); pub const OID_DOT11_CCA_WATCHDOG_TIMER_MAX = @as(u32, 218170169); pub const OID_DOT11_CCA_WATCHDOG_COUNT_MAX = @as(u32, 218170170); pub const OID_DOT11_CCA_WATCHDOG_TIMER_MIN = @as(u32, 218170171); pub const OID_DOT11_CCA_WATCHDOG_COUNT_MIN = @as(u32, 218170172); pub const OID_DOT11_REG_DOMAINS_SUPPORT_VALUE = @as(u32, 218170173); pub const OID_DOT11_SUPPORTED_TX_ANTENNA = @as(u32, 218170174); pub const OID_DOT11_SUPPORTED_RX_ANTENNA = @as(u32, 218170175); pub const OID_DOT11_DIVERSITY_SELECTION_RX = @as(u32, 218170176); pub const OID_DOT11_SUPPORTED_DATA_RATES_VALUE = @as(u32, 218170177); pub const MAX_NUM_SUPPORTED_RATES = @as(u32, 8); pub const MAX_NUM_SUPPORTED_RATES_V2 = @as(u32, 255); pub const OID_DOT11_CURRENT_FREQUENCY = @as(u32, 218170178); pub const OID_DOT11_TI_THRESHOLD = @as(u32, 218170179); pub const OID_DOT11_FREQUENCY_BANDS_SUPPORTED = @as(u32, 218170180); pub const DOT11_FREQUENCY_BANDS_LOWER = @as(u32, 1); pub const DOT11_FREQUENCY_BANDS_MIDDLE = @as(u32, 2); pub const DOT11_FREQUENCY_BANDS_UPPER = @as(u32, 4); pub const OID_DOT11_SHORT_PREAMBLE_OPTION_IMPLEMENTED = @as(u32, 218170181); pub const OID_DOT11_PBCC_OPTION_IMPLEMENTED = @as(u32, 218170182); pub const OID_DOT11_CHANNEL_AGILITY_PRESENT = @as(u32, 218170183); pub const OID_DOT11_CHANNEL_AGILITY_ENABLED = @as(u32, 218170184); pub const OID_DOT11_HR_CCA_MODE_SUPPORTED = @as(u32, 218170185); pub const DOT11_HR_CCA_MODE_ED_ONLY = @as(u32, 1); pub const DOT11_HR_CCA_MODE_CS_ONLY = @as(u32, 2); pub const DOT11_HR_CCA_MODE_CS_AND_ED = @as(u32, 4); pub const DOT11_HR_CCA_MODE_CS_WITH_TIMER = @as(u32, 8); pub const DOT11_HR_CCA_MODE_HRCS_AND_ED = @as(u32, 16); pub const OID_DOT11_MULTI_DOMAIN_CAPABILITY_IMPLEMENTED = @as(u32, 218170186); pub const OID_DOT11_MULTI_DOMAIN_CAPABILITY_ENABLED = @as(u32, 218170187); pub const OID_DOT11_COUNTRY_STRING = @as(u32, 218170188); pub const OID_DOT11_MULTI_DOMAIN_CAPABILITY = @as(u32, 218170189); pub const OID_DOT11_EHCC_PRIME_RADIX = @as(u32, 218170190); pub const OID_DOT11_EHCC_NUMBER_OF_CHANNELS_FAMILY_INDEX = @as(u32, 218170191); pub const OID_DOT11_EHCC_CAPABILITY_IMPLEMENTED = @as(u32, 218170192); pub const OID_DOT11_EHCC_CAPABILITY_ENABLED = @as(u32, 218170193); pub const OID_DOT11_HOP_ALGORITHM_ADOPTED = @as(u32, 218170194); pub const OID_DOT11_RANDOM_TABLE_FLAG = @as(u32, 218170195); pub const OID_DOT11_NUMBER_OF_HOPPING_SETS = @as(u32, 218170196); pub const OID_DOT11_HOP_MODULUS = @as(u32, 218170197); pub const OID_DOT11_HOP_OFFSET = @as(u32, 218170198); pub const OID_DOT11_HOPPING_PATTERN = @as(u32, 218170199); pub const OID_DOT11_RANDOM_TABLE_FIELD_NUMBER = @as(u32, 218170200); pub const OID_DOT11_WPA_TSC = @as(u32, 218170201); pub const OID_DOT11_RSSI_RANGE = @as(u32, 218170202); pub const OID_DOT11_RF_USAGE = @as(u32, 218170203); pub const OID_DOT11_NIC_SPECIFIC_EXTENSION = @as(u32, 218170204); pub const OID_DOT11_AP_JOIN_REQUEST = @as(u32, 218170205); pub const OID_DOT11_ERP_PBCC_OPTION_IMPLEMENTED = @as(u32, 218170206); pub const OID_DOT11_ERP_PBCC_OPTION_ENABLED = @as(u32, 218170207); pub const OID_DOT11_DSSS_OFDM_OPTION_IMPLEMENTED = @as(u32, 218170208); pub const OID_DOT11_DSSS_OFDM_OPTION_ENABLED = @as(u32, 218170209); pub const OID_DOT11_SHORT_SLOT_TIME_OPTION_IMPLEMENTED = @as(u32, 218170210); pub const OID_DOT11_SHORT_SLOT_TIME_OPTION_ENABLED = @as(u32, 218170211); pub const OID_DOT11_MAX_MAC_ADDRESS_STATES = @as(u32, 218170212); pub const OID_DOT11_RECV_SENSITIVITY_LIST = @as(u32, 218170213); pub const OID_DOT11_WME_IMPLEMENTED = @as(u32, 218170214); pub const OID_DOT11_WME_ENABLED = @as(u32, 218170215); pub const OID_DOT11_WME_AC_PARAMETERS = @as(u32, 218170216); pub const OID_DOT11_WME_UPDATE_IE = @as(u32, 218170217); pub const OID_DOT11_QOS_TX_QUEUES_SUPPORTED = @as(u32, 218170218); pub const OID_DOT11_QOS_TX_DURATION = @as(u32, 218170219); pub const OID_DOT11_QOS_TX_MEDIUM_TIME = @as(u32, 218170220); pub const OID_DOT11_SUPPORTED_OFDM_FREQUENCY_LIST = @as(u32, 218170221); pub const OID_DOT11_SUPPORTED_DSSS_CHANNEL_LIST = @as(u32, 218170222); pub const DOT11_BSS_ENTRY_BYTE_ARRAY_REVISION_1 = @as(u32, 1); pub const DOT11_POWER_SAVING_NO_POWER_SAVING = @as(u32, 0); pub const DOT11_POWER_SAVING_FAST_PSP = @as(u32, 8); pub const DOT11_POWER_SAVING_MAX_PSP = @as(u32, 16); pub const DOT11_POWER_SAVING_MAXIMUM_LEVEL = @as(u32, 24); pub const DOT11_SSID_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_MAC_ADDRESS_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_PMKID_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_STATISTICS_REVISION_1 = @as(u32, 1); pub const DOT11_EXEMPT_NO_EXEMPTION = @as(u32, 0); pub const DOT11_EXEMPT_ALWAYS = @as(u32, 1); pub const DOT11_EXEMPT_ON_KEY_MAPPING_KEY_UNAVAILABLE = @as(u32, 2); pub const DOT11_EXEMPT_UNICAST = @as(u32, 1); pub const DOT11_EXEMPT_MULTICAST = @as(u32, 2); pub const DOT11_EXEMPT_BOTH = @as(u32, 3); pub const DOT11_PRIVACY_EXEMPTION_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_AUTH_ALGORITHM_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_AUTH_CIPHER_PAIR_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_CIPHER_ALGORITHM_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_CIPHER_DEFAULT_KEY_VALUE_REVISION_1 = @as(u32, 1); pub const DOT11_CIPHER_KEY_MAPPING_KEY_VALUE_BYTE_ARRAY_REVISION_1 = @as(u32, 1); pub const DOT11_ASSOCIATION_INFO_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_PHY_ID_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_EXTSTA_CAPABILITY_REVISION_1 = @as(u32, 1); pub const DOT11_DATA_RATE_MAPPING_TABLE_REVISION_1 = @as(u32, 1); pub const DOT11_COUNTRY_OR_REGION_STRING_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_PORT_STATE_NOTIFICATION_REVISION_1 = @as(u32, 1); pub const DOT11_IBSS_PARAMS_REVISION_1 = @as(u32, 1); pub const DOT11_QOS_PARAMS_REVISION_1 = @as(u32, 1); pub const DOT11_ASSOCIATION_PARAMS_REVISION_1 = @as(u32, 1); pub const DOT11_MAX_NUM_OF_FRAGMENTS = @as(u32, 16); pub const DOT11_PRIORITY_CONTENTION = @as(u32, 0); pub const DOT11_PRIORITY_CONTENTION_FREE = @as(u32, 1); pub const DOT11_SERVICE_CLASS_REORDERABLE_MULTICAST = @as(u32, 0); pub const DOT11_SERVICE_CLASS_STRICTLY_ORDERED = @as(u32, 1); pub const DOT11_FLAGS_80211B_SHORT_PREAMBLE = @as(u32, 1); pub const DOT11_FLAGS_80211B_PBCC = @as(u32, 2); pub const DOT11_FLAGS_80211B_CHANNEL_AGILITY = @as(u32, 4); pub const DOT11_FLAGS_PS_ON = @as(u32, 8); pub const DOT11_FLAGS_80211G_DSSS_OFDM = @as(u32, 16); pub const DOT11_FLAGS_80211G_USE_PROTECTION = @as(u32, 32); pub const DOT11_FLAGS_80211G_NON_ERP_PRESENT = @as(u32, 64); pub const DOT11_FLAGS_80211G_BARKER_PREAMBLE_MODE = @as(u32, 128); pub const DOT11_WME_PACKET = @as(u32, 256); pub const DOT11_PHY_ATTRIBUTES_REVISION_1 = @as(u32, 1); pub const DOT11_EXTSTA_ATTRIBUTES_SAFEMODE_OID_SUPPORTED = @as(u32, 1); pub const DOT11_EXTSTA_ATTRIBUTES_SAFEMODE_CERTIFIED = @as(u32, 2); pub const DOT11_EXTSTA_ATTRIBUTES_SAFEMODE_RESERVED = @as(u32, 12); pub const DOT11_EXTSTA_ATTRIBUTES_REVISION_1 = @as(u32, 1); pub const DOT11_EXTSTA_ATTRIBUTES_REVISION_2 = @as(u32, 2); pub const DOT11_EXTSTA_ATTRIBUTES_REVISION_3 = @as(u32, 3); pub const DOT11_EXTSTA_ATTRIBUTES_REVISION_4 = @as(u32, 4); pub const DOT11_SEND_CONTEXT_REVISION_1 = @as(u32, 1); pub const DOT11_RECV_CONTEXT_REVISION_1 = @as(u32, 1); pub const DOT11_STATUS_SUCCESS = @as(u32, 1); pub const DOT11_STATUS_RETRY_LIMIT_EXCEEDED = @as(u32, 2); pub const DOT11_STATUS_UNSUPPORTED_PRIORITY = @as(u32, 4); pub const DOT11_STATUS_UNSUPPORTED_SERVICE_CLASS = @as(u32, 8); pub const DOT11_STATUS_UNAVAILABLE_PRIORITY = @as(u32, 16); pub const DOT11_STATUS_UNAVAILABLE_SERVICE_CLASS = @as(u32, 32); pub const DOT11_STATUS_XMIT_MSDU_TIMER_EXPIRED = @as(u32, 64); pub const DOT11_STATUS_UNAVAILABLE_BSS = @as(u32, 128); pub const DOT11_STATUS_EXCESSIVE_DATA_LENGTH = @as(u32, 256); pub const DOT11_STATUS_ENCRYPTION_FAILED = @as(u32, 512); pub const DOT11_STATUS_WEP_KEY_UNAVAILABLE = @as(u32, 1024); pub const DOT11_STATUS_ICV_VERIFIED = @as(u32, 2048); pub const DOT11_STATUS_PACKET_REASSEMBLED = @as(u32, 4096); pub const DOT11_STATUS_PACKET_NOT_REASSEMBLED = @as(u32, 8192); pub const DOT11_STATUS_GENERATE_AUTH_FAILED = @as(u32, 16384); pub const DOT11_STATUS_AUTH_NOT_VERIFIED = @as(u32, 32768); pub const DOT11_STATUS_AUTH_VERIFIED = @as(u32, 65536); pub const DOT11_STATUS_AUTH_FAILED = @as(u32, 131072); pub const DOT11_STATUS_PS_LIFETIME_EXPIRED = @as(u32, 262144); pub const DOT11_STATUS_RESET_CONFIRM = @as(u32, 4); pub const DOT11_STATUS_SCAN_CONFIRM = @as(u32, 1); pub const DOT11_STATUS_JOIN_CONFIRM = @as(u32, 2); pub const DOT11_STATUS_START_CONFIRM = @as(u32, 3); pub const DOT11_STATUS_AP_JOIN_CONFIRM = @as(u32, 5); pub const DOT11_STATUS_MPDU_MAX_LENGTH_CHANGED = @as(u32, 6); pub const DOT11_MPDU_MAX_LENGTH_INDICATION_REVISION_1 = @as(u32, 1); pub const DOT11_ASSOCIATION_START_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_ENCAP_RFC_1042 = @as(u32, 1); pub const DOT11_ENCAP_802_1H = @as(u32, 2); pub const DOT11_ASSOC_STATUS_SUCCESS = @as(u32, 0); pub const DOT11_ASSOCIATION_COMPLETION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_ASSOCIATION_COMPLETION_PARAMETERS_REVISION_2 = @as(u32, 2); pub const DOT11_CONNECTION_START_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_CONNECTION_STATUS_SUCCESS = @as(u32, 0); pub const DOT11_CONNECTION_COMPLETION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_ROAMING_START_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_ROAMING_COMPLETION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_DISASSOCIATION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_TKIPMIC_FAILURE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_PMKID_CANDIDATE_LIST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_PHY_STATE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_LINK_QUALITY_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_EXTSTA_SEND_CONTEXT_REVISION_1 = @as(u32, 1); pub const DOT11_EXTSTA_RECV_CONTEXT_REVISION_1 = @as(u32, 1); pub const OID_DOT11_PRIVATE_OIDS_START = @as(u32, 218171136); pub const OID_DOT11_CURRENT_ADDRESS = @as(u32, 218171138); pub const OID_DOT11_PERMANENT_ADDRESS = @as(u32, 218171139); pub const OID_DOT11_MULTICAST_LIST = @as(u32, 218171140); pub const OID_DOT11_MAXIMUM_LIST_SIZE = @as(u32, 218171141); pub const DOT11_EXTAP_ATTRIBUTES_REVISION_1 = @as(u32, 1); pub const DOT11_INCOMING_ASSOC_STARTED_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_INCOMING_ASSOC_REQUEST_RECEIVED_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_ASSOC_ERROR_SOURCE_OS = @as(u32, 0); pub const DOT11_ASSOC_ERROR_SOURCE_REMOTE = @as(u32, 1); pub const DOT11_ASSOC_ERROR_SOURCE_OTHER = @as(u32, 255); pub const DOT11_INCOMING_ASSOC_COMPLETION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_STOP_AP_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_STOP_AP_REASON_FREQUENCY_NOT_AVAILABLE = @as(u32, 1); pub const DOT11_STOP_AP_REASON_CHANNEL_NOT_AVAILABLE = @as(u32, 2); pub const DOT11_STOP_AP_REASON_AP_ACTIVE = @as(u32, 3); pub const DOT11_STOP_AP_REASON_IHV_START = @as(u32, 4278190080); pub const DOT11_STOP_AP_REASON_IHV_END = @as(u32, 4294967295); pub const DOT11_PHY_FREQUENCY_ADOPTED_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_CAN_SUSTAIN_AP_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_CAN_SUSTAIN_AP_REASON_IHV_START = @as(u32, 4278190080); pub const DOT11_CAN_SUSTAIN_AP_REASON_IHV_END = @as(u32, 4294967295); pub const DOT11_AVAILABLE_CHANNEL_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_AVAILABLE_FREQUENCY_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_DISASSOCIATE_PEER_REQUEST_REVISION_1 = @as(u32, 1); pub const DOT11_INCOMING_ASSOC_DECISION_REVISION_1 = @as(u32, 1); pub const DOT11_INCOMING_ASSOC_DECISION_REVISION_2 = @as(u32, 2); pub const DOT11_ADDITIONAL_IE_REVISION_1 = @as(u32, 1); pub const DOT11_EXTAP_SEND_CONTEXT_REVISION_1 = @as(u32, 1); pub const DOT11_EXTAP_RECV_CONTEXT_REVISION_1 = @as(u32, 1); pub const DOT11_PEER_INFO_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_VWIFI_COMBINATION_REVISION_1 = @as(u32, 1); pub const DOT11_VWIFI_COMBINATION_REVISION_2 = @as(u32, 2); pub const DOT11_VWIFI_COMBINATION_REVISION_3 = @as(u32, 3); pub const DOT11_VWIFI_ATTRIBUTES_REVISION_1 = @as(u32, 1); pub const DOT11_MAC_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_ATTRIBUTES_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_STATUS_SUCCESS = @as(u32, 0); pub const DOT11_WFD_STATUS_FAILED_INFORMATION_IS_UNAVAILABLE = @as(u32, 1); pub const DOT11_WFD_STATUS_FAILED_INCOMPATIBLE_PARAMETERS = @as(u32, 2); pub const DOT11_WFD_STATUS_FAILED_LIMIT_REACHED = @as(u32, 3); pub const DOT11_WFD_STATUS_FAILED_INVALID_PARAMETERS = @as(u32, 4); pub const DOT11_WFD_STATUS_FAILED_UNABLE_TO_ACCOMODATE_REQUEST = @as(u32, 5); pub const DOT11_WFD_STATUS_FAILED_PREVIOUS_PROTOCOL_ERROR = @as(u32, 6); pub const DOT11_WFD_STATUS_FAILED_NO_COMMON_CHANNELS = @as(u32, 7); pub const DOT11_WFD_STATUS_FAILED_UNKNOWN_WFD_GROUP = @as(u32, 8); pub const DOT11_WFD_STATUS_FAILED_MATCHING_MAX_INTENT = @as(u32, 9); pub const DOT11_WFD_STATUS_FAILED_INCOMPATIBLE_PROVISIONING_METHOD = @as(u32, 10); pub const DOT11_WFD_STATUS_FAILED_REJECTED_BY_USER = @as(u32, 11); pub const DOT11_WFD_STATUS_SUCCESS_ACCEPTED_BY_USER = @as(u32, 12); pub const DOT11_WFD_MINOR_REASON_SUCCESS = @as(u32, 0); pub const DOT11_WFD_MINOR_REASON_DISASSOCIATED_FROM_WLAN_CROSS_CONNECTION_POLICY = @as(u32, 1); pub const DOT11_WFD_MINOR_REASON_DISASSOCIATED_NOT_MANAGED_INFRASTRUCTURE_CAPABLE = @as(u32, 2); pub const DOT11_WFD_MINOR_REASON_DISASSOCIATED_WFD_COEXISTENCE_POLICY = @as(u32, 3); pub const DOT11_WFD_MINOR_REASON_DISASSOCIATED_INFRASTRUCTURE_MANAGED_POLICY = @as(u32, 4); pub const DOT11_WPS_VERSION_1_0 = @as(u32, 1); pub const DOT11_WPS_VERSION_2_0 = @as(u32, 2); pub const DOT11_WFD_DEVICE_CAPABILITY_SERVICE_DISCOVERY = @as(u32, 1); pub const DOT11_WFD_DEVICE_CAPABILITY_P2P_CLIENT_DISCOVERABILITY = @as(u32, 2); pub const DOT11_WFD_DEVICE_CAPABILITY_CONCURRENT_OPERATION = @as(u32, 4); pub const DOT11_WFD_DEVICE_CAPABILITY_P2P_INFRASTRUCTURE_MANAGED = @as(u32, 8); pub const DOT11_WFD_DEVICE_CAPABILITY_P2P_DEVICE_LIMIT = @as(u32, 16); pub const DOT11_WFD_DEVICE_CAPABILITY_P2P_INVITATION_PROCEDURE = @as(u32, 32); pub const DOT11_WFD_DEVICE_CAPABILITY_RESERVED_6 = @as(u32, 64); pub const DOT11_WFD_DEVICE_CAPABILITY_RESERVED_7 = @as(u32, 128); pub const DOT11_WFD_GROUP_CAPABILITY_NONE = @as(u32, 0); pub const DOT11_WFD_GROUP_CAPABILITY_GROUP_OWNER = @as(u32, 1); pub const DOT11_WFD_GROUP_CAPABILITY_PERSISTENT_GROUP = @as(u32, 2); pub const DOT11_WFD_GROUP_CAPABILITY_GROUP_LIMIT_REACHED = @as(u32, 4); pub const DOT11_WFD_GROUP_CAPABILITY_INTRABSS_DISTRIBUTION_SUPPORTED = @as(u32, 8); pub const DOT11_WFD_GROUP_CAPABILITY_CROSS_CONNECTION_SUPPORTED = @as(u32, 16); pub const DOT11_WFD_GROUP_CAPABILITY_PERSISTENT_RECONNECT_SUPPORTED = @as(u32, 32); pub const DOT11_WFD_GROUP_CAPABILITY_IN_GROUP_FORMATION = @as(u32, 64); pub const DOT11_WFD_GROUP_CAPABILITY_RESERVED_7 = @as(u32, 128); pub const DOT11_WFD_GROUP_CAPABILITY_EAPOL_KEY_IP_ADDRESS_ALLOCATION_SUPPORTED = @as(u32, 128); pub const DOT11_WPS_DEVICE_NAME_MAX_LENGTH = @as(u32, 32); pub const DOT11_WPS_MAX_PASSKEY_LENGTH = @as(u32, 8); pub const DOT11_WPS_MAX_MODEL_NAME_LENGTH = @as(u32, 32); pub const DOT11_WPS_MAX_MODEL_NUMBER_LENGTH = @as(u32, 32); pub const WFDSVC_CONNECTION_CAPABILITY_NEW = @as(u32, 1); pub const WFDSVC_CONNECTION_CAPABILITY_CLIENT = @as(u32, 2); pub const WFDSVC_CONNECTION_CAPABILITY_GO = @as(u32, 4); pub const DOT11_WFD_DISCOVER_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_DISCOVER_COMPLETE_MAX_LIST_SIZE = @as(u32, 128); pub const DOT11_GO_NEGOTIATION_REQUEST_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_GO_NEGOTIATION_REQUEST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_GO_NEGOTIATION_RESPONSE_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_GO_NEGOTIATION_RESPONSE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_GO_NEGOTIATION_CONFIRMATION_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_GO_NEGOTIATION_CONFIRMATION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_INVITATION_REQUEST_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_INVITATION_REQUEST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_INVITATION_RESPONSE_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_INVITATION_RESPONSE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_PROVISION_DISCOVERY_REQUEST_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_PROVISION_DISCOVERY_REQUEST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_PROVISION_DISCOVERY_RESPONSE_SEND_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_RECEIVED_PROVISION_DISCOVERY_RESPONSE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_ANQP_QUERY_COMPLETE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_DEVICE_CAPABILITY_CONFIG_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_GROUP_OWNER_CAPABILITY_CONFIG_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_GROUP_OWNER_CAPABILITY_CONFIG_REVISION_2 = @as(u32, 2); pub const DOT11_WFD_DEVICE_INFO_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_SECONDARY_DEVICE_TYPE_LIST_REVISION_1 = @as(u32, 1); pub const DISCOVERY_FILTER_BITMASK_DEVICE = @as(u32, 1); pub const DISCOVERY_FILTER_BITMASK_GO = @as(u32, 2); pub const DISCOVERY_FILTER_BITMASK_ANY = @as(u32, 15); pub const DOT11_WFD_DISCOVER_REQUEST_REVISION_1 = @as(u32, 1); pub const DOT11_DEVICE_ENTRY_BYTE_ARRAY_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_DEVICE_NOT_DISCOVERABLE = @as(u32, 0); pub const DOT11_WFD_DEVICE_AUTO_AVAILABILITY = @as(u32, 16); pub const DOT11_WFD_DEVICE_HIGH_AVAILABILITY = @as(u32, 24); pub const DOT11_WFD_ADDITIONAL_IE_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_GO_NEGOTIATION_REQUEST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_GO_NEGOTIATION_RESPONSE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_GO_NEGOTIATION_CONFIRMATION_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_INVITATION_REQUEST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_INVITATION_RESPONSE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_PROVISION_DISCOVERY_REQUEST_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_SEND_PROVISION_DISCOVERY_RESPONSE_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_DEVICE_LISTEN_CHANNEL_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_GROUP_START_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_WFD_GROUP_JOIN_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_POWER_MGMT_AUTO_MODE_ENABLED_REVISION_1 = @as(u32, 1); pub const DOT11_POWER_MGMT_MODE_STATUS_INFO_REVISION_1 = @as(u32, 1); pub const DOT11_MAX_CHANNEL_HINTS = @as(u32, 4); pub const DOT11_INVALID_CHANNEL_NUMBER = @as(u32, 0); pub const DOT11_NLO_FLAG_STOP_NLO_INDICATION = @as(u32, 1); pub const DOT11_NLO_FLAG_SCAN_ON_AOAC_PLATFORM = @as(u32, 2); pub const DOT11_NLO_FLAG_SCAN_AT_SYSTEM_RESUME = @as(u32, 4); pub const DOT11_OFFLOAD_NETWORK_LIST_REVISION_1 = @as(u32, 1); pub const DOT11_OFFLOAD_NETWORK_STATUS_PARAMETERS_REVISION_1 = @as(u32, 1); pub const DOT11_MANUFACTURING_TEST_REVISION_1 = @as(u32, 1); pub const DOT11_MANUFACTURING_CALLBACK_REVISION_1 = @as(u32, 1); pub const DOT11_SSID_MAX_LENGTH = @as(u32, 32); pub const DOT11_OI_MAX_LENGTH = @as(u32, 5); pub const DOT11_OI_MIN_LENGTH = @as(u32, 3); pub const DevProp_PciRootBus_SecondaryInterface_PciConventional = @as(u32, 0); pub const DevProp_PciRootBus_SecondaryInterface_PciXMode1 = @as(u32, 1); pub const DevProp_PciRootBus_SecondaryInterface_PciXMode2 = @as(u32, 2); pub const DevProp_PciRootBus_SecondaryInterface_PciExpress = @as(u32, 3); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_Conventional_33Mhz = @as(u32, 0); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_Conventional_66Mhz = @as(u32, 1); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_Mode1_66Mhz = @as(u32, 2); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_Mode1_100Mhz = @as(u32, 3); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_Mode1_133Mhz = @as(u32, 4); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_Mode1_ECC_66Mhz = @as(u32, 5); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_Mode1_ECC_100Mhz = @as(u32, 6); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_Mode1_ECC_133Mhz = @as(u32, 7); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_266_Mode2_66Mhz = @as(u32, 8); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_266_Mode2_100Mhz = @as(u32, 9); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_266_Mode2_133Mhz = @as(u32, 10); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_533_Mode2_66Mhz = @as(u32, 11); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_533_Mode2_100Mhz = @as(u32, 12); pub const DevProp_PciRootBus_CurrentSpeedAndMode_Pci_X_533_Mode2_133Mhz = @as(u32, 13); pub const DevProp_PciRootBus_SupportedSpeedsAndModes_Pci_Conventional_33Mhz = @as(u32, 1); pub const DevProp_PciRootBus_SupportedSpeedsAndModes_Pci_Conventional_66Mhz = @as(u32, 2); pub const DevProp_PciRootBus_SupportedSpeedsAndModes_Pci_X_66Mhz = @as(u32, 4); pub const DevProp_PciRootBus_SupportedSpeedsAndModes_Pci_X_133Mhz = @as(u32, 8); pub const DevProp_PciRootBus_SupportedSpeedsAndModes_Pci_X_266Mhz = @as(u32, 16); pub const DevProp_PciRootBus_SupportedSpeedsAndModes_Pci_X_533Mhz = @as(u32, 32); pub const DevProp_PciRootBus_BusWidth_32Bits = @as(u32, 0); pub const DevProp_PciRootBus_BusWidth_64Bits = @as(u32, 1); pub const DevProp_PciDevice_DeviceType_PciConventional = @as(u32, 0); pub const DevProp_PciDevice_DeviceType_PciX = @as(u32, 1); pub const DevProp_PciDevice_DeviceType_PciExpressEndpoint = @as(u32, 2); pub const DevProp_PciDevice_DeviceType_PciExpressLegacyEndpoint = @as(u32, 3); pub const DevProp_PciDevice_DeviceType_PciExpressRootComplexIntegratedEndpoint = @as(u32, 4); pub const DevProp_PciDevice_DeviceType_PciExpressTreatedAsPci = @as(u32, 5); pub const DevProp_PciDevice_BridgeType_PciConventional = @as(u32, 6); pub const DevProp_PciDevice_BridgeType_PciX = @as(u32, 7); pub const DevProp_PciDevice_BridgeType_PciExpressRootPort = @as(u32, 8); pub const DevProp_PciDevice_BridgeType_PciExpressUpstreamSwitchPort = @as(u32, 9); pub const DevProp_PciDevice_BridgeType_PciExpressDownstreamSwitchPort = @as(u32, 10); pub const DevProp_PciDevice_BridgeType_PciExpressToPciXBridge = @as(u32, 11); pub const DevProp_PciDevice_BridgeType_PciXToExpressBridge = @as(u32, 12); pub const DevProp_PciDevice_BridgeType_PciExpressTreatedAsPci = @as(u32, 13); pub const DevProp_PciDevice_BridgeType_PciExpressEventCollector = @as(u32, 14); pub const DevProp_PciDevice_CurrentSpeedAndMode_Pci_Conventional_33MHz = @as(u32, 0); pub const DevProp_PciDevice_CurrentSpeedAndMode_Pci_Conventional_66MHz = @as(u32, 1); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode_Conventional_Pci = @as(u32, 0); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode1_66Mhz = @as(u32, 1); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode1_100Mhz = @as(u32, 2); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode1_133MHZ = @as(u32, 3); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode1_ECC_66Mhz = @as(u32, 5); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode1_ECC_100Mhz = @as(u32, 6); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode1_ECC_133Mhz = @as(u32, 7); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode2_266_66MHz = @as(u32, 9); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode2_266_100MHz = @as(u32, 10); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode2_266_133MHz = @as(u32, 11); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode2_533_66MHz = @as(u32, 13); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode2_533_100MHz = @as(u32, 14); pub const DevProp_PciDevice_CurrentSpeedAndMode_PciX_Mode2_533_133MHz = @as(u32, 15); pub const DevProp_PciExpressDevice_PayloadOrRequestSize_128Bytes = @as(u32, 0); pub const DevProp_PciExpressDevice_PayloadOrRequestSize_256Bytes = @as(u32, 1); pub const DevProp_PciExpressDevice_PayloadOrRequestSize_512Bytes = @as(u32, 2); pub const DevProp_PciExpressDevice_PayloadOrRequestSize_1024Bytes = @as(u32, 3); pub const DevProp_PciExpressDevice_PayloadOrRequestSize_2048Bytes = @as(u32, 4); pub const DevProp_PciExpressDevice_PayloadOrRequestSize_4096Bytes = @as(u32, 5); pub const DevProp_PciExpressDevice_LinkSpeed_TwoAndHalf_Gbps = @as(u32, 1); pub const DevProp_PciExpressDevice_LinkSpeed_Five_Gbps = @as(u32, 2); pub const DevProp_PciExpressDevice_LinkWidth_By_1 = @as(u32, 1); pub const DevProp_PciExpressDevice_LinkWidth_By_2 = @as(u32, 2); pub const DevProp_PciExpressDevice_LinkWidth_By_4 = @as(u32, 4); pub const DevProp_PciExpressDevice_LinkWidth_By_8 = @as(u32, 8); pub const DevProp_PciExpressDevice_LinkWidth_By_12 = @as(u32, 12); pub const DevProp_PciExpressDevice_LinkWidth_By_16 = @as(u32, 16); pub const DevProp_PciExpressDevice_LinkWidth_By_32 = @as(u32, 32); pub const DevProp_PciExpressDevice_Spec_Version_10 = @as(u32, 1); pub const DevProp_PciExpressDevice_Spec_Version_11 = @as(u32, 2); pub const DevProp_PciDevice_InterruptType_LineBased = @as(u32, 1); pub const DevProp_PciDevice_InterruptType_Msi = @as(u32, 2); pub const DevProp_PciDevice_InterruptType_MsiX = @as(u32, 4); pub const DevProp_PciDevice_SriovSupport_Ok = @as(u32, 0); pub const DevProp_PciDevice_SriovSupport_MissingAcs = @as(u32, 1); pub const DevProp_PciDevice_SriovSupport_MissingPfDriver = @as(u32, 2); pub const DevProp_PciDevice_SriovSupport_NoBusResource = @as(u32, 3); pub const DevProp_PciDevice_SriovSupport_DidntGetVfBarSpace = @as(u32, 4); pub const DevProp_PciDevice_AcsSupport_Present = @as(u32, 0); pub const DevProp_PciDevice_AcsSupport_NotNeeded = @as(u32, 1); pub const DevProp_PciDevice_AcsSupport_Missing = @as(u32, 2); pub const DevProp_PciDevice_AcsCompatibleUpHierarchy_NotSupported = @as(u32, 0); pub const DevProp_PciDevice_AcsCompatibleUpHierarchy_SingleFunctionSupported = @as(u32, 1); pub const DevProp_PciDevice_AcsCompatibleUpHierarchy_NoP2PSupported = @as(u32, 2); pub const DevProp_PciDevice_AcsCompatibleUpHierarchy_Supported = @as(u32, 3); pub const DevProp_PciDevice_AcsCompatibleUpHierarchy_Enhanced = @as(u32, 4); pub const WLAN_API_VERSION_1_0 = @as(u32, 1); pub const WLAN_API_VERSION_2_0 = @as(u32, 2); pub const WLAN_API_VERSION = @as(u32, 2); pub const WLAN_MAX_NAME_LENGTH = @as(u32, 256); pub const WLAN_PROFILE_GROUP_POLICY = @as(u32, 1); pub const WLAN_PROFILE_USER = @as(u32, 2); pub const WLAN_PROFILE_GET_PLAINTEXT_KEY = @as(u32, 4); pub const WLAN_PROFILE_CONNECTION_MODE_SET_BY_CLIENT = @as(u32, 65536); pub const WLAN_PROFILE_CONNECTION_MODE_AUTO = @as(u32, 131072); pub const DOT11_PSD_IE_MAX_DATA_SIZE = @as(u32, 240); pub const DOT11_PSD_IE_MAX_ENTRY_NUMBER = @as(u32, 5); pub const WLAN_REASON_CODE_NETWORK_NOT_COMPATIBLE = @as(u32, 131073); pub const WLAN_REASON_CODE_PROFILE_NOT_COMPATIBLE = @as(u32, 131074); pub const WLAN_REASON_CODE_NO_AUTO_CONNECTION = @as(u32, 163841); pub const WLAN_REASON_CODE_NOT_VISIBLE = @as(u32, 163842); pub const WLAN_REASON_CODE_GP_DENIED = @as(u32, 163843); pub const WLAN_REASON_CODE_USER_DENIED = @as(u32, 163844); pub const WLAN_REASON_CODE_BSS_TYPE_NOT_ALLOWED = @as(u32, 163845); pub const WLAN_REASON_CODE_IN_FAILED_LIST = @as(u32, 163846); pub const WLAN_REASON_CODE_IN_BLOCKED_LIST = @as(u32, 163847); pub const WLAN_REASON_CODE_SSID_LIST_TOO_LONG = @as(u32, 163848); pub const WLAN_REASON_CODE_CONNECT_CALL_FAIL = @as(u32, 163849); pub const WLAN_REASON_CODE_SCAN_CALL_FAIL = @as(u32, 163850); pub const WLAN_REASON_CODE_NETWORK_NOT_AVAILABLE = @as(u32, 163851); pub const WLAN_REASON_CODE_PROFILE_CHANGED_OR_DELETED = @as(u32, 163852); pub const WLAN_REASON_CODE_KEY_MISMATCH = @as(u32, 163853); pub const WLAN_REASON_CODE_USER_NOT_RESPOND = @as(u32, 163854); pub const WLAN_REASON_CODE_AP_PROFILE_NOT_ALLOWED_FOR_CLIENT = @as(u32, 163855); pub const WLAN_REASON_CODE_AP_PROFILE_NOT_ALLOWED = @as(u32, 163856); pub const WLAN_REASON_CODE_HOTSPOT2_PROFILE_DENIED = @as(u32, 163857); pub const WLAN_REASON_CODE_INVALID_PROFILE_SCHEMA = @as(u32, 524289); pub const WLAN_REASON_CODE_PROFILE_MISSING = @as(u32, 524290); pub const WLAN_REASON_CODE_INVALID_PROFILE_NAME = @as(u32, 524291); pub const WLAN_REASON_CODE_INVALID_PROFILE_TYPE = @as(u32, 524292); pub const WLAN_REASON_CODE_INVALID_PHY_TYPE = @as(u32, 524293); pub const WLAN_REASON_CODE_MSM_SECURITY_MISSING = @as(u32, 524294); pub const WLAN_REASON_CODE_IHV_SECURITY_NOT_SUPPORTED = @as(u32, 524295); pub const WLAN_REASON_CODE_IHV_OUI_MISMATCH = @as(u32, 524296); pub const WLAN_REASON_CODE_IHV_OUI_MISSING = @as(u32, 524297); pub const WLAN_REASON_CODE_IHV_SETTINGS_MISSING = @as(u32, 524298); pub const WLAN_REASON_CODE_CONFLICT_SECURITY = @as(u32, 524299); pub const WLAN_REASON_CODE_SECURITY_MISSING = @as(u32, 524300); pub const WLAN_REASON_CODE_INVALID_BSS_TYPE = @as(u32, 524301); pub const WLAN_REASON_CODE_INVALID_ADHOC_CONNECTION_MODE = @as(u32, 524302); pub const WLAN_REASON_CODE_NON_BROADCAST_SET_FOR_ADHOC = @as(u32, 524303); pub const WLAN_REASON_CODE_AUTO_SWITCH_SET_FOR_ADHOC = @as(u32, 524304); pub const WLAN_REASON_CODE_AUTO_SWITCH_SET_FOR_MANUAL_CONNECTION = @as(u32, 524305); pub const WLAN_REASON_CODE_IHV_SECURITY_ONEX_MISSING = @as(u32, 524306); pub const WLAN_REASON_CODE_PROFILE_SSID_INVALID = @as(u32, 524307); pub const WLAN_REASON_CODE_TOO_MANY_SSID = @as(u32, 524308); pub const WLAN_REASON_CODE_IHV_CONNECTIVITY_NOT_SUPPORTED = @as(u32, 524309); pub const WLAN_REASON_CODE_BAD_MAX_NUMBER_OF_CLIENTS_FOR_AP = @as(u32, 524310); pub const WLAN_REASON_CODE_INVALID_CHANNEL = @as(u32, 524311); pub const WLAN_REASON_CODE_OPERATION_MODE_NOT_SUPPORTED = @as(u32, 524312); pub const WLAN_REASON_CODE_AUTO_AP_PROFILE_NOT_ALLOWED = @as(u32, 524313); pub const WLAN_REASON_CODE_AUTO_CONNECTION_NOT_ALLOWED = @as(u32, 524314); pub const WLAN_REASON_CODE_HOTSPOT2_PROFILE_NOT_ALLOWED = @as(u32, 524315); pub const WLAN_REASON_CODE_UNSUPPORTED_SECURITY_SET_BY_OS = @as(u32, 196609); pub const WLAN_REASON_CODE_UNSUPPORTED_SECURITY_SET = @as(u32, 196610); pub const WLAN_REASON_CODE_BSS_TYPE_UNMATCH = @as(u32, 196611); pub const WLAN_REASON_CODE_PHY_TYPE_UNMATCH = @as(u32, 196612); pub const WLAN_REASON_CODE_DATARATE_UNMATCH = @as(u32, 196613); pub const WLAN_REASON_CODE_USER_CANCELLED = @as(u32, 229377); pub const WLAN_REASON_CODE_ASSOCIATION_FAILURE = @as(u32, 229378); pub const WLAN_REASON_CODE_ASSOCIATION_TIMEOUT = @as(u32, 229379); pub const WLAN_REASON_CODE_PRE_SECURITY_FAILURE = @as(u32, 229380); pub const WLAN_REASON_CODE_START_SECURITY_FAILURE = @as(u32, 229381); pub const WLAN_REASON_CODE_SECURITY_FAILURE = @as(u32, 229382); pub const WLAN_REASON_CODE_SECURITY_TIMEOUT = @as(u32, 229383); pub const WLAN_REASON_CODE_ROAMING_FAILURE = @as(u32, 229384); pub const WLAN_REASON_CODE_ROAMING_SECURITY_FAILURE = @as(u32, 229385); pub const WLAN_REASON_CODE_ADHOC_SECURITY_FAILURE = @as(u32, 229386); pub const WLAN_REASON_CODE_DRIVER_DISCONNECTED = @as(u32, 229387); pub const WLAN_REASON_CODE_DRIVER_OPERATION_FAILURE = @as(u32, 229388); pub const WLAN_REASON_CODE_IHV_NOT_AVAILABLE = @as(u32, 229389); pub const WLAN_REASON_CODE_IHV_NOT_RESPONDING = @as(u32, 229390); pub const WLAN_REASON_CODE_DISCONNECT_TIMEOUT = @as(u32, 229391); pub const WLAN_REASON_CODE_INTERNAL_FAILURE = @as(u32, 229392); pub const WLAN_REASON_CODE_UI_REQUEST_TIMEOUT = @as(u32, 229393); pub const WLAN_REASON_CODE_TOO_MANY_SECURITY_ATTEMPTS = @as(u32, 229394); pub const WLAN_REASON_CODE_AP_STARTING_FAILURE = @as(u32, 229395); pub const WLAN_REASON_CODE_NO_VISIBLE_AP = @as(u32, 229396); pub const WLAN_REASON_CODE_MSMSEC_MIN = @as(u32, 262144); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_KEY_INDEX = @as(u32, 262145); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_PSK_PRESENT = @as(u32, 262146); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_KEY_LENGTH = @as(u32, 262147); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_PSK_LENGTH = @as(u32, 262148); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_NO_AUTH_CIPHER_SPECIFIED = @as(u32, 262149); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_TOO_MANY_AUTH_CIPHER_SPECIFIED = @as(u32, 262150); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_DUPLICATE_AUTH_CIPHER = @as(u32, 262151); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_RAWDATA_INVALID = @as(u32, 262152); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_AUTH_CIPHER = @as(u32, 262153); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_ONEX_DISABLED = @as(u32, 262154); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_ONEX_ENABLED = @as(u32, 262155); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_PMKCACHE_MODE = @as(u32, 262156); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_PMKCACHE_SIZE = @as(u32, 262157); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_PMKCACHE_TTL = @as(u32, 262158); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_PREAUTH_MODE = @as(u32, 262159); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_PREAUTH_THROTTLE = @as(u32, 262160); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_PREAUTH_ONLY_ENABLED = @as(u32, 262161); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_NETWORK = @as(u32, 262162); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_NIC = @as(u32, 262163); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_PROFILE = @as(u32, 262164); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_DISCOVERY = @as(u32, 262165); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_PASSPHRASE_CHAR = @as(u32, 262166); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_KEYMATERIAL_CHAR = @as(u32, 262167); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_WRONG_KEYTYPE = @as(u32, 262168); pub const WLAN_REASON_CODE_MSMSEC_MIXED_CELL = @as(u32, 262169); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_AUTH_TIMERS_INVALID = @as(u32, 262170); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_INVALID_GKEY_INTV = @as(u32, 262171); pub const WLAN_REASON_CODE_MSMSEC_TRANSITION_NETWORK = @as(u32, 262172); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_KEY_UNMAPPED_CHAR = @as(u32, 262173); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_PROFILE_AUTH = @as(u32, 262174); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_PROFILE_CIPHER = @as(u32, 262175); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_SAFE_MODE = @as(u32, 262176); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_PROFILE_SAFE_MODE_NIC = @as(u32, 262177); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_PROFILE_SAFE_MODE_NW = @as(u32, 262178); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_UNSUPPORTED_AUTH = @as(u32, 262179); pub const WLAN_REASON_CODE_MSMSEC_PROFILE_UNSUPPORTED_CIPHER = @as(u32, 262180); pub const WLAN_REASON_CODE_MSMSEC_CAPABILITY_MFP_NW_NIC = @as(u32, 262181); pub const WLAN_REASON_CODE_MSMSEC_UI_REQUEST_FAILURE = @as(u32, 294913); pub const WLAN_REASON_CODE_MSMSEC_AUTH_START_TIMEOUT = @as(u32, 294914); pub const WLAN_REASON_CODE_MSMSEC_AUTH_SUCCESS_TIMEOUT = @as(u32, 294915); pub const WLAN_REASON_CODE_MSMSEC_KEY_START_TIMEOUT = @as(u32, 294916); pub const WLAN_REASON_CODE_MSMSEC_KEY_SUCCESS_TIMEOUT = @as(u32, 294917); pub const WLAN_REASON_CODE_MSMSEC_M3_MISSING_KEY_DATA = @as(u32, 294918); pub const WLAN_REASON_CODE_MSMSEC_M3_MISSING_IE = @as(u32, 294919); pub const WLAN_REASON_CODE_MSMSEC_M3_MISSING_GRP_KEY = @as(u32, 294920); pub const WLAN_REASON_CODE_MSMSEC_PR_IE_MATCHING = @as(u32, 294921); pub const WLAN_REASON_CODE_MSMSEC_SEC_IE_MATCHING = @as(u32, 294922); pub const WLAN_REASON_CODE_MSMSEC_NO_PAIRWISE_KEY = @as(u32, 294923); pub const WLAN_REASON_CODE_MSMSEC_G1_MISSING_KEY_DATA = @as(u32, 294924); pub const WLAN_REASON_CODE_MSMSEC_G1_MISSING_GRP_KEY = @as(u32, 294925); pub const WLAN_REASON_CODE_MSMSEC_PEER_INDICATED_INSECURE = @as(u32, 294926); pub const WLAN_REASON_CODE_MSMSEC_NO_AUTHENTICATOR = @as(u32, 294927); pub const WLAN_REASON_CODE_MSMSEC_NIC_FAILURE = @as(u32, 294928); pub const WLAN_REASON_CODE_MSMSEC_CANCELLED = @as(u32, 294929); pub const WLAN_REASON_CODE_MSMSEC_KEY_FORMAT = @as(u32, 294930); pub const WLAN_REASON_CODE_MSMSEC_DOWNGRADE_DETECTED = @as(u32, 294931); pub const WLAN_REASON_CODE_MSMSEC_PSK_MISMATCH_SUSPECTED = @as(u32, 294932); pub const WLAN_REASON_CODE_MSMSEC_FORCED_FAILURE = @as(u32, 294933); pub const WLAN_REASON_CODE_MSMSEC_M3_TOO_MANY_RSNIE = @as(u32, 294934); pub const WLAN_REASON_CODE_MSMSEC_M2_MISSING_KEY_DATA = @as(u32, 294935); pub const WLAN_REASON_CODE_MSMSEC_M2_MISSING_IE = @as(u32, 294936); pub const WLAN_REASON_CODE_MSMSEC_AUTH_WCN_COMPLETED = @as(u32, 294937); pub const WLAN_REASON_CODE_MSMSEC_M3_MISSING_MGMT_GRP_KEY = @as(u32, 294938); pub const WLAN_REASON_CODE_MSMSEC_G1_MISSING_MGMT_GRP_KEY = @as(u32, 294939); pub const WLAN_REASON_CODE_MSMSEC_MAX = @as(u32, 327679); pub const WLAN_AVAILABLE_NETWORK_CONNECTED = @as(u32, 1); pub const WLAN_AVAILABLE_NETWORK_HAS_PROFILE = @as(u32, 2); pub const WLAN_AVAILABLE_NETWORK_CONSOLE_USER_PROFILE = @as(u32, 4); pub const WLAN_AVAILABLE_NETWORK_INTERWORKING_SUPPORTED = @as(u32, 8); pub const WLAN_AVAILABLE_NETWORK_HOTSPOT2_ENABLED = @as(u32, 16); pub const WLAN_AVAILABLE_NETWORK_ANQP_SUPPORTED = @as(u32, 32); pub const WLAN_AVAILABLE_NETWORK_HOTSPOT2_DOMAIN = @as(u32, 64); pub const WLAN_AVAILABLE_NETWORK_HOTSPOT2_ROAMING = @as(u32, 128); pub const WLAN_AVAILABLE_NETWORK_AUTO_CONNECT_FAILED = @as(u32, 256); pub const WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_ADHOC_PROFILES = @as(u32, 1); pub const WLAN_AVAILABLE_NETWORK_INCLUDE_ALL_MANUAL_HIDDEN_PROFILES = @as(u32, 2); pub const WLAN_MAX_PHY_TYPE_NUMBER = @as(u32, 8); pub const WLAN_MAX_PHY_INDEX = @as(u32, 64); pub const WLAN_CONNECTION_HIDDEN_NETWORK = @as(u32, 1); pub const WLAN_CONNECTION_ADHOC_JOIN_ONLY = @as(u32, 2); pub const WLAN_CONNECTION_IGNORE_PRIVACY_BIT = @as(u32, 4); pub const WLAN_CONNECTION_EAPOL_PASSTHROUGH = @as(u32, 8); pub const WLAN_CONNECTION_PERSIST_DISCOVERY_PROFILE = @as(u32, 16); pub const WLAN_CONNECTION_PERSIST_DISCOVERY_PROFILE_CONNECTION_MODE_AUTO = @as(u32, 32); pub const WLAN_CONNECTION_PERSIST_DISCOVERY_PROFILE_OVERWRITE_EXISTING = @as(u32, 64); pub const WLAN_NOTIFICATION_SOURCE_NONE = @as(u32, 0); pub const WLAN_NOTIFICATION_SOURCE_ALL = @as(u32, 65535); pub const WLAN_NOTIFICATION_SOURCE_ACM = @as(u32, 8); pub const WLAN_NOTIFICATION_SOURCE_MSM = @as(u32, 16); pub const WLAN_NOTIFICATION_SOURCE_SECURITY = @as(u32, 32); pub const WLAN_NOTIFICATION_SOURCE_IHV = @as(u32, 64); pub const WLAN_NOTIFICATION_SOURCE_HNWK = @as(u32, 128); pub const WLAN_NOTIFICATION_SOURCE_ONEX = @as(u32, 4); pub const WLAN_NOTIFICATION_SOURCE_DEVICE_SERVICE = @as(u32, 2048); pub const WFD_API_VERSION_1_0 = @as(u32, 1); pub const WFD_API_VERSION = @as(u32, 1); pub const WLAN_UI_API_VERSION = @as(u32, 1); pub const WLAN_UI_API_INITIAL_VERSION = @as(u32, 1); pub const GUID_DEVINTERFACE_WIFIDIRECT_DEVICE = Guid.initString("439b20af-8955-405b-99f0-a62af0c68d43"); pub const GUID_AEPSERVICE_WIFIDIRECT_DEVICE = Guid.initString("cc29827c-9caf-4928-99a9-18f7c2381389"); pub const GUID_DEVINTERFACE_ASP_INFRA_DEVICE = Guid.initString("ff823995-7a72-4c80-8757-c67ee13d1a49"); pub const DEVPKEY_WiFiDirect_DeviceAddress = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 1 }; pub const DEVPKEY_WiFiDirect_InterfaceAddress = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 2 }; pub const DEVPKEY_WiFiDirect_InterfaceGuid = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 3 }; pub const DEVPKEY_WiFiDirect_GroupId = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 4 }; pub const DEVPKEY_WiFiDirect_IsConnected = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 5 }; pub const DEVPKEY_WiFiDirect_IsVisible = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 6 }; pub const DEVPKEY_WiFiDirect_IsLegacyDevice = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 7 }; pub const DEVPKEY_WiFiDirect_MiracastVersion = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 8 }; pub const DEVPKEY_WiFiDirect_IsMiracastLCPSupported = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 9 }; pub const DEVPKEY_WiFiDirect_Services = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 10 }; pub const DEVPKEY_WiFiDirect_SupportedChannelList = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 11 }; pub const DEVPKEY_WiFiDirect_InformationElements = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 12 }; pub const DEVPKEY_WiFiDirect_DeviceAddressCopy = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 13 }; pub const DEVPKEY_WiFiDirect_IsRecentlyAssociated = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 14 }; pub const DEVPKEY_WiFiDirect_Service_Aeps = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 15 }; pub const DEVPKEY_WiFiDirect_NoMiracastAutoProject = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 16 }; pub const DEVPKEY_InfraCast_Supported = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 17 }; pub const DEVPKEY_InfraCast_StreamSecuritySupported = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 18 }; pub const DEVPKEY_InfraCast_AccessPointBssid = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 19 }; pub const DEVPKEY_InfraCast_SinkHostName = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 20 }; pub const DEVPKEY_InfraCast_ChallengeAep = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 21 }; pub const DEVPKEY_WiFiDirect_IsDMGCapable = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 22 }; pub const DEVPKEY_InfraCast_DevnodeAep = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 23 }; pub const DEVPKEY_WiFiDirect_FoundWsbService = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 24 }; pub const DEVPKEY_InfraCast_HostName_ResolutionMode = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 25 }; pub const DEVPKEY_InfraCast_SinkIpAddress = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 26 }; pub const DEVPKEY_WiFiDirect_TransientAssociation = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 27 }; pub const DEVPKEY_WiFiDirect_LinkQuality = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 28 }; pub const DEVPKEY_InfraCast_PinSupported = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 29 }; pub const DEVPKEY_InfraCast_RtspTcpConnectionParametersSupported = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 30 }; pub const DEVPKEY_WiFiDirect_Miracast_SessionMgmtControlPort = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 31 }; pub const DEVPKEY_WiFiDirect_RtspTcpConnectionParametersSupported = PROPERTYKEY { .fmtid = Guid.initString("1506935d-e3e7-450f-8637-82233ebe5f6e"), .pid = 32 }; pub const DEVPKEY_WiFiDirectServices_ServiceAddress = PROPERTYKEY { .fmtid = Guid.initString("31b37743-7c5e-4005-93e6-e953f92b82e9"), .pid = 2 }; pub const DEVPKEY_WiFiDirectServices_ServiceName = PROPERTYKEY { .fmtid = Guid.initString("31b37743-7c5e-4005-93e6-e953f92b82e9"), .pid = 3 }; pub const DEVPKEY_WiFiDirectServices_ServiceInformation = PROPERTYKEY { .fmtid = Guid.initString("31b37743-7c5e-4005-93e6-e953f92b82e9"), .pid = 4 }; pub const DEVPKEY_WiFiDirectServices_AdvertisementId = PROPERTYKEY { .fmtid = Guid.initString("31b37743-7c5e-4005-93e6-e953f92b82e9"), .pid = 5 }; pub const DEVPKEY_WiFiDirectServices_ServiceConfigMethods = PROPERTYKEY { .fmtid = Guid.initString("31b37743-7c5e-4005-93e6-e953f92b82e9"), .pid = 6 }; pub const DEVPKEY_WiFiDirectServices_RequestServiceInformation = PROPERTYKEY { .fmtid = Guid.initString("31b37743-7c5e-4005-93e6-e953f92b82e9"), .pid = 7 }; pub const DEVPKEY_WiFi_InterfaceGuid = PROPERTYKEY { .fmtid = Guid.initString("ef1167eb-cbfc-4341-a568-a7c91a68982c"), .pid = 2 }; //-------------------------------------------------------------------------------- // Section: Types (330) //-------------------------------------------------------------------------------- pub const WLAN_SET_EAPHOST_FLAGS = enum(u32) { S = 1, }; pub const WLAN_SET_EAPHOST_DATA_ALL_USERS = WLAN_SET_EAPHOST_FLAGS.S; pub const WLAN_CONNECTION_NOTIFICATION_FLAGS = enum(u32) { ADHOC_NETWORK_FORMED = 1, CONSOLE_USER_PROFILE = 4, }; pub const WLAN_CONNECTION_NOTIFICATION_ADHOC_NETWORK_FORMED = WLAN_CONNECTION_NOTIFICATION_FLAGS.ADHOC_NETWORK_FORMED; pub const WLAN_CONNECTION_NOTIFICATION_CONSOLE_USER_PROFILE = WLAN_CONNECTION_NOTIFICATION_FLAGS.CONSOLE_USER_PROFILE; pub const DOT11_BSS_TYPE = enum(i32) { infrastructure = 1, independent = 2, any = 3, }; pub const dot11_BSS_type_infrastructure = DOT11_BSS_TYPE.infrastructure; pub const dot11_BSS_type_independent = DOT11_BSS_TYPE.independent; pub const dot11_BSS_type_any = DOT11_BSS_TYPE.any; pub const DOT11_SSID = extern struct { uSSIDLength: u32, ucSSID: [32]u8, }; pub const DOT11_AUTH_ALGORITHM = enum(i32) { @"80211_OPEN" = 1, @"80211_SHARED_KEY" = 2, WPA = 3, WPA_PSK = 4, WPA_NONE = 5, RSNA = 6, RSNA_PSK = 7, WPA3 = 8, // WPA3_ENT_192 = 8, this enum value conflicts with WPA3 WPA3_SAE = 9, OWE = 10, WPA3_ENT = 11, IHV_START = -2147483648, IHV_END = -1, }; pub const DOT11_AUTH_ALGO_80211_OPEN = DOT11_AUTH_ALGORITHM.@"80211_OPEN"; pub const DOT11_AUTH_ALGO_80211_SHARED_KEY = DOT11_AUTH_ALGORITHM.@"80211_SHARED_KEY"; pub const DOT11_AUTH_ALGO_WPA = DOT11_AUTH_ALGORITHM.WPA; pub const DOT11_AUTH_ALGO_WPA_PSK = DOT11_AUTH_ALGORITHM.WPA_PSK; pub const DOT11_AUTH_ALGO_WPA_NONE = DOT11_AUTH_ALGORITHM.WPA_NONE; pub const DOT11_AUTH_ALGO_RSNA = DOT11_AUTH_ALGORITHM.RSNA; pub const DOT11_AUTH_ALGO_RSNA_PSK = DOT11_AUTH_ALGORITHM.RSNA_PSK; pub const DOT11_AUTH_ALGO_WPA3 = DOT11_AUTH_ALGORITHM.WPA3; pub const DOT11_AUTH_ALGO_WPA3_ENT_192 = DOT11_AUTH_ALGORITHM.WPA3; pub const DOT11_AUTH_ALGO_WPA3_SAE = DOT11_AUTH_ALGORITHM.WPA3_SAE; pub const DOT11_AUTH_ALGO_OWE = DOT11_AUTH_ALGORITHM.OWE; pub const DOT11_AUTH_ALGO_WPA3_ENT = DOT11_AUTH_ALGORITHM.WPA3_ENT; pub const DOT11_AUTH_ALGO_IHV_START = DOT11_AUTH_ALGORITHM.IHV_START; pub const DOT11_AUTH_ALGO_IHV_END = DOT11_AUTH_ALGORITHM.IHV_END; pub const DOT11_CIPHER_ALGORITHM = enum(i32) { NONE = 0, WEP40 = 1, TKIP = 2, CCMP = 4, WEP104 = 5, BIP = 6, GCMP = 8, GCMP_256 = 9, CCMP_256 = 10, BIP_GMAC_128 = 11, BIP_GMAC_256 = 12, BIP_CMAC_256 = 13, WPA_USE_GROUP = 256, // RSN_USE_GROUP = 256, this enum value conflicts with WPA_USE_GROUP WEP = 257, IHV_START = -2147483648, IHV_END = -1, }; pub const DOT11_CIPHER_ALGO_NONE = DOT11_CIPHER_ALGORITHM.NONE; pub const DOT11_CIPHER_ALGO_WEP40 = DOT11_CIPHER_ALGORITHM.WEP40; pub const DOT11_CIPHER_ALGO_TKIP = DOT11_CIPHER_ALGORITHM.TKIP; pub const DOT11_CIPHER_ALGO_CCMP = DOT11_CIPHER_ALGORITHM.CCMP; pub const DOT11_CIPHER_ALGO_WEP104 = DOT11_CIPHER_ALGORITHM.WEP104; pub const DOT11_CIPHER_ALGO_BIP = DOT11_CIPHER_ALGORITHM.BIP; pub const DOT11_CIPHER_ALGO_GCMP = DOT11_CIPHER_ALGORITHM.GCMP; pub const DOT11_CIPHER_ALGO_GCMP_256 = DOT11_CIPHER_ALGORITHM.GCMP_256; pub const DOT11_CIPHER_ALGO_CCMP_256 = DOT11_CIPHER_ALGORITHM.CCMP_256; pub const DOT11_CIPHER_ALGO_BIP_GMAC_128 = DOT11_CIPHER_ALGORITHM.BIP_GMAC_128; pub const DOT11_CIPHER_ALGO_BIP_GMAC_256 = DOT11_CIPHER_ALGORITHM.BIP_GMAC_256; pub const DOT11_CIPHER_ALGO_BIP_CMAC_256 = DOT11_CIPHER_ALGORITHM.BIP_CMAC_256; pub const DOT11_CIPHER_ALGO_WPA_USE_GROUP = DOT11_CIPHER_ALGORITHM.WPA_USE_GROUP; pub const DOT11_CIPHER_ALGO_RSN_USE_GROUP = DOT11_CIPHER_ALGORITHM.WPA_USE_GROUP; pub const DOT11_CIPHER_ALGO_WEP = DOT11_CIPHER_ALGORITHM.WEP; pub const DOT11_CIPHER_ALGO_IHV_START = DOT11_CIPHER_ALGORITHM.IHV_START; pub const DOT11_CIPHER_ALGO_IHV_END = DOT11_CIPHER_ALGORITHM.IHV_END; pub const DOT11_AUTH_CIPHER_PAIR = extern struct { AuthAlgoId: DOT11_AUTH_ALGORITHM, CipherAlgoId: DOT11_CIPHER_ALGORITHM, }; pub const DOT11_OI = extern struct { OILength: u16, OI: [5]u8, }; pub const DOT11_ACCESSNETWORKOPTIONS = extern struct { AccessNetworkType: u8, Internet: u8, ASRA: u8, ESR: u8, UESA: u8, }; pub const DOT11_VENUEINFO = extern struct { VenueGroup: u8, VenueType: u8, }; pub const DOT11_BSSID_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, BSSIDs: [6]u8, }; pub const DOT11_PHY_TYPE = enum(i32) { unknown = 0, // any = 0, this enum value conflicts with unknown fhss = 1, dsss = 2, irbaseband = 3, ofdm = 4, hrdsss = 5, erp = 6, ht = 7, vht = 8, dmg = 9, he = 10, IHV_start = -2147483648, IHV_end = -1, }; pub const dot11_phy_type_unknown = DOT11_PHY_TYPE.unknown; pub const dot11_phy_type_any = DOT11_PHY_TYPE.unknown; pub const dot11_phy_type_fhss = DOT11_PHY_TYPE.fhss; pub const dot11_phy_type_dsss = DOT11_PHY_TYPE.dsss; pub const dot11_phy_type_irbaseband = DOT11_PHY_TYPE.irbaseband; pub const dot11_phy_type_ofdm = DOT11_PHY_TYPE.ofdm; pub const dot11_phy_type_hrdsss = DOT11_PHY_TYPE.hrdsss; pub const dot11_phy_type_erp = DOT11_PHY_TYPE.erp; pub const dot11_phy_type_ht = DOT11_PHY_TYPE.ht; pub const dot11_phy_type_vht = DOT11_PHY_TYPE.vht; pub const dot11_phy_type_dmg = DOT11_PHY_TYPE.dmg; pub const dot11_phy_type_he = DOT11_PHY_TYPE.he; pub const dot11_phy_type_IHV_start = DOT11_PHY_TYPE.IHV_start; pub const dot11_phy_type_IHV_end = DOT11_PHY_TYPE.IHV_end; pub const DOT11_RATE_SET = extern struct { uRateSetLength: u32, ucRateSet: [126]u8, }; pub const DOT11_WFD_SESSION_INFO = extern struct { uSessionInfoLength: u16, ucSessionInfo: [144]u8, }; pub const DOT11_OFFLOAD_CAPABILITY = extern struct { uReserved: u32, uFlags: u32, uSupportedWEPAlgorithms: u32, uNumOfReplayWindows: u32, uMaxWEPKeyMappingLength: u32, uSupportedAuthAlgorithms: u32, uMaxAuthKeyMappingLength: u32, }; pub const DOT11_CURRENT_OFFLOAD_CAPABILITY = extern struct { uReserved: u32, uFlags: u32, }; pub const DOT11_OFFLOAD_TYPE = enum(i32) { wep = 1, auth = 2, }; pub const dot11_offload_type_wep = DOT11_OFFLOAD_TYPE.wep; pub const dot11_offload_type_auth = DOT11_OFFLOAD_TYPE.auth; pub const DOT11_IV48_COUNTER = extern struct { uIV32Counter: u32, usIV16Counter: u16, }; pub const DOT11_WEP_OFFLOAD = extern struct { uReserved: u32, hOffloadContext: ?HANDLE, hOffload: ?HANDLE, dot11OffloadType: DOT11_OFFLOAD_TYPE, dwAlgorithm: u32, bRowIsOutbound: BOOLEAN, bUseDefault: BOOLEAN, uFlags: u32, ucMacAddress: [6]u8, uNumOfRWsOnPeer: u32, uNumOfRWsOnMe: u32, dot11IV48Counters: [16]DOT11_IV48_COUNTER, usDot11RWBitMaps: [16]u16, usKeyLength: u16, ucKey: [1]u8, }; pub const DOT11_WEP_UPLOAD = extern struct { uReserved: u32, dot11OffloadType: DOT11_OFFLOAD_TYPE, hOffload: ?HANDLE, uNumOfRWsUsed: u32, dot11IV48Counters: [16]DOT11_IV48_COUNTER, usDot11RWBitMaps: [16]u16, }; pub const DOT11_KEY_DIRECTION = enum(i32) { both = 1, inbound = 2, outbound = 3, }; pub const dot11_key_direction_both = DOT11_KEY_DIRECTION.both; pub const dot11_key_direction_inbound = DOT11_KEY_DIRECTION.inbound; pub const dot11_key_direction_outbound = DOT11_KEY_DIRECTION.outbound; pub const DOT11_DEFAULT_WEP_OFFLOAD = extern struct { uReserved: u32, hOffloadContext: ?HANDLE, hOffload: ?HANDLE, dwIndex: u32, dot11OffloadType: DOT11_OFFLOAD_TYPE, dwAlgorithm: u32, uFlags: u32, dot11KeyDirection: DOT11_KEY_DIRECTION, ucMacAddress: [6]u8, uNumOfRWsOnMe: u32, dot11IV48Counters: [16]DOT11_IV48_COUNTER, usDot11RWBitMaps: [16]u16, usKeyLength: u16, ucKey: [1]u8, }; pub const DOT11_DEFAULT_WEP_UPLOAD = extern struct { uReserved: u32, dot11OffloadType: DOT11_OFFLOAD_TYPE, hOffload: ?HANDLE, uNumOfRWsUsed: u32, dot11IV48Counters: [16]DOT11_IV48_COUNTER, usDot11RWBitMaps: [16]u16, }; pub const DOT11_OPERATION_MODE_CAPABILITY = extern struct { uReserved: u32, uMajorVersion: u32, uMinorVersion: u32, uNumOfTXBuffers: u32, uNumOfRXBuffers: u32, uOpModeCapability: u32, }; pub const DOT11_CURRENT_OPERATION_MODE = extern struct { uReserved: u32, uCurrentOpMode: u32, }; pub const DOT11_SCAN_TYPE = enum(i32) { active = 1, passive = 2, auto = 3, forced = -2147483648, }; pub const dot11_scan_type_active = DOT11_SCAN_TYPE.active; pub const dot11_scan_type_passive = DOT11_SCAN_TYPE.passive; pub const dot11_scan_type_auto = DOT11_SCAN_TYPE.auto; pub const dot11_scan_type_forced = DOT11_SCAN_TYPE.forced; pub const DOT11_SCAN_REQUEST = extern struct { dot11BSSType: DOT11_BSS_TYPE, dot11BSSID: [6]u8, dot11SSID: DOT11_SSID, dot11ScanType: DOT11_SCAN_TYPE, bRestrictedScan: BOOLEAN, bUseRequestIE: BOOLEAN, uRequestIDsOffset: u32, uNumOfRequestIDs: u32, uPhyTypesOffset: u32, uNumOfPhyTypes: u32, uIEsOffset: u32, uIEsLength: u32, ucBuffer: [1]u8, }; pub const CH_DESCRIPTION_TYPE = enum(i32) { logical = 1, center_frequency = 2, phy_specific = 3, }; pub const ch_description_type_logical = CH_DESCRIPTION_TYPE.logical; pub const ch_description_type_center_frequency = CH_DESCRIPTION_TYPE.center_frequency; pub const ch_description_type_phy_specific = CH_DESCRIPTION_TYPE.phy_specific; pub const DOT11_PHY_TYPE_INFO = extern struct { dot11PhyType: DOT11_PHY_TYPE, bUseParameters: BOOLEAN, uProbeDelay: u32, uMinChannelTime: u32, uMaxChannelTime: u32, ChDescriptionType: CH_DESCRIPTION_TYPE, uChannelListSize: u32, ucChannelListBuffer: [1]u8, }; pub const DOT11_SCAN_REQUEST_V2 = extern struct { dot11BSSType: DOT11_BSS_TYPE, dot11BSSID: [6]u8, dot11ScanType: DOT11_SCAN_TYPE, bRestrictedScan: BOOLEAN, udot11SSIDsOffset: u32, uNumOfdot11SSIDs: u32, bUseRequestIE: BOOLEAN, uRequestIDsOffset: u32, uNumOfRequestIDs: u32, uPhyTypeInfosOffset: u32, uNumOfPhyTypeInfos: u32, uIEsOffset: u32, uIEsLength: u32, ucBuffer: [1]u8, }; pub const DOT11_PHY_TYPE_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11PhyType: [1]DOT11_PHY_TYPE, }; pub const DOT11_BSS_DESCRIPTION = extern struct { uReserved: u32, dot11BSSID: [6]u8, dot11BSSType: DOT11_BSS_TYPE, usBeaconPeriod: u16, ullTimestamp: u64, usCapabilityInformation: u16, uBufferLength: u32, ucBuffer: [1]u8, }; pub const DOT11_JOIN_REQUEST = extern struct { uJoinFailureTimeout: u32, OperationalRateSet: DOT11_RATE_SET, uChCenterFrequency: u32, dot11BSSDescription: DOT11_BSS_DESCRIPTION, }; pub const DOT11_START_REQUEST = extern struct { uStartFailureTimeout: u32, OperationalRateSet: DOT11_RATE_SET, uChCenterFrequency: u32, dot11BSSDescription: DOT11_BSS_DESCRIPTION, }; pub const DOT11_UPDATE_IE_OP = enum(i32) { create_replace = 1, delete = 2, }; pub const dot11_update_ie_op_create_replace = DOT11_UPDATE_IE_OP.create_replace; pub const dot11_update_ie_op_delete = DOT11_UPDATE_IE_OP.delete; pub const DOT11_UPDATE_IE = extern struct { dot11UpdateIEOp: DOT11_UPDATE_IE_OP, uBufferLength: u32, ucBuffer: [1]u8, }; pub const DOT11_RESET_TYPE = enum(i32) { phy = 1, mac = 2, phy_and_mac = 3, }; pub const dot11_reset_type_phy = DOT11_RESET_TYPE.phy; pub const dot11_reset_type_mac = DOT11_RESET_TYPE.mac; pub const dot11_reset_type_phy_and_mac = DOT11_RESET_TYPE.phy_and_mac; pub const DOT11_RESET_REQUEST = extern struct { dot11ResetType: DOT11_RESET_TYPE, dot11MacAddress: [6]u8, bSetDefaultMIB: BOOLEAN, }; pub const DOT11_OPTIONAL_CAPABILITY = extern struct { uReserved: u32, bDot11PCF: BOOLEAN, bDot11PCFMPDUTransferToPC: BOOLEAN, bStrictlyOrderedServiceClass: BOOLEAN, }; pub const DOT11_CURRENT_OPTIONAL_CAPABILITY = extern struct { uReserved: u32, bDot11CFPollable: BOOLEAN, bDot11PCF: BOOLEAN, bDot11PCFMPDUTransferToPC: BOOLEAN, bStrictlyOrderedServiceClass: BOOLEAN, }; pub const DOT11_POWER_MODE = enum(i32) { unknown = 0, active = 1, powersave = 2, }; pub const dot11_power_mode_unknown = DOT11_POWER_MODE.unknown; pub const dot11_power_mode_active = DOT11_POWER_MODE.active; pub const dot11_power_mode_powersave = DOT11_POWER_MODE.powersave; pub const DOT11_POWER_MGMT_MODE = extern struct { dot11PowerMode: DOT11_POWER_MODE, uPowerSaveLevel: u32, usListenInterval: u16, usAID: u16, bReceiveDTIMs: BOOLEAN, }; pub const DOT11_COUNTERS_ENTRY = extern struct { uTransmittedFragmentCount: u32, uMulticastTransmittedFrameCount: u32, uFailedCount: u32, uRetryCount: u32, uMultipleRetryCount: u32, uFrameDuplicateCount: u32, uRTSSuccessCount: u32, uRTSFailureCount: u32, uACKFailureCount: u32, uReceivedFragmentCount: u32, uMulticastReceivedFrameCount: u32, uFCSErrorCount: u32, uTransmittedFrameCount: u32, }; pub const DOT11_SUPPORTED_PHY_TYPES = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11PHYType: [1]DOT11_PHY_TYPE, }; pub const DOT11_TEMP_TYPE = enum(i32) { unknown = 0, @"1" = 1, @"2" = 2, }; pub const dot11_temp_type_unknown = DOT11_TEMP_TYPE.unknown; pub const dot11_temp_type_1 = DOT11_TEMP_TYPE.@"1"; pub const dot11_temp_type_2 = DOT11_TEMP_TYPE.@"2"; pub const DOT11_DIVERSITY_SUPPORT = enum(i32) { unknown = 0, fixedlist = 1, notsupported = 2, dynamic = 3, }; pub const dot11_diversity_support_unknown = DOT11_DIVERSITY_SUPPORT.unknown; pub const dot11_diversity_support_fixedlist = DOT11_DIVERSITY_SUPPORT.fixedlist; pub const dot11_diversity_support_notsupported = DOT11_DIVERSITY_SUPPORT.notsupported; pub const dot11_diversity_support_dynamic = DOT11_DIVERSITY_SUPPORT.dynamic; pub const DOT11_SUPPORTED_POWER_LEVELS = extern struct { uNumOfSupportedPowerLevels: u32, uTxPowerLevelValues: [8]u32, }; pub const DOT11_REG_DOMAIN_VALUE = extern struct { uRegDomainsSupportIndex: u32, uRegDomainsSupportValue: u32, }; pub const DOT11_REG_DOMAINS_SUPPORT_VALUE = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11RegDomainValue: [1]DOT11_REG_DOMAIN_VALUE, }; pub const DOT11_SUPPORTED_ANTENNA = extern struct { uAntennaListIndex: u32, bSupportedAntenna: BOOLEAN, }; pub const DOT11_SUPPORTED_ANTENNA_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11SupportedAntenna: [1]DOT11_SUPPORTED_ANTENNA, }; pub const DOT11_DIVERSITY_SELECTION_RX = extern struct { uAntennaListIndex: u32, bDiversitySelectionRX: BOOLEAN, }; pub const DOT11_DIVERSITY_SELECTION_RX_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11DiversitySelectionRx: [1]DOT11_DIVERSITY_SELECTION_RX, }; pub const DOT11_SUPPORTED_DATA_RATES_VALUE = extern struct { ucSupportedTxDataRatesValue: [8]u8, ucSupportedRxDataRatesValue: [8]u8, }; pub const DOT11_SUPPORTED_DATA_RATES_VALUE_V2 = extern struct { ucSupportedTxDataRatesValue: [255]u8, ucSupportedRxDataRatesValue: [255]u8, }; pub const DOT11_MULTI_DOMAIN_CAPABILITY_ENTRY = extern struct { uMultiDomainCapabilityIndex: u32, uFirstChannelNumber: u32, uNumberOfChannels: u32, lMaximumTransmitPowerLevel: i32, }; pub const DOT11_MD_CAPABILITY_ENTRY_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11MDCapabilityEntry: [1]DOT11_MULTI_DOMAIN_CAPABILITY_ENTRY, }; pub const DOT11_HOP_ALGO_ADOPTED = enum(i32) { current = 0, hop_index = 1, hcc = 2, }; pub const dot11_hop_algo_current = DOT11_HOP_ALGO_ADOPTED.current; pub const dot11_hop_algo_hop_index = DOT11_HOP_ALGO_ADOPTED.hop_index; pub const dot11_hop_algo_hcc = DOT11_HOP_ALGO_ADOPTED.hcc; pub const DOT11_HOPPING_PATTERN_ENTRY = extern struct { uHoppingPatternIndex: u32, uRandomTableFieldNumber: u32, }; pub const DOT11_HOPPING_PATTERN_ENTRY_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11HoppingPatternEntry: [1]DOT11_HOPPING_PATTERN_ENTRY, }; pub const DOT11_WPA_TSC = extern struct { uReserved: u32, dot11OffloadType: DOT11_OFFLOAD_TYPE, hOffload: ?HANDLE, dot11IV48Counter: DOT11_IV48_COUNTER, }; pub const DOT11_RSSI_RANGE = extern struct { dot11PhyType: DOT11_PHY_TYPE, uRSSIMin: u32, uRSSIMax: u32, }; pub const DOT11_NIC_SPECIFIC_EXTENSION = extern struct { uBufferLength: u32, uTotalBufferLength: u32, ucBuffer: [1]u8, }; pub const DOT11_AP_JOIN_REQUEST = extern struct { uJoinFailureTimeout: u32, OperationalRateSet: DOT11_RATE_SET, uChCenterFrequency: u32, dot11BSSDescription: DOT11_BSS_DESCRIPTION, }; pub const DOT11_RECV_SENSITIVITY = extern struct { ucDataRate: u8, lRSSIMin: i32, lRSSIMax: i32, }; pub const DOT11_RECV_SENSITIVITY_LIST = extern struct { Anonymous: extern union { dot11PhyType: DOT11_PHY_TYPE, uPhyId: u32, }, uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11RecvSensitivity: [1]DOT11_RECV_SENSITIVITY, }; pub const DOT11_AC_PARAM = enum(i32) { BE = 0, BK = 1, VI = 2, VO = 3, max = 4, }; pub const dot11_AC_param_BE = DOT11_AC_PARAM.BE; pub const dot11_AC_param_BK = DOT11_AC_PARAM.BK; pub const dot11_AC_param_VI = DOT11_AC_PARAM.VI; pub const dot11_AC_param_VO = DOT11_AC_PARAM.VO; pub const dot11_AC_param_max = DOT11_AC_PARAM.max; pub const DOT11_WME_AC_PARAMETERS = extern struct { ucAccessCategoryIndex: u8, ucAIFSN: u8, ucECWmin: u8, ucECWmax: u8, usTXOPLimit: u16, }; pub const _DOT11_WME_AC_PARAMTERS_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11WMEACParameters: [1]DOT11_WME_AC_PARAMETERS, }; pub const DOT11_WME_UPDATE_IE = extern struct { uParamElemMinBeaconIntervals: u32, uWMEInfoElemOffset: u32, uWMEInfoElemLength: u32, uWMEParamElemOffset: u32, uWMEParamElemLength: u32, ucBuffer: [1]u8, }; pub const DOT11_QOS_TX_DURATION = extern struct { uNominalMSDUSize: u32, uMinPHYRate: u32, uDuration: u32, }; pub const DOT11_QOS_TX_MEDIUM_TIME = extern struct { dot11PeerAddress: [6]u8, ucQoSPriority: u8, uMediumTimeAdmited: u32, }; pub const DOT11_SUPPORTED_OFDM_FREQUENCY = extern struct { uCenterFrequency: u32, }; pub const DOT11_SUPPORTED_OFDM_FREQUENCY_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11SupportedOFDMFrequency: [1]DOT11_SUPPORTED_OFDM_FREQUENCY, }; pub const DOT11_SUPPORTED_DSSS_CHANNEL = extern struct { uChannel: u32, }; pub const DOT11_SUPPORTED_DSSS_CHANNEL_LIST = extern struct { uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11SupportedDSSSChannel: [1]DOT11_SUPPORTED_DSSS_CHANNEL, }; pub const DOT11_BYTE_ARRAY = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfBytes: u32, uTotalNumOfBytes: u32, ucBuffer: [1]u8, }; pub const DOT11_BSS_ENTRY_PHY_SPECIFIC_INFO = extern union { uChCenterFrequency: u32, FHSS: extern struct { uHopPattern: u32, uHopSet: u32, uDwellTime: u32, }, }; pub const DOT11_BSS_ENTRY = extern struct { uPhyId: u32, PhySpecificInfo: DOT11_BSS_ENTRY_PHY_SPECIFIC_INFO, dot11BSSID: [6]u8, dot11BSSType: DOT11_BSS_TYPE, lRSSI: i32, uLinkQuality: u32, bInRegDomain: BOOLEAN, usBeaconPeriod: u16, ullTimestamp: u64, ullHostTimestamp: u64, usCapabilityInformation: u16, uBufferLength: u32, ucBuffer: [1]u8, }; pub const DOT11_SSID_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, SSIDs: [1]DOT11_SSID, }; pub const DOT11_MAC_ADDRESS_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, MacAddrs: [6]u8, }; pub const DOT11_PMKID_ENTRY = extern struct { BSSID: [6]u8, PMKID: [16]u8, uFlags: u32, }; pub const DOT11_PMKID_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, PMKIDs: [1]DOT11_PMKID_ENTRY, }; pub const DOT11_PHY_FRAME_STATISTICS = extern struct { ullTransmittedFrameCount: u64, ullMulticastTransmittedFrameCount: u64, ullFailedCount: u64, ullRetryCount: u64, ullMultipleRetryCount: u64, ullMaxTXLifetimeExceededCount: u64, ullTransmittedFragmentCount: u64, ullRTSSuccessCount: u64, ullRTSFailureCount: u64, ullACKFailureCount: u64, ullReceivedFrameCount: u64, ullMulticastReceivedFrameCount: u64, ullPromiscuousReceivedFrameCount: u64, ullMaxRXLifetimeExceededCount: u64, ullFrameDuplicateCount: u64, ullReceivedFragmentCount: u64, ullPromiscuousReceivedFragmentCount: u64, ullFCSErrorCount: u64, }; pub const DOT11_MAC_FRAME_STATISTICS = extern struct { ullTransmittedFrameCount: u64, ullReceivedFrameCount: u64, ullTransmittedFailureFrameCount: u64, ullReceivedFailureFrameCount: u64, ullWEPExcludedCount: u64, ullTKIPLocalMICFailures: u64, ullTKIPReplays: u64, ullTKIPICVErrorCount: u64, ullCCMPReplays: u64, ullCCMPDecryptErrors: u64, ullWEPUndecryptableCount: u64, ullWEPICVErrorCount: u64, ullDecryptSuccessCount: u64, ullDecryptFailureCount: u64, }; pub const DOT11_STATISTICS = extern struct { Header: NDIS_OBJECT_HEADER, ullFourWayHandshakeFailures: u64, ullTKIPCounterMeasuresInvoked: u64, ullReserved: u64, MacUcastCounters: DOT11_MAC_FRAME_STATISTICS, MacMcastCounters: DOT11_MAC_FRAME_STATISTICS, PhyCounters: [1]DOT11_PHY_FRAME_STATISTICS, }; pub const DOT11_PRIVACY_EXEMPTION = extern struct { usEtherType: u16, usExemptionActionType: u16, usExemptionPacketType: u16, }; pub const DOT11_PRIVACY_EXEMPTION_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, PrivacyExemptionEntries: [1]DOT11_PRIVACY_EXEMPTION, }; pub const DOT11_AUTH_ALGORITHM_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, AlgorithmIds: [1]DOT11_AUTH_ALGORITHM, }; pub const DOT11_AUTH_CIPHER_PAIR_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, AuthCipherPairs: [1]DOT11_AUTH_CIPHER_PAIR, }; pub const DOT11_CIPHER_ALGORITHM_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, AlgorithmIds: [1]DOT11_CIPHER_ALGORITHM, }; pub const DOT11_CIPHER_DEFAULT_KEY_VALUE = extern struct { Header: NDIS_OBJECT_HEADER, uKeyIndex: u32, AlgorithmId: DOT11_CIPHER_ALGORITHM, MacAddr: [6]u8, bDelete: BOOLEAN, bStatic: BOOLEAN, usKeyLength: u16, ucKey: [1]u8, }; pub const DOT11_KEY_ALGO_TKIP_MIC = extern struct { ucIV48Counter: [6]u8, ulTKIPKeyLength: u32, ulMICKeyLength: u32, ucTKIPMICKeys: [1]u8, }; pub const DOT11_KEY_ALGO_CCMP = extern struct { ucIV48Counter: [6]u8, ulCCMPKeyLength: u32, ucCCMPKey: [1]u8, }; pub const DOT11_KEY_ALGO_GCMP = extern struct { ucIV48Counter: [6]u8, ulGCMPKeyLength: u32, ucGCMPKey: [1]u8, }; pub const DOT11_KEY_ALGO_GCMP_256 = extern struct { ucIV48Counter: [6]u8, ulGCMP256KeyLength: u32, ucGCMP256Key: [1]u8, }; pub const DOT11_KEY_ALGO_BIP = extern struct { ucIPN: [6]u8, ulBIPKeyLength: u32, ucBIPKey: [1]u8, }; pub const DOT11_KEY_ALGO_BIP_GMAC_256 = extern struct { ucIPN: [6]u8, ulBIPGmac256KeyLength: u32, ucBIPGmac256Key: [1]u8, }; pub const DOT11_DIRECTION = enum(i32) { INBOUND = 1, OUTBOUND = 2, BOTH = 3, }; pub const DOT11_DIR_INBOUND = DOT11_DIRECTION.INBOUND; pub const DOT11_DIR_OUTBOUND = DOT11_DIRECTION.OUTBOUND; pub const DOT11_DIR_BOTH = DOT11_DIRECTION.BOTH; pub const DOT11_CIPHER_KEY_MAPPING_KEY_VALUE = extern struct { PeerMacAddr: [6]u8, AlgorithmId: DOT11_CIPHER_ALGORITHM, Direction: DOT11_DIRECTION, bDelete: BOOLEAN, bStatic: BOOLEAN, usKeyLength: u16, ucKey: [1]u8, }; pub const DOT11_ASSOCIATION_STATE = enum(i32) { zero = 0, unauth_unassoc = 1, auth_unassoc = 2, auth_assoc = 3, }; pub const dot11_assoc_state_zero = DOT11_ASSOCIATION_STATE.zero; pub const dot11_assoc_state_unauth_unassoc = DOT11_ASSOCIATION_STATE.unauth_unassoc; pub const dot11_assoc_state_auth_unassoc = DOT11_ASSOCIATION_STATE.auth_unassoc; pub const dot11_assoc_state_auth_assoc = DOT11_ASSOCIATION_STATE.auth_assoc; pub const DOT11_ASSOCIATION_INFO_EX = extern struct { PeerMacAddress: [6]u8, BSSID: [6]u8, usCapabilityInformation: u16, usListenInterval: u16, ucPeerSupportedRates: [255]u8, usAssociationID: u16, dot11AssociationState: DOT11_ASSOCIATION_STATE, dot11PowerMode: DOT11_POWER_MODE, liAssociationUpTime: LARGE_INTEGER, ullNumOfTxPacketSuccesses: u64, ullNumOfTxPacketFailures: u64, ullNumOfRxPacketSuccesses: u64, ullNumOfRxPacketFailures: u64, }; pub const DOT11_ASSOCIATION_INFO_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11AssocInfo: [1]DOT11_ASSOCIATION_INFO_EX, }; pub const DOT11_PHY_ID_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, dot11PhyId: [1]u32, }; pub const DOT11_EXTSTA_CAPABILITY = extern struct { Header: NDIS_OBJECT_HEADER, uScanSSIDListSize: u32, uDesiredBSSIDListSize: u32, uDesiredSSIDListSize: u32, uExcludedMacAddressListSize: u32, uPrivacyExemptionListSize: u32, uKeyMappingTableSize: u32, uDefaultKeyTableSize: u32, uWEPKeyValueMaxLength: u32, uPMKIDCacheSize: u32, uMaxNumPerSTADefaultKeyTables: u32, }; pub const DOT11_DATA_RATE_MAPPING_ENTRY = extern struct { ucDataRateIndex: u8, ucDataRateFlag: u8, usDataRateValue: u16, }; pub const DOT11_DATA_RATE_MAPPING_TABLE = extern struct { Header: NDIS_OBJECT_HEADER, uDataRateMappingLength: u32, DataRateMappingEntries: [126]DOT11_DATA_RATE_MAPPING_ENTRY, }; pub const DOT11_COUNTRY_OR_REGION_STRING_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, CountryOrRegionStrings: [3]u8, }; pub const DOT11_PORT_STATE_NOTIFICATION = extern struct { Header: NDIS_OBJECT_HEADER, PeerMac: [6]u8, bOpen: BOOLEAN, }; pub const DOT11_IBSS_PARAMS = extern struct { Header: NDIS_OBJECT_HEADER, bJoinOnly: BOOLEAN, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_QOS_PARAMS = extern struct { Header: NDIS_OBJECT_HEADER, ucEnabledQoSProtocolFlags: u8, }; pub const DOT11_ASSOCIATION_PARAMS = extern struct { Header: NDIS_OBJECT_HEADER, BSSID: [6]u8, uAssocRequestIEsOffset: u32, uAssocRequestIEsLength: u32, }; pub const DOT11_FRAGMENT_DESCRIPTOR = extern struct { uOffset: u32, uLength: u32, }; pub const DOT11_PER_MSDU_COUNTERS = extern struct { uTransmittedFragmentCount: u32, uRetryCount: u32, uRTSSuccessCount: u32, uRTSFailureCount: u32, uACKFailureCount: u32, }; pub const DOT11_HRDSSS_PHY_ATTRIBUTES = extern struct { bShortPreambleOptionImplemented: BOOLEAN, bPBCCOptionImplemented: BOOLEAN, bChannelAgilityPresent: BOOLEAN, uHRCCAModeSupported: u32, }; pub const DOT11_OFDM_PHY_ATTRIBUTES = extern struct { uFrequencyBandsSupported: u32, }; pub const DOT11_ERP_PHY_ATTRIBUTES = extern struct { HRDSSSAttributes: DOT11_HRDSSS_PHY_ATTRIBUTES, bERPPBCCOptionImplemented: BOOLEAN, bDSSSOFDMOptionImplemented: BOOLEAN, bShortSlotTimeOptionImplemented: BOOLEAN, }; pub const DOT11_PHY_ATTRIBUTES = extern struct { Header: NDIS_OBJECT_HEADER, PhyType: DOT11_PHY_TYPE, bHardwarePhyState: BOOLEAN, bSoftwarePhyState: BOOLEAN, bCFPollable: BOOLEAN, uMPDUMaxLength: u32, TempType: DOT11_TEMP_TYPE, DiversitySupport: DOT11_DIVERSITY_SUPPORT, PhySpecificAttributes: extern union { HRDSSSAttributes: DOT11_HRDSSS_PHY_ATTRIBUTES, OFDMAttributes: DOT11_OFDM_PHY_ATTRIBUTES, ERPAttributes: DOT11_ERP_PHY_ATTRIBUTES, }, uNumberSupportedPowerLevels: u32, TxPowerLevels: [8]u32, uNumDataRateMappingEntries: u32, DataRateMappingEntries: [126]DOT11_DATA_RATE_MAPPING_ENTRY, SupportedDataRatesValue: DOT11_SUPPORTED_DATA_RATES_VALUE_V2, }; pub const DOT11_EXTSTA_ATTRIBUTES = extern struct { Header: NDIS_OBJECT_HEADER, uScanSSIDListSize: u32, uDesiredBSSIDListSize: u32, uDesiredSSIDListSize: u32, uExcludedMacAddressListSize: u32, uPrivacyExemptionListSize: u32, uKeyMappingTableSize: u32, uDefaultKeyTableSize: u32, uWEPKeyValueMaxLength: u32, uPMKIDCacheSize: u32, uMaxNumPerSTADefaultKeyTables: u32, bStrictlyOrderedServiceClassImplemented: BOOLEAN, ucSupportedQoSProtocolFlags: u8, bSafeModeImplemented: BOOLEAN, uNumSupportedCountryOrRegionStrings: u32, pSupportedCountryOrRegionStrings: ?*u8, uInfraNumSupportedUcastAlgoPairs: u32, pInfraSupportedUcastAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, uInfraNumSupportedMcastAlgoPairs: u32, pInfraSupportedMcastAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, uAdhocNumSupportedUcastAlgoPairs: u32, pAdhocSupportedUcastAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, uAdhocNumSupportedMcastAlgoPairs: u32, pAdhocSupportedMcastAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, bAutoPowerSaveMode: BOOLEAN, uMaxNetworkOffloadListSize: u32, bMFPCapable: BOOLEAN, uInfraNumSupportedMcastMgmtAlgoPairs: u32, pInfraSupportedMcastMgmtAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, bNeighborReportSupported: BOOLEAN, bAPChannelReportSupported: BOOLEAN, bActionFramesSupported: BOOLEAN, bANQPQueryOffloadSupported: BOOLEAN, bHESSIDConnectionSupported: BOOLEAN, }; pub const DOT11_RECV_EXTENSION_INFO = extern struct { uVersion: u32, pvReserved: ?*anyopaque, dot11PhyType: DOT11_PHY_TYPE, uChCenterFrequency: u32, lRSSI: i32, lRSSIMin: i32, lRSSIMax: i32, uRSSI: u32, ucPriority: u8, ucDataRate: u8, ucPeerMacAddress: [6]u8, dwExtendedStatus: u32, hWEPOffloadContext: ?HANDLE, hAuthOffloadContext: ?HANDLE, usWEPAppliedMask: u16, usWPAMSDUPriority: u16, dot11LowestIV48Counter: DOT11_IV48_COUNTER, usDot11LeftRWBitMap: u16, dot11HighestIV48Counter: DOT11_IV48_COUNTER, usDot11RightRWBitMap: u16, usNumberOfMPDUsReceived: u16, usNumberOfFragments: u16, pNdisPackets: [1]?*anyopaque, }; pub const DOT11_RECV_EXTENSION_INFO_V2 = extern struct { uVersion: u32, pvReserved: ?*anyopaque, dot11PhyType: DOT11_PHY_TYPE, uChCenterFrequency: u32, lRSSI: i32, uRSSI: u32, ucPriority: u8, ucDataRate: u8, ucPeerMacAddress: [6]u8, dwExtendedStatus: u32, hWEPOffloadContext: ?HANDLE, hAuthOffloadContext: ?HANDLE, usWEPAppliedMask: u16, usWPAMSDUPriority: u16, dot11LowestIV48Counter: DOT11_IV48_COUNTER, usDot11LeftRWBitMap: u16, dot11HighestIV48Counter: DOT11_IV48_COUNTER, usDot11RightRWBitMap: u16, usNumberOfMPDUsReceived: u16, usNumberOfFragments: u16, pNdisPackets: [1]?*anyopaque, }; pub const DOT11_STATUS_INDICATION = extern struct { uStatusType: u32, ndisStatus: i32, }; pub const DOT11_MPDU_MAX_LENGTH_INDICATION = extern struct { Header: NDIS_OBJECT_HEADER, uPhyId: u32, uMPDUMaxLength: u32, }; pub const DOT11_ASSOCIATION_START_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, MacAddr: [6]u8, SSID: DOT11_SSID, uIHVDataOffset: u32, uIHVDataSize: u32, }; pub const DOT11_ENCAP_ENTRY = extern struct { usEtherType: u16, usEncapType: u16, }; pub const DOT11_DS_INFO = enum(i32) { CHANGED = 0, UNCHANGED = 1, UNKNOWN = 2, }; pub const DOT11_DS_CHANGED = DOT11_DS_INFO.CHANGED; pub const DOT11_DS_UNCHANGED = DOT11_DS_INFO.UNCHANGED; pub const DOT11_DS_UNKNOWN = DOT11_DS_INFO.UNKNOWN; pub const DOT11_ASSOCIATION_COMPLETION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, MacAddr: [6]u8, uStatus: u32, bReAssocReq: BOOLEAN, bReAssocResp: BOOLEAN, uAssocReqOffset: u32, uAssocReqSize: u32, uAssocRespOffset: u32, uAssocRespSize: u32, uBeaconOffset: u32, uBeaconSize: u32, uIHVDataOffset: u32, uIHVDataSize: u32, AuthAlgo: DOT11_AUTH_ALGORITHM, UnicastCipher: DOT11_CIPHER_ALGORITHM, MulticastCipher: DOT11_CIPHER_ALGORITHM, uActivePhyListOffset: u32, uActivePhyListSize: u32, bFourAddressSupported: BOOLEAN, bPortAuthorized: BOOLEAN, ucActiveQoSProtocol: u8, DSInfo: DOT11_DS_INFO, uEncapTableOffset: u32, uEncapTableSize: u32, MulticastMgmtCipher: DOT11_CIPHER_ALGORITHM, uAssocComebackTime: u32, }; pub const DOT11_CONNECTION_START_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, BSSType: DOT11_BSS_TYPE, AdhocBSSID: [6]u8, AdhocSSID: DOT11_SSID, }; pub const DOT11_CONNECTION_COMPLETION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, uStatus: u32, }; pub const DOT11_ROAMING_START_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, AdhocBSSID: [6]u8, AdhocSSID: DOT11_SSID, uRoamingReason: u32, }; pub const DOT11_ROAMING_COMPLETION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, uStatus: u32, }; pub const DOT11_DISASSOCIATION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, MacAddr: [6]u8, uReason: u32, uIHVDataOffset: u32, uIHVDataSize: u32, }; pub const DOT11_TKIPMIC_FAILURE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, bDefaultKeyFailure: BOOLEAN, uKeyIndex: u32, PeerMac: [6]u8, }; pub const DOT11_PMKID_CANDIDATE_LIST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, uCandidateListSize: u32, uCandidateListOffset: u32, }; pub const DOT11_BSSID_CANDIDATE = extern struct { BSSID: [6]u8, uFlags: u32, }; pub const DOT11_PHY_STATE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, uPhyId: u32, bHardwarePhyState: BOOLEAN, bSoftwarePhyState: BOOLEAN, }; pub const DOT11_LINK_QUALITY_ENTRY = extern struct { PeerMacAddr: [6]u8, ucLinkQuality: u8, }; pub const DOT11_LINK_QUALITY_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, uLinkQualityListSize: u32, uLinkQualityListOffset: u32, }; pub const DOT11_EXTSTA_SEND_CONTEXT = extern struct { Header: NDIS_OBJECT_HEADER, usExemptionActionType: u16, uPhyId: u32, uDelayedSleepValue: u32, pvMediaSpecificInfo: ?*anyopaque, uSendFlags: u32, }; pub const DOT11_EXTSTA_RECV_CONTEXT = extern struct { Header: NDIS_OBJECT_HEADER, uReceiveFlags: u32, uPhyId: u32, uChCenterFrequency: u32, usNumberOfMPDUsReceived: u16, lRSSI: i32, ucDataRate: u8, uSizeMediaSpecificInfo: u32, pvMediaSpecificInfo: ?*anyopaque, ullTimestamp: u64, }; pub const DOT11_EXTAP_ATTRIBUTES = extern struct { Header: NDIS_OBJECT_HEADER, uScanSSIDListSize: u32, uDesiredSSIDListSize: u32, uPrivacyExemptionListSize: u32, uAssociationTableSize: u32, uDefaultKeyTableSize: u32, uWEPKeyValueMaxLength: u32, bStrictlyOrderedServiceClassImplemented: BOOLEAN, uNumSupportedCountryOrRegionStrings: u32, pSupportedCountryOrRegionStrings: ?*u8, uInfraNumSupportedUcastAlgoPairs: u32, pInfraSupportedUcastAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, uInfraNumSupportedMcastAlgoPairs: u32, pInfraSupportedMcastAlgoPairs: ?*DOT11_AUTH_CIPHER_PAIR, }; pub const DOT11_INCOMING_ASSOC_STARTED_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerMacAddr: [6]u8, }; pub const DOT11_INCOMING_ASSOC_REQUEST_RECEIVED_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerMacAddr: [6]u8, bReAssocReq: BOOLEAN, uAssocReqOffset: u32, uAssocReqSize: u32, }; pub const DOT11_INCOMING_ASSOC_COMPLETION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerMacAddr: [6]u8, uStatus: u32, ucErrorSource: u8, bReAssocReq: BOOLEAN, bReAssocResp: BOOLEAN, uAssocReqOffset: u32, uAssocReqSize: u32, uAssocRespOffset: u32, uAssocRespSize: u32, AuthAlgo: DOT11_AUTH_ALGORITHM, UnicastCipher: DOT11_CIPHER_ALGORITHM, MulticastCipher: DOT11_CIPHER_ALGORITHM, uActivePhyListOffset: u32, uActivePhyListSize: u32, uBeaconOffset: u32, uBeaconSize: u32, }; pub const DOT11_STOP_AP_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ulReason: u32, }; pub const DOT11_PHY_FREQUENCY_ADOPTED_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ulPhyId: u32, Anonymous: extern union { ulChannel: u32, ulFrequency: u32, }, }; pub const DOT11_CAN_SUSTAIN_AP_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ulReason: u32, }; pub const DOT11_AVAILABLE_CHANNEL_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, uChannelNumber: [1]u32, }; pub const DOT11_AVAILABLE_FREQUENCY_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, uFrequencyValue: [1]u32, }; pub const DOT11_DISASSOCIATE_PEER_REQUEST = extern struct { Header: NDIS_OBJECT_HEADER, PeerMacAddr: [6]u8, usReason: u16, }; pub const DOT11_INCOMING_ASSOC_DECISION = extern struct { Header: NDIS_OBJECT_HEADER, PeerMacAddr: [6]u8, bAccept: BOOLEAN, usReasonCode: u16, uAssocResponseIEsOffset: u32, uAssocResponseIEsLength: u32, }; pub const DOT11_INCOMING_ASSOC_DECISION_V2 = extern struct { Header: NDIS_OBJECT_HEADER, PeerMacAddr: [6]u8, bAccept: BOOLEAN, usReasonCode: u16, uAssocResponseIEsOffset: u32, uAssocResponseIEsLength: u32, WFDStatus: u8, }; pub const DOT11_ADDITIONAL_IE = extern struct { Header: NDIS_OBJECT_HEADER, uBeaconIEsOffset: u32, uBeaconIEsLength: u32, uResponseIEsOffset: u32, uResponseIEsLength: u32, }; pub const DOT11_PEER_STATISTICS = extern struct { ullDecryptSuccessCount: u64, ullDecryptFailureCount: u64, ullTxPacketSuccessCount: u64, ullTxPacketFailureCount: u64, ullRxPacketSuccessCount: u64, ullRxPacketFailureCount: u64, }; pub const DOT11_PEER_INFO = extern struct { MacAddress: [6]u8, usCapabilityInformation: u16, AuthAlgo: DOT11_AUTH_ALGORITHM, UnicastCipherAlgo: DOT11_CIPHER_ALGORITHM, MulticastCipherAlgo: DOT11_CIPHER_ALGORITHM, bWpsEnabled: BOOLEAN, usListenInterval: u16, ucSupportedRates: [255]u8, usAssociationID: u16, AssociationState: DOT11_ASSOCIATION_STATE, PowerMode: DOT11_POWER_MODE, liAssociationUpTime: LARGE_INTEGER, Statistics: DOT11_PEER_STATISTICS, }; pub const DOT11_PEER_INFO_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, PeerInfo: [1]DOT11_PEER_INFO, }; pub const DOT11_VWIFI_COMBINATION = extern struct { Header: NDIS_OBJECT_HEADER, uNumInfrastructure: u32, uNumAdhoc: u32, uNumSoftAP: u32, }; pub const DOT11_VWIFI_COMBINATION_V2 = extern struct { Header: NDIS_OBJECT_HEADER, uNumInfrastructure: u32, uNumAdhoc: u32, uNumSoftAP: u32, uNumVirtualStation: u32, }; pub const DOT11_VWIFI_COMBINATION_V3 = extern struct { Header: NDIS_OBJECT_HEADER, uNumInfrastructure: u32, uNumAdhoc: u32, uNumSoftAP: u32, uNumVirtualStation: u32, uNumWFDGroup: u32, }; pub const DOT11_VWIFI_ATTRIBUTES = extern struct { Header: NDIS_OBJECT_HEADER, uTotalNumOfEntries: u32, Combinations: [1]DOT11_VWIFI_COMBINATION, }; pub const DOT11_MAC_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, uOpmodeMask: u32, }; pub const DOT11_MAC_INFO = extern struct { uReserved: u32, uNdisPortNumber: u32, MacAddr: [6]u8, }; pub const DOT11_WFD_ATTRIBUTES = extern struct { Header: NDIS_OBJECT_HEADER, uNumConcurrentGORole: u32, uNumConcurrentClientRole: u32, WPSVersionsSupported: u32, bServiceDiscoverySupported: BOOLEAN, bClientDiscoverabilitySupported: BOOLEAN, bInfrastructureManagementSupported: BOOLEAN, uMaxSecondaryDeviceTypeListSize: u32, DeviceAddress: [6]u8, uInterfaceAddressListCount: u32, pInterfaceAddressList: ?*u8, uNumSupportedCountryOrRegionStrings: u32, pSupportedCountryOrRegionStrings: ?*u8, uDiscoveryFilterListSize: u32, uGORoleClientTableSize: u32, }; pub const DOT11_WFD_DEVICE_TYPE = extern struct { CategoryID: u16, SubCategoryID: u16, OUI: [4]u8, }; pub const DOT11_WPS_DEVICE_NAME = extern struct { uDeviceNameLength: u32, ucDeviceName: [32]u8, }; pub const DOT11_WFD_CONFIGURATION_TIMEOUT = extern struct { GOTimeout: u8, ClientTimeout: u8, }; pub const DOT11_WFD_GROUP_ID = extern struct { DeviceAddress: [6]u8, SSID: DOT11_SSID, }; pub const DOT11_WFD_GO_INTENT = extern struct { _bitfield: u8, }; pub const DOT11_WFD_CHANNEL = extern struct { CountryRegionString: [3]u8, OperatingClass: u8, ChannelNumber: u8, }; pub const DOT11_WPS_CONFIG_METHOD = enum(i32) { NULL = 0, DISPLAY = 8, NFC_TAG = 32, NFC_INTERFACE = 64, PUSHBUTTON = 128, KEYPAD = 256, WFDS_DEFAULT = 4096, }; pub const DOT11_WPS_CONFIG_METHOD_NULL = DOT11_WPS_CONFIG_METHOD.NULL; pub const DOT11_WPS_CONFIG_METHOD_DISPLAY = DOT11_WPS_CONFIG_METHOD.DISPLAY; pub const DOT11_WPS_CONFIG_METHOD_NFC_TAG = DOT11_WPS_CONFIG_METHOD.NFC_TAG; pub const DOT11_WPS_CONFIG_METHOD_NFC_INTERFACE = DOT11_WPS_CONFIG_METHOD.NFC_INTERFACE; pub const DOT11_WPS_CONFIG_METHOD_PUSHBUTTON = DOT11_WPS_CONFIG_METHOD.PUSHBUTTON; pub const DOT11_WPS_CONFIG_METHOD_KEYPAD = DOT11_WPS_CONFIG_METHOD.KEYPAD; pub const DOT11_WPS_CONFIG_METHOD_WFDS_DEFAULT = DOT11_WPS_CONFIG_METHOD.WFDS_DEFAULT; pub const DOT11_WPS_DEVICE_PASSWORD_ID = enum(i32) { DEFAULT = 0, USER_SPECIFIED = 1, MACHINE_SPECIFIED = 2, REKEY = 3, PUSHBUTTON = 4, REGISTRAR_SPECIFIED = 5, NFC_CONNECTION_HANDOVER = 7, WFD_SERVICES = 8, OOB_RANGE_MIN = 16, OOB_RANGE_MAX = 65535, }; pub const DOT11_WPS_PASSWORD_ID_DEFAULT = DOT11_WPS_DEVICE_PASSWORD_ID.DEFAULT; pub const DOT11_WPS_PASSWORD_ID_USER_SPECIFIED = DOT11_WPS_DEVICE_PASSWORD_ID.USER_SPECIFIED; pub const DOT11_WPS_PASSWORD_ID_MACHINE_SPECIFIED = DOT11_WPS_DEVICE_PASSWORD_ID.MACHINE_SPECIFIED; pub const DOT11_WPS_PASSWORD_ID_REKEY = DOT11_WPS_DEVICE_PASSWORD_ID.REKEY; pub const DOT11_WPS_PASSWORD_ID_PUSHBUTTON = DOT11_WPS_DEVICE_PASSWORD_ID.PUSHBUTTON; pub const DOT11_WPS_PASSWORD_ID_REGISTRAR_SPECIFIED = DOT11_WPS_DEVICE_PASSWORD_ID.REGISTRAR_SPECIFIED; pub const DOT11_WPS_PASSWORD_ID_NFC_CONNECTION_HANDOVER = DOT11_WPS_DEVICE_PASSWORD_ID.NFC_CONNECTION_HANDOVER; pub const DOT11_WPS_PASSWORD_ID_WFD_SERVICES = DOT11_WPS_DEVICE_PASSWORD_ID.WFD_SERVICES; pub const DOT11_WPS_PASSWORD_ID_OOB_RANGE_MIN = DOT11_WPS_DEVICE_PASSWORD_ID.OOB_RANGE_MIN; pub const DOT11_WPS_PASSWORD_ID_OOB_RANGE_MAX = DOT11_WPS_DEVICE_PASSWORD_ID.OOB_RANGE_MAX; pub const WFDSVC_CONNECTION_CAPABILITY = extern struct { bNew: BOOLEAN, bClient: BOOLEAN, bGO: BOOLEAN, }; pub const DOT11_WFD_SERVICE_HASH_LIST = extern struct { ServiceHashCount: u16, ServiceHash: [6]u8, }; pub const DOT11_WFD_ADVERTISEMENT_ID = extern struct { AdvertisementID: u32, ServiceAddress: [6]u8, }; pub const DOT11_WFD_SESSION_ID = extern struct { SessionID: u32, SessionAddress: [6]u8, }; pub const DOT11_WFD_ADVERTISED_SERVICE_DESCRIPTOR = extern struct { AdvertisementID: u32, ConfigMethods: u16, ServiceNameLength: u8, ServiceName: [255]u8, }; pub const DOT11_WFD_ADVERTISED_SERVICE_LIST = extern struct { ServiceCount: u16, AdvertisedService: [1]DOT11_WFD_ADVERTISED_SERVICE_DESCRIPTOR, }; pub const DOT11_WFD_DISCOVER_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, Status: i32, uNumOfEntries: u32, uTotalNumOfEntries: u32, uListOffset: u32, uListLength: u32, }; pub const DOT11_GO_NEGOTIATION_REQUEST_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_GO_NEGOTIATION_REQUEST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, RequestContext: ?*anyopaque, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_GO_NEGOTIATION_RESPONSE_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_GO_NEGOTIATION_RESPONSE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, ResponseContext: ?*anyopaque, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_GO_NEGOTIATION_CONFIRMATION_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_GO_NEGOTIATION_CONFIRMATION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_INVITATION_REQUEST_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, ReceiverAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_INVITATION_REQUEST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, TransmitterDeviceAddress: [6]u8, BSSID: [6]u8, DialogToken: u8, RequestContext: ?*anyopaque, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_INVITATION_RESPONSE_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ReceiverDeviceAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_INVITATION_RESPONSE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, TransmitterDeviceAddress: [6]u8, BSSID: [6]u8, DialogToken: u8, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_PROVISION_DISCOVERY_REQUEST_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, ReceiverAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_PROVISION_DISCOVERY_REQUEST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, TransmitterDeviceAddress: [6]u8, BSSID: [6]u8, DialogToken: u8, RequestContext: ?*anyopaque, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_PROVISION_DISCOVERY_RESPONSE_SEND_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ReceiverDeviceAddress: [6]u8, DialogToken: u8, Status: i32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_RECEIVED_PROVISION_DISCOVERY_RESPONSE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, TransmitterDeviceAddress: [6]u8, BSSID: [6]u8, DialogToken: u8, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_ANQP_QUERY_RESULT = enum(i32) { success = 0, failure = 1, timed_out = 2, resources = 3, advertisement_protocol_not_supported_on_remote = 4, gas_protocol_failure = 5, advertisement_server_not_responding = 6, access_issues = 7, }; pub const dot11_ANQP_query_result_success = DOT11_ANQP_QUERY_RESULT.success; pub const dot11_ANQP_query_result_failure = DOT11_ANQP_QUERY_RESULT.failure; pub const dot11_ANQP_query_result_timed_out = DOT11_ANQP_QUERY_RESULT.timed_out; pub const dot11_ANQP_query_result_resources = DOT11_ANQP_QUERY_RESULT.resources; pub const dot11_ANQP_query_result_advertisement_protocol_not_supported_on_remote = DOT11_ANQP_QUERY_RESULT.advertisement_protocol_not_supported_on_remote; pub const dot11_ANQP_query_result_gas_protocol_failure = DOT11_ANQP_QUERY_RESULT.gas_protocol_failure; pub const dot11_ANQP_query_result_advertisement_server_not_responding = DOT11_ANQP_QUERY_RESULT.advertisement_server_not_responding; pub const dot11_ANQP_query_result_access_issues = DOT11_ANQP_QUERY_RESULT.access_issues; pub const DOT11_ANQP_QUERY_COMPLETE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, Status: DOT11_ANQP_QUERY_RESULT, hContext: ?HANDLE, uResponseLength: u32, }; pub const DOT11_WFD_DEVICE_CAPABILITY_CONFIG = extern struct { Header: NDIS_OBJECT_HEADER, bServiceDiscoveryEnabled: BOOLEAN, bClientDiscoverabilityEnabled: BOOLEAN, bConcurrentOperationSupported: BOOLEAN, bInfrastructureManagementEnabled: BOOLEAN, bDeviceLimitReached: BOOLEAN, bInvitationProcedureEnabled: BOOLEAN, WPSVersionsEnabled: u32, }; pub const DOT11_WFD_GROUP_OWNER_CAPABILITY_CONFIG = extern struct { Header: NDIS_OBJECT_HEADER, bPersistentGroupEnabled: BOOLEAN, bIntraBSSDistributionSupported: BOOLEAN, bCrossConnectionSupported: BOOLEAN, bPersistentReconnectSupported: BOOLEAN, bGroupFormationEnabled: BOOLEAN, uMaximumGroupLimit: u32, }; pub const DOT11_WFD_GROUP_OWNER_CAPABILITY_CONFIG_V2 = extern struct { Header: NDIS_OBJECT_HEADER, bPersistentGroupEnabled: BOOLEAN, bIntraBSSDistributionSupported: BOOLEAN, bCrossConnectionSupported: BOOLEAN, bPersistentReconnectSupported: BOOLEAN, bGroupFormationEnabled: BOOLEAN, uMaximumGroupLimit: u32, bEapolKeyIpAddressAllocationSupported: BOOLEAN, }; pub const DOT11_WFD_DEVICE_INFO = extern struct { Header: NDIS_OBJECT_HEADER, DeviceAddress: [6]u8, ConfigMethods: u16, PrimaryDeviceType: DOT11_WFD_DEVICE_TYPE, DeviceName: DOT11_WPS_DEVICE_NAME, }; pub const DOT11_WFD_SECONDARY_DEVICE_TYPE_LIST = extern struct { Header: NDIS_OBJECT_HEADER, uNumOfEntries: u32, uTotalNumOfEntries: u32, SecondaryDeviceTypes: [1]DOT11_WFD_DEVICE_TYPE, }; pub const DOT11_WFD_DISCOVER_TYPE = enum(i32) { scan_only = 1, find_only = 2, auto = 3, scan_social_channels = 4, forced = -2147483648, }; pub const dot11_wfd_discover_type_scan_only = DOT11_WFD_DISCOVER_TYPE.scan_only; pub const dot11_wfd_discover_type_find_only = DOT11_WFD_DISCOVER_TYPE.find_only; pub const dot11_wfd_discover_type_auto = DOT11_WFD_DISCOVER_TYPE.auto; pub const dot11_wfd_discover_type_scan_social_channels = DOT11_WFD_DISCOVER_TYPE.scan_social_channels; pub const dot11_wfd_discover_type_forced = DOT11_WFD_DISCOVER_TYPE.forced; pub const DOT11_WFD_SCAN_TYPE = enum(i32) { active = 1, passive = 2, auto = 3, }; pub const dot11_wfd_scan_type_active = DOT11_WFD_SCAN_TYPE.active; pub const dot11_wfd_scan_type_passive = DOT11_WFD_SCAN_TYPE.passive; pub const dot11_wfd_scan_type_auto = DOT11_WFD_SCAN_TYPE.auto; pub const DOT11_WFD_DISCOVER_DEVICE_FILTER = extern struct { DeviceID: [6]u8, ucBitmask: u8, GroupSSID: DOT11_SSID, }; pub const DOT11_WFD_DISCOVER_REQUEST = extern struct { Header: NDIS_OBJECT_HEADER, DiscoverType: DOT11_WFD_DISCOVER_TYPE, ScanType: DOT11_WFD_SCAN_TYPE, uDiscoverTimeout: u32, uDeviceFilterListOffset: u32, uNumDeviceFilters: u32, uIEsOffset: u32, uIEsLength: u32, bForceScanLegacyNetworks: BOOLEAN, }; pub const DOT11_WFD_DEVICE_ENTRY = extern struct { uPhyId: u32, PhySpecificInfo: DOT11_BSS_ENTRY_PHY_SPECIFIC_INFO, dot11BSSID: [6]u8, dot11BSSType: DOT11_BSS_TYPE, TransmitterAddress: [6]u8, lRSSI: i32, uLinkQuality: u32, usBeaconPeriod: u16, ullTimestamp: u64, ullBeaconHostTimestamp: u64, ullProbeResponseHostTimestamp: u64, usCapabilityInformation: u16, uBeaconIEsOffset: u32, uBeaconIEsLength: u32, uProbeResponseIEsOffset: u32, uProbeResponseIEsLength: u32, }; pub const DOT11_WFD_ADDITIONAL_IE = extern struct { Header: NDIS_OBJECT_HEADER, uBeaconIEsOffset: u32, uBeaconIEsLength: u32, uProbeResponseIEsOffset: u32, uProbeResponseIEsLength: u32, uDefaultRequestIEsOffset: u32, uDefaultRequestIEsLength: u32, }; pub const DOT11_SEND_GO_NEGOTIATION_REQUEST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, uSendTimeout: u32, GroupOwnerIntent: DOT11_WFD_GO_INTENT, MinimumConfigTimeout: DOT11_WFD_CONFIGURATION_TIMEOUT, IntendedInterfaceAddress: [6]u8, GroupCapability: u8, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_SEND_GO_NEGOTIATION_RESPONSE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, RequestContext: ?*anyopaque, uSendTimeout: u32, Status: u8, GroupOwnerIntent: DOT11_WFD_GO_INTENT, MinimumConfigTimeout: DOT11_WFD_CONFIGURATION_TIMEOUT, IntendedInterfaceAddress: [6]u8, GroupCapability: u8, GroupID: DOT11_WFD_GROUP_ID, bUseGroupID: BOOLEAN, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_SEND_GO_NEGOTIATION_CONFIRMATION_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, PeerDeviceAddress: [6]u8, DialogToken: u8, ResponseContext: ?*anyopaque, uSendTimeout: u32, Status: u8, GroupCapability: u8, GroupID: DOT11_WFD_GROUP_ID, bUseGroupID: BOOLEAN, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_WFD_INVITATION_FLAGS = extern struct { _bitfield: u8, }; pub const DOT11_SEND_INVITATION_REQUEST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, DialogToken: u8, PeerDeviceAddress: [6]u8, uSendTimeout: u32, MinimumConfigTimeout: DOT11_WFD_CONFIGURATION_TIMEOUT, InvitationFlags: DOT11_WFD_INVITATION_FLAGS, GroupBSSID: [6]u8, bUseGroupBSSID: BOOLEAN, OperatingChannel: DOT11_WFD_CHANNEL, bUseSpecifiedOperatingChannel: BOOLEAN, GroupID: DOT11_WFD_GROUP_ID, bLocalGO: BOOLEAN, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_SEND_INVITATION_RESPONSE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ReceiverDeviceAddress: [6]u8, DialogToken: u8, RequestContext: ?*anyopaque, uSendTimeout: u32, Status: u8, MinimumConfigTimeout: DOT11_WFD_CONFIGURATION_TIMEOUT, GroupBSSID: [6]u8, bUseGroupBSSID: BOOLEAN, OperatingChannel: DOT11_WFD_CHANNEL, bUseSpecifiedOperatingChannel: BOOLEAN, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_SEND_PROVISION_DISCOVERY_REQUEST_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, DialogToken: u8, PeerDeviceAddress: [6]u8, uSendTimeout: u32, GroupCapability: u8, GroupID: DOT11_WFD_GROUP_ID, bUseGroupID: BOOLEAN, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_SEND_PROVISION_DISCOVERY_RESPONSE_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, ReceiverDeviceAddress: [6]u8, DialogToken: u8, RequestContext: ?*anyopaque, uSendTimeout: u32, uIEsOffset: u32, uIEsLength: u32, }; pub const DOT11_WFD_DEVICE_LISTEN_CHANNEL = extern struct { Header: NDIS_OBJECT_HEADER, ChannelNumber: u8, }; pub const DOT11_WFD_GROUP_START_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, AdvertisedOperatingChannel: DOT11_WFD_CHANNEL, }; pub const DOT11_WFD_GROUP_JOIN_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, GOOperatingChannel: DOT11_WFD_CHANNEL, GOConfigTime: u32, bInGroupFormation: BOOLEAN, bWaitForWPSReady: BOOLEAN, }; pub const DOT11_POWER_MGMT_AUTO_MODE_ENABLED_INFO = extern struct { Header: NDIS_OBJECT_HEADER, bEnabled: BOOLEAN, }; pub const DOT11_POWER_MODE_REASON = enum(i32) { no_change = 0, noncompliant_AP = 1, legacy_WFD_device = 2, compliant_AP = 3, compliant_WFD_device = 4, others = 5, }; pub const dot11_power_mode_reason_no_change = DOT11_POWER_MODE_REASON.no_change; pub const dot11_power_mode_reason_noncompliant_AP = DOT11_POWER_MODE_REASON.noncompliant_AP; pub const dot11_power_mode_reason_legacy_WFD_device = DOT11_POWER_MODE_REASON.legacy_WFD_device; pub const dot11_power_mode_reason_compliant_AP = DOT11_POWER_MODE_REASON.compliant_AP; pub const dot11_power_mode_reason_compliant_WFD_device = DOT11_POWER_MODE_REASON.compliant_WFD_device; pub const dot11_power_mode_reason_others = DOT11_POWER_MODE_REASON.others; pub const DOT11_POWER_MGMT_MODE_STATUS_INFO = extern struct { Header: NDIS_OBJECT_HEADER, PowerSaveMode: DOT11_POWER_MODE, uPowerSaveLevel: u32, Reason: DOT11_POWER_MODE_REASON, }; pub const DOT11_CHANNEL_HINT = extern struct { Dot11PhyType: DOT11_PHY_TYPE, uChannelNumber: u32, }; pub const DOT11_OFFLOAD_NETWORK = extern struct { Ssid: DOT11_SSID, UnicastCipher: DOT11_CIPHER_ALGORITHM, AuthAlgo: DOT11_AUTH_ALGORITHM, Dot11ChannelHints: [4]DOT11_CHANNEL_HINT, }; pub const DOT11_OFFLOAD_NETWORK_LIST_INFO = extern struct { Header: NDIS_OBJECT_HEADER, ulFlags: u32, FastScanPeriod: u32, FastScanIterations: u32, SlowScanPeriod: u32, uNumOfEntries: u32, offloadNetworkList: [1]DOT11_OFFLOAD_NETWORK, }; pub const DOT11_OFFLOAD_NETWORK_STATUS_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, Status: i32, }; pub const DOT11_MANUFACTURING_TEST_TYPE = enum(i32) { unknown = 0, self_start = 1, self_query_result = 2, rx = 3, tx = 4, query_adc = 5, set_data = 6, query_data = 7, sleep = 8, awake = 9, IHV_start = -2147483648, IHV_end = -1, }; pub const dot11_manufacturing_test_unknown = DOT11_MANUFACTURING_TEST_TYPE.unknown; pub const dot11_manufacturing_test_self_start = DOT11_MANUFACTURING_TEST_TYPE.self_start; pub const dot11_manufacturing_test_self_query_result = DOT11_MANUFACTURING_TEST_TYPE.self_query_result; pub const dot11_manufacturing_test_rx = DOT11_MANUFACTURING_TEST_TYPE.rx; pub const dot11_manufacturing_test_tx = DOT11_MANUFACTURING_TEST_TYPE.tx; pub const dot11_manufacturing_test_query_adc = DOT11_MANUFACTURING_TEST_TYPE.query_adc; pub const dot11_manufacturing_test_set_data = DOT11_MANUFACTURING_TEST_TYPE.set_data; pub const dot11_manufacturing_test_query_data = DOT11_MANUFACTURING_TEST_TYPE.query_data; pub const dot11_manufacturing_test_sleep = DOT11_MANUFACTURING_TEST_TYPE.sleep; pub const dot11_manufacturing_test_awake = DOT11_MANUFACTURING_TEST_TYPE.awake; pub const dot11_manufacturing_test_IHV_start = DOT11_MANUFACTURING_TEST_TYPE.IHV_start; pub const dot11_manufacturing_test_IHV_end = DOT11_MANUFACTURING_TEST_TYPE.IHV_end; pub const DOT11_MANUFACTURING_TEST = extern struct { dot11ManufacturingTestType: DOT11_MANUFACTURING_TEST_TYPE, uBufferLength: u32, ucBuffer: [1]u8, }; pub const DOT11_MANUFACTURING_SELF_TEST_TYPE = enum(i32) { INTERFACE = 1, RF_INTERFACE = 2, BT_COEXISTENCE = 3, }; pub const DOT11_MANUFACTURING_SELF_TEST_TYPE_INTERFACE = DOT11_MANUFACTURING_SELF_TEST_TYPE.INTERFACE; pub const DOT11_MANUFACTURING_SELF_TEST_TYPE_RF_INTERFACE = DOT11_MANUFACTURING_SELF_TEST_TYPE.RF_INTERFACE; pub const DOT11_MANUFACTURING_SELF_TEST_TYPE_BT_COEXISTENCE = DOT11_MANUFACTURING_SELF_TEST_TYPE.BT_COEXISTENCE; pub const DOT11_MANUFACTURING_SELF_TEST_SET_PARAMS = extern struct { SelfTestType: DOT11_MANUFACTURING_SELF_TEST_TYPE, uTestID: u32, uPinBitMask: u32, pvContext: ?*anyopaque, uBufferLength: u32, ucBufferIn: [1]u8, }; pub const DOT11_MANUFACTURING_SELF_TEST_QUERY_RESULTS = extern struct { SelfTestType: DOT11_MANUFACTURING_SELF_TEST_TYPE, uTestID: u32, bResult: BOOLEAN, uPinFailedBitMask: u32, pvContext: ?*anyopaque, uBytesWrittenOut: u32, ucBufferOut: [1]u8, }; pub const DOT11_BAND = enum(i32) { @"2p4g" = 1, @"4p9g" = 2, @"5g" = 3, }; pub const dot11_band_2p4g = DOT11_BAND.@"2p4g"; pub const dot11_band_4p9g = DOT11_BAND.@"4p9g"; pub const dot11_band_5g = DOT11_BAND.@"5g"; pub const DOT11_MANUFACTURING_FUNCTIONAL_TEST_RX = extern struct { bEnabled: BOOLEAN, Dot11Band: DOT11_BAND, uChannel: u32, PowerLevel: i32, }; pub const DOT11_MANUFACTURING_FUNCTIONAL_TEST_TX = extern struct { bEnable: BOOLEAN, bOpenLoop: BOOLEAN, Dot11Band: DOT11_BAND, uChannel: u32, uSetPowerLevel: u32, ADCPowerLevel: i32, }; pub const DOT11_MANUFACTURING_FUNCTIONAL_TEST_QUERY_ADC = extern struct { Dot11Band: DOT11_BAND, uChannel: u32, ADCPowerLevel: i32, }; pub const DOT11_MANUFACTURING_TEST_SET_DATA = extern struct { uKey: u32, uOffset: u32, uBufferLength: u32, ucBufferIn: [1]u8, }; pub const DOT11_MANUFACTURING_TEST_QUERY_DATA = extern struct { uKey: u32, uOffset: u32, uBufferLength: u32, uBytesRead: u32, ucBufferOut: [1]u8, }; pub const DOT11_MANUFACTURING_TEST_SLEEP = extern struct { uSleepTime: u32, pvContext: ?*anyopaque, }; pub const DOT11_MANUFACTURING_CALLBACK_TYPE = enum(i32) { unknown = 0, self_test_complete = 1, sleep_complete = 2, IHV_start = -2147483648, IHV_end = -1, }; pub const dot11_manufacturing_callback_unknown = DOT11_MANUFACTURING_CALLBACK_TYPE.unknown; pub const dot11_manufacturing_callback_self_test_complete = DOT11_MANUFACTURING_CALLBACK_TYPE.self_test_complete; pub const dot11_manufacturing_callback_sleep_complete = DOT11_MANUFACTURING_CALLBACK_TYPE.sleep_complete; pub const dot11_manufacturing_callback_IHV_start = DOT11_MANUFACTURING_CALLBACK_TYPE.IHV_start; pub const dot11_manufacturing_callback_IHV_end = DOT11_MANUFACTURING_CALLBACK_TYPE.IHV_end; pub const DOT11_MANUFACTURING_CALLBACK_PARAMETERS = extern struct { Header: NDIS_OBJECT_HEADER, dot11ManufacturingCallbackType: DOT11_MANUFACTURING_CALLBACK_TYPE, uStatus: u32, pvContext: ?*anyopaque, }; pub const L2_NOTIFICATION_DATA = extern struct { NotificationSource: u32, NotificationCode: u32, InterfaceGuid: Guid, dwDataSize: u32, pData: ?*anyopaque, }; pub const WLAN_PROFILE_INFO = extern struct { strProfileName: [256]u16, dwFlags: u32, }; pub const DOT11_NETWORK = extern struct { dot11Ssid: DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, }; pub const WLAN_RAW_DATA = extern struct { dwDataSize: u32, DataBlob: [1]u8, }; pub const WLAN_RAW_DATA_LIST = extern struct { dwTotalSize: u32, dwNumberOfItems: u32, DataList: [1]extern struct { dwDataOffset: u32, dwDataSize: u32, }, }; pub const WLAN_CONNECTION_MODE = enum(i32) { profile = 0, temporary_profile = 1, discovery_secure = 2, discovery_unsecure = 3, auto = 4, invalid = 5, }; pub const wlan_connection_mode_profile = WLAN_CONNECTION_MODE.profile; pub const wlan_connection_mode_temporary_profile = WLAN_CONNECTION_MODE.temporary_profile; pub const wlan_connection_mode_discovery_secure = WLAN_CONNECTION_MODE.discovery_secure; pub const wlan_connection_mode_discovery_unsecure = WLAN_CONNECTION_MODE.discovery_unsecure; pub const wlan_connection_mode_auto = WLAN_CONNECTION_MODE.auto; pub const wlan_connection_mode_invalid = WLAN_CONNECTION_MODE.invalid; pub const WLAN_RATE_SET = extern struct { uRateSetLength: u32, usRateSet: [126]u16, }; pub const WLAN_AVAILABLE_NETWORK = extern struct { strProfileName: [256]u16, dot11Ssid: DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, uNumberOfBssids: u32, bNetworkConnectable: BOOL, wlanNotConnectableReason: u32, uNumberOfPhyTypes: u32, dot11PhyTypes: [8]DOT11_PHY_TYPE, bMorePhyTypes: BOOL, wlanSignalQuality: u32, bSecurityEnabled: BOOL, dot11DefaultAuthAlgorithm: DOT11_AUTH_ALGORITHM, dot11DefaultCipherAlgorithm: DOT11_CIPHER_ALGORITHM, dwFlags: u32, dwReserved: u32, }; pub const WLAN_AVAILABLE_NETWORK_V2 = extern struct { strProfileName: [256]u16, dot11Ssid: DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, uNumberOfBssids: u32, bNetworkConnectable: BOOL, wlanNotConnectableReason: u32, uNumberOfPhyTypes: u32, dot11PhyTypes: [8]DOT11_PHY_TYPE, bMorePhyTypes: BOOL, wlanSignalQuality: u32, bSecurityEnabled: BOOL, dot11DefaultAuthAlgorithm: DOT11_AUTH_ALGORITHM, dot11DefaultCipherAlgorithm: DOT11_CIPHER_ALGORITHM, dwFlags: u32, AccessNetworkOptions: DOT11_ACCESSNETWORKOPTIONS, dot11HESSID: [6]u8, VenueInfo: DOT11_VENUEINFO, dwReserved: u32, }; pub const WLAN_BSS_ENTRY = extern struct { dot11Ssid: DOT11_SSID, uPhyId: u32, dot11Bssid: [6]u8, dot11BssType: DOT11_BSS_TYPE, dot11BssPhyType: DOT11_PHY_TYPE, lRssi: i32, uLinkQuality: u32, bInRegDomain: BOOLEAN, usBeaconPeriod: u16, ullTimestamp: u64, ullHostTimestamp: u64, usCapabilityInformation: u16, ulChCenterFrequency: u32, wlanRateSet: WLAN_RATE_SET, ulIeOffset: u32, ulIeSize: u32, }; pub const WLAN_BSS_LIST = extern struct { dwTotalSize: u32, dwNumberOfItems: u32, wlanBssEntries: [1]WLAN_BSS_ENTRY, }; pub const WLAN_INTERFACE_STATE = enum(i32) { not_ready = 0, connected = 1, ad_hoc_network_formed = 2, disconnecting = 3, disconnected = 4, associating = 5, discovering = 6, authenticating = 7, }; pub const wlan_interface_state_not_ready = WLAN_INTERFACE_STATE.not_ready; pub const wlan_interface_state_connected = WLAN_INTERFACE_STATE.connected; pub const wlan_interface_state_ad_hoc_network_formed = WLAN_INTERFACE_STATE.ad_hoc_network_formed; pub const wlan_interface_state_disconnecting = WLAN_INTERFACE_STATE.disconnecting; pub const wlan_interface_state_disconnected = WLAN_INTERFACE_STATE.disconnected; pub const wlan_interface_state_associating = WLAN_INTERFACE_STATE.associating; pub const wlan_interface_state_discovering = WLAN_INTERFACE_STATE.discovering; pub const wlan_interface_state_authenticating = WLAN_INTERFACE_STATE.authenticating; pub const WLAN_ADHOC_NETWORK_STATE = enum(i32) { formed = 0, connected = 1, }; pub const wlan_adhoc_network_state_formed = WLAN_ADHOC_NETWORK_STATE.formed; pub const wlan_adhoc_network_state_connected = WLAN_ADHOC_NETWORK_STATE.connected; pub const WLAN_INTERFACE_INFO = extern struct { InterfaceGuid: Guid, strInterfaceDescription: [256]u16, isState: WLAN_INTERFACE_STATE, }; pub const WLAN_ASSOCIATION_ATTRIBUTES = extern struct { dot11Ssid: DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, dot11Bssid: [6]u8, dot11PhyType: DOT11_PHY_TYPE, uDot11PhyIndex: u32, wlanSignalQuality: u32, ulRxRate: u32, ulTxRate: u32, }; pub const WLAN_SECURITY_ATTRIBUTES = extern struct { bSecurityEnabled: BOOL, bOneXEnabled: BOOL, dot11AuthAlgorithm: DOT11_AUTH_ALGORITHM, dot11CipherAlgorithm: DOT11_CIPHER_ALGORITHM, }; pub const WLAN_CONNECTION_ATTRIBUTES = extern struct { isState: WLAN_INTERFACE_STATE, wlanConnectionMode: WLAN_CONNECTION_MODE, strProfileName: [256]u16, wlanAssociationAttributes: WLAN_ASSOCIATION_ATTRIBUTES, wlanSecurityAttributes: WLAN_SECURITY_ATTRIBUTES, }; pub const DOT11_RADIO_STATE = enum(i32) { unknown = 0, on = 1, off = 2, }; pub const dot11_radio_state_unknown = DOT11_RADIO_STATE.unknown; pub const dot11_radio_state_on = DOT11_RADIO_STATE.on; pub const dot11_radio_state_off = DOT11_RADIO_STATE.off; pub const WLAN_PHY_RADIO_STATE = extern struct { dwPhyIndex: u32, dot11SoftwareRadioState: DOT11_RADIO_STATE, dot11HardwareRadioState: DOT11_RADIO_STATE, }; pub const WLAN_RADIO_STATE = extern struct { dwNumberOfPhys: u32, PhyRadioState: [64]WLAN_PHY_RADIO_STATE, }; pub const WLAN_OPERATIONAL_STATE = enum(i32) { unknown = 0, off = 1, on = 2, going_off = 3, going_on = 4, }; pub const wlan_operational_state_unknown = WLAN_OPERATIONAL_STATE.unknown; pub const wlan_operational_state_off = WLAN_OPERATIONAL_STATE.off; pub const wlan_operational_state_on = WLAN_OPERATIONAL_STATE.on; pub const wlan_operational_state_going_off = WLAN_OPERATIONAL_STATE.going_off; pub const wlan_operational_state_going_on = WLAN_OPERATIONAL_STATE.going_on; pub const WLAN_INTERFACE_TYPE = enum(i32) { emulated_802_11 = 0, native_802_11 = 1, invalid = 2, }; pub const wlan_interface_type_emulated_802_11 = WLAN_INTERFACE_TYPE.emulated_802_11; pub const wlan_interface_type_native_802_11 = WLAN_INTERFACE_TYPE.native_802_11; pub const wlan_interface_type_invalid = WLAN_INTERFACE_TYPE.invalid; pub const WLAN_INTERFACE_CAPABILITY = extern struct { interfaceType: WLAN_INTERFACE_TYPE, bDot11DSupported: BOOL, dwMaxDesiredSsidListSize: u32, dwMaxDesiredBssidListSize: u32, dwNumberOfSupportedPhys: u32, dot11PhyTypes: [64]DOT11_PHY_TYPE, }; pub const WLAN_AUTH_CIPHER_PAIR_LIST = extern struct { dwNumberOfItems: u32, pAuthCipherPairList: [1]DOT11_AUTH_CIPHER_PAIR, }; pub const WLAN_COUNTRY_OR_REGION_STRING_LIST = extern struct { dwNumberOfItems: u32, pCountryOrRegionStringList: [3]u8, }; pub const WLAN_PROFILE_INFO_LIST = extern struct { dwNumberOfItems: u32, dwIndex: u32, ProfileInfo: [1]WLAN_PROFILE_INFO, }; pub const WLAN_AVAILABLE_NETWORK_LIST = extern struct { dwNumberOfItems: u32, dwIndex: u32, Network: [1]WLAN_AVAILABLE_NETWORK, }; pub const WLAN_AVAILABLE_NETWORK_LIST_V2 = extern struct { dwNumberOfItems: u32, dwIndex: u32, Network: [1]WLAN_AVAILABLE_NETWORK_V2, }; pub const WLAN_INTERFACE_INFO_LIST = extern struct { dwNumberOfItems: u32, dwIndex: u32, InterfaceInfo: [1]WLAN_INTERFACE_INFO, }; pub const DOT11_NETWORK_LIST = extern struct { dwNumberOfItems: u32, dwIndex: u32, Network: [1]DOT11_NETWORK, }; pub const WLAN_POWER_SETTING = enum(i32) { no_saving = 0, low_saving = 1, medium_saving = 2, maximum_saving = 3, invalid = 4, }; pub const wlan_power_setting_no_saving = WLAN_POWER_SETTING.no_saving; pub const wlan_power_setting_low_saving = WLAN_POWER_SETTING.low_saving; pub const wlan_power_setting_medium_saving = WLAN_POWER_SETTING.medium_saving; pub const wlan_power_setting_maximum_saving = WLAN_POWER_SETTING.maximum_saving; pub const wlan_power_setting_invalid = WLAN_POWER_SETTING.invalid; pub const WLAN_CONNECTION_PARAMETERS = extern struct { wlanConnectionMode: WLAN_CONNECTION_MODE, strProfile: ?[*:0]const u16, pDot11Ssid: ?*DOT11_SSID, pDesiredBssidList: ?*DOT11_BSSID_LIST, dot11BssType: DOT11_BSS_TYPE, dwFlags: u32, }; pub const WLAN_CONNECTION_PARAMETERS_V2 = extern struct { wlanConnectionMode: WLAN_CONNECTION_MODE, strProfile: ?[*:0]const u16, pDot11Ssid: ?*DOT11_SSID, pDot11Hessid: ?*u8, pDesiredBssidList: ?*DOT11_BSSID_LIST, dot11BssType: DOT11_BSS_TYPE, dwFlags: u32, pDot11AccessNetworkOptions: ?*DOT11_ACCESSNETWORKOPTIONS, }; pub const WLAN_MSM_NOTIFICATION_DATA = extern struct { wlanConnectionMode: WLAN_CONNECTION_MODE, strProfileName: [256]u16, dot11Ssid: DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, dot11MacAddr: [6]u8, bSecurityEnabled: BOOL, bFirstPeer: BOOL, bLastPeer: BOOL, wlanReasonCode: u32, }; pub const WLAN_CONNECTION_NOTIFICATION_DATA = extern struct { wlanConnectionMode: WLAN_CONNECTION_MODE, strProfileName: [256]u16, dot11Ssid: DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, bSecurityEnabled: BOOL, wlanReasonCode: u32, dwFlags: WLAN_CONNECTION_NOTIFICATION_FLAGS, strProfileXml: [1]u16, }; pub const WLAN_DEVICE_SERVICE_NOTIFICATION_DATA = extern struct { DeviceService: Guid, dwOpCode: u32, dwDataSize: u32, DataBlob: [1]u8, }; pub const WLAN_NOTIFICATION_ACM = enum(i32) { start = 0, autoconf_enabled = 1, autoconf_disabled = 2, background_scan_enabled = 3, background_scan_disabled = 4, bss_type_change = 5, power_setting_change = 6, scan_complete = 7, scan_fail = 8, connection_start = 9, connection_complete = 10, connection_attempt_fail = 11, filter_list_change = 12, interface_arrival = 13, interface_removal = 14, profile_change = 15, profile_name_change = 16, profiles_exhausted = 17, network_not_available = 18, network_available = 19, disconnecting = 20, disconnected = 21, adhoc_network_state_change = 22, profile_unblocked = 23, screen_power_change = 24, profile_blocked = 25, scan_list_refresh = 26, operational_state_change = 27, end = 28, }; pub const wlan_notification_acm_start = WLAN_NOTIFICATION_ACM.start; pub const wlan_notification_acm_autoconf_enabled = WLAN_NOTIFICATION_ACM.autoconf_enabled; pub const wlan_notification_acm_autoconf_disabled = WLAN_NOTIFICATION_ACM.autoconf_disabled; pub const wlan_notification_acm_background_scan_enabled = WLAN_NOTIFICATION_ACM.background_scan_enabled; pub const wlan_notification_acm_background_scan_disabled = WLAN_NOTIFICATION_ACM.background_scan_disabled; pub const wlan_notification_acm_bss_type_change = WLAN_NOTIFICATION_ACM.bss_type_change; pub const wlan_notification_acm_power_setting_change = WLAN_NOTIFICATION_ACM.power_setting_change; pub const wlan_notification_acm_scan_complete = WLAN_NOTIFICATION_ACM.scan_complete; pub const wlan_notification_acm_scan_fail = WLAN_NOTIFICATION_ACM.scan_fail; pub const wlan_notification_acm_connection_start = WLAN_NOTIFICATION_ACM.connection_start; pub const wlan_notification_acm_connection_complete = WLAN_NOTIFICATION_ACM.connection_complete; pub const wlan_notification_acm_connection_attempt_fail = WLAN_NOTIFICATION_ACM.connection_attempt_fail; pub const wlan_notification_acm_filter_list_change = WLAN_NOTIFICATION_ACM.filter_list_change; pub const wlan_notification_acm_interface_arrival = WLAN_NOTIFICATION_ACM.interface_arrival; pub const wlan_notification_acm_interface_removal = WLAN_NOTIFICATION_ACM.interface_removal; pub const wlan_notification_acm_profile_change = WLAN_NOTIFICATION_ACM.profile_change; pub const wlan_notification_acm_profile_name_change = WLAN_NOTIFICATION_ACM.profile_name_change; pub const wlan_notification_acm_profiles_exhausted = WLAN_NOTIFICATION_ACM.profiles_exhausted; pub const wlan_notification_acm_network_not_available = WLAN_NOTIFICATION_ACM.network_not_available; pub const wlan_notification_acm_network_available = WLAN_NOTIFICATION_ACM.network_available; pub const wlan_notification_acm_disconnecting = WLAN_NOTIFICATION_ACM.disconnecting; pub const wlan_notification_acm_disconnected = WLAN_NOTIFICATION_ACM.disconnected; pub const wlan_notification_acm_adhoc_network_state_change = WLAN_NOTIFICATION_ACM.adhoc_network_state_change; pub const wlan_notification_acm_profile_unblocked = WLAN_NOTIFICATION_ACM.profile_unblocked; pub const wlan_notification_acm_screen_power_change = WLAN_NOTIFICATION_ACM.screen_power_change; pub const wlan_notification_acm_profile_blocked = WLAN_NOTIFICATION_ACM.profile_blocked; pub const wlan_notification_acm_scan_list_refresh = WLAN_NOTIFICATION_ACM.scan_list_refresh; pub const wlan_notification_acm_operational_state_change = WLAN_NOTIFICATION_ACM.operational_state_change; pub const wlan_notification_acm_end = WLAN_NOTIFICATION_ACM.end; pub const WLAN_NOTIFICATION_MSM = enum(i32) { start = 0, associating = 1, associated = 2, authenticating = 3, connected = 4, roaming_start = 5, roaming_end = 6, radio_state_change = 7, signal_quality_change = 8, disassociating = 9, disconnected = 10, peer_join = 11, peer_leave = 12, adapter_removal = 13, adapter_operation_mode_change = 14, link_degraded = 15, link_improved = 16, end = 17, }; pub const wlan_notification_msm_start = WLAN_NOTIFICATION_MSM.start; pub const wlan_notification_msm_associating = WLAN_NOTIFICATION_MSM.associating; pub const wlan_notification_msm_associated = WLAN_NOTIFICATION_MSM.associated; pub const wlan_notification_msm_authenticating = WLAN_NOTIFICATION_MSM.authenticating; pub const wlan_notification_msm_connected = WLAN_NOTIFICATION_MSM.connected; pub const wlan_notification_msm_roaming_start = WLAN_NOTIFICATION_MSM.roaming_start; pub const wlan_notification_msm_roaming_end = WLAN_NOTIFICATION_MSM.roaming_end; pub const wlan_notification_msm_radio_state_change = WLAN_NOTIFICATION_MSM.radio_state_change; pub const wlan_notification_msm_signal_quality_change = WLAN_NOTIFICATION_MSM.signal_quality_change; pub const wlan_notification_msm_disassociating = WLAN_NOTIFICATION_MSM.disassociating; pub const wlan_notification_msm_disconnected = WLAN_NOTIFICATION_MSM.disconnected; pub const wlan_notification_msm_peer_join = WLAN_NOTIFICATION_MSM.peer_join; pub const wlan_notification_msm_peer_leave = WLAN_NOTIFICATION_MSM.peer_leave; pub const wlan_notification_msm_adapter_removal = WLAN_NOTIFICATION_MSM.adapter_removal; pub const wlan_notification_msm_adapter_operation_mode_change = WLAN_NOTIFICATION_MSM.adapter_operation_mode_change; pub const wlan_notification_msm_link_degraded = WLAN_NOTIFICATION_MSM.link_degraded; pub const wlan_notification_msm_link_improved = WLAN_NOTIFICATION_MSM.link_improved; pub const wlan_notification_msm_end = WLAN_NOTIFICATION_MSM.end; pub const WLAN_NOTIFICATION_SECURITY = enum(i32) { start = 0, end = 1, }; pub const wlan_notification_security_start = WLAN_NOTIFICATION_SECURITY.start; pub const wlan_notification_security_end = WLAN_NOTIFICATION_SECURITY.end; pub const WLAN_NOTIFICATION_CALLBACK = fn( param0: ?*L2_NOTIFICATION_DATA, param1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub const WLAN_OPCODE_VALUE_TYPE = enum(i32) { query_only = 0, set_by_group_policy = 1, set_by_user = 2, invalid = 3, }; pub const wlan_opcode_value_type_query_only = WLAN_OPCODE_VALUE_TYPE.query_only; pub const wlan_opcode_value_type_set_by_group_policy = WLAN_OPCODE_VALUE_TYPE.set_by_group_policy; pub const wlan_opcode_value_type_set_by_user = WLAN_OPCODE_VALUE_TYPE.set_by_user; pub const wlan_opcode_value_type_invalid = WLAN_OPCODE_VALUE_TYPE.invalid; pub const WLAN_INTF_OPCODE = enum(i32) { autoconf_start = 0, autoconf_enabled = 1, background_scan_enabled = 2, media_streaming_mode = 3, radio_state = 4, bss_type = 5, interface_state = 6, current_connection = 7, channel_number = 8, supported_infrastructure_auth_cipher_pairs = 9, supported_adhoc_auth_cipher_pairs = 10, supported_country_or_region_string_list = 11, current_operation_mode = 12, supported_safe_mode = 13, certified_safe_mode = 14, hosted_network_capable = 15, management_frame_protection_capable = 16, secondary_sta_interfaces = 17, secondary_sta_synchronized_connections = 18, autoconf_end = 268435455, msm_start = 268435712, statistics = 268435713, rssi = 268435714, msm_end = 536870911, security_start = 536936448, security_end = 805306367, ihv_start = 805306368, ihv_end = 1073741823, }; pub const wlan_intf_opcode_autoconf_start = WLAN_INTF_OPCODE.autoconf_start; pub const wlan_intf_opcode_autoconf_enabled = WLAN_INTF_OPCODE.autoconf_enabled; pub const wlan_intf_opcode_background_scan_enabled = WLAN_INTF_OPCODE.background_scan_enabled; pub const wlan_intf_opcode_media_streaming_mode = WLAN_INTF_OPCODE.media_streaming_mode; pub const wlan_intf_opcode_radio_state = WLAN_INTF_OPCODE.radio_state; pub const wlan_intf_opcode_bss_type = WLAN_INTF_OPCODE.bss_type; pub const wlan_intf_opcode_interface_state = WLAN_INTF_OPCODE.interface_state; pub const wlan_intf_opcode_current_connection = WLAN_INTF_OPCODE.current_connection; pub const wlan_intf_opcode_channel_number = WLAN_INTF_OPCODE.channel_number; pub const wlan_intf_opcode_supported_infrastructure_auth_cipher_pairs = WLAN_INTF_OPCODE.supported_infrastructure_auth_cipher_pairs; pub const wlan_intf_opcode_supported_adhoc_auth_cipher_pairs = WLAN_INTF_OPCODE.supported_adhoc_auth_cipher_pairs; pub const wlan_intf_opcode_supported_country_or_region_string_list = WLAN_INTF_OPCODE.supported_country_or_region_string_list; pub const wlan_intf_opcode_current_operation_mode = WLAN_INTF_OPCODE.current_operation_mode; pub const wlan_intf_opcode_supported_safe_mode = WLAN_INTF_OPCODE.supported_safe_mode; pub const wlan_intf_opcode_certified_safe_mode = WLAN_INTF_OPCODE.certified_safe_mode; pub const wlan_intf_opcode_hosted_network_capable = WLAN_INTF_OPCODE.hosted_network_capable; pub const wlan_intf_opcode_management_frame_protection_capable = WLAN_INTF_OPCODE.management_frame_protection_capable; pub const wlan_intf_opcode_secondary_sta_interfaces = WLAN_INTF_OPCODE.secondary_sta_interfaces; pub const wlan_intf_opcode_secondary_sta_synchronized_connections = WLAN_INTF_OPCODE.secondary_sta_synchronized_connections; pub const wlan_intf_opcode_autoconf_end = WLAN_INTF_OPCODE.autoconf_end; pub const wlan_intf_opcode_msm_start = WLAN_INTF_OPCODE.msm_start; pub const wlan_intf_opcode_statistics = WLAN_INTF_OPCODE.statistics; pub const wlan_intf_opcode_rssi = WLAN_INTF_OPCODE.rssi; pub const wlan_intf_opcode_msm_end = WLAN_INTF_OPCODE.msm_end; pub const wlan_intf_opcode_security_start = WLAN_INTF_OPCODE.security_start; pub const wlan_intf_opcode_security_end = WLAN_INTF_OPCODE.security_end; pub const wlan_intf_opcode_ihv_start = WLAN_INTF_OPCODE.ihv_start; pub const wlan_intf_opcode_ihv_end = WLAN_INTF_OPCODE.ihv_end; pub const WLAN_AUTOCONF_OPCODE = enum(i32) { start = 0, show_denied_networks = 1, power_setting = 2, only_use_gp_profiles_for_allowed_networks = 3, allow_explicit_creds = 4, block_period = 5, allow_virtual_station_extensibility = 6, end = 7, }; pub const wlan_autoconf_opcode_start = WLAN_AUTOCONF_OPCODE.start; pub const wlan_autoconf_opcode_show_denied_networks = WLAN_AUTOCONF_OPCODE.show_denied_networks; pub const wlan_autoconf_opcode_power_setting = WLAN_AUTOCONF_OPCODE.power_setting; pub const wlan_autoconf_opcode_only_use_gp_profiles_for_allowed_networks = WLAN_AUTOCONF_OPCODE.only_use_gp_profiles_for_allowed_networks; pub const wlan_autoconf_opcode_allow_explicit_creds = WLAN_AUTOCONF_OPCODE.allow_explicit_creds; pub const wlan_autoconf_opcode_block_period = WLAN_AUTOCONF_OPCODE.block_period; pub const wlan_autoconf_opcode_allow_virtual_station_extensibility = WLAN_AUTOCONF_OPCODE.allow_virtual_station_extensibility; pub const wlan_autoconf_opcode_end = WLAN_AUTOCONF_OPCODE.end; pub const WLAN_IHV_CONTROL_TYPE = enum(i32) { service = 0, driver = 1, }; pub const wlan_ihv_control_type_service = WLAN_IHV_CONTROL_TYPE.service; pub const wlan_ihv_control_type_driver = WLAN_IHV_CONTROL_TYPE.driver; pub const WLAN_FILTER_LIST_TYPE = enum(i32) { gp_permit = 0, gp_deny = 1, user_permit = 2, user_deny = 3, }; pub const wlan_filter_list_type_gp_permit = WLAN_FILTER_LIST_TYPE.gp_permit; pub const wlan_filter_list_type_gp_deny = WLAN_FILTER_LIST_TYPE.gp_deny; pub const wlan_filter_list_type_user_permit = WLAN_FILTER_LIST_TYPE.user_permit; pub const wlan_filter_list_type_user_deny = WLAN_FILTER_LIST_TYPE.user_deny; pub const WLAN_PHY_FRAME_STATISTICS = extern struct { ullTransmittedFrameCount: u64, ullMulticastTransmittedFrameCount: u64, ullFailedCount: u64, ullRetryCount: u64, ullMultipleRetryCount: u64, ullMaxTXLifetimeExceededCount: u64, ullTransmittedFragmentCount: u64, ullRTSSuccessCount: u64, ullRTSFailureCount: u64, ullACKFailureCount: u64, ullReceivedFrameCount: u64, ullMulticastReceivedFrameCount: u64, ullPromiscuousReceivedFrameCount: u64, ullMaxRXLifetimeExceededCount: u64, ullFrameDuplicateCount: u64, ullReceivedFragmentCount: u64, ullPromiscuousReceivedFragmentCount: u64, ullFCSErrorCount: u64, }; pub const WLAN_MAC_FRAME_STATISTICS = extern struct { ullTransmittedFrameCount: u64, ullReceivedFrameCount: u64, ullWEPExcludedCount: u64, ullTKIPLocalMICFailures: u64, ullTKIPReplays: u64, ullTKIPICVErrorCount: u64, ullCCMPReplays: u64, ullCCMPDecryptErrors: u64, ullWEPUndecryptableCount: u64, ullWEPICVErrorCount: u64, ullDecryptSuccessCount: u64, ullDecryptFailureCount: u64, }; pub const WLAN_STATISTICS = extern struct { ullFourWayHandshakeFailures: u64, ullTKIPCounterMeasuresInvoked: u64, ullReserved: u64, MacUcastCounters: WLAN_MAC_FRAME_STATISTICS, MacMcastCounters: WLAN_MAC_FRAME_STATISTICS, dwNumberOfPhys: u32, PhyCounters: [1]WLAN_PHY_FRAME_STATISTICS, }; pub const WLAN_SECURABLE_OBJECT = enum(i32) { wlan_secure_permit_list = 0, wlan_secure_deny_list = 1, wlan_secure_ac_enabled = 2, wlan_secure_bc_scan_enabled = 3, wlan_secure_bss_type = 4, wlan_secure_show_denied = 5, wlan_secure_interface_properties = 6, wlan_secure_ihv_control = 7, wlan_secure_all_user_profiles_order = 8, wlan_secure_add_new_all_user_profiles = 9, wlan_secure_add_new_per_user_profiles = 10, wlan_secure_media_streaming_mode_enabled = 11, wlan_secure_current_operation_mode = 12, wlan_secure_get_plaintext_key = 13, wlan_secure_hosted_network_elevated_access = 14, wlan_secure_virtual_station_extensibility = 15, wlan_secure_wfd_elevated_access = 16, WLAN_SECURABLE_OBJECT_COUNT = 17, }; pub const wlan_secure_permit_list = WLAN_SECURABLE_OBJECT.wlan_secure_permit_list; pub const wlan_secure_deny_list = WLAN_SECURABLE_OBJECT.wlan_secure_deny_list; pub const wlan_secure_ac_enabled = WLAN_SECURABLE_OBJECT.wlan_secure_ac_enabled; pub const wlan_secure_bc_scan_enabled = WLAN_SECURABLE_OBJECT.wlan_secure_bc_scan_enabled; pub const wlan_secure_bss_type = WLAN_SECURABLE_OBJECT.wlan_secure_bss_type; pub const wlan_secure_show_denied = WLAN_SECURABLE_OBJECT.wlan_secure_show_denied; pub const wlan_secure_interface_properties = WLAN_SECURABLE_OBJECT.wlan_secure_interface_properties; pub const wlan_secure_ihv_control = WLAN_SECURABLE_OBJECT.wlan_secure_ihv_control; pub const wlan_secure_all_user_profiles_order = WLAN_SECURABLE_OBJECT.wlan_secure_all_user_profiles_order; pub const wlan_secure_add_new_all_user_profiles = WLAN_SECURABLE_OBJECT.wlan_secure_add_new_all_user_profiles; pub const wlan_secure_add_new_per_user_profiles = WLAN_SECURABLE_OBJECT.wlan_secure_add_new_per_user_profiles; pub const wlan_secure_media_streaming_mode_enabled = WLAN_SECURABLE_OBJECT.wlan_secure_media_streaming_mode_enabled; pub const wlan_secure_current_operation_mode = WLAN_SECURABLE_OBJECT.wlan_secure_current_operation_mode; pub const wlan_secure_get_plaintext_key = WLAN_SECURABLE_OBJECT.wlan_secure_get_plaintext_key; pub const wlan_secure_hosted_network_elevated_access = WLAN_SECURABLE_OBJECT.wlan_secure_hosted_network_elevated_access; pub const wlan_secure_virtual_station_extensibility = WLAN_SECURABLE_OBJECT.wlan_secure_virtual_station_extensibility; pub const wlan_secure_wfd_elevated_access = WLAN_SECURABLE_OBJECT.wlan_secure_wfd_elevated_access; pub const WLAN_SECURABLE_OBJECT_COUNT = WLAN_SECURABLE_OBJECT.WLAN_SECURABLE_OBJECT_COUNT; pub const WLAN_DEVICE_SERVICE_GUID_LIST = extern struct { dwNumberOfItems: u32, dwIndex: u32, DeviceService: [1]Guid, }; pub const WFD_ROLE_TYPE = enum(i32) { NONE = 0, DEVICE = 1, GROUP_OWNER = 2, CLIENT = 4, MAX = 5, }; pub const WFD_ROLE_TYPE_NONE = WFD_ROLE_TYPE.NONE; pub const WFD_ROLE_TYPE_DEVICE = WFD_ROLE_TYPE.DEVICE; pub const WFD_ROLE_TYPE_GROUP_OWNER = WFD_ROLE_TYPE.GROUP_OWNER; pub const WFD_ROLE_TYPE_CLIENT = WFD_ROLE_TYPE.CLIENT; pub const WFD_ROLE_TYPE_MAX = WFD_ROLE_TYPE.MAX; pub const WFD_GROUP_ID = extern struct { DeviceAddress: [6]u8, GroupSSID: DOT11_SSID, }; pub const WL_DISPLAY_PAGES = enum(i32) { ConnectionPage = 0, SecurityPage = 1, AdvPage = 2, }; pub const WLConnectionPage = WL_DISPLAY_PAGES.ConnectionPage; pub const WLSecurityPage = WL_DISPLAY_PAGES.SecurityPage; pub const WLAdvPage = WL_DISPLAY_PAGES.AdvPage; pub const WLAN_HOSTED_NETWORK_STATE = enum(i32) { unavailable = 0, idle = 1, active = 2, }; pub const wlan_hosted_network_unavailable = WLAN_HOSTED_NETWORK_STATE.unavailable; pub const wlan_hosted_network_idle = WLAN_HOSTED_NETWORK_STATE.idle; pub const wlan_hosted_network_active = WLAN_HOSTED_NETWORK_STATE.active; pub const WLAN_HOSTED_NETWORK_REASON = enum(i32) { success = 0, unspecified = 1, bad_parameters = 2, service_shutting_down = 3, insufficient_resources = 4, elevation_required = 5, read_only = 6, persistence_failed = 7, crypt_error = 8, impersonation = 9, stop_before_start = 10, interface_available = 11, interface_unavailable = 12, miniport_stopped = 13, miniport_started = 14, incompatible_connection_started = 15, incompatible_connection_stopped = 16, user_action = 17, client_abort = 18, ap_start_failed = 19, peer_arrived = 20, peer_departed = 21, peer_timeout = 22, gp_denied = 23, service_unavailable = 24, device_change = 25, properties_change = 26, virtual_station_blocking_use = 27, service_available_on_virtual_station = 28, }; pub const wlan_hosted_network_reason_success = WLAN_HOSTED_NETWORK_REASON.success; pub const wlan_hosted_network_reason_unspecified = WLAN_HOSTED_NETWORK_REASON.unspecified; pub const wlan_hosted_network_reason_bad_parameters = WLAN_HOSTED_NETWORK_REASON.bad_parameters; pub const wlan_hosted_network_reason_service_shutting_down = WLAN_HOSTED_NETWORK_REASON.service_shutting_down; pub const wlan_hosted_network_reason_insufficient_resources = WLAN_HOSTED_NETWORK_REASON.insufficient_resources; pub const wlan_hosted_network_reason_elevation_required = WLAN_HOSTED_NETWORK_REASON.elevation_required; pub const wlan_hosted_network_reason_read_only = WLAN_HOSTED_NETWORK_REASON.read_only; pub const wlan_hosted_network_reason_persistence_failed = WLAN_HOSTED_NETWORK_REASON.persistence_failed; pub const wlan_hosted_network_reason_crypt_error = WLAN_HOSTED_NETWORK_REASON.crypt_error; pub const wlan_hosted_network_reason_impersonation = WLAN_HOSTED_NETWORK_REASON.impersonation; pub const wlan_hosted_network_reason_stop_before_start = WLAN_HOSTED_NETWORK_REASON.stop_before_start; pub const wlan_hosted_network_reason_interface_available = WLAN_HOSTED_NETWORK_REASON.interface_available; pub const wlan_hosted_network_reason_interface_unavailable = WLAN_HOSTED_NETWORK_REASON.interface_unavailable; pub const wlan_hosted_network_reason_miniport_stopped = WLAN_HOSTED_NETWORK_REASON.miniport_stopped; pub const wlan_hosted_network_reason_miniport_started = WLAN_HOSTED_NETWORK_REASON.miniport_started; pub const wlan_hosted_network_reason_incompatible_connection_started = WLAN_HOSTED_NETWORK_REASON.incompatible_connection_started; pub const wlan_hosted_network_reason_incompatible_connection_stopped = WLAN_HOSTED_NETWORK_REASON.incompatible_connection_stopped; pub const wlan_hosted_network_reason_user_action = WLAN_HOSTED_NETWORK_REASON.user_action; pub const wlan_hosted_network_reason_client_abort = WLAN_HOSTED_NETWORK_REASON.client_abort; pub const wlan_hosted_network_reason_ap_start_failed = WLAN_HOSTED_NETWORK_REASON.ap_start_failed; pub const wlan_hosted_network_reason_peer_arrived = WLAN_HOSTED_NETWORK_REASON.peer_arrived; pub const wlan_hosted_network_reason_peer_departed = WLAN_HOSTED_NETWORK_REASON.peer_departed; pub const wlan_hosted_network_reason_peer_timeout = WLAN_HOSTED_NETWORK_REASON.peer_timeout; pub const wlan_hosted_network_reason_gp_denied = WLAN_HOSTED_NETWORK_REASON.gp_denied; pub const wlan_hosted_network_reason_service_unavailable = WLAN_HOSTED_NETWORK_REASON.service_unavailable; pub const wlan_hosted_network_reason_device_change = WLAN_HOSTED_NETWORK_REASON.device_change; pub const wlan_hosted_network_reason_properties_change = WLAN_HOSTED_NETWORK_REASON.properties_change; pub const wlan_hosted_network_reason_virtual_station_blocking_use = WLAN_HOSTED_NETWORK_REASON.virtual_station_blocking_use; pub const wlan_hosted_network_reason_service_available_on_virtual_station = WLAN_HOSTED_NETWORK_REASON.service_available_on_virtual_station; pub const WLAN_HOSTED_NETWORK_PEER_AUTH_STATE = enum(i32) { invalid = 0, authenticated = 1, }; pub const wlan_hosted_network_peer_state_invalid = WLAN_HOSTED_NETWORK_PEER_AUTH_STATE.invalid; pub const wlan_hosted_network_peer_state_authenticated = WLAN_HOSTED_NETWORK_PEER_AUTH_STATE.authenticated; pub const WLAN_HOSTED_NETWORK_PEER_STATE = extern struct { PeerMacAddress: [6]u8, PeerAuthState: WLAN_HOSTED_NETWORK_PEER_AUTH_STATE, }; pub const WLAN_HOSTED_NETWORK_RADIO_STATE = extern struct { dot11SoftwareRadioState: DOT11_RADIO_STATE, dot11HardwareRadioState: DOT11_RADIO_STATE, }; pub const WLAN_HOSTED_NETWORK_NOTIFICATION_CODE = enum(i32) { state_change = 4096, peer_state_change = 4097, radio_state_change = 4098, }; pub const wlan_hosted_network_state_change = WLAN_HOSTED_NETWORK_NOTIFICATION_CODE.state_change; pub const wlan_hosted_network_peer_state_change = WLAN_HOSTED_NETWORK_NOTIFICATION_CODE.peer_state_change; pub const wlan_hosted_network_radio_state_change = WLAN_HOSTED_NETWORK_NOTIFICATION_CODE.radio_state_change; pub const WLAN_HOSTED_NETWORK_STATE_CHANGE = extern struct { OldState: WLAN_HOSTED_NETWORK_STATE, NewState: WLAN_HOSTED_NETWORK_STATE, StateChangeReason: WLAN_HOSTED_NETWORK_REASON, }; pub const WLAN_HOSTED_NETWORK_DATA_PEER_STATE_CHANGE = extern struct { OldState: WLAN_HOSTED_NETWORK_PEER_STATE, NewState: WLAN_HOSTED_NETWORK_PEER_STATE, PeerStateChangeReason: WLAN_HOSTED_NETWORK_REASON, }; pub const WLAN_HOSTED_NETWORK_OPCODE = enum(i32) { connection_settings = 0, security_settings = 1, station_profile = 2, enable = 3, }; pub const wlan_hosted_network_opcode_connection_settings = WLAN_HOSTED_NETWORK_OPCODE.connection_settings; pub const wlan_hosted_network_opcode_security_settings = WLAN_HOSTED_NETWORK_OPCODE.security_settings; pub const wlan_hosted_network_opcode_station_profile = WLAN_HOSTED_NETWORK_OPCODE.station_profile; pub const wlan_hosted_network_opcode_enable = WLAN_HOSTED_NETWORK_OPCODE.enable; pub const WLAN_HOSTED_NETWORK_CONNECTION_SETTINGS = extern struct { hostedNetworkSSID: DOT11_SSID, dwMaxNumberOfPeers: u32, }; pub const WLAN_HOSTED_NETWORK_SECURITY_SETTINGS = extern struct { dot11AuthAlgo: DOT11_AUTH_ALGORITHM, dot11CipherAlgo: DOT11_CIPHER_ALGORITHM, }; pub const WLAN_HOSTED_NETWORK_STATUS = extern struct { HostedNetworkState: WLAN_HOSTED_NETWORK_STATE, IPDeviceID: Guid, wlanHostedNetworkBSSID: [6]u8, dot11PhyType: DOT11_PHY_TYPE, ulChannelFrequency: u32, dwNumberOfPeers: u32, PeerList: [1]WLAN_HOSTED_NETWORK_PEER_STATE, }; pub const WFD_OPEN_SESSION_COMPLETE_CALLBACK = fn( hSessionHandle: ?HANDLE, pvContext: ?*anyopaque, guidSessionInterface: Guid, dwError: u32, dwReasonCode: u32, ) callconv(@import("std").os.windows.WINAPI) void; pub const ONEX_AUTH_IDENTITY = enum(i32) { None = 0, Machine = 1, User = 2, ExplicitUser = 3, Guest = 4, Invalid = 5, }; pub const OneXAuthIdentityNone = ONEX_AUTH_IDENTITY.None; pub const OneXAuthIdentityMachine = ONEX_AUTH_IDENTITY.Machine; pub const OneXAuthIdentityUser = ONEX_AUTH_IDENTITY.User; pub const OneXAuthIdentityExplicitUser = ONEX_AUTH_IDENTITY.ExplicitUser; pub const OneXAuthIdentityGuest = ONEX_AUTH_IDENTITY.Guest; pub const OneXAuthIdentityInvalid = ONEX_AUTH_IDENTITY.Invalid; pub const ONEX_AUTH_STATUS = enum(i32) { NotStarted = 0, InProgress = 1, NoAuthenticatorFound = 2, Success = 3, Failure = 4, Invalid = 5, }; pub const OneXAuthNotStarted = ONEX_AUTH_STATUS.NotStarted; pub const OneXAuthInProgress = ONEX_AUTH_STATUS.InProgress; pub const OneXAuthNoAuthenticatorFound = ONEX_AUTH_STATUS.NoAuthenticatorFound; pub const OneXAuthSuccess = ONEX_AUTH_STATUS.Success; pub const OneXAuthFailure = ONEX_AUTH_STATUS.Failure; pub const OneXAuthInvalid = ONEX_AUTH_STATUS.Invalid; pub const ONEX_REASON_CODE = enum(i32) { REASON_CODE_SUCCESS = 0, REASON_START = 327680, UNABLE_TO_IDENTIFY_USER = 327681, IDENTITY_NOT_FOUND = 327682, UI_DISABLED = 327683, UI_FAILURE = 327684, EAP_FAILURE_RECEIVED = 327685, AUTHENTICATOR_NO_LONGER_PRESENT = 327686, NO_RESPONSE_TO_IDENTITY = 327687, PROFILE_VERSION_NOT_SUPPORTED = 327688, PROFILE_INVALID_LENGTH = 327689, PROFILE_DISALLOWED_EAP_TYPE = 327690, PROFILE_INVALID_EAP_TYPE_OR_FLAG = 327691, PROFILE_INVALID_ONEX_FLAGS = 327692, PROFILE_INVALID_TIMER_VALUE = 327693, PROFILE_INVALID_SUPPLICANT_MODE = 327694, PROFILE_INVALID_AUTH_MODE = 327695, PROFILE_INVALID_EAP_CONNECTION_PROPERTIES = 327696, UI_CANCELLED = 327697, PROFILE_INVALID_EXPLICIT_CREDENTIALS = 327698, PROFILE_EXPIRED_EXPLICIT_CREDENTIALS = 327699, UI_NOT_PERMITTED = 327700, }; pub const ONEX_REASON_CODE_SUCCESS = ONEX_REASON_CODE.REASON_CODE_SUCCESS; pub const ONEX_REASON_START = ONEX_REASON_CODE.REASON_START; pub const ONEX_UNABLE_TO_IDENTIFY_USER = ONEX_REASON_CODE.UNABLE_TO_IDENTIFY_USER; pub const ONEX_IDENTITY_NOT_FOUND = ONEX_REASON_CODE.IDENTITY_NOT_FOUND; pub const ONEX_UI_DISABLED = ONEX_REASON_CODE.UI_DISABLED; pub const ONEX_UI_FAILURE = ONEX_REASON_CODE.UI_FAILURE; pub const ONEX_EAP_FAILURE_RECEIVED = ONEX_REASON_CODE.EAP_FAILURE_RECEIVED; pub const ONEX_AUTHENTICATOR_NO_LONGER_PRESENT = ONEX_REASON_CODE.AUTHENTICATOR_NO_LONGER_PRESENT; pub const ONEX_NO_RESPONSE_TO_IDENTITY = ONEX_REASON_CODE.NO_RESPONSE_TO_IDENTITY; pub const ONEX_PROFILE_VERSION_NOT_SUPPORTED = ONEX_REASON_CODE.PROFILE_VERSION_NOT_SUPPORTED; pub const ONEX_PROFILE_INVALID_LENGTH = ONEX_REASON_CODE.PROFILE_INVALID_LENGTH; pub const ONEX_PROFILE_DISALLOWED_EAP_TYPE = ONEX_REASON_CODE.PROFILE_DISALLOWED_EAP_TYPE; pub const ONEX_PROFILE_INVALID_EAP_TYPE_OR_FLAG = ONEX_REASON_CODE.PROFILE_INVALID_EAP_TYPE_OR_FLAG; pub const ONEX_PROFILE_INVALID_ONEX_FLAGS = ONEX_REASON_CODE.PROFILE_INVALID_ONEX_FLAGS; pub const ONEX_PROFILE_INVALID_TIMER_VALUE = ONEX_REASON_CODE.PROFILE_INVALID_TIMER_VALUE; pub const ONEX_PROFILE_INVALID_SUPPLICANT_MODE = ONEX_REASON_CODE.PROFILE_INVALID_SUPPLICANT_MODE; pub const ONEX_PROFILE_INVALID_AUTH_MODE = ONEX_REASON_CODE.PROFILE_INVALID_AUTH_MODE; pub const ONEX_PROFILE_INVALID_EAP_CONNECTION_PROPERTIES = ONEX_REASON_CODE.PROFILE_INVALID_EAP_CONNECTION_PROPERTIES; pub const ONEX_UI_CANCELLED = ONEX_REASON_CODE.UI_CANCELLED; pub const ONEX_PROFILE_INVALID_EXPLICIT_CREDENTIALS = ONEX_REASON_CODE.PROFILE_INVALID_EXPLICIT_CREDENTIALS; pub const ONEX_PROFILE_EXPIRED_EXPLICIT_CREDENTIALS = ONEX_REASON_CODE.PROFILE_EXPIRED_EXPLICIT_CREDENTIALS; pub const ONEX_UI_NOT_PERMITTED = ONEX_REASON_CODE.UI_NOT_PERMITTED; pub const ONEX_NOTIFICATION_TYPE = enum(i32) { PublicNotificationBase = 0, NotificationTypeResultUpdate = 1, NotificationTypeAuthRestarted = 2, NotificationTypeEventInvalid = 3, // NumNotifications = 3, this enum value conflicts with NotificationTypeEventInvalid }; pub const OneXPublicNotificationBase = ONEX_NOTIFICATION_TYPE.PublicNotificationBase; pub const OneXNotificationTypeResultUpdate = ONEX_NOTIFICATION_TYPE.NotificationTypeResultUpdate; pub const OneXNotificationTypeAuthRestarted = ONEX_NOTIFICATION_TYPE.NotificationTypeAuthRestarted; pub const OneXNotificationTypeEventInvalid = ONEX_NOTIFICATION_TYPE.NotificationTypeEventInvalid; pub const OneXNumNotifications = ONEX_NOTIFICATION_TYPE.NotificationTypeEventInvalid; pub const ONEX_AUTH_RESTART_REASON = enum(i32) { PeerInitiated = 0, MsmInitiated = 1, OneXHeldStateTimeout = 2, OneXAuthTimeout = 3, OneXConfigurationChanged = 4, OneXUserChanged = 5, QuarantineStateChanged = 6, AltCredsTrial = 7, Invalid = 8, }; pub const OneXRestartReasonPeerInitiated = ONEX_AUTH_RESTART_REASON.PeerInitiated; pub const OneXRestartReasonMsmInitiated = ONEX_AUTH_RESTART_REASON.MsmInitiated; pub const OneXRestartReasonOneXHeldStateTimeout = ONEX_AUTH_RESTART_REASON.OneXHeldStateTimeout; pub const OneXRestartReasonOneXAuthTimeout = ONEX_AUTH_RESTART_REASON.OneXAuthTimeout; pub const OneXRestartReasonOneXConfigurationChanged = ONEX_AUTH_RESTART_REASON.OneXConfigurationChanged; pub const OneXRestartReasonOneXUserChanged = ONEX_AUTH_RESTART_REASON.OneXUserChanged; pub const OneXRestartReasonQuarantineStateChanged = ONEX_AUTH_RESTART_REASON.QuarantineStateChanged; pub const OneXRestartReasonAltCredsTrial = ONEX_AUTH_RESTART_REASON.AltCredsTrial; pub const OneXRestartReasonInvalid = ONEX_AUTH_RESTART_REASON.Invalid; pub const ONEX_VARIABLE_BLOB = extern struct { dwSize: u32, dwOffset: u32, }; pub const ONEX_AUTH_PARAMS = extern struct { fUpdatePending: BOOL, oneXConnProfile: ONEX_VARIABLE_BLOB, authIdentity: ONEX_AUTH_IDENTITY, dwQuarantineState: u32, _bitfield: u32, dwSessionId: u32, hUserToken: ?HANDLE, OneXUserProfile: ONEX_VARIABLE_BLOB, Identity: ONEX_VARIABLE_BLOB, UserName: ONEX_VARIABLE_BLOB, Domain: ONEX_VARIABLE_BLOB, }; pub const ONEX_EAP_ERROR = extern struct { dwWinError: u32, type: EAP_METHOD_TYPE, dwReasonCode: u32, rootCauseGuid: Guid, repairGuid: Guid, helpLinkGuid: Guid, _bitfield: u32, RootCauseString: ONEX_VARIABLE_BLOB, RepairString: ONEX_VARIABLE_BLOB, }; pub const ONEX_STATUS = extern struct { authStatus: ONEX_AUTH_STATUS, dwReason: u32, dwError: u32, }; pub const ONEX_EAP_METHOD_BACKEND_SUPPORT = enum(i32) { SupportUnknown = 0, Supported = 1, Unsupported = 2, }; pub const OneXEapMethodBackendSupportUnknown = ONEX_EAP_METHOD_BACKEND_SUPPORT.SupportUnknown; pub const OneXEapMethodBackendSupported = ONEX_EAP_METHOD_BACKEND_SUPPORT.Supported; pub const OneXEapMethodBackendUnsupported = ONEX_EAP_METHOD_BACKEND_SUPPORT.Unsupported; pub const ONEX_RESULT_UPDATE_DATA = extern struct { oneXStatus: ONEX_STATUS, BackendSupport: ONEX_EAP_METHOD_BACKEND_SUPPORT, fBackendEngaged: BOOL, _bitfield: u32, authParams: ONEX_VARIABLE_BLOB, eapError: ONEX_VARIABLE_BLOB, }; pub const ONEX_USER_INFO = extern struct { authIdentity: ONEX_AUTH_IDENTITY, _bitfield: u32, UserName: ONEX_VARIABLE_BLOB, DomainName: ONEX_VARIABLE_BLOB, }; const CLSID_Dot11AdHocManager_Value = Guid.initString("dd06a84f-83bd-4d01-8ab9-2389fea0869e"); pub const CLSID_Dot11AdHocManager = &CLSID_Dot11AdHocManager_Value; pub const DOT11_ADHOC_CIPHER_ALGORITHM = enum(i32) { INVALID = -1, NONE = 0, CCMP = 4, WEP = 257, }; pub const DOT11_ADHOC_CIPHER_ALGO_INVALID = DOT11_ADHOC_CIPHER_ALGORITHM.INVALID; pub const DOT11_ADHOC_CIPHER_ALGO_NONE = DOT11_ADHOC_CIPHER_ALGORITHM.NONE; pub const DOT11_ADHOC_CIPHER_ALGO_CCMP = DOT11_ADHOC_CIPHER_ALGORITHM.CCMP; pub const DOT11_ADHOC_CIPHER_ALGO_WEP = DOT11_ADHOC_CIPHER_ALGORITHM.WEP; pub const DOT11_ADHOC_AUTH_ALGORITHM = enum(i32) { INVALID = -1, @"80211_OPEN" = 1, RSNA_PSK = 7, }; pub const DOT11_ADHOC_AUTH_ALGO_INVALID = DOT11_ADHOC_AUTH_ALGORITHM.INVALID; pub const DOT11_ADHOC_AUTH_ALGO_80211_OPEN = DOT11_ADHOC_AUTH_ALGORITHM.@"80211_OPEN"; pub const DOT11_ADHOC_AUTH_ALGO_RSNA_PSK = DOT11_ADHOC_AUTH_ALGORITHM.RSNA_PSK; pub const DOT11_ADHOC_NETWORK_CONNECTION_STATUS = enum(i32) { INVALID = 0, DISCONNECTED = 11, CONNECTING = 12, CONNECTED = 13, FORMED = 14, }; pub const DOT11_ADHOC_NETWORK_CONNECTION_STATUS_INVALID = DOT11_ADHOC_NETWORK_CONNECTION_STATUS.INVALID; pub const DOT11_ADHOC_NETWORK_CONNECTION_STATUS_DISCONNECTED = DOT11_ADHOC_NETWORK_CONNECTION_STATUS.DISCONNECTED; pub const DOT11_ADHOC_NETWORK_CONNECTION_STATUS_CONNECTING = DOT11_ADHOC_NETWORK_CONNECTION_STATUS.CONNECTING; pub const DOT11_ADHOC_NETWORK_CONNECTION_STATUS_CONNECTED = DOT11_ADHOC_NETWORK_CONNECTION_STATUS.CONNECTED; pub const DOT11_ADHOC_NETWORK_CONNECTION_STATUS_FORMED = DOT11_ADHOC_NETWORK_CONNECTION_STATUS.FORMED; pub const DOT11_ADHOC_CONNECT_FAIL_REASON = enum(i32) { DOMAIN_MISMATCH = 0, PASSPHRASE_MISMATCH = 1, OTHER = 2, }; pub const DOT11_ADHOC_CONNECT_FAIL_DOMAIN_MISMATCH = DOT11_ADHOC_CONNECT_FAIL_REASON.DOMAIN_MISMATCH; pub const DOT11_ADHOC_CONNECT_FAIL_PASSPHRASE_MISMATCH = DOT11_ADHOC_CONNECT_FAIL_REASON.PASSPHRASE_MISMATCH; pub const DOT11_ADHOC_CONNECT_FAIL_OTHER = DOT11_ADHOC_CONNECT_FAIL_REASON.OTHER; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocManager_Value = Guid.initString("8f10cc26-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocManager = &IID_IDot11AdHocManager_Value; pub const IDot11AdHocManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateNetwork: fn( self: *const IDot11AdHocManager, Name: ?[*:0]const u16, Password: ?[*:0]const u16, GeographicalId: i32, pInterface: ?*IDot11AdHocInterface, pSecurity: ?*IDot11AdHocSecuritySettings, pContextGuid: ?*Guid, pIAdHoc: ?*?*IDot11AdHocNetwork, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommitCreatedNetwork: fn( self: *const IDot11AdHocManager, pIAdHoc: ?*IDot11AdHocNetwork, fSaveProfile: BOOLEAN, fMakeSavedProfileUserSpecific: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIEnumDot11AdHocNetworks: fn( self: *const IDot11AdHocManager, pContextGuid: ?*Guid, ppEnum: ?*?*IEnumDot11AdHocNetworks, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIEnumDot11AdHocInterfaces: fn( self: *const IDot11AdHocManager, ppEnum: ?*?*IEnumDot11AdHocInterfaces, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetNetwork: fn( self: *const IDot11AdHocManager, NetworkSignature: ?*Guid, pNetwork: ?*?*IDot11AdHocNetwork, ) 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 IDot11AdHocManager_CreateNetwork(self: *const T, Name: ?[*:0]const u16, Password: ?[*:0]const u16, GeographicalId: i32, pInterface: ?*IDot11AdHocInterface, pSecurity: ?*IDot11AdHocSecuritySettings, pContextGuid: ?*Guid, pIAdHoc: ?*?*IDot11AdHocNetwork) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManager.VTable, self.vtable).CreateNetwork(@ptrCast(*const IDot11AdHocManager, self), Name, Password, GeographicalId, pInterface, pSecurity, pContextGuid, pIAdHoc); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManager_CommitCreatedNetwork(self: *const T, pIAdHoc: ?*IDot11AdHocNetwork, fSaveProfile: BOOLEAN, fMakeSavedProfileUserSpecific: BOOLEAN) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManager.VTable, self.vtable).CommitCreatedNetwork(@ptrCast(*const IDot11AdHocManager, self), pIAdHoc, fSaveProfile, fMakeSavedProfileUserSpecific); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManager_GetIEnumDot11AdHocNetworks(self: *const T, pContextGuid: ?*Guid, ppEnum: ?*?*IEnumDot11AdHocNetworks) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManager.VTable, self.vtable).GetIEnumDot11AdHocNetworks(@ptrCast(*const IDot11AdHocManager, self), pContextGuid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManager_GetIEnumDot11AdHocInterfaces(self: *const T, ppEnum: ?*?*IEnumDot11AdHocInterfaces) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManager.VTable, self.vtable).GetIEnumDot11AdHocInterfaces(@ptrCast(*const IDot11AdHocManager, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManager_GetNetwork(self: *const T, NetworkSignature: ?*Guid, pNetwork: ?*?*IDot11AdHocNetwork) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManager.VTable, self.vtable).GetNetwork(@ptrCast(*const IDot11AdHocManager, self), NetworkSignature, pNetwork); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocManagerNotificationSink_Value = Guid.initString("8f10cc27-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocManagerNotificationSink = &IID_IDot11AdHocManagerNotificationSink_Value; pub const IDot11AdHocManagerNotificationSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnNetworkAdd: fn( self: *const IDot11AdHocManagerNotificationSink, pIAdHocNetwork: ?*IDot11AdHocNetwork, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnNetworkRemove: fn( self: *const IDot11AdHocManagerNotificationSink, Signature: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnInterfaceAdd: fn( self: *const IDot11AdHocManagerNotificationSink, pIAdHocInterface: ?*IDot11AdHocInterface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnInterfaceRemove: fn( self: *const IDot11AdHocManagerNotificationSink, Signature: ?*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 IDot11AdHocManagerNotificationSink_OnNetworkAdd(self: *const T, pIAdHocNetwork: ?*IDot11AdHocNetwork) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManagerNotificationSink.VTable, self.vtable).OnNetworkAdd(@ptrCast(*const IDot11AdHocManagerNotificationSink, self), pIAdHocNetwork); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManagerNotificationSink_OnNetworkRemove(self: *const T, Signature: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManagerNotificationSink.VTable, self.vtable).OnNetworkRemove(@ptrCast(*const IDot11AdHocManagerNotificationSink, self), Signature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManagerNotificationSink_OnInterfaceAdd(self: *const T, pIAdHocInterface: ?*IDot11AdHocInterface) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManagerNotificationSink.VTable, self.vtable).OnInterfaceAdd(@ptrCast(*const IDot11AdHocManagerNotificationSink, self), pIAdHocInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocManagerNotificationSink_OnInterfaceRemove(self: *const T, Signature: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocManagerNotificationSink.VTable, self.vtable).OnInterfaceRemove(@ptrCast(*const IDot11AdHocManagerNotificationSink, self), Signature); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IEnumDot11AdHocNetworks_Value = Guid.initString("8f10cc28-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IEnumDot11AdHocNetworks = &IID_IEnumDot11AdHocNetworks_Value; pub const IEnumDot11AdHocNetworks = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumDot11AdHocNetworks, cElt: u32, rgElt: [*]?*IDot11AdHocNetwork, pcEltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumDot11AdHocNetworks, cElt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumDot11AdHocNetworks, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumDot11AdHocNetworks, ppEnum: ?*?*IEnumDot11AdHocNetworks, ) 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 IEnumDot11AdHocNetworks_Next(self: *const T, cElt: u32, rgElt: [*]?*IDot11AdHocNetwork, pcEltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocNetworks.VTable, self.vtable).Next(@ptrCast(*const IEnumDot11AdHocNetworks, self), cElt, rgElt, pcEltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocNetworks_Skip(self: *const T, cElt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocNetworks.VTable, self.vtable).Skip(@ptrCast(*const IEnumDot11AdHocNetworks, self), cElt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocNetworks_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocNetworks.VTable, self.vtable).Reset(@ptrCast(*const IEnumDot11AdHocNetworks, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocNetworks_Clone(self: *const T, ppEnum: ?*?*IEnumDot11AdHocNetworks) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocNetworks.VTable, self.vtable).Clone(@ptrCast(*const IEnumDot11AdHocNetworks, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocNetwork_Value = Guid.initString("8f10cc29-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocNetwork = &IID_IDot11AdHocNetwork_Value; pub const IDot11AdHocNetwork = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetStatus: fn( self: *const IDot11AdHocNetwork, eStatus: ?*DOT11_ADHOC_NETWORK_CONNECTION_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSSID: fn( self: *const IDot11AdHocNetwork, ppszwSSID: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HasProfile: fn( self: *const IDot11AdHocNetwork, pf11d: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProfileName: fn( self: *const IDot11AdHocNetwork, ppszwProfileName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeleteProfile: fn( self: *const IDot11AdHocNetwork, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignalQuality: fn( self: *const IDot11AdHocNetwork, puStrengthValue: ?*u32, puStrengthMax: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSecuritySetting: fn( self: *const IDot11AdHocNetwork, pAdHocSecuritySetting: ?*?*IDot11AdHocSecuritySettings, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetContextGuid: fn( self: *const IDot11AdHocNetwork, pContextGuid: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSignature: fn( self: *const IDot11AdHocNetwork, pSignature: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInterface: fn( self: *const IDot11AdHocNetwork, pAdHocInterface: ?*?*IDot11AdHocInterface, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Connect: fn( self: *const IDot11AdHocNetwork, Passphrase: ?[*:0]const u16, GeographicalId: i32, fSaveProfile: BOOLEAN, fMakeSavedProfileUserSpecific: BOOLEAN, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Disconnect: fn( self: *const IDot11AdHocNetwork, ) 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 IDot11AdHocNetwork_GetStatus(self: *const T, eStatus: ?*DOT11_ADHOC_NETWORK_CONNECTION_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetStatus(@ptrCast(*const IDot11AdHocNetwork, self), eStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetSSID(self: *const T, ppszwSSID: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetSSID(@ptrCast(*const IDot11AdHocNetwork, self), ppszwSSID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_HasProfile(self: *const T, pf11d: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).HasProfile(@ptrCast(*const IDot11AdHocNetwork, self), pf11d); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetProfileName(self: *const T, ppszwProfileName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetProfileName(@ptrCast(*const IDot11AdHocNetwork, self), ppszwProfileName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_DeleteProfile(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).DeleteProfile(@ptrCast(*const IDot11AdHocNetwork, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetSignalQuality(self: *const T, puStrengthValue: ?*u32, puStrengthMax: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetSignalQuality(@ptrCast(*const IDot11AdHocNetwork, self), puStrengthValue, puStrengthMax); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetSecuritySetting(self: *const T, pAdHocSecuritySetting: ?*?*IDot11AdHocSecuritySettings) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetSecuritySetting(@ptrCast(*const IDot11AdHocNetwork, self), pAdHocSecuritySetting); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetContextGuid(self: *const T, pContextGuid: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetContextGuid(@ptrCast(*const IDot11AdHocNetwork, self), pContextGuid); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetSignature(self: *const T, pSignature: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetSignature(@ptrCast(*const IDot11AdHocNetwork, self), pSignature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_GetInterface(self: *const T, pAdHocInterface: ?*?*IDot11AdHocInterface) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).GetInterface(@ptrCast(*const IDot11AdHocNetwork, self), pAdHocInterface); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_Connect(self: *const T, Passphrase: ?[*:0]const u16, GeographicalId: i32, fSaveProfile: BOOLEAN, fMakeSavedProfileUserSpecific: BOOLEAN) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).Connect(@ptrCast(*const IDot11AdHocNetwork, self), Passphrase, GeographicalId, fSaveProfile, fMakeSavedProfileUserSpecific); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetwork_Disconnect(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetwork.VTable, self.vtable).Disconnect(@ptrCast(*const IDot11AdHocNetwork, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocNetworkNotificationSink_Value = Guid.initString("8f10cc2a-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocNetworkNotificationSink = &IID_IDot11AdHocNetworkNotificationSink_Value; pub const IDot11AdHocNetworkNotificationSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnStatusChange: fn( self: *const IDot11AdHocNetworkNotificationSink, eStatus: DOT11_ADHOC_NETWORK_CONNECTION_STATUS, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnConnectFail: fn( self: *const IDot11AdHocNetworkNotificationSink, eFailReason: DOT11_ADHOC_CONNECT_FAIL_REASON, ) 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 IDot11AdHocNetworkNotificationSink_OnStatusChange(self: *const T, eStatus: DOT11_ADHOC_NETWORK_CONNECTION_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetworkNotificationSink.VTable, self.vtable).OnStatusChange(@ptrCast(*const IDot11AdHocNetworkNotificationSink, self), eStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocNetworkNotificationSink_OnConnectFail(self: *const T, eFailReason: DOT11_ADHOC_CONNECT_FAIL_REASON) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocNetworkNotificationSink.VTable, self.vtable).OnConnectFail(@ptrCast(*const IDot11AdHocNetworkNotificationSink, self), eFailReason); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocInterface_Value = Guid.initString("8f10cc2b-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocInterface = &IID_IDot11AdHocInterface_Value; pub const IDot11AdHocInterface = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDeviceSignature: fn( self: *const IDot11AdHocInterface, pSignature: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFriendlyName: fn( self: *const IDot11AdHocInterface, ppszName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsDot11d: fn( self: *const IDot11AdHocInterface, pf11d: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsAdHocCapable: fn( self: *const IDot11AdHocInterface, pfAdHocCapable: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, IsRadioOn: fn( self: *const IDot11AdHocInterface, pfIsRadioOn: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetActiveNetwork: fn( self: *const IDot11AdHocInterface, ppNetwork: ?*?*IDot11AdHocNetwork, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIEnumSecuritySettings: fn( self: *const IDot11AdHocInterface, ppEnum: ?*?*IEnumDot11AdHocSecuritySettings, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetIEnumDot11AdHocNetworks: fn( self: *const IDot11AdHocInterface, pFilterGuid: ?*Guid, ppEnum: ?*?*IEnumDot11AdHocNetworks, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetStatus: fn( self: *const IDot11AdHocInterface, pState: ?*DOT11_ADHOC_NETWORK_CONNECTION_STATUS, ) 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 IDot11AdHocInterface_GetDeviceSignature(self: *const T, pSignature: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).GetDeviceSignature(@ptrCast(*const IDot11AdHocInterface, self), pSignature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_GetFriendlyName(self: *const T, ppszName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).GetFriendlyName(@ptrCast(*const IDot11AdHocInterface, self), ppszName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_IsDot11d(self: *const T, pf11d: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).IsDot11d(@ptrCast(*const IDot11AdHocInterface, self), pf11d); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_IsAdHocCapable(self: *const T, pfAdHocCapable: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).IsAdHocCapable(@ptrCast(*const IDot11AdHocInterface, self), pfAdHocCapable); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_IsRadioOn(self: *const T, pfIsRadioOn: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).IsRadioOn(@ptrCast(*const IDot11AdHocInterface, self), pfIsRadioOn); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_GetActiveNetwork(self: *const T, ppNetwork: ?*?*IDot11AdHocNetwork) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).GetActiveNetwork(@ptrCast(*const IDot11AdHocInterface, self), ppNetwork); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_GetIEnumSecuritySettings(self: *const T, ppEnum: ?*?*IEnumDot11AdHocSecuritySettings) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).GetIEnumSecuritySettings(@ptrCast(*const IDot11AdHocInterface, self), ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_GetIEnumDot11AdHocNetworks(self: *const T, pFilterGuid: ?*Guid, ppEnum: ?*?*IEnumDot11AdHocNetworks) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).GetIEnumDot11AdHocNetworks(@ptrCast(*const IDot11AdHocInterface, self), pFilterGuid, ppEnum); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocInterface_GetStatus(self: *const T, pState: ?*DOT11_ADHOC_NETWORK_CONNECTION_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterface.VTable, self.vtable).GetStatus(@ptrCast(*const IDot11AdHocInterface, self), pState); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IEnumDot11AdHocInterfaces_Value = Guid.initString("8f10cc2c-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IEnumDot11AdHocInterfaces = &IID_IEnumDot11AdHocInterfaces_Value; pub const IEnumDot11AdHocInterfaces = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumDot11AdHocInterfaces, cElt: u32, rgElt: [*]?*IDot11AdHocInterface, pcEltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumDot11AdHocInterfaces, cElt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumDot11AdHocInterfaces, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumDot11AdHocInterfaces, ppEnum: ?*?*IEnumDot11AdHocInterfaces, ) 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 IEnumDot11AdHocInterfaces_Next(self: *const T, cElt: u32, rgElt: [*]?*IDot11AdHocInterface, pcEltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocInterfaces.VTable, self.vtable).Next(@ptrCast(*const IEnumDot11AdHocInterfaces, self), cElt, rgElt, pcEltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocInterfaces_Skip(self: *const T, cElt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocInterfaces.VTable, self.vtable).Skip(@ptrCast(*const IEnumDot11AdHocInterfaces, self), cElt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocInterfaces_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocInterfaces.VTable, self.vtable).Reset(@ptrCast(*const IEnumDot11AdHocInterfaces, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocInterfaces_Clone(self: *const T, ppEnum: ?*?*IEnumDot11AdHocInterfaces) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocInterfaces.VTable, self.vtable).Clone(@ptrCast(*const IEnumDot11AdHocInterfaces, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IEnumDot11AdHocSecuritySettings_Value = Guid.initString("8f10cc2d-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IEnumDot11AdHocSecuritySettings = &IID_IEnumDot11AdHocSecuritySettings_Value; pub const IEnumDot11AdHocSecuritySettings = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Next: fn( self: *const IEnumDot11AdHocSecuritySettings, cElt: u32, rgElt: [*]?*IDot11AdHocSecuritySettings, pcEltFetched: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Skip: fn( self: *const IEnumDot11AdHocSecuritySettings, cElt: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Reset: fn( self: *const IEnumDot11AdHocSecuritySettings, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Clone: fn( self: *const IEnumDot11AdHocSecuritySettings, ppEnum: ?*?*IEnumDot11AdHocSecuritySettings, ) 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 IEnumDot11AdHocSecuritySettings_Next(self: *const T, cElt: u32, rgElt: [*]?*IDot11AdHocSecuritySettings, pcEltFetched: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocSecuritySettings.VTable, self.vtable).Next(@ptrCast(*const IEnumDot11AdHocSecuritySettings, self), cElt, rgElt, pcEltFetched); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocSecuritySettings_Skip(self: *const T, cElt: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocSecuritySettings.VTable, self.vtable).Skip(@ptrCast(*const IEnumDot11AdHocSecuritySettings, self), cElt); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocSecuritySettings_Reset(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocSecuritySettings.VTable, self.vtable).Reset(@ptrCast(*const IEnumDot11AdHocSecuritySettings, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IEnumDot11AdHocSecuritySettings_Clone(self: *const T, ppEnum: ?*?*IEnumDot11AdHocSecuritySettings) callconv(.Inline) HRESULT { return @ptrCast(*const IEnumDot11AdHocSecuritySettings.VTable, self.vtable).Clone(@ptrCast(*const IEnumDot11AdHocSecuritySettings, self), ppEnum); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocSecuritySettings_Value = Guid.initString("8f10cc2e-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocSecuritySettings = &IID_IDot11AdHocSecuritySettings_Value; pub const IDot11AdHocSecuritySettings = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetDot11AuthAlgorithm: fn( self: *const IDot11AdHocSecuritySettings, pAuth: ?*DOT11_ADHOC_AUTH_ALGORITHM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetDot11CipherAlgorithm: fn( self: *const IDot11AdHocSecuritySettings, pCipher: ?*DOT11_ADHOC_CIPHER_ALGORITHM, ) 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 IDot11AdHocSecuritySettings_GetDot11AuthAlgorithm(self: *const T, pAuth: ?*DOT11_ADHOC_AUTH_ALGORITHM) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocSecuritySettings.VTable, self.vtable).GetDot11AuthAlgorithm(@ptrCast(*const IDot11AdHocSecuritySettings, self), pAuth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IDot11AdHocSecuritySettings_GetDot11CipherAlgorithm(self: *const T, pCipher: ?*DOT11_ADHOC_CIPHER_ALGORITHM) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocSecuritySettings.VTable, self.vtable).GetDot11CipherAlgorithm(@ptrCast(*const IDot11AdHocSecuritySettings, self), pCipher); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IDot11AdHocInterfaceNotificationSink_Value = Guid.initString("8f10cc2f-cf0d-42a0-acbe-e2de7007384d"); pub const IID_IDot11AdHocInterfaceNotificationSink = &IID_IDot11AdHocInterfaceNotificationSink_Value; pub const IDot11AdHocInterfaceNotificationSink = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnConnectionStatusChange: fn( self: *const IDot11AdHocInterfaceNotificationSink, eStatus: DOT11_ADHOC_NETWORK_CONNECTION_STATUS, ) 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 IDot11AdHocInterfaceNotificationSink_OnConnectionStatusChange(self: *const T, eStatus: DOT11_ADHOC_NETWORK_CONNECTION_STATUS) callconv(.Inline) HRESULT { return @ptrCast(*const IDot11AdHocInterfaceNotificationSink.VTable, self.vtable).OnConnectionStatusChange(@ptrCast(*const IDot11AdHocInterfaceNotificationSink, self), eStatus); } };} pub usingnamespace MethodMixin(@This()); }; //-------------------------------------------------------------------------------- // Section: Functions (61) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanOpenHandle( dwClientVersion: u32, pReserved: ?*anyopaque, pdwNegotiatedVersion: ?*u32, phClientHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanCloseHandle( hClientHandle: ?HANDLE, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanEnumInterfaces( hClientHandle: ?HANDLE, pReserved: ?*anyopaque, ppInterfaceList: ?*?*WLAN_INTERFACE_INFO_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetAutoConfigParameter( hClientHandle: ?HANDLE, OpCode: WLAN_AUTOCONF_OPCODE, dwDataSize: u32, // TODO: what to do with BytesParamIndex 2? pData: ?*const anyopaque, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanQueryAutoConfigParameter( hClientHandle: ?HANDLE, OpCode: WLAN_AUTOCONF_OPCODE, pReserved: ?*anyopaque, pdwDataSize: ?*u32, ppData: ?*?*anyopaque, pWlanOpcodeValueType: ?*WLAN_OPCODE_VALUE_TYPE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetInterfaceCapability( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pReserved: ?*anyopaque, ppCapability: ?*?*WLAN_INTERFACE_CAPABILITY, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetInterface( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, OpCode: WLAN_INTF_OPCODE, dwDataSize: u32, // TODO: what to do with BytesParamIndex 3? pData: ?*const anyopaque, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanQueryInterface( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, OpCode: WLAN_INTF_OPCODE, pReserved: ?*anyopaque, pdwDataSize: ?*u32, ppData: ?*?*anyopaque, pWlanOpcodeValueType: ?*WLAN_OPCODE_VALUE_TYPE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanIhvControl( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, Type: WLAN_IHV_CONTROL_TYPE, dwInBufferSize: u32, // TODO: what to do with BytesParamIndex 3? pInBuffer: ?*anyopaque, dwOutBufferSize: u32, // TODO: what to do with BytesParamIndex 5? pOutBuffer: ?*anyopaque, pdwBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanScan( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pDot11Ssid: ?*const DOT11_SSID, pIeData: ?*const WLAN_RAW_DATA, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetAvailableNetworkList( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, dwFlags: u32, pReserved: ?*anyopaque, ppAvailableNetworkList: ?*?*WLAN_AVAILABLE_NETWORK_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "wlanapi" fn WlanGetAvailableNetworkList2( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, dwFlags: u32, pReserved: ?*anyopaque, ppAvailableNetworkList: ?*?*WLAN_AVAILABLE_NETWORK_LIST_V2, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetNetworkBssList( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pDot11Ssid: ?*const DOT11_SSID, dot11BssType: DOT11_BSS_TYPE, bSecurityEnabled: BOOL, pReserved: ?*anyopaque, ppWlanBssList: ?*?*WLAN_BSS_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanConnect( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pConnectionParameters: ?*const WLAN_CONNECTION_PARAMETERS, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "wlanapi" fn WlanConnect2( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pConnectionParameters: ?*const WLAN_CONNECTION_PARAMETERS_V2, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanDisconnect( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanRegisterNotification( hClientHandle: ?HANDLE, dwNotifSource: u32, bIgnoreDuplicate: BOOL, funcCallback: ?WLAN_NOTIFICATION_CALLBACK, pCallbackContext: ?*anyopaque, pReserved: ?*anyopaque, pdwPrevNotifSource: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetProfile( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, pReserved: ?*anyopaque, pstrProfileXml: ?*?PWSTR, pdwFlags: ?*u32, pdwGrantedAccess: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetProfileEapUserData( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, eapType: EAP_METHOD_TYPE, dwFlags: WLAN_SET_EAPHOST_FLAGS, dwEapUserDataSize: u32, // TODO: what to do with BytesParamIndex 5? pbEapUserData: ?*const u8, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetProfileEapXmlUserData( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, dwFlags: WLAN_SET_EAPHOST_FLAGS, strEapXmlUserData: ?[*:0]const u16, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetProfile( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, dwFlags: u32, strProfileXml: ?[*:0]const u16, strAllUserProfileSecurity: ?[*:0]const u16, bOverwrite: BOOL, pReserved: ?*anyopaque, pdwReasonCode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanDeleteProfile( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanRenameProfile( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strOldProfileName: ?[*:0]const u16, strNewProfileName: ?[*:0]const u16, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetProfileList( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pReserved: ?*anyopaque, ppProfileList: ?*?*WLAN_PROFILE_INFO_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetProfileList( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, dwItems: u32, strProfileNames: [*]?PWSTR, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetProfilePosition( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, dwPosition: u32, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetProfileCustomUserData( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, dwDataSize: u32, // TODO: what to do with BytesParamIndex 3? pData: ?*const u8, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetProfileCustomUserData( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, pReserved: ?*anyopaque, pdwDataSize: ?*u32, ppData: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetFilterList( hClientHandle: ?HANDLE, wlanFilterListType: WLAN_FILTER_LIST_TYPE, pNetworkList: ?*const DOT11_NETWORK_LIST, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetFilterList( hClientHandle: ?HANDLE, wlanFilterListType: WLAN_FILTER_LIST_TYPE, pReserved: ?*anyopaque, ppNetworkList: ?*?*DOT11_NETWORK_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetPsdIEDataList( hClientHandle: ?HANDLE, strFormat: ?[*:0]const u16, pPsdIEDataList: ?*const WLAN_RAW_DATA_LIST, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSaveTemporaryProfile( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, strProfileName: ?[*:0]const u16, strAllUserProfileSecurity: ?[*:0]const u16, dwFlags: u32, bOverWrite: BOOL, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "wlanapi" fn WlanDeviceServiceCommand( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, pDeviceServiceGuid: ?*Guid, dwOpCode: u32, dwInBufferSize: u32, // TODO: what to do with BytesParamIndex 4? pInBuffer: ?*anyopaque, dwOutBufferSize: u32, // TODO: what to do with BytesParamIndex 6? pOutBuffer: ?*anyopaque, pdwBytesReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "wlanapi" fn WlanGetSupportedDeviceServices( hClientHandle: ?HANDLE, pInterfaceGuid: ?*const Guid, ppDevSvcGuidList: ?*?*WLAN_DEVICE_SERVICE_GUID_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "wlanapi" fn WlanRegisterDeviceServiceNotification( hClientHandle: ?HANDLE, pDevSvcGuidList: ?*const WLAN_DEVICE_SERVICE_GUID_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanExtractPsdIEDataList( hClientHandle: ?HANDLE, dwIeDataSize: u32, // TODO: what to do with BytesParamIndex 1? pRawIeData: ?*const u8, strFormat: ?[*:0]const u16, pReserved: ?*anyopaque, ppPsdIEDataList: ?*?*WLAN_RAW_DATA_LIST, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanReasonCodeToString( dwReasonCode: u32, dwBufferSize: u32, pStringBuffer: [*]u16, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanAllocateMemory( dwMemorySize: u32, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanFreeMemory( pMemory: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanSetSecuritySettings( hClientHandle: ?HANDLE, SecurableObject: WLAN_SECURABLE_OBJECT, strModifiedSDDL: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanapi" fn WlanGetSecuritySettings( hClientHandle: ?HANDLE, SecurableObject: WLAN_SECURABLE_OBJECT, pValueType: ?*WLAN_OPCODE_VALUE_TYPE, pstrCurrentSDDL: ?*?PWSTR, pdwGrantedAccess: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "wlanui" fn WlanUIEditProfile( dwClientVersion: u32, wstrProfileName: ?[*:0]const u16, pInterfaceGuid: ?*Guid, hWnd: ?HWND, wlStartPage: WL_DISPLAY_PAGES, pReserved: ?*anyopaque, pWlanReasonCode: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkStartUsing( hClientHandle: ?HANDLE, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkStopUsing( hClientHandle: ?HANDLE, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkForceStart( hClientHandle: ?HANDLE, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkForceStop( hClientHandle: ?HANDLE, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkQueryProperty( hClientHandle: ?HANDLE, OpCode: WLAN_HOSTED_NETWORK_OPCODE, pdwDataSize: ?*u32, ppvData: ?*?*anyopaque, pWlanOpcodeValueType: ?*WLAN_OPCODE_VALUE_TYPE, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkSetProperty( hClientHandle: ?HANDLE, OpCode: WLAN_HOSTED_NETWORK_OPCODE, dwDataSize: u32, // TODO: what to do with BytesParamIndex 2? pvData: ?*anyopaque, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkInitSettings( hClientHandle: ?HANDLE, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkRefreshSecuritySettings( hClientHandle: ?HANDLE, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkQueryStatus( hClientHandle: ?HANDLE, ppWlanHostedNetworkStatus: ?*?*WLAN_HOSTED_NETWORK_STATUS, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkSetSecondaryKey( hClientHandle: ?HANDLE, dwKeyLength: u32, // TODO: what to do with BytesParamIndex 1? pucKeyData: ?*u8, bIsPassPhrase: BOOL, bPersistent: BOOL, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanHostedNetworkQuerySecondaryKey( hClientHandle: ?HANDLE, pdwKeyLength: ?*u32, ppucKeyData: ?*?*u8, pbIsPassPhrase: ?*BOOL, pbPersistent: ?*BOOL, pFailReason: ?*WLAN_HOSTED_NETWORK_REASON, pvReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows6.1' pub extern "wlanapi" fn WlanRegisterVirtualStationNotification( hClientHandle: ?HANDLE, bRegister: BOOL, pReserved: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDOpenHandle( dwClientVersion: u32, pdwNegotiatedVersion: ?*u32, phClientHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDCloseHandle( hClientHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDStartOpenSession( hClientHandle: ?HANDLE, pDeviceAddress: ?*?*u8, pvContext: ?*anyopaque, pfnCallback: ?WFD_OPEN_SESSION_COMPLETE_CALLBACK, phSessionHandle: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDCancelOpenSession( hSessionHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDOpenLegacySession( hClientHandle: ?HANDLE, pLegacyMacAddress: ?*?*u8, phSessionHandle: ?*?HANDLE, pGuidSessionInterface: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDCloseSession( hSessionHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows8.0' pub extern "wlanapi" fn WFDUpdateDeviceVisibility( pDeviceAddress: ?*?*u8, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (0) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { }, .wide => struct { }, .unspecified => if (@import("builtin").is_test) struct { } else struct { }, }; //-------------------------------------------------------------------------------- // Section: Imports (12) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BOOLEAN = @import("../foundation.zig").BOOLEAN; const EAP_METHOD_TYPE = @import("../security/extensible_authentication_protocol.zig").EAP_METHOD_TYPE; const HANDLE = @import("../foundation.zig").HANDLE; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IUnknown = @import("../system/com.zig").IUnknown; const LARGE_INTEGER = @import("../foundation.zig").LARGE_INTEGER; const NDIS_OBJECT_HEADER = @import("../network_management/ndis.zig").NDIS_OBJECT_HEADER; const PROPERTYKEY = @import("../ui/shell/properties_system.zig").PROPERTYKEY; const PWSTR = @import("../foundation.zig").PWSTR; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "WLAN_NOTIFICATION_CALLBACK")) { _ = WLAN_NOTIFICATION_CALLBACK; } if (@hasDecl(@This(), "WFD_OPEN_SESSION_COMPLETE_CALLBACK")) { _ = WFD_OPEN_SESSION_COMPLETE_CALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("builtin").is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
win32/network_management/wi_fi.zig
const std = @import("std"); const clap = @import("clap"); const csv = @import("csv"); const Converter = @import("./converter.zig").Converter; // Print flag usage to stdout. pub fn printHelp(comptime params: []const clap.Param(clap.Help)) !void { std.debug.print("Convert CSV to JSON files.\n", .{}); try clap.help( std.io.getStdErr().writer(), params, ); } pub fn printStats(start: u64, end: u64, lines: u64) void { const diff = @intToFloat(f64, end - start); const ln = @intToFloat(f64, lines); var val: f64 = 0; var unit: []const u8 = undefined; if (diff < std.time.ns_per_us) { val = diff; unit = "nano"; } else if (diff < std.time.ns_per_ms) { val = diff / @intToFloat(f64, std.time.ns_per_us); unit = "micro"; } else if (diff < std.time.ns_per_s) { val = diff / @intToFloat(f64, std.time.ns_per_ms); unit = "milli"; } else { val = diff / @intToFloat(f64, std.time.ns_per_s); } var rate = ln / (diff / @intToFloat(f64, std.time.ns_per_s)); if (rate > ln) { rate = ln; } std.debug.print("Processed {d} lines in {d:.2} {s}seconds ({d:.2} lines / second)\n", .{ lines, val, unit, rate }); } pub fn main() !void { const params = comptime [_]clap.Param(clap.Help){ clap.parseParam("-h, --help Display this help and exit.") catch unreachable, clap.parseParam("-i, --in <STR> Path to input CSV file.") catch unreachable, clap.parseParam("-a, --array <BOOL> Convert rows to arrays instead of JSON lines.") catch unreachable, clap.parseParam("-b, --buf <UINT32> Line buffer (default: 4096). Should be greater than the longest line.") catch unreachable, }; // Help / usage. var args = clap.parse(clap.Help, &params, .{}) catch |err| { std.debug.print("invalid flags: {s}\n\n", .{@errorName(err)}); try printHelp(&params); std.os.exit(1); }; defer args.deinit(); if (args.flag("--help")) { try printHelp(&params); std.os.exit(1); } var bufSize: u32 = 4096; if (args.option("--buf")) |b| { bufSize = std.fmt.parseUnsigned(u32, b, 10) catch |err| { std.debug.print("Invalid buffer size {s}\n\n", .{@errorName(err)}); // to fix the error: unused capture std.os.exit(1); }; } if (args.option("--in")) |fPath| { std.debug.print("Reading {s} ...\n", .{fPath}); var timer = try std.time.Timer.start(); const start = timer.read(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); // New Error: // ./src/main.zig:79:45: error: expected type '*std.mem.Allocator', found '*const (bound fn(*std.heap.arena_allocator.ArenaAllocator) std.mem.Allocator)' // var conv = try Converter.init(&arena.allocator, std.io.getStdOut().writer(), bufSize); // ^ // To Fix The New Error: defer arena.deinit(); // it looks like the API for allocators has changed slightly [Refrence issue: https://github.com/Sobeston/ziglearn/issues/131] const allocator = &arena.allocator(); // allocator is a function, not a field // var conv = try Converter.init(&arena.allocator, std.io.getStdOut().writer(), bufSize); var conv = try Converter.init(allocator, std.io.getStdOut().writer(), bufSize); const lines = try conv.convert(fPath); printStats(start, timer.read(), lines); std.os.exit(0); } // No flags. try printHelp(&params); }
src/main.zig
const wlr = @import("../wlroots.zig"); const wayland = @import("wayland"); const wl = wayland.server.wl; pub const AxisSource = enum(c_int) { wheel, finger, continuous, wheel_tilt, }; pub const AxisOrientation = enum(c_int) { vertical, horizontal, }; pub const Pointer = extern struct { pub const event = struct { pub const Motion = extern struct { device: *wlr.InputDevice, time_msec: u32, delta_x: f64, delta_y: f64, unaccel_dx: f64, unaccel_dy: f64, }; pub const MotionAbsolute = extern struct { device: *wlr.InputDevice, time_msec: u32, x: f64, y: f64, }; pub const Button = extern struct { device: *wlr.InputDevice, time_msec: u32, button: u32, state: wl.Pointer.ButtonState, }; pub const Axis = extern struct { device: *wlr.InputDevice, time_msec: u32, source: AxisSource, orientation: AxisOrientation, delta: f64, delta_discrete: i32, }; pub const SwipeBegin = extern struct { device: *wlr.InputDevice, time_msec: u32, fingers: u32, }; pub const SwipeUpdate = extern struct { device: *wlr.InputDevice, time_msec: u32, fingers: u32, dx: f64, dy: f64, }; pub const SwipeEnd = extern struct { device: *wlr.InputDevice, time_msec: u32, cancelled: bool, }; pub const PinchBegin = extern struct { device: *wlr.InputDevice, time_msec: u32, fingers: u32, }; pub const PinchUpdate = extern struct { device: *wlr.InputDevice, time_msec: u32, fingers: u32, dx: f64, dy: f64, scale: f64, rotation: f64, }; pub const PinchEnd = extern struct { device: *wlr.InputDevice, time_msec: u32, cancelled: bool, }; pub const HoldBegin = extern struct { device: *wlr.InputDevice, time_msec: u32, fingers: u32, }; pub const HoldEnd = extern struct { device: *wlr.InputDevice, time_msec: u32, cancelled: bool, }; }; const Impl = opaque {}; impl: *const Impl, events: extern struct { motion: wl.Signal(*event.Motion), motion_absolute: wl.Signal(*event.MotionAbsolute), button: wl.Signal(*event.Button), axis: wl.Signal(*event.Axis), frame: wl.Signal(*Pointer), swipe_begin: wl.Signal(*event.SwipeBegin), swipe_update: wl.Signal(*event.SwipeUpdate), swipe_end: wl.Signal(*event.SwipeEnd), pinch_begin: wl.Signal(*event.PinchBegin), pinch_update: wl.Signal(*event.PinchUpdate), pinch_end: wl.Signal(*event.PinchEnd), hold_begin: wl.Signal(*event.HoldBegin), hold_end: wl.Signal(*event.HoldEnd), }, };
src/types/pointer.zig
const std = @import("std"); const BoundedArray = std.BoundedArray; const EnumMap = std.EnumMap; const hasFn = std.meta.trait.hasFn; const builtin = @import("builtin"); pub const Schema = struct { tables: []const type, indexes: []const TableColumn, foreign_keys: []const ForeignKey, }; pub const TableColumn = struct { table: type, field: []const u8, }; pub const ForeignKey = struct { pkey: TableColumn, fkey: TableColumn, }; pub fn Selector(comptime KeyType: type) type { return struct { field_name: []const u8, op: enum { eql, greater_than, less_than }, comparison_value: KeyType, }; } // Temporary in-memory tables fn TransactionRow(comptime Row: anytype) type { _ = Row; return struct { pk_id: u32, // fields would be added at compile time (search Row for pk_* fields) field_id: u32, state: enum { nulled, non_null, deleted }, new_value: []const u8, }; } pub fn DataBase(comptime schema: []const type) type { _ = schema; return struct { const Self = @This(); pub fn load(file_path: []const u8, schema_version: u32) !Self { _ = file_path; _ = schema_version; // open database file, check schema version, check schema matches database, etc. return Self{}; } pub fn getOne(self: *Self, comptime RowType: type, field_name: []const u8, comptime value: anytype) !RowType { _ = self; _ = field_name; _ = value; var row: RowType = undefined; // full table scan for matching row if (builtin.mode == .Debug and hasFn("validate")(RowType)) { try row.validate(); } return row; } pub fn getMany(self: *Self, comptime RowType: type, selector: anytype) ![]RowType { _ = self; _ = RowType; _ = selector; return undefined; } pub fn insert(self: *Self, comptime RowType: type, row: RowType) !void { _ = self; if (hasFn("validate")(RowType)) { try row.validate(); } } pub fn insertAutoInc(self: *Self, comptime RowType: type, auto_inc_field: []const u8, row: RowType) !void { _ = self; _ = RowType; _ = auto_inc_field; _ = row; } pub fn update(self: *Self, comptime RowType: type, row: RowType, field_names: []const []const u8) !void { _ = self; _ = RowType; _ = row; _ = field_names; } pub fn delete(self: *Self, comptime RowType: type, field_name: []const u8, comptime value: anytype) !void { _ = self; _ = RowType; _ = field_name; _ = value; } pub fn commit(self: *Self) !void { _ = self; // write current in-memory transaction to disk } pub fn deinit(self: *Self) !void { try self.commit(); // close file etc. } }; } ///// const my_schema = [_]type{ Sim, Clothing }; const SimAge = enum { baby, toddler, child, teenager, adult, elder }; const SimNameType = BoundedArray(u8, 24); const Sim = struct { // pk_* fields are primary keys pk_id: u32, first_name: SimNameType, last_name: SimNameType, genetics: [16]u8, age: SimAge, clothes: union(enum) { full_body_outfit: u32, // fkey top_bottom_outfit: struct { top: u32, // fkey bottom: u32, // fkey }, }, // Row structs can have a validate() function which is called when inserting and updating pub fn validate(self: Sim) !void { if (self.first_name.len == 0 or self.last_name.len == 0) { return error.InvalidName; } } }; const Clothing = struct { pk_id: u32, name: BoundedArray(u8, 32), asset_name: BoundedArray(u8, 32), valid_ages: EnumMap(SimAge, void), }; test "" { var db = try DataBase(my_schema[0..]).load("mydatabase", 3); defer db.deinit() catch unreachable; var my_sim = Sim{ .pk_id = 6, .first_name = SimNameType.fromSlice("John") catch unreachable, .last_name = SimNameType.fromSlice("Doe") catch unreachable, .genetics = [_]u8{0} ** 16, .age = .adult, .clothes = .{ .full_body_outfit = 0 }, }; try db.insert(Sim, my_sim); try db.insertAutoInc(Sim, "pk_id", my_sim); // id set to autoincrement value my_sim = try db.getOne(Sim, "pk_id", 5); my_sim.first_name = SimNameType.fromSlice("Susan") catch unreachable; try db.update(Sim, my_sim, ([_][]const u8{"first_name"})[0..]); // update specific field(s) try db.delete(Sim, "pk_id", 6); try db.commit(); }
Game Database.zig
const std = @import("std"); const max_n = 12; const Vec = std.meta.Vector(max_n, u8); fn runInParallel(tasks: []std.Thread, len: usize, comptime f: anytype, args: anytype) !void { const len_per_task = @divTrunc(len, tasks.len + 1); for (tasks) |*task, i| { const first = len_per_task*i; const last = first + len_per_task; task.* = try std.Thread.spawn(.{}, f, .{first, last} ++ args); } @call(.{}, f, .{tasks.len*len_per_task, len} ++ args); for (tasks) |*task| task.join(); } fn reverse_mask(n: u8) Vec { // global constant is not used to workaround a compiler bug var v = Vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var i: u8 = 0; while (i < n) : (i += 1) v[i] = n - i - 1; return v; } fn rotate_mask(n: u8) Vec { var v = Vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var i: u8 = 0; while (i < n) : (i += 1) v[i] = (i + 1) % n; return v; } fn nextPermMask(n: u8) Vec { var v = Vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; var i: u8 = 2; while (i <= n) : (i += 1) v = applyMask(v, i, rotate_mask); return v; } fn applyMask(a: Vec, n: u8, comptime mask: anytype) Vec { comptime var i: u8 = 0; inline while (i < max_n) : (i += 1) if (i == n) return @shuffle(u8, a, undefined, mask(i)); unreachable; } fn pfannkuchen(perm: Vec) u32 { var flip_count: u32 = 0; var a = perm; while (true) { const k = a[0]; if (k == 0) return flip_count; a = applyMask(a, k + 1, reverse_mask); flip_count += 1; } } fn factorial(n: u8) u32 { var res: u32 = 1; var i: u8 = 2; while (i <= n) : (i += 1) res *= i; return res; } fn factorialComptime(n: u8) u32 { comptime var i = 0; inline while (i < max_n) : (i += 1) if (i == n) return comptime factorial(i); unreachable; } fn countAtPos(n: u8, start: usize) [max_n]u8 { var count: [max_n]u8 = undefined; var r = start; var i = n; while (i > 0) { i -= 1; const total_perms = factorialComptime(i); count[i] = i + 1 - @intCast(u8, r / total_perms); r %= total_perms; } return count; } fn permWithCount(n: u8, count: [max_n]u8) Vec { var perm = Vec { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }; const permVals = std.mem.asBytes(&perm); var i = n; while (i > 0) : (i -= 1) std.mem.rotate(u8, permVals[0..i], i - count[i - 1]); return perm; } const Stats = struct { checksum: i32 = 0, max_flips: u32 = 0, }; fn nextPermutation(perm: Vec, count: []u8) ?Vec { const r = for (count) |v, i| { if (v != 1) break @intCast(u8, i); } else return null; const next_perm = applyMask(perm, r + 1, nextPermMask); count[r] -= 1; for (count[0..r]) |*v, i| v.* = @intCast(u8, i + 1); return next_perm; } fn pfannkuchenStats(first: usize, last: usize, n: u8, res: *Stats) void { var count = countAtPos(n, first); var perm = permWithCount(n, count); var stats = Stats {}; var i = first; while (i < last) : (i += 1) { const flips = pfannkuchen(perm); const parity = 1 - @intCast(i32, i % 2)*2; stats.max_flips = std.math.max(stats.max_flips, flips); stats.checksum += @intCast(i32, flips) * parity; perm = nextPermutation(perm, count[0..n]) orelse break; } _ = @atomicRmw(u32, &res.max_flips, .Max, stats.max_flips, .SeqCst); _ = @atomicRmw(i32, &res.checksum, .Add, stats.checksum, .SeqCst); } pub fn main() !void { const n = try get_n(); var tasks_buf: [64]std.Thread = undefined; const task_count = try std.Thread.getCpuCount(); const tasks = tasks_buf[0 .. task_count - 1]; var stats = Stats {}; const perms_count = factorialComptime(n); try runInParallel(tasks, perms_count, pfannkuchenStats, .{n, &stats}); const stdout = std.io.getStdOut().writer(); try stdout.print("{d}\nPfannkuchen({d}) = {d}\n", .{ stats.checksum, n, stats.max_flips }); } fn get_n() !u8 { var arg_it = std.process.args(); _ = arg_it.skip(); const arg = arg_it.next() orelse return 10; return try std.fmt.parseInt(u8, arg, 10); }
bench/algorithm/fannkuch-redux/2-m.zig
const std = @import("std"); const mem = std.mem; const json = std.json; const Lexer = @import("lexer.zig").Lexer; const log = @import("log.zig"); usingnamespace @import("parse_atx_heading.zig"); usingnamespace @import("parse_codeblock.zig"); /// Function prototype for a State Transition in the Parser pub const StateTransition = fn (lexer: *Lexer) anyerror!?AstNode; pub const Node = struct { ID: ID, Value: ?[]const u8, PositionStart: Position, PositionEnd: Position, Children: std.ArrayList(Node), Level: u32, pub const Position = struct { Line: u32, Column: u32, Offset: u32, }; pub const ID = enum { AtxHeading, Text, CodeBlock, pub fn jsonStringify( value: ID, options: json.StringifyOptions, out_stream: anytype, ) !void { try json.stringify(@tagName(value), options, out_stream); } }; pub const StringifyOptions = struct { pub const Whitespace = struct { /// How many indentation levels deep are we? indent_level: usize = 0, /// What character(s) should be used for indentation? indent: union(enum) { Space: u8, Tab: void, } = .{ .Space = 4 }, /// Newline after each element separator: bool = true, pub fn outputIndent( whitespace: @This(), out_stream: anytype, ) @TypeOf(out_stream).Error!void { var char: u8 = undefined; var n_chars: usize = undefined; switch (whitespace.indent) { .Space => |n_spaces| { char = ' '; n_chars = n_spaces; }, .Tab => { char = '\t'; n_chars = 1; }, } n_chars *= whitespace.indent_level; try out_stream.writeByteNTimes(char, n_chars); } }; /// Controls the whitespace emitted whitespace: ?Whitespace = null, string: StringOptions = StringOptions{ .String = .{} }, /// Should []u8 be serialised as a string? or an array? pub const StringOptions = union(enum) { Array, String: StringOutputOptions, /// String output options const StringOutputOptions = struct { /// Should '/' be escaped in strings? escape_solidus: bool = false, /// Should unicode characters be escaped in strings? escape_unicode: bool = false, }; }; }; pub fn deinit(self: @This()) void { self.Children.deinit(); } pub fn jsonStringify( value: @This(), options: json.StringifyOptions, out_stream: anytype, ) !void { try out_stream.writeByte('{'); const T = @TypeOf(value); const S = @typeInfo(T).Struct; comptime var field_output = false; var child_options = options; if (child_options.whitespace) |*child_whitespace| { child_whitespace.indent_level += 1; } inline for (S.fields) |Field, field_i| { if (Field.field_type == void) continue; if (!field_output) { field_output = true; } else { try out_stream.writeByte(','); } if (child_options.whitespace) |child_whitespace| { try out_stream.writeByte('\n'); try child_whitespace.outputIndent(out_stream); } try json.stringify(Field.name, options, out_stream); try out_stream.writeByte(':'); if (child_options.whitespace) |child_whitespace| { if (child_whitespace.separator) { try out_stream.writeByte(' '); } } if (comptime !mem.eql(u8, Field.name, "Children")) { try json.stringify(@field(value, Field.name), child_options, out_stream); } else { var boop = @field(value, Field.name); if (boop.items.len == 0) { _ = try out_stream.writeAll("[]"); } else { _ = try out_stream.write("["); for (boop.items) |item| { try json.stringify(item, child_options, out_stream); } _ = try out_stream.write("]"); } } } if (field_output) { if (options.whitespace) |whitespace| { try out_stream.writeByte('\n'); try whitespace.outputIndent(out_stream); } } try out_stream.writeByte('}'); return; } pub fn htmlStringify( value: @This(), options: StringifyOptions, out_stream: anytype, ) !void { var child_options = options; switch (value.ID) { .AtxHeading => { var lvl = value.Level; var text = value.Children.items[0].Value; _ = try out_stream.print("<h{}>{}</h{}>", .{ lvl, text, lvl }); if (child_options.whitespace) |child_whitespace| { if (child_whitespace.separator) { try out_stream.writeByte('\n'); } } }, .CodeBlock => { var lvl = value.Level; var text = value.Children.items[0].Value; _ = try out_stream.print("<pre><code>{}</code></pre>", .{text}); if (child_options.whitespace) |child_whitespace| { if (child_whitespace.separator) { try out_stream.writeByte('\n'); } } }, .Text => {}, } } }; /// A non-stream Markdown parser which constructs a tree of Nodes pub const Parser = struct { allocator: *mem.Allocator, root: std.ArrayList(Node), state: State, lex: Lexer, pub const State = enum { Start, AtxHeader, CodeBlock, }; pub fn init( allocator: *mem.Allocator, ) Parser { return Parser{ .allocator = allocator, .state = .Start, .root = std.ArrayList(Node).init(allocator), .lex = undefined, }; } pub fn deinit(self: *Parser) void { for (self.root.items) |item| { for (item.Children.items) |subchild| { if (subchild.Value) |val2| { self.allocator.free(val2); } subchild.deinit(); } if (item.Value) |val| { self.allocator.free(val); } item.deinit(); } self.root.deinit(); self.lex.deinit(); } pub fn parse(self: *Parser, input: []const u8) !void { self.lex = try Lexer.init(self.allocator, input); while (true) { if (try self.lex.next()) |tok| { switch (tok.ID) { .Invalid => {}, .Text => {}, .Whitespace => { try stateCodeBlock(self); // if (mem.eql(u8, tok.string, "\n")) {} }, .AtxHeader => { try stateAtxHeader(self); }, .EOF => { log.Debug("Found EOF"); break; }, } } } } };
src/md/parse.zig
const std = @import("std"); const ig = @import("imgui"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const Child = std.meta.Child; const NULL_TERM = [_]u8{0}; fn nullTerm(comptime str: []const u8) [:0]const u8 { const fullStr = str ++ NULL_TERM; return fullStr[0..str.len :0]; } fn allocPrintZ(allocator: *Allocator, comptime fmt: []const u8, params: anytype) ![:0]const u8 { const formatted = try std.fmt.allocPrint(allocator, fmt ++ NULL_TERM, params); assert(formatted[formatted.len - 1] == 0); return formatted[0 .. formatted.len - 1 :0]; } const INLINE_FLAGS = ig.TreeNodeFlags{ .Leaf = true, .NoTreePushOnOpen = true, .Bullet = true }; const MAX_STRING_LEN = 255; pub fn draw(comptime DataType: type, dataPtr: *const DataType, heapAllocator: *Allocator) void { var allocatorRaw = std.heap.ArenaAllocator.init(heapAllocator); defer allocatorRaw.deinit(); const arena = &allocatorRaw.allocator; drawStructUI(DataType, dataPtr, arena); } /// Recursively draws generated read-only UI for a single struct. /// No memory from the passed arena is in use after this call. It can be freed or reset. pub fn drawStructUI(comptime DataType: type, dataPtr: *const DataType, arena: *Allocator) void { switch (@typeInfo(DataType)) { .Struct => |info| { inline for (info.fields) |field| { drawFieldUI(field.field_type, &@field(dataPtr, field.name), nullTerm(field.name), arena); } }, .Pointer => { drawStructUI(Child(DataType), dataPtr.*, arena); }, else => @compileError("Invalid type passed to drawStructUI: " ++ @typeName(DataType)), } } /// Recursively draws generated read-only UI for a named field. /// name must be a null-terminated string. /// No memory from the passed arena is in use after this call. It can be freed or reset. /// fieldPtr is `var` to allow arbitrary bit alignment pub fn drawFieldUI(comptime FieldType: type, fieldPtr: anytype, name: [:0]const u8, arena: *Allocator) void { if (FieldType == c_void) { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("0x%p", fieldPtr); ig.NextColumn(); return; } switch (@typeInfo(FieldType)) { .Bool => { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text(if (fieldPtr.*) "true" else "false"); ig.NextColumn(); }, .Int => |info| { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); if (info.is_signed) { ig.Text("%lld (%s)", @intCast(isize, fieldPtr.*), @typeName(FieldType)); } else { ig.Text("%llu (%s)", @intCast(usize, fieldPtr.*), @typeName(FieldType)); } ig.NextColumn(); }, .Float => { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("%f (%s)", fieldPtr.*, @typeName(FieldType)); ig.NextColumn(); }, .Array => |info| { drawSliceFieldUI(info.child, fieldPtr.*[0..info.len], name, arena); }, .Enum => |info| { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); const cstr = if (allocPrintZ(arena, "{}", .{@tagName(fieldPtr.*)})) |str| str else |err| "<out of memory>"; ig.Text(".%s", cstr.ptr); ig.NextColumn(); }, .Struct => |info| { ig.AlignTextToFramePadding(); const nodeOpen = ig.TreeNodeStr(name.ptr); defer if (nodeOpen) ig.TreePop(); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("%s", @typeName(FieldType)); ig.NextColumn(); if (nodeOpen) { drawStructUI(FieldType, fieldPtr, arena); } }, .Optional => |info| { if (fieldPtr.*) |nonnullValue| { drawFieldUI(info.child, &nonnullValue, name, arena); } else { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("null"); ig.NextColumn(); } }, .Pointer => |info| { switch (info.size) { .One => drawFieldUI(info.child, fieldPtr.*, name, arena), .Slice => drawSliceFieldUI(info.child, fieldPtr.*, name, arena), else => { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("0x%p", fieldPtr.*); ig.NextColumn(); }, } }, .Opaque => { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("%s@0x%p", @typeName(FieldType), fieldPtr); ig.NextColumn(); }, else => { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("<TODO " ++ @typeName(FieldType) ++ ">@0x%p", fieldPtr); ig.NextColumn(); }, } } /// Recursively draws generated UI for a slice. If the slice is []u8, checks if it is a printable string /// and draws it if so. Otherwise generates similar UI to a struct, with fields named [0], [1], etc. /// If the slice has length one and its payload is a struct, the [0] field will be elided and the single /// element will be displayed inline. /// No memory from the passed arena is in use after this call. It can be freed or reset. pub fn drawSliceFieldUI(comptime DataType: type, slice: []const DataType, name: [:0]const u8, arena: *Allocator) void { if (DataType == u8 and slice.len < MAX_STRING_LEN and isPrintable(slice)) { ig.AlignTextToFramePadding(); _ = ig.TreeNodeExStrExt(name.ptr, INLINE_FLAGS); ig.NextColumn(); ig.AlignTextToFramePadding(); const nullTermStr = if (allocPrintZ(arena, "{}", .{slice})) |cstr| cstr else |err| "out of memory"; ig.Text("\"%s\" ", nullTermStr.ptr); ig.NextColumn(); } else { ig.AlignTextToFramePadding(); const nodeOpen = ig.TreeNodeStr(name.ptr); defer if (nodeOpen) ig.TreePop(); ig.NextColumn(); ig.AlignTextToFramePadding(); ig.Text("[%llu]%s", slice.len, nullTerm(@typeName(DataType)).ptr); ig.NextColumn(); if (nodeOpen) { const NextDisplayType = RemoveSinglePointers(DataType); if (@typeInfo(NextDisplayType) == .Struct and slice.len == 1) { drawStructUI(DataType, &slice[0], arena); } else { for (slice) |*item, i| { // TODO: Put null-terminated printing into const itemName: [:0]const u8 = if (allocPrintZ(arena, "[{}]", .{i})) |str| str else |err| "<out of memory>"; drawFieldUI(DataType, item, itemName, arena); } } } } } /// Returns true if the string is made up of only printable characters. /// \n,\r, and \t are not considered printable by this function. fn isPrintable(string: []const u8) bool { for (string) |char| { if (char < 32 or char > 126) return false; } return true; } /// Returns the type that this type points to after unwrapping all /// non-nullable single pointers. Examples: /// *T -> T /// **T -> T /// ?*T -> ?*T /// **?*T -> ?*T /// *[*]*T -> [*]*T fn RemoveSinglePointers(comptime InType: type) type { comptime var Type = InType; comptime while (@typeInfo(Type) == .Pointer and @typeInfo(Type).Pointer.size == .One) { Type = Child(Type); }; return Type; }
src/autogui.zig
const std = @import("std"); const mem = std.mem; const fmt = std.fmt; /// X25519 DH function. pub const X25519 = struct { /// The underlying elliptic curve. pub const Curve = @import("curve25519.zig").Curve25519; /// Length (in bytes) of a secret key. pub const secret_length = 32; /// Length (in bytes) of the output of the DH function. pub const minimum_key_length = 32; /// Compute the public key for a given private key. pub fn createPublicKey(public_key: []u8, private_key: []const u8) bool { std.debug.assert(private_key.len >= minimum_key_length); std.debug.assert(public_key.len >= minimum_key_length); var s: [32]u8 = undefined; mem.copy(u8, &s, private_key[0..32]); if (Curve.basePoint.clampedMul(s)) |q| { mem.copy(u8, public_key, q.toBytes()[0..]); return true; } else |_| { return false; } } /// Compute the scalar product of a public key and a secret scalar. /// Note that the output should not be used as a shared secret without /// hashing it first. pub fn create(out: []u8, private_key: []const u8, public_key: []const u8) bool { std.debug.assert(out.len >= secret_length); std.debug.assert(private_key.len >= minimum_key_length); std.debug.assert(public_key.len >= minimum_key_length); var s: [32]u8 = undefined; var b: [32]u8 = undefined; mem.copy(u8, &s, private_key[0..32]); mem.copy(u8, &b, public_key[0..32]); if (Curve.fromBytes(b).clampedMul(s)) |q| { mem.copy(u8, out, q.toBytes()[0..]); return true; } else |_| { return false; } } }; test "x25519 public key calculation from secret key" { var sk: [32]u8 = undefined; var pk_expected: [32]u8 = undefined; var pk_calculated: [32]u8 = undefined; try fmt.hexToBytes(sk[0..], "8052030376d47112be7f73ed7a019293dd12ad910b654455798b4667d73de166"); try fmt.hexToBytes(pk_expected[0..], "f1814f0e8ff1043d8a44d25babff3cedcae6c22c3edaa48f857ae70de2baae50"); std.testing.expect(X25519.createPublicKey(pk_calculated[0..], &sk)); std.testing.expectEqual(pk_calculated, pk_expected); } test "x25519 rfc7748 vector1" { const secret_key = [32]u8{ 0xa5, 0x46, 0xe3, 0x6b, 0xf0, 0x52, 0x7c, 0x9d, 0x3b, 0x16, 0x15, 0x4b, 0x82, 0x46, 0x5e, 0xdd, 0x62, 0x14, 0x4c, 0x0a, 0xc1, 0xfc, 0x5a, 0x18, 0x50, 0x6a, 0x22, 0x44, 0xba, 0x44, 0x9a, 0xc4 }; const public_key = [32]u8{ 0xe6, 0xdb, 0x68, 0x67, 0x58, 0x30, 0x30, 0xdb, 0x35, 0x94, 0xc1, 0xa4, 0x24, 0xb1, 0x5f, 0x7c, 0x72, 0x66, 0x24, 0xec, 0x26, 0xb3, 0x35, 0x3b, 0x10, 0xa9, 0x03, 0xa6, 0xd0, 0xab, 0x1c, 0x4c }; const expected_output = [32]u8{ 0xc3, 0xda, 0x55, 0x37, 0x9d, 0xe9, 0xc6, 0x90, 0x8e, 0x94, 0xea, 0x4d, 0xf2, 0x8d, 0x08, 0x4f, 0x32, 0xec, 0xcf, 0x03, 0x49, 0x1c, 0x71, 0xf7, 0x54, 0xb4, 0x07, 0x55, 0x77, 0xa2, 0x85, 0x52 }; var output: [32]u8 = undefined; std.testing.expect(X25519.create(output[0..], secret_key[0..], public_key[0..])); std.testing.expectEqual(output, expected_output); } test "x25519 rfc7748 vector2" { const secret_key = [32]u8{ 0x4b, 0x66, 0xe9, 0xd4, 0xd1, 0xb4, 0x67, 0x3c, 0x5a, 0xd2, 0x26, 0x91, 0x95, 0x7d, 0x6a, 0xf5, 0xc1, 0x1b, 0x64, 0x21, 0xe0, 0xea, 0x01, 0xd4, 0x2c, 0xa4, 0x16, 0x9e, 0x79, 0x18, 0xba, 0x0d }; const public_key = [32]u8{ 0xe5, 0x21, 0x0f, 0x12, 0x78, 0x68, 0x11, 0xd3, 0xf4, 0xb7, 0x95, 0x9d, 0x05, 0x38, 0xae, 0x2c, 0x31, 0xdb, 0xe7, 0x10, 0x6f, 0xc0, 0x3c, 0x3e, 0xfc, 0x4c, 0xd5, 0x49, 0xc7, 0x15, 0xa4, 0x93 }; const expected_output = [32]u8{ 0x95, 0xcb, 0xde, 0x94, 0x76, 0xe8, 0x90, 0x7d, 0x7a, 0xad, 0xe4, 0x5c, 0xb4, 0xb8, 0x73, 0xf8, 0x8b, 0x59, 0x5a, 0x68, 0x79, 0x9f, 0xa1, 0x52, 0xe6, 0xf8, 0xf7, 0x64, 0x7a, 0xac, 0x79, 0x57 }; var output: [32]u8 = undefined; std.testing.expect(X25519.create(output[0..], secret_key[0..], public_key[0..])); std.testing.expectEqual(output, expected_output); } test "x25519 rfc7748 one iteration" { const initial_value = [32]u8{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const expected_output = [32]u8{ 0x42, 0x2c, 0x8e, 0x7a, 0x62, 0x27, 0xd7, 0xbc, 0xa1, 0x35, 0x0b, 0x3e, 0x2b, 0xb7, 0x27, 0x9f, 0x78, 0x97, 0xb8, 0x7b, 0xb6, 0x85, 0x4b, 0x78, 0x3c, 0x60, 0xe8, 0x03, 0x11, 0xae, 0x30, 0x79 }; var k: [32]u8 = initial_value; var u: [32]u8 = initial_value; var i: usize = 0; while (i < 1) : (i += 1) { var output: [32]u8 = undefined; std.testing.expect(X25519.create(output[0..], &k, &u)); mem.copy(u8, u[0..], k[0..]); mem.copy(u8, k[0..], output[0..]); } std.testing.expectEqual(k, expected_output); } test "x25519 rfc7748 1,000 iterations" { // These iteration tests are slow so we always skip them. Results have been verified. if (true) { return error.SkipZigTest; } const initial_value = [32]u8{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const expected_output = [32]u8{ 0x68, 0x4c, 0xf5, 0x9b, 0xa8, 0x33, 0x09, 0x55, 0x28, 0x00, 0xef, 0x56, 0x6f, 0x2f, 0x4d, 0x3c, 0x1c, 0x38, 0x87, 0xc4, 0x93, 0x60, 0xe3, 0x87, 0x5f, 0x2e, 0xb9, 0x4d, 0x99, 0x53, 0x2c, 0x51 }; var k: [32]u8 = initial_value.*; var u: [32]u8 = initial_value.*; var i: usize = 0; while (i < 1000) : (i += 1) { var output: [32]u8 = undefined; std.testing.expect(X25519.create(output[0..], &k, &u)); mem.copy(u8, u[0..], k[0..]); mem.copy(u8, k[0..], output[0..]); } std.testing.expectEqual(k, expected_output); } test "x25519 rfc7748 1,000,000 iterations" { if (true) { return error.SkipZigTest; } const initial_value = [32]u8{ 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; const expected_output = [32]u8{ 0x7c, 0x39, 0x11, 0xe0, 0xab, 0x25, 0x86, 0xfd, 0x86, 0x44, 0x97, 0x29, 0x7e, 0x57, 0x5e, 0x6f, 0x3b, 0xc6, 0x01, 0xc0, 0x88, 0x3c, 0x30, 0xdf, 0x5f, 0x4d, 0xd2, 0xd2, 0x4f, 0x66, 0x54, 0x24 }; var k: [32]u8 = initial_value.*; var u: [32]u8 = initial_value.*; var i: usize = 0; while (i < 1000000) : (i += 1) { var output: [32]u8 = undefined; std.testing.expect(X25519.create(output[0..], &k, &u)); mem.copy(u8, u[0..], k[0..]); mem.copy(u8, k[0..], output[0..]); } std.testing.expectEqual(k[0..], expected_output); }
lib/std/crypto/25519/x25519.zig
const __fixtfdi = @import("fixtfdi.zig").__fixtfdi; const std = @import("std"); const math = std.math; const testing = std.testing; const warn = std.debug.warn; fn test__fixtfdi(a: f128, expected: i64) void { const x = __fixtfdi(a); //warn("a={}:{x} x={}:{x} expected={}:{x}:@as(u64, {x})\n", .{a, @bitCast(u128, a), x, x, expected, expected, @bitCast(u64, expected)}); testing.expect(x == expected); } test "fixtfdi" { //warn("\n", .{}); test__fixtfdi(-math.f128_max, math.minInt(i64)); test__fixtfdi(-0x1.FFFFFFFFFFFFFp+1023, math.minInt(i64)); test__fixtfdi(-0x1.FFFFFFFFFFFFFp+1023, -0x8000000000000000); test__fixtfdi(-0x1.0000000000000p+127, -0x8000000000000000); test__fixtfdi(-0x1.FFFFFFFFFFFFFp+126, -0x8000000000000000); test__fixtfdi(-0x1.FFFFFFFFFFFFEp+126, -0x8000000000000000); test__fixtfdi(-0x1.0000000000001p+63, -0x8000000000000000); test__fixtfdi(-0x1.0000000000000p+63, -0x8000000000000000); test__fixtfdi(-0x1.FFFFFFFFFFFFFp+62, -0x7FFFFFFFFFFFFC00); test__fixtfdi(-0x1.FFFFFFFFFFFFEp+62, -0x7FFFFFFFFFFFF800); test__fixtfdi(-0x1.FFFFFEp+62, -0x7FFFFF8000000000); test__fixtfdi(-0x1.FFFFFCp+62, -0x7FFFFF0000000000); test__fixtfdi(-0x1.000000p+31, -0x80000000); test__fixtfdi(-0x1.FFFFFFp+30, -0x7FFFFFC0); test__fixtfdi(-0x1.FFFFFEp+30, -0x7FFFFF80); test__fixtfdi(-0x1.FFFFFCp+30, -0x7FFFFF00); test__fixtfdi(-2.01, -2); test__fixtfdi(-2.0, -2); test__fixtfdi(-1.99, -1); test__fixtfdi(-1.0, -1); test__fixtfdi(-0.99, 0); test__fixtfdi(-0.5, 0); test__fixtfdi(-math.f64_min, 0); test__fixtfdi(0.0, 0); test__fixtfdi(math.f64_min, 0); test__fixtfdi(0.5, 0); test__fixtfdi(0.99, 0); test__fixtfdi(1.0, 1); test__fixtfdi(1.5, 1); test__fixtfdi(1.99, 1); test__fixtfdi(2.0, 2); test__fixtfdi(2.01, 2); test__fixtfdi(0x1.FFFFFCp+30, 0x7FFFFF00); test__fixtfdi(0x1.FFFFFEp+30, 0x7FFFFF80); test__fixtfdi(0x1.FFFFFFp+30, 0x7FFFFFC0); test__fixtfdi(0x1.000000p+31, 0x80000000); test__fixtfdi(0x1.FFFFFCp+62, 0x7FFFFF0000000000); test__fixtfdi(0x1.FFFFFEp+62, 0x7FFFFF8000000000); test__fixtfdi(0x1.FFFFFFFFFFFFEp+62, 0x7FFFFFFFFFFFF800); test__fixtfdi(0x1.FFFFFFFFFFFFFp+62, 0x7FFFFFFFFFFFFC00); test__fixtfdi(0x1.0000000000000p+63, 0x7FFFFFFFFFFFFFFF); test__fixtfdi(0x1.0000000000001p+63, 0x7FFFFFFFFFFFFFFF); test__fixtfdi(0x1.FFFFFFFFFFFFEp+126, 0x7FFFFFFFFFFFFFFF); test__fixtfdi(0x1.FFFFFFFFFFFFFp+126, 0x7FFFFFFFFFFFFFFF); test__fixtfdi(0x1.0000000000000p+127, 0x7FFFFFFFFFFFFFFF); test__fixtfdi(0x1.FFFFFFFFFFFFFp+1023, 0x7FFFFFFFFFFFFFFF); test__fixtfdi(0x1.FFFFFFFFFFFFFp+1023, math.maxInt(i64)); test__fixtfdi(math.f128_max, math.maxInt(i64)); }
lib/std/special/compiler_rt/fixtfdi_test.zig
pub const SUCCESS = 0; /// Incorrect function. pub const INVALID_FUNCTION = 1; /// The system cannot find the file specified. pub const FILE_NOT_FOUND = 2; /// The system cannot find the path specified. pub const PATH_NOT_FOUND = 3; /// The system cannot open the file. pub const TOO_MANY_OPEN_FILES = 4; /// Access is denied. pub const ACCESS_DENIED = 5; /// The handle is invalid. pub const INVALID_HANDLE = 6; /// The storage control blocks were destroyed. pub const ARENA_TRASHED = 7; /// Not enough storage is available to process this command. pub const NOT_ENOUGH_MEMORY = 8; /// The storage control block address is invalid. pub const INVALID_BLOCK = 9; /// The environment is incorrect. pub const BAD_ENVIRONMENT = 10; /// An attempt was made to load a program with an incorrect format. pub const BAD_FORMAT = 11; /// The access code is invalid. pub const INVALID_ACCESS = 12; /// The data is invalid. pub const INVALID_DATA = 13; /// Not enough storage is available to complete this operation. pub const OUTOFMEMORY = 14; /// The system cannot find the drive specified. pub const INVALID_DRIVE = 15; /// The directory cannot be removed. pub const CURRENT_DIRECTORY = 16; /// The system cannot move the file to a different disk drive. pub const NOT_SAME_DEVICE = 17; /// There are no more files. pub const NO_MORE_FILES = 18; /// The media is write protected. pub const WRITE_PROTECT = 19; /// The system cannot find the device specified. pub const BAD_UNIT = 20; /// The device is not ready. pub const NOT_READY = 21; /// The device does not recognize the command. pub const BAD_COMMAND = 22; /// Data error (cyclic redundancy check). pub const CRC = 23; /// The program issued a command but the command length is incorrect. pub const BAD_LENGTH = 24; /// The drive cannot locate a specific area or track on the disk. pub const SEEK = 25; /// The specified disk or diskette cannot be accessed. pub const NOT_DOS_DISK = 26; /// The drive cannot find the sector requested. pub const SECTOR_NOT_FOUND = 27; /// The printer is out of paper. pub const OUT_OF_PAPER = 28; /// The system cannot write to the specified device. pub const WRITE_FAULT = 29; /// The system cannot read from the specified device. pub const READ_FAULT = 30; /// A device attached to the system is not functioning. pub const GEN_FAILURE = 31; /// The process cannot access the file because it is being used by another process. pub const SHARING_VIOLATION = 32; /// The process cannot access the file because another process has locked a portion of the file. pub const LOCK_VIOLATION = 33; /// The wrong diskette is in the drive. Insert %2 (Volume Serial Number: %3) into drive %1. pub const WRONG_DISK = 34; /// Too many files opened for sharing. pub const SHARING_BUFFER_EXCEEDED = 36; /// Reached the end of the file. pub const HANDLE_EOF = 38; /// The disk is full. pub const HANDLE_DISK_FULL = 39; /// The request is not supported. pub const NOT_SUPPORTED = 50; /// Windows cannot find the network path. Verify that the network path is correct and the destination computer is not busy or turned off. If Windows still cannot find the network path, contact your network administrator. pub const REM_NOT_LIST = 51; /// You were not connected because a duplicate name exists on the network. If joining a domain, go to System in Control Panel to change the computer name and try again. If joining a workgroup, choose another workgroup name. pub const DUP_NAME = 52; /// The network path was not found. pub const BAD_NETPATH = 53; /// The network is busy. pub const NETWORK_BUSY = 54; /// The specified network resource or device is no longer available. pub const DEV_NOT_EXIST = 55; /// The network BIOS command limit has been reached. pub const TOO_MANY_CMDS = 56; /// A network adapter hardware error occurred. pub const ADAP_HDW_ERR = 57; /// The specified server cannot perform the requested operation. pub const BAD_NET_RESP = 58; /// An unexpected network error occurred. pub const UNEXP_NET_ERR = 59; /// The remote adapter is not compatible. pub const BAD_REM_ADAP = 60; /// The printer queue is full. pub const PRINTQ_FULL = 61; /// Space to store the file waiting to be printed is not available on the server. pub const NO_SPOOL_SPACE = 62; /// Your file waiting to be printed was deleted. pub const PRINT_CANCELLED = 63; /// The specified network name is no longer available. pub const NETNAME_DELETED = 64; /// Network access is denied. pub const NETWORK_ACCESS_DENIED = 65; /// The network resource type is not correct. pub const BAD_DEV_TYPE = 66; /// The network name cannot be found. pub const BAD_NET_NAME = 67; /// The name limit for the local computer network adapter card was exceeded. pub const TOO_MANY_NAMES = 68; /// The network BIOS session limit was exceeded. pub const TOO_MANY_SESS = 69; /// The remote server has been paused or is in the process of being started. pub const SHARING_PAUSED = 70; /// No more connections can be made to this remote computer at this time because there are already as many connections as the computer can accept. pub const REQ_NOT_ACCEP = 71; /// The specified printer or disk device has been paused. pub const REDIR_PAUSED = 72; /// The file exists. pub const FILE_EXISTS = 80; /// The directory or file cannot be created. pub const CANNOT_MAKE = 82; /// Fail on INT 24. pub const FAIL_I24 = 83; /// Storage to process this request is not available. pub const OUT_OF_STRUCTURES = 84; /// The local device name is already in use. pub const ALREADY_ASSIGNED = 85; /// The specified network password is not correct. pub const INVALID_PASSWORD = 86; /// The parameter is incorrect. pub const INVALID_PARAMETER = 87; /// A write fault occurred on the network. pub const NET_WRITE_FAULT = 88; /// The system cannot start another process at this time. pub const NO_PROC_SLOTS = 89; /// Cannot create another system semaphore. pub const TOO_MANY_SEMAPHORES = 100; /// The exclusive semaphore is owned by another process. pub const EXCL_SEM_ALREADY_OWNED = 101; /// The semaphore is set and cannot be closed. pub const SEM_IS_SET = 102; /// The semaphore cannot be set again. pub const TOO_MANY_SEM_REQUESTS = 103; /// Cannot request exclusive semaphores at interrupt time. pub const INVALID_AT_INTERRUPT_TIME = 104; /// The previous ownership of this semaphore has ended. pub const SEM_OWNER_DIED = 105; /// Insert the diskette for drive %1. pub const SEM_USER_LIMIT = 106; /// The program stopped because an alternate diskette was not inserted. pub const DISK_CHANGE = 107; /// The disk is in use or locked by another process. pub const DRIVE_LOCKED = 108; /// The pipe has been ended. pub const BROKEN_PIPE = 109; /// The system cannot open the device or file specified. pub const OPEN_FAILED = 110; /// The file name is too long. pub const BUFFER_OVERFLOW = 111; /// There is not enough space on the disk. pub const DISK_FULL = 112; /// No more internal file identifiers available. pub const NO_MORE_SEARCH_HANDLES = 113; /// The target internal file identifier is incorrect. pub const INVALID_TARGET_HANDLE = 114; /// The IOCTL call made by the application program is not correct. pub const INVALID_CATEGORY = 117; /// The verify-on-write switch parameter value is not correct. pub const INVALID_VERIFY_SWITCH = 118; /// The system does not support the command requested. pub const BAD_DRIVER_LEVEL = 119; /// This function is not supported on this system. pub const CALL_NOT_IMPLEMENTED = 120; /// The semaphore timeout period has expired. pub const SEM_TIMEOUT = 121; /// The data area passed to a system call is too small. pub const INSUFFICIENT_BUFFER = 122; /// The filename, directory name, or volume label syntax is incorrect. pub const INVALID_NAME = 123; /// The system call level is not correct. pub const INVALID_LEVEL = 124; /// The disk has no volume label. pub const NO_VOLUME_LABEL = 125; /// The specified module could not be found. pub const MOD_NOT_FOUND = 126; /// The specified procedure could not be found. pub const PROC_NOT_FOUND = 127; /// There are no child processes to wait for. pub const WAIT_NO_CHILDREN = 128; /// The %1 application cannot be run in Win32 mode. pub const CHILD_NOT_COMPLETE = 129; /// Attempt to use a file handle to an open disk partition for an operation other than raw disk I/O. pub const DIRECT_ACCESS_HANDLE = 130; /// An attempt was made to move the file pointer before the beginning of the file. pub const NEGATIVE_SEEK = 131; /// The file pointer cannot be set on the specified device or file. pub const SEEK_ON_DEVICE = 132; /// A JOIN or SUBST command cannot be used for a drive that contains previously joined drives. pub const IS_JOIN_TARGET = 133; /// An attempt was made to use a JOIN or SUBST command on a drive that has already been joined. pub const IS_JOINED = 134; /// An attempt was made to use a JOIN or SUBST command on a drive that has already been substituted. pub const IS_SUBSTED = 135; /// The system tried to delete the JOIN of a drive that is not joined. pub const NOT_JOINED = 136; /// The system tried to delete the substitution of a drive that is not substituted. pub const NOT_SUBSTED = 137; /// The system tried to join a drive to a directory on a joined drive. pub const JOIN_TO_JOIN = 138; /// The system tried to substitute a drive to a directory on a substituted drive. pub const SUBST_TO_SUBST = 139; /// The system tried to join a drive to a directory on a substituted drive. pub const JOIN_TO_SUBST = 140; /// The system tried to SUBST a drive to a directory on a joined drive. pub const SUBST_TO_JOIN = 141; /// The system cannot perform a JOIN or SUBST at this time. pub const BUSY_DRIVE = 142; /// The system cannot join or substitute a drive to or for a directory on the same drive. pub const SAME_DRIVE = 143; /// The directory is not a subdirectory of the root directory. pub const DIR_NOT_ROOT = 144; /// The directory is not empty. pub const DIR_NOT_EMPTY = 145; /// The path specified is being used in a substitute. pub const IS_SUBST_PATH = 146; /// Not enough resources are available to process this command. pub const IS_JOIN_PATH = 147; /// The path specified cannot be used at this time. pub const PATH_BUSY = 148; /// An attempt was made to join or substitute a drive for which a directory on the drive is the target of a previous substitute. pub const IS_SUBST_TARGET = 149; /// System trace information was not specified in your CONFIG.SYS file, or tracing is disallowed. pub const SYSTEM_TRACE = 150; /// The number of specified semaphore events for DosMuxSemWait is not correct. pub const INVALID_EVENT_COUNT = 151; /// DosMuxSemWait did not execute; too many semaphores are already set. pub const TOO_MANY_MUXWAITERS = 152; /// The DosMuxSemWait list is not correct. pub const INVALID_LIST_FORMAT = 153; /// The volume label you entered exceeds the label character limit of the target file system. pub const LABEL_TOO_LONG = 154; /// Cannot create another thread. pub const TOO_MANY_TCBS = 155; /// The recipient process has refused the signal. pub const SIGNAL_REFUSED = 156; /// The segment is already discarded and cannot be locked. pub const DISCARDED = 157; /// The segment is already unlocked. pub const NOT_LOCKED = 158; /// The address for the thread ID is not correct. pub const BAD_THREADID_ADDR = 159; /// One or more arguments are not correct. pub const BAD_ARGUMENTS = 160; /// The specified path is invalid. pub const BAD_PATHNAME = 161; /// A signal is already pending. pub const SIGNAL_PENDING = 162; /// No more threads can be created in the system. pub const MAX_THRDS_REACHED = 164; /// Unable to lock a region of a file. pub const LOCK_FAILED = 167; /// The requested resource is in use. pub const BUSY = 170; /// Device's command support detection is in progress. pub const DEVICE_SUPPORT_IN_PROGRESS = 171; /// A lock request was not outstanding for the supplied cancel region. pub const CANCEL_VIOLATION = 173; /// The file system does not support atomic changes to the lock type. pub const ATOMIC_LOCKS_NOT_SUPPORTED = 174; /// The system detected a segment number that was not correct. pub const INVALID_SEGMENT_NUMBER = 180; /// The operating system cannot run %1. pub const INVALID_ORDINAL = 182; /// Cannot create a file when that file already exists. pub const ALREADY_EXISTS = 183; /// The flag passed is not correct. pub const INVALID_FLAG_NUMBER = 186; /// The specified system semaphore name was not found. pub const SEM_NOT_FOUND = 187; /// The operating system cannot run %1. pub const INVALID_STARTING_CODESEG = 188; /// The operating system cannot run %1. pub const INVALID_STACKSEG = 189; /// The operating system cannot run %1. pub const INVALID_MODULETYPE = 190; /// Cannot run %1 in Win32 mode. pub const INVALID_EXE_SIGNATURE = 191; /// The operating system cannot run %1. pub const EXE_MARKED_INVALID = 192; /// %1 is not a valid Win32 application. pub const BAD_EXE_FORMAT = 193; /// The operating system cannot run %1. pub const ITERATED_DATA_EXCEEDS_64k = 194; /// The operating system cannot run %1. pub const INVALID_MINALLOCSIZE = 195; /// The operating system cannot run this application program. pub const DYNLINK_FROM_INVALID_RING = 196; /// The operating system is not presently configured to run this application. pub const IOPL_NOT_ENABLED = 197; /// The operating system cannot run %1. pub const INVALID_SEGDPL = 198; /// The operating system cannot run this application program. pub const AUTODATASEG_EXCEEDS_64k = 199; /// The code segment cannot be greater than or equal to 64K. pub const RING2SEG_MUST_BE_MOVABLE = 200; /// The operating system cannot run %1. pub const RELOC_CHAIN_XEEDS_SEGLIM = 201; /// The operating system cannot run %1. pub const INFLOOP_IN_RELOC_CHAIN = 202; /// The system could not find the environment option that was entered. pub const ENVVAR_NOT_FOUND = 203; /// No process in the command subtree has a signal handler. pub const NO_SIGNAL_SENT = 205; /// The filename or extension is too long. pub const FILENAME_EXCED_RANGE = 206; /// The ring 2 stack is in use. pub const RING2_STACK_IN_USE = 207; /// The global filename characters, * or ?, are entered incorrectly or too many global filename characters are specified. pub const META_EXPANSION_TOO_LONG = 208; /// The signal being posted is not correct. pub const INVALID_SIGNAL_NUMBER = 209; /// The signal handler cannot be set. pub const THREAD_1_INACTIVE = 210; /// The segment is locked and cannot be reallocated. pub const LOCKED = 212; /// Too many dynamic-link modules are attached to this program or dynamic-link module. pub const TOO_MANY_MODULES = 214; /// Cannot nest calls to LoadModule. pub const NESTING_NOT_ALLOWED = 215; /// This version of %1 is not compatible with the version of Windows you're running. Check your computer's system information and then contact the software publisher. pub const EXE_MACHINE_TYPE_MISMATCH = 216; /// The image file %1 is signed, unable to modify. pub const EXE_CANNOT_MODIFY_SIGNED_BINARY = 217; /// The image file %1 is strong signed, unable to modify. pub const EXE_CANNOT_MODIFY_STRONG_SIGNED_BINARY = 218; /// This file is checked out or locked for editing by another user. pub const FILE_CHECKED_OUT = 220; /// The file must be checked out before saving changes. pub const CHECKOUT_REQUIRED = 221; /// The file type being saved or retrieved has been blocked. pub const BAD_FILE_TYPE = 222; /// The file size exceeds the limit allowed and cannot be saved. pub const FILE_TOO_LARGE = 223; /// Access Denied. Before opening files in this location, you must first add the web site to your trusted sites list, browse to the web site, and select the option to login automatically. pub const FORMS_AUTH_REQUIRED = 224; /// Operation did not complete successfully because the file contains a virus or potentially unwanted software. pub const VIRUS_INFECTED = 225; /// This file contains a virus or potentially unwanted software and cannot be opened. Due to the nature of this virus or potentially unwanted software, the file has been removed from this location. pub const VIRUS_DELETED = 226; /// The pipe is local. pub const PIPE_LOCAL = 229; /// The pipe state is invalid. pub const BAD_PIPE = 230; /// All pipe instances are busy. pub const PIPE_BUSY = 231; /// The pipe is being closed. pub const NO_DATA = 232; /// No process is on the other end of the pipe. pub const PIPE_NOT_CONNECTED = 233; /// More data is available. pub const MORE_DATA = 234; /// The session was canceled. pub const VC_DISCONNECTED = 240; /// The specified extended attribute name was invalid. pub const INVALID_EA_NAME = 254; /// The extended attributes are inconsistent. pub const EA_LIST_INCONSISTENT = 255; /// The wait operation timed out. pub const IMEOUT = 258; /// No more data is available. pub const NO_MORE_ITEMS = 259; /// The copy functions cannot be used. pub const CANNOT_COPY = 266; /// The directory name is invalid. pub const DIRECTORY = 267; /// The extended attributes did not fit in the buffer. pub const EAS_DIDNT_FIT = 275; /// The extended attribute file on the mounted file system is corrupt. pub const EA_FILE_CORRUPT = 276; /// The extended attribute table file is full. pub const EA_TABLE_FULL = 277; /// The specified extended attribute handle is invalid. pub const INVALID_EA_HANDLE = 278; /// The mounted file system does not support extended attributes. pub const EAS_NOT_SUPPORTED = 282; /// Attempt to release mutex not owned by caller. pub const NOT_OWNER = 288; /// Too many posts were made to a semaphore. pub const TOO_MANY_POSTS = 298; /// Only part of a ReadProcessMemory or WriteProcessMemory request was completed. pub const PARTIAL_COPY = 299; /// The oplock request is denied. pub const OPLOCK_NOT_GRANTED = 300; /// An invalid oplock acknowledgment was received by the system. pub const INVALID_OPLOCK_PROTOCOL = 301; /// The volume is too fragmented to complete this operation. pub const DISK_TOO_FRAGMENTED = 302; /// The file cannot be opened because it is in the process of being deleted. pub const DELETE_PENDING = 303; /// Short name settings may not be changed on this volume due to the global registry setting. pub const INCOMPATIBLE_WITH_GLOBAL_SHORT_NAME_REGISTRY_SETTING = 304; /// Short names are not enabled on this volume. pub const SHORT_NAMES_NOT_ENABLED_ON_VOLUME = 305; /// The security stream for the given volume is in an inconsistent state. Please run CHKDSK on the volume. pub const SECURITY_STREAM_IS_INCONSISTENT = 306; /// A requested file lock operation cannot be processed due to an invalid byte range. pub const INVALID_LOCK_RANGE = 307; /// The subsystem needed to support the image type is not present. pub const IMAGE_SUBSYSTEM_NOT_PRESENT = 308; /// The specified file already has a notification GUID associated with it. pub const NOTIFICATION_GUID_ALREADY_DEFINED = 309; /// An invalid exception handler routine has been detected. pub const INVALID_EXCEPTION_HANDLER = 310; /// Duplicate privileges were specified for the token. pub const DUPLICATE_PRIVILEGES = 311; /// No ranges for the specified operation were able to be processed. pub const NO_RANGES_PROCESSED = 312; /// Operation is not allowed on a file system internal file. pub const NOT_ALLOWED_ON_SYSTEM_FILE = 313; /// The physical resources of this disk have been exhausted. pub const DISK_RESOURCES_EXHAUSTED = 314; /// The token representing the data is invalid. pub const INVALID_TOKEN = 315; /// The device does not support the command feature. pub const DEVICE_FEATURE_NOT_SUPPORTED = 316; /// The system cannot find message text for message number 0x%1 in the message file for %2. pub const MR_MID_NOT_FOUND = 317; /// The scope specified was not found. pub const SCOPE_NOT_FOUND = 318; /// The Central Access Policy specified is not defined on the target machine. pub const UNDEFINED_SCOPE = 319; /// The Central Access Policy obtained from Active Directory is invalid. pub const INVALID_CAP = 320; /// The device is unreachable. pub const DEVICE_UNREACHABLE = 321; /// The target device has insufficient resources to complete the operation. pub const DEVICE_NO_RESOURCES = 322; /// A data integrity checksum error occurred. Data in the file stream is corrupt. pub const DATA_CHECKSUM_ERROR = 323; /// An attempt was made to modify both a KERNEL and normal Extended Attribute (EA) in the same operation. pub const INTERMIXED_KERNEL_EA_OPERATION = 324; /// Device does not support file-level TRIM. pub const FILE_LEVEL_TRIM_NOT_SUPPORTED = 326; /// The command specified a data offset that does not align to the device's granularity/alignment. pub const OFFSET_ALIGNMENT_VIOLATION = 327; /// The command specified an invalid field in its parameter list. pub const INVALID_FIELD_IN_PARAMETER_LIST = 328; /// An operation is currently in progress with the device. pub const OPERATION_IN_PROGRESS = 329; /// An attempt was made to send down the command via an invalid path to the target device. pub const BAD_DEVICE_PATH = 330; /// The command specified a number of descriptors that exceeded the maximum supported by the device. pub const TOO_MANY_DESCRIPTORS = 331; /// Scrub is disabled on the specified file. pub const SCRUB_DATA_DISABLED = 332; /// The storage device does not provide redundancy. pub const NOT_REDUNDANT_STORAGE = 333; /// An operation is not supported on a resident file. pub const RESIDENT_FILE_NOT_SUPPORTED = 334; /// An operation is not supported on a compressed file. pub const COMPRESSED_FILE_NOT_SUPPORTED = 335; /// An operation is not supported on a directory. pub const DIRECTORY_NOT_SUPPORTED = 336; /// The specified copy of the requested data could not be read. pub const NOT_READ_FROM_COPY = 337; /// No action was taken as a system reboot is required. pub const FAIL_NOACTION_REBOOT = 350; /// The shutdown operation failed. pub const FAIL_SHUTDOWN = 351; /// The restart operation failed. pub const FAIL_RESTART = 352; /// The maximum number of sessions has been reached. pub const MAX_SESSIONS_REACHED = 353; /// The thread is already in background processing mode. pub const THREAD_MODE_ALREADY_BACKGROUND = 400; /// The thread is not in background processing mode. pub const THREAD_MODE_NOT_BACKGROUND = 401; /// The process is already in background processing mode. pub const PROCESS_MODE_ALREADY_BACKGROUND = 402; /// The process is not in background processing mode. pub const PROCESS_MODE_NOT_BACKGROUND = 403; /// Attempt to access invalid address. pub const INVALID_ADDRESS = 487; /// User profile cannot be loaded. pub const USER_PROFILE_LOAD = 500; /// Arithmetic result exceeded 32 bits. pub const ARITHMETIC_OVERFLOW = 534; /// There is a process on other end of the pipe. pub const PIPE_CONNECTED = 535; /// Waiting for a process to open the other end of the pipe. pub const PIPE_LISTENING = 536; /// Application verifier has found an error in the current process. pub const VERIFIER_STOP = 537; /// An error occurred in the ABIOS subsystem. pub const ABIOS_ERROR = 538; /// A warning occurred in the WX86 subsystem. pub const WX86_WARNING = 539; /// An error occurred in the WX86 subsystem. pub const WX86_ERROR = 540; /// An attempt was made to cancel or set a timer that has an associated APC and the subject thread is not the thread that originally set the timer with an associated APC routine. pub const TIMER_NOT_CANCELED = 541; /// Unwind exception code. pub const UNWIND = 542; /// An invalid or unaligned stack was encountered during an unwind operation. pub const BAD_STACK = 543; /// An invalid unwind target was encountered during an unwind operation. pub const INVALID_UNWIND_TARGET = 544; /// Invalid Object Attributes specified to NtCreatePort or invalid Port Attributes specified to NtConnectPort pub const INVALID_PORT_ATTRIBUTES = 545; /// Length of message passed to NtRequestPort or NtRequestWaitReplyPort was longer than the maximum message allowed by the port. pub const PORT_MESSAGE_TOO_LONG = 546; /// An attempt was made to lower a quota limit below the current usage. pub const INVALID_QUOTA_LOWER = 547; /// An attempt was made to attach to a device that was already attached to another device. pub const DEVICE_ALREADY_ATTACHED = 548; /// An attempt was made to execute an instruction at an unaligned address and the host system does not support unaligned instruction references. pub const INSTRUCTION_MISALIGNMENT = 549; /// Profiling not started. pub const PROFILING_NOT_STARTED = 550; /// Profiling not stopped. pub const PROFILING_NOT_STOPPED = 551; /// The passed ACL did not contain the minimum required information. pub const COULD_NOT_INTERPRET = 552; /// The number of active profiling objects is at the maximum and no more may be started. pub const PROFILING_AT_LIMIT = 553; /// Used to indicate that an operation cannot continue without blocking for I/O. pub const CANT_WAIT = 554; /// Indicates that a thread attempted to terminate itself by default (called NtTerminateThread with NULL) and it was the last thread in the current process. pub const CANT_TERMINATE_SELF = 555; /// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception. pub const UNEXPECTED_MM_CREATE_ERR = 556; /// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception. pub const UNEXPECTED_MM_MAP_ERROR = 557; /// If an MM error is returned which is not defined in the standard FsRtl filter, it is converted to one of the following errors which is guaranteed to be in the filter. In this case information is lost, however, the filter correctly handles the exception. pub const UNEXPECTED_MM_EXTEND_ERR = 558; /// A malformed function table was encountered during an unwind operation. pub const BAD_FUNCTION_TABLE = 559; /// Indicates that an attempt was made to assign protection to a file system file or directory and one of the SIDs in the security descriptor could not be translated into a GUID that could be stored by the file system. This causes the protection attempt to fail, which may cause a file creation attempt to fail. pub const NO_GUID_TRANSLATION = 560; /// Indicates that an attempt was made to grow an LDT by setting its size, or that the size was not an even number of selectors. pub const INVALID_LDT_SIZE = 561; /// Indicates that the starting value for the LDT information was not an integral multiple of the selector size. pub const INVALID_LDT_OFFSET = 563; /// Indicates that the user supplied an invalid descriptor when trying to set up Ldt descriptors. pub const INVALID_LDT_DESCRIPTOR = 564; /// Indicates a process has too many threads to perform the requested action. For example, assignment of a primary token may only be performed when a process has zero or one threads. pub const TOO_MANY_THREADS = 565; /// An attempt was made to operate on a thread within a specific process, but the thread specified is not in the process specified. pub const THREAD_NOT_IN_PROCESS = 566; /// Page file quota was exceeded. pub const PAGEFILE_QUOTA_EXCEEDED = 567; /// The Netlogon service cannot start because another Netlogon service running in the domain conflicts with the specified role. pub const LOGON_SERVER_CONFLICT = 568; /// The SAM database on a Windows Server is significantly out of synchronization with the copy on the Domain Controller. A complete synchronization is required. pub const SYNCHRONIZATION_REQUIRED = 569; /// The NtCreateFile API failed. This error should never be returned to an application, it is a place holder for the Windows Lan Manager Redirector to use in its internal error mapping routines. pub const NET_OPEN_FAILED = 570; /// {Privilege Failed} The I/O permissions for the process could not be changed. pub const IO_PRIVILEGE_FAILED = 571; /// {Application Exit by CTRL+C} The application terminated as a result of a CTRL+C. pub const CONTROL_C_EXIT = 572; /// {Missing System File} The required system file %hs is bad or missing. pub const MISSING_SYSTEMFILE = 573; /// {Application Error} The exception %s (0x%08lx) occurred in the application at location 0x%08lx. pub const UNHANDLED_EXCEPTION = 574; /// {Application Error} The application was unable to start correctly (0x%lx). Click OK to close the application. pub const APP_INIT_FAILURE = 575; /// {Unable to Create Paging File} The creation of the paging file %hs failed (%lx). The requested size was %ld. pub const PAGEFILE_CREATE_FAILED = 576; /// Windows cannot verify the digital signature for this file. A recent hardware or software change might have installed a file that is signed incorrectly or damaged, or that might be malicious software from an unknown source. pub const INVALID_IMAGE_HASH = 577; /// {No Paging File Specified} No paging file was specified in the system configuration. pub const NO_PAGEFILE = 578; /// {EXCEPTION} A real-mode application issued a floating-point instruction and floating-point hardware is not present. pub const ILLEGAL_FLOAT_CONTEXT = 579; /// An event pair synchronization operation was performed using the thread specific client/server event pair object, but no event pair object was associated with the thread. pub const NO_EVENT_PAIR = 580; /// A Windows Server has an incorrect configuration. pub const DOMAIN_CTRLR_CONFIG_ERROR = 581; /// An illegal character was encountered. For a multi-byte character set this includes a lead byte without a succeeding trail byte. For the Unicode character set this includes the characters 0xFFFF and 0xFFFE. pub const ILLEGAL_CHARACTER = 582; /// The Unicode character is not defined in the Unicode character set installed on the system. pub const UNDEFINED_CHARACTER = 583; /// The paging file cannot be created on a floppy diskette. pub const FLOPPY_VOLUME = 584; /// The system BIOS failed to connect a system interrupt to the device or bus for which the device is connected. pub const BIOS_FAILED_TO_CONNECT_INTERRUPT = 585; /// This operation is only allowed for the Primary Domain Controller of the domain. pub const BACKUP_CONTROLLER = 586; /// An attempt was made to acquire a mutant such that its maximum count would have been exceeded. pub const MUTANT_LIMIT_EXCEEDED = 587; /// A volume has been accessed for which a file system driver is required that has not yet been loaded. pub const FS_DRIVER_REQUIRED = 588; /// {Registry File Failure} The registry cannot load the hive (file): %hs or its log or alternate. It is corrupt, absent, or not writable. pub const CANNOT_LOAD_REGISTRY_FILE = 589; /// {Unexpected Failure in DebugActiveProcess} An unexpected failure occurred while processing a DebugActiveProcess API request. You may choose OK to terminate the process, or Cancel to ignore the error. pub const DEBUG_ATTACH_FAILED = 590; /// {Fatal System Error} The %hs system process terminated unexpectedly with a status of 0x%08x (0x%08x 0x%08x). The system has been shut down. pub const SYSTEM_PROCESS_TERMINATED = 591; /// {Data Not Accepted} The TDI client could not handle the data received during an indication. pub const DATA_NOT_ACCEPTED = 592; /// NTVDM encountered a hard error. pub const VDM_HARD_ERROR = 593; /// {Cancel Timeout} The driver %hs failed to complete a cancelled I/O request in the allotted time. pub const DRIVER_CANCEL_TIMEOUT = 594; /// {Reply Message Mismatch} An attempt was made to reply to an LPC message, but the thread specified by the client ID in the message was not waiting on that message. pub const REPLY_MESSAGE_MISMATCH = 595; /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs. The data has been lost. This error may be caused by a failure of your computer hardware or network connection. Please try to save this file elsewhere. pub const LOST_WRITEBEHIND_DATA = 596; /// The parameter(s) passed to the server in the client/server shared memory window were invalid. Too much data may have been put in the shared memory window. pub const CLIENT_SERVER_PARAMETERS_INVALID = 597; /// The stream is not a tiny stream. pub const NOT_TINY_STREAM = 598; /// The request must be handled by the stack overflow code. pub const STACK_OVERFLOW_READ = 599; /// Internal OFS status codes indicating how an allocation operation is handled. Either it is retried after the containing onode is moved or the extent stream is converted to a large stream. pub const CONVERT_TO_LARGE = 600; /// The attempt to find the object found an object matching by ID on the volume but it is out of the scope of the handle used for the operation. pub const FOUND_OUT_OF_SCOPE = 601; /// The bucket array must be grown. Retry transaction after doing so. pub const ALLOCATE_BUCKET = 602; /// The user/kernel marshalling buffer has overflowed. pub const MARSHALL_OVERFLOW = 603; /// The supplied variant structure contains invalid data. pub const INVALID_VARIANT = 604; /// The specified buffer contains ill-formed data. pub const BAD_COMPRESSION_BUFFER = 605; /// {Audit Failed} An attempt to generate a security audit failed. pub const AUDIT_FAILED = 606; /// The timer resolution was not previously set by the current process. pub const TIMER_RESOLUTION_NOT_SET = 607; /// There is insufficient account information to log you on. pub const INSUFFICIENT_LOGON_INFO = 608; /// {Invalid DLL Entrypoint} The dynamic link library %hs is not written correctly. The stack pointer has been left in an inconsistent state. The entrypoint should be declared as WINAPI or STDCALL. Select YES to fail the DLL load. Select NO to continue execution. Selecting NO may cause the application to operate incorrectly. pub const BAD_DLL_ENTRYPOINT = 609; /// {Invalid Service Callback Entrypoint} The %hs service is not written correctly. The stack pointer has been left in an inconsistent state. The callback entrypoint should be declared as WINAPI or STDCALL. Selecting OK will cause the service to continue operation. However, the service process may operate incorrectly. pub const BAD_SERVICE_ENTRYPOINT = 610; /// There is an IP address conflict with another system on the network. pub const IP_ADDRESS_CONFLICT1 = 611; /// There is an IP address conflict with another system on the network. pub const IP_ADDRESS_CONFLICT2 = 612; /// {Low On Registry Space} The system has reached the maximum size allowed for the system part of the registry. Additional storage requests will be ignored. pub const REGISTRY_QUOTA_LIMIT = 613; /// A callback return system service cannot be executed when no callback is active. pub const NO_CALLBACK_ACTIVE = 614; /// The password provided is too short to meet the policy of your user account. Please choose a longer password. pub const PWD_TOO_SHORT = 615; /// The policy of your user account does not allow you to change passwords too frequently. This is done to prevent users from changing back to a familiar, but potentially discovered, password. If you feel your password has been compromised then please contact your administrator immediately to have a new one assigned. pub const PWD_TOO_RECENT = 616; /// You have attempted to change your password to one that you have used in the past. The policy of your user account does not allow this. Please select a password that you have not previously used. pub const PWD_HISTORY_CONFLICT = 617; /// The specified compression format is unsupported. pub const UNSUPPORTED_COMPRESSION = 618; /// The specified hardware profile configuration is invalid. pub const INVALID_HW_PROFILE = 619; /// The specified Plug and Play registry device path is invalid. pub const INVALID_PLUGPLAY_DEVICE_PATH = 620; /// The specified quota list is internally inconsistent with its descriptor. pub const QUOTA_LIST_INCONSISTENT = 621; /// {Windows Evaluation Notification} The evaluation period for this installation of Windows has expired. This system will shutdown in 1 hour. To restore access to this installation of Windows, please upgrade this installation using a licensed distribution of this product. pub const EVALUATION_EXPIRATION = 622; /// {Illegal System DLL Relocation} The system DLL %hs was relocated in memory. The application will not run properly. The relocation occurred because the DLL %hs occupied an address range reserved for Windows system DLLs. The vendor supplying the DLL should be contacted for a new DLL. pub const ILLEGAL_DLL_RELOCATION = 623; /// {DLL Initialization Failed} The application failed to initialize because the window station is shutting down. pub const DLL_INIT_FAILED_LOGOFF = 624; /// The validation process needs to continue on to the next step. pub const VALIDATE_CONTINUE = 625; /// There are no more matches for the current index enumeration. pub const NO_MORE_MATCHES = 626; /// The range could not be added to the range list because of a conflict. pub const RANGE_LIST_CONFLICT = 627; /// The server process is running under a SID different than that required by client. pub const SERVER_SID_MISMATCH = 628; /// A group marked use for deny only cannot be enabled. pub const CANT_ENABLE_DENY_ONLY = 629; /// {EXCEPTION} Multiple floating point faults. pub const FLOAT_MULTIPLE_FAULTS = 630; /// {EXCEPTION} Multiple floating point traps. pub const FLOAT_MULTIPLE_TRAPS = 631; /// The requested interface is not supported. pub const NOINTERFACE = 632; /// {System Standby Failed} The driver %hs does not support standby mode. Updating this driver may allow the system to go to standby mode. pub const DRIVER_FAILED_SLEEP = 633; /// The system file %1 has become corrupt and has been replaced. pub const CORRUPT_SYSTEM_FILE = 634; /// {Virtual Memory Minimum Too Low} Your system is low on virtual memory. Windows is increasing the size of your virtual memory paging file. During this process, memory requests for some applications may be denied. For more information, see Help. pub const COMMITMENT_MINIMUM = 635; /// A device was removed so enumeration must be restarted. pub const PNP_RESTART_ENUMERATION = 636; /// {Fatal System Error} The system image %s is not properly signed. The file has been replaced with the signed file. The system has been shut down. pub const SYSTEM_IMAGE_BAD_SIGNATURE = 637; /// Device will not start without a reboot. pub const PNP_REBOOT_REQUIRED = 638; /// There is not enough power to complete the requested operation. pub const INSUFFICIENT_POWER = 639; /// ERROR_MULTIPLE_FAULT_VIOLATION pub const MULTIPLE_FAULT_VIOLATION = 640; /// The system is in the process of shutting down. pub const SYSTEM_SHUTDOWN = 641; /// An attempt to remove a processes DebugPort was made, but a port was not already associated with the process. pub const PORT_NOT_SET = 642; /// This version of Windows is not compatible with the behavior version of directory forest, domain or domain controller. pub const DS_VERSION_CHECK_FAILURE = 643; /// The specified range could not be found in the range list. pub const RANGE_NOT_FOUND = 644; /// The driver was not loaded because the system is booting into safe mode. pub const NOT_SAFE_MODE_DRIVER = 646; /// The driver was not loaded because it failed its initialization call. pub const FAILED_DRIVER_ENTRY = 647; /// The "%hs" encountered an error while applying power or reading the device configuration. This may be caused by a failure of your hardware or by a poor connection. pub const DEVICE_ENUMERATION_ERROR = 648; /// The create operation failed because the name contained at least one mount point which resolves to a volume to which the specified device object is not attached. pub const MOUNT_POINT_NOT_RESOLVED = 649; /// The device object parameter is either not a valid device object or is not attached to the volume specified by the file name. pub const INVALID_DEVICE_OBJECT_PARAMETER = 650; /// A Machine Check Error has occurred. Please check the system eventlog for additional information. pub const MCA_OCCURED = 651; /// There was error [%2] processing the driver database. pub const DRIVER_DATABASE_ERROR = 652; /// System hive size has exceeded its limit. pub const SYSTEM_HIVE_TOO_LARGE = 653; /// The driver could not be loaded because a previous version of the driver is still in memory. pub const DRIVER_FAILED_PRIOR_UNLOAD = 654; /// {Volume Shadow Copy Service} Please wait while the Volume Shadow Copy Service prepares volume %hs for hibernation. pub const VOLSNAP_PREPARE_HIBERNATE = 655; /// The system has failed to hibernate (The error code is %hs). Hibernation will be disabled until the system is restarted. pub const HIBERNATION_FAILURE = 656; /// The password provided is too long to meet the policy of your user account. Please choose a shorter password. pub const PWD_TOO_LONG = 657; /// The requested operation could not be completed due to a file system limitation. pub const FILE_SYSTEM_LIMITATION = 665; /// An assertion failure has occurred. pub const ASSERTION_FAILURE = 668; /// An error occurred in the ACPI subsystem. pub const ACPI_ERROR = 669; /// WOW Assertion Error. pub const WOW_ASSERTION = 670; /// A device is missing in the system BIOS MPS table. This device will not be used. Please contact your system vendor for system BIOS update. pub const PNP_BAD_MPS_TABLE = 671; /// A translator failed to translate resources. pub const PNP_TRANSLATION_FAILED = 672; /// A IRQ translator failed to translate resources. pub const PNP_IRQ_TRANSLATION_FAILED = 673; /// Driver %2 returned invalid ID for a child device (%3). pub const PNP_INVALID_ID = 674; /// {Kernel Debugger Awakened} the system debugger was awakened by an interrupt. pub const WAKE_SYSTEM_DEBUGGER = 675; /// {Handles Closed} Handles to objects have been automatically closed as a result of the requested operation. pub const HANDLES_CLOSED = 676; /// {Too Much Information} The specified access control list (ACL) contained more information than was expected. pub const EXTRANEOUS_INFORMATION = 677; /// This warning level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has NOT been completed, but has not been rolled back either (so it may still be committed if desired). pub const RXACT_COMMIT_NECESSARY = 678; /// {Media Changed} The media may have changed. pub const MEDIA_CHECK = 679; /// {GUID Substitution} During the translation of a global identifier (GUID) to a Windows security ID (SID), no administratively-defined GUID prefix was found. A substitute prefix was used, which will not compromise system security. However, this may provide a more restrictive access than intended. pub const GUID_SUBSTITUTION_MADE = 680; /// The create operation stopped after reaching a symbolic link. pub const STOPPED_ON_SYMLINK = 681; /// A long jump has been executed. pub const LONGJUMP = 682; /// The Plug and Play query operation was not successful. pub const PLUGPLAY_QUERY_VETOED = 683; /// A frame consolidation has been executed. pub const UNWIND_CONSOLIDATE = 684; /// {Registry Hive Recovered} Registry hive (file): %hs was corrupted and it has been recovered. Some data might have been lost. pub const REGISTRY_HIVE_RECOVERED = 685; /// The application is attempting to run executable code from the module %hs. This may be insecure. An alternative, %hs, is available. Should the application use the secure module %hs? pub const DLL_MIGHT_BE_INSECURE = 686; /// The application is loading executable code from the module %hs. This is secure, but may be incompatible with previous releases of the operating system. An alternative, %hs, is available. Should the application use the secure module %hs? pub const DLL_MIGHT_BE_INCOMPATIBLE = 687; /// Debugger did not handle the exception. pub const DBG_EXCEPTION_NOT_HANDLED = 688; /// Debugger will reply later. pub const DBG_REPLY_LATER = 689; /// Debugger cannot provide handle. pub const DBG_UNABLE_TO_PROVIDE_HANDLE = 690; /// Debugger terminated thread. pub const DBG_TERMINATE_THREAD = 691; /// Debugger terminated process. pub const DBG_TERMINATE_PROCESS = 692; /// Debugger got control C. pub const DBG_CONTROL_C = 693; /// Debugger printed exception on control C. pub const DBG_PRINTEXCEPTION_C = 694; /// Debugger received RIP exception. pub const DBG_RIPEXCEPTION = 695; /// Debugger received control break. pub const DBG_CONTROL_BREAK = 696; /// Debugger command communication exception. pub const DBG_COMMAND_EXCEPTION = 697; /// {Object Exists} An attempt was made to create an object and the object name already existed. pub const OBJECT_NAME_EXISTS = 698; /// {Thread Suspended} A thread termination occurred while the thread was suspended. The thread was resumed, and termination proceeded. pub const THREAD_WAS_SUSPENDED = 699; /// {Image Relocated} An image file could not be mapped at the address specified in the image file. Local fixups must be performed on this image. pub const IMAGE_NOT_AT_BASE = 700; /// This informational level status indicates that a specified registry sub-tree transaction state did not yet exist and had to be created. pub const RXACT_STATE_CREATED = 701; /// {Segment Load} A virtual DOS machine (VDM) is loading, unloading, or moving an MS-DOS or Win16 program segment image. An exception is raised so a debugger can load, unload or track symbols and breakpoints within these 16-bit segments. pub const SEGMENT_NOTIFICATION = 702; /// {Invalid Current Directory} The process cannot switch to the startup current directory %hs. Select OK to set current directory to %hs, or select CANCEL to exit. pub const BAD_CURRENT_DIRECTORY = 703; /// {Redundant Read} To satisfy a read request, the NT fault-tolerant file system successfully read the requested data from a redundant copy. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was unable to reassign the failing area of the device. pub const FT_READ_RECOVERY_FROM_BACKUP = 704; /// {Redundant Write} To satisfy a write request, the NT fault-tolerant file system successfully wrote a redundant copy of the information. This was done because the file system encountered a failure on a member of the fault-tolerant volume, but was not able to reassign the failing area of the device. pub const FT_WRITE_RECOVERY = 705; /// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. Select OK to continue, or CANCEL to fail the DLL load. pub const IMAGE_MACHINE_TYPE_MISMATCH = 706; /// {Partial Data Received} The network transport returned partial data to its client. The remaining data will be sent later. pub const RECEIVE_PARTIAL = 707; /// {Expedited Data Received} The network transport returned data to its client that was marked as expedited by the remote system. pub const RECEIVE_EXPEDITED = 708; /// {Partial Expedited Data Received} The network transport returned partial data to its client and this data was marked as expedited by the remote system. The remaining data will be sent later. pub const RECEIVE_PARTIAL_EXPEDITED = 709; /// {TDI Event Done} The TDI indication has completed successfully. pub const EVENT_DONE = 710; /// {TDI Event Pending} The TDI indication has entered the pending state. pub const EVENT_PENDING = 711; /// Checking file system on %wZ. pub const CHECKING_FILE_SYSTEM = 712; /// {Fatal Application Exit} %hs. pub const FATAL_APP_EXIT = 713; /// The specified registry key is referenced by a predefined handle. pub const PREDEFINED_HANDLE = 714; /// {Page Unlocked} The page protection of a locked page was changed to 'No Access' and the page was unlocked from memory and from the process. pub const WAS_UNLOCKED = 715; /// %hs pub const SERVICE_NOTIFICATION = 716; /// {Page Locked} One of the pages to lock was already locked. pub const WAS_LOCKED = 717; /// Application popup: %1 : %2 pub const LOG_HARD_ERROR = 718; /// ERROR_ALREADY_WIN32 pub const ALREADY_WIN32 = 719; /// {Machine Type Mismatch} The image file %hs is valid, but is for a machine type other than the current machine. pub const IMAGE_MACHINE_TYPE_MISMATCH_EXE = 720; /// A yield execution was performed and no thread was available to run. pub const NO_YIELD_PERFORMED = 721; /// The resumable flag to a timer API was ignored. pub const TIMER_RESUME_IGNORED = 722; /// The arbiter has deferred arbitration of these resources to its parent. pub const ARBITRATION_UNHANDLED = 723; /// The inserted CardBus device cannot be started because of a configuration error on "%hs". pub const CARDBUS_NOT_SUPPORTED = 724; /// The CPUs in this multiprocessor system are not all the same revision level. To use all processors the operating system restricts itself to the features of the least capable processor in the system. Should problems occur with this system, contact the CPU manufacturer to see if this mix of processors is supported. pub const MP_PROCESSOR_MISMATCH = 725; /// The system was put into hibernation. pub const HIBERNATED = 726; /// The system was resumed from hibernation. pub const RESUME_HIBERNATION = 727; /// Windows has detected that the system firmware (BIOS) was updated [previous firmware date = %2, current firmware date %3]. pub const FIRMWARE_UPDATED = 728; /// A device driver is leaking locked I/O pages causing system degradation. The system has automatically enabled tracking code in order to try and catch the culprit. pub const DRIVERS_LEAKING_LOCKED_PAGES = 729; /// The system has awoken. pub const WAKE_SYSTEM = 730; /// ERROR_WAIT_1 pub const WAIT_1 = 731; /// ERROR_WAIT_2 pub const WAIT_2 = 732; /// ERROR_WAIT_3 pub const WAIT_3 = 733; /// ERROR_WAIT_63 pub const WAIT_63 = 734; /// ERROR_ABANDONED_WAIT_0 pub const ABANDONED_WAIT_0 = 735; /// ERROR_ABANDONED_WAIT_63 pub const ABANDONED_WAIT_63 = 736; /// ERROR_USER_APC pub const USER_APC = 737; /// ERROR_KERNEL_APC pub const KERNEL_APC = 738; /// ERROR_ALERTED pub const ALERTED = 739; /// The requested operation requires elevation. pub const ELEVATION_REQUIRED = 740; /// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link. pub const REPARSE = 741; /// An open/create operation completed while an oplock break is underway. pub const OPLOCK_BREAK_IN_PROGRESS = 742; /// A new volume has been mounted by a file system. pub const VOLUME_MOUNTED = 743; /// This success level status indicates that the transaction state already exists for the registry sub-tree, but that a transaction commit was previously aborted. The commit has now been completed. pub const RXACT_COMMITTED = 744; /// This indicates that a notify change request has been completed due to closing the handle which made the notify change request. pub const NOTIFY_CLEANUP = 745; /// {Connect Failure on Primary Transport} An attempt was made to connect to the remote server %hs on the primary transport, but the connection failed. The computer WAS able to connect on a secondary transport. pub const PRIMARY_TRANSPORT_CONNECT_FAILED = 746; /// Page fault was a transition fault. pub const PAGE_FAULT_TRANSITION = 747; /// Page fault was a demand zero fault. pub const PAGE_FAULT_DEMAND_ZERO = 748; /// Page fault was a demand zero fault. pub const PAGE_FAULT_COPY_ON_WRITE = 749; /// Page fault was a demand zero fault. pub const PAGE_FAULT_GUARD_PAGE = 750; /// Page fault was satisfied by reading from a secondary storage device. pub const PAGE_FAULT_PAGING_FILE = 751; /// Cached page was locked during operation. pub const CACHE_PAGE_LOCKED = 752; /// Crash dump exists in paging file. pub const CRASH_DUMP = 753; /// Specified buffer contains all zeros. pub const BUFFER_ALL_ZEROS = 754; /// A reparse should be performed by the Object Manager since the name of the file resulted in a symbolic link. pub const REPARSE_OBJECT = 755; /// The device has succeeded a query-stop and its resource requirements have changed. pub const RESOURCE_REQUIREMENTS_CHANGED = 756; /// The translator has translated these resources into the global space and no further translations should be performed. pub const TRANSLATION_COMPLETE = 757; /// A process being terminated has no threads to terminate. pub const NOTHING_TO_TERMINATE = 758; /// The specified process is not part of a job. pub const PROCESS_NOT_IN_JOB = 759; /// The specified process is part of a job. pub const PROCESS_IN_JOB = 760; /// {Volume Shadow Copy Service} The system is now ready for hibernation. pub const VOLSNAP_HIBERNATE_READY = 761; /// A file system or file system filter driver has successfully completed an FsFilter operation. pub const FSFILTER_OP_COMPLETED_SUCCESSFULLY = 762; /// The specified interrupt vector was already connected. pub const INTERRUPT_VECTOR_ALREADY_CONNECTED = 763; /// The specified interrupt vector is still connected. pub const INTERRUPT_STILL_CONNECTED = 764; /// An operation is blocked waiting for an oplock. pub const WAIT_FOR_OPLOCK = 765; /// Debugger handled exception. pub const DBG_EXCEPTION_HANDLED = 766; /// Debugger continued. pub const DBG_CONTINUE = 767; /// An exception occurred in a user mode callback and the kernel callback frame should be removed. pub const CALLBACK_POP_STACK = 768; /// Compression is disabled for this volume. pub const COMPRESSION_DISABLED = 769; /// The data provider cannot fetch backwards through a result set. pub const CANTFETCHBACKWARDS = 770; /// The data provider cannot scroll backwards through a result set. pub const CANTSCROLLBACKWARDS = 771; /// The data provider requires that previously fetched data is released before asking for more data. pub const ROWSNOTRELEASED = 772; /// The data provider was not able to interpret the flags set for a column binding in an accessor. pub const BAD_ACCESSOR_FLAGS = 773; /// One or more errors occurred while processing the request. pub const ERRORS_ENCOUNTERED = 774; /// The implementation is not capable of performing the request. pub const NOT_CAPABLE = 775; /// The client of a component requested an operation which is not valid given the state of the component instance. pub const REQUEST_OUT_OF_SEQUENCE = 776; /// A version number could not be parsed. pub const VERSION_PARSE_ERROR = 777; /// The iterator's start position is invalid. pub const BADSTARTPOSITION = 778; /// The hardware has reported an uncorrectable memory error. pub const MEMORY_HARDWARE = 779; /// The attempted operation required self healing to be enabled. pub const DISK_REPAIR_DISABLED = 780; /// The Desktop heap encountered an error while allocating session memory. There is more information in the system event log. pub const INSUFFICIENT_RESOURCE_FOR_SPECIFIED_SHARED_SECTION_SIZE = 781; /// The system power state is transitioning from %2 to %3. pub const SYSTEM_POWERSTATE_TRANSITION = 782; /// The system power state is transitioning from %2 to %3 but could enter %4. pub const SYSTEM_POWERSTATE_COMPLEX_TRANSITION = 783; /// A thread is getting dispatched with MCA EXCEPTION because of MCA. pub const MCA_EXCEPTION = 784; /// Access to %1 is monitored by policy rule %2. pub const ACCESS_AUDIT_BY_POLICY = 785; /// Access to %1 has been restricted by your Administrator by policy rule %2. pub const ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY = 786; /// A valid hibernation file has been invalidated and should be abandoned. pub const ABANDON_HIBERFILE = 787; /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused by network connectivity issues. Please try to save this file elsewhere. pub const LOST_WRITEBEHIND_DATA_NETWORK_DISCONNECTED = 788; /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error was returned by the server on which the file exists. Please try to save this file elsewhere. pub const LOST_WRITEBEHIND_DATA_NETWORK_SERVER_ERROR = 789; /// {Delayed Write Failed} Windows was unable to save all the data for the file %hs; the data has been lost. This error may be caused if the device has been removed or the media is write-protected. pub const LOST_WRITEBEHIND_DATA_LOCAL_DISK_ERROR = 790; /// The resources required for this device conflict with the MCFG table. pub const BAD_MCFG_TABLE = 791; /// The volume repair could not be performed while it is online. Please schedule to take the volume offline so that it can be repaired. pub const DISK_REPAIR_REDIRECTED = 792; /// The volume repair was not successful. pub const DISK_REPAIR_UNSUCCESSFUL = 793; /// One of the volume corruption logs is full. Further corruptions that may be detected won't be logged. pub const CORRUPT_LOG_OVERFULL = 794; /// One of the volume corruption logs is internally corrupted and needs to be recreated. The volume may contain undetected corruptions and must be scanned. pub const CORRUPT_LOG_CORRUPTED = 795; /// One of the volume corruption logs is unavailable for being operated on. pub const CORRUPT_LOG_UNAVAILABLE = 796; /// One of the volume corruption logs was deleted while still having corruption records in them. The volume contains detected corruptions and must be scanned. pub const CORRUPT_LOG_DELETED_FULL = 797; /// One of the volume corruption logs was cleared by chkdsk and no longer contains real corruptions. pub const CORRUPT_LOG_CLEARED = 798; /// Orphaned files exist on the volume but could not be recovered because no more new names could be created in the recovery directory. Files must be moved from the recovery directory. pub const ORPHAN_NAME_EXHAUSTED = 799; /// The oplock that was associated with this handle is now associated with a different handle. pub const OPLOCK_SWITCHED_TO_NEW_HANDLE = 800; /// An oplock of the requested level cannot be granted. An oplock of a lower level may be available. pub const CANNOT_GRANT_REQUESTED_OPLOCK = 801; /// The operation did not complete successfully because it would cause an oplock to be broken. The caller has requested that existing oplocks not be broken. pub const CANNOT_BREAK_OPLOCK = 802; /// The handle with which this oplock was associated has been closed. The oplock is now broken. pub const OPLOCK_HANDLE_CLOSED = 803; /// The specified access control entry (ACE) does not contain a condition. pub const NO_ACE_CONDITION = 804; /// The specified access control entry (ACE) contains an invalid condition. pub const INVALID_ACE_CONDITION = 805; /// Access to the specified file handle has been revoked. pub const FILE_HANDLE_REVOKED = 806; /// An image file was mapped at a different address from the one specified in the image file but fixups will still be automatically performed on the image. pub const IMAGE_AT_DIFFERENT_BASE = 807; /// Access to the extended attribute was denied. pub const EA_ACCESS_DENIED = 994; /// The I/O operation has been aborted because of either a thread exit or an application request. pub const OPERATION_ABORTED = 995; /// Overlapped I/O event is not in a signaled state. pub const IO_INCOMPLETE = 996; /// Overlapped I/O operation is in progress. pub const IO_PENDING = 997; /// Invalid access to memory location. pub const NOACCESS = 998; /// Error performing inpage operation. pub const SWAPERROR = 999; /// Recursion too deep; the stack overflowed. pub const STACK_OVERFLOW = 1001; /// The window cannot act on the sent message. pub const INVALID_MESSAGE = 1002; /// Cannot complete this function. pub const CAN_NOT_COMPLETE = 1003; /// Invalid flags. pub const INVALID_FLAGS = 1004; /// The volume does not contain a recognized file system. Please make sure that all required file system drivers are loaded and that the volume is not corrupted. pub const UNRECOGNIZED_VOLUME = 1005; /// The volume for a file has been externally altered so that the opened file is no longer valid. pub const FILE_INVALID = 1006; /// The requested operation cannot be performed in full-screen mode. pub const FULLSCREEN_MODE = 1007; /// An attempt was made to reference a token that does not exist. pub const NO_TOKEN = 1008; /// The configuration registry database is corrupt. pub const BADDB = 1009; /// The configuration registry key is invalid. pub const BADKEY = 1010; /// The configuration registry key could not be opened. pub const CANTOPEN = 1011; /// The configuration registry key could not be read. pub const CANTREAD = 1012; /// The configuration registry key could not be written. pub const CANTWRITE = 1013; /// One of the files in the registry database had to be recovered by use of a log or alternate copy. The recovery was successful. pub const REGISTRY_RECOVERED = 1014; /// The registry is corrupted. The structure of one of the files containing registry data is corrupted, or the system's memory image of the file is corrupted, or the file could not be recovered because the alternate copy or log was absent or corrupted. pub const REGISTRY_CORRUPT = 1015; /// An I/O operation initiated by the registry failed unrecoverably. The registry could not read in, or write out, or flush, one of the files that contain the system's image of the registry. pub const REGISTRY_IO_FAILED = 1016; /// The system has attempted to load or restore a file into the registry, but the specified file is not in a registry file format. pub const NOT_REGISTRY_FILE = 1017; /// Illegal operation attempted on a registry key that has been marked for deletion. pub const KEY_DELETED = 1018; /// System could not allocate the required space in a registry log. pub const NO_LOG_SPACE = 1019; /// Cannot create a symbolic link in a registry key that already has subkeys or values. pub const KEY_HAS_CHILDREN = 1020; /// Cannot create a stable subkey under a volatile parent key. pub const CHILD_MUST_BE_VOLATILE = 1021; /// A notify change request is being completed and the information is not being returned in the caller's buffer. The caller now needs to enumerate the files to find the changes. pub const NOTIFY_ENUM_DIR = 1022; /// A stop control has been sent to a service that other running services are dependent on. pub const DEPENDENT_SERVICES_RUNNING = 1051; /// The requested control is not valid for this service. pub const INVALID_SERVICE_CONTROL = 1052; /// The service did not respond to the start or control request in a timely fashion. pub const SERVICE_REQUEST_TIMEOUT = 1053; /// A thread could not be created for the service. pub const SERVICE_NO_THREAD = 1054; /// The service database is locked. pub const SERVICE_DATABASE_LOCKED = 1055; /// An instance of the service is already running. pub const SERVICE_ALREADY_RUNNING = 1056; /// The account name is invalid or does not exist, or the password is invalid for the account name specified. pub const INVALID_SERVICE_ACCOUNT = 1057; /// The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. pub const SERVICE_DISABLED = 1058; /// Circular service dependency was specified. pub const CIRCULAR_DEPENDENCY = 1059; /// The specified service does not exist as an installed service. pub const SERVICE_DOES_NOT_EXIST = 1060; /// The service cannot accept control messages at this time. pub const SERVICE_CANNOT_ACCEPT_CTRL = 1061; /// The service has not been started. pub const SERVICE_NOT_ACTIVE = 1062; /// The service process could not connect to the service controller. pub const FAILED_SERVICE_CONTROLLER_CONNECT = 1063; /// An exception occurred in the service when handling the control request. pub const EXCEPTION_IN_SERVICE = 1064; /// The database specified does not exist. pub const DATABASE_DOES_NOT_EXIST = 1065; /// The service has returned a service-specific error code. pub const SERVICE_SPECIFIC_ERROR = 1066; /// The process terminated unexpectedly. pub const PROCESS_ABORTED = 1067; /// The dependency service or group failed to start. pub const SERVICE_DEPENDENCY_FAIL = 1068; /// The service did not start due to a logon failure. pub const SERVICE_LOGON_FAILED = 1069; /// After starting, the service hung in a start-pending state. pub const SERVICE_START_HANG = 1070; /// The specified service database lock is invalid. pub const INVALID_SERVICE_LOCK = 1071; /// The specified service has been marked for deletion. pub const SERVICE_MARKED_FOR_DELETE = 1072; /// The specified service already exists. pub const SERVICE_EXISTS = 1073; /// The system is currently running with the last-known-good configuration. pub const ALREADY_RUNNING_LKG = 1074; /// The dependency service does not exist or has been marked for deletion. pub const SERVICE_DEPENDENCY_DELETED = 1075; /// The current boot has already been accepted for use as the last-known-good control set. pub const BOOT_ALREADY_ACCEPTED = 1076; /// No attempts to start the service have been made since the last boot. pub const SERVICE_NEVER_STARTED = 1077; /// The name is already in use as either a service name or a service display name. pub const DUPLICATE_SERVICE_NAME = 1078; /// The account specified for this service is different from the account specified for other services running in the same process. pub const DIFFERENT_SERVICE_ACCOUNT = 1079; /// Failure actions can only be set for Win32 services, not for drivers. pub const CANNOT_DETECT_DRIVER_FAILURE = 1080; /// This service runs in the same process as the service control manager. Therefore, the service control manager cannot take action if this service's process terminates unexpectedly. pub const CANNOT_DETECT_PROCESS_ABORT = 1081; /// No recovery program has been configured for this service. pub const NO_RECOVERY_PROGRAM = 1082; /// The executable program that this service is configured to run in does not implement the service. pub const SERVICE_NOT_IN_EXE = 1083; /// This service cannot be started in Safe Mode. pub const NOT_SAFEBOOT_SERVICE = 1084; /// The physical end of the tape has been reached. pub const END_OF_MEDIA = 1100; /// A tape access reached a filemark. pub const FILEMARK_DETECTED = 1101; /// The beginning of the tape or a partition was encountered. pub const BEGINNING_OF_MEDIA = 1102; /// A tape access reached the end of a set of files. pub const SETMARK_DETECTED = 1103; /// No more data is on the tape. pub const NO_DATA_DETECTED = 1104; /// Tape could not be partitioned. pub const PARTITION_FAILURE = 1105; /// When accessing a new tape of a multivolume partition, the current block size is incorrect. pub const INVALID_BLOCK_LENGTH = 1106; /// Tape partition information could not be found when loading a tape. pub const DEVICE_NOT_PARTITIONED = 1107; /// Unable to lock the media eject mechanism. pub const UNABLE_TO_LOCK_MEDIA = 1108; /// Unable to unload the media. pub const UNABLE_TO_UNLOAD_MEDIA = 1109; /// The media in the drive may have changed. pub const MEDIA_CHANGED = 1110; /// The I/O bus was reset. pub const BUS_RESET = 1111; /// No media in drive. pub const NO_MEDIA_IN_DRIVE = 1112; /// No mapping for the Unicode character exists in the target multi-byte code page. pub const NO_UNICODE_TRANSLATION = 1113; /// A dynamic link library (DLL) initialization routine failed. pub const DLL_INIT_FAILED = 1114; /// A system shutdown is in progress. pub const SHUTDOWN_IN_PROGRESS = 1115; /// Unable to abort the system shutdown because no shutdown was in progress. pub const NO_SHUTDOWN_IN_PROGRESS = 1116; /// The request could not be performed because of an I/O device error. pub const IO_DEVICE = 1117; /// No serial device was successfully initialized. The serial driver will unload. pub const SERIAL_NO_DEVICE = 1118; /// Unable to open a device that was sharing an interrupt request (IRQ) with other devices. At least one other device that uses that IRQ was already opened. pub const IRQ_BUSY = 1119; /// A serial I/O operation was completed by another write to the serial port. The IOCTL_SERIAL_XOFF_COUNTER reached zero.) pub const MORE_WRITES = 1120; /// A serial I/O operation completed because the timeout period expired. The IOCTL_SERIAL_XOFF_COUNTER did not reach zero.) pub const COUNTER_TIMEOUT = 1121; /// No ID address mark was found on the floppy disk. pub const FLOPPY_ID_MARK_NOT_FOUND = 1122; /// Mismatch between the floppy disk sector ID field and the floppy disk controller track address. pub const FLOPPY_WRONG_CYLINDER = 1123; /// The floppy disk controller reported an error that is not recognized by the floppy disk driver. pub const FLOPPY_UNKNOWN_ERROR = 1124; /// The floppy disk controller returned inconsistent results in its registers. pub const FLOPPY_BAD_REGISTERS = 1125; /// While accessing the hard disk, a recalibrate operation failed, even after retries. pub const DISK_RECALIBRATE_FAILED = 1126; /// While accessing the hard disk, a disk operation failed even after retries. pub const DISK_OPERATION_FAILED = 1127; /// While accessing the hard disk, a disk controller reset was needed, but even that failed. pub const DISK_RESET_FAILED = 1128; /// Physical end of tape encountered. pub const EOM_OVERFLOW = 1129; /// Not enough server storage is available to process this command. pub const NOT_ENOUGH_SERVER_MEMORY = 1130; /// A potential deadlock condition has been detected. pub const POSSIBLE_DEADLOCK = 1131; /// The base address or the file offset specified does not have the proper alignment. pub const MAPPED_ALIGNMENT = 1132; /// An attempt to change the system power state was vetoed by another application or driver. pub const SET_POWER_STATE_VETOED = 1140; /// The system BIOS failed an attempt to change the system power state. pub const SET_POWER_STATE_FAILED = 1141; /// An attempt was made to create more links on a file than the file system supports. pub const TOO_MANY_LINKS = 1142; /// The specified program requires a newer version of Windows. pub const OLD_WIN_VERSION = 1150; /// The specified program is not a Windows or MS-DOS program. pub const APP_WRONG_OS = 1151; /// Cannot start more than one instance of the specified program. pub const SINGLE_INSTANCE_APP = 1152; /// The specified program was written for an earlier version of Windows. pub const RMODE_APP = 1153; /// One of the library files needed to run this application is damaged. pub const INVALID_DLL = 1154; /// No application is associated with the specified file for this operation. pub const NO_ASSOCIATION = 1155; /// An error occurred in sending the command to the application. pub const DDE_FAIL = 1156; /// One of the library files needed to run this application cannot be found. pub const DLL_NOT_FOUND = 1157; /// The current process has used all of its system allowance of handles for Window Manager objects. pub const NO_MORE_USER_HANDLES = 1158; /// The message can be used only with synchronous operations. pub const MESSAGE_SYNC_ONLY = 1159; /// The indicated source element has no media. pub const SOURCE_ELEMENT_EMPTY = 1160; /// The indicated destination element already contains media. pub const DESTINATION_ELEMENT_FULL = 1161; /// The indicated element does not exist. pub const ILLEGAL_ELEMENT_ADDRESS = 1162; /// The indicated element is part of a magazine that is not present. pub const MAGAZINE_NOT_PRESENT = 1163; /// The indicated device requires reinitialization due to hardware errors. pub const DEVICE_REINITIALIZATION_NEEDED = 1164; /// The device has indicated that cleaning is required before further operations are attempted. pub const DEVICE_REQUIRES_CLEANING = 1165; /// The device has indicated that its door is open. pub const DEVICE_DOOR_OPEN = 1166; /// The device is not connected. pub const DEVICE_NOT_CONNECTED = 1167; /// Element not found. pub const NOT_FOUND = 1168; /// There was no match for the specified key in the index. pub const NO_MATCH = 1169; /// The property set specified does not exist on the object. pub const SET_NOT_FOUND = 1170; /// The point passed to GetMouseMovePoints is not in the buffer. pub const POINT_NOT_FOUND = 1171; /// The tracking (workstation) service is not running. pub const NO_TRACKING_SERVICE = 1172; /// The Volume ID could not be found. pub const NO_VOLUME_ID = 1173; /// Unable to remove the file to be replaced. pub const UNABLE_TO_REMOVE_REPLACED = 1175; /// Unable to move the replacement file to the file to be replaced. The file to be replaced has retained its original name. pub const UNABLE_TO_MOVE_REPLACEMENT = 1176; /// Unable to move the replacement file to the file to be replaced. The file to be replaced has been renamed using the backup name. pub const UNABLE_TO_MOVE_REPLACEMENT_2 = 1177; /// The volume change journal is being deleted. pub const JOURNAL_DELETE_IN_PROGRESS = 1178; /// The volume change journal is not active. pub const JOURNAL_NOT_ACTIVE = 1179; /// A file was found, but it may not be the correct file. pub const POTENTIAL_FILE_FOUND = 1180; /// The journal entry has been deleted from the journal. pub const JOURNAL_ENTRY_DELETED = 1181; /// A system shutdown has already been scheduled. pub const SHUTDOWN_IS_SCHEDULED = 1190; /// The system shutdown cannot be initiated because there are other users logged on to the computer. pub const SHUTDOWN_USERS_LOGGED_ON = 1191; /// The specified device name is invalid. pub const BAD_DEVICE = 1200; /// The device is not currently connected but it is a remembered connection. pub const CONNECTION_UNAVAIL = 1201; /// The local device name has a remembered connection to another network resource. pub const DEVICE_ALREADY_REMEMBERED = 1202; /// The network path was either typed incorrectly, does not exist, or the network provider is not currently available. Please try retyping the path or contact your network administrator. pub const NO_NET_OR_BAD_PATH = 1203; /// The specified network provider name is invalid. pub const BAD_PROVIDER = 1204; /// Unable to open the network connection profile. pub const CANNOT_OPEN_PROFILE = 1205; /// The network connection profile is corrupted. pub const BAD_PROFILE = 1206; /// Cannot enumerate a noncontainer. pub const NOT_CONTAINER = 1207; /// An extended error has occurred. pub const EXTENDED_ERROR = 1208; /// The format of the specified group name is invalid. pub const INVALID_GROUPNAME = 1209; /// The format of the specified computer name is invalid. pub const INVALID_COMPUTERNAME = 1210; /// The format of the specified event name is invalid. pub const INVALID_EVENTNAME = 1211; /// The format of the specified domain name is invalid. pub const INVALID_DOMAINNAME = 1212; /// The format of the specified service name is invalid. pub const INVALID_SERVICENAME = 1213; /// The format of the specified network name is invalid. pub const INVALID_NETNAME = 1214; /// The format of the specified share name is invalid. pub const INVALID_SHARENAME = 1215; /// The format of the specified password is invalid. pub const INVALID_PASSWORDNAME = 1216; /// The format of the specified message name is invalid. pub const INVALID_MESSAGENAME = 1217; /// The format of the specified message destination is invalid. pub const INVALID_MESSAGEDEST = 1218; /// Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again. pub const SESSION_CREDENTIAL_CONFLICT = 1219; /// An attempt was made to establish a session to a network server, but there are already too many sessions established to that server. pub const REMOTE_SESSION_LIMIT_EXCEEDED = 1220; /// The workgroup or domain name is already in use by another computer on the network. pub const DUP_DOMAINNAME = 1221; /// The network is not present or not started. pub const NO_NETWORK = 1222; /// The operation was canceled by the user. pub const CANCELLED = 1223; /// The requested operation cannot be performed on a file with a user-mapped section open. pub const USER_MAPPED_FILE = 1224; /// The remote computer refused the network connection. pub const CONNECTION_REFUSED = 1225; /// The network connection was gracefully closed. pub const GRACEFUL_DISCONNECT = 1226; /// The network transport endpoint already has an address associated with it. pub const ADDRESS_ALREADY_ASSOCIATED = 1227; /// An address has not yet been associated with the network endpoint. pub const ADDRESS_NOT_ASSOCIATED = 1228; /// An operation was attempted on a nonexistent network connection. pub const CONNECTION_INVALID = 1229; /// An invalid operation was attempted on an active network connection. pub const CONNECTION_ACTIVE = 1230; /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const NETWORK_UNREACHABLE = 1231; /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const HOST_UNREACHABLE = 1232; /// The network location cannot be reached. For information about network troubleshooting, see Windows Help. pub const PROTOCOL_UNREACHABLE = 1233; /// No service is operating at the destination network endpoint on the remote system. pub const PORT_UNREACHABLE = 1234; /// The request was aborted. pub const REQUEST_ABORTED = 1235; /// The network connection was aborted by the local system. pub const CONNECTION_ABORTED = 1236; /// The operation could not be completed. A retry should be performed. pub const RETRY = 1237; /// A connection to the server could not be made because the limit on the number of concurrent connections for this account has been reached. pub const CONNECTION_COUNT_LIMIT = 1238; /// Attempting to log in during an unauthorized time of day for this account. pub const LOGIN_TIME_RESTRICTION = 1239; /// The account is not authorized to log in from this station. pub const LOGIN_WKSTA_RESTRICTION = 1240; /// The network address could not be used for the operation requested. pub const INCORRECT_ADDRESS = 1241; /// The service is already registered. pub const ALREADY_REGISTERED = 1242; /// The specified service does not exist. pub const SERVICE_NOT_FOUND = 1243; /// The operation being requested was not performed because the user has not been authenticated. pub const NOT_AUTHENTICATED = 1244; /// The operation being requested was not performed because the user has not logged on to the network. The specified service does not exist. pub const NOT_LOGGED_ON = 1245; /// Continue with work in progress. pub const CONTINUE = 1246; /// An attempt was made to perform an initialization operation when initialization has already been completed. pub const ALREADY_INITIALIZED = 1247; /// No more local devices. pub const NO_MORE_DEVICES = 1248; /// The specified site does not exist. pub const NO_SUCH_SITE = 1249; /// A domain controller with the specified name already exists. pub const DOMAIN_CONTROLLER_EXISTS = 1250; /// This operation is supported only when you are connected to the server. pub const ONLY_IF_CONNECTED = 1251; /// The group policy framework should call the extension even if there are no changes. pub const OVERRIDE_NOCHANGES = 1252; /// The specified user does not have a valid profile. pub const BAD_USER_PROFILE = 1253; /// This operation is not supported on a computer running Windows Server 2003 for Small Business Server. pub const NOT_SUPPORTED_ON_SBS = 1254; /// The server machine is shutting down. pub const SERVER_SHUTDOWN_IN_PROGRESS = 1255; /// The remote system is not available. For information about network troubleshooting, see Windows Help. pub const HOST_DOWN = 1256; /// The security identifier provided is not from an account domain. pub const NON_ACCOUNT_SID = 1257; /// The security identifier provided does not have a domain component. pub const NON_DOMAIN_SID = 1258; /// AppHelp dialog canceled thus preventing the application from starting. pub const APPHELP_BLOCK = 1259; /// This program is blocked by group policy. For more information, contact your system administrator. pub const ACCESS_DISABLED_BY_POLICY = 1260; /// A program attempt to use an invalid register value. Normally caused by an uninitialized register. This error is Itanium specific. pub const REG_NAT_CONSUMPTION = 1261; /// The share is currently offline or does not exist. pub const CSCSHARE_OFFLINE = 1262; /// The Kerberos protocol encountered an error while validating the KDC certificate during smartcard logon. There is more information in the system event log. pub const PKINIT_FAILURE = 1263; /// The Kerberos protocol encountered an error while attempting to utilize the smartcard subsystem. pub const SMARTCARD_SUBSYSTEM_FAILURE = 1264; /// The system cannot contact a domain controller to service the authentication request. Please try again later. pub const DOWNGRADE_DETECTED = 1265; /// The machine is locked and cannot be shut down without the force option. pub const MACHINE_LOCKED = 1271; /// An application-defined callback gave invalid data when called. pub const CALLBACK_SUPPLIED_INVALID_DATA = 1273; /// The group policy framework should call the extension in the synchronous foreground policy refresh. pub const SYNC_FOREGROUND_REFRESH_REQUIRED = 1274; /// This driver has been blocked from loading. pub const DRIVER_BLOCKED = 1275; /// A dynamic link library (DLL) referenced a module that was neither a DLL nor the process's executable image. pub const INVALID_IMPORT_OF_NON_DLL = 1276; /// Windows cannot open this program since it has been disabled. pub const ACCESS_DISABLED_WEBBLADE = 1277; /// Windows cannot open this program because the license enforcement system has been tampered with or become corrupted. pub const ACCESS_DISABLED_WEBBLADE_TAMPER = 1278; /// A transaction recover failed. pub const RECOVERY_FAILURE = 1279; /// The current thread has already been converted to a fiber. pub const ALREADY_FIBER = 1280; /// The current thread has already been converted from a fiber. pub const ALREADY_THREAD = 1281; /// The system detected an overrun of a stack-based buffer in this application. This overrun could potentially allow a malicious user to gain control of this application. pub const STACK_BUFFER_OVERRUN = 1282; /// Data present in one of the parameters is more than the function can operate on. pub const PARAMETER_QUOTA_EXCEEDED = 1283; /// An attempt to do an operation on a debug object failed because the object is in the process of being deleted. pub const DEBUGGER_INACTIVE = 1284; /// An attempt to delay-load a .dll or get a function address in a delay-loaded .dll failed. pub const DELAY_LOAD_FAILED = 1285; /// %1 is a 16-bit application. You do not have permissions to execute 16-bit applications. Check your permissions with your system administrator. pub const VDM_DISALLOWED = 1286; /// Insufficient information exists to identify the cause of failure. pub const UNIDENTIFIED_ERROR = 1287; /// The parameter passed to a C runtime function is incorrect. pub const INVALID_CRUNTIME_PARAMETER = 1288; /// The operation occurred beyond the valid data length of the file. pub const BEYOND_VDL = 1289; /// The service start failed since one or more services in the same process have an incompatible service SID type setting. A service with restricted service SID type can only coexist in the same process with other services with a restricted SID type. If the service SID type for this service was just configured, the hosting process must be restarted in order to start this service. /// On Windows Server 2003 and Windows XP, an unrestricted service cannot coexist in the same process with other services. The service with the unrestricted service SID type must be moved to an owned process in order to start this service. pub const INCOMPATIBLE_SERVICE_SID_TYPE = 1290; /// The process hosting the driver for this device has been terminated. pub const DRIVER_PROCESS_TERMINATED = 1291; /// An operation attempted to exceed an implementation-defined limit. pub const IMPLEMENTATION_LIMIT = 1292; /// Either the target process, or the target thread's containing process, is a protected process. pub const PROCESS_IS_PROTECTED = 1293; /// The service notification client is lagging too far behind the current state of services in the machine. pub const SERVICE_NOTIFY_CLIENT_LAGGING = 1294; /// The requested file operation failed because the storage quota was exceeded. To free up disk space, move files to a different location or delete unnecessary files. For more information, contact your system administrator. pub const DISK_QUOTA_EXCEEDED = 1295; /// The requested file operation failed because the storage policy blocks that type of file. For more information, contact your system administrator. pub const CONTENT_BLOCKED = 1296; /// A privilege that the service requires to function properly does not exist in the service account configuration. You may use the Services Microsoft Management Console (MMC) snap-in (services.msc) and the Local Security Settings MMC snap-in (secpol.msc) to view the service configuration and the account configuration. pub const INCOMPATIBLE_SERVICE_PRIVILEGE = 1297; /// A thread involved in this operation appears to be unresponsive. pub const APP_HANG = 1298; /// Indicates a particular Security ID may not be assigned as the label of an object. pub const INVALID_LABEL = 1299; /// Not all privileges or groups referenced are assigned to the caller. pub const NOT_ALL_ASSIGNED = 1300; /// Some mapping between account names and security IDs was not done. pub const SOME_NOT_MAPPED = 1301; /// No system quota limits are specifically set for this account. pub const NO_QUOTAS_FOR_ACCOUNT = 1302; /// No encryption key is available. A well-known encryption key was returned. pub const LOCAL_USER_SESSION_KEY = 1303; /// The password is too complex to be converted to a LAN Manager password. The LAN Manager password returned is a NULL string. pub const NULL_LM_PASSWORD = <PASSWORD>; /// The revision level is unknown. pub const UNKNOWN_REVISION = 1305; /// Indicates two revision levels are incompatible. pub const REVISION_MISMATCH = 1306; /// This security ID may not be assigned as the owner of this object. pub const INVALID_OWNER = 1307; /// This security ID may not be assigned as the primary group of an object. pub const INVALID_PRIMARY_GROUP = 1308; /// An attempt has been made to operate on an impersonation token by a thread that is not currently impersonating a client. pub const NO_IMPERSONATION_TOKEN = 1309; /// The group may not be disabled. pub const CANT_DISABLE_MANDATORY = 1310; /// There are currently no logon servers available to service the logon request. pub const NO_LOGON_SERVERS = 1311; /// A specified logon session does not exist. It may already have been terminated. pub const NO_SUCH_LOGON_SESSION = 1312; /// A specified privilege does not exist. pub const NO_SUCH_PRIVILEGE = 1313; /// A required privilege is not held by the client. pub const PRIVILEGE_NOT_HELD = 1314; /// The name provided is not a properly formed account name. pub const INVALID_ACCOUNT_NAME = 1315; /// The specified account already exists. pub const USER_EXISTS = 1316; /// The specified account does not exist. pub const NO_SUCH_USER = 1317; /// The specified group already exists. pub const GROUP_EXISTS = 1318; /// The specified group does not exist. pub const NO_SUCH_GROUP = 1319; /// Either the specified user account is already a member of the specified group, or the specified group cannot be deleted because it contains a member. pub const MEMBER_IN_GROUP = 1320; /// The specified user account is not a member of the specified group account. pub const MEMBER_NOT_IN_GROUP = 1321; /// This operation is disallowed as it could result in an administration account being disabled, deleted or unable to log on. pub const LAST_ADMIN = 1322; /// Unable to update the password. The value provided as the current password is incorrect. pub const WRONG_PASSWORD = <PASSWORD>; /// Unable to update the password. The value provided for the new password contains values that are not allowed in passwords. pub const ILL_FORMED_PASSWORD = 1324; /// Unable to update the password. The value provided for the new password does not meet the length, complexity, or history requirements of the domain. pub const PASSWORD_RESTRICTION = 1325; /// The user name or password is incorrect. pub const LOGON_FAILURE = 1326; /// Account restrictions are preventing this user from signing in. For example: blank passwords aren't allowed, sign-in times are limited, or a policy restriction has been enforced. pub const ACCOUNT_RESTRICTION = 1327; /// Your account has time restrictions that keep you from signing in right now. pub const INVALID_LOGON_HOURS = 1328; /// This user isn't allowed to sign in to this computer. pub const INVALID_WORKSTATION = 1329; /// The password for this account has expired. pub const PASSWORD_EXPIRED = <PASSWORD>; /// This user can't sign in because this account is currently disabled. pub const ACCOUNT_DISABLED = 1331; /// No mapping between account names and security IDs was done. pub const NONE_MAPPED = 1332; /// Too many local user identifiers (LUIDs) were requested at one time. pub const TOO_MANY_LUIDS_REQUESTED = 1333; /// No more local user identifiers (LUIDs) are available. pub const LUIDS_EXHAUSTED = 1334; /// The subauthority part of a security ID is invalid for this particular use. pub const INVALID_SUB_AUTHORITY = 1335; /// The access control list (ACL) structure is invalid. pub const INVALID_ACL = 1336; /// The security ID structure is invalid. pub const INVALID_SID = 1337; /// The security descriptor structure is invalid. pub const INVALID_SECURITY_DESCR = 1338; /// The inherited access control list (ACL) or access control entry (ACE) could not be built. pub const BAD_INHERITANCE_ACL = 1340; /// The server is currently disabled. pub const SERVER_DISABLED = 1341; /// The server is currently enabled. pub const SERVER_NOT_DISABLED = 1342; /// The value provided was an invalid value for an identifier authority. pub const INVALID_ID_AUTHORITY = 1343; /// No more memory is available for security information updates. pub const ALLOTTED_SPACE_EXCEEDED = 1344; /// The specified attributes are invalid, or incompatible with the attributes for the group as a whole. pub const INVALID_GROUP_ATTRIBUTES = 1345; /// Either a required impersonation level was not provided, or the provided impersonation level is invalid. pub const BAD_IMPERSONATION_LEVEL = 1346; /// Cannot open an anonymous level security token. pub const CANT_OPEN_ANONYMOUS = 1347; /// The validation information class requested was invalid. pub const BAD_VALIDATION_CLASS = 1348; /// The type of the token is inappropriate for its attempted use. pub const BAD_TOKEN_TYPE = 1349; /// Unable to perform a security operation on an object that has no associated security. pub const NO_SECURITY_ON_OBJECT = 1350; /// Configuration information could not be read from the domain controller, either because the machine is unavailable, or access has been denied. pub const CANT_ACCESS_DOMAIN_INFO = 1351; /// The security account manager (SAM) or local security authority (LSA) server was in the wrong state to perform the security operation. pub const INVALID_SERVER_STATE = 1352; /// The domain was in the wrong state to perform the security operation. pub const INVALID_DOMAIN_STATE = 1353; /// This operation is only allowed for the Primary Domain Controller of the domain. pub const INVALID_DOMAIN_ROLE = 1354; /// The specified domain either does not exist or could not be contacted. pub const NO_SUCH_DOMAIN = 1355; /// The specified domain already exists. pub const DOMAIN_EXISTS = 1356; /// An attempt was made to exceed the limit on the number of domains per server. pub const DOMAIN_LIMIT_EXCEEDED = 1357; /// Unable to complete the requested operation because of either a catastrophic media failure or a data structure corruption on the disk. pub const INTERNAL_DB_CORRUPTION = 1358; /// An internal error occurred. pub const INTERNAL_ERROR = 1359; /// Generic access types were contained in an access mask which should already be mapped to nongeneric types. pub const GENERIC_NOT_MAPPED = 1360; /// A security descriptor is not in the right format (absolute or self-relative). pub const BAD_DESCRIPTOR_FORMAT = 1361; /// The requested action is restricted for use by logon processes only. The calling process has not registered as a logon process. pub const NOT_LOGON_PROCESS = 1362; /// Cannot start a new logon session with an ID that is already in use. pub const LOGON_SESSION_EXISTS = 1363; /// A specified authentication package is unknown. pub const NO_SUCH_PACKAGE = 1364; /// The logon session is not in a state that is consistent with the requested operation. pub const BAD_LOGON_SESSION_STATE = 1365; /// The logon session ID is already in use. pub const LOGON_SESSION_COLLISION = 1366; /// A logon request contained an invalid logon type value. pub const INVALID_LOGON_TYPE = 1367; /// Unable to impersonate using a named pipe until data has been read from that pipe. pub const CANNOT_IMPERSONATE = 1368; /// The transaction state of a registry subtree is incompatible with the requested operation. pub const RXACT_INVALID_STATE = 1369; /// An internal security database corruption has been encountered. pub const RXACT_COMMIT_FAILURE = 1370; /// Cannot perform this operation on built-in accounts. pub const SPECIAL_ACCOUNT = 1371; /// Cannot perform this operation on this built-in special group. pub const SPECIAL_GROUP = 1372; /// Cannot perform this operation on this built-in special user. pub const SPECIAL_USER = 1373; /// The user cannot be removed from a group because the group is currently the user's primary group. pub const MEMBERS_PRIMARY_GROUP = 1374; /// The token is already in use as a primary token. pub const TOKEN_ALREADY_IN_USE = 1375; /// The specified local group does not exist. pub const NO_SUCH_ALIAS = 1376; /// The specified account name is not a member of the group. pub const MEMBER_NOT_IN_ALIAS = 1377; /// The specified account name is already a member of the group. pub const MEMBER_IN_ALIAS = 1378; /// The specified local group already exists. pub const ALIAS_EXISTS = 1379; /// Logon failure: the user has not been granted the requested logon type at this computer. pub const LOGON_NOT_GRANTED = 1380; /// The maximum number of secrets that may be stored in a single system has been exceeded. pub const TOO_MANY_SECRETS = 1381; /// The length of a secret exceeds the maximum length allowed. pub const SECRET_TOO_LONG = 1382; /// The local security authority database contains an internal inconsistency. pub const INTERNAL_DB_ERROR = 1383; /// During a logon attempt, the user's security context accumulated too many security IDs. pub const TOO_MANY_CONTEXT_IDS = 1384; /// Logon failure: the user has not been granted the requested logon type at this computer. pub const LOGON_TYPE_NOT_GRANTED = 1385; /// A cross-encrypted password is necessary to change a user password. pub const NT_CROSS_ENCRYPTION_REQUIRED = 1386; /// A member could not be added to or removed from the local group because the member does not exist. pub const NO_SUCH_MEMBER = 1387; /// A new member could not be added to a local group because the member has the wrong account type. pub const INVALID_MEMBER = 1388; /// Too many security IDs have been specified. pub const TOO_MANY_SIDS = 1389; /// A cross-encrypted password is necessary to change this user password. pub const LM_CROSS_ENCRYPTION_REQUIRED = 1390; /// Indicates an ACL contains no inheritable components. pub const NO_INHERITANCE = 1391; /// The file or directory is corrupted and unreadable. pub const FILE_CORRUPT = 1392; /// The disk structure is corrupted and unreadable. pub const DISK_CORRUPT = 1393; /// There is no user session key for the specified logon session. pub const NO_USER_SESSION_KEY = 1394; /// The service being accessed is licensed for a particular number of connections. No more connections can be made to the service at this time because there are already as many connections as the service can accept. pub const LICENSE_QUOTA_EXCEEDED = 1395; /// The target account name is incorrect. pub const WRONG_TARGET_NAME = 1396; /// Mutual Authentication failed. The server's password is out of date at the domain controller. pub const MUTUAL_AUTH_FAILED = 1397; /// There is a time and/or date difference between the client and server. pub const TIME_SKEW = 1398; /// This operation cannot be performed on the current domain. pub const CURRENT_DOMAIN_NOT_ALLOWED = 1399; /// Invalid window handle. pub const INVALID_WINDOW_HANDLE = 1400; /// Invalid menu handle. pub const INVALID_MENU_HANDLE = 1401; /// Invalid cursor handle. pub const INVALID_CURSOR_HANDLE = 1402; /// Invalid accelerator table handle. pub const INVALID_ACCEL_HANDLE = 1403; /// Invalid hook handle. pub const INVALID_HOOK_HANDLE = 1404; /// Invalid handle to a multiple-window position structure. pub const INVALID_DWP_HANDLE = 1405; /// Cannot create a top-level child window. pub const TLW_WITH_WSCHILD = 1406; /// Cannot find window class. pub const CANNOT_FIND_WND_CLASS = 1407; /// Invalid window; it belongs to other thread. pub const WINDOW_OF_OTHER_THREAD = 1408; /// Hot key is already registered. pub const HOTKEY_ALREADY_REGISTERED = 1409; /// Class already exists. pub const CLASS_ALREADY_EXISTS = 1410; /// Class does not exist. pub const CLASS_DOES_NOT_EXIST = 1411; /// Class still has open windows. pub const CLASS_HAS_WINDOWS = 1412; /// Invalid index. pub const INVALID_INDEX = 1413; /// Invalid icon handle. pub const INVALID_ICON_HANDLE = 1414; /// Using private DIALOG window words. pub const PRIVATE_DIALOG_INDEX = 1415; /// The list box identifier was not found. pub const LISTBOX_ID_NOT_FOUND = 1416; /// No wildcards were found. pub const NO_WILDCARD_CHARACTERS = 1417; /// Thread does not have a clipboard open. pub const CLIPBOARD_NOT_OPEN = 1418; /// Hot key is not registered. pub const HOTKEY_NOT_REGISTERED = 1419; /// The window is not a valid dialog window. pub const WINDOW_NOT_DIALOG = 1420; /// Control ID not found. pub const CONTROL_ID_NOT_FOUND = 1421; /// Invalid message for a combo box because it does not have an edit control. pub const INVALID_COMBOBOX_MESSAGE = 1422; /// The window is not a combo box. pub const WINDOW_NOT_COMBOBOX = 1423; /// Height must be less than 256. pub const INVALID_EDIT_HEIGHT = 1424; /// Invalid device context (DC) handle. pub const DC_NOT_FOUND = 1425; /// Invalid hook procedure type. pub const INVALID_HOOK_FILTER = 1426; /// Invalid hook procedure. pub const INVALID_FILTER_PROC = 1427; /// Cannot set nonlocal hook without a module handle. pub const HOOK_NEEDS_HMOD = 1428; /// This hook procedure can only be set globally. pub const GLOBAL_ONLY_HOOK = 1429; /// The journal hook procedure is already installed. pub const JOURNAL_HOOK_SET = 1430; /// The hook procedure is not installed. pub const HOOK_NOT_INSTALLED = 1431; /// Invalid message for single-selection list box. pub const INVALID_LB_MESSAGE = 1432; /// LB_SETCOUNT sent to non-lazy list box. pub const SETCOUNT_ON_BAD_LB = 1433; /// This list box does not support tab stops. pub const LB_WITHOUT_TABSTOPS = 1434; /// Cannot destroy object created by another thread. pub const DESTROY_OBJECT_OF_OTHER_THREAD = 1435; /// Child windows cannot have menus. pub const CHILD_WINDOW_MENU = 1436; /// The window does not have a system menu. pub const NO_SYSTEM_MENU = 1437; /// Invalid message box style. pub const INVALID_MSGBOX_STYLE = 1438; /// Invalid system-wide (SPI_*) parameter. pub const INVALID_SPI_VALUE = 1439; /// Screen already locked. pub const SCREEN_ALREADY_LOCKED = 1440; /// All handles to windows in a multiple-window position structure must have the same parent. pub const HWNDS_HAVE_DIFF_PARENT = 1441; /// The window is not a child window. pub const NOT_CHILD_WINDOW = 1442; /// Invalid GW_* command. pub const INVALID_GW_COMMAND = 1443; /// Invalid thread identifier. pub const INVALID_THREAD_ID = 1444; /// Cannot process a message from a window that is not a multiple document interface (MDI) window. pub const NON_MDICHILD_WINDOW = 1445; /// Popup menu already active. pub const POPUP_ALREADY_ACTIVE = 1446; /// The window does not have scroll bars. pub const NO_SCROLLBARS = 1447; /// Scroll bar range cannot be greater than MAXLONG. pub const INVALID_SCROLLBAR_RANGE = 1448; /// Cannot show or remove the window in the way specified. pub const INVALID_SHOWWIN_COMMAND = 1449; /// Insufficient system resources exist to complete the requested service. pub const NO_SYSTEM_RESOURCES = 1450; /// Insufficient system resources exist to complete the requested service. pub const NONPAGED_SYSTEM_RESOURCES = 1451; /// Insufficient system resources exist to complete the requested service. pub const PAGED_SYSTEM_RESOURCES = 1452; /// Insufficient quota to complete the requested service. pub const WORKING_SET_QUOTA = 1453; /// Insufficient quota to complete the requested service. pub const PAGEFILE_QUOTA = 1454; /// The paging file is too small for this operation to complete. pub const COMMITMENT_LIMIT = 1455; /// A menu item was not found. pub const MENU_ITEM_NOT_FOUND = 1456; /// Invalid keyboard layout handle. pub const INVALID_KEYBOARD_HANDLE = 1457; /// Hook type not allowed. pub const HOOK_TYPE_NOT_ALLOWED = 1458; /// This operation requires an interactive window station. pub const REQUIRES_INTERACTIVE_WINDOWSTATION = 1459; /// This operation returned because the timeout period expired. pub const TIMEOUT = 1460; /// Invalid monitor handle. pub const INVALID_MONITOR_HANDLE = 1461; /// Incorrect size argument. pub const INCORRECT_SIZE = 1462; /// The symbolic link cannot be followed because its type is disabled. pub const SYMLINK_CLASS_DISABLED = 1463; /// This application does not support the current operation on symbolic links. pub const SYMLINK_NOT_SUPPORTED = 1464; /// Windows was unable to parse the requested XML data. pub const XML_PARSE_ERROR = 1465; /// An error was encountered while processing an XML digital signature. pub const XMLDSIG_ERROR = 1466; /// This application must be restarted. pub const RESTART_APPLICATION = 1467; /// The caller made the connection request in the wrong routing compartment. pub const WRONG_COMPARTMENT = 1468; /// There was an AuthIP failure when attempting to connect to the remote host. pub const AUTHIP_FAILURE = 1469; /// Insufficient NVRAM resources exist to complete the requested service. A reboot might be required. pub const NO_NVRAM_RESOURCES = 1470; /// Unable to finish the requested operation because the specified process is not a GUI process. pub const NOT_GUI_PROCESS = 1471; /// The event log file is corrupted. pub const EVENTLOG_FILE_CORRUPT = 1500; /// No event log file could be opened, so the event logging service did not start. pub const EVENTLOG_CANT_START = 1501; /// The event log file is full. pub const LOG_FILE_FULL = 1502; /// The event log file has changed between read operations. pub const EVENTLOG_FILE_CHANGED = 1503; /// The specified task name is invalid. pub const INVALID_TASK_NAME = 1550; /// The specified task index is invalid. pub const INVALID_TASK_INDEX = 1551; /// The specified thread is already joining a task. pub const THREAD_ALREADY_IN_TASK = 1552; /// The Windows Installer Service could not be accessed. This can occur if the Windows Installer is not correctly installed. Contact your support personnel for assistance. pub const INSTALL_SERVICE_FAILURE = 1601; /// User cancelled installation. pub const INSTALL_USEREXIT = 1602; /// Fatal error during installation. pub const INSTALL_FAILURE = 1603; /// Installation suspended, incomplete. pub const INSTALL_SUSPEND = 1604; /// This action is only valid for products that are currently installed. pub const UNKNOWN_PRODUCT = 1605; /// Feature ID not registered. pub const UNKNOWN_FEATURE = 1606; /// Component ID not registered. pub const UNKNOWN_COMPONENT = 1607; /// Unknown property. pub const UNKNOWN_PROPERTY = 1608; /// Handle is in an invalid state. pub const INVALID_HANDLE_STATE = 1609; /// The configuration data for this product is corrupt. Contact your support personnel. pub const BAD_CONFIGURATION = 1610; /// Component qualifier not present. pub const INDEX_ABSENT = 1611; /// The installation source for this product is not available. Verify that the source exists and that you can access it. pub const INSTALL_SOURCE_ABSENT = 1612; /// This installation package cannot be installed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service. pub const INSTALL_PACKAGE_VERSION = 1613; /// Product is uninstalled. pub const PRODUCT_UNINSTALLED = 1614; /// SQL query syntax invalid or unsupported. pub const BAD_QUERY_SYNTAX = 1615; /// Record field does not exist. pub const INVALID_FIELD = 1616; /// The device has been removed. pub const DEVICE_REMOVED = 1617; /// Another installation is already in progress. Complete that installation before proceeding with this install. pub const INSTALL_ALREADY_RUNNING = 1618; /// This installation package could not be opened. Verify that the package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer package. pub const INSTALL_PACKAGE_OPEN_FAILED = 1619; /// This installation package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer package. pub const INSTALL_PACKAGE_INVALID = 1620; /// There was an error starting the Windows Installer service user interface. Contact your support personnel. pub const INSTALL_UI_FAILURE = 1621; /// Error opening installation log file. Verify that the specified log file location exists and that you can write to it. pub const INSTALL_LOG_FAILURE = 1622; /// The language of this installation package is not supported by your system. pub const INSTALL_LANGUAGE_UNSUPPORTED = 1623; /// Error applying transforms. Verify that the specified transform paths are valid. pub const INSTALL_TRANSFORM_FAILURE = 1624; /// This installation is forbidden by system policy. Contact your system administrator. pub const INSTALL_PACKAGE_REJECTED = 1625; /// Function could not be executed. pub const FUNCTION_NOT_CALLED = 1626; /// Function failed during execution. pub const FUNCTION_FAILED = 1627; /// Invalid or unknown table specified. pub const INVALID_TABLE = 1628; /// Data supplied is of wrong type. pub const DATATYPE_MISMATCH = 1629; /// Data of this type is not supported. pub const UNSUPPORTED_TYPE = 1630; /// The Windows Installer service failed to start. Contact your support personnel. pub const CREATE_FAILED = 1631; /// The Temp folder is on a drive that is full or is inaccessible. Free up space on the drive or verify that you have write permission on the Temp folder. pub const INSTALL_TEMP_UNWRITABLE = 1632; /// This installation package is not supported by this processor type. Contact your product vendor. pub const INSTALL_PLATFORM_UNSUPPORTED = 1633; /// Component not used on this computer. pub const INSTALL_NOTUSED = 1634; /// This update package could not be opened. Verify that the update package exists and that you can access it, or contact the application vendor to verify that this is a valid Windows Installer update package. pub const PATCH_PACKAGE_OPEN_FAILED = 1635; /// This update package could not be opened. Contact the application vendor to verify that this is a valid Windows Installer update package. pub const PATCH_PACKAGE_INVALID = 1636; /// This update package cannot be processed by the Windows Installer service. You must install a Windows service pack that contains a newer version of the Windows Installer service. pub const PATCH_PACKAGE_UNSUPPORTED = 1637; /// Another version of this product is already installed. Installation of this version cannot continue. To configure or remove the existing version of this product, use Add/Remove Programs on the Control Panel. pub const PRODUCT_VERSION = 1638; /// Invalid command line argument. Consult the Windows Installer SDK for detailed command line help. pub const INVALID_COMMAND_LINE = 1639; /// Only administrators have permission to add, remove, or configure server software during a Terminal services remote session. If you want to install or configure software on the server, contact your network administrator. pub const INSTALL_REMOTE_DISALLOWED = 1640; /// The requested operation completed successfully. The system will be restarted so the changes can take effect. pub const SUCCESS_REBOOT_INITIATED = 1641; /// The upgrade cannot be installed by the Windows Installer service because the program to be upgraded may be missing, or the upgrade may update a different version of the program. Verify that the program to be upgraded exists on your computer and that you have the correct upgrade. pub const PATCH_TARGET_NOT_FOUND = 1642; /// The update package is not permitted by software restriction policy. pub const PATCH_PACKAGE_REJECTED = 1643; /// One or more customizations are not permitted by software restriction policy. pub const INSTALL_TRANSFORM_REJECTED = 1644; /// The Windows Installer does not permit installation from a Remote Desktop Connection. pub const INSTALL_REMOTE_PROHIBITED = 1645; /// Uninstallation of the update package is not supported. pub const PATCH_REMOVAL_UNSUPPORTED = 1646; /// The update is not applied to this product. pub const UNKNOWN_PATCH = 1647; /// No valid sequence could be found for the set of updates. pub const PATCH_NO_SEQUENCE = 1648; /// Update removal was disallowed by policy. pub const PATCH_REMOVAL_DISALLOWED = 1649; /// The XML update data is invalid. pub const INVALID_PATCH_XML = 1650; /// Windows Installer does not permit updating of managed advertised products. At least one feature of the product must be installed before applying the update. pub const PATCH_MANAGED_ADVERTISED_PRODUCT = 1651; /// The Windows Installer service is not accessible in Safe Mode. Please try again when your computer is not in Safe Mode or you can use System Restore to return your machine to a previous good state. pub const INSTALL_SERVICE_SAFEBOOT = 1652; /// A fail fast exception occurred. Exception handlers will not be invoked and the process will be terminated immediately. pub const FAIL_FAST_EXCEPTION = 1653; /// The app that you are trying to run is not supported on this version of Windows. pub const INSTALL_REJECTED = 1654; /// The string binding is invalid. pub const RPC_S_INVALID_STRING_BINDING = 1700; /// The binding handle is not the correct type. pub const RPC_S_WRONG_KIND_OF_BINDING = 1701; /// The binding handle is invalid. pub const RPC_S_INVALID_BINDING = 1702; /// The RPC protocol sequence is not supported. pub const RPC_S_PROTSEQ_NOT_SUPPORTED = 1703; /// The RPC protocol sequence is invalid. pub const RPC_S_INVALID_RPC_PROTSEQ = 1704; /// The string universal unique identifier (UUID) is invalid. pub const RPC_S_INVALID_STRING_UUID = 1705; /// The endpoint format is invalid. pub const RPC_S_INVALID_ENDPOINT_FORMAT = 1706; /// The network address is invalid. pub const RPC_S_INVALID_NET_ADDR = 1707; /// No endpoint was found. pub const RPC_S_NO_ENDPOINT_FOUND = 1708; /// The timeout value is invalid. pub const RPC_S_INVALID_TIMEOUT = 1709; /// The object universal unique identifier (UUID) was not found. pub const RPC_S_OBJECT_NOT_FOUND = 1710; /// The object universal unique identifier (UUID) has already been registered. pub const RPC_S_ALREADY_REGISTERED = 1711; /// The type universal unique identifier (UUID) has already been registered. pub const RPC_S_TYPE_ALREADY_REGISTERED = 1712; /// The RPC server is already listening. pub const RPC_S_ALREADY_LISTENING = 1713; /// No protocol sequences have been registered. pub const RPC_S_NO_PROTSEQS_REGISTERED = 1714; /// The RPC server is not listening. pub const RPC_S_NOT_LISTENING = 1715; /// The manager type is unknown. pub const RPC_S_UNKNOWN_MGR_TYPE = 1716; /// The interface is unknown. pub const RPC_S_UNKNOWN_IF = 1717; /// There are no bindings. pub const RPC_S_NO_BINDINGS = 1718; /// There are no protocol sequences. pub const RPC_S_NO_PROTSEQS = 1719; /// The endpoint cannot be created. pub const RPC_S_CANT_CREATE_ENDPOINT = 1720; /// Not enough resources are available to complete this operation. pub const RPC_S_OUT_OF_RESOURCES = 1721; /// The RPC server is unavailable. pub const RPC_S_SERVER_UNAVAILABLE = 1722; /// The RPC server is too busy to complete this operation. pub const RPC_S_SERVER_TOO_BUSY = 1723; /// The network options are invalid. pub const RPC_S_INVALID_NETWORK_OPTIONS = 1724; /// There are no remote procedure calls active on this thread. pub const RPC_S_NO_CALL_ACTIVE = 1725; /// The remote procedure call failed. pub const RPC_S_CALL_FAILED = 1726; /// The remote procedure call failed and did not execute. pub const RPC_S_CALL_FAILED_DNE = 1727; /// A remote procedure call (RPC) protocol error occurred. pub const RPC_S_PROTOCOL_ERROR = 1728; /// Access to the HTTP proxy is denied. pub const RPC_S_PROXY_ACCESS_DENIED = 1729; /// The transfer syntax is not supported by the RPC server. pub const RPC_S_UNSUPPORTED_TRANS_SYN = 1730; /// The universal unique identifier (UUID) type is not supported. pub const RPC_S_UNSUPPORTED_TYPE = 1732; /// The tag is invalid. pub const RPC_S_INVALID_TAG = 1733; /// The array bounds are invalid. pub const RPC_S_INVALID_BOUND = 1734; /// The binding does not contain an entry name. pub const RPC_S_NO_ENTRY_NAME = 1735; /// The name syntax is invalid. pub const RPC_S_INVALID_NAME_SYNTAX = 1736; /// The name syntax is not supported. pub const RPC_S_UNSUPPORTED_NAME_SYNTAX = 1737; /// No network address is available to use to construct a universal unique identifier (UUID). pub const RPC_S_UUID_NO_ADDRESS = 1739; /// The endpoint is a duplicate. pub const RPC_S_DUPLICATE_ENDPOINT = 1740; /// The authentication type is unknown. pub const RPC_S_UNKNOWN_AUTHN_TYPE = 1741; /// The maximum number of calls is too small. pub const RPC_S_MAX_CALLS_TOO_SMALL = 1742; /// The string is too long. pub const RPC_S_STRING_TOO_LONG = 1743; /// The RPC protocol sequence was not found. pub const RPC_S_PROTSEQ_NOT_FOUND = 1744; /// The procedure number is out of range. pub const RPC_S_PROCNUM_OUT_OF_RANGE = 1745; /// The binding does not contain any authentication information. pub const RPC_S_BINDING_HAS_NO_AUTH = 1746; /// The authentication service is unknown. pub const RPC_S_UNKNOWN_AUTHN_SERVICE = 1747; /// The authentication level is unknown. pub const RPC_S_UNKNOWN_AUTHN_LEVEL = 1748; /// The security context is invalid. pub const RPC_S_INVALID_AUTH_IDENTITY = 1749; /// The authorization service is unknown. pub const RPC_S_UNKNOWN_AUTHZ_SERVICE = 1750; /// The entry is invalid. pub const EPT_S_INVALID_ENTRY = 1751; /// The server endpoint cannot perform the operation. pub const EPT_S_CANT_PERFORM_OP = 1752; /// There are no more endpoints available from the endpoint mapper. pub const EPT_S_NOT_REGISTERED = 1753; /// No interfaces have been exported. pub const RPC_S_NOTHING_TO_EXPORT = 1754; /// The entry name is incomplete. pub const RPC_S_INCOMPLETE_NAME = 1755; /// The version option is invalid. pub const RPC_S_INVALID_VERS_OPTION = 1756; /// There are no more members. pub const RPC_S_NO_MORE_MEMBERS = 1757; /// There is nothing to unexport. pub const RPC_S_NOT_ALL_OBJS_UNEXPORTED = 1758; /// The interface was not found. pub const RPC_S_INTERFACE_NOT_FOUND = 1759; /// The entry already exists. pub const RPC_S_ENTRY_ALREADY_EXISTS = 1760; /// The entry is not found. pub const RPC_S_ENTRY_NOT_FOUND = 1761; /// The name service is unavailable. pub const RPC_S_NAME_SERVICE_UNAVAILABLE = 1762; /// The network address family is invalid. pub const RPC_S_INVALID_NAF_ID = 1763; /// The requested operation is not supported. pub const RPC_S_CANNOT_SUPPORT = 1764; /// No security context is available to allow impersonation. pub const RPC_S_NO_CONTEXT_AVAILABLE = 1765; /// An internal error occurred in a remote procedure call (RPC). pub const RPC_S_INTERNAL_ERROR = 1766; /// The RPC server attempted an integer division by zero. pub const RPC_S_ZERO_DIVIDE = 1767; /// An addressing error occurred in the RPC server. pub const RPC_S_ADDRESS_ERROR = 1768; /// A floating-point operation at the RPC server caused a division by zero. pub const RPC_S_FP_DIV_ZERO = 1769; /// A floating-point underflow occurred at the RPC server. pub const RPC_S_FP_UNDERFLOW = 1770; /// A floating-point overflow occurred at the RPC server. pub const RPC_S_FP_OVERFLOW = 1771; /// The list of RPC servers available for the binding of auto handles has been exhausted. pub const RPC_X_NO_MORE_ENTRIES = 1772; /// Unable to open the character translation table file. pub const RPC_X_SS_CHAR_TRANS_OPEN_FAIL = 1773; /// The file containing the character translation table has fewer than 512 bytes. pub const RPC_X_SS_CHAR_TRANS_SHORT_FILE = 1774; /// A null context handle was passed from the client to the host during a remote procedure call. pub const RPC_X_SS_IN_NULL_CONTEXT = 1775; /// The context handle changed during a remote procedure call. pub const RPC_X_SS_CONTEXT_DAMAGED = 1777; /// The binding handles passed to a remote procedure call do not match. pub const RPC_X_SS_HANDLES_MISMATCH = 1778; /// The stub is unable to get the remote procedure call handle. pub const RPC_X_SS_CANNOT_GET_CALL_HANDLE = 1779; /// A null reference pointer was passed to the stub. pub const RPC_X_NULL_REF_POINTER = 1780; /// The enumeration value is out of range. pub const RPC_X_ENUM_VALUE_OUT_OF_RANGE = 1781; /// The byte count is too small. pub const RPC_X_BYTE_COUNT_TOO_SMALL = 1782; /// The stub received bad data. pub const RPC_X_BAD_STUB_DATA = 1783; /// The supplied user buffer is not valid for the requested operation. pub const INVALID_USER_BUFFER = 1784; /// The disk media is not recognized. It may not be formatted. pub const UNRECOGNIZED_MEDIA = 1785; /// The workstation does not have a trust secret. pub const NO_TRUST_LSA_SECRET = 1786; /// The security database on the server does not have a computer account for this workstation trust relationship. pub const NO_TRUST_SAM_ACCOUNT = 1787; /// The trust relationship between the primary domain and the trusted domain failed. pub const TRUSTED_DOMAIN_FAILURE = 1788; /// The trust relationship between this workstation and the primary domain failed. pub const TRUSTED_RELATIONSHIP_FAILURE = 1789; /// The network logon failed. pub const TRUST_FAILURE = 1790; /// A remote procedure call is already in progress for this thread. pub const RPC_S_CALL_IN_PROGRESS = 1791; /// An attempt was made to logon, but the network logon service was not started. pub const NETLOGON_NOT_STARTED = 1792; /// The user's account has expired. pub const ACCOUNT_EXPIRED = 1793; /// The redirector is in use and cannot be unloaded. pub const REDIRECTOR_HAS_OPEN_HANDLES = 1794; /// The specified printer driver is already installed. pub const PRINTER_DRIVER_ALREADY_INSTALLED = 1795; /// The specified port is unknown. pub const UNKNOWN_PORT = 1796; /// The printer driver is unknown. pub const UNKNOWN_PRINTER_DRIVER = 1797; /// The print processor is unknown. pub const UNKNOWN_PRINTPROCESSOR = 1798; /// The specified separator file is invalid. pub const INVALID_SEPARATOR_FILE = 1799; /// The specified priority is invalid. pub const INVALID_PRIORITY = 1800; /// The printer name is invalid. pub const INVALID_PRINTER_NAME = 1801; /// The printer already exists. pub const PRINTER_ALREADY_EXISTS = 1802; /// The printer command is invalid. pub const INVALID_PRINTER_COMMAND = 1803; /// The specified datatype is invalid. pub const INVALID_DATATYPE = 1804; /// The environment specified is invalid. pub const INVALID_ENVIRONMENT = 1805; /// There are no more bindings. pub const RPC_S_NO_MORE_BINDINGS = 1806; /// The account used is an interdomain trust account. Use your global user account or local user account to access this server. pub const NOLOGON_INTERDOMAIN_TRUST_ACCOUNT = 1807; /// The account used is a computer account. Use your global user account or local user account to access this server. pub const NOLOGON_WORKSTATION_TRUST_ACCOUNT = 1808; /// The account used is a server trust account. Use your global user account or local user account to access this server. pub const NOLOGON_SERVER_TRUST_ACCOUNT = 1809; /// The name or security ID (SID) of the domain specified is inconsistent with the trust information for that domain. pub const DOMAIN_TRUST_INCONSISTENT = 1810; /// The server is in use and cannot be unloaded. pub const SERVER_HAS_OPEN_HANDLES = 1811; /// The specified image file did not contain a resource section. pub const RESOURCE_DATA_NOT_FOUND = 1812; /// The specified resource type cannot be found in the image file. pub const RESOURCE_TYPE_NOT_FOUND = 1813; /// The specified resource name cannot be found in the image file. pub const RESOURCE_NAME_NOT_FOUND = 1814; /// The specified resource language ID cannot be found in the image file. pub const RESOURCE_LANG_NOT_FOUND = 1815; /// Not enough quota is available to process this command. pub const NOT_ENOUGH_QUOTA = 1816; /// No interfaces have been registered. pub const RPC_S_NO_INTERFACES = 1817; /// The remote procedure call was cancelled. pub const RPC_S_CALL_CANCELLED = 1818; /// The binding handle does not contain all required information. pub const RPC_S_BINDING_INCOMPLETE = 1819; /// A communications failure occurred during a remote procedure call. pub const RPC_S_COMM_FAILURE = 1820; /// The requested authentication level is not supported. pub const RPC_S_UNSUPPORTED_AUTHN_LEVEL = 1821; /// No principal name registered. pub const RPC_S_NO_PRINC_NAME = 1822; /// The error specified is not a valid Windows RPC error code. pub const RPC_S_NOT_RPC_ERROR = 1823; /// A UUID that is valid only on this computer has been allocated. pub const RPC_S_UUID_LOCAL_ONLY = 1824; /// A security package specific error occurred. pub const RPC_S_SEC_PKG_ERROR = 1825; /// Thread is not canceled. pub const RPC_S_NOT_CANCELLED = 1826; /// Invalid operation on the encoding/decoding handle. pub const RPC_X_INVALID_ES_ACTION = 1827; /// Incompatible version of the serializing package. pub const RPC_X_WRONG_ES_VERSION = 1828; /// Incompatible version of the RPC stub. pub const RPC_X_WRONG_STUB_VERSION = 1829; /// The RPC pipe object is invalid or corrupted. pub const RPC_X_INVALID_PIPE_OBJECT = 1830; /// An invalid operation was attempted on an RPC pipe object. pub const RPC_X_WRONG_PIPE_ORDER = 1831; /// Unsupported RPC pipe version. pub const RPC_X_WRONG_PIPE_VERSION = 1832; /// HTTP proxy server rejected the connection because the cookie authentication failed. pub const RPC_S_COOKIE_AUTH_FAILED = 1833; /// The group member was not found. pub const RPC_S_GROUP_MEMBER_NOT_FOUND = 1898; /// The endpoint mapper database entry could not be created. pub const EPT_S_CANT_CREATE = 1899; /// The object universal unique identifier (UUID) is the nil UUID. pub const RPC_S_INVALID_OBJECT = 1900; /// The specified time is invalid. pub const INVALID_TIME = 1901; /// The specified form name is invalid. pub const INVALID_FORM_NAME = 1902; /// The specified form size is invalid. pub const INVALID_FORM_SIZE = 1903; /// The specified printer handle is already being waited on. pub const ALREADY_WAITING = 1904; /// The specified printer has been deleted. pub const PRINTER_DELETED = 1905; /// The state of the printer is invalid. pub const INVALID_PRINTER_STATE = 1906; /// The user's password must be changed before signing in. pub const PASSWORD_MUST_CHANGE = 1907; /// Could not find the domain controller for this domain. pub const DOMAIN_CONTROLLER_NOT_FOUND = 1908; /// The referenced account is currently locked out and may not be logged on to. pub const ACCOUNT_LOCKED_OUT = 1909; /// The object exporter specified was not found. pub const OR_INVALID_OXID = 1910; /// The object specified was not found. pub const OR_INVALID_OID = 1911; /// The object resolver set specified was not found. pub const OR_INVALID_SET = 1912; /// Some data remains to be sent in the request buffer. pub const RPC_S_SEND_INCOMPLETE = 1913; /// Invalid asynchronous remote procedure call handle. pub const RPC_S_INVALID_ASYNC_HANDLE = 1914; /// Invalid asynchronous RPC call handle for this operation. pub const RPC_S_INVALID_ASYNC_CALL = 1915; /// The RPC pipe object has already been closed. pub const RPC_X_PIPE_CLOSED = 1916; /// The RPC call completed before all pipes were processed. pub const RPC_X_PIPE_DISCIPLINE_ERROR = 1917; /// No more data is available from the RPC pipe. pub const RPC_X_PIPE_EMPTY = 1918; /// No site name is available for this machine. pub const NO_SITENAME = 1919; /// The file cannot be accessed by the system. pub const CANT_ACCESS_FILE = 1920; /// The name of the file cannot be resolved by the system. pub const CANT_RESOLVE_FILENAME = 1921; /// The entry is not of the expected type. pub const RPC_S_ENTRY_TYPE_MISMATCH = 1922; /// Not all object UUIDs could be exported to the specified entry. pub const RPC_S_NOT_ALL_OBJS_EXPORTED = 1923; /// Interface could not be exported to the specified entry. pub const RPC_S_INTERFACE_NOT_EXPORTED = 1924; /// The specified profile entry could not be added. pub const RPC_S_PROFILE_NOT_ADDED = 1925; /// The specified profile element could not be added. pub const RPC_S_PRF_ELT_NOT_ADDED = 1926; /// The specified profile element could not be removed. pub const RPC_S_PRF_ELT_NOT_REMOVED = 1927; /// The group element could not be added. pub const RPC_S_GRP_ELT_NOT_ADDED = 1928; /// The group element could not be removed. pub const RPC_S_GRP_ELT_NOT_REMOVED = 1929; /// The printer driver is not compatible with a policy enabled on your computer that blocks NT 4.0 drivers. pub const KM_DRIVER_BLOCKED = 1930; /// The context has expired and can no longer be used. pub const CONTEXT_EXPIRED = 1931; /// The current user's delegated trust creation quota has been exceeded. pub const PER_USER_TRUST_QUOTA_EXCEEDED = 1932; /// The total delegated trust creation quota has been exceeded. pub const ALL_USER_TRUST_QUOTA_EXCEEDED = 1933; /// The current user's delegated trust deletion quota has been exceeded. pub const USER_DELETE_TRUST_QUOTA_EXCEEDED = 1934; /// The computer you are signing into is protected by an authentication firewall. The specified account is not allowed to authenticate to the computer. pub const AUTHENTICATION_FIREWALL_FAILED = 1935; /// Remote connections to the Print Spooler are blocked by a policy set on your machine. pub const REMOTE_PRINT_CONNECTIONS_BLOCKED = 1936; /// Authentication failed because NTLM authentication has been disabled. pub const NTLM_BLOCKED = 1937; /// Logon Failure: EAS policy requires that the user change their password before this operation can be performed. pub const PASSWORD_CHANGE_REQUIRED = 1938; /// The pixel format is invalid. pub const INVALID_PIXEL_FORMAT = 2000; /// The specified driver is invalid. pub const BAD_DRIVER = 2001; /// The window style or class attribute is invalid for this operation. pub const INVALID_WINDOW_STYLE = 2002; /// The requested metafile operation is not supported. pub const METAFILE_NOT_SUPPORTED = 2003; /// The requested transformation operation is not supported. pub const TRANSFORM_NOT_SUPPORTED = 2004; /// The requested clipping operation is not supported. pub const CLIPPING_NOT_SUPPORTED = 2005; /// The specified color management module is invalid. pub const INVALID_CMM = 2010; /// The specified color profile is invalid. pub const INVALID_PROFILE = 2011; /// The specified tag was not found. pub const TAG_NOT_FOUND = 2012; /// A required tag is not present. pub const TAG_NOT_PRESENT = 2013; /// The specified tag is already present. pub const DUPLICATE_TAG = 2014; /// The specified color profile is not associated with the specified device. pub const PROFILE_NOT_ASSOCIATED_WITH_DEVICE = 2015; /// The specified color profile was not found. pub const PROFILE_NOT_FOUND = 2016; /// The specified color space is invalid. pub const INVALID_COLORSPACE = 2017; /// Image Color Management is not enabled. pub const ICM_NOT_ENABLED = 2018; /// There was an error while deleting the color transform. pub const DELETING_ICM_XFORM = 2019; /// The specified color transform is invalid. pub const INVALID_TRANSFORM = 2020; /// The specified transform does not match the bitmap's color space. pub const COLORSPACE_MISMATCH = 2021; /// The specified named color index is not present in the profile. pub const INVALID_COLORINDEX = 2022; /// The specified profile is intended for a device of a different type than the specified device. pub const PROFILE_DOES_NOT_MATCH_DEVICE = 2023; /// The network connection was made successfully, but the user had to be prompted for a password other than the one originally specified. pub const CONNECTED_OTHER_PASSWORD = <PASSWORD>; /// The network connection was made successfully using default credentials. pub const CONNECTED_OTHER_PASSWORD_DEFAULT = <PASSWORD>; /// The specified username is invalid. pub const BAD_USERNAME = 2202; /// This network connection does not exist. pub const NOT_CONNECTED = 2250; /// This network connection has files open or requests pending. pub const OPEN_FILES = 2401; /// Active connections still exist. pub const ACTIVE_CONNECTIONS = 2402; /// The device is in use by an active process and cannot be disconnected. pub const DEVICE_IN_USE = 2404; /// The specified print monitor is unknown. pub const UNKNOWN_PRINT_MONITOR = 3000; /// The specified printer driver is currently in use. pub const PRINTER_DRIVER_IN_USE = 3001; /// The spool file was not found. pub const SPOOL_FILE_NOT_FOUND = 3002; /// A StartDocPrinter call was not issued. pub const SPL_NO_STARTDOC = 3003; /// An AddJob call was not issued. pub const SPL_NO_ADDJOB = 3004; /// The specified print processor has already been installed. pub const PRINT_PROCESSOR_ALREADY_INSTALLED = 3005; /// The specified print monitor has already been installed. pub const PRINT_MONITOR_ALREADY_INSTALLED = 3006; /// The specified print monitor does not have the required functions. pub const INVALID_PRINT_MONITOR = 3007; /// The specified print monitor is currently in use. pub const PRINT_MONITOR_IN_USE = 3008; /// The requested operation is not allowed when there are jobs queued to the printer. pub const PRINTER_HAS_JOBS_QUEUED = 3009; /// The requested operation is successful. Changes will not be effective until the system is rebooted. pub const SUCCESS_REBOOT_REQUIRED = 3010; /// The requested operation is successful. Changes will not be effective until the service is restarted. pub const SUCCESS_RESTART_REQUIRED = 3011; /// No printers were found. pub const PRINTER_NOT_FOUND = 3012; /// The printer driver is known to be unreliable. pub const PRINTER_DRIVER_WARNED = 3013; /// The printer driver is known to harm the system. pub const PRINTER_DRIVER_BLOCKED = 3014; /// The specified printer driver package is currently in use. pub const PRINTER_DRIVER_PACKAGE_IN_USE = 3015; /// Unable to find a core driver package that is required by the printer driver package. pub const CORE_DRIVER_PACKAGE_NOT_FOUND = 3016; /// The requested operation failed. A system reboot is required to roll back changes made. pub const FAIL_REBOOT_REQUIRED = 3017; /// The requested operation failed. A system reboot has been initiated to roll back changes made. pub const FAIL_REBOOT_INITIATED = 3018; /// The specified printer driver was not found on the system and needs to be downloaded. pub const PRINTER_DRIVER_DOWNLOAD_NEEDED = 3019; /// The requested print job has failed to print. A print system update requires the job to be resubmitted. pub const PRINT_JOB_RESTART_REQUIRED = 3020; /// The printer driver does not contain a valid manifest, or contains too many manifests. pub const INVALID_PRINTER_DRIVER_MANIFEST = 3021; /// The specified printer cannot be shared. pub const PRINTER_NOT_SHAREABLE = 3022; /// The operation was paused. pub const REQUEST_PAUSED = 3050; /// Reissue the given operation as a cached IO operation. pub const IO_REISSUE_AS_CACHED = 3950;
lib/std/os/windows/error.zig
const std = @import("std"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; fn get_input() !std.ArrayList(i32) { const f = try std.fs.cwd().openFile("inputs/day10.txt", .{ .read = true }); var file_contents = try f.reader().readAllAlloc( allocator, // file wont be bigger, RIGHT? 999_999_999, ); defer allocator.free(file_contents); var file_contents_trimmed = std.mem.trim(u8, file_contents, "\n"); var data = std.ArrayList(i32).init(allocator); var lines = std.mem.split(file_contents_trimmed, "\n"); while (lines.next()) |line| { try data.append(try std.fmt.parseInt(i32, line, 10)); } return data; } fn part1() i32 { var data = get_input() catch unreachable; defer data.deinit(); std.sort.sort(i32, data.items, {}, comptime std.sort.asc(i32)); data.insert(0, 0) catch unreachable; data.append(data.items[data.items.len - 1] + 3) catch unreachable; var ones: i32 = 0; var threes: i32 = 0; var i: usize = 1; while (i < data.items.len) : (i += 1) { const diff = data.items[i] - data.items[i - 1]; if (diff == 1) { ones += 1; } else if (diff == 3) { threes += 1; } } return ones * threes; } fn dp(data: std.ArrayList(i32), memo: *std.AutoHashMap(usize, usize), curr: usize) usize { if (memo.contains(curr)) { return memo.get(curr).?; } var res: usize = 0; var i: usize = 1; while (i <= 3) : (i += 1) { if (curr + i >= data.items.len) { break; } if (data.items[curr + i] - data.items[curr] <= 3) { res += dp(data, memo, curr + i); } } res = std.math.max(res, 1); memo.put(curr, res) catch unreachable; return res; } fn part2() usize { var data = get_input() catch unreachable; defer data.deinit(); std.sort.sort(i32, data.items, {}, comptime std.sort.asc(i32)); data.insert(0, 0) catch unreachable; data.append(data.items[data.items.len - 1] + 3) catch unreachable; var memo = std.AutoHashMap(usize, usize).init(allocator); defer memo.deinit(); return dp(data, &memo, 0); } pub fn main() void { std.debug.print("day 10:\n\tpart 1: {}\n\tpart 2: {}\n", .{ part1(), part2() }); }
src/day10.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; }; const Sprite = @This(); // Constructor/destructor /// Inits a sprite with no texture pub fn create() !Sprite { var sprite = sf.c.sfSprite_create(); if (sprite == null) return sf.Error.nullptrUnknownReason; return Sprite{ ._ptr = sprite.? }; } /// Inits a sprite with a texture pub fn createFromTexture(texture: sf.Texture) !Sprite { var sprite = sf.c.sfSprite_create(); if (sprite == null) return sf.Error.nullptrUnknownReason; sf.c.sfSprite_setTexture(sprite, texture._get(), 1); return Sprite{ ._ptr = sprite.? }; } /// Destroys this sprite pub fn destroy(self: *Sprite) void { sf.c.sfSprite_destroy(self._ptr); } // Draw function pub fn sfDraw(self: Sprite, window: anytype, states: ?*sf.c.sfRenderStates) void { switch (@TypeOf(window)) { sf.RenderWindow => sf.c.sfRenderWindow_drawSprite(window._ptr, self._ptr, states), sf.RenderTexture => sf.c.sfRenderTexture_drawSprite(window._ptr, self._ptr, states), else => @compileError("window must be a render target"), } } // Getters/setters /// Gets the position of this sprite pub fn getPosition(self: Sprite) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfSprite_getPosition(self._ptr)); } /// Sets the position of this sprite pub fn setPosition(self: *Sprite, pos: sf.Vector2f) void { sf.c.sfSprite_setPosition(self._ptr, pos._toCSFML()); } /// Adds the offset to this shape's position pub fn move(self: *Sprite, offset: sf.Vector2f) void { sf.c.sfSprite_move(self._ptr, offset._toCSFML()); } /// Gets the scale of this sprite pub fn getScale(self: Sprite) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfSprite_getScale(self._ptr)); } /// Sets the scale of this sprite pub fn setScale(self: *Sprite, factor: sf.Vector2f) void { sf.c.sfSprite_setScale(self._ptr, factor._toCSFML()); } /// Scales this sprite pub fn scale(self: *Sprite, factor: sf.Vector2f) void { sf.c.sfSprite_scale(self._ptr, factor._toCSFML()); } /// Gets the origin of this sprite pub fn getOrigin(self: Sprite) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfSprite_getOrigin(self._ptr)); } /// Sets the origin of this sprite pub fn setOrigin(self: *Sprite, origin: sf.Vector2f) void { sf.c.sfSprite_setOrigin(self._ptr, origin._toCSFML()); } /// Gets the rotation of this sprite pub fn getRotation(self: Sprite) f32 { return sf.c.sfSprite_getRotation(self._ptr); } /// Sets the rotation of this sprite pub fn setRotation(self: *Sprite, angle: f32) void { sf.c.sfSprite_setRotation(self._ptr, angle); } /// Rotates this shape by a given amount pub fn rotate(self: *Sprite, angle: f32) void { sf.c.sfSprite_rotate(self._ptr, angle); } /// Gets the color of this sprite pub fn getColor(self: Sprite) sf.Color { return sf.Color._fromCSFML(sf.c.sfSprite_getColor(self._ptr)); } /// Sets the color of this sprite pub fn setColor(self: *Sprite, color: sf.Color) void { sf.c.sfSprite_setColor(self._ptr, color._toCSFML()); } /// Gets the texture of this shape pub fn getTexture(self: Sprite) ?sf.Texture { const t = sf.c.sfSprite_getTexture(self._ptr); if (t) |tex| { return sf.Texture{ ._const_ptr = tex }; } else return null; } /// Sets this sprite's texture (the sprite will take the texture's dimensions) pub fn setTexture(self: *Sprite, texture: ?sf.Texture) void { var tex = if (texture) |t| t._get() else null; sf.c.sfSprite_setTexture(self._ptr, tex, 1); } /// Gets the sub-rectangle of the texture that the sprite will display pub fn getTextureRect(self: Sprite) sf.IntRect { return sf.IntRect._fromCSFML(sf.c.sfSprite_getTextureRect(self._ptr)); } /// Sets the sub-rectangle of the texture that the sprite will display pub fn setTextureRect(self: *Sprite, rect: sf.IntRect) void { sf.c.sfSprite_setTextureRect(self._ptr, rect._toCSFML()); } /// Pointer to the csfml structure _ptr: *sf.c.sfSprite, test "sprite: sane getters and setters" { const tst = @import("std").testing; var spr = try Sprite.create(); defer spr.destroy(); spr.setColor(sf.Color.Yellow); spr.setRotation(15); spr.setPosition(.{ .x = 1, .y = 2 }); spr.setOrigin(.{ .x = 20, .y = 25 }); spr.setScale(.{ .x = 2, .y = 2 }); spr.setTexture(null); try tst.expectEqual(sf.Color.Yellow, spr.getColor()); try tst.expectEqual(sf.Vector2f{ .x = 1, .y = 2 }, spr.getPosition()); try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, spr.getOrigin()); try tst.expectEqual(@as(?sf.Texture, null), spr.getTexture()); try tst.expectEqual(sf.Vector2f{ .x = 2, .y = 2 }, spr.getScale()); spr.rotate(5); spr.move(.{ .x = -5, .y = 5 }); spr.scale(.{ .x = 5, .y = 5 }); try tst.expectEqual(@as(f32, 20), spr.getRotation()); try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, spr.getPosition()); try tst.expectEqual(sf.Vector2f{ .x = 10, .y = 10 }, spr.getScale()); }
src/sfml/graphics/Sprite.zig
const sf = struct { pub usingnamespace @import("../sfml.zig"); pub usingnamespace sf.system; pub usingnamespace sf.graphics; }; const Text = @This(); // Constructor/destructor /// Inits an empty text pub fn create() !Text { var text = sf.c.sfText_create(); if (text == null) return sf.Error.nullptrUnknownReason; return Text{ ._ptr = text.? }; } /// Inits a text with content pub fn createWithText(string: [:0]const u8, font: sf.Font, character_size: usize) !Text { var text = sf.c.sfText_create(); if (text == null) return sf.Error.nullptrUnknownReason; sf.c.sfText_setFont(text, font._ptr); sf.c.sfText_setCharacterSize(text, @intCast(c_uint, character_size)); sf.c.sfText_setString(text, string); return Text{ ._ptr = text.? }; } /// Destroys a text pub fn destroy(self: *Text) void { sf.c.sfText_destroy(self._ptr); } // Draw function pub fn sfDraw(self: Text, window: anytype, states: ?*sf.c.sfRenderStates) void { switch (@TypeOf(window)) { sf.RenderWindow => sf.c.sfRenderWindow_drawText(window._ptr, self._ptr, states), sf.RenderTexture => sf.c.sfRenderTexture_drawText(window._ptr, self._ptr, states), else => @compileError("window must be a render target"), } } // Getters/setters /// Sets the content of this text pub fn setString(self: *Text, string: [:0]const u8) void { sf.c.sfText_setString(self._ptr, string); } /// Sets the font of this text pub fn setFont(self: *Text, font: sf.Font) void { sf.c.sfText_setFont(self._ptr, font._ptr); } /// Gets the character size of this text pub fn getCharacterSize(self: Text) usize { return @intCast(usize, sf.c.sfText_getCharacterSize(self._ptr)); } /// Sets the character size of this text pub fn setCharacterSize(self: *Text, character_size: usize) void { sf.c.sfText_setCharacterSize(self._ptr, @intCast(c_uint, character_size)); } /// Gets the fill color of this text pub fn getFillColor(self: Text) sf.Color { return sf.Color._fromCSFML(sf.c.sfText_getFillColor(self._ptr)); } /// Sets the fill color of this text pub fn setFillColor(self: *Text, color: sf.Color) void { sf.c.sfText_setFillColor(self._ptr, color._toCSFML()); } /// Gets the outline color of this text pub fn getOutlineColor(self: Text) sf.Color { return sf.Color._fromCSFML(sf.c.sfText_getOutlineColor(self._ptr)); } /// Sets the outline color of this text pub fn setOutlineColor(self: *Text, color: sf.Color) void { sf.c.sfText_setOutlineColor(self._ptr, color._toCSFML()); } /// Gets the outline thickness of this text pub fn getOutlineThickness(self: Text) f32 { return sf.c.sfText_getOutlineThickness(self._ptr); } /// Sets the outline thickness of this text pub fn setOutlineThickness(self: *Text, thickness: f32) void { sf.c.sfText_setOutlineThickness(self._ptr, thickness); } /// Gets the position of this text pub fn getPosition(self: Text) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfText_getPosition(self._ptr)); } /// Sets the position of this text pub fn setPosition(self: *Text, pos: sf.Vector2f) void { sf.c.sfText_setPosition(self._ptr, pos._toCSFML()); } /// Adds the offset to this text pub fn move(self: *Text, offset: sf.Vector2f) void { sf.c.sfText_move(self._ptr, offset._toCSFML()); } /// Gets the origin of this text pub fn getOrigin(self: Text) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfText_getOrigin(self._ptr)); } /// Sets the origin of this text pub fn setOrigin(self: *Text, origin: sf.Vector2f) void { sf.c.sfText_setOrigin(self._ptr, origin._toCSFML()); } /// Gets the rotation of this text pub fn getRotation(self: Text) f32 { return sf.c.sfText_getRotation(self._ptr); } /// Sets the rotation of this text pub fn setRotation(self: *Text, angle: f32) void { sf.c.sfText_setRotation(self._ptr, angle); } /// Rotates this text by a given amount pub fn rotate(self: *Text, angle: f32) void { sf.c.sfText_rotate(self._ptr, angle); } /// Gets the scale of this text pub fn getScale(self: Text) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfText_getScale(self._ptr)); } /// Sets the scale of this text pub fn setScale(self: *Text, factor: sf.Vector2f) void { sf.c.sfText_setScale(self._ptr, factor._toCSFML()); } /// Scales this text pub fn scale(self: *Text, factor: sf.Vector2f) void { sf.c.sfText_scale(self._ptr, factor._toCSFML()); } /// return the position of the index-th character pub fn findCharacterPos(self: Text, index: usize) sf.Vector2f { return sf.Vector2f._fromCSFML(sf.c.sfText_findCharacterPos(self._ptr, index)); } /// Gets the letter spacing factor pub fn getLetterSpacing(self: Text) f32 { return sf.c.sfText_getLetterSpacing(self._ptr); } /// Sets the letter spacing factor pub fn setLetterSpacing(self: *Text, spacing_factor: f32) void { sf.c.sfText_setLetterSpacing(self._ptr, spacing_factor); } /// Gets the line spacing factor pub fn getLineSpacing(self: Text) f32 { return sf.c.sfText_getLineSpacing(self._ptr); } /// Sets the line spacing factor pub fn setLineSpacing(self: *Text, spacing_factor: f32) void { sf.c.sfText_setLineSpacing(self._ptr, spacing_factor); } /// Gets the local bounding rectangle of the text pub fn getLocalBounds(self: Text) sf.FloatRect { return sf.FloatRect._fromCSFML(sf.c.sfText_getLocalBounds(self._ptr)); } /// Gets the global bounding rectangle of the text pub fn getGlobalBounds(self: Text) sf.FloatRect { return sf.FloatRect._fromCSFML(sf.c.sfText_getGlobalBounds(self._ptr)); } pub const getTransform = @compileError("Function is not implemented yet."); pub const getInverseTransform = @compileError("Function is not implemented yet."); /// Pointer to the csfml font _ptr: *sf.c.sfText, test "text: sane getters and setters" { const tst = @import("std").testing; var text = try Text.create(); defer text.destroy(); text.setString("hello"); text.setFillColor(sf.Color.Yellow); text.setOutlineColor(sf.Color.Red); text.setOutlineThickness(2); text.setCharacterSize(10); text.setRotation(15); text.setPosition(.{ .x = 1, .y = 2 }); text.setOrigin(.{ .x = 20, .y = 25 }); text.setScale(.{ .x = 2, .y = 2 }); text.rotate(5); text.move(.{ .x = -5, .y = 5 }); text.scale(.{ .x = 2, .y = 3 }); try tst.expectEqual(sf.Color.Yellow, text.getFillColor()); try tst.expectEqual(sf.Color.Red, text.getOutlineColor()); try tst.expectEqual(@as(f32, 2), text.getOutlineThickness()); try tst.expectEqual(@as(usize, 10), text.getCharacterSize()); try tst.expectEqual(@as(f32, 20), text.getRotation()); try tst.expectEqual(sf.Vector2f{ .x = -4, .y = 7 }, text.getPosition()); try tst.expectEqual(sf.Vector2f{ .x = 20, .y = 25 }, text.getOrigin()); try tst.expectEqual(sf.Vector2f{ .x = 4, .y = 6 }, text.getScale()); _ = text.getLocalBounds(); _ = text.getGlobalBounds(); }
src/sfml/graphics/Text.zig
const std = @import("std"); const root = @import("main.zig"); const math = std.math; const panic = std.debug.panic; const testing = std.testing; pub const Vec4 = Vector4(f32); pub const Vec4_f64 = Vector4(f64); pub const Vec4_i32 = Vector4(i32); /// A 4 dimensional vector. pub fn Vector4(comptime T: type) type { if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) { @compileError("Vector4 not implemented for " ++ @typeName(T)); } return struct { x: T, y: T, z: T, w: T, const Self = @This(); /// Constract vector from given 3 components. pub fn new(x: T, y: T, z: T, w: T) Self { return Self{ .x = x, .y = y, .z = z, .w = w, }; } /// Set all components to the same given value. pub fn set(val: T) Self { return Self.new(val, val, val, val); } pub fn zero() Self { return Self.new(0, 0, 0, 0); } pub fn one() Self { return Self.new(1, 1, 1, 1); } /// Negate the given vector. pub fn negate(self: Self) Self { return self.scale(-1); } /// Cast a type to another type. Only for integers and floats. /// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt pub fn cast(self: Self, dest: anytype) Vector4(dest) { const source_info = @typeInfo(T); const dest_info = @typeInfo(dest); if (source_info == .Float and dest_info == .Int) { const x = @floatToInt(dest, self.x); const y = @floatToInt(dest, self.y); const z = @floatToInt(dest, self.z); const w = @floatToInt(dest, self.w); return Vector4(dest).new(x, y, z, w); } if (source_info == .Int and dest_info == .Float) { const x = @intToFloat(dest, self.x); const y = @intToFloat(dest, self.y); const z = @intToFloat(dest, self.z); const w = @intToFloat(dest, self.w); return Vector4(dest).new(x, y, z, w); } return switch (dest_info) { .Float => { const x = @floatCast(dest, self.x); const y = @floatCast(dest, self.y); const z = @floatCast(dest, self.z); const w = @floatCast(dest, self.w); return Vector4(dest).new(x, y, z, w); }, .Int => { const x = @intCast(dest, self.x); const y = @intCast(dest, self.y); const z = @intCast(dest, self.z); const w = @intCast(dest, self.w); return Vector4(dest).new(x, y, z, w); }, else => panic( "Error, given type should be integers or float.\n", .{}, ), }; } /// Construct new vector from slice. pub fn fromSlice(slice: []const T) Self { return Self.new(slice[0], slice[1], slice[2], slice[3]); } /// Transform vector to array. pub fn toArray(self: Self) [4]T { return .{ self.x, self.y, self.z, self.w }; } /// Compute the length (magnitude) of given vector |a|. pub fn length(self: Self) T { return math.sqrt( (self.x * self.x) + (self.y * self.y) + (self.z * self.z) + (self.w * self.w), ); } /// Compute the distance between two points. pub fn distance(a: Self, b: Self) T { return math.sqrt( math.pow(T, b.x - a.x, 2) + math.pow(T, b.y - a.y, 2) + math.pow(T, b.z - a.z, 2) + math.pow(T, b.w - a.w, 2), ); } /// Construct new normalized vector from a given vector. pub fn norm(self: Self) Self { var l = length(self); return Self.new(self.x / l, self.y / l, self.z / l, self.w / l); } pub fn eql(left: Self, right: Self) bool { return left.x == right.x and left.y == right.y and left.z == right.z and left.w == right.w; } /// Substraction between two given vector. pub fn sub(left: Self, right: Self) Self { return Self.new( left.x - right.x, left.y - right.y, left.z - right.z, left.w - right.w, ); } /// Addition betwen two given vector. pub fn add(left: Self, right: Self) Self { return Self.new( left.x + right.x, left.y + right.y, left.z + right.z, left.w + right.w, ); } /// Multiply each components by the given scalar. pub fn scale(v: Self, scalar: T) Self { return Self.new( v.x * scalar, v.y * scalar, v.z * scalar, v.w * scalar, ); } /// Return the dot product between two given vector. pub fn dot(left: Self, right: Self) T { return (left.x * right.x) + (left.y * right.y) + (left.z * right.z) + (left.w * right.w); } /// Lerp between two vectors. pub fn lerp(left: Self, right: Self, t: T) Self { const x = root.lerp(T, left.x, right.x, t); const y = root.lerp(T, left.y, right.y, t); const z = root.lerp(T, left.z, right.z, t); const w = root.lerp(T, left.w, right.w, t); return Self.new(x, y, z, w); } /// Construct a new vector from the min components between two vectors. pub fn min(left: Self, right: Self) Self { return Self.new( math.min(left.x, right.x), math.min(left.y, right.y), math.min(left.z, right.z), math.min(left.w, right.w), ); } /// Construct a new vector from the max components between two vectors. pub fn max(left: Self, right: Self) Self { return Self.new( math.max(left.x, right.x), math.max(left.y, right.y), math.max(left.z, right.z), math.max(left.w, right.w), ); } }; } test "zalgebra.Vec4.init" { var _vec_0 = Vec4.new(1.5, 2.6, 3.7, 4.7); try testing.expectEqual(_vec_0.x, 1.5); try testing.expectEqual(_vec_0.y, 2.6); try testing.expectEqual(_vec_0.z, 3.7); try testing.expectEqual(_vec_0.w, 4.7); } test "zalgebra.Vec4.eql" { var _vec_0 = Vec4.new(1, 2, 3, 4); var _vec_1 = Vec4.new(1, 2, 3, 4); var _vec_2 = Vec4.new(1, 2, 3, 5); try testing.expectEqual(Vec4.eql(_vec_0, _vec_1), true); try testing.expectEqual(Vec4.eql(_vec_0, _vec_2), false); } test "zalgebra.Vec4.set" { var _vec_0 = Vec4.new(2.5, 2.5, 2.5, 2.5); var _vec_1 = Vec4.set(2.5); try testing.expectEqual(Vec4.eql(_vec_0, _vec_1), true); } test "zalgebra.Vec4.negate" { var a = Vec4.set(5); var b = Vec4.set(-5); try testing.expectEqual(Vec4.eql(a.negate(), b), true); } test "zalgebra.Vec2.toArray" { const _vec_0 = Vec4.new(0, 1, 0, 1).toArray(); const _vec_1 = [_]f32{ 0, 1, 0, 1 }; try testing.expectEqual(std.mem.eql(f32, &_vec_0, &_vec_1), true); } test "zalgebra.Vec4.length" { var _vec_0 = Vec4.new(1.5, 2.6, 3.7, 4.7); try testing.expectEqual(_vec_0.length(), 6.69253301); } test "zalgebra.Vec4.distance" { var a = Vec4.new(0, 0, 0, 0); var b = Vec4.new(-1, 0, 0, 0); var c = Vec4.new(0, 5, 0, 0); try testing.expectEqual(Vec4.distance(a, b), 1); try testing.expectEqual(Vec4.distance(a, c), 5); } test "zalgebra.Vec4.normalize" { var _vec_0 = Vec4.new(1.5, 2.6, 3.7, 4.0); try testing.expectEqual(Vec4.eql( _vec_0.norm(), Vec4.new(0.241121411, 0.417943745, 0.594766139, 0.642990410), ), true); } test "zalgebra.Vec4.sub" { var _vec_0 = Vec4.new(1, 2, 3, 6); var _vec_1 = Vec4.new(2, 2, 3, 5); try testing.expectEqual(Vec4.eql( Vec4.sub(_vec_0, _vec_1), Vec4.new(-1, 0, 0, 1), ), true); } test "zalgebra.Vec4.add" { var _vec_0 = Vec4.new(1, 2, 3, 5); var _vec_1 = Vec4.new(2, 2, 3, 6); try testing.expectEqual(Vec4.eql( Vec4.add(_vec_0, _vec_1), Vec4.new(3, 4, 6, 11), ), true); } test "zalgebra.Vec4.scale" { var _vec_0 = Vec4.new(1, 2, 3, 4); try testing.expectEqual(Vec4.eql( Vec4.scale(_vec_0, 5), Vec4.new(5, 10, 15, 20), ), true); } test "zalgebra.Vec4.dot" { var _vec_0 = Vec4.new(1.5, 2.6, 3.7, 5); var _vec_1 = Vec4.new(2.5, 3.45, 1.0, 1); try testing.expectEqual(Vec4.dot(_vec_0, _vec_1), 21.4200000); } test "zalgebra.Vec4.lerp" { var _vec_0 = Vec4.new(-10.0, 0.0, -10.0, -10.0); var _vec_1 = Vec4.new(10.0, 10.0, 10.0, 10.0); try testing.expectEqual(Vec4.eql( Vec4.lerp(_vec_0, _vec_1, 0.5), Vec4.new(0.0, 5.0, 0.0, 0.0), ), true); } test "zalgebra.Vec4.min" { var _vec_0 = Vec4.new(10.0, -2.0, 0.0, 1.0); var _vec_1 = Vec4.new(-10.0, 5.0, 0.0, 1.01); try testing.expectEqual(Vec4.eql( Vec4.min(_vec_0, _vec_1), Vec4.new(-10.0, -2.0, 0.0, 1.0), ), true); } test "zalgebra.Vec4.max" { var _vec_0 = Vec4.new(10.0, -2.0, 0.0, 1.0); var _vec_1 = Vec4.new(-10.0, 5.0, 0.0, 1.01); try testing.expectEqual(Vec4.eql( Vec4.max(_vec_0, _vec_1), Vec4.new(10.0, 5.0, 0.0, 1.01), ), true); } test "zalgebra.Vec2.fromSlice" { const array = [4]f32{ 2, 4, 3, 6 }; try testing.expectEqual(Vec4.eql( Vec4.fromSlice(&array), Vec4.new(2, 4, 3, 6), ), true); } test "zalgebra.Vec4.cast" { const a = Vec4_i32.new(3, 6, 2, 0); const b = Vector4(usize).new(3, 6, 2, 0); try testing.expectEqual( Vector4(usize).eql(a.cast(usize), b), true, ); const c = Vec4.new(3.5, 6.5, 2.0, 0); const d = Vec4_f64.new(3.5, 6.5, 2, 0.0); try testing.expectEqual( Vec4_f64.eql(c.cast(f64), d), true, ); const e = Vec4_i32.new(3, 6, 2, 0); const f = Vec4.new(3.0, 6.0, 2.0, 0.0); try testing.expectEqual( Vec4.eql(e.cast(f32), f), true, ); const g = Vec4.new(3.0, 6.0, 2.0, 0.0); const h = Vec4_i32.new(3, 6, 2, 0); try testing.expectEqual( Vec4_i32.eql(g.cast(i32), h), true, ); }
src/vec4.zig
const std = @import("std"); const sqlite = @import("sqlite"); const string = []const u8; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = &gpa.allocator; const Employee = struct { id: [128:0]u8, name: [128:0]u8, age: usize, salary: usize, }; pub fn main() anyerror!void { std.os.unlink("./testfile.db") catch { std.log.info("no exsiting DB to delete\n", .{}); }; var db: sqlite.Db = undefined; try db.init(.{ .mode = sqlite.Db.Mode{ .File = "./testfile.db" }, .open_flags = .{ .write = true, .create = true, }, .threading_mode = .MultiThread, }); var create = try db.prepare("CREATE TABLE employees (id text, name text, age int, salary int)"); defer create.deinit(); try create.exec(.{}); var add = try db.prepare("INSERT INTO employees (id, name, age, salary) VALUES (?,?,?,?)"); defer add.deinit(); add.reset(); try add.exec(.{ "ABC", "Mr Smith", 33, 12000 }); add.reset(); try add.exec(.{ "DEF", "Mr Jones", 32, 11000 }); add.reset(); try add.exec(.{ "GHI", "Mr Wayne", 31, 14000 }); add.reset(); try add.exec(.{ "JKL", "Mr Fred", 38, 12000 }); add.reset(); try add.exec(.{ "MNO", "Mr Smythe", 36, 11000 }); add.reset(); try add.exec(.{ "PQR", "Mr Tonsil", 30, 11000 }); add.reset(); try add.exec(.{ "STU", "Mr Fancypants", 22, 8000 }); add.reset(); try add.exec(.{ "VXY", "Mr Thing", 24, 7000 }); add.reset(); try add.exec(.{ "ZZZ", "Mr What", 27, 6000 }); var select = try db.prepare("SELECT id,name,age,salary FROM employees ORDER BY salary DESC LIMIT 5"); defer select.deinit(); var iter = try select.iterator(Employee, .{}); while (try iter.next(.{})) |row| { std.log.info("name: {s}, age: {}, id: {s}, salary: {}", .{ std.mem.spanZ(&row.name), row.age, std.mem.spanZ(&row.id), row.salary }); } } test "test" { std.debug.print("Tests pass\n", .{}); std.testing.expect(true); }
src/main.zig
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "Platform", .filter = .info, }).write; // Submodules pub const acpi = @import("acpi.zig"); pub const pci = @import("pci.zig"); pub const devicetree = @import("devicetree.zig"); pub const smp = @import("smp.zig"); // Anything else comes from this platform specific file pub const arch = if (@hasField(std.builtin, "arch")) std.builtin.arch else std.Target.current.cpu.arch; pub const endian = if (@hasField(std.builtin, "endian")) std.builtin.endian else arch.endian(); usingnamespace @import(switch (arch) { .aarch64 => "aarch64/aarch64.zig", .x86_64 => "x86_64/x86_64.zig", else => unreachable, }); const assert = @import("std").debug.assert; pub const PageFaultAccess = enum { Read, Write, InstructionFetch, }; fn attempt_handle_physmem_page_fault(base: usize, addr: usize, map_type: os.platform.paging.MemoryType) bool { if (base <= addr and addr < base + os.memory.paging.kernel_context.max_phys) { // Map 1G of this memory const phys = addr - base; const phys_gb_aligned = lib.util.libalign.alignDown(usize, 1024 * 1024 * 1024, phys); os.vital(os.memory.paging.mapPhys(.{ .virt = base + phys_gb_aligned, .phys = phys_gb_aligned, .size = 1024 * 1024 * 1024, .perm = os.memory.paging.rw(), .memtype = map_type, }), "Lazily mapping physmem"); return true; } return false; } fn handle_physmem_page_fault(addr: usize) bool { const context = &os.memory.paging.kernel_context; if (attempt_handle_physmem_page_fault(context.wb_virt_base, addr, .MemoryWriteBack)) { return true; } if (attempt_handle_physmem_page_fault(context.wc_virt_base, addr, .DeviceWriteCombining)) { return true; } if (attempt_handle_physmem_page_fault(context.uc_virt_base, addr, .DeviceUncacheable)) { return true; } return false; } pub fn page_fault(addr: usize, present: bool, access: PageFaultAccess, frame: anytype) void { // We lazily map some physical memory, see if this is what's happening if (!present) { switch (access) { .Read, .Write => if (handle_physmem_page_fault(addr)) return, else => {}, } } log(null, "Platform: Unhandled page fault on {e} at 0x{X}, present: {b}", .{ access, addr, present, }); log(null, "Frame dump:\n{}", .{frame}); frame.trace_stack(); @panic("Page fault"); } pub fn hang() noreturn { _ = get_and_disable_interrupts(); while (true) { await_interrupt(); } } pub fn set_current_task(task_ptr: *os.thread.Task) void { thread.get_current_cpu().current_task = task_ptr; } pub fn get_current_task() *os.thread.Task { return thread.get_current_cpu().current_task; } pub const virt_slice = struct { ptr: usize, len: usize, }; pub fn phys_ptr(comptime ptr_type: type) type { return struct { addr: usize, pub fn get_writeback(self: *const @This()) ptr_type { return @intToPtr(ptr_type, os.memory.paging.physToWriteBackVirt(self.addr)); } pub fn get_write_combining(self: *const @This()) ptr_type { return @intToPtr(ptr_type, os.memory.paging.physToWriteCombiningVirt(self.addr)); } pub fn get_uncached(self: *const @This()) ptr_type { return @intToPtr(ptr_type, os.memory.paging.physToUncachedVirt(self.addr)); } pub fn from_int(a: usize) @This() { return .{ .addr = a, }; } pub fn cast(self: *const @This(), comptime to_type: type) phys_ptr(to_type) { return .{ .addr = self.addr, }; } pub fn format(self: *const @This(), fmt: anytype) void { fmt("phys 0x{X}", .{self.addr}); } }; } pub fn phys_slice(comptime T: type) type { return struct { ptr: phys_ptr([*]T), len: usize, pub fn init(addr: usize, len: usize) @This() { return .{ .ptr = phys_ptr([*]T).from_int(addr), .len = len, }; } pub fn to_slice_writeback(self: *const @This()) []T { return self.ptr.get_writeback()[0..self.len]; } pub fn to_slice_write_combining(self: *const @This()) []T { return self.ptr.get_write_combining()[0..self.len]; } pub fn to_slice_uncached(self: *const @This()) []T { return self.ptr.get_uncached()[0..self.len]; } }; } pub const PhysBytes = struct { ptr: usize, len: usize, }; /// Helper for calling functions on scheduler stack pub fn sched_call(fun: fn (*os.platform.InterruptFrame, usize) void, ctx: usize) void { const state = os.platform.get_and_disable_interrupts(); os.platform.thread.sched_call_impl(@ptrToInt(fun), ctx); os.platform.set_interrupts(state); }
subprojects/flork/src/platform/platform.zig
const std = @import("std"); const testing = std.testing; const fs = std.fs; const File = fs.File; const expect = std.testing.expect; const print = std.debug.print; const parseInt = std.fmt.parseInt; var arena: std.heap.ArenaAllocator = undefined; var allocator: *std.mem.Allocator = undefined; var fb0: File = undefined; var mouse0: File = undefined; pub var bitmap: []u8 = undefined; pub var display_size: Size = undefined; pub var bytes_per_pixel: u8 = undefined; pub const Point = struct { x: i16, y: i16 }; pub const Position = struct { x: u16, y: u16 }; pub const Size = struct { x: u16, y: u16 }; pub const Mouse = struct { dx: i8 = 0, dy: i8 = 0, lmb: bool = false, // left mouse button rmb: bool = false, // right mouse button }; pub const ParseError = error{ SeparatorNotFound, NoIntegerValue, }; ///`pub fn init() !void` call once before other functions. pub fn init() !void { fb0 = try fs.openFileAbsolute("/dev/fb0", .{ .write = true }); // user needs to be in group input: $ sudo adduser username input mouse0 = try fs.openFileAbsolute("/dev/input/mouse0", .{ .read = true }); bytes_per_pixel = (try bitsPerPixel()) / 8; display_size = try resolution(); arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); allocator = &arena.allocator; const mem_size: u32 = @as(u32, display_size.x) * @as(u32, display_size.y) * @as(u32, 4); bitmap = try allocator.alloc(u8, mem_size); } ///`pub fn exit() void` call after using other functions. pub fn exit() void { fb0.close(); mouse0.close(); allocator.free(bitmap); arena.deinit(); } test "files exists" { try fs.accessAbsolute("/sys/class/graphics/fb0/bits_per_pixel", .{ .read = true }); try fs.accessAbsolute("/sys/class/graphics/fb0/virtual_size", .{ .read = true }); try fs.accessAbsolute("/dev/fb0", .{ .write = true }); try fs.accessAbsolute("/dev/input/mouse0", .{ .read = true }); } pub fn bitsPerPixel() !u8 { var buf: [4]u8 = undefined; var size = try readNumber("/sys/class/graphics/fb0/bits_per_pixel", &buf); return std.fmt.parseInt(u8, buf[0..size], 10) catch { std.debug.print("bitsPerPixel(): {s} is no u8 value\n", .{buf[0..size]}); return ParseError.NoIntegerValue; }; } pub fn resolution() !Size { var buf: [15]u8 = undefined; var size = try readNumber("/sys/class/graphics/fb0/virtual_size", &buf); const separator = std.mem.indexOf(u8, buf[0..size], ","); if (separator == null) return ParseError.SeparatorNotFound; const width = std.fmt.parseInt(u16, buf[0..separator.?], 10) catch { print("width: {s} is no u16 value\n", .{buf[0..separator.?]}); return ParseError.NoIntegerValue; }; const height = std.fmt.parseInt(u16, buf[(separator.? + 1)..size], 10) catch { print("height: {s} is no u16 value\n", .{buf[(separator.? + 1)..size]}); return ParseError.NoIntegerValue; }; return Size{ .x = width, .y = height }; } pub fn readNumber(path: []const u8, buffer: []u8) !usize { var file = try fs.openFileAbsolute(path, .{ .read = true }); defer file.close(); var bytes_read = try file.readAll(buffer); // remove line feed at the end if (!std.ascii.isDigit(buffer[bytes_read])) { bytes_read -= 1; } return bytes_read; } pub fn flush() fs.File.PWriteError!void { try fb0.seekTo(0); _ = try fb0.write(bitmap); } pub fn flushBitmapStripe(offset: usize, len: usize) fs.File.PWriteError!void { try fb0.seekTo(offset); _ = try fb0.write(bitmap[offset..(offset + len)]); } pub fn flushData(data: []u8, offset: usize) fs.File.PWriteError!void { try fb0.seekTo(offset); _ = try fb0.write(data); } pub fn clear(color: [4]u8, size: u8) void { for (bitmap) |_, index| { bitmap[index] = color[index % size]; } } ///`pub fn readMouse() !Mouse` blocking call to read position offset and mouse button status. pub fn readMouse() !Mouse { var buf: [3]u8 = undefined; var bytes_read = try mouse0.readAll(&buf); return Mouse{ .dx = if (buf[1] >= 0x80) @intCast(i8, ~(buf[1] -% 1)) * -1 else @intCast(i8, buf[1]), .dy = if (buf[2] >= 0x80) @intCast(i8, ~(buf[2] -% 1)) * -1 else @intCast(i8, buf[2]), .lmb = (buf[0] & 0x01) == 0x01, .rmb = (buf[0] & 0x02) == 0x02, }; }
libs/core/pagez.zig
const std = @import("std"); const types = @import("types.zig"); const json = @import("json.zig"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const Value = std.json.Value; const js = json.json_serializer; const jd = json.json_deserializer; pub fn Method(comptime RequestType: type, comptime ResponseType: type) type { return struct { pub const Request = RequestType; pub const Response = ResponseType; }; } pub const core = struct { const capability_name = "urn:ietf:params:jmap:core"; const Capabilities = struct { /// The maximum file size, in octets, that the server will accept for a /// single file upload (for any purpose). max_size_upload: types.UnsignedInt = 50000000, /// The maximum number of concurrent requests the server will accept to the /// upload endpoint. max_concurrent_upload: types.UnsignedInt = 4, /// The maximum size, in octets, that the server will accept for a single /// request to the API endpoint. max_size_request: types.UnsignedInt = 10000000, /// The maximum number of concurrent requests the server will accept to the /// API endpoint. max_concurrent_requests: types.UnsignedInt = 4, /// The maximum number of method calls the server will accept in a single /// request to the API endpoint. max_calls_in_request: types.UnsignedInt = 16, /// The maximum number of objects that the client may request in a single /// /get type method call. max_objects_in_get: types.UnsignedInt = 500, /// The maximum number of objects the client may send to create, update, /// or destroy in a single /set type method call. max_objects_in_set: types.UnsignedInt = 500, /// A list of identifiers for algorithms registered in the collation /// registry, as defined in RFC 4790, that the server supports for /// sorting when querying records. collation_algorithms: []const []const u8, }; pub const Get = Method(GetRequest, GetResponse); pub const Changes = Method(ChangesRequest, ChangesResponse); pub const Set = Method(SetRequest, SetResponse); pub const Copy = Method(CopyRequest, CopyResponse); pub const Query = Method(QueryRequest, QueryResponse); pub const QueryChanges = Method(QueryChangesRequest, QueryChangesResponse); // TODO see if we can remove the memory copies in fromJson and toJson pub const CoreEchoRequest = struct { args: std.json.ObjectMap, pub fn fromJson(allocator: *Allocator, obj: Value) !CoreEchoRequest { if (obj != .Object) return error.CannotDeserialize; return .{ .args = std.mem.dupe(allocator, Value, obj) }; } pub fn toJson(self: CoreEchoRequest, allocator: *Allocator) !Value { return std.mem.dupe(allocator, Value, self.args); } pub fn handle(req: CoreEchoRequest) }; pub const GetRequest = struct { account_id: types.Id, ids: ?[]const types.Id, properties: ?[]const []const u8, }; pub fn GetResponse(comptime R: type) type { return struct { account_id: types.Id, state: []const u8, list: []const R, not_found: []const types.Id, }; } pub const ChangesRequest = struct { account_id: types.Id, since_state: []const u8, max_changes: ?types.UnsignedInt, }; pub const ChangesResponse = struct { account_id: types.Id, old_state: []const u8, new_state: []const u8, has_more_changes: bool, created: []const types.Id, updated: []const types.Id, destroyed: []const types.Id, }; pub const SetError = struct { type: []const u8, description: ?[]const u8, properties: ?[]const []const u8, }; pub fn SetRequest(comptime R: type) type { return struct { const Self = @This(); account_id: types.Id, if_in_state: ?[]const u8, create: ?JsonStringMap(R), // update is a mapping from Id to PatchObject, which is an arbitrary object based // on the properties of the type it represents. // TODO is this the best way to do this? update: ?std.json.ObjectMap, destroy: ?[]const types.Id, pub fn fromJson(allocator: *Allocator, obj: Value) !Self { if (std.meta.activeTag(obj) != .Object) { return error.CannotDeserialize; } var r: Self = undefined; const account_id = obj.getValue("accountId") orelse return error.CannotDeserialize; r.account_id = try jd.toJson(@TypeOf(r.account_id), allocator, account_id); const if_in_state = obj.getValue("ifInState") orelse return error.CannotDeserialize; r.if_in_state = try jd.toJson(@TypeOf(r.if_in_state), allocator, if_in_state); return result; } pub fn toJson(self: Self, allocator: *Allocator) !Value { var map = ObjectMap.init(allocator); try map.ensureCapacity(5); _ = map.putAssumeCapacity("accountId", js.toJson(self.account_id, allocator)); _ = map.putAssumeCapacity("ifInState", js.toJson(self.if_in_state, allocator)); _ = map.putAssumeCapacity("create", js.toJson(self.create, allocator)); _ = map.putAssumeCapacity("destroy", js.toJson(self.destroy, allocator)); const update = if (self.update) |unwrapped| Value{ .Object = unwrapped } else Value{ .Null = {} }; _ = map.putAssumeCapacity("update", update); return Value{ .Object = map }; } }; } pub fn SetResponse(comptime R: type) type { return struct { account_id: types.Id, old_state: ?[]const u8, new_state: []const u8, created: ?JsonStringMap(R), updated: ?JsonStringMap(?R), destroyed: ?[]const types.Id, not_created: ?JsonStringMap(SetError), not_updated: ?JsonStringMap(SetError), not_destroyed: ?JsonStringMap(SetError), }; } pub fn CopyRequest(comptime R: type) type { return struct { from_account_id: types.Id, ifFromInState: ?[]const u8, account_id: types.Id, if_in_state: ?[]const u8, create: JsonStringMap(R), on_success_destroy_original: bool = false, destroy_from_if_in_state: ?[]const u8, }; } pub fn CopyResponse(comptime R: type) type { return struct { from_account_id: types.Id, account_id: types.Id, old_state: ?[]const u8, new_state: []const u8, created: ?JsonStringMap(R), not_created: ?JsonStringMap(SetError), }; } pub fn custom_filter(comptime C: type) type { return struct { pub const FilterOperator = struct { operator: []const u8, conditions: []const Filter, }; pub const Filter = union(enum) { filter_operator: FilterOperator, filter_condition: C, }; }; } // TODO add "keyword" field for email objects pub const Comparator = struct { property: []const u8, is_ascending: bool = true, collation: []const u8, position: types.Int = 0, anchor: ?types.Id, anchor_offset: types.Int = 0, limit: ?types.UnsignedInt, calculate_total: bool = false, }; pub const QueryRequest = struct { account_id: types.Id, filter: ?Filter, sort: ?[]const Comparator, }; pub const QueryResponse = struct { account_id: types.Id, query_state: []const u8, can_calculate_changes: bool, position: types.UnsignedInt, ids: []const types.Id, total: ?types.UnsignedInt, limit: ?types.UnsignedInt, }; pub const QueryChangesRequest = struct { account_id: types.Id, filter: ?Filter, sort: ?[]const Comparator, since_query_state: []const u8, max_changes: ?types.UnsignedInt, up_to_id: ?types.Id, calculate_total: bool = false, }; pub const AddedItem = struct { id: types.Id, index: types.UnsignedInt, }; pub const QueryChangesResponse = struct { account_id: types.Id, old_query_state: []const u8, new_query_state: []const u8, total: ?types.UnsignedInt, removed: []const types.Id, added: []const AddedItem, }; }; const DownloadRequest = struct { account_id: types.Id, blobId: types.Id, type: []const u8, name: []const u8, }; const UploadResponse = struct { account_id: types.Id, blob_id: types.Id, type: []const u8, size: types.UnsignedInt, }; const BlobCopyRequest = struct { from_account_id: types.Id, account_id: types.Id, blob_ids: []const types.Id, }; const BlobCopyResponse = struct { from_account_id: types.Id, account_id: types.Id, copied: ?std.AutoHashMap(types.Id, types.Id), not_copied: ?std.AutoHashMap(types.Id, SetError), }; // TODO PushSubscription stuff
core.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const odbc = @import("odbc"); const EraseComptime = @import("util.zig").EraseComptime; /// This struct contains the information necessary to communicate with the ODBC driver /// about the type of a value. `sql_type` is often used to tell the driver how to convert /// the value into one that SQL will understand, whereas `c_type` is generally used so that /// the driver has a way to convert a `*anyopaque` or `[]u8` into a value. pub fn SqlParameter(comptime T: type) type { return struct { sql_type: odbc.Types.SqlType, c_type: odbc.Types.CType, precision: ?u16 = null, // Only for numeric types, not sure the best way to model this value: T, }; } /// Get the default SqlType and CType equivalents for an arbitrary value. If the value is a float, /// precision will be defaulted to `6`. If the value is a `comptime_int` or `comptime_float`, then /// it will be converted here to `i64` or `f64`, respectively. pub fn default(value: anytype) SqlParameter(EraseComptime(@TypeOf(value))) { const ValueType = EraseComptime(@TypeOf(value)); var result = SqlParameter(ValueType){ .value = value, .sql_type = comptime odbc.Types.SqlType.fromType(ValueType) orelse @compileError("Cannot get default SqlType for type " ++ @typeName(ValueType)), .c_type = comptime odbc.Types.CType.fromType(ValueType) orelse @compileError("Cannot get default CType for type " ++ @typeName(ValueType)), }; if (std.meta.trait.isFloat(@TypeOf(value))) { result.precision = 6; } return result; } pub const ParameterBucket = struct { pub const Param = struct { param: *anyopaque, indicator: *c_longlong, }; data: std.ArrayListAlignedUnmanaged(u8, null), param_indices: std.ArrayListUnmanaged(usize), indicators: []c_longlong, allocator: Allocator, pub fn init(allocator: Allocator, num_params: usize) !ParameterBucket { return ParameterBucket{ .allocator = allocator, .data = try std.ArrayListAlignedUnmanaged(u8, null).initCapacity(allocator, num_params * 8), .param_indices = try std.ArrayListUnmanaged(usize).initCapacity(allocator, num_params), .indicators = try allocator.alloc(c_longlong, num_params) }; } pub fn deinit(self: *ParameterBucket) void { self.data.deinit(self.allocator); self.param_indices.deinit(self.allocator); self.allocator.free(self.indicators); } /// Insert a parameter into the bucker at the given index. Old parameter data at the /// old index won't be overwritten, but old indicator values will be overwritten. pub fn addParameter(self: *ParameterBucket, index: usize, param: anytype) !Param { const ParamType = EraseComptime(@TypeOf(param)); const param_index = self.data.items.len; try self.param_indices.append(self.allocator, param_index); if (comptime std.meta.trait.isZigString(ParamType)) { try self.data.appendSlice(self.allocator, param); self.indicators[index] = @intCast(c_longlong, param.len); } else { try self.data.appendSlice(self.allocator, std.mem.toBytes(@as(ParamType, param))[0..]); self.indicators[index] = @sizeOf(ParamType); } return Param{ .param = @ptrCast(*anyopaque, &self.data.items[param_index]), .indicator = &self.indicators[index] }; } }; test "SqlParameter defaults" { const SqlType = odbc.Types.SqlType; const CType = odbc.Types.CType; const a = default(10); try std.testing.expect(a.precision == null); try std.testing.expect(a.value == 10); try std.testing.expectEqual(i64, @TypeOf(a.value)); try std.testing.expectEqual(CType.SBigInt, a.c_type); try std.testing.expectEqual(SqlType.BigInt, a.sql_type); } test "SqlParameter string" { const SqlType = odbc.Types.SqlType; const CType = odbc.Types.CType; const param = default("some string"); try std.testing.expect(param.precision == null); try std.testing.expectEqualStrings("some string", param.value); try std.testing.expectEqual(*const [11:0] u8, @TypeOf(param.value)); try std.testing.expectEqual(CType.Char, param.c_type); try std.testing.expectEqual(SqlType.Varchar, param.sql_type); } test "add parameter to ParameterBucket" { const allocator = std.testing.allocator; var bucket = try ParameterBucket.init(allocator, 5); defer bucket.deinit(); var param_value: u32 = 10; const param = try bucket.addParameter(0, param_value); const param_data = @ptrCast([*]u8, param.param)[0..@intCast(usize, param.indicator.*)]; try std.testing.expectEqualSlices(u8, std.mem.toBytes(param_value)[0..], param_data); } test "add string parameter to ParameterBucket" { const allocator = std.testing.allocator; var bucket = try ParameterBucket.init(allocator, 5); defer bucket.deinit(); var param_value = "some string value"; const param = try bucket.addParameter(0, param_value); const param_data = @ptrCast([*]u8, param.param)[0..@intCast(usize, param.indicator.*)]; try std.testing.expectEqualStrings(param_value, param_data); }
src/parameter.zig
const std = @import("std"); const audiometa = @import("audiometa"); const id3 = audiometa.id3v2; const fmtUtf8SliceEscapeUpper = audiometa.util.fmtUtf8SliceEscapeUpper; const meta = audiometa.metadata; const MetadataMap = meta.MetadataMap; const Metadata = meta.Metadata; const TypedMetadata = meta.TypedMetadata; const ID3v2Metadata = meta.ID3v2Metadata; const FullTextEntry = audiometa.id3v2_data.FullTextMap.Entry; const AllMetadata = meta.AllMetadata; const Allocator = std.mem.Allocator; const testing = std.testing; const assert = std.debug.assert; const start_testing_at_prefix = ""; const buggy_files = buggy_files: { @setEvalBranchQuota(10000); break :buggy_files std.ComptimeStringMap(void, .{ // TagLib gives no ID3v2 frames for these files, but they have valid tags AFAICT .{"Dawn Treader/(2002) Dawn Treader/DAWN TREADER - demo - 4 - Roller Coaster in a Theme Park.mp3"}, .{"DAWNTREADER-disco/Dawn Treader/(2002) Dawn Treader/DAWN TREADER - demo - 4 - Roller Coaster in a Theme Park.mp3"}, .{"Discography/Dawn Treader - Roller Coaster in a Theme Park.mp3"}, .{"flattery/sunday.mp3"}, .{"V.A. - I Love D-Crust V/En Tus Ojos.mp3"}, // TagLib gives nothing but a COMM for these files, but they have valid tags AFAICT .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 01 - the global cannibal.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 02 - what did we expect.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 03 - advancing the cause.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 04 - as long as i'm safe.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 05 - hooked on chirst.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 06 - cycle of violence.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 07 - self-inflicted extinction.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 08 - her body. her decision.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 09 - the army of god.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 10 - the politics of hunger.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 11 - non-lethal weapons.mp3"}, .{"behind enemy lines - the global cannibal/behind enemy lines - the global cannibal - 12 - light it up.mp3"}, .{"blue_monday-rewritten/blue monday - ...a moving train.mp3"}, .{"blue_monday-rewritten/blue monday - 100 inari.mp3"}, .{"blue_monday-rewritten/blue monday - bereaved.mp3"}, .{"blue_monday-rewritten/blue monday - bloody knuckles.mp3"}, .{"blue_monday-rewritten/blue monday - drenched.mp3"}, .{"blue_monday-rewritten/blue monday - it's your life.mp3"}, .{"blue_monday-rewritten/blue monday - let it out.mp3"}, .{"blue_monday-rewritten/blue monday - lost and found.mp3"}, .{"blue_monday-rewritten/blue monday - next breath.mp3"}, .{"blue_monday-rewritten/blue monday - on the outside.mp3"}, .{"blue_monday-rewritten/blue monday - the everything festival.mp3"}, .{"blue_monday-rewritten/blue monday - turning the tables.mp3"}, .{"comeback_kid-wake_the_dead-2005/01 false idols fall.mp3"}, .{"comeback_kid-wake_the_dead-2005/02 my other side.mp3"}, .{"comeback_kid-wake_the_dead-2005/03 wake the dead.mp3"}, .{"comeback_kid-wake_the_dead-2005/04 the trouble i love.mp3"}, .{"comeback_kid-wake_the_dead-2005/05 talk is cheap.mp3"}, .{"comeback_kid-wake_the_dead-2005/06 partners in crime.mp3"}, .{"comeback_kid-wake_the_dead-2005/07 our distance.mp3"}, .{"comeback_kid-wake_the_dead-2005/08 bright lights keep shining.mp3"}, .{"comeback_kid-wake_the_dead-2005/09 falling apart.mp3"}, .{"comeback_kid-wake_the_dead-2005/10 losing patience.mp3"}, .{"comeback_kid-wake_the_dead-2005/11 final goodbye.mp3"}, .{"carry_on-its all our blood/06 - check yourself.mp3"}, .{"final_fight-under_attack/final fight - 01 - it's in the blood.mp3"}, .{"final_fight-under_attack/final fight - 02 - getting my eyes checked.mp3"}, .{"final_fight-under_attack/final fight - 03 - dying of laughter.mp3"}, .{"final_fight-under_attack/final fight - 04 - notes on bombs and fists.mp3"}, .{"final_fight-under_attack/final fight - 05 - when actions go unchallenged.mp3"}, .{"final_fight-under_attack/final fight - 06 - lost loyalty.mp3"}, .{"final_fight-under_attack/final fight - 07 - shifting the center.mp3"}, .{"final_fight-under_attack/final fight - 08 - one and two.mp3"}, .{"final_fight-under_attack/final fight - 09 - when words go unchallenged.mp3"}, .{"final_fight-under_attack/final fight - 10 - three years ago.mp3"}, .{"final_fight-under_attack/final fight - 11 - modified people.mp3"}, .{"final_fight-under_attack/final fight - 12 - waste of mind, waste of life.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/01-kids_like_us-outta_control.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/02-kids_like_us-box_of_buttholes.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/03-kids_like_us-dont_fake_the_punk.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/04-kids_like_us-dont_eat_rocks._we_rocks.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/05-kids_like_us-skate_hate.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/06-kids_like_us-soda_jerk.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/07-kids_like_us-dog_food.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/08-kids_like_us-lantern_corps.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/09-kids_like_us-monster_squad.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/10-kids_like_us-asshat.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/11-kids_like_us-you_know_your_life_sucks.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/12-kids_like_us-the_clock_on_the_wall.mp3"}, .{"kids_like_us-outta_control-advance-2005-sdr/13-kids_like_us-gator_smash.mp3"}, .{"Wake Up On Fire Demo/01 Holes.mp3"}, .{"Wake Up On Fire Demo/02 Green Mouth.mp3"}, .{"Wake Up On Fire Demo/03 Dust.mp3"}, .{"Wake Up On Fire Demo/04 Stress By Design, Crazy 'Ole Boss.mp3"}, .{"Wake Up On Fire Demo/05 Jihad the Buffy Slayer.mp3"}, .{"Wake Up On Fire Demo/06 Will To Be Hollow.mp3"}, .{"Wake Up On Fire Demo/07 Stay Out Of the World.mp3"}, // TagLib gives partial frames for these files, but they have valid tags AFAICT .{"cro-mags - the age of quarrel/01 we gotta know.mp3"}, .{"have_heart-what_counts/have heart -01- lionheart.mp3"}, .{"have_heart-what_counts/have heart -02- get the knife.mp3"}, .{"have_heart-what_counts/have heart -03- something more than ink.mp3"}, .{"have_heart-what_counts/have heart -04- what counts.mp3"}, .{"have_heart-what_counts/have heart -05- dig somewhere else.mp3"}, .{"have_heart-what_counts/have heart -06- reinforced(outspoken).mp3"}, .{"<NAME> - Theyll Come They Come 2007/05-immanu_el-panda.mp3"}, .{"Mortal Treason - A Call To The Martyrs [2004]/06 Bridens Last Kiss.mp3"}, .{"November 13th & AK47 - split/november 13th - ancient spirits.mp3"}, .{"Strength_For_A_Reason-Blood_Faith_Loyalty-2005-RNS/02-strength_for_a_reason-dead_to_me.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/02 Cherry Tree.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/03 Fissure.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/04 Sky.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/05 Road.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/06 Light.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/07 Wind.mp3"}, .{"Swarrrm - Black Bong (2007) [256kbps]/08 Black Bong.mp3"}, .{"trash talk - self-titled/01 The Hand That Feeds.mp3"}, .{"trash talk - self-titled/02 Well Of Souls.mp3"}, .{"trash talk - self-titled/03 Birth Plague Die.mp3"}, .{"trash talk - self-titled/04 Incarnate.mp3"}, .{"trash talk - self-titled/05 I Block.mp3"}, .{"trash talk - self-titled/06 Dig.mp3"}, .{"trash talk - self-titled/07 Onward and Upward.mp3"}, .{"trash talk - self-titled/08 Immaculate Infection.mp3"}, .{"trash talk - self-titled/09 Shame.mp3"}, .{"trash talk - self-titled/10 All The Kings Men.mp3"}, .{"trash talk - self-titled/11 The Mistake.mp3"}, .{"trash talk - self-titled/12 Revelation.mp3"}, // TagLib gives no COMM frames for these files, but they have at least one AFAICT .{"Crow - 終焉の扉 (The Door Of The End) (V0)/01 - 終焉の扉.mp3"}, .{"Crow - 終焉の扉 (The Door Of The End) (V0)/02 - My Last Dream.mp3"}, .{"Crow - 終焉の扉 (The Door Of The End) (V0)/03 - Scapegoat.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/01 Blue Skies.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/02 Maybe Tomorrow.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/03 Autumn Tears.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/04 Deceived.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/05 Unanswered Prayers.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/06 Through Dark Days.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/07 Embrace The End.mp3"}, .{"Embrace The End - It All Begins With One Broken Dream [2001] by_fightheday/08 Last Goodbye.mp3"}, .{"matt besser - (2001) may i help you dumbass (missing 9-13)/08. matt besser - automated operator.mp3"}, // TagLib trims whitespace from TCOM in these files, audiometa does not .{"<NAME> - Streams Inwards/01 - Starmaker.mp3"}, .{"<NAME> - Streams Inwards/02 - Shining Human Skin.mp3"}, .{"<NAME> - Streams Inwards/03 - The Bell and the Solar Gust.mp3"}, .{"<NAME> - Streams Inwards/04 - Spectral Ocean.mp3"}, .{"<NAME> - Streams Inwards/05 - Sensing the New Orbit.mp3"}, .{"<NAME> - Streams Inwards/06 - Catatonic North.mp3"}, .{"<NAME> - Streams Inwards/07 - Knotted Delirium.mp3"}, .{"<NAME> - Streams Inwards/08 - A Sea of Dead Comets.mp3"}, .{"<NAME> - Streams Inwards/09 - Aphelion Aura [bonus track].mp3"}, // TagLib doesn't handle EOF/padding edge cases for v2.4 non-synchsafe-encoded frame sizes .{"mr. meeble - never trust the chinese/05. it all came to pass.mp3"}, .{"mr. meeble - never trust the chinese/07. a ton of bricks.mp3"}, // These files have a totally invalid COMM frame that says it's // UTF-16 with BOM but then uses u8 chars with no BOM in its text fields. // TagLib reports this as a COMM frame with no description/value but // that doesn't seem great. Instead, we treat it as an invalid frame and skip it. .{"Sending All Processes The Kill Signal - Life Not Found -404- Error/02.mp3"}, .{"Sending All Processes The Kill Signal - Life Not Found -404- Error/05.mp3"}, // This is just weird, it's a v2.3 tag with a mix of v2.2 field IDs and v2.3 // field IDs, and a TAL with one value and TALB with another. Just skip it // since I don't want to deal with all the conversions TagLib is doing .{"Sonic Cathedrals Vol. XLVI Curated by Age of Collapse/04 Prowler.mp3"}, .{"Sonic Cathedrals Vol. XLVI Curated by Age of Collapse/18 With empty hands extended.mp3"}, // TDRC / TYER conversion nonsense, just skip it for now .{"TH3 LOR3L3I COLL3CTION/It's Only Me.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 01 La Cova.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 02 El cant dels ocells.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 03 Les hores perdudes.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 04 Vulnerable.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 05 No hi ha esperanca.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 06 A les seves mans.mp3"}, .{"Una Bestia Incontrolable - 10.11.12/Una Bestia Incontrolable - 07 De dia.mp3"}, // There is an unreadable COMM frame in these files, with no room for the language string // For some reason TagLib still outputs this frame even though it seems to report it as an error .{"go it alone - vancouver gold/Go it Alone - Our Mistakes.mp3"}, .{"go it alone - vancouver gold/Go it Alone - Silence.mp3"}, .{"go it alone - vancouver gold/Go it Alone - Statement.mp3"}, .{"go it alone - vancouver gold/Go it Alone - The Best of You.mp3"}, .{"go it alone - vancouver gold/Go it Alone - Turn It Off.mp3"}, // TagLib removes a NUL byte from the end of a \xA9cmt atom's data, // but we preserve it (since string data is not NUL-terminated in MP4 files) .{"Dystopia & Suffering Luna - Split/02 La Reina Del Rosario.m4a"}, }); }; test "music folder" { const allocator = std.testing.allocator; var dir = try std.fs.cwd().openDir("/media/drive4/music", .{ .iterate = true }); var walker = try dir.walk(allocator); defer walker.deinit(); var testing_started = false; while (try walker.next()) |entry| { if (!testing_started) { if (std.mem.startsWith(u8, entry.path, start_testing_at_prefix)) { testing_started = true; } else { continue; } } if (entry.kind != .File) continue; if (buggy_files.has(entry.path)) continue; const extension = std.fs.path.extension(entry.basename); const is_mp3 = std.ascii.eqlIgnoreCase(extension, ".mp3"); const is_flac = std.ascii.eqlIgnoreCase(extension, ".flac"); const is_m4a = std.ascii.eqlIgnoreCase(extension, ".m4a"); const readable = is_mp3 or is_flac or is_m4a; if (!readable) continue; std.debug.print("\n{s}\n", .{fmtUtf8SliceEscapeUpper(entry.path)}); var expected_metadata = try getTagLibMetadata(allocator, entry.dir, entry.basename); defer expected_metadata.deinit(); var file = try entry.dir.openFile(entry.basename, .{}); defer file.close(); // skip zero sized files const size = (try file.stat()).size; if (size == 0) continue; var stream_source = std.io.StreamSource{ .file = file }; var metadata = try meta.readAll(allocator, &stream_source); defer metadata.deinit(); try compareMetadata(allocator, &expected_metadata, &metadata); } } fn convertID3v2Alloc(allocator: Allocator, map: *MetadataMap, id3_major_version: u8) !MetadataMap { var converted = MetadataMap.init(allocator); errdefer converted.deinit(); for (map.entries.items) |entry| { // Keep the unconverted names since I don't really understand fully // how taglib converts things. This will make things less precise but // more foolproof for the type of comparisons we're trying to make try converted.put(entry.name, entry.value); if (taglibConversions.get(entry.name)) |converted_name| { try converted.put(converted_name, entry.value); } } if (id3_major_version < 4) { try mergeDate(&converted); // TagLib seems to convert TDAT and TIME to a zero-length string if (converted.getFirst("TDAT") != null) { const indexes_entry = try converted.getOrPutEntry("TDAT"); const entry_index = indexes_entry.value_ptr.items[0]; var entry = &converted.entries.items[entry_index]; converted.allocator.free(entry.value); entry.value = &[_]u8{}; } if (converted.getFirst("TIME") != null) { const indexes_entry = try converted.getOrPutEntry("TIME"); const entry_index = indexes_entry.value_ptr.items[0]; var entry = &converted.entries.items[entry_index]; converted.allocator.free(entry.value); entry.value = &[_]u8{}; } } //var name_map_it = converted.name_to_indexes.iterator(); //while (name_map_it.next()) |name_map_entry| { // if ((name_map_entry.key_ptr.*).len != 4 or (name_map_entry.key_ptr.*)[0] != 'T') { // continue; // } for (frames_to_combine) |frame_id| { if (converted.name_to_indexes.contains(frame_id)) { const name_map_entry = converted.name_to_indexes.getEntry(frame_id).?; const count = name_map_entry.value_ptr.items.len; if (count > 1) { const joined = (try converted.getJoinedAlloc(allocator, name_map_entry.key_ptr.*, " ")).?; defer allocator.free(joined); // this is hacky but we can get away with only replacing the first // value with the joined value, since TagLib will only report one value // and therefore we will only compare the first value in compareMetadataMapID3v2 try converted.putOrReplaceFirst(name_map_entry.key_ptr.*, joined); } } } return converted; } const frames_to_combine: []const []const u8 = &.{ "TCOM", "TPE2", "TDOR" }; const taglibConversions = std.ComptimeStringMap([]const u8, .{ // 2.2 -> 2.4 .{ "BUF", "RBUF" }, .{ "CNT", "PCNT" }, .{ "COM", "COMM" }, .{ "CRA", "AENC" }, .{ "ETC", "ETCO" }, .{ "GEO", "GEOB" }, .{ "IPL", "TIPL" }, .{ "MCI", "MCDI" }, .{ "MLL", "MLLT" }, .{ "POP", "POPM" }, .{ "REV", "RVRB" }, .{ "SLT", "SYLT" }, .{ "STC", "SYTC" }, .{ "TAL", "TALB" }, .{ "TBP", "TBPM" }, .{ "TCM", "TCOM" }, .{ "TCO", "TCON" }, .{ "TCP", "TCMP" }, .{ "TCR", "TCOP" }, .{ "TDY", "TDLY" }, .{ "TEN", "TENC" }, .{ "TFT", "TFLT" }, .{ "TKE", "TKEY" }, .{ "TLA", "TLAN" }, .{ "TLE", "TLEN" }, .{ "TMT", "TMED" }, .{ "TOA", "TOAL" }, .{ "TOF", "TOFN" }, .{ "TOL", "TOLY" }, .{ "TOR", "TDOR" }, .{ "TOT", "TOAL" }, .{ "TP1", "TPE1" }, .{ "TP2", "TPE2" }, .{ "TP3", "TPE3" }, .{ "TP4", "TPE4" }, .{ "TPA", "TPOS" }, .{ "TPB", "TPUB" }, .{ "TRC", "TSRC" }, .{ "TRD", "TDRC" }, .{ "TRK", "TRCK" }, .{ "TS2", "TSO2" }, .{ "TSA", "TSOA" }, .{ "TSC", "TSOC" }, .{ "TSP", "TSOP" }, .{ "TSS", "TSSE" }, .{ "TST", "TSOT" }, .{ "TT1", "TIT1" }, .{ "TT2", "TIT2" }, .{ "TT3", "TIT3" }, .{ "TXT", "TOLY" }, .{ "TXX", "TXXX" }, .{ "TYE", "TDRC" }, .{ "UFI", "UFID" }, .{ "ULT", "USLT" }, .{ "WAF", "WOAF" }, .{ "WAR", "WOAR" }, .{ "WAS", "WOAS" }, .{ "WCM", "WCOM" }, .{ "WCP", "WCOP" }, .{ "WPB", "WPUB" }, .{ "WXX", "WXXX" }, // 2.2 -> 2.4 Apple iTunes nonstandard frames .{ "PCS", "PCST" }, .{ "TCT", "TCAT" }, .{ "TDR", "TDRL" }, .{ "TDS", "TDES" }, .{ "TID", "TGID" }, .{ "WFD", "WFED" }, .{ "MVN", "MVNM" }, .{ "MVI", "MVIN" }, .{ "GP1", "GRP1" }, // 2.3 -> 2.4 .{ "TORY", "TDOR" }, .{ "TYER", "TDRC" }, .{ "IPLS", "TIPL" }, }); const date_format = "YYYY-MM-DDThh:mm"; fn isValidDateComponent(maybe_date: ?[]const u8) bool { if (maybe_date == null) return false; const date = maybe_date.?; if (date.len != 4) return false; // only 0-9 allowed for (date) |byte| switch (byte) { '0'...'9' => {}, else => return false, }; return true; } fn mergeDate(metadata: *MetadataMap) !void { var date_buf: [date_format.len]u8 = undefined; var date: []u8 = date_buf[0..0]; var year = metadata.getFirst("TDRC"); if (!isValidDateComponent(year)) return; date = date_buf[0..4]; std.mem.copy(u8, date, (year.?)[0..4]); var maybe_daymonth = metadata.getFirst("TDAT"); if (isValidDateComponent(maybe_daymonth)) { const daymonth = maybe_daymonth.?; date = date_buf[0..10]; // TDAT is DDMM, we want -MM-DD var day = daymonth[0..2]; var month = daymonth[2..4]; _ = try std.fmt.bufPrint(date[4..10], "-{s}-{s}", .{ month, day }); var maybe_time = metadata.getFirst("TIME"); if (isValidDateComponent(maybe_time)) { const time = maybe_time.?; date = date_buf[0..]; // TIME is HHMM var hours = time[0..2]; var mins = time[2..4]; _ = try std.fmt.bufPrint(date[10..], "T{s}:{s}", .{ hours, mins }); } } try metadata.putOrReplaceFirst("TDRC", date); } fn compareTDRC(expected: *MetadataMap, actual: *MetadataMap) !void { const expected_count = expected.valueCount("TDRC").?; if (expected_count == 1) { const expected_value = expected.getFirst("TDRC").?; if (actual.getFirst("TDRC")) |actual_tdrc| { try std.testing.expectEqualStrings(expected_value, actual_tdrc); } else if (actual.getFirst("TYER")) |actual_tyer| { try std.testing.expectEqualStrings(expected_value, actual_tyer); } else { return error.MissingTDRC; } } else { unreachable; // TODO multiple TDRC values } } fn compareMetadataMapID3v2(allocator: Allocator, expected: *MetadataMap, actual: *MetadataMap, id3_major_version: u8) !void { var actual_converted = try convertID3v2Alloc(allocator, actual, id3_major_version); defer actual_converted.deinit(); for (expected.entries.items) |field| { // genre is messy, just skip it for now // TODO: dont skip it if (std.mem.eql(u8, field.name, "TCON")) { continue; } // TIPL (Involved people list) is also messy, since taglib converts from IPLS to TIPL else if (std.mem.eql(u8, field.name, "TIPL")) { continue; } // TagLib seems to give TSIZ as an empty string, so skip it else if (std.mem.eql(u8, field.name, "TSIZ")) { continue; } else { if (actual_converted.contains(field.name)) { var expected_num_values = expected.valueCount(field.name).?; if (expected_num_values == 1) { var actual_value = actual_converted.getFirst(field.name).?; std.testing.expectEqualStrings(field.value, actual_value) catch |e| { std.debug.print("\nfield: {s}\n", .{fmtUtf8SliceEscapeUpper(field.name)}); std.debug.print("\nexpected:\n", .{}); expected.dump(); std.debug.print("\nactual:\n", .{}); actual.dump(); std.debug.print("\nactual converted:\n", .{}); actual_converted.dump(); return e; }; } else { const expected_values = (try expected.getAllAlloc(allocator, field.name)).?; defer allocator.free(expected_values); const actual_values = (try actual_converted.getAllAlloc(allocator, field.name)).?; defer allocator.free(actual_values); std.testing.expectEqual(expected_values.len, actual_values.len) catch |err| { std.debug.print("Field: {s}\n", .{field.name}); return err; }; for (expected_values) |expected_value| { var found = false; for (actual_values) |actual_value| { if (std.mem.eql(u8, expected_value, actual_value)) { found = true; break; } } if (!found) { std.debug.print("Value not found for field {s}, expected value: '{}'\n", .{ fmtUtf8SliceEscapeUpper(field.name), fmtUtf8SliceEscapeUpper(expected_value) }); std.debug.print(" Actual values:\n", .{}); for (actual_values) |actual_value| { std.debug.print(" '{s}'\n", .{fmtUtf8SliceEscapeUpper(actual_value)}); } return error.ExpectedFieldValueNotFound; } } } } else { std.debug.print("\nmissing field {s}\n", .{field.name}); std.debug.print("\nexpected:\n", .{}); expected.dump(); std.debug.print("\nactual:\n", .{}); actual.dump(); std.debug.print("\nactual converted:\n", .{}); actual_converted.dump(); return error.MissingField; } } } } fn compareMetadataMap(expected: *const MetadataMap, actual: *const MetadataMap) !void { expected_loop: for (expected.entries.items) |field| { var found_matching_key = false; for (actual.entries.items) |entry| { if (std.mem.eql(u8, field.name, entry.name)) { if (std.mem.eql(u8, field.value, entry.value)) { continue :expected_loop; } found_matching_key = true; } } std.debug.print("field: {s}\n", .{fmtUtf8SliceEscapeUpper(field.name)}); std.debug.print("\nexpected:\n", .{}); expected.dump(); std.debug.print("\nactual:\n", .{}); actual.dump(); if (found_matching_key) { return error.FieldValuesDontMatch; } else { return error.MissingField; } } } fn compareMetadataMapFLAC(expected: *MetadataMap, actual: *MetadataMap) !void { expected_loop: for (expected.entries.items) |field| { var found_matching_key = false; for (actual.entries.items) |entry| { if (std.ascii.eqlIgnoreCase(field.name, entry.name)) { if (std.mem.eql(u8, field.value, entry.value)) { continue :expected_loop; } found_matching_key = true; } } std.debug.print("field: {s}\n", .{fmtUtf8SliceEscapeUpper(field.name)}); std.debug.print("\nexpected:\n", .{}); expected.dump(); std.debug.print("\nactual:\n", .{}); actual.dump(); if (found_matching_key) { return error.FieldValuesDontMatch; } else { return error.MissingField; } } } fn compareFullText(expected: FullTextEntry, actual: FullTextEntry) !void { try testing.expectEqualStrings(expected.language, actual.language); try testing.expectEqualStrings(expected.description, actual.description); try testing.expectEqualStrings(expected.value, actual.value); } const taglibMP4Conversions = std.ComptimeStringMap([]const u8, .{ .{ "\xA9nam", "TITLE" }, .{ "\xA9ART", "ARTIST" }, .{ "\xA9alb", "ALBUM" }, .{ "\xA9cmt", "COMMENT" }, .{ "\xA9gen", "GENRE" }, .{ "\xA9day", "DATE" }, .{ "\xA9wrt", "COMPOSER" }, .{ "\xA9grp", "GROUPING" }, .{ "aART", "ALBUMARTIST" }, .{ "trkn", "TRACKNUMBER" }, .{ "disk", "DISCNUMBER" }, .{ "cpil", "COMPILATION" }, .{ "tmpo", "BPM" }, .{ "cprt", "COPYRIGHT" }, .{ "\xA9lyr", "LYRICS" }, .{ "\xA9too", "ENCODEDBY" }, .{ "soal", "ALBUMSORT" }, .{ "soaa", "ALBUMARTISTSORT" }, .{ "soar", "ARTISTSORT" }, .{ "sonm", "TITLESORT" }, .{ "soco", "COMPOSERSORT" }, .{ "sosn", "SHOWSORT" }, .{ "shwm", "SHOWWORKMOVEMENT" }, .{ "pgap", "GAPLESSPLAYBACK" }, .{ "pcst", "PODCAST" }, .{ "catg", "PODCASTCATEGORY" }, .{ "desc", "PODCASTDESC" }, .{ "egid", "PODCASTID" }, .{ "purl", "PODCASTURL" }, .{ "tves", "TVEPISODE" }, .{ "tven", "TVEPISODEID" }, .{ "tvnn", "TVNETWORK" }, .{ "tvsn", "TVSEASON" }, .{ "tvsh", "TVSHOW" }, .{ "\xA9wrk", "WORK" }, .{ "\xA9mvn", "MOVEMENTNAME" }, .{ "\xA9mvi", "MOVEMENTNUMBER" }, .{ "\xA9mvc", "MOVEMENTCOUNT" }, // TagLib converts gnre to \xA9gen while parsing, which then gets converted to GENRE .{ "gnre", "GENRE" }, }); fn compareMetadataMapMP4(expected: *const MetadataMap, actual: *const MetadataMap) !void { expected_loop: for (expected.entries.items) |field| { var found_matching_key = false; for (actual.entries.items) |entry| { const converted_name = taglibMP4Conversions.get(entry.name); if (converted_name == null) { continue; } if (std.mem.eql(u8, field.name, converted_name.?)) { if (std.mem.eql(u8, field.value, entry.value)) { continue :expected_loop; } found_matching_key = true; } } std.debug.print("field: {s}\n", .{fmtUtf8SliceEscapeUpper(field.name)}); std.debug.print("\nexpected:\n", .{}); expected.dump(); std.debug.print("\nactual:\n", .{}); actual.dump(); if (found_matching_key) { return error.FieldValuesDontMatch; } else { return error.MissingField; } } } fn compareMetadata(allocator: Allocator, all_expected: *AllMetadata, all_actual: *AllMetadata) !void { // dumb way to do this but oh well errdefer { std.debug.print("\nexpected:\n", .{}); all_expected.dump(); std.debug.print("\nactual:\n", .{}); all_actual.dump(); } for (all_expected.tags) |expected_tag| { switch (expected_tag) { .id3v2 => { const maybe_actual_id3v2 = all_actual.getFirstMetadataOfType(.id3v2); if (maybe_actual_id3v2 == null) { return error.MissingID3v2; } const actual_id3v2 = maybe_actual_id3v2.?; // Don't compare version, Taglib doesn't give the actual version in the file, but // instead the version it decided to convert the tag to //try testing.expectEqual(expected_tag.id3v2.header.major_version, actual_id3v2.header.major_version); try testing.expectEqual(expected_tag.id3v2.comments.entries.items.len, actual_id3v2.comments.entries.items.len); for (expected_tag.id3v2.comments.entries.items) |expected_comment, comment_i| { // TagLib seems to give blank descriptions for blank values, if we see // blank both then skip this one if (expected_comment.description.len == 0 and expected_comment.value.len == 0) { continue; } const actual_comment = actual_id3v2.comments.entries.items[comment_i]; try compareFullText(expected_comment, actual_comment); } for (expected_tag.id3v2.unsynchronized_lyrics.entries.items) |expected_lyrics, lyrics_i| { const actual_lyrics = actual_id3v2.unsynchronized_lyrics.entries.items[lyrics_i]; try compareFullText(expected_lyrics, actual_lyrics); } try compareMetadataMap(&expected_tag.id3v2.user_defined, &actual_id3v2.user_defined); try compareMetadataMapID3v2(allocator, &expected_tag.getMetadata().map, &actual_id3v2.metadata.map, expected_tag.id3v2.header.major_version); }, .flac => { const maybe_actual_flac = all_actual.getFirstMetadataOfType(.flac); if (maybe_actual_flac == null) { return error.MissingFLAC; } const actual_flac = maybe_actual_flac.?; try compareMetadataMapFLAC(&expected_tag.getMetadata().map, &actual_flac.map); }, .mp4 => { const maybe_actual_mp4 = all_actual.getFirstMetadataOfType(.mp4); if (maybe_actual_mp4 == null) { return error.MissingMP4; } const actual_mp4 = maybe_actual_mp4.?; try compareMetadataMapMP4(&expected_tag.getMetadata().map, &actual_mp4.map); }, else => @panic("TODO: comparisons for more tag types supported by taglib"), } } } fn getTagLibMetadata(allocator: Allocator, cwd: ?std.fs.Dir, filepath: []const u8) !AllMetadata { const result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &[_][]const u8{ "framelist", filepath, }, .cwd_dir = cwd, }); defer allocator.free(result.stdout); defer allocator.free(result.stderr); var id3v2_metadata: ?ID3v2Metadata = null; errdefer if (id3v2_metadata != null) id3v2_metadata.?.deinit(); const maybe_metadata_start = std.mem.indexOf(u8, result.stdout, "ID3v2"); if (maybe_metadata_start) |metadata_start| { var metadata_line = result.stdout[metadata_start..]; const metadata_line_end = std.mem.indexOfScalar(u8, metadata_line, '\n').?; metadata_line = metadata_line[0..metadata_line_end]; std.debug.print("metadataline: {s}\n", .{std.fmt.fmtSliceEscapeLower(metadata_line)}); var major_version = try std.fmt.parseInt(u8, metadata_line[6..7], 10); // taglib doesn't render v2.2 frames AFAICT, and instead upgrades them to v2.3. // So bump major_version up to 3 here since we need to read the upgraded version. if (major_version == 2) { major_version = 3; } var num_frames_str = metadata_line[11..]; const num_frames_end = std.mem.indexOfScalar(u8, num_frames_str, ' ').?; num_frames_str = num_frames_str[0..num_frames_end]; const num_frames = try std.fmt.parseInt(usize, num_frames_str, 10); id3v2_metadata = ID3v2Metadata.init(allocator, id3.ID3Header{ .major_version = major_version, .revision_num = 0, .flags = 0, .size = 0, }, 0, 0); const start_value_string = "[====["; const end_value_string = "]====]"; var frame_i: usize = 0; const absolute_metadata_line_end_after_newline = metadata_start + metadata_line_end + 1; var frames_data = result.stdout[absolute_metadata_line_end_after_newline..]; while (frame_i < num_frames) : (frame_i += 1) { const frame_id = frames_data[0..4]; frames_data = frames_data[4..]; const is_comment = std.mem.eql(u8, frame_id, "COMM"); const is_lyrics = std.mem.eql(u8, frame_id, "USLT"); const is_usertext = std.mem.eql(u8, frame_id, "TXXX"); var language: ?[]const u8 = null; var description: ?[]const u8 = null; if (is_comment or is_lyrics) { var start_quote_index = std.mem.indexOf(u8, frames_data, start_value_string).?; language = frames_data[0..start_quote_index]; const description_start = start_quote_index + start_value_string.len; var end_quote_index = std.mem.indexOf(u8, frames_data[description_start..], end_value_string).?; const abs_end_quote_index = description_start + end_quote_index; description = frames_data[description_start..abs_end_quote_index]; frames_data = frames_data[abs_end_quote_index + end_value_string.len ..]; } else if (is_usertext) { const description_start = start_value_string.len; var end_quote_index = std.mem.indexOf(u8, frames_data[description_start..], end_value_string).?; const abs_end_quote_index = description_start + end_quote_index; description = frames_data[description_start..abs_end_quote_index]; frames_data = frames_data[abs_end_quote_index + end_value_string.len ..]; } assert(frames_data[0] == '='); const value_start_index = 1; var start_quote_index = std.mem.indexOf(u8, frames_data[value_start_index..], start_value_string).?; const abs_after_start_quote_index = value_start_index + start_quote_index + start_value_string.len; var end_quote_index = std.mem.indexOf(u8, frames_data[abs_after_start_quote_index..], end_value_string).?; const abs_end_quote_index = abs_after_start_quote_index + end_quote_index; var value = frames_data[abs_after_start_quote_index..abs_end_quote_index]; if (is_comment) { try id3v2_metadata.?.comments.put(language.?, description.?, value); } else if (is_lyrics) { try id3v2_metadata.?.unsynchronized_lyrics.put(language.?, description.?, value); } else if (is_usertext) { try id3v2_metadata.?.user_defined.put(description.?, value); } else { try id3v2_metadata.?.metadata.map.put(frame_id, value); } var after_linebreaks = abs_end_quote_index + end_value_string.len; while (after_linebreaks < frames_data.len and frames_data[after_linebreaks] == '\n') { after_linebreaks += 1; } frames_data = frames_data[after_linebreaks..]; } } var flac_metadata: ?Metadata = null; errdefer if (flac_metadata != null) flac_metadata.?.deinit(); const flac_start_string = "FLAC:::::::::\n"; const maybe_flac_start = std.mem.indexOf(u8, result.stdout, flac_start_string); if (maybe_flac_start) |flac_start| { const flac_data_start = flac_start + flac_start_string.len; var flac_data = result.stdout[flac_data_start..]; flac_metadata = Metadata.init(allocator); while (true) { var equals_index = std.mem.indexOfScalar(u8, flac_data, '=') orelse break; var name = flac_data[0..equals_index]; const value_start_index = equals_index + 1; const start_value_string = "[====["; var start_quote_index = std.mem.indexOf(u8, flac_data[value_start_index..], start_value_string) orelse break; const abs_after_start_quote_index = value_start_index + start_quote_index + start_value_string.len; const end_value_string = "]====]"; var end_quote_index = std.mem.indexOf(u8, flac_data[abs_after_start_quote_index..], end_value_string) orelse break; const abs_end_quote_index = abs_after_start_quote_index + end_quote_index; var value = flac_data[abs_after_start_quote_index..abs_end_quote_index]; try flac_metadata.?.map.put(name, value); var after_linebreaks = abs_end_quote_index + end_value_string.len; while (after_linebreaks < flac_data.len and flac_data[after_linebreaks] == '\n') { after_linebreaks += 1; } flac_data = flac_data[after_linebreaks..]; } } var mp4_metadata: ?Metadata = null; errdefer if (mp4_metadata != null) mp4_metadata.?.deinit(); const mp4_start_string = "MP4:::::::::\n"; const maybe_mp4_start = std.mem.indexOf(u8, result.stdout, mp4_start_string); if (maybe_mp4_start) |mp4_start| { const mp4_data_start = mp4_start + mp4_start_string.len; var mp4_data = result.stdout[mp4_data_start..]; mp4_metadata = Metadata.init(allocator); while (true) { var equals_index = std.mem.indexOfScalar(u8, mp4_data, '=') orelse break; var name = mp4_data[0..equals_index]; const value_start_index = equals_index + 1; const start_value_string = "[====["; var start_quote_index = std.mem.indexOf(u8, mp4_data[value_start_index..], start_value_string) orelse break; const abs_after_start_quote_index = value_start_index + start_quote_index + start_value_string.len; const end_value_string = "]====]"; var end_quote_index = std.mem.indexOf(u8, mp4_data[abs_after_start_quote_index..], end_value_string) orelse break; const abs_end_quote_index = abs_after_start_quote_index + end_quote_index; var value = mp4_data[abs_after_start_quote_index..abs_end_quote_index]; try mp4_metadata.?.map.put(name, value); var after_linebreaks = abs_end_quote_index + end_value_string.len; while (after_linebreaks < mp4_data.len and mp4_data[after_linebreaks] == '\n') { after_linebreaks += 1; } mp4_data = mp4_data[after_linebreaks..]; } } var count: usize = 0; if (id3v2_metadata != null) count += 1; if (flac_metadata != null) count += 1; if (mp4_metadata != null) count += 1; var tags_slice = try allocator.alloc(TypedMetadata, count); errdefer allocator.free(tags_slice); var tag_index: usize = 0; if (id3v2_metadata) |val| { tags_slice[tag_index] = .{ .id3v2 = val }; tag_index += 1; } if (flac_metadata) |val| { tags_slice[tag_index] = .{ .flac = val }; tag_index += 1; } if (mp4_metadata) |val| { tags_slice[tag_index] = .{ .mp4 = val }; tag_index += 1; } return AllMetadata{ .tags = tags_slice, .allocator = allocator, }; } test "taglib compare" { const allocator = std.testing.allocator; //const filepath = "/media/drive4/music/Wolfpack - Allday Hell [EAC-FLAC]/01 - No Neo Bastards.flac"; const filepath = "/media/drive4/music/'selvə - セルヴァ/'selvə- - セルヴァ - 01 estens.mp3"; var probed_metadata = try getTagLibMetadata(allocator, null, filepath); defer probed_metadata.deinit(); var file = try std.fs.cwd().openFile(filepath, .{}); defer file.close(); var stream_source = std.io.StreamSource{ .file = file }; var metadata = try meta.readAll(allocator, &stream_source); defer metadata.deinit(); try compareMetadata(allocator, &probed_metadata, &metadata); }
test/test_against_taglib.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const data = @embedFile("../inputs/day09.txt"); pub fn main() anyerror!void { var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa_impl.deinit(); const gpa = gpa_impl.allocator(); return main_with_allocator(gpa); } pub fn main_with_allocator(allocator: Allocator) anyerror!void { const basin = try parse(allocator, data[0..]); defer { for (basin.items) |row| { row.deinit(); } basin.deinit(); } print("Part 1: {d}\n", .{part1(basin)}); print("Part 2: {d}\n", .{try part2(allocator, basin)}); } const Basin = std.ArrayList(std.ArrayList(u4)); fn parse(allocator: Allocator, input: []const u8) !Basin { var basin = try Basin.initCapacity(allocator, 100); var lines = std.mem.tokenize(u8, input, "\n"); while (lines.next()) |line| { if (line.len > 0) { var row = try std.ArrayList(u4).initCapacity(allocator, 100); for (line) |c| { try row.append(@intCast(u4, c - '0')); } try basin.append(row); } } return basin; } fn part1(basin: Basin) usize { var risk_level: usize = 0; for (basin.items) |row, y| { for (row.items) |height, x| { var lower = true; // up if (y > 0 and basin.items[y - 1].items[x] <= height) lower = false; // down if (y < basin.items.len - 1 and basin.items[y + 1].items[x] <= height) lower = false; // left if (x > 0 and row.items[x - 1] <= height) lower = false; // right if (x < row.items.len - 1 and row.items[x + 1] <= height) lower = false; if (lower) { risk_level += 1 + height; } } } return risk_level; } const Point = struct { x: isize, y: isize, }; const PointSet = std.AutoHashMap(Point, void); fn add_point(arena: *std.heap.ArenaAllocator, point: Point, basin: Basin, unique_basins: *std.ArrayList(*PointSet), basins_map: *std.AutoHashMap(Point, *PointSet)) anyerror!void { if (basins_map.contains(point)) return; const x = point.x; const y = point.y; if (y < 0 or y >= basin.items.len) return; const row = basin.items[@intCast(usize, y)]; if (x < 0 or x >= row.items.len) return; const height = row.items[@intCast(usize, x)]; if (height == 9) return; const adjacent = [4]Point{ .{ .x = x - 1, .y = y }, .{ .x = x + 1, .y = y }, .{ .x = x, .y = y - 1 }, .{ .x = x, .y = y + 1 }, }; var found_adjacent = false; for (adjacent) |p| { if (p.y < 0 or p.y >= basin.items.len or p.x < 0 or p.x >= row.items.len) continue; if (basin.items[@intCast(usize, p.y)].items[@intCast(usize, p.x)] == 9) continue; if (basins_map.get(p)) |ptr| { try ptr.put(point, .{}); try basins_map.put(point, ptr); found_adjacent = true; break; } } if (!found_adjacent) { const ptr = try arena.allocator().create(PointSet); ptr.* = PointSet.init(arena.allocator()); try ptr.*.put(point, .{}); try basins_map.put(point, ptr); try unique_basins.append(ptr); } for (adjacent) |p| { try add_point(arena, p, basin, unique_basins, basins_map); } } fn part2(allocator: Allocator, basin: Basin) !usize { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); var unique_basins = std.ArrayList(*PointSet).init(allocator); defer unique_basins.deinit(); var basins_map = std.AutoHashMap(Point, *PointSet).init(allocator); defer basins_map.deinit(); try basins_map.ensureTotalCapacity(100 * 100); for (basin.items) |row, y| { for (row.items) |_, x| { const point = Point{ .x = @intCast(isize, x), .y = @intCast(isize, y) }; try add_point(&arena, point, basin, &unique_basins, &basins_map); } } var top_3 = [3]usize{ 0, 0, 0 }; { for (unique_basins.items) |b| { var current: usize = b.*.count(); for (top_3) |*t| { if (current > t.*) { std.mem.swap(usize, &current, t); } } } } return top_3[0] * top_3[1] * top_3[2]; } test "smoke basin" { const input = \\2199943210 \\3987894921 \\9856789892 \\8767896789 \\9899965678 ; const allocator = std.testing.allocator; const basin = try parse(allocator, input[0..]); defer { for (basin.items) |row| { row.deinit(); } basin.deinit(); } try std.testing.expectEqual(@as(usize, 15), part1(basin)); try std.testing.expectEqual(@as(usize, 1134), try part2(allocator, basin)); }
src/day09.zig
const std = @import("std"); const subcommands = @import("../subcommands.zig"); const shared = @import("../shared.zig"); const zsw = @import("zsw"); const log = std.log.scoped(.basename); pub const name = "basename"; pub const usage = \\Usage: {0s} NAME [SUFFIX] \\ or: {0s} OPTION... NAME... \\ \\Print NAME with any leading directory components removed. \\If specified, also remove a trailing SUFFIX. \\ \\Mandatory arguments to long options are mandatory for short options too. \\ -a, --multiple support multiple arguments and treat each as a NAME \\ -s, --suffix=SUFFIX remove a trailing SUFFIX; implies -a \\ -z, --zero end each output line with NUL, not newline \\ --help display this help and exit \\ --version output version information and exit \\ ; // io // .{ // .stderr: std.io.Writer, // .stdin: std.io.Reader, // .stdout: std.io.Writer, // }, // args // struct { // fn next(self: *Self) ?shared.Arg, // // // intended to only be called for the first argument // fn nextWithHelpOrVersion(self: *Self) !?shared.Arg, // // fn nextRaw(self: *Self) ?[]const u8, // } pub fn execute( allocator: std.mem.Allocator, io: anytype, args: anytype, system: zsw.System, exe_path: []const u8, ) subcommands.Error!u8 { _ = system; const z = shared.tracy.traceNamed(@src(), name); defer z.end(); var opt_arg: ?shared.Arg = try args.nextWithHelpOrVersion(); var zero: bool = false; var multiple: bool = false; var opt_multiple_suffix: ?[]const u8 = null; while (opt_arg) |*arg| : (opt_arg = args.next()) { switch (arg.arg_type) { .longhand => |longhand| { if (std.mem.eql(u8, longhand, "zero")) { zero = true; log.debug("got zero longhand", .{}); } else if (std.mem.eql(u8, longhand, "multiple")) { multiple = true; log.debug("got multiple longhand", .{}); } else if (std.mem.eql(u8, longhand, "suffix")) { return shared.printInvalidUsage( @This(), io, exe_path, "option '--suffix' requires an argument", ); } else { return try shared.printInvalidUsageAlloc( @This(), allocator, io, exe_path, "unrecognized option '--{s}'", .{longhand}, ); } }, .longhand_with_value => |longhand_with_value| { if (std.mem.eql(u8, longhand_with_value.longhand, "suffix")) { multiple = true; opt_multiple_suffix = longhand_with_value.value; log.debug("got suffix longhand with value = {s}", .{longhand_with_value.value}); } else { return try shared.printInvalidUsageAlloc( @This(), allocator, io, exe_path, "unrecognized option '{s}'", .{longhand_with_value.value}, ); } }, .positional => { if (multiple) { return try multipleArguments( io, args, arg.raw, zero, opt_multiple_suffix, ); } return try singleArgument(allocator, io, args, exe_path, arg.raw, zero); }, .shorthand => |*shorthand| { while (shorthand.next()) |char| { if (char == 'z') { zero = true; log.debug("got zero shorthand", .{}); } else if (char == 'a') { multiple = true; log.debug("got multiple shorthand", .{}); } else if (char == 's') { opt_multiple_suffix = args.nextRaw() orelse { return shared.printInvalidUsage( @This(), io, exe_path, "option requires an argument -- 's'", ); }; multiple = true; log.debug("got suffix shorthand with value = {s}", .{opt_multiple_suffix orelse unreachable}); } else { return try shared.printInvalidUsageAlloc( @This(), allocator, io, exe_path, "unrecognized option -- '{c}'", .{char}, ); } } }, } } return shared.printInvalidUsage(@This(), io, exe_path, "missing operand"); } fn singleArgument( allocator: std.mem.Allocator, io: anytype, args: anytype, exe_path: []const u8, first_arg: []const u8, zero: bool, ) !u8 { const z = shared.tracy.traceNamed(@src(), "single argument"); defer z.end(); z.addText(first_arg); const opt_suffix: ?[]const u8 = blk: { const suffix_zone = shared.tracy.traceNamed(@src(), "get suffix"); defer suffix_zone.end(); const arg = args.nextRaw() orelse break :blk null; if (args.nextRaw()) |additional_arg| { return try shared.printInvalidUsageAlloc( @This(), allocator, io, exe_path, "extra operand '{s}'", .{additional_arg}, ); } suffix_zone.addText(arg); break :blk arg; }; log.info("singleArgument called, first_arg='{s}', zero={}, suffix='{s}'", .{ first_arg, zero, opt_suffix }); const basename = getBasename(first_arg, opt_suffix); log.debug("got basename: '{s}'", .{basename}); io.stdout.writeAll(basename) catch |err| { shared.unableToWriteTo("stdout", io, err); return 1; }; io.stdout.writeByte(if (zero) 0 else '\n') catch |err| { shared.unableToWriteTo("stdout", io, err); return 1; }; return 0; } fn multipleArguments( io: anytype, args: anytype, first_arg: []const u8, zero: bool, opt_suffix: ?[]const u8, ) !u8 { const z = shared.tracy.traceNamed(@src(), "multiple arguments"); defer z.end(); log.info("multipleArguments called, first_arg='{s}', zero={}, suffix='{s}'", .{ first_arg, zero, opt_suffix }); const end_byte: u8 = if (zero) 0 else '\n'; var opt_arg: ?[]const u8 = first_arg; var arg_frame = shared.tracy.namedFrame("arg"); defer arg_frame.end(); while (opt_arg) |arg| : ({ arg_frame.mark(); opt_arg = args.nextRaw(); }) { const argument_zone = shared.tracy.traceNamed(@src(), "process arg"); defer argument_zone.end(); argument_zone.addText(arg); const basename = getBasename(arg, opt_suffix); log.debug("got basename: '{s}'", .{basename}); io.stdout.writeAll(basename) catch |err| { shared.unableToWriteTo("stdout", io, err); return 1; }; io.stdout.writeByte(end_byte) catch |err| { shared.unableToWriteTo("stdout", io, err); return 1; }; } return 0; } fn getBasename(buf: []const u8, opt_suffix: ?[]const u8) []const u8 { const basename = std.fs.path.basename(buf); return if (opt_suffix) |suffix| if (std.mem.lastIndexOf(u8, basename, suffix)) |end_index| basename[0..end_index] else basename else basename; } test "basename no args" { try subcommands.testError(@This(), &.{}, .{}, "missing operand"); } test "basename help" { try subcommands.testHelp(@This()); } test "basename version" { try subcommands.testVersion(@This()); } comptime { std.testing.refAllDecls(@This()); }
src/subcommands/basename.zig
const std = @import("std"); const assert = std.debug.assert; const expectEqual = std.testing.expectEqual; pub const Player = enum(u1) { P1, P2, pub inline fn foe(self: Player) Player { return @intToEnum(Player, ~@enumToInt(self)); } pub inline fn ident(self: Player, id: u3) ID { assert(id > 0 and id <= 6); return .{ .id = id, .player = self }; } }; test "Player" { try expectEqual(Player.P2, Player.P1.foe()); try expectEqual(@as(u8, 0b0001), @bitCast(u8, Player.P1.ident(1))); try expectEqual(@as(u8, 0b1101), @bitCast(u8, Player.P2.ident(5))); } pub const ID = packed struct { id: u3 = 0, player: Player = .P1, _: u4 = 0, comptime { assert(@sizeOf(ID) == 1); } pub inline fn int(self: ID) u4 { return @truncate(u4, @bitCast(u8, self)); } pub inline fn from(id: u4) ID { return @bitCast(ID, @as(u8, id)); } }; test "ID" { try expectEqual(@as(u8, 0b0001), @bitCast(u8, ID{ .player = .P1, .id = 1 })); try expectEqual(@as(u8, 0b1101), @bitCast(u8, ID{ .player = .P2, .id = 5 })); const id = ID{ .player = .P2, .id = 4 }; try expectEqual(id, ID.from(id.int())); } pub const Choice = packed struct { type: Choice.Type = .Pass, _: u2 = 0, data: u4 = 0, pub const Type = enum(u2) { Pass, Move, Switch, }; comptime { assert(@sizeOf(Choice) == 1); } }; test "Choice" { const p1: Choice = .{ .type = .Move, .data = 4 }; const p2: Choice = .{ .type = .Switch, .data = 5 }; try expectEqual(5, p2.data); try expectEqual(Choice.Type.Move, p1.type); try expectEqual(0b0100_0001, @bitCast(u8, p1)); try expectEqual(0b0101_0010, @bitCast(u8, p2)); } pub const Result = packed struct { type: Result.Type = .None, p1: Choice.Type = .Pass, p2: Choice.Type = .Pass, pub const Type = enum(u4) { None, Win, Lose, Tie, Error, // Desync, EBC, etc. }; pub const Tie: Result = .{ .type = .Tie }; pub const Win: Result = .{ .type = .Win }; pub const Lose: Result = .{ .type = .Lose }; pub const Error: Result = .{ .type = .Error }; pub const Default: Result = .{ .p1 = .Move, .p2 = .Move }; comptime { assert(@sizeOf(Result) == 1); } }; test "Result" { try expectEqual(0b0101_0000, @bitCast(u8, Result.Default)); try expectEqual(0b1000_0000, @bitCast(u8, Result{ .p2 = .Switch })); }
src/lib/common/data.zig
const std = @import("std"); const stdx = @import("stdx.zig"); const t = stdx.testing; const assert = std.debug.assert; const mem = std.mem; const log = stdx.log.scoped(.unicode); // Adapted from std.unicode.utf16lToUtf8Alloc pub fn utf16beToUtf8Alloc(alloc: mem.Allocator, utf16be: []const u16) ![]u8 { var result = std.ArrayList(u8).init(alloc); // optimistically guess that it will all be ascii. try result.ensureTotalCapacity(utf16be.len); var out_index: usize = 0; var it = Utf16BeIterator.init(utf16be); while (try it.nextCodepoint()) |codepoint| { const utf8_len = std.unicode.utf8CodepointSequenceLength(codepoint) catch unreachable; try result.resize(result.items.len + utf8_len); assert((std.unicode.utf8Encode(codepoint, result.items[out_index..]) catch unreachable) == utf8_len); out_index += utf8_len; } return result.toOwnedSlice(); } pub const Utf16BeIterator = struct { bytes: []const u8, i: usize, pub fn init(s: []const u16) Utf16BeIterator { return Utf16BeIterator{ .bytes = mem.sliceAsBytes(s), .i = 0, }; } pub fn nextCodepoint(it: *@This()) !?u21 { assert(it.i <= it.bytes.len); if (it.i == it.bytes.len) return null; const c0: u21 = mem.readIntBig(u16, it.bytes[it.i..][0..2]); if (c0 & ~@as(u21, 0x03ff) == 0xd800) { // surrogate pair it.i += 2; if (it.i >= it.bytes.len) return error.DanglingSurrogateHalf; const c1: u21 = mem.readIntBig(u16, it.bytes[it.i..][0..2]); if (c1 & ~@as(u21, 0x03ff) != 0xdc00) return error.ExpectedSecondSurrogateHalf; it.i += 2; return 0x10000 + (((c0 & 0x03ff) << 10) | (c1 & 0x03ff)); } else if (c0 & ~@as(u21, 0x03ff) == 0xdc00) { return error.UnexpectedSecondSurrogateHalf; } else { it.i += 2; return c0; } } }; // TODO: Check unicode spaces too. pub fn isSpace(cp: u21) bool { if (cp < 128) { return std.ascii.isSpace(@intCast(u8, cp)); } return false; } pub fn printCodepoint(cp: u21) void { const buf: []u8 = undefined; _ = std.unicode.utf8Encode(cp, buf) catch unreachable; log.debug("codepoint: {} {s}", .{ cp, buf[0..std.unicode.utf8CodepointSequenceLength(cp)] }); } /// Like std.ascii.toLowerString but for unicode. pub fn toLowerString(out: []u8, input: []const u8) ![]u8 { const view = try std.unicode.Utf8View.init(input); var iter = view.iterator(); var i: u32 = 0; while (iter.nextCodepointSlice()) |cp_slice| { const cp = std.unicode.utf8Decode(cp_slice) catch unreachable; if (cp <= std.math.maxInt(u8)) { const lower = std.ascii.toLower(@intCast(u8, cp)); out[i] = lower; i += 1; } else { std.mem.copy(u8, out[i..i+cp_slice.len], cp_slice); i += @intCast(u32, cp_slice.len); } } return out[0..i]; } test "toLowerString" { var buf: [100]u8 = undefined; try t.eqSlice(u8, try toLowerString(&buf, "FOO"), "foo"); try t.eqSlice(u8, try toLowerString(&buf, "FO🐥O"), "fo🐥o"); }
stdx/unicode.zig
const std = @import("std"); const builtin = @import("builtin"); const net = @import("net"); const ssl = @import("ssl"); const http = @import("http"); const Uri = @import("uri").Uri; const tar = @import("tar.zig"); const zzz = @import("zzz"); const Allocator = std.mem.Allocator; const gzipStream = std.compress.gzip.gzipStream; const github_pem = @embedFile("github-com-chain.pem"); pub const Import = struct { name: []const u8, root: []const u8, src: Source, integrity: ?Integrity = null, const Self = @This(); const Hasher = std.crypto.hash.blake2.Blake2b128; const Source = union(enum) { github: Github, url: []const u8, const Github = struct { user: []const u8, repo: []const u8, ref: []const u8, }; fn addToZNode(source: Source, root: *zzz.ZNode, tree: anytype) !void { if (@typeInfo(@TypeOf(tree)) != .Pointer) { @compileError("tree must be pointer"); } switch (source) { .github => |github| { var node = try tree.addNode(root, .{ .String = "github" }); var repo_key = try tree.addNode(node, .{ .String = "repo" }); _ = try tree.addNode(repo_key, .{ .String = github.repo }); var user_key = try tree.addNode(node, .{ .String = "user" }); _ = try tree.addNode(user_key, .{ .String = github.user }); var ref_key = try tree.addNode(node, .{ .String = "ref" }); _ = try tree.addNode(ref_key, .{ .String = github.ref }); }, .url => |url| { var node = try tree.addNode(root, .{ .String = "url" }); _ = try tree.addNode(node, .{ .String = url }); }, } } fn fromZNode(node: *const zzz.ZNode) !Source { const key = try getZNodeString(node); return if (std.mem.eql(u8, "github", key)) blk: { var repo: ?[]const u8 = null; var user: ?[]const u8 = null; var ref: ?[]const u8 = null; var child = node.*.child; while (child) |elem| : (child = child.?.sibling) { const gh_key = try getZNodeString(elem); if (std.mem.eql(u8, "repo", gh_key)) { repo = try getZNodeString(elem.child orelse return error.MissingRepo); } else if (std.mem.eql(u8, "user", gh_key)) { user = try getZNodeString(elem.child orelse return error.MissingUser); } else if (std.mem.eql(u8, "ref", gh_key)) { ref = try getZNodeString(elem.child orelse return error.MissingRef); } else { return error.UnknownKey; } } break :blk Source{ .github = .{ .repo = repo orelse return error.MissingRepo, .user = user orelse return error.MissingUser, .ref = ref orelse return error.MissingRef, }, }; } else if (std.mem.eql(u8, "url", key)) Source{ .url = try getZNodeString(node.*.child orelse return error.MissingUrl) } else { return error.UnknownKey; }; } }; const Integrity = struct { hash_type: HashType, digest: []const u8, const HashType = @TagType(HashEngine); // TODO: compiler bug if we try to do smart comptime stuff const HashEngine = union(enum) { md5: std.crypto.hash.Md5, sha1: std.crypto.hash.Sha1, sha224: std.crypto.hash.sha2.Sha224, sha256: std.crypto.hash.sha2.Sha256, sha384: std.crypto.hash.sha2.Sha384, sha512: std.crypto.hash.sha2.Sha512, blake2b512: std.crypto.hash.blake2.Blake2b512, }; fn fromZNode(node: *const zzz.ZNode) !Integrity { const key = try getZNodeString(node); const hash_type_str = try getZNodeString(node); const hash_type = inline for (std.meta.fields(HashType)) |field| { if (std.mem.eql(u8, field.name, hash_type_str)) break @field(HashType, field.name); } else return error.UnknownHashType; const digest = try getZNodeString(node.*.child orelse return error.MissingDigest); return Integrity{ .hash_type = hash_type, .digest = digest, }; } }; const Checker = struct { engine: ?Integrity.HashEngine, connection: Connection.Reader, const Self = @This(); const ReadError = Connection.Reader.Error; pub const Reader = std.io.Reader(*Checker, ReadError, read); fn init(integrity: ?Integrity, connection: Connection.Reader) !Checker { return Checker{ .connection = connection, .engine = if (integrity) |integ| switch (integ.hash_type) { .md5 => Integrity.HashEngine{ .md5 = std.crypto.hash.Md5.init(.{}) }, .sha1 => Integrity.HashEngine{ .sha1 = std.crypto.hash.Sha1.init(.{}) }, .sha224 => Integrity.HashEngine{ .sha224 = std.crypto.hash.sha2.Sha224.init(.{}) }, .sha256 => Integrity.HashEngine{ .sha256 = std.crypto.hash.sha2.Sha256.init(.{}) }, .sha384 => Integrity.HashEngine{ .sha384 = std.crypto.hash.sha2.Sha384.init(.{}) }, .sha512 => Integrity.HashEngine{ .sha512 = std.crypto.hash.sha2.Sha512.init(.{}) }, .blake2b512 => Integrity.HashEngine{ .blake2b512 = std.crypto.hash.blake2.Blake2b512.init(.{}) }, } else null, }; } fn read(self: *Checker, buf: []u8) ReadError!usize { const n = try self.connection.read(buf); if (self.engine) |engine| { switch (engine) { .md5 => self.engine.?.md5.update(buf[0..n]), .sha1 => self.engine.?.sha1.update(buf[0..n]), .sha224 => self.engine.?.sha224.update(buf[0..n]), .sha256 => self.engine.?.sha256.update(buf[0..n]), .sha384 => self.engine.?.sha384.update(buf[0..n]), .sha512 => self.engine.?.sha512.update(buf[0..n]), .blake2b512 => self.engine.?.blake2b512.update(buf[0..n]), } } return n; } fn reader(self: *Checker) Reader { return .{ .context = self }; } fn compareDigest(engine: anytype, digest: []const u8) !bool { var out: [@TypeOf(engine.*).digest_length]u8 = undefined; var fmted: [@TypeOf(engine.*).digest_length * 2]u8 = undefined; engine.final(&out); var fixed_buffer = std.io.fixedBufferStream(&fmted); for (out) |i| try std.fmt.format(fixed_buffer.writer(), "{x:0>2}", .{i}); return std.mem.eql(u8, &fmted, digest); } fn check(self: *Checker, digest: ?[]const u8) !void { // TODO: make generic for when there are more var out: [std.crypto.hash.sha2.Sha256.digest_length]u8 = undefined; var fmted: [std.crypto.hash.sha2.Sha256.digest_length * 2]u8 = undefined; if (self.engine) |engine| { if (digest == null) return error.MissingDigest; if (!switch (engine) { .md5 => try compareDigest(&self.engine.?.md5, digest.?), .sha1 => try compareDigest(&self.engine.?.sha1, digest.?), .sha224 => try compareDigest(&self.engine.?.sha224, digest.?), .sha256 => try compareDigest(&self.engine.?.sha256, digest.?), .sha384 => try compareDigest(&self.engine.?.sha384, digest.?), .sha512 => try compareDigest(&self.engine.?.sha512, digest.?), .blake2b512 => try compareDigest(&self.engine.?.blake2b512, digest.?), }) return error.FailedHash; } } }; fn getZNodeString(node: *const zzz.ZNode) ![]const u8 { return switch (node.value) { .String => |str| str, else => return error.NotAString, }; } pub fn fromZNode(node: *const zzz.ZNode) !Import { const name = switch (node.value) { .String => |str| str, else => return error.MissingName, }; var root_path: ?[]const u8 = null; var src: ?Source = null; var integrity: ?Integrity = null; var child = node.*.child; while (child) |elem| : (child = child.?.sibling) { const key = try getZNodeString(elem); if (std.mem.eql(u8, "root", key)) { root_path = if (elem.child) |child_node| try getZNodeString(child_node) else null; } else if (std.mem.eql(u8, "src", key)) { src = try Source.fromZNode(elem.child orelse return error.MissingSourceType); } else if (std.mem.eql(u8, "integrity", key)) { integrity = try Integrity.fromZNode(elem.child orelse return error.MissingHashType); } else { return error.UnknownKey; } } return Import{ .name = name, .root = root_path orelse "src/main.zig", .src = src orelse return error.MissingSource, .integrity = integrity, }; } pub fn addToZNode(self: Self, root: *zzz.ZNode, tree: anytype) !void { if (@typeInfo(@TypeOf(tree)) != .Pointer) { @compileError("tree must be pointer"); } const import = try tree.addNode(root, .{ .String = self.name }); const root_path = try tree.addNode(import, .{ .String = "root" }); _ = try tree.addNode(root_path, .{ .String = self.root }); const src = try tree.addNode(import, .{ .String = "src" }); try self.src.addToZNode(src, tree); if (self.integrity) |integrity| { const integ_node = try tree.addNode(import, .{ .String = "integrity" }); const hash_type = try tree.addNode(integ_node, .{ .String = inline for (std.meta.fields(Integrity.HashType)) |field| { if (integrity.hash_type == @field(Integrity.HashType, field.name)) break field.name; } else unreachable, }); _ = try tree.addNode(hash_type, .{ .String = integrity.digest }); } } pub fn urlToSource(url: []const u8) !Source { const prefix = "https://github.com/"; if (!std.mem.startsWith(u8, url, prefix)) return error.SorryOnlyGithubOverHttps; var it = std.mem.tokenize(url[prefix.len..], "/"); const user = it.next() orelse return error.MissingUser; const repo = it.next() orelse return error.MissingRepo; return Source{ .github = .{ .user = user, .repo = repo, .ref = "master", }, }; } pub fn toUrl(self: Import, allocator: *Allocator) ![]const u8 { return switch (self.src) { .github => |github| try std.mem.join(allocator, "/", &[_][]const u8{ "https://api.github.com/repos", github.user, github.repo, "tarball", github.ref, }), .url => |url| try allocator.dupe(u8, url), }; } pub fn path(self: Self, allocator: *Allocator, base_path: []const u8) ![]const u8 { const file_proto = "file://"; switch (self.src) { .url => |url| { if (std.mem.startsWith(u8, url, file_proto)) return url[file_proto.len..]; }, else => {}, } const digest = try self.hash(); return try std.fs.path.join(allocator, &[_][]const u8{ base_path, &digest }); } pub fn hash(self: Self) ![Hasher.digest_length * 2]u8 { var tree = zzz.ZTree(1, 100){}; var root = try tree.addNode(null, .Null); try self.src.addToZNode(root, &tree); var buf: [std.mem.page_size]u8 = undefined; var digest: [Hasher.digest_length]u8 = undefined; var ret: [Hasher.digest_length * 2]u8 = undefined; var fixed_buffer = std.io.fixedBufferStream(&buf); try root.stringify(fixed_buffer.writer()); Hasher.hash(fixed_buffer.getWritten(), &digest, .{}); // TODO: format properly const lookup = [_]u8{ '0', '1', '2', '3', '4', '5', '6', '7', '8', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; for (digest) |val, i| { ret[2 * i] = lookup[val >> 4]; ret[(2 * i) + 1] = lookup[@truncate(u4, val)]; } return ret; } pub fn fetch(self: Self, allocator: *Allocator, deps_path: []const u8) !void { // don't need to fetch if it's a file:// switch (self.src) { .url => |url| { if (std.mem.startsWith(u8, url, "file://")) { if (self.integrity != null) std.log.warn("integrity is not checked for '{}', importing directly through the filesystem", .{self.name}); return; } }, else => {}, } var source = try HttpsSource.init(allocator, self); defer source.deinit(); var checker = try Checker.init(self.integrity, source.reader()); var gzip = try gzipStream(allocator, checker.reader()); defer gzip.deinit(); var deps_dir = try std.fs.cwd().makeOpenPath(deps_path, .{ .access_sub_paths = true }); defer deps_dir.close(); const digest = try self.hash(); var dest_dir = try deps_dir.makeOpenPath(&digest, .{ .access_sub_paths = true }); try tar.instantiate(allocator, dest_dir, gzip.reader(), 1); checker.check(if (self.integrity) |integ| integ.digest else null) catch |err| { if (err == error.FailedHash) { // delete dest_dir and its contents dest_dir.close(); try deps_dir.deleteTree(&digest); } return err; }; defer dest_dir.close(); } pub fn getBranchHead(self: Self, allocator: *Allocator) !?[]const u8 { var source = try HttpsSource.init(allocator, self); defer source.deinit(); var gzip = try gzipStream(allocator, source.reader()); defer gzip.deinit(); const header = try gzip.reader().readStruct(tar.Header); if (header.typeflag != .pax_global) return null; const body = try gzip.reader().readUntilDelimiterAlloc( allocator, 0, try std.fmt.parseUnsigned(usize, &header.size, 8), ); const commit_key = "comment="; const commit_idx = (std.mem.indexOf(u8, body, commit_key) orelse return null) + commit_key.len; const end_idx = for (body[commit_idx..]) |c, i| { switch (c) { 'A'...'F', 'a'...'f', '0'...'9' => continue, else => break commit_idx + i, } } else body.len; return try allocator.dupe(u8, body[commit_idx..end_idx]); } }; const Connection = struct { ssl_client: ssl.Client, ssl_socket: SslStream, socket: net.Socket, socket_reader: net.Socket.Reader, socket_writer: net.Socket.Writer, http_buf: [std.mem.page_size]u8, http_client: HttpClient, window: []const u8, const SslStream = ssl.Stream(*net.Socket.Reader, *net.Socket.Writer); const HttpClient = http.base.client.BaseClient(SslStream.DstInStream, SslStream.DstOutStream); const Self = @This(); pub fn init(allocator: *Allocator, hostname: [:0]const u8, port: u16, x509: *ssl.x509.Minimal) !*Self { var ret = try allocator.create(Self); errdefer allocator.destroy(ret); ret.window = &[_]u8{}; ret.ssl_client = ssl.Client.init(x509.getEngine()); ret.ssl_client.relocate(); try ret.ssl_client.reset(hostname, false); ret.socket = try net.connectToHost(allocator, hostname, port, .tcp); errdefer ret.socket.close(); ret.socket_reader = ret.socket.reader(); ret.socket_writer = ret.socket.writer(); ret.ssl_socket = ssl.initStream( ret.ssl_client.getEngine(), &ret.socket_reader, &ret.socket_writer, ); errdefer ret.ssl_socket.close catch {}; ret.http_client = http.base.client.create( &ret.http_buf, ret.ssl_socket.inStream(), ret.ssl_socket.outStream(), ); return ret; } pub fn deinit(self: *Self) void { self.ssl_socket.close() catch {}; self.socket.close(); } pub const Reader = HttpClient.PayloadReader; pub fn reader(self: *Self) Reader { return self.http_client.reader(); } }; const HttpsSource = struct { allocator: *Allocator, trust_anchor: ssl.TrustAnchorCollection, x509: ssl.x509.Minimal, connection: *Connection, const Self = @This(); pub fn init(allocator: *Allocator, import: Import) !Self { var url = try import.toUrl(allocator); defer allocator.free(url); var trust_anchor = ssl.TrustAnchorCollection.init(allocator); errdefer trust_anchor.deinit(); switch (builtin.os.tag) { .linux => pem: { const file = std.fs.openFileAbsolute("/etc/ssl/cert.pem", .{ .read = true }) catch |err| { if (err == error.FileNotFound) { try trust_anchor.appendFromPEM(github_pem); break :pem; } else return err; }; defer file.close(); const certs = try file.readToEndAlloc(allocator, 500000); defer allocator.free(certs); try trust_anchor.appendFromPEM(certs); }, else => { try trust_anchor.appendFromPEM(github_pem); }, } var x509 = ssl.x509.Minimal.init(trust_anchor); var conn: *Connection = undefined; redirect: while (true) { const uri = try Uri.parse(url, true); const port = uri.port orelse 443; if (!std.mem.eql(u8, uri.scheme, "https")) { return if (uri.scheme.len == 0) error.PutQuotesAroundUrl else error.HttpsOnly; } const hostname = try std.cstr.addNullByte(allocator, uri.host.name); defer allocator.free(hostname); conn = try Connection.init(allocator, hostname, port, &x509); try conn.http_client.writeStatusLine("GET", uri.path); try conn.http_client.writeHeaderValue("Host", hostname); try conn.http_client.writeHeaderValue("User-Agent", "zkg"); try conn.http_client.writeHeaderValue("Accept", "*/*"); try conn.http_client.finishHeaders(); try conn.ssl_socket.flush(); var redirect = false; while (try conn.http_client.next()) |event| { switch (event) { .status => |status| switch (status.code) { 200 => {}, 302 => redirect = true, else => { std.log.err("got an HTTP return code: {}", .{status.code}); return error.HttpFailed; }, }, .header => |header| { if (redirect and std.mem.eql(u8, "location", header.name)) { allocator.free(url); url = try allocator.dupe(u8, header.value); conn.deinit(); continue :redirect; } }, .head_done => break :redirect, else => |val| std.debug.print("got other: {}\n", .{val}), } } } std.log.info("fetching {}", .{url}); return Self{ .allocator = allocator, .trust_anchor = trust_anchor, .x509 = x509, .connection = conn, }; } pub fn deinit(self: *Self) void { self.connection.deinit(); self.trust_anchor.deinit(); } pub fn reader(self: *Self) Connection.Reader { return self.connection.reader(); } };
src/import.zig
const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const native_endian = builtin.cpu.arch.endian(); test "correct size of packed structs" { const T1 = packed struct { one: u8, three: [3]u8 }; try expectEqual(4, @sizeOf(T1)); try expectEqual(4 * 8, @bitSizeOf(T1)); const T2 = packed struct { three: [3]u8, one: u8 }; try expectEqual(4, @sizeOf(T2)); try expectEqual(4 * 8, @bitSizeOf(T2)); const T3 = packed struct { _1: u1, x: u7, _: u24 }; try expectEqual(4, @sizeOf(T3)); try expectEqual(4 * 8, @bitSizeOf(T3)); const T4 = packed struct { _1: u1, x: u7, _2: u8, _3: u16 }; try expectEqual(4, @sizeOf(T4)); try expectEqual(4 * 8, @bitSizeOf(T4)); const T5 = packed struct { _1: u1, x: u7, _2: u16, _3: u8 }; try expectEqual(4, @sizeOf(T5)); try expectEqual(4 * 8, @bitSizeOf(T5)); } test "flags in packed structs" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; const Flags1 = packed struct { // first 8 bits b0_0: u1, b0_1: u1, b0_2: u1, b0_3: u1, b0_4: u1, b0_5: u1, b0_6: u1, b0_7: u1, // 7 more bits b1_0: u1, b1_1: u1, b1_2: u1, b1_3: u1, b1_4: u1, b1_5: u1, b1_6: u1, // some padding to fill to 24 bits _: u9, }; try expectEqual(@sizeOf(u24), @sizeOf(Flags1)); try expectEqual(24, @bitSizeOf(Flags1)); const Flags2 = packed struct { // byte 0 b0_0: u1, b0_1: u1, b0_2: u1, b0_3: u1, b0_4: u1, b0_5: u1, b0_6: u1, b0_7: u1, // partial byte 1 (but not 8 bits) b1_0: u1, b1_1: u1, b1_2: u1, b1_3: u1, b1_4: u1, b1_5: u1, b1_6: u1, // some padding that should yield @sizeOf(Flags2) == 4 _: u10, }; try expectEqual(@sizeOf(u25), @sizeOf(Flags2)); try expectEqual(25, @bitSizeOf(Flags2)); const Flags3 = packed struct { // byte 0 b0_0: u1, b0_1: u1, b0_2: u1, b0_3: u1, b0_4: u1, b0_5: u1, b0_6: u1, b0_7: u1, // byte 1 b1_0: u1, b1_1: u1, b1_2: u1, b1_3: u1, b1_4: u1, b1_5: u1, b1_6: u1, b1_7: u1, // some padding that should yield @sizeOf(Flags2) == 4 _: u16, // it works, if the padding is 8-based }; try expectEqual(@sizeOf(u32), @sizeOf(Flags3)); try expectEqual(32, @bitSizeOf(Flags3)); } test "arrays in packed structs" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; const T1 = packed struct { array: [3][3]u8 }; const T2 = packed struct { array: [9]u8 }; try expectEqual(@sizeOf(u72), @sizeOf(T1)); try expectEqual(72, @bitSizeOf(T1)); try expectEqual(@sizeOf(u72), @sizeOf(T2)); try expectEqual(72, @bitSizeOf(T2)); } test "consistent size of packed structs" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; const TxData1 = packed struct { data: u8, _23: u23, full: bool = false }; const TxData2 = packed struct { data: u9, _22: u22, full: bool = false }; const register_size_bits = 32; const register_size_bytes = @sizeOf(u32); try expectEqual(register_size_bits, @bitSizeOf(TxData1)); try expectEqual(register_size_bytes, @sizeOf(TxData1)); try expectEqual(register_size_bits, @bitSizeOf(TxData2)); try expectEqual(register_size_bytes, @sizeOf(TxData2)); const TxData3 = packed struct { a: u32, b: [3]u8 }; const TxData4 = packed struct { a: u32, b: u24 }; const TxData5 = packed struct { a: [3]u8, b: u32 }; const TxData6 = packed struct { a: u24, b: u32 }; const expectedBitSize = 56; const expectedByteSize = @sizeOf(u56); try expectEqual(expectedBitSize, @bitSizeOf(TxData3)); try expectEqual(expectedByteSize, @sizeOf(TxData3)); try expectEqual(expectedBitSize, @bitSizeOf(TxData4)); try expectEqual(expectedByteSize, @sizeOf(TxData4)); try expectEqual(expectedBitSize, @bitSizeOf(TxData5)); try expectEqual(expectedByteSize, @sizeOf(TxData5)); try expectEqual(expectedBitSize, @bitSizeOf(TxData6)); try expectEqual(expectedByteSize, @sizeOf(TxData6)); } test "correct sizeOf and offsets in packed structs" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const PStruct = packed struct { bool_a: bool, bool_b: bool, bool_c: bool, bool_d: bool, bool_e: bool, bool_f: bool, u1_a: u1, bool_g: bool, u1_b: u1, u3_a: u3, u10_a: u10, u10_b: u10, }; try expectEqual(0, @offsetOf(PStruct, "bool_a")); try expectEqual(0, @bitOffsetOf(PStruct, "bool_a")); try expectEqual(0, @offsetOf(PStruct, "bool_b")); try expectEqual(1, @bitOffsetOf(PStruct, "bool_b")); try expectEqual(0, @offsetOf(PStruct, "bool_c")); try expectEqual(2, @bitOffsetOf(PStruct, "bool_c")); try expectEqual(0, @offsetOf(PStruct, "bool_d")); try expectEqual(3, @bitOffsetOf(PStruct, "bool_d")); try expectEqual(0, @offsetOf(PStruct, "bool_e")); try expectEqual(4, @bitOffsetOf(PStruct, "bool_e")); try expectEqual(0, @offsetOf(PStruct, "bool_f")); try expectEqual(5, @bitOffsetOf(PStruct, "bool_f")); try expectEqual(0, @offsetOf(PStruct, "u1_a")); try expectEqual(6, @bitOffsetOf(PStruct, "u1_a")); try expectEqual(0, @offsetOf(PStruct, "bool_g")); try expectEqual(7, @bitOffsetOf(PStruct, "bool_g")); try expectEqual(1, @offsetOf(PStruct, "u1_b")); try expectEqual(8, @bitOffsetOf(PStruct, "u1_b")); try expectEqual(1, @offsetOf(PStruct, "u3_a")); try expectEqual(9, @bitOffsetOf(PStruct, "u3_a")); try expectEqual(1, @offsetOf(PStruct, "u10_a")); try expectEqual(12, @bitOffsetOf(PStruct, "u10_a")); try expectEqual(2, @offsetOf(PStruct, "u10_b")); try expectEqual(22, @bitOffsetOf(PStruct, "u10_b")); try expectEqual(4, @sizeOf(PStruct)); if (native_endian == .Little) { const s1 = @bitCast(PStruct, @as(u32, 0x12345678)); try expectEqual(false, s1.bool_a); try expectEqual(false, s1.bool_b); try expectEqual(false, s1.bool_c); try expectEqual(true, s1.bool_d); try expectEqual(true, s1.bool_e); try expectEqual(true, s1.bool_f); try expectEqual(@as(u1, 1), s1.u1_a); try expectEqual(false, s1.bool_g); try expectEqual(@as(u1, 0), s1.u1_b); try expectEqual(@as(u3, 3), s1.u3_a); try expectEqual(@as(u10, 0b1101000101), s1.u10_a); try expectEqual(@as(u10, 0b0001001000), s1.u10_b); const s2 = @bitCast(packed struct { x: u1, y: u7, z: u24 }, @as(u32, 0xd5c71ff4)); try expectEqual(@as(u1, 0), s2.x); try expectEqual(@as(u7, 0b1111010), s2.y); try expectEqual(@as(u24, 0xd5c71f), s2.z); } const S = packed struct { a: u32, pad: [3]u32, b: u32 }; try expectEqual(16, @offsetOf(S, "b")); try expectEqual(128, @bitOffsetOf(S, "b")); try expectEqual(@sizeOf(u160), @sizeOf(S)); } test "nested packed structs" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; // TODO if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; // TODO const S1 = packed struct { a: u8, b: u8, c: u8 }; const S2 = packed struct { d: u8, e: u8, f: u8 }; const S3 = packed struct { x: S1, y: S2 }; const S3Padded = packed struct { s3: S3, pad: u16 }; try expectEqual(48, @bitSizeOf(S3)); try expectEqual(@sizeOf(u48), @sizeOf(S3)); try expectEqual(3, @offsetOf(S3, "y")); try expectEqual(24, @bitOffsetOf(S3, "y")); if (native_endian == .Little) { const s3 = @bitCast(S3Padded, @as(u64, 0xe952d5c71ff4)).s3; try expectEqual(@as(u8, 0xf4), s3.x.a); try expectEqual(@as(u8, 0x1f), s3.x.b); try expectEqual(@as(u8, 0xc7), s3.x.c); try expectEqual(@as(u8, 0xd5), s3.y.d); try expectEqual(@as(u8, 0x52), s3.y.e); try expectEqual(@as(u8, 0xe9), s3.y.f); } const S4 = packed struct { a: i32, b: i8 }; const S5 = packed struct { a: i32, b: i8, c: S4 }; const S6 = packed struct { a: i32, b: S4, c: i8 }; const expectedBitSize = 80; const expectedByteSize = @sizeOf(u80); try expectEqual(expectedBitSize, @bitSizeOf(S5)); try expectEqual(expectedByteSize, @sizeOf(S5)); try expectEqual(expectedBitSize, @bitSizeOf(S6)); try expectEqual(expectedByteSize, @sizeOf(S6)); try expectEqual(5, @offsetOf(S5, "c")); try expectEqual(40, @bitOffsetOf(S5, "c")); try expectEqual(9, @offsetOf(S6, "c")); try expectEqual(72, @bitOffsetOf(S6, "c")); } test "regular in irregular packed struct" { if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const Irregular = packed struct { bar: Regular = Regular{}, _: u24 = 0, pub const Regular = packed struct { a: u16 = 0, b: u8 = 0 }; }; var foo = Irregular{}; foo.bar.a = 235; foo.bar.b = 42; try expectEqual(@as(u16, 235), foo.bar.a); try expectEqual(@as(u8, 42), foo.bar.b); } test "byte-aligned field pointer offsets" { if (builtin.zig_backend == .stage1) return error.SkipZigTest; if (builtin.zig_backend == .stage2_wasm) return error.SkipZigTest; if (builtin.zig_backend == .stage2_c) return error.SkipZigTest; if (builtin.zig_backend == .stage2_x86_64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_aarch64) return error.SkipZigTest; if (builtin.zig_backend == .stage2_arm) return error.SkipZigTest; const S = struct { const A = packed struct { a: u8, b: u8, c: u8, d: u8, }; const B = packed struct { a: u16, b: u16, }; fn doTheTest() !void { var a: A = .{ .a = 1, .b = 2, .c = 3, .d = 4, }; switch (comptime builtin.cpu.arch.endian()) { .Little => { comptime assert(@TypeOf(&a.a) == *align(4) u8); comptime assert(@TypeOf(&a.b) == *u8); comptime assert(@TypeOf(&a.c) == *align(2) u8); comptime assert(@TypeOf(&a.d) == *u8); }, .Big => { // TODO re-evaluate packed struct endianness comptime assert(@TypeOf(&a.a) == *align(4:0:4) u8); comptime assert(@TypeOf(&a.b) == *align(4:8:4) u8); comptime assert(@TypeOf(&a.c) == *align(4:16:4) u8); comptime assert(@TypeOf(&a.d) == *align(4:24:4) u8); }, } try expect(a.a == 1); try expect(a.b == 2); try expect(a.c == 3); try expect(a.d == 4); a.a += 1; try expect(a.a == 2); try expect(a.b == 2); try expect(a.c == 3); try expect(a.d == 4); a.b += 1; try expect(a.a == 2); try expect(a.b == 3); try expect(a.c == 3); try expect(a.d == 4); a.c += 1; try expect(a.a == 2); try expect(a.b == 3); try expect(a.c == 4); try expect(a.d == 4); a.d += 1; try expect(a.a == 2); try expect(a.b == 3); try expect(a.c == 4); try expect(a.d == 5); var b: B = .{ .a = 1, .b = 2, }; switch (comptime builtin.cpu.arch.endian()) { .Little => { comptime assert(@TypeOf(&b.a) == *align(4) u16); comptime assert(@TypeOf(&b.b) == *u16); }, .Big => { comptime assert(@TypeOf(&b.a) == *align(4:0:4) u16); comptime assert(@TypeOf(&b.b) == *align(4:16:4) u16); }, } try expect(b.a == 1); try expect(b.b == 2); b.a += 1; try expect(b.a == 2); try expect(b.b == 2); b.b += 1; try expect(b.a == 2); try expect(b.b == 3); } }; try S.doTheTest(); comptime try S.doTheTest(); }
test/behavior/packed-struct.zig
const std = @import("std"); const math = @import("std").math; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const assert = std.debug.assert; const print = std.debug.print; const testing = std.testing; const input = @embedFile("./input.txt"); pub fn main() anyerror!void { print("Day 3: Binary Diagnostic\n", .{}); print("Part 1: {d}\n", .{part1()}); // print("Part 2: {d}\n", .{part2()}); } fn bitArrayToUnsignedInt(bits: []u2) u64 { var integer: u64 = 0; for (bits) |bit| { integer = (integer << 1) + bit; } return integer; } fn part1() !u64 { const allocator = std.heap.page_allocator; const report = try readReport(input); const numbers = try parseNumbers(report); var bitWidth: u64 = report[0].len; var total: u64 = numbers.len; var offset: u64 = 0; const bits = try allocator.alloc(u2, bitWidth); defer allocator.free(bits); const ones = try allocator.alloc(u64, bitWidth); defer allocator.free(ones); for (bits) |*x| x.* = 0; for (ones) |*x| x.* = 0; while (offset < bitWidth) { var mask = math.pow(u64, 2, bitWidth - offset) / 2; for (numbers) |number| { if (number & mask != 0) { ones[offset] = @as(u64, ones[offset]) + @as(u64, 1); } } offset += 1; } for (ones) |count, i| { bits[i] = @boolToInt(2 * count >= total); } const gamma: u64 = bitArrayToUnsignedInt(bits); const epsilon: u64 = ~gamma & 0xFFF; // print("lines: {[total]d}\n", .{ .total = total }); // print("ones: {[ones]d}\n", .{ .ones = ones }); // print("bits: {[bits]d}\n", .{ .bits = bits }); // print("gamma: {[gamma]d}\n", .{ .gamma = gamma }); // print("epsilon: {[epsilon]d}\n", .{ .epsilon = epsilon }); return gamma * epsilon; } test "day03.part1" { @setEvalBranchQuota(200_000); try testing.expectEqual(@as(u64, 3549854), try part1()); } fn readReport(whole_input: []const u8) ![][]const u8 { var report = ArrayList([]const u8).init(std.heap.page_allocator); defer report.deinit(); var lines_iter = std.mem.split(u8, std.mem.trimRight(u8, whole_input, "\n"), "\n"); while (lines_iter.next()) |line| { try report.append(line); } return report.toOwnedSlice(); } fn parseNumbers(report: [][]const u8) ![]u64 { var numbers = ArrayList(u64).init(std.heap.page_allocator); defer numbers.deinit(); for (report) |line| { try numbers.append(try std.fmt.parseInt(u64, line, 2)); } return numbers.toOwnedSlice(); }
src/day03/day03.zig
const std = @import("std"); const io = std.io; const Allocator = std.mem.Allocator; pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = &arena.allocator; var buf: [4000]u8 = undefined; var stream = io.bufferedReader(io.getStdIn().reader()); var rd = stream.reader(); var lexer = Lexer.init(alloc); const readToken = TokenReader(@TypeOf(rd)).readToken; var valid: usize = 0; var seen: usize = 0; var fields = Fields{}; while (try readToken(&lexer, rd)) |token| { switch (token) { .separator => { seen += 1; if (fields.valid()) valid += 1; fields = Fields{}; }, .word => |word| { _ = fields.setField(word); }, } } std.log.notice("Seen = {} Valid = {}", .{ seen, valid }); } // Lexer code that was more fun to write than the rest of this problem. const Buffer = std.ArrayList(u8); pub const Kind = enum { separator, word, }; pub const Token = union(Kind) { separator: void, word: []const u8, }; const Lexer = struct { const Self = @This(); const State = enum { token, ws, nl, sep, word, end, eof, invalid, }; pub const Error = error{ UnshiftOverflow, InvalidState, }; state: State = .token, pending: ?u8 = null, token: Buffer, chunk: []u8 = undefined, buf: [256]u8 = undefined, fn init(allocator: *Allocator) Self { var self = Self{ .token = Buffer.init(allocator), }; self.chunk = self.buf[0..0]; return self; } fn unshift(self: *Self, c: u8) Error!void { if (self.pending != null) { return Error.UnshiftOverflow; } self.pending = c; } fn shift(self: *Self) ?u8 { if (self.pending) |c| { self.pending = null; return c; } if (self.chunk.len == 0) { return null; } const c = self.chunk[0]; self.chunk = self.chunk[1..]; return c; } fn lexChar(self: *Self, c: u8) !?Token { return switch (self.state) { .token => try self.lexToken(c), .ws => try self.lexSpace(c), .nl => try self.lexNL(c), .word => try self.lexWord(c), .sep => try self.lexSep(c), else => Error.InvalidState, }; } fn lexToken(self: *Self, c: u8) !?Token { // Reset token buffer to 0 length. Never allocs. self.token.resize(0) catch unreachable; switch (c) { ' ' => self.state = .ws, '\n' => self.state = .nl, else => { try self.unshift(c); self.state = .word; }, } return null; } fn lexSpace(self: *Self, c: u8) !?Token { if (c != ' ' and c != '\n') { self.state = .token; try self.unshift(c); } return null; } fn lexNL(self: *Self, c: u8) !?Token { switch (c) { '\n' => self.state = .sep, // If a line is just whitespace, treat it as a newline. ' ' => {}, else => { try self.unshift(c); self.state = .token; }, } return null; } fn lexSep(self: *Self, c: u8) !?Token { if (c == '\n') { return null; } try self.unshift(c); self.state = .token; return .separator; } fn lexWord(self: *Self, c: u8) !?Token { switch (c) { '\x00'...' ' => { self.state = .token; try self.unshift(c); return Token{ .word = self.token.items }; }, else => { try self.token.append(c); return null; }, } } }; // Lexer type tied to a given Reader type. pub fn TokenReader(comptime Reader: type) type { return struct { const Self = @This(); pub fn readToken(lex: *Lexer, reader: Reader) !?Token { // NOTE: There's a hack in here to account for producing a separator // at EOF followed by a null (to end a while(..) with the optional). // It'd probably be better to handle this by just returning an EOF // token but I got lazy. switch (lex.state) { .end => { lex.state = .eof; return .separator; }, .eof => { lex.state = .invalid; return null; }, else => {}, } while (true) { while (lex.shift()) |c| { if (try lex.lexChar(c)) |token| return token; } const nread = try reader.read(&lex.buf); if (nread == 0) { switch (lex.state) { .word => { lex.state = .end; return Token{ .word = lex.token.items }; }, else => { lex.state = .eof; return .separator; }, } } lex.chunk = lex.buf[0..nread]; } } }; } // Awful field parsing functions. const Fields = packed struct { const Self = @This(); byr: u1 = 0, // Birth Year iyr: u1 = 0, // Issue Year eyr: u1 = 0, // Expiration Year hgt: u1 = 0, // Height hcl: u1 = 0, // Hair Color ecl: u1 = 0, // Eye Color pid: u1 = 0, // Passport ID cid: u1 = 0, // Country ID fn valid(self: Self) bool { return (self.byr & self.iyr & self.eyr & self.hgt & self.hcl & self.ecl & self.pid) == 1; } fn setField(self: *Self, text: []const u8) bool { if (text.len < 5 or text[3] != ':') return false; const head = text[0..3]; const tail = text[4..]; if (std.mem.eql(u8, head, "byr")) { if (!inYear(1920, 2002, tail)) return false; self.byr = 1; } else if (std.mem.eql(u8, head, "iyr")) { if (!inYear(2010, 2020, tail)) return false; self.iyr = 1; } else if (std.mem.eql(u8, head, "eyr")) { if (!inYear(2020, 2030, tail)) return false; self.eyr = 1; } else if (std.mem.eql(u8, head, "hgt")) { if (switch (height(tail) catch return false) { .cm => |cm| cm < 150 or 193 < cm, .in => |in| in < 59 or 76 < in, }) return false; self.hgt = 1; } else if (std.mem.eql(u8, head, "hcl")) { if (!isHex(tail)) return false; self.hcl = 1; } else if (std.mem.eql(u8, head, "ecl")) { if (!isHairColor(tail)) return false; self.ecl = 1; } else if (std.mem.eql(u8, head, "pid")) { if (tail.len != 9 or !isDigits(tail)) return false; self.pid = 1; } else if (std.mem.eql(u8, head, "cid")) { self.cid = 1; } else { return false; } return true; } }; const HeightError = error{Invalid}; const Unit = enum { cm, in }; const Height = union(Unit) { cm: usize, in: usize, }; fn height(text: []const u8) !Height { const n = text.len; if (n < 3) return HeightError.Invalid; const unit = text[n - 2 ..]; const meas = text[0 .. n - 2]; const i = try std.fmt.parseInt(usize, meas, 10); if (std.mem.eql(u8, unit, "cm")) { return Height{ .cm = i }; } else if (std.mem.eql(u8, unit, "in")) { return Height{ .in = i }; } return HeightError.Invalid; } fn inYear(comptime min: u16, comptime max: u16, in: []const u8) bool { if (in.len != 4) return false; const i = std.fmt.parseInt(u16, in, 10) catch return false; return min <= i and i <= max; } fn isHexDigit(c: u8) bool { return switch (c) { 'a'...'f', 'A'...'F', '0'...'9' => true, else => false, }; } fn isHex(text: []const u8) bool { return text.len == 7 and text[0] == '#' and for (text[1..]) |c| { if (!isHexDigit(c)) break false; } else true; } const hairColors = [_][]const u8{ "amb", "blu", "brn", "gry", "grn", "hzl", "oth", }; fn isHairColor(text: []const u8) bool { for (hairColors) |col| if (std.mem.eql(u8, text, col)) return true; return false; } fn isDigits(text: []const u8) bool { for (text) |c| { switch (c) { '0'...'9' => {}, else => return false, } } return true; } fn hasPrefix(slice: []const u8, prefix: []const u8) bool { if (slice.len < prefix.len) return false; return std.mem.eql(u8, slice[0..prefix.len], prefix); }
day4/src/main.zig
const std = @import("std"); const semitone = std.math.pow(f32, 2.0, 1.0 / 12.0); fn calcNoteFreq(note: i32) f32 { return std.math.pow(f32, semitone, @intToFloat(f32, note)); } // note: these are relative frequencies, so you'll have to multiply the value // by the value you want as a4 (such as 440.0) pub const c0 = calcNoteFreq(-57); pub const cs0 = calcNoteFreq(-56); pub const db0 = calcNoteFreq(-56); pub const d0 = calcNoteFreq(-55); pub const ds0 = calcNoteFreq(-54); pub const eb0 = calcNoteFreq(-54); pub const e0 = calcNoteFreq(-53); pub const f0 = calcNoteFreq(-52); pub const fs0 = calcNoteFreq(-51); pub const gb0 = calcNoteFreq(-51); pub const g0 = calcNoteFreq(-50); pub const gs0 = calcNoteFreq(-49); pub const ab0 = calcNoteFreq(-49); pub const a0 = calcNoteFreq(-48); pub const as0 = calcNoteFreq(-47); pub const bb0 = calcNoteFreq(-47); pub const b0 = calcNoteFreq(-46); pub const c1 = calcNoteFreq(-45); pub const cs1 = calcNoteFreq(-44); pub const db1 = calcNoteFreq(-44); pub const d1 = calcNoteFreq(-43); pub const ds1 = calcNoteFreq(-42); pub const eb1 = calcNoteFreq(-42); pub const e1 = calcNoteFreq(-41); pub const f1 = calcNoteFreq(-40); pub const fs1 = calcNoteFreq(-39); pub const gb1 = calcNoteFreq(-39); pub const g1 = calcNoteFreq(-38); pub const gs1 = calcNoteFreq(-37); pub const ab1 = calcNoteFreq(-37); pub const a1 = calcNoteFreq(-36); pub const as1 = calcNoteFreq(-35); pub const bb1 = calcNoteFreq(-35); pub const b1 = calcNoteFreq(-34); pub const c2 = calcNoteFreq(-33); pub const cs2 = calcNoteFreq(-32); pub const db2 = calcNoteFreq(-32); pub const d2 = calcNoteFreq(-31); pub const ds2 = calcNoteFreq(-30); pub const eb2 = calcNoteFreq(-30); pub const e2 = calcNoteFreq(-29); pub const f2 = calcNoteFreq(-28); pub const fs2 = calcNoteFreq(-27); pub const gb2 = calcNoteFreq(-27); pub const g2 = calcNoteFreq(-26); pub const gs2 = calcNoteFreq(-25); pub const ab2 = calcNoteFreq(-25); pub const a2 = calcNoteFreq(-24); pub const as2 = calcNoteFreq(-23); pub const bb2 = calcNoteFreq(-23); pub const b2 = calcNoteFreq(-22); pub const c3 = calcNoteFreq(-21); pub const cs3 = calcNoteFreq(-20); pub const db3 = calcNoteFreq(-20); pub const d3 = calcNoteFreq(-19); pub const ds3 = calcNoteFreq(-18); pub const eb3 = calcNoteFreq(-18); pub const e3 = calcNoteFreq(-17); pub const f3 = calcNoteFreq(-16); pub const fs3 = calcNoteFreq(-15); pub const gb3 = calcNoteFreq(-15); pub const g3 = calcNoteFreq(-14); pub const gs3 = calcNoteFreq(-13); pub const ab3 = calcNoteFreq(-13); pub const a3 = calcNoteFreq(-12); pub const as3 = calcNoteFreq(-11); pub const bb3 = calcNoteFreq(-11); pub const b3 = calcNoteFreq(-10); pub const c4 = calcNoteFreq(-9); pub const cs4 = calcNoteFreq(-8); pub const db4 = calcNoteFreq(-8); pub const d4 = calcNoteFreq(-7); pub const ds4 = calcNoteFreq(-6); pub const eb4 = calcNoteFreq(-6); pub const e4 = calcNoteFreq(-5); pub const f4 = calcNoteFreq(-4); pub const fs4 = calcNoteFreq(-3); pub const gb4 = calcNoteFreq(-3); pub const g4 = calcNoteFreq(-2); pub const gs4 = calcNoteFreq(-1); pub const ab4 = calcNoteFreq(-1); pub const a4 = calcNoteFreq(0); pub const as4 = calcNoteFreq(1); pub const bb4 = calcNoteFreq(1); pub const b4 = calcNoteFreq(2); pub const c5 = calcNoteFreq(3); pub const cs5 = calcNoteFreq(4); pub const db5 = calcNoteFreq(4); pub const d5 = calcNoteFreq(5); pub const ds5 = calcNoteFreq(6); pub const eb5 = calcNoteFreq(6); pub const e5 = calcNoteFreq(7); pub const f5 = calcNoteFreq(8); pub const fs5 = calcNoteFreq(9); pub const gb5 = calcNoteFreq(9); pub const g5 = calcNoteFreq(10); pub const gs5 = calcNoteFreq(11); pub const ab5 = calcNoteFreq(11); pub const a5 = calcNoteFreq(12); pub const as5 = calcNoteFreq(13); pub const bb5 = calcNoteFreq(13); pub const b5 = calcNoteFreq(14); pub const c6 = calcNoteFreq(15); pub const cs6 = calcNoteFreq(16); pub const db6 = calcNoteFreq(16); pub const d6 = calcNoteFreq(17); pub const ds6 = calcNoteFreq(18); pub const eb6 = calcNoteFreq(18); pub const e6 = calcNoteFreq(19); pub const f6 = calcNoteFreq(20); pub const fs6 = calcNoteFreq(21); pub const gb6 = calcNoteFreq(21); pub const g6 = calcNoteFreq(22); pub const gs6 = calcNoteFreq(23); pub const ab6 = calcNoteFreq(23); pub const a6 = calcNoteFreq(24); pub const as6 = calcNoteFreq(25); pub const bb6 = calcNoteFreq(25); pub const b6 = calcNoteFreq(26); pub const c7 = calcNoteFreq(27); pub const cs7 = calcNoteFreq(28); pub const db7 = calcNoteFreq(28); pub const d7 = calcNoteFreq(29); pub const ds7 = calcNoteFreq(30); pub const eb7 = calcNoteFreq(30); pub const e7 = calcNoteFreq(31); pub const f7 = calcNoteFreq(32); pub const fs7 = calcNoteFreq(33); pub const gb7 = calcNoteFreq(33); pub const g7 = calcNoteFreq(34); pub const gs7 = calcNoteFreq(35); pub const ab7 = calcNoteFreq(35); pub const a7 = calcNoteFreq(36); pub const as7 = calcNoteFreq(37); pub const bb7 = calcNoteFreq(37); pub const b7 = calcNoteFreq(38); pub const c8 = calcNoteFreq(39); pub const cs8 = calcNoteFreq(40); pub const db8 = calcNoteFreq(40); pub const d8 = calcNoteFreq(41); pub const ds8 = calcNoteFreq(42); pub const eb8 = calcNoteFreq(42); pub const e8 = calcNoteFreq(43); pub const f8 = calcNoteFreq(44); pub const fs8 = calcNoteFreq(45); pub const gb8 = calcNoteFreq(45); pub const g8 = calcNoteFreq(46); pub const gs8 = calcNoteFreq(47); pub const ab8 = calcNoteFreq(47); pub const a8 = calcNoteFreq(48); pub const as8 = calcNoteFreq(49); pub const bb8 = calcNoteFreq(49); pub const b8 = calcNoteFreq(50);
src/zang-12tet.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const Blob = @import("sqlite.zig").Blob; /// Text is used to represent a SQLite TEXT value when binding a parameter or reading a column. pub const Text = struct { data: []const u8 }; const BindMarker = struct { /// Contains the expected type for a bind parameter which will be checked /// at comptime when calling bind on a statement. /// /// A null means the bind parameter is untyped so there won't be comptime checking. typed: ?type = null, }; fn isNamedIdentifierChar(c: u8) bool { return std.ascii.isAlpha(c) or std.ascii.isDigit(c) or c == '_'; } pub const ParsedQuery = struct { const Self = @This(); bind_markers: [128]BindMarker, nb_bind_markers: usize, query: [1024]u8, query_size: usize, pub fn from(comptime query: []const u8) Self { // This contains the final SQL query after parsing with our // own typed bind markers removed. comptime var buf: [query.len]u8 = undefined; comptime var pos = 0; comptime var state = .start; comptime var current_bind_marker_type: [256]u8 = undefined; comptime var current_bind_marker_type_pos = 0; comptime var parsed_query: ParsedQuery = undefined; parsed_query.nb_bind_markers = 0; inline for (query) |c| { switch (state) { .start => switch (c) { '?', ':', '@', '$' => { parsed_query.bind_markers[parsed_query.nb_bind_markers] = BindMarker{}; current_bind_marker_type_pos = 0; state = .bind_marker; buf[pos] = c; pos += 1; }, '\'', '"' => { state = .inside_string; buf[pos] = c; pos += 1; }, else => { buf[pos] = c; pos += 1; }, }, .inside_string => switch (c) { '\'', '"' => { state = .start; buf[pos] = c; pos += 1; }, else => { buf[pos] = c; pos += 1; }, }, .bind_marker => switch (c) { '?', ':', '@', '$' => @compileError("invalid multiple '?', ':', '$' or '@'."), '{' => { state = .bind_marker_type; }, else => { if (isNamedIdentifierChar(c)) { // This is the start of a named bind marker. state = .bind_marker_identifier; } else { // This is a unnamed, untyped bind marker. state = .start; parsed_query.bind_markers[parsed_query.nb_bind_markers].typed = null; parsed_query.nb_bind_markers += 1; } buf[pos] = c; pos += 1; }, }, .bind_marker_identifier => switch (c) { '?', ':', '@', '$' => @compileError("unregconised multiple '?', ':', '$' or '@'."), '{' => { state = .bind_marker_type; current_bind_marker_type_pos = 0; }, else => { if (!isNamedIdentifierChar(c)) { // This marks the end of the named bind marker. state = .start; parsed_query.nb_bind_markers += 1; } buf[pos] = c; pos += 1; }, }, .bind_marker_type => switch (c) { '}' => { state = .start; const type_info_string = current_bind_marker_type[0..current_bind_marker_type_pos]; // Handles optional types const typ = if (type_info_string[0] == '?') blk: { const child_type = parseType(type_info_string[1..]); break :blk @Type(std.builtin.TypeInfo{ .Optional = .{ .child = child_type, }, }); } else blk: { break :blk parseType(type_info_string); }; parsed_query.bind_markers[parsed_query.nb_bind_markers].typed = typ; parsed_query.nb_bind_markers += 1; }, else => { current_bind_marker_type[current_bind_marker_type_pos] = c; current_bind_marker_type_pos += 1; }, }, else => { @compileError("invalid state " ++ @tagName(state)); }, } } // The last character was a bind marker prefix so this must be an untyped bind marker. switch (state) { .bind_marker => { parsed_query.bind_markers[parsed_query.nb_bind_markers].typed = null; parsed_query.nb_bind_markers += 1; }, .bind_marker_identifier => { parsed_query.nb_bind_markers += 1; }, .start => {}, else => @compileError("invalid final state " ++ @tagName(state) ++ ", this means you wrote an incomplete bind marker type"), } mem.copy(u8, &parsed_query.query, &buf); parsed_query.query_size = pos; return parsed_query; } fn parseType(type_info: []const u8) type { if (type_info.len <= 0) @compileError("invalid type info " ++ type_info); // Integer if (mem.eql(u8, "usize", type_info)) return usize; if (mem.eql(u8, "isize", type_info)) return isize; if (type_info[0] == 'u' or type_info[0] == 'i') { return @Type(std.builtin.TypeInfo{ .Int = std.builtin.TypeInfo.Int{ .signedness = if (type_info[0] == 'i') .signed else .unsigned, .bits = std.fmt.parseInt(usize, type_info[1..type_info.len], 10) catch { @compileError("invalid type info " ++ type_info); }, }, }); } // Float if (mem.eql(u8, "f16", type_info)) return f16; if (mem.eql(u8, "f32", type_info)) return f32; if (mem.eql(u8, "f64", type_info)) return f64; if (mem.eql(u8, "f128", type_info)) return f128; // Bool if (mem.eql(u8, "bool", type_info)) return bool; // Strings if (mem.eql(u8, "[]const u8", type_info) or mem.eql(u8, "[]u8", type_info)) { return []const u8; } if (mem.eql(u8, "text", type_info)) return Text; if (mem.eql(u8, "blob", type_info)) return Blob; @compileError("invalid type info " ++ type_info); } pub fn getQuery(comptime self: *const Self) []const u8 { return self.query[0..self.query_size]; } }; test "parsed query: query" { const testCase = struct { query: []const u8, expected_query: []const u8, }; const testCases = &[_]testCase{ .{ .query = "INSERT INTO user(id, name, age) VALUES(?{usize}, ?{[]const u8}, ?{u32})", .expected_query = "INSERT INTO user(id, name, age) VALUES(?, ?, ?)", }, .{ .query = "SELECT id, name, age FROM user WHER age > ?{u32} AND age < ?{u32}", .expected_query = "SELECT id, name, age FROM user WHER age > ? AND age < ?", }, .{ .query = "SELECT id, name, age FROM user WHER age > ? AND age < ?", .expected_query = "SELECT id, name, age FROM user WHER age > ? AND age < ?", }, }; inline for (testCases) |tc| { @setEvalBranchQuota(100000); comptime var parsed_query = ParsedQuery.from(tc.query); try testing.expectEqualStrings(tc.expected_query, parsed_query.getQuery()); } } test "parsed query: bind markers types" { const testCase = struct { query: []const u8, expected_marker: BindMarker, }; const prefixes = &[_][]const u8{ "?", "?123", ":", ":hello", "$", "$foobar", "@", "@name", }; inline for (prefixes) |prefix| { const testCases = &[_]testCase{ .{ .query = "foobar " ++ prefix ++ "{usize}", .expected_marker = .{ .typed = usize }, }, .{ .query = "foobar " ++ prefix ++ "{text}", .expected_marker = .{ .typed = Text }, }, .{ .query = "foobar " ++ prefix ++ "{blob}", .expected_marker = .{ .typed = Blob }, }, .{ .query = "foobar " ++ prefix, .expected_marker = .{ .typed = null }, }, .{ .query = "foobar " ++ prefix ++ "{?[]const u8}", .expected_marker = .{ .typed = ?[]const u8 }, }, }; inline for (testCases) |tc| { @setEvalBranchQuota(100000); comptime var parsed_query = ParsedQuery.from(tc.query); try testing.expectEqual(1, parsed_query.nb_bind_markers); const bind_marker = parsed_query.bind_markers[0]; try testing.expectEqual(tc.expected_marker.typed, bind_marker.typed); } } } test "parsed query: bind markers identifier" { const testCase = struct { query: []const u8, expected_marker: BindMarker, }; const testCases = &[_]testCase{ .{ .query = "foobar @ABC{usize}", .expected_marker = .{ .typed = usize }, }, .{ .query = "foobar ?123{text}", .expected_marker = .{ .typed = Text }, }, .{ .query = "foobar $abc{blob}", .expected_marker = .{ .typed = Blob }, }, .{ .query = "foobar :430{u32}", .expected_marker = .{ .typed = u32 }, }, .{ .query = "foobar ?123", .expected_marker = .{}, }, .{ .query = "foobar :hola", .expected_marker = .{}, }, .{ .query = "foobar @foo", .expected_marker = .{}, }, }; inline for (testCases) |tc| { comptime var parsed_query = ParsedQuery.from(tc.query); try testing.expectEqual(@as(usize, 1), parsed_query.nb_bind_markers); const bind_marker = parsed_query.bind_markers[0]; try testing.expectEqual(tc.expected_marker, bind_marker); } } test "parsed query: query bind identifier" { const testCase = struct { query: []const u8, expected_query: []const u8, expected_nb_bind_markers: usize, }; const testCases = &[_]testCase{ .{ .query = "INSERT INTO user(id, name, age) VALUES(@id{usize}, :name{[]const u8}, $age{u32})", .expected_query = "INSERT INTO user(id, name, age) VALUES(@id, :name, $age)", .expected_nb_bind_markers = 3, }, .{ .query = "INSERT INTO user(id, name, age) VALUES($id, $name, $age)", .expected_query = "INSERT INTO user(id, name, age) VALUES($id, $name, $age)", .expected_nb_bind_markers = 3, }, .{ .query = "SELECT id, name, age FROM user WHER age > :ageGT{u32} AND age < @ageLT{u32}", .expected_query = "SELECT id, name, age FROM user WHER age > :ageGT AND age < @ageLT", .expected_nb_bind_markers = 2, }, .{ .query = "SELECT id, name, age FROM user WHER age > :ageGT AND age < $ageLT", .expected_query = "SELECT id, name, age FROM user WHER age > :ageGT AND age < $ageLT", .expected_nb_bind_markers = 2, }, .{ .query = "SELECT id, name, age FROM user WHER age > $my_age{i32} AND age < :your_age{i32}", .expected_query = "SELECT id, name, age FROM user WHER age > $my_age AND age < :your_age", .expected_nb_bind_markers = 2, }, }; inline for (testCases) |tc| { @setEvalBranchQuota(100000); comptime var parsed_query = ParsedQuery.from(tc.query); try testing.expectEqualStrings(tc.expected_query, parsed_query.getQuery()); try testing.expectEqual(tc.expected_nb_bind_markers, parsed_query.nb_bind_markers); } } test "parsed query: bind marker character inside string" { const testCase = struct { query: []const u8, exp_bind_markers: comptime_int, exp: []const u8, }; const testCases = &[_]testCase{ .{ .query = "SELECT json_extract(metadata, '$.name') AS name FROM foobar", .exp_bind_markers = 0, .exp = "SELECT json_extract(metadata, '$.name') AS name FROM foobar", }, .{ .query = "SELECT json_extract(metadata, '$.name') AS name FROM foobar WHERE name = $name{text}", .exp_bind_markers = 1, .exp = "SELECT json_extract(metadata, '$.name') AS name FROM foobar WHERE name = $name", }, }; inline for (testCases) |tc| { @setEvalBranchQuota(100000); comptime var parsed_query = ParsedQuery.from(tc.query); try testing.expectEqual(@as(usize, tc.exp_bind_markers), parsed_query.nb_bind_markers); try testing.expectEqualStrings(tc.exp, parsed_query.getQuery()); } }
query.zig
const std = @import("std"); usingnamespace std.os.windows; const DynLib = std.DynLib; const zeroes = std.mem.zeroes; const c = @cImport({ @cInclude("dsound.h"); }); pub const DSBPLAY_LOOPING = 0x00000001; pub const DirectSoundCreate = fn (pcGuidDevice: ?*c.GUID, ppDS: **IDirectSound, pUnkOuter: ?*c.IUnknown) HRESULT; pub const IID = GUID; pub const IDirectSoundVtbl = extern struct { QueryInterface: ?fn (*IDirectSound, *const IID, *LPVOID) callconv(.C) HRESULT, AddRef: ?fn (*IDirectSound) callconv(.C) ULONG, Release: ?fn (*IDirectSound) callconv(.C) ULONG, CreateSoundBuffer: ?fn (*IDirectSound, *const c.DSBUFFERDESC, **c.IDirectSoundBuffer, ?*c.IUnknown) callconv(.C) HRESULT, GetCaps: ?fn (*IDirectSound, *c.DSCAPS) callconv(.C) HRESULT, DuplicateSoundBuffer: ?fn (*IDirectSound, *c.IDirectSoundBuffer, **c.IDirectSoundBuffer) callconv(.C) HRESULT, SetCooperativeLevel: ?fn (*IDirectSound, HWND, DWORD) callconv(.C) HRESULT, Compact: ?fn (*IDirectSound) callconv(.C) HRESULT, GetSpeakerConfig: ?fn (*IDirectSound, LPDWORD) callconv(.C) HRESULT, SetSpeakerConfig: ?fn (*IDirectSound, DWORD) callconv(.C) HRESULT, Initialize: ?fn (*IDirectSound, *const GUID) callconv(.C) HRESULT, }; pub const IDirectSound = extern struct { lpVtbl: *IDirectSoundVtbl, }; pub inline fn succeeded(result: HRESULT) bool { return result >= 0; } pub var GlobalSoundBuffer: *c.IDirectSoundBuffer = undefined; pub fn IDirectSoundBuffer_Play(p: *c.IDirectSoundBuffer, dwReserved1: c_ulong, dwReserved2: c_ulong, dwFlags: c_ulong) !void { const r = p.*.lpVtbl.*.Play.?(p, dwReserved1, dwReserved2, dwFlags); if (succeeded(r)) { return; } std.debug.print("IDirectSoundBuffer_Play Error: {}\n", .{r}); return error.DirectSoundError; } pub inline fn IDirectSoundBuffer_Lock(p: anytype, a: anytype, b: anytype, c_: anytype, d: anytype, e: anytype, f: anytype, g: anytype) !void { const r = p.*.lpVtbl.*.Lock.?(p, a, b, c_, d, e, f, g); if (succeeded(r)) { return; } std.debug.print("IDirectSoundBuffer_Lock Error: {}\n", .{r}); return error.DirectSoundError; } pub inline fn IDirectSoundBuffer_Unlock(a: anytype, b: anytype, c_: anytype, d: anytype) !void { const r = GlobalSoundBuffer.*.lpVtbl.*.Unlock.?(GlobalSoundBuffer, a, b, c_, d); if (succeeded(r)) { return; } std.debug.print("IDirectSoundBuffer_Unock Error: {}\n", .{r}); return error.DirectSoundError; } pub inline fn IDirectSoundBuffer_GetCurrentPosition(a: anytype, b: anytype) !void { const r = GlobalSoundBuffer.*.lpVtbl.*.GetCurrentPosition.?(GlobalSoundBuffer, a, b); if (succeeded(r)) { return; } std.debug.print("IDirectSoundBuffer_GetCurrentPosition Error: {}\n", .{r}); return error.DirectSoundError; } pub const win32_sound_output = struct { samplesPerSecond: u32, bytesPerSample: u32, soundBufferSize: DWORD, runningSampleIndex: u32, latencySampleCount: u32, }; pub fn win32InitDSound(window: HWND, samplesPerSecond: u32, bufferSize: DWORD) void { var dsound_lib = DynLib.open("dsound.dll") catch return; if (dsound_lib.lookup(DirectSoundCreate, "DirectSoundCreate")) |directSoundCreate| { var directSound: *IDirectSound = undefined; var res = directSoundCreate(null, &directSound, null); if (succeeded(res)) { const nChannels = 2; const wBitsPerSample = 16; const nBlockAlign = @truncate(c_ushort, @divTrunc(nChannels * wBitsPerSample, 8)); var waveFormat: c.WAVEFORMATEX = .{ .wFormatTag = c.WAVE_FORMAT_PCM, .nChannels = nChannels, .nSamplesPerSec = samplesPerSecond, .nAvgBytesPerSec = nBlockAlign * samplesPerSecond, .nBlockAlign = nBlockAlign, .wBitsPerSample = wBitsPerSample, .cbSize = 0, }; if (succeeded(directSound.*.lpVtbl.*.SetCooperativeLevel.?(directSound, window, c.DSSCL_PRIORITY))) { const bufferDescription: c.DSBUFFERDESC = .{ .dwSize = @sizeOf(c.DSBUFFERDESC), .dwFlags = c.DSBCAPS_PRIMARYBUFFER, .dwBufferBytes = 0, .dwReserved = 0, .lpwfxFormat = null, .guid3DAlgorithm = zeroes(c.GUID), }; var primaryBuffer: *c.IDirectSoundBuffer = undefined; if (succeeded(directSound.*.lpVtbl.*.CreateSoundBuffer.?(directSound, &bufferDescription, &primaryBuffer, null))) { const result = primaryBuffer.*.lpVtbl.*.SetFormat.?(primaryBuffer, &waveFormat); if (succeeded(result)) { std.debug.print("Primary buffer format was set\n", .{}); } else { std.debug.print("Primary buffer format error {}\n", .{result}); } } } const secondBufferDesc: c.DSBUFFERDESC = .{ .dwSize = @sizeOf(c.DSBUFFERDESC), .dwFlags = 0, .dwBufferBytes = bufferSize, .dwReserved = 0, .lpwfxFormat = &waveFormat, .guid3DAlgorithm = zeroes(c.GUID), }; var resSec = directSound.*.lpVtbl.*.CreateSoundBuffer.?(directSound, &secondBufferDesc, &GlobalSoundBuffer, null); if (succeeded(resSec)) { std.debug.print("CreateSoundBuffer GlobalSoundBuffer success\n", .{}); } else { std.debug.print("Error CreateSoundBuffer GlobalSoundBuffer: {}\n", .{resSec}); } } else { std.debug.print("Error DirectSoundCreate: {}\n", .{res}); } } }
src/dsound.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const Condition = @This(); const Mutex = std.Thread.Mutex; const os = std.os; const assert = std.debug.assert; const testing = std.testing; const Atomic = std.atomic.Atomic; const Futex = std.Thread.Futex; impl: Impl = .{}, /// Atomically releases the Mutex, blocks the caller thread, then re-acquires the Mutex on return. /// "Atomically" here refers to accesses done on the Condition after acquiring the Mutex. /// /// The Mutex must be locked by the caller's thread when this function is called. /// A Mutex can have multiple Conditions waiting with it concurrently, but not the opposite. /// It is undefined behavior for multiple threads to wait ith different mutexes using the same Condition concurrently. /// Once threads have finished waiting with one Mutex, the Condition can be used to wait with another Mutex. /// /// A blocking call to wait() is unblocked from one of the following conditions: /// - a spurious ("at random") wake up occurs /// - a future call to `signal()` or `broadcast()` which has acquired the Mutex and is sequenced after this `wait()`. /// /// Given wait() can be interrupted spuriously, the blocking condition should be checked continuously /// irrespective of any notifications from `signal()` or `broadcast()`. pub fn wait(self: *Condition, mutex: *Mutex) void { self.impl.wait(mutex, null) catch |err| switch (err) { error.Timeout => unreachable, // no timeout provided so we shouldn't have timed-out }; } /// Atomically releases the Mutex, blocks the caller thread, then re-acquires the Mutex on return. /// "Atomically" here refers to accesses done on the Condition after acquiring the Mutex. /// /// The Mutex must be locked by the caller's thread when this function is called. /// A Mutex can have multiple Conditions waiting with it concurrently, but not the opposite. /// It is undefined behavior for multiple threads to wait ith different mutexes using the same Condition concurrently. /// Once threads have finished waiting with one Mutex, the Condition can be used to wait with another Mutex. /// /// A blocking call to `timedWait()` is unblocked from one of the following conditions: /// - a spurious ("at random") wake occurs /// - the caller was blocked for around `timeout_ns` nanoseconds, in which `error.Timeout` is returned. /// - a future call to `signal()` or `broadcast()` which has acquired the Mutex and is sequenced after this `timedWait()`. /// /// Given `timedWait()` can be interrupted spuriously, the blocking condition should be checked continuously /// irrespective of any notifications from `signal()` or `broadcast()`. pub fn timedWait(self: *Condition, mutex: *Mutex, timeout_ns: u64) error{Timeout}!void { return self.impl.wait(mutex, timeout_ns); } /// Unblocks at least one thread blocked in a call to `wait()` or `timedWait()` with a given Mutex. /// The blocked thread must be sequenced before this call with respect to acquiring the same Mutex in order to be observable for unblocking. /// `signal()` can be called with or without the relevant Mutex being acquired and have no "effect" if there's no observable blocked threads. pub fn signal(self: *Condition) void { self.impl.wake(.one); } /// Unblocks all threads currently blocked in a call to `wait()` or `timedWait()` with a given Mutex. /// The blocked threads must be sequenced before this call with respect to acquiring the same Mutex in order to be observable for unblocking. /// `broadcast()` can be called with or without the relevant Mutex being acquired and have no "effect" if there's no observable blocked threads. pub fn broadcast(self: *Condition) void { self.impl.wake(.all); } const Impl = if (builtin.single_threaded) SingleThreadedImpl else if (builtin.os.tag == .windows) WindowsImpl else FutexImpl; const Notify = enum { one, // wake up only one thread all, // wake up all threads }; const SingleThreadedImpl = struct { fn wait(self: *Impl, mutex: *Mutex, timeout: ?u64) error{Timeout}!void { _ = self; _ = mutex; // There are no other threads to wake us up. // So if we wait without a timeout we would never wake up. const timeout_ns = timeout orelse { unreachable; // deadlock detected }; std.time.sleep(timeout_ns); return error.Timeout; } fn wake(self: *Impl, comptime notify: Notify) void { // There are no other threads to wake up. _ = self; _ = notify; } }; const WindowsImpl = struct { condition: os.windows.CONDITION_VARIABLE = .{}, fn wait(self: *Impl, mutex: *Mutex, timeout: ?u64) error{Timeout}!void { var timeout_overflowed = false; var timeout_ms: os.windows.DWORD = os.windows.INFINITE; if (timeout) |timeout_ns| { // Round the nanoseconds to the nearest millisecond, // then saturating cast it to windows DWORD for use in kernel32 call. const ms = (timeout_ns +| (std.time.ns_per_ms / 2)) / std.time.ns_per_ms; timeout_ms = std.math.cast(os.windows.DWORD, ms) orelse std.math.maxInt(os.windows.DWORD); // Track if the timeout overflowed into INFINITE and make sure not to wait forever. if (timeout_ms == os.windows.INFINITE) { timeout_overflowed = true; timeout_ms -= 1; } } const rc = os.windows.kernel32.SleepConditionVariableSRW( &self.condition, &mutex.impl.srwlock, timeout_ms, 0, // the srwlock was assumed to acquired in exclusive mode not shared ); // Return error.Timeout if we know the timeout elapsed correctly. if (rc == os.windows.FALSE) { assert(os.windows.kernel32.GetLastError() == .TIMEOUT); if (!timeout_overflowed) return error.Timeout; } } fn wake(self: *Impl, comptime notify: Notify) void { switch (notify) { .one => os.windows.kernel32.WakeConditionVariable(&self.condition), .all => os.windows.kernel32.WakeAllConditionVariable(&self.condition), } } }; const FutexImpl = struct { state: Atomic(u32) = Atomic(u32).init(0), epoch: Atomic(u32) = Atomic(u32).init(0), const one_waiter = 1; const waiter_mask = 0xffff; const one_signal = 1 << 16; const signal_mask = 0xffff << 16; fn wait(self: *Impl, mutex: *Mutex, timeout: ?u64) error{Timeout}!void { // Register that we're waiting on the state by incrementing the wait count. // This assumes that there can be at most ((1<<16)-1) or 65,355 threads concurrently waiting on the same Condvar. // If this is hit in practice, then this condvar not working is the least of your concerns. var state = self.state.fetchAdd(one_waiter, .Monotonic); assert(state & waiter_mask != waiter_mask); state += one_waiter; // Temporarily release the mutex in order to block on the condition variable. mutex.unlock(); defer mutex.lock(); var futex_deadline = Futex.Deadline.init(timeout); while (true) { // Try to wake up by consuming a signal and decremented the waiter we added previously. // Acquire barrier ensures code before the wake() which added the signal happens before we decrement it and return. while (state & signal_mask != 0) { const new_state = state - one_waiter - one_signal; state = self.state.tryCompareAndSwap(state, new_state, .Acquire, .Monotonic) orelse return; } // Observe the epoch, then check the state again to see if we should wake up. // The epoch must be observed before we check the state or we could potentially miss a wake() and deadlock: // // - T1: s = LOAD(&state) // - T2: UPDATE(&s, signal) // - T2: UPDATE(&epoch, 1) + FUTEX_WAKE(&epoch) // - T1: e = LOAD(&epoch) (was reordered after the state load) // - T1: s & signals == 0 -> FUTEX_WAIT(&epoch, e) (missed the state update + the epoch change) // // Acquire barrier to ensure the epoch load happens before the state load. const epoch = self.epoch.load(.Acquire); state = self.state.load(.Monotonic); if (state & signal_mask != 0) { continue; } futex_deadline.wait(&self.epoch, epoch) catch |err| switch (err) { // On timeout, we must decrement the waiter we added above. error.Timeout => { while (true) { // If there's a signal when we're timing out, consume it and report being woken up instead. // Acquire barrier ensures code before the wake() which added the signal happens before we decrement it and return. while (state & signal_mask != 0) { const new_state = state - one_waiter - one_signal; state = self.state.tryCompareAndSwap(state, new_state, .Acquire, .Monotonic) orelse return; } // Remove the waiter we added and officially return timed out. const new_state = state - one_waiter; state = self.state.tryCompareAndSwap(state, new_state, .Monotonic, .Monotonic) orelse return err; } }, }; } } fn wake(self: *Impl, comptime notify: Notify) void { var state = self.state.load(.Monotonic); while (true) { const waiters = (state & waiter_mask) / one_waiter; const signals = (state & signal_mask) / one_signal; // Reserves which waiters to wake up by incrementing the signals count. // Therefor, the signals count is always less than or equal to the waiters count. // We don't need to Futex.wake if there's nothing to wake up or if other wake() threads have reserved to wake up the current waiters. const wakeable = waiters - signals; if (wakeable == 0) { return; } const to_wake = switch (notify) { .one => 1, .all => wakeable, }; // Reserve the amount of waiters to wake by incrementing the signals count. // Release barrier ensures code before the wake() happens before the signal it posted and consumed by the wait() threads. const new_state = state + (one_signal * to_wake); state = self.state.tryCompareAndSwap(state, new_state, .Release, .Monotonic) orelse { // Wake up the waiting threads we reserved above by changing the epoch value. // NOTE: a waiting thread could miss a wake up if *exactly* ((1<<32)-1) wake()s happen between it observing the epoch and sleeping on it. // This is very unlikely due to how many precise amount of Futex.wake() calls that would be between the waiting thread's potential preemption. // // Release barrier ensures the signal being added to the state happens before the epoch is changed. // If not, the waiting thread could potentially deadlock from missing both the state and epoch change: // // - T2: UPDATE(&epoch, 1) (reordered before the state change) // - T1: e = LOAD(&epoch) // - T1: s = LOAD(&state) // - T2: UPDATE(&state, signal) + FUTEX_WAKE(&epoch) // - T1: s & signals == 0 -> FUTEX_WAIT(&epoch, e) (missed both epoch change and state change) _ = self.epoch.fetchAdd(1, .Release); Futex.wake(&self.epoch, to_wake); return; }; } } }; test "Condition - smoke test" { var mutex = Mutex{}; var cond = Condition{}; // Try to wake outside the mutex defer cond.signal(); defer cond.broadcast(); mutex.lock(); defer mutex.unlock(); // Try to wait with a timeout (should not deadlock) try testing.expectError(error.Timeout, cond.timedWait(&mutex, 0)); try testing.expectError(error.Timeout, cond.timedWait(&mutex, std.time.ns_per_ms)); // Try to wake inside the mutex. cond.signal(); cond.broadcast(); } // Inspired from: https://github.com/Amanieu/parking_lot/pull/129 test "Condition - wait and signal" { // This test requires spawning threads if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const MultiWait = struct { mutex: Mutex = .{}, cond: Condition = .{}, threads: [num_threads]std.Thread = undefined, fn run(self: *@This()) void { self.mutex.lock(); defer self.mutex.unlock(); self.cond.wait(&self.mutex); self.cond.timedWait(&self.mutex, std.time.ns_per_ms) catch {}; self.cond.signal(); } }; var multi_wait = MultiWait{}; for (multi_wait.threads) |*t| { t.* = try std.Thread.spawn(.{}, MultiWait.run, .{&multi_wait}); } std.time.sleep(100 * std.time.ns_per_ms); multi_wait.cond.signal(); for (multi_wait.threads) |t| { t.join(); } } test "Condition - signal" { // This test requires spawning threads if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const SignalTest = struct { mutex: Mutex = .{}, cond: Condition = .{}, notified: bool = false, threads: [num_threads]std.Thread = undefined, fn run(self: *@This()) void { self.mutex.lock(); defer self.mutex.unlock(); // Use timedWait() a few times before using wait() // to test multiple threads timing out frequently. var i: usize = 0; while (!self.notified) : (i +%= 1) { if (i < 5) { self.cond.timedWait(&self.mutex, 1) catch {}; } else { self.cond.wait(&self.mutex); } } // Once we received the signal, notify another thread (inside the lock). assert(self.notified); self.cond.signal(); } }; var signal_test = SignalTest{}; for (signal_test.threads) |*t| { t.* = try std.Thread.spawn(.{}, SignalTest.run, .{&signal_test}); } { // Wait for a bit in hopes that the spawned threads start queuing up on the condvar std.time.sleep(10 * std.time.ns_per_ms); // Wake up one of them (outside the lock) after setting notified=true. defer signal_test.cond.signal(); signal_test.mutex.lock(); defer signal_test.mutex.unlock(); try testing.expect(!signal_test.notified); signal_test.notified = true; } for (signal_test.threads) |t| { t.join(); } } test "Condition - multi signal" { // This test requires spawning threads if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const num_iterations = 4; const Paddle = struct { mutex: Mutex = .{}, cond: Condition = .{}, value: u32 = 0, fn hit(self: *@This()) void { defer self.cond.signal(); self.mutex.lock(); defer self.mutex.unlock(); self.value += 1; } fn run(self: *@This(), hit_to: *@This()) !void { self.mutex.lock(); defer self.mutex.unlock(); var current: u32 = 0; while (current < num_iterations) : (current += 1) { // Wait for the value to change from hit() while (self.value == current) { self.cond.wait(&self.mutex); } // hit the next paddle try testing.expectEqual(self.value, current + 1); hit_to.hit(); } } }; var paddles = [_]Paddle{.{}} ** num_threads; var threads = [_]std.Thread{undefined} ** num_threads; // Create a circle of paddles which hit each other for (threads) |*t, i| { const paddle = &paddles[i]; const hit_to = &paddles[(i + 1) % paddles.len]; t.* = try std.Thread.spawn(.{}, Paddle.run, .{ paddle, hit_to }); } // Hit the first paddle and wait for them all to complete by hitting each other for num_iterations. paddles[0].hit(); for (threads) |t| t.join(); // The first paddle will be hit one last time by the last paddle. for (paddles) |p, i| { const expected = @as(u32, num_iterations) + @boolToInt(i == 0); try testing.expectEqual(p.value, expected); } } test "Condition - broadcasting" { // This test requires spawning threads if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 10; const BroadcastTest = struct { mutex: Mutex = .{}, cond: Condition = .{}, completed: Condition = .{}, count: usize = 0, threads: [num_threads]std.Thread = undefined, fn run(self: *@This()) void { self.mutex.lock(); defer self.mutex.unlock(); // The last broadcast thread to start tells the main test thread it's completed. self.count += 1; if (self.count == num_threads) { self.completed.signal(); } // Waits for the count to reach zero after the main test thread observes it at num_threads. // Tries to use timedWait() a bit before falling back to wait() to test multiple threads timing out. var i: usize = 0; while (self.count != 0) : (i +%= 1) { if (i < 10) { self.cond.timedWait(&self.mutex, 1) catch {}; } else { self.cond.wait(&self.mutex); } } } }; var broadcast_test = BroadcastTest{}; for (broadcast_test.threads) |*t| { t.* = try std.Thread.spawn(.{}, BroadcastTest.run, .{&broadcast_test}); } { broadcast_test.mutex.lock(); defer broadcast_test.mutex.unlock(); // Wait for all the broadcast threads to spawn. // timedWait() to detect any potential deadlocks. while (broadcast_test.count != num_threads) { try broadcast_test.completed.timedWait( &broadcast_test.mutex, 1 * std.time.ns_per_s, ); } // Reset the counter and wake all the threads to exit. broadcast_test.count = 0; broadcast_test.cond.broadcast(); } for (broadcast_test.threads) |t| { t.join(); } }
lib/std/Thread/Condition.zig
const string = @import("string.zig"); const std = @import("std"); const @"struct" = @import("../struct.zig"); const @"union" = @import("../union.zig"); const StructField = @"struct".Field; const Struct = @"struct".Struct; const UnionField = @"union".Field; const Union = @"union".Union; const debug = std.debug; const mem = std.mem; const testing = std.testing; pub fn ParseResult(comptime Input: type, comptime Result: type) type { return struct { input: Input, result: Result, }; } fn Func(comptime Result: type) type { return @TypeOf(struct { fn func(input: var) ?ParseResult(@TypeOf(input), Result) { unreachable; } }.func); } pub fn eatIf(comptime Token: type, comptime predicate: fn (Token) bool) type { return struct { pub const Result = Token; pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { const curr = input.curr() orelse return null; if (!predicate(curr)) return null; return ParseResult(@TypeOf(input), Result){ .input = input.next(), .result = curr, }; } }; } pub fn end() type { return struct { pub const Result = void; pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { if (input.curr() == null) { return ParseResult(@TypeOf(input), void){ .input = input, .result = {}, }; } return null; } }; } pub fn sequence(comptime parsers: []const type) type { return struct { pub const Result = SeqParserResult(parsers); pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { var res: Result = undefined; var next = input; inline for (@TypeOf(res).fields) |field, i| { const r = parsers[i].parse(next) orelse return null; next = r.input; res.ptr(i).* = r.result; } return ParseResult(@TypeOf(input), Result){ .input = next, .result = res, }; } }; } fn SeqParserResult(comptime parsers: []const type) type { var results: [parsers.len]StructField(usize) = undefined; for (parsers) |Par, i| results[i] = StructField(usize).init(i, Par.Result); return Struct(usize, results); } pub fn options(comptime parsers: []const type) type { return struct { pub const Result = OptParserResult(parsers); pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { inline for (parsers) |Par| { if (Par.parse(input)) |res| { return ParseResult(@TypeOf(input), Result){ .input = res.input, .result = res.result, }; } } return null; } }; } fn OptParserResult(comptime parsers: []const type) type { debug.assert(parsers.len != 0); const Res = parsers[0].Result; for (parsers[1..]) |Par| { //@compileLog(Par.Result, Res); debug.assert(Par.Result == Res); } return Res; } pub fn then( comptime Parser: type, comptime Res: type, comptime func: fn (Parser.Result) Res, ) type { return struct { pub const Result = Res; pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { const parsed = Parser.parse(input) orelse return null; const res = func(parsed.result); return ParseResult(@TypeOf(input), Result){ .input = parsed.input, .result = res, }; } }; } pub fn toVoid(comptime T: type) fn (T) void { return struct { fn toVoid(arg: T) void {} }.toVoid; } pub const nothing = struct { pub const Result = void; pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { return ParseResult(@TypeOf(input), Result){ .input = input, .result = {}, }; } }; fn refFunc() type { unreachable; } pub fn ref(comptime Res: type, comptime f: @TypeOf(refFunc)) type { return struct { pub const Result = Res; pub fn parse(input: var) ?ParseResult(@TypeOf(input), Result) { return f().parse(input); } }; } fn isPred(comptime c: u8) fn (u8) bool { return struct { fn predicate(char: u8) bool { return char == c; } }.predicate; } fn testSuccess(comptime P: type, str: []const u8, result: var) void { const res = P.parse(string.Input.init(str)) orelse unreachable; comptime testing.expectEqual(@sizeOf(P.Result), @sizeOf(@TypeOf(result))); if (@sizeOf(P.Result) != 0) testing.expectEqualSlices(u8, &mem.toBytes(result), &mem.toBytes(res.result)); } fn testFail(comptime P: type, str: []const u8) void { if (P.parse(string.Input.init(str))) |res| { testing.expect(res.input.str.len != 0); } } test "parser.eatIf" { const P = eatIf(u8, comptime isPred('a')); testSuccess(P, "a", @as(u8, 'a')); testFail(P, "b"); } test "parser.end" { const P = end(); testSuccess(P, "", {}); testFail(P, "b"); } test "parser.sequence" { const A = eatIf(u8, comptime isPred('a')); const B = eatIf(u8, comptime isPred('b')); const C = eatIf(u8, comptime isPred('c')); const P = sequence([_]type{ A, B, C }); testSuccess(P, "abc", "abc"); testFail(P, "cba"); } test "parser.options" { const A = eatIf(u8, comptime isPred('a')); const B = eatIf(u8, comptime isPred('b')); const C = eatIf(u8, comptime isPred('c')); const P = options(&[_]type{ A, B, C }); testSuccess(P, "a", @as(u8, 'a')); testSuccess(P, "b", @as(u8, 'b')); testSuccess(P, "c", @as(u8, 'c')); testFail(P, "d"); } test "parser.options" { const A = eatIf(u8, comptime isPred('a')); const B = eatIf(u8, comptime isPred('b')); const C = eatIf(u8, comptime isPred('c')); const P = options(&[_]type{ A, B, C }); testSuccess(P, "a", @as(u8, 'a')); testSuccess(P, "b", @as(u8, 'b')); testSuccess(P, "c", @as(u8, 'c')); testFail(P, "d"); } test "parser.then" { const A = eatIf(u8, comptime isPred('a')); const B = eatIf(u8, comptime isPred('b')); const S = sequence(&[_]type{ A, B }); const P = options(&[_]type{ then(S, void, comptime toVoid(S.Result)), then(A, void, comptime toVoid(A.Result)), }); testSuccess(P, "a", {}); testSuccess(P, "ab", {}); testFail(P, "ba"); } test "parser.nothing" { testSuccess(nothing, "a", {}); testSuccess(nothing, "aaa", {}); testSuccess(nothing, "qqq", {}); testSuccess(nothing, "", {}); testSuccess(nothing, "2", {}); testSuccess(nothing, "10", {}); }
src/parser/common.zig
const std = @import("std"); const zgt = @import("zgt"); const bottom = @import("bottom"); pub usingnamespace zgt.cross_platform; pub fn encode(button: *zgt.Button_Impl) !void { // If we received the event, this means we're parented, so it's safe to assert const root = button.getRoot().?; // Get 'encode-text' and cast it to a TextField const input = root.get("encode-text").?.as(zgt.TextField_Impl); // Same cast, but with 'decode-text' const output = root.get("decode-text").?.as(zgt.TextField_Impl); const allocator = zgt.internal.scratch_allocator; const encoded = try bottom.encoder.encodeAlloc(input.getText(), allocator); // Free old text allocator.free(output.getText()); output.setText(encoded); } pub fn decode(button: *zgt.Button_Impl) !void { const root = button.getRoot().?; const input = root.get("decode-text").?.as(zgt.TextField_Impl); const output = root.get("encode-text").?.as(zgt.TextField_Impl); const allocator = zgt.internal.scratch_allocator; const decoded = try bottom.decoder.decodeAlloc(input.getText(), allocator); allocator.free(output.getText()); output.setText(decoded); } pub fn main() !void { try zgt.backend.init(); var window = try zgt.Window.init(); try window.set( zgt.Column(.{}, .{ zgt.Label(.{ .text = "Bottom encoder and decoder" }), zgt.Column(.{}, .{ zgt.Row(.{}, .{ zgt.Label(.{ .text = "Input text" }), zgt.TextField(.{ }) .setName("encode-text"), }), zgt.Row(.{}, .{ zgt.Label(.{ .text = "Output text" }), zgt.TextField(.{ }) .setName("decode-text"), }), }), zgt.Row(.{}, .{ zgt.Button(.{ .label = "Encode", .onclick = encode }), zgt.Button(.{ .label = "Decode", .onclick = decode }), }) }) ); window.resize(800, 600); window.show(); zgt.runEventLoop(); }
src/main.zig
const bs = @import("./bitstream.zig"); const bu = @import("./bits.zig"); // bits utilities const deflate = @import("./deflate.zig"); const hm = @import("./huffman.zig"); const lz = @import("./lz77.zig"); const std = @import("std"); const assert = std.debug.assert; const expect = std.testing.expect; const mem = std.mem; const hamlet = @embedFile("../fixtures/hamlet.txt"); // from test_utils.c fn next_test_rand(x: u32) u32 { // Pseudo-random number generator, using the linear congruential // method (see Knuth, TAOCP Vol. 2) with some random constants // from the interwebs. const a: u32 = 196314165; const c: u32 = 907633515; var mul: u32 = undefined; var total: u32 = undefined; _ = @mulWithOverflow(u32, a, x, &mul); _ = @addWithOverflow(u32, mul, c, &total); return total; } // Compress src, then decompress it and check that it matches. // Returns the size of the compressed data. fn deflate_roundtrip(src: [*]const u8, len: usize) !usize { var compressed: []u8 = undefined; var decompressed: []u8 = undefined; var compressed_sz: usize = 0; var decompressed_sz: usize = 0; var compressed_used: usize = 0; var i: usize = 0; var tmp: usize = 0; const compressed_buffer_len = len * 2 + 100; const allocator = std.testing.allocator; compressed = try allocator.alloc(u8, compressed_buffer_len); defer allocator.free(compressed); try expect(deflate.hwdeflate(src, len, compressed.ptr, compressed_buffer_len, &compressed_sz)); decompressed = try allocator.alloc(u8, len); defer allocator.free(decompressed); try expect(deflate.hwinflate( compressed.ptr, compressed_sz, &compressed_used, decompressed.ptr, len, &decompressed_sz, ) == deflate.inf_stat_t.HWINF_OK); try expect(compressed_used == compressed_sz); try expect(decompressed_sz == len); try expect(mem.eql(u8, src[0..len], decompressed[0..len])); if (len < 1000) { // For small inputs, check that a too small buffer fails. i = 0; while (i < compressed_used) : (i += 1) { try expect(!deflate.hwdeflate(src, len, compressed.ptr, i, &tmp)); } } else if (compressed_sz > 500) { // For larger inputs, try cutting off the first block. try expect(!deflate.hwdeflate(src, len, compressed.ptr, 500, &tmp)); } return compressed_sz; } const block_t: type = u2; const UNCOMP: block_t = 0x0; const STATIC: block_t = 0x1; const DYNAMIC: block_t = 0x2; fn check_deflate_string(str: []const u8, expected_type: block_t) !void { var comp: [1000]u8 = undefined; var comp_sz: usize = 0; try expect(deflate.hwdeflate(str.ptr, str.len, &comp, comp.len, &comp_sz)); try expect(((comp[0] & 7) >> 1) == expected_type); _ = try deflate_roundtrip(str.ptr, str.len); } test "deflate_basic" { var buf: [256]u8 = undefined; var i: usize = 0; // Empty input; a static block is shortest. try check_deflate_string("", STATIC); // One byte; a static block is shortest. try check_deflate_string("a", STATIC); // Repeated substring. try check_deflate_string("hellohello", STATIC); // Non-repeated long string with small alphabet. Dynamic. try check_deflate_string("abcdefghijklmnopqrstuvwxyz" ++ "zyxwvutsrqponmlkjihgfedcba", DYNAMIC); // No repetition, uniform distribution. Uncompressed. i = 0; while (i < 255) : (i += 1) { buf[i] = @intCast(u8, i + 1); } buf[255] = 0; try check_deflate_string(&buf, UNCOMP); } // PKZIP 2.50 pkzip -exx a.zip hamlet.txt 79754 bytes // info-zip 3.0 zip -9 a.zip hamlet.txt 80032 bytes // 7-Zip 16.02 7z a -mx=9 -mpass=15 a.zip hamlet.txt 76422 bytes test "deflate_hamlet" { var len: usize = 0; len = try deflate_roundtrip(hamlet, hamlet.len); // Update if we make compression better. try expect(len == 79708); } test "deflate_mixed_blocks" { var src: [*]u8 = undefined; var p: [*]u8 = undefined; var r: u32 = 0; var i: usize = 0; var j: usize = 0; const src_size: usize = 2 * 1024 * 1024; const SrcBuffer: type = [src_size]u8; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); src = try allocator.create(SrcBuffer); mem.set(u8, src[0..src_size], 0); p = src; r = 0; i = 0; while (i < 5) : (i += 1) { // Data suitable for compressed blocks. mem.copy(u8, src[0..src_size], hamlet[0..]); p += hamlet.len; // Random data, likely to go in an uncompressed block. j = 0; while (j < 128000) : (j += 1) { r = next_test_rand(r); p.* = @intCast(u8, r >> 24); p.* = std.math.maxInt(u8); _ = @addWithOverflow(u8, p[0], 2, &p[0]); } assert(@intCast(usize, @ptrToInt(p) - @ptrToInt(src)) <= src_size); } _ = try deflate_roundtrip(src, src_size); } test "deflate_random" { var src: [*]u8 = undefined; const src_size: usize = 3 * 1024 * 1024; var r: u32 = 0; var i: usize = 0; const SrcBuffer: type = [src_size]u8; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); src = try allocator.create(SrcBuffer); r = 0; i = 0; while (i < src_size) : (i += 1) { r = next_test_rand(r); src[i] = @intCast(u8, r >> 24); } _ = try deflate_roundtrip(src, src_size); } const MIN_LITLEN_LENS = 257; const MAX_LITLEN_LENS = 288; const MIN_DIST_LENS = 1; const MAX_DIST_LENS = 32; const MIN_CODELEN_LENS = 4; const MAX_CODELEN_LENS = 19; const CODELEN_MAX_LIT = 15; const CODELEN_COPY = 16; const CODELEN_COPY_MIN = 3; const CODELEN_COPY_MAX = 6; const CODELEN_ZEROS = 17; const CODELEN_ZEROS_MIN = 3; const CODELEN_ZEROS_MAX = 10; const CODELEN_ZEROS2 = 18; const CODELEN_ZEROS2_MIN = 11; const CODELEN_ZEROS2_MAX = 138; const block_header: type = struct { bfinal: u1, bh_type: u32, num_litlen_lens: usize, num_dist_lens: usize, code_lengths: [MIN_LITLEN_LENS + MAX_LITLEN_LENS]u32, }; const codelen_lengths_order: [MAX_CODELEN_LENS]u32 = [_]u32{ 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15, }; fn read_block_header(is: *bs.istream_t) !block_header { var h: block_header = undefined; var bits: u64 = 0; var num_codelen_lens: usize = 0; var used: usize = 0; var i: usize = 0; var n: usize = 0; var codelen_lengths: [MAX_CODELEN_LENS]u8 = undefined; var codelen_dec: hm.huffman_decoder_t = undefined; var sym: u16 = 0; bits = bs.istream_bits(is); h.bfinal = @truncate(u1, bits & @as(u64, 1)); bits >>= 1; h.bh_type = @intCast(u32, bu.lsb(bits, 2)); _ = bs.istream_advance(is, 3); if (h.bh_type != 2) { return h; } bits = bs.istream_bits(is); // Number of litlen codeword lengths (5 bits + 257). h.num_litlen_lens = @intCast(usize, bu.lsb(bits, 5) + MIN_LITLEN_LENS); bits >>= 5; assert(h.num_litlen_lens <= MAX_LITLEN_LENS); // Number of dist codeword lengths (5 bits + 1). h.num_dist_lens = @intCast(usize, bu.lsb(bits, 5) + MIN_DIST_LENS); bits >>= 5; assert(h.num_dist_lens <= MAX_DIST_LENS); // Number of code length lengths (4 bits + 4). num_codelen_lens = @intCast(usize, bu.lsb(bits, 4) + MIN_CODELEN_LENS); bits >>= 4; assert(num_codelen_lens <= MAX_CODELEN_LENS); _ = bs.istream_advance(is, 5 + 5 + 4); // Read the codelen codeword lengths (3 bits each) // and initialize the codelen decoder. i = 0; while (i < num_codelen_lens) : (i += 1) { bits = bs.istream_bits(is); codelen_lengths[codelen_lengths_order[i]] = @intCast(u8, bu.lsb(bits, 3)); _ = bs.istream_advance(is, 3); } while (i < MAX_CODELEN_LENS) : (i += 1) { codelen_lengths[codelen_lengths_order[i]] = 0; } _ = hm.huffman_decoder_init(&codelen_dec, &codelen_lengths, MAX_CODELEN_LENS); // Read the litlen and dist codeword lengths. i = 0; while (i < h.num_litlen_lens + h.num_dist_lens) { bits = bs.istream_bits(is); sym = try hm.huffman_decode(&codelen_dec, @truncate(u16, bits), &used); bits >>= @intCast(u6, used); _ = bs.istream_advance(is, used); if (sym >= 0 and sym <= CODELEN_MAX_LIT) { // A literal codeword length. h.code_lengths[i] = @intCast(u8, sym); i += 1; } else if (sym == CODELEN_COPY) { // Copy the previous codeword length 3--6 times. // 2 bits + 3 n = @intCast(usize, bu.lsb(bits, 2)) + CODELEN_COPY_MIN; _ = bs.istream_advance(is, 2); assert(n >= CODELEN_COPY_MIN and n <= CODELEN_COPY_MAX); while (n > 0) : (n -= 1) { h.code_lengths[i] = h.code_lengths[i - 1]; i += 1; } } else if (sym == CODELEN_ZEROS) { // 3--10 zeros; 3 bits + 3 n = @intCast(usize, bu.lsb(bits, 3) + CODELEN_ZEROS_MIN); _ = bs.istream_advance(is, 3); assert(n >= CODELEN_ZEROS_MIN and n <= CODELEN_ZEROS_MAX); while (n > 0) : (n -= 1) { h.code_lengths[i] = 0; i += 1; } } else if (sym == CODELEN_ZEROS2) { // 11--138 zeros; 7 bits + 138. n = @intCast(usize, bu.lsb(bits, 7) + CODELEN_ZEROS2_MIN); _ = bs.istream_advance(is, 7); assert(n >= CODELEN_ZEROS2_MIN and n <= CODELEN_ZEROS2_MAX); while (n > 0) : (n -= 1) { h.code_lengths[i] = 0; i += 1; } } } return h; } test "deflate_no_dist_codes" { // Compressing this will not use any dist codes, but check that we // still encode two non-zero dist codes to be compatible with old // zlib versions. const src = [32]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, }; var compressed: [1000]u8 = undefined; var compressed_sz: usize = 0; var is: bs.istream_t = undefined; var h: block_header = undefined; try expect(deflate.hwdeflate(&src, src.len, &compressed, compressed.len, &compressed_sz)); bs.istream_init(&is, &compressed, compressed_sz); h = try read_block_header(&is); try expect(h.num_dist_lens == 2); try expect(h.code_lengths[h.num_litlen_lens + 0] == 1); try expect(h.code_lengths[h.num_litlen_lens + 1] == 1); } test "inflate_invalid_block_header" { // bfinal: 0, btype: 11 const src = [_]u8{0x6}; // 0000 0110 var src_used: usize = 0; var dst_used: usize = 0; var dst: [10]u8 = undefined; try expect(deflate.hwinflate(&src, 1, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); } test "inflate_uncompressed" { var dst: [10]u8 = undefined; var src_used: usize = 0; var dst_used: usize = 0; const bad = [_]u8{ 0x01, // 0000 0001 bfinal: 1, btype: 00 0x05, 0x00, // len: 5 0x12, 0x34, // nlen: garbage }; const good = [_]u8{ 0x01, // 0000 0001 bfinal: 1, btype: 00 0x05, 0x00, // len: 5 0xfa, 0xff, // nlen 'H', 'e', 'l', 'l', 'o', }; // Too short for block header. try expect(deflate.hwinflate(&bad, 0, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); // Too short for len. try expect(deflate.hwinflate(&bad, 1, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); try expect(deflate.hwinflate(&bad, 2, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); // Too short for nlen. try expect(deflate.hwinflate(&bad, 3, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); try expect(deflate.hwinflate(&bad, 4, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); // nlen len mismatch. try expect(deflate.hwinflate(&bad, 5, &src_used, &dst, 10, &dst_used) == deflate.inf_stat_t.HWINF_ERR); // Not enough input. try expect(deflate.hwinflate(&good, 9, &src_used, &dst, 4, &dst_used) == deflate.inf_stat_t.HWINF_ERR); // Not enough room to output. try expect(deflate.hwinflate(&good, 10, &src_used, &dst, 4, &dst_used) == deflate.inf_stat_t.HWINF_FULL); // Success. try expect(deflate.hwinflate(&good, 10, &src_used, &dst, 5, &dst_used) == deflate.inf_stat_t.HWINF_OK); try expect(src_used == 10); try expect(dst_used == 5); try expect(mem.eql(u8, dst[0..5], "Hello")); } test "inflate_twocities_intro" { const deflated = [_]u8{ 0x74, 0xeb, 0xcd, 0x0d, 0x80, 0x20, 0x0c, 0x47, 0x71, 0xdc, 0x9d, 0xa2, 0x03, 0xb8, 0x88, 0x63, 0xf0, 0xf1, 0x47, 0x9a, 0x00, 0x35, 0xb4, 0x86, 0xf5, 0x0d, 0x27, 0x63, 0x82, 0xe7, 0xdf, 0x7b, 0x87, 0xd1, 0x70, 0x4a, 0x96, 0x41, 0x1e, 0x6a, 0x24, 0x89, 0x8c, 0x2b, 0x74, 0xdf, 0xf8, 0x95, 0x21, 0xfd, 0x8f, 0xdc, 0x89, 0x09, 0x83, 0x35, 0x4a, 0x5d, 0x49, 0x12, 0x29, 0xac, 0xb9, 0x41, 0xbf, 0x23, 0x2e, 0x09, 0x79, 0x06, 0x1e, 0x85, 0x91, 0xd6, 0xc6, 0x2d, 0x74, 0xc4, 0xfb, 0xa1, 0x7b, 0x0f, 0x52, 0x20, 0x84, 0x61, 0x28, 0x0c, 0x63, 0xdf, 0x53, 0xf4, 0x00, 0x1e, 0xc3, 0xa5, 0x97, 0x88, 0xf4, 0xd9, 0x04, 0xa5, 0x2d, 0x49, 0x54, 0xbc, 0xfd, 0x90, 0xa5, 0x0c, 0xae, 0xbf, 0x3f, 0x84, 0x77, 0x88, 0x3f, 0xaf, 0xc0, 0x40, 0xd6, 0x5b, 0x14, 0x8b, 0x54, 0xf6, 0x0f, 0x9b, 0x49, 0xf7, 0xbf, 0xbf, 0x36, 0x54, 0x5a, 0x0d, 0xe6, 0x3e, 0xf0, 0x9e, 0x29, 0xcd, 0xa1, 0x41, 0x05, 0x36, 0x48, 0x74, 0x4a, 0xe9, 0x46, 0x66, 0x2a, 0x19, 0x17, 0xf4, 0x71, 0x8e, 0xcb, 0x15, 0x5b, 0x57, 0xe4, 0xf3, 0xc7, 0xe7, 0x1e, 0x9d, 0x50, 0x08, 0xc3, 0x50, 0x18, 0xc6, 0x2a, 0x19, 0xa0, 0xdd, 0xc3, 0x35, 0x82, 0x3d, 0x6a, 0xb0, 0x34, 0x92, 0x16, 0x8b, 0xdb, 0x1b, 0xeb, 0x7d, 0xbc, 0xf8, 0x16, 0xf8, 0xc2, 0xe1, 0xaf, 0x81, 0x7e, 0x58, 0xf4, 0x9f, 0x74, 0xf8, 0xcd, 0x39, 0xd3, 0xaa, 0x0f, 0x26, 0x31, 0xcc, 0x8d, 0x9a, 0xd2, 0x04, 0x3e, 0x51, 0xbe, 0x7e, 0xbc, 0xc5, 0x27, 0x3d, 0xa5, 0xf3, 0x15, 0x63, 0x94, 0x42, 0x75, 0x53, 0x6b, 0x61, 0xc8, 0x01, 0x13, 0x4d, 0x23, 0xba, 0x2a, 0x2d, 0x6c, 0x94, 0x65, 0xc7, 0x4b, 0x86, 0x9b, 0x25, 0x3e, 0xba, 0x01, 0x10, 0x84, 0x81, 0x28, 0x80, 0x55, 0x1c, 0xc0, 0xa5, 0xaa, 0x36, 0xa6, 0x09, 0xa8, 0xa1, 0x85, 0xf9, 0x7d, 0x45, 0xbf, 0x80, 0xe4, 0xd1, 0xbb, 0xde, 0xb9, 0x5e, 0xf1, 0x23, 0x89, 0x4b, 0x00, 0xd5, 0x59, 0x84, 0x85, 0xe3, 0xd4, 0xdc, 0xb2, 0x66, 0xe9, 0xc1, 0x44, 0x0b, 0x1e, 0x84, 0xec, 0xe6, 0xa1, 0xc7, 0x42, 0x6a, 0x09, 0x6d, 0x9a, 0x5e, 0x70, 0xa2, 0x36, 0x94, 0x29, 0x2c, 0x85, 0x3f, 0x24, 0x39, 0xf3, 0xae, 0xc3, 0xca, 0xca, 0xaf, 0x2f, 0xce, 0x8e, 0x58, 0x91, 0x00, 0x25, 0xb5, 0xb3, 0xe9, 0xd4, 0xda, 0xef, 0xfa, 0x48, 0x7b, 0x3b, 0xe2, 0x63, 0x12, 0x00, 0x00, 0x20, 0x04, 0x80, 0x70, 0x36, 0x8c, 0xbd, 0x04, 0x71, 0xff, 0xf6, 0x0f, 0x66, 0x38, 0xcf, 0xa1, 0x39, 0x11, 0x0f, }; const expected = \\It was the best of times, \\it was the worst of times, \\it was the age of wisdom, \\it was the age of foolishness, \\it was the epoch of belief, \\it was the epoch of incredulity, \\it was the season of Light, \\it was the season of Darkness, \\it was the spring of hope, \\it was the winter of despair, \\ \\we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way---in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only. \\ ; var dst: [1000]u8 = undefined; var src_used: usize = 0; var dst_used: usize = 0; var i: usize = 0; try expect(deflate.hwinflate(&deflated, deflated.len, &src_used, &dst, dst.len, &dst_used) == deflate.inf_stat_t.HWINF_OK); try expect(dst_used == expected.len + 1); // expected.len doesn't include the last null byte try expect(src_used == deflated.len); try expect(mem.eql(u8, dst[0..expected.len], expected[0..])); // Truncated inputs should fail. i = 0; while (i < deflated.len) : (i += 1) { try expect(deflate.hwinflate(&deflated, i, &src_used, &dst, dst.len, &dst_used) == deflate.inf_stat_t.HWINF_ERR); } } // hamlet.txt compressed by zlib at level 0 to 9 const level_0: []const u8 = @embedFile("../fixtures/hamlet.level_0.zlib"); const level_1: []const u8 = @embedFile("../fixtures/hamlet.level_1.zlib"); const level_2: []const u8 = @embedFile("../fixtures/hamlet.level_2.zlib"); const level_3: []const u8 = @embedFile("../fixtures/hamlet.level_3.zlib"); const level_4: []const u8 = @embedFile("../fixtures/hamlet.level_4.zlib"); const level_5: []const u8 = @embedFile("../fixtures/hamlet.level_5.zlib"); const level_6: []const u8 = @embedFile("../fixtures/hamlet.level_6.zlib"); const level_7: []const u8 = @embedFile("../fixtures/hamlet.level_7.zlib"); const level_8: []const u8 = @embedFile("../fixtures/hamlet.level_8.zlib"); const level_9: []const u8 = @embedFile("../fixtures/hamlet.level_9.zlib"); const zlib_levels = [_][]const u8{ level_0, level_1, level_2, level_3, level_4, level_5, level_6, level_7, level_8, level_9, }; test "inflate_hamlet" { var decompressed: [hamlet.len]u8 = undefined; var compressed_sz: usize = 0; var src_used: usize = 0; var dst_used: usize = 0; for (zlib_levels) |compressed| { compressed_sz = compressed.len; try expect(deflate.hwinflate( compressed.ptr, compressed_sz, &src_used, &decompressed, decompressed.len, &dst_used, ) == deflate.inf_stat_t.HWINF_OK); try expect(src_used == compressed_sz); try expect(dst_used == hamlet.len); try expect(mem.eql(u8, decompressed[0..], hamlet[0..])); } } // Both hwzip and zlib will always emit at least two non-zero dist codeword // lengths, but that's not required by the spec. Make sure we can inflate // also when there are no dist codes. test "inflate_no_dist_codes" { const compressed = [_]u8{ 0x05, 0x00, 0x05, 0x0d, 0x00, 0x30, 0xe8, 0x38, 0x4e, 0xff, 0xb6, 0xdf, 0x03, 0x24, 0x16, 0x35, 0x8f, 0xac, 0x9e, 0xbd, 0xdb, 0xe9, 0xca, 0x70, 0x53, 0x61, 0x42, 0x78, 0x1f, }; const expected = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, }; var decompressed: [expected.len]u8 = undefined; var compressed_used: usize = 0; var decompressed_used: usize = 0; try expect(deflate.hwinflate( &compressed, compressed.len, &compressed_used, &decompressed, decompressed.len, &decompressed_used, ) == deflate.inf_stat_t.HWINF_OK); try expect(decompressed_used == expected.len); try expect(mem.eql(u8, decompressed[0..], expected[0..])); }
src/deflate_test.zig
const builtin = @import("builtin"); const std = @import("std"); const meta = std.meta; pub fn VecFns(comptime Self: type) type { comptime var N = @typeInfo(Self).Struct.fields.len; comptime var T = @typeInfo(Self).Struct.fields[0].field_type; comptime { if (@typeInfo(T) == .Array) { if (N > 1) { @compileError("Generic Vec can only have 1 field."); } N = @typeInfo(T).Array.len; T = @typeInfo(T).Array.child; } else { inline for (@typeInfo(Self).Struct.fields) |f| { if (T != f.field_type) { @compileError("All fields of a Vec must be of the same type"); } } } } return struct { pub usingnamespace VecFloat(Self, T); pub usingnamespace VecToArray(Self, N, T); pub const T = T; pub const N = N; pub fn map(self: Self, comptime f: anytype, args: anytype) Self { var r: getArrayType() = undefined; var v1 = self.toArray(); comptime var opts: std.builtin.CallOptions = .{}; comptime var i = 0; inline while (i < N) : (i += 1) { r[i] = @call(opts, f, .{v1[i]} ++ args); } return Self.fromArray(r); } pub fn apply(self: Self, comptime f: anytype) Self { return self.map(f, .{}); } pub fn map2(a: anytype, b: anytype, comptime f: anytype, args: anytype) Self { var r: getArrayType() = undefined; var v1 = a.toArray(); comptime var other_info = @typeInfo(@TypeOf(b)); comptime var isStruct = other_info == .Struct; comptime var opts: std.builtin.CallOptions = .{}; if (isStruct) { var v2 = b.toArray(); comptime var i = 0; inline while (i < N) : (i += 1) { r[i] = @call(opts, f, .{ v1[i], v2[i] } ++ args); } } else { comptime var i = 0; inline while (i < N) : (i += 1) { r[i] = @call(opts, f, .{ v1[i], b } ++ args); } } return Self.fromArray(r); } pub fn reduce(self: Self, comptime f: anytype, args: anytype) T { comptime var opts: std.builtin.CallOptions = .{}; var v1 = self.toArray(); var r: T = v1[0]; comptime var i = 1; inline while (i < N) : (i += 1) { r = @call(opts, f, .{ r, v1[i] } ++ args); } return r; } pub fn add(self: Self, other: anytype) Self { return map2(self, other, _add, .{}); } pub fn mul(self: Self, other: anytype) Self { return map2(self, other, _mul, .{}); } pub fn sub(self: Self, other: anytype) Self { return map2(self, other, _sub, .{}); } /// Subtraction clamping at zero to prevent underflow of unsigned types pub fn sub0(self: Self, other: anytype) Self { return map2(self, other, _sub0, .{}); } pub fn lerp(self: Self, other: anytype, a: T) Self { return map2(self, other, _lerp, .{a}); } pub fn sum(self: Self) T { return self.reduce(_add, .{}); } pub fn prod(self: Self) T { return self.reduce(_mul, .{}); } pub fn divExact(self: Self, other: anytype) Self { return map2(self, other, _divExact, .{}); } pub fn divFloor(self: Self, other: anytype) Self { return map2(self, other, _divFloor, .{}); } pub fn divTrunc(self: Self, other: anytype) Self { return map2(self, other, _divTrunc, .{}); } pub fn div(self: Self, other: anytype) Self { return map2(self, other, _div, .{}); } pub fn max(self: Self, other: anytype) Self { return map2(self, other, _max, .{}); } pub fn min(self: Self, other: anytype) Self { return map2(self, other, _min, .{}); } pub fn clamp(self: Self, minimum: anytype, maximum: anytype) Self { return map2(self, minimum, _max, .{}).map2(maximum, _min, .{}); } pub fn eq(self: Self, other: anytype) bool { return GenericVec(N, bool).map2(self, other, _eq, .{}).reduce(_and, .{}); } pub fn gt(self: Self, other: anytype) bool { return GenericVec(N, bool).map2(self, other, _gt, .{}).reduce(_and, .{}); } pub fn gte(self: Self, other: anytype) bool { return GenericVec(N, bool).map2(self, other, _gte, .{}).reduce(_and, .{}); } pub fn lt(self: Self, other: anytype) bool { return GenericVec(N, bool).map2(self, other, _lt, .{}).reduce(_and, .{}); } pub fn lte(self: Self, other: anytype) bool { return GenericVec(N, bool).map2(self, other, _lte, .{}).reduce(_and, .{}); } pub fn dot(self: Self, other: anytype) T { return self.mul(other).sum(); } pub fn length(self: Self) T { return std.math.sqrt(self.dot(self)); } pub fn into(self: Self, comptime VType: type) VType { if (comptime N != VType.N) { @compileError("Can't convert into type. Both vectors must have the same dimension."); } if (comptime T == VType.T and @sizeOf(Self) == @sizeOf(VType)) { return @bitCast(VType, self); } var v = self.toArray(); var r: VType.getArrayType() = undefined; comptime var i = 0; inline while (i < N) : (i += 1) { if (comptime T != VType.T) { switch (@typeInfo(T)) { .Float => { switch (@typeInfo(VType.T)) { .Float => { r[i] = @floatCast(VType.T, v[i]); }, .Int => { r[i] = @floatToInt(VType.T, v[i]); }, else => unreachable, } }, .Int => { switch (@typeInfo(VType.T)) { .Float => { r[i] = @intToFloat(VType.T, v[i]); }, .Int => { r[i] = @intCast(VType.T, v[i]); }, else => unreachable, } }, else => unreachable, } } else { r[i] = v[i]; } } return VType.fromArray(r); } pub fn join(self: Self, other: Self) [2 * N]T { var array: [2 * N]T = undefined; var v1 = self.toArray(); var v2 = other.toArray(); for (v1) |v, i| { array[i] = v; } for (v2) |v, i| { array[N + i] = v; } return array; } pub fn zero() Self { return std.mem.zeroes(Self); } pub fn all(n: anytype) Self { var r: getArrayType() = undefined; inline for (r) |*e| { e.* = n; } return Self.fromArray(r); } pub fn getArrayType() type { return [N]T; } /// Return a GenericVec containing the values indicated by `fields`. /// All selected fields must have single-character names (e.g. `x`) pub fn swizzle(self: Self, comptime fields: []const u8) GenericVec(fields.len, T) { var ret: GenericVec(fields.len, T) = undefined; inline for (fields) |member, i| { ret.data[i] = @field(self, &[_]u8{member}); } return ret; } }; } pub fn GenericVec(comptime N: comptime_int, comptime T: type) type { return struct { usingnamespace VecFns(@This()); data: [N]T, }; } fn VecToArray(comptime Self: type, comptime N: comptime_int, comptime T: type) type { if (@typeInfo(Self).Struct.fields[0].field_type == [N]T) { return struct { pub fn toArray(self: Self) [N]T { return @field(self, @typeInfo(Self).Struct.fields[0].name); } pub fn fromArray(array: [N]T) Self { var r: Self = undefined; @field(r, @typeInfo(Self).Struct.fields[0].name) = array; return r; } }; } else { return struct { pub fn toArray(self: Self) [N]T { if (@sizeOf([N]T) == @sizeOf(Self)) { return @bitCast([N]T, self); } else { var r: [N]T = undefined; comptime var i = 0; inline while (i < N) : (i += 1) { r[i] = @field(self, @typeInfo(Self).Struct.fields[i].name); } return r; } } pub fn fromArray(array: [N]T) Self { var r: Self = undefined; inline for (meta.fields(Self)) |f, i| { const name = f.name; @field(r, name) = array[i]; } return r; } }; } } fn VecFloat(comptime Self: type, comptime T: type) type { if (comptime isFloat(T)) { return struct { pub fn len(self: Self) T { return std.math.sqrt(self.mul(self).sum()); } pub fn distance(self: Self, other: anytype) T { var s = self.sub(other); return std.math.sqrt(s.mul(s).sum()); } pub fn norm(self: Self) Self { var l = self.len(); if (l > 0 or l < 0) { return self.div(l); } else { return Self.zero(); } } }; } else { return struct {}; } } fn isFloat(comptime t: type) bool { return switch (@typeInfo(t)) { .Float, .ComptimeFloat => true, else => false, }; } inline fn _add(a: anytype, b: anytype) @TypeOf(a) { return a + b; } inline fn _mul(a: anytype, b: anytype) @TypeOf(a) { return a * b; } inline fn _sub(a: anytype, b: anytype) @TypeOf(a) { return a - b; } inline fn _sub0(a: anytype, b: anytype) @TypeOf(a) { return if (a > b) a - b else 0; } inline fn _lerp(a: anytype, b: anytype, c: anytype) @TypeOf(a) { return a * c + b * (1 - c); } inline fn _divExact(a: anytype, b: anytype) @TypeOf(a) { return @divExact(a, b); } inline fn _divFloor(a: anytype, b: anytype) @TypeOf(a) { return @divFloor(a, b); } inline fn _divTrunc(a: anytype, b: anytype) @TypeOf(a) { return @divTrunc(a, b); } inline fn _div(a: anytype, b: anytype) @TypeOf(a) { return a / b; } inline fn _max(a: anytype, b: anytype) @TypeOf(a) { return if (a > b) a else b; } inline fn _min(a: anytype, b: anytype) @TypeOf(a) { return if (a < b) a else b; } inline fn _eq(a: anytype, b: anytype) bool { return a == b; } inline fn _and(a: bool, b: bool) bool { return a and b; } inline fn _gt(a: anytype, b: anytype) bool { return a > b; } inline fn _gte(a: anytype, b: anytype) bool { return a >= b; } inline fn _lt(a: anytype, b: anytype) bool { return a < b; } inline fn _lte(a: anytype, b: anytype) bool { return a <= b; } test "VecFns.eq" { const V = struct { pub usingnamespace VecFns(@This()); x: f32 = 0.5, y: f32 = 0.5, }; var v: V = .{}; try std.testing.expect(!v.eq(0)); try std.testing.expect(v.eq(0.5)); } test "vec operations" { const MyVec = struct { pub usingnamespace VecFns(@This()); x: i32 = 0, y: i32 = 0, }; const MyVec2 = packed struct { pub usingnamespace VecFns(@This()); x: f32 = 0, y: f32 = 0, }; var a: MyVec = .{ .x = 0, .y = 0 }; var a2 = a.add(2).mul(10).divExact(10).sub(3); try std.testing.expect(a2.x == -1 and a2.y == -1); var b: MyVec2 = .{ .x = 0, .y = 0 }; var b2 = b.add(2).mul(10).div(10).sub(3); try std.testing.expect(b2.x == -1 and b2.y == -1); var a3 = a2.add(a2).mul(a2).divExact(a2).sub(a2).into(MyVec2); var b3 = b2.add(b2).mul(b2).div(b2).sub(b2); try std.testing.expect(a3.eq(b3)); } test "division with signed integers" { // Note that div won't compile with signed integers and divExact will // produce a runtime panic if there is a remainder. So when using // signed integers you should probably want to use either divFloor or // divTrunc. If all values are positive these two will behave the same. // However when negative values are in play they will produce different // results: const MyVec = struct { pub usingnamespace VecFns(@This()); x: i32 = 0, y: i32 = 0, }; // What happens when we divide -7 by 2? const a = MyVec{ .x = -7, .y = 1}; const b = MyVec{ .x = 2, .y = 1 }; // divFloor rounds towards negative infinity const floor = a.divFloor(b); try std.testing.expect(floor.x == -4 and floor.y == 1); // while divTrunc behaves the way you probably expect integer division to work const trunc = a.divTrunc(b); try std.testing.expect(trunc.x == -3 and trunc.y == 1); } test "swizzle" { const MyVec = struct { pub usingnamespace VecFns(@This()); x: i32 = 0, y: i32 = 0, }; var a: MyVec = .{ .x=7, .y=12 }; var b = a.swizzle("yxxyx"); try std.testing.expectEqual(a.y, b.data[0]); try std.testing.expectEqual(a.x, b.data[1]); try std.testing.expectEqual(a.x, b.data[2]); try std.testing.expectEqual(a.y, b.data[3]); try std.testing.expectEqual(a.x, b.data[4]); } test "ordering" { const MyVec = struct { pub usingnamespace VecFns(@This()); x: i32 = 0, y: i32 = 0, }; var a: MyVec = .{ .x = 0, .y = 0 }; try std.testing.expect(a.gt(MyVec{ .x = -1, .y = -2 })); try std.testing.expect(a.gte(MyVec{ .x = 0, .y = 0 })); // equal case try std.testing.expect(a.gte(MyVec{ .x = -1, .y = 0 })); try std.testing.expect(a.lt(MyVec{ .x = 7, .y = 1 })); try std.testing.expect(a.lte(MyVec{ .x = 0, .y = 0 })); // equal case try std.testing.expect(a.lte(MyVec{ .x = 1, .y = 0 })); } test "prod" { const MyVec = struct { pub usingnamespace VecFns(@This()); x: i32 = 0, y: i32 = 0, }; const a = MyVec{ .x = 10, .y = 7 }; try std.testing.expectEqual(@as(i32, 70), a.prod()); } test "clamp" { const MyVec = struct { pub usingnamespace VecFns(@This()); x: i32 = 0, y: i32 = 0, }; var a = MyVec{ .x = 10, .y = -10 }; const b = MyVec{ .x = 0, .y = 0 }; const c = MyVec{ .x = 5, .y = 5 }; try std.testing.expectEqual(MyVec{ .x = 5, .y = 0}, a.clamp(b, c)); a = MyVec{ .x = 3, .y = 3 }; try std.testing.expectEqual(a, a.clamp(b, c)); } test "sub0" { const MyVec = struct { pub usingnamespace VecFns(@This()); x: u32 = 0, y: u32 = 0, }; const a = MyVec{ .x = 10, .y = 10 }; const b = MyVec{ .x = 20, .y = 2 }; try std.testing.expectEqual(MyVec{ .x = 0, .y = 8 }, a.sub0(b)); const c = MyVec{ .x = 10, .y = 2 }; try std.testing.expectEqual(MyVec{ .x = 0, .y = 8 }, a.sub0(c)); }
vec_fns.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const mem = std.mem; const process = std.process; const Archive = @import("archive/Archive.zig"); const overview = \\Zig Archiver \\ \\Usage: zar [options] [-]<operation>[modifiers] [relpos] [count] <archive> [files] \\ \\Options: \\ TODO! \\ \\Operations: \\ r - replace/insert [files] in <archive> (NOTE: c modifier allows for archive creation) \\ d - delete [files] from <archive> \\ m - move [files] in <archive> \\ p - print [files] in <archive> \\ q - quick append [files] to <archive> \\ s - act as ranlib \\ t - display contents of <archive> \\ x - extract [files] from <archive> \\ \\Modifiers: \\ TODO! \\ ; fn printError(stderr: anytype, comptime errorString: []const u8) !void { try stderr.print("error: " ++ errorString ++ "\n", .{}); try stderr.print(overview, .{}); } fn checkArgsBounds(stderr: anytype, args: anytype, index: u32) !bool { if (index >= args.len) { try printError(stderr, "an archive must be specified"); return false; } return true; } fn openOrCreateFile(archive_path: []u8) !fs.File { const open_file_handle = fs.cwd().openFile(archive_path, .{ .write = true }) catch |err| switch (err) { error.FileNotFound => { const create_file_handle = try fs.cwd().createFile(archive_path, .{ .read = true }); return create_file_handle; }, else => return err, }; return open_file_handle; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); var allocator = &arena.allocator; const args = try process.argsAlloc(allocator); // skip the executable name const stdout = io.getStdOut().writer(); const stderr = io.getStdErr().writer(); var arg_index: u32 = 1; if (!try checkArgsBounds(stderr, args, arg_index)) { return; } // Process Options First var keep_processing_current_option = true; while (keep_processing_current_option) { keep_processing_current_option = false; var current_arg = args[arg_index]; { const format_string = "--format="; if (mem.startsWith(u8, current_arg, format_string)) { // TODO: Handle format option! keep_processing_current_option = true; arg_index = arg_index + 1; continue; } } } if (!try checkArgsBounds(stderr, args, arg_index)) { return; } // Process Operation! const operation = operation: { // the operation may start with a hyphen - so slice it! var arg_slice = args[arg_index][0..args[arg_index].len]; if (arg_slice[0] == '-') { arg_slice = arg_slice[1..arg_slice.len]; } switch (arg_slice[0]) { 'r' => break :operation Archive.Operation.insert, 'd' => break :operation Archive.Operation.delete, 'm' => break :operation Archive.Operation.move, 'p' => break :operation Archive.Operation.print, 'w' => break :operation Archive.Operation.quick_append, 's' => break :operation Archive.Operation.ranlib, 't' => break :operation Archive.Operation.display_contents, 'x' => break :operation Archive.Operation.extract, else => { try printError(stderr, "a valid operation must be provided"); return; }, } // TODO: Process modifiers! }; arg_index = arg_index + 1; if (!try checkArgsBounds(stderr, args, arg_index)) { return; } // TODO: Process [relpos] // TODO: Process [count] const archive_path = args[arg_index]; arg_index = arg_index + 1; const files = file_result: { if (args.len > arg_index) { break :file_result args[arg_index..args.len]; } const empty = [_][:0]u8{}; break :file_result &empty; }; switch (operation) { .insert => { const file = try openOrCreateFile(archive_path); defer file.close(); var archive = Archive.create(file, archive_path); if (archive.parse(allocator, stderr)) { try archive.insertFiles(allocator, files); try archive.finalize(allocator); } else |err| switch (err) { // These are errors we know how to handle error.NotArchive => { // archive.parse prints appropriate errors for these messages return; }, else => return err, } }, .delete => { const file = try openOrCreateFile(archive_path); defer file.close(); var archive = Archive.create(file, archive_path); if (archive.parse(allocator, stderr)) { try archive.deleteFiles(files); try archive.finalize(allocator); } else |err| return err; }, .display_contents => { const file = try fs.cwd().openFile(archive_path, .{}); defer file.close(); var archive = Archive.create(file, archive_path); if (archive.parse(allocator, stderr)) { for (archive.files.items) |parsed_file| { try stdout.print("{s}\n", .{parsed_file.name}); } } else |err| switch (err) { // These are errors we know how to handle error.NotArchive => { // archive.parse prints appropriate errors for these messages return; }, else => return err, } }, .print => { const file = try fs.cwd().openFile(archive_path, .{}); defer file.close(); var archive = Archive.create(file, archive_path); if (archive.parse(allocator, stderr)) { for (archive.files.items) |parsed_file| { try parsed_file.contents.write(stdout, stderr); } } else |err| switch (err) { // These are errors we know how to handle error.NotArchive => { // archive.parse prints appropriate errors for these messages return; }, else => return err, } }, else => { std.debug.warn("Operation {} still needs to be implemented!\n", .{operation}); return error.TODO; }, } }
src/main.zig
const std = @import("std"); const assert = std.debug.assert; const koino = @import("koino"); const MenuItem = struct { input_file_name: []const u8, output_file_name: []const u8, header: []const u8, }; const menu_items = [_]MenuItem{ MenuItem{ .input_file_name = "documentation/README.md", .output_file_name = "website/docs/language.htm", .header = "Language Reference", }, MenuItem{ .input_file_name = "documentation/standard-library.md", .output_file_name = "website/docs/standard-library.htm", .header = "Standard Library", }, MenuItem{ .input_file_name = "documentation/runtime-library.md", .output_file_name = "website/docs/runtime-library.htm", .header = "Runtime Library", }, MenuItem{ .input_file_name = "documentation/ir.md", .output_file_name = "website/docs/intermediate-language.htm", .header = "IR", }, MenuItem{ .input_file_name = "documentation/modules.md", .output_file_name = "website/docs/module-binary.htm", .header = "Module Format", }, }; pub fn main() !u8 { @setEvalBranchQuota(1500); var stderr = std.io.getStdErr().writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var args = std.process.args(); const exe_name = try (args.next(&gpa.allocator) orelse return 1); gpa.allocator.free(exe_name); const version_name = if (args.next(&gpa.allocator)) |v| try v else null; defer if (version_name) |name| { gpa.allocator.free(name); }; for (menu_items) |current_file, current_index| { const options = koino.Options{ .extensions = .{ .table = true, .autolink = true, .strikethrough = true, }, }; var infile = try std.fs.cwd().openFile(current_file.input_file_name, .{}); defer infile.close(); var markdown = try infile.reader().readAllAlloc(&gpa.allocator, 1024 * 1024 * 1024); defer gpa.allocator.free(markdown); var output = try markdownToHtml(&gpa.allocator, options, markdown); defer gpa.allocator.free(output); var outfile = try std.fs.cwd().createFile(current_file.output_file_name, .{}); defer outfile.close(); try outfile.writeAll( \\<!DOCTYPE html> \\<html lang="en"> \\ \\<head> \\ <meta charset="utf-8"> \\ <meta name="viewport" content="width=device-width, initial-scale=1"> \\ <title>LoLa Documentation</title> \\ <link rel="icon" \\ href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAgklEQVR4AWMYWuD7EllJIM4G4g4g5oIJ/odhOJ8wToOxSTXgNxDHoeiBMfA4+wGShjyYOCkG/IGqWQziEzYAoUAeiF9D5U+DxEg14DRU7jWIT5IBIOdCxf+A+CQZAAoopEB7QJwBCBwHiip8UYmRdrAlDpIMgApwQZNnNii5Dq0MBgCxxycBnwEd+wAAAABJRU5ErkJggg=="> \\ <link rel="stylesheet" href="../documentation.css" /> \\</head> \\ \\<body class="canvas"> \\ <div class="flex-main"> \\ <div class="flex-filler"></div> \\ <div class="flex-left sidebar"> \\ <nav> \\ <div class="logo"> \\ <img src="../img/logo.png" /> \\ </div> \\ <div id="sectPkgs" class=""> \\ <h2><span>Documents</span></h2> \\ <ul id="listPkgs" class="packages"> ); for (menu_items) |menu, i| { var is_current = (current_index == i); var current_class = if (is_current) @as([]const u8, "class=\"active\"") else ""; try outfile.writer().print( \\<li><a href="{}" {}>{}</a></li> \\ , .{ std.fs.path.basename(menu.output_file_name), current_class, menu.header, }); } var version_name_str = @as(?[]const u8, version_name) orelse @as([]const u8, "development"); try outfile.writer().print( \\ </ul> \\ </div> \\ <div id="sectInfo" class=""> \\ <h2><span>LoLa Version</span></h2> \\ <p class="str" id="tdZigVer">{}</p> \\ </div> \\ </nav> \\ </div> \\ <div class="flex-right"> \\ <div class="wrap"> \\ <section class="docs"> , .{ version_name_str, }); try outfile.writer().writeAll(output); try outfile.writeAll( \\ </section> \\ </div> \\ <div class="flex-filler"></div> \\ </div> \\ </div> \\</body> \\ \\</html> \\ ); } return 0; } fn markdownToHtmlInternal(resultAllocator: *std.mem.Allocator, internalAllocator: *std.mem.Allocator, options: koino.Options, markdown: []const u8) ![]u8 { var p = try koino.parser.Parser.init(internalAllocator, options); try p.feed(markdown); var doc = try p.finish(); p.deinit(); defer doc.deinit(); return try koino.html.print(resultAllocator, p.options, doc); } pub fn markdownToHtml(allocator: *std.mem.Allocator, options: koino.Options, markdown: []const u8) ![]u8 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); return markdownToHtmlInternal(allocator, &arena.allocator, options, markdown); }
src/tools/render-md-page.zig