code
stringlengths
38
801k
repo_path
stringlengths
6
263
const std = @import("std"); const os = std.os; const mem = std.mem; const net = std.net; const testing = std.testing; const assert = std.debug.assert; // For testing slow and fast clients. const delay_time = std.time.ns_per_ms * 100; const clients_count = 40; // 1. Connect // 2. Write // 3. Disconnect const how_many_events_expected = clients_count * 3; fn startClient(address: *net.Address) !void { const message = try std.fmt.allocPrint(testing.allocator, "hello from client!", .{}); defer testing.allocator.free(message); var buf: [256]u8 = undefined; std.time.sleep(delay_time); const client_socket = try os.socket( os.AF_UNIX, os.SOCK_SEQPACKET | os.SOCK_CLOEXEC, os.PF_UNIX, ); defer os.closeSocket(client_socket); try os.connect( client_socket, @ptrCast(*os.sockaddr, &address.un), @sizeOf(@TypeOf(address.un)), ); std.time.sleep(delay_time); const bytes_sent = try os.send(client_socket, message, os.MSG_EOR); std.debug.print("client bytes sent: {d}\n", .{bytes_sent}); assert(message.len == bytes_sent); const bytes_read = try os.recv(client_socket, &buf, 0); std.debug.print( "received on client: {s}, {d} bytes\n", .{ buf[0..bytes_read], bytes_read }, ); } test "poll socket for listening and for reading" { const socket_path = try std.fmt.allocPrint(testing.allocator, "/tmp/poll.socket", .{}); defer testing.allocator.free(socket_path); std.fs.deleteFileAbsolute(socket_path) catch |err| switch (err) { error.FileNotFound => {}, else => return err, }; const address = try testing.allocator.create(net.Address); defer testing.allocator.destroy(address); address.* = try net.Address.initUnix(socket_path); const pid = try os.fork(); if (pid == 0) { // Client var threads: [clients_count]std.Thread = undefined; for (threads) |*thr| { thr.* = try std.Thread.spawn(.{}, startClient, .{address}); } for (threads) |thr| { std.Thread.join(thr); } } else { // Server var buf: [256]u8 = undefined; const message = try std.fmt.allocPrint(testing.allocator, "hello from server!", .{}); defer testing.allocator.free(message); const socket = try os.socket( os.AF_UNIX, os.SOCK_SEQPACKET | os.SOCK_CLOEXEC, os.PF_UNIX, ); try os.bind(socket, @ptrCast(*os.sockaddr, &address.un), @sizeOf(@TypeOf(address.un))); try os.listen(socket, 10); const FdType = enum { listen, read_write }; var fds = std.ArrayList(os.pollfd).init(testing.allocator); defer { for (fds.items) |fd| os.closeSocket(fd.fd); fds.deinit(); } var fd_types = std.ArrayList(FdType).init(testing.allocator); defer fd_types.deinit(); try fds.append(os.pollfd{ .fd = socket, .events = os.POLLIN, .revents = 0, }); try fd_types.append(.listen); std.debug.print("\n", .{}); var loop_counter: usize = 0; var event_counter: u8 = 0; while (true) : (loop_counter += 1) { std.debug.print("loop counter: {d}\n", .{loop_counter}); const polled_events_count = try os.poll(fds.items, -1); if (polled_events_count > 0) { var current_event: u8 = 0; var processed_events_count: u8 = 0; while (current_event < fds.items.len) : (current_event += 1) { if (fds.items[current_event].revents > 0) { processed_events_count += 1; event_counter += 1; if (fds.items[current_event].revents & os.POLLHUP != 0) { _ = fds.swapRemove(current_event); _ = fd_types.swapRemove(current_event); continue; } fds.items[current_event].revents = 0; switch (fd_types.items[current_event]) { .listen => { const accepted_socket = try os.accept( socket, null, null, os.SOCK_CLOEXEC, ); try fds.append( .{ .fd = accepted_socket, .events = os.POLLIN, .revents = 0 }, ); try fd_types.append(.read_write); }, .read_write => { const bytes_read = try os.recv(fds.items[current_event].fd, &buf, 0); std.debug.print( "received on server: {s}, {d} bytes\n", .{ buf[0..bytes_read], bytes_read }, ); const bytes_sent = try os.send( fds.items[current_event].fd, message, os.MSG_EOR, ); std.debug.print("server bytes sent: {d}\n", .{bytes_sent}); assert(message.len == bytes_sent); }, } } if (processed_events_count == polled_events_count) break; } } if (event_counter == how_many_events_expected) break; } std.debug.print("\n", .{}); std.debug.print("total events: {d}\n", .{event_counter}); } }
poc/poll_sockets.zig
const std = @import("std"); const stdx = @import("stdx"); const build_options = @import("build_options"); const Backend = build_options.GraphicsBackend; const platform = @import("platform"); const vk = @import("vk"); const graphics = @import("graphics.zig"); const gpu = graphics.gpu; const gvk = graphics.vk; /// A Renderer abstracts how and where a frame is drawn to and provides: /// 1. An interface to begin/end a frame. /// 2. A graphics context to paint things to a frame. /// 3. TODO: If the window resizes, it is responsible for adjusting the framebuffers and graphics context. /// 4. TODO: Measuring fps should probably be here. pub const Renderer = struct { swapchain: graphics.SwapChain, gctx: graphics.Graphics, win: *platform.Window, inner: switch (Backend) { .Vulkan => struct { ctx: gvk.VkContext, }, .OpenGL => void, else => void, }, const Self = @This(); /// Creates a renderer that targets a window. pub fn init(self: *Self, alloc: std.mem.Allocator, win: *platform.Window) void { self.win = win; switch (Backend) { .Vulkan => { self.swapchain.initVK(alloc, win); const vk_ctx = gvk.VkContext.init(alloc, win, self.swapchain); self.inner.ctx = vk_ctx; self.gctx.initVK(alloc, win.impl.dpr, vk_ctx); }, .OpenGL => { self.swapchain.init(alloc, win); self.gctx.init(alloc, win.impl.dpr); }, else => {}, } } pub fn deinit(self: *Self, alloc: std.mem.Allocator) void { // Deinit swapchain first to make sure there aren't any pending resources in use. self.swapchain.deinit(alloc); self.gctx.deinit(); if (Backend == .Vulkan) { self.inner.ctx.deinit(alloc); } } pub fn getGraphics(self: *Self) *graphics.Graphics { return &self.gctx; } /// Start of frame with a camera view. pub inline fn beginFrame(self: *Self, cam: graphics.Camera) void { self.swapchain.beginFrame(); switch (Backend) { .Vulkan => { const cur_image_idx = self.swapchain.impl.cur_image_idx; const cur_frame_idx = self.swapchain.impl.cur_frame_idx; gpu.Graphics.beginFrameVK(&self.gctx.impl, self.win.impl.buf_width, self.win.impl.buf_height, cur_image_idx, cur_frame_idx); }, .OpenGL => { // In OpenGL, glClear can block if there there are too many commands in the queue. gpu.Graphics.beginFrame(&self.gctx.impl, self.win.impl.buf_width, self.win.impl.buf_height, self.win.impl.fbo_id); }, else => stdx.unsupported(), } gpu.Graphics.setCamera(&self.gctx.impl, cam); } /// End of frame, flush to framebuffer. pub inline fn endFrame(self: *Self) void { switch (Backend) { .Vulkan => { gpu.Graphics.endFrameVK(&self.gctx.impl); const cur_image_idx = self.swapchain.impl.cur_image_idx; const cur_frame_idx = self.swapchain.impl.cur_frame_idx; // Submit command. const wait_stage_flag = @intCast(u32, vk.VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT); const submit_info = vk.VkSubmitInfo{ .sType = vk.VK_STRUCTURE_TYPE_SUBMIT_INFO, .waitSemaphoreCount = 1, .pWaitSemaphores = &self.swapchain.impl.image_available_semas[cur_frame_idx], .pWaitDstStageMask = &wait_stage_flag, .commandBufferCount = 1, .pCommandBuffers = &self.inner.ctx.cmd_bufs[cur_image_idx], .signalSemaphoreCount = 1, .pSignalSemaphores = &self.swapchain.impl.render_finished_semas[cur_frame_idx], .pNext = null, }; const res = vk.queueSubmit(self.inner.ctx.graphics_queue, 1, &submit_info, self.swapchain.impl.inflight_fences[cur_frame_idx]); vk.assertSuccess(res); }, .OpenGL => { gpu.Graphics.endFrame(&self.gctx.impl, self.win.impl.buf_width, self.win.impl.buf_height, self.win.impl.fbo_id); }, else => stdx.unsupported(), } self.swapchain.endFrame(); } };
graphics/src/renderer.zig
const std = @import("std"); extern fn strncpy(dest: [*:0]u8, src: [*:0]const u8, n: usize) callconv(.C) [*:0]u8; extern fn memset(dest: ?[*]u8, c: u8, n: usize) callconv(.C) ?[*]u8; extern fn memcpy(noalias dest: ?[*]u8, noalias src: ?[*]const u8, n: usize) callconv(.C) ?[*]u8; extern fn memmove(dest: ?[*]u8, src: ?[*]const u8, n: usize) callconv(.C) ?[*]u8; // Avoid dragging in the runtime safety mechanisms into this .o file. pub fn panic(msg: []const u8, error_return_trace: ?*std.builtin.StackTrace) noreturn { _ = msg; _ = error_return_trace; @setCold(true); std.os.abort(); } export fn __stack_chk_fail() callconv(.C) noreturn { @panic("stack smashing detected"); } export fn __chk_fail() callconv(.C) noreturn { @panic("buffer overflow detected"); } // Emitted when targeting some architectures (eg. i386) // XXX: This symbol should be hidden export fn __stack_chk_fail_local() callconv(.C) noreturn { __stack_chk_fail(); } // XXX: Initialize the canary with random data export var __stack_chk_guard: usize = blk: { var buf = [1]u8{0} ** @sizeOf(usize); buf[@sizeOf(usize) - 1] = 255; buf[@sizeOf(usize) - 2] = '\n'; break :blk @bitCast(usize, buf); }; export fn __strcpy_chk(dest: [*:0]u8, src: [*:0]const u8, dest_n: usize) callconv(.C) [*:0]u8 { @setRuntimeSafety(false); var i: usize = 0; while (i < dest_n and src[i] != 0) : (i += 1) { dest[i] = src[i]; } if (i == dest_n) __chk_fail(); dest[i] = 0; return dest; } export fn __strncpy_chk(dest: [*:0]u8, src: [*:0]const u8, n: usize, dest_n: usize) callconv(.C) [*:0]u8 { if (dest_n < n) __chk_fail(); return strncpy(dest, src, n); } export fn __strcat_chk(dest: [*:0]u8, src: [*:0]const u8, dest_n: usize) callconv(.C) [*:0]u8 { @setRuntimeSafety(false); var avail = dest_n; var dest_end: usize = 0; while (avail > 0 and dest[dest_end] != 0) : (dest_end += 1) { avail -= 1; } if (avail < 1) __chk_fail(); var i: usize = 0; while (avail > 0 and src[i] != 0) : (i += 1) { dest[dest_end + i] = src[i]; avail -= 1; } if (avail < 1) __chk_fail(); dest[dest_end + i] = 0; return dest; } export fn __strncat_chk(dest: [*:0]u8, src: [*:0]const u8, n: usize, dest_n: usize) callconv(.C) [*:0]u8 { @setRuntimeSafety(false); var avail = dest_n; var dest_end: usize = 0; while (avail > 0 and dest[dest_end] != 0) : (dest_end += 1) { avail -= 1; } if (avail < 1) __chk_fail(); var i: usize = 0; while (avail > 0 and i < n and src[i] != 0) : (i += 1) { dest[dest_end + i] = src[i]; avail -= 1; } if (avail < 1) __chk_fail(); dest[dest_end + i] = 0; return dest; } export fn __memcpy_chk(noalias dest: ?[*]u8, noalias src: ?[*]const u8, n: usize, dest_n: usize) callconv(.C) ?[*]u8 { if (dest_n < n) __chk_fail(); return memcpy(dest, src, n); } export fn __memmove_chk(dest: ?[*]u8, src: ?[*]const u8, n: usize, dest_n: usize) callconv(.C) ?[*]u8 { if (dest_n < n) __chk_fail(); return memmove(dest, src, n); } export fn __memset_chk(dest: ?[*]u8, c: u8, n: usize, dest_n: usize) callconv(.C) ?[*]u8 { if (dest_n < n) __chk_fail(); return memset(dest, c, n); }
lib/std/special/ssp.zig
const std = @import("std"); const bog = @import("bog.zig"); const Tree = bog.Tree; const Node = bog.Node; const TokenIndex = bog.Token.Index; const changeDetectionWriter = std.io.changeDetectionStream; const autoIndentingWriter = std.io.autoIndentingStream; const indent_delta = 4; pub fn render(tree: *Tree, writer: anytype) @TypeOf(writer).Error!bool { var renderer = Renderer{ .source = tree.source, .tokens = tree.tokens, }; var change_writer = changeDetectionWriter(tree.source, writer); var indent_writer = autoIndentingWriter(indent_delta, change_writer.writer()); try renderer.renderComments(0, &indent_writer, .newline); for (tree.nodes) |node, i| { try renderer.renderNode(node, &indent_writer, .newline); if (Renderer.isBlock(node)) { // render extra newlines after blocks try indent_writer.insertNewline(); try indent_writer.insertNewline(); continue; } if (i + 1 == tree.nodes.len) break; const last_token = node.lastToken(); if (renderer.lineDist(last_token, renderer.nextToken(last_token)) > 1) { try indent_writer.writer().writeByte('\n'); } } return change_writer.changeDetected(); } const Renderer = struct { source: []const u8, tokens: []const bog.Token, fn prevToken(self: *Renderer, tok: TokenIndex) TokenIndex { var index = tok - 1; while (true) { switch (self.tokens[index].id) { .Comment, .Nl, .Indent => index -= 1, else => break, } } return index; } fn nextToken(self: *Renderer, tok: TokenIndex) TokenIndex { var index = tok + 1; while (true) { switch (self.tokens[index].id) { .Comment, .Nl, .Indent => index += 1, else => break, } } return index; } fn lineDist(self: *Renderer, a: TokenIndex, b: TokenIndex) u32 { const first_end = self.tokens[a].end; const second_start = self.tokens[b].start; var i = first_end; var count: u32 = 0; while (i < second_start) : (i += 1) { if (self.source[i] == '\n') { count += 1; } } return count; } fn renderNode(self: *Renderer, node: *Node, writer: anytype, space: Space) @TypeOf(writer.*).Error!void { switch (node.id) { .Literal => { const literal = @fieldParentPtr(Node.Literal, "base", node); if (literal.kind == .none) { try self.renderToken(self.prevToken(literal.tok), writer, .none); } return self.renderToken(literal.tok, writer, space); }, .Infix => { const infix = @fieldParentPtr(Node.Infix, "base", node); try self.renderNode(infix.lhs, writer, .space); const after_op_space: Space = if (self.lineDist(infix.tok, self.nextToken(infix.tok)) == 0) .space else .newline; writer.pushIndent(); try self.renderToken(infix.tok, writer, after_op_space); writer.popIndent(); writer.pushIndentOneShot(); return self.renderNode(infix.rhs, writer, space); }, .Range => { const range = @fieldParentPtr(Node.Range, "base", node); if (range.start) |some| try self.renderNode(some, writer, .none); try self.renderToken(range.colon_1, writer, if (range.end == null and range.colon_2 == null and range.step == null) space else .none); if (range.end) |some| try self.renderNode(some, writer, if (range.colon_2 == null and range.step == null) space else .none); if (range.colon_2) |some| try self.renderToken(some, writer, if (range.step == null) space else .none); if (range.step) |some| try self.renderNode(some, writer, space); }, .Prefix => { const prefix = @fieldParentPtr(Node.Prefix, "base", node); switch (prefix.op) { .bool_not => try self.renderToken(prefix.tok, writer, .space), .bit_not, .minus, .plus => try self.renderToken(prefix.tok, writer, .none), } return self.renderNode(prefix.rhs, writer, space); }, .Grouped => { const grouped = @fieldParentPtr(Node.Grouped, "base", node); try self.renderToken(grouped.l_tok, writer, getBlockIndent(grouped.expr, .none)); try self.renderNode(grouped.expr, writer, .none); return self.renderToken(grouped.r_tok, writer, space); }, .TypeInfix => { const type_infix = @fieldParentPtr(Node.TypeInfix, "base", node); try self.renderNode(type_infix.lhs, writer, .space); try self.renderToken(type_infix.tok, writer, .space); return self.renderToken(type_infix.type_tok, writer, space); }, .Discard, .Identifier, .This => { const single = @fieldParentPtr(Node.SingleToken, "base", node); return self.renderToken(single.tok, writer, space); }, .Suffix => { const suffix = @fieldParentPtr(Node.Suffix, "base", node); try self.renderNode(suffix.lhs, writer, .none); try self.renderToken(suffix.l_tok, writer, .none); switch (suffix.op) { .call => |params| try self.renderCommaList(params, suffix.r_tok, writer, .none), .subscript => |arr_node| try self.renderNode(arr_node, writer, .none), .member => {}, } return self.renderToken(suffix.r_tok, writer, space); }, .Decl => { const decl = @fieldParentPtr(Node.Decl, "base", node); try self.renderToken(decl.let_const, writer, .space); try self.renderNode(decl.capture, writer, .space); try self.renderToken(decl.eq_tok, writer, getBlockIndent(decl.value, .space)); return self.renderNode(decl.value, writer, space); }, .Import => { const import = @fieldParentPtr(Node.Import, "base", node); try self.renderToken(import.tok, writer, .none); try self.renderToken(self.nextToken(import.tok), writer, .none); try self.renderToken(import.str_tok, writer, .none); return self.renderToken(import.r_paren, writer, space); }, .Error => { const err = @fieldParentPtr(Node.Error, "base", node); const after_tok_space = if (err.capture == null) space else .none; try self.renderToken(err.tok, writer, after_tok_space); if (err.capture) |some| try self.renderNode(some, writer, space); }, .Tagged => { const tag = @fieldParentPtr(Node.Tagged, "base", node); try self.renderToken(tag.at, writer, .none); const after_tok_space = if (tag.capture == null) space else .none; try self.renderToken(tag.name, writer, after_tok_space); if (tag.capture) |some| try self.renderNode(some, writer, space); }, .Jump => { const jump = @fieldParentPtr(Node.Jump, "base", node); switch (jump.op) { .Return => |expr| { if (expr) |some| { try self.renderToken(jump.tok, writer, getBlockIndent(some, .space)); return self.renderNode(some, writer, space); } else { try self.renderToken(jump.tok, writer, space); } }, .Continue, .Break => try self.renderToken(jump.tok, writer, space), } }, .While => { const while_expr = @fieldParentPtr(Node.While, "base", node); try self.renderToken(while_expr.while_tok, writer, .space); try self.renderToken(self.nextToken(while_expr.while_tok), writer, .none); if (while_expr.capture) |some| { try self.renderToken(while_expr.let_const.?, writer, .space); try self.renderNode(some, writer, .space); try self.renderToken(while_expr.eq_tok.?, writer, .space); } try self.renderNode(while_expr.cond, writer, .none); try self.renderToken(while_expr.r_paren, writer, getBlockIndent(while_expr.body, .space)); return self.renderNode(while_expr.body, writer, space); }, .For => { const for_expr = @fieldParentPtr(Node.For, "base", node); try self.renderToken(for_expr.for_tok, writer, .space); try self.renderToken(self.nextToken(for_expr.for_tok), writer, .none); if (for_expr.capture) |some| { try self.renderToken(for_expr.let_const.?, writer, .space); try self.renderNode(some, writer, .space); try self.renderToken(for_expr.in_tok.?, writer, .space); } try self.renderNode(for_expr.cond, writer, .none); try self.renderToken(for_expr.r_paren, writer, getBlockIndent(for_expr.body, .space)); return self.renderNode(for_expr.body, writer, space); }, .Fn => { const fn_expr = @fieldParentPtr(Node.Fn, "base", node); try self.renderToken(fn_expr.fn_tok, writer, .none); try self.renderToken(self.nextToken(fn_expr.fn_tok), writer, .none); try self.renderCommaList(fn_expr.params, fn_expr.r_paren, writer, .none); try self.renderToken(fn_expr.r_paren, writer, getBlockIndent(fn_expr.body, .space)); return self.renderNode(fn_expr.body, writer, space); }, .List, .Tuple, .Map => { const ltm = @fieldParentPtr(Node.ListTupleMap, "base", node); try self.renderToken(ltm.l_tok, writer, .none); try self.renderCommaList(ltm.values, ltm.r_tok, writer, .none); return self.renderToken(ltm.r_tok, writer, space); }, .Block => { const blk = @fieldParentPtr(Node.Block, "base", node); writer.pushIndent(); for (blk.stmts) |stmt, i| { try self.renderNode(stmt, writer, .newline); if (isBlock(stmt)) { // render extra newlines after blocks try writer.insertNewline(); try writer.insertNewline(); continue; } if (i + 1 == blk.stmts.len) break; const last_token = stmt.lastToken(); if (self.lineDist(last_token, self.nextToken(last_token)) > 1) { try writer.insertNewline(); } } writer.popIndent(); }, .MapItem => { const item = @fieldParentPtr(Node.MapItem, "base", node); if (item.key) |some| { try self.renderNode(some, writer, .none); try self.renderToken(item.colon.?, writer, .space); } return self.renderNode(item.value, writer, space); }, .Try => { const try_expr = @fieldParentPtr(Node.Try, "base", node); try self.renderToken(try_expr.tok, writer, getBlockIndent(try_expr.expr, .space)); try self.renderNode(try_expr.expr, writer, .space); for (try_expr.catches) |catch_expr, i| { if (i + 1 == try_expr.catches.len) { try self.renderNode(catch_expr, writer, space); } else { try self.renderNode(catch_expr, writer, .space); } } }, .Catch => { const catch_expr = @fieldParentPtr(Node.Catch, "base", node); if (catch_expr.capture) |some| { try self.renderToken(catch_expr.tok, writer, .space); try self.renderToken(self.nextToken(catch_expr.tok), writer, .none); if (catch_expr.let_const) |tok| { try self.renderToken(tok, writer, .space); } try self.renderNode(some, writer, .none); try self.renderToken(self.nextToken(some.lastToken()), writer, getBlockIndent(catch_expr.expr, .space)); } else { try self.renderToken(catch_expr.tok, writer, getBlockIndent(catch_expr.expr, .space)); } return self.renderNode(catch_expr.expr, writer, space); }, .If => { const if_expr = @fieldParentPtr(Node.If, "base", node); try self.renderToken(if_expr.if_tok, writer, .space); try self.renderToken(self.nextToken(if_expr.if_tok), writer, .none); if (if_expr.capture) |some| { try self.renderToken(if_expr.let_const.?, writer, .space); try self.renderNode(some, writer, .space); try self.renderToken(if_expr.eq_tok.?, writer, .space); } try self.renderNode(if_expr.cond, writer, .none); try self.renderToken(if_expr.r_paren, writer, getBlockIndent(if_expr.if_body, .space)); if (if_expr.else_body) |some| { try self.renderNode(if_expr.if_body, writer, .space); try self.renderToken(if_expr.else_tok.?, writer, getBlockIndent(some, .space)); return self.renderNode(some, writer, space); } else { return self.renderNode(if_expr.if_body, writer, space); } }, .Match => { const match_expr = @fieldParentPtr(Node.Match, "base", node); try self.renderToken(match_expr.match_tok, writer, .space); try self.renderToken(self.nextToken(match_expr.match_tok), writer, .none); try self.renderNode(match_expr.expr, writer, .none); try self.renderToken(match_expr.r_paren, writer, .newline); writer.pushIndent(); for (match_expr.cases) |case| { try self.renderNode(case, writer, .newline); } writer.popIndent(); }, .MatchCatchAll => { const case = @fieldParentPtr(Node.MatchCatchAll, "base", node); try self.renderToken(case.tok, writer, .space); try self.renderToken(case.eq_arr, writer, getBlockIndent(case.expr, .space)); return self.renderNode(case.expr, writer, space); }, .MatchLet => { const case = @fieldParentPtr(Node.MatchLet, "base", node); try self.renderToken(case.let_const, writer, .space); try self.renderNode(case.capture, writer, .space); try self.renderToken(case.eq_arr, writer, getBlockIndent(case.expr, .space)); return self.renderNode(case.expr, writer, space); }, .MatchCase => { const case = @fieldParentPtr(Node.MatchCase, "base", node); try self.renderCommaList(case.items, case.eq_arr, writer, .space); try self.renderToken(case.eq_arr, writer, getBlockIndent(case.expr, .space)); return self.renderNode(case.expr, writer, space); }, .FormatString => { const fmt_str = @fieldParentPtr(Node.FormatString, "base", node); for (fmt_str.format) |str, i| { if (self.tokens[str].id == .FormatEnd) { return self.renderToken(str, writer, space); } try self.renderToken(str, writer, .none); try self.renderNode(fmt_str.args[i], writer, .none); } }, } } fn renderCommaList(self: *Renderer, nodes: []const *Node, last_token: TokenIndex, writer: anytype, space: Space) !void { if (nodes.len == 0) return; const prev = self.tokens[last_token - 1].id; if (prev == .Comma or prev == .Nl or prev == .Comment or self.lineDist(nodes[0].firstToken(), last_token) > 0) { try writer.insertNewline(); writer.pushIndent(); for (nodes) |node, i| { try self.renderNode(node, writer, .comma); } writer.popIndent(); } else { for (nodes) |node, i| { if (i + 1 == nodes.len) { try self.renderNode(node, writer, space); break; } try self.renderNode(node, writer, .none); try self.renderToken(self.nextToken(node.lastToken()), writer, .space); } } } fn renderComments(self: *Renderer, token: TokenIndex, writer: anytype, space: Space) !void { var i = token; var last_token = i; while (true) : (i += 1) { switch (self.tokens[i].id) { .Nl, .Indent => continue, .Comment => {}, else => break, } var tok = self.tokens[i]; const slice = self.source[tok.start..tok.end]; const trimmed = std.mem.trimRight(u8, slice, " \t\r"); if (trimmed.len == 1) continue; if (self.lineDist(last_token, i) > 1) { // insert extra new line between separate comments try writer.insertNewline(); } last_token = i; try writer.writer().writeAll(trimmed); try writer.insertNewline(); } } fn getBlockIndent(node: *Node, space: Space) Space { return switch (node.id) { .Block, .Match => .newline, else => space, }; } fn isBlock(node: *Node) bool { switch (node.id) { .Match => { const match_node = @fieldParentPtr(Node.Match, "base", node); return !isBlock(match_node.cases[match_node.cases.len - 1]); }, .Block => { const block_node = @fieldParentPtr(Node.Block, "base", node); return !isBlock(block_node.stmts[block_node.stmts.len - 1]); }, .If => { const if_node = @fieldParentPtr(Node.If, "base", node); if (if_node.else_body) |some| return isBlock(some); return isBlock(if_node.if_body); }, .For => { const for_node = @fieldParentPtr(Node.For, "base", node); return isBlock(for_node.body); }, .While => { const while_node = @fieldParentPtr(Node.While, "base", node); return isBlock(while_node.body); }, .Decl => { const decl = @fieldParentPtr(Node.Decl, "base", node); return isBlock(decl.value); }, .Fn => { const fn_node = @fieldParentPtr(Node.Fn, "base", node); return isBlock(fn_node.body); }, .Try => { const try_node = @fieldParentPtr(Node.Try, "base", node); return isBlock(try_node.expr); }, .Catch => { const catch_node = @fieldParentPtr(Node.Catch, "base", node); return isBlock(catch_node.expr); }, else => return false, } } const Space = enum { none, newline, space, comma, }; fn renderToken(self: *Renderer, token: TokenIndex, writer: anytype, space: Space) !void { var tok = self.tokens[token]; try writer.writer().writeAll(self.source[tok.start..tok.end]); switch (space) { .none => {}, .newline => try writer.insertNewline(), .space => try writer.writer().writeByte(' '), .comma => { try writer.writer().writeByte(','); var comments = token + 1; var i = comments; while (true) : (i += 1) { switch (self.tokens[i].id) { .Nl, .Indent => continue, .Comma => comments += 1, .Comment => { try writer.writer().writeByte(' '); break; }, else => return writer.insertNewline(), } } return self.renderComments(comments, writer, space); }, } try self.renderComments(token + 1, writer, space); } };
src/render.zig
const std = @import("std"); const allocators = @import("allocators.zig"); pub const fs = @import("lua-fs.zig"); pub const util = @import("lua-util.zig"); pub const c = @cImport({ @cDefine("LUA_EXTRASPACE", std.fmt.comptimePrint("{}", .{@sizeOf(allocators.TempAllocator)})); @cInclude("lua.h"); @cInclude("lualib.h"); @cInclude("lauxlib.h"); }); const L = ?*c.lua_State; /// Use State.call(0, 0) or State.callAll to invoke this pub fn registerStdLib(l: L) callconv(.C) c_int { c.luaL_openlibs(l); return 0; } pub fn getTempAlloc(l: L) *allocators.TempAllocator { // Note: this relies on LUA_EXTRASPACE being defined correctly, both in the @cImport and when the lua source files are compiled return @ptrCast(*allocators.TempAllocator, @alignCast(8, c.lua_getextraspace(l))); } pub const State = struct { l: L, pub fn init() State { var l = c.luaL_newstate(); getTempAlloc(l).* = allocators.TempAllocator.init(std.heap.page_allocator); return .{ .l = l, }; } pub fn deinit(self: State) void { getTempAlloc(self.l).deinit(); c.lua_close(self.l); } pub fn execute(self: State, chunk: []const u8, chunk_name: [:0]const u8) !void { switch (c.luaL_loadbufferx(self.l, chunk.ptr, chunk.len, chunk_name.ptr, null)) { c.LUA_OK => {}, c.LUA_ERRMEM => return error.OutOfMemory, else => return error.LuaSyntaxError, } try self.call(0, 0); } pub fn callAll(self: State, funcs: []const c.lua_CFunction) !void { if (funcs.len > std.math.maxInt(c_int) or 0 == c.lua_checkstack(self.l, @intCast(c_int, funcs.len))) { return error.TooManyFunctions; } self.pushCFunction(traceUnsafe); const trace_index = self.getTop(); self.pushCFunction(callAllUnsafe); for (funcs) |func| { self.pushCFunction(func); } defer self.removeIndex(trace_index); switch (c.lua_pcallk(self.l, @intCast(c_int, funcs.len), 0, trace_index, 0, null)) { c.LUA_OK => {}, c.LUA_ERRMEM => return error.OutOfMemory, else => return error.LuaRuntimeError, } } fn callAllUnsafe(l: L) callconv(.C) c_int { const top = c.lua_gettop(l); var i: c_int = 1; while (i <= top) : (i += 1) { c.lua_pushvalue(l, i); c.lua_callk(l, 0, 0, 0, null); } return 0; } pub fn call(self: State, num_args: c_int, num_results: c_int) !void { var func_index = self.getTop() - num_args; self.pushCFunction(traceUnsafe); self.moveToIndex(func_index); // put it under function and args defer self.removeIndex(func_index); switch (c.lua_pcallk(self.l, num_args, num_results, func_index, 0, null)) { c.LUA_OK => {}, c.LUA_ERRMEM => return error.OutOfMemory, else => return error.LuaRuntimeError, } } fn traceUnsafe(l: L) callconv(.C) c_int { if (c.lua_isstring(l, 1) != 0) { var ptr = c.lua_tolstring(l, 1, null); c.luaL_traceback(l, l, ptr, 1); } else if (!c.lua_isnoneornil(l, 1)) { var ptr = c.luaL_tolstring(l, 1, null); c.luaL_traceback(l, l, ptr, 1); removeIndex(.{ .l = l }, 2); } return 1; } pub fn callNoTrace(self: State, num_args: c_int, num_results: c_int) !void { switch (c.lua_pcallk(self.l, num_args, num_results, 0, 0, null)) { c.LUA_OK => {}, c.LUA_ERRMEM => return error.OutOfMemory, else => return error.LuaRuntimeError, } } pub fn pushGlobal(self: State, slot: []const u8) !void { _ = c.lua_rawgeti(self.l, c.LUA_REGISTRYINDEX, c.LUA_RIDX_GLOBALS); try self.pushTableString(-1, slot); self.removeIndex(-2); } pub fn pushTableString(self: State, table_index: c_int, slot: []const u8) !void { var mutable_slot = slot; c.lua_pushvalue(self.l, table_index); self.pushCFunction(pushTableStringUnsafe); self.moveToIndex(-2); self.pushPointer(&mutable_slot); try self.call(2, 1); } fn pushTableStringUnsafe(l: L) callconv(.C) c_int { var slot_ptr = @ptrCast(*const []const u8, @alignCast(8, c.lua_topointer(l, 2))); _ = c.lua_pushlstring(l, slot_ptr.*.ptr, slot_ptr.*.len); _ = c.lua_gettable(l, 1); return 1; } pub fn setGlobalString(self: State, slot: []const u8, value: []const u8) !void { _ = c.lua_rawgeti(self.l, c.LUA_REGISTRYINDEX, c.LUA_RIDX_GLOBALS); try self.setTableStringString(-1, slot, value); c.lua_settop(self.l, -2); } pub fn setTableStringString(self: State, table_index: c_int, slot: []const u8, value: []const u8) !void { var mutable_slot = slot; var mutable_value = value; c.lua_pushvalue(self.l, table_index); self.pushCFunction(setTableStringStringUnsafe); self.moveToIndex(-2); self.pushPointer(&mutable_slot); self.pushPointer(&mutable_value); try self.call(3, 0); } fn setTableStringStringUnsafe(l: L) callconv(.C) c_int { var slot_ptr = @ptrCast(*const []const u8, @alignCast(8, c.lua_topointer(l, 2))); var value_ptr = @ptrCast(*const []const u8, @alignCast(8, c.lua_topointer(l, 3))); _ = c.lua_pushlstring(l, slot_ptr.*.ptr, slot_ptr.*.len); _ = c.lua_pushlstring(l, value_ptr.*.ptr, value_ptr.*.len); c.lua_settable(l, 1); return 0; } pub fn pushString(self: State, str: []const u8) !void { self.pushCFunction(pushStringUnsafe); self.pushPointer(&str); self.callNoTrace(1, 1); } fn pushStringUnsafe(l: L) callconv(.C) c_int { var str_ptr = @as(*[]const u8, c.lua_topointer(l, 1)); c.lua_settop(l, 0); _ = c.lua_pushlstring(l, str_ptr.*.ptr, str_ptr.*.len); return 1; } pub inline fn pushInteger(self: State, value: c.lua_Integer) void { c.lua_pushinteger(self.l, value); } pub inline fn pushPointer(self: State, value: *anyopaque) void { c.lua_pushlightuserdata(self.l, value); } pub inline fn pushCFunction(self: State, func: c.lua_CFunction) void { c.lua_pushcclosure(self.l, func, 0); } pub inline fn moveToIndex(self: State, index: c_int) void { c.lua_rotate(self.l, index, 1); } // This is only safe when removing an index that isn't to-be-closed inline fn removeIndex(self: State, index: c_int) void { c.lua_rotate(self.l, index, -1); c.lua_settop(self.l, -2); } pub inline fn getTop(self: State) c_int { return c.lua_gettop(self.l); } pub inline fn setTop(self: State, index: c_int) void { c.lua_settop(self.l, index); } pub fn getString(self: State, index: i8, default: []const u8) []const u8 { if (c.lua_type(self.l, index) == c.LUA_TSTRING) { var slice: []const u8 = undefined; slice.ptr = c.lua_tolstring(self.l, index, &slice.len); return slice; } else { return default; } } pub fn debugStack(self: State, msg: []const u8) !void { var stdout = std.io.getStdOut().writer(); var top = self.getTop(); try stdout.print("{s} ({}): ", .{ msg, top }); var i: c_int = 1; while (i <= top) : (i += 1) { switch (c.lua_type(self.l, i)) { c.LUA_TNIL => { try stdout.print("nil, ", .{}); }, c.LUA_TNUMBER => { try stdout.print("number, ", .{}); }, c.LUA_TBOOLEAN => { try stdout.print("boolean, ", .{}); }, c.LUA_TSTRING => { try stdout.print("string, ", .{}); }, c.LUA_TTABLE => { try stdout.print("table, ", .{}); }, c.LUA_TFUNCTION => { try stdout.print("function, ", .{}); }, c.LUA_TUSERDATA => { try stdout.print("ud, ", .{}); }, c.LUA_TTHREAD => { try stdout.print("thread, ", .{}); }, c.LUA_TLIGHTUSERDATA => { try stdout.print("lightud, ", .{}); }, else => { try stdout.print("unknown, ", .{}); }, } } try stdout.print("\n", .{}); } };
limp/lua.zig
const std = @import("std"); const c = @import("c.zig"); const git = @import("../git.zig"); const log = std.log.scoped(.git); pub inline fn wrapCall(comptime name: []const u8, args: anytype) git.GitError!void { if (@typeInfo(@TypeOf(@field(c, name))).Fn.return_type.? == void) { @call(.{}, @field(c, name), args); return; } const result = @call(.{}, @field(c, name), args); if (result >= 0) return; return unwrapError(name, result); } pub inline fn wrapCallWithReturn( comptime name: []const u8, args: anytype, ) git.GitError!@typeInfo(@TypeOf(@field(c, name))).Fn.return_type.? { const result = @call(.{}, @field(c, name), args); if (result >= 0) return result; return unwrapError(name, result); } fn unwrapError(name: []const u8, value: c.git_error_code) git.GitError { const err = switch (value) { c.GIT_ERROR => git.GitError.GenericError, c.GIT_ENOTFOUND => git.GitError.NotFound, c.GIT_EEXISTS => git.GitError.Exists, c.GIT_EAMBIGUOUS => git.GitError.Ambiguous, c.GIT_EBUFS => git.GitError.BufferTooShort, c.GIT_EUSER => git.GitError.User, c.GIT_EBAREREPO => git.GitError.BareRepo, c.GIT_EUNBORNBRANCH => git.GitError.UnbornBranch, c.GIT_EUNMERGED => git.GitError.Unmerged, c.GIT_ENONFASTFORWARD => git.GitError.NonFastForwardable, c.GIT_EINVALIDSPEC => git.GitError.InvalidSpec, c.GIT_ECONFLICT => git.GitError.Conflict, c.GIT_ELOCKED => git.GitError.Locked, c.GIT_EMODIFIED => git.GitError.Modifed, c.GIT_EAUTH => git.GitError.Auth, c.GIT_ECERTIFICATE => git.GitError.Certificate, c.GIT_EAPPLIED => git.GitError.Applied, c.GIT_EPEEL => git.GitError.Peel, c.GIT_EEOF => git.GitError.EndOfFile, c.GIT_EINVALID => git.GitError.Invalid, c.GIT_EUNCOMMITTED => git.GitError.Uncommited, c.GIT_EDIRECTORY => git.GitError.Directory, c.GIT_EMERGECONFLICT => git.GitError.MergeConflict, c.GIT_PASSTHROUGH => git.GitError.Passthrough, c.GIT_ITEROVER => git.GitError.IterOver, c.GIT_RETRY => git.GitError.Retry, c.GIT_EMISMATCH => git.GitError.Mismatch, c.GIT_EINDEXDIRTY => git.GitError.IndexDirty, c.GIT_EAPPLYFAIL => git.GitError.ApplyFail, else => { log.err("encountered unknown libgit2 error: {}", .{value}); unreachable; }, }; // We dont want to output log messages in tests, as the error might be expected // also dont incur the cost of calling `getDetailedLastError` if we are not going to use it if (!@import("builtin").is_test and @enumToInt(std.log.Level.warn) <= @enumToInt(std.log.level)) { if (git.getDetailedLastError()) |detailed| { log.warn("{s} failed with error {s}/{s} - {s}", .{ name, @errorName(err), @tagName(detailed.class), detailed.message(), }); } else { log.warn("{s} failed with error {s}", .{ name, @errorName(err), }); } } return err; } pub fn formatWithoutFields( value: anytype, options: std.fmt.FormatOptions, writer: anytype, comptime blacklist: []const []const u8, ) !void { // This ANY const is a workaround for: https://github.com/ziglang/zig/issues/7948 const ANY = "any"; const T = @TypeOf(value); switch (@typeInfo(T)) { .Struct => |info| { try writer.writeAll(@typeName(T)); try writer.writeAll("{"); comptime var i = 0; outer: inline for (info.fields) |f| { inline for (blacklist) |blacklist_item| { if (comptime std.mem.indexOf(u8, f.name, blacklist_item) != null) continue :outer; } if (i == 0) { try writer.writeAll(" ."); } else { try writer.writeAll(", ."); } try writer.writeAll(f.name); try writer.writeAll(" = "); try std.fmt.formatType(@field(value, f.name), ANY, options, writer, std.fmt.default_max_depth - 1); i += 1; } try writer.writeAll(" }"); }, else => { @compileError("Unimplemented for: " ++ @typeName(T)); }, } } comptime { std.testing.refAllDecls(@This()); }
src/internal/internal.zig
const std = @import("std"); const user32 = std.os.windows.user32; const w = @import("windows.zig"); const xinput = @import("xinput.zig"); const dsound = @import("dsound.zig"); const L = std.unicode.utf8ToUtf16LeStringLiteral; // const c = @cImport({ // @cInclude("windows.h"); // @cInclude("wingdi.h"); // @cInclude("xinput.h"); // }); var allocator: *std.mem.Allocator = undefined; //const allocator = std.heap.page_allocator; //const allocator = std.testing.allocator; const GameInput = @import("handmade.zig").GameInput; const GameOffscreenBuffer = @import("handmade.zig").GameOffscreenBuffer; const GameButtonState = @import("handmade.zig").GameButtonState; const GameSoundOutputBuffer = @import("handmade.zig").GameSoundOutputBuffer; const GameUpdateAndRender = @import("handmade.zig").GameUpdateAndRender; const OffscreenBuffer = struct { info: w.BITMAPINFO = std.mem.zeroes(w.BITMAPINFO), memory: ?[:0]c_uint = null, width: i32 = undefined, height: i32 = undefined, bytesPerPixel: usize = undefined, pitch: usize = undefined, }; //Globals var running = false; var backBuffer: OffscreenBuffer = .{ .bytesPerPixel = 4, }; const WindowSize = struct { width: i32, height: i32, }; fn Win32GetWindowSize(window: user32.HWND) WindowSize { var clientRect: user32.RECT = undefined; _ = w.getClientRect(window, &clientRect) catch unreachable; const width = clientRect.right - clientRect.left; const height = clientRect.bottom - clientRect.top; return .{ .width = width, .height = height }; } fn Win32ResizeDIBSection(buffer: *OffscreenBuffer, width: i32, height: i32) void { if (buffer.memory != null) { allocator.free(buffer.memory.?); buffer.memory = null; } buffer.width = width; buffer.height = height; buffer.bytesPerPixel = 4; buffer.pitch = @intCast(usize, width); buffer.info.bmiHeader.biSize = @sizeOf(w.BITMAPINFOHEADER); buffer.info.bmiHeader.biWidth = width; buffer.info.bmiHeader.biHeight = -height; // Negative for top-down drawing buffer.info.bmiHeader.biPlanes = 1; buffer.info.bmiHeader.biBitCount = 32; buffer.info.bmiHeader.biCompression = w.BI_RGB; const bitmapSize: usize = @intCast(usize, width * height); if (bitmapSize != 0) { // bitmapSize is 0 when the window is minimized buffer.memory = allocator.allocWithOptions(c_uint, bitmapSize, null, 0) catch unreachable; } // TODO: clear to black? } fn Win32UpdateWindow(hdc: user32.HDC, windowWidth: i32, windowHeight: i32, buffer: *OffscreenBuffer, x: i32, y: i32, width: i32, height: i32) void { _ = x; _ = y; _ = width; _ = height; // TODO: Aspect ratio correction _ = w.stretchDIBits(hdc, 0, 0, windowWidth, windowHeight, 0, 0, buffer.width, buffer.height, buffer.memory.?.ptr, &buffer.info, w.DIB_RGB_COLORS, w.SRCCOPY) catch unreachable; } // Responds to Windows' calls into this app // https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms633573(v=vs.85) fn Win32MainWindowCallback(window: user32.HWND, message: c_uint, wparam: usize, lparam: isize) callconv(.C) user32.LRESULT { const result: user32.LRESULT = 0; switch (message) { user32.WM_SIZE => { // const windowSize = Win32GetWindowSize(window); // Win32ResizeDIBSection(&backBuffer, windowSize.width, windowSize.height); // TODO: screen goes black while resizing. // calling RenderWeirdGradient fixes this but // we would have to make the offsets global // RenderWeirdGradient(0,0); }, user32.WM_ACTIVATE => { std.debug.print("WM_ACTIVATE\n", .{}); }, user32.WM_CLOSE => { std.debug.print("WM_CLOSE\n", .{}); running = false; }, user32.WM_DESTROY => { std.debug.print("WM_DESTROY\n", .{}); running = false; }, user32.WM_SYSKEYDOWN, user32.WM_SYSKEYUP, user32.WM_KEYDOWN, user32.WM_KEYUP => { const vKCode = @truncate(u8, wparam); const altDown = (lparam & (1 << 29)) != 0; const wasDown = (lparam & (1 << 30)) != 0; const isDown = (lparam & (1 << 31)) == 0; const justPressed = isDown and !wasDown; //const justReleased = !isDown and wasDown; switch (vKCode) { 'W' => std.debug.print("W\n", .{}), 'A' => std.debug.print("A\n", .{}), 'S' => std.debug.print("S\n", .{}), 'D' => std.debug.print("D\n", .{}), 'Q' => std.debug.print("Q\n", .{}), 'E' => std.debug.print("E\n", .{}), '1' => std.debug.print("1\n", .{}), '2' => std.debug.print("2\n", .{}), '3' => std.debug.print("3\n", .{}), '4' => std.debug.print("4\n", .{}), '5' => std.debug.print("5\n", .{}), w.VK_ESCAPE => { std.debug.print("Esc ", .{}); if (isDown) { std.debug.print("IsDown ", .{}); } if (wasDown) { std.debug.print("Was Down", .{}); } std.debug.print("\n", .{}); }, w.VK_SPACE => std.debug.print("Spacebar\n", .{}), w.VK_LEFT => std.debug.print("LEFT\n", .{}), w.VK_UP => std.debug.print("UP\n", .{}), w.VK_RIGHT => std.debug.print("RIGHT\n", .{}), w.VK_DOWN => std.debug.print("DOWN\n", .{}), w.VK_PRINT => std.debug.print("PRINT\n", .{}), w.VK_F4 => { if (altDown and justPressed) { running = false; } }, else => {}, } }, user32.WM_PAINT => { var paint: w.PAINTSTRUCT = undefined; var context = w.beginPaint(window, &paint).?; defer _ = w.endPaint(window, &paint); const x = paint.rcPaint.left; const y = paint.rcPaint.top; const width = paint.rcPaint.right - paint.rcPaint.left; const height = paint.rcPaint.bottom - paint.rcPaint.top; const windowSize = Win32GetWindowSize(window); Win32UpdateWindow(context, windowSize.width, windowSize.height, &backBuffer, x, y, width, height); }, else => { return user32.defWindowProcW(window, message, wparam, lparam); }, } return result; } fn win32FillSoundBuffer(soundOutput: *dsound.win32_sound_output, lockOffset: w.DWORD, bytesToWrite: w.DWORD, sourceBuffer: *GameSoundOutputBuffer) !void { var Region1: ?*c_void = undefined; var Region1Size: u32 = undefined; var Region2: ?*c_void = undefined; var Region2Size: u32 = undefined; if (bytesToWrite == 0) return; if (dsound.IDirectSoundBuffer_Lock(dsound.GlobalSoundBuffer, lockOffset, bytesToWrite, &Region1, &Region1Size, &Region2, &Region2Size, 0)) { var sourceIndex: usize = 0; const Region1SampleCount = Region1Size / soundOutput.bytesPerSample; var destSample = @ptrCast([*c]i16, @alignCast(@alignOf(i16), Region1)); var sampleIndex: u32 = 0; while (sampleIndex < Region1SampleCount) : (sampleIndex +%= 1) { destSample.* = sourceBuffer.samples.*[sourceIndex]; destSample += 1; sourceIndex += 1; destSample.* = sourceBuffer.samples.*[sourceIndex]; destSample += 1; sourceIndex += 1; soundOutput.runningSampleIndex +%= 1; } const Region2SampleCount = Region2Size / soundOutput.bytesPerSample; destSample = @ptrCast([*c]i16, @alignCast(@alignOf(i16), Region2)); sampleIndex = 0; while (sampleIndex < Region2SampleCount) : (sampleIndex +%= 1) { destSample.* = sourceBuffer.samples.*[sourceIndex]; destSample += 1; sourceIndex += 1; destSample.* = sourceBuffer.samples.*[sourceIndex]; destSample += 1; sourceIndex += 1; soundOutput.runningSampleIndex +%= 1; } dsound.IDirectSoundBuffer_Unlock(Region1, Region1Size, Region2, Region2Size) catch {}; } else |_| {} } fn win32ClearSoundBuffer(soundOutput: *dsound.win32_sound_output) void { var Region1: ?*c_void = undefined; var Region1Size: u32 = undefined; var Region2: ?*c_void = undefined; var Region2Size: u32 = undefined; if (dsound.IDirectSoundBuffer_Lock(dsound.GlobalSoundBuffer, 0, soundOutput.soundBufferSize, &Region1, &Region1Size, &Region2, &Region2Size, 0)) { const Region1SampleCount = Region1Size / soundOutput.bytesPerSample; var destSample = @ptrCast([*c]i16, @alignCast(@alignOf(i16), Region1)); var sampleIndex: u32 = 0; while (sampleIndex < Region1SampleCount) : (sampleIndex +%= 1) { destSample.* = 0; destSample += 1; destSample.* = 0; destSample += 1; } const Region2SampleCount = Region2Size / soundOutput.bytesPerSample; destSample = @ptrCast([*c]i16, @alignCast(@alignOf(i16), Region2)); sampleIndex = 0; while (sampleIndex < Region2SampleCount) : (sampleIndex +%= 1) { destSample.* = 0; destSample += 1; destSample.* = 0; destSample += 1; } dsound.IDirectSoundBuffer_Unlock(Region1, Region1Size, Region2, Region2Size) catch {}; } else |_| {} } fn Win32ProcessXInputDigitalButton(xinputButtonState: w.DWORD, oldState: *GameButtonState, buttonBit: w.DWORD, newState: *GameButtonState) void { newState.endedDown = (xinputButtonState & buttonBit) == buttonBit; newState.halfTransitionCounter = if (oldState.endedDown != newState.endedDown) 1 else 0; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer std.testing.expect(!gpa.deinit()) catch @panic("leak"); allocator = &gpa.allocator; const instance = @ptrCast(user32.HINSTANCE, w.kernel32.GetModuleHandleW(null).?); var counterPerSecond = w.QueryPerformanceFrequency(); xinput.win32LoadXinput(); Win32ResizeDIBSection(&backBuffer, 1280, 720); defer Win32ResizeDIBSection(&backBuffer, 0, 0); // Frees the backBuffer.memory at the end const window_title = L("Handmade Zero"); var windowClass: user32.WNDCLASSEXW = .{ .lpfnWndProc = Win32MainWindowCallback, .hInstance = instance, .lpszClassName = L("HandmadeWindowClass"), .style = user32.CS_HREDRAW | user32.CS_VREDRAW | user32.CS_OWNDC, .lpszMenuName = null, .hIcon = null, .hCursor = null, .hbrBackground = null, .hIconSm = null, }; _ = user32.registerClassExW(&windowClass) catch |err| { std.debug.print("error registerClassExW: {}", .{err}); return err; }; var window = user32.createWindowExW(0, windowClass.lpszClassName, window_title, user32.WS_OVERLAPPEDWINDOW | user32.WS_VISIBLE, user32.CW_USEDEFAULT, user32.CW_USEDEFAULT, user32.CW_USEDEFAULT, user32.CW_USEDEFAULT, null, null, instance, null) catch |err| { std.debug.print("error createWindowExW: {}", .{err}); return err; }; // CS_OWNDC in windowClass.style lets us keep the deviceContext forever const deviceContext = user32.getDC(window) catch unreachable; //defer _ = user32.ReleaseDC(window, deviceContext); // Sound Stuff var soundOutput = blk: { const samplesPerSecond = 48000; const bytesPerSample = @sizeOf(u16) * 2; break :blk dsound.win32_sound_output{ .samplesPerSecond = samplesPerSecond, .bytesPerSample = bytesPerSample, .soundBufferSize = samplesPerSecond * bytesPerSample, .runningSampleIndex = 0, .latencySampleCount = samplesPerSecond / 15, }; }; dsound.win32InitDSound(window, soundOutput.samplesPerSecond, soundOutput.soundBufferSize); win32ClearSoundBuffer(&soundOutput); dsound.IDirectSoundBuffer_Play(dsound.GlobalSoundBuffer, 0, 0, dsound.DSBPLAY_LOOPING) catch {}; var samples: []i16 = try allocator.alloc(i16, soundOutput.soundBufferSize); defer allocator.free(samples); var inputs: [2]GameInput = .{ std.mem.zeroes(GameInput), std.mem.zeroes(GameInput) }; var newInput: *GameInput = &inputs[1]; var oldInput: *GameInput = &inputs[0]; //var lastCycleCounter = w.__rdtsc(); var lastCounter = w.QueryPerformanceCounter(); running = true; while (running) { var message: user32.MSG = undefined; while (user32.peekMessageW(&message, window, 0, 0, user32.PM_REMOVE)) |moreMessages| { if (!moreMessages) break; if (message.message == user32.WM_QUIT) { running = false; } _ = user32.translateMessage(&message); _ = user32.dispatchMessageW(&message); } else |err| { std.debug.print("error getMessageW: {}", .{err}); return err; } // Controller var maxControllerCount = std.math.min(xinput.XUSER_MAX_COUNT, newInput.controllers.len); var controllerIndex: u32 = 0; while (controllerIndex < maxControllerCount) : (controllerIndex += 1) { var oldController = &oldInput.controllers[@as(usize, controllerIndex)]; var newController = &newInput.controllers[@as(usize, controllerIndex)]; var controllerState: xinput.XINPUT_STATE = undefined; if (xinput.getState(controllerIndex, &controllerState)) { const Pad = controllerState.Gamepad; // const Up: bool = Pad.wButtons & xinput.GAMEPAD_DPAD_UP != 0; // const Down: bool = Pad.wButtons & xinput.GAMEPAD_DPAD_DOWN != 0; // const Left: bool = Pad.wButtons & xinput.GAMEPAD_DPAD_LEFT != 0; // const Right: bool = Pad.wButtons & xinput.GAMEPAD_DPAD_RIGHT != 0; // const Start: bool = Pad.wButtons & xinput.GAMEPAD_START != 0; // const Back: bool = Pad.wButtons & xinput.GAMEPAD_BACK != 0; // const LeftShoulder: bool = Pad.wButtons & xinput.GAMEPAD_LEFT_SHOULDER != 0; // const RightShoulder: bool = Pad.wButtons & xinput.GAMEPAD_RIGHT_SHOULDER != 0; // const AButton: bool = Pad.wButtons & xinput.GAMEPAD_A != 0; // const BButton: bool = Pad.wButtons & xinput.GAMEPAD_B != 0; // const XButton: bool = Pad.wButtons & xinput.GAMEPAD_X != 0; // const YButton: bool = Pad.wButtons & xinput.GAMEPAD_Y != 0; Win32ProcessXInputDigitalButton(Pad.wButtons, &oldController.buttons.up, xinput.GAMEPAD_DPAD_UP, &newController.buttons.up); Win32ProcessXInputDigitalButton(Pad.wButtons, &oldController.buttons.down, xinput.GAMEPAD_DPAD_DOWN, &newController.buttons.down); Win32ProcessXInputDigitalButton(Pad.wButtons, &oldController.buttons.left, xinput.GAMEPAD_DPAD_LEFT, &newController.buttons.left); Win32ProcessXInputDigitalButton(Pad.wButtons, &oldController.buttons.right, xinput.GAMEPAD_DPAD_RIGHT, &newController.buttons.right); Win32ProcessXInputDigitalButton(Pad.wButtons, &oldController.buttons.leftShoulder, xinput.GAMEPAD_START, &newController.buttons.leftShoulder); Win32ProcessXInputDigitalButton(Pad.wButtons, &oldController.buttons.rightShoulder, xinput.GAMEPAD_BACK, &newController.buttons.rightShoulder); newController.isAnalog = true; newController.startX = oldController.endX; newController.startY = oldController.endY; // CHECK, it seems the max left is -32767 and not -32768 const leftStickX: f32 = if (Pad.sThumbLX < 0) (@intToFloat(f32, Pad.sThumbLX) / 32767) else (@intToFloat(f32, Pad.sThumbLX) / 32767); const leftStickY: f32 = if (Pad.sThumbLY < 0) (@intToFloat(f32, Pad.sThumbLY) / 32767) else (@intToFloat(f32, Pad.sThumbLY) / 32767); newController.minX = leftStickX; newController.maxX = leftStickX; newController.endX = leftStickX; newController.minY = leftStickY; newController.maxY = leftStickY; newController.endY = leftStickY; // TODO: deadzone } else |_| { // Controller not available } } // Sound stuff var PlayCursor: w.DWORD = undefined; var WriteCursor: w.DWORD = undefined; var lockOffset: w.DWORD = undefined; var targetCursor: w.DWORD = undefined; var bytesToWrite: w.DWORD = undefined; var soundIsValid = false; if (dsound.IDirectSoundBuffer_GetCurrentPosition(&PlayCursor, &WriteCursor)) { lockOffset = (soundOutput.runningSampleIndex * soundOutput.bytesPerSample) % soundOutput.soundBufferSize; targetCursor = (PlayCursor + (soundOutput.latencySampleCount * soundOutput.bytesPerSample)) % soundOutput.soundBufferSize; bytesToWrite = blk: { if (lockOffset == targetCursor) { break :blk 0; } else if (lockOffset > targetCursor) { break :blk soundOutput.soundBufferSize - lockOffset + targetCursor; } else { break :blk targetCursor - lockOffset; } }; soundIsValid = true; } else |_| {} var soundBuffer: GameSoundOutputBuffer = .{ .samplesPerSecond = soundOutput.samplesPerSecond, .sampleCount = @divTrunc(@intCast(i32, bytesToWrite), @intCast(i32, soundOutput.bytesPerSample)), .samples = &samples, }; var buffer: GameOffscreenBuffer = .{ .memory = &backBuffer.memory, .width = backBuffer.width, .height = backBuffer.height, .pitch = backBuffer.pitch, }; GameUpdateAndRender(newInput, &buffer, &soundBuffer); if (soundIsValid) { win32FillSoundBuffer(&soundOutput, lockOffset, bytesToWrite, &soundBuffer) catch {}; } else |_| {} const windowSize = Win32GetWindowSize(window); Win32UpdateWindow(deviceContext, windowSize.width, windowSize.height, &backBuffer, 0, 0, windowSize.width, windowSize.height); // var currentCycleCounter = w.__rdtsc(); var currentCounter = w.QueryPerformanceCounter(); var counterElapsed = currentCounter - lastCounter; // var cycleElapsed = currentCycleCounter - lastCycleCounter; var msPerFrame = 1000 * counterElapsed / counterPerSecond; var fps = counterPerSecond / counterElapsed; //var mcpf = cycleElapsed / (1000 * 1000); if (false) { std.debug.print("ms/f: {d}, fps: {d}, mc/f: {d}\n", .{ msPerFrame, fps, 0 }); } lastCounter = currentCounter; // lastCycleCounter = currentCycleCounter; var temp = oldInput; oldInput = newInput; newInput = temp; } }
src/win32_handmade.zig
const clap = @import("clap"); const format = @import("format"); const std = @import("std"); const util = @import("util"); const debug = std.debug; const fmt = std.fmt; const fs = std.fs; const heap = std.heap; const io = std.io; const log = std.log; const math = std.math; const mem = std.mem; const os = std.os; const rand = std.rand; const testing = std.testing; const Program = @This(); allocator: mem.Allocator, options: struct { easy_hms: bool, fast_text: bool, biking: Allow, running: Allow, exp_scale: f64, static_scale: f64, trainer_scale: f64, wild_scale: f64, }, const Allow = enum { unchanged, nowhere, everywhere, }; pub const main = util.generateMain(Program); pub const version = "0.0.0"; pub const description = \\Command to apply miscellaneous changed. \\ ; pub const params = &[_]clap.Param(clap.Help){ clap.parseParam(" --allow-biking <unchanged|nowhere|everywhere> Change where biking is allowed (gen3 only) (default: unchanged).") catch unreachable, clap.parseParam(" --allow-running <unchanged|nowhere|everywhere> Change where running is allowed (gen3 only) (default: unchanged).") catch unreachable, clap.parseParam(" --easy-hms Have all Pokémon be able to learn all HMs.") catch unreachable, clap.parseParam(" --fast-text Change text speed to fastest possible for the game.") catch unreachable, clap.parseParam(" --exp-yield-scaling <FLOAT> Scale The amount of exp Pokémons give. (default: 1.0).") catch unreachable, clap.parseParam(" --static-level-scaling <FLOAT> Scale static Pokémon levels by this number. (default: 1.0).") catch unreachable, clap.parseParam(" --trainer-level-scaling <FLOAT> Scale trainer Pokémon levels by this number. (default: 1.0).") catch unreachable, clap.parseParam(" --wild-level-scaling <FLOAT> Scale wild Pokémon levels by this number. (default: 1.0).") catch unreachable, clap.parseParam("-h, --help Display this help text and exit.") catch unreachable, clap.parseParam("-v, --version Output version information and exit.") catch unreachable, }; pub fn init(allocator: mem.Allocator, args: anytype) !Program { const biking_arg = args.option("--allow-biking") orelse "unchanged"; const running_arg = args.option("--allow-running") orelse "unchanged"; const exp_scale_arg = args.option("--exp-yield-scaling") orelse "1.0"; const static_scale_arg = args.option("--static-level-scaling") orelse "1.0"; const trainer_scale_arg = args.option("--trainer-level-scaling") orelse "1.0"; const wild_scale_arg = args.option("--wild-level-scaling") orelse "1.0"; const easy_hms = args.flag("--easy-hms"); const fast_text = args.flag("--fast-text"); const biking = std.meta.stringToEnum(Allow, biking_arg); const running = std.meta.stringToEnum(Allow, running_arg); const trainer_scale = fmt.parseFloat(f64, trainer_scale_arg); const wild_scale = fmt.parseFloat(f64, wild_scale_arg); const static_scale = fmt.parseFloat(f64, static_scale_arg); const exp_scale = fmt.parseFloat(f64, exp_scale_arg); for ([_]struct { arg: []const u8, value: []const u8, check: ?Allow }{ .{ .arg = "--allow-biking", .value = biking_arg, .check = biking }, .{ .arg = "--allow-running", .value = running_arg, .check = running }, }) |arg| { if (arg.check == null) { log.err("Invalid value for {s}: {s}", .{ arg.arg, arg.value }); return error.InvalidArgument; } } for ([_]struct { arg: []const u8, value: []const u8, check: anyerror!f64 }{ .{ .arg = "--exp-yield-scaling", .value = exp_scale_arg, .check = exp_scale }, .{ .arg = "--static-level-scaling", .value = static_scale_arg, .check = static_scale }, .{ .arg = "--trainer-level-scaling", .value = trainer_scale_arg, .check = trainer_scale }, .{ .arg = "--wild-level-scaling", .value = wild_scale_arg, .check = wild_scale }, }) |arg| { if (arg.check) |_| {} else |_| { log.err("Invalid value for {s}: {s}", .{ arg.arg, arg.value }); return error.InvalidArgument; } } return Program{ .allocator = allocator, .options = .{ .easy_hms = easy_hms, .fast_text = fast_text, .biking = biking.?, .running = running.?, .exp_scale = exp_scale catch unreachable, .static_scale = static_scale catch unreachable, .trainer_scale = trainer_scale catch unreachable, .wild_scale = wild_scale catch unreachable, }, }; } pub fn run( program: *Program, comptime Reader: type, comptime Writer: type, stdio: util.CustomStdIoStreams(Reader, Writer), ) !void { try format.io( program.allocator, stdio.in, stdio.out, .{ .out = stdio.out, .program = program }, useGame, ); } fn useGame(ctx: anytype, game: format.Game) !void { const out = ctx.out; const program = ctx.program; switch (game) { .instant_text => |_| if (program.options.fast_text) { return out.print(".instant_text=true\n", .{}); } else { return error.DidNotConsumeData; }, .text_delays => |delay| if (program.options.fast_text) { const new_delay = switch (delay.index) { 0 => @as(usize, 2), 1 => @as(usize, 1), else => @as(usize, 0), }; return out.print(".text_delays[{}]={}\n", .{ delay.index, new_delay }); } else { return error.DidNotConsumeData; }, .pokemons => |pokemons| switch (pokemons.value) { .base_exp_yield => |yield| if (program.options.exp_scale != 1.0) { const new_yield_float = math.floor(@intToFloat(f64, yield) * program.options.exp_scale); const new_yield = @floatToInt(u16, new_yield_float); return out.print(".pokemons[{}].base_exp_yield={}\n", .{ pokemons.index, new_yield, }); } else { return error.DidNotConsumeData; }, .hms => |hm| return out.print(".pokemons[{}].hms[{}]={}\n", .{ pokemons.index, hm.index, hm.value or program.options.easy_hms, }), .stats, .types, .catch_rate, .ev_yield, .items, .gender_ratio, .egg_cycles, .base_friendship, .growth_rate, .egg_groups, .abilities, .color, .evos, .moves, .tms, .name, .pokedex_entry, => return error.DidNotConsumeData, }, .maps => |maps| { switch (maps.value) { .allow_cycling, .allow_running => { const allow = if (maps.value == .allow_running) program.options.running else program.options.biking; if (allow == .unchanged) return error.DidNotConsumeData; return out.print(".maps[{}].{s}={}\n", .{ maps.index, @tagName(maps.value), allow == .everywhere, }); }, .music, .cave, .weather, .type, .escape_rope, .battle_scene, .allow_escaping, .show_map_name, => return error.DidNotConsumeData, } }, .trainers => |trainers| switch (trainers.value) { .party => |party| switch (party.value) { .level => |level| if (program.options.trainer_scale != 1.0) { const new_level_float = math.floor(@intToFloat(f64, level) * program.options.trainer_scale); const new_level = @floatToInt(u8, math.min(new_level_float, 100)); return out.print(".trainers[{}].party[{}].level={}\n", .{ trainers.index, party.index, new_level, }); } else { return error.DidNotConsumeData; }, .ability, .species, .item, .moves, => return error.DidNotConsumeData, }, .class, .encounter_music, .trainer_picture, .name, .items, .party_type, .party_size, => return error.DidNotConsumeData, }, .wild_pokemons => |wild_areas| { const wild_area = wild_areas.value.value(); switch (wild_area) { .pokemons => |pokemons| switch (pokemons.value) { .min_level, .max_level => |level| if (program.options.wild_scale != 1.0) { const new_level_float = math.floor(@intToFloat(f64, level) * program.options.wild_scale); const new_level = @floatToInt(u8, math.min(new_level_float, 100)); return out.print(".wild_pokemons[{}].{s}.pokemons[{}].{s}={}\n", .{ wild_areas.index, @tagName(wild_areas.value), pokemons.index, @tagName(pokemons.value), new_level, }); } else { return error.DidNotConsumeData; }, .species => return error.DidNotConsumeData, }, .encounter_rate => return error.DidNotConsumeData, } }, .static_pokemons => |pokemons| switch (pokemons.value) { .level => |level| if (program.options.static_scale != 1.0) { const new_level_float = math.floor( @intToFloat(f64, level) * program.options.static_scale, ); const new_level = @floatToInt(u8, math.min(new_level_float, 100)); return out.print(".static_pokemons[{}].level={}\n", .{ pokemons.index, new_level }); } else { return error.DidNotConsumeData; }, .species => return error.DidNotConsumeData, }, .version, .game_title, .gamecode, .starters, .moves, .abilities, .types, .tms, .hms, .items, .pokedex, .given_pokemons, .pokeball_items, .hidden_hollows, .text, => return error.DidNotConsumeData, } unreachable; } test { const Pattern = util.testing.Pattern; const test_input = try util.testing.filter(util.testing.test_case, &.{ ".maps[*].allow_*=*", ".instant_text=*", ".text_delays[*]=*", ".static_pokemons[*].level=*", ".trainers[*].party[*].level=*", ".wild_pokemons[*].*.pokemons[*].*_level=*", ".pokemons[*].base_exp_yield=*", ".pokemons[*].hms[*]=*", }); defer testing.allocator.free(test_input); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--allow-biking=unchanged"}, .patterns = &[_]Pattern{ Pattern.string(165, 165, "].allow_cycling=true\n"), Pattern.string(353, 353, "].allow_cycling=false\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--allow-biking=everywhere"}, .patterns = &[_]Pattern{ Pattern.string(518, 518, "].allow_cycling=true\n"), Pattern.string(000, 000, "].allow_cycling=false\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--allow-biking=nowhere"}, .patterns = &[_]Pattern{ Pattern.string(000, 000, "].allow_cycling=true\n"), Pattern.string(518, 518, "].allow_cycling=false\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--allow-running=unchanged"}, .patterns = &[_]Pattern{ Pattern.string(228, 228, "].allow_running=true\n"), Pattern.string(290, 290, "].allow_running=false\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--allow-running=everywhere"}, .patterns = &[_]Pattern{ Pattern.string(518, 518, "].allow_running=true\n"), Pattern.string(000, 000, "].allow_running=false\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--allow-running=nowhere"}, .patterns = &[_]Pattern{ Pattern.string(000, 000, "].allow_running=true\n"), Pattern.string(518, 518, "].allow_running=false\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--fast-text"}, .patterns = &[_]Pattern{ Pattern.string(1, 1, ".instant_text=true\n"), Pattern.string(1, 1, ".text_delays[0]=2\n"), Pattern.string(1, 1, ".text_delays[1]=1\n"), Pattern.string(1, 1, ".text_delays[2]=0\n"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--static-level-scaling=1.0"}, .patterns = &[_]Pattern{ Pattern.glob(4, 4, ".static_pokemons[*].level=70"), Pattern.glob(3, 3, ".static_pokemons[*].level=68"), Pattern.glob(10, 10, ".static_pokemons[*].level=65"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--static-level-scaling=0.5"}, .patterns = &[_]Pattern{ Pattern.glob(4, 4, ".static_pokemons[*].level=35"), Pattern.glob(3, 3, ".static_pokemons[*].level=34"), Pattern.glob(10, 10, ".static_pokemons[*].level=32"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--trainer-level-scaling=1.0"}, .patterns = &[_]Pattern{ Pattern.glob(11, 11, ".trainers[*].party[*].level=20"), Pattern.glob(16, 16, ".trainers[*].party[*].level=40"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--trainer-level-scaling=2.0"}, .patterns = &[_]Pattern{ Pattern.glob(11, 11, ".trainers[*].party[*].level=40"), Pattern.glob(16, 16, ".trainers[*].party[*].level=80"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--wild-level-scaling=1.0"}, .patterns = &[_]Pattern{ Pattern.glob(97, 97, ".wild_pokemons[*].*.pokemons[*].min_level=10"), Pattern.glob(37, 37, ".wild_pokemons[*].*.pokemons[*].max_level=10"), Pattern.glob(09, 09, ".wild_pokemons[*].*.pokemons[*].min_level=20"), Pattern.glob(44, 44, ".wild_pokemons[*].*.pokemons[*].max_level=20"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--wild-level-scaling=2.0"}, .patterns = &[_]Pattern{ Pattern.glob(97, 97, ".wild_pokemons[*].*.pokemons[*].min_level=20"), Pattern.glob(37, 37, ".wild_pokemons[*].*.pokemons[*].max_level=20"), Pattern.glob(09, 09, ".wild_pokemons[*].*.pokemons[*].min_level=40"), Pattern.glob(44, 44, ".wild_pokemons[*].*.pokemons[*].max_level=40"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--exp-yield-scaling=1.0"}, .patterns = &[_]Pattern{ Pattern.glob(06, 06, ".pokemons[*].base_exp_yield=50"), Pattern.glob(20, 20, ".pokemons[*].base_exp_yield=60"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--exp-yield-scaling=2.0"}, .patterns = &[_]Pattern{ Pattern.glob(06, 06, ".pokemons[*].base_exp_yield=100"), Pattern.glob(20, 20, ".pokemons[*].base_exp_yield=120"), }, }); try util.testing.runProgramFindPatterns(Program, .{ .in = test_input, .args = &[_][]const u8{"--easy-hms"}, .patterns = &[_]Pattern{ Pattern.glob(0, 0, ".pokemons[*].hms[*]=false"), }, }); }
src/other/tm35-misc.zig
const math = @import("std").math; fn StripComptime(comptime T: type) type { return switch (T) { comptime_float => f64, comptime_int => f64, else => T, }; } fn hasMethod(comptime T: type, comptime name: []const u8) bool { return @typeInfo(T) == .Struct and @hasDecl(T, name); } pub fn gmath(comptime T: type) type { return struct { pub const pi: T = 3.14159265358979323; pub const invPi: T = 0.31830988618379067; pub const tau: T = 6.28318530717958647; pub const invTau: T = 0.15915494309189534; pub const phi: T = 1.61803398874989484; pub const invPhi: T = 0.61803398874989484; pub const sqrt2: T = 1.41421356237309504; pub const invSqrt2: T = 0.70710678118654752; pub const sqrt3: T = 1.73205080756887729; pub const halfSqrt3: T = 0.86602540378443865; pub const almostOne = 1.0 - math.epsilon(T); pub fn sq(x: T) T { return x * x; } pub fn pow3(x: T) T { return x * x * x; } pub fn pow4(x: T) T { const xx = x * x; return xx * xx; } pub fn pow5(x: T) T { const xx = x * x; return xx * xx * x; } pub fn pow6(x: T) T { const xx = x * x; return xx * xx * xx; } pub fn pow8(x: T) T { const xx = x * x; const xxxx = xx * xx; return xxxx * xxxx; } pub fn pow16(x: T) T { const xx = x * x; const xxxx = xx * xx; const xxxxxxxx = xxxx * xxxx; return xxxxxxxx * xxxxxxxx; } pub fn coSq(x: T) T { return 1 - (1 - x) * (1 - x); } pub fn coSqN(x: T, n: usize) T { var y = 1 - x; var i = n; while (i != 0) : (i -= 1) { y *= y; } return 1 - y; } pub fn sqrt01Approx(x: T) T { //const a = mix(0.1 * math.e, 1, x); //const b = coMix(-a, 1, x); //const y = (1 + a) - a / b; const fma1 = x * 0.72817181715409548 + 0.27182818284590452; const fma2 = x * 0.72817181715409548 + 1.27182818284590452; const fma3 = x * -0.72817181715409548 + -0.27182818284590452; const div1 = x / fma2; const div2 = fma1 / fma2; const add1 = div1 + div2; const div3 = fma3 / add1; const add2 = fma2 + div3; const y = add2; return y; } pub fn parabola(x: anytype) T { return 4 * x * (1 - x); } /// First derivative is 0 at 0 and 1. pub fn sigmoidC1(x: anytype) T { return x * x * mix(3, 1, x); } /// First and second derivatives are 0 at 0 and 1. pub fn sigmoidC2(x: anytype) T { return x * x * x * (x * (x * 6 - 15) + 10); } /// First, second and third derivatives are 0 at 0 and 1. pub fn sigmoidC3(x: anytype) T { const xx = x * x; return xx * xx * (x * (-20 * xx + 70 * x - 84) + 35); } pub fn fract(x: T) T { return @mod(x, 1); } pub fn quantize(quantum: anytype, x: anytype) T { return @trunc(x / quantum) * quantum; } pub fn clamp(e0: anytype, e1: anytype, x: anytype) T { return if (x < e0) e0 else if (x > e1) e1 else x; } pub fn bump(e0: anytype, e1: anytype, x: anytype) T { return if (x < e0 or x > e1) 0 else parabola(coMix(e0, e1, x)); } pub fn saturate(x: anytype) T { return clamp(0, almostOne, x); } pub fn length1(x: T) T { return math.fabs(x); } pub fn length2(x: T, y: T) T { return math.hypot(T, x, y); } pub fn length2sq(x: anytype, y: anytype) T { return x * x + y * y; } pub fn coLength1(x: anytype) T { return 1 - math.fabs(x); } pub fn coLength2(x: T, y: T) T { return 1 - math.hypot(x, y); } pub fn fma(m: anytype, a: anytype, in: anytype) T { return in * m + a; } pub fn pow(x: anytype, a: anytype) T { return math.pow(T, x, a); } pub fn copysign(x: anytype, s: anytype) T { return math.copysign(T, x, s); } pub fn powCopySign(x: anytype, a: anytype) T { return copysign(pow(x, a), x); } pub fn fmapow(m: anytype, a: anytype, p: anytype, in: anytype) T { return powCopySign(fma(m, a, in), p); } pub fn mix_(lowOut: anytype, highOut: anytype, in: anytype) T { return fma(highOut - lowOut, lowOut, in); } fn comptimeFloat(comptime x: anytype) comptime_float { comptime { return switch (@TypeOf(x)) { comptime_float => x, comptime_int => @intToFloat(T, x), else => @compileError("comptimeFloat not implemented for " ++ @typeName(T)), }; } } pub fn coMix_(lowIn: anytype, highIn: anytype, in: anytype) T { if ((@TypeOf(lowIn) == comptime_float or @TypeOf(lowIn) == comptime_int) and (@TypeOf(highIn) == comptime_float or @TypeOf(highIn) == comptime_int)) { const m = 1.0 / (comptimeFloat(highIn) - comptimeFloat(lowIn)); return fma(m, -comptimeFloat(lowIn) * m, in); } else { return (in - lowIn) / (highIn - lowIn); // Divide and two subtractions. } } pub fn mix(a: anytype, b: anytype, x: f64) StripComptime(@TypeOf(a)) { const A = @TypeOf(a); return if (comptime hasMethod(A, "mix")) A.mix(a, b, x) else mix_(a, b, x); } pub fn coMix(a: anytype, b: anytype, x: f64) StripComptime(@TypeOf(a)) { const A = @TypeOf(a); return if (comptime hasMethod(A, "coMix")) A.coMix(a, b, x) else coMix_(a, b, x); } pub fn map(a: anytype, b: anytype, c: anytype, d: anytype, x: f64) StripComptime(@TypeOf(a)) { return mix(c, d, coMix(a, b, x)); } pub fn step(in: anytype, edge: anytype) T { if (in < edge) { return 0; } else { return 1; } } pub fn coStep(in: anytype, edge: anytype) T { if (in >= edge) { return 0; } else { return 1; } } pub fn linearstep(e0: anytype, e1: anytype, x: anytype) T { return saturate(coMix(e0, e1, x)); } pub fn sqstep(e0: anytype, e1: anytype, x: anytype) T { return sq(linearstep(e0, e1, x)); } pub fn cosqstep(e0: anytype, e1: anytype, x: anytype) T { return coSq(linearstep(e0, e1, x)); } pub fn smoothstepC1(e0: anytype, e1: anytype, x: anytype) T { return sigmoidC1(linearstep(e0, e1, x)); } pub fn smoothstepC2(e0: anytype, e1: anytype, x: anytype) T { return sigmoidC2(linearstep(e0, e1, x)); } pub fn smoothstepC3(e0: anytype, e1: anytype, x: anytype) T { return sigmoidC3(linearstep(e0, e1, x)); } pub fn logstep(e0: anytype, e1: anytype, x: anytype) T { return linearstep(0, log1p(e1 - e0), log1p(math.max(0, x - e0))); } pub fn logStrengthstep(e0: anytype, e1: anytype, strength: anytype, x: anytype) T { const linear = linearstep(e0, e1, x); if (strength <= 1e-5) { return linear; } else { return log1p(linear * strength) / log1p(strength); } } pub fn sigmoidSkew(strength: anytype, skew: anytype, in: anytype) T { const skewed = mix(sq(in), coSq(in), skew); const sCurved = smoothstepC3(0, 1, skewed); const dampened = mix(in, sCurved, strength); return dampened; } // Adds a filmic curve and input range on top of liftGammaGain. // defaults: mapDynamicRange(0, 1, 0, 1, 1, 0, 0.5, x) // (in-range, out-range, power, linear/s-curve, s-curve-skew) pub fn mapDynamicRange(lowIn: anytype, highIn: anytype, lowOut: anytype, highOut: anytype, power: anytype, sCurveStrength: anytype, sCurveSkew: anytype, in: anytype) T { const inputRanged = linearstep(lowIn, highIn, in); const gammaed = pow(inputRanged, power); const sCurved = sigmoidSkew(sCurveStrength, sCurveSkew, gammaed); const outputRanged = mix(lowOut, highOut, sCurved); return outputRanged; } // Adds a filmic curve and input range on top of liftGammaGain. // defaults: mapDynamicRange(0, 1, 0, 1, 1, 0, 0.5, x) // (in-range, out-range, power, linear/s-curve, s-curve-skew) pub fn mapDynamicRangeLog(lowIn: anytype, highIn: anytype, lowOut: anytype, highOut: anytype, power: anytype, sCurveStrength: anytype, sCurveSkew: anytype, in: anytype) T { const inputRanged = linearstep(lowIn, highIn, in); const logged = math.log1p(inputRanged); const gammaed = pow(logged, power); const sCurved = sigmoidSkew(sCurveStrength, sCurveSkew, gammaed); const outputRanged = mix(lowOut, highOut, sCurved); return outputRanged; } pub fn filmicDynamicRange(blackPoint: anytype, whitePoint: anytype, sCurveStrength: anytype, sCurveSkew: anytype, in: anytype) T { return sigmoidSkew(sCurveStrength, sCurveSkew, logstep(blackPoint, whitePoint, in)); } pub fn log1p(x: anytype) T { return switch (@TypeOf(x)) { comptime_int, comptime_float => comptime math.log1p(@as(T, x)), else => math.log1p(x), }; } pub fn expm1(x: anytype) T { return switch (@TypeOf(x)) { comptime_int, comptime_float => comptime math.expm1(@as(T, x)), else => math.expm1(x), }; } // https://lowepost.com/resources/colortheory/cdl-r9/ // ASC-CDL: https://blender.stackexchange.com/questions/55231/what-is-the-the-asc-cdl-node pub fn slopeOffsetPower(slope: anytype, offset: anytype, power: anytype, x: anytype) T { return fmapow(slope, offset, power, x); } // Different characterisation of slopeOffsetPower. pub fn mixPow(low: anytype, high: anytype, power: anytype, x: anytype) T { return powCopySign(mix(low, high, x), power); } // Different characterisation of slopeOffsetPower. pub fn coMixPow(low: anytype, high: anytype, power: anytype, x: anytype) T { return powCopySign(coMix(low, high, in), power); } pub fn powMix(power: anytype, lowOut: anytype, highOut: anytype, in: anytype) T { return mix(lowOut, highOut, powCopySign(in, power)); } // http://filmicworlds.com/blog/minimal-color-grading-tools/ // Use slopeOffsetPower instead. pub fn liftGammaGain(lift: anytype, gamma: anytype, gain: anytype, x: anytype) T { return powMix(gamma, lift, gain, x); } /// https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/ pub fn tonemapAces(j: T) T { // j⋅(2.51⋅j + 0.03) // ──────────────────────── // j⋅(2.43⋅j + 0.59) + 0.14 return j * (2.51 * j + 0.03) / (j * (j * 2.43 + 0.59) + 0.14); } pub fn rrtAndOdtFit(j: T) T { // j⋅(j + 0.0245786) - 9.0537e-5 // ──────────────────────────────────── // j⋅(0.983729⋅j + 0.432951) + 0.238081 return (j * (j + 0.0245786) - 9.0537e-5) / (j * (0.983729 * j + 0.432951) + 0.238081); } /// https://www.iquilezles.org/www/articles/functions/functions.htm pub fn almostIdentity(y0: T, xc: T, x: T) T { if (x > xc) { return x; } else { const t = x / xc; return (t * (2 * y0 + xc) + (2 * xc - 3 * y0)) * t * t + y0; } } pub const Fma = struct { const Self = @This(); m: T, a: T, pub inline fn apply(self: Self, x: T) T { return x * self.m + self.a; } pub fn mix(lowOut: anytype, highOut: anytype) Self { return .{ .m = highOut - lowOut, .a = lowOut }; } pub fn coMix(lowIn: anytype, highIn: anytype) Self { const m = 1.0 / (highIn - lowIn); return .{ .m = m, .a = -lowIn * m }; } pub fn add(self: Self, x: T) Self { return .{ .m = self.m, .a = self.a + x }; } pub fn mul(self: Self, x: T) Self { return .{ .m = self.m * x, .a = self.a * x }; } pub fn neg(self: Self) Self { return .{ .m = -self.m, .a = -self.a }; } }; }; }
lib/gmath.zig
const std = @import("std"); const arrayIt = @import("arrayIterator.zig").iterator; const iterator = @import("iterator.zig").iterator; const enumerateIt = @import("enumerate.zig").iterator; const TypeId = @import("builtin").TypeId; const mem = std.mem; const Info = enum { Slice, Iterator, Other, }; pub fn hasIteratorMember(comptime objType: type) bool { comptime { if (@typeId(objType) != TypeId.Struct) { return false; } const count = @memberCount(objType); var i = 0; inline while (i < count) : (i += 1) { if (mem.eql(u8, @memberName(objType, i), "iterator")) { return true; } } return false; } } pub fn getType(comptime objType: type) type { comptime { switch (@typeInfo(objType)) { TypeId.Pointer => |pointer| { switch (pointer.size) { .One, .Many, .C => { return pointer.child; }, .Slice => { const BaseType = pointer.child; return iterator(BaseType, arrayIt(BaseType)); }, } }, TypeId.Struct => |structInfo| { if (!hasIteratorMember(objType)) { @compileError("No 'iterator' or 'Child' property found"); } const it_type = @TypeOf(objType.iterator); const return_type = it_type.next.ReturnType; return findTillNoChild(return_type); }, else => { @compileError("Can only use slices and structs have 'iterator' function, remember to convert arrays to slices."); }, } @compileError("No 'iterator' or 'Child' property found"); } } pub fn findTillNoChild(comptime Type: type) type { if (@typeId(Type) == TypeId.Nullable) { return findTillNoChild(Type.Child); } return Type; } pub fn initType(comptime objType: type, value: var) getType(objType) { comptime const it_type = getType(objType); switch (@typeInfo(objType)) { TypeId.Pointer => |pointer| { switch (pointer.size) { .Slice => { return it_type{ .nextIt = arrayIt(pointer.child).init(value) }; }, else => unreachable, } }, TypeId.Struct => { if (comptime !hasIteratorMember(objType)) { unreachable; } return it_type{ .nextIt = value.iterator() }; }, else => unreachable, } }
src/info.zig
const std = @import("std"); const io = std.io; const mem = std.mem; const zen = std.os.zen; const Message = zen.Message; const Server = zen.Server; const warn = std.debug.warn; //// // Entry point. // pub fn main() void { var stdin_file = io.getStdIn() catch unreachable; var stdin = &stdin_file.inStream().stream; var buffer: [1024]u8 = undefined; warn("\n"); while (true) { warn(">>> "); const len = readLine(stdin, buffer[0..]); execute(buffer[0..len]); } } //// // Execute a command. // // Arguments: // command: Command string. // fn execute(command: []u8) void { if (command.len == 0) { return; } else if (mem.eql(u8, command, "clear")) { clear(); } else if (mem.eql(u8, command, "version")) { version(); } else { help(); } } //// // Read a line from a stream into a buffer. // // Arguments: // stream: The stream to read from. // buffer: The buffer to write into. // // Returns: // The length of the line (excluding newline character). // fn readLine(stream: var, buffer: []u8) usize { // TODO: change the type of stream when #764 is fixed. var i: usize = 0; var char: u8 = 0; while (char != '\n') { char = stream.readByte() catch unreachable; if (char == 8) { // Backspace deletes the last character (if there's one). if (i > 0) { warn("{c}", char); i -= 1; } } else { // Save printable characters in the buffer. warn("{c}", char); buffer[i] = char; i += 1; } } return i - 1; // Exclude \n. } ////////////////////////// //// Shell commands //// ////////////////////////// fn clear() void { zen.send(&Message.to(Server.Terminal, 0)); } fn help() void { warn("{}\n\n", \\List of supported commands: \\ clear Clear the screen \\ help Show help message \\ version Show Zen version ); } fn version() void { warn("Zen v0.0.1\n\n"); }
servers/shell/main.zig
const std = @import("std"); const fs = std.fs; const io = std.io; const info = std.log.info; const print = std.debug.print; const fmt = std.fmt; const ArrayList = std.ArrayList; const utils = @import("utils.zig"); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const State = enum { active, inactive, }; const Coord = [3]isize; fn countActiveCubes(cubes: std.AutoHashMap(Coord, Cube)) usize { var res: usize = 0; var cubes_iter = cubes.iterator(); while (cubes_iter.next()) |cube| { if (cube.value.state == .active) { res += 1; } } return res; } const Cube = struct { x: isize, y: isize, z: isize, state: State, next_state: ?State = null, near_coords: ?[26]Coord = null, pub fn init(coord: Coord, state: State) Cube { return Cube{ .x = coord[0], .y = coord[1], .z = coord[2], .state = state, }; } pub fn getNearCoords(self: *Cube) [26]Coord { if (self.near_coords) |nc| { return nc; } const self_coords = Coord{ self.x, self.y, self.z }; var res = [_]Coord{undefined} ** 26; var i: usize = 0; var idx: usize = 0; while (i < 27) : (i += 1) { const ii = @intCast(isize, i); if (i == 13) { continue; } const cube_coords: Coord = .{ self.x + @mod(ii, 3) - 1, self.y + @mod(@divTrunc(ii, 3), 3) - 1, self.z + @divTrunc(ii, 9) - 1, }; res[idx] = cube_coords; idx += 1; } self.near_coords = res; return res; } pub fn calcNextState(self: *Cube, neighbors: std.AutoHashMap(Coord, Cube)) void { const neighbor_coords = self.getNearCoords(); var actives: usize = 0; for (neighbor_coords) |nc, i| { // active block must have all neighboring blocks const neighbor = neighbors.get(nc) orelse { if (self.state == .inactive) { continue; } else { unreachable; } }; if (neighbor.state == .active) { actives += 1; } } if (self.state == .active) { if (actives == 2 or actives == 3) { // remain active } else { self.next_state = .inactive; } } else { if (actives == 3) { self.next_state = .active; } } } pub fn commit(self: *Cube) void { if (self.next_state) |ns| { self.state = ns; self.next_state = null; } } }; pub fn main() !void { const begin = @divTrunc(std.time.nanoTimestamp(), 1000); // setup // defer _ = gpa.deinit(); var allo = &gpa.allocator; var lines: std.mem.TokenIterator = try utils.readInputLines(allo, "./input1"); defer allo.free(lines.buffer); var cubes = std.AutoHashMap([3]isize, Cube).init(allo); defer cubes.deinit(); // load initial cubes var y: isize = 0; while (lines.next()) |line| : (y += 1) { for (line) |char, _x| { const x = @intCast(isize, _x); if (char == '.') { continue; } const cube = Cube.init(.{ x, y, 0 }, .active); cubes.put(.{ x, y, 0 }, cube) catch unreachable; } } // do p1 var cycle: usize = 0; while (cycle < 6) : (cycle += 1) { // add all inactive neighoring cubes info("cycle: {} cubes: {}", .{ cycle, countActiveCubes(cubes) }); var new_cubes = ArrayList(Cube).init(allo); defer new_cubes.deinit(); var iter_cubes = cubes.iterator(); while (iter_cubes.next()) |cube| { if (cube.value.state == .inactive) { continue; } const near_coords = cube.value.getNearCoords(); for (near_coords) |near_coord| { if (cubes.get(near_coord)) |existing_cube| { continue; } // init all non-existant cubes as inactive const new_cube = Cube.init(near_coord, .inactive); new_cubes.append(new_cube) catch unreachable; } } for (new_cubes.items) |new_cube| { cubes.put(Coord{ new_cube.x, new_cube.y, new_cube.z, }, new_cube) catch unreachable; } iter_cubes = cubes.iterator(); while (iter_cubes.next()) |cube| { cube.value.calcNextState(cubes); } iter_cubes = cubes.iterator(); while (iter_cubes.next()) |cube| { cube.value.commit(); } } info("p1: {}", .{countActiveCubes(cubes)}); // end const delta = @divTrunc(std.time.nanoTimestamp(), 1000) - begin; print("all done in {} microseconds\n", .{delta}); }
day_17/src/main_p1.zig
const std = @import("std"); const mem = std.mem; const Numeric = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 188, hi: u21 = 194704, pub fn init(allocator: *mem.Allocator) !Numeric { var instance = Numeric{ .allocator = allocator, .array = try allocator.alloc(bool, 194517), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 2) : (index += 1) { instance.array[index] = true; } index = 2360; while (index <= 2365) : (index += 1) { instance.array[index] = true; } index = 2742; while (index <= 2747) : (index += 1) { instance.array[index] = true; } index = 2868; while (index <= 2870) : (index += 1) { instance.array[index] = true; } index = 3004; while (index <= 3010) : (index += 1) { instance.array[index] = true; } index = 3228; while (index <= 3234) : (index += 1) { instance.array[index] = true; } index = 3252; while (index <= 3260) : (index += 1) { instance.array[index] = true; } index = 3694; while (index <= 3703) : (index += 1) { instance.array[index] = true; } index = 4790; while (index <= 4800) : (index += 1) { instance.array[index] = true; } index = 5682; while (index <= 5684) : (index += 1) { instance.array[index] = true; } index = 5940; while (index <= 5949) : (index += 1) { instance.array[index] = true; } index = 8340; while (index <= 8355) : (index += 1) { instance.array[index] = true; } index = 8356; while (index <= 8390) : (index += 1) { instance.array[index] = true; } index = 8393; while (index <= 8396) : (index += 1) { instance.array[index] = true; } instance.array[8397] = true; index = 9133; while (index <= 9143) : (index += 1) { instance.array[index] = true; } index = 9153; while (index <= 9163) : (index += 1) { instance.array[index] = true; } index = 9173; while (index <= 9183) : (index += 1) { instance.array[index] = true; } index = 9263; while (index <= 9272) : (index += 1) { instance.array[index] = true; } instance.array[9282] = true; instance.array[9923] = true; instance.array[9933] = true; instance.array[9943] = true; instance.array[11329] = true; instance.array[12107] = true; index = 12133; while (index <= 12141) : (index += 1) { instance.array[index] = true; } index = 12156; while (index <= 12158) : (index += 1) { instance.array[index] = true; } index = 12502; while (index <= 12505) : (index += 1) { instance.array[index] = true; } index = 12644; while (index <= 12653) : (index += 1) { instance.array[index] = true; } index = 12684; while (index <= 12691) : (index += 1) { instance.array[index] = true; } index = 12693; while (index <= 12707) : (index += 1) { instance.array[index] = true; } index = 12740; while (index <= 12749) : (index += 1) { instance.array[index] = true; } index = 12789; while (index <= 12803) : (index += 1) { instance.array[index] = true; } instance.array[13129] = true; instance.array[13255] = true; instance.array[14190] = true; instance.array[14993] = true; instance.array[19780] = true; instance.array[19783] = true; instance.array[19787] = true; instance.array[19789] = true; instance.array[19873] = true; instance.array[19920] = true; instance.array[19928] = true; instance.array[19930] = true; index = 19971; while (index <= 19972) : (index += 1) { instance.array[index] = true; } instance.array[20003] = true; instance.array[20012] = true; instance.array[20049] = true; instance.array[20148] = true; instance.array[20552] = true; instance.array[20618] = true; instance.array[20653] = true; instance.array[20655] = true; instance.array[20657] = true; instance.array[21125] = true; index = 21127; while (index <= 21129) : (index += 1) { instance.array[index] = true; } instance.array[21136] = true; index = 21253; while (index <= 21256) : (index += 1) { instance.array[index] = true; } instance.array[22047] = true; instance.array[22581] = true; instance.array[22589] = true; instance.array[23998] = true; index = 24130; while (index <= 24131) : (index += 1) { instance.array[index] = true; } index = 24144; while (index <= 24146) : (index += 1) { instance.array[index] = true; } instance.array[24148] = true; instance.array[25154] = true; instance.array[25232] = true; instance.array[26390] = true; instance.array[28234] = true; instance.array[29402] = true; instance.array[30146] = true; instance.array[32714] = true; instance.array[33648] = true; instance.array[35826] = true; instance.array[35831] = true; instance.array[35956] = true; instance.array[38245] = true; instance.array[38282] = true; instance.array[38288] = true; instance.array[38332] = true; instance.array[38458] = true; index = 42538; while (index <= 42547) : (index += 1) { instance.array[index] = true; } index = 42868; while (index <= 42873) : (index += 1) { instance.array[index] = true; } instance.array[63663] = true; instance.array[63671] = true; instance.array[63676] = true; instance.array[63734] = true; instance.array[63765] = true; instance.array[63767] = true; instance.array[63809] = true; index = 65611; while (index <= 65655) : (index += 1) { instance.array[index] = true; } index = 65668; while (index <= 65720) : (index += 1) { instance.array[index] = true; } index = 65721; while (index <= 65724) : (index += 1) { instance.array[index] = true; } index = 65742; while (index <= 65743) : (index += 1) { instance.array[index] = true; } index = 66085; while (index <= 66111) : (index += 1) { instance.array[index] = true; } index = 66148; while (index <= 66151) : (index += 1) { instance.array[index] = true; } instance.array[66181] = true; instance.array[66190] = true; index = 66325; while (index <= 66329) : (index += 1) { instance.array[index] = true; } index = 67484; while (index <= 67491) : (index += 1) { instance.array[index] = true; } index = 67517; while (index <= 67523) : (index += 1) { instance.array[index] = true; } index = 67563; while (index <= 67571) : (index += 1) { instance.array[index] = true; } index = 67647; while (index <= 67651) : (index += 1) { instance.array[index] = true; } index = 67674; while (index <= 67679) : (index += 1) { instance.array[index] = true; } index = 67840; while (index <= 67841) : (index += 1) { instance.array[index] = true; } index = 67844; while (index <= 67859) : (index += 1) { instance.array[index] = true; } index = 67862; while (index <= 67907) : (index += 1) { instance.array[index] = true; } index = 67976; while (index <= 67980) : (index += 1) { instance.array[index] = true; } index = 68033; while (index <= 68034) : (index += 1) { instance.array[index] = true; } index = 68065; while (index <= 68067) : (index += 1) { instance.array[index] = true; } index = 68143; while (index <= 68147) : (index += 1) { instance.array[index] = true; } index = 68252; while (index <= 68259) : (index += 1) { instance.array[index] = true; } index = 68284; while (index <= 68291) : (index += 1) { instance.array[index] = true; } index = 68333; while (index <= 68339) : (index += 1) { instance.array[index] = true; } index = 68670; while (index <= 68675) : (index += 1) { instance.array[index] = true; } index = 69037; while (index <= 69058) : (index += 1) { instance.array[index] = true; } index = 69217; while (index <= 69226) : (index += 1) { instance.array[index] = true; } index = 69269; while (index <= 69272) : (index += 1) { instance.array[index] = true; } index = 69385; while (index <= 69391) : (index += 1) { instance.array[index] = true; } index = 69535; while (index <= 69545) : (index += 1) { instance.array[index] = true; } index = 69925; while (index <= 69944) : (index += 1) { instance.array[index] = true; } index = 71294; while (index <= 71295) : (index += 1) { instance.array[index] = true; } index = 71726; while (index <= 71734) : (index += 1) { instance.array[index] = true; } index = 72606; while (index <= 72624) : (index += 1) { instance.array[index] = true; } index = 73476; while (index <= 73496) : (index += 1) { instance.array[index] = true; } index = 74564; while (index <= 74674) : (index += 1) { instance.array[index] = true; } index = 92831; while (index <= 92837) : (index += 1) { instance.array[index] = true; } index = 93636; while (index <= 93658) : (index += 1) { instance.array[index] = true; } index = 119332; while (index <= 119351) : (index += 1) { instance.array[index] = true; } index = 119460; while (index <= 119484) : (index += 1) { instance.array[index] = true; } index = 124939; while (index <= 124947) : (index += 1) { instance.array[index] = true; } index = 125877; while (index <= 125935) : (index += 1) { instance.array[index] = true; } index = 125937; while (index <= 125939) : (index += 1) { instance.array[index] = true; } index = 125941; while (index <= 125944) : (index += 1) { instance.array[index] = true; } index = 126021; while (index <= 126065) : (index += 1) { instance.array[index] = true; } index = 126067; while (index <= 126081) : (index += 1) { instance.array[index] = true; } index = 127055; while (index <= 127056) : (index += 1) { instance.array[index] = true; } instance.array[130885] = true; instance.array[130984] = true; instance.array[131110] = true; instance.array[131173] = true; instance.array[133230] = true; instance.array[133319] = true; instance.array[133328] = true; instance.array[133344] = true; instance.array[133678] = true; instance.array[133697] = true; instance.array[133725] = true; instance.array[139988] = true; instance.array[141532] = true; instance.array[146015] = true; instance.array[156081] = true; instance.array[194516] = true; // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *Numeric) void { self.allocator.free(self.array); } // isNumeric checks if cp is of the kind Numeric. pub fn isNumeric(self: Numeric, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedNumericType/Numeric.zig
const std = @import("std"); const c = @cImport({ @cInclude("binding.h"); }); pub const PropertyAttribute = struct { pub const None = c.None; pub const ReadOnly = c.ReadOnly; }; // Currently, user callback functions passed into FunctionTemplate will need to have this declared as a param and then // converted to FunctionCallbackInfo to get a nicer interface. pub const C_FunctionCallbackInfo = c.FunctionCallbackInfo; pub const C_PropertyCallbackInfo = c.PropertyCallbackInfo; pub const C_WeakCallbackInfo = c.WeakCallbackInfo; pub const FunctionCallback = c.FunctionCallback; pub const AccessorNameGetterCallback = c.AccessorNameGetterCallback; pub const AccessorNameSetterCallback = c.AccessorNameSetterCallback; pub const Name = c.Name; pub const Platform = struct { const Self = @This(); handle: *c.Platform, /// Must be called first before initV8Platform and initV8 /// Returns a new instance of the default v8::Platform implementation. /// /// |thread_pool_size| is the number of worker threads to allocate for /// background jobs. If a value of zero is passed, a suitable default /// based on the current number of processors online will be chosen. /// If |idle_task_support| is enabled then the platform will accept idle /// tasks (IdleTasksEnabled will return true) and will rely on the embedder /// calling v8::platform::RunIdleTasks to process the idle tasks. pub fn initDefault(thread_pool_size: u32, idle_task_support: bool) Self { // Verify struct sizes. const assert = std.debug.assert; assert(@sizeOf(c.CreateParams) == c.v8__Isolate__CreateParams__SIZEOF()); assert(@sizeOf(c.TryCatch) == c.v8__TryCatch__SIZEOF()); return .{ .handle = c.v8__Platform__NewDefaultPlatform(@intCast(c_int, thread_pool_size), if (idle_task_support) 1 else 0).?, }; } pub fn deinit(self: Self) void { c.v8__Platform__DELETE(self.handle); } /// [V8] /// Pumps the message loop for the given isolate. /// /// The caller has to make sure that this is called from the right thread. /// Returns true if a task was executed, and false otherwise. If the call to /// PumpMessageLoop is nested within another call to PumpMessageLoop, only /// nestable tasks may run. Otherwise, any task may run. Unless requested through /// the |behavior| parameter, this call does not block if no task is pending. The /// |platform| has to be created using |NewDefaultPlatform|. pub fn pumpMessageLoop(self: Self, isolate: Isolate, wait_for_work: bool) bool { return c.v8__Platform__PumpMessageLoop(self.handle, isolate.handle, wait_for_work); } }; pub fn getVersion() []const u8 { const str = c.v8__V8__GetVersion(); const idx = std.mem.indexOfSentinel(u8, 0, str); return str[0..idx]; } pub fn initV8Platform(platform: Platform) void { c.v8__V8__InitializePlatform(platform.handle); } pub fn initV8() void { c.v8__V8__Initialize(); } pub fn deinitV8() bool { return c.v8__V8__Dispose() == 1; } pub fn deinitV8Platform() void { c.v8__V8__ShutdownPlatform(); } pub fn initCreateParams() c.CreateParams { var params: c.CreateParams = undefined; c.v8__Isolate__CreateParams__CONSTRUCT(&params); return params; } pub fn createDefaultArrayBufferAllocator() *c.ArrayBufferAllocator { return c.v8__ArrayBuffer__Allocator__NewDefaultAllocator().?; } pub fn destroyArrayBufferAllocator(alloc: *c.ArrayBufferAllocator) void { c.v8__ArrayBuffer__Allocator__DELETE(alloc); } pub const Exception = struct { pub fn initError(msg: String) Value { return .{ .handle = c.v8__Exception__Error(msg.handle).?, }; } }; pub const Isolate = struct { const Self = @This(); handle: *c.Isolate, pub fn init(params: *const c.CreateParams) Self { const ptr = @intToPtr(*c.CreateParams, @ptrToInt(params)); return .{ .handle = c.v8__Isolate__New(ptr).?, }; } /// [V8] /// Disposes the isolate. The isolate must not be entered by any /// thread to be disposable. pub fn deinit(self: Self) void { c.v8__Isolate__Dispose(self.handle); } /// [V8] /// Sets this isolate as the entered one for the current thread. /// Saves the previously entered one (if any), so that it can be /// restored when exiting. Re-entering an isolate is allowed. /// [Notes] /// This is equivalent to initing an Isolate Scope. pub fn enter(self: *Self) void { c.v8__Isolate__Enter(self.handle); } /// [V8] /// Exits this isolate by restoring the previously entered one in the /// current thread. The isolate may still stay the same, if it was /// entered more than once. /// /// Requires: this == Isolate::GetCurrent(). /// [Notes] /// This is equivalent to deiniting an Isolate Scope. pub fn exit(self: *Self) void { c.v8__Isolate__Exit(self.handle); } pub fn getCurrentContext(self: Self) Context { return .{ .handle = c.v8__Isolate__GetCurrentContext(self.handle).?, }; } /// It seems stack trace is only captured if the value is wrapped in an Exception.initError. pub fn throwException(self: Self, value: anytype) Value { return .{ .handle = c.v8__Isolate__ThrowException(self.handle, getValueHandle(value)).?, }; } }; pub const HandleScope = struct { const Self = @This(); inner: c.HandleScope, /// [Notes] /// This starts a new stack frame to record local objects created. pub fn init(self: *Self, isolate: Isolate) void { c.v8__HandleScope__CONSTRUCT(&self.inner, isolate.handle); } /// [Notes] /// This pops the scope frame and allows V8 to mark/free local objects created since HandleScope.init. /// In C++ code, this would happen automatically when the HandleScope var leaves the current scope. pub fn deinit(self: *Self) void { c.v8__HandleScope__DESTRUCT(&self.inner); } }; pub const Context = struct { const Self = @This(); handle: *const c.Context, /// [V8] /// Creates a new context and returns a handle to the newly allocated /// context. /// /// \param isolate The isolate in which to create the context. /// /// \param extensions An optional extension configuration containing /// the extensions to be installed in the newly created context. /// /// \param global_template An optional object template from which the /// global object for the newly created context will be created. /// /// \param global_object An optional global object to be reused for /// the newly created context. This global object must have been /// created by a previous call to Context::New with the same global /// template. The state of the global object will be completely reset /// and only object identify will remain. pub fn init(isolate: Isolate, global_tmpl: ?ObjectTemplate, global_obj: ?*c.Value) Self { return .{ .handle = c.v8__Context__New(isolate.handle, if (global_tmpl != null) global_tmpl.?.handle else null, global_obj).?, }; } /// [V8] /// Enter this context. After entering a context, all code compiled /// and run is compiled and run in this context. If another context /// is already entered, this old context is saved so it can be /// restored when the new context is exited. pub fn enter(self: Self) void { c.v8__Context__Enter(self.handle); } /// [V8] /// Exit this context. Exiting the current context restores the /// context that was in place when entering the current context. pub fn exit(self: Self) void { c.v8__Context__Exit(self.handle); } /// [V8] /// Returns the isolate associated with a current context. pub fn getIsolate(self: Self) *Isolate { return c.v8__Context__GetIsolate(self); } pub fn getGlobal(self: Self) Object { return .{ .handle = c.v8__Context__Global(self.handle).?, }; } }; pub const PropertyCallbackInfo = struct { const Self = @This(); handle: *const c.PropertyCallbackInfo, pub fn initFromV8(val: ?*const c.PropertyCallbackInfo) Self { return .{ .handle = val.?, }; } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__PropertyCallbackInfo__GetIsolate(self.handle).?, }; } pub fn getReturnValue(self: Self) ReturnValue { var res: c.ReturnValue = undefined; c.v8__PropertyCallbackInfo__GetReturnValue(self.handle, &res); return .{ .inner = res, }; } pub fn getThis(self: Self) Object { return .{ .handle = c.v8__PropertyCallbackInfo__This(self.handle).?, }; } }; pub const WeakCallbackInfo = struct { const Self = @This(); handle: *const c.WeakCallbackInfo, pub fn initFromC(val: ?*const c.WeakCallbackInfo) Self { return .{ .handle = val.?, }; } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__WeakCallbackInfo__GetIsolate(self.handle).?, }; } pub fn getParameter(self: Self) *const anyopaque { return c.v8__WeakCallbackInfo__GetParameter(self.handle).?; } }; pub const FunctionCallbackInfo = struct { const Self = @This(); handle: *const c.FunctionCallbackInfo, pub fn initFromV8(val: ?*const c.FunctionCallbackInfo) Self { return .{ .handle = val.?, }; } pub fn length(self: Self) u32 { return @intCast(u32, c.v8__FunctionCallbackInfo__Length(self.handle)); } pub fn getIsolate(self: Self) Isolate { return .{ .handle = c.v8__FunctionCallbackInfo__GetIsolate(self.handle).?, }; } pub fn getArg(self: Self, i: u32) Value { return .{ .handle = c.v8__FunctionCallbackInfo__INDEX(self.handle, @intCast(c_int, i)).?, }; } pub fn getReturnValue(self: Self) ReturnValue { var res: c.ReturnValue = undefined; c.v8__FunctionCallbackInfo__GetReturnValue(self.handle, &res); return .{ .inner = res, }; } pub fn getThis(self: Self) Object { return .{ .handle = c.v8__FunctionCallbackInfo__This(self.handle).?, }; } }; pub const ReturnValue = struct { const Self = @This(); inner: c.ReturnValue, pub fn set(self: Self, value: anytype) void { c.v8__ReturnValue__Set(self.inner, getValueHandle(value)); } pub fn setValueHandle(self: Self, ptr: *const c.Value) void { c.v8__ReturnValue__Set(self.inner, ptr); } pub fn get(self: Self) Value { return .{ .handle = c.v8__ReturnValue__Get(self.inner).?, }; } }; pub const FunctionTemplate = struct { const Self = @This(); handle: *const c.FunctionTemplate, pub fn initDefault(isolate: Isolate) Self { return .{ .handle = c.v8__FunctionTemplate__New__DEFAULT(isolate.handle).?, }; } pub fn initCallback(isolate: Isolate, callback: c.FunctionCallback) Self { return .{ .handle = c.v8__FunctionTemplate__New__DEFAULT2(isolate.handle, callback).?, }; } /// This is typically used to set class fields. pub fn getInstanceTemplate(self: Self) ObjectTemplate { return .{ .handle = c.v8__FunctionTemplate__InstanceTemplate(self.handle).?, }; } /// This is typically used to set class methods. pub fn getPrototypeTemplate(self: Self) ObjectTemplate { return .{ .handle = c.v8__FunctionTemplate__PrototypeTemplate(self.handle).?, }; } /// There is only one unique function for a FunctionTemplate in a given context. /// The Function can then be used to invoke NewInstance which is equivalent to doing js "new". pub fn getFunction(self: Self, ctx: Context) Function { return .{ .handle = c.v8__FunctionTemplate__GetFunction(self.handle, ctx.handle).?, }; } /// Sets static property on the template. pub fn set(self: Self, key: anytype, value: anytype, attr: c.PropertyAttribute) void { c.v8__Template__Set(getTemplateHandle(self), getNameHandle(key), getDataHandle(value), attr); } pub fn setGetter(self: Self, name: anytype, getter: FunctionTemplate) void { c.v8__Template__SetAccessorProperty__DEFAULT(getTemplateHandle(self), getNameHandle(name), getter.handle); } pub fn setClassName(self: Self, name: String) void { c.v8__FunctionTemplate__SetClassName(self.handle, name.handle); } pub fn setReadOnlyPrototype(self: Self) void { c.v8__FunctionTemplate__ReadOnlyPrototype(self.handle); } }; pub const Function = struct { const Self = @This(); handle: *const c.Function, /// receiver_val is "this" in the function context. This is equivalent to calling fn.apply(receiver, args) in JS. /// Returns null if there was an error. pub fn call(self: Self, ctx: Context, receiver_val: anytype, args: []const Value) ?Value { const c_args = @ptrCast(?[*]const ?*anyopaque, args.ptr); if (c.v8__Function__Call(self.handle, ctx.handle, getValueHandle(receiver_val), @intCast(c_int, args.len), c_args)) |ret| { return Value{ .handle = ret, }; } else return null; } // Equavalent to js "new". pub fn initInstance(self: Self, ctx: Context, args: []const Value) ?Object { const c_args = @ptrCast(?[*]const ?*anyopaque, args.ptr); if (c.v8__Function__NewInstance(self.handle, ctx.handle, @intCast(c_int, args.len), c_args)) |ret| { return Object{ .handle = ret, }; } else return null; } pub fn toObject(self: Self) Object { return .{ .handle = @ptrCast(*const c.Object, self.handle), }; } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } /// Should only be called if you know the underlying type is a v8.Persistent. pub fn castToPersistent(self: Self) Persistent { return .{ .handle = self.handle, }; } }; pub const Persistent = struct { const Self = @This(); // The Persistent handle is just like other value handles for easy casting. // But when creating and operating on it, an indirect pointer is used to represent a c.Persistent struct (v8::Persistent<v8::Value> in C++). handle: *const anyopaque, /// A new value is created that references the original value. pub fn init(isolate: Isolate, value: anytype) Self { var handle: *anyopaque = undefined; c.v8__Persistent__New(isolate.handle, getValueHandle(value), @ptrCast(*c.Persistent, &handle)); return .{ .handle = handle, }; } pub fn deinit(self: *Self) void { c.v8__Persistent__Reset(@ptrCast(*c.Persistent, &self.handle)); } /// Should only be called if you know the underlying type is a v8.Function. pub fn castToFunction(self: Self) Function { return .{ .handle = @ptrCast(*const c.Function, self.handle), }; } /// Should only be called if you know the underlying type is a v8.Object. pub fn castToObject(self: Self) Object { return .{ .handle = @ptrCast(*const c.Object, self.handle), }; } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } pub fn setWeak(self: *Self) void { c.v8__Persistent__SetWeak(@ptrCast(*c.Persistent, &self.handle)); } pub fn setWeakFinalizer(self: *Self, finalizer_ctx: *anyopaque, cb: c.WeakCallback, cb_type: c.WeakCallbackType) void { c.v8__Persistent__SetWeakFinalizer(@ptrCast(*c.Persistent, &self.handle), finalizer_ctx, cb, cb_type); } }; /// [V8] /// kParameter will pass a void* parameter back to the callback, kInternalFields /// will pass the first two internal fields back to the callback, kFinalizer /// will pass a void* parameter back, but is invoked before the object is /// actually collected, so it can be resurrected. In the last case, it is not /// possible to request a second pass callback. pub const WeakCallbackType = struct { pub const kParameter = c.kParameter; pub const kInternalFields = c.kInternalFields; pub const kFinalizer = c.kFinalizer; }; pub const ObjectTemplate = struct { const Self = @This(); handle: *const c.ObjectTemplate, pub fn initDefault(isolate: Isolate) Self { return .{ .handle = c.v8__ObjectTemplate__New__DEFAULT(isolate.handle).?, }; } pub fn init(isolate: Isolate, constructor: FunctionTemplate) Self { return .{ .handle = c.v8__ObjectTemplate__New(isolate.handle, constructor.handle).?, }; } pub fn initInstance(self: Self, ctx: Context) Object { return .{ .handle = c.v8__ObjectTemplate__NewInstance(self.handle, ctx.handle).?, }; } pub fn setGetter(self: Self, name: anytype, getter: c.AccessorNameGetterCallback) void { c.v8__ObjectTemplate__SetAccessor__DEFAULT(self.handle, getNameHandle(name), getter); } pub fn setGetterAndSetter(self: Self, name: anytype, getter: c.AccessorNameGetterCallback, setter: c.AccessorNameSetterCallback) void { c.v8__ObjectTemplate__SetAccessor__DEFAULT2(self.handle, getNameHandle(name), getter, setter); } pub fn set(self: Self, key: anytype, value: anytype, attr: c.PropertyAttribute) void { c.v8__Template__Set(getTemplateHandle(self), getNameHandle(key), getDataHandle(value), attr); } pub fn setInternalFieldCount(self: Self, count: u32) void { c.v8__ObjectTemplate__SetInternalFieldCount(self.handle, @intCast(c_int, count)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const Array = struct { const Self = @This(); handle: *const c.Array, pub fn length(self: Self) u32 { return c.v8__Array__Length(self.handle); } }; pub const Object = struct { const Self = @This(); handle: *const c.Object, pub fn init(isolate: Isolate) Self { return .{ .handle = c.v8__Object__New(isolate.handle).?, }; } pub fn setInternalField(self: Self, idx: u32, value: anytype) void { c.v8__Object__SetInternalField(self.handle, @intCast(c_int, idx), getValueHandle(value)); } pub fn getInternalField(self: Self, idx: u32) Value { return .{ .handle = c.v8__Object__GetInternalField(self.handle, @intCast(c_int, idx)).?, }; } // Returns true on success, false on fail. pub fn setValue(self: Self, ctx: Context, key: anytype, value: anytype) bool { var out: c.MaybeBool = undefined; c.v8__Object__Set(self.handle, ctx.handle, getValueHandle(key), getValueHandle(value), &out); // Set only returns empty for an error or true. return out.has_value == 1; } pub fn getValue(self: Self, ctx: Context, key: anytype) Value { return .{ .handle = c.v8__Object__Get(self.handle, ctx.handle, getValueHandle(key)).?, }; } pub fn getAtIndex(self: Self, ctx: Context, idx: u32) Value { return .{ .handle = c.v8__Object__GetIndex(self.handle, ctx.handle, idx).?, }; } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } pub fn defineOwnProperty(self: Self, ctx: Context, name: anytype, value: anytype, attr: c.PropertyAttribute) ?bool { var out: c.MaybeBool = undefined; c.v8__Object__DefineOwnProperty(self.handle, ctx.handle, getNameHandle(name), getValueHandle(value), attr, &out); if (out.has_value == 1) { return out.value == 1; } else return null; } }; pub const Number = struct { const Self = @This(); handle: *const c.Number, pub fn init(isolate: Isolate, val: f64) Self { return .{ .handle = c.v8__Number__New(isolate.handle, val).?, }; } pub fn initBitCastedU64(isolate: Isolate, val: u64) Self { return init(isolate, @bitCast(f64, val)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const Integer = struct { const Self = @This(); handle: *const c.Integer, pub fn initI32(isolate: Isolate, val: i32) Self { return .{ .handle = c.v8__Integer__New(isolate.handle, val).?, }; } pub fn initU32(isolate: Isolate, val: u32) Self { return .{ .handle = c.v8__Integer__NewFromUnsigned(isolate.handle, val).?, }; } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub inline fn getValue(val: anytype) Value { return .{ .handle = getValueHandle(val), }; } inline fn getValueHandle(val: anytype) *const c.Value { return @ptrCast(*const c.Value, comptime switch (@TypeOf(val)) { Object => val.handle, Value => val.handle, String => val.handle, Integer => val.handle, Primitive => val.handle, Number => val.handle, Function => val.handle, Persistent => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Value", .{@typeName(@TypeOf(val))})), }); } inline fn getNameHandle(val: anytype) *const c.Name { return @ptrCast(*const c.Name, comptime switch (@TypeOf(val)) { *const c.String => val, String => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Name", .{@typeName(@TypeOf(val))})), }); } inline fn getTemplateHandle(val: anytype) *const c.Template { return @ptrCast(*const c.Template, comptime switch (@TypeOf(val)) { FunctionTemplate => val.handle, ObjectTemplate => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Template", .{@typeName(@TypeOf(val))})), }); } inline fn getDataHandle(val: anytype) *const c.Data { return @ptrCast(*const c.Data, comptime switch (@TypeOf(val)) { FunctionTemplate => val.handle, ObjectTemplate => val.handle, Integer => val.handle, else => @compileError(std.fmt.comptimePrint("{s} is not a subtype of v8::Data", .{@typeName(@TypeOf(val))})), }); } pub const Message = struct { const Self = @This(); handle: *const c.Message, pub fn getSourceLine(self: Self, ctx: Context) ?String { if (c.v8__Message__GetSourceLine(self.handle, ctx.handle)) |string| { return String{ .handle = string, }; } else return null; } pub fn getScriptResourceName(self: Self) *const c.Value { return c.v8__Message__GetScriptResourceName(self.handle).?; } pub fn getLineNumber(self: Self, ctx: Context) ?u32 { const num = c.v8__Message__GetLineNumber(self.handle, ctx.handle); return if (num >= 0) @intCast(u32, num) else null; } pub fn getStartColumn(self: Self) u32 { return @intCast(u32, c.v8__Message__GetStartColumn(self.handle)); } pub fn getEndColumn(self: Self) u32 { return @intCast(u32, c.v8__Message__GetEndColumn(self.handle)); } }; pub const TryCatch = struct { const Self = @This(); inner: c.TryCatch, // TryCatch is wrapped in a v8::Local so have to initialize in place. pub fn init(self: *Self, isolate: Isolate) void { c.v8__TryCatch__CONSTRUCT(&self.inner, isolate.handle); } pub fn deinit(self: *Self) void { c.v8__TryCatch__DESTRUCT(&self.inner); } pub fn hasCaught(self: Self) bool { return c.v8__TryCatch__HasCaught(&self.inner); } pub fn getException(self: Self) Value { return .{ .handle = c.v8__TryCatch__Exception(&self.inner).?, }; } pub fn getStackTrace(self: Self, ctx: Context) ?Value { if (c.v8__TryCatch__StackTrace(&self.inner, ctx.handle)) |value| { return Value{ .handle = value, }; } else return null; } pub fn getMessage(self: Self) ?Message { if (c.v8__TryCatch__Message(&self.inner)) |message| { return Message{ .handle = message, }; } else { return null; } } }; pub const ScriptOrigin = struct { const Self = @This(); inner: c.ScriptOrigin, // ScriptOrigin is not wrapped in a v8::Local so we don't care if it points to another copy. pub fn initDefault(isolate: Isolate, resource_name: *const c.Value) Self { var inner: c.ScriptOrigin = undefined; c.v8__ScriptOrigin__CONSTRUCT(&inner, isolate.handle, resource_name); return .{ .inner = inner, }; } }; pub const Boolean = struct { const Self = @This(); handle: *const c.Boolean, pub fn init(isolate: Isolate, val: bool) Self { return .{ .handle = c.v8__Boolean__New(isolate.handle, val).?, }; } }; pub const String = struct { const Self = @This(); handle: *const c.String, pub fn initUtf8(isolate: Isolate, str: []const u8) Self { return .{ .handle = c.v8__String__NewFromUtf8(isolate.handle, str.ptr, c.kNormal, @intCast(c_int, str.len)).?, }; } pub fn lenUtf8(self: Self, isolate: Isolate) u32 { return @intCast(u32, c.v8__String__Utf8Length(self.handle, isolate.handle)); } pub fn writeUtf8(self: String, isolate: Isolate, buf: []const u8) u32 { const options = c.NO_NULL_TERMINATION | c.REPLACE_INVALID_UTF8; // num chars is how many utf8 characters are actually written and the function returns how many bytes were written. var nchars: c_int = 0; // TODO: Return num chars return @intCast(u32, c.v8__String__WriteUtf8(self.handle, isolate.handle, buf.ptr, @intCast(c_int, buf.len), &nchars, options)); } pub fn toValue(self: Self) Value { return .{ .handle = self.handle, }; } }; pub const Script = struct { const Self = @This(); handle: *const c.Script, /// Null indicates there was an compile error. pub fn compile(ctx: Context, src: String, origin: ?ScriptOrigin) ?Self { if (c.v8__Script__Compile(ctx.handle, src.handle, if (origin != null) &origin.?.inner else null)) |handle| { return Self{ .handle = handle, }; } else return null; } /// Null indicates a runtime error. pub fn run(self: Self, ctx: Context) ?Value { if (c.v8__Script__Run(self.handle, ctx.handle)) |value| { return Value{ .handle = value, }; } else return null; } }; pub const Value = struct { const Self = @This(); handle: *const c.Value, pub fn toString(self: Self, ctx: Context) String { return .{ .handle = c.v8__Value__ToString(self.handle, ctx.handle).?, }; } pub fn toBool(self: Self, isolate: Isolate) bool { return c.v8__Value__BooleanValue(self.handle, isolate.handle); } pub fn toU32(self: Self, ctx: Context) u32 { var out: c.MaybeU32 = undefined; c.v8__Value__Uint32Value(self.handle, ctx.handle, &out); if (out.has_value == 1) { return out.value; } else { return 0; } } pub fn toF32(self: Self, ctx: Context) f32 { var out: c.MaybeF64 = undefined; c.v8__Value__NumberValue(self.handle, ctx.handle, &out); if (out.has_value == 1) { return @floatCast(f32, out.value); } else { return 0; } } pub fn toF64(self: Self, ctx: Context) f64 { var out: c.MaybeF64 = undefined; c.v8__Value__NumberValue(self.handle, ctx.handle, &out); if (out.has_value == 1) { return out.value; } else { return 0; } } pub fn bitCastToU64(self: Self, ctx: Context) u64 { var out: c.MaybeF64 = undefined; c.v8__Value__NumberValue(self.handle, ctx.handle, &out); if (out.has_value == 1) { return @bitCast(u64, out.value); } else { return 0; } } pub fn instanceOf(self: Self, ctx: Context, obj: Object) bool { var out: c.MaybeBool = undefined; c.v8__Value__InstanceOf(self.handle, ctx.handle, obj.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return false; } pub fn isObject(self: Self) bool { return c.v8__Value__IsObject(self.handle); } pub fn isFunction(self: Self) bool { return c.v8__Value__IsFunction(self.handle); } pub fn isArray(self: Self) bool { return c.v8__Value__IsArray(self.handle); } /// Should only be called if you know the underlying type is a v8.Function. pub fn castToFunction(self: Self) Function { return .{ .handle = @ptrCast(*const c.Function, self.handle), }; } /// Should only be called if you know the underlying type is a v8.Object. pub fn castToObject(self: Self) Object { return .{ .handle = @ptrCast(*const c.Object, self.handle), }; } /// Should only be called if you know the underlying type is a v8.Array. pub fn castToArray(self: Self) Array { return .{ .handle = @ptrCast(*const c.Array, self.handle), }; } }; pub const Primitive = struct { const Self = @This(); handle: *const c.Primitive, }; pub fn initUndefined(isolate: Isolate) Primitive { return .{ .handle = c.v8__Undefined(isolate.handle).?, }; } pub fn initTrue(isolate: Isolate) Boolean { return .{ .handle = c.v8__True(isolate.handle).?, }; } pub fn initFalse(isolate: Isolate) Boolean { return .{ .handle = c.v8__False(isolate.handle).?, }; } pub const Promise = struct { const Self = @This(); handle: *const c.Promise, }; pub const PromiseResolver = struct { const Self = @This(); handle: *const c.PromiseResolver, pub fn init(ctx: Context) Self { return .{ .handle = c.v8__Promise__Resolver__New(ctx.handle).?, }; } pub fn getPromise(self: Self) Promise { return .{ .handle = c.v8__Promise__Resolver__GetPromise(self.handle).?, }; } pub fn resolve(self: Self, ctx: Context, val: Value) ?bool { var out: c.MaybeBool = undefined; c.v8__Promise__Resolver__Resolve(self.handle, ctx.handle, val.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return null; } pub fn reject(self: Self, ctx: Context, val: Value) ?bool { var out: c.MaybeBool = undefined; c.v8__Promise__Resolver__Resolve(self.handle, ctx.handle, val.handle, &out); if (out.has_value == 1) { return out.value == 1; } else return null; } };
src/v8.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const panic = std.debug.panic; const vk = @import("vulkan"); const InstanceDispatch = @import("instance.zig").InstanceDispatch; pub const Device = struct { const Self = @This(); allocator: *Allocator, pdevice: vk.PhysicalDevice, handle: vk.Device, dispatch: *DeviceDispatch, graphics_queue: vk.Queue, memory_properties: vk.PhysicalDeviceMemoryProperties, pub fn init( allocator: *Allocator, instance_dispatch: InstanceDispatch, pdevice: vk.PhysicalDevice, graphics_queue_index: u32, ) !Self { const required_device_extensions = [_][]const u8{vk.extension_info.khr_swapchain.name}; const props = instance_dispatch.getPhysicalDeviceProperties(pdevice); std.log.info("Device: \n\tName: {s}\n\tDriver: {}\n\tType: {}", .{ props.device_name, props.driver_version, props.device_type }); const priority = [_]f32{1}; const qci = [_]vk.DeviceQueueCreateInfo{ .{ .flags = .{}, .queue_family_index = graphics_queue_index, .queue_count = 1, .p_queue_priorities = &priority, }, }; var handle = try instance_dispatch.createDevice(pdevice, .{ .flags = .{}, .queue_create_info_count = 1, .p_queue_create_infos = &qci, .enabled_layer_count = 0, .pp_enabled_layer_names = undefined, .enabled_extension_count = required_device_extensions.len, .pp_enabled_extension_names = @ptrCast([*]const [*:0]const u8, &required_device_extensions), .p_enabled_features = null, }, null); var dispatch: *DeviceDispatch = try allocator.create(DeviceDispatch); dispatch.* = try DeviceDispatch.load(handle, instance_dispatch.dispatch.vkGetDeviceProcAddr); var graphics_queue = dispatch.getDeviceQueue(handle, graphics_queue_index, 0); var memory_properties = instance_dispatch.getPhysicalDeviceMemoryProperties(pdevice); return Self{ .allocator = allocator, .pdevice = pdevice, .handle = handle, .dispatch = dispatch, .graphics_queue = graphics_queue, .memory_properties = memory_properties, }; } pub fn deinit(self: *Self) void { self.dispatch.destroyDevice(self.handle, null); self.allocator.destroy(self.dispatch); } pub fn waitIdle(self: Self) void { self.dispatch.deviceWaitIdle(self.handle) catch panic("Failed to deviceWaitIdle", .{}); } pub fn endFrame(self: *Self) !void { var current_frame = &self.frames[self.frame_index]; self.dispatch.cmdEndRenderPass(current_frame.command_buffer); try self.dispatch.endCommandBuffer(current_frame.command_buffer); var wait_stages = vk.PipelineStageFlags{ .color_attachment_output_bit = true, }; const submitInfo = vk.SubmitInfo{ .wait_semaphore_count = 1, .p_wait_semaphores = @ptrCast([*]const vk.Semaphore, &current_frame.image_ready_semaphore), .p_wait_dst_stage_mask = @ptrCast([*]const vk.PipelineStageFlags, &wait_stages), .command_buffer_count = 1, .p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &current_frame.command_buffer), .signal_semaphore_count = 1, .p_signal_semaphores = @ptrCast([*]const vk.Semaphore, &current_frame.present_semaphore), }; try self.dispatch.queueSubmit(self.graphics_queue, 1, @ptrCast([*]const vk.SubmitInfo, &submitInfo), current_frame.frame_done_fence); _ = self.dispatch.queuePresentKHR(self.graphics_queue, .{ .wait_semaphore_count = 1, .p_wait_semaphores = @ptrCast([*]const vk.Semaphore, &current_frame.present_semaphore), .swapchain_count = 1, .p_swapchains = @ptrCast([*]const vk.SwapchainKHR, &self.swapchain.handle), .p_image_indices = @ptrCast([*]const u32, &self.swapchain_index), .p_results = null, }) catch |err| { switch (err) { error.OutOfDateKHR => { self.swapchain.invalid = true; }, else => return err, } }; self.frame_index = @rem(self.frame_index + 1, @intCast(u32, self.frames.len)); } //TODO: use VMA //TODO use VMA or alternative fn findMemoryTypeIndex(self: Self, memory_type_bits: u32, flags: vk.MemoryPropertyFlags) !u32 { for (self.memory_properties.memory_types[0..self.memory_properties.memory_type_count]) |memory_type, i| { if (memory_type_bits & (@as(u32, 1) << @truncate(u5, i)) != 0 and memory_type.property_flags.contains(flags)) { return @truncate(u32, i); } } return error.NoSuitableMemoryType; } //TODO: track memory allocations pub fn allocate_memory(self: Self, requirements: vk.MemoryRequirements, flags: vk.MemoryPropertyFlags) !vk.DeviceMemory { return try self.dispatch.allocateMemory(self.handle, .{ .allocation_size = requirements.size, .memory_type_index = try self.findMemoryTypeIndex(requirements.memory_type_bits, flags), }, null); } pub fn free_memory(self: Self, memory: vk.DeviceMemory) void { self.dispatch.freeMemory(self.handle, memory, null); } pub fn createPipeline( self: Self, pipeline_layout: vk.PipelineLayout, render_pass: vk.RenderPass, vert_code: []align(@alignOf(u32)) const u8, frag_code: []align(@alignOf(u32)) const u8, input_binding: *const vk.VertexInputBindingDescription, input_attributes: []const vk.VertexInputAttributeDescription, settings: *const PipelineState, ) !vk.Pipeline { const vert = try self.dispatch.createShaderModule(self.handle, .{ .flags = .{}, .code_size = vert_code.len, .p_code = std.mem.bytesAsSlice(u32, vert_code).ptr, }, null); defer self.dispatch.destroyShaderModule(self.handle, vert, null); const frag = try self.dispatch.createShaderModule(self.handle, .{ .flags = .{}, .code_size = frag_code.len, .p_code = std.mem.bytesAsSlice(u32, frag_code).ptr, }, null); defer self.dispatch.destroyShaderModule(self.handle, frag, null); const pssci = [_]vk.PipelineShaderStageCreateInfo{ .{ .flags = .{}, .stage = .{ .vertex_bit = true }, .module = vert, .p_name = "main", .p_specialization_info = null, }, .{ .flags = .{}, .stage = .{ .fragment_bit = true }, .module = frag, .p_name = "main", .p_specialization_info = null, }, }; const pvisci = vk.PipelineVertexInputStateCreateInfo{ .flags = .{}, .vertex_binding_description_count = 1, .p_vertex_binding_descriptions = @ptrCast([*]const vk.VertexInputBindingDescription, input_binding), .vertex_attribute_description_count = @intCast(u32, input_attributes.len), .p_vertex_attribute_descriptions = input_attributes.ptr, }; const piasci = vk.PipelineInputAssemblyStateCreateInfo{ .flags = .{}, .topology = .triangle_list, .primitive_restart_enable = vk.FALSE, }; const pvsci = vk.PipelineViewportStateCreateInfo{ .flags = .{}, .viewport_count = 1, .p_viewports = undefined, .scissor_count = 1, .p_scissors = undefined, }; const prsci = vk.PipelineRasterizationStateCreateInfo{ .flags = .{}, .depth_clamp_enable = vk.FALSE, .rasterizer_discard_enable = vk.FALSE, .polygon_mode = .fill, .cull_mode = settings.cull_mode, .front_face = .counter_clockwise, .depth_bias_enable = vk.FALSE, .depth_bias_constant_factor = 0, .depth_bias_clamp = 0, .depth_bias_slope_factor = 0, .line_width = 1, }; const pmsci = vk.PipelineMultisampleStateCreateInfo{ .flags = .{}, .rasterization_samples = .{ .@"1_bit" = true }, .sample_shading_enable = vk.FALSE, .min_sample_shading = 1, .p_sample_mask = null, .alpha_to_coverage_enable = vk.FALSE, .alpha_to_one_enable = vk.FALSE, }; var blend_enable: vk.Bool32 = vk.FALSE; if (settings.blend_enable) { blend_enable = vk.TRUE; } const pcbas = vk.PipelineColorBlendAttachmentState{ .blend_enable = vk.TRUE, .src_color_blend_factor = settings.src_color_blend_factor, .dst_color_blend_factor = settings.dst_color_blend_factor, .color_blend_op = settings.color_blend_op, .src_alpha_blend_factor = settings.src_alpha_blend_factor, .dst_alpha_blend_factor = settings.dst_alpha_blend_factor, .alpha_blend_op = settings.alpha_blend_op, .color_write_mask = .{ .r_bit = true, .g_bit = true, .b_bit = true, .a_bit = true }, }; const pcbsci = vk.PipelineColorBlendStateCreateInfo{ .flags = .{}, .logic_op_enable = vk.FALSE, .logic_op = .copy, .attachment_count = 1, .p_attachments = @ptrCast([*]const vk.PipelineColorBlendAttachmentState, &pcbas), .blend_constants = [_]f32{ 0, 0, 0, 0 }, }; const dynstate = [_]vk.DynamicState{ .viewport, .scissor }; const pdsci = vk.PipelineDynamicStateCreateInfo{ .flags = .{}, .dynamic_state_count = dynstate.len, .p_dynamic_states = &dynstate, }; //TODO: depth testing const gpci = vk.GraphicsPipelineCreateInfo{ .flags = .{}, .stage_count = 2, .p_stages = &pssci, .p_vertex_input_state = &pvisci, .p_input_assembly_state = &piasci, .p_tessellation_state = null, .p_viewport_state = &pvsci, .p_rasterization_state = &prsci, .p_multisample_state = &pmsci, .p_depth_stencil_state = null, .p_color_blend_state = &pcbsci, .p_dynamic_state = &pdsci, .layout = pipeline_layout, .render_pass = render_pass, .subpass = 0, .base_pipeline_handle = .null_handle, .base_pipeline_index = -1, }; var pipeline: vk.Pipeline = undefined; _ = try self.dispatch.createGraphicsPipelines( self.handle, .null_handle, 1, @ptrCast([*]const vk.GraphicsPipelineCreateInfo, &gpci), null, @ptrCast([*]vk.Pipeline, &pipeline), ); return pipeline; } }; pub const PipelineState = struct { cull_mode: vk.CullModeFlags = .{ .back_bit = true }, blend_enable: bool = false, src_color_blend_factor: vk.BlendFactor = .one, dst_color_blend_factor: vk.BlendFactor = .zero, color_blend_op: vk.BlendOp = .add, src_alpha_blend_factor: vk.BlendFactor = .one, dst_alpha_blend_factor: vk.BlendFactor = .zero, alpha_blend_op: vk.BlendOp = .add, }; //TODO Split wrappers by extension maybe? pub const DeviceDispatch = vk.DeviceWrapper(&.{ .acquireNextImageKHR, .allocateCommandBuffers, .allocateDescriptorSets, .allocateMemory, .beginCommandBuffer, .bindBufferMemory, .bindImageMemory, .cmdBeginRenderPass, .cmdBindDescriptorSets, .cmdBindIndexBuffer, .cmdBindPipeline, .cmdBindVertexBuffers, .cmdCopyBuffer, .cmdCopyBufferToImage, .cmdDraw, .cmdDrawIndexed, .cmdEndRenderPass, .cmdPipelineBarrier, .cmdPushConstants, .cmdSetScissor, .cmdSetViewport, .createBuffer, .createCommandPool, .createDescriptorPool, .createDescriptorSetLayout, .createFence, .createFramebuffer, .createGraphicsPipelines, .createImage, .createImageView, .createPipelineLayout, .createRenderPass, .createSampler, .createSemaphore, .createShaderModule, .createSwapchainKHR, .destroyBuffer, .destroyCommandPool, .destroyDescriptorPool, .destroyDescriptorSetLayout, .destroyFence, .destroyFramebuffer, .destroyImage, .destroyImageView, .destroyPipeline, .destroyPipelineLayout, .destroyRenderPass, .destroySampler, .destroySemaphore, .destroyShaderModule, .destroySwapchainKHR, .deviceWaitIdle, .endCommandBuffer, .freeCommandBuffers, .freeMemory, .getBufferMemoryRequirements, .getDeviceQueue, .getImageMemoryRequirements, .getSwapchainImagesKHR, .mapMemory, .queuePresentKHR, .queueSubmit, .queueWaitIdle, .resetFences, .unmapMemory, .updateDescriptorSets, .waitForFences, .destroyDevice, });
src/vulkan/device.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { _ = b; //const tests = b.addTest("src/zbullet.zig"); //const zmath = std.build.Pkg{ // .name = "zmath", // .path = .{ .path = thisDir() ++ "/../zmath/zmath.zig" }, //}; //tests.addPackage(zmath); //tests.setBuildMode(b.standardReleaseOptions()); //tests.setTarget(b.standardTargetOptions(.{})); //link(b, tests); //const test_step = b.step("test", "Run library tests"); //test_step.dependOn(&tests.step); } pub fn link(b: *std.build.Builder, step: *std.build.LibExeObjStep) void { const lib = buildLibrary(b, step); step.linkLibrary(lib); step.addIncludeDir(thisDir() ++ "/src/c"); } fn buildLibrary(b: *std.build.Builder, step: *std.build.LibExeObjStep) *std.build.LibExeObjStep { const lib = b.addStaticLibrary("common", thisDir() ++ "/src/common.zig"); lib.setBuildMode(step.build_mode); lib.setTarget(step.target); lib.want_lto = false; lib.addIncludeDir(thisDir() ++ "/src/c"); lib.linkSystemLibrary("c"); lib.linkSystemLibrary("c++"); lib.linkSystemLibrary("imm32"); lib.addCSourceFile(thisDir() ++ "/src/c/imgui/imgui.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/imgui/imgui_widgets.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/imgui/imgui_tables.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/imgui/imgui_draw.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/imgui/imgui_demo.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/cimgui.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/cgltf.c", &.{"-std=c99"}); lib.addCSourceFile(thisDir() ++ "/src/c/stb_image.c", &.{"-std=c99"}); lib.addCSourceFile(thisDir() ++ "/src/c/meshoptimizer/clusterizer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/meshoptimizer/indexgenerator.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/meshoptimizer/vcacheoptimizer.cpp", &.{""}); lib.addCSourceFile(thisDir() ++ "/src/c/meshoptimizer/vfetchoptimizer.cpp", &.{""}); lib.install(); return lib; } fn thisDir() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; }
libs/common/build.zig
const wlr = @import("../wlroots.zig"); const os = @import("std").os; const wayland = @import("wayland"); const wl = wayland.server.wl; pub const SerialRange = extern struct { min_incl: u32, max_incl: u32, }; pub const SerialRingset = extern struct { data: [128]SerialRange, end: c_int, count: c_int, }; pub const TouchPoint = extern struct { touch_id: i32, surface: ?*wlr.Surface, client: *wlr.Seat.Client, focus_surface: ?*wlr.Surface, focus_client: ?*wlr.Seat.Client, sx: f64, sy: f64, surface_destroy: wl.Listener(*wlr.Surface), focus_surface_destroy: wl.Listener(*wlr.Surface), client_destroy: wl.Listener(*Seat.Client), events: extern struct { destroy: wl.Signal(*TouchPoint), }, /// Seat.TouchState.touch_points link: wl.list.Link, }; pub const Seat = extern struct { pub const Client = extern struct { client: *wl.Client, seat: *Seat, /// Seat.clients link: wl.list.Link, resources: wl.list.Head(wl.Resource, null), pointers: wl.list.Head(wl.Resource, null), keyboards: wl.list.Head(wl.Resource, null), touches: wl.list.Head(wl.Resource, null), data_devices: wl.list.Head(wl.Resource, null), events: extern struct { destroy: wl.Signal(*Seat.Client), }, serials: SerialRingset, extern fn wlr_seat_client_next_serial(client: *Client) u32; pub const nextSerial = wlr_seat_client_next_serial; extern fn wlr_seat_client_validate_event_serial(client: *Client, serial: u32) bool; pub const validateEventSerial = wlr_seat_client_validate_event_serial; extern fn wlr_seat_client_from_resource(seat: *wl.Seat) ?*Client; pub const fromWlSeat = wlr_seat_client_from_resource; extern fn wlr_seat_client_from_pointer_resource(pointer: *wl.Pointer) ?*Client; pub const fromWlPointer = wlr_seat_client_from_pointer_resource; }; pub const PointerGrab = extern struct { pub const Interface = extern struct { enter: fn ( grab: *PointerGrab, surface: *wlr.Surface, sx: f64, sy: f64, ) callconv(.C) void, clear_focus: fn (grab: *PointerGrab) callconv(.C) void, motion: fn (grab: *PointerGrab, time_msec: u32, sx: f64, sy: f64) callconv(.C) void, button: fn ( grab: *PointerGrab, time_msec: u32, button: u32, state: wl.Pointer.ButtonState, ) callconv(.C) u32, axis: fn ( grab: *PointerGrab, time_msec: u32, orientation: wlr.AxisOrientation, value: f64, value_discrete: i32, source: wlr.AxisSource, ) callconv(.C) void, frame: ?fn (grab: *PointerGrab) callconv(.C) void, cancel: ?fn (grab: *PointerGrab) callconv(.C) void, }; interface: *const Interface, seat: *Seat, data: usize, }; pub const KeyboardGrab = extern struct { pub const Interface = extern struct { enter: fn ( grab: *KeyboardGrab, surface: *wlr.Surface, keycodes: ?[*]u32, num_keycodes: usize, modifiers: ?*wlr.Keyboard.Modifiers, ) callconv(.C) void, clear_focus: fn (grab: *KeyboardGrab) callconv(.C) void, key: fn (grab: *KeyboardGrab, time_msec: u32, key: u32, state: u32) callconv(.C) void, modifiers: fn (grab: *KeyboardGrab, modifiers: ?*wlr.Keyboard.Modifiers) callconv(.C) void, cancel: ?fn (grab: *KeyboardGrab) callconv(.C) void, }; interface: *const Interface, seat: *Seat, data: usize, }; pub const TouchGrab = extern struct { pub const Interface = extern struct { down: fn (grab: *TouchGrab, time_msec: u32, point: *TouchPoint) callconv(.C) u32, up: fn (grab: *TouchGrab, time_msec: u32, point: *TouchPoint) callconv(.C) void, motion: fn (grab: *TouchGrab, time_msec: u32, point: *TouchPoint) callconv(.C) void, enter: fn (grab: *TouchGrab, time_msec: u32, point: *TouchPoint) callconv(.C) void, cancel: ?fn (grab: *TouchGrab) callconv(.C) void, }; interface: *const Interface, seat: *Seat, data: usize, }; pub const PointerState = extern struct { seat: *Seat, focused_client: ?*Seat.Client, focused_surface: ?*wlr.Surface, sx: f64, sy: f64, grab: *PointerGrab, default_grab: *PointerGrab, buttons: [16]u32, button_count: usize, grab_button: u32, grab_serial: u32, grab_time: u32, surface_destroy: wl.Listener(*wlr.Surface), events: extern struct { focus_change: wl.Signal(*event.PointerFocusChange), }, }; pub const KeyboardState = extern struct { seat: *Seat, keyboard: ?*wlr.Keyboard, focused_client: ?*Seat.Client, focused_surface: ?*wlr.Surface, keyboard_destroy: wl.Listener(*wlr.Keyboard), keyboard_keymap: wl.Listener(*wlr.Keyboard), keyboard_repeat_info: wl.Listener(*wlr.Keyboard), surface_destroy: wl.Listener(*wlr.Surface), grab: *KeyboardGrab, default_grab: *KeyboardGrab, events: extern struct { focus_change: wl.Signal(*event.KeyboardFocusChange), }, }; pub const TouchState = extern struct { seat: *Seat, touch_points: wl.list.Head(TouchPoint, "link"), grab_serial: u32, grab_id: u32, grab: *TouchGrab, default_grab: *TouchGrab, }; pub const event = struct { pub const PointerFocusChange = extern struct { seat: *Seat, old_surface: ?*wlr.Surface, new_surface: ?*wlr.Surface, sx: f64, sy: f64, }; pub const KeyboardFocusChange = extern struct { seat: *Seat, old_surface: ?*wlr.Surface, new_surface: ?*wlr.Surface, }; pub const RequestSetCursor = extern struct { seat_client: *Seat.Client, surface: ?*wlr.Surface, serial: u32, hotspot_x: i32, hotspot_y: i32, }; pub const RequestSetSelection = extern struct { source: ?*wlr.DataSource, serial: u32, }; pub const RequestSetPrimarySelection = extern struct { source: ?*wlr.PrimarySelectionSource, serial: u32, }; pub const RequestStartDrag = extern struct { drag: *wlr.Drag, origin: *wlr.Surface, serial: u32, }; }; global: *wl.Global, server: *wl.Server, clients: wl.list.Head(Seat.Client, "link"), name: [*:0]u8, capabilities: u32, accumulated_capabilities: u32, last_event: os.timespec, selection_source: ?*wlr.DataSource, selection_serial: u32, /// wlr.DataOffer.link selection_offers: wl.list.Head(wlr.DataOffer, "link"), primary_selection_source: ?*wlr.PrimarySelectionSource, primary_selection_serial: u32, drag: ?*wlr.Drag, drag_source: ?*wlr.DataSource, drag_serial: u32, /// wlr.DataOffer.link drag_offers: wl.list.Head(wlr.DataOffer, "link"), pointer_state: PointerState, keyboard_state: KeyboardState, touch_state: TouchState, server_destroy: wl.Listener(*wl.Server), selection_source_destroy: wl.Listener(*wlr.DataSource), primary_selection_source_destroy: wl.Listener(*wlr.PrimarySelectionSource), drag_source_destroy: wl.Listener(*wlr.DataSource), events: extern struct { pointer_grab_begin: wl.Signal(*PointerGrab), pointer_grab_end: wl.Signal(*PointerGrab), keyboard_grab_begin: wl.Signal(*KeyboardGrab), keyboard_grab_end: wl.Signal(*KeyboardGrab), touch_grab_begin: wl.Signal(*TouchGrab), touch_grab_end: wl.Signal(*TouchGrab), request_set_cursor: wl.Signal(*event.RequestSetCursor), request_set_selection: wl.Signal(*event.RequestSetSelection), set_selection: wl.Signal(*wlr.Seat), request_set_primary_selection: wl.Signal(*event.RequestSetPrimarySelection), set_primary_selection: wl.Signal(*wlr.Seat), request_start_drag: wl.Signal(*event.RequestStartDrag), start_drag: wl.Signal(*wlr.Drag), destroy: wl.Signal(*wlr.Seat), }, data: usize, extern fn wlr_seat_create(server: *wl.Server, name: [*:0]const u8) ?*Seat; pub const create = wlr_seat_create; extern fn wlr_seat_destroy(seat: *Seat) void; pub const destroy = wlr_seat_destroy; extern fn wlr_seat_client_for_wl_client(seat: *Seat, wl_client: *wl.Client) ?*Seat.Client; pub const clientForWlClient = wlr_seat_client_for_wl_client; extern fn wlr_seat_set_capabilities(seat: *Seat, capabilities: u32) void; pub inline fn setCapabilities(seat: *Seat, capabilities: wl.Seat.Capability) void { wlr_seat_set_capabilities(seat, @bitCast(u32, capabilities)); } extern fn wlr_seat_set_name(seat: *Seat, name: [*:0]const u8) void; pub const setName = wlr_seat_set_name; extern fn wlr_seat_pointer_surface_has_focus(seat: *Seat, surface: *wlr.Surface) bool; pub const pointerSurfaceHasFocus = wlr_seat_pointer_surface_has_focus; extern fn wlr_seat_pointer_enter(seat: *Seat, surface: ?*wlr.Surface, sx: f64, sy: f64) void; pub const pointerEnter = wlr_seat_pointer_enter; extern fn wlr_seat_pointer_clear_focus(seat: *Seat) void; pub const pointerClearFocus = wlr_seat_pointer_clear_focus; extern fn wlr_seat_pointer_send_motion(seat: *Seat, time_msec: u32, sx: f64, sy: f64) void; pub const pointerSendMotion = wlr_seat_pointer_send_motion; extern fn wlr_seat_pointer_send_button(seat: *Seat, time_msec: u32, button: u32, state: wl.Pointer.ButtonState) u32; pub const pointerSendButton = wlr_seat_pointer_send_button; extern fn wlr_seat_pointer_send_axis(seat: *Seat, time_msec: u32, orientation: wlr.AxisOrientation, value: f64, value_discrete: i32, source: wlr.AxisSource) void; pub const pointerSendAxis = wlr_seat_pointer_send_axis; extern fn wlr_seat_pointer_send_frame(seat: *Seat) void; pub const pointerSendFrame = wlr_seat_pointer_send_frame; extern fn wlr_seat_pointer_notify_enter(seat: *Seat, surface: *wlr.Surface, sx: f64, sy: f64) void; pub const pointerNotifyEnter = wlr_seat_pointer_notify_enter; extern fn wlr_seat_pointer_notify_clear_focus(seat: *Seat) void; pub const pointerNotifyClearFocus = wlr_seat_pointer_notify_clear_focus; extern fn wlr_seat_pointer_warp(seat: *Seat, sx: f64, sy: f64) void; pub const pointerWarp = wlr_seat_pointer_warp; extern fn wlr_seat_pointer_notify_motion(seat: *Seat, time_msec: u32, sx: f64, sy: f64) void; pub const pointerNotifyMotion = wlr_seat_pointer_notify_motion; extern fn wlr_seat_pointer_notify_button(seat: *Seat, time_msec: u32, button: u32, state: wl.Pointer.ButtonState) u32; pub const pointerNotifyButton = wlr_seat_pointer_notify_button; extern fn wlr_seat_pointer_notify_axis(seat: *Seat, time_msec: u32, orientation: wlr.AxisOrientation, value: f64, value_discrete: i32, source: wlr.AxisSource) void; pub const pointerNotifyAxis = wlr_seat_pointer_notify_axis; extern fn wlr_seat_pointer_notify_frame(seat: *Seat) void; pub const pointerNotifyFrame = wlr_seat_pointer_notify_frame; extern fn wlr_seat_pointer_start_grab(seat: *Seat, grab: ?*PointerGrab) void; pub const pointerStartGrab = wlr_seat_pointer_start_grab; extern fn wlr_seat_pointer_end_grab(seat: *Seat) void; pub const pointerEndGrab = wlr_seat_pointer_end_grab; extern fn wlr_seat_pointer_has_grab(seat: *Seat) bool; pub const pointerHasGrab = wlr_seat_pointer_has_grab; extern fn wlr_seat_set_keyboard(seat: *Seat, dev: ?*wlr.InputDevice) void; pub const setKeyboard = wlr_seat_set_keyboard; extern fn wlr_seat_get_keyboard(seat: *Seat) ?*wlr.Keyboard; pub const getKeyboard = wlr_seat_get_keyboard; extern fn wlr_seat_keyboard_send_key(seat: *Seat, time_msec: u32, key: u32, state: u32) void; pub const keyboardSendKey = wlr_seat_keyboard_send_key; extern fn wlr_seat_keyboard_send_modifiers(seat: *Seat, modifiers: ?*wlr.Keyboard.Modifiers) void; pub const keyboardSendModifiers = wlr_seat_keyboard_send_modifiers; extern fn wlr_seat_keyboard_enter(seat: *Seat, surface: ?*wlr.Surface, keycodes: ?[*]u32, num_keycodes: usize, modifiers: ?*wlr.Keyboard.Modifiers) void; pub const keyboardEnter = wlr_seat_keyboard_enter; extern fn wlr_seat_keyboard_clear_focus(seat: *Seat) void; pub const keyboardClearFocus = wlr_seat_keyboard_clear_focus; extern fn wlr_seat_keyboard_notify_key(seat: *Seat, time_msec: u32, key: u32, state: u32) void; pub fn keyboardNotifyKey(seat: *Seat, time_msec: u32, key: u32, state: wl.Keyboard.KeyState) void { wlr_seat_keyboard_notify_key(seat, time_msec, key, @intCast(u32, @enumToInt(state))); } extern fn wlr_seat_keyboard_notify_modifiers(seat: *Seat, modifiers: ?*wlr.Keyboard.Modifiers) void; pub const keyboardNotifyModifiers = wlr_seat_keyboard_notify_modifiers; extern fn wlr_seat_keyboard_notify_enter(seat: *Seat, surface: *wlr.Surface, keycodes: ?[*]u32, num_keycodes: usize, modifiers: ?*wlr.Keyboard.Modifiers) void; pub const keyboardNotifyEnter = wlr_seat_keyboard_notify_enter; extern fn wlr_seat_keyboard_notify_clear_focus(seat: *Seat) void; pub const keyboardNotifyClearFocus = wlr_seat_keyboard_notify_clear_focus; extern fn wlr_seat_keyboard_start_grab(seat: *Seat, grab: *KeyboardGrab) void; pub const keyboardStartGrab = wlr_seat_keyboard_start_grab; extern fn wlr_seat_keyboard_end_grab(seat: *Seat) void; pub const keyboardEndGrab = wlr_seat_keyboard_end_grab; extern fn wlr_seat_keyboard_has_grab(seat: *Seat) bool; pub const keyboardHasGrab = wlr_seat_keyboard_has_grab; extern fn wlr_seat_touch_get_point(seat: *Seat, touch_id: i32) ?*TouchPoint; pub const touchGetPoint = wlr_seat_touch_get_point; extern fn wlr_seat_touch_point_focus(seat: *Seat, surface: *wlr.Surface, time_msec: u32, touch_id: i32, sx: f64, sy: f64) void; pub const touchPointFocus = wlr_seat_touch_point_focus; extern fn wlr_seat_touch_point_clear_focus(seat: *Seat, time_msec: u32, touch_id: i32) void; pub const touchPointClearFocus = wlr_seat_touch_point_clear_focus; extern fn wlr_seat_touch_send_down(seat: *Seat, surface: *wlr.Surface, time_msec: u32, touch_id: i32, sx: f64, sy: f64) u32; pub const touchSendDown = wlr_seat_touch_send_down; extern fn wlr_seat_touch_send_up(seat: *Seat, time_msec: u32, touch_id: i32) void; pub const touchSendUp = wlr_seat_touch_send_up; extern fn wlr_seat_touch_send_motion(seat: *Seat, time_msec: u32, touch_id: i32, sx: f64, sy: f64) void; pub const touchSendMotion = wlr_seat_touch_send_motion; extern fn wlr_seat_touch_notify_down(seat: *Seat, surface: *wlr.Surface, time_msec: u32, touch_id: i32, sx: f64, sy: f64) u32; pub const touchNotifyDown = wlr_seat_touch_notify_down; extern fn wlr_seat_touch_notify_up(seat: *Seat, time_msec: u32, touch_id: i32) void; pub const touchNotifyUp = wlr_seat_touch_notify_up; extern fn wlr_seat_touch_notify_motion(seat: *Seat, time_msec: u32, touch_id: i32, sx: f64, sy: f64) void; pub const touchNotifyMotion = wlr_seat_touch_notify_motion; extern fn wlr_seat_touch_num_points(seat: *Seat) c_int; pub const touchNumPoints = wlr_seat_touch_num_points; extern fn wlr_seat_touch_start_grab(seat: *Seat, grab: *TouchGrab) void; pub const touchStartGrab = wlr_seat_touch_start_grab; extern fn wlr_seat_touch_end_grab(seat: *Seat) void; pub const touchEndGrab = wlr_seat_touch_end_grab; extern fn wlr_seat_touch_has_grab(seat: *Seat) bool; pub const touchHasGrab = wlr_seat_touch_has_grab; extern fn wlr_seat_validate_grab_serial(seat: *Seat, serial: u32) bool; pub const validateGrabSerial = wlr_seat_validate_grab_serial; extern fn wlr_seat_validate_pointer_grab_serial(seat: *Seat, origin: ?*wlr.Surface, serial: u32) bool; pub const validatePointerGrabSerial = wlr_seat_validate_pointer_grab_serial; extern fn wlr_seat_validate_touch_grab_serial(seat: *Seat, origin: ?*wlr.Surface, serial: u32, point_ptr: *?*TouchPoint) bool; pub const validateTouchGrabSerial = wlr_seat_validate_touch_grab_serial; extern fn wlr_seat_request_set_selection(seat: *Seat, client: ?*Seat.Client, source: ?*wlr.DataSource, serial: u32) void; pub const requestSetSelection = wlr_seat_request_set_selection; extern fn wlr_seat_set_selection(seat: *Seat, source: ?*wlr.DataSource, serial: u32) void; pub const setSelection = wlr_seat_set_selection; extern fn wlr_seat_request_set_primary_selection(seat: *Seat, client: ?*Seat.Client, source: ?*wlr.PrimarySelectionSource, serial: u32) void; pub const requestSetPrimarySelection = wlr_seat_request_set_primary_selection; extern fn wlr_seat_set_primary_selection(seat: *Seat, source: ?*wlr.PrimarySelectionSource, serial: u32) void; pub const setPrimarySelection = wlr_seat_set_primary_selection; extern fn wlr_seat_request_start_drag(seat: *Seat, drag: *wlr.Drag, origin: *wlr.Surface, serial: u32) void; pub const requestStartDrag = wlr_seat_request_start_drag; extern fn wlr_seat_start_drag(seat: *Seat, drag: *wlr.Drag, serial: u32) void; pub const startDrag = wlr_seat_start_drag; extern fn wlr_seat_start_pointer_drag(seat: *Seat, drag: *wlr.Drag, serial: u32) void; pub const startPointerDrag = wlr_seat_start_pointer_drag; extern fn wlr_seat_start_touch_drag(seat: *Seat, drag: *wlr.Drag, serial: u32, point: *TouchPoint) void; pub const startTouchDrag = wlr_seat_start_touch_drag; };
src/types/seat.zig
const std = @import("std"); const endian: std.builtin.Endian = .Big; const PacketType = enum(u3) { literal = 4, sum = 0, product = 1, minimum = 2, maximum = 3, greater_than = 5, less_than = 6, equal_to = 7, }; const LengthMode = enum(u1) { bits = 0, packets = 1, }; const Length = union(LengthMode) { bits: u15, packets: u11, }; const PacketResult = u64; const PacketIter = struct { remaining: Length, fbs: *std.io.FixedBufferStream([]const u8), bits: *std.io.BitReader(endian, std.io.FixedBufferStream([]const u8).Reader), pub fn next(pi: *PacketIter) error{InvalidPacket}!?PacketResult { switch(pi.remaining) { .bits => |*bits| { // unfortunately super messy because BitReader doesn't count bits if(bits.* == 0) return null; const pos_start = pi.fbs.pos; const bit_start = 8 - @as(u4, pi.bits.bit_count); const result = try eval(pi.fbs, pi.bits); const pos_end = pi.fbs.pos; const bit_end = 8 - @as(u4, pi.bits.bit_count); const total_bits = (pos_end * 8 + bit_end) - (pos_start * 8 + bit_start); if(total_bits > std.math.maxInt(u15)) return error.InvalidPacket; if(bits.* < total_bits) return error.InvalidPacket; bits.* -= @intCast(u15, total_bits); return result; }, .packets => |*pc| { if(pc.* == 0) return null; pc.* -= 1; return try eval(pi.fbs, pi.bits); }, } } pub fn reduce( pi: *PacketIter, comptime Reducer: type, ) !@TypeOf(Reducer.initial) { var result = Reducer.initial; while(try pi.next()) |value| { result = Reducer.cb(result, value); } return result; } }; const Reducers = struct { const Sum = struct { const initial: PacketResult = 0; pub fn cb(t: PacketResult, a: PacketResult) PacketResult { return t + a; } }; const Mul = struct { const initial: PacketResult = 1; pub fn cb(t: PacketResult, a: PacketResult) PacketResult { return t * a; } }; const Min = struct { const initial: PacketResult = std.math.maxInt(u64); pub fn cb(t: PacketResult, a: PacketResult) PacketResult { return std.math.min(t, a); } }; const Max = struct { const initial: PacketResult = std.math.minInt(u64); pub fn cb(t: PacketResult, a: PacketResult) PacketResult { return std.math.max(t, a); } }; }; pub fn eval( fbs: *std.io.FixedBufferStream([]const u8), bits: *std.io.BitReader(endian, std.io.FixedBufferStream([]const u8).Reader), ) error{InvalidPacket}!PacketResult { const version = bits.readBitsNoEof(u3, 3) catch return error.InvalidPacket; _ = version; // no one cares about you const packet_type_raw = bits.readBitsNoEof(u3, 3) catch return error.InvalidPacket; const packet_type = std.meta.intToEnum(PacketType, packet_type_raw) catch return error.InvalidPacket; if(packet_type == .literal) { var res: u64 = 0; while(true) { const cont = 1 == (bits.readBitsNoEof(u1, 1) catch return error.InvalidPacket); res <<= 4; res |= bits.readBitsNoEof(u4, 4) catch return error.InvalidPacket; if(!cont) break; } return res; } const len_kind = @intToEnum(LengthMode, bits.readBitsNoEof(u1, 1) catch return error.InvalidPacket); const len: Length = switch(len_kind) { .bits => .{.bits = bits.readBitsNoEof(u15, 15) catch return error.InvalidPacket}, .packets => .{.packets = bits.readBitsNoEof(u11, 11) catch return error.InvalidPacket}, }; var iter = PacketIter{ .remaining = len, .fbs = fbs, .bits = bits, }; return switch(packet_type) { .literal => unreachable, .sum => iter.reduce(Reducers.Sum), .product => iter.reduce(Reducers.Mul), .minimum => iter.reduce(Reducers.Min), .maximum => iter.reduce(Reducers.Max), .greater_than, .less_than, .equal_to => { const a = (iter.next() catch return error.InvalidPacket) orelse return error.InvalidPacket; const b = (iter.next() catch return error.InvalidPacket) orelse return error.InvalidPacket; if((iter.next() catch return error.InvalidPacket) != null) return error.InvalidPacket; return switch(packet_type) { .greater_than => @boolToInt(a > b), .less_than => @boolToInt(a < b), .equal_to => @boolToInt(a == b), else => unreachable, }; }, }; } pub fn evalFromInput(raw_input: []const u8, alloc: std.mem.Allocator) !usize { const input = std.mem.trim(u8, raw_input, "\r\n "); var data = try std.ArrayList(u8).initCapacity( alloc, std.math.divCeil(usize, input.len, 2) catch unreachable, ); defer data.deinit(); var writer = std.io.bitWriter(endian, data.writer()); for(input) |char| { writer.writeBits( @intCast(u4, try std.fmt.charToDigit(char, 16)), 4, ) catch unreachable; } var fbs = std.io.fixedBufferStream(@as([]const u8, data.items)); var reader = std.io.bitReader(endian, fbs.reader()); return try eval(&fbs, &reader); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const alloc = arena.allocator(); const input = @embedFile("day16.txt"); std.log.info("result: {d}", .{try evalFromInput(input, alloc)}); } fn testCase(input: []const u8, result: usize) !void { try std.testing.expectEqual(result, try evalFromInput(input, std.testing.allocator)); } fn testError(input: []const u8) !void { try std.testing.expectError(try evalFromInput(input, std.testing.allocator)); } test "cases" { // C200B40A82 finds the sum of 1 and 2, resulting in the value 3. // 04005AC33890 finds the product of 6 and 9, resulting in the value 54. // 880086C3E88112 finds the minimum of 7, 8, and 9, resulting in the value 7. // CE00C43D881120 finds the maximum of 7, 8, and 9, resulting in the value 9. // D8005AC2A8F0 produces 1, because 5 is less than 15. // F600BC2D8F produces 0, because 5 is not greater than 15. // 9C005AC2F8F0 produces 0, because 5 is not equal to 15. // 9C0141080250320F1802104A08 produces 1, because 1 + 3 = 2 * 2. try testCase("C200B40A82", 3); try testCase("04005AC33890", 54); try testCase("880086C3E88112", 7); try testCase("CE00C43D881120", 9); try testCase("D8005AC2A8F0", 1); try testCase("F600BC2D8F", 0); try testCase("9C005AC2F8F0", 0); try testCase("9C0141080250320F1802104A08", 1); // ^ gh copilot converted those into test cases for me, thanks try testCase(@embedFile("day16.txt"), 1015320896946); }
2021/solutions/day16/day16.zig
const std = @import("std"); const ArrayList = std.ArrayList; const builtin = std.builtin; const sha256 = std.crypto.hash.sha2.Sha256; const hashes_of_zero = @import("./zeros.zig").hashes_of_zero; const Allocator = std.mem.Allocator; /// Number of bytes per chunk. const BYTES_PER_CHUNK = 32; /// Number of bytes per serialized length offset. const BYTES_PER_LENGTH_OFFSET = 4; // Determine the serialized size of an object so that // the code serializing of variable-size objects can // determine the offset to the next object. fn serializedSize(comptime T: type, data: T) !usize { const info = @typeInfo(T); return switch (info) { .Array => data.len, .Pointer => switch (info.Pointer.size) { .Slice => data.len, else => serializedSize(info.Pointer.child, data.*), }, .Optional => if (data == null) @as(usize, 0) else serializedSize(info.Optional.child, data.?), .Null => @as(usize, 0), else => error.NoSerializedSizeAvailable, }; } /// Returns true if an object is of fixed size fn isFixedSizeObject(comptime T: type) !bool { const info = @typeInfo(T); switch (info) { .Bool, .Int, .Null => return true, .Array => return false, .Struct => inline for (info.Struct.fields) |field| { if (!try isFixedSizeObject(field.field_type)) { return false; } }, .Pointer => switch (info.Pointer.size) { .Many, .Slice, .C => return false, .One => return isFixedSizeObject(info.Pointer.child), }, else => return error.UnknownType, } return true; } /// Provides the generic serialization of any `data` var to SSZ. The /// serialization is written to the `ArrayList` `l`. pub fn serialize(comptime T: type, data: T, l: *ArrayList(u8)) !void { const info = @typeInfo(T); switch (info) { .Array => { // Bitvector[N] or vector? if (info.Array.child == bool) { var byte: u8 = 0; for (data) |bit, index| { if (bit) { byte |= @as(u8, 1) << @truncate(u3, index); } if (index % 8 == 7) { try l.append(byte); byte = 0; } } // Write the last byte if the length // is not byte-aligned if (data.len % 8 != 0) { try l.append(byte); } } else { // If the item type is fixed-size, serialize inline, // otherwise, create an array of offsets and then // serialize each object afterwards. if (try isFixedSizeObject(info.Array.child)) { for (data) |item| { try serialize(info.Array.child, item, l); } } else { // Size of the buffer before anything is // written to it. var start = l.items.len; // Reserve the space for the offset const offset = [_]u8{ 0, 0, 0, 0 }; for (data) |_| { _ = try l.writer().write(offset[0..4]); } // Now serialize one item after the other // and update the offset list with its location. for (data) |item| { std.mem.writeIntLittle(u32, l.items[start .. start + 4][0..4], @truncate(u32, l.items.len)); _ = try serialize(info.Array.child, item, l); start += 4; } } } }, .Bool => { if (data) { try l.append(1); } else { try l.append(0); } }, .Int => { var serialized: [@sizeOf(T)]u8 = undefined; std.mem.writeIntLittle(T, serialized[0..], data); _ = try l.writer().write(serialized[0..]); }, .Pointer => { // Bitlist[N] or list? switch (info.Pointer.size) { .Slice, .One => { if (@sizeOf(info.Pointer.child) == 1) { _ = try l.writer().write(data); } else { for (data) |item| { try serialize(@TypeOf(item), item, l); } } }, else => return error.UnSupportedPointerType, } }, .Struct => { // First pass, accumulate the fixed sizes comptime var var_start = 0; inline for (info.Struct.fields) |field| { if (@typeInfo(field.field_type) == .Int or @typeInfo(field.field_type) == .Bool) { var_start += @sizeOf(field.field_type); } else { var_start += 4; } } // Second pass: intertwine fixed fields and variables offsets var var_acc = @as(usize, var_start); // variable part size accumulator inline for (info.Struct.fields) |field| { switch (@typeInfo(field.field_type)) { .Int, .Bool => { try serialize(field.field_type, @field(data, field.name), l); }, else => { try serialize(u32, @truncate(u32, var_acc), l); var_acc += try serializedSize(field.field_type, @field(data, field.name)); }, } } // Third pass: add variable fields at the end if (var_acc > var_start) { inline for (info.Struct.fields) |field| { switch (@typeInfo(field.field_type)) { .Int, .Bool => { // skip fixed-size fields }, else => { try serialize(field.field_type, @field(data, field.name), l); }, } } } }, // Nothing to be added .Null => {}, .Optional => if (data != null) try serialize(info.Optional.child, data.?, l), .Union => { if (info.Union.tag_type == null) { return error.UnionIsNotTagged; } inline for (info.Union.fields) |f, index| { if (@enumToInt(data) == index) { try serialize(u32, index, l); try serialize(f.field_type, @field(data, f.name), l); return; } } }, else => { return error.UnknownType; }, } } /// Takes a byte array containing the serialized payload of type `T` (with /// possible trailing data) and deserializes it into the `T` object pointed /// at by `out`. pub fn deserialize(comptime T: type, serialized: []const u8, out: *T) !void { const info = @typeInfo(T); switch (info) { .Array => { // Bitvector[N] or regular vector? if (info.Array.child == bool) { for (serialized) |byte, bindex| { var i = @as(u8, 0); var b = byte; while (bindex * 8 + i < out.len and i < 8) : (i += 1) { out[bindex * 8 + i] = b & 1 == 1; b >>= 1; } } } else { const U = info.Array.child; if (try isFixedSizeObject(U)) { comptime var i = 0; const pitch = @sizeOf(U); inline while (i < out.len) : (i += pitch) { try deserialize(U, serialized[i * pitch .. (i + 1) * pitch], &out[i]); } } else { // first variable index is also the size of the list // of indices. Recast that list as a []const u32. const size = std.mem.readIntLittle(u32, serialized[0..4]) / @sizeOf(u32); const indices = std.mem.bytesAsSlice(u32, serialized[0 .. size * 4]); var i = @as(usize, 0); while (i < size) : (i += 1) { const end = if (i < size - 1) indices[i + 1] else serialized.len; const start = indices[i]; if (start >= serialized.len or end > serialized.len) { return error.IndexOutOfBounds; } try deserialize(U, serialized[start..end], &out[i]); } } } }, .Bool => out.* = (serialized[0] == 1), .Int => { const N = @sizeOf(T); out.* = std.mem.readIntLittle(T, serialized[0..N]); }, .Optional => if (serialized.len != 0) { var x: info.Optional.child = undefined; try deserialize(info.Optional.child, serialized, &x); out.* = x; } else { out.* = null; }, // Data is not copied in this function, copy is therefore // the responsibility of the caller. .Pointer => out.* = serialized[0..], .Struct => { // Calculate the number of variable fields in the // struct. comptime var n_var_fields = 0; comptime { for (info.Struct.fields) |field| { switch (@typeInfo(field.field_type)) { .Int, .Bool => {}, else => n_var_fields += 1, } } } var indices: [n_var_fields]u32 = undefined; // First pass, read the value of each fixed-size field, // and write down the start offset of each variable-sized // field. comptime var i = 0; inline for (info.Struct.fields) |field, field_index| { switch (@typeInfo(field.field_type)) { .Bool, .Int => { // Direct deserialize try deserialize(field.field_type, serialized[i .. i + @sizeOf(field.field_type)], &@field(out.*, field.name)); i += @sizeOf(field.field_type); }, else => { try deserialize(u32, serialized[i .. i + 4], &indices[field_index]); i += 4; }, } } // Second pass, deserialize each variable-sized value // now that their offset is known. comptime var last_index = 0; inline for (info.Struct.fields) |field| { switch (@typeInfo(field.field_type)) { .Bool, .Int => {}, // covered by the previous pass else => { const end = if (last_index == indices.len - 1) serialized.len else indices[last_index + 1]; try deserialize(field.field_type, serialized[indices[last_index]..end], &@field(out.*, field.name)); last_index += 1; }, } } }, .Union => { // Read the type index var union_index: u32 = undefined; try deserialize(u32, serialized, &union_index); // Use the index to figure out which type must // be deserialized. inline for (info.Union.fields) |field, index| { if (index == union_index) { // &@field(out.*, field.name) can not be used directly, // because this field type hasn't been activated at this // stage. var data: field.field_type = undefined; try deserialize(field.field_type, serialized[4..], &data); out.* = @unionInit(T, field.name, data); } } }, else => return error.NotImplemented, } } fn mixInLength(root: [32]u8, length: [32]u8, out: *[32]u8) void { var hasher = sha256.init(sha256.Options{}); hasher.update(root[0..]); hasher.update(length[0..]); hasher.final(out[0..]); } test "mixInLength" { var root: [32]u8 = undefined; var length: [32]u8 = undefined; var expected: [32]u8 = undefined; var mixin: [32]u8 = undefined; _ = try std.fmt.hexToBytes(root[0..], "2279cf111c15f2d594e7a0055e8735e7409e56ed4250735d6d2f2b0d1bcf8297"); _ = try std.fmt.hexToBytes(length[0..], "deadbeef00000000000000000000000000000000000000000000000000000000"); _ = try std.fmt.hexToBytes(expected[0..], "0b665dda6e4c269730bc4bbe3e990a69d37fa82892bac5fe055ca4f02a98c900"); mixInLength(root, length, &mixin); try std.testing.expect(std.mem.eql(u8, mixin[0..], expected[0..])); } fn mixInSelector(root: [32]u8, comptime selector: usize, out: *[32]u8) void { var hasher = sha256.init(sha256.Options{}); hasher.update(root[0..]); var tmp = [_]u8{0} ** 32; std.mem.writeIntLittle(@TypeOf(selector), tmp[0..@sizeOf(@TypeOf(selector))], selector); hasher.update(tmp[0..]); hasher.final(out[0..]); } test "mixInSelector" { var root: [32]u8 = undefined; var expected: [32]u8 = undefined; var mixin: [32]u8 = undefined; _ = try std.fmt.hexToBytes(root[0..], "2279cf111c15f2d594e7a0055e8735e7409e56ed4250735d6d2f2b0d1bcf8297"); _ = try std.fmt.hexToBytes(expected[0..], "c483cb731afcfe9f2c596698eaca1c4e0dcb4a1136297adef74c31c268966eb5"); mixInSelector(root, 25, &mixin); try std.testing.expect(std.mem.eql(u8, mixin[0..], expected[0..])); } /// Calculates the number of leaves needed for the merkelization /// of this type. pub fn chunkCount(comptime T: type) usize { const info = @typeInfo(T); switch (info) { .Int, .Bool => return 1, .Pointer => return chunkCount(info.Pointer.child), // the chunk size of an array depends on its type .Array => switch (@typeInfo(info.Array.child)) { // Bitvector[N] .Bool => return (info.Array.len + 255) / 256, // Vector[B,N] .Int => return (info.Array.len * @sizeOf(info.Array.child) + 31) / 32, // Vector[C,N] else => return info.Array.len, }, .Struct => return info.Struct.fields.len, else => return error.NotSupported, } } const chunk = [BYTES_PER_CHUNK]u8; const zero_chunk: chunk = [_]u8{0} ** BYTES_PER_CHUNK; fn pack(comptime T: type, values: T, l: *ArrayList(u8)) ![]chunk { try serialize(T, values, l); const padding_size = (BYTES_PER_CHUNK - l.items.len % BYTES_PER_CHUNK) % BYTES_PER_CHUNK; _ = try l.writer().write(zero_chunk[0..padding_size]); return std.mem.bytesAsSlice(chunk, l.items); } test "pack u32" { var expected: [32]u8 = undefined; var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); const out = try pack(u32, 0xdeadbeef, &list); _ = try std.fmt.hexToBytes(expected[0..], "efbeadde00000000000000000000000000000000000000000000000000000000"); try std.testing.expect(std.mem.eql(u8, out[0][0..], expected[0..])); } test "pack bool" { var expected: [32]u8 = undefined; var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); const out = try pack(bool, true, &list); _ = try std.fmt.hexToBytes(expected[0..], "0100000000000000000000000000000000000000000000000000000000000000"); try std.testing.expect(std.mem.eql(u8, out[0][0..], expected[0..])); } test "pack string" { var expected: [128]u8 = undefined; var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); const out = try pack([]const u8, "a" ** 100, &list); _ = try std.fmt.hexToBytes(expected[0..], "6161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616161616100000000000000000000000000000000000000000000000000000000"); try std.testing.expect(expected.len == out.len * out[0].len); try std.testing.expect(std.mem.eql(u8, out[0][0..], expected[0..32])); try std.testing.expect(std.mem.eql(u8, out[1][0..], expected[32..64])); try std.testing.expect(std.mem.eql(u8, out[2][0..], expected[64..96])); try std.testing.expect(std.mem.eql(u8, out[3][0..], expected[96..])); } fn nextPowOfTwo(len: usize) !usize { if (len == 0) { return @as(usize, 0); } // check that the msb isn't set and // return an error if it is, as it // would overflow. if (@clz(usize, len) == 0) { return error.OverflowsUSize; } const n = std.math.log2(std.math.shl(usize, len, 1) - 1); return std.math.powi(usize, 2, n); } test "next power of 2" { var out = try nextPowOfTwo(0b1); try std.testing.expect(out == 1); out = try nextPowOfTwo(0b10); try std.testing.expect(out == 2); out = try nextPowOfTwo(0b11); try std.testing.expect(out == 4); // special cases out = try nextPowOfTwo(0); try std.testing.expect(out == 0); try std.testing.expectError(error.OverflowsUSize, nextPowOfTwo(std.math.maxInt(usize))); } // merkleize recursively calculates the root hash of a Merkle tree. pub fn merkleize(chunks: []chunk, limit: ?usize, out: *[32]u8) anyerror!void { // Calculate the number of chunks to be padded, check the limit if (limit != null and chunks.len > limit.?) { return error.ChunkSizeExceedsLimit; } var size = try nextPowOfTwo(limit orelse chunks.len); // Perform the merkelization switch (size) { 0 => std.mem.copy(u8, out.*[0..], zero_chunk[0..]), 1 => std.mem.copy(u8, out.*[0..], chunks[0][0..]), else => { // Merkleize the left side. If the number of chunks // isn't enough to fill the entire width, complete // with zeroes. var digest = sha256.init(sha256.Options{}); var buf: [32]u8 = undefined; const split = if (size / 2 < chunks.len) size / 2 else chunks.len; try merkleize(chunks[0..split], size / 2, &buf); digest.update(buf[0..]); // Merkleize the right side. If the number of chunks only // covers the first half, directly input the hashed zero- // filled subtrie. if (size / 2 < chunks.len) { try merkleize(chunks[size / 2 ..], size / 2, &buf); digest.update(buf[0..]); } else digest.update(hashes_of_zero[size / 2 - 1][0..]); digest.final(out); }, } } test "merkleize a string" { var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); var chunks = try pack([]const u8, "a" ** 100, &list); var out: [32]u8 = undefined; try merkleize(chunks, null, &out); // Build the expected tree const leaf1 = [_]u8{0x61} ** 32; // "0xaaaaa....aa" 32 times var leaf2: [32]u8 = [_]u8{0x61} ** 4 ++ [_]u8{0} ** 28; var root: [32]u8 = undefined; var internal_left: [32]u8 = undefined; var internal_right: [32]u8 = undefined; var hasher = sha256.init(sha256.Options{}); hasher.update(leaf1[0..]); hasher.update(leaf1[0..]); hasher.final(&internal_left); hasher = sha256.init(sha256.Options{}); hasher.update(leaf1[0..]); hasher.update(leaf2[0..]); hasher.final(&internal_right); hasher = sha256.init(sha256.Options{}); hasher.update(internal_left[0..]); hasher.update(internal_right[0..]); hasher.final(&root); try std.testing.expect(std.mem.eql(u8, out[0..], root[0..])); } test "merkleize a boolean" { var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); var chunks = try pack(bool, false, &list); var expected = [_]u8{0} ** BYTES_PER_CHUNK; var out: [BYTES_PER_CHUNK]u8 = undefined; try merkleize(chunks, null, &out); try std.testing.expect(std.mem.eql(u8, out[0..], expected[0..])); var list2 = ArrayList(u8).init(std.testing.allocator); defer list2.deinit(); chunks = try pack(bool, true, &list2); expected[0] = 1; try merkleize(chunks, null, &out); try std.testing.expect(std.mem.eql(u8, out[0..], expected[0..])); } test "merkleize a bytes16 vector with one element" { var list = ArrayList(u8).init(std.testing.allocator); defer list.deinit(); var chunks = try pack([16]u8, [_]u8{0xaa} ** 16, &list); var expected: [32]u8 = [_]u8{0xaa} ** 16 ++ [_]u8{0x00} ** 16; var out: [32]u8 = undefined; try merkleize(chunks, null, &out); try std.testing.expect(std.mem.eql(u8, out[0..], expected[0..])); } fn packBits(bits: []const bool, l: *ArrayList(u8)) ![]chunk { var byte: u8 = 0; for (bits) |bit, bitidx| { if (bit) { byte |= @as(u8, 1) << @truncate(u3, 7 - bitidx % 8); } if (bitidx % 8 == 7 or bitidx == bits.len - 1) { try l.append(byte); byte = 0; } } // pad the last chunk with 0s const padding_size = (BYTES_PER_CHUNK - l.items.len % BYTES_PER_CHUNK) % BYTES_PER_CHUNK; _ = try l.writer().write(zero_chunk[0..padding_size]); return std.mem.bytesAsSlice(chunk, l.items); } pub fn hashTreeRoot(comptime T: type, value: T, out: *[32]u8, allctr: Allocator) !void { const type_info = @typeInfo(T); switch (type_info) { .Int, .Bool => { var list = ArrayList(u8).init(allctr); defer list.deinit(); var chunks = try pack(T, value, &list); try merkleize(chunks, null, out); }, .Array => { // Check if the child is a basic type. If so, return // the merkle root of its chunked serialization. // Otherwise, it is a composite object and the chunks // are the merkle roots of its elements. switch (@typeInfo(type_info.Array.child)) { .Int => { var list = ArrayList(u8).init(allctr); defer list.deinit(); var chunks = try pack(T, value, &list); try merkleize(chunks, null, out); }, .Bool => { var list = ArrayList(u8).init(allctr); defer list.deinit(); var chunks = try packBits(value[0..], &list); try merkleize(chunks, chunkCount(T), out); }, .Array => { var chunks = ArrayList(chunk).init(allctr); defer chunks.deinit(); var tmp: chunk = undefined; for (value) |item| { try hashTreeRoot(@TypeOf(item), item, &tmp, allctr); try chunks.append(tmp); } try merkleize(chunks.items, null, out); }, else => return error.NotSupported, } }, .Pointer => { switch (type_info.Pointer.size) { .One => hashTreeRoot(type_info.Pointer.child, value.*, out, allctr), .Slice => { switch (@typeInfo(type_info.Pointer.child)) { .Int => { var list = ArrayList(u8).init(allctr); defer list.deinit(); var chunks = try pack(T, value, &list); merkleize(chunks, null, out); }, else => return error.UnSupportedPointerType, } }, else => return error.UnSupportedPointerType, } }, .Struct => { var chunks = ArrayList(chunk).init(allctr); defer chunks.deinit(); var tmp: chunk = undefined; inline for (type_info.Struct.fields) |f| { try hashTreeRoot(f.field_type, @field(value, f.name), &tmp, allctr); try chunks.append(tmp); } try merkleize(chunks.items, null, out); }, // An optional is a union with `None` as first value. .Optional => if (value != null) { var tmp: chunk = undefined; try hashTreeRoot(type_info.Optional.child, value.?, &tmp, allctr); mixInSelector(tmp, 1, out); } else { mixInSelector(zero_chunk, 0, out); }, .Union => { if (type_info.Union.tag_type == null) { return error.UnionIsNotTagged; } inline for (type_info.Union.fields) |f, index| { if (@enumToInt(value) == index) { var tmp: chunk = undefined; try hashTreeRoot(f.field_type, @field(value, f.name), &tmp, allctr); mixInSelector(tmp, index, out); } } }, else => return error.NotSupported, } } // used at comptime to generate a bitvector from a byte vector fn bytesToBits(comptime N: usize, src: [N]u8) [N * 8]bool { var bitvector: [N * 8]bool = undefined; for (src) |byte, idx| { var i = 0; while (i < 8) : (i += 1) { bitvector[i + idx * 8] = ((byte >> (7 - i)) & 1) == 1; } } return bitvector; }
src/main.zig
export fn _IO_flockfile() void {} export fn _IO_ftrylockfile() void {} export fn _IO_funlockfile() void {} export fn __close() void {} export fn __connect() void {} export fn __errno_location() void {} export fn __fcntl() void {} export fn __fork() void {} export fn __h_errno_location() void {} export fn __libc_allocate_rtsig() void {} export fn __libc_current_sigrtmax() void {} export fn __libc_current_sigrtmin() void {} export fn __libpthread_freeres() void {} export fn __lseek() void {} export fn __nanosleep() void {} export fn __open() void {} export fn __open64() void {} export fn __pread64() void {} export fn __pthread_barrier_init() void {} export fn __pthread_barrier_wait() void {} export fn __pthread_cleanup_routine() void {} export fn __pthread_clock_gettime() void {} export fn __pthread_clock_settime() void {} export fn __pthread_get_minstack() void {} export fn __pthread_getspecific() void {} export fn __pthread_initialize_minimal() void {} export fn __pthread_key_create() void {} export fn __pthread_mutex_destroy() void {} export fn __pthread_mutex_init() void {} export fn __pthread_mutex_lock() void {} export fn __pthread_mutex_trylock() void {} export fn __pthread_mutex_unlock() void {} export fn __pthread_mutexattr_destroy() void {} export fn __pthread_mutexattr_init() void {} export fn __pthread_mutexattr_settype() void {} export fn __pthread_once() void {} export fn __pthread_register_cancel() void {} export fn __pthread_register_cancel_defer() void {} export fn __pthread_rwlock_destroy() void {} export fn __pthread_rwlock_init() void {} export fn __pthread_rwlock_rdlock() void {} export fn __pthread_rwlock_tryrdlock() void {} export fn __pthread_rwlock_trywrlock() void {} export fn __pthread_rwlock_unlock() void {} export fn __pthread_rwlock_wrlock() void {} export fn __pthread_setspecific() void {} export fn __pthread_unregister_cancel() void {} export fn __pthread_unregister_cancel_restore() void {} export fn __pthread_unwind() void {} export fn __pthread_unwind_next() void {} export fn __pwrite64() void {} export fn __read() void {} export fn __res_state() void {} export fn __send() void {} export fn __shm_directory() void {} export fn __sigaction() void {} export fn __vfork() void {} export fn __wait() void {} export fn __write() void {} export fn _pthread_cleanup_pop() void {} export fn _pthread_cleanup_pop_restore() void {} export fn _pthread_cleanup_push() void {} export fn _pthread_cleanup_push_defer() void {} export fn accept() void {} export fn call_once() void {} export fn close() void {} export fn cnd_broadcast() void {} export fn cnd_destroy() void {} export fn cnd_init() void {} export fn cnd_signal() void {} export fn cnd_timedwait() void {} export fn cnd_wait() void {} export fn connect() void {} export fn fcntl() void {} export fn flockfile() void {} export fn fork() void {} export fn fsync() void {} export fn ftrylockfile() void {} export fn funlockfile() void {} export fn longjmp() void {} export fn lseek() void {} export fn lseek64() void {} export fn msync() void {} export fn mtx_destroy() void {} export fn mtx_init() void {} export fn mtx_lock() void {} export fn mtx_timedlock() void {} export fn mtx_trylock() void {} export fn mtx_unlock() void {} export fn nanosleep() void {} export fn open() void {} export fn open64() void {} export fn pause() void {} export fn pread() void {} export fn pread64() void {} export fn pthread_atfork() void {} export fn pthread_attr_destroy() void {} export fn pthread_attr_getaffinity_np() void {} export fn pthread_attr_getdetachstate() void {} export fn pthread_attr_getguardsize() void {} export fn pthread_attr_getinheritsched() void {} export fn pthread_attr_getschedparam() void {} export fn pthread_attr_getschedpolicy() void {} export fn pthread_attr_getscope() void {} export fn pthread_attr_getstack() void {} export fn pthread_attr_getstackaddr() void {} export fn pthread_attr_getstacksize() void {} export fn pthread_attr_init() void {} export fn pthread_attr_setaffinity_np() void {} export fn pthread_attr_setdetachstate() void {} export fn pthread_attr_setguardsize() void {} export fn pthread_attr_setinheritsched() void {} export fn pthread_attr_setschedparam() void {} export fn pthread_attr_setschedpolicy() void {} export fn pthread_attr_setscope() void {} export fn pthread_attr_setstack() void {} export fn pthread_attr_setstackaddr() void {} export fn pthread_attr_setstacksize() void {} export fn pthread_barrier_destroy() void {} export fn pthread_barrier_init() void {} export fn pthread_barrier_wait() void {} export fn pthread_barrierattr_destroy() void {} export fn pthread_barrierattr_getpshared() void {} export fn pthread_barrierattr_init() void {} export fn pthread_barrierattr_setpshared() void {} export fn pthread_cancel() void {} export fn pthread_cond_broadcast() void {} export fn pthread_cond_destroy() void {} export fn pthread_cond_init() void {} export fn pthread_cond_signal() void {} export fn pthread_cond_timedwait() void {} export fn pthread_cond_wait() void {} export fn pthread_condattr_destroy() void {} export fn pthread_condattr_getclock() void {} export fn pthread_condattr_getpshared() void {} export fn pthread_condattr_init() void {} export fn pthread_condattr_setclock() void {} export fn pthread_condattr_setpshared() void {} export fn pthread_create() void {} export fn pthread_detach() void {} export fn pthread_equal() void {} export fn pthread_exit() void {} export fn pthread_getaffinity_np() void {} export fn pthread_getattr_default_np() void {} export fn pthread_getattr_np() void {} export fn pthread_getconcurrency() void {} export fn pthread_getcpuclockid() void {} export fn pthread_getname_np() void {} export fn pthread_getschedparam() void {} export fn pthread_getspecific() void {} export fn pthread_join() void {} export fn pthread_key_create() void {} export fn pthread_key_delete() void {} export fn pthread_kill() void {} export fn pthread_kill_other_threads_np() void {} export fn pthread_mutex_consistent() void {} export fn pthread_mutex_consistent_np() void {} export fn pthread_mutex_destroy() void {} export fn pthread_mutex_getprioceiling() void {} export fn pthread_mutex_init() void {} export fn pthread_mutex_lock() void {} export fn pthread_mutex_setprioceiling() void {} export fn pthread_mutex_timedlock() void {} export fn pthread_mutex_trylock() void {} export fn pthread_mutex_unlock() void {} export fn pthread_mutexattr_destroy() void {} export fn pthread_mutexattr_getkind_np() void {} export fn pthread_mutexattr_getprioceiling() void {} export fn pthread_mutexattr_getprotocol() void {} export fn pthread_mutexattr_getpshared() void {} export fn pthread_mutexattr_getrobust() void {} export fn pthread_mutexattr_getrobust_np() void {} export fn pthread_mutexattr_gettype() void {} export fn pthread_mutexattr_init() void {} export fn pthread_mutexattr_setkind_np() void {} export fn pthread_mutexattr_setprioceiling() void {} export fn pthread_mutexattr_setprotocol() void {} export fn pthread_mutexattr_setpshared() void {} export fn pthread_mutexattr_setrobust() void {} export fn pthread_mutexattr_setrobust_np() void {} export fn pthread_mutexattr_settype() void {} export fn pthread_once() void {} export fn pthread_rwlock_destroy() void {} export fn pthread_rwlock_init() void {} export fn pthread_rwlock_rdlock() void {} export fn pthread_rwlock_timedrdlock() void {} export fn pthread_rwlock_timedwrlock() void {} export fn pthread_rwlock_tryrdlock() void {} export fn pthread_rwlock_trywrlock() void {} export fn pthread_rwlock_unlock() void {} export fn pthread_rwlock_wrlock() void {} export fn pthread_rwlockattr_destroy() void {} export fn pthread_rwlockattr_getkind_np() void {} export fn pthread_rwlockattr_getpshared() void {} export fn pthread_rwlockattr_init() void {} export fn pthread_rwlockattr_setkind_np() void {} export fn pthread_rwlockattr_setpshared() void {} export fn pthread_self() void {} export fn pthread_setaffinity_np() void {} export fn pthread_setattr_default_np() void {} export fn pthread_setcancelstate() void {} export fn pthread_setcanceltype() void {} export fn pthread_setconcurrency() void {} export fn pthread_setname_np() void {} export fn pthread_setschedparam() void {} export fn pthread_setschedprio() void {} export fn pthread_setspecific() void {} export fn pthread_sigmask() void {} export fn pthread_sigqueue() void {} export fn pthread_spin_destroy() void {} export fn pthread_spin_init() void {} export fn pthread_spin_lock() void {} export fn pthread_spin_trylock() void {} export fn pthread_spin_unlock() void {} export fn pthread_testcancel() void {} export fn pthread_timedjoin_np() void {} export fn pthread_tryjoin_np() void {} export fn pthread_yield() void {} export fn pwrite() void {} export fn pwrite64() void {} export fn raise() void {} export fn read() void {} export fn recv() void {} export fn recvfrom() void {} export fn recvmsg() void {} export fn sem_close() void {} export fn sem_destroy() void {} export fn sem_getvalue() void {} export fn sem_init() void {} export fn sem_open() void {} export fn sem_post() void {} export fn sem_timedwait() void {} export fn sem_trywait() void {} export fn sem_unlink() void {} export fn sem_wait() void {} export fn send() void {} export fn sendmsg() void {} export fn sendto() void {} export fn sigaction() void {} export fn siglongjmp() void {} export fn sigwait() void {} export fn system() void {} export fn tcdrain() void {} export fn thrd_create() void {} export fn thrd_detach() void {} export fn thrd_exit() void {} export fn thrd_join() void {} export fn tss_create() void {} export fn tss_delete() void {} export fn tss_get() void {} export fn tss_set() void {} export fn vfork() void {} export fn wait() void {} export fn waitpid() void {} export fn write() void {}
libc/dummy/pthread.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"); pub const QueryParameters = struct { const Self = @This(); consistency_level: Consistency, values: ?Values, skip_metadata: bool, page_size: ?u32, paging_state: ?[]const u8, // NOTE(vincent): not a string serial_consistency_level: ?Consistency, timestamp: ?u64, keyspace: ?[]const u8, now_in_seconds: ?u32, const FlagWithValues: u32 = 0x0001; const FlagSkipMetadata: u32 = 0x0002; const FlagWithPageSize: u32 = 0x0004; const FlagWithPagingState: u32 = 0x0008; const FlagWithSerialConsistency: u32 = 0x0010; const FlagWithDefaultTimestamp: u32 = 0x0020; const FlagWithNamedValues: u32 = 0x0040; const FlagWithKeyspace: u32 = 0x0080; const FlagWithNowInSeconds: u32 = 0x100; pub fn write(self: Self, protocol_version: ProtocolVersion, pw: *PrimitiveWriter) !void { _ = try pw.writeConsistency(self.consistency_level); // Build the flags value var flags: u32 = 0; if (self.values) |v| { flags |= FlagWithValues; if (v == .Named) { flags |= FlagWithNamedValues; } } if (self.skip_metadata) { flags |= FlagSkipMetadata; } if (self.page_size != null) { flags |= FlagWithPageSize; } if (self.paging_state != null) { flags |= FlagWithPagingState; } 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 if (self.values) |values| { switch (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); } }, } } if (self.page_size) |ps| { _ = try pw.writeInt(u32, ps); } if (self.paging_state) |ps| { _ = try pw.writeBytes(ps); } if (self.serial_consistency_level) |consistency| { _ = try pw.writeConsistency(consistency); } if (self.timestamp) |ts| { _ = try pw.writeInt(u64, ts); } if (!protocol_version.is(5)) { return; } // The following flags are only valid with protocol v5 if (self.keyspace) |ks| { _ = try pw.writeString(ks); } if (self.now_in_seconds) |s| { _ = try pw.writeInt(u32, s); } } pub fn read(allocator: *mem.Allocator, protocol_version: ProtocolVersion, pr: *PrimitiveReader) !QueryParameters { var params = QueryParameters{ .consistency_level = undefined, .values = null, .skip_metadata = false, .page_size = null, .paging_state = null, .serial_consistency_level = null, .timestamp = null, .keyspace = null, .now_in_seconds = null, }; params.consistency_level = try pr.readConsistency(); // The remaining data in the frame depends on the flags // 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 & FlagWithValues == FlagWithValues) { const n = try pr.readInt(u16); if (flags & FlagWithNamedValues == FlagWithNamedValues) { var list = std.ArrayList(NamedValue).init(allocator); errdefer list.deinit(); var i: usize = 0; while (i < @as(usize, n)) : (i += 1) { const nm = NamedValue{ .name = try pr.readString(allocator), .value = try pr.readValue(allocator), }; _ = try list.append(nm); } params.values = Values{ .Named = list.toOwnedSlice() }; } else { var list = std.ArrayList(Value).init(allocator); errdefer list.deinit(); var i: usize = 0; while (i < @as(usize, n)) : (i += 1) { const value = try pr.readValue(allocator); _ = try list.append(value); } params.values = Values{ .Normal = list.toOwnedSlice() }; } } if (flags & FlagSkipMetadata == FlagSkipMetadata) { params.skip_metadata = true; } if (flags & FlagWithPageSize == FlagWithPageSize) { params.page_size = try pr.readInt(u32); } if (flags & FlagWithPagingState == FlagWithPagingState) { params.paging_state = try pr.readBytes(allocator); } if (flags & FlagWithSerialConsistency == FlagWithSerialConsistency) { const consistency_level = try pr.readConsistency(); if (consistency_level != .Serial and consistency_level != .LocalSerial) { return error.InvalidSerialConsistency; } params.serial_consistency_level = consistency_level; } if (flags & FlagWithDefaultTimestamp == FlagWithDefaultTimestamp) { const timestamp = try pr.readInt(u64); if (timestamp < 0) { return error.InvalidNegativeTimestamp; } params.timestamp = timestamp; } if (!protocol_version.is(5)) { return params; } // The following flags are only valid with protocol v5 if (flags & FlagWithKeyspace == FlagWithKeyspace) { params.keyspace = try pr.readString(allocator); } if (flags & FlagWithNowInSeconds == FlagWithNowInSeconds) { params.now_in_seconds = try pr.readInt(u32); } return params; } };
src/query_parameters.zig
const std = @import("std"); const sdk = @import("sdk"); const log = @import("log.zig"); const ifaces = @import("interface.zig").ifaces; const FontRecord = struct { name: [:0]const u8, tall: u32, const HashCtx = struct { pub fn eql(self: @This(), a: FontRecord, b: FontRecord) bool { _ = self; return a.tall == b.tall and std.mem.eql(u8, a.name, b.name); } pub fn hash(self: @This(), f: FontRecord) u64 { _ = self; return std.hash.Wyhash.hash(f.tall, f.name); } }; }; const FontMap = std.HashMap(FontRecord, sdk.HFont, FontRecord.HashCtx, std.hash_map.default_max_load_percentage); var font_map: FontMap = undefined; var handle_pool: std.ArrayList(sdk.HFont) = undefined; pub fn init(allocator: std.mem.Allocator) void { font_map = FontMap.init(allocator); handle_pool = std.ArrayList(sdk.HFont).init(allocator); } pub fn deinit() void { font_map.deinit(); handle_pool.deinit(); } pub fn findRawFont(name: [:0]const u8, tall: u32) ?sdk.HFont { if (font_map.get(.{ .name = name, .tall = tall })) |handle| return handle; const handle = handle_pool.popOrNull() orelse ifaces.ISurface.createFont(); if (ifaces.ISurface.setFontGlyphSet(handle, name, @intCast(c_int, tall), 80, 0, 0, 0, 0, 0)) { font_map.put(.{ .name = name, .tall = tall }, handle) catch {}; // TODO: make key persistent, i.e. owned memory. TODO: handle error return handle; } // We fucked up. Add the handle back to the pool handle_pool.append(handle) catch {}; // TODO: handle error return null; } const FcConfig = opaque {}; const FcPattern = opaque {}; const FcObjectSet = opaque {}; const FcFontSet = extern struct { nfont: c_int, sfont: c_int, fonts: [*]*FcPattern, }; extern "fontconfig" fn FcConfigGetCurrent() *FcConfig; extern "fontconfig" fn FcPatternCreate() *FcPattern; extern "fontconfig" fn FcObjectSetBuild(first: ?[*:0]const u8, ...) *FcObjectSet; extern "fontconfig" fn FcFontList(config: ?*FcConfig, p: *FcPattern, os: *FcObjectSet) *FcFontSet; extern "fontconfig" fn FcPatternGetString(pat: *FcPattern, object: [*:0]const u8, n: c_int, s: *[*:0]const u8) c_int; extern "fontconfig" fn FcPatternGetInteger(pat: *FcPattern, object: [*:0]const u8, n: c_int, i: *c_int) c_int; extern "fontconfig" fn FcFontSetDestroy(s: *FcFontSet) void; fn listFontsLinux() void { const config = FcConfigGetCurrent(); const pat = FcPatternCreate(); const os = FcObjectSetBuild("family", "file", "weight", @as(?[*:0]const u8, null)); const fs = FcFontList(config, pat, os); for (fs.fonts[0..@intCast(usize, fs.nfont)]) |font| { var name: [*:0]const u8 = undefined; var file: [*:0]const u8 = undefined; var weight: c_int = undefined; if (FcPatternGetString(font, "family", 0, &name) != 0) continue; if (FcPatternGetString(font, "file", 0, &file) != 0) continue; if (FcPatternGetInteger(font, "weight", 0, &weight) != 0 or weight != 80) continue; log.info("{s}\n", .{name}); } FcFontSetDestroy(fs); } const LOGFONT = extern struct { height: i32, width: i32, escapement: i32, orientation: i32, weight: i32, italic: u8, underline: u8, strikeout: u8, charset: u8, out_precision: u8, clip_precision: u8, quality: u8, pitch_and_family: u8, face_name: [32]u8, }; const HDC = ?*opaque {}; const FONTENUMPROCA = fn (*const LOGFONT, *const TEXTMETRIC, u32, ?*anyopaque) callconv(.Stdcall) c_int; const TEXTMETRIC = opaque {}; // don't care const WND = opaque {}; extern "gdi32" fn EnumFontFamiliesExA(hfc: HDC, logfont: *LOGFONT, proc: FONTENUMPROCA, param: ?*anyopaque, flags: u32) callconv(.Stdcall) c_int; extern "gdi32" fn GetDC(wnd: ?*WND) callconv(.Stdcall) HDC; extern "gdi32" fn ReleaseDC(wnd: ?*WND, hdc: HDC) callconv(.Stdcall) c_int; fn windowsEnumFontCbk(lf: *const LOGFONT, tm: *const TEXTMETRIC, font_type: u32, param: ?*anyopaque) callconv(.Stdcall) c_int { _ = tm; _ = font_type; _ = param; log.info("{s}\n", .{std.mem.sliceTo(&lf.face_name, 0)}); return 1; } fn listFontsWindows() void { const hdc = GetDC(null) orelse return; var logfont: LOGFONT = undefined; logfont.charset = 1; // DEFAULT_CHARSET logfont.face_name[0] = 0; logfont.pitch_and_family = 0; _ = EnumFontFamiliesExA(hdc, &logfont, windowsEnumFontCbk, null, 0); _ = ReleaseDC(null, hdc); } pub const listFonts = switch (@import("builtin").os.tag) { .windows => listFontsWindows, .linux => listFontsLinux, else => @compileError("Platform not supported"), };
src/font_manager.zig
const std = @import("std"); const log_ = @import("Log.zig"); const errLog_ = log_.errLog; const dbgLog_ = log_.dbgLog; const assert = std.debug.assert; const openssl = @import("OpenSSL.zig").openssl; const c_allocator = std.heap.c_allocator; const page_allocator = std.heap.page_allocator; const ObjectPool = @import("ObjectPool.zig").ObjectPool; const TCPServer = @import("TCPServer.zig"); const tls = @import("TLS.zig"); const MAX_BUFFER_SIZE = TCPServer.WRITE_BUFFER_SIZE; pub fn dbgLog(comptime s: []const u8, args: var) void { dbgLog_("TLSCustomBIO: " ++ s, args); } pub fn errLog(comptime s: []const u8, args: var) void { errLog_("TLSCustomBIO: " ++ s, args); } var bio_method: *openssl.BIO_METHOD = undefined; pub fn init() !void { const meth = openssl.BIO_meth_new(openssl.BIO_get_new_index() | openssl.BIO_TYPE_SOURCE_SINK, "Custom BIO"); if (meth == null) { return error.OutOfMemory; } bio_method = meth.?; _ = openssl.BIO_meth_set_write(bio_method, bioWrite); _ = openssl.BIO_meth_set_read(bio_method, bioRead); // _ = openssl.BIO_meth_set_puts(bio_method, bioPuts); // _ = openssl.BIO_meth_set_gets(bio_method, bioGets); _ = openssl.BIO_meth_set_create(bio_method, bioCreate); _ = openssl.BIO_meth_set_ctrl(bio_method, bioCtrl); _ = openssl.BIO_meth_set_destroy(bio_method, bioDestroy); // _ = openssl.BIO_meth_set_callback_ctrl(bio_method, bioCallbackCtrl); } // pub fn threadLocalInit() void { // } pub const CustomBIO = struct { bio: *openssl.BIO, // Not persistent, new buffer acquired for each write write_buffer: ?*([MAX_BUFFER_SIZE]u8) = null, data_length: u32 = 0, data_outgoing: bool = false, data_sent_confirmed: u32 = 0, next_read_data: ?[]const u8 = null, pub fn init(self: *CustomBIO) !void { const bio_ = openssl.BIO_new(bio_method); if (bio_ == null) { return error.OpenSSLError; } // _ = openssl.BIO_set_ex_data(bio_.?, 0, self); _ = openssl.BIO_set_data(bio_.?, self); self.* = CustomBIO{ .bio = bio_.? }; } pub fn canSendData(self: *CustomBIO, l: u32) bool { return !self.data_outgoing and self.data_length + l <= MAX_BUFFER_SIZE; } pub fn flush(self: *CustomBIO, conn: usize) !void { if (self.write_buffer == null) { return; } if (self.data_outgoing) { return error.WaitingOnPrevWrite; } self.data_outgoing = true; dbgLog("Sending {} bytes", .{self.data_length}); try TCPServer.sendData(conn, self.write_buffer.?.*[0..self.data_length], 0); } pub fn writeDone(self: *CustomBIO, conn: usize, data: []const u8) void { assert(self.data_outgoing); dbgLog("Write confirmed ({} bytes)", .{data.len}); if (self.data_outgoing) { self.data_sent_confirmed += @intCast(u32, data.len); if (self.data_sent_confirmed >= self.data_length) { dbgLog("Write finished ({} bytes)", .{self.data_length}); TCPServer.write_buffer_pool.free(self.write_buffer.?); self.write_buffer = null; self.data_sent_confirmed = 0; self.data_outgoing = false; self.data_length = 0; } else { dbgLog("Partial write. Written {}/{} bytes", .{ data.len, self.data_length }); } } self.flush(conn) catch {}; } }; export fn bioCreate(bio: ?*openssl.BIO) c_int { openssl.BIO_set_init(bio, 1); return 1; } export fn bioDestroy(bio: ?*openssl.BIO) c_int { openssl.BIO_set_init(bio, 0); var custom_BIO = @ptrCast(*CustomBIO, @alignCast(8, openssl.BIO_get_data(bio))); if (custom_BIO.write_buffer != null) { TCPServer.write_buffer_pool.free(custom_BIO.write_buffer.?); } dbgLog("BIO destroyed.", .{}); return 1; } // TODO: Can this copy be avoided? Maybe by taking control of OpenSSL's memory management fn fillWriteBuffer(custom_BIO: *CustomBIO, data: []const u8) !void { if (custom_BIO.write_buffer == null) { custom_BIO.write_buffer = try TCPServer.write_buffer_pool.alloc(); } std.mem.copy(u8, custom_BIO.write_buffer.?.*[custom_BIO.data_length .. custom_BIO.data_length + data.len], data); custom_BIO.data_length += @intCast(u32, data.len); } export fn bioWrite(bio: ?*openssl.BIO, data: [*c]const u8, data_len: c_int) c_int { assert(bio != null and data != null and data_len >= 0); openssl.BIO_clear_flags(bio, openssl.BIO_FLAGS_RWS | openssl.BIO_FLAGS_SHOULD_RETRY); if (data_len <= 0) { return 0; } var custom_BIO = @ptrCast(*CustomBIO, @alignCast(8, openssl.BIO_get_data(bio))); var cannot_write = false; if (custom_BIO.data_outgoing) { dbgLog("Data outgoing. cannot write", .{}); cannot_write = true; } if (custom_BIO.data_length + @intCast(u32, data_len) > MAX_BUFFER_SIZE) { dbgLog("Not enough space in buffer. cannot write", .{}); cannot_write = true; } fillWriteBuffer(custom_BIO, data[0..@intCast(u32, data_len)]) catch |e| { errLog("fillWriteBuffer error: {}", .{e}); cannot_write = true; }; if (cannot_write) { openssl.BIO_set_flags(bio, (openssl.BIO_FLAGS_WRITE | openssl.BIO_FLAGS_SHOULD_RETRY)); return -1; } dbgLog("Write {} bytes", .{data_len}); return data_len; } // TODO: Is there a way to avoid the copy? export fn bioRead(bio: ?*openssl.BIO, data: [*c]u8, data_len: c_int) c_int { assert(bio != null and data != null and data_len >= 0); if (data_len <= 0) { return 0; } var custom_BIO = @ptrCast(*CustomBIO, @alignCast(8, openssl.BIO_get_data(bio))); if (custom_BIO.next_read_data != null and custom_BIO.next_read_data.?.len == 0) { custom_BIO.next_read_data = null; } openssl.BIO_clear_flags(bio, openssl.BIO_FLAGS_RWS | openssl.BIO_FLAGS_SHOULD_RETRY); if (custom_BIO.next_read_data == null) { openssl.BIO_set_flags(bio, (openssl.BIO_FLAGS_READ | openssl.BIO_FLAGS_SHOULD_RETRY)); return -1; } var l = @intCast(usize, data_len); if (l > custom_BIO.next_read_data.?.len) { l = custom_BIO.next_read_data.?.len; } std.mem.copy(u8, data[0..l], custom_BIO.next_read_data.?[0..l]); if (l >= custom_BIO.next_read_data.?.len) { custom_BIO.next_read_data = null; } else { custom_BIO.next_read_data = custom_BIO.next_read_data.?[l..]; } // next_read_data is now null if all data is been read return @intCast(c_int, l); } export fn bioCtrl(bio: ?*openssl.BIO, cmd: c_int, larg: c_long, pargs: ?*c_void) c_long { if (cmd == openssl.BIO_CTRL_PENDING or cmd == openssl.BIO_CTRL_WPENDING) { return 0; } return 1; }
src/TLSCustomBIO.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const nfd = @import("nfd"); const nvg = @import("nanovg"); const gui = @import("gui"); const icons = @import("icons.zig"); const geometry = @import("gui/geometry.zig"); const Point = geometry.Point; const Rect = geometry.Rect; const col = @import("color.zig"); const ColorLayer = col.ColorLayer; const Clipboard = @import("Clipboard.zig"); const Document = @import("Document.zig"); const MessageBoxWidget = @import("MessageBoxWidget.zig"); const NewDocumentWidget = @import("NewDocumentWidget.zig"); const AboutDialogWidget = @import("AboutDialogWidget.zig"); const CanvasWidget = @import("CanvasWidget.zig"); const ColorPaletteWidget = @import("ColorPaletteWidget.zig"); const ColorPickerWidget = @import("ColorPickerWidget.zig"); const ColorForegroundBackgroundWidget = @import("ColorForegroundBackgroundWidget.zig"); const BlendModeWidget = @import("BlendModeWidget.zig"); const PreviewWidget = @import("PreviewWidget.zig"); pub const EditorWidget = @This(); widget: gui.Widget, allocator: Allocator, document: *Document, document_file_path: ?[]const u8 = null, has_unsaved_changes: bool = false, menu_bar: *gui.Toolbar, new_button: *gui.Button, open_button: *gui.Button, save_button: *gui.Button, saveas_button: *gui.Button, undo_button: *gui.Button, redo_button: *gui.Button, cut_button: *gui.Button, copy_button: *gui.Button, paste_button: *gui.Button, crop_tool_button: *gui.Button, select_tool_button: *gui.Button, draw_tool_button: *gui.Button, fill_tool_button: *gui.Button, mirror_h_tool_button: *gui.Button, mirror_v_tool_button: *gui.Button, rotate_ccw_tool_button: *gui.Button, rotate_cw_tool_button: *gui.Button, pixel_grid_button: *gui.Button, custom_grid_button: *gui.Button, snap_button: *gui.Button, custom_grid_x_spinner: *gui.Spinner(i32), custom_grid_y_spinner: *gui.Spinner(i32), zoom_label: *gui.Label, zoom_spinner: *gui.Spinner(f32), about_button: *gui.Button, status_bar: *gui.Toolbar, help_status_label: *gui.Label, tool_status_label: *gui.Label, image_status_label: *gui.Label, memory_status_label: *gui.Label, // help_text: [200]u8 = .{0} ** 200, tool_text: [100]u8 = .{0} ** 100, image_text: [40]u8 = .{0} ** 40, memory_text: [100]u8 = .{0} ** 100, message_box_widget: *MessageBoxWidget, message_box_result_context: usize = 0, onMessageBoxResultFn: ?fn (usize, MessageBoxWidget.Result) void = null, new_document_widget: *NewDocumentWidget, about_dialog_widget: *AboutDialogWidget, canvas: *CanvasWidget, palette_bar: *gui.Toolbar, palette_open_button: *gui.Button, palette_save_button: *gui.Button, palette_copy_button: *gui.Button, palette_paste_button: *gui.Button, palette_toggle_button: *gui.Button, color_palette: *ColorPaletteWidget, color_picker: *ColorPickerWidget, color_foreground_background: *ColorForegroundBackgroundWidget, blend_mode: *BlendModeWidget, preview: *PreviewWidget, panel_right: *gui.Panel, const Self = @This(); pub fn init(allocator: Allocator, rect: Rect(f32), vg: nvg) !*Self { var self = try allocator.create(Self); self.* = Self{ .widget = gui.Widget.init(allocator, rect), .allocator = allocator, .document = try Document.init(allocator, vg), .menu_bar = try gui.Toolbar.init(allocator, rect), .new_button = try gui.Button.init(allocator, rect, ""), .open_button = try gui.Button.init(allocator, rect, ""), .save_button = try gui.Button.init(allocator, rect, ""), .saveas_button = try gui.Button.init(allocator, rect, ""), .undo_button = try gui.Button.init(allocator, rect, ""), .redo_button = try gui.Button.init(allocator, rect, ""), .cut_button = try gui.Button.init(allocator, rect, ""), .copy_button = try gui.Button.init(allocator, rect, ""), .paste_button = try gui.Button.init(allocator, rect, ""), .crop_tool_button = try gui.Button.init(allocator, rect, ""), .select_tool_button = try gui.Button.init(allocator, rect, ""), .draw_tool_button = try gui.Button.init(allocator, rect, ""), .fill_tool_button = try gui.Button.init(allocator, rect, ""), .mirror_h_tool_button = try gui.Button.init(allocator, rect, ""), .mirror_v_tool_button = try gui.Button.init(allocator, rect, ""), .rotate_ccw_tool_button = try gui.Button.init(allocator, rect, ""), .rotate_cw_tool_button = try gui.Button.init(allocator, rect, ""), .pixel_grid_button = try gui.Button.init(allocator, rect, ""), .custom_grid_button = try gui.Button.init(allocator, rect, ""), .snap_button = try gui.Button.init(allocator, rect, ""), .custom_grid_x_spinner = try gui.Spinner(i32).init(allocator, Rect(f32).make(0, 0, 45, 20)), .custom_grid_y_spinner = try gui.Spinner(i32).init(allocator, Rect(f32).make(0, 0, 45, 20)), .zoom_label = try gui.Label.init(allocator, Rect(f32).make(0, 0, 37, 20), "Zoom:"), .zoom_spinner = try gui.Spinner(f32).init(allocator, Rect(f32).make(0, 0, 55, 20)), .about_button = try gui.Button.init(allocator, rect, ""), .status_bar = try gui.Toolbar.init(allocator, rect), .help_status_label = try gui.Label.init(allocator, Rect(f32).make(0, 0, 450, 20), ""), .tool_status_label = try gui.Label.init(allocator, Rect(f32).make(0, 0, 205, 20), ""), .image_status_label = try gui.Label.init(allocator, Rect(f32).make(0, 0, 100, 20), ""), .memory_status_label = try gui.Label.init(allocator, Rect(f32).make(0, 0, 80, 20), ""), .message_box_widget = try MessageBoxWidget.init(allocator, ""), .new_document_widget = try NewDocumentWidget.init(allocator, self), .about_dialog_widget = try AboutDialogWidget.init(allocator), .canvas = try CanvasWidget.init(allocator, Rect(f32).make(0, 24, rect.w, rect.h), self.document, vg), .palette_bar = try gui.Toolbar.init(allocator, Rect(f32).make(0, 0, 163, 24)), .palette_open_button = try gui.Button.init(allocator, rect, ""), .palette_save_button = try gui.Button.init(allocator, rect, ""), .palette_copy_button = try gui.Button.init(allocator, rect, ""), .palette_paste_button = try gui.Button.init(allocator, rect, ""), .palette_toggle_button = try gui.Button.init(allocator, rect, ""), .color_palette = try ColorPaletteWidget.init(allocator, Rect(f32).make(0, 0, 163, 163)), .color_picker = try ColorPickerWidget.init(allocator, Rect(f32).make(0, 0, 163, 117)), .color_foreground_background = try ColorForegroundBackgroundWidget.init(allocator, Rect(f32).make(0, 0, 66, 66), vg), .blend_mode = try BlendModeWidget.init(allocator, Rect(f32).make(66, 0, 163 - 66, 66), vg), .preview = try PreviewWidget.init(allocator, Rect(f32).make(0, 0, 163, 120), self.document, vg), .panel_right = try gui.Panel.init(allocator, Rect(f32).make(0, 0, 163, 200)), }; self.widget.onResizeFn = onResize; self.widget.onKeyDownFn = onKeyDown; self.widget.onClipboardUpdateFn = onClipboardUpdate; try self.initMenubar(); self.help_status_label.padding = 3; self.help_status_label.draw_border = true; self.help_status_label.widget.layout.grow = true; self.tool_status_label.padding = 3; self.tool_status_label.draw_border = true; self.image_status_label.padding = 3; self.image_status_label.draw_border = true; self.memory_status_label.padding = 3; self.memory_status_label.draw_border = true; self.status_bar.has_grip = true; // build status bar try self.status_bar.addWidget(&self.help_status_label.widget); try self.status_bar.addWidget(&self.tool_status_label.widget); try self.status_bar.addWidget(&self.image_status_label.widget); try self.status_bar.addWidget(&self.memory_status_label.widget); // add main widgets try self.widget.addChild(&self.menu_bar.widget); try self.widget.addChild(&self.canvas.widget); try self.widget.addChild(&self.palette_bar.widget); try self.palette_bar.addButton(self.palette_open_button); try self.palette_bar.addButton(self.palette_save_button); try self.palette_bar.addSeparator(); try self.palette_bar.addButton(self.palette_copy_button); try self.palette_bar.addButton(self.palette_paste_button); try self.palette_bar.addSeparator(); try self.palette_bar.addButton(self.palette_toggle_button); try self.widget.addChild(&self.color_palette.widget); try self.widget.addChild(&self.color_picker.widget); try self.widget.addChild(&self.color_foreground_background.widget); try self.widget.addChild(&self.blend_mode.widget); try self.widget.addChild(&self.preview.widget); try self.widget.addChild(&self.panel_right.widget); try self.widget.addChild(&self.status_bar.widget); configureToolbarButton(self.palette_open_button, icons.iconOpen, tryOpenPalette, "Open Palette"); configureToolbarButton(self.palette_save_button, icons.iconSave, trySavePalette, "Save Palette"); configureToolbarButton(self.palette_copy_button, icons.iconCopyEnabled, tryCopyPalette, "Copy Color"); configureToolbarButton(self.palette_paste_button, icons.iconPasteEnabled, tryPastePalette, "Paste Color"); configureToolbarButton(self.palette_toggle_button, icons.iconColorPalette, tryTogglePalette, "Toggle between 8-bit indexed mode and true color"); std.mem.copy(u8, self.document.colormap, &self.color_palette.colors); try self.document.history.reset(self.document); // so palette is part of first snapshot self.color_palette.onSelectionChangedFn = struct { fn selectionChanged(color_palette: *ColorPaletteWidget) void { if (color_palette.widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); if (color_palette.selected) |selected| { const color = color_palette.colors[4 * selected ..][0..4]; switch (editor.document.getBitmapType()) { .color => editor.color_picker.setRgb(color[0..3]), // in true color mode we don't set the alpha .indexed => editor.color_picker.setRgba(color), } editor.color_foreground_background.setActiveRgba(&editor.color_picker.color); switch (editor.color_foreground_background.active) { .foreground => { editor.document.foreground_color = editor.color_picker.color; editor.document.foreground_index = @truncate(u8, selected); }, .background => { editor.document.background_color = editor.color_picker.color; editor.document.background_index = @truncate(u8, selected); }, } } editor.checkClipboard(); } } }.selectionChanged; self.canvas.onColorPickedFn = struct { fn colorPicked(canvas: *CanvasWidget) void { if (canvas.widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); switch (editor.document.bitmap) { .color => editor.color_foreground_background.setRgba(.foreground, &editor.document.foreground_color), .indexed => { if (editor.color_foreground_background.active == .foreground) { editor.color_palette.setSelection(editor.document.foreground_index); } else { editor.color_foreground_background.setRgba(.foreground, &editor.document.foreground_color); } }, } } } }.colorPicked; self.canvas.onScaleChangedFn = struct { fn zoomChanged(canvas: *CanvasWidget, zoom: f32) void { if (canvas.widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); editor.zoom_spinner.setValue(zoom); } } }.zoomChanged; self.color_picker.onChangedFn = struct { fn changed(color_picker: *ColorPickerWidget) void { if (color_picker.widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); if (editor.color_palette.selected) |selected| { std.mem.copy(u8, editor.color_palette.colors[4 * selected ..][0..4], &color_picker.color); editor.updateDocumentPaletteAt(selected); } editor.color_foreground_background.setActiveRgba(&color_picker.color); switch (editor.color_foreground_background.active) { .foreground => editor.document.foreground_color = editor.color_picker.color, .background => editor.document.background_color = editor.color_picker.color, } } } }.changed; self.color_foreground_background.onChangedFn = struct { fn changed(color_foreground_background: *ColorForegroundBackgroundWidget, change_type: ColorForegroundBackgroundWidget.ChangeType) void { if (color_foreground_background.widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); const color = color_foreground_background.getActiveRgba(); switch (editor.document.getBitmapType()) { .color => { if (editor.color_palette.selected) |selected| { // In true color mode deselect const palette_color = editor.color_palette.colors[4 * selected ..][0..4]; if (!std.mem.eql(u8, palette_color[0..3], color[0..3])) { editor.color_palette.clearSelection(); } } editor.document.foreground_color = editor.color_foreground_background.getRgba(.foreground); editor.document.background_color = editor.color_foreground_background.getRgba(.background); }, .indexed => { if (change_type == .swap) { std.mem.swap(u8, &editor.document.foreground_index, &editor.document.background_index); } if (change_type == .active or change_type == .swap) { switch (color_foreground_background.active) { .foreground => editor.color_palette.selected = editor.document.foreground_index, .background => editor.color_palette.selected = editor.document.background_index, } } }, } editor.color_picker.setRgba(&color); } } }.changed; self.blend_mode.onChangedFn = struct { fn changed(blend_mode: *BlendModeWidget) void { if (blend_mode.widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); editor.document.blend_mode = blend_mode.active; } } }.changed; self.document.history.editor = self; // Register for updates self.updateLayout(); self.setTool(.draw); self.canvas.centerDocument(); self.updateImageStatus(); self.checkClipboard(); return self; } fn configureToolbarButton( button: *gui.Button, icon: fn (nvg) void, comptime onEditorClick: fn (*Self) void, comptime help_text: []const u8, ) void { button.iconFn = icon; button.onClickFn = struct { fn click(b: *gui.Button) void { onEditorClick(getEditorFromMenuButton(b)); } }.click; button.onEnterFn = struct { fn enter(b: *gui.Button) void { getEditorFromMenuButton(b).setHelpText(help_text); } }.enter; button.onLeaveFn = menuButtonOnLeave; } fn initMenubar(self: *Self) !void { configureToolbarButton(self.new_button, icons.iconNew, newDocument, "New Document (Ctrl+N)"); configureToolbarButton(self.open_button, icons.iconOpen, tryOpenDocument, "Open Document (Ctrl+O)"); configureToolbarButton(self.save_button, icons.iconSave, trySaveDocument, "Save Document (Ctrl+S)"); configureToolbarButton(self.saveas_button, icons.iconSaveAs, trySaveAsDocument, "Save Document As (Ctrl+Shift+S)"); configureToolbarButton(self.undo_button, icons.iconUndoDisabled, tryUndoDocument, "Undo Action (Ctrl+Z)"); configureToolbarButton(self.redo_button, icons.iconRedoDisabled, tryRedoDocument, "Redo Action (Ctrl+Y)"); configureToolbarButton(self.cut_button, icons.iconCut, cutDocument, "Cut Selection to Clipboard (Ctrl+X)"); configureToolbarButton(self.copy_button, icons.iconCopyEnabled, copyDocument, "Copy Selection to Clipboard (Ctrl+C)"); configureToolbarButton(self.paste_button, icons.iconPasteEnabled, pasteDocument, "Paste from Clipboard (Ctrl+V)"); configureToolbarButton(self.crop_tool_button, icons.iconToolCrop, setToolCrop, "Crop/Enlarge Tool (C)"); configureToolbarButton(self.select_tool_button, icons.iconToolSelect, setToolSelect, "Rectangle Select Tool (R)"); configureToolbarButton(self.draw_tool_button, icons.iconToolPen, setToolDraw, "Pen Tool (N)"); configureToolbarButton(self.fill_tool_button, icons.iconToolBucket, setToolFill, "Fill Tool (B)"); configureToolbarButton(self.mirror_h_tool_button, icons.iconMirrorHorizontally, mirrorHorizontallyDocument, "Mirror Horizontally"); configureToolbarButton(self.mirror_v_tool_button, icons.iconMirrorVertically, mirrorVerticallyDocument, "Mirror Vertically"); configureToolbarButton(self.rotate_ccw_tool_button, icons.iconRotateCcw, rotateDocumentCcw, "Rotate Counterclockwise"); configureToolbarButton(self.rotate_cw_tool_button, icons.iconRotateCw, rotateDocumentCw, "Rotate Clockwise"); configureToolbarButton(self.pixel_grid_button, icons.iconPixelGrid, togglePixelGrid, "Toggle Pixel Grid (#)"); self.pixel_grid_button.checked = self.canvas.pixel_grid_enabled; configureToolbarButton(self.custom_grid_button, icons.iconCustomGrid, toggleCustomGrid, "Toggle Custom Grid"); self.custom_grid_button.checked = self.canvas.pixel_grid_enabled; configureToolbarButton(self.snap_button, icons.iconSnapDisabled, toggleGridSnapping, "Toggle Grid Snapping"); self.snap_button.widget.enabled = false; self.snap_button.checked = self.canvas.grid_snapping_enabled; self.custom_grid_x_spinner.min_value = 2; self.custom_grid_x_spinner.max_value = 512; self.custom_grid_x_spinner.step_mode = .exponential; self.custom_grid_x_spinner.setValue(@intCast(i32, self.canvas.custom_grid_spacing_x)); self.custom_grid_x_spinner.widget.enabled = false; self.custom_grid_x_spinner.onChangedFn = struct { fn changed(spinner: *gui.Spinner(i32)) void { if (spinner.widget.parent) |menu_bar_widget| { if (menu_bar_widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); editor.canvas.custom_grid_spacing_x = @intCast(u32, spinner.value); } } } }.changed; self.custom_grid_y_spinner.min_value = 2; self.custom_grid_y_spinner.max_value = 512; self.custom_grid_y_spinner.step_mode = .exponential; self.custom_grid_y_spinner.setValue(@intCast(i32, self.canvas.custom_grid_spacing_y)); self.custom_grid_y_spinner.widget.enabled = false; self.custom_grid_y_spinner.onChangedFn = struct { fn changed(spinner: *gui.Spinner(i32)) void { if (spinner.widget.parent) |menu_bar_widget| { if (menu_bar_widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); editor.canvas.custom_grid_spacing_y = @intCast(u32, spinner.value); } } } }.changed; self.zoom_spinner.setValue(self.canvas.scale); self.zoom_spinner.min_value = CanvasWidget.min_scale; self.zoom_spinner.max_value = CanvasWidget.max_scale; //self.zoom_spinner.step_value = 0.5; self.zoom_spinner.step_mode = .exponential; self.zoom_spinner.onChangedFn = struct { fn changed(spinner: *gui.Spinner(f32)) void { if (spinner.widget.parent) |menu_bar_widget| { if (menu_bar_widget.parent) |parent| { var editor = @fieldParentPtr(EditorWidget, "widget", parent); const factor = spinner.value / editor.canvas.scale; editor.canvas.zoomToDocumentCenter(factor); } } } }.changed; configureToolbarButton(self.about_button, icons.iconAbout, showAboutDialog, "About Mini Pixel"); // build menu bar try self.menu_bar.addButton(self.new_button); try self.menu_bar.addButton(self.open_button); try self.menu_bar.addButton(self.save_button); try self.menu_bar.addButton(self.saveas_button); try self.menu_bar.addSeparator(); try self.menu_bar.addButton(self.undo_button); try self.menu_bar.addButton(self.redo_button); try self.menu_bar.addSeparator(); try self.menu_bar.addButton(self.cut_button); try self.menu_bar.addButton(self.copy_button); try self.menu_bar.addButton(self.paste_button); try self.menu_bar.addSeparator(); try self.menu_bar.addButton(self.crop_tool_button); try self.menu_bar.addButton(self.select_tool_button); try self.menu_bar.addButton(self.draw_tool_button); try self.menu_bar.addButton(self.fill_tool_button); try self.menu_bar.addSeparator(); try self.menu_bar.addButton(self.mirror_h_tool_button); try self.menu_bar.addButton(self.mirror_v_tool_button); try self.menu_bar.addButton(self.rotate_ccw_tool_button); try self.menu_bar.addButton(self.rotate_cw_tool_button); try self.menu_bar.addSeparator(); try self.menu_bar.addButton(self.pixel_grid_button); try self.menu_bar.addButton(self.custom_grid_button); try self.menu_bar.addButton(self.snap_button); try self.menu_bar.addWidget(&self.custom_grid_x_spinner.widget); try self.menu_bar.addWidget(&self.custom_grid_y_spinner.widget); try self.menu_bar.addSeparator(); try self.menu_bar.addWidget(&self.zoom_label.widget); try self.menu_bar.addWidget(&self.zoom_spinner.widget); try self.menu_bar.addSeparator(); try self.menu_bar.addButton(self.about_button); } pub fn deinit(self: *Self, vg: nvg) void { self.document.deinit(vg); if (self.document_file_path) |document_file_path| { self.allocator.free(document_file_path); } self.menu_bar.deinit(); self.new_button.deinit(); self.open_button.deinit(); self.save_button.deinit(); self.saveas_button.deinit(); self.undo_button.deinit(); self.redo_button.deinit(); self.cut_button.deinit(); self.copy_button.deinit(); self.paste_button.deinit(); self.crop_tool_button.deinit(); self.select_tool_button.deinit(); self.draw_tool_button.deinit(); self.fill_tool_button.deinit(); self.mirror_h_tool_button.deinit(); self.mirror_v_tool_button.deinit(); self.rotate_ccw_tool_button.deinit(); self.rotate_cw_tool_button.deinit(); self.pixel_grid_button.deinit(); self.custom_grid_button.deinit(); self.snap_button.deinit(); self.custom_grid_x_spinner.deinit(); self.custom_grid_y_spinner.deinit(); self.zoom_label.deinit(); self.zoom_spinner.deinit(); self.about_button.deinit(); self.status_bar.deinit(); self.help_status_label.deinit(); self.tool_status_label.deinit(); self.image_status_label.deinit(); self.memory_status_label.deinit(); self.message_box_widget.deinit(); self.new_document_widget.deinit(); self.about_dialog_widget.deinit(); self.canvas.deinit(vg); self.palette_bar.deinit(); self.palette_open_button.deinit(); self.palette_save_button.deinit(); self.palette_copy_button.deinit(); self.palette_paste_button.deinit(); self.palette_toggle_button.deinit(); self.color_palette.deinit(); self.color_picker.deinit(); self.color_foreground_background.deinit(vg); self.blend_mode.deinit(vg); self.preview.deinit(vg); self.panel_right.deinit(); self.widget.deinit(); self.allocator.destroy(self); } fn onResize(widget: *gui.Widget, event: *const gui.ResizeEvent) void { _ = event; const self = @fieldParentPtr(Self, "widget", widget); self.updateLayout(); } fn onKeyDown(widget: *gui.Widget, key_event: *gui.KeyEvent) void { const self = @fieldParentPtr(Self, "widget", widget); const shift_held = key_event.isModifierPressed(.shift); if (key_event.isModifierPressed(.ctrl)) { switch (key_event.key) { .N => self.newDocument(), .O => self.tryOpenDocument(), .S => if (shift_held) self.trySaveAsDocument() else self.trySaveDocument(), .Z => self.tryUndoDocument(), .Y => self.tryRedoDocument(), .A => self.selectAll(), .X => self.cutDocument(), .C => self.copyDocument(), .V => self.pasteDocument(), .Comma => self.fillDocument(.foreground), .Period => self.fillDocument(.background), else => key_event.event.ignore(), } } else if (key_event.modifiers == 0) { switch (key_event.key) { .C => self.setTool(.crop), // Crop .R => self.setTool(.select), // Rectangle select .N => self.setTool(.draw), // peNcil .B => self.setTool(.fill), // Bucket .X => self.color_foreground_background.swap(), .Hash => self.togglePixelGrid(), else => key_event.event.ignore(), } } else { key_event.event.ignore(); } } pub fn onUndoChanged(self: *Self, document: *Document) void { self.undo_button.widget.enabled = document.canUndo(); self.undo_button.iconFn = if (self.undo_button.widget.enabled) icons.iconUndoEnabled else icons.iconUndoDisabled; self.redo_button.widget.enabled = document.canRedo(); self.redo_button.iconFn = if (self.redo_button.widget.enabled) icons.iconRedoEnabled else icons.iconRedoDisabled; self.onDocumentChanged(); self.updateImageStatus(); self.has_unsaved_changes = true; self.updateWindowTitle(); } fn onClipboardUpdate(widget: *gui.Widget) void { const self = @fieldParentPtr(Self, "widget", widget); self.checkClipboard(); } fn checkClipboard(self: *Self) void { if (Clipboard.hasImage()) { self.paste_button.widget.enabled = true; self.paste_button.iconFn = icons.iconPasteEnabled; } else { self.paste_button.widget.enabled = false; self.paste_button.iconFn = icons.iconPasteDisabled; } if (self.color_palette.selected != null) { self.palette_copy_button.widget.enabled = true; self.palette_copy_button.iconFn = icons.iconCopyEnabled; } else { self.palette_copy_button.widget.enabled = false; self.palette_copy_button.iconFn = icons.iconCopyDisabled; } if (self.color_palette.selected != null and Clipboard.hasColor(self.allocator)) { self.palette_paste_button.widget.enabled = true; self.palette_paste_button.iconFn = icons.iconPasteEnabled; } else { self.palette_paste_button.widget.enabled = false; self.palette_paste_button.iconFn = icons.iconPasteDisabled; } } fn updateLayout(self: *Self) void { const rect = self.widget.relative_rect; const menu_bar_h = 24; const right_col_w = self.color_picker.widget.relative_rect.w; const canvas_w = rect.w - right_col_w; const canvas_h = rect.h - menu_bar_h - menu_bar_h; self.canvas.widget.relative_rect.x = 0; self.palette_bar.widget.relative_rect.x = canvas_w; self.color_palette.widget.relative_rect.x = canvas_w; self.color_picker.widget.relative_rect.x = canvas_w; self.color_foreground_background.widget.relative_rect.x = canvas_w; self.blend_mode.widget.relative_rect.x = canvas_w + self.color_foreground_background.widget.relative_rect.w; self.preview.widget.relative_rect.x = canvas_w; self.panel_right.widget.relative_rect.x = canvas_w; var y: f32 = menu_bar_h; self.canvas.widget.relative_rect.y = y; self.palette_bar.widget.relative_rect.y = y; self.palette_bar.widget.relative_rect.h = menu_bar_h; y += self.palette_bar.widget.relative_rect.h; self.color_palette.widget.relative_rect.y = y; y += self.color_palette.widget.relative_rect.h; self.color_picker.widget.relative_rect.y = y; y += self.color_picker.widget.relative_rect.h; self.color_foreground_background.widget.relative_rect.y = y; self.blend_mode.widget.relative_rect.y = y; y += self.color_foreground_background.widget.relative_rect.h; self.preview.widget.relative_rect.y = y; y += self.preview.widget.relative_rect.h; self.panel_right.widget.relative_rect.y = y; self.status_bar.widget.relative_rect.y = rect.h - menu_bar_h; self.menu_bar.widget.setSize(rect.w, menu_bar_h); self.panel_right.widget.setSize(right_col_w, std.math.max(0, menu_bar_h + canvas_h - self.panel_right.widget.relative_rect.y)); self.canvas.widget.setSize(canvas_w, canvas_h); self.status_bar.widget.setSize(rect.w, menu_bar_h); } pub fn showErrorMessageBox(self: *Self, title: [:0]const u8, message: []const u8) void { self.message_box_widget.setSize(240, 100); self.message_box_widget.configure(.@"error", .ok, message); self.onMessageBoxResultFn = null; self.showMessageBox(title); } pub fn showUnsavedChangesDialog(self: *Self, onResultFn: ?fn (usize, MessageBoxWidget.Result) void, result_context: usize) void { self.message_box_widget.setSize(280, 100); self.message_box_widget.configure(.question, .yes_no_cancel, "This file has been changed.\nWould you like to save those changes?"); self.message_box_widget.yes_button.text = "Save"; self.message_box_widget.no_button.text = "Discard"; self.onMessageBoxResultFn = onResultFn; self.message_box_result_context = result_context; self.showMessageBox("Unsaved changes"); } fn showMessageBox(self: *Self, title: [:0]const u8) void { if (self.widget.getWindow()) |parent_window| { var window_or_error = parent_window.createChildWindow( title, self.message_box_widget.widget.relative_rect.w, self.message_box_widget.widget.relative_rect.h, gui.Window.CreateOptions{ .resizable = false }, ); if (window_or_error) |window| { window.is_modal = true; window.setMainWidget(&self.message_box_widget.widget); self.message_box_widget.ok_button.widget.setFocus(true, .programmatic); self.message_box_widget.yes_button.widget.setFocus(true, .programmatic); window.closed_context = @ptrToInt(self); window.onClosedFn = onMessageBoxClosed; } else |_| {} } } fn onMessageBoxClosed(context: usize) void { const editor = @intToPtr(*EditorWidget, context); if (editor.onMessageBoxResultFn) |onMessageBoxResult| { onMessageBoxResult(editor.message_box_result_context, editor.message_box_widget.result); } } pub fn newDocument(self: *Self) void { // TODO if (self.widget.getWindow()) |parent_window| { var window_or_error = parent_window.createChildWindow( "New Document", self.new_document_widget.widget.relative_rect.w, self.new_document_widget.widget.relative_rect.h, gui.Window.CreateOptions{ .resizable = false }, ); if (window_or_error) |window| { window.is_modal = true; window.setMainWidget(&self.new_document_widget.widget); self.new_document_widget.width_spinner.setFocus(true, .keyboard); // keyboard will select text } else |_| { // TODO: show error } } } fn showAboutDialog(self: *Self) void { if (self.widget.getWindow()) |parent_window| { var window_or_error = parent_window.createChildWindow( "About", self.about_dialog_widget.widget.relative_rect.w, self.about_dialog_widget.widget.relative_rect.h, gui.Window.CreateOptions{ .resizable = false }, ); if (window_or_error) |window| { window.is_modal = true; window.setMainWidget(&self.about_dialog_widget.widget); self.about_dialog_widget.close_button.widget.setFocus(true, .programmatic); } else |_| { // TODO: show error } } } pub fn createNewDocument(self: *Self, width: u32, height: u32, bitmap_type: Document.BitmapType) !void { try self.document.createNew(width, height, bitmap_type); self.has_unsaved_changes = false; self.canvas.centerAndZoomDocument(); self.updateImageStatus(); try self.setDocumentFilePath(null); } fn loadDocument(self: *Self, file_path: []const u8) !void { try self.document.load(file_path); self.has_unsaved_changes = false; self.canvas.centerAndZoomDocument(); self.updateImageStatus(); try self.setDocumentFilePath(file_path); } pub fn tryLoadDocument(self: *Self, file_path: []const u8) void { self.loadDocument(file_path) catch { self.showErrorMessageBox("Load document", "Could not load document."); }; } fn openDocument(self: *Self) !void { if (try nfd.openFileDialog("png", null)) |nfd_file_path| { defer nfd.freePath(nfd_file_path); try self.loadDocument(nfd_file_path); } } fn tryOpenDocument(self: *Self) void { self.openDocument() catch { self.showErrorMessageBox("Open document", "Could not open document."); }; } fn saveDocument(self: *Self, force_save_as: bool) !void { if (force_save_as or self.document_file_path == null) { if (try nfd.saveFileDialog("png", null)) |nfd_file_path| { defer nfd.freePath(nfd_file_path); var png_file_path = try copyWithExtension(self.allocator, nfd_file_path, ".png"); defer self.allocator.free(png_file_path); try self.document.save(png_file_path); self.has_unsaved_changes = false; try self.setDocumentFilePath(png_file_path); } } else if (self.document_file_path) |document_file_path| { try self.document.save(document_file_path); self.has_unsaved_changes = false; self.updateWindowTitle(); } } pub fn trySaveDocument(self: *Self) void { self.saveDocument(false) catch { self.showErrorMessageBox("Save document", "Could not save document."); }; } pub fn trySaveAsDocument(self: *Self) void { self.saveDocument(true) catch { self.showErrorMessageBox("Save document", "Could not save document."); }; } fn tryUndoDocument(self: *Self) void { self.document.undo() catch { self.showErrorMessageBox("Undo", "Could not undo."); }; } fn tryRedoDocument(self: *Self) void { self.document.redo() catch { self.showErrorMessageBox("Redo", "Could not redo."); }; } fn selectAll(self: *Self) void { self.setTool(.select); if (self.document.selection) |_| { self.document.clearSelection() catch {}; // TODO } const w = @intCast(i32, self.document.getWidth()); const h = @intCast(i32, self.document.getHeight()); self.document.makeSelection(Rect(i32).make(0, 0, w, h)) catch {}; // TODO } fn cutDocument(self: *Self) void { self.document.cut() catch { self.showErrorMessageBox("Cut image", "Could not cut to clipboard."); return; }; self.checkClipboard(); } fn copyDocument(self: *Self) void { self.document.copy() catch { self.showErrorMessageBox("Copy image", "Could not copy to clipboard."); return; }; self.checkClipboard(); } fn pasteDocument(self: *Self) void { self.document.paste() catch { self.showErrorMessageBox("Paste image", "Could not paste from clipboard."); return; }; self.checkClipboard(); self.setTool(.select); } fn fillDocument(self: *Self, color_layer: ColorLayer) void { self.document.fill(color_layer) catch { self.showErrorMessageBox("Fill image", "Could not fill the image."); }; } fn mirrorHorizontallyDocument(self: *Self) void { self.document.mirrorHorizontally() catch { self.showErrorMessageBox("Mirror image", "Could not mirror the image."); }; } fn mirrorVerticallyDocument(self: *Self) void { self.document.mirrorVertically() catch { self.showErrorMessageBox("Mirror image", "Could not mirror the image."); }; } fn rotateDocumentCw(self: *Self) void { self.rotateDocument(true); } fn rotateDocumentCcw(self: *Self) void { self.rotateDocument(false); } fn rotateDocument(self: *Self, clockwise: bool) void { self.document.rotate(clockwise) catch { self.showErrorMessageBox("Rotate image", "Could not rotate the image."); }; } fn setToolCrop(self: *Self) void { self.setTool(.crop); } fn setToolSelect(self: *Self) void { self.setTool(.select); } fn setToolDraw(self: *Self) void { self.setTool(.draw); } fn setToolFill(self: *Self) void { self.setTool(.fill); } fn setTool(self: *Self, tool: CanvasWidget.ToolType) void { self.canvas.setTool(tool); self.crop_tool_button.checked = tool == .crop; self.select_tool_button.checked = tool == .select; self.draw_tool_button.checked = tool == .draw; self.fill_tool_button.checked = tool == .fill; self.setHelpText(self.getToolHelpText()); } fn togglePixelGrid(self: *Self) void { self.canvas.pixel_grid_enabled = !self.canvas.pixel_grid_enabled; self.pixel_grid_button.checked = self.canvas.pixel_grid_enabled; } fn toggleCustomGrid(self: *Self) void { self.canvas.custom_grid_enabled = !self.canvas.custom_grid_enabled; self.custom_grid_button.checked = self.canvas.custom_grid_enabled; self.snap_button.widget.enabled = self.canvas.custom_grid_enabled; self.snap_button.iconFn = if (self.canvas.custom_grid_enabled) icons.iconSnapEnabled else icons.iconSnapDisabled; self.custom_grid_x_spinner.widget.enabled = self.canvas.custom_grid_enabled; self.custom_grid_y_spinner.widget.enabled = self.canvas.custom_grid_enabled; } fn toggleGridSnapping(self: *Self) void { self.canvas.grid_snapping_enabled = !self.canvas.grid_snapping_enabled; self.snap_button.checked = self.canvas.grid_snapping_enabled; } fn openPalette(self: *Self) !void { if (try nfd.openFileDialog("pal", null)) |nfd_file_path| { defer nfd.freePath(nfd_file_path); try self.color_palette.loadPal(self.allocator, nfd_file_path); // TODO: ask for .map / .replace mode try self.updateDocumentPalette(.map); } } fn tryOpenPalette(self: *Self) void { self.openPalette() catch { self.showErrorMessageBox("Open palette", "Could not open palette."); }; } fn savePalette(self: *Self) !void { if (try nfd.saveFileDialog("pal", null)) |nfd_file_path| { defer nfd.freePath(nfd_file_path); const pal_file_path = try copyWithExtension(self.allocator, nfd_file_path, ".pal"); defer self.allocator.free(pal_file_path); try self.color_palette.writePal(pal_file_path); } } fn trySavePalette(self: *Self) void { self.savePalette() catch { self.showErrorMessageBox("Save palette", "Could not save palette."); }; } fn tryCopyPalette(self: *Self) void { if (self.color_palette.selected) |selected| { const c = self.color_palette.colors[4 * @as(usize, selected) ..][0..4]; Clipboard.setColor(self.allocator, .{ c[0], c[1], c[2], c[3] }) catch { self.showErrorMessageBox("Copy color", "Could not copy color."); return; }; self.checkClipboard(); } } fn tryPastePalette(self: *Self) void { if (Clipboard.getColor(self.allocator)) |color| { if (self.color_palette.selected) |selected| { std.mem.copy(u8, self.color_palette.colors[4 * @as(usize, selected) ..][0..4], &color); self.updateDocumentPaletteAt(selected); } self.color_foreground_background.setActiveRgba(&color); } else |_| { self.showErrorMessageBox("Paste color", "Could not paste color."); } } fn togglePalette(self: *Self) !void { if (self.palette_toggle_button.checked) { try self.document.convertToTruecolor(); } else { if (try self.document.canLosslesslyConvertToIndexed()) { try self.document.convertToIndexed(); } else { self.message_box_widget.setSize(190, 100); self.message_box_widget.configure(.warning, .ok_cancel, "Some colors will be lost\nduring conversion."); self.onMessageBoxResultFn = struct { fn onResult(context: usize, result: MessageBoxWidget.Result) void { if (result == .ok) { var editor = @intToPtr(*Self, context); editor.document.convertToIndexed() catch {}; // TODO: Can't show message box because the widget is in use } } }.onResult; self.message_box_result_context = @ptrToInt(self); std.debug.print("context {}\n", .{self.message_box_result_context}); self.showMessageBox("Toggle color mode"); } } } fn tryTogglePalette(self: *Self) void { self.togglePalette() catch { self.showErrorMessageBox("Toggle color mode", "Color conversion failed."); }; } fn onDocumentChanged(self: *Self) void { // update GUI std.mem.copy(u8, &self.color_palette.colors, self.document.colormap); switch (self.document.bitmap) { .color => { self.palette_toggle_button.checked = false; self.color_palette.selection_locked = false; std.mem.copy(u8, &self.document.foreground_color, &self.color_foreground_background.getRgba(.foreground)); std.mem.copy(u8, &self.document.background_color, &self.color_foreground_background.getRgba(.background)); self.blend_mode.widget.enabled = true; }, .indexed => { self.palette_toggle_button.checked = true; // find nearest colors in colormap const fgc = self.color_foreground_background.getRgba(.foreground); var dfgc = self.document.colormap[4 * @as(usize, self.document.foreground_index) ..][0..4]; if (!std.mem.eql(u8, &fgc, dfgc)) { self.document.foreground_index = @truncate(u8, col.findNearest(self.document.colormap, &fgc)); dfgc = self.document.colormap[4 * @as(usize, self.document.foreground_index) ..][0..4]; self.color_foreground_background.setRgba(.foreground, dfgc); } const bgc = self.color_foreground_background.getRgba(.background); var dbgc = self.document.colormap[4 * @as(usize, self.document.background_index) ..][0..4]; if (!std.mem.eql(u8, &bgc, dbgc)) { self.document.background_index = @truncate(u8, col.findNearest(self.document.colormap, &bgc)); dbgc = self.document.colormap[4 * @as(usize, self.document.background_index) ..][0..4]; self.color_foreground_background.setRgba(.background, dbgc); } self.color_palette.selection_locked = true; switch (self.color_foreground_background.active) { .foreground => self.color_palette.setSelection(self.document.foreground_index), .background => self.color_palette.setSelection(self.document.background_index), } self.blend_mode.widget.enabled = false; }, } } fn updateDocumentPalette(self: *Self, mode: Document.PaletteUpdateMode) !void { try self.document.applyPalette(&self.color_palette.colors, mode); } fn updateDocumentPaletteAt(self: *Self, i: usize) void { std.mem.copy(u8, self.document.colormap[4 * i .. 4 * i + 4], self.color_palette.colors[4 * i .. 4 * i + 4]); self.document.need_texture_update = true; } fn setDocumentFilePath(self: *Self, maybe_file_path: ?[]const u8) !void { if (self.document_file_path) |document_file_path| { self.allocator.free(document_file_path); } if (maybe_file_path) |file_path| { self.document_file_path = try self.allocator.dupe(u8, file_path); } else { self.document_file_path = null; } self.updateWindowTitle(); } var window_title_buffer: [1024]u8 = undefined; fn updateWindowTitle(self: *Self) void { if (self.widget.getWindow()) |window| { const unsaved_changes_indicator = if (self.has_unsaved_changes) "● " else ""; const document_title = if (self.document_file_path) |file_path| std.fs.path.basename(file_path) else "Untitled"; const title = std.fmt.bufPrintZ( &window_title_buffer, "{s}{s} - Mini Pixel", .{ unsaved_changes_indicator, document_title }, ) catch unreachable; window.setTitle(title); } } fn setHelpText(self: *Self, help_text: []const u8) void { self.help_status_label.text = help_text; } fn getToolHelpText(self: Self) []const u8 { return switch (self.canvas.tool) { .crop => "Drag to create crop region, double click region to apply, right click to cancel", .select => "Drag to create selection, right click to cancel selection", .draw => "Left click to draw, right click to pick color, hold shift to draw line", .fill => "Left click to flood fill, right click to pick color", }; } pub fn updateImageStatus(self: *Self) void { self.image_status_label.text = std.fmt.bufPrintZ( self.image_text[0..], "{d}x{d}@{d}", .{ self.document.getWidth(), self.document.getHeight(), self.document.getColorDepth() }, ) catch unreachable; } pub fn setMemoryUsageInfo(self: *Self, bytes: usize) void { var unit = "KiB"; var fb = @intToFloat(f32, bytes) / 1024.0; if (bytes > 1 << 20) { unit = "MiB"; fb /= 1024.0; } self.memory_status_label.text = std.fmt.bufPrintZ( self.memory_text[0..], "{d:.2} {s}", .{ fb, unit }, ) catch unreachable; } fn hasExtension(filename: []const u8, extension: []const u8) bool { return std.ascii.eqlIgnoreCase(std.fs.path.extension(filename), extension); } fn copyWithExtension(allocator: Allocator, filename: []const u8, extension: []const u8) ![]const u8 { return (if (!hasExtension(filename, extension)) try std.mem.concat(allocator, u8, &.{ filename, extension }) else try allocator.dupe(u8, filename)); } fn getEditorFromMenuButton(menu_button: *gui.Button) *Self { if (menu_button.widget.parent) |menu_bar_widget| { if (menu_bar_widget.parent) |parent| { return @fieldParentPtr(EditorWidget, "widget", parent); } } unreachable; // forgot to add button to the menu_bar } fn menuButtonOnLeave(menu_button: *gui.Button) void { const editor = getEditorFromMenuButton(menu_button); editor.setHelpText(editor.getToolHelpText()); }
src/EditorWidget.zig
const DaisyChain = @This(); state: u8 = 0, vector: u8 = 0, // shared pins relevant for interrupt handling pub const M1: u64 = 1<<24; // machine cycle 1 pub const IORQ: u64 = 1<<26; // IO request pub const INT: u64 = 1<<31; // maskable interrupt requested pub const IEIO: u64 = 1<<37; // interrupt daisy chain: interrupt-enable-I/O pub const RETI: u64 = 1<<38; // interrupt daisy chain: RETI decoded pub const INT_NEEDED: u3 = 1<<0; // interrupt request needed pub const INT_REQUESTED: u3 = 1<<1; // interrupt request issued, waiting for ACK from CPU pub const INT_SERVICING: u3 = 1<<2; // interrupt was acknoledged, now serving // reset the daisychain state pub fn reset(self: *DaisyChain) void { self.state = 0; } // request an interrupt pub fn irq(self: *DaisyChain) void { self.state = INT_NEEDED; } pub fn tick(self: *DaisyChain, in_pins: u64) u64 { var pins = in_pins; // - set status of IEO pin depending on IEI pin and current // channel's interrupt request/acknowledge status, this // 'ripples' to the next channel and downstream interrupt // controllers // // - the IEO pin will be set to inactive (interrupt disabled) // when: (1) the IEI pin is inactive, or (2) the IEI pin is // active and and an interrupt has been requested // // - if an interrupt has been requested but not ackowledged by // the CPU because interrupts are disabled, the RETI state // must be passed to downstream devices. If a RETI is // received in the interrupt-requested state, the IEIO // pin will be set to active, so that downstream devices // get a chance to decode the RETI // // if any higher priority device in the daisy chain has cleared // the IEIO pin, skip interrupt handling // if ((0 != (pins & IEIO)) and (0 != self.state)) { // check if if the CPU has decoded a RETI if (0 != (pins & RETI)) { // if we're the device that's currently under service by // the CPU, keep interrupts enabled for downstream devices and // clear our interrupt state (this is basically the // 'HELP' logic described in the PIO and CTC manuals // if (0 != (self.state & INT_SERVICING)) { self.state = 0; } // if we are *NOT* the device currently under service, this // means we have an interrupt request pending but the CPU // denied the request (because interruprs were disabled) // } // need to request interrupt? if (0 != (self.state & INT_NEEDED)) { self.state &= ~INT_NEEDED; self.state |= INT_REQUESTED; } // need to place interrupt vector on data bus? if ((pins & (IORQ|M1)) == (IORQ|M1)) { // CPU has acknowledged the interrupt, place interrupt vector on data bus pins = setData(pins, self.vector); self.state &= ~INT_REQUESTED; self.state |= INT_SERVICING; } // disable interrupts for downstream devices? if (0 != self.state) { pins &= ~IEIO; } // set INT pin state during INT_REQUESTED if (0 != (self.state & INT_REQUESTED)) { pins |= INT; } } return pins; } fn setData(pins: u64, data: u8) u64 { const DataPinShift = 16; const DataPinMask: u64 = 0xFF0000; return (pins & ~DataPinMask) | (@as(u64, data) << DataPinShift); }
src/emu/DaisyChain.zig
const std = @import("std"); const builtin = @import("builtin"); var gpa = std.heap.GeneralPurposeAllocator(.{ .safety = true, }){}; pub const VM = opaque { pub extern fn bz_newVM(self: *VM) *VM; pub extern fn bz_deinitVM(self: *VM) void; pub extern fn bz_compile(self: *VM, source: [*:0]const u8, file_name: [*:0]const u8) ?*ObjFunction; pub extern fn bz_interpret(self: *VM, function: *ObjFunction) bool; pub extern fn bz_push(self: *VM, value: *Value) void; pub extern fn bz_pop(self: *VM) *Value; pub extern fn bz_peek(self: *VM, distance: u32) *Value; pub extern fn bz_pushBool(self: *VM, value: bool) void; pub extern fn bz_pushNum(self: *VM, value: f64) void; pub extern fn bz_pushString(self: *VM, value: *ObjString) void; pub extern fn bz_pushList(self: *VM, value: *ObjList) void; pub extern fn bz_pushNull(self: *VM) void; pub extern fn bz_pushVoid(self: *VM) void; pub extern fn bz_throw(vm: *VM, value: *Value) void; pub extern fn bz_throwString(vm: *VM, message: [*:0]const u8) void; pub extern fn bz_allocated(self: *VM) usize; pub extern fn bz_collect(self: *VM) bool; pub var allocator: std.mem.Allocator = if (builtin.mode == .Debug) gpa.allocator() else std.heap.c_allocator; }; pub const Value = opaque { pub extern fn bz_valueToBool(value: *Value) bool; pub extern fn bz_valueToString(value: *Value) ?[*:0]const u8; pub extern fn bz_valueToNumber(value: *Value) f64; }; pub const ObjTypeDef = opaque { pub extern fn bz_boolType() ?*ObjTypeDef; pub extern fn bz_stringType() ?*ObjTypeDef; pub extern fn bz_voidType() ?*ObjTypeDef; pub extern fn bz_newFunctionType(name: [*:0]const u8, return_type: ?*ObjTypeDef) ?*ObjTypeDef; pub extern fn bz_addFunctionArgument(function_type: *ObjTypeDef, name: [*:0]const u8, arg_type: *ObjTypeDef) bool; }; pub const ObjString = opaque { pub extern fn bz_string(vm: *VM, string: [*:0]const u8) ?*ObjString; }; pub const ObjList = opaque { pub extern fn bz_newList(vm: *VM, of_type: *ObjTypeDef) ?*ObjList; pub extern fn bz_listAppend(self: *ObjList, value: *Value) bool; pub extern fn bz_valueToList(value: *Value) *ObjList; pub extern fn bz_listGet(self: *ObjList, index: usize) *Value; pub extern fn bz_listLen(self: *ObjList) usize; }; pub const ObjFunction = opaque {}; pub const UserData = opaque {}; pub const ObjUserData = opaque { pub extern fn bz_newUserData(vm: *VM, userdata: *UserData) ?*ObjUserData; };
lib/buzz_api.zig
const Dylib = @This(); const std = @import("std"); const fs = std.fs; const log = std.log.scoped(.dylib); const macho = std.macho; const mem = std.mem; const Allocator = mem.Allocator; const Symbol = @import("Symbol.zig"); usingnamespace @import("commands.zig"); allocator: *Allocator, arch: ?std.Target.Cpu.Arch = null, header: ?macho.mach_header_64 = null, file: ?fs.File = null, name: ?[]const u8 = null, ordinal: ?u16 = null, load_commands: std.ArrayListUnmanaged(LoadCommand) = .{}, symtab_cmd_index: ?u16 = null, dysymtab_cmd_index: ?u16 = null, id_cmd_index: ?u16 = null, id: ?Id = null, symbols: std.StringArrayHashMapUnmanaged(*Symbol) = .{}, pub const Id = struct { name: []const u8, timestamp: u32, current_version: u32, compatibility_version: u32, pub fn deinit(id: *Id, allocator: *Allocator) void { allocator.free(id.name); } }; pub fn init(allocator: *Allocator) Dylib { return .{ .allocator = allocator }; } pub fn deinit(self: *Dylib) void { for (self.load_commands.items) |*lc| { lc.deinit(self.allocator); } self.load_commands.deinit(self.allocator); for (self.symbols.items()) |entry| { entry.value.deinit(self.allocator); self.allocator.destroy(entry.value); } self.symbols.deinit(self.allocator); if (self.name) |name| { self.allocator.free(name); } if (self.id) |*id| { id.deinit(self.allocator); } } pub fn closeFile(self: Dylib) void { if (self.file) |file| { file.close(); } } pub fn parse(self: *Dylib) !void { log.debug("parsing shared library '{s}'", .{self.name.?}); var reader = self.file.?.reader(); self.header = try reader.readStruct(macho.mach_header_64); if (self.header.?.filetype != macho.MH_DYLIB) { log.err("invalid filetype: expected 0x{x}, found 0x{x}", .{ macho.MH_DYLIB, self.header.?.filetype }); return error.MalformedDylib; } const this_arch: std.Target.Cpu.Arch = switch (self.header.?.cputype) { macho.CPU_TYPE_ARM64 => .aarch64, macho.CPU_TYPE_X86_64 => .x86_64, else => |value| { log.err("unsupported cpu architecture 0x{x}", .{value}); return error.UnsupportedCpuArchitecture; }, }; if (this_arch != self.arch.?) { log.err("mismatched cpu architecture: expected {s}, found {s}", .{ self.arch.?, this_arch }); return error.MismatchedCpuArchitecture; } try self.readLoadCommands(reader); try self.parseId(); try self.parseSymbols(); } pub fn readLoadCommands(self: *Dylib, reader: anytype) !void { try self.load_commands.ensureCapacity(self.allocator, self.header.?.ncmds); var i: u16 = 0; while (i < self.header.?.ncmds) : (i += 1) { var cmd = try LoadCommand.read(self.allocator, reader); switch (cmd.cmd()) { macho.LC_SYMTAB => { self.symtab_cmd_index = i; }, macho.LC_DYSYMTAB => { self.dysymtab_cmd_index = i; }, macho.LC_ID_DYLIB => { self.id_cmd_index = i; }, else => { log.debug("Unknown load command detected: 0x{x}.", .{cmd.cmd()}); }, } self.load_commands.appendAssumeCapacity(cmd); } } pub fn parseId(self: *Dylib) !void { const index = self.id_cmd_index orelse { log.debug("no LC_ID_DYLIB load command found; using hard-coded defaults...", .{}); self.id = .{ .name = try self.allocator.dupe(u8, self.name.?), .timestamp = 2, .current_version = 0, .compatibility_version = 0, }; return; }; const id_cmd = self.load_commands.items[index].Dylib; const dylib = id_cmd.inner.dylib; // TODO should we compare the name from the dylib's id with the user-specified one? const dylib_name = @ptrCast([*:0]const u8, id_cmd.data[dylib.name - @sizeOf(macho.dylib_command) ..]); const name = try self.allocator.dupe(u8, mem.spanZ(dylib_name)); self.id = .{ .name = name, .timestamp = dylib.timestamp, .current_version = dylib.current_version, .compatibility_version = dylib.compatibility_version, }; } pub fn parseSymbols(self: *Dylib) !void { const index = self.symtab_cmd_index orelse return; const symtab_cmd = self.load_commands.items[index].Symtab; var symtab = try self.allocator.alloc(u8, @sizeOf(macho.nlist_64) * symtab_cmd.nsyms); defer self.allocator.free(symtab); _ = try self.file.?.preadAll(symtab, symtab_cmd.symoff); const slice = @alignCast(@alignOf(macho.nlist_64), mem.bytesAsSlice(macho.nlist_64, symtab)); var strtab = try self.allocator.alloc(u8, symtab_cmd.strsize); defer self.allocator.free(strtab); _ = try self.file.?.preadAll(strtab, symtab_cmd.stroff); for (slice) |sym| { const sym_name = mem.spanZ(@ptrCast([*:0]const u8, strtab.ptr + sym.n_strx)); if (!(Symbol.isSect(sym) and Symbol.isExt(sym))) continue; const name = try self.allocator.dupe(u8, sym_name); const proxy = try self.allocator.create(Symbol.Proxy); errdefer self.allocator.destroy(proxy); proxy.* = .{ .base = .{ .@"type" = .proxy, .name = name, }, .dylib = self, }; try self.symbols.putNoClobber(self.allocator, name, &proxy.base); } }
src/link/MachO/Dylib.zig
const std = @import("../../../std.zig"); const linux = std.os.linux; const socklen_t = linux.socklen_t; const iovec = linux.iovec; const iovec_const = linux.iovec_const; const uid_t = linux.uid_t; const gid_t = linux.gid_t; const stack_t = linux.stack_t; const sigset_t = linux.sigset_t; pub const SYS = extern enum(usize) { io_setup = 0, io_destroy = 1, io_submit = 2, io_cancel = 3, io_getevents = 4, setxattr = 5, lsetxattr = 6, fsetxattr = 7, getxattr = 8, lgetxattr = 9, fgetxattr = 10, listxattr = 11, llistxattr = 12, flistxattr = 13, removexattr = 14, lremovexattr = 15, fremovexattr = 16, getcwd = 17, lookup_dcookie = 18, eventfd2 = 19, epoll_create1 = 20, epoll_ctl = 21, epoll_pwait = 22, dup = 23, dup3 = 24, fcntl = 25, inotify_init1 = 26, inotify_add_watch = 27, inotify_rm_watch = 28, ioctl = 29, ioprio_set = 30, ioprio_get = 31, flock = 32, mknodat = 33, mkdirat = 34, unlinkat = 35, symlinkat = 36, linkat = 37, renameat = 38, umount2 = 39, mount = 40, pivot_root = 41, nfsservctl = 42, statfs = 43, fstatfs = 44, truncate = 45, ftruncate = 46, fallocate = 47, faccessat = 48, chdir = 49, fchdir = 50, chroot = 51, fchmod = 52, fchmodat = 53, fchownat = 54, fchown = 55, openat = 56, close = 57, vhangup = 58, pipe2 = 59, quotactl = 60, getdents64 = 61, lseek = 62, read = 63, write = 64, readv = 65, writev = 66, pread64 = 67, pwrite64 = 68, preadv = 69, pwritev = 70, sendfile = 71, pselect6 = 72, ppoll = 73, signalfd4 = 74, vmsplice = 75, splice = 76, tee = 77, readlinkat = 78, fstatat = 79, fstat = 80, sync = 81, fsync = 82, fdatasync = 83, sync_file_range2 = 84, sync_file_range = 84, timerfd_create = 85, timerfd_settime = 86, timerfd_gettime = 87, utimensat = 88, acct = 89, capget = 90, capset = 91, personality = 92, exit = 93, exit_group = 94, waitid = 95, set_tid_address = 96, unshare = 97, futex = 98, set_robust_list = 99, get_robust_list = 100, nanosleep = 101, getitimer = 102, setitimer = 103, kexec_load = 104, init_module = 105, delete_module = 106, timer_create = 107, timer_gettime = 108, timer_getoverrun = 109, timer_settime = 110, timer_delete = 111, clock_settime = 112, clock_gettime = 113, clock_getres = 114, clock_nanosleep = 115, syslog = 116, ptrace = 117, sched_setparam = 118, sched_setscheduler = 119, sched_getscheduler = 120, sched_getparam = 121, sched_setaffinity = 122, sched_getaffinity = 123, sched_yield = 124, sched_get_priority_max = 125, sched_get_priority_min = 126, sched_rr_get_interval = 127, restart_syscall = 128, kill = 129, tkill = 130, tgkill = 131, sigaltstack = 132, rt_sigsuspend = 133, rt_sigaction = 134, rt_sigprocmask = 135, rt_sigpending = 136, rt_sigtimedwait = 137, rt_sigqueueinfo = 138, rt_sigreturn = 139, setpriority = 140, getpriority = 141, reboot = 142, setregid = 143, setgid = 144, setreuid = 145, setuid = 146, setresuid = 147, getresuid = 148, setresgid = 149, getresgid = 150, setfsuid = 151, setfsgid = 152, times = 153, setpgid = 154, getpgid = 155, getsid = 156, setsid = 157, getgroups = 158, setgroups = 159, uname = 160, sethostname = 161, setdomainname = 162, getrlimit = 163, setrlimit = 164, getrusage = 165, umask = 166, prctl = 167, getcpu = 168, gettimeofday = 169, settimeofday = 170, adjtimex = 171, getpid = 172, getppid = 173, getuid = 174, geteuid = 175, getgid = 176, getegid = 177, gettid = 178, sysinfo = 179, mq_open = 180, mq_unlink = 181, mq_timedsend = 182, mq_timedreceive = 183, mq_notify = 184, mq_getsetattr = 185, msgget = 186, msgctl = 187, msgrcv = 188, msgsnd = 189, semget = 190, semctl = 191, semtimedop = 192, semop = 193, shmget = 194, shmctl = 195, shmat = 196, shmdt = 197, socket = 198, socketpair = 199, bind = 200, listen = 201, accept = 202, connect = 203, getsockname = 204, getpeername = 205, sendto = 206, recvfrom = 207, setsockopt = 208, getsockopt = 209, shutdown = 210, sendmsg = 211, recvmsg = 212, readahead = 213, brk = 214, munmap = 215, mremap = 216, add_key = 217, request_key = 218, keyctl = 219, clone = 220, execve = 221, mmap = 222, fadvise64 = 223, swapon = 224, swapoff = 225, mprotect = 226, msync = 227, mlock = 228, munlock = 229, mlockall = 230, munlockall = 231, mincore = 232, madvise = 233, remap_file_pages = 234, mbind = 235, get_mempolicy = 236, set_mempolicy = 237, migrate_pages = 238, move_pages = 239, rt_tgsigqueueinfo = 240, perf_event_open = 241, accept4 = 242, recvmmsg = 243, arch_specific_syscall = 244, wait4 = 260, prlimit64 = 261, fanotify_init = 262, fanotify_mark = 263, clock_adjtime = 266, syncfs = 267, setns = 268, sendmmsg = 269, process_vm_readv = 270, process_vm_writev = 271, kcmp = 272, finit_module = 273, sched_setattr = 274, sched_getattr = 275, renameat2 = 276, seccomp = 277, getrandom = 278, memfd_create = 279, bpf = 280, execveat = 281, userfaultfd = 282, membarrier = 283, mlock2 = 284, copy_file_range = 285, preadv2 = 286, pwritev2 = 287, pkey_mprotect = 288, pkey_alloc = 289, pkey_free = 290, statx = 291, io_pgetevents = 292, rseq = 293, kexec_file_load = 294, pidfd_send_signal = 424, io_uring_setup = 425, io_uring_enter = 426, io_uring_register = 427, open_tree = 428, move_mount = 429, fsopen = 430, fsconfig = 431, fsmount = 432, fspick = 433, pidfd_open = 434, clone3 = 435, openat2 = 437, pidfd_getfd = 438, _, }; 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 = 0o40000; pub const O_NOFOLLOW = 0o100000; pub const O_CLOEXEC = 0o2000000; pub const O_ASYNC = 0o20000; pub const O_DIRECT = 0o200000; pub const O_LARGEFILE = 0o400000; pub const O_NOATIME = 0o1000000; pub const O_PATH = 0o10000000; pub const O_TMPFILE = 0o20040000; 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; /// 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 = "__kernel_clock_gettime"; pub const VDSO_CGT_VER = "LINUX_2.6.39"; 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 blksize_t = i32; pub const nlink_t = u32; pub const time_t = isize; pub const mode_t = u32; pub const off_t = isize; pub const ino_t = usize; pub const dev_t = usize; pub const blkcnt_t = isize; /// 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: dev_t, ino: ino_t, mode: mode_t, nlink: nlink_t, uid: uid_t, gid: gid_t, rdev: dev_t, __pad: usize, size: off_t, blksize: blksize_t, __pad2: i32, blocks: blkcnt_t, atim: timespec, mtim: timespec, ctim: timespec, __unused: [2]u32, pub fn atime(self: 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: time_t, 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 mcontext_t = extern struct { fault_address: usize, regs: [31]usize, sp: usize, pc: usize, pstate: usize, // Make sure the field is correctly aligned since this area // holds various FP/vector registers reserved1: [256 * 16]u8 align(16), }; pub const ucontext_t = extern struct { flags: usize, link: *ucontext_t, stack: stack_t, sigmask: sigset_t, mcontext: mcontext_t, }; pub const Elf_Symndx = u32;
lib/std/os/bits/linux/arm64.zig
const std = @import("std"); const builtin = std.builtin; const is_test = builtin.is_test; const is_gnu = std.Target.current.abi.isGnu(); const is_mingw = builtin.os.tag == .windows and is_gnu; comptime { const linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Weak; const strong_linkage = if (is_test) builtin.GlobalLinkage.Internal else builtin.GlobalLinkage.Strong; switch (builtin.arch) { .i386, .x86_64 => @export(@import("compiler_rt/stack_probe.zig").zig_probe_stack, .{ .name = "__zig_probe_stack", .linkage = linkage }), .aarch64, .aarch64_be, .aarch64_32 => { @export(@import("compiler_rt/clear_cache.zig").clear_cache, .{ .name = "__clear_cache", .linkage = linkage }); }, else => {}, } @export(@import("compiler_rt/compareXf2.zig").__lesf2, .{ .name = "__lesf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__ledf2, .{ .name = "__ledf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__letf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__gesf2, .{ .name = "__gesf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__gedf2, .{ .name = "__gedf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__getf2, .{ .name = "__getf2", .linkage = linkage }); if (!is_test) { @export(@import("compiler_rt/compareXf2.zig").__lesf2, .{ .name = "__cmpsf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__ledf2, .{ .name = "__cmpdf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__cmptf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__eqsf2, .{ .name = "__eqsf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__eqdf2, .{ .name = "__eqdf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__eqtf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__ltsf2, .{ .name = "__ltsf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__ltdf2, .{ .name = "__ltdf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__lttf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__nesf2, .{ .name = "__nesf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__nedf2, .{ .name = "__nedf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__letf2, .{ .name = "__netf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__gtsf2, .{ .name = "__gtsf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__gtdf2, .{ .name = "__gtdf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__getf2, .{ .name = "__gttf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendhfsf2, .{ .name = "__gnu_h2f_ieee", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncsfhf2, .{ .name = "__gnu_f2h_ieee", .linkage = linkage }); } @export(@import("compiler_rt/compareXf2.zig").__unordsf2, .{ .name = "__unordsf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__unorddf2, .{ .name = "__unorddf2", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__unordtf2, .{ .name = "__unordtf2", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__addsf3, .{ .name = "__addsf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__adddf3, .{ .name = "__adddf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__addtf3, .{ .name = "__addtf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__subsf3, .{ .name = "__subsf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__subdf3, .{ .name = "__subdf3", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__subtf3, .{ .name = "__subtf3", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__mulsf3, .{ .name = "__mulsf3", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__muldf3, .{ .name = "__muldf3", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__multf3, .{ .name = "__multf3", .linkage = linkage }); @export(@import("compiler_rt/divsf3.zig").__divsf3, .{ .name = "__divsf3", .linkage = linkage }); @export(@import("compiler_rt/divdf3.zig").__divdf3, .{ .name = "__divdf3", .linkage = linkage }); @export(@import("compiler_rt/divtf3.zig").__divtf3, .{ .name = "__divtf3", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__ashldi3, .{ .name = "__ashldi3", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__ashlti3, .{ .name = "__ashlti3", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__ashrdi3, .{ .name = "__ashrdi3", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__ashrti3, .{ .name = "__ashrti3", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__lshrdi3, .{ .name = "__lshrdi3", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__lshrti3, .{ .name = "__lshrti3", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsidf, .{ .name = "__floatsidf", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsisf, .{ .name = "__floatsisf", .linkage = linkage }); @export(@import("compiler_rt/floatdidf.zig").__floatdidf, .{ .name = "__floatdidf", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__floatsitf, .{ .name = "__floatsitf", .linkage = linkage }); @export(@import("compiler_rt/floatunsisf.zig").__floatunsisf, .{ .name = "__floatunsisf", .linkage = linkage }); @export(@import("compiler_rt/floatundisf.zig").__floatundisf, .{ .name = "__floatundisf", .linkage = linkage }); @export(@import("compiler_rt/floatunsidf.zig").__floatunsidf, .{ .name = "__floatunsidf", .linkage = linkage }); @export(@import("compiler_rt/floatundidf.zig").__floatundidf, .{ .name = "__floatundidf", .linkage = linkage }); @export(@import("compiler_rt/floattitf.zig").__floattitf, .{ .name = "__floattitf", .linkage = linkage }); @export(@import("compiler_rt/floattidf.zig").__floattidf, .{ .name = "__floattidf", .linkage = linkage }); @export(@import("compiler_rt/floattisf.zig").__floattisf, .{ .name = "__floattisf", .linkage = linkage }); @export(@import("compiler_rt/floatunditf.zig").__floatunditf, .{ .name = "__floatunditf", .linkage = linkage }); @export(@import("compiler_rt/floatunsitf.zig").__floatunsitf, .{ .name = "__floatunsitf", .linkage = linkage }); @export(@import("compiler_rt/floatuntitf.zig").__floatuntitf, .{ .name = "__floatuntitf", .linkage = linkage }); @export(@import("compiler_rt/floatuntidf.zig").__floatuntidf, .{ .name = "__floatuntidf", .linkage = linkage }); @export(@import("compiler_rt/floatuntisf.zig").__floatuntisf, .{ .name = "__floatuntisf", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extenddftf2, .{ .name = "__extenddftf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendsftf2, .{ .name = "__extendsftf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendhfsf2, .{ .name = "__extendhfsf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncsfhf2, .{ .name = "__truncsfhf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncdfhf2, .{ .name = "__truncdfhf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__trunctfdf2, .{ .name = "__trunctfdf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__trunctfsf2, .{ .name = "__trunctfsf2", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__truncdfsf2, .{ .name = "__truncdfsf2", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__extendsfdf2, .{ .name = "__extendsfdf2", .linkage = linkage }); @export(@import("compiler_rt/fixunssfsi.zig").__fixunssfsi, .{ .name = "__fixunssfsi", .linkage = linkage }); @export(@import("compiler_rt/fixunssfdi.zig").__fixunssfdi, .{ .name = "__fixunssfdi", .linkage = linkage }); @export(@import("compiler_rt/fixunssfti.zig").__fixunssfti, .{ .name = "__fixunssfti", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfsi.zig").__fixunsdfsi, .{ .name = "__fixunsdfsi", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfdi.zig").__fixunsdfdi, .{ .name = "__fixunsdfdi", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfti.zig").__fixunsdfti, .{ .name = "__fixunsdfti", .linkage = linkage }); @export(@import("compiler_rt/fixunstfsi.zig").__fixunstfsi, .{ .name = "__fixunstfsi", .linkage = linkage }); @export(@import("compiler_rt/fixunstfdi.zig").__fixunstfdi, .{ .name = "__fixunstfdi", .linkage = linkage }); @export(@import("compiler_rt/fixunstfti.zig").__fixunstfti, .{ .name = "__fixunstfti", .linkage = linkage }); @export(@import("compiler_rt/fixdfdi.zig").__fixdfdi, .{ .name = "__fixdfdi", .linkage = linkage }); @export(@import("compiler_rt/fixdfsi.zig").__fixdfsi, .{ .name = "__fixdfsi", .linkage = linkage }); @export(@import("compiler_rt/fixdfti.zig").__fixdfti, .{ .name = "__fixdfti", .linkage = linkage }); @export(@import("compiler_rt/fixsfdi.zig").__fixsfdi, .{ .name = "__fixsfdi", .linkage = linkage }); @export(@import("compiler_rt/fixsfsi.zig").__fixsfsi, .{ .name = "__fixsfsi", .linkage = linkage }); @export(@import("compiler_rt/fixsfti.zig").__fixsfti, .{ .name = "__fixsfti", .linkage = linkage }); @export(@import("compiler_rt/fixtfdi.zig").__fixtfdi, .{ .name = "__fixtfdi", .linkage = linkage }); @export(@import("compiler_rt/fixtfsi.zig").__fixtfsi, .{ .name = "__fixtfsi", .linkage = linkage }); @export(@import("compiler_rt/fixtfti.zig").__fixtfti, .{ .name = "__fixtfti", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__udivmoddi4, .{ .name = "__udivmoddi4", .linkage = linkage }); @export(@import("compiler_rt/popcountdi2.zig").__popcountdi2, .{ .name = "__popcountdi2", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__mulsi3, .{ .name = "__mulsi3", .linkage = linkage }); @export(@import("compiler_rt/muldi3.zig").__muldi3, .{ .name = "__muldi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__divmoddi4, .{ .name = "__divmoddi4", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__divsi3, .{ .name = "__divsi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__divdi3, .{ .name = "__divdi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__udivsi3, .{ .name = "__udivsi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__udivdi3, .{ .name = "__udivdi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__modsi3, .{ .name = "__modsi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__moddi3, .{ .name = "__moddi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__umodsi3, .{ .name = "__umodsi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__umoddi3, .{ .name = "__umoddi3", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__divmodsi4, .{ .name = "__divmodsi4", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__udivmodsi4, .{ .name = "__udivmodsi4", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__negsf2, .{ .name = "__negsf2", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__negdf2, .{ .name = "__negdf2", .linkage = linkage }); @export(@import("compiler_rt/clzsi2.zig").__clzsi2, .{ .name = "__clzsi2", .linkage = linkage }); if ((builtin.arch.isARM() or builtin.arch.isThumb()) and !is_test) { @export(@import("compiler_rt/arm.zig").__aeabi_unwind_cpp_pr0, .{ .name = "__aeabi_unwind_cpp_pr0", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_unwind_cpp_pr1, .{ .name = "__aeabi_unwind_cpp_pr1", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_unwind_cpp_pr2, .{ .name = "__aeabi_unwind_cpp_pr2", .linkage = linkage }); @export(@import("compiler_rt/muldi3.zig").__muldi3, .{ .name = "__aeabi_lmul", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_ldivmod, .{ .name = "__aeabi_ldivmod", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_uldivmod, .{ .name = "__aeabi_uldivmod", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__divsi3, .{ .name = "__aeabi_idiv", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_idivmod, .{ .name = "__aeabi_idivmod", .linkage = linkage }); @export(@import("compiler_rt/int.zig").__udivsi3, .{ .name = "__aeabi_uidiv", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_uidivmod, .{ .name = "__aeabi_uidivmod", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memcpy, .{ .name = "__aeabi_memcpy", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memcpy, .{ .name = "__aeabi_memcpy4", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memcpy, .{ .name = "__aeabi_memcpy8", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memmove, .{ .name = "__aeabi_memmove", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memmove, .{ .name = "__aeabi_memmove4", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memmove, .{ .name = "__aeabi_memmove8", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memset, .{ .name = "__aeabi_memset", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memset, .{ .name = "__aeabi_memset4", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memset, .{ .name = "__aeabi_memset8", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr4", .linkage = linkage }); @export(@import("compiler_rt/arm.zig").__aeabi_memclr, .{ .name = "__aeabi_memclr8", .linkage = linkage }); if (builtin.os.tag == .linux) { @export(@import("compiler_rt/arm.zig").__aeabi_read_tp, .{ .name = "__aeabi_read_tp", .linkage = linkage }); } @export(@import("compiler_rt/extendXfYf2.zig").__aeabi_f2d, .{ .name = "__aeabi_f2d", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__aeabi_i2d, .{ .name = "__aeabi_i2d", .linkage = linkage }); @export(@import("compiler_rt/floatdidf.zig").__aeabi_l2d, .{ .name = "__aeabi_l2d", .linkage = linkage }); @export(@import("compiler_rt/floatunsidf.zig").__aeabi_ui2d, .{ .name = "__aeabi_ui2d", .linkage = linkage }); @export(@import("compiler_rt/floatundidf.zig").__aeabi_ul2d, .{ .name = "__aeabi_ul2d", .linkage = linkage }); @export(@import("compiler_rt/floatunsisf.zig").__aeabi_ui2f, .{ .name = "__aeabi_ui2f", .linkage = linkage }); @export(@import("compiler_rt/floatundisf.zig").__aeabi_ul2f, .{ .name = "__aeabi_ul2f", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__aeabi_fneg, .{ .name = "__aeabi_fneg", .linkage = linkage }); @export(@import("compiler_rt/negXf2.zig").__aeabi_dneg, .{ .name = "__aeabi_dneg", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__aeabi_fmul, .{ .name = "__aeabi_fmul", .linkage = linkage }); @export(@import("compiler_rt/mulXf3.zig").__aeabi_dmul, .{ .name = "__aeabi_dmul", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__aeabi_d2h, .{ .name = "__aeabi_d2h", .linkage = linkage }); @export(@import("compiler_rt/fixunssfdi.zig").__aeabi_f2ulz, .{ .name = "__aeabi_f2ulz", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfdi.zig").__aeabi_d2ulz, .{ .name = "__aeabi_d2ulz", .linkage = linkage }); @export(@import("compiler_rt/fixsfdi.zig").__aeabi_f2lz, .{ .name = "__aeabi_f2lz", .linkage = linkage }); @export(@import("compiler_rt/fixdfdi.zig").__aeabi_d2lz, .{ .name = "__aeabi_d2lz", .linkage = linkage }); @export(@import("compiler_rt/fixunsdfsi.zig").__aeabi_d2uiz, .{ .name = "__aeabi_d2uiz", .linkage = linkage }); @export(@import("compiler_rt/extendXfYf2.zig").__aeabi_h2f, .{ .name = "__aeabi_h2f", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__aeabi_f2h, .{ .name = "__aeabi_f2h", .linkage = linkage }); @export(@import("compiler_rt/floatsiXf.zig").__aeabi_i2f, .{ .name = "__aeabi_i2f", .linkage = linkage }); @export(@import("compiler_rt/truncXfYf2.zig").__aeabi_d2f, .{ .name = "__aeabi_d2f", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_fadd, .{ .name = "__aeabi_fadd", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_dadd, .{ .name = "__aeabi_dadd", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_fsub, .{ .name = "__aeabi_fsub", .linkage = linkage }); @export(@import("compiler_rt/addXf3.zig").__aeabi_dsub, .{ .name = "__aeabi_dsub", .linkage = linkage }); @export(@import("compiler_rt/fixunssfsi.zig").__aeabi_f2uiz, .{ .name = "__aeabi_f2uiz", .linkage = linkage }); @export(@import("compiler_rt/fixsfsi.zig").__aeabi_f2iz, .{ .name = "__aeabi_f2iz", .linkage = linkage }); @export(@import("compiler_rt/fixdfsi.zig").__aeabi_d2iz, .{ .name = "__aeabi_d2iz", .linkage = linkage }); @export(@import("compiler_rt/divsf3.zig").__aeabi_fdiv, .{ .name = "__aeabi_fdiv", .linkage = linkage }); @export(@import("compiler_rt/divdf3.zig").__aeabi_ddiv, .{ .name = "__aeabi_ddiv", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__aeabi_llsl, .{ .name = "__aeabi_llsl", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__aeabi_lasr, .{ .name = "__aeabi_lasr", .linkage = linkage }); @export(@import("compiler_rt/shift.zig").__aeabi_llsr, .{ .name = "__aeabi_llsr", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpeq, .{ .name = "__aeabi_fcmpeq", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmplt, .{ .name = "__aeabi_fcmplt", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmple, .{ .name = "__aeabi_fcmple", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpge, .{ .name = "__aeabi_fcmpge", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpgt, .{ .name = "__aeabi_fcmpgt", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_fcmpun, .{ .name = "__aeabi_fcmpun", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_dcmpeq, .{ .name = "__aeabi_dcmpeq", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_dcmplt, .{ .name = "__aeabi_dcmplt", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_dcmple, .{ .name = "__aeabi_dcmple", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_dcmpge, .{ .name = "__aeabi_dcmpge", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_dcmpgt, .{ .name = "__aeabi_dcmpgt", .linkage = linkage }); @export(@import("compiler_rt/compareXf2.zig").__aeabi_dcmpun, .{ .name = "__aeabi_dcmpun", .linkage = linkage }); } if (builtin.arch == .i386 and builtin.abi == .msvc) { // Don't let LLVM apply the stdcall name mangling on those MSVC builtins @export(@import("compiler_rt/aulldiv.zig")._alldiv, .{ .name = "\x01__alldiv", .linkage = strong_linkage }); @export(@import("compiler_rt/aulldiv.zig")._aulldiv, .{ .name = "\x01__aulldiv", .linkage = strong_linkage }); @export(@import("compiler_rt/aullrem.zig")._allrem, .{ .name = "\x01__allrem", .linkage = strong_linkage }); @export(@import("compiler_rt/aullrem.zig")._aullrem, .{ .name = "\x01__aullrem", .linkage = strong_linkage }); } if (builtin.os.tag == .windows) { // Default stack-probe functions emitted by LLVM if (is_mingw) { @export(@import("compiler_rt/stack_probe.zig")._chkstk, .{ .name = "_alloca", .linkage = strong_linkage }); @export(@import("compiler_rt/stack_probe.zig").___chkstk_ms, .{ .name = "___chkstk_ms", .linkage = strong_linkage }); } else if (!builtin.link_libc) { // This symbols are otherwise exported by MSVCRT.lib @export(@import("compiler_rt/stack_probe.zig")._chkstk, .{ .name = "_chkstk", .linkage = strong_linkage }); @export(@import("compiler_rt/stack_probe.zig").__chkstk, .{ .name = "__chkstk", .linkage = strong_linkage }); } if (is_mingw) { @export(__stack_chk_fail, .{ .name = "__stack_chk_fail", .linkage = strong_linkage }); @export(__stack_chk_guard, .{ .name = "__stack_chk_guard", .linkage = strong_linkage }); } switch (builtin.arch) { .i386 => { @export(@import("compiler_rt/divti3.zig").__divti3, .{ .name = "__divti3", .linkage = linkage }); @export(@import("compiler_rt/modti3.zig").__modti3, .{ .name = "__modti3", .linkage = linkage }); @export(@import("compiler_rt/multi3.zig").__multi3, .{ .name = "__multi3", .linkage = linkage }); @export(@import("compiler_rt/udivti3.zig").__udivti3, .{ .name = "__udivti3", .linkage = linkage }); @export(@import("compiler_rt/udivmodti4.zig").__udivmodti4, .{ .name = "__udivmodti4", .linkage = linkage }); @export(@import("compiler_rt/umodti3.zig").__umodti3, .{ .name = "__umodti3", .linkage = linkage }); }, .x86_64 => { // The "ti" functions must use @Vector(2, u64) parameter types to adhere to the ABI // that LLVM expects compiler-rt to have. @export(@import("compiler_rt/divti3.zig").__divti3_windows_x86_64, .{ .name = "__divti3", .linkage = linkage }); @export(@import("compiler_rt/modti3.zig").__modti3_windows_x86_64, .{ .name = "__modti3", .linkage = linkage }); @export(@import("compiler_rt/multi3.zig").__multi3_windows_x86_64, .{ .name = "__multi3", .linkage = linkage }); @export(@import("compiler_rt/udivti3.zig").__udivti3_windows_x86_64, .{ .name = "__udivti3", .linkage = linkage }); @export(@import("compiler_rt/udivmodti4.zig").__udivmodti4_windows_x86_64, .{ .name = "__udivmodti4", .linkage = linkage }); @export(@import("compiler_rt/umodti3.zig").__umodti3_windows_x86_64, .{ .name = "__umodti3", .linkage = linkage }); }, else => {}, } } else { if (std.Target.current.isGnuLibC() and builtin.link_libc) { @export(__stack_chk_guard, .{ .name = "__stack_chk_guard", .linkage = linkage }); } @export(@import("compiler_rt/divti3.zig").__divti3, .{ .name = "__divti3", .linkage = linkage }); @export(@import("compiler_rt/modti3.zig").__modti3, .{ .name = "__modti3", .linkage = linkage }); @export(@import("compiler_rt/multi3.zig").__multi3, .{ .name = "__multi3", .linkage = linkage }); @export(@import("compiler_rt/udivti3.zig").__udivti3, .{ .name = "__udivti3", .linkage = linkage }); @export(@import("compiler_rt/udivmodti4.zig").__udivmodti4, .{ .name = "__udivmodti4", .linkage = linkage }); @export(@import("compiler_rt/umodti3.zig").__umodti3, .{ .name = "__umodti3", .linkage = linkage }); } @export(@import("compiler_rt/muloti4.zig").__muloti4, .{ .name = "__muloti4", .linkage = linkage }); @export(@import("compiler_rt/mulodi4.zig").__mulodi4, .{ .name = "__mulodi4", .linkage = linkage }); } // Avoid dragging in the runtime safety mechanisms into this .o file, // unless we're trying to test this file. pub fn panic(msg: []const u8, error_return_trace: ?*builtin.StackTrace) noreturn { @setCold(true); if (is_test) { std.debug.panic("{}", .{msg}); } else { unreachable; } } fn __stack_chk_fail() callconv(.C) noreturn { @panic("stack smashing detected"); } extern var __stack_chk_guard: usize = blk: { var buf = [1]u8{0} ** @sizeOf(usize); buf[@sizeOf(usize) - 1] = 255; buf[@sizeOf(usize) - 2] = '\n'; break :blk @bitCast(usize, buf); };
lib/std/special/compiler_rt.zig
const builtin = @import("builtin"); const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; /// Returns the cosine of the radian value x. /// /// Special Cases: /// - cos(+-inf) = nan /// - cos(nan) = nan pub fn cos(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => cos_(f32, x), f64 => cos_(f64, x), else => @compileError("cos not implemented for " ++ @typeName(T)), }; } // sin polynomial coefficients const S0 = 1.58962301576546568060E-10; const S1 = -2.50507477628578072866E-8; const S2 = 2.75573136213857245213E-6; const S3 = -1.98412698295895385996E-4; const S4 = 8.33333333332211858878E-3; const S5 = -1.66666666666666307295E-1; // cos polynomial coeffiecients const C0 = -1.13585365213876817300E-11; const C1 = 2.08757008419747316778E-9; const C2 = -2.75573141792967388112E-7; const C3 = 2.48015872888517045348E-5; const C4 = -1.38888888888730564116E-3; const C5 = 4.16666666666665929218E-2; const pi4a = 7.85398125648498535156e-1; const pi4b = 3.77489470793079817668E-8; const pi4c = 2.69515142907905952645E-15; const m4pi = 1.273239544735162542821171882678754627704620361328125; fn cos_(comptime T: type, x_: T) T { const I = std.meta.Int(.signed, @typeInfo(T).Float.bits); var x = x_; if (math.isNan(x) or math.isInf(x)) { return math.nan(T); } var sign = false; x = math.fabs(x); var y = math.floor(x * m4pi); var j = @floatToInt(I, y); if (j & 1 == 1) { j += 1; y += 1; } j &= 7; if (j > 3) { j -= 4; sign = !sign; } if (j > 1) { sign = !sign; } const z = ((x - y * pi4a) - y * pi4b) - y * pi4c; const w = z * z; const r = if (j == 1 or j == 2) z + z * w * (S5 + w * (S4 + w * (S3 + w * (S2 + w * (S1 + w * S0))))) else 1.0 - 0.5 * w + w * w * (C5 + w * (C4 + w * (C3 + w * (C2 + w * (C1 + w * C0))))); return if (sign) -r else r; } test "math.cos" { expect(cos(@as(f32, 0.0)) == cos_(f32, 0.0)); expect(cos(@as(f64, 0.0)) == cos_(f64, 0.0)); } test "math.cos32" { const epsilon = 0.000001; expect(math.approxEqAbs(f32, cos_(f32, 0.0), 1.0, epsilon)); expect(math.approxEqAbs(f32, cos_(f32, 0.2), 0.980067, epsilon)); expect(math.approxEqAbs(f32, cos_(f32, 0.8923), 0.627623, epsilon)); expect(math.approxEqAbs(f32, cos_(f32, 1.5), 0.070737, epsilon)); expect(math.approxEqAbs(f32, cos_(f32, -1.5), 0.070737, epsilon)); expect(math.approxEqAbs(f32, cos_(f32, 37.45), 0.969132, epsilon)); expect(math.approxEqAbs(f32, cos_(f32, 89.123), 0.400798, epsilon)); } test "math.cos64" { const epsilon = 0.000001; expect(math.approxEqAbs(f64, cos_(f64, 0.0), 1.0, epsilon)); expect(math.approxEqAbs(f64, cos_(f64, 0.2), 0.980067, epsilon)); expect(math.approxEqAbs(f64, cos_(f64, 0.8923), 0.627623, epsilon)); expect(math.approxEqAbs(f64, cos_(f64, 1.5), 0.070737, epsilon)); expect(math.approxEqAbs(f64, cos_(f64, -1.5), 0.070737, epsilon)); expect(math.approxEqAbs(f64, cos_(f64, 37.45), 0.969132, epsilon)); expect(math.approxEqAbs(f64, cos_(f64, 89.123), 0.40080, epsilon)); } test "math.cos32.special" { expect(math.isNan(cos_(f32, math.inf(f32)))); expect(math.isNan(cos_(f32, -math.inf(f32)))); expect(math.isNan(cos_(f32, math.nan(f32)))); } test "math.cos64.special" { expect(math.isNan(cos_(f64, math.inf(f64)))); expect(math.isNan(cos_(f64, -math.inf(f64)))); expect(math.isNan(cos_(f64, math.nan(f64)))); }
lib/std/math/cos.zig
const std = @import("std"); const aoc = @import("aoc-lib.zig"); fn parts(alloc: std.mem.Allocator, in: []const u8, p1Days: usize) ![2]usize { var oct: []u8 = try alloc.dupe(u8, in); defer alloc.free(oct); var w: usize = 0; while (in[w] != '\n') : (w += 1) {} var h = in.len / (w + 1); var r = [2]usize{ 0, 0 }; var c: usize = 0; var day: usize = 1; while (true) : (day += 1) { for (oct) |ch, i| { if (ch != '\n') { oct[i] += 1; } } //aoc.print("{s}\n", .{oct}) catch unreachable; for (oct) |ch, i| { if (ch > '9' and ch != '~') { flash(oct, i, w, h); } } var p2: usize = 0; for (oct) |ch, i| { if (ch != '~') { continue; } oct[i] = '0'; p2 += 1; } //aoc.print("{}: {}\n{s}\n", .{ day, p2, oct }) catch unreachable; c += p2; if (day == p1Days) { r[0] = c; } if (p2 == w * h) { r[1] = day; return r; } } return r; } fn flash(oct: []u8, i: usize, w: usize, h: usize) void { var x = @intCast(isize, i % (w + 1)); var y = @intCast(isize, i / (w + 1)); //aoc.print("flash {},{}\n{s}\n", .{ x, y, oct }) catch unreachable; oct[i] = '~'; for ([3]isize{ x - 1, x, x + 1 }) |nx| { for ([3]isize{ y - 1, y, y + 1 }) |ny| { if (x == nx and y == ny) { continue; } if (nx < 0 or ny < 0 or nx >= w or ny >= h) { continue; } var ni = @intCast(usize, nx) + @intCast(usize, ny) * (w + 1); if (oct[ni] == '~') { continue; } oct[ni] += 1; if (oct[ni] > '9') { flash(oct, ni, w, h); } } } } test "examples" { var test0 = try parts(aoc.talloc, aoc.test0file, 1); var test1 = try parts(aoc.talloc, aoc.test1file, 100); var real = try parts(aoc.talloc, aoc.inputfile, 100); try aoc.assertEq(@as(usize, 9), test0[0]); try aoc.assertEq(@as(usize, 1656), test1[0]); try aoc.assertEq(@as(usize, 1652), real[0]); try aoc.assertEq(@as(usize, 6), test0[1]); try aoc.assertEq(@as(usize, 195), test1[1]); try aoc.assertEq(@as(usize, 220), real[1]); } fn day11(inp: []const u8, bench: bool) anyerror!void { var p = try parts(aoc.halloc, inp, 100); if (!bench) { try aoc.print("Part 1: {}\nPart 2: {}\n", .{ p[0], p[1] }); } } pub fn main() anyerror!void { try aoc.benchme(aoc.input(), day11); }
2021/11/aoc.zig
/// Builtin functions pub const builtins = [_][]const u8{ "@addWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:result: *T})", "@alignCast(${1:comptime alignment: u29}, ${2:ptr: var})", "@alignOf(${1:comptime T: type})", "@as(${1:comptime T: type}, ${2:expression})", "@asyncCall(${1:frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8}, ${2:result_ptr}, ${3:function_ptr}, ${4:args: ...})", "@atomicLoad(${1:comptime T: type}, ${2:ptr: *const T}, ${3:comptime ordering: builtin.AtomicOrder})", "@atomicRmw(${1:comptime T: type}, ${2:ptr: *T}, ${3:comptime op: builtin.AtomicRmwOp}, ${4:operand: T}, ${5:comptime ordering: builtin.AtomicOrder})", "@atomicStore(${1:comptime T: type}, ${2:ptr: *T}, ${3:value: T}, ${4:comptime ordering: builtin.AtomicOrder})", "@bitCast(${1:comptime DestType: type}, ${2:value: var})", "@bitOffsetOf(${1:comptime T: type}, ${2:comptime field_name: []const u8})", "@boolToInt(${1:value: bool})", "@bitSizeOf(${1:comptime T: type})", "@breakpoint()", "@mulAdd(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:c: T})", "@byteSwap(${1:comptime T: type}, ${2:operand: T})", "@bitReverse(${1:comptime T: type}, ${2:integer: T})", "@byteOffsetOf(${1:comptime T: type}, ${2:comptime field_name: []const u8})", "@call(${1:options: std.builtin.CallOptions}, ${2:function: var}, ${3:args: var})", "@cDefine(${1:comptime name: []u8}, ${2:value})", "@cImport(${1:expression})", "@cInclude(${1:comptime path: []u8})", "@clz(${1:comptime T: type}, ${2:integer: T})", "@cmpxchgStrong(${1:comptime T: type}, ${2:ptr: *T}, ${3:expected_value: T}, ${4:new_value: T}, ${5:success_order: AtomicOrder}, ${6:fail_order: AtomicOrder})", "@cmpxchgWeak(${1:comptime T: type}, ${2:ptr: *T}, ${3:expected_value: T}, ${4:new_value: T}, ${5:success_order: AtomicOrder}, ${6:fail_order: AtomicOrder})", "@compileError(${1:comptime msg: []u8})", "@compileLog(${1:args: ...})", "@ctz(${1:comptime T: type}, ${2:integer: T})", "@cUndef(${1:comptime name: []u8})", "@divExact(${1:numerator: T}, ${2:denominator: T})", "@divFloor(${1:numerator: T}, ${2:denominator: T})", "@divTrunc(${1:numerator: T}, ${2:denominator: T})", "@embedFile(${1:comptime path: []const u8})", "@enumToInt(${1:enum_or_tagged_union: var})", "@errorName(${1:err: anyerror})", "@errorReturnTrace()", "@errorToInt(${1:err: var) std.meta.IntType(false}, ${2:@sizeOf(anyerror})", "@errSetCast(${1:comptime T: DestType}, ${2:value: var})", "@export(${1:target: var}, ${2:comptime options: std.builtin.ExportOptions})", "@fence(${1:order: AtomicOrder})", "@field(${1:lhs: var}, ${2:comptime field_name: []const u8})", "@fieldParentPtr(${1:comptime ParentType: type}, ${2:comptime field_name: []const u8}, ${3:\n field_ptr: *T})", "@floatCast(${1:comptime DestType: type}, ${2:value: var})", "@floatToInt(${1:comptime DestType: type}, ${2:float: var})", "@frame()", "@Frame(${1:func: var})", "@frameAddress()", "@frameSize()", "@hasDecl(${1:comptime Container: type}, ${2:comptime name: []const u8})", "@hasField(${1:comptime Container: type}, ${2:comptime name: []const u8})", "@import(${1:comptime path: []u8})", "@intCast(${1:comptime DestType: type}, ${2:int: var})", "@intToEnum(${1:comptime DestType: type}, ${2:int_value: @TagType(DestType)})", "@intToError(${1:value: std.meta.IntType(false, @sizeOf(anyerror) * 8)})", "@intToFloat(${1:comptime DestType: type}, ${2:int: var})", "@intToPtr(${1:comptime DestType: type}, ${2:address: usize})", "@memcpy(${1:noalias dest: [*]u8}, ${2:noalias source: [*]const u8}, ${3:byte_count: usize})", "@memset(${1:dest: [*]u8}, ${2:c: u8}, ${3:byte_count: usize})", "@mod(${1:numerator: T}, ${2:denominator: T})", "@mulWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:result: *T})", "@OpaqueType()", "@panic(${1:message: []const u8})", "@popCount(${1:comptime T: type}, ${2:integer: T})", "@ptrCast(${1:comptime DestType: type}, ${2:value: var})", "@ptrToInt(${1:value: var})", "@rem(${1:numerator: T}, ${2:denominator: T})", "@returnAddress()", "@setAlignStack(${1:comptime alignment: u29})", "@setCold(${1:is_cold: bool})", "@setEvalBranchQuota(${1:new_quota: usize})", "@setFloatMode(${1:mode: @import(\"builtin\").FloatMode})", "@setRuntimeSafety(${1:safety_on: bool})", "@shlExact(${1:value: T}, ${2:shift_amt: Log2T})", "@shlWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:shift_amt: Log2T}, ${4:result: *T})", "@shrExact(${1:value: T}, ${2:shift_amt: Log2T})", "@shuffle(${1:comptime E: type}, ${2:a: @Vector(a_len, E)}, ${3:b: @Vector(b_len, E)}, ${4:comptime mask: @Vector(mask_len, i32)})", "@sizeOf(${1:comptime T: type})", "@splat(${1:comptime len: u32}, ${2:scalar: var})", "@sqrt(${1:value: var})", "@sin(${1:value: var})", "@cos(${1:value: var})", "@exp(${1:value: var})", "@exp2(${1:value: var})", "@log(${1:value: var})", "@log2(${1:value: var})", "@log10(${1:value: var})", "@fabs(${1:value: var})", "@floor(${1:value: var})", "@ceil(${1:value: var})", "@trunc(${1:value: var})", "@round(${1:value: var})", "@subWithOverflow(${1:comptime T: type}, ${2:a: T}, ${3:b: T}, ${4:result: *T})", "@tagName(${1:value: var})", "@TagType(${1:T: type})", "@This()", "@truncate(${1:comptime T: type}, ${2:integer: var})", "@Type(${1:comptime info: @import(\"builtin\").TypeInfo})", "@typeInfo(${1:comptime T: type})", "@typeName(${1:T: type})", "@TypeOf(${1:...})", "@unionInit(${1:comptime Union: type}, ${2:comptime active_field_name: []const u8}, ${3:init_expr})", "@Vector(${1:comptime len: u32}, ${2:comptime ElemType: type})" }; /// Builtin function details pub const builtin_details = [_][]const u8{ "@addWithOverflow(comptime T: type, a: T, b: T, result: *T) bool", "@alignCast(comptime alignment: u29, ptr: var) var", "@alignOf(comptime T: type) comptime_int", "@as(comptime T: type, expression) T", "@asyncCall(frame_buffer: []align(@alignOf(@Frame(anyAsyncFunction))) u8, result_ptr, function_ptr, args: ...) anyframe->T", "@atomicLoad(comptime T: type, ptr: *const T, comptime ordering: builtin.AtomicOrder) T", "@atomicRmw(comptime T: type, ptr: *T, comptime op: builtin.AtomicRmwOp, operand: T, comptime ordering: builtin.AtomicOrder) T", "@atomicStore(comptime T: type, ptr: *T, value: T, comptime ordering: builtin.AtomicOrder) void", "@bitCast(comptime DestType: type, value: var) DestType", "@bitOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int", "@boolToInt(value: bool) u1", "@bitSizeOf(comptime T: type) comptime_int", "@breakpoint()", "@mulAdd(comptime T: type, a: T, b: T, c: T) T", "@byteSwap(comptime T: type, operand: T) T", "@bitReverse(comptime T: type, integer: T) T", "@byteOffsetOf(comptime T: type, comptime field_name: []const u8) comptime_int", "@call(options: std.builtin.CallOptions, function: var, args: var) var", "@cDefine(comptime name: []u8, value)", "@cImport(expression) type", "@cInclude(comptime path: []u8)", "@clz(comptime T: type, integer: T)", "@cmpxchgStrong(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T", "@cmpxchgWeak(comptime T: type, ptr: *T, expected_value: T, new_value: T, success_order: AtomicOrder, fail_order: AtomicOrder) ?T", "@compileError(comptime msg: []u8)", "@compileLog(args: ...)", "@ctz(comptime T: type, integer: T)", "@cUndef(comptime name: []u8)", "@divExact(numerator: T, denominator: T) T", "@divFloor(numerator: T, denominator: T) T", "@divTrunc(numerator: T, denominator: T) T", "@embedFile(comptime path: []const u8) *const [X:0]u8", "@enumToInt(enum_or_tagged_union: var) var", "@errorName(err: anyerror) []const u8", "@errorReturnTrace() ?*builtin.StackTrace", "@errorToInt(err: var) std.meta.IntType(false, @sizeOf(anyerror) * 8)", "@errSetCast(comptime T: DestType, value: var) DestType", "@export(target: var, comptime options: std.builtin.ExportOptions) void", "@fence(order: AtomicOrder)", "@field(lhs: var, comptime field_name: []const u8) (field)", "@fieldParentPtr(comptime ParentType: type, comptime field_name: []const u8,\n field_ptr: *T) *ParentType", "@floatCast(comptime DestType: type, value: var) DestType", "@floatToInt(comptime DestType: type, float: var) DestType", "@frame() *@Frame(func)", "@Frame(func: var) type", "@frameAddress() usize", "@frameSize() usize", "@hasDecl(comptime Container: type, comptime name: []const u8) bool", "@hasField(comptime Container: type, comptime name: []const u8) bool", "@import(comptime path: []u8) type", "@intCast(comptime DestType: type, int: var) DestType", "@intToEnum(comptime DestType: type, int_value: @TagType(DestType)) DestType", "@intToError(value: std.meta.IntType(false, @sizeOf(anyerror) * 8)) anyerror", "@intToFloat(comptime DestType: type, int: var) DestType", "@intToPtr(comptime DestType: type, address: usize) DestType", "@memcpy(noalias dest: [*]u8, noalias source: [*]const u8, byte_count: usize)", "@memset(dest: [*]u8, c: u8, byte_count: usize)", "@mod(numerator: T, denominator: T) T", "@mulWithOverflow(comptime T: type, a: T, b: T, result: *T) bool", "@OpaqueType() type", "@panic(message: []const u8) noreturn", "@popCount(comptime T: type, integer: T)", "@ptrCast(comptime DestType: type, value: var) DestType", "@ptrToInt(value: var) usize", "@rem(numerator: T, denominator: T) T", "@returnAddress() usize", "@setAlignStack(comptime alignment: u29)", "@setCold(is_cold: bool)", "@setEvalBranchQuota(new_quota: usize)", "@setFloatMode(mode: @import(\"builtin\").FloatMode)", "@setRuntimeSafety(safety_on: bool)", "@shlExact(value: T, shift_amt: Log2T) T", "@shlWithOverflow(comptime T: type, a: T, shift_amt: Log2T, result: *T) bool", "@shrExact(value: T, shift_amt: Log2T) T", "@shuffle(comptime E: type, a: @Vector(a_len, E), b: @Vector(b_len, E), comptime mask: @Vector(mask_len, i32)) @Vector(mask_len, E)", "@sizeOf(comptime T: type) comptime_int", "@splat(comptime len: u32, scalar: var) @Vector(len, @TypeOf(scalar))", "@sqrt(value: var) @TypeOf(value)", "@sin(value: var) @TypeOf(value)", "@cos(value: var) @TypeOf(value)", "@exp(value: var) @TypeOf(value)", "@exp2(value: var) @TypeOf(value)", "@log(value: var) @TypeOf(value)", "@log2(value: var) @TypeOf(value)", "@log10(value: var) @TypeOf(value)", "@fabs(value: var) @TypeOf(value)", "@floor(value: var) @TypeOf(value)", "@ceil(value: var) @TypeOf(value)", "@trunc(value: var) @TypeOf(value)", "@round(value: var) @TypeOf(value)", "@subWithOverflow(comptime T: type, a: T, b: T, result: *T) bool", "@tagName(value: var) []const u8", "@TagType(T: type) type", "@This() type", "@truncate(comptime T: type, integer: var) T", "@Type(comptime info: @import(\"builtin\").TypeInfo) type", "@typeInfo(comptime T: type) @import(\"std\").builtin.TypeInfo", "@typeName(T: type) [N]u8", "@TypeOf(...) type", "@unionInit(comptime Union: type, comptime active_field_name: []const u8, init_expr) Union", "@Vector(comptime len: u32, comptime ElemType: type) type" }; /// Builtin function docs pub const builtin_docs = [_][]const u8{ "Performs result.* = a + b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.", "ptr can be *T, fn(), ?*T, ?fn(), or []T. It returns the same type as ptr except with the alignment adjusted to the new value.", "This function returns the number of bytes that this type should be aligned to for the current target to match the C ABI. When the child type of a pointer has this alignment, the alignment can be omitted from the type.", "Performs Type Coercion. This cast is allowed when the conversion is unambiguous and safe, and is the preferred way to convert between types, whenever possible.", "@asyncCall performs an async call on a function pointer, which may or may not be an async function.", "This builtin function atomically dereferences a pointer and returns the value.", "This builtin function atomically modifies memory and then returns the previous value.", "This builtin function atomically stores a value.", "Converts a value of one type to another type.", "Returns the bit offset of a field relative to its containing struct.", "Converts true to u1(1) and false to u1(0).", "This function returns the number of bits it takes to store T in memory. The result is a target-specific compile time constant.", "This function inserts a platform-specific debug trap instruction which causes debuggers to break there.", "Fused multiply add, similar to (a * b) + c, except only rounds once, and is thus more accurate.", "T must be an integer type with bit count evenly divisible by 8.", "T accepts any integer type.", "Returns the byte offset of a field relative to its containing struct.", "Calls a function, in the same way that invoking an expression with parentheses does:", "This function can only occur inside @cImport.", "This function parses C code and imports the functions, types, variables, and compatible macro definitions into a new empty struct type, and then returns that type.", "This function can only occur inside @cImport.", "This function counts the number of most-significant (leading in a big-Endian sense) zeroes in integer.", "This function performs a strong atomic compare exchange operation. It's the equivalent of this code, except atomic:", "This function performs a weak atomic compare exchange operation. It's the equivalent of this code, except atomic:", "This function, when semantically analyzed, causes a compile error with the message msg.", "This function prints the arguments passed to it at compile-time.", "This function counts the number of least-significant (trailing in a big-Endian sense) zeroes in integer.", "This function can only occur inside @cImport.", "Exact division. Caller guarantees denominator != 0 and @divTrunc(numerator, denominator) * denominator == numerator.", "Floored division. Rounds toward negative infinity. For unsigned integers it is the same as numerator / denominator. Caller guarantees denominator != 0 and !(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1).", "Truncated division. Rounds toward zero. For unsigned integers it is the same as numerator / denominator. Caller guarantees denominator != 0 and !(@typeInfo(T) == .Int and T.is_signed and numerator == std.math.minInt(T) and denominator == -1).", "This function returns a compile time constant pointer to null-terminated, fixed-size array with length equal to the byte count of the file given by path. The contents of the array are the contents of the file. This is equivalent to a string literal with the file contents.", "Converts an enumeration value into its integer tag type. When a tagged union is passed, the tag value is used as the enumeration value.", "This function returns the string representation of an error. The string representation of error.OutOfMem is \"OutOfMem\".", "If the binary is built with error return tracing, and this function is invoked in a function that calls a function with an error or error union return type, returns a stack trace object. Otherwise returns `null`.", "Supports the following types:", "Converts an error value from one error set to another error set. Attempting to convert an error which is not in the destination error set results in safety-protected Undefined Behavior.", "Creates a symbol in the output object file.", "The fence function is used to introduce happens-before edges between operations.", "Performs field access by a compile-time string.", "Given a pointer to a field, returns the base pointer of a struct.", "Convert from one float type to another. This cast is safe, but may cause the numeric value to lose precision.", "Converts the integer part of a floating point number to the destination type.", "This function returns a pointer to the frame for a given function. This type can be coerced to anyframe->T and to anyframe, where T is the return type of the function in scope.", "This function returns the frame type of a function. This works for Async Functions as well as any function without a specific calling convention.", "This function returns the base pointer of the current stack frame.", "This is the same as @sizeOf(@Frame(func)), where func may be runtime-known.", "Returns whether or not a struct, enum, or union has a declaration matching name.", "Returns whether the field name of a struct, union, or enum exists.", "This function finds a zig file corresponding to path and adds it to the build, if it is not already added.", "Converts an integer to another integer while keeping the same numerical value. Attempting to convert a number which is out of range of the destination type results in safety-protected Undefined Behavior.", "Converts an integer into an enum value.", "Converts from the integer representation of an error into The Global Error Set type.", "Converts an integer to the closest floating point representation. To convert the other way, use @floatToInt. This cast is always safe.", "Converts an integer to a pointer. To convert the other way, use @ptrToInt.", "This function copies bytes from one region of memory to another. dest and source are both pointers and must not overlap.", "This function sets a region of memory to c. dest is a pointer.", "Modulus division. For unsigned integers this is the same as numerator % denominator. Caller guarantees denominator > 0.", "Performs result.* = a * b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.", "Creates a new type with an unknown (but non-zero) size and alignment.", "Invokes the panic handler function. By default the panic handler function calls the public panic function exposed in the root source file, or if there is not one specified, the std.builtin.default_panic function from std/builtin.zig.", "Counts the number of bits set in an integer.", "Converts a pointer of one type to a pointer of another type.", "Converts value to a usize which is the address of the pointer. value can be one of these types:", "Remainder division. For unsigned integers this is the same as numerator % denominator. Caller guarantees denominator > 0.", "This function returns the address of the next machine code instruction that will be executed when the current function returns.", "Ensures that a function will have a stack alignment of at least alignment bytes.", "Tells the optimizer that a function is rarely called.", "Changes the maximum number of backwards branches that compile-time code execution can use before giving up and making a compile error.", "Sets the floating point mode of the current scope. Possible values are:", "Sets whether runtime safety checks are enabled for the scope that contains the function call.", "Performs the left shift operation (<<). Caller guarantees that the shift will not shift any 1 bits out.", "Performs result.* = a << b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.", "Performs the right shift operation (>>). Caller guarantees that the shift will not shift any 1 bits out.", "Constructs a new vector by selecting elements from a and b based on mask.", "This function returns the number of bytes it takes to store T in memory. The result is a target-specific compile time constant.", "Produces a vector of length len where each element is the value scalar:", "Performs the square root of a floating point number. Uses a dedicated hardware instruction when available.", "Sine trigometric function on a floating point number. Uses a dedicated hardware instruction when available.", "Cosine trigometric function on a floating point number. Uses a dedicated hardware instruction when available.", "Base-e exponential function on a floating point number. Uses a dedicated hardware instruction when available.", "Base-2 exponential function on a floating point number. Uses a dedicated hardware instruction when available.", "Returns the natural logarithm of a floating point number. Uses a dedicated hardware instruction when available.", "Returns the logarithm to the base 2 of a floating point number. Uses a dedicated hardware instruction when available.", "Returns the logarithm to the base 10 of a floating point number. Uses a dedicated hardware instruction when available.", "Returns the absolute value of a floating point number. Uses a dedicated hardware instruction when available.", "Returns the largest integral value not greater than the given floating point number. Uses a dedicated hardware instruction when available.", "Returns the largest integral value not less than the given floating point number. Uses a dedicated hardware instruction when available.", "Rounds the given floating point number to an integer, towards zero. Uses a dedicated hardware instruction when available.", "Rounds the given floating point number to an integer, away from zero. Uses a dedicated hardware instruction when available.", "Performs result.* = a - b. If overflow or underflow occurs, stores the overflowed bits in result and returns true. If no overflow or underflow occurs, returns false.", "Converts an enum value or union value to a slice of bytes representing the name.", "For an enum, returns the integer type that is used to store the enumeration value.", "Returns the innermost struct or union that this function call is inside. This can be useful for an anonymous struct that needs to refer to itself:", "This function truncates bits from an integer type, resulting in a smaller or same-sized integer type.", "This function is the inverse of @typeInfo. It reifies type information into a type.", "Provides type reflection.", "This function returns the string representation of a type, as an array. It is equivalent to a string literal of the type name.", "@TypeOf is a special builtin function that takes any (nonzero) number of expressions as parameters and returns the type of the result, using Peer Type Resolution.", "This is the same thing as union initialization syntax, except that the field name is a comptime-known value rather than an identifier token.", "This function returns a vector type for SIMD." };
src/data/0.6.0.zig
const Core = @This(); const std = @import("std"); const builtin = @import("builtin"); const enums = @import("enums.zig"); pub const Button = enums.Button; pub const Key = enums.Key; pub const Pos = struct { x: i16, y: i16, }; pub const Dim = struct { width: u16, height: u16, }; pub const Event = struct { window: Window, ev: union(enum) { key_press: struct { key: Key, }, key_release: struct { key: Key, }, button_press: struct { button: Button, }, button_release: struct { button: Button, }, mouse_scroll: struct { scroll_x: i2, scroll_y: i2, }, mouse_motion: Pos, mouse_enter: Pos, mouse_leave: Pos, focus_in: void, focus_out: void, window_resize: Dim, quit: void, }, }; pub const WindowInfo = struct { title: ?[]const u8 = null, width: u16 = 256, height: u16 = 256, }; fn CoreType() type { if (builtin.cpu.arch == .wasm32) return @import("wasm/Core.zig"); return @import("xcb/Core.zig"); } fn WindowType() type { return CoreType().Window; } internal: *CoreType(), pub fn init(allocator: std.mem.Allocator) !Core { return Core{ .internal = try CoreType().init(allocator) }; } pub fn deinit(core: *Core) void { core.internal.deinit(); } pub fn createWindow(core: *Core, info: WindowInfo) !Window { return Window{ .internal = try core.internal.createWindow(info) }; } pub fn pollEvent(core: *Core) ?Event { return core.internal.pollEvent(); } pub fn waitEvent(core: *Core) ?Event { return core.internal.waitEvent(); } pub fn getKeyDown(core: *Core, key: Key) bool { return core.internal.getKeyDown(key); } pub const Window = struct { internal: *WindowType(), pub fn init(info: WindowInfo) !Window { return .{ .internal = try WindowType().init(info) }; } pub fn initFromInternal(internal: *WindowType()) Window { return .{ .internal = internal }; } pub fn deinit(window: *Window) void { window.internal.deinit(); } pub fn setTitle(window: *Window, title: []const u8) void { window.internal.setTitle(title); } pub fn setSize(window: *Window, width: u16, height: u16) void { window.internal.setSize(width, height); } pub fn getSize(window: *Window) Dim { return window.internal.getSize(); } };
src/main.zig
const std = @import("std"); const mem = std.mem; const IDContinue = @This(); allocator: *mem.Allocator, array: []bool, lo: u21 = 48, hi: u21 = 917999, pub fn init(allocator: *mem.Allocator) !IDContinue { var instance = IDContinue{ .allocator = allocator, .array = try allocator.alloc(bool, 917952), }; mem.set(bool, instance.array, false); var index: u21 = 0; index = 0; while (index <= 9) : (index += 1) { instance.array[index] = true; } index = 17; while (index <= 42) : (index += 1) { instance.array[index] = true; } instance.array[47] = true; index = 49; while (index <= 74) : (index += 1) { instance.array[index] = true; } instance.array[122] = true; instance.array[133] = true; instance.array[135] = true; instance.array[138] = true; index = 144; while (index <= 166) : (index += 1) { instance.array[index] = true; } index = 168; while (index <= 198) : (index += 1) { instance.array[index] = true; } index = 200; while (index <= 394) : (index += 1) { instance.array[index] = true; } instance.array[395] = true; index = 396; while (index <= 399) : (index += 1) { instance.array[index] = true; } index = 400; while (index <= 403) : (index += 1) { instance.array[index] = true; } index = 404; while (index <= 611) : (index += 1) { instance.array[index] = true; } instance.array[612] = true; index = 613; while (index <= 639) : (index += 1) { instance.array[index] = true; } index = 640; while (index <= 657) : (index += 1) { instance.array[index] = true; } index = 662; while (index <= 673) : (index += 1) { instance.array[index] = true; } index = 688; while (index <= 692) : (index += 1) { instance.array[index] = true; } instance.array[700] = true; instance.array[702] = true; index = 720; while (index <= 831) : (index += 1) { instance.array[index] = true; } index = 832; while (index <= 835) : (index += 1) { instance.array[index] = true; } instance.array[836] = true; index = 838; while (index <= 839) : (index += 1) { instance.array[index] = true; } instance.array[842] = true; index = 843; while (index <= 845) : (index += 1) { instance.array[index] = true; } instance.array[847] = true; instance.array[854] = true; instance.array[855] = true; index = 856; while (index <= 858) : (index += 1) { instance.array[index] = true; } instance.array[860] = true; index = 862; while (index <= 881) : (index += 1) { instance.array[index] = true; } index = 883; while (index <= 965) : (index += 1) { instance.array[index] = true; } index = 967; while (index <= 1105) : (index += 1) { instance.array[index] = true; } index = 1107; while (index <= 1111) : (index += 1) { instance.array[index] = true; } index = 1114; while (index <= 1279) : (index += 1) { instance.array[index] = true; } index = 1281; while (index <= 1318) : (index += 1) { instance.array[index] = true; } instance.array[1321] = true; index = 1328; while (index <= 1368) : (index += 1) { instance.array[index] = true; } index = 1377; while (index <= 1421) : (index += 1) { instance.array[index] = true; } instance.array[1423] = true; index = 1425; while (index <= 1426) : (index += 1) { instance.array[index] = true; } index = 1428; while (index <= 1429) : (index += 1) { instance.array[index] = true; } instance.array[1431] = true; index = 1440; while (index <= 1466) : (index += 1) { instance.array[index] = true; } index = 1471; while (index <= 1474) : (index += 1) { instance.array[index] = true; } index = 1504; while (index <= 1514) : (index += 1) { instance.array[index] = true; } index = 1520; while (index <= 1551) : (index += 1) { instance.array[index] = true; } instance.array[1552] = true; index = 1553; while (index <= 1562) : (index += 1) { instance.array[index] = true; } index = 1563; while (index <= 1583) : (index += 1) { instance.array[index] = true; } index = 1584; while (index <= 1593) : (index += 1) { instance.array[index] = true; } index = 1598; while (index <= 1599) : (index += 1) { instance.array[index] = true; } instance.array[1600] = true; index = 1601; while (index <= 1699) : (index += 1) { instance.array[index] = true; } instance.array[1701] = true; index = 1702; while (index <= 1708) : (index += 1) { instance.array[index] = true; } index = 1711; while (index <= 1716) : (index += 1) { instance.array[index] = true; } index = 1717; while (index <= 1718) : (index += 1) { instance.array[index] = true; } index = 1719; while (index <= 1720) : (index += 1) { instance.array[index] = true; } index = 1722; while (index <= 1725) : (index += 1) { instance.array[index] = true; } index = 1726; while (index <= 1727) : (index += 1) { instance.array[index] = true; } index = 1728; while (index <= 1737) : (index += 1) { instance.array[index] = true; } index = 1738; while (index <= 1740) : (index += 1) { instance.array[index] = true; } instance.array[1743] = true; instance.array[1760] = true; instance.array[1761] = true; index = 1762; while (index <= 1791) : (index += 1) { instance.array[index] = true; } index = 1792; while (index <= 1818) : (index += 1) { instance.array[index] = true; } index = 1821; while (index <= 1909) : (index += 1) { instance.array[index] = true; } index = 1910; while (index <= 1920) : (index += 1) { instance.array[index] = true; } instance.array[1921] = true; index = 1936; while (index <= 1945) : (index += 1) { instance.array[index] = true; } index = 1946; while (index <= 1978) : (index += 1) { instance.array[index] = true; } index = 1979; while (index <= 1987) : (index += 1) { instance.array[index] = true; } index = 1988; while (index <= 1989) : (index += 1) { instance.array[index] = true; } instance.array[1994] = true; instance.array[1997] = true; index = 2000; while (index <= 2021) : (index += 1) { instance.array[index] = true; } index = 2022; while (index <= 2025) : (index += 1) { instance.array[index] = true; } instance.array[2026] = true; index = 2027; while (index <= 2035) : (index += 1) { instance.array[index] = true; } instance.array[2036] = true; index = 2037; while (index <= 2039) : (index += 1) { instance.array[index] = true; } instance.array[2040] = true; index = 2041; while (index <= 2045) : (index += 1) { instance.array[index] = true; } index = 2064; while (index <= 2088) : (index += 1) { instance.array[index] = true; } index = 2089; while (index <= 2091) : (index += 1) { instance.array[index] = true; } index = 2096; while (index <= 2106) : (index += 1) { instance.array[index] = true; } index = 2160; while (index <= 2180) : (index += 1) { instance.array[index] = true; } index = 2182; while (index <= 2199) : (index += 1) { instance.array[index] = true; } index = 2211; while (index <= 2225) : (index += 1) { instance.array[index] = true; } index = 2227; while (index <= 2258) : (index += 1) { instance.array[index] = true; } instance.array[2259] = true; index = 2260; while (index <= 2313) : (index += 1) { instance.array[index] = true; } instance.array[2314] = true; instance.array[2315] = true; instance.array[2316] = true; instance.array[2317] = true; index = 2318; while (index <= 2320) : (index += 1) { instance.array[index] = true; } index = 2321; while (index <= 2328) : (index += 1) { instance.array[index] = true; } index = 2329; while (index <= 2332) : (index += 1) { instance.array[index] = true; } instance.array[2333] = true; index = 2334; while (index <= 2335) : (index += 1) { instance.array[index] = true; } instance.array[2336] = true; index = 2337; while (index <= 2343) : (index += 1) { instance.array[index] = true; } index = 2344; while (index <= 2353) : (index += 1) { instance.array[index] = true; } index = 2354; while (index <= 2355) : (index += 1) { instance.array[index] = true; } index = 2358; while (index <= 2367) : (index += 1) { instance.array[index] = true; } instance.array[2369] = true; index = 2370; while (index <= 2384) : (index += 1) { instance.array[index] = true; } instance.array[2385] = true; index = 2386; while (index <= 2387) : (index += 1) { instance.array[index] = true; } index = 2389; while (index <= 2396) : (index += 1) { instance.array[index] = true; } index = 2399; while (index <= 2400) : (index += 1) { instance.array[index] = true; } index = 2403; while (index <= 2424) : (index += 1) { instance.array[index] = true; } index = 2426; while (index <= 2432) : (index += 1) { instance.array[index] = true; } instance.array[2434] = true; index = 2438; while (index <= 2441) : (index += 1) { instance.array[index] = true; } instance.array[2444] = true; instance.array[2445] = true; index = 2446; while (index <= 2448) : (index += 1) { instance.array[index] = true; } index = 2449; while (index <= 2452) : (index += 1) { instance.array[index] = true; } index = 2455; while (index <= 2456) : (index += 1) { instance.array[index] = true; } index = 2459; while (index <= 2460) : (index += 1) { instance.array[index] = true; } instance.array[2461] = true; instance.array[2462] = true; instance.array[2471] = true; index = 2476; while (index <= 2477) : (index += 1) { instance.array[index] = true; } index = 2479; while (index <= 2481) : (index += 1) { instance.array[index] = true; } index = 2482; while (index <= 2483) : (index += 1) { instance.array[index] = true; } index = 2486; while (index <= 2495) : (index += 1) { instance.array[index] = true; } index = 2496; while (index <= 2497) : (index += 1) { instance.array[index] = true; } instance.array[2508] = true; instance.array[2510] = true; index = 2513; while (index <= 2514) : (index += 1) { instance.array[index] = true; } instance.array[2515] = true; index = 2517; while (index <= 2522) : (index += 1) { instance.array[index] = true; } index = 2527; while (index <= 2528) : (index += 1) { instance.array[index] = true; } index = 2531; while (index <= 2552) : (index += 1) { instance.array[index] = true; } index = 2554; while (index <= 2560) : (index += 1) { instance.array[index] = true; } index = 2562; while (index <= 2563) : (index += 1) { instance.array[index] = true; } index = 2565; while (index <= 2566) : (index += 1) { instance.array[index] = true; } index = 2568; while (index <= 2569) : (index += 1) { instance.array[index] = true; } instance.array[2572] = true; index = 2574; while (index <= 2576) : (index += 1) { instance.array[index] = true; } index = 2577; while (index <= 2578) : (index += 1) { instance.array[index] = true; } index = 2583; while (index <= 2584) : (index += 1) { instance.array[index] = true; } index = 2587; while (index <= 2589) : (index += 1) { instance.array[index] = true; } instance.array[2593] = true; index = 2601; while (index <= 2604) : (index += 1) { instance.array[index] = true; } instance.array[2606] = true; index = 2614; while (index <= 2623) : (index += 1) { instance.array[index] = true; } index = 2624; while (index <= 2625) : (index += 1) { instance.array[index] = true; } index = 2626; while (index <= 2628) : (index += 1) { instance.array[index] = true; } instance.array[2629] = true; index = 2641; while (index <= 2642) : (index += 1) { instance.array[index] = true; } instance.array[2643] = true; index = 2645; while (index <= 2653) : (index += 1) { instance.array[index] = true; } index = 2655; while (index <= 2657) : (index += 1) { instance.array[index] = true; } index = 2659; while (index <= 2680) : (index += 1) { instance.array[index] = true; } index = 2682; while (index <= 2688) : (index += 1) { instance.array[index] = true; } index = 2690; while (index <= 2691) : (index += 1) { instance.array[index] = true; } index = 2693; while (index <= 2697) : (index += 1) { instance.array[index] = true; } instance.array[2700] = true; instance.array[2701] = true; index = 2702; while (index <= 2704) : (index += 1) { instance.array[index] = true; } index = 2705; while (index <= 2709) : (index += 1) { instance.array[index] = true; } index = 2711; while (index <= 2712) : (index += 1) { instance.array[index] = true; } instance.array[2713] = true; index = 2715; while (index <= 2716) : (index += 1) { instance.array[index] = true; } instance.array[2717] = true; instance.array[2720] = true; index = 2736; while (index <= 2737) : (index += 1) { instance.array[index] = true; } index = 2738; while (index <= 2739) : (index += 1) { instance.array[index] = true; } index = 2742; while (index <= 2751) : (index += 1) { instance.array[index] = true; } instance.array[2761] = true; index = 2762; while (index <= 2767) : (index += 1) { instance.array[index] = true; } instance.array[2769] = true; index = 2770; while (index <= 2771) : (index += 1) { instance.array[index] = true; } index = 2773; while (index <= 2780) : (index += 1) { instance.array[index] = true; } index = 2783; while (index <= 2784) : (index += 1) { instance.array[index] = true; } index = 2787; while (index <= 2808) : (index += 1) { instance.array[index] = true; } index = 2810; while (index <= 2816) : (index += 1) { instance.array[index] = true; } index = 2818; while (index <= 2819) : (index += 1) { instance.array[index] = true; } index = 2821; while (index <= 2825) : (index += 1) { instance.array[index] = true; } instance.array[2828] = true; instance.array[2829] = true; instance.array[2830] = true; instance.array[2831] = true; instance.array[2832] = true; index = 2833; while (index <= 2836) : (index += 1) { instance.array[index] = true; } index = 2839; while (index <= 2840) : (index += 1) { instance.array[index] = true; } index = 2843; while (index <= 2844) : (index += 1) { instance.array[index] = true; } instance.array[2845] = true; index = 2853; while (index <= 2854) : (index += 1) { instance.array[index] = true; } instance.array[2855] = true; index = 2860; while (index <= 2861) : (index += 1) { instance.array[index] = true; } index = 2863; while (index <= 2865) : (index += 1) { instance.array[index] = true; } index = 2866; while (index <= 2867) : (index += 1) { instance.array[index] = true; } index = 2870; while (index <= 2879) : (index += 1) { instance.array[index] = true; } instance.array[2881] = true; instance.array[2898] = true; instance.array[2899] = true; index = 2901; while (index <= 2906) : (index += 1) { instance.array[index] = true; } index = 2910; while (index <= 2912) : (index += 1) { instance.array[index] = true; } index = 2914; while (index <= 2917) : (index += 1) { instance.array[index] = true; } index = 2921; while (index <= 2922) : (index += 1) { instance.array[index] = true; } instance.array[2924] = true; index = 2926; while (index <= 2927) : (index += 1) { instance.array[index] = true; } index = 2931; while (index <= 2932) : (index += 1) { instance.array[index] = true; } index = 2936; while (index <= 2938) : (index += 1) { instance.array[index] = true; } index = 2942; while (index <= 2953) : (index += 1) { instance.array[index] = true; } index = 2958; while (index <= 2959) : (index += 1) { instance.array[index] = true; } instance.array[2960] = true; index = 2961; while (index <= 2962) : (index += 1) { instance.array[index] = true; } index = 2966; while (index <= 2968) : (index += 1) { instance.array[index] = true; } index = 2970; while (index <= 2972) : (index += 1) { instance.array[index] = true; } instance.array[2973] = true; instance.array[2976] = true; instance.array[2983] = true; index = 2998; while (index <= 3007) : (index += 1) { instance.array[index] = true; } instance.array[3024] = true; index = 3025; while (index <= 3027) : (index += 1) { instance.array[index] = true; } instance.array[3028] = true; index = 3029; while (index <= 3036) : (index += 1) { instance.array[index] = true; } index = 3038; while (index <= 3040) : (index += 1) { instance.array[index] = true; } index = 3042; while (index <= 3064) : (index += 1) { instance.array[index] = true; } index = 3066; while (index <= 3081) : (index += 1) { instance.array[index] = true; } instance.array[3085] = true; index = 3086; while (index <= 3088) : (index += 1) { instance.array[index] = true; } index = 3089; while (index <= 3092) : (index += 1) { instance.array[index] = true; } index = 3094; while (index <= 3096) : (index += 1) { instance.array[index] = true; } index = 3098; while (index <= 3101) : (index += 1) { instance.array[index] = true; } index = 3109; while (index <= 3110) : (index += 1) { instance.array[index] = true; } index = 3112; while (index <= 3114) : (index += 1) { instance.array[index] = true; } index = 3120; while (index <= 3121) : (index += 1) { instance.array[index] = true; } index = 3122; while (index <= 3123) : (index += 1) { instance.array[index] = true; } index = 3126; while (index <= 3135) : (index += 1) { instance.array[index] = true; } instance.array[3152] = true; instance.array[3153] = true; index = 3154; while (index <= 3155) : (index += 1) { instance.array[index] = true; } index = 3157; while (index <= 3164) : (index += 1) { instance.array[index] = true; } index = 3166; while (index <= 3168) : (index += 1) { instance.array[index] = true; } index = 3170; while (index <= 3192) : (index += 1) { instance.array[index] = true; } index = 3194; while (index <= 3203) : (index += 1) { instance.array[index] = true; } index = 3205; while (index <= 3209) : (index += 1) { instance.array[index] = true; } instance.array[3212] = true; instance.array[3213] = true; instance.array[3214] = true; instance.array[3215] = true; index = 3216; while (index <= 3220) : (index += 1) { instance.array[index] = true; } instance.array[3222] = true; index = 3223; while (index <= 3224) : (index += 1) { instance.array[index] = true; } index = 3226; while (index <= 3227) : (index += 1) { instance.array[index] = true; } index = 3228; while (index <= 3229) : (index += 1) { instance.array[index] = true; } index = 3237; while (index <= 3238) : (index += 1) { instance.array[index] = true; } instance.array[3246] = true; index = 3248; while (index <= 3249) : (index += 1) { instance.array[index] = true; } index = 3250; while (index <= 3251) : (index += 1) { instance.array[index] = true; } index = 3254; while (index <= 3263) : (index += 1) { instance.array[index] = true; } index = 3265; while (index <= 3266) : (index += 1) { instance.array[index] = true; } index = 3280; while (index <= 3281) : (index += 1) { instance.array[index] = true; } index = 3282; while (index <= 3283) : (index += 1) { instance.array[index] = true; } index = 3284; while (index <= 3292) : (index += 1) { instance.array[index] = true; } index = 3294; while (index <= 3296) : (index += 1) { instance.array[index] = true; } index = 3298; while (index <= 3338) : (index += 1) { instance.array[index] = true; } index = 3339; while (index <= 3340) : (index += 1) { instance.array[index] = true; } instance.array[3341] = true; index = 3342; while (index <= 3344) : (index += 1) { instance.array[index] = true; } index = 3345; while (index <= 3348) : (index += 1) { instance.array[index] = true; } index = 3350; while (index <= 3352) : (index += 1) { instance.array[index] = true; } index = 3354; while (index <= 3356) : (index += 1) { instance.array[index] = true; } instance.array[3357] = true; instance.array[3358] = true; index = 3364; while (index <= 3366) : (index += 1) { instance.array[index] = true; } instance.array[3367] = true; index = 3375; while (index <= 3377) : (index += 1) { instance.array[index] = true; } index = 3378; while (index <= 3379) : (index += 1) { instance.array[index] = true; } index = 3382; while (index <= 3391) : (index += 1) { instance.array[index] = true; } index = 3402; while (index <= 3407) : (index += 1) { instance.array[index] = true; } instance.array[3409] = true; index = 3410; while (index <= 3411) : (index += 1) { instance.array[index] = true; } index = 3413; while (index <= 3430) : (index += 1) { instance.array[index] = true; } index = 3434; while (index <= 3457) : (index += 1) { instance.array[index] = true; } index = 3459; while (index <= 3467) : (index += 1) { instance.array[index] = true; } instance.array[3469] = true; index = 3472; while (index <= 3478) : (index += 1) { instance.array[index] = true; } instance.array[3482] = true; index = 3487; while (index <= 3489) : (index += 1) { instance.array[index] = true; } index = 3490; while (index <= 3492) : (index += 1) { instance.array[index] = true; } instance.array[3494] = true; index = 3496; while (index <= 3503) : (index += 1) { instance.array[index] = true; } index = 3510; while (index <= 3519) : (index += 1) { instance.array[index] = true; } index = 3522; while (index <= 3523) : (index += 1) { instance.array[index] = true; } index = 3537; while (index <= 3584) : (index += 1) { instance.array[index] = true; } instance.array[3585] = true; index = 3586; while (index <= 3587) : (index += 1) { instance.array[index] = true; } index = 3588; while (index <= 3594) : (index += 1) { instance.array[index] = true; } index = 3600; while (index <= 3605) : (index += 1) { instance.array[index] = true; } instance.array[3606] = true; index = 3607; while (index <= 3614) : (index += 1) { instance.array[index] = true; } index = 3616; while (index <= 3625) : (index += 1) { instance.array[index] = true; } index = 3665; while (index <= 3666) : (index += 1) { instance.array[index] = true; } instance.array[3668] = true; index = 3670; while (index <= 3674) : (index += 1) { instance.array[index] = true; } index = 3676; while (index <= 3699) : (index += 1) { instance.array[index] = true; } instance.array[3701] = true; index = 3703; while (index <= 3712) : (index += 1) { instance.array[index] = true; } instance.array[3713] = true; index = 3714; while (index <= 3715) : (index += 1) { instance.array[index] = true; } index = 3716; while (index <= 3724) : (index += 1) { instance.array[index] = true; } instance.array[3725] = true; index = 3728; while (index <= 3732) : (index += 1) { instance.array[index] = true; } instance.array[3734] = true; index = 3736; while (index <= 3741) : (index += 1) { instance.array[index] = true; } index = 3744; while (index <= 3753) : (index += 1) { instance.array[index] = true; } index = 3756; while (index <= 3759) : (index += 1) { instance.array[index] = true; } instance.array[3792] = true; index = 3816; while (index <= 3817) : (index += 1) { instance.array[index] = true; } index = 3824; while (index <= 3833) : (index += 1) { instance.array[index] = true; } instance.array[3845] = true; instance.array[3847] = true; instance.array[3849] = true; index = 3854; while (index <= 3855) : (index += 1) { instance.array[index] = true; } index = 3856; while (index <= 3863) : (index += 1) { instance.array[index] = true; } index = 3865; while (index <= 3900) : (index += 1) { instance.array[index] = true; } index = 3905; while (index <= 3918) : (index += 1) { instance.array[index] = true; } instance.array[3919] = true; index = 3920; while (index <= 3924) : (index += 1) { instance.array[index] = true; } index = 3926; while (index <= 3927) : (index += 1) { instance.array[index] = true; } index = 3928; while (index <= 3932) : (index += 1) { instance.array[index] = true; } index = 3933; while (index <= 3943) : (index += 1) { instance.array[index] = true; } index = 3945; while (index <= 3980) : (index += 1) { instance.array[index] = true; } instance.array[3990] = true; index = 4048; while (index <= 4090) : (index += 1) { instance.array[index] = true; } index = 4091; while (index <= 4092) : (index += 1) { instance.array[index] = true; } index = 4093; while (index <= 4096) : (index += 1) { instance.array[index] = true; } instance.array[4097] = true; index = 4098; while (index <= 4103) : (index += 1) { instance.array[index] = true; } instance.array[4104] = true; index = 4105; while (index <= 4106) : (index += 1) { instance.array[index] = true; } index = 4107; while (index <= 4108) : (index += 1) { instance.array[index] = true; } index = 4109; while (index <= 4110) : (index += 1) { instance.array[index] = true; } instance.array[4111] = true; index = 4112; while (index <= 4121) : (index += 1) { instance.array[index] = true; } index = 4128; while (index <= 4133) : (index += 1) { instance.array[index] = true; } index = 4134; while (index <= 4135) : (index += 1) { instance.array[index] = true; } index = 4136; while (index <= 4137) : (index += 1) { instance.array[index] = true; } index = 4138; while (index <= 4141) : (index += 1) { instance.array[index] = true; } index = 4142; while (index <= 4144) : (index += 1) { instance.array[index] = true; } instance.array[4145] = true; index = 4146; while (index <= 4148) : (index += 1) { instance.array[index] = true; } index = 4149; while (index <= 4150) : (index += 1) { instance.array[index] = true; } index = 4151; while (index <= 4157) : (index += 1) { instance.array[index] = true; } index = 4158; while (index <= 4160) : (index += 1) { instance.array[index] = true; } index = 4161; while (index <= 4164) : (index += 1) { instance.array[index] = true; } index = 4165; while (index <= 4177) : (index += 1) { instance.array[index] = true; } instance.array[4178] = true; index = 4179; while (index <= 4180) : (index += 1) { instance.array[index] = true; } index = 4181; while (index <= 4182) : (index += 1) { instance.array[index] = true; } index = 4183; while (index <= 4188) : (index += 1) { instance.array[index] = true; } instance.array[4189] = true; instance.array[4190] = true; instance.array[4191] = true; index = 4192; while (index <= 4201) : (index += 1) { instance.array[index] = true; } index = 4202; while (index <= 4204) : (index += 1) { instance.array[index] = true; } instance.array[4205] = true; index = 4208; while (index <= 4245) : (index += 1) { instance.array[index] = true; } instance.array[4247] = true; instance.array[4253] = true; index = 4256; while (index <= 4298) : (index += 1) { instance.array[index] = true; } instance.array[4300] = true; index = 4301; while (index <= 4303) : (index += 1) { instance.array[index] = true; } index = 4304; while (index <= 4632) : (index += 1) { instance.array[index] = true; } index = 4634; while (index <= 4637) : (index += 1) { instance.array[index] = true; } index = 4640; while (index <= 4646) : (index += 1) { instance.array[index] = true; } instance.array[4648] = true; index = 4650; while (index <= 4653) : (index += 1) { instance.array[index] = true; } index = 4656; while (index <= 4696) : (index += 1) { instance.array[index] = true; } index = 4698; while (index <= 4701) : (index += 1) { instance.array[index] = true; } index = 4704; while (index <= 4736) : (index += 1) { instance.array[index] = true; } index = 4738; while (index <= 4741) : (index += 1) { instance.array[index] = true; } index = 4744; while (index <= 4750) : (index += 1) { instance.array[index] = true; } instance.array[4752] = true; index = 4754; while (index <= 4757) : (index += 1) { instance.array[index] = true; } index = 4760; while (index <= 4774) : (index += 1) { instance.array[index] = true; } index = 4776; while (index <= 4832) : (index += 1) { instance.array[index] = true; } index = 4834; while (index <= 4837) : (index += 1) { instance.array[index] = true; } index = 4840; while (index <= 4906) : (index += 1) { instance.array[index] = true; } index = 4909; while (index <= 4911) : (index += 1) { instance.array[index] = true; } index = 4921; while (index <= 4929) : (index += 1) { instance.array[index] = true; } index = 4944; while (index <= 4959) : (index += 1) { instance.array[index] = true; } index = 4976; while (index <= 5061) : (index += 1) { instance.array[index] = true; } index = 5064; while (index <= 5069) : (index += 1) { instance.array[index] = true; } index = 5073; while (index <= 5692) : (index += 1) { instance.array[index] = true; } index = 5695; while (index <= 5711) : (index += 1) { instance.array[index] = true; } index = 5713; while (index <= 5738) : (index += 1) { instance.array[index] = true; } index = 5744; while (index <= 5818) : (index += 1) { instance.array[index] = true; } index = 5822; while (index <= 5824) : (index += 1) { instance.array[index] = true; } index = 5825; while (index <= 5832) : (index += 1) { instance.array[index] = true; } index = 5840; while (index <= 5852) : (index += 1) { instance.array[index] = true; } index = 5854; while (index <= 5857) : (index += 1) { instance.array[index] = true; } index = 5858; while (index <= 5860) : (index += 1) { instance.array[index] = true; } index = 5872; while (index <= 5889) : (index += 1) { instance.array[index] = true; } index = 5890; while (index <= 5892) : (index += 1) { instance.array[index] = true; } index = 5904; while (index <= 5921) : (index += 1) { instance.array[index] = true; } index = 5922; while (index <= 5923) : (index += 1) { instance.array[index] = true; } index = 5936; while (index <= 5948) : (index += 1) { instance.array[index] = true; } index = 5950; while (index <= 5952) : (index += 1) { instance.array[index] = true; } index = 5954; while (index <= 5955) : (index += 1) { instance.array[index] = true; } index = 5968; while (index <= 6019) : (index += 1) { instance.array[index] = true; } index = 6020; while (index <= 6021) : (index += 1) { instance.array[index] = true; } instance.array[6022] = true; index = 6023; while (index <= 6029) : (index += 1) { instance.array[index] = true; } index = 6030; while (index <= 6037) : (index += 1) { instance.array[index] = true; } instance.array[6038] = true; index = 6039; while (index <= 6040) : (index += 1) { instance.array[index] = true; } index = 6041; while (index <= 6051) : (index += 1) { instance.array[index] = true; } instance.array[6055] = true; instance.array[6060] = true; instance.array[6061] = true; index = 6064; while (index <= 6073) : (index += 1) { instance.array[index] = true; } index = 6107; while (index <= 6109) : (index += 1) { instance.array[index] = true; } index = 6112; while (index <= 6121) : (index += 1) { instance.array[index] = true; } index = 6128; while (index <= 6162) : (index += 1) { instance.array[index] = true; } instance.array[6163] = true; index = 6164; while (index <= 6216) : (index += 1) { instance.array[index] = true; } index = 6224; while (index <= 6228) : (index += 1) { instance.array[index] = true; } index = 6229; while (index <= 6230) : (index += 1) { instance.array[index] = true; } index = 6231; while (index <= 6264) : (index += 1) { instance.array[index] = true; } instance.array[6265] = true; instance.array[6266] = true; index = 6272; while (index <= 6341) : (index += 1) { instance.array[index] = true; } index = 6352; while (index <= 6382) : (index += 1) { instance.array[index] = true; } index = 6384; while (index <= 6386) : (index += 1) { instance.array[index] = true; } index = 6387; while (index <= 6390) : (index += 1) { instance.array[index] = true; } index = 6391; while (index <= 6392) : (index += 1) { instance.array[index] = true; } index = 6393; while (index <= 6395) : (index += 1) { instance.array[index] = true; } index = 6400; while (index <= 6401) : (index += 1) { instance.array[index] = true; } instance.array[6402] = true; index = 6403; while (index <= 6408) : (index += 1) { instance.array[index] = true; } index = 6409; while (index <= 6411) : (index += 1) { instance.array[index] = true; } index = 6422; while (index <= 6431) : (index += 1) { instance.array[index] = true; } index = 6432; while (index <= 6461) : (index += 1) { instance.array[index] = true; } index = 6464; while (index <= 6468) : (index += 1) { instance.array[index] = true; } index = 6480; while (index <= 6523) : (index += 1) { instance.array[index] = true; } index = 6528; while (index <= 6553) : (index += 1) { instance.array[index] = true; } index = 6560; while (index <= 6569) : (index += 1) { instance.array[index] = true; } instance.array[6570] = true; index = 6608; while (index <= 6630) : (index += 1) { instance.array[index] = true; } index = 6631; while (index <= 6632) : (index += 1) { instance.array[index] = true; } index = 6633; while (index <= 6634) : (index += 1) { instance.array[index] = true; } instance.array[6635] = true; index = 6640; while (index <= 6692) : (index += 1) { instance.array[index] = true; } instance.array[6693] = true; instance.array[6694] = true; instance.array[6695] = true; index = 6696; while (index <= 6702) : (index += 1) { instance.array[index] = true; } instance.array[6704] = true; instance.array[6705] = true; instance.array[6706] = true; index = 6707; while (index <= 6708) : (index += 1) { instance.array[index] = true; } index = 6709; while (index <= 6716) : (index += 1) { instance.array[index] = true; } index = 6717; while (index <= 6722) : (index += 1) { instance.array[index] = true; } index = 6723; while (index <= 6732) : (index += 1) { instance.array[index] = true; } instance.array[6735] = true; index = 6736; while (index <= 6745) : (index += 1) { instance.array[index] = true; } index = 6752; while (index <= 6761) : (index += 1) { instance.array[index] = true; } instance.array[6775] = true; index = 6784; while (index <= 6797) : (index += 1) { instance.array[index] = true; } index = 6799; while (index <= 6800) : (index += 1) { instance.array[index] = true; } index = 6864; while (index <= 6867) : (index += 1) { instance.array[index] = true; } instance.array[6868] = true; index = 6869; while (index <= 6915) : (index += 1) { instance.array[index] = true; } instance.array[6916] = true; instance.array[6917] = true; index = 6918; while (index <= 6922) : (index += 1) { instance.array[index] = true; } instance.array[6923] = true; instance.array[6924] = true; index = 6925; while (index <= 6929) : (index += 1) { instance.array[index] = true; } instance.array[6930] = true; index = 6931; while (index <= 6932) : (index += 1) { instance.array[index] = true; } index = 6933; while (index <= 6939) : (index += 1) { instance.array[index] = true; } index = 6944; while (index <= 6953) : (index += 1) { instance.array[index] = true; } index = 6971; while (index <= 6979) : (index += 1) { instance.array[index] = true; } index = 6992; while (index <= 6993) : (index += 1) { instance.array[index] = true; } instance.array[6994] = true; index = 6995; while (index <= 7024) : (index += 1) { instance.array[index] = true; } instance.array[7025] = true; index = 7026; while (index <= 7029) : (index += 1) { instance.array[index] = true; } index = 7030; while (index <= 7031) : (index += 1) { instance.array[index] = true; } index = 7032; while (index <= 7033) : (index += 1) { instance.array[index] = true; } instance.array[7034] = true; index = 7035; while (index <= 7037) : (index += 1) { instance.array[index] = true; } index = 7038; while (index <= 7039) : (index += 1) { instance.array[index] = true; } index = 7040; while (index <= 7049) : (index += 1) { instance.array[index] = true; } index = 7050; while (index <= 7093) : (index += 1) { instance.array[index] = true; } instance.array[7094] = true; instance.array[7095] = true; index = 7096; while (index <= 7097) : (index += 1) { instance.array[index] = true; } index = 7098; while (index <= 7100) : (index += 1) { instance.array[index] = true; } instance.array[7101] = true; instance.array[7102] = true; index = 7103; while (index <= 7105) : (index += 1) { instance.array[index] = true; } index = 7106; while (index <= 7107) : (index += 1) { instance.array[index] = true; } index = 7120; while (index <= 7155) : (index += 1) { instance.array[index] = true; } index = 7156; while (index <= 7163) : (index += 1) { instance.array[index] = true; } index = 7164; while (index <= 7171) : (index += 1) { instance.array[index] = true; } index = 7172; while (index <= 7173) : (index += 1) { instance.array[index] = true; } index = 7174; while (index <= 7175) : (index += 1) { instance.array[index] = true; } index = 7184; while (index <= 7193) : (index += 1) { instance.array[index] = true; } index = 7197; while (index <= 7199) : (index += 1) { instance.array[index] = true; } index = 7200; while (index <= 7209) : (index += 1) { instance.array[index] = true; } index = 7210; while (index <= 7239) : (index += 1) { instance.array[index] = true; } index = 7240; while (index <= 7245) : (index += 1) { instance.array[index] = true; } index = 7248; while (index <= 7256) : (index += 1) { instance.array[index] = true; } index = 7264; while (index <= 7306) : (index += 1) { instance.array[index] = true; } index = 7309; while (index <= 7311) : (index += 1) { instance.array[index] = true; } index = 7328; while (index <= 7330) : (index += 1) { instance.array[index] = true; } index = 7332; while (index <= 7344) : (index += 1) { instance.array[index] = true; } instance.array[7345] = true; index = 7346; while (index <= 7352) : (index += 1) { instance.array[index] = true; } index = 7353; while (index <= 7356) : (index += 1) { instance.array[index] = true; } instance.array[7357] = true; index = 7358; while (index <= 7363) : (index += 1) { instance.array[index] = true; } instance.array[7364] = true; index = 7365; while (index <= 7366) : (index += 1) { instance.array[index] = true; } instance.array[7367] = true; index = 7368; while (index <= 7369) : (index += 1) { instance.array[index] = true; } instance.array[7370] = true; index = 7376; while (index <= 7419) : (index += 1) { instance.array[index] = true; } index = 7420; while (index <= 7482) : (index += 1) { instance.array[index] = true; } index = 7483; while (index <= 7495) : (index += 1) { instance.array[index] = true; } instance.array[7496] = true; index = 7497; while (index <= 7530) : (index += 1) { instance.array[index] = true; } index = 7531; while (index <= 7567) : (index += 1) { instance.array[index] = true; } index = 7568; while (index <= 7625) : (index += 1) { instance.array[index] = true; } index = 7627; while (index <= 7631) : (index += 1) { instance.array[index] = true; } index = 7632; while (index <= 7909) : (index += 1) { instance.array[index] = true; } index = 7912; while (index <= 7917) : (index += 1) { instance.array[index] = true; } index = 7920; while (index <= 7957) : (index += 1) { instance.array[index] = true; } index = 7960; while (index <= 7965) : (index += 1) { instance.array[index] = true; } index = 7968; while (index <= 7975) : (index += 1) { instance.array[index] = true; } instance.array[7977] = true; instance.array[7979] = true; instance.array[7981] = true; index = 7983; while (index <= 8013) : (index += 1) { instance.array[index] = true; } index = 8016; while (index <= 8068) : (index += 1) { instance.array[index] = true; } index = 8070; while (index <= 8076) : (index += 1) { instance.array[index] = true; } instance.array[8078] = true; index = 8082; while (index <= 8084) : (index += 1) { instance.array[index] = true; } index = 8086; while (index <= 8092) : (index += 1) { instance.array[index] = true; } index = 8096; while (index <= 8099) : (index += 1) { instance.array[index] = true; } index = 8102; while (index <= 8107) : (index += 1) { instance.array[index] = true; } index = 8112; while (index <= 8124) : (index += 1) { instance.array[index] = true; } index = 8130; while (index <= 8132) : (index += 1) { instance.array[index] = true; } index = 8134; while (index <= 8140) : (index += 1) { instance.array[index] = true; } index = 8207; while (index <= 8208) : (index += 1) { instance.array[index] = true; } instance.array[8228] = true; instance.array[8257] = true; instance.array[8271] = true; index = 8288; while (index <= 8300) : (index += 1) { instance.array[index] = true; } index = 8352; while (index <= 8364) : (index += 1) { instance.array[index] = true; } instance.array[8369] = true; index = 8373; while (index <= 8384) : (index += 1) { instance.array[index] = true; } instance.array[8402] = true; instance.array[8407] = true; index = 8410; while (index <= 8419) : (index += 1) { instance.array[index] = true; } instance.array[8421] = true; instance.array[8424] = true; index = 8425; while (index <= 8429) : (index += 1) { instance.array[index] = true; } instance.array[8436] = true; instance.array[8438] = true; instance.array[8440] = true; index = 8442; while (index <= 8445) : (index += 1) { instance.array[index] = true; } instance.array[8446] = true; index = 8447; while (index <= 8452) : (index += 1) { instance.array[index] = true; } index = 8453; while (index <= 8456) : (index += 1) { instance.array[index] = true; } instance.array[8457] = true; index = 8460; while (index <= 8463) : (index += 1) { instance.array[index] = true; } index = 8469; while (index <= 8473) : (index += 1) { instance.array[index] = true; } instance.array[8478] = true; index = 8496; while (index <= 8530) : (index += 1) { instance.array[index] = true; } index = 8531; while (index <= 8532) : (index += 1) { instance.array[index] = true; } index = 8533; while (index <= 8536) : (index += 1) { instance.array[index] = true; } index = 11216; while (index <= 11262) : (index += 1) { instance.array[index] = true; } index = 11264; while (index <= 11310) : (index += 1) { instance.array[index] = true; } index = 11312; while (index <= 11339) : (index += 1) { instance.array[index] = true; } index = 11340; while (index <= 11341) : (index += 1) { instance.array[index] = true; } index = 11342; while (index <= 11444) : (index += 1) { instance.array[index] = true; } index = 11451; while (index <= 11454) : (index += 1) { instance.array[index] = true; } index = 11455; while (index <= 11457) : (index += 1) { instance.array[index] = true; } index = 11458; while (index <= 11459) : (index += 1) { instance.array[index] = true; } index = 11472; while (index <= 11509) : (index += 1) { instance.array[index] = true; } instance.array[11511] = true; instance.array[11517] = true; index = 11520; while (index <= 11575) : (index += 1) { instance.array[index] = true; } instance.array[11583] = true; instance.array[11599] = true; index = 11600; while (index <= 11622) : (index += 1) { instance.array[index] = true; } index = 11632; while (index <= 11638) : (index += 1) { instance.array[index] = true; } index = 11640; while (index <= 11646) : (index += 1) { instance.array[index] = true; } index = 11648; while (index <= 11654) : (index += 1) { instance.array[index] = true; } index = 11656; while (index <= 11662) : (index += 1) { instance.array[index] = true; } index = 11664; while (index <= 11670) : (index += 1) { instance.array[index] = true; } index = 11672; while (index <= 11678) : (index += 1) { instance.array[index] = true; } index = 11680; while (index <= 11686) : (index += 1) { instance.array[index] = true; } index = 11688; while (index <= 11694) : (index += 1) { instance.array[index] = true; } index = 11696; while (index <= 11727) : (index += 1) { instance.array[index] = true; } instance.array[12245] = true; instance.array[12246] = true; instance.array[12247] = true; index = 12273; while (index <= 12281) : (index += 1) { instance.array[index] = true; } index = 12282; while (index <= 12285) : (index += 1) { instance.array[index] = true; } index = 12286; while (index <= 12287) : (index += 1) { instance.array[index] = true; } index = 12289; while (index <= 12293) : (index += 1) { instance.array[index] = true; } index = 12296; while (index <= 12298) : (index += 1) { instance.array[index] = true; } instance.array[12299] = true; instance.array[12300] = true; index = 12305; while (index <= 12390) : (index += 1) { instance.array[index] = true; } index = 12393; while (index <= 12394) : (index += 1) { instance.array[index] = true; } index = 12395; while (index <= 12396) : (index += 1) { instance.array[index] = true; } index = 12397; while (index <= 12398) : (index += 1) { instance.array[index] = true; } instance.array[12399] = true; index = 12401; while (index <= 12490) : (index += 1) { instance.array[index] = true; } index = 12492; while (index <= 12494) : (index += 1) { instance.array[index] = true; } instance.array[12495] = true; index = 12501; while (index <= 12543) : (index += 1) { instance.array[index] = true; } index = 12545; while (index <= 12638) : (index += 1) { instance.array[index] = true; } index = 12656; while (index <= 12687) : (index += 1) { instance.array[index] = true; } index = 12736; while (index <= 12751) : (index += 1) { instance.array[index] = true; } index = 13264; while (index <= 19855) : (index += 1) { instance.array[index] = true; } index = 19920; while (index <= 40908) : (index += 1) { instance.array[index] = true; } index = 40912; while (index <= 40932) : (index += 1) { instance.array[index] = true; } instance.array[40933] = true; index = 40934; while (index <= 42076) : (index += 1) { instance.array[index] = true; } index = 42144; while (index <= 42183) : (index += 1) { instance.array[index] = true; } index = 42184; while (index <= 42189) : (index += 1) { instance.array[index] = true; } index = 42192; while (index <= 42459) : (index += 1) { instance.array[index] = true; } instance.array[42460] = true; index = 42464; while (index <= 42479) : (index += 1) { instance.array[index] = true; } index = 42480; while (index <= 42489) : (index += 1) { instance.array[index] = true; } index = 42490; while (index <= 42491) : (index += 1) { instance.array[index] = true; } index = 42512; while (index <= 42557) : (index += 1) { instance.array[index] = true; } instance.array[42558] = true; instance.array[42559] = true; index = 42564; while (index <= 42573) : (index += 1) { instance.array[index] = true; } instance.array[42575] = true; index = 42576; while (index <= 42603) : (index += 1) { instance.array[index] = true; } index = 42604; while (index <= 42605) : (index += 1) { instance.array[index] = true; } index = 42606; while (index <= 42607) : (index += 1) { instance.array[index] = true; } index = 42608; while (index <= 42677) : (index += 1) { instance.array[index] = true; } index = 42678; while (index <= 42687) : (index += 1) { instance.array[index] = true; } index = 42688; while (index <= 42689) : (index += 1) { instance.array[index] = true; } index = 42727; while (index <= 42735) : (index += 1) { instance.array[index] = true; } index = 42738; while (index <= 42815) : (index += 1) { instance.array[index] = true; } instance.array[42816] = true; index = 42817; while (index <= 42839) : (index += 1) { instance.array[index] = true; } instance.array[42840] = true; index = 42843; while (index <= 42846) : (index += 1) { instance.array[index] = true; } instance.array[42847] = true; index = 42848; while (index <= 42895) : (index += 1) { instance.array[index] = true; } index = 42898; while (index <= 42906) : (index += 1) { instance.array[index] = true; } index = 42949; while (index <= 42950) : (index += 1) { instance.array[index] = true; } instance.array[42951] = true; index = 42952; while (index <= 42953) : (index += 1) { instance.array[index] = true; } instance.array[42954] = true; index = 42955; while (index <= 42961) : (index += 1) { instance.array[index] = true; } instance.array[42962] = true; index = 42963; while (index <= 42965) : (index += 1) { instance.array[index] = true; } instance.array[42966] = true; index = 42967; while (index <= 42970) : (index += 1) { instance.array[index] = true; } instance.array[42971] = true; index = 42972; while (index <= 42994) : (index += 1) { instance.array[index] = true; } index = 42995; while (index <= 42996) : (index += 1) { instance.array[index] = true; } index = 42997; while (index <= 42998) : (index += 1) { instance.array[index] = true; } instance.array[42999] = true; instance.array[43004] = true; index = 43024; while (index <= 43075) : (index += 1) { instance.array[index] = true; } index = 43088; while (index <= 43089) : (index += 1) { instance.array[index] = true; } index = 43090; while (index <= 43139) : (index += 1) { instance.array[index] = true; } index = 43140; while (index <= 43155) : (index += 1) { instance.array[index] = true; } index = 43156; while (index <= 43157) : (index += 1) { instance.array[index] = true; } index = 43168; while (index <= 43177) : (index += 1) { instance.array[index] = true; } index = 43184; while (index <= 43201) : (index += 1) { instance.array[index] = true; } index = 43202; while (index <= 43207) : (index += 1) { instance.array[index] = true; } instance.array[43211] = true; index = 43213; while (index <= 43214) : (index += 1) { instance.array[index] = true; } instance.array[43215] = true; index = 43216; while (index <= 43225) : (index += 1) { instance.array[index] = true; } index = 43226; while (index <= 43253) : (index += 1) { instance.array[index] = true; } index = 43254; while (index <= 43261) : (index += 1) { instance.array[index] = true; } index = 43264; while (index <= 43286) : (index += 1) { instance.array[index] = true; } index = 43287; while (index <= 43297) : (index += 1) { instance.array[index] = true; } index = 43298; while (index <= 43299) : (index += 1) { instance.array[index] = true; } index = 43312; while (index <= 43340) : (index += 1) { instance.array[index] = true; } index = 43344; while (index <= 43346) : (index += 1) { instance.array[index] = true; } instance.array[43347] = true; index = 43348; while (index <= 43394) : (index += 1) { instance.array[index] = true; } instance.array[43395] = true; index = 43396; while (index <= 43397) : (index += 1) { instance.array[index] = true; } index = 43398; while (index <= 43401) : (index += 1) { instance.array[index] = true; } index = 43402; while (index <= 43403) : (index += 1) { instance.array[index] = true; } index = 43404; while (index <= 43405) : (index += 1) { instance.array[index] = true; } index = 43406; while (index <= 43408) : (index += 1) { instance.array[index] = true; } instance.array[43423] = true; index = 43424; while (index <= 43433) : (index += 1) { instance.array[index] = true; } index = 43440; while (index <= 43444) : (index += 1) { instance.array[index] = true; } instance.array[43445] = true; instance.array[43446] = true; index = 43447; while (index <= 43455) : (index += 1) { instance.array[index] = true; } index = 43456; while (index <= 43465) : (index += 1) { instance.array[index] = true; } index = 43466; while (index <= 43470) : (index += 1) { instance.array[index] = true; } index = 43472; while (index <= 43512) : (index += 1) { instance.array[index] = true; } index = 43513; while (index <= 43518) : (index += 1) { instance.array[index] = true; } index = 43519; while (index <= 43520) : (index += 1) { instance.array[index] = true; } index = 43521; while (index <= 43522) : (index += 1) { instance.array[index] = true; } index = 43523; while (index <= 43524) : (index += 1) { instance.array[index] = true; } index = 43525; while (index <= 43526) : (index += 1) { instance.array[index] = true; } index = 43536; while (index <= 43538) : (index += 1) { instance.array[index] = true; } instance.array[43539] = true; index = 43540; while (index <= 43547) : (index += 1) { instance.array[index] = true; } instance.array[43548] = true; instance.array[43549] = true; index = 43552; while (index <= 43561) : (index += 1) { instance.array[index] = true; } index = 43568; while (index <= 43583) : (index += 1) { instance.array[index] = true; } instance.array[43584] = true; index = 43585; while (index <= 43590) : (index += 1) { instance.array[index] = true; } instance.array[43594] = true; instance.array[43595] = true; instance.array[43596] = true; instance.array[43597] = true; index = 43598; while (index <= 43647) : (index += 1) { instance.array[index] = true; } instance.array[43648] = true; instance.array[43649] = true; index = 43650; while (index <= 43652) : (index += 1) { instance.array[index] = true; } index = 43653; while (index <= 43654) : (index += 1) { instance.array[index] = true; } index = 43655; while (index <= 43656) : (index += 1) { instance.array[index] = true; } index = 43657; while (index <= 43661) : (index += 1) { instance.array[index] = true; } index = 43662; while (index <= 43663) : (index += 1) { instance.array[index] = true; } instance.array[43664] = true; instance.array[43665] = true; instance.array[43666] = true; index = 43691; while (index <= 43692) : (index += 1) { instance.array[index] = true; } instance.array[43693] = true; index = 43696; while (index <= 43706) : (index += 1) { instance.array[index] = true; } instance.array[43707] = true; index = 43708; while (index <= 43709) : (index += 1) { instance.array[index] = true; } index = 43710; while (index <= 43711) : (index += 1) { instance.array[index] = true; } instance.array[43714] = true; index = 43715; while (index <= 43716) : (index += 1) { instance.array[index] = true; } instance.array[43717] = true; instance.array[43718] = true; index = 43729; while (index <= 43734) : (index += 1) { instance.array[index] = true; } index = 43737; while (index <= 43742) : (index += 1) { instance.array[index] = true; } index = 43745; while (index <= 43750) : (index += 1) { instance.array[index] = true; } index = 43760; while (index <= 43766) : (index += 1) { instance.array[index] = true; } index = 43768; while (index <= 43774) : (index += 1) { instance.array[index] = true; } index = 43776; while (index <= 43818) : (index += 1) { instance.array[index] = true; } index = 43820; while (index <= 43823) : (index += 1) { instance.array[index] = true; } index = 43824; while (index <= 43832) : (index += 1) { instance.array[index] = true; } instance.array[43833] = true; index = 43840; while (index <= 43919) : (index += 1) { instance.array[index] = true; } index = 43920; while (index <= 43954) : (index += 1) { instance.array[index] = true; } index = 43955; while (index <= 43956) : (index += 1) { instance.array[index] = true; } instance.array[43957] = true; index = 43958; while (index <= 43959) : (index += 1) { instance.array[index] = true; } instance.array[43960] = true; index = 43961; while (index <= 43962) : (index += 1) { instance.array[index] = true; } instance.array[43964] = true; instance.array[43965] = true; index = 43968; while (index <= 43977) : (index += 1) { instance.array[index] = true; } index = 43984; while (index <= 55155) : (index += 1) { instance.array[index] = true; } index = 55168; while (index <= 55190) : (index += 1) { instance.array[index] = true; } index = 55195; while (index <= 55243) : (index += 1) { instance.array[index] = true; } index = 63696; while (index <= 64061) : (index += 1) { instance.array[index] = true; } index = 64064; while (index <= 64169) : (index += 1) { instance.array[index] = true; } index = 64208; while (index <= 64214) : (index += 1) { instance.array[index] = true; } index = 64227; while (index <= 64231) : (index += 1) { instance.array[index] = true; } instance.array[64237] = true; instance.array[64238] = true; index = 64239; while (index <= 64248) : (index += 1) { instance.array[index] = true; } index = 64250; while (index <= 64262) : (index += 1) { instance.array[index] = true; } index = 64264; while (index <= 64268) : (index += 1) { instance.array[index] = true; } instance.array[64270] = true; index = 64272; while (index <= 64273) : (index += 1) { instance.array[index] = true; } index = 64275; while (index <= 64276) : (index += 1) { instance.array[index] = true; } index = 64278; while (index <= 64385) : (index += 1) { instance.array[index] = true; } index = 64419; while (index <= 64781) : (index += 1) { instance.array[index] = true; } index = 64800; while (index <= 64863) : (index += 1) { instance.array[index] = true; } index = 64866; while (index <= 64919) : (index += 1) { instance.array[index] = true; } index = 64960; while (index <= 64971) : (index += 1) { instance.array[index] = true; } index = 64976; while (index <= 64991) : (index += 1) { instance.array[index] = true; } index = 65008; while (index <= 65023) : (index += 1) { instance.array[index] = true; } index = 65027; while (index <= 65028) : (index += 1) { instance.array[index] = true; } index = 65053; while (index <= 65055) : (index += 1) { instance.array[index] = true; } index = 65088; while (index <= 65092) : (index += 1) { instance.array[index] = true; } index = 65094; while (index <= 65228) : (index += 1) { instance.array[index] = true; } index = 65248; while (index <= 65257) : (index += 1) { instance.array[index] = true; } index = 65265; while (index <= 65290) : (index += 1) { instance.array[index] = true; } instance.array[65295] = true; index = 65297; while (index <= 65322) : (index += 1) { instance.array[index] = true; } index = 65334; while (index <= 65343) : (index += 1) { instance.array[index] = true; } instance.array[65344] = true; index = 65345; while (index <= 65389) : (index += 1) { instance.array[index] = true; } index = 65390; while (index <= 65391) : (index += 1) { instance.array[index] = true; } index = 65392; while (index <= 65422) : (index += 1) { instance.array[index] = true; } index = 65426; while (index <= 65431) : (index += 1) { instance.array[index] = true; } index = 65434; while (index <= 65439) : (index += 1) { instance.array[index] = true; } index = 65442; while (index <= 65447) : (index += 1) { instance.array[index] = true; } index = 65450; while (index <= 65452) : (index += 1) { instance.array[index] = true; } index = 65488; while (index <= 65499) : (index += 1) { instance.array[index] = true; } index = 65501; while (index <= 65526) : (index += 1) { instance.array[index] = true; } index = 65528; while (index <= 65546) : (index += 1) { instance.array[index] = true; } index = 65548; while (index <= 65549) : (index += 1) { instance.array[index] = true; } index = 65551; while (index <= 65565) : (index += 1) { instance.array[index] = true; } index = 65568; while (index <= 65581) : (index += 1) { instance.array[index] = true; } index = 65616; while (index <= 65738) : (index += 1) { instance.array[index] = true; } index = 65808; while (index <= 65860) : (index += 1) { instance.array[index] = true; } instance.array[65997] = true; index = 66128; while (index <= 66156) : (index += 1) { instance.array[index] = true; } index = 66160; while (index <= 66208) : (index += 1) { instance.array[index] = true; } instance.array[66224] = true; index = 66256; while (index <= 66287) : (index += 1) { instance.array[index] = true; } index = 66301; while (index <= 66320) : (index += 1) { instance.array[index] = true; } instance.array[66321] = true; index = 66322; while (index <= 66329) : (index += 1) { instance.array[index] = true; } instance.array[66330] = true; index = 66336; while (index <= 66373) : (index += 1) { instance.array[index] = true; } index = 66374; while (index <= 66378) : (index += 1) { instance.array[index] = true; } index = 66384; while (index <= 66413) : (index += 1) { instance.array[index] = true; } index = 66416; while (index <= 66451) : (index += 1) { instance.array[index] = true; } index = 66456; while (index <= 66463) : (index += 1) { instance.array[index] = true; } index = 66465; while (index <= 66469) : (index += 1) { instance.array[index] = true; } index = 66512; while (index <= 66591) : (index += 1) { instance.array[index] = true; } index = 66592; while (index <= 66669) : (index += 1) { instance.array[index] = true; } index = 66672; while (index <= 66681) : (index += 1) { instance.array[index] = true; } index = 66688; while (index <= 66723) : (index += 1) { instance.array[index] = true; } index = 66728; while (index <= 66763) : (index += 1) { instance.array[index] = true; } index = 66768; while (index <= 66807) : (index += 1) { instance.array[index] = true; } index = 66816; while (index <= 66867) : (index += 1) { instance.array[index] = true; } index = 67024; while (index <= 67334) : (index += 1) { instance.array[index] = true; } index = 67344; while (index <= 67365) : (index += 1) { instance.array[index] = true; } index = 67376; while (index <= 67383) : (index += 1) { instance.array[index] = true; } index = 67536; while (index <= 67541) : (index += 1) { instance.array[index] = true; } instance.array[67544] = true; index = 67546; while (index <= 67589) : (index += 1) { instance.array[index] = true; } index = 67591; while (index <= 67592) : (index += 1) { instance.array[index] = true; } instance.array[67596] = true; index = 67599; while (index <= 67621) : (index += 1) { instance.array[index] = true; } index = 67632; while (index <= 67654) : (index += 1) { instance.array[index] = true; } index = 67664; while (index <= 67694) : (index += 1) { instance.array[index] = true; } index = 67760; while (index <= 67778) : (index += 1) { instance.array[index] = true; } index = 67780; while (index <= 67781) : (index += 1) { instance.array[index] = true; } index = 67792; while (index <= 67813) : (index += 1) { instance.array[index] = true; } index = 67824; while (index <= 67849) : (index += 1) { instance.array[index] = true; } index = 67920; while (index <= 67975) : (index += 1) { instance.array[index] = true; } index = 67982; while (index <= 67983) : (index += 1) { instance.array[index] = true; } instance.array[68048] = true; index = 68049; while (index <= 68051) : (index += 1) { instance.array[index] = true; } index = 68053; while (index <= 68054) : (index += 1) { instance.array[index] = true; } index = 68060; while (index <= 68063) : (index += 1) { instance.array[index] = true; } index = 68064; while (index <= 68067) : (index += 1) { instance.array[index] = true; } index = 68069; while (index <= 68071) : (index += 1) { instance.array[index] = true; } index = 68073; while (index <= 68101) : (index += 1) { instance.array[index] = true; } index = 68104; while (index <= 68106) : (index += 1) { instance.array[index] = true; } instance.array[68111] = true; index = 68144; while (index <= 68172) : (index += 1) { instance.array[index] = true; } index = 68176; while (index <= 68204) : (index += 1) { instance.array[index] = true; } index = 68240; while (index <= 68247) : (index += 1) { instance.array[index] = true; } index = 68249; while (index <= 68276) : (index += 1) { instance.array[index] = true; } index = 68277; while (index <= 68278) : (index += 1) { instance.array[index] = true; } index = 68304; while (index <= 68357) : (index += 1) { instance.array[index] = true; } index = 68368; while (index <= 68389) : (index += 1) { instance.array[index] = true; } index = 68400; while (index <= 68418) : (index += 1) { instance.array[index] = true; } index = 68432; while (index <= 68449) : (index += 1) { instance.array[index] = true; } index = 68560; while (index <= 68632) : (index += 1) { instance.array[index] = true; } index = 68688; while (index <= 68738) : (index += 1) { instance.array[index] = true; } index = 68752; while (index <= 68802) : (index += 1) { instance.array[index] = true; } index = 68816; while (index <= 68851) : (index += 1) { instance.array[index] = true; } index = 68852; while (index <= 68855) : (index += 1) { instance.array[index] = true; } index = 68864; while (index <= 68873) : (index += 1) { instance.array[index] = true; } index = 69200; while (index <= 69241) : (index += 1) { instance.array[index] = true; } index = 69243; while (index <= 69244) : (index += 1) { instance.array[index] = true; } index = 69248; while (index <= 69249) : (index += 1) { instance.array[index] = true; } index = 69328; while (index <= 69356) : (index += 1) { instance.array[index] = true; } instance.array[69367] = true; index = 69376; while (index <= 69397) : (index += 1) { instance.array[index] = true; } index = 69398; while (index <= 69408) : (index += 1) { instance.array[index] = true; } index = 69504; while (index <= 69524) : (index += 1) { instance.array[index] = true; } index = 69552; while (index <= 69574) : (index += 1) { instance.array[index] = true; } instance.array[69584] = true; instance.array[69585] = true; instance.array[69586] = true; index = 69587; while (index <= 69639) : (index += 1) { instance.array[index] = true; } index = 69640; while (index <= 69654) : (index += 1) { instance.array[index] = true; } index = 69686; while (index <= 69695) : (index += 1) { instance.array[index] = true; } index = 69711; while (index <= 69713) : (index += 1) { instance.array[index] = true; } instance.array[69714] = true; index = 69715; while (index <= 69759) : (index += 1) { instance.array[index] = true; } index = 69760; while (index <= 69762) : (index += 1) { instance.array[index] = true; } index = 69763; while (index <= 69766) : (index += 1) { instance.array[index] = true; } index = 69767; while (index <= 69768) : (index += 1) { instance.array[index] = true; } index = 69769; while (index <= 69770) : (index += 1) { instance.array[index] = true; } index = 69792; while (index <= 69816) : (index += 1) { instance.array[index] = true; } index = 69824; while (index <= 69833) : (index += 1) { instance.array[index] = true; } index = 69840; while (index <= 69842) : (index += 1) { instance.array[index] = true; } index = 69843; while (index <= 69878) : (index += 1) { instance.array[index] = true; } index = 69879; while (index <= 69883) : (index += 1) { instance.array[index] = true; } instance.array[69884] = true; index = 69885; while (index <= 69892) : (index += 1) { instance.array[index] = true; } index = 69894; while (index <= 69903) : (index += 1) { instance.array[index] = true; } instance.array[69908] = true; index = 69909; while (index <= 69910) : (index += 1) { instance.array[index] = true; } instance.array[69911] = true; index = 69920; while (index <= 69954) : (index += 1) { instance.array[index] = true; } instance.array[69955] = true; instance.array[69958] = true; index = 69968; while (index <= 69969) : (index += 1) { instance.array[index] = true; } instance.array[69970] = true; index = 69971; while (index <= 70018) : (index += 1) { instance.array[index] = true; } index = 70019; while (index <= 70021) : (index += 1) { instance.array[index] = true; } index = 70022; while (index <= 70030) : (index += 1) { instance.array[index] = true; } index = 70031; while (index <= 70032) : (index += 1) { instance.array[index] = true; } index = 70033; while (index <= 70036) : (index += 1) { instance.array[index] = true; } index = 70041; while (index <= 70044) : (index += 1) { instance.array[index] = true; } instance.array[70046] = true; instance.array[70047] = true; index = 70048; while (index <= 70057) : (index += 1) { instance.array[index] = true; } instance.array[70058] = true; instance.array[70060] = true; index = 70096; while (index <= 70113) : (index += 1) { instance.array[index] = true; } index = 70115; while (index <= 70139) : (index += 1) { instance.array[index] = true; } index = 70140; while (index <= 70142) : (index += 1) { instance.array[index] = true; } index = 70143; while (index <= 70145) : (index += 1) { instance.array[index] = true; } index = 70146; while (index <= 70147) : (index += 1) { instance.array[index] = true; } instance.array[70148] = true; instance.array[70149] = true; index = 70150; while (index <= 70151) : (index += 1) { instance.array[index] = true; } instance.array[70158] = true; index = 70224; while (index <= 70230) : (index += 1) { instance.array[index] = true; } instance.array[70232] = true; index = 70234; while (index <= 70237) : (index += 1) { instance.array[index] = true; } index = 70239; while (index <= 70253) : (index += 1) { instance.array[index] = true; } index = 70255; while (index <= 70264) : (index += 1) { instance.array[index] = true; } index = 70272; while (index <= 70318) : (index += 1) { instance.array[index] = true; } instance.array[70319] = true; index = 70320; while (index <= 70322) : (index += 1) { instance.array[index] = true; } index = 70323; while (index <= 70330) : (index += 1) { instance.array[index] = true; } index = 70336; while (index <= 70345) : (index += 1) { instance.array[index] = true; } index = 70352; while (index <= 70353) : (index += 1) { instance.array[index] = true; } index = 70354; while (index <= 70355) : (index += 1) { instance.array[index] = true; } index = 70357; while (index <= 70364) : (index += 1) { instance.array[index] = true; } index = 70367; while (index <= 70368) : (index += 1) { instance.array[index] = true; } index = 70371; while (index <= 70392) : (index += 1) { instance.array[index] = true; } index = 70394; while (index <= 70400) : (index += 1) { instance.array[index] = true; } index = 70402; while (index <= 70403) : (index += 1) { instance.array[index] = true; } index = 70405; while (index <= 70409) : (index += 1) { instance.array[index] = true; } index = 70411; while (index <= 70412) : (index += 1) { instance.array[index] = true; } instance.array[70413] = true; index = 70414; while (index <= 70415) : (index += 1) { instance.array[index] = true; } instance.array[70416] = true; index = 70417; while (index <= 70420) : (index += 1) { instance.array[index] = true; } index = 70423; while (index <= 70424) : (index += 1) { instance.array[index] = true; } index = 70427; while (index <= 70429) : (index += 1) { instance.array[index] = true; } instance.array[70432] = true; instance.array[70439] = true; index = 70445; while (index <= 70449) : (index += 1) { instance.array[index] = true; } index = 70450; while (index <= 70451) : (index += 1) { instance.array[index] = true; } index = 70454; while (index <= 70460) : (index += 1) { instance.array[index] = true; } index = 70464; while (index <= 70468) : (index += 1) { instance.array[index] = true; } index = 70608; while (index <= 70660) : (index += 1) { instance.array[index] = true; } index = 70661; while (index <= 70663) : (index += 1) { instance.array[index] = true; } index = 70664; while (index <= 70671) : (index += 1) { instance.array[index] = true; } index = 70672; while (index <= 70673) : (index += 1) { instance.array[index] = true; } index = 70674; while (index <= 70676) : (index += 1) { instance.array[index] = true; } instance.array[70677] = true; instance.array[70678] = true; index = 70679; while (index <= 70682) : (index += 1) { instance.array[index] = true; } index = 70688; while (index <= 70697) : (index += 1) { instance.array[index] = true; } instance.array[70702] = true; index = 70703; while (index <= 70705) : (index += 1) { instance.array[index] = true; } index = 70736; while (index <= 70783) : (index += 1) { instance.array[index] = true; } index = 70784; while (index <= 70786) : (index += 1) { instance.array[index] = true; } index = 70787; while (index <= 70792) : (index += 1) { instance.array[index] = true; } instance.array[70793] = true; instance.array[70794] = true; index = 70795; while (index <= 70798) : (index += 1) { instance.array[index] = true; } index = 70799; while (index <= 70800) : (index += 1) { instance.array[index] = true; } instance.array[70801] = true; index = 70802; while (index <= 70803) : (index += 1) { instance.array[index] = true; } index = 70804; while (index <= 70805) : (index += 1) { instance.array[index] = true; } instance.array[70807] = true; index = 70816; while (index <= 70825) : (index += 1) { instance.array[index] = true; } index = 70992; while (index <= 71038) : (index += 1) { instance.array[index] = true; } index = 71039; while (index <= 71041) : (index += 1) { instance.array[index] = true; } index = 71042; while (index <= 71045) : (index += 1) { instance.array[index] = true; } index = 71048; while (index <= 71051) : (index += 1) { instance.array[index] = true; } index = 71052; while (index <= 71053) : (index += 1) { instance.array[index] = true; } instance.array[71054] = true; index = 71055; while (index <= 71056) : (index += 1) { instance.array[index] = true; } index = 71080; while (index <= 71083) : (index += 1) { instance.array[index] = true; } index = 71084; while (index <= 71085) : (index += 1) { instance.array[index] = true; } index = 71120; while (index <= 71167) : (index += 1) { instance.array[index] = true; } index = 71168; while (index <= 71170) : (index += 1) { instance.array[index] = true; } index = 71171; while (index <= 71178) : (index += 1) { instance.array[index] = true; } index = 71179; while (index <= 71180) : (index += 1) { instance.array[index] = true; } instance.array[71181] = true; instance.array[71182] = true; index = 71183; while (index <= 71184) : (index += 1) { instance.array[index] = true; } instance.array[71188] = true; index = 71200; while (index <= 71209) : (index += 1) { instance.array[index] = true; } index = 71248; while (index <= 71290) : (index += 1) { instance.array[index] = true; } instance.array[71291] = true; instance.array[71292] = true; instance.array[71293] = true; index = 71294; while (index <= 71295) : (index += 1) { instance.array[index] = true; } index = 71296; while (index <= 71301) : (index += 1) { instance.array[index] = true; } instance.array[71302] = true; instance.array[71303] = true; instance.array[71304] = true; index = 71312; while (index <= 71321) : (index += 1) { instance.array[index] = true; } index = 71376; while (index <= 71402) : (index += 1) { instance.array[index] = true; } index = 71405; while (index <= 71407) : (index += 1) { instance.array[index] = true; } index = 71408; while (index <= 71409) : (index += 1) { instance.array[index] = true; } index = 71410; while (index <= 71413) : (index += 1) { instance.array[index] = true; } instance.array[71414] = true; index = 71415; while (index <= 71419) : (index += 1) { instance.array[index] = true; } index = 71424; while (index <= 71433) : (index += 1) { instance.array[index] = true; } index = 71632; while (index <= 71675) : (index += 1) { instance.array[index] = true; } index = 71676; while (index <= 71678) : (index += 1) { instance.array[index] = true; } index = 71679; while (index <= 71687) : (index += 1) { instance.array[index] = true; } instance.array[71688] = true; index = 71689; while (index <= 71690) : (index += 1) { instance.array[index] = true; } index = 71792; while (index <= 71855) : (index += 1) { instance.array[index] = true; } index = 71856; while (index <= 71865) : (index += 1) { instance.array[index] = true; } index = 71887; while (index <= 71894) : (index += 1) { instance.array[index] = true; } instance.array[71897] = true; index = 71900; while (index <= 71907) : (index += 1) { instance.array[index] = true; } index = 71909; while (index <= 71910) : (index += 1) { instance.array[index] = true; } index = 71912; while (index <= 71935) : (index += 1) { instance.array[index] = true; } index = 71936; while (index <= 71941) : (index += 1) { instance.array[index] = true; } index = 71943; while (index <= 71944) : (index += 1) { instance.array[index] = true; } index = 71947; while (index <= 71948) : (index += 1) { instance.array[index] = true; } instance.array[71949] = true; instance.array[71950] = true; instance.array[71951] = true; instance.array[71952] = true; instance.array[71953] = true; instance.array[71954] = true; instance.array[71955] = true; index = 71968; while (index <= 71977) : (index += 1) { instance.array[index] = true; } index = 72048; while (index <= 72055) : (index += 1) { instance.array[index] = true; } index = 72058; while (index <= 72096) : (index += 1) { instance.array[index] = true; } index = 72097; while (index <= 72099) : (index += 1) { instance.array[index] = true; } index = 72100; while (index <= 72103) : (index += 1) { instance.array[index] = true; } index = 72106; while (index <= 72107) : (index += 1) { instance.array[index] = true; } index = 72108; while (index <= 72111) : (index += 1) { instance.array[index] = true; } instance.array[72112] = true; instance.array[72113] = true; instance.array[72115] = true; instance.array[72116] = true; instance.array[72144] = true; index = 72145; while (index <= 72154) : (index += 1) { instance.array[index] = true; } index = 72155; while (index <= 72194) : (index += 1) { instance.array[index] = true; } index = 72195; while (index <= 72200) : (index += 1) { instance.array[index] = true; } instance.array[72201] = true; instance.array[72202] = true; index = 72203; while (index <= 72206) : (index += 1) { instance.array[index] = true; } instance.array[72215] = true; instance.array[72224] = true; index = 72225; while (index <= 72230) : (index += 1) { instance.array[index] = true; } index = 72231; while (index <= 72232) : (index += 1) { instance.array[index] = true; } index = 72233; while (index <= 72235) : (index += 1) { instance.array[index] = true; } index = 72236; while (index <= 72281) : (index += 1) { instance.array[index] = true; } index = 72282; while (index <= 72294) : (index += 1) { instance.array[index] = true; } instance.array[72295] = true; index = 72296; while (index <= 72297) : (index += 1) { instance.array[index] = true; } instance.array[72301] = true; index = 72336; while (index <= 72392) : (index += 1) { instance.array[index] = true; } index = 72656; while (index <= 72664) : (index += 1) { instance.array[index] = true; } index = 72666; while (index <= 72702) : (index += 1) { instance.array[index] = true; } instance.array[72703] = true; index = 72704; while (index <= 72710) : (index += 1) { instance.array[index] = true; } index = 72712; while (index <= 72717) : (index += 1) { instance.array[index] = true; } instance.array[72718] = true; instance.array[72719] = true; instance.array[72720] = true; index = 72736; while (index <= 72745) : (index += 1) { instance.array[index] = true; } index = 72770; while (index <= 72799) : (index += 1) { instance.array[index] = true; } index = 72802; while (index <= 72823) : (index += 1) { instance.array[index] = true; } instance.array[72825] = true; index = 72826; while (index <= 72832) : (index += 1) { instance.array[index] = true; } instance.array[72833] = true; index = 72834; while (index <= 72835) : (index += 1) { instance.array[index] = true; } instance.array[72836] = true; index = 72837; while (index <= 72838) : (index += 1) { instance.array[index] = true; } index = 72912; while (index <= 72918) : (index += 1) { instance.array[index] = true; } index = 72920; while (index <= 72921) : (index += 1) { instance.array[index] = true; } index = 72923; while (index <= 72960) : (index += 1) { instance.array[index] = true; } index = 72961; while (index <= 72966) : (index += 1) { instance.array[index] = true; } instance.array[72970] = true; index = 72972; while (index <= 72973) : (index += 1) { instance.array[index] = true; } index = 72975; while (index <= 72981) : (index += 1) { instance.array[index] = true; } instance.array[72982] = true; instance.array[72983] = true; index = 72992; while (index <= 73001) : (index += 1) { instance.array[index] = true; } index = 73008; while (index <= 73013) : (index += 1) { instance.array[index] = true; } index = 73015; while (index <= 73016) : (index += 1) { instance.array[index] = true; } index = 73018; while (index <= 73049) : (index += 1) { instance.array[index] = true; } index = 73050; while (index <= 73054) : (index += 1) { instance.array[index] = true; } index = 73056; while (index <= 73057) : (index += 1) { instance.array[index] = true; } index = 73059; while (index <= 73060) : (index += 1) { instance.array[index] = true; } instance.array[73061] = true; instance.array[73062] = true; instance.array[73063] = true; instance.array[73064] = true; index = 73072; while (index <= 73081) : (index += 1) { instance.array[index] = true; } index = 73392; while (index <= 73410) : (index += 1) { instance.array[index] = true; } index = 73411; while (index <= 73412) : (index += 1) { instance.array[index] = true; } index = 73413; while (index <= 73414) : (index += 1) { instance.array[index] = true; } instance.array[73600] = true; index = 73680; while (index <= 74601) : (index += 1) { instance.array[index] = true; } index = 74704; while (index <= 74814) : (index += 1) { instance.array[index] = true; } index = 74832; while (index <= 75027) : (index += 1) { instance.array[index] = true; } index = 77776; while (index <= 78846) : (index += 1) { instance.array[index] = true; } index = 82896; while (index <= 83478) : (index += 1) { instance.array[index] = true; } index = 92112; while (index <= 92680) : (index += 1) { instance.array[index] = true; } index = 92688; while (index <= 92718) : (index += 1) { instance.array[index] = true; } index = 92720; while (index <= 92729) : (index += 1) { instance.array[index] = true; } index = 92832; while (index <= 92861) : (index += 1) { instance.array[index] = true; } index = 92864; while (index <= 92868) : (index += 1) { instance.array[index] = true; } index = 92880; while (index <= 92927) : (index += 1) { instance.array[index] = true; } index = 92928; while (index <= 92934) : (index += 1) { instance.array[index] = true; } index = 92944; while (index <= 92947) : (index += 1) { instance.array[index] = true; } index = 92960; while (index <= 92969) : (index += 1) { instance.array[index] = true; } index = 92979; while (index <= 92999) : (index += 1) { instance.array[index] = true; } index = 93005; while (index <= 93023) : (index += 1) { instance.array[index] = true; } index = 93712; while (index <= 93775) : (index += 1) { instance.array[index] = true; } index = 93904; while (index <= 93978) : (index += 1) { instance.array[index] = true; } instance.array[93983] = true; instance.array[93984] = true; index = 93985; while (index <= 94039) : (index += 1) { instance.array[index] = true; } index = 94047; while (index <= 94050) : (index += 1) { instance.array[index] = true; } index = 94051; while (index <= 94063) : (index += 1) { instance.array[index] = true; } index = 94128; while (index <= 94129) : (index += 1) { instance.array[index] = true; } instance.array[94131] = true; instance.array[94132] = true; index = 94144; while (index <= 94145) : (index += 1) { instance.array[index] = true; } index = 94160; while (index <= 100295) : (index += 1) { instance.array[index] = true; } index = 100304; while (index <= 101541) : (index += 1) { instance.array[index] = true; } index = 101584; while (index <= 101592) : (index += 1) { instance.array[index] = true; } index = 110544; while (index <= 110830) : (index += 1) { instance.array[index] = true; } index = 110880; while (index <= 110882) : (index += 1) { instance.array[index] = true; } index = 110900; while (index <= 110903) : (index += 1) { instance.array[index] = true; } index = 110912; while (index <= 111307) : (index += 1) { instance.array[index] = true; } index = 113616; while (index <= 113722) : (index += 1) { instance.array[index] = true; } index = 113728; while (index <= 113740) : (index += 1) { instance.array[index] = true; } index = 113744; while (index <= 113752) : (index += 1) { instance.array[index] = true; } index = 113760; while (index <= 113769) : (index += 1) { instance.array[index] = true; } index = 113773; while (index <= 113774) : (index += 1) { instance.array[index] = true; } index = 119093; while (index <= 119094) : (index += 1) { instance.array[index] = true; } index = 119095; while (index <= 119097) : (index += 1) { instance.array[index] = true; } index = 119101; while (index <= 119106) : (index += 1) { instance.array[index] = true; } index = 119115; while (index <= 119122) : (index += 1) { instance.array[index] = true; } index = 119125; while (index <= 119131) : (index += 1) { instance.array[index] = true; } index = 119162; while (index <= 119165) : (index += 1) { instance.array[index] = true; } index = 119314; while (index <= 119316) : (index += 1) { instance.array[index] = true; } index = 119760; while (index <= 119844) : (index += 1) { instance.array[index] = true; } index = 119846; while (index <= 119916) : (index += 1) { instance.array[index] = true; } index = 119918; while (index <= 119919) : (index += 1) { instance.array[index] = true; } instance.array[119922] = true; index = 119925; while (index <= 119926) : (index += 1) { instance.array[index] = true; } index = 119929; while (index <= 119932) : (index += 1) { instance.array[index] = true; } index = 119934; while (index <= 119945) : (index += 1) { instance.array[index] = true; } instance.array[119947] = true; index = 119949; while (index <= 119955) : (index += 1) { instance.array[index] = true; } index = 119957; while (index <= 120021) : (index += 1) { instance.array[index] = true; } index = 120023; while (index <= 120026) : (index += 1) { instance.array[index] = true; } index = 120029; while (index <= 120036) : (index += 1) { instance.array[index] = true; } index = 120038; while (index <= 120044) : (index += 1) { instance.array[index] = true; } index = 120046; while (index <= 120073) : (index += 1) { instance.array[index] = true; } index = 120075; while (index <= 120078) : (index += 1) { instance.array[index] = true; } index = 120080; while (index <= 120084) : (index += 1) { instance.array[index] = true; } instance.array[120086] = true; index = 120090; while (index <= 120096) : (index += 1) { instance.array[index] = true; } index = 120098; while (index <= 120437) : (index += 1) { instance.array[index] = true; } index = 120440; while (index <= 120464) : (index += 1) { instance.array[index] = true; } index = 120466; while (index <= 120490) : (index += 1) { instance.array[index] = true; } index = 120492; while (index <= 120522) : (index += 1) { instance.array[index] = true; } index = 120524; while (index <= 120548) : (index += 1) { instance.array[index] = true; } index = 120550; while (index <= 120580) : (index += 1) { instance.array[index] = true; } index = 120582; while (index <= 120606) : (index += 1) { instance.array[index] = true; } index = 120608; while (index <= 120638) : (index += 1) { instance.array[index] = true; } index = 120640; while (index <= 120664) : (index += 1) { instance.array[index] = true; } index = 120666; while (index <= 120696) : (index += 1) { instance.array[index] = true; } index = 120698; while (index <= 120722) : (index += 1) { instance.array[index] = true; } index = 120724; while (index <= 120731) : (index += 1) { instance.array[index] = true; } index = 120734; while (index <= 120783) : (index += 1) { instance.array[index] = true; } index = 121296; while (index <= 121350) : (index += 1) { instance.array[index] = true; } index = 121355; while (index <= 121404) : (index += 1) { instance.array[index] = true; } instance.array[121413] = true; instance.array[121428] = true; index = 121451; while (index <= 121455) : (index += 1) { instance.array[index] = true; } index = 121457; while (index <= 121471) : (index += 1) { instance.array[index] = true; } index = 122832; while (index <= 122838) : (index += 1) { instance.array[index] = true; } index = 122840; while (index <= 122856) : (index += 1) { instance.array[index] = true; } index = 122859; while (index <= 122865) : (index += 1) { instance.array[index] = true; } index = 122867; while (index <= 122868) : (index += 1) { instance.array[index] = true; } index = 122870; while (index <= 122874) : (index += 1) { instance.array[index] = true; } index = 123088; while (index <= 123132) : (index += 1) { instance.array[index] = true; } index = 123136; while (index <= 123142) : (index += 1) { instance.array[index] = true; } index = 123143; while (index <= 123149) : (index += 1) { instance.array[index] = true; } index = 123152; while (index <= 123161) : (index += 1) { instance.array[index] = true; } instance.array[123166] = true; index = 123536; while (index <= 123579) : (index += 1) { instance.array[index] = true; } index = 123580; while (index <= 123583) : (index += 1) { instance.array[index] = true; } index = 123584; while (index <= 123593) : (index += 1) { instance.array[index] = true; } index = 124880; while (index <= 125076) : (index += 1) { instance.array[index] = true; } index = 125088; while (index <= 125094) : (index += 1) { instance.array[index] = true; } index = 125136; while (index <= 125203) : (index += 1) { instance.array[index] = true; } index = 125204; while (index <= 125210) : (index += 1) { instance.array[index] = true; } instance.array[125211] = true; index = 125216; while (index <= 125225) : (index += 1) { instance.array[index] = true; } index = 126416; while (index <= 126419) : (index += 1) { instance.array[index] = true; } index = 126421; while (index <= 126447) : (index += 1) { instance.array[index] = true; } index = 126449; while (index <= 126450) : (index += 1) { instance.array[index] = true; } instance.array[126452] = true; instance.array[126455] = true; index = 126457; while (index <= 126466) : (index += 1) { instance.array[index] = true; } index = 126468; while (index <= 126471) : (index += 1) { instance.array[index] = true; } instance.array[126473] = true; instance.array[126475] = true; instance.array[126482] = true; instance.array[126487] = true; instance.array[126489] = true; instance.array[126491] = true; index = 126493; while (index <= 126495) : (index += 1) { instance.array[index] = true; } index = 126497; while (index <= 126498) : (index += 1) { instance.array[index] = true; } instance.array[126500] = true; instance.array[126503] = true; instance.array[126505] = true; instance.array[126507] = true; instance.array[126509] = true; instance.array[126511] = true; index = 126513; while (index <= 126514) : (index += 1) { instance.array[index] = true; } instance.array[126516] = true; index = 126519; while (index <= 126522) : (index += 1) { instance.array[index] = true; } index = 126524; while (index <= 126530) : (index += 1) { instance.array[index] = true; } index = 126532; while (index <= 126535) : (index += 1) { instance.array[index] = true; } index = 126537; while (index <= 126540) : (index += 1) { instance.array[index] = true; } instance.array[126542] = true; index = 126544; while (index <= 126553) : (index += 1) { instance.array[index] = true; } index = 126555; while (index <= 126571) : (index += 1) { instance.array[index] = true; } index = 126577; while (index <= 126579) : (index += 1) { instance.array[index] = true; } index = 126581; while (index <= 126585) : (index += 1) { instance.array[index] = true; } index = 126587; while (index <= 126603) : (index += 1) { instance.array[index] = true; } index = 129984; while (index <= 129993) : (index += 1) { instance.array[index] = true; } index = 131024; while (index <= 173741) : (index += 1) { instance.array[index] = true; } index = 173776; while (index <= 177924) : (index += 1) { instance.array[index] = true; } index = 177936; while (index <= 178157) : (index += 1) { instance.array[index] = true; } index = 178160; while (index <= 183921) : (index += 1) { instance.array[index] = true; } index = 183936; while (index <= 191408) : (index += 1) { instance.array[index] = true; } index = 194512; while (index <= 195053) : (index += 1) { instance.array[index] = true; } index = 196560; while (index <= 201498) : (index += 1) { instance.array[index] = true; } index = 917712; while (index <= 917951) : (index += 1) { instance.array[index] = true; } // Placeholder: 0. Struct name, 1. Code point kind return instance; } pub fn deinit(self: *IDContinue) void { self.allocator.free(self.array); } // isIDContinue checks if cp is of the kind ID_Continue. pub fn isIDContinue(self: IDContinue, cp: u21) bool { if (cp < self.lo or cp > self.hi) return false; const index = cp - self.lo; return if (index >= self.array.len) false else self.array[index]; }
src/components/autogen/DerivedCoreProperties/IDContinue.zig
const std = @import("std"); const zalgebra = @import("zalgebra"); const Vec3 = zalgebra.Vec3; const Quat = zalgebra.Quat; const Allocator = std.mem.Allocator; const graphics = @import("didot-graphics"); const objects = @import("didot-objects"); const models = @import("didot-models"); const image = @import("didot-image"); // const physics = @import("didot-physics"); const bmp = image.bmp; const obj = models.obj; const application = @import("didot-app"); const GameObject = objects.GameObject; const Scene = objects.Scene; const Camera = objects.Camera; const PointLight = objects.PointLight; const Input = graphics.Input; const Transform = objects.Transform; // var world: physics.World = undefined; var simPaused: bool = false; var cube2: GameObject = undefined; const App = blk: { comptime var systems = application.Systems {}; systems.addSystem(cameraSystem); break :blk application.Application(systems); }; //const Component = objects.Component; const CameraController = struct { input: *Input, player: *GameObject }; fn cameraSystem(controller: *CameraController, transform: *Transform) !void { const input = controller.input; transform.position = controller.player.getComponent(Transform).?.position; if (input.isMouseButtonDown(.Left)) { input.setMouseInputMode(.Grabbed); } else if (input.isMouseButtonDown(.Right) or input.isKeyDown(Input.KEY_ESCAPE)) { input.setMouseInputMode(.Normal); } if (input.getMouseInputMode() == .Grabbed) { const delta = 1.0; // TODO: put delta in Application struct var euler = transform.rotation.extractRotation(); euler.x += (input.mouseDelta.x / 3.0) * delta; euler.y -= (input.mouseDelta.y / 3.0) * delta; if (euler.y > 89) euler.y = 89; if (euler.y < -89) euler.y = -89; transform.rotation = Quat.fromEulerAngle(euler); } } //const CameraControllerData = struct { input: *graphics.Input }; //const CameraController = objects.ComponentType(.CameraController, CameraControllerData, .{ .updateFn = cameraInput }) {}; // fn cameraInput(allocator: Allocator, component: *Component, delta: f32) !void { // _ = allocator; // const data = component.getData(CameraControllerData); // const input = data.input; // const gameObject = component.gameObject; // const speed: f32 = 0.1 * delta; // const forward = gameObject.getForward(); // const left = gameObject.getLeft(); // if (input.isKeyDown(graphics.Input.KEY_W)) { // gameObject.position = gameObject.position.add(forward.scale(speed)); // } // if (input.isKeyDown(graphics.Input.KEY_S)) { // gameObject.position = gameObject.position.add(forward.scale(-speed)); // } // if (input.isKeyDown(graphics.Input.KEY_A)) { // gameObject.position = gameObject.position.add(left.scale(speed)); // } // if (input.isKeyDown(graphics.Input.KEY_D)) { // gameObject.position = gameObject.position.add(left.scale(-speed)); // } // if (input.isKeyDown(graphics.Input.KEY_UP)) { // // if (cube2.findComponent(.Rigidbody)) |rb| { // // rb.getData(physics.RigidbodyData).addForce(zlm.Vec3.new(0, 20, 0)); // // } // } // if (input.isKeyDown(graphics.Input.KEY_LEFT)) { // // if (cube2.findComponent(.Rigidbody)) |rb| { // // rb.getData(physics.RigidbodyData).addForce(zlm.Vec3.new(5, 0, 0)); // // } // } // if (input.isKeyDown(graphics.Input.KEY_RIGHT)) { // // if (cube2.findComponent(.Rigidbody)) |rb| { // // rb.getData(physics.RigidbodyData).addForce(zlm.Vec3.new(0, 0, 5)); // // } // } // if (input.isMouseButtonDown(.Left)) { // input.setMouseInputMode(.Grabbed); // simPaused = false; // } else if (input.isMouseButtonDown(.Right)) { // input.setMouseInputMode(.Normal); // } else if (input.isKeyDown(graphics.Input.KEY_ESCAPE)) { // input.setMouseInputMode(.Normal); // } // if (input.getMouseInputMode() == .Grabbed) { // gameObject.rotation.x -= (input.mouseDelta.x / 300.0) * delta; // gameObject.rotation.y -= (input.mouseDelta.y / 300.0) * delta; // } // if (input.getJoystick(0)) |joystick| { // const axes = joystick.getRawAxes(); // var r = axes[0]; // right // var fw = axes[1]; // forward // const thrust = (axes[3] - 1.0) * -0.5; // const threshold = 0.2; // if (r < threshold and r > 0) r = 0; if (r > -threshold and r < 0) r = 0; // if (fw < threshold and fw > 0) fw = 0; if (fw > -threshold and fw < 0) fw = 0; // gameObject.position = gameObject.position.add(forward.scale(thrust * speed)); // gameObject.rotation.x -= (r / 50.0) * delta; // gameObject.rotation.y -= (fw / 50.0) * delta; // // std.debug.warn("A: {}, B: {}, X: {}, Y: {}\n", .{ // // joystick.isButtonDown(.A), // // joystick.isButtonDown(.B), // // joystick.isButtonDown(.X), // // joystick.isButtonDown(.Y), // // }); // } //} // const TestLight = objects.ComponentType(.TestLight, struct {}, .{ .updateFn = testLight }) {}; // fn testLight(allocator: Allocator, component: *Component, delta: f32) !void { // _ = delta; // _ = allocator; // const time = @intToFloat(f64, std.time.milliTimestamp()); // const rad = @floatCast(f32, @mod((time / 1000.0), std.math.pi * 2.0)); // component.gameObject.position = Vec3.new(std.math.sin(rad) * 20 + 10, 3, std.math.cos(rad) * 10 - 10); // } fn loadSkybox(allocator: Allocator, camera: *Camera, scene: *Scene) !void { const asset = &scene.assetManager; try asset.put("textures/skybox", try graphics.TextureAsset.initCubemap(allocator, .{ .front = asset.get("textures/skybox/front.png").?, .back = asset.get("textures/skybox/back.png").?, .left = asset.get("textures/skybox/left.png").?, .right = asset.get("textures/skybox/right.png").?, .top = asset.get("textures/skybox/top.png").?, .bottom = asset.get("textures/skybox/bottom.png").?, })); var skyboxShader = try graphics.ShaderProgram.createFromFile(allocator, "assets/shaders/skybox-vert.glsl", "assets/shaders/skybox-frag.glsl"); camera.skybox = objects.Skybox { .mesh = asset.get("Mesh/Cube").?, .cubemap = asset.get("textures/skybox").?, .shader = skyboxShader }; } fn initFromFile(allocator: Allocator, app: *App) !void { _ = allocator; // input = &app.window.input; var scene = Scene.loadFromFile(allocator, "res/example-scene.json"); // scene.findChild("Camera").?.updateFn = cameraInput; // scene.findChild("Light").?.updateFn = testLight; app.scene = scene; //var skybox = try loadSkybox(allocator, camera); //try scene.add(skybox); // var i: f32 = 0; // while (i < 5) { // var j: f32 = 0; // while (j < 5) { // var kart2 = GameObject.createObject(allocator, "Mesh/Kart"); // kart2.position = Vec3.new(0.7 + (j*8), 0.75, -8 - (i*3)); // try scene.add(kart2); // j += 1; // } // i += 1; // } } fn update(allocator: Allocator, app: *App, delta: f32) !void { _ = allocator; _ = app; _ = delta; // if (!simPaused) // world.update(); } fn init(allocator: Allocator, app: *App) !void { // world = physics.World.create(); // world.setGravity(zlm.Vec3.new(0, -9.8, 0)); var shader = try graphics.ShaderProgram.createFromFile(allocator, "assets/shaders/vert.glsl", "assets/shaders/frag.glsl"); const scene = app.scene; const asset = &scene.assetManager; try asset.autoLoad(allocator); var player = try GameObject.createObject(allocator, null); player.getComponent(Transform).?.* = .{ .position = Vec3.new(1.5, 3.5, -0.5), .scale = Vec3.new(2, 2, 2) }; player.name = "Player"; // try player.addComponent(PlayerController { .input = &app.window.input }); // try player.addComponent(physics.Rigidbody { // .world = &world, // .collider = .{ // .Sphere = .{ .radius = 1.0 } // } // }); try scene.add(player); var camera = try GameObject.createObject(allocator, null); try camera.addComponent(Camera { .shader = shader }); camera.getComponent(Transform).?.* = .{ .position = Vec3.new(1.5, 3.5, -0.5), .rotation = Quat.fromEulerAngle(Vec3.new(-120, -15, 0)) }; camera.name = "Camera"; try camera.addComponent(CameraController { .input = &app.window.input, .player = scene.findChild("Player").? }); try scene.add(camera); //const controller = try CameraController.newWithData(allocator, .{ .input = &app.window.input }); //try camera.gameObject.addComponent(controller); //try scene.add(camera.gameObject); try loadSkybox(allocator, camera.getComponent(Camera).?, scene); // try scene.assetManager.put("Texture/Grass", try graphics.TextureAsset.init(allocator, .{ // .path = "assets/textures/grass.png", .format = "png", // .tiling = zlm.Vec2.new(2, 2) // })); var grassMaterial = graphics.Material{ .texture = asset.get("textures/grass.png") }; var cube = try GameObject.createObject(allocator, asset.get("Mesh/Cube")); cube.getComponent(Transform).?.* = .{ .position = Vec3.new(5, -0.75, -10), .scale = Vec3.new(50, 1, 50) }; cube.material = grassMaterial; // try cube.addComponent(try physics.Rigidbody.newWithData(allocator, .{ .world=&world, .kinematic=.Kinematic, .collider = .{ // .Box = .{ .size = Vec3.new(50, 1, 50) } // } })); try scene.add(cube); cube2 = try GameObject.createObject(allocator, asset.get("Mesh/Cube")); cube2.getComponent(Transform).?.* = .{ .position = Vec3.new(-1.2, 5.75, -3) }; cube2.material.ambient = Vec3.new(0.2, 0.1, 0.1); cube2.material.diffuse = Vec3.new(0.8, 0.8, 0.8); // try cube2.addComponent(try physics.Rigidbody.newWithData(allocator, .{ .world = &world })); try scene.add(cube2); var kart = try GameObject.createObject(allocator, asset.get("kart.obj")); kart.getComponent(Transform).?.* = .{ .position = Vec3.new(0.7, 0.75, -5) }; kart.name = "Kart"; // try kart.addComponent(try physics.Rigidbody.newWithData(allocator, .{ .world = &world })); try scene.add(kart); var i: f32 = 0; while (i < 7) { // rows front to back var j: f32 = 0; while (j < 5) { // cols left to right var kart2 = try GameObject.createObject(allocator, asset.get("kart.obj")); kart2.getComponent(Transform).?.* = .{ .position = Vec3.new(0.7 + (j * 8), 0.75, -8 - (i * 3)) }; // lets decorate the kart based on its location kart2.material.ambient = Vec3.new(0.0, j * 0.001, 0.002); kart2.material.diffuse = Vec3.new(i * 0.1, j * 0.1, 0.6); // dull on the left, getting shinier to the right kart2.material.specular = Vec3.new(1.0 - (j * 0.2), 1.0 - (j * 0.2), 0.2); kart2.material.shininess = 110.0 - (j * 20.0); //try kart2.addComponent(try physics.Rigidbody.newWithData(allocator,.{.world=&world})); try scene.add(kart2); j += 1; } i += 1; } var light = try GameObject.createObject(allocator, asset.get("Mesh/Cube")); light.getComponent(Transform).?.* = .{ .position = Vec3.new(1, 5, -5) }; light.material.ambient = Vec3.new(1.0, 1.0, 1.0); //try light.addComponent(try TestLight.new(allocator)); //try light.addComponent(try PointLight.newWithData(allocator, .{})); try light.addComponent(PointLight{}); try scene.add(light); } var gp: std.heap.GeneralPurposeAllocator(.{}) = .{}; pub fn main() !void { defer _ = gp.deinit(); const allocator = gp.allocator(); var scene = try Scene.create(allocator, null); var app = App { .title = "Test Cubes", .initFn = init }; try app.run(allocator, scene); }
examples/kart-and-cubes/example-scene.zig
const std = @import("std"); const Chunk = @import("chunk.zig").Chunk; fn printFunction(writer: anytype, function: *Function) !void { if (function.name) |name| { try writer.print("<fn {}>", .{name.chars}); } else { try writer.print("<script>", .{}); } } /// A lox value. pub const Value = union(enum) { number: f64, boolean: bool, nil: void, obj: *Obj, pub fn format(self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { switch (self) { .number => |v| try writer.print("{d}", .{v}), .boolean => |v| { var rendering: []const u8 = if (v) "true" else "false"; try writer.print("{}", .{rendering}); }, .nil => try writer.print("nil", .{}), .obj => { switch (self.obj.ty) { .string => try writer.print("\"{}\"", .{self.cast([]const u8).?}), .function => { const function = self.cast(*Function).?; try printFunction(writer, function); }, .closure => { const closure = self.cast(*Closure).?; try printFunction(writer, closure.function); }, .native => { try writer.print("<native fn>", .{}); }, .upvalue => { try writer.print("<upvalue>", .{}); }, } }, } } pub const Type = enum { number, boolean, nil, string, function, closure, native, upvalue, pub fn format(self: Type, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { switch (self) { .number => try writer.print("{}", .{"number"}), .boolean => try writer.print("{}", .{"bool"}), .nil => try writer.print("{}", .{"nil"}), .string => try writer.print("{}", .{"string"}), .function => try writer.print("{}", .{"function"}), .closure => try writer.print("{}", .{"closure"}), .native => try writer.print("{}", .{"native fn"}), .upvalue => try writer.print("{}", .{"upvalue"}), } } }; pub fn ty(self: Value) Type { switch (self) { .number => return .number, .boolean => return .boolean, .nil => return .nil, .obj => { switch (self.obj.ty) { .string => return .string, .function => return .function, .native => return .native, .closure => return .closure, .upvalue => return .upvalue, } }, } } pub fn cast(self: Value, comptime T: type) ?T { switch (T) { f64 => if (self == .number) { return self.number; } else { return null; }, bool => if (self == .boolean) { return self.boolean; } else { return null; }, *Obj => if (self == .obj) { return self.obj; } else { return null; }, *String => if (self.ty() == .string) { return @fieldParentPtr(String, "base", self.obj); } else { return null; }, *Function => if (self.ty() == .function) { return @fieldParentPtr(Function, "base", self.obj); } else { return null; }, *Closure => if (self.ty() == .closure) { return @fieldParentPtr(Closure, "base", self.obj); } else { return null; }, *Native => if (self.ty() == .native) { return @fieldParentPtr(Native, "base", self.obj); } else { return null; }, *Upvalue => if (self.ty() == .upvalue) { return @fieldParentPtr(Upvalue, "base", self.obj); } else { return null; }, []const u8 => if (self.ty() == .string) { return @fieldParentPtr(String, "base", self.obj).chars; } else { return null; }, else => unreachable, } } }; pub const Obj = struct { pub const Type = enum { string, function, closure, native, upvalue, }; ty: Type, next: ?*Obj, pub fn cast(self: *Obj, comptime T: type) ?*T { switch (T) { String => if (self.ty == .string) { return @fieldParentPtr(String, "base", self); } else { return null; }, Function => if (self.ty == .function) { return @fieldParentPtr(Function, "base", self); } else { return null; }, Closure => if (self.ty == .closure) { return @fieldParentPtr(Closure, "base", self); } else { return null; }, Native => if (self.ty == .native) { return @fieldParentPtr(Native, "base", self); } else { return null; }, Upvalue => if (self.ty == .upvalue) { return @fieldParentPtr(Upvalue, "base", self); } else { return null; }, else => unreachable, } } }; pub const String = struct { pub const base_type = .string; base: Obj, chars: []const u8, }; pub const Function = struct { pub const base_type = .function; base: Obj, arity: i32, upvalue_count: i32, chunk: Chunk, name: ?*String, }; pub const Closure = struct { pub const base_type = .closure; base: Obj, function: *Function, upvalues: []?*Upvalue }; pub const Native = struct { pub const base_type = .native; pub const Fn = fn ([]Value) Value; base: Obj, function: Fn, }; pub const Upvalue = struct { pub const base_type = .upvalue; base: Obj, next: ?*Upvalue, location: *Value, closed: Value, }; pub fn equal(a: Value, b: Value) bool { if (a.ty() != b.ty()) return false; switch (a.ty()) { .boolean => return a.boolean == b.boolean, .nil => return true, .number => return a.number == b.number, .string, .function, .native, .closure, .upvalue, => return a.obj == b.obj, } }
src/value.zig
const std = @import("std"); const gpa = std.heap.c_allocator; const style = @import("ansi").style; const licenses = @import("licenses"); const zigmod = @import("../lib.zig"); const u = @import("./../util/index.zig"); const common = @import("./../common.zig"); const List = std.ArrayList(zigmod.Module); const Map = std.StringArrayHashMap(*List); // Inspired by: // https://github.com/onur/cargo-license pub fn execute(args: [][]u8) !void { _ = args; const cachepath = try std.fs.path.join(gpa, &.{ ".zigmod", "deps" }); const dir = std.fs.cwd(); var options = common.CollectOptions{ .log = false, .update = false, .alloc = gpa, }; const top_module = try common.collect_deps_deep(cachepath, dir, &options); const master_list = &List.init(gpa); try common.collect_pkgs(top_module, master_list); const map = &Map.init(gpa); const unspecified_list = &List.init(gpa); for (master_list.items) |item| { if (item.clean_path.len == 0) { continue; } if (std.mem.eql(u8, item.clean_path, "files")) { continue; } if (item.yaml == null) { try unspecified_list.append(item); continue; } const license_code = item.yaml.?.get_string("license"); if (license_code.len == 0) { try unspecified_list.append(item); continue; } const map_item = try map.getOrPut(license_code); if (!map_item.found_existing) { const temp = try gpa.create(List); temp.* = List.init(gpa); map_item.value_ptr.* = temp; } const tracking_list = map_item.value_ptr.*; try tracking_list.append(item); } const stdout = std.io.getStdOut(); const istty = stdout.isTty(); const writer = stdout.writer(); const Bold = if (!istty) "" else style.Bold; const Faint = if (!istty) "" else style.Faint; const ResetIntensity = if (!istty) "" else style.ResetIntensity; var first = true; var iter = map.iterator(); while (iter.next()) |entry| { if (!first) std.debug.print("\n", .{}); first = false; try writer.writeAll(Bold); try writer.print("{s}:\n", .{entry.key_ptr.*}); if (u.list_contains(licenses.spdx, entry.key_ptr.*)) { try writer.writeAll(Faint); try writer.print("= {s}{s}\n", .{ "https://spdx.org/licenses/", entry.key_ptr.* }); } try writer.writeAll(ResetIntensity); for (entry.value_ptr.*.items) |item| { if (std.mem.eql(u8, item.clean_path, "../..")) { try writer.print("- This\n", .{}); } else { try writer.print("- {s} {s}\n", .{ @tagName(item.dep.?.type), item.dep.?.path }); } } } if (unspecified_list.items.len > 0) { try writer.writeAll(Bold); try writer.print("Unspecified:\n", .{}); try writer.writeAll(ResetIntensity); for (unspecified_list.items) |item| { if (std.mem.eql(u8, item.clean_path, "../..")) { try writer.print("- This\n", .{}); } else { try writer.print("- {s} {s}\n", .{ @tagName(item.dep.?.type), item.dep.?.path }); } } } }
src/cmd/license.zig
const std = @import("std"); comptime { std.testing.refAllDecls(@This()); } // types const MAX_STRING_SIZE = 200; const Offset_i8 = extern struct { x: i8, y: i8, }; const RGBColor = extern struct { r: u8, g: u8, b: u8, }; // ------------------------ // HARDWARE REGISTERS / RAM pub const WIDTH: u32 = 240; pub const HEIGHT: u32 = 136; pub const FRAMEBUFFER: *allowzero volatile [16320]u8 = @intToPtr(*allowzero volatile [16320]u8, 0); pub const TILES : *[8192]u8 = @intToPtr(*[8192]u8, 0x4000); pub const SPRITES : *[8192]u8 = @intToPtr(*[8192]u8, 0x6000); pub const MAP : *[32640]u8 = @intToPtr(*[32640]u8, 0x8000); pub const GAMEPADS : *[4]u8 = @intToPtr(*[4]u8, 0xFF80); pub const MOUSE : *[4]u8 = @intToPtr(*[4]u8, 0xFF84); pub const KEYBOARD : *[4]u8 = @intToPtr(*[4]u8, 0xFF88); pub const SFX_STATE: *[16]u8 = @intToPtr(*[16]u8, 0xFF8C); pub const SOUND_REGISTERS: *[72]u8 = @intToPtr(*[72]u8, 0xFF9C); pub const WAVEFORMS: *[256]u8 =@intToPtr(*[256]u8, 0xFFE4); pub const SFX: *[4224]u8 =@intToPtr(*[4224]u8, 0x100E4); pub const MUSIC_PATTERNS: *[11520]u8 =@intToPtr(*[11520]u8, 0x11164); pub const MUSIC_TRACKS: *[408]u8 =@intToPtr(*[408]u8, 0x13E64); pub const SOUND_STATE: *[4]u8 =@intToPtr(*[4]u8, 0x13FFC); pub const STEREO_VOLUME: *[4]u8 =@intToPtr(*[4]u8, 0x14000); pub const PERSISTENT_RAM: *[1024]u8 =@intToPtr(*[1024]u8, 0x14004); pub const PERSISTENT_RAM_u32: *[256]u32 =@intToPtr(*[256]u32, 0x14004); pub const SPRITE_FLAGS: *[512]u8 =@intToPtr(*[512]u8, 0x14404); pub const SYSTEM_FONT: *[2048]u8 =@intToPtr(*[2048]u8, 0x14604); // vbank 0 const PaletteMap = packed struct { color0: u4, color1: u4, color2: u4, color3: u4, color4: u4, color5: u4, color6: u4, color7: u4, color8: u4, color9: u4, color10: u4, color11: u4, color12: u4, color13: u4, color14: u4, color15: u4, }; pub const PALETTE: *[16]RGBColor = @intToPtr(*[16]RGBColor, 0x3FC0); pub const PALETTE_u8: *[48]u8 = @intToPtr(*[48]u8, 0x3FC0); pub const PALETTE_MAP: *PaletteMap = @intToPtr(*PaletteMap, 0x3FF0); pub const PALETTE_MAP_u8: *[8]u8 = @intToPtr(*[8]u8, 0x3FF0); // TODO: this doesn't work unless it's packed, which I dno't think we can do? // pub const PALETTE_MAP: *[16]u4 = @intToPtr(*[16]u4, 0x3FF0); pub const BORDER_COLOR: *u8 = @intToPtr(*u8, 0x3FF8); pub const SCREEN_OFFSET: *Offset_i8 = @intToPtr(*Offset_i8, 0x3FF9); pub const MOUSE_CURSOR: *u8 = @intToPtr(*u8, 0x3FFB); pub const BLIT_SEGMENT: *u8 = @intToPtr(*u8, 0x3FFC); // vbank 1 pub const OVR_TRANSPARENCY: *u8 = @intToPtr(*u8, 0x3FF8); // import the RAW api pub const raw = struct { extern fn btn(id: i32) i32; extern fn btnp(id: i32, hold: i32, period: i32 ) bool; extern fn clip(x: i32, y: i32, w: i32, h: i32) void; extern fn cls(color: i32) void; extern fn circ(x: i32, y: i32, radius: i32, color: i32) void; extern fn circb(x: i32, y: i32, radius: i32, color: i32) void; extern fn exit() void; extern fn elli(x: i32, y: i32, a: i32, b: i32, color: i32) void; extern fn ellib(x: i32, y: i32, a: i32, b: i32, color: i32) void; extern fn fget(id: i32, flag: u8) bool; extern fn font(text: [*:0]u8, x: u32, y: i32, trans_colors: ?[*]const u8, color_count: i32, char_width: i32, char_height: i32, fixed: bool, scale: i32) i32; extern fn fset(id: i32, flag: u8, value: bool) bool; extern fn key(keycode: i32) bool; extern fn keyp(keycode: i32, hold: i32, period: i32 ) bool; extern fn line(x0: i32, y0: i32, x1: i32, y1: i32, color: i32) void; extern fn map(x: i32, y: i32, w: i32, h: i32, sx: i32, sy: i32, trans_colors: ?[*]const u8, color_count: i32, scale: i32, remap: i32) void; extern fn memcpy(to: u32, from: u32, length: u32) void; extern fn memset(addr: u32, value: u8, length: u32) void; extern fn mget(x: i32, y:i32) i32; extern fn mouse(data: *MouseData) void; extern fn mset(x: i32, y:i32, value: bool) void; extern fn music(track: i32, frame: i32, row: i32, loop: bool, sustain: bool, tempo: i32, speed: i32) void; extern fn peek(addr: u32, bits: i32) u8; extern fn peek4(addr4: u32) u8; extern fn peek2(addr2: u32) u8; extern fn peek1(bitaddr: u32) u8; extern fn pix(x: i32, y:i32, color: i32) void; extern fn pmem(index: u32, value: i64) u32; extern fn poke(addr: u32, value: u8, bits: i32) void; extern fn poke4(addr4: u32, value: u8) void; extern fn poke2(addr2: u32, value: u8) void; extern fn poke1(bitaddr: u32, value: u8) void; extern fn print(text: [*:0]u8, x: i32, y: i32, color: i32, fixed: bool, scale: i32, smallfont: bool) i32; extern fn rect(x: i32, y: i32, w: i32, h:i32, color: i32) void; extern fn rectb(x: i32, y: i32, w: i32, h:i32, color: i32) void; extern fn reset() void; extern fn sfx(id: i32, note: i32, octave: i32, duration: i32, channel: i32, volumeLeft: i32, volumeRight: i32, speed: i32) void; extern fn spr(id: i32, x: i32, y: i32, trans_colors: ?[*]const u8, color_count: i32, scale: i32, flip: i32, rotate: i32, w: i32, h: i32) void; extern fn sync(mask: i32, bank: i32, tocart: bool) void; extern fn textri(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, u1: f32, v1: f32, u2: f32, v2: f32, u3: f32, v3: f32, texsrc: i32, trans_colors: ?[*]const u8, color_count: i32) void; extern fn tri(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, color: i32) void; extern fn trib(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, color: i32) void; extern fn time() f32; extern fn trace(text: [*:0]u8, color: i32) void; extern fn tstamp() u64; extern fn vbank(bank: i32) u8; }; // ----- // INPUT const MouseData = extern struct { x: i16, y: i16, scrollx: i8, scrolly: i8, left: bool, middle: bool, right: bool, }; pub const key = raw.key; // TODO: nicer API? pub const keyp = raw.keyp; pub const held = raw.btnp; pub fn pressed(id: i32) bool { return raw.btnp(id, -1, -1); } pub fn btn(id: i32) bool { return raw.btn(id) != 0; } pub fn anybtn() bool { return raw.btn(-1) != 0; } // ----------------- // DRAW / DRAW UTILS pub const clip = raw.clip; pub fn noclip() void { raw.clip(0, 0, WIDTH, HEIGHT); } pub const cls = raw.cls; pub const circ = raw.circ; pub const circb = raw.circb; pub const elli = raw.elli; pub const ellib = raw.ellib; pub const fget = raw.fget; pub const fset = raw.fset; pub const line = raw.line; pub const mset = raw.mset; pub const mget = raw.mget; pub const mouse = raw.mouse; // map [x=0 y=0] [w=30 h=17] [sx=0 sy=0] [colorkey=-1] [scale=1] [remap=nil] // TODO: remap should be what???? // pub extern fn map(x: i32, y: i32, w: i32, h: i32, sx: i32, sy: i32, trans_colors: ?[*]u8, color_count: i32, scale: i32, remap: i32) void; const MapArgs = struct { x: i32 = 0, y: i32 = 0, w: i32 = 30, h: i32 = 17, sx: i32 = 0, sy: i32 = 0, transparent: []const u8 = .{}, scale: u8 = 1, remap: i32 = -1, // TODO }; pub fn map(args: MapArgs) void { const color_count = @intCast(u8,args.transparent.len); const colors = args.transparent.ptr; std.debug.assert(color_count < 16); raw.map(args.x, args.y, args.w, args.h, args.sx, args.sy, colors, color_count, args.scale, args.remap); } pub fn pix(x: i32, y: i32, color: u8) void { raw.pix(x,y,color); } pub fn getpix(x: i32, y: i32) u8 { raw.pix(x,y, -1); } // pub extern fn spr(id: i32, x: i32, y: i32, trans_colors: [*]u8, color_count: i32, scale: i32, flip: i32, rotate: i32, w: i32, h: i32) void; pub const Flip = enum(u2) { no = 0, horizontal = 1, vertical = 2, both = 3, }; pub const Rotate = enum(u2) { no = 0, by90 = 1, by180 = 2, by270 = 3, }; const SpriteArgs = struct { w: i32 = 1, h: i32 = 1, transparent: []const u8 = .{}, scale: u8 = 1, flip: Flip = Flip.no, rotate: Rotate = Rotate.no, }; pub fn spr(id: i32, x: i32, y: i32, args: SpriteArgs) void { const color_count = @intCast(u8,args.transparent.len); const colors = args.transparent.ptr; std.debug.assert(color_count < 16); raw.spr(id, x, y, colors, color_count, args.scale, @enumToInt(args.flip), @enumToInt(args.rotate), args.w, args.h); } pub const rect = raw.rect; pub const rectb = raw.rectb; pub const tri = raw.tri; pub const trib = raw.trib; const TextriArgs = struct { texsrc : i32 = 0, transparent: []const u8 = .{}, }; pub fn textri(x1: f32, y1: f32, x2: f32, y2: f32, x3: f32, y3: f32, @"u1": f32, v1: f32, @"u2": f32, v2: f32, @"u3": f32, v3: f32, args: TextriArgs) void { const color_count = @intCast(u8,args.transparent.len); const trans_colors = args.transparent.ptr; raw.textri(x1, y1, x2, y2, x3, y3, @"u1", v1, @"u2", v2, @"u3", v3, args.texsrc, trans_colors, color_count); } // ---- // TEXT const PrintArgs = struct { color: u8 = 15, fixed : bool = false, small_font : bool = false, scale : u8 = 1, }; const FontArgs = struct { transparent: []const u8 = .{}, char_width: u8, char_height: u8, fixed: bool = false, scale: u8 = 1 }; fn sliceToZString(text: []const u8, buff: [*:0]u8, maxLen: u16) void { var len = std.math.min(maxLen, text.len); std.mem.copy(u8, buff[0..len], text[0..len]); buff[len] = 0; } pub fn print(text: []const u8, x: i32, y: i32, args: PrintArgs) i32 { var buff : [MAX_STRING_SIZE:0]u8 = undefined; sliceToZString(text, &buff, MAX_STRING_SIZE); return raw.print(&buff, x, y, args.color, args.fixed, args.scale, args.small_font); } pub fn printf(comptime fmt: []const u8, fmtargs: anytype, x: i32, y: i32, args: PrintArgs) i32 { var buff : [MAX_STRING_SIZE:0]u8 = undefined; _ = std.fmt.bufPrintZ(&buff, fmt, fmtargs) catch unreachable; return raw.print(&buff, x, y, args.color, args.fixed, args.scale, args.small_font); } pub fn font(text: []const u8, x: u32, y: i32, args: FontArgs) i32 { const color_count = @intCast(u8,args.transparent.len); const colors = args.transparent.ptr; var buff : [MAX_STRING_SIZE:0]u8 = undefined; sliceToZString(text, &buff, MAX_STRING_SIZE); return raw.font(&buff, x, y, colors, color_count, args.char_width, args.char_height, args.fixed, args.scale); } // ----- // AUDIO // music [track=-1] [frame=-1] [row=-1] [loop=true] [sustain=false] [tempo=-1] [speed=-1] const MusicArgs = struct { frame: i8 = -1, row: i8 = -1, loop: bool = true, sustain: bool = false, tempo: i8 = -1, speed: i8 = -1, }; pub fn music(track:i32, args: MusicArgs) void { raw.music(track, args.frame, args.row, args.loop, args.sustain, args.tempo, args.speed); } pub fn nomusic() void { music(-1, .{}); } // sfx id [note] [duration=-1] [channel=0] [volume=15] [speed=0] // void tic_api_sfx(tic_mem* memory, s32 index, s32 note, s32 octave, s32 duration, s32 channel, s32 left, s32 right, s32 speed) const MAX_VOLUME : i8 = 15; const SfxArgs = struct { sfx: i8 = -1, note: i8 = -1, octave: i8 = -1, duration: i8 = -1, channel: i8 = 0, volume: i8 = 15, volumeLeft: i8 = 15, volumeRight: i8 = 15, speed: i8 = 0, }; // pub extern fn sfx(id: i32, note: i32, duration: i32, channel: i32, volume: i32, speed: i32) void; const SFX_NOTES = [_][] const u8 {"C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#", "A-", "A#", "B-"}; fn parse_note(name: []const u8, noteArgs: *SfxArgs) bool { var note_signature : []const u8 = undefined; var octave : u8 = undefined; if (name.len == 2) { note_signature = &.{ name[0], '-' }; octave = name[1]; } else { note_signature = name[0..2]; octave = name[2]; } var i: i8 = 0; for (SFX_NOTES) |music_note| { if (std.mem.eql(u8, music_note, note_signature)) { noteArgs.note = i; noteArgs.octave = @intCast(i8, octave - '1'); return true; } i+=1; } return false; } pub fn note(name: []const u8, args: SfxArgs) void { var largs : SfxArgs = args; if (parse_note(name, &largs)) { sfx(args.sfx, largs); } } pub fn sfx(id: i32, args: SfxArgs) void { var largs = args; if (args.volume != MAX_VOLUME) { largs.volumeLeft = args.volume; largs.volumeRight = args.volume; } raw.sfx(id, args.note, args.octave, args.duration, args.channel, largs.volumeLeft, largs.volumeRight, args.speed); } pub fn nosfx() void { sfx(-1, .{}); } // ------ // MEMORY pub fn pmemset(index: u32, value: u3) void { raw.pmem(index, value); } pub fn pmemget(index: u32) u32 { return raw.pmem(index, -1); } pub const memcpy = raw.memcpy; pub const memset = raw.memset; pub fn poke(addr: u32, value: u8) void { raw.poke(addr, value, 8); } pub const poke4 = raw.poke4; pub const poke2 = raw.poke2; pub const poke1 = raw.poke1; pub fn peek(addr: u32) u8 { return raw.peek(addr, 8); } pub const peek4 = raw.peek4; pub const peek2 = raw.peek2; pub const peek1 = raw.peek1; pub const vbank = raw.vbank; // SYSTEM pub const exit = raw.exit; pub const reset = raw.reset; pub fn trace(text: []const u8) void { var buff : [MAX_STRING_SIZE:0]u8 = undefined; sliceToZString(text, &buff, MAX_STRING_SIZE); raw.trace(&buff); } const SectionFlags = packed struct { // tiles = 1<<0 -- 1 // sprites = 1<<1 -- 2 // map = 1<<2 -- 4 // sfx = 1<<3 -- 8 // music = 1<<4 -- 16 // palette = 1<<5 -- 32 // flags = 1<<6 -- 64 // screen = 1<<7 -- 128 (as of 0.90) tiles: bool = false, sprites: bool = false, map: bool = false, sfx: bool = false, music: bool = false, palette: bool = false, flags: bool = false, screen: bool = false, }; // const SectionFlagsMask = packed union { // sections: SectionFlags, // value: u8 // }; const SyncArgs = struct { sections: SectionFlags, bank: u8, toCartridge: bool = false, fromCartridge: bool = false, }; pub fn sync(args: SyncArgs) void { // var mask = SectionFlagsMask { .sections = args.sections }; raw.sync(@bitCast(u8, args.sections), args.bank, args.toCartridge); } // TIME KEEPING pub const time = raw.time; pub const tstamp = raw.tstamp;
templates/zig/src/tic80.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day11.txt"); // const data = @embedFile("../data/day11-tst.txt"); pub fn main() !void { const w = 10; const h = 10; var grid = [_]u8{0} ** (w * h); var flashed = [_]bool{false} ** (w * h); var it = tokenize(u8, data, "\r\n"); var j: isize = 0; while (it.next()) |line| : (j += 1) { for (line) |c, i| { grid[idx(@intCast(isize, i), j)] = c - '0'; } } var flash_count: usize = 0; // for ([_]u0{0} ** 100) |_, i| { // Uncomment this for step1 for ([_]u0{0} ** 1000) |_, i| { flash_count += step(grid[0..], flashed[0..]); var all_flashed = true; for (grid) |n| { if (n != 0) { all_flashed = false; break; } } if (all_flashed) { print("{}\n", .{i}); break; } } print("{}\n", .{flash_count}); } pub fn idx(i: isize, j: isize) usize { return @intCast(usize, i + 10 * j); } pub fn printGrid(grid: []u8) void { var i: isize = 0; while (i < 10) : (i += 1) { var j: isize = 0; while (j < 10) : (j += 1) { print("{d: >3.}", .{grid[idx(j, i)]}); } print("\n", .{}); } print("\n", .{}); } pub fn step(grid: []u8, flashed: []bool) usize { std.mem.set(bool, flashed, false); for (grid) |*v| { v.* += 1; } var flash_count: usize = 0; while (true) { var had_flash = false; for (grid) |v, i| { if (v > 9 and !flashed[i]) { flash(@intCast(isize, i), grid, flashed); had_flash = true; flash_count += 1; } } if (!had_flash) { break; } } for (grid) |*v, i| { if (flashed[i]) { v.* = 0; } } return flash_count; } fn flash(index: isize, grid: []u8, flashed: []bool) void { flashed[@intCast(usize, index)] = true; var cx: isize = @mod(index, 10); var cy: isize = @divTrunc(index, 10); assert(index == (cx + 10 * cy)); var j: isize = -1; while (j <= 1) : (j += 1) { var y = cy + j; if (y < 0 or y >= 10) continue; var i: isize = -1; while (i <= 1) : (i += 1) { var x = cx + i; if (x < 0 or x >= 10) continue; if (x == cx and y == cy) continue; grid[idx(x, y)] += 1; } } } // 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/day11.zig
const std = @import("std"); const mode = @import("builtin").mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels inline fn cast(comptime DestType: type, target: anytype) DestType { if (@typeInfo(@TypeOf(target)) == .Int) { const dest = @typeInfo(DestType).Int; const source = @typeInfo(@TypeOf(target)).Int; if (dest.bits < source.bits) { return @bitCast(DestType, @truncate(std.meta.Int(source.signedness, dest.bits), target)); } else { return @bitCast(DestType, @as(std.meta.Int(source.signedness, dest.bits), target)); } } return @as(DestType, target); } // The type LooseFieldElement is a field element with loose bounds. // Bounds: [[0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000], [0x0 ~> 0x18000000000000]] pub const LooseFieldElement = [5]u64; // The type TightFieldElement is a field element with tight bounds. // Bounds: [[0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000], [0x0 ~> 0x8000000000000]] pub const TightFieldElement = [5]u64; /// The function addcarryxU51 is an addition with carry. /// /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^51 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^51⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x7ffffffffffff] /// arg3: [0x0 ~> 0x7ffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0x7ffffffffffff] /// out2: [0x0 ~> 0x1] inline fn addcarryxU51(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u64, arg1) + arg2) + arg3); const x2 = (x1 & 0x7ffffffffffff); const x3 = cast(u1, (x1 >> 51)); out1.* = x2; out2.* = x3; } /// The function subborrowxU51 is a subtraction with borrow. /// /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^51 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^51⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0x7ffffffffffff] /// arg3: [0x0 ~> 0x7ffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0x7ffffffffffff] /// out2: [0x0 ~> 0x1] inline fn subborrowxU51(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = cast(i64, (cast(i128, cast(i64, (cast(i128, arg2) - cast(i128, arg1)))) - cast(i128, arg3))); const x2 = cast(i1, (x1 >> 51)); const x3 = cast(u64, (cast(i128, x1) & cast(i128, 0x7ffffffffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function cmovznzU64 is a single-word conditional move. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] inline fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (~(~arg1)); const x2 = cast(u64, (cast(i128, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i128, 0xffffffffffffffff))); const x3 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function carryMul multiplies two field elements and reduces the result. /// /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg2) mod m /// pub fn carryMul(out1: *TightFieldElement, arg1: LooseFieldElement, arg2: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u128, (arg1[4])) * cast(u128, ((arg2[4]) * 0x13))); const x2 = (cast(u128, (arg1[4])) * cast(u128, ((arg2[3]) * 0x13))); const x3 = (cast(u128, (arg1[4])) * cast(u128, ((arg2[2]) * 0x13))); const x4 = (cast(u128, (arg1[4])) * cast(u128, ((arg2[1]) * 0x13))); const x5 = (cast(u128, (arg1[3])) * cast(u128, ((arg2[4]) * 0x13))); const x6 = (cast(u128, (arg1[3])) * cast(u128, ((arg2[3]) * 0x13))); const x7 = (cast(u128, (arg1[3])) * cast(u128, ((arg2[2]) * 0x13))); const x8 = (cast(u128, (arg1[2])) * cast(u128, ((arg2[4]) * 0x13))); const x9 = (cast(u128, (arg1[2])) * cast(u128, ((arg2[3]) * 0x13))); const x10 = (cast(u128, (arg1[1])) * cast(u128, ((arg2[4]) * 0x13))); const x11 = (cast(u128, (arg1[4])) * cast(u128, (arg2[0]))); const x12 = (cast(u128, (arg1[3])) * cast(u128, (arg2[1]))); const x13 = (cast(u128, (arg1[3])) * cast(u128, (arg2[0]))); const x14 = (cast(u128, (arg1[2])) * cast(u128, (arg2[2]))); const x15 = (cast(u128, (arg1[2])) * cast(u128, (arg2[1]))); const x16 = (cast(u128, (arg1[2])) * cast(u128, (arg2[0]))); const x17 = (cast(u128, (arg1[1])) * cast(u128, (arg2[3]))); const x18 = (cast(u128, (arg1[1])) * cast(u128, (arg2[2]))); const x19 = (cast(u128, (arg1[1])) * cast(u128, (arg2[1]))); const x20 = (cast(u128, (arg1[1])) * cast(u128, (arg2[0]))); const x21 = (cast(u128, (arg1[0])) * cast(u128, (arg2[4]))); const x22 = (cast(u128, (arg1[0])) * cast(u128, (arg2[3]))); const x23 = (cast(u128, (arg1[0])) * cast(u128, (arg2[2]))); const x24 = (cast(u128, (arg1[0])) * cast(u128, (arg2[1]))); const x25 = (cast(u128, (arg1[0])) * cast(u128, (arg2[0]))); const x26 = (x25 + (x10 + (x9 + (x7 + x4)))); const x27 = cast(u64, (x26 >> 51)); const x28 = cast(u64, (x26 & cast(u128, 0x7ffffffffffff))); const x29 = (x21 + (x17 + (x14 + (x12 + x11)))); const x30 = (x22 + (x18 + (x15 + (x13 + x1)))); const x31 = (x23 + (x19 + (x16 + (x5 + x2)))); const x32 = (x24 + (x20 + (x8 + (x6 + x3)))); const x33 = (cast(u128, x27) + x32); const x34 = cast(u64, (x33 >> 51)); const x35 = cast(u64, (x33 & cast(u128, 0x7ffffffffffff))); const x36 = (cast(u128, x34) + x31); const x37 = cast(u64, (x36 >> 51)); const x38 = cast(u64, (x36 & cast(u128, 0x7ffffffffffff))); const x39 = (cast(u128, x37) + x30); const x40 = cast(u64, (x39 >> 51)); const x41 = cast(u64, (x39 & cast(u128, 0x7ffffffffffff))); const x42 = (cast(u128, x40) + x29); const x43 = cast(u64, (x42 >> 51)); const x44 = cast(u64, (x42 & cast(u128, 0x7ffffffffffff))); const x45 = (x43 * 0x13); const x46 = (x28 + x45); const x47 = (x46 >> 51); const x48 = (x46 & 0x7ffffffffffff); const x49 = (x47 + x35); const x50 = cast(u1, (x49 >> 51)); const x51 = (x49 & 0x7ffffffffffff); const x52 = (cast(u64, x50) + x38); out1[0] = x48; out1[1] = x51; out1[2] = x52; out1[3] = x41; out1[4] = x44; } /// The function carrySquare squares a field element and reduces the result. /// /// Postconditions: /// eval out1 mod m = (eval arg1 * eval arg1) mod m /// pub fn carrySquare(out1: *TightFieldElement, arg1: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[4]) * 0x13); const x2 = (x1 * 0x2); const x3 = ((arg1[4]) * 0x2); const x4 = ((arg1[3]) * 0x13); const x5 = (x4 * 0x2); const x6 = ((arg1[3]) * 0x2); const x7 = ((arg1[2]) * 0x2); const x8 = ((arg1[1]) * 0x2); const x9 = (cast(u128, (arg1[4])) * cast(u128, x1)); const x10 = (cast(u128, (arg1[3])) * cast(u128, x2)); const x11 = (cast(u128, (arg1[3])) * cast(u128, x4)); const x12 = (cast(u128, (arg1[2])) * cast(u128, x2)); const x13 = (cast(u128, (arg1[2])) * cast(u128, x5)); const x14 = (cast(u128, (arg1[2])) * cast(u128, (arg1[2]))); const x15 = (cast(u128, (arg1[1])) * cast(u128, x2)); const x16 = (cast(u128, (arg1[1])) * cast(u128, x6)); const x17 = (cast(u128, (arg1[1])) * cast(u128, x7)); const x18 = (cast(u128, (arg1[1])) * cast(u128, (arg1[1]))); const x19 = (cast(u128, (arg1[0])) * cast(u128, x3)); const x20 = (cast(u128, (arg1[0])) * cast(u128, x6)); const x21 = (cast(u128, (arg1[0])) * cast(u128, x7)); const x22 = (cast(u128, (arg1[0])) * cast(u128, x8)); const x23 = (cast(u128, (arg1[0])) * cast(u128, (arg1[0]))); const x24 = (x23 + (x15 + x13)); const x25 = cast(u64, (x24 >> 51)); const x26 = cast(u64, (x24 & cast(u128, 0x7ffffffffffff))); const x27 = (x19 + (x16 + x14)); const x28 = (x20 + (x17 + x9)); const x29 = (x21 + (x18 + x10)); const x30 = (x22 + (x12 + x11)); const x31 = (cast(u128, x25) + x30); const x32 = cast(u64, (x31 >> 51)); const x33 = cast(u64, (x31 & cast(u128, 0x7ffffffffffff))); const x34 = (cast(u128, x32) + x29); const x35 = cast(u64, (x34 >> 51)); const x36 = cast(u64, (x34 & cast(u128, 0x7ffffffffffff))); const x37 = (cast(u128, x35) + x28); const x38 = cast(u64, (x37 >> 51)); const x39 = cast(u64, (x37 & cast(u128, 0x7ffffffffffff))); const x40 = (cast(u128, x38) + x27); const x41 = cast(u64, (x40 >> 51)); const x42 = cast(u64, (x40 & cast(u128, 0x7ffffffffffff))); const x43 = (x41 * 0x13); const x44 = (x26 + x43); const x45 = (x44 >> 51); const x46 = (x44 & 0x7ffffffffffff); const x47 = (x45 + x33); const x48 = cast(u1, (x47 >> 51)); const x49 = (x47 & 0x7ffffffffffff); const x50 = (cast(u64, x48) + x36); out1[0] = x46; out1[1] = x49; out1[2] = x50; out1[3] = x39; out1[4] = x42; } /// The function carry reduces a field element. /// /// Postconditions: /// eval out1 mod m = eval arg1 mod m /// pub fn carry(out1: *TightFieldElement, arg1: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); const x2 = ((x1 >> 51) + (arg1[1])); const x3 = ((x2 >> 51) + (arg1[2])); const x4 = ((x3 >> 51) + (arg1[3])); const x5 = ((x4 >> 51) + (arg1[4])); const x6 = ((x1 & 0x7ffffffffffff) + ((x5 >> 51) * 0x13)); const x7 = (cast(u64, cast(u1, (x6 >> 51))) + (x2 & 0x7ffffffffffff)); const x8 = (x6 & 0x7ffffffffffff); const x9 = (x7 & 0x7ffffffffffff); const x10 = (cast(u64, cast(u1, (x7 >> 51))) + (x3 & 0x7ffffffffffff)); const x11 = (x4 & 0x7ffffffffffff); const x12 = (x5 & 0x7ffffffffffff); out1[0] = x8; out1[1] = x9; out1[2] = x10; out1[3] = x11; out1[4] = x12; } /// The function add adds two field elements. /// /// Postconditions: /// eval out1 mod m = (eval arg1 + eval arg2) mod m /// pub fn add(out1: *LooseFieldElement, arg1: TightFieldElement, arg2: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) + (arg2[0])); const x2 = ((arg1[1]) + (arg2[1])); const x3 = ((arg1[2]) + (arg2[2])); const x4 = ((arg1[3]) + (arg2[3])); const x5 = ((arg1[4]) + (arg2[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function sub subtracts two field elements. /// /// Postconditions: /// eval out1 mod m = (eval arg1 - eval arg2) mod m /// pub fn sub(out1: *LooseFieldElement, arg1: TightFieldElement, arg2: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = ((0xfffffffffffda + (arg1[0])) - (arg2[0])); const x2 = ((0xffffffffffffe + (arg1[1])) - (arg2[1])); const x3 = ((0xffffffffffffe + (arg1[2])) - (arg2[2])); const x4 = ((0xffffffffffffe + (arg1[3])) - (arg2[3])); const x5 = ((0xffffffffffffe + (arg1[4])) - (arg2[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function opp negates a field element. /// /// Postconditions: /// eval out1 mod m = -eval arg1 mod m /// pub fn opp(out1: *LooseFieldElement, arg1: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (0xfffffffffffda - (arg1[0])); const x2 = (0xffffffffffffe - (arg1[1])); const x3 = (0xffffffffffffe - (arg1[2])); const x4 = (0xffffffffffffe - (arg1[3])); const x5 = (0xffffffffffffe - (arg1[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function selectznz is a multi-limb conditional select. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn selectznz(out1: *[5]u64, arg1: u1, arg2: [5]u64, arg3: [5]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u64 = undefined; cmovznzU64(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u64 = undefined; cmovznzU64(&x5, arg1, (arg2[4]), (arg3[4])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function toBytes serializes a field element to bytes in little-endian order. /// /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..31] /// /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] pub fn toBytes(out1: *[32]u8, arg1: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU51(&x1, &x2, 0x0, (arg1[0]), 0x7ffffffffffed); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU51(&x3, &x4, x2, (arg1[1]), 0x7ffffffffffff); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU51(&x5, &x6, x4, (arg1[2]), 0x7ffffffffffff); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU51(&x7, &x8, x6, (arg1[3]), 0x7ffffffffffff); var x9: u64 = undefined; var x10: u1 = undefined; subborrowxU51(&x9, &x10, x8, (arg1[4]), 0x7ffffffffffff); var x11: u64 = undefined; cmovznzU64(&x11, x10, cast(u64, 0x0), 0xffffffffffffffff); var x12: u64 = undefined; var x13: u1 = undefined; addcarryxU51(&x12, &x13, 0x0, x1, (x11 & 0x7ffffffffffed)); var x14: u64 = undefined; var x15: u1 = undefined; addcarryxU51(&x14, &x15, x13, x3, (x11 & 0x7ffffffffffff)); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU51(&x16, &x17, x15, x5, (x11 & 0x7ffffffffffff)); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU51(&x18, &x19, x17, x7, (x11 & 0x7ffffffffffff)); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU51(&x20, &x21, x19, x9, (x11 & 0x7ffffffffffff)); const x22 = (x20 << 4); const x23 = (x18 * cast(u64, 0x2)); const x24 = (x16 << 6); const x25 = (x14 << 3); const x26 = cast(u8, (x12 & cast(u64, 0xff))); const x27 = (x12 >> 8); const x28 = cast(u8, (x27 & cast(u64, 0xff))); const x29 = (x27 >> 8); const x30 = cast(u8, (x29 & cast(u64, 0xff))); const x31 = (x29 >> 8); const x32 = cast(u8, (x31 & cast(u64, 0xff))); const x33 = (x31 >> 8); const x34 = cast(u8, (x33 & cast(u64, 0xff))); const x35 = (x33 >> 8); const x36 = cast(u8, (x35 & cast(u64, 0xff))); const x37 = cast(u8, (x35 >> 8)); const x38 = (x25 + cast(u64, x37)); const x39 = cast(u8, (x38 & cast(u64, 0xff))); const x40 = (x38 >> 8); const x41 = cast(u8, (x40 & cast(u64, 0xff))); const x42 = (x40 >> 8); const x43 = cast(u8, (x42 & cast(u64, 0xff))); const x44 = (x42 >> 8); const x45 = cast(u8, (x44 & cast(u64, 0xff))); const x46 = (x44 >> 8); const x47 = cast(u8, (x46 & cast(u64, 0xff))); const x48 = (x46 >> 8); const x49 = cast(u8, (x48 & cast(u64, 0xff))); const x50 = cast(u8, (x48 >> 8)); const x51 = (x24 + cast(u64, x50)); const x52 = cast(u8, (x51 & cast(u64, 0xff))); const x53 = (x51 >> 8); const x54 = cast(u8, (x53 & cast(u64, 0xff))); const x55 = (x53 >> 8); const x56 = cast(u8, (x55 & cast(u64, 0xff))); const x57 = (x55 >> 8); const x58 = cast(u8, (x57 & cast(u64, 0xff))); const x59 = (x57 >> 8); const x60 = cast(u8, (x59 & cast(u64, 0xff))); const x61 = (x59 >> 8); const x62 = cast(u8, (x61 & cast(u64, 0xff))); const x63 = (x61 >> 8); const x64 = cast(u8, (x63 & cast(u64, 0xff))); const x65 = cast(u1, (x63 >> 8)); const x66 = (x23 + cast(u64, x65)); const x67 = cast(u8, (x66 & cast(u64, 0xff))); const x68 = (x66 >> 8); const x69 = cast(u8, (x68 & cast(u64, 0xff))); const x70 = (x68 >> 8); const x71 = cast(u8, (x70 & cast(u64, 0xff))); const x72 = (x70 >> 8); const x73 = cast(u8, (x72 & cast(u64, 0xff))); const x74 = (x72 >> 8); const x75 = cast(u8, (x74 & cast(u64, 0xff))); const x76 = (x74 >> 8); const x77 = cast(u8, (x76 & cast(u64, 0xff))); const x78 = cast(u8, (x76 >> 8)); const x79 = (x22 + cast(u64, x78)); const x80 = cast(u8, (x79 & cast(u64, 0xff))); const x81 = (x79 >> 8); const x82 = cast(u8, (x81 & cast(u64, 0xff))); const x83 = (x81 >> 8); const x84 = cast(u8, (x83 & cast(u64, 0xff))); const x85 = (x83 >> 8); const x86 = cast(u8, (x85 & cast(u64, 0xff))); const x87 = (x85 >> 8); const x88 = cast(u8, (x87 & cast(u64, 0xff))); const x89 = (x87 >> 8); const x90 = cast(u8, (x89 & cast(u64, 0xff))); const x91 = cast(u8, (x89 >> 8)); out1[0] = x26; out1[1] = x28; out1[2] = x30; out1[3] = x32; out1[4] = x34; out1[5] = x36; out1[6] = x39; out1[7] = x41; out1[8] = x43; out1[9] = x45; out1[10] = x47; out1[11] = x49; out1[12] = x52; out1[13] = x54; out1[14] = x56; out1[15] = x58; out1[16] = x60; out1[17] = x62; out1[18] = x64; out1[19] = x67; out1[20] = x69; out1[21] = x71; out1[22] = x73; out1[23] = x75; out1[24] = x77; out1[25] = x80; out1[26] = x82; out1[27] = x84; out1[28] = x86; out1[29] = x88; out1[30] = x90; out1[31] = x91; } /// The function fromBytes deserializes a field element from bytes in little-endian order. /// /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x7f]] pub fn fromBytes(out1: *TightFieldElement, arg1: [32]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, (arg1[31])) << 44); const x2 = (cast(u64, (arg1[30])) << 36); const x3 = (cast(u64, (arg1[29])) << 28); const x4 = (cast(u64, (arg1[28])) << 20); const x5 = (cast(u64, (arg1[27])) << 12); const x6 = (cast(u64, (arg1[26])) << 4); const x7 = (cast(u64, (arg1[25])) << 47); const x8 = (cast(u64, (arg1[24])) << 39); const x9 = (cast(u64, (arg1[23])) << 31); const x10 = (cast(u64, (arg1[22])) << 23); const x11 = (cast(u64, (arg1[21])) << 15); const x12 = (cast(u64, (arg1[20])) << 7); const x13 = (cast(u64, (arg1[19])) << 50); const x14 = (cast(u64, (arg1[18])) << 42); const x15 = (cast(u64, (arg1[17])) << 34); const x16 = (cast(u64, (arg1[16])) << 26); const x17 = (cast(u64, (arg1[15])) << 18); const x18 = (cast(u64, (arg1[14])) << 10); const x19 = (cast(u64, (arg1[13])) << 2); const x20 = (cast(u64, (arg1[12])) << 45); const x21 = (cast(u64, (arg1[11])) << 37); const x22 = (cast(u64, (arg1[10])) << 29); const x23 = (cast(u64, (arg1[9])) << 21); const x24 = (cast(u64, (arg1[8])) << 13); const x25 = (cast(u64, (arg1[7])) << 5); const x26 = (cast(u64, (arg1[6])) << 48); const x27 = (cast(u64, (arg1[5])) << 40); const x28 = (cast(u64, (arg1[4])) << 32); const x29 = (cast(u64, (arg1[3])) << 24); const x30 = (cast(u64, (arg1[2])) << 16); const x31 = (cast(u64, (arg1[1])) << 8); const x32 = (arg1[0]); const x33 = (x31 + cast(u64, x32)); const x34 = (x30 + x33); const x35 = (x29 + x34); const x36 = (x28 + x35); const x37 = (x27 + x36); const x38 = (x26 + x37); const x39 = (x38 & 0x7ffffffffffff); const x40 = cast(u8, (x38 >> 51)); const x41 = (x25 + cast(u64, x40)); const x42 = (x24 + x41); const x43 = (x23 + x42); const x44 = (x22 + x43); const x45 = (x21 + x44); const x46 = (x20 + x45); const x47 = (x46 & 0x7ffffffffffff); const x48 = cast(u8, (x46 >> 51)); const x49 = (x19 + cast(u64, x48)); const x50 = (x18 + x49); const x51 = (x17 + x50); const x52 = (x16 + x51); const x53 = (x15 + x52); const x54 = (x14 + x53); const x55 = (x13 + x54); const x56 = (x55 & 0x7ffffffffffff); const x57 = cast(u8, (x55 >> 51)); const x58 = (x12 + cast(u64, x57)); const x59 = (x11 + x58); const x60 = (x10 + x59); const x61 = (x9 + x60); const x62 = (x8 + x61); const x63 = (x7 + x62); const x64 = (x63 & 0x7ffffffffffff); const x65 = cast(u8, (x63 >> 51)); const x66 = (x6 + cast(u64, x65)); const x67 = (x5 + x66); const x68 = (x4 + x67); const x69 = (x3 + x68); const x70 = (x2 + x69); const x71 = (x1 + x70); out1[0] = x39; out1[1] = x47; out1[2] = x56; out1[3] = x64; out1[4] = x71; } /// The function relax is the identity function converting from tight field elements to loose field elements. /// /// Postconditions: /// out1 = arg1 /// pub fn relax(out1: *LooseFieldElement, arg1: TightFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); const x2 = (arg1[1]); const x3 = (arg1[2]); const x4 = (arg1[3]); const x5 = (arg1[4]); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; } /// The function carryScmul121666 multiplies a field element by 121666 and reduces the result. /// /// Postconditions: /// eval out1 mod m = (121666 * eval arg1) mod m /// pub fn carryScmul121666(out1: *TightFieldElement, arg1: LooseFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u128, 0x1db42) * cast(u128, (arg1[4]))); const x2 = (cast(u128, 0x1db42) * cast(u128, (arg1[3]))); const x3 = (cast(u128, 0x1db42) * cast(u128, (arg1[2]))); const x4 = (cast(u128, 0x1db42) * cast(u128, (arg1[1]))); const x5 = (cast(u128, 0x1db42) * cast(u128, (arg1[0]))); const x6 = cast(u64, (x5 >> 51)); const x7 = cast(u64, (x5 & cast(u128, 0x7ffffffffffff))); const x8 = (cast(u128, x6) + x4); const x9 = cast(u64, (x8 >> 51)); const x10 = cast(u64, (x8 & cast(u128, 0x7ffffffffffff))); const x11 = (cast(u128, x9) + x3); const x12 = cast(u64, (x11 >> 51)); const x13 = cast(u64, (x11 & cast(u128, 0x7ffffffffffff))); const x14 = (cast(u128, x12) + x2); const x15 = cast(u64, (x14 >> 51)); const x16 = cast(u64, (x14 & cast(u128, 0x7ffffffffffff))); const x17 = (cast(u128, x15) + x1); const x18 = cast(u64, (x17 >> 51)); const x19 = cast(u64, (x17 & cast(u128, 0x7ffffffffffff))); const x20 = (x18 * 0x13); const x21 = (x7 + x20); const x22 = cast(u1, (x21 >> 51)); const x23 = (x21 & 0x7ffffffffffff); const x24 = (cast(u64, x22) + x10); const x25 = cast(u1, (x24 >> 51)); const x26 = (x24 & 0x7ffffffffffff); const x27 = (cast(u64, x25) + x13); out1[0] = x23; out1[1] = x26; out1[2] = x27; out1[3] = x16; out1[4] = x19; }
fiat-zig/src/curve25519_64.zig
const std = @import("std"); const mode = @import("builtin").mode; // Checked arithmetic is disabled in non-debug modes to avoid side channels inline fn cast(comptime DestType: type, target: anytype) DestType { if (@typeInfo(@TypeOf(target)) == .Int) { const dest = @typeInfo(DestType).Int; const source = @typeInfo(@TypeOf(target)).Int; if (dest.bits < source.bits) { return @bitCast(DestType, @truncate(std.meta.Int(source.signedness, dest.bits), target)); } else { return @bitCast(DestType, @as(std.meta.Int(source.signedness, dest.bits), target)); } } return @as(DestType, target); } // The type MontgomeryDomainFieldElement is a field element in the Montgomery domain. // Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub const MontgomeryDomainFieldElement = [7]u64; // The type NonMontgomeryDomainFieldElement is a field element NOT in the Montgomery domain. // Bounds: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub const NonMontgomeryDomainFieldElement = [7]u64; /// The function addcarryxU64 is an addition with carry. /// /// Postconditions: /// out1 = (arg1 + arg2 + arg3) mod 2^64 /// out2 = ⌊(arg1 + arg2 + arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] inline fn addcarryxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(u128, arg1) + cast(u128, arg2)) + cast(u128, arg3)); const x2 = cast(u64, (x1 & cast(u128, 0xffffffffffffffff))); const x3 = cast(u1, (x1 >> 64)); out1.* = x2; out2.* = x3; } /// The function subborrowxU64 is a subtraction with borrow. /// /// Postconditions: /// out1 = (-arg1 + arg2 + -arg3) mod 2^64 /// out2 = -⌊(-arg1 + arg2 + -arg3) / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0x1] inline fn subborrowxU64(out1: *u64, out2: *u1, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((cast(i128, arg2) - cast(i128, arg1)) - cast(i128, arg3)); const x2 = cast(i1, (x1 >> 64)); const x3 = cast(u64, (x1 & cast(i128, 0xffffffffffffffff))); out1.* = x3; out2.* = cast(u1, (cast(i2, 0x0) - cast(i2, x2))); } /// The function mulxU64 is a multiplication, returning the full double-width result. /// /// Postconditions: /// out1 = (arg1 * arg2) mod 2^64 /// out2 = ⌊arg1 * arg2 / 2^64⌋ /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [0x0 ~> 0xffffffffffffffff] inline fn mulxU64(out1: *u64, out2: *u64, arg1: u64, arg2: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u128, arg1) * cast(u128, arg2)); const x2 = cast(u64, (x1 & cast(u128, 0xffffffffffffffff))); const x3 = cast(u64, (x1 >> 64)); out1.* = x2; out2.* = x3; } /// The function cmovznzU64 is a single-word conditional move. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [0x0 ~> 0xffffffffffffffff] /// arg3: [0x0 ~> 0xffffffffffffffff] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] inline fn cmovznzU64(out1: *u64, arg1: u1, arg2: u64, arg3: u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (~(~arg1)); const x2 = cast(u64, (cast(i128, cast(i1, (cast(i2, 0x0) - cast(i2, x1)))) & cast(i128, 0xffffffffffffffff))); const x3 = ((x2 & arg3) | ((~x2) & arg2)); out1.* = x3; } /// The function mul multiplies two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn mul(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[4]); const x5 = (arg1[5]); const x6 = (arg1[6]); const x7 = (arg1[0]); var x8: u64 = undefined; var x9: u64 = undefined; mulxU64(&x8, &x9, x7, (arg2[6])); var x10: u64 = undefined; var x11: u64 = undefined; mulxU64(&x10, &x11, x7, (arg2[5])); var x12: u64 = undefined; var x13: u64 = undefined; mulxU64(&x12, &x13, x7, (arg2[4])); var x14: u64 = undefined; var x15: u64 = undefined; mulxU64(&x14, &x15, x7, (arg2[3])); var x16: u64 = undefined; var x17: u64 = undefined; mulxU64(&x16, &x17, x7, (arg2[2])); var x18: u64 = undefined; var x19: u64 = undefined; mulxU64(&x18, &x19, x7, (arg2[1])); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x7, (arg2[0])); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, 0x0, x21, x18); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, x19, x16); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, x17, x14); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x15, x12); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, x13, x10); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x11, x8); const x34 = (cast(u64, x33) + x9); var x35: u64 = undefined; var x36: u64 = undefined; mulxU64(&x35, &x36, x20, 0x2341f27177344); var x37: u64 = undefined; var x38: u64 = undefined; mulxU64(&x37, &x38, x20, 0x6cfc5fd681c52056); var x39: u64 = undefined; var x40: u64 = undefined; mulxU64(&x39, &x40, x20, 0x7bc65c783158aea3); var x41: u64 = undefined; var x42: u64 = undefined; mulxU64(&x41, &x42, x20, 0xfdc1767ae2ffffff); var x43: u64 = undefined; var x44: u64 = undefined; mulxU64(&x43, &x44, x20, 0xffffffffffffffff); var x45: u64 = undefined; var x46: u64 = undefined; mulxU64(&x45, &x46, x20, 0xffffffffffffffff); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x20, 0xffffffffffffffff); var x49: u64 = undefined; var x50: u1 = undefined; addcarryxU64(&x49, &x50, 0x0, x48, x45); var x51: u64 = undefined; var x52: u1 = undefined; addcarryxU64(&x51, &x52, x50, x46, x43); var x53: u64 = undefined; var x54: u1 = undefined; addcarryxU64(&x53, &x54, x52, x44, x41); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, x54, x42, x39); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x40, x37); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, x58, x38, x35); const x61 = (cast(u64, x60) + x36); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x20, x47); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x22, x49); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x24, x51); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x26, x53); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, x28, x55); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, x71, x30, x57); var x74: u64 = undefined; var x75: u1 = undefined; addcarryxU64(&x74, &x75, x73, x32, x59); var x76: u64 = undefined; var x77: u1 = undefined; addcarryxU64(&x76, &x77, x75, x34, x61); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x1, (arg2[6])); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x1, (arg2[5])); var x82: u64 = undefined; var x83: u64 = undefined; mulxU64(&x82, &x83, x1, (arg2[4])); var x84: u64 = undefined; var x85: u64 = undefined; mulxU64(&x84, &x85, x1, (arg2[3])); var x86: u64 = undefined; var x87: u64 = undefined; mulxU64(&x86, &x87, x1, (arg2[2])); var x88: u64 = undefined; var x89: u64 = undefined; mulxU64(&x88, &x89, x1, (arg2[1])); var x90: u64 = undefined; var x91: u64 = undefined; mulxU64(&x90, &x91, x1, (arg2[0])); var x92: u64 = undefined; var x93: u1 = undefined; addcarryxU64(&x92, &x93, 0x0, x91, x88); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, x93, x89, x86); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x87, x84); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x85, x82); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x83, x80); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, x101, x81, x78); const x104 = (cast(u64, x103) + x79); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, 0x0, x64, x90); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, x106, x66, x92); var x109: u64 = undefined; var x110: u1 = undefined; addcarryxU64(&x109, &x110, x108, x68, x94); var x111: u64 = undefined; var x112: u1 = undefined; addcarryxU64(&x111, &x112, x110, x70, x96); var x113: u64 = undefined; var x114: u1 = undefined; addcarryxU64(&x113, &x114, x112, x72, x98); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, x114, x74, x100); var x117: u64 = undefined; var x118: u1 = undefined; addcarryxU64(&x117, &x118, x116, x76, x102); var x119: u64 = undefined; var x120: u1 = undefined; addcarryxU64(&x119, &x120, x118, cast(u64, x77), x104); var x121: u64 = undefined; var x122: u64 = undefined; mulxU64(&x121, &x122, x105, 0x2341f27177344); var x123: u64 = undefined; var x124: u64 = undefined; mulxU64(&x123, &x124, x105, 0x6cfc5fd681c52056); var x125: u64 = undefined; var x126: u64 = undefined; mulxU64(&x125, &x126, x105, 0x7bc65c783158aea3); var x127: u64 = undefined; var x128: u64 = undefined; mulxU64(&x127, &x128, x105, 0xfdc1767ae2ffffff); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x105, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x105, 0xffffffffffffffff); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x105, 0xffffffffffffffff); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x130, x127); var x141: u64 = undefined; var x142: u1 = undefined; addcarryxU64(&x141, &x142, x140, x128, x125); var x143: u64 = undefined; var x144: u1 = undefined; addcarryxU64(&x143, &x144, x142, x126, x123); var x145: u64 = undefined; var x146: u1 = undefined; addcarryxU64(&x145, &x146, x144, x124, x121); const x147 = (cast(u64, x146) + x122); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, 0x0, x105, x133); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x107, x135); var x152: u64 = undefined; var x153: u1 = undefined; addcarryxU64(&x152, &x153, x151, x109, x137); var x154: u64 = undefined; var x155: u1 = undefined; addcarryxU64(&x154, &x155, x153, x111, x139); var x156: u64 = undefined; var x157: u1 = undefined; addcarryxU64(&x156, &x157, x155, x113, x141); var x158: u64 = undefined; var x159: u1 = undefined; addcarryxU64(&x158, &x159, x157, x115, x143); var x160: u64 = undefined; var x161: u1 = undefined; addcarryxU64(&x160, &x161, x159, x117, x145); var x162: u64 = undefined; var x163: u1 = undefined; addcarryxU64(&x162, &x163, x161, x119, x147); const x164 = (cast(u64, x163) + cast(u64, x120)); var x165: u64 = undefined; var x166: u64 = undefined; mulxU64(&x165, &x166, x2, (arg2[6])); var x167: u64 = undefined; var x168: u64 = undefined; mulxU64(&x167, &x168, x2, (arg2[5])); var x169: u64 = undefined; var x170: u64 = undefined; mulxU64(&x169, &x170, x2, (arg2[4])); var x171: u64 = undefined; var x172: u64 = undefined; mulxU64(&x171, &x172, x2, (arg2[3])); var x173: u64 = undefined; var x174: u64 = undefined; mulxU64(&x173, &x174, x2, (arg2[2])); var x175: u64 = undefined; var x176: u64 = undefined; mulxU64(&x175, &x176, x2, (arg2[1])); var x177: u64 = undefined; var x178: u64 = undefined; mulxU64(&x177, &x178, x2, (arg2[0])); var x179: u64 = undefined; var x180: u1 = undefined; addcarryxU64(&x179, &x180, 0x0, x178, x175); var x181: u64 = undefined; var x182: u1 = undefined; addcarryxU64(&x181, &x182, x180, x176, x173); var x183: u64 = undefined; var x184: u1 = undefined; addcarryxU64(&x183, &x184, x182, x174, x171); var x185: u64 = undefined; var x186: u1 = undefined; addcarryxU64(&x185, &x186, x184, x172, x169); var x187: u64 = undefined; var x188: u1 = undefined; addcarryxU64(&x187, &x188, x186, x170, x167); var x189: u64 = undefined; var x190: u1 = undefined; addcarryxU64(&x189, &x190, x188, x168, x165); const x191 = (cast(u64, x190) + x166); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, 0x0, x150, x177); var x194: u64 = undefined; var x195: u1 = undefined; addcarryxU64(&x194, &x195, x193, x152, x179); var x196: u64 = undefined; var x197: u1 = undefined; addcarryxU64(&x196, &x197, x195, x154, x181); var x198: u64 = undefined; var x199: u1 = undefined; addcarryxU64(&x198, &x199, x197, x156, x183); var x200: u64 = undefined; var x201: u1 = undefined; addcarryxU64(&x200, &x201, x199, x158, x185); var x202: u64 = undefined; var x203: u1 = undefined; addcarryxU64(&x202, &x203, x201, x160, x187); var x204: u64 = undefined; var x205: u1 = undefined; addcarryxU64(&x204, &x205, x203, x162, x189); var x206: u64 = undefined; var x207: u1 = undefined; addcarryxU64(&x206, &x207, x205, x164, x191); var x208: u64 = undefined; var x209: u64 = undefined; mulxU64(&x208, &x209, x192, 0x2341f27177344); var x210: u64 = undefined; var x211: u64 = undefined; mulxU64(&x210, &x211, x192, 0x6cfc5fd681c52056); var x212: u64 = undefined; var x213: u64 = undefined; mulxU64(&x212, &x213, x192, 0x7bc65c783158aea3); var x214: u64 = undefined; var x215: u64 = undefined; mulxU64(&x214, &x215, x192, 0xfdc1767ae2ffffff); var x216: u64 = undefined; var x217: u64 = undefined; mulxU64(&x216, &x217, x192, 0xffffffffffffffff); var x218: u64 = undefined; var x219: u64 = undefined; mulxU64(&x218, &x219, x192, 0xffffffffffffffff); var x220: u64 = undefined; var x221: u64 = undefined; mulxU64(&x220, &x221, x192, 0xffffffffffffffff); var x222: u64 = undefined; var x223: u1 = undefined; addcarryxU64(&x222, &x223, 0x0, x221, x218); var x224: u64 = undefined; var x225: u1 = undefined; addcarryxU64(&x224, &x225, x223, x219, x216); var x226: u64 = undefined; var x227: u1 = undefined; addcarryxU64(&x226, &x227, x225, x217, x214); var x228: u64 = undefined; var x229: u1 = undefined; addcarryxU64(&x228, &x229, x227, x215, x212); var x230: u64 = undefined; var x231: u1 = undefined; addcarryxU64(&x230, &x231, x229, x213, x210); var x232: u64 = undefined; var x233: u1 = undefined; addcarryxU64(&x232, &x233, x231, x211, x208); const x234 = (cast(u64, x233) + x209); var x235: u64 = undefined; var x236: u1 = undefined; addcarryxU64(&x235, &x236, 0x0, x192, x220); var x237: u64 = undefined; var x238: u1 = undefined; addcarryxU64(&x237, &x238, x236, x194, x222); var x239: u64 = undefined; var x240: u1 = undefined; addcarryxU64(&x239, &x240, x238, x196, x224); var x241: u64 = undefined; var x242: u1 = undefined; addcarryxU64(&x241, &x242, x240, x198, x226); var x243: u64 = undefined; var x244: u1 = undefined; addcarryxU64(&x243, &x244, x242, x200, x228); var x245: u64 = undefined; var x246: u1 = undefined; addcarryxU64(&x245, &x246, x244, x202, x230); var x247: u64 = undefined; var x248: u1 = undefined; addcarryxU64(&x247, &x248, x246, x204, x232); var x249: u64 = undefined; var x250: u1 = undefined; addcarryxU64(&x249, &x250, x248, x206, x234); const x251 = (cast(u64, x250) + cast(u64, x207)); var x252: u64 = undefined; var x253: u64 = undefined; mulxU64(&x252, &x253, x3, (arg2[6])); var x254: u64 = undefined; var x255: u64 = undefined; mulxU64(&x254, &x255, x3, (arg2[5])); var x256: u64 = undefined; var x257: u64 = undefined; mulxU64(&x256, &x257, x3, (arg2[4])); var x258: u64 = undefined; var x259: u64 = undefined; mulxU64(&x258, &x259, x3, (arg2[3])); var x260: u64 = undefined; var x261: u64 = undefined; mulxU64(&x260, &x261, x3, (arg2[2])); var x262: u64 = undefined; var x263: u64 = undefined; mulxU64(&x262, &x263, x3, (arg2[1])); var x264: u64 = undefined; var x265: u64 = undefined; mulxU64(&x264, &x265, x3, (arg2[0])); var x266: u64 = undefined; var x267: u1 = undefined; addcarryxU64(&x266, &x267, 0x0, x265, x262); var x268: u64 = undefined; var x269: u1 = undefined; addcarryxU64(&x268, &x269, x267, x263, x260); var x270: u64 = undefined; var x271: u1 = undefined; addcarryxU64(&x270, &x271, x269, x261, x258); var x272: u64 = undefined; var x273: u1 = undefined; addcarryxU64(&x272, &x273, x271, x259, x256); var x274: u64 = undefined; var x275: u1 = undefined; addcarryxU64(&x274, &x275, x273, x257, x254); var x276: u64 = undefined; var x277: u1 = undefined; addcarryxU64(&x276, &x277, x275, x255, x252); const x278 = (cast(u64, x277) + x253); var x279: u64 = undefined; var x280: u1 = undefined; addcarryxU64(&x279, &x280, 0x0, x237, x264); var x281: u64 = undefined; var x282: u1 = undefined; addcarryxU64(&x281, &x282, x280, x239, x266); var x283: u64 = undefined; var x284: u1 = undefined; addcarryxU64(&x283, &x284, x282, x241, x268); var x285: u64 = undefined; var x286: u1 = undefined; addcarryxU64(&x285, &x286, x284, x243, x270); var x287: u64 = undefined; var x288: u1 = undefined; addcarryxU64(&x287, &x288, x286, x245, x272); var x289: u64 = undefined; var x290: u1 = undefined; addcarryxU64(&x289, &x290, x288, x247, x274); var x291: u64 = undefined; var x292: u1 = undefined; addcarryxU64(&x291, &x292, x290, x249, x276); var x293: u64 = undefined; var x294: u1 = undefined; addcarryxU64(&x293, &x294, x292, x251, x278); var x295: u64 = undefined; var x296: u64 = undefined; mulxU64(&x295, &x296, x279, 0x2341f27177344); var x297: u64 = undefined; var x298: u64 = undefined; mulxU64(&x297, &x298, x279, 0x6cfc5fd681c52056); var x299: u64 = undefined; var x300: u64 = undefined; mulxU64(&x299, &x300, x279, 0x7bc65c783158aea3); var x301: u64 = undefined; var x302: u64 = undefined; mulxU64(&x301, &x302, x279, 0xfdc1767ae2ffffff); var x303: u64 = undefined; var x304: u64 = undefined; mulxU64(&x303, &x304, x279, 0xffffffffffffffff); var x305: u64 = undefined; var x306: u64 = undefined; mulxU64(&x305, &x306, x279, 0xffffffffffffffff); var x307: u64 = undefined; var x308: u64 = undefined; mulxU64(&x307, &x308, x279, 0xffffffffffffffff); var x309: u64 = undefined; var x310: u1 = undefined; addcarryxU64(&x309, &x310, 0x0, x308, x305); var x311: u64 = undefined; var x312: u1 = undefined; addcarryxU64(&x311, &x312, x310, x306, x303); var x313: u64 = undefined; var x314: u1 = undefined; addcarryxU64(&x313, &x314, x312, x304, x301); var x315: u64 = undefined; var x316: u1 = undefined; addcarryxU64(&x315, &x316, x314, x302, x299); var x317: u64 = undefined; var x318: u1 = undefined; addcarryxU64(&x317, &x318, x316, x300, x297); var x319: u64 = undefined; var x320: u1 = undefined; addcarryxU64(&x319, &x320, x318, x298, x295); const x321 = (cast(u64, x320) + x296); var x322: u64 = undefined; var x323: u1 = undefined; addcarryxU64(&x322, &x323, 0x0, x279, x307); var x324: u64 = undefined; var x325: u1 = undefined; addcarryxU64(&x324, &x325, x323, x281, x309); var x326: u64 = undefined; var x327: u1 = undefined; addcarryxU64(&x326, &x327, x325, x283, x311); var x328: u64 = undefined; var x329: u1 = undefined; addcarryxU64(&x328, &x329, x327, x285, x313); var x330: u64 = undefined; var x331: u1 = undefined; addcarryxU64(&x330, &x331, x329, x287, x315); var x332: u64 = undefined; var x333: u1 = undefined; addcarryxU64(&x332, &x333, x331, x289, x317); var x334: u64 = undefined; var x335: u1 = undefined; addcarryxU64(&x334, &x335, x333, x291, x319); var x336: u64 = undefined; var x337: u1 = undefined; addcarryxU64(&x336, &x337, x335, x293, x321); const x338 = (cast(u64, x337) + cast(u64, x294)); var x339: u64 = undefined; var x340: u64 = undefined; mulxU64(&x339, &x340, x4, (arg2[6])); var x341: u64 = undefined; var x342: u64 = undefined; mulxU64(&x341, &x342, x4, (arg2[5])); var x343: u64 = undefined; var x344: u64 = undefined; mulxU64(&x343, &x344, x4, (arg2[4])); var x345: u64 = undefined; var x346: u64 = undefined; mulxU64(&x345, &x346, x4, (arg2[3])); var x347: u64 = undefined; var x348: u64 = undefined; mulxU64(&x347, &x348, x4, (arg2[2])); var x349: u64 = undefined; var x350: u64 = undefined; mulxU64(&x349, &x350, x4, (arg2[1])); var x351: u64 = undefined; var x352: u64 = undefined; mulxU64(&x351, &x352, x4, (arg2[0])); var x353: u64 = undefined; var x354: u1 = undefined; addcarryxU64(&x353, &x354, 0x0, x352, x349); var x355: u64 = undefined; var x356: u1 = undefined; addcarryxU64(&x355, &x356, x354, x350, x347); var x357: u64 = undefined; var x358: u1 = undefined; addcarryxU64(&x357, &x358, x356, x348, x345); var x359: u64 = undefined; var x360: u1 = undefined; addcarryxU64(&x359, &x360, x358, x346, x343); var x361: u64 = undefined; var x362: u1 = undefined; addcarryxU64(&x361, &x362, x360, x344, x341); var x363: u64 = undefined; var x364: u1 = undefined; addcarryxU64(&x363, &x364, x362, x342, x339); const x365 = (cast(u64, x364) + x340); var x366: u64 = undefined; var x367: u1 = undefined; addcarryxU64(&x366, &x367, 0x0, x324, x351); var x368: u64 = undefined; var x369: u1 = undefined; addcarryxU64(&x368, &x369, x367, x326, x353); var x370: u64 = undefined; var x371: u1 = undefined; addcarryxU64(&x370, &x371, x369, x328, x355); var x372: u64 = undefined; var x373: u1 = undefined; addcarryxU64(&x372, &x373, x371, x330, x357); var x374: u64 = undefined; var x375: u1 = undefined; addcarryxU64(&x374, &x375, x373, x332, x359); var x376: u64 = undefined; var x377: u1 = undefined; addcarryxU64(&x376, &x377, x375, x334, x361); var x378: u64 = undefined; var x379: u1 = undefined; addcarryxU64(&x378, &x379, x377, x336, x363); var x380: u64 = undefined; var x381: u1 = undefined; addcarryxU64(&x380, &x381, x379, x338, x365); var x382: u64 = undefined; var x383: u64 = undefined; mulxU64(&x382, &x383, x366, 0x2341f27177344); var x384: u64 = undefined; var x385: u64 = undefined; mulxU64(&x384, &x385, x366, 0x6cfc5fd681c52056); var x386: u64 = undefined; var x387: u64 = undefined; mulxU64(&x386, &x387, x366, 0x7bc65c783158aea3); var x388: u64 = undefined; var x389: u64 = undefined; mulxU64(&x388, &x389, x366, 0xfdc1767ae2ffffff); var x390: u64 = undefined; var x391: u64 = undefined; mulxU64(&x390, &x391, x366, 0xffffffffffffffff); var x392: u64 = undefined; var x393: u64 = undefined; mulxU64(&x392, &x393, x366, 0xffffffffffffffff); var x394: u64 = undefined; var x395: u64 = undefined; mulxU64(&x394, &x395, x366, 0xffffffffffffffff); var x396: u64 = undefined; var x397: u1 = undefined; addcarryxU64(&x396, &x397, 0x0, x395, x392); var x398: u64 = undefined; var x399: u1 = undefined; addcarryxU64(&x398, &x399, x397, x393, x390); var x400: u64 = undefined; var x401: u1 = undefined; addcarryxU64(&x400, &x401, x399, x391, x388); var x402: u64 = undefined; var x403: u1 = undefined; addcarryxU64(&x402, &x403, x401, x389, x386); var x404: u64 = undefined; var x405: u1 = undefined; addcarryxU64(&x404, &x405, x403, x387, x384); var x406: u64 = undefined; var x407: u1 = undefined; addcarryxU64(&x406, &x407, x405, x385, x382); const x408 = (cast(u64, x407) + x383); var x409: u64 = undefined; var x410: u1 = undefined; addcarryxU64(&x409, &x410, 0x0, x366, x394); var x411: u64 = undefined; var x412: u1 = undefined; addcarryxU64(&x411, &x412, x410, x368, x396); var x413: u64 = undefined; var x414: u1 = undefined; addcarryxU64(&x413, &x414, x412, x370, x398); var x415: u64 = undefined; var x416: u1 = undefined; addcarryxU64(&x415, &x416, x414, x372, x400); var x417: u64 = undefined; var x418: u1 = undefined; addcarryxU64(&x417, &x418, x416, x374, x402); var x419: u64 = undefined; var x420: u1 = undefined; addcarryxU64(&x419, &x420, x418, x376, x404); var x421: u64 = undefined; var x422: u1 = undefined; addcarryxU64(&x421, &x422, x420, x378, x406); var x423: u64 = undefined; var x424: u1 = undefined; addcarryxU64(&x423, &x424, x422, x380, x408); const x425 = (cast(u64, x424) + cast(u64, x381)); var x426: u64 = undefined; var x427: u64 = undefined; mulxU64(&x426, &x427, x5, (arg2[6])); var x428: u64 = undefined; var x429: u64 = undefined; mulxU64(&x428, &x429, x5, (arg2[5])); var x430: u64 = undefined; var x431: u64 = undefined; mulxU64(&x430, &x431, x5, (arg2[4])); var x432: u64 = undefined; var x433: u64 = undefined; mulxU64(&x432, &x433, x5, (arg2[3])); var x434: u64 = undefined; var x435: u64 = undefined; mulxU64(&x434, &x435, x5, (arg2[2])); var x436: u64 = undefined; var x437: u64 = undefined; mulxU64(&x436, &x437, x5, (arg2[1])); var x438: u64 = undefined; var x439: u64 = undefined; mulxU64(&x438, &x439, x5, (arg2[0])); var x440: u64 = undefined; var x441: u1 = undefined; addcarryxU64(&x440, &x441, 0x0, x439, x436); var x442: u64 = undefined; var x443: u1 = undefined; addcarryxU64(&x442, &x443, x441, x437, x434); var x444: u64 = undefined; var x445: u1 = undefined; addcarryxU64(&x444, &x445, x443, x435, x432); var x446: u64 = undefined; var x447: u1 = undefined; addcarryxU64(&x446, &x447, x445, x433, x430); var x448: u64 = undefined; var x449: u1 = undefined; addcarryxU64(&x448, &x449, x447, x431, x428); var x450: u64 = undefined; var x451: u1 = undefined; addcarryxU64(&x450, &x451, x449, x429, x426); const x452 = (cast(u64, x451) + x427); var x453: u64 = undefined; var x454: u1 = undefined; addcarryxU64(&x453, &x454, 0x0, x411, x438); var x455: u64 = undefined; var x456: u1 = undefined; addcarryxU64(&x455, &x456, x454, x413, x440); var x457: u64 = undefined; var x458: u1 = undefined; addcarryxU64(&x457, &x458, x456, x415, x442); var x459: u64 = undefined; var x460: u1 = undefined; addcarryxU64(&x459, &x460, x458, x417, x444); var x461: u64 = undefined; var x462: u1 = undefined; addcarryxU64(&x461, &x462, x460, x419, x446); var x463: u64 = undefined; var x464: u1 = undefined; addcarryxU64(&x463, &x464, x462, x421, x448); var x465: u64 = undefined; var x466: u1 = undefined; addcarryxU64(&x465, &x466, x464, x423, x450); var x467: u64 = undefined; var x468: u1 = undefined; addcarryxU64(&x467, &x468, x466, x425, x452); var x469: u64 = undefined; var x470: u64 = undefined; mulxU64(&x469, &x470, x453, 0x2341f27177344); var x471: u64 = undefined; var x472: u64 = undefined; mulxU64(&x471, &x472, x453, 0x6cfc5fd681c52056); var x473: u64 = undefined; var x474: u64 = undefined; mulxU64(&x473, &x474, x453, 0x7bc65c783158aea3); var x475: u64 = undefined; var x476: u64 = undefined; mulxU64(&x475, &x476, x453, 0xfdc1767ae2ffffff); var x477: u64 = undefined; var x478: u64 = undefined; mulxU64(&x477, &x478, x453, 0xffffffffffffffff); var x479: u64 = undefined; var x480: u64 = undefined; mulxU64(&x479, &x480, x453, 0xffffffffffffffff); var x481: u64 = undefined; var x482: u64 = undefined; mulxU64(&x481, &x482, x453, 0xffffffffffffffff); var x483: u64 = undefined; var x484: u1 = undefined; addcarryxU64(&x483, &x484, 0x0, x482, x479); var x485: u64 = undefined; var x486: u1 = undefined; addcarryxU64(&x485, &x486, x484, x480, x477); var x487: u64 = undefined; var x488: u1 = undefined; addcarryxU64(&x487, &x488, x486, x478, x475); var x489: u64 = undefined; var x490: u1 = undefined; addcarryxU64(&x489, &x490, x488, x476, x473); var x491: u64 = undefined; var x492: u1 = undefined; addcarryxU64(&x491, &x492, x490, x474, x471); var x493: u64 = undefined; var x494: u1 = undefined; addcarryxU64(&x493, &x494, x492, x472, x469); const x495 = (cast(u64, x494) + x470); var x496: u64 = undefined; var x497: u1 = undefined; addcarryxU64(&x496, &x497, 0x0, x453, x481); var x498: u64 = undefined; var x499: u1 = undefined; addcarryxU64(&x498, &x499, x497, x455, x483); var x500: u64 = undefined; var x501: u1 = undefined; addcarryxU64(&x500, &x501, x499, x457, x485); var x502: u64 = undefined; var x503: u1 = undefined; addcarryxU64(&x502, &x503, x501, x459, x487); var x504: u64 = undefined; var x505: u1 = undefined; addcarryxU64(&x504, &x505, x503, x461, x489); var x506: u64 = undefined; var x507: u1 = undefined; addcarryxU64(&x506, &x507, x505, x463, x491); var x508: u64 = undefined; var x509: u1 = undefined; addcarryxU64(&x508, &x509, x507, x465, x493); var x510: u64 = undefined; var x511: u1 = undefined; addcarryxU64(&x510, &x511, x509, x467, x495); const x512 = (cast(u64, x511) + cast(u64, x468)); var x513: u64 = undefined; var x514: u64 = undefined; mulxU64(&x513, &x514, x6, (arg2[6])); var x515: u64 = undefined; var x516: u64 = undefined; mulxU64(&x515, &x516, x6, (arg2[5])); var x517: u64 = undefined; var x518: u64 = undefined; mulxU64(&x517, &x518, x6, (arg2[4])); var x519: u64 = undefined; var x520: u64 = undefined; mulxU64(&x519, &x520, x6, (arg2[3])); var x521: u64 = undefined; var x522: u64 = undefined; mulxU64(&x521, &x522, x6, (arg2[2])); var x523: u64 = undefined; var x524: u64 = undefined; mulxU64(&x523, &x524, x6, (arg2[1])); var x525: u64 = undefined; var x526: u64 = undefined; mulxU64(&x525, &x526, x6, (arg2[0])); var x527: u64 = undefined; var x528: u1 = undefined; addcarryxU64(&x527, &x528, 0x0, x526, x523); var x529: u64 = undefined; var x530: u1 = undefined; addcarryxU64(&x529, &x530, x528, x524, x521); var x531: u64 = undefined; var x532: u1 = undefined; addcarryxU64(&x531, &x532, x530, x522, x519); var x533: u64 = undefined; var x534: u1 = undefined; addcarryxU64(&x533, &x534, x532, x520, x517); var x535: u64 = undefined; var x536: u1 = undefined; addcarryxU64(&x535, &x536, x534, x518, x515); var x537: u64 = undefined; var x538: u1 = undefined; addcarryxU64(&x537, &x538, x536, x516, x513); const x539 = (cast(u64, x538) + x514); var x540: u64 = undefined; var x541: u1 = undefined; addcarryxU64(&x540, &x541, 0x0, x498, x525); var x542: u64 = undefined; var x543: u1 = undefined; addcarryxU64(&x542, &x543, x541, x500, x527); var x544: u64 = undefined; var x545: u1 = undefined; addcarryxU64(&x544, &x545, x543, x502, x529); var x546: u64 = undefined; var x547: u1 = undefined; addcarryxU64(&x546, &x547, x545, x504, x531); var x548: u64 = undefined; var x549: u1 = undefined; addcarryxU64(&x548, &x549, x547, x506, x533); var x550: u64 = undefined; var x551: u1 = undefined; addcarryxU64(&x550, &x551, x549, x508, x535); var x552: u64 = undefined; var x553: u1 = undefined; addcarryxU64(&x552, &x553, x551, x510, x537); var x554: u64 = undefined; var x555: u1 = undefined; addcarryxU64(&x554, &x555, x553, x512, x539); var x556: u64 = undefined; var x557: u64 = undefined; mulxU64(&x556, &x557, x540, 0x2341f27177344); var x558: u64 = undefined; var x559: u64 = undefined; mulxU64(&x558, &x559, x540, 0x6cfc5fd681c52056); var x560: u64 = undefined; var x561: u64 = undefined; mulxU64(&x560, &x561, x540, 0x7bc65c783158aea3); var x562: u64 = undefined; var x563: u64 = undefined; mulxU64(&x562, &x563, x540, 0xfdc1767ae2ffffff); var x564: u64 = undefined; var x565: u64 = undefined; mulxU64(&x564, &x565, x540, 0xffffffffffffffff); var x566: u64 = undefined; var x567: u64 = undefined; mulxU64(&x566, &x567, x540, 0xffffffffffffffff); var x568: u64 = undefined; var x569: u64 = undefined; mulxU64(&x568, &x569, x540, 0xffffffffffffffff); var x570: u64 = undefined; var x571: u1 = undefined; addcarryxU64(&x570, &x571, 0x0, x569, x566); var x572: u64 = undefined; var x573: u1 = undefined; addcarryxU64(&x572, &x573, x571, x567, x564); var x574: u64 = undefined; var x575: u1 = undefined; addcarryxU64(&x574, &x575, x573, x565, x562); var x576: u64 = undefined; var x577: u1 = undefined; addcarryxU64(&x576, &x577, x575, x563, x560); var x578: u64 = undefined; var x579: u1 = undefined; addcarryxU64(&x578, &x579, x577, x561, x558); var x580: u64 = undefined; var x581: u1 = undefined; addcarryxU64(&x580, &x581, x579, x559, x556); const x582 = (cast(u64, x581) + x557); var x583: u64 = undefined; var x584: u1 = undefined; addcarryxU64(&x583, &x584, 0x0, x540, x568); var x585: u64 = undefined; var x586: u1 = undefined; addcarryxU64(&x585, &x586, x584, x542, x570); var x587: u64 = undefined; var x588: u1 = undefined; addcarryxU64(&x587, &x588, x586, x544, x572); var x589: u64 = undefined; var x590: u1 = undefined; addcarryxU64(&x589, &x590, x588, x546, x574); var x591: u64 = undefined; var x592: u1 = undefined; addcarryxU64(&x591, &x592, x590, x548, x576); var x593: u64 = undefined; var x594: u1 = undefined; addcarryxU64(&x593, &x594, x592, x550, x578); var x595: u64 = undefined; var x596: u1 = undefined; addcarryxU64(&x595, &x596, x594, x552, x580); var x597: u64 = undefined; var x598: u1 = undefined; addcarryxU64(&x597, &x598, x596, x554, x582); const x599 = (cast(u64, x598) + cast(u64, x555)); var x600: u64 = undefined; var x601: u1 = undefined; subborrowxU64(&x600, &x601, 0x0, x585, 0xffffffffffffffff); var x602: u64 = undefined; var x603: u1 = undefined; subborrowxU64(&x602, &x603, x601, x587, 0xffffffffffffffff); var x604: u64 = undefined; var x605: u1 = undefined; subborrowxU64(&x604, &x605, x603, x589, 0xffffffffffffffff); var x606: u64 = undefined; var x607: u1 = undefined; subborrowxU64(&x606, &x607, x605, x591, 0xfdc1767ae2ffffff); var x608: u64 = undefined; var x609: u1 = undefined; subborrowxU64(&x608, &x609, x607, x593, 0x7bc65c783158aea3); var x610: u64 = undefined; var x611: u1 = undefined; subborrowxU64(&x610, &x611, x609, x595, 0x6cfc5fd681c52056); var x612: u64 = undefined; var x613: u1 = undefined; subborrowxU64(&x612, &x613, x611, x597, 0x2341f27177344); var x614: u64 = undefined; var x615: u1 = undefined; subborrowxU64(&x614, &x615, x613, x599, cast(u64, 0x0)); var x616: u64 = undefined; cmovznzU64(&x616, x615, x600, x585); var x617: u64 = undefined; cmovznzU64(&x617, x615, x602, x587); var x618: u64 = undefined; cmovznzU64(&x618, x615, x604, x589); var x619: u64 = undefined; cmovznzU64(&x619, x615, x606, x591); var x620: u64 = undefined; cmovznzU64(&x620, x615, x608, x593); var x621: u64 = undefined; cmovznzU64(&x621, x615, x610, x595); var x622: u64 = undefined; cmovznzU64(&x622, x615, x612, x597); out1[0] = x616; out1[1] = x617; out1[2] = x618; out1[3] = x619; out1[4] = x620; out1[5] = x621; out1[6] = x622; } /// The function square squares a field element in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) * eval (from_montgomery arg1)) mod m /// 0 ≤ eval out1 < m /// pub fn square(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[4]); const x5 = (arg1[5]); const x6 = (arg1[6]); const x7 = (arg1[0]); var x8: u64 = undefined; var x9: u64 = undefined; mulxU64(&x8, &x9, x7, (arg1[6])); var x10: u64 = undefined; var x11: u64 = undefined; mulxU64(&x10, &x11, x7, (arg1[5])); var x12: u64 = undefined; var x13: u64 = undefined; mulxU64(&x12, &x13, x7, (arg1[4])); var x14: u64 = undefined; var x15: u64 = undefined; mulxU64(&x14, &x15, x7, (arg1[3])); var x16: u64 = undefined; var x17: u64 = undefined; mulxU64(&x16, &x17, x7, (arg1[2])); var x18: u64 = undefined; var x19: u64 = undefined; mulxU64(&x18, &x19, x7, (arg1[1])); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x7, (arg1[0])); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, 0x0, x21, x18); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, x19, x16); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, x17, x14); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x15, x12); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, x13, x10); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x11, x8); const x34 = (cast(u64, x33) + x9); var x35: u64 = undefined; var x36: u64 = undefined; mulxU64(&x35, &x36, x20, 0x2341f27177344); var x37: u64 = undefined; var x38: u64 = undefined; mulxU64(&x37, &x38, x20, 0x6cfc5fd681c52056); var x39: u64 = undefined; var x40: u64 = undefined; mulxU64(&x39, &x40, x20, 0x7bc65c783158aea3); var x41: u64 = undefined; var x42: u64 = undefined; mulxU64(&x41, &x42, x20, 0xfdc1767ae2ffffff); var x43: u64 = undefined; var x44: u64 = undefined; mulxU64(&x43, &x44, x20, 0xffffffffffffffff); var x45: u64 = undefined; var x46: u64 = undefined; mulxU64(&x45, &x46, x20, 0xffffffffffffffff); var x47: u64 = undefined; var x48: u64 = undefined; mulxU64(&x47, &x48, x20, 0xffffffffffffffff); var x49: u64 = undefined; var x50: u1 = undefined; addcarryxU64(&x49, &x50, 0x0, x48, x45); var x51: u64 = undefined; var x52: u1 = undefined; addcarryxU64(&x51, &x52, x50, x46, x43); var x53: u64 = undefined; var x54: u1 = undefined; addcarryxU64(&x53, &x54, x52, x44, x41); var x55: u64 = undefined; var x56: u1 = undefined; addcarryxU64(&x55, &x56, x54, x42, x39); var x57: u64 = undefined; var x58: u1 = undefined; addcarryxU64(&x57, &x58, x56, x40, x37); var x59: u64 = undefined; var x60: u1 = undefined; addcarryxU64(&x59, &x60, x58, x38, x35); const x61 = (cast(u64, x60) + x36); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, 0x0, x20, x47); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x22, x49); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x24, x51); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x26, x53); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, x28, x55); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, x71, x30, x57); var x74: u64 = undefined; var x75: u1 = undefined; addcarryxU64(&x74, &x75, x73, x32, x59); var x76: u64 = undefined; var x77: u1 = undefined; addcarryxU64(&x76, &x77, x75, x34, x61); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x1, (arg1[6])); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x1, (arg1[5])); var x82: u64 = undefined; var x83: u64 = undefined; mulxU64(&x82, &x83, x1, (arg1[4])); var x84: u64 = undefined; var x85: u64 = undefined; mulxU64(&x84, &x85, x1, (arg1[3])); var x86: u64 = undefined; var x87: u64 = undefined; mulxU64(&x86, &x87, x1, (arg1[2])); var x88: u64 = undefined; var x89: u64 = undefined; mulxU64(&x88, &x89, x1, (arg1[1])); var x90: u64 = undefined; var x91: u64 = undefined; mulxU64(&x90, &x91, x1, (arg1[0])); var x92: u64 = undefined; var x93: u1 = undefined; addcarryxU64(&x92, &x93, 0x0, x91, x88); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, x93, x89, x86); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x87, x84); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x85, x82); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x83, x80); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, x101, x81, x78); const x104 = (cast(u64, x103) + x79); var x105: u64 = undefined; var x106: u1 = undefined; addcarryxU64(&x105, &x106, 0x0, x64, x90); var x107: u64 = undefined; var x108: u1 = undefined; addcarryxU64(&x107, &x108, x106, x66, x92); var x109: u64 = undefined; var x110: u1 = undefined; addcarryxU64(&x109, &x110, x108, x68, x94); var x111: u64 = undefined; var x112: u1 = undefined; addcarryxU64(&x111, &x112, x110, x70, x96); var x113: u64 = undefined; var x114: u1 = undefined; addcarryxU64(&x113, &x114, x112, x72, x98); var x115: u64 = undefined; var x116: u1 = undefined; addcarryxU64(&x115, &x116, x114, x74, x100); var x117: u64 = undefined; var x118: u1 = undefined; addcarryxU64(&x117, &x118, x116, x76, x102); var x119: u64 = undefined; var x120: u1 = undefined; addcarryxU64(&x119, &x120, x118, cast(u64, x77), x104); var x121: u64 = undefined; var x122: u64 = undefined; mulxU64(&x121, &x122, x105, 0x2341f27177344); var x123: u64 = undefined; var x124: u64 = undefined; mulxU64(&x123, &x124, x105, 0x6cfc5fd681c52056); var x125: u64 = undefined; var x126: u64 = undefined; mulxU64(&x125, &x126, x105, 0x7bc65c783158aea3); var x127: u64 = undefined; var x128: u64 = undefined; mulxU64(&x127, &x128, x105, 0xfdc1767ae2ffffff); var x129: u64 = undefined; var x130: u64 = undefined; mulxU64(&x129, &x130, x105, 0xffffffffffffffff); var x131: u64 = undefined; var x132: u64 = undefined; mulxU64(&x131, &x132, x105, 0xffffffffffffffff); var x133: u64 = undefined; var x134: u64 = undefined; mulxU64(&x133, &x134, x105, 0xffffffffffffffff); var x135: u64 = undefined; var x136: u1 = undefined; addcarryxU64(&x135, &x136, 0x0, x134, x131); var x137: u64 = undefined; var x138: u1 = undefined; addcarryxU64(&x137, &x138, x136, x132, x129); var x139: u64 = undefined; var x140: u1 = undefined; addcarryxU64(&x139, &x140, x138, x130, x127); var x141: u64 = undefined; var x142: u1 = undefined; addcarryxU64(&x141, &x142, x140, x128, x125); var x143: u64 = undefined; var x144: u1 = undefined; addcarryxU64(&x143, &x144, x142, x126, x123); var x145: u64 = undefined; var x146: u1 = undefined; addcarryxU64(&x145, &x146, x144, x124, x121); const x147 = (cast(u64, x146) + x122); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, 0x0, x105, x133); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x107, x135); var x152: u64 = undefined; var x153: u1 = undefined; addcarryxU64(&x152, &x153, x151, x109, x137); var x154: u64 = undefined; var x155: u1 = undefined; addcarryxU64(&x154, &x155, x153, x111, x139); var x156: u64 = undefined; var x157: u1 = undefined; addcarryxU64(&x156, &x157, x155, x113, x141); var x158: u64 = undefined; var x159: u1 = undefined; addcarryxU64(&x158, &x159, x157, x115, x143); var x160: u64 = undefined; var x161: u1 = undefined; addcarryxU64(&x160, &x161, x159, x117, x145); var x162: u64 = undefined; var x163: u1 = undefined; addcarryxU64(&x162, &x163, x161, x119, x147); const x164 = (cast(u64, x163) + cast(u64, x120)); var x165: u64 = undefined; var x166: u64 = undefined; mulxU64(&x165, &x166, x2, (arg1[6])); var x167: u64 = undefined; var x168: u64 = undefined; mulxU64(&x167, &x168, x2, (arg1[5])); var x169: u64 = undefined; var x170: u64 = undefined; mulxU64(&x169, &x170, x2, (arg1[4])); var x171: u64 = undefined; var x172: u64 = undefined; mulxU64(&x171, &x172, x2, (arg1[3])); var x173: u64 = undefined; var x174: u64 = undefined; mulxU64(&x173, &x174, x2, (arg1[2])); var x175: u64 = undefined; var x176: u64 = undefined; mulxU64(&x175, &x176, x2, (arg1[1])); var x177: u64 = undefined; var x178: u64 = undefined; mulxU64(&x177, &x178, x2, (arg1[0])); var x179: u64 = undefined; var x180: u1 = undefined; addcarryxU64(&x179, &x180, 0x0, x178, x175); var x181: u64 = undefined; var x182: u1 = undefined; addcarryxU64(&x181, &x182, x180, x176, x173); var x183: u64 = undefined; var x184: u1 = undefined; addcarryxU64(&x183, &x184, x182, x174, x171); var x185: u64 = undefined; var x186: u1 = undefined; addcarryxU64(&x185, &x186, x184, x172, x169); var x187: u64 = undefined; var x188: u1 = undefined; addcarryxU64(&x187, &x188, x186, x170, x167); var x189: u64 = undefined; var x190: u1 = undefined; addcarryxU64(&x189, &x190, x188, x168, x165); const x191 = (cast(u64, x190) + x166); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, 0x0, x150, x177); var x194: u64 = undefined; var x195: u1 = undefined; addcarryxU64(&x194, &x195, x193, x152, x179); var x196: u64 = undefined; var x197: u1 = undefined; addcarryxU64(&x196, &x197, x195, x154, x181); var x198: u64 = undefined; var x199: u1 = undefined; addcarryxU64(&x198, &x199, x197, x156, x183); var x200: u64 = undefined; var x201: u1 = undefined; addcarryxU64(&x200, &x201, x199, x158, x185); var x202: u64 = undefined; var x203: u1 = undefined; addcarryxU64(&x202, &x203, x201, x160, x187); var x204: u64 = undefined; var x205: u1 = undefined; addcarryxU64(&x204, &x205, x203, x162, x189); var x206: u64 = undefined; var x207: u1 = undefined; addcarryxU64(&x206, &x207, x205, x164, x191); var x208: u64 = undefined; var x209: u64 = undefined; mulxU64(&x208, &x209, x192, 0x2341f27177344); var x210: u64 = undefined; var x211: u64 = undefined; mulxU64(&x210, &x211, x192, 0x6cfc5fd681c52056); var x212: u64 = undefined; var x213: u64 = undefined; mulxU64(&x212, &x213, x192, 0x7bc65c783158aea3); var x214: u64 = undefined; var x215: u64 = undefined; mulxU64(&x214, &x215, x192, 0xfdc1767ae2ffffff); var x216: u64 = undefined; var x217: u64 = undefined; mulxU64(&x216, &x217, x192, 0xffffffffffffffff); var x218: u64 = undefined; var x219: u64 = undefined; mulxU64(&x218, &x219, x192, 0xffffffffffffffff); var x220: u64 = undefined; var x221: u64 = undefined; mulxU64(&x220, &x221, x192, 0xffffffffffffffff); var x222: u64 = undefined; var x223: u1 = undefined; addcarryxU64(&x222, &x223, 0x0, x221, x218); var x224: u64 = undefined; var x225: u1 = undefined; addcarryxU64(&x224, &x225, x223, x219, x216); var x226: u64 = undefined; var x227: u1 = undefined; addcarryxU64(&x226, &x227, x225, x217, x214); var x228: u64 = undefined; var x229: u1 = undefined; addcarryxU64(&x228, &x229, x227, x215, x212); var x230: u64 = undefined; var x231: u1 = undefined; addcarryxU64(&x230, &x231, x229, x213, x210); var x232: u64 = undefined; var x233: u1 = undefined; addcarryxU64(&x232, &x233, x231, x211, x208); const x234 = (cast(u64, x233) + x209); var x235: u64 = undefined; var x236: u1 = undefined; addcarryxU64(&x235, &x236, 0x0, x192, x220); var x237: u64 = undefined; var x238: u1 = undefined; addcarryxU64(&x237, &x238, x236, x194, x222); var x239: u64 = undefined; var x240: u1 = undefined; addcarryxU64(&x239, &x240, x238, x196, x224); var x241: u64 = undefined; var x242: u1 = undefined; addcarryxU64(&x241, &x242, x240, x198, x226); var x243: u64 = undefined; var x244: u1 = undefined; addcarryxU64(&x243, &x244, x242, x200, x228); var x245: u64 = undefined; var x246: u1 = undefined; addcarryxU64(&x245, &x246, x244, x202, x230); var x247: u64 = undefined; var x248: u1 = undefined; addcarryxU64(&x247, &x248, x246, x204, x232); var x249: u64 = undefined; var x250: u1 = undefined; addcarryxU64(&x249, &x250, x248, x206, x234); const x251 = (cast(u64, x250) + cast(u64, x207)); var x252: u64 = undefined; var x253: u64 = undefined; mulxU64(&x252, &x253, x3, (arg1[6])); var x254: u64 = undefined; var x255: u64 = undefined; mulxU64(&x254, &x255, x3, (arg1[5])); var x256: u64 = undefined; var x257: u64 = undefined; mulxU64(&x256, &x257, x3, (arg1[4])); var x258: u64 = undefined; var x259: u64 = undefined; mulxU64(&x258, &x259, x3, (arg1[3])); var x260: u64 = undefined; var x261: u64 = undefined; mulxU64(&x260, &x261, x3, (arg1[2])); var x262: u64 = undefined; var x263: u64 = undefined; mulxU64(&x262, &x263, x3, (arg1[1])); var x264: u64 = undefined; var x265: u64 = undefined; mulxU64(&x264, &x265, x3, (arg1[0])); var x266: u64 = undefined; var x267: u1 = undefined; addcarryxU64(&x266, &x267, 0x0, x265, x262); var x268: u64 = undefined; var x269: u1 = undefined; addcarryxU64(&x268, &x269, x267, x263, x260); var x270: u64 = undefined; var x271: u1 = undefined; addcarryxU64(&x270, &x271, x269, x261, x258); var x272: u64 = undefined; var x273: u1 = undefined; addcarryxU64(&x272, &x273, x271, x259, x256); var x274: u64 = undefined; var x275: u1 = undefined; addcarryxU64(&x274, &x275, x273, x257, x254); var x276: u64 = undefined; var x277: u1 = undefined; addcarryxU64(&x276, &x277, x275, x255, x252); const x278 = (cast(u64, x277) + x253); var x279: u64 = undefined; var x280: u1 = undefined; addcarryxU64(&x279, &x280, 0x0, x237, x264); var x281: u64 = undefined; var x282: u1 = undefined; addcarryxU64(&x281, &x282, x280, x239, x266); var x283: u64 = undefined; var x284: u1 = undefined; addcarryxU64(&x283, &x284, x282, x241, x268); var x285: u64 = undefined; var x286: u1 = undefined; addcarryxU64(&x285, &x286, x284, x243, x270); var x287: u64 = undefined; var x288: u1 = undefined; addcarryxU64(&x287, &x288, x286, x245, x272); var x289: u64 = undefined; var x290: u1 = undefined; addcarryxU64(&x289, &x290, x288, x247, x274); var x291: u64 = undefined; var x292: u1 = undefined; addcarryxU64(&x291, &x292, x290, x249, x276); var x293: u64 = undefined; var x294: u1 = undefined; addcarryxU64(&x293, &x294, x292, x251, x278); var x295: u64 = undefined; var x296: u64 = undefined; mulxU64(&x295, &x296, x279, 0x2341f27177344); var x297: u64 = undefined; var x298: u64 = undefined; mulxU64(&x297, &x298, x279, 0x6cfc5fd681c52056); var x299: u64 = undefined; var x300: u64 = undefined; mulxU64(&x299, &x300, x279, 0x7bc65c783158aea3); var x301: u64 = undefined; var x302: u64 = undefined; mulxU64(&x301, &x302, x279, 0xfdc1767ae2ffffff); var x303: u64 = undefined; var x304: u64 = undefined; mulxU64(&x303, &x304, x279, 0xffffffffffffffff); var x305: u64 = undefined; var x306: u64 = undefined; mulxU64(&x305, &x306, x279, 0xffffffffffffffff); var x307: u64 = undefined; var x308: u64 = undefined; mulxU64(&x307, &x308, x279, 0xffffffffffffffff); var x309: u64 = undefined; var x310: u1 = undefined; addcarryxU64(&x309, &x310, 0x0, x308, x305); var x311: u64 = undefined; var x312: u1 = undefined; addcarryxU64(&x311, &x312, x310, x306, x303); var x313: u64 = undefined; var x314: u1 = undefined; addcarryxU64(&x313, &x314, x312, x304, x301); var x315: u64 = undefined; var x316: u1 = undefined; addcarryxU64(&x315, &x316, x314, x302, x299); var x317: u64 = undefined; var x318: u1 = undefined; addcarryxU64(&x317, &x318, x316, x300, x297); var x319: u64 = undefined; var x320: u1 = undefined; addcarryxU64(&x319, &x320, x318, x298, x295); const x321 = (cast(u64, x320) + x296); var x322: u64 = undefined; var x323: u1 = undefined; addcarryxU64(&x322, &x323, 0x0, x279, x307); var x324: u64 = undefined; var x325: u1 = undefined; addcarryxU64(&x324, &x325, x323, x281, x309); var x326: u64 = undefined; var x327: u1 = undefined; addcarryxU64(&x326, &x327, x325, x283, x311); var x328: u64 = undefined; var x329: u1 = undefined; addcarryxU64(&x328, &x329, x327, x285, x313); var x330: u64 = undefined; var x331: u1 = undefined; addcarryxU64(&x330, &x331, x329, x287, x315); var x332: u64 = undefined; var x333: u1 = undefined; addcarryxU64(&x332, &x333, x331, x289, x317); var x334: u64 = undefined; var x335: u1 = undefined; addcarryxU64(&x334, &x335, x333, x291, x319); var x336: u64 = undefined; var x337: u1 = undefined; addcarryxU64(&x336, &x337, x335, x293, x321); const x338 = (cast(u64, x337) + cast(u64, x294)); var x339: u64 = undefined; var x340: u64 = undefined; mulxU64(&x339, &x340, x4, (arg1[6])); var x341: u64 = undefined; var x342: u64 = undefined; mulxU64(&x341, &x342, x4, (arg1[5])); var x343: u64 = undefined; var x344: u64 = undefined; mulxU64(&x343, &x344, x4, (arg1[4])); var x345: u64 = undefined; var x346: u64 = undefined; mulxU64(&x345, &x346, x4, (arg1[3])); var x347: u64 = undefined; var x348: u64 = undefined; mulxU64(&x347, &x348, x4, (arg1[2])); var x349: u64 = undefined; var x350: u64 = undefined; mulxU64(&x349, &x350, x4, (arg1[1])); var x351: u64 = undefined; var x352: u64 = undefined; mulxU64(&x351, &x352, x4, (arg1[0])); var x353: u64 = undefined; var x354: u1 = undefined; addcarryxU64(&x353, &x354, 0x0, x352, x349); var x355: u64 = undefined; var x356: u1 = undefined; addcarryxU64(&x355, &x356, x354, x350, x347); var x357: u64 = undefined; var x358: u1 = undefined; addcarryxU64(&x357, &x358, x356, x348, x345); var x359: u64 = undefined; var x360: u1 = undefined; addcarryxU64(&x359, &x360, x358, x346, x343); var x361: u64 = undefined; var x362: u1 = undefined; addcarryxU64(&x361, &x362, x360, x344, x341); var x363: u64 = undefined; var x364: u1 = undefined; addcarryxU64(&x363, &x364, x362, x342, x339); const x365 = (cast(u64, x364) + x340); var x366: u64 = undefined; var x367: u1 = undefined; addcarryxU64(&x366, &x367, 0x0, x324, x351); var x368: u64 = undefined; var x369: u1 = undefined; addcarryxU64(&x368, &x369, x367, x326, x353); var x370: u64 = undefined; var x371: u1 = undefined; addcarryxU64(&x370, &x371, x369, x328, x355); var x372: u64 = undefined; var x373: u1 = undefined; addcarryxU64(&x372, &x373, x371, x330, x357); var x374: u64 = undefined; var x375: u1 = undefined; addcarryxU64(&x374, &x375, x373, x332, x359); var x376: u64 = undefined; var x377: u1 = undefined; addcarryxU64(&x376, &x377, x375, x334, x361); var x378: u64 = undefined; var x379: u1 = undefined; addcarryxU64(&x378, &x379, x377, x336, x363); var x380: u64 = undefined; var x381: u1 = undefined; addcarryxU64(&x380, &x381, x379, x338, x365); var x382: u64 = undefined; var x383: u64 = undefined; mulxU64(&x382, &x383, x366, 0x2341f27177344); var x384: u64 = undefined; var x385: u64 = undefined; mulxU64(&x384, &x385, x366, 0x6cfc5fd681c52056); var x386: u64 = undefined; var x387: u64 = undefined; mulxU64(&x386, &x387, x366, 0x7bc65c783158aea3); var x388: u64 = undefined; var x389: u64 = undefined; mulxU64(&x388, &x389, x366, 0xfdc1767ae2ffffff); var x390: u64 = undefined; var x391: u64 = undefined; mulxU64(&x390, &x391, x366, 0xffffffffffffffff); var x392: u64 = undefined; var x393: u64 = undefined; mulxU64(&x392, &x393, x366, 0xffffffffffffffff); var x394: u64 = undefined; var x395: u64 = undefined; mulxU64(&x394, &x395, x366, 0xffffffffffffffff); var x396: u64 = undefined; var x397: u1 = undefined; addcarryxU64(&x396, &x397, 0x0, x395, x392); var x398: u64 = undefined; var x399: u1 = undefined; addcarryxU64(&x398, &x399, x397, x393, x390); var x400: u64 = undefined; var x401: u1 = undefined; addcarryxU64(&x400, &x401, x399, x391, x388); var x402: u64 = undefined; var x403: u1 = undefined; addcarryxU64(&x402, &x403, x401, x389, x386); var x404: u64 = undefined; var x405: u1 = undefined; addcarryxU64(&x404, &x405, x403, x387, x384); var x406: u64 = undefined; var x407: u1 = undefined; addcarryxU64(&x406, &x407, x405, x385, x382); const x408 = (cast(u64, x407) + x383); var x409: u64 = undefined; var x410: u1 = undefined; addcarryxU64(&x409, &x410, 0x0, x366, x394); var x411: u64 = undefined; var x412: u1 = undefined; addcarryxU64(&x411, &x412, x410, x368, x396); var x413: u64 = undefined; var x414: u1 = undefined; addcarryxU64(&x413, &x414, x412, x370, x398); var x415: u64 = undefined; var x416: u1 = undefined; addcarryxU64(&x415, &x416, x414, x372, x400); var x417: u64 = undefined; var x418: u1 = undefined; addcarryxU64(&x417, &x418, x416, x374, x402); var x419: u64 = undefined; var x420: u1 = undefined; addcarryxU64(&x419, &x420, x418, x376, x404); var x421: u64 = undefined; var x422: u1 = undefined; addcarryxU64(&x421, &x422, x420, x378, x406); var x423: u64 = undefined; var x424: u1 = undefined; addcarryxU64(&x423, &x424, x422, x380, x408); const x425 = (cast(u64, x424) + cast(u64, x381)); var x426: u64 = undefined; var x427: u64 = undefined; mulxU64(&x426, &x427, x5, (arg1[6])); var x428: u64 = undefined; var x429: u64 = undefined; mulxU64(&x428, &x429, x5, (arg1[5])); var x430: u64 = undefined; var x431: u64 = undefined; mulxU64(&x430, &x431, x5, (arg1[4])); var x432: u64 = undefined; var x433: u64 = undefined; mulxU64(&x432, &x433, x5, (arg1[3])); var x434: u64 = undefined; var x435: u64 = undefined; mulxU64(&x434, &x435, x5, (arg1[2])); var x436: u64 = undefined; var x437: u64 = undefined; mulxU64(&x436, &x437, x5, (arg1[1])); var x438: u64 = undefined; var x439: u64 = undefined; mulxU64(&x438, &x439, x5, (arg1[0])); var x440: u64 = undefined; var x441: u1 = undefined; addcarryxU64(&x440, &x441, 0x0, x439, x436); var x442: u64 = undefined; var x443: u1 = undefined; addcarryxU64(&x442, &x443, x441, x437, x434); var x444: u64 = undefined; var x445: u1 = undefined; addcarryxU64(&x444, &x445, x443, x435, x432); var x446: u64 = undefined; var x447: u1 = undefined; addcarryxU64(&x446, &x447, x445, x433, x430); var x448: u64 = undefined; var x449: u1 = undefined; addcarryxU64(&x448, &x449, x447, x431, x428); var x450: u64 = undefined; var x451: u1 = undefined; addcarryxU64(&x450, &x451, x449, x429, x426); const x452 = (cast(u64, x451) + x427); var x453: u64 = undefined; var x454: u1 = undefined; addcarryxU64(&x453, &x454, 0x0, x411, x438); var x455: u64 = undefined; var x456: u1 = undefined; addcarryxU64(&x455, &x456, x454, x413, x440); var x457: u64 = undefined; var x458: u1 = undefined; addcarryxU64(&x457, &x458, x456, x415, x442); var x459: u64 = undefined; var x460: u1 = undefined; addcarryxU64(&x459, &x460, x458, x417, x444); var x461: u64 = undefined; var x462: u1 = undefined; addcarryxU64(&x461, &x462, x460, x419, x446); var x463: u64 = undefined; var x464: u1 = undefined; addcarryxU64(&x463, &x464, x462, x421, x448); var x465: u64 = undefined; var x466: u1 = undefined; addcarryxU64(&x465, &x466, x464, x423, x450); var x467: u64 = undefined; var x468: u1 = undefined; addcarryxU64(&x467, &x468, x466, x425, x452); var x469: u64 = undefined; var x470: u64 = undefined; mulxU64(&x469, &x470, x453, 0x2341f27177344); var x471: u64 = undefined; var x472: u64 = undefined; mulxU64(&x471, &x472, x453, 0x6cfc5fd681c52056); var x473: u64 = undefined; var x474: u64 = undefined; mulxU64(&x473, &x474, x453, 0x7bc65c783158aea3); var x475: u64 = undefined; var x476: u64 = undefined; mulxU64(&x475, &x476, x453, 0xfdc1767ae2ffffff); var x477: u64 = undefined; var x478: u64 = undefined; mulxU64(&x477, &x478, x453, 0xffffffffffffffff); var x479: u64 = undefined; var x480: u64 = undefined; mulxU64(&x479, &x480, x453, 0xffffffffffffffff); var x481: u64 = undefined; var x482: u64 = undefined; mulxU64(&x481, &x482, x453, 0xffffffffffffffff); var x483: u64 = undefined; var x484: u1 = undefined; addcarryxU64(&x483, &x484, 0x0, x482, x479); var x485: u64 = undefined; var x486: u1 = undefined; addcarryxU64(&x485, &x486, x484, x480, x477); var x487: u64 = undefined; var x488: u1 = undefined; addcarryxU64(&x487, &x488, x486, x478, x475); var x489: u64 = undefined; var x490: u1 = undefined; addcarryxU64(&x489, &x490, x488, x476, x473); var x491: u64 = undefined; var x492: u1 = undefined; addcarryxU64(&x491, &x492, x490, x474, x471); var x493: u64 = undefined; var x494: u1 = undefined; addcarryxU64(&x493, &x494, x492, x472, x469); const x495 = (cast(u64, x494) + x470); var x496: u64 = undefined; var x497: u1 = undefined; addcarryxU64(&x496, &x497, 0x0, x453, x481); var x498: u64 = undefined; var x499: u1 = undefined; addcarryxU64(&x498, &x499, x497, x455, x483); var x500: u64 = undefined; var x501: u1 = undefined; addcarryxU64(&x500, &x501, x499, x457, x485); var x502: u64 = undefined; var x503: u1 = undefined; addcarryxU64(&x502, &x503, x501, x459, x487); var x504: u64 = undefined; var x505: u1 = undefined; addcarryxU64(&x504, &x505, x503, x461, x489); var x506: u64 = undefined; var x507: u1 = undefined; addcarryxU64(&x506, &x507, x505, x463, x491); var x508: u64 = undefined; var x509: u1 = undefined; addcarryxU64(&x508, &x509, x507, x465, x493); var x510: u64 = undefined; var x511: u1 = undefined; addcarryxU64(&x510, &x511, x509, x467, x495); const x512 = (cast(u64, x511) + cast(u64, x468)); var x513: u64 = undefined; var x514: u64 = undefined; mulxU64(&x513, &x514, x6, (arg1[6])); var x515: u64 = undefined; var x516: u64 = undefined; mulxU64(&x515, &x516, x6, (arg1[5])); var x517: u64 = undefined; var x518: u64 = undefined; mulxU64(&x517, &x518, x6, (arg1[4])); var x519: u64 = undefined; var x520: u64 = undefined; mulxU64(&x519, &x520, x6, (arg1[3])); var x521: u64 = undefined; var x522: u64 = undefined; mulxU64(&x521, &x522, x6, (arg1[2])); var x523: u64 = undefined; var x524: u64 = undefined; mulxU64(&x523, &x524, x6, (arg1[1])); var x525: u64 = undefined; var x526: u64 = undefined; mulxU64(&x525, &x526, x6, (arg1[0])); var x527: u64 = undefined; var x528: u1 = undefined; addcarryxU64(&x527, &x528, 0x0, x526, x523); var x529: u64 = undefined; var x530: u1 = undefined; addcarryxU64(&x529, &x530, x528, x524, x521); var x531: u64 = undefined; var x532: u1 = undefined; addcarryxU64(&x531, &x532, x530, x522, x519); var x533: u64 = undefined; var x534: u1 = undefined; addcarryxU64(&x533, &x534, x532, x520, x517); var x535: u64 = undefined; var x536: u1 = undefined; addcarryxU64(&x535, &x536, x534, x518, x515); var x537: u64 = undefined; var x538: u1 = undefined; addcarryxU64(&x537, &x538, x536, x516, x513); const x539 = (cast(u64, x538) + x514); var x540: u64 = undefined; var x541: u1 = undefined; addcarryxU64(&x540, &x541, 0x0, x498, x525); var x542: u64 = undefined; var x543: u1 = undefined; addcarryxU64(&x542, &x543, x541, x500, x527); var x544: u64 = undefined; var x545: u1 = undefined; addcarryxU64(&x544, &x545, x543, x502, x529); var x546: u64 = undefined; var x547: u1 = undefined; addcarryxU64(&x546, &x547, x545, x504, x531); var x548: u64 = undefined; var x549: u1 = undefined; addcarryxU64(&x548, &x549, x547, x506, x533); var x550: u64 = undefined; var x551: u1 = undefined; addcarryxU64(&x550, &x551, x549, x508, x535); var x552: u64 = undefined; var x553: u1 = undefined; addcarryxU64(&x552, &x553, x551, x510, x537); var x554: u64 = undefined; var x555: u1 = undefined; addcarryxU64(&x554, &x555, x553, x512, x539); var x556: u64 = undefined; var x557: u64 = undefined; mulxU64(&x556, &x557, x540, 0x2341f27177344); var x558: u64 = undefined; var x559: u64 = undefined; mulxU64(&x558, &x559, x540, 0x6cfc5fd681c52056); var x560: u64 = undefined; var x561: u64 = undefined; mulxU64(&x560, &x561, x540, 0x7bc65c783158aea3); var x562: u64 = undefined; var x563: u64 = undefined; mulxU64(&x562, &x563, x540, 0xfdc1767ae2ffffff); var x564: u64 = undefined; var x565: u64 = undefined; mulxU64(&x564, &x565, x540, 0xffffffffffffffff); var x566: u64 = undefined; var x567: u64 = undefined; mulxU64(&x566, &x567, x540, 0xffffffffffffffff); var x568: u64 = undefined; var x569: u64 = undefined; mulxU64(&x568, &x569, x540, 0xffffffffffffffff); var x570: u64 = undefined; var x571: u1 = undefined; addcarryxU64(&x570, &x571, 0x0, x569, x566); var x572: u64 = undefined; var x573: u1 = undefined; addcarryxU64(&x572, &x573, x571, x567, x564); var x574: u64 = undefined; var x575: u1 = undefined; addcarryxU64(&x574, &x575, x573, x565, x562); var x576: u64 = undefined; var x577: u1 = undefined; addcarryxU64(&x576, &x577, x575, x563, x560); var x578: u64 = undefined; var x579: u1 = undefined; addcarryxU64(&x578, &x579, x577, x561, x558); var x580: u64 = undefined; var x581: u1 = undefined; addcarryxU64(&x580, &x581, x579, x559, x556); const x582 = (cast(u64, x581) + x557); var x583: u64 = undefined; var x584: u1 = undefined; addcarryxU64(&x583, &x584, 0x0, x540, x568); var x585: u64 = undefined; var x586: u1 = undefined; addcarryxU64(&x585, &x586, x584, x542, x570); var x587: u64 = undefined; var x588: u1 = undefined; addcarryxU64(&x587, &x588, x586, x544, x572); var x589: u64 = undefined; var x590: u1 = undefined; addcarryxU64(&x589, &x590, x588, x546, x574); var x591: u64 = undefined; var x592: u1 = undefined; addcarryxU64(&x591, &x592, x590, x548, x576); var x593: u64 = undefined; var x594: u1 = undefined; addcarryxU64(&x593, &x594, x592, x550, x578); var x595: u64 = undefined; var x596: u1 = undefined; addcarryxU64(&x595, &x596, x594, x552, x580); var x597: u64 = undefined; var x598: u1 = undefined; addcarryxU64(&x597, &x598, x596, x554, x582); const x599 = (cast(u64, x598) + cast(u64, x555)); var x600: u64 = undefined; var x601: u1 = undefined; subborrowxU64(&x600, &x601, 0x0, x585, 0xffffffffffffffff); var x602: u64 = undefined; var x603: u1 = undefined; subborrowxU64(&x602, &x603, x601, x587, 0xffffffffffffffff); var x604: u64 = undefined; var x605: u1 = undefined; subborrowxU64(&x604, &x605, x603, x589, 0xffffffffffffffff); var x606: u64 = undefined; var x607: u1 = undefined; subborrowxU64(&x606, &x607, x605, x591, 0xfdc1767ae2ffffff); var x608: u64 = undefined; var x609: u1 = undefined; subborrowxU64(&x608, &x609, x607, x593, 0x7bc65c783158aea3); var x610: u64 = undefined; var x611: u1 = undefined; subborrowxU64(&x610, &x611, x609, x595, 0x6cfc5fd681c52056); var x612: u64 = undefined; var x613: u1 = undefined; subborrowxU64(&x612, &x613, x611, x597, 0x2341f27177344); var x614: u64 = undefined; var x615: u1 = undefined; subborrowxU64(&x614, &x615, x613, x599, cast(u64, 0x0)); var x616: u64 = undefined; cmovznzU64(&x616, x615, x600, x585); var x617: u64 = undefined; cmovznzU64(&x617, x615, x602, x587); var x618: u64 = undefined; cmovznzU64(&x618, x615, x604, x589); var x619: u64 = undefined; cmovznzU64(&x619, x615, x606, x591); var x620: u64 = undefined; cmovznzU64(&x620, x615, x608, x593); var x621: u64 = undefined; cmovznzU64(&x621, x615, x610, x595); var x622: u64 = undefined; cmovznzU64(&x622, x615, x612, x597); out1[0] = x616; out1[1] = x617; out1[2] = x618; out1[3] = x619; out1[4] = x620; out1[5] = x621; out1[6] = x622; } /// The function add adds two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) + eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn add(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; addcarryxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; addcarryxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; addcarryxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; var x10: u1 = undefined; addcarryxU64(&x9, &x10, x8, (arg1[4]), (arg2[4])); var x11: u64 = undefined; var x12: u1 = undefined; addcarryxU64(&x11, &x12, x10, (arg1[5]), (arg2[5])); var x13: u64 = undefined; var x14: u1 = undefined; addcarryxU64(&x13, &x14, x12, (arg1[6]), (arg2[6])); var x15: u64 = undefined; var x16: u1 = undefined; subborrowxU64(&x15, &x16, 0x0, x1, 0xffffffffffffffff); var x17: u64 = undefined; var x18: u1 = undefined; subborrowxU64(&x17, &x18, x16, x3, 0xffffffffffffffff); var x19: u64 = undefined; var x20: u1 = undefined; subborrowxU64(&x19, &x20, x18, x5, 0xffffffffffffffff); var x21: u64 = undefined; var x22: u1 = undefined; subborrowxU64(&x21, &x22, x20, x7, 0xfdc1767ae2ffffff); var x23: u64 = undefined; var x24: u1 = undefined; subborrowxU64(&x23, &x24, x22, x9, 0x7bc65c783158aea3); var x25: u64 = undefined; var x26: u1 = undefined; subborrowxU64(&x25, &x26, x24, x11, 0x6cfc5fd681c52056); var x27: u64 = undefined; var x28: u1 = undefined; subborrowxU64(&x27, &x28, x26, x13, 0x2341f27177344); var x29: u64 = undefined; var x30: u1 = undefined; subborrowxU64(&x29, &x30, x28, cast(u64, x14), cast(u64, 0x0)); var x31: u64 = undefined; cmovznzU64(&x31, x30, x15, x1); var x32: u64 = undefined; cmovznzU64(&x32, x30, x17, x3); var x33: u64 = undefined; cmovznzU64(&x33, x30, x19, x5); var x34: u64 = undefined; cmovznzU64(&x34, x30, x21, x7); var x35: u64 = undefined; cmovznzU64(&x35, x30, x23, x9); var x36: u64 = undefined; cmovznzU64(&x36, x30, x25, x11); var x37: u64 = undefined; cmovznzU64(&x37, x30, x27, x13); out1[0] = x31; out1[1] = x32; out1[2] = x33; out1[3] = x34; out1[4] = x35; out1[5] = x36; out1[6] = x37; } /// The function sub subtracts two field elements in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// 0 ≤ eval arg2 < m /// Postconditions: /// eval (from_montgomery out1) mod m = (eval (from_montgomery arg1) - eval (from_montgomery arg2)) mod m /// 0 ≤ eval out1 < m /// pub fn sub(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement, arg2: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, (arg1[0]), (arg2[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, (arg1[1]), (arg2[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, (arg1[2]), (arg2[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, (arg1[3]), (arg2[3])); var x9: u64 = undefined; var x10: u1 = undefined; subborrowxU64(&x9, &x10, x8, (arg1[4]), (arg2[4])); var x11: u64 = undefined; var x12: u1 = undefined; subborrowxU64(&x11, &x12, x10, (arg1[5]), (arg2[5])); var x13: u64 = undefined; var x14: u1 = undefined; subborrowxU64(&x13, &x14, x12, (arg1[6]), (arg2[6])); var x15: u64 = undefined; cmovznzU64(&x15, x14, cast(u64, 0x0), 0xffffffffffffffff); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, 0x0, x1, x15); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, x17, x3, x15); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, x5, x15); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, x21, x7, (x15 & 0xfdc1767ae2ffffff)); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, x9, (x15 & 0x7bc65c783158aea3)); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, x11, (x15 & 0x6cfc5fd681c52056)); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x13, (x15 & 0x2341f27177344)); out1[0] = x16; out1[1] = x18; out1[2] = x20; out1[3] = x22; out1[4] = x24; out1[5] = x26; out1[6] = x28; } /// The function opp negates a field element in the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = -eval (from_montgomery arg1) mod m /// 0 ≤ eval out1 < m /// pub fn opp(out1: *MontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; subborrowxU64(&x1, &x2, 0x0, cast(u64, 0x0), (arg1[0])); var x3: u64 = undefined; var x4: u1 = undefined; subborrowxU64(&x3, &x4, x2, cast(u64, 0x0), (arg1[1])); var x5: u64 = undefined; var x6: u1 = undefined; subborrowxU64(&x5, &x6, x4, cast(u64, 0x0), (arg1[2])); var x7: u64 = undefined; var x8: u1 = undefined; subborrowxU64(&x7, &x8, x6, cast(u64, 0x0), (arg1[3])); var x9: u64 = undefined; var x10: u1 = undefined; subborrowxU64(&x9, &x10, x8, cast(u64, 0x0), (arg1[4])); var x11: u64 = undefined; var x12: u1 = undefined; subborrowxU64(&x11, &x12, x10, cast(u64, 0x0), (arg1[5])); var x13: u64 = undefined; var x14: u1 = undefined; subborrowxU64(&x13, &x14, x12, cast(u64, 0x0), (arg1[6])); var x15: u64 = undefined; cmovznzU64(&x15, x14, cast(u64, 0x0), 0xffffffffffffffff); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, 0x0, x1, x15); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, x17, x3, x15); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, x5, x15); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, x21, x7, (x15 & 0xfdc1767ae2ffffff)); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, x9, (x15 & 0x7bc65c783158aea3)); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, x11, (x15 & 0x6cfc5fd681c52056)); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x13, (x15 & 0x2341f27177344)); out1[0] = x16; out1[1] = x18; out1[2] = x20; out1[3] = x22; out1[4] = x24; out1[5] = x26; out1[6] = x28; } /// The function fromMontgomery translates a field element out of the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval out1 mod m = (eval arg1 * ((2^64)⁻¹ mod m)^7) mod m /// 0 ≤ eval out1 < m /// pub fn fromMontgomery(out1: *NonMontgomeryDomainFieldElement, arg1: MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[0]); var x2: u64 = undefined; var x3: u64 = undefined; mulxU64(&x2, &x3, x1, 0x2341f27177344); var x4: u64 = undefined; var x5: u64 = undefined; mulxU64(&x4, &x5, x1, 0x6cfc5fd681c52056); var x6: u64 = undefined; var x7: u64 = undefined; mulxU64(&x6, &x7, x1, 0x7bc65c783158aea3); var x8: u64 = undefined; var x9: u64 = undefined; mulxU64(&x8, &x9, x1, 0xfdc1767ae2ffffff); var x10: u64 = undefined; var x11: u64 = undefined; mulxU64(&x10, &x11, x1, 0xffffffffffffffff); var x12: u64 = undefined; var x13: u64 = undefined; mulxU64(&x12, &x13, x1, 0xffffffffffffffff); var x14: u64 = undefined; var x15: u64 = undefined; mulxU64(&x14, &x15, x1, 0xffffffffffffffff); var x16: u64 = undefined; var x17: u1 = undefined; addcarryxU64(&x16, &x17, 0x0, x15, x12); var x18: u64 = undefined; var x19: u1 = undefined; addcarryxU64(&x18, &x19, x17, x13, x10); var x20: u64 = undefined; var x21: u1 = undefined; addcarryxU64(&x20, &x21, x19, x11, x8); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, x21, x9, x6); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, x7, x4); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, x5, x2); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, 0x0, x1, x14); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, cast(u64, 0x0), x16); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, cast(u64, 0x0), x18); var x34: u64 = undefined; var x35: u1 = undefined; addcarryxU64(&x34, &x35, x33, cast(u64, 0x0), x20); var x36: u64 = undefined; var x37: u1 = undefined; addcarryxU64(&x36, &x37, x35, cast(u64, 0x0), x22); var x38: u64 = undefined; var x39: u1 = undefined; addcarryxU64(&x38, &x39, x37, cast(u64, 0x0), x24); var x40: u64 = undefined; var x41: u1 = undefined; addcarryxU64(&x40, &x41, x39, cast(u64, 0x0), x26); var x42: u64 = undefined; var x43: u1 = undefined; addcarryxU64(&x42, &x43, 0x0, x30, (arg1[1])); var x44: u64 = undefined; var x45: u1 = undefined; addcarryxU64(&x44, &x45, x43, x32, cast(u64, 0x0)); var x46: u64 = undefined; var x47: u1 = undefined; addcarryxU64(&x46, &x47, x45, x34, cast(u64, 0x0)); var x48: u64 = undefined; var x49: u1 = undefined; addcarryxU64(&x48, &x49, x47, x36, cast(u64, 0x0)); var x50: u64 = undefined; var x51: u1 = undefined; addcarryxU64(&x50, &x51, x49, x38, cast(u64, 0x0)); var x52: u64 = undefined; var x53: u1 = undefined; addcarryxU64(&x52, &x53, x51, x40, cast(u64, 0x0)); var x54: u64 = undefined; var x55: u64 = undefined; mulxU64(&x54, &x55, x42, 0x2341f27177344); var x56: u64 = undefined; var x57: u64 = undefined; mulxU64(&x56, &x57, x42, 0x6cfc5fd681c52056); var x58: u64 = undefined; var x59: u64 = undefined; mulxU64(&x58, &x59, x42, 0x7bc65c783158aea3); var x60: u64 = undefined; var x61: u64 = undefined; mulxU64(&x60, &x61, x42, 0xfdc1767ae2ffffff); var x62: u64 = undefined; var x63: u64 = undefined; mulxU64(&x62, &x63, x42, 0xffffffffffffffff); var x64: u64 = undefined; var x65: u64 = undefined; mulxU64(&x64, &x65, x42, 0xffffffffffffffff); var x66: u64 = undefined; var x67: u64 = undefined; mulxU64(&x66, &x67, x42, 0xffffffffffffffff); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, 0x0, x67, x64); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, x65, x62); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, x71, x63, x60); var x74: u64 = undefined; var x75: u1 = undefined; addcarryxU64(&x74, &x75, x73, x61, x58); var x76: u64 = undefined; var x77: u1 = undefined; addcarryxU64(&x76, &x77, x75, x59, x56); var x78: u64 = undefined; var x79: u1 = undefined; addcarryxU64(&x78, &x79, x77, x57, x54); var x80: u64 = undefined; var x81: u1 = undefined; addcarryxU64(&x80, &x81, 0x0, x42, x66); var x82: u64 = undefined; var x83: u1 = undefined; addcarryxU64(&x82, &x83, x81, x44, x68); var x84: u64 = undefined; var x85: u1 = undefined; addcarryxU64(&x84, &x85, x83, x46, x70); var x86: u64 = undefined; var x87: u1 = undefined; addcarryxU64(&x86, &x87, x85, x48, x72); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, x87, x50, x74); var x90: u64 = undefined; var x91: u1 = undefined; addcarryxU64(&x90, &x91, x89, x52, x76); var x92: u64 = undefined; var x93: u1 = undefined; addcarryxU64(&x92, &x93, x91, (cast(u64, x53) + (cast(u64, x41) + (cast(u64, x27) + x3))), x78); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, 0x0, x82, (arg1[2])); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x84, cast(u64, 0x0)); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x86, cast(u64, 0x0)); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x88, cast(u64, 0x0)); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, x101, x90, cast(u64, 0x0)); var x104: u64 = undefined; var x105: u1 = undefined; addcarryxU64(&x104, &x105, x103, x92, cast(u64, 0x0)); var x106: u64 = undefined; var x107: u64 = undefined; mulxU64(&x106, &x107, x94, 0x2341f27177344); var x108: u64 = undefined; var x109: u64 = undefined; mulxU64(&x108, &x109, x94, 0x6cfc5fd681c52056); var x110: u64 = undefined; var x111: u64 = undefined; mulxU64(&x110, &x111, x94, 0x7bc65c783158aea3); var x112: u64 = undefined; var x113: u64 = undefined; mulxU64(&x112, &x113, x94, 0xfdc1767ae2ffffff); var x114: u64 = undefined; var x115: u64 = undefined; mulxU64(&x114, &x115, x94, 0xffffffffffffffff); var x116: u64 = undefined; var x117: u64 = undefined; mulxU64(&x116, &x117, x94, 0xffffffffffffffff); var x118: u64 = undefined; var x119: u64 = undefined; mulxU64(&x118, &x119, x94, 0xffffffffffffffff); var x120: u64 = undefined; var x121: u1 = undefined; addcarryxU64(&x120, &x121, 0x0, x119, x116); var x122: u64 = undefined; var x123: u1 = undefined; addcarryxU64(&x122, &x123, x121, x117, x114); var x124: u64 = undefined; var x125: u1 = undefined; addcarryxU64(&x124, &x125, x123, x115, x112); var x126: u64 = undefined; var x127: u1 = undefined; addcarryxU64(&x126, &x127, x125, x113, x110); var x128: u64 = undefined; var x129: u1 = undefined; addcarryxU64(&x128, &x129, x127, x111, x108); var x130: u64 = undefined; var x131: u1 = undefined; addcarryxU64(&x130, &x131, x129, x109, x106); var x132: u64 = undefined; var x133: u1 = undefined; addcarryxU64(&x132, &x133, 0x0, x94, x118); var x134: u64 = undefined; var x135: u1 = undefined; addcarryxU64(&x134, &x135, x133, x96, x120); var x136: u64 = undefined; var x137: u1 = undefined; addcarryxU64(&x136, &x137, x135, x98, x122); var x138: u64 = undefined; var x139: u1 = undefined; addcarryxU64(&x138, &x139, x137, x100, x124); var x140: u64 = undefined; var x141: u1 = undefined; addcarryxU64(&x140, &x141, x139, x102, x126); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, x141, x104, x128); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, x143, (cast(u64, x105) + (cast(u64, x93) + (cast(u64, x79) + x55))), x130); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, 0x0, x134, (arg1[3])); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x136, cast(u64, 0x0)); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x138, cast(u64, 0x0)); var x152: u64 = undefined; var x153: u1 = undefined; addcarryxU64(&x152, &x153, x151, x140, cast(u64, 0x0)); var x154: u64 = undefined; var x155: u1 = undefined; addcarryxU64(&x154, &x155, x153, x142, cast(u64, 0x0)); var x156: u64 = undefined; var x157: u1 = undefined; addcarryxU64(&x156, &x157, x155, x144, cast(u64, 0x0)); var x158: u64 = undefined; var x159: u64 = undefined; mulxU64(&x158, &x159, x146, 0x2341f27177344); var x160: u64 = undefined; var x161: u64 = undefined; mulxU64(&x160, &x161, x146, 0x6cfc5fd681c52056); var x162: u64 = undefined; var x163: u64 = undefined; mulxU64(&x162, &x163, x146, 0x7bc65c783158aea3); var x164: u64 = undefined; var x165: u64 = undefined; mulxU64(&x164, &x165, x146, 0xfdc1767ae2ffffff); var x166: u64 = undefined; var x167: u64 = undefined; mulxU64(&x166, &x167, x146, 0xffffffffffffffff); var x168: u64 = undefined; var x169: u64 = undefined; mulxU64(&x168, &x169, x146, 0xffffffffffffffff); var x170: u64 = undefined; var x171: u64 = undefined; mulxU64(&x170, &x171, x146, 0xffffffffffffffff); var x172: u64 = undefined; var x173: u1 = undefined; addcarryxU64(&x172, &x173, 0x0, x171, x168); var x174: u64 = undefined; var x175: u1 = undefined; addcarryxU64(&x174, &x175, x173, x169, x166); var x176: u64 = undefined; var x177: u1 = undefined; addcarryxU64(&x176, &x177, x175, x167, x164); var x178: u64 = undefined; var x179: u1 = undefined; addcarryxU64(&x178, &x179, x177, x165, x162); var x180: u64 = undefined; var x181: u1 = undefined; addcarryxU64(&x180, &x181, x179, x163, x160); var x182: u64 = undefined; var x183: u1 = undefined; addcarryxU64(&x182, &x183, x181, x161, x158); var x184: u64 = undefined; var x185: u1 = undefined; addcarryxU64(&x184, &x185, 0x0, x146, x170); var x186: u64 = undefined; var x187: u1 = undefined; addcarryxU64(&x186, &x187, x185, x148, x172); var x188: u64 = undefined; var x189: u1 = undefined; addcarryxU64(&x188, &x189, x187, x150, x174); var x190: u64 = undefined; var x191: u1 = undefined; addcarryxU64(&x190, &x191, x189, x152, x176); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, x191, x154, x178); var x194: u64 = undefined; var x195: u1 = undefined; addcarryxU64(&x194, &x195, x193, x156, x180); var x196: u64 = undefined; var x197: u1 = undefined; addcarryxU64(&x196, &x197, x195, (cast(u64, x157) + (cast(u64, x145) + (cast(u64, x131) + x107))), x182); var x198: u64 = undefined; var x199: u1 = undefined; addcarryxU64(&x198, &x199, 0x0, x186, (arg1[4])); var x200: u64 = undefined; var x201: u1 = undefined; addcarryxU64(&x200, &x201, x199, x188, cast(u64, 0x0)); var x202: u64 = undefined; var x203: u1 = undefined; addcarryxU64(&x202, &x203, x201, x190, cast(u64, 0x0)); var x204: u64 = undefined; var x205: u1 = undefined; addcarryxU64(&x204, &x205, x203, x192, cast(u64, 0x0)); var x206: u64 = undefined; var x207: u1 = undefined; addcarryxU64(&x206, &x207, x205, x194, cast(u64, 0x0)); var x208: u64 = undefined; var x209: u1 = undefined; addcarryxU64(&x208, &x209, x207, x196, cast(u64, 0x0)); var x210: u64 = undefined; var x211: u64 = undefined; mulxU64(&x210, &x211, x198, 0x2341f27177344); var x212: u64 = undefined; var x213: u64 = undefined; mulxU64(&x212, &x213, x198, 0x6cfc5fd681c52056); var x214: u64 = undefined; var x215: u64 = undefined; mulxU64(&x214, &x215, x198, 0x7bc65c783158aea3); var x216: u64 = undefined; var x217: u64 = undefined; mulxU64(&x216, &x217, x198, 0xfdc1767ae2ffffff); var x218: u64 = undefined; var x219: u64 = undefined; mulxU64(&x218, &x219, x198, 0xffffffffffffffff); var x220: u64 = undefined; var x221: u64 = undefined; mulxU64(&x220, &x221, x198, 0xffffffffffffffff); var x222: u64 = undefined; var x223: u64 = undefined; mulxU64(&x222, &x223, x198, 0xffffffffffffffff); var x224: u64 = undefined; var x225: u1 = undefined; addcarryxU64(&x224, &x225, 0x0, x223, x220); var x226: u64 = undefined; var x227: u1 = undefined; addcarryxU64(&x226, &x227, x225, x221, x218); var x228: u64 = undefined; var x229: u1 = undefined; addcarryxU64(&x228, &x229, x227, x219, x216); var x230: u64 = undefined; var x231: u1 = undefined; addcarryxU64(&x230, &x231, x229, x217, x214); var x232: u64 = undefined; var x233: u1 = undefined; addcarryxU64(&x232, &x233, x231, x215, x212); var x234: u64 = undefined; var x235: u1 = undefined; addcarryxU64(&x234, &x235, x233, x213, x210); var x236: u64 = undefined; var x237: u1 = undefined; addcarryxU64(&x236, &x237, 0x0, x198, x222); var x238: u64 = undefined; var x239: u1 = undefined; addcarryxU64(&x238, &x239, x237, x200, x224); var x240: u64 = undefined; var x241: u1 = undefined; addcarryxU64(&x240, &x241, x239, x202, x226); var x242: u64 = undefined; var x243: u1 = undefined; addcarryxU64(&x242, &x243, x241, x204, x228); var x244: u64 = undefined; var x245: u1 = undefined; addcarryxU64(&x244, &x245, x243, x206, x230); var x246: u64 = undefined; var x247: u1 = undefined; addcarryxU64(&x246, &x247, x245, x208, x232); var x248: u64 = undefined; var x249: u1 = undefined; addcarryxU64(&x248, &x249, x247, (cast(u64, x209) + (cast(u64, x197) + (cast(u64, x183) + x159))), x234); var x250: u64 = undefined; var x251: u1 = undefined; addcarryxU64(&x250, &x251, 0x0, x238, (arg1[5])); var x252: u64 = undefined; var x253: u1 = undefined; addcarryxU64(&x252, &x253, x251, x240, cast(u64, 0x0)); var x254: u64 = undefined; var x255: u1 = undefined; addcarryxU64(&x254, &x255, x253, x242, cast(u64, 0x0)); var x256: u64 = undefined; var x257: u1 = undefined; addcarryxU64(&x256, &x257, x255, x244, cast(u64, 0x0)); var x258: u64 = undefined; var x259: u1 = undefined; addcarryxU64(&x258, &x259, x257, x246, cast(u64, 0x0)); var x260: u64 = undefined; var x261: u1 = undefined; addcarryxU64(&x260, &x261, x259, x248, cast(u64, 0x0)); var x262: u64 = undefined; var x263: u64 = undefined; mulxU64(&x262, &x263, x250, 0x2341f27177344); var x264: u64 = undefined; var x265: u64 = undefined; mulxU64(&x264, &x265, x250, 0x6cfc5fd681c52056); var x266: u64 = undefined; var x267: u64 = undefined; mulxU64(&x266, &x267, x250, 0x7bc65c783158aea3); var x268: u64 = undefined; var x269: u64 = undefined; mulxU64(&x268, &x269, x250, 0xfdc1767ae2ffffff); var x270: u64 = undefined; var x271: u64 = undefined; mulxU64(&x270, &x271, x250, 0xffffffffffffffff); var x272: u64 = undefined; var x273: u64 = undefined; mulxU64(&x272, &x273, x250, 0xffffffffffffffff); var x274: u64 = undefined; var x275: u64 = undefined; mulxU64(&x274, &x275, x250, 0xffffffffffffffff); var x276: u64 = undefined; var x277: u1 = undefined; addcarryxU64(&x276, &x277, 0x0, x275, x272); var x278: u64 = undefined; var x279: u1 = undefined; addcarryxU64(&x278, &x279, x277, x273, x270); var x280: u64 = undefined; var x281: u1 = undefined; addcarryxU64(&x280, &x281, x279, x271, x268); var x282: u64 = undefined; var x283: u1 = undefined; addcarryxU64(&x282, &x283, x281, x269, x266); var x284: u64 = undefined; var x285: u1 = undefined; addcarryxU64(&x284, &x285, x283, x267, x264); var x286: u64 = undefined; var x287: u1 = undefined; addcarryxU64(&x286, &x287, x285, x265, x262); var x288: u64 = undefined; var x289: u1 = undefined; addcarryxU64(&x288, &x289, 0x0, x250, x274); var x290: u64 = undefined; var x291: u1 = undefined; addcarryxU64(&x290, &x291, x289, x252, x276); var x292: u64 = undefined; var x293: u1 = undefined; addcarryxU64(&x292, &x293, x291, x254, x278); var x294: u64 = undefined; var x295: u1 = undefined; addcarryxU64(&x294, &x295, x293, x256, x280); var x296: u64 = undefined; var x297: u1 = undefined; addcarryxU64(&x296, &x297, x295, x258, x282); var x298: u64 = undefined; var x299: u1 = undefined; addcarryxU64(&x298, &x299, x297, x260, x284); var x300: u64 = undefined; var x301: u1 = undefined; addcarryxU64(&x300, &x301, x299, (cast(u64, x261) + (cast(u64, x249) + (cast(u64, x235) + x211))), x286); var x302: u64 = undefined; var x303: u1 = undefined; addcarryxU64(&x302, &x303, 0x0, x290, (arg1[6])); var x304: u64 = undefined; var x305: u1 = undefined; addcarryxU64(&x304, &x305, x303, x292, cast(u64, 0x0)); var x306: u64 = undefined; var x307: u1 = undefined; addcarryxU64(&x306, &x307, x305, x294, cast(u64, 0x0)); var x308: u64 = undefined; var x309: u1 = undefined; addcarryxU64(&x308, &x309, x307, x296, cast(u64, 0x0)); var x310: u64 = undefined; var x311: u1 = undefined; addcarryxU64(&x310, &x311, x309, x298, cast(u64, 0x0)); var x312: u64 = undefined; var x313: u1 = undefined; addcarryxU64(&x312, &x313, x311, x300, cast(u64, 0x0)); var x314: u64 = undefined; var x315: u64 = undefined; mulxU64(&x314, &x315, x302, 0x2341f27177344); var x316: u64 = undefined; var x317: u64 = undefined; mulxU64(&x316, &x317, x302, 0x6cfc5fd681c52056); var x318: u64 = undefined; var x319: u64 = undefined; mulxU64(&x318, &x319, x302, 0x7bc65c783158aea3); var x320: u64 = undefined; var x321: u64 = undefined; mulxU64(&x320, &x321, x302, 0xfdc1767ae2ffffff); var x322: u64 = undefined; var x323: u64 = undefined; mulxU64(&x322, &x323, x302, 0xffffffffffffffff); var x324: u64 = undefined; var x325: u64 = undefined; mulxU64(&x324, &x325, x302, 0xffffffffffffffff); var x326: u64 = undefined; var x327: u64 = undefined; mulxU64(&x326, &x327, x302, 0xffffffffffffffff); var x328: u64 = undefined; var x329: u1 = undefined; addcarryxU64(&x328, &x329, 0x0, x327, x324); var x330: u64 = undefined; var x331: u1 = undefined; addcarryxU64(&x330, &x331, x329, x325, x322); var x332: u64 = undefined; var x333: u1 = undefined; addcarryxU64(&x332, &x333, x331, x323, x320); var x334: u64 = undefined; var x335: u1 = undefined; addcarryxU64(&x334, &x335, x333, x321, x318); var x336: u64 = undefined; var x337: u1 = undefined; addcarryxU64(&x336, &x337, x335, x319, x316); var x338: u64 = undefined; var x339: u1 = undefined; addcarryxU64(&x338, &x339, x337, x317, x314); var x340: u64 = undefined; var x341: u1 = undefined; addcarryxU64(&x340, &x341, 0x0, x302, x326); var x342: u64 = undefined; var x343: u1 = undefined; addcarryxU64(&x342, &x343, x341, x304, x328); var x344: u64 = undefined; var x345: u1 = undefined; addcarryxU64(&x344, &x345, x343, x306, x330); var x346: u64 = undefined; var x347: u1 = undefined; addcarryxU64(&x346, &x347, x345, x308, x332); var x348: u64 = undefined; var x349: u1 = undefined; addcarryxU64(&x348, &x349, x347, x310, x334); var x350: u64 = undefined; var x351: u1 = undefined; addcarryxU64(&x350, &x351, x349, x312, x336); var x352: u64 = undefined; var x353: u1 = undefined; addcarryxU64(&x352, &x353, x351, (cast(u64, x313) + (cast(u64, x301) + (cast(u64, x287) + x263))), x338); const x354 = (cast(u64, x353) + (cast(u64, x339) + x315)); var x355: u64 = undefined; var x356: u1 = undefined; subborrowxU64(&x355, &x356, 0x0, x342, 0xffffffffffffffff); var x357: u64 = undefined; var x358: u1 = undefined; subborrowxU64(&x357, &x358, x356, x344, 0xffffffffffffffff); var x359: u64 = undefined; var x360: u1 = undefined; subborrowxU64(&x359, &x360, x358, x346, 0xffffffffffffffff); var x361: u64 = undefined; var x362: u1 = undefined; subborrowxU64(&x361, &x362, x360, x348, 0xfdc1767ae2ffffff); var x363: u64 = undefined; var x364: u1 = undefined; subborrowxU64(&x363, &x364, x362, x350, 0x7bc65c783158aea3); var x365: u64 = undefined; var x366: u1 = undefined; subborrowxU64(&x365, &x366, x364, x352, 0x6cfc5fd681c52056); var x367: u64 = undefined; var x368: u1 = undefined; subborrowxU64(&x367, &x368, x366, x354, 0x2341f27177344); var x369: u64 = undefined; var x370: u1 = undefined; subborrowxU64(&x369, &x370, x368, cast(u64, 0x0), cast(u64, 0x0)); var x371: u64 = undefined; cmovznzU64(&x371, x370, x355, x342); var x372: u64 = undefined; cmovznzU64(&x372, x370, x357, x344); var x373: u64 = undefined; cmovznzU64(&x373, x370, x359, x346); var x374: u64 = undefined; cmovznzU64(&x374, x370, x361, x348); var x375: u64 = undefined; cmovznzU64(&x375, x370, x363, x350); var x376: u64 = undefined; cmovznzU64(&x376, x370, x365, x352); var x377: u64 = undefined; cmovznzU64(&x377, x370, x367, x354); out1[0] = x371; out1[1] = x372; out1[2] = x373; out1[3] = x374; out1[4] = x375; out1[5] = x376; out1[6] = x377; } /// The function toMontgomery translates a field element into the Montgomery domain. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// eval (from_montgomery out1) mod m = eval arg1 mod m /// 0 ≤ eval out1 < m /// pub fn toMontgomery(out1: *MontgomeryDomainFieldElement, arg1: NonMontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[1]); const x2 = (arg1[2]); const x3 = (arg1[3]); const x4 = (arg1[4]); const x5 = (arg1[5]); const x6 = (arg1[6]); const x7 = (arg1[0]); var x8: u64 = undefined; var x9: u64 = undefined; mulxU64(&x8, &x9, x7, 0x25a89bcdd12a); var x10: u64 = undefined; var x11: u64 = undefined; mulxU64(&x10, &x11, x7, 0x69e16a61c7686d9a); var x12: u64 = undefined; var x13: u64 = undefined; mulxU64(&x12, &x13, x7, 0xabcd92bf2dde347e); var x14: u64 = undefined; var x15: u64 = undefined; mulxU64(&x14, &x15, x7, 0x175cc6af8d6c7c0b); var x16: u64 = undefined; var x17: u64 = undefined; mulxU64(&x16, &x17, x7, 0xab27973f8311688d); var x18: u64 = undefined; var x19: u64 = undefined; mulxU64(&x18, &x19, x7, 0xacec7367768798c2); var x20: u64 = undefined; var x21: u64 = undefined; mulxU64(&x20, &x21, x7, 0x28e55b65dcd69b30); var x22: u64 = undefined; var x23: u1 = undefined; addcarryxU64(&x22, &x23, 0x0, x21, x18); var x24: u64 = undefined; var x25: u1 = undefined; addcarryxU64(&x24, &x25, x23, x19, x16); var x26: u64 = undefined; var x27: u1 = undefined; addcarryxU64(&x26, &x27, x25, x17, x14); var x28: u64 = undefined; var x29: u1 = undefined; addcarryxU64(&x28, &x29, x27, x15, x12); var x30: u64 = undefined; var x31: u1 = undefined; addcarryxU64(&x30, &x31, x29, x13, x10); var x32: u64 = undefined; var x33: u1 = undefined; addcarryxU64(&x32, &x33, x31, x11, x8); var x34: u64 = undefined; var x35: u64 = undefined; mulxU64(&x34, &x35, x20, 0x2341f27177344); var x36: u64 = undefined; var x37: u64 = undefined; mulxU64(&x36, &x37, x20, 0x6cfc5fd681c52056); var x38: u64 = undefined; var x39: u64 = undefined; mulxU64(&x38, &x39, x20, 0x7bc65c783158aea3); var x40: u64 = undefined; var x41: u64 = undefined; mulxU64(&x40, &x41, x20, 0xfdc1767ae2ffffff); var x42: u64 = undefined; var x43: u64 = undefined; mulxU64(&x42, &x43, x20, 0xffffffffffffffff); var x44: u64 = undefined; var x45: u64 = undefined; mulxU64(&x44, &x45, x20, 0xffffffffffffffff); var x46: u64 = undefined; var x47: u64 = undefined; mulxU64(&x46, &x47, x20, 0xffffffffffffffff); var x48: u64 = undefined; var x49: u1 = undefined; addcarryxU64(&x48, &x49, 0x0, x47, x44); var x50: u64 = undefined; var x51: u1 = undefined; addcarryxU64(&x50, &x51, x49, x45, x42); var x52: u64 = undefined; var x53: u1 = undefined; addcarryxU64(&x52, &x53, x51, x43, x40); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, x53, x41, x38); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, x55, x39, x36); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x37, x34); var x60: u64 = undefined; var x61: u1 = undefined; addcarryxU64(&x60, &x61, 0x0, x20, x46); var x62: u64 = undefined; var x63: u1 = undefined; addcarryxU64(&x62, &x63, x61, x22, x48); var x64: u64 = undefined; var x65: u1 = undefined; addcarryxU64(&x64, &x65, x63, x24, x50); var x66: u64 = undefined; var x67: u1 = undefined; addcarryxU64(&x66, &x67, x65, x26, x52); var x68: u64 = undefined; var x69: u1 = undefined; addcarryxU64(&x68, &x69, x67, x28, x54); var x70: u64 = undefined; var x71: u1 = undefined; addcarryxU64(&x70, &x71, x69, x30, x56); var x72: u64 = undefined; var x73: u1 = undefined; addcarryxU64(&x72, &x73, x71, x32, x58); var x74: u64 = undefined; var x75: u64 = undefined; mulxU64(&x74, &x75, x1, 0x25a89bcdd12a); var x76: u64 = undefined; var x77: u64 = undefined; mulxU64(&x76, &x77, x1, 0x69e16a61c7686d9a); var x78: u64 = undefined; var x79: u64 = undefined; mulxU64(&x78, &x79, x1, 0xabcd92bf2dde347e); var x80: u64 = undefined; var x81: u64 = undefined; mulxU64(&x80, &x81, x1, 0x175cc6af8d6c7c0b); var x82: u64 = undefined; var x83: u64 = undefined; mulxU64(&x82, &x83, x1, 0xab27973f8311688d); var x84: u64 = undefined; var x85: u64 = undefined; mulxU64(&x84, &x85, x1, 0xacec7367768798c2); var x86: u64 = undefined; var x87: u64 = undefined; mulxU64(&x86, &x87, x1, 0x28e55b65dcd69b30); var x88: u64 = undefined; var x89: u1 = undefined; addcarryxU64(&x88, &x89, 0x0, x87, x84); var x90: u64 = undefined; var x91: u1 = undefined; addcarryxU64(&x90, &x91, x89, x85, x82); var x92: u64 = undefined; var x93: u1 = undefined; addcarryxU64(&x92, &x93, x91, x83, x80); var x94: u64 = undefined; var x95: u1 = undefined; addcarryxU64(&x94, &x95, x93, x81, x78); var x96: u64 = undefined; var x97: u1 = undefined; addcarryxU64(&x96, &x97, x95, x79, x76); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, x97, x77, x74); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, 0x0, x62, x86); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, x101, x64, x88); var x104: u64 = undefined; var x105: u1 = undefined; addcarryxU64(&x104, &x105, x103, x66, x90); var x106: u64 = undefined; var x107: u1 = undefined; addcarryxU64(&x106, &x107, x105, x68, x92); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, x107, x70, x94); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x72, x96); var x112: u64 = undefined; var x113: u1 = undefined; addcarryxU64(&x112, &x113, x111, ((cast(u64, x73) + (cast(u64, x33) + x9)) + (cast(u64, x59) + x35)), x98); var x114: u64 = undefined; var x115: u64 = undefined; mulxU64(&x114, &x115, x100, 0x2341f27177344); var x116: u64 = undefined; var x117: u64 = undefined; mulxU64(&x116, &x117, x100, 0x6cfc5fd681c52056); var x118: u64 = undefined; var x119: u64 = undefined; mulxU64(&x118, &x119, x100, 0x7bc65c783158aea3); var x120: u64 = undefined; var x121: u64 = undefined; mulxU64(&x120, &x121, x100, 0xfdc1767ae2ffffff); var x122: u64 = undefined; var x123: u64 = undefined; mulxU64(&x122, &x123, x100, 0xffffffffffffffff); var x124: u64 = undefined; var x125: u64 = undefined; mulxU64(&x124, &x125, x100, 0xffffffffffffffff); var x126: u64 = undefined; var x127: u64 = undefined; mulxU64(&x126, &x127, x100, 0xffffffffffffffff); var x128: u64 = undefined; var x129: u1 = undefined; addcarryxU64(&x128, &x129, 0x0, x127, x124); var x130: u64 = undefined; var x131: u1 = undefined; addcarryxU64(&x130, &x131, x129, x125, x122); var x132: u64 = undefined; var x133: u1 = undefined; addcarryxU64(&x132, &x133, x131, x123, x120); var x134: u64 = undefined; var x135: u1 = undefined; addcarryxU64(&x134, &x135, x133, x121, x118); var x136: u64 = undefined; var x137: u1 = undefined; addcarryxU64(&x136, &x137, x135, x119, x116); var x138: u64 = undefined; var x139: u1 = undefined; addcarryxU64(&x138, &x139, x137, x117, x114); var x140: u64 = undefined; var x141: u1 = undefined; addcarryxU64(&x140, &x141, 0x0, x100, x126); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, x141, x102, x128); var x144: u64 = undefined; var x145: u1 = undefined; addcarryxU64(&x144, &x145, x143, x104, x130); var x146: u64 = undefined; var x147: u1 = undefined; addcarryxU64(&x146, &x147, x145, x106, x132); var x148: u64 = undefined; var x149: u1 = undefined; addcarryxU64(&x148, &x149, x147, x108, x134); var x150: u64 = undefined; var x151: u1 = undefined; addcarryxU64(&x150, &x151, x149, x110, x136); var x152: u64 = undefined; var x153: u1 = undefined; addcarryxU64(&x152, &x153, x151, x112, x138); var x154: u64 = undefined; var x155: u64 = undefined; mulxU64(&x154, &x155, x2, 0x25a89bcdd12a); var x156: u64 = undefined; var x157: u64 = undefined; mulxU64(&x156, &x157, x2, 0x69e16a61c7686d9a); var x158: u64 = undefined; var x159: u64 = undefined; mulxU64(&x158, &x159, x2, 0xabcd92bf2dde347e); var x160: u64 = undefined; var x161: u64 = undefined; mulxU64(&x160, &x161, x2, 0x175cc6af8d6c7c0b); var x162: u64 = undefined; var x163: u64 = undefined; mulxU64(&x162, &x163, x2, 0xab27973f8311688d); var x164: u64 = undefined; var x165: u64 = undefined; mulxU64(&x164, &x165, x2, 0xacec7367768798c2); var x166: u64 = undefined; var x167: u64 = undefined; mulxU64(&x166, &x167, x2, 0x28e55b65dcd69b30); var x168: u64 = undefined; var x169: u1 = undefined; addcarryxU64(&x168, &x169, 0x0, x167, x164); var x170: u64 = undefined; var x171: u1 = undefined; addcarryxU64(&x170, &x171, x169, x165, x162); var x172: u64 = undefined; var x173: u1 = undefined; addcarryxU64(&x172, &x173, x171, x163, x160); var x174: u64 = undefined; var x175: u1 = undefined; addcarryxU64(&x174, &x175, x173, x161, x158); var x176: u64 = undefined; var x177: u1 = undefined; addcarryxU64(&x176, &x177, x175, x159, x156); var x178: u64 = undefined; var x179: u1 = undefined; addcarryxU64(&x178, &x179, x177, x157, x154); var x180: u64 = undefined; var x181: u1 = undefined; addcarryxU64(&x180, &x181, 0x0, x142, x166); var x182: u64 = undefined; var x183: u1 = undefined; addcarryxU64(&x182, &x183, x181, x144, x168); var x184: u64 = undefined; var x185: u1 = undefined; addcarryxU64(&x184, &x185, x183, x146, x170); var x186: u64 = undefined; var x187: u1 = undefined; addcarryxU64(&x186, &x187, x185, x148, x172); var x188: u64 = undefined; var x189: u1 = undefined; addcarryxU64(&x188, &x189, x187, x150, x174); var x190: u64 = undefined; var x191: u1 = undefined; addcarryxU64(&x190, &x191, x189, x152, x176); var x192: u64 = undefined; var x193: u1 = undefined; addcarryxU64(&x192, &x193, x191, ((cast(u64, x153) + (cast(u64, x113) + (cast(u64, x99) + x75))) + (cast(u64, x139) + x115)), x178); var x194: u64 = undefined; var x195: u64 = undefined; mulxU64(&x194, &x195, x180, 0x2341f27177344); var x196: u64 = undefined; var x197: u64 = undefined; mulxU64(&x196, &x197, x180, 0x6cfc5fd681c52056); var x198: u64 = undefined; var x199: u64 = undefined; mulxU64(&x198, &x199, x180, 0x7bc65c783158aea3); var x200: u64 = undefined; var x201: u64 = undefined; mulxU64(&x200, &x201, x180, 0xfdc1767ae2ffffff); var x202: u64 = undefined; var x203: u64 = undefined; mulxU64(&x202, &x203, x180, 0xffffffffffffffff); var x204: u64 = undefined; var x205: u64 = undefined; mulxU64(&x204, &x205, x180, 0xffffffffffffffff); var x206: u64 = undefined; var x207: u64 = undefined; mulxU64(&x206, &x207, x180, 0xffffffffffffffff); var x208: u64 = undefined; var x209: u1 = undefined; addcarryxU64(&x208, &x209, 0x0, x207, x204); var x210: u64 = undefined; var x211: u1 = undefined; addcarryxU64(&x210, &x211, x209, x205, x202); var x212: u64 = undefined; var x213: u1 = undefined; addcarryxU64(&x212, &x213, x211, x203, x200); var x214: u64 = undefined; var x215: u1 = undefined; addcarryxU64(&x214, &x215, x213, x201, x198); var x216: u64 = undefined; var x217: u1 = undefined; addcarryxU64(&x216, &x217, x215, x199, x196); var x218: u64 = undefined; var x219: u1 = undefined; addcarryxU64(&x218, &x219, x217, x197, x194); var x220: u64 = undefined; var x221: u1 = undefined; addcarryxU64(&x220, &x221, 0x0, x180, x206); var x222: u64 = undefined; var x223: u1 = undefined; addcarryxU64(&x222, &x223, x221, x182, x208); var x224: u64 = undefined; var x225: u1 = undefined; addcarryxU64(&x224, &x225, x223, x184, x210); var x226: u64 = undefined; var x227: u1 = undefined; addcarryxU64(&x226, &x227, x225, x186, x212); var x228: u64 = undefined; var x229: u1 = undefined; addcarryxU64(&x228, &x229, x227, x188, x214); var x230: u64 = undefined; var x231: u1 = undefined; addcarryxU64(&x230, &x231, x229, x190, x216); var x232: u64 = undefined; var x233: u1 = undefined; addcarryxU64(&x232, &x233, x231, x192, x218); var x234: u64 = undefined; var x235: u64 = undefined; mulxU64(&x234, &x235, x3, 0x25a89bcdd12a); var x236: u64 = undefined; var x237: u64 = undefined; mulxU64(&x236, &x237, x3, 0x69e16a61c7686d9a); var x238: u64 = undefined; var x239: u64 = undefined; mulxU64(&x238, &x239, x3, 0xabcd92bf2dde347e); var x240: u64 = undefined; var x241: u64 = undefined; mulxU64(&x240, &x241, x3, 0x175cc6af8d6c7c0b); var x242: u64 = undefined; var x243: u64 = undefined; mulxU64(&x242, &x243, x3, 0xab27973f8311688d); var x244: u64 = undefined; var x245: u64 = undefined; mulxU64(&x244, &x245, x3, 0xacec7367768798c2); var x246: u64 = undefined; var x247: u64 = undefined; mulxU64(&x246, &x247, x3, 0x28e55b65dcd69b30); var x248: u64 = undefined; var x249: u1 = undefined; addcarryxU64(&x248, &x249, 0x0, x247, x244); var x250: u64 = undefined; var x251: u1 = undefined; addcarryxU64(&x250, &x251, x249, x245, x242); var x252: u64 = undefined; var x253: u1 = undefined; addcarryxU64(&x252, &x253, x251, x243, x240); var x254: u64 = undefined; var x255: u1 = undefined; addcarryxU64(&x254, &x255, x253, x241, x238); var x256: u64 = undefined; var x257: u1 = undefined; addcarryxU64(&x256, &x257, x255, x239, x236); var x258: u64 = undefined; var x259: u1 = undefined; addcarryxU64(&x258, &x259, x257, x237, x234); var x260: u64 = undefined; var x261: u1 = undefined; addcarryxU64(&x260, &x261, 0x0, x222, x246); var x262: u64 = undefined; var x263: u1 = undefined; addcarryxU64(&x262, &x263, x261, x224, x248); var x264: u64 = undefined; var x265: u1 = undefined; addcarryxU64(&x264, &x265, x263, x226, x250); var x266: u64 = undefined; var x267: u1 = undefined; addcarryxU64(&x266, &x267, x265, x228, x252); var x268: u64 = undefined; var x269: u1 = undefined; addcarryxU64(&x268, &x269, x267, x230, x254); var x270: u64 = undefined; var x271: u1 = undefined; addcarryxU64(&x270, &x271, x269, x232, x256); var x272: u64 = undefined; var x273: u1 = undefined; addcarryxU64(&x272, &x273, x271, ((cast(u64, x233) + (cast(u64, x193) + (cast(u64, x179) + x155))) + (cast(u64, x219) + x195)), x258); var x274: u64 = undefined; var x275: u64 = undefined; mulxU64(&x274, &x275, x260, 0x2341f27177344); var x276: u64 = undefined; var x277: u64 = undefined; mulxU64(&x276, &x277, x260, 0x6cfc5fd681c52056); var x278: u64 = undefined; var x279: u64 = undefined; mulxU64(&x278, &x279, x260, 0x7bc65c783158aea3); var x280: u64 = undefined; var x281: u64 = undefined; mulxU64(&x280, &x281, x260, 0xfdc1767ae2ffffff); var x282: u64 = undefined; var x283: u64 = undefined; mulxU64(&x282, &x283, x260, 0xffffffffffffffff); var x284: u64 = undefined; var x285: u64 = undefined; mulxU64(&x284, &x285, x260, 0xffffffffffffffff); var x286: u64 = undefined; var x287: u64 = undefined; mulxU64(&x286, &x287, x260, 0xffffffffffffffff); var x288: u64 = undefined; var x289: u1 = undefined; addcarryxU64(&x288, &x289, 0x0, x287, x284); var x290: u64 = undefined; var x291: u1 = undefined; addcarryxU64(&x290, &x291, x289, x285, x282); var x292: u64 = undefined; var x293: u1 = undefined; addcarryxU64(&x292, &x293, x291, x283, x280); var x294: u64 = undefined; var x295: u1 = undefined; addcarryxU64(&x294, &x295, x293, x281, x278); var x296: u64 = undefined; var x297: u1 = undefined; addcarryxU64(&x296, &x297, x295, x279, x276); var x298: u64 = undefined; var x299: u1 = undefined; addcarryxU64(&x298, &x299, x297, x277, x274); var x300: u64 = undefined; var x301: u1 = undefined; addcarryxU64(&x300, &x301, 0x0, x260, x286); var x302: u64 = undefined; var x303: u1 = undefined; addcarryxU64(&x302, &x303, x301, x262, x288); var x304: u64 = undefined; var x305: u1 = undefined; addcarryxU64(&x304, &x305, x303, x264, x290); var x306: u64 = undefined; var x307: u1 = undefined; addcarryxU64(&x306, &x307, x305, x266, x292); var x308: u64 = undefined; var x309: u1 = undefined; addcarryxU64(&x308, &x309, x307, x268, x294); var x310: u64 = undefined; var x311: u1 = undefined; addcarryxU64(&x310, &x311, x309, x270, x296); var x312: u64 = undefined; var x313: u1 = undefined; addcarryxU64(&x312, &x313, x311, x272, x298); var x314: u64 = undefined; var x315: u64 = undefined; mulxU64(&x314, &x315, x4, 0x25a89bcdd12a); var x316: u64 = undefined; var x317: u64 = undefined; mulxU64(&x316, &x317, x4, 0x69e16a61c7686d9a); var x318: u64 = undefined; var x319: u64 = undefined; mulxU64(&x318, &x319, x4, 0xabcd92bf2dde347e); var x320: u64 = undefined; var x321: u64 = undefined; mulxU64(&x320, &x321, x4, 0x175cc6af8d6c7c0b); var x322: u64 = undefined; var x323: u64 = undefined; mulxU64(&x322, &x323, x4, 0xab27973f8311688d); var x324: u64 = undefined; var x325: u64 = undefined; mulxU64(&x324, &x325, x4, 0xacec7367768798c2); var x326: u64 = undefined; var x327: u64 = undefined; mulxU64(&x326, &x327, x4, 0x28e55b65dcd69b30); var x328: u64 = undefined; var x329: u1 = undefined; addcarryxU64(&x328, &x329, 0x0, x327, x324); var x330: u64 = undefined; var x331: u1 = undefined; addcarryxU64(&x330, &x331, x329, x325, x322); var x332: u64 = undefined; var x333: u1 = undefined; addcarryxU64(&x332, &x333, x331, x323, x320); var x334: u64 = undefined; var x335: u1 = undefined; addcarryxU64(&x334, &x335, x333, x321, x318); var x336: u64 = undefined; var x337: u1 = undefined; addcarryxU64(&x336, &x337, x335, x319, x316); var x338: u64 = undefined; var x339: u1 = undefined; addcarryxU64(&x338, &x339, x337, x317, x314); var x340: u64 = undefined; var x341: u1 = undefined; addcarryxU64(&x340, &x341, 0x0, x302, x326); var x342: u64 = undefined; var x343: u1 = undefined; addcarryxU64(&x342, &x343, x341, x304, x328); var x344: u64 = undefined; var x345: u1 = undefined; addcarryxU64(&x344, &x345, x343, x306, x330); var x346: u64 = undefined; var x347: u1 = undefined; addcarryxU64(&x346, &x347, x345, x308, x332); var x348: u64 = undefined; var x349: u1 = undefined; addcarryxU64(&x348, &x349, x347, x310, x334); var x350: u64 = undefined; var x351: u1 = undefined; addcarryxU64(&x350, &x351, x349, x312, x336); var x352: u64 = undefined; var x353: u1 = undefined; addcarryxU64(&x352, &x353, x351, ((cast(u64, x313) + (cast(u64, x273) + (cast(u64, x259) + x235))) + (cast(u64, x299) + x275)), x338); var x354: u64 = undefined; var x355: u64 = undefined; mulxU64(&x354, &x355, x340, 0x2341f27177344); var x356: u64 = undefined; var x357: u64 = undefined; mulxU64(&x356, &x357, x340, 0x6cfc5fd681c52056); var x358: u64 = undefined; var x359: u64 = undefined; mulxU64(&x358, &x359, x340, 0x7bc65c783158aea3); var x360: u64 = undefined; var x361: u64 = undefined; mulxU64(&x360, &x361, x340, 0xfdc1767ae2ffffff); var x362: u64 = undefined; var x363: u64 = undefined; mulxU64(&x362, &x363, x340, 0xffffffffffffffff); var x364: u64 = undefined; var x365: u64 = undefined; mulxU64(&x364, &x365, x340, 0xffffffffffffffff); var x366: u64 = undefined; var x367: u64 = undefined; mulxU64(&x366, &x367, x340, 0xffffffffffffffff); var x368: u64 = undefined; var x369: u1 = undefined; addcarryxU64(&x368, &x369, 0x0, x367, x364); var x370: u64 = undefined; var x371: u1 = undefined; addcarryxU64(&x370, &x371, x369, x365, x362); var x372: u64 = undefined; var x373: u1 = undefined; addcarryxU64(&x372, &x373, x371, x363, x360); var x374: u64 = undefined; var x375: u1 = undefined; addcarryxU64(&x374, &x375, x373, x361, x358); var x376: u64 = undefined; var x377: u1 = undefined; addcarryxU64(&x376, &x377, x375, x359, x356); var x378: u64 = undefined; var x379: u1 = undefined; addcarryxU64(&x378, &x379, x377, x357, x354); var x380: u64 = undefined; var x381: u1 = undefined; addcarryxU64(&x380, &x381, 0x0, x340, x366); var x382: u64 = undefined; var x383: u1 = undefined; addcarryxU64(&x382, &x383, x381, x342, x368); var x384: u64 = undefined; var x385: u1 = undefined; addcarryxU64(&x384, &x385, x383, x344, x370); var x386: u64 = undefined; var x387: u1 = undefined; addcarryxU64(&x386, &x387, x385, x346, x372); var x388: u64 = undefined; var x389: u1 = undefined; addcarryxU64(&x388, &x389, x387, x348, x374); var x390: u64 = undefined; var x391: u1 = undefined; addcarryxU64(&x390, &x391, x389, x350, x376); var x392: u64 = undefined; var x393: u1 = undefined; addcarryxU64(&x392, &x393, x391, x352, x378); var x394: u64 = undefined; var x395: u64 = undefined; mulxU64(&x394, &x395, x5, 0x25a89bcdd12a); var x396: u64 = undefined; var x397: u64 = undefined; mulxU64(&x396, &x397, x5, 0x69e16a61c7686d9a); var x398: u64 = undefined; var x399: u64 = undefined; mulxU64(&x398, &x399, x5, 0xabcd92bf2dde347e); var x400: u64 = undefined; var x401: u64 = undefined; mulxU64(&x400, &x401, x5, 0x175cc6af8d6c7c0b); var x402: u64 = undefined; var x403: u64 = undefined; mulxU64(&x402, &x403, x5, 0xab27973f8311688d); var x404: u64 = undefined; var x405: u64 = undefined; mulxU64(&x404, &x405, x5, 0xacec7367768798c2); var x406: u64 = undefined; var x407: u64 = undefined; mulxU64(&x406, &x407, x5, 0x28e55b65dcd69b30); var x408: u64 = undefined; var x409: u1 = undefined; addcarryxU64(&x408, &x409, 0x0, x407, x404); var x410: u64 = undefined; var x411: u1 = undefined; addcarryxU64(&x410, &x411, x409, x405, x402); var x412: u64 = undefined; var x413: u1 = undefined; addcarryxU64(&x412, &x413, x411, x403, x400); var x414: u64 = undefined; var x415: u1 = undefined; addcarryxU64(&x414, &x415, x413, x401, x398); var x416: u64 = undefined; var x417: u1 = undefined; addcarryxU64(&x416, &x417, x415, x399, x396); var x418: u64 = undefined; var x419: u1 = undefined; addcarryxU64(&x418, &x419, x417, x397, x394); var x420: u64 = undefined; var x421: u1 = undefined; addcarryxU64(&x420, &x421, 0x0, x382, x406); var x422: u64 = undefined; var x423: u1 = undefined; addcarryxU64(&x422, &x423, x421, x384, x408); var x424: u64 = undefined; var x425: u1 = undefined; addcarryxU64(&x424, &x425, x423, x386, x410); var x426: u64 = undefined; var x427: u1 = undefined; addcarryxU64(&x426, &x427, x425, x388, x412); var x428: u64 = undefined; var x429: u1 = undefined; addcarryxU64(&x428, &x429, x427, x390, x414); var x430: u64 = undefined; var x431: u1 = undefined; addcarryxU64(&x430, &x431, x429, x392, x416); var x432: u64 = undefined; var x433: u1 = undefined; addcarryxU64(&x432, &x433, x431, ((cast(u64, x393) + (cast(u64, x353) + (cast(u64, x339) + x315))) + (cast(u64, x379) + x355)), x418); var x434: u64 = undefined; var x435: u64 = undefined; mulxU64(&x434, &x435, x420, 0x2341f27177344); var x436: u64 = undefined; var x437: u64 = undefined; mulxU64(&x436, &x437, x420, 0x6cfc5fd681c52056); var x438: u64 = undefined; var x439: u64 = undefined; mulxU64(&x438, &x439, x420, 0x7bc65c783158aea3); var x440: u64 = undefined; var x441: u64 = undefined; mulxU64(&x440, &x441, x420, 0xfdc1767ae2ffffff); var x442: u64 = undefined; var x443: u64 = undefined; mulxU64(&x442, &x443, x420, 0xffffffffffffffff); var x444: u64 = undefined; var x445: u64 = undefined; mulxU64(&x444, &x445, x420, 0xffffffffffffffff); var x446: u64 = undefined; var x447: u64 = undefined; mulxU64(&x446, &x447, x420, 0xffffffffffffffff); var x448: u64 = undefined; var x449: u1 = undefined; addcarryxU64(&x448, &x449, 0x0, x447, x444); var x450: u64 = undefined; var x451: u1 = undefined; addcarryxU64(&x450, &x451, x449, x445, x442); var x452: u64 = undefined; var x453: u1 = undefined; addcarryxU64(&x452, &x453, x451, x443, x440); var x454: u64 = undefined; var x455: u1 = undefined; addcarryxU64(&x454, &x455, x453, x441, x438); var x456: u64 = undefined; var x457: u1 = undefined; addcarryxU64(&x456, &x457, x455, x439, x436); var x458: u64 = undefined; var x459: u1 = undefined; addcarryxU64(&x458, &x459, x457, x437, x434); var x460: u64 = undefined; var x461: u1 = undefined; addcarryxU64(&x460, &x461, 0x0, x420, x446); var x462: u64 = undefined; var x463: u1 = undefined; addcarryxU64(&x462, &x463, x461, x422, x448); var x464: u64 = undefined; var x465: u1 = undefined; addcarryxU64(&x464, &x465, x463, x424, x450); var x466: u64 = undefined; var x467: u1 = undefined; addcarryxU64(&x466, &x467, x465, x426, x452); var x468: u64 = undefined; var x469: u1 = undefined; addcarryxU64(&x468, &x469, x467, x428, x454); var x470: u64 = undefined; var x471: u1 = undefined; addcarryxU64(&x470, &x471, x469, x430, x456); var x472: u64 = undefined; var x473: u1 = undefined; addcarryxU64(&x472, &x473, x471, x432, x458); var x474: u64 = undefined; var x475: u64 = undefined; mulxU64(&x474, &x475, x6, 0x25a89bcdd12a); var x476: u64 = undefined; var x477: u64 = undefined; mulxU64(&x476, &x477, x6, 0x69e16a61c7686d9a); var x478: u64 = undefined; var x479: u64 = undefined; mulxU64(&x478, &x479, x6, 0xabcd92bf2dde347e); var x480: u64 = undefined; var x481: u64 = undefined; mulxU64(&x480, &x481, x6, 0x175cc6af8d6c7c0b); var x482: u64 = undefined; var x483: u64 = undefined; mulxU64(&x482, &x483, x6, 0xab27973f8311688d); var x484: u64 = undefined; var x485: u64 = undefined; mulxU64(&x484, &x485, x6, 0xacec7367768798c2); var x486: u64 = undefined; var x487: u64 = undefined; mulxU64(&x486, &x487, x6, 0x28e55b65dcd69b30); var x488: u64 = undefined; var x489: u1 = undefined; addcarryxU64(&x488, &x489, 0x0, x487, x484); var x490: u64 = undefined; var x491: u1 = undefined; addcarryxU64(&x490, &x491, x489, x485, x482); var x492: u64 = undefined; var x493: u1 = undefined; addcarryxU64(&x492, &x493, x491, x483, x480); var x494: u64 = undefined; var x495: u1 = undefined; addcarryxU64(&x494, &x495, x493, x481, x478); var x496: u64 = undefined; var x497: u1 = undefined; addcarryxU64(&x496, &x497, x495, x479, x476); var x498: u64 = undefined; var x499: u1 = undefined; addcarryxU64(&x498, &x499, x497, x477, x474); var x500: u64 = undefined; var x501: u1 = undefined; addcarryxU64(&x500, &x501, 0x0, x462, x486); var x502: u64 = undefined; var x503: u1 = undefined; addcarryxU64(&x502, &x503, x501, x464, x488); var x504: u64 = undefined; var x505: u1 = undefined; addcarryxU64(&x504, &x505, x503, x466, x490); var x506: u64 = undefined; var x507: u1 = undefined; addcarryxU64(&x506, &x507, x505, x468, x492); var x508: u64 = undefined; var x509: u1 = undefined; addcarryxU64(&x508, &x509, x507, x470, x494); var x510: u64 = undefined; var x511: u1 = undefined; addcarryxU64(&x510, &x511, x509, x472, x496); var x512: u64 = undefined; var x513: u1 = undefined; addcarryxU64(&x512, &x513, x511, ((cast(u64, x473) + (cast(u64, x433) + (cast(u64, x419) + x395))) + (cast(u64, x459) + x435)), x498); var x514: u64 = undefined; var x515: u64 = undefined; mulxU64(&x514, &x515, x500, 0x2341f27177344); var x516: u64 = undefined; var x517: u64 = undefined; mulxU64(&x516, &x517, x500, 0x6cfc5fd681c52056); var x518: u64 = undefined; var x519: u64 = undefined; mulxU64(&x518, &x519, x500, 0x7bc65c783158aea3); var x520: u64 = undefined; var x521: u64 = undefined; mulxU64(&x520, &x521, x500, 0xfdc1767ae2ffffff); var x522: u64 = undefined; var x523: u64 = undefined; mulxU64(&x522, &x523, x500, 0xffffffffffffffff); var x524: u64 = undefined; var x525: u64 = undefined; mulxU64(&x524, &x525, x500, 0xffffffffffffffff); var x526: u64 = undefined; var x527: u64 = undefined; mulxU64(&x526, &x527, x500, 0xffffffffffffffff); var x528: u64 = undefined; var x529: u1 = undefined; addcarryxU64(&x528, &x529, 0x0, x527, x524); var x530: u64 = undefined; var x531: u1 = undefined; addcarryxU64(&x530, &x531, x529, x525, x522); var x532: u64 = undefined; var x533: u1 = undefined; addcarryxU64(&x532, &x533, x531, x523, x520); var x534: u64 = undefined; var x535: u1 = undefined; addcarryxU64(&x534, &x535, x533, x521, x518); var x536: u64 = undefined; var x537: u1 = undefined; addcarryxU64(&x536, &x537, x535, x519, x516); var x538: u64 = undefined; var x539: u1 = undefined; addcarryxU64(&x538, &x539, x537, x517, x514); var x540: u64 = undefined; var x541: u1 = undefined; addcarryxU64(&x540, &x541, 0x0, x500, x526); var x542: u64 = undefined; var x543: u1 = undefined; addcarryxU64(&x542, &x543, x541, x502, x528); var x544: u64 = undefined; var x545: u1 = undefined; addcarryxU64(&x544, &x545, x543, x504, x530); var x546: u64 = undefined; var x547: u1 = undefined; addcarryxU64(&x546, &x547, x545, x506, x532); var x548: u64 = undefined; var x549: u1 = undefined; addcarryxU64(&x548, &x549, x547, x508, x534); var x550: u64 = undefined; var x551: u1 = undefined; addcarryxU64(&x550, &x551, x549, x510, x536); var x552: u64 = undefined; var x553: u1 = undefined; addcarryxU64(&x552, &x553, x551, x512, x538); const x554 = ((cast(u64, x553) + (cast(u64, x513) + (cast(u64, x499) + x475))) + (cast(u64, x539) + x515)); var x555: u64 = undefined; var x556: u1 = undefined; subborrowxU64(&x555, &x556, 0x0, x542, 0xffffffffffffffff); var x557: u64 = undefined; var x558: u1 = undefined; subborrowxU64(&x557, &x558, x556, x544, 0xffffffffffffffff); var x559: u64 = undefined; var x560: u1 = undefined; subborrowxU64(&x559, &x560, x558, x546, 0xffffffffffffffff); var x561: u64 = undefined; var x562: u1 = undefined; subborrowxU64(&x561, &x562, x560, x548, 0xfdc1767ae2ffffff); var x563: u64 = undefined; var x564: u1 = undefined; subborrowxU64(&x563, &x564, x562, x550, 0x7bc65c783158aea3); var x565: u64 = undefined; var x566: u1 = undefined; subborrowxU64(&x565, &x566, x564, x552, 0x6cfc5fd681c52056); var x567: u64 = undefined; var x568: u1 = undefined; subborrowxU64(&x567, &x568, x566, x554, 0x2341f27177344); var x569: u64 = undefined; var x570: u1 = undefined; subborrowxU64(&x569, &x570, x568, cast(u64, 0x0), cast(u64, 0x0)); var x571: u64 = undefined; cmovznzU64(&x571, x570, x555, x542); var x572: u64 = undefined; cmovznzU64(&x572, x570, x557, x544); var x573: u64 = undefined; cmovznzU64(&x573, x570, x559, x546); var x574: u64 = undefined; cmovznzU64(&x574, x570, x561, x548); var x575: u64 = undefined; cmovznzU64(&x575, x570, x563, x550); var x576: u64 = undefined; cmovznzU64(&x576, x570, x565, x552); var x577: u64 = undefined; cmovznzU64(&x577, x570, x567, x554); out1[0] = x571; out1[1] = x572; out1[2] = x573; out1[3] = x574; out1[4] = x575; out1[5] = x576; out1[6] = x577; } /// The function nonzero outputs a single non-zero word if the input is non-zero and zero otherwise. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = 0 ↔ eval (from_montgomery arg1) mod m = 0 /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] pub fn nonzero(out1: *u64, arg1: [7]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = ((arg1[0]) | ((arg1[1]) | ((arg1[2]) | ((arg1[3]) | ((arg1[4]) | ((arg1[5]) | (arg1[6]))))))); out1.* = x1; } /// The function selectznz is a multi-limb conditional select. /// /// Postconditions: /// out1 = (if arg1 = 0 then arg2 else arg3) /// /// Input Bounds: /// arg1: [0x0 ~> 0x1] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn selectznz(out1: *[7]u64, arg1: u1, arg2: [7]u64, arg3: [7]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; cmovznzU64(&x1, arg1, (arg2[0]), (arg3[0])); var x2: u64 = undefined; cmovznzU64(&x2, arg1, (arg2[1]), (arg3[1])); var x3: u64 = undefined; cmovznzU64(&x3, arg1, (arg2[2]), (arg3[2])); var x4: u64 = undefined; cmovznzU64(&x4, arg1, (arg2[3]), (arg3[3])); var x5: u64 = undefined; cmovznzU64(&x5, arg1, (arg2[4]), (arg3[4])); var x6: u64 = undefined; cmovznzU64(&x6, arg1, (arg2[5]), (arg3[5])); var x7: u64 = undefined; cmovznzU64(&x7, arg1, (arg2[6]), (arg3[6])); out1[0] = x1; out1[1] = x2; out1[2] = x3; out1[3] = x4; out1[4] = x5; out1[5] = x6; out1[6] = x7; } /// The function toBytes serializes a field element NOT in the Montgomery domain to bytes in little-endian order. /// /// Preconditions: /// 0 ≤ eval arg1 < m /// Postconditions: /// out1 = map (λ x, ⌊((eval arg1 mod m) mod 2^(8 * (x + 1))) / 2^(8 * x)⌋) [0..54] /// /// Input Bounds: /// arg1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x3ffffffffffff]] /// Output Bounds: /// out1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] pub fn toBytes(out1: *[55]u8, arg1: [7]u64) void { @setRuntimeSafety(mode == .Debug); const x1 = (arg1[6]); const x2 = (arg1[5]); const x3 = (arg1[4]); const x4 = (arg1[3]); const x5 = (arg1[2]); const x6 = (arg1[1]); const x7 = (arg1[0]); const x8 = cast(u8, (x7 & cast(u64, 0xff))); const x9 = (x7 >> 8); const x10 = cast(u8, (x9 & cast(u64, 0xff))); const x11 = (x9 >> 8); const x12 = cast(u8, (x11 & cast(u64, 0xff))); const x13 = (x11 >> 8); const x14 = cast(u8, (x13 & cast(u64, 0xff))); const x15 = (x13 >> 8); const x16 = cast(u8, (x15 & cast(u64, 0xff))); const x17 = (x15 >> 8); const x18 = cast(u8, (x17 & cast(u64, 0xff))); const x19 = (x17 >> 8); const x20 = cast(u8, (x19 & cast(u64, 0xff))); const x21 = cast(u8, (x19 >> 8)); const x22 = cast(u8, (x6 & cast(u64, 0xff))); const x23 = (x6 >> 8); const x24 = cast(u8, (x23 & cast(u64, 0xff))); const x25 = (x23 >> 8); const x26 = cast(u8, (x25 & cast(u64, 0xff))); const x27 = (x25 >> 8); const x28 = cast(u8, (x27 & cast(u64, 0xff))); const x29 = (x27 >> 8); const x30 = cast(u8, (x29 & cast(u64, 0xff))); const x31 = (x29 >> 8); const x32 = cast(u8, (x31 & cast(u64, 0xff))); const x33 = (x31 >> 8); const x34 = cast(u8, (x33 & cast(u64, 0xff))); const x35 = cast(u8, (x33 >> 8)); const x36 = cast(u8, (x5 & cast(u64, 0xff))); const x37 = (x5 >> 8); const x38 = cast(u8, (x37 & cast(u64, 0xff))); const x39 = (x37 >> 8); const x40 = cast(u8, (x39 & cast(u64, 0xff))); const x41 = (x39 >> 8); const x42 = cast(u8, (x41 & cast(u64, 0xff))); const x43 = (x41 >> 8); const x44 = cast(u8, (x43 & cast(u64, 0xff))); const x45 = (x43 >> 8); const x46 = cast(u8, (x45 & cast(u64, 0xff))); const x47 = (x45 >> 8); const x48 = cast(u8, (x47 & cast(u64, 0xff))); const x49 = cast(u8, (x47 >> 8)); const x50 = cast(u8, (x4 & cast(u64, 0xff))); const x51 = (x4 >> 8); const x52 = cast(u8, (x51 & cast(u64, 0xff))); const x53 = (x51 >> 8); const x54 = cast(u8, (x53 & cast(u64, 0xff))); const x55 = (x53 >> 8); const x56 = cast(u8, (x55 & cast(u64, 0xff))); const x57 = (x55 >> 8); const x58 = cast(u8, (x57 & cast(u64, 0xff))); const x59 = (x57 >> 8); const x60 = cast(u8, (x59 & cast(u64, 0xff))); const x61 = (x59 >> 8); const x62 = cast(u8, (x61 & cast(u64, 0xff))); const x63 = cast(u8, (x61 >> 8)); const x64 = cast(u8, (x3 & cast(u64, 0xff))); const x65 = (x3 >> 8); const x66 = cast(u8, (x65 & cast(u64, 0xff))); const x67 = (x65 >> 8); const x68 = cast(u8, (x67 & cast(u64, 0xff))); const x69 = (x67 >> 8); const x70 = cast(u8, (x69 & cast(u64, 0xff))); const x71 = (x69 >> 8); const x72 = cast(u8, (x71 & cast(u64, 0xff))); const x73 = (x71 >> 8); const x74 = cast(u8, (x73 & cast(u64, 0xff))); const x75 = (x73 >> 8); const x76 = cast(u8, (x75 & cast(u64, 0xff))); const x77 = cast(u8, (x75 >> 8)); const x78 = cast(u8, (x2 & cast(u64, 0xff))); const x79 = (x2 >> 8); const x80 = cast(u8, (x79 & cast(u64, 0xff))); const x81 = (x79 >> 8); const x82 = cast(u8, (x81 & cast(u64, 0xff))); const x83 = (x81 >> 8); const x84 = cast(u8, (x83 & cast(u64, 0xff))); const x85 = (x83 >> 8); const x86 = cast(u8, (x85 & cast(u64, 0xff))); const x87 = (x85 >> 8); const x88 = cast(u8, (x87 & cast(u64, 0xff))); const x89 = (x87 >> 8); const x90 = cast(u8, (x89 & cast(u64, 0xff))); const x91 = cast(u8, (x89 >> 8)); const x92 = cast(u8, (x1 & cast(u64, 0xff))); const x93 = (x1 >> 8); const x94 = cast(u8, (x93 & cast(u64, 0xff))); const x95 = (x93 >> 8); const x96 = cast(u8, (x95 & cast(u64, 0xff))); const x97 = (x95 >> 8); const x98 = cast(u8, (x97 & cast(u64, 0xff))); const x99 = (x97 >> 8); const x100 = cast(u8, (x99 & cast(u64, 0xff))); const x101 = (x99 >> 8); const x102 = cast(u8, (x101 & cast(u64, 0xff))); const x103 = cast(u8, (x101 >> 8)); out1[0] = x8; out1[1] = x10; out1[2] = x12; out1[3] = x14; out1[4] = x16; out1[5] = x18; out1[6] = x20; out1[7] = x21; out1[8] = x22; out1[9] = x24; out1[10] = x26; out1[11] = x28; out1[12] = x30; out1[13] = x32; out1[14] = x34; out1[15] = x35; out1[16] = x36; out1[17] = x38; out1[18] = x40; out1[19] = x42; out1[20] = x44; out1[21] = x46; out1[22] = x48; out1[23] = x49; out1[24] = x50; out1[25] = x52; out1[26] = x54; out1[27] = x56; out1[28] = x58; out1[29] = x60; out1[30] = x62; out1[31] = x63; out1[32] = x64; out1[33] = x66; out1[34] = x68; out1[35] = x70; out1[36] = x72; out1[37] = x74; out1[38] = x76; out1[39] = x77; out1[40] = x78; out1[41] = x80; out1[42] = x82; out1[43] = x84; out1[44] = x86; out1[45] = x88; out1[46] = x90; out1[47] = x91; out1[48] = x92; out1[49] = x94; out1[50] = x96; out1[51] = x98; out1[52] = x100; out1[53] = x102; out1[54] = x103; } /// The function fromBytes deserializes a field element NOT in the Montgomery domain from bytes in little-endian order. /// /// Preconditions: /// 0 ≤ bytes_eval arg1 < m /// Postconditions: /// eval out1 mod m = bytes_eval arg1 mod m /// 0 ≤ eval out1 < m /// /// Input Bounds: /// arg1: [[0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0xff], [0x0 ~> 0x3]] /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0x3ffffffffffff]] pub fn fromBytes(out1: *[7]u64, arg1: [55]u8) void { @setRuntimeSafety(mode == .Debug); const x1 = (cast(u64, (arg1[54])) << 48); const x2 = (cast(u64, (arg1[53])) << 40); const x3 = (cast(u64, (arg1[52])) << 32); const x4 = (cast(u64, (arg1[51])) << 24); const x5 = (cast(u64, (arg1[50])) << 16); const x6 = (cast(u64, (arg1[49])) << 8); const x7 = (arg1[48]); const x8 = (cast(u64, (arg1[47])) << 56); const x9 = (cast(u64, (arg1[46])) << 48); const x10 = (cast(u64, (arg1[45])) << 40); const x11 = (cast(u64, (arg1[44])) << 32); const x12 = (cast(u64, (arg1[43])) << 24); const x13 = (cast(u64, (arg1[42])) << 16); const x14 = (cast(u64, (arg1[41])) << 8); const x15 = (arg1[40]); const x16 = (cast(u64, (arg1[39])) << 56); const x17 = (cast(u64, (arg1[38])) << 48); const x18 = (cast(u64, (arg1[37])) << 40); const x19 = (cast(u64, (arg1[36])) << 32); const x20 = (cast(u64, (arg1[35])) << 24); const x21 = (cast(u64, (arg1[34])) << 16); const x22 = (cast(u64, (arg1[33])) << 8); const x23 = (arg1[32]); const x24 = (cast(u64, (arg1[31])) << 56); const x25 = (cast(u64, (arg1[30])) << 48); const x26 = (cast(u64, (arg1[29])) << 40); const x27 = (cast(u64, (arg1[28])) << 32); const x28 = (cast(u64, (arg1[27])) << 24); const x29 = (cast(u64, (arg1[26])) << 16); const x30 = (cast(u64, (arg1[25])) << 8); const x31 = (arg1[24]); const x32 = (cast(u64, (arg1[23])) << 56); const x33 = (cast(u64, (arg1[22])) << 48); const x34 = (cast(u64, (arg1[21])) << 40); const x35 = (cast(u64, (arg1[20])) << 32); const x36 = (cast(u64, (arg1[19])) << 24); const x37 = (cast(u64, (arg1[18])) << 16); const x38 = (cast(u64, (arg1[17])) << 8); const x39 = (arg1[16]); const x40 = (cast(u64, (arg1[15])) << 56); const x41 = (cast(u64, (arg1[14])) << 48); const x42 = (cast(u64, (arg1[13])) << 40); const x43 = (cast(u64, (arg1[12])) << 32); const x44 = (cast(u64, (arg1[11])) << 24); const x45 = (cast(u64, (arg1[10])) << 16); const x46 = (cast(u64, (arg1[9])) << 8); const x47 = (arg1[8]); const x48 = (cast(u64, (arg1[7])) << 56); const x49 = (cast(u64, (arg1[6])) << 48); const x50 = (cast(u64, (arg1[5])) << 40); const x51 = (cast(u64, (arg1[4])) << 32); const x52 = (cast(u64, (arg1[3])) << 24); const x53 = (cast(u64, (arg1[2])) << 16); const x54 = (cast(u64, (arg1[1])) << 8); const x55 = (arg1[0]); const x56 = (x54 + cast(u64, x55)); const x57 = (x53 + x56); const x58 = (x52 + x57); const x59 = (x51 + x58); const x60 = (x50 + x59); const x61 = (x49 + x60); const x62 = (x48 + x61); const x63 = (x46 + cast(u64, x47)); const x64 = (x45 + x63); const x65 = (x44 + x64); const x66 = (x43 + x65); const x67 = (x42 + x66); const x68 = (x41 + x67); const x69 = (x40 + x68); const x70 = (x38 + cast(u64, x39)); const x71 = (x37 + x70); const x72 = (x36 + x71); const x73 = (x35 + x72); const x74 = (x34 + x73); const x75 = (x33 + x74); const x76 = (x32 + x75); const x77 = (x30 + cast(u64, x31)); const x78 = (x29 + x77); const x79 = (x28 + x78); const x80 = (x27 + x79); const x81 = (x26 + x80); const x82 = (x25 + x81); const x83 = (x24 + x82); const x84 = (x22 + cast(u64, x23)); const x85 = (x21 + x84); const x86 = (x20 + x85); const x87 = (x19 + x86); const x88 = (x18 + x87); const x89 = (x17 + x88); const x90 = (x16 + x89); const x91 = (x14 + cast(u64, x15)); const x92 = (x13 + x91); const x93 = (x12 + x92); const x94 = (x11 + x93); const x95 = (x10 + x94); const x96 = (x9 + x95); const x97 = (x8 + x96); const x98 = (x6 + cast(u64, x7)); const x99 = (x5 + x98); const x100 = (x4 + x99); const x101 = (x3 + x100); const x102 = (x2 + x101); const x103 = (x1 + x102); out1[0] = x62; out1[1] = x69; out1[2] = x76; out1[3] = x83; out1[4] = x90; out1[5] = x97; out1[6] = x103; } /// The function setOne returns the field element one in the Montgomery domain. /// /// Postconditions: /// eval (from_montgomery out1) mod m = 1 mod m /// 0 ≤ eval out1 < m /// pub fn setOne(out1: *MontgomeryDomainFieldElement) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0x742c; out1[1] = cast(u64, 0x0); out1[2] = cast(u64, 0x0); out1[3] = 0xb90ff404fc000000; out1[4] = 0xd801a4fb559facd4; out1[5] = 0xe93254545f77410c; out1[6] = 0xeceea7bd2eda; } /// The function msat returns the saturated representation of the prime modulus. /// /// Postconditions: /// twos_complement_eval out1 = m /// 0 ≤ eval out1 < m /// /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn msat(out1: *[8]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0xffffffffffffffff; out1[1] = 0xffffffffffffffff; out1[2] = 0xffffffffffffffff; out1[3] = 0xfdc1767ae2ffffff; out1[4] = 0x7bc65c783158aea3; out1[5] = 0x6cfc5fd681c52056; out1[6] = 0x2341f27177344; out1[7] = cast(u64, 0x0); } /// The function divstep computes a divstep. /// /// Preconditions: /// 0 ≤ eval arg4 < m /// 0 ≤ eval arg5 < m /// Postconditions: /// out1 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then 1 - arg1 else 1 + arg1) /// twos_complement_eval out2 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then twos_complement_eval arg3 else twos_complement_eval arg2) /// twos_complement_eval out3 = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then ⌊(twos_complement_eval arg3 - twos_complement_eval arg2) / 2⌋ else ⌊(twos_complement_eval arg3 + (twos_complement_eval arg3 mod 2) * twos_complement_eval arg2) / 2⌋) /// eval (from_montgomery out4) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (2 * eval (from_montgomery arg5)) mod m else (2 * eval (from_montgomery arg4)) mod m) /// eval (from_montgomery out5) mod m = (if 0 < arg1 ∧ (twos_complement_eval arg3) is odd then (eval (from_montgomery arg4) - eval (from_montgomery arg4)) mod m else (eval (from_montgomery arg5) + (twos_complement_eval arg3 mod 2) * eval (from_montgomery arg4)) mod m) /// 0 ≤ eval out5 < m /// 0 ≤ eval out5 < m /// 0 ≤ eval out2 < m /// 0 ≤ eval out3 < m /// /// Input Bounds: /// arg1: [0x0 ~> 0xffffffffffffffff] /// arg2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// arg5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// Output Bounds: /// out1: [0x0 ~> 0xffffffffffffffff] /// out2: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out3: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out4: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] /// out5: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstep(out1: *u64, out2: *[8]u64, out3: *[8]u64, out4: *[7]u64, out5: *[7]u64, arg1: u64, arg2: [8]u64, arg3: [8]u64, arg4: [7]u64, arg5: [7]u64) void { @setRuntimeSafety(mode == .Debug); var x1: u64 = undefined; var x2: u1 = undefined; addcarryxU64(&x1, &x2, 0x0, (~arg1), cast(u64, 0x1)); const x3 = (cast(u1, (x1 >> 63)) & cast(u1, ((arg3[0]) & cast(u64, 0x1)))); var x4: u64 = undefined; var x5: u1 = undefined; addcarryxU64(&x4, &x5, 0x0, (~arg1), cast(u64, 0x1)); var x6: u64 = undefined; cmovznzU64(&x6, x3, arg1, x4); var x7: u64 = undefined; cmovznzU64(&x7, x3, (arg2[0]), (arg3[0])); var x8: u64 = undefined; cmovznzU64(&x8, x3, (arg2[1]), (arg3[1])); var x9: u64 = undefined; cmovznzU64(&x9, x3, (arg2[2]), (arg3[2])); var x10: u64 = undefined; cmovznzU64(&x10, x3, (arg2[3]), (arg3[3])); var x11: u64 = undefined; cmovznzU64(&x11, x3, (arg2[4]), (arg3[4])); var x12: u64 = undefined; cmovznzU64(&x12, x3, (arg2[5]), (arg3[5])); var x13: u64 = undefined; cmovznzU64(&x13, x3, (arg2[6]), (arg3[6])); var x14: u64 = undefined; cmovznzU64(&x14, x3, (arg2[7]), (arg3[7])); var x15: u64 = undefined; var x16: u1 = undefined; addcarryxU64(&x15, &x16, 0x0, cast(u64, 0x1), (~(arg2[0]))); var x17: u64 = undefined; var x18: u1 = undefined; addcarryxU64(&x17, &x18, x16, cast(u64, 0x0), (~(arg2[1]))); var x19: u64 = undefined; var x20: u1 = undefined; addcarryxU64(&x19, &x20, x18, cast(u64, 0x0), (~(arg2[2]))); var x21: u64 = undefined; var x22: u1 = undefined; addcarryxU64(&x21, &x22, x20, cast(u64, 0x0), (~(arg2[3]))); var x23: u64 = undefined; var x24: u1 = undefined; addcarryxU64(&x23, &x24, x22, cast(u64, 0x0), (~(arg2[4]))); var x25: u64 = undefined; var x26: u1 = undefined; addcarryxU64(&x25, &x26, x24, cast(u64, 0x0), (~(arg2[5]))); var x27: u64 = undefined; var x28: u1 = undefined; addcarryxU64(&x27, &x28, x26, cast(u64, 0x0), (~(arg2[6]))); var x29: u64 = undefined; var x30: u1 = undefined; addcarryxU64(&x29, &x30, x28, cast(u64, 0x0), (~(arg2[7]))); var x31: u64 = undefined; cmovznzU64(&x31, x3, (arg3[0]), x15); var x32: u64 = undefined; cmovznzU64(&x32, x3, (arg3[1]), x17); var x33: u64 = undefined; cmovznzU64(&x33, x3, (arg3[2]), x19); var x34: u64 = undefined; cmovznzU64(&x34, x3, (arg3[3]), x21); var x35: u64 = undefined; cmovznzU64(&x35, x3, (arg3[4]), x23); var x36: u64 = undefined; cmovznzU64(&x36, x3, (arg3[5]), x25); var x37: u64 = undefined; cmovznzU64(&x37, x3, (arg3[6]), x27); var x38: u64 = undefined; cmovznzU64(&x38, x3, (arg3[7]), x29); var x39: u64 = undefined; cmovznzU64(&x39, x3, (arg4[0]), (arg5[0])); var x40: u64 = undefined; cmovznzU64(&x40, x3, (arg4[1]), (arg5[1])); var x41: u64 = undefined; cmovznzU64(&x41, x3, (arg4[2]), (arg5[2])); var x42: u64 = undefined; cmovznzU64(&x42, x3, (arg4[3]), (arg5[3])); var x43: u64 = undefined; cmovznzU64(&x43, x3, (arg4[4]), (arg5[4])); var x44: u64 = undefined; cmovznzU64(&x44, x3, (arg4[5]), (arg5[5])); var x45: u64 = undefined; cmovznzU64(&x45, x3, (arg4[6]), (arg5[6])); var x46: u64 = undefined; var x47: u1 = undefined; addcarryxU64(&x46, &x47, 0x0, x39, x39); var x48: u64 = undefined; var x49: u1 = undefined; addcarryxU64(&x48, &x49, x47, x40, x40); var x50: u64 = undefined; var x51: u1 = undefined; addcarryxU64(&x50, &x51, x49, x41, x41); var x52: u64 = undefined; var x53: u1 = undefined; addcarryxU64(&x52, &x53, x51, x42, x42); var x54: u64 = undefined; var x55: u1 = undefined; addcarryxU64(&x54, &x55, x53, x43, x43); var x56: u64 = undefined; var x57: u1 = undefined; addcarryxU64(&x56, &x57, x55, x44, x44); var x58: u64 = undefined; var x59: u1 = undefined; addcarryxU64(&x58, &x59, x57, x45, x45); var x60: u64 = undefined; var x61: u1 = undefined; subborrowxU64(&x60, &x61, 0x0, x46, 0xffffffffffffffff); var x62: u64 = undefined; var x63: u1 = undefined; subborrowxU64(&x62, &x63, x61, x48, 0xffffffffffffffff); var x64: u64 = undefined; var x65: u1 = undefined; subborrowxU64(&x64, &x65, x63, x50, 0xffffffffffffffff); var x66: u64 = undefined; var x67: u1 = undefined; subborrowxU64(&x66, &x67, x65, x52, 0xfdc1767ae2ffffff); var x68: u64 = undefined; var x69: u1 = undefined; subborrowxU64(&x68, &x69, x67, x54, 0x7bc65c783158aea3); var x70: u64 = undefined; var x71: u1 = undefined; subborrowxU64(&x70, &x71, x69, x56, 0x6cfc5fd681c52056); var x72: u64 = undefined; var x73: u1 = undefined; subborrowxU64(&x72, &x73, x71, x58, 0x2341f27177344); var x74: u64 = undefined; var x75: u1 = undefined; subborrowxU64(&x74, &x75, x73, cast(u64, x59), cast(u64, 0x0)); const x76 = (arg4[6]); const x77 = (arg4[5]); const x78 = (arg4[4]); const x79 = (arg4[3]); const x80 = (arg4[2]); const x81 = (arg4[1]); const x82 = (arg4[0]); var x83: u64 = undefined; var x84: u1 = undefined; subborrowxU64(&x83, &x84, 0x0, cast(u64, 0x0), x82); var x85: u64 = undefined; var x86: u1 = undefined; subborrowxU64(&x85, &x86, x84, cast(u64, 0x0), x81); var x87: u64 = undefined; var x88: u1 = undefined; subborrowxU64(&x87, &x88, x86, cast(u64, 0x0), x80); var x89: u64 = undefined; var x90: u1 = undefined; subborrowxU64(&x89, &x90, x88, cast(u64, 0x0), x79); var x91: u64 = undefined; var x92: u1 = undefined; subborrowxU64(&x91, &x92, x90, cast(u64, 0x0), x78); var x93: u64 = undefined; var x94: u1 = undefined; subborrowxU64(&x93, &x94, x92, cast(u64, 0x0), x77); var x95: u64 = undefined; var x96: u1 = undefined; subborrowxU64(&x95, &x96, x94, cast(u64, 0x0), x76); var x97: u64 = undefined; cmovznzU64(&x97, x96, cast(u64, 0x0), 0xffffffffffffffff); var x98: u64 = undefined; var x99: u1 = undefined; addcarryxU64(&x98, &x99, 0x0, x83, x97); var x100: u64 = undefined; var x101: u1 = undefined; addcarryxU64(&x100, &x101, x99, x85, x97); var x102: u64 = undefined; var x103: u1 = undefined; addcarryxU64(&x102, &x103, x101, x87, x97); var x104: u64 = undefined; var x105: u1 = undefined; addcarryxU64(&x104, &x105, x103, x89, (x97 & 0xfdc1767ae2ffffff)); var x106: u64 = undefined; var x107: u1 = undefined; addcarryxU64(&x106, &x107, x105, x91, (x97 & 0x7bc65c783158aea3)); var x108: u64 = undefined; var x109: u1 = undefined; addcarryxU64(&x108, &x109, x107, x93, (x97 & 0x6cfc5fd681c52056)); var x110: u64 = undefined; var x111: u1 = undefined; addcarryxU64(&x110, &x111, x109, x95, (x97 & 0x2341f27177344)); var x112: u64 = undefined; cmovznzU64(&x112, x3, (arg5[0]), x98); var x113: u64 = undefined; cmovznzU64(&x113, x3, (arg5[1]), x100); var x114: u64 = undefined; cmovznzU64(&x114, x3, (arg5[2]), x102); var x115: u64 = undefined; cmovznzU64(&x115, x3, (arg5[3]), x104); var x116: u64 = undefined; cmovznzU64(&x116, x3, (arg5[4]), x106); var x117: u64 = undefined; cmovznzU64(&x117, x3, (arg5[5]), x108); var x118: u64 = undefined; cmovznzU64(&x118, x3, (arg5[6]), x110); const x119 = cast(u1, (x31 & cast(u64, 0x1))); var x120: u64 = undefined; cmovznzU64(&x120, x119, cast(u64, 0x0), x7); var x121: u64 = undefined; cmovznzU64(&x121, x119, cast(u64, 0x0), x8); var x122: u64 = undefined; cmovznzU64(&x122, x119, cast(u64, 0x0), x9); var x123: u64 = undefined; cmovznzU64(&x123, x119, cast(u64, 0x0), x10); var x124: u64 = undefined; cmovznzU64(&x124, x119, cast(u64, 0x0), x11); var x125: u64 = undefined; cmovznzU64(&x125, x119, cast(u64, 0x0), x12); var x126: u64 = undefined; cmovznzU64(&x126, x119, cast(u64, 0x0), x13); var x127: u64 = undefined; cmovznzU64(&x127, x119, cast(u64, 0x0), x14); var x128: u64 = undefined; var x129: u1 = undefined; addcarryxU64(&x128, &x129, 0x0, x31, x120); var x130: u64 = undefined; var x131: u1 = undefined; addcarryxU64(&x130, &x131, x129, x32, x121); var x132: u64 = undefined; var x133: u1 = undefined; addcarryxU64(&x132, &x133, x131, x33, x122); var x134: u64 = undefined; var x135: u1 = undefined; addcarryxU64(&x134, &x135, x133, x34, x123); var x136: u64 = undefined; var x137: u1 = undefined; addcarryxU64(&x136, &x137, x135, x35, x124); var x138: u64 = undefined; var x139: u1 = undefined; addcarryxU64(&x138, &x139, x137, x36, x125); var x140: u64 = undefined; var x141: u1 = undefined; addcarryxU64(&x140, &x141, x139, x37, x126); var x142: u64 = undefined; var x143: u1 = undefined; addcarryxU64(&x142, &x143, x141, x38, x127); var x144: u64 = undefined; cmovznzU64(&x144, x119, cast(u64, 0x0), x39); var x145: u64 = undefined; cmovznzU64(&x145, x119, cast(u64, 0x0), x40); var x146: u64 = undefined; cmovznzU64(&x146, x119, cast(u64, 0x0), x41); var x147: u64 = undefined; cmovznzU64(&x147, x119, cast(u64, 0x0), x42); var x148: u64 = undefined; cmovznzU64(&x148, x119, cast(u64, 0x0), x43); var x149: u64 = undefined; cmovznzU64(&x149, x119, cast(u64, 0x0), x44); var x150: u64 = undefined; cmovznzU64(&x150, x119, cast(u64, 0x0), x45); var x151: u64 = undefined; var x152: u1 = undefined; addcarryxU64(&x151, &x152, 0x0, x112, x144); var x153: u64 = undefined; var x154: u1 = undefined; addcarryxU64(&x153, &x154, x152, x113, x145); var x155: u64 = undefined; var x156: u1 = undefined; addcarryxU64(&x155, &x156, x154, x114, x146); var x157: u64 = undefined; var x158: u1 = undefined; addcarryxU64(&x157, &x158, x156, x115, x147); var x159: u64 = undefined; var x160: u1 = undefined; addcarryxU64(&x159, &x160, x158, x116, x148); var x161: u64 = undefined; var x162: u1 = undefined; addcarryxU64(&x161, &x162, x160, x117, x149); var x163: u64 = undefined; var x164: u1 = undefined; addcarryxU64(&x163, &x164, x162, x118, x150); var x165: u64 = undefined; var x166: u1 = undefined; subborrowxU64(&x165, &x166, 0x0, x151, 0xffffffffffffffff); var x167: u64 = undefined; var x168: u1 = undefined; subborrowxU64(&x167, &x168, x166, x153, 0xffffffffffffffff); var x169: u64 = undefined; var x170: u1 = undefined; subborrowxU64(&x169, &x170, x168, x155, 0xffffffffffffffff); var x171: u64 = undefined; var x172: u1 = undefined; subborrowxU64(&x171, &x172, x170, x157, 0xfdc1767ae2ffffff); var x173: u64 = undefined; var x174: u1 = undefined; subborrowxU64(&x173, &x174, x172, x159, 0x7bc65c783158aea3); var x175: u64 = undefined; var x176: u1 = undefined; subborrowxU64(&x175, &x176, x174, x161, 0x6cfc5fd681c52056); var x177: u64 = undefined; var x178: u1 = undefined; subborrowxU64(&x177, &x178, x176, x163, 0x2341f27177344); var x179: u64 = undefined; var x180: u1 = undefined; subborrowxU64(&x179, &x180, x178, cast(u64, x164), cast(u64, 0x0)); var x181: u64 = undefined; var x182: u1 = undefined; addcarryxU64(&x181, &x182, 0x0, x6, cast(u64, 0x1)); const x183 = ((x128 >> 1) | ((x130 << 63) & 0xffffffffffffffff)); const x184 = ((x130 >> 1) | ((x132 << 63) & 0xffffffffffffffff)); const x185 = ((x132 >> 1) | ((x134 << 63) & 0xffffffffffffffff)); const x186 = ((x134 >> 1) | ((x136 << 63) & 0xffffffffffffffff)); const x187 = ((x136 >> 1) | ((x138 << 63) & 0xffffffffffffffff)); const x188 = ((x138 >> 1) | ((x140 << 63) & 0xffffffffffffffff)); const x189 = ((x140 >> 1) | ((x142 << 63) & 0xffffffffffffffff)); const x190 = ((x142 & 0x8000000000000000) | (x142 >> 1)); var x191: u64 = undefined; cmovznzU64(&x191, x75, x60, x46); var x192: u64 = undefined; cmovznzU64(&x192, x75, x62, x48); var x193: u64 = undefined; cmovznzU64(&x193, x75, x64, x50); var x194: u64 = undefined; cmovznzU64(&x194, x75, x66, x52); var x195: u64 = undefined; cmovznzU64(&x195, x75, x68, x54); var x196: u64 = undefined; cmovznzU64(&x196, x75, x70, x56); var x197: u64 = undefined; cmovznzU64(&x197, x75, x72, x58); var x198: u64 = undefined; cmovznzU64(&x198, x180, x165, x151); var x199: u64 = undefined; cmovznzU64(&x199, x180, x167, x153); var x200: u64 = undefined; cmovznzU64(&x200, x180, x169, x155); var x201: u64 = undefined; cmovznzU64(&x201, x180, x171, x157); var x202: u64 = undefined; cmovznzU64(&x202, x180, x173, x159); var x203: u64 = undefined; cmovznzU64(&x203, x180, x175, x161); var x204: u64 = undefined; cmovznzU64(&x204, x180, x177, x163); out1.* = x181; out2[0] = x7; out2[1] = x8; out2[2] = x9; out2[3] = x10; out2[4] = x11; out2[5] = x12; out2[6] = x13; out2[7] = x14; out3[0] = x183; out3[1] = x184; out3[2] = x185; out3[3] = x186; out3[4] = x187; out3[5] = x188; out3[6] = x189; out3[7] = x190; out4[0] = x191; out4[1] = x192; out4[2] = x193; out4[3] = x194; out4[4] = x195; out4[5] = x196; out4[6] = x197; out5[0] = x198; out5[1] = x199; out5[2] = x200; out5[3] = x201; out5[4] = x202; out5[5] = x203; out5[6] = x204; } /// The function divstepPrecomp returns the precomputed value for Bernstein-Yang-inversion (in montgomery form). /// /// Postconditions: /// eval (from_montgomery out1) = ⌊(m - 1) / 2⌋^(if ⌊log2 m⌋ + 1 < 46 then ⌊(49 * (⌊log2 m⌋ + 1) + 80) / 17⌋ else ⌊(49 * (⌊log2 m⌋ + 1) + 57) / 17⌋) /// 0 ≤ eval out1 < m /// /// Output Bounds: /// out1: [[0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff], [0x0 ~> 0xffffffffffffffff]] pub fn divstepPrecomp(out1: *[7]u64) void { @setRuntimeSafety(mode == .Debug); out1[0] = 0x9f9776e27e1a2b72; out1[1] = 0x28b59f067e2393d0; out1[2] = 0xcf316ce1572add54; out1[3] = 0x312c8965f9032c2f; out1[4] = 0x9d9cab29ad90d34c; out1[5] = 0x6e1ddae1d9609ae1; out1[6] = 0x6df82285eec6; }
fiat-zig/src/p434_64.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = true; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const assert = std.debug.assert; pub const main = tools.defaultMain("2021/day13.txt", run); const Vec2 = tools.Vec2; fn sortAndremoveDups(list: []Vec2) []Vec2 { std.sort.sort(Vec2, list, {}, tools.Vec.lessThan); var i: u32 = 1; var j: u32 = 0; while (i < list.len) : (i += 1) { if (@reduce(.Or, list[i] != list[j])) { j += 1; list[j] = list[i]; } } return list[0 .. j + 1]; } pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { //var arena_alloc = std.heap.ArenaAllocator.init(gpa); //defer arena_alloc.deinit(); //const arena = arena_alloc.allocator(); var dot_list = std.ArrayList(Vec2).init(gpa); defer dot_list.deinit(); var first_fold: ?[]Vec2 = null; defer if (first_fold) |l| gpa.free(l); var it = std.mem.tokenize(u8, input, "\n"); while (it.next()) |line| { if (tools.match_pattern("{},{}", line)) |val| { const v = Vec2{ @intCast(i32, val[0].imm), @intCast(i32, val[1].imm), }; try dot_list.append(v); } else if (tools.match_pattern("fold along x={}", line)) |val| { const x = @intCast(i32, val[0].imm); for (dot_list.items) |*v| { if (v.*[0] > x) v.* = Vec2{ 2 * x, 0 } + Vec2{ -1, 1 } * v.*; } if (first_fold == null) first_fold = try gpa.dupe(Vec2, dot_list.items); } else if (tools.match_pattern("fold along y={}", line)) |val| { const y = @intCast(i32, val[0].imm); for (dot_list.items) |*v| { if (v.*[1] > y) v.* = Vec2{ 0, 2 * y } + Vec2{ 1, -1 } * v.*; } if (first_fold == null) first_fold = try gpa.dupe(Vec2, dot_list.items); } else { std.debug.print("skipping {s}\n", .{line}); } } const ans1 = ans: { const l = sortAndremoveDups(first_fold.?); break :ans l.len; }; var buf: [4096]u8 = undefined; const ans2 = ans: { const dots = sortAndremoveDups(dot_list.items); const max = max: { var m = Vec2{ 0, 0 }; for (dots) |v| m = @maximum(m, v); break :max m; }; var dot_idx: u32 = 0; var buf_idx: u32 = 0; var p = Vec2{ 0, 0 }; while (p[1] <= max[1]) : (p += Vec2{ 0, 1 }) { p[0] = 0; while (p[0] <= max[0]) : (p += Vec2{ 1, 0 }) { if (dot_idx < dots.len and @reduce(.And, p == dots[dot_idx])) { buf[buf_idx] = '#'; dot_idx += 1; } else { buf[buf_idx] = ' '; } buf_idx += 1; } buf[buf_idx] = '\n'; buf_idx += 1; } break :ans buf[0..buf_idx]; }; return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans1}), try std.fmt.allocPrint(gpa, "{s}", .{ans2}), }; } test { const res0 = try run( \\6,10 \\0,14 \\9,10 \\0,3 \\10,4 \\4,11 \\6,0 \\6,12 \\4,1 \\0,13 \\10,12 \\3,4 \\3,0 \\8,4 \\1,10 \\2,14 \\8,10 \\9,0 \\ \\fold along y=7 \\fold along x=5 , std.testing.allocator); defer std.testing.allocator.free(res0[0]); defer std.testing.allocator.free(res0[1]); try std.testing.expectEqualStrings("17", res0[0]); try std.testing.expectEqualStrings( \\##### \\# # \\# # \\# # \\##### \\ , res0[1]); }
2021/day13.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = true; const assert = std.debug.assert; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const Arg = union(enum) { reg: u5, imm: i64, }; pub fn match_insn(comptime pattern: []const u8, text: []const u8) ?[2]Arg { if (tools.match_pattern(pattern, text)) |vals| { var count: usize = 0; var values: [2]Arg = undefined; for (values) |*v, i| { switch (vals[i]) { .imm => |imm| v.* = .{ .imm = imm }, .name => |name| v.* = .{ .reg = @intCast(u5, name[0] - 'a') }, } } return values; } return null; } pub fn main() anyerror!void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const limit = 1 * 1024 * 1024 * 1024; const text = try std.fs.cwd().readFileAlloc(allocator, "day18.txt", limit); defer allocator.free(text); const Opcode = enum { set, add, mul, mod, jgz, }; const Insn = struct { opcode: Opcode, arg: [2]Arg, }; var program: [500]Insn = undefined; var program_len: usize = 0; var it = std.mem.tokenize(u8, text, "\n"); while (it.next()) |line| { if (match_insn("set {} {}", line)) |vals| { trace("set {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .set; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("add {} {}", line)) |vals| { trace("add {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .add; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("mul {} {}", line)) |vals| { trace("mul {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .mul; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("mod {} {}", line)) |vals| { trace("mod {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .mod; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("jgz {} {}", line)) |vals| { trace("jgz {} {}\n", .{ vals[0], vals[1] }); program[program_len].opcode = .jgz; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = vals[1]; program_len += 1; } else if (match_insn("snd {}", line)) |vals| { trace("snd {}\n", .{vals[0]}); program[program_len].opcode = .set; program[program_len].arg[0] = Arg{ .reg = 31 }; program[program_len].arg[1] = vals[0]; program_len += 1; } else if (match_insn("rcv {}", line)) |vals| { trace("rcv {}\n", .{vals[0]}); program[program_len].opcode = .set; program[program_len].arg[0] = vals[0]; program[program_len].arg[1] = Arg{ .reg = 31 }; program_len += 1; } else { trace("skipping {}\n", .{line}); } } const Computer = struct { pc: usize, regs: [32]i64, rcv_queue: [256]i64, rcv_len: usize, send_count: usize, }; var cpus = [_]Computer{ Computer{ .pc = 0, .regs = [1]i64{0} ** 32, .rcv_queue = undefined, .rcv_len = 0, .send_count = 0 }, Computer{ .pc = 0, .regs = [1]i64{0} ** 32, .rcv_queue = undefined, .rcv_len = 0, .send_count = 0 }, }; cpus[0].regs['p' - 'a'] = 0; cpus[1].regs['p' - 'a'] = 1; var prevcount0 = cpus[0].send_count + 10000; var prevcount1 = cpus[1].send_count; while (prevcount0 != cpus[0].send_count or prevcount1 != cpus[1].send_count) { prevcount0 = cpus[0].send_count; prevcount1 = cpus[1].send_count; for (cpus) |*c, icpu| { const other = &cpus[1 - icpu]; run: while (c.pc < program_len) { const insn = &program[c.pc]; switch (insn.opcode) { .set => { const is_input = (insn.arg[1] == .reg and insn.arg[1].reg == 31); const is_output = (insn.arg[0] == .reg and insn.arg[0].reg == 31); if (is_input) { if (c.rcv_len == 0) { trace("{}: rcv <- stalled\n", .{icpu}); break :run; // stall } trace("{}: rcv <- {}\n", .{ icpu, c.rcv_queue[0] }); c.regs[insn.arg[0].reg] = c.rcv_queue[0]; std.mem.copy(i64, c.rcv_queue[0 .. c.rcv_len - 1], c.rcv_queue[1..c.rcv_len]); c.rcv_len -= 1; } else if (is_output) { other.rcv_queue[other.rcv_len] = switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; trace("{}: snd -> {}\n", .{ icpu, other.rcv_queue[other.rcv_len] }); other.rcv_len += 1; c.send_count += 1; } else { c.regs[insn.arg[0].reg] = switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; } }, .add => { c.regs[insn.arg[0].reg] += switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; }, .mul => { c.regs[insn.arg[0].reg] *= switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; }, .mod => { c.regs[insn.arg[0].reg] = @mod(c.regs[insn.arg[0].reg], switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }); }, .jgz => { const val = switch (insn.arg[0]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; const ofs = switch (insn.arg[1]) { .imm => |imm| imm, .reg => |reg| c.regs[reg], }; if (val > 0) { c.pc = @intCast(usize, @intCast(i32, c.pc) + ofs); continue; // skip c.pc + 1... } }, } c.pc += 1; } } } try stdout.print("cpu0 = {}\ncpu1 = {}\n", .{ cpus[0], cpus[1] }); }
2017/day18.zig
const std = @import("std"); const za = @import("zalgebra"); const Vec2 = za.vec2; const Vec3 = za.vec3; const Vec4 = za.vec4; // dross-zig const Vector2 = @import("vector2.zig").Vector2; // ----------------------------------------- // - Vector3 - // ----------------------------------------- pub const Vector3 = struct { data: Vec3, const Self = @This(); /// Builds and returns a new Vector3 with the compoents /// set to their respective passed values. pub fn new(x_value: f32, y_value: f32, z_value: f32) Self { return Self{ .data = Vec3.new(x_value, y_value, z_value), }; } /// Create a Vector3 from a given Vector2 and a z value pub fn fromVector2(xy: Vector2, desired_z: f32) Self { return Self{ .data = Vec3.new(xy.x(), xy.y(), desired_z), }; } /// Returns the value of the x component pub fn x(self: Self) f32 { return self.data.x; } /// Returns the value of the y component pub fn y(self: Self) f32 { return self.data.y; } /// Returns the value of the z component pub fn z(self: Self) f32 { return self.data.z; } /// Builds and returns a Vector3 with all components /// set to `value`. pub fn setAll(value: f32) Self { return Self{ .data = Vec3.set(value), }; } /// Copies the values of the given Vector pub fn copy(self: Self, other: Self) Self { return .{ .data = Vec3.new(other.data.x, other.data.y, other.data.z), }; } /// Shorthand for a zeroed out Vector 3 pub fn zero() Self { return Self{ .data = Vec3.zero(), }; } /// Shorthand for (0.0, 1.0, 0.0) pub fn up() Self { return Self{ .data = Vec3.up(), }; } /// Shorthand for (1.0, 0.0, 0.0) pub fn right() Self { return Self{ .data = Vec3.right(), }; } /// Shorthand for (0.0, 0.0, 1.0) pub fn forward() Self { return Self{ .data = Vec3.forward(), }; } /// Transform vector to an array pub fn toArray(self: Self) [3]f32 { return self.data.to_array(); } /// Returns the angle (in degrees) between two vectors. pub fn getAngle(lhs: Self, rhs: Self) f32 { return lhs.data.get_angle(rhs.data); } /// Returns the length (magnitude) of the calling vector |a|. pub fn length(self: Self) f32 { return self.data.length(); } /// Returns a normalized copy of the calling vector. pub fn normalize(self: Self) Self { return Self{ .data = self.data.norm(), }; } /// Returns whether two vectors are equal or not pub fn isEqual(lhs: Self, rhs: Self) bool { return lhs.data.is_eq(rhs.data); } /// Subtraction between two vectors. pub fn subtract(lhs: Self, rhs: Self) Self { return Self{ .data = Vec3.sub(lhs.data, rhs.data), }; } /// Addition between two vectors. pub fn add(lhs: Self, rhs: Self) Self { return Self{ .data = Vec3.add(lhs.data, rhs.data), }; } /// Returns a new Vector3 multiplied by a scalar value pub fn scale(self: Self, scalar: f32) Self { return Self{ .data = self.data.scale(scalar), }; } /// Returns the cross product of the given vectors. pub fn cross(lhs: Self, rhs: Self) Self { return Self{ .data = lhs.data.cross(rhs.data), }; } /// Returns the dot product between two given vectors. pub fn dot(lhs: Self, rhs: Self) f32 { return lhs.data.dot(rhs.data); } /// Returns a linear interpolated Vector3 of the given vectors. /// t: [0.0 - 1.0] - How much should lhs move towards rhs /// Formula for a single value: /// start * (1 - t) + end * t pub fn lerp(lhs: Self, rhs: Self, t: f32) Self { return Self{ .data = lhs.data.lerp(rhs.data, t), }; } /// Returns a random Vector3 with a minimum range of `min` and /// a maximum range of `max`, inclusively. If pub fn random(max: f32) !Self { var prng = std.rand.DefaultPrng.init(blk: { var seed: u64 = undefined; try std.os.getrandom(std.mem.asBytes(&seed)); break :blk seed; }); const rand = &prng.random; return Self{ .data = Vec3.new( rand.float(f32) * max, rand.float(f32) * max, rand.float(f32) * max, ), }; } };
src/core/vector3.zig
const addv = @import("addo.zig"); const std = @import("std"); const testing = std.testing; const math = std.math; fn test__addodi4(a: i64, b: i64) !void { var result_ov: c_int = undefined; var expected_ov: c_int = undefined; var result = addv.__addodi4(a, b, &result_ov); var expected: i64 = simple_addodi4(a, b, &expected_ov); try testing.expectEqual(expected, result); try testing.expectEqual(expected_ov, result_ov); } fn simple_addodi4(a: i64, b: i64, overflow: *c_int) i64 { overflow.* = 0; const min: i64 = math.minInt(i64); const max: i64 = math.maxInt(i64); if (((a > 0) and (b > max - a)) or ((a < 0) and (b < min - a))) overflow.* = 1; return a +% b; } test "addodi4" { const min: i64 = math.minInt(i64); const max: i64 = math.maxInt(i64); var i: i64 = 1; while (i < max) : (i *|= 2) { try test__addodi4(i, i); try test__addodi4(-i, -i); try test__addodi4(i, -i); try test__addodi4(-i, i); } // edge cases // 0 + 0 = 0 // MIN + MIN overflow // MAX + MAX overflow // 0 + MIN MIN // 0 + MAX MAX // MIN + 0 MIN // MAX + 0 MAX // MIN + MAX -1 // MAX + MIN -1 try test__addodi4(0, 0); try test__addodi4(min, min); try test__addodi4(max, max); try test__addodi4(0, min); try test__addodi4(0, max); try test__addodi4(min, 0); try test__addodi4(max, 0); try test__addodi4(min, max); try test__addodi4(max, min); // derived edge cases // MIN+1 + MIN overflow // MAX-1 + MAX overflow // 1 + MIN = MIN+1 // -1 + MIN overflow // -1 + MAX = MAX-1 // +1 + MAX overflow // MIN + 1 = MIN+1 // MIN + -1 overflow // MAX + 1 overflow // MAX + -1 = MAX-1 try test__addodi4(min + 1, min); try test__addodi4(max - 1, max); try test__addodi4(1, min); try test__addodi4(-1, min); try test__addodi4(-1, max); try test__addodi4(1, max); try test__addodi4(min, 1); try test__addodi4(min, -1); try test__addodi4(max, -1); try test__addodi4(max, 1); }
lib/std/special/compiler_rt/addodi4_test.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const abs = std.math.absInt; const assert = std.debug.assert; const Point = struct { x: i32, y: i32, const Self = @This(); pub fn distance(self: Self) !i32 { return (try abs(self.x)) + (try abs(self.y)); } pub fn distanceBetween(a: Self, b: Self) !i32 { return (try abs(a.x - b.x)) + (try abs(a.y - b.y)); } pub fn eql(a: Self, b: Self) bool { return a.x == b.x and a.y == b.y; } pub fn flip(self: Self) Self { return Self{ .x = self.y, .y = self.x }; } }; const Direction = enum { Up, Down, Left, Right, }; const Instruction = struct { dir: Direction, len: i32, const Self = @This(); pub fn fromStr(s: []const u8) !Self { return Self{ .dir = switch (s[0]) { 'U' => .Up, 'D' => .Down, 'L' => .Left, 'R' => .Right, else => { std.debug.warn("{}\n", .{s}); return error.InvalidDirection; }, }, .len = try std.fmt.parseInt(i32, s[1..], 10), }; } }; const TwoDir = enum { Vertical, Horizontal, }; const Line = struct { start: Point, end: Point, const Self = @This(); pub const IntersectError = Allocator.Error; pub fn intersect(alloc: *Allocator, a: Self, b: Self) IntersectError![]Point { var result = ArrayList(Point).init(alloc); const dir_a = if (a.start.x == a.end.x) TwoDir.Vertical else TwoDir.Horizontal; const dir_b = if (b.start.x == b.end.x) TwoDir.Vertical else TwoDir.Horizontal; // Parallel if (dir_a == TwoDir.Vertical and dir_b == TwoDir.Vertical) { // They need to have same x, otherwise it's impossible // to have an intersection if (a.start.x == b.start.x) { const a_bot_p = if (a.start.y < a.end.y) a.start else a.end; const a_top_p = if (a.start.y < a.end.y) a.end else a.start; const b_bot_p = if (b.start.y < b.end.y) b.start else b.end; const b_top_p = if (b.start.y < b.end.y) b.end else b.start; if (a_top_p.y > b_top_p.y) { const start_y = b_top_p.y; const end_y = a_bot_p.y; var i: i32 = start_y; while (i >= end_y) : (i -= 1) { try result.append(Point{ .x = a_bot_p.x, .y = i }); } } else { const start_y = a_top_p.y; const end_y = b_bot_p.y; var i: i32 = start_y; while (i >= end_y) : (i -= 1) { try result.append(Point{ .x = a_bot_p.x, .y = i }); } } } } else if (dir_a == TwoDir.Horizontal and dir_b == TwoDir.Horizontal) { // Flip x and y try result.appendSlice(try Self.intersect(alloc, Self{ .start = a.start.flip(), .end = a.end.flip() }, Self{ .start = b.start.flip(), .end = b.end.flip() })); } // Crossed else if (dir_a == TwoDir.Vertical and dir_b == TwoDir.Horizontal) { const a_x = a.start.x; const b_y = b.start.y; // a_x needs to be in range of b.start.x to b.end.x const b_left_p = if (b.start.x < b.end.x) b.start else b.end; const b_right_p = if (b.start.x < b.end.x) b.end else b.start; if (a_x >= b_left_p.x and a_x <= b_right_p.x) { // b_y needs to be in range of a.start.y to a.end.y const a_bot_p = if (a.start.y < a.end.y) a.start else a.end; const a_top_p = if (a.start.y < a.end.y) a.end else a.start; if (b_y >= a_bot_p.y and b_y <= a_top_p.y) { try result.append(Point{ .x = a_x, .y = b_y }); } } } else { // Flip a and b try result.appendSlice(try Self.intersect(alloc, b, a)); } // Remove (0,0) as valid intersections var i: usize = 0; while (i < result.items.len) { if (result.items[i].x == 0 and result.items[i].y == 0) { _ = result.orderedRemove(i); } else { i += 1; } } return result.items; } pub fn len(self: Line) !i32 { return try self.start.distanceBetween(self.end); } pub fn has(self: Line, p: Point) !bool { const dir = if (self.start.x == self.end.x) TwoDir.Vertical else TwoDir.Horizontal; const correct_dir = (dir == .Vertical and self.start.x == p.x) or (dir == .Horizontal and self.start.y == p.y); const between = (try self.start.distanceBetween(p)) <= (try self.len()); return correct_dir and between; } }; const Path = struct { lines: []Line, const Self = @This(); pub fn fromInstructions(alloc: *Allocator, instr: []Instruction) !Self { var result = ArrayList(Line).init(alloc); var current = Point{ .x = 0, .y = 0 }; for (instr) |i| { switch (i.dir) { .Right => { const dest_x = current.x + i.len; const dest = Point{ .x = dest_x, .y = current.y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, .Left => { const dest_x = current.x - i.len; const dest = Point{ .x = dest_x, .y = current.y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, .Down => { const dest_y = current.y - i.len; const dest = Point{ .x = current.x, .y = dest_y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, .Up => { const dest_y = current.y + i.len; const dest = Point{ .x = current.x, .y = dest_y }; try result.append(Line{ .start = current, .end = dest }); current = dest; }, } } return Path{ .lines = result.toOwnedSlice() }; } pub fn intersections(alloc: *Allocator, a: Path, b: Path) ![]Point { var result = ArrayList(Point).init(alloc); for (a.lines) |l| { for (b.lines) |p| { const ints = try Line.intersect(alloc, l, p); try result.appendSlice(ints); } } return result.toOwnedSlice(); } pub fn distanceFromStart(self: Path, p: Point) !i32 { var result: i32 = 0; // add up all the lines that lead up to this point var last_line = self.lines[0]; for (self.lines) |l| { last_line = l; if (try l.has(p)) { break; } else { result += try l.len(); } } // add the distance from the last line to the point result += try p.distanceBetween(last_line.start); return result; } }; test "test example path" { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var instructions_1 = ArrayList(Instruction).init(allocator); try instructions_1.append(try Instruction.fromStr("R8")); try instructions_1.append(try Instruction.fromStr("U5")); try instructions_1.append(try Instruction.fromStr("L5")); try instructions_1.append(try Instruction.fromStr("D3")); const path_1 = try Path.fromInstructions(allocator, instructions_1.toOwnedSlice()); var instructions_2 = ArrayList(Instruction).init(allocator); try instructions_2.append(try Instruction.fromStr("U7")); try instructions_2.append(try Instruction.fromStr("R6")); try instructions_2.append(try Instruction.fromStr("D4")); try instructions_2.append(try Instruction.fromStr("L4")); const path_2 = try Path.fromInstructions(allocator, instructions_2.toOwnedSlice()); const ints = try Path.intersections(allocator, path_1, path_2); assert(path_1.lines.len == 4); assert(path_2.lines.len == 4); std.debug.warn("ints len {}\n", .{ints.len}); std.debug.warn("ints 0 {}\n", .{ints[0]}); std.debug.warn("ints 0 x {}\n", .{ints[0].x}); std.debug.warn("ints 0 y {}\n", .{ints[0].y}); assert(ints.len == 2); } pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); const allocator = &arena.allocator; defer arena.deinit(); var paths = ArrayList(Path).init(allocator); const input_file = try std.fs.cwd().openFile("input03.txt", .{}); var input_stream = input_file.reader(); while (input_stream.readUntilDelimiterAlloc(allocator, '\n', 1024)) |line| { var instructions = ArrayList(Instruction).init(allocator); defer instructions.deinit(); var iter = std.mem.split(line, ","); while (iter.next()) |itm| { try instructions.append(try Instruction.fromStr(itm)); } try paths.append(try Path.fromInstructions(allocator, instructions.items)); } else |err| switch (err) { error.EndOfStream => {}, else => return err, } const path_1 = paths.items[0]; const path_2 = paths.items[1]; const ints = try Path.intersections(allocator, path_1, path_2); std.debug.warn("Number of intersections: {}\n", .{ints.len}); // Find closest intersection var min_dist: ?i32 = null; for (ints) |p| { const dist = (try path_1.distanceFromStart(p)) + (try path_2.distanceFromStart(p)); if (min_dist) |min| { if (dist < min) min_dist = dist; } else { min_dist = dist; } } std.debug.warn("Minimum distance: {}\n", .{min_dist}); }
zig/03_2.zig
const std = @import("std"); const expect = std.testing.expect; const assert = std.debug.assert; fn RingBuffer(comptime T: type) type { return struct { buffer: []T, head: usize, tail: usize, last_action: enum { Add, Remove }, pub fn init(buffer: []T) @This() { return .{ .buffer = buffer, .head = 0, .tail = 0, .last_action = .Remove, }; } pub fn next(self: *@This()) void { std.debug.assert(!self.is_empty()); self.tail = (self.tail + 1) % self.buffer.len; self.last_action = .Remove; } pub fn skip(self: *@This(), count: usize) void { std.debug.assert(count <= self.used_size()); self.tail = (self.tail + count) % self.buffer.len; if (count != 0) { self.last_action = .Remove; } } pub fn read_ahead(self: *const @This()) T { std.debug.assert(!self.is_empty()); return self.buffer[self.tail]; } pub fn read_ahead_at(self: *const @This(), index: usize) T { std.debug.assert(index < self.used_size()); return self.buffer[(self.tail + index) % self.buffer.len]; } pub fn read_ahead_slice(self: *const @This(), slice: []T) void { std.debug.assert(slice.len <= self.used_size()); for (slice) |*ref, i| { ref.* = self.read_ahead_at(i); } } pub fn push(self: *@This(), elem: T) void { std.debug.assert(!self.is_full()); self.buffer[self.head] = elem; self.head = (self.head + 1) % self.buffer.len; self.last_action = .Add; } pub fn pop(self: *@This()) T { std.debug.assert(!self.is_empty()); var result: T = self.buffer[self.tail]; self.next(); return result; } pub fn push_slice(self: *@This(), slice: []const T) void { std.debug.assert(slice.len <= self.free_size()); for (slice) |value| { self.push(value); } } pub fn pop_slice(self: *@This(), slice: []T) void { std.debug.assert(slice.len <= self.used_size()); self.read_ahead_slice(slice); self.skip(slice.len); } pub fn used_size(self: *const @This()) usize { if (self.head > self.tail) { return self.head - self.tail; } else if (self.head < self.tail) { return (self.head + self.buffer.len) - self.tail; } else if (self.last_action == .Remove) { return 0; } else { return self.buffer.len; } } pub fn free_size(self: *const @This()) usize { return self.buffer.len - self.used_size(); } pub fn is_empty(self: *const @This()) bool { return self.used_size() == 0; } pub fn is_full(self: *const @This()) bool { return self.free_size() == 0; } }; } test "push pop sequence" { var buffer_space: [4]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push(1); buffer.push(2); buffer.push(3); buffer.push(4); expect(buffer.pop() == 1); buffer.push(5); expect(buffer.pop() == 2); expect(buffer.pop() == 3); expect(buffer.pop() == 4); expect(buffer.pop() == 5); } test "push pop slices sequence" { var buffer_space: [5]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push_slice(&[_]u64{ 0, 1, 2, 3 }); buffer.next(); var return_buffer: [3]u64 = undefined; buffer.pop_slice(&return_buffer); expect(return_buffer[0] == 1); expect(return_buffer[1] == 2); expect(return_buffer[2] == 3); } test "read ahead" { var buffer_space: [3]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push(1); buffer.push(2); buffer.push(3); buffer.next(); buffer.push(4); expect(buffer.read_ahead() == 2); expect(buffer.read_ahead_at(0) == 2); expect(buffer.read_ahead_at(1) == 3); expect(buffer.read_ahead_at(2) == 4); var read_ahead_buffer: [2]u64 = undefined; buffer.read_ahead_slice(&read_ahead_buffer); expect(read_ahead_buffer[0] == 2); expect(read_ahead_buffer[1] == 3); } test "sizes" { var buffer_space: [4]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); expect(buffer.free_size() == 4); expect(buffer.used_size() == 0); expect(buffer.is_empty()); expect(!buffer.is_full()); buffer.push(0); expect(buffer.free_size() == 3); expect(buffer.used_size() == 1); expect(!buffer.is_empty()); expect(!buffer.is_full()); buffer.push(1); buffer.push(2); buffer.push(3); expect(buffer.free_size() == 0); expect(buffer.used_size() == 4); expect(buffer.is_full()); expect(!buffer.is_empty()); buffer.next(); expect(buffer.free_size() == 1); expect(buffer.used_size() == 3); expect(!buffer.is_empty()); expect(!buffer.is_full()); } test "skip and next" { var buffer_space: [4]u64 = undefined; var buffer = RingBuffer(u64).init(&buffer_space); buffer.push(0); buffer.push(1); buffer.push(2); buffer.push(3); buffer.next(); buffer.skip(2); expect(buffer.pop() == 3); }
src/lib/ringbuffer.zig
usingnamespace @import("root").preamble; const log = lib.output.log.scoped(.{ .prefix = "PMM", .filter = .info, }).write; const assert = std.debug.assert; const platform = os.platform; const lalign = lib.util.libalign; const pmm_sizes = { comptime var shift = 12; comptime var sizes: []const usize = &[0]usize{}; while (shift < @bitSizeOf(usize) - 3) : (shift += 1) { sizes = sizes ++ [1]usize{1 << shift}; } return sizes; }; const reverse_sizes = { var result: [pmm_sizes.len]usize = undefined; for (pmm_sizes) |psz, i| { result[pmm_sizes.len - i - 1] = psz; } return result; }; var free_roots = [_]usize{0} ** pmm_sizes.len; var pmm_mutex = os.thread.Mutex{}; fn allocImpl(ind: usize) error{OutOfMemory}!usize { if (free_roots[ind] == 0) { if (ind + 1 >= pmm_sizes.len) return error.OutOfMemory; var next = try allocImpl(ind + 1); var next_size = pmm_sizes[ind + 1]; const current_size = pmm_sizes[ind]; while (next_size > current_size) { freeImpl(next, ind); next += current_size; next_size -= current_size; } return next; } else { const retval = free_roots[ind]; const new_root = os.platform.phys_ptr(*usize).from_int(retval).get_writeback().*; if (std.debug.runtime_safety and !lalign.isAligned(usize, pmm_sizes[ind], new_root)) { log(null, "New root: 0x{X} at index {d} is bad, referenced by 0x{X}!", .{ free_roots[ind], ind, retval }); @panic("Physical heap corrupted"); } free_roots[ind] = new_root; return retval; } } fn freeImpl(phys: usize, ind: usize) void { const last = free_roots[ind]; free_roots[ind] = phys; os.platform.phys_ptr(*usize).from_int(phys).get_writeback().* = last; } pub fn consume(phys: usize, size: usize) void { pmm_mutex.lock(); defer pmm_mutex.unlock(); var sz = size; var pp = phys; outer: while (sz != 0) { for (reverse_sizes) |psz, ri| { const i = pmm_sizes.len - ri - 1; if (sz >= psz and lalign.isAligned(usize, psz, pp)) { freeImpl(pp, i); sz -= psz; pp += psz; continue :outer; } } unreachable; } } pub fn allocPhys(size: usize) !usize { for (pmm_sizes) |psz, i| { if (size <= psz) { pmm_mutex.lock(); defer pmm_mutex.unlock(); return allocImpl(i); } } return error.PhysAllocTooSmall; } pub fn getAllocationSize(size: usize) usize { for (pmm_sizes) |psz, i| { if (size <= psz) { return psz; } } @panic("getAllocationSize"); } pub fn freePhys(phys: usize, size: usize) void { pmm_mutex.lock(); defer pmm_mutex.unlock(); for (pmm_sizes) |psz, i| { if (size <= psz and lalign.isAligned(usize, psz, phys)) { return freeImpl(phys, i); } } unreachable; } const PhysAllocator = struct { allocator: std.mem.Allocator = .{ .allocFn = allocFn, .resizeFn = resizeFn, }, fn allocFn(alloc: *std.mem.Allocator, len: usize, ptr_align: u29, len_align: u29, ret_addr: usize) std.mem.Allocator.Error![]u8 { const alloc_len = getAllocationSize(len); const ptr = os.platform.phys_ptr([*]u8).from_int(allocPhys(alloc_len) catch |err| { switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { log(null, "PMM allocator: {e}", .{err}); @panic("PMM allocator allocation error"); }, } }); return ptr.get_writeback()[0..len]; } fn resizeFn(alloc: *std.mem.Allocator, old_mem: []u8, old_align: u29, new_size: usize, len_align: u29, ret_addr: usize) std.mem.Allocator.Error!usize { const old_alloc = getAllocationSize(old_mem.len); const addr = @ptrToInt(old_mem.ptr); const base_vaddr = @ptrToInt(os.platform.phys_ptr([*]u8).from_int(0).get_writeback()); const paddr = addr - base_vaddr; if (new_size == 0) { freePhys(paddr, old_alloc); return 0; } else { const new_alloc = getAllocationSize(new_size); if (new_alloc > old_alloc) return error.OutOfMemory; var curr_alloc = old_alloc; while (new_alloc < curr_alloc) { freePhys(paddr + curr_alloc / 2, curr_alloc / 2); curr_alloc /= 2; } return new_size; } } }; var phys_alloc = PhysAllocator{}; var phys_gpa = std.heap.GeneralPurposeAllocator(.{ .thread_safe = true, .MutexType = os.thread.Mutex, }){ .backing_allocator = &phys_alloc.allocator, }; pub const phys_heap = &phys_gpa.allocator; export fn laihost_malloc(sz: usize) ?*c_void { if (sz == 0) return @intToPtr(*c_void, 0x1000); const mem = phys_heap.alloc(u8, sz) catch return os.kernel.lai.NULL; return @ptrCast(*c_void, mem.ptr); } export fn laihost_realloc(ptr: ?*c_void, newsize: usize, oldsize: usize) ?*c_void { if (oldsize == 0) { return laihost_malloc(newsize); } if (newsize == 0) { laihost_free(ptr, oldsize); return @intToPtr(*c_void, 0x1000); } const ret = laihost_malloc(newsize); @memcpy(@ptrCast([*]u8, ret), @ptrCast([*]const u8, ptr), oldsize); laihost_free(ptr, oldsize); return ret; } export fn laihost_free(ptr: ?*c_void, oldsize: usize) void { if (oldsize == 0 or ptr == null) return; phys_heap.free(@ptrCast([*]u8, ptr)[0..oldsize]); }
subprojects/flork/src/memory/pmm.zig
const std = @import("../std.zig"); const CpuFeature = std.Target.Cpu.Feature; const CpuModel = std.Target.Cpu.Model; pub const Feature = enum { v1_1, v1_2, v1_3, v1_4, v1_5, SPV_AMD_shader_fragment_mask, SPV_AMD_gpu_shader_int16, SPV_AMD_gpu_shader_half_float, SPV_AMD_texture_gather_bias_lod, SPV_AMD_shader_ballot, SPV_AMD_gcn_shader, SPV_AMD_shader_image_load_store_lod, SPV_AMD_shader_explicit_vertex_parameter, SPV_AMD_shader_trinary_minmax, SPV_AMD_gpu_shader_half_float_fetch, SPV_GOOGLE_hlsl_functionality1, SPV_GOOGLE_user_type, SPV_GOOGLE_decorate_string, SPV_EXT_demote_to_helper_invocation, SPV_EXT_descriptor_indexing, SPV_EXT_fragment_fully_covered, SPV_EXT_shader_stencil_export, SPV_EXT_physical_storage_buffer, SPV_EXT_shader_atomic_float_add, SPV_EXT_shader_atomic_float_min_max, SPV_EXT_shader_image_int64, SPV_EXT_fragment_shader_interlock, SPV_EXT_fragment_invocation_density, SPV_EXT_shader_viewport_index_layer, SPV_INTEL_loop_fuse, SPV_INTEL_fpga_dsp_control, SPV_INTEL_fpga_reg, SPV_INTEL_fpga_memory_accesses, SPV_INTEL_fpga_loop_controls, SPV_INTEL_io_pipes, SPV_INTEL_unstructured_loop_controls, SPV_INTEL_blocking_pipes, SPV_INTEL_device_side_avc_motion_estimation, SPV_INTEL_fpga_memory_attributes, SPV_INTEL_fp_fast_math_mode, SPV_INTEL_media_block_io, SPV_INTEL_shader_integer_functions2, SPV_INTEL_subgroups, SPV_INTEL_fpga_cluster_attributes, SPV_INTEL_kernel_attributes, SPV_INTEL_arbitrary_precision_integers, SPV_KHR_8bit_storage, SPV_KHR_shader_clock, SPV_KHR_device_group, SPV_KHR_16bit_storage, SPV_KHR_variable_pointers, SPV_KHR_no_integer_wrap_decoration, SPV_KHR_subgroup_vote, SPV_KHR_multiview, SPV_KHR_shader_ballot, SPV_KHR_vulkan_memory_model, SPV_KHR_physical_storage_buffer, SPV_KHR_workgroup_memory_explicit_layout, SPV_KHR_fragment_shading_rate, SPV_KHR_shader_atomic_counter_ops, SPV_KHR_shader_draw_parameters, SPV_KHR_storage_buffer_storage_class, SPV_KHR_linkonce_odr, SPV_KHR_terminate_invocation, SPV_KHR_non_semantic_info, SPV_KHR_post_depth_coverage, SPV_KHR_expect_assume, SPV_KHR_ray_tracing, SPV_KHR_ray_query, SPV_KHR_float_controls, SPV_NV_viewport_array2, SPV_NV_shader_subgroup_partitioned, SPV_NVX_multiview_per_view_attributes, SPV_NV_ray_tracing, SPV_NV_shader_image_footprint, SPV_NV_shading_rate, SPV_NV_stereo_view_rendering, SPV_NV_compute_shader_derivatives, SPV_NV_shader_sm_builtins, SPV_NV_mesh_shader, SPV_NV_geometry_shader_passthrough, SPV_NV_fragment_shader_barycentric, SPV_NV_cooperative_matrix, SPV_NV_sample_mask_override_coverage, Matrix, Shader, Geometry, Tessellation, Addresses, Linkage, Kernel, Vector16, Float16Buffer, Float16, Float64, Int64, Int64Atomics, ImageBasic, ImageReadWrite, ImageMipmap, Pipes, Groups, DeviceEnqueue, LiteralSampler, AtomicStorage, Int16, TessellationPointSize, GeometryPointSize, ImageGatherExtended, StorageImageMultisample, UniformBufferArrayDynamicIndexing, SampledImageArrayDynamicIndexing, StorageBufferArrayDynamicIndexing, StorageImageArrayDynamicIndexing, ClipDistance, CullDistance, ImageCubeArray, SampleRateShading, ImageRect, SampledRect, GenericPointer, Int8, InputAttachment, SparseResidency, MinLod, Sampled1D, Image1D, SampledCubeArray, SampledBuffer, ImageBuffer, ImageMSArray, StorageImageExtendedFormats, ImageQuery, DerivativeControl, InterpolationFunction, TransformFeedback, GeometryStreams, StorageImageReadWithoutFormat, StorageImageWriteWithoutFormat, MultiViewport, SubgroupDispatch, NamedBarrier, PipeStorage, GroupNonUniform, GroupNonUniformVote, GroupNonUniformArithmetic, GroupNonUniformBallot, GroupNonUniformShuffle, GroupNonUniformShuffleRelative, GroupNonUniformClustered, GroupNonUniformQuad, ShaderLayer, ShaderViewportIndex, FragmentShadingRateKHR, SubgroupBallotKHR, DrawParameters, WorkgroupMemoryExplicitLayoutKHR, WorkgroupMemoryExplicitLayout8BitAccessKHR, WorkgroupMemoryExplicitLayout16BitAccessKHR, SubgroupVoteKHR, StorageBuffer16BitAccess, StorageUniformBufferBlock16, UniformAndStorageBuffer16BitAccess, StorageUniform16, StoragePushConstant16, StorageInputOutput16, DeviceGroup, MultiView, VariablePointersStorageBuffer, VariablePointers, AtomicStorageOps, SampleMaskPostDepthCoverage, StorageBuffer8BitAccess, UniformAndStorageBuffer8BitAccess, StoragePushConstant8, DenormPreserve, DenormFlushToZero, SignedZeroInfNanPreserve, RoundingModeRTE, RoundingModeRTZ, RayQueryProvisionalKHR, RayQueryKHR, RayTraversalPrimitiveCullingKHR, RayTracingKHR, Float16ImageAMD, ImageGatherBiasLodAMD, FragmentMaskAMD, StencilExportEXT, ImageReadWriteLodAMD, Int64ImageEXT, ShaderClockKHR, SampleMaskOverrideCoverageNV, GeometryShaderPassthroughNV, ShaderViewportIndexLayerEXT, ShaderViewportIndexLayerNV, ShaderViewportMaskNV, ShaderStereoViewNV, PerViewAttributesNV, FragmentFullyCoveredEXT, MeshShadingNV, ImageFootprintNV, FragmentBarycentricNV, ComputeDerivativeGroupQuadsNV, FragmentDensityEXT, ShadingRateNV, GroupNonUniformPartitionedNV, ShaderNonUniform, ShaderNonUniformEXT, RuntimeDescriptorArray, RuntimeDescriptorArrayEXT, InputAttachmentArrayDynamicIndexing, InputAttachmentArrayDynamicIndexingEXT, UniformTexelBufferArrayDynamicIndexing, UniformTexelBufferArrayDynamicIndexingEXT, StorageTexelBufferArrayDynamicIndexing, StorageTexelBufferArrayDynamicIndexingEXT, UniformBufferArrayNonUniformIndexing, UniformBufferArrayNonUniformIndexingEXT, SampledImageArrayNonUniformIndexing, SampledImageArrayNonUniformIndexingEXT, StorageBufferArrayNonUniformIndexing, StorageBufferArrayNonUniformIndexingEXT, StorageImageArrayNonUniformIndexing, StorageImageArrayNonUniformIndexingEXT, InputAttachmentArrayNonUniformIndexing, InputAttachmentArrayNonUniformIndexingEXT, UniformTexelBufferArrayNonUniformIndexing, UniformTexelBufferArrayNonUniformIndexingEXT, StorageTexelBufferArrayNonUniformIndexing, StorageTexelBufferArrayNonUniformIndexingEXT, RayTracingNV, VulkanMemoryModel, VulkanMemoryModelKHR, VulkanMemoryModelDeviceScope, VulkanMemoryModelDeviceScopeKHR, PhysicalStorageBufferAddresses, PhysicalStorageBufferAddressesEXT, ComputeDerivativeGroupLinearNV, RayTracingProvisionalKHR, CooperativeMatrixNV, FragmentShaderSampleInterlockEXT, FragmentShaderShadingRateInterlockEXT, ShaderSMBuiltinsNV, FragmentShaderPixelInterlockEXT, DemoteToHelperInvocationEXT, SubgroupShuffleINTEL, SubgroupBufferBlockIOINTEL, SubgroupImageBlockIOINTEL, SubgroupImageMediaBlockIOINTEL, RoundToInfinityINTEL, FloatingPointModeINTEL, IntegerFunctions2INTEL, FunctionPointersINTEL, IndirectReferencesINTEL, AsmINTEL, AtomicFloat32MinMaxEXT, AtomicFloat64MinMaxEXT, AtomicFloat16MinMaxEXT, VectorComputeINTEL, VectorAnyINTEL, ExpectAssumeKHR, SubgroupAvcMotionEstimationINTEL, SubgroupAvcMotionEstimationIntraINTEL, SubgroupAvcMotionEstimationChromaINTEL, VariableLengthArrayINTEL, FunctionFloatControlINTEL, FPGAMemoryAttributesINTEL, FPFastMathModeINTEL, ArbitraryPrecisionIntegersINTEL, UnstructuredLoopControlsINTEL, FPGALoopControlsINTEL, KernelAttributesINTEL, FPGAKernelAttributesINTEL, FPGAMemoryAccessesINTEL, FPGAClusterAttributesINTEL, LoopFuseINTEL, FPGABufferLocationINTEL, USMStorageClassesINTEL, IOPipesINTEL, BlockingPipesINTEL, FPGARegINTEL, AtomicFloat32AddEXT, AtomicFloat64AddEXT, LongConstantCompositeINTEL, }; pub usingnamespace CpuFeature.feature_set_fns(Feature); pub const all_features = blk: { @setEvalBranchQuota(2000); const len = @typeInfo(Feature).Enum.fields.len; std.debug.assert(len <= CpuFeature.Set.needed_bit_count); var result: [len]CpuFeature = undefined; result[@enumToInt(Feature.v1_1)] = .{ .llvm_name = null, .description = "SPIR-V version 1.1", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.v1_2)] = .{ .llvm_name = null, .description = "SPIR-V version 1.2", .dependencies = featureSet(&[_]Feature{ .v1_1, }), }; result[@enumToInt(Feature.v1_3)] = .{ .llvm_name = null, .description = "SPIR-V version 1.3", .dependencies = featureSet(&[_]Feature{ .v1_2, }), }; result[@enumToInt(Feature.v1_4)] = .{ .llvm_name = null, .description = "SPIR-V version 1.4", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.v1_5)] = .{ .llvm_name = null, .description = "SPIR-V version 1.5", .dependencies = featureSet(&[_]Feature{ .v1_4, }), }; result[@enumToInt(Feature.SPV_AMD_shader_fragment_mask)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_shader_fragment_mask", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_gpu_shader_int16)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_gpu_shader_int16", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_gpu_shader_half_float)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_gpu_shader_half_float", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_texture_gather_bias_lod)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_texture_gather_bias_lod", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_shader_ballot)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_shader_ballot", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_gcn_shader)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_gcn_shader", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_shader_image_load_store_lod)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_shader_image_load_store_lod", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_shader_explicit_vertex_parameter)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_shader_explicit_vertex_parameter", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_shader_trinary_minmax)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_shader_trinary_minmax", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_AMD_gpu_shader_half_float_fetch)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_AMD_gpu_shader_half_float_fetch", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_GOOGLE_hlsl_functionality1)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_GOOGLE_hlsl_functionality1", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_GOOGLE_user_type)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_GOOGLE_user_type", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_GOOGLE_decorate_string)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_GOOGLE_decorate_string", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_demote_to_helper_invocation)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_demote_to_helper_invocation", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_descriptor_indexing)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_descriptor_indexing", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_fragment_fully_covered)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_fragment_fully_covered", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_shader_stencil_export)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_shader_stencil_export", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_physical_storage_buffer)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_physical_storage_buffer", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_shader_atomic_float_add)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_shader_atomic_float_add", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_shader_atomic_float_min_max)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_shader_atomic_float_min_max", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_shader_image_int64)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_shader_image_int64", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_fragment_shader_interlock)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_fragment_shader_interlock", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_fragment_invocation_density)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_fragment_invocation_density", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_EXT_shader_viewport_index_layer)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_EXT_shader_viewport_index_layer", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_loop_fuse)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_loop_fuse", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fpga_dsp_control)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fpga_dsp_control", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fpga_reg)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fpga_reg", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fpga_memory_accesses)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fpga_memory_accesses", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fpga_loop_controls)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fpga_loop_controls", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_io_pipes)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_io_pipes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_unstructured_loop_controls)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_unstructured_loop_controls", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_blocking_pipes)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_blocking_pipes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_device_side_avc_motion_estimation)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_device_side_avc_motion_estimation", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fpga_memory_attributes)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fpga_memory_attributes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fp_fast_math_mode)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fp_fast_math_mode", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_media_block_io)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_media_block_io", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_shader_integer_functions2)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_shader_integer_functions2", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_subgroups)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_subgroups", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_fpga_cluster_attributes)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_fpga_cluster_attributes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_kernel_attributes)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_kernel_attributes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_INTEL_arbitrary_precision_integers)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_INTEL_arbitrary_precision_integers", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_8bit_storage)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_8bit_storage", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_shader_clock)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_shader_clock", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_device_group)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_device_group", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_16bit_storage)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_16bit_storage", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_variable_pointers)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_variable_pointers", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_no_integer_wrap_decoration)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_no_integer_wrap_decoration", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_subgroup_vote)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_subgroup_vote", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_multiview)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_multiview", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_shader_ballot)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_shader_ballot", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_vulkan_memory_model)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_vulkan_memory_model", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_physical_storage_buffer)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_physical_storage_buffer", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_workgroup_memory_explicit_layout)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_workgroup_memory_explicit_layout", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_fragment_shading_rate)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_fragment_shading_rate", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_shader_atomic_counter_ops)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_shader_atomic_counter_ops", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_shader_draw_parameters)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_shader_draw_parameters", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_storage_buffer_storage_class)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_storage_buffer_storage_class", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_linkonce_odr)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_linkonce_odr", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_terminate_invocation)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_terminate_invocation", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_non_semantic_info)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_non_semantic_info", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_post_depth_coverage)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_post_depth_coverage", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_expect_assume)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_expect_assume", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_ray_tracing)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_ray_tracing", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_ray_query)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_ray_query", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_KHR_float_controls)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_KHR_float_controls", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_viewport_array2)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_viewport_array2", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_shader_subgroup_partitioned)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_shader_subgroup_partitioned", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NVX_multiview_per_view_attributes)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NVX_multiview_per_view_attributes", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_ray_tracing)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_ray_tracing", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_shader_image_footprint)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_shader_image_footprint", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_shading_rate)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_shading_rate", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_stereo_view_rendering)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_stereo_view_rendering", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_compute_shader_derivatives)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_compute_shader_derivatives", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_shader_sm_builtins)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_shader_sm_builtins", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_mesh_shader)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_mesh_shader", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_geometry_shader_passthrough)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_geometry_shader_passthrough", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_fragment_shader_barycentric)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_fragment_shader_barycentric", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_cooperative_matrix)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_cooperative_matrix", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SPV_NV_sample_mask_override_coverage)] = .{ .llvm_name = null, .description = "SPIR-V extension SPV_NV_sample_mask_override_coverage", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Matrix)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Matrix", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Shader)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Shader", .dependencies = featureSet(&[_]Feature{ .Matrix, }), }; result[@enumToInt(Feature.Geometry)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Geometry", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.Tessellation)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Tessellation", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.Addresses)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Addresses", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Linkage)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Linkage", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Kernel)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Kernel", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Vector16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Vector16", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.Float16Buffer)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Float16Buffer", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.Float16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Float16", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Float64)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Float64", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Int64)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Int64", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Int64Atomics)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Int64Atomics", .dependencies = featureSet(&[_]Feature{ .Int64, }), }; result[@enumToInt(Feature.ImageBasic)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageBasic", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.ImageReadWrite)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageReadWrite", .dependencies = featureSet(&[_]Feature{ .ImageBasic, }), }; result[@enumToInt(Feature.ImageMipmap)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageMipmap", .dependencies = featureSet(&[_]Feature{ .ImageBasic, }), }; result[@enumToInt(Feature.Pipes)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Pipes", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.Groups)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Groups", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.DeviceEnqueue)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DeviceEnqueue", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.LiteralSampler)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability LiteralSampler", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.AtomicStorage)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicStorage", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.Int16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Int16", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.TessellationPointSize)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability TessellationPointSize", .dependencies = featureSet(&[_]Feature{ .Tessellation, }), }; result[@enumToInt(Feature.GeometryPointSize)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GeometryPointSize", .dependencies = featureSet(&[_]Feature{ .Geometry, }), }; result[@enumToInt(Feature.ImageGatherExtended)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageGatherExtended", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.StorageImageMultisample)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageMultisample", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.UniformBufferArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformBufferArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SampledImageArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampledImageArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.StorageBufferArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageBufferArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.StorageImageArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ClipDistance)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ClipDistance", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.CullDistance)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability CullDistance", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ImageCubeArray)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageCubeArray", .dependencies = featureSet(&[_]Feature{ .SampledCubeArray, }), }; result[@enumToInt(Feature.SampleRateShading)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampleRateShading", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ImageRect)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageRect", .dependencies = featureSet(&[_]Feature{ .SampledRect, }), }; result[@enumToInt(Feature.SampledRect)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampledRect", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.GenericPointer)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GenericPointer", .dependencies = featureSet(&[_]Feature{ .Addresses, }), }; result[@enumToInt(Feature.Int8)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Int8", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.InputAttachment)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability InputAttachment", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SparseResidency)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SparseResidency", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.MinLod)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability MinLod", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.Sampled1D)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Sampled1D", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.Image1D)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Image1D", .dependencies = featureSet(&[_]Feature{ .Sampled1D, }), }; result[@enumToInt(Feature.SampledCubeArray)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampledCubeArray", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SampledBuffer)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampledBuffer", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ImageBuffer)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageBuffer", .dependencies = featureSet(&[_]Feature{ .SampledBuffer, }), }; result[@enumToInt(Feature.ImageMSArray)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageMSArray", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.StorageImageExtendedFormats)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageExtendedFormats", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ImageQuery)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageQuery", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.DerivativeControl)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DerivativeControl", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.InterpolationFunction)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability InterpolationFunction", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.TransformFeedback)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability TransformFeedback", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.GeometryStreams)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GeometryStreams", .dependencies = featureSet(&[_]Feature{ .Geometry, }), }; result[@enumToInt(Feature.StorageImageReadWithoutFormat)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageReadWithoutFormat", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.StorageImageWriteWithoutFormat)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageWriteWithoutFormat", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.MultiViewport)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability MultiViewport", .dependencies = featureSet(&[_]Feature{ .Geometry, }), }; result[@enumToInt(Feature.SubgroupDispatch)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupDispatch", .dependencies = featureSet(&[_]Feature{ .v1_1, .DeviceEnqueue, }), }; result[@enumToInt(Feature.NamedBarrier)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability NamedBarrier", .dependencies = featureSet(&[_]Feature{ .v1_1, .Kernel, }), }; result[@enumToInt(Feature.PipeStorage)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability PipeStorage", .dependencies = featureSet(&[_]Feature{ .v1_1, .Pipes, }), }; result[@enumToInt(Feature.GroupNonUniform)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniform", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.GroupNonUniformVote)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformVote", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.GroupNonUniformArithmetic)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformArithmetic", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.GroupNonUniformBallot)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformBallot", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.GroupNonUniformShuffle)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformShuffle", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.GroupNonUniformShuffleRelative)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformShuffleRelative", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.GroupNonUniformClustered)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformClustered", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.GroupNonUniformQuad)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformQuad", .dependencies = featureSet(&[_]Feature{ .v1_3, .GroupNonUniform, }), }; result[@enumToInt(Feature.ShaderLayer)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderLayer", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.ShaderViewportIndex)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderViewportIndex", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.FragmentShadingRateKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentShadingRateKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SubgroupBallotKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupBallotKHR", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.DrawParameters)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DrawParameters", .dependencies = featureSet(&[_]Feature{ .v1_3, .Shader, }), }; result[@enumToInt(Feature.WorkgroupMemoryExplicitLayoutKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability WorkgroupMemoryExplicitLayoutKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.WorkgroupMemoryExplicitLayout8BitAccessKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability WorkgroupMemoryExplicitLayout8BitAccessKHR", .dependencies = featureSet(&[_]Feature{ .WorkgroupMemoryExplicitLayoutKHR, }), }; result[@enumToInt(Feature.WorkgroupMemoryExplicitLayout16BitAccessKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability WorkgroupMemoryExplicitLayout16BitAccessKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SubgroupVoteKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupVoteKHR", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.StorageBuffer16BitAccess)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageBuffer16BitAccess", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.StorageUniformBufferBlock16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageUniformBufferBlock16", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.UniformAndStorageBuffer16BitAccess)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformAndStorageBuffer16BitAccess", .dependencies = featureSet(&[_]Feature{ .v1_3, .StorageBuffer16BitAccess, .StorageUniformBufferBlock16, }), }; result[@enumToInt(Feature.StorageUniform16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageUniform16", .dependencies = featureSet(&[_]Feature{ .v1_3, .StorageBuffer16BitAccess, .StorageUniformBufferBlock16, }), }; result[@enumToInt(Feature.StoragePushConstant16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StoragePushConstant16", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.StorageInputOutput16)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageInputOutput16", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.DeviceGroup)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DeviceGroup", .dependencies = featureSet(&[_]Feature{ .v1_3, }), }; result[@enumToInt(Feature.MultiView)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability MultiView", .dependencies = featureSet(&[_]Feature{ .v1_3, .Shader, }), }; result[@enumToInt(Feature.VariablePointersStorageBuffer)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VariablePointersStorageBuffer", .dependencies = featureSet(&[_]Feature{ .v1_3, .Shader, }), }; result[@enumToInt(Feature.VariablePointers)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VariablePointers", .dependencies = featureSet(&[_]Feature{ .v1_3, .VariablePointersStorageBuffer, }), }; result[@enumToInt(Feature.AtomicStorageOps)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicStorageOps", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SampleMaskPostDepthCoverage)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampleMaskPostDepthCoverage", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.StorageBuffer8BitAccess)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageBuffer8BitAccess", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.UniformAndStorageBuffer8BitAccess)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformAndStorageBuffer8BitAccess", .dependencies = featureSet(&[_]Feature{ .v1_5, .StorageBuffer8BitAccess, }), }; result[@enumToInt(Feature.StoragePushConstant8)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StoragePushConstant8", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.DenormPreserve)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DenormPreserve", .dependencies = featureSet(&[_]Feature{ .v1_4, }), }; result[@enumToInt(Feature.DenormFlushToZero)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DenormFlushToZero", .dependencies = featureSet(&[_]Feature{ .v1_4, }), }; result[@enumToInt(Feature.SignedZeroInfNanPreserve)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SignedZeroInfNanPreserve", .dependencies = featureSet(&[_]Feature{ .v1_4, }), }; result[@enumToInt(Feature.RoundingModeRTE)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RoundingModeRTE", .dependencies = featureSet(&[_]Feature{ .v1_4, }), }; result[@enumToInt(Feature.RoundingModeRTZ)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RoundingModeRTZ", .dependencies = featureSet(&[_]Feature{ .v1_4, }), }; result[@enumToInt(Feature.RayQueryProvisionalKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RayQueryProvisionalKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.RayQueryKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RayQueryKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.RayTraversalPrimitiveCullingKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RayTraversalPrimitiveCullingKHR", .dependencies = featureSet(&[_]Feature{ .RayQueryKHR, .RayTracingKHR, }), }; result[@enumToInt(Feature.RayTracingKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RayTracingKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.Float16ImageAMD)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Float16ImageAMD", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ImageGatherBiasLodAMD)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageGatherBiasLodAMD", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.FragmentMaskAMD)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentMaskAMD", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.StencilExportEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StencilExportEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ImageReadWriteLodAMD)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageReadWriteLodAMD", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.Int64ImageEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability Int64ImageEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ShaderClockKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderClockKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SampleMaskOverrideCoverageNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampleMaskOverrideCoverageNV", .dependencies = featureSet(&[_]Feature{ .SampleRateShading, }), }; result[@enumToInt(Feature.GeometryShaderPassthroughNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GeometryShaderPassthroughNV", .dependencies = featureSet(&[_]Feature{ .Geometry, }), }; result[@enumToInt(Feature.ShaderViewportIndexLayerEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderViewportIndexLayerEXT", .dependencies = featureSet(&[_]Feature{ .MultiViewport, }), }; result[@enumToInt(Feature.ShaderViewportIndexLayerNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderViewportIndexLayerNV", .dependencies = featureSet(&[_]Feature{ .MultiViewport, }), }; result[@enumToInt(Feature.ShaderViewportMaskNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderViewportMaskNV", .dependencies = featureSet(&[_]Feature{ .ShaderViewportIndexLayerNV, }), }; result[@enumToInt(Feature.ShaderStereoViewNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderStereoViewNV", .dependencies = featureSet(&[_]Feature{ .ShaderViewportMaskNV, }), }; result[@enumToInt(Feature.PerViewAttributesNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability PerViewAttributesNV", .dependencies = featureSet(&[_]Feature{ .MultiView, }), }; result[@enumToInt(Feature.FragmentFullyCoveredEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentFullyCoveredEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.MeshShadingNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability MeshShadingNV", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ImageFootprintNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ImageFootprintNV", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FragmentBarycentricNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentBarycentricNV", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ComputeDerivativeGroupQuadsNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ComputeDerivativeGroupQuadsNV", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FragmentDensityEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentDensityEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ShadingRateNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShadingRateNV", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.GroupNonUniformPartitionedNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability GroupNonUniformPartitionedNV", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ShaderNonUniform)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderNonUniform", .dependencies = featureSet(&[_]Feature{ .v1_5, .Shader, }), }; result[@enumToInt(Feature.ShaderNonUniformEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderNonUniformEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .Shader, }), }; result[@enumToInt(Feature.RuntimeDescriptorArray)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RuntimeDescriptorArray", .dependencies = featureSet(&[_]Feature{ .v1_5, .Shader, }), }; result[@enumToInt(Feature.RuntimeDescriptorArrayEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RuntimeDescriptorArrayEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .Shader, }), }; result[@enumToInt(Feature.InputAttachmentArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability InputAttachmentArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .InputAttachment, }), }; result[@enumToInt(Feature.InputAttachmentArrayDynamicIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability InputAttachmentArrayDynamicIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .InputAttachment, }), }; result[@enumToInt(Feature.UniformTexelBufferArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformTexelBufferArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .SampledBuffer, }), }; result[@enumToInt(Feature.UniformTexelBufferArrayDynamicIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformTexelBufferArrayDynamicIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .SampledBuffer, }), }; result[@enumToInt(Feature.StorageTexelBufferArrayDynamicIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageTexelBufferArrayDynamicIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .ImageBuffer, }), }; result[@enumToInt(Feature.StorageTexelBufferArrayDynamicIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageTexelBufferArrayDynamicIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .ImageBuffer, }), }; result[@enumToInt(Feature.UniformBufferArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformBufferArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.UniformBufferArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformBufferArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.SampledImageArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampledImageArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.SampledImageArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SampledImageArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.StorageBufferArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageBufferArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.StorageBufferArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageBufferArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.StorageImageArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.StorageImageArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageImageArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .ShaderNonUniform, }), }; result[@enumToInt(Feature.InputAttachmentArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability InputAttachmentArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .InputAttachment, .ShaderNonUniform, }), }; result[@enumToInt(Feature.InputAttachmentArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability InputAttachmentArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .InputAttachment, .ShaderNonUniform, }), }; result[@enumToInt(Feature.UniformTexelBufferArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformTexelBufferArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .SampledBuffer, .ShaderNonUniform, }), }; result[@enumToInt(Feature.UniformTexelBufferArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UniformTexelBufferArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .SampledBuffer, .ShaderNonUniform, }), }; result[@enumToInt(Feature.StorageTexelBufferArrayNonUniformIndexing)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageTexelBufferArrayNonUniformIndexing", .dependencies = featureSet(&[_]Feature{ .v1_5, .ImageBuffer, .ShaderNonUniform, }), }; result[@enumToInt(Feature.StorageTexelBufferArrayNonUniformIndexingEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability StorageTexelBufferArrayNonUniformIndexingEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .ImageBuffer, .ShaderNonUniform, }), }; result[@enumToInt(Feature.RayTracingNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RayTracingNV", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.VulkanMemoryModel)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VulkanMemoryModel", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.VulkanMemoryModelKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VulkanMemoryModelKHR", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.VulkanMemoryModelDeviceScope)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VulkanMemoryModelDeviceScope", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.VulkanMemoryModelDeviceScopeKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VulkanMemoryModelDeviceScopeKHR", .dependencies = featureSet(&[_]Feature{ .v1_5, }), }; result[@enumToInt(Feature.PhysicalStorageBufferAddresses)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability PhysicalStorageBufferAddresses", .dependencies = featureSet(&[_]Feature{ .v1_5, .Shader, }), }; result[@enumToInt(Feature.PhysicalStorageBufferAddressesEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability PhysicalStorageBufferAddressesEXT", .dependencies = featureSet(&[_]Feature{ .v1_5, .Shader, }), }; result[@enumToInt(Feature.ComputeDerivativeGroupLinearNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ComputeDerivativeGroupLinearNV", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.RayTracingProvisionalKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RayTracingProvisionalKHR", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.CooperativeMatrixNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability CooperativeMatrixNV", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.FragmentShaderSampleInterlockEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentShaderSampleInterlockEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.FragmentShaderShadingRateInterlockEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentShaderShadingRateInterlockEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.ShaderSMBuiltinsNV)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ShaderSMBuiltinsNV", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.FragmentShaderPixelInterlockEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FragmentShaderPixelInterlockEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.DemoteToHelperInvocationEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability DemoteToHelperInvocationEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.SubgroupShuffleINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupShuffleINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SubgroupBufferBlockIOINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupBufferBlockIOINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SubgroupImageBlockIOINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupImageBlockIOINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SubgroupImageMediaBlockIOINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupImageMediaBlockIOINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.RoundToInfinityINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability RoundToInfinityINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FloatingPointModeINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FloatingPointModeINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.IntegerFunctions2INTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability IntegerFunctions2INTEL", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.FunctionPointersINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FunctionPointersINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.IndirectReferencesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability IndirectReferencesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.AsmINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AsmINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.AtomicFloat32MinMaxEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicFloat32MinMaxEXT", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.AtomicFloat64MinMaxEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicFloat64MinMaxEXT", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.AtomicFloat16MinMaxEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicFloat16MinMaxEXT", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.VectorComputeINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VectorComputeINTEL", .dependencies = featureSet(&[_]Feature{ .VectorAnyINTEL, }), }; result[@enumToInt(Feature.VectorAnyINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VectorAnyINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.ExpectAssumeKHR)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ExpectAssumeKHR", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SubgroupAvcMotionEstimationINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupAvcMotionEstimationINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SubgroupAvcMotionEstimationIntraINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupAvcMotionEstimationIntraINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.SubgroupAvcMotionEstimationChromaINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability SubgroupAvcMotionEstimationChromaINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.VariableLengthArrayINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability VariableLengthArrayINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FunctionFloatControlINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FunctionFloatControlINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGAMemoryAttributesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGAMemoryAttributesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPFastMathModeINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPFastMathModeINTEL", .dependencies = featureSet(&[_]Feature{ .Kernel, }), }; result[@enumToInt(Feature.ArbitraryPrecisionIntegersINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability ArbitraryPrecisionIntegersINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.UnstructuredLoopControlsINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability UnstructuredLoopControlsINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGALoopControlsINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGALoopControlsINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.KernelAttributesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability KernelAttributesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGAKernelAttributesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGAKernelAttributesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGAMemoryAccessesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGAMemoryAccessesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGAClusterAttributesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGAClusterAttributesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.LoopFuseINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability LoopFuseINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGABufferLocationINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGABufferLocationINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.USMStorageClassesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability USMStorageClassesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.IOPipesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability IOPipesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.BlockingPipesINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability BlockingPipesINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.FPGARegINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability FPGARegINTEL", .dependencies = featureSet(&[_]Feature{}), }; result[@enumToInt(Feature.AtomicFloat32AddEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicFloat32AddEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.AtomicFloat64AddEXT)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability AtomicFloat64AddEXT", .dependencies = featureSet(&[_]Feature{ .Shader, }), }; result[@enumToInt(Feature.LongConstantCompositeINTEL)] = .{ .llvm_name = null, .description = "Enable SPIR-V capability LongConstantCompositeINTEL", .dependencies = featureSet(&[_]Feature{}), }; const ti = @typeInfo(Feature); for (result) |*elem, i| { elem.index = i; elem.name = ti.Enum.fields[i].name; } break :blk result; };
lib/std/target/spirv.zig
const std = @import("std"); const util = @import("./util.zig"); const lexer = @import("./lang/lexer.zig"); const col = @import("./term/colors.zig"); const CProcess = std.ChildProcess; const Color = col.Color; const File = std.fs.File; const io = std.io; const os = std.os; pub const IdlShell = struct { session_id: usize, allocator: std.mem.Allocator, mode: Mode = .repl, state: State, const Self = @This(); pub fn init(allocator: std.mem.Allocator) !Self { var state = try State.init(allocator); return Self{ .session_id = 0, .mode = .repl, .state = state, .allocator = allocator, }; } pub fn repl(self: Self) !void { var exit_flag = false; var help_flag = false; while (true) rpl: { try ShPrompt.promptFmt(); const input = try util.readUntil(self.allocator, '\n'); var re = std.mem.split(u8, input, " "); var lexr = lexer.Lexer.init(input, self.allocator); _ = try lexr.lex(); const tks = try lexr.tokenListToString(); _ = try std.io.getStdOut().writeAll(tks); const cmd = re.next(); while (re.next()) |arg| rpl_parse: { if (re.index) |ix| if (ix == 0) { if (cmd) |cm| { if (std.mem.eql(u8, cm, "exit") or std.mem.eql(u8, cm, "quit")) { exit_flag = true; break :rpl; } else if (std.mem.startsWith(u8, cm, "--")) { switch (arg[2]) { 'Q' => { exit_flag = true; break :rpl; }, 'H' => { help_flag = true; break :rpl_parse; }, 'R' => {}, else => {}, } } else if (std.mem.startsWith(u8, arg, "-")) { switch (arg[1]) { 'Q' => { exit_flag = true; break :rpl; }, 'H' => { help_flag = true; break :rpl_parse; }, 'R' => {}, else => {}, } } } }; } if (exit_flag) { respOk("Goodbye!"); std.process.exit(0); } } } pub const State = struct { pwd: []const u8, pids: []usize, prev_cmd: ?[]const u8, prompt: ShPrompt, session_hist: std.StringArrayHashMap([]const u8), curr_hist: std.StringArrayHashMap([]const u8), config: std.StringArrayHashMap([]const u8), pub fn init(a: std.mem.Allocator) !State { var cwd: [256]u8 = undefined; _ = try os.getcwd(&cwd); const cfg = std.StringArrayHashMap([]const u8).init(a); const shi = std.StringArrayHashMap([]const u8).init(a); const chi = std.StringArrayHashMap([]const u8).init(a); const pr = ShPrompt.default(a); return State{ .pids = undefined, .prompt = pr, .pwd = &cwd, .prev_cmd = null, .session_hist = chi, .curr_hist = shi, .config = cfg, }; } }; pub const Mode = enum(u16) { os, edit, repl, }; }; pub const ShPrompt = struct { text: []const u8, custom: bool, pub fn default(a: std.mem.Allocator) ShPrompt { return ShPrompt{ .text = promptAlloc(a) catch { return ShPrompt{ .text = "idlsh >", .custom = false }; }, .custom = false }; } pub fn arrowStr(comptime color: Color) []const u8 { return comptime color.bold(null) ++ " -> " ++ col.reset(); } pub fn promptAlloc(a: std.mem.Allocator) ![]const u8 { const pr = ilangFmt(); const arr = arrowStr(.yellow); return try std.fmt.allocPrint(a, "{s}{s}{s}", .{ pr, "", arr }); } pub fn promptFmt() !void { const pr = ilangFmt(); const arr = arrowStr(.yellow); std.debug.print("{s}{s}{s}", .{ pr, "", arr }); } }; pub const ShellError = error{ InvalidInput, }; pub fn ilangFmt() []const u8 { return comptime Color.blue.bold(null) ++ "[" ++ col.reset() ++ Color.blue.bold(null) ++ " I" ++ col.reset() ++ Color.green.finish(.bright_fg) ++ "lang " ++ col.reset() ++ Color.blue.bold(null) ++ "]" ++ col.reset(); } pub fn respOk(comptime s: []const u8) void { const a = .{ comptime ilangFmt(), comptime respDiv(.yellow), comptime okStr(), comptime s }; std.debug.print("{s}{s}{s}{s}\n", a); } pub fn respErr(comptime s: []const u8) void { std.debug.print("{s}{s}{s}{s}\n", .{ comptime ilangFmt(), comptime respDiv(.red), comptime errStr(), comptime s }); } pub fn respDiv(comptime color: Color) []const u8 { return comptime color.bold(null) ++ " :: " ++ col.reset(); } pub fn okStr() []const u8 { return comptime Color.green.bold(null) ++ "[" ++ col.reset() ++ Color.green.bold(null) ++ "OK" ++ col.reset() ++ Color.green.bold(.bright_fg) ++ "] " ++ col.reset(); } pub fn errStr() []const u8 { return comptime Color.green.bold(null) ++ "[" ++ col.reset() ++ Color.red.bold(.bright_fg) ++ "ERR" ++ col.reset() ++ Color.red.bold(.bright_fg) ++ "] " ++ col.reset(); }
src/sh.zig
const std = @import("std"); const debug = std.debug; const heap = std.heap; const io = std.io; const math = std.math; const mem = std.mem; pub fn main() !void { const stdin = &(try io.getStdIn()).inStream().stream; const stdout = &(try io.getStdOut()).outStream().stream; var direct_allocator = heap.DirectAllocator.init(); const allocator = &direct_allocator.allocator; defer direct_allocator.deinit(); const polymer = mem.trimRight(u8, try stdin.readUntilDelimiterAlloc(allocator, '\n', 100000), "\r\n"); defer allocator.free(polymer); const reacted_polymer = try react(allocator, polymer); try stdout.print("{}\n", reacted_polymer.len); var best: usize = math.maxInt(usize); for ([]void{{}} ** ('z' - 'a')) |_, i| { const c = @intCast(u8, i + 'a'); const filtered = try filter(allocator, c, polymer); defer allocator.free(filtered); const reacted_filtered = try react(allocator, filtered); defer allocator.free(reacted_filtered); best = math.min(best, reacted_filtered.len); } try stdout.print("{}\n", best); } fn react(allocator: *mem.Allocator, polymer: []const u8) ![]u8 { var res = std.ArrayList(u8).init(allocator); errdefer res.deinit(); for (polymer) |unit| { if (!isAlpha(unit)) return error.InvalidPolymer; try res.append(unit); while (true) { const curr = res.toSliceConst(); if (curr.len < 2) break; const a = res.pop(); const b = res.pop(); if (!canReact(a, b)) { res.append(b) catch unreachable; res.append(a) catch unreachable; break; } } } return res.toOwnedSlice(); } fn filter(allocator: *mem.Allocator, unit: u8, polymer: []const u8) ![]u8 { const norm_unit = toLower(unit); var res = std.ArrayList(u8).init(allocator); errdefer res.deinit(); for (polymer) |c| { if (toLower(c) != norm_unit) try res.append(c); } return res.toOwnedSlice(); } fn isAlpha(c: u8) bool { return switch (c) { 'a'...'z', 'A'...'Z' => true, else => false, }; } fn toLower(c: u8) u8 { return switch (c) { 'A'...'Z' => c + ('a' - 'A'), else => c, }; } fn canReact(a: u8, b: u8) bool { const low = math.min(a, b); const high = math.max(a, b); return u16(low) + ('a' - 'A') == high; }
src/day5.zig
const std = @import("std"); const z80 = @import("zig80.zig"); inline fn stderr() std.fs.File.Writer { return std.io.getStdErr().writer(); } const Tester = struct { cpu: z80.CPU, failed: bool = false, memory: [0x10000]u8 = [_]u8 { 0 } ** 0x10000, fn read(self: *Tester, addr: u16) u8 { return self.memory[addr]; } fn write(self: *Tester, addr: u16, value: u8) void { self.memory[addr] = value; } fn out(self: *Tester, port: u16, value: u8) void { _ = port; _ = value; switch (self.cpu.getC()) { // e = char to print 2 => { const char = self.cpu.getE(); stderr().writeByte(char) catch {}; }, // de = '$'-terminated string 9 => { const addr = self.cpu.getDE(); const str = std.mem.sliceTo(self.memory[addr..], '$'); // if string contains "ERROR", then a test failed if (std.mem.indexOf(u8, str, "ERROR") != null) { self.failed = true; } stderr().writeAll(str) catch {}; }, else => {}, } } fn run(rom: []const u8, expected_cycles: u64) !void { // tester object var self = Tester{ .cpu = undefined }; // store COM file starting at 100h std.mem.copy(u8, self.memory[0x100..], rom); // cp/m warm boot function: self.memory[0x0000] = 0x76; // halt // cp/m bdos function: self.memory[0x0005] = 0xd3; // out (0),a ; trigger i/o callback self.memory[0x0006] = 0x00; // self.memory[0x0007] = 0xc9; // ret // z80 cpu self.cpu = .{ .interface = z80.Interface.init(&self, .{ .read = read, .write = write, .out = out, }), .pc = 0x100, }; // check for cycle accuracy var actual_cycles: u64 = 0; while (!self.cpu.halted) { // step cpu, add to total cycle count self.cpu.step(); actual_cycles += self.cpu.cycles; self.cpu.cycles = 0; } // if the exerciser reported at least one error, then fail if (self.failed) { std.debug.print("one or more tests failed\n", .{}); return error.TestFailed; } // check for cycle accuracy try std.testing.expectEqual(expected_cycles, actual_cycles); } }; test "documented instructions" { try Tester.run(@embedFile("tests/zexdoc.com"), 46734978642); } test "all instructions" { try Tester.run(@embedFile("tests/zexall.com"), 46734978642); }
src/tests.zig
const std = @import("std"); const util = @import("util"); const input = @embedFile("16.txt"); const TicketRule = struct { name: []const u8, ranges: [4]u32, fn inRange(self: TicketRule, int: u32) bool { return (int >= self.ranges[0] and int <= self.ranges[1]) or (int >= self.ranges[2] and int <= self.ranges[3]); } }; const input_sections: [3][]const u8 = comptime blk: { @setEvalBranchQuota(input.len * 5); var sections: [3][]const u8 = [_][]const u8{ input, undefined, undefined }; var section_idx = 0; while (section_idx < 2) : (section_idx += 1) { var prev_char = 0; const section = sections[section_idx]; for (section) |c, i| { defer prev_char = c; if (c == prev_char and c == '\n') { sections[section_idx] = section[0..i]; sections[section_idx + 1] = section[(i + 1)..]; break; } } else unreachable; } for (.{ &sections[1], &sections[2] }) |section| { while (section.*[0] != '\n') section.* = section.*[1..]; section.* = section.*[1..]; } break :blk sections; }; const ticket_rules: [ticket_rules_.len]TicketRule = ticket_rules_[0..ticket_rules_.len].*; const ticket_rules_ = comptime blk: { @setEvalBranchQuota(input.len * 20); var rules: []const TicketRule = &[_]TicketRule{}; var rules_str = input_sections[0]; while (rules_str.len > 0) { var ticket_rule: TicketRule = undefined; for (rules_str) |c, i| { if (c == ':') { ticket_rule.name = rules_str[0..i]; rules_str = rules_str[(i + 2)..]; break; } } else unreachable; for (.{ 0, 2 }) |offset| { for (rules_str) |c, i| { if (c == '-') { ticket_rule.ranges[offset] = util.parseUint(u32, rules_str[0..i]) catch unreachable; rules_str = rules_str[(i + 1)..]; break; } } else unreachable; for (rules_str) |c, i| { if (c == ' ' or c == '\n') { ticket_rule.ranges[offset + 1] = util.parseUint(u32, rules_str[0..i]) catch unreachable; if (c == ' ') rules_str = rules_str[(i + 4)..]; if (c == '\n') rules_str = rules_str[(i + 1)..]; break; } } else unreachable; } rules = rules ++ [_]TicketRule{ticket_rule}; } break :blk rules; }; const my_ticket = comptime blk: { @setEvalBranchQuota(input_sections[1].len * 20); var entries: []const u32 = &[_]u32{}; var ticket_str = input_sections[1]; while (ticket_str.len > 0) { for (ticket_str) |c, i| { if (c == ',' or c == '\n') { const entry = util.parseUint(u32, ticket_str[0..i]) catch unreachable; ticket_str = ticket_str[(i + 1)..]; entries = entries ++ [_]u32{entry}; break; } } else unreachable; } break :blk entries[0..entries.len].*; }; const nearby_tickets = comptime blk: { @setEvalBranchQuota(input_sections[2].len * 20); const Ticket = [my_ticket.len]u32; var tickets: []const Ticket = &[_]Ticket{}; var ticket_str = input_sections[2]; while (ticket_str.len > 0) { var ticket: Ticket = undefined; for (ticket) |*entry| { for (ticket_str) |c, i| { if (c == ',' or c == '\n') { entry.* = util.parseUint(u32, ticket_str[0..i]) catch unreachable; ticket_str = ticket_str[(i + 1)..]; break; } } else unreachable; } tickets = tickets ++ [_]Ticket{ticket}; } break :blk tickets[0..tickets.len].*; }; pub fn main(n: util.Utils) !void { var error_rate: u32 = 0; var departure_product: u64 = 1; var valid_for: [my_ticket.len][]usize = undefined; var valid_for_buf = comptime blk: { var indices: [ticket_rules.len]usize = undefined; for (indices) |*x, i| x.* = i; break :blk [_][ticket_rules.len]usize{indices} ** my_ticket.len; }; inline for ([_]void{{}} ** my_ticket.len) |_, i| { valid_for[i] = &valid_for_buf[i]; } outer: while (true) : (error_rate = 0) { for (nearby_tickets) |ticket| { const prev_error_rate = error_rate; for (ticket) |entry, i| { for (ticket_rules) |rule| { if (rule.inRange(entry)) break; } else error_rate += entry; } if (error_rate != prev_error_rate) continue; for (ticket) |entry, i| { var j: usize = 0; var rules = valid_for[i]; if (rules.len == 0) continue; while (j < rules.len) { if (!ticket_rules[rules[j]].inRange(entry)) { rules[j] = rules[rules.len - 1]; rules.len -= 1; } else j += 1; } valid_for[i] = rules; if (rules.len == 1) { const idx = rules[0]; if (std.mem.startsWith(u8, ticket_rules[idx].name, "departure")) departure_product *= my_ticket[i]; for (valid_for) |*ruleset, k| { j = 0; while (j < ruleset.len) : (j += 1) { if (ruleset.*[j] == idx) { ruleset.*[j] = ruleset.*[ruleset.len - 1]; ruleset.len -= 1; break; } } } continue :outer; } } } break; } try n.out.print("{}\n{}\n", .{ error_rate, departure_product }); }
2020/16.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 Reference = opaque { pub fn deinit(self: *Reference) void { log.debug("Reference.deinit called", .{}); c.git_reference_free(@ptrCast(*c.git_reference, self)); log.debug("reference freed successfully", .{}); } /// Delete an existing branch reference. /// /// Note that if the deletion succeeds, the reference will not be valid anymore, and should be freed immediately by the user /// using `deinit`. pub fn deleteBranch(self: *Reference) !void { log.debug("Reference.deleteBranch called", .{}); try internal.wrapCall("git_branch_delete", .{@ptrCast(*c.git_reference, self)}); log.debug("successfully deleted branch", .{}); } pub fn annotatedCommitCreate(self: *const Reference, repository: *git.Repository) !*git.AnnotatedCommit { log.debug("Reference.annotatedCommitCreate called, repository: {*}", .{repository}); var result: *git.AnnotatedCommit = undefined; try internal.wrapCall("git_annotated_commit_from_ref", .{ @ptrCast(*?*c.git_annotated_commit, &result), @ptrCast(*c.git_repository, repository), @ptrCast(*const c.git_reference, self), }); log.debug("successfully created annotated commit", .{}); return result; } /// Move/rename an existing local branch reference. /// /// The new branch name will be checked for validity. /// /// Note that if the move succeeds, the old reference will not be valid anymore, and should be freed immediately by the user /// using `deinit`. pub fn move(self: *Reference, new_branch_name: [:0]const u8, force: bool) !*Reference { log.debug("Reference.move called, new_branch_name: {s}, force: {}", .{ new_branch_name, force }); var ref: *Reference = undefined; try internal.wrapCall("git_branch_move", .{ @ptrCast(*?*c.git_reference, &ref), @ptrCast(*c.git_reference, self), new_branch_name.ptr, @boolToInt(force), }); log.debug("successfully moved branch", .{}); return ref; } pub fn nameGet(self: *Reference) ![:0]const u8 { log.debug("Reference.nameGet called", .{}); var name: ?[*:0]const u8 = undefined; try internal.wrapCall("git_branch_name", .{ &name, @ptrCast(*const c.git_reference, self) }); const slice = std.mem.sliceTo(name.?, 0); log.debug("successfully fetched name: {s}", .{slice}); return slice; } pub fn upstreamGet(self: *Reference) !*Reference { log.debug("Reference.upstreamGet called", .{}); var ref: *Reference = undefined; try internal.wrapCall("git_branch_upstream", .{ @ptrCast(*?*c.git_reference, &ref), @ptrCast(*const c.git_reference, self), }); log.debug("successfully fetched reference: {*}", .{ref}); return ref; } pub fn upstreamSet(self: *Reference, branch_name: [:0]const u8) !void { log.debug("Reference.upstreamSet called, branch_name: {s}", .{branch_name}); try internal.wrapCall("git_branch_set_upstream", .{ @ptrCast(*c.git_reference, self), branch_name.ptr }); log.debug("successfully set upstream branch", .{}); } pub fn isHead(self: *const Reference) !bool { log.debug("Reference.isHead", .{}); const ret = (try internal.wrapCallWithReturn("git_branch_is_head", .{@ptrCast(*const c.git_reference, self)})) == 1; log.debug("is head: {}", .{ret}); return ret; } pub fn isCheckedOut(self: *const Reference) !bool { log.debug("Reference.isCheckedOut", .{}); const ret = (try internal.wrapCallWithReturn("git_branch_is_checked_out", .{@ptrCast(*const c.git_reference, self)})) == 1; log.debug("is checked out: {}", .{ret}); return ret; } comptime { std.testing.refAllDecls(@This()); } }; comptime { std.testing.refAllDecls(@This()); }
src/reference.zig
const builtin = @import("builtin"); const testing = @import("std").testing; // TODO: I wish I could write something like `{ ...self, ._state = ty }` pub fn setField(lhs: var, comptime field_name: []const u8, value: var) @typeOf(lhs) { var new = lhs; @field(new, field_name) = value; return new; } test "setField updates a field and returns a brand new struct" { const x = setField(struct { a: u32, b: u32, }{ .a = 42, .b = 84, }, "a", 100); testing.expectEqual(u32(100), x.a); testing.expectEqual(u32(84), x.b); } pub fn append(lhs: var, x: var) @typeOf(lhs) { switch (@typeInfo(@typeOf(lhs))) { builtin.TypeId.Pointer => |info| switch (info.size) { builtin.TypeInfo.Pointer.Size.Slice => { const elem_type = info.child; return lhs ++ ([_]elem_type{x})[0..1]; }, else => @compileError("lhs must be a slice"), }, else => @compileError("lhs must be a slice"), } } test "append appends a new element" { comptime { const s0 = empty(u32); const s1 = append(s0, 100); testing.expectEqual([]const u32, @typeOf(s1)); testing.expectEqual(100, s1[0]); const s2 = append(s1, 200); testing.expectEqual([]const u32, @typeOf(s2)); testing.expectEqual(100, s2[0]); testing.expectEqual(200, s2[1]); } } pub fn empty(comptime ty: type) []const ty { return [_]ty{}; } test "empty produces an empty slice" { comptime { testing.expectEqual(empty(u32).len, 0); } } pub fn map(comptime To: type, comptime transducer: var, comptime slice: var) [slice.len]To { var ret: [slice.len]To = undefined; for (slice) |*e, i| { ret[i] = transducer(e); } return ret; } test "map does its job" { comptime { const array1 = map(u8, struct { fn ___(x: *const u32) u8 { return undefined; } }.___, empty(u8)); testing.expectEqual([0]u8, @typeOf(array1)); testing.expectEqualSlices(u8, &[_]u8{}, &array1); const array2 = map(u8, struct { fn ___(x: *const u32) u8 { return @truncate(u8, x.*) + 1; } }.___, [_]u32{ 1, 2, 3 }); testing.expectEqual([3]u8, @typeOf(array2)); testing.expectEqualSlices(u8, &[_]u8{ 2, 3, 4 }, &array2); } } pub fn intToStr(comptime i: var) []const u8 { comptime { if (i < 0) { @compileError("negative numbers are not supported (yet)"); } else if (i == 0) { return "0"; } else { var str: []const u8 = ""; var ii = i; while (ii > 0) { str = [1]u8{'0' + ii % 10} ++ str; ii /= 10; } return str; } } } test "intToStr does its job" { testing.expectEqualSlices(u8, &"0", intToStr(0)); testing.expectEqualSlices(u8, &"4", intToStr(4)); testing.expectEqualSlices(u8, &"42", intToStr(42)); }
druzhba/comptimeutils.zig
const c = @cImport({ @cInclude("cfl_input.h"); }); const widget = @import("widget.zig"); const enums = @import("enums.zig"); pub const Output = struct { inner: ?*c.Fl_Output, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) Output { const ptr = c.Fl_Output_new(x, y, w, h, title); if (ptr == null) unreachable; return Output{ .inner = ptr, }; } pub fn raw(self: *Output) ?*c.Fl_Output { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Output) Output { return Output{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) Output { return Output{ .inner = @ptrCast(?*c.Fl_Output, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) Output { return Output{ .inner = @ptrCast(?*c.Fl_Output, ptr), }; } pub fn toVoidPtr(self: *MultilineOutput) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const Output) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn handle(self: *Output, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Output_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *Output, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Output_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } pub fn value(self: *const Output) [*c]const u8 { return c.Fl_Output_value(self.inner); } pub fn setValue(self: *Output, val: [*c]const u8) void { c.Fl_Output_set_value(self.inner, val); } pub fn setTextFont(self: *Output, font: enums.Font) void { c.Fl_Output_set_text_font(self.inner, @enumToInt(font)); } pub fn setTextColor(self: *Output, col: u32) void { c.Fl_Output_set_text_color(self.inner, col); } pub fn setTextSize(self: *Output, sz: u32) void { c.Fl_Output_set_text_size(self.inner, sz); } }; pub const MultilineOutput = struct { inner: ?*c.Fl_Multiline_Output, pub fn new(x: i32, y: i32, w: i32, h: i32, title: [*c]const u8) MultilineOutput { const ptr = c.Fl_Multiline_Output_new(x, y, w, h, title); if (ptr == null) unreachable; return MultilineOutput{ .inner = ptr, }; } pub fn raw(self: *MultilineOutput) ?*c.Fl_Multiline_Output { return self.inner; } pub fn fromRaw(ptr: ?*c.Fl_Multiline_Output) MultilineOutput { return MultilineOutput{ .inner = ptr, }; } pub fn fromWidgetPtr(w: widget.WidgetPtr) MultilineOutput { return MultilineOutput{ .inner = @ptrCast(?*c.Fl_Multiline_Output, w), }; } pub fn fromVoidPtr(ptr: ?*c_void) MultilineOutput { return MultilineOutput{ .inner = @ptrCast(?*c.Fl_Multiline_Output, ptr), }; } pub fn toVoidPtr(self: *MultilineOutput) ?*c_void { return @ptrCast(?*c_void, self.inner); } pub fn asWidget(self: *const MultilineOutput) widget.Widget { return widget.Widget{ .inner = @ptrCast(widget.WidgetPtr, self.inner), }; } pub fn asOutput(self: *const MultilineOutput) Output { return Output{ .inner = @ptrCast(?*c.Fl_Output, self.inner), }; } pub fn handle(self: *MultilineOutput, cb: fn (w: widget.WidgetPtr, ev: i32, data: ?*c_void) callconv(.C) i32, data: ?*c_void) void { c.Fl_Multiline_Output_handle(self.inner, @ptrCast(c.custom_handler_callback, cb), data); } pub fn draw(self: *MultilineOutput, cb: fn (w: widget.WidgetPtr, data: ?*c_void) callconv(.C) void, data: ?*c_void) void { c.Fl_Multiline_Output_handle(self.inner, @ptrCast(c.custom_draw_callback, cb), data); } }; test "" { @import("std").testing.refAllDecls(@This()); }
src/output.zig
const zt = @import("zt"); const main = @import("../main.zig"); const ig = @import("imgui"); const zg = zt.custom_components; var rotation: f32 = 0.0; var zoom: f32 = 1.0; // We're just going to lazy init it when the example loads this scene. var rt: ?zt.gl.RenderTarget = null; fn ensure() void { if (rt == null) { rt = zt.gl.RenderTarget.init(200, 200); } } pub fn update(ctx: *main.SampleApplication.Context) void { var io = ig.igGetIO(); ensure(); control(ctx); var render = ctx.data.render; render.updateRenderSize(io.*.DisplaySize); render.updateCamera(.{}, zoom, rotation); render.sprite(ctx.data.sheet, .{}, 0, zt.math.vec2(32, 32), zt.math.Vec4.white, zt.math.vec2(0.5, 0.5), zt.math.rect(16, 0, 16, 16)); var pos = render.worldToScreen(.{}); // Cache where the rt is focused render.flush(); // And this is a screenspace transform! // This part wont be affected by position/zoom/rotation. Make sure you flush between the changes. render.updateCameraScreenSpace(); render.rectangleHollow(ctx.data.sheet, zt.math.rect(131, 84, 2, 2), zt.math.rect(pos.x - 100, pos.y - 100, 200, 200), 0, 3, zt.math.vec4(1.0, 1.0, 0.0, 1.0)); render.flush(); } fn control(ctx: *main.SampleApplication.Context) void { var io = ig.igGetIO(); ig.igSetNextWindowPos(io.*.DisplaySize, ig.ImGuiCond_Appearing, .{ .x = 1, .y = 1 }); if (ig.igBegin("RenderTarget Demo Settings", null, ig.ImGuiWindowFlags_None)) { ig.igPushItemWidth(ig.igGetWindowWidth() * 0.5); _ = ig.igDragFloat("Camera Rotation", &rotation, 0.02, zt.math.toRadians(-360.0), zt.math.toRadians(360.0), "%.3f", ig.ImGuiSliderFlags_None); _ = ig.igDragFloat("Camera Zoom", &zoom, 0.02, 0.1, 16, "%.3f", ig.ImGuiSliderFlags_None); ig.igPopItemWidth(); } ig.igEnd(); // Display the rendertarget ig.igSetNextWindowPos(zt.math.vec2(io.*.DisplaySize.x, 0), ig.ImGuiCond_Appearing, .{ .x = 1, .y = 0 }); if (ig.igBegin("RenderTarget Demo Viewer", null, ig.ImGuiWindowFlags_NoScrollbar)) { var contentSpace: zt.math.Vec2 = .{}; ig.igGetContentRegionAvail(&contentSpace); var ratio = contentSpace.x / rt.?.target.width; // With opengl and imgui, you need to flip the y source vectors. var uv1 = zt.math.vec2(0, 1); var uv2 = zt.math.vec2(1, 0); var size = zt.math.vec2(contentSpace.x, rt.?.target.height * ratio); ig.igImage(rt.?.target.imguiId(), size, uv1, uv2, zt.math.Vec4.white, zt.math.Vec4.white); if (ig.igButton("Update RT", .{})) { drawIntoRT(ctx); } ig.igSameLine(0, 2); if (ig.igButton("Nearest", .{})) { rt.?.target.setNearestFilter(); } ig.igSameLine(0, 2); if (ig.igButton("Linear", .{})) { rt.?.target.setLinearFilter(); } } ig.igEnd(); } fn drawIntoRT(ctx: *main.SampleApplication.Context) void { const gl = @import("gl"); var render = ctx.data.render; rt.?.bind(); // We need to manually clear the buffer: gl.glClear(gl.GL_COLOR_BUFFER_BIT); render.updateRenderSize(zt.math.vec2(rt.?.target.width, rt.?.target.height)); render.updateCamera(.{}, zoom, rotation); render.sprite(ctx.data.sheet, .{}, 0, zt.math.vec2(32, 32), zt.math.Vec4.white, zt.math.vec2(0.5, 0.5), zt.math.rect(16, 0, 16, 16)); render.flush(); rt.?.unbind(); }
example/src/scenes/rendertarget.zig
const std = @import("std"); const _compiler = @import("./compiler.zig"); const Compiler = _compiler.Compiler; const ParserState = _compiler.ParserState; const Scanner = @import("./scanner.zig").Scanner; const _obj = @import("./obj.zig"); const _value = @import("./value.zig"); const Token = @import("./token.zig").Token; const Value = _value.Value; const ObjTypeDef = _obj.ObjTypeDef; const copyStringRaw = _obj.copyStringRaw; pub const StringScanner = struct { const Self = @This(); source: []const u8, compiler: *Compiler, current: ?u8 = null, // TODO: this memory is never freed: it end up as key of the `strings` hashmap // and since not all of its keys come from here, we don't know which we can // free when we deinit strings. current_chunk: std.ArrayList(u8), offset: usize = 0, previous_interp: ?usize = null, chunk_count: usize = 0, pub fn init(compiler: *Compiler, source: []const u8) Self { return Self{ .compiler = compiler, .source = source, .current_chunk = std.ArrayList(u8).init(compiler.allocator), }; } fn advance(self: *Self) ?u8 { if (self.offset >= self.source.len) { return null; } self.current = self.source[self.offset]; self.offset += 1; return self.current; } pub fn parse(self: *Self) !void { if (self.source.len == 0) { // Push the empty string which is always the constant 0 try self.compiler.emitCodeArg(.OP_CONSTANT, 0); return; } while (self.offset < self.source.len) { const char: ?u8 = self.advance(); if (char == null) { break; } switch (char.?) { '\\' => try self.escape(), '{' => { if (self.previous_interp == null or self.previous_interp.? < self.offset - 1) { if (self.current_chunk.items.len > 0) { try self.push(self.current_chunk.items); // The previous `current_chunk` memory is owned by the compiler self.current_chunk = std.ArrayList(u8).init(self.compiler.allocator); try self.inc(); } } try self.interpolation(); try self.inc(); }, else => try self.current_chunk.append(char.?), } } // Trailing string if ((self.previous_interp == null or self.previous_interp.? < self.offset) and self.current_chunk.items.len > 0) { try self.push(self.current_chunk.items); // The previous `current_chunk` memory is owned by the compiler self.current_chunk = std.ArrayList(u8).init(self.compiler.allocator); if (self.previous_interp != null) { try self.compiler.emitOpCode(.OP_ADD); } } } fn push(self: *Self, chars: []const u8) !void { try self.compiler.emitConstant(Value{ .Obj = (try copyStringRaw( self.compiler.strings, self.compiler.allocator, chars, true, // The substring we built is now owned by compiler )).toObj(), }); } fn inc(self: *Self) !void { self.chunk_count += 1; if (self.chunk_count == 2 or self.chunk_count > 2) { try self.compiler.emitOpCode(.OP_ADD); } } fn interpolation(self: *Self) !void { var expr: []const u8 = self.source[self.offset..]; var expr_scanner = Scanner.init(expr); // Replace compiler scanner with one that only looks at that substring var scanner = self.compiler.scanner; self.compiler.scanner = expr_scanner; var parser = self.compiler.parser; self.compiler.parser = ParserState.init(self.compiler.allocator); try self.compiler.advance(); // Parse expression var expr_type: *ObjTypeDef = try self.compiler.expression(false); // if placeholder we emit a useless OP_TO_STRING! if (expr_type.def_type != .String or expr_type.optional) { try self.compiler.emitOpCode(.OP_TO_STRING); } const current: Token = self.compiler.parser.current_token.?; // } var delta: usize = self.compiler.scanner.?.current.offset; if (self.compiler.parser.ahead.items.len > 0) { const next = self.compiler.parser.ahead.items[self.compiler.parser.ahead.items.len - 1]; delta = delta - next.lexeme.len - next.offset + current.offset; } self.offset += delta - 1; self.previous_interp = self.offset; // Put back compiler's scanner self.compiler.scanner = scanner; self.compiler.parser.deinit(); self.compiler.parser = parser; // Consume closing `}` _ = self.advance(); } fn escape(self: *Self) !void { const char: ?u8 = self.advance(); if (char == null) { return; } switch (char.?) { 'n' => try self.current_chunk.append('\n'), 't' => try self.current_chunk.append('\t'), 'r' => try self.current_chunk.append('\r'), '"' => try self.current_chunk.append('"'), '\\' => try self.current_chunk.append('\\'), '{' => try self.current_chunk.append('{'), else => try self.rawChar(), } } fn rawChar(self: *Self) !void { const start: usize = self.offset - 1; while (self.offset + 1 < self.source.len and self.source[self.offset + 1] >= '0' and self.source[self.offset + 1] <= '9') { _ = self.advance(); } const num_str: []const u8 = self.source[start .. self.offset + 1]; _ = self.advance(); const number: ?u8 = std.fmt.parseInt(u8, num_str, 10) catch null; if (number) |unumber| { try self.current_chunk.append(unumber); } else { try self.compiler.reportError("Raw char should be between 0 and 255."); } } };
src/string_scanner.zig
const std = @import("std"); const utils = @import("utils.zig"); const Token = @import("tokenizer.zig").Token; const Tokenizer = @import("tokenizer.zig").Tokenizer; const TokenType = @import("tokenizer.zig").TokenType; const tokenizerDump = @import("tokenizer.zig").dump; const debug = std.debug.print; const testing = std.testing; const ial = @import("indexedarraylist.zig"); const ParseError = error{ UnexpectedToken, InvalidValue, OutOfMemory }; const DifNodeType = enum { Unit, // aka file - a top node intended to contain all the nodes parsed from the same source Edge, Node, Group, Layer, // TODO: Implement Instantiation, Relationship, Value, // key=value Include, }; /// To be populated with retrieved node-specific fields from a dif-node/tree pub const NodeParams = struct { label: ?[]const u8 = null, bgcolor: ?[]const u8 = null, fgcolor: ?[]const u8 = null, shape: ?[]const u8 = null, note: ?[]const u8 = null, }; /// To be populated with retrieved edge-specific fields from a dif-node/tree pub const EdgeParams = struct { label: ?[]const u8 = null, edge_style: ?EdgeStyle = null, source_symbol: ?EdgeEndStyle = null, source_label: ?[]const u8 = null, target_symbol: ?EdgeEndStyle = null, target_label: ?[]const u8 = null, }; /// To be populated with retrieved group-specific fields from a dif-node/tree /// The top level diagram is also considered a group in this context. pub const GroupParams = struct { label: ?[]const u8 = null, layout: ?[]const u8 = null, bgcolor: ?[]const u8 = null, note: ?[]const u8 = null, }; pub const DifNode = struct { const Self = @This(); // Common fields node_type: DifNodeType, parent: ?ial.Entry(Self) = null, first_child: ?ial.Entry(Self) = null, next_sibling: ?ial.Entry(Self) = null, initial_token: ?Token = null, // Reference back to source name: ?[]const u8 = null, data: union(DifNodeType) { Unit: struct { src_buf: []const u8, // Reference to the source buffer, to e.g. look up surrounding code for error message etc. params: GroupParams = .{}, }, Edge: struct { params: EdgeParams = .{}, }, Node: struct { params: NodeParams = .{}, }, Group: struct { // TODO: possibly populate all supported field types. TBD: how to solve for top layer? Add same to Unit as well? params: GroupParams = .{}, }, Layer: struct {}, Instantiation: struct { target: []const u8, // TODO: rname to "node_type" or similar // Populated during sema - might move to separate data structure later node_type_ref: ?ial.Entry(DifNode) = null, params: NodeParams = .{}, // TODO: add resolved variants of all supported node-properties as well? }, Relationship: struct { edge: []const u8, target: []const u8, // TODO: include actual references to the nodes to be populated during sema? // TBD: Can also implement a separate node structure with higher requirements of correctness - i.e. with minimal nulls, optionals and possibly already-resolved parameter lookups // This way the DifNode-structure is a "work in progress", and once properly built we can tighten it up. This way we can also better optimize for self-rolled renderer. // This new structure can also be nicely organized data-wise as we will have good control of the types of data as well as the total number of elements required for storage. // Populated during sema - might move to separate data structure later source_ref: ?ial.Entry(DifNode) = null, edge_ref: ?ial.Entry(DifNode) = null, target_ref: ?ial.Entry(DifNode) = null, // TODO: add resolved variants of all supported edge-properties as well? params: EdgeParams = .{}, }, Value: struct { value: []const u8, }, Include: struct {}, }, }; pub const NodeShape = enum { box, circle, ellipse, diamond, polygon, cylinder, pub fn fromString(name: []const u8) !NodeShape { return std.meta.stringToEnum(NodeShape, name) orelse error.InvalidValue; } }; pub const EdgeStyle = enum { solid, dotted, dashed, bold, pub fn fromString(name: []const u8) !EdgeStyle { return std.meta.stringToEnum(EdgeStyle, name) orelse error.InvalidValue; } }; pub const EdgeEndStyle = enum { none, arrow_open, arrow_closed, arrow_filled, pub fn fromString(name: []const u8) !EdgeEndStyle { return std.meta.stringToEnum(EdgeEndStyle, name) orelse error.InvalidValue; } }; const DififierState = enum { start, kwnode, kwedge, kwgroup, kwlayer, definition, // Common type for any non-keyword-definition }; /// Entry-function to module. Returns reference to first top-level node in graph, given a text buffer. pub fn bufToDif(node_pool: *ial.IndexedArrayList(DifNode), buf: []const u8, unit_name: []const u8) !ial.Entry(DifNode) { var tokenizer = Tokenizer.init(buf); return try tokensToDif(node_pool, &tokenizer, unit_name); } /// Entry-function to module. Returns reference to first top-level node in graph, given a tokenizer. pub fn tokensToDif(node_pool: *ial.IndexedArrayList(DifNode), tokenizer: *Tokenizer, unit_name: []const u8) !ial.Entry(DifNode) { var initial_len = node_pool.storage.items.len; // Create top-level node for unit var unit_node = node_pool.addOne() catch { return error.OutOfMemory; }; unit_node.get().* = DifNode{ .node_type = .Unit, .name = unit_name, .initial_token = null, .data = .{ .Unit = .{ .src_buf = tokenizer.buf } } }; parseTokensRecursively(node_pool, tokenizer, unit_node) catch { return error.ParseError; }; if (node_pool.storage.items.len <= initial_len) { return error.NothingFound; } return unit_node; } pub fn parseTokensRecursively(node_pool: *ial.IndexedArrayList(DifNode), tokenizer: *Tokenizer, maybe_parent: ?ial.Entry(DifNode)) ParseError!void { var state: DififierState = .start; var parent = maybe_parent; var prev_sibling: ?ial.Entry(DifNode) = null; var tok: Token = undefined; main: while (true) { switch (state) { .start => { tok = tokenizer.nextToken(); switch (tok.typ) { .eof => { break :main; }, .eos => { state = .start; }, .brace_end => { // backing up, backing up... break :main; }, .identifier => { // identifier can be relevant for either instantiation, relationship or key/value. state = .definition; }, .keyword_edge, .keyword_node, .keyword_layer, .keyword_group => { // Create node for edge, with value=name-slice // If data-chunk follows; recurse and pass current node as parent var node = node_pool.addOne() catch { return error.OutOfMemory; }; // Get label var initial_token = tok; tok = tokenizer.nextToken(); if (tok.typ != .identifier) { parseError(tokenizer.buf, tok.start, "Expected identifier, got token type '{s}'", .{@tagName(tok.typ)}); return error.UnexpectedToken; } node.get().* = switch (initial_token.typ) { .keyword_edge => DifNode{ .node_type = .Edge, .parent = parent, .name = tok.slice, .initial_token = initial_token, .data = .{ .Edge = .{} } }, .keyword_node => DifNode{ .node_type = .Node, .parent = parent, .name = tok.slice, .initial_token = initial_token, .data = .{ .Node = .{} } }, .keyword_group => DifNode{ .node_type = .Group, .parent = parent, .name = tok.slice, .initial_token = initial_token, .data = .{ .Group = .{} } }, .keyword_layer => DifNode{ .node_type = .Layer, .parent = parent, .name = tok.slice, .initial_token = initial_token, .data = .{ .Layer = .{} } }, else => unreachable, // as long as this set of cases matches the ones leading to this branch }; if (parent) |*realparent| { if (realparent.get().first_child == null) { realparent.get().first_child = node; } } if (prev_sibling) |*prev| { prev.get().next_sibling = node; } prev_sibling = node; tok = tokenizer.nextToken(); switch (tok.typ) { .eos => {}, .brace_start => { // Recurse try parseTokensRecursively(node_pool, tokenizer, node); }, else => { parseError(tokenizer.buf, tok.start, "Unexpected token type '{s}', expected {{ or ;", .{@tagName(tok.typ)}); return error.UnexpectedToken; }, } state = .start; }, .include => { var node = node_pool.addOne() catch { return error.OutOfMemory; }; node.get().* = DifNode{ .node_type = .Include, .parent = parent, .name = tok.slice[1..], .initial_token = tok, .data = .{ .Include = .{}, }, }; if (parent) |*realparent| { if (realparent.get().first_child == null) { realparent.get().first_child = node; } } if (prev_sibling) |*prev| { prev.get().next_sibling = node; } prev_sibling = node; }, else => { parseError(tokenizer.buf, tok.start, "Unexpected token type '{s}'", .{@tagName(tok.typ)}); return error.UnexpectedToken; }, } }, .definition => { // Check for either instantiation, key/value or relationship // instantiation: identifier colon identifier + ; or {} // key/value : identifier equal identifier/string + ; // relationship : identifier identifier identifier + ; or {} // Att! These can be followed by either ; or { (e.g. can contain children-set), if so; recurse const token1 = tok; std.debug.assert(token1.typ == .identifier); const token2 = tokenizer.nextToken(); const token3 = tokenizer.nextToken(); // TODO: these pointers don't remain valid. Need either a persistant area, or discrete allocations // could be resolved by storing indexes, then use those to traverse further. Perf? var node = node_pool.addOne() catch { return error.OutOfMemory; }; switch (token2.typ) { .equal => { // key/value node.get().* = DifNode{ .node_type = .Value, .parent = parent, .name = token1.slice, .initial_token = token1, .data = .{ .Value = .{ // TODO: Currently assuming single-token value for simplicity. This will likely not be the case for e.g. numbers with units .value = token3.slice, }, }, }; }, .colon => { // instantiation node.get().* = DifNode{ .node_type = .Instantiation, .parent = parent, .name = token1.slice, .initial_token = token1, .data = .{ .Instantiation = .{ .target = token3.slice, }, } }; }, .identifier => { // relationship node.get().* = DifNode{ .node_type = .Relationship, .parent = parent, .name = token1.slice, // source... Otherwise create an ID here, and keep source, edge and target all in .data? (TODO) .initial_token = token1, .data = .{ .Relationship = .{ .edge = token2.slice, .target = token3.slice, }, }, }; }, else => { parseError(tokenizer.buf, token2.start, "Unexpected token type '{s}', expected =, : or an identifier", .{@tagName(token2.typ)}); return error.UnexpectedToken; }, // invalid } if (parent) |*realparent| { if (realparent.get().first_child == null) { realparent.get().first_child = node; } } if (prev_sibling) |*prev| { prev.get().next_sibling = node; } prev_sibling = node; const token4 = tokenizer.nextToken(); switch (token4.typ) { // .brace_end, .eos => {}, .brace_start => { try parseTokensRecursively(node_pool, tokenizer, node); }, else => { parseError(tokenizer.buf, token4.start, "Unexpected token type '{s}', expected ; or {{", .{@tagName(token4.typ)}); return error.UnexpectedToken; }, // invalid } state = .start; tok = token4; }, else => {}, } } } test "dif (parseTokensRecursively) parses include statement" { { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var root_a = try bufToDif(&node_pool, \\@myfile.daya , "test"); try testing.expectEqual(DifNodeType.Include, root_a.get().first_child.?.get().node_type); try testing.expectEqualStrings("myfile.daya", root_a.get().first_child.?.get().name.?); } { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var root_a = try bufToDif(&node_pool, \\@myfile.daya \\node Node; , "test"); try testing.expectEqual(DifNodeType.Include, root_a.get().first_child.?.get().node_type); try testing.expectEqualStrings("myfile.daya", root_a.get().first_child.?.get().name.?); try testing.expectEqual(DifNodeType.Node, root_a.get().first_child.?.get().next_sibling.?.get().node_type); } } /// Join two dif-graphs: adds second to end of first pub fn join(base_root: ial.Entry(DifNode), to_join: ial.Entry(DifNode)) void { var current = base_root; // Find last sibling while (true) { if (current.get().next_sibling) |next| { current = next; } else { break; } } // join to_join as as new sibling current.get().next_sibling = to_join; } test "join" { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var root_a = try bufToDif(&node_pool, \\node Component; \\edge owns; , "test"); try testing.expectEqual(node_pool.storage.items.len, 3); try testing.expectEqualStrings("owns", node_pool.storage.items[2].name.?); var root_b = try bufToDif(&node_pool, \\compA: Component; \\compB: Component; \\compA owns compB; , "test"); join(root_a, root_b); try testing.expectEqual(node_pool.storage.items.len, 7); try testing.expectEqualStrings("compA", node_pool.storage.items[6].name.?); try testing.expectEqual(DifNodeType.Relationship, node_pool.storage.items[6].node_type); } // test/debug pub fn dumpDifAst(node: *DifNode, level: u8) void { var i: usize = 0; while (i < level) : (i += 1) debug(" ", .{}); debug("{s}: {s}\n", .{ @tagName(node.node_type), node.name }); if (node.first_child) |*child| { dumpDifAst(child.get(), level + 1); } if (node.next_sibling) |*next| { dumpDifAst(next.get(), level); } } // test/debug fn parseAndDump(buf: []const u8) void { tokenizerDump(buf); var tokenizer = Tokenizer.init(buf[0..]); var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); parseTokensRecursively(1024, &node_pool, &tokenizer, null) catch { debug("Got error parsing\n", .{}); }; dumpDifAst(&node_pool.storage.items[0], 0); } pub fn parseError(src: []const u8, start_idx: usize, comptime fmt: []const u8, args: anytype) void { const writer = std.io.getStdErr().writer(); var lc = utils.idxToLineCol(src, start_idx); writer.print("PARSE ERROR ({d}:{d}): ", .{ lc.line, lc.col }) catch {}; writer.print(fmt, args) catch {}; writer.print("\n", .{}) catch {}; utils.dumpSrcChunkRef(@TypeOf(writer), writer, src, start_idx); writer.print("\n", .{}) catch {}; var i: usize = 0; if (lc.col > 0) while (i < lc.col - 1) : (i += 1) { writer.print(" ", .{}) catch {}; }; writer.print("^\n", .{}) catch {}; } /// Traverse through DifNode-tree as identified by node. For all nodes matching node_type: add to result_buf. /// Will fail with .TooManyMatches if num matches exceeds result_buf.len pub fn findAllNodesOfType(result_buf: []ial.Entry(DifNode), node: ial.Entry(DifNode), node_type: DifNodeType) error{TooManyMatches}![]ial.Entry(DifNode) { var current = node; var next_idx: usize = 0; while (true) { // Got match? if (current.get().node_type == node_type) { if (next_idx >= result_buf.len) return error.TooManyMatches; result_buf[next_idx] = current; next_idx += 1; } // Recurse into children sets if (current.get().first_child) |child| { next_idx += (try findAllNodesOfType(result_buf[next_idx..], child, node_type)).len; } // Iterate the sibling set if (current.get().next_sibling) |next| { current = next; } else { break; } } return result_buf[0..next_idx]; } test "findAllNodesOfType find all nodes of given type" { // Simple case: only sibling set { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var root_a = try bufToDif(&node_pool, \\node Component; \\edge owns; \\edge uses; , "test"); var result_buf: [16]ial.Entry(DifNode) = undefined; try testing.expectEqual((try findAllNodesOfType(result_buf[0..], root_a, DifNodeType.Node)).len, 1); try testing.expectEqual((try findAllNodesOfType(result_buf[0..], root_a, DifNodeType.Edge)).len, 2); } // Advanced case: siblings and children { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var root_a = try bufToDif(&node_pool, \\edge woop; \\group mygroup { \\ edge owns; \\ node Component; \\ node Lib; \\} , "test"); var result_buf: [16]ial.Entry(DifNode) = undefined; try testing.expectEqual((try findAllNodesOfType(result_buf[0..], root_a, DifNodeType.Edge)).len, 2); try testing.expectEqual((try findAllNodesOfType(result_buf[0..], root_a, DifNodeType.Node)).len, 2); } } test "findAllNodesOfType fails with error.TooManyMatches if buffer too small" { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var root_a = try bufToDif(&node_pool, \\node Component; , "test"); var result_buf: [0]ial.Entry(DifNode) = undefined; try testing.expectError(error.TooManyMatches, findAllNodesOfType(result_buf[0..], root_a, DifNodeType.Node)); } /// Iterator-like interface for searching a dif-tree. Depth-first. pub const DifTraverser = struct { const Self = @This(); next_node: ?*ial.Entry(DifNode), node_type: DifNodeType, pub fn init(root: *ial.Entry(DifNode), node_type: DifNodeType) Self { return Self { .next_node = root, .node_type = node_type }; } /// Will traverse each node in a well-formed dif-graph, depth-first, returning any /// nodes of the desired node-type specified at .init(). /// Assumed that the .init()-specified root-node is the actual root of the dif-tree. pub fn next(self: *Self) ?*DifNode { while(self.next_node) |next_node| { var to_check = next_node.get(); // Traverse tree if(to_check.first_child) |*child| { self.next_node = child; } else if (to_check.next_sibling) |*sibling| { self.next_node = sibling; } else if(to_check.parent) |*parent| { // Any parent was already checked before traversing down, so: // check if parent has sibling, otherwise go further up var up_parent = parent; blk: while(true) { if(up_parent.get().next_sibling) |*sibling| { self.next_node = sibling; break :blk; } else if(up_parent.get().parent) |*up_parent_parent| { up_parent = up_parent_parent; } else { // ingen parent, ingen sibling... The End! self.next_node = null; break :blk; } } } else { // Reached end self.next_node = null; } // Check current if(to_check.node_type == self.node_type) { return to_check; } } return null; } }; test "DifTraverser" { var node_pool = ial.IndexedArrayList(DifNode).init(std.testing.allocator); defer node_pool.deinit(); var dif_root = try bufToDif(&node_pool, \\node Comp; \\edge uses; \\node Lib; \\edge owns; \\myComp: Comp; \\group mygroup { node InGroupNode; } \\myLib: Lib; \\myComp uses myLib; \\node Framework; , "test"); var trav = DifTraverser.init(&dif_root, DifNodeType.Node); try testing.expectEqual(DifNodeType.Node, trav.next().?.node_type); try testing.expectEqual(DifNodeType.Node, trav.next().?.node_type); try testing.expectEqualStrings("InGroupNode", trav.next().?.name.?); try testing.expectEqualStrings("Framework", trav.next().?.name.?); try testing.expect(trav.next() == null); }
libdaya/src/dif.zig
const std = @import("std"); const debug = std.debug; const fmt = std.fmt; const mem = std.mem; const math = std.math; pub fn main() !void { var allocator = &std.heap.DirectAllocator.init().allocator; var result1 = try biggest_finite_area(allocator, coordinates); debug.assert(result1 == 2342); debug.warn("06-1: {}\n", result1); var result2 = try safe_area(coordinates, 10000); debug.assert(result2 == 43302); debug.warn("06-2: {}\n", result2); } fn safe_area(coords: []const V2, distance_threshold: usize) !u32 { var max = point(0, 0); for (coords) |c| { //V2.print(c); if (c.x > max.x) { max.x = c.x; } if (c.y > max.y) { max.y = c.y; } } const field_stride = max.x + 1; const field_size: usize = field_stride * (max.y + 1); var area: u32 = 0; var cell_i: usize = 0; while (cell_i < field_size) : (cell_i += 1) { var distance_sum: usize = 0; for (coords) |coord, coord_i| { var dist = try manhattan_distance(point_from_index(cell_i, field_stride), coord); distance_sum += dist; if (distance_sum >= distance_threshold) { break; } } if (distance_sum < distance_threshold) { area += 1; } } return area; } test "safe area" { const test_threshold: usize = 32; debug.assert(16 == try safe_area(test_coords, test_threshold)); } fn biggest_finite_area(allocator: *mem.Allocator, coords: []const V2) !u32 { var max = point(0, 0); for (coords) |c| { //V2.print(c); if (c.x > max.x) { max.x = c.x; } if (c.y > max.y) { max.y = c.y; } } var field_stride = max.x + 1; var field = try allocator.alloc(isize, field_stride * (max.y + 1)); defer allocator.free(field); for (field) |*cell, cell_i| { cell.* = -1; var closest_distance = field.len * 1000; for (coords) |coord, coord_i| { var dist = try manhattan_distance(point_from_index(cell_i, field_stride), coord); if (dist < closest_distance) { closest_distance = dist; cell.* = @intCast(isize, coord_i); } else if (dist == closest_distance) { // when a cell of the field contains -1, this represents a tie cell.* = -1; } } } var coord_counts = try allocator.alloc(isize, coords.len); defer allocator.free(coord_counts); for (coord_counts) |*count| { count.* = 0; } for (field) |cell, cell_i| { if (cell < 0) { continue; } var current_cell = point_from_index(cell_i, field_stride); if (current_cell.x == 0 or current_cell.y == 0 or current_cell.x >= max.x or current_cell.y >= max.y) { // when a coord_count contains -1, this means that the area of that // coord is infinite coord_counts[@intCast(usize, cell)] = -1; } else { if (coord_counts[@intCast(usize, cell)] != -1) { coord_counts[@intCast(usize, cell)] += 1; } } } var max_area: isize = 0; var max_coord: usize = 0; for (coord_counts) |count, coord_i| { //debug.warn("[{}]: {}\n", coord_i, count); if (count > max_area) { max_area = count; max_coord = coord_i; } } debug.assert(max_area >= 0); return @intCast(u32, max_area); } test "biggest finite area" { var allocator = &std.heap.DirectAllocator.init().allocator; debug.assert(17 == try biggest_finite_area(allocator, test_coords)); } fn point_from_index(i: usize, stride: usize) V2 { var x: u32 = @intCast(u32, i % stride); var y: u32 = @intCast(u32, @divTrunc(i, stride)); return V2 { .x = x, .y = y }; } // 0 1 2 3 4 // 5 6 7 8 9 // 10 11 12 13 14 test "point from index" { debug.assert(0 == point_from_index(0, 5).x); debug.assert(0 == point_from_index(0, 5).y); debug.assert(1 == point_from_index(6, 5).x); debug.assert(1 == point_from_index(6, 5).y); debug.assert(2 == point_from_index(7, 5).x); debug.assert(1 == point_from_index(7, 5).y); debug.assert(4 == point_from_index(14, 5).x); debug.assert(2 == point_from_index(14, 5).y); } fn manhattan_distance(p1: V2, p2: V2) !u32 { var x_dist = (try math.absInt(@intCast(i32, p1.x) - @intCast(i32, p2.x))); var y_dist = (try math.absInt(@intCast(i32, p1.y) - @intCast(i32, p2.y))); return @intCast(u32, x_dist + y_dist); } test "manhattan" { debug.assert(5 == try manhattan_distance(point(1, 1), point(3, 4))); debug.assert(5 == try manhattan_distance(point(3, 4), point(1, 1))); debug.assert(0 == try manhattan_distance(point(13, 14), point(13, 14))); } const V2 = struct { x: u32, y: u32, fn print(self: V2) void { debug.warn("({}, {})\n", self.x, self.y); } }; inline fn point(x: u32, y: u32) V2 { return V2 { .x = x, .y = y, }; } const test_coords = []const V2 { point(1, 1), point(1, 6), point(8, 3), point(3, 4), point(5, 5), point(8, 9), }; const coordinates = comptime block: { break :block []V2{ point(67, 191), point(215, 237), point(130, 233), point(244, 61), point(93, 93), point(145, 351), point(254, 146), point(260, 278), point(177, 117), point(89, 291), point(313, 108), point(145, 161), point(143, 304), point(329, 139), point(153, 357), point(217, 156), point(139, 247), point(304, 63), point(202, 344), point(140, 302), point(233, 127), point(260, 251), point(235, 46), point(357, 336), point(302, 284), point(313, 260), point(135, 40), point(95, 57), point(227, 202), point(277, 126), point(163, 99), point(232, 271), point(130, 158), point(72, 289), point(89, 66), point(94, 111), point(210, 184), point(139, 58), point(99, 272), point(322, 148), point(209, 111), point(170, 244), point(230, 348), point(112, 200), point(287, 55), point(320, 270), point(53, 219), point(42, 52), point(313, 205), point(166, 259), }; };
2018/day_06.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const BufMap = std.BufMap; const testing = std.testing; const input_file = "input04.txt"; const fields = [_][]const u8{ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", "cid", }; fn isValid(passport: BufMap) bool { return for (fields) |field| { if (std.mem.eql(u8, field, "cid")) continue; if (passport.get(field) == null) break false; } else true; } test "is valid" { const allocator = std.testing.allocator; var passport = std.BufMap.init(allocator); defer passport.deinit(); // ecl:gry pid:860033327 eyr:2020 hcl:#fffffd // byr:1937 iyr:2017 cid:147 hgt:183cm try passport.set("ecl", "gry"); try passport.set("pid", "860033327"); try passport.set("eyr", "2020"); try passport.set("hcl", "#fffffd"); try passport.set("byr", "1937"); try passport.set("iyr", "2017"); try passport.set("cid", "147"); try passport.set("hgt", "183cm"); try testing.expect(isValid(passport)); } fn parsePassports(allocator: *Allocator, str: []const u8) ![]BufMap { var result = std.ArrayList(BufMap).init(allocator); var current_passport = BufMap.init(allocator); var iter = std.mem.split(str, "\n"); while (iter.next()) |line| { if (line.len == 0) { try result.append(current_passport); current_passport = BufMap.init(allocator); } else { var item_iter = std.mem.split(line, " "); while (item_iter.next()) |item| { var part_iter = std.mem.split(item, ":"); const key = part_iter.next() orelse return error.WrongFormat; const value = part_iter.next() orelse return error.WrongFormat; try current_passport.set(key, value); } } } return result.toOwnedSlice(); } fn freePassports(allocator: *Allocator, passports: []BufMap) void { for (passports) |*x| x.deinit(); allocator.free(passports); } test "parse passports" { const allocator = std.testing.allocator; const str = \\ecl:gry pid:860033327 eyr:2020 hcl:#fffffd \\byr:1937 iyr:2017 cid:147 hgt:183cm \\ \\iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884 \\hcl:#cfa07d byr:1929 \\ \\hcl:#ae17e1 iyr:2013 \\eyr:2024 \\ecl:brn pid:760753108 byr:1931 \\hgt:179cm \\ \\hcl:#cfa07d eyr:2025 pid:166559648 \\iyr:2011 ecl:brn hgt:59in \\ ; const parsed = try parsePassports(allocator, str); defer freePassports(allocator, parsed); try testing.expectEqual(@as(usize, 4), parsed.len); try testing.expectEqualSlices(u8, "gry", parsed[0].get("ecl").?); try testing.expectEqualSlices(u8, "1931", parsed[2].get("byr").?); try testing.expectEqual(@as(?[]const u8, null), parsed[0].get("asdf")); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = &gpa.allocator; var file = try std.fs.cwd().openFile(input_file, .{}); defer file.close(); const reader = file.reader(); const content = try reader.readAllAlloc(allocator, 4 * 1024 * 1024); defer allocator.free(content); const passports = try parsePassports(allocator, content); defer freePassports(allocator, passports); var valid_passports: u32 = 0; for (passports) |p| { if (isValid(p)) valid_passports += 1; } std.debug.print("valid passports: {}\n", .{valid_passports}); }
src/04.zig
const std = @import("std"); const Dir = std.fs.Dir; const Entry = std.fs.Dir.Entry; const Sha3_256 = std.crypto.Sha3_256; const base64 = std.base64.standard_encoder; const io = std.io; const json = std.json; const mem = std.mem; const path = std.fs.path; const warn = std.debug.warn; pub fn hashDir(allocator: *std.mem.Allocator, output_buf: *std.Buffer, full_path: []const u8) !void { var buf = &try std.Buffer.init(allocator, ""); defer buf.deinit(); var stream = io.BufferOutStream.init(buf); try walkTree(allocator, &stream.stream, full_path); var h = Sha3_256.init(); var out: [Sha3_256.digest_length]u8 = undefined; h.update(buf.toSlice()); h.final(out[0..]); try output_buf.resize(std.base64.Base64Encoder.calcSize(out.len)); base64.encode(output_buf.toSlice(), out[0..]); } fn walkTree(allocator: *std.mem.Allocator, stream: var, full_path: []const u8) anyerror!void { var dir = try Dir.open(allocator, full_path); defer dir.close(); var full_entry_buf = std.ArrayList(u8).init(allocator); defer full_entry_buf.deinit(); var h = Sha3_256.init(); var out: [Sha3_256.digest_length]u8 = undefined; while (try dir.next()) |entry| { if (entry.name[0] == '.' or mem.eql(u8, entry.name, "zig-cache")) { continue; } try full_entry_buf.resize(full_path.len + entry.name.len + 1); const full_entry_path = full_entry_buf.toSlice(); mem.copy(u8, full_entry_path, full_path); full_entry_path[full_path.len] = path.sep; mem.copy(u8, full_entry_path[full_path.len + 1 ..], entry.name); switch (entry.kind) { Entry.Kind.File => { const content = try io.readFileAlloc(allocator, full_entry_path); errdefer allocator.free(content); h.reset(); h.update(content); h.final(out[0..]); try stream.print("{x} {s}\n", out, full_entry_path); allocator.free(content); }, Entry.Kind.Directory => { try walkTree(allocator, stream, full_entry_path); }, else => {}, } } }
src/pkg/dirhash/dirhash.zig
const std = @import("std"); const hpke = @import("main.zig"); const fmt = std.fmt; const testing = std.testing; const primitives = hpke.primitives; const max_aead_tag_length = hpke.max_aead_tag_length; const Suite = hpke.Suite; test "hpke" { const suite = try Suite.init( primitives.Kem.X25519HkdfSha256.id, primitives.Kdf.HkdfSha256.id, primitives.Aead.Aes128Gcm.id, ); var info_hex = "4f6465206f6e2061204772656369616e2055726e"; var info: [info_hex.len / 2]u8 = undefined; _ = try fmt.hexToBytes(&info, info_hex); const server_seed_hex = "29e5fcb544130784b7606e3160d736309d63e044c241d4461a9c9d2e9362f1db"; var server_seed: [server_seed_hex.len / 2]u8 = undefined; _ = try fmt.hexToBytes(&server_seed, server_seed_hex); var server_kp = try suite.deterministicKeyPair(&server_seed); var expected: [32]u8 = undefined; _ = try fmt.hexToBytes(&expected, "ad5e716159a11fdb33527ce98fe39f24ae3449ffb6e93e8911f62c0e9781718a"); try testing.expectEqualSlices(u8, &expected, server_kp.secret_key.slice()); _ = try fmt.hexToBytes(&expected, "46570dfa9f66e17c38e7a081c65cf42bc00e6fed969d326c692748ae866eac6f"); try testing.expectEqualSlices(u8, &expected, server_kp.public_key.slice()); const client_seed_hex = "3b8ed55f38545e6ea459b6838280b61ff4f5df2a140823373380609fb6c68933"; var client_seed: [client_seed_hex.len / 2]u8 = undefined; _ = try fmt.hexToBytes(&client_seed, client_seed_hex); var client_kp = try suite.deterministicKeyPair(&client_seed); _ = client_kp; var client_ctx_and_encapsulated_secret = try suite.createClientContext(server_kp.public_key.slice(), &info, null, &client_seed); var encapsulated_secret = client_ctx_and_encapsulated_secret.encapsulated_secret; _ = try fmt.hexToBytes(&expected, "e7d9aa41faa0481c005d1343b26939c0748a5f6bf1f81fbd1a4e924bf0719149"); try testing.expectEqualSlices(u8, &expected, encapsulated_secret.encapsulated.constSlice()); var client_ctx = client_ctx_and_encapsulated_secret.client_ctx; _ = try fmt.hexToBytes(&expected, "d27ca8c6ce9d8998f3692613c29e5ae0b064234b874a52d65a014eeffed429b9"); try testing.expectEqualSlices(u8, &expected, client_ctx.exporterSecret().constSlice()); var server_ctx = try suite.createServerContext(encapsulated_secret.encapsulated.constSlice(), server_kp, &info, null); const message = "message"; const ad = "ad"; var ciphertext: [max_aead_tag_length + message.len]u8 = undefined; client_ctx.encryptToServer(&ciphertext, message, ad); _ = try fmt.hexToBytes(&expected, "dc54a1124854e041089e52066349a238380aaf6bf98a4c"); try testing.expectEqualSlices(u8, expected[0..ciphertext.len], &ciphertext); var message2: [message.len]u8 = undefined; try server_ctx.decryptFromClient(&message2, &ciphertext, ad); try testing.expectEqualSlices(u8, message[0..], message2[0..]); client_ctx.encryptToServer(&ciphertext, message, ad); _ = try fmt.hexToBytes(&expected, "37fbdf5f21e77f15291212fe94579054f56eaf5e78f2b5"); try testing.expectEqualSlices(u8, expected[0..ciphertext.len], &ciphertext); try server_ctx.decryptFromClient(&message2, &ciphertext, ad); try testing.expectEqualSlices(u8, message[0..], message2[0..]); _ = try fmt.hexToBytes(&expected, "ede5198c19b2591389fc7cea"); const base_nonce = client_ctx.ctx.outbound_state.?.base_nonce.constSlice(); try testing.expectEqualSlices(u8, base_nonce, expected[0..base_nonce.len]); var exported_secret: [expected.len]u8 = undefined; _ = try fmt.hexToBytes(&expected, "4ab2fe1958f433ebdd2e6302a81a5a7ca91f2ecf2188658524d681be7a9f8e45"); try client_ctx.exportSecret(&exported_secret, "exported secret"); try testing.expectEqualSlices(u8, &expected, &exported_secret); try server_ctx.exportSecret(&exported_secret, "exported secret"); try testing.expectEqualSlices(u8, &expected, &exported_secret); client_ctx_and_encapsulated_secret = try suite.createAuthenticatedClientContext( client_kp, server_kp.public_key.constSlice(), &info, null, null, ); encapsulated_secret = client_ctx_and_encapsulated_secret.encapsulated_secret; client_ctx = client_ctx_and_encapsulated_secret.client_ctx; server_ctx = try suite.createAuthenticatedServerContext( client_kp.public_key.constSlice(), encapsulated_secret.encapsulated.constSlice(), server_kp, &info, null, ); client_ctx.encryptToServer(&ciphertext, message, ad); try server_ctx.decryptFromClient(&message2, &ciphertext, ad); try testing.expectEqualSlices(u8, message[0..], message2[0..]); server_ctx.encryptToClient(&ciphertext, message, ad); try client_ctx.decryptFromServer(&message2, &ciphertext, ad); try testing.expectEqualSlices(u8, message[0..], message2[0..]); }
src/tests.zig
const std = @import("std"); const build_options = @import("build_options"); const dcommon = @import("../common/dcommon.zig"); const arch = @import("arch.zig"); const hw = @import("../hw.zig"); usingnamespace @import("paging.zig"); fn entryAssert(cond: bool, comptime msg: []const u8) callconv(.Inline) void { if (!cond) { hw.entry_uart.carefully(.{ msg, "\r\n" }); while (true) {} } } /// dainboot passes control here. MMU is **off**. We are in EL1. pub export fn daintree_mmu_start(entry_data: *dcommon.EntryData) noreturn { hw.entry_uart.init(entry_data); const daintree_base = arch.loadAddress("__daintree_base"); const daintree_rodata_base = arch.loadAddress("__daintree_rodata_base"); const daintree_data_base = arch.loadAddress("__daintree_data_base"); const daintree_end = arch.loadAddress("__daintree_end"); const daintree_main = arch.loadAddress("daintree_main"); const vbar_el1 = arch.loadAddress("__vbar_el1"); const current_el = arch.readRegister(.CurrentEL) >> 2; const sctlr_el1 = arch.readRegister(.SCTLR_EL1); const cpacr_el1 = arch.readRegister(.CPACR_EL1); hw.entry_uart.carefully(.{ "__daintree_base: ", daintree_base, "\r\n" }); hw.entry_uart.carefully(.{ "__daintree_rodata_base: ", daintree_rodata_base, "\r\n" }); hw.entry_uart.carefully(.{ "__daintree_data_base: ", daintree_data_base, "\r\n" }); hw.entry_uart.carefully(.{ "__daintree_end: ", daintree_end, "\r\n" }); hw.entry_uart.carefully(.{ "daintree_main: ", daintree_main, "\r\n" }); hw.entry_uart.carefully(.{ "__vbar_el1: ", vbar_el1, "\r\n" }); hw.entry_uart.carefully(.{ "CurrentEL: ", current_el, "\r\n" }); hw.entry_uart.carefully(.{ "SCTLR_EL1: ", sctlr_el1, "\r\n" }); hw.entry_uart.carefully(.{ "CPACR_EL1: ", cpacr_el1, "\r\n" }); const tcr_el1 = comptime (TCR_EL1{ .ips = .B36, .tg1 = .K4, .t1sz = 64 - PAGING.address_bits, // in practice: 25 .tg0 = .K4, .t0sz = 64 - PAGING.address_bits, }).toU64(); comptime std.debug.assert(0x00000001_b5193519 == tcr_el1); arch.writeRegister(.TCR_EL1, tcr_el1); const mair_el1 = comptime (MAIR_EL1{ .index = DEVICE_MAIR_INDEX, .attrs = 0b00 }).toU64() | (MAIR_EL1{ .index = MEMORY_MAIR_INDEX, .attrs = 0b1111_1111 }).toU64(); comptime std.debug.assert(0x00000000_000000ff == mair_el1); arch.writeRegister(.MAIR_EL1, mair_el1); var bump = paging.BumpAllocator{ .next = daintree_end }; TTBR0_IDENTITY = bump.alloc(PageTable); K_DIRECTORY = bump.alloc(PageTable); var l2 = bump.alloc(PageTable); var l3 = bump.alloc(PageTable); const ttbr0_el1 = @ptrToInt(TTBR0_IDENTITY) | 1; const ttbr1_el1 = @ptrToInt(K_DIRECTORY) | 1; hw.entry_uart.carefully(.{ "setting TTBR0_EL1: ", ttbr0_el1, "\r\n" }); hw.entry_uart.carefully(.{ "setting TTBR1_EL1: ", ttbr1_el1, "\r\n" }); arch.writeRegister(.TTBR0_EL1, ttbr0_el1); arch.writeRegister(.TTBR1_EL1, ttbr1_el1); // XXX add 100MiB to catch page tables var it = PAGING.range(1, entry_data.conventional_start, entry_data.conventional_bytes + 100 * 1048576); while (it.next()) |r| { hw.entry_uart.carefully(.{ "mapping identity: page ", r.page, " address ", r.address, "\r\n" }); TTBR0_IDENTITY.map(r.page, r.address, .block, .kernel_promisc); } K_DIRECTORY.map(0, @ptrToInt(l2), .table, .non_leaf); l2.map(0, @ptrToInt(l3), .table, .non_leaf); var end: u64 = (daintree_end - daintree_base) >> PAGING.page_bits; entryAssert(end <= 512, "end got too big (1)"); var i: u64 = 0; { var address = daintree_base; var flags: paging.MapFlags = .kernel_code; hw.entry_uart.carefully(.{ "MAP: text at ", PAGING.kernelPageAddress(i), "~\r\n" }); while (i < end) : (i += 1) { if (address >= daintree_data_base) { if (flags != .kernel_data) { hw.entry_uart.carefully(.{ "MAP: data at ", PAGING.kernelPageAddress(i), "~\r\n" }); flags = .kernel_data; } } else if (address >= daintree_rodata_base) { if (flags != .kernel_rodata) { hw.entry_uart.carefully(.{ "MAP: rodata at ", PAGING.kernelPageAddress(i), "~\r\n" }); flags = .kernel_rodata; } } l3.map(i, address, .table, flags); address += PAGING.page_size; } entryAssert(address == daintree_end, "address != daintree_end"); } hw.entry_uart.carefully(.{ "MAP: null at ", PAGING.kernelPageAddress(i), "\r\n" }); l3.map(i, 0, .table, .kernel_rodata); i += 1; end = i + STACK_PAGES; hw.entry_uart.carefully(.{ "MAP: stack at ", PAGING.kernelPageAddress(i), "~\r\n" }); while (i < end) : (i += 1) { l3.map(i, bump.allocPage(), .table, .kernel_data); } entryAssert(end <= 512, "end got too big (2)"); // Let's hackily put UART at wherever's next. hw.entry_uart.carefully(.{ "MAP: UART at ", PAGING.kernelPageAddress(i), "\r\n" }); l3.map(i, entry_data.uart_base, .table, .peripheral); // address now points to the stack. make space for common.EntryData, align. var entry_address = bump.next - @sizeOf(dcommon.EntryData); entry_address &= ~@as(u64, 15); var new_entry = @intToPtr(*dcommon.EntryData, entry_address); new_entry.* = .{ .memory_map = entry_data.memory_map, .memory_map_size = entry_data.memory_map_size, .descriptor_size = entry_data.descriptor_size, .dtb_ptr = undefined, .dtb_len = entry_data.dtb_len, .conventional_start = entry_data.conventional_start, .conventional_bytes = entry_data.conventional_bytes, .fb = entry_data.fb, .fb_vert = entry_data.fb_vert, .fb_horiz = entry_data.fb_horiz, .uart_base = PAGING.kernelPageAddress(i), .uart_width = entry_data.uart_width, .bump_next = undefined, }; var new_sp = PAGING.kernelPageAddress(i); new_sp -= @sizeOf(dcommon.EntryData); new_sp &= ~@as(u64, 15); // I hate that I'm doing this. Put the DTB in here. { i += 1; new_entry.dtb_ptr = @intToPtr([*]const u8, PAGING.kernelPageAddress(i)); var dtb_target = @intToPtr([*]u8, bump.next)[0..entry_data.dtb_len]; // How many pages? const dtb_pages = (entry_data.dtb_len + PAGING.page_size - 1) / PAGING.page_size; var new_end = end + 1 + dtb_pages; // Skip 1 page since UART is there entryAssert(new_end <= 512, "end got too big (3)"); hw.entry_uart.carefully(.{ "MAP: DTB at ", PAGING.kernelPageAddress(i), "~\r\n" }); while (i < new_end) : (i += 1) { l3.map(i, bump.allocPage(), .table, .kernel_rodata); } std.mem.copy(u8, dtb_target, entry_data.dtb_ptr[0..entry_data.dtb_len]); } new_entry.bump_next = bump.next; hw.entry_uart.carefully(.{ "MAP: end at ", PAGING.kernelPageAddress(i), ".\r\n" }); hw.entry_uart.carefully(.{ "about to install:\r\nsp: ", new_sp, "\r\n" }); hw.entry_uart.carefully(.{ "lr: ", daintree_main - daintree_base + PAGING.kernel_base, "\r\n" }); hw.entry_uart.carefully(.{ "vbar_el1: ", vbar_el1 - daintree_base + PAGING.kernel_base, "\r\n" }); hw.entry_uart.carefully(.{ "uart mapped to: ", PAGING.kernelPageAddress(i), "\r\n" }); // Control passes to daintree_main. asm volatile ( \\mov sp, %[sp] \\mov lr, %[lr] \\msr VBAR_EL1, %[vbar_el1] \\mov x0, %[sp] \\mrs x1, SCTLR_EL1 \\orr x1, x1, #1 \\msr SCTLR_EL1, x1 \\tlbi vmalle1 \\dsb ish \\isb \\ret : : [sp] "r" (new_sp), [lr] "r" (daintree_main - daintree_base + PAGING.kernel_base), [vbar_el1] "r" (vbar_el1 - daintree_base + PAGING.kernel_base) ); unreachable; }
dainkrnl/src/arm64/entry.zig
const gllparser = @import("../gllparser/gllparser.zig"); const Error = gllparser.Error; const Parser = gllparser.Parser; const ParserContext = gllparser.Context; const Result = gllparser.Result; const NodeName = gllparser.NodeName; const ResultStream = gllparser.ResultStream; const Literal = @import("../parser/literal.zig").Literal; const LiteralValue = @import("../parser/literal.zig").Value; const std = @import("std"); const testing = std.testing; const mem = std.mem; pub fn Context(comptime Payload: type, comptime V: type) type { return struct { /// The parser which should be repeatedly parsed. parser: *Parser(Payload, V), /// The minimum number of times the parser must successfully match. min: usize, /// The maximum number of times the parser can match, or -1 for unlimited. max: isize, }; } /// Represents a single value in the stream of repeated values. /// /// In the case of a non-ambiguous grammar, a `Repeated` combinator will yield: /// /// ``` /// stream(value1, value2) /// ``` /// /// In the case of an ambiguous grammar, it would yield a stream with only the first parse path. /// Use RepeatedAmbiguous if ambiguou parse paths are desirable. pub fn Value(comptime V: type) type { return struct { results: *ResultStream(Result(V)), pub fn deinit(self: *const @This(), allocator: mem.Allocator) void { self.results.deinit(); allocator.destroy(self.results); } }; } /// Matches the `input` repeatedly, between `[min, max]` times (inclusive.) If ambiguous parse paths /// are desirable, use RepeatedAmbiguous. /// /// The `input` parsers must remain alive for as long as the `Repeated` parser will be used. pub fn Repeated(comptime Payload: type, comptime V: type) type { return struct { parser: Parser(Payload, Value(V)) = Parser(Payload, Value(V)).init(parse, nodeName, deinit, countReferencesTo), input: Context(Payload, V), const Self = @This(); pub fn init(allocator: mem.Allocator, input: Context(Payload, V)) !*Parser(Payload, Value(V)) { const self = Self{ .input = input }; return try self.parser.heapAlloc(allocator, self); } pub fn initStack(input: Context(Payload, V)) Self { return Self{ .input = input }; } pub fn deinit(parser: *Parser(Payload, Value(V)), allocator: mem.Allocator, freed: ?*std.AutoHashMap(usize, void)) void { const self = @fieldParentPtr(Self, "parser", parser); self.input.parser.deinit(allocator, freed); } pub fn countReferencesTo(parser: *const Parser(Payload, Value(V)), other: usize, freed: *std.AutoHashMap(usize, void)) usize { const self = @fieldParentPtr(Self, "parser", parser); if (@ptrToInt(parser) == other) return 1; return self.input.parser.countReferencesTo(other, freed); } pub fn nodeName(parser: *const Parser(Payload, Value(V)), node_name_cache: *std.AutoHashMap(usize, NodeName)) Error!u64 { const self = @fieldParentPtr(Self, "parser", parser); var v = std.hash_map.hashString("Repeated"); v +%= try self.input.parser.nodeName(node_name_cache); v +%= std.hash_map.getAutoHashFn(usize, void)({}, self.input.min); v +%= std.hash_map.getAutoHashFn(isize, void)({}, self.input.max); return v; } pub fn parse(parser: *const Parser(Payload, Value(V)), in_ctx: *const ParserContext(Payload, Value(V))) callconv(.Async) Error!void { const self = @fieldParentPtr(Self, "parser", parser); var ctx = in_ctx.with(self.input); defer ctx.results.close(); // Invoke the child parser repeatedly to produce each of our results. Each time we ask // the child parser to parse, it can produce a set of results (its result stream) which // are varying parse paths / interpretations, we take the first successful one. // Return early if we're not trying to parse anything (stream close signals to the // consumer there were no matches). if (ctx.input.max == 0) { return; } var buffer = try ctx.allocator.create(ResultStream(Result(V))); errdefer ctx.allocator.destroy(buffer); errdefer buffer.deinit(); buffer.* = try ResultStream(Result(V)).init(ctx.allocator, ctx.key); var num_values: usize = 0; var offset: usize = ctx.offset; while (true) { const child_node_name = try self.input.parser.nodeName(&in_ctx.memoizer.node_name_cache); var child_ctx = try in_ctx.initChild(V, child_node_name, offset); defer child_ctx.deinitChild(); if (!child_ctx.existing_results) try self.input.parser.parse(&child_ctx); var num_local_values: usize = 0; var sub = child_ctx.subscribe(); while (sub.next()) |next| { switch (next.result) { .err => { offset = next.offset; if (num_values < ctx.input.min) { buffer.close(); buffer.deinit(); ctx.allocator.destroy(buffer); try ctx.results.add(Result(Value(V)).initError(next.offset, next.result.err)); return; } buffer.close(); try ctx.results.add(Result(Value(V)).init(offset, .{ .results = buffer })); return; }, else => { // TODO(slimsag): need path committal functionality if (num_local_values == 0) { offset = next.offset; // TODO(slimsag): if no consumption, could get stuck forever! try buffer.add(next.toUnowned()); } num_local_values += 1; }, } } num_values += 1; if (num_values >= ctx.input.max and ctx.input.max != -1) break; } buffer.close(); try ctx.results.add(Result(Value(V)).init(offset, .{ .results = buffer })); } }; } test "repeated" { nosuspend { const allocator = testing.allocator; const Payload = void; const ctx = try ParserContext(Payload, Value(LiteralValue)).init(allocator, "abcabcabc123abc", {}); defer ctx.deinit(); var abcInfinity = try Repeated(Payload, LiteralValue).init(allocator, .{ .parser = (try Literal(Payload).init(allocator, "abc")).ref(), .min = 0, .max = -1, }); defer abcInfinity.deinit(allocator, null); try abcInfinity.parse(&ctx); var sub = ctx.subscribe(); var repeated = sub.next().?.result.value; try testing.expect(sub.next() == null); // stream closed var repeatedSub = repeated.results.subscribe(ctx.key, ctx.path, Result(LiteralValue).initError(ctx.offset, "matches only the empty language")); try testing.expectEqual(@as(usize, 3), repeatedSub.next().?.offset); try testing.expectEqual(@as(usize, 6), repeatedSub.next().?.offset); try testing.expectEqual(@as(usize, 9), repeatedSub.next().?.offset); try testing.expect(repeatedSub.next() == null); // stream closed } }
src/combn/combinator/repeated.zig
const std = @import("std"); pub const Ipv4Host = extern struct { bytes: [4]u8, pub fn format( self: Ipv4Host, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { try writer.print("{}.{}.{}.{}", .{ self.bytes[0], self.bytes[1], self.bytes[2], self.bytes[3], }); } }; pub const IpHeader = extern struct { ver_ihl: u8, tos: u8, total_length: u16, id: u16, flags_fo: u16, ttl: u8, protocol: u8, checksum: u16, src_addr: Ipv4Host, dst_addr: Ipv4Host, }; pub const Icmp = extern struct { /// message type @"type": enum(u8) { ECHO_REPLY = 0, ECHO_REQUEST = 8, _ }, /// type sub-code code: u8, checksum: u16, un: extern union { /// path mtu discovery echo: extern struct { id_be: u16, sequence_be: u16, pub fn id(self: @This()) u16 { return std.mem.toNative(u16, self.id_be, .Big); } pub fn sequence(self: @This()) u16 { return std.mem.toNative(u16, self.sequence_be, .Big); } }, gateway: u32, frag: extern struct { _reserved: u16, mtu: u16, }, }, data: extern struct { bytes: [56]u8 = [_]u8{0} ** 56, pub fn setEchoTime(self: *@This(), time: std.os.timeval) void { std.mem.writeIntBig(u32, self.bytes[0..4], @intCast(u32, time.tv_sec)); std.mem.writeIntBig(i32, self.bytes[4..8], @intCast(i32, time.tv_usec)); } pub fn getEchoTime(self: @This()) std.os.timeval { var result: std.os.timeval = undefined; result.tv_sec = std.mem.readIntBig(u32, self.bytes[0..4]); result.tv_usec = std.mem.readIntBig(i32, self.bytes[4..8]); return result; } }, pub fn initEcho(id: u16, sequence: u16, time: std.os.timeval) Icmp { var result = Icmp{ .@"type" = .ECHO_REQUEST, .code = 0, .checksum = undefined, .un = .{ .echo = .{ .id_be = std.mem.nativeTo(u16, id, .Big), .sequence_be = std.mem.nativeTo(u16, sequence, .Big), }, }, .data = .{}, }; result.data.setEchoTime(time); result.recalcChecksum(); return result; } pub fn recalcChecksum(self: *Icmp) void { self.checksum = 0; self.checksum = rfc1071Checksum(std.mem.asBytes(self)); } pub fn checksumValid(self: Icmp) bool { var copy = self; copy.checksum = 0; return self.checksum == rfc1071Checksum(std.mem.asBytes(&copy)); } }; pub fn rfc1071Checksum(bytes: []const u8) u16 { const slice = std.mem.bytesAsSlice(u16, bytes); var sum: u16 = 0; for (slice) |d| { if (@addWithOverflow(u16, sum, d, &sum)) { sum += 1; } } return ~sum; } pub fn icmpConnectTo(allocator: *std.mem.Allocator, name: []const u8) !std.fs.File { const list = try std.net.getAddressList(allocator, name, 0); defer list.deinit(); if (list.addrs.len == 0) return error.UnknownHostName; for (list.addrs) |addr| { return icmpConnectToAddress(addr) catch |err| switch (err) { error.ConnectionRefused => continue, else => return err, }; } return error.ConnectionRefused; } pub fn icmpConnectToAddress(address: std.net.Address) !std.fs.File { const nonblock = if (std.io.is_async) std.os.SOCK_NONBLOCK else 0; const sock_flags = std.os.SOCK_DGRAM | nonblock | (if (std.builtin.os.tag == .windows) 0 else std.os.SOCK_CLOEXEC); const sockfd = try std.os.socket(address.any.family, sock_flags, std.os.IPPROTO_ICMP); errdefer std.os.closeSocket(sockfd); if (std.io.is_async) { const loop = std.event.Loop.instance orelse return error.WouldBlock; try loop.connect(sockfd, &address.any, address.getOsSockLen()); } else { try std.os.connect(sockfd, &address.any, address.getOsSockLen()); } return std.fs.File{ .handle = sockfd }; }
src/netx.zig
const std = @import("std"); const builtin = @import("builtin"); const liu = @import("./lib.zig"); const EPSILON: f32 = 0.000001; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; // Parser - https://github.com/RazrFalcon/ttf-parser // Raster - https://github.com/raphlinus/font-rs pub fn accumulate(alloc: Allocator, src: []const f32) ![]u8 { var acc: f32 = 0.0; const out = try alloc.alloc(u8, src.len); for (src) |c, idx| { acc += c; var y = @fabs(acc); y = if (y < 1.0) y else 1.0; out[idx] = @floatToInt(u8, 255.0 * y); } return out; } const Point = struct { x: f32, y: f32, pub fn intInit(x: i64, y: i64) Point { const xF = @intToFloat(f32, x); const yF = @intToFloat(f32, y); return .{ .x = xF, .y = yF }; } pub fn lerp(t0: f32, p0: Point, p1: Point) Point { const t = @splat(2, t0); const d0 = liu.Vec2{ p0.x, p0.y }; const d1 = liu.Vec2{ p1.x, p1.y }; const data = d0 + t * (d1 - d0); return Point{ .x = data[0], .y = data[1] }; } }; const Affine = struct { data: [6]f32, pub fn concat(t1: *const Affine, t2: *const Affine) Affine { _ = t1; _ = t2; const Vec6 = @Vector(6, f32); const v0 = Vec6{ t1[0], t1[1], t1[0], t1[1], t1[0], t1[1] }; const v1 = Vec6{ t2[0], t2[0], t2[2], t2[2], t2[4], t2[4] }; const v2 = Vec6{ t1[2], t1[3], t1[2], t1[3], t1[2], t1[3] }; const v3 = Vec6{ t2[1], t2[1], t2[3], t2[3], t2[5], t2[5] }; var out = v0 * v1 + v2 * v3; out[4] += t1[4]; out[5] += t1[5]; return Affine{ .data = out }; } pub fn pt(z: *const Affine, p: *const Point) Point { const v0 = liu.Vec2{ z.data[0], z.data[1] }; const v1 = liu.Vec2{ p.x, p.x }; const v2 = liu.Vec2{ z.data[2], z.data[3] }; const v3 = liu.Vec2{ p.y, p.y }; const v4 = liu.Vec2{ z.data[4], z.data[5] }; const data = v0 * v1 + v2 * v3 + v4; return Point{ .x = data[0], .y = data[1] }; } }; const Metrics = struct { l: i32, t: i32, r: i32, b: i32, pub fn width(self: *const Metrics) usize { return @intCast(usize, self.r - self.l); } pub fn height(self: *const Metrics) usize { return @intCast(usize, self.b - self.t); } }; pub const VMetrics = struct { ascent: f32, descent: f32, line_gap: f32, }; pub const HMetrics = struct { advance_width: f32, left_side_bearing: f32, }; const Raster = struct { w: usize, h: usize, a: []f32, pub fn init(alloc: Allocator, w: usize, h: usize) !Raster { const a = try alloc.alloc(f32, w * h + 4); std.mem.set(f32, a, 0.0); return Raster{ .w = w, .h = h, .a = a }; } pub fn drawLine(self: *Raster, _p0: Point, _p1: Point) void { if (@fabs(_p0.y - _p1.y) <= EPSILON) { return; } var p0 = _p0; var p1 = _p1; const dir: f32 = if (p0.y < p1.y) 1.0 else value: { p0 = _p1; p1 = _p0; break :value -1.0; }; const dxdy = (p1.x - p0.x) / (p1.y - p0.y); var x = p0.x; if (p0.y < 0.0) { x -= p0.y * dxdy; } const h_f32 = @intToFloat(f32, self.h); const max = @floatToInt(usize, std.math.min(h_f32, @ceil(p1.y))); // Raph says: "note: implicit max of 0 because usize (TODO: really true?)" // Raph means: Who tf knows. Wouldn't it be the MIN that's zero? Also, // doesn't your coordinate system start at zero anyways? var y: usize = @floatToInt(usize, p0.y); while (y < max) : (y += 1) { const linestart = y * self.w; const y_plus_1 = @intToFloat(f32, y + 1); const y_f32 = @intToFloat(f32, y); const dy = std.math.min(y_plus_1, p1.y) - std.math.max(y_f32, p0.y); const d = dy * dir; const xnext = x + dxdy * dy; var x0 = xnext; var x1 = x; if (x < xnext) { x0 = x; x1 = xnext; } const x0floor = @floor(x0); const x0i = @floatToInt(i32, x0floor); const x1ceil = @ceil(x1); const x1i = @floatToInt(i32, x1ceil); const linestart_x0i = @intCast(isize, linestart) + x0i; if (linestart_x0i < 0) { continue; // oob index } const linestart_x0 = @intCast(usize, linestart_x0i); if (x1i <= x0i + 1) { const xmf = 0.5 * (x + xnext) - x0floor; self.a[linestart_x0] += d - d * xmf; self.a[linestart_x0 + 1] += d * xmf; } else { const s = 1.0 / (x1 - x0); const x0f = x0 - x0floor; const a0 = 0.5 * s * (1.0 - x0f) * (1.0 - x0f); const x1f = x1 - x1ceil + 1.0; const am = 0.5 * s * x1f * x1f; self.a[linestart_x0] += d * a0; if (x1i == x0i + 2) { self.a[linestart_x0 + 1] += d * (1.0 - a0 - am); } else { const a1 = s * (1.5 - x0f); self.a[linestart_x0 + 1] += d * (a1 - a0); var xi: usize = @intCast(usize, x0i) + 2; while (xi < x1i - 1) : (xi += 1) { self.a[linestart + xi] += d * s; } const a2 = a1 + @intToFloat(f32, x1i - x0i - 3) * s; self.a[linestart + @intCast(usize, x1i - 1)] += d * (1.0 - a2 - am); } self.a[linestart + @intCast(usize, x1i)] += d * am; } x = xnext; } } pub fn drawQuad(self: *Raster, p0: Point, p1: Point, p2: Point) void { const devx = p0.x - 2.0 * p1.x + p2.x; const devy = p0.y - 2.0 * p1.y + p2.y; const devsq = devx * devx + devy * devy; if (devsq < 0.333) { self.drawLine(p0, p2); return; } // I'm pretty sure `tol` here stands for tolerance but the original code // says `tol` and i dont wanna change it without knowing what `tol` // actually stands for const tol = 3.0; const n = n: { // No idea what these interim values are, but having it be // written the other way seems dumb idk const idk0 = devx * devx + devy * devy; const idk1 = tol * idk0; const idk2 = @floor(@sqrt(@sqrt(idk1))); const idk3 = 1 + @floatToInt(usize, idk2); break :n idk3; }; var p = p0; const nrecip = 1 / @intToFloat(f32, n); var t: f32 = 0.0; var i: u32 = 0; while (i < n - 1) : (i += 1) { t += nrecip; const a = Point.lerp(t, p0, p1); const b = Point.lerp(t, p1, p2); const pn = Point.lerp(t, a, b); self.drawLine(p, pn); p = pn; } self.drawLine(p, p2); } }; const native_endian = builtin.target.cpu.arch.endian(); pub fn read(bytes: []const u8, comptime T: type) ?T { const Size = @sizeOf(T); if (bytes.len < Size) return null; switch (@typeInfo(T)) { .Int => { var value: T = @bitCast(T, bytes[0..Size].*); if (native_endian != .Big) value = @byteSwap(T, value); return value; }, else => @compileError("input type is not allowed (only allows integers right now)"), } } const FontParseError = error{ HeaderInvalid, OffsetInvalid, OffsetLengthInvalid, Unknown, }; const Font = struct { version: u32, head: []const u8, maxp: []const u8, loca: ?[]const u8, cmap: ?[]const u8, glyf: ?[]const u8, hhea: ?[]const u8, hmtx: ?[]const u8, const TagDescriptor = struct { tag: u32, value: usize }; const Tag = enum(u16) { head, maxp, loca, glyf, cmap, hhea, hmtx, _ }; const Count = std.meta.fields(Tag).len; const TagData: []const TagDescriptor = tags: { var data: []const TagDescriptor = &.{}; for (std.meta.fields(Tag)) |field| { data = data ++ [_]TagDescriptor{.{ .tag = @bitCast(u32, field.name[0..4].*), .value = field.value, }}; } break :tags data; }; pub fn init(data: []const u8) FontParseError!Font { const HeadErr = error.HeaderInvalid; const version = read(data[0..], u32) orelse return HeadErr; const num_tables = read(data[4..], u16) orelse return HeadErr; var tags: [Count]?[]const u8 = .{null} ** Count; var i: u16 = 0; table_loop: while (i < num_tables) : (i += 1) { const entry_begin = 12 + i * 16; const header = data[entry_begin..][0..16]; const offset = read(header[8..], u32) orelse return HeadErr; const length = read(header[12..], u32) orelse return HeadErr; if (offset > data.len) return error.OffsetInvalid; if (offset + length > data.len) return error.OffsetLengthInvalid; const table_data = data[offset..][0..length]; const tag = @bitCast(u32, header[0..4].*); // Ideally the code below should use: // // ``` // inline for (std.meta.fields(Tag)) |field| { // ``` // // But that seg-faults. Seems like a compiler bug. for (TagData) |field| { if (tag == field.tag) { tags[field.value] = table_data; continue :table_loop; } } } return Font{ .version = version, .head = tags[@enumToInt(Tag.head)] orelse return HeadErr, .maxp = tags[@enumToInt(Tag.maxp)] orelse return HeadErr, .loca = tags[@enumToInt(Tag.loca)], .cmap = tags[@enumToInt(Tag.cmap)], .glyf = tags[@enumToInt(Tag.glyf)], .hhea = tags[@enumToInt(Tag.hhea)], .hmtx = tags[@enumToInt(Tag.hmtx)], }; } // IDK what to do here yet pub fn getGlyphId(self: *const Font, code_point: u32) FontParseError!?u16 { if (code_point > std.math.maxInt(u16)) { return null; } // const num_tables = read(self.cmap[0..], u16) orelse return error.OffsetInvalid; // if (self.cmap.len < 4 + num_tables * 8) { // return error.OffsetLengthInvalid; // } // const encoding = encoding: { // var i: u16 = 0; // while (i < num_tables) : (i += 1) { // const offset = 8 * i + 4; // const table = self.cmap[offset..][0..8]; // const subtable_offset = read(table[4..], u32) orelse return error.OffsetInvalid; // const subtable_len = read(self.cmap[(subtable_offset + 2)..], u16) orelse // return error.OffsetInvalid; // const subtable = self.cmap[subtable_offset..][0..subtable_len]; // const format = read(subtable[0..], u16) orelse return error.OffsetInvalid; // std.debug.print("\nasdf: {}\n", .{format}); // if (format == 4) break :encoding subtable; // } // return error.Unknown; // }; // _ = encoding; _ = self; return 12; } }; // https://github.com/A1Liu/ted/blob/624527d690bd7019d463b51baa8fac8bea796c00/src/editor/fonts.rs#L71 // let face = expect(ttf::Face::from_slice(COURIER, 0)); // let (ascent, descent) = (face.ascender(), face.descender()); // let line_gap = face.line_gap(); // let glyph_id = unwrap(face.glyph_index('_')); // let rect = unwrap(face.glyph_bounding_box(glyph_id)); // face.outline_glyph(id, &mut builder); test "Fonts: basic" { const mark = liu.TempMark; defer liu.TempMark = mark; const bytes = @embedFile("../../static/fonts/cour.ttf"); const f = try Font.init(bytes); _ = try f.getGlyphId('A'); const affine = Affine{ .data = .{ 0, 1, 0, 1, 0.5, 0.25 } }; const p0 = Point{ .x = 1, .y = 0 }; const p1 = Point{ .x = 0, .y = 1 }; const p2 = Point{ .x = 0, .y = 0 }; var raster = try Raster.init(liu.Temp, 100, 100); raster.drawLine(p0, p1); raster.drawQuad(p0, p1, p2); _ = Point.lerp(0.5, p0, p1); _ = affine.pt(&p1); const out = try accumulate(liu.Temp, raster.a); _ = out; }
src/liu/fonts.zig
const std = @import("std"); const ArrayList = std.ArrayList; const AutoHashMap = std.AutoHashMap; const Allocator = std.mem.Allocator; const print = std.debug.print; const helpers = @import("helpers.zig"); const mode = @import("builtin").mode; const dbg = helpers.dbg; const testing = std.testing; /// A node in an undirected graph. It holds a value, and a hashmap representing /// edges where each entry stores the adjacent node pointer as its key and the /// weight as its value. /// `Value` is the type of data to be stored in `Node`s, with copy semantics. /// `Weight` is the type of weights or costs between `Node`s. Weights are /// allocated twice, once in each nodes' edge hashmap. An edge that is set /// twice between the same two nodes simply has its weight updated. pub fn Node(comptime Value: type, comptime Weight: type) type { return struct { pub const Self = @This(); pub const EdgeMap = AutoHashMap(*Self, Weight); pub const Edge = struct { that: *Self, weight: Weight, }; /// An edges between two node pointers. Isn't used by Nodes to store /// their edges (a hashmap is used instead) but rather when enumerating /// all edges in the graph. pub const FullEdge = struct { this: *Self, that: *Self, weight: Weight, }; allocator: Allocator, value: Value, /// Individual edges are stored twice, once in each node in a pair /// that form the edge. These are separate from `FullEdge` structs, which /// keep track of pairs of nodes. edges: EdgeMap, /// Creates a new node, allocating a copy of Value. pub fn init(allocator: Allocator, value: Value) !*Self { var node = try allocator.create(Self); node.* = Self{ .allocator = allocator, .value = value, .edges = EdgeMap.init(allocator), }; return node; } /// Same as `init`, but initializes this node's hashmap to the edges /// passed in. Duplicate edges will only have the last copy saved. pub fn initWithEdges( allocator: Allocator, value: Value, edges: []const Edge, ) !*Self { var node = try init(allocator, value); // Add edges into the hashmap. for (edges) |edge| try node.addEdge(edge.that, edge.weight); return node; } /// Puts an edge entry into each node's hashmap. /// If the edge already exists, the weight will be updated. pub fn addEdge(self: *Self, other: *Self, weight: Weight) !void { // Use of `put` assumes `edges` was passed in with no // duplicates, otherwise will overwrite the weight. try self.edges.put(other, weight); // Add this node to the adjacent's edges try other.edges.put(self, weight); } /// Removes an edge by deleting the outgoing and all incoming /// references. // Assumes edges are always a valid pair of incoming/outgoing pub fn removeEdge(self: *Self, other: *Self) bool { return self.edges.remove(other) and // Remove outgoing other.edges.remove(self); // Remove incoming } /// Removes a node and all its references (equivalent to calling /// detach and destroy, but faster). /// You probably want this function instead of calling both detach and /// destroy. pub fn deinit(self: *Self, allocator: Allocator) void { var edge_iter = self.edges.keyIterator(); while (edge_iter.next()) |adjacent| _ = adjacent.*.edges.remove(self); self.edges.deinit(); // Free this list of edges allocator.destroy(self); // Free this node } /// Detach adjacent nodes (erase their references of this node). pub fn detach(self: *Self) void { var edge_iter = self.edges.keyIterator(); // Free incoming references to this node in adjacents. while (edge_iter.next()) |adjacent| { const was_removed = adjacent.*.edges.remove(self); comptime { if (std.builtin.mod == .debugs) testing.expect(!was_removed); } } // Free outgoing references self.edges.clear(); // self.edges.clearRetainingCapacity(); } /// Free the memory backing this node. /// Incoming edges will no longer be valid, so this function should /// only be called on detached nodes (ones without edges). pub fn destroy(self: *Self) void { self.edges.deinit(); // Free this list of edges self.allocator.destroy(self); // Free this node } /// Returns a set of all nodes in this graph. /// Caller frees (calls `deinit`). // Node pointers must be used because HashMaps don't allow structs // containing slices. pub fn nodeSet( self: *const Self, allocator: Allocator, ) !AutoHashMap(*const Self, void) { var node_set = AutoHashMap(*const Self, void).init(allocator); // A stack to add nodes reached across edges var to_visit = ArrayList(*const Self).init(allocator); defer to_visit.deinit(); // Greedily add all neighbors to `to_visit`, then loop until // no new neighbors are found. try to_visit.append(self); while (to_visit.popOrNull()) |node_ptr| { // If the node is unvisited if (!node_set.contains(node_ptr)) { // Add to set (marks as visited) try node_set.put(node_ptr, {}); // Save adjacent nodes to check later var adjacents = self.edges.keyIterator(); while (adjacents.next()) |adjacent_ptr| { try to_visit.append(adjacent_ptr.*); } } } return node_set; } /// Returns a set of all node pointers in this graph. /// If you don't need to mutate any nodes, call `nodes` instead. /// Caller frees (calls `deinit`). pub fn nodePtrSet( self: *Self, allocator: Allocator, ) !AutoHashMap(*Self, void) { var node_set = AutoHashMap(*Self, void).init(allocator); // A stack to add nodes reached across edges var to_visit = ArrayList(*Self).init(allocator); defer to_visit.deinit(); // Greedily add all neighbors to `to_visit`, then loop until // no new neighbors are found. try to_visit.append(self); while (to_visit.popOrNull()) |node_ptr| { // If the node is unvisited if (!node_set.contains(node_ptr)) { // Add to set (marks as visited) try node_set.put(node_ptr, {}); // Save adjacent nodes to check later var adjacents = self.edges.keyIterator(); while (adjacents.next()) |adjacent_ptr| { try to_visit.append(adjacent_ptr.*); } } } return node_set; } /// Returns a set of all edges in this graph. /// Caller frees (calls `deinit`). pub fn edgeSet( self: *Self, allocator: Allocator, ) !AutoHashMap(FullEdge, void) { // Use a 0 size value (void) to use a hashmap as a set, in order // to avoid listing edges twice. var edge_set = AutoHashMap(FullEdge, void).init(allocator); // Get a view of all nodes var node_set = try self.nodePtrSet(allocator); defer node_set.deinit(); var nodes_iter = node_set.keyIterator(); while (nodes_iter.next()) |node_ptr| { // For each node var edge_iter = node_ptr.*.edges.iterator(); // Get its edges while (edge_iter.next()) |edge_entry| { // For each edge if (!edge_set.contains( // If it's reverse isn't in yet FullEdge{ .this = edge_entry.key_ptr.*, .that = node_ptr.*, .weight = edge_entry.value_ptr.*, }, )) // Overwrite if the edge exists already try edge_set.put( FullEdge{ .this = node_ptr.*, .that = edge_entry.key_ptr.*, .weight = edge_entry.value_ptr.*, }, {}, // The 0 size "value" ); } } return edge_set; } /// Pass into `exportDot` to configure dot output. pub const DotSettings = struct { // graph_setting: ?String = null, // node_setting: ?String = null, // edge_setting: ?String = null, }; /// Writes the graph out in dot (graphviz) to the given `writer`. /// Node value types currently must be `[]const u8`. pub fn exportDot( self: *Self, allocator: Allocator, writer: anytype, dot_settings: DotSettings, ) !void { _ = dot_settings; // TODO try writer.writeAll("Graph {\n"); var node_set = try self.nodePtrSet(allocator); defer node_set.deinit(); var nodes_iter = node_set.keyIterator(); while (nodes_iter.next()) |node_ptr| { try writer.print( "{s} [];\n", .{node_ptr.*.value}, ); } var edge_set = try self.edgeSet(self.allocator); defer edge_set.deinit(); var edge_iter = edge_set.keyIterator(); while (edge_iter.next()) |edge| { try writer.print( "{s} -- {s} [label={}];\n", .{ edge.this.value, edge.that.value, edge.weight, }, ); } try writer.writeAll("}\n"); } }; } // TODO: test memory under rare conditions: // - allocator failure // - inside add: allocator succeeds but list append fails test "graph memory management" { std.testing.log_level = .debug; const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).init(allocator, "n2"); defer node2.deinit(allocator); try node1.addEdge(node2, 123); } test "iterate over single node" { const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var edges = try node1.edgeSet(allocator); defer edges.deinit(); var edge_iter = edges.keyIterator(); // Print nodes' values while (edge_iter.next()) |edge_ptr| { print("({s})--[{}]--({s})\n", .{ edge_ptr.this.value, edge_ptr.weight, edge_ptr.that.value, }); } } test "iterate over edges" { const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).initWithEdges(allocator, "n2", &.{}); defer node2.deinit(allocator); var node3 = try Node([]const u8, u32).initWithEdges(allocator, "n3", &.{}); defer node3.deinit(allocator); const node4 = try Node([]const u8, u32).initWithEdges( allocator, "n4", // Segfaults if an anon struct is used instead &[_]Node([]const u8, u32).Edge{ .{ .that = node1, .weight = 41 }, }, ); defer node4.deinit(allocator); try node1.addEdge(node2, 12); try node3.addEdge(node1, 31); try node2.addEdge(node1, 21); // should update 12 to 21 try node2.addEdge(node1, 21); // should be a no op try node2.addEdge(node3, 23); // Allocate the current edges var edges = try node1.edgeSet(allocator); defer edges.deinit(); // The hashmap is used as a set, so it only has keys var edge_iter = edges.keyIterator(); // Print their nodes' values and the weights between them while (edge_iter.next()) |edge| { print("({s})--[{}]--({s})\n", .{ edge.this.value, edge.weight, edge.that.value, }); } } test "dot export" { const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).init(allocator, "n2"); defer node2.deinit(allocator); try node1.addEdge(node2, 123); _ = try node1.exportDot(allocator, std.io.getStdOut().writer(), .{}); } test "remove edge" { std.testing.log_level = .debug; const allocator = std.testing.allocator; var node1 = try Node([]const u8, u32).init(allocator, "n1"); defer node1.deinit(allocator); var node2 = try Node([]const u8, u32).init(allocator, "n2"); defer node2.deinit(allocator); try node1.addEdge(node2, 123); try testing.expect(node1.removeEdge(node2)); // should be removable try testing.expect(!node1.removeEdge(node2)); // shouldn't be there }
src/graph.zig
const std = @import("std"); const testing = std.testing; pub fn main() void {} inline fn swap(comptime T: type, a: *T, b: *T) void { const tmp = a.*; a.* = b.*; b.* = tmp; } pub const PermutationError = error{ListTooLong}; /// Returns an iterator that iterates all the permutations of `list`. /// `permutate(u8, slice_of_bytes)` /// will return all permutations of slice_of_bytes followed by `null` as the last value. /// If `list.len` is greater than 16 an error is returned. pub fn permutate(comptime T: type, list: []T) PermutationError!PermutationIterator(T) { if (list.len > 16) return PermutationError.ListTooLong; return PermutationIterator(T){ .list = list[0..], .size = @intCast(u4, list.len), .state = [_]u4{0} ** 16, .stateIndex = 0, .first = true, }; } pub fn PermutationIterator(comptime T: type) type { return struct { list: []T, size: u4, state: [16]u4, stateIndex: u4, first: bool, const Self = @This(); pub fn next(self: *Self) ?[]T { if (self.first) { self.first = false; return self.list; } while (self.stateIndex < self.size) { if (self.state[self.stateIndex] < self.stateIndex) { if (self.stateIndex % 2 == 0) { swap(T, &self.list[0], &self.list[self.stateIndex]); } else { swap(T, &self.list[self.state[self.stateIndex]], &self.list[self.stateIndex]); } self.state[self.stateIndex] += 1; self.stateIndex = 0; return self.list; } else { self.state[self.stateIndex] = 0; self.stateIndex += 1; } } return null; } }; } test "permutate []u8" { var input = "ab".*; var pit = try permutate(u8, input[0..]); try testing.expectEqualStrings("ab", pit.next().?); try testing.expectEqualStrings("ba", pit.next().?); } test "list too long" { var input = [_]u8{0} ** 17; var pit = permutate(u8, &input); try testing.expectError(PermutationError.ListTooLong, pit); } test "swap u32" { const exp_a: u32 = 5; const exp_b: u32 = 3; var a: u32 = 3; var b: u32 = 5; swap(u32, &a, &b); try testing.expectEqual(exp_a, a); try testing.expectEqual(exp_b, b); } test "swap u32 in slice" { const exp_a: u32 = 5; const exp_b: u32 = 3; var s = [_]u32{ 3, 5 }; swap(u32, &s[0], &s[1]); try testing.expectEqual(exp_a, s[0]); try testing.expectEqual(exp_b, s[1]); } test "generates 10! perms" { var str = "0123456789".*; const expected: usize = 3628800; var count: usize = 0; var pit = try permutate(u8, str[0..]); while (pit.next()) |_| { count += 1; } try testing.expectEqual(expected, count); }
src/permutate.zig
const bld = @import("std").build; const mem = @import("std").mem; const zig = @import("std").zig; // build sokol into a static library pub fn buildSokol(b: *bld.Builder, comptime prefix_path: []const u8) *bld.LibExeObjStep { const lib = b.addStaticLibrary("sokol", null); lib.linkLibC(); lib.setBuildMode(b.standardReleaseOptions()); const sokol_path = prefix_path ++ "src/sokol/c/"; const csources = [_][]const u8{ "sokol_app.c", "sokol_gfx.c", "sokol_time.c", "sokol_audio.c", "sokol_gl.c", "sokol_debugtext.c", "sokol_shape.c", }; if (lib.target.isDarwin()) { b.env_map.set("ZIG_SYSTEM_LINKER_HACK", "1") catch unreachable; inline for (csources) |csrc| { lib.addCSourceFile(sokol_path ++ csrc, &[_][]const u8{ "-ObjC", "-DIMPL" }); } lib.linkFramework("MetalKit"); lib.linkFramework("Metal"); lib.linkFramework("Cocoa"); lib.linkFramework("QuartzCore"); lib.linkFramework("AudioToolbox"); } else { inline for (csources) |csrc| { lib.addCSourceFile(sokol_path ++ csrc, &[_][]const u8{"-DIMPL"}); } if (lib.target.isLinux()) { lib.linkSystemLibrary("X11"); lib.linkSystemLibrary("Xi"); lib.linkSystemLibrary("Xcursor"); lib.linkSystemLibrary("GL"); lib.linkSystemLibrary("asound"); } else if (lib.target.isWindows()) { lib.linkSystemLibrary("gdi32"); } // exe.linkSystemLibrary("user32"); // exe.linkSystemLibrary("shell32"); // exe.linkSystemLibrary("kernel32"); } return lib; } // build one of the example exes fn buildExample(b: *bld.Builder, comptime prefix_path: []const u8, sokol: *bld.LibExeObjStep, comptime name: []const u8) void { const e = b.addExecutable(name, prefix_path ++ "src/examples/" ++ name ++ ".zig"); const sokol_path = prefix_path ++ "src/sokol/"; e.linkLibrary(sokol); e.setBuildMode(b.standardReleaseOptions()); e.addPackagePath("sokol", sokol_path ++ "sokol.zig"); e.install(); b.step("run-" ++ name, "Run " ++ name).dependOn(&e.run().step); } fn buildMain(b: *bld.Builder, comptime prefix_path: []const u8, sokol: *bld.LibExeObjStep, comptime name: []const u8) void { const e = b.addExecutable(name, "main.zig"); const sokol_path = prefix_path ++ "src/sokol/"; e.linkLibrary(sokol); e.setBuildMode(b.standardReleaseOptions()); e.addCSourceFile("external/DDSLoader/src/dds.c", &[_][]const u8{"-std=c99"}); e.addIncludeDir("external"); e.addPackagePath("sokol", sokol_path ++ "sokol.zig"); e.addPackagePath("zigimg", "external/zigimg/zigimg.zig"); e.addPackagePath("nooice", "external/nooice/src/nooice.zig"); e.install(); b.step("run-" ++ name, "Run " ++ name).dependOn(&e.run().step); } // fn buildShaders(b: *bld.Builder, comptime prefix_path: []const u8, sokol: *bld.LibExeObjStep, comptime name: []const u8) void { // const e = b.add(name, name ++ "lol.zig"); // const sokol_path = prefix_path ++ "src/sokol/"; // e.linkLibrary(sokol); // e.setBuildMode(b.standardReleaseOptions()); // e.addPackagePath("sokol", sokol_path ++ "sokol.zig"); // e.install(); // b.step("run-" ++ name, "Run " ++ name).dependOn(&e.run().step); // } pub fn build(b: *bld.Builder) void { const prefix_path = "external/sokol-zig/"; const sokol = buildSokol(b, prefix_path); buildMain(b, prefix_path, sokol, "misty"); // buildExample(b, prefix_path, sokol, "clear"); // buildExample(b, prefix_path, sokol, "clear"); // buildExample(b, prefix_path, sokol, "triangle"); // buildExample(b, prefix_path, sokol, "quad"); // buildExample(b, prefix_path, sokol, "bufferoffsets"); // buildExample(b, prefix_path, sokol, "cube"); // buildExample(b, prefix_path, sokol, "noninterleaved"); // buildExample(b, prefix_path, sokol, "texcube"); // buildExample(b, prefix_path, sokol, "offscreen"); // buildExample(b, prefix_path, sokol, "instancing"); // buildExample(b, prefix_path, sokol, "mrt"); // buildExample(b, prefix_path, sokol, "saudio"); // buildExample(b, prefix_path, sokol, "sgl"); // buildExample(b, prefix_path, sokol, "debugtext"); // buildExample(b, prefix_path, sokol, "debugtext-print"); // buildExample(b, prefix_path, sokol, "debugtext-userfont"); // buildExample(b, prefix_path, sokol, "shapes"); }
build.zig
const std = @import("std"); const tools = @import("tools"); const with_trace = false; fn trace(comptime fmt: []const u8, args: anytype) void { if (with_trace) std.debug.print(fmt, args); } const assert = std.debug.assert; pub const main = tools.defaultMain("2021/day07.txt", run); fn fuelCost_part1(dist: u32) u32 { return dist; } fn fuelCost_part2(dist: u32) u32 { return dist * (dist + 1) / 2; } fn computeTotalFuel(list: []i16, t: i16, fuelcostFn: fn (u32) u32) u64 { var total: u64 = 0; for (list) |p| { total += fuelcostFn(@intCast(u32, std.math.absInt(t - p) catch unreachable)); } return total; } fn findBest(list: []i16, fuelcostFn: fn (u32) u32) u64 { var pos_left: i16 = 0; //std.mem.min(i16, list); var pos_right: i16 = 10000; //std.mem.max(i16, list); var eval_left = computeTotalFuel(list, pos_left, fuelcostFn); var eval_right = computeTotalFuel(list, pos_right, fuelcostFn); trace("left={} -> {}\n", .{ pos_left, eval_left }); trace("right={} -> {}\n", .{ pos_right, eval_right }); //var p = pos_left; //while (p < pos_right) : (p += 1) { // const eval = computeTotalFuel(list, p, fuelcostFn); // trace("pos={} eval={}\n", .{ p, eval }); // if (eval_left > eval) eval_left = eval; //} // fontions en V : on est soit sur la partie \ soit sur la partie /... while (pos_left < pos_right) { var mid = @divFloor(pos_left + pos_right, 2); const eval0 = computeTotalFuel(list, mid, fuelcostFn); const eval1 = computeTotalFuel(list, mid + 1, fuelcostFn); trace("[{}...{}]: {} -> {},{}\n", .{ pos_left, pos_right, mid, eval0, eval1 }); if (eval0 > eval1) { // dans la moitié décroisante pos_left = mid + 1; eval_left = eval1; } else { // dans la moitié croisante pos_right = mid; eval_right = eval0; } } assert(eval_left == eval_right); return eval_left; } pub fn run(input: []const u8, gpa: std.mem.Allocator) tools.RunError![2][]const u8 { var list0 = std.ArrayList(i16).init(gpa); defer list0.deinit(); { try list0.ensureTotalCapacity(input.len / 2); var it = std.mem.tokenize(u8, input, ", \t\n\r"); while (it.next()) |num| { try list0.append(try std.fmt.parseInt(i16, num, 10)); } } const ans1 = findBest(list0.items, fuelCost_part1); const ans2 = findBest(list0.items, fuelCost_part2); // bonus: if (list0.items[0] > 1000) { var cpu = tools.IntCode_Computer{ .name = "decoder", .memory = try gpa.alloc(tools.IntCode_Computer.Data, 10000), }; defer gpa.free(cpu.memory); const image = try gpa.alloc(tools.IntCode_Computer.Data, list0.items.len); defer gpa.free(image); for (image) |*m, i| { m.* = list0.items[i]; } cpu.boot(image); _ = async cpu.run(); while (!cpu.is_halted()) { switch (cpu.io_mode) { .input => unreachable, .output => trace("{c}", .{@intCast(u8, cpu.io_port)}), // "Ceci n'est pas une intcode program" } resume cpu.io_runframe; } } return [_][]const u8{ try std.fmt.allocPrint(gpa, "{}", .{ans1}), try std.fmt.allocPrint(gpa, "{}", .{ans2}), }; } test { const res = try run("16,1,2,0,4,2,7,1,2,14", std.testing.allocator); defer std.testing.allocator.free(res[0]); defer std.testing.allocator.free(res[1]); try std.testing.expectEqualStrings("37", res[0]); try std.testing.expectEqualStrings("168", res[1]); }
2021/day07.zig
const actorNs = @import("actor.zig"); const Actor = actorNs.Actor; const ActorInterface = actorNs.ActorInterface; const msgNs = @import("message.zig"); const Message = msgNs.Message; const MessageHeader = msgNs.MessageHeader; const messageQueueNs = @import("message_queue.zig"); const SignalContext = messageQueueNs.SignalContext; const MessageAllocator = @import("message_allocator.zig").MessageAllocator; const ActorDispatcher = @import("actor_dispatcher.zig").ActorDispatcher; const actorModelNs = @import("actor_model.zig"); const ActorThreadContext = actorModelNs.ActorThreadContext; const std = @import("std"); const bufPrint = std.fmt.bufPrint; const assert = std.debug.assert; const warn = std.debug.warn; const mem = std.mem; const math = std.math; const builtin = @import("builtin"); const AtomicOrder = builtin.AtomicOrder; const AtomicRmwOp = builtin.AtomicRmwOp; const Ball = packed struct { const Self = @This(); hits: u64, fn init(pSelf: *Self) void { //warn("{*}.init()\n", pSelf); pSelf.hits = 0; } pub fn format( pSelf: *const Self, comptime fmt: []const u8, context: var, comptime FmtError: type, output: fn (@typeOf(context), []const u8) FmtError!void ) FmtError!void { try std.fmt.format(context, FmtError, output, "hits={}", pSelf.hits); } }; const Player = struct { const Self = @This(); allocator: MessageAllocator(), hits: u64, max_hits: u64, last_ball_hits: u64, fn init(pSelf: *Actor(Player)) void { pSelf.body.hits = 0; pSelf.body.max_hits = 0; pSelf.body.last_ball_hits = 0; // Should not fail, error out in safy builds pSelf.body.allocator.init(10, 0) catch unreachable; } fn initDone(pSelf: *Actor(Player), pDone: *Done) void { pSelf.body.pDone = pDone; } fn hitBall(pSelf: *Actor(Player), cmd: u64, pMsg: *Message(Ball)) !void { var pResponse = pSelf.body.allocator.get(Message(Ball)) orelse return; // error.NoMessages; pResponse.init(cmd); pResponse.header.initSwap(&pMsg.header); pResponse.body.hits = pMsg.body.hits + 1; try pResponse.send(); //warn("{*}.hitBall pResponse={}\n\n", pSelf, pResponse); } pub fn processMessage(pActorInterface: *ActorInterface, pMsgHeader: *MessageHeader) void { var pSelf: *Actor(Player) = Actor(Player).getActorPtr(pActorInterface); var pMsg = Message(Ball).getMessagePtr(pMsgHeader); //warn("{*}.processMessage pMsg={}\n", pSelf, pMsg); switch(pMsg.header.cmd) { 0 => { warn("{*}.processMessage START pMsgHeader={*} cmd={}\n", pSelf, pMsgHeader, pMsgHeader.cmd); // First Ball Player.hitBall(pSelf, 1, pMsg) catch |err| warn("error hitBall={}\n", err); }, 1 => { //warn("{*}.processMessage ONE pMsgHeader={*} cmd={}\n", pSelf, pMsgHeader, pMsgHeader.cmd); pSelf.body.hits += 1; pSelf.body.last_ball_hits = pMsg.body.hits; if (pSelf.body.hits <= pSelf.body.max_hits) { // Regular Balls Player.hitBall(pSelf, 1, pMsg) catch |err| warn("error hitBall={}\n", err); } else { // Last ball warn("{*}.processMessage LASTBALL pMsgHeader={*} cmd={} hits={}\n", pSelf, pMsgHeader, pMsgHeader.cmd, pSelf.body.hits); if (pSelf.interface.doneFn) |doneFn| { warn("{*}.processMessage DONE pMsgHeader={*} cmd={} hits={} call doneFn\n", pSelf, pMsgHeader, pMsgHeader.cmd, pSelf.body.hits); doneFn(pSelf.interface.doneFn_handle); } // Tell partner game over warn("{*}.processMessage TELLPRTR pMsgHeader={*} cmd={} hits={}\n", pSelf, pMsgHeader, pMsgHeader.cmd, pSelf.body.hits); Player.hitBall(pSelf, 2, pMsg) catch |err| warn("error hitBall={}\n", err); } }, 2 => { if (pSelf.interface.doneFn) |doneFn| { warn("{*}.processMessage GAMEOVER pMsgHeader={*} cmd={} hits={} call doneFn\n", pSelf, pMsgHeader, pMsgHeader.cmd, pSelf.body.hits); doneFn(pSelf.interface.doneFn_handle); warn("{*}.processMessage GAMEOVER pMsgHeader={*} cmd={} hits={} aftr doneFn\n", pSelf, pMsgHeader, pMsgHeader.cmd, pSelf.body.hits); } }, else => { // Ignore unknown commands warn("{*}.processMessage IGNORE pMsgHeader={*} cmd={} hits={}\n", pSelf, pMsgHeader, pMsgHeader.cmd, pSelf.body.hits); }, } // TODO: Should process message be responsible for returning message? if (pMsg.header.pAllocator) |pAllocator| pAllocator.put(pMsgHeader); } }; test "actors-single-threaded" { // Create Dispatcher const Dispatcher = ActorDispatcher(2); var dispatcher: Dispatcher = undefined; dispatcher.init(); // Create a PlayerActor type const PlayerActor = Actor(Player); const max_hits = 10; // Create player0 var player0 = PlayerActor.init(); player0.body.max_hits = max_hits; assert(player0.body.hits == 0); try dispatcher.add(&player0.interface); // Create player1 var player1 = PlayerActor.init(); player1.body.max_hits = max_hits; assert(player1.body.hits == 0); try dispatcher.add(&player1.interface); // Create a message to get things going var ballMsg: Message(Ball) = undefined; ballMsg.init(0); // Initializes Message.header.cmd to 0 and calls Ball.init() // via Ball.init(&Message.body). Does NOT init any other header fields! // Initialize header fields ballMsg.header.pAllocator = null; ballMsg.header.pDstActor = &player0.interface; ballMsg.header.pSrcActor = &player1.interface; // Send the message try ballMsg.send(); // Dispatch messages until there are no messages to process _ = dispatcher.loop(); // Validate players hit the ball the expected number of times. assert(player0.body.hits > 0); assert(player1.body.hits > 0); assert(player1.body.last_ball_hits > 0); assert(player0.body.hits + player1.body.hits == player1.body.last_ball_hits); } test "actors-multi-threaded" { warn("\ncall thread_context init's\n"); var thread0_context: ActorThreadContext = undefined; thread0_context.init(0, "thread0"); var thread1_context: ActorThreadContext = undefined; thread1_context.init(1, "thread1"); var thread0 = try std.os.spawnThread(&thread0_context, ActorThreadContext.threadDispatcherFn); var thread1 = try std.os.spawnThread(&thread1_context, ActorThreadContext.threadDispatcherFn); warn("threads Spawned\n"); // Create a PlayerActor type const PlayerActor = Actor(Player); const max_hits = 10; // Create player0 var player0 = PlayerActor.initFull(ActorThreadContext.threadDoneFn, @ptrToInt(&thread0_context)); player0.body.max_hits = max_hits; assert(player0.body.hits == 0); warn("add player0\n"); try thread0_context.dispatcher.add(&player0.interface); // Create player1 var player1 = PlayerActor.initFull(ActorThreadContext.threadDoneFn, @ptrToInt(&thread1_context)); player1.body.max_hits = max_hits; assert(player1.body.hits == 0); warn("add player1\n"); try thread1_context.dispatcher.add(&player1.interface); // Create a message to get things going warn("create start message\n"); var ballMsg: Message(Ball) = undefined; ballMsg.init(0); // Initializes Message.header.cmd to 0 and calls Ball.init() // via Ball.init(&Message.body). Does NOT init any other header fields! // Initialize header fields ballMsg.header.pAllocator = null; ballMsg.header.pDstActor = &player0.interface; ballMsg.header.pSrcActor = &player1.interface; warn("ballMsg={}\n", &ballMsg); // Send the message try ballMsg.send(); // Order of waiting does not mater warn("call wait thread1\n"); thread1.wait(); warn("aftr wait thread1\n"); warn("call wait thread0\n"); thread0.wait(); warn("aftr wait thread0\n"); // Validate players hit the ball the expected number of times. assert(player0.body.hits > 0); assert(player1.body.hits > 0); assert(player1.body.last_ball_hits > 0); assert(player0.body.hits + player1.body.hits == player1.body.last_ball_hits); }
test.zig
const std = @import("std"); const io = std.io; const mem = std.mem; pub const PROTOCOL_VERSION = 196608; pub const SSL_REQUEST_CODE = 80877103; pub const SSL_ALLOWED = 'S'; pub const SSL_NOT_ALLOWED = 'N'; pub const Type = struct { pub const AUTHENTICATION: u8 = 'R'; pub const ERROR: u8 = 'E'; pub const EMPTY_QUERY: u8 = 'I'; pub const DESCRIBE: u8 = 'D'; pub const RAW_DESCRIPTION: u8 = 'T'; pub const DATA_RAW: u8 = 'D'; pub const QUERY: u8 = 'Q'; pub const COMMAND_COMPLETE: u8 = 'C'; pub const TERMINATE: u8 = 'X'; pub const NOTICE: u8 = 'N'; pub const PASSWORD: u8 = 'p'; pub const ReadyForQueryMessage: u8 = 'Z'; }; const Auth = struct { pub const OK = 0; pub const KERBEROS_v5 = 2; pub const CLEAR_TEXT = 3; pub const MD5 = 5; pub const SCM = 6; pub const GSS = 7; pub const GSS_CONTINUE = 8; pub const SSPI = 9; pub fn createPasswordMessage(buf: *std.Buffer, password: []const u8) !void { var w = &Writer.init(buf); try w.writeByte(Type.PASSWORD); try w.writeInt32(0); try w.writeString(password); try w.resetLength(.Base); } }; pub const Offset = enum { Startup, Base, }; pub const Severity = struct { pub const FATAL = "FATAL"; pub const PANIC = "PANIC"; pub const WARNING = "WARNING"; pub const NOTICE = "NOTICE"; pub const DEBUG = "DEBUG"; pub const INFO = "INFO"; pub const LOG = "LOG"; }; pub const Field = struct { pub const SEVERITY: u8 = 'S'; pub const CODE: u8 = 'C'; pub const MESSAGE: u8 = 'M'; pub const MESSAGE_DETAIL: u8 = 'D'; pub const MESSAGE_HINT: u8 = 'H'; pub const POSITION: u8 = 'P'; pub const INTERNAL_POSITION: u8 = 'p'; pub const INTERNAL_QUERY: u8 = 'q'; pub const WHERE: u8 = 'W'; pub const SCHEME_NAME: u8 = 's'; pub const TABLE_NAME: u8 = 't'; pub const COLUMN_NAME: u8 = 'c'; pub const DATA_TYPE_NAME: u8 = 'd'; pub const CONSTRAINT_NAME: u8 = 'n'; pub const FILE: u8 = 'F'; pub const LINE: u8 = 'L'; pub const ROUTINE: u8 = 'R'; }; const Code = struct { // Class 00 — Successful Completion pub const SuccessfulCompletion = "00000"; // successful_completion // Class 01 — Warning pub const Warning = "01000"; // warning pub const WarningDynamicResultSetsReturned = "0100C"; // dynamic_result_sets_returned pub const WarningImplicitZeroBitPadding = "01008"; // implicit_zero_bit_padding pub const WarningNullValueEliminatedInSetFunction = "01003"; // null_value_eliminated_in_set_function pub const WarningPrivilegeNotGranted = "01007"; // privilege_not_granted pub const WarningPrivilegeNotRevoked = "01006"; // privilege_not_revoked pub const WarningStringDataRightTruncation = "01004"; // string_data_right_truncation pub const WarningDeprecatedFeature = "01P01"; // deprecated_feature // Class 02 — No Data (this is also a warning class per the SQL standard) pub const NoData = "02000"; // no_data; pub const NoAdditionalDynamicResultSetsReturned = "02001"; // no_additional_dynamic_result_sets_returned // Class 03 — SQL Statement Not Yet Complete pub const SQLStatementNotYetComplete = "03000"; // sql_statement_not_yet_complete // Class 08 — Connection Exception pub const ConnectionException = "08000"; // connection_exception pub const ConnectionDoesNotExist = "08003"; // connection_does_not_exist pub const ConnectionFailure = "08006"; // connection_failure pub const SQLClientUnableToEstablishSQLConnection = "08001"; // sqlclient_unable_to_establish_sqlconnection pub const SQLServerRejectedEstablishementOfSQLConnection = "08004"; // sqlserver_rejected_establishment_of_sqlconnection pub const TransactionResolutionUnknown = "08007"; // transaction_resolution_unknown pub const ProtocolViolation = "08P01"; // protocol_violation // Class 09 — Triggered Action Exception pub const TriggeredActionException = "09000"; // triggered_action_exception // Class 0A — Feature Not Supported pub const FeatureNotSupported = "0A000"; // feature_not_supported // Class 0B — Invalid Transaction Initiation pub const InvalidTransactionInitiation = "0B000"; // invalid_transaction_initiation // Class 0F — Locator Exception pub const LocatorException = "0F000"; // locator_exception pub const InvalidLocatorSpecification = "0F001"; // invalid_locator_specification // Class 0L — Invalid Grantor pub const InvalidGrantor = "0L000"; // invalid_grantor pub const InvalidGrantOperation = "0LP01"; // invalid_grant_operation // Class 0P — Invalid Role Specification pub const InvalidRoleSpecification = "0P000"; // invalid_role_specification // Class 0Z — Diagnostics Exception pub const DiagnosticsException = "0Z000"; // diagnostics_exception pub const StackedDiagnosticsAccessedWithoutActiveHandler = "0Z002"; // stacked_diagnostics_accessed_without_active_handler // Class 20 — Case Not Found pub const CaseNotFound = "20000"; // case_not_found // Class 21 — Cardinality Violation pub const CardinalityViolation = "21000"; // cardinality_violation // Class 22 — Data Exception pub const DataException = "22000"; // data_exception pub const ArraySubscriptError = "2202E"; // array_subscript_error pub const CharacterNotInRepertoire = "22021"; // character_not_in_repertoire pub const DatatimeFieldOverflow = "22008"; // datetime_field_overflow pub const DivisionByZero = "22012"; // division_by_zero pub const ErrorInAssignment = "22005"; // error_in_assignment pub const EscapeCharacterConflict = "2200B"; // escape_character_conflict pub const IndicatorOverflow = "22022"; // indicator_overflow pub const IntervalFieldOverflow = "22015"; // interval_field_overflow pub const InvalidArgumentForLogarithm = "2201E"; // invalid_argument_for_logarithm pub const InvalidArgumentForNTileFunction = "22014"; // invalid_argument_for_ntile_function pub const InvalidArgumentForNthValueFunction = "22016"; // invalid_argument_for_nth_value_function pub const InvalidArgumentForPowerFunction = "2201F"; // invalid_argument_for_power_function pub const InvalidArgumentForWidthBucketFunction = "2201G"; // invalid_argument_for_width_bucket_function pub const InvalidCharacterValueForCast = "22018"; // invalid_character_value_for_cast pub const InvalidDatatimeFormat = "22007"; // invalid_datetime_format pub const InvalidEscapeCharacter = "22019"; // invalid_escape_character pub const InvalidEscapeOctet = "2200D"; // invalid_escape_octet pub const InvalidEscapeSequence = "22025"; // invalid_escape_sequence pub const NonStandardUseOfEscapeCharacter = "22P06"; // nonstandard_use_of_escape_character pub const InvalidIndicatorParameterValue = "22010"; // invalid_indicator_parameter_value pub const InvalidParameterValue = "22023"; // invalid_parameter_value pub const InvalidRegularExpression = "2201B"; // invalid_regular_expression pub const InvalidRowCountInLimitClause = "2201W"; // invalid_row_count_in_limit_clause pub const InvalidRowCountInResultOffsetClause = "2201X"; // invalid_row_count_in_result_offset_clause pub const InvalidTablesampleArgument = "2202H"; // invalid_tablesample_argument pub const InvalidTablesampleRepeat = "2202G"; // invalid_tablesample_repeat pub const InvalidTimeZoneDisplacementValue = "22009"; // invalid_time_zone_displacement_value pub const InvalidInvalidUseOfEscapeCharacter = "2200C"; // invalid_use_of_escape_character pub const MostSpecificTypeMismatch = "2200G"; // most_specific_type_mismatch pub const NullValueNotAllowed = "22004"; // null_value_not_allowed pub const NullValueNoIndicatorParameter = "22002"; // null_value_no_indicator_parameter pub const NumericValueOutOfRange = "22003"; // numeric_value_out_of_range pub const StringDataLengthMismatch = "22026"; // string_data_length_mismatch pub const StringDataRightTruncation = "22001"; // string_data_right_truncation pub const SubstringError = "22011"; // substring_error pub const TrimError = "22027"; // trim_error pub const UntermincatedCString = "22024"; // unterminated_c_string pub const ZeroLengthCharacterString = "2200F"; // zero_length_character_string pub const FloatingPointException = "22P01"; // floating_point_exception pub const InvalidTextRepresentation = "22P02"; // invalid_text_representation pub const InvalidBinaryRepresentation = "22P03"; // invalid_binary_representation pub const BadCopyFileFormat = "22P04"; // bad_copy_file_format pub const UnstranslatableCharacter = "22P05"; // untranslatable_character pub const NotAnXMLDocument = "2200L"; // not_an_xml_document pub const InvalideXMLDocument = "2200M"; // invalid_xml_document pub const InvalidXMLContent = "2200N"; // invalid_xml_content pub const InvalidXMLComment = "2200S"; // invalid_xml_comment pub const InvalidXMLProcessingInstruction = "2200T"; // invalid_xml_processing_instruction // // Class 23 — Integrity Constraint Violation pub const IntegrityConstraintViolation = "23000"; // integrity_constraint_violation pub const RestrictViolation = "23001"; // restrict_violation pub const NotNullViolation = "23502"; // not_null_violation pub const ForeignKeyViolation = "23503"; // foreign_key_violation pub const UniqueViolation = "23505"; // unique_violation pub const CheckViolation = "23514"; // check_violation pub const ExclusionViolation = "23P01"; // exclusion_violation // // Class 24 — Invalid Cursor State pub const InvalidCursorState = "24000"; // invalid_cursor_state // // Class 25 — Invalid Transaction State pub const InvalidTransactionState = "25000"; // invalid_transaction_state pub const ActiveSQLTransaction = "25001"; // active_sql_transaction pub const BranchTransactionAlreadyActive = "25002"; // branch_transaction_already_active pub const HeldCursorRequiresSameIsolationLevel = "25008"; // held_cursor_requires_same_isolation_level pub const InappropriateAccessModeForBranchTransaction = "25003"; // inappropriate_access_mode_for_branch_transaction pub const InappropriateIsolationLevelForBranchTransaction = "25004"; // inappropriate_isolation_level_for_branch_transaction pub const NoActiveSQLTransactionForBranchTransaction = "25005"; // no_active_sql_transaction_for_branch_transaction pub const ReadOnlySQLTransaction = "25006"; // read_only_sql_transaction pub const SchemaAndDataStatementMixingNotSupported = "25007"; // schema_and_data_statement_mixing_not_supported pub const NoActiveSQLTransaction = "25P01"; // no_active_sql_transaction pub const InFailedSQLTransaction = "25P02"; // in_failed_sql_transaction pub const IdleInTransactionSessionTimeout = "25P03"; // idle_in_transaction_session_timeout // Class 26 — Invalid SQL Statement Name pub const InvalidSQLStatementName = "26000"; // invalid_sql_statement_name // Class 27 — Triggered Data Change Violation pub const TriggeredDataChangeViolation = "27000"; // triggered_data_change_violation // Class 28 — Invalid Authorization Specification pub const InvalidAuthorizationSpecification = "28000"; // invalid_authorization_specification pub const InvalidPassword = "<PASSWORD>"; // invalid_password // Class 2B — Dependent Privilege Descriptors Still Exist pub const DependentPrivilegeDescriptorsStillExist = "2B000"; // dependent_privilege_descriptors_still_exist pub const DependentObjectsStillExist = "2BP01"; // dependent_objects_still_exist // Class 2D — Invalid Transaction Termination pub const InvalidTransactionTermination = "2D000"; // invalid_transaction_termination // Class 2F — SQL Routine Exception pub const RoutineSQLRuntimeException = "2F000"; // sql_routine_exception pub const RoutineFunctionExecutedNoReturnStatement = "2F005"; // function_executed_no_return_statement pub const RoutineModifyingSQLDataNotPermitted = "2F002"; // modifying_sql_data_not_permitted pub const RoutineProhibitedSQLStatementAttempted = "2F003"; // prohibited_sql_statement_attempted pub const RoutineReadingSQLDataNotPermitted = "2F004"; // reading_sql_data_not_permitted // Class 34 — Invalid Cursor Name pub const InvalidCursorName = "34000"; // invalid_cursor_name // Class 38 — External Routine Exception pub const ExternalRoutineException = "38000"; // external_routine_exception pub const ExternalRoutineContainingSQLNotPermitted = "38001"; // containing_sql_not_permitted pub const ExternalRoutineModifyingSQLDataNotPermitted = "38002"; // modifying_sql_data_not_permitted pub const ExternalRoutineProhibitedSQLStatementAttempted = "38003"; // prohibited_sql_statement_attempted pub const ExternalRoutineReadingSQLDataNotPermitted = "38004"; // reading_sql_data_not_permitted // Class 39 — External Routine Invocation Exception pub const ExternalRoutineInvocationException = "39000"; // external_routine_invocation_exception pub const ExternalRoutineInvalidSQLStateReturned = "39001"; // invalid_sqlstate_returned pub const ExternalRoutineNullValueNotAllowed = "39004"; // null_value_not_allowed pub const ExternalRoutineTriggerProtocolViolated = "39P01"; // trigger_protocol_violated pub const ExternalRoutineSRFProtocolViolated = "39P02"; // srf_protocol_violated pub const ExternalRoutineEventTriggerProtocol = "39P03"; // event_trigger_protocol_violated // Class 3B — Savepoint Exception pub const SavepointException = "3B000"; // savepoint_exception pub const InvalidSavepointSpecification = "3B001"; // invalid_savepoint_specification // Class 3D — Invalid Catalog Name pub const InvalidCatalogName = "3D000"; // invalid_catalog_name // Class 3F — Invalid Schema Name pub const InvalidSchemaName = "3F000"; // invalid_schema_name // Class 40 — Transaction Rollback pub const TransactionRollback = "40000"; // transaction_rollback pub const TransactionIntegrityConstraintViolation = "40002"; // transaction_integrity_constraint_violation pub const SerializationFailure = "40001"; // serialization_failure pub const StatementCompletionUnknown = "40003"; // statement_completion_unknown pub const DeadlockDetected = "40P01"; // deadlock_detected // Class 42 — Syntax Error or Access Rule Violation pub const SyntaxErrorOrAccessRuleViolation = "42000"; // syntax_error_or_access_rule_violation pub const SyntaxError = "42601"; // syntax_error pub const InsufficientPrivilege = "42501"; // insufficient_privilege pub const CannotCoerce = "42846"; // cannot_coerce pub const GroupingError = "42803"; // grouping_error pub const WindowingError = "42P20"; // windowing_error pub const InvalidRecursion = "42P19"; // invalid_recursion pub const InvalidForeignKey = "42830"; // invalid_foreign_key pub const InvalidName = "42602"; // invalid_name pub const NameTooLong = "42622"; // name_too_long pub const ReservedName = "42939"; // reserved_name pub const DatatypeMismatch = "42804"; // datatype_mismatch pub const IndeterminateDatatype = "42P18"; // indeterminate_datatype pub const CollationMismatch = "42P21"; // collation_mismatch pub const IndeterminateCollation = "42P22"; // indeterminate_collation pub const WrongObjectType = "42809"; // wrong_object_type pub const UndefinedColumn = "42703"; // undefined_column pub const UndefinedFunction = "42883"; // undefined_function pub const UndefinedTable = "42P01"; // undefined_table pub const UndefinedParameter = "42P02"; // undefined_parameter pub const UndefinedObject = "42704"; // undefined_object pub const DuplicateColumn = "42701"; // duplicate_column pub const DuplicateCursor = "42P03"; // duplicate_cursor pub const DuplicateDatabase = "42P04"; // duplicate_database pub const DuplicateFunction = "42723"; // duplicate_function pub const DuplicatePreparedStatement = "42P05"; // duplicate_prepared_statement pub const DuplicateSchema = "42P06"; // duplicate_schema pub const DuplicateTable = "42P07"; // duplicate_table pub const DuplicateAlias = "42712"; // duplicate_alias pub const DuplicateObject = "42710"; // duplicate_object pub const AmbiguousColumn = "42702"; // ambiguous_column pub const AmbiguousFunction = "42725"; // ambiguous_function pub const AmbiguousParameter = "42P08"; // ambiguous_parameter pub const AmbiguousAlias = "42P09"; // ambiguous_alias pub const InvalidColumnReference = "42P10"; // invalid_column_reference pub const InvalidColumnDefinition = "42611"; // invalid_column_definition pub const InvalidCursorDefinition = "42P11"; // invalid_cursor_definition pub const InvalidDatabaseDefinition = "42P12"; // invalid_database_definition pub const InvalidFunctionDefinition = "42P13"; // invalid_function_definition pub const InvalidStatementDefinition = "42P14"; // invalid_prepared_statement_definition pub const InvalidSchemaDefinition = "42P15"; // invalid_schema_definition pub const InvalidTableDefinition = "42P16"; // invalid_table_definition pub const InvalidObjectDefinition = "42P17"; // invalid_object_definition // Class 44 — WITH CHECK OPTION Violation pub const WithCheckOptionViolation = "44000"; // with_check_option_violation // Class 53 — Insufficient Resources pub const InsufficientResources = "53000"; // insufficient_resources pub const DiskFull = "53100"; // disk_full pub const OutOfMemory = "53200"; // out_of_memory pub const TooManyConnections = "53300"; // too_many_connections pub const ConfigurationLimitExceeded = "53400"; // configuration_limit_exceeded // Class 54 — Program Limit Exceeded pub const ProgramLimitExceeded = "54000"; // program_limit_exceeded pub const StatementTooComplex = "54001"; // statement_too_complex pub const TooManyColumns = "54011"; // too_many_columns pub const TooManyArguments = "54023"; // too_many_arguments // Class 55 — Object Not In Prerequisite State pub const ObjectNotInPrerequisiteState = "55000"; // object_not_in_prerequisite_state pub const ObjectInUse = "55006"; // object_in_use pub const CantChangeRuntimeParam = "55P02"; // cant_change_runtime_param pub const LockNotAvailable = "55P03"; // lock_not_available // Class 57 — Operator Intervention pub const OperatorIntervention = "57000"; // operator_intervention pub const QueryCanceled = "57014"; // query_canceled pub const AdminShutdown = "57P01"; // admin_shutdown pub const CrashShutdown = "57P02"; // crash_shutdown pub const CannotConnectNow = "57P03"; // cannot_connect_now pub const DatabaseDropped = "57P04"; // database_dropped // Class 58 — System Error (errors external to PostgreSQL itself) pub const SystemError = "58000"; // system_error pub const IOError = "58030"; // io_error pub const UndefinedFile = "58P01"; // undefined_file pub const DuplicateFile = "58P02"; // duplicate_file // Class 72 — Snapshot Failure pub const SnapshotTooOld = "72000"; // snapshot_too_old // Class F0 — Configuration File Error pub const ConfigFileError = "F0000"; // config_file_error pub const LockFileExists = "F0001"; // lock_file_exists // Class HV — Foreign Data Wrapper Error (SQL/MED) pub const FDWError = "HV000"; // fdw_error pub const FDWColumnNameNotFound = "HV005"; // fdw_column_name_not_found pub const FDWDynamicParameterValueNeeded = "HV002"; // fdw_dynamic_parameter_value_needed pub const FDWFunctionSequenceError = "HV010"; // fdw_function_sequence_error pub const FDWInconsistentDescriptorInformation = "HV021"; // fdw_inconsistent_descriptor_information pub const FDWInvalidAttributeValue = "HV024"; // fdw_invalid_attribute_value pub const FDWInvalidColumnName = "HV007"; // fdw_invalid_column_name pub const FDWInvalidColumnNumber = "HV008"; // fdw_invalid_column_number pub const FDWInvalidDataType = "HV004"; // fdw_invalid_data_type pub const FDWInvalidDataTypeDescriptors = "HV006"; // fdw_invalid_data_type_descriptors pub const FDWInvalidDescriptorFieldIdentifier = "HV091"; // fdw_invalid_descriptor_field_identifier pub const FDWInvalidHandle = "HV00B"; // fdw_invalid_handle pub const FDWInvalidOptionIndex = "HV00C"; // fdw_invalid_option_index pub const FDWInvalidOptionName = "HV00D"; // fdw_invalid_option_name pub const FDWInvalidStringLengthOrBufferLength = "HV090"; // fdw_invalid_string_length_or_buffer_length pub const FDWInvalidStringFormat = "HV00A"; // fdw_invalid_string_format pub const FDWInvalidUseOfNullPointer = "HV009"; // fdw_invalid_use_of_null_pointer pub const FDWTooManyHandles = "HV014"; // fdw_too_many_handles pub const FDWOutOfMemory = "HV001"; // fdw_out_of_memory pub const FDWNoSchemas = "HV00P"; // fdw_no_schemas pub const FDWOptionNameNotFound = "HV00J"; // fdw_option_name_not_found pub const FDWReplyHandle = "HV00K"; // fdw_reply_handle pub const FDWSchemaNotFound = "HV00Q"; // fdw_schema_not_found pub const FDWTableNotFound = "HV00R"; // fdw_table_not_found pub const FDWUnableToCreateExecution = "HV00L"; // fdw_unable_to_create_execution pub const FDWUnableToCreateReply = "HV00M"; // fdw_unable_to_create_reply pub const FDWUnableToEstablishConnection = "HV00N"; // fdw_unable_to_establish_connection // Class P0 — PL/pgSQL Error pub const PLPGSQLError = "P0000"; // plpgsql_error pub const RaiseException = "P0001"; // raise_exception pub const NoDataFound = "P0002"; // no_data_found pub const TooManyRows = "P0003"; // too_many_rows pub const AssertFailure = "P0004"; // assert_failure // Class XX — Internal Error pub const InternalError = "XX000"; // internal_error pub const DataCorrupted = "XX001"; // data_corrupted pub const IndexCorrupted = "XX002"; // index_corrupted }; // Writer wraps a Buffer and allows writing postgres wired values pub const Writer = struct { buf: *std.Buffer, writer: io.BufferOutStream, pub fn init(buf: *std.Buffer) Writer { return Writer{ .buf = buf, .writer = io.BufferOutStream.init(buf), }; } pub fn writeByte(self: *Writer, b: u8) !void { try self.buf.appendByte(b); } pub fn write(self: *Writer, b: []const u8) !void { try self.buf.append(b); } pub fn writeString(self: *Writer, b: []const u8) !void { try self.buf.append(b); try self.buf.appendByte(0x00); } pub fn writeInt32(self: *Writer, b: i32) !void { var stream = &self.writer.stream; try stream.writeIntBig(u32, @intCast(u32, b)); } pub fn writeInt16(self: *Writer, b: i16) !void { var stream = &self.writer.stream; try stream.writeIntBig(u16, @intCast(u16, b)); } pub fn resetLength(self: *Writer, offset: Offset) void { var b = self.buf.toSlice(); var s = b[@enumToInt(offset)..]; var bytes: [(u32.bit_count + 7) / 8]u8 = undefined; mem.writeIntBig(u32, &bytes, @intCast(u32, s.len)); mem.copy(u8, s, bytes[0..]); } }; pub const Error = struct { severity: []const u8, code: []const u8, message: []const u8, detail: ?[]const u8, hint: ?[]const u8, position: ?[]const u8, internal_position: ?[]const u8, internal_query: ?[]const u8, where: ?[]const u8, schema_name: ?[]const u8, table_name: ?[]const u8, column_name: ?[]const u8, data_type_name: ?[]const u8, constraint: ?[]const u8, file: ?[]const u8, line: ?[]const u8, routine: ?[]const u8, pub fn getMessage(buf: *std.Buffer) !void { var w = &MessageWriter.init(buf); try w.writeByte(Type.ERROR_MESSAGE); try w.writeInt32(0); try w.writeByte(Field.SEVERITY); try w.writeString(self.severity); try w.writeByte(Field.CODE); try w.writeString(self.code); try w.writeByte(Field.MESSAGE); try w.writeString(self.message); if (self.detail) |detail| { try w.writeByte(Field.MESSAGE_DETAIL); try w.writeString(self.detail); } if (self.hint) |hint| { try w.writeByte(Field.MESSAGE_HINT); try w.writeString(self.hint); } try w.writeByte(0x00); try w.resetLength(.Base); } pub fn format( self: Error, comptime fmt: []const u8, comptime options: std.fmt.FormatOptions, ctx: var, comptime Errors: type, output: fn (@typeOf(ctx), []const u8) Errors!void, ) Errors!void { try std.fmt.format( context, Errors, output, "pq: {}: {}", self.severity, self.message, ); } pub fn parse(e: []const u8) !Error { var s = e[5..]; var idx: usize = 0; var o: Error = undefined; while (idx < s.len) { const field = s[idx]; const end = idx + 1; inner: while (end < s.len) : (end += 1) { if (s[end] == 0x00) { break inner; } } const value = s[idx..end]; idx = end + 1; switch (field) { Field.SEVERITY => { o.severity = value; }, Field.CODE => { o.code = value; }, Field.MESSAGE => { o.message = value; }, Field.MESSAGE_DETAIL => { o.detail = value; }, Field.MESSAGE_HINT => { o.hint = value; }, Field.POSITION => { o.position = value; }, Field.INTERNAL_POSITION => { o.internal_position = value; }, Field.INTERNAL_QUERY => { o.internal_query = value; }, Field.WHERE => { o.where = value; }, Field.SCHEME_NAME => { o.schema_name = value; }, Field.TABLE_NAME => { o.table_name = value; }, Field.COLUMN_NAME => { o.column_name = value; }, Field.DATA_TYPE_NAME => { o.data_type_name = value; }, Field.CONSTRAINT_NAME => { o.constraint = value; }, Field.FILE => { o.file = value; }, Field.LINE => { o.line = value; }, Field.ROUTINE => { o.routine = value; }, else => unreachable, } } return o; } }; pub const Message = struct { pub fn type(msg: []const u8) u8 { return msg[0]; } pub fn length(msg: []const u8) ui32 { return readInt(u32, msg[1..5]); } pub fn readInt(T: type, out: []const u8) T { var bytes: [(T.bit_count + 7) / 8]u8 = undefined; mem.copy(u8, bytes[0..], out); return mem.readIntBig(T, &bytes); } pub const terminate_message = blk: { var o: [5]u8 = undefined; var bytes: [(u32.bit_count + 7) / 8]u8 = undefined; mem.writeIntBig(u32, &bytes, value); o[0] = 'X'; mem.copy(u8, o[1..], bytes[0..]); break :blk o[0..]; }; };
src/db/pq/protocol.zig
const std = @import("std"); // const assert = std.debug.assert; const warn = std.debug.warn; const main_sokol = @import("main_sokol.zig"); const system = @import("../core/system.zig"); usingnamespace @import("../main/util.zig"); const MainState = struct { sm: *system.SystemManager, allocator: *std.mem.Allocator, }; // SYSTEMS const transform_system = @import("../systems/transform_system.zig"); fn init_safe(user_data: *c_void) void { init(user_data) catch |err| { std.debug.assert(false); }; } fn init(user_data: *c_void) !void { var mainstate = @ptrCast([*]MainState, @alignCast(@alignOf([*]MainState), user_data)); var sm = mainstate.*.sm; var systems = std.ArrayList(system.System).init(sm.allocator); var ts = transform_system.init("transform", sm.allocator); warn("1 {}\n", ts.funcs[0].pass); try systems.append(ts); warn("2 {}\n", ts.funcs[0].pass); sm.registerAllSystems(systems.toSlice()); var params = VariantMap.init(sm.allocator); params.putNoClobber("allocator", Variant.set_ptr(sm.allocator, stringTag("allocator"))) catch unreachable; params.putNoClobber("max_entity_count", Variant.set_int(128)) catch unreachable; sm.runSystemFunc("init", params); } fn deinit(user_data: *c_void) void {} fn update(dt: f64, total_time: f64, user_data: *c_void) bool { var mainstate = @ptrCast([*]MainState, @alignCast(@alignOf([*]MainState), user_data)); var sm = mainstate.*.sm; sm.runSystemFunc("update"); return false; } pub fn main() void { var arena = std.heap.ArenaAllocator.init(std.heap.direct_allocator); defer arena.deinit(); var sm = system.SystemManager.init(&arena.allocator); defer sm.deinit(); var mainstate = MainState{ .sm = &sm, // .allocator = std.heap.c_allocator, .allocator = &arena.allocator, }; var state = main_sokol.AppState{ .init_func = init_safe, .cleanup_func = deinit, .update_func = update, .user_data = &mainstate, }; // TODO: Change to main_sokol.run(...) var desc = zero_struct(main_sokol.sokol.sapp_desc); desc.width = 800; desc.height = 480; desc.window_title = c"Zag"; desc.user_data = &state; desc.init_userdata_cb = main_sokol.init; desc.frame_userdata_cb = main_sokol.update; desc.cleanup_userdata_cb = main_sokol.deinit; desc.event_cb = main_sokol.event; var exit_code = main_sokol.sokol.sapp_run(&desc); warn("Done!\n"); }
code/main/main.zig
const std = @import("std"); const os = @import("root").os; const CoreID = os.platform.CoreID; /// Maximum number of supported CPUs const max_cpus = comptime os.config.kernel.max_cpus; /// CPUs data var core_datas: [max_cpus]CoreData = [1]CoreData{undefined} ** max_cpus; /// Count of CPUs that have not finished booting. /// Assigned in stivale2.zig pub var cpus_left: usize = undefined; /// Pointer to CPUS data pub var cpus: []CoreData = core_datas[0..1]; pub const CoreData = struct { current_task: *os.thread.Task = undefined, booted: bool, panicked: bool, acpi_id: u64, executable_tasks: os.thread.ReadyQueue, tasks_count: usize, platform_data: os.platform.thread.CoreData, int_stack: usize, sched_stack: usize, pub fn id(self: *@This()) usize { return os.lib.get_index(self, cpus); } fn bootstrap_stack(size: usize) usize { const guard_size = os.platform.thread.stack_guard_size; const total_size = guard_size + size; // Allocate non-backing virtual memory const nonbacked = os.memory.vmm.nonbacked(); const virt = @ptrToInt(os.vital(nonbacked.allocFn(nonbacked, total_size, 1, 1, 0), "bootstrap stack valloc").ptr); // Map pages os.vital(os.memory.paging.map(.{ .virt = virt + guard_size, .size = size, .perm = os.memory.paging.rw(), .memtype = .MemoryWriteBack, }), "bootstrap stack map"); return virt + total_size; } pub fn bootstrap_stacks(self: *@This()) void { self.int_stack = CoreData.bootstrap_stack(os.platform.thread.int_stack_size); self.sched_stack = CoreData.bootstrap_stack(os.platform.thread.sched_stack_size); } }; pub fn prepare() void { os.platform.thread.set_current_cpu(&cpus[0]); cpus[0].panicked = false; cpus[0].tasks_count = 1; cpus[0].platform_data = .{}; } pub fn init(num_cores: usize) void { if(num_cores < 2) return; cpus.len = std.math.min(num_cores, max_cpus); // for(cpus[1..]) |*c| { // AAAAAAAAAAAAAAAAAAAAA https://github.com/ziglang/zig/issues/7968 // Nope, can't do that. Instead we have to do the following: var i: usize = 1; while(i < cpus.len) : (i += 1) { const c = &cpus[i]; // ugh. c.panicked = false; c.tasks_count = 0; c.executable_tasks.init(); c.bootstrap_stacks(); c.platform_data = .{}; } }
src/platform/smp.zig
const std = @import("std"); const Builder = std.build.Builder; const LibExeObjStep = std.build.LibExeObjStep; const vma_config = @import("vma_config.zig"); fn getConfigArgs(comptime config: vma_config.Config) []const []const u8 { comptime { @setEvalBranchQuota(100000); var args: []const []const u8 = &[_][]const u8 { std.fmt.comptimePrint("-DVMA_VULKAN_VERSION={}", .{ config.vulkanVersion }), std.fmt.comptimePrint("-DVMA_DEDICATED_ALLOCATION={}", .{ @boolToInt(config.dedicatedAllocation)}), std.fmt.comptimePrint("-DVMA_BIND_MEMORY2={}", .{ @boolToInt(config.bindMemory2)}), std.fmt.comptimePrint("-DVMA_MEMORY_BUDGET={}", .{ @boolToInt(config.memoryBudget)}), std.fmt.comptimePrint("-DVMA_STATIC_VULKAN_FUNCTIONS={}", .{ @boolToInt(config.staticVulkanFunctions)}), std.fmt.comptimePrint("-DVMA_STATS_STRING_ENABLED={}", .{ @boolToInt(config.statsStringEnabled)}), }; if (config.debugInitializeAllocations) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_DEBUG_INITIALIZE_ALLOCATIONS={}", .{ @boolToInt(value) }, ) }; } if (config.debugMargin) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_DEBUG_MARGIN={}", .{ value }, ) }; } if (config.debugDetectCorruption) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_DEBUG_DETECT_CORRUPTION={}", .{ @boolToInt(value) }, ) }; } if (config.recordingEnabled) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_RECORDING_ENABLED={}", .{ @boolToInt(value) }, ) }; } if (config.debugMinBufferImageGranularity) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_DEBUG_MIN_BUFFER_IMAGE_GRANULARITY={}", .{ value }, ) }; } if (config.debugGlobalMutex) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_DEBUG_GLOBAL_MUTEX={}", .{ @boolToInt(value) }, ) }; } if (config.useStlContainers) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_USE_STL_CONTAINERS={}", .{ @boolToInt(value) }, ) }; } if (config.useStlSharedMutex) |value| { args = args ++ &[_][]const u8 { std.fmt.comptimePrint( "-DVMA_USE_STL_SHARED_MUTEX={}", .{ @boolToInt(value) }, ) }; } return args; } } pub fn linkVma(object: *LibExeObjStep, vk_root_file: []const u8, mode: std.builtin.Mode, target: std.zig.CrossTarget) void { const commonArgs = &[_][]const u8 { "-std=c++14" }; const releaseArgs = &[_][]const u8 { } ++ commonArgs ++ comptime getConfigArgs(vma_config.releaseConfig); const debugArgs = &[_][]const u8 { } ++ commonArgs ++ comptime getConfigArgs(vma_config.debugConfig); const args = if (mode == .Debug) debugArgs else releaseArgs; object.addCSourceFile("VulkanMemoryAllocator/src/VmaUsage.cpp", args); object.addIncludeDir("VulkanMemoryAllocator/src/"); object.addPackage(std.build.Pkg{ .name = "vma", .path = "vma.zig", .dependencies = &[_]std.build.Pkg{ .{ .name = "vk", .path = vk_root_file, } }, }); object.linkLibC(); if (target.getAbi() != .msvc) { // MSVC can't link libc++, it causes duplicate symbol errors. // But it's needed for other targets. object.linkSystemLibrary("c++"); } } pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const lib = b.addTest("test/test.zig"); lib.addPackagePath("vk", "test/vulkan_core.zig"); linkVma(lib, "test/vulkan_core.zig", mode, target); lib.linkSystemLibrary("test/vulkan-1"); lib.setTarget(target); const test_step = b.step("test", "run tests"); test_step.dependOn(&lib.step); }
build.zig
const std = @import("std"); const assert = std.debug.assert; const c_allocator = std.heap.c_allocator; const page_allocator = std.heap.page_allocator; const Allocator = std.mem.Allocator; const ObjectPool = @import("ObjectPool.zig").ObjectPool; pub fn LinkedBuffers(comptime buffer_size: u32, comptime sub_pool_size: u32) type { return struct { const Self = @This(); pub const Buffer = struct { next: ?*Buffer = null, data: *[buffer_size]u8, }; buffer_pool: ObjectPool([buffer_size]u8, sub_pool_size, null), meta_pool: ObjectPool(Buffer, sub_pool_size, null), // allocator_lists is for object pool metadata and for Buffer linked lists pub fn init(allocator_lists: *Allocator, allocator_data: *Allocator) Self { return Self{ .buffer_pool = ObjectPool([buffer_size]u8, sub_pool_size, null).init(allocator_lists, allocator_data), .meta_pool = ObjectPool(Buffer, sub_pool_size, null).init(allocator_lists, allocator_lists), }; } // First Buffer object is created on stack, subsequent Buffer objects in chain are allocated // (Buffer is metadata not the buffer data itself) pub fn newBufferChain(self: *Self) !Buffer { return Buffer{ .data = try self.buffer_pool.alloc() }; } pub fn freeBufferChain(self: *Self, first_buffer: *const Buffer) void { self.buffer_pool.free(first_buffer.data); var buffer: ?*Buffer = first_buffer.next; while (buffer != null) { self.buffer_pool.free(buffer.?.data); const next = buffer.?.next; self.meta_pool.free(buffer.?); buffer = next; } } pub fn addToChain(self: *Self, last_in_chain: *Buffer) !*Buffer { var next = try self.meta_pool.alloc(); errdefer self.meta_pool.free(next); next.* = Buffer{ .data = try self.buffer_pool.alloc() }; last_in_chain.next = next; return next; } pub fn getLastBuffer(self: *Self, first_buffer: *Buffer) *Buffer { var buffer: *Buffer = first_buffer; while (true) { if (buffer.next != null) { buffer = buffer.next.?; } else { break; } } return buffer; } pub fn addData(self: *Self, first_buffer: *?Buffer, data_length: *u32, data: []const u8) !void { if (first_buffer.* == null) { first_buffer.* = try self.newBufferChain(); assert(data_length.* == 0); } var buffer = self.getLastBuffer(&first_buffer.*.?); var data_left = data[0..]; // Fill up to end of first buffer const data_already_in_buffer_len = (data_length.* % buffer_size); var space_left_in_buffer = buffer_size - data_already_in_buffer_len; var l = space_left_in_buffer; if (l > data_left.len) { l = @intCast(u32, data_left.len); } std.mem.copy(u8, buffer.*.data[data_already_in_buffer_len .. data_already_in_buffer_len + l], data_left[0..l]); data_left = data_left[l..]; data_length.* += @intCast(u32, l); if (data_left.len > 0) { buffer = try self.addToChain(buffer); } else { return; } // Fill subsequent buffers while (data_left.len > 0) { l = @intCast(u32, data_left.len); if (l > buffer_size) { l = buffer_size; } std.mem.copy(u8, buffer.*.data[0..l], data_left[0..l]); data_left = data_left[l..]; data_length.* += @intCast(u32, l); if (data_left.len > 0) { buffer = try self.addToChain(buffer); } } } pub fn size(self: Self) usize { return self.buffer_pool.size(); } }; } test "Linked buffer" { var linked_buffer_obj = LinkedBuffers(4096, 1024).init(c_allocator, page_allocator); var chain1 = try linked_buffer_obj.newBufferChain(); var chain2 = try linked_buffer_obj.newBufferChain(); var chain3 = try linked_buffer_obj.newBufferChain(); chain1.data[55] = 3; chain2.data[55] = 3; chain3.data[4096 - 1] = 3; var chain2_2 = try linked_buffer_obj.addToChain(&chain2); chain2_2.data[4096 - 1] = 66; linked_buffer_obj.freeBufferChain(&chain1); linked_buffer_obj.freeBufferChain(&chain2); linked_buffer_obj.freeBufferChain(&chain3); }
src/LinkedBuffers.zig
const std = @import("std"); const Arena = std.heap.ArenaAllocator; const Allocator = std.mem.Allocator; const eql = std.meta.eql; const panic = std.debug.panic; const assert = std.debug.assert; const initCodebase = @import("init_codebase.zig").initCodebase; const MockFileSystem = @import("file_system.zig").FileSystem; const analyzeSemantics = @import("semantic_analyzer.zig").analyzeSemantics; const codegen = @import("codegen.zig").codegen; const ecs = @import("ecs.zig"); const Entity = ecs.Entity; const ECS = ecs.ECS; const components = @import("components.zig"); const query = @import("query.zig"); const literalOf = query.literalOf; const typeOf = query.typeOf; const valueType = query.valueType; const valueOf = query.valueOf; const List = @import("list.zig").List; const strings_module = @import("strings.zig"); const Strings = strings_module.Strings; const InternedString = strings_module.InternedString; const Wasm = List(u8, .{ .initial_capacity = 1000 }); fn printWasmType(wasm: *Wasm, type_of: Entity) error{OutOfMemory}!void { const b = type_of.ecs.get(components.Builtins); const builtins = [_]Entity{ b.I64, b.U64, b.I32, b.U32, b.I16, b.U16, b.I8, b.U8, b.F64, b.F32, b.I64X2, b.I32X4, b.I16X8, b.I8X16, b.U64X2, b.U32X4, b.U16X8, b.U8X16, b.F64X2, b.F32X4 }; const strings = [_][]const u8{ "i64", "i64", "i32", "i32", "i32", "i32", "i32", "i32", "f64", "f32", "v128", "v128", "v128", "v128", "v128", "v128", "v128", "v128", "v128", "v128" }; for (builtins) |builtin, i| { if (eql(type_of, builtin)) { return try wasm.appendSlice(strings[i]); } } if (type_of.has(components.ParentType)) |parent_type| { if (eql(parent_type.entity, b.Ptr)) { return try wasm.appendSlice("i32"); } } if (type_of.has(components.Fields)) |field_component| { const fields = field_component.slice(); const last = fields.len - 1; for (fields) |field, i| { try printWasmType(wasm, typeOf(field)); if (i < last) { try wasm.append(' '); } } return; } panic("\nwasm unsupported type {s}\n", .{literalOf(type_of)}); } fn functionName(function: Entity) ![]const u8 { if (function.has(components.WasmName)) |name| { return name.slice(); } var wasm_name = components.WasmName.init(function.ecs.arena.allocator()); try wasm_name.append('$'); try wasm_name.appendSlice(literalOf(function.get(components.Module).entity)); try wasm_name.append('/'); try wasm_name.appendSlice(literalOf(function.get(components.Name).entity)); const builtins = function.ecs.get(components.Builtins); for (function.get(components.Parameters).slice()) |parameter| { try wasm_name.appendSlice(".."); try wasm_name.appendSlice(literalOf(parameter.get(components.Name).entity)); try wasm_name.append('.'); const type_of = typeOf(parameter); const literal = literalOf(type_of); if (type_of.has(components.ParentType)) |parent_type| { if (eql(parent_type.entity, builtins.Ptr)) { try wasm_name.appendSlice("ptr."); try wasm_name.appendSlice(literal[1..]); continue; } assert(eql(parent_type.entity, builtins.Array)); try wasm_name.appendSlice("array."); try wasm_name.appendSlice(literal[2..]); } else { try wasm_name.appendSlice(literal); } } _ = try function.set(.{wasm_name}); return wasm_name.slice(); } fn printWasmFunctionName(wasm: *Wasm, function: Entity) !void { try wasm.appendSlice("\n\n (func "); try wasm.appendSlice(try functionName(function)); } fn printWasmFunctionParameters(wasm: *Wasm, function: Entity) !void { for (function.get(components.Parameters).slice()) |parameter| { const type_of = typeOf(parameter); const literal = literalOf(parameter.get(components.Name).entity); if (type_of.has(components.AstKind)) |ast_kind| { if (ast_kind == .struct_) { for (type_of.get(components.Fields).slice()) |field| { try wasm.appendSlice(" (param $"); try wasm.appendSlice(literal); try wasm.append('.'); try wasm.appendSlice(literalOf(field)); try wasm.append(' '); try printWasmType(wasm, typeOf(field)); try wasm.append(')'); } return; } } try wasm.appendSlice(" (param $"); try wasm.appendSlice(literal); try wasm.append(' '); try printWasmType(wasm, type_of); try wasm.append(')'); } } fn printWasmFunctionReturnType(wasm: *Wasm, function: Entity) !void { const return_type = function.get(components.ReturnType).entity; if (eql(return_type, function.ecs.get(components.Builtins).Void)) { return; } try wasm.appendSlice(" (result "); try printWasmType(wasm, return_type); try wasm.append(')'); } fn printWasmFunctionLocals(wasm: *Wasm, function: Entity) !void { const parameters = function.get(components.Parameters).slice(); const parameter_names = try function.ecs.arena.allocator().alloc(InternedString, parameters.len); for (parameters) |parameter, i| { parameter_names[i] = parameter.get(components.Name).entity.get(components.Literal).interned; } const strings = function.ecs.get(Strings); for (function.get(components.Locals).slice()) |local| { const local_name = local.get(components.Name).entity.get(components.Literal).interned; var found = false; for (parameter_names) |parameter_name| { if (eql(parameter_name, local_name)) { found = true; } } if (found) { continue; } const type_of = typeOf(local); if (type_of.has(components.AstKind)) |ast_kind| { if (ast_kind == .struct_) { for (type_of.get(components.Fields).slice()) |field| { try wasm.appendSlice("\n (local $"); try wasm.appendSlice(strings.get(local_name)); try wasm.append('.'); try wasm.appendSlice(literalOf(field)); try wasm.append(' '); try printWasmType(wasm, typeOf(field)); try wasm.append(')'); } continue; } } try wasm.appendSlice("\n (local $"); try wasm.appendSlice(strings.get(local_name)); try wasm.append(' '); try printWasmType(wasm, type_of); try wasm.append(')'); } } fn printWasmLabel(wasm: *Wasm, wasm_instruction: Entity) !void { const label = wasm_instruction.get(components.Label).value; const result = try std.fmt.allocPrint(wasm.allocator, "$.label.{}", .{label}); try wasm.appendSlice(result); } fn printWasmLocalSet(wasm: *Wasm, wasm_instruction: Entity) !void { const local = wasm_instruction.get(components.Local).entity; const type_of = typeOf(local); const literal = literalOf(local.get(components.Name).entity); if (type_of.has(components.AstKind)) |ast_kind| { if (ast_kind == .struct_) { const fields = type_of.get(components.Fields).slice(); var i = fields.len; while (i > 0) : (i -= 1) { try wasm.appendSlice("\n (local.set $"); try wasm.appendSlice(literal); try wasm.append('.'); try wasm.appendSlice(literalOf(fields[i - 1].get(components.Name).entity)); try wasm.append(')'); } return; } } try wasm.appendSlice("\n (local.set $"); try wasm.appendSlice(literal); try wasm.append(')'); } fn printWasmLocalGet(wasm: *Wasm, wasm_instruction: Entity) !void { const local = wasm_instruction.get(components.Local).entity; const type_of = typeOf(local); const literal = literalOf(local.get(components.Name).entity); if (type_of.has(components.AstKind)) |ast_kind| { if (ast_kind == .struct_) { for (type_of.get(components.Fields).slice()) |field| { try wasm.appendSlice("\n (local.get $"); try wasm.appendSlice(literal); try wasm.append('.'); try wasm.appendSlice(literalOf(field.get(components.Name).entity)); try wasm.append(')'); } return; } } try wasm.appendSlice("\n (local.get $"); try wasm.appendSlice(literal); try wasm.append(')'); } fn printWasmField(wasm: *Wasm, wasm_instruction: Entity) !void { const local = wasm_instruction.get(components.Local).entity; try wasm.appendSlice("\n (local.get $"); try wasm.appendSlice(literalOf(local.get(components.Name).entity)); try wasm.append('.'); try wasm.appendSlice(literalOf(wasm_instruction.get(components.Field).entity)); try wasm.append(')'); } fn printWasmAssignField(wasm: *Wasm, wasm_instruction: Entity) !void { const local = wasm_instruction.get(components.Local).entity; try wasm.appendSlice("\n (local.set $"); try wasm.appendSlice(literalOf(local.get(components.Name).entity)); try wasm.append('.'); try wasm.appendSlice(literalOf(wasm_instruction.get(components.Field).entity)); try wasm.append(')'); } fn printWasmInstruction(wasm: *Wasm, wasm_instruction: Entity) !void { switch (wasm_instruction.get(components.WasmInstructionKind)) { .i64_const => { try wasm.appendSlice("\n (i64.const "); try wasm.appendSlice(literalOf(wasm_instruction.get(components.Constant).entity)); try wasm.append(')'); }, .i32_const => { try wasm.appendSlice("\n (i32.const "); try wasm.appendSlice(literalOf(wasm_instruction.get(components.Constant).entity)); try wasm.append(')'); }, .f64_const => { try wasm.appendSlice("\n (f64.const "); try wasm.appendSlice(literalOf(wasm_instruction.get(components.Constant).entity)); try wasm.append(')'); }, .f32_const => { try wasm.appendSlice("\n (f32.const "); try wasm.appendSlice(literalOf(wasm_instruction.get(components.Constant).entity)); try wasm.append(')'); }, .i64_add => try wasm.appendSlice("\n i64.add"), .i32_add => try wasm.appendSlice("\n i32.add"), .i32_add_mod_16 => { try wasm.appendSlice("\n i32.add"); try wasm.appendSlice("\n (i32.const 65535)"); try wasm.appendSlice("\n i32.and"); }, .i32_add_mod_8 => { try wasm.appendSlice("\n i32.add"); try wasm.appendSlice("\n (i32.const 255)"); try wasm.appendSlice("\n i32.and"); }, .f64_add => try wasm.appendSlice("\n f64.add"), .f32_add => try wasm.appendSlice("\n f32.add"), .i64_sub => try wasm.appendSlice("\n i64.sub"), .i32_sub => try wasm.appendSlice("\n i32.sub"), .i32_sub_mod_16 => { try wasm.appendSlice("\n i32.sub"); try wasm.appendSlice("\n (i32.const 65535)"); try wasm.appendSlice("\n i32.and"); }, .i32_sub_mod_8 => { try wasm.appendSlice("\n i32.sub"); try wasm.appendSlice("\n (i32.const 255)"); try wasm.appendSlice("\n i32.and"); }, .f64_sub => try wasm.appendSlice("\n f64.sub"), .f32_sub => try wasm.appendSlice("\n f32.sub"), .i64_mul => try wasm.appendSlice("\n i64.mul"), .i32_mul => try wasm.appendSlice("\n i32.mul"), .i32_mul_mod_16 => { try wasm.appendSlice("\n i32.mul"); try wasm.appendSlice("\n (i32.const 65535)"); try wasm.appendSlice("\n i32.and"); }, .i32_mul_mod_8 => { try wasm.appendSlice("\n i32.mul"); try wasm.appendSlice("\n (i32.const 255)"); try wasm.appendSlice("\n i32.and"); }, .f64_mul => try wasm.appendSlice("\n f64.mul"), .f32_mul => try wasm.appendSlice("\n f32.mul"), .i64_div => try wasm.appendSlice("\n i64.div_s"), .i32_div => try wasm.appendSlice("\n i32.div_s"), .u64_div => try wasm.appendSlice("\n i64.div_u"), .u32_div => try wasm.appendSlice("\n i32.div_u"), .f64_div => try wasm.appendSlice("\n f64.div"), .f32_div => try wasm.appendSlice("\n f32.div"), .i64_lt => try wasm.appendSlice("\n i64.lt_s"), .i32_lt => try wasm.appendSlice("\n i32.lt_s"), .u64_lt => try wasm.appendSlice("\n i64.lt_u"), .u32_lt => try wasm.appendSlice("\n i32.lt_u"), .f64_lt => try wasm.appendSlice("\n f64.lt"), .f32_lt => try wasm.appendSlice("\n f32.lt"), .i64_le => try wasm.appendSlice("\n i64.le_s"), .i32_le => try wasm.appendSlice("\n i32.le_s"), .u64_le => try wasm.appendSlice("\n i64.le_u"), .u32_le => try wasm.appendSlice("\n i32.le_u"), .f64_le => try wasm.appendSlice("\n f64.le"), .f32_le => try wasm.appendSlice("\n f32.le"), .i64_gt => try wasm.appendSlice("\n i64.gt_s"), .i32_gt => try wasm.appendSlice("\n i32.gt_s"), .u64_gt => try wasm.appendSlice("\n i64.gt_u"), .u32_gt => try wasm.appendSlice("\n i32.gt_u"), .f64_gt => try wasm.appendSlice("\n f64.gt"), .f32_gt => try wasm.appendSlice("\n f32.gt"), .i64_ge => try wasm.appendSlice("\n i64.ge_s"), .i32_ge => try wasm.appendSlice("\n i32.ge_s"), .u64_ge => try wasm.appendSlice("\n i64.ge_u"), .u32_ge => try wasm.appendSlice("\n i32.ge_u"), .f64_ge => try wasm.appendSlice("\n f64.ge"), .f32_ge => try wasm.appendSlice("\n f32.ge"), .i64_eq => try wasm.appendSlice("\n i64.eq"), .i32_eq => try wasm.appendSlice("\n i32.eq"), .f64_eq => try wasm.appendSlice("\n f64.eq"), .f32_eq => try wasm.appendSlice("\n f32.eq"), .i64_ne => try wasm.appendSlice("\n i64.ne"), .i32_ne => try wasm.appendSlice("\n i32.ne"), .f64_ne => try wasm.appendSlice("\n f64.ne"), .f32_ne => try wasm.appendSlice("\n f32.ne"), .i64_or => try wasm.appendSlice("\n i64.or"), .i32_or => try wasm.appendSlice("\n i32.or"), .i64_and => try wasm.appendSlice("\n i64.and"), .i32_and => try wasm.appendSlice("\n i32.and"), .i64_shl => try wasm.appendSlice("\n i64.shl"), .i32_shl => try wasm.appendSlice("\n i32.shl"), .u64_shl => try wasm.appendSlice("\n i64.shl"), .u32_shl => try wasm.appendSlice("\n i32.shl"), .i64_shr => try wasm.appendSlice("\n i64.shr_s"), .i32_shr => try wasm.appendSlice("\n i32.shr_s"), .u64_shr => try wasm.appendSlice("\n i64.shr_u"), .u32_shr => try wasm.appendSlice("\n i32.shr_u"), .i64_rem => try wasm.appendSlice("\n i64.rem_s"), .i32_rem => try wasm.appendSlice("\n i32.rem_s"), .u64_rem => try wasm.appendSlice("\n i64.rem_u"), .u32_rem => try wasm.appendSlice("\n i32.rem_u"), .i64_xor => try wasm.appendSlice("\n i64.xor"), .i32_xor => try wasm.appendSlice("\n i32.xor"), .i32_eqz => try wasm.appendSlice("\n i32.eqz"), .call => { try wasm.appendSlice("\n (call "); const callable = wasm_instruction.get(components.Callable).entity; try wasm.appendSlice(try functionName(callable)); try wasm.append(')'); }, .local_get => try printWasmLocalGet(wasm, wasm_instruction), .local_set => try printWasmLocalSet(wasm, wasm_instruction), .if_ => { try wasm.appendSlice("\n if (result "); try printWasmType(wasm, wasm_instruction.get(components.Type).entity); try wasm.append(')'); }, .else_ => try wasm.appendSlice("\n else"), .end => { try wasm.appendSlice("\n end"); if (wasm_instruction.contains(components.Label)) { try wasm.append(' '); try printWasmLabel(wasm, wasm_instruction); } }, .block => { try wasm.appendSlice("\n block "); try printWasmLabel(wasm, wasm_instruction); }, .loop => { try wasm.appendSlice("\n loop "); try printWasmLabel(wasm, wasm_instruction); }, .br_if => { try wasm.appendSlice("\n br_if "); try printWasmLabel(wasm, wasm_instruction); }, .br => { try wasm.appendSlice("\n br "); try printWasmLabel(wasm, wasm_instruction); }, .i64_store => try wasm.appendSlice("\n i64.store"), .i32_store => try wasm.appendSlice("\n i32.store"), .f64_store => try wasm.appendSlice("\n f64.store"), .f32_store => try wasm.appendSlice("\n f32.store"), .i64_load => try wasm.appendSlice("\n i64.load"), .i32_load => try wasm.appendSlice("\n i32.load"), .i32_load8_u => try wasm.appendSlice("\n i32.load8_u"), .f64_load => try wasm.appendSlice("\n f64.load"), .f32_load => try wasm.appendSlice("\n f32.load"), .v128_load => try wasm.appendSlice("\n v128.load"), .v128_store => try wasm.appendSlice("\n v128.store"), .i64x2_add => try wasm.appendSlice("\n i64x2.add"), .i32x4_add => try wasm.appendSlice("\n i32x4.add"), .i16x8_add => try wasm.appendSlice("\n i16x8.add"), .i8x16_add => try wasm.appendSlice("\n i8x16.add"), .f64x2_add => try wasm.appendSlice("\n f64x2.add"), .f32x4_add => try wasm.appendSlice("\n f32x4.add"), .i64x2_sub => try wasm.appendSlice("\n i64x2.sub"), .i32x4_sub => try wasm.appendSlice("\n i32x4.sub"), .i16x8_sub => try wasm.appendSlice("\n i16x8.sub"), .i8x16_sub => try wasm.appendSlice("\n i8x16.sub"), .f64x2_sub => try wasm.appendSlice("\n f64x2.sub"), .f32x4_sub => try wasm.appendSlice("\n f32x4.sub"), .i64x2_mul => try wasm.appendSlice("\n i64x2.mul"), .i32x4_mul => try wasm.appendSlice("\n i32x4.mul"), .i16x8_mul => try wasm.appendSlice("\n i16x8.mul"), .i8x16_mul => try wasm.appendSlice("\n i8x16.mul"), .f64x2_mul => try wasm.appendSlice("\n f64x2.mul"), .f32x4_mul => try wasm.appendSlice("\n f32x4.mul"), .f64x2_div => try wasm.appendSlice("\n f64x2.div"), .f32x4_div => try wasm.appendSlice("\n f32x4.div"), .field => try printWasmField(wasm, wasm_instruction), .assign_field => try printWasmAssignField(wasm, wasm_instruction), } } fn printWasmFunction(wasm: *Wasm, function: Entity) !void { try printWasmFunctionName(wasm, function); try printWasmFunctionParameters(wasm, function); try printWasmFunctionReturnType(wasm, function); try printWasmFunctionLocals(wasm, function); for (function.get(components.WasmInstructions).slice()) |wasm_instruction| { try printWasmInstruction(wasm, wasm_instruction); } try wasm.append(')'); } fn printWasmForeignImport(wasm: *Wasm, function: Entity) !void { try wasm.appendSlice("\n\n (import \""); try wasm.appendSlice(literalOf(function.get(components.ForeignModule).entity)); try wasm.appendSlice("\" \""); try wasm.appendSlice(literalOf(function.get(components.ForeignName).entity)); try wasm.appendSlice("\" (func "); try wasm.appendSlice(try functionName(function)); try printWasmFunctionParameters(wasm, function); try printWasmFunctionReturnType(wasm, function); try wasm.appendSlice("))"); } fn printBytesAsHex(comptime T: type, wasm: *Wasm, allocator: Allocator, values: []const Entity) !void { for (values) |value| { var data = (try valueOf(T, value)).?; const bytes = @ptrCast([*]u8, &data); var i: usize = 0; while (i < @sizeOf(T)) : (i += 1) { try wasm.append('\\'); const octal = try std.fmt.allocPrint(allocator, "{x}", .{bytes[i]}); if (octal.len == 1) { try wasm.append('0'); } try wasm.appendSlice(octal); } } } fn printDataSegment(wasm: *Wasm, codebase: *ECS) !void { if (codebase.contains(components.UsesMemory)) { const data_segment = codebase.get(components.DataSegment); const allocator = codebase.arena.allocator(); const b = codebase.get(components.Builtins); for (data_segment.entities.slice()) |entity| { try wasm.appendSlice("\n\n (data (i32.const "); const location = entity.get(components.Location).value; const string = try std.fmt.allocPrint(allocator, "{}", .{location}); try wasm.appendSlice(string); try wasm.appendSlice(") \""); switch (entity.get(components.AstKind)) { .string => { for (literalOf(entity)) |c| { switch (c) { '\n' => try wasm.appendSlice("\\n"), else => try wasm.append(c), } } }, .array_literal => { const values = entity.get(components.Values).slice(); const value_type = valueType(typeOf(entity)); if (eql(value_type, b.I32)) { try printBytesAsHex(i32, wasm, allocator, values); } else if (eql(value_type, b.F32)) { try printBytesAsHex(f32, wasm, allocator, values); } else { panic("\n print bytes as hex unsupported type {s} \n", .{literalOf(value_type)}); } }, else => |k| panic("\nwasm print data unsupported kind {}\n", .{k}), } try wasm.appendSlice("\")"); } try wasm.appendSlice("\n\n (memory 1)\n (export \"memory\" (memory 0))"); } } pub fn printWasm(module: Entity) ![]u8 { const codebase = module.ecs; var wasm = Wasm.init(codebase.arena.allocator()); try wasm.appendSlice("(module"); for (codebase.get(components.ForeignImports).slice()) |foreign_import| { try printWasmForeignImport(&wasm, foreign_import); } for (codebase.get(components.Functions).slice()) |function| { try printWasmFunction(&wasm, function); } const top_level = module.get(components.TopLevel); const foreign_exports = module.get(components.ForeignExports).slice(); if (foreign_exports.len > 0) { for (foreign_exports) |foreign_export| { const literal = foreign_export.get(components.Literal); const overload = top_level.findLiteral(literal).get(components.Overloads).slice()[0]; try wasm.appendSlice("\n\n (export \""); try wasm.appendSlice(literalOf(overload.get(components.Name).entity)); try wasm.appendSlice("\" (func "); try wasm.appendSlice(try functionName(overload)); try wasm.appendSlice("))"); } } else { const start = top_level.findString("start").get(components.Overloads).slice()[0]; try wasm.appendSlice("\n\n (export \"_start\" (func "); try wasm.appendSlice(try functionName(start)); try wasm.appendSlice("))"); } try printDataSegment(&wasm, codebase); try wasm.append(')'); return wasm.mutSlice(); }
src/wasm_printer.zig
const build_options = @import("build_options"); const std = @import("std"); const os = std.os; const common = @import("common.zig"); const simdjzon = @import("simdjzon.zig"); const dom = simdjzon.dom; const ondemand = simdjzon.ondemand; pub const step_size = if (build_options.step_128) 128 else 64; pub const read_buf_cap = build_options.ondemand_read_cap; pub fn domMain() !u8 { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var parser: dom.Parser = undefined; if (os.argv.len == 1) { var stdin = std.io.getStdIn().reader(); const input = try stdin.readAllAlloc(allocator, std.math.maxInt(u32)); parser = try dom.Parser.initFixedBuffer(allocator, input, .{}); } else if (os.argv.len == 2) { const filename = std.mem.span(os.argv[1]); parser = try dom.Parser.initFile(allocator, filename, .{}); } else { std.log.err("Too many arguments. Please provide input via filename or stdin", .{}); return 1; } defer parser.deinit(); parser.parse() catch |err| switch (err) { // error.EndOfStream => {}, else => { std.log.err("parse failed. {s}", .{@errorName(err)}); return 1; }, }; std.log.debug("parse valid", .{}); return 0; } pub fn ondemandMain() !u8 { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); // const allocator = std.heap.c_allocator; var parser: ondemand.Parser = undefined; defer if (parser.src.* == .file) parser.src.file.close(); if (os.argv.len == 1) { var stdin = std.io.getStdIn().reader(); const input = try stdin.readAllAlloc(allocator, std.math.maxInt(u32)); var src = std.io.StreamSource{ .buffer = std.io.fixedBufferStream(input) }; parser = try ondemand.Parser.init(&src, allocator, "<stdin>", .{}); } else if (os.argv.len == 2) { const filepath = std.mem.span(os.argv[1]); const file = try std.fs.cwd().openFile(filepath, .{ .read = true }); var src = std.io.StreamSource{ .file = file }; parser = try ondemand.Parser.init(&src, allocator, filepath, .{}); } else { std.log.err("Too many arguments. Please provide input via filename or stdin", .{}); return 1; } defer parser.deinit(); var doc = try parser.iterate(); // common.debug = true; var string_buf: [0x1000]u8 = undefined; var end_index: u32 = 0; recursive_iterate_json(&doc, 1, parser.parser.max_depth, &string_buf, &end_index) catch |err| switch (err) { // error.EndOfStream => {}, else => { std.log.err("{s}:{} parse failed. {s}", .{ parser.parser.filename, end_index, @errorName(err) }); return 1; }, }; if (end_index != doc.iter.last_document_position()[0]) { std.log.err("More than one JSON value at the root of the document, or extra characters at the end of the JSON!", .{}); return 1; } std.log.debug("parse valid", .{}); return 0; } inline fn recursive_iterate_json(element: anytype, depth: u16, max_depth: u16, string_buf: []u8, end_index: *u32) common.Error!void { if (depth >= max_depth) return error.DEPTH_ERROR; var iter = switch (@TypeOf(element)) { *ondemand.Document => element.iter, *ondemand.Value => element.iter.iter, else => unreachable, }; switch (try element.get_type()) { .array => { var arr = try element.get_array(); var it = arr.iterator(); while (try it.next()) |*child| { try recursive_iterate_json(child, depth + 1, max_depth, string_buf, end_index); } end_index.* = (it.iter.iter.token.index - 1)[0]; return; }, .object => { var obj = try element.get_object(); var it = obj.iterator(); var key: [<KEY> = undefined; while (try it.next(&key)) |*field| { try recursive_iterate_json(&field.value, depth + 1, max_depth, string_buf, end_index); } end_index.* = (it.iter.iter.token.index - 1)[0]; return; }, .number => { // FIXME: clean this up to match dom behavior of big int values // failing to match JSONTestSuite on: // i_number_too_big_neg_int.json // i_number_too_big_pos_int.json // i_number_very_big_negative_int.json switch ((try iter.peek_delta(0, 1))[0]) { '-' => _ = element.get_int(i64) catch { _ = try element.get_double(); }, else => _ = element.get_int(u64) catch { _ = try element.get_double(); }, } }, .string => _ = try element.get_string([]u8, string_buf), .bool => _ = try element.get_bool(), .nul => if (!(try element.is_null())) return error.INCORRECT_TYPE, } end_index.* = (iter.token.index - 1)[0]; return; } pub fn main() !u8 { return if (build_options.ondemand) ondemandMain() else domMain(); }
src/main.zig
const std = @import("std"); const io = std.io; const mem = std.mem; const debug = std.debug; const assert = debug.assert; const testing = std.testing; const ArrayListSentineled = std.ArrayListSentineled; const ArrayList = std.ArrayList; const maxInt = std.math.maxInt; const Token = union(enum) { Word: []const u8, OpenBrace, CloseBrace, Comma, Eof, }; var global_allocator: *mem.Allocator = undefined; fn tokenize(input: []const u8) !ArrayList(Token) { const State = enum { Start, Word, }; var token_list = ArrayList(Token).init(global_allocator); var tok_begin: usize = undefined; var state = State.Start; for (input) |b, i| { switch (state) { State.Start => switch (b) { 'a'...'z', 'A'...'Z' => { state = State.Word; tok_begin = i; }, '{' => try token_list.append(Token.OpenBrace), '}' => try token_list.append(Token.CloseBrace), ',' => try token_list.append(Token.Comma), else => return error.InvalidInput, }, State.Word => switch (b) { 'a'...'z', 'A'...'Z' => {}, '{', '}', ',' => { try token_list.append(Token{ .Word = input[tok_begin..i] }); switch (b) { '{' => try token_list.append(Token.OpenBrace), '}' => try token_list.append(Token.CloseBrace), ',' => try token_list.append(Token.Comma), else => unreachable, } state = State.Start; }, else => return error.InvalidInput, }, } } switch (state) { State.Start => {}, State.Word => try token_list.append(Token{ .Word = input[tok_begin..] }), } try token_list.append(Token.Eof); return token_list; } const Node = union(enum) { Scalar: []const u8, List: ArrayList(Node), Combine: []Node, }; const ParseError = error{ InvalidInput, OutOfMemory, }; fn parse(tokens: *const ArrayList(Token), token_index: *usize) ParseError!Node { const first_token = tokens.items[token_index.*]; token_index.* += 1; const result_node = switch (first_token) { Token.Word => |word| Node{ .Scalar = word }, Token.OpenBrace => blk: { var list = ArrayList(Node).init(global_allocator); while (true) { try list.append(try parse(tokens, token_index)); const token = tokens.items[token_index.*]; token_index.* += 1; switch (token) { Token.CloseBrace => break, Token.Comma => continue, else => return error.InvalidInput, } } break :blk Node{ .List = list }; }, else => return error.InvalidInput, }; switch (tokens.items[token_index.*]) { Token.Word, Token.OpenBrace => { const pair = try global_allocator.alloc(Node, 2); pair[0] = result_node; pair[1] = try parse(tokens, token_index); return Node{ .Combine = pair }; }, else => return result_node, } } fn expandString(input: []const u8, output: *ArrayListSentineled(u8, 0)) !void { const tokens = try tokenize(input); if (tokens.items.len == 1) { return output.resize(0); } var token_index: usize = 0; const root = try parse(&tokens, &token_index); const last_token = tokens.items[token_index]; switch (last_token) { Token.Eof => {}, else => return error.InvalidInput, } var result_list = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); defer result_list.deinit(); try expandNode(root, &result_list); try output.resize(0); for (result_list.items) |buf, i| { if (i != 0) { try output.append(' '); } try output.appendSlice(buf.span()); } } const ExpandNodeError = error{OutOfMemory}; fn expandNode(node: Node, output: *ArrayList(ArrayListSentineled(u8, 0))) ExpandNodeError!void { assert(output.items.len == 0); switch (node) { Node.Scalar => |scalar| { try output.append(try ArrayListSentineled(u8, 0).init(global_allocator, scalar)); }, Node.Combine => |pair| { const a_node = pair[0]; const b_node = pair[1]; var child_list_a = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); try expandNode(a_node, &child_list_a); var child_list_b = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); try expandNode(b_node, &child_list_b); for (child_list_a.items) |buf_a| { for (child_list_b.items) |buf_b| { var combined_buf = try ArrayListSentineled(u8, 0).initFromBuffer(buf_a); try combined_buf.appendSlice(buf_b.span()); try output.append(combined_buf); } } }, Node.List => |list| { for (list.items) |child_node| { var child_list = ArrayList(ArrayListSentineled(u8, 0)).init(global_allocator); try expandNode(child_node, &child_list); for (child_list.items) |buf| { try output.append(buf); } } }, } } pub fn main() !void { const stdin_file = io.getStdIn(); const stdout_file = io.getStdOut(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); global_allocator = &arena.allocator; var stdin_buf = try ArrayListSentineled(u8, 0).initSize(global_allocator, 0); defer stdin_buf.deinit(); var stdin_adapter = stdin_file.inStream(); try stdin_adapter.stream.readAllBuffer(&stdin_buf, maxInt(usize)); var result_buf = try ArrayListSentineled(u8, 0).initSize(global_allocator, 0); defer result_buf.deinit(); try expandString(stdin_buf.span(), &result_buf); try stdout_file.write(result_buf.span()); } test "invalid inputs" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); global_allocator = &arena.allocator; expectError("}ABC", error.InvalidInput); expectError("{ABC", error.InvalidInput); expectError("}{", error.InvalidInput); expectError("{}", error.InvalidInput); expectError("A,B,C", error.InvalidInput); expectError("{A{B,C}", error.InvalidInput); expectError("{A,}", error.InvalidInput); expectError("\n", error.InvalidInput); } fn expectError(test_input: []const u8, expected_err: anyerror) void { var output_buf = ArrayListSentineled(u8, 0).initSize(global_allocator, 0) catch unreachable; defer output_buf.deinit(); testing.expectError(expected_err, expandString(test_input, &output_buf)); } test "valid inputs" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); global_allocator = &arena.allocator; expectExpansion("{x,y,z}", "x y z"); expectExpansion("{A,B}{x,y}", "Ax Ay Bx By"); expectExpansion("{A,B{x,y}}", "A Bx By"); expectExpansion("{ABC}", "ABC"); expectExpansion("{A,B,C}", "A B C"); expectExpansion("ABC", "ABC"); expectExpansion("", ""); expectExpansion("{A,B}{C,{x,y}}{g,h}", "ACg ACh Axg Axh Ayg Ayh BCg BCh Bxg Bxh Byg Byh"); expectExpansion("{A,B}{C,C{x,y}}{g,h}", "ACg ACh ACxg ACxh ACyg ACyh BCg BCh BCxg BCxh BCyg BCyh"); expectExpansion("{A,B}a", "Aa Ba"); expectExpansion("{C,{x,y}}", "C x y"); expectExpansion("z{C,{x,y}}", "zC zx zy"); expectExpansion("a{b,c{d,e{f,g}}}", "ab acd acef aceg"); expectExpansion("a{x,y}b", "axb ayb"); expectExpansion("z{{a,b}}", "za zb"); expectExpansion("a{b}", "ab"); } fn expectExpansion(test_input: []const u8, expected_result: []const u8) void { var result = ArrayListSentineled(u8, 0).initSize(global_allocator, 0) catch unreachable; defer result.deinit(); expandString(test_input, &result) catch unreachable; testing.expectEqualSlices(u8, expected_result, result.span()); }
test/standalone/brace_expansion/main.zig
const std = @import("std.zig"); const builtin = std.builtin; const assert = std.debug.assert; const testing = std.testing; const os = std.os; const math = std.math; const is_windows = std.Target.current.os.tag == .windows; pub const epoch = @import("time/epoch.zig"); /// Spurious wakeups are possible and no precision of timing is guaranteed. /// TODO integrate with evented I/O pub fn sleep(nanoseconds: u64) void { if (is_windows) { const big_ms_from_ns = nanoseconds / ns_per_ms; const ms = math.cast(os.windows.DWORD, big_ms_from_ns) catch math.maxInt(os.windows.DWORD); os.windows.kernel32.Sleep(ms); return; } if (builtin.os.tag == .wasi) { const w = std.os.wasi; const userdata: w.userdata_t = 0x0123_45678; const clock = w.subscription_clock_t{ .id = w.CLOCK_MONOTONIC, .timeout = nanoseconds, .precision = 0, .flags = 0, }; const in = w.subscription_t{ .userdata = userdata, .u = w.subscription_u_t{ .tag = w.EVENTTYPE_CLOCK, .u = w.subscription_u_u_t{ .clock = clock, }, }, }; var event: w.event_t = undefined; var nevents: usize = undefined; _ = w.poll_oneoff(&in, &event, 1, &nevents); return; } const s = nanoseconds / ns_per_s; const ns = nanoseconds % ns_per_s; std.os.nanosleep(s, ns); } /// Get a calendar timestamp, in seconds, relative to UTC 1970-01-01. /// Precision of timing depends on the hardware and operating system. /// The return value is signed because it is possible to have a date that is /// before the epoch. /// See `std.os.clock_gettime` for a POSIX timestamp. pub fn timestamp() i64 { return @divFloor(milliTimestamp(), ns_per_s); } /// Get a calendar timestamp, in milliseconds, relative to UTC 1970-01-01. /// Precision of timing depends on the hardware and operating system. /// The return value is signed because it is possible to have a date that is /// before the epoch. /// See `std.os.clock_gettime` for a POSIX timestamp. pub fn milliTimestamp() i64 { return @intCast(i64, @divFloor(nanoTimestamp(), ns_per_ms)); } /// Get a calendar timestamp, in nanoseconds, relative to UTC 1970-01-01. /// Precision of timing depends on the hardware and operating system. /// On Windows this has a maximum granularity of 100 nanoseconds. /// The return value is signed because it is possible to have a date that is /// before the epoch. /// See `std.os.clock_gettime` for a POSIX timestamp. pub fn nanoTimestamp() i128 { if (is_windows) { // FileTime has a granularity of 100 nanoseconds and uses the NTFS/Windows epoch, // which is 1601-01-01. const epoch_adj = epoch.windows * (ns_per_s / 100); var ft: os.windows.FILETIME = undefined; os.windows.kernel32.GetSystemTimeAsFileTime(&ft); const ft64 = (@as(u64, ft.dwHighDateTime) << 32) | ft.dwLowDateTime; return @as(i128, @bitCast(i64, ft64) + epoch_adj) * 100; } if (builtin.os.tag == .wasi and !builtin.link_libc) { var ns: os.wasi.timestamp_t = undefined; const err = os.wasi.clock_time_get(os.wasi.CLOCK_REALTIME, 1, &ns); assert(err == os.wasi.ESUCCESS); return ns; } var ts: os.timespec = undefined; os.clock_gettime(os.CLOCK_REALTIME, &ts) catch |err| switch (err) { error.UnsupportedClock, error.Unexpected => return 0, // "Precision of timing depends on hardware and OS". }; return (@as(i128, ts.tv_sec) * ns_per_s) + ts.tv_nsec; } // Divisions of a nanosecond. pub const ns_per_us = 1000; pub const ns_per_ms = 1000 * ns_per_us; pub const ns_per_s = 1000 * ns_per_ms; pub const ns_per_min = 60 * ns_per_s; pub const ns_per_hour = 60 * ns_per_min; pub const ns_per_day = 24 * ns_per_hour; pub const ns_per_week = 7 * ns_per_day; // Divisions of a microsecond. pub const us_per_ms = 1000; pub const us_per_s = 1000 * us_per_ms; pub const us_per_min = 60 * us_per_s; pub const us_per_hour = 60 * us_per_min; pub const us_per_day = 24 * us_per_hour; pub const us_per_week = 7 * us_per_day; // Divisions of a millisecond. pub const ms_per_s = 1000; pub const ms_per_min = 60 * ms_per_s; pub const ms_per_hour = 60 * ms_per_min; pub const ms_per_day = 24 * ms_per_hour; pub const ms_per_week = 7 * ms_per_day; // Divisions of a second. pub const s_per_min = 60; pub const s_per_hour = s_per_min * 60; pub const s_per_day = s_per_hour * 24; pub const s_per_week = s_per_day * 7; /// A monotonic high-performance timer. /// Timer.start() must be called to initialize the struct, which captures /// the counter frequency on windows and darwin, records the resolution, /// and gives the user an opportunity to check for the existnece of /// monotonic clocks without forcing them to check for error on each read. /// .resolution is in nanoseconds on all platforms but .start_time's meaning /// depends on the OS. On Windows and Darwin it is a hardware counter /// value that requires calculation to convert to a meaninful unit. pub const Timer = struct { ///if we used resolution's value when performing the /// performance counter calc on windows/darwin, it would /// be less precise frequency: switch (builtin.os.tag) { .windows => u64, .macosx, .ios, .tvos, .watchos => os.darwin.mach_timebase_info_data, else => void, }, resolution: u64, start_time: u64, pub const Error = error{TimerUnsupported}; /// At some point we may change our minds on RAW, but for now we're /// sticking with posix standard MONOTONIC. For more information, see: /// https://github.com/ziglang/zig/pull/933 const monotonic_clock_id = os.CLOCK_MONOTONIC; /// Initialize the timer structure. /// Can only fail when running in a hostile environment that intentionally injects /// error values into syscalls, such as using seccomp on Linux to intercept /// `clock_gettime`. pub fn start() Error!Timer { // This gives us an opportunity to grab the counter frequency in windows. // On Windows: QueryPerformanceCounter will succeed on anything >= XP/2000. // On Posix: CLOCK_MONOTONIC will only fail if the monotonic counter is not // supported, or if the timespec pointer is out of bounds, which should be // impossible here barring cosmic rays or other such occurrences of // incredibly bad luck. // On Darwin: This cannot fail, as far as I am able to tell. if (is_windows) { const freq = os.windows.QueryPerformanceFrequency(); return Timer{ .frequency = freq, .resolution = @divFloor(ns_per_s, freq), .start_time = os.windows.QueryPerformanceCounter(), }; } else if (comptime std.Target.current.isDarwin()) { var freq: os.darwin.mach_timebase_info_data = undefined; os.darwin.mach_timebase_info(&freq); return Timer{ .frequency = freq, .resolution = @divFloor(freq.numer, freq.denom), .start_time = os.darwin.mach_absolute_time(), }; } else { // On Linux, seccomp can do arbitrary things to our ability to call // syscalls, including return any errno value it wants and // inconsistently throwing errors. Since we can't account for // abuses of seccomp in a reasonable way, we'll assume that if // seccomp is going to block us it will at least do so consistently var res: os.timespec = undefined; os.clock_getres(monotonic_clock_id, &res) catch return error.TimerUnsupported; var ts: os.timespec = undefined; os.clock_gettime(monotonic_clock_id, &ts) catch return error.TimerUnsupported; return Timer{ .resolution = @intCast(u64, res.tv_sec) * ns_per_s + @intCast(u64, res.tv_nsec), .start_time = @intCast(u64, ts.tv_sec) * ns_per_s + @intCast(u64, ts.tv_nsec), .frequency = {}, }; } return self; } /// Reads the timer value since start or the last reset in nanoseconds pub fn read(self: Timer) u64 { var clock = clockNative() - self.start_time; return self.nativeDurationToNanos(clock); } /// Resets the timer value to 0/now. pub fn reset(self: *Timer) void { self.start_time = clockNative(); } /// Returns the current value of the timer in nanoseconds, then resets it pub fn lap(self: *Timer) u64 { var now = clockNative(); var lap_time = self.nativeDurationToNanos(now - self.start_time); self.start_time = now; return lap_time; } fn clockNative() u64 { if (is_windows) { return os.windows.QueryPerformanceCounter(); } if (comptime std.Target.current.isDarwin()) { return os.darwin.mach_absolute_time(); } var ts: os.timespec = undefined; os.clock_gettime(monotonic_clock_id, &ts) catch unreachable; return @intCast(u64, ts.tv_sec) * @as(u64, ns_per_s) + @intCast(u64, ts.tv_nsec); } fn nativeDurationToNanos(self: Timer, duration: u64) u64 { if (is_windows) { return @divFloor(duration * ns_per_s, self.frequency); } if (comptime std.Target.current.isDarwin()) { return @divFloor(duration * self.frequency.numer, self.frequency.denom); } return duration; } }; test "sleep" { sleep(1); } test "timestamp" { const margin = ns_per_ms * 50; const time_0 = milliTimestamp(); sleep(ns_per_ms); const time_1 = milliTimestamp(); const interval = time_1 - time_0; testing.expect(interval > 0 and interval < margin); } test "Timer" { const margin = ns_per_ms * 150; var timer = try Timer.start(); sleep(10 * ns_per_ms); const time_0 = timer.read(); testing.expect(time_0 > 0 and time_0 < margin); const time_1 = timer.lap(); testing.expect(time_1 >= time_0); timer.reset(); testing.expect(timer.read() < time_1); }
lib/std/time.zig
const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const maxInt = std.math.maxInt; /// Returns sqrt(x * x + y * y), avoiding unncessary overflow and underflow. /// /// Special Cases: /// - hypot(+-inf, y) = +inf /// - hypot(x, +-inf) = +inf /// - hypot(nan, y) = nan /// - hypot(x, nan) = nan pub fn hypot(comptime T: type, x: T, y: T) T { return switch (T) { f32 => hypot32(x, y), f64 => hypot64(x, y), else => @compileError("hypot not implemented for " ++ @typeName(T)), }; } fn hypot32(x: f32, y: f32) f32 { var ux = @bitCast(u32, x); var uy = @bitCast(u32, y); ux &= maxInt(u32) >> 1; uy &= maxInt(u32) >> 1; if (ux < uy) { const tmp = ux; ux = uy; uy = tmp; } var xx = @bitCast(f32, ux); var yy = @bitCast(f32, uy); if (uy == 0xFF << 23) { return yy; } if (ux >= 0xFF << 23 or uy == 0 or ux - uy >= (25 << 23)) { return xx + yy; } var z: f32 = 1.0; if (ux >= (0x7F + 60) << 23) { z = 0x1.0p90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; } else if (uy < (0x7F - 60) << 23) { z = 0x1.0p-90; xx *= 0x1.0p-90; yy *= 0x1.0p-90; } return z * math.sqrt(@floatCast(f32, @as(f64, x) * x + @as(f64, y) * y)); } fn sq(hi: *f64, lo: *f64, x: f64) void { const split: f64 = 0x1.0p27 + 1.0; const xc = x * split; const xh = x - xc + xc; const xl = x - xh; hi.* = x * x; lo.* = xh * xh - hi.* + 2 * xh * xl + xl * xl; } fn hypot64(x: f64, y: f64) f64 { var ux = @bitCast(u64, x); var uy = @bitCast(u64, y); ux &= maxInt(u64) >> 1; uy &= maxInt(u64) >> 1; if (ux < uy) { const tmp = ux; ux = uy; uy = tmp; } const ex = ux >> 52; const ey = uy >> 52; var xx = @bitCast(f64, ux); var yy = @bitCast(f64, uy); // hypot(inf, nan) == inf if (ey == 0x7FF) { return yy; } if (ex == 0x7FF or uy == 0) { return xx; } // hypot(x, y) ~= x + y * y / x / 2 with inexact for small y/x if (ex - ey > 64) { return xx + yy; } var z: f64 = 1; if (ex > 0x3FF + 510) { z = 0x1.0p700; xx *= 0x1.0p-700; yy *= 0x1.0p-700; } else if (ey < 0x3FF - 450) { z = 0x1.0p-700; xx *= 0x1.0p700; yy *= 0x1.0p700; } var hx: f64 = undefined; var lx: f64 = undefined; var hy: f64 = undefined; var ly: f64 = undefined; sq(&hx, &lx, x); sq(&hy, &ly, y); return z * math.sqrt(ly + lx + hy + hx); } test "math.hypot" { expect(hypot(f32, 0.0, -1.2) == hypot32(0.0, -1.2)); expect(hypot(f64, 0.0, -1.2) == hypot64(0.0, -1.2)); } test "math.hypot32" { const epsilon = 0.000001; expect(math.approxEqAbs(f32, hypot32(0.0, -1.2), 1.2, epsilon)); expect(math.approxEqAbs(f32, hypot32(0.2, -0.34), 0.394462, epsilon)); expect(math.approxEqAbs(f32, hypot32(0.8923, 2.636890), 2.783772, epsilon)); expect(math.approxEqAbs(f32, hypot32(1.5, 5.25), 5.460083, epsilon)); expect(math.approxEqAbs(f32, hypot32(37.45, 159.835), 164.163742, epsilon)); expect(math.approxEqAbs(f32, hypot32(89.123, 382.028905), 392.286865, epsilon)); expect(math.approxEqAbs(f32, hypot32(123123.234375, 529428.707813), 543556.875, epsilon)); } test "math.hypot64" { const epsilon = 0.000001; expect(math.approxEqAbs(f64, hypot64(0.0, -1.2), 1.2, epsilon)); expect(math.approxEqAbs(f64, hypot64(0.2, -0.34), 0.394462, epsilon)); expect(math.approxEqAbs(f64, hypot64(0.8923, 2.636890), 2.783772, epsilon)); expect(math.approxEqAbs(f64, hypot64(1.5, 5.25), 5.460082, epsilon)); expect(math.approxEqAbs(f64, hypot64(37.45, 159.835), 164.163728, epsilon)); expect(math.approxEqAbs(f64, hypot64(89.123, 382.028905), 392.286876, epsilon)); expect(math.approxEqAbs(f64, hypot64(123123.234375, 529428.707813), 543556.885247, epsilon)); } test "math.hypot32.special" { expect(math.isPositiveInf(hypot32(math.inf(f32), 0.0))); expect(math.isPositiveInf(hypot32(-math.inf(f32), 0.0))); expect(math.isPositiveInf(hypot32(0.0, math.inf(f32)))); expect(math.isPositiveInf(hypot32(0.0, -math.inf(f32)))); expect(math.isNan(hypot32(math.nan(f32), 0.0))); expect(math.isNan(hypot32(0.0, math.nan(f32)))); } test "math.hypot64.special" { expect(math.isPositiveInf(hypot64(math.inf(f64), 0.0))); expect(math.isPositiveInf(hypot64(-math.inf(f64), 0.0))); expect(math.isPositiveInf(hypot64(0.0, math.inf(f64)))); expect(math.isPositiveInf(hypot64(0.0, -math.inf(f64)))); expect(math.isNan(hypot64(math.nan(f64), 0.0))); expect(math.isNan(hypot64(0.0, math.nan(f64)))); }
lib/std/math/hypot.zig
const std = @import("std"); const uri = @import("uri"); const Engine = @import("Engine.zig"); const Dependency = @import("Dependency.zig"); const Project = @import("Project.zig"); const api = @import("api.zig"); const cache = @import("cache.zig"); const utils = @import("utils.zig"); const local = @import("local.zig"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; pub const name = "url"; pub const Resolution = void; pub const ResolutionEntry = struct { root: []const u8, str: []const u8, dep_idx: ?usize = null, }; pub const FetchError = @typeInfo(@typeInfo(@TypeOf(fetch)).Fn.return_type.?).ErrorUnion.error_set; const FetchQueue = Engine.MultiQueueImpl(Resolution, FetchError); const ResolutionTable = std.ArrayListUnmanaged(ResolutionEntry); pub fn deserializeLockfileEntry( allocator: *Allocator, it: *std.mem.TokenIterator(u8), resolutions: *ResolutionTable, ) !void { const entry = ResolutionEntry{ .root = it.next() orelse return error.NoRoot, .str = it.next() orelse return error.NoUrl, }; if (std.mem.startsWith(u8, entry.str, "file://")) return error.OldLocalFormat; try resolutions.append(allocator, entry); } pub fn serializeResolutions( resolutions: []const ResolutionEntry, writer: anytype, ) !void { for (resolutions) |entry| if (entry.dep_idx != null) try writer.print("url {s} {s}\n", .{ entry.root, entry.str, }); } fn findResolution(dep: Dependency.Source, resolutions: []const ResolutionEntry) ?usize { const root = dep.url.root orelse utils.default_root; return for (resolutions) |entry, i| { if (std.mem.eql(u8, dep.url.str, entry.str) and std.mem.eql(u8, root, entry.root)) { break i; } } else null; } fn findMatch(dep_table: []const Dependency.Source, dep_idx: usize, edges: []const Engine.Edge) ?usize { const dep = dep_table[dep_idx].url; const root = dep.root orelse utils.default_root; return for (edges) |edge| { const other = dep_table[edge.to].url; const other_root = other.root orelse utils.default_root; if (std.mem.eql(u8, dep.str, other.str) and std.mem.eql(u8, root, other_root)) { break edge.to; } } else null; } fn findPartialMatch(dep_table: []const Dependency.Source, dep_idx: usize, edges: []const Engine.Edge) ?usize { const dep = dep_table[dep_idx].url; return for (edges) |edge| { const other = dep_table[edge.to].url; if (std.mem.eql(u8, dep.str, other.str)) { break edge.to; } } else null; } fn fetch( arena: *std.heap.ArenaAllocator, dep: Dependency.Source, deps: *std.ArrayListUnmanaged(Dependency), path: *?[]const u8, ) !void { const allocator = arena.child_allocator; const link = try uri.parse(dep.url.str); const entry_name = try std.mem.replaceOwned(u8, allocator, dep.url.str[link.scheme.?.len + 3 ..], "/", "-"); defer allocator.free(entry_name); var entry = try cache.getEntry(entry_name); defer entry.deinit(); if (!try entry.isDone()) { var content_dir = try entry.contentDir(); defer content_dir.close(); // TODO: allow user to strip directories from a tarball try api.getTarGz(allocator, dep.url.str, content_dir); try entry.done(); } const base_path = try std.fs.path.join(arena.child_allocator, &.{ ".gyro", entry_name, "pkg", }); defer arena.child_allocator.free(base_path); const root = dep.url.root orelse utils.default_root; path.* = try utils.joinPathConvertSep(arena, &.{ base_path, root }); var base_dir = try std.fs.cwd().openDir(base_path, .{}); defer base_dir.close(); const project_file = try base_dir.createFile("gyro.zzz", .{ .read = true, .truncate = false, .exclusive = false, }); defer project_file.close(); const text = try project_file.reader().readAllAlloc(&arena.allocator, std.math.maxInt(usize)); const project = try Project.fromUnownedText(arena.child_allocator, ".", text); defer project.destroy(); try deps.appendSlice(arena.child_allocator, project.deps.items); } pub fn dedupeResolveAndFetch( dep_table: []const Dependency.Source, resolutions: []const ResolutionEntry, fetch_queue: *FetchQueue, i: usize, ) FetchError!void { const arena = &fetch_queue.items(.arena)[i]; _ = arena; const dep_idx = fetch_queue.items(.edge)[i].to; // check lockfile for entry if (findResolution(dep_table[dep_idx], resolutions)) |res_idx| { if (resolutions[res_idx].dep_idx) |idx| { fetch_queue.items(.result)[i] = .{ .replace_me = idx, }; return; } else if (findMatch(dep_table, dep_idx, fetch_queue.items(.edge)[0..i])) |idx| { fetch_queue.items(.result)[i] = .{ .replace_me = idx, }; return; } else { fetch_queue.items(.result)[i] = .{ .fill_resolution = res_idx, }; } } else if (findMatch(dep_table, dep_idx, fetch_queue.items(.edge)[0..i])) |idx| { fetch_queue.items(.result)[i] = .{ .replace_me = idx, }; return; } else if (findPartialMatch(dep_table, dep_idx, fetch_queue.items(.edge)[0..i])) |idx| { fetch_queue.items(.result)[i] = .{ .copy_deps = idx, }; return; } else { fetch_queue.items(.result)[i] = .{ .new_entry = {}, }; } try fetch( arena, dep_table[dep_idx], &fetch_queue.items(.deps)[i], &fetch_queue.items(.path)[i], ); } pub fn updateResolution( allocator: *Allocator, resolutions: *ResolutionTable, dep_table: []const Dependency.Source, fetch_queue: *FetchQueue, i: usize, ) !void { switch (fetch_queue.items(.result)[i]) { .fill_resolution => |res_idx| { const dep_idx = fetch_queue.items(.edge)[i].to; assert(resolutions.items[res_idx].dep_idx == null); resolutions.items[res_idx].dep_idx = dep_idx; }, .new_entry => { const dep_idx = fetch_queue.items(.edge)[i].to; const url = &dep_table[dep_idx].url; const root = url.root orelse utils.default_root; try resolutions.append(allocator, .{ .str = url.str, .root = root, .dep_idx = dep_idx, }); }, .replace_me => |dep_idx| fetch_queue.items(.edge)[i].to = dep_idx, .err => |err| return err, // TODO: update resolution table .copy_deps => |queue_idx| try fetch_queue.items(.deps)[i].appendSlice( allocator, fetch_queue.items(.deps)[queue_idx].items, ), } }
src/url.zig
const std = @import("std"); const info = std.log.info; const dbg = std.log.debug; const emerg = std.log.emerg; pub const SystemSegmentAndGateDescriptorType = packed enum(u4) { available_task_state_segment_16bit = 1, busy_task_state_segment_16bit = 3, call_gate_16bit = 4, task_gate = 5, interrupt_gate_16bit = 6, trap_gate_16bit = 7, available_task_statement_segment_32bit = 9, busy_task_statement_segment_32bit = 11, call_gate_32bit = 12, interrupt_gate_32bit = 14, trap_gate_32bit = 15, }; pub const DescriptorType = packed enum(u1) { system = 0, code_or_data = 1, }; pub const SegmentDescriptor32Bit = packed struct { pub const segment_type_code_readable_flag: u4 = 0x2; pub const segment_type_data_writable_flag: u4 = 0x2; pub const segment_type_code_conforming_flag: u4 = 0x4; pub const segment_type_data_expansion_direction_down_flag: u4 = 0x4; pub const segment_type_executable_flag: u4 = 0x8; /// 15:0 of Segment Limit segment_limit_bit_15_to_0: u16, /// 23:0 of Base Address base_address_bit_23_to_0: u24, segment_type: u4, descriptor_type: DescriptorType, descriptor_privilege_level: u2, is_present: bool, /// 19:16 of Segment limit segment_limit_bit_19_to_16: u4, /// This field can be used by OS to store extra data field_available_to_os: u1, /// Only used for IA-32e(64-bit mode) is_64bit_code_segment: bool, /// Set to `false` for 16-bit and 64-bit code/data Segments. is_32bit_code_data_segment: bool, /// If set to true, Segment Limit is multiplied by 4KiB. is_4k_granularity: bool, /// 31:24 of Base Address base_address_bit_31_to_24: u8, pub fn set_segment_limit(self: *SegmentDescriptor32Bit, segment_limit: u20) void { self.segment_limit_bit_15_to_0 = @intCast(u16, segment_limit & 0x0FFFF); self.segment_limit_bit_19_to_16 = @intCast(u4, (segment_limit & 0xF0000) >> 16); } pub fn set_base_address(self: *SegmentDescriptor32Bit, base_address: u32) void { self.base_address_bit_23_to_0 = @intCast(u24, base_address & 0x00FFFFFF); self.base_address_bit_31_to_24 = @intCast(u8, (base_address & 0xFF000000) >> 8); } pub fn get_segment_limit(self: *const SegmentDescriptor32Bit) u20 { return @intCast(u20, self.segment_limit_bit_15_to_0) | (@intCast(u20, self.segment_limit_bit_19_to_16) << 16); } pub fn get_base_address(self: *const SegmentDescriptor32Bit) u32 { return @intCast(u32, self.base_address_bit_23_to_0) | (@intCast(u32, self.base_address_bit_31_to_24) << 24); } pub fn new_null_descriptor() SegmentDescriptor32Bit { return .{ .segment_limit_bit_15_to_0 = 0, .base_address_bit_23_to_0 = 0, .segment_type = 0, .descriptor_type = @intToEnum(DescriptorType, 0), .descriptor_privilege_level = 0, .is_present = false, .segment_limit_bit_19_to_16 = 0, .field_available_to_os = 0, .is_64bit_code_segment = false, .is_32bit_code_data_segment = false, .is_4k_granularity = false, .base_address_bit_31_to_24 = 0, }; } pub fn new_system_descriptor( segment_limit: u20, base_address: u32, segment_type: u4, descriptior_privilege_level: u2, is_present: bool, is_4k_granularity: bool, ) SegmentDescriptor32Bit { var segment_descriptor = SegmentDescriptor32Bit{ .segment_limit_bit_15_to_0 = 0, // Will be initialized later .base_address_bit_23_to_0 = 0, // Will be initialized later .segment_type = segment_type, .descriptor_type = .system, .descriptior_privilege_level = descriptior_privilege_level, .is_present = is_present, .segment_limit_bit_19_to_16 = 0, // Will be initialized later .field_available_to_os = 0, // Reserved .is_64bit_code_segment = false, // Reserved .is_32bit_code_data_segment = false, // Reserved .is_4k_granularity = is_4k_granularity, .base_address_bit_31_to_24 = 0, // Will be initialized later }; segment_descriptor.set_segment_limit(segment_limit); segment_descriptor.set_base_address(base_address); return segment_descriptor; } pub fn new_code_descriptor( segment_limit: u20, base_address: u32, is_readable: bool, is_conforming: bool, descriptor_privilege_level: u2, is_present: bool, is_4k_granularity: bool, ) SegmentDescriptor32Bit { var segment_type_value = segment_type_executable_flag; if (is_readable) { segment_type_value |= segment_type_code_readable_flag; } if (is_conforming) { segment_type_value |= segment_type_code_conforming_flag; } var segment_descriptor = SegmentDescriptor32Bit{ .segment_limit_bit_15_to_0 = 0, // Will be initialized later .base_address_bit_23_to_0 = 0, // Will be initialized later .segment_type = segment_type_value, .descriptor_type = .code_or_data, .descriptor_privilege_level = descriptor_privilege_level, .is_present = is_present, .segment_limit_bit_19_to_16 = 0, // Will be initialized later .field_available_to_os = 0, .is_64bit_code_segment = false, // Reserved .is_32bit_code_data_segment = true, .is_4k_granularity = is_4k_granularity, .base_address_bit_31_to_24 = 0, // Will be initialized later }; segment_descriptor.set_segment_limit(segment_limit); segment_descriptor.set_base_address(base_address); return segment_descriptor; } pub fn new_data_descriptor( segment_limit: u20, base_address: u32, is_writable: bool, is_expansion_direction_down: bool, descriptor_privilege_level: u2, is_present: bool, is_4k_granularity: bool, ) SegmentDescriptor32Bit { var segment_type_value: u4 = 0x0; if (is_writable) { segment_type_value |= segment_type_data_writable_flag; } if (is_expansion_direction_down) { segment_type_value |= segment_type_data_expansion_direction_down_flag; } var segment_descriptor = SegmentDescriptor32Bit{ .segment_limit_bit_15_to_0 = 0, // Will be initialized later .base_address_bit_23_to_0 = 0, // Will be initialized later .segment_type = segment_type_value, .descriptor_type = .code_or_data, .descriptor_privilege_level = descriptor_privilege_level, .is_present = is_present, .segment_limit_bit_19_to_16 = 0, // Will be initialized later .field_available_to_os = 0, .is_64bit_code_segment = false, // Reserved .is_32bit_code_data_segment = true, .is_4k_granularity = is_4k_granularity, .base_address_bit_31_to_24 = 0, // Will be initialized later }; segment_descriptor.set_segment_limit(segment_limit); segment_descriptor.set_base_address(base_address); return segment_descriptor; } pub fn new_kernel_code_descriptor() SegmentDescriptor32Bit { return new_code_descriptor(0xFFFFF, 0, false, false, 0, true, true); } pub fn new_kernel_data_descriptor() SegmentDescriptor32Bit { return new_data_descriptor(0xFFFFF, 0, false, false, 0, true, true); } }; pub const DescriptorTableRegister = packed struct { table_limit: u16, descriptors_ptr: [*]SegmentDescriptor32Bit, pub fn load_gdt_to_processor(self: *const DescriptorTableRegister) void { asm volatile ("lgdt %[descriptor_table_register]" : : [descriptor_table_register] "=*m" (self) ); } pub fn store_gdt_from_processor() DescriptorTableRegister { var descriptor_table_register: DescriptorTableRegister = undefined; asm volatile ("sgdt %[descriptor_table_register]" : : [descriptor_table_register] "=*m" (&descriptor_table_register) ); return descriptor_table_register; } pub fn descriptors(self: *DescriptorTableRegister) []SegmentDescriptor32Bit { const descriptor_count = self.table_limit / @sizeOf(SegmentDescriptor32Bit); return self.descriptors_ptr[0..descriptor_count]; } }; var global_descriptors = [_]SegmentDescriptor32Bit{ SegmentDescriptor32Bit.new_null_descriptor(), SegmentDescriptor32Bit.new_kernel_code_descriptor(), SegmentDescriptor32Bit.new_kernel_data_descriptor(), }; pub fn initialize() void { var descriptor_table_register = DescriptorTableRegister { .table_limit = @sizeOf(SegmentDescriptor32Bit) * global_descriptors.len, .descriptors_ptr = &global_descriptors, }; info("Loading Global Descriptor Table Register", .{}); descriptor_table_register.load_gdt_to_processor(); info("Loaded Global Descriptor Table Register", .{}); var new_descriptor_table_register = DescriptorTableRegister.store_gdt_from_processor(); info("=========================== Global Descriptor Table ===========================", .{}); for (new_descriptor_table_register.descriptors()) |descriptor, index| { info("[{}] Base P{X:0>8} Limit {X:0>8}", .{ index, descriptor.get_base_address(), descriptor.get_segment_limit() }); } info("=========================== Global Descriptor Table ===========================", .{}); }
kernel/descriptor.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const mem = std.mem; const trait = std.meta.trait; const asn1 = @import("asn1.zig"); // zig fmt: off // http://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8 pub const CurveId = enum { sect163k1, sect163r1, sect163r2, sect193r1, sect193r2, sect233k1, sect233r1, sect239k1, sect283k1, sect283r1, sect409k1, sect409r1, sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, secp192k1, secp192r1, secp224k1, secp224r1, secp256k1, secp256r1, secp384r1, secp521r1,brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, curve25519, curve448, }; // zig fmt: on pub const PublicKey = union(enum) { pub const empty = PublicKey{ .ec = .{ .id = undefined, .curve_point = &[0]u8{} } }; /// RSA public key rsa: struct { //Positive std.math.big.int.Const numbers. modulus: []const usize, exponent: []const usize, }, /// Elliptic curve public key ec: struct { id: CurveId, /// Public curve point (uncompressed format) curve_point: []const u8, }, pub fn deinit(self: @This(), alloc: *Allocator) void { switch (self) { .rsa => |rsa| { alloc.free(rsa.modulus); alloc.free(rsa.exponent); }, .ec => |ec| alloc.free(ec.curve_point), } } pub fn eql(self: @This(), other: @This()) bool { if (@as(std.meta.Tag(@This()), self) != @as(std.meta.Tag(@This()), other)) return false; switch (self) { .rsa => |mod_exp| return mem.eql(usize, mod_exp.exponent, other.rsa.exponent) and mem.eql(usize, mod_exp.modulus, other.rsa.modulus), .ec => |ec| return ec.id == other.ec.id and mem.eql(u8, ec.curve_point, other.ec.curve_point), } } }; pub const PrivateKey = PublicKey; pub fn parse_public_key(allocator: *Allocator, reader: anytype) !PublicKey { if ((try reader.readByte()) != 0x30) return error.MalformedDER; const seq_len = try asn1.der.parse_length(reader); if ((try reader.readByte()) != 0x06) return error.MalformedDER; const oid_bytes = try asn1.der.parse_length(reader); if (oid_bytes == 9) { // @TODO This fails in async if merged with the if if (!try reader.isBytes(&[9]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0xD, 0x1, 0x1, 0x1 })) return error.MalformedDER; // OID is 1.2.840.113549.1.1.1 // RSA key // Skip past the NULL const null_byte = try reader.readByte(); if (null_byte != 0x05) return error.MalformedDER; const null_len = try asn1.der.parse_length(reader); if (null_len != 0x00) return error.MalformedDER; { // BitString next! if ((try reader.readByte()) != 0x03) return error.MalformedDER; _ = try asn1.der.parse_length(reader); const bit_string_unused_bits = try reader.readByte(); if (bit_string_unused_bits != 0) return error.MalformedDER; if ((try reader.readByte()) != 0x30) return error.MalformedDER; _ = try asn1.der.parse_length(reader); // Modulus if ((try reader.readByte()) != 0x02) return error.MalformedDER; const modulus = try asn1.der.parse_int(allocator, reader); errdefer allocator.free(modulus.limbs); if (!modulus.positive) return error.MalformedDER; // Exponent if ((try reader.readByte()) != 0x02) return error.MalformedDER; const exponent = try asn1.der.parse_int(allocator, reader); errdefer allocator.free(exponent.limbs); if (!exponent.positive) return error.MalformedDER; return PublicKey{ .rsa = .{ .modulus = modulus.limbs, .exponent = exponent.limbs, }, }; } } else if (oid_bytes == 7) { // @TODO This fails in async if merged with the if if (!try reader.isBytes(&[7]u8{ 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x02, 0x01 })) return error.MalformedDER; // OID is 1.2.840.10045.2.1 // Elliptical curve // We only support named curves, for which the parameter field is an OID. const oid_tag = try reader.readByte(); if (oid_tag != 0x06) return error.MalformedDER; const curve_oid_bytes = try asn1.der.parse_length(reader); var key: PublicKey = undefined; if (curve_oid_bytes == 5) { if (!try reader.isBytes(&[4]u8{ 0x2B, 0x81, 0x04, 0x00 })) return error.MalformedDER; // 172.16.58.3.{34, 35} const last_byte = try reader.readByte(); if (last_byte == 0x22) key = .{ .ec = .{ .id = .secp384r1, .curve_point = undefined } } else if (last_byte == 0x23) key = .{ .ec = .{ .id = .secp521r1, .curve_point = undefined } } else return error.MalformedDER; } else if (curve_oid_bytes == 8) { if (!try reader.isBytes(&[8]u8{ 0x2A, 0x86, 0x48, 0xCE, 0x3D, 0x3, 0x1, 0x7 })) return error.MalformedDER; key = .{ .ec = .{ .id = .secp256r1, .curve_point = undefined } }; } else { return error.MalformedDER; } if ((try reader.readByte()) != 0x03) return error.MalformedDER; const byte_len = try asn1.der.parse_length(reader); const unused_bits = try reader.readByte(); const bit_count = (byte_len - 1) * 8 - unused_bits; if (bit_count % 8 != 0) return error.MalformedDER; const bit_memory = try allocator.alloc(u8, std.math.divCeil(usize, bit_count, 8) catch unreachable); errdefer allocator.free(bit_memory); try reader.readNoEof(bit_memory[0 .. byte_len - 1]); key.ec.curve_point = bit_memory; return key; } return error.MalformedDER; } pub fn DecodeDERError(comptime Reader: type) type { return Reader.Error || error{ MalformedPEM, MalformedDER, EndOfStream, OutOfMemory, }; } pub const Certificate = struct { pub const SignatureAlgorithm = struct { hash: enum(u8) { none = 0, md5 = 1, sha1 = 2, sha224 = 3, sha256 = 4, sha384 = 5, sha512 = 6, }, signature: enum(u8) { anonymous = 0, rsa = 1, dsa = 2, ecdsa = 3, }, }; /// Subject distinguished name dn: []const u8, /// A "CA" anchor is deemed fit to verify signatures on certificates. /// A "non-CA" anchor is accepted only for direct trust (server's certificate /// name and key match the anchor). is_ca: bool = false, public_key: PublicKey, const CaptureState = struct { self: *Certificate, allocator: *Allocator, dn_allocated: bool = false, pk_allocated: bool = false, }; fn initSubjectDn(state: *CaptureState, tag_byte: u8, length: usize, reader: anytype) !void { const dn_mem = try state.allocator.alloc(u8, length); errdefer state.allocator.free(dn_mem); try reader.readNoEof(dn_mem); state.self.dn = dn_mem; state.dn_allocated = true; } fn processExtension(state: *CaptureState, tag_byte: u8, length: usize, reader: anytype) !void { const object_id = try asn1.der.parse_value(state.allocator, reader); defer object_id.deinit(state.allocator); if (object_id != .object_identifier) return error.DoesNotMatchSchema; if (object_id.object_identifier.len != 4) return; const data = object_id.object_identifier.data; // Basic constraints extension if (data[0] != 2 or data[1] != 5 or data[2] != 29 or data[3] != 19) return; const basic_constraints = try asn1.der.parse_value(state.allocator, reader); defer basic_constraints.deinit(state.allocator); switch (basic_constraints) { .bool => |b| state.self.is_ca = true, .octet_string => |s| { if (s.len != 5 or s[0] != 0x30 or s[1] != 0x03 or s[2] != 0x01 or s[3] != 0x01) return error.DoesNotMatchSchema; state.self.is_ca = s[4] != 0x00; }, else => return error.DoesNotMatchSchema, } } fn initExtensions(state: *CaptureState, tag_byte: u8, length: usize, reader: anytype) !void { const schema = .{ .sequence_of, .{ .capture, 0, .sequence }, }; const captures = .{ state, processExtension, }; try asn1.der.parse_schema(schema, captures, reader); } fn initPublicKeyInfo(state: *CaptureState, tag_byte: u8, length: usize, reader: anytype) !void { state.self.public_key = try parse_public_key(state.allocator, reader); state.pk_allocated = true; } /// Initialize a trusted anchor from distinguished encoding rules (DER) encoded data pub fn create(allocator: *Allocator, der_reader: anytype) DecodeDERError(@TypeOf(der_reader))!@This() { var self: @This() = undefined; self.is_ca = false; // https://tools.ietf.org/html/rfc5280#page-117 const schema = .{ .sequence, .{ // tbsCertificate .{ .sequence, .{ .{ .context_specific, 0 }, // version .{.int}, // serialNumber .{.sequence}, // signature .{.sequence}, // issuer .{.sequence}, // validity, .{ .capture, 0, .sequence }, // subject .{ .capture, 1, .sequence }, // subjectPublicKeyInfo .{ .optional, .context_specific, 1 }, // issuerUniqueID .{ .optional, .context_specific, 2 }, // subjectUniqueID .{ .capture, 2, .optional, .context_specific, 3 }, // extensions }, }, // signatureAlgorithm .{.sequence}, // signatureValue .{.bit_string}, }, }; var capture_state = CaptureState{ .self = &self, .allocator = allocator, }; const captures = .{ &capture_state, initSubjectDn, &capture_state, initPublicKeyInfo, &capture_state, initExtensions, }; errdefer { if (capture_state.dn_allocated) allocator.free(self.dn); if (capture_state.pk_allocated) self.public_key.deinit(allocator); } asn1.der.parse_schema(schema, captures, der_reader) catch |err| switch (err) { error.InvalidLength, error.InvalidTag, error.InvalidContainerLength, error.DoesNotMatchSchema, => return error.MalformedDER, else => |e| return e, }; return self; } pub fn deinit(self: @This(), alloc: *Allocator) void { alloc.free(self.dn); self.public_key.deinit(alloc); } pub fn format(self: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.print( \\CERTIFICATE \\----------- \\IS CA: {} \\Subject distinguished name (encoded): \\{X} \\Public key: \\ , .{ self.is_ca, self.dn }); switch (self.public_key) { .rsa => |mod_exp| { const modulus = std.math.big.int.Const{ .positive = true, .limbs = mod_exp.modulus }; const exponent = std.math.big.int.Const{ .positive = true, .limbs = mod_exp.exponent }; try writer.print( \\RSA \\modulus: {} \\exponent: {} \\ , .{ modulus, exponent, }); }, .ec => |ec| { try writer.print( \\EC (Curve: {}) \\point: {} \\ , .{ ec.id, ec.curve_point, }); }, } try writer.writeAll( \\----------- \\ ); } }; pub const CertificateChain = struct { data: std.ArrayList(Certificate), pub fn from_pem(allocator: *Allocator, pem_reader: anytype) DecodeDERError(@TypeOf(pem_reader))!@This() { var self = @This(){ .data = std.ArrayList(Certificate).init(allocator) }; errdefer self.deinit(); var it = pemCertificateIterator(pem_reader); while (try it.next()) |cert_reader| { var buffered = std.io.bufferedReader(cert_reader); const anchor = try Certificate.create(allocator, buffered.reader()); errdefer anchor.deinit(allocator); try self.data.append(anchor); } return self; } pub fn deinit(self: @This()) void { const alloc = self.data.allocator; for (self.data.items) |ta| ta.deinit(alloc); self.data.deinit(); } }; pub fn get_signature_algorithm( reader: anytype, ) (@TypeOf(reader).Error || error{EndOfStream})!?Certificate.SignatureAlgorithm { const oid_tag = try reader.readByte(); if (oid_tag != 0x06) return null; const oid_length = try asn1.der.parse_length(reader); if (oid_length == 9) { var oid_bytes: [9]u8 = undefined; try reader.readNoEof(&oid_bytes); if (mem.eql(u8, &oid_bytes, &[_]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01 })) { // TODO: Is hash actually none here? return Certificate.SignatureAlgorithm{ .signature = .rsa, .hash = .none }; } else if (mem.eql(u8, &oid_bytes, &[_]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x04 })) { return Certificate.SignatureAlgorithm{ .signature = .rsa, .hash = .md5 }; } else if (mem.eql(u8, &oid_bytes, &[_]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x05 })) { return Certificate.SignatureAlgorithm{ .signature = .rsa, .hash = .sha1 }; } else if (mem.eql(u8, &oid_bytes, &[_]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B })) { return Certificate.SignatureAlgorithm{ .signature = .rsa, .hash = .sha256 }; } else if (mem.eql(u8, &oid_bytes, &[_]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0C })) { return Certificate.SignatureAlgorithm{ .signature = .rsa, .hash = .sha384 }; } else if (mem.eql(u8, &oid_bytes, &[_]u8{ 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0D })) { return Certificate.SignatureAlgorithm{ .signature = .rsa, .hash = .sha512 }; } else { return null; } return; } else if (oid_length == 10) { // TODO // ECDSA + <Hash> algorithms } return null; } pub const ClientCertificateChain = struct { /// Number of certificates in the chain cert_len: usize, /// Contains the raw data of each certificate in the certificate chain raw_certs: [*]const []const u8, /// Issuer distinguished name in DER format of each certificate in the certificate chain /// issuer_dn[N] is a dubslice of raw[N] cert_issuer_dns: [*]const []const u8, signature_algorithm: Certificate.SignatureAlgorithm, private_key: PrivateKey, // TODO: Encrypted private keys, non-RSA private keys pub fn from_pem(allocator: *Allocator, pem_reader: anytype) !@This() { var it = PEMSectionIterator(@TypeOf(pem_reader), .{ .section_names = &.{ "X.509 CERTIFICATE", "CERTIFICATE", "RSA PRIVATE KEY", }, .skip_irrelevant_lines = true, }){ .reader = pem_reader }; var raw_certs = std.ArrayListUnmanaged([]const u8){}; var cert_issuer_dns = std.ArrayList([]const u8).init(allocator); errdefer { for (raw_certs.items) |bytes| { allocator.free(bytes); } raw_certs.deinit(allocator); cert_issuer_dns.deinit(); } var signature_algorithm: Certificate.SignatureAlgorithm = undefined; var private_key: ?PrivateKey = null; errdefer if (private_key) |pk| { pk.deinit(allocator); }; while (try it.next()) |state_and_reader| { switch (state_and_reader.state) { .@"X.509 CERTIFICATE", .@"CERTIFICATE" => { const cert_bytes = try state_and_reader.reader.readAllAlloc(allocator, std.math.maxInt(usize)); errdefer allocator.free(cert_bytes); try raw_certs.append(allocator, cert_bytes); const schema = .{ .sequence, .{ // tbsCertificate .{ .sequence, .{ .{ .context_specific, 0 }, // version .{.int}, // serialNumber .{.sequence}, // signature .{ .capture, 0, .sequence }, // issuer .{.sequence}, // validity .{.sequence}, // subject .{.sequence}, // subjectPublicKeyInfo .{ .optional, .context_specific, 1 }, // issuerUniqueID .{ .optional, .context_specific, 2 }, // subjectUniqueID .{ .optional, .context_specific, 3 }, // extensions }, }, // signatureAlgorithm .{ .capture, 1, .sequence }, // signatureValue .{.bit_string}, }, }; var fbs = std.io.fixedBufferStream(cert_bytes); const state = .{ .fbs = &fbs, .dns = &cert_issuer_dns, .signature_algorithm = &signature_algorithm, }; const captures = .{ state, struct { fn capture(_state: anytype, tag: u8, length: usize, reader: anytype) !void { // TODO: Some way to get tag + length buffer directly in the capture callback? const encoded_length = asn1.der.encode_length(length).slice(); const pos = _state.fbs.pos; const dn = _state.fbs.buffer[pos - encoded_length.len - 1 .. pos + length]; try _state.dns.append(dn); } }.capture, state, struct { fn capture(_state: anytype, tag: u8, length: usize, reader: anytype) !void { if (_state.dns.items.len == 1) _state.signature_algorithm.* = (try get_signature_algorithm(reader)) orelse return error.InvalidSignatureAlgorithm; } }.capture, }; asn1.der.parse_schema(schema, captures, fbs.reader()) catch |err| switch (err) { error.DoesNotMatchSchema, error.EndOfStream, error.InvalidTag, error.InvalidLength, error.InvalidSignatureAlgorithm, error.InvalidContainerLength, => return error.InvalidCertificate, error.OutOfMemory => return error.OutOfMemory, }; }, .@"RSA PRIVATE KEY" => { if (private_key != null) return error.MultiplePrivateKeys; const schema = .{ .sequence, .{ .{.int}, // version .{ .capture, 0, .int }, //modulus .{.int}, //publicExponent .{ .capture, 1, .int }, //privateExponent .{.int}, // prime1 .{.int}, //prime2 .{.int}, //exponent1 .{.int}, //exponent2 .{.int}, //coefficient .{ .optional, .any }, //otherPrimeInfos }, }; private_key = .{ .rsa = undefined }; const state = .{ .modulus = &private_key.?.rsa.modulus, .exponent = &private_key.?.rsa.exponent, .allocator = allocator, }; const captures = .{ state, struct { fn capture(_state: anytype, tag: u8, length: usize, reader: anytype) !void { _state.modulus.* = (try asn1.der.parse_int_with_length( _state.allocator, length, reader, )).limbs; } }.capture, state, struct { fn capture(_state: anytype, tag: u8, length: usize, reader: anytype) !void { _state.exponent.* = (try asn1.der.parse_int_with_length( _state.allocator, length, reader, )).limbs; } }.capture, }; asn1.der.parse_schema(schema, captures, state_and_reader.reader) catch |err| switch (err) { error.DoesNotMatchSchema, error.EndOfStream, error.InvalidTag, error.InvalidLength, error.InvalidContainerLength, => return error.InvalidPrivateKey, error.OutOfMemory => return error.OutOfMemory, error.MalformedPEM => return error.MalformedPEM, }; }, .none, .other => unreachable, } } if (private_key == null) return error.NoPrivateKey; std.debug.assert(cert_issuer_dns.items.len == raw_certs.items.len); return @This(){ .cert_len = raw_certs.items.len, .raw_certs = raw_certs.toOwnedSlice(allocator).ptr, .cert_issuer_dns = cert_issuer_dns.toOwnedSlice().ptr, .signature_algorithm = signature_algorithm, .private_key = private_key.?, }; } pub fn deinit(self: *@This(), allocator: *Allocator) void { for (self.raw_certs[0..self.cert_len]) |cert_bytes| { allocator.free(cert_bytes); } allocator.free(self.raw_certs[0..self.cert_len]); allocator.free(self.cert_issuer_dns[0..self.cert_len]); self.private_key.deinit(allocator); } }; fn PEMSectionReader(comptime Reader: type, comptime options: PEMSectionIteratorOptions) type { const Error = Reader.Error || error{MalformedPEM}; const read = struct { fn f(it: *PEMSectionIterator(Reader, options), buf: []u8) Error!usize { var out_idx: usize = 0; if (it.waiting_chars_len > 0) { const rest_written = std.math.min(it.waiting_chars_len, buf.len); while (out_idx < rest_written) : (out_idx += 1) { buf[out_idx] = it.waiting_chars[out_idx]; } it.waiting_chars_len -= rest_written; if (it.waiting_chars_len != 0) { std.mem.copy(u8, it.waiting_chars[0..], it.waiting_chars[rest_written..]); } if (out_idx == buf.len) { return out_idx; } } if (it.state == .none) return out_idx; var base64_buf: [4]u8 = undefined; var base64_idx: usize = 0; while (true) { const byte = it.reader.readByte() catch |err| switch (err) { error.EndOfStream => return out_idx, else => |e| return e, }; if (byte == '-') { if (it.reader.isBytes("----END ") catch |err| switch (err) { error.EndOfStream => return error.MalformedPEM, else => |e| return e, }) { try it.reader.skipUntilDelimiterOrEof('\n'); it.state = .none; return out_idx; } else return error.MalformedPEM; } else if (byte == '\r') { if ((it.reader.readByte() catch |err| switch (err) { error.EndOfStream => return error.MalformedPEM, else => |e| return e, }) != '\n') return error.MalformedPEM; continue; } else if (byte == '\n') continue; base64_buf[base64_idx] = byte; base64_idx += 1; if (base64_idx == base64_buf.len) { base64_idx = 0; const out_len = std.base64.standard_decoder.calcSizeForSlice(&base64_buf) catch return error.MalformedPEM; const rest_chars = if (out_len > buf.len - out_idx) out_len - (buf.len - out_idx) else 0; const buf_chars = out_len - rest_chars; var res_buffer: [3]u8 = undefined; std.base64.standard_decoder.decode(res_buffer[0..out_len], &base64_buf) catch return error.MalformedPEM; var i: u3 = 0; while (i < buf_chars) : (i += 1) { buf[out_idx] = res_buffer[i]; out_idx += 1; } if (rest_chars > 0) { mem.copy(u8, &it.waiting_chars, res_buffer[i..]); it.waiting_chars_len = @intCast(u2, rest_chars); } if (out_idx == buf.len) return out_idx; } } } }.f; return std.io.Reader( *PEMSectionIterator(Reader, options), Error, read, ); } const PEMSectionIteratorOptions = struct { section_names: []const []const u8, skip_irrelevant_lines: bool = false, }; fn PEMSectionIterator(comptime Reader: type, comptime options: PEMSectionIteratorOptions) type { var biggest_name_len = 0; var fields: [options.section_names.len + 2]std.builtin.TypeInfo.EnumField = undefined; fields[0] = .{ .name = "none", .value = 0 }; fields[1] = .{ .name = "other", .value = 1 }; for (fields[2..]) |*field, idx| { field.name = options.section_names[idx]; field.value = @as(u8, idx + 2); if (field.name.len > biggest_name_len) biggest_name_len = field.name.len; } const StateEnum = @Type(.{ .Enum = .{ .layout = .Auto, .tag_type = u8, .fields = &fields, .decls = &.{}, .is_exhaustive = true, }, }); return struct { pub const SectionReader = PEMSectionReader(Reader, options); pub const StateAndName = struct { state: StateEnum, reader: SectionReader, }; pub const NextError = SectionReader.Error || error{EndOfStream}; reader: Reader, // Internal state for the iterator and the current reader. state: StateEnum = .none, waiting_chars: [4]u8 = undefined, waiting_chars_len: u2 = 0, // TODO More verification, this will accept lots of invalid PEM // TODO Simplify code pub fn next(self: *@This()) NextError!?StateAndName { self.waiting_chars_len = 0; outer_loop: while (true) { const byte = self.reader.readByte() catch |err| switch (err) { error.EndOfStream => if (self.state == .none) return null else return error.EndOfStream, else => |e| return e, }; switch (self.state) { .none => switch (byte) { '#' => { try self.reader.skipUntilDelimiterOrEof('\n'); continue; }, '\r', '\n', ' ', '\t' => continue, '-' => { if (try self.reader.isBytes("----BEGIN ")) { var name_char_idx: usize = 0; var name_buf: [biggest_name_len]u8 = undefined; while (true) { const next_byte = try self.reader.readByte(); switch (next_byte) { '-' => { try self.reader.skipUntilDelimiterOrEof('\n'); const name = name_buf[0..name_char_idx]; for (options.section_names) |sec_name, idx| { if (mem.eql(u8, sec_name, name)) { self.state = @intToEnum(StateEnum, @intCast(u8, idx + 2)); return StateAndName{ .reader = .{ .context = self }, .state = self.state, }; } } self.state = .other; continue :outer_loop; }, '\n' => return error.MalformedPEM, else => { if (name_char_idx == biggest_name_len) { try self.reader.skipUntilDelimiterOrEof('\n'); self.state = .other; continue :outer_loop; } name_buf[name_char_idx] = next_byte; name_char_idx += 1; }, } } } else return error.MalformedPEM; }, else => { if (options.skip_irrelevant_lines) { try self.reader.skipUntilDelimiterOrEof('\n'); continue; } else { return error.MalformedPEM; } }, }, else => switch (byte) { '#' => { try self.reader.skipUntilDelimiterOrEof('\n'); continue; }, '\r', '\n', ' ', '\t' => continue, '-' => { if (try self.reader.isBytes("----END ")) { try self.reader.skipUntilDelimiterOrEof('\n'); self.state = .none; continue; } else return error.MalformedPEM; }, // TODO: Make sure the character is base64 else => continue, }, } } } }; } fn PEMCertificateIterator(comptime Reader: type) type { const SectionIterator = PEMSectionIterator(Reader, .{ .section_names = &.{ "X.509 CERTIFICATE", "CERTIFICATE" }, }); return struct { pub const SectionReader = SectionIterator.SectionReader; pub const NextError = SectionReader.Error || error{EndOfStream}; section_it: SectionIterator, pub fn next(self: *@This()) NextError!?SectionReader { return ((try self.section_it.next()) orelse return null).reader; } }; } /// Iterator of io.Reader that each decode one certificate from the PEM reader. /// Readers do not have to be fully consumed until end of stream, but they must be /// read from in order. /// Iterator.SectionReader is the type of the io.Reader, Iterator.NextError is the error /// set of the next() function. pub fn pemCertificateIterator(reader: anytype) PEMCertificateIterator(@TypeOf(reader)) { return .{ .section_it = .{ .reader = reader } }; } pub const NameElement = struct { // Encoded OID without tag oid: asn1.ObjectIdentifier, // Destination buffer buf: []u8, status: enum { not_found, found, errored, }, }; const github_pem = @embedFile("../test/github.pem"); const github_der = @embedFile("../test/github.der"); fn expected_pem_certificate_chain(bytes: []const u8, certs: []const []const u8) !void { var fbs = std.io.fixedBufferStream(bytes); var it = pemCertificateIterator(fbs.reader()); var idx: usize = 0; while (try it.next()) |cert_reader| : (idx += 1) { const result_bytes = try cert_reader.readAllAlloc(std.testing.allocator, std.math.maxInt(usize)); defer std.testing.allocator.free(result_bytes); try std.testing.expectEqualSlices(u8, certs[idx], result_bytes); } if (idx != certs.len) { std.debug.panic("Read {} certificates, wanted {}", .{ idx, certs.len }); } try std.testing.expect((try it.next()) == null); } fn expected_pem_certificate(bytes: []const u8, cert_bytes: []const u8) !void { try expected_pem_certificate_chain(bytes, &[1][]const u8{cert_bytes}); } test "pemCertificateIterator" { try expected_pem_certificate(github_pem, github_der); try expected_pem_certificate( \\-----BEGIN BOGUS----- \\-----END BOGUS----- \\ ++ github_pem, github_der, ); try expected_pem_certificate_chain( github_pem ++ \\ \\-----BEGIN BOGUS----- \\-----END BOGUS----- \\ ++ github_pem, &[2][]const u8{ github_der, github_der }, ); try expected_pem_certificate_chain( \\-----BEGIN BOGUS----- \\-----END BOGUS----- \\ , &[0][]const u8{}, ); // Try reading byte by byte from a cert reader { var fbs = std.io.fixedBufferStream(github_pem ++ "\n# Some comment\n" ++ github_pem); var it = pemCertificateIterator(fbs.reader()); // Read a couple of bytes from the first reader, then skip to the next { const first_reader = (try it.next()) orelse return error.NoCertificate; var first_few: [8]u8 = undefined; const bytes = try first_reader.readAll(&first_few); try std.testing.expectEqual(first_few.len, bytes); try std.testing.expectEqualSlices(u8, github_der[0..bytes], &first_few); } const next_reader = (try it.next()) orelse return error.NoCertificate; var idx: usize = 0; while (true) : (idx += 1) { const byte = next_reader.readByte() catch |err| switch (err) { error.EndOfStream => break, else => |e| return e, }; if (github_der[idx] != byte) { std.debug.panic("index {}: expected 0x{X}, found 0x{X}", .{ idx, github_der[idx], byte }); } } try std.testing.expectEqual(github_der.len, idx); try std.testing.expect((try it.next()) == null); } } test "CertificateChain" { var fbs = std.io.fixedBufferStream(github_pem ++ \\ \\# Hellenic Academic and Research Institutions RootCA 2011 \\-----BEGIN CERTIFICATE----- \\MIIEMTCCAxmgAwIBAgIBADANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMCR1Ix \\<KEY>oTO0hlbGxlbmljIEFjYWRlbWljIGFuZCBSZXNlYXJjaCBJbnN0aXR1 \\dGlvbnMgQ2VydC4gQXV0aG9yaXR5MUAwPgYDVQQDEzdIZWxsZW5pYyBBY2FkZW1p \\YyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25zIFJvb3RDQSAyMDExMB4XDTExMTIw \\NjEzNDk1MloXDTMxMTIwMTEzNDk1MlowgZUxCzAJBgNVBAYTAkdSMUQwQgYDVQQK \\EztIZWxsZW5pYyBBY2FkZW1pYyBhbmQgUmVzZWFyY2ggSW5zdGl0dXRpb25zIENl \\cnQuIEF1dGhvcml0eTFAMD4GA1UEAxM3SGVsbGVuaWMgQWNhZGVtaWMgYW5kIFJl \\c2VhcmNoIEluc3RpdHV0aW9ucyBSb290Q0EgMjAxMTCCASIwDQYJKoZIhvcNAQEB \\BQADggEPADCCAQoCggEBAKlTAOMupvaO+mDYLZU++CwqVE7NuYRhlFhPjz2L5EPz \\dYmNUeTDN9KKiE15HrcS3UN4SoqS5tdI1Q+kOilENbgH9mgdVc04UfCMJDGFr4PJ \\fel3r+0ae50X+bOdOFAPplp5kYCvN66m0zH7tSYJnTxa71HFK9+WXesyHgLacEns \\bgzImjeN9/E2YEsmLIKe0HjzDQ9jpFEw4fkrJxIH2Oq9GGKYsFk3fb7u8yBRQlqD \\75O6aRXxYp2fmTmCobd0LovUxQt7L/DICto9eQqakxylKHJzkUOap9FNhYS5qXSP \\FEDH3N6sQWRstBmbAmNtJGSPRLIl6s5ddAxjMlyNh+UCAwEAAaOBiTCBhjAPBgNV \\HRMBAf8EBTADAQH/MAsGA1UdDwQEAwIBBjAdBgNVHQ4EFgQUppFC/RNhSiOeCKQp <KEY> <KEY> <KEY> \\6z0GW5k6x8zDmjR/qw7IThzh+uTczQ2+vyT+bOdrwg3IBp5OjWEopmr95fZi6hg8 \\TqBTnbI6nOulnJEWtk2C4AwFSKls9cz4y51JtPACpf1wA+2KIaWuE4ZJwzNzvoc7 \\dIsXRSZMFpGD/md9zU1jZ/rzAxKWeAaNsWftjj++n08C9bMJL/NMh98qy5V8Acys \\Nnq/onN694/BtZqhFLKPM58N7yLcZnuEvUUXBj08yrl3NI/K6s8/MT7jiOOASSXI \\l7WdmplNsDz4SgCbZN2fOUvRJ9e4 \\-----END CERTIFICATE----- \\ \\# ePKI Root Certification Authority \\-----BEGIN CERTIFICATE----- \\MIIFsDCCA5igAwIBAgIQFci9ZUdcr7iXAF7kBtK8nTANBgkqhkiG9w0BAQUFADBe \\MQswCQYDVQQGEwJUVzEjMCEGA1UECgwaQ2h1bmdod2EgVGVsZWNvbSBDby4sIEx0 \\ZC4xKjAoBgNVBAsMIWVQS0kgUm9vdCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAe \\Fw0wNDEyMjAwMjMxMjdaFw0zNDEyMjAwMjMxMjdaMF4xCzAJBgNVBAYTAlRXMSMw \\IQYDVQQKDBpDaHVuZ2h3YSBUZWxlY29tIENvLiwgTHRkLjEqMCgGA1UECwwhZVBL \\SSBSb290IENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkqhkiG9w0BAQEF \\AAOCAg8AMIICCgKCAgEA4SUP7o3biDN1Z82tH306Tm2d0y8U82N0ywEhajfqhFAH \\SyZbCUNsIZ5qyNUD9WBpj8zwIuQf5/dqIjG3LBXy4P4AakP/h2XGtRrBp0xtInAh \\ijHyl3SJCRImHJ7K2RKilTza6We/CKBk49ZCt0Xvl/T29de1ShUCWH2YWEtgvM3X \\DZoTM1PRYfl61dd4s5oz9wCGzh1NlDivqOx4UXCKXBCDUSH3ET00hl7lSM2XgYI1 \\TBnsZfZrxQWh7kcT1rMhJ5QQCtkkO7q+RBNGMD+XPNjX12ruOzjjK9SXDrkb5wdJ \\fzcq+Xd4z1TtW0ado4AOkUPB1ltfFLqfpo0kR0BZv3I4sjZsN/+Z0V0OWQqraffA \\sgRFelQArr5T9rXn4fg8ozHSqf4hUmTFpmfwdQcGlBSBVcYn5AGPF8Fqcde+S/uU \\WH1+ETOxQvdibBjWzwloPn9s9h6PYq2lY9sJpx8iQkEeb5mKPtf5P0B6ebClAZLS \\nT0IFaUQAS2zMnaolQ2zepr7BxB4EW/hj8e6DyUadCrlHJhBmd8hh+iVBmoKs2pH \\dmX2Os+PYhcZewoozRrSgx4hxyy/vv9haLdnG7t4TY3OZ+XkwY63I2binZB1NJip \\NiuKmpS5nezMirH4JYlcWrYvjB9teSSnUmjDhDXiZo1jDiVN1Rmy5nk3pyKdVDEC \\AwEAAaNqMGgwHQYDVR0OBBYEFB4M97Zn8uGSJglFwFU5Lnc/QkqiMAwGA1UdEwQF \\MAMBAf8wOQYEZyoHAAQxMC8wLQIBADAJBgUrDgMCGgUAMAcGBWcqAwAABBRFsMLH <KEY> <KEY> <KEY> \\<KEY> \\/<KEY> \\<KEY> \\W9c3rkIO3aQab3yIVMUWbuF6aC74Or8NpDyJO3inTmODBCEIZ43ygknQW/2xzQ+D \\hNQ+IIX3Sj0rnP0qCglN6oH4EZw= \\-----END CERTIFICATE----- ); const chain = try CertificateChain.from_pem(std.testing.allocator, fbs.reader()); defer chain.deinit(); }
src/x509.zig
const std = @import("std"); const builtin = @import("builtin"); const debug = std.debug.print; const daya = @import("daya"); const argparse = @import("argparse.zig"); pub const APP_NAME = "daya"; pub const APP_VERSION = blk: { if (builtin.mode != .Debug) { break :blk @embedFile("../VERSION"); } else { break :blk @embedFile("../VERSION") ++ "-UNRELEASED"; } }; const errors = error { ParseError, CouldNotReadInputFile, CouldNotWriteOutputFile, TooLargeInputFile, ProcessError }; /// Main executable entry point /// Sets up allocator, parses arguments and invokes do() - the main doer. pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const aa = arena.allocator(); const args = try std.process.argsAlloc(aa); defer std.process.argsFree(aa, args); var parsedArgs = argparse.parseArgs(args[1..]) catch |e| switch(e) { error.OkExit => { return; }, else => { debug("Unable to continue. Exiting.\n", .{}); return; } }; do(aa, &parsedArgs) catch |e| switch(e) { errors.CouldNotReadInputFile => { debug("Could not read input-file: {s}\nVerify that the path is correct and that the file is readable.\n", .{parsedArgs.input_file}); }, errors.CouldNotWriteOutputFile => { debug("Could not write to output-file: {s}\n", .{parsedArgs.output_file}); }, errors.ProcessError => { // Compilation-error, previous output should pinpoint the issue. }, else => { debug("DEBUG: Unhandled error: {s}\n", .{e}); } }; } /// pub fn do(allocator: std.mem.Allocator, args: *argparse.AppArgs) errors!void { // v0.1.0: // Generate a .dot anyway: tmp.dot // Att! This makes it not possible to run in parallal for now const TEMPORARY_FILE = "__daya_tmp.dot"; try dayaFileToDotFile(allocator, args.input_file, TEMPORARY_FILE); defer std.fs.cwd().deleteFile(TEMPORARY_FILE) catch |e| { debug("ERROR: Could not delete temporary file '{s}' ({s})\n", .{TEMPORARY_FILE, @errorName(e)}); }; switch(args.output_format) { .dot => { // Copy the temporary file as-is to output-path std.fs.cwd().copyFile(TEMPORARY_FILE, std.fs.cwd(), args.output_file, std.fs.CopyFileOptions{}) catch { debug("ERROR: Could not create output file: {s}\n", .{args.output_file}); }; }, .png, .svg => { // Call external dot to convert callDot(allocator, TEMPORARY_FILE, args.output_file, args.output_format) catch |e| { debug("ERROR: dot failed - {s}\n", .{@errorName(e)}); return errors.ProcessError; }; }, } } /// pub fn dayaFileToDotFile(allocator: std.mem.Allocator, path_daya_input: []const u8, path_dot_output: []const u8) errors!void { // TODO: Set cwd to the folder of the file so any includes are handled relatively to file var input_buffer = std.fs.cwd().readFileAlloc(allocator, path_daya_input, 10*1024*1024) catch |e| switch(e) { error.FileTooBig => return errors.TooLargeInputFile, error.FileNotFound, error.AccessDenied => return errors.CouldNotReadInputFile, else => { debug("ERROR: Got error '{s}' while reading input file '{s}'\n", .{@errorName(e), path_daya_input}); return errors.ProcessError; }, }; defer allocator.free(input_buffer); var file = std.fs.cwd().createFile(path_dot_output, .{ .truncate = true }) catch |e| { debug("ERROR: Got error '{s}' while attempting to create file '{s}'\n", .{@errorName(e), path_dot_output}); return errors.ProcessError; }; errdefer std.fs.cwd().deleteFile(path_dot_output) catch |e| { debug("ERROR: Could not delete temporary file '{s}' ({s})\n", .{path_dot_output, @errorName(e)}); }; defer file.close(); daya.dayaToDot(allocator, std.fs.File.Writer, file.writer(), input_buffer[0..], path_daya_input) catch |e| { debug("ERROR: Got error '{s}' when compiling, see messages above\n", .{@errorName(e)}); return errors.ProcessError; }; } /// Launches a child process to call dot, assumes it's available in path fn callDot(allocator: std.mem.Allocator, input_file: []const u8, output_file: []const u8, output_format: argparse.OutputFormat) !void { var output_file_arg_buf: [1024]u8 = undefined; var output_file_arg = try std.fmt.bufPrint(output_file_arg_buf[0..], "-o{s}", .{output_file}); const result = try std.ChildProcess.exec(.{ .allocator = allocator, .argv = &[_][]const u8{"dot", input_file, output_file_arg, switch(output_format) { .png => "-Tpng", .svg => "-Tsvg", else => unreachable }}, .max_output_bytes = 128, }); var got_error: bool = switch(result.term) { .Stopped => |code| code > 0, .Exited => |code| code > 0, .Signal => true, .Unknown => true, }; if(got_error) { debug("dot returned error: {s}\n", .{result.stderr}); debug("Generate .dot-file instead to debug generated data. This is most likely a bug in daya.", .{}); return error.ProcessError; } defer { allocator.free(result.stderr); allocator.free(result.stdout); } } test { _ = @import("argparse.zig"); }
compiler/src/main.zig
const std = @import("std"); const Image = @import("image.zig").Image; const Allocator = std.mem.Allocator; pub const PngError = error { InvalidHeader, InvalidFilter, UnsupportedFormat }; const ChunkStream = std.io.FixedBufferStream([]u8); // PNG files are made of chunks which have this structure: const Chunk = struct { length: u32, type: []const u8, data: []const u8, stream: ChunkStream, crc: u32, allocator: *Allocator, pub fn deinit(self: *const Chunk) void { self.allocator.free(self.type); self.allocator.free(self.data); } // fancy Zig reflection for basically loading the chunk into a struct // for the experienced: this method is necessary instead of a simple @bitCast because of endianess, as // PNG uses big-endian. pub fn toStruct(self: *Chunk, comptime T: type) T { var result: T = undefined; var reader = self.stream.reader(); inline for (@typeInfo(T).Struct.fields) |field| { const fieldInfo = @typeInfo(field.field_type); switch (fieldInfo) { .Int => { const f = reader.readIntBig(field.field_type) catch unreachable; @field(result, field.name) = f; }, .Enum => |e| { const id = reader.readIntBig(e.tag_type) catch unreachable; @field(result, field.name) = @intToEnum(field.field_type, id); }, else => unreachable } } return result; } }; const ColorType = enum(u8) { Greyscale = 0, Truecolor = 2, IndexedColor = 3, GreyscaleAlpha = 4, TruecolorAlpha = 6 }; const CompressionMethod = enum(u8) { Deflate = 0, }; // Struct for the IHDR chunk, which contains most of metadata about the image. const IHDR = struct { width: u32, height: u32, bitDepth: u8, colorType: ColorType, compressionMethod: CompressionMethod, filterMethod: u8, interlaceMethod: u8 }; fn filterNone(image: []const u8, sample: u8, x: usize, y: usize, width: usize, pos: usize) u8 { return sample; } fn filterSub(image: []const u8, sample: u8, x: usize, y: usize, width: usize, pos: usize) u8 { if (x < 3) { return sample; } else { return sample +% image[pos-3]; } } fn filterUp(image: []const u8, sample: u8, x: usize, y: usize, width: usize, pos: usize) u8 { if (y == 0) { return sample; } else { return sample +% image[pos-width]; } } fn filterAverage(image: []const u8, sample: u8, x: usize, y: usize, width: usize, pos: usize) u8 { var val: u16 = if (x >= 3) image[pos-3] else 0; // val = a if (y > 0) { val += image[pos-width]; // val = a + b } return sample +% @intCast(u8, val / 2); } fn filterPaeth(image: []const u8, sample: u8, x: usize, y: usize, width: usize, pos: usize) u8 { const a: i32 = if (x >= 3) image[pos-3] else 0; const b: i32 = if (y > 0) image[pos-width] else 0; const c: i32 = if (x >= 3 and y > 0) image[pos-width-3] else 0; const p: i32 = a + b - c; // the minimum value of p is -255, minus the minimum value of a/b/c, the minimum result is -510, so using unreachable is safe const pa = std.math.absInt(p - a) catch unreachable; const pb = std.math.absInt(p - b) catch unreachable; const pc = std.math.absInt(p - c) catch unreachable; if (pa <= pb and pa <= pc) { return sample +% @intCast(u8, a); } else if (pb <= pc) { return sample +% @intCast(u8, b); } else { return sample +% @intCast(u8, c); } } fn readChunk(allocator: *Allocator, reader: anytype) !Chunk { const length = try reader.readIntBig(u32); var chunkType = try allocator.alloc(u8, 4); _ = try reader.readAll(chunkType); var data = try allocator.alloc(u8, length); _ = try reader.readAll(data); const crc = try reader.readIntBig(u32); var stream = ChunkStream { .buffer = data, .pos = 0 }; return Chunk { .length = length, .type = chunkType, .data = data, .stream = stream, .crc = crc, .allocator = allocator }; } pub fn read(allocator: *Allocator, path: []const u8) !Image { const file = try std.fs.cwd().openFile(path, .{ .read = true }); const unbufferedReader = file.reader(); var bufferedReader = std.io.BufferedReader(16*1024, @TypeOf(unbufferedReader)) { .unbuffered_reader = unbufferedReader }; const reader = bufferedReader.reader(); var signature = reader.readBytesNoEof(8) catch return error.UnsupportedFormat; if (!std.mem.eql(u8, signature[0..], "\x89PNG\r\n\x1A\n")) { return error.UnsupportedFormat; } var ihdrChunk = try readChunk(allocator, reader); defer ihdrChunk.deinit(); if (!std.mem.eql(u8, ihdrChunk.type, "IHDR")) { return error.InvalidHeader; // first chunk must ALWAYS be IHDR } const ihdr = ihdrChunk.toStruct(IHDR); if (ihdr.filterMethod != 0) { // there's only one filter method declared in the PNG specification // the error falls under InvalidHeader because InvalidFilter is for // the per-scanline filter type. return error.InvalidHeader; } var idatData = try allocator.alloc(u8, 0); defer allocator.free(idatData); while (true) { const chunk = try readChunk(allocator, reader); defer chunk.deinit(); if (std.mem.eql(u8, chunk.type, "IEND")) { break; } else if (std.mem.eql(u8, chunk.type, "IDAT")) { // image data const pos = idatData.len; // in PNG files, there can be multiple IDAT chunks, and their data must all be concatenated. idatData = try allocator.realloc(idatData, idatData.len + chunk.data.len); std.mem.copy(u8, idatData[pos..], chunk.data); } } // the following lines create a zlib stream over our concatenated data from IDAT chunks. var idatStream = std.io.FixedBufferStream([]u8) { .buffer = idatData, .pos = 0 }; var zlibStream = try std.compress.zlib.zlibStream(allocator, idatStream.reader()); defer zlibStream.deinit(); var zlibReader = zlibStream.reader(); const idatReader = (std.io.BufferedReader(16*1024, @TypeOf(zlibReader)) { .unbuffered_reader = zlibReader }).reader(); // allocate image data (TODO: support more than RGB) const imageData = try allocator.alloc(u8, ihdr.width*ihdr.height*3); if (ihdr.colorType == .Truecolor) { var x: u32 = 0; var y: u32 = 0; var pixel: [3]u8 = undefined; const bytesPerLine = ihdr.width * 3; while (y < ihdr.height) { x = 0; // in PNG files, each scanlines have a filter, it is used to have more efficient compression. const filterType = try idatReader.readByte(); const filter = switch (filterType) { 0 => filterNone, 1 => filterSub, 2 => filterUp, 3 => filterAverage, 4 => filterPaeth, else => return error.InvalidFilter }; while (x < bytesPerLine) { const pos = y*bytesPerLine + x; _ = try idatReader.readAll(&pixel); imageData[pos] = filter(imageData, pixel[0], x, y, bytesPerLine, pos); imageData[pos+1] = filter(imageData, pixel[1], x+1, y, bytesPerLine, pos+1); imageData[pos+2] = filter(imageData, pixel[2], x+2, y, bytesPerLine, pos+2); x += 3; // since we use 3 bytes per pixel, let's directly increment X by 3 // (that optimisation is also useful in the filter method) } y += 1; } return Image { .allocator = allocator, .data = imageData, .width = ihdr.width, .height = ihdr.height, .format = .RGB24 }; } else { return PngError.UnsupportedFormat; } }
didot-image/png.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day05.txt"); const Line = struct { x1: u32, y1: u32, x2: u32, y2: u32, }; pub fn main() !void { const lines: []Line = blk: { var iter_lines = tokenize(u8, data, "\n\r"); var list = std.ArrayList(Line).init(gpa); while (iter_lines.next()) |s| { var iter_nums = tokenize(u8, s, ", ->"); var line: Line = undefined; line.x1 = try parseInt(u32, iter_nums.next().?, 10); line.y1 = try parseInt(u32, iter_nums.next().?, 10); line.x2 = try parseInt(u32, iter_nums.next().?, 10); line.y2 = try parseInt(u32, iter_nums.next().?, 10); try list.append(line); } break :blk list.toOwnedSlice(); }; // only consider lines where x1==x2 or y1==y2 const axial_lines: []Line = blk: { var list = std.ArrayList(Line).init(gpa); for (lines) |line| { if (line.x1==line.x2 or line.y1==line.y2) { try list.append(line); } } break :blk list.toOwnedSlice(); }; { // Part 1 var coverage = [_][991]u8{[_]u8{0}**991}**991; for (axial_lines) |line| { if (line.x1 == line.x2) { var y: usize = min(line.y1, line.y2); while (y <= max(line.y1, line.y2)) : (y += 1) { coverage[line.x1][y] += 1; } } else if (line.y1 == line.y2) { var x: usize = min(line.x1, line.x2); while (x <= max(line.x1, line.x2)) : (x += 1) { coverage[x][line.y1] += 1; } } else unreachable; } var count: u32 = 0; for (coverage) |row| { for (row) |val| { if (val >= 2) { count += 1; } } } print("{d}\n", .{count}); } { // Part 2 var coverage = [_][991]u8{[_]u8{0}**991}**991; for (lines) |line| { if (line.x1 == line.x2) { var y: usize = min(line.y1, line.y2); while (y <= max(line.y1, line.y2)) : (y += 1) { coverage[line.x1][y] += 1; } } else if (line.y1 == line.y2) { var x: usize = min(line.x1, line.x2); while (x <= max(line.x1, line.x2)) : (x += 1) { coverage[x][line.y1] += 1; } } else { var x: usize = line.x1; var y: usize = line.y1; while (true) { coverage[x][y] += 1; if (x == line.x2) { assert(y == line.y2); break; } x = if (line.x1 < line.x2) x+1 else x-1; y = if (line.y1 < line.y2) y+1 else y-1; } } } var count: u32 = 0; for (coverage) |row| { for (row) |val| { if (val >= 2) { count += 1; } } } print("{d}\n", .{count}); } } // 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/day05.zig
pub const USB_PRINTER_INTERFACE_CLASSIC = @as(u32, 1); pub const USB_PRINTER_INTERFACE_IPP = @as(u32, 2); pub const USB_PRINTER_INTERFACE_DUAL = @as(u32, 3); pub const USBPRINT_IOCTL_INDEX = @as(u32, 0); pub const IOCTL_USBPRINT_GET_LPT_STATUS = @as(u32, 2228272); pub const IOCTL_USBPRINT_GET_1284_ID = @as(u32, 2228276); pub const IOCTL_USBPRINT_VENDOR_SET_COMMAND = @as(u32, 2228280); pub const IOCTL_USBPRINT_VENDOR_GET_COMMAND = @as(u32, 2228284); pub const IOCTL_USBPRINT_SOFT_RESET = @as(u32, 2228288); pub const IOCTL_USBPRINT_GET_PROTOCOL = @as(u32, 2228292); pub const IOCTL_USBPRINT_SET_PROTOCOL = @as(u32, 2228296); pub const IOCTL_USBPRINT_GET_INTERFACE_TYPE = @as(u32, 2228300); pub const IOCTL_USBPRINT_SET_PORT_NUMBER = @as(u32, 2228304); pub const IOCTL_USBPRINT_ADD_MSIPP_COMPAT_ID = @as(u32, 2228308); pub const IOCTL_USBPRINT_SET_DEVICE_ID = @as(u32, 2228312); pub const IOCTL_USBPRINT_ADD_CHILD_DEVICE = @as(u32, 2228316); pub const IOCTL_USBPRINT_CYCLE_PORT = @as(u32, 2228320); pub const TVOT_2STATES = @as(u32, 0); pub const TVOT_3STATES = @as(u32, 1); pub const TVOT_UDARROW = @as(u32, 2); pub const TVOT_TRACKBAR = @as(u32, 3); pub const TVOT_SCROLLBAR = @as(u32, 4); pub const TVOT_LISTBOX = @as(u32, 5); pub const TVOT_COMBOBOX = @as(u32, 6); pub const TVOT_EDITBOX = @as(u32, 7); pub const TVOT_PUSHBUTTON = @as(u32, 8); pub const TVOT_CHKBOX = @as(u32, 9); pub const TVOT_NSTATES_EX = @as(u32, 10); pub const CHKBOXS_FALSE_TRUE = @as(u32, 0); pub const CHKBOXS_NO_YES = @as(u32, 1); pub const CHKBOXS_OFF_ON = @as(u32, 2); pub const CHKBOXS_FALSE_PDATA = @as(u32, 3); pub const CHKBOXS_NO_PDATA = @as(u32, 4); pub const CHKBOXS_OFF_PDATA = @as(u32, 5); pub const CHKBOXS_NONE_PDATA = @as(u32, 6); pub const PUSHBUTTON_TYPE_DLGPROC = @as(u32, 0); pub const PUSHBUTTON_TYPE_CALLBACK = @as(u32, 1); pub const PUSHBUTTON_TYPE_HTCLRADJ = @as(u32, 2); pub const PUSHBUTTON_TYPE_HTSETUP = @as(u32, 3); pub const MAX_RES_STR_CHARS = @as(u32, 160); pub const OPTPF_HIDE = @as(u32, 1); pub const OPTPF_DISABLED = @as(u32, 2); pub const OPTPF_ICONID_AS_HICON = @as(u32, 4); pub const OPTPF_OVERLAY_WARNING_ICON = @as(u32, 8); pub const OPTPF_OVERLAY_STOP_ICON = @as(u32, 16); pub const OPTPF_OVERLAY_NO_ICON = @as(u32, 32); pub const OPTPF_USE_HDLGTEMPLATE = @as(u32, 64); pub const OPTPF_MASK = @as(u32, 127); pub const OPTCF_HIDE = @as(u32, 1); pub const OPTCF_MASK = @as(u32, 1); pub const OPTTF_TYPE_DISABLED = @as(u32, 1); pub const OPTTF_NOSPACE_BEFORE_POSTFIX = @as(u32, 2); pub const OPTTF_MASK = @as(u32, 3); pub const OTS_LBCB_SORT = @as(u32, 1); pub const OTS_LBCB_PROPPAGE_LBUSECB = @as(u32, 2); pub const OTS_LBCB_PROPPAGE_CBUSELB = @as(u32, 4); pub const OTS_LBCB_INCL_ITEM_NONE = @as(u32, 8); pub const OTS_LBCB_NO_ICON16_IN_ITEM = @as(u32, 16); pub const OTS_PUSH_INCL_SETUP_TITLE = @as(u32, 32); pub const OTS_PUSH_NO_DOT_DOT_DOT = @as(u32, 64); pub const OTS_PUSH_ENABLE_ALWAYS = @as(u32, 128); pub const OTS_MASK = @as(u32, 255); pub const EPF_PUSH_TYPE_DLGPROC = @as(u32, 1); pub const EPF_INCL_SETUP_TITLE = @as(u32, 2); pub const EPF_NO_DOT_DOT_DOT = @as(u32, 4); pub const EPF_ICONID_AS_HICON = @as(u32, 8); pub const EPF_OVERLAY_WARNING_ICON = @as(u32, 16); pub const EPF_OVERLAY_STOP_ICON = @as(u32, 32); pub const EPF_OVERLAY_NO_ICON = @as(u32, 64); pub const EPF_USE_HDLGTEMPLATE = @as(u32, 128); pub const EPF_MASK = @as(u32, 255); pub const ECBF_CHECKNAME_AT_FRONT = @as(u32, 1); pub const ECBF_CHECKNAME_ONLY_ENABLED = @as(u32, 2); pub const ECBF_ICONID_AS_HICON = @as(u32, 4); pub const ECBF_OVERLAY_WARNING_ICON = @as(u32, 8); pub const ECBF_OVERLAY_ECBICON_IF_CHECKED = @as(u32, 16); pub const ECBF_OVERLAY_STOP_ICON = @as(u32, 32); pub const ECBF_OVERLAY_NO_ICON = @as(u32, 64); pub const ECBF_CHECKNAME_ONLY = @as(u32, 128); pub const ECBF_MASK = @as(u32, 255); pub const OPTIF_COLLAPSE = @as(i32, 1); pub const OPTIF_HIDE = @as(i32, 2); pub const OPTIF_CALLBACK = @as(i32, 4); pub const OPTIF_CHANGED = @as(i32, 8); pub const OPTIF_CHANGEONCE = @as(i32, 16); pub const OPTIF_DISABLED = @as(i32, 32); pub const OPTIF_ECB_CHECKED = @as(i32, 64); pub const OPTIF_EXT_HIDE = @as(i32, 128); pub const OPTIF_EXT_DISABLED = @as(i32, 256); pub const OPTIF_SEL_AS_HICON = @as(i32, 512); pub const OPTIF_EXT_IS_EXTPUSH = @as(i32, 1024); pub const OPTIF_NO_GROUPBOX_NAME = @as(i32, 2048); pub const OPTIF_OVERLAY_WARNING_ICON = @as(i32, 4096); pub const OPTIF_OVERLAY_STOP_ICON = @as(i32, 8192); pub const OPTIF_OVERLAY_NO_ICON = @as(i32, 16384); pub const OPTIF_INITIAL_TVITEM = @as(i32, 32768); pub const OPTIF_HAS_POIEXT = @as(i32, 65536); pub const OPTIF_MASK = @as(i32, 131071); pub const DMPUB_NONE = @as(u32, 0); pub const DMPUB_FIRST = @as(u32, 1); pub const DMPUB_ORIENTATION = @as(u32, 1); pub const DMPUB_SCALE = @as(u32, 2); pub const DMPUB_COPIES_COLLATE = @as(u32, 3); pub const DMPUB_DEFSOURCE = @as(u32, 4); pub const DMPUB_PRINTQUALITY = @as(u32, 5); pub const DMPUB_COLOR = @as(u32, 6); pub const DMPUB_DUPLEX = @as(u32, 7); pub const DMPUB_TTOPTION = @as(u32, 8); pub const DMPUB_FORMNAME = @as(u32, 9); pub const DMPUB_ICMMETHOD = @as(u32, 10); pub const DMPUB_ICMINTENT = @as(u32, 11); pub const DMPUB_MEDIATYPE = @as(u32, 12); pub const DMPUB_DITHERTYPE = @as(u32, 13); pub const DMPUB_OUTPUTBIN = @as(u32, 14); pub const DMPUB_QUALITY = @as(u32, 15); pub const DMPUB_NUP = @as(u32, 16); pub const DMPUB_PAGEORDER = @as(u32, 17); pub const DMPUB_NUP_DIRECTION = @as(u32, 18); pub const DMPUB_MANUAL_DUPLEX = @as(u32, 19); pub const DMPUB_STAPLE = @as(u32, 20); pub const DMPUB_BOOKLET_EDGE = @as(u32, 21); pub const DMPUB_LAST = @as(u32, 21); pub const DMPUB_OEM_PAPER_ITEM = @as(u32, 97); pub const DMPUB_OEM_GRAPHIC_ITEM = @as(u32, 98); pub const DMPUB_OEM_ROOT_ITEM = @as(u32, 99); pub const DMPUB_USER = @as(u32, 100); pub const OIEXTF_ANSI_STRING = @as(u32, 1); pub const CPSUICB_REASON_SEL_CHANGED = @as(u32, 0); pub const CPSUICB_REASON_PUSHBUTTON = @as(u32, 1); pub const CPSUICB_REASON_ECB_CHANGED = @as(u32, 2); pub const CPSUICB_REASON_DLGPROC = @as(u32, 3); pub const CPSUICB_REASON_UNDO_CHANGES = @as(u32, 4); pub const CPSUICB_REASON_EXTPUSH = @as(u32, 5); pub const CPSUICB_REASON_APPLYNOW = @as(u32, 6); pub const CPSUICB_REASON_OPTITEM_SETFOCUS = @as(u32, 7); pub const CPSUICB_REASON_ITEMS_REVERTED = @as(u32, 8); pub const CPSUICB_REASON_ABOUT = @as(u32, 9); pub const CPSUICB_REASON_SETACTIVE = @as(u32, 10); pub const CPSUICB_REASON_KILLACTIVE = @as(u32, 11); pub const CPSUICB_ACTION_NONE = @as(u32, 0); pub const CPSUICB_ACTION_OPTIF_CHANGED = @as(u32, 1); pub const CPSUICB_ACTION_REINIT_ITEMS = @as(u32, 2); pub const CPSUICB_ACTION_NO_APPLY_EXIT = @as(u32, 3); pub const CPSUICB_ACTION_ITEMS_APPLIED = @as(u32, 4); pub const DP_STD_TREEVIEWPAGE = @as(u32, 65535); pub const DP_STD_DOCPROPPAGE2 = @as(u32, 65534); pub const DP_STD_DOCPROPPAGE1 = @as(u32, 65533); pub const DP_STD_RESERVED_START = @as(u32, 65520); pub const MAX_DLGPAGE_COUNT = @as(u32, 64); pub const DPF_ICONID_AS_HICON = @as(u32, 1); pub const DPF_USE_HDLGTEMPLATE = @as(u32, 2); pub const CPSUIF_UPDATE_PERMISSION = @as(u32, 1); pub const CPSUIF_ICONID_AS_HICON = @as(u32, 2); pub const CPSUIF_ABOUT_CALLBACK = @as(u32, 4); pub const CPSFUNC_ADD_HPROPSHEETPAGE = @as(u32, 0); pub const CPSFUNC_ADD_PROPSHEETPAGEW = @as(u32, 1); pub const CPSFUNC_ADD_PCOMPROPSHEETUIA = @as(u32, 2); pub const CPSFUNC_ADD_PCOMPROPSHEETUIW = @as(u32, 3); pub const CPSFUNC_ADD_PFNPROPSHEETUIA = @as(u32, 4); pub const CPSFUNC_ADD_PFNPROPSHEETUIW = @as(u32, 5); pub const CPSFUNC_DELETE_HCOMPROPSHEET = @as(u32, 6); pub const CPSFUNC_SET_HSTARTPAGE = @as(u32, 7); pub const CPSFUNC_GET_PAGECOUNT = @as(u32, 8); pub const CPSFUNC_SET_RESULT = @as(u32, 9); pub const CPSFUNC_GET_HPSUIPAGES = @as(u32, 10); pub const CPSFUNC_LOAD_CPSUI_STRINGA = @as(u32, 11); pub const CPSFUNC_LOAD_CPSUI_STRINGW = @as(u32, 12); pub const CPSFUNC_LOAD_CPSUI_ICON = @as(u32, 13); pub const CPSFUNC_GET_PFNPROPSHEETUI_ICON = @as(u32, 14); pub const CPSFUNC_ADD_PROPSHEETPAGEA = @as(u32, 15); pub const CPSFUNC_INSERT_PSUIPAGEA = @as(u32, 16); pub const CPSFUNC_INSERT_PSUIPAGEW = @as(u32, 17); pub const CPSFUNC_SET_PSUIPAGE_TITLEA = @as(u32, 18); pub const CPSFUNC_SET_PSUIPAGE_TITLEW = @as(u32, 19); pub const CPSFUNC_SET_PSUIPAGE_ICON = @as(u32, 20); pub const CPSFUNC_SET_DATABLOCK = @as(u32, 21); pub const CPSFUNC_QUERY_DATABLOCK = @as(u32, 22); pub const CPSFUNC_SET_DMPUB_HIDEBITS = @as(u32, 23); pub const CPSFUNC_IGNORE_CPSUI_PSN_APPLY = @as(u32, 24); pub const CPSFUNC_DO_APPLY_CPSUI = @as(u32, 25); pub const CPSFUNC_SET_FUSION_CONTEXT = @as(u32, 26); pub const MAX_CPSFUNC_INDEX = @as(u32, 26); pub const CPSFUNC_ADD_PCOMPROPSHEETUI = @as(u32, 3); pub const CPSFUNC_ADD_PFNPROPSHEETUI = @as(u32, 5); pub const CPSFUNC_LOAD_CPSUI_STRING = @as(u32, 12); pub const CPSFUNC_ADD_PROPSHEETPAGE = @as(u32, 1); pub const CPSFUNC_INSERT_PSUIPAGE = @as(u32, 17); pub const CPSFUNC_SET_PSUIPAGE_TITLE = @as(u32, 19); pub const SR_OWNER = @as(u32, 0); pub const SR_OWNER_PARENT = @as(u32, 1); pub const PSUIPAGEINSERT_GROUP_PARENT = @as(u32, 0); pub const PSUIPAGEINSERT_PCOMPROPSHEETUI = @as(u32, 1); pub const PSUIPAGEINSERT_PFNPROPSHEETUI = @as(u32, 2); pub const PSUIPAGEINSERT_PROPSHEETPAGE = @as(u32, 3); pub const PSUIPAGEINSERT_HPROPSHEETPAGE = @as(u32, 4); pub const PSUIPAGEINSERT_DLL = @as(u32, 5); pub const MAX_PSUIPAGEINSERT_INDEX = @as(u32, 5); pub const INSPSUIPAGE_MODE_BEFORE = @as(u32, 0); pub const INSPSUIPAGE_MODE_AFTER = @as(u32, 1); pub const INSPSUIPAGE_MODE_FIRST_CHILD = @as(u32, 2); pub const INSPSUIPAGE_MODE_LAST_CHILD = @as(u32, 3); pub const INSPSUIPAGE_MODE_INDEX = @as(u32, 4); pub const SSP_TVPAGE = @as(u32, 10000); pub const SSP_STDPAGE1 = @as(u32, 10001); pub const SSP_STDPAGE2 = @as(u32, 10002); pub const APPLYCPSUI_NO_NEWDEF = @as(u32, 1); pub const APPLYCPSUI_OK_CANCEL_BUTTON = @as(u32, 2); pub const PROPSHEETUI_REASON_INIT = @as(u32, 0); pub const PROPSHEETUI_REASON_GET_INFO_HEADER = @as(u32, 1); pub const PROPSHEETUI_REASON_DESTROY = @as(u32, 2); pub const PROPSHEETUI_REASON_SET_RESULT = @as(u32, 3); pub const PROPSHEETUI_REASON_GET_ICON = @as(u32, 4); pub const PROPSHEETUI_REASON_BEFORE_INIT = @as(u32, 5); pub const MAX_PROPSHEETUI_REASON_INDEX = @as(u32, 5); pub const PROPSHEETUI_INFO_VERSION = @as(u32, 256); pub const PSUIINFO_UNICODE = @as(u32, 1); pub const PSUIHDRF_OBSOLETE = @as(u32, 1); pub const PSUIHDRF_NOAPPLYNOW = @as(u32, 2); pub const PSUIHDRF_PROPTITLE = @as(u32, 4); pub const PSUIHDRF_USEHICON = @as(u32, 8); pub const PSUIHDRF_DEFTITLE = @as(u32, 16); pub const PSUIHDRF_EXACT_PTITLE = @as(u32, 32); pub const CPSUI_CANCEL = @as(u32, 0); pub const CPSUI_OK = @as(u32, 1); pub const CPSUI_RESTARTWINDOWS = @as(u32, 2); pub const CPSUI_REBOOTSYSTEM = @as(u32, 3); pub const ERR_CPSUI_GETLASTERROR = @as(i32, -1); pub const ERR_CPSUI_ALLOCMEM_FAILED = @as(i32, -2); pub const ERR_CPSUI_INVALID_PDATA = @as(i32, -3); pub const ERR_CPSUI_INVALID_LPARAM = @as(i32, -4); pub const ERR_CPSUI_NULL_HINST = @as(i32, -5); pub const ERR_CPSUI_NULL_CALLERNAME = @as(i32, -6); pub const ERR_CPSUI_NULL_OPTITEMNAME = @as(i32, -7); pub const ERR_CPSUI_NO_PROPSHEETPAGE = @as(i32, -8); pub const ERR_CPSUI_TOO_MANY_PROPSHEETPAGES = @as(i32, -9); pub const ERR_CPSUI_CREATEPROPPAGE_FAILED = @as(i32, -10); pub const ERR_CPSUI_MORE_THAN_ONE_TVPAGE = @as(i32, -11); pub const ERR_CPSUI_MORE_THAN_ONE_STDPAGE = @as(i32, -12); pub const ERR_CPSUI_INVALID_PDLGPAGE = @as(i32, -13); pub const ERR_CPSUI_INVALID_DLGPAGE_CBSIZE = @as(i32, -14); pub const ERR_CPSUI_TOO_MANY_DLGPAGES = @as(i32, -15); pub const ERR_CPSUI_INVALID_DLGPAGEIDX = @as(i32, -16); pub const ERR_CPSUI_SUBITEM_DIFF_DLGPAGEIDX = @as(i32, -17); pub const ERR_CPSUI_NULL_POPTITEM = @as(i32, -18); pub const ERR_CPSUI_INVALID_OPTITEM_CBSIZE = @as(i32, -19); pub const ERR_CPSUI_INVALID_OPTTYPE_CBSIZE = @as(i32, -20); pub const ERR_CPSUI_INVALID_OPTTYPE_COUNT = @as(i32, -21); pub const ERR_CPSUI_NULL_POPTPARAM = @as(i32, -22); pub const ERR_CPSUI_INVALID_OPTPARAM_CBSIZE = @as(i32, -23); pub const ERR_CPSUI_INVALID_EDITBOX_PSEL = @as(i32, -24); pub const ERR_CPSUI_INVALID_EDITBOX_BUF_SIZE = @as(i32, -25); pub const ERR_CPSUI_INVALID_ECB_CBSIZE = @as(i32, -26); pub const ERR_CPSUI_NULL_ECB_PTITLE = @as(i32, -27); pub const ERR_CPSUI_NULL_ECB_PCHECKEDNAME = @as(i32, -28); pub const ERR_CPSUI_INVALID_DMPUBID = @as(i32, -29); pub const ERR_CPSUI_INVALID_DMPUB_TVOT = @as(i32, -30); pub const ERR_CPSUI_CREATE_TRACKBAR_FAILED = @as(i32, -31); pub const ERR_CPSUI_CREATE_UDARROW_FAILED = @as(i32, -32); pub const ERR_CPSUI_CREATE_IMAGELIST_FAILED = @as(i32, -33); pub const ERR_CPSUI_INVALID_TVOT_TYPE = @as(i32, -34); pub const ERR_CPSUI_INVALID_LBCB_TYPE = @as(i32, -35); pub const ERR_CPSUI_SUBITEM_DIFF_OPTIF_HIDE = @as(i32, -36); pub const ERR_CPSUI_INVALID_PUSHBUTTON_TYPE = @as(i32, -38); pub const ERR_CPSUI_INVALID_EXTPUSH_CBSIZE = @as(i32, -39); pub const ERR_CPSUI_NULL_EXTPUSH_DLGPROC = @as(i32, -40); pub const ERR_CPSUI_NO_EXTPUSH_DLGTEMPLATEID = @as(i32, -41); pub const ERR_CPSUI_NULL_EXTPUSH_CALLBACK = @as(i32, -42); pub const ERR_CPSUI_DMCOPIES_USE_EXTPUSH = @as(i32, -43); pub const ERR_CPSUI_ZERO_OPTITEM = @as(i32, -44); pub const ERR_CPSUI_FUNCTION_NOT_IMPLEMENTED = @as(i32, -9999); pub const ERR_CPSUI_INTERNAL_ERROR = @as(i32, -10000); pub const IDI_CPSUI_ICONID_FIRST = @as(u32, 64000); pub const IDI_CPSUI_EMPTY = @as(u32, 64000); pub const IDI_CPSUI_SEL_NONE = @as(u32, 64001); pub const IDI_CPSUI_WARNING = @as(u32, 64002); pub const IDI_CPSUI_NO = @as(u32, 64003); pub const IDI_CPSUI_YES = @as(u32, 64004); pub const IDI_CPSUI_FALSE = @as(u32, 64005); pub const IDI_CPSUI_TRUE = @as(u32, 64006); pub const IDI_CPSUI_OFF = @as(u32, 64007); pub const IDI_CPSUI_ON = @as(u32, 64008); pub const IDI_CPSUI_PAPER_OUTPUT = @as(u32, 64009); pub const IDI_CPSUI_ENVELOPE = @as(u32, 64010); pub const IDI_CPSUI_MEM = @as(u32, 64011); pub const IDI_CPSUI_FONTCARTHDR = @as(u32, 64012); pub const IDI_CPSUI_FONTCART = @as(u32, 64013); pub const IDI_CPSUI_STAPLER_ON = @as(u32, 64014); pub const IDI_CPSUI_STAPLER_OFF = @as(u32, 64015); pub const IDI_CPSUI_HT_HOST = @as(u32, 64016); pub const IDI_CPSUI_HT_DEVICE = @as(u32, 64017); pub const IDI_CPSUI_TT_PRINTASGRAPHIC = @as(u32, 64018); pub const IDI_CPSUI_TT_DOWNLOADSOFT = @as(u32, 64019); pub const IDI_CPSUI_TT_DOWNLOADVECT = @as(u32, 64020); pub const IDI_CPSUI_TT_SUBDEV = @as(u32, 64021); pub const IDI_CPSUI_PORTRAIT = @as(u32, 64022); pub const IDI_CPSUI_LANDSCAPE = @as(u32, 64023); pub const IDI_CPSUI_ROT_LAND = @as(u32, 64024); pub const IDI_CPSUI_AUTOSEL = @as(u32, 64025); pub const IDI_CPSUI_PAPER_TRAY = @as(u32, 64026); pub const IDI_CPSUI_PAPER_TRAY2 = @as(u32, 64027); pub const IDI_CPSUI_PAPER_TRAY3 = @as(u32, 64028); pub const IDI_CPSUI_TRANSPARENT = @as(u32, 64029); pub const IDI_CPSUI_COLLATE = @as(u32, 64030); pub const IDI_CPSUI_DUPLEX_NONE = @as(u32, 64031); pub const IDI_CPSUI_DUPLEX_HORZ = @as(u32, 64032); pub const IDI_CPSUI_DUPLEX_VERT = @as(u32, 64033); pub const IDI_CPSUI_RES_DRAFT = @as(u32, 64034); pub const IDI_CPSUI_RES_LOW = @as(u32, 64035); pub const IDI_CPSUI_RES_MEDIUM = @as(u32, 64036); pub const IDI_CPSUI_RES_HIGH = @as(u32, 64037); pub const IDI_CPSUI_RES_PRESENTATION = @as(u32, 64038); pub const IDI_CPSUI_MONO = @as(u32, 64039); pub const IDI_CPSUI_COLOR = @as(u32, 64040); pub const IDI_CPSUI_DITHER_NONE = @as(u32, 64041); pub const IDI_CPSUI_DITHER_COARSE = @as(u32, 64042); pub const IDI_CPSUI_DITHER_FINE = @as(u32, 64043); pub const IDI_CPSUI_DITHER_LINEART = @as(u32, 64044); pub const IDI_CPSUI_SCALING = @as(u32, 64045); pub const IDI_CPSUI_COPY = @as(u32, 64046); pub const IDI_CPSUI_HTCLRADJ = @as(u32, 64047); pub const IDI_CPSUI_HALFTONE_SETUP = @as(u32, 64048); pub const IDI_CPSUI_WATERMARK = @as(u32, 64049); pub const IDI_CPSUI_ERROR = @as(u32, 64050); pub const IDI_CPSUI_ICM_OPTION = @as(u32, 64051); pub const IDI_CPSUI_ICM_METHOD = @as(u32, 64052); pub const IDI_CPSUI_ICM_INTENT = @as(u32, 64053); pub const IDI_CPSUI_STD_FORM = @as(u32, 64054); pub const IDI_CPSUI_OUTBIN = @as(u32, 64055); pub const IDI_CPSUI_OUTPUT = @as(u32, 64056); pub const IDI_CPSUI_GRAPHIC = @as(u32, 64057); pub const IDI_CPSUI_ADVANCE = @as(u32, 64058); pub const IDI_CPSUI_DOCUMENT = @as(u32, 64059); pub const IDI_CPSUI_DEVICE = @as(u32, 64060); pub const IDI_CPSUI_DEVICE2 = @as(u32, 64061); pub const IDI_CPSUI_PRINTER = @as(u32, 64062); pub const IDI_CPSUI_PRINTER2 = @as(u32, 64063); pub const IDI_CPSUI_PRINTER3 = @as(u32, 64064); pub const IDI_CPSUI_PRINTER4 = @as(u32, 64065); pub const IDI_CPSUI_OPTION = @as(u32, 64066); pub const IDI_CPSUI_OPTION2 = @as(u32, 64067); pub const IDI_CPSUI_STOP = @as(u32, 64068); pub const IDI_CPSUI_NOTINSTALLED = @as(u32, 64069); pub const IDI_CPSUI_WARNING_OVERLAY = @as(u32, 64070); pub const IDI_CPSUI_STOP_WARNING_OVERLAY = @as(u32, 64071); pub const IDI_CPSUI_GENERIC_OPTION = @as(u32, 64072); pub const IDI_CPSUI_GENERIC_ITEM = @as(u32, 64073); pub const IDI_CPSUI_RUN_DIALOG = @as(u32, 64074); pub const IDI_CPSUI_QUESTION = @as(u32, 64075); pub const IDI_CPSUI_FORMTRAYASSIGN = @as(u32, 64076); pub const IDI_CPSUI_PRINTER_FOLDER = @as(u32, 64077); pub const IDI_CPSUI_INSTALLABLE_OPTION = @as(u32, 64078); pub const IDI_CPSUI_PRINTER_FEATURE = @as(u32, 64079); pub const IDI_CPSUI_DEVICE_FEATURE = @as(u32, 64080); pub const IDI_CPSUI_FONTSUB = @as(u32, 64081); pub const IDI_CPSUI_POSTSCRIPT = @as(u32, 64082); pub const IDI_CPSUI_TELEPHONE = @as(u32, 64083); pub const IDI_CPSUI_DUPLEX_NONE_L = @as(u32, 64084); pub const IDI_CPSUI_DUPLEX_HORZ_L = @as(u32, 64085); pub const IDI_CPSUI_DUPLEX_VERT_L = @as(u32, 64086); pub const IDI_CPSUI_LF_PEN_PLOTTER = @as(u32, 64087); pub const IDI_CPSUI_SF_PEN_PLOTTER = @as(u32, 64088); pub const IDI_CPSUI_LF_RASTER_PLOTTER = @as(u32, 64089); pub const IDI_CPSUI_SF_RASTER_PLOTTER = @as(u32, 64090); pub const IDI_CPSUI_ROLL_PAPER = @as(u32, 64091); pub const IDI_CPSUI_PEN_CARROUSEL = @as(u32, 64092); pub const IDI_CPSUI_PLOTTER_PEN = @as(u32, 64093); pub const IDI_CPSUI_MANUAL_FEED = @as(u32, 64094); pub const IDI_CPSUI_FAX = @as(u32, 64095); pub const IDI_CPSUI_PAGE_PROTECT = @as(u32, 64096); pub const IDI_CPSUI_ENVELOPE_FEED = @as(u32, 64097); pub const IDI_CPSUI_FONTCART_SLOT = @as(u32, 64098); pub const IDI_CPSUI_LAYOUT_BMP_PORTRAIT = @as(u32, 64099); pub const IDI_CPSUI_LAYOUT_BMP_ARROWL = @as(u32, 64100); pub const IDI_CPSUI_LAYOUT_BMP_ARROWS = @as(u32, 64101); pub const IDI_CPSUI_LAYOUT_BMP_BOOKLETL = @as(u32, 64102); pub const IDI_CPSUI_LAYOUT_BMP_BOOKLETP = @as(u32, 64103); pub const IDI_CPSUI_LAYOUT_BMP_ARROWLR = @as(u32, 64104); pub const IDI_CPSUI_LAYOUT_BMP_ROT_PORT = @as(u32, 64105); pub const IDI_CPSUI_LAYOUT_BMP_BOOKLETL_NB = @as(u32, 64106); pub const IDI_CPSUI_LAYOUT_BMP_BOOKLETP_NB = @as(u32, 64107); pub const IDI_CPSUI_ROT_PORT = @as(u32, 64110); pub const IDI_CPSUI_NUP_BORDER = @as(u32, 64111); pub const IDI_CPSUI_ICONID_LAST = @as(u32, 64111); pub const IDS_CPSUI_STRID_FIRST = @as(u32, 64700); pub const IDS_CPSUI_SETUP = @as(u32, 64700); pub const IDS_CPSUI_MORE = @as(u32, 64701); pub const IDS_CPSUI_CHANGE = @as(u32, 64702); pub const IDS_CPSUI_OPTION = @as(u32, 64703); pub const IDS_CPSUI_OF = @as(u32, 64704); pub const IDS_CPSUI_RANGE_FROM = @as(u32, 64705); pub const IDS_CPSUI_TO = @as(u32, 64706); pub const IDS_CPSUI_COLON_SEP = @as(u32, 64707); pub const IDS_CPSUI_LEFT_ANGLE = @as(u32, 64708); pub const IDS_CPSUI_RIGHT_ANGLE = @as(u32, 64709); pub const IDS_CPSUI_SLASH_SEP = @as(u32, 64710); pub const IDS_CPSUI_PERCENT = @as(u32, 64711); pub const IDS_CPSUI_LBCB_NOSEL = @as(u32, 64712); pub const IDS_CPSUI_PROPERTIES = @as(u32, 64713); pub const IDS_CPSUI_DEFAULTDOCUMENT = @as(u32, 64714); pub const IDS_CPSUI_DOCUMENT = @as(u32, 64715); pub const IDS_CPSUI_ADVANCEDOCUMENT = @as(u32, 64716); pub const IDS_CPSUI_PRINTER = @as(u32, 64717); pub const IDS_CPSUI_AUTOSELECT = @as(u32, 64718); pub const IDS_CPSUI_PAPER_OUTPUT = @as(u32, 64719); pub const IDS_CPSUI_GRAPHIC = @as(u32, 64720); pub const IDS_CPSUI_OPTIONS = @as(u32, 64721); pub const IDS_CPSUI_ADVANCED = @as(u32, 64722); pub const IDS_CPSUI_STDDOCPROPTAB = @as(u32, 64723); pub const IDS_CPSUI_STDDOCPROPTVTAB = @as(u32, 64724); pub const IDS_CPSUI_DEVICEOPTIONS = @as(u32, 64725); pub const IDS_CPSUI_FALSE = @as(u32, 64726); pub const IDS_CPSUI_TRUE = @as(u32, 64727); pub const IDS_CPSUI_NO = @as(u32, 64728); pub const IDS_CPSUI_YES = @as(u32, 64729); pub const IDS_CPSUI_OFF = @as(u32, 64730); pub const IDS_CPSUI_ON = @as(u32, 64731); pub const IDS_CPSUI_DEFAULT = @as(u32, 64732); pub const IDS_CPSUI_ERROR = @as(u32, 64733); pub const IDS_CPSUI_NONE = @as(u32, 64734); pub const IDS_CPSUI_NOT = @as(u32, 64735); pub const IDS_CPSUI_EXIST = @as(u32, 64736); pub const IDS_CPSUI_NOTINSTALLED = @as(u32, 64737); pub const IDS_CPSUI_ORIENTATION = @as(u32, 64738); pub const IDS_CPSUI_SCALING = @as(u32, 64739); pub const IDS_CPSUI_NUM_OF_COPIES = @as(u32, 64740); pub const IDS_CPSUI_SOURCE = @as(u32, 64741); pub const IDS_CPSUI_PRINTQUALITY = @as(u32, 64742); pub const IDS_CPSUI_RESOLUTION = @as(u32, 64743); pub const IDS_CPSUI_COLOR_APPERANCE = @as(u32, 64744); pub const IDS_CPSUI_DUPLEX = @as(u32, 64745); pub const IDS_CPSUI_TTOPTION = @as(u32, 64746); pub const IDS_CPSUI_FORMNAME = @as(u32, 64747); pub const IDS_CPSUI_ICM = @as(u32, 64748); pub const IDS_CPSUI_ICMMETHOD = @as(u32, 64749); pub const IDS_CPSUI_ICMINTENT = @as(u32, 64750); pub const IDS_CPSUI_MEDIA = @as(u32, 64751); pub const IDS_CPSUI_DITHERING = @as(u32, 64752); pub const IDS_CPSUI_PORTRAIT = @as(u32, 64753); pub const IDS_CPSUI_LANDSCAPE = @as(u32, 64754); pub const IDS_CPSUI_ROT_LAND = @as(u32, 64755); pub const IDS_CPSUI_COLLATE = @as(u32, 64756); pub const IDS_CPSUI_COLLATED = @as(u32, 64757); pub const IDS_CPSUI_PRINTFLDSETTING = @as(u32, 64758); pub const IDS_CPSUI_DRAFT = @as(u32, 64759); pub const IDS_CPSUI_LOW = @as(u32, 64760); pub const IDS_CPSUI_MEDIUM = @as(u32, 64761); pub const IDS_CPSUI_HIGH = @as(u32, 64762); pub const IDS_CPSUI_PRESENTATION = @as(u32, 64763); pub const IDS_CPSUI_COLOR = @as(u32, 64764); pub const IDS_CPSUI_GRAYSCALE = @as(u32, 64765); pub const IDS_CPSUI_MONOCHROME = @as(u32, 64766); pub const IDS_CPSUI_SIMPLEX = @as(u32, 64767); pub const IDS_CPSUI_HORIZONTAL = @as(u32, 64768); pub const IDS_CPSUI_VERTICAL = @as(u32, 64769); pub const IDS_CPSUI_LONG_SIDE = @as(u32, 64770); pub const IDS_CPSUI_SHORT_SIDE = @as(u32, 64771); pub const IDS_CPSUI_TT_PRINTASGRAPHIC = @as(u32, 64772); pub const IDS_CPSUI_TT_DOWNLOADSOFT = @as(u32, 64773); pub const IDS_CPSUI_TT_DOWNLOADVECT = @as(u32, 64774); pub const IDS_CPSUI_TT_SUBDEV = @as(u32, 64775); pub const IDS_CPSUI_ICM_BLACKWHITE = @as(u32, 64776); pub const IDS_CPSUI_ICM_NO = @as(u32, 64777); pub const IDS_CPSUI_ICM_YES = @as(u32, 64778); pub const IDS_CPSUI_ICM_SATURATION = @as(u32, 64779); pub const IDS_CPSUI_ICM_CONTRAST = @as(u32, 64780); pub const IDS_CPSUI_ICM_COLORMETRIC = @as(u32, 64781); pub const IDS_CPSUI_STANDARD = @as(u32, 64782); pub const IDS_CPSUI_GLOSSY = @as(u32, 64783); pub const IDS_CPSUI_TRANSPARENCY = @as(u32, 64784); pub const IDS_CPSUI_REGULAR = @as(u32, 64785); pub const IDS_CPSUI_BOND = @as(u32, 64786); pub const IDS_CPSUI_COARSE = @as(u32, 64787); pub const IDS_CPSUI_FINE = @as(u32, 64788); pub const IDS_CPSUI_LINEART = @as(u32, 64789); pub const IDS_CPSUI_ERRDIFFUSE = @as(u32, 64790); pub const IDS_CPSUI_HALFTONE = @as(u32, 64791); pub const IDS_CPSUI_HTCLRADJ = @as(u32, 64792); pub const IDS_CPSUI_USE_HOST_HT = @as(u32, 64793); pub const IDS_CPSUI_USE_DEVICE_HT = @as(u32, 64794); pub const IDS_CPSUI_USE_PRINTER_HT = @as(u32, 64795); pub const IDS_CPSUI_OUTBINASSIGN = @as(u32, 64796); pub const IDS_CPSUI_WATERMARK = @as(u32, 64797); pub const IDS_CPSUI_FORMTRAYASSIGN = @as(u32, 64798); pub const IDS_CPSUI_UPPER_TRAY = @as(u32, 64799); pub const IDS_CPSUI_ONLYONE = @as(u32, 64800); pub const IDS_CPSUI_LOWER_TRAY = @as(u32, 64801); pub const IDS_CPSUI_MIDDLE_TRAY = @as(u32, 64802); pub const IDS_CPSUI_MANUAL_TRAY = @as(u32, 64803); pub const IDS_CPSUI_ENVELOPE_TRAY = @as(u32, 64804); pub const IDS_CPSUI_ENVMANUAL_TRAY = @as(u32, 64805); pub const IDS_CPSUI_TRACTOR_TRAY = @as(u32, 64806); pub const IDS_CPSUI_SMALLFMT_TRAY = @as(u32, 64807); pub const IDS_CPSUI_LARGEFMT_TRAY = @as(u32, 64808); pub const IDS_CPSUI_LARGECAP_TRAY = @as(u32, 64809); pub const IDS_CPSUI_CASSETTE_TRAY = @as(u32, 64810); pub const IDS_CPSUI_DEFAULT_TRAY = @as(u32, 64811); pub const IDS_CPSUI_FORMSOURCE = @as(u32, 64812); pub const IDS_CPSUI_MANUALFEED = @as(u32, 64813); pub const IDS_CPSUI_PRINTERMEM_KB = @as(u32, 64814); pub const IDS_CPSUI_PRINTERMEM_MB = @as(u32, 64815); pub const IDS_CPSUI_PAGEPROTECT = @as(u32, 64816); pub const IDS_CPSUI_HALFTONE_SETUP = @as(u32, 64817); pub const IDS_CPSUI_INSTFONTCART = @as(u32, 64818); pub const IDS_CPSUI_SLOT1 = @as(u32, 64819); pub const IDS_CPSUI_SLOT2 = @as(u32, 64820); pub const IDS_CPSUI_SLOT3 = @as(u32, 64821); pub const IDS_CPSUI_SLOT4 = @as(u32, 64822); pub const IDS_CPSUI_LEFT_SLOT = @as(u32, 64823); pub const IDS_CPSUI_RIGHT_SLOT = @as(u32, 64824); pub const IDS_CPSUI_STAPLER = @as(u32, 64825); pub const IDS_CPSUI_STAPLER_ON = @as(u32, 64826); pub const IDS_CPSUI_STAPLER_OFF = @as(u32, 64827); pub const IDS_CPSUI_STACKER = @as(u32, 64828); pub const IDS_CPSUI_MAILBOX = @as(u32, 64829); pub const IDS_CPSUI_COPY = @as(u32, 64830); pub const IDS_CPSUI_COPIES = @as(u32, 64831); pub const IDS_CPSUI_TOTAL = @as(u32, 64832); pub const IDS_CPSUI_MAKE = @as(u32, 64833); pub const IDS_CPSUI_PRINT = @as(u32, 64834); pub const IDS_CPSUI_FAX = @as(u32, 64835); pub const IDS_CPSUI_PLOT = @as(u32, 64836); pub const IDS_CPSUI_SLOW = @as(u32, 64837); pub const IDS_CPSUI_FAST = @as(u32, 64838); pub const IDS_CPSUI_ROTATED = @as(u32, 64839); pub const IDS_CPSUI_RESET = @as(u32, 64840); pub const IDS_CPSUI_ALL = @as(u32, 64841); pub const IDS_CPSUI_DEVICE = @as(u32, 64842); pub const IDS_CPSUI_SETTINGS = @as(u32, 64843); pub const IDS_CPSUI_REVERT = @as(u32, 64844); pub const IDS_CPSUI_CHANGES = @as(u32, 64845); pub const IDS_CPSUI_CHANGED = @as(u32, 64846); pub const IDS_CPSUI_WARNING = @as(u32, 64847); pub const IDS_CPSUI_ABOUT = @as(u32, 64848); pub const IDS_CPSUI_VERSION = @as(u32, 64849); pub const IDS_CPSUI_NO_NAME = @as(u32, 64850); pub const IDS_CPSUI_SETTING = @as(u32, 64851); pub const IDS_CPSUI_DEVICE_SETTINGS = @as(u32, 64852); pub const IDS_CPSUI_STDDOCPROPTAB1 = @as(u32, 64853); pub const IDS_CPSUI_STDDOCPROPTAB2 = @as(u32, 64854); pub const IDS_CPSUI_PAGEORDER = @as(u32, 64855); pub const IDS_CPSUI_FRONTTOBACK = @as(u32, 64856); pub const IDS_CPSUI_BACKTOFRONT = @as(u32, 64857); pub const IDS_CPSUI_QUALITY_SETTINGS = @as(u32, 64858); pub const IDS_CPSUI_QUALITY_DRAFT = @as(u32, 64859); pub const IDS_CPSUI_QUALITY_BETTER = @as(u32, 64860); pub const IDS_CPSUI_QUALITY_BEST = @as(u32, 64861); pub const IDS_CPSUI_QUALITY_CUSTOM = @as(u32, 64862); pub const IDS_CPSUI_OUTPUTBIN = @as(u32, 64863); pub const IDS_CPSUI_NUP = @as(u32, 64864); pub const IDS_CPSUI_NUP_NORMAL = @as(u32, 64865); pub const IDS_CPSUI_NUP_TWOUP = @as(u32, 64866); pub const IDS_CPSUI_NUP_FOURUP = @as(u32, 64867); pub const IDS_CPSUI_NUP_SIXUP = @as(u32, 64868); pub const IDS_CPSUI_NUP_NINEUP = @as(u32, 64869); pub const IDS_CPSUI_NUP_SIXTEENUP = @as(u32, 64870); pub const IDS_CPSUI_SIDE1 = @as(u32, 64871); pub const IDS_CPSUI_SIDE2 = @as(u32, 64872); pub const IDS_CPSUI_BOOKLET = @as(u32, 64873); pub const IDS_CPSUI_POSTER = @as(u32, 64874); pub const IDS_CPSUI_POSTER_2x2 = @as(u32, 64875); pub const IDS_CPSUI_POSTER_3x3 = @as(u32, 64876); pub const IDS_CPSUI_POSTER_4x4 = @as(u32, 64877); pub const IDS_CPSUI_NUP_DIRECTION = @as(u32, 64878); pub const IDS_CPSUI_RIGHT_THEN_DOWN = @as(u32, 64879); pub const IDS_CPSUI_DOWN_THEN_RIGHT = @as(u32, 64880); pub const IDS_CPSUI_LEFT_THEN_DOWN = @as(u32, 64881); pub const IDS_CPSUI_DOWN_THEN_LEFT = @as(u32, 64882); pub const IDS_CPSUI_MANUAL_DUPLEX = @as(u32, 64883); pub const IDS_CPSUI_MANUAL_DUPLEX_ON = @as(u32, 64884); pub const IDS_CPSUI_MANUAL_DUPLEX_OFF = @as(u32, 64885); pub const IDS_CPSUI_ROT_PORT = @as(u32, 64886); pub const IDS_CPSUI_STAPLE = @as(u32, 64887); pub const IDS_CPSUI_BOOKLET_EDGE = @as(u32, 64888); pub const IDS_CPSUI_BOOKLET_EDGE_LEFT = @as(u32, 64889); pub const IDS_CPSUI_BOOKLET_EDGE_RIGHT = @as(u32, 64890); pub const IDS_CPSUI_NUP_BORDER = @as(u32, 64891); pub const IDS_CPSUI_NUP_BORDERED = @as(u32, 64892); pub const IDS_CPSUI_STRID_LAST = @as(u32, 64892); pub const MXDC_ESCAPE = @as(u32, 4122); pub const MXDCOP_GET_FILENAME = @as(u32, 14); pub const MXDCOP_PRINTTICKET_FIXED_DOC_SEQ = @as(u32, 22); pub const MXDCOP_PRINTTICKET_FIXED_DOC = @as(u32, 24); pub const MXDCOP_PRINTTICKET_FIXED_PAGE = @as(u32, 26); pub const MXDCOP_SET_S0PAGE = @as(u32, 28); pub const MXDCOP_SET_S0PAGE_RESOURCE = @as(u32, 30); pub const MXDCOP_SET_XPSPASSTHRU_MODE = @as(u32, 32); pub const CLSID_OEMRENDER = Guid.initString("6d6abf26-9f38-11d1-882a-00c04fb961ec"); pub const CLSID_OEMUI = Guid.initString("abce80d7-9f46-11d1-882a-00c04fb961ec"); pub const CLSID_OEMUIMXDC = Guid.initString("4e144300-5b43-4288-932a-5e4dd6d82bed"); pub const CLSID_OEMPTPROVIDER = Guid.initString("91723892-45d2-48e2-9ec9-562379daf992"); pub const S_DEVCAP_OUTPUT_FULL_REPLACEMENT = @import("../zig.zig").typedConst(HRESULT, @as(i32, 318465)); pub const CLSID_PTPROVIDER = Guid.initString("46ac151b-8490-4531-96cc-55bf2bf19e11"); pub const E_VERSION_NOT_SUPPORTED = @as(u32, 2147745793); pub const S_NO_CONFLICT = @as(u32, 262145); pub const S_CONFLICT_RESOLVED = @as(u32, 262146); pub const PRINTER_EXTENSION_DETAILEDREASON_PRINTER_STATUS = Guid.initString("5d5a1704-dfd1-4181-8eee-815c86edad31"); pub const PRINTER_EXTENSION_REASON_PRINT_PREFERENCES = Guid.initString("ec8f261f-267c-469f-b5d6-3933023c29cc"); pub const PRINTER_EXTENSION_REASON_DRIVER_EVENT = Guid.initString("23bb1328-63de-4293-915b-a6a23d929acb"); pub const FMTID_PrinterPropertyBag = Guid.initString("75f9adca-097d-45c3-a6e4-bab29e276f3e"); pub const PRINTER_OEMINTF_VERSION = @as(u32, 65536); pub const OEM_MODE_PUBLISHER = @as(u32, 1); pub const OEMGI_GETSIGNATURE = @as(u32, 1); pub const OEMGI_GETINTERFACEVERSION = @as(u32, 2); pub const OEMGI_GETVERSION = @as(u32, 3); pub const OEMGI_GETPUBLISHERINFO = @as(u32, 4); pub const OEMGI_GETREQUESTEDHELPERINTERFACES = @as(u32, 5); pub const OEMPUBLISH_DEFAULT = @as(u32, 0); pub const OEMPUBLISH_IPRINTCOREHELPER = @as(u32, 1); pub const OEMDM_SIZE = @as(u32, 1); pub const OEMDM_DEFAULT = @as(u32, 2); pub const OEMDM_CONVERT = @as(u32, 3); pub const OEMDM_MERGE = @as(u32, 4); pub const OEMGDS_MIN_DOCSTICKY = @as(u32, 1); pub const OEMGDS_PSDM_FLAGS = @as(u32, 1); pub const OEMGDS_PSDM_DIALECT = @as(u32, 2); pub const OEMGDS_PSDM_TTDLFMT = @as(u32, 3); pub const OEMGDS_PSDM_NUP = @as(u32, 4); pub const OEMGDS_PSDM_PSLEVEL = @as(u32, 5); pub const OEMGDS_PSDM_CUSTOMSIZE = @as(u32, 6); pub const OEMGDS_UNIDM_GPDVER = @as(u32, 16384); pub const OEMGDS_UNIDM_FLAGS = @as(u32, 16385); pub const OEMGDS_MIN_PRINTERSTICKY = @as(u32, 32768); pub const OEMGDS_PRINTFLAGS = @as(u32, 32768); pub const OEMGDS_FREEMEM = @as(u32, 32769); pub const OEMGDS_JOBTIMEOUT = @as(u32, 32770); pub const OEMGDS_WAITTIMEOUT = @as(u32, 32771); pub const OEMGDS_PROTOCOL = @as(u32, 32772); pub const OEMGDS_MINOUTLINE = @as(u32, 32773); pub const OEMGDS_MAXBITMAP = @as(u32, 32774); pub const OEMGDS_MAX = @as(u32, 65536); pub const GPD_OEMCUSTOMDATA = @as(u32, 1); pub const MV_UPDATE = @as(u32, 1); pub const MV_RELATIVE = @as(u32, 2); pub const MV_GRAPHICS = @as(u32, 4); pub const MV_PHYSICAL = @as(u32, 8); pub const MV_SENDXMOVECMD = @as(u32, 16); pub const MV_SENDYMOVECMD = @as(u32, 32); pub const OEMTTY_INFO_MARGINS = @as(u32, 1); pub const OEMTTY_INFO_CODEPAGE = @as(u32, 2); pub const OEMTTY_INFO_NUM_UFMS = @as(u32, 3); pub const OEMTTY_INFO_UFM_IDS = @as(u32, 4); pub const UFOFLAG_TTFONT = @as(u32, 1); pub const UFOFLAG_TTDOWNLOAD_BITMAP = @as(u32, 2); pub const UFOFLAG_TTDOWNLOAD_TTOUTLINE = @as(u32, 4); pub const UFOFLAG_TTOUTLINE_BOLD_SIM = @as(u32, 8); pub const UFOFLAG_TTOUTLINE_ITALIC_SIM = @as(u32, 16); pub const UFOFLAG_TTOUTLINE_VERTICAL = @as(u32, 32); pub const UFOFLAG_TTSUBSTITUTED = @as(u32, 64); pub const UFO_GETINFO_FONTOBJ = @as(u32, 1); pub const UFO_GETINFO_GLYPHSTRING = @as(u32, 2); pub const UFO_GETINFO_GLYPHBITMAP = @as(u32, 3); pub const UFO_GETINFO_GLYPHWIDTH = @as(u32, 4); pub const UFO_GETINFO_MEMORY = @as(u32, 5); pub const UFO_GETINFO_STDVARIABLE = @as(u32, 6); pub const FNT_INFO_PRINTDIRINCCDEGREES = @as(u32, 0); pub const FNT_INFO_GRAYPERCENTAGE = @as(u32, 1); pub const FNT_INFO_NEXTFONTID = @as(u32, 2); pub const FNT_INFO_NEXTGLYPH = @as(u32, 3); pub const FNT_INFO_FONTHEIGHT = @as(u32, 4); pub const FNT_INFO_FONTWIDTH = @as(u32, 5); pub const FNT_INFO_FONTBOLD = @as(u32, 6); pub const FNT_INFO_FONTITALIC = @as(u32, 7); pub const FNT_INFO_FONTUNDERLINE = @as(u32, 8); pub const FNT_INFO_FONTSTRIKETHRU = @as(u32, 9); pub const FNT_INFO_CURRENTFONTID = @as(u32, 10); pub const FNT_INFO_TEXTYRES = @as(u32, 11); pub const FNT_INFO_TEXTXRES = @as(u32, 12); pub const FNT_INFO_FONTMAXWIDTH = @as(u32, 13); pub const FNT_INFO_MAX = @as(u32, 14); pub const TTDOWNLOAD_DONTCARE = @as(u32, 0); pub const TTDOWNLOAD_GRAPHICS = @as(u32, 1); pub const TTDOWNLOAD_BITMAP = @as(u32, 2); pub const TTDOWNLOAD_TTOUTLINE = @as(u32, 3); pub const TYPE_UNICODE = @as(u32, 1); pub const TYPE_TRANSDATA = @as(u32, 2); pub const TYPE_GLYPHHANDLE = @as(u32, 3); pub const TYPE_GLYPHID = @as(u32, 4); pub const PDEV_ADJUST_PAPER_MARGIN_TYPE = @as(u32, 1); pub const PDEV_HOSTFONT_ENABLED_TYPE = @as(u32, 2); pub const PDEV_USE_TRUE_COLOR_TYPE = @as(u32, 3); pub const OEMCUIP_DOCPROP = @as(u32, 1); pub const OEMCUIP_PRNPROP = @as(u32, 2); pub const CUSTOMPARAM_WIDTH = @as(u32, 0); pub const CUSTOMPARAM_HEIGHT = @as(u32, 1); pub const CUSTOMPARAM_WIDTHOFFSET = @as(u32, 2); pub const CUSTOMPARAM_HEIGHTOFFSET = @as(u32, 3); pub const CUSTOMPARAM_ORIENTATION = @as(u32, 4); pub const CUSTOMPARAM_MAX = @as(u32, 5); pub const SETOPTIONS_FLAG_RESOLVE_CONFLICT = @as(u32, 1); pub const SETOPTIONS_FLAG_KEEP_CONFLICT = @as(u32, 2); pub const SETOPTIONS_RESULT_NO_CONFLICT = @as(u32, 0); pub const SETOPTIONS_RESULT_CONFLICT_RESOLVED = @as(u32, 1); pub const SETOPTIONS_RESULT_CONFLICT_REMAINED = @as(u32, 2); pub const UNIFM_VERSION_1_0 = @as(u32, 65536); pub const UFM_SOFT = @as(u32, 1); pub const UFM_CART = @as(u32, 2); pub const UFM_SCALABLE = @as(u32, 4); pub const DF_TYPE_HPINTELLIFONT = @as(u32, 0); pub const DF_TYPE_TRUETYPE = @as(u32, 1); pub const DF_TYPE_PST1 = @as(u32, 2); pub const DF_TYPE_CAPSL = @as(u32, 3); pub const DF_TYPE_OEM1 = @as(u32, 4); pub const DF_TYPE_OEM2 = @as(u32, 5); pub const DF_NOITALIC = @as(u32, 1); pub const DF_NOUNDER = @as(u32, 2); pub const DF_XM_CR = @as(u32, 4); pub const DF_NO_BOLD = @as(u32, 8); pub const DF_NO_DOUBLE_UNDERLINE = @as(u32, 16); pub const DF_NO_STRIKETHRU = @as(u32, 32); pub const DF_BKSP_OK = @as(u32, 64); pub const UNI_GLYPHSETDATA_VERSION_1_0 = @as(u32, 65536); pub const MTYPE_FORMAT_MASK = @as(u32, 7); pub const MTYPE_COMPOSE = @as(u32, 1); pub const MTYPE_DIRECT = @as(u32, 2); pub const MTYPE_PAIRED = @as(u32, 4); pub const MTYPE_DOUBLEBYTECHAR_MASK = @as(u32, 24); pub const MTYPE_SINGLE = @as(u32, 8); pub const MTYPE_DOUBLE = @as(u32, 16); pub const MTYPE_PREDEFIN_MASK = @as(u32, 224); pub const MTYPE_REPLACE = @as(u32, 32); pub const MTYPE_ADD = @as(u32, 64); pub const MTYPE_DISABLE = @as(u32, 128); pub const CC_NOPRECNV = @as(u32, 65535); pub const CC_DEFAULT = @as(u32, 0); pub const CC_CP437 = @as(i32, -1); pub const CC_CP850 = @as(i32, -2); pub const CC_CP863 = @as(i32, -3); pub const CC_BIG5 = @as(i32, -10); pub const CC_ISC = @as(i32, -11); pub const CC_JIS = @as(i32, -12); pub const CC_JIS_ANK = @as(i32, -13); pub const CC_NS86 = @as(i32, -14); pub const CC_TCA = @as(i32, -15); pub const CC_GB2312 = @as(i32, -16); pub const CC_SJIS = @as(i32, -17); pub const CC_WANSUNG = @as(i32, -18); pub const UFF_VERSION_NUMBER = @as(u32, 65537); pub const FONT_DIR_SORTED = @as(u32, 1); pub const FONT_FL_UFM = @as(u32, 1); pub const FONT_FL_IFI = @as(u32, 2); pub const FONT_FL_SOFTFONT = @as(u32, 4); pub const FONT_FL_PERMANENT_SF = @as(u32, 8); pub const FONT_FL_DEVICEFONT = @as(u32, 16); pub const FONT_FL_GLYPHSET_GTT = @as(u32, 32); pub const FONT_FL_GLYPHSET_RLE = @as(u32, 64); pub const FONT_FL_RESERVED = @as(u32, 32768); pub const FG_CANCHANGE = @as(u32, 128); pub const WM_FI_FILENAME = @as(u32, 900); pub const UNKNOWN_PROTOCOL = @as(u32, 0); pub const PROTOCOL_UNKNOWN_TYPE = @as(u32, 0); pub const RAWTCP = @as(u32, 1); pub const PROTOCOL_RAWTCP_TYPE = @as(u32, 1); pub const LPR = @as(u32, 2); pub const PROTOCOL_LPR_TYPE = @as(u32, 2); pub const MAX_PORTNAME_LEN = @as(u32, 64); pub const MAX_NETWORKNAME_LEN = @as(u32, 49); pub const MAX_NETWORKNAME2_LEN = @as(u32, 128); pub const MAX_SNMP_COMMUNITY_STR_LEN = @as(u32, 33); pub const MAX_QUEUENAME_LEN = @as(u32, 33); pub const MAX_IPADDR_STR_LEN = @as(u32, 16); pub const MAX_ADDRESS_STR_LEN = @as(u32, 13); pub const MAX_DEVICEDESCRIPTION_STR_LEN = @as(u32, 257); pub const DPS_NOPERMISSION = @as(u32, 1); pub const DM_ADVANCED = @as(u32, 16); pub const DM_NOPERMISSION = @as(u32, 32); pub const DM_USER_DEFAULT = @as(u32, 64); pub const DM_PROMPT_NON_MODAL = @as(u32, 1073741824); pub const DM_INVALIDATE_DRIVER_CACHE = @as(u32, 536870912); pub const DM_RESERVED = @as(u32, 2147483648); pub const CDM_CONVERT = @as(u32, 1); pub const CDM_CONVERT351 = @as(u32, 2); pub const CDM_DRIVER_DEFAULT = @as(u32, 4); pub const DOCUMENTEVENT_FIRST = @as(u32, 1); pub const DOCUMENTEVENT_CREATEDCPRE = @as(u32, 1); pub const DOCUMENTEVENT_CREATEDCPOST = @as(u32, 2); pub const DOCUMENTEVENT_RESETDCPRE = @as(u32, 3); pub const DOCUMENTEVENT_RESETDCPOST = @as(u32, 4); pub const DOCUMENTEVENT_STARTDOC = @as(u32, 5); pub const DOCUMENTEVENT_STARTDOCPRE = @as(u32, 5); pub const DOCUMENTEVENT_STARTPAGE = @as(u32, 6); pub const DOCUMENTEVENT_ENDPAGE = @as(u32, 7); pub const DOCUMENTEVENT_ENDDOC = @as(u32, 8); pub const DOCUMENTEVENT_ENDDOCPRE = @as(u32, 8); pub const DOCUMENTEVENT_ABORTDOC = @as(u32, 9); pub const DOCUMENTEVENT_DELETEDC = @as(u32, 10); pub const DOCUMENTEVENT_ESCAPE = @as(u32, 11); pub const DOCUMENTEVENT_ENDDOCPOST = @as(u32, 12); pub const DOCUMENTEVENT_STARTDOCPOST = @as(u32, 13); pub const DOCUMENTEVENT_QUERYFILTER = @as(u32, 14); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTSEQUENCEPRE = @as(u32, 1); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTPRE = @as(u32, 2); pub const DOCUMENTEVENT_XPS_ADDFIXEDPAGEEPRE = @as(u32, 3); pub const DOCUMENTEVENT_XPS_ADDFIXEDPAGEPOST = @as(u32, 4); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTPOST = @as(u32, 5); pub const DOCUMENTEVENT_XPS_CANCELJOB = @as(u32, 6); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTSEQUENCEPRINTTICKETPRE = @as(u32, 7); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTPRINTTICKETPRE = @as(u32, 8); pub const DOCUMENTEVENT_XPS_ADDFIXEDPAGEPRINTTICKETPRE = @as(u32, 9); pub const DOCUMENTEVENT_XPS_ADDFIXEDPAGEPRINTTICKETPOST = @as(u32, 10); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTPRINTTICKETPOST = @as(u32, 11); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTSEQUENCEPRINTTICKETPOST = @as(u32, 12); pub const DOCUMENTEVENT_XPS_ADDFIXEDDOCUMENTSEQUENCEPOST = @as(u32, 13); pub const DOCUMENTEVENT_LAST = @as(u32, 15); pub const DOCUMENTEVENT_SPOOLED = @as(u32, 65536); pub const DOCUMENTEVENT_SUCCESS = @as(u32, 1); pub const DOCUMENTEVENT_UNSUPPORTED = @as(u32, 0); pub const DOCUMENTEVENT_FAILURE = @as(i32, -1); pub const PRINTER_EVENT_CONFIGURATION_CHANGE = @as(u32, 0); pub const PRINTER_EVENT_ADD_CONNECTION = @as(u32, 1); pub const PRINTER_EVENT_DELETE_CONNECTION = @as(u32, 2); pub const PRINTER_EVENT_INITIALIZE = @as(u32, 3); pub const PRINTER_EVENT_DELETE = @as(u32, 4); pub const PRINTER_EVENT_CACHE_REFRESH = @as(u32, 5); pub const PRINTER_EVENT_CACHE_DELETE = @as(u32, 6); pub const PRINTER_EVENT_ATTRIBUTES_CHANGED = @as(u32, 7); pub const PRINTER_EVENT_CONFIGURATION_UPDATE = @as(u32, 8); pub const PRINTER_EVENT_ADD_CONNECTION_NO_UI = @as(u32, 9); pub const PRINTER_EVENT_DELETE_CONNECTION_NO_UI = @as(u32, 10); pub const PRINTER_EVENT_FLAG_NO_UI = @as(u32, 1); pub const DRIVER_EVENT_INITIALIZE = @as(u32, 1); pub const DRIVER_EVENT_DELETE = @as(u32, 2); pub const BORDER_PRINT = @as(u32, 0); pub const NO_BORDER_PRINT = @as(u32, 1); pub const NORMAL_PRINT = @as(u32, 0); pub const REVERSE_PRINT = @as(u32, 1); pub const BOOKLET_PRINT = @as(u32, 2); pub const NO_COLOR_OPTIMIZATION = @as(u32, 0); pub const COLOR_OPTIMIZATION = @as(u32, 1); pub const REVERSE_PAGES_FOR_REVERSE_DUPLEX = @as(u32, 1); pub const RIGHT_THEN_DOWN = @as(u32, 1); pub const BOOKLET_EDGE_LEFT = @as(u32, 0); pub const BOOKLET_EDGE_RIGHT = @as(u32, 1); pub const QCP_DEVICEPROFILE = @as(u32, 0); pub const QCP_SOURCEPROFILE = @as(u32, 1); pub const QCP_PROFILEMEMORY = @as(u32, 1); pub const QCP_PROFILEDISK = @as(u32, 2); pub const EMF_PP_COLOR_OPTIMIZATION = @as(u32, 1); pub const PRINTER_NOTIFY_STATUS_ENDPOINT = @as(u32, 1); pub const PRINTER_NOTIFY_STATUS_POLL = @as(u32, 2); pub const PRINTER_NOTIFY_STATUS_INFO = @as(u32, 4); pub const ROUTER_UNKNOWN = @as(u32, 0); pub const ROUTER_SUCCESS = @as(u32, 1); pub const ROUTER_STOP_ROUTING = @as(u32, 2); pub const FILL_WITH_DEFAULTS = @as(u32, 1); pub const PRINTER_NOTIFY_INFO_DATA_COMPACT = @as(u32, 1); pub const COPYFILE_EVENT_SET_PRINTER_DATAEX = @as(u32, 1); pub const COPYFILE_EVENT_DELETE_PRINTER = @as(u32, 2); pub const COPYFILE_EVENT_ADD_PRINTER_CONNECTION = @as(u32, 3); pub const COPYFILE_EVENT_DELETE_PRINTER_CONNECTION = @as(u32, 4); pub const COPYFILE_EVENT_FILES_CHANGED = @as(u32, 5); pub const COPYFILE_FLAG_CLIENT_SPOOLER = @as(u32, 1); pub const COPYFILE_FLAG_SERVER_SPOOLER = @as(u32, 2); pub const DSPRINT_PUBLISH = @as(u32, 1); pub const DSPRINT_UPDATE = @as(u32, 2); pub const DSPRINT_UNPUBLISH = @as(u32, 4); pub const DSPRINT_REPUBLISH = @as(u32, 8); pub const DSPRINT_PENDING = @as(u32, 2147483648); pub const PRINTER_CONTROL_PAUSE = @as(u32, 1); pub const PRINTER_CONTROL_RESUME = @as(u32, 2); pub const PRINTER_CONTROL_PURGE = @as(u32, 3); pub const PRINTER_CONTROL_SET_STATUS = @as(u32, 4); pub const PRINTER_STATUS_PAUSED = @as(u32, 1); pub const PRINTER_STATUS_ERROR = @as(u32, 2); pub const PRINTER_STATUS_PENDING_DELETION = @as(u32, 4); pub const PRINTER_STATUS_PAPER_JAM = @as(u32, 8); pub const PRINTER_STATUS_PAPER_OUT = @as(u32, 16); pub const PRINTER_STATUS_MANUAL_FEED = @as(u32, 32); pub const PRINTER_STATUS_PAPER_PROBLEM = @as(u32, 64); pub const PRINTER_STATUS_OFFLINE = @as(u32, 128); pub const PRINTER_STATUS_IO_ACTIVE = @as(u32, 256); pub const PRINTER_STATUS_BUSY = @as(u32, 512); pub const PRINTER_STATUS_PRINTING = @as(u32, 1024); pub const PRINTER_STATUS_OUTPUT_BIN_FULL = @as(u32, 2048); pub const PRINTER_STATUS_NOT_AVAILABLE = @as(u32, 4096); pub const PRINTER_STATUS_WAITING = @as(u32, 8192); pub const PRINTER_STATUS_PROCESSING = @as(u32, 16384); pub const PRINTER_STATUS_INITIALIZING = @as(u32, 32768); pub const PRINTER_STATUS_WARMING_UP = @as(u32, 65536); pub const PRINTER_STATUS_TONER_LOW = @as(u32, 131072); pub const PRINTER_STATUS_NO_TONER = @as(u32, 262144); pub const PRINTER_STATUS_PAGE_PUNT = @as(u32, 524288); pub const PRINTER_STATUS_USER_INTERVENTION = @as(u32, 1048576); pub const PRINTER_STATUS_OUT_OF_MEMORY = @as(u32, 2097152); pub const PRINTER_STATUS_DOOR_OPEN = @as(u32, 4194304); pub const PRINTER_STATUS_SERVER_UNKNOWN = @as(u32, 8388608); pub const PRINTER_STATUS_POWER_SAVE = @as(u32, 16777216); pub const PRINTER_STATUS_SERVER_OFFLINE = @as(u32, 33554432); pub const PRINTER_STATUS_DRIVER_UPDATE_NEEDED = @as(u32, 67108864); pub const PRINTER_ATTRIBUTE_QUEUED = @as(u32, 1); pub const PRINTER_ATTRIBUTE_DIRECT = @as(u32, 2); pub const PRINTER_ATTRIBUTE_DEFAULT = @as(u32, 4); pub const PRINTER_ATTRIBUTE_SHARED = @as(u32, 8); pub const PRINTER_ATTRIBUTE_NETWORK = @as(u32, 16); pub const PRINTER_ATTRIBUTE_HIDDEN = @as(u32, 32); pub const PRINTER_ATTRIBUTE_LOCAL = @as(u32, 64); pub const PRINTER_ATTRIBUTE_ENABLE_DEVQ = @as(u32, 128); pub const PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS = @as(u32, 256); pub const PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST = @as(u32, 512); pub const PRINTER_ATTRIBUTE_WORK_OFFLINE = @as(u32, 1024); pub const PRINTER_ATTRIBUTE_ENABLE_BIDI = @as(u32, 2048); pub const PRINTER_ATTRIBUTE_RAW_ONLY = @as(u32, 4096); pub const PRINTER_ATTRIBUTE_PUBLISHED = @as(u32, 8192); pub const PRINTER_ATTRIBUTE_FAX = @as(u32, 16384); pub const PRINTER_ATTRIBUTE_TS = @as(u32, 32768); pub const PRINTER_ATTRIBUTE_PUSHED_USER = @as(u32, 131072); pub const PRINTER_ATTRIBUTE_PUSHED_MACHINE = @as(u32, 262144); pub const PRINTER_ATTRIBUTE_MACHINE = @as(u32, 524288); pub const PRINTER_ATTRIBUTE_FRIENDLY_NAME = @as(u32, 1048576); pub const PRINTER_ATTRIBUTE_TS_GENERIC_DRIVER = @as(u32, 2097152); pub const PRINTER_ATTRIBUTE_PER_USER = @as(u32, 4194304); pub const PRINTER_ATTRIBUTE_ENTERPRISE_CLOUD = @as(u32, 8388608); pub const NO_PRIORITY = @as(u32, 0); pub const MAX_PRIORITY = @as(u32, 99); pub const MIN_PRIORITY = @as(u32, 1); pub const DEF_PRIORITY = @as(u32, 1); pub const JOB_CONTROL_PAUSE = @as(u32, 1); pub const JOB_CONTROL_RESUME = @as(u32, 2); pub const JOB_CONTROL_CANCEL = @as(u32, 3); pub const JOB_CONTROL_RESTART = @as(u32, 4); pub const JOB_CONTROL_DELETE = @as(u32, 5); pub const JOB_CONTROL_SENT_TO_PRINTER = @as(u32, 6); pub const JOB_CONTROL_LAST_PAGE_EJECTED = @as(u32, 7); pub const JOB_CONTROL_RETAIN = @as(u32, 8); pub const JOB_CONTROL_RELEASE = @as(u32, 9); pub const JOB_STATUS_PAUSED = @as(u32, 1); pub const JOB_STATUS_ERROR = @as(u32, 2); pub const JOB_STATUS_DELETING = @as(u32, 4); pub const JOB_STATUS_SPOOLING = @as(u32, 8); pub const JOB_STATUS_PRINTING = @as(u32, 16); pub const JOB_STATUS_OFFLINE = @as(u32, 32); pub const JOB_STATUS_PAPEROUT = @as(u32, 64); pub const JOB_STATUS_PRINTED = @as(u32, 128); pub const JOB_STATUS_DELETED = @as(u32, 256); pub const JOB_STATUS_BLOCKED_DEVQ = @as(u32, 512); pub const JOB_STATUS_USER_INTERVENTION = @as(u32, 1024); pub const JOB_STATUS_RESTART = @as(u32, 2048); pub const JOB_STATUS_COMPLETE = @as(u32, 4096); pub const JOB_STATUS_RETAINED = @as(u32, 8192); pub const JOB_STATUS_RENDERING_LOCALLY = @as(u32, 16384); pub const JOB_POSITION_UNSPECIFIED = @as(u32, 0); pub const PRINTER_DRIVER_PACKAGE_AWARE = @as(u32, 1); pub const PRINTER_DRIVER_XPS = @as(u32, 2); pub const PRINTER_DRIVER_SANDBOX_ENABLED = @as(u32, 4); pub const PRINTER_DRIVER_CLASS = @as(u32, 8); pub const PRINTER_DRIVER_DERIVED = @as(u32, 16); pub const PRINTER_DRIVER_NOT_SHAREABLE = @as(u32, 32); pub const PRINTER_DRIVER_CATEGORY_FAX = @as(u32, 64); pub const PRINTER_DRIVER_CATEGORY_FILE = @as(u32, 128); pub const PRINTER_DRIVER_CATEGORY_VIRTUAL = @as(u32, 256); pub const PRINTER_DRIVER_CATEGORY_SERVICE = @as(u32, 512); pub const PRINTER_DRIVER_SOFT_RESET_REQUIRED = @as(u32, 1024); pub const PRINTER_DRIVER_SANDBOX_DISABLED = @as(u32, 2048); pub const PRINTER_DRIVER_CATEGORY_3D = @as(u32, 4096); pub const PRINTER_DRIVER_CATEGORY_CLOUD = @as(u32, 8192); pub const DRIVER_KERNELMODE = @as(u32, 1); pub const DRIVER_USERMODE = @as(u32, 2); pub const DPD_DELETE_UNUSED_FILES = @as(u32, 1); pub const DPD_DELETE_SPECIFIC_VERSION = @as(u32, 2); pub const DPD_DELETE_ALL_FILES = @as(u32, 4); pub const APD_STRICT_UPGRADE = @as(u32, 1); pub const APD_STRICT_DOWNGRADE = @as(u32, 2); pub const APD_COPY_ALL_FILES = @as(u32, 4); pub const APD_COPY_NEW_FILES = @as(u32, 8); pub const APD_COPY_FROM_DIRECTORY = @as(u32, 16); pub const STRING_NONE = @as(u32, 1); pub const STRING_MUIDLL = @as(u32, 2); pub const STRING_LANGPAIR = @as(u32, 4); pub const MAX_FORM_KEYWORD_LENGTH = @as(u32, 64); pub const DI_CHANNEL = @as(u32, 1); pub const DI_READ_SPOOL_JOB = @as(u32, 3); pub const DI_MEMORYMAP_WRITE = @as(u32, 1); pub const FORM_USER = @as(u32, 0); pub const FORM_BUILTIN = @as(u32, 1); pub const FORM_PRINTER = @as(u32, 2); pub const PPCAPS_RIGHT_THEN_DOWN = @as(u32, 1); pub const PPCAPS_BORDER_PRINT = @as(u32, 1); pub const PPCAPS_BOOKLET_EDGE = @as(u32, 1); pub const PPCAPS_REVERSE_PAGES_FOR_REVERSE_DUPLEX = @as(u32, 1); pub const PPCAPS_SQUARE_SCALING = @as(u32, 1); pub const PORT_TYPE_WRITE = @as(u32, 1); pub const PORT_TYPE_READ = @as(u32, 2); pub const PORT_TYPE_REDIRECTED = @as(u32, 4); pub const PORT_TYPE_NET_ATTACHED = @as(u32, 8); pub const PORT_STATUS_TYPE_ERROR = @as(u32, 1); pub const PORT_STATUS_TYPE_WARNING = @as(u32, 2); pub const PORT_STATUS_TYPE_INFO = @as(u32, 3); pub const PORT_STATUS_OFFLINE = @as(u32, 1); pub const PORT_STATUS_PAPER_JAM = @as(u32, 2); pub const PORT_STATUS_PAPER_OUT = @as(u32, 3); pub const PORT_STATUS_OUTPUT_BIN_FULL = @as(u32, 4); pub const PORT_STATUS_PAPER_PROBLEM = @as(u32, 5); pub const PORT_STATUS_NO_TONER = @as(u32, 6); pub const PORT_STATUS_DOOR_OPEN = @as(u32, 7); pub const PORT_STATUS_USER_INTERVENTION = @as(u32, 8); pub const PORT_STATUS_OUT_OF_MEMORY = @as(u32, 9); pub const PORT_STATUS_TONER_LOW = @as(u32, 10); pub const PORT_STATUS_WARMING_UP = @as(u32, 11); pub const PORT_STATUS_POWER_SAVE = @as(u32, 12); pub const PRINTER_ENUM_DEFAULT = @as(u32, 1); pub const PRINTER_ENUM_LOCAL = @as(u32, 2); pub const PRINTER_ENUM_CONNECTIONS = @as(u32, 4); pub const PRINTER_ENUM_FAVORITE = @as(u32, 4); pub const PRINTER_ENUM_NAME = @as(u32, 8); pub const PRINTER_ENUM_REMOTE = @as(u32, 16); pub const PRINTER_ENUM_SHARED = @as(u32, 32); pub const PRINTER_ENUM_NETWORK = @as(u32, 64); pub const PRINTER_ENUM_EXPAND = @as(u32, 16384); pub const PRINTER_ENUM_CONTAINER = @as(u32, 32768); pub const PRINTER_ENUM_ICONMASK = @as(u32, 16711680); pub const PRINTER_ENUM_ICON1 = @as(u32, 65536); pub const PRINTER_ENUM_ICON2 = @as(u32, 131072); pub const PRINTER_ENUM_ICON3 = @as(u32, 262144); pub const PRINTER_ENUM_ICON4 = @as(u32, 524288); pub const PRINTER_ENUM_ICON5 = @as(u32, 1048576); pub const PRINTER_ENUM_ICON6 = @as(u32, 2097152); pub const PRINTER_ENUM_ICON7 = @as(u32, 4194304); pub const PRINTER_ENUM_ICON8 = @as(u32, 8388608); pub const PRINTER_ENUM_HIDE = @as(u32, 16777216); pub const PRINTER_ENUM_CATEGORY_ALL = @as(u32, 33554432); pub const PRINTER_ENUM_CATEGORY_3D = @as(u32, 67108864); pub const SPOOL_FILE_PERSISTENT = @as(u32, 1); pub const SPOOL_FILE_TEMPORARY = @as(u32, 2); pub const PRINTER_NOTIFY_TYPE = @as(u32, 0); pub const JOB_NOTIFY_TYPE = @as(u32, 1); pub const SERVER_NOTIFY_TYPE = @as(u32, 2); pub const PRINTER_NOTIFY_FIELD_SERVER_NAME = @as(u32, 0); pub const PRINTER_NOTIFY_FIELD_PRINTER_NAME = @as(u32, 1); pub const PRINTER_NOTIFY_FIELD_SHARE_NAME = @as(u32, 2); pub const PRINTER_NOTIFY_FIELD_PORT_NAME = @as(u32, 3); pub const PRINTER_NOTIFY_FIELD_DRIVER_NAME = @as(u32, 4); pub const PRINTER_NOTIFY_FIELD_COMMENT = @as(u32, 5); pub const PRINTER_NOTIFY_FIELD_LOCATION = @as(u32, 6); pub const PRINTER_NOTIFY_FIELD_DEVMODE = @as(u32, 7); pub const PRINTER_NOTIFY_FIELD_SEPFILE = @as(u32, 8); pub const PRINTER_NOTIFY_FIELD_PRINT_PROCESSOR = @as(u32, 9); pub const PRINTER_NOTIFY_FIELD_PARAMETERS = @as(u32, 10); pub const PRINTER_NOTIFY_FIELD_DATATYPE = @as(u32, 11); pub const PRINTER_NOTIFY_FIELD_SECURITY_DESCRIPTOR = @as(u32, 12); pub const PRINTER_NOTIFY_FIELD_ATTRIBUTES = @as(u32, 13); pub const PRINTER_NOTIFY_FIELD_PRIORITY = @as(u32, 14); pub const PRINTER_NOTIFY_FIELD_DEFAULT_PRIORITY = @as(u32, 15); pub const PRINTER_NOTIFY_FIELD_START_TIME = @as(u32, 16); pub const PRINTER_NOTIFY_FIELD_UNTIL_TIME = @as(u32, 17); pub const PRINTER_NOTIFY_FIELD_STATUS = @as(u32, 18); pub const PRINTER_NOTIFY_FIELD_STATUS_STRING = @as(u32, 19); pub const PRINTER_NOTIFY_FIELD_CJOBS = @as(u32, 20); pub const PRINTER_NOTIFY_FIELD_AVERAGE_PPM = @as(u32, 21); pub const PRINTER_NOTIFY_FIELD_TOTAL_PAGES = @as(u32, 22); pub const PRINTER_NOTIFY_FIELD_PAGES_PRINTED = @as(u32, 23); pub const PRINTER_NOTIFY_FIELD_TOTAL_BYTES = @as(u32, 24); pub const PRINTER_NOTIFY_FIELD_BYTES_PRINTED = @as(u32, 25); pub const PRINTER_NOTIFY_FIELD_OBJECT_GUID = @as(u32, 26); pub const PRINTER_NOTIFY_FIELD_FRIENDLY_NAME = @as(u32, 27); pub const PRINTER_NOTIFY_FIELD_BRANCH_OFFICE_PRINTING = @as(u32, 28); pub const JOB_NOTIFY_FIELD_PRINTER_NAME = @as(u32, 0); pub const JOB_NOTIFY_FIELD_MACHINE_NAME = @as(u32, 1); pub const JOB_NOTIFY_FIELD_PORT_NAME = @as(u32, 2); pub const JOB_NOTIFY_FIELD_USER_NAME = @as(u32, 3); pub const JOB_NOTIFY_FIELD_NOTIFY_NAME = @as(u32, 4); pub const JOB_NOTIFY_FIELD_DATATYPE = @as(u32, 5); pub const JOB_NOTIFY_FIELD_PRINT_PROCESSOR = @as(u32, 6); pub const JOB_NOTIFY_FIELD_PARAMETERS = @as(u32, 7); pub const JOB_NOTIFY_FIELD_DRIVER_NAME = @as(u32, 8); pub const JOB_NOTIFY_FIELD_DEVMODE = @as(u32, 9); pub const JOB_NOTIFY_FIELD_STATUS = @as(u32, 10); pub const JOB_NOTIFY_FIELD_STATUS_STRING = @as(u32, 11); pub const JOB_NOTIFY_FIELD_SECURITY_DESCRIPTOR = @as(u32, 12); pub const JOB_NOTIFY_FIELD_DOCUMENT = @as(u32, 13); pub const JOB_NOTIFY_FIELD_PRIORITY = @as(u32, 14); pub const JOB_NOTIFY_FIELD_POSITION = @as(u32, 15); pub const JOB_NOTIFY_FIELD_SUBMITTED = @as(u32, 16); pub const JOB_NOTIFY_FIELD_START_TIME = @as(u32, 17); pub const JOB_NOTIFY_FIELD_UNTIL_TIME = @as(u32, 18); pub const JOB_NOTIFY_FIELD_TIME = @as(u32, 19); pub const JOB_NOTIFY_FIELD_TOTAL_PAGES = @as(u32, 20); pub const JOB_NOTIFY_FIELD_PAGES_PRINTED = @as(u32, 21); pub const JOB_NOTIFY_FIELD_TOTAL_BYTES = @as(u32, 22); pub const JOB_NOTIFY_FIELD_BYTES_PRINTED = @as(u32, 23); pub const JOB_NOTIFY_FIELD_REMOTE_JOB_ID = @as(u32, 24); pub const SERVER_NOTIFY_FIELD_PRINT_DRIVER_ISOLATION_GROUP = @as(u32, 0); pub const PRINTER_NOTIFY_CATEGORY_ALL = @as(u32, 4096); pub const PRINTER_NOTIFY_CATEGORY_3D = @as(u32, 8192); pub const PRINTER_NOTIFY_OPTIONS_REFRESH = @as(u32, 1); pub const PRINTER_NOTIFY_INFO_DISCARDED = @as(u32, 1); pub const BIDI_ACCESS_ADMINISTRATOR = @as(u32, 1); pub const BIDI_ACCESS_USER = @as(u32, 2); pub const ERROR_BIDI_STATUS_OK = @as(u32, 0); pub const ERROR_BIDI_ERROR_BASE = @as(u32, 13000); pub const ERROR_BIDI_STATUS_WARNING = @as(u32, 13001); pub const ERROR_BIDI_SCHEMA_READ_ONLY = @as(u32, 13002); pub const ERROR_BIDI_SERVER_OFFLINE = @as(u32, 13003); pub const ERROR_BIDI_DEVICE_OFFLINE = @as(u32, 13004); pub const ERROR_BIDI_SCHEMA_NOT_SUPPORTED = @as(u32, 13005); pub const ERROR_BIDI_SET_DIFFERENT_TYPE = @as(u32, 13006); pub const ERROR_BIDI_SET_MULTIPLE_SCHEMAPATH = @as(u32, 13007); pub const ERROR_BIDI_SET_INVALID_SCHEMAPATH = @as(u32, 13008); pub const ERROR_BIDI_SET_UNKNOWN_FAILURE = @as(u32, 13009); pub const ERROR_BIDI_SCHEMA_WRITE_ONLY = @as(u32, 13010); pub const ERROR_BIDI_GET_REQUIRES_ARGUMENT = @as(u32, 13011); pub const ERROR_BIDI_GET_ARGUMENT_NOT_SUPPORTED = @as(u32, 13012); pub const ERROR_BIDI_GET_MISSING_ARGUMENT = @as(u32, 13013); pub const ERROR_BIDI_DEVICE_CONFIG_UNCHANGED = @as(u32, 13014); pub const ERROR_BIDI_NO_LOCALIZED_RESOURCES = @as(u32, 13015); pub const ERROR_BIDI_NO_BIDI_SCHEMA_EXTENSIONS = @as(u32, 13016); pub const ERROR_BIDI_UNSUPPORTED_CLIENT_LANGUAGE = @as(u32, 13017); pub const ERROR_BIDI_UNSUPPORTED_RESOURCE_FORMAT = @as(u32, 13018); pub const PRINTER_CHANGE_ADD_PRINTER = @as(u32, 1); pub const PRINTER_CHANGE_SET_PRINTER = @as(u32, 2); pub const PRINTER_CHANGE_DELETE_PRINTER = @as(u32, 4); pub const PRINTER_CHANGE_FAILED_CONNECTION_PRINTER = @as(u32, 8); pub const PRINTER_CHANGE_PRINTER = @as(u32, 255); pub const PRINTER_CHANGE_ADD_JOB = @as(u32, 256); pub const PRINTER_CHANGE_SET_JOB = @as(u32, 512); pub const PRINTER_CHANGE_DELETE_JOB = @as(u32, 1024); pub const PRINTER_CHANGE_WRITE_JOB = @as(u32, 2048); pub const PRINTER_CHANGE_JOB = @as(u32, 65280); pub const PRINTER_CHANGE_ADD_FORM = @as(u32, 65536); pub const PRINTER_CHANGE_SET_FORM = @as(u32, 131072); pub const PRINTER_CHANGE_DELETE_FORM = @as(u32, 262144); pub const PRINTER_CHANGE_FORM = @as(u32, 458752); pub const PRINTER_CHANGE_ADD_PORT = @as(u32, 1048576); pub const PRINTER_CHANGE_CONFIGURE_PORT = @as(u32, 2097152); pub const PRINTER_CHANGE_DELETE_PORT = @as(u32, 4194304); pub const PRINTER_CHANGE_PORT = @as(u32, 7340032); pub const PRINTER_CHANGE_ADD_PRINT_PROCESSOR = @as(u32, 16777216); pub const PRINTER_CHANGE_DELETE_PRINT_PROCESSOR = @as(u32, 67108864); pub const PRINTER_CHANGE_PRINT_PROCESSOR = @as(u32, 117440512); pub const PRINTER_CHANGE_SERVER = @as(u32, 134217728); pub const PRINTER_CHANGE_ADD_PRINTER_DRIVER = @as(u32, 268435456); pub const PRINTER_CHANGE_SET_PRINTER_DRIVER = @as(u32, 536870912); pub const PRINTER_CHANGE_DELETE_PRINTER_DRIVER = @as(u32, 1073741824); pub const PRINTER_CHANGE_PRINTER_DRIVER = @as(u32, 1879048192); pub const PRINTER_CHANGE_TIMEOUT = @as(u32, 2147483648); pub const PRINTER_CHANGE_ALL = @as(u32, 2138570751); pub const PRINTER_ERROR_INFORMATION = @as(u32, 2147483648); pub const PRINTER_ERROR_WARNING = @as(u32, 1073741824); pub const PRINTER_ERROR_SEVERE = @as(u32, 536870912); pub const PRINTER_ERROR_OUTOFPAPER = @as(u32, 1); pub const PRINTER_ERROR_JAM = @as(u32, 2); pub const PRINTER_ERROR_OUTOFTONER = @as(u32, 4); pub const SERVER_ACCESS_ADMINISTER = @as(u32, 1); pub const SERVER_ACCESS_ENUMERATE = @as(u32, 2); pub const PRINTER_ACCESS_ADMINISTER = @as(u32, 4); pub const PRINTER_ACCESS_USE = @as(u32, 8); pub const JOB_ACCESS_ADMINISTER = @as(u32, 16); pub const JOB_ACCESS_READ = @as(u32, 32); pub const PRINTER_ACCESS_MANAGE_LIMITED = @as(u32, 64); pub const PRINTER_CONNECTION_MISMATCH = @as(u32, 32); pub const PRINTER_CONNECTION_NO_UI = @as(u32, 64); pub const IPDFP_COPY_ALL_FILES = @as(u32, 1); pub const UPDP_SILENT_UPLOAD = @as(u32, 1); pub const UPDP_UPLOAD_ALWAYS = @as(u32, 2); pub const UPDP_CHECK_DRIVERSTORE = @as(u32, 4); pub const DISPID_PRINTSCHEMA_ELEMENT = @as(u32, 10000); pub const DISPID_PRINTSCHEMA_ELEMENT_XMLNODE = @as(u32, 10001); pub const DISPID_PRINTSCHEMA_ELEMENT_NAME = @as(u32, 10002); pub const DISPID_PRINTSCHEMA_ELEMENT_NAMESPACEURI = @as(u32, 10003); pub const DISPID_PRINTSCHEMA_DISPLAYABLEELEMENT = @as(u32, 10100); pub const DISPID_PRINTSCHEMA_DISPLAYABLEELEMENT_DISPLAYNAME = @as(u32, 10101); pub const DISPID_PRINTSCHEMA_OPTION = @as(u32, 10200); pub const DISPID_PRINTSCHEMA_OPTION_SELECTED = @as(u32, 10201); pub const DISPID_PRINTSCHEMA_OPTION_CONSTRAINED = @as(u32, 10202); pub const DISPID_PRINTSCHEMA_OPTION_GETPROPERTYVALUE = @as(u32, 10203); pub const DISPID_PRINTSCHEMA_PAGEMEDIASIZEOPTION = @as(u32, 10300); pub const DISPID_PRINTSCHEMA_PAGEMEDIASIZEOPTION_WIDTH = @as(u32, 10301); pub const DISPID_PRINTSCHEMA_PAGEMEDIASIZEOPTION_HEIGHT = @as(u32, 10302); pub const DISPID_PRINTSCHEMA_NUPOPTION = @as(u32, 10400); pub const DISPID_PRINTSCHEMA_NUPOPTION_PAGESPERSHEET = @as(u32, 10401); pub const DISPID_PRINTSCHEMA_OPTIONCOLLECTION = @as(u32, 10500); pub const DISPID_PRINTSCHEMA_OPTIONCOLLECTION_COUNT = @as(u32, 10501); pub const DISPID_PRINTSCHEMA_OPTIONCOLLECTION_GETAT = @as(u32, 10502); pub const DISPID_PRINTSCHEMA_FEATURE = @as(u32, 10600); pub const DISPID_PRINTSCHEMA_FEATURE_SELECTEDOPTION = @as(u32, 10601); pub const DISPID_PRINTSCHEMA_FEATURE_SELECTIONTYPE = @as(u32, 10602); pub const DISPID_PRINTSCHEMA_FEATURE_GETOPTION = @as(u32, 10603); pub const DISPID_PRINTSCHEMA_FEATURE_DISPLAYUI = @as(u32, 10604); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE = @as(u32, 10700); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE_IMAGEABLE_WIDTH = @as(u32, 10701); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE_IMAGEABLE_HEIGHT = @as(u32, 10702); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE_ORIGIN_WIDTH = @as(u32, 10703); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE_ORIGIN_HEIGHT = @as(u32, 10704); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE_EXTENT_WIDTH = @as(u32, 10705); pub const DISPID_PRINTSCHEMA_PAGEIMAGEABLESIZE_EXTENT_HEIGHT = @as(u32, 10706); pub const DISPID_PRINTSCHEMA_CAPABILITIES = @as(u32, 10800); pub const DISPID_PRINTSCHEMA_CAPABILITIES_GETFEATURE_KEYNAME = @as(u32, 10801); pub const DISPID_PRINTSCHEMA_CAPABILITIES_GETFEATURE = @as(u32, 10802); pub const DISPID_PRINTSCHEMA_CAPABILITIES_PAGEIMAGEABLESIZE = @as(u32, 10803); pub const DISPID_PRINTSCHEMA_CAPABILITIES_JOBCOPIESMINVALUE = @as(u32, 10804); pub const DISPID_PRINTSCHEMA_CAPABILITIES_JOBCOPIESMAXVALUE = @as(u32, 10805); pub const DISPID_PRINTSCHEMA_CAPABILITIES_GETSELECTEDOPTION = @as(u32, 10806); pub const DISPID_PRINTSCHEMA_CAPABILITIES_GETOPTIONS = @as(u32, 10807); pub const DISPID_PRINTSCHEMA_CAPABILITIES_GETPARAMETERDEFINITION = @as(u32, 10808); pub const DISPID_PRINTSCHEMA_ASYNCOPERATION = @as(u32, 10900); pub const DISPID_PRINTSCHEMA_ASYNCOPERATION_START = @as(u32, 10901); pub const DISPID_PRINTSCHEMA_ASYNCOPERATION_CANCEL = @as(u32, 10902); pub const DISPID_PRINTSCHEMA_TICKET = @as(u32, 11000); pub const DISPID_PRINTSCHEMA_TICKET_GETFEATURE_KEYNAME = @as(u32, 11001); pub const DISPID_PRINTSCHEMA_TICKET_GETFEATURE = @as(u32, 11002); pub const DISPID_PRINTSCHEMA_TICKET_VALIDATEASYNC = @as(u32, 11003); pub const DISPID_PRINTSCHEMA_TICKET_COMMITASYNC = @as(u32, 11004); pub const DISPID_PRINTSCHEMA_TICKET_NOTIFYXMLCHANGED = @as(u32, 11005); pub const DISPID_PRINTSCHEMA_TICKET_GETCAPABILITIES = @as(u32, 11006); pub const DISPID_PRINTSCHEMA_TICKET_JOBCOPIESALLDOCUMENTS = @as(u32, 11007); pub const DISPID_PRINTSCHEMA_TICKET_GETPARAMETERINITIALIZER = @as(u32, 11008); pub const DISPID_PRINTSCHEMA_ASYNCOPERATIONEVENT = @as(u32, 11100); pub const DISPID_PRINTSCHEMA_ASYNCOPERATIONEVENT_COMPLETED = @as(u32, 11101); pub const DISPID_PRINTERSCRIPTABLESEQUENTIALSTREAM = @as(u32, 11200); pub const DISPID_PRINTERSCRIPTABLESEQUENTIALSTREAM_READ = @as(u32, 11201); pub const DISPID_PRINTERSCRIPTABLESEQUENTIALSTREAM_WRITE = @as(u32, 11202); pub const DISPID_PRINTERSCRIPTABLESTREAM = @as(u32, 11300); pub const DISPID_PRINTERSCRIPTABLESTREAM_COMMIT = @as(u32, 11301); pub const DISPID_PRINTERSCRIPTABLESTREAM_SEEK = @as(u32, 11302); pub const DISPID_PRINTERSCRIPTABLESTREAM_SETSIZE = @as(u32, 11303); pub const DISPID_PRINTERPROPERTYBAG = @as(u32, 11400); pub const DISPID_PRINTERPROPERTYBAG_GETBOOL = @as(u32, 11401); pub const DISPID_PRINTERPROPERTYBAG_SETBOOL = @as(u32, 11402); pub const DISPID_PRINTERPROPERTYBAG_GETINT32 = @as(u32, 11403); pub const DISPID_PRINTERPROPERTYBAG_SETINT32 = @as(u32, 11404); pub const DISPID_PRINTERPROPERTYBAG_GETSTRING = @as(u32, 11405); pub const DISPID_PRINTERPROPERTYBAG_SETSTRING = @as(u32, 11406); pub const DISPID_PRINTERPROPERTYBAG_GETBYTES = @as(u32, 11407); pub const DISPID_PRINTERPROPERTYBAG_SETBYTES = @as(u32, 11408); pub const DISPID_PRINTERPROPERTYBAG_GETREADSTREAM = @as(u32, 11409); pub const DISPID_PRINTERPROPERTYBAG_GETWRITESTREAM = @as(u32, 11410); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETSTREAMASXML = @as(u32, 11411); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG = @as(u32, 11500); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETBOOL = @as(u32, 11501); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_SETBOOL = @as(u32, 11502); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETINT32 = @as(u32, 11503); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_SETINT32 = @as(u32, 11504); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETSTRING = @as(u32, 11505); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_SETSTRING = @as(u32, 11506); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETBYTES = @as(u32, 11507); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_SETBYTES = @as(u32, 11508); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETREADSTREAM = @as(u32, 11509); pub const DISPID_PRINTERSCRIPTABLEPROPERTYBAG_GETWRITESTREAM = @as(u32, 11510); pub const DISPID_PRINTERQUEUE = @as(u32, 11600); pub const DISPID_PRINTERQUEUE_HANDLE = @as(u32, 11601); pub const DISPID_PRINTERQUEUE_NAME = @as(u32, 11602); pub const DISPID_PRINTERQUEUE_SENDBIDIQUERY = @as(u32, 11603); pub const DISPID_PRINTERQUEUE_GETPROPERTIES = @as(u32, 11604); pub const DISPID_PRINTERQUEUE_SENDBIDISETREQUESTASYNC = @as(u32, 11605); pub const DISPID_PRINTERQUEUE_GETPRINTERQUEUEVIEW = @as(u32, 11606); pub const DISPID_PRINTERQUEUEEVENT = @as(u32, 11700); pub const DISPID_PRINTERQUEUEEVENT_ONBIDIRESPONSERECEIVED = @as(u32, 11701); pub const DISPID_PRINTEREXTENSION_CONTEXT = @as(u32, 11800); pub const DISPID_PRINTEREXTENSION_CONTEXT_PRINTERQUEUE = @as(u32, 11801); pub const DISPID_PRINTEREXTENSION_CONTEXT_PRINTSCHEMATICKET = @as(u32, 11802); pub const DISPID_PRINTEREXTENSION_CONTEXT_DRIVERPROPERTIES = @as(u32, 11803); pub const DISPID_PRINTEREXTENSION_CONTEXT_USERPROPERTIES = @as(u32, 11804); pub const DISPID_PRINTEREXTENSION_REQUEST = @as(u32, 11900); pub const DISPID_PRINTEREXTENSION_REQUEST_CANCEL = @as(u32, 11901); pub const DISPID_PRINTEREXTENSION_REQUEST_COMPLETE = @as(u32, 11902); pub const DISPID_PRINTEREXTENSION_EVENTARGS = @as(u32, 12000); pub const DISPID_PRINTEREXTENSION_EVENTARGS_BIDINOTIFICATION = @as(u32, 12001); pub const DISPID_PRINTEREXTENSION_EVENTARGS_REASONID = @as(u32, 12002); pub const DISPID_PRINTEREXTENSION_EVENTARGS_REQUEST = @as(u32, 12003); pub const DISPID_PRINTEREXTENSION_EVENTARGS_SOURCEAPPLICATION = @as(u32, 12004); pub const DISPID_PRINTEREXTENSION_EVENTARGS_DETAILEDREASONID = @as(u32, 12005); pub const DISPID_PRINTEREXTENSION_EVENTARGS_WINDOWMODAL = @as(u32, 12006); pub const DISPID_PRINTEREXTENSION_EVENTARGS_WINDOWPARENT = @as(u32, 12007); pub const DISPID_PRINTEREXTENSION_CONTEXTCOLLECTION = @as(u32, 12100); pub const DISPID_PRINTEREXTENSION_CONTEXTCOLLECTION_COUNT = @as(u32, 12101); pub const DISPID_PRINTEREXTENSION_CONTEXTCOLLECTION_GETAT = @as(u32, 12102); pub const DISPID_PRINTEREXTENSION_EVENT = @as(u32, 12200); pub const DISPID_PRINTEREXTENSION_EVENT_ONDRIVEREVENT = @as(u32, 12201); pub const DISPID_PRINTEREXTENSION_EVENT_ONPRINTERQUEUESENUMERATED = @as(u32, 12202); pub const DISPID_PRINTERSCRIPTCONTEXT = @as(u32, 12300); pub const DISPID_PRINTERSCRIPTCONTEXT_DRIVERPROPERTIES = @as(u32, 12301); pub const DISPID_PRINTERSCRIPTCONTEXT_QUEUEPROPERTIES = @as(u32, 12302); pub const DISPID_PRINTERSCRIPTCONTEXT_USERPROPERTIES = @as(u32, 12303); pub const DISPID_PRINTSCHEMA_PARAMETERINITIALIZER = @as(u32, 12400); pub const DISPID_PRINTSCHEMA_PARAMETERINITIALIZER_VALUE = @as(u32, 12401); pub const DISPID_PRINTSCHEMA_PARAMETERDEFINITION = @as(u32, 12500); pub const DISPID_PRINTSCHEMA_PARAMETERDEFINITION_USERINPUTREQUIRED = @as(u32, 12501); pub const DISPID_PRINTSCHEMA_PARAMETERDEFINITION_UNITTYPE = @as(u32, 12502); pub const DISPID_PRINTSCHEMA_PARAMETERDEFINITION_DATATYPE = @as(u32, 12503); pub const DISPID_PRINTSCHEMA_PARAMETERDEFINITION_RANGEMIN = @as(u32, 12504); pub const DISPID_PRINTSCHEMA_PARAMETERDEFINITION_RANGEMAX = @as(u32, 12505); pub const DISPID_PRINTJOBCOLLECTION = @as(u32, 12600); pub const DISPID_PRINTJOBCOLLECTION_COUNT = @as(u32, 12601); pub const DISPID_PRINTJOBCOLLECTION_GETAT = @as(u32, 12602); pub const DISPID_PRINTERQUEUEVIEW = @as(u32, 12700); pub const DISPID_PRINTERQUEUEVIEW_SETVIEWRANGE = @as(u32, 12701); pub const DISPID_PRINTERQUEUEVIEW_EVENT = @as(u32, 12800); pub const DISPID_PRINTERQUEUEVIEW_EVENT_ONCHANGED = @as(u32, 12801); pub const NOTIFICATION_RELEASE = Guid.initString("ba9a5027-a70e-4ae7-9b7d-eb3e06ad4157"); pub const PRINT_APP_BIDI_NOTIFY_CHANNEL = Guid.initString("2abad223-b994-4aca-82fc-4571b1b585ac"); pub const PRINT_PORT_MONITOR_NOTIFY_CHANNEL = Guid.initString("25df3b0e-74a9-47f5-80ce-79b4b1eb5c58"); pub const GUID_DEVINTERFACE_USBPRINT = Guid.initString("28d78fad-5a12-11d1-ae5b-0000f803a8c2"); pub const GUID_DEVINTERFACE_IPPUSB_PRINT = Guid.initString("f2f40381-f46d-4e51-bce7-62de6cf2d098"); pub const CLSID_XPSRASTERIZER_FACTORY = Guid.initString("503e79bf-1d09-4764-9d72-1eb0c65967c6"); //-------------------------------------------------------------------------------- // Section: Types (370) //-------------------------------------------------------------------------------- const CLSID_BidiRequest_Value = Guid.initString("b9162a23-45f9-47cc-80f5-fe0fe9b9e1a2"); pub const CLSID_BidiRequest = &CLSID_BidiRequest_Value; const CLSID_BidiRequestContainer_Value = Guid.initString("fc5b8a24-db05-4a01-8388-22edf6c2bbba"); pub const CLSID_BidiRequestContainer = &CLSID_BidiRequestContainer_Value; const CLSID_BidiSpl_Value = Guid.initString("2a614240-a4c5-4c33-bd87-1bc709331639"); pub const CLSID_BidiSpl = &CLSID_BidiSpl_Value; pub const IBidiRequestVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, SetSchema: isize, SetInputData: isize, GetResult: isize, GetOutputData: isize, GetEnumCount: isize, }; pub const IBidiRequest = extern struct { lpVtbl: ?*IBidiRequestVtbl, }; pub const IBidiRequestContainerVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, AddRequest: isize, GetEnumObject: isize, GetRequestCount: isize, }; pub const IBidiRequestContainer = extern struct { lpVtbl: ?*IBidiRequestContainerVtbl, }; pub const IBidiSplVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, BindDevice: isize, UnbindDevice: isize, SendRecv: isize, MultiSendRecv: isize, }; pub const IBidiSpl = extern struct { lpVtbl: ?*IBidiSplVtbl, }; pub const IBidiSpl2Vtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, BindDevice: isize, UnbindDevice: isize, SendRecvXMLString: isize, SendRecvXMLStream: isize, }; pub const IBidiSpl2 = extern struct { lpVtbl: ?*IBidiSpl2Vtbl, }; pub const __MIDL___MIDL_itf_imgerror_0000_0000_0001 = extern struct { description: ?BSTR, guid: Guid, helpContext: u32, helpFile: ?BSTR, source: ?BSTR, devDescription: ?BSTR, errorID: Guid, cUserParameters: u32, aUserParameters: ?*?BSTR, userFallback: ?BSTR, exceptionID: u32, }; pub const IImgErrorInfoVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetGUID: isize, GetSource: isize, GetDescription: isize, GetHelpFile: isize, GetHelpContext: isize, GetDeveloperDescription: isize, GetUserErrorId: isize, GetUserParameterCount: isize, GetUserParameter: isize, GetUserFallback: isize, GetExceptionId: isize, DetachErrorInfo: isize, }; pub const IImgErrorInfo = extern struct { lpVtbl: ?*IImgErrorInfoVtbl, }; pub const IImgCreateErrorInfoVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, SetGUID: isize, SetSource: isize, SetDescription: isize, SetHelpFile: isize, SetHelpContext: isize, AttachToErrorInfo: isize, }; pub const IImgCreateErrorInfo = extern struct { lpVtbl: ?*IImgCreateErrorInfoVtbl, }; pub const EXpsCompressionOptions = enum(i32) { NotCompressed = 0, Normal = 1, Small = 2, Fast = 3, }; pub const Compression_NotCompressed = EXpsCompressionOptions.NotCompressed; pub const Compression_Normal = EXpsCompressionOptions.Normal; pub const Compression_Small = EXpsCompressionOptions.Small; pub const Compression_Fast = EXpsCompressionOptions.Fast; pub const EXpsFontOptions = enum(i32) { Normal = 0, Obfusticate = 1, }; pub const Font_Normal = EXpsFontOptions.Normal; pub const Font_Obfusticate = EXpsFontOptions.Obfusticate; pub const EXpsJobConsumption = enum(i32) { DocumentSequenceAdded = 0, FixedDocumentAdded = 1, FixedPageAdded = 2, }; pub const XpsJob_DocumentSequenceAdded = EXpsJobConsumption.DocumentSequenceAdded; pub const XpsJob_FixedDocumentAdded = EXpsJobConsumption.FixedDocumentAdded; pub const XpsJob_FixedPageAdded = EXpsJobConsumption.FixedPageAdded; pub const EXpsFontRestriction = enum(i32) { Installable = 0, NoEmbedding = 2, PreviewPrint = 4, Editable = 8, }; pub const Xps_Restricted_Font_Installable = EXpsFontRestriction.Installable; pub const Xps_Restricted_Font_NoEmbedding = EXpsFontRestriction.NoEmbedding; pub const Xps_Restricted_Font_PreviewPrint = EXpsFontRestriction.PreviewPrint; pub const Xps_Restricted_Font_Editable = EXpsFontRestriction.Editable; pub const IPrintReadStreamVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, Seek: isize, ReadBytes: isize, }; pub const IPrintReadStream = extern struct { lpVtbl: ?*IPrintReadStreamVtbl, }; pub const IPrintWriteStreamVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, WriteBytes: isize, Close: isize, }; pub const IPrintWriteStream = extern struct { lpVtbl: ?*IPrintWriteStreamVtbl, }; pub const IPrintWriteStreamFlushVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, FlushData: isize, }; pub const IPrintWriteStreamFlush = extern struct { lpVtbl: ?*IPrintWriteStreamFlushVtbl, }; pub const IInterFilterCommunicatorVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, RequestReader: isize, RequestWriter: isize, }; pub const IInterFilterCommunicator = extern struct { lpVtbl: ?*IInterFilterCommunicatorVtbl, }; pub const IPrintPipelineManagerControlVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, RequestShutdown: isize, FilterFinished: isize, }; pub const IPrintPipelineManagerControl = extern struct { lpVtbl: ?*IPrintPipelineManagerControlVtbl, }; pub const IPrintPipelinePropertyBagVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, AddProperty: isize, GetProperty: isize, DeleteProperty: isize, }; pub const IPrintPipelinePropertyBag = extern struct { lpVtbl: ?*IPrintPipelinePropertyBagVtbl, }; pub const IPrintPipelineProgressReportVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, ReportProgress: isize, }; pub const IPrintPipelineProgressReport = extern struct { lpVtbl: ?*IPrintPipelineProgressReportVtbl, }; pub const IPrintClassObjectFactoryVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetPrintClassObject: isize, }; pub const IPrintClassObjectFactory = extern struct { lpVtbl: ?*IPrintClassObjectFactoryVtbl, }; pub const IPrintPipelineFilterVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, InitializeFilter: isize, ShutdownOperation: isize, StartOperation: isize, }; pub const IPrintPipelineFilter = extern struct { lpVtbl: ?*IPrintPipelineFilterVtbl, }; pub const IXpsDocumentProviderVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetXpsPart: isize, }; pub const IXpsDocumentProvider = extern struct { lpVtbl: ?*IXpsDocumentProviderVtbl, }; pub const IXpsDocumentConsumerVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, SendXpsUnknown: isize, SendXpsDocument: isize, SendFixedDocumentSequence: isize, SendFixedDocument: isize, SendFixedPage: isize, CloseSender: isize, GetNewEmptyPart: isize, }; pub const IXpsDocumentConsumer = extern struct { lpVtbl: ?*IXpsDocumentConsumerVtbl, }; pub const IXpsDocumentVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetThumbnail: isize, SetThumbnail: isize, }; pub const IXpsDocument = extern struct { lpVtbl: ?*IXpsDocumentVtbl, }; pub const IFixedDocumentSequenceVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetPrintTicket: isize, SetPrintTicket: isize, }; pub const IFixedDocumentSequence = extern struct { lpVtbl: ?*IFixedDocumentSequenceVtbl, }; pub const IFixedDocumentVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetPrintTicket: isize, SetPrintTicket: isize, }; pub const IFixedDocument = extern struct { lpVtbl: ?*IFixedDocumentVtbl, }; pub const IPartBaseVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, }; pub const IPartBase = extern struct { lpVtbl: ?*IPartBaseVtbl, }; pub const IFixedPageVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, GetPrintTicket: isize, GetPagePart: isize, GetWriteStream: isize, SetPrintTicket: isize, SetPagePart: isize, DeleteResource: isize, GetXpsPartIterator: isize, }; pub const IFixedPage = extern struct { lpVtbl: ?*IFixedPageVtbl, }; pub const IPartImageVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, GetImageProperties: isize, SetImageContent: isize, }; pub const IPartImage = extern struct { lpVtbl: ?*IPartImageVtbl, }; pub const IPartFontVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, GetFontProperties: isize, SetFontContent: isize, SetFontOptions: isize, }; pub const IPartFont = extern struct { lpVtbl: ?*IPartFontVtbl, }; pub const IPartFont2Vtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, GetFontProperties: isize, SetFontContent: isize, SetFontOptions: isize, GetFontRestriction: isize, }; pub const IPartFont2 = extern struct { lpVtbl: ?*IPartFont2Vtbl, }; pub const IPartThumbnailVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, GetThumbnailProperties: isize, SetThumbnailContent: isize, }; pub const IPartThumbnail = extern struct { lpVtbl: ?*IPartThumbnailVtbl, }; pub const IPartPrintTicketVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, }; pub const IPartPrintTicket = extern struct { lpVtbl: ?*IPartPrintTicketVtbl, }; pub const IPartColorProfileVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, }; pub const IPartColorProfile = extern struct { lpVtbl: ?*IPartColorProfileVtbl, }; pub const IPartResourceDictionaryVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetUri: isize, GetStream: isize, GetPartCompression: isize, SetPartCompression: isize, }; pub const IPartResourceDictionary = extern struct { lpVtbl: ?*IPartResourceDictionaryVtbl, }; pub const IXpsPartIteratorVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, Reset: isize, Current: isize, IsDone: isize, Next: isize, }; pub const IXpsPartIterator = extern struct { lpVtbl: ?*IXpsPartIteratorVtbl, }; pub const IPrintReadStreamFactoryVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetStream: isize, }; pub const IPrintReadStreamFactory = extern struct { lpVtbl: ?*IPrintReadStreamFactoryVtbl, }; pub const IPartDiscardControlVtbl = extern struct { QueryInterface: isize, AddRef: isize, Release: isize, GetDiscardProperties: isize, }; pub const IPartDiscardControl = extern struct { lpVtbl: ?*IPartDiscardControlVtbl, }; pub const OPTPARAM = extern struct { cbSize: u16, Flags: u8, Style: u8, pData: ?*i8, IconID: usize, lParam: LPARAM, dwReserved: [2]usize, }; pub const OPTCOMBO = extern struct { cbSize: u16, Flags: u8, cListItem: u16, pListItem: ?*OPTPARAM, Sel: i32, dwReserved: [3]u32, }; pub const OPTTYPE = extern struct { cbSize: u16, Type: u8, Flags: u8, Count: u16, BegCtrlID: u16, pOptParam: ?*OPTPARAM, Style: u16, wReserved: [3]u16, dwReserved: [3]usize, }; pub const EXTPUSH = extern struct { cbSize: u16, Flags: u16, pTitle: ?*i8, Anonymous1: extern union { DlgProc: ?DLGPROC, pfnCallBack: ?FARPROC, }, IconID: usize, Anonymous2: extern union { DlgTemplateID: u16, hDlgTemplate: ?HANDLE, }, dwReserved: [3]usize, }; pub const EXTCHKBOX = extern struct { cbSize: u16, Flags: u16, pTitle: ?*i8, pSeparator: ?*i8, pCheckedName: ?*i8, IconID: usize, wReserved: [4]u16, dwReserved: [2]usize, }; pub const OIEXT = extern struct { cbSize: u16, Flags: u16, hInstCaller: ?HINSTANCE, pHelpFile: ?*i8, dwReserved: [4]usize, }; pub const OPTITEM = extern struct { cbSize: u16, Level: u8, DlgPageIdx: u8, Flags: u32, UserData: usize, pName: ?*i8, Anonymous1: extern union { Sel: i32, pSel: ?*i8, }, Anonymous2: extern union { pExtChkBox: ?*EXTCHKBOX, pExtPush: ?*EXTPUSH, }, pOptType: ?*OPTTYPE, HelpIndex: u32, DMPubID: u8, UserItemID: u8, wReserved: u16, pOIExt: ?*OIEXT, dwReserved: [3]usize, }; pub const CPSUICBPARAM = extern struct { cbSize: u16, Reason: u16, hDlg: ?HWND, pOptItem: ?*OPTITEM, cOptItem: u16, Flags: u16, pCurItem: ?*OPTITEM, Anonymous: extern union { OldSel: i32, pOldSel: ?*i8, }, UserData: usize, Result: usize, }; pub const _CPSUICALLBACK = fn( pCPSUICBParam: ?*CPSUICBPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const DLGPAGE = extern struct { cbSize: u16, Flags: u16, DlgProc: ?DLGPROC, pTabName: ?*i8, IconID: usize, Anonymous: extern union { DlgTemplateID: u16, hDlgTemplate: ?HANDLE, }, }; pub const COMPROPSHEETUI = extern struct { cbSize: u16, Flags: u16, hInstCaller: ?HINSTANCE, pCallerName: ?*i8, UserData: usize, pHelpFile: ?*i8, pfnCallBack: ?_CPSUICALLBACK, pOptItem: ?*OPTITEM, pDlgPage: ?*DLGPAGE, cOptItem: u16, cDlgPage: u16, IconID: usize, pOptItemName: ?*i8, CallerVersion: u16, OptItemVersion: u16, dwReserved: [4]usize, }; pub const SETRESULT_INFO = extern struct { cbSize: u16, wReserved: u16, hSetResult: ?HANDLE, Result: LRESULT, }; pub const INSERTPSUIPAGE_INFO = extern struct { cbSize: u16, Type: u8, Mode: u8, dwData1: usize, dwData2: usize, dwData3: usize, }; pub const PFNCOMPROPSHEET = fn( hComPropSheet: ?HANDLE, Function: u32, lParam1: LPARAM, lParam2: LPARAM, ) callconv(@import("std").os.windows.WINAPI) isize; pub const PSPINFO = extern struct { cbSize: u16, wReserved: u16, hComPropSheet: ?HANDLE, hCPSUIPage: ?HANDLE, pfnComPropSheet: ?PFNCOMPROPSHEET, }; pub const CPSUIDATABLOCK = extern struct { cbData: u32, pbData: ?*u8, }; pub const PROPSHEETUI_INFO = extern struct { cbSize: u16, Version: u16, Flags: u16, Reason: u16, hComPropSheet: ?HANDLE, pfnComPropSheet: ?PFNCOMPROPSHEET, lParamInit: LPARAM, UserData: usize, Result: usize, }; pub const PROPSHEETUI_GETICON_INFO = extern struct { cbSize: u16, Flags: u16, cxIcon: u16, cyIcon: u16, hIcon: ?HICON, }; pub const PFNPROPSHEETUI = fn( pPSUIInfo: ?*PROPSHEETUI_INFO, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const PROPSHEETUI_INFO_HEADER = extern struct { cbSize: u16, Flags: u16, pTitle: ?*i8, hWndParent: ?HWND, hInst: ?HINSTANCE, Anonymous: extern union { hIcon: ?HICON, IconID: usize, }, }; pub const PRINTER_INFO_1A = extern struct { Flags: u32, pDescription: ?PSTR, pName: ?PSTR, pComment: ?PSTR, }; pub const PRINTER_INFO_1W = extern struct { Flags: u32, pDescription: ?PWSTR, pName: ?PWSTR, pComment: ?PWSTR, }; pub const PRINTER_INFO_2A = extern struct { pServerName: ?PSTR, pPrinterName: ?PSTR, pShareName: ?PSTR, pPortName: ?PSTR, pDriverName: ?PSTR, pComment: ?PSTR, pLocation: ?PSTR, pDevMode: ?*DEVMODEA, pSepFile: ?PSTR, pPrintProcessor: ?PSTR, pDatatype: ?PSTR, pParameters: ?PSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, Attributes: u32, Priority: u32, DefaultPriority: u32, StartTime: u32, UntilTime: u32, Status: u32, cJobs: u32, AveragePPM: u32, }; pub const PRINTER_INFO_2W = extern struct { pServerName: ?PWSTR, pPrinterName: ?PWSTR, pShareName: ?PWSTR, pPortName: ?PWSTR, pDriverName: ?PWSTR, pComment: ?PWSTR, pLocation: ?PWSTR, pDevMode: ?*DEVMODEW, pSepFile: ?PWSTR, pPrintProcessor: ?PWSTR, pDatatype: ?PWSTR, pParameters: ?PWSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, Attributes: u32, Priority: u32, DefaultPriority: u32, StartTime: u32, UntilTime: u32, Status: u32, cJobs: u32, AveragePPM: u32, }; pub const PRINTER_INFO_3 = extern struct { pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, }; pub const PRINTER_INFO_4A = extern struct { pPrinterName: ?PSTR, pServerName: ?PSTR, Attributes: u32, }; pub const PRINTER_INFO_4W = extern struct { pPrinterName: ?PWSTR, pServerName: ?PWSTR, Attributes: u32, }; pub const PRINTER_INFO_5A = extern struct { pPrinterName: ?PSTR, pPortName: ?PSTR, Attributes: u32, DeviceNotSelectedTimeout: u32, TransmissionRetryTimeout: u32, }; pub const PRINTER_INFO_5W = extern struct { pPrinterName: ?PWSTR, pPortName: ?PWSTR, Attributes: u32, DeviceNotSelectedTimeout: u32, TransmissionRetryTimeout: u32, }; pub const PRINTER_INFO_6 = extern struct { dwStatus: u32, }; pub const PRINTER_INFO_7A = extern struct { pszObjectGUID: ?PSTR, dwAction: u32, }; pub const PRINTER_INFO_7W = extern struct { pszObjectGUID: ?PWSTR, dwAction: u32, }; pub const PRINTER_INFO_8A = extern struct { pDevMode: ?*DEVMODEA, }; pub const PRINTER_INFO_8W = extern struct { pDevMode: ?*DEVMODEW, }; pub const PRINTER_INFO_9A = extern struct { pDevMode: ?*DEVMODEA, }; pub const PRINTER_INFO_9W = extern struct { pDevMode: ?*DEVMODEW, }; pub const JOB_INFO_1A = extern struct { JobId: u32, pPrinterName: ?PSTR, pMachineName: ?PSTR, pUserName: ?PSTR, pDocument: ?PSTR, pDatatype: ?PSTR, pStatus: ?PSTR, Status: u32, Priority: u32, Position: u32, TotalPages: u32, PagesPrinted: u32, Submitted: SYSTEMTIME, }; pub const JOB_INFO_1W = extern struct { JobId: u32, pPrinterName: ?PWSTR, pMachineName: ?PWSTR, pUserName: ?PWSTR, pDocument: ?PWSTR, pDatatype: ?PWSTR, pStatus: ?PWSTR, Status: u32, Priority: u32, Position: u32, TotalPages: u32, PagesPrinted: u32, Submitted: SYSTEMTIME, }; pub const JOB_INFO_2A = extern struct { JobId: u32, pPrinterName: ?PSTR, pMachineName: ?PSTR, pUserName: ?PSTR, pDocument: ?PSTR, pNotifyName: ?PSTR, pDatatype: ?PSTR, pPrintProcessor: ?PSTR, pParameters: ?PSTR, pDriverName: ?PSTR, pDevMode: ?*DEVMODEA, pStatus: ?PSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, Status: u32, Priority: u32, Position: u32, StartTime: u32, UntilTime: u32, TotalPages: u32, Size: u32, Submitted: SYSTEMTIME, Time: u32, PagesPrinted: u32, }; pub const JOB_INFO_2W = extern struct { JobId: u32, pPrinterName: ?PWSTR, pMachineName: ?PWSTR, pUserName: ?PWSTR, pDocument: ?PWSTR, pNotifyName: ?PWSTR, pDatatype: ?PWSTR, pPrintProcessor: ?PWSTR, pParameters: ?PWSTR, pDriverName: ?PWSTR, pDevMode: ?*DEVMODEW, pStatus: ?PWSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, Status: u32, Priority: u32, Position: u32, StartTime: u32, UntilTime: u32, TotalPages: u32, Size: u32, Submitted: SYSTEMTIME, Time: u32, PagesPrinted: u32, }; pub const JOB_INFO_3 = extern struct { JobId: u32, NextJobId: u32, Reserved: u32, }; pub const JOB_INFO_4A = extern struct { JobId: u32, pPrinterName: ?PSTR, pMachineName: ?PSTR, pUserName: ?PSTR, pDocument: ?PSTR, pNotifyName: ?PSTR, pDatatype: ?PSTR, pPrintProcessor: ?PSTR, pParameters: ?PSTR, pDriverName: ?PSTR, pDevMode: ?*DEVMODEA, pStatus: ?PSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, Status: u32, Priority: u32, Position: u32, StartTime: u32, UntilTime: u32, TotalPages: u32, Size: u32, Submitted: SYSTEMTIME, Time: u32, PagesPrinted: u32, SizeHigh: i32, }; pub const JOB_INFO_4W = extern struct { JobId: u32, pPrinterName: ?PWSTR, pMachineName: ?PWSTR, pUserName: ?PWSTR, pDocument: ?PWSTR, pNotifyName: ?PWSTR, pDatatype: ?PWSTR, pPrintProcessor: ?PWSTR, pParameters: ?PWSTR, pDriverName: ?PWSTR, pDevMode: ?*DEVMODEW, pStatus: ?PWSTR, pSecurityDescriptor: ?*SECURITY_DESCRIPTOR, Status: u32, Priority: u32, Position: u32, StartTime: u32, UntilTime: u32, TotalPages: u32, Size: u32, Submitted: SYSTEMTIME, Time: u32, PagesPrinted: u32, SizeHigh: i32, }; pub const ADDJOB_INFO_1A = extern struct { Path: ?PSTR, JobId: u32, }; pub const ADDJOB_INFO_1W = extern struct { Path: ?PWSTR, JobId: u32, }; pub const DRIVER_INFO_1A = extern struct { pName: ?PSTR, }; pub const DRIVER_INFO_1W = extern struct { pName: ?PWSTR, }; pub const DRIVER_INFO_2A = extern struct { cVersion: u32, pName: ?PSTR, pEnvironment: ?PSTR, pDriverPath: ?PSTR, pDataFile: ?PSTR, pConfigFile: ?PSTR, }; pub const DRIVER_INFO_2W = extern struct { cVersion: u32, pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverPath: ?PWSTR, pDataFile: ?PWSTR, pConfigFile: ?PWSTR, }; pub const DRIVER_INFO_3A = extern struct { cVersion: u32, pName: ?PSTR, pEnvironment: ?PSTR, pDriverPath: ?PSTR, pDataFile: ?PSTR, pConfigFile: ?PSTR, pHelpFile: ?PSTR, pDependentFiles: ?PSTR, pMonitorName: ?PSTR, pDefaultDataType: ?PSTR, }; pub const DRIVER_INFO_3W = extern struct { cVersion: u32, pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverPath: ?PWSTR, pDataFile: ?PWSTR, pConfigFile: ?PWSTR, pHelpFile: ?PWSTR, pDependentFiles: ?PWSTR, pMonitorName: ?PWSTR, pDefaultDataType: ?PWSTR, }; pub const DRIVER_INFO_4A = extern struct { cVersion: u32, pName: ?PSTR, pEnvironment: ?PSTR, pDriverPath: ?PSTR, pDataFile: ?PSTR, pConfigFile: ?PSTR, pHelpFile: ?PSTR, pDependentFiles: ?PSTR, pMonitorName: ?PSTR, pDefaultDataType: ?PSTR, pszzPreviousNames: ?PSTR, }; pub const DRIVER_INFO_4W = extern struct { cVersion: u32, pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverPath: ?PWSTR, pDataFile: ?PWSTR, pConfigFile: ?PWSTR, pHelpFile: ?PWSTR, pDependentFiles: ?PWSTR, pMonitorName: ?PWSTR, pDefaultDataType: ?PWSTR, pszzPreviousNames: ?PWSTR, }; pub const DRIVER_INFO_5A = extern struct { cVersion: u32, pName: ?PSTR, pEnvironment: ?PSTR, pDriverPath: ?PSTR, pDataFile: ?PSTR, pConfigFile: ?PSTR, dwDriverAttributes: u32, dwConfigVersion: u32, dwDriverVersion: u32, }; pub const DRIVER_INFO_5W = extern struct { cVersion: u32, pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverPath: ?PWSTR, pDataFile: ?PWSTR, pConfigFile: ?PWSTR, dwDriverAttributes: u32, dwConfigVersion: u32, dwDriverVersion: u32, }; pub const DRIVER_INFO_6A = extern struct { cVersion: u32, pName: ?PSTR, pEnvironment: ?PSTR, pDriverPath: ?PSTR, pDataFile: ?PSTR, pConfigFile: ?PSTR, pHelpFile: ?PSTR, pDependentFiles: ?PSTR, pMonitorName: ?PSTR, pDefaultDataType: ?PSTR, pszzPreviousNames: ?PSTR, ftDriverDate: FILETIME, dwlDriverVersion: u64, pszMfgName: ?PSTR, pszOEMUrl: ?PSTR, pszHardwareID: ?PSTR, pszProvider: ?PSTR, }; pub const DRIVER_INFO_6W = extern struct { cVersion: u32, pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverPath: ?PWSTR, pDataFile: ?PWSTR, pConfigFile: ?PWSTR, pHelpFile: ?PWSTR, pDependentFiles: ?PWSTR, pMonitorName: ?PWSTR, pDefaultDataType: ?PWSTR, pszzPreviousNames: ?PWSTR, ftDriverDate: FILETIME, dwlDriverVersion: u64, pszMfgName: ?PWSTR, pszOEMUrl: ?PWSTR, pszHardwareID: ?PWSTR, pszProvider: ?PWSTR, }; pub const DRIVER_INFO_8A = extern struct { cVersion: u32, pName: ?PSTR, pEnvironment: ?PSTR, pDriverPath: ?PSTR, pDataFile: ?PSTR, pConfigFile: ?PSTR, pHelpFile: ?PSTR, pDependentFiles: ?PSTR, pMonitorName: ?PSTR, pDefaultDataType: ?PSTR, pszzPreviousNames: ?PSTR, ftDriverDate: FILETIME, dwlDriverVersion: u64, pszMfgName: ?PSTR, pszOEMUrl: ?PSTR, pszHardwareID: ?PSTR, pszProvider: ?PSTR, pszPrintProcessor: ?PSTR, pszVendorSetup: ?PSTR, pszzColorProfiles: ?PSTR, pszInfPath: ?PSTR, dwPrinterDriverAttributes: u32, pszzCoreDriverDependencies: ?PSTR, ftMinInboxDriverVerDate: FILETIME, dwlMinInboxDriverVerVersion: u64, }; pub const DRIVER_INFO_8W = extern struct { cVersion: u32, pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverPath: ?PWSTR, pDataFile: ?PWSTR, pConfigFile: ?PWSTR, pHelpFile: ?PWSTR, pDependentFiles: ?PWSTR, pMonitorName: ?PWSTR, pDefaultDataType: ?PWSTR, pszzPreviousNames: ?PWSTR, ftDriverDate: FILETIME, dwlDriverVersion: u64, pszMfgName: ?PWSTR, pszOEMUrl: ?PWSTR, pszHardwareID: ?PWSTR, pszProvider: ?PWSTR, pszPrintProcessor: ?PWSTR, pszVendorSetup: ?PWSTR, pszzColorProfiles: ?PWSTR, pszInfPath: ?PWSTR, dwPrinterDriverAttributes: u32, pszzCoreDriverDependencies: ?PWSTR, ftMinInboxDriverVerDate: FILETIME, dwlMinInboxDriverVerVersion: u64, }; pub const DOC_INFO_1A = extern struct { pDocName: ?PSTR, pOutputFile: ?PSTR, pDatatype: ?PSTR, }; pub const DOC_INFO_1W = extern struct { pDocName: ?PWSTR, pOutputFile: ?PWSTR, pDatatype: ?PWSTR, }; pub const FORM_INFO_1A = extern struct { Flags: u32, pName: ?PSTR, Size: SIZE, ImageableArea: RECTL, }; pub const FORM_INFO_1W = extern struct { Flags: u32, pName: ?PWSTR, Size: SIZE, ImageableArea: RECTL, }; pub const FORM_INFO_2A = extern struct { Flags: u32, pName: ?[*:0]const u8, Size: SIZE, ImageableArea: RECTL, pKeyword: ?[*:0]const u8, StringType: u32, pMuiDll: ?[*:0]const u8, dwResourceId: u32, pDisplayName: ?[*:0]const u8, wLangId: u16, }; pub const FORM_INFO_2W = extern struct { Flags: u32, pName: ?[*:0]const u16, Size: SIZE, ImageableArea: RECTL, pKeyword: ?[*:0]const u8, StringType: u32, pMuiDll: ?[*:0]const u16, dwResourceId: u32, pDisplayName: ?[*:0]const u16, wLangId: u16, }; pub const DOC_INFO_2A = extern struct { pDocName: ?PSTR, pOutputFile: ?PSTR, pDatatype: ?PSTR, dwMode: u32, JobId: u32, }; pub const DOC_INFO_2W = extern struct { pDocName: ?PWSTR, pOutputFile: ?PWSTR, pDatatype: ?PWSTR, dwMode: u32, JobId: u32, }; pub const DOC_INFO_3A = extern struct { pDocName: ?PSTR, pOutputFile: ?PSTR, pDatatype: ?PSTR, dwFlags: u32, }; pub const DOC_INFO_3W = extern struct { pDocName: ?PWSTR, pOutputFile: ?PWSTR, pDatatype: ?PWSTR, dwFlags: u32, }; pub const PRINTPROCESSOR_INFO_1A = extern struct { pName: ?PSTR, }; pub const PRINTPROCESSOR_INFO_1W = extern struct { pName: ?PWSTR, }; pub const PRINTPROCESSOR_CAPS_1 = extern struct { dwLevel: u32, dwNupOptions: u32, dwPageOrderFlags: u32, dwNumberOfCopies: u32, }; pub const PRINTPROCESSOR_CAPS_2 = extern struct { dwLevel: u32, dwNupOptions: u32, dwPageOrderFlags: u32, dwNumberOfCopies: u32, dwDuplexHandlingCaps: u32, dwNupDirectionCaps: u32, dwNupBorderCaps: u32, dwBookletHandlingCaps: u32, dwScalingCaps: u32, }; pub const PORT_INFO_1A = extern struct { pName: ?PSTR, }; pub const PORT_INFO_1W = extern struct { pName: ?PWSTR, }; pub const PORT_INFO_2A = extern struct { pPortName: ?PSTR, pMonitorName: ?PSTR, pDescription: ?PSTR, fPortType: u32, Reserved: u32, }; pub const PORT_INFO_2W = extern struct { pPortName: ?PWSTR, pMonitorName: ?PWSTR, pDescription: ?PWSTR, fPortType: u32, Reserved: u32, }; pub const PORT_INFO_3A = extern struct { dwStatus: u32, pszStatus: ?PSTR, dwSeverity: u32, }; pub const PORT_INFO_3W = extern struct { dwStatus: u32, pszStatus: ?PWSTR, dwSeverity: u32, }; pub const MONITOR_INFO_1A = extern struct { pName: ?PSTR, }; pub const MONITOR_INFO_1W = extern struct { pName: ?PWSTR, }; pub const MONITOR_INFO_2A = extern struct { pName: ?PSTR, pEnvironment: ?PSTR, pDLLName: ?PSTR, }; pub const MONITOR_INFO_2W = extern struct { pName: ?PWSTR, pEnvironment: ?PWSTR, pDLLName: ?PWSTR, }; pub const DATATYPES_INFO_1A = extern struct { pName: ?PSTR, }; pub const DATATYPES_INFO_1W = extern struct { pName: ?PWSTR, }; pub const PRINTER_DEFAULTSA = extern struct { pDatatype: ?PSTR, pDevMode: ?*DEVMODEA, DesiredAccess: u32, }; pub const PRINTER_DEFAULTSW = extern struct { pDatatype: ?PWSTR, pDevMode: ?*DEVMODEW, DesiredAccess: u32, }; pub const PRINTER_ENUM_VALUESA = extern struct { pValueName: ?PSTR, cbValueName: u32, dwType: u32, pData: ?*u8, cbData: u32, }; pub const PRINTER_ENUM_VALUESW = extern struct { pValueName: ?PWSTR, cbValueName: u32, dwType: u32, pData: ?*u8, cbData: u32, }; pub const PRINTER_NOTIFY_OPTIONS_TYPE = extern struct { Type: u16, Reserved0: u16, Reserved1: u32, Reserved2: u32, Count: u32, pFields: ?*u16, }; pub const PRINTER_NOTIFY_OPTIONS = extern struct { Version: u32, Flags: u32, Count: u32, pTypes: ?*PRINTER_NOTIFY_OPTIONS_TYPE, }; pub const PRINTER_NOTIFY_INFO_DATA = extern struct { Type: u16, Field: u16, Reserved: u32, Id: u32, NotifyData: extern union { adwData: [2]u32, Data: extern struct { cbBuf: u32, pBuf: ?*anyopaque, }, }, }; pub const PRINTER_NOTIFY_INFO = extern struct { Version: u32, Flags: u32, Count: u32, aData: [1]PRINTER_NOTIFY_INFO_DATA, }; pub const BINARY_CONTAINER = extern struct { cbBuf: u32, pData: ?*u8, }; pub const BIDI_DATA = extern struct { dwBidiType: u32, u: extern union { bData: BOOL, iData: i32, sData: ?PWSTR, fData: f32, biData: BINARY_CONTAINER, }, }; pub const BIDI_REQUEST_DATA = extern struct { dwReqNumber: u32, pSchema: ?PWSTR, data: BIDI_DATA, }; pub const BIDI_REQUEST_CONTAINER = extern struct { Version: u32, Flags: u32, Count: u32, aData: [1]BIDI_REQUEST_DATA, }; pub const BIDI_RESPONSE_DATA = extern struct { dwResult: u32, dwReqNumber: u32, pSchema: ?PWSTR, data: BIDI_DATA, }; pub const BIDI_RESPONSE_CONTAINER = extern struct { Version: u32, Flags: u32, Count: u32, aData: [1]BIDI_RESPONSE_DATA, }; pub const BIDI_TYPE = enum(i32) { NULL = 0, INT = 1, FLOAT = 2, BOOL = 3, STRING = 4, TEXT = 5, ENUM = 6, BLOB = 7, }; pub const BIDI_NULL = BIDI_TYPE.NULL; pub const BIDI_INT = BIDI_TYPE.INT; pub const BIDI_FLOAT = BIDI_TYPE.FLOAT; pub const BIDI_BOOL = BIDI_TYPE.BOOL; pub const BIDI_STRING = BIDI_TYPE.STRING; pub const BIDI_TEXT = BIDI_TYPE.TEXT; pub const BIDI_ENUM = BIDI_TYPE.ENUM; pub const BIDI_BLOB = BIDI_TYPE.BLOB; pub const PROVIDOR_INFO_1A = extern struct { pName: ?PSTR, pEnvironment: ?PSTR, pDLLName: ?PSTR, }; pub const PROVIDOR_INFO_1W = extern struct { pName: ?PWSTR, pEnvironment: ?PWSTR, pDLLName: ?PWSTR, }; pub const PROVIDOR_INFO_2A = extern struct { pOrder: ?PSTR, }; pub const PROVIDOR_INFO_2W = extern struct { pOrder: ?PWSTR, }; pub const PRINTER_OPTION_FLAGS = enum(i32) { NO_CACHE = 1, CACHE = 2, CLIENT_CHANGE = 4, NO_CLIENT_DATA = 8, }; pub const PRINTER_OPTION_NO_CACHE = PRINTER_OPTION_FLAGS.NO_CACHE; pub const PRINTER_OPTION_CACHE = PRINTER_OPTION_FLAGS.CACHE; pub const PRINTER_OPTION_CLIENT_CHANGE = PRINTER_OPTION_FLAGS.CLIENT_CHANGE; pub const PRINTER_OPTION_NO_CLIENT_DATA = PRINTER_OPTION_FLAGS.NO_CLIENT_DATA; pub const PRINTER_OPTIONSA = extern struct { cbSize: u32, dwFlags: u32, }; pub const PRINTER_OPTIONSW = extern struct { cbSize: u32, dwFlags: u32, }; pub const PRINTER_CONNECTION_INFO_1A = extern struct { dwFlags: u32, pszDriverName: ?PSTR, }; pub const PRINTER_CONNECTION_INFO_1W = extern struct { dwFlags: u32, pszDriverName: ?PWSTR, }; pub const CORE_PRINTER_DRIVERA = extern struct { CoreDriverGUID: Guid, ftDriverDate: FILETIME, dwlDriverVersion: u64, szPackageID: [260]CHAR, }; pub const CORE_PRINTER_DRIVERW = extern struct { CoreDriverGUID: Guid, ftDriverDate: FILETIME, dwlDriverVersion: u64, szPackageID: [260]u16, }; pub const EPrintPropertyType = enum(i32) { String = 1, Int32 = 2, Int64 = 3, Byte = 4, Time = 5, DevMode = 6, SD = 7, NotificationReply = 8, NotificationOptions = 9, Buffer = 10, }; pub const kPropertyTypeString = EPrintPropertyType.String; pub const kPropertyTypeInt32 = EPrintPropertyType.Int32; pub const kPropertyTypeInt64 = EPrintPropertyType.Int64; pub const kPropertyTypeByte = EPrintPropertyType.Byte; pub const kPropertyTypeTime = EPrintPropertyType.Time; pub const kPropertyTypeDevMode = EPrintPropertyType.DevMode; pub const kPropertyTypeSD = EPrintPropertyType.SD; pub const kPropertyTypeNotificationReply = EPrintPropertyType.NotificationReply; pub const kPropertyTypeNotificationOptions = EPrintPropertyType.NotificationOptions; pub const kPropertyTypeBuffer = EPrintPropertyType.Buffer; pub const EPrintXPSJobProgress = enum(i32) { AddingDocumentSequence = 0, DocumentSequenceAdded = 1, AddingFixedDocument = 2, FixedDocumentAdded = 3, AddingFixedPage = 4, FixedPageAdded = 5, ResourceAdded = 6, FontAdded = 7, ImageAdded = 8, XpsDocumentCommitted = 9, }; pub const kAddingDocumentSequence = EPrintXPSJobProgress.AddingDocumentSequence; pub const kDocumentSequenceAdded = EPrintXPSJobProgress.DocumentSequenceAdded; pub const kAddingFixedDocument = EPrintXPSJobProgress.AddingFixedDocument; pub const kFixedDocumentAdded = EPrintXPSJobProgress.FixedDocumentAdded; pub const kAddingFixedPage = EPrintXPSJobProgress.AddingFixedPage; pub const kFixedPageAdded = EPrintXPSJobProgress.FixedPageAdded; pub const kResourceAdded = EPrintXPSJobProgress.ResourceAdded; pub const kFontAdded = EPrintXPSJobProgress.FontAdded; pub const kImageAdded = EPrintXPSJobProgress.ImageAdded; pub const kXpsDocumentCommitted = EPrintXPSJobProgress.XpsDocumentCommitted; pub const EPrintXPSJobOperation = enum(i32) { Production = 1, Consumption = 2, }; pub const kJobProduction = EPrintXPSJobOperation.Production; pub const kJobConsumption = EPrintXPSJobOperation.Consumption; pub const PrintPropertyValue = extern struct { ePropertyType: EPrintPropertyType, value: extern union { propertyByte: u8, propertyString: ?PWSTR, propertyInt32: i32, propertyInt64: i64, propertyBlob: extern struct { cbBuf: u32, pBuf: ?*anyopaque, }, }, }; pub const PrintNamedProperty = extern struct { propertyName: ?PWSTR, propertyValue: PrintPropertyValue, }; pub const PrintPropertiesCollection = extern struct { numberOfProperties: u32, propertiesCollection: ?*PrintNamedProperty, }; pub const PRINT_EXECUTION_CONTEXT = enum(i32) { APPLICATION = 0, SPOOLER_SERVICE = 1, SPOOLER_ISOLATION_HOST = 2, FILTER_PIPELINE = 3, WOW64 = 4, }; pub const PRINT_EXECUTION_CONTEXT_APPLICATION = PRINT_EXECUTION_CONTEXT.APPLICATION; pub const PRINT_EXECUTION_CONTEXT_SPOOLER_SERVICE = PRINT_EXECUTION_CONTEXT.SPOOLER_SERVICE; pub const PRINT_EXECUTION_CONTEXT_SPOOLER_ISOLATION_HOST = PRINT_EXECUTION_CONTEXT.SPOOLER_ISOLATION_HOST; pub const PRINT_EXECUTION_CONTEXT_FILTER_PIPELINE = PRINT_EXECUTION_CONTEXT.FILTER_PIPELINE; pub const PRINT_EXECUTION_CONTEXT_WOW64 = PRINT_EXECUTION_CONTEXT.WOW64; pub const PRINT_EXECUTION_DATA = extern struct { context: PRINT_EXECUTION_CONTEXT, clientAppPID: u32, }; pub const MxdcLandscapeRotationEnums = enum(i32) { COUNTERCLOCKWISE_90_DEGREES = 90, NONE = 0, COUNTERCLOCKWISE_270_DEGREES = -90, }; pub const MXDC_LANDSCAPE_ROTATE_COUNTERCLOCKWISE_90_DEGREES = MxdcLandscapeRotationEnums.COUNTERCLOCKWISE_90_DEGREES; pub const MXDC_LANDSCAPE_ROTATE_NONE = MxdcLandscapeRotationEnums.NONE; pub const MXDC_LANDSCAPE_ROTATE_COUNTERCLOCKWISE_270_DEGREES = MxdcLandscapeRotationEnums.COUNTERCLOCKWISE_270_DEGREES; pub const MxdcImageTypeEnums = enum(i32) { JPEGHIGH_COMPRESSION = 1, JPEGMEDIUM_COMPRESSION = 2, JPEGLOW_COMPRESSION = 3, PNG = 4, }; pub const MXDC_IMAGETYPE_JPEGHIGH_COMPRESSION = MxdcImageTypeEnums.JPEGHIGH_COMPRESSION; pub const MXDC_IMAGETYPE_JPEGMEDIUM_COMPRESSION = MxdcImageTypeEnums.JPEGMEDIUM_COMPRESSION; pub const MXDC_IMAGETYPE_JPEGLOW_COMPRESSION = MxdcImageTypeEnums.JPEGLOW_COMPRESSION; pub const MXDC_IMAGETYPE_PNG = MxdcImageTypeEnums.PNG; pub const MxdcEscapeHeader = packed struct { cbInput: u32, cbOutput: u32, opCode: u32, }; pub const MxdcGetFileNameData = packed struct { cbOutput: u32, wszData: [1]u16, }; pub const MxdcS0PageData = packed struct { dwSize: u32, bData: [1]u8, }; pub const MxdcS0PageEnums = enum(i32) { TTF = 0, JPEG = 1, PNG = 2, TIFF = 3, WDP = 4, DICTIONARY = 5, ICC_PROFILE = 6, JPEG_THUMBNAIL = 7, PNG_THUMBNAIL = 8, MAX = 9, }; pub const MXDC_RESOURCE_TTF = MxdcS0PageEnums.TTF; pub const MXDC_RESOURCE_JPEG = MxdcS0PageEnums.JPEG; pub const MXDC_RESOURCE_PNG = MxdcS0PageEnums.PNG; pub const MXDC_RESOURCE_TIFF = MxdcS0PageEnums.TIFF; pub const MXDC_RESOURCE_WDP = MxdcS0PageEnums.WDP; pub const MXDC_RESOURCE_DICTIONARY = MxdcS0PageEnums.DICTIONARY; pub const MXDC_RESOURCE_ICC_PROFILE = MxdcS0PageEnums.ICC_PROFILE; pub const MXDC_RESOURCE_JPEG_THUMBNAIL = MxdcS0PageEnums.JPEG_THUMBNAIL; pub const MXDC_RESOURCE_PNG_THUMBNAIL = MxdcS0PageEnums.PNG_THUMBNAIL; pub const MXDC_RESOURCE_MAX = MxdcS0PageEnums.MAX; pub const MxdcXpsS0PageResource = packed struct { dwSize: u32, dwResourceType: u32, szUri: [260]u8, dwDataSize: u32, bData: [1]u8, }; pub const MxdcPrintTicketPassthrough = packed struct { dwDataSize: u32, bData: [1]u8, }; pub const MxdcPrintTicketEscape = extern struct { mxdcEscape: MxdcEscapeHeader, printTicketData: MxdcPrintTicketPassthrough, }; pub const MxdcS0PagePassthroughEscape = extern struct { mxdcEscape: MxdcEscapeHeader, xpsS0PageData: MxdcS0PageData, }; pub const MxdcS0PageResourceEscape = extern struct { mxdcEscape: MxdcEscapeHeader, xpsS0PageResourcePassthrough: MxdcXpsS0PageResource, }; pub const DEVICEPROPERTYHEADER = extern struct { cbSize: u16, Flags: u16, hPrinter: ?HANDLE, pszPrinterName: ?*i8, }; pub const DOCUMENTPROPERTYHEADER = extern struct { cbSize: u16, Reserved: u16, hPrinter: ?HANDLE, pszPrinterName: ?*i8, pdmIn: ?*DEVMODEA, pdmOut: ?*DEVMODEA, cbOut: u32, fMode: u32, }; pub const DEVQUERYPRINT_INFO = extern struct { cbSize: u16, Level: u16, hPrinter: ?HANDLE, pDevMode: ?*DEVMODEA, pszErrorStr: ?PWSTR, cchErrorStr: u32, cchNeeded: u32, }; pub const DRIVER_UPGRADE_INFO_1 = extern struct { pPrinterName: ?*i8, pOldDriverDirectory: ?*i8, }; pub const DRIVER_UPGRADE_INFO_2 = extern struct { pPrinterName: ?*i8, pOldDriverDirectory: ?*i8, cVersion: u32, pName: ?*i8, pEnvironment: ?*i8, pDriverPath: ?*i8, pDataFile: ?*i8, pConfigFile: ?*i8, pHelpFile: ?*i8, pDependentFiles: ?*i8, pMonitorName: ?*i8, pDefaultDataType: ?*i8, pszzPreviousNames: ?*i8, }; pub const DOCEVENT_FILTER = extern struct { cbSize: u32, cElementsAllocated: u32, cElementsNeeded: u32, cElementsReturned: u32, aDocEventCall: [1]u32, }; pub const DOCEVENT_CREATEDCPRE = extern struct { pszDriver: ?PWSTR, pszDevice: ?PWSTR, pdm: ?*DEVMODEW, bIC: BOOL, }; pub const DOCEVENT_ESCAPE = extern struct { iEscape: i32, cjInput: i32, pvInData: ?*anyopaque, }; pub const PRINTER_EVENT_ATTRIBUTES_INFO = extern struct { cbSize: u32, dwOldAttributes: u32, dwNewAttributes: u32, }; pub const ATTRIBUTE_INFO_1 = extern struct { dwJobNumberOfPagesPerSide: u32, dwDrvNumberOfPagesPerSide: u32, dwNupBorderFlags: u32, dwJobPageOrderFlags: u32, dwDrvPageOrderFlags: u32, dwJobNumberOfCopies: u32, dwDrvNumberOfCopies: u32, }; pub const ATTRIBUTE_INFO_2 = extern struct { dwJobNumberOfPagesPerSide: u32, dwDrvNumberOfPagesPerSide: u32, dwNupBorderFlags: u32, dwJobPageOrderFlags: u32, dwDrvPageOrderFlags: u32, dwJobNumberOfCopies: u32, dwDrvNumberOfCopies: u32, dwColorOptimization: u32, }; pub const ATTRIBUTE_INFO_3 = extern struct { dwJobNumberOfPagesPerSide: u32, dwDrvNumberOfPagesPerSide: u32, dwNupBorderFlags: u32, dwJobPageOrderFlags: u32, dwDrvPageOrderFlags: u32, dwJobNumberOfCopies: u32, dwDrvNumberOfCopies: u32, dwColorOptimization: u32, dmPrintQuality: i16, dmYResolution: i16, }; pub const ATTRIBUTE_INFO_4 = extern struct { dwJobNumberOfPagesPerSide: u32, dwDrvNumberOfPagesPerSide: u32, dwNupBorderFlags: u32, dwJobPageOrderFlags: u32, dwDrvPageOrderFlags: u32, dwJobNumberOfCopies: u32, dwDrvNumberOfCopies: u32, dwColorOptimization: u32, dmPrintQuality: i16, dmYResolution: i16, dwDuplexFlags: u32, dwNupDirection: u32, dwBookletFlags: u32, dwScalingPercentX: u32, dwScalingPercentY: u32, }; pub const PSCRIPT5_PRIVATE_DEVMODE = extern struct { wReserved: [57]u16, wSize: u16, }; pub const UNIDRV_PRIVATE_DEVMODE = extern struct { wReserved: [4]u16, wSize: u16, }; pub const PUBLISHERINFO = extern struct { dwMode: u32, wMinoutlinePPEM: u16, wMaxbitmapPPEM: u16, }; pub const OEMDMPARAM = extern struct { cbSize: u32, pdriverobj: ?*anyopaque, hPrinter: ?HANDLE, hModule: ?HANDLE, pPublicDMIn: ?*DEVMODEA, pPublicDMOut: ?*DEVMODEA, pOEMDMIn: ?*anyopaque, pOEMDMOut: ?*anyopaque, cbBufSize: u32, }; pub const OEM_DMEXTRAHEADER = extern struct { dwSize: u32, dwSignature: u32, dwVersion: u32, }; pub const USERDATA = extern struct { dwSize: u32, dwItemID: usize, pKeyWordName: ?PSTR, dwReserved: [8]u32, }; pub const PFN_DrvGetDriverSetting = fn( pdriverobj: ?*anyopaque, Feature: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 3? pOutput: ?*anyopaque, cbSize: u32, pcbNeeded: ?*u32, pdwOptionsReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvUpgradeRegistrySetting = fn( hPrinter: ?HANDLE, pFeature: ?[*:0]const u8, pOption: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const PFN_DrvUpdateUISetting = fn( pdriverobj: ?*anyopaque, pOptItem: ?*anyopaque, dwPreviousSelection: u32, dwMode: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const SIMULATE_CAPS_1 = extern struct { dwLevel: u32, dwPageOrderFlags: u32, dwNumberOfCopies: u32, dwCollate: u32, dwNupOptions: u32, }; pub const OEMUIPROCS = extern struct { DrvGetDriverSetting: ?PFN_DrvGetDriverSetting, DrvUpdateUISetting: ?PFN_DrvUpdateUISetting, }; pub const OEMUIOBJ = extern struct { cbSize: u32, pOemUIProcs: ?*OEMUIPROCS, }; pub const OEMCUIPCALLBACK = fn( param0: ?*CPSUICBPARAM, param1: ?*OEMCUIPPARAM, ) callconv(@import("std").os.windows.WINAPI) i32; pub const OEMCUIPPARAM = extern struct { cbSize: u32, poemuiobj: ?*OEMUIOBJ, hPrinter: ?HANDLE, pPrinterName: ?PWSTR, hModule: ?HANDLE, hOEMHeap: ?HANDLE, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, dwFlags: u32, pDrvOptItems: ?*OPTITEM, cDrvOptItems: u32, pOEMOptItems: ?*OPTITEM, cOEMOptItems: u32, pOEMUserData: ?*anyopaque, OEMCUIPCallback: ?OEMCUIPCALLBACK, }; pub const OEMUIPSPARAM = extern struct { cbSize: u32, poemuiobj: ?*OEMUIOBJ, hPrinter: ?HANDLE, pPrinterName: ?PWSTR, hModule: ?HANDLE, hOEMHeap: ?HANDLE, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, pOEMUserData: ?*anyopaque, dwFlags: u32, pOemEntry: ?*anyopaque, }; pub const EATTRIBUTE_DATATYPE = enum(i32) { UNKNOWN = 0, BOOL = 1, INT = 2, LONG = 3, DWORD = 4, ASCII = 5, UNICODE = 6, BINARY = 7, SIZE = 8, RECT = 9, CUSTOMSIZEPARAMS = 10, }; pub const kADT_UNKNOWN = EATTRIBUTE_DATATYPE.UNKNOWN; pub const kADT_BOOL = EATTRIBUTE_DATATYPE.BOOL; pub const kADT_INT = EATTRIBUTE_DATATYPE.INT; pub const kADT_LONG = EATTRIBUTE_DATATYPE.LONG; pub const kADT_DWORD = EATTRIBUTE_DATATYPE.DWORD; pub const kADT_ASCII = EATTRIBUTE_DATATYPE.ASCII; pub const kADT_UNICODE = EATTRIBUTE_DATATYPE.UNICODE; pub const kADT_BINARY = EATTRIBUTE_DATATYPE.BINARY; pub const kADT_SIZE = EATTRIBUTE_DATATYPE.SIZE; pub const kADT_RECT = EATTRIBUTE_DATATYPE.RECT; pub const kADT_CUSTOMSIZEPARAMS = EATTRIBUTE_DATATYPE.CUSTOMSIZEPARAMS; pub const CUSTOMSIZEPARAM = extern struct { dwOrder: i32, lMinVal: i32, lMaxVal: i32, }; pub const PRINT_FEATURE_OPTION = extern struct { pszFeature: ?[*:0]const u8, pszOption: ?[*:0]const u8, }; const IID_IPrintCoreHelper_Value = Guid.initString("a89ec53e-3905-49c6-9c1a-c0a88117fdb6"); pub const IID_IPrintCoreHelper = &IID_IPrintCoreHelper_Value; pub const IPrintCoreHelper = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetOption: fn( self: *const IPrintCoreHelper, // TODO: what to do with BytesParamIndex 1? pDevmode: ?*const DEVMODEA, cbSize: u32, pszFeatureRequested: ?[*:0]const u8, ppszOption: ?*?PSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOptions: fn( self: *const IPrintCoreHelper, pDevmode: ?*DEVMODEA, cbSize: u32, bResolveConflicts: BOOL, pFOPairs: ?*const PRINT_FEATURE_OPTION, cPairs: u32, pcPairsWritten: ?*u32, pdwResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumConstrainedOptions: fn( self: *const IPrintCoreHelper, pDevmode: ?*const DEVMODEA, cbSize: u32, pszFeatureKeyword: ?[*:0]const u8, pConstrainedOptionList: ?*?*?*?PSTR, pdwNumOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WhyConstrained: fn( self: *const IPrintCoreHelper, // TODO: what to do with BytesParamIndex 1? pDevmode: ?*const DEVMODEA, cbSize: u32, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, ppFOConstraints: ?*const ?*PRINT_FEATURE_OPTION, pdwNumOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumFeatures: fn( self: *const IPrintCoreHelper, pFeatureList: ?*?*?*?PSTR, pdwNumFeatures: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOptions: fn( self: *const IPrintCoreHelper, pszFeatureKeyword: ?[*:0]const u8, pOptionList: ?*?*?*?PSTR, pdwNumOptions: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFontSubstitution: fn( self: *const IPrintCoreHelper, pszTrueTypeFontName: ?[*:0]const u16, ppszDevFontName: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetFontSubstitution: fn( self: *const IPrintCoreHelper, pszTrueTypeFontName: ?[*:0]const u16, pszDevFontName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateInstanceOfMSXMLObject: fn( self: *const IPrintCoreHelper, rclsid: ?*const Guid, pUnkOuter: ?*IUnknown, dwClsContext: u32, riid: ?*const Guid, ppv: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_GetOption(self: *const T, pDevmode: ?*const DEVMODEA, cbSize: u32, pszFeatureRequested: ?[*:0]const u8, ppszOption: ?*?PSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).GetOption(@ptrCast(*const IPrintCoreHelper, self), pDevmode, cbSize, pszFeatureRequested, ppszOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_SetOptions(self: *const T, pDevmode: ?*DEVMODEA, cbSize: u32, bResolveConflicts: BOOL, pFOPairs: ?*const PRINT_FEATURE_OPTION, cPairs: u32, pcPairsWritten: ?*u32, pdwResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).SetOptions(@ptrCast(*const IPrintCoreHelper, self), pDevmode, cbSize, bResolveConflicts, pFOPairs, cPairs, pcPairsWritten, pdwResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_EnumConstrainedOptions(self: *const T, pDevmode: ?*const DEVMODEA, cbSize: u32, pszFeatureKeyword: ?[*:0]const u8, pConstrainedOptionList: ?*?*?*?PSTR, pdwNumOptions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).EnumConstrainedOptions(@ptrCast(*const IPrintCoreHelper, self), pDevmode, cbSize, pszFeatureKeyword, pConstrainedOptionList, pdwNumOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_WhyConstrained(self: *const T, pDevmode: ?*const DEVMODEA, cbSize: u32, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, ppFOConstraints: ?*const ?*PRINT_FEATURE_OPTION, pdwNumOptions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).WhyConstrained(@ptrCast(*const IPrintCoreHelper, self), pDevmode, cbSize, pszFeatureKeyword, pszOptionKeyword, ppFOConstraints, pdwNumOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_EnumFeatures(self: *const T, pFeatureList: ?*?*?*?PSTR, pdwNumFeatures: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).EnumFeatures(@ptrCast(*const IPrintCoreHelper, self), pFeatureList, pdwNumFeatures); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_EnumOptions(self: *const T, pszFeatureKeyword: ?[*:0]const u8, pOptionList: ?*?*?*?PSTR, pdwNumOptions: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).EnumOptions(@ptrCast(*const IPrintCoreHelper, self), pszFeatureKeyword, pOptionList, pdwNumOptions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_GetFontSubstitution(self: *const T, pszTrueTypeFontName: ?[*:0]const u16, ppszDevFontName: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).GetFontSubstitution(@ptrCast(*const IPrintCoreHelper, self), pszTrueTypeFontName, ppszDevFontName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_SetFontSubstitution(self: *const T, pszTrueTypeFontName: ?[*:0]const u16, pszDevFontName: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).SetFontSubstitution(@ptrCast(*const IPrintCoreHelper, self), pszTrueTypeFontName, pszDevFontName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelper_CreateInstanceOfMSXMLObject(self: *const T, rclsid: ?*const Guid, pUnkOuter: ?*IUnknown, dwClsContext: u32, riid: ?*const Guid, ppv: ?*?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelper.VTable, self.vtable).CreateInstanceOfMSXMLObject(@ptrCast(*const IPrintCoreHelper, self), rclsid, pUnkOuter, dwClsContext, riid, ppv); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintCoreHelperUni_Value = Guid.initString("7e8e51d6-e5ee-4426-817b-958b9444eb79"); pub const IID_IPrintCoreHelperUni = &IID_IPrintCoreHelperUni_Value; pub const IPrintCoreHelperUni = extern struct { pub const VTable = extern struct { base: IPrintCoreHelper.VTable, CreateGDLSnapshot: fn( self: *const IPrintCoreHelperUni, pDevmode: ?*DEVMODEA, cbSize: u32, dwFlags: u32, ppSnapshotStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreateDefaultGDLSnapshot: fn( self: *const IPrintCoreHelperUni, dwFlags: u32, ppSnapshotStream: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintCoreHelper.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelperUni_CreateGDLSnapshot(self: *const T, pDevmode: ?*DEVMODEA, cbSize: u32, dwFlags: u32, ppSnapshotStream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelperUni.VTable, self.vtable).CreateGDLSnapshot(@ptrCast(*const IPrintCoreHelperUni, self), pDevmode, cbSize, dwFlags, ppSnapshotStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelperUni_CreateDefaultGDLSnapshot(self: *const T, dwFlags: u32, ppSnapshotStream: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelperUni.VTable, self.vtable).CreateDefaultGDLSnapshot(@ptrCast(*const IPrintCoreHelperUni, self), dwFlags, ppSnapshotStream); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintCoreHelperUni2_Value = Guid.initString("6c8afdfc-ead0-4d2d-8071-9bf0175a6c3a"); pub const IID_IPrintCoreHelperUni2 = &IID_IPrintCoreHelperUni2_Value; pub const IPrintCoreHelperUni2 = extern struct { pub const VTable = extern struct { base: IPrintCoreHelperUni.VTable, GetNamedCommand: fn( self: *const IPrintCoreHelperUni2, // TODO: what to do with BytesParamIndex 1? pDevmode: ?*DEVMODEA, cbSize: u32, pszCommandName: ?[*:0]const u16, ppCommandBytes: ?*?*u8, pcbCommandSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintCoreHelperUni.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelperUni2_GetNamedCommand(self: *const T, pDevmode: ?*DEVMODEA, cbSize: u32, pszCommandName: ?[*:0]const u16, ppCommandBytes: ?*?*u8, pcbCommandSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelperUni2.VTable, self.vtable).GetNamedCommand(@ptrCast(*const IPrintCoreHelperUni2, self), pDevmode, cbSize, pszCommandName, ppCommandBytes, pcbCommandSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintCoreHelperPS_Value = Guid.initString("c2c14f6f-95d3-4d63-96cf-6bd9e6c907c2"); pub const IID_IPrintCoreHelperPS = &IID_IPrintCoreHelperPS_Value; pub const IPrintCoreHelperPS = extern struct { pub const VTable = extern struct { base: IPrintCoreHelper.VTable, GetGlobalAttribute: fn( self: *const IPrintCoreHelperPS, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, ppbData: ?*?*u8, pcbSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFeatureAttribute: fn( self: *const IPrintCoreHelperPS, pszFeatureKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, ppbData: ?*?*u8, pcbSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOptionAttribute: fn( self: *const IPrintCoreHelperPS, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, ppbData: ?*?*u8, pcbSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintCoreHelper.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelperPS_GetGlobalAttribute(self: *const T, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, ppbData: ?*?*u8, pcbSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelperPS.VTable, self.vtable).GetGlobalAttribute(@ptrCast(*const IPrintCoreHelperPS, self), pszAttribute, pdwDataType, ppbData, pcbSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelperPS_GetFeatureAttribute(self: *const T, pszFeatureKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, ppbData: ?*?*u8, pcbSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelperPS.VTable, self.vtable).GetFeatureAttribute(@ptrCast(*const IPrintCoreHelperPS, self), pszFeatureKeyword, pszAttribute, pdwDataType, ppbData, pcbSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreHelperPS_GetOptionAttribute(self: *const T, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, ppbData: ?*?*u8, pcbSize: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreHelperPS.VTable, self.vtable).GetOptionAttribute(@ptrCast(*const IPrintCoreHelperPS, self), pszFeatureKeyword, pszOptionKeyword, pszAttribute, pdwDataType, ppbData, pcbSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintOemCommon_Value = Guid.initString("7f42285e-91d5-11d1-8820-00c04fb961ec"); pub const IID_IPrintOemCommon = &IID_IPrintOemCommon_Value; pub const IPrintOemCommon = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetInfo: fn( self: *const IPrintOemCommon, dwMode: u32, // TODO: what to do with BytesParamIndex 2? pBuffer: ?*anyopaque, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DevMode: fn( self: *const IPrintOemCommon, dwMode: u32, pOemDMParam: ?*OEMDMPARAM, ) 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 IPrintOemCommon_GetInfo(self: *const T, dwMode: u32, pBuffer: ?*anyopaque, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemCommon.VTable, self.vtable).GetInfo(@ptrCast(*const IPrintOemCommon, self), dwMode, pBuffer, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemCommon_DevMode(self: *const T, dwMode: u32, pOemDMParam: ?*OEMDMPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemCommon.VTable, self.vtable).DevMode(@ptrCast(*const IPrintOemCommon, self), dwMode, pOemDMParam); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintOemUI_Value = Guid.initString("c6a7a9d0-774c-11d1-947f-00a0c90640b8"); pub const IID_IPrintOemUI = &IID_IPrintOemUI_Value; pub const IPrintOemUI = extern struct { pub const VTable = extern struct { base: IPrintOemCommon.VTable, PublishDriverInterface: fn( self: *const IPrintOemUI, pIUnknown: ?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommonUIProp: fn( self: *const IPrintOemUI, dwMode: u32, pOemCUIPParam: ?*OEMCUIPPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DocumentPropertySheets: fn( self: *const IPrintOemUI, pPSUIInfo: ?*PROPSHEETUI_INFO, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DevicePropertySheets: fn( self: *const IPrintOemUI, pPSUIInfo: ?*PROPSHEETUI_INFO, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DevQueryPrintEx: fn( self: *const IPrintOemUI, poemuiobj: ?*OEMUIOBJ, pDQPInfo: ?*DEVQUERYPRINT_INFO, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DeviceCapabilitiesA: fn( self: *const IPrintOemUI, poemuiobj: ?*OEMUIOBJ, hPrinter: ?HANDLE, pDeviceName: ?PWSTR, wCapability: u16, pOutput: ?*anyopaque, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, dwOld: u32, dwResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpgradePrinter: fn( self: *const IPrintOemUI, dwLevel: u32, pDriverUpgradeInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, PrinterEvent: fn( self: *const IPrintOemUI, pPrinterName: ?PWSTR, iDriverEvent: i32, dwFlags: u32, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DriverEvent: fn( self: *const IPrintOemUI, dwDriverEvent: u32, dwLevel: u32, pDriverInfo: ?*u8, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryColorProfile: fn( self: *const IPrintOemUI, hPrinter: ?HANDLE, poemuiobj: ?*OEMUIOBJ, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, ulQueryMode: u32, pvProfileData: [*]u8, pcbProfileData: ?*u32, pflProfileData: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FontInstallerDlgProc: fn( self: *const IPrintOemUI, hWnd: ?HWND, usMsg: u32, wParam: WPARAM, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UpdateExternalFonts: fn( self: *const IPrintOemUI, hPrinter: ?HANDLE, hHeap: ?HANDLE, pwstrCartridges: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintOemCommon.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_PublishDriverInterface(self: *const T, pIUnknown: ?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).PublishDriverInterface(@ptrCast(*const IPrintOemUI, self), pIUnknown); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_CommonUIProp(self: *const T, dwMode: u32, pOemCUIPParam: ?*OEMCUIPPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).CommonUIProp(@ptrCast(*const IPrintOemUI, self), dwMode, pOemCUIPParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_DocumentPropertySheets(self: *const T, pPSUIInfo: ?*PROPSHEETUI_INFO, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).DocumentPropertySheets(@ptrCast(*const IPrintOemUI, self), pPSUIInfo, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_DevicePropertySheets(self: *const T, pPSUIInfo: ?*PROPSHEETUI_INFO, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).DevicePropertySheets(@ptrCast(*const IPrintOemUI, self), pPSUIInfo, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_DevQueryPrintEx(self: *const T, poemuiobj: ?*OEMUIOBJ, pDQPInfo: ?*DEVQUERYPRINT_INFO, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).DevQueryPrintEx(@ptrCast(*const IPrintOemUI, self), poemuiobj, pDQPInfo, pPublicDM, pOEMDM); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_DeviceCapabilitiesA(self: *const T, poemuiobj: ?*OEMUIOBJ, hPrinter: ?HANDLE, pDeviceName: ?PWSTR, wCapability: u16, pOutput: ?*anyopaque, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, dwOld: u32, dwResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).DeviceCapabilitiesA(@ptrCast(*const IPrintOemUI, self), poemuiobj, hPrinter, pDeviceName, wCapability, pOutput, pPublicDM, pOEMDM, dwOld, dwResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_UpgradePrinter(self: *const T, dwLevel: u32, pDriverUpgradeInfo: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).UpgradePrinter(@ptrCast(*const IPrintOemUI, self), dwLevel, pDriverUpgradeInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_PrinterEvent(self: *const T, pPrinterName: ?PWSTR, iDriverEvent: i32, dwFlags: u32, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).PrinterEvent(@ptrCast(*const IPrintOemUI, self), pPrinterName, iDriverEvent, dwFlags, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_DriverEvent(self: *const T, dwDriverEvent: u32, dwLevel: u32, pDriverInfo: ?*u8, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).DriverEvent(@ptrCast(*const IPrintOemUI, self), dwDriverEvent, dwLevel, pDriverInfo, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_QueryColorProfile(self: *const T, hPrinter: ?HANDLE, poemuiobj: ?*OEMUIOBJ, pPublicDM: ?*DEVMODEA, pOEMDM: ?*anyopaque, ulQueryMode: u32, pvProfileData: [*]u8, pcbProfileData: ?*u32, pflProfileData: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).QueryColorProfile(@ptrCast(*const IPrintOemUI, self), hPrinter, poemuiobj, pPublicDM, pOEMDM, ulQueryMode, pvProfileData, pcbProfileData, pflProfileData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_FontInstallerDlgProc(self: *const T, hWnd: ?HWND, usMsg: u32, wParam: WPARAM, lParam: LPARAM) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).FontInstallerDlgProc(@ptrCast(*const IPrintOemUI, self), hWnd, usMsg, wParam, lParam); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI_UpdateExternalFonts(self: *const T, hPrinter: ?HANDLE, hHeap: ?HANDLE, pwstrCartridges: ?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI.VTable, self.vtable).UpdateExternalFonts(@ptrCast(*const IPrintOemUI, self), hPrinter, hHeap, pwstrCartridges); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintOemUI2_Value = Guid.initString("292515f9-b54b-489b-9275-bab56821395e"); pub const IID_IPrintOemUI2 = &IID_IPrintOemUI2_Value; pub const IPrintOemUI2 = extern struct { pub const VTable = extern struct { base: IPrintOemUI.VTable, QueryJobAttributes: fn( self: *const IPrintOemUI2, hPrinter: ?HANDLE, pDevmode: ?*DEVMODEA, dwLevel: u32, lpAttributeInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, HideStandardUI: fn( self: *const IPrintOemUI2, dwMode: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DocumentEvent: fn( self: *const IPrintOemUI2, hPrinter: ?HANDLE, hdc: ?HDC, iEsc: i32, cbIn: u32, pvIn: ?*anyopaque, cbOut: u32, pvOut: ?*anyopaque, piResult: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintOemUI.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI2_QueryJobAttributes(self: *const T, hPrinter: ?HANDLE, pDevmode: ?*DEVMODEA, dwLevel: u32, lpAttributeInfo: ?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI2.VTable, self.vtable).QueryJobAttributes(@ptrCast(*const IPrintOemUI2, self), hPrinter, pDevmode, dwLevel, lpAttributeInfo); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI2_HideStandardUI(self: *const T, dwMode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI2.VTable, self.vtable).HideStandardUI(@ptrCast(*const IPrintOemUI2, self), dwMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUI2_DocumentEvent(self: *const T, hPrinter: ?HANDLE, hdc: ?HDC, iEsc: i32, cbIn: u32, pvIn: ?*anyopaque, cbOut: u32, pvOut: ?*anyopaque, piResult: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUI2.VTable, self.vtable).DocumentEvent(@ptrCast(*const IPrintOemUI2, self), hPrinter, hdc, iEsc, cbIn, pvIn, cbOut, pvOut, piResult); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintOemUIMXDC_Value = Guid.initString("7349d725-e2c1-4dca-afb5-c13e91bc9306"); pub const IID_IPrintOemUIMXDC = &IID_IPrintOemUIMXDC_Value; pub const IPrintOemUIMXDC = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AdjustImageableArea: fn( self: *const IPrintOemUIMXDC, hPrinter: ?HANDLE, cbDevMode: u32, pDevMode: ?*const DEVMODEA, cbOEMDM: u32, pOEMDM: ?*const anyopaque, prclImageableArea: ?*RECTL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AdjustImageCompression: fn( self: *const IPrintOemUIMXDC, hPrinter: ?HANDLE, cbDevMode: u32, pDevMode: ?*const DEVMODEA, cbOEMDM: u32, pOEMDM: ?*const anyopaque, pCompressionMode: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AdjustDPI: fn( self: *const IPrintOemUIMXDC, hPrinter: ?HANDLE, cbDevMode: u32, pDevMode: ?*const DEVMODEA, cbOEMDM: u32, pOEMDM: ?*const anyopaque, pDPI: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUIMXDC_AdjustImageableArea(self: *const T, hPrinter: ?HANDLE, cbDevMode: u32, pDevMode: ?*const DEVMODEA, cbOEMDM: u32, pOEMDM: ?*const anyopaque, prclImageableArea: ?*RECTL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUIMXDC.VTable, self.vtable).AdjustImageableArea(@ptrCast(*const IPrintOemUIMXDC, self), hPrinter, cbDevMode, pDevMode, cbOEMDM, pOEMDM, prclImageableArea); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUIMXDC_AdjustImageCompression(self: *const T, hPrinter: ?HANDLE, cbDevMode: u32, pDevMode: ?*const DEVMODEA, cbOEMDM: u32, pOEMDM: ?*const anyopaque, pCompressionMode: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUIMXDC.VTable, self.vtable).AdjustImageCompression(@ptrCast(*const IPrintOemUIMXDC, self), hPrinter, cbDevMode, pDevMode, cbOEMDM, pOEMDM, pCompressionMode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemUIMXDC_AdjustDPI(self: *const T, hPrinter: ?HANDLE, cbDevMode: u32, pDevMode: ?*const DEVMODEA, cbOEMDM: u32, pOEMDM: ?*const anyopaque, pDPI: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemUIMXDC.VTable, self.vtable).AdjustDPI(@ptrCast(*const IPrintOemUIMXDC, self), hPrinter, cbDevMode, pDevMode, cbOEMDM, pOEMDM, pDPI); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintOemDriverUI_Value = Guid.initString("92b05d50-78bc-11d1-9480-00a0c90640b8"); pub const IID_IPrintOemDriverUI = &IID_IPrintOemDriverUI_Value; pub const IPrintOemDriverUI = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, DrvGetDriverSetting: fn( self: *const IPrintOemDriverUI, pci: ?*anyopaque, Feature: ?[*:0]const u8, pOutput: ?*anyopaque, cbSize: u32, pcbNeeded: ?*u32, pdwOptionsReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DrvUpgradeRegistrySetting: fn( self: *const IPrintOemDriverUI, hPrinter: ?HANDLE, pFeature: ?[*:0]const u8, pOption: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DrvUpdateUISetting: fn( self: *const IPrintOemDriverUI, pci: ?*anyopaque, pOptItem: ?*anyopaque, dwPreviousSelection: u32, dwMode: 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 IPrintOemDriverUI_DrvGetDriverSetting(self: *const T, pci: ?*anyopaque, Feature: ?[*:0]const u8, pOutput: ?*anyopaque, cbSize: u32, pcbNeeded: ?*u32, pdwOptionsReturned: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemDriverUI.VTable, self.vtable).DrvGetDriverSetting(@ptrCast(*const IPrintOemDriverUI, self), pci, Feature, pOutput, cbSize, pcbNeeded, pdwOptionsReturned); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemDriverUI_DrvUpgradeRegistrySetting(self: *const T, hPrinter: ?HANDLE, pFeature: ?[*:0]const u8, pOption: ?[*:0]const u8) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemDriverUI.VTable, self.vtable).DrvUpgradeRegistrySetting(@ptrCast(*const IPrintOemDriverUI, self), hPrinter, pFeature, pOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintOemDriverUI_DrvUpdateUISetting(self: *const T, pci: ?*anyopaque, pOptItem: ?*anyopaque, dwPreviousSelection: u32, dwMode: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintOemDriverUI.VTable, self.vtable).DrvUpdateUISetting(@ptrCast(*const IPrintOemDriverUI, self), pci, pOptItem, dwPreviousSelection, dwMode); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintCoreUI2_Value = Guid.initString("085ccfca-3adf-4c9e-b491-d851a6edc997"); pub const IID_IPrintCoreUI2 = &IID_IPrintCoreUI2_Value; pub const IPrintCoreUI2 = extern struct { pub const VTable = extern struct { base: IPrintOemDriverUI.VTable, GetOptions: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, // TODO: what to do with BytesParamIndex 3? pmszFeaturesRequested: ?*i8, cbIn: u32, // TODO: what to do with BytesParamIndex 5? pmszFeatureOptionBuf: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetOptions: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, // TODO: what to do with BytesParamIndex 3? pmszFeatureOptionBuf: ?*i8, cbIn: u32, pdwResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumConstrainedOptions: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 4? pmszConstrainedOptionList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, WhyConstrained: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 5? pmszReasonList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetGlobalAttribute: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, // TODO: what to do with BytesParamIndex 5? pbData: ?*u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFeatureAttribute: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, // TODO: what to do with BytesParamIndex 6? pbData: ?*u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOptionAttribute: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, // TODO: what to do with BytesParamIndex 7? pbData: ?*u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumFeatures: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, // TODO: what to do with BytesParamIndex 3? pmszFeatureList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, EnumOptions: fn( self: *const IPrintCoreUI2, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 4? pmszOptionList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QuerySimulationSupport: fn( self: *const IPrintCoreUI2, hPrinter: ?HANDLE, dwLevel: u32, // TODO: what to do with BytesParamIndex 3? pCaps: ?*u8, cbSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintOemDriverUI.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_GetOptions(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pmszFeaturesRequested: ?*i8, cbIn: u32, pmszFeatureOptionBuf: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).GetOptions(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pmszFeaturesRequested, cbIn, pmszFeatureOptionBuf, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_SetOptions(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pmszFeatureOptionBuf: ?*i8, cbIn: u32, pdwResult: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).SetOptions(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pmszFeatureOptionBuf, cbIn, pdwResult); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_EnumConstrainedOptions(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pmszConstrainedOptionList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).EnumConstrainedOptions(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pszFeatureKeyword, pmszConstrainedOptionList, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_WhyConstrained(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, pmszReasonList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).WhyConstrained(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pszFeatureKeyword, pszOptionKeyword, pmszReasonList, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_GetGlobalAttribute(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, pbData: ?*u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).GetGlobalAttribute(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pszAttribute, pdwDataType, pbData, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_GetFeatureAttribute(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, pbData: ?*u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).GetFeatureAttribute(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pszFeatureKeyword, pszAttribute, pdwDataType, pbData, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_GetOptionAttribute(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pszOptionKeyword: ?[*:0]const u8, pszAttribute: ?[*:0]const u8, pdwDataType: ?*u32, pbData: ?*u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).GetOptionAttribute(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pszFeatureKeyword, pszOptionKeyword, pszAttribute, pdwDataType, pbData, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_EnumFeatures(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pmszFeatureList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).EnumFeatures(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pmszFeatureList, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_EnumOptions(self: *const T, poemuiobj: ?*OEMUIOBJ, dwFlags: u32, pszFeatureKeyword: ?[*:0]const u8, pmszOptionList: ?[*]u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).EnumOptions(@ptrCast(*const IPrintCoreUI2, self), poemuiobj, dwFlags, pszFeatureKeyword, pmszOptionList, cbSize, pcbNeeded); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintCoreUI2_QuerySimulationSupport(self: *const T, hPrinter: ?HANDLE, dwLevel: u32, pCaps: ?*u8, cbSize: u32, pcbNeeded: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintCoreUI2.VTable, self.vtable).QuerySimulationSupport(@ptrCast(*const IPrintCoreUI2, self), hPrinter, dwLevel, pCaps, cbSize, pcbNeeded); } };} pub usingnamespace MethodMixin(@This()); }; pub const SHIMOPTS = enum(i32) { DEFAULT = 0, NOSNAPSHOT = 1, }; pub const PTSHIM_DEFAULT = SHIMOPTS.DEFAULT; pub const PTSHIM_NOSNAPSHOT = SHIMOPTS.NOSNAPSHOT; const IID_IPrintTicketProvider_Value = Guid.initString("bb5116db-0a23-4c3a-a6b6-89e5558dfb5d"); pub const IID_IPrintTicketProvider = &IID_IPrintTicketProvider_Value; pub const IPrintTicketProvider = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetSupportedVersions: fn( self: *const IPrintTicketProvider, hPrinter: ?HANDLE, ppVersions: ?*?*i32, cVersions: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, BindPrinter: fn( self: *const IPrintTicketProvider, hPrinter: ?HANDLE, version: i32, pOptions: ?*SHIMOPTS, pDevModeFlags: ?*u32, cNamespaces: ?*i32, ppNamespaces: ?*?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, QueryDeviceNamespace: fn( self: *const IPrintTicketProvider, pDefaultNamespace: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConvertPrintTicketToDevMode: fn( self: *const IPrintTicketProvider, pPrintTicket: ?*IXMLDOMDocument2, cbDevmodeIn: u32, pDevmodeIn: ?*DEVMODEA, pcbDevmodeOut: ?*u32, ppDevmodeOut: ?*?*DEVMODEA, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ConvertDevModeToPrintTicket: fn( self: *const IPrintTicketProvider, cbDevmode: u32, pDevmode: ?*DEVMODEA, pPrintTicket: ?*IXMLDOMDocument2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrintCapabilities: fn( self: *const IPrintTicketProvider, pPrintTicket: ?*IXMLDOMDocument2, ppCapabilities: ?*?*IXMLDOMDocument2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ValidatePrintTicket: fn( self: *const IPrintTicketProvider, pBaseTicket: ?*IXMLDOMDocument2, ) 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 IPrintTicketProvider_GetSupportedVersions(self: *const T, hPrinter: ?HANDLE, ppVersions: ?*?*i32, cVersions: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).GetSupportedVersions(@ptrCast(*const IPrintTicketProvider, self), hPrinter, ppVersions, cVersions); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider_BindPrinter(self: *const T, hPrinter: ?HANDLE, version: i32, pOptions: ?*SHIMOPTS, pDevModeFlags: ?*u32, cNamespaces: ?*i32, ppNamespaces: ?*?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).BindPrinter(@ptrCast(*const IPrintTicketProvider, self), hPrinter, version, pOptions, pDevModeFlags, cNamespaces, ppNamespaces); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider_QueryDeviceNamespace(self: *const T, pDefaultNamespace: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).QueryDeviceNamespace(@ptrCast(*const IPrintTicketProvider, self), pDefaultNamespace); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider_ConvertPrintTicketToDevMode(self: *const T, pPrintTicket: ?*IXMLDOMDocument2, cbDevmodeIn: u32, pDevmodeIn: ?*DEVMODEA, pcbDevmodeOut: ?*u32, ppDevmodeOut: ?*?*DEVMODEA) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).ConvertPrintTicketToDevMode(@ptrCast(*const IPrintTicketProvider, self), pPrintTicket, cbDevmodeIn, pDevmodeIn, pcbDevmodeOut, ppDevmodeOut); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider_ConvertDevModeToPrintTicket(self: *const T, cbDevmode: u32, pDevmode: ?*DEVMODEA, pPrintTicket: ?*IXMLDOMDocument2) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).ConvertDevModeToPrintTicket(@ptrCast(*const IPrintTicketProvider, self), cbDevmode, pDevmode, pPrintTicket); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider_GetPrintCapabilities(self: *const T, pPrintTicket: ?*IXMLDOMDocument2, ppCapabilities: ?*?*IXMLDOMDocument2) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).GetPrintCapabilities(@ptrCast(*const IPrintTicketProvider, self), pPrintTicket, ppCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider_ValidatePrintTicket(self: *const T, pBaseTicket: ?*IXMLDOMDocument2) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider.VTable, self.vtable).ValidatePrintTicket(@ptrCast(*const IPrintTicketProvider, self), pBaseTicket); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintTicketProvider2_Value = Guid.initString("b8a70ab2-3dfc-4fec-a074-511b13c651cb"); pub const IID_IPrintTicketProvider2 = &IID_IPrintTicketProvider2_Value; pub const IPrintTicketProvider2 = extern struct { pub const VTable = extern struct { base: IPrintTicketProvider.VTable, GetPrintDeviceCapabilities: fn( self: *const IPrintTicketProvider2, pPrintTicket: ?*IXMLDOMDocument2, ppDeviceCapabilities: ?*?*IXMLDOMDocument2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrintDeviceResources: fn( self: *const IPrintTicketProvider2, pszLocaleName: ?[*:0]const u16, pPrintTicket: ?*IXMLDOMDocument2, ppDeviceResources: ?*?*IXMLDOMDocument2, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintTicketProvider.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider2_GetPrintDeviceCapabilities(self: *const T, pPrintTicket: ?*IXMLDOMDocument2, ppDeviceCapabilities: ?*?*IXMLDOMDocument2) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider2.VTable, self.vtable).GetPrintDeviceCapabilities(@ptrCast(*const IPrintTicketProvider2, self), pPrintTicket, ppDeviceCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintTicketProvider2_GetPrintDeviceResources(self: *const T, pszLocaleName: ?[*:0]const u16, pPrintTicket: ?*IXMLDOMDocument2, ppDeviceResources: ?*?*IXMLDOMDocument2) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintTicketProvider2.VTable, self.vtable).GetPrintDeviceResources(@ptrCast(*const IPrintTicketProvider2, self), pszLocaleName, pPrintTicket, ppDeviceResources); } };} pub usingnamespace MethodMixin(@This()); }; const CLSID_PrinterQueue_Value = Guid.initString("eb54c230-798c-4c9e-b461-29fad04039b1"); pub const CLSID_PrinterQueue = &CLSID_PrinterQueue_Value; const CLSID_PrinterQueueView_Value = Guid.initString("eb54c231-798c-4c9e-b461-29fad04039b1"); pub const CLSID_PrinterQueueView = &CLSID_PrinterQueueView_Value; const CLSID_PrintSchemaAsyncOperation_Value = Guid.initString("43b2f83d-10f2-48ab-831b-55fdbdbd34a4"); pub const CLSID_PrintSchemaAsyncOperation = &CLSID_PrintSchemaAsyncOperation_Value; const CLSID_PrinterExtensionManager_Value = Guid.initString("331b60da-9e90-4dd0-9c84-eac4e659b61f"); pub const CLSID_PrinterExtensionManager = &CLSID_PrinterExtensionManager_Value; const IID_IPrintSchemaElement_Value = Guid.initString("724c1646-e64b-4bbf-8eb4-d45e4fd580da"); pub const IID_IPrintSchemaElement = &IID_IPrintSchemaElement_Value; pub const IPrintSchemaElement = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_XmlNode: fn( self: *const IPrintSchemaElement, ppXmlNode: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IPrintSchemaElement, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_NamespaceUri: fn( self: *const IPrintSchemaElement, pbstrNamespaceUri: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaElement_get_XmlNode(self: *const T, ppXmlNode: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaElement.VTable, self.vtable).get_XmlNode(@ptrCast(*const IPrintSchemaElement, self), ppXmlNode); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaElement_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaElement.VTable, self.vtable).get_Name(@ptrCast(*const IPrintSchemaElement, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaElement_get_NamespaceUri(self: *const T, pbstrNamespaceUri: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaElement.VTable, self.vtable).get_NamespaceUri(@ptrCast(*const IPrintSchemaElement, self), pbstrNamespaceUri); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaDisplayableElement_Value = Guid.initString("af45af49-d6aa-407d-bf87-3912236e9d94"); pub const IID_IPrintSchemaDisplayableElement = &IID_IPrintSchemaDisplayableElement_Value; pub const IPrintSchemaDisplayableElement = extern struct { pub const VTable = extern struct { base: IPrintSchemaElement.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayName: fn( self: *const IPrintSchemaDisplayableElement, pbstrDisplayName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaDisplayableElement_get_DisplayName(self: *const T, pbstrDisplayName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaDisplayableElement.VTable, self.vtable).get_DisplayName(@ptrCast(*const IPrintSchemaDisplayableElement, self), pbstrDisplayName); } };} pub usingnamespace MethodMixin(@This()); }; pub const PrintSchemaConstrainedSetting = enum(i32) { None = 0, PrintTicket = 1, Admin = 2, Device = 3, }; pub const PrintSchemaConstrainedSetting_None = PrintSchemaConstrainedSetting.None; pub const PrintSchemaConstrainedSetting_PrintTicket = PrintSchemaConstrainedSetting.PrintTicket; pub const PrintSchemaConstrainedSetting_Admin = PrintSchemaConstrainedSetting.Admin; pub const PrintSchemaConstrainedSetting_Device = PrintSchemaConstrainedSetting.Device; const IID_IPrintSchemaOption_Value = Guid.initString("66bb2f51-5844-4997-8d70-4b7cc221cf92"); pub const IID_IPrintSchemaOption = &IID_IPrintSchemaOption_Value; pub const IPrintSchemaOption = extern struct { pub const VTable = extern struct { base: IPrintSchemaDisplayableElement.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Selected: fn( self: *const IPrintSchemaOption, pbIsSelected: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Constrained: fn( self: *const IPrintSchemaOption, pSetting: ?*PrintSchemaConstrainedSetting, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPropertyValue: fn( self: *const IPrintSchemaOption, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppXmlValueNode: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaDisplayableElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaOption_get_Selected(self: *const T, pbIsSelected: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaOption.VTable, self.vtable).get_Selected(@ptrCast(*const IPrintSchemaOption, self), pbIsSelected); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaOption_get_Constrained(self: *const T, pSetting: ?*PrintSchemaConstrainedSetting) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaOption.VTable, self.vtable).get_Constrained(@ptrCast(*const IPrintSchemaOption, self), pSetting); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaOption_GetPropertyValue(self: *const T, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppXmlValueNode: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaOption.VTable, self.vtable).GetPropertyValue(@ptrCast(*const IPrintSchemaOption, self), bstrName, bstrNamespaceUri, ppXmlValueNode); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaPageMediaSizeOption_Value = Guid.initString("68746729-f493-4830-a10f-69028774605d"); pub const IID_IPrintSchemaPageMediaSizeOption = &IID_IPrintSchemaPageMediaSizeOption_Value; pub const IPrintSchemaPageMediaSizeOption = extern struct { pub const VTable = extern struct { base: IPrintSchemaOption.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_WidthInMicrons: fn( self: *const IPrintSchemaPageMediaSizeOption, pulWidth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_HeightInMicrons: fn( self: *const IPrintSchemaPageMediaSizeOption, pulHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaOption.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageMediaSizeOption_get_WidthInMicrons(self: *const T, pulWidth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageMediaSizeOption.VTable, self.vtable).get_WidthInMicrons(@ptrCast(*const IPrintSchemaPageMediaSizeOption, self), pulWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageMediaSizeOption_get_HeightInMicrons(self: *const T, pulHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageMediaSizeOption.VTable, self.vtable).get_HeightInMicrons(@ptrCast(*const IPrintSchemaPageMediaSizeOption, self), pulHeight); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaNUpOption_Value = Guid.initString("1f6342f2-d848-42e3-8995-c10a9ef9a3ba"); pub const IID_IPrintSchemaNUpOption = &IID_IPrintSchemaNUpOption_Value; pub const IPrintSchemaNUpOption = extern struct { pub const VTable = extern struct { base: IPrintSchemaOption.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PagesPerSheet: fn( self: *const IPrintSchemaNUpOption, pulPagesPerSheet: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaOption.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaNUpOption_get_PagesPerSheet(self: *const T, pulPagesPerSheet: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaNUpOption.VTable, self.vtable).get_PagesPerSheet(@ptrCast(*const IPrintSchemaNUpOption, self), pulPagesPerSheet); } };} pub usingnamespace MethodMixin(@This()); }; pub const PrintSchemaSelectionType = enum(i32) { One = 0, Many = 1, }; pub const PrintSchemaSelectionType_PickOne = PrintSchemaSelectionType.One; pub const PrintSchemaSelectionType_PickMany = PrintSchemaSelectionType.Many; const IID_IPrintSchemaOptionCollection_Value = Guid.initString("baecb0bd-a946-4771-bc30-e8b24f8d45c1"); pub const IID_IPrintSchemaOptionCollection = &IID_IPrintSchemaOptionCollection_Value; pub const IPrintSchemaOptionCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IPrintSchemaOptionCollection, pulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IPrintSchemaOptionCollection, ulIndex: u32, ppOption: ?*?*IPrintSchemaOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IPrintSchemaOptionCollection, ppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaOptionCollection_get_Count(self: *const T, pulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaOptionCollection.VTable, self.vtable).get_Count(@ptrCast(*const IPrintSchemaOptionCollection, self), pulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaOptionCollection_GetAt(self: *const T, ulIndex: u32, ppOption: ?*?*IPrintSchemaOption) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaOptionCollection.VTable, self.vtable).GetAt(@ptrCast(*const IPrintSchemaOptionCollection, self), ulIndex, ppOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaOptionCollection_get__NewEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaOptionCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IPrintSchemaOptionCollection, self), ppUnk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaFeature_Value = Guid.initString("ef189461-5d62-4626-8e57-ff83583c4826"); pub const IID_IPrintSchemaFeature = &IID_IPrintSchemaFeature_Value; pub const IPrintSchemaFeature = extern struct { pub const VTable = extern struct { base: IPrintSchemaDisplayableElement.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SelectedOption: fn( self: *const IPrintSchemaFeature, ppOption: ?*?*IPrintSchemaOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_SelectedOption: fn( self: *const IPrintSchemaFeature, pOption: ?*IPrintSchemaOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SelectionType: fn( self: *const IPrintSchemaFeature, pSelectionType: ?*PrintSchemaSelectionType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOption: fn( self: *const IPrintSchemaFeature, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppOption: ?*?*IPrintSchemaOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DisplayUI: fn( self: *const IPrintSchemaFeature, pbShow: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaDisplayableElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaFeature_get_SelectedOption(self: *const T, ppOption: ?*?*IPrintSchemaOption) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaFeature.VTable, self.vtable).get_SelectedOption(@ptrCast(*const IPrintSchemaFeature, self), ppOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaFeature_put_SelectedOption(self: *const T, pOption: ?*IPrintSchemaOption) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaFeature.VTable, self.vtable).put_SelectedOption(@ptrCast(*const IPrintSchemaFeature, self), pOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaFeature_get_SelectionType(self: *const T, pSelectionType: ?*PrintSchemaSelectionType) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaFeature.VTable, self.vtable).get_SelectionType(@ptrCast(*const IPrintSchemaFeature, self), pSelectionType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaFeature_GetOption(self: *const T, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppOption: ?*?*IPrintSchemaOption) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaFeature.VTable, self.vtable).GetOption(@ptrCast(*const IPrintSchemaFeature, self), bstrName, bstrNamespaceUri, ppOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaFeature_get_DisplayUI(self: *const T, pbShow: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaFeature.VTable, self.vtable).get_DisplayUI(@ptrCast(*const IPrintSchemaFeature, self), pbShow); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaPageImageableSize_Value = Guid.initString("7c85bf5e-dc7c-4f61-839b-4107e1c9b68e"); pub const IID_IPrintSchemaPageImageableSize = &IID_IPrintSchemaPageImageableSize_Value; pub const IPrintSchemaPageImageableSize = extern struct { pub const VTable = extern struct { base: IPrintSchemaElement.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ImageableSizeWidthInMicrons: fn( self: *const IPrintSchemaPageImageableSize, pulImageableSizeWidth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ImageableSizeHeightInMicrons: fn( self: *const IPrintSchemaPageImageableSize, pulImageableSizeHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OriginWidthInMicrons: fn( self: *const IPrintSchemaPageImageableSize, pulOriginWidth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_OriginHeightInMicrons: fn( self: *const IPrintSchemaPageImageableSize, pulOriginHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExtentWidthInMicrons: fn( self: *const IPrintSchemaPageImageableSize, pulExtentWidth: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ExtentHeightInMicrons: fn( self: *const IPrintSchemaPageImageableSize, pulExtentHeight: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageImageableSize_get_ImageableSizeWidthInMicrons(self: *const T, pulImageableSizeWidth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageImageableSize.VTable, self.vtable).get_ImageableSizeWidthInMicrons(@ptrCast(*const IPrintSchemaPageImageableSize, self), pulImageableSizeWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageImageableSize_get_ImageableSizeHeightInMicrons(self: *const T, pulImageableSizeHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageImageableSize.VTable, self.vtable).get_ImageableSizeHeightInMicrons(@ptrCast(*const IPrintSchemaPageImageableSize, self), pulImageableSizeHeight); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageImageableSize_get_OriginWidthInMicrons(self: *const T, pulOriginWidth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageImageableSize.VTable, self.vtable).get_OriginWidthInMicrons(@ptrCast(*const IPrintSchemaPageImageableSize, self), pulOriginWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageImageableSize_get_OriginHeightInMicrons(self: *const T, pulOriginHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageImageableSize.VTable, self.vtable).get_OriginHeightInMicrons(@ptrCast(*const IPrintSchemaPageImageableSize, self), pulOriginHeight); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageImageableSize_get_ExtentWidthInMicrons(self: *const T, pulExtentWidth: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageImageableSize.VTable, self.vtable).get_ExtentWidthInMicrons(@ptrCast(*const IPrintSchemaPageImageableSize, self), pulExtentWidth); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaPageImageableSize_get_ExtentHeightInMicrons(self: *const T, pulExtentHeight: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaPageImageableSize.VTable, self.vtable).get_ExtentHeightInMicrons(@ptrCast(*const IPrintSchemaPageImageableSize, self), pulExtentHeight); } };} pub usingnamespace MethodMixin(@This()); }; pub const PrintSchemaParameterDataType = enum(i32) { Integer = 0, NumericString = 1, String = 2, }; pub const PrintSchemaParameterDataType_Integer = PrintSchemaParameterDataType.Integer; pub const PrintSchemaParameterDataType_NumericString = PrintSchemaParameterDataType.NumericString; pub const PrintSchemaParameterDataType_String = PrintSchemaParameterDataType.String; const IID_IPrintSchemaParameterDefinition_Value = Guid.initString("b5ade81e-0e61-4fe1-81c6-c333e4ffe0f1"); pub const IID_IPrintSchemaParameterDefinition = &IID_IPrintSchemaParameterDefinition_Value; pub const IPrintSchemaParameterDefinition = extern struct { pub const VTable = extern struct { base: IPrintSchemaDisplayableElement.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserInputRequired: fn( self: *const IPrintSchemaParameterDefinition, pbIsRequired: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UnitType: fn( self: *const IPrintSchemaParameterDefinition, pbstrUnitType: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DataType: fn( self: *const IPrintSchemaParameterDefinition, pDataType: ?*PrintSchemaParameterDataType, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RangeMin: fn( self: *const IPrintSchemaParameterDefinition, pRangeMin: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_RangeMax: fn( self: *const IPrintSchemaParameterDefinition, pRangeMax: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaDisplayableElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterDefinition_get_UserInputRequired(self: *const T, pbIsRequired: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterDefinition.VTable, self.vtable).get_UserInputRequired(@ptrCast(*const IPrintSchemaParameterDefinition, self), pbIsRequired); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterDefinition_get_UnitType(self: *const T, pbstrUnitType: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterDefinition.VTable, self.vtable).get_UnitType(@ptrCast(*const IPrintSchemaParameterDefinition, self), pbstrUnitType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterDefinition_get_DataType(self: *const T, pDataType: ?*PrintSchemaParameterDataType) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterDefinition.VTable, self.vtable).get_DataType(@ptrCast(*const IPrintSchemaParameterDefinition, self), pDataType); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterDefinition_get_RangeMin(self: *const T, pRangeMin: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterDefinition.VTable, self.vtable).get_RangeMin(@ptrCast(*const IPrintSchemaParameterDefinition, self), pRangeMin); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterDefinition_get_RangeMax(self: *const T, pRangeMax: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterDefinition.VTable, self.vtable).get_RangeMax(@ptrCast(*const IPrintSchemaParameterDefinition, self), pRangeMax); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaParameterInitializer_Value = Guid.initString("52027082-0b74-4648-9564-828cc6cb656c"); pub const IID_IPrintSchemaParameterInitializer = &IID_IPrintSchemaParameterInitializer_Value; pub const IPrintSchemaParameterInitializer = extern struct { pub const VTable = extern struct { base: IPrintSchemaElement.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Value: fn( self: *const IPrintSchemaParameterInitializer, pVar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_Value: fn( self: *const IPrintSchemaParameterInitializer, pVar: ?*VARIANT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterInitializer_get_Value(self: *const T, pVar: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterInitializer.VTable, self.vtable).get_Value(@ptrCast(*const IPrintSchemaParameterInitializer, self), pVar); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaParameterInitializer_put_Value(self: *const T, pVar: ?*VARIANT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaParameterInitializer.VTable, self.vtable).put_Value(@ptrCast(*const IPrintSchemaParameterInitializer, self), pVar); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaCapabilities_Value = Guid.initString("5a577640-501d-4927-bcd0-5ef57a7ed175"); pub const IID_IPrintSchemaCapabilities = &IID_IPrintSchemaCapabilities_Value; pub const IPrintSchemaCapabilities = extern struct { pub const VTable = extern struct { base: IPrintSchemaElement.VTable, GetFeatureByKeyName: fn( self: *const IPrintSchemaCapabilities, bstrKeyName: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFeature: fn( self: *const IPrintSchemaCapabilities, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PageImageableSize: fn( self: *const IPrintSchemaCapabilities, ppPageImageableSize: ?*?*IPrintSchemaPageImageableSize, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_JobCopiesAllDocumentsMinValue: fn( self: *const IPrintSchemaCapabilities, pulJobCopiesAllDocumentsMinValue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_JobCopiesAllDocumentsMaxValue: fn( self: *const IPrintSchemaCapabilities, pulJobCopiesAllDocumentsMaxValue: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetSelectedOptionInPrintTicket: fn( self: *const IPrintSchemaCapabilities, pFeature: ?*IPrintSchemaFeature, ppOption: ?*?*IPrintSchemaOption, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetOptions: fn( self: *const IPrintSchemaCapabilities, pFeature: ?*IPrintSchemaFeature, ppOptionCollection: ?*?*IPrintSchemaOptionCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_GetFeatureByKeyName(self: *const T, bstrKeyName: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).GetFeatureByKeyName(@ptrCast(*const IPrintSchemaCapabilities, self), bstrKeyName, ppFeature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_GetFeature(self: *const T, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).GetFeature(@ptrCast(*const IPrintSchemaCapabilities, self), bstrName, bstrNamespaceUri, ppFeature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_get_PageImageableSize(self: *const T, ppPageImageableSize: ?*?*IPrintSchemaPageImageableSize) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).get_PageImageableSize(@ptrCast(*const IPrintSchemaCapabilities, self), ppPageImageableSize); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_get_JobCopiesAllDocumentsMinValue(self: *const T, pulJobCopiesAllDocumentsMinValue: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).get_JobCopiesAllDocumentsMinValue(@ptrCast(*const IPrintSchemaCapabilities, self), pulJobCopiesAllDocumentsMinValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_get_JobCopiesAllDocumentsMaxValue(self: *const T, pulJobCopiesAllDocumentsMaxValue: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).get_JobCopiesAllDocumentsMaxValue(@ptrCast(*const IPrintSchemaCapabilities, self), pulJobCopiesAllDocumentsMaxValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_GetSelectedOptionInPrintTicket(self: *const T, pFeature: ?*IPrintSchemaFeature, ppOption: ?*?*IPrintSchemaOption) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).GetSelectedOptionInPrintTicket(@ptrCast(*const IPrintSchemaCapabilities, self), pFeature, ppOption); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities_GetOptions(self: *const T, pFeature: ?*IPrintSchemaFeature, ppOptionCollection: ?*?*IPrintSchemaOptionCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities.VTable, self.vtable).GetOptions(@ptrCast(*const IPrintSchemaCapabilities, self), pFeature, ppOptionCollection); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaCapabilities2_Value = Guid.initString("b58845f4-9970-4d87-a636-169fb82ed642"); pub const IID_IPrintSchemaCapabilities2 = &IID_IPrintSchemaCapabilities2_Value; pub const IPrintSchemaCapabilities2 = extern struct { pub const VTable = extern struct { base: IPrintSchemaCapabilities.VTable, GetParameterDefinition: fn( self: *const IPrintSchemaCapabilities2, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppParameterDefinition: ?*?*IPrintSchemaParameterDefinition, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaCapabilities.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaCapabilities2_GetParameterDefinition(self: *const T, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppParameterDefinition: ?*?*IPrintSchemaParameterDefinition) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaCapabilities2.VTable, self.vtable).GetParameterDefinition(@ptrCast(*const IPrintSchemaCapabilities2, self), bstrName, bstrNamespaceUri, ppParameterDefinition); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaAsyncOperation_Value = Guid.initString("143c8dcb-d37f-47f7-88e8-6b1d21f2c5f7"); pub const IID_IPrintSchemaAsyncOperation = &IID_IPrintSchemaAsyncOperation_Value; pub const IPrintSchemaAsyncOperation = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Start: fn( self: *const IPrintSchemaAsyncOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Cancel: fn( self: *const IPrintSchemaAsyncOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaAsyncOperation_Start(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaAsyncOperation.VTable, self.vtable).Start(@ptrCast(*const IPrintSchemaAsyncOperation, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaAsyncOperation_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaAsyncOperation.VTable, self.vtable).Cancel(@ptrCast(*const IPrintSchemaAsyncOperation, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaTicket_Value = Guid.initString("e480b861-4708-4e6d-a5b4-a2b4eeb9baa4"); pub const IID_IPrintSchemaTicket = &IID_IPrintSchemaTicket_Value; pub const IPrintSchemaTicket = extern struct { pub const VTable = extern struct { base: IPrintSchemaElement.VTable, GetFeatureByKeyName: fn( self: *const IPrintSchemaTicket, bstrKeyName: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetFeature: fn( self: *const IPrintSchemaTicket, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ValidateAsync: fn( self: *const IPrintSchemaTicket, ppAsyncOperation: ?*?*IPrintSchemaAsyncOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CommitAsync: fn( self: *const IPrintSchemaTicket, pPrintTicketCommit: ?*IPrintSchemaTicket, ppAsyncOperation: ?*?*IPrintSchemaAsyncOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, NotifyXmlChanged: fn( self: *const IPrintSchemaTicket, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetCapabilities: fn( self: *const IPrintSchemaTicket, ppCapabilities: ?*?*IPrintSchemaCapabilities, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_JobCopiesAllDocuments: fn( self: *const IPrintSchemaTicket, pulJobCopiesAllDocuments: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? put_JobCopiesAllDocuments: fn( self: *const IPrintSchemaTicket, ulJobCopiesAllDocuments: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaElement.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_GetFeatureByKeyName(self: *const T, bstrKeyName: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).GetFeatureByKeyName(@ptrCast(*const IPrintSchemaTicket, self), bstrKeyName, ppFeature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_GetFeature(self: *const T, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppFeature: ?*?*IPrintSchemaFeature) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).GetFeature(@ptrCast(*const IPrintSchemaTicket, self), bstrName, bstrNamespaceUri, ppFeature); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_ValidateAsync(self: *const T, ppAsyncOperation: ?*?*IPrintSchemaAsyncOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).ValidateAsync(@ptrCast(*const IPrintSchemaTicket, self), ppAsyncOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_CommitAsync(self: *const T, pPrintTicketCommit: ?*IPrintSchemaTicket, ppAsyncOperation: ?*?*IPrintSchemaAsyncOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).CommitAsync(@ptrCast(*const IPrintSchemaTicket, self), pPrintTicketCommit, ppAsyncOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_NotifyXmlChanged(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).NotifyXmlChanged(@ptrCast(*const IPrintSchemaTicket, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_GetCapabilities(self: *const T, ppCapabilities: ?*?*IPrintSchemaCapabilities) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).GetCapabilities(@ptrCast(*const IPrintSchemaTicket, self), ppCapabilities); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_get_JobCopiesAllDocuments(self: *const T, pulJobCopiesAllDocuments: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).get_JobCopiesAllDocuments(@ptrCast(*const IPrintSchemaTicket, self), pulJobCopiesAllDocuments); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket_put_JobCopiesAllDocuments(self: *const T, ulJobCopiesAllDocuments: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket.VTable, self.vtable).put_JobCopiesAllDocuments(@ptrCast(*const IPrintSchemaTicket, self), ulJobCopiesAllDocuments); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaTicket2_Value = Guid.initString("2ec1f844-766a-47a1-91f4-2eeb6190f80c"); pub const IID_IPrintSchemaTicket2 = &IID_IPrintSchemaTicket2_Value; pub const IPrintSchemaTicket2 = extern struct { pub const VTable = extern struct { base: IPrintSchemaTicket.VTable, GetParameterInitializer: fn( self: *const IPrintSchemaTicket2, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppParameterInitializer: ?*?*IPrintSchemaParameterInitializer, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintSchemaTicket.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaTicket2_GetParameterInitializer(self: *const T, bstrName: ?BSTR, bstrNamespaceUri: ?BSTR, ppParameterInitializer: ?*?*IPrintSchemaParameterInitializer) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaTicket2.VTable, self.vtable).GetParameterInitializer(@ptrCast(*const IPrintSchemaTicket2, self), bstrName, bstrNamespaceUri, ppParameterInitializer); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintSchemaAsyncOperationEvent_Value = Guid.initString("23adbb16-0133-4906-b29a-1dce1d026379"); pub const IID_IPrintSchemaAsyncOperationEvent = &IID_IPrintSchemaAsyncOperationEvent_Value; pub const IPrintSchemaAsyncOperationEvent = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Completed: fn( self: *const IPrintSchemaAsyncOperationEvent, pTicket: ?*IPrintSchemaTicket, hrOperation: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintSchemaAsyncOperationEvent_Completed(self: *const T, pTicket: ?*IPrintSchemaTicket, hrOperation: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintSchemaAsyncOperationEvent.VTable, self.vtable).Completed(@ptrCast(*const IPrintSchemaAsyncOperationEvent, self), pTicket, hrOperation); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterScriptableSequentialStream_Value = Guid.initString("2072838a-316f-467a-a949-27f68c44a854"); pub const IID_IPrinterScriptableSequentialStream = &IID_IPrinterScriptableSequentialStream_Value; pub const IPrinterScriptableSequentialStream = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Read: fn( self: *const IPrinterScriptableSequentialStream, cbRead: i32, ppArray: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Write: fn( self: *const IPrinterScriptableSequentialStream, pArray: ?*IDispatch, pcbWritten: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptableSequentialStream_Read(self: *const T, cbRead: i32, ppArray: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptableSequentialStream.VTable, self.vtable).Read(@ptrCast(*const IPrinterScriptableSequentialStream, self), cbRead, ppArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptableSequentialStream_Write(self: *const T, pArray: ?*IDispatch, pcbWritten: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptableSequentialStream.VTable, self.vtable).Write(@ptrCast(*const IPrinterScriptableSequentialStream, self), pArray, pcbWritten); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterScriptableStream_Value = Guid.initString("7edf9a92-4750-41a5-a17f-879a6f4f7dcb"); pub const IID_IPrinterScriptableStream = &IID_IPrinterScriptableStream_Value; pub const IPrinterScriptableStream = extern struct { pub const VTable = extern struct { base: IPrinterScriptableSequentialStream.VTable, Commit: fn( self: *const IPrinterScriptableStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Seek: fn( self: *const IPrinterScriptableStream, lOffset: i32, streamSeek: STREAM_SEEK, plPosition: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetSize: fn( self: *const IPrinterScriptableStream, lSize: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrinterScriptableSequentialStream.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptableStream_Commit(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptableStream.VTable, self.vtable).Commit(@ptrCast(*const IPrinterScriptableStream, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptableStream_Seek(self: *const T, lOffset: i32, streamSeek: STREAM_SEEK, plPosition: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptableStream.VTable, self.vtable).Seek(@ptrCast(*const IPrinterScriptableStream, self), lOffset, streamSeek, plPosition); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptableStream_SetSize(self: *const T, lSize: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptableStream.VTable, self.vtable).SetSize(@ptrCast(*const IPrinterScriptableStream, self), lSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterPropertyBag_Value = Guid.initString("fea77364-df95-4a23-a905-019b79a8e481"); pub const IID_IPrinterPropertyBag = &IID_IPrinterPropertyBag_Value; pub const IPrinterPropertyBag = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetBool: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, pbValue: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBool: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, bValue: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInt32: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, pnValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetInt32: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, nValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetString: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, pbstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetString: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, bstrValue: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBytes: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, pcbValue: ?*u32, ppValue: [*]?*u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBytes: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, cbValue: u32, pValue: [*:0]u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReadStream: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, ppValue: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWriteStream: fn( self: *const IPrinterPropertyBag, bstrName: ?BSTR, ppValue: ?*?*IStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_GetBool(self: *const T, bstrName: ?BSTR, pbValue: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).GetBool(@ptrCast(*const IPrinterPropertyBag, self), bstrName, pbValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_SetBool(self: *const T, bstrName: ?BSTR, bValue: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).SetBool(@ptrCast(*const IPrinterPropertyBag, self), bstrName, bValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_GetInt32(self: *const T, bstrName: ?BSTR, pnValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).GetInt32(@ptrCast(*const IPrinterPropertyBag, self), bstrName, pnValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_SetInt32(self: *const T, bstrName: ?BSTR, nValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).SetInt32(@ptrCast(*const IPrinterPropertyBag, self), bstrName, nValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_GetString(self: *const T, bstrName: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).GetString(@ptrCast(*const IPrinterPropertyBag, self), bstrName, pbstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_SetString(self: *const T, bstrName: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).SetString(@ptrCast(*const IPrinterPropertyBag, self), bstrName, bstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_GetBytes(self: *const T, bstrName: ?BSTR, pcbValue: ?*u32, ppValue: [*]?*u8) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).GetBytes(@ptrCast(*const IPrinterPropertyBag, self), bstrName, pcbValue, ppValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_SetBytes(self: *const T, bstrName: ?BSTR, cbValue: u32, pValue: [*:0]u8) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).SetBytes(@ptrCast(*const IPrinterPropertyBag, self), bstrName, cbValue, pValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_GetReadStream(self: *const T, bstrName: ?BSTR, ppValue: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).GetReadStream(@ptrCast(*const IPrinterPropertyBag, self), bstrName, ppValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterPropertyBag_GetWriteStream(self: *const T, bstrName: ?BSTR, ppValue: ?*?*IStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterPropertyBag.VTable, self.vtable).GetWriteStream(@ptrCast(*const IPrinterPropertyBag, self), bstrName, ppValue); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterScriptablePropertyBag_Value = Guid.initString("91c7765f-ed57-49ad-8b01-dc24816a5294"); pub const IID_IPrinterScriptablePropertyBag = &IID_IPrinterScriptablePropertyBag_Value; pub const IPrinterScriptablePropertyBag = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, GetBool: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, pbValue: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBool: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, bValue: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetInt32: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, pnValue: ?*i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetInt32: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, nValue: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetString: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, pbstrValue: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetString: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, bstrValue: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetBytes: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, ppArray: ?*?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetBytes: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, pArray: ?*IDispatch, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetReadStream: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, ppStream: ?*?*IPrinterScriptableStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetWriteStream: fn( self: *const IPrinterScriptablePropertyBag, bstrName: ?BSTR, ppStream: ?*?*IPrinterScriptableStream, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_GetBool(self: *const T, bstrName: ?BSTR, pbValue: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).GetBool(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, pbValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_SetBool(self: *const T, bstrName: ?BSTR, bValue: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).SetBool(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, bValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_GetInt32(self: *const T, bstrName: ?BSTR, pnValue: ?*i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).GetInt32(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, pnValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_SetInt32(self: *const T, bstrName: ?BSTR, nValue: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).SetInt32(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, nValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_GetString(self: *const T, bstrName: ?BSTR, pbstrValue: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).GetString(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, pbstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_SetString(self: *const T, bstrName: ?BSTR, bstrValue: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).SetString(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, bstrValue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_GetBytes(self: *const T, bstrName: ?BSTR, ppArray: ?*?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).GetBytes(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, ppArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_SetBytes(self: *const T, bstrName: ?BSTR, pArray: ?*IDispatch) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).SetBytes(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, pArray); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_GetReadStream(self: *const T, bstrName: ?BSTR, ppStream: ?*?*IPrinterScriptableStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).GetReadStream(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, ppStream); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag_GetWriteStream(self: *const T, bstrName: ?BSTR, ppStream: ?*?*IPrinterScriptableStream) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag.VTable, self.vtable).GetWriteStream(@ptrCast(*const IPrinterScriptablePropertyBag, self), bstrName, ppStream); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterScriptablePropertyBag2_Value = Guid.initString("2a1c53c4-8638-4b3e-b518-2773c94556a3"); pub const IID_IPrinterScriptablePropertyBag2 = &IID_IPrinterScriptablePropertyBag2_Value; pub const IPrinterScriptablePropertyBag2 = extern struct { pub const VTable = extern struct { base: IPrinterScriptablePropertyBag.VTable, GetReadStreamAsXML: fn( self: *const IPrinterScriptablePropertyBag2, bstrName: ?BSTR, ppXmlNode: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrinterScriptablePropertyBag.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptablePropertyBag2_GetReadStreamAsXML(self: *const T, bstrName: ?BSTR, ppXmlNode: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptablePropertyBag2.VTable, self.vtable).GetReadStreamAsXML(@ptrCast(*const IPrinterScriptablePropertyBag2, self), bstrName, ppXmlNode); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterQueue_Value = Guid.initString("3580a828-07fe-4b94-ac1a-757d9d2d3056"); pub const IID_IPrinterQueue = &IID_IPrinterQueue_Value; pub const IPrinterQueue = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Handle: fn( self: *const IPrinterQueue, phPrinter: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IPrinterQueue, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SendBidiQuery: fn( self: *const IPrinterQueue, bstrBidiQuery: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetProperties: fn( self: *const IPrinterQueue, ppPropertyBag: ?*?*IPrinterPropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueue_get_Handle(self: *const T, phPrinter: ?*?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueue.VTable, self.vtable).get_Handle(@ptrCast(*const IPrinterQueue, self), phPrinter); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueue_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueue.VTable, self.vtable).get_Name(@ptrCast(*const IPrinterQueue, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueue_SendBidiQuery(self: *const T, bstrBidiQuery: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueue.VTable, self.vtable).SendBidiQuery(@ptrCast(*const IPrinterQueue, self), bstrBidiQuery); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueue_GetProperties(self: *const T, ppPropertyBag: ?*?*IPrinterPropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueue.VTable, self.vtable).GetProperties(@ptrCast(*const IPrinterQueue, self), ppPropertyBag); } };} pub usingnamespace MethodMixin(@This()); }; pub const PrintJobStatus = enum(i32) { Paused = 1, Error = 2, Deleting = 4, Spooling = 8, Printing = 16, Offline = 32, PaperOut = 64, Printed = 128, Deleted = 256, BlockedDeviceQueue = 512, UserIntervention = 1024, Restarted = 2048, Complete = 4096, Retained = 8192, }; pub const PrintJobStatus_Paused = PrintJobStatus.Paused; pub const PrintJobStatus_Error = PrintJobStatus.Error; pub const PrintJobStatus_Deleting = PrintJobStatus.Deleting; pub const PrintJobStatus_Spooling = PrintJobStatus.Spooling; pub const PrintJobStatus_Printing = PrintJobStatus.Printing; pub const PrintJobStatus_Offline = PrintJobStatus.Offline; pub const PrintJobStatus_PaperOut = PrintJobStatus.PaperOut; pub const PrintJobStatus_Printed = PrintJobStatus.Printed; pub const PrintJobStatus_Deleted = PrintJobStatus.Deleted; pub const PrintJobStatus_BlockedDeviceQueue = PrintJobStatus.BlockedDeviceQueue; pub const PrintJobStatus_UserIntervention = PrintJobStatus.UserIntervention; pub const PrintJobStatus_Restarted = PrintJobStatus.Restarted; pub const PrintJobStatus_Complete = PrintJobStatus.Complete; pub const PrintJobStatus_Retained = PrintJobStatus.Retained; const IID_IPrintJob_Value = Guid.initString("b771dab8-1282-41b7-858c-f206e4d20577"); pub const IID_IPrintJob = &IID_IPrintJob_Value; pub const IPrintJob = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Name: fn( self: *const IPrintJob, pbstrName: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Id: fn( self: *const IPrintJob, pulID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrintedPages: fn( self: *const IPrintJob, pulPages: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_TotalPages: fn( self: *const IPrintJob, pulPages: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Status: fn( self: *const IPrintJob, pStatus: ?*PrintJobStatus, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SubmissionTime: fn( self: *const IPrintJob, pSubmissionTime: ?*f64, ) callconv(@import("std").os.windows.WINAPI) HRESULT, RequestCancel: fn( self: *const IPrintJob, ) 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 IPrintJob_get_Name(self: *const T, pbstrName: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).get_Name(@ptrCast(*const IPrintJob, self), pbstrName); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJob_get_Id(self: *const T, pulID: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).get_Id(@ptrCast(*const IPrintJob, self), pulID); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJob_get_PrintedPages(self: *const T, pulPages: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).get_PrintedPages(@ptrCast(*const IPrintJob, self), pulPages); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJob_get_TotalPages(self: *const T, pulPages: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).get_TotalPages(@ptrCast(*const IPrintJob, self), pulPages); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJob_get_Status(self: *const T, pStatus: ?*PrintJobStatus) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).get_Status(@ptrCast(*const IPrintJob, self), pStatus); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJob_get_SubmissionTime(self: *const T, pSubmissionTime: ?*f64) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).get_SubmissionTime(@ptrCast(*const IPrintJob, self), pSubmissionTime); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJob_RequestCancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJob.VTable, self.vtable).RequestCancel(@ptrCast(*const IPrintJob, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintJobCollection_Value = Guid.initString("72b82a24-a598-4e87-895f-cdb23a49e9dc"); pub const IID_IPrintJobCollection = &IID_IPrintJobCollection_Value; pub const IPrintJobCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IPrintJobCollection, pulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IPrintJobCollection, ulIndex: u32, ppJob: ?*?*IPrintJob, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IPrintJobCollection, ppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJobCollection_get_Count(self: *const T, pulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJobCollection.VTable, self.vtable).get_Count(@ptrCast(*const IPrintJobCollection, self), pulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJobCollection_GetAt(self: *const T, ulIndex: u32, ppJob: ?*?*IPrintJob) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJobCollection.VTable, self.vtable).GetAt(@ptrCast(*const IPrintJobCollection, self), ulIndex, ppJob); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintJobCollection_get__NewEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintJobCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IPrintJobCollection, self), ppUnk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterQueueViewEvent_Value = Guid.initString("c5b6042b-fd21-404a-a0ef-e2fbb52b9080"); pub const IID_IPrinterQueueViewEvent = &IID_IPrinterQueueViewEvent_Value; pub const IPrinterQueueViewEvent = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, OnChanged: fn( self: *const IPrinterQueueViewEvent, pCollection: ?*IPrintJobCollection, ulViewOffset: u32, ulViewSize: u32, ulCountJobsInPrintQueue: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueueViewEvent_OnChanged(self: *const T, pCollection: ?*IPrintJobCollection, ulViewOffset: u32, ulViewSize: u32, ulCountJobsInPrintQueue: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueueViewEvent.VTable, self.vtable).OnChanged(@ptrCast(*const IPrinterQueueViewEvent, self), pCollection, ulViewOffset, ulViewSize, ulCountJobsInPrintQueue); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterQueueView_Value = Guid.initString("476e2969-3b2b-4b3f-8277-cff6056042aa"); pub const IID_IPrinterQueueView = &IID_IPrinterQueueView_Value; pub const IPrinterQueueView = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, SetViewRange: fn( self: *const IPrinterQueueView, ulViewOffset: u32, ulViewSize: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueueView_SetViewRange(self: *const T, ulViewOffset: u32, ulViewSize: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueueView.VTable, self.vtable).SetViewRange(@ptrCast(*const IPrinterQueueView, self), ulViewOffset, ulViewSize); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterQueueEvent_Value = Guid.initString("214685f6-7b78-4681-87e0-495f739273d1"); pub const IID_IPrinterQueueEvent = &IID_IPrinterQueueEvent_Value; pub const IPrinterQueueEvent = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, OnBidiResponseReceived: fn( self: *const IPrinterQueueEvent, bstrResponse: ?BSTR, hrStatus: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueueEvent_OnBidiResponseReceived(self: *const T, bstrResponse: ?BSTR, hrStatus: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueueEvent.VTable, self.vtable).OnBidiResponseReceived(@ptrCast(*const IPrinterQueueEvent, self), bstrResponse, hrStatus); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterBidiSetRequestCallback_Value = Guid.initString("c52d32dd-f2b4-4052-8502-ec4305ecb71f"); pub const IID_IPrinterBidiSetRequestCallback = &IID_IPrinterBidiSetRequestCallback_Value; pub const IPrinterBidiSetRequestCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Completed: fn( self: *const IPrinterBidiSetRequestCallback, bstrResponse: ?BSTR, hrStatus: HRESULT, ) 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 IPrinterBidiSetRequestCallback_Completed(self: *const T, bstrResponse: ?BSTR, hrStatus: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterBidiSetRequestCallback.VTable, self.vtable).Completed(@ptrCast(*const IPrinterBidiSetRequestCallback, self), bstrResponse, hrStatus); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionAsyncOperation_Value = Guid.initString("108d6a23-6a4b-4552-9448-68b427186acd"); pub const IID_IPrinterExtensionAsyncOperation = &IID_IPrinterExtensionAsyncOperation_Value; pub const IPrinterExtensionAsyncOperation = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Cancel: fn( self: *const IPrinterExtensionAsyncOperation, ) 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 IPrinterExtensionAsyncOperation_Cancel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionAsyncOperation.VTable, self.vtable).Cancel(@ptrCast(*const IPrinterExtensionAsyncOperation, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterQueue2_Value = Guid.initString("8cd444e8-c9bb-49b3-8e38-e03209416131"); pub const IID_IPrinterQueue2 = &IID_IPrinterQueue2_Value; pub const IPrinterQueue2 = extern struct { pub const VTable = extern struct { base: IPrinterQueue.VTable, SendBidiSetRequestAsync: fn( self: *const IPrinterQueue2, bstrBidiRequest: ?BSTR, pCallback: ?*IPrinterBidiSetRequestCallback, ppAsyncOperation: ?*?*IPrinterExtensionAsyncOperation, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrinterQueueView: fn( self: *const IPrinterQueue2, ulViewOffset: u32, ulViewSize: u32, ppJobView: ?*?*IPrinterQueueView, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrinterQueue.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueue2_SendBidiSetRequestAsync(self: *const T, bstrBidiRequest: ?BSTR, pCallback: ?*IPrinterBidiSetRequestCallback, ppAsyncOperation: ?*?*IPrinterExtensionAsyncOperation) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueue2.VTable, self.vtable).SendBidiSetRequestAsync(@ptrCast(*const IPrinterQueue2, self), bstrBidiRequest, pCallback, ppAsyncOperation); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterQueue2_GetPrinterQueueView(self: *const T, ulViewOffset: u32, ulViewSize: u32, ppJobView: ?*?*IPrinterQueueView) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterQueue2.VTable, self.vtable).GetPrinterQueueView(@ptrCast(*const IPrinterQueue2, self), ulViewOffset, ulViewSize, ppJobView); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionContext_Value = Guid.initString("39843bf2-c4d2-41fd-b4b2-aedbee5e1900"); pub const IID_IPrinterExtensionContext = &IID_IPrinterExtensionContext_Value; pub const IPrinterExtensionContext = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrinterQueue: fn( self: *const IPrinterExtensionContext, ppQueue: ?*?*IPrinterQueue, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_PrintSchemaTicket: fn( self: *const IPrinterExtensionContext, ppTicket: ?*?*IPrintSchemaTicket, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DriverProperties: fn( self: *const IPrinterExtensionContext, ppPropertyBag: ?*?*IPrinterPropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserProperties: fn( self: *const IPrinterExtensionContext, ppPropertyBag: ?*?*IPrinterPropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContext_get_PrinterQueue(self: *const T, ppQueue: ?*?*IPrinterQueue) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContext.VTable, self.vtable).get_PrinterQueue(@ptrCast(*const IPrinterExtensionContext, self), ppQueue); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContext_get_PrintSchemaTicket(self: *const T, ppTicket: ?*?*IPrintSchemaTicket) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContext.VTable, self.vtable).get_PrintSchemaTicket(@ptrCast(*const IPrinterExtensionContext, self), ppTicket); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContext_get_DriverProperties(self: *const T, ppPropertyBag: ?*?*IPrinterPropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContext.VTable, self.vtable).get_DriverProperties(@ptrCast(*const IPrinterExtensionContext, self), ppPropertyBag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContext_get_UserProperties(self: *const T, ppPropertyBag: ?*?*IPrinterPropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContext.VTable, self.vtable).get_UserProperties(@ptrCast(*const IPrinterExtensionContext, self), ppPropertyBag); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionRequest_Value = Guid.initString("39843bf3-c4d2-41fd-b4b2-aedbee5e1900"); pub const IID_IPrinterExtensionRequest = &IID_IPrinterExtensionRequest_Value; pub const IPrinterExtensionRequest = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, Cancel: fn( self: *const IPrinterExtensionRequest, hrStatus: HRESULT, bstrLogMessage: ?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, Complete: fn( self: *const IPrinterExtensionRequest, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionRequest_Cancel(self: *const T, hrStatus: HRESULT, bstrLogMessage: ?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionRequest.VTable, self.vtable).Cancel(@ptrCast(*const IPrinterExtensionRequest, self), hrStatus, bstrLogMessage); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionRequest_Complete(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionRequest.VTable, self.vtable).Complete(@ptrCast(*const IPrinterExtensionRequest, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionEventArgs_Value = Guid.initString("39843bf4-c4d2-41fd-b4b2-aedbee5e1900"); pub const IID_IPrinterExtensionEventArgs = &IID_IPrinterExtensionEventArgs_Value; pub const IPrinterExtensionEventArgs = extern struct { pub const VTable = extern struct { base: IPrinterExtensionContext.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_BidiNotification: fn( self: *const IPrinterExtensionEventArgs, pbstrBidiNotification: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_ReasonId: fn( self: *const IPrinterExtensionEventArgs, pReasonId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Request: fn( self: *const IPrinterExtensionEventArgs, ppRequest: ?*?*IPrinterExtensionRequest, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_SourceApplication: fn( self: *const IPrinterExtensionEventArgs, pbstrApplication: ?*?BSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DetailedReasonId: fn( self: *const IPrinterExtensionEventArgs, pDetailedReasonId: ?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_WindowModal: fn( self: *const IPrinterExtensionEventArgs, pbModal: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_WindowParent: fn( self: *const IPrinterExtensionEventArgs, phwndParent: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrinterExtensionContext.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_BidiNotification(self: *const T, pbstrBidiNotification: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_BidiNotification(@ptrCast(*const IPrinterExtensionEventArgs, self), pbstrBidiNotification); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_ReasonId(self: *const T, pReasonId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_ReasonId(@ptrCast(*const IPrinterExtensionEventArgs, self), pReasonId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_Request(self: *const T, ppRequest: ?*?*IPrinterExtensionRequest) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_Request(@ptrCast(*const IPrinterExtensionEventArgs, self), ppRequest); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_SourceApplication(self: *const T, pbstrApplication: ?*?BSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_SourceApplication(@ptrCast(*const IPrinterExtensionEventArgs, self), pbstrApplication); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_DetailedReasonId(self: *const T, pDetailedReasonId: ?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_DetailedReasonId(@ptrCast(*const IPrinterExtensionEventArgs, self), pDetailedReasonId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_WindowModal(self: *const T, pbModal: ?*BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_WindowModal(@ptrCast(*const IPrinterExtensionEventArgs, self), pbModal); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEventArgs_get_WindowParent(self: *const T, phwndParent: ?*?HANDLE) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEventArgs.VTable, self.vtable).get_WindowParent(@ptrCast(*const IPrinterExtensionEventArgs, self), phwndParent); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionContextCollection_Value = Guid.initString("fb476970-9bab-4861-811e-3e98b0c5addf"); pub const IID_IPrinterExtensionContextCollection = &IID_IPrinterExtensionContextCollection_Value; pub const IPrinterExtensionContextCollection = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_Count: fn( self: *const IPrinterExtensionContextCollection, pulCount: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetAt: fn( self: *const IPrinterExtensionContextCollection, ulIndex: u32, ppContext: ?*?*IPrinterExtensionContext, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get__NewEnum: fn( self: *const IPrinterExtensionContextCollection, ppUnk: ?*?*IUnknown, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContextCollection_get_Count(self: *const T, pulCount: ?*u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContextCollection.VTable, self.vtable).get_Count(@ptrCast(*const IPrinterExtensionContextCollection, self), pulCount); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContextCollection_GetAt(self: *const T, ulIndex: u32, ppContext: ?*?*IPrinterExtensionContext) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContextCollection.VTable, self.vtable).GetAt(@ptrCast(*const IPrinterExtensionContextCollection, self), ulIndex, ppContext); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionContextCollection_get__NewEnum(self: *const T, ppUnk: ?*?*IUnknown) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionContextCollection.VTable, self.vtable).get__NewEnum(@ptrCast(*const IPrinterExtensionContextCollection, self), ppUnk); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionEvent_Value = Guid.initString("c093cb63-5ef5-4585-af8e-4d5637487b57"); pub const IID_IPrinterExtensionEvent = &IID_IPrinterExtensionEvent_Value; pub const IPrinterExtensionEvent = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, OnDriverEvent: fn( self: *const IPrinterExtensionEvent, pEventArgs: ?*IPrinterExtensionEventArgs, ) callconv(@import("std").os.windows.WINAPI) HRESULT, OnPrinterQueuesEnumerated: fn( self: *const IPrinterExtensionEvent, pContextCollection: ?*IPrinterExtensionContextCollection, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEvent_OnDriverEvent(self: *const T, pEventArgs: ?*IPrinterExtensionEventArgs) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEvent.VTable, self.vtable).OnDriverEvent(@ptrCast(*const IPrinterExtensionEvent, self), pEventArgs); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionEvent_OnPrinterQueuesEnumerated(self: *const T, pContextCollection: ?*IPrinterExtensionContextCollection) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionEvent.VTable, self.vtable).OnPrinterQueuesEnumerated(@ptrCast(*const IPrinterExtensionEvent, self), pContextCollection); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterExtensionManager_Value = Guid.initString("93c6eb8c-b001-4355-9629-8e8a1b3f8e77"); pub const IID_IPrinterExtensionManager = &IID_IPrinterExtensionManager_Value; pub const IPrinterExtensionManager = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, EnableEvents: fn( self: *const IPrinterExtensionManager, printerDriverId: Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DisableEvents: fn( self: *const IPrinterExtensionManager, ) 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 IPrinterExtensionManager_EnableEvents(self: *const T, printerDriverId: Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionManager.VTable, self.vtable).EnableEvents(@ptrCast(*const IPrinterExtensionManager, self), printerDriverId); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterExtensionManager_DisableEvents(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterExtensionManager.VTable, self.vtable).DisableEvents(@ptrCast(*const IPrinterExtensionManager, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrinterScriptContext_Value = Guid.initString("066acbca-8881-49c9-bb98-fae16b4889e1"); pub const IID_IPrinterScriptContext = &IID_IPrinterScriptContext_Value; pub const IPrinterScriptContext = extern struct { pub const VTable = extern struct { base: IDispatch.VTable, // TODO: this function has a "SpecialName", should Zig do anything with this? get_DriverProperties: fn( self: *const IPrinterScriptContext, ppPropertyBag: ?*?*IPrinterScriptablePropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_QueueProperties: fn( self: *const IPrinterScriptContext, ppPropertyBag: ?*?*IPrinterScriptablePropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, // TODO: this function has a "SpecialName", should Zig do anything with this? get_UserProperties: fn( self: *const IPrinterScriptContext, ppPropertyBag: ?*?*IPrinterScriptablePropertyBag, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IDispatch.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptContext_get_DriverProperties(self: *const T, ppPropertyBag: ?*?*IPrinterScriptablePropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptContext.VTable, self.vtable).get_DriverProperties(@ptrCast(*const IPrinterScriptContext, self), ppPropertyBag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptContext_get_QueueProperties(self: *const T, ppPropertyBag: ?*?*IPrinterScriptablePropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptContext.VTable, self.vtable).get_QueueProperties(@ptrCast(*const IPrinterScriptContext, self), ppPropertyBag); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrinterScriptContext_get_UserProperties(self: *const T, ppPropertyBag: ?*?*IPrinterScriptablePropertyBag) callconv(.Inline) HRESULT { return @ptrCast(*const IPrinterScriptContext.VTable, self.vtable).get_UserProperties(@ptrCast(*const IPrinterScriptContext, self), ppPropertyBag); } };} pub usingnamespace MethodMixin(@This()); }; pub const PrintAsyncNotifyUserFilter = enum(i32) { PerUser = 0, AllUsers = 1, }; pub const kPerUser = PrintAsyncNotifyUserFilter.PerUser; pub const kAllUsers = PrintAsyncNotifyUserFilter.AllUsers; pub const PrintAsyncNotifyConversationStyle = enum(i32) { BiDirectional = 0, UniDirectional = 1, }; pub const kBiDirectional = PrintAsyncNotifyConversationStyle.BiDirectional; pub const kUniDirectional = PrintAsyncNotifyConversationStyle.UniDirectional; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPrintAsyncNotifyDataObject_Value = Guid.initString("77cf513e-5d49-4789-9f30-d0822b335c0d"); pub const IID_IPrintAsyncNotifyDataObject = &IID_IPrintAsyncNotifyDataObject_Value; pub const IPrintAsyncNotifyDataObject = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, AcquireData: fn( self: *const IPrintAsyncNotifyDataObject, ppNotificationData: ?*?*u8, pSize: ?*u32, ppSchema: ?*?*Guid, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ReleaseData: fn( self: *const IPrintAsyncNotifyDataObject, ) 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 IPrintAsyncNotifyDataObject_AcquireData(self: *const T, ppNotificationData: ?*?*u8, pSize: ?*u32, ppSchema: ?*?*Guid) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyDataObject.VTable, self.vtable).AcquireData(@ptrCast(*const IPrintAsyncNotifyDataObject, self), ppNotificationData, pSize, ppSchema); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyDataObject_ReleaseData(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyDataObject.VTable, self.vtable).ReleaseData(@ptrCast(*const IPrintAsyncNotifyDataObject, self)); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPrintAsyncNotifyChannel_Value = Guid.initString("4a5031b1-1f3f-4db0-a462-4530ed8b0451"); pub const IID_IPrintAsyncNotifyChannel = &IID_IPrintAsyncNotifyChannel_Value; pub const IPrintAsyncNotifyChannel = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SendNotification: fn( self: *const IPrintAsyncNotifyChannel, pData: ?*IPrintAsyncNotifyDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CloseChannel: fn( self: *const IPrintAsyncNotifyChannel, pData: ?*IPrintAsyncNotifyDataObject, ) 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 IPrintAsyncNotifyChannel_SendNotification(self: *const T, pData: ?*IPrintAsyncNotifyDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyChannel.VTable, self.vtable).SendNotification(@ptrCast(*const IPrintAsyncNotifyChannel, self), pData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyChannel_CloseChannel(self: *const T, pData: ?*IPrintAsyncNotifyDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyChannel.VTable, self.vtable).CloseChannel(@ptrCast(*const IPrintAsyncNotifyChannel, self), pData); } };} pub usingnamespace MethodMixin(@This()); }; // TODO: this type is limited to platform 'windows6.0.6000' const IID_IPrintAsyncNotifyCallback_Value = Guid.initString("7def34c1-9d92-4c99-b3b3-db94a9d4191b"); pub const IID_IPrintAsyncNotifyCallback = &IID_IPrintAsyncNotifyCallback_Value; pub const IPrintAsyncNotifyCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, OnEventNotify: fn( self: *const IPrintAsyncNotifyCallback, pChannel: ?*IPrintAsyncNotifyChannel, pData: ?*IPrintAsyncNotifyDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, ChannelClosed: fn( self: *const IPrintAsyncNotifyCallback, pChannel: ?*IPrintAsyncNotifyChannel, pData: ?*IPrintAsyncNotifyDataObject, ) 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 IPrintAsyncNotifyCallback_OnEventNotify(self: *const T, pChannel: ?*IPrintAsyncNotifyChannel, pData: ?*IPrintAsyncNotifyDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyCallback.VTable, self.vtable).OnEventNotify(@ptrCast(*const IPrintAsyncNotifyCallback, self), pChannel, pData); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyCallback_ChannelClosed(self: *const T, pChannel: ?*IPrintAsyncNotifyChannel, pData: ?*IPrintAsyncNotifyDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyCallback.VTable, self.vtable).ChannelClosed(@ptrCast(*const IPrintAsyncNotifyCallback, self), pChannel, pData); } };} pub usingnamespace MethodMixin(@This()); }; pub const PrintAsyncNotifyError = enum(i32) { CHANNEL_CLOSED_BY_SERVER = 1, CHANNEL_CLOSED_BY_ANOTHER_LISTENER = 2, CHANNEL_CLOSED_BY_SAME_LISTENER = 3, CHANNEL_RELEASED_BY_LISTENER = 4, UNIRECTIONAL_NOTIFICATION_LOST = 5, ASYNC_NOTIFICATION_FAILURE = 6, NO_LISTENERS = 7, CHANNEL_ALREADY_CLOSED = 8, CHANNEL_ALREADY_OPENED = 9, CHANNEL_WAITING_FOR_CLIENT_NOTIFICATION = 10, CHANNEL_NOT_OPENED = 11, ASYNC_CALL_ALREADY_PARKED = 12, NOT_REGISTERED = 13, ALREADY_UNREGISTERED = 14, ALREADY_REGISTERED = 15, CHANNEL_ACQUIRED = 16, ASYNC_CALL_IN_PROGRESS = 17, MAX_NOTIFICATION_SIZE_EXCEEDED = 18, INTERNAL_NOTIFICATION_QUEUE_IS_FULL = 19, INVALID_NOTIFICATION_TYPE = 20, MAX_REGISTRATION_COUNT_EXCEEDED = 21, MAX_CHANNEL_COUNT_EXCEEDED = 22, LOCAL_ONLY_REGISTRATION = 23, REMOTE_ONLY_REGISTRATION = 24, }; pub const CHANNEL_CLOSED_BY_SERVER = PrintAsyncNotifyError.CHANNEL_CLOSED_BY_SERVER; pub const CHANNEL_CLOSED_BY_ANOTHER_LISTENER = PrintAsyncNotifyError.CHANNEL_CLOSED_BY_ANOTHER_LISTENER; pub const CHANNEL_CLOSED_BY_SAME_LISTENER = PrintAsyncNotifyError.CHANNEL_CLOSED_BY_SAME_LISTENER; pub const CHANNEL_RELEASED_BY_LISTENER = PrintAsyncNotifyError.CHANNEL_RELEASED_BY_LISTENER; pub const UNIRECTIONAL_NOTIFICATION_LOST = PrintAsyncNotifyError.UNIRECTIONAL_NOTIFICATION_LOST; pub const ASYNC_NOTIFICATION_FAILURE = PrintAsyncNotifyError.ASYNC_NOTIFICATION_FAILURE; pub const NO_LISTENERS = PrintAsyncNotifyError.NO_LISTENERS; pub const CHANNEL_ALREADY_CLOSED = PrintAsyncNotifyError.CHANNEL_ALREADY_CLOSED; pub const CHANNEL_ALREADY_OPENED = PrintAsyncNotifyError.CHANNEL_ALREADY_OPENED; pub const CHANNEL_WAITING_FOR_CLIENT_NOTIFICATION = PrintAsyncNotifyError.CHANNEL_WAITING_FOR_CLIENT_NOTIFICATION; pub const CHANNEL_NOT_OPENED = PrintAsyncNotifyError.CHANNEL_NOT_OPENED; pub const ASYNC_CALL_ALREADY_PARKED = PrintAsyncNotifyError.ASYNC_CALL_ALREADY_PARKED; pub const NOT_REGISTERED = PrintAsyncNotifyError.NOT_REGISTERED; pub const ALREADY_UNREGISTERED = PrintAsyncNotifyError.ALREADY_UNREGISTERED; pub const ALREADY_REGISTERED = PrintAsyncNotifyError.ALREADY_REGISTERED; pub const CHANNEL_ACQUIRED = PrintAsyncNotifyError.CHANNEL_ACQUIRED; pub const ASYNC_CALL_IN_PROGRESS = PrintAsyncNotifyError.ASYNC_CALL_IN_PROGRESS; pub const MAX_NOTIFICATION_SIZE_EXCEEDED = PrintAsyncNotifyError.MAX_NOTIFICATION_SIZE_EXCEEDED; pub const INTERNAL_NOTIFICATION_QUEUE_IS_FULL = PrintAsyncNotifyError.INTERNAL_NOTIFICATION_QUEUE_IS_FULL; pub const INVALID_NOTIFICATION_TYPE = PrintAsyncNotifyError.INVALID_NOTIFICATION_TYPE; pub const MAX_REGISTRATION_COUNT_EXCEEDED = PrintAsyncNotifyError.MAX_REGISTRATION_COUNT_EXCEEDED; pub const MAX_CHANNEL_COUNT_EXCEEDED = PrintAsyncNotifyError.MAX_CHANNEL_COUNT_EXCEEDED; pub const LOCAL_ONLY_REGISTRATION = PrintAsyncNotifyError.LOCAL_ONLY_REGISTRATION; pub const REMOTE_ONLY_REGISTRATION = PrintAsyncNotifyError.REMOTE_ONLY_REGISTRATION; const IID_IPrintAsyncNotifyRegistration_Value = Guid.initString("0f6f27b6-6f86-4591-9203-64c3bfadedfe"); pub const IID_IPrintAsyncNotifyRegistration = &IID_IPrintAsyncNotifyRegistration_Value; pub const IPrintAsyncNotifyRegistration = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RegisterForNotifications: fn( self: *const IPrintAsyncNotifyRegistration, ) callconv(@import("std").os.windows.WINAPI) HRESULT, UnregisterForNotifications: fn( self: *const IPrintAsyncNotifyRegistration, ) 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 IPrintAsyncNotifyRegistration_RegisterForNotifications(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyRegistration.VTable, self.vtable).RegisterForNotifications(@ptrCast(*const IPrintAsyncNotifyRegistration, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyRegistration_UnregisterForNotifications(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyRegistration.VTable, self.vtable).UnregisterForNotifications(@ptrCast(*const IPrintAsyncNotifyRegistration, self)); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IPrintAsyncNotify_Value = Guid.initString("532818f7-921b-4fb2-bff8-2f4fd52ebebf"); pub const IID_IPrintAsyncNotify = &IID_IPrintAsyncNotify_Value; pub const IPrintAsyncNotify = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreatePrintAsyncNotifyChannel: fn( self: *const IPrintAsyncNotify, param0: u32, param1: ?*Guid, param2: PrintAsyncNotifyUserFilter, param3: PrintAsyncNotifyConversationStyle, param4: ?*IPrintAsyncNotifyCallback, param5: ?*?*IPrintAsyncNotifyChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CreatePrintAsyncNotifyRegistration: fn( self: *const IPrintAsyncNotify, param0: ?*Guid, param1: PrintAsyncNotifyUserFilter, param2: PrintAsyncNotifyConversationStyle, param3: ?*IPrintAsyncNotifyCallback, param4: ?*?*IPrintAsyncNotifyRegistration, ) 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 IPrintAsyncNotify_CreatePrintAsyncNotifyChannel(self: *const T, param0: u32, param1: ?*Guid, param2: PrintAsyncNotifyUserFilter, param3: PrintAsyncNotifyConversationStyle, param4: ?*IPrintAsyncNotifyCallback, param5: ?*?*IPrintAsyncNotifyChannel) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotify.VTable, self.vtable).CreatePrintAsyncNotifyChannel(@ptrCast(*const IPrintAsyncNotify, self), param0, param1, param2, param3, param4, param5); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotify_CreatePrintAsyncNotifyRegistration(self: *const T, param0: ?*Guid, param1: PrintAsyncNotifyUserFilter, param2: PrintAsyncNotifyConversationStyle, param3: ?*IPrintAsyncNotifyCallback, param4: ?*?*IPrintAsyncNotifyRegistration) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotify.VTable, self.vtable).CreatePrintAsyncNotifyRegistration(@ptrCast(*const IPrintAsyncNotify, self), param0, param1, param2, param3, param4); } };} pub usingnamespace MethodMixin(@This()); }; pub const IPrintAsyncCookie = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, FinishAsyncCall: fn( self: *const IPrintAsyncCookie, param0: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelAsyncCall: fn( self: *const IPrintAsyncCookie, param0: HRESULT, ) 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 IPrintAsyncCookie_FinishAsyncCall(self: *const T, param0: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncCookie.VTable, self.vtable).FinishAsyncCall(@ptrCast(*const IPrintAsyncCookie, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncCookie_CancelAsyncCall(self: *const T, param0: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncCookie.VTable, self.vtable).CancelAsyncCall(@ptrCast(*const IPrintAsyncCookie, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; pub const IPrintAsyncNewChannelCookie = extern struct { pub const VTable = extern struct { base: IPrintAsyncCookie.VTable, FinishAsyncCallWithData: fn( self: *const IPrintAsyncNewChannelCookie, param0: ?*?*IPrintAsyncNotifyChannel, param1: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintAsyncCookie.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNewChannelCookie_FinishAsyncCallWithData(self: *const T, param0: ?*?*IPrintAsyncNotifyChannel, param1: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNewChannelCookie.VTable, self.vtable).FinishAsyncCallWithData(@ptrCast(*const IPrintAsyncNewChannelCookie, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; pub const IAsyncGetSendNotificationCookie = extern struct { pub const VTable = extern struct { base: IPrintAsyncCookie.VTable, FinishAsyncCallWithData: fn( self: *const IAsyncGetSendNotificationCookie, param0: ?*IPrintAsyncNotifyDataObject, param1: BOOL, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintAsyncCookie.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAsyncGetSendNotificationCookie_FinishAsyncCallWithData(self: *const T, param0: ?*IPrintAsyncNotifyDataObject, param1: BOOL) callconv(.Inline) HRESULT { return @ptrCast(*const IAsyncGetSendNotificationCookie.VTable, self.vtable).FinishAsyncCallWithData(@ptrCast(*const IAsyncGetSendNotificationCookie, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; pub const IAsyncGetSrvReferralCookie = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, FinishAsyncCall: fn( self: *const IAsyncGetSrvReferralCookie, param0: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, CancelAsyncCall: fn( self: *const IAsyncGetSrvReferralCookie, param0: HRESULT, ) callconv(@import("std").os.windows.WINAPI) HRESULT, FinishAsyncCallWithData: fn( self: *const IAsyncGetSrvReferralCookie, param0: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAsyncGetSrvReferralCookie_FinishAsyncCall(self: *const T, param0: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IAsyncGetSrvReferralCookie.VTable, self.vtable).FinishAsyncCall(@ptrCast(*const IAsyncGetSrvReferralCookie, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAsyncGetSrvReferralCookie_CancelAsyncCall(self: *const T, param0: HRESULT) callconv(.Inline) HRESULT { return @ptrCast(*const IAsyncGetSrvReferralCookie.VTable, self.vtable).CancelAsyncCall(@ptrCast(*const IAsyncGetSrvReferralCookie, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IAsyncGetSrvReferralCookie_FinishAsyncCallWithData(self: *const T, param0: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IAsyncGetSrvReferralCookie.VTable, self.vtable).FinishAsyncCallWithData(@ptrCast(*const IAsyncGetSrvReferralCookie, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; pub const IPrintBidiAsyncNotifyRegistration = extern struct { pub const VTable = extern struct { base: IPrintAsyncNotifyRegistration.VTable, AsyncGetNewChannel: fn( self: *const IPrintBidiAsyncNotifyRegistration, param0: ?*IPrintAsyncNewChannelCookie, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintAsyncNotifyRegistration.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintBidiAsyncNotifyRegistration_AsyncGetNewChannel(self: *const T, param0: ?*IPrintAsyncNewChannelCookie) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintBidiAsyncNotifyRegistration.VTable, self.vtable).AsyncGetNewChannel(@ptrCast(*const IPrintBidiAsyncNotifyRegistration, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; pub const IPrintUnidiAsyncNotifyRegistration = extern struct { pub const VTable = extern struct { base: IPrintAsyncNotifyRegistration.VTable, AsyncGetNotification: fn( self: *const IPrintUnidiAsyncNotifyRegistration, param0: ?*IAsyncGetSendNotificationCookie, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintAsyncNotifyRegistration.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintUnidiAsyncNotifyRegistration_AsyncGetNotification(self: *const T, param0: ?*IAsyncGetSendNotificationCookie) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintUnidiAsyncNotifyRegistration.VTable, self.vtable).AsyncGetNotification(@ptrCast(*const IPrintUnidiAsyncNotifyRegistration, self), param0); } };} pub usingnamespace MethodMixin(@This()); }; pub const IPrintAsyncNotifyServerReferral = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, GetServerReferral: fn( self: *const IPrintAsyncNotifyServerReferral, param0: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AsyncGetServerReferral: fn( self: *const IPrintAsyncNotifyServerReferral, param0: ?*IAsyncGetSrvReferralCookie, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetServerReferral: fn( self: *const IPrintAsyncNotifyServerReferral, pRmtServerReferral: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyServerReferral_GetServerReferral(self: *const T, param0: ?*?PWSTR) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyServerReferral.VTable, self.vtable).GetServerReferral(@ptrCast(*const IPrintAsyncNotifyServerReferral, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyServerReferral_AsyncGetServerReferral(self: *const T, param0: ?*IAsyncGetSrvReferralCookie) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyServerReferral.VTable, self.vtable).AsyncGetServerReferral(@ptrCast(*const IPrintAsyncNotifyServerReferral, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintAsyncNotifyServerReferral_SetServerReferral(self: *const T, pRmtServerReferral: ?[*:0]const u16) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintAsyncNotifyServerReferral.VTable, self.vtable).SetServerReferral(@ptrCast(*const IPrintAsyncNotifyServerReferral, self), pRmtServerReferral); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IBidiAsyncNotifyChannel_Value = Guid.initString("532818f7-921b-4fb2-bff8-2f4fd52ebebf"); pub const IID_IBidiAsyncNotifyChannel = &IID_IBidiAsyncNotifyChannel_Value; pub const IBidiAsyncNotifyChannel = extern struct { pub const VTable = extern struct { base: IPrintAsyncNotifyChannel.VTable, CreateNotificationChannel: fn( self: *const IBidiAsyncNotifyChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetPrintName: fn( self: *const IBidiAsyncNotifyChannel, param0: ?*?*IPrintAsyncNotifyDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, GetChannelNotificationType: fn( self: *const IBidiAsyncNotifyChannel, param0: ?*?*IPrintAsyncNotifyDataObject, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AsyncGetNotificationSendResponse: fn( self: *const IBidiAsyncNotifyChannel, param0: ?*IPrintAsyncNotifyDataObject, param1: ?*IAsyncGetSendNotificationCookie, ) callconv(@import("std").os.windows.WINAPI) HRESULT, AsyncCloseChannel: fn( self: *const IBidiAsyncNotifyChannel, param0: ?*IPrintAsyncNotifyDataObject, param1: ?*IPrintAsyncCookie, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IPrintAsyncNotifyChannel.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IBidiAsyncNotifyChannel_CreateNotificationChannel(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IBidiAsyncNotifyChannel.VTable, self.vtable).CreateNotificationChannel(@ptrCast(*const IBidiAsyncNotifyChannel, self)); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IBidiAsyncNotifyChannel_GetPrintName(self: *const T, param0: ?*?*IPrintAsyncNotifyDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IBidiAsyncNotifyChannel.VTable, self.vtable).GetPrintName(@ptrCast(*const IBidiAsyncNotifyChannel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IBidiAsyncNotifyChannel_GetChannelNotificationType(self: *const T, param0: ?*?*IPrintAsyncNotifyDataObject) callconv(.Inline) HRESULT { return @ptrCast(*const IBidiAsyncNotifyChannel.VTable, self.vtable).GetChannelNotificationType(@ptrCast(*const IBidiAsyncNotifyChannel, self), param0); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IBidiAsyncNotifyChannel_AsyncGetNotificationSendResponse(self: *const T, param0: ?*IPrintAsyncNotifyDataObject, param1: ?*IAsyncGetSendNotificationCookie) callconv(.Inline) HRESULT { return @ptrCast(*const IBidiAsyncNotifyChannel.VTable, self.vtable).AsyncGetNotificationSendResponse(@ptrCast(*const IBidiAsyncNotifyChannel, self), param0, param1); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IBidiAsyncNotifyChannel_AsyncCloseChannel(self: *const T, param0: ?*IPrintAsyncNotifyDataObject, param1: ?*IPrintAsyncCookie) callconv(.Inline) HRESULT { return @ptrCast(*const IBidiAsyncNotifyChannel.VTable, self.vtable).AsyncCloseChannel(@ptrCast(*const IBidiAsyncNotifyChannel, self), param0, param1); } };} pub usingnamespace MethodMixin(@This()); }; pub const UNIFM_HDR = extern struct { dwSize: u32, dwVersion: u32, ulDefaultCodepage: u32, lGlyphSetDataRCID: i32, loUnidrvInfo: u32, loIFIMetrics: u32, loExtTextMetric: u32, loWidthTable: u32, loKernPair: u32, dwReserved: [2]u32, }; pub const INVOC = extern struct { dwCount: u32, loOffset: u32, }; pub const UNIDRVINFO = extern struct { dwSize: u32, flGenFlags: u32, wType: u16, fCaps: u16, wXRes: u16, wYRes: u16, sYAdjust: i16, sYMoved: i16, wPrivateData: u16, sShift: i16, SelectFont: INVOC, UnSelectFont: INVOC, wReserved: [4]u16, }; pub const PRINTIFI32 = extern struct { cjThis: u32, cjIfiExtra: u32, dpwszFamilyName: i32, dpwszStyleName: i32, dpwszFaceName: i32, dpwszUniqueName: i32, dpFontSim: i32, lEmbedId: i32, lItalicAngle: i32, lCharBias: i32, dpCharSets: i32, jWinCharSet: u8, jWinPitchAndFamily: u8, usWinWeight: u16, flInfo: u32, fsSelection: u16, fsType: u16, fwdUnitsPerEm: i16, fwdLowestPPEm: i16, fwdWinAscender: i16, fwdWinDescender: i16, fwdMacAscender: i16, fwdMacDescender: i16, fwdMacLineGap: i16, fwdTypoAscender: i16, fwdTypoDescender: i16, fwdTypoLineGap: i16, fwdAveCharWidth: i16, fwdMaxCharInc: i16, fwdCapHeight: i16, fwdXHeight: i16, fwdSubscriptXSize: i16, fwdSubscriptYSize: i16, fwdSubscriptXOffset: i16, fwdSubscriptYOffset: i16, fwdSuperscriptXSize: i16, fwdSuperscriptYSize: i16, fwdSuperscriptXOffset: i16, fwdSuperscriptYOffset: i16, fwdUnderscoreSize: i16, fwdUnderscorePosition: i16, fwdStrikeoutSize: i16, fwdStrikeoutPosition: i16, chFirstChar: u8, chLastChar: u8, chDefaultChar: u8, chBreakChar: u8, wcFirstChar: u16, wcLastChar: u16, wcDefaultChar: u16, wcBreakChar: u16, ptlBaseline: POINTL, ptlAspect: POINTL, ptlCaret: POINTL, rclFontBox: RECTL, achVendId: [4]u8, cKerningPairs: u32, ulPanoseCulture: u32, panose: PANOSE, }; pub const EXTTEXTMETRIC = extern struct { emSize: i16, emPointSize: i16, emOrientation: i16, emMasterHeight: i16, emMinScale: i16, emMaxScale: i16, emMasterUnits: i16, emCapHeight: i16, emXHeight: i16, emLowerCaseAscent: i16, emLowerCaseDescent: i16, emSlant: i16, emSuperScript: i16, emSubScript: i16, emSuperScriptSize: i16, emSubScriptSize: i16, emUnderlineOffset: i16, emUnderlineWidth: i16, emDoubleUpperUnderlineOffset: i16, emDoubleLowerUnderlineOffset: i16, emDoubleUpperUnderlineWidth: i16, emDoubleLowerUnderlineWidth: i16, emStrikeOutOffset: i16, emStrikeOutWidth: i16, emKernPairs: u16, emKernTracks: u16, }; pub const WIDTHRUN = extern struct { wStartGlyph: u16, wGlyphCount: u16, loCharWidthOffset: u32, }; pub const WIDTHTABLE = extern struct { dwSize: u32, dwRunNum: u32, WidthRun: [1]WIDTHRUN, }; pub const KERNDATA = extern struct { dwSize: u32, dwKernPairNum: u32, KernPair: [1]FD_KERNINGPAIR, }; pub const UNI_GLYPHSETDATA = extern struct { dwSize: u32, dwVersion: u32, dwFlags: u32, lPredefinedID: i32, dwGlyphCount: u32, dwRunCount: u32, loRunOffset: u32, dwCodePageCount: u32, loCodePageOffset: u32, loMapTableOffset: u32, dwReserved: [2]u32, }; pub const UNI_CODEPAGEINFO = extern struct { dwCodePage: u32, SelectSymbolSet: INVOC, UnSelectSymbolSet: INVOC, }; pub const GLYPHRUN = extern struct { wcLow: u16, wGlyphCount: u16, }; pub const TRANSDATA = extern struct { ubCodePageID: u8, ubType: u8, uCode: extern union { sCode: i16, ubCode: u8, ubPairs: [2]u8, }, }; pub const MAPTABLE = extern struct { dwSize: u32, dwGlyphNum: u32, Trans: [1]TRANSDATA, }; pub const UFF_FILEHEADER = extern struct { dwSignature: u32, dwVersion: u32, dwSize: u32, nFonts: u32, nGlyphSets: u32, nVarData: u32, offFontDir: u32, dwFlags: u32, dwReserved: [4]u32, }; pub const UFF_FONTDIRECTORY = extern struct { dwSignature: u32, wSize: u16, wFontID: u16, sGlyphID: i16, wFlags: u16, dwInstallerSig: u32, offFontName: u32, offCartridgeName: u32, offFontData: u32, offGlyphData: u32, offVarData: u32, }; pub const DATA_HEADER = extern struct { dwSignature: u32, wSize: u16, wDataID: u16, dwDataSize: u32, dwReserved: u32, }; pub const OEMFONTINSTPARAM = extern struct { cbSize: u32, hPrinter: ?HANDLE, hModule: ?HANDLE, hHeap: ?HANDLE, dwFlags: u32, pFontInstallerName: ?PWSTR, }; pub const PORT_DATA_1 = extern struct { sztPortName: [64]u16, dwVersion: u32, dwProtocol: u32, cbSize: u32, dwReserved: u32, sztHostAddress: [49]u16, sztSNMPCommunity: [33]u16, dwDoubleSpool: u32, sztQueue: [33]u16, sztIPAddress: [16]u16, Reserved: [540]u8, dwPortNumber: u32, dwSNMPEnabled: u32, dwSNMPDevIndex: u32, }; pub const PORT_DATA_2 = extern struct { sztPortName: [64]u16, dwVersion: u32, dwProtocol: u32, cbSize: u32, dwReserved: u32, sztHostAddress: [128]u16, sztSNMPCommunity: [33]u16, dwDoubleSpool: u32, sztQueue: [33]u16, Reserved: [514]u8, dwPortNumber: u32, dwSNMPEnabled: u32, dwSNMPDevIndex: u32, dwPortMonitorMibIndex: u32, }; pub const PORT_DATA_LIST_1 = extern struct { dwVersion: u32, cPortData: u32, pPortData: [1]PORT_DATA_2, }; pub const DELETE_PORT_DATA_1 = extern struct { psztPortName: [64]u16, Reserved: [98]u8, dwVersion: u32, dwReserved: u32, }; pub const CONFIG_INFO_DATA_1 = extern struct { Reserved: [128]u8, dwVersion: u32, }; pub const EMFPLAYPROC = fn( param0: ?HDC, param1: i32, param2: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) i32; pub const EBranchOfficeJobEventType = enum(i32) { InvalidJobState = 0, LogJobPrinted = 1, LogJobRendered = 2, LogJobError = 3, LogJobPipelineError = 4, LogOfflineFileFull = 5, }; pub const kInvalidJobState = EBranchOfficeJobEventType.InvalidJobState; pub const kLogJobPrinted = EBranchOfficeJobEventType.LogJobPrinted; pub const kLogJobRendered = EBranchOfficeJobEventType.LogJobRendered; pub const kLogJobError = EBranchOfficeJobEventType.LogJobError; pub const kLogJobPipelineError = EBranchOfficeJobEventType.LogJobPipelineError; pub const kLogOfflineFileFull = EBranchOfficeJobEventType.LogOfflineFileFull; pub const BranchOfficeJobDataPrinted = extern struct { Status: u32, pDocumentName: ?PWSTR, pUserName: ?PWSTR, pMachineName: ?PWSTR, pPrinterName: ?PWSTR, pPortName: ?PWSTR, Size: i64, TotalPages: u32, }; pub const BranchOfficeJobDataError = extern struct { LastError: u32, pDocumentName: ?PWSTR, pUserName: ?PWSTR, pPrinterName: ?PWSTR, pDataType: ?PWSTR, TotalSize: i64, PrintedSize: i64, TotalPages: u32, PrintedPages: u32, pMachineName: ?PWSTR, pJobError: ?PWSTR, pErrorDescription: ?PWSTR, }; pub const BranchOfficeJobDataRendered = extern struct { Size: i64, ICMMethod: u32, Color: i16, PrintQuality: i16, YResolution: i16, Copies: i16, TTOption: i16, }; pub const BranchOfficeJobDataPipelineFailed = extern struct { pDocumentName: ?PWSTR, pPrinterName: ?PWSTR, pExtraErrorInfo: ?PWSTR, }; pub const BranchOfficeLogOfflineFileFull = extern struct { pMachineName: ?PWSTR, }; pub const BranchOfficeJobData = extern struct { eEventType: EBranchOfficeJobEventType, JobId: u32, JobInfo: extern union { LogJobPrinted: BranchOfficeJobDataPrinted, LogJobRendered: BranchOfficeJobDataRendered, LogJobError: BranchOfficeJobDataError, LogPipelineFailed: BranchOfficeJobDataPipelineFailed, LogOfflineFileFull: BranchOfficeLogOfflineFileFull, }, }; pub const BranchOfficeJobDataContainer = extern struct { cJobDataEntries: u32, JobData: [1]BranchOfficeJobData, }; pub const PRINTER_NOTIFY_INIT = extern struct { Size: u32, Reserved: u32, PollTime: u32, }; pub const SPLCLIENT_INFO_1 = extern struct { dwSize: u32, pMachineName: ?PWSTR, pUserName: ?PWSTR, dwBuildNum: u32, dwMajorVersion: u32, dwMinorVersion: u32, wProcessorArchitecture: u16, }; pub const _SPLCLIENT_INFO_2_V1 = extern struct { hSplPrinter: usize, }; pub const _SPLCLIENT_INFO_2_V3 = extern struct { hSplPrinter: u64, }; pub const SPLCLIENT_INFO_3_VISTA = extern struct { cbSize: u32, dwFlags: u32, dwSize: u32, pMachineName: ?PWSTR, pUserName: ?PWSTR, dwBuildNum: u32, dwMajorVersion: u32, dwMinorVersion: u32, wProcessorArchitecture: u16, hSplPrinter: u64, }; pub const PRINTPROVIDOR = extern struct { fpOpenPrinter: isize, fpSetJob: isize, fpGetJob: isize, fpEnumJobs: isize, fpAddPrinter: isize, fpDeletePrinter: isize, fpSetPrinter: isize, fpGetPrinter: isize, fpEnumPrinters: isize, fpAddPrinterDriver: isize, fpEnumPrinterDrivers: isize, fpGetPrinterDriver: isize, fpGetPrinterDriverDirectory: isize, fpDeletePrinterDriver: isize, fpAddPrintProcessor: isize, fpEnumPrintProcessors: isize, fpGetPrintProcessorDirectory: isize, fpDeletePrintProcessor: isize, fpEnumPrintProcessorDatatypes: isize, fpStartDocPrinter: isize, fpStartPagePrinter: isize, fpWritePrinter: isize, fpEndPagePrinter: isize, fpAbortPrinter: isize, fpReadPrinter: isize, fpEndDocPrinter: isize, fpAddJob: isize, fpScheduleJob: isize, fpGetPrinterData: isize, fpSetPrinterData: isize, fpWaitForPrinterChange: isize, fpClosePrinter: isize, fpAddForm: isize, fpDeleteForm: isize, fpGetForm: isize, fpSetForm: isize, fpEnumForms: isize, fpEnumMonitors: isize, fpEnumPorts: isize, fpAddPort: isize, fpConfigurePort: isize, fpDeletePort: isize, fpCreatePrinterIC: isize, fpPlayGdiScriptOnPrinterIC: isize, fpDeletePrinterIC: isize, fpAddPrinterConnection: isize, fpDeletePrinterConnection: isize, fpPrinterMessageBox: isize, fpAddMonitor: isize, fpDeleteMonitor: isize, fpResetPrinter: isize, fpGetPrinterDriverEx: isize, fpFindFirstPrinterChangeNotification: isize, fpFindClosePrinterChangeNotification: isize, fpAddPortEx: isize, fpShutDown: isize, fpRefreshPrinterChangeNotification: isize, fpOpenPrinterEx: isize, fpAddPrinterEx: isize, fpSetPort: isize, fpEnumPrinterData: isize, fpDeletePrinterData: isize, fpClusterSplOpen: isize, fpClusterSplClose: isize, fpClusterSplIsAlive: isize, fpSetPrinterDataEx: isize, fpGetPrinterDataEx: isize, fpEnumPrinterDataEx: isize, fpEnumPrinterKey: isize, fpDeletePrinterDataEx: isize, fpDeletePrinterKey: isize, fpSeekPrinter: isize, fpDeletePrinterDriverEx: isize, fpAddPerMachineConnection: isize, fpDeletePerMachineConnection: isize, fpEnumPerMachineConnections: isize, fpXcvData: isize, fpAddPrinterDriverEx: isize, fpSplReadPrinter: isize, fpDriverUnloadComplete: isize, fpGetSpoolFileInfo: isize, fpCommitSpoolData: isize, fpCloseSpoolFileHandle: isize, fpFlushPrinter: isize, fpSendRecvBidiData: isize, fpAddPrinterConnection2: isize, fpGetPrintClassObject: isize, fpReportJobProcessingProgress: isize, fpEnumAndLogProvidorObjects: isize, fpInternalGetPrinterDriver: isize, fpFindCompatibleDriver: isize, fpGetJobNamedPropertyValue: isize, fpSetJobNamedProperty: isize, fpDeleteJobNamedProperty: isize, fpEnumJobNamedProperties: isize, fpPowerEvent: isize, fpGetUserPropertyBag: isize, fpCanShutdown: isize, fpLogJobInfoForBranchOffice: isize, fpRegeneratePrintDeviceCapabilities: isize, fpPrintSupportOperation: isize, fpIppCreateJobOnPrinter: isize, fpIppGetJobAttributes: isize, fpIppSetJobAttributes: isize, fpIppGetPrinterAttributes: isize, fpIppSetPrinterAttributes: isize, }; pub const PRINTPROCESSOROPENDATA = extern struct { pDevMode: ?*DEVMODEA, pDatatype: ?PWSTR, pParameters: ?PWSTR, pDocumentName: ?PWSTR, JobId: u32, pOutputFile: ?PWSTR, pPrinterName: ?PWSTR, }; pub const MONITORREG = extern struct { cbSize: u32, fpCreateKey: isize, fpOpenKey: isize, fpCloseKey: isize, fpDeleteKey: isize, fpEnumKey: isize, fpQueryInfoKey: isize, fpSetValue: isize, fpDeleteValue: isize, fpEnumValue: isize, fpQueryValue: isize, }; pub const MONITORINIT = extern struct { cbSize: u32, hSpooler: ?HANDLE, hckRegistryRoot: ?HKEY, pMonitorReg: ?*MONITORREG, bLocal: BOOL, pszServerName: ?[*:0]const u16, }; pub const MONITOR = extern struct { pfnEnumPorts: isize, pfnOpenPort: isize, pfnOpenPortEx: isize, pfnStartDocPort: isize, pfnWritePort: isize, pfnReadPort: isize, pfnEndDocPort: isize, pfnClosePort: isize, pfnAddPort: isize, pfnAddPortEx: isize, pfnConfigurePort: isize, pfnDeletePort: isize, pfnGetPrinterDataFromPort: isize, pfnSetPortTimeOuts: isize, pfnXcvOpenPort: isize, pfnXcvDataPort: isize, pfnXcvClosePort: isize, }; pub const MONITOREX = extern struct { dwMonitorSize: u32, Monitor: MONITOR, }; pub const MONITOR2 = extern struct { cbSize: u32, pfnEnumPorts: isize, pfnOpenPort: isize, pfnOpenPortEx: isize, pfnStartDocPort: isize, pfnWritePort: isize, pfnReadPort: isize, pfnEndDocPort: isize, pfnClosePort: isize, pfnAddPort: isize, pfnAddPortEx: isize, pfnConfigurePort: isize, pfnDeletePort: isize, pfnGetPrinterDataFromPort: isize, pfnSetPortTimeOuts: isize, pfnXcvOpenPort: isize, pfnXcvDataPort: isize, pfnXcvClosePort: isize, pfnShutdown: isize, pfnSendRecvBidiDataFromPort: isize, pfnNotifyUsedPorts: isize, pfnNotifyUnusedPorts: isize, pfnPowerEvent: isize, }; pub const MONITORUI = extern struct { dwMonitorUISize: u32, pfnAddPortUI: isize, pfnConfigurePortUI: isize, pfnDeletePortUI: isize, }; pub const ROUTER_NOTIFY_CALLBACK = fn( dwCommand: u32, pContext: ?*anyopaque, dwColor: u32, pNofityInfo: ?*PRINTER_NOTIFY_INFO, fdwFlags: u32, pdwResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub const NOTIFICATION_CALLBACK_COMMANDS = enum(i32) { NOTIFY = 0, CONTEXT_ACQUIRE = 1, CONTEXT_RELEASE = 2, }; pub const NOTIFICATION_COMMAND_NOTIFY = NOTIFICATION_CALLBACK_COMMANDS.NOTIFY; pub const NOTIFICATION_COMMAND_CONTEXT_ACQUIRE = NOTIFICATION_CALLBACK_COMMANDS.CONTEXT_ACQUIRE; pub const NOTIFICATION_COMMAND_CONTEXT_RELEASE = NOTIFICATION_CALLBACK_COMMANDS.CONTEXT_RELEASE; pub const NOTIFICATION_CONFIG_1 = extern struct { cbSize: u32, fdwFlags: u32, pfnNotifyCallback: ?ROUTER_NOTIFY_CALLBACK, pContext: ?*anyopaque, }; pub const NOTIFICATION_CONFIG_FLAGS = enum(i32) { CREATE_EVENT = 1, REGISTER_CALLBACK = 2, EVENT_TRIGGER = 4, ASYNC_CHANNEL = 8, }; pub const NOTIFICATION_CONFIG_CREATE_EVENT = NOTIFICATION_CONFIG_FLAGS.CREATE_EVENT; pub const NOTIFICATION_CONFIG_REGISTER_CALLBACK = NOTIFICATION_CONFIG_FLAGS.REGISTER_CALLBACK; pub const NOTIFICATION_CONFIG_EVENT_TRIGGER = NOTIFICATION_CONFIG_FLAGS.EVENT_TRIGGER; pub const NOTIFICATION_CONFIG_ASYNC_CHANNEL = NOTIFICATION_CONFIG_FLAGS.ASYNC_CHANNEL; pub const UI_TYPE = enum(i32) { x = 0, }; pub const kMessageBox = UI_TYPE.x; pub const MESSAGEBOX_PARAMS = extern struct { cbSize: u32, pTitle: ?PWSTR, pMessage: ?PWSTR, Style: u32, dwTimeout: u32, bWait: BOOL, }; pub const SHOWUIPARAMS = extern struct { UIType: UI_TYPE, MessageBoxParams: MESSAGEBOX_PARAMS, }; const IID_IXpsRasterizerNotificationCallback_Value = Guid.initString("9ab8fd0d-cb94-49c2-9cb0-97ec1d5469d2"); pub const IID_IXpsRasterizerNotificationCallback = &IID_IXpsRasterizerNotificationCallback_Value; pub const IXpsRasterizerNotificationCallback = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, Continue: fn( self: *const IXpsRasterizerNotificationCallback, ) 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 IXpsRasterizerNotificationCallback_Continue(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsRasterizerNotificationCallback.VTable, self.vtable).Continue(@ptrCast(*const IXpsRasterizerNotificationCallback, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const XPSRAS_RENDERING_MODE = enum(i32) { NTIALIASED = 0, LIASED = 1, }; pub const XPSRAS_RENDERING_MODE_ANTIALIASED = XPSRAS_RENDERING_MODE.NTIALIASED; pub const XPSRAS_RENDERING_MODE_ALIASED = XPSRAS_RENDERING_MODE.LIASED; const IID_IXpsRasterizer_Value = Guid.initString("7567cfc8-c156-47a8-9dac-11a2ae5bdd6b"); pub const IID_IXpsRasterizer = &IID_IXpsRasterizer_Value; pub const IXpsRasterizer = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, RasterizeRect: fn( self: *const IXpsRasterizer, x: i32, y: i32, width: i32, height: i32, notificationCallback: ?*IXpsRasterizerNotificationCallback, bitmap: ?*?*IWICBitmap, ) callconv(@import("std").os.windows.WINAPI) HRESULT, SetMinimalLineWidth: fn( self: *const IXpsRasterizer, width: i32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, }; vtable: *const VTable, pub fn MethodMixin(comptime T: type) type { return struct { pub usingnamespace IUnknown.MethodMixin(T); // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsRasterizer_RasterizeRect(self: *const T, x: i32, y: i32, width: i32, height: i32, notificationCallback: ?*IXpsRasterizerNotificationCallback, bitmap: ?*?*IWICBitmap) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsRasterizer.VTable, self.vtable).RasterizeRect(@ptrCast(*const IXpsRasterizer, self), x, y, width, height, notificationCallback, bitmap); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IXpsRasterizer_SetMinimalLineWidth(self: *const T, width: i32) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsRasterizer.VTable, self.vtable).SetMinimalLineWidth(@ptrCast(*const IXpsRasterizer, self), width); } };} pub usingnamespace MethodMixin(@This()); }; const IID_IXpsRasterizationFactory_Value = Guid.initString("e094808a-24c6-482b-a3a7-c21ac9b55f17"); pub const IID_IXpsRasterizationFactory = &IID_IXpsRasterizationFactory_Value; pub const IXpsRasterizationFactory = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateRasterizer: fn( self: *const IXpsRasterizationFactory, xpsPage: ?*IXpsOMPage, DPI: f32, nonTextRenderingMode: XPSRAS_RENDERING_MODE, textRenderingMode: XPSRAS_RENDERING_MODE, ppIXPSRasterizer: ?*?*IXpsRasterizer, ) 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 IXpsRasterizationFactory_CreateRasterizer(self: *const T, xpsPage: ?*IXpsOMPage, DPI: f32, nonTextRenderingMode: XPSRAS_RENDERING_MODE, textRenderingMode: XPSRAS_RENDERING_MODE, ppIXPSRasterizer: ?*?*IXpsRasterizer) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsRasterizationFactory.VTable, self.vtable).CreateRasterizer(@ptrCast(*const IXpsRasterizationFactory, self), xpsPage, DPI, nonTextRenderingMode, textRenderingMode, ppIXPSRasterizer); } };} pub usingnamespace MethodMixin(@This()); }; pub const XPSRAS_PIXEL_FORMAT = enum(i32) { @"32BPP_PBGRA_UINT_SRGB" = 1, @"64BPP_PRGBA_HALF_SCRGB" = 2, @"128BPP_PRGBA_FLOAT_SCRGB" = 3, }; pub const XPSRAS_PIXEL_FORMAT_32BPP_PBGRA_UINT_SRGB = XPSRAS_PIXEL_FORMAT.@"32BPP_PBGRA_UINT_SRGB"; pub const XPSRAS_PIXEL_FORMAT_64BPP_PRGBA_HALF_SCRGB = XPSRAS_PIXEL_FORMAT.@"64BPP_PRGBA_HALF_SCRGB"; pub const XPSRAS_PIXEL_FORMAT_128BPP_PRGBA_FLOAT_SCRGB = XPSRAS_PIXEL_FORMAT.@"128BPP_PRGBA_FLOAT_SCRGB"; const IID_IXpsRasterizationFactory1_Value = Guid.initString("2d6e5f77-6414-4a1e-a8e0-d4194ce6a26f"); pub const IID_IXpsRasterizationFactory1 = &IID_IXpsRasterizationFactory1_Value; pub const IXpsRasterizationFactory1 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateRasterizer: fn( self: *const IXpsRasterizationFactory1, xpsPage: ?*IXpsOMPage, DPI: f32, nonTextRenderingMode: XPSRAS_RENDERING_MODE, textRenderingMode: XPSRAS_RENDERING_MODE, pixelFormat: XPSRAS_PIXEL_FORMAT, ppIXPSRasterizer: ?*?*IXpsRasterizer, ) 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 IXpsRasterizationFactory1_CreateRasterizer(self: *const T, xpsPage: ?*IXpsOMPage, DPI: f32, nonTextRenderingMode: XPSRAS_RENDERING_MODE, textRenderingMode: XPSRAS_RENDERING_MODE, pixelFormat: XPSRAS_PIXEL_FORMAT, ppIXPSRasterizer: ?*?*IXpsRasterizer) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsRasterizationFactory1.VTable, self.vtable).CreateRasterizer(@ptrCast(*const IXpsRasterizationFactory1, self), xpsPage, DPI, nonTextRenderingMode, textRenderingMode, pixelFormat, ppIXPSRasterizer); } };} pub usingnamespace MethodMixin(@This()); }; pub const XPSRAS_BACKGROUND_COLOR = enum(i32) { TRANSPARENT = 0, OPAQUE = 1, }; pub const XPSRAS_BACKGROUND_COLOR_TRANSPARENT = XPSRAS_BACKGROUND_COLOR.TRANSPARENT; pub const XPSRAS_BACKGROUND_COLOR_OPAQUE = XPSRAS_BACKGROUND_COLOR.OPAQUE; const IID_IXpsRasterizationFactory2_Value = Guid.initString("9c16ce3e-10f5-41fd-9ddc-6826669c2ff6"); pub const IID_IXpsRasterizationFactory2 = &IID_IXpsRasterizationFactory2_Value; pub const IXpsRasterizationFactory2 = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, CreateRasterizer: fn( self: *const IXpsRasterizationFactory2, xpsPage: ?*IXpsOMPage, DPIX: f32, DPIY: f32, nonTextRenderingMode: XPSRAS_RENDERING_MODE, textRenderingMode: XPSRAS_RENDERING_MODE, pixelFormat: XPSRAS_PIXEL_FORMAT, backgroundColor: XPSRAS_BACKGROUND_COLOR, ppIXpsRasterizer: ?*?*IXpsRasterizer, ) 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 IXpsRasterizationFactory2_CreateRasterizer(self: *const T, xpsPage: ?*IXpsOMPage, DPIX: f32, DPIY: f32, nonTextRenderingMode: XPSRAS_RENDERING_MODE, textRenderingMode: XPSRAS_RENDERING_MODE, pixelFormat: XPSRAS_PIXEL_FORMAT, backgroundColor: XPSRAS_BACKGROUND_COLOR, ppIXpsRasterizer: ?*?*IXpsRasterizer) callconv(.Inline) HRESULT { return @ptrCast(*const IXpsRasterizationFactory2.VTable, self.vtable).CreateRasterizer(@ptrCast(*const IXpsRasterizationFactory2, self), xpsPage, DPIX, DPIY, nonTextRenderingMode, textRenderingMode, pixelFormat, backgroundColor, ppIXpsRasterizer); } };} pub usingnamespace MethodMixin(@This()); }; pub const PageCountType = enum(i32) { FinalPageCount = 0, IntermediatePageCount = 1, }; pub const FinalPageCount = PageCountType.FinalPageCount; pub const IntermediatePageCount = PageCountType.IntermediatePageCount; const IID_IPrintPreviewDxgiPackageTarget_Value = Guid.initString("1a6dd0ad-1e2a-4e99-a5ba-91f17818290e"); pub const IID_IPrintPreviewDxgiPackageTarget = &IID_IPrintPreviewDxgiPackageTarget_Value; pub const IPrintPreviewDxgiPackageTarget = extern struct { pub const VTable = extern struct { base: IUnknown.VTable, SetJobPageCount: fn( self: *const IPrintPreviewDxgiPackageTarget, countType: PageCountType, count: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, DrawPage: fn( self: *const IPrintPreviewDxgiPackageTarget, jobPageNumber: u32, pageImage: ?*IDXGISurface, dpiX: f32, dpiY: f32, ) callconv(@import("std").os.windows.WINAPI) HRESULT, InvalidatePreview: fn( self: *const IPrintPreviewDxgiPackageTarget, ) 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 IPrintPreviewDxgiPackageTarget_SetJobPageCount(self: *const T, countType: PageCountType, count: u32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintPreviewDxgiPackageTarget.VTable, self.vtable).SetJobPageCount(@ptrCast(*const IPrintPreviewDxgiPackageTarget, self), countType, count); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintPreviewDxgiPackageTarget_DrawPage(self: *const T, jobPageNumber: u32, pageImage: ?*IDXGISurface, dpiX: f32, dpiY: f32) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintPreviewDxgiPackageTarget.VTable, self.vtable).DrawPage(@ptrCast(*const IPrintPreviewDxgiPackageTarget, self), jobPageNumber, pageImage, dpiX, dpiY); } // NOTE: method is namespaced with interface name to avoid conflicts for now pub fn IPrintPreviewDxgiPackageTarget_InvalidatePreview(self: *const T) callconv(.Inline) HRESULT { return @ptrCast(*const IPrintPreviewDxgiPackageTarget.VTable, self.vtable).InvalidatePreview(@ptrCast(*const IPrintPreviewDxgiPackageTarget, self)); } };} pub usingnamespace MethodMixin(@This()); }; pub const _SPLCLIENT_INFO_2_V2 = switch(@import("../zig.zig").arch) { .X64, .Arm64 => extern struct { hSplPrinter: u64, }, .X86 => extern struct { hSplPrinter: u32, }, }; //-------------------------------------------------------------------------------- // Section: Functions (214) //-------------------------------------------------------------------------------- pub extern "COMPSTUI" fn CommonPropertySheetUIA( hWndOwner: ?HWND, pfnPropSheetUI: ?PFNPROPSHEETUI, lParam: LPARAM, pResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "COMPSTUI" fn CommonPropertySheetUIW( hWndOwner: ?HWND, pfnPropSheetUI: ?PFNPROPSHEETUI, lParam: LPARAM, pResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "COMPSTUI" fn GetCPSUIUserData( hDlg: ?HWND, ) callconv(@import("std").os.windows.WINAPI) usize; pub extern "COMPSTUI" fn SetCPSUIUserData( hDlg: ?HWND, CPSUIUserData: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrintersA( Flags: u32, Name: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pPrinterEnum: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrintersW( Flags: u32, Name: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pPrinterEnum: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetSpoolFileHandle( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn CommitSpoolData( hPrinter: ?HANDLE, hSpoolFile: ?HANDLE, cbCommit: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn CloseSpoolFileHandle( hPrinter: ?HANDLE, hSpoolFile: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn OpenPrinterA( pPrinterName: ?PSTR, phPrinter: ?*?HANDLE, pDefault: ?*PRINTER_DEFAULTSA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn OpenPrinterW( pPrinterName: ?PWSTR, phPrinter: ?*?HANDLE, pDefault: ?*PRINTER_DEFAULTSW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ResetPrinterA( hPrinter: ?HANDLE, pDefault: ?*PRINTER_DEFAULTSA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ResetPrinterW( hPrinter: ?HANDLE, pDefault: ?*PRINTER_DEFAULTSW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetJobA( hPrinter: ?HANDLE, JobId: u32, Level: u32, pJob: ?*u8, Command: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetJobW( hPrinter: ?HANDLE, JobId: u32, Level: u32, pJob: ?*u8, Command: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetJobA( hPrinter: ?HANDLE, JobId: u32, Level: u32, // TODO: what to do with BytesParamIndex 4? pJob: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetJobW( hPrinter: ?HANDLE, JobId: u32, Level: u32, // TODO: what to do with BytesParamIndex 4? pJob: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumJobsA( hPrinter: ?HANDLE, FirstJob: u32, NoJobs: u32, Level: u32, // TODO: what to do with BytesParamIndex 5? pJob: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumJobsW( hPrinter: ?HANDLE, FirstJob: u32, NoJobs: u32, Level: u32, // TODO: what to do with BytesParamIndex 5? pJob: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterA( pName: ?PSTR, Level: u32, pPrinter: ?*u8, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn AddPrinterW( pName: ?PWSTR, Level: u32, pPrinter: ?*u8, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn DeletePrinter( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetPrinterA( hPrinter: ?HANDLE, Level: u32, pPrinter: ?*u8, Command: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetPrinterW( hPrinter: ?HANDLE, Level: u32, pPrinter: ?*u8, Command: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterA( hPrinter: ?HANDLE, Level: u32, // TODO: what to do with BytesParamIndex 3? pPrinter: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterW( hPrinter: ?HANDLE, Level: u32, // TODO: what to do with BytesParamIndex 3? pPrinter: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterDriverA( pName: ?PSTR, Level: u32, pDriverInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterDriverW( pName: ?PWSTR, Level: u32, pDriverInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterDriverExA( pName: ?PSTR, Level: u32, lpbDriverInfo: ?*u8, dwFileCopyFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterDriverExW( pName: ?PWSTR, Level: u32, lpbDriverInfo: ?*u8, dwFileCopyFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrinterDriversA( pName: ?PSTR, pEnvironment: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDriverInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrinterDriversW( pName: ?PWSTR, pEnvironment: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDriverInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterDriverA( hPrinter: ?HANDLE, pEnvironment: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDriverInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterDriverW( hPrinter: ?HANDLE, pEnvironment: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDriverInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterDriverDirectoryA( pName: ?PSTR, pEnvironment: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDriverDirectory: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterDriverDirectoryW( pName: ?PWSTR, pEnvironment: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDriverDirectory: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterDriverA( pName: ?PSTR, pEnvironment: ?PSTR, pDriverName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterDriverW( pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterDriverExA( pName: ?PSTR, pEnvironment: ?PSTR, pDriverName: ?PSTR, dwDeleteFlag: u32, dwVersionFlag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterDriverExW( pName: ?PWSTR, pEnvironment: ?PWSTR, pDriverName: ?PWSTR, dwDeleteFlag: u32, dwVersionFlag: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrintProcessorA( pName: ?PSTR, pEnvironment: ?PSTR, pPathName: ?PSTR, pPrintProcessorName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrintProcessorW( pName: ?PWSTR, pEnvironment: ?PWSTR, pPathName: ?PWSTR, pPrintProcessorName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrintProcessorsA( pName: ?PSTR, pEnvironment: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pPrintProcessorInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrintProcessorsW( pName: ?PWSTR, pEnvironment: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pPrintProcessorInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrintProcessorDirectoryA( pName: ?PSTR, pEnvironment: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pPrintProcessorInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrintProcessorDirectoryW( pName: ?PWSTR, pEnvironment: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pPrintProcessorInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrintProcessorDatatypesA( pName: ?PSTR, pPrintProcessorName: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDatatypes: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPrintProcessorDatatypesW( pName: ?PWSTR, pPrintProcessorName: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pDatatypes: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrintProcessorA( pName: ?PSTR, pEnvironment: ?PSTR, pPrintProcessorName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrintProcessorW( pName: ?PWSTR, pEnvironment: ?PWSTR, pPrintProcessorName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn StartDocPrinterA( hPrinter: ?HANDLE, Level: u32, pDocInfo: ?*DOC_INFO_1A, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn StartDocPrinterW( hPrinter: ?HANDLE, Level: u32, pDocInfo: ?*DOC_INFO_1W, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn StartPagePrinter( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn WritePrinter( hPrinter: ?HANDLE, // TODO: what to do with BytesParamIndex 2? pBuf: ?*anyopaque, cbBuf: u32, pcWritten: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn FlushPrinter( hPrinter: ?HANDLE, // TODO: what to do with BytesParamIndex 2? pBuf: ?*anyopaque, cbBuf: u32, pcWritten: ?*u32, cSleep: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EndPagePrinter( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AbortPrinter( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ReadPrinter( hPrinter: ?HANDLE, // TODO: what to do with BytesParamIndex 2? pBuf: ?*anyopaque, cbBuf: u32, pNoBytesRead: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EndDocPrinter( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddJobA( hPrinter: ?HANDLE, Level: u32, // TODO: what to do with BytesParamIndex 3? pData: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddJobW( hPrinter: ?HANDLE, Level: u32, // TODO: what to do with BytesParamIndex 3? pData: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ScheduleJob( hPrinter: ?HANDLE, JobId: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn PrinterProperties( hWnd: ?HWND, hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DocumentPropertiesA( hWnd: ?HWND, hPrinter: ?HANDLE, pDeviceName: ?PSTR, pDevModeOutput: ?*DEVMODEA, pDevModeInput: ?*DEVMODEA, fMode: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "WINSPOOL" fn DocumentPropertiesW( hWnd: ?HWND, hPrinter: ?HANDLE, pDeviceName: ?PWSTR, pDevModeOutput: ?*DEVMODEW, pDevModeInput: ?*DEVMODEW, fMode: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "WINSPOOL" fn AdvancedDocumentPropertiesA( hWnd: ?HWND, hPrinter: ?HANDLE, pDeviceName: ?PSTR, pDevModeOutput: ?*DEVMODEA, pDevModeInput: ?*DEVMODEA, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "WINSPOOL" fn AdvancedDocumentPropertiesW( hWnd: ?HWND, hPrinter: ?HANDLE, pDeviceName: ?PWSTR, pDevModeOutput: ?*DEVMODEW, pDevModeInput: ?*DEVMODEW, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "WINSPOOL" fn ExtDeviceMode( hWnd: ?HWND, hInst: ?HANDLE, pDevModeOutput: ?*DEVMODEA, pDeviceName: ?PSTR, pPort: ?PSTR, pDevModeInput: ?*DEVMODEA, pProfile: ?PSTR, fMode: u32, ) callconv(@import("std").os.windows.WINAPI) i32; pub extern "WINSPOOL" fn GetPrinterDataA( hPrinter: ?HANDLE, pValueName: ?PSTR, pType: ?*u32, // TODO: what to do with BytesParamIndex 4? pData: ?*u8, nSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn GetPrinterDataW( hPrinter: ?HANDLE, pValueName: ?PWSTR, pType: ?*u32, // TODO: what to do with BytesParamIndex 4? pData: ?*u8, nSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn GetPrinterDataExA( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u8, pValueName: ?[*:0]const u8, pType: ?*u32, // TODO: what to do with BytesParamIndex 5? pData: ?*u8, nSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn GetPrinterDataExW( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u16, pValueName: ?[*:0]const u16, pType: ?*u32, // TODO: what to do with BytesParamIndex 5? pData: ?*u8, nSize: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumPrinterDataA( hPrinter: ?HANDLE, dwIndex: u32, // TODO: what to do with BytesParamIndex 3? pValueName: ?PSTR, cbValueName: u32, pcbValueName: ?*u32, pType: ?*u32, pData: ?[*:0]u8, cbData: u32, pcbData: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumPrinterDataW( hPrinter: ?HANDLE, dwIndex: u32, // TODO: what to do with BytesParamIndex 3? pValueName: ?PWSTR, cbValueName: u32, pcbValueName: ?*u32, pType: ?*u32, pData: ?[*:0]u8, cbData: u32, pcbData: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumPrinterDataExA( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 3? pEnumValues: ?*u8, cbEnumValues: u32, pcbEnumValues: ?*u32, pnEnumValues: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumPrinterDataExW( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? pEnumValues: ?*u8, cbEnumValues: u32, pcbEnumValues: ?*u32, pnEnumValues: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumPrinterKeyA( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u8, // TODO: what to do with BytesParamIndex 3? pSubkey: ?PSTR, cbSubkey: u32, pcbSubkey: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumPrinterKeyW( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? pSubkey: ?PWSTR, cbSubkey: u32, pcbSubkey: ?*u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn SetPrinterDataA( hPrinter: ?HANDLE, pValueName: ?PSTR, Type: u32, // TODO: what to do with BytesParamIndex 4? pData: ?*u8, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn SetPrinterDataW( hPrinter: ?HANDLE, pValueName: ?PWSTR, Type: u32, // TODO: what to do with BytesParamIndex 4? pData: ?*u8, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn SetPrinterDataExA( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u8, pValueName: ?[*:0]const u8, Type: u32, // TODO: what to do with BytesParamIndex 5? pData: ?*u8, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn SetPrinterDataExW( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u16, pValueName: ?[*:0]const u16, Type: u32, // TODO: what to do with BytesParamIndex 5? pData: ?*u8, cbData: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeletePrinterDataA( hPrinter: ?HANDLE, pValueName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeletePrinterDataW( hPrinter: ?HANDLE, pValueName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeletePrinterDataExA( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u8, pValueName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeletePrinterDataExW( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u16, pValueName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeletePrinterKeyA( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeletePrinterKeyW( hPrinter: ?HANDLE, pKeyName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn WaitForPrinterChange( hPrinter: ?HANDLE, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn FindFirstPrinterChangeNotification( hPrinter: ?HANDLE, fdwFilter: u32, fdwOptions: u32, pPrinterNotifyOptions: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn FindNextPrinterChangeNotification( hChange: ?HANDLE, pdwChange: ?*u32, pvReserved: ?*anyopaque, ppPrinterNotifyInfo: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn FreePrinterNotifyInfo( pPrinterNotifyInfo: ?*PRINTER_NOTIFY_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn FindClosePrinterChangeNotification( hChange: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn PrinterMessageBoxA( hPrinter: ?HANDLE, Error: u32, hWnd: ?HWND, pText: ?PSTR, pCaption: ?PSTR, dwType: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn PrinterMessageBoxW( hPrinter: ?HANDLE, Error: u32, hWnd: ?HWND, pText: ?PWSTR, pCaption: ?PWSTR, dwType: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn ClosePrinter( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddFormA( hPrinter: ?HANDLE, Level: u32, pForm: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddFormW( hPrinter: ?HANDLE, Level: u32, pForm: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeleteFormA( hPrinter: ?HANDLE, pFormName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeleteFormW( hPrinter: ?HANDLE, pFormName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetFormA( hPrinter: ?HANDLE, pFormName: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pForm: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetFormW( hPrinter: ?HANDLE, pFormName: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 4? pForm: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetFormA( hPrinter: ?HANDLE, pFormName: ?PSTR, Level: u32, pForm: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetFormW( hPrinter: ?HANDLE, pFormName: ?PWSTR, Level: u32, pForm: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumFormsA( hPrinter: ?HANDLE, Level: u32, // TODO: what to do with BytesParamIndex 3? pForm: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumFormsW( hPrinter: ?HANDLE, Level: u32, // TODO: what to do with BytesParamIndex 3? pForm: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumMonitorsA( pName: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 3? pMonitor: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumMonitorsW( pName: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 3? pMonitor: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddMonitorA( pName: ?PSTR, Level: u32, pMonitors: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddMonitorW( pName: ?PWSTR, Level: u32, pMonitors: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeleteMonitorA( pName: ?PSTR, pEnvironment: ?PSTR, pMonitorName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeleteMonitorW( pName: ?PWSTR, pEnvironment: ?PWSTR, pMonitorName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPortsA( pName: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 3? pPort: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn EnumPortsW( pName: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 3? pPort: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, pcReturned: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPortA( pName: ?PSTR, hWnd: ?HWND, pMonitorName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPortW( pName: ?PWSTR, hWnd: ?HWND, pMonitorName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ConfigurePortA( pName: ?PSTR, hWnd: ?HWND, pPortName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ConfigurePortW( pName: ?PWSTR, hWnd: ?HWND, pPortName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePortA( pName: ?PSTR, hWnd: ?HWND, pPortName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePortW( pName: ?PWSTR, hWnd: ?HWND, pPortName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn XcvDataW( hXcv: ?HANDLE, pszDataName: ?[*:0]const u16, // TODO: what to do with BytesParamIndex 3? pInputData: ?*u8, cbInputData: u32, // TODO: what to do with BytesParamIndex 5? pOutputData: ?*u8, cbOutputData: u32, pcbOutputNeeded: ?*u32, pdwStatus: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetDefaultPrinterA( pszBuffer: ?[*:0]u8, pcchBuffer: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetDefaultPrinterW( pszBuffer: ?[*:0]u16, pcchBuffer: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetDefaultPrinterA( pszPrinter: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetDefaultPrinterW( pszPrinter: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetPortA( pName: ?PSTR, pPortName: ?PSTR, dwLevel: u32, pPortInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn SetPortW( pName: ?PWSTR, pPortName: ?PWSTR, dwLevel: u32, pPortInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterConnectionA( pName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterConnectionW( pName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterConnectionA( pName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterConnectionW( pName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn ConnectToPrinterDlg( hwnd: ?HWND, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn AddPrintProvidorA( pName: ?PSTR, Level: u32, pProvidorInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrintProvidorW( pName: ?PWSTR, Level: u32, pProvidorInfo: ?*u8, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrintProvidorA( pName: ?PSTR, pEnvironment: ?PSTR, pPrintProvidorName: ?PSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrintProvidorW( pName: ?PWSTR, pEnvironment: ?PWSTR, pPrintProvidorName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn IsValidDevmodeA( pDevmode: ?*DEVMODEA, DevmodeSize: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn IsValidDevmodeW( pDevmode: ?*DEVMODEW, DevmodeSize: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn OpenPrinter2A( pPrinterName: ?[*:0]const u8, phPrinter: ?*?HANDLE, pDefault: ?*PRINTER_DEFAULTSA, pOptions: ?*PRINTER_OPTIONSA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn OpenPrinter2W( pPrinterName: ?[*:0]const u16, phPrinter: ?*?HANDLE, pDefault: ?*PRINTER_DEFAULTSW, pOptions: ?*PRINTER_OPTIONSW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterConnection2A( hWnd: ?HWND, pszName: ?[*:0]const u8, dwLevel: u32, pConnectionInfo: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn AddPrinterConnection2W( hWnd: ?HWND, pszName: ?[*:0]const u16, dwLevel: u32, pConnectionInfo: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn InstallPrinterDriverFromPackageA( pszServer: ?[*:0]const u8, pszInfPath: ?[*:0]const u8, pszDriverName: ?[*:0]const u8, pszEnvironment: ?[*:0]const u8, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn InstallPrinterDriverFromPackageW( pszServer: ?[*:0]const u16, pszInfPath: ?[*:0]const u16, pszDriverName: ?[*:0]const u16, pszEnvironment: ?[*:0]const u16, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn UploadPrinterDriverPackageA( pszServer: ?[*:0]const u8, pszInfPath: ?[*:0]const u8, pszEnvironment: ?[*:0]const u8, dwFlags: u32, hwnd: ?HWND, pszDestInfPath: [*:0]u8, pcchDestInfPath: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn UploadPrinterDriverPackageW( pszServer: ?[*:0]const u16, pszInfPath: ?[*:0]const u16, pszEnvironment: ?[*:0]const u16, dwFlags: u32, hwnd: ?HWND, pszDestInfPath: [*:0]u16, pcchDestInfPath: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn GetCorePrinterDriversA( pszServer: ?[*:0]const u8, pszEnvironment: ?[*:0]const u8, pszzCoreDriverDependencies: ?[*:0]const u8, cCorePrinterDrivers: u32, pCorePrinterDrivers: [*]CORE_PRINTER_DRIVERA, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn GetCorePrinterDriversW( pszServer: ?[*:0]const u16, pszEnvironment: ?[*:0]const u16, pszzCoreDriverDependencies: ?[*:0]const u16, cCorePrinterDrivers: u32, pCorePrinterDrivers: [*]CORE_PRINTER_DRIVERW, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // This function from dll 'WINSPOOL' is being skipped because it has some sort of issue pub fn CorePrinterDriverInstalledA() void { @panic("this function is not working"); } // This function from dll 'WINSPOOL' is being skipped because it has some sort of issue pub fn CorePrinterDriverInstalledW() void { @panic("this function is not working"); } pub extern "WINSPOOL" fn GetPrinterDriverPackagePathA( pszServer: ?[*:0]const u8, pszEnvironment: ?[*:0]const u8, pszLanguage: ?[*:0]const u8, pszPackageID: ?[*:0]const u8, pszDriverPackageCab: ?[*:0]u8, cchDriverPackageCab: u32, pcchRequiredSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn GetPrinterDriverPackagePathW( pszServer: ?[*:0]const u16, pszEnvironment: ?[*:0]const u16, pszLanguage: ?[*:0]const u16, pszPackageID: ?[*:0]const u16, pszDriverPackageCab: ?[*:0]u16, cchDriverPackageCab: u32, pcchRequiredSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn DeletePrinterDriverPackageA( pszServer: ?[*:0]const u8, pszInfPath: ?[*:0]const u8, pszEnvironment: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn DeletePrinterDriverPackageW( pszServer: ?[*:0]const u16, pszInfPath: ?[*:0]const u16, pszEnvironment: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn ReportJobProcessingProgress( printerHandle: ?HANDLE, jobId: u32, jobOperation: EPrintXPSJobOperation, jobProgress: EPrintXPSJobProgress, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn GetPrinterDriver2A( hWnd: ?HWND, hPrinter: ?HANDLE, pEnvironment: ?PSTR, Level: u32, // TODO: what to do with BytesParamIndex 5? pDriverInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrinterDriver2W( hWnd: ?HWND, hPrinter: ?HANDLE, pEnvironment: ?PWSTR, Level: u32, // TODO: what to do with BytesParamIndex 5? pDriverInfo: ?*u8, cbBuf: u32, pcbNeeded: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetPrintExecutionData( pData: ?*PRINT_EXECUTION_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn GetJobNamedPropertyValue( hPrinter: ?HANDLE, JobId: u32, pszName: ?[*:0]const u16, pValue: ?*PrintPropertyValue, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn FreePrintPropertyValue( pValue: ?*PrintPropertyValue, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WINSPOOL" fn FreePrintNamedPropertyArray( cProperties: u32, ppProperties: ?[*]?*PrintNamedProperty, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "WINSPOOL" fn SetJobNamedProperty( hPrinter: ?HANDLE, JobId: u32, pProperty: ?*const PrintNamedProperty, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn DeleteJobNamedProperty( hPrinter: ?HANDLE, JobId: u32, pszName: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn EnumJobNamedProperties( hPrinter: ?HANDLE, JobId: u32, pcProperties: ?*u32, ppProperties: ?*?*PrintNamedProperty, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "WINSPOOL" fn GetPrintOutputInfo( hWnd: ?HWND, pszPrinter: ?[*:0]const u16, phFile: ?*?HANDLE, ppszOutputFile: ?*?PWSTR, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "WINSPOOL" fn DevQueryPrintEx( pDQPInfo: ?*DEVQUERYPRINT_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WINSPOOL" fn RegisterForPrintAsyncNotifications( pszName: ?[*:0]const u16, pNotificationType: ?*Guid, eUserFilter: PrintAsyncNotifyUserFilter, eConversationStyle: PrintAsyncNotifyConversationStyle, pCallback: ?*IPrintAsyncNotifyCallback, phNotify: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WINSPOOL" fn UnRegisterForPrintAsyncNotifications( param0: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "WINSPOOL" fn CreatePrintAsyncNotifyChannel( pszName: ?[*:0]const u16, pNotificationType: ?*Guid, eUserFilter: PrintAsyncNotifyUserFilter, eConversationStyle: PrintAsyncNotifyConversationStyle, pCallback: ?*IPrintAsyncNotifyCallback, ppIAsynchNotification: ?*?*IPrintAsyncNotifyChannel, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "GDI32" fn GdiGetSpoolFileHandle( pwszPrinterName: ?PWSTR, pDevmode: ?*DEVMODEW, pwszDocName: ?PWSTR, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "GDI32" fn GdiDeleteSpoolFileHandle( SpoolFileHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiGetPageCount( SpoolFileHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "GDI32" fn GdiGetDC( SpoolFileHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) ?HDC; pub extern "GDI32" fn GdiGetPageHandle( SpoolFileHandle: ?HANDLE, Page: u32, pdwPageType: ?*u32, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "GDI32" fn GdiStartDocEMF( SpoolFileHandle: ?HANDLE, pDocInfo: ?*DOCINFOW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiStartPageEMF( SpoolFileHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiPlayPageEMF( SpoolFileHandle: ?HANDLE, hemf: ?HANDLE, prectDocument: ?*RECT, prectBorder: ?*RECT, prectClip: ?*RECT, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiEndPageEMF( SpoolFileHandle: ?HANDLE, dwOptimization: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiEndDocEMF( SpoolFileHandle: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiGetDevmodeForPage( SpoolFileHandle: ?HANDLE, dwPageNumber: u32, pCurrDM: ?*?*DEVMODEW, pLastDM: ?*?*DEVMODEW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "GDI32" fn GdiResetDCEMF( SpoolFileHandle: ?HANDLE, pCurrDM: ?*DEVMODEW, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn GetJobAttributes( pPrinterName: ?PWSTR, pDevmode: ?*DEVMODEW, pAttributeInfo: ?*ATTRIBUTE_INFO_3, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn GetJobAttributesEx( pPrinterName: ?PWSTR, pDevmode: ?*DEVMODEW, dwLevel: u32, // TODO: what to do with BytesParamIndex 4? pAttributeInfo: ?*u8, nSize: u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn CreatePrinterIC( hPrinter: ?HANDLE, pDevMode: ?*DEVMODEW, ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "WINSPOOL" fn PlayGdiScriptOnPrinterIC( hPrinterIC: ?HANDLE, // TODO: what to do with BytesParamIndex 2? pIn: ?*u8, cIn: u32, // TODO: what to do with BytesParamIndex 4? pOut: ?*u8, cOut: u32, ul: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DeletePrinterIC( hPrinterIC: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "WINSPOOL" fn DevQueryPrint( hPrinter: ?HANDLE, pDevMode: ?*DEVMODEA, pResID: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn RevertToPrinterSelf( ) callconv(@import("std").os.windows.WINAPI) ?HANDLE; pub extern "SPOOLSS" fn ImpersonatePrinterClient( hToken: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn ReplyPrinterChangeNotification( hPrinter: ?HANDLE, fdwChangeFlags: u32, pdwResult: ?*u32, pPrinterNotifyInfo: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn ReplyPrinterChangeNotificationEx( hNotify: ?HANDLE, dwColor: u32, fdwFlags: u32, pdwResult: ?*u32, pPrinterNotifyInfo: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn PartialReplyPrinterChangeNotification( hPrinter: ?HANDLE, pDataSrc: ?*PRINTER_NOTIFY_INFO_DATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn RouterAllocPrinterNotifyInfo( cPrinterNotifyInfoData: u32, ) callconv(@import("std").os.windows.WINAPI) ?*PRINTER_NOTIFY_INFO; pub extern "SPOOLSS" fn RouterFreePrinterNotifyInfo( pInfo: ?*PRINTER_NOTIFY_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn RouterAllocBidiResponseContainer( Count: u32, ) callconv(@import("std").os.windows.WINAPI) ?*BIDI_RESPONSE_CONTAINER; pub extern "SPOOLSS" fn RouterAllocBidiMem( NumBytes: usize, ) callconv(@import("std").os.windows.WINAPI) ?*anyopaque; pub extern "WINSPOOL" fn RouterFreeBidiResponseContainer( pData: ?*BIDI_RESPONSE_CONTAINER, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "SPOOLSS" fn RouterFreeBidiMem( pMemPointer: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "SPOOLSS" fn AppendPrinterNotifyInfoData( pInfoDest: ?*PRINTER_NOTIFY_INFO, pDataSrc: ?*PRINTER_NOTIFY_INFO_DATA, fdwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn CallRouterFindFirstPrinterChangeNotification( hPrinterRPC: ?HANDLE, fdwFilterFlags: u32, fdwOptions: u32, hNotify: ?HANDLE, pPrinterNotifyOptions: ?*PRINTER_NOTIFY_OPTIONS, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "SPOOLSS" fn ProvidorFindFirstPrinterChangeNotification( hPrinter: ?HANDLE, fdwFlags: u32, fdwOptions: u32, hNotify: ?HANDLE, pPrinterNotifyOptions: ?*anyopaque, pvReserved1: ?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn ProvidorFindClosePrinterChangeNotification( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn SpoolerFindFirstPrinterChangeNotification( hPrinter: ?HANDLE, fdwFilterFlags: u32, fdwOptions: u32, pPrinterNotifyOptions: ?*anyopaque, pvReserved: ?*anyopaque, pNotificationConfig: ?*anyopaque, phNotify: ?*?HANDLE, phEvent: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn SpoolerFindNextPrinterChangeNotification( hPrinter: ?HANDLE, pfdwChange: ?*u32, pPrinterNotifyOptions: ?*anyopaque, ppPrinterNotifyInfo: ?*?*anyopaque, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn SpoolerRefreshPrinterChangeNotification( hPrinter: ?HANDLE, dwColor: u32, pOptions: ?*PRINTER_NOTIFY_OPTIONS, ppInfo: ?*?*PRINTER_NOTIFY_INFO, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn SpoolerFreePrinterNotifyInfo( pInfo: ?*PRINTER_NOTIFY_INFO, ) callconv(@import("std").os.windows.WINAPI) void; pub extern "SPOOLSS" fn SpoolerFindClosePrinterChangeNotification( hPrinter: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn SpoolerCopyFileEvent( pszPrinterName: ?PWSTR, pszKey: ?PWSTR, dwCopyFileEvent: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "mscms" fn GenerateCopyFilePaths( pszPrinterName: ?[*:0]const u16, pszDirectory: ?[*:0]const u16, pSplClientInfo: ?*u8, dwLevel: u32, pszSourceDir: [*:0]u16, pcchSourceDirSize: ?*u32, pszTargetDir: [*:0]u16, pcchTargetDirSize: ?*u32, dwFlags: u32, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "SPOOLSS" fn SplPromptUIInUsersSession( hPrinter: ?HANDLE, JobId: u32, pUIParams: ?*SHOWUIPARAMS, pResponse: ?*u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; pub extern "SPOOLSS" fn SplIsSessionZero( hPrinter: ?HANDLE, JobId: u32, pIsSessionZero: ?*BOOL, ) callconv(@import("std").os.windows.WINAPI) u32; pub extern "SPOOLSS" fn AddPrintDeviceObject( hPrinter: ?HANDLE, phDeviceObject: ?*?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "SPOOLSS" fn UpdatePrintDeviceObject( hPrinter: ?HANDLE, hDeviceObject: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; pub extern "SPOOLSS" fn RemovePrintDeviceObject( hDeviceObject: ?HANDLE, ) callconv(@import("std").os.windows.WINAPI) HRESULT; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (103) //-------------------------------------------------------------------------------- const thismodule = @This(); pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const PRINTER_INFO_1 = thismodule.PRINTER_INFO_1A; pub const PRINTER_INFO_2 = thismodule.PRINTER_INFO_2A; pub const PRINTER_INFO_4 = thismodule.PRINTER_INFO_4A; pub const PRINTER_INFO_5 = thismodule.PRINTER_INFO_5A; pub const PRINTER_INFO_7 = thismodule.PRINTER_INFO_7A; pub const PRINTER_INFO_8 = thismodule.PRINTER_INFO_8A; pub const PRINTER_INFO_9 = thismodule.PRINTER_INFO_9A; pub const JOB_INFO_1 = thismodule.JOB_INFO_1A; pub const JOB_INFO_2 = thismodule.JOB_INFO_2A; pub const JOB_INFO_4 = thismodule.JOB_INFO_4A; pub const ADDJOB_INFO_1 = thismodule.ADDJOB_INFO_1A; pub const DRIVER_INFO_1 = thismodule.DRIVER_INFO_1A; pub const DRIVER_INFO_2 = thismodule.DRIVER_INFO_2A; pub const DRIVER_INFO_3 = thismodule.DRIVER_INFO_3A; pub const DRIVER_INFO_4 = thismodule.DRIVER_INFO_4A; pub const DRIVER_INFO_5 = thismodule.DRIVER_INFO_5A; pub const DRIVER_INFO_6 = thismodule.DRIVER_INFO_6A; pub const DRIVER_INFO_8 = thismodule.DRIVER_INFO_8A; pub const DOC_INFO_1 = thismodule.DOC_INFO_1A; pub const FORM_INFO_1 = thismodule.FORM_INFO_1A; pub const FORM_INFO_2 = thismodule.FORM_INFO_2A; pub const DOC_INFO_2 = thismodule.DOC_INFO_2A; pub const DOC_INFO_3 = thismodule.DOC_INFO_3A; pub const PRINTPROCESSOR_INFO_1 = thismodule.PRINTPROCESSOR_INFO_1A; pub const PORT_INFO_1 = thismodule.PORT_INFO_1A; pub const PORT_INFO_2 = thismodule.PORT_INFO_2A; pub const PORT_INFO_3 = thismodule.PORT_INFO_3A; pub const MONITOR_INFO_1 = thismodule.MONITOR_INFO_1A; pub const MONITOR_INFO_2 = thismodule.MONITOR_INFO_2A; pub const DATATYPES_INFO_1 = thismodule.DATATYPES_INFO_1A; pub const PRINTER_DEFAULTS = thismodule.PRINTER_DEFAULTSA; pub const PRINTER_ENUM_VALUES = thismodule.PRINTER_ENUM_VALUESA; pub const PROVIDOR_INFO_1 = thismodule.PROVIDOR_INFO_1A; pub const PROVIDOR_INFO_2 = thismodule.PROVIDOR_INFO_2A; pub const PRINTER_OPTIONS = thismodule.PRINTER_OPTIONSA; pub const PRINTER_CONNECTION_INFO_1 = thismodule.PRINTER_CONNECTION_INFO_1A; pub const CORE_PRINTER_DRIVER = thismodule.CORE_PRINTER_DRIVERA; pub const CommonPropertySheetUI = thismodule.CommonPropertySheetUIA; pub const EnumPrinters = thismodule.EnumPrintersA; pub const OpenPrinter = thismodule.OpenPrinterA; pub const ResetPrinter = thismodule.ResetPrinterA; pub const SetJob = thismodule.SetJobA; pub const GetJob = thismodule.GetJobA; pub const EnumJobs = thismodule.EnumJobsA; pub const AddPrinter = thismodule.AddPrinterA; pub const SetPrinter = thismodule.SetPrinterA; pub const GetPrinter = thismodule.GetPrinterA; pub const AddPrinterDriver = thismodule.AddPrinterDriverA; pub const AddPrinterDriverEx = thismodule.AddPrinterDriverExA; pub const EnumPrinterDrivers = thismodule.EnumPrinterDriversA; pub const GetPrinterDriver = thismodule.GetPrinterDriverA; pub const GetPrinterDriverDirectory = thismodule.GetPrinterDriverDirectoryA; pub const DeletePrinterDriver = thismodule.DeletePrinterDriverA; pub const DeletePrinterDriverEx = thismodule.DeletePrinterDriverExA; pub const AddPrintProcessor = thismodule.AddPrintProcessorA; pub const EnumPrintProcessors = thismodule.EnumPrintProcessorsA; pub const GetPrintProcessorDirectory = thismodule.GetPrintProcessorDirectoryA; pub const EnumPrintProcessorDatatypes = thismodule.EnumPrintProcessorDatatypesA; pub const DeletePrintProcessor = thismodule.DeletePrintProcessorA; pub const StartDocPrinter = thismodule.StartDocPrinterA; pub const AddJob = thismodule.AddJobA; pub const DocumentProperties = thismodule.DocumentPropertiesA; pub const AdvancedDocumentProperties = thismodule.AdvancedDocumentPropertiesA; pub const GetPrinterData = thismodule.GetPrinterDataA; pub const GetPrinterDataEx = thismodule.GetPrinterDataExA; pub const EnumPrinterData = thismodule.EnumPrinterDataA; pub const EnumPrinterDataEx = thismodule.EnumPrinterDataExA; pub const EnumPrinterKey = thismodule.EnumPrinterKeyA; pub const SetPrinterData = thismodule.SetPrinterDataA; pub const SetPrinterDataEx = thismodule.SetPrinterDataExA; pub const DeletePrinterData = thismodule.DeletePrinterDataA; pub const DeletePrinterDataEx = thismodule.DeletePrinterDataExA; pub const DeletePrinterKey = thismodule.DeletePrinterKeyA; pub const PrinterMessageBox = thismodule.PrinterMessageBoxA; pub const AddForm = thismodule.AddFormA; pub const DeleteForm = thismodule.DeleteFormA; pub const GetForm = thismodule.GetFormA; pub const SetForm = thismodule.SetFormA; pub const EnumForms = thismodule.EnumFormsA; pub const EnumMonitors = thismodule.EnumMonitorsA; pub const AddMonitor = thismodule.AddMonitorA; pub const DeleteMonitor = thismodule.DeleteMonitorA; pub const EnumPorts = thismodule.EnumPortsA; pub const AddPort = thismodule.AddPortA; pub const ConfigurePort = thismodule.ConfigurePortA; pub const DeletePort = thismodule.DeletePortA; pub const GetDefaultPrinter = thismodule.GetDefaultPrinterA; pub const SetDefaultPrinter = thismodule.SetDefaultPrinterA; pub const SetPort = thismodule.SetPortA; pub const AddPrinterConnection = thismodule.AddPrinterConnectionA; pub const DeletePrinterConnection = thismodule.DeletePrinterConnectionA; pub const AddPrintProvidor = thismodule.AddPrintProvidorA; pub const DeletePrintProvidor = thismodule.DeletePrintProvidorA; pub const IsValidDevmode = thismodule.IsValidDevmodeA; pub const OpenPrinter2 = thismodule.OpenPrinter2A; pub const AddPrinterConnection2 = thismodule.AddPrinterConnection2A; pub const InstallPrinterDriverFromPackage = thismodule.InstallPrinterDriverFromPackageA; pub const UploadPrinterDriverPackage = thismodule.UploadPrinterDriverPackageA; pub const GetCorePrinterDrivers = thismodule.GetCorePrinterDriversA; pub const CorePrinterDriverInstalled = thismodule.CorePrinterDriverInstalledA; pub const GetPrinterDriverPackagePath = thismodule.GetPrinterDriverPackagePathA; pub const DeletePrinterDriverPackage = thismodule.DeletePrinterDriverPackageA; pub const GetPrinterDriver2 = thismodule.GetPrinterDriver2A; }, .wide => struct { pub const PRINTER_INFO_1 = thismodule.PRINTER_INFO_1W; pub const PRINTER_INFO_2 = thismodule.PRINTER_INFO_2W; pub const PRINTER_INFO_4 = thismodule.PRINTER_INFO_4W; pub const PRINTER_INFO_5 = thismodule.PRINTER_INFO_5W; pub const PRINTER_INFO_7 = thismodule.PRINTER_INFO_7W; pub const PRINTER_INFO_8 = thismodule.PRINTER_INFO_8W; pub const PRINTER_INFO_9 = thismodule.PRINTER_INFO_9W; pub const JOB_INFO_1 = thismodule.JOB_INFO_1W; pub const JOB_INFO_2 = thismodule.JOB_INFO_2W; pub const JOB_INFO_4 = thismodule.JOB_INFO_4W; pub const ADDJOB_INFO_1 = thismodule.ADDJOB_INFO_1W; pub const DRIVER_INFO_1 = thismodule.DRIVER_INFO_1W; pub const DRIVER_INFO_2 = thismodule.DRIVER_INFO_2W; pub const DRIVER_INFO_3 = thismodule.DRIVER_INFO_3W; pub const DRIVER_INFO_4 = thismodule.DRIVER_INFO_4W; pub const DRIVER_INFO_5 = thismodule.DRIVER_INFO_5W; pub const DRIVER_INFO_6 = thismodule.DRIVER_INFO_6W; pub const DRIVER_INFO_8 = thismodule.DRIVER_INFO_8W; pub const DOC_INFO_1 = thismodule.DOC_INFO_1W; pub const FORM_INFO_1 = thismodule.FORM_INFO_1W; pub const FORM_INFO_2 = thismodule.FORM_INFO_2W; pub const DOC_INFO_2 = thismodule.DOC_INFO_2W; pub const DOC_INFO_3 = thismodule.DOC_INFO_3W; pub const PRINTPROCESSOR_INFO_1 = thismodule.PRINTPROCESSOR_INFO_1W; pub const PORT_INFO_1 = thismodule.PORT_INFO_1W; pub const PORT_INFO_2 = thismodule.PORT_INFO_2W; pub const PORT_INFO_3 = thismodule.PORT_INFO_3W; pub const MONITOR_INFO_1 = thismodule.MONITOR_INFO_1W; pub const MONITOR_INFO_2 = thismodule.MONITOR_INFO_2W; pub const DATATYPES_INFO_1 = thismodule.DATATYPES_INFO_1W; pub const PRINTER_DEFAULTS = thismodule.PRINTER_DEFAULTSW; pub const PRINTER_ENUM_VALUES = thismodule.PRINTER_ENUM_VALUESW; pub const PROVIDOR_INFO_1 = thismodule.PROVIDOR_INFO_1W; pub const PROVIDOR_INFO_2 = thismodule.PROVIDOR_INFO_2W; pub const PRINTER_OPTIONS = thismodule.PRINTER_OPTIONSW; pub const PRINTER_CONNECTION_INFO_1 = thismodule.PRINTER_CONNECTION_INFO_1W; pub const CORE_PRINTER_DRIVER = thismodule.CORE_PRINTER_DRIVERW; pub const CommonPropertySheetUI = thismodule.CommonPropertySheetUIW; pub const EnumPrinters = thismodule.EnumPrintersW; pub const OpenPrinter = thismodule.OpenPrinterW; pub const ResetPrinter = thismodule.ResetPrinterW; pub const SetJob = thismodule.SetJobW; pub const GetJob = thismodule.GetJobW; pub const EnumJobs = thismodule.EnumJobsW; pub const AddPrinter = thismodule.AddPrinterW; pub const SetPrinter = thismodule.SetPrinterW; pub const GetPrinter = thismodule.GetPrinterW; pub const AddPrinterDriver = thismodule.AddPrinterDriverW; pub const AddPrinterDriverEx = thismodule.AddPrinterDriverExW; pub const EnumPrinterDrivers = thismodule.EnumPrinterDriversW; pub const GetPrinterDriver = thismodule.GetPrinterDriverW; pub const GetPrinterDriverDirectory = thismodule.GetPrinterDriverDirectoryW; pub const DeletePrinterDriver = thismodule.DeletePrinterDriverW; pub const DeletePrinterDriverEx = thismodule.DeletePrinterDriverExW; pub const AddPrintProcessor = thismodule.AddPrintProcessorW; pub const EnumPrintProcessors = thismodule.EnumPrintProcessorsW; pub const GetPrintProcessorDirectory = thismodule.GetPrintProcessorDirectoryW; pub const EnumPrintProcessorDatatypes = thismodule.EnumPrintProcessorDatatypesW; pub const DeletePrintProcessor = thismodule.DeletePrintProcessorW; pub const StartDocPrinter = thismodule.StartDocPrinterW; pub const AddJob = thismodule.AddJobW; pub const DocumentProperties = thismodule.DocumentPropertiesW; pub const AdvancedDocumentProperties = thismodule.AdvancedDocumentPropertiesW; pub const GetPrinterData = thismodule.GetPrinterDataW; pub const GetPrinterDataEx = thismodule.GetPrinterDataExW; pub const EnumPrinterData = thismodule.EnumPrinterDataW; pub const EnumPrinterDataEx = thismodule.EnumPrinterDataExW; pub const EnumPrinterKey = thismodule.EnumPrinterKeyW; pub const SetPrinterData = thismodule.SetPrinterDataW; pub const SetPrinterDataEx = thismodule.SetPrinterDataExW; pub const DeletePrinterData = thismodule.DeletePrinterDataW; pub const DeletePrinterDataEx = thismodule.DeletePrinterDataExW; pub const DeletePrinterKey = thismodule.DeletePrinterKeyW; pub const PrinterMessageBox = thismodule.PrinterMessageBoxW; pub const AddForm = thismodule.AddFormW; pub const DeleteForm = thismodule.DeleteFormW; pub const GetForm = thismodule.GetFormW; pub const SetForm = thismodule.SetFormW; pub const EnumForms = thismodule.EnumFormsW; pub const EnumMonitors = thismodule.EnumMonitorsW; pub const AddMonitor = thismodule.AddMonitorW; pub const DeleteMonitor = thismodule.DeleteMonitorW; pub const EnumPorts = thismodule.EnumPortsW; pub const AddPort = thismodule.AddPortW; pub const ConfigurePort = thismodule.ConfigurePortW; pub const DeletePort = thismodule.DeletePortW; pub const GetDefaultPrinter = thismodule.GetDefaultPrinterW; pub const SetDefaultPrinter = thismodule.SetDefaultPrinterW; pub const SetPort = thismodule.SetPortW; pub const AddPrinterConnection = thismodule.AddPrinterConnectionW; pub const DeletePrinterConnection = thismodule.DeletePrinterConnectionW; pub const AddPrintProvidor = thismodule.AddPrintProvidorW; pub const DeletePrintProvidor = thismodule.DeletePrintProvidorW; pub const IsValidDevmode = thismodule.IsValidDevmodeW; pub const OpenPrinter2 = thismodule.OpenPrinter2W; pub const AddPrinterConnection2 = thismodule.AddPrinterConnection2W; pub const InstallPrinterDriverFromPackage = thismodule.InstallPrinterDriverFromPackageW; pub const UploadPrinterDriverPackage = thismodule.UploadPrinterDriverPackageW; pub const GetCorePrinterDrivers = thismodule.GetCorePrinterDriversW; pub const CorePrinterDriverInstalled = thismodule.CorePrinterDriverInstalledW; pub const GetPrinterDriverPackagePath = thismodule.GetPrinterDriverPackagePathW; pub const DeletePrinterDriverPackage = thismodule.DeletePrinterDriverPackageW; pub const GetPrinterDriver2 = thismodule.GetPrinterDriver2W; }, .unspecified => if (@import("builtin").is_test) struct { pub const PRINTER_INFO_1 = *opaque{}; pub const PRINTER_INFO_2 = *opaque{}; pub const PRINTER_INFO_4 = *opaque{}; pub const PRINTER_INFO_5 = *opaque{}; pub const PRINTER_INFO_7 = *opaque{}; pub const PRINTER_INFO_8 = *opaque{}; pub const PRINTER_INFO_9 = *opaque{}; pub const JOB_INFO_1 = *opaque{}; pub const JOB_INFO_2 = *opaque{}; pub const JOB_INFO_4 = *opaque{}; pub const ADDJOB_INFO_1 = *opaque{}; pub const DRIVER_INFO_1 = *opaque{}; pub const DRIVER_INFO_2 = *opaque{}; pub const DRIVER_INFO_3 = *opaque{}; pub const DRIVER_INFO_4 = *opaque{}; pub const DRIVER_INFO_5 = *opaque{}; pub const DRIVER_INFO_6 = *opaque{}; pub const DRIVER_INFO_8 = *opaque{}; pub const DOC_INFO_1 = *opaque{}; pub const FORM_INFO_1 = *opaque{}; pub const FORM_INFO_2 = *opaque{}; pub const DOC_INFO_2 = *opaque{}; pub const DOC_INFO_3 = *opaque{}; pub const PRINTPROCESSOR_INFO_1 = *opaque{}; pub const PORT_INFO_1 = *opaque{}; pub const PORT_INFO_2 = *opaque{}; pub const PORT_INFO_3 = *opaque{}; pub const MONITOR_INFO_1 = *opaque{}; pub const MONITOR_INFO_2 = *opaque{}; pub const DATATYPES_INFO_1 = *opaque{}; pub const PRINTER_DEFAULTS = *opaque{}; pub const PRINTER_ENUM_VALUES = *opaque{}; pub const PROVIDOR_INFO_1 = *opaque{}; pub const PROVIDOR_INFO_2 = *opaque{}; pub const PRINTER_OPTIONS = *opaque{}; pub const PRINTER_CONNECTION_INFO_1 = *opaque{}; pub const CORE_PRINTER_DRIVER = *opaque{}; pub const CommonPropertySheetUI = *opaque{}; pub const EnumPrinters = *opaque{}; pub const OpenPrinter = *opaque{}; pub const ResetPrinter = *opaque{}; pub const SetJob = *opaque{}; pub const GetJob = *opaque{}; pub const EnumJobs = *opaque{}; pub const AddPrinter = *opaque{}; pub const SetPrinter = *opaque{}; pub const GetPrinter = *opaque{}; pub const AddPrinterDriver = *opaque{}; pub const AddPrinterDriverEx = *opaque{}; pub const EnumPrinterDrivers = *opaque{}; pub const GetPrinterDriver = *opaque{}; pub const GetPrinterDriverDirectory = *opaque{}; pub const DeletePrinterDriver = *opaque{}; pub const DeletePrinterDriverEx = *opaque{}; pub const AddPrintProcessor = *opaque{}; pub const EnumPrintProcessors = *opaque{}; pub const GetPrintProcessorDirectory = *opaque{}; pub const EnumPrintProcessorDatatypes = *opaque{}; pub const DeletePrintProcessor = *opaque{}; pub const StartDocPrinter = *opaque{}; pub const AddJob = *opaque{}; pub const DocumentProperties = *opaque{}; pub const AdvancedDocumentProperties = *opaque{}; pub const GetPrinterData = *opaque{}; pub const GetPrinterDataEx = *opaque{}; pub const EnumPrinterData = *opaque{}; pub const EnumPrinterDataEx = *opaque{}; pub const EnumPrinterKey = *opaque{}; pub const SetPrinterData = *opaque{}; pub const SetPrinterDataEx = *opaque{}; pub const DeletePrinterData = *opaque{}; pub const DeletePrinterDataEx = *opaque{}; pub const DeletePrinterKey = *opaque{}; pub const PrinterMessageBox = *opaque{}; pub const AddForm = *opaque{}; pub const DeleteForm = *opaque{}; pub const GetForm = *opaque{}; pub const SetForm = *opaque{}; pub const EnumForms = *opaque{}; pub const EnumMonitors = *opaque{}; pub const AddMonitor = *opaque{}; pub const DeleteMonitor = *opaque{}; pub const EnumPorts = *opaque{}; pub const AddPort = *opaque{}; pub const ConfigurePort = *opaque{}; pub const DeletePort = *opaque{}; pub const GetDefaultPrinter = *opaque{}; pub const SetDefaultPrinter = *opaque{}; pub const SetPort = *opaque{}; pub const AddPrinterConnection = *opaque{}; pub const DeletePrinterConnection = *opaque{}; pub const AddPrintProvidor = *opaque{}; pub const DeletePrintProvidor = *opaque{}; pub const IsValidDevmode = *opaque{}; pub const OpenPrinter2 = *opaque{}; pub const AddPrinterConnection2 = *opaque{}; pub const InstallPrinterDriverFromPackage = *opaque{}; pub const UploadPrinterDriverPackage = *opaque{}; pub const GetCorePrinterDrivers = *opaque{}; pub const CorePrinterDriverInstalled = *opaque{}; pub const GetPrinterDriverPackagePath = *opaque{}; pub const DeletePrinterDriverPackage = *opaque{}; pub const GetPrinterDriver2 = *opaque{}; } else struct { pub const PRINTER_INFO_1 = @compileError("'PRINTER_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_INFO_2 = @compileError("'PRINTER_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_INFO_4 = @compileError("'PRINTER_INFO_4' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_INFO_5 = @compileError("'PRINTER_INFO_5' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_INFO_7 = @compileError("'PRINTER_INFO_7' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_INFO_8 = @compileError("'PRINTER_INFO_8' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_INFO_9 = @compileError("'PRINTER_INFO_9' requires that UNICODE be set to true or false in the root module"); pub const JOB_INFO_1 = @compileError("'JOB_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const JOB_INFO_2 = @compileError("'JOB_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const JOB_INFO_4 = @compileError("'JOB_INFO_4' requires that UNICODE be set to true or false in the root module"); pub const ADDJOB_INFO_1 = @compileError("'ADDJOB_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_1 = @compileError("'DRIVER_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_2 = @compileError("'DRIVER_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_3 = @compileError("'DRIVER_INFO_3' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_4 = @compileError("'DRIVER_INFO_4' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_5 = @compileError("'DRIVER_INFO_5' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_6 = @compileError("'DRIVER_INFO_6' requires that UNICODE be set to true or false in the root module"); pub const DRIVER_INFO_8 = @compileError("'DRIVER_INFO_8' requires that UNICODE be set to true or false in the root module"); pub const DOC_INFO_1 = @compileError("'DOC_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const FORM_INFO_1 = @compileError("'FORM_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const FORM_INFO_2 = @compileError("'FORM_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const DOC_INFO_2 = @compileError("'DOC_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const DOC_INFO_3 = @compileError("'DOC_INFO_3' requires that UNICODE be set to true or false in the root module"); pub const PRINTPROCESSOR_INFO_1 = @compileError("'PRINTPROCESSOR_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const PORT_INFO_1 = @compileError("'PORT_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const PORT_INFO_2 = @compileError("'PORT_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const PORT_INFO_3 = @compileError("'PORT_INFO_3' requires that UNICODE be set to true or false in the root module"); pub const MONITOR_INFO_1 = @compileError("'MONITOR_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const MONITOR_INFO_2 = @compileError("'MONITOR_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const DATATYPES_INFO_1 = @compileError("'DATATYPES_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_DEFAULTS = @compileError("'PRINTER_DEFAULTS' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_ENUM_VALUES = @compileError("'PRINTER_ENUM_VALUES' requires that UNICODE be set to true or false in the root module"); pub const PROVIDOR_INFO_1 = @compileError("'PROVIDOR_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const PROVIDOR_INFO_2 = @compileError("'PROVIDOR_INFO_2' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_OPTIONS = @compileError("'PRINTER_OPTIONS' requires that UNICODE be set to true or false in the root module"); pub const PRINTER_CONNECTION_INFO_1 = @compileError("'PRINTER_CONNECTION_INFO_1' requires that UNICODE be set to true or false in the root module"); pub const CORE_PRINTER_DRIVER = @compileError("'CORE_PRINTER_DRIVER' requires that UNICODE be set to true or false in the root module"); pub const CommonPropertySheetUI = @compileError("'CommonPropertySheetUI' requires that UNICODE be set to true or false in the root module"); pub const EnumPrinters = @compileError("'EnumPrinters' requires that UNICODE be set to true or false in the root module"); pub const OpenPrinter = @compileError("'OpenPrinter' requires that UNICODE be set to true or false in the root module"); pub const ResetPrinter = @compileError("'ResetPrinter' requires that UNICODE be set to true or false in the root module"); pub const SetJob = @compileError("'SetJob' requires that UNICODE be set to true or false in the root module"); pub const GetJob = @compileError("'GetJob' requires that UNICODE be set to true or false in the root module"); pub const EnumJobs = @compileError("'EnumJobs' requires that UNICODE be set to true or false in the root module"); pub const AddPrinter = @compileError("'AddPrinter' requires that UNICODE be set to true or false in the root module"); pub const SetPrinter = @compileError("'SetPrinter' requires that UNICODE be set to true or false in the root module"); pub const GetPrinter = @compileError("'GetPrinter' requires that UNICODE be set to true or false in the root module"); pub const AddPrinterDriver = @compileError("'AddPrinterDriver' requires that UNICODE be set to true or false in the root module"); pub const AddPrinterDriverEx = @compileError("'AddPrinterDriverEx' requires that UNICODE be set to true or false in the root module"); pub const EnumPrinterDrivers = @compileError("'EnumPrinterDrivers' requires that UNICODE be set to true or false in the root module"); pub const GetPrinterDriver = @compileError("'GetPrinterDriver' requires that UNICODE be set to true or false in the root module"); pub const GetPrinterDriverDirectory = @compileError("'GetPrinterDriverDirectory' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterDriver = @compileError("'DeletePrinterDriver' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterDriverEx = @compileError("'DeletePrinterDriverEx' requires that UNICODE be set to true or false in the root module"); pub const AddPrintProcessor = @compileError("'AddPrintProcessor' requires that UNICODE be set to true or false in the root module"); pub const EnumPrintProcessors = @compileError("'EnumPrintProcessors' requires that UNICODE be set to true or false in the root module"); pub const GetPrintProcessorDirectory = @compileError("'GetPrintProcessorDirectory' requires that UNICODE be set to true or false in the root module"); pub const EnumPrintProcessorDatatypes = @compileError("'EnumPrintProcessorDatatypes' requires that UNICODE be set to true or false in the root module"); pub const DeletePrintProcessor = @compileError("'DeletePrintProcessor' requires that UNICODE be set to true or false in the root module"); pub const StartDocPrinter = @compileError("'StartDocPrinter' requires that UNICODE be set to true or false in the root module"); pub const AddJob = @compileError("'AddJob' requires that UNICODE be set to true or false in the root module"); pub const DocumentProperties = @compileError("'DocumentProperties' requires that UNICODE be set to true or false in the root module"); pub const AdvancedDocumentProperties = @compileError("'AdvancedDocumentProperties' requires that UNICODE be set to true or false in the root module"); pub const GetPrinterData = @compileError("'GetPrinterData' requires that UNICODE be set to true or false in the root module"); pub const GetPrinterDataEx = @compileError("'GetPrinterDataEx' requires that UNICODE be set to true or false in the root module"); pub const EnumPrinterData = @compileError("'EnumPrinterData' requires that UNICODE be set to true or false in the root module"); pub const EnumPrinterDataEx = @compileError("'EnumPrinterDataEx' requires that UNICODE be set to true or false in the root module"); pub const EnumPrinterKey = @compileError("'EnumPrinterKey' requires that UNICODE be set to true or false in the root module"); pub const SetPrinterData = @compileError("'SetPrinterData' requires that UNICODE be set to true or false in the root module"); pub const SetPrinterDataEx = @compileError("'SetPrinterDataEx' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterData = @compileError("'DeletePrinterData' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterDataEx = @compileError("'DeletePrinterDataEx' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterKey = @compileError("'DeletePrinterKey' requires that UNICODE be set to true or false in the root module"); pub const PrinterMessageBox = @compileError("'PrinterMessageBox' requires that UNICODE be set to true or false in the root module"); pub const AddForm = @compileError("'AddForm' requires that UNICODE be set to true or false in the root module"); pub const DeleteForm = @compileError("'DeleteForm' requires that UNICODE be set to true or false in the root module"); pub const GetForm = @compileError("'GetForm' requires that UNICODE be set to true or false in the root module"); pub const SetForm = @compileError("'SetForm' requires that UNICODE be set to true or false in the root module"); pub const EnumForms = @compileError("'EnumForms' requires that UNICODE be set to true or false in the root module"); pub const EnumMonitors = @compileError("'EnumMonitors' requires that UNICODE be set to true or false in the root module"); pub const AddMonitor = @compileError("'AddMonitor' requires that UNICODE be set to true or false in the root module"); pub const DeleteMonitor = @compileError("'DeleteMonitor' requires that UNICODE be set to true or false in the root module"); pub const EnumPorts = @compileError("'EnumPorts' requires that UNICODE be set to true or false in the root module"); pub const AddPort = @compileError("'AddPort' requires that UNICODE be set to true or false in the root module"); pub const ConfigurePort = @compileError("'ConfigurePort' requires that UNICODE be set to true or false in the root module"); pub const DeletePort = @compileError("'DeletePort' requires that UNICODE be set to true or false in the root module"); pub const GetDefaultPrinter = @compileError("'GetDefaultPrinter' requires that UNICODE be set to true or false in the root module"); pub const SetDefaultPrinter = @compileError("'SetDefaultPrinter' requires that UNICODE be set to true or false in the root module"); pub const SetPort = @compileError("'SetPort' requires that UNICODE be set to true or false in the root module"); pub const AddPrinterConnection = @compileError("'AddPrinterConnection' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterConnection = @compileError("'DeletePrinterConnection' requires that UNICODE be set to true or false in the root module"); pub const AddPrintProvidor = @compileError("'AddPrintProvidor' requires that UNICODE be set to true or false in the root module"); pub const DeletePrintProvidor = @compileError("'DeletePrintProvidor' requires that UNICODE be set to true or false in the root module"); pub const IsValidDevmode = @compileError("'IsValidDevmode' requires that UNICODE be set to true or false in the root module"); pub const OpenPrinter2 = @compileError("'OpenPrinter2' requires that UNICODE be set to true or false in the root module"); pub const AddPrinterConnection2 = @compileError("'AddPrinterConnection2' requires that UNICODE be set to true or false in the root module"); pub const InstallPrinterDriverFromPackage = @compileError("'InstallPrinterDriverFromPackage' requires that UNICODE be set to true or false in the root module"); pub const UploadPrinterDriverPackage = @compileError("'UploadPrinterDriverPackage' requires that UNICODE be set to true or false in the root module"); pub const GetCorePrinterDrivers = @compileError("'GetCorePrinterDrivers' requires that UNICODE be set to true or false in the root module"); pub const CorePrinterDriverInstalled = @compileError("'CorePrinterDriverInstalled' requires that UNICODE be set to true or false in the root module"); pub const GetPrinterDriverPackagePath = @compileError("'GetPrinterDriverPackagePath' requires that UNICODE be set to true or false in the root module"); pub const DeletePrinterDriverPackage = @compileError("'DeletePrinterDriverPackage' requires that UNICODE be set to true or false in the root module"); pub const GetPrinterDriver2 = @compileError("'GetPrinterDriver2' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (39) //-------------------------------------------------------------------------------- const Guid = @import("../zig.zig").Guid; const BOOL = @import("../foundation.zig").BOOL; const BSTR = @import("../foundation.zig").BSTR; const CHAR = @import("../foundation.zig").CHAR; const DEVMODEA = @import("../graphics/gdi.zig").DEVMODEA; const DEVMODEW = @import("../graphics/gdi.zig").DEVMODEW; const DLGPROC = @import("../ui/windows_and_messaging.zig").DLGPROC; const DOCINFOW = @import("../storage/xps.zig").DOCINFOW; const FARPROC = @import("../foundation.zig").FARPROC; const FD_KERNINGPAIR = @import("../devices/display.zig").FD_KERNINGPAIR; const FILETIME = @import("../foundation.zig").FILETIME; const HANDLE = @import("../foundation.zig").HANDLE; const HDC = @import("../graphics/gdi.zig").HDC; const HICON = @import("../ui/windows_and_messaging.zig").HICON; const HINSTANCE = @import("../foundation.zig").HINSTANCE; const HKEY = @import("../system/registry.zig").HKEY; const HRESULT = @import("../foundation.zig").HRESULT; const HWND = @import("../foundation.zig").HWND; const IDispatch = @import("../system/com.zig").IDispatch; const IDXGISurface = @import("../graphics/dxgi.zig").IDXGISurface; const IStream = @import("../system/com.zig").IStream; const IUnknown = @import("../system/com.zig").IUnknown; const IWICBitmap = @import("../graphics/imaging.zig").IWICBitmap; const IXMLDOMDocument2 = @import("../data/xml/ms_xml.zig").IXMLDOMDocument2; const IXpsOMPage = @import("../storage/xps.zig").IXpsOMPage; const LPARAM = @import("../foundation.zig").LPARAM; const LRESULT = @import("../foundation.zig").LRESULT; const PANOSE = @import("../graphics/gdi.zig").PANOSE; const POINTL = @import("../foundation.zig").POINTL; const PSTR = @import("../foundation.zig").PSTR; const PWSTR = @import("../foundation.zig").PWSTR; const RECT = @import("../foundation.zig").RECT; const RECTL = @import("../foundation.zig").RECTL; const SECURITY_DESCRIPTOR = @import("../security.zig").SECURITY_DESCRIPTOR; const SIZE = @import("../foundation.zig").SIZE; const STREAM_SEEK = @import("../system/com.zig").STREAM_SEEK; const SYSTEMTIME = @import("../foundation.zig").SYSTEMTIME; const VARIANT = @import("../system/com.zig").VARIANT; const WPARAM = @import("../foundation.zig").WPARAM; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "_CPSUICALLBACK")) { _ = _CPSUICALLBACK; } if (@hasDecl(@This(), "PFNCOMPROPSHEET")) { _ = PFNCOMPROPSHEET; } if (@hasDecl(@This(), "PFNPROPSHEETUI")) { _ = PFNPROPSHEETUI; } if (@hasDecl(@This(), "PFN_DrvGetDriverSetting")) { _ = PFN_DrvGetDriverSetting; } if (@hasDecl(@This(), "PFN_DrvUpgradeRegistrySetting")) { _ = PFN_DrvUpgradeRegistrySetting; } if (@hasDecl(@This(), "PFN_DrvUpdateUISetting")) { _ = PFN_DrvUpdateUISetting; } if (@hasDecl(@This(), "OEMCUIPCALLBACK")) { _ = OEMCUIPCALLBACK; } if (@hasDecl(@This(), "EMFPLAYPROC")) { _ = EMFPLAYPROC; } if (@hasDecl(@This(), "ROUTER_NOTIFY_CALLBACK")) { _ = ROUTER_NOTIFY_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; } } } //-------------------------------------------------------------------------------- // Section: SubModules (1) //-------------------------------------------------------------------------------- pub const print_ticket = @import("printing/print_ticket.zig");
win32/graphics/printing.zig
const std = @import("std"); const vk = @import("vulkan"); const c = @import("c.zig"); const resources = @import("resources"); const GraphicsContext = @import("graphics_context.zig").GraphicsContext; const Swapchain = @import("swapchain.zig").Swapchain; const Allocator = std.mem.Allocator; const app_name = "vulkan-zig triangle example"; const Vertex = struct { const binding_description = vk.VertexInputBindingDescription{ .binding = 0, .stride = @sizeOf(Vertex), .input_rate = .vertex, }; const attribute_description = [_]vk.VertexInputAttributeDescription{ .{ .binding = 0, .location = 0, .format = .r32g32_sfloat, .offset = @offsetOf(Vertex, "pos"), }, .{ .binding = 0, .location = 1, .format = .r32g32b32_sfloat, .offset = @offsetOf(Vertex, "color"), }, }; pos: [2]f32, color: [3]f32, }; const vertices = [_]Vertex{ .{ .pos = .{ 0, -0.5 }, .color = .{ 1, 0, 0 } }, .{ .pos = .{ 0.5, 0.5 }, .color = .{ 0, 1, 0 } }, .{ .pos = .{ -0.5, 0.5 }, .color = .{ 0, 0, 1 } }, }; pub fn main() !void { if (c.glfwInit() != c.GLFW_TRUE) return error.GlfwInitFailed; defer c.glfwTerminate(); var extent = vk.Extent2D{ .width = 800, .height = 600 }; c.glfwWindowHint(c.GLFW_CLIENT_API, c.GLFW_NO_API); const window = c.glfwCreateWindow( @intCast(c_int, extent.width), @intCast(c_int, extent.height), app_name, null, null, ) orelse return error.WindowInitFailed; defer c.glfwDestroyWindow(window); const allocator = std.heap.page_allocator; const gc = try GraphicsContext.init(allocator, app_name, window); defer gc.deinit(); std.debug.print("Using device: {s}\n", .{gc.deviceName()}); var swapchain = try Swapchain.init(&gc, allocator, extent); defer swapchain.deinit(); const pipeline_layout = try gc.vkd.createPipelineLayout(gc.dev, .{ .flags = .{}, .set_layout_count = 0, .p_set_layouts = undefined, .push_constant_range_count = 0, .p_push_constant_ranges = undefined, }, null); defer gc.vkd.destroyPipelineLayout(gc.dev, pipeline_layout, null); const render_pass = try createRenderPass(&gc, swapchain); defer gc.vkd.destroyRenderPass(gc.dev, render_pass, null); var pipeline = try createPipeline(&gc, pipeline_layout, render_pass); defer gc.vkd.destroyPipeline(gc.dev, pipeline, null); var framebuffers = try createFramebuffers(&gc, allocator, render_pass, swapchain); defer destroyFramebuffers(&gc, allocator, framebuffers); const pool = try gc.vkd.createCommandPool(gc.dev, .{ .flags = .{}, .queue_family_index = gc.graphics_queue.family, }, null); defer gc.vkd.destroyCommandPool(gc.dev, pool, null); const buffer = try gc.vkd.createBuffer(gc.dev, .{ .flags = .{}, .size = @sizeOf(@TypeOf(vertices)), .usage = .{ .transfer_dst_bit = true, .vertex_buffer_bit = true }, .sharing_mode = .exclusive, .queue_family_index_count = 0, .p_queue_family_indices = undefined, }, null); defer gc.vkd.destroyBuffer(gc.dev, buffer, null); const mem_reqs = gc.vkd.getBufferMemoryRequirements(gc.dev, buffer); const memory = try gc.allocate(mem_reqs, .{ .device_local_bit = true }); defer gc.vkd.freeMemory(gc.dev, memory, null); try gc.vkd.bindBufferMemory(gc.dev, buffer, memory, 0); try uploadVertices(&gc, pool, buffer); var cmdbufs = try createCommandBuffers( &gc, pool, allocator, buffer, swapchain.extent, render_pass, pipeline, framebuffers, ); defer destroyCommandBuffers(&gc, pool, allocator, cmdbufs); while (c.glfwWindowShouldClose(window) == c.GLFW_FALSE) { const cmdbuf = cmdbufs[swapchain.image_index]; const state = swapchain.present(cmdbuf) catch |err| switch (err) { error.OutOfDateKHR => Swapchain.PresentState.suboptimal, else => |narrow| return narrow, }; if (state == .suboptimal) { var w: c_int = undefined; var h: c_int = undefined; c.glfwGetWindowSize(window, &w, &h); extent.width = @intCast(u32, w); extent.height = @intCast(u32, h); try swapchain.recreate(extent); destroyFramebuffers(&gc, allocator, framebuffers); framebuffers = try createFramebuffers(&gc, allocator, render_pass, swapchain); destroyCommandBuffers(&gc, pool, allocator, cmdbufs); cmdbufs = try createCommandBuffers( &gc, pool, allocator, buffer, swapchain.extent, render_pass, pipeline, framebuffers, ); } c.glfwSwapBuffers(window); c.glfwPollEvents(); } try swapchain.waitForAllFences(); } fn uploadVertices(gc: *const GraphicsContext, pool: vk.CommandPool, buffer: vk.Buffer) !void { const staging_buffer = try gc.vkd.createBuffer(gc.dev, .{ .flags = .{}, .size = @sizeOf(@TypeOf(vertices)), .usage = .{ .transfer_src_bit = true }, .sharing_mode = .exclusive, .queue_family_index_count = 0, .p_queue_family_indices = undefined, }, null); defer gc.vkd.destroyBuffer(gc.dev, staging_buffer, null); const mem_reqs = gc.vkd.getBufferMemoryRequirements(gc.dev, staging_buffer); const staging_memory = try gc.allocate(mem_reqs, .{ .host_visible_bit = true, .host_coherent_bit = true }); defer gc.vkd.freeMemory(gc.dev, staging_memory, null); try gc.vkd.bindBufferMemory(gc.dev, staging_buffer, staging_memory, 0); { const data = try gc.vkd.mapMemory(gc.dev, staging_memory, 0, vk.WHOLE_SIZE, .{}); defer gc.vkd.unmapMemory(gc.dev, staging_memory); const gpu_vertices = @ptrCast([*]Vertex, @alignCast(@alignOf(Vertex), data)); for (vertices) |vertex, i| { gpu_vertices[i] = vertex; } } try copyBuffer(gc, pool, buffer, staging_buffer, @sizeOf(@TypeOf(vertices))); } fn copyBuffer(gc: *const GraphicsContext, pool: vk.CommandPool, dst: vk.Buffer, src: vk.Buffer, size: vk.DeviceSize) !void { var cmdbuf: vk.CommandBuffer = undefined; try gc.vkd.allocateCommandBuffers(gc.dev, .{ .command_pool = pool, .level = .primary, .command_buffer_count = 1, }, @ptrCast([*]vk.CommandBuffer, &cmdbuf)); defer gc.vkd.freeCommandBuffers(gc.dev, pool, 1, @ptrCast([*]const vk.CommandBuffer, &cmdbuf)); try gc.vkd.beginCommandBuffer(cmdbuf, .{ .flags = .{ .one_time_submit_bit = true }, .p_inheritance_info = null, }); const region = vk.BufferCopy{ .src_offset = 0, .dst_offset = 0, .size = size, }; gc.vkd.cmdCopyBuffer(cmdbuf, src, dst, 1, @ptrCast([*]const vk.BufferCopy, &region)); try gc.vkd.endCommandBuffer(cmdbuf); const si = vk.SubmitInfo{ .wait_semaphore_count = 0, .p_wait_semaphores = undefined, .p_wait_dst_stage_mask = undefined, .command_buffer_count = 1, .p_command_buffers = @ptrCast([*]const vk.CommandBuffer, &cmdbuf), .signal_semaphore_count = 0, .p_signal_semaphores = undefined, }; try gc.vkd.queueSubmit(gc.graphics_queue.handle, 1, @ptrCast([*]const vk.SubmitInfo, &si), .null_handle); try gc.vkd.queueWaitIdle(gc.graphics_queue.handle); } fn createCommandBuffers( gc: *const GraphicsContext, pool: vk.CommandPool, allocator: *Allocator, buffer: vk.Buffer, extent: vk.Extent2D, render_pass: vk.RenderPass, pipeline: vk.Pipeline, framebuffers: []vk.Framebuffer, ) ![]vk.CommandBuffer { const cmdbufs = try allocator.alloc(vk.CommandBuffer, framebuffers.len); errdefer allocator.free(cmdbufs); try gc.vkd.allocateCommandBuffers(gc.dev, .{ .command_pool = pool, .level = .primary, .command_buffer_count = @truncate(u32, cmdbufs.len), }, cmdbufs.ptr); errdefer gc.vkd.freeCommandBuffers(gc.dev, pool, @truncate(u32, cmdbufs.len), cmdbufs.ptr); const clear = vk.ClearValue{ .color = .{ .float_32 = .{ 0, 0, 0, 1 } }, }; const viewport = vk.Viewport{ .x = 0, .y = 0, .width = @intToFloat(f32, extent.width), .height = @intToFloat(f32, extent.height), .min_depth = 0, .max_depth = 1, }; const scissor = vk.Rect2D{ .offset = .{ .x = 0, .y = 0 }, .extent = extent, }; for (cmdbufs) |cmdbuf, i| { try gc.vkd.beginCommandBuffer(cmdbuf, .{ .flags = .{}, .p_inheritance_info = null, }); gc.vkd.cmdSetViewport(cmdbuf, 0, 1, @ptrCast([*]const vk.Viewport, &viewport)); gc.vkd.cmdSetScissor(cmdbuf, 0, 1, @ptrCast([*]const vk.Rect2D, &scissor)); gc.vkd.cmdBeginRenderPass(cmdbuf, .{ .render_pass = render_pass, .framebuffer = framebuffers[i], .render_area = .{ .offset = .{ .x = 0, .y = 0 }, .extent = extent, }, .clear_value_count = 1, .p_clear_values = @ptrCast([*]const vk.ClearValue, &clear), }, .@"inline"); gc.vkd.cmdBindPipeline(cmdbuf, .graphics, pipeline); const offset = [_]vk.DeviceSize{0}; gc.vkd.cmdBindVertexBuffers(cmdbuf, 0, 1, @ptrCast([*]const vk.Buffer, &buffer), &offset); gc.vkd.cmdDraw(cmdbuf, vertices.len, 1, 0, 0); gc.vkd.cmdEndRenderPass(cmdbuf); try gc.vkd.endCommandBuffer(cmdbuf); } return cmdbufs; } fn destroyCommandBuffers(gc: *const GraphicsContext, pool: vk.CommandPool, allocator: *Allocator, cmdbufs: []vk.CommandBuffer) void { gc.vkd.freeCommandBuffers(gc.dev, pool, @truncate(u32, cmdbufs.len), cmdbufs.ptr); allocator.free(cmdbufs); } fn createFramebuffers(gc: *const GraphicsContext, allocator: *Allocator, render_pass: vk.RenderPass, swapchain: Swapchain) ![]vk.Framebuffer { const framebuffers = try allocator.alloc(vk.Framebuffer, swapchain.swap_images.len); errdefer allocator.free(framebuffers); var i: usize = 0; errdefer for (framebuffers[0..i]) |fb| gc.vkd.destroyFramebuffer(gc.dev, fb, null); for (framebuffers) |*fb| { fb.* = try gc.vkd.createFramebuffer(gc.dev, .{ .flags = .{}, .render_pass = render_pass, .attachment_count = 1, .p_attachments = @ptrCast([*]const vk.ImageView, &swapchain.swap_images[i].view), .width = swapchain.extent.width, .height = swapchain.extent.height, .layers = 1, }, null); i += 1; } return framebuffers; } fn destroyFramebuffers(gc: *const GraphicsContext, allocator: *Allocator, framebuffers: []const vk.Framebuffer) void { for (framebuffers) |fb| gc.vkd.destroyFramebuffer(gc.dev, fb, null); allocator.free(framebuffers); } fn createRenderPass(gc: *const GraphicsContext, swapchain: Swapchain) !vk.RenderPass { const color_attachment = vk.AttachmentDescription{ .flags = .{}, .format = swapchain.surface_format.format, .samples = .{ .@"1_bit" = true }, .load_op = .clear, .store_op = .store, .stencil_load_op = .dont_care, .stencil_store_op = .dont_care, .initial_layout = .@"undefined", .final_layout = .present_src_khr, }; const color_attachment_ref = vk.AttachmentReference{ .attachment = 0, .layout = .color_attachment_optimal, }; const subpass = vk.SubpassDescription{ .flags = .{}, .pipeline_bind_point = .graphics, .input_attachment_count = 0, .p_input_attachments = undefined, .color_attachment_count = 1, .p_color_attachments = @ptrCast([*]const vk.AttachmentReference, &color_attachment_ref), .p_resolve_attachments = null, .p_depth_stencil_attachment = null, .preserve_attachment_count = 0, .p_preserve_attachments = undefined, }; return try gc.vkd.createRenderPass(gc.dev, .{ .flags = .{}, .attachment_count = 1, .p_attachments = @ptrCast([*]const vk.AttachmentDescription, &color_attachment), .subpass_count = 1, .p_subpasses = @ptrCast([*]const vk.SubpassDescription, &subpass), .dependency_count = 0, .p_dependencies = undefined, }, null); } fn createPipeline( gc: *const GraphicsContext, layout: vk.PipelineLayout, render_pass: vk.RenderPass, ) !vk.Pipeline { const vert = try gc.vkd.createShaderModule(gc.dev, .{ .flags = .{}, .code_size = resources.triangle_vert.len, .p_code = @ptrCast([*]const u32, resources.triangle_vert), }, null); defer gc.vkd.destroyShaderModule(gc.dev, vert, null); const frag = try gc.vkd.createShaderModule(gc.dev, .{ .flags = .{}, .code_size = resources.triangle_frag.len, .p_code = @ptrCast([*]const u32, resources.triangle_frag), }, null); defer gc.vkd.destroyShaderModule(gc.dev, frag, null); const pssci = [_]vk.PipelineShaderStageCreateInfo{ .{ .flags = .{}, .stage = .{ .vertex_bit = true }, .module = vert, .p_name = "main", .p_specialization_info = null, }, .{ .flags = .{}, .stage = .{ .fragment_bit = true }, .module = frag, .p_name = "main", .p_specialization_info = null, }, }; const pvisci = vk.PipelineVertexInputStateCreateInfo{ .flags = .{}, .vertex_binding_description_count = 1, .p_vertex_binding_descriptions = @ptrCast([*]const vk.VertexInputBindingDescription, &Vertex.binding_description), .vertex_attribute_description_count = Vertex.attribute_description.len, .p_vertex_attribute_descriptions = &Vertex.attribute_description, }; const piasci = vk.PipelineInputAssemblyStateCreateInfo{ .flags = .{}, .topology = .triangle_list, .primitive_restart_enable = vk.FALSE, }; const pvsci = vk.PipelineViewportStateCreateInfo{ .flags = .{}, .viewport_count = 1, .p_viewports = undefined, // set in createCommandBuffers with cmdSetViewport .scissor_count = 1, .p_scissors = undefined, // set in createCommandBuffers with cmdSetScissor }; const prsci = vk.PipelineRasterizationStateCreateInfo{ .flags = .{}, .depth_clamp_enable = vk.FALSE, .rasterizer_discard_enable = vk.FALSE, .polygon_mode = .fill, .cull_mode = .{ .back_bit = true }, .front_face = .clockwise, .depth_bias_enable = vk.FALSE, .depth_bias_constant_factor = 0, .depth_bias_clamp = 0, .depth_bias_slope_factor = 0, .line_width = 1, }; const pmsci = vk.PipelineMultisampleStateCreateInfo{ .flags = .{}, .rasterization_samples = .{ .@"1_bit" = true }, .sample_shading_enable = vk.FALSE, .min_sample_shading = 1, .p_sample_mask = null, .alpha_to_coverage_enable = vk.FALSE, .alpha_to_one_enable = vk.FALSE, }; const pcbas = vk.PipelineColorBlendAttachmentState{ .blend_enable = vk.FALSE, .src_color_blend_factor = .one, .dst_color_blend_factor = .zero, .color_blend_op = .add, .src_alpha_blend_factor = .one, .dst_alpha_blend_factor = .zero, .alpha_blend_op = .add, .color_write_mask = .{ .r_bit = true, .g_bit = true, .b_bit = true, .a_bit = true }, }; const pcbsci = vk.PipelineColorBlendStateCreateInfo{ .flags = .{}, .logic_op_enable = vk.FALSE, .logic_op = .copy, .attachment_count = 1, .p_attachments = @ptrCast([*]const vk.PipelineColorBlendAttachmentState, &pcbas), .blend_constants = [_]f32{ 0, 0, 0, 0 }, }; const dynstate = [_]vk.DynamicState{ .viewport, .scissor }; const pdsci = vk.PipelineDynamicStateCreateInfo{ .flags = .{}, .dynamic_state_count = dynstate.len, .p_dynamic_states = &dynstate, }; const gpci = vk.GraphicsPipelineCreateInfo{ .flags = .{}, .stage_count = 2, .p_stages = &pssci, .p_vertex_input_state = &pvisci, .p_input_assembly_state = &piasci, .p_tessellation_state = null, .p_viewport_state = &pvsci, .p_rasterization_state = &prsci, .p_multisample_state = &pmsci, .p_depth_stencil_state = null, .p_color_blend_state = &pcbsci, .p_dynamic_state = &pdsci, .layout = layout, .render_pass = render_pass, .subpass = 0, .base_pipeline_handle = .null_handle, .base_pipeline_index = -1, }; var pipeline: vk.Pipeline = undefined; _ = try gc.vkd.createGraphicsPipelines( gc.dev, .null_handle, 1, @ptrCast([*]const vk.GraphicsPipelineCreateInfo, &gpci), null, @ptrCast([*]vk.Pipeline, &pipeline), ); return pipeline; }
examples/triangle.zig
const base = @import("../base.zig"); const gen = @import("../gen.zig"); const cal_gr = @import("gregorian.zig"); const COMMON = [_:null]?base.Segment{ .{ .offset = 28 * 0 + 35 * 0, .month = 1, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 1 + 35 * 0, .month = 2, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 1 + 35 * 1, .month = 3, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 2 + 35 * 1, .month = 4, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 3 + 35 * 1, .month = 5, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 3 + 35 * 2, .month = 6, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 4 + 35 * 2, .month = 7, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 5 + 35 * 2, .month = 8, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 5 + 35 * 3, .month = 9, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 6 + 35 * 3, .month = 10, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 7 + 35 * 3, .month = 11, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 7 + 35 * 4, .month = 12, .day_start = 1, .day_end = 28 }, }; const LEAP = [_:null]?base.Segment{ .{ .offset = 28 * 0 + 35 * 0, .month = 1, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 1 + 35 * 0, .month = 2, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 1 + 35 * 1, .month = 3, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 2 + 35 * 1, .month = 4, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 3 + 35 * 1, .month = 5, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 3 + 35 * 2, .month = 6, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 4 + 35 * 2, .month = 7, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 5 + 35 * 2, .month = 8, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 5 + 35 * 3, .month = 9, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 6 + 35 * 3, .month = 10, .day_start = 1, .day_end = 28 }, .{ .offset = 28 * 7 + 35 * 3, .month = 11, .day_start = 1, .day_end = 35 }, .{ .offset = 28 * 7 + 35 * 4, .month = 12, .day_start = 1, .day_end = 35 }, }; var common_var: [COMMON.len:null]?base.Segment = COMMON; var leap_var: [LEAP.len:null]?base.Segment = LEAP; pub const symmetry454 = base.Cal{ .intercalary_list = null, .common_lookup_list = @as([*:null]?base.Segment, &common_var), .leap_lookup_list = @as([*:null]?base.Segment, &leap_var), .leap_cycle = .{ .year_count = 293, .leap_year_count = 52, .offset_years = -146, .common_days = gen.dayCount(COMMON[0..COMMON.len]), .leap_days = gen.leapDayCount(COMMON[0..COMMON.len], LEAP[0..LEAP.len]), .offset_days = (-146 * 364) + (-26 * 7), .skip100 = false, .skip4000 = false, .symmetric = true, }, .week = .{ .start = @enumToInt(base.Weekday7.Monday), .length = gen.lastOfEnum(base.Weekday7), .continuous = true, }, .epoch_mjd = cal_gr.gregorian.epoch_mjd, .common_month_max = gen.monthMax(COMMON[0..COMMON.len]), .leap_month_max = gen.monthMax(LEAP[0..LEAP.len]), .year0 = true, };
src/cal/symmetry454.zig
const std = @import("std"); const os = std.os; const wayland = @import("wayland"); const wl = wayland.client.wl; const xdg = wayland.client.xdg; const c = @cImport(@cInclude("linux/input-event-codes.h")); const Context = struct { shm: ?*wl.Shm = null, compositor: ?*wl.Compositor = null, wm_base: ?*xdg.WmBase = null, xdg_toplevel: ?*xdg.Toplevel = null, seat: ?*wl.Seat = null, }; pub fn main() anyerror!void { const display = try wl.Display.connect(null); const registry = try display.getRegistry(); var context = Context{}; registry.setListener(*Context, registryListener, &context); _ = try display.roundtrip(); const shm = context.shm orelse return error.NoWlShm; const compositor = context.compositor orelse return error.NoWlCompositor; const wm_base = context.wm_base orelse return error.NoXdgWmBase; const buffer = blk: { const width = 128; const height = 128; const stride = width * 4; const size = stride * height; const fd = try os.memfd_create("hello-zig-wayland", 0); try os.ftruncate(fd, size); const data = try os.mmap(null, size, os.PROT_READ | os.PROT_WRITE, os.MAP_SHARED, fd, 0); std.mem.copy(u8, data, @embedFile("cat.bgra")); const pool = try shm.createPool(fd, size); defer pool.destroy(); break :blk try pool.createBuffer(0, width, height, stride, wl.Shm.Format.argb8888); }; defer buffer.destroy(); const surface = try compositor.createSurface(); defer surface.destroy(); const xdg_surface = try wm_base.getXdgSurface(surface); defer xdg_surface.destroy(); context.xdg_toplevel = try xdg_surface.getToplevel(); defer context.xdg_toplevel.?.destroy(); var running = true; xdg_surface.setListener(*wl.Surface, xdgSurfaceListener, surface); context.xdg_toplevel.?.setListener(*bool, xdgToplevelListener, &running); surface.commit(); _ = try display.roundtrip(); surface.attach(buffer, 0, 0); surface.commit(); while (running) _ = try display.dispatch(); } fn registryListener(registry: *wl.Registry, event: wl.Registry.Event, context: *Context) void { switch (event) { .global => |global| { if (std.cstr.cmp(global.interface, wl.Compositor.getInterface().name) == 0) { context.compositor = registry.bind(global.name, wl.Compositor, 1) catch return; } else if (std.cstr.cmp(global.interface, wl.Seat.getInterface().name) == 0) { context.seat = registry.bind(global.name, wl.Seat, 1) catch return; context.seat.?.setListener(*Context, seatListener, context); } else if (std.cstr.cmp(global.interface, wl.Shm.getInterface().name) == 0) { context.shm = registry.bind(global.name, wl.Shm, 1) catch return; } else if (std.cstr.cmp(global.interface, xdg.WmBase.getInterface().name) == 0) { context.wm_base = registry.bind(global.name, xdg.WmBase, 1) catch return; } }, .global_remove => {}, } } fn seatListener(seat: *wl.Seat, event: wl.Seat.Event, context: *Context) void { switch (event) { .capabilities => |data| { if (data.capabilities.pointer) { const pointer = seat.getPointer() catch return; pointer.setListener(*Context, pointerListener, context); } }, .name => {}, } } fn pointerListener(pointer: *wl.Pointer, event: wl.Pointer.Event, context: *Context) void { switch (event) { .enter => {}, .leave => {}, .motion => {}, .button => |data| { if (data.button == c.BTN_LEFT and data.state == wl.Pointer.ButtonState.pressed) { context.xdg_toplevel.?.move(context.seat.?, data.serial); } }, .frame => {}, .axis => {}, .axis_source => {}, .axis_stop => {}, .axis_discrete => {}, } } fn xdgSurfaceListener(xdg_surface: *xdg.Surface, event: xdg.Surface.Event, surface: *wl.Surface) void { switch (event) { .configure => |configure| { xdg_surface.ackConfigure(configure.serial); surface.commit(); }, } } fn xdgToplevelListener(xdg_toplevel: *xdg.Toplevel, event: xdg.Toplevel.Event, running: *bool) void { switch (event) { .configure => {}, .close => running.* = false, } }
hello.zig
const std = @import("std"); const math = std.math; const qnan128 = @bitCast(f128, @as(u128, 0x7fff800000000000) << 64); const __addtf3 = @import("addXf3.zig").__addtf3; fn test__addtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void { const x = __addtf3(a, b); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expected_hi and lo == expected_lo) { return; } // test other possible NaN representation (signal NaN) else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } return error.TestFailed; } test "addtf3" { try test__addtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN + any = NaN try test__addtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf + inf = inf try test__addtf3(math.inf(f128), math.inf(f128), 0x7fff000000000000, 0x0); // inf + any = inf try test__addtf3(math.inf(f128), 0x1.2335653452436234723489432abcdefp+5, 0x7fff000000000000, 0x0); // any + any try test__addtf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x40042afc95c8b579, 0x61e58dd6c51eb77c); try test__addtf3(0x1.edcba52449872455634654321fp-1, 0x1.23456734245345543849abcdefp+5, 0x40042afc95c8b579, 0x61e58dd6c51eb77c); } const __subtf3 = @import("addXf3.zig").__subtf3; fn test__subtf3(a: f128, b: f128, expected_hi: u64, expected_lo: u64) !void { const x = __subtf3(a, b); const rep = @bitCast(u128, x); const hi = @intCast(u64, rep >> 64); const lo = @truncate(u64, rep); if (hi == expected_hi and lo == expected_lo) { return; } // test other possible NaN representation (signal NaN) else if (expected_hi == 0x7fff800000000000 and expected_lo == 0x0) { if ((hi & 0x7fff000000000000) == 0x7fff000000000000 and ((hi & 0xffffffffffff) > 0 or lo > 0)) { return; } } return error.TestFailed; } test "subtf3" { // qNaN - any = qNaN try test__subtf3(qnan128, 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // NaN + any = NaN try test__subtf3(@bitCast(f128, (@as(u128, 0x7fff000000000000) << 64) | @as(u128, 0x800030000000)), 0x1.23456789abcdefp+5, 0x7fff800000000000, 0x0); // inf - any = inf try test__subtf3(math.inf(f128), 0x1.23456789abcdefp+5, 0x7fff000000000000, 0x0); // any + any try test__subtf3(0x1.234567829a3bcdef5678ade36734p+5, 0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x40041b8af1915166, 0xa44a7bca780a166c); try test__subtf3(0x1.ee9d7c52354a6936ab8d7654321fp-1, 0x1.234567829a3bcdef5678ade36734p+5, 0xc0041b8af1915166, 0xa44a7bca780a166c); } const __addxf3 = @import("addXf3.zig").__addxf3; const qnan80 = @bitCast(f80, @bitCast(u80, math.nan(f80)) | (1 << (math.floatFractionalBits(f80) - 1))); fn test__addxf3(a: f80, b: f80, expected: u80) !void { const x = __addxf3(a, b); const rep = @bitCast(u80, x); if (rep == expected) return; if (math.isNan(@bitCast(f80, expected)) and math.isNan(x)) return; // We don't currently test NaN payload propagation return error.TestFailed; } test "addxf3" { // NaN + any = NaN try test__addxf3(qnan80, 0x1.23456789abcdefp+5, @bitCast(u80, qnan80)); try test__addxf3(@bitCast(f80, @as(u80, 0x7fff_8000_8000_3000_0000)), 0x1.23456789abcdefp+5, @bitCast(u80, qnan80)); // any + NaN = NaN try test__addxf3(0x1.23456789abcdefp+5, qnan80, @bitCast(u80, qnan80)); try test__addxf3(0x1.23456789abcdefp+5, @bitCast(f80, @as(u80, 0x7fff_8000_8000_3000_0000)), @bitCast(u80, qnan80)); // NaN + inf = NaN try test__addxf3(qnan80, math.inf(f80), @bitCast(u80, qnan80)); // inf + NaN = NaN try test__addxf3(math.inf(f80), qnan80, @bitCast(u80, qnan80)); // inf + inf = inf try test__addxf3(math.inf(f80), math.inf(f80), @bitCast(u80, math.inf(f80))); // inf + -inf = NaN try test__addxf3(math.inf(f80), -math.inf(f80), @bitCast(u80, qnan80)); // -inf + inf = NaN try test__addxf3(-math.inf(f80), math.inf(f80), @bitCast(u80, qnan80)); // inf + any = inf try test__addxf3(math.inf(f80), 0x1.2335653452436234723489432abcdefp+5, @bitCast(u80, math.inf(f80))); // any + inf = inf try test__addxf3(0x1.2335653452436234723489432abcdefp+5, math.inf(f80), @bitCast(u80, math.inf(f80))); // any + any try test__addxf3(0x1.23456789abcdp+5, 0x1.dcba987654321p+5, 0x4005_BFFFFFFFFFFFC400); try test__addxf3(0x1.23456734245345543849abcdefp+5, 0x1.edcba52449872455634654321fp-1, 0x4004_957E_4AE4_5ABC_B0F3); try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.0p-63, 0x3FFF_FFFFFFFFFFFFFFFF); // exact try test__addxf3(0x1.ffff_ffff_ffff_fffep+0, 0x0.0p0, 0x3FFF_FFFFFFFFFFFFFFFF); // exact try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.4p-63, 0x3FFF_FFFFFFFFFFFFFFFF); // round down try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.8p-63, 0x4000_8000000000000000); // round up to even try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x1.cp-63, 0x4000_8000000000000000); // round up try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x2.0p-63, 0x4000_8000000000000000); // exact try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x2.1p-63, 0x4000_8000000000000000); // round down try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x3.0p-63, 0x4000_8000000000000000); // round down to even try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x3.1p-63, 0x4000_8000000000000001); // round up try test__addxf3(0x1.ffff_ffff_ffff_fffcp+0, 0x4.0p-63, 0x4000_8000000000000001); // exact try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.0p-63, 0x3FFF_8800000000000000); // exact try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.7p-63, 0x3FFF_8800000000000000); // round down try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.8p-63, 0x3FFF_8800000000000000); // round down to even try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x1.9p-63, 0x3FFF_8800000000000001); // round up try test__addxf3(0x1.0fff_ffff_ffff_fffep+0, 0x2.0p-63, 0x3FFF_8800000000000001); // exact try test__addxf3(0x0.ffff_ffff_ffff_fffcp-16382, 0x0.0000_0000_0000_0002p-16382, 0x0000_7FFFFFFFFFFFFFFF); // exact try test__addxf3(0x0.1fff_ffff_ffff_fffcp-16382, 0x0.0000_0000_0000_0002p-16382, 0x0000_0FFFFFFFFFFFFFFF); // exact }
lib/compiler_rt/addXf3_test.zig
const std = @import("std"); const Context = struct { id: u64, frame_buffer: []align(16) u8, allocator: *std.mem.Allocator, func: fn () callconv(.Async) void, frame: ?anyframe = null, done: bool = false, const Self = @This(); fn init(id: u64, func: fn () callconv(.Async) void, allocator: *std.mem.Allocator) !Context { var frame_buffer = try allocator.allocAdvanced(u8, 16, 4096 * 4, .at_least); var context = Context{ .id = id, .frame_buffer = frame_buffer, .allocator = allocator, .func = func, }; return context; } fn deinit(self: *Self) void { self.allocator.free(self.frame_buffer); } fn call(self: *Self) !void { currentContext = self; if (self.frame) |frame| { resume frame; } else { _ = @asyncCall(self.frame_buffer, {}, self.func, .{}); } currentContext = null; } }; var currentContext: ?*Context = null; var gAllocator: *std.mem.Allocator = undefined; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); var allocator = &gpa.allocator; gAllocator = allocator; std.log.info("test async", .{}); var calls = std.ArrayList(Context).init(allocator); defer calls.deinit(); for ([_]u8{0} ** 3) |_, i| { try calls.append(try Context.init(i, foo, allocator)); } defer for (calls.items) |*context| { context.deinit(); }; while (calls.items.len > 0) { var i: usize = 0; while (i < calls.items.len) { try calls.items[i].call(); if (calls.items[i].done) { var context = calls.swapRemove(i); context.deinit(); } else { i += 1; } } } } fn callAsync(func: anytype, args: anytype) callconv(.Async) void { var buff = gAllocator.allocAdvanced(u8, 16, @frameSize(func), .at_least) catch unreachable; defer gAllocator.free(buff); _ = @asyncCall(buff, {}, func, args); var frame = currentContext.?.frame; if (frame) |f| { suspend currentContext.?.frame = @frame(); resume f; } } fn yield() void { suspend currentContext.?.frame = @frame(); } fn bar(b: bool) callconv(.Async) void { if (b) { baz(); } else { callAsync(bar, .{!b}); } } fn baz() void { std.log.info("baz 1", .{}); //yield(); std.log.info("baz 2", .{}); } fn foo() void { var i: i64 = 0; while (i < 2) : (i += 1) { std.log.info("[{}:{}] {any}", .{ @ptrToInt(currentContext), currentContext.?.id, i }); bar(false); std.log.info("[{}:{}] after suspend", .{ @ptrToInt(currentContext), currentContext.?.id }); } std.log.info("[{}:{}] after loop", .{ @ptrToInt(currentContext), currentContext.?.id }); currentContext.?.done = true; }
src/test_async.zig
usingnamespace @import("root").preamble; const interrupts = @import("interrupts.zig"); const idt = @import("idt.zig"); const gdt = @import("gdt.zig"); const serial = @import("serial.zig"); const ports = @import("ports.zig"); const regs = @import("regs.zig"); const apic = @import("apic.zig"); const pci = os.platform.pci; const Tss = @import("tss.zig").Tss; pub const paging = @import("paging.zig"); pub const pci_space = @import("pci_space.zig"); pub const thread = @import("thread.zig"); pub const PagingRoot = u64; pub const InterruptFrame = interrupts.InterruptFrame; pub const InterruptState = interrupts.InterruptState; pub const irq_eoi = apic.eoi; pub const irq_with_ctx = interrupts.irq_with_ctx; fn setup_syscall_instr() void { if (comptime !config.kernel.x86_64.allow_syscall_instr) return; regs.IA32_LSTAR.write(@ptrToInt(interrupts.syscall_handler)); // Clear everything but the res1 bit (bit 1) regs.IA32_FMASK.write(@truncate(u22, ~@as(u64, 1 << 1))); comptime { if (gdt.selector.data64 != gdt.selector.code64 + 8) @compileError("syscall instruction assumes this"); } regs.IA32_STAR.write(@as(u64, gdt.selector.code64) << 32); // Allow syscall instructions regs.IA32_EFER.write(regs.IA32_EFER.read() | (1 << 0)); } pub fn get_and_disable_interrupts() InterruptState { return regs.eflags() & 0x200 == 0x200; } pub fn set_interrupts(s: InterruptState) void { if (s) { asm volatile ( \\sti ); } else { asm volatile ( \\cli ); } } pub fn platform_init() !void { try os.platform.acpi.init_acpi(); @import("ps2.zig").init(); set_interrupts(true); @import("vmware.zig").init(); try os.platform.pci.init_pci(); } pub fn platform_early_init() void { // Set SMP metadata for the first CPU os.platform.smp.prepare(); serial.init(); // Load IDT interrupts.init_interrupts(); // Init BSP GDT os.platform.smp.cpus[0].platform_data.gdt.load(); os.memory.paging.init(); } pub fn bsp_pre_scheduler_init() void { idt.load_idt(); apic.enable(); setup_syscall_instr(); const cpu = &os.platform.smp.cpus[0]; // Init BSP TSS cpu.platform_data.shared_tss = .{}; cpu.platform_data.shared_tss.set_interrupt_stack(cpu.int_stack); cpu.platform_data.shared_tss.set_scheduler_stack(cpu.sched_stack); // Load BSP TSS cpu.platform_data.gdt.update_tss(&cpu.platform_data.shared_tss); } pub fn ap_init() void { os.memory.paging.kernel_context.apply(); idt.load_idt(); setup_syscall_instr(); const cpu = os.platform.thread.get_current_cpu(); cpu.platform_data.gdt.load(); cpu.platform_data.shared_tss = .{}; cpu.platform_data.shared_tss.set_interrupt_stack(cpu.int_stack); cpu.platform_data.shared_tss.set_scheduler_stack(cpu.sched_stack); cpu.platform_data.gdt.update_tss(&cpu.platform_data.shared_tss); apic.enable(); } pub fn spin_hint() void { asm volatile ("pause"); } pub fn await_interrupt() void { asm volatile ( \\sti \\hlt \\cli : : : "memory" ); } pub fn debugputch(ch: u8) void { if (config.kernel.x86_64.e9.enable) ports.outb(0xe9, ch); inline for (config.kernel.x86_64.serial.enabled_ports) |port| { serial.port(port).write(ch); } } pub fn clock() usize { var eax: u32 = undefined; var edx: u32 = undefined; asm volatile ("rdtsc" : [_] "={eax}" (eax), [_] "={edx}" (edx) ); return @as(usize, eax) + (@as(usize, edx) << 32); }
subprojects/flork/src/platform/x86_64/x86_64.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const print = std.debug.print; const data = @embedFile("../inputs/day15.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 grid = try parse(allocator, data); defer deinit_grid(u64, grid); print("Part 1: {d}\n", .{try part1(allocator, grid)}); print("Part 2: {d}\n", .{try part2(allocator, grid)}); } fn Grid(comptime T: type) type { return std.ArrayList(std.ArrayList(T)); } fn deinit_grid(comptime T: type, grid: Grid(T)) void { for (grid.items) |row| { row.deinit(); } grid.deinit(); } fn parse(allocator: Allocator, input: []const u8) !Grid(u64) { var grid = Grid(u64).init(allocator); var lines = std.mem.tokenize(u8, input, "\n"); while (lines.next()) |line| { var row = try std.ArrayList(u64).initCapacity(allocator, line.len); for (line) |c| { try row.append(c - '0'); } try grid.append(row); } return grid; } fn part1(allocator: Allocator, grid: Grid(u64)) !u64 { return solve(1, allocator, grid); } fn part2(allocator: Allocator, grid: Grid(u64)) !u64 { return solve(5, allocator, grid); } const Context = struct { width: usize, distances: *[]u64, }; const Point = struct { const Self = @This(); x: usize, y: usize, fn distance(self: Self, context: Context) u64 { return context.distances.*[self.y * context.width + self.x]; } fn update_distance(self: *Self, context: Context, dist: u64) bool { const current = context.distances.*[self.y * context.width + self.x]; if (dist < current) { context.distances.*[self.y * context.width + self.x] = dist; return true; } return false; } }; fn shorter_distance(context: Context, a: Point, b: Point) std.math.Order { return std.math.order(a.distance(context), b.distance(context)); } fn solve(comptime repeat: usize, allocator: Allocator, grid: Grid(u64)) !u64 { const yl = grid.items.len; const xl = grid.items[0].items.len; const height = yl * repeat; const width = xl * repeat; var distances = try allocator.alloc(u64, height * width); defer allocator.free(distances); std.mem.set(u64, distances, std.math.maxInt(u64)); distances[0] = 0; const context = Context{ .width = width, .distances = &distances }; var to_visit = std.PriorityQueue(Point, Context, shorter_distance).init(allocator, context); defer to_visit.deinit(); try to_visit.add(Point{ .x = 0, .y = 0, }); while (to_visit.removeOrNull()) |current| { if (current.y == height - 1 and current.x == width - 1) return current.distance(context); const neighbours = [4][2]isize{ [2]isize{ -1, 0 }, // left [2]isize{ 1, 0 }, // right [2]isize{ 0, 1 }, // down [2]isize{ 0, -1 }, // up }; for (neighbours) |n| { const nx = @intCast(isize, current.x) + n[0]; const ny = @intCast(isize, current.y) + n[1]; if (nx < 0 or nx >= width or ny < 0 or ny >= height) continue; const unx = @intCast(usize, nx); const uny = @intCast(usize, ny); var neighbour_point = Point{ .x = unx, .y = uny, }; var cost: u64 = grid.items[uny % yl].items[unx % xl] + (unx / xl) + (uny / yl); if (cost > 9) cost -= 9; if (neighbour_point.update_distance(context, current.distance(context) + cost)) { try to_visit.add(neighbour_point); } } } else unreachable; } test "chiton" { const input = \\1163751742 \\1381373672 \\2136511328 \\3694931569 \\7463417111 \\1319128137 \\1359912421 \\3125421639 \\1293138521 \\2311944581 ; const allocator = std.testing.allocator; const grid = try parse(allocator, input); defer { for (grid.items) |row| { row.deinit(); } grid.deinit(); } try std.testing.expectEqual(@as(u64, 40), try part1(allocator, grid)); try std.testing.expectEqual(@as(u64, 315), try part2(allocator, grid)); }
src/day15.zig
const std = @import("std"); const builtin = @import("builtin"); const warn = std.debug.print; const Allocator = std.mem.Allocator; const Buffers = @import("./simple_buffer.zig"); pub fn sliceAddNull(allocator: *Allocator, str: []const u8) []const u8 { return std.cstr.addNullByte(allocator, str) catch unreachable; } pub fn sliceToCstr(allocator: *Allocator, str: []const u8) [*]u8 { var str_null: []u8 = allocator.alloc(u8, str.len + 1) catch unreachable; std.mem.copy(u8, str_null[0..], str); str_null[str.len] = 0; return str_null.ptr; } pub fn cstrToSliceCopy(allocator: *Allocator, cstr: [*c]const u8) []const u8 { var i: usize = std.mem.len(cstr); var ram = allocator.alloc(u8, i) catch unreachable; std.mem.copy(u8, ram, cstr[0..i]); return ram; } pub fn hashIdSame(comptime T: type, a: T, b: T) bool { return std.mem.eql(u8, a.get("id").?.String, b.get("id").?.String); } pub fn mastodonExpandUrl(host: []const u8, home: bool, allocator: *Allocator) []const u8 { var url = Buffers.SimpleU8.initSize(allocator, 0) catch unreachable; var filteredHost = host; if (filteredHost.len > 0) { if (filteredHost[filteredHost.len - 1] == '/') { filteredHost = filteredHost[0 .. filteredHost.len - 1]; } if (std.mem.order(u8, filteredHost[0..6], "https:") != std.math.Order.eq) { url.append("https://") catch unreachable; } url.append(filteredHost) catch unreachable; if (home) { url.append("/api/v1/timelines/home") catch unreachable; } else { url.append("/api/v1/timelines/public") catch unreachable; } return url.toSliceConst(); } else { warn("mastodonExpandUrl given empty host!\n", .{}); return ""; } } pub fn htmlTagStrip(str: []const u8, allocator: *Allocator) ![]const u8 { var newStr = try Buffers.SimpleU8.initSize(allocator, 0); const States = enum { Looking, TagBegin }; var state = States.Looking; var tagEndPlusOne: usize = 0; for (str) |char, idx| { if (state == States.Looking and char == '<') { state = States.TagBegin; try newStr.append(str[tagEndPlusOne..idx]); } else if (state == States.TagBegin and char == '>') { tagEndPlusOne = idx + 1; state = States.Looking; } } if (tagEndPlusOne <= str.len) { try newStr.append(str[tagEndPlusOne..]); } return newStr.toSliceConst(); } test "htmlTagStrip" { const allocator = std.debug.global_allocator; var stripped = htmlTagStrip("a<p>b</p>", allocator) catch unreachable; std.testing.expect(std.mem.eql(u8, stripped, "ab")); stripped = htmlTagStrip("a<p>b</p>c", allocator) catch unreachable; std.testing.expect(std.mem.eql(u8, stripped, "abc")); stripped = htmlTagStrip("a<a img=\"\">b</a>c", allocator) catch unreachable; std.testing.expect(std.mem.eql(u8, stripped, "abc")); } pub fn htmlEntityDecode(str: []const u8, allocator: *Allocator) ![]const u8 { var newStr = try Buffers.SimpleU8.initSize(allocator, 0); var previousStrEndMark: usize = 0; const States = enum { Looking, EntityBegin, EntityFound }; var state = States.Looking; var escStart: usize = undefined; for (str) |char, idx| { if (state == States.Looking and char == '&') { state = States.EntityBegin; escStart = idx; } else if (state == States.EntityBegin) { if (char == ';') { const snip = str[previousStrEndMark..escStart]; previousStrEndMark = idx + 1; try newStr.append(snip); const sigil = str[escStart + 1 .. idx]; var newChar: u8 = undefined; if (std.mem.order(u8, sigil, "amp") == std.math.Order.eq) { newChar = '&'; } try newStr.appendByte(newChar); state = States.Looking; } else if (idx - escStart > 4) { state = States.Looking; } } } if (previousStrEndMark <= str.len) { try newStr.append(str[previousStrEndMark..]); } return newStr.toSliceConst(); } test "htmlEntityParse" { const allocator = std.debug.global_allocator; var stripped = htmlEntityDecode("amp&amp;pam", allocator) catch unreachable; std.testing.expect(std.mem.eql(u8, stripped, "amp&pam")); }
src/util.zig
const std = @import("std"); const getty = @import("getty"); const ArrayVisitor = @import("de/impl/visitor/array.zig").Visitor; const ArrayListVisitor = @import("de/impl/visitor/array_list.zig").Visitor; const BoolVisitor = @import("de/impl/visitor/bool.zig"); const EnumVisitor = @import("de/impl/visitor/enum.zig").Visitor; const FloatVisitor = @import("de/impl/visitor/float.zig").Visitor; const HashMapVisitor = @import("de/impl/visitor/hash_map.zig").Visitor; const IntVisitor = @import("de/impl/visitor/int.zig").Visitor; const OptionalVisitor = @import("de/impl/visitor/optional.zig").Visitor; const LinkedListVisitor = @import("de/impl/visitor/linked_list.zig").Visitor; const PointerVisitor = @import("de/impl/visitor/pointer.zig").Visitor; const SliceVisitor = @import("de/impl/visitor/slice.zig").Visitor; const StructVisitor = @import("de/impl/visitor/struct.zig").Visitor; const TailQueueVisitor = @import("de/impl/visitor/tail_queue.zig").Visitor; const TupleVisitor = @import("de/impl/visitor/tuple.zig").Visitor; const VoidVisitor = @import("de/impl/visitor/void.zig"); /// Deserializer interface pub usingnamespace @import("de/interface/deserializer.zig"); /// `De` interface pub usingnamespace @import("de/interface/de.zig"); pub const de = struct { /// Generic error set for `getty.De` implementations. pub const Error = std.mem.Allocator.Error || error{ DuplicateField, InvalidLength, InvalidType, InvalidValue, MissingField, UnknownField, UnknownVariant, Unsupported, }; pub usingnamespace @import("de/interface/access/map.zig"); pub usingnamespace @import("de/interface/access/sequence.zig"); pub usingnamespace @import("de/interface/seed.zig"); pub usingnamespace @import("de/interface/visitor.zig"); pub usingnamespace @import("de/impl/de/bool.zig"); pub usingnamespace @import("de/impl/de/enum.zig"); pub usingnamespace @import("de/impl/de/float.zig"); pub usingnamespace @import("de/impl/de/int.zig"); pub usingnamespace @import("de/impl/de/map.zig"); pub usingnamespace @import("de/impl/de/optional.zig"); pub usingnamespace @import("de/impl/de/sequence.zig"); pub usingnamespace @import("de/impl/de/string.zig"); pub usingnamespace @import("de/impl/de/struct.zig"); pub usingnamespace @import("de/impl/de/void.zig"); pub usingnamespace @import("de/impl/seed/default.zig"); /// Frees resources allocated during deserialization. pub fn free(allocator: std.mem.Allocator, value: anytype) void { const T = @TypeOf(value); const name = @typeName(T); switch (@typeInfo(T)) { .Bool, .Float, .ComptimeFloat, .Int, .ComptimeInt, .Enum, .EnumLiteral, .Null, .Void => {}, .Array => for (value) |v| free(allocator, v), .Optional => if (value) |v| free(allocator, v), .Pointer => |info| switch (comptime std.meta.trait.isZigString(T)) { true => allocator.free(value), false => switch (info.size) { .One => { free(allocator, value.*); allocator.destroy(value); }, .Slice => { for (value) |v| free(allocator, v); allocator.free(value); }, else => unreachable, }, }, .Union => |info| { if (info.tag_type) |Tag| { inline for (info.fields) |field| { if (value == @field(Tag, field.name)) { free(allocator, @field(value, field.name)); break; } } } else unreachable; }, .Struct => |info| { if (comptime std.mem.startsWith(u8, name, "std.array_list.ArrayListAlignedUnmanaged")) { for (value.items) |v| free(allocator, v); var mut = value; mut.deinit(allocator); } else if (comptime std.mem.startsWith(u8, name, "std.array_list.ArrayList")) { for (value.items) |v| free(allocator, v); value.deinit(); } else if (comptime std.mem.startsWith(u8, name, "std.hash_map.HashMapUnmanaged")) { var iterator = value.iterator(); while (iterator.next()) |entry| { free(allocator, entry.key_ptr.*); free(allocator, entry.value_ptr.*); } var mut = value; mut.deinit(allocator); } else if (comptime std.mem.startsWith(u8, name, "std.hash_map.HashMap")) { var iterator = value.iterator(); while (iterator.next()) |entry| { free(allocator, entry.key_ptr.*); free(allocator, entry.value_ptr.*); } var mut = value; mut.deinit(); } else if (comptime std.mem.startsWith(u8, name, "std.linked_list")) { var iterator = value.first; while (iterator) |node| { free(allocator, node.data); iterator = node.next; allocator.destroy(node); } } else { inline for (info.fields) |field| { if (!field.is_comptime) free(allocator, @field(value, field.name)); } } }, else => unreachable, } } }; /// Performs deserialization using a provided serializer and `de`. pub fn deserializeWith( allocator: ?std.mem.Allocator, comptime T: type, deserializer: anytype, d: anytype, ) @TypeOf(deserializer).Error!T { return try d.deserialize(allocator, T, deserializer); } /// Performs deserialization using a provided serializer and a default `de`. pub fn deserialize( allocator: ?std.mem.Allocator, comptime T: type, deserializer: anytype, ) @TypeOf(deserializer).Error!T { var v = switch (@typeInfo(T)) { .Array => ArrayVisitor(T){}, .Bool => BoolVisitor{}, .Enum => EnumVisitor(T){ .allocator = allocator }, .Float, .ComptimeFloat => FloatVisitor(T){}, .Int, .ComptimeInt => IntVisitor(T){}, .Optional => OptionalVisitor(T){ .allocator = allocator }, .Pointer => |info| switch (info.size) { .One => PointerVisitor(T){ .allocator = allocator.? }, .Slice => SliceVisitor(T){ .allocator = allocator.? }, else => @compileError("type ` " ++ @typeName(T) ++ "` is not supported"), }, .Struct => |info| blk: { if (comptime std.mem.startsWith(u8, @typeName(T), "std.array_list")) { break :blk ArrayListVisitor(T){ .allocator = allocator.? }; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.hash_map")) { break :blk HashMapVisitor(T){ .allocator = allocator.? }; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.linked_list.SinglyLinkedList")) { break :blk LinkedListVisitor(T){ .allocator = allocator.? }; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.linked_list.TailQueue")) { break :blk TailQueueVisitor(T){ .allocator = allocator.? }; } else switch (info.is_tuple) { true => break :blk TupleVisitor(T){}, false => break :blk StructVisitor(T){ .allocator = allocator }, } }, .Void => VoidVisitor{}, else => @compileError("type ` " ++ @typeName(T) ++ "` is not supported"), }; return try _deserialize(allocator, T, deserializer, v.visitor()); } fn _deserialize( allocator: ?std.mem.Allocator, comptime T: type, deserializer: anytype, visitor: anytype, ) @TypeOf(deserializer).Error!@TypeOf(visitor).Value { const Visitor = @TypeOf(visitor); var d = switch (@typeInfo(T)) { .Array => de.SequenceDe(Visitor){ .visitor = visitor }, .Bool => de.BoolDe(Visitor){ .visitor = visitor }, .Enum => de.EnumDe(Visitor){ .visitor = visitor }, .Float, .ComptimeFloat => de.FloatDe(Visitor){ .visitor = visitor }, .Int, .ComptimeInt => de.IntDe(Visitor){ .visitor = visitor }, .Optional => de.OptionalDe(Visitor){ .visitor = visitor }, .Pointer => |info| switch (comptime std.meta.trait.isZigString(T)) { true => de.StringDe(Visitor){ .visitor = visitor }, false => switch (info.size) { .One => return try _deserialize(allocator, std.meta.Child(T), deserializer, visitor), .Slice => de.SequenceDe(Visitor){ .visitor = visitor }, else => unreachable, // UNREACHABLE: `deserialize` raises a compile error for this branch. }, }, .Struct => |info| blk: { if (comptime std.mem.startsWith(u8, @typeName(T), "std.array_list")) { break :blk de.SequenceDe(Visitor){ .visitor = visitor }; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.hash_map")) { break :blk de.MapDe(Visitor){ .visitor = visitor }; } else if (comptime std.mem.startsWith(u8, @typeName(T), "std.linked_list")) { break :blk de.SequenceDe(Visitor){ .visitor = visitor }; } else switch (info.is_tuple) { true => break :blk de.SequenceDe(Visitor){ .visitor = visitor }, false => break :blk de.StructDe(Visitor){ .visitor = visitor }, } }, .Void => de.VoidDe(Visitor){ .visitor = visitor }, else => unreachable, // UNREACHABLE: `deserialize` raises a compile error for this branch. }; return try deserializeWith(allocator, Visitor.Value, deserializer, d.de()); }
src/de.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const HashMap = std.HashMap; /// Core enumeration types. const Result = packed enum(i32) { ok, not_found, bad_argument, serialization_failure, parse_failure, bad_expression, invalid_memory_access, empty, cas_mismatch, result_mismatch, internal_failure, broken_connection, unimplemented, }; const LogLevel = packed enum(i32) { trace, debug, info, warn, err, critical }; const FilterHeadersStatus = packed enum(i32) { ok, stop, continue_and_end_stream, stop_all_iteration_and_buffer, stop_all_iteration_and_watermark }; const FilterMetadataStatus = packed enum(i32) { ok }; const FilterTrailersStatus = packed enum(i32) { ok, stop }; const FilterDataStatus = packed enum(i32) { ok, stop_iteration_and_buffer, stop_iteration_and_watermark, stop_iteration_no_buffer }; const BufferType = packed enum(i32) { http_request_body, http_response_body, network_downstream_data, network_upstream_data, http_call_response_body, grpc_receive_buffer, vm_configuration, plugin_configuration, call_data, }; const HeaderType = packed enum(i32) { request_headers, request_trailers, response_headers, response_trailers, grpc_receive_initial_metadata, grpc_receive_trailing_metadata, http_call_response_headers, http_call_response_trailers, }; /// ABI compatibility stub. export fn proxy_abi_version_0_2_0() void {} /// Core functions to accept data from the host. var buf: [64 * 1024]u8 = undefined; var buf_len: usize = undefined; export fn malloc(len: usize) [*]u8 { if (len > buf.len) { @panic("malloc buffer overrun"); } buf_len = len; return &buf; } // Buffer is overwritten after each ABI call. Copy if needed. fn buffer() []const u8 { return buf[0..buf_len]; } fn bufferCopy(allocator: *Allocator) ![]const u8 { return std.mem.dupe(allocator, u8, buf[0..buf_len]); } fn parsePairs(pairs: []const u8, map: anytype) Result { var n = @bitCast(usize, pairs[0..4].*); var offset: usize = 4; var i: usize = 0; var slice: []const u8 = undefined; var keys: [1024]usize = undefined; var values: [1024]usize = undefined; while (i < n) { slice = pairs[offset .. offset + 4]; keys[i] = @bitCast(usize, slice[0..4].*); offset += 4; slice = pairs[offset .. offset + 4]; values[i] = @bitCast(usize, slice[0..4].*); offset += 4; i += 1; } i = 0; while (i < n) { var key = pairs[offset .. offset + keys[i]]; offset += keys[i] + 1; var value = pairs[offset .. offset + values[i]]; offset += values[i] + 1; map.put(key, value) catch return .parse_failure; i += 1; } return .ok; } /// Logging. extern "env" fn proxy_log(LogLevel, [*]const u8, usize) Result; fn log(comptime l: LogLevel, comptime fmt: []const u8, args: anytype) void { var log_buf: [1024]u8 = undefined; const msg = std.fmt.bufPrint(log_buf[0..], fmt, args) catch { const err: []const u8 = "buffer too small"; _ = proxy_log(.trace, err.ptr, err.len); return; }; _ = proxy_log(l, msg.ptr, msg.len); } /// Access and set host properties. extern "env" fn proxy_get_property([*]const u8, usize, *i32, *i32) Result; fn getProperty(comptime T: type, comptime parts: anytype) ?T { comptime var size: usize = 0; inline for (parts) |part| { size += part.len + 1; } comptime var path: [size]u8 = undefined; comptime var i: usize = 0; inline for (parts) |part| { @memcpy(path[i..], part, part.len); i = i + part.len + 1; path[i - 1] = 0; } var addr1: i32 = undefined; var addr2: i32 = undefined; if (proxy_get_property(&path, size, &addr1, &addr2) != .ok) { return null; } switch (T) { i64, u64 => { std.debug.assert(buf_len == @sizeOf(T)); return @bitCast(T, buf[0..@sizeOf(T)].*); }, []const u8 => return buffer(), else => return null, } } extern "env" fn proxy_set_property([*]const u8, usize, [*]const u8, usize) Result; fn setProperty(key: []const u8, value: []const u8) Result { return proxy_set_property(key.ptr, key.len, value.ptr, value.len); } /// Timer. extern "env" fn proxy_set_tick_period_milliseconds(millis: u32) Result; export fn proxy_on_tick(id: u32) void {} /// Stream processing callbacks. export fn proxy_on_context_create(id: u32, parent_id: u32) void { log(.info, "context create {} from {}, memory size pages (64kB) {}", .{ id, parent_id, @wasmMemorySize(0) }); } export fn proxy_on_request_headers(id: u32, headers: u32, end_stream: u32) FilterHeadersStatus { log(.info, "request headers {} {} {}", .{ id, headers, end_stream }); _ = addHeader(.request_headers, "wasm-test", "wasm-value"); return .ok; } export fn proxy_on_request_body(id: u32, body_buffer_length: u32, end_stream: u32) FilterDataStatus { return .ok; } export fn proxy_on_request_trailers(id: u32, trailers: u32) FilterTrailersStatus { return .ok; } export fn proxy_on_request_metadata(id: u32, nelements: u32) FilterMetadataStatus { return .ok; } export fn proxy_on_response_headers(id: u32, headers: u32, end_stream: u32) FilterHeadersStatus { log(.info, "response headers {} {} {}", .{ id, headers, end_stream }); return .ok; } export fn proxy_on_response_body(id: u32, body_buffer_length: u32, end_stream: u32) FilterDataStatus { return .ok; } export fn proxy_on_response_trailers(id: u32, trailers: u32) FilterTrailersStatus { return .ok; } export fn proxy_on_response_metadata(id: u32, nelements: u32) FilterMetadataStatus { return .ok; } export fn proxy_on_log(id: u32) void { log(.info, "log {}", .{id}); log(.info, "request size {}, with headers {}, header value {}, which is same as {}", .{ getProperty(i64, .{ "request", "size" }), getProperty(i64, .{ "request", "total_size" }), getHeader(.request_headers, "wasm-test"), getProperty([]const u8, .{ "request", "headers", "wasm-test" }), }); var map_buffer: [4096]u8 = undefined; var allocator = &std.heap.FixedBufferAllocator.init(&map_buffer).allocator; var map = std.StringHashMap([]const u8).init(allocator); _ = getAllHeaders(.request_headers, &map); var it = map.iterator(); while (it.next()) |next| { log(.info, "{}: {}", .{ next.key, next.value }); } } /// Buffers. extern "env" fn proxy_get_buffer_bytes(t: BufferType, start: u32, len: u32, *i32, *i32) Result; /// Headers. extern "env" fn proxy_add_header_map_value(t: HeaderType, [*]const u8, usize, [*]const u8, usize) Result; fn addHeader(t: HeaderType, key: []const u8, value: []const u8) Result { return proxy_add_header_map_value(t, key.ptr, key.len, value.ptr, value.len); } extern "env" fn proxy_get_header_map_value(t: HeaderType, [*]const u8, usize, *i32, *i32) Result; fn getHeader(t: HeaderType, key: []const u8) ?[]const u8 { var addr1: i32 = undefined; var addr2: i32 = undefined; if (proxy_get_header_map_value(t, key.ptr, key.len, &addr1, &addr2) == .ok) { return buffer(); } return null; } extern "env" fn proxy_replace_header_map_value(t: HeaderType, [*]const u8, usize, [*]const u8, usize) Result; fn replaceHeader(t: HeaderType, key: []const u8, value: []const u8) Result { return proxy_replace_header_map_value(t, key.ptr, key.len, value.ptr, value.len); } extern "env" fn proxy_remove_header_map_value(t: HeaderType, [*]const u8, usize) Result; fn removeHeader(t: HeaderType, key: []const u8) Result { return proxy_remove_header_map_value(t, key.ptr, key.len); } extern "env" fn proxy_get_header_map_pairs(t: HeaderType, *i32, *i32) Result; fn getAllHeaders(t: HeaderType, map: anytype) Result { var addr1: i32 = undefined; var addr2: i32 = undefined; const result = proxy_get_header_map_pairs(t, &addr1, &addr2); if (result == .ok) { return parsePairs(buffer(), map); } return result; } extern "env" fn proxy_set_header_map_pairs(t: HeaderType, [*]const u8, usize) Result; extern "env" fn proxy_get_header_map_size(t: HeaderType, *i32) Result; /// Lifecycle. extern "env" fn proxy_set_effective_context(id: u32) Result; export fn proxy_on_vm_start(id: u32, len: u32) bool { log(.info, "vm start {}", .{id}); return true; } export fn proxy_on_configure(id: u32, len: u32) bool { var addr1: i32 = undefined; var addr2: i32 = undefined; if (proxy_get_buffer_bytes(.plugin_configuration, 0, len, &addr1, &addr2) == .ok) { log(.info, "configure {} {}", .{ id, buffer() }); } return true; }
extensions/zig_demo/module.zig
const std = @import("std"); const assert = std.debug.assert; /// A First In, First Out ring buffer holding at most `size` elements. pub fn RingBuffer(comptime T: type, comptime size: usize) type { return struct { const Self = @This(); buffer: [size]T = undefined, /// The index of the slot with the first item, if any. index: usize = 0, /// The number of items in the buffer. count: usize = 0, /// Add an element to the RingBuffer. Returns an error if the buffer /// is already full and the element could not be added. pub fn push(self: *Self, item: T) error{NoSpaceLeft}!void { if (self.full()) return error.NoSpaceLeft; self.buffer[(self.index + self.count) % self.buffer.len] = item; self.count += 1; } /// Return, but do not remove, the next item, if any. pub fn peek(self: *Self) ?T { return (self.peek_ptr() orelse return null).*; } /// Return a pointer to, but do not remove, the next item, if any. pub fn peek_ptr(self: *Self) ?*T { if (self.empty()) return null; return &self.buffer[self.index]; } /// Remove and return the next item, if any. pub fn pop(self: *Self) ?T { if (self.empty()) return null; defer { self.index = (self.index + 1) % self.buffer.len; self.count -= 1; } return self.buffer[self.index]; } /// Returns whether the ring buffer is completely full. pub fn full(self: *const Self) bool { return self.count == self.buffer.len; } /// Returns whether the ring buffer is completely empty. pub fn empty(self: *const Self) bool { return self.count == 0; } pub const Iterator = struct { ring: *Self, count: usize = 0, pub fn next(it: *Iterator) ?T { return (it.next_ptr() orelse return null).*; } pub fn next_ptr(it: *Iterator) ?*T { assert(it.count <= it.ring.count); if (it.count == it.ring.count) return null; defer it.count += 1; return &it.ring.buffer[(it.ring.index + it.count) % it.ring.buffer.len]; } }; /// Returns an iterator to iterate through all `count` items in the ring buffer. /// The iterator is invalidated and unsafe if the ring buffer is modified. pub fn iterator(self: *Self) Iterator { return .{ .ring = self }; } }; } const testing = std.testing; test "push/peek/pop/full/empty" { var fifo = RingBuffer(u32, 3){}; try testing.expect(!fifo.full()); try testing.expect(fifo.empty()); try fifo.push(1); try testing.expectEqual(@as(?u32, 1), fifo.peek()); try testing.expect(!fifo.full()); try testing.expect(!fifo.empty()); try fifo.push(2); try testing.expectEqual(@as(?u32, 1), fifo.peek()); try fifo.push(3); try testing.expectError(error.NoSpaceLeft, fifo.push(4)); try testing.expect(fifo.full()); try testing.expect(!fifo.empty()); try testing.expectEqual(@as(?u32, 1), fifo.peek()); try testing.expectEqual(@as(?u32, 1), fifo.pop()); try testing.expect(!fifo.full()); try testing.expect(!fifo.empty()); fifo.peek_ptr().?.* += 1000; try testing.expectEqual(@as(?u32, 1002), fifo.pop()); try testing.expectEqual(@as(?u32, 3), fifo.pop()); try testing.expectEqual(@as(?u32, null), fifo.pop()); try testing.expect(!fifo.full()); try testing.expect(fifo.empty()); } fn test_iterator(comptime T: type, ring: *T, values: []const u32) !void { const ring_index = ring.index; var loops: usize = 0; while (loops < 2) : (loops += 1) { var iterator = ring.iterator(); var index: usize = 0; while (iterator.next()) |item| { try testing.expectEqual(values[index], item); index += 1; } try testing.expectEqual(values.len, index); } try testing.expectEqual(ring_index, ring.index); } test "iterator" { const Ring = RingBuffer(u32, 2); var ring = Ring{}; try test_iterator(Ring, &ring, &[_]u32{}); try ring.push(0); try test_iterator(Ring, &ring, &[_]u32{0}); try ring.push(1); try test_iterator(Ring, &ring, &[_]u32{ 0, 1 }); try testing.expectEqual(@as(?u32, 0), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{1}); try ring.push(2); try test_iterator(Ring, &ring, &[_]u32{ 1, 2 }); var iterator = ring.iterator(); while (iterator.next_ptr()) |item_ptr| { item_ptr.* += 1000; } try testing.expectEqual(@as(?u32, 1001), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{1002}); try ring.push(3); try test_iterator(Ring, &ring, &[_]u32{ 1002, 3 }); try testing.expectEqual(@as(?u32, 1002), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{3}); try testing.expectEqual(@as(?u32, 3), ring.pop()); try test_iterator(Ring, &ring, &[_]u32{}); }
src/ring_buffer.zig