text
stringlengths
32
314k
url
stringlengths
93
243
const root = @import("root"); pub const c = if (@hasDecl(root, "loadable_extension")) @import("c/loadable_extension.zig") else @cImport({ @cInclude("sqlite3.h"); }); // versionGreaterThanOrEqualTo returns true if the SQLite version is >= to the major.minor.patch provided. pub fn versionGreaterThanOrEqualTo(major: u8, minor: u8, patch: u8) bool { return c.SQLITE_VERSION_NUMBER >= @as(u32, major) * 1000000 + @as(u32, minor) * 1000 + @as(u32, patch); } comptime { if (!versionGreaterThanOrEqualTo(3, 21, 0)) { @compileError("must use SQLite >= 3.21.0"); } }
https://raw.githubusercontent.com/OAguinagalde/zig-issue-repro/134932fb6982f5c49c881f232c9be580035c7868/deps/zig-sqlite/c.zig
pub usingnamespace @import("src/main.zig"); pub const bun = @import("src/bun.zig"); pub const content = struct { pub const error_js_path = "packages/bun-error/dist/index.js"; pub const error_js = @embedFile(error_js_path); pub const error_css_path = "packages/bun-error/dist/bun-error.css"; pub const error_css_path_dev = "packages/bun-error/bun-error.css"; pub const error_css = @embedFile(error_css_path); }; pub const completions = struct { pub const bash = @embedFile("./completions/bun.bash"); pub const zsh = @embedFile("./completions/bun.zsh"); pub const fish = @embedFile("./completions/bun.fish"); }; pub const JavaScriptCore = @import("./src/jsc.zig"); pub const C = @import("./src/c.zig");
https://raw.githubusercontent.com/ziord/bun/7fb06c0488da302b56507191841d25ef3c62c0c8/root.zig
pub usingnamespace @import("src/main.zig"); pub const bun = @import("src/bun.zig"); pub const content = struct { pub const error_js_path = "packages/bun-error/dist/index.js"; pub const error_js = @embedFile(error_js_path); pub const error_css_path = "packages/bun-error/dist/bun-error.css"; pub const error_css_path_dev = "packages/bun-error/bun-error.css"; pub const error_css = @embedFile(error_css_path); }; pub const completions = struct { pub const bash = @embedFile("./completions/bun.bash"); pub const zsh = @embedFile("./completions/bun.zsh"); pub const fish = @embedFile("./completions/bun.fish"); }; pub const JavaScriptCore = @import("./src/jsc.zig"); pub const C = @import("./src/c.zig");
https://raw.githubusercontent.com/beingofexistence13/multiversal-lang/dd769e3fc6182c23ef43ed4479614f43f29738c9/javascript/bun/root.zig
const lua = @cImport({ @cInclude("lua.h"); @cInclude("lualib.h"); @cInclude("lauxlib.h"); }); export fn add(s: ?*lua.lua_State) c_int { const a = lua.luaL_checkinteger(s, 1); const b = lua.luaL_checkinteger(s, 2); const c = a + b; lua.lua_pushinteger(s, c); return 1; } pub fn main() void { var s = lua.luaL_newstate(); lua.luaL_openlibs(s); lua.lua_register(s, "zig_add", add); // TODO translate-c: luaL_dostring _ = lua.luaL_loadstring(s, "print(zig_add(3, 5))"); // TODO translate-c: lua_pcall _ = lua.lua_pcallk(s, 0, lua.LUA_MULTRET, 0, 0, null); }
https://raw.githubusercontent.com/akavel/blimps-zig/423dccc4a0b076028f5a0862c7f22df918304cc8/.gyro/github.com-tiehuis-zig-lua-archive-bb4e2759304b4b38df10919a499528fadfe33632.tar.gz/pkg/zig-lua-bb4e2759304b4b38df10919a499528fadfe33632/main.zig
const expect = @import("std").testing.expect; test "for" { //character literals are equivalent to integer literals const string = [_]u8{ 'a', 'b', 'c' }; for (string, 0..) |character, index| { _ = character; _ = index; } for (string) |character| { _ = character; } for (string, 0..) |_, index| { _ = index; } for (string) |_| {} }
https://raw.githubusercontent.com/t0yohei/zig-practice/0f86d58d7f1a3cc03fcdc67c40b3d20630879cea/for_loops.zig
//! Matrix math operations pub fn mul(comptime M: usize, comptime N: usize, comptime P: usize, comptime T: type, a: [N][M]T, b: [P][N]T) [P][M]T { var res: [P][M]T = undefined; for (&res, 0..) |*column, i| { for (column, 0..) |*c, j| { var va: @Vector(N, T) = undefined; comptime var k: usize = 0; inline while (k < N) : (k += 1) { va[k] = a[k][j]; } const vb: @Vector(N, T) = b[i]; c.* = @reduce(.Add, va * vb); } } return res; } const std = @import("std"); test mul { try std.testing.expectEqualDeep([3][4]f32{ .{ 5, 8, 6, 11 }, .{ 4, 9, 5, 9 }, .{ 3, 5, 3, 6 }, }, mul( 4, 3, 3, f32, .{ .{ 1, 2, 0, 1 }, .{ 0, 1, 1, 1 }, .{ 1, 1, 1, 2 }, }, .{ .{ 1, 2, 4 }, .{ 2, 3, 2 }, .{ 1, 1, 2 }, }, )); try std.testing.expectEqualDeep([1][4]f32{ .{ 1, 2, 3, 4 }, }, mul( 4, 4, 1, f32, .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 0, 0, 0, 1 }, }, .{ .{ 1, 2, 3, 4 }, }, )); try std.testing.expectEqualDeep([4][4]f32{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 7, 9, 11, 1 }, }, mul( 4, 4, 4, f32, .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 2, 3, 4, 1 }, }, .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 5, 6, 7, 1 }, }, )); try std.testing.expectEqualDeep([4][4]f32{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 5, 6, 7, 0 }, }, mul( 4, 4, 4, f32, .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 2, 3, 4, 0 }, }, .{ .{ 1, 0, 0, 0 }, .{ 0, 1, 0, 0 }, .{ 0, 0, 1, 0 }, .{ 5, 6, 7, 0 }, }, )); }
https://raw.githubusercontent.com/leroycep/utils.zig/51e07120e8b05e6c5941bc53c765b072a9958c0f/mat.zig
// This code is based on https://github.com/frmdstryr/zhp/blob/a4b5700c289c3619647206144e10fb414113a888/src/websocket.zig // Thank you @frmdstryr. const std = @import("std"); const os = std.os; const bun = @import("root").bun; const string = bun.string; const Output = bun.Output; const Global = bun.Global; const Environment = bun.Environment; const strings = bun.strings; const MutableString = bun.MutableString; const stringZ = bun.stringZ; const default_allocator = bun.default_allocator; const C = bun.C; pub const Opcode = enum(u4) { Continue = 0x0, Text = 0x1, Binary = 0x2, Res3 = 0x3, Res4 = 0x4, Res5 = 0x5, Res6 = 0x6, Res7 = 0x7, Close = 0x8, Ping = 0x9, Pong = 0xA, ResB = 0xB, ResC = 0xC, ResD = 0xD, ResE = 0xE, ResF = 0xF, pub fn isControl(opcode: Opcode) bool { return @intFromEnum(opcode) & 0x8 != 0; } }; pub const WebsocketHeader = packed struct { len: u7, mask: bool, opcode: Opcode, rsv: u2 = 0, //rsv2 and rsv3 compressed: bool = false, // rsv1 final: bool = true, pub fn writeHeader(header: WebsocketHeader, writer: anytype, n: usize) anyerror!void { // packed structs are sometimes buggy // lets check it worked right if (comptime Environment.allow_assert) { var buf_ = [2]u8{ 0, 0 }; var stream = std.io.fixedBufferStream(&buf_); stream.writer().writeInt(u16, @as(u16, @bitCast(header)), .big) catch unreachable; stream.pos = 0; const casted = stream.reader().readInt(u16, .big) catch unreachable; bun.assert(casted == @as(u16, @bitCast(header))); bun.assert(std.meta.eql(@as(WebsocketHeader, @bitCast(casted)), header)); } try writer.writeInt(u16, @as(u16, @bitCast(header)), .big); bun.assert(header.len == packLength(n)); } pub fn packLength(length: usize) u7 { return switch (length) { 0...125 => @as(u7, @truncate(length)), 126...0xFFFF => 126, else => 127, }; } const mask_length = 4; const header_length = 2; pub fn lengthByteCount(byte_length: usize) usize { return switch (byte_length) { 0...125 => 0, 126...0xFFFF => @sizeOf(u16), else => @sizeOf(u64), }; } pub fn frameSize(byte_length: usize) usize { return header_length + byte_length + lengthByteCount(byte_length); } pub fn frameSizeIncludingMask(byte_length: usize) usize { return frameSize(byte_length) + mask_length; } pub fn slice(self: WebsocketHeader) [2]u8 { return @as([2]u8, @bitCast(@byteSwap(@as(u16, @bitCast(self))))); } pub fn fromSlice(bytes: [2]u8) WebsocketHeader { return @as(WebsocketHeader, @bitCast(@byteSwap(@as(u16, @bitCast(bytes))))); } }; pub const WebsocketDataFrame = struct { header: WebsocketHeader, mask: [4]u8 = undefined, data: []const u8, pub fn isValid(dataframe: WebsocketDataFrame) bool { // Validate control frame if (dataframe.header.opcode.isControl()) { if (!dataframe.header.final) { return false; // Control frames cannot be fragmented } if (dataframe.data.len > 125) { return false; // Control frame payloads cannot exceed 125 bytes } } // Validate header len field const expected = switch (dataframe.data.len) { 0...126 => dataframe.data.len, 127...0xFFFF => 126, else => 127, }; return dataframe.header.len == expected; } }; // Create a buffered writer // TODO: This will still split packets pub fn Writer(comptime size: usize, comptime opcode: Opcode) type { const WriterType = switch (opcode) { .Text => Websocket.TextFrameWriter, .Binary => Websocket.BinaryFrameWriter, else => @compileError("Unsupported writer opcode"), }; return std.io.BufferedWriter(size, WriterType); } const ReadStream = std.io.FixedBufferStream([]u8); pub const Websocket = struct { pub const WriteError = error{ InvalidMessage, MessageTooLarge, EndOfStream, } || std.fs.File.WriteError; stream: std.net.Stream, err: ?anyerror = null, buf: [8192]u8 = undefined, read_stream: ReadStream, reader: ReadStream.Reader, flags: u32 = 0, pub fn create( fd: std.os.fd_t, comptime flags: u32, ) Websocket { const stream = ReadStream{ .buffer = &[_]u8{}, .pos = 0, }; var socket = Websocket{ .read_stream = undefined, .reader = undefined, .stream = std.net.Stream{ .handle = bun.socketcast(fd) }, .flags = flags, }; socket.read_stream = stream; socket.reader = socket.read_stream.reader(); return socket; } // ------------------------------------------------------------------------ // Stream API // ------------------------------------------------------------------------ pub const TextFrameWriter = std.io.Writer(*Websocket, WriteError, Websocket.writeText); pub const BinaryFrameWriter = std.io.Writer(*Websocket, anyerror, Websocket.writeBinary); // A buffered writer that will buffer up to size bytes before writing out pub fn newWriter(self: *Websocket, comptime size: usize, comptime opcode: Opcode) Writer(size, opcode) { const BufferedWriter = Writer(size, opcode); const frame_writer = switch (opcode) { .Text => TextFrameWriter{ .context = self }, .Binary => BinaryFrameWriter{ .context = self }, else => @compileError("Unsupported writer type"), }; return BufferedWriter{ .unbuffered_writer = frame_writer }; } // Close and send the status pub fn close(self: *Websocket, code: u16) !void { const c = @byteSwap(code); const data = @as([2]u8, @bitCast(c)); _ = try self.writeMessage(.Close, &data); } // ------------------------------------------------------------------------ // Low level API // ------------------------------------------------------------------------ // Flush any buffered data out the underlying stream pub fn flush(self: *Websocket) !void { try self.io.flush(); } pub fn writeText(self: *Websocket, data: []const u8) !usize { return self.writeMessage(.Text, data); } pub fn writeBinary(self: *Websocket, data: []const u8) anyerror!usize { return self.writeMessage(.Binary, data); } // Write a final message packet with the given opcode pub fn writeMessage(self: *Websocket, opcode: Opcode, message: []const u8) anyerror!usize { return self.writeSplitMessage(opcode, true, message); } // Write a message packet with the given opcode and final flag pub fn writeSplitMessage(self: *Websocket, opcode: Opcode, final: bool, message: []const u8) anyerror!usize { return self.writeDataFrame(WebsocketDataFrame{ .header = WebsocketHeader{ .final = final, .opcode = opcode, .mask = false, // Server to client is not masked .len = WebsocketHeader.packLength(message.len), }, .data = message, }); } // Write a raw data frame pub fn writeDataFrame(self: *Websocket, dataframe: WebsocketDataFrame) anyerror!usize { var stream = self.stream.writer(); if (!dataframe.isValid()) return error.InvalidMessage; try stream.writeInt(u16, @as(u16, @bitCast(dataframe.header)), .big); // Write extended length if needed const n = dataframe.data.len; switch (n) { 0...126 => {}, // Included in header 127...0xFFFF => try stream.writeInt(u16, @as(u16, @truncate(n)), .big), else => try stream.writeInt(u64, n, .big), } // TODO: Handle compression if (dataframe.header.compressed) return error.InvalidMessage; if (dataframe.header.mask) { const mask = &dataframe.mask; try stream.writeAll(mask); // Encode for (dataframe.data, 0..) |c, i| { try stream.writeByte(c ^ mask[i % 4]); } } else { try stream.writeAll(dataframe.data); } // try self.io.flush(); return dataframe.data.len; } pub fn read(self: *Websocket) !WebsocketDataFrame { @memset(&self.buf, 0); // Read and retry if we hit the end of the stream buffer const start = try self.stream.read(&self.buf); if (start == 0) { return error.ConnectionClosed; } self.read_stream.pos = start; return try self.readDataFrameInBuffer(); } pub fn eatAt(self: *Websocket, offset: usize, _len: usize) []u8 { const len = @min(self.read_stream.buffer.len, _len); self.read_stream.pos = len; return self.read_stream.buffer[offset..len]; } // Read assuming everything can fit before the stream hits the end of // it's buffer pub fn readDataFrameInBuffer( self: *Websocket, ) !WebsocketDataFrame { var buf: []u8 = self.buf[0..]; const header_bytes = buf[0..2]; var header = std.mem.zeroes(WebsocketHeader); header.final = header_bytes[0] & 0x80 == 0x80; // header.rsv1 = header_bytes[0] & 0x40 == 0x40; // header.rsv2 = header_bytes[0] & 0x20; // header.rsv3 = header_bytes[0] & 0x10; header.opcode = @as(Opcode, @enumFromInt(@as(u4, @truncate(header_bytes[0])))); header.mask = header_bytes[1] & 0x80 == 0x80; header.len = @as(u7, @truncate(header_bytes[1])); // Decode length var length: u64 = header.len; switch (header.len) { 126 => { length = std.mem.readInt(u16, buf[2..4], .big); buf = buf[4..]; }, 127 => { length = std.mem.readInt(u64, buf[2..10], .big); // Most significant bit must be 0 if (length >> 63 == 1) { return error.InvalidMessage; } buf = buf[10..]; }, else => { buf = buf[2..]; }, } const start: usize = if (header.mask) 4 else 0; const end = start + length; if (end > self.read_stream.pos) { const extend_length = try self.stream.read(self.buf[self.read_stream.pos..]); if (self.read_stream.pos + extend_length > self.buf.len) { return error.MessageTooLarge; } self.read_stream.pos += extend_length; } var data = buf[start..end]; if (header.mask) { const mask = buf[0..4]; // Decode data in place for (data, 0..) |_, i| { data[i] ^= mask[i % 4]; } } return WebsocketDataFrame{ .header = header, .mask = if (header.mask) buf[0..4].* else undefined, .data = data, }; } };
https://raw.githubusercontent.com/oven-sh/bun/fab96a74ea13da04459ea7f62663c4d2fd421778/src/http/websocket.zig
// There is a generic CRC implementation "Crc()" which can be paramterized via // the Algorithm struct for a plethora of uses. // // The primary interface for all of the standard CRC algorithms is the // generated file "crc.zig", which uses the implementation code here to define // many standard CRCs. const std = @import("std"); pub fn Algorithm(comptime W: type) type { return struct { polynomial: W, initial: W, reflect_input: bool, reflect_output: bool, xor_output: W, }; } pub fn Crc(comptime W: type, comptime algorithm: Algorithm(W)) type { return struct { const Self = @This(); const I = if (@bitSizeOf(W) < 8) u8 else W; const lookup_table = blk: { @setEvalBranchQuota(2500); const poly = if (algorithm.reflect_input) @bitReverse(@as(I, algorithm.polynomial)) >> (@bitSizeOf(I) - @bitSizeOf(W)) else @as(I, algorithm.polynomial) << (@bitSizeOf(I) - @bitSizeOf(W)); var table: [256]I = undefined; for (&table, 0..) |*e, i| { var crc: I = i; if (algorithm.reflect_input) { var j: usize = 0; while (j < 8) : (j += 1) { crc = (crc >> 1) ^ ((crc & 1) * poly); } } else { crc <<= @bitSizeOf(I) - 8; var j: usize = 0; while (j < 8) : (j += 1) { crc = (crc << 1) ^ (((crc >> (@bitSizeOf(I) - 1)) & 1) * poly); } } e.* = crc; } break :blk table; }; crc: I, pub fn init() Self { const initial = if (algorithm.reflect_input) @bitReverse(@as(I, algorithm.initial)) >> (@bitSizeOf(I) - @bitSizeOf(W)) else @as(I, algorithm.initial) << (@bitSizeOf(I) - @bitSizeOf(W)); return Self{ .crc = initial }; } inline fn tableEntry(index: I) I { return lookup_table[@as(u8, @intCast(index & 0xFF))]; } pub fn update(self: *Self, bytes: []const u8) void { var i: usize = 0; if (@bitSizeOf(I) <= 8) { while (i < bytes.len) : (i += 1) { self.crc = tableEntry(self.crc ^ bytes[i]); } } else if (algorithm.reflect_input) { while (i < bytes.len) : (i += 1) { const table_index = self.crc ^ bytes[i]; self.crc = tableEntry(table_index) ^ (self.crc >> 8); } } else { while (i < bytes.len) : (i += 1) { const table_index = (self.crc >> (@bitSizeOf(I) - 8)) ^ bytes[i]; self.crc = tableEntry(table_index) ^ (self.crc << 8); } } } pub fn final(self: Self) W { var c = self.crc; if (algorithm.reflect_input != algorithm.reflect_output) { c = @bitReverse(c); } if (!algorithm.reflect_output) { c >>= @bitSizeOf(I) - @bitSizeOf(W); } return @as(W, @intCast(c ^ algorithm.xor_output)); } pub fn hash(bytes: []const u8) W { var c = Self.init(); c.update(bytes); return c.final(); } }; } pub const Polynomial = enum(u32) { IEEE = @compileError("use Crc with algorithm .Crc32IsoHdlc"), Castagnoli = @compileError("use Crc with algorithm .Crc32Iscsi"), Koopman = @compileError("use Crc with algorithm .Crc32Koopman"), _, }; pub const Crc32WithPoly = @compileError("use Crc instead"); pub const Crc32SmallWithPoly = @compileError("use Crc instead");
https://raw.githubusercontent.com/ziglang/zig/d9bd34fd0533295044ffb4160da41f7873aff905/lib/std/hash/crc/impl.zig
const std = @import("std"); const c = @cImport(@cInclude("alsa/asoundlib.h")); const main = @import("main.zig"); const backends = @import("backends.zig"); const util = @import("util.zig"); const inotify_event = std.os.linux.inotify_event; const is_little = @import("builtin").cpu.arch.endian() == .little; const default_sample_rate = 44_100; // Hz var lib: Lib = undefined; const Lib = struct { handle: std.DynLib, snd_lib_error_set_handler: *const fn (c.snd_lib_error_handler_t) callconv(.C) c_int, snd_pcm_info_malloc: *const fn ([*c]?*c.snd_pcm_info_t) callconv(.C) c_int, snd_pcm_info_free: *const fn (?*c.snd_pcm_info_t) callconv(.C) void, snd_pcm_open: *const fn ([*c]?*c.snd_pcm_t, [*c]const u8, c.snd_pcm_stream_t, c_int) callconv(.C) c_int, snd_pcm_close: *const fn (?*c.snd_pcm_t) callconv(.C) c_int, snd_pcm_state: *const fn (?*c.snd_pcm_t) callconv(.C) c.snd_pcm_state_t, snd_pcm_pause: *const fn (?*c.snd_pcm_t, c_int) callconv(.C) c_int, snd_pcm_writei: *const fn (?*c.snd_pcm_t, ?*const anyopaque, c.snd_pcm_uframes_t) callconv(.C) c.snd_pcm_sframes_t, snd_pcm_readi: *const fn (?*c.snd_pcm_t, ?*const anyopaque, c.snd_pcm_uframes_t) callconv(.C) c.snd_pcm_sframes_t, snd_pcm_prepare: *const fn (?*c.snd_pcm_t) callconv(.C) c_int, snd_pcm_info_set_device: *const fn (?*c.snd_pcm_info_t, c_uint) callconv(.C) void, snd_pcm_info_set_subdevice: *const fn (?*c.snd_pcm_info_t, c_uint) callconv(.C) void, snd_pcm_info_get_name: *const fn (?*const c.snd_pcm_info_t) callconv(.C) [*c]const u8, snd_pcm_info_set_stream: *const fn (?*c.snd_pcm_info_t, c.snd_pcm_stream_t) callconv(.C) void, snd_pcm_hw_free: *const fn (?*c.snd_pcm_t) callconv(.C) c_int, snd_pcm_hw_params_malloc: *const fn ([*c]?*c.snd_pcm_hw_params_t) callconv(.C) c_int, snd_pcm_hw_params_free: *const fn (?*c.snd_pcm_hw_params_t) callconv(.C) void, snd_pcm_set_params: *const fn (?*c.snd_pcm_t, c.snd_pcm_format_t, c.snd_pcm_access_t, c_uint, c_uint, c_int, c_uint) callconv(.C) c_int, snd_pcm_hw_params_any: *const fn (?*c.snd_pcm_t, ?*c.snd_pcm_hw_params_t) callconv(.C) c_int, snd_pcm_hw_params_can_pause: *const fn (?*const c.snd_pcm_hw_params_t) callconv(.C) c_int, snd_pcm_hw_params_current: *const fn (?*c.snd_pcm_t, ?*c.snd_pcm_hw_params_t) callconv(.C) c_int, snd_pcm_hw_params_get_format_mask: *const fn (?*c.snd_pcm_hw_params_t, ?*c.snd_pcm_format_mask_t) callconv(.C) void, snd_pcm_hw_params_get_rate_min: *const fn (?*const c.snd_pcm_hw_params_t, [*c]c_uint, [*c]c_int) callconv(.C) c_int, snd_pcm_hw_params_get_rate_max: *const fn (?*const c.snd_pcm_hw_params_t, [*c]c_uint, [*c]c_int) callconv(.C) c_int, snd_pcm_hw_params_get_period_size: *const fn (?*const c.snd_pcm_hw_params_t, [*c]c.snd_pcm_uframes_t, [*c]c_int) callconv(.C) c_int, snd_pcm_query_chmaps: *const fn (?*c.snd_pcm_t) callconv(.C) [*c][*c]c.snd_pcm_chmap_query_t, snd_pcm_free_chmaps: *const fn ([*c][*c]c.snd_pcm_chmap_query_t) callconv(.C) void, snd_pcm_format_mask_malloc: *const fn ([*c]?*c.snd_pcm_format_mask_t) callconv(.C) c_int, snd_pcm_format_mask_free: *const fn (?*c.snd_pcm_format_mask_t) callconv(.C) void, snd_pcm_format_mask_none: *const fn (?*c.snd_pcm_format_mask_t) callconv(.C) void, snd_pcm_format_mask_set: *const fn (?*c.snd_pcm_format_mask_t, c.snd_pcm_format_t) callconv(.C) void, snd_pcm_format_mask_test: *const fn (?*const c.snd_pcm_format_mask_t, c.snd_pcm_format_t) callconv(.C) c_int, snd_card_next: *const fn ([*c]c_int) callconv(.C) c_int, snd_ctl_open: *const fn ([*c]?*c.snd_ctl_t, [*c]const u8, c_int) callconv(.C) c_int, snd_ctl_close: *const fn (?*c.snd_ctl_t) callconv(.C) c_int, snd_ctl_pcm_next_device: *const fn (?*c.snd_ctl_t, [*c]c_int) callconv(.C) c_int, snd_ctl_pcm_info: *const fn (?*c.snd_ctl_t, ?*c.snd_pcm_info_t) callconv(.C) c_int, snd_mixer_open: *const fn ([*c]?*c.snd_mixer_t, c_int) callconv(.C) c_int, snd_mixer_close: *const fn (?*c.snd_mixer_t) callconv(.C) c_int, snd_mixer_load: *const fn (?*c.snd_mixer_t) callconv(.C) c_int, snd_mixer_attach: *const fn (?*c.snd_mixer_t, [*c]const u8) callconv(.C) c_int, snd_mixer_find_selem: *const fn (?*c.snd_mixer_t, ?*const c.snd_mixer_selem_id_t) callconv(.C) ?*c.snd_mixer_elem_t, snd_mixer_selem_register: *const fn (?*c.snd_mixer_t, [*c]c.struct_snd_mixer_selem_regopt, [*c]?*c.snd_mixer_class_t) callconv(.C) c_int, snd_mixer_selem_id_malloc: *const fn ([*c]?*c.snd_mixer_selem_id_t) callconv(.C) c_int, snd_mixer_selem_id_free: *const fn (?*c.snd_mixer_selem_id_t) callconv(.C) void, snd_mixer_selem_id_set_index: *const fn (?*c.snd_mixer_selem_id_t, c_uint) callconv(.C) void, snd_mixer_selem_id_set_name: *const fn (?*c.snd_mixer_selem_id_t, [*c]const u8) callconv(.C) void, snd_mixer_selem_set_playback_volume_all: *const fn (?*c.snd_mixer_elem_t, c_long) callconv(.C) c_int, snd_mixer_selem_get_playback_volume: *const fn (?*c.snd_mixer_elem_t, c.snd_mixer_selem_channel_id_t, [*c]c_long) callconv(.C) c_int, snd_mixer_selem_get_playback_volume_range: *const fn (?*c.snd_mixer_elem_t, [*c]c_long, [*c]c_long) callconv(.C) c_int, snd_mixer_selem_has_playback_channel: *const fn (?*c.snd_mixer_elem_t, c.snd_mixer_selem_channel_id_t) callconv(.C) c_int, snd_mixer_selem_set_capture_volume_all: *const fn (?*c.snd_mixer_elem_t, c_long) callconv(.C) c_int, snd_mixer_selem_get_capture_volume: *const fn (?*c.snd_mixer_elem_t, c.snd_mixer_selem_channel_id_t, [*c]c_long) callconv(.C) c_int, snd_mixer_selem_get_capture_volume_range: *const fn (?*c.snd_mixer_elem_t, [*c]c_long, [*c]c_long) callconv(.C) c_int, snd_mixer_selem_has_capture_channel: *const fn (?*c.snd_mixer_elem_t, c.snd_mixer_selem_channel_id_t) callconv(.C) c_int, pub fn load() !void { lib.handle = std.DynLib.open("libasound.so") catch return error.LibraryNotFound; inline for (@typeInfo(Lib).Struct.fields[1..]) |field| { const name = std.fmt.comptimePrint("{s}\x00", .{field.name}); const name_z: [:0]const u8 = @ptrCast(name[0 .. name.len - 1]); @field(lib, field.name) = lib.handle.lookup(field.type, name_z) orelse return error.SymbolLookup; } } }; pub const Context = struct { allocator: std.mem.Allocator, devices_info: util.DevicesInfo, watcher: ?Watcher, const Watcher = struct { deviceChangeFn: main.Context.DeviceChangeFn, user_data: ?*anyopaque, thread: std.Thread, aborted: std.atomic.Value(bool), notify_fd: std.c.fd_t, notify_wd: std.c.fd_t, notify_pipe_fd: [2]std.c.fd_t, }; pub fn init(allocator: std.mem.Allocator, options: main.Context.Options) !backends.Context { try Lib.load(); _ = lib.snd_lib_error_set_handler(@as(c.snd_lib_error_handler_t, @ptrCast(&util.doNothing))); const ctx = try allocator.create(Context); errdefer allocator.destroy(ctx); ctx.* = .{ .allocator = allocator, .devices_info = util.DevicesInfo.init(), .watcher = blk: { if (options.deviceChangeFn) |deviceChangeFn| { const notify_fd = std.posix.inotify_init1(std.os.linux.IN.NONBLOCK) catch |err| switch (err) { error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, error.SystemResources, => return error.SystemResources, error.Unexpected => unreachable, }; errdefer std.posix.close(notify_fd); const notify_wd = std.posix.inotify_add_watch( notify_fd, "/dev/snd", std.os.linux.IN.CREATE | std.os.linux.IN.DELETE, ) catch |err| switch (err) { error.AccessDenied => return error.AccessDenied, error.UserResourceLimitReached, error.NotDir, error.FileNotFound, error.SystemResources, => return error.SystemResources, error.NameTooLong, error.WatchAlreadyExists, error.Unexpected, => unreachable, }; errdefer std.posix.inotify_rm_watch(notify_fd, notify_wd); const notify_pipe_fd = std.posix.pipe2(.{ .NONBLOCK = true }) catch |err| switch (err) { error.ProcessFdQuotaExceeded, error.SystemFdQuotaExceeded, => return error.SystemResources, error.Unexpected => unreachable, }; errdefer { std.posix.close(notify_pipe_fd[0]); std.posix.close(notify_pipe_fd[1]); } break :blk .{ .deviceChangeFn = deviceChangeFn, .user_data = options.user_data, .aborted = .{ .raw = false }, .notify_fd = notify_fd, .notify_wd = notify_wd, .notify_pipe_fd = notify_pipe_fd, .thread = std.Thread.spawn(.{}, deviceEventsLoop, .{ctx}) catch |err| switch (err) { error.ThreadQuotaExceeded, error.SystemResources, error.LockedMemoryLimitExceeded, => return error.SystemResources, error.OutOfMemory => return error.OutOfMemory, error.Unexpected => unreachable, }, }; } break :blk null; }, }; return .{ .alsa = ctx }; } pub fn deinit(ctx: *Context) void { if (ctx.watcher) |*watcher| { watcher.aborted.store(true, .unordered); _ = std.posix.write(watcher.notify_pipe_fd[1], "a") catch {}; watcher.thread.join(); std.posix.close(watcher.notify_pipe_fd[0]); std.posix.close(watcher.notify_pipe_fd[1]); std.posix.inotify_rm_watch(watcher.notify_fd, watcher.notify_wd); std.posix.close(watcher.notify_fd); } for (ctx.devices_info.list.items) |d| freeDevice(ctx.allocator, d); ctx.devices_info.list.deinit(ctx.allocator); ctx.allocator.destroy(ctx); lib.handle.close(); } fn deviceEventsLoop(ctx: *Context) void { var watcher = ctx.watcher.?; var scan = false; var last_crash: ?i64 = null; var buf: [2048]u8 = undefined; var fds = [2]std.posix.pollfd{ .{ .fd = watcher.notify_fd, .events = std.posix.POLL.IN, .revents = 0, }, .{ .fd = watcher.notify_pipe_fd[0], .events = std.posix.POLL.IN, .revents = 0, }, }; while (!watcher.aborted.load(.unordered)) { _ = std.posix.poll(&fds, -1) catch |err| switch (err) { error.NetworkSubsystemFailed, error.SystemResources, => { const ts = std.time.milliTimestamp(); if (last_crash) |lc| { if (ts - lc < 500) return; } last_crash = ts; continue; }, error.Unexpected => unreachable, }; if (watcher.notify_fd & std.posix.POLL.IN != 0) { while (true) { const len = std.posix.read(watcher.notify_fd, &buf) catch |err| { if (err == error.WouldBlock) break; const ts = std.time.milliTimestamp(); if (last_crash) |lc| { if (ts - lc < 500) return; } last_crash = ts; break; }; if (len == 0) break; var i: usize = 0; var evt: *inotify_event = undefined; while (i < buf.len) : (i += @sizeOf(inotify_event) + evt.len) { evt = @as(*inotify_event, @ptrCast(@alignCast(buf[i..]))); const evt_name = @as([*]u8, @ptrCast(buf[i..]))[@sizeOf(inotify_event) .. @sizeOf(inotify_event) + 8]; if (evt.mask & std.os.linux.IN.ISDIR != 0 or !std.mem.startsWith(u8, evt_name, "pcm")) continue; scan = true; } } } if (scan) { watcher.deviceChangeFn(ctx.watcher.?.user_data); scan = false; } } } pub fn refresh(ctx: *Context) !void { for (ctx.devices_info.list.items) |d| freeDevice(ctx.allocator, d); ctx.devices_info.clear(); var pcm_info: ?*c.snd_pcm_info_t = null; _ = lib.snd_pcm_info_malloc(&pcm_info); defer lib.snd_pcm_info_free(pcm_info); var card_idx: c_int = -1; if (lib.snd_card_next(&card_idx) < 0) return error.SystemResources; while (card_idx >= 0) { var card_id_buf: [8]u8 = undefined; const card_id = std.fmt.bufPrintZ(&card_id_buf, "hw:{d}", .{card_idx}) catch break; var ctl: ?*c.snd_ctl_t = undefined; _ = switch (-lib.snd_ctl_open(&ctl, card_id.ptr, 0)) { 0 => {}, @intFromEnum(std.posix.E.NOENT) => break, else => return error.OpeningDevice, }; defer _ = lib.snd_ctl_close(ctl); var dev_idx: c_int = -1; if (lib.snd_ctl_pcm_next_device(ctl, &dev_idx) < 0) return error.SystemResources; lib.snd_pcm_info_set_device(pcm_info, @as(c_uint, @intCast(dev_idx))); lib.snd_pcm_info_set_subdevice(pcm_info, 0); const name = std.mem.span(lib.snd_pcm_info_get_name(pcm_info) orelse continue); for (&[_]main.Device.Mode{ .playback, .capture }) |mode| { const snd_stream = modeToStream(mode); lib.snd_pcm_info_set_stream(pcm_info, snd_stream); const err = lib.snd_ctl_pcm_info(ctl, pcm_info); switch (@as(std.posix.E, @enumFromInt(-err))) { .SUCCESS => {}, .NOENT, .NXIO, .NODEV, => break, else => return error.SystemResources, } var buf: [9]u8 = undefined; // 'hw' + max(card|device) * 2 + ':' + \0 const id = std.fmt.bufPrintZ(&buf, "hw:{d},{d}", .{ card_idx, dev_idx }) catch continue; var pcm: ?*c.snd_pcm_t = null; if (lib.snd_pcm_open(&pcm, id.ptr, snd_stream, 0) < 0) continue; defer _ = lib.snd_pcm_close(pcm); var params: ?*c.snd_pcm_hw_params_t = null; _ = lib.snd_pcm_hw_params_malloc(&params); defer lib.snd_pcm_hw_params_free(params); if (lib.snd_pcm_hw_params_any(pcm, params) < 0) continue; if (lib.snd_pcm_hw_params_can_pause(params) == 0) continue; const device = main.Device{ .mode = mode, .channels = blk: { const chmap = lib.snd_pcm_query_chmaps(pcm); if (chmap) |_| { defer lib.snd_pcm_free_chmaps(chmap); if (chmap[0] == null) continue; const channels = try ctx.allocator.alloc(main.ChannelPosition, chmap.*.*.map.channels); for (channels, 0..) |*ch, i| ch.* = fromAlsaChannel(chmap[0][0].map.pos()[i]) catch return error.OpeningDevice; break :blk channels; } else { continue; } }, .formats = blk: { var fmt_mask: ?*c.snd_pcm_format_mask_t = null; _ = lib.snd_pcm_format_mask_malloc(&fmt_mask); defer lib.snd_pcm_format_mask_free(fmt_mask); lib.snd_pcm_format_mask_none(fmt_mask); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S8); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U8); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S16_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S16_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U16_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U16_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S24_3LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S24_3BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U24_3LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U24_3BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S24_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S24_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U24_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U24_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S32_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_S32_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U32_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_U32_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_FLOAT_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_FLOAT_BE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_FLOAT64_LE); lib.snd_pcm_format_mask_set(fmt_mask, c.SND_PCM_FORMAT_FLOAT64_BE); lib.snd_pcm_hw_params_get_format_mask(params, fmt_mask); var fmt_arr = std.ArrayList(main.Format).init(ctx.allocator); inline for (std.meta.tags(main.Format)) |format| { if (lib.snd_pcm_format_mask_test(fmt_mask, toAlsaFormat(format)) != 0) { try fmt_arr.append(format); } } break :blk try fmt_arr.toOwnedSlice(); }, .sample_rate = blk: { var rate_min: c_uint = 0; var rate_max: c_uint = 0; if (lib.snd_pcm_hw_params_get_rate_min(params, &rate_min, null) < 0) continue; if (lib.snd_pcm_hw_params_get_rate_max(params, &rate_max, null) < 0) continue; break :blk .{ .min = @as(u24, @intCast(rate_min)), .max = @as(u24, @intCast(rate_max)), }; }, .id = try ctx.allocator.dupeZ(u8, id), .name = try ctx.allocator.dupeZ(u8, name), }; try ctx.devices_info.list.append(ctx.allocator, device); if (ctx.devices_info.default(mode) == null and dev_idx == 0) { ctx.devices_info.setDefault(mode, ctx.devices_info.list.items.len - 1); } } if (lib.snd_card_next(&card_idx) < 0) return error.SystemResources; } } pub fn devices(ctx: Context) []const main.Device { return ctx.devices_info.list.items; } pub fn defaultDevice(ctx: Context, mode: main.Device.Mode) ?main.Device { return ctx.devices_info.default(mode); } pub fn createStream( ctx: Context, device: main.Device, format: main.Format, sample_rate: u24, pcm: *?*c.snd_pcm_t, mixer: *?*c.snd_mixer_t, selem: *?*c.snd_mixer_selem_id_t, mixer_elm: *?*c.snd_mixer_elem_t, period_size: *c_ulong, ) !void { if (lib.snd_pcm_open(pcm, device.id.ptr, modeToStream(device.mode), 0) < 0) return error.OpeningDevice; errdefer _ = lib.snd_pcm_close(pcm.*); { var hw_params: ?*c.snd_pcm_hw_params_t = null; if ((lib.snd_pcm_set_params( pcm.*, toAlsaFormat(format), c.SND_PCM_ACCESS_RW_INTERLEAVED, @as(c_uint, @intCast(device.channels.len)), sample_rate, 1, main.default_latency, )) < 0) return error.OpeningDevice; errdefer _ = lib.snd_pcm_hw_free(pcm.*); if (lib.snd_pcm_hw_params_malloc(&hw_params) < 0) return error.OpeningDevice; defer lib.snd_pcm_hw_params_free(hw_params); if (lib.snd_pcm_hw_params_current(pcm.*, hw_params) < 0) return error.OpeningDevice; if (lib.snd_pcm_hw_params_get_period_size(hw_params, period_size, null) < 0) return error.OpeningDevice; } { if (lib.snd_mixer_open(mixer, 0) < 0) return error.OutOfMemory; const card_id = try ctx.allocator.dupeZ(u8, std.mem.sliceTo(device.id, ',')); defer ctx.allocator.free(card_id); if (lib.snd_mixer_attach(mixer.*, card_id.ptr) < 0) return error.IncompatibleDevice; if (lib.snd_mixer_selem_register(mixer.*, null, null) < 0) return error.OpeningDevice; if (lib.snd_mixer_load(mixer.*) < 0) return error.OpeningDevice; if (lib.snd_mixer_selem_id_malloc(selem) < 0) return error.OutOfMemory; errdefer lib.snd_mixer_selem_id_free(selem.*); lib.snd_mixer_selem_id_set_index(selem.*, 0); lib.snd_mixer_selem_id_set_name(selem.*, "Master"); mixer_elm.* = lib.snd_mixer_find_selem(mixer.*, selem.*) orelse return error.IncompatibleDevice; } } pub fn createPlayer(ctx: Context, device: main.Device, writeFn: main.WriteFn, options: main.StreamOptions) !backends.Player { const format = device.preferredFormat(options.format); const sample_rate = device.sample_rate.clamp(options.sample_rate orelse default_sample_rate); var pcm: ?*c.snd_pcm_t = null; var mixer: ?*c.snd_mixer_t = null; var selem: ?*c.snd_mixer_selem_id_t = null; var mixer_elm: ?*c.snd_mixer_elem_t = null; var period_size: c_ulong = 0; try ctx.createStream(device, format, sample_rate, &pcm, &mixer, &selem, &mixer_elm, &period_size); const player = try ctx.allocator.create(Player); player.* = .{ .allocator = ctx.allocator, .thread = undefined, .aborted = .{ .raw = false }, .sample_buffer = try ctx.allocator.alloc(u8, period_size * format.frameSize(@intCast(device.channels.len))), .period_size = period_size, .pcm = pcm.?, .mixer = mixer.?, .selem = selem.?, .mixer_elm = mixer_elm.?, .writeFn = writeFn, .user_data = options.user_data, .channels = device.channels, .format = format, .sample_rate = sample_rate, }; return .{ .alsa = player }; } pub fn createRecorder(ctx: *Context, device: main.Device, readFn: main.ReadFn, options: main.StreamOptions) !backends.Recorder { const format = device.preferredFormat(options.format); const sample_rate = device.sample_rate.clamp(options.sample_rate orelse default_sample_rate); var pcm: ?*c.snd_pcm_t = null; var mixer: ?*c.snd_mixer_t = null; var selem: ?*c.snd_mixer_selem_id_t = null; var mixer_elm: ?*c.snd_mixer_elem_t = null; var period_size: c_ulong = 0; try ctx.createStream(device, format, sample_rate, &pcm, &mixer, &selem, &mixer_elm, &period_size); const recorder = try ctx.allocator.create(Recorder); recorder.* = .{ .allocator = ctx.allocator, .thread = undefined, .aborted = .{ .raw = false }, .sample_buffer = try ctx.allocator.alloc(u8, period_size * format.frameSize(@intCast(device.channels.len))), .period_size = period_size, .pcm = pcm.?, .mixer = mixer.?, .selem = selem.?, .mixer_elm = mixer_elm.?, .readFn = readFn, .user_data = options.user_data, .channels = device.channels, .format = format, .sample_rate = sample_rate, }; return .{ .alsa = recorder }; } }; pub const Player = struct { allocator: std.mem.Allocator, thread: std.Thread, aborted: std.atomic.Value(bool), sample_buffer: []u8, period_size: c_ulong, pcm: *c.snd_pcm_t, mixer: *c.snd_mixer_t, selem: *c.snd_mixer_selem_id_t, mixer_elm: *c.snd_mixer_elem_t, writeFn: main.WriteFn, user_data: ?*anyopaque, channels: []main.ChannelPosition, format: main.Format, sample_rate: u24, pub fn deinit(player: *Player) void { player.aborted.store(true, .unordered); player.thread.join(); _ = lib.snd_mixer_close(player.mixer); lib.snd_mixer_selem_id_free(player.selem); _ = lib.snd_pcm_close(player.pcm); _ = lib.snd_pcm_hw_free(player.pcm); player.allocator.free(player.sample_buffer); player.allocator.destroy(player); } pub fn start(player: *Player) !void { player.thread = std.Thread.spawn(.{}, writeThread, .{player}) catch |err| switch (err) { error.ThreadQuotaExceeded, error.SystemResources, error.LockedMemoryLimitExceeded, => return error.SystemResources, error.OutOfMemory => return error.OutOfMemory, error.Unexpected => unreachable, }; } fn writeThread(player: *Player) void { var underrun = false; while (!player.aborted.load(.unordered)) { if (!underrun) { player.writeFn( player.user_data, player.sample_buffer[0 .. player.period_size * player.format.frameSize(@intCast(player.channels.len))], ); } underrun = false; const n = lib.snd_pcm_writei(player.pcm, player.sample_buffer.ptr, player.period_size); if (n < 0) { _ = lib.snd_pcm_prepare(player.pcm); underrun = true; } } } pub fn play(player: *Player) !void { if (lib.snd_pcm_state(player.pcm) == c.SND_PCM_STATE_PAUSED) { if (lib.snd_pcm_pause(player.pcm, 0) < 0) return error.CannotPlay; } } pub fn pause(player: *Player) !void { if (lib.snd_pcm_state(player.pcm) != c.SND_PCM_STATE_PAUSED) { if (lib.snd_pcm_pause(player.pcm, 1) < 0) return error.CannotPause; } } pub fn paused(player: *Player) bool { return lib.snd_pcm_state(player.pcm) == c.SND_PCM_STATE_PAUSED; } pub fn setVolume(player: *Player, vol: f32) !void { var min_vol: c_long = 0; var max_vol: c_long = 0; if (lib.snd_mixer_selem_get_playback_volume_range(player.mixer_elm, &min_vol, &max_vol) < 0) return error.CannotSetVolume; const dist = @as(f32, @floatFromInt(max_vol - min_vol)); if (lib.snd_mixer_selem_set_playback_volume_all( player.mixer_elm, @as(c_long, @intFromFloat(dist * vol)) + min_vol, ) < 0) return error.CannotSetVolume; } pub fn volume(player: *Player) !f32 { var vol: c_long = 0; var channel: c_int = 0; while (channel < c.SND_MIXER_SCHN_LAST) : (channel += 1) { if (lib.snd_mixer_selem_has_playback_channel(player.mixer_elm, channel) == 1) { if (lib.snd_mixer_selem_get_playback_volume(player.mixer_elm, channel, &vol) == 0) break; } } if (channel == c.SND_MIXER_SCHN_LAST) return error.CannotGetVolume; var min_vol: c_long = 0; var max_vol: c_long = 0; if (lib.snd_mixer_selem_get_playback_volume_range(player.mixer_elm, &min_vol, &max_vol) < 0) return error.CannotGetVolume; return @as(f32, @floatFromInt(vol)) / @as(f32, @floatFromInt(max_vol - min_vol)); } }; pub const Recorder = struct { allocator: std.mem.Allocator, thread: std.Thread, aborted: std.atomic.Value(bool), sample_buffer: []u8, period_size: c_ulong, pcm: *c.snd_pcm_t, mixer: *c.snd_mixer_t, selem: *c.snd_mixer_selem_id_t, mixer_elm: *c.snd_mixer_elem_t, readFn: main.ReadFn, user_data: ?*anyopaque, channels: []main.ChannelPosition, format: main.Format, sample_rate: u24, pub fn deinit(recorder: *Recorder) void { recorder.aborted.store(true, .unordered); recorder.thread.join(); _ = lib.snd_mixer_close(recorder.mixer); lib.snd_mixer_selem_id_free(recorder.selem); _ = lib.snd_pcm_close(recorder.pcm); _ = lib.snd_pcm_hw_free(recorder.pcm); recorder.allocator.free(recorder.sample_buffer); recorder.allocator.destroy(recorder); } pub fn start(recorder: *Recorder) !void { recorder.thread = std.Thread.spawn(.{}, readThread, .{recorder}) catch |err| switch (err) { error.ThreadQuotaExceeded, error.SystemResources, error.LockedMemoryLimitExceeded, => return error.SystemResources, error.OutOfMemory => return error.OutOfMemory, error.Unexpected => unreachable, }; } fn readThread(recorder: *Recorder) void { var underrun = false; while (!recorder.aborted.load(.unordered)) { if (!underrun) { recorder.readFn(recorder.user_data, recorder.sample_buffer[0..recorder.period_size]); } underrun = false; const n = lib.snd_pcm_readi(recorder.pcm, recorder.sample_buffer.ptr, recorder.period_size); if (n < 0) { _ = lib.snd_pcm_prepare(recorder.pcm); underrun = true; } } } pub fn record(recorder: *Recorder) !void { if (lib.snd_pcm_state(recorder.pcm) == c.SND_PCM_STATE_PAUSED) { if (lib.snd_pcm_pause(recorder.pcm, 0) < 0) return error.CannotRecord; } } pub fn pause(recorder: *Recorder) !void { if (lib.snd_pcm_state(recorder.pcm) != c.SND_PCM_STATE_PAUSED) { if (lib.snd_pcm_pause(recorder.pcm, 1) < 0) return error.CannotPause; } } pub fn paused(recorder: *Recorder) bool { return lib.snd_pcm_state(recorder.pcm) == c.SND_PCM_STATE_PAUSED; } pub fn setVolume(recorder: *Recorder, vol: f32) !void { var min_vol: c_long = 0; var max_vol: c_long = 0; if (lib.snd_mixer_selem_get_capture_volume_range(recorder.mixer_elm, &min_vol, &max_vol) < 0) return error.CannotSetVolume; const dist = @as(f32, @floatFromInt(max_vol - min_vol)); if (lib.snd_mixer_selem_set_capture_volume_all( recorder.mixer_elm, @as(c_long, @intFromFloat(dist * vol)) + min_vol, ) < 0) return error.CannotSetVolume; } pub fn volume(recorder: *Recorder) !f32 { var vol: c_long = 0; var channel: c_int = 0; while (channel < c.SND_MIXER_SCHN_LAST) : (channel += 1) { if (lib.snd_mixer_selem_has_capture_channel(recorder.mixer_elm, channel) == 1) { if (lib.snd_mixer_selem_get_capture_volume(recorder.mixer_elm, channel, &vol) == 0) break; } } if (channel == c.SND_MIXER_SCHN_LAST) return error.CannotGetVolume; var min_vol: c_long = 0; var max_vol: c_long = 0; if (lib.snd_mixer_selem_get_capture_volume_range(recorder.mixer_elm, &min_vol, &max_vol) < 0) return error.CannotGetVolume; return @as(f32, @floatFromInt(vol)) / @as(f32, @floatFromInt(max_vol - min_vol)); } }; fn freeDevice(allocator: std.mem.Allocator, device: main.Device) void { allocator.free(device.id); allocator.free(device.name); allocator.free(device.formats); allocator.free(device.channels); } pub fn modeToStream(mode: main.Device.Mode) c_uint { return switch (mode) { .playback => c.SND_PCM_STREAM_PLAYBACK, .capture => c.SND_PCM_STREAM_CAPTURE, }; } pub fn toAlsaFormat(format: main.Format) c.snd_pcm_format_t { return switch (format) { .u8 => c.SND_PCM_FORMAT_U8, .i16 => if (is_little) c.SND_PCM_FORMAT_S16_LE else c.SND_PCM_FORMAT_S16_BE, .i24 => if (is_little) c.SND_PCM_FORMAT_S24_3LE else c.SND_PCM_FORMAT_S24_3BE, .i32 => if (is_little) c.SND_PCM_FORMAT_S32_LE else c.SND_PCM_FORMAT_S32_BE, .f32 => if (is_little) c.SND_PCM_FORMAT_FLOAT_LE else c.SND_PCM_FORMAT_FLOAT_BE, }; } pub fn fromAlsaChannel(pos: c_uint) !main.ChannelPosition { return switch (pos) { c.SND_CHMAP_UNKNOWN, c.SND_CHMAP_NA => return error.Invalid, c.SND_CHMAP_MONO, c.SND_CHMAP_FC => .front_center, c.SND_CHMAP_FL => .front_left, c.SND_CHMAP_FR => .front_right, c.SND_CHMAP_LFE => .lfe, c.SND_CHMAP_SL => .side_left, c.SND_CHMAP_SR => .side_right, c.SND_CHMAP_RC => .back_center, c.SND_CHMAP_RLC => .back_left, c.SND_CHMAP_RRC => .back_right, c.SND_CHMAP_FLC => .front_left_center, c.SND_CHMAP_FRC => .front_right_center, c.SND_CHMAP_TC => .top_center, c.SND_CHMAP_TFL => .top_front_left, c.SND_CHMAP_TFR => .top_front_right, c.SND_CHMAP_TFC => .top_front_center, c.SND_CHMAP_TRL => .top_back_left, c.SND_CHMAP_TRR => .top_back_right, c.SND_CHMAP_TRC => .top_back_center, else => return error.Invalid, }; } pub fn toCHMAP(pos: main.ChannelPosition) c_uint { return switch (pos) { .front_center => c.SND_CHMAP_FC, .front_left => c.SND_CHMAP_FL, .front_right => c.SND_CHMAP_FR, .lfe => c.SND_CHMAP_LFE, .side_left => c.SND_CHMAP_SL, .side_right => c.SND_CHMAP_SR, .back_center => c.SND_CHMAP_RC, .back_left => c.SND_CHMAP_RLC, .back_right => c.SND_CHMAP_RRC, .front_left_center => c.SND_CHMAP_FLC, .front_right_center => c.SND_CHMAP_FRC, .top_center => c.SND_CHMAP_TC, .top_front_left => c.SND_CHMAP_TFL, .top_front_right => c.SND_CHMAP_TFR, .top_front_center => c.SND_CHMAP_TFC, .top_back_left => c.SND_CHMAP_TRL, .top_back_right => c.SND_CHMAP_TRR, .top_back_center => c.SND_CHMAP_TRC, }; }
https://raw.githubusercontent.com/hexops/mach/b72f0e11b6d292c2b60789359a61f7ee6d7dc371/src/sysaudio/alsa.zig
const std = @import("std"); // support zig 0.11 as well as current master pub usingnamespace if (@hasField(std.meta, "trait")) std.meta.trait else struct { const TraitFn = fn (type) bool; pub fn isNumber(comptime T: type) bool { return switch (@typeInfo(T)) { .Int, .Float, .ComptimeInt, .ComptimeFloat => true, else => false, }; } pub fn isContainer(comptime T: type) bool { return switch (@typeInfo(T)) { .Struct, .Union, .Enum, .Opaque => true, else => false, }; } pub fn is(comptime id: std.builtin.TypeId) TraitFn { const Closure = struct { pub fn trait(comptime T: type) bool { return id == @typeInfo(T); } }; return Closure.trait; } pub fn isPtrTo(comptime id: std.builtin.TypeId) TraitFn { const Closure = struct { pub fn trait(comptime T: type) bool { if (!comptime isSingleItemPtr(T)) return false; return id == @typeInfo(std.meta.Child(T)); } }; return Closure.trait; } pub fn isSingleItemPtr(comptime T: type) bool { if (comptime is(.Pointer)(T)) { return @typeInfo(T).Pointer.size == .One; } return false; } pub fn isIntegral(comptime T: type) bool { return switch (@typeInfo(T)) { .Int, .ComptimeInt => true, else => false, }; } pub fn isZigString(comptime T: type) bool { return comptime blk: { // Only pointer types can be strings, no optionals const info = @typeInfo(T); if (info != .Pointer) break :blk false; const ptr = &info.Pointer; // Check for CV qualifiers that would prevent coerction to []const u8 if (ptr.is_volatile or ptr.is_allowzero) break :blk false; // If it's already a slice, simple check. if (ptr.size == .Slice) { break :blk ptr.child == u8; } // Otherwise check if it's an array type that coerces to slice. if (ptr.size == .One) { const child = @typeInfo(ptr.child); if (child == .Array) { const arr = &child.Array; break :blk arr.child == u8; } } break :blk false; }; } pub fn hasUniqueRepresentation(comptime T: type) bool { switch (@typeInfo(T)) { else => return false, // TODO can we know if it's true for some of these types ? .AnyFrame, .Enum, .ErrorSet, .Fn, => return true, .Bool => return false, .Int => |info| return @sizeOf(T) * 8 == info.bits, .Pointer => |info| return info.size != .Slice, .Array => |info| return comptime hasUniqueRepresentation(info.child), .Struct => |info| { var sum_size = @as(usize, 0); inline for (info.fields) |field| { const FieldType = field.type; if (comptime !hasUniqueRepresentation(FieldType)) return false; sum_size += @sizeOf(FieldType); } return @sizeOf(T) == sum_size; }, .Vector => |info| return comptime hasUniqueRepresentation(info.child) and @sizeOf(T) == @sizeOf(info.child) * info.len, } } };
https://raw.githubusercontent.com/capy-ui/capy/0f714f8317f69e283a1cdf49f2f39bdfdd88ec95/src/trait.zig
const math = @import("std").math; pub fn binarySearch(comptime T: type, input: []const T, search_value: T) ?usize { if (input.len == 0) return null; if (@sizeOf(T) == 0) return 0; var low: usize = 0; var high: usize = input.len - 1; return while (low <= high) { const mid = ((high - low) / 2) + low; const mid_elem: T = input[mid]; if (mid_elem > search_value) high = math.sub(usize, mid, 1) catch break null else if (mid_elem < search_value) low = mid + 1 else break mid; } else null; }
https://raw.githubusercontent.com/acmeism/RosettaCodeData/29a5eea0d45a07fe7f50994dd8a253eef2c26d51/Task/Binary-search/Zig/binary-search-3.zig
const std = @import("std"); const python = @cImport(@cInclude("Python.h")); // wasmGetSignalState has to be defined at the typescript level, since it potentially // reads from a small SharedArrayBuffer that WASM does not have access to. It returns // any pending signal. extern fn wasmGetSignalState() i32; export fn _Py_CheckEmscriptenSignals() void { const signal = wasmGetSignalState(); // std.debug.print("python-wasm: _Py_CheckEmscriptenSignals: signal={}\n", .{signal}); if (signal != 0) { // std.debug.print("_Py_CheckEmscriptenSignals: got a signal! {}\n", .{signal}); if (python.PyErr_SetInterruptEx(signal) != 0) { std.debug.print("_Py_CheckEmscriptenSignals: ERROR -- invalid signal = {}\n", .{signal}); } } } // Upstream uses 50 for analogue of SIGNAL_INTERVAL (see Python/emscripten_signal.c in the cpython sources). // However, this may or may not be called frequently, so not checking more could be a problem. It would // make a lot more sense to space these out with a high performance system clock... but of course access to // that is at least as expensive as wasmGetSignalState, so there's no point. const SIGNAL_INTERVAL: i32 = 50; var signal_counter: i32 = SIGNAL_INTERVAL; export fn _Py_CheckEmscriptenSignalsPeriodically() void { // std.debug.print("python-wasm: _Py_CheckEmscriptenSignalsPeriodically\n", .{}); signal_counter -= 1; if (signal_counter <= 0) { signal_counter = SIGNAL_INTERVAL; _Py_CheckEmscriptenSignals(); } } pub fn keepalive() void {}
https://raw.githubusercontent.com/sagemathinc/cowasm/e8bba5584f03937611619934f0d5858e4d03853d/python/python-wasm/src/signal.zig
const macro = @import("pspmacros.zig"); comptime { asm (macro.import_module_start("sceAudio", "0x40010000", "27")); asm (macro.import_function("sceAudio", "0x8C1009B2", "sceAudioOutput")); asm (macro.import_function("sceAudio", "0x136CAF51", "sceAudioOutputBlocking")); asm (macro.import_function("sceAudio", "0xE2D56B2D", "sceAudioOutputPanned")); asm (macro.import_function("sceAudio", "0x13F592BC", "sceAudioOutputPannedBlocking")); asm (macro.import_function("sceAudio", "0x5EC81C55", "sceAudioChReserve")); asm (macro.import_function("sceAudio", "0x41EFADE7", "sceAudioOneshotOutput")); asm (macro.import_function("sceAudio", "0x6FC46853", "sceAudioChRelease")); asm (macro.import_function("sceAudio", "0xE9D97901", "sceAudioGetChannelRestLen")); asm (macro.import_function("sceAudio", "0xCB2E439E", "sceAudioSetChannelDataLen")); asm (macro.import_function("sceAudio", "0x95FD0C2D", "sceAudioChangeChannelConfig")); asm (macro.import_function("sceAudio", "0xB7E1D8E7", "sceAudioChangeChannelVolume")); asm (macro.import_function("sceAudio", "0x38553111", "sceAudioSRCChReserve")); asm (macro.import_function("sceAudio", "0x5C37C0AE", "sceAudioSRCChRelease")); asm (macro.import_function("sceAudio", "0xE0727056", "sceAudioSRCOutputBlocking")); asm (macro.import_function("sceAudio", "0x086E5895", "sceAudioInputBlocking")); asm (macro.import_function("sceAudio", "0x6D4BEC68", "sceAudioInput")); asm (macro.import_function("sceAudio", "0xA708C6A6", "sceAudioGetInputLength")); asm (macro.import_function("sceAudio", "0x87B2E651", "sceAudioWaitInputEnd")); asm (macro.import_function("sceAudio", "0x7DE61688", "sceAudioInputInit")); asm (macro.import_function("sceAudio", "0xA633048E", "sceAudioPollInputEnd")); asm (macro.import_function("sceAudio", "0xB011922F", "sceAudioGetChannelRestLength")); asm (macro.import_function("sceAudio", "0xE926D3FB", "sceAudioInputInitEx")); asm (macro.import_function("sceAudio", "0x01562BA3", "sceAudioOutput2Reserve")); asm (macro.import_function("sceAudio", "0x2D53F36E", "sceAudioOutput2OutputBlocking")); asm (macro.import_function("sceAudio", "0x43196845", "sceAudioOutput2Release")); asm (macro.import_function("sceAudio", "0x63F2889C", "sceAudioOutput2ChangeLength")); asm (macro.import_function("sceAudio", "0x647CEF33", "sceAudioOutput2GetRestSample")); }
https://raw.githubusercontent.com/zPSP-Dev/Zig-PSP/53edbc71ed6b0339e7d7a06c9d84794eea2288dd/src/psp/nids/pspaudio.zig
//HSLuv-C: Human-friendly HSL //<https://github.com/hsluv/hsluv-c> //<https://www.hsluv.org/> // //Copyright (c) 2015 Alexei Boronine (original idea, JavaScript implementation) //Copyright (c) 2015 Roger Tallada (Obj-C implementation) //Copyright (c) 2017 Martin Mitáš (C implementation, based on Obj-C implementation) //Copyright (c) 2024 David Vanderson (Zig implementation, based on C implementation) // //Permission is hereby granted, free of charge, to any person obtaining a //copy of this software and associated documentation files (the "Software"), //to deal in the Software without restriction, including without limitation //the rights to use, copy, modify, merge, publish, distribute, sublicense, //and/or sell copies of the Software, and to permit persons to whom the //Software is furnished to do so, subject to the following conditions: // //The above copyright notice and this permission notice shall be included in //all copies or substantial portions of the Software. // //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING //FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS //IN THE SOFTWARE. const std = @import("std"); pub const Triplet = struct { a: f32, b: f32, c: f32, }; // zig fmt: off // for RGB const m: [3]Triplet = [_]Triplet{ .{ .a = 3.24096994190452134377, .b = -1.53738317757009345794, .c = -0.49861076029300328366 }, .{ .a = -0.96924363628087982613, .b = 1.87596750150772066772, .c = 0.04155505740717561247 }, .{ .a = 0.05563007969699360846, .b = -0.20397695888897656435, .c = 1.05697151424287856072 } }; // for XYZ const m_inv: [3]Triplet = [_]Triplet{ .{ .a = 0.41239079926595948129, .b = 0.35758433938387796373, .c = 0.18048078840183428751 }, .{ .a = 0.21263900587151035754, .b = 0.71516867876775592746, .c = 0.07219231536073371500 }, .{ .a = 0.01933081871559185069, .b = 0.11919477979462598791, .c = 0.95053215224966058086 } }; // zig fmt: on const ref_u = 0.19783000664283680764; const ref_v = 0.46831999493879100370; const kappa = 903.29629629629629629630; const epsilon = 0.00885645167903563082; const Bounds = struct { a: f32, b: f32, }; fn get_bounds(l: f32, bounds: *[6]Bounds) void { const tl = l + 16.0; const sub1 = (tl * tl * tl) / 1560896.0; const sub2 = if (sub1 > epsilon) sub1 else (l / kappa); for (0..3) |channel| { const m1 = m[channel].a; const m2 = m[channel].b; const m3 = m[channel].c; for (0..2) |t| { const top1 = (284517.0 * m1 - 94839.0 * m3) * sub2; const top2 = (838422.0 * m3 + 769860.0 * m2 + 731718.0 * m1) * l * sub2 - 769860.0 * @as(f32, @floatFromInt(t)) * l; const bottom = (632260.0 * m3 - 126452.0 * m2) * sub2 + 126452.0 * @as(f32, @floatFromInt(t)); bounds[channel * 2 + t].a = top1 / bottom; bounds[channel * 2 + t].b = top2 / bottom; } } } fn intersect_line_line(line1: Bounds, line2: Bounds) f32 { return (line1.b - line2.b) / (line2.a - line1.a); } fn dist_from_pole_squared(x: f32, y: f32) f32 { return x * x + y * y; } fn ray_length_until_intersect(theta: f32, line: Bounds) f32 { return line.b / (@sin(theta) - line.a * @cos(theta)); } fn max_safe_chroma_for_l(l: f32) f32 { var min_len_squared: f32 = std.math.floatMax(f32); var bounds: [6]Bounds = undefined; get_bounds(l, &bounds); for (0..6) |i| { const m1 = bounds[i].a; const b1 = bounds[i].b; // x where line intersects with perpendicular running though (0, 0) const line2 = Bounds{ .a = -1.0 / m1, .b = 0.0 }; const x = intersect_line_line(bounds[i], line2); const distance = dist_from_pole_squared(x, b1 + x * m1); if (distance < min_len_squared) min_len_squared = distance; } return @sqrt(min_len_squared); } fn max_chroma_for_lh(l: f32, h: f32) f32 { var min_len: f32 = std.math.floatMax(f32); const hrad = h * 0.01745329251994329577; // (2 * pi / 360) var bounds: [6]Bounds = undefined; get_bounds(l, &bounds); for (0..6) |i| { const len = ray_length_until_intersect(hrad, bounds[i]); if (len >= 0 and len < min_len) min_len = len; } return min_len; } fn dot_product(t1: Triplet, t2: Triplet) f32 { return (t1.a * t2.a + t1.b * t2.b + t1.c * t2.c); } // Used for rgb conversions fn from_linear(c: f32) f32 { if (c <= 0.0031308) { return 12.92 * c; } else { return 1.055 * std.math.pow(f32, c, 1.0 / 2.4) - 0.055; } } fn to_linear(c: f32) f32 { if (c > 0.04045) { return std.math.pow(f32, (c + 0.055) / 1.055, 2.4); } else { return c / 12.92; } } pub fn xyz2rgb(in_out: *Triplet) void { const r = from_linear(dot_product(m[0], in_out.*)); const g = from_linear(dot_product(m[1], in_out.*)); const b = from_linear(dot_product(m[2], in_out.*)); in_out.a = r; in_out.b = g; in_out.c = b; } pub fn rgb2xyz(in_out: *Triplet) void { const rgbl: Triplet = .{ .a = to_linear(in_out.a), .b = to_linear(in_out.b), .c = to_linear(in_out.c) }; const x = dot_product(m_inv[0], rgbl); const y = dot_product(m_inv[1], rgbl); const z = dot_product(m_inv[2], rgbl); in_out.a = x; in_out.b = y; in_out.c = z; } // https://en.wikipedia.org/wiki/CIELUV // In these formulas, Yn refers to the reference white point. We are using // illuminant D65, so Yn (see refY in Maxima file) equals 1. The formula is // simplified accordingly. fn y2l(y: f32) f32 { if (y <= epsilon) { return y * kappa; } else { return 116.0 * std.math.cbrt(y) - 16.0; } } fn l2y(l: f32) f32 { if (l <= 8.0) { return l / kappa; } else { const x = (l + 16.0) / 116.0; return (x * x * x); } } pub fn xyz2luv(in_out: *Triplet) void { const var_u = (4.0 * in_out.a) / (in_out.a + (15.0 * in_out.b) + (3.0 * in_out.c)); const var_v = (9.0 * in_out.b) / (in_out.a + (15.0 * in_out.b) + (3.0 * in_out.c)); const l = y2l(in_out.b); const u = 13.0 * l * (var_u - ref_u); const v = 13.0 * l * (var_v - ref_v); in_out.a = l; if (l < 0.00001) { in_out.b = 0.0; in_out.c = 0.0; } else { in_out.b = u; in_out.c = v; } } pub fn luv2xyz(in_out: *Triplet) void { if (in_out.a <= 0.00001) { // Black will create a divide-by-zero error. in_out.a = 0.0; in_out.b = 0.0; in_out.c = 0.0; return; } const var_u = in_out.b / (13.0 * in_out.a) + ref_u; const var_v = in_out.c / (13.0 * in_out.a) + ref_v; const y = l2y(in_out.a); const x = -(9.0 * y * var_u) / ((var_u - 4.0) * var_v - var_u * var_v); const z = (9.0 * y - (15.0 * var_v * y) - (var_v * x)) / (3.0 * var_v); in_out.a = x; in_out.b = y; in_out.c = z; } pub fn luv2lch(in_out: *Triplet) void { const l = in_out.a; const u = in_out.b; const v = in_out.c; var h: f32 = undefined; const c = @sqrt(u * u + v * v); // Grays: disambiguate hue if (c < 0.0001) { h = 0; } else { h = std.math.atan2(v, u) * 57.29577951308232087680; // (180 / pi) if (h < 0.0) h += 360.0; } in_out.a = l; in_out.b = c; in_out.c = h; } pub fn lch2luv(in_out: *Triplet) void { const hrad = in_out.c * 0.01745329251994329577; // (pi / 180.0) const u = @cos(hrad) * in_out.b; const v = @sin(hrad) * in_out.b; in_out.b = u; in_out.c = v; } pub fn hsluv2lch(in_out: *Triplet) void { var h: f32 = in_out.a; const s = in_out.b; const l = in_out.c; var c: f32 = undefined; // White and black: disambiguate chroma if (l > 99.9999 or l < 0.00001) { c = 0.0; } else { c = max_chroma_for_lh(l, h) / 100.0 * s; } // Grays: disambiguate hue if (s < 0.00001) h = 0.0; in_out.a = l; in_out.b = c; in_out.c = h; } pub fn lch2hsluv(in_out: *Triplet) void { const l = in_out.a; const c = in_out.b; var h: f32 = in_out.c; var s: f32 = undefined; // White and black: disambiguate saturation if (l > 99.9999 or l < 0.00001) { s = 0.0; } else { s = c / max_chroma_for_lh(l, h) * 100.0; } // Grays: disambiguate hue if (c < 0.00001) { h = 0.0; } in_out.a = h; in_out.b = s; in_out.c = l; } pub fn hpluv2lch(in_out: *Triplet) void { var h: f32 = in_out.a; const s = in_out.b; const l = in_out.c; var c: f32 = undefined; // White and black: disambiguate chroma if (l > 99.9999 or l < 0.00001) { c = 0.0; } else { c = max_safe_chroma_for_l(l) / 100.0 * s; } // Grays: disambiguate hue if (s < 0.00001) h = 0.0; in_out.a = l; in_out.b = c; in_out.c = h; } pub fn lch2hpluv(in_out: *Triplet) void { const l = in_out.a; const c = in_out.b; var h: f32 = in_out.c; var s: f32 = undefined; // White and black: disambiguate saturation if (l > 99.9999 or l < 0.00001) { s = 0.0; } else { s = c / max_safe_chroma_for_l(l) * 100.0; } // Grays: disambiguate hue if (c < 0.00001) h = 0.0; in_out.a = h; in_out.b = s; in_out.c = l; } pub fn hsluv2rgb(h: f32, s: f32, l: f32, pr: *f32, pg: *f32, pb: *f32) void { var tmp = Triplet{ .a = h, .b = s, .c = l }; hsluv2lch(&tmp); lch2luv(&tmp); luv2xyz(&tmp); xyz2rgb(&tmp); pr.* = std.math.clamp(tmp.a, 0.0, 1.0); pg.* = std.math.clamp(tmp.b, 0.0, 1.0); pb.* = std.math.clamp(tmp.c, 0.0, 1.0); } pub fn hpluv2rgb(h: f32, s: f32, l: f32, pr: *f32, pg: *f32, pb: *f32) void { var tmp = Triplet{ .a = h, .b = s, .c = l }; hpluv2lch(&tmp); lch2luv(&tmp); luv2xyz(&tmp); xyz2rgb(&tmp); pr.* = std.math.clamp(tmp.a, 0.0, 1.0); pg.* = std.math.clamp(tmp.b, 0.0, 1.0); pb.* = std.math.clamp(tmp.c, 0.0, 1.0); } pub fn rgb2hsluv(r: f32, g: f32, b: f32, ph: *f32, ps: *f32, pl: *f32) void { var tmp = Triplet{ .a = r, .b = g, .c = b }; rgb2xyz(&tmp); xyz2luv(&tmp); luv2lch(&tmp); lch2hsluv(&tmp); ph.* = std.math.clamp(tmp.a, 0.0, 360.0); ps.* = std.math.clamp(tmp.b, 0.0, 100.0); pl.* = std.math.clamp(tmp.c, 0.0, 100.0); } pub fn rgb2hpluv(r: f32, g: f32, b: f32, ph: *f32, ps: *f32, pl: *f32) bool { var tmp = Triplet{ .a = r, .b = g, .c = b }; rgb2xyz(&tmp); xyz2luv(&tmp); luv2lch(&tmp); lch2hpluv(&tmp); ph.* = std.math.clamp(tmp.a, 0.0, 360.0); // Do NOT clamp the saturation. Application may want to have an idea // how much off the valid range the given RGB color is. ps.* = tmp.b; pl.* = std.math.clamp(tmp.c, 0.0, 100.0); return if (0.0 <= tmp.b and tmp.b <= 100.0) true else false; }
https://raw.githubusercontent.com/david-vanderson/dvui/8645f753c1b2eb93f1bd795e2d24469f5493b670/src/hsluv.zig
name: []const u8, description: []const u8, type: []const u8, tokens: Tokens, editor: Style, editor_cursor: Style, editor_line_highlight: Style, editor_error: Style, editor_warning: Style, editor_information: Style, editor_hint: Style, editor_match: Style, editor_selection: Style, editor_whitespace: Style, editor_gutter: Style, editor_gutter_active: Style, editor_gutter_modified: Style, editor_gutter_added: Style, editor_gutter_deleted: Style, editor_widget: Style, editor_widget_border: Style, statusbar: Style, statusbar_hover: Style, scrollbar: Style, scrollbar_hover: Style, scrollbar_active: Style, sidebar: Style, panel: Style, input: Style, input_border: Style, input_placeholder: Style, input_option_active: Style, input_option_hover: Style, pub const FontStyle = enum { normal, bold, italic, underline, undercurl, strikethrough }; pub const Style = struct { fg: ?Color = null, bg: ?Color = null, fs: ?FontStyle = null }; pub const Color = u24; pub const Token = struct { id: usize, style: Style }; pub const Tokens = []const Token;
https://raw.githubusercontent.com/neurocyte/flow-themes/15e8cad1619429bf2547a6819b5b999510d5c1e5/src/theme.zig
/// /// TOPPERS/ASP Kernel /// Toyohashi Open Platform for Embedded Real-Time Systems/ /// Advanced Standard Profile Kernel /// /// Copyright (C) 2000-2003 by Embedded and Real-Time Systems Laboratory /// Toyohashi Univ. of Technology, JAPAN /// Copyright (C) 2005-2020 by Embedded and Real-Time Systems Laboratory /// Graduate School of Informatics, Nagoya Univ., JAPAN /// /// 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ /// ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改 /// 変・再配布(以下,利用と呼ぶ)することを無償で許諾する. /// (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作 /// 権表示,この利用条件および下記の無保証規定が,そのままの形でソー /// スコード中に含まれていること. /// (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使 /// 用できる形で再配布する場合には,再配布に伴うドキュメント(利用 /// 者マニュアルなど)に,上記の著作権表示,この利用条件および下記 /// の無保証規定を掲載すること. /// (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使 /// 用できない形で再配布する場合には,次のいずれかの条件を満たすこ /// と. /// (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著 /// 作権表示,この利用条件および下記の無保証規定を掲載すること. /// (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに /// 報告すること. /// (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損 /// 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること. /// また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理 /// 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを /// 免責すること. /// /// 本ソフトウェアは,無保証で提供されているものである.上記著作権者お /// よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的 /// に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ /// アの利用により直接的または間接的に生じたいかなる損害に関しても,そ /// の責任を負わない. /// /// $Id$ /// /// /// タスク管理モジュール /// usingnamespace @import("kernel_impl.zig"); usingnamespace wait; usingnamespace time_event; usingnamespace check; /// /// ターゲット依存のタスク属性 /// const TARGET_TSKATR = decl(ATR, target_impl, "TARGET_TSKATR", 0); /// /// スタックサイズの最小値 /// const TARGET_MIN_STKSZ = decl(usize, target_impl, "TARGET_MIN_STKSZ", 1); /// /// スタックサイズのアライン単位 /// const CHECK_STKSZ_ALIGN = decl(usize, target_impl, "CHECK_STKSZ_ALIGN", 1); /// /// スタック領域のアライン単位(チェック用) /// const CHECK_STACK_ALIGN = decl(usize, target_impl, "CHECK_STACK_ALIGN", 1); /// /// スタック領域のアライン単位(確保用) /// const STACK_ALIGN = decl(usize, target_impl, "STACK_ALIGN", CHECK_STACK_ALIGN); /// /// 優先度の範囲チェック /// pub fn validTaskPri(tskpri: PRI) bool { return TMIN_TPRI <= tskpri and tskpri <= TMAX_TPRI; } /// /// タスクの優先度の内部表現の型 /// pub const TaskPrio = prio_bitmap.PrioType(TNUM_TPRI); /// /// タスク優先度の内部表現・外部表現変換関数 /// pub fn internalTaskPrio(tskpri: PRI) TaskPrio { return @intCast(TaskPrio, tskpri - TMIN_TPRI); } pub fn externalTaskPrio(prio: TaskPrio) PRI { return @intCast(PRI, prio + TMIN_TPRI); } /// /// タスク状態の内部表現 /// /// TCB中のタスク状態のフィールドでは,タスクの状態と,タスクが待ち状 /// 態の時の待ち要因を表す.ただし,実行状態(RUNNING)と実行可能状態 /// (READY)は区別せず,両状態をあわせて実行できる状態(RUNNABLE)と /// して管理する.二重待ち状態は,(TS_WAITING_??? | TS_SUSPENDED)で表 /// す. /// /// タスクが待ち状態(二重待ち状態を含む)の時は,TS_WAITING_???で待 /// ち要因を表す.待ち要因(5ビットで表現される)の上位2ビットで,同 /// 期・通信オブジェクトの待ちキューにつながっているかどうかを表す. /// 同期・通信オブジェクトの待ちキューにつながらないものは上位2ビット /// を00,同期・通信オブジェクトの管理ブロックの共通部分(WOBJCB)の /// 待ちキューにつながるものは10または11,それ以外の待ちキューにつな /// がるものは01とする. /// pub const TS_DORMANT = 0x00; // 休止状態 pub const TS_RUNNABLE = 0x01; // 実行できる状態 pub const TS_SUSPENDED = 0x02; // 強制待ち状態 pub const TS_WAITING_SLP = (0x01 << 2); // 起床待ち pub const TS_WAITING_DLY = (0x02 << 2); // 時間経過待ち pub const TS_WAITING_RDTQ = (0x08 << 2); // データキューからの受信待ち pub const TS_WAITING_RPDQ = (0x09 << 2); // 優先度データキューからの受信待ち pub const TS_WAITING_SEM = (0x10 << 2); // セマフォ資源の獲得待ち pub const TS_WAITING_FLG = (0x11 << 2); // イベントフラグ待ち pub const TS_WAITING_SDTQ = (0x12 << 2); // データキューへの送信待ち pub const TS_WAITING_SPDQ = (0x13 << 2); // 優先度データキューへの送信待ち pub const TS_WAITING_MTX = (0x14 << 2); // ミューテックスのロック待ち pub const TS_WAITING_MPF = (0x15 << 2); // 固定長メモリブロックの獲得待ち pub const TS_WAITING_MASK = (0x1f << 2); // 待ち状態の判別用マスク /// /// タスク状態判別関数 /// /// isDormantはタスクが休止状態であるかどうかを,isRunnableはタスクが /// 実行できる状態であるかどうかを判別する.isWaitingは待ち状態と二重 /// 待ち状態のいずれかであるかどうかを,isSuspendedは強制待ち状態と二 /// 重待ち状態のいずれかであるかどうかを判別する. /// pub fn isDormant(tstat: u8) bool { return tstat == TS_DORMANT; } pub fn isRunnable(tstat: u8) bool { return (tstat & TS_RUNNABLE) != 0; } pub fn isWaiting(tstat: u8) bool { return (tstat & TS_WAITING_MASK) != 0; } pub fn isSuspended(tstat: u8) bool { return (tstat & TS_SUSPENDED) != 0; } /// /// タスク待ち要因判別関数 /// /// isWaitingSlpはタスクが起床待ちであるかどうかを,isWaitingMtxはタ /// スクがミューテックス待ちであるかどうかを判別する. /// /// また,isWaitingWobjはタスクが同期・通信オブジェクトに対する待ちで /// あるか(言い換えると,同期・通信オブジェクトの待ちキューにつなが /// れているか)どうかを,isWaitingWobjCBはタスクが同期・通信オブジェ /// クトの管理ブロックの共通部分(WOBJCB)の待ちキューにつながれてい /// るかどうかを判別する. /// pub fn isWaitingSlp(tstat: u8) bool { return (tstat & ~@as(u8, TS_SUSPENDED)) == TS_WAITING_SLP; } pub fn isWaitingMtx(tstat: u8) bool { return (tstat & ~@as(u8, TS_SUSPENDED)) == TS_WAITING_MTX; } pub fn isWaitingWobj(tstat: u8) bool { return (tstat & (0x18 << 2)) != 0; } pub fn isWaitingWobjCB(tstat: u8) bool { return (tstat & (0x10 << 2)) != 0; } /// /// タスク初期化ブロック /// /// タスクに関する情報を,値が変わらないためにROMに置ける部分(タスク /// 初期化ブロック)と,値が変化するためにRAMに置かなければならない部 /// 分(タスク管理ブロック,TCB)に分離し,TCB内に対応するタスク初期 /// 化ブロックを指すポインタを入れる.タスク初期化ブロック内に対応す /// るTCBを指すポインタを入れる方法の方が,RAMの節約の観点からは望ま /// しいが,実行効率が悪くなるために採用していない.他のオブジェクト /// についても同様に扱う. /// pub const TINIB = struct { tskatr: ATR, // タスク属性 exinf: EXINF, // タスクの拡張情報 task: TASK, // タスクの起動番地 ipri: c_uint, // タスクの起動時優先度(内部表現) tskinictxb: // タスク初期化コンテキストブロック if (@hasDecl(target_impl, "TSKINICTXB")) target_impl.TSKINICTXB else struct { stksz: usize, // スタック領域のサイズ(丸めた値) stk: [*]u8, // スタック領域 }, }; /// /// タスク管理ブロック(TCB) /// /// ASPカーネルでは,強制待ち要求ネスト数の最大値(TMAX_SUSCNT)が1に /// 固定されているので,強制待ち要求ネスト数(suscnt)は必要ない. /// /// TCBのいくつかのフィールドは,特定のタスク状態でのみ有効な値を保持 /// し,それ以外の場合は値が保証されない(よって,参照してはならない). /// 各フィールドが有効な値を保持する条件は次の通り. /// /// ・初期化後は常に有効: /// p_tinib,tstat,actque, staovr, leftotm /// ・休止状態以外で有効(休止状態では初期値になっている): /// bpriority,priority,wupque,raster,enater,p_lastmtx /// ・待ち状態(二重待ち状態を含む)で有効: /// p_winfo /// ・実行できる状態と同期・通信オブジェクトに対する待ち状態で有効: /// task_queue /// ・実行可能状態,待ち状態,強制待ち状態,二重待ち状態で有効: /// tskctxb /// pub const TCB = struct { task_queue: queue.Queue, // タスクキュー p_tinib: *const TINIB, // 初期化ブロックへのポインタ tstat: u8, // タスク状態(内部表現) bprio: TaskPrio, // ベース優先度(内部表現) prio: TaskPrio, // 現在の優先度(内部表現) flags: packed struct { actque: u1, // 起動要求キューイング wupque: u1, // 起床要求キューイング raster: bool, // タスク終了要求状態 enater: bool, // タスク終了許可状態 staovr: if (TOPPERS_SUPPORT_OVRHDR) bool else void, // オーバランハンドラ動作状態 }, p_winfo: *WINFO, // 待ち情報ブロックへのポインタ p_lastmtx: ?*mutex.MTXCB, // 最後にロックしたミューテックス */ leftotm: if (TOPPERS_SUPPORT_OVRHDR) PRCTIM else void, // 残りプロセッサ時間 tskctxb: target_impl.TSKCTXB, }; // タスクコンテキストブロック /// /// 実行状態のタスク /// /// 実行状態のタスク(=プロセッサがコンテキストを持っているタスク) /// のTCBを指すポインタ.実行状態のタスクがない場合はnullにする. /// /// サービスコールの処理中で,自タスク(サービスコールを呼び出したタ /// スク)に関する情報を参照する場合はp_runtskを使う.p_runtskを書き /// 換えるのは,ディスパッチャ(と初期化処理)のみである. /// pub var p_runtsk: ?*TCB = undefined; /// /// 実行すべきタスク /// /// 実行すべきタスクのTCBを指すポインタ.実行できるタスクがない場合は /// nullにする. /// /// p_runtskは,通常はp_schedtskと一致しているが,非タスクコンテキス /// ト実行中は,一致しているとは限らない.割込み優先度マスク全解除で /// ない状態の間とディスパッチ禁止状態の間(すなわち,dspflgがfalseで /// ある間)は,p_schedtskを更新しない. /// pub var p_schedtsk: ?*TCB = undefined; /// /// ディスパッチ許可状態 /// /// ディスパッチ許可状態であることを示すフラグ. /// pub var enadsp: bool = undefined; /// /// タスクディスパッチ可能状態 /// /// 割込み優先度マスク全解除状態であり,ディスパッチ許可状態である /// (ディスパッチ禁止状態でない)ことを示すフラグ.ディスパッチ保留 /// 状態でないことは,タスクコンテキスト実行中で,CPUロック状態でなく, /// dspflgがtrueであることで判別することができる. /// pub var dspflg: bool = undefined; /// /// レディキュー /// /// レディキューは,実行できる状態のタスクを管理するためのキューであ /// る.実行状態のタスクも管理しているため,レディ(実行可能)キュー /// という名称は正確ではないが,レディキューという名称が定着している /// ため,この名称で呼ぶことにする. /// /// レディキューは,優先度ごとのタスクキューで構成されている.タスク /// のTCBは,該当する優先度のキューに登録される. /// pub var ready_queue: [TNUM_TPRI]queue.Queue = undefined; /// /// レディキューサーチのためのビットマップ /// /// レディキューのサーチを効率よく行うために,優先度ごとのタスクキュー /// にタスクが入っているかどうかを示すビットマップを用意している.ビッ /// トマップを使うことで,メモリアクセスの回数を減らすことができるが, /// ビット操作命令が充実していないプロセッサで,優先度の段階数が少な /// い場合には,ビットマップ操作のオーバーヘッドのために,逆に効率が /// 落ちる可能性もある. /// var ready_primap: prio_bitmap.PrioBitmap(TNUM_TPRI) = undefined; /// /// タスクに関するコンフィギュレーションデータの取り込み /// pub const ExternTskCfg = struct { /// /// タスク初期化ブロック(スライス) /// pub extern const _kernel_tinib_table: []TINIB; /// /// タスク生成順序テーブル /// // Zigの制限事項の回避:十分に大きいサイズの配列とする pub extern const _kernel_torder_table: [1000]ID; /// /// TCBのエリア /// // Zigの制限事項の回避:十分に大きいサイズの配列とする pub extern var _kernel_tcb_table: [1000]TCB; }; /// /// タスクIDの最大値 /// fn maxTskId() ID { return @intCast(ID, TMIN_TSKID + cfg._kernel_tinib_table.len - 1); } /// /// タスクIDからTCBを取り出すための関数 /// fn indexTsk(tskid: ID) usize { return @intCast(usize, tskid - TMIN_TSKID); } pub fn checkAndGetTCB(tskid: ID) ItronError!*TCB { try checkId(TMIN_TSKID <= tskid and tskid <= maxTskId()); return &cfg._kernel_tcb_table[indexTsk(tskid)]; } /// /// タスクIDからタスク初期化ブロックを取り出すための関数 /// pub fn getTIniB(tskid: ID) *const TINIB { return &cfg._kernel_tinib_table[indexTsk(tskid)]; } /// /// TCBからタスクIDを取り出すための関数 /// pub fn getTskIdFromTCB(p_tcb: *TCB) ID { return @intCast(ID, (@ptrToInt(p_tcb) - @ptrToInt(&cfg._kernel_tcb_table)) / @sizeOf(TCB)) + TMIN_TSKID; } /// /// タスクキューからTCBを取り出すための関数 /// pub fn getTCBFromQueue(p_entry: *queue.Queue) *TCB { return @fieldParentPtr(TCB, "task_queue", p_entry); } /// /// ミューテックス機能のためのフックルーチン /// pub var mtxhook_check_ceilpri: ?fn(p_tcb: *TCB, bprio: TaskPrio) bool = null; pub var mtxhook_scan_ceilmtx: ?fn(p_tcb: *TCB) bool = null; pub var mtxhook_release_all: ?fn(p_tcb: *TCB) void = null; /// /// タスク管理モジュールの初期化 /// pub fn initialize_task() void { p_runtsk = null; p_schedtsk = null; enadsp = true; dspflg = true; for (ready_queue) |*p_queue| { p_queue.initialize(); } ready_primap.initialize(); for (cfg._kernel_torder_table[0 .. cfg._kernel_tinib_table.len]) |tskid| { const p_tcb = &cfg._kernel_tcb_table[indexTsk(tskid)]; p_tcb.p_tinib = &cfg._kernel_tinib_table[indexTsk(tskid)]; p_tcb.flags.actque = 0; make_dormant(p_tcb); p_tcb.p_lastmtx = null; if ((p_tcb.p_tinib.tskatr & TA_ACT) != 0) { make_active(p_tcb); } } } /// /// 最高優先順位タスクのサーチ /// /// レディキュー中の最高優先順位のタスクをサーチし,そのTCBへのポイン /// タを返す.レディキューが空の場合には,この関数を呼び出してはなら /// ない. /// fn searchSchedtsk() *TCB { return getTCBFromQueue(ready_queue[ready_primap.search()].p_next); } /// /// 実行できる状態への遷移 /// /// p_tcbで指定されるタスクをレディキューに挿入する.また,必要な場合 /// には,実行すべきタスクを更新する. /// pub fn make_runnable(p_tcb: *TCB) void { const prio = p_tcb.prio; ready_queue[prio].insertPrev(&p_tcb.task_queue); ready_primap.set(prio); if (dspflg) { if (p_schedtsk == null or prio < p_schedtsk.?.prio) { p_schedtsk = p_tcb; } } } /// /// 実行できる状態から他の状態への遷移 /// /// p_tcbで指定されるタスクをレディキューに挿入する.また,必要な場合 /// には,実行すべきタスクを更新する. /// pub fn make_non_runnable(p_tcb: *TCB) void { const prio = p_tcb.prio; const p_queue = &ready_queue[prio]; p_tcb.task_queue.delete(); if (p_queue.isEmpty()) { ready_primap.clear(prio); if (p_schedtsk == p_tcb) { assert(dspflg); p_schedtsk = if (ready_primap.isEmpty()) null else searchSchedtsk(); } } else { if (p_schedtsk == p_tcb) { assert(dspflg); p_schedtsk = getTCBFromQueue(p_queue.p_next); } } } /// /// タスクディスパッチ可能状態への遷移 /// /// タスクディスパッチ可能状態であることを示すフラグ(dspflg)をtrue /// にし,実行すべきタスクを更新する. /// pub fn set_dspflg() void { dspflg = true; p_schedtsk = searchSchedtsk(); } /// /// 休止状態への遷移 /// /// p_tcbで指定されるタスクの状態を休止状態とする.また,タスクの起動 /// 時に初期化すべき変数の初期化と,タスク起動のためのコンテキストを /// 設定する. /// fn make_dormant(p_tcb: *TCB) void { p_tcb.tstat = TS_DORMANT; p_tcb.bprio = @intCast(TaskPrio, p_tcb.p_tinib.ipri); p_tcb.prio = p_tcb.bprio; p_tcb.flags.wupque = 0; p_tcb.flags.raster = false; p_tcb.flags.enater = true; if (TOPPERS_SUPPORT_OVRHDR) { p_tcb.flags.staovr = false; } traceLog("taskStateChange", .{ p_tcb }); } /// /// 休止状態から実行できる状態への遷移 /// /// p_tcbで指定されるタスクの状態を休止状態から実行できる状態とする. /// pub fn make_active(p_tcb: *TCB) void { target_impl.activateContext(p_tcb); p_tcb.tstat = TS_RUNNABLE; traceLog("taskStateChange", .{ p_tcb }); make_runnable(p_tcb); } /// /// タスクの優先度の変更 /// /// p_tcbで指定されるタスクの優先度をnewpri(内部表現)に変更する.ま /// た,必要な場合には,実行すべきタスクを更新する. /// /// p_tcbで指定されるタスクが実行できる状態である場合,その優先順位は, /// 優先度が同じタスクの中で,mtxmodeがfalseの時は最低,mtxmodeがtrue /// の時は最高とする. /// pub fn change_priority(p_tcb: *TCB, newprio: TaskPrio, mtxmode: bool) void { const oldprio = p_tcb.prio; p_tcb.prio = newprio; if (isRunnable(p_tcb.tstat)) { // タスクが実行できる状態の場合 p_tcb.task_queue.delete(); if (ready_queue[oldprio].isEmpty()) { ready_primap.clear(oldprio); } if (mtxmode) { ready_queue[newprio].insertNext(&p_tcb.task_queue); } else { ready_queue[newprio].insertPrev(&p_tcb.task_queue); } ready_primap.set(newprio); if (dspflg) { if (p_schedtsk == p_tcb) { if (newprio >= oldprio) { p_schedtsk = searchSchedtsk(); } } else { if (newprio <= p_schedtsk.?.prio) { p_schedtsk = getTCBFromQueue(ready_queue[newprio].p_next); } } } } else { if (isWaitingWobjCB(p_tcb.tstat)) { // タスクが,同期・通信オブジェクトの管理ブロックの共通部 // 分(WOBJCB)の待ちキューにつながれている場合 wobj_change_priority(@fieldParentPtr(WINFO_WOBJ, "winfo", p_tcb.p_winfo).p_wobjcb, p_tcb); } } } /// /// レディキューの回転 /// /// レディキュー中の,p_queueで指定されるタスクキューを回転させる.ま /// た,必要な場合には,実行すべきタスクを更新する. /// pub fn rotate_ready_queue(prio: TaskPrio) void { const p_queue = &ready_queue[prio]; if (!p_queue.isEmpty() and p_queue.p_next.p_next != p_queue) { const p_entry = p_queue.deleteNext(); p_queue.insertPrev(p_entry); if (dspflg) { if (p_schedtsk == getTCBFromQueue(p_entry)) { p_schedtsk = getTCBFromQueue(p_queue.p_next); } } } } /// /// タスクの終了処理 /// /// p_tcbで指定されるタスクを終了させる処理を行う.タスクの起動要求 /// キューイング数が0でない場合には,再度起動するための処理を行う. /// pub fn task_terminate(p_tcb: *TCB) void { if (isRunnable(p_tcb.tstat)) { make_non_runnable(p_tcb); } else if (isWaiting(p_tcb.tstat)) { wait_dequeue_wobj(p_tcb); wait_dequeue_tmevtb(p_tcb); } if (p_tcb.p_lastmtx != null) { mtxhook_release_all.?(p_tcb); } make_dormant(p_tcb); if (p_tcb.flags.actque > 0) { p_tcb.flags.actque -= 1; make_active(p_tcb); } } /// /// 必要な場合にはタスクディスパッチを行う /// /// タスクコンテキストから呼ぶ場合はtaskDispatch,非コンテキストから /// も呼ぶ場合にはrequestTaskDispatchを用いる. /// pub fn taskDispatch() void { if (p_runtsk != p_schedtsk) { target_impl.dispatch(); } } pub fn requestTaskDispatch() void { if (p_runtsk != p_schedtsk) { if (!target_impl.senseContext()) { target_impl.dispatch(); } else { target_impl.requestDispatchRetint(); } } } /// /// タスクの生成(静的APIの処理) /// pub fn cre_tsk(comptime ctsk: T_CTSK) ItronError!TINIB { // tskatrが無効の場合(E_RSATR)[NGKI1028][NGKI3526][ASPS0009] // [NGKI1016] //(TA_ACT,TA_NOACTQUE,TARGET_TSKATR以外のビットがセットされている場合) try checkValidAtr(ctsk.tskatr, TA_ACT|TA_NOACTQUE | TARGET_TSKATR); // itskpriが有効範囲外の場合(E_PAR)[NGKI1034] //(TMIN_TPRI <= itskpri && itskpri <= TMAX_TPRIでない場合) try checkParameter(validTaskPri(ctsk.itskpri)); // stkszがターゲット定義の最小値(TARGET_MIN_STKSZ,未定義の場合は1) // よりも小さい場合(E_PAR)[NGKI1042] try checkParameter(ctsk.stksz >= TARGET_MIN_STKSZ); // stkszがターゲット定義の制約に合致しない場合(E_PAR)[NGKI1056] try checkParameter((ctsk.stksz & (CHECK_STKSZ_ALIGN - 1)) == 0); // ターゲット依存のエラーチェック if (@hasDecl(target_impl, "checkCreTsk")) { try target_impl.checkCreTsk(ctsk); } // タスクのスタック領域の確保 // // この記述では,タスク毎に別々のスタック領域が割り当てられる保証 // がない.コンパイラのバージョンが上がると,誤動作する可能性があ // る. comptime const stksz = TOPPERS_ROUND_SZ(ctsk.stksz, STACK_ALIGN); comptime const stk = if (ctsk.stk) |stk| stk else &struct { var stack: [stksz]u8 align(STACK_ALIGN) = undefined; }.stack; // タスク初期化ブロックを返す return TINIB{ .tskatr = ctsk.tskatr, .exinf = ctsk.exinf, .task = ctsk.task, .ipri = internalTaskPrio(ctsk.itskpri), .tskinictxb = if (@hasDecl(target_impl, "TSKINICTXB")) target_impl.genTskIniCtxB(stksz, stk) else .{ .stksz = stksz, .stk = stk, }, }; } /// /// タスクに関するコンフィギュレーションデータの生成(静的APIの処理) /// pub fn ExportTskCfg(tinib_table: []TINIB, torder_table: []ID) type { // チェック処理用の定義の生成 exportCheck(@sizeOf(TINIB), "sizeof_TINIB"); exportCheck(@sizeOf(TASK), "sizeof_TASK"); exportCheck(@byteOffsetOf(TINIB, "task"), "offsetof_TINIB_task"); exportCheck(@byteOffsetOf(TINIB, "tskinictxb") + @byteOffsetOf(@TypeOf(tinib_table[0].tskinictxb), "stk"), "offsetof_TINIB_stk"); const tnum_tsk = tinib_table.len; return struct { pub export const _kernel_tinib_table = tinib_table; pub export const _kernel_torder_table = torder_table[0 .. tnum_tsk].*; pub export var _kernel_tcb_table: [tnum_tsk]TCB = undefined; }; } /// /// トレースログのためのカーネル情報の取出し関数 /// pub fn getTskId(info: usize) usize { var tskid: ID = undefined; if (@intToPtr(?*TCB, info)) |p_tcb| { tskid = getTskIdFromTCB(p_tcb); } else { tskid = TSK_NONE; } return @intCast(usize, tskid); } pub fn getTskStat(info: usize) usize { var tstatstr: [*:0]const u8 = undefined; const tstat = @intCast(u8, info); if (isDormant(tstat)) { tstatstr = "DORMANT"; } else { if (isSuspended(tstat)) { if (isWaiting(tstat)) { tstatstr = "WAITING-SUSPENDED"; } else { tstatstr = "SUSPENDED"; } } else if (isWaiting(tstat)) { tstatstr = "WAITING"; } else { tstatstr = "RUNNABLE"; } } return @ptrToInt(tstatstr); } /// /// カーネルの整合性検査のための関数 /// /// /// TCBへのポインタのチェック /// pub fn validTCB(p_tcb: *TCB) bool { if ((@ptrToInt(p_tcb) - @ptrToInt(&cfg._kernel_tcb_table)) % @sizeOf(TCB) != 0) { return false; } const tskid = getTskIdFromTCB(p_tcb); return TMIN_TSKID <= tskid and tskid <= maxTskId(); } /// /// スタック上を指しているかのチェック /// pub fn onStack(addr: usize, size: usize, p_tinib: *const TINIB) bool { if (@hasDecl(target_impl, "onStack")) { return target_impl.onStack(addr, size, p_tinib); } else { return @ptrToInt(p_tinib.tskinictxb.stk) <= addr and addr + size <= @ptrToInt(&p_tinib.tskinictxb.stk [p_tinib.tskinictxb.stksz]); } } /// /// タスクコンテキストブロックのチェック /// pub fn validTSKCTXB(p_tcb: *TCB) bool { if (@hasDecl(target_impl, "validTSKCTXB")) { return target_impl.validTSKCTXB(&p_tcb.tskctxb, p_tcb); } else { // spがアラインしているかをチェック if ((@ptrToInt(p_tcb.tskctxb.sp) & (CHECK_STACK_ALIGN - 1)) != 0) { return false; } // spがスタック上を指しているかをチェック if (!onStack(@ptrToInt(p_tcb.tskctxb.sp), 0, p_tcb.p_tinib)) { return false; } return true; } } /// /// スケジューリングのためのデータ構造の整合性検査 /// fn bitSched() ItronError!void { // p_schedtskの整合性検査 if (dspflg) { if (ready_primap.isEmpty()) { try checkBit(p_schedtsk == null); } else { try checkBit(p_schedtsk == searchSchedtsk()); } } // ready_primapの整合性検査 try checkBit(ready_primap.bitCheck()); // ready_queueとready_primapの整合性の検査 for (ready_queue) |*p_queue, prio| { if (p_queue.isEmpty()) { try checkBit(!ready_primap.isSet(@intCast(TaskPrio, prio))); } else { try checkBit(ready_primap.isSet(@intCast(TaskPrio, prio))); } var p_entry = p_queue.p_next; while (p_entry != p_queue) : (p_entry = p_entry.p_next) { const p_tcb = getTCBFromQueue(p_entry); try checkBit(validTCB(p_tcb)); try checkBit(isRunnable(p_tcb.tstat)); try checkBit(p_tcb.prio == prio); } } } /// /// タスク毎の整合性検査 /// fn bitTCB(p_tcb: *TCB) ItronError!void { const p_tinib = p_tcb.p_tinib; const tstat = p_tcb.tstat; // タスク初期化ブロックへのポインタの整合性検査 try checkBit(p_tinib == getTIniB(getTskIdFromTCB(p_tcb))); // tstatの整合性検査 if (isDormant(tstat)) { try checkBit(tstat == TS_DORMANT); } else if (isWaiting(tstat)) { try checkBit((tstat & ~@as(u8, TS_WAITING_MASK | TS_SUSPENDED)) == 0); } else if (isSuspended(tstat)) { try checkBit(tstat == TS_SUSPENDED); } else { try checkBit(tstat == TS_RUNNABLE); } // ベース優先度の検査 try checkBit(p_tcb.bprio < TNUM_TPRI); // 現在の優先度の検査 try checkBit(p_tcb.prio <= p_tcb.bprio); // rasterと他の状態の整合性検査 if (p_tcb.flags.raster) { try checkBit(!p_tcb.flags.enater); try checkBit(!isWaiting(tstat)); } // 休止状態における整合性検査 if (isDormant(tstat)) { try checkBit(p_tcb.bprio == p_tinib.ipri); try checkBit(p_tcb.prio == p_tinib.ipri); try checkBit(p_tcb.flags.actque == 0); try checkBit(p_tcb.flags.wupque == 0); try checkBit(p_tcb.flags.raster == false); try checkBit(p_tcb.flags.enater == true); try checkBit(p_tcb.p_lastmtx == null); } // 実行できる状態における整合性検査 if (isRunnable(tstat)) { try checkBit(ready_queue[p_tcb.prio].bitIncluded(&p_tcb.task_queue)); } // 待ち状態における整合性検査 if (isWaiting(tstat)) { var winfo_size: usize = undefined; if (p_tcb.p_winfo.p_tmevtb) |p_tmevtb| { try checkBit(onStack(@ptrToInt(p_tmevtb), @sizeOf(TMEVTB), p_tinib)); try checkBit(validTMEVTB(p_tmevtb)); if ((tstat & TS_WAITING_MASK) != TS_WAITING_DLY) { try checkBit(p_tmevtb.callback == wait_tmout); } else { try checkBit(p_tmevtb.callback == wait_tmout_ok); } try checkBit(p_tmevtb.arg == @ptrToInt(p_tcb)); } switch (tstat & TS_WAITING_MASK) { TS_WAITING_SLP => { try checkBit(p_tcb.flags.wupque == 0); winfo_size = @sizeOf(WINFO); }, TS_WAITING_DLY => { try checkBit(p_tcb.p_winfo.p_tmevtb != null); winfo_size = @sizeOf(WINFO); }, // ★未完成 TS_WAITING_MTX => { const p_mtxcb = mutex.getWinfoMtx(p_tcb.p_winfo).p_wobjcb; try checkBit(mutex.validMTXCB(p_mtxcb)); try checkBit(p_mtxcb.wait_queue.bitIncluded(&p_tcb.task_queue)); winfo_size = @sizeOf(mutex.WINFO_MTX); }, // ★未完成 else => { // return ItronError.SystemError; } } try checkBit(onStack(@ptrToInt(p_tcb.p_winfo), winfo_size, p_tinib)); } // p_lastmtxの検査 if (p_tcb.p_lastmtx) |p_lastmtx| { try checkBit(mutex.validMTXCB(p_lastmtx)); } // tskctxbの検査 if (!isDormant(tstat) and p_tcb != p_runtsk) { try checkBit(validTSKCTXB(p_tcb)); } } /// /// タスクに関する整合性検査 /// pub fn bitTask() ItronError!void { // スケジューリングのためのデータ構造の整合性検査 try bitSched(); // タスク毎の整合性検査 for (cfg._kernel_tcb_table[0 .. cfg._kernel_tinib_table.len]) |*p_tcb| { try bitTCB(p_tcb); } }
https://raw.githubusercontent.com/toppers/asp3_in_zig/7413474dc07ab906ac31eb367636ecf9c1cf2580/kernel/task.zig
// The I/O APIC manages hardware interrupts for an SMP system. // http://www.intel.com/design/chipsets/datashts/29056601.pdf // See also picirq.c. const mp = @import("mp.zig"); const trap = @import("trap.zig"); const IOAPIC = 0xFEC00000; // Default physical address of IO APIC const REG_ID = 0x00; // Register index: ID const REG_VER = 0x01; // Register index: version const REG_TABLE = 0x10; // Redirection table base // The redirection table starts at REG_TABLE and uses // two registers to configure each interrupt. // The first (low) register in a pair contains configuration bits. // The second (high) register contains a bitmask telling which const INT_DISABLED = 0x00010000; // Interrupt disabled const INT_LEVEL = 0x00008000; // Level-triggered (vs edge-) const INT_ACTIVELOW = 0x00002000; // Active low (vs high) const INT_LOGICAL = 0x00000800; // Destination is CPU id (vs APIC ID) var ioapic: *ioapic_t = undefined; const ioapic_t = packed struct { reg: u32, pad: u96, data: u32, const Self = @This(); fn read(self: *Self, reg: u32) u32 { self.*.reg = reg; return self.*.data; } fn write(self: *Self, reg: u32, data: u32) void { self.*.reg = reg; self.*.data = data; } }; pub fn ioapicinit() void { ioapic = @as(*ioapic_t, @ptrFromInt(IOAPIC)); const maxintr = (ioapic.read(REG_VER) >> 16) & 0xff; const id = ioapic.read(REG_ID) >> 24; if (id != mp.ioapicid) { asm volatile ("1: jmp 1b"); } // Mark all interrupts edge-triggered, active high, disabled, // and not routed to any CPUs. var i: u32 = 0; while (i <= maxintr) : (i += 1) { ioapic.write(REG_TABLE + 2 * i, INT_DISABLED | (trap.T_IRQ0 + i)); ioapic.write(REG_TABLE + 2 * i + 1, 0); } } pub fn ioapicenable(irq: u32, cpunum: u8) void { // Mark interrupt edge-triggered, active high, // enabled, and routed to the given cpunum, // which happens to be that cpu's APIC ID. ioapic.write(REG_TABLE + 2 * irq, trap.T_IRQ0 + irq); ioapic.write(REG_TABLE + 2 * irq + 1, @as(u32, @intCast(cpunum)) << 24); }
https://raw.githubusercontent.com/saza-ku/xv6-zig/2a31edcf16854ceb0ff11c5aa5949d13fac2f28c/src/ioapic.zig
base: Context, version: u32, debug_info: []const u8 = &.{}, debug_line: []const u8 = &.{}, debug_loc: []const u8 = &.{}, debug_ranges: []const u8 = &.{}, debug_pubnames: []const u8 = &.{}, debug_pubtypes: []const u8 = &.{}, debug_str: []const u8 = &.{}, debug_abbrev: []const u8 = &.{}, pub fn isWasmFile(data: []const u8) bool { return data.len >= 4 and std.mem.eql(u8, &std.wasm.magic, data[0..4]); } pub fn deinit(wasm_file: *Wasm, gpa: std.mem.Allocator) void { _ = wasm_file; _ = gpa; } pub fn parse(gpa: std.mem.Allocator, data: []const u8) !*Wasm { const wasm = try gpa.create(Wasm); errdefer gpa.destroy(wasm); wasm.* = .{ .base = .{ .tag = .wasm, .data = data, }, .version = 0, }; var fbs = std.io.fixedBufferStream(data); const reader = fbs.reader(); try reader.skipBytes(4, .{}); wasm.version = try reader.readInt(u32, .little); while (reader.readByte()) |byte| { const tag = try std.meta.intToEnum(std.wasm.Section, byte); const len = try std.leb.readULEB128(u32, reader); switch (tag) { .custom => { const name_len = try std.leb.readULEB128(u32, reader); var buf: [200]u8 = undefined; try reader.readNoEof(buf[0..name_len]); const name = buf[0..name_len]; const remaining_size = len - getULEB128Size(name_len) - name_len; if (std.mem.startsWith(u8, name, ".debug")) { const debug_info = data[reader.context.pos..][0..remaining_size]; if (std.mem.eql(u8, name, ".debug_info")) { wasm.debug_info = debug_info; } else if (std.mem.eql(u8, name, ".debug_line")) { wasm.debug_line = debug_info; } else if (std.mem.eql(u8, name, ".debug_loc")) { wasm.debug_loc = debug_info; } else if (std.mem.eql(u8, name, ".debug_ranges")) { wasm.debug_ranges = debug_info; } else if (std.mem.eql(u8, name, ".debug_pubnames")) { wasm.debug_pubnames = debug_info; } else if (std.mem.eql(u8, name, ".debug_pubtypes")) { wasm.debug_pubtypes = debug_info; } else if (std.mem.eql(u8, name, ".debug_abbrev")) { wasm.debug_abbrev = debug_info; } else if (std.mem.eql(u8, name, ".debug_str")) { wasm.debug_str = debug_info; } } try reader.skipBytes(remaining_size, .{}); }, else => try reader.skipBytes(len, .{}), } } else |err| switch (err) { error.EndOfStream => {}, // finished parsing else => |e| return e, } return wasm; } pub fn getDebugAbbrevData(wasm_file: *const Wasm) ?[]const u8 { if (wasm_file.debug_abbrev.len == 0) return null; return wasm_file.debug_abbrev; } pub fn getDebugStringData(wasm_file: *const Wasm) ?[]const u8 { if (wasm_file.debug_str.len == 0) return null; return wasm_file.debug_str; } pub fn getDebugInfoData(wasm_file: *const Wasm) ?[]const u8 { if (wasm_file.debug_info.len == 0) return null; return wasm_file.debug_info; } /// From a given unsigned integer, returns the size it takes /// in bytes to store the integer using leb128-encoding. fn getULEB128Size(uint_value: anytype) u32 { const T = @TypeOf(uint_value); const U = if (@typeInfo(T).Int.bits < 8) u8 else T; var value = @as(U, @intCast(uint_value)); var size: u32 = 0; while (value != 0) : (size += 1) { value >>= 7; } return size; } const std = @import("std"); const Context = @import("../Context.zig"); const Wasm = @This();
https://raw.githubusercontent.com/kubkon/zig-dwarfdump/24f1b9a73dff6d1b39b4ade558230aa303e1d849/src/Context/Wasm.zig
const std = @import("std"); const libalign = @import("../util/libalign.zig"); const PixelFormat = @import("pixel_format.zig").PixelFormat; const Color = @import("color.zig").Color; pub const InvalidateRectFunc = fn (r: *ImageRegion, x: usize, y: usize, width: usize, height: usize) void; pub const ImageRegion = struct { width: usize, height: usize, pixel_format: PixelFormat, bytes: []u8, pitch: usize, /// Function to call when a subregion of the image has been modified invalidateRectFunc: ?InvalidateRectFunc, // The following variables are managed by this struct and shouldn't be changed /// If the image is a less wide subregion() of any other ImageRegion /// means that the bytes between bpp*width and pitch can't be overwritten full_width: bool = true, // Offsets are needed for the invalidation callbacks for subregions x_offset: usize = 0, y_offset: usize = 0, pub fn subregion( self: *const @This(), x: usize, y: usize, width: usize, height: usize, ) @This() { if (x + width > self.width) unreachable; if (y + height > self.height) unreachable; return .{ .width = width, .height = height, .pixel_format = self.pixel_format, .bytes = self.startingAt(x, y), .pitch = self.pitch, .invalidateRectFunc = self.invalidateRectFunc, .full_width = self.full_width and width == self.width, .x_offset = self.x_offset + x, .y_offset = self.y_offset + y, }; } pub fn invalidateRect( self: *const @This(), x: usize, y: usize, width: usize, height: usize, ) void { if (x + width > self.width) unreachable; if (y + height > self.height) unreachable; if (self.invalidateRectFunc) |func| func(@intToPtr(*@This(), @ptrToInt(self)), x + self.x_offset, y + self.y_offset, width, height); } /// Draw a pixel to the region pub fn drawPixel( self: *const @This(), c: Color, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawPixelWithFormat(.rgb, c, x, y, invalidate), .rgba => self.drawPixelWithFormat(.rgba, c, x, y, invalidate), .rgbx => self.drawPixelWithFormat(.rgbx, c, x, y, invalidate), } } /// Draw a pixel, assuming the target format pub fn drawPixelWithFormat( self: *const @This(), comptime fmt: PixelFormat, c: Color, x: usize, y: usize, comptime invalidate: bool, ) void { if (x > self.width) unreachable; if (y > self.height) unreachable; if (fmt != self.pixel_format) unreachable; c.writeAsFmt(fmt, self.startingAt(x, y)); if (comptime invalidate) self.invalidateRect(x, y, 1, 1); } pub fn getPixel( self: *const @This(), x: usize, y: usize, ) Color { return switch (self.pixel_format) { .rgb => self.getPixelWithFormat(.rgb, x, y), .rgba => self.getPixelWithFormat(.rgba, x, y), .rgbx => self.getPixelWithFormat(.rgbx, x, y), }; } pub fn getPixelWithFormat(self: *const @This(), comptime fmt: PixelFormat, x: usize, y: usize) Color { if (x > self.width) unreachable; if (y > self.height) unreachable; if (fmt != self.pixel_format) unreachable; return Color.readAsFmt(fmt, startingAt(x, y)); } pub fn fill( self: *const @This(), c: Color, x: usize, y: usize, width: usize, height: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.fillWithFormat(.rgb, c, x, y, width, height, invalidate), .rgba => self.fillWithFormat(.rgba, c, x, y, width, height, invalidate), .rgbx => self.fillWithFormat(.rgbx, c, x, y, width, height, invalidate), } } pub fn fillWithFormat( target: *const @This(), comptime fmt: PixelFormat, c: Color, x: usize, y: usize, width: usize, height: usize, comptime invalidate: bool, ) void { if (!target.pixel_format.canWrite(fmt)) unreachable; if (width + x > target.width) unreachable; if (height + y > target.height) unreachable; // Can we memset (all bytes equal) when filing? if (c.memsetAsFmt(fmt)) |byte_value| { if (x == 0 and width == target.width and target.full_width) { libalign.alignedFill(u32, target.startingAt(0, y)[0 .. height * target.pitch], byte_value); } else { var curr_y: usize = 0; var target_lines = target.startingAt(x, y); while (true) { const line = target_lines[0 .. width * comptime fmt.bytesPerPixel()]; libalign.alignedFill(u32, line, byte_value); curr_y += 1; if (curr_y == height) break; target_lines = target_lines[target.pitch..]; } } } else { var pixel_bytes: [fmt.meaningfulBytesPerPixel()]u8 = undefined; c.writeAsFmt(fmt, &pixel_bytes); var curr_y: usize = 0; var target_lines = target.startingAt(x, y); while (true) { var curr_x: usize = 0; var target_pixels = target_lines; while (true) { libalign.alignedCopy(u8, target_pixels, pixel_bytes[0..]); curr_x += 1; if (curr_x == width) break; target_pixels = target_pixels[comptime fmt.bytesPerPixel()..]; } curr_y += 1; if (curr_y == height) break; target_lines = target_lines[target.pitch..]; } } if (comptime invalidate) target.invalidateRect(x, y, width, height); } /// Assume both source and target formats pub fn drawImageWithFmt( target: *const @This(), comptime source_fmt: PixelFormat, comptime target_fmt: PixelFormat, source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { // Check if the formats we're using are valid if (!source.pixel_format.canReadManyAs(source_fmt)) unreachable; if (!target.pixel_format.canWriteMany(target_fmt)) unreachable; // Bounds checks if (source.width + x > target.width) unreachable; if (source.height + y > target.height) unreachable; // Check if the input and output formats are bit-compatible if (comptime target_fmt.canWriteMany(source_fmt)) { // Can we copy the entire thing in one memcpy? if (source.pitch == target.pitch and source.full_width and target.full_width) { const num_bytes = source.pitch * source.height; libalign.alignedCopy(u32, target.startingAt(x, y), source.bytes[0..num_bytes]); } else { const num_bytes = source.width * comptime source_fmt.bytesPerPixel(); var source_bytes = source.bytes; var target_bytes = target.startingAt(x, y); var source_y: usize = 0; while (true) { libalign.alignedCopy(u32, target_bytes, source_bytes[0..num_bytes]); source_y += 1; if (source_y == source.height) break; target_bytes = target_bytes[target.pitch..]; source_bytes = source_bytes[source.pitch..]; } } } // Fine, do one pixel at a time else { var source_lines = source.bytes; var target_lines = target.startingAt(x, y); var source_y: usize = 0; while (true) { var source_x: usize = 0; var source_pixels = source_lines; var target_pixels = target_lines; while (true) { if (comptime target_fmt.canWrite(source_fmt)) { const source_bytes = source_fmt.meaningfulBytesPerPixel(); const target_bytes = target_fmt.meaningfulBytesPerPixel(); const bytes_to_copy = std.math.min(source_bytes, target_bytes); libalign.alignedCopy(u32, target_pixels, source_pixels[0..comptime bytes_to_copy]); } else { Color.readAsFmt( source_fmt, source_pixels, ).writeAsFmt( target_fmt, target_pixels, ); } source_x += 1; if (source_x == source.width) break; source_pixels = source_pixels[comptime source_fmt.bytesPerPixel()..]; target_pixels = target_pixels[comptime target_fmt.bytesPerPixel()..]; } source_y += 1; if (source_y == source.height) break; source_lines = source_lines[source.pitch..]; target_lines = target_lines[target.pitch..]; } } if (comptime invalidate) target.invalidateRect(x, y, source.width, source.height); } // I wish I could use https://github.com/ziglang/zig/issues/7224 right now... /// Assume the sourcce format pub fn drawImageWithSourceFmt( self: *const @This(), comptime source_fmt: PixelFormat, source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawImageWithFmt(source_fmt, .rgb, source, x, y, invalidate), .rgba => self.drawImageWithFmt(source_fmt, .rgba, source, x, y, invalidate), .rgbx => self.drawImageWithFmt(source_fmt, .rgbx, source, x, y, invalidate), } } /// Assume the target format pub fn drawImageWithTargetFmt( self: *const @This(), comptime target_fmt: PixelFormat, source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (source.pixel_format) { .rgb => self.drawImageWithFmt(.rgb, target_fmt, source, x, y, invalidate), .rgba => self.drawImageWithFmt(.rgba, target_fmt, source, x, y, invalidate), .rgbx => self.drawImageWithFmt(.rgbx, target_fmt, source, x, y, invalidate), } } /// Assume the source and target pixel formats are equal pub fn drawImageSameFmt( self: *const @This(), source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawImageWithFmt(.rgb, .rgb, source, x, y, invalidate), .rgba => self.drawImageWithFmt(.rgba, .rgba, source, x, y, invalidate), .rgbx => self.drawImageWithFmt(.rgbx, .rgbx, source, x, y, invalidate), } } /// Draw the source image region to the target one pub fn drawImage( self: *const @This(), source: ImageRegion, x: usize, y: usize, comptime invalidate: bool, ) void { switch (self.pixel_format) { .rgb => self.drawImageWithTargetFmt(.rgb, source, x, y, invalidate), .rgba => self.drawImageWithTargetFmt(.rgba, source, x, y, invalidate), .rgbx => self.drawImageWithTargetFmt(.rgbx, source, x, y, invalidate), } } fn startingAt(self: *const @This(), x: usize, y: usize) []u8 { if (x > self.width) unreachable; if (y > self.height) unreachable; const offset = self.pixel_format.bytesPerPixel() * x + self.pitch * y; return self.bytes[offset..]; } };
https://raw.githubusercontent.com/FlorenceOS/Florence/aaa5a9e568197ad24780ec9adb421217530d4466/lib/graphics/image_region.zig
const std = @import("std"); const inquirer = @import("inquirer"); // Comparison adaptation of https://github.com/SBoudrias/Inquirer.js/blob/master/packages/inquirer/examples/pizza.js pub fn main() !void { std.log.info("All your codebase are belong to us.", .{}); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const alloc = &gpa.allocator; const in = std.io.getStdIn().reader(); const out = std.io.getStdOut().writer(); _ = try inquirer.forConfirm(out, in, "Is this for delivery?", alloc); _ = try inquirer.forString(out, in, "What's your phone number?", alloc, null); _ = try inquirer.forEnum(out, in, "What size do you need?", alloc, enum { Small, Medium, Large }, null); // _ = try inquirer.forNumber(out,in,"How many do you need?", alloc, u32, 1); // TODO forNumber is causing a compiler crash // TODO toppings for string list _ = try inquirer.forEnum(out, in, "You also get a free 2L:", alloc, enum { Pepsi, @"7up", Coke }, null); const comment = try inquirer.forString(out, in, "Any comments on your purchase experience?", alloc, "Nope, all good!"); if (!std.mem.eql(u8, comment, "Nope, all good!")) { _ = try inquirer.forEnum(out, in, "For leaving a comment, you get a freebie:", alloc, enum { Cake, Fries }, null); } }
https://raw.githubusercontent.com/nektro/zig-inquirer/cf43dd6c9f328073f7468b5341c69ed0bb185db3/src/main.zig
const std = @import("std"); const core = @import("core.zig"); events: std.ArrayList(Event), const Self = @This(); pub fn create(allocator: std.mem.Allocator) Self { return .{ .events = std.ArrayList(Event).init(allocator), }; } pub fn addEvent(self: *Self, ev: Event) std.mem.Allocator.Error!void { try self.events.append(ev); } pub fn debugPrint(self: *const Self) void { std.debug.print("{any}\n", .{ self.events.items }); } pub const ResponseEvent = union(enum) { Defense: core.Defense, Take: void, }; pub const ThrowEvent = union(enum) { Throw: core.ThrowAttack, Skip: void, }; pub const InitialAttackEvent = core.InitialAttack; pub const Event = union(enum) { Response: ResponseEvent, Play: InitialAttackEvent, Throw: ThrowEvent, };
https://raw.githubusercontent.com/AntonC9018/durak_domino/0cff8c06c94810ace5fe8e84d05977ffb7c93d5c/src/EventQueue.zig
// // A big advantage of Zig is the integration of its own test system. // This allows the philosophy of Test Driven Development (TDD) to be // implemented perfectly. Zig even goes one step further than other // languages, the tests can be included directly in the source file. // // This has several advantages. On the one hand it is much clearer to // have everything in one file, both the source code and the associated // test code. On the other hand, it is much easier for third parties // to understand what exactly a function is supposed to do if they can // simply look at the test inside the source and compare both. // // Especially if you want to understand how e.g. the standard library // of Zig works, this approach is very helpful. Furthermore it is very // practical, if you want to report a bug to the Zig community, to // illustrate it with a small example including a test. // // Therefore, in this exercise we will deal with the basics of testing // in Zig. Basically, tests work as follows: you pass certain parameters // to a function, for which you get a return - the result. This is then // compared with the EXPECTED value. If both values match, the test is // passed, otherwise an error message is displayed. // // testing.expect(foo(param1, param2) == expected); // // Also other comparisons are possible, deviations or also errors can // be provoked, which must lead to an appropriate behavior of the // function, so that the test is passed. // // Tests can be run via Zig build system or applied directly to // individual modules using "zig test xyz.zig". // // Both can be used script-driven to execute tests automatically, e.g. // after checking into a Git repository. Something we also make extensive // use of here at Ziglings. // const std = @import("std"); const testing = std.testing; // This is a simple function // that builds a sum from the // passed parameters and returns. fn add(a: f16, b: f16) f16 { return a + b; } // The associated test. // It always starts with the keyword "test", // followed by a description of the tasks // of the test. This is followed by the // test cases in curly brackets. test "add" { // The first test checks if the sum // of '41' and '1' gives '42', which // is correct. try testing.expect(add(41, 1) == 42); // Another way to perform this test // is as follows: try testing.expectEqual(add(41, 1), 42); // This time a test with the addition // of a negative number: try testing.expect(add(5, -4) == 1); // And a floating point operation: try testing.expect(add(1.5, 1.5) == 3); } // Another simple function // that returns the result // of subtracting the two // parameters. fn sub(a: f16, b: f16) f16 { return a - b; } // The corresponding test // is not much different // from the previous one. // Except that it contains // an error that you need // to correct. test "sub" { try testing.expect(sub(10, 5) == 5); try testing.expect(sub(3, 1.5) == 1.5); } // This function divides the // numerator by the denominator. // Here it is important that the // denominator must not be zero. // This is checked and if it // occurs an error is returned. fn divide(a: f16, b: f16) !f16 { if (b == 0) return error.DivisionByZero; return a / b; } test "divide" { try testing.expect(divide(2, 2) catch unreachable == 1); try testing.expect(divide(-1, -1) catch unreachable == 1); try testing.expect(divide(10, 2) catch unreachable == 5); try testing.expect(divide(1, 3) catch unreachable == 0.3333333333333333); // Now we test if the function returns an error // if we pass a zero as denominator. // But which error needs to be tested? try testing.expectError(error.DivisionByZero, divide(15, 0)); }
https://raw.githubusercontent.com/egonik-unlp/Ziglings---egonik-unlp/1d7e89127f1f905d49e5c2c5e176f17a0fdce7e2/exercises/102_testing.zig
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2024 Lee Cannon <leecannon@leecannon.xyz> const core = @import("core"); const std = @import("std"); const acpi = @import("acpi"); /// The Fixed ACPI Description Table (FADT) defines various fixed hardware ACPI information vital to an ACPI-compatible /// OS, such as the base address for the following hardware registers blocks: /// - PM1a_EVT_BLK /// - PM1b_EVT_BLK /// - PM1a_CNT_BLK /// - PM1b_CNT_BLK /// - PM2_CNT_BLK /// - PM_TMR_BLK /// - GPE0_BLK /// - GPE1_BLK. /// /// The FADT also has a pointer to the DSDT that contains the Differentiated Definition Block, which in turn provides /// variable information to an ACPI-compatible OS concerning the base system design. /// /// All fields in the FADT that provide hardware addresses provide processor-relative physical addresses. /// /// [ACPI 6.5 Specification Link](https://uefi.org/specs/ACPI/6.5/05_ACPI_Software_Programming_Model.html#fixed-acpi-description-table-fadt) pub const FADT = extern struct { header: acpi.SharedHeader align(1), /// Physical memory address of the FACS, where OSPM and Firmware exchange control information. /// /// If the `X_FIRMWARE_CTRL` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. /// /// If the `hardware_reduced_acpi` flag is set, and both this field and the `X_FIRMWARE_CTRL` field are zero, there /// is no FACS available. FIRMWARE_CTRL: u32 align(1), /// Physical memory address of the DSDT. /// /// If the `X_DSDT` field contains a non-zero value which can be used by the OSPM, then this field must be ignored /// by the OSPM. DSDT: u32 align(1), /// ACPI 1.0 defined this offset as a field named `int_model`, which was eliminated in ACPI 2.0. /// /// Platforms should set this field to zero but field values of one are also allowed to maintain compatibility with /// ACPI 1.0. _reserved1: u8, /// This field is set by the OEM to convey the preferred power management profile to OSPM. /// /// OSPM can use this field to set default power management policy parameters during OS installation. preferred_pm_profile: PowerManagementProfile, /// System vector the SCI interrupt is wired to in 8259 mode. /// /// On systems that do not contain the 8259, this field contains the Global System interrupt number of the SCI /// interrupt. /// /// OSPM is required to treat the ACPI SCI interrupt as a shareable, level, active low interrupt SCI_INT: u16 align(1), /// System port address of the SMI Command Port. /// /// During ACPI OS initialization, OSPM can determine that the ACPI hardware registers are owned by SMI /// (by way of the `sci_en` bit), in which case the ACPI OS issues the `ACPI_ENABLE` command to the `SMI_CMD` port. /// /// The `sci_en` bit effectively tracks the ownership of the ACPI hardware registers. /// /// OSPM issues commands to the `SMI_CMD` port synchronously from the boot processor. /// /// This field is reserved and must be zero on system that does not support System Management mode. SMI_CMD: u32 align(1), /// The value to write to `SMI_CMD` to disable SMI ownership of the ACPI hardware registers. /// /// The last action SMI does to relinquish ownership is to set the `sci_en` bit. /// /// During the OS initialization process, OSPM will synchronously wait for the transfer of SMI ownership to /// complete, so the ACPI system releases SMI ownership as quickly as possible. /// /// This field is reserved and must be zero on systems that do not support Legacy Mode. ACPI_ENABLE: u8, /// The value to write to `SMI_CMD` to re-enable SMI ownership of the ACPI hardware registers. /// /// This can only be done when ownership was originally acquired from SMI by OSPM using `ACPI_ENABLE`. /// /// An OS can hand ownership back to SMI by relinquishing use to the ACPI hardware registers, masking off all SCI /// interrupts, clearing the `sci_en` bit and then writing `ACPI_DISABLE` to the `SMI_CMD` port from the boot /// processor. /// /// This field is reserved and must be zero on systems that do not support Legacy Mode. ACPI_DISABLE: u8, /// The value to write to `SMI_CMD` to enter the S4BIOS state. /// /// The S4BIOS state provides an alternate way to enter the S4 state where the firmware saves and restores the /// memory context. /// /// A value of zero in `FACS.flags.S4BIOS_F` indicates `S4BIOS_REQ` is not supported. S4BIOS_REQ: u8, /// If non-zero, this field contains the value OSPM writes to the `SMI_CMD` register to assume processor performance /// state control responsibility. PSTATE_CNT: u8, /// System port address of the PM1a Event Register Block. /// /// This is a required field. /// /// If the `X_PM1a_EVT_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. PM1a_EVT_BLK: u32 align(1), /// System port address of the PM1b Event Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If the `X_PM1b_EVT_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. PM1b_EVT_BLK: u32 align(1), /// System port address of the PM1a Control Register Block. /// /// This is a required field. /// /// If the `X_PM1a_CNT_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. PM1a_CNT_BLK: u32 align(1), /// System port address of the PM1b Control Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If the `X_PM1b_CNT_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. PM1b_CNT_BLK: u32 align(1), /// System port address of the PM2 Control Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If the `X_PM2_CNT_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. PM2_CNT_BLK: u32 align(1), /// System port address of the Power Management Timer Control Register Block. /// /// This is an optional field; if this register block is not supported, this field contains zero. /// /// If the `X_PM_TMR_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. PM_TMR_BLK: u32 align(1), /// System port address of General-Purpose Event 0 Register Block. /// /// If this register block is not supported, this field contains zero. /// /// If the `X_GPE0_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. GPE0_BLK: u32 align(1), /// System port address of General-Purpose Event 1 Register Block. /// /// This is an optional field; if this register block is not supported, this field contains zero. /// /// If the `X_GPE1_BLK` field contains a non zero value which can be used by the OSPM, then this field must be /// ignored by the OSPM. GPE1_BLK: u32 align(1), /// Number of bytes decoded by PM1a_EVT_BLK and, if supported, PM1b_EVT_BLK. /// /// This value is >= 4. PM1_EVT_LEN: u8, /// Number of bytes decoded by PM1a_CNT_BLK and, if supported, PM1b_CNT_BLK. /// /// This value is >= 2. PM1_CNT_LEN: u8, /// Number of bytes decoded by PM2_CNT_BLK. /// /// Support for the PM2 register block is optional. /// /// If supported, this value is >= 1. /// /// If not supported, this field contains zero. PM2_CNT_LEN: u8, /// Number of bytes decoded by PM_TMR_BLK. /// /// If the PM Timer is supported, this field’s value must be 4. /// /// If not supported, this field contains zero. PM_TMR_LEN: u8, /// The length of the register whose address is given by `X_GPE0_BLK` (if nonzero) or by `GPE0_BLK` (otherwise) in /// bytes. /// /// The value is a non-negative multiple of 2. GPE0_BLK_LEN: u8, /// The length of the register whose address is given by `X_GPE1_BLK` (if nonzero) or by `GPE1_BLK` (otherwise) in /// bytes. /// /// The value is a non-negative multiple of 2. GPE1_BLK_LEN: u8, /// Offset within the ACPI general-purpose event model where GPE1 based events start. GPE1_BASE: u8, /// If non-zero, this field contains the value OSPM writes to the `SMI_CMD` register to indicate OS support for the /// _CST object and C States Changed notification. CST_CNT: u8, /// The worst-case hardware latency, in microseconds, to enter and exit a C2 state. /// /// A value > 100 indicates the system does not support a C2 state. P_LVL2_LAT: u16 align(1), /// The worst-case hardware latency, in microseconds, to enter and exit a C3 state. /// /// A value > 1000 indicates the system does not support a C3 state. P_LVL3_LAT: u16 align(1), /// If `WBINVD`=0, the value of this field is the number of flush strides that need to be read /// (using cacheable addresses) to completely flush dirty lines from any processor’s memory caches. /// /// Notice that the value in `FLUSH_STRIDE` is typically the smallest cache line width on any of the processor’s /// caches (for more information, see the `FLUSH_STRIDE` field definition). /// /// If the system does not support a method for flushing the processor’s caches, then `FLUSH_SIZE` and `WBINVD` are /// set to zero. /// /// Notice that this method of flushing the processor caches has limitations, and `WBINVD`=1 is the preferred way /// to flush the processors caches. /// /// This value is typically at least 2 times the cache size. /// /// The maximum allowed value for `FLUSH_SIZE` multiplied by `FLUSH_STRIDE` is 2 MB for a typical /// maximum supported cache size of 1 MB. Larger cache sizes are supported using `WBINVD`=1. /// /// This value is ignored if `WBINVD`=1. /// /// This field is maintained for ACPI 1.0 processor compatibility on existing systems. /// /// Processors in new ACPI-compatible systems are required to support the WBINVD function and indicate this to OSPM /// by setting the `WBINVD` field = 1. FLUSH_SIZE: u16 align(1), /// If `WBINVD`=0, the value of this field is the cache line width, in bytes, of the processor’s memory caches. /// /// This value is typically the smallest cache line width on any of the processor’s caches. /// /// For more information, see the description of the `FLUSH_SIZE` field. /// /// This value is ignored if `WBINVD`=1. /// /// This field is maintained for ACPI 1.0 processor compatibility on existing systems. /// /// Processors in new ACPI-compatible systems are required to support the WBINVD function and indicate this to OSPM /// by setting the `WBINVD` field = 1. FLUSH_STRIDE: u16 align(1), /// The zero-based index of where the processor’s duty cycle setting is within the processor’s P_CNT register. DUTY_OFFSET: u8, /// The bit width of the processor’s duty cycle setting value in the P_CNT register. /// /// Each processor’s duty cycle setting allows the software to select a nominal processor frequency below its /// absolute frequency as defined by: /// /// `THTL_EN = 1 BF * DC/(2DUTY_WIDTH)` /// /// Where: /// - BF: Base frequency /// - DC: Duty cycle setting /// /// When THTL_EN is 0, the processor runs at its absolute BF. /// /// A `DUTY_WIDTH` value of 0 indicates that processor duty cycle is not supported and the processor continuously /// runs at its base frequency. DUTY_WIDTH: u8, /// The RTC CMOS RAM index to the day-of-month alarm value. /// /// If this field contains a zero, then the RTC day of the month alarm feature is not supported. /// /// If this field has a non-zero value, then this field contains an index into RTC RAM space that OSPM can use to /// program the day of the month alarm. DAY_ALRM: u8, /// The RTC CMOS RAM index to the month of year alarm value. /// /// If this field contains a zero, then the RTC month of the year alarm feature is not supported. /// /// If this field has a non-zero value, then this field contains an index into RTC RAM space that OSPM can use to /// program the month of the year alarm. /// /// If this feature is supported, then the DAY_ALRM feature must be supported also. MON_ALRM: u8, /// The RTC CMOS RAM index to the century of data value (hundred and thousand year decimals). /// /// If this field contains a zero, then the RTC centenary feature is not supported. /// /// If this field has a non-zero value, then this field contains an index into RTC RAM space that OSPM can use to /// program the centenary field. CENTURY: u8, /// IA-PC Boot Architecture Flags. /// /// This set of flags is used by an OS to guide the assumptions it can make in initializing hardware on IA-PC /// platforms. /// /// These flags are used by an OS at boot time (before the OS is capable of providing an operating environment /// suitable for parsing the ACPI namespace) to determine the code paths to take during boot. /// /// In IA-PC platforms with reduced legacy hardware, the OS can skip code paths for legacy devices if none are /// present. /// /// For example, if there are no ISA devices, an OS could skip code that assumes the presence of these devices and /// their associated resources. /// /// These flags are used independently of the ACPI namespace. /// /// The presence of other devices must be described in the ACPI namespace. /// /// These flags pertain only to IA-PC platforms. On other system architectures, the entire field should be set to 0. IA_PC_BOOT_ARCH: IA_PC_ARCHITECHTURE_FLAGS align(1), _reserved2: u8, /// Fixed feature flags. fixed_feature_flags: FixedFeatureFlags align(1), /// The address of the reset register. /// /// Note: Only System I/O space, System Memory space and PCI Configuration space (bus #0) are valid for values for /// `address_space`. /// /// Also, `register_bit_width` must be 8 and `register_bit_offset` must be 0 RESET_REG: acpi.Address align(1), /// Indicates the value to write to the `RESET_REG` port to reset the system. RESET_VALUE: u8, /// ARM Boot Architecture Flags. ARM_BOOT_ARCH: ARM_ARCHITECHTURE_FLAGS align(1), /// Minor Version of this FADT structure, in "Major.Minor" form, where 'Major' is the value in the /// `header.version` field. /// /// Bits 0-3 - The low order bits correspond to the minor version of the specification version. /// /// For instance, ACPI 6.3 has a major version of 6, and a minor version of 3. /// /// Bits 4-7 - The high order bits correspond to the version of the ACPI Specification errata this table complies /// with. /// /// A value of 0 means that it complies with the base version of the current specification. /// /// A value of 1 means this is compatible with Errata A, 2 would be compatible with Errata B, and so on. FADT_minor_version: u8, /// Extended physical address of the FACS. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `FIRMWARE_CTRL` field must be /// ignored by the OSPM. /// /// If `fixed_feature_flags.HARDWARE_REDUCED_ACPI` flag is set, and both this field and the `FIRMWARE_CTRL` field /// are zero, there is no FACS available X_FIRMWARE_CTRL: core.PhysicalAddress align(1), /// Extended physical address of the DSDT. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `DSDT` field must be ignored /// by the OSPM. X_DSDT: core.PhysicalAddress align(1), /// Extended address of the PM1a Event Register Block. /// /// This is a required field /// /// If this field contains a nonzero value which can be used by the OSPM, then the `PM1a_EVT_BLK` field must be /// ignored by the OSPM. X_PM1a_EVT_BLK: acpi.Address align(1), /// Extended address of the PM1b Event Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `PM1b_EVT_BLK` field must be /// ignored by the OSPM X_PM1b_EVT_BLK: acpi.Address align(1), /// Extended address of the PM1a Control Register Block. /// /// This is a required field. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `PM1a_CNT_BLK` field must be /// ignored by the OSPM. X_PM1a_CNT_BLK: acpi.Address align(1), /// Extended address of the PM1b Control Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `PM1b_CNT_BLK` field must be /// ignored by the OSPM. X_PM1b_CNT_BLK: acpi.Address align(1), /// Extended address of the PM2 Control Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `PM2_CNT_BLK` field must be /// ignored by the OSPM. X_PM2_CNT_BLK: acpi.Address align(1), /// Extended address of the Power Management Timer Control Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `PM_TMR_BLK` field must be /// ignored by the OSPM. X_PM_TMR_BLK: acpi.Address align(1), /// Extended address of the General-Purpose Event 0 Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `GPE0_BLK` field must be /// ignored by the OSPM. /// /// Note: Only System I/O space and System Memory space are valid for `address_space` values, and the OSPM ignores /// `register_bit_width`, `register_bit_offset` and `access_size`. X_GPE0_BLK: acpi.Address align(1), /// Extended address of the General-Purpose Event 1 Register Block. /// /// This field is optional; if this register block is not supported, this field contains zero. /// /// If this field contains a nonzero value which can be used by the OSPM, then the `GPE1_BLK` field must be /// ignored by the OSPM. /// /// Note: Only System I/O space and System Memory space are valid for `address_space` values, and the OSPM ignores /// `register_bit_width`, `register_bit_offset` and `access_size`. X_GPE1_BLK: acpi.Address align(1), /// The address of the Sleep register. /// /// Note: Only System I/O space, System Memory space and PCI Configuration space (bus #0) are valid for values for /// `address_space`. /// /// Also, `register_bit_width` must be 8 and `register_bit_offset` must be 0. SLEEP_CONTROL_REG: acpi.Address align(1), /// The address of the Sleep status register. /// /// Note: Only System I/O space, System Memory space and PCI Configuration space (bus #0) are valid for values for /// `address_space`. /// /// Also, `register_bit_width` must be 8 and `register_bit_offset` must be 0. SLEEP_STATUS_REG: acpi.Address align(1), /// 64-bit identifier of hypervisor vendor. /// /// All bytes in this field are considered part of the vendor identity. /// /// These identifiers are defined independently by the vendors themselves, usually following the name of the /// hypervisor product. /// /// Version information should NOT be included in this field - this shall simply denote the vendor's name or /// identifier. /// /// Version information can be communicated through a supplemental vendor-specific hypervisor API. /// /// Firmware implementers would place zero bytes into this field, denoting that no hypervisor is present in the /// actual firmware. hypervisor_vedor_identity: u64 align(1), pub const SIGNATURE_STRING = "FACP"; pub const PowerManagementProfile = enum(u8) { unspecified = 0, /// A single user, full featured, stationary computing device that resides on or near an individual’s work area. /// /// Most often contains one processor. /// /// Must be connected to AC power to function. /// /// This device is used to perform work that is considered mainstream corporate or home computing /// (for example, word processing, Internet browsing, spreadsheets, and so on). desktop = 1, /// A single-user, full-featured, portable computing device that is capable of running on batteries or other /// power storage devices to perform its normal functions. /// /// Most often contains one processor. /// /// This device performs the same task set as a desktop. However it may have limitations dues to its size, /// thermal requirements, and/or power source life. mobile = 2, /// A single-user, full-featured, stationary computing device that resides on or near an individual's work area. /// /// Often contains more than one processor. /// /// Must be connected to AC power to function. /// /// This device is used to perform large quantities of computations in support of such work as CAD/CAM and /// other graphics-intensive applications. workstation = 3, /// A multi-user, stationary computing device that frequently resides in a separate, often specially designed, room. /// /// Will almost always contain more than one processor. /// /// Must be connected to AC power to function. /// /// This device is used to support large-scale networking, database, communications, or financial /// operations within a corporation or government. enterprise_server = 4, /// A multi-user, stationary computing device that frequently resides in a separate area or room in a small or /// home office. /// /// May contain more than one processor. /// /// Must be connected to AC power to function. /// /// This device is generally used to support all of the networking, database, communications, and financial /// operations of a small office or home office. soho_server = 5, /// A device specifically designed to operate in a low-noise, high-availability environment such as a /// consumer's living rooms or family room. /// /// Most often contains one processor. /// /// This category also includes home Internet gateways, Web pads, set top boxes and other devices that support ACPI. /// /// Must be connected to AC power to function. /// /// Normally they are sealed case style and may only perform a subset of the tasks normally associated with /// today's personal computers appliance_pc = 6, /// A multi-user stationary computing device that frequently resides in a separate, often specially designed room. /// /// Will often contain more than one processor. /// /// Must be connected to AC power to function. /// /// This device is used in an environment where power savings features are willing to be sacrificed for /// better performance and quicker responsiveness performance_server = 7, /// A full-featured, highly mobile computing device which resembles writing tablets and which users interact /// with primarily through a touch interface. /// /// The touch digitizer is the primary user input device, although a keyboard and/or mouse may be present. /// /// Tablet devices typically run on battery power and are generally only plugged into AC power in order to charge. /// /// This device performs many of the same tasks as Mobile; however battery life expectations of Tablet devices /// generally require more aggressive power savings especially for managing display and touch components. tablet = 8, _, }; pub const FixedFeatureFlags = packed struct(u32) { /// Processor properly implements a functional equivalent to the WBINVD IA-32 instruction. /// /// If set, signifies that the WBINVD instruction correctly flushes the processor caches, maintains memory /// coherency, and upon completion of the instruction, all caches for the current processor contain no /// cached data other than what OSPM references and allows to be cached. /// /// If this flag is not set, the ACPI OS is responsible for disabling all ACPI features that need this function. /// /// This field is maintained for ACPI 1.0 processor compatibility on existing systems. /// /// Processors in new ACPI-compatible systems are required to support this function and indicate this to OSPM /// by setting this field. WBINVD: bool, /// If set, indicates that the hardware flushes all caches on the WBINVD instruction and maintains memory /// coherency, but does not guarantee the caches are invalidated. /// /// This provides the complete semantics of the WBINVD instruction, and provides enough to support the /// system sleeping states. /// /// If neither of the WBINVD flags is set, the system will require FLUSH_SIZE and FLUSH_STRIDE to support /// sleeping states. /// /// If the FLUSH parameters are also not supported, the machine cannot support sleeping states S1, S2, or S3. WBINVD_FLUSH: bool, /// `true` indicates that the C1 power state is supported on all processors. PROC_C1: bool, /// A `false` indicates that the C2 power state is configured to only work on a uniprocessor (UP) system. /// /// A one indicates that the C2 power state is configured to work on a UP or multiprocessor (MP) system. P_LVL2_UP: bool, /// A `false` indicates the power button is handled as a fixed feature programming model; a `true` indicates /// the power button is handled as a control method device. /// /// If the system does not have a power button, this value would be `true` and no power button device would /// be present. /// /// Independent of the value of this field, the presence of a power button device in the namespace indicates /// to OSPM that the power button is handled as a control method device. PWR_BUTTON: bool, /// A `false` indicates the sleep button is handled as a fixed feature programming model; a `true` indicates /// the sleep button is handled as a control method device. /// /// If the system does not have a sleep button, this value would be `true` and no sleep button device would /// be present. /// /// Independent of the value of this field, the presence of a sleep button device in the namespace indicates /// to OSPM that the sleep button is handled as a control method device. SLP_BUTTON: bool, /// A `false` indicates the RTC wake status is supported in fixed register space; a `true` indicates the RTC /// wake status is not supported in fixed register space. FIX_RTC: bool, /// Indicates whether the RTC alarm function can wake the system from the S4 state. /// /// The RTC must be able to wake the system from an S1, S2, or S3 sleep state. /// /// The RTC alarm can optionally support waking the system from the S4 state, as indicated by this value. RTC_S4: bool, /// A `false` indicates TMR_VAL is implemented as a 24-bit value. /// /// A `true` indicates TMR_VAL is implemented as a 32-bit value. /// /// The TMR_STS bit is set when the most significant bit of the TMR_VAL toggles TMR_VAL_EXT: bool, /// A `false` indicates that the system cannot support docking. /// /// A `true` indicates that the system can support docking. /// /// Notice that this flag does not indicate whether or not a docking station is currently present; /// it only indicates that the system is capable of docking. DCK_CAP: bool, /// If set, indicates the system supports system reset via the FADT RESET_REG. RESET_REG_SUP: bool, /// System Type Attribute. /// /// If set indicates that the system has no internal expansion capabilities and the case is sealed. SEALED_CASE: bool, /// System Type Attribute. /// /// If set indicates the system cannot detect the monitor or keyboard / mouse devices. HEADLESS: bool, /// If set, indicates to OSPM that a processor native instruction must be executed after writing /// the SLP_TYPx register. CPU_SW_SLP: bool, /// If set, indicates the platform supports the PCI-EXP_WAKE_STS bit in the PM1 Status register and the /// PCIEXP_WAKE_EN bit in the PM1 Enable register. /// /// This bit must be set on platforms containing chipsets that implement PCI Express and supports PM1 PCIEXP_WAK bits. PCI_EXP_WAK: bool, /// A value of `true` indicates that OSPM should use a platform provided timer to drive any monotonically /// non-decreasing counters, such as OSPM performance counter services. /// /// Which particular platform timer will be used is OSPM specific, however, it is recommended that the timer /// used is based on the following algorithm: If the HPET is exposed to OSPM, OSPM should use the HPET. /// Otherwise, OSPM will use the ACPI power management timer. /// /// A value of `true` indicates that the platform is known to have a correctly implemented ACPI power management /// timer. /// /// A platform may choose to set this flag if a internal processor clock (or clocks in a multi-processor /// configuration) cannot provide consistent monotonically non-decreasing counters. /// /// Note: If a value of `false` is present, OSPM may arbitrarily choose to use an internal processor clock or a /// platform timer clock for these operations. That is, a `false` does not imply that OSPM will necessarily use /// the internal processor clock to generate a monotonically non-decreasing counter to the system. USE_PLATFORM_CLOCK: bool, /// A `true` indicates that the contents of the RTC_STS flag is valid when waking the system from S4. /// /// Some existing systems do not reliably set this input today, and this bit allows OSPM to differentiate /// correctly functioning platforms from platforms with this errata. S4_RTC_STS_VALID: bool, /// A `true` indicates that the platform is compatible with remote power-on. /// /// That is, the platform supports OSPM leaving GPE wake events armed prior to an S5 transition. /// /// Some existing platforms do not reliably transition to S5 with wake events enabled (for example, the /// platform may immediately generate a spurious wake event after completing the S5 transition). /// /// This flag allows OSPM to differentiate correctly functioning platforms from platforms with this type of errata. REMOTE_POWER_ON_CAPABLE: bool, /// A `true` indicates that all local APICs must be configured for the cluster destination model when delivering /// interrupts in logical mode. /// /// If this bit is set, then logical mode interrupt delivery operation may be undefined until OSPM has moved all /// local APICs to the cluster model. /// /// Note that the cluster destination model doesn’t apply to Itanium Processor Family (IPF) local SAPICs. /// /// This bit is intended for xAPIC based machines that require the cluster destination model even when 8 or /// fewer local APICs are present in the machine. FORCE_APIC_CLUSTER_MODEL: bool, /// A `true` indicates that all local xAPICs must be configured for physical destination mode. /// /// If this bit is set, interrupt delivery operation in logical destination mode is undefined. /// /// On machines that contain fewer than 8 local xAPICs or that do not use the xAPIC architecture, this bit is ignored. FORCE_APIC_PHYSICAL_DESTINATION_MODE: bool, /// A one indicates that the Hardware-Reduced ACPI is implemented, therefore software-only alternatives are used /// for supported fixed-features. HW_REDUCED_ACPI: bool, /// A `true` informs OSPM that the platform is able to achieve power savings in S0 similar to or better than /// those typically achieved in S3. /// /// In effect, when this bit is set it indicates that the system will achieve no power benefit by making a sleep /// transition to S3. LOW_POWER_S0_IDLE_CAPABLE: bool, /// Described whether cpu caches and any other caches that are coherent with them, are considered by the /// platform to be persistent. /// /// The platform evaluates the configuration present at system startup to determine this value. /// /// System configuration changes after system startup may invalidate this. PERSISTENT_CPU_CACHES: PersistentCpuCaches, _reserved: u8, pub const PersistentCpuCaches = enum(u2) { /// Not reported by the platform. /// /// Software should reference the NFIT Platform Capabilities. not_supported = 0b00, /// Cpu caches and any other caches that are coherent with them, are not persistent. /// /// Software is responsible for flushing data from cpu caches to make stores persistent. /// /// Supersedes NFIT Platform Capabilities. not_persistent = 0b01, /// Cpu caches and any other caches that are coherent with them, are persistent. /// /// Supersedes NFIT Platform Capabilities. /// /// When reporting this state, the platform shall provide enough stored energy for ALL of the following: /// - Time to flush cpu caches and any other caches that are coherent with them /// - Time of all targets of those flushes to complete flushing stored data /// - If supporting hot plug, the worst case CXL device topology that can be hotplugged persistent = 0b10, reserved = 0b11, }; }; pub const IA_PC_ARCHITECHTURE_FLAGS = packed struct(u16) { /// If set, indicates that the motherboard supports user-visible devices on the LPC or ISA bus. /// /// User-visible devices are devices that have end-user accessible connectors (for example, LPT port), or /// devices for which the OS must load a device driver so that an end-user application can use a device. /// /// If clear, the OS may assume there are no such devices and that all devices in the system can be detected /// exclusively via industry standard device enumeration mechanisms (including the ACPI namespace). LEGACY_DEVICES: bool, /// If set, indicates that the motherboard contains support for a port 60 and 64 based keyboard controller, /// usually implemented as an 8042 or equivalent micro-controller. @"8042": bool, /// If set, indicates to OSPM that it must not blindly probe the VGA hardware /// (that responds to MMIO addresses A0000h-BFFFFh and IO ports 3B0h-3BBh and 3C0h-3DFh) that may cause machine /// check on this system. /// /// If clear, indicates to OSPM that it is safe to probe the VGA hardware vga_not_present: bool, /// If set, indicates to OSPM that it must not enable Message Signaled Interrupts (MSI) on this platform. msi_not_supported: bool, /// If set, indicates to OSPM that it must not enable OSPM ASPM control on this platform. pcie_aspm_controls: bool, /// If set, indicates that the CMOS RTC is either not implemented, or does not exist at the legacy addresses. /// /// OSPM uses the Control Method Time and Alarm Namespace device instead. cmos_rtc_not_present: bool, _reserved: u10, }; pub const ARM_ARCHITECHTURE_FLAGS = packed struct(u16) { /// `true` if PSCI is implemented. PSCI_COMPLIANT: bool, /// `true` if HVC must be used as the PSCI conduit, instead of SMC. PSCI_USE_HVC: bool, _reserved: u14, }; comptime { core.testing.expectSize(@This(), 276); } }; comptime { refAllDeclsRecursive(@This()); } // Copy of `std.testing.refAllDeclsRecursive`, being in the file give access to private decls. fn refAllDeclsRecursive(comptime T: type) void { if (!@import("builtin").is_test) return; inline for (switch (@typeInfo(T)) { .Struct => |info| info.decls, .Enum => |info| info.decls, .Union => |info| info.decls, .Opaque => |info| info.decls, else => @compileError("Expected struct, enum, union, or opaque type, found '" ++ @typeName(T) ++ "'"), }) |decl| { if (@TypeOf(@field(T, decl.name)) == type) { switch (@typeInfo(@field(T, decl.name))) { .Struct, .Enum, .Union, .Opaque => refAllDeclsRecursive(@field(T, decl.name)), else => {}, } } _ = &@field(T, decl.name); } }
https://raw.githubusercontent.com/CascadeOS/CascadeOS/07e8248e8a189b1ff74c21b60f0eb80bfe6f9574/lib/acpi/FADT.zig
const expect = @import("std").testing.expect; test "if statement" { const a = true; var x: u16 = 0; if (a) { x += 1; } else { x += 2; } try expect(x == 1); }
https://raw.githubusercontent.com/Sobeston/zig.guide/a49e8a20cd5b3699fc1510f3c9c2c5a698869358/website/versioned_docs/version-0.12/01-language-basics/03.expect.zig
const Procedures = @import("procedures.zig"); const PhysAlloc = @import("phys_alloc.zig"); const std = @import("std"); pub const ModuleSpec = struct { name: []const u8, init: ?*const fn () void, deinit: ?*const fn () void, }; pub var loaded_modules: std.ArrayList(ModuleSpec) = undefined; // TODO: Support for deinit pub fn init() void { loaded_modules = std.ArrayList(ModuleSpec).init(PhysAlloc.allocator()); } pub fn init_modules(modules: []const ModuleSpec) !void { for (modules) |module| { if (module.init) |init_| { init_(); try loaded_modules.append(module); Procedures.write_fmt("Module {s} successfully initialized\n", .{module.name}) catch {}; } } }
https://raw.githubusercontent.com/sawcce/mimi/527c2076c556b187d4fb82e0cac882b25ae7c0e3/kernel/src/modules/module.zig
const std = @import("std"); fn root() []const u8 { return std.fs.path.dirname(@src().file) orelse "."; } const root_path = root() ++ "/"; pub const include_dir = root_path ++ "curl/include"; const package_path = root_path ++ "src/main.zig"; const lib_dir = root_path ++ "curl/lib"; pub const Define = struct { key: []const u8, value: ?[]const u8, }; pub const Options = struct { import_name: ?[]const u8 = null, }; pub const Library = struct { exported_defines: []Define, step: *std.build.LibExeObjStep, pub fn link(self: Library, other: *std.build.LibExeObjStep, opts: Options) void { for (self.exported_defines) |def| other.defineCMacro(def.key, def.value); other.addIncludePath(.{ .path = include_dir }); other.linkLibrary(self.step); if (opts.import_name) |import_name| other.addAnonymousModule( import_name, .{ .source_file = .{ .path = package_path } }, ); } }; pub fn create( b: *std.build.Builder, target: std.zig.CrossTarget, optimize: std.builtin.OptimizeMode, ) !Library { const ret = b.addStaticLibrary(.{ .name = "curl", .target = target, .optimize = optimize, }); ret.addCSourceFiles(srcs, &.{}); ret.addIncludePath(.{ .path = include_dir }); ret.addIncludePath(.{ .path = lib_dir }); ret.linkLibC(); var exported_defines = std.ArrayList(Define).init(b.allocator); defer exported_defines.deinit(); ret.defineCMacro("BUILDING_LIBCURL", null); // when not building a shared library ret.defineCMacro("CURL_STATICLIB", "1"); try exported_defines.append(.{ .key = "CURL_STATICLIB", .value = "1" }); // disables LDAP ret.defineCMacro("CURL_DISABLE_LDAP", "1"); // disables LDAPS ret.defineCMacro("CURL_DISABLE_LDAPS", "1"); // if mbedTLS is enabled ret.defineCMacro("USE_MBEDTLS", "1"); // disables alt-svc // #undef CURL_DISABLE_ALTSVC // disables cookies support // #undef CURL_DISABLE_COOKIES // disables cryptographic authentication // #undef CURL_DISABLE_CRYPTO_AUTH // disables DICT ret.defineCMacro("CURL_DISABLE_DICT", "1"); // disables DNS-over-HTTPS // #undef CURL_DISABLE_DOH // disables FILE ret.defineCMacro("CURL_DISABLE_FILE", "1"); // disables FTP ret.defineCMacro("CURL_DISABLE_FTP", "1"); // disables GOPHER ret.defineCMacro("CURL_DISABLE_GOPHER", "1"); // disables HSTS support // #undef CURL_DISABLE_HSTS // disables HTTP // #undef CURL_DISABLE_HTTP // disables IMAP ret.defineCMacro("CURL_DISABLE_IMAP", "1"); // disables --libcurl option from the curl tool // #undef CURL_DISABLE_LIBCURL_OPTION // disables MIME support // #undef CURL_DISABLE_MIME // disables MQTT ret.defineCMacro("CURL_DISABLE_MQTT", "1"); // disables netrc parser // #undef CURL_DISABLE_NETRC // disables NTLM support // #undef CURL_DISABLE_NTLM // disables date parsing // #undef CURL_DISABLE_PARSEDATE // disables POP3 ret.defineCMacro("CURL_DISABLE_POP3", "1"); // disables built-in progress meter // #undef CURL_DISABLE_PROGRESS_METER // disables proxies // #undef CURL_DISABLE_PROXY // disables RTSP ret.defineCMacro("CURL_DISABLE_RTSP", "1"); // disables SMB ret.defineCMacro("CURL_DISABLE_SMB", "1"); // disables SMTP ret.defineCMacro("CURL_DISABLE_SMTP", "1"); // disables use of socketpair for curl_multi_poll // #undef CURL_DISABLE_SOCKETPAIR // disables TELNET ret.defineCMacro("CURL_DISABLE_TELNET", "1"); // disables TFTP ret.defineCMacro("CURL_DISABLE_TFTP", "1"); // disables verbose strings // #undef CURL_DISABLE_VERBOSE_STRINGS // Define to 1 if you have the `ssh2' library (-lssh2). // ret.defineCMacro("HAVE_LIBSSH2", "1"); // Define to 1 if you have the <libssh2.h> header file. // ret.defineCMacro("HAVE_LIBSSH2_H", "1"); // if zlib is available ret.defineCMacro("HAVE_LIBZ", "1"); // if you have the zlib.h header file ret.defineCMacro("HAVE_ZLIB_H", "1"); if (target.isWindows()) { // Define if you want to enable WIN32 threaded DNS lookup //ret.defineCMacro("USE_THREADS_WIN32", "1"); return Library{ .step = ret, .exported_defines = try exported_defines.toOwnedSlice() }; } //ret.defineCMacro("libcurl_EXPORTS", null); //ret.defineCMacro("STDC_HEADERS", null); // when building libcurl itself // #undef BUILDING_LIBCURL // Location of default ca bundle // ret.defineCMacro("CURL_CA_BUNDLE", "\"/etc/ssl/certs/ca-certificates.crt\""); // define "1" to use built-in ca store of TLS backend // #undef CURL_CA_FALLBACK // Location of default ca path // ret.defineCMacro("CURL_CA_PATH", "\"/etc/ssl/certs\""); // to make a symbol visible ret.defineCMacro("CURL_EXTERN_SYMBOL", "__attribute__ ((__visibility__ (\"default\"))"); // Ensure using CURL_EXTERN_SYMBOL is possible //#ifndef CURL_EXTERN_SYMBOL //ret.defineCMacro("CURL_EXTERN_SYMBOL //#endif // Allow SMB to work on Windows // #undef USE_WIN32_CRYPTO // Use Windows LDAP implementation // #undef USE_WIN32_LDAP // your Entropy Gathering Daemon socket pathname // #undef EGD_SOCKET // Define if you want to enable IPv6 support if (!target.isDarwin()) ret.defineCMacro("ENABLE_IPV6", "1"); // Define to 1 if you have the alarm function. ret.defineCMacro("HAVE_ALARM", "1"); // Define to 1 if you have the <alloca.h> header file. ret.defineCMacro("HAVE_ALLOCA_H", "1"); // Define to 1 if you have the <arpa/inet.h> header file. ret.defineCMacro("HAVE_ARPA_INET_H", "1"); // Define to 1 if you have the <arpa/tftp.h> header file. ret.defineCMacro("HAVE_ARPA_TFTP_H", "1"); // Define to 1 if you have the <assert.h> header file. ret.defineCMacro("HAVE_ASSERT_H", "1"); // Define to 1 if you have the `basename' function. ret.defineCMacro("HAVE_BASENAME", "1"); // Define to 1 if bool is an available type. ret.defineCMacro("HAVE_BOOL_T", "1"); // Define to 1 if you have the __builtin_available function. ret.defineCMacro("HAVE_BUILTIN_AVAILABLE", "1"); // Define to 1 if you have the clock_gettime function and monotonic timer. ret.defineCMacro("HAVE_CLOCK_GETTIME_MONOTONIC", "1"); // Define to 1 if you have the `closesocket' function. // #undef HAVE_CLOSESOCKET // Define to 1 if you have the `CRYPTO_cleanup_all_ex_data' function. // #undef HAVE_CRYPTO_CLEANUP_ALL_EX_DATA // Define to 1 if you have the <dlfcn.h> header file. ret.defineCMacro("HAVE_DLFCN_H", "1"); // Define to 1 if you have the <errno.h> header file. ret.defineCMacro("HAVE_ERRNO_H", "1"); // Define to 1 if you have the fcntl function. ret.defineCMacro("HAVE_FCNTL", "1"); // Define to 1 if you have the <fcntl.h> header file. ret.defineCMacro("HAVE_FCNTL_H", "1"); // Define to 1 if you have a working fcntl O_NONBLOCK function. ret.defineCMacro("HAVE_FCNTL_O_NONBLOCK", "1"); // Define to 1 if you have the freeaddrinfo function. ret.defineCMacro("HAVE_FREEADDRINFO", "1"); // Define to 1 if you have the ftruncate function. ret.defineCMacro("HAVE_FTRUNCATE", "1"); // Define to 1 if you have a working getaddrinfo function. ret.defineCMacro("HAVE_GETADDRINFO", "1"); // Define to 1 if you have the `geteuid' function. ret.defineCMacro("HAVE_GETEUID", "1"); // Define to 1 if you have the `getppid' function. ret.defineCMacro("HAVE_GETPPID", "1"); // Define to 1 if you have the gethostbyname function. ret.defineCMacro("HAVE_GETHOSTBYNAME", "1"); // Define to 1 if you have the gethostbyname_r function. if (!target.isDarwin()) ret.defineCMacro("HAVE_GETHOSTBYNAME_R", "1"); // gethostbyname_r() takes 3 args // #undef HAVE_GETHOSTBYNAME_R_3 // gethostbyname_r() takes 5 args // #undef HAVE_GETHOSTBYNAME_R_5 // gethostbyname_r() takes 6 args ret.defineCMacro("HAVE_GETHOSTBYNAME_R_6", "1"); // Define to 1 if you have the gethostname function. ret.defineCMacro("HAVE_GETHOSTNAME", "1"); // Define to 1 if you have a working getifaddrs function. // #undef HAVE_GETIFADDRS // Define to 1 if you have the `getpass_r' function. // #undef HAVE_GETPASS_R // Define to 1 if you have the `getppid' function. ret.defineCMacro("HAVE_GETPPID", "1"); // Define to 1 if you have the `getprotobyname' function. ret.defineCMacro("HAVE_GETPROTOBYNAME", "1"); // Define to 1 if you have the `getpeername' function. ret.defineCMacro("HAVE_GETPEERNAME", "1"); // Define to 1 if you have the `getsockname' function. ret.defineCMacro("HAVE_GETSOCKNAME", "1"); // Define to 1 if you have the `if_nametoindex' function. ret.defineCMacro("HAVE_IF_NAMETOINDEX", "1"); // Define to 1 if you have the `getpwuid' function. ret.defineCMacro("HAVE_GETPWUID", "1"); // Define to 1 if you have the `getpwuid_r' function. ret.defineCMacro("HAVE_GETPWUID_R", "1"); // Define to 1 if you have the `getrlimit' function. ret.defineCMacro("HAVE_GETRLIMIT", "1"); // Define to 1 if you have the `gettimeofday' function. ret.defineCMacro("HAVE_GETTIMEOFDAY", "1"); // Define to 1 if you have a working glibc-style strerror_r function. // #undef HAVE_GLIBC_STRERROR_R // Define to 1 if you have a working gmtime_r function. ret.defineCMacro("HAVE_GMTIME_R", "1"); // if you have the gssapi libraries // #undef HAVE_GSSAPI // Define to 1 if you have the <gssapi/gssapi_generic.h> header file. // #undef HAVE_GSSAPI_GSSAPI_GENERIC_H // Define to 1 if you have the <gssapi/gssapi.h> header file. // #undef HAVE_GSSAPI_GSSAPI_H // Define to 1 if you have the <gssapi/gssapi_krb5.h> header file. // #undef HAVE_GSSAPI_GSSAPI_KRB5_H // if you have the GNU gssapi libraries // #undef HAVE_GSSGNU // if you have the Heimdal gssapi libraries // #undef HAVE_GSSHEIMDAL // if you have the MIT gssapi libraries // #undef HAVE_GSSMIT // Define to 1 if you have the `idna_strerror' function. // #undef HAVE_IDNA_STRERROR // Define to 1 if you have the `idn_free' function. // #undef HAVE_IDN_FREE // Define to 1 if you have the <idn-free.h> header file. // #undef HAVE_IDN_FREE_H // Define to 1 if you have the <ifaddrs.h> header file. ret.defineCMacro("HAVE_IFADDRS_H", "1"); // Define to 1 if you have the `inet_addr' function. ret.defineCMacro("HAVE_INET_ADDR", "1"); // Define to 1 if you have a IPv6 capable working inet_ntop function. // #undef HAVE_INET_NTOP // Define to 1 if you have a IPv6 capable working inet_pton function. ret.defineCMacro("HAVE_INET_PTON", "1"); // Define to 1 if symbol `sa_family_t' exists ret.defineCMacro("HAVE_SA_FAMILY_T", "1"); // Define to 1 if symbol `ADDRESS_FAMILY' exists // #undef HAVE_ADDRESS_FAMILY // Define to 1 if you have the <inttypes.h> header file. ret.defineCMacro("HAVE_INTTYPES_H", "1"); // Define to 1 if you have the ioctl function. ret.defineCMacro("HAVE_IOCTL", "1"); // Define to 1 if you have the ioctlsocket function. // #undef HAVE_IOCTLSOCKET // Define to 1 if you have the IoctlSocket camel case function. // #undef HAVE_IOCTLSOCKET_CAMEL // Define to 1 if you have a working IoctlSocket camel case FIONBIO function. // #undef HAVE_IOCTLSOCKET_CAMEL_FIONBIO // Define to 1 if you have a working ioctlsocket FIONBIO function. // #undef HAVE_IOCTLSOCKET_FIONBIO // Define to 1 if you have a working ioctl FIONBIO function. ret.defineCMacro("HAVE_IOCTL_FIONBIO", "1"); // Define to 1 if you have a working ioctl SIOCGIFADDR function. ret.defineCMacro("HAVE_IOCTL_SIOCGIFADDR", "1"); // Define to 1 if you have the <io.h> header file. // #undef HAVE_IO_H // if you have the Kerberos4 libraries (including -ldes) // #undef HAVE_KRB4 // Define to 1 if you have the `krb_get_our_ip_for_realm' function. // #undef HAVE_KRB_GET_OUR_IP_FOR_REALM // Define to 1 if you have the <krb.h> header file. // #undef HAVE_KRB_H // Define to 1 if you have the lber.h header file. // #undef HAVE_LBER_H // Define to 1 if you have the ldapssl.h header file. // #undef HAVE_LDAPSSL_H // Define to 1 if you have the ldap.h header file. // #undef HAVE_LDAP_H // Use LDAPS implementation // #undef HAVE_LDAP_SSL // Define to 1 if you have the ldap_ssl.h header file. // #undef HAVE_LDAP_SSL_H // Define to 1 if you have the `ldap_url_parse' function. ret.defineCMacro("HAVE_LDAP_URL_PARSE", "1"); // Define to 1 if you have the <libgen.h> header file. ret.defineCMacro("HAVE_LIBGEN_H", "1"); // Define to 1 if you have the `idn2' library (-lidn2). // #undef HAVE_LIBIDN2 // Define to 1 if you have the idn2.h header file. ret.defineCMacro("HAVE_IDN2_H", "1"); // Define to 1 if you have the `resolv' library (-lresolv). // #undef HAVE_LIBRESOLV // Define to 1 if you have the `resolve' library (-lresolve). // #undef HAVE_LIBRESOLVE // Define to 1 if you have the `socket' library (-lsocket). // #undef HAVE_LIBSOCKET // if brotli is available // #undef HAVE_BROTLI // if zstd is available // #undef HAVE_ZSTD // if your compiler supports LL ret.defineCMacro("HAVE_LL", "1"); // Define to 1 if you have the <locale.h> header file. ret.defineCMacro("HAVE_LOCALE_H", "1"); // Define to 1 if you have a working localtime_r function. ret.defineCMacro("HAVE_LOCALTIME_R", "1"); // Define to 1 if the compiler supports the 'long long' data type. ret.defineCMacro("HAVE_LONGLONG", "1"); // Define to 1 if you have the malloc.h header file. ret.defineCMacro("HAVE_MALLOC_H", "1"); // Define to 1 if you have the <memory.h> header file. ret.defineCMacro("HAVE_MEMORY_H", "1"); // Define to 1 if you have the MSG_NOSIGNAL flag. if (!target.isDarwin()) ret.defineCMacro("HAVE_MSG_NOSIGNAL", "1"); // Define to 1 if you have the <netdb.h> header file. ret.defineCMacro("HAVE_NETDB_H", "1"); // Define to 1 if you have the <netinet/in.h> header file. ret.defineCMacro("HAVE_NETINET_IN_H", "1"); // Define to 1 if you have the <netinet/tcp.h> header file. ret.defineCMacro("HAVE_NETINET_TCP_H", "1"); // Define to 1 if you have the <linux/tcp.h> header file. if (target.isLinux()) ret.defineCMacro("HAVE_LINUX_TCP_H", "1"); // Define to 1 if you have the <net/if.h> header file. ret.defineCMacro("HAVE_NET_IF_H", "1"); // Define to 1 if NI_WITHSCOPEID exists and works. // #undef HAVE_NI_WITHSCOPEID // if you have an old MIT gssapi library, lacking GSS_C_NT_HOSTBASED_SERVICE // #undef HAVE_OLD_GSSMIT // Define to 1 if you have the <pem.h> header file. // #undef HAVE_PEM_H // Define to 1 if you have the `pipe' function. ret.defineCMacro("HAVE_PIPE", "1"); // Define to 1 if you have a working poll function. ret.defineCMacro("HAVE_POLL", "1"); // If you have a fine poll ret.defineCMacro("HAVE_POLL_FINE", "1"); // Define to 1 if you have the <poll.h> header file. ret.defineCMacro("HAVE_POLL_H", "1"); // Define to 1 if you have a working POSIX-style strerror_r function. ret.defineCMacro("HAVE_POSIX_STRERROR_R", "1"); // Define to 1 if you have the <pthread.h> header file ret.defineCMacro("HAVE_PTHREAD_H", "1"); // Define to 1 if you have the <pwd.h> header file. ret.defineCMacro("HAVE_PWD_H", "1"); // Define to 1 if you have the `RAND_egd' function. // #undef HAVE_RAND_EGD // Define to 1 if you have the `RAND_screen' function. // #undef HAVE_RAND_SCREEN // Define to 1 if you have the `RAND_status' function. // #undef HAVE_RAND_STATUS // Define to 1 if you have the recv function. ret.defineCMacro("HAVE_RECV", "1"); // Define to 1 if you have the recvfrom function. // #undef HAVE_RECVFROM // Define to 1 if you have the select function. ret.defineCMacro("HAVE_SELECT", "1"); // Define to 1 if you have the send function. ret.defineCMacro("HAVE_SEND", "1"); // Define to 1 if you have the 'fsetxattr' function. ret.defineCMacro("HAVE_FSETXATTR", "1"); // fsetxattr() takes 5 args ret.defineCMacro("HAVE_FSETXATTR_5", "1"); // fsetxattr() takes 6 args // #undef HAVE_FSETXATTR_6 // Define to 1 if you have the <setjmp.h> header file. ret.defineCMacro("HAVE_SETJMP_H", "1"); // Define to 1 if you have the `setlocale' function. ret.defineCMacro("HAVE_SETLOCALE", "1"); // Define to 1 if you have the `setmode' function. // #undef HAVE_SETMODE // Define to 1 if you have the `setrlimit' function. ret.defineCMacro("HAVE_SETRLIMIT", "1"); // Define to 1 if you have the setsockopt function. ret.defineCMacro("HAVE_SETSOCKOPT", "1"); // Define to 1 if you have a working setsockopt SO_NONBLOCK function. // #undef HAVE_SETSOCKOPT_SO_NONBLOCK // Define to 1 if you have the sigaction function. ret.defineCMacro("HAVE_SIGACTION", "1"); // Define to 1 if you have the siginterrupt function. ret.defineCMacro("HAVE_SIGINTERRUPT", "1"); // Define to 1 if you have the signal function. ret.defineCMacro("HAVE_SIGNAL", "1"); // Define to 1 if you have the <signal.h> header file. ret.defineCMacro("HAVE_SIGNAL_H", "1"); // Define to 1 if you have the sigsetjmp function or macro. ret.defineCMacro("HAVE_SIGSETJMP", "1"); // Define to 1 if struct sockaddr_in6 has the sin6_scope_id member ret.defineCMacro("HAVE_SOCKADDR_IN6_SIN6_SCOPE_ID", "1"); // Define to 1 if you have the `socket' function. ret.defineCMacro("HAVE_SOCKET", "1"); // Define to 1 if you have the <stdbool.h> header file. ret.defineCMacro("HAVE_STDBOOL_H", "1"); // Define to 1 if you have the <stdint.h> header file. ret.defineCMacro("HAVE_STDINT_H", "1"); // Define to 1 if you have the <stdio.h> header file. ret.defineCMacro("HAVE_STDIO_H", "1"); // Define to 1 if you have the <stdlib.h> header file. ret.defineCMacro("HAVE_STDLIB_H", "1"); // Define to 1 if you have the strcasecmp function. ret.defineCMacro("HAVE_STRCASECMP", "1"); // Define to 1 if you have the strcasestr function. // #undef HAVE_STRCASESTR // Define to 1 if you have the strcmpi function. // #undef HAVE_STRCMPI // Define to 1 if you have the strdup function. ret.defineCMacro("HAVE_STRDUP", "1"); // Define to 1 if you have the strerror_r function. ret.defineCMacro("HAVE_STRERROR_R", "1"); // Define to 1 if you have the stricmp function. // #undef HAVE_STRICMP // Define to 1 if you have the <strings.h> header file. ret.defineCMacro("HAVE_STRINGS_H", "1"); // Define to 1 if you have the <string.h> header file. ret.defineCMacro("HAVE_STRING_H", "1"); // Define to 1 if you have the strncmpi function. // #undef HAVE_STRNCMPI // Define to 1 if you have the strnicmp function. // #undef HAVE_STRNICMP // Define to 1 if you have the <stropts.h> header file. // #undef HAVE_STROPTS_H // Define to 1 if you have the strstr function. ret.defineCMacro("HAVE_STRSTR", "1"); // Define to 1 if you have the strtok_r function. ret.defineCMacro("HAVE_STRTOK_R", "1"); // Define to 1 if you have the strtoll function. ret.defineCMacro("HAVE_STRTOLL", "1"); // if struct sockaddr_storage is defined ret.defineCMacro("HAVE_STRUCT_SOCKADDR_STORAGE", "1"); // Define to 1 if you have the timeval struct. ret.defineCMacro("HAVE_STRUCT_TIMEVAL", "1"); // Define to 1 if you have the <sys/filio.h> header file. // #undef HAVE_SYS_FILIO_H // Define to 1 if you have the <sys/ioctl.h> header file. ret.defineCMacro("HAVE_SYS_IOCTL_H", "1"); // Define to 1 if you have the <sys/param.h> header file. ret.defineCMacro("HAVE_SYS_PARAM_H", "1"); // Define to 1 if you have the <sys/poll.h> header file. ret.defineCMacro("HAVE_SYS_POLL_H", "1"); // Define to 1 if you have the <sys/resource.h> header file. ret.defineCMacro("HAVE_SYS_RESOURCE_H", "1"); // Define to 1 if you have the <sys/select.h> header file. ret.defineCMacro("HAVE_SYS_SELECT_H", "1"); // Define to 1 if you have the <sys/socket.h> header file. ret.defineCMacro("HAVE_SYS_SOCKET_H", "1"); // Define to 1 if you have the <sys/sockio.h> header file. // #undef HAVE_SYS_SOCKIO_H // Define to 1 if you have the <sys/stat.h> header file. ret.defineCMacro("HAVE_SYS_STAT_H", "1"); // Define to 1 if you have the <sys/time.h> header file. ret.defineCMacro("HAVE_SYS_TIME_H", "1"); // Define to 1 if you have the <sys/types.h> header file. ret.defineCMacro("HAVE_SYS_TYPES_H", "1"); // Define to 1 if you have the <sys/uio.h> header file. ret.defineCMacro("HAVE_SYS_UIO_H", "1"); // Define to 1 if you have the <sys/un.h> header file. ret.defineCMacro("HAVE_SYS_UN_H", "1"); // Define to 1 if you have the <sys/utime.h> header file. // #undef HAVE_SYS_UTIME_H // Define to 1 if you have the <termios.h> header file. ret.defineCMacro("HAVE_TERMIOS_H", "1"); // Define to 1 if you have the <termio.h> header file. ret.defineCMacro("HAVE_TERMIO_H", "1"); // Define to 1 if you have the <time.h> header file. ret.defineCMacro("HAVE_TIME_H", "1"); // Define to 1 if you have the <tld.h> header file. // #undef HAVE_TLD_H // Define to 1 if you have the `tld_strerror' function. // #undef HAVE_TLD_STRERROR // Define to 1 if you have the `uname' function. ret.defineCMacro("HAVE_UNAME", "1"); // Define to 1 if you have the <unistd.h> header file. ret.defineCMacro("HAVE_UNISTD_H", "1"); // Define to 1 if you have the `utime' function. ret.defineCMacro("HAVE_UTIME", "1"); // Define to 1 if you have the `utimes' function. ret.defineCMacro("HAVE_UTIMES", "1"); // Define to 1 if you have the <utime.h> header file. ret.defineCMacro("HAVE_UTIME_H", "1"); // Define to 1 if compiler supports C99 variadic macro style. ret.defineCMacro("HAVE_VARIADIC_MACROS_C99", "1"); // Define to 1 if compiler supports old gcc variadic macro style. ret.defineCMacro("HAVE_VARIADIC_MACROS_GCC", "1"); // Define to 1 if you have the winber.h header file. // #undef HAVE_WINBER_H // Define to 1 if you have the windows.h header file. // #undef HAVE_WINDOWS_H // Define to 1 if you have the winldap.h header file. // #undef HAVE_WINLDAP_H // Define to 1 if you have the winsock2.h header file. // #undef HAVE_WINSOCK2_H // Define this symbol if your OS supports changing the contents of argv // #undef HAVE_WRITABLE_ARGV // Define to 1 if you have the writev function. // #undef HAVE_WRITEV // Define to 1 if you have the ws2tcpip.h header file. // #undef HAVE_WS2TCPIP_H // Define to 1 if you have the <x509.h> header file. // #undef HAVE_X509_H // Define if you have the <process.h> header file. // #undef HAVE_PROCESS_H // Define to the sub-directory in which libtool stores uninstalled libraries. // #undef LT_OBJDIR // If you lack a fine basename() prototype // #undef NEED_BASENAME_PROTO // Define to 1 if you need the lber.h header file even with ldap.h // #undef NEED_LBER_H // Define to 1 if you need the malloc.h header file even with stdlib.h // #undef NEED_MALLOC_H // Define to 1 if _REENTRANT preprocessor symbol must be defined. // #undef NEED_REENTRANT // cpu-machine-OS ret.defineCMacro("OS", "\"Linux\""); // Name of package // #undef PACKAGE // Define to the address where bug reports for this package should be sent. // #undef PACKAGE_BUGREPORT // Define to the full name of this package. // #undef PACKAGE_NAME // Define to the full name and version of this package. // #undef PACKAGE_STRING // Define to the one symbol short name of this package. // #undef PACKAGE_TARNAME // Define to the version of this package. // #undef PACKAGE_VERSION // a suitable file to read random data from ret.defineCMacro("RANDOM_FILE", "\"/dev/urandom\""); // Define to the type of arg 1 for recvfrom. // #undef RECVFROM_TYPE_ARG1 // Define to the type pointed by arg 2 for recvfrom. // #undef RECVFROM_TYPE_ARG2 // Define to 1 if the type pointed by arg 2 for recvfrom is void. // #undef RECVFROM_TYPE_ARG2_IS_VOID // Define to the type of arg 3 for recvfrom. // #undef RECVFROM_TYPE_ARG3 // Define to the type of arg 4 for recvfrom. // #undef RECVFROM_TYPE_ARG4 // Define to the type pointed by arg 5 for recvfrom. // #undef RECVFROM_TYPE_ARG5 // Define to 1 if the type pointed by arg 5 for recvfrom is void. // #undef RECVFROM_TYPE_ARG5_IS_VOID // Define to the type pointed by arg 6 for recvfrom. // #undef RECVFROM_TYPE_ARG6 // Define to 1 if the type pointed by arg 6 for recvfrom is void. // #undef RECVFROM_TYPE_ARG6_IS_VOID // Define to the function return type for recvfrom. // #undef RECVFROM_TYPE_RETV // Define to the type of arg 1 for recv. ret.defineCMacro("RECV_TYPE_ARG1", "int"); // Define to the type of arg 2 for recv. ret.defineCMacro("RECV_TYPE_ARG2", "void *"); // Define to the type of arg 3 for recv. ret.defineCMacro("RECV_TYPE_ARG3", "size_t"); // Define to the type of arg 4 for recv. ret.defineCMacro("RECV_TYPE_ARG4", "int"); // Define to the function return type for recv. ret.defineCMacro("RECV_TYPE_RETV", "ssize_t"); // Define to the type qualifier of arg 5 for select. // #undef SELECT_QUAL_ARG5 // Define to the type of arg 1 for select. // #undef SELECT_TYPE_ARG1 // Define to the type of args 2, 3 and 4 for select. // #undef SELECT_TYPE_ARG234 // Define to the type of arg 5 for select. // #undef SELECT_TYPE_ARG5 // Define to the function return type for select. // #undef SELECT_TYPE_RETV // Define to the type qualifier of arg 2 for send. ret.defineCMacro("SEND_QUAL_ARG2", "const"); // Define to the type of arg 1 for send. ret.defineCMacro("SEND_TYPE_ARG1", "int"); // Define to the type of arg 2 for send. ret.defineCMacro("SEND_TYPE_ARG2", "void *"); // Define to the type of arg 3 for send. ret.defineCMacro("SEND_TYPE_ARG3", "size_t"); // Define to the type of arg 4 for send. ret.defineCMacro("SEND_TYPE_ARG4", "int"); // Define to the function return type for send. ret.defineCMacro("SEND_TYPE_RETV", "ssize_t"); // Note: SIZEOF_* variables are fetched with CMake through check_type_size(). // As per CMake documentation on CheckTypeSize, C preprocessor code is // generated by CMake into SIZEOF_*_CODE. This is what we use in the // following statements. // // Reference: https://cmake.org/cmake/help/latest/module/CheckTypeSize.html // The size of `int', as computed by sizeof. ret.defineCMacro("SIZEOF_INT", "4"); // The size of `short', as computed by sizeof. ret.defineCMacro("SIZEOF_SHORT", "2"); // The size of `long', as computed by sizeof. ret.defineCMacro("SIZEOF_LONG", "8"); // The size of `off_t', as computed by sizeof. ret.defineCMacro("SIZEOF_OFF_T", "8"); // The size of `curl_off_t', as computed by sizeof. ret.defineCMacro("SIZEOF_CURL_OFF_T", "8"); // The size of `size_t', as computed by sizeof. ret.defineCMacro("SIZEOF_SIZE_T", "8"); // The size of `time_t', as computed by sizeof. ret.defineCMacro("SIZEOF_TIME_T", "8"); // Define to 1 if you have the ANSI C header files. ret.defineCMacro("STDC_HEADERS", "1"); // Define to the type of arg 3 for strerror_r. // #undef STRERROR_R_TYPE_ARG3 // Define to 1 if you can safely include both <sys/time.h> and <time.h>. ret.defineCMacro("TIME_WITH_SYS_TIME", "1"); // Define if you want to enable c-ares support // #undef USE_ARES // Define if you want to enable POSIX threaded DNS lookup ret.defineCMacro("USE_THREADS_POSIX", "1"); // if libSSH2 is in use // ret.defineCMacro("USE_LIBSSH2", "1"); // If you want to build curl with the built-in manual // #undef USE_MANUAL // if NSS is enabled // #undef USE_NSS // if you have the PK11_CreateManagedGenericObject function // #undef HAVE_PK11_CREATEMANAGEDGENERICOBJECT // if you want to use OpenLDAP code instead of legacy ldap implementation // #undef USE_OPENLDAP // to enable NGHTTP2 // #undef USE_NGHTTP2 // to enable NGTCP2 // #undef USE_NGTCP2 // to enable NGHTTP3 // #undef USE_NGHTTP3 // to enable quiche // #undef USE_QUICHE // Define to 1 if you have the quiche_conn_set_qlog_fd function. // #undef HAVE_QUICHE_CONN_SET_QLOG_FD // if Unix domain sockets are enabled ret.defineCMacro("USE_UNIX_SOCKETS", null); // Define to 1 if you are building a Windows target with large file support. // #undef USE_WIN32_LARGE_FILES // to enable SSPI support // #undef USE_WINDOWS_SSPI // to enable Windows SSL // #undef USE_SCHANNEL // enable multiple SSL backends // #undef CURL_WITH_MULTI_SSL // Define to 1 if using yaSSL in OpenSSL compatibility mode. // #undef USE_YASSLEMUL // Version number of package // #undef VERSION // Define to 1 if OS is AIX. //#ifndef _ALL_SOURCE //# undef _ALL_SOURCE //#endif // Number of bits in a file offset, on hosts where this is settable. ret.defineCMacro("_FILE_OFFSET_BITS", "64"); // Define for large files, on AIX-style hosts. // #undef _LARGE_FILES // define this if you need it to compile thread-safe code // #undef _THREAD_SAFE // Define to empty if `const' does not conform to ANSI C. // #undef const // Type to use in place of in_addr_t when system does not provide it. // #undef in_addr_t // Define to `__inline__' or `__inline' if that's what the C compiler // calls it, or to nothing if 'inline' is not supported under any name. //#ifndef __cplusplus //#undef inline //#endif // Define to `unsigned int' if <sys/types.h> does not define. // #undef size_t // the signed version of size_t // #undef ssize_t // Define to 1 if you have the mach_absolute_time function. // #undef HAVE_MACH_ABSOLUTE_TIME // to enable Windows IDN // #undef USE_WIN32_IDN // to make the compiler know the prototypes of Windows IDN APIs // #undef WANT_IDN_PROTOTYPES return Library{ .step = ret, .exported_defines = try exported_defines.toOwnedSlice() }; } const srcs = &.{ root_path ++ "curl/lib/hostcheck.c", root_path ++ "curl/lib/curl_gethostname.c", root_path ++ "curl/lib/strerror.c", root_path ++ "curl/lib/strdup.c", root_path ++ "curl/lib/asyn-ares.c", root_path ++ "curl/lib/pop3.c", root_path ++ "curl/lib/bufref.c", root_path ++ "curl/lib/rename.c", root_path ++ "curl/lib/nwlib.c", root_path ++ "curl/lib/file.c", root_path ++ "curl/lib/curl_gssapi.c", root_path ++ "curl/lib/ldap.c", root_path ++ "curl/lib/socketpair.c", root_path ++ "curl/lib/system_win32.c", root_path ++ "curl/lib/http_aws_sigv4.c", root_path ++ "curl/lib/content_encoding.c", root_path ++ "curl/lib/vquic/ngtcp2.c", root_path ++ "curl/lib/vquic/quiche.c", root_path ++ "curl/lib/vquic/vquic.c", root_path ++ "curl/lib/ftp.c", root_path ++ "curl/lib/curl_ntlm_wb.c", root_path ++ "curl/lib/curl_ntlm_core.c", root_path ++ "curl/lib/hostip.c", root_path ++ "curl/lib/urlapi.c", root_path ++ "curl/lib/curl_get_line.c", root_path ++ "curl/lib/vtls/mesalink.c", root_path ++ "curl/lib/vtls/mbedtls_threadlock.c", root_path ++ "curl/lib/vtls/nss.c", root_path ++ "curl/lib/vtls/gskit.c", root_path ++ "curl/lib/vtls/wolfssl.c", root_path ++ "curl/lib/vtls/keylog.c", root_path ++ "curl/lib/vtls/rustls.c", root_path ++ "curl/lib/vtls/vtls.c", root_path ++ "curl/lib/vtls/gtls.c", root_path ++ "curl/lib/vtls/schannel.c", root_path ++ "curl/lib/vtls/schannel_verify.c", root_path ++ "curl/lib/vtls/sectransp.c", root_path ++ "curl/lib/vtls/openssl.c", root_path ++ "curl/lib/vtls/mbedtls.c", root_path ++ "curl/lib/vtls/bearssl.c", root_path ++ "curl/lib/parsedate.c", root_path ++ "curl/lib/sendf.c", root_path ++ "curl/lib/altsvc.c", root_path ++ "curl/lib/krb5.c", root_path ++ "curl/lib/curl_rtmp.c", root_path ++ "curl/lib/curl_ctype.c", root_path ++ "curl/lib/inet_pton.c", root_path ++ "curl/lib/pingpong.c", root_path ++ "curl/lib/mime.c", root_path ++ "curl/lib/vauth/krb5_gssapi.c", root_path ++ "curl/lib/vauth/krb5_sspi.c", root_path ++ "curl/lib/vauth/spnego_sspi.c", root_path ++ "curl/lib/vauth/digest.c", root_path ++ "curl/lib/vauth/ntlm_sspi.c", root_path ++ "curl/lib/vauth/vauth.c", root_path ++ "curl/lib/vauth/gsasl.c", root_path ++ "curl/lib/vauth/cram.c", root_path ++ "curl/lib/vauth/oauth2.c", root_path ++ "curl/lib/vauth/digest_sspi.c", root_path ++ "curl/lib/vauth/cleartext.c", root_path ++ "curl/lib/vauth/spnego_gssapi.c", root_path ++ "curl/lib/vauth/ntlm.c", root_path ++ "curl/lib/version_win32.c", root_path ++ "curl/lib/multi.c", root_path ++ "curl/lib/http_ntlm.c", root_path ++ "curl/lib/curl_sspi.c", root_path ++ "curl/lib/md5.c", root_path ++ "curl/lib/dict.c", root_path ++ "curl/lib/http.c", root_path ++ "curl/lib/curl_des.c", root_path ++ "curl/lib/memdebug.c", root_path ++ "curl/lib/non-ascii.c", root_path ++ "curl/lib/transfer.c", root_path ++ "curl/lib/inet_ntop.c", root_path ++ "curl/lib/slist.c", root_path ++ "curl/lib/http_negotiate.c", root_path ++ "curl/lib/http_digest.c", root_path ++ "curl/lib/vssh/wolfssh.c", root_path ++ "curl/lib/vssh/libssh.c", root_path ++ "curl/lib/vssh/libssh2.c", root_path ++ "curl/lib/hsts.c", root_path ++ "curl/lib/escape.c", root_path ++ "curl/lib/hostsyn.c", root_path ++ "curl/lib/speedcheck.c", root_path ++ "curl/lib/asyn-thread.c", root_path ++ "curl/lib/curl_addrinfo.c", root_path ++ "curl/lib/nwos.c", root_path ++ "curl/lib/tftp.c", root_path ++ "curl/lib/version.c", root_path ++ "curl/lib/rand.c", root_path ++ "curl/lib/psl.c", root_path ++ "curl/lib/imap.c", root_path ++ "curl/lib/mqtt.c", root_path ++ "curl/lib/share.c", root_path ++ "curl/lib/doh.c", root_path ++ "curl/lib/curl_range.c", root_path ++ "curl/lib/openldap.c", root_path ++ "curl/lib/getinfo.c", root_path ++ "curl/lib/select.c", root_path ++ "curl/lib/base64.c", root_path ++ "curl/lib/curl_sasl.c", root_path ++ "curl/lib/curl_endian.c", root_path ++ "curl/lib/connect.c", root_path ++ "curl/lib/fileinfo.c", root_path ++ "curl/lib/telnet.c", root_path ++ "curl/lib/x509asn1.c", root_path ++ "curl/lib/conncache.c", root_path ++ "curl/lib/strcase.c", root_path ++ "curl/lib/if2ip.c", root_path ++ "curl/lib/gopher.c", root_path ++ "curl/lib/ftplistparser.c", root_path ++ "curl/lib/setopt.c", root_path ++ "curl/lib/idn_win32.c", root_path ++ "curl/lib/strtoofft.c", root_path ++ "curl/lib/hmac.c", root_path ++ "curl/lib/getenv.c", root_path ++ "curl/lib/smb.c", root_path ++ "curl/lib/dotdot.c", root_path ++ "curl/lib/curl_threads.c", root_path ++ "curl/lib/md4.c", root_path ++ "curl/lib/easygetopt.c", root_path ++ "curl/lib/curl_fnmatch.c", root_path ++ "curl/lib/sha256.c", root_path ++ "curl/lib/cookie.c", root_path ++ "curl/lib/amigaos.c", root_path ++ "curl/lib/progress.c", root_path ++ "curl/lib/nonblock.c", root_path ++ "curl/lib/llist.c", root_path ++ "curl/lib/hostip6.c", root_path ++ "curl/lib/dynbuf.c", root_path ++ "curl/lib/warnless.c", root_path ++ "curl/lib/hostasyn.c", root_path ++ "curl/lib/http_chunks.c", root_path ++ "curl/lib/wildcard.c", root_path ++ "curl/lib/strtok.c", root_path ++ "curl/lib/curl_memrchr.c", root_path ++ "curl/lib/rtsp.c", root_path ++ "curl/lib/http2.c", root_path ++ "curl/lib/socks.c", root_path ++ "curl/lib/curl_path.c", root_path ++ "curl/lib/curl_multibyte.c", root_path ++ "curl/lib/http_proxy.c", root_path ++ "curl/lib/formdata.c", root_path ++ "curl/lib/netrc.c", root_path ++ "curl/lib/socks_sspi.c", root_path ++ "curl/lib/mprintf.c", root_path ++ "curl/lib/easyoptions.c", root_path ++ "curl/lib/easy.c", root_path ++ "curl/lib/c-hyper.c", root_path ++ "curl/lib/hostip4.c", root_path ++ "curl/lib/timeval.c", root_path ++ "curl/lib/smtp.c", root_path ++ "curl/lib/splay.c", root_path ++ "curl/lib/socks_gssapi.c", root_path ++ "curl/lib/url.c", root_path ++ "curl/lib/hash.c", };
https://raw.githubusercontent.com/renerocksai/gpt4all.zig/6fd8327a75c945ba4d0d681a5eaab89d49e0b553/src/zig-libcurl/libcurl.zig
const std = @import("std"); const network = @import("network"); const uri = @import("uri"); const serve = @import("serve.zig"); const logger = std.log.scoped(.serve_gemini); pub const GeminiListener = struct { const Binding = struct { address: network.Address, port: u16, socket: ?network.Socket, tls: serve.TlsCore, }; allocator: std.mem.Allocator, bindings: std.ArrayList(Binding), /// Normalize incoming paths for the client, so a query to `"/"`, `"//"` and `""` are equivalent and will all receive /// `"/"` as the path. normalize_paths: bool = true, pub fn init(allocator: std.mem.Allocator) !GeminiListener { return GeminiListener{ .allocator = allocator, .bindings = std.ArrayList(Binding).init(allocator), }; } pub fn deinit(self: *GeminiListener) void { for (self.bindings.items) |*bind| { bind.tls.deinit(); if (bind.socket) |*sock| { sock.close(); } } self.bindings.deinit(); self.* = undefined; } const AddEndpointError = error{ AlreadyExists, AlreadyStarted, TlsError, InvalidCertificate, OutOfMemory }; pub fn addEndpoint( self: *GeminiListener, target_ip: serve.IP, port: u16, certificate_file: []const u8, key_file: []const u8, ) AddEndpointError!void { for (self.bindings.items) |*bind| { if (bind.socket != null) return error.AlreadyStarted; } var tls = serve.TlsCore.init() catch return error.TlsError; errdefer tls.deinit(); var temp = std.heap.ArenaAllocator.init(self.allocator); defer temp.deinit(); tls.useCertifcateFile(try temp.allocator().dupeZ(u8, certificate_file)) catch return error.InvalidCertificate; tls.usePrivateKeyFile(try temp.allocator().dupeZ(u8, key_file)) catch return error.InvalidCertificate; var bind = Binding{ .address = target_ip.convertToNetwork(), .port = port, .socket = null, .tls = tls, }; for (self.bindings.items) |*other| { if (std.meta.eql(other.*, bind)) return error.AlreadyExists; } try self.bindings.append(bind); } pub const StartError = std.os.SocketError || std.os.BindError || std.os.ListenError || error{ NoBindings, AlreadyStarted }; pub fn start(self: *GeminiListener) StartError!void { if (self.bindings.items.len == 0) { return error.NoBindings; } for (self.bindings.items) |*bind| { if (bind.socket != null) return error.AlreadyStarted; } errdefer for (self.bindings.items) |*bind| { if (bind.socket) |*sock| { sock.close(); } bind.socket = null; }; for (self.bindings.items) |*bind| { var sock = try network.Socket.create(std.meta.activeTag(bind.address), .tcp); errdefer sock.close(); sock.enablePortReuse(true) catch |e| logger.err("Failed to enable port reuse: {s}", .{@errorName(e)}); try sock.bind(.{ .address = bind.address, .port = bind.port }); try sock.listen(); bind.socket = sock; } } pub fn stop(self: *GeminiListener) void { for (self.bindings.items) |*bind| { if (bind.socket) |*sock| { sock.close(); } bind.socket = null; } } const GetContextError = std.os.PollError || std.os.AcceptError || network.Socket.Reader.Error || error{ UnsupportedAddressFamily, NotStarted, OutOfMemory, EndOfStream, StreamTooLong }; pub fn getContext(self: *GeminiListener) GetContextError!*GeminiContext { for (self.bindings.items) |*bind| { if (bind.socket == null) return error.NotStarted; } var set = try network.SocketSet.init(self.allocator); defer set.deinit(); while (true) { for (self.bindings.items) |*bind| { try set.add(bind.socket.?, .{ .read = true, .write = false }); } const events = try network.waitForSocketEvent(&set, null); std.debug.assert(events >= 1); var any_error = false; for (self.bindings.items) |*bind| { if (set.isReadyRead(bind.socket.?)) { return self.acceptContext(bind.socket.?, &bind.tls) catch |e| { logger.warn("Invalid incoming connection: {s}", .{@errorName(e)}); any_error = true; continue; }; } } // This means something very terrible has gone wrong std.debug.assert(any_error); } } fn acceptContext(self: *GeminiListener, sock: network.Socket, tls: *serve.TlsCore) !*GeminiContext { var client_sock: network.Socket = try sock.accept(); errdefer client_sock.close(); logger.debug("accepted tcp connection from {!}", .{client_sock.getRemoteEndPoint()}); var temp_memory = std.heap.ArenaAllocator.init(self.allocator); errdefer temp_memory.deinit(); const context = try temp_memory.allocator().create(GeminiContext); context.* = GeminiContext{ .memory = temp_memory, .request = GeminiRequest{ .url = undefined, .requested_server_name = null, .client_certificate = null, }, .response = GeminiResponse{ .socket = client_sock, .ssl = undefined, }, }; context.response.ssl = try tls.accept(&context.response.socket); errdefer context.response.ssl.close(); logger.debug("accepted tls connection", .{}); context.request.client_certificate = try context.response.ssl.getPeerCertificate(); context.request.requested_server_name = try context.response.ssl.getServerNameIndication(context.memory.allocator()); var url_buffer: [2048]u8 = undefined; var reader = context.response.ssl.reader(); var url_string = try reader.readUntilDelimiter(&url_buffer, '\n'); if (std.mem.endsWith(u8, url_string, "\r")) { url_string = url_string[0 .. url_string.len - 1]; } logger.info("request for {s}", .{url_string}); const url_string_owned = try context.memory.allocator().dupeZ(u8, url_string); context.request.url = try uri.parse(url_string_owned); return context; } }; pub const GeminiContext = struct { memory: std.heap.ArenaAllocator, request: GeminiRequest, response: GeminiResponse, fn finalize(self: *GeminiContext) !void { if (!self.response.is_writing) { try self.response.writeHeader(); } } pub fn deinit(self: *GeminiContext) void { self.finalize() catch |e| logger.warn("Failed to finalize connection: {s}", .{@errorName(e)}); logger.debug("closing tcp connection to {!}", .{self.response.socket.getRemoteEndPoint()}); self.response.ssl.close(); self.response.socket.close(); var copy = self.memory; copy.deinit(); } }; pub const GeminiRequest = struct { url: uri.UriComponents, client_certificate: ?serve.TlsCore.Certificate, requested_server_name: ?[]const u8, }; pub const GeminiResponse = struct { pub const buffer_size = 1024; const BufferedWriter = std.io.BufferedWriter(buffer_size, network.Socket.Writer); socket: network.Socket, ssl: serve.TlsClient, is_writing: bool = false, status_code: GeminiStatusCode = .success, meta: std.ArrayListUnmanaged(u8) = .{}, fn getAllocator(self: *GeminiResponse) std.mem.Allocator { return @fieldParentPtr(GeminiContext, "response", self).memory.allocator(); } pub fn setStatusCode(self: *GeminiResponse, status_code: GeminiStatusCode) !void { std.debug.assert(self.is_writing == false); self.status_code = status_code; if (self.meta.items.len == 0) { try self.meta.appendSlice(self.getAllocator(), switch (status_code) { .input => "input", .sensitive_input => "sensitive input", .success => "application/octet-stream", .temporary_redirect => "temporary redirect", .permanent_redirect => "permanent redirect", .temporary_failure => "temporary failure", .server_unavailable => "server unavailable", .cgi_error => "cgi error", .proxy_error => "proxy error", .slow_down => "slow down", .permanent_failure => "permanent failure", .not_found => "not found", .gone => "gone", .proxy_request_refused => "proxy request refused", .bad_request => "bad request", .client_certificate_required => "client certificate required", .certificate_not_authorised => "certificate not authorised", .certificate_not_valid => "certificate not valid", else => switch (@enumToInt(status_code) / 10) { 0 => "undefined", 1 => "input", 2 => "success", 3 => "redirect", 4 => "temporary failure", 5 => "permanent failure", 6 => "client certificate required", 7 => "undefined", 8 => "undefined", 9 => "undefined", else => unreachable, }, }); } } pub fn setMeta(self: *GeminiResponse, text: []const u8) !void { std.debug.assert(self.is_writing == false); self.meta.shrinkRetainingCapacity(0); try self.meta.appendSlice(self.getAllocator(), text); } fn writeHeader(self: *GeminiResponse) !void { try self.ssl.writer().print("{}{} {s}\r\n", .{ (@enumToInt(self.status_code) / 10) % 10, (@enumToInt(self.status_code) / 1) % 10, self.meta.items, }); } pub fn writer(self: *GeminiResponse) !serve.TlsClient.Writer { std.debug.assert(self.status_code.class() == .success); if (!self.is_writing) { try self.writeHeader(); } self.is_writing = true; return self.ssl.writer(); } }; pub const GeminiStatusClass = enum(u4) { input = 1, success = 2, redirect = 3, temporary_failure = 4, permanent_failure = 5, client_certificate_required = 6, }; pub const GeminiStatusCode = enum(u8) { input = 10, sensitive_input = 11, success = 20, temporary_redirect = 30, permanent_redirect = 31, temporary_failure = 40, server_unavailable = 41, cgi_error = 42, proxy_error = 43, slow_down = 44, permanent_failure = 50, not_found = 51, gone = 52, proxy_request_refused = 53, bad_request = 59, client_certificate_required = 60, certificate_not_authorised = 61, certificate_not_valid = 62, _, // other status codes are legal as well pub fn class(self: GeminiStatusCode) GeminiStatusClass { return @intToEnum(GeminiStatusClass, @truncate(u4, @enumToInt(self) / 10)); } };
https://raw.githubusercontent.com/ikskuh/zig-serve/2e11e5671d52c256c66bd4d60b1e5975fb9f27f8/src/gemini.zig
const std = @import("std.zig"); const builtin = @import("builtin"); const unicode = std.unicode; const io = std.io; const fs = std.fs; const os = std.os; const process = std.process; const File = std.fs.File; const windows = os.windows; const linux = os.linux; const mem = std.mem; const math = std.math; const debug = std.debug; const EnvMap = process.EnvMap; const maxInt = std.math.maxInt; const assert = std.debug.assert; pub const ChildProcess = struct { pub const Id = switch (builtin.os.tag) { .windows => windows.HANDLE, .wasi => void, else => os.pid_t, }; /// Available after calling `spawn()`. This becomes `undefined` after calling `wait()`. /// On Windows this is the hProcess. /// On POSIX this is the pid. id: Id, thread_handle: if (builtin.os.tag == .windows) windows.HANDLE else void, allocator: mem.Allocator, stdin: ?File, stdout: ?File, stderr: ?File, term: ?(SpawnError!Term), argv: []const []const u8, /// Leave as null to use the current env map using the supplied allocator. env_map: ?*const EnvMap, stdin_behavior: StdIo, stdout_behavior: StdIo, stderr_behavior: StdIo, /// Set to change the user id when spawning the child process. uid: if (builtin.os.tag == .windows or builtin.os.tag == .wasi) void else ?os.uid_t, /// Set to change the group id when spawning the child process. gid: if (builtin.os.tag == .windows or builtin.os.tag == .wasi) void else ?os.gid_t, /// Set to change the current working directory when spawning the child process. cwd: ?[]const u8, /// Set to change the current working directory when spawning the child process. /// This is not yet implemented for Windows. See https://github.com/ziglang/zig/issues/5190 /// Once that is done, `cwd` will be deprecated in favor of this field. cwd_dir: ?fs.Dir = null, err_pipe: ?if (builtin.os.tag == .windows) void else [2]os.fd_t, expand_arg0: Arg0Expand, /// Darwin-only. Disable ASLR for the child process. disable_aslr: bool = false, /// Darwin-only. Start child process in suspended state as if SIGSTOP was sent. start_suspended: bool = false, /// Set to true to obtain rusage information for the child process. /// Depending on the target platform and implementation status, the /// requested statistics may or may not be available. If they are /// available, then the `resource_usage_statistics` field will be populated /// after calling `wait`. /// On Linux and Darwin, this obtains rusage statistics from wait4(). request_resource_usage_statistics: bool = false, /// This is available after calling wait if /// `request_resource_usage_statistics` was set to `true` before calling /// `spawn`. resource_usage_statistics: ResourceUsageStatistics = .{}, pub const ResourceUsageStatistics = struct { rusage: @TypeOf(rusage_init) = rusage_init, /// Returns the peak resident set size of the child process, in bytes, /// if available. pub inline fn getMaxRss(rus: ResourceUsageStatistics) ?usize { switch (builtin.os.tag) { .linux => { if (rus.rusage) |ru| { return @as(usize, @intCast(ru.maxrss)) * 1024; } else { return null; } }, .windows => { if (rus.rusage) |ru| { return ru.PeakWorkingSetSize; } else { return null; } }, .macos, .ios => { if (rus.rusage) |ru| { // Darwin oddly reports in bytes instead of kilobytes. return @as(usize, @intCast(ru.maxrss)); } else { return null; } }, else => return null, } } const rusage_init = switch (builtin.os.tag) { .linux, .macos, .ios => @as(?std.os.rusage, null), .windows => @as(?windows.VM_COUNTERS, null), else => {}, }; }; pub const Arg0Expand = os.Arg0Expand; pub const SpawnError = error{ OutOfMemory, /// POSIX-only. `StdIo.Ignore` was selected and opening `/dev/null` returned ENODEV. NoDevice, /// Windows-only. One of: /// * `cwd` was provided and it could not be re-encoded into UTF16LE, or /// * The `PATH` or `PATHEXT` environment variable contained invalid UTF-8. InvalidUtf8, /// Windows-only. `cwd` was provided, but the path did not exist when spawning the child process. CurrentWorkingDirectoryUnlinked, } || os.ExecveError || os.SetIdError || os.ChangeCurDirError || windows.CreateProcessError || windows.GetProcessMemoryInfoError || windows.WaitForSingleObjectError; pub const Term = union(enum) { Exited: u8, Signal: u32, Stopped: u32, Unknown: u32, }; pub const StdIo = enum { Inherit, Ignore, Pipe, Close, }; /// First argument in argv is the executable. pub fn init(argv: []const []const u8, allocator: mem.Allocator) ChildProcess { return .{ .allocator = allocator, .argv = argv, .id = undefined, .thread_handle = undefined, .err_pipe = null, .term = null, .env_map = null, .cwd = null, .uid = if (builtin.os.tag == .windows or builtin.os.tag == .wasi) {} else null, .gid = if (builtin.os.tag == .windows or builtin.os.tag == .wasi) {} else null, .stdin = null, .stdout = null, .stderr = null, .stdin_behavior = StdIo.Inherit, .stdout_behavior = StdIo.Inherit, .stderr_behavior = StdIo.Inherit, .expand_arg0 = .no_expand, }; } pub fn setUserName(self: *ChildProcess, name: []const u8) !void { const user_info = try std.process.getUserInfo(name); self.uid = user_info.uid; self.gid = user_info.gid; } /// On success must call `kill` or `wait`. /// After spawning the `id` is available. pub fn spawn(self: *ChildProcess) SpawnError!void { if (!std.process.can_spawn) { @compileError("the target operating system cannot spawn processes"); } if (builtin.os.tag == .windows) { return self.spawnWindows(); } else { return self.spawnPosix(); } } pub fn spawnAndWait(self: *ChildProcess) SpawnError!Term { try self.spawn(); return self.wait(); } /// Forcibly terminates child process and then cleans up all resources. pub fn kill(self: *ChildProcess) !Term { if (builtin.os.tag == .windows) { return self.killWindows(1); } else { return self.killPosix(); } } pub fn killWindows(self: *ChildProcess, exit_code: windows.UINT) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } windows.TerminateProcess(self.id, exit_code) catch |err| switch (err) { error.PermissionDenied => { // Usually when TerminateProcess triggers a ACCESS_DENIED error, it // indicates that the process has already exited, but there may be // some rare edge cases where our process handle no longer has the // PROCESS_TERMINATE access right, so let's do another check to make // sure the process is really no longer running: windows.WaitForSingleObjectEx(self.id, 0, false) catch return err; return error.AlreadyTerminated; }, else => return err, }; try self.waitUnwrappedWindows(); return self.term.?; } pub fn killPosix(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } os.kill(self.id, os.SIG.TERM) catch |err| switch (err) { error.ProcessNotFound => return error.AlreadyTerminated, else => return err, }; try self.waitUnwrapped(); return self.term.?; } /// Blocks until child process terminates and then cleans up all resources. pub fn wait(self: *ChildProcess) !Term { const term = if (builtin.os.tag == .windows) try self.waitWindows() else try self.waitPosix(); self.id = undefined; return term; } pub const RunResult = struct { term: Term, stdout: []u8, stderr: []u8, }; fn fifoToOwnedArrayList(fifo: *std.io.PollFifo) std.ArrayList(u8) { if (fifo.head > 0) { @memcpy(fifo.buf[0..fifo.count], fifo.buf[fifo.head..][0..fifo.count]); } const result = std.ArrayList(u8){ .items = fifo.buf[0..fifo.count], .capacity = fifo.buf.len, .allocator = fifo.allocator, }; fifo.* = std.io.PollFifo.init(fifo.allocator); return result; } /// Collect the output from the process's stdout and stderr. Will return once all output /// has been collected. This does not mean that the process has ended. `wait` should still /// be called to wait for and clean up the process. /// /// The process must be started with stdout_behavior and stderr_behavior == .Pipe pub fn collectOutput( child: ChildProcess, stdout: *std.ArrayList(u8), stderr: *std.ArrayList(u8), max_output_bytes: usize, ) !void { debug.assert(child.stdout_behavior == .Pipe); debug.assert(child.stderr_behavior == .Pipe); // we could make this work with multiple allocators but YAGNI if (stdout.allocator.ptr != stderr.allocator.ptr or stdout.allocator.vtable != stderr.allocator.vtable) { unreachable; // ChildProcess.collectOutput only supports 1 allocator } var poller = std.io.poll(stdout.allocator, enum { stdout, stderr }, .{ .stdout = child.stdout.?, .stderr = child.stderr.?, }); defer poller.deinit(); while (try poller.poll()) { if (poller.fifo(.stdout).count > max_output_bytes) return error.StdoutStreamTooLong; if (poller.fifo(.stderr).count > max_output_bytes) return error.StderrStreamTooLong; } stdout.* = fifoToOwnedArrayList(poller.fifo(.stdout)); stderr.* = fifoToOwnedArrayList(poller.fifo(.stderr)); } pub const RunError = os.GetCwdError || os.ReadError || SpawnError || os.PollError || error{ StdoutStreamTooLong, StderrStreamTooLong, }; /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. /// If it succeeds, the caller owns result.stdout and result.stderr memory. pub fn run(args: struct { allocator: mem.Allocator, argv: []const []const u8, cwd: ?[]const u8 = null, cwd_dir: ?fs.Dir = null, env_map: ?*const EnvMap = null, max_output_bytes: usize = 50 * 1024, expand_arg0: Arg0Expand = .no_expand, }) RunError!RunResult { var child = ChildProcess.init(args.argv, args.allocator); child.stdin_behavior = .Ignore; child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; child.cwd = args.cwd; child.cwd_dir = args.cwd_dir; child.env_map = args.env_map; child.expand_arg0 = args.expand_arg0; var stdout = std.ArrayList(u8).init(args.allocator); var stderr = std.ArrayList(u8).init(args.allocator); errdefer { stdout.deinit(); stderr.deinit(); } try child.spawn(); try child.collectOutput(&stdout, &stderr, args.max_output_bytes); return RunResult{ .term = try child.wait(), .stdout = try stdout.toOwnedSlice(), .stderr = try stderr.toOwnedSlice(), }; } fn waitWindows(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } try self.waitUnwrappedWindows(); return self.term.?; } fn waitPosix(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } try self.waitUnwrapped(); return self.term.?; } fn waitUnwrappedWindows(self: *ChildProcess) !void { const result = windows.WaitForSingleObjectEx(self.id, windows.INFINITE, false); self.term = @as(SpawnError!Term, x: { var exit_code: windows.DWORD = undefined; if (windows.kernel32.GetExitCodeProcess(self.id, &exit_code) == 0) { break :x Term{ .Unknown = 0 }; } else { break :x Term{ .Exited = @as(u8, @truncate(exit_code)) }; } }); if (self.request_resource_usage_statistics) { self.resource_usage_statistics.rusage = try windows.GetProcessMemoryInfo(self.id); } os.close(self.id); os.close(self.thread_handle); self.cleanupStreams(); return result; } fn waitUnwrapped(self: *ChildProcess) !void { const res: os.WaitPidResult = res: { if (self.request_resource_usage_statistics) { switch (builtin.os.tag) { .linux, .macos, .ios => { var ru: std.os.rusage = undefined; const res = os.wait4(self.id, 0, &ru); self.resource_usage_statistics.rusage = ru; break :res res; }, else => {}, } } break :res os.waitpid(self.id, 0); }; const status = res.status; self.cleanupStreams(); self.handleWaitResult(status); } fn handleWaitResult(self: *ChildProcess, status: u32) void { self.term = self.cleanupAfterWait(status); } fn cleanupStreams(self: *ChildProcess) void { if (self.stdin) |*stdin| { stdin.close(); self.stdin = null; } if (self.stdout) |*stdout| { stdout.close(); self.stdout = null; } if (self.stderr) |*stderr| { stderr.close(); self.stderr = null; } } fn cleanupAfterWait(self: *ChildProcess, status: u32) !Term { if (self.err_pipe) |err_pipe| { defer destroyPipe(err_pipe); if (builtin.os.tag == .linux) { var fd = [1]std.os.pollfd{std.os.pollfd{ .fd = err_pipe[0], .events = std.os.POLL.IN, .revents = undefined, }}; // Check if the eventfd buffer stores a non-zero value by polling // it, that's the error code returned by the child process. _ = std.os.poll(&fd, 0) catch unreachable; // According to eventfd(2) the descriptor is readable if the counter // has a value greater than 0 if ((fd[0].revents & std.os.POLL.IN) != 0) { const err_int = try readIntFd(err_pipe[0]); return @as(SpawnError, @errorCast(@errorFromInt(err_int))); } } else { // Write maxInt(ErrInt) to the write end of the err_pipe. This is after // waitpid, so this write is guaranteed to be after the child // pid potentially wrote an error. This way we can do a blocking // read on the error pipe and either get maxInt(ErrInt) (no error) or // an error code. try writeIntFd(err_pipe[1], maxInt(ErrInt)); const err_int = try readIntFd(err_pipe[0]); // Here we potentially return the fork child's error from the parent // pid. if (err_int != maxInt(ErrInt)) { return @as(SpawnError, @errorCast(@errorFromInt(err_int))); } } } return statusToTerm(status); } fn statusToTerm(status: u32) Term { return if (os.W.IFEXITED(status)) Term{ .Exited = os.W.EXITSTATUS(status) } else if (os.W.IFSIGNALED(status)) Term{ .Signal = os.W.TERMSIG(status) } else if (os.W.IFSTOPPED(status)) Term{ .Stopped = os.W.STOPSIG(status) } else Term{ .Unknown = status }; } fn spawnPosix(self: *ChildProcess) SpawnError!void { const pipe_flags: os.O = .{}; const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try os.pipe2(pipe_flags) else undefined; errdefer if (self.stdin_behavior == StdIo.Pipe) { destroyPipe(stdin_pipe); }; const stdout_pipe = if (self.stdout_behavior == StdIo.Pipe) try os.pipe2(pipe_flags) else undefined; errdefer if (self.stdout_behavior == StdIo.Pipe) { destroyPipe(stdout_pipe); }; const stderr_pipe = if (self.stderr_behavior == StdIo.Pipe) try os.pipe2(pipe_flags) else undefined; errdefer if (self.stderr_behavior == StdIo.Pipe) { destroyPipe(stderr_pipe); }; const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const dev_null_fd = if (any_ignore) os.openZ("/dev/null", .{ .ACCMODE = .RDWR }, 0) catch |err| switch (err) { error.PathAlreadyExists => unreachable, error.NoSpaceLeft => unreachable, error.FileTooBig => unreachable, error.DeviceBusy => unreachable, error.FileLocksNotSupported => unreachable, error.BadPathName => unreachable, // Windows-only error.InvalidHandle => unreachable, // WASI-only error.WouldBlock => unreachable, error.NetworkNotFound => unreachable, // Windows-only else => |e| return e, } else undefined; defer { if (any_ignore) os.close(dev_null_fd); } var arena_allocator = std.heap.ArenaAllocator.init(self.allocator); defer arena_allocator.deinit(); const arena = arena_allocator.allocator(); // The POSIX standard does not allow malloc() between fork() and execve(), // and `self.allocator` may be a libc allocator. // I have personally observed the child process deadlocking when it tries // to call malloc() due to a heap allocation between fork() and execve(), // in musl v1.1.24. // Additionally, we want to reduce the number of possible ways things // can fail between fork() and execve(). // Therefore, we do all the allocation for the execve() before the fork(). // This means we must do the null-termination of argv and env vars here. const argv_buf = try arena.allocSentinel(?[*:0]const u8, self.argv.len, null); for (self.argv, 0..) |arg, i| argv_buf[i] = (try arena.dupeZ(u8, arg)).ptr; const envp = m: { if (self.env_map) |env_map| { const envp_buf = try createNullDelimitedEnvMap(arena, env_map); break :m envp_buf.ptr; } else if (builtin.link_libc) { break :m std.c.environ; } else if (builtin.output_mode == .Exe) { // Then we have Zig start code and this works. // TODO type-safety for null-termination of `os.environ`. break :m @as([*:null]const ?[*:0]const u8, @ptrCast(os.environ.ptr)); } else { // TODO come up with a solution for this. @compileError("missing std lib enhancement: ChildProcess implementation has no way to collect the environment variables to forward to the child process"); } }; // This pipe is used to communicate errors between the time of fork // and execve from the child process to the parent process. const err_pipe = blk: { if (builtin.os.tag == .linux) { const fd = try os.eventfd(0, linux.EFD.CLOEXEC); // There's no distinction between the readable and the writeable // end with eventfd break :blk [2]os.fd_t{ fd, fd }; } else { break :blk try os.pipe2(.{ .CLOEXEC = true }); } }; errdefer destroyPipe(err_pipe); const pid_result = try os.fork(); if (pid_result == 0) { // we are the child setUpChildIo(self.stdin_behavior, stdin_pipe[0], os.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stdout_behavior, stdout_pipe[1], os.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stderr_behavior, stderr_pipe[1], os.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); if (self.stdin_behavior == .Pipe) { os.close(stdin_pipe[0]); os.close(stdin_pipe[1]); } if (self.stdout_behavior == .Pipe) { os.close(stdout_pipe[0]); os.close(stdout_pipe[1]); } if (self.stderr_behavior == .Pipe) { os.close(stderr_pipe[0]); os.close(stderr_pipe[1]); } if (self.cwd_dir) |cwd| { os.fchdir(cwd.fd) catch |err| forkChildErrReport(err_pipe[1], err); } else if (self.cwd) |cwd| { os.chdir(cwd) catch |err| forkChildErrReport(err_pipe[1], err); } if (self.gid) |gid| { os.setregid(gid, gid) catch |err| forkChildErrReport(err_pipe[1], err); } if (self.uid) |uid| { os.setreuid(uid, uid) catch |err| forkChildErrReport(err_pipe[1], err); } const err = switch (self.expand_arg0) { .expand => os.execvpeZ_expandArg0(.expand, argv_buf.ptr[0].?, argv_buf.ptr, envp), .no_expand => os.execvpeZ_expandArg0(.no_expand, argv_buf.ptr[0].?, argv_buf.ptr, envp), }; forkChildErrReport(err_pipe[1], err); } // we are the parent const pid = @as(i32, @intCast(pid_result)); if (self.stdin_behavior == StdIo.Pipe) { self.stdin = File{ .handle = stdin_pipe[1] }; } else { self.stdin = null; } if (self.stdout_behavior == StdIo.Pipe) { self.stdout = File{ .handle = stdout_pipe[0] }; } else { self.stdout = null; } if (self.stderr_behavior == StdIo.Pipe) { self.stderr = File{ .handle = stderr_pipe[0] }; } else { self.stderr = null; } self.id = pid; self.err_pipe = err_pipe; self.term = null; if (self.stdin_behavior == StdIo.Pipe) { os.close(stdin_pipe[0]); } if (self.stdout_behavior == StdIo.Pipe) { os.close(stdout_pipe[1]); } if (self.stderr_behavior == StdIo.Pipe) { os.close(stderr_pipe[1]); } } fn spawnWindows(self: *ChildProcess) SpawnError!void { var saAttr = windows.SECURITY_ATTRIBUTES{ .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES), .bInheritHandle = windows.TRUE, .lpSecurityDescriptor = null, }; const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const nul_handle = if (any_ignore) // "\Device\Null" or "\??\NUL" windows.OpenFile(&[_]u16{ '\\', 'D', 'e', 'v', 'i', 'c', 'e', '\\', 'N', 'u', 'l', 'l' }, .{ .access_mask = windows.GENERIC_READ | windows.GENERIC_WRITE | windows.SYNCHRONIZE, .share_access = windows.FILE_SHARE_READ | windows.FILE_SHARE_WRITE, .sa = &saAttr, .creation = windows.OPEN_EXISTING, }) catch |err| switch (err) { error.PathAlreadyExists => unreachable, // not possible for "NUL" error.PipeBusy => unreachable, // not possible for "NUL" error.FileNotFound => unreachable, // not possible for "NUL" error.AccessDenied => unreachable, // not possible for "NUL" error.NameTooLong => unreachable, // not possible for "NUL" error.WouldBlock => unreachable, // not possible for "NUL" error.NetworkNotFound => unreachable, // not possible for "NUL" else => |e| return e, } else undefined; defer { if (any_ignore) os.close(nul_handle); } var g_hChildStd_IN_Rd: ?windows.HANDLE = null; var g_hChildStd_IN_Wr: ?windows.HANDLE = null; switch (self.stdin_behavior) { StdIo.Pipe => { try windowsMakePipeIn(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr); }, StdIo.Ignore => { g_hChildStd_IN_Rd = nul_handle; }, StdIo.Inherit => { g_hChildStd_IN_Rd = windows.GetStdHandle(windows.STD_INPUT_HANDLE) catch null; }, StdIo.Close => { g_hChildStd_IN_Rd = null; }, } errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr); }; var g_hChildStd_OUT_Rd: ?windows.HANDLE = null; var g_hChildStd_OUT_Wr: ?windows.HANDLE = null; switch (self.stdout_behavior) { StdIo.Pipe => { try windowsMakeAsyncPipe(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr); }, StdIo.Ignore => { g_hChildStd_OUT_Wr = nul_handle; }, StdIo.Inherit => { g_hChildStd_OUT_Wr = windows.GetStdHandle(windows.STD_OUTPUT_HANDLE) catch null; }, StdIo.Close => { g_hChildStd_OUT_Wr = null; }, } errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr); }; var g_hChildStd_ERR_Rd: ?windows.HANDLE = null; var g_hChildStd_ERR_Wr: ?windows.HANDLE = null; switch (self.stderr_behavior) { StdIo.Pipe => { try windowsMakeAsyncPipe(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &saAttr); }, StdIo.Ignore => { g_hChildStd_ERR_Wr = nul_handle; }, StdIo.Inherit => { g_hChildStd_ERR_Wr = windows.GetStdHandle(windows.STD_ERROR_HANDLE) catch null; }, StdIo.Close => { g_hChildStd_ERR_Wr = null; }, } errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); }; var siStartInfo = windows.STARTUPINFOW{ .cb = @sizeOf(windows.STARTUPINFOW), .hStdError = g_hChildStd_ERR_Wr, .hStdOutput = g_hChildStd_OUT_Wr, .hStdInput = g_hChildStd_IN_Rd, .dwFlags = windows.STARTF_USESTDHANDLES, .lpReserved = null, .lpDesktop = null, .lpTitle = null, .dwX = 0, .dwY = 0, .dwXSize = 0, .dwYSize = 0, .dwXCountChars = 0, .dwYCountChars = 0, .dwFillAttribute = 0, .wShowWindow = 0, .cbReserved2 = 0, .lpReserved2 = null, }; var piProcInfo: windows.PROCESS_INFORMATION = undefined; const cwd_w = if (self.cwd) |cwd| try unicode.utf8ToUtf16LeWithNull(self.allocator, cwd) else null; defer if (cwd_w) |cwd| self.allocator.free(cwd); const cwd_w_ptr = if (cwd_w) |cwd| cwd.ptr else null; const maybe_envp_buf = if (self.env_map) |env_map| try createWindowsEnvBlock(self.allocator, env_map) else null; defer if (maybe_envp_buf) |envp_buf| self.allocator.free(envp_buf); const envp_ptr = if (maybe_envp_buf) |envp_buf| envp_buf.ptr else null; const app_name_utf8 = self.argv[0]; const app_name_is_absolute = fs.path.isAbsolute(app_name_utf8); // the cwd set in ChildProcess is in effect when choosing the executable path // to match posix semantics var cwd_path_w_needs_free = false; const cwd_path_w = x: { // If the app name is absolute, then we need to use its dirname as the cwd if (app_name_is_absolute) { cwd_path_w_needs_free = true; const dir = fs.path.dirname(app_name_utf8).?; break :x try unicode.utf8ToUtf16LeWithNull(self.allocator, dir); } else if (self.cwd) |cwd| { cwd_path_w_needs_free = true; break :x try unicode.utf8ToUtf16LeWithNull(self.allocator, cwd); } else { break :x &[_:0]u16{}; // empty for cwd } }; defer if (cwd_path_w_needs_free) self.allocator.free(cwd_path_w); // If the app name has more than just a filename, then we need to separate that // into the basename and dirname and use the dirname as an addition to the cwd // path. This is because NtQueryDirectoryFile cannot accept FileName params with // path separators. const app_basename_utf8 = fs.path.basename(app_name_utf8); // If the app name is absolute, then the cwd will already have the app's dirname in it, // so only populate app_dirname if app name is a relative path with > 0 path separators. const maybe_app_dirname_utf8 = if (!app_name_is_absolute) fs.path.dirname(app_name_utf8) else null; const app_dirname_w: ?[:0]u16 = x: { if (maybe_app_dirname_utf8) |app_dirname_utf8| { break :x try unicode.utf8ToUtf16LeWithNull(self.allocator, app_dirname_utf8); } break :x null; }; defer if (app_dirname_w != null) self.allocator.free(app_dirname_w.?); const app_name_w = try unicode.utf8ToUtf16LeWithNull(self.allocator, app_basename_utf8); defer self.allocator.free(app_name_w); const cmd_line_w = argvToCommandLineWindows(self.allocator, self.argv) catch |err| switch (err) { // argv[0] contains unsupported characters that will never resolve to a valid exe. error.InvalidArg0 => return error.FileNotFound, else => |e| return e, }; defer self.allocator.free(cmd_line_w); run: { const PATH: [:0]const u16 = std.os.getenvW(unicode.utf8ToUtf16LeStringLiteral("PATH")) orelse &[_:0]u16{}; const PATHEXT: [:0]const u16 = std.os.getenvW(unicode.utf8ToUtf16LeStringLiteral("PATHEXT")) orelse &[_:0]u16{}; var app_buf = std.ArrayListUnmanaged(u16){}; defer app_buf.deinit(self.allocator); try app_buf.appendSlice(self.allocator, app_name_w); var dir_buf = std.ArrayListUnmanaged(u16){}; defer dir_buf.deinit(self.allocator); if (cwd_path_w.len > 0) { try dir_buf.appendSlice(self.allocator, cwd_path_w); } if (app_dirname_w) |app_dir| { if (dir_buf.items.len > 0) try dir_buf.append(self.allocator, fs.path.sep); try dir_buf.appendSlice(self.allocator, app_dir); } if (dir_buf.items.len > 0) { // Need to normalize the path, openDirW can't handle things like double backslashes const normalized_len = windows.normalizePath(u16, dir_buf.items) catch return error.BadPathName; dir_buf.shrinkRetainingCapacity(normalized_len); } windowsCreateProcessPathExt(self.allocator, &dir_buf, &app_buf, PATHEXT, cmd_line_w.ptr, envp_ptr, cwd_w_ptr, &siStartInfo, &piProcInfo) catch |no_path_err| { const original_err = switch (no_path_err) { error.FileNotFound, error.InvalidExe, error.AccessDenied => |e| e, error.UnrecoverableInvalidExe => return error.InvalidExe, else => |e| return e, }; // If the app name had path separators, that disallows PATH searching, // and there's no need to search the PATH if the app name is absolute. // We still search the path if the cwd is absolute because of the // "cwd set in ChildProcess is in effect when choosing the executable path // to match posix semantics" behavior--we don't want to skip searching // the PATH just because we were trying to set the cwd of the child process. if (app_dirname_w != null or app_name_is_absolute) { return original_err; } var it = mem.tokenizeScalar(u16, PATH, ';'); while (it.next()) |search_path| { dir_buf.clearRetainingCapacity(); try dir_buf.appendSlice(self.allocator, search_path); // Need to normalize the path, some PATH values can contain things like double // backslashes which openDirW can't handle const normalized_len = windows.normalizePath(u16, dir_buf.items) catch continue; dir_buf.shrinkRetainingCapacity(normalized_len); if (windowsCreateProcessPathExt(self.allocator, &dir_buf, &app_buf, PATHEXT, cmd_line_w.ptr, envp_ptr, cwd_w_ptr, &siStartInfo, &piProcInfo)) { break :run; } else |err| switch (err) { error.FileNotFound, error.AccessDenied, error.InvalidExe => continue, error.UnrecoverableInvalidExe => return error.InvalidExe, else => |e| return e, } } else { return original_err; } }; } if (g_hChildStd_IN_Wr) |h| { self.stdin = File{ .handle = h }; } else { self.stdin = null; } if (g_hChildStd_OUT_Rd) |h| { self.stdout = File{ .handle = h }; } else { self.stdout = null; } if (g_hChildStd_ERR_Rd) |h| { self.stderr = File{ .handle = h }; } else { self.stderr = null; } self.id = piProcInfo.hProcess; self.thread_handle = piProcInfo.hThread; self.term = null; if (self.stdin_behavior == StdIo.Pipe) { os.close(g_hChildStd_IN_Rd.?); } if (self.stderr_behavior == StdIo.Pipe) { os.close(g_hChildStd_ERR_Wr.?); } if (self.stdout_behavior == StdIo.Pipe) { os.close(g_hChildStd_OUT_Wr.?); } } fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) !void { switch (stdio) { .Pipe => try os.dup2(pipe_fd, std_fileno), .Close => os.close(std_fileno), .Inherit => {}, .Ignore => try os.dup2(dev_null_fd, std_fileno), } } }; /// Expects `app_buf` to contain exactly the app name, and `dir_buf` to contain exactly the dir path. /// After return, `app_buf` will always contain exactly the app name and `dir_buf` will always contain exactly the dir path. /// Note: `app_buf` should not contain any leading path separators. /// Note: If the dir is the cwd, dir_buf should be empty (len = 0). fn windowsCreateProcessPathExt( allocator: mem.Allocator, dir_buf: *std.ArrayListUnmanaged(u16), app_buf: *std.ArrayListUnmanaged(u16), pathext: [:0]const u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u16, cwd_ptr: ?[*:0]u16, lpStartupInfo: *windows.STARTUPINFOW, lpProcessInformation: *windows.PROCESS_INFORMATION, ) !void { const app_name_len = app_buf.items.len; const dir_path_len = dir_buf.items.len; if (app_name_len == 0) return error.FileNotFound; defer app_buf.shrinkRetainingCapacity(app_name_len); defer dir_buf.shrinkRetainingCapacity(dir_path_len); // The name of the game here is to avoid CreateProcessW calls at all costs, // and only ever try calling it when we have a real candidate for execution. // Secondarily, we want to minimize the number of syscalls used when checking // for each PATHEXT-appended version of the app name. // // An overview of the technique used: // - Open the search directory for iteration (either cwd or a path from PATH) // - Use NtQueryDirectoryFile with a wildcard filename of `<app name>*` to // check if anything that could possibly match either the unappended version // of the app name or any of the versions with a PATHEXT value appended exists. // - If the wildcard NtQueryDirectoryFile call found nothing, we can exit early // without needing to use PATHEXT at all. // // This allows us to use a <open dir, NtQueryDirectoryFile, close dir> sequence // for any directory that doesn't contain any possible matches, instead of having // to use a separate look up for each individual filename combination (unappended + // each PATHEXT appended). For directories where the wildcard *does* match something, // we iterate the matches and take note of any that are either the unappended version, // or a version with a supported PATHEXT appended. We then try calling CreateProcessW // with the found versions in the appropriate order. var dir = dir: { // needs to be null-terminated try dir_buf.append(allocator, 0); defer dir_buf.shrinkRetainingCapacity(dir_path_len); const dir_path_z = dir_buf.items[0 .. dir_buf.items.len - 1 :0]; const prefixed_path = try windows.wToPrefixedFileW(null, dir_path_z); break :dir fs.cwd().openDirW(prefixed_path.span().ptr, .{ .iterate = true }) catch return error.FileNotFound; }; defer dir.close(); // Add wildcard and null-terminator try app_buf.append(allocator, '*'); try app_buf.append(allocator, 0); const app_name_wildcard = app_buf.items[0 .. app_buf.items.len - 1 :0]; // This 2048 is arbitrary, we just want it to be large enough to get multiple FILE_DIRECTORY_INFORMATION entries // returned per NtQueryDirectoryFile call. var file_information_buf: [2048]u8 align(@alignOf(os.windows.FILE_DIRECTORY_INFORMATION)) = undefined; const file_info_maximum_single_entry_size = @sizeOf(windows.FILE_DIRECTORY_INFORMATION) + (windows.NAME_MAX * 2); if (file_information_buf.len < file_info_maximum_single_entry_size) { @compileError("file_information_buf must be large enough to contain at least one maximum size FILE_DIRECTORY_INFORMATION entry"); } var io_status: windows.IO_STATUS_BLOCK = undefined; const num_supported_pathext = @typeInfo(CreateProcessSupportedExtension).Enum.fields.len; var pathext_seen = [_]bool{false} ** num_supported_pathext; var any_pathext_seen = false; var unappended_exists = false; // Fully iterate the wildcard matches via NtQueryDirectoryFile and take note of all versions // of the app_name we should try to spawn. // Note: This is necessary because the order of the files returned is filesystem-dependent: // On NTFS, `blah.exe*` will always return `blah.exe` first if it exists. // On FAT32, it's possible for something like `blah.exe.obj` to be returned first. while (true) { const app_name_len_bytes = math.cast(u16, app_name_wildcard.len * 2) orelse return error.NameTooLong; var app_name_unicode_string = windows.UNICODE_STRING{ .Length = app_name_len_bytes, .MaximumLength = app_name_len_bytes, .Buffer = @constCast(app_name_wildcard.ptr), }; const rc = windows.ntdll.NtQueryDirectoryFile( dir.fd, null, null, null, &io_status, &file_information_buf, file_information_buf.len, .FileDirectoryInformation, windows.FALSE, // single result &app_name_unicode_string, windows.FALSE, // restart iteration ); // If we get nothing with the wildcard, then we can just bail out // as we know appending PATHEXT will not yield anything. switch (rc) { .SUCCESS => {}, .NO_SUCH_FILE => return error.FileNotFound, .NO_MORE_FILES => break, .ACCESS_DENIED => return error.AccessDenied, else => return windows.unexpectedStatus(rc), } // According to the docs, this can only happen if there is not enough room in the // buffer to write at least one complete FILE_DIRECTORY_INFORMATION entry. // Therefore, this condition should not be possible to hit with the buffer size we use. std.debug.assert(io_status.Information != 0); var it = windows.FileInformationIterator(windows.FILE_DIRECTORY_INFORMATION){ .buf = &file_information_buf }; while (it.next()) |info| { // Skip directories if (info.FileAttributes & windows.FILE_ATTRIBUTE_DIRECTORY != 0) continue; const filename = @as([*]u16, @ptrCast(&info.FileName))[0 .. info.FileNameLength / 2]; // Because all results start with the app_name since we're using the wildcard `app_name*`, // if the length is equal to app_name then this is an exact match if (filename.len == app_name_len) { // Note: We can't break early here because it's possible that the unappended version // fails to spawn, in which case we still want to try the PATHEXT appended versions. unappended_exists = true; } else if (windowsCreateProcessSupportsExtension(filename[app_name_len..])) |pathext_ext| { pathext_seen[@intFromEnum(pathext_ext)] = true; any_pathext_seen = true; } } } const unappended_err = unappended: { if (unappended_exists) { if (dir_path_len != 0) switch (dir_buf.items[dir_buf.items.len - 1]) { '/', '\\' => {}, else => try dir_buf.append(allocator, fs.path.sep), }; try dir_buf.appendSlice(allocator, app_buf.items[0..app_name_len]); try dir_buf.append(allocator, 0); const full_app_name = dir_buf.items[0 .. dir_buf.items.len - 1 :0]; if (windowsCreateProcess(full_app_name.ptr, cmd_line, envp_ptr, cwd_ptr, lpStartupInfo, lpProcessInformation)) |_| { return; } else |err| switch (err) { error.FileNotFound, error.AccessDenied, => break :unappended err, error.InvalidExe => { // On InvalidExe, if the extension of the app name is .exe then // it's treated as an unrecoverable error. Otherwise, it'll be // skipped as normal. const app_name = app_buf.items[0..app_name_len]; const ext_start = std.mem.lastIndexOfScalar(u16, app_name, '.') orelse break :unappended err; const ext = app_name[ext_start..]; if (windows.eqlIgnoreCaseWTF16(ext, unicode.utf8ToUtf16LeStringLiteral(".EXE"))) { return error.UnrecoverableInvalidExe; } break :unappended err; }, else => return err, } } break :unappended error.FileNotFound; }; if (!any_pathext_seen) return unappended_err; // Now try any PATHEXT appended versions that we've seen var ext_it = mem.tokenizeScalar(u16, pathext, ';'); while (ext_it.next()) |ext| { const ext_enum = windowsCreateProcessSupportsExtension(ext) orelse continue; if (!pathext_seen[@intFromEnum(ext_enum)]) continue; dir_buf.shrinkRetainingCapacity(dir_path_len); if (dir_path_len != 0) switch (dir_buf.items[dir_buf.items.len - 1]) { '/', '\\' => {}, else => try dir_buf.append(allocator, fs.path.sep), }; try dir_buf.appendSlice(allocator, app_buf.items[0..app_name_len]); try dir_buf.appendSlice(allocator, ext); try dir_buf.append(allocator, 0); const full_app_name = dir_buf.items[0 .. dir_buf.items.len - 1 :0]; if (windowsCreateProcess(full_app_name.ptr, cmd_line, envp_ptr, cwd_ptr, lpStartupInfo, lpProcessInformation)) |_| { return; } else |err| switch (err) { error.FileNotFound => continue, error.AccessDenied => continue, error.InvalidExe => { // On InvalidExe, if the extension of the app name is .exe then // it's treated as an unrecoverable error. Otherwise, it'll be // skipped as normal. if (windows.eqlIgnoreCaseWTF16(ext, unicode.utf8ToUtf16LeStringLiteral(".EXE"))) { return error.UnrecoverableInvalidExe; } continue; }, else => return err, } } return unappended_err; } fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u16, cwd_ptr: ?[*:0]u16, lpStartupInfo: *windows.STARTUPINFOW, lpProcessInformation: *windows.PROCESS_INFORMATION) !void { // TODO the docs for environment pointer say: // > A pointer to the environment block for the new process. If this parameter // > is NULL, the new process uses the environment of the calling process. // > ... // > An environment block can contain either Unicode or ANSI characters. If // > the environment block pointed to by lpEnvironment contains Unicode // > characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. // > If this parameter is NULL and the environment block of the parent process // > contains Unicode characters, you must also ensure that dwCreationFlags // > includes CREATE_UNICODE_ENVIRONMENT. // This seems to imply that we have to somehow know whether our process parent passed // CREATE_UNICODE_ENVIRONMENT if we want to pass NULL for the environment parameter. // Since we do not know this information that would imply that we must not pass NULL // for the parameter. // However this would imply that programs compiled with -DUNICODE could not pass // environment variables to programs that were not, which seems unlikely. // More investigation is needed. return windows.CreateProcessW( app_name, cmd_line, null, null, windows.TRUE, windows.CREATE_UNICODE_ENVIRONMENT, @as(?*anyopaque, @ptrCast(envp_ptr)), cwd_ptr, lpStartupInfo, lpProcessInformation, ); } // Should be kept in sync with `windowsCreateProcessSupportsExtension` const CreateProcessSupportedExtension = enum { bat, cmd, com, exe, }; /// Case-insensitive UTF-16 lookup fn windowsCreateProcessSupportsExtension(ext: []const u16) ?CreateProcessSupportedExtension { if (ext.len != 4) return null; const State = enum { start, dot, b, ba, c, cm, co, e, ex, }; var state: State = .start; for (ext) |c| switch (state) { .start => switch (c) { '.' => state = .dot, else => return null, }, .dot => switch (c) { 'b', 'B' => state = .b, 'c', 'C' => state = .c, 'e', 'E' => state = .e, else => return null, }, .b => switch (c) { 'a', 'A' => state = .ba, else => return null, }, .c => switch (c) { 'm', 'M' => state = .cm, 'o', 'O' => state = .co, else => return null, }, .e => switch (c) { 'x', 'X' => state = .ex, else => return null, }, .ba => switch (c) { 't', 'T' => return .bat, else => return null, }, .cm => switch (c) { 'd', 'D' => return .cmd, else => return null, }, .co => switch (c) { 'm', 'M' => return .com, else => return null, }, .ex => switch (c) { 'e', 'E' => return .exe, else => return null, }, }; return null; } test "windowsCreateProcessSupportsExtension" { try std.testing.expectEqual(CreateProcessSupportedExtension.exe, windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e' }).?); try std.testing.expect(windowsCreateProcessSupportsExtension(&[_]u16{ '.', 'e', 'X', 'e', 'c' }) == null); } pub const ArgvToCommandLineError = error{ OutOfMemory, InvalidUtf8, InvalidArg0 }; /// Serializes `argv` to a Windows command-line string suitable for passing to a child process and /// parsing by the `CommandLineToArgvW` algorithm. The caller owns the returned slice. pub fn argvToCommandLineWindows( allocator: mem.Allocator, argv: []const []const u8, ) ArgvToCommandLineError![:0]u16 { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); if (argv.len != 0) { const arg0 = argv[0]; // The first argument must be quoted if it contains spaces or ASCII control characters // (excluding DEL). It also follows special quoting rules where backslashes have no special // interpretation, which makes it impossible to pass certain first arguments containing // double quotes to a child process without characters from the first argument leaking into // subsequent ones (which could have security implications). // // Empty arguments technically don't need quotes, but we quote them anyway for maximum // compatibility with different implementations of the 'CommandLineToArgvW' algorithm. // // Double quotes are illegal in paths on Windows, so for the sake of simplicity we reject // all first arguments containing double quotes, even ones that we could theoretically // serialize in unquoted form. var needs_quotes = arg0.len == 0; for (arg0) |c| { if (c <= ' ') { needs_quotes = true; } else if (c == '"') { return error.InvalidArg0; } } if (needs_quotes) { try buf.append('"'); try buf.appendSlice(arg0); try buf.append('"'); } else { try buf.appendSlice(arg0); } for (argv[1..]) |arg| { try buf.append(' '); // Subsequent arguments must be quoted if they contain spaces, tabs or double quotes, // or if they are empty. For simplicity and for maximum compatibility with different // implementations of the 'CommandLineToArgvW' algorithm, we also quote all ASCII // control characters (again, excluding DEL). needs_quotes = for (arg) |c| { if (c <= ' ' or c == '"') { break true; } } else arg.len == 0; if (!needs_quotes) { try buf.appendSlice(arg); continue; } try buf.append('"'); var backslash_count: usize = 0; for (arg) |byte| { switch (byte) { '\\' => { backslash_count += 1; }, '"' => { try buf.appendNTimes('\\', backslash_count * 2 + 1); try buf.append('"'); backslash_count = 0; }, else => { try buf.appendNTimes('\\', backslash_count); try buf.append(byte); backslash_count = 0; }, } } try buf.appendNTimes('\\', backslash_count * 2); try buf.append('"'); } } return try unicode.utf8ToUtf16LeWithNull(allocator, buf.items); } test "argvToCommandLineWindows" { const t = testArgvToCommandLineWindows; try t(&.{ \\C:\Program Files\zig\zig.exe , \\run , \\.\src\main.zig , \\-target , \\x86_64-windows-gnu , \\-O , \\ReleaseSafe , \\-- , \\--emoji=🗿 , \\--eval=new Regex("Dwayne \"The Rock\" Johnson") , }, \\"C:\Program Files\zig\zig.exe" run .\src\main.zig -target x86_64-windows-gnu -O ReleaseSafe -- --emoji=🗿 "--eval=new Regex(\"Dwayne \\\"The Rock\\\" Johnson\")" ); try t(&.{}, ""); try t(&.{""}, "\"\""); try t(&.{" "}, "\" \""); try t(&.{"\t"}, "\"\t\""); try t(&.{"\x07"}, "\"\x07\""); try t(&.{"🦎"}, "🦎"); try t( &.{ "zig", "aa aa", "bb\tbb", "cc\ncc", "dd\r\ndd", "ee\x7Fee" }, "zig \"aa aa\" \"bb\tbb\" \"cc\ncc\" \"dd\r\ndd\" ee\x7Fee", ); try t( &.{ "\\\\foo bar\\foo bar\\", "\\\\zig zag\\zig zag\\" }, "\"\\\\foo bar\\foo bar\\\" \"\\\\zig zag\\zig zag\\\\\"", ); try std.testing.expectError( error.InvalidArg0, argvToCommandLineWindows(std.testing.allocator, &.{"\"quotes\"quotes\""}), ); try std.testing.expectError( error.InvalidArg0, argvToCommandLineWindows(std.testing.allocator, &.{"quotes\"quotes"}), ); try std.testing.expectError( error.InvalidArg0, argvToCommandLineWindows(std.testing.allocator, &.{"q u o t e s \" q u o t e s"}), ); } fn testArgvToCommandLineWindows(argv: []const []const u8, expected_cmd_line: []const u8) !void { const cmd_line_w = try argvToCommandLineWindows(std.testing.allocator, argv); defer std.testing.allocator.free(cmd_line_w); const cmd_line = try unicode.utf16leToUtf8Alloc(std.testing.allocator, cmd_line_w); defer std.testing.allocator.free(cmd_line); try std.testing.expectEqualStrings(expected_cmd_line, cmd_line); } fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void { if (rd) |h| os.close(h); if (wr) |h| os.close(h); } fn windowsMakePipeIn(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const windows.SECURITY_ATTRIBUTES) !void { var rd_h: windows.HANDLE = undefined; var wr_h: windows.HANDLE = undefined; try windows.CreatePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windows.SetHandleInformation(wr_h, windows.HANDLE_FLAG_INHERIT, 0); rd.* = rd_h; wr.* = wr_h; } var pipe_name_counter = std.atomic.Value(u32).init(1); fn windowsMakeAsyncPipe(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const windows.SECURITY_ATTRIBUTES) !void { var tmp_bufw: [128]u16 = undefined; // Anonymous pipes are built upon Named pipes. // https://docs.microsoft.com/en-us/windows/win32/api/namedpipeapi/nf-namedpipeapi-createpipe // Asynchronous (overlapped) read and write operations are not supported by anonymous pipes. // https://docs.microsoft.com/en-us/windows/win32/ipc/anonymous-pipe-operations const pipe_path = blk: { var tmp_buf: [128]u8 = undefined; // Forge a random path for the pipe. const pipe_path = std.fmt.bufPrintZ( &tmp_buf, "\\\\.\\pipe\\zig-childprocess-{d}-{d}", .{ windows.kernel32.GetCurrentProcessId(), pipe_name_counter.fetchAdd(1, .Monotonic) }, ) catch unreachable; const len = std.unicode.utf8ToUtf16Le(&tmp_bufw, pipe_path) catch unreachable; tmp_bufw[len] = 0; break :blk tmp_bufw[0..len :0]; }; // Create the read handle that can be used with overlapped IO ops. const read_handle = windows.kernel32.CreateNamedPipeW( pipe_path.ptr, windows.PIPE_ACCESS_INBOUND | windows.FILE_FLAG_OVERLAPPED, windows.PIPE_TYPE_BYTE, 1, 4096, 4096, 0, sattr, ); if (read_handle == windows.INVALID_HANDLE_VALUE) { switch (windows.kernel32.GetLastError()) { else => |err| return windows.unexpectedError(err), } } errdefer os.close(read_handle); var sattr_copy = sattr.*; const write_handle = windows.kernel32.CreateFileW( pipe_path.ptr, windows.GENERIC_WRITE, 0, &sattr_copy, windows.OPEN_EXISTING, windows.FILE_ATTRIBUTE_NORMAL, null, ); if (write_handle == windows.INVALID_HANDLE_VALUE) { switch (windows.kernel32.GetLastError()) { else => |err| return windows.unexpectedError(err), } } errdefer os.close(write_handle); try windows.SetHandleInformation(read_handle, windows.HANDLE_FLAG_INHERIT, 0); rd.* = read_handle; wr.* = write_handle; } fn destroyPipe(pipe: [2]os.fd_t) void { os.close(pipe[0]); if (pipe[0] != pipe[1]) os.close(pipe[1]); } // Child of fork calls this to report an error to the fork parent. // Then the child exits. fn forkChildErrReport(fd: i32, err: ChildProcess.SpawnError) noreturn { writeIntFd(fd, @as(ErrInt, @intFromError(err))) catch {}; // If we're linking libc, some naughty applications may have registered atexit handlers // which we really do not want to run in the fork child. I caught LLVM doing this and // it caused a deadlock instead of doing an exit syscall. In the words of Avril Lavigne, // "Why'd you have to go and make things so complicated?" if (builtin.link_libc) { // The _exit(2) function does nothing but make the exit syscall, unlike exit(3) std.c._exit(1); } os.exit(1); } const ErrInt = std.meta.Int(.unsigned, @sizeOf(anyerror) * 8); fn writeIntFd(fd: i32, value: ErrInt) !void { const file = File{ .handle = fd }; file.writer().writeInt(u64, @intCast(value), .little) catch return error.SystemResources; } fn readIntFd(fd: i32) !ErrInt { const file = File{ .handle = fd }; return @as(ErrInt, @intCast(file.reader().readInt(u64, .little) catch return error.SystemResources)); } /// Caller must free result. pub fn createWindowsEnvBlock(allocator: mem.Allocator, env_map: *const EnvMap) ![]u16 { // count bytes needed const max_chars_needed = x: { var max_chars_needed: usize = 4; // 4 for the final 4 null bytes var it = env_map.iterator(); while (it.next()) |pair| { // +1 for '=' // +1 for null byte max_chars_needed += pair.key_ptr.len + pair.value_ptr.len + 2; } break :x max_chars_needed; }; const result = try allocator.alloc(u16, max_chars_needed); errdefer allocator.free(result); var it = env_map.iterator(); var i: usize = 0; while (it.next()) |pair| { i += try unicode.utf8ToUtf16Le(result[i..], pair.key_ptr.*); result[i] = '='; i += 1; i += try unicode.utf8ToUtf16Le(result[i..], pair.value_ptr.*); result[i] = 0; i += 1; } result[i] = 0; i += 1; result[i] = 0; i += 1; result[i] = 0; i += 1; result[i] = 0; i += 1; return try allocator.realloc(result, i); } pub fn createNullDelimitedEnvMap(arena: mem.Allocator, env_map: *const EnvMap) ![:null]?[*:0]u8 { const envp_count = env_map.count(); const envp_buf = try arena.allocSentinel(?[*:0]u8, envp_count, null); { var it = env_map.iterator(); var i: usize = 0; while (it.next()) |pair| : (i += 1) { const env_buf = try arena.allocSentinel(u8, pair.key_ptr.len + pair.value_ptr.len + 1, 0); @memcpy(env_buf[0..pair.key_ptr.len], pair.key_ptr.*); env_buf[pair.key_ptr.len] = '='; @memcpy(env_buf[pair.key_ptr.len + 1 ..][0..pair.value_ptr.len], pair.value_ptr.*); envp_buf[i] = env_buf.ptr; } assert(i == envp_count); } return envp_buf; } test "createNullDelimitedEnvMap" { const testing = std.testing; const allocator = testing.allocator; var envmap = EnvMap.init(allocator); defer envmap.deinit(); try envmap.put("HOME", "/home/ifreund"); try envmap.put("WAYLAND_DISPLAY", "wayland-1"); try envmap.put("DISPLAY", ":1"); try envmap.put("DEBUGINFOD_URLS", " "); try envmap.put("XCURSOR_SIZE", "24"); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const environ = try createNullDelimitedEnvMap(arena.allocator(), &envmap); try testing.expectEqual(@as(usize, 5), environ.len); inline for (.{ "HOME=/home/ifreund", "WAYLAND_DISPLAY=wayland-1", "DISPLAY=:1", "DEBUGINFOD_URLS= ", "XCURSOR_SIZE=24", }) |target| { for (environ) |variable| { if (mem.eql(u8, mem.span(variable orelse continue), target)) break; } else { try testing.expect(false); // Environment variable not found } } }
https://raw.githubusercontent.com/2lambda123/ziglang-zig/d7563a7753393d7f0d1af445276a64b8a55cb857/lib/std/child_process.zig
const w4 = @import("wasm4.zig"); const std = @import("std"); pub const Shard = enum(u2) { air, square, ring, circle, }; pub const Item = packed struct { top_right: Shard = .air, bottom_right: Shard = .air, bottom_left: Shard = .air, top_left: Shard = .air, pub fn rotateClockwise(self: Item) Item { return .{ .top_right = self.top_left, .bottom_right = self.top_right, .bottom_left = self.bottom_right, .top_left = self.bottom_left, }; } pub fn render(self: Item, x: i32, y: i32) void { w4.blitSub(&texture_data, x + 2, y, 2, 2, @as(u32, @enumToInt(self.top_right)) * 2, 0, 8, 0); w4.blitSub(&texture_data, x + 2, y + 2, 2, 2, @as(u32, @enumToInt(self.bottom_right)) * 2, 0, 8, w4.BLIT_FLIP_Y); w4.blitSub(&texture_data, x, y + 2, 2, 2, @as(u32, @enumToInt(self.bottom_left)) * 2, 0, 8, w4.BLIT_FLIP_X | w4.BLIT_FLIP_Y); w4.blitSub(&texture_data, x, y, 2, 2, @as(u32, @enumToInt(self.top_left)) * 2, 0, 8, w4.BLIT_FLIP_X); } pub fn renderBig(self: Item, x: i32, y: i32) void { w4.blitSub(&texture_data_big, x + 4, y, 4, 4, @as(u32, @enumToInt(self.top_right)) * 4, 0, 16, 0); w4.blitSub(&texture_data_big, x + 4, y + 4, 4, 4, @as(u32, @enumToInt(self.bottom_right)) * 4, 0, 16, w4.BLIT_FLIP_Y); w4.blitSub(&texture_data_big, x, y + 4, 4, 4, @as(u32, @enumToInt(self.bottom_left)) * 4, 0, 16, w4.BLIT_FLIP_X | w4.BLIT_FLIP_Y); w4.blitSub(&texture_data_big, x, y, 4, 4, @as(u32, @enumToInt(self.top_left)) * 4, 0, 16, w4.BLIT_FLIP_X); } pub const empty = Item{}; pub const ring = baseItem(.ring); pub const circle = baseItem(.circle); pub const square = baseItem(.square); fn baseItem(shard: Shard) Item { return Item{ .top_right = shard, .bottom_right = shard, .bottom_left = shard, .top_left = shard, }; } pub fn eql(a: Item, b: Item) bool { return @bitCast(u8, a) == @bitCast(u8, b); } pub fn leftHalf(self: Item) Item { return @bitCast(Item, @bitCast(u8, self) & 0xf0); } pub fn rightHalf(self: Item) Item { return @bitCast(Item, @bitCast(u8, self) & 0x0f); } pub fn isValidLeftHalf(self: Item) bool { const left_half = @bitCast(u8, self) & 0xf0; const right_half = @bitCast(u8, self) & 0x0f; return left_half != 0 and right_half == 0; } pub fn isValidRightHalf(self: Item) bool { const left_half = @bitCast(u8, self) & 0xf0; const right_half = @bitCast(u8, self) & 0x0f; return left_half == 0 and right_half != 0; } pub fn merge(left: Item, right: Item) Item { std.debug.assert(left.isValidLeftHalf()); std.debug.assert(right.isValidRightHalf()); return @bitCast(Item, @bitCast(u8, left) | @bitCast(u8, right)); } }; const texture_data = [2]u8{ 0b00111110, 0b00110111, }; const texture_data_big = [_]u8{ 0b00001111, 0b11111100, 0b00001111, 0b11111100, 0b00001111, 0b00111111, 0b00001111, 0b00111111, };
https://raw.githubusercontent.com/luehmann/assemblio/d1de94c299b99aea9ef40a209e3c8064b3e661e9/src/item.zig
//! The PWM is a counter that increments once every clock until it reaches //! a certain limit. When that limit is hit, the counter is reset to 0. //! This behaviour is called a PWM slice. Each slice has also two channels. //! Each Channel (a and b) has a level value. As soon as the PWM hits that level //! value, you can perform some actions, such as interrupts. //! You can also configure a pin to be a "PWM channel output". This means: //! - on counter reset, the pin is set to high level //! - on counter level match, the pin is reset to low level //! By this, you can generate square waves with a certain frequency and duty cycle. //! //! NOTE: Each pin has a fixed PWM slice and channel assigned, you can look these up //! in the datasheet. //! //! In this example, we're going to use the PWM slice 4, channel b, which happens to be //! attached to the LED pin (25). We're going to set a fixed frequency, and move the //! duty cycle between 0% and 50% forth and back. This way, the LED will slowly blink //! in a smooth fashion. //! //! Prerequisites: `blinky.zig` //! const std = @import("std"); const microzig = @import("microzig"); const rp2040 = microzig.hal; const pwm = rp2040.pwm; const time = rp2040.time; pub fn main() void { // Don't forget to reset the PWM into a well-defined state rp2040.resets.reset(&.{.pwm}); // We want the pwm to count from 0 to 10_000 const pwm_limit = 10_000; // and we are using the system clock const sys_freq = comptime rp2040.clock_config.pll_sys.?.frequency(); // and we want to achieve a well defined target frequency. This frequency defines // how often the PWM sweeps from 0 to 10_000 per second. const target_freq = 500; // Hz // The PWM increments its counter once per clock, so we need to have a much higher // input frequency: const increment_freq = pwm_limit * target_freq; // The PWM clock is derived from the system clock, and uses a divider to get its own // clock. Thus, we compute the divider here. // We're using @divExact as we want to trigger a compile error when the PWM frequency // cannot be perfectly hit. const divider = @divExact(sys_freq, increment_freq); // Now let's set up the PWM: var led_pwm = pwm.PWM(4, .b){}; // get a handle to PWM 4 Channel B // get the PWM slice from our channel handle and set up the values const slice = led_pwm.slice(); slice.setClkDiv(divider, 0); slice.setWrap(pwm_limit); slice.enable(); // start the counter rp2040.gpio.setFunction(25, .pwm); // route the LED pin to the PWM output // Sweep the duty cycle up and down. // By using a delay of 250µs and a limit of 10_000, this loop will repeat // every 2.5 seconds. while (true) { var level: u16 = 0; while (level < pwm_limit / 2) : (level += 1) { led_pwm.setLevel(level); time.sleepUs(250); } while (level > 0) { level -= 1; led_pwm.setLevel(level); time.sleepUs(250); } } }
https://raw.githubusercontent.com/ZigEmbeddedGroup/sycl-workshop-2022/8ed9cc49aea938370860d1fbddb29b7dbc47d0a6/demos/pwm.zig
const std = @import("std"); const Pos = struct { x: usize = 0, y: usize = 0, fn new(x: usize, y: usize) Pos { return Pos{ .x = x, .y = y }; } }; const NumberPos = struct { number: usize = 0, pos: Pos = Pos{}, fn new(number: usize, x: usize, y: usize) NumberPos { return NumberPos{ .number = number, .pos = Pos.new(x, y) }; } fn digits(self: *const NumberPos) usize { if (self.number == 0) return 1; return std.math.log10_int(self.number) + 1; } fn next_to(self: *const NumberPos, pos: Pos) bool { const xAdjacent = pos.x + 1 >= self.pos.x and pos.x <= self.pos.x + self.digits(); const yAdjacent = pos.y + 1 >= self.pos.y and pos.y <= self.pos.y + 1; return xAdjacent and yAdjacent; } }; fn part1(input: []const u8) !usize { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer _ = gpa.deinit(); var numbers = std.ArrayList(NumberPos).init(allocator); defer numbers.deinit(); var symbols = std.ArrayList(Pos).init(allocator); defer symbols.deinit(); // Find numbers var linesIter = std.mem.tokenizeScalar(u8, input, '\n'); var y: usize = 0; while (linesIter.next()) |line| : (y += 1) { var partNumberIter = std.mem.splitAny(u8, line, ".#@/*+$-=&%"); var x: usize = 0; while (partNumberIter.next()) |partNumber| : (x += 1) { if (partNumber.len != 0) { const number = try std.fmt.parseInt(usize, partNumber, 10); try numbers.append(NumberPos.new(number, x, y)); x += partNumber.len; } } } // Find all symbols linesIter = std.mem.tokenizeScalar(u8, input, '\n'); y = 0; while (linesIter.next()) |line| : (y += 1) { for (line, 0..) |char, x| { if (char != '.' and !std.ascii.isDigit(char)) { try symbols.append(Pos.new(x, y)); } } } var sum: usize = 0; // For every number for (numbers.items) |number| { for (symbols.items) |symbol| { // Check if there is a symbol next to it if (number.next_to(symbol)) { sum += number.number; break; } } } return sum; } fn part2(input: []const u8) !usize { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer _ = gpa.deinit(); var numbers = std.ArrayList(NumberPos).init(allocator); defer numbers.deinit(); var stars = std.ArrayList(Pos).init(allocator); defer stars.deinit(); // Find numbers var linesIter = std.mem.tokenizeScalar(u8, input, '\n'); var y: usize = 0; while (linesIter.next()) |line| : (y += 1) { var partNumberIter = std.mem.splitAny(u8, line, ".#@/*+$-=&%"); var x: usize = 0; while (partNumberIter.next()) |partNumber| : (x += 1) { if (partNumber.len != 0) { const number = try std.fmt.parseInt(usize, partNumber, 10); try numbers.append(NumberPos.new(number, x, y)); x += partNumber.len; } } } // Find stars linesIter = std.mem.tokenizeScalar(u8, input, '\n'); y = 0; while (linesIter.next()) |line| : (y += 1) { for (line, 0..) |char, x| { if (char == '*') { try stars.append(Pos.new(x, y)); } } } var sum: usize = 0; for (stars.items) |star| { var count: usize = 0; var product: usize = 1; for (numbers.items) |number| { if (number.next_to(star)) { count += 1; product *= number.number; } } if (count == 2) { sum += product; } } return sum; } pub fn main() !void { const content = comptime @embedFile("data/day03.txt"); std.debug.print("~~ Day 03 ~~\n", .{}); std.debug.print("Part 1: {}\n", .{try part1(content)}); std.debug.print("Part 2: {}\n", .{try part2(content)}); }
https://raw.githubusercontent.com/Niphram/aoc2023/19dd061eafbc10c9ce56b678d786e43f4418e7be/src/day03.zig
const utils = @import("utils.zig"); const term = @import("term.zig"); const config = @import("config.zig"); const logo_embed = @embedFile("resources/logo.txt"); const logo_arr = utils.splitLine(logo_embed); pub const height: u32 = logo_arr.len; pub const width: u32 = logo_arr[0].len; pub fn dump(y: u32, x: u32) void { if (!config.drawBg) { return; } for (logo_arr, 0..) |line, row| { const oy: u32 = @intCast(row); term.mvSlice(y + oy, x, line); } } pub fn dumpCenter() void { const w2 = term.getWidth() / 2; const h2 = term.getHeight() / 2; const height2 = height / 2; const width2 = width / 2; if (w2 < width2 or h2 < height2) { return; } dump(h2 - height2, w2 - width2); }
https://raw.githubusercontent.com/atemmel/spider/849f376ea460bc327a08d6b2ef904287f7f93b62/src/logo.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const exe = b.addExecutable(.{ .name = "zigit", .root_source_file = .{ .path = "src/main.zig" }, .target = b.standardTargetOptions(.{}), .optimize = b.standardOptimizeOption(.{ .preferred_optimize_mode = .ReleaseFast, }), }); exe.linkSystemLibrary("c"); exe.linkSystemLibrary("git2"); b.installArtifact(exe); const run_exe = b.addRunArtifact(exe); const run_step = b.step("run", "Run the application"); run_step.dependOn(&run_exe.step); }
https://raw.githubusercontent.com/Dosx001/zigit/09a7ce06aef7c6fc6769db324325fc8a80dd38e1/build.zig
const std = @import("std"); const vk = @import("vk.zig"); const Framebuffer = @This(); vk: vk.api.VkFramebuffer, device: vk.api.VkDevice, pub fn deinit(self: Framebuffer) void { vk.api.vkDestroyFramebuffer(self.device, self.vk, null); }
https://raw.githubusercontent.com/Sudoku-Boys/Sudoku/218ea16ecc86507698861b59a496ff178a7a7587/vulkan/Framebuffer.zig
const std = @import("std"); const print = std.debug.print; const List = std.ArrayList; const util = @import("util.zig"); const gpa = util.gpa; const data = @embedFile("../data/day10.txt"); fn find(char: u8) ?u8 { const openings = [_]u8{ '(', '[', '{', '<' }; const closings = [_]u8{ ')', ']', '}', '>' }; for (openings) |opener, i| { if (char == opener) return closings[i]; } return null; } const asc = std.sort.asc(usize); pub fn main() !void { var stack = List(u8).init(gpa); defer stack.deinit(); var lines = try util.toStrSlice(data, "\n"); defer gpa.free(lines); var score: usize = 0; var scores_incomplete = List(usize).init(gpa); for (lines) |line| { var is_incomplete = true; for (line) |char| { if (find(char)) |closing| { // an opening try stack.append(closing); } else { // a closing var expect = stack.pop(); if (expect != char) { score += switch (char) { ')' => 3, ']' => 57, '}' => 1197, '>' => 25137, else => @as(usize, 0), }; is_incomplete = false; break; } } } // incomplete if (is_incomplete) { var incomplete: usize = 0; while (stack.items.len > 0) { incomplete *= 5; var char = stack.pop(); incomplete += switch (char) { ')' => 1, ']' => 2, '}' => 3, '>' => 4, else => @as(usize, 0), }; } try scores_incomplete.append(incomplete); } stack.clearAndFree(); } std.sort.sort(usize, scores_incomplete.items, {}, asc); print("{}\n", .{score}); print("{}\n", .{scores_incomplete.items[scores_incomplete.items.len / 2]}); }
https://raw.githubusercontent.com/natecraddock/aoc/f749f9a30b7adf2421df68678e08a698fa8cdd10/2021/src/day10.zig
// // ------------------------------------------------------------ // TOP SECRET TOP SECRET TOP SECRET TOP SECRET TOP SECRET // ------------------------------------------------------------ // // Are you ready for the THE TRUTH about Zig string literals? // // Here it is: // // @TypeOf("foo") == *const [3:0]u8 // // Which means a string literal is a "constant pointer to a // zero-terminated (null-terminated) fixed-size array of u8". // // Now you know. You've earned it. Welcome to the secret club! // // ------------------------------------------------------------ // // Why do we bother using a zero/null sentinel to terminate // strings in Zig when we already have a known length? // // Versatility! Zig strings are compatible with C strings (which // are null-terminated) AND can be coerced to a variety of other // Zig types: // // const a: [5]u8 = "array".*; // const b: *const [16]u8 = "pointer to array"; // const c: []const u8 = "slice"; // const d: [:0]const u8 = "slice with sentinel"; // const e: [*:0]const u8 = "many-item pointer with sentinel"; // const f: [*]const u8 = "many-item pointer"; // // All but 'f' may be printed. (A many-item pointer without a // sentinel is not safe to print because we don't know where it // ends!) // const print = @import("std").debug.print; const WeirdContainer = struct { data: [*]const u8, length: usize, }; pub fn main() void { // WeirdContainer is an awkward way to house a string. // // Being a many-item pointer (with no sentinel termination), // the 'data' field "loses" the length information AND the // sentinel termination of the string literal "Weird Data!". // // Luckily, the 'length' field makes it possible to still // work with this value. const foo = WeirdContainer{ .data = "Weird Data!", .length = 11, }; // How do we get a printable value from 'foo'? One way is to // turn it into something with a known length. We do have a // length... You've actually solved this problem before! // // Here's a big hint: do you remember how to take a slice? const printable : []const u8 = foo.data[0..foo.length]; print("{s}\n", .{printable}); }
https://raw.githubusercontent.com/rjkroege/ziglings/ed4a97781b7ef89d7b6cbb0b36255eb2aa66e4ec/exercises/077_sentinels2.zig
// This code was generated by a tool. // IUP Metadata Code Generator // https://github.com/batiati/IUPMetadata // // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. const std = @import("std"); const interop = @import("../interop.zig"); const iup = @import("../iup.zig"); const Impl = @import("../impl.zig").Impl; const CallbackHandler = @import("../callback_handler.zig").CallbackHandler; const debug = std.debug; const trait = std.meta.trait; const Element = iup.Element; const Handle = iup.Handle; const Error = iup.Error; const ChildrenIterator = iup.ChildrenIterator; const Size = iup.Size; const Margin = iup.Margin; /// /// Creates a dial for regulating a given angular variable. /// It inherits from IupCanvas. /// (Migrated from the IupControls library since IUP 3.24, it does not depend /// on the CD library anymore.) pub const Dial = opaque { pub const CLASS_NAME = "dial"; pub const NATIVE_TYPE = iup.NativeType.Canvas; const Self = @This(); /// /// SCROLL_CB SCROLL_CB Called when some manipulation is made to the scrollbar. /// The canvas is automatically redrawn only if this callback is NOT defined. /// (GTK 2.8) Also the POSX and POSY values will not be correctly updated for /// older GTK versions. /// In Ubuntu, when liboverlay-scrollbar is enabled (the new tiny auto-hide /// scrollbar) only the IUP_SBPOSV and IUP_SBPOSH codes are used. /// Callback int function(Ihandle *ih, int op, float posx, float posy); [in C] /// ih:scroll_cb(op, posx, posy: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// op: indicates the operation performed on the scrollbar. /// If the manipulation was made on the vertical scrollbar, it can have the /// following values: IUP_SBUP - line up IUP_SBDN - line down IUP_SBPGUP - page /// up IUP_SBPGDN - page down IUP_SBPOSV - vertical positioning IUP_SBDRAGV - /// vertical drag If it was on the horizontal scrollbar, the following values /// are valid: IUP_SBLEFT - column left IUP_SBRIGHT - column right IUP_SBPGLEFT /// - page left IUP_SBPGRIGHT - page right IUP_SBPOSH - horizontal positioning /// IUP_SBDRAGH - horizontal drag posx, posy: the same as the ACTION canvas /// callback (corresponding to the values of attributes POSX and POSY). /// Notes IUP_SBDRAGH and IUP_SBDRAGV are not supported in GTK. /// During drag IUP_SBPOSH and IUP_SBPOSV are used. /// In Windows, after a drag when mouse is released IUP_SBPOSH or IUP_SBPOSV /// are called. /// Affects IupCanvas, IupGLCanvas, SCROLLBAR pub const OnScrollFn = fn (self: *Self, arg0: i32, arg1: f32, arg2: f32) anyerror!void; pub const OnFocusFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// BUTTON_RELEASE_CB: Called when the user releases the left mouse button /// after pressing it over the dial. /// int function(Ihandle *ih, double angle) ih:button_release_cb(angle: number) /// -> (ret: number) [in Lua] ih: identifier of the element that activated the event. /// angle: the dial value converted according to UNIT. pub const OnButtonReleaseFn = fn (self: *Self, arg0: f64) anyerror!void; /// /// WOM_CB WOM_CB Action generated when an audio device receives an event. /// [Windows Only] Callback int function(Ihandle *ih, int state); [in C] /// ih:wom_cb(state: number) -> (ret: number) [in Lua] ih: identifies the /// element that activated the event. /// state: can be opening=1, done=0, or closing=-1. /// Notes This callback is used to syncronize video playback with audio. /// It is sent when the audio device: Message Description opening is opened by /// using the waveOutOpen function. /// done is finished with a data block sent by using the waveOutWrite function. /// closing is closed by using the waveOutClose function. /// You must use the HWND attribute when calling waveOutOpen in the dwCallback /// parameter and set fdwOpen to CALLBACK_WINDOW. /// Affects IupDialog, IupCanvas, IupGLCanvas pub const OnWomFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub const OnKAnyFn = fn (self: *Self, arg0: i32) anyerror!void; /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub const OnHelpFn = fn (self: *Self) anyerror!void; pub const OnDropMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void; /// /// KEYPRESS_CB KEYPRESS_CB Action generated when a key is pressed or released. /// If the key is pressed and held several calls will occur. /// It is called after the callback K_ANY is processed. /// Callback int function(Ihandle *ih, int c, int press); [in C] /// ih:keypress_cb(c, press: number) -> (ret: number) [in Lua] ih: identifier /// of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// press: 1 is the user pressed the key or 0 otherwise. /// Returns: If IUP_IGNORE is returned the key is ignored by the system. /// IUP_CLOSE will be processed. /// Affects IupCanvas pub const OnKeyPressFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; pub const OnDragEndFn = fn (self: *Self, arg0: i32) anyerror!void; pub const OnDragBeginFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; /// /// ACTION ACTION Action generated when the element is activated. /// Affects each element differently. /// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// In some elements, this callback may receive more parameters, apart from ih. /// Please refer to each element's documentation. /// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline, /// IupToggle pub const OnActionFn = fn (self: *Self, arg0: f32, arg1: f32) anyerror!void; /// /// MOTION_CB MOTION_CB Action generated when the mouse moves. /// Callback int function(Ihandle *ih, int x, int y, char *status); [in C] /// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes Between press and release all mouse events are redirected only to /// this control, even if the cursor moves outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupGLCanvas pub const OnMotionFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: [:0]const u8) anyerror!void; /// /// WHEEL_CB WHEEL_CB Action generated when the mouse wheel is rotated. /// If this callback is not defined the wheel will automatically scroll the /// canvas in the vertical direction by some lines, the SCROLL_CB callback if /// defined will be called with the IUP_SBDRAGV operation. /// Callback int function(Ihandle *ih, float delta, int x, int y, char /// *status); [in C] ih:wheel_cb(delta, x, y: number, status: string) -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// delta: the amount the wheel was rotated in notches. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes In Motif and GTK delta is always 1 or -1. /// In Windows is some situations delta can reach the value of two. /// In the future with more precise wheels this increment can be changed. /// Affects IupCanvas, IupGLCanvas pub const OnWheelFn = fn (self: *Self, arg0: f32, arg1: i32, arg2: i32, arg3: [:0]const u8) anyerror!void; /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnMapFn = fn (self: *Self) anyerror!void; /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub const OnEnterWindowFn = fn (self: *Self) anyerror!void; /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub const OnDestroyFn = fn (self: *Self) anyerror!void; pub const OnDropDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: ?*anyopaque, arg2: i32, arg3: i32, arg4: i32) anyerror!void; /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub const OnKillFocusFn = fn (self: *Self) anyerror!void; /// /// MOUSEMOVE_CB: Called each time the user moves the dial with the mouse /// button pressed. /// The angle the dial rotated since it was initialized is passed as a parameter. /// int function(Ihandle *ih, double angle); [in C] ih:mousemove_cb(angle: /// number) -> (ret: number) [in Lua] pub const OnMouseMoveFn = fn (self: *Self, arg0: f64) anyerror!void; pub const OnDragDataFn = fn (self: *Self, arg0: [:0]const u8, arg1: ?*anyopaque, arg2: i32) anyerror!void; /// /// BUTTON_PRESS_CB: Called when the user presses the left mouse button over /// the dial. /// The angle here is always zero, except for the circular dial. /// int function(Ihandle *ih, double angle) ih:button_press_cb(angle: number) /// -> (ret: number) [in Lua] pub const OnButtonPressFn = fn (self: *Self, arg0: f64) anyerror!void; pub const OnDragDataSizeFn = fn (self: *Self, arg0: [:0]const u8) anyerror!void; /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub const OnDropFilesFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: i32, arg3: i32) anyerror!void; /// /// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed. /// Callback int function(Ihandle *ih, int width, int height); [in C] /// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// width: the width of the internal element size in pixels not considering the /// decorations (client size) height: the height of the internal element size /// in pixels not considering the decorations (client size) Notes For the /// dialog, this action is also generated when the dialog is mapped, after the /// map and before the show. /// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is /// hidden/shown after changing the DX or DY attributes from inside the /// callback, the size of the drawing area will immediately change, so the /// parameters with and height will be invalid. /// To update the parameters consult the DRAWSIZE attribute. /// Also activate the drawing toolkit only after updating the DX or DY attributes. /// Affects IupCanvas, IupGLCanvas, IupDialog pub const OnResizeFn = fn (self: *Self, arg0: i32, arg1: i32) anyerror!void; /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub const OnUnmapFn = fn (self: *Self) anyerror!void; /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub const OnGetFocusFn = fn (self: *Self) anyerror!void; /// /// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released. /// Callback int function(Ihandle* ih, int button, int pressed, int x, int y, /// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status: /// string) -> (ret: number) [in Lua] ih: identifies the element that activated /// the event. /// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse /// button (button 1); IUP_BUTTON2 - middle mouse button (button 2); /// IUP_BUTTON3 - right mouse button (button 3). /// pressed: indicates the state of the button: 0 - mouse button was released; /// 1 - mouse button was pressed. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of the mouse buttons and some keyboard keys at the moment /// the event is generated. /// The following macros must be used for verification: iup_isshift(status) /// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status) /// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status) /// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if /// the respective key or button is pressed, and 0 otherwise. /// These macros are also available in Lua, returning a boolean. /// Returns: IUP_CLOSE will be processed. /// On some controls if IUP_IGNORE is returned the action is ignored (this is /// system dependent). /// Notes This callback can be used to customize a button behavior. /// For a standard button behavior use the ACTION callback of the IupButton. /// For a single click the callback is called twice, one for pressed=1 and one /// for pressed=0. /// Only after both calls the ACTION callback is called. /// In Windows, if a dialog is shown or popup in any situation there could be /// unpredictable results because the native system still has processing to be /// done even after the callback is called. /// A double click is preceded by two single clicks, one for pressed=1 and one /// for pressed=0, and followed by a press=0, all three without the double /// click flag set. /// In GTK, it is preceded by an additional two single clicks sequence. /// For example, for one double click all the following calls are made: /// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [ /// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 /// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 /// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all /// mouse events are redirected only to this control, even if the cursor moves /// outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas pub const OnButtonFn = fn (self: *Self, arg0: i32, arg1: i32, arg2: i32, arg3: i32, arg4: [:0]const u8) anyerror!void; /// /// VALUECHANGED_CB: Called after the value was interactively changed by the user. /// It is called whenever a BUTTON_PRESS_CB, a BUTTON_RELEASE_CB or a /// MOUSEMOVE_CB would also be called, but if defined those callbacks will not /// be called. /// (since 3.0) int function(Ihandle *ih); [in C]ih:valuechanged_cb() -> (ret: /// number) [in Lua] pub const OnValueChangedFn = fn (self: *Self) anyerror!void; pub const OnLDestroyFn = fn (self: *Self) anyerror!void; /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub const OnLeaveWindowFn = fn (self: *Self) anyerror!void; pub const OnPostMessageFn = fn (self: *Self, arg0: [:0]const u8, arg1: i32, arg2: f64, arg3: ?*anyopaque) anyerror!void; pub const DrawTextAlignment = enum { ACenter, ARight, ALeft, }; pub const ZOrder = enum { Top, Bottom, }; /// /// EXPAND: the default is "NO". pub const Expand = enum { Yes, Horizontal, Vertical, HorizontalFree, VerticalFree, No, }; /// /// ORIENTATION (creation only) (non inheritable): dial layout configuration /// "VERTICAL", "HORIZONTAL" or "CIRCULAR". /// Default: "HORIZONTAL". /// Vertical increments when moved up, and decrements when moved down. /// Horizontal increments when moved right, and decrements when moved left. /// Circular increments when moved counter clock wise, and decrements when /// moved clock wise. pub const Orientation = enum { Horizontal, Vertical, }; pub const Floating = enum { Yes, Ignore, No, }; pub const DrawStyle = enum { Fill, StrokeDash, StrokeDot, StrokeDashDot, StrokeDashDotdot, DrawStroke, }; pub const Initializer = struct { last_error: ?anyerror = null, ref: *Self, /// /// Returns a pointer to IUP element or an error. /// Only top-level or detached elements needs to be unwraped, pub fn unwrap(self: Initializer) !*Self { if (self.last_error) |e| { return e; } else { return self.ref; } } /// /// Captures a reference into a external variable /// Allows to capture some references even using full declarative API pub fn capture(self: Initializer, ref: **Self) Initializer { ref.* = self.ref; return self; } pub fn setStrAttribute(self: Initializer, attributeName: [:0]const u8, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; Self.setStrAttribute(self.ref, attributeName, arg); return self; } pub fn setIntAttribute(self: Initializer, attributeName: [:0]const u8, arg: i32) Initializer { if (self.last_error) |_| return self; Self.setIntAttribute(self.ref, attributeName, arg); return self; } pub fn setBoolAttribute(self: Initializer, attributeName: [:0]const u8, arg: bool) Initializer { if (self.last_error) |_| return self; Self.setBoolAttribute(self.ref, attributeName, arg); return self; } pub fn setPtrAttribute(self: Initializer, comptime T: type, attributeName: [:0]const u8, value: ?*T) Initializer { if (self.last_error) |_| return self; Self.setPtrAttribute(self.ref, T, attributeName, value); return self; } pub fn setHandle(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setHandle(self.ref, arg); return self; } /// /// FGCOLOR: foreground color. /// The default value is "64 64 64". /// (appears in circular dial since 3.24) pub fn setFgColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "FGCOLOR", .{}, rgb); return self; } pub fn setHandleName(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "HANDLENAME", .{}, arg); return self; } pub fn setTipBgColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "TIPBGCOLOR", .{}, rgb); return self; } pub fn setXMin(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "XMIN", .{}, arg); return self; } pub fn setTipIcon(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "TIPICON", .{}, arg); return self; } pub fn setMaxSize(self: Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MAXSIZE", .{}, value); return self; } pub fn setDrawTextWrap(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAWTEXTWRAP", .{}, arg); return self; } pub fn setPosition(self: Initializer, x: i32, y: i32) Initializer { if (self.last_error) |_| return self; var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self.ref, "POSITION", .{}, value); return self; } pub fn setDropFilesTarget(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DROPFILESTARGET", .{}, arg); return self; } pub fn setDrawTextAlignment(self: Initializer, arg: ?DrawTextAlignment) Initializer { if (self.last_error) |_| return self; if (arg) |value| switch (value) { .ACenter => interop.setStrAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}, "ACENTER"), .ARight => interop.setStrAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}, "ARIGHT"), .ALeft => interop.setStrAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}, "ALEFT"), } else { interop.clearAttribute(self.ref, "DRAWTEXTALIGNMENT", .{}); } return self; } pub fn setTip(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "TIP", .{}, arg); return self; } pub fn setDrawTextLayoutCenter(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAWTEXTLAYOUTCENTER", .{}, arg); return self; } pub fn setType(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "TYPE", .{}, arg); return self; } pub fn setCanFocus(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "CANFOCUS", .{}, arg); return self; } pub fn setDragSourceMove(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAGSOURCEMOVE", .{}, arg); return self; } pub fn setVisible(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "VISIBLE", .{}, arg); return self; } pub fn setLineX(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "LINEX", .{}, arg); return self; } pub fn setCursor(self: Initializer, arg: anytype) Initializer { if (self.last_error) |_| return self; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "CURSOR", .{}, arg); } else |err| { self.last_error = err; } return self; } pub fn setCursorHandleName(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "CURSOR", .{}, arg); return self; } pub fn setLineY(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "LINEY", .{}, arg); return self; } pub fn zOrder(self: Initializer, arg: ?ZOrder) Initializer { if (self.last_error) |_| return self; if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self.ref, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self.ref, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self.ref, "ZORDER", .{}); } return self; } pub fn setDrawLineWidth(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "DRAWLINEWIDTH", .{}, arg); return self; } pub fn setDragDrop(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAGDROP", .{}, arg); return self; } pub fn setTheme(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "THEME", .{}, arg); return self; } /// /// FLATCOLOR: color of the border when FLAT=Yes. /// Default: "160 160 160". /// (since 3.24) pub fn setFlatColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "FLATCOLOR", .{}, rgb); return self; } /// /// EXPAND: the default is "NO". pub fn setExpand(self: Initializer, arg: ?Expand) Initializer { if (self.last_error) |_| return self; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self.ref, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self.ref, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self.ref, "EXPAND", .{}); } return self; } pub fn setDrawFont(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "DRAWFONT", .{}, arg); return self; } /// /// SIZE (non inheritable): the initial size is "16x80", "80x16" or "40x35" /// according to the dial orientation. /// Set to NULL to allow the automatic layout use smaller values. pub fn setSize(self: Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "SIZE", .{}, value); return self; } pub fn setPosX(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "POSX", .{}, arg); return self; } pub fn setPosY(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "POSY", .{}, arg); return self; } pub fn setTipMarkup(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "TIPMARKUP", .{}, arg); return self; } pub fn setYMin(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "YMIN", .{}, arg); return self; } /// /// ORIENTATION (creation only) (non inheritable): dial layout configuration /// "VERTICAL", "HORIZONTAL" or "CIRCULAR". /// Default: "HORIZONTAL". /// Vertical increments when moved up, and decrements when moved down. /// Horizontal increments when moved right, and decrements when moved left. /// Circular increments when moved counter clock wise, and decrements when /// moved clock wise. pub fn setOrientation(self: Initializer, arg: ?Orientation) Initializer { if (self.last_error) |_| return self; if (arg) |value| switch (value) { .Horizontal => interop.setStrAttribute(self.ref, "ORIENTATION", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self.ref, "ORIENTATION", .{}, "VERTICAL"), } else { interop.clearAttribute(self.ref, "ORIENTATION", .{}); } return self; } pub fn setDrawMakeInactive(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAWMAKEINACTIVE", .{}, arg); return self; } pub fn setFontSize(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "FONTSIZE", .{}, arg); return self; } pub fn setDropTypes(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "DROPTYPES", .{}, arg); return self; } pub fn setUserSize(self: Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "USERSIZE", .{}, value); return self; } pub fn setTipDelay(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "TIPDELAY", .{}, arg); return self; } pub fn setScrollBar(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "SCROLLBAR", .{}, arg); return self; } pub fn setXAutoHide(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "XAUTOHIDE", .{}, arg); return self; } pub fn setPropagateFocus(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "PROPAGATEFOCUS", .{}, arg); return self; } pub fn setXMax(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "XMAX", .{}, arg); return self; } pub fn setBgColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "BGCOLOR", .{}, rgb); return self; } pub fn setDropTarget(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DROPTARGET", .{}, arg); return self; } pub fn setDX(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "DX", .{}, arg); return self; } pub fn setDY(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "DY", .{}, arg); return self; } pub fn setDrawTextEllipsis(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAWTEXTELLIPSIS", .{}, arg); return self; } pub fn setDragSource(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAGSOURCE", .{}, arg); return self; } pub fn setDrawTextClip(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "DRAWTEXTCLIP", .{}, arg); return self; } pub fn setFloating(self: Initializer, arg: ?Floating) Initializer { if (self.last_error) |_| return self; if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self.ref, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self.ref, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self.ref, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self.ref, "FLOATING", .{}); } return self; } pub fn setNormalizerGroup(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "NORMALIZERGROUP", .{}, arg); return self; } pub fn setRasterSize(self: Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "RASTERSIZE", .{}, value); return self; } pub fn setTipFgColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "TIPFGCOLOR", .{}, rgb); return self; } pub fn setFontFace(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "FONTFACE", .{}, arg); return self; } pub fn setDrawColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "DRAWCOLOR", .{}, rgb); return self; } pub fn setDrawTextOrientation(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "DRAWTEXTORIENTATION", .{}, arg); return self; } pub fn setDrawBgColor(self: Initializer, rgb: iup.Rgb) Initializer { if (self.last_error) |_| return self; interop.setRgb(self.ref, "DRAWBGCOLOR", .{}, rgb); return self; } pub fn setName(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "NAME", .{}, arg); return self; } pub fn setBackingStore(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "BACKINGSTORE", .{}, arg); return self; } pub fn setYAutoHide(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "YAUTOHIDE", .{}, arg); return self; } pub fn setDrawStyle(self: Initializer, arg: ?DrawStyle) Initializer { if (self.last_error) |_| return self; if (arg) |value| switch (value) { .Fill => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "FILL"), .StrokeDash => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DASH"), .StrokeDot => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DOT"), .StrokeDashDot => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DASH_DOT"), .StrokeDashDotdot => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "STROKE_DASH_DOT_DOT"), .DrawStroke => interop.setStrAttribute(self.ref, "DRAWSTYLE", .{}, "DRAW_STROKE"), } else { interop.clearAttribute(self.ref, "DRAWSTYLE", .{}); } return self; } /// /// VALUE (non inheritable): The dial angular value in radians always. /// The value is reset to zero when the interaction is started, except for ORIENTATION=CIRCULAR. /// When orientation is vertical or horizontal, the dial measures relative angles. /// When orientation is circular the dial measure absolute angles, where the /// origin is at 3 O'clock. pub fn setValue(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "VALUE", .{}, arg); return self; } /// /// ACTIVE, BGCOLOR, FONT, SCREENPOSITION, POSITION, MINSIZE, MAXSIZE, WID, /// TIP, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn setActive(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "ACTIVE", .{}, arg); return self; } pub fn setTipVisible(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "TIPVISIBLE", .{}, arg); return self; } pub fn setYMax(self: Initializer, arg: i32) Initializer { if (self.last_error) |_| return self; interop.setIntAttribute(self.ref, "YMAX", .{}, arg); return self; } pub fn setExpandWeight(self: Initializer, arg: f64) Initializer { if (self.last_error) |_| return self; interop.setDoubleAttribute(self.ref, "EXPANDWEIGHT", .{}, arg); return self; } pub fn setMinSize(self: Initializer, width: ?i32, height: ?i32) Initializer { if (self.last_error) |_| return self; var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self.ref, "MINSIZE", .{}, value); return self; } /// /// FLAT: use a 1 pixel flat border instead of the default 3 pixels sunken border. /// Can be Yes or No. /// Default: No. /// (since 3.24) pub fn setFlat(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "FLAT", .{}, arg); return self; } pub fn setNTheme(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "NTHEME", .{}, arg); return self; } pub fn setDragTypes(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "DRAGTYPES", .{}, arg); return self; } pub fn setWheelDropFocus(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "WHEELDROPFOCUS", .{}, arg); return self; } pub fn setFontStyle(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "FONTSTYLE", .{}, arg); return self; } pub fn setTouch(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "TOUCH", .{}, arg); return self; } pub fn setFont(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "FONT", .{}, arg); return self; } pub fn setMdiClient(self: Initializer, arg: bool) Initializer { if (self.last_error) |_| return self; interop.setBoolAttribute(self.ref, "MDICLIENT", .{}, arg); return self; } pub fn setMdiMenu(self: Initializer, arg: *iup.Menu) Initializer { if (self.last_error) |_| return self; interop.setHandleAttribute(self.ref, "MDIMENU", .{}, arg); return self; } pub fn setMdiMenuHandleName(self: Initializer, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "MDIMENU", .{}, arg); return self; } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: Initializer, index: i32, arg: anytype) Initializer { if (self.last_error) |_| return self; if (interop.validateHandle(.Image, arg)) { interop.setHandleAttribute(self.ref, "TABIMAGE", .{index}, arg); } else |err| { self.last_error = err; } return self; } pub fn setTabImageHandleName(self: Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "TABIMAGE", .{index}, arg); return self; } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: Initializer, index: i32, arg: [:0]const u8) Initializer { if (self.last_error) |_| return self; interop.setStrAttribute(self.ref, "TABTITLE", .{index}, arg); return self; } /// /// SCROLL_CB SCROLL_CB Called when some manipulation is made to the scrollbar. /// The canvas is automatically redrawn only if this callback is NOT defined. /// (GTK 2.8) Also the POSX and POSY values will not be correctly updated for /// older GTK versions. /// In Ubuntu, when liboverlay-scrollbar is enabled (the new tiny auto-hide /// scrollbar) only the IUP_SBPOSV and IUP_SBPOSH codes are used. /// Callback int function(Ihandle *ih, int op, float posx, float posy); [in C] /// ih:scroll_cb(op, posx, posy: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// op: indicates the operation performed on the scrollbar. /// If the manipulation was made on the vertical scrollbar, it can have the /// following values: IUP_SBUP - line up IUP_SBDN - line down IUP_SBPGUP - page /// up IUP_SBPGDN - page down IUP_SBPOSV - vertical positioning IUP_SBDRAGV - /// vertical drag If it was on the horizontal scrollbar, the following values /// are valid: IUP_SBLEFT - column left IUP_SBRIGHT - column right IUP_SBPGLEFT /// - page left IUP_SBPGRIGHT - page right IUP_SBPOSH - horizontal positioning /// IUP_SBDRAGH - horizontal drag posx, posy: the same as the ACTION canvas /// callback (corresponding to the values of attributes POSX and POSY). /// Notes IUP_SBDRAGH and IUP_SBDRAGV are not supported in GTK. /// During drag IUP_SBPOSH and IUP_SBPOSV are used. /// In Windows, after a drag when mouse is released IUP_SBPOSH or IUP_SBPOSV /// are called. /// Affects IupCanvas, IupGLCanvas, SCROLLBAR pub fn setScrollCallback(self: Initializer, callback: ?*const OnScrollFn) Initializer { const Handler = CallbackHandler(Self, OnScrollFn, "SCROLL_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setFocusCallback(self: Initializer, callback: ?*const OnFocusFn) Initializer { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// BUTTON_RELEASE_CB: Called when the user releases the left mouse button /// after pressing it over the dial. /// int function(Ihandle *ih, double angle) ih:button_release_cb(angle: number) /// -> (ret: number) [in Lua] ih: identifier of the element that activated the event. /// angle: the dial value converted according to UNIT. pub fn setButtonReleaseCallback(self: Initializer, callback: ?*const OnButtonReleaseFn) Initializer { const Handler = CallbackHandler(Self, OnButtonReleaseFn, "BUTTON_RELEASE_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// WOM_CB WOM_CB Action generated when an audio device receives an event. /// [Windows Only] Callback int function(Ihandle *ih, int state); [in C] /// ih:wom_cb(state: number) -> (ret: number) [in Lua] ih: identifies the /// element that activated the event. /// state: can be opening=1, done=0, or closing=-1. /// Notes This callback is used to syncronize video playback with audio. /// It is sent when the audio device: Message Description opening is opened by /// using the waveOutOpen function. /// done is finished with a data block sent by using the waveOutWrite function. /// closing is closed by using the waveOutClose function. /// You must use the HWND attribute when calling waveOutOpen in the dwCallback /// parameter and set fdwOpen to CALLBACK_WINDOW. /// Affects IupDialog, IupCanvas, IupGLCanvas pub fn setWomCallback(self: Initializer, callback: ?*const OnWomFn) Initializer { const Handler = CallbackHandler(Self, OnWomFn, "WOM_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub fn setKAnyCallback(self: Initializer, callback: ?*const OnKAnyFn) Initializer { const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY"); Handler.setCallback(self.ref, callback); return self; } /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub fn setHelpCallback(self: Initializer, callback: ?*const OnHelpFn) Initializer { const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setDropMotionCallback(self: Initializer, callback: ?*const OnDropMotionFn) Initializer { const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// KEYPRESS_CB KEYPRESS_CB Action generated when a key is pressed or released. /// If the key is pressed and held several calls will occur. /// It is called after the callback K_ANY is processed. /// Callback int function(Ihandle *ih, int c, int press); [in C] /// ih:keypress_cb(c, press: number) -> (ret: number) [in Lua] ih: identifier /// of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// press: 1 is the user pressed the key or 0 otherwise. /// Returns: If IUP_IGNORE is returned the key is ignored by the system. /// IUP_CLOSE will be processed. /// Affects IupCanvas pub fn setKeyPressCallback(self: Initializer, callback: ?*const OnKeyPressFn) Initializer { const Handler = CallbackHandler(Self, OnKeyPressFn, "KEYPRESS_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setDragEndCallback(self: Initializer, callback: ?*const OnDragEndFn) Initializer { const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setDragBeginCallback(self: Initializer, callback: ?*const OnDragBeginFn) Initializer { const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// ACTION ACTION Action generated when the element is activated. /// Affects each element differently. /// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// In some elements, this callback may receive more parameters, apart from ih. /// Please refer to each element's documentation. /// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline, /// IupToggle pub fn setActionCallback(self: Initializer, callback: ?*const OnActionFn) Initializer { const Handler = CallbackHandler(Self, OnActionFn, "ACTION"); Handler.setCallback(self.ref, callback); return self; } /// /// MOTION_CB MOTION_CB Action generated when the mouse moves. /// Callback int function(Ihandle *ih, int x, int y, char *status); [in C] /// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes Between press and release all mouse events are redirected only to /// this control, even if the cursor moves outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupGLCanvas pub fn setMotionCallback(self: Initializer, callback: ?*const OnMotionFn) Initializer { const Handler = CallbackHandler(Self, OnMotionFn, "MOTION_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// WHEEL_CB WHEEL_CB Action generated when the mouse wheel is rotated. /// If this callback is not defined the wheel will automatically scroll the /// canvas in the vertical direction by some lines, the SCROLL_CB callback if /// defined will be called with the IUP_SBDRAGV operation. /// Callback int function(Ihandle *ih, float delta, int x, int y, char /// *status); [in C] ih:wheel_cb(delta, x, y: number, status: string) -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// delta: the amount the wheel was rotated in notches. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes In Motif and GTK delta is always 1 or -1. /// In Windows is some situations delta can reach the value of two. /// In the future with more precise wheels this increment can be changed. /// Affects IupCanvas, IupGLCanvas pub fn setWheelCallback(self: Initializer, callback: ?*const OnWheelFn) Initializer { const Handler = CallbackHandler(Self, OnWheelFn, "WHEEL_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: Initializer, callback: ?*const OnMapFn) Initializer { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: Initializer, callback: ?*const OnEnterWindowFn) Initializer { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub fn setDestroyCallback(self: Initializer, callback: ?*const OnDestroyFn) Initializer { const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setDropDataCallback(self: Initializer, callback: ?*const OnDropDataFn) Initializer { const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub fn setKillFocusCallback(self: Initializer, callback: ?*const OnKillFocusFn) Initializer { const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// MOUSEMOVE_CB: Called each time the user moves the dial with the mouse /// button pressed. /// The angle the dial rotated since it was initialized is passed as a parameter. /// int function(Ihandle *ih, double angle); [in C] ih:mousemove_cb(angle: /// number) -> (ret: number) [in Lua] pub fn setMouseMoveCallback(self: Initializer, callback: ?*const OnMouseMoveFn) Initializer { const Handler = CallbackHandler(Self, OnMouseMoveFn, "MOUSEMOVE_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setDragDataCallback(self: Initializer, callback: ?*const OnDragDataFn) Initializer { const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// BUTTON_PRESS_CB: Called when the user presses the left mouse button over /// the dial. /// The angle here is always zero, except for the circular dial. /// int function(Ihandle *ih, double angle) ih:button_press_cb(angle: number) /// -> (ret: number) [in Lua] pub fn setButtonPressCallback(self: Initializer, callback: ?*const OnButtonPressFn) Initializer { const Handler = CallbackHandler(Self, OnButtonPressFn, "BUTTON_PRESS_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setDragDataSizeCallback(self: Initializer, callback: ?*const OnDragDataSizeFn) Initializer { const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub fn setDropFilesCallback(self: Initializer, callback: ?*const OnDropFilesFn) Initializer { const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed. /// Callback int function(Ihandle *ih, int width, int height); [in C] /// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// width: the width of the internal element size in pixels not considering the /// decorations (client size) height: the height of the internal element size /// in pixels not considering the decorations (client size) Notes For the /// dialog, this action is also generated when the dialog is mapped, after the /// map and before the show. /// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is /// hidden/shown after changing the DX or DY attributes from inside the /// callback, the size of the drawing area will immediately change, so the /// parameters with and height will be invalid. /// To update the parameters consult the DRAWSIZE attribute. /// Also activate the drawing toolkit only after updating the DX or DY attributes. /// Affects IupCanvas, IupGLCanvas, IupDialog pub fn setResizeCallback(self: Initializer, callback: ?*const OnResizeFn) Initializer { const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: Initializer, callback: ?*const OnUnmapFn) Initializer { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub fn setGetFocusCallback(self: Initializer, callback: ?*const OnGetFocusFn) Initializer { const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released. /// Callback int function(Ihandle* ih, int button, int pressed, int x, int y, /// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status: /// string) -> (ret: number) [in Lua] ih: identifies the element that activated /// the event. /// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse /// button (button 1); IUP_BUTTON2 - middle mouse button (button 2); /// IUP_BUTTON3 - right mouse button (button 3). /// pressed: indicates the state of the button: 0 - mouse button was released; /// 1 - mouse button was pressed. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of the mouse buttons and some keyboard keys at the moment /// the event is generated. /// The following macros must be used for verification: iup_isshift(status) /// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status) /// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status) /// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if /// the respective key or button is pressed, and 0 otherwise. /// These macros are also available in Lua, returning a boolean. /// Returns: IUP_CLOSE will be processed. /// On some controls if IUP_IGNORE is returned the action is ignored (this is /// system dependent). /// Notes This callback can be used to customize a button behavior. /// For a standard button behavior use the ACTION callback of the IupButton. /// For a single click the callback is called twice, one for pressed=1 and one /// for pressed=0. /// Only after both calls the ACTION callback is called. /// In Windows, if a dialog is shown or popup in any situation there could be /// unpredictable results because the native system still has processing to be /// done even after the callback is called. /// A double click is preceded by two single clicks, one for pressed=1 and one /// for pressed=0, and followed by a press=0, all three without the double /// click flag set. /// In GTK, it is preceded by an additional two single clicks sequence. /// For example, for one double click all the following calls are made: /// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [ /// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 /// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 /// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all /// mouse events are redirected only to this control, even if the cursor moves /// outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas pub fn setButtonCallback(self: Initializer, callback: ?*const OnButtonFn) Initializer { const Handler = CallbackHandler(Self, OnButtonFn, "BUTTON_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// VALUECHANGED_CB: Called after the value was interactively changed by the user. /// It is called whenever a BUTTON_PRESS_CB, a BUTTON_RELEASE_CB or a /// MOUSEMOVE_CB would also be called, but if defined those callbacks will not /// be called. /// (since 3.0) int function(Ihandle *ih); [in C]ih:valuechanged_cb() -> (ret: /// number) [in Lua] pub fn setValueChangedCallback(self: Initializer, callback: ?*const OnValueChangedFn) Initializer { const Handler = CallbackHandler(Self, OnValueChangedFn, "VALUECHANGED_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setLDestroyCallback(self: Initializer, callback: ?*const OnLDestroyFn) Initializer { const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB"); Handler.setCallback(self.ref, callback); return self; } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: Initializer, callback: ?*const OnLeaveWindowFn) Initializer { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self.ref, callback); return self; } pub fn setPostMessageCallback(self: Initializer, callback: ?*const OnPostMessageFn) Initializer { const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB"); Handler.setCallback(self.ref, callback); return self; } }; pub fn setStrAttribute(self: *Self, attribute: [:0]const u8, arg: [:0]const u8) void { interop.setStrAttribute(self, attribute, .{}, arg); } pub fn getStrAttribute(self: *Self, attribute: [:0]const u8) [:0]const u8 { return interop.getStrAttribute(self, attribute, .{}); } pub fn setIntAttribute(self: *Self, attribute: [:0]const u8, arg: i32) void { interop.setIntAttribute(self, attribute, .{}, arg); } pub fn getIntAttribute(self: *Self, attribute: [:0]const u8) i32 { return interop.getIntAttribute(self, attribute, .{}); } pub fn setBoolAttribute(self: *Self, attribute: [:0]const u8, arg: bool) void { interop.setBoolAttribute(self, attribute, .{}, arg); } pub fn getBoolAttribute(self: *Self, attribute: [:0]const u8) bool { return interop.getBoolAttribute(self, attribute, .{}); } pub fn getPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8) ?*T { return interop.getPtrAttribute(T, self, attribute, .{}); } pub fn setPtrAttribute(self: *Self, comptime T: type, attribute: [:0]const u8, value: ?*T) void { interop.setPtrAttribute(T, self, attribute, .{}, value); } pub fn setHandle(self: *Self, arg: [:0]const u8) void { interop.setHandle(self, arg); } pub fn fromHandleName(handle_name: [:0]const u8) ?*Self { return interop.fromHandleName(Self, handle_name); } pub fn postMessage(self: *Self, s: [:0]const u8, i: i32, f: f64, p: ?*anyopaque) void { return interop.postMessage(self, s, i, f, p); } /// /// Creates an interface element given its class name and parameters. /// After creation the element still needs to be attached to a container and mapped to the native system so it can be visible. pub fn init() Initializer { var handle = interop.create(Self); if (handle) |valid| { return .{ .ref = @as(*Self, @ptrCast(valid)), }; } else { return .{ .ref = undefined, .last_error = Error.NotInitialized }; } } /// /// Destroys an interface element and all its children. /// Only dialogs, timers, popup menus and images should be normally destroyed, but detached elements can also be destroyed. pub fn deinit(self: *Self) void { interop.destroy(self); } /// /// Creates (maps) the native interface objects corresponding to the given IUP interface elements. /// It will also called recursively to create the native element of all the children in the element's tree. /// The element must be already attached to a mapped container, except the dialog. A child can only be mapped if its parent is already mapped. /// This function is automatically called before the dialog is shown in IupShow, IupShowXY or IupPopup. /// If the element is a dialog then the abstract layout will be updated even if the dialog is already mapped. If the dialog is visible the elements will be immediately repositioned. Calling IupMap for an already mapped dialog is the same as only calling IupRefresh for the dialog. /// Calling IupMap for an already mapped element that is not a dialog does nothing. /// If you add new elements to an already mapped dialog you must call IupMap for that elements. And then call IupRefresh to update the dialog layout. /// If the WID attribute of an element is NULL, it means the element was not already mapped. Some containers do not have a native element associated, like VBOX and HBOX. In this case their WID is a fake value (void*)(-1). /// It is useful for the application to call IupMap when the value of the WID attribute must be known, i.e. the native element must exist, before a dialog is made visible. /// The MAP_CB callback is called at the end of the IupMap function, after all processing, so it can also be used to create other things that depend on the WID attribute. But notice that for non dialog elements it will be called before the dialog layout has been updated, so the element current size will still be 0x0 (since 3.14). pub fn map(self: *Self) !void { try interop.map(self); } /// /// pub fn getDialog(self: *Self) ?*iup.Dialog { return interop.getDialog(self); } /// /// Returns the the child element that has the NAME attribute equals to the given value on the same dialog hierarchy. /// Works also for children of a menu that is associated with a dialog. pub fn getDialogChild(self: *Self, byName: [:0]const u8) ?Element { return interop.getDialogChild(self, byName); } /// /// Updates the size and layout of all controls in the same dialog. /// To be used after changing size attributes, or attributes that affect the size of the control. Can be used for any element inside a dialog, but the layout of the dialog and all controls will be updated. It can change the layout of all the controls inside the dialog because of the dynamic layout positioning. pub fn refresh(self: *Self) void { Impl(Self).refresh(self); } /// /// Updates the size and layout of all controls in the same dialog. pub fn update(self: *Self) void { Impl(Self).update(self); } /// /// Updates the size and layout of all controls in the same dialog. pub fn updateChildren(self: *Self) void { Impl(Self).updateChildren(self); } /// /// Force the element and its children to be redrawn immediately. pub fn redraw(self: *Self, redraw_children: bool) void { Impl(Self).redraw(self, redraw_children); } /// /// FGCOLOR: foreground color. /// The default value is "64 64 64". /// (appears in circular dial since 3.24) pub fn getFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "FGCOLOR", .{}); } /// /// FGCOLOR: foreground color. /// The default value is "64 64 64". /// (appears in circular dial since 3.24) pub fn setFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "FGCOLOR", .{}, rgb); } pub fn getHandleName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "HANDLENAME", .{}); } pub fn setHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "HANDLENAME", .{}, arg); } pub fn getTipBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPBGCOLOR", .{}); } pub fn setTipBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPBGCOLOR", .{}, rgb); } pub fn getXMin(self: *Self) i32 { return interop.getIntAttribute(self, "XMIN", .{}); } pub fn setXMin(self: *Self, arg: i32) void { interop.setIntAttribute(self, "XMIN", .{}, arg); } pub fn getTipIcon(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPICON", .{}); } pub fn setTipIcon(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPICON", .{}, arg); } pub fn getMaxSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MAXSIZE", .{}); return Size.parse(str); } pub fn setMaxSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MAXSIZE", .{}, value); } pub fn getDrawTextWrap(self: *Self) bool { return interop.getBoolAttribute(self, "DRAWTEXTWRAP", .{}); } pub fn setDrawTextWrap(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAWTEXTWRAP", .{}, arg); } pub fn getScreenPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "SCREENPOSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn getPosition(self: *Self) iup.XYPos { var str = interop.getStrAttribute(self, "POSITION", .{}); return iup.XYPos.parse(str, ','); } pub fn setPosition(self: *Self, x: i32, y: i32) void { var buffer: [128]u8 = undefined; var value = iup.XYPos.intIntToString(&buffer, x, y, ','); interop.setStrAttribute(self, "POSITION", .{}, value); } pub fn getDropFilesTarget(self: *Self) bool { return interop.getBoolAttribute(self, "DROPFILESTARGET", .{}); } pub fn setDropFilesTarget(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DROPFILESTARGET", .{}, arg); } pub fn getDrawTextAlignment(self: *Self) ?DrawTextAlignment { var ret = interop.getStrAttribute(self, "DRAWTEXTALIGNMENT", .{}); if (std.ascii.eqlIgnoreCase("ACENTER", ret)) return .ACenter; if (std.ascii.eqlIgnoreCase("ARIGHT", ret)) return .ARight; if (std.ascii.eqlIgnoreCase("ALEFT", ret)) return .ALeft; return null; } pub fn setDrawTextAlignment(self: *Self, arg: ?DrawTextAlignment) void { if (arg) |value| switch (value) { .ACenter => interop.setStrAttribute(self, "DRAWTEXTALIGNMENT", .{}, "ACENTER"), .ARight => interop.setStrAttribute(self, "DRAWTEXTALIGNMENT", .{}, "ARIGHT"), .ALeft => interop.setStrAttribute(self, "DRAWTEXTALIGNMENT", .{}, "ALEFT"), } else { interop.clearAttribute(self, "DRAWTEXTALIGNMENT", .{}); } } pub fn getTip(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIP", .{}); } pub fn setTip(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIP", .{}, arg); } pub fn getDrawTextLayoutCenter(self: *Self) bool { return interop.getBoolAttribute(self, "DRAWTEXTLAYOUTCENTER", .{}); } pub fn setDrawTextLayoutCenter(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAWTEXTLAYOUTCENTER", .{}, arg); } pub fn getType(self: *Self) f64 { return interop.getDoubleAttribute(self, "TYPE", .{}); } pub fn setType(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "TYPE", .{}, arg); } pub fn getCanFocus(self: *Self) bool { return interop.getBoolAttribute(self, "CANFOCUS", .{}); } pub fn setCanFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "CANFOCUS", .{}, arg); } pub fn getDragSourceMove(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGSOURCEMOVE", .{}); } pub fn setDragSourceMove(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGSOURCEMOVE", .{}, arg); } pub fn getVisible(self: *Self) bool { return interop.getBoolAttribute(self, "VISIBLE", .{}); } pub fn setVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "VISIBLE", .{}, arg); } pub fn getLineX(self: *Self) f64 { return interop.getDoubleAttribute(self, "LINEX", .{}); } pub fn setLineX(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "LINEX", .{}, arg); } pub fn getCursor(self: *Self) ?iup.Element { if (interop.getHandleAttribute(self, "CURSOR", .{})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } pub fn setCursor(self: *Self, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "CURSOR", .{}, arg); } pub fn setCursorHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "CURSOR", .{}, arg); } pub fn getLineY(self: *Self) f64 { return interop.getDoubleAttribute(self, "LINEY", .{}); } pub fn setLineY(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "LINEY", .{}, arg); } pub fn zOrder(self: *Self, arg: ?ZOrder) void { if (arg) |value| switch (value) { .Top => interop.setStrAttribute(self, "ZORDER", .{}, "TOP"), .Bottom => interop.setStrAttribute(self, "ZORDER", .{}, "BOTTOM"), } else { interop.clearAttribute(self, "ZORDER", .{}); } } pub fn getDrawLineWidth(self: *Self) i32 { return interop.getIntAttribute(self, "DRAWLINEWIDTH", .{}); } pub fn setDrawLineWidth(self: *Self, arg: i32) void { interop.setIntAttribute(self, "DRAWLINEWIDTH", .{}, arg); } pub fn getX(self: *Self) i32 { return interop.getIntAttribute(self, "X", .{}); } pub fn getY(self: *Self) i32 { return interop.getIntAttribute(self, "Y", .{}); } pub fn getDragDrop(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGDROP", .{}); } pub fn setDragDrop(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGDROP", .{}, arg); } pub fn getTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "THEME", .{}); } pub fn setTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "THEME", .{}, arg); } /// /// FLATCOLOR: color of the border when FLAT=Yes. /// Default: "160 160 160". /// (since 3.24) pub fn getFlatColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "FLATCOLOR", .{}); } /// /// FLATCOLOR: color of the border when FLAT=Yes. /// Default: "160 160 160". /// (since 3.24) pub fn setFlatColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "FLATCOLOR", .{}, rgb); } /// /// EXPAND: the default is "NO". pub fn getExpand(self: *Self) ?Expand { var ret = interop.getStrAttribute(self, "EXPAND", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("HORIZONTAL", ret)) return .Horizontal; if (std.ascii.eqlIgnoreCase("VERTICAL", ret)) return .Vertical; if (std.ascii.eqlIgnoreCase("HORIZONTALFREE", ret)) return .HorizontalFree; if (std.ascii.eqlIgnoreCase("VERTICALFREE", ret)) return .VerticalFree; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } /// /// EXPAND: the default is "NO". pub fn setExpand(self: *Self, arg: ?Expand) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "EXPAND", .{}, "YES"), .Horizontal => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTAL"), .Vertical => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICAL"), .HorizontalFree => interop.setStrAttribute(self, "EXPAND", .{}, "HORIZONTALFREE"), .VerticalFree => interop.setStrAttribute(self, "EXPAND", .{}, "VERTICALFREE"), .No => interop.setStrAttribute(self, "EXPAND", .{}, "NO"), } else { interop.clearAttribute(self, "EXPAND", .{}); } } pub fn getDrawFont(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DRAWFONT", .{}); } pub fn setDrawFont(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DRAWFONT", .{}, arg); } /// /// SIZE (non inheritable): the initial size is "16x80", "80x16" or "40x35" /// according to the dial orientation. /// Set to NULL to allow the automatic layout use smaller values. pub fn getSize(self: *Self) Size { var str = interop.getStrAttribute(self, "SIZE", .{}); return Size.parse(str); } /// /// SIZE (non inheritable): the initial size is "16x80", "80x16" or "40x35" /// according to the dial orientation. /// Set to NULL to allow the automatic layout use smaller values. pub fn setSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "SIZE", .{}, value); } pub fn getPosX(self: *Self) f64 { return interop.getDoubleAttribute(self, "POSX", .{}); } pub fn setPosX(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "POSX", .{}, arg); } pub fn getPosY(self: *Self) f64 { return interop.getDoubleAttribute(self, "POSY", .{}); } pub fn setPosY(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "POSY", .{}, arg); } pub fn getWId(self: *Self) i32 { return interop.getIntAttribute(self, "WID", .{}); } pub fn getTipMarkup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "TIPMARKUP", .{}); } pub fn setTipMarkup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "TIPMARKUP", .{}, arg); } pub fn getYMin(self: *Self) i32 { return interop.getIntAttribute(self, "YMIN", .{}); } pub fn setYMin(self: *Self, arg: i32) void { interop.setIntAttribute(self, "YMIN", .{}, arg); } pub fn getDrawMakeInactive(self: *Self) bool { return interop.getBoolAttribute(self, "DRAWMAKEINACTIVE", .{}); } pub fn setDrawMakeInactive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAWMAKEINACTIVE", .{}, arg); } pub fn getFontSize(self: *Self) i32 { return interop.getIntAttribute(self, "FONTSIZE", .{}); } pub fn setFontSize(self: *Self, arg: i32) void { interop.setIntAttribute(self, "FONTSIZE", .{}, arg); } pub fn getNaturalSize(self: *Self) Size { var str = interop.getStrAttribute(self, "NATURALSIZE", .{}); return Size.parse(str); } pub fn getDropTypes(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DROPTYPES", .{}); } pub fn setDropTypes(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DROPTYPES", .{}, arg); } pub fn getUserSize(self: *Self) Size { var str = interop.getStrAttribute(self, "USERSIZE", .{}); return Size.parse(str); } pub fn setUserSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "USERSIZE", .{}, value); } pub fn getTipDelay(self: *Self) i32 { return interop.getIntAttribute(self, "TIPDELAY", .{}); } pub fn setTipDelay(self: *Self, arg: i32) void { interop.setIntAttribute(self, "TIPDELAY", .{}, arg); } pub fn getScrollBar(self: *Self) bool { return interop.getBoolAttribute(self, "SCROLLBAR", .{}); } pub fn setScrollBar(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "SCROLLBAR", .{}, arg); } pub fn getXHidden(self: *Self) bool { return interop.getBoolAttribute(self, "XHIDDEN", .{}); } pub fn getXAutoHide(self: *Self) bool { return interop.getBoolAttribute(self, "XAUTOHIDE", .{}); } pub fn setXAutoHide(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "XAUTOHIDE", .{}, arg); } pub fn getPropagateFocus(self: *Self) bool { return interop.getBoolAttribute(self, "PROPAGATEFOCUS", .{}); } pub fn setPropagateFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "PROPAGATEFOCUS", .{}, arg); } pub fn getXMax(self: *Self) i32 { return interop.getIntAttribute(self, "XMAX", .{}); } pub fn setXMax(self: *Self, arg: i32) void { interop.setIntAttribute(self, "XMAX", .{}, arg); } pub fn getBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "BGCOLOR", .{}); } pub fn setBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "BGCOLOR", .{}, rgb); } pub fn getDropTarget(self: *Self) bool { return interop.getBoolAttribute(self, "DROPTARGET", .{}); } pub fn setDropTarget(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DROPTARGET", .{}, arg); } pub fn getDX(self: *Self) f64 { return interop.getDoubleAttribute(self, "DX", .{}); } pub fn setDX(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "DX", .{}, arg); } pub fn getDY(self: *Self) f64 { return interop.getDoubleAttribute(self, "DY", .{}); } pub fn setDY(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "DY", .{}, arg); } pub fn getDrawTextEllipsis(self: *Self) bool { return interop.getBoolAttribute(self, "DRAWTEXTELLIPSIS", .{}); } pub fn setDrawTextEllipsis(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAWTEXTELLIPSIS", .{}, arg); } pub fn getDragSource(self: *Self) bool { return interop.getBoolAttribute(self, "DRAGSOURCE", .{}); } pub fn setDragSource(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAGSOURCE", .{}, arg); } pub fn getDrawTextClip(self: *Self) bool { return interop.getBoolAttribute(self, "DRAWTEXTCLIP", .{}); } pub fn setDrawTextClip(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "DRAWTEXTCLIP", .{}, arg); } pub fn getFloating(self: *Self) ?Floating { var ret = interop.getStrAttribute(self, "FLOATING", .{}); if (std.ascii.eqlIgnoreCase("YES", ret)) return .Yes; if (std.ascii.eqlIgnoreCase("IGNORE", ret)) return .Ignore; if (std.ascii.eqlIgnoreCase("NO", ret)) return .No; return null; } pub fn setFloating(self: *Self, arg: ?Floating) void { if (arg) |value| switch (value) { .Yes => interop.setStrAttribute(self, "FLOATING", .{}, "YES"), .Ignore => interop.setStrAttribute(self, "FLOATING", .{}, "IGNORE"), .No => interop.setStrAttribute(self, "FLOATING", .{}, "NO"), } else { interop.clearAttribute(self, "FLOATING", .{}); } } pub fn getNormalizerGroup(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NORMALIZERGROUP", .{}); } pub fn setNormalizerGroup(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NORMALIZERGROUP", .{}, arg); } pub fn getRasterSize(self: *Self) Size { var str = interop.getStrAttribute(self, "RASTERSIZE", .{}); return Size.parse(str); } pub fn setRasterSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "RASTERSIZE", .{}, value); } pub fn getTipFgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "TIPFGCOLOR", .{}); } pub fn setTipFgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "TIPFGCOLOR", .{}, rgb); } pub fn getYHidden(self: *Self) bool { return interop.getBoolAttribute(self, "YHIDDEN", .{}); } pub fn getDrawSize(self: *Self) Size { var str = interop.getStrAttribute(self, "DRAWSIZE", .{}); return Size.parse(str); } pub fn getFontFace(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTFACE", .{}); } pub fn setFontFace(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTFACE", .{}, arg); } pub fn getDrawColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "DRAWCOLOR", .{}); } pub fn setDrawColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "DRAWCOLOR", .{}, rgb); } pub fn getDrawTextOrientation(self: *Self) f64 { return interop.getDoubleAttribute(self, "DRAWTEXTORIENTATION", .{}); } pub fn setDrawTextOrientation(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "DRAWTEXTORIENTATION", .{}, arg); } pub fn getDrawBgColor(self: *Self) ?iup.Rgb { return interop.getRgb(self, "DRAWBGCOLOR", .{}); } pub fn setDrawBgColor(self: *Self, rgb: iup.Rgb) void { interop.setRgb(self, "DRAWBGCOLOR", .{}, rgb); } pub fn getName(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NAME", .{}); } pub fn setName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NAME", .{}, arg); } pub fn getBackingStore(self: *Self) bool { return interop.getBoolAttribute(self, "BACKINGSTORE", .{}); } pub fn setBackingStore(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "BACKINGSTORE", .{}, arg); } pub fn getDrawDriver(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DRAWDRIVER", .{}); } pub fn getYAutoHide(self: *Self) bool { return interop.getBoolAttribute(self, "YAUTOHIDE", .{}); } pub fn setYAutoHide(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "YAUTOHIDE", .{}, arg); } pub fn getDrawStyle(self: *Self) ?DrawStyle { var ret = interop.getStrAttribute(self, "DRAWSTYLE", .{}); if (std.ascii.eqlIgnoreCase("FILL", ret)) return .Fill; if (std.ascii.eqlIgnoreCase("STROKE_DASH", ret)) return .StrokeDash; if (std.ascii.eqlIgnoreCase("STROKE_DOT", ret)) return .StrokeDot; if (std.ascii.eqlIgnoreCase("STROKE_DASH_DOT", ret)) return .StrokeDashDot; if (std.ascii.eqlIgnoreCase("STROKE_DASH_DOT_DOT", ret)) return .StrokeDashDotdot; if (std.ascii.eqlIgnoreCase("DRAW_STROKE", ret)) return .DrawStroke; return null; } pub fn setDrawStyle(self: *Self, arg: ?DrawStyle) void { if (arg) |value| switch (value) { .Fill => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "FILL"), .StrokeDash => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DASH"), .StrokeDot => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DOT"), .StrokeDashDot => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DASH_DOT"), .StrokeDashDotdot => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "STROKE_DASH_DOT_DOT"), .DrawStroke => interop.setStrAttribute(self, "DRAWSTYLE", .{}, "DRAW_STROKE"), } else { interop.clearAttribute(self, "DRAWSTYLE", .{}); } } /// /// VALUE (non inheritable): The dial angular value in radians always. /// The value is reset to zero when the interaction is started, except for ORIENTATION=CIRCULAR. /// When orientation is vertical or horizontal, the dial measures relative angles. /// When orientation is circular the dial measure absolute angles, where the /// origin is at 3 O'clock. pub fn getValue(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "VALUE", .{}); } /// /// VALUE (non inheritable): The dial angular value in radians always. /// The value is reset to zero when the interaction is started, except for ORIENTATION=CIRCULAR. /// When orientation is vertical or horizontal, the dial measures relative angles. /// When orientation is circular the dial measure absolute angles, where the /// origin is at 3 O'clock. pub fn setValue(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "VALUE", .{}, arg); } /// /// ACTIVE, BGCOLOR, FONT, SCREENPOSITION, POSITION, MINSIZE, MAXSIZE, WID, /// TIP, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn getActive(self: *Self) bool { return interop.getBoolAttribute(self, "ACTIVE", .{}); } /// /// ACTIVE, BGCOLOR, FONT, SCREENPOSITION, POSITION, MINSIZE, MAXSIZE, WID, /// TIP, RASTERSIZE, ZORDER, VISIBLE, THEME: also accepted. pub fn setActive(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "ACTIVE", .{}, arg); } pub fn getTipVisible(self: *Self) bool { return interop.getBoolAttribute(self, "TIPVISIBLE", .{}); } pub fn setTipVisible(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TIPVISIBLE", .{}, arg); } pub fn getYMax(self: *Self) i32 { return interop.getIntAttribute(self, "YMAX", .{}); } pub fn setYMax(self: *Self, arg: i32) void { interop.setIntAttribute(self, "YMAX", .{}, arg); } pub fn getExpandWeight(self: *Self) f64 { return interop.getDoubleAttribute(self, "EXPANDWEIGHT", .{}); } pub fn setExpandWeight(self: *Self, arg: f64) void { interop.setDoubleAttribute(self, "EXPANDWEIGHT", .{}, arg); } pub fn getMinSize(self: *Self) Size { var str = interop.getStrAttribute(self, "MINSIZE", .{}); return Size.parse(str); } pub fn setMinSize(self: *Self, width: ?i32, height: ?i32) void { var buffer: [128]u8 = undefined; var value = Size.intIntToString(&buffer, width, height); interop.setStrAttribute(self, "MINSIZE", .{}, value); } /// /// FLAT: use a 1 pixel flat border instead of the default 3 pixels sunken border. /// Can be Yes or No. /// Default: No. /// (since 3.24) pub fn getFlat(self: *Self) bool { return interop.getBoolAttribute(self, "FLAT", .{}); } /// /// FLAT: use a 1 pixel flat border instead of the default 3 pixels sunken border. /// Can be Yes or No. /// Default: No. /// (since 3.24) pub fn setFlat(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "FLAT", .{}, arg); } pub fn getNTheme(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "NTHEME", .{}); } pub fn setNTheme(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "NTHEME", .{}, arg); } pub fn getBorder(self: *Self) bool { return interop.getBoolAttribute(self, "BORDER", .{}); } pub fn getCharSize(self: *Self) Size { var str = interop.getStrAttribute(self, "CHARSIZE", .{}); return Size.parse(str); } pub fn getDragTypes(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "DRAGTYPES", .{}); } pub fn setDragTypes(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "DRAGTYPES", .{}, arg); } pub fn getWheelDropFocus(self: *Self) bool { return interop.getBoolAttribute(self, "WHEELDROPFOCUS", .{}); } pub fn setWheelDropFocus(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "WHEELDROPFOCUS", .{}, arg); } pub fn getFontStyle(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONTSTYLE", .{}); } pub fn setFontStyle(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONTSTYLE", .{}, arg); } pub fn getTouch(self: *Self) bool { return interop.getBoolAttribute(self, "TOUCH", .{}); } pub fn setTouch(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "TOUCH", .{}, arg); } pub fn getFont(self: *Self) [:0]const u8 { return interop.getStrAttribute(self, "FONT", .{}); } pub fn setFont(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "FONT", .{}, arg); } pub fn getMdiClient(self: *Self) bool { return interop.getBoolAttribute(self, "MDICLIENT", .{}); } pub fn setMdiClient(self: *Self, arg: bool) void { interop.setBoolAttribute(self, "MDICLIENT", .{}, arg); } pub fn getMdiMenu(self: *Self) ?*iup.Menu { if (interop.getHandleAttribute(self, "MDIMENU", .{})) |handle| { return @as(*iup.Menu, @ptrCast(handle)); } else { return null; } } pub fn setMdiMenu(self: *Self, arg: *iup.Menu) void { interop.setHandleAttribute(self, "MDIMENU", .{}, arg); } pub fn setMdiMenuHandleName(self: *Self, arg: [:0]const u8) void { interop.setStrAttribute(self, "MDIMENU", .{}, arg); } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabImage(self: *Self, index: i32) ?iup.Element { if (interop.getHandleAttribute(self, "TABIMAGE", .{index})) |handle| { return iup.Element.fromHandle(handle); } else { return null; } } /// /// TABIMAGEn (non inheritable): image name to be used in the respective tab. /// Use IupSetHandle or IupSetAttributeHandle to associate an image to a name. /// n starts at 0. /// See also IupImage. /// In Motif, the image is shown only if TABTITLEn is NULL. /// In Windows and Motif set the BGCOLOR attribute before setting the image. /// When set after map will update the TABIMAGE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABIMAGE (non inheritable) (at children only): Same as TABIMAGEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabImage(self: *Self, index: i32, arg: anytype) !void { try interop.validateHandle(.Image, arg); interop.setHandleAttribute(self, "TABIMAGE", .{index}, arg); } pub fn setTabImageHandleName(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABIMAGE", .{index}, arg); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn getTabTitle(self: *Self, index: i32) [:0]const u8 { return interop.getStrAttribute(self, "TABTITLE", .{index}); } /// /// TABTITLEn (non inheritable): Contains the text to be shown in the /// respective tab title. /// n starts at 0. /// If this value is NULL, it will remain empty. /// The "&" character can be used to define a mnemonic, the next character will /// be used as key. /// Use "&&" to show the "&" character instead on defining a mnemonic. /// The button can be activated from any control in the dialog using the /// "Alt+key" combination. /// (mnemonic support since 3.3). /// When set after map will update the TABTITLE attribute on the respective /// child (since 3.10). /// (since 3.0). /// TABTITLE (non inheritable) (at children only): Same as TABTITLEn but set in /// each child. /// Works only if set before the child is added to the tabs. pub fn setTabTitle(self: *Self, index: i32, arg: [:0]const u8) void { interop.setStrAttribute(self, "TABTITLE", .{index}, arg); } /// /// SCROLL_CB SCROLL_CB Called when some manipulation is made to the scrollbar. /// The canvas is automatically redrawn only if this callback is NOT defined. /// (GTK 2.8) Also the POSX and POSY values will not be correctly updated for /// older GTK versions. /// In Ubuntu, when liboverlay-scrollbar is enabled (the new tiny auto-hide /// scrollbar) only the IUP_SBPOSV and IUP_SBPOSH codes are used. /// Callback int function(Ihandle *ih, int op, float posx, float posy); [in C] /// ih:scroll_cb(op, posx, posy: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// op: indicates the operation performed on the scrollbar. /// If the manipulation was made on the vertical scrollbar, it can have the /// following values: IUP_SBUP - line up IUP_SBDN - line down IUP_SBPGUP - page /// up IUP_SBPGDN - page down IUP_SBPOSV - vertical positioning IUP_SBDRAGV - /// vertical drag If it was on the horizontal scrollbar, the following values /// are valid: IUP_SBLEFT - column left IUP_SBRIGHT - column right IUP_SBPGLEFT /// - page left IUP_SBPGRIGHT - page right IUP_SBPOSH - horizontal positioning /// IUP_SBDRAGH - horizontal drag posx, posy: the same as the ACTION canvas /// callback (corresponding to the values of attributes POSX and POSY). /// Notes IUP_SBDRAGH and IUP_SBDRAGV are not supported in GTK. /// During drag IUP_SBPOSH and IUP_SBPOSV are used. /// In Windows, after a drag when mouse is released IUP_SBPOSH or IUP_SBPOSV /// are called. /// Affects IupCanvas, IupGLCanvas, SCROLLBAR pub fn setScrollCallback(self: *Self, callback: ?*const OnScrollFn) void { const Handler = CallbackHandler(Self, OnScrollFn, "SCROLL_CB"); Handler.setCallback(self, callback); } pub fn setFocusCallback(self: *Self, callback: ?*const OnFocusFn) void { const Handler = CallbackHandler(Self, OnFocusFn, "FOCUS_CB"); Handler.setCallback(self, callback); } /// /// BUTTON_RELEASE_CB: Called when the user releases the left mouse button /// after pressing it over the dial. /// int function(Ihandle *ih, double angle) ih:button_release_cb(angle: number) /// -> (ret: number) [in Lua] ih: identifier of the element that activated the event. /// angle: the dial value converted according to UNIT. pub fn setButtonReleaseCallback(self: *Self, callback: ?*const OnButtonReleaseFn) void { const Handler = CallbackHandler(Self, OnButtonReleaseFn, "BUTTON_RELEASE_CB"); Handler.setCallback(self, callback); } /// /// WOM_CB WOM_CB Action generated when an audio device receives an event. /// [Windows Only] Callback int function(Ihandle *ih, int state); [in C] /// ih:wom_cb(state: number) -> (ret: number) [in Lua] ih: identifies the /// element that activated the event. /// state: can be opening=1, done=0, or closing=-1. /// Notes This callback is used to syncronize video playback with audio. /// It is sent when the audio device: Message Description opening is opened by /// using the waveOutOpen function. /// done is finished with a data block sent by using the waveOutWrite function. /// closing is closed by using the waveOutClose function. /// You must use the HWND attribute when calling waveOutOpen in the dwCallback /// parameter and set fdwOpen to CALLBACK_WINDOW. /// Affects IupDialog, IupCanvas, IupGLCanvas pub fn setWomCallback(self: *Self, callback: ?*const OnWomFn) void { const Handler = CallbackHandler(Self, OnWomFn, "WOM_CB"); Handler.setCallback(self, callback); } /// /// K_ANY K_ANY Action generated when a keyboard event occurs. /// Callback int function(Ihandle *ih, int c); [in C] ih:k_any(c: number) -> /// (ret: number) [in Lua] ih: identifier of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// Returns: If IUP_IGNORE is returned the key is ignored and not processed by /// the control and not propagated. /// If returns IUP_CONTINUE, the key will be processed and the event will be /// propagated to the parent of the element receiving it, this is the default behavior. /// If returns IUP_DEFAULT the key is processed but it is not propagated. /// IUP_CLOSE will be processed. /// Notes Keyboard callbacks depend on the keyboard usage of the control with /// the focus. /// So if you return IUP_IGNORE the control will usually not process the key. /// But be aware that sometimes the control process the key in another event so /// even returning IUP_IGNORE the key can get processed. /// Although it will not be propagated. /// IMPORTANT: The callbacks "K_*" of the dialog or native containers depend on /// the IUP_CONTINUE return value to work while the control is in focus. /// If the callback does not exists it is automatically propagated to the /// parent of the element. /// K_* callbacks All defined keys are also callbacks of any element, called /// when the respective key is activated. /// For example: "K_cC" is also a callback activated when the user press /// Ctrl+C, when the focus is at the element or at a children with focus. /// This is the way an application can create shortcut keys, also called hot keys. /// These callbacks are not available in IupLua. /// Affects All elements with keyboard interaction. pub fn setKAnyCallback(self: *Self, callback: ?*const OnKAnyFn) void { const Handler = CallbackHandler(Self, OnKAnyFn, "K_ANY"); Handler.setCallback(self, callback); } /// /// HELP_CB HELP_CB Action generated when the user press F1 at a control. /// In Motif is also activated by the Help button in some workstations keyboard. /// Callback void function(Ihandle *ih); [in C] ih:help_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Returns: IUP_CLOSE will be processed. /// Affects All elements with user interaction. pub fn setHelpCallback(self: *Self, callback: ?*const OnHelpFn) void { const Handler = CallbackHandler(Self, OnHelpFn, "HELP_CB"); Handler.setCallback(self, callback); } pub fn setDropMotionCallback(self: *Self, callback: ?*const OnDropMotionFn) void { const Handler = CallbackHandler(Self, OnDropMotionFn, "DROPMOTION_CB"); Handler.setCallback(self, callback); } /// /// KEYPRESS_CB KEYPRESS_CB Action generated when a key is pressed or released. /// If the key is pressed and held several calls will occur. /// It is called after the callback K_ANY is processed. /// Callback int function(Ihandle *ih, int c, int press); [in C] /// ih:keypress_cb(c, press: number) -> (ret: number) [in Lua] ih: identifier /// of the element that activated the event. /// c: identifier of typed key. /// Please refer to the Keyboard Codes table for a list of possible values. /// press: 1 is the user pressed the key or 0 otherwise. /// Returns: If IUP_IGNORE is returned the key is ignored by the system. /// IUP_CLOSE will be processed. /// Affects IupCanvas pub fn setKeyPressCallback(self: *Self, callback: ?*const OnKeyPressFn) void { const Handler = CallbackHandler(Self, OnKeyPressFn, "KEYPRESS_CB"); Handler.setCallback(self, callback); } pub fn setDragEndCallback(self: *Self, callback: ?*const OnDragEndFn) void { const Handler = CallbackHandler(Self, OnDragEndFn, "DRAGEND_CB"); Handler.setCallback(self, callback); } pub fn setDragBeginCallback(self: *Self, callback: ?*const OnDragBeginFn) void { const Handler = CallbackHandler(Self, OnDragBeginFn, "DRAGBEGIN_CB"); Handler.setCallback(self, callback); } /// /// ACTION ACTION Action generated when the element is activated. /// Affects each element differently. /// Callback int function(Ihandle *ih); [in C] ih:action() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// In some elements, this callback may receive more parameters, apart from ih. /// Please refer to each element's documentation. /// Affects IupButton, IupItem, IupList, IupText, IupCanvas, IupMultiline, /// IupToggle pub fn setActionCallback(self: *Self, callback: ?*const OnActionFn) void { const Handler = CallbackHandler(Self, OnActionFn, "ACTION"); Handler.setCallback(self, callback); } /// /// MOTION_CB MOTION_CB Action generated when the mouse moves. /// Callback int function(Ihandle *ih, int x, int y, char *status); [in C] /// ih:motion_cb(x, y: number, status: string) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes Between press and release all mouse events are redirected only to /// this control, even if the cursor moves outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupGLCanvas pub fn setMotionCallback(self: *Self, callback: ?*const OnMotionFn) void { const Handler = CallbackHandler(Self, OnMotionFn, "MOTION_CB"); Handler.setCallback(self, callback); } /// /// WHEEL_CB WHEEL_CB Action generated when the mouse wheel is rotated. /// If this callback is not defined the wheel will automatically scroll the /// canvas in the vertical direction by some lines, the SCROLL_CB callback if /// defined will be called with the IUP_SBDRAGV operation. /// Callback int function(Ihandle *ih, float delta, int x, int y, char /// *status); [in C] ih:wheel_cb(delta, x, y: number, status: string) -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// delta: the amount the wheel was rotated in notches. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of mouse buttons and certain keyboard keys at the moment the /// event was generated. /// The same macros used for BUTTON_CB can be used for this status. /// Notes In Motif and GTK delta is always 1 or -1. /// In Windows is some situations delta can reach the value of two. /// In the future with more precise wheels this increment can be changed. /// Affects IupCanvas, IupGLCanvas pub fn setWheelCallback(self: *Self, callback: ?*const OnWheelFn) void { const Handler = CallbackHandler(Self, OnWheelFn, "WHEEL_CB"); Handler.setCallback(self, callback); } /// /// MAP_CB MAP_CB Called right after an element is mapped and its attributes /// updated in IupMap. /// When the element is a dialog, it is called after the layout is updated. /// For all other elements is called before the layout is updated, so the /// element current size will still be 0x0 during MAP_CB (since 3.14). /// Callback int function(Ihandle *ih); [in C] ih:map_cb() -> (ret: number) [in /// Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setMapCallback(self: *Self, callback: ?*const OnMapFn) void { const Handler = CallbackHandler(Self, OnMapFn, "MAP_CB"); Handler.setCallback(self, callback); } /// /// ENTERWINDOW_CB ENTERWINDOW_CB Action generated when the mouse enters the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:enterwindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also LEAVEWINDOW_CB pub fn setEnterWindowCallback(self: *Self, callback: ?*const OnEnterWindowFn) void { const Handler = CallbackHandler(Self, OnEnterWindowFn, "ENTERWINDOW_CB"); Handler.setCallback(self, callback); } /// /// DESTROY_CB DESTROY_CB Called right before an element is destroyed. /// Callback int function(Ihandle *ih); [in C] ih:destroy_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Notes If the dialog is visible then it is hidden before it is destroyed. /// The callback will be called right after it is hidden. /// The callback will be called before all other destroy procedures. /// For instance, if the element has children then it is called before the /// children are destroyed. /// For language binding implementations use the callback name "LDESTROY_CB" to /// release memory allocated by the binding for the element. /// Also the callback will be called before the language callback. /// Affects All. pub fn setDestroyCallback(self: *Self, callback: ?*const OnDestroyFn) void { const Handler = CallbackHandler(Self, OnDestroyFn, "DESTROY_CB"); Handler.setCallback(self, callback); } pub fn setDropDataCallback(self: *Self, callback: ?*const OnDropDataFn) void { const Handler = CallbackHandler(Self, OnDropDataFn, "DROPDATA_CB"); Handler.setCallback(self, callback); } /// /// KILLFOCUS_CB KILLFOCUS_CB Action generated when an element loses keyboard focus. /// This callback is called before the GETFOCUS_CB of the element that gets the focus. /// Callback int function(Ihandle *ih); [in C] ih:killfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Affects All elements with user interaction, except menus. /// In Windows, there are restrictions when using this callback. /// From MSDN on WM_KILLFOCUS: "While processing this message, do not make any /// function calls that display or activate a window. /// This causes the thread to yield control and can cause the application to /// stop responding to messages. /// See Also GETFOCUS_CB, IupGetFocus, IupSetFocus pub fn setKillFocusCallback(self: *Self, callback: ?*const OnKillFocusFn) void { const Handler = CallbackHandler(Self, OnKillFocusFn, "KILLFOCUS_CB"); Handler.setCallback(self, callback); } /// /// MOUSEMOVE_CB: Called each time the user moves the dial with the mouse /// button pressed. /// The angle the dial rotated since it was initialized is passed as a parameter. /// int function(Ihandle *ih, double angle); [in C] ih:mousemove_cb(angle: /// number) -> (ret: number) [in Lua] pub fn setMouseMoveCallback(self: *Self, callback: ?*const OnMouseMoveFn) void { const Handler = CallbackHandler(Self, OnMouseMoveFn, "MOUSEMOVE_CB"); Handler.setCallback(self, callback); } pub fn setDragDataCallback(self: *Self, callback: ?*const OnDragDataFn) void { const Handler = CallbackHandler(Self, OnDragDataFn, "DRAGDATA_CB"); Handler.setCallback(self, callback); } /// /// BUTTON_PRESS_CB: Called when the user presses the left mouse button over /// the dial. /// The angle here is always zero, except for the circular dial. /// int function(Ihandle *ih, double angle) ih:button_press_cb(angle: number) /// -> (ret: number) [in Lua] pub fn setButtonPressCallback(self: *Self, callback: ?*const OnButtonPressFn) void { const Handler = CallbackHandler(Self, OnButtonPressFn, "BUTTON_PRESS_CB"); Handler.setCallback(self, callback); } pub fn setDragDataSizeCallback(self: *Self, callback: ?*const OnDragDataSizeFn) void { const Handler = CallbackHandler(Self, OnDragDataSizeFn, "DRAGDATASIZE_CB"); Handler.setCallback(self, callback); } /// /// DROPFILES_CB DROPFILES_CB Action called when a file is "dropped" into the control. /// When several files are dropped at once, the callback is called several /// times, once for each file. /// If defined after the element is mapped then the attribute DROPFILESTARGET /// must be set to YES. /// [Windows and GTK Only] (GTK 2.6) Callback int function(Ihandle *ih, const /// char* filename, int num, int x, int y); [in C] ih:dropfiles_cb(filename: /// string; num, x, y: number) -> (ret: number) [in Lua] ih: identifier of the /// element that activated the event. /// filename: Name of the dropped file. /// num: Number index of the dropped file. /// If several files are dropped, num is the index of the dropped file starting /// from "total-1" to "0". /// x: X coordinate of the point where the user released the mouse button. /// y: Y coordinate of the point where the user released the mouse button. /// Returns: If IUP_IGNORE is returned the callback will NOT be called for the /// next dropped files, and the processing of dropped files will be interrupted. /// Affects IupDialog, IupCanvas, IupGLCanvas, IupText, IupList pub fn setDropFilesCallback(self: *Self, callback: ?*const OnDropFilesFn) void { const Handler = CallbackHandler(Self, OnDropFilesFn, "DROPFILES_CB"); Handler.setCallback(self, callback); } /// /// RESIZE_CB RESIZE_CB Action generated when the canvas or dialog size is changed. /// Callback int function(Ihandle *ih, int width, int height); [in C] /// ih:resize_cb(width, height: number) -> (ret: number) [in Lua] ih: /// identifier of the element that activated the event. /// width: the width of the internal element size in pixels not considering the /// decorations (client size) height: the height of the internal element size /// in pixels not considering the decorations (client size) Notes For the /// dialog, this action is also generated when the dialog is mapped, after the /// map and before the show. /// When XAUTOHIDE=Yes or YAUTOHIDE=Yes, if the canvas scrollbar is /// hidden/shown after changing the DX or DY attributes from inside the /// callback, the size of the drawing area will immediately change, so the /// parameters with and height will be invalid. /// To update the parameters consult the DRAWSIZE attribute. /// Also activate the drawing toolkit only after updating the DX or DY attributes. /// Affects IupCanvas, IupGLCanvas, IupDialog pub fn setResizeCallback(self: *Self, callback: ?*const OnResizeFn) void { const Handler = CallbackHandler(Self, OnResizeFn, "RESIZE_CB"); Handler.setCallback(self, callback); } /// /// UNMAP_CB UNMAP_CB Called right before an element is unmapped. /// Callback int function(Ihandle *ih); [in C] ih:unmap_cb() -> (ret: number) /// [in Lua] ih: identifier of the element that activated the event. /// Affects All that have a native representation. pub fn setUnmapCallback(self: *Self, callback: ?*const OnUnmapFn) void { const Handler = CallbackHandler(Self, OnUnmapFn, "UNMAP_CB"); Handler.setCallback(self, callback); } /// /// GETFOCUS_CB GETFOCUS_CB Action generated when an element is given keyboard focus. /// This callback is called after the KILLFOCUS_CB of the element that loosed /// the focus. /// The IupGetFocus function during the callback returns the element that /// loosed the focus. /// Callback int function(Ihandle *ih); [in C] ih:getfocus_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that received keyboard focus. /// Affects All elements with user interaction, except menus. /// See Also KILLFOCUS_CB, IupGetFocus, IupSetFocus pub fn setGetFocusCallback(self: *Self, callback: ?*const OnGetFocusFn) void { const Handler = CallbackHandler(Self, OnGetFocusFn, "GETFOCUS_CB"); Handler.setCallback(self, callback); } /// /// BUTTON_CB BUTTON_CB Action generated when a mouse button is pressed or released. /// Callback int function(Ihandle* ih, int button, int pressed, int x, int y, /// char* status); [in C] ih:button_cb(button, pressed, x, y: number, status: /// string) -> (ret: number) [in Lua] ih: identifies the element that activated /// the event. /// button: identifies the activated mouse button: IUP_BUTTON1 - left mouse /// button (button 1); IUP_BUTTON2 - middle mouse button (button 2); /// IUP_BUTTON3 - right mouse button (button 3). /// pressed: indicates the state of the button: 0 - mouse button was released; /// 1 - mouse button was pressed. /// x, y: position in the canvas where the event has occurred, in pixels. /// status: status of the mouse buttons and some keyboard keys at the moment /// the event is generated. /// The following macros must be used for verification: iup_isshift(status) /// iup_iscontrol(status) iup_isbutton1(status) iup_isbutton2(status) /// iup_isbutton3(status) iup_isbutton4(status) iup_isbutton5(status) /// iup_isdouble(status) iup_isalt(status) iup_issys(status) They return 1 if /// the respective key or button is pressed, and 0 otherwise. /// These macros are also available in Lua, returning a boolean. /// Returns: IUP_CLOSE will be processed. /// On some controls if IUP_IGNORE is returned the action is ignored (this is /// system dependent). /// Notes This callback can be used to customize a button behavior. /// For a standard button behavior use the ACTION callback of the IupButton. /// For a single click the callback is called twice, one for pressed=1 and one /// for pressed=0. /// Only after both calls the ACTION callback is called. /// In Windows, if a dialog is shown or popup in any situation there could be /// unpredictable results because the native system still has processing to be /// done even after the callback is called. /// A double click is preceded by two single clicks, one for pressed=1 and one /// for pressed=0, and followed by a press=0, all three without the double /// click flag set. /// In GTK, it is preceded by an additional two single clicks sequence. /// For example, for one double click all the following calls are made: /// BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) BUTTON_CB(but=1 (0), x=154, y=83 [ /// 1 ]) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 /// (0), x=154, y=83 [ 1 ]) (in GTK only) BUTTON_CB(but=1 (1), x=154, y=83 [ 1 /// D ]) BUTTON_CB(but=1 (0), x=154, y=83 [ 1 ]) Between press and release all /// mouse events are redirected only to this control, even if the cursor moves /// outside the element. /// So the BUTTON_CB callback when released and the MOTION_CB callback can be /// called with coordinates outside the element rectangle. /// Affects IupCanvas, IupButton, IupText, IupList, IupGLCanvas pub fn setButtonCallback(self: *Self, callback: ?*const OnButtonFn) void { const Handler = CallbackHandler(Self, OnButtonFn, "BUTTON_CB"); Handler.setCallback(self, callback); } /// /// VALUECHANGED_CB: Called after the value was interactively changed by the user. /// It is called whenever a BUTTON_PRESS_CB, a BUTTON_RELEASE_CB or a /// MOUSEMOVE_CB would also be called, but if defined those callbacks will not /// be called. /// (since 3.0) int function(Ihandle *ih); [in C]ih:valuechanged_cb() -> (ret: /// number) [in Lua] pub fn setValueChangedCallback(self: *Self, callback: ?*const OnValueChangedFn) void { const Handler = CallbackHandler(Self, OnValueChangedFn, "VALUECHANGED_CB"); Handler.setCallback(self, callback); } pub fn setLDestroyCallback(self: *Self, callback: ?*const OnLDestroyFn) void { const Handler = CallbackHandler(Self, OnLDestroyFn, "LDESTROY_CB"); Handler.setCallback(self, callback); } /// /// LEAVEWINDOW_CB LEAVEWINDOW_CB Action generated when the mouse leaves the /// native element. /// Callback int function(Ihandle *ih); [in C] ih:leavewindow_cb() -> (ret: /// number) [in Lua] ih: identifier of the element that activated the event. /// Notes When the cursor is moved from one element to another, the call order /// in all platforms will be first the LEAVEWINDOW_CB callback of the old /// control followed by the ENTERWINDOW_CB callback of the new control. /// (since 3.14) If the mouse button is hold pressed and the cursor moves /// outside the element the behavior is system dependent. /// In Windows the LEAVEWINDOW_CB/ENTERWINDOW_CB callbacks are NOT called, in /// GTK the callbacks are called. /// Affects All controls with user interaction. /// See Also ENTERWINDOW_CB pub fn setLeaveWindowCallback(self: *Self, callback: ?*const OnLeaveWindowFn) void { const Handler = CallbackHandler(Self, OnLeaveWindowFn, "LEAVEWINDOW_CB"); Handler.setCallback(self, callback); } pub fn setPostMessageCallback(self: *Self, callback: ?*const OnPostMessageFn) void { const Handler = CallbackHandler(Self, OnPostMessageFn, "POSTMESSAGE_CB"); Handler.setCallback(self, callback); } }; test "Dial FgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial HandleName" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setHandleName("Hello").unwrap()); defer item.deinit(); var ret = item.getHandleName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial TipBgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTipBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial XMin" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setXMin(42).unwrap()); defer item.deinit(); var ret = item.getXMin(); try std.testing.expect(ret == 42); } test "Dial TipIcon" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTipIcon("Hello").unwrap()); defer item.deinit(); var ret = item.getTipIcon(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial MaxSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setMaxSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMaxSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Dial DrawTextWrap" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawTextWrap(true).unwrap()); defer item.deinit(); var ret = item.getDrawTextWrap(); try std.testing.expect(ret == true); } test "Dial Position" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setPosition(9, 10).unwrap()); defer item.deinit(); var ret = item.getPosition(); try std.testing.expect(ret.x == 9 and ret.y == 10); } test "Dial DropFilesTarget" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDropFilesTarget(true).unwrap()); defer item.deinit(); var ret = item.getDropFilesTarget(); try std.testing.expect(ret == true); } test "Dial DrawTextAlignment" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawTextAlignment(.ACenter).unwrap()); defer item.deinit(); var ret = item.getDrawTextAlignment(); try std.testing.expect(ret != null and ret.? == .ACenter); } test "Dial Tip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTip("Hello").unwrap()); defer item.deinit(); var ret = item.getTip(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial DrawTextLayoutCenter" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawTextLayoutCenter(true).unwrap()); defer item.deinit(); var ret = item.getDrawTextLayoutCenter(); try std.testing.expect(ret == true); } test "Dial Type" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setType(3.14).unwrap()); defer item.deinit(); var ret = item.getType(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial CanFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setCanFocus(true).unwrap()); defer item.deinit(); var ret = item.getCanFocus(); try std.testing.expect(ret == true); } test "Dial DragSourceMove" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDragSourceMove(true).unwrap()); defer item.deinit(); var ret = item.getDragSourceMove(); try std.testing.expect(ret == true); } test "Dial Visible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setVisible(true).unwrap()); defer item.deinit(); var ret = item.getVisible(); try std.testing.expect(ret == true); } test "Dial LineX" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setLineX(3.14).unwrap()); defer item.deinit(); var ret = item.getLineX(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial LineY" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setLineY(3.14).unwrap()); defer item.deinit(); var ret = item.getLineY(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial DrawLineWidth" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawLineWidth(42).unwrap()); defer item.deinit(); var ret = item.getDrawLineWidth(); try std.testing.expect(ret == 42); } test "Dial DragDrop" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDragDrop(true).unwrap()); defer item.deinit(); var ret = item.getDragDrop(); try std.testing.expect(ret == true); } test "Dial Theme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial FlatColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFlatColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getFlatColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial Expand" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setExpand(.Yes).unwrap()); defer item.deinit(); var ret = item.getExpand(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Dial DrawFont" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawFont("Hello").unwrap()); defer item.deinit(); var ret = item.getDrawFont(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial Size" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Dial PosX" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setPosX(3.14).unwrap()); defer item.deinit(); var ret = item.getPosX(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial PosY" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setPosY(3.14).unwrap()); defer item.deinit(); var ret = item.getPosY(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial TipMarkup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTipMarkup("Hello").unwrap()); defer item.deinit(); var ret = item.getTipMarkup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial YMin" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setYMin(42).unwrap()); defer item.deinit(); var ret = item.getYMin(); try std.testing.expect(ret == 42); } test "Dial DrawMakeInactive" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawMakeInactive(true).unwrap()); defer item.deinit(); var ret = item.getDrawMakeInactive(); try std.testing.expect(ret == true); } test "Dial FontSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFontSize(42).unwrap()); defer item.deinit(); var ret = item.getFontSize(); try std.testing.expect(ret == 42); } test "Dial DropTypes" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDropTypes("Hello").unwrap()); defer item.deinit(); var ret = item.getDropTypes(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial UserSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setUserSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getUserSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Dial TipDelay" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTipDelay(42).unwrap()); defer item.deinit(); var ret = item.getTipDelay(); try std.testing.expect(ret == 42); } test "Dial ScrollBar" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setScrollBar(true).unwrap()); defer item.deinit(); var ret = item.getScrollBar(); try std.testing.expect(ret == true); } test "Dial XAutoHide" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setXAutoHide(true).unwrap()); defer item.deinit(); var ret = item.getXAutoHide(); try std.testing.expect(ret == true); } test "Dial PropagateFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setPropagateFocus(true).unwrap()); defer item.deinit(); var ret = item.getPropagateFocus(); try std.testing.expect(ret == true); } test "Dial XMax" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setXMax(42).unwrap()); defer item.deinit(); var ret = item.getXMax(); try std.testing.expect(ret == 42); } test "Dial BgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial DropTarget" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDropTarget(true).unwrap()); defer item.deinit(); var ret = item.getDropTarget(); try std.testing.expect(ret == true); } test "Dial DX" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDX(3.14).unwrap()); defer item.deinit(); var ret = item.getDX(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial DY" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDY(3.14).unwrap()); defer item.deinit(); var ret = item.getDY(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial DrawTextEllipsis" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawTextEllipsis(true).unwrap()); defer item.deinit(); var ret = item.getDrawTextEllipsis(); try std.testing.expect(ret == true); } test "Dial DragSource" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDragSource(true).unwrap()); defer item.deinit(); var ret = item.getDragSource(); try std.testing.expect(ret == true); } test "Dial DrawTextClip" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawTextClip(true).unwrap()); defer item.deinit(); var ret = item.getDrawTextClip(); try std.testing.expect(ret == true); } test "Dial Floating" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFloating(.Yes).unwrap()); defer item.deinit(); var ret = item.getFloating(); try std.testing.expect(ret != null and ret.? == .Yes); } test "Dial NormalizerGroup" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setNormalizerGroup("Hello").unwrap()); defer item.deinit(); var ret = item.getNormalizerGroup(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial RasterSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setRasterSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getRasterSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Dial TipFgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTipFgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getTipFgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial FontFace" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFontFace("Hello").unwrap()); defer item.deinit(); var ret = item.getFontFace(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial DrawColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getDrawColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial DrawTextOrientation" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawTextOrientation(3.14).unwrap()); defer item.deinit(); var ret = item.getDrawTextOrientation(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial DrawBgColor" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawBgColor(.{ .r = 9, .g = 10, .b = 11 }).unwrap()); defer item.deinit(); var ret = item.getDrawBgColor(); try std.testing.expect(ret != null and ret.?.r == 9 and ret.?.g == 10 and ret.?.b == 11); } test "Dial Name" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setName("Hello").unwrap()); defer item.deinit(); var ret = item.getName(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial BackingStore" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setBackingStore(true).unwrap()); defer item.deinit(); var ret = item.getBackingStore(); try std.testing.expect(ret == true); } test "Dial YAutoHide" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setYAutoHide(true).unwrap()); defer item.deinit(); var ret = item.getYAutoHide(); try std.testing.expect(ret == true); } test "Dial DrawStyle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDrawStyle(.Fill).unwrap()); defer item.deinit(); var ret = item.getDrawStyle(); try std.testing.expect(ret != null and ret.? == .Fill); } test "Dial Value" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setValue("Hello").unwrap()); defer item.deinit(); var ret = item.getValue(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial Active" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setActive(true).unwrap()); defer item.deinit(); var ret = item.getActive(); try std.testing.expect(ret == true); } test "Dial TipVisible" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTipVisible(true).unwrap()); defer item.deinit(); var ret = item.getTipVisible(); try std.testing.expect(ret == true); } test "Dial YMax" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setYMax(42).unwrap()); defer item.deinit(); var ret = item.getYMax(); try std.testing.expect(ret == 42); } test "Dial ExpandWeight" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setExpandWeight(3.14).unwrap()); defer item.deinit(); var ret = item.getExpandWeight(); try std.testing.expect(ret == @as(f64, 3.14)); } test "Dial MinSize" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setMinSize(9, 10).unwrap()); defer item.deinit(); var ret = item.getMinSize(); try std.testing.expect(ret.width != null and ret.width.? == 9 and ret.height != null and ret.height.? == 10); } test "Dial Flat" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFlat(true).unwrap()); defer item.deinit(); var ret = item.getFlat(); try std.testing.expect(ret == true); } test "Dial NTheme" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setNTheme("Hello").unwrap()); defer item.deinit(); var ret = item.getNTheme(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial DragTypes" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setDragTypes("Hello").unwrap()); defer item.deinit(); var ret = item.getDragTypes(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial WheelDropFocus" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setWheelDropFocus(true).unwrap()); defer item.deinit(); var ret = item.getWheelDropFocus(); try std.testing.expect(ret == true); } test "Dial FontStyle" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFontStyle("Hello").unwrap()); defer item.deinit(); var ret = item.getFontStyle(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); } test "Dial Touch" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setTouch(true).unwrap()); defer item.deinit(); var ret = item.getTouch(); try std.testing.expect(ret == true); } test "Dial Font" { try iup.MainLoop.open(); defer iup.MainLoop.close(); var item = try (iup.Dial.init().setFont("Hello").unwrap()); defer item.deinit(); var ret = item.getFont(); try std.testing.expect(std.mem.eql(u8, ret, "Hello")); }
https://raw.githubusercontent.com/batiati/IUPforZig/dad3a26ab0e214a379f59d8d664830e1e08d8722/src/elements/dial.zig
const std = @import("std"); const History = struct { lists: std.ArrayList(std.ArrayList(i32)), pub fn init(numbersText: []const u8, allocator: std.mem.Allocator) !History { var result = History{ .lists = std.ArrayList(std.ArrayList(i32)).init(allocator) }; try result.lists.append(std.ArrayList(i32).init(allocator)); var itNumber = std.mem.tokenizeScalar(u8, numbersText, ' '); while (itNumber.next()) |numText| { try result.lists.items[result.lists.items.len - 1].append(try std.fmt.parseInt(i32, numText, 10)); } return result; } pub fn reduce(self: *@This(), allocator: std.mem.Allocator) !bool { var more: bool = false; var newList = std.ArrayList(i32).init(allocator); var last: ?i32 = null; for (self.lists.getLast().items) |num| { if (last) |l| { const diff = num - l; if (diff != 0) { more = true; } try newList.append(diff); } last = num; } try self.lists.append(newList); return more; } pub fn nextValue(self: *const @This()) i32 { var val: ?i32 = null; var i: usize = self.lists.items.len - 1; while (i > 0) { i -= 1; val = (val orelse 0) + self.lists.items[i].getLast(); } return val.?; } pub fn prevValue(self: *const @This()) i32 { var val: ?i32 = null; var i: usize = self.lists.items.len - 1; while (i > 0) { i -= 1; val = self.lists.items[i].items[0] - (val orelse 0); } return val.?; } pub fn deinit(self: *const @This()) void { for (self.lists.items) |list| { list.deinit(); } self.lists.deinit(); } }; fn part1(input: []const u8, allocator: std.mem.Allocator) !i32 { var lists = std.ArrayList(History).init(allocator); defer lists.deinit(); var it = std.mem.tokenizeAny(u8, input, "\r\n"); while (it.next()) |line| { var hist = try History.init(line, allocator); while (try hist.reduce(allocator)) {} try lists.append(hist); } var sum: i32 = 0; for (lists.items) |hist| { sum += hist.nextValue(); hist.deinit(); } return sum; } test "part 1" { const example = \\0 3 6 9 12 15 \\1 3 6 10 15 21 \\10 13 16 21 30 45 ; try std.testing.expectEqual(@as(i32, 114), try part1(example, std.testing.allocator)); } fn part2(input: []const u8, allocator: std.mem.Allocator) !i32 { var lists = std.ArrayList(History).init(allocator); defer lists.deinit(); var it = std.mem.tokenizeAny(u8, input, "\r\n"); while (it.next()) |line| { var hist = try History.init(line, allocator); while (try hist.reduce(allocator)) {} try lists.append(hist); } var sum: i32 = 0; for (lists.items) |hist| { sum += hist.prevValue(); hist.deinit(); } return sum; } test "part 2" { const example = \\0 3 6 9 12 15 \\1 3 6 10 15 21 \\10 13 16 21 30 45 ; try std.testing.expectEqual(@as(i32, 2), try part2(example, std.testing.allocator)); } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); // https://adventofcode.com/2023/day/9 const input = @embedFile("input"); std.debug.print("Day 9, 2023: Mirage Maintenance\n", .{}); std.debug.print(" Part 1: {}\n", .{try part1(input, allocator)}); std.debug.print(" Part 2: {}\n", .{try part2(input, allocator)}); }
https://raw.githubusercontent.com/ocitrev/advent-of-code/7ecf5b4d74b68bec14e2dabc8ea7550f3df75020/src/2023/day9.zig
const std = @import("std"); const ArrayList = std.ArrayList; const common = @import("common.zig"); const expect = std.testing.expect; const print = std.debug.print; fn measureIncreases(depths: []const usize) usize { var count: usize = 0; var previous: usize = undefined; for (depths) |v| { if (v > previous) count += 1; previous = v; } return count; } fn measureSlidingIncreases(depths: []const usize) usize { var count: usize = 0; var previous: usize = undefined; for (depths, 0..) |_, index| { var sum: usize = 0; var end = if (index < depths.len - 3) index + 3 else depths.len; for (depths[index..end]) |v| sum += v; if (sum > previous) count += 1; previous = sum; } return count; } pub fn main() anyerror!void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var list = try common.readFile(allocator, "data/day1input.txt"); var depths = ArrayList(usize).init(allocator); for (list) |line| { try depths.append(try std.fmt.parseInt(usize, line, 10)); } print("Day 1: {d}, {d}\n", .{ measureIncreases(depths.items), measureSlidingIncreases(depths.items) }); } test "Example depths" { const values = [_]usize{ 199, 200, 208, 210, 200, 207, 240, 269, 260, 263 }; var increases = measureIncreases(values[0..]); try expect(increases == 7); var slidingIncreases = measureSlidingIncreases(values[0..]); try expect(slidingIncreases == 5); }
https://raw.githubusercontent.com/brettporter/advent-of-code-2021/853781b877cedb62eb4a70cb536db4b91ccae060/src/advent1.zig
const std = @import("std.zig"); const assert = std.debug.assert; const testing = std.testing; const mem = std.mem; const math = std.math; pub fn binarySearch( comptime T: type, key: T, items: []const T, context: anytype, comptime compareFn: fn (context: @TypeOf(context), lhs: T, rhs: T) math.Order, ) ?usize { var left: usize = 0; var right: usize = items.len; while (left < right) { // Avoid overflowing in the midpoint calculation const mid = left + (right - left) / 2; // Compare the key with the midpoint element switch (compareFn(context, key, items[mid])) { .eq => return mid, .gt => left = mid + 1, .lt => right = mid, } } return null; } test "binarySearch" { const S = struct { fn order_u32(context: void, lhs: u32, rhs: u32) math.Order { _ = context; return math.order(lhs, rhs); } fn order_i32(context: void, lhs: i32, rhs: i32) math.Order { _ = context; return math.order(lhs, rhs); } }; try testing.expectEqual( @as(?usize, null), binarySearch(u32, 1, &[_]u32{}, {}, S.order_u32), ); try testing.expectEqual( @as(?usize, 0), binarySearch(u32, 1, &[_]u32{1}, {}, S.order_u32), ); try testing.expectEqual( @as(?usize, null), binarySearch(u32, 1, &[_]u32{0}, {}, S.order_u32), ); try testing.expectEqual( @as(?usize, null), binarySearch(u32, 0, &[_]u32{1}, {}, S.order_u32), ); try testing.expectEqual( @as(?usize, 4), binarySearch(u32, 5, &[_]u32{ 1, 2, 3, 4, 5 }, {}, S.order_u32), ); try testing.expectEqual( @as(?usize, 0), binarySearch(u32, 2, &[_]u32{ 2, 4, 8, 16, 32, 64 }, {}, S.order_u32), ); try testing.expectEqual( @as(?usize, 1), binarySearch(i32, -4, &[_]i32{ -7, -4, 0, 9, 10 }, {}, S.order_i32), ); try testing.expectEqual( @as(?usize, 3), binarySearch(i32, 98, &[_]i32{ -100, -25, 2, 98, 99, 100 }, {}, S.order_i32), ); } /// Stable in-place sort. O(n) best case, O(pow(n, 2)) worst case. O(1) memory (no allocator required). pub fn insertionSort( comptime T: type, items: []T, context: anytype, comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool, ) void { var i: usize = 1; while (i < items.len) : (i += 1) { const x = items[i]; var j: usize = i; while (j > 0 and lessThan(context, x, items[j - 1])) : (j -= 1) { items[j] = items[j - 1]; } items[j] = x; } } const Range = struct { start: usize, end: usize, fn init(start: usize, end: usize) Range { return Range{ .start = start, .end = end, }; } fn length(self: Range) usize { return self.end - self.start; } }; const Iterator = struct { size: usize, power_of_two: usize, numerator: usize, decimal: usize, denominator: usize, decimal_step: usize, numerator_step: usize, fn init(size2: usize, min_level: usize) Iterator { const power_of_two = math.floorPowerOfTwo(usize, size2); const denominator = power_of_two / min_level; return Iterator{ .numerator = 0, .decimal = 0, .size = size2, .power_of_two = power_of_two, .denominator = denominator, .decimal_step = size2 / denominator, .numerator_step = size2 % denominator, }; } fn begin(self: *Iterator) void { self.numerator = 0; self.decimal = 0; } fn nextRange(self: *Iterator) Range { const start = self.decimal; self.decimal += self.decimal_step; self.numerator += self.numerator_step; if (self.numerator >= self.denominator) { self.numerator -= self.denominator; self.decimal += 1; } return Range{ .start = start, .end = self.decimal, }; } fn finished(self: *Iterator) bool { return self.decimal >= self.size; } fn nextLevel(self: *Iterator) bool { self.decimal_step += self.decimal_step; self.numerator_step += self.numerator_step; if (self.numerator_step >= self.denominator) { self.numerator_step -= self.denominator; self.decimal_step += 1; } return (self.decimal_step < self.size); } fn length(self: *Iterator) usize { return self.decimal_step; } }; const Pull = struct { from: usize, to: usize, count: usize, range: Range, }; /// Stable in-place sort. O(n) best case, O(n*log(n)) worst case and average case. O(1) memory (no allocator required). /// Currently implemented as block sort. pub fn sort( comptime T: type, items: []T, context: anytype, comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool, ) void { // Implementation ported from https://github.com/BonzaiThePenguin/WikiSort/blob/master/WikiSort.c var cache: [512]T = undefined; if (items.len < 4) { if (items.len == 3) { // hard coded insertion sort if (lessThan(context, items[1], items[0])) mem.swap(T, &items[0], &items[1]); if (lessThan(context, items[2], items[1])) { mem.swap(T, &items[1], &items[2]); if (lessThan(context, items[1], items[0])) mem.swap(T, &items[0], &items[1]); } } else if (items.len == 2) { if (lessThan(context, items[1], items[0])) mem.swap(T, &items[0], &items[1]); } return; } // sort groups of 4-8 items at a time using an unstable sorting network, // but keep track of the original item orders to force it to be stable // http://pages.ripco.net/~jgamble/nw.html var iterator = Iterator.init(items.len, 4); while (!iterator.finished()) { var order = [_]u8{ 0, 1, 2, 3, 4, 5, 6, 7 }; const range = iterator.nextRange(); const sliced_items = items[range.start..]; switch (range.length()) { 8 => { swap(T, sliced_items, context, lessThan, &order, 0, 1); swap(T, sliced_items, context, lessThan, &order, 2, 3); swap(T, sliced_items, context, lessThan, &order, 4, 5); swap(T, sliced_items, context, lessThan, &order, 6, 7); swap(T, sliced_items, context, lessThan, &order, 0, 2); swap(T, sliced_items, context, lessThan, &order, 1, 3); swap(T, sliced_items, context, lessThan, &order, 4, 6); swap(T, sliced_items, context, lessThan, &order, 5, 7); swap(T, sliced_items, context, lessThan, &order, 1, 2); swap(T, sliced_items, context, lessThan, &order, 5, 6); swap(T, sliced_items, context, lessThan, &order, 0, 4); swap(T, sliced_items, context, lessThan, &order, 3, 7); swap(T, sliced_items, context, lessThan, &order, 1, 5); swap(T, sliced_items, context, lessThan, &order, 2, 6); swap(T, sliced_items, context, lessThan, &order, 1, 4); swap(T, sliced_items, context, lessThan, &order, 3, 6); swap(T, sliced_items, context, lessThan, &order, 2, 4); swap(T, sliced_items, context, lessThan, &order, 3, 5); swap(T, sliced_items, context, lessThan, &order, 3, 4); }, 7 => { swap(T, sliced_items, context, lessThan, &order, 1, 2); swap(T, sliced_items, context, lessThan, &order, 3, 4); swap(T, sliced_items, context, lessThan, &order, 5, 6); swap(T, sliced_items, context, lessThan, &order, 0, 2); swap(T, sliced_items, context, lessThan, &order, 3, 5); swap(T, sliced_items, context, lessThan, &order, 4, 6); swap(T, sliced_items, context, lessThan, &order, 0, 1); swap(T, sliced_items, context, lessThan, &order, 4, 5); swap(T, sliced_items, context, lessThan, &order, 2, 6); swap(T, sliced_items, context, lessThan, &order, 0, 4); swap(T, sliced_items, context, lessThan, &order, 1, 5); swap(T, sliced_items, context, lessThan, &order, 0, 3); swap(T, sliced_items, context, lessThan, &order, 2, 5); swap(T, sliced_items, context, lessThan, &order, 1, 3); swap(T, sliced_items, context, lessThan, &order, 2, 4); swap(T, sliced_items, context, lessThan, &order, 2, 3); }, 6 => { swap(T, sliced_items, context, lessThan, &order, 1, 2); swap(T, sliced_items, context, lessThan, &order, 4, 5); swap(T, sliced_items, context, lessThan, &order, 0, 2); swap(T, sliced_items, context, lessThan, &order, 3, 5); swap(T, sliced_items, context, lessThan, &order, 0, 1); swap(T, sliced_items, context, lessThan, &order, 3, 4); swap(T, sliced_items, context, lessThan, &order, 2, 5); swap(T, sliced_items, context, lessThan, &order, 0, 3); swap(T, sliced_items, context, lessThan, &order, 1, 4); swap(T, sliced_items, context, lessThan, &order, 2, 4); swap(T, sliced_items, context, lessThan, &order, 1, 3); swap(T, sliced_items, context, lessThan, &order, 2, 3); }, 5 => { swap(T, sliced_items, context, lessThan, &order, 0, 1); swap(T, sliced_items, context, lessThan, &order, 3, 4); swap(T, sliced_items, context, lessThan, &order, 2, 4); swap(T, sliced_items, context, lessThan, &order, 2, 3); swap(T, sliced_items, context, lessThan, &order, 1, 4); swap(T, sliced_items, context, lessThan, &order, 0, 3); swap(T, sliced_items, context, lessThan, &order, 0, 2); swap(T, sliced_items, context, lessThan, &order, 1, 3); swap(T, sliced_items, context, lessThan, &order, 1, 2); }, 4 => { swap(T, sliced_items, context, lessThan, &order, 0, 1); swap(T, sliced_items, context, lessThan, &order, 2, 3); swap(T, sliced_items, context, lessThan, &order, 0, 2); swap(T, sliced_items, context, lessThan, &order, 1, 3); swap(T, sliced_items, context, lessThan, &order, 1, 2); }, else => {}, } } if (items.len < 8) return; // then merge sort the higher levels, which can be 8-15, 16-31, 32-63, 64-127, etc. while (true) { // if every A and B block will fit into the cache, use a special branch specifically for merging with the cache // (we use < rather than <= since the block size might be one more than iterator.length()) if (iterator.length() < cache.len) { // if four subarrays fit into the cache, it's faster to merge both pairs of subarrays into the cache, // then merge the two merged subarrays from the cache back into the original array if ((iterator.length() + 1) * 4 <= cache.len and iterator.length() * 4 <= items.len) { iterator.begin(); while (!iterator.finished()) { // merge A1 and B1 into the cache var A1 = iterator.nextRange(); var B1 = iterator.nextRange(); var A2 = iterator.nextRange(); var B2 = iterator.nextRange(); if (lessThan(context, items[B1.end - 1], items[A1.start])) { // the two ranges are in reverse order, so copy them in reverse order into the cache mem.copy(T, cache[B1.length()..], items[A1.start..A1.end]); mem.copy(T, cache[0..], items[B1.start..B1.end]); } else if (lessThan(context, items[B1.start], items[A1.end - 1])) { // these two ranges weren't already in order, so merge them into the cache mergeInto(T, items, A1, B1, context, lessThan, cache[0..]); } else { // if A1, B1, A2, and B2 are all in order, skip doing anything else if (!lessThan(context, items[B2.start], items[A2.end - 1]) and !lessThan(context, items[A2.start], items[B1.end - 1])) continue; // copy A1 and B1 into the cache in the same order mem.copy(T, cache[0..], items[A1.start..A1.end]); mem.copy(T, cache[A1.length()..], items[B1.start..B1.end]); } A1 = Range.init(A1.start, B1.end); // merge A2 and B2 into the cache if (lessThan(context, items[B2.end - 1], items[A2.start])) { // the two ranges are in reverse order, so copy them in reverse order into the cache mem.copy(T, cache[A1.length() + B2.length() ..], items[A2.start..A2.end]); mem.copy(T, cache[A1.length()..], items[B2.start..B2.end]); } else if (lessThan(context, items[B2.start], items[A2.end - 1])) { // these two ranges weren't already in order, so merge them into the cache mergeInto(T, items, A2, B2, context, lessThan, cache[A1.length()..]); } else { // copy A2 and B2 into the cache in the same order mem.copy(T, cache[A1.length()..], items[A2.start..A2.end]); mem.copy(T, cache[A1.length() + A2.length() ..], items[B2.start..B2.end]); } A2 = Range.init(A2.start, B2.end); // merge A1 and A2 from the cache into the items const A3 = Range.init(0, A1.length()); const B3 = Range.init(A1.length(), A1.length() + A2.length()); if (lessThan(context, cache[B3.end - 1], cache[A3.start])) { // the two ranges are in reverse order, so copy them in reverse order into the items mem.copy(T, items[A1.start + A2.length() ..], cache[A3.start..A3.end]); mem.copy(T, items[A1.start..], cache[B3.start..B3.end]); } else if (lessThan(context, cache[B3.start], cache[A3.end - 1])) { // these two ranges weren't already in order, so merge them back into the items mergeInto(T, cache[0..], A3, B3, context, lessThan, items[A1.start..]); } else { // copy A3 and B3 into the items in the same order mem.copy(T, items[A1.start..], cache[A3.start..A3.end]); mem.copy(T, items[A1.start + A1.length() ..], cache[B3.start..B3.end]); } } // we merged two levels at the same time, so we're done with this level already // (iterator.nextLevel() is called again at the bottom of this outer merge loop) _ = iterator.nextLevel(); } else { iterator.begin(); while (!iterator.finished()) { var A = iterator.nextRange(); var B = iterator.nextRange(); if (lessThan(context, items[B.end - 1], items[A.start])) { // the two ranges are in reverse order, so a simple rotation should fix it mem.rotate(T, items[A.start..B.end], A.length()); } else if (lessThan(context, items[B.start], items[A.end - 1])) { // these two ranges weren't already in order, so we'll need to merge them! mem.copy(T, cache[0..], items[A.start..A.end]); mergeExternal(T, items, A, B, context, lessThan, cache[0..]); } } } } else { // this is where the in-place merge logic starts! // 1. pull out two internal buffers each containing √A unique values // 1a. adjust block_size and buffer_size if we couldn't find enough unique values // 2. loop over the A and B subarrays within this level of the merge sort // 3. break A and B into blocks of size 'block_size' // 4. "tag" each of the A blocks with values from the first internal buffer // 5. roll the A blocks through the B blocks and drop/rotate them where they belong // 6. merge each A block with any B values that follow, using the cache or the second internal buffer // 7. sort the second internal buffer if it exists // 8. redistribute the two internal buffers back into the items var block_size: usize = math.sqrt(iterator.length()); var buffer_size = iterator.length() / block_size + 1; // as an optimization, we really only need to pull out the internal buffers once for each level of merges // after that we can reuse the same buffers over and over, then redistribute it when we're finished with this level var A: Range = undefined; var B: Range = undefined; var index: usize = 0; var last: usize = 0; var count: usize = 0; var find: usize = 0; var start: usize = 0; var pull_index: usize = 0; var pull = [_]Pull{ Pull{ .from = 0, .to = 0, .count = 0, .range = Range.init(0, 0), }, Pull{ .from = 0, .to = 0, .count = 0, .range = Range.init(0, 0), }, }; var buffer1 = Range.init(0, 0); var buffer2 = Range.init(0, 0); // find two internal buffers of size 'buffer_size' each find = buffer_size + buffer_size; var find_separately = false; if (block_size <= cache.len) { // if every A block fits into the cache then we won't need the second internal buffer, // so we really only need to find 'buffer_size' unique values find = buffer_size; } else if (find > iterator.length()) { // we can't fit both buffers into the same A or B subarray, so find two buffers separately find = buffer_size; find_separately = true; } // we need to find either a single contiguous space containing 2√A unique values (which will be split up into two buffers of size √A each), // or we need to find one buffer of < 2√A unique values, and a second buffer of √A unique values, // OR if we couldn't find that many unique values, we need the largest possible buffer we can get // in the case where it couldn't find a single buffer of at least √A unique values, // all of the Merge steps must be replaced by a different merge algorithm (MergeInPlace) iterator.begin(); while (!iterator.finished()) { A = iterator.nextRange(); B = iterator.nextRange(); // just store information about where the values will be pulled from and to, // as well as how many values there are, to create the two internal buffers // check A for the number of unique values we need to fill an internal buffer // these values will be pulled out to the start of A last = A.start; count = 1; while (count < find) : ({ last = index; count += 1; }) { index = findLastForward(T, items, items[last], Range.init(last + 1, A.end), context, lessThan, find - count); if (index == A.end) break; } index = last; if (count >= buffer_size) { // keep track of the range within the items where we'll need to "pull out" these values to create the internal buffer pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, .to = A.start, }; pull_index = 1; if (count == buffer_size + buffer_size) { // we were able to find a single contiguous section containing 2√A unique values, // so this section can be used to contain both of the internal buffers we'll need buffer1 = Range.init(A.start, A.start + buffer_size); buffer2 = Range.init(A.start + buffer_size, A.start + count); break; } else if (find == buffer_size + buffer_size) { // we found a buffer that contains at least √A unique values, but did not contain the full 2√A unique values, // so we still need to find a second separate buffer of at least √A unique values buffer1 = Range.init(A.start, A.start + count); find = buffer_size; } else if (block_size <= cache.len) { // we found the first and only internal buffer that we need, so we're done! buffer1 = Range.init(A.start, A.start + count); break; } else if (find_separately) { // found one buffer, but now find the other one buffer1 = Range.init(A.start, A.start + count); find_separately = false; } else { // we found a second buffer in an 'A' subarray containing √A unique values, so we're done! buffer2 = Range.init(A.start, A.start + count); break; } } else if (pull_index == 0 and count > buffer1.length()) { // keep track of the largest buffer we were able to find buffer1 = Range.init(A.start, A.start + count); pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, .to = A.start, }; } // check B for the number of unique values we need to fill an internal buffer // these values will be pulled out to the end of B last = B.end - 1; count = 1; while (count < find) : ({ last = index - 1; count += 1; }) { index = findFirstBackward(T, items, items[last], Range.init(B.start, last), context, lessThan, find - count); if (index == B.start) break; } index = last; if (count >= buffer_size) { // keep track of the range within the items where we'll need to "pull out" these values to create the internal buffe pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, .to = B.end, }; pull_index = 1; if (count == buffer_size + buffer_size) { // we were able to find a single contiguous section containing 2√A unique values, // so this section can be used to contain both of the internal buffers we'll need buffer1 = Range.init(B.end - count, B.end - buffer_size); buffer2 = Range.init(B.end - buffer_size, B.end); break; } else if (find == buffer_size + buffer_size) { // we found a buffer that contains at least √A unique values, but did not contain the full 2√A unique values, // so we still need to find a second separate buffer of at least √A unique values buffer1 = Range.init(B.end - count, B.end); find = buffer_size; } else if (block_size <= cache.len) { // we found the first and only internal buffer that we need, so we're done! buffer1 = Range.init(B.end - count, B.end); break; } else if (find_separately) { // found one buffer, but now find the other one buffer1 = Range.init(B.end - count, B.end); find_separately = false; } else { // buffer2 will be pulled out from a 'B' subarray, so if the first buffer was pulled out from the corresponding 'A' subarray, // we need to adjust the end point for that A subarray so it knows to stop redistributing its values before reaching buffer2 if (pull[0].range.start == A.start) pull[0].range.end -= pull[1].count; // we found a second buffer in an 'B' subarray containing √A unique values, so we're done! buffer2 = Range.init(B.end - count, B.end); break; } } else if (pull_index == 0 and count > buffer1.length()) { // keep track of the largest buffer we were able to find buffer1 = Range.init(B.end - count, B.end); pull[pull_index] = Pull{ .range = Range.init(A.start, B.end), .count = count, .from = index, .to = B.end, }; } } // pull out the two ranges so we can use them as internal buffers pull_index = 0; while (pull_index < 2) : (pull_index += 1) { const length = pull[pull_index].count; if (pull[pull_index].to < pull[pull_index].from) { // we're pulling the values out to the left, which means the start of an A subarray index = pull[pull_index].from; count = 1; while (count < length) : (count += 1) { index = findFirstBackward(T, items, items[index - 1], Range.init(pull[pull_index].to, pull[pull_index].from - (count - 1)), context, lessThan, length - count); const range = Range.init(index + 1, pull[pull_index].from + 1); mem.rotate(T, items[range.start..range.end], range.length() - count); pull[pull_index].from = index + count; } } else if (pull[pull_index].to > pull[pull_index].from) { // we're pulling values out to the right, which means the end of a B subarray index = pull[pull_index].from + 1; count = 1; while (count < length) : (count += 1) { index = findLastForward(T, items, items[index], Range.init(index, pull[pull_index].to), context, lessThan, length - count); const range = Range.init(pull[pull_index].from, index - 1); mem.rotate(T, items[range.start..range.end], count); pull[pull_index].from = index - 1 - count; } } } // adjust block_size and buffer_size based on the values we were able to pull out buffer_size = buffer1.length(); block_size = iterator.length() / buffer_size + 1; // the first buffer NEEDS to be large enough to tag each of the evenly sized A blocks, // so this was originally here to test the math for adjusting block_size above // assert((iterator.length() + 1)/block_size <= buffer_size); // now that the two internal buffers have been created, it's time to merge each A+B combination at this level of the merge sort! iterator.begin(); while (!iterator.finished()) { A = iterator.nextRange(); B = iterator.nextRange(); // remove any parts of A or B that are being used by the internal buffers start = A.start; if (start == pull[0].range.start) { if (pull[0].from > pull[0].to) { A.start += pull[0].count; // if the internal buffer takes up the entire A or B subarray, then there's nothing to merge // this only happens for very small subarrays, like √4 = 2, 2 * (2 internal buffers) = 4, // which also only happens when cache.len is small or 0 since it'd otherwise use MergeExternal if (A.length() == 0) continue; } else if (pull[0].from < pull[0].to) { B.end -= pull[0].count; if (B.length() == 0) continue; } } if (start == pull[1].range.start) { if (pull[1].from > pull[1].to) { A.start += pull[1].count; if (A.length() == 0) continue; } else if (pull[1].from < pull[1].to) { B.end -= pull[1].count; if (B.length() == 0) continue; } } if (lessThan(context, items[B.end - 1], items[A.start])) { // the two ranges are in reverse order, so a simple rotation should fix it mem.rotate(T, items[A.start..B.end], A.length()); } else if (lessThan(context, items[A.end], items[A.end - 1])) { // these two ranges weren't already in order, so we'll need to merge them! var findA: usize = undefined; // break the remainder of A into blocks. firstA is the uneven-sized first A block var blockA = Range.init(A.start, A.end); var firstA = Range.init(A.start, A.start + blockA.length() % block_size); // swap the first value of each A block with the value in buffer1 var indexA = buffer1.start; index = firstA.end; while (index < blockA.end) : ({ indexA += 1; index += block_size; }) { mem.swap(T, &items[indexA], &items[index]); } // start rolling the A blocks through the B blocks! // whenever we leave an A block behind, we'll need to merge the previous A block with any B blocks that follow it, so track that information as well var lastA = firstA; var lastB = Range.init(0, 0); var blockB = Range.init(B.start, B.start + math.min(block_size, B.length())); blockA.start += firstA.length(); indexA = buffer1.start; // if the first unevenly sized A block fits into the cache, copy it there for when we go to Merge it // otherwise, if the second buffer is available, block swap the contents into that if (lastA.length() <= cache.len) { mem.copy(T, cache[0..], items[lastA.start..lastA.end]); } else if (buffer2.length() > 0) { blockSwap(T, items, lastA.start, buffer2.start, lastA.length()); } if (blockA.length() > 0) { while (true) { // if there's a previous B block and the first value of the minimum A block is <= the last value of the previous B block, // then drop that minimum A block behind. or if there are no B blocks left then keep dropping the remaining A blocks. if ((lastB.length() > 0 and !lessThan(context, items[lastB.end - 1], items[indexA])) or blockB.length() == 0) { // figure out where to split the previous B block, and rotate it at the split const B_split = binaryFirst(T, items, items[indexA], lastB, context, lessThan); const B_remaining = lastB.end - B_split; // swap the minimum A block to the beginning of the rolling A blocks var minA = blockA.start; findA = minA + block_size; while (findA < blockA.end) : (findA += block_size) { if (lessThan(context, items[findA], items[minA])) { minA = findA; } } blockSwap(T, items, blockA.start, minA, block_size); // swap the first item of the previous A block back with its original value, which is stored in buffer1 mem.swap(T, &items[blockA.start], &items[indexA]); indexA += 1; // locally merge the previous A block with the B values that follow it // if lastA fits into the external cache we'll use that (with MergeExternal), // or if the second internal buffer exists we'll use that (with MergeInternal), // or failing that we'll use a strictly in-place merge algorithm (MergeInPlace) if (lastA.length() <= cache.len) { mergeExternal(T, items, lastA, Range.init(lastA.end, B_split), context, lessThan, cache[0..]); } else if (buffer2.length() > 0) { mergeInternal(T, items, lastA, Range.init(lastA.end, B_split), context, lessThan, buffer2); } else { mergeInPlace(T, items, lastA, Range.init(lastA.end, B_split), context, lessThan); } if (buffer2.length() > 0 or block_size <= cache.len) { // copy the previous A block into the cache or buffer2, since that's where we need it to be when we go to merge it anyway if (block_size <= cache.len) { mem.copy(T, cache[0..], items[blockA.start .. blockA.start + block_size]); } else { blockSwap(T, items, blockA.start, buffer2.start, block_size); } // this is equivalent to rotating, but faster // the area normally taken up by the A block is either the contents of buffer2, or data we don't need anymore since we memcopied it // either way, we don't need to retain the order of those items, so instead of rotating we can just block swap B to where it belongs blockSwap(T, items, B_split, blockA.start + block_size - B_remaining, B_remaining); } else { // we are unable to use the 'buffer2' trick to speed up the rotation operation since buffer2 doesn't exist, so perform a normal rotation mem.rotate(T, items[B_split .. blockA.start + block_size], blockA.start - B_split); } // update the range for the remaining A blocks, and the range remaining from the B block after it was split lastA = Range.init(blockA.start - B_remaining, blockA.start - B_remaining + block_size); lastB = Range.init(lastA.end, lastA.end + B_remaining); // if there are no more A blocks remaining, this step is finished! blockA.start += block_size; if (blockA.length() == 0) break; } else if (blockB.length() < block_size) { // move the last B block, which is unevenly sized, to before the remaining A blocks, by using a rotation // the cache is disabled here since it might contain the contents of the previous A block mem.rotate(T, items[blockA.start..blockB.end], blockB.start - blockA.start); lastB = Range.init(blockA.start, blockA.start + blockB.length()); blockA.start += blockB.length(); blockA.end += blockB.length(); blockB.end = blockB.start; } else { // roll the leftmost A block to the end by swapping it with the next B block blockSwap(T, items, blockA.start, blockB.start, block_size); lastB = Range.init(blockA.start, blockA.start + block_size); blockA.start += block_size; blockA.end += block_size; blockB.start += block_size; if (blockB.end > B.end - block_size) { blockB.end = B.end; } else { blockB.end += block_size; } } } } // merge the last A block with the remaining B values if (lastA.length() <= cache.len) { mergeExternal(T, items, lastA, Range.init(lastA.end, B.end), context, lessThan, cache[0..]); } else if (buffer2.length() > 0) { mergeInternal(T, items, lastA, Range.init(lastA.end, B.end), context, lessThan, buffer2); } else { mergeInPlace(T, items, lastA, Range.init(lastA.end, B.end), context, lessThan); } } } // when we're finished with this merge step we should have the one or two internal buffers left over, where the second buffer is all jumbled up // insertion sort the second buffer, then redistribute the buffers back into the items using the opposite process used for creating the buffer // while an unstable sort like quicksort could be applied here, in benchmarks it was consistently slightly slower than a simple insertion sort, // even for tens of millions of items. this may be because insertion sort is quite fast when the data is already somewhat sorted, like it is here insertionSort(T, items[buffer2.start..buffer2.end], context, lessThan); pull_index = 0; while (pull_index < 2) : (pull_index += 1) { var unique = pull[pull_index].count * 2; if (pull[pull_index].from > pull[pull_index].to) { // the values were pulled out to the left, so redistribute them back to the right var buffer = Range.init(pull[pull_index].range.start, pull[pull_index].range.start + pull[pull_index].count); while (buffer.length() > 0) { index = findFirstForward(T, items, items[buffer.start], Range.init(buffer.end, pull[pull_index].range.end), context, lessThan, unique); const amount = index - buffer.end; mem.rotate(T, items[buffer.start..index], buffer.length()); buffer.start += (amount + 1); buffer.end += amount; unique -= 2; } } else if (pull[pull_index].from < pull[pull_index].to) { // the values were pulled out to the right, so redistribute them back to the left var buffer = Range.init(pull[pull_index].range.end - pull[pull_index].count, pull[pull_index].range.end); while (buffer.length() > 0) { index = findLastBackward(T, items, items[buffer.end - 1], Range.init(pull[pull_index].range.start, buffer.start), context, lessThan, unique); const amount = buffer.start - index; mem.rotate(T, items[index..buffer.end], amount); buffer.start -= amount; buffer.end -= (amount + 1); unique -= 2; } } } } // double the size of each A and B subarray that will be merged in the next level if (!iterator.nextLevel()) break; } } // merge operation without a buffer fn mergeInPlace( comptime T: type, items: []T, A_arg: Range, B_arg: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, ) void { if (A_arg.length() == 0 or B_arg.length() == 0) return; // this just repeatedly binary searches into B and rotates A into position. // the paper suggests using the 'rotation-based Hwang and Lin algorithm' here, // but I decided to stick with this because it had better situational performance // // (Hwang and Lin is designed for merging subarrays of very different sizes, // but WikiSort almost always uses subarrays that are roughly the same size) // // normally this is incredibly suboptimal, but this function is only called // when none of the A or B blocks in any subarray contained 2√A unique values, // which places a hard limit on the number of times this will ACTUALLY need // to binary search and rotate. // // according to my analysis the worst case is √A rotations performed on √A items // once the constant factors are removed, which ends up being O(n) // // again, this is NOT a general-purpose solution – it only works well in this case! // kind of like how the O(n^2) insertion sort is used in some places var A = A_arg; var B = B_arg; while (true) { // find the first place in B where the first item in A needs to be inserted const mid = binaryFirst(T, items, items[A.start], B, context, lessThan); // rotate A into place const amount = mid - A.end; mem.rotate(T, items[A.start..mid], A.length()); if (B.end == mid) break; // calculate the new A and B ranges B.start = mid; A = Range.init(A.start + amount, B.start); A.start = binaryLast(T, items, items[A.start], A, context, lessThan); if (A.length() == 0) break; } } // merge operation using an internal buffer fn mergeInternal( comptime T: type, items: []T, A: Range, B: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, buffer: Range, ) void { // whenever we find a value to add to the final array, swap it with the value that's already in that spot // when this algorithm is finished, 'buffer' will contain its original contents, but in a different order var A_count: usize = 0; var B_count: usize = 0; var insert: usize = 0; if (B.length() > 0 and A.length() > 0) { while (true) { if (!lessThan(context, items[B.start + B_count], items[buffer.start + A_count])) { mem.swap(T, &items[A.start + insert], &items[buffer.start + A_count]); A_count += 1; insert += 1; if (A_count >= A.length()) break; } else { mem.swap(T, &items[A.start + insert], &items[B.start + B_count]); B_count += 1; insert += 1; if (B_count >= B.length()) break; } } } // swap the remainder of A into the final array blockSwap(T, items, buffer.start + A_count, A.start + insert, A.length() - A_count); } fn blockSwap(comptime T: type, items: []T, start1: usize, start2: usize, block_size: usize) void { var index: usize = 0; while (index < block_size) : (index += 1) { mem.swap(T, &items[start1 + index], &items[start2 + index]); } } // combine a linear search with a binary search to reduce the number of comparisons in situations // where have some idea as to how many unique values there are and where the next value might be fn findFirstForward( comptime T: type, items: []T, value: T, range: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, unique: usize, ) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, @as(usize, 1)); var index = range.start + skip; while (lessThan(context, items[index - 1], value)) : (index += skip) { if (index >= range.end - skip) { return binaryFirst(T, items, value, Range.init(index, range.end), context, lessThan); } } return binaryFirst(T, items, value, Range.init(index - skip, index), context, lessThan); } fn findFirstBackward( comptime T: type, items: []T, value: T, range: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, unique: usize, ) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, @as(usize, 1)); var index = range.end - skip; while (index > range.start and !lessThan(context, items[index - 1], value)) : (index -= skip) { if (index < range.start + skip) { return binaryFirst(T, items, value, Range.init(range.start, index), context, lessThan); } } return binaryFirst(T, items, value, Range.init(index, index + skip), context, lessThan); } fn findLastForward( comptime T: type, items: []T, value: T, range: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, unique: usize, ) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, @as(usize, 1)); var index = range.start + skip; while (!lessThan(context, value, items[index - 1])) : (index += skip) { if (index >= range.end - skip) { return binaryLast(T, items, value, Range.init(index, range.end), context, lessThan); } } return binaryLast(T, items, value, Range.init(index - skip, index), context, lessThan); } fn findLastBackward( comptime T: type, items: []T, value: T, range: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, unique: usize, ) usize { if (range.length() == 0) return range.start; const skip = math.max(range.length() / unique, @as(usize, 1)); var index = range.end - skip; while (index > range.start and lessThan(context, value, items[index - 1])) : (index -= skip) { if (index < range.start + skip) { return binaryLast(T, items, value, Range.init(range.start, index), context, lessThan); } } return binaryLast(T, items, value, Range.init(index, index + skip), context, lessThan); } fn binaryFirst( comptime T: type, items: []T, value: T, range: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, ) usize { var curr = range.start; var size = range.length(); if (range.start >= range.end) return range.end; while (size > 0) { const offset = size % 2; size /= 2; const mid = items[curr + size]; if (lessThan(context, mid, value)) { curr += size + offset; } } return curr; } fn binaryLast( comptime T: type, items: []T, value: T, range: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, ) usize { var curr = range.start; var size = range.length(); if (range.start >= range.end) return range.end; while (size > 0) { const offset = size % 2; size /= 2; const mid = items[curr + size]; if (!lessThan(context, value, mid)) { curr += size + offset; } } return curr; } fn mergeInto( comptime T: type, from: []T, A: Range, B: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, into: []T, ) void { var A_index: usize = A.start; var B_index: usize = B.start; const A_last = A.end; const B_last = B.end; var insert_index: usize = 0; while (true) { if (!lessThan(context, from[B_index], from[A_index])) { into[insert_index] = from[A_index]; A_index += 1; insert_index += 1; if (A_index == A_last) { // copy the remainder of B into the final array mem.copy(T, into[insert_index..], from[B_index..B_last]); break; } } else { into[insert_index] = from[B_index]; B_index += 1; insert_index += 1; if (B_index == B_last) { // copy the remainder of A into the final array mem.copy(T, into[insert_index..], from[A_index..A_last]); break; } } } } fn mergeExternal( comptime T: type, items: []T, A: Range, B: Range, context: anytype, comptime lessThan: fn (@TypeOf(context), T, T) bool, cache: []T, ) void { // A fits into the cache, so use that instead of the internal buffer var A_index: usize = 0; var B_index: usize = B.start; var insert_index: usize = A.start; const A_last = A.length(); const B_last = B.end; if (B.length() > 0 and A.length() > 0) { while (true) { if (!lessThan(context, items[B_index], cache[A_index])) { items[insert_index] = cache[A_index]; A_index += 1; insert_index += 1; if (A_index == A_last) break; } else { items[insert_index] = items[B_index]; B_index += 1; insert_index += 1; if (B_index == B_last) break; } } } // copy the remainder of A into the final array mem.copy(T, items[insert_index..], cache[A_index..A_last]); } fn swap( comptime T: type, items: []T, context: anytype, comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool, order: *[8]u8, x: usize, y: usize, ) void { if (lessThan(context, items[y], items[x]) or ((order.*)[x] > (order.*)[y] and !lessThan(context, items[x], items[y]))) { mem.swap(T, &items[x], &items[y]); mem.swap(u8, &(order.*)[x], &(order.*)[y]); } } /// Use to generate a comparator function for a given type. e.g. `sort(u8, slice, {}, comptime asc(u8))`. pub fn asc(comptime T: type) fn (void, T, T) bool { const impl = struct { fn inner(context: void, a: T, b: T) bool { _ = context; return a < b; } }; return impl.inner; } /// Use to generate a comparator function for a given type. e.g. `sort(u8, slice, {}, comptime desc(u8))`. pub fn desc(comptime T: type) fn (void, T, T) bool { const impl = struct { fn inner(context: void, a: T, b: T) bool { _ = context; return a > b; } }; return impl.inner; } test "stable sort" { try testStableSort(); comptime try testStableSort(); } fn testStableSort() !void { var expected = [_]IdAndValue{ IdAndValue{ .id = 0, .value = 0 }, IdAndValue{ .id = 1, .value = 0 }, IdAndValue{ .id = 2, .value = 0 }, IdAndValue{ .id = 0, .value = 1 }, IdAndValue{ .id = 1, .value = 1 }, IdAndValue{ .id = 2, .value = 1 }, IdAndValue{ .id = 0, .value = 2 }, IdAndValue{ .id = 1, .value = 2 }, IdAndValue{ .id = 2, .value = 2 }, }; var cases = [_][9]IdAndValue{ [_]IdAndValue{ IdAndValue{ .id = 0, .value = 0 }, IdAndValue{ .id = 0, .value = 1 }, IdAndValue{ .id = 0, .value = 2 }, IdAndValue{ .id = 1, .value = 0 }, IdAndValue{ .id = 1, .value = 1 }, IdAndValue{ .id = 1, .value = 2 }, IdAndValue{ .id = 2, .value = 0 }, IdAndValue{ .id = 2, .value = 1 }, IdAndValue{ .id = 2, .value = 2 }, }, [_]IdAndValue{ IdAndValue{ .id = 0, .value = 2 }, IdAndValue{ .id = 0, .value = 1 }, IdAndValue{ .id = 0, .value = 0 }, IdAndValue{ .id = 1, .value = 2 }, IdAndValue{ .id = 1, .value = 1 }, IdAndValue{ .id = 1, .value = 0 }, IdAndValue{ .id = 2, .value = 2 }, IdAndValue{ .id = 2, .value = 1 }, IdAndValue{ .id = 2, .value = 0 }, }, }; for (cases) |*case| { insertionSort(IdAndValue, (case.*)[0..], {}, cmpByValue); for (case.*) |item, i| { try testing.expect(item.id == expected[i].id); try testing.expect(item.value == expected[i].value); } } } const IdAndValue = struct { id: usize, value: i32, }; fn cmpByValue(context: void, a: IdAndValue, b: IdAndValue) bool { return asc_i32(context, a.value, b.value); } const asc_u8 = asc(u8); const asc_i32 = asc(i32); const desc_u8 = desc(u8); const desc_i32 = desc(i32); test "sort" { const u8cases = [_][]const []const u8{ &[_][]const u8{ "", "", }, &[_][]const u8{ "a", "a", }, &[_][]const u8{ "az", "az", }, &[_][]const u8{ "za", "az", }, &[_][]const u8{ "asdf", "adfs", }, &[_][]const u8{ "one", "eno", }, }; for (u8cases) |case| { var buf: [8]u8 = undefined; const slice = buf[0..case[0].len]; mem.copy(u8, slice, case[0]); sort(u8, slice, {}, asc_u8); try testing.expect(mem.eql(u8, slice, case[1])); } const i32cases = [_][]const []const i32{ &[_][]const i32{ &[_]i32{}, &[_]i32{}, }, &[_][]const i32{ &[_]i32{1}, &[_]i32{1}, }, &[_][]const i32{ &[_]i32{ 0, 1 }, &[_]i32{ 0, 1 }, }, &[_][]const i32{ &[_]i32{ 1, 0 }, &[_]i32{ 0, 1 }, }, &[_][]const i32{ &[_]i32{ 1, -1, 0 }, &[_]i32{ -1, 0, 1 }, }, &[_][]const i32{ &[_]i32{ 2, 1, 3 }, &[_]i32{ 1, 2, 3 }, }, }; for (i32cases) |case| { var buf: [8]i32 = undefined; const slice = buf[0..case[0].len]; mem.copy(i32, slice, case[0]); sort(i32, slice, {}, asc_i32); try testing.expect(mem.eql(i32, slice, case[1])); } } test "sort descending" { const rev_cases = [_][]const []const i32{ &[_][]const i32{ &[_]i32{}, &[_]i32{}, }, &[_][]const i32{ &[_]i32{1}, &[_]i32{1}, }, &[_][]const i32{ &[_]i32{ 0, 1 }, &[_]i32{ 1, 0 }, }, &[_][]const i32{ &[_]i32{ 1, 0 }, &[_]i32{ 1, 0 }, }, &[_][]const i32{ &[_]i32{ 1, -1, 0 }, &[_]i32{ 1, 0, -1 }, }, &[_][]const i32{ &[_]i32{ 2, 1, 3 }, &[_]i32{ 3, 2, 1 }, }, }; for (rev_cases) |case| { var buf: [8]i32 = undefined; const slice = buf[0..case[0].len]; mem.copy(i32, slice, case[0]); sort(i32, slice, {}, desc_i32); try testing.expect(mem.eql(i32, slice, case[1])); } } test "another sort case" { var arr = [_]i32{ 5, 3, 1, 2, 4 }; sort(i32, arr[0..], {}, asc_i32); try testing.expect(mem.eql(i32, &arr, &[_]i32{ 1, 2, 3, 4, 5 })); } test "sort fuzz testing" { var prng = std.rand.DefaultPrng.init(0x12345678); const random = prng.random(); const test_case_count = 10; var i: usize = 0; while (i < test_case_count) : (i += 1) { try fuzzTest(random); } } var fixed_buffer_mem: [100 * 1024]u8 = undefined; fn fuzzTest(rng: std.rand.Random) !void { const array_size = rng.intRangeLessThan(usize, 0, 1000); var array = try testing.allocator.alloc(IdAndValue, array_size); defer testing.allocator.free(array); // populate with random data for (array) |*item, index| { item.id = index; item.value = rng.intRangeLessThan(i32, 0, 100); } sort(IdAndValue, array, {}, cmpByValue); var index: usize = 1; while (index < array.len) : (index += 1) { if (array[index].value == array[index - 1].value) { try testing.expect(array[index].id > array[index - 1].id); } else { try testing.expect(array[index].value > array[index - 1].value); } } } pub fn argMin( comptime T: type, items: []const T, context: anytype, comptime lessThan: fn (@TypeOf(context), lhs: T, rhs: T) bool, ) ?usize { if (items.len == 0) { return null; } var smallest = items[0]; var smallest_index: usize = 0; for (items[1..]) |item, i| { if (lessThan(context, item, smallest)) { smallest = item; smallest_index = i + 1; } } return smallest_index; } test "argMin" { try testing.expectEqual(@as(?usize, null), argMin(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 3), argMin(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMin(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 3), argMin(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32)); } pub fn min( comptime T: type, items: []const T, context: anytype, comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool, ) ?T { const i = argMin(T, items, context, lessThan) orelse return null; return items[i]; } test "min" { try testing.expectEqual(@as(?i32, null), min(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 2), min(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), min(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, -10), min(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 7), min(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32)); } pub fn argMax( comptime T: type, items: []const T, context: anytype, comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool, ) ?usize { if (items.len == 0) { return null; } var biggest = items[0]; var biggest_index: usize = 0; for (items[1..]) |item, i| { if (lessThan(context, biggest, item)) { biggest = item; biggest_index = i + 1; } } return biggest_index; } test "argMax" { try testing.expectEqual(@as(?usize, null), argMax(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?usize, 4), argMax(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 0), argMax(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 2), argMax(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32)); try testing.expectEqual(@as(?usize, 1), argMax(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32)); } pub fn max( comptime T: type, items: []const T, context: anytype, comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool, ) ?T { const i = argMax(T, items, context, lessThan) orelse return null; return items[i]; } test "max" { try testing.expectEqual(@as(?i32, null), max(i32, &[_]i32{}, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{1}, {}, asc_i32)); try testing.expectEqual(@as(?i32, 5), max(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 9), max(i32, &[_]i32{ 9, 3, 8, 2, 5 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 1), max(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 10), max(i32, &[_]i32{ -10, 1, 10 }, {}, asc_i32)); try testing.expectEqual(@as(?i32, 3), max(i32, &[_]i32{ 6, 3, 5, 7, 6 }, {}, desc_i32)); } pub fn isSorted( comptime T: type, items: []const T, context: anytype, comptime lessThan: fn (context: @TypeOf(context), lhs: T, rhs: T) bool, ) bool { var i: usize = 1; while (i < items.len) : (i += 1) { if (lessThan(context, items[i], items[i - 1])) { return false; } } return true; } test "isSorted" { try testing.expect(isSorted(i32, &[_]i32{}, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{10}, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{ -10, 1, 1, 1, 10 }, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{}, {}, desc_i32)); try testing.expect(isSorted(i32, &[_]i32{-20}, {}, desc_i32)); try testing.expect(isSorted(i32, &[_]i32{ 3, 2, 1, 0, -1 }, {}, desc_i32)); try testing.expect(isSorted(i32, &[_]i32{ 10, -10 }, {}, desc_i32)); try testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, asc_i32)); try testing.expect(isSorted(i32, &[_]i32{ 1, 1, 1, 1, 1 }, {}, desc_i32)); try testing.expectEqual(false, isSorted(i32, &[_]i32{ 5, 4, 3, 2, 1 }, {}, asc_i32)); try testing.expectEqual(false, isSorted(i32, &[_]i32{ 1, 2, 3, 4, 5 }, {}, desc_i32)); try testing.expect(isSorted(u8, "abcd", {}, asc_u8)); try testing.expect(isSorted(u8, "zyxw", {}, desc_u8)); try testing.expectEqual(false, isSorted(u8, "abcd", {}, desc_u8)); try testing.expectEqual(false, isSorted(u8, "zyxw", {}, asc_u8)); try testing.expect(isSorted(u8, "ffff", {}, asc_u8)); try testing.expect(isSorted(u8, "ffff", {}, desc_u8)); }
https://raw.githubusercontent.com/natanalt/zig-x86_16/1b38fc3ef5e539047c76604ffe71b81e246f1a1e/lib/std/sort.zig
// BITCOUNT key [start end] pub const BITCOUNT = struct { //! ``` //! const cmd = BITCOUNT.init("test", BITCOUNT.Bounds{ .Slice = .{ .start = -2, .end = -1 } }); //! ``` key: []const u8, bounds: Bounds = .FullString, const Self = @This(); pub fn init(key: []const u8, bounds: Bounds) BITCOUNT { return .{ .key = key, .bounds = bounds }; } pub fn validate(self: Self) !void { if (self.key.len == 0) return error.EmptyKeyName; } pub const RedisCommand = struct { pub fn serialize(self: BITCOUNT, comptime rootSerializer: type, msg: anytype) !void { return rootSerializer.serializeCommand(msg, .{ "BITCOUNT", self.key, self.bounds }); } }; pub const Bounds = union(enum) { FullString, Slice: struct { start: isize, end: isize, }, pub const RedisArguments = struct { pub fn count(self: Bounds) usize { return switch (self) { .FullString => 0, .Slice => 2, }; } pub fn serialize(self: Bounds, comptime rootSerializer: type, msg: anytype) !void { switch (self) { .FullString => {}, .Slice => |slice| { try rootSerializer.serializeArgument(msg, isize, slice.start); try rootSerializer.serializeArgument(msg, isize, slice.end); }, } } }; }; }; test "example" { _ = BITCOUNT.init("test", BITCOUNT.Bounds{ .Slice = .{ .start = -2, .end = -1 } }); } test "serializer" { const std = @import("std"); const serializer = @import("../../serializer.zig").CommandSerializer; var correctBuf: [1000]u8 = undefined; var correctMsg = std.io.fixedBufferStream(correctBuf[0..]); var testBuf: [1000]u8 = undefined; var testMsg = std.io.fixedBufferStream(testBuf[0..]); { correctMsg.reset(); testMsg.reset(); try serializer.serializeCommand( testMsg.writer(), BITCOUNT.init("mykey", BITCOUNT.Bounds{ .Slice = .{ .start = 1, .end = 10 } }), ); try serializer.serializeCommand( correctMsg.writer(), .{ "BITCOUNT", "mykey", 1, 10 }, ); try std.testing.expectEqualSlices(u8, correctMsg.getWritten(), testMsg.getWritten()); } }
https://raw.githubusercontent.com/kristoff-it/zig-okredis/4566f358afd2c4f9096e086f22925220286d37b5/src/commands/strings/bitcount.zig
const std = @import("std"); /// The runtime’s logging scope. pub const log_runtime = std.log.scoped(.Runtime); /// The handler’s logging scope. pub const log_handler = std.log.scoped(.Handler); pub const Allocators = struct { gpa: std.mem.Allocator, arena: std.mem.Allocator, }; pub const Context = struct { const DEFAULT_REGION: []const u8 = "us-east-1"; const DEFAULT_MEMORY_MB: u16 = 128; const DEFAULT_INIT_TYPE = InitType.on_demand; pub const InitType = enum { on_demand, provisioned, snap_start, }; // // Function Meta // /// Environment variables; user-provided and [function meta](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html#configuration-envvars-runtime). env: *const std.process.EnvMap, /// URL host and port of the [Runtime API](https://docs.aws.amazon.com/lambda/latest/dg/runtimes-api.html)’s. api_origin: []const u8 = undefined, /// AWS Region where the Lambda function is executed. aws_region: []const u8 = DEFAULT_REGION, /// Access key obtained from the function's [execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html). aws_access_id: []const u8 = &[_]u8{}, /// Access key obtained from the function's [execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html). aws_access_secret: []const u8 = &[_]u8{}, /// Access key obtained from the function's [execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html). aws_session_token: []const u8 = &[_]u8{}, /// Name of the function. function_name: []const u8 = &[_]u8{}, /// Version of the function being executed. function_version: []const u8 = &[_]u8{}, /// Amount of memory available to the function in MB. function_size: u16 = DEFAULT_MEMORY_MB, /// Initialization type of the function. function_init_type: InitType = DEFAULT_INIT_TYPE, /// Handler location configured on the function. function_handler: []const u8 = &[_]u8{}, /// Name of the Amazon CloudWatch Logs group for the function. log_group: []const u8 = &[_]u8{}, /// Name of the Amazon CloudWatch Logs stream for the function. log_stream: []const u8 = &[_]u8{}, // // Invocation Meta // /// AWS request ID associated with the request. request_id: []const u8 = &[_]u8{}, /// X-Ray tracing id. xray_trace: []const u8 = &[_]u8{}, /// The function ARN requested. /// /// **This can be different in each invoke** that executes the same version. invoked_arn: []const u8 = &[_]u8{}, /// Function execution deadline counted in milliseconds since the _Unix epoch_. deadline_ms: u64 = 0, /// Information about the client application and device when invoked through the AWS Mobile SDK. client_context: []const u8 = &[_]u8{}, /// Information about the Amazon Cognito identity provider when invoked through the AWS Mobile SDK. cognito_identity: []const u8 = &[_]u8{}, // // Methods // pub fn init(allocator: std.mem.Allocator) !Context { var env = try loadEnv(allocator); errdefer env.deinit(); var self = Context{ .env = env }; var has_origin = false; if (env.get("AWS_LAMBDA_RUNTIME_API")) |v| { if (v.len > 0) { has_origin = true; self.api_origin = v; } } if (!has_origin) { return error.MissingRuntimeOrigin; } if (env.get("AWS_REGION")) |v| { self.aws_region = v; } else if (env.get("AWS_DEFAULT_REGION")) |v| { self.aws_region = v; } if (env.get("AWS_ACCESS_KEY_ID")) |v| { self.aws_access_id = v; } else if (env.get("AWS_ACCESS_KEY")) |v| { self.aws_access_id = v; } if (env.get("AWS_LAMBDA_FUNCTION_MEMORY_SIZE")) |v| { if (std.fmt.parseUnsigned(u16, v, 10)) |d| { self.function_size = d; } else |_| {} } if (env.get("AWS_LAMBDA_INITIALIZATION_TYPE")) |v| { if (std.mem.eql(u8, v, "on-demand")) { self.function_init_type = .on_demand; } else if (std.mem.eql(u8, v, "provisioned-concurrency")) { self.function_init_type = .provisioned; } else if (std.mem.eql(u8, v, "snap-start")) { self.function_init_type = .snap_start; } } if (env.get("AWS_SECRET_ACCESS_KEY")) |v| self.aws_access_secret = v; if (env.get("AWS_SESSION_TOKEN")) |v| self.aws_session_token = v; if (env.get("AWS_LAMBDA_FUNCTION_NAME")) |v| self.function_name = v; if (env.get("AWS_LAMBDA_FUNCTION_VERSION")) |v| self.function_version = v; if (env.get("_HANDLER")) |v| self.function_handler = v; if (env.get("AWS_LAMBDA_LOG_GROUP_NAME")) |v| self.log_group = v; if (env.get("AWS_LAMBDA_LOG_STREAM_NAME")) |v| self.log_stream = v; if (env.get("_X_AMZN_TRACE_ID")) |v| self.xray_trace = v; return self; } pub fn deinit(self: *Context, allocator: std.mem.Allocator) void { @constCast(self.env).hash_map.deinit(); allocator.destroy(self.env); } fn loadEnv(allocator: std.mem.Allocator) !*std.process.EnvMap { const env = try allocator.create(std.process.EnvMap); env.* = std.process.EnvMap.init(allocator); if (@import("builtin").link_libc) { var ptr = std.c.environ; while (ptr[0]) |line| : (ptr += 1) try parseAndPutVar(env, line); } else { for (std.os.environ) |line| try parseAndPutVar(env, line); } return env; } // Based on std.process.getEnvMap fn parseAndPutVar(map: *std.process.EnvMap, line: [*]u8) !void { var line_i: usize = 0; while (line[line_i] != 0 and line[line_i] != '=') : (line_i += 1) {} const key = line[0..line_i]; var end_i: usize = line_i; while (line[end_i] != 0) : (end_i += 1) {} const value = line[line_i + 1 .. end_i]; try map.putMove(key, value); } };
https://raw.githubusercontent.com/by-nir/aws-lambda-zig/9ca01fa5398e150de3479f9c9709d6d798b8d3b0/src/lambda.zig
const std = @import("std"); const warn = std.debug.warn; pub const io_mode = .evented; const argParser = struct { const Self = @This(); p: []i32 = undefined, i: usize = undefined, flags: [3]u1 = undefined, fn get(s: Self, n: usize) i32 { if (s.i + n >= s.p.len) return -0xaa; var a = s.p[s.i + n]; return if (s.flags[n - 1] == 1) a else if (a >= s.p.len) -0xaa else s.p[@intCast(usize, a)]; } fn imm(s: Self, n: usize) usize { return @intCast(usize, s.p[s.i + n]); } fn init(p: []i32, i: usize) Self { var s = Self{ .p = p, .i = i }; for (s.flags) |_, fi| { const exp = std.math.powi(usize, 10, fi + 2) catch unreachable; s.flags[fi] = @intCast(u1, (@intCast(usize, p[i]) / exp) % 10); } return s; } }; const IntChan = std.event.Channel(i32); const machine = struct { const Self = @This(); p: []i32 = undefined, i: usize = 0, in: *IntChan, out: *IntChan, done: *std.event.Channel(bool), id: usize, fn run(self: *Self) void { while (self.i < self.p.len) { var op = @mod(self.p[self.i], 100); var args = argParser.init(self.p, self.i); switch (op) { // stores 1 => self.p[args.imm(3)] = args.get(1) + args.get(2), 2 => self.p[args.imm(3)] = args.get(1) * args.get(2), 7 => self.p[args.imm(3)] = if (args.get(1) < args.get(2)) 1 else 0, 8 => self.p[args.imm(3)] = if (args.get(1) == args.get(2)) 1 else 0, // conditional jumps 5 => self.i = if (args.get(1) != 0) @intCast(usize, args.get(2)) else self.i + 3, 6 => self.i = if (args.get(1) == 0) @intCast(usize, args.get(2)) else self.i + 3, // I/O 3 => self.p[args.imm(1)] = self.in.get(), 4 => self.out.put(args.get(1)), // halt 99 => { self.done.put(true); return; }, else => @panic("error.InvalidOpCode"), } self.i += switch (op) { 1, 2, 7, 8 => @intCast(usize, 4), 5, 6 => 0, // already jumped 3, 4 => 2, 99 => 1, else => @panic("error.InvalidOpCode"), }; } unreachable; } }; fn unique(xs: var, map: var) !bool { map.clear(); for (xs) |x| _ = try map.put(x, {}); return xs.len == map.count(); } fn perms5(lo: i32, hi: i32, perm_ch: *std.event.Channel(?[5]i32)) void { const al = std.heap.page_allocator; var map = std.AutoHashMap(i32, void).init(al); defer map.deinit(); var a: i32 = lo; while (a <= hi) : (a += 1) { var b: i32 = lo; while (b <= hi) : (b += 1) { var c: i32 = lo; while (c <= hi) : (c += 1) { var d: i32 = lo; while (d <= hi) : (d += 1) { var e: i32 = lo; while (e <= hi) : (e += 1) { const candidate = [_]i32{ a, b, c, d, e }; const u = unique(candidate, &map) catch @panic("no memory"); if (u) perm_ch.put(candidate); } } } } } perm_ch.put(null); } pub fn main() !void { const allr = std.heap.page_allocator; const stdin = std.io.getStdIn(); const stream = &stdin.inStream().stream; var buf: [20]u8 = undefined; var prog: [2024]i32 = undefined; var numi: usize = 0; while (try stream.readUntilDelimiterOrEof(&buf, ',')) |num| : (numi += 1) { prog[numi] = try std.fmt.parseInt(i32, num, 10); } var perm_ch: std.event.Channel(?[5]i32) = undefined; perm_ch.init(&[_]?[5]i32{}); _ = async perms5(0, 4, &perm_ch); // part 1 var max: i32 = -1; var machines: [5]machine = undefined; var frames: [5]@Frame(machine.run) = undefined; var chans: [6]IntChan = undefined; var done: std.event.Channel(bool) = undefined; while (perm_ch.get()) |perm| { for (chans) |*chan| chan.init(&[_]i32{}); done.init(&[_]bool{}); for (machines) |*m, i| { m.* = machine{ .p = try std.mem.dupe(allr, i32, prog[0..numi]), .in = &chans[i], .out = &chans[i + 1], .done = &done, .id = i, }; frames[i] = async machines[i].run(); } for (perm) |p, i| chans[i].put(p); chans[0].put(0); for (machines[0..4]) |_, i| _ = done.get(); const out = chans[5].get(); _ = done.get(); max = std.math.max(max, out); } warn("{}\n", .{max}); // part 2 perm_ch.init(&[_]?[5]i32{}); _ = async perms5(5, 9, &perm_ch); max = -1; while (perm_ch.get()) |perm| { for (chans) |*chan| chan.init(&[_]i32{}); done.init(&[_]bool{}); for (machines) |*m, i| { m.* = machine{ .p = try std.mem.dupe(allr, i32, prog[0..numi]), .in = &chans[(4 + i) % 5], .out = &chans[i], .done = &done, .id = i, }; frames[i] = async machines[i].run(); } for (machines) |_, i| chans[(4 + i) % 5].put(perm[i]); chans[4].put(0); for (machines[0..4]) |_, i| _ = done.get(); const out = chans[4].get(); _ = done.get(); max = std.math.max(max, out); } warn("{}\n", .{max}); }
https://raw.githubusercontent.com/travisstaloch/advocode2019/55ed89e9114d151178428f0eb1162483c820901e/7.zig
const std = @import("std"); const path = std.fs.path; const assert = std.debug.assert; const target_util = @import("target.zig"); const Compilation = @import("Compilation.zig"); const build_options = @import("build_options"); const trace = @import("tracy.zig").trace; const libcxxabi_files = [_][]const u8{ "src/abort_message.cpp", "src/cxa_aux_runtime.cpp", "src/cxa_default_handlers.cpp", "src/cxa_demangle.cpp", "src/cxa_exception.cpp", "src/cxa_exception_storage.cpp", "src/cxa_guard.cpp", "src/cxa_handlers.cpp", "src/cxa_noexception.cpp", "src/cxa_personality.cpp", "src/cxa_thread_atexit.cpp", "src/cxa_vector.cpp", "src/cxa_virtual.cpp", "src/fallback_malloc.cpp", "src/private_typeinfo.cpp", "src/stdlib_exception.cpp", "src/stdlib_new_delete.cpp", "src/stdlib_stdexcept.cpp", "src/stdlib_typeinfo.cpp", }; const libcxx_files = [_][]const u8{ "src/algorithm.cpp", "src/any.cpp", "src/atomic.cpp", "src/barrier.cpp", "src/bind.cpp", "src/charconv.cpp", "src/chrono.cpp", "src/condition_variable.cpp", "src/condition_variable_destructor.cpp", "src/debug.cpp", "src/exception.cpp", "src/experimental/memory_resource.cpp", "src/filesystem/directory_iterator.cpp", "src/filesystem/int128_builtins.cpp", "src/filesystem/operations.cpp", "src/functional.cpp", "src/future.cpp", "src/hash.cpp", "src/ios.cpp", "src/ios.instantiations.cpp", "src/iostream.cpp", "src/locale.cpp", "src/memory.cpp", "src/mutex.cpp", "src/mutex_destructor.cpp", "src/new.cpp", "src/optional.cpp", "src/random.cpp", "src/random_shuffle.cpp", "src/regex.cpp", "src/shared_mutex.cpp", "src/stdexcept.cpp", "src/string.cpp", "src/strstream.cpp", "src/support/solaris/xlocale.cpp", "src/support/win32/locale_win32.cpp", "src/support/win32/support.cpp", "src/support/win32/thread_win32.cpp", "src/system_error.cpp", "src/thread.cpp", "src/typeinfo.cpp", "src/utility.cpp", "src/valarray.cpp", "src/variant.cpp", "src/vector.cpp", }; pub fn buildLibCXX(comp: *Compilation) !void { if (!build_options.have_llvm) { return error.ZigCompilerNotBuiltWithLLVMExtensions; } const tracy = trace(@src()); defer tracy.end(); var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa); defer arena_allocator.deinit(); const arena = &arena_allocator.allocator; const root_name = "c++"; const output_mode = .Lib; const link_mode = .Static; const target = comp.getTarget(); const basename = try std.zig.binNameAlloc(arena, .{ .root_name = root_name, .target = target, .output_mode = output_mode, .link_mode = link_mode, }); const emit_bin = Compilation.EmitLoc{ .directory = null, // Put it in the cache directory. .basename = basename, }; const cxxabi_include_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxxabi", "include" }); const cxx_include_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxx", "include" }); var c_source_files = std.ArrayList(Compilation.CSourceFile).init(arena); try c_source_files.ensureCapacity(libcxx_files.len); for (libcxx_files) |cxx_src| { var cflags = std.ArrayList([]const u8).init(arena); if (target.os.tag == .windows or target.os.tag == .wasi) { // Filesystem stuff isn't supported on WASI and Windows. if (std.mem.startsWith(u8, cxx_src, "src/filesystem/")) continue; } if (target.os.tag != .windows) { if (std.mem.startsWith(u8, cxx_src, "src/support/win32/")) continue; } try cflags.append("-DNDEBUG"); try cflags.append("-D_LIBCPP_BUILDING_LIBRARY"); try cflags.append("-D_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER"); try cflags.append("-DLIBCXX_BUILDING_LIBCXXABI"); try cflags.append("-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS"); try cflags.append("-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS"); try cflags.append("-D_LIBCPP_HAS_NO_VENDOR_AVAILABILITY_ANNOTATIONS"); try cflags.append("-fvisibility=hidden"); try cflags.append("-fvisibility-inlines-hidden"); if (target.abi.isMusl()) { try cflags.append("-D_LIBCPP_HAS_MUSL_LIBC"); } if (target.os.tag == .wasi) { // WASI doesn't support thread and exception yet. try cflags.append("-D_LIBCPP_HAS_NO_THREADS"); try cflags.append("-fno-exceptions"); } try cflags.append("-I"); try cflags.append(cxx_include_path); try cflags.append("-I"); try cflags.append(cxxabi_include_path); if (target_util.supports_fpic(target)) { try cflags.append("-fPIC"); } try cflags.append("-nostdinc++"); try cflags.append("-std=c++14"); try cflags.append("-Wno-user-defined-literals"); c_source_files.appendAssumeCapacity(.{ .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxx", cxx_src }), .extra_flags = cflags.items, }); } const sub_compilation = try Compilation.create(comp.gpa, .{ .local_cache_directory = comp.global_cache_directory, .global_cache_directory = comp.global_cache_directory, .zig_lib_directory = comp.zig_lib_directory, .target = target, .root_name = root_name, .root_pkg = null, .output_mode = output_mode, .thread_pool = comp.thread_pool, .libc_installation = comp.bin_file.options.libc_installation, .emit_bin = emit_bin, .optimize_mode = comp.compilerRtOptMode(), .link_mode = link_mode, .want_sanitize_c = false, .want_stack_check = false, .want_red_zone = comp.bin_file.options.red_zone, .want_valgrind = false, .want_tsan = comp.bin_file.options.tsan, .want_pic = comp.bin_file.options.pic, .want_pie = comp.bin_file.options.pie, .want_lto = comp.bin_file.options.lto, .function_sections = comp.bin_file.options.function_sections, .emit_h = null, .strip = comp.compilerRtStrip(), .is_native_os = comp.bin_file.options.is_native_os, .is_native_abi = comp.bin_file.options.is_native_abi, .self_exe_path = comp.self_exe_path, .c_source_files = c_source_files.items, .verbose_cc = comp.verbose_cc, .verbose_link = comp.bin_file.options.verbose_link, .verbose_air = comp.verbose_air, .verbose_llvm_ir = comp.verbose_llvm_ir, .verbose_cimport = comp.verbose_cimport, .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features, .clang_passthrough_mode = comp.clang_passthrough_mode, .link_libc = true, .skip_linker_dependencies = true, }); defer sub_compilation.destroy(); try sub_compilation.updateSubCompilation(); assert(comp.libcxx_static_lib == null); comp.libcxx_static_lib = Compilation.CRTFile{ .full_object_path = try sub_compilation.bin_file.options.emit.?.directory.join( comp.gpa, &[_][]const u8{basename}, ), .lock = sub_compilation.bin_file.toOwnedLock(), }; } pub fn buildLibCXXABI(comp: *Compilation) !void { if (!build_options.have_llvm) { return error.ZigCompilerNotBuiltWithLLVMExtensions; } const tracy = trace(@src()); defer tracy.end(); var arena_allocator = std.heap.ArenaAllocator.init(comp.gpa); defer arena_allocator.deinit(); const arena = &arena_allocator.allocator; const root_name = "c++abi"; const output_mode = .Lib; const link_mode = .Static; const target = comp.getTarget(); const basename = try std.zig.binNameAlloc(arena, .{ .root_name = root_name, .target = target, .output_mode = output_mode, .link_mode = link_mode, }); const emit_bin = Compilation.EmitLoc{ .directory = null, // Put it in the cache directory. .basename = basename, }; const cxxabi_include_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxxabi", "include" }); const cxx_include_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxx", "include" }); var c_source_files = std.ArrayList(Compilation.CSourceFile).init(arena); try c_source_files.ensureCapacity(libcxxabi_files.len); for (libcxxabi_files) |cxxabi_src| { var cflags = std.ArrayList([]const u8).init(arena); if (target.os.tag == .wasi) { // WASI doesn't support thread and exception yet. if (std.mem.startsWith(u8, cxxabi_src, "src/cxa_thread_atexit.cpp") or std.mem.startsWith(u8, cxxabi_src, "src/cxa_exception.cpp") or std.mem.startsWith(u8, cxxabi_src, "src/cxa_personality.cpp")) continue; try cflags.append("-D_LIBCXXABI_HAS_NO_THREADS"); try cflags.append("-fno-exceptions"); } else { try cflags.append("-DHAVE___CXA_THREAD_ATEXIT_IMPL"); } try cflags.append("-D_LIBCPP_DISABLE_EXTERN_TEMPLATE"); try cflags.append("-D_LIBCPP_ENABLE_CXX17_REMOVED_UNEXPECTED_FUNCTIONS"); try cflags.append("-D_LIBCXXABI_BUILDING_LIBRARY"); try cflags.append("-D_LIBCXXABI_DISABLE_VISIBILITY_ANNOTATIONS"); try cflags.append("-D_LIBCPP_DISABLE_VISIBILITY_ANNOTATIONS"); try cflags.append("-fvisibility=hidden"); try cflags.append("-fvisibility-inlines-hidden"); if (target.abi.isMusl()) { try cflags.append("-D_LIBCPP_HAS_MUSL_LIBC"); } try cflags.append("-I"); try cflags.append(cxxabi_include_path); try cflags.append("-I"); try cflags.append(cxx_include_path); if (target_util.supports_fpic(target)) { try cflags.append("-fPIC"); } try cflags.append("-nostdinc++"); try cflags.append("-fstrict-aliasing"); try cflags.append("-funwind-tables"); try cflags.append("-std=c++11"); c_source_files.appendAssumeCapacity(.{ .src_path = try comp.zig_lib_directory.join(arena, &[_][]const u8{ "libcxxabi", cxxabi_src }), .extra_flags = cflags.items, }); } const sub_compilation = try Compilation.create(comp.gpa, .{ .local_cache_directory = comp.global_cache_directory, .global_cache_directory = comp.global_cache_directory, .zig_lib_directory = comp.zig_lib_directory, .target = target, .root_name = root_name, .root_pkg = null, .output_mode = output_mode, .thread_pool = comp.thread_pool, .libc_installation = comp.bin_file.options.libc_installation, .emit_bin = emit_bin, .optimize_mode = comp.compilerRtOptMode(), .link_mode = link_mode, .want_sanitize_c = false, .want_stack_check = false, .want_red_zone = comp.bin_file.options.red_zone, .want_valgrind = false, .want_tsan = comp.bin_file.options.tsan, .want_pic = comp.bin_file.options.pic, .want_pie = comp.bin_file.options.pie, .want_lto = comp.bin_file.options.lto, .function_sections = comp.bin_file.options.function_sections, .emit_h = null, .strip = comp.compilerRtStrip(), .is_native_os = comp.bin_file.options.is_native_os, .is_native_abi = comp.bin_file.options.is_native_abi, .self_exe_path = comp.self_exe_path, .c_source_files = c_source_files.items, .verbose_cc = comp.verbose_cc, .verbose_link = comp.bin_file.options.verbose_link, .verbose_air = comp.verbose_air, .verbose_llvm_ir = comp.verbose_llvm_ir, .verbose_cimport = comp.verbose_cimport, .verbose_llvm_cpu_features = comp.verbose_llvm_cpu_features, .clang_passthrough_mode = comp.clang_passthrough_mode, .link_libc = true, .skip_linker_dependencies = true, }); defer sub_compilation.destroy(); try sub_compilation.updateSubCompilation(); assert(comp.libcxxabi_static_lib == null); comp.libcxxabi_static_lib = Compilation.CRTFile{ .full_object_path = try sub_compilation.bin_file.options.emit.?.directory.join( comp.gpa, &[_][]const u8{basename}, ), .lock = sub_compilation.bin_file.toOwnedLock(), }; }
https://raw.githubusercontent.com/collinalexbell/all-the-compilers/7f834984f71054806bfec8604e02e86b99c0f831/zig/src/libcxx.zig
const std = @import("std"); const windows = @import("windows.zig"); const IUnknown = windows.IUnknown; const BYTE = windows.BYTE; const HRESULT = windows.HRESULT; const WINAPI = windows.WINAPI; const UINT32 = windows.UINT32; const BOOL = windows.BOOL; const FALSE = windows.FALSE; const L = std.unicode.utf8ToUtf16LeStringLiteral; pub const VOLUMEMETER_LEVELS = packed struct { pPeakLevels: ?[*]f32, pRMSLevels: ?[*]f32, ChannelCount: UINT32, }; pub const REVERB_MIN_FRAMERATE: UINT32 = 20000; pub const REVERB_MAX_FRAMERATE: UINT32 = 48000; pub const REVERB_PARAMETERS = packed struct { WetDryMix: f32, ReflectionsDelay: UINT32, ReverbDelay: BYTE, RearDelay: BYTE, SideDelay: BYTE, PositionLeft: BYTE, PositionRight: BYTE, PositionMatrixLeft: BYTE, PositionMatrixRight: BYTE, EarlyDiffusion: BYTE, LateDiffusion: BYTE, LowEQGain: BYTE, LowEQCutoff: BYTE, HighEQGain: BYTE, HighEQCutoff: BYTE, RoomFilterFreq: f32, RoomFilterMain: f32, RoomFilterHF: f32, ReflectionsGain: f32, ReverbGain: f32, DecayTime: f32, Density: f32, RoomSize: f32, DisableLateField: BOOL, pub fn initDefault() REVERB_PARAMETERS { return .{ .WetDryMix = REVERB_DEFAULT_WET_DRY_MIX, .ReflectionsDelay = REVERB_DEFAULT_REFLECTIONS_DELAY, .ReverbDelay = REVERB_DEFAULT_REVERB_DELAY, .RearDelay = REVERB_DEFAULT_REAR_DELAY, .SideDelay = REVERB_DEFAULT_REAR_DELAY, .PositionLeft = REVERB_DEFAULT_POSITION, .PositionRight = REVERB_DEFAULT_POSITION, .PositionMatrixLeft = REVERB_DEFAULT_POSITION_MATRIX, .PositionMatrixRight = REVERB_DEFAULT_POSITION_MATRIX, .EarlyDiffusion = REVERB_DEFAULT_EARLY_DIFFUSION, .LateDiffusion = REVERB_DEFAULT_LATE_DIFFUSION, .LowEQGain = REVERB_DEFAULT_LOW_EQ_GAIN, .LowEQCutoff = REVERB_DEFAULT_LOW_EQ_CUTOFF, .HighEQGain = REVERB_DEFAULT_HIGH_EQ_CUTOFF, .HighEQCutoff = REVERB_DEFAULT_HIGH_EQ_GAIN, .RoomFilterFreq = REVERB_DEFAULT_ROOM_FILTER_FREQ, .RoomFilterMain = REVERB_DEFAULT_ROOM_FILTER_MAIN, .RoomFilterHF = REVERB_DEFAULT_ROOM_FILTER_HF, .ReflectionsGain = REVERB_DEFAULT_REFLECTIONS_GAIN, .ReverbGain = REVERB_DEFAULT_REVERB_GAIN, .DecayTime = REVERB_DEFAULT_DECAY_TIME, .Density = REVERB_DEFAULT_DENSITY, .RoomSize = REVERB_DEFAULT_ROOM_SIZE, .DisableLateField = REVERB_DEFAULT_DISABLE_LATE_FIELD, }; } }; pub const REVERB_MIN_WET_DRY_MIX: f32 = 0.0; pub const REVERB_MIN_REFLECTIONS_DELAY: UINT32 = 0; pub const REVERB_MIN_REVERB_DELAY: BYTE = 0; pub const REVERB_MIN_REAR_DELAY: BYTE = 0; pub const REVERB_MIN_7POINT1_SIDE_DELAY: BYTE = 0; pub const REVERB_MIN_7POINT1_REAR_DELAY: BYTE = 0; pub const REVERB_MIN_POSITION: BYTE = 0; pub const REVERB_MIN_DIFFUSION: BYTE = 0; pub const REVERB_MIN_LOW_EQ_GAIN: BYTE = 0; pub const REVERB_MIN_LOW_EQ_CUTOFF: BYTE = 0; pub const REVERB_MIN_HIGH_EQ_GAIN: BYTE = 0; pub const REVERB_MIN_HIGH_EQ_CUTOFF: BYTE = 0; pub const REVERB_MIN_ROOM_FILTER_FREQ: f32 = 20.0; pub const REVERB_MIN_ROOM_FILTER_MAIN: f32 = -100.0; pub const REVERB_MIN_ROOM_FILTER_HF: f32 = -100.0; pub const REVERB_MIN_REFLECTIONS_GAIN: f32 = -100.0; pub const REVERB_MIN_REVERB_GAIN: f32 = -100.0; pub const REVERB_MIN_DECAY_TIME: f32 = 0.1; pub const REVERB_MIN_DENSITY: f32 = 0.0; pub const REVERB_MIN_ROOM_SIZE: f32 = 0.0; pub const REVERB_MAX_WET_DRY_MIX: f32 = 100.0; pub const REVERB_MAX_REFLECTIONS_DELAY: UINT32 = 300; pub const REVERB_MAX_REVERB_DELAY: BYTE = 85; pub const REVERB_MAX_REAR_DELAY: BYTE = 5; pub const REVERB_MAX_7POINT1_SIDE_DELAY: BYTE = 5; pub const REVERB_MAX_7POINT1_REAR_DELAY: BYTE = 20; pub const REVERB_MAX_POSITION: BYTE = 30; pub const REVERB_MAX_DIFFUSION: BYTE = 15; pub const REVERB_MAX_LOW_EQ_GAIN: BYTE = 12; pub const REVERB_MAX_LOW_EQ_CUTOFF: BYTE = 9; pub const REVERB_MAX_HIGH_EQ_GAIN: BYTE = 8; pub const REVERB_MAX_HIGH_EQ_CUTOFF: BYTE = 14; pub const REVERB_MAX_ROOM_FILTER_FREQ: f32 = 20000.0; pub const REVERB_MAX_ROOM_FILTER_MAIN: f32 = 0.0; pub const REVERB_MAX_ROOM_FILTER_HF: f32 = 0.0; pub const REVERB_MAX_REFLECTIONS_GAIN: f32 = 20.0; pub const REVERB_MAX_REVERB_GAIN: f32 = 20.0; pub const REVERB_MAX_DENSITY: f32 = 100.0; pub const REVERB_MAX_ROOM_SIZE: f32 = 100.0; pub const REVERB_DEFAULT_WET_DRY_MIX: f32 = 100.0; pub const REVERB_DEFAULT_REFLECTIONS_DELAY: UINT32 = 5; pub const REVERB_DEFAULT_REVERB_DELAY: BYTE = 5; pub const REVERB_DEFAULT_REAR_DELAY: BYTE = 5; pub const REVERB_DEFAULT_7POINT1_SIDE_DELAY: BYTE = 5; pub const REVERB_DEFAULT_7POINT1_REAR_DELAY: BYTE = 20; pub const REVERB_DEFAULT_POSITION: BYTE = 6; pub const REVERB_DEFAULT_POSITION_MATRIX: BYTE = 27; pub const REVERB_DEFAULT_EARLY_DIFFUSION: BYTE = 8; pub const REVERB_DEFAULT_LATE_DIFFUSION: BYTE = 8; pub const REVERB_DEFAULT_LOW_EQ_GAIN: BYTE = 8; pub const REVERB_DEFAULT_LOW_EQ_CUTOFF: BYTE = 4; pub const REVERB_DEFAULT_HIGH_EQ_GAIN: BYTE = 8; pub const REVERB_DEFAULT_HIGH_EQ_CUTOFF: BYTE = 4; pub const REVERB_DEFAULT_ROOM_FILTER_FREQ: f32 = 5000.0; pub const REVERB_DEFAULT_ROOM_FILTER_MAIN: f32 = 0.0; pub const REVERB_DEFAULT_ROOM_FILTER_HF: f32 = 0.0; pub const REVERB_DEFAULT_REFLECTIONS_GAIN: f32 = 0.0; pub const REVERB_DEFAULT_REVERB_GAIN: f32 = 0.0; pub const REVERB_DEFAULT_DECAY_TIME: f32 = 1.0; pub const REVERB_DEFAULT_DENSITY: f32 = 100.0; pub const REVERB_DEFAULT_ROOM_SIZE: f32 = 100.0; pub const REVERB_DEFAULT_DISABLE_LATE_FIELD: BOOL = FALSE; pub fn createVolumeMeter(apo: *?*IUnknown, _: UINT32) HRESULT { var xaudio2_dll = windows.kernel32.GetModuleHandleW(L("xaudio2_9redist.dll")); if (xaudio2_dll == null) { xaudio2_dll = (std.DynLib.openZ("d3d12/xaudio2_9redist.dll") catch unreachable).dll; } var CreateAudioVolumeMeter: fn (*?*IUnknown) callconv(WINAPI) HRESULT = undefined; CreateAudioVolumeMeter = @ptrCast( @TypeOf(CreateAudioVolumeMeter), windows.kernel32.GetProcAddress(xaudio2_dll.?, "CreateAudioVolumeMeter").?, ); return CreateAudioVolumeMeter(apo); } pub fn createReverb(apo: *?*IUnknown, _: UINT32) HRESULT { var xaudio2_dll = windows.kernel32.GetModuleHandleW(L("xaudio2_9redist.dll")); if (xaudio2_dll == null) { xaudio2_dll = (std.DynLib.openZ("d3d12/xaudio2_9redist.dll") catch unreachable).dll; } var CreateAudioReverb: fn (*?*IUnknown) callconv(WINAPI) HRESULT = undefined; CreateAudioReverb = @ptrCast( @TypeOf(CreateAudioReverb), windows.kernel32.GetProcAddress(xaudio2_dll.?, "CreateAudioReverb").?, ); return CreateAudioReverb(apo); }
https://raw.githubusercontent.com/alpqr/zw/e987d667917cfe26438c0b72bb781529f9722be5/libs/zwin32/src/xaudio2fx.zig
const std = @import("std"); const gl = @import("zopengl"); const Shader = @import("Shader.zig"); const Texture = @import("Texture.zig"); pub const PostProcessor = @This(); const Self = PostProcessor; pub fn init(shader: Shader, width: u32, height: u32) !Self { var self = Self{ .post_processing_shader = shader, .width = width, .height = height, }; gl.genFramebuffers(1, &self.msfbo); gl.genFramebuffers(1, &self.fbo); gl.genRenderbuffers(1, &self.rbo); gl.bindFramebuffer(gl.FRAMEBUFFER, self.msfbo); gl.bindRenderbuffer(gl.RENDERBUFFER, self.rbo); gl.renderbufferStorageMultisample(gl.RENDERBUFFER, 4, gl.RGB, @intCast(width), @intCast(height)); gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, self.rbo); if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) { std.log.err("ERROR::POSTPROCESSOR: Failed to initialize MSFBO", .{}); return error.FramebufferIncompleteMS; } gl.bindFramebuffer(gl.FRAMEBUFFER, self.fbo); self.texture = Texture.generate(gl.RGB, @intCast(width), @intCast(height), gl.RGB, gl.REPEAT, gl.REPEAT, gl.LINEAR, gl.LINEAR, null); gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, self.texture.id, 0); if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) != gl.FRAMEBUFFER_COMPLETE) { std.log.err("ERROR::POSTPROCESSOR: Failed to initialize MSFBO", .{}); return error.FramebufferIncomplete; } gl.bindFramebuffer(gl.FRAMEBUFFER, 0); self.initRenderData(); self.post_processing_shader.setInteger("scene", 0, true); const offset: f32 = 1.0 / 300.0; const offsets = [18]f32{ -offset, offset, 0.0, offset, offset, offset, -offset, 0.0, 0.0, 0.0, offset, 0.0, -offset, -offset, 0.0, -offset, offset, -offset, }; gl.uniform2fv(gl.getUniformLocation(self.post_processing_shader.id.?, "offsets"), 9, @ptrCast(&offsets)); const edge_kernel = [9]i32{ -1, -1, -1, -1, 8, -1, -1, -1, -1, }; gl.uniform1iv(gl.getUniformLocation(self.post_processing_shader.id.?, "edge_kernel"), 9, @ptrCast(&edge_kernel)); const blur_kernel = [9]f32{ 1.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0, 2.0 / 16.0, 2.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0, 2.0 / 16.0, 1.0 / 16.0, }; gl.uniform1fv(gl.getUniformLocation(self.post_processing_shader.id.?, "blur_kernel"), 9, @ptrCast(&blur_kernel)); return self; } post_processing_shader: Shader, texture: Texture = undefined, width: u32, height: u32, confuse: bool = false, chaos: bool = false, shake: bool = false, msfbo: u32 = undefined, fbo: u32 = undefined, rbo: u32 = undefined, vao: u32 = undefined, pub fn deinit(self: *Self) void { gl.deleteRenderbuffers(1, &self.rbo); gl.deleteFramebuffers(1, &self.msfbo); gl.deleteFramebuffers(1, &self.fbo); gl.deleteVertexArrayBuffers(1, &self.vao); } pub fn beginRender(self: *Self) void { gl.bindFramebuffer(gl.FRAMEBUFFER, self.msfbo); gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.clear(gl.COLOR_BUFFER_BIT); } pub fn render(self: *Self, time: f32) void { // set the uniforms/options self.post_processing_shader.use(); self.post_processing_shader.setFloat("time", time, false); self.post_processing_shader.setInteger("confuse", @intFromBool(self.confuse), false); self.post_processing_shader.setInteger("chaos", @intFromBool(self.chaos), false); self.post_processing_shader.setInteger("shake", @intFromBool(self.shake), false); gl.activeTexture(gl.TEXTURE0); self.texture.bind(); gl.bindVertexArray(self.vao); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.bindVertexArray(0); } pub fn endRender(self: *Self) void { gl.bindFramebuffer(gl.READ_FRAMEBUFFER, self.msfbo); gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, self.fbo); gl.blitFramebuffer(0, 0, @intCast(self.width), @intCast(self.height), 0, 0, @intCast(self.width), @intCast(self.height), gl.COLOR_BUFFER_BIT, gl.NEAREST); gl.bindFramebuffer(gl.FRAMEBUFFER, 0); } fn initRenderData(self: *Self) void { var vbo: u32 = undefined; const vertices = [_]f32{ // pos // tex -1.0, -1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, -1.0, 1.0, 0.0, 1.0, -1.0, -1.0, 0.0, 0.0, 1.0, -1.0, 1.0, 0.0, 1.0, 1.0, 1.0, 1.0, }; gl.genVertexArrays(1, &self.vao); gl.genBuffers(1, &vbo); gl.bindBuffer(gl.ARRAY_BUFFER, vbo); gl.bufferData(gl.ARRAY_BUFFER, vertices.len * @sizeOf(f32), &vertices, gl.STATIC_DRAW); gl.bindVertexArray(self.vao); gl.enableVertexAttribArray(0); gl.vertexAttribPointer(0, 4, gl.FLOAT, gl.FALSE, 4 * @sizeOf(f32), null); gl.bindBuffer(gl.ARRAY_BUFFER, 0); gl.bindVertexArray(0); }
https://raw.githubusercontent.com/loic-o/potential-guacamole/13479663faa5cf663d85440f4237b19ce59ba68f/src/PostProcessor.zig
pub const Symbol_Target = union (enum) { not_found, instruction: Instruction_Ref, expression: Expression.Handle, // always in the same file where it's being referenced stack: Stack_Ref, // If this is an instruction target, it must be in the same file as `s` pub fn instruction_handle(self: Symbol_Target, s: Source_File.Slices) Instruction.Handle { return switch (self) { .expression => |expr_handle| s.file.find_instruction_by_expr(expr_handle), .stack => |stack_ref| stack_ref.instruction, .instruction => |insn_ref| i: { std.debug.assert(insn_ref.file == s.file.handle); break :i insn_ref.instruction; }, .not_found => unreachable, }; } }; pub const Stack_Ref = struct { additional_sp_offset: u32, instruction: Instruction.Handle, stack_block_name: []const u8, }; pub const Instruction_Ref = struct { file: Source_File.Handle, instruction: Instruction.Handle, }; pub fn parse_symbol(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) *const Constant { switch (s.expr.items(.info)[expr_handle]) { .literal_symbol_def, .literal_symbol_ref => { const file = s.file; const token_handle = s.expr.items(.token)[expr_handle]; const literal = file.tokens.get(token_handle).location(file.source); const constant = Constant.init_symbol_literal(a.gpa, &a.constant_temp, literal); return constant.intern(a.arena, a.gpa, &a.constants); }, .directive_symbol_def, .directive_symbol_ref => |inner_expr| { const expr_resolved_constants = s.expr.items(.resolved_constant); if (expr_resolved_constants[inner_expr]) |interned_symbol_name| { return interned_symbol_name; } else if (typechecking.try_resolve_expr_type(a, s, inner_expr)) { return expr_resolved_constants[inner_expr].?; } else unreachable; }, else => unreachable, } } pub fn lookup_symbol(a: *Assembler, s: Source_File.Slices, symbol_token_handle: lex.Token.Handle, symbol: []const u8, comptime check_ambiguity: bool) Symbol_Target { const file = s.file; const operations = s.insn.items(.operation); const resolved_constants = s.expr.items(.resolved_constant); const insn_containing_symbol_expression = file.find_instruction_by_token(symbol_token_handle); const block_handle = file.find_block_by_token(symbol_token_handle); // Look for lexically scoped symbols (.def expressions and stack labels) var def_symbol_definition: ?Expression.Handle = null; var maybe_stack_ref: ?Stack_Ref = null; var block_iter = s.block_instructions(block_handle); var dupe_strategy: Stack_Label_Dupe_Strategy = if (check_ambiguity) .report_both else .skip_check; while (block_iter.next()) |insn_handle| { if (insn_handle >= insn_containing_symbol_expression) break; const op = operations[insn_handle]; switch (op) { .def => { const params_expr = s.insn.items(.params)[insn_handle].?; const symbol_and_definition = s.expr.items(.info)[params_expr].list; const def_symbol_expr = symbol_and_definition.left; const def_symbol = resolved_constants[def_symbol_expr].?; if (std.mem.eql(u8, symbol, def_symbol.as_string())) { def_symbol_definition = symbol_and_definition.right; } }, .undef => if (def_symbol_definition) |_| { if (s.insn.items(.params)[insn_handle]) |params_expr| { if (undef_list_contains_symbol(a, s, params_expr, symbol)) { def_symbol_definition = null; } } }, .push, .pop => { const expr_infos = s.expr.items(.info); var maybe_expr_handle = s.insn.items(.params)[insn_handle]; while (maybe_expr_handle) |expr_handle| switch (expr_infos[expr_handle]) { .list => |bin| { maybe_stack_ref = process_push_or_pop(a, s, op, maybe_stack_ref, bin.left, symbol_token_handle, symbol, &dupe_strategy); maybe_expr_handle = bin.right; }, else => { maybe_stack_ref = process_push_or_pop(a, s, op, maybe_stack_ref, expr_handle, symbol_token_handle, symbol, &dupe_strategy); maybe_expr_handle = null; } }; }, else => {}, } } const maybe_private_label = if (std.mem.startsWith(u8, symbol, "_")) s.block.items(.labels)[block_handle].get(symbol) else null; const maybe_local = s.file.locals.get(symbol); const maybe_public = a.public_labels.get(symbol); if (check_ambiguity) { var num_matches: u32 = 0; if (def_symbol_definition != null) num_matches += 1; if (maybe_private_label != null) num_matches += 1; if (maybe_stack_ref != null) num_matches += 1; if (maybe_local != null) num_matches += 1; if (maybe_public) |insn_ref| { if (insn_ref.file != s.file.handle) { num_matches += 1; } } if (num_matches > 1) { const insn_line_numbers = s.insn.items(.line_number); if (def_symbol_definition) |expr_handle| { const insn_handle = s.file.find_instruction_by_expr(expr_handle); const line_number = insn_line_numbers[insn_handle]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be .def symbol from line {}", .{ line_number }, .{}); } if (maybe_private_label) |insn_handle| { const line_number = insn_line_numbers[insn_handle]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be private label from line {}", .{ line_number }, .{}); } if (maybe_stack_ref) |stack_ref| { if (dupe_strategy == .report_both) { const line_number = insn_line_numbers[stack_ref.instruction]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be stack label from line {}", .{ line_number }, .{}); } } if (maybe_local) |target| switch (target) { .not_found, .stack => unreachable, .instruction => |insn_ref| { const line_number = insn_line_numbers[insn_ref.instruction]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be file-local label from line {}", .{ line_number }, .{}); }, .expression => |expr_handle| { const insn_handle = s.file.find_instruction_by_expr(expr_handle); const line_number = insn_line_numbers[insn_handle]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be .local symbol from line {}", .{ line_number }, .{}); }, }; if (maybe_public) |insn_ref| { if (insn_ref.file != s.file.handle) { const target_file = a.get_source(insn_ref.file); const line_number = target_file.instructions.items(.line_number)[insn_ref.instruction]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be public label from line {} in {s}", .{ line_number, target_file.name }, .{}); } } } } return if (def_symbol_definition) |expr_handle| .{ .expression = expr_handle } else if (maybe_private_label) |insn_handle| .{ .instruction = .{ .file = s.file.handle, .instruction = insn_handle, }} else if (maybe_stack_ref) |stack_ref| .{ .stack = stack_ref } else if (maybe_local) |local| local else if (maybe_public) |insn_ref| .{ .instruction = insn_ref } else .not_found ; } pub fn compute_push_or_pop_size(a: *Assembler, s: Source_File.Slices, maybe_stack_name_list: ?Expression.Handle) u32 { const expr_infos = s.expr.items(.info); var result: u32 = 0; var maybe_expr_handle = maybe_stack_name_list; while (maybe_expr_handle) |expr_handle| switch (expr_infos[expr_handle]) { .list => |bin| { result += compute_stack_size(a, s, bin.left); maybe_expr_handle = bin.right; }, else => { result += compute_stack_size(a, s, expr_handle); maybe_expr_handle = null; } }; return result; } fn compute_stack_size(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) u32 { const constant = parse_symbol(a, s, expr_handle); if (s.file.stacks.get(constant.as_string())) |stack_block_handle| { const block_insns = s.block_instructions(stack_block_handle); if (block_insns.begin != block_insns.end) { const insn_handle = block_insns.end - 1; const address = s.insn.items(.address)[insn_handle]; const length = s.insn.items(.length)[insn_handle]; return std.mem.alignForward(u32, address + length, 2); } } return 0; } const Stack_Label_Dupe_Strategy = enum { skip_check, report_both, report_dupe_only, }; fn process_push_or_pop(a: *Assembler, s: Source_File.Slices, op: Instruction.Operation_Type, maybe_stack_ref: ?Stack_Ref, expr_handle: Expression.Handle, symbol_token_handle: lex.Token.Handle, symbol: []const u8, dupe_strategy: *Stack_Label_Dupe_Strategy) ?Stack_Ref { if (maybe_stack_ref) |stack_ref| { var offset = stack_ref.additional_sp_offset; const stack_size = compute_stack_size(a, s, expr_handle); if (op == .pop) { const stack_block_name = parse_symbol(a, s, expr_handle).as_string(); if (std.mem.eql(u8, stack_ref.stack_block_name, stack_block_name)) { // this was the push that contains our symbol return null; } if (offset >= stack_size) { offset -= stack_size; } else { offset = 0; } } else { if (dupe_strategy.* != .skip_check) { const stack_block_name = parse_symbol(a, s, expr_handle).as_string(); if (s.file.stacks.get(stack_block_name)) |stack_block_handle| { const stack_labels = s.block.items(.labels)[stack_block_handle]; if (stack_labels.get(symbol)) |insn_handle| { const insn_line_numbers = s.insn.items(.line_number); if (dupe_strategy.* == .report_both) { const line_number = insn_line_numbers[stack_ref.instruction]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be stack label from line {}", .{ line_number }, .{}); dupe_strategy.* = .report_dupe_only; } const line_number = insn_line_numbers[insn_handle]; a.record_token_error_fmt(s.file.handle, symbol_token_handle, "Ambiguous symbol; could be stack label from line {}", .{ line_number }, .{}); } } } offset += stack_size; } return .{ .additional_sp_offset = offset, .instruction = stack_ref.instruction, .stack_block_name = stack_ref.stack_block_name, }; } if (op == .push) { const stack_block_name = parse_symbol(a, s, expr_handle).as_string(); if (s.file.stacks.get(stack_block_name)) |stack_block_handle| { const stack_labels = s.block.items(.labels)[stack_block_handle]; if (stack_labels.get(symbol)) |insn_handle| { return .{ .additional_sp_offset = 0, .instruction = insn_handle, .stack_block_name = stack_block_name, }; } } } return maybe_stack_ref; } fn undef_list_contains_symbol(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle, symbol: []const u8) bool { switch (s.expr.items(.info)[expr_handle]) { .list => |bin| { return undef_list_contains_symbol(a, s, bin.left, symbol) or undef_list_contains_symbol(a, s, bin.right, symbol); }, .literal_symbol_def => { const token_handle = s.expr.items(.token)[expr_handle]; const raw_symbol = s.file.tokens.get(token_handle).location(s.file.source); const undef_symbol = Constant.init_symbol_literal(a.gpa, &a.constant_temp, raw_symbol); return std.mem.eql(u8, symbol, undef_symbol.as_string()); }, .directive_symbol_def => |literal_expr| { const undef_symbol = s.expr.items(.resolved_constant)[literal_expr].?; return std.mem.eql(u8, symbol, undef_symbol.as_string()); }, else => unreachable, } } const lex = @import("lex.zig"); const typechecking = @import("typechecking.zig"); const Assembler = @import("Assembler.zig"); const Source_File = @import("Source_File.zig"); const Instruction = @import("Instruction.zig"); const Expression = @import("Expression.zig"); const Constant = @import("Constant.zig"); const std = @import("std");
https://raw.githubusercontent.com/bcrist/vera/3fa048b730dedfc3551ecf352792a8322466867a/lib/assembler/symbols.zig
const cpu = @import("mk20dx256.zig"); pub fn enable() void { asm volatile ("CPSIE i" : : : "memory" ); } pub fn disable() void { asm volatile ("CPSID i" : : : "memory" ); } pub fn trigger_pendsv() void { cpu.SystemControl.ICSR = 0x10000000; } extern fn xPortPendSVHandler() callconv(.C) void; extern fn xPortSysTickHandler() callconv(.C) void; extern fn vPortSVCHandler() callconv(.C) void; extern fn USBOTG_IRQHandler() callconv(.C) void; pub export fn isr_panic() void { while (true) {} } pub export fn isr_ignore() void {} pub const isr_non_maskable: fn () callconv(.C) void = isr_panic; pub const isr_hard_fault: fn () callconv(.C) void = isr_panic; pub const isr_memmanage_fault: fn () callconv(.C) void = isr_panic; pub const isr_bus_fault: fn () callconv(.C) void = isr_panic; pub const isr_usage_fault: fn () callconv(.C) void = isr_panic; pub const isr_svcall: fn () callconv(.C) void = vPortSVCHandler; pub const isr_debug_monitor: fn () callconv(.C) void = isr_ignore; pub const isr_pendablesrvreq: fn () callconv(.C) void = xPortPendSVHandler; pub const isr_systick: fn () callconv(.C) void = xPortSysTickHandler; pub const isr_dma_ch0_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch1_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch2_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch3_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch4_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch5_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch6_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch7_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch8_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch9_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch10_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch11_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch12_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch13_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch14_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_ch15_complete: fn () callconv(.C) void = isr_ignore; pub const isr_dma_error: fn () callconv(.C) void = isr_ignore; pub const isr_flash_cmd_complete: fn () callconv(.C) void = isr_ignore; pub const isr_flash_read_collision: fn () callconv(.C) void = isr_ignore; pub const isr_low_voltage_warning: fn () callconv(.C) void = isr_ignore; pub const isr_low_voltage_wakeup: fn () callconv(.C) void = isr_ignore; pub const isr_wdog_or_emw: fn () callconv(.C) void = isr_ignore; pub const isr_i2c0: fn () callconv(.C) void = isr_ignore; pub const isr_i2c1: fn () callconv(.C) void = isr_ignore; pub const isr_spi0: fn () callconv(.C) void = isr_ignore; pub const isr_spi1: fn () callconv(.C) void = isr_ignore; pub const isr_can0_or_msg_buf: fn () callconv(.C) void = isr_ignore; pub const isr_can0_bus_off: fn () callconv(.C) void = isr_ignore; pub const isr_can0_error: fn () callconv(.C) void = isr_ignore; pub const isr_can0_transmit_warn: fn () callconv(.C) void = isr_ignore; pub const isr_can0_receive_warn: fn () callconv(.C) void = isr_ignore; pub const isr_can0_wakeup: fn () callconv(.C) void = isr_ignore; pub const isr_i2s0_transmit: fn () callconv(.C) void = isr_ignore; pub const isr_i2s0_receive: fn () callconv(.C) void = isr_ignore; pub const isr_uart0_lon: fn () callconv(.C) void = isr_ignore; pub const isr_uart0_status: fn () callconv(.C) void = isr_ignore; pub const isr_uart0_error: fn () callconv(.C) void = isr_ignore; pub const isr_uart1_status: fn () callconv(.C) void = isr_ignore; pub const isr_uart1_error: fn () callconv(.C) void = isr_ignore; pub const isr_uart2_status: fn () callconv(.C) void = isr_ignore; pub const isr_uart2_error: fn () callconv(.C) void = isr_ignore; pub const isr_adc0: fn () callconv(.C) void = isr_ignore; pub const isr_adc1: fn () callconv(.C) void = isr_ignore; pub const isr_cmp0: fn () callconv(.C) void = isr_ignore; pub const isr_cmp1: fn () callconv(.C) void = isr_ignore; pub const isr_cmp2: fn () callconv(.C) void = isr_ignore; pub const isr_ftm0: fn () callconv(.C) void = isr_ignore; pub const isr_ftm1: fn () callconv(.C) void = isr_ignore; pub const isr_ftm2: fn () callconv(.C) void = isr_ignore; pub const isr_cmt: fn () callconv(.C) void = isr_ignore; pub const isr_rtc_alarm: fn () callconv(.C) void = isr_ignore; pub const isr_rtc_seconds: fn () callconv(.C) void = isr_ignore; pub const isr_pit_ch0: fn () callconv(.C) void = isr_ignore; pub const isr_pit_ch1: fn () callconv(.C) void = isr_ignore; pub const isr_pit_ch2: fn () callconv(.C) void = isr_ignore; pub const isr_pit_ch3: fn () callconv(.C) void = isr_ignore; pub const isr_pdb: fn () callconv(.C) void = isr_ignore; pub const isr_usb_otg: fn () callconv(.C) void = USBOTG_IRQHandler; pub const isr_usb_charger: fn () callconv(.C) void = isr_ignore; pub const isr_dac0: fn () callconv(.C) void = isr_ignore; pub const isr_tsi: fn () callconv(.C) void = isr_ignore; pub const isr_mcg: fn () callconv(.C) void = isr_ignore; pub const isr_lpt: fn () callconv(.C) void = isr_ignore; pub const isr_port_a: fn () callconv(.C) void = isr_ignore; pub const isr_port_b: fn () callconv(.C) void = isr_ignore; pub const isr_port_c: fn () callconv(.C) void = isr_ignore; pub const isr_port_d: fn () callconv(.C) void = isr_ignore; pub const isr_port_e: fn () callconv(.C) void = isr_ignore; pub const isr_software: fn () callconv(.C) void = isr_ignore;
https://raw.githubusercontent.com/vlabo/zrt/c5b367b90d62b6eeec9a261b9bf55aa946b53928/src/teensy3_2/interrupt.zig
const std = @import("std"); pub fn build(b: *std.Build) void { // standard target and optimize options const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // build sandbox const sandbox = b.addExecutable(.{ .name = "sandbox", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); b.installArtifact(sandbox); // run sandbox const run_cmd = b.addRunArtifact(sandbox); run_cmd.step.dependOn(b.getInstallStep()); // take cmdline arguments if (b.args) |args| { run_cmd.addArgs(args); } // create the run step const run_step = b.step("run", "Run the sandbox"); run_step.dependOn(&run_cmd.step); // run unit tests const unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); }
https://raw.githubusercontent.com/procub3r/riscv_emu/e4010fe001d2a7007f893522ec6798312cb25141/build.zig
//! Futex is a mechanism used to block (`wait`) and unblock (`wake`) threads using a 32bit memory address as hints. //! Blocking a thread is acknowledged only if the 32bit memory address is equal to a given value. //! This check helps avoid block/unblock deadlocks which occur if a `wake()` happens before a `wait()`. //! Using Futex, other Thread synchronization primitives can be built which efficiently wait for cross-thread events or signals. const std = @import("../std.zig"); const builtin = @import("builtin"); const Futex = @This(); const os = std.os; const assert = std.debug.assert; const testing = std.testing; const Atomic = std.atomic.Atomic; /// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either: /// - The value at `ptr` is no longer equal to `expect`. /// - The caller is unblocked by a matching `wake()`. /// - The caller is unblocked spuriously ("at random"). /// /// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically /// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`. pub fn wait(ptr: *const Atomic(u32), expect: u32) void { @setCold(true); Impl.wait(ptr, expect, null) catch |err| switch (err) { error.Timeout => unreachable, // null timeout meant to wait forever }; } /// Checks if `ptr` still contains the value `expect` and, if so, blocks the caller until either: /// - The value at `ptr` is no longer equal to `expect`. /// - The caller is unblocked by a matching `wake()`. /// - The caller is unblocked spuriously ("at random"). /// - The caller blocks for longer than the given timeout. In which case, `error.Timeout` is returned. /// /// The checking of `ptr` and `expect`, along with blocking the caller, is done atomically /// and totally ordered (sequentially consistent) with respect to other wait()/wake() calls on the same `ptr`. pub fn timedWait(ptr: *const Atomic(u32), expect: u32, timeout_ns: u64) error{Timeout}!void { @setCold(true); // Avoid calling into the OS for no-op timeouts. if (timeout_ns == 0) { if (ptr.load(.SeqCst) != expect) return; return error.Timeout; } return Impl.wait(ptr, expect, timeout_ns); } /// Unblocks at most `max_waiters` callers blocked in a `wait()` call on `ptr`. pub fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { @setCold(true); // Avoid calling into the OS if there's nothing to wake up. if (max_waiters == 0) { return; } Impl.wake(ptr, max_waiters); } const Impl = if (builtin.single_threaded) SingleThreadedImpl else if (builtin.os.tag == .windows) WindowsImpl else if (builtin.os.tag.isDarwin()) DarwinImpl else if (builtin.os.tag == .linux) LinuxImpl else if (builtin.os.tag == .freebsd) FreebsdImpl else if (builtin.os.tag == .openbsd) OpenbsdImpl else if (builtin.os.tag == .dragonfly) DragonflyImpl else if (builtin.target.isWasm()) WasmImpl else if (std.Thread.use_pthreads) PosixImpl else UnsupportedImpl; /// We can't do @compileError() in the `Impl` switch statement above as its eagerly evaluated. /// So instead, we @compileError() on the methods themselves for platforms which don't support futex. const UnsupportedImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { return unsupported(.{ ptr, expect, timeout }); } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { return unsupported(.{ ptr, max_waiters }); } fn unsupported(unused: anytype) noreturn { _ = unused; @compileError("Unsupported operating system " ++ @tagName(builtin.target.os.tag)); } }; const SingleThreadedImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { if (ptr.loadUnchecked() != expect) { return; } // There are no threads to wake us up. // So if we wait without a timeout we would never wake up. const delay = timeout orelse { unreachable; // deadlock detected }; std.time.sleep(delay); return error.Timeout; } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { // There are no other threads to possibly wake up _ = ptr; _ = max_waiters; } }; // We use WaitOnAddress through NtDll instead of API-MS-Win-Core-Synch-l1-2-0.dll // as it's generally already a linked target and is autoloaded into all processes anyway. const WindowsImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { var timeout_value: os.windows.LARGE_INTEGER = undefined; var timeout_ptr: ?*const os.windows.LARGE_INTEGER = null; // NTDLL functions work with time in units of 100 nanoseconds. // Positive values are absolute deadlines while negative values are relative durations. if (timeout) |delay| { timeout_value = @as(os.windows.LARGE_INTEGER, @intCast(delay / 100)); timeout_value = -timeout_value; timeout_ptr = &timeout_value; } const rc = os.windows.ntdll.RtlWaitOnAddress( @as(?*const anyopaque, @ptrCast(ptr)), @as(?*const anyopaque, @ptrCast(&expect)), @sizeOf(@TypeOf(expect)), timeout_ptr, ); switch (rc) { .SUCCESS => {}, .TIMEOUT => { assert(timeout != null); return error.Timeout; }, else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { const address = @as(?*const anyopaque, @ptrCast(ptr)); assert(max_waiters != 0); switch (max_waiters) { 1 => os.windows.ntdll.RtlWakeAddressSingle(address), else => os.windows.ntdll.RtlWakeAddressAll(address), } } }; const DarwinImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { // Darwin XNU 7195.50.7.100.1 introduced __ulock_wait2 and migrated code paths (notably pthread_cond_t) towards it: // https://github.com/apple/darwin-xnu/commit/d4061fb0260b3ed486147341b72468f836ed6c8f#diff-08f993cc40af475663274687b7c326cc6c3031e0db3ac8de7b24624610616be6 // // This XNU version appears to correspond to 11.0.1: // https://kernelshaman.blogspot.com/2021/01/building-xnu-for-macos-big-sur-1101.html // // ulock_wait() uses 32-bit micro-second timeouts where 0 = INFINITE or no-timeout // ulock_wait2() uses 64-bit nano-second timeouts (with the same convention) const supports_ulock_wait2 = builtin.target.os.version_range.semver.min.major >= 11; var timeout_ns: u64 = 0; if (timeout) |delay| { assert(delay != 0); // handled by timedWait() timeout_ns = delay; } // If we're using `__ulock_wait` and `timeout` is too big to fit inside a `u32` count of // micro-seconds (around 70min), we'll request a shorter timeout. This is fine (users // should handle spurious wakeups), but we need to remember that we did so, so that // we don't return `Timeout` incorrectly. If that happens, we set this variable to // true so that we we know to ignore the ETIMEDOUT result. var timeout_overflowed = false; const addr = @as(*const anyopaque, @ptrCast(ptr)); const flags = os.darwin.UL_COMPARE_AND_WAIT | os.darwin.ULF_NO_ERRNO; const status = blk: { if (supports_ulock_wait2) { break :blk os.darwin.__ulock_wait2(flags, addr, expect, timeout_ns, 0); } const timeout_us = std.math.cast(u32, timeout_ns / std.time.ns_per_us) orelse overflow: { timeout_overflowed = true; break :overflow std.math.maxInt(u32); }; break :blk os.darwin.__ulock_wait(flags, addr, expect, timeout_us); }; if (status >= 0) return; switch (@as(std.os.E, @enumFromInt(-status))) { // Wait was interrupted by the OS or other spurious signalling. .INTR => {}, // Address of the futex was paged out. This is unlikely, but possible in theory, and // pthread/libdispatch on darwin bother to handle it. In this case we'll return // without waiting, but the caller should retry anyway. .FAULT => {}, // Only report Timeout if we didn't have to cap the timeout .TIMEDOUT => { assert(timeout != null); if (!timeout_overflowed) return error.Timeout; }, else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { var flags: u32 = os.darwin.UL_COMPARE_AND_WAIT | os.darwin.ULF_NO_ERRNO; if (max_waiters > 1) { flags |= os.darwin.ULF_WAKE_ALL; } while (true) { const addr = @as(*const anyopaque, @ptrCast(ptr)); const status = os.darwin.__ulock_wake(flags, addr, 0); if (status >= 0) return; switch (@as(std.os.E, @enumFromInt(-status))) { .INTR => continue, // spurious wake() .FAULT => unreachable, // __ulock_wake doesn't generate EFAULT according to darwin pthread_cond_t .NOENT => return, // nothing was woken up .ALREADY => unreachable, // only for ULF_WAKE_THREAD else => unreachable, } } } }; // https://man7.org/linux/man-pages/man2/futex.2.html const LinuxImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { var ts: os.timespec = undefined; if (timeout) |timeout_ns| { ts.tv_sec = @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s)); ts.tv_nsec = @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s)); } const rc = os.linux.futex_wait( @as(*const i32, @ptrCast(&ptr.value)), os.linux.FUTEX.PRIVATE_FLAG | os.linux.FUTEX.WAIT, @as(i32, @bitCast(expect)), if (timeout != null) &ts else null, ); switch (os.linux.getErrno(rc)) { .SUCCESS => {}, // notified by `wake()` .INTR => {}, // spurious wakeup .AGAIN => {}, // ptr.* != expect .TIMEDOUT => { assert(timeout != null); return error.Timeout; }, .INVAL => {}, // possibly timeout overflow .FAULT => unreachable, // ptr was invalid else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { const rc = os.linux.futex_wake( @as(*const i32, @ptrCast(&ptr.value)), os.linux.FUTEX.PRIVATE_FLAG | os.linux.FUTEX.WAKE, std.math.cast(i32, max_waiters) orelse std.math.maxInt(i32), ); switch (os.linux.getErrno(rc)) { .SUCCESS => {}, // successful wake up .INVAL => {}, // invalid futex_wait() on ptr done elsewhere .FAULT => {}, // pointer became invalid while doing the wake else => unreachable, } } }; // https://www.freebsd.org/cgi/man.cgi?query=_umtx_op&sektion=2&n=1 const FreebsdImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { var tm_size: usize = 0; var tm: os.freebsd._umtx_time = undefined; var tm_ptr: ?*const os.freebsd._umtx_time = null; if (timeout) |timeout_ns| { tm_ptr = &tm; tm_size = @sizeOf(@TypeOf(tm)); tm._flags = 0; // use relative time not UMTX_ABSTIME tm._clockid = os.CLOCK.MONOTONIC; tm._timeout.tv_sec = @as(@TypeOf(tm._timeout.tv_sec), @intCast(timeout_ns / std.time.ns_per_s)); tm._timeout.tv_nsec = @as(@TypeOf(tm._timeout.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s)); } const rc = os.freebsd._umtx_op( @intFromPtr(&ptr.value), @intFromEnum(os.freebsd.UMTX_OP.WAIT_UINT_PRIVATE), @as(c_ulong, expect), tm_size, @intFromPtr(tm_ptr), ); switch (os.errno(rc)) { .SUCCESS => {}, .FAULT => unreachable, // one of the args points to invalid memory .INVAL => unreachable, // arguments should be correct .TIMEDOUT => { assert(timeout != null); return error.Timeout; }, .INTR => {}, // spurious wake else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { const rc = os.freebsd._umtx_op( @intFromPtr(&ptr.value), @intFromEnum(os.freebsd.UMTX_OP.WAKE_PRIVATE), @as(c_ulong, max_waiters), 0, // there is no timeout struct 0, // there is no timeout struct pointer ); switch (os.errno(rc)) { .SUCCESS => {}, .FAULT => {}, // it's ok if the ptr doesn't point to valid memory .INVAL => unreachable, // arguments should be correct else => unreachable, } } }; // https://man.openbsd.org/futex.2 const OpenbsdImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { var ts: os.timespec = undefined; if (timeout) |timeout_ns| { ts.tv_sec = @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s)); ts.tv_nsec = @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s)); } const rc = os.openbsd.futex( @as(*const volatile u32, @ptrCast(&ptr.value)), os.openbsd.FUTEX_WAIT | os.openbsd.FUTEX_PRIVATE_FLAG, @as(c_int, @bitCast(expect)), if (timeout != null) &ts else null, null, // FUTEX_WAIT takes no requeue address ); switch (os.errno(rc)) { .SUCCESS => {}, // woken up by wake .NOSYS => unreachable, // the futex operation shouldn't be invalid .FAULT => unreachable, // ptr was invalid .AGAIN => {}, // ptr != expect .INVAL => unreachable, // invalid timeout .TIMEDOUT => { assert(timeout != null); return error.Timeout; }, .INTR => {}, // spurious wake from signal .CANCELED => {}, // spurious wake from signal with SA_RESTART else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { const rc = os.openbsd.futex( @as(*const volatile u32, @ptrCast(&ptr.value)), os.openbsd.FUTEX_WAKE | os.openbsd.FUTEX_PRIVATE_FLAG, std.math.cast(c_int, max_waiters) orelse std.math.maxInt(c_int), null, // FUTEX_WAKE takes no timeout ptr null, // FUTEX_WAKE takes no requeue address ); // returns number of threads woken up. assert(rc >= 0); } }; // https://man.dragonflybsd.org/?command=umtx&section=2 const DragonflyImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { // Dragonfly uses a scheme where 0 timeout means wait until signaled or spurious wake. // It's reporting of timeout's is also unrealiable so we use an external timing source (Timer) instead. var timeout_us: c_int = 0; var timeout_overflowed = false; var sleep_timer: std.time.Timer = undefined; if (timeout) |delay| { assert(delay != 0); // handled by timedWait(). timeout_us = std.math.cast(c_int, delay / std.time.ns_per_us) orelse blk: { timeout_overflowed = true; break :blk std.math.maxInt(c_int); }; // Only need to record the start time if we can provide somewhat accurate error.Timeout's if (!timeout_overflowed) { sleep_timer = std.time.Timer.start() catch unreachable; } } const value = @as(c_int, @bitCast(expect)); const addr = @as(*const volatile c_int, @ptrCast(&ptr.value)); const rc = os.dragonfly.umtx_sleep(addr, value, timeout_us); switch (os.errno(rc)) { .SUCCESS => {}, .BUSY => {}, // ptr != expect .AGAIN => { // maybe timed out, or paged out, or hit 2s kernel refresh if (timeout) |timeout_ns| { // Report error.Timeout only if we know the timeout duration has passed. // If not, there's not much choice other than treating it as a spurious wake. if (!timeout_overflowed and sleep_timer.read() >= timeout_ns) { return error.Timeout; } } }, .INTR => {}, // spurious wake .INVAL => unreachable, // invalid timeout else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { // A count of zero means wake all waiters. assert(max_waiters != 0); const to_wake = std.math.cast(c_int, max_waiters) orelse 0; // https://man.dragonflybsd.org/?command=umtx&section=2 // > umtx_wakeup() will generally return 0 unless the address is bad. // We are fine with the address being bad (e.g. for Semaphore.post() where Semaphore.wait() frees the Semaphore) const addr = @as(*const volatile c_int, @ptrCast(&ptr.value)); _ = os.dragonfly.umtx_wakeup(addr, to_wake); } }; const WasmImpl = struct { fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { if (!comptime std.Target.wasm.featureSetHas(builtin.target.cpu.features, .atomics)) { @compileError("WASI target missing cpu feature 'atomics'"); } const to: i64 = if (timeout) |to| @intCast(to) else -1; const result = asm ( \\local.get %[ptr] \\local.get %[expected] \\local.get %[timeout] \\memory.atomic.wait32 0 \\local.set %[ret] : [ret] "=r" (-> u32), : [ptr] "r" (&ptr.value), [expected] "r" (@as(i32, @bitCast(expect))), [timeout] "r" (to), ); switch (result) { 0 => {}, // ok 1 => {}, // expected =! loaded 2 => return error.Timeout, else => unreachable, } } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { if (!comptime std.Target.wasm.featureSetHas(builtin.target.cpu.features, .atomics)) { @compileError("WASI target missing cpu feature 'atomics'"); } assert(max_waiters != 0); const woken_count = asm ( \\local.get %[ptr] \\local.get %[waiters] \\memory.atomic.notify 0 \\local.set %[ret] : [ret] "=r" (-> u32), : [ptr] "r" (&ptr.value), [waiters] "r" (max_waiters), ); _ = woken_count; // can be 0 when linker flag 'shared-memory' is not enabled } }; /// Modified version of linux's futex and Go's sema to implement userspace wait queues with pthread: /// https://code.woboq.org/linux/linux/kernel/futex.c.html /// https://go.dev/src/runtime/sema.go const PosixImpl = struct { const Event = struct { cond: std.c.pthread_cond_t, mutex: std.c.pthread_mutex_t, state: enum { empty, waiting, notified }, fn init(self: *Event) void { // Use static init instead of pthread_cond/mutex_init() since this is generally faster. self.cond = .{}; self.mutex = .{}; self.state = .empty; } fn deinit(self: *Event) void { // Some platforms reportedly give EINVAL for statically initialized pthread types. const rc = std.c.pthread_cond_destroy(&self.cond); assert(rc == .SUCCESS or rc == .INVAL); const rm = std.c.pthread_mutex_destroy(&self.mutex); assert(rm == .SUCCESS or rm == .INVAL); self.* = undefined; } fn wait(self: *Event, timeout: ?u64) error{Timeout}!void { assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS); defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS); // Early return if the event was already set. if (self.state == .notified) { return; } // Compute the absolute timeout if one was specified. // POSIX requires that REALTIME is used by default for the pthread timedwait functions. // This can be changed with pthread_condattr_setclock, but it's an extension and may not be available everywhere. var ts: os.timespec = undefined; if (timeout) |timeout_ns| { os.clock_gettime(os.CLOCK.REALTIME, &ts) catch unreachable; ts.tv_sec +|= @as(@TypeOf(ts.tv_sec), @intCast(timeout_ns / std.time.ns_per_s)); ts.tv_nsec += @as(@TypeOf(ts.tv_nsec), @intCast(timeout_ns % std.time.ns_per_s)); if (ts.tv_nsec >= std.time.ns_per_s) { ts.tv_sec +|= 1; ts.tv_nsec -= std.time.ns_per_s; } } // Start waiting on the event - there can be only one thread waiting. assert(self.state == .empty); self.state = .waiting; while (true) { // Block using either pthread_cond_wait or pthread_cond_timewait if there's an absolute timeout. const rc = blk: { if (timeout == null) break :blk std.c.pthread_cond_wait(&self.cond, &self.mutex); break :blk std.c.pthread_cond_timedwait(&self.cond, &self.mutex, &ts); }; // After waking up, check if the event was set. if (self.state == .notified) { return; } assert(self.state == .waiting); switch (rc) { .SUCCESS => {}, .TIMEDOUT => { // If timed out, reset the event to avoid the set() thread doing an unnecessary signal(). self.state = .empty; return error.Timeout; }, .INVAL => unreachable, // cond, mutex, and potentially ts should all be valid .PERM => unreachable, // mutex is locked when cond_*wait() functions are called else => unreachable, } } } fn set(self: *Event) void { assert(std.c.pthread_mutex_lock(&self.mutex) == .SUCCESS); defer assert(std.c.pthread_mutex_unlock(&self.mutex) == .SUCCESS); // Make sure that multiple calls to set() were not done on the same Event. const old_state = self.state; assert(old_state != .notified); // Mark the event as set and wake up the waiting thread if there was one. // This must be done while the mutex as the wait() thread could deallocate // the condition variable once it observes the new state, potentially causing a UAF if done unlocked. self.state = .notified; if (old_state == .waiting) { assert(std.c.pthread_cond_signal(&self.cond) == .SUCCESS); } } }; const Treap = std.Treap(usize, std.math.order); const Waiter = struct { node: Treap.Node, prev: ?*Waiter, next: ?*Waiter, tail: ?*Waiter, is_queued: bool, event: Event, }; // An unordered set of Waiters const WaitList = struct { top: ?*Waiter = null, len: usize = 0, fn push(self: *WaitList, waiter: *Waiter) void { waiter.next = self.top; self.top = waiter; self.len += 1; } fn pop(self: *WaitList) ?*Waiter { const waiter = self.top orelse return null; self.top = waiter.next; self.len -= 1; return waiter; } }; const WaitQueue = struct { fn insert(treap: *Treap, address: usize, waiter: *Waiter) void { // prepare the waiter to be inserted. waiter.next = null; waiter.is_queued = true; // Find the wait queue entry associated with the address. // If there isn't a wait queue on the address, this waiter creates the queue. var entry = treap.getEntryFor(address); const entry_node = entry.node orelse { waiter.prev = null; waiter.tail = waiter; entry.set(&waiter.node); return; }; // There's a wait queue on the address; get the queue head and tail. const head = @fieldParentPtr(Waiter, "node", entry_node); const tail = head.tail orelse unreachable; // Push the waiter to the tail by replacing it and linking to the previous tail. head.tail = waiter; tail.next = waiter; waiter.prev = tail; } fn remove(treap: *Treap, address: usize, max_waiters: usize) WaitList { // Find the wait queue associated with this address and get the head/tail if any. var entry = treap.getEntryFor(address); var queue_head = if (entry.node) |node| @fieldParentPtr(Waiter, "node", node) else null; const queue_tail = if (queue_head) |head| head.tail else null; // Once we're done updating the head, fix it's tail pointer and update the treap's queue head as well. defer entry.set(blk: { const new_head = queue_head orelse break :blk null; new_head.tail = queue_tail; break :blk &new_head.node; }); var removed = WaitList{}; while (removed.len < max_waiters) { // dequeue and collect waiters from their wait queue. const waiter = queue_head orelse break; queue_head = waiter.next; removed.push(waiter); // When dequeueing, we must mark is_queued as false. // This ensures that a waiter which calls tryRemove() returns false. assert(waiter.is_queued); waiter.is_queued = false; } return removed; } fn tryRemove(treap: *Treap, address: usize, waiter: *Waiter) bool { if (!waiter.is_queued) { return false; } queue_remove: { // Find the wait queue associated with the address. var entry = blk: { // A waiter without a previous link means it's the queue head that's in the treap so we can avoid lookup. if (waiter.prev == null) { assert(waiter.node.key == address); break :blk treap.getEntryForExisting(&waiter.node); } break :blk treap.getEntryFor(address); }; // The queue head and tail must exist if we're removing a queued waiter. const head = @fieldParentPtr(Waiter, "node", entry.node orelse unreachable); const tail = head.tail orelse unreachable; // A waiter with a previous link is never the head of the queue. if (waiter.prev) |prev| { assert(waiter != head); prev.next = waiter.next; // A waiter with both a previous and next link is in the middle. // We only need to update the surrounding waiter's links to remove it. if (waiter.next) |next| { assert(waiter != tail); next.prev = waiter.prev; break :queue_remove; } // A waiter with a previous but no next link means it's the tail of the queue. // In that case, we need to update the head's tail reference. assert(waiter == tail); head.tail = waiter.prev; break :queue_remove; } // A waiter with no previous link means it's the queue head of queue. // We must replace (or remove) the head waiter reference in the treap. assert(waiter == head); entry.set(blk: { const new_head = waiter.next orelse break :blk null; new_head.tail = head.tail; break :blk &new_head.node; }); } // Mark the waiter as successfully removed. waiter.is_queued = false; return true; } }; const Bucket = struct { mutex: std.c.pthread_mutex_t align(std.atomic.cache_line) = .{}, pending: Atomic(usize) = Atomic(usize).init(0), treap: Treap = .{}, // Global array of buckets that addresses map to. // Bucket array size is pretty much arbitrary here, but it must be a power of two for fibonacci hashing. var buckets = [_]Bucket{.{}} ** @bitSizeOf(usize); // https://github.com/Amanieu/parking_lot/blob/1cf12744d097233316afa6c8b7d37389e4211756/core/src/parking_lot.rs#L343-L353 fn from(address: usize) *Bucket { // The upper `@bitSizeOf(usize)` bits of the fibonacci golden ratio. // Hashing this via (h * k) >> (64 - b) where k=golden-ration and b=bitsize-of-array // evenly lays out h=hash values over the bit range even when the hash has poor entropy (identity-hash for pointers). const max_multiplier_bits = @bitSizeOf(usize); const fibonacci_multiplier = 0x9E3779B97F4A7C15 >> (64 - max_multiplier_bits); const max_bucket_bits = @ctz(buckets.len); comptime assert(std.math.isPowerOfTwo(buckets.len)); const index = (address *% fibonacci_multiplier) >> (max_multiplier_bits - max_bucket_bits); return &buckets[index]; } }; const Address = struct { fn from(ptr: *const Atomic(u32)) usize { // Get the alignment of the pointer. const alignment = @alignOf(Atomic(u32)); comptime assert(std.math.isPowerOfTwo(alignment)); // Make sure the pointer is aligned, // then cut off the zero bits from the alignment to get the unique address. const addr = @intFromPtr(ptr); assert(addr & (alignment - 1) == 0); return addr >> @ctz(@as(usize, alignment)); } }; fn wait(ptr: *const Atomic(u32), expect: u32, timeout: ?u64) error{Timeout}!void { const address = Address.from(ptr); const bucket = Bucket.from(address); // Announce that there's a waiter in the bucket before checking the ptr/expect condition. // If the announcement is reordered after the ptr check, the waiter could deadlock: // // - T1: checks ptr == expect which is true // - T2: updates ptr to != expect // - T2: does Futex.wake(), sees no pending waiters, exits // - T1: bumps pending waiters (was reordered after the ptr == expect check) // - T1: goes to sleep and misses both the ptr change and T2's wake up // // SeqCst as Acquire barrier to ensure the announcement happens before the ptr check below. // SeqCst as shared modification order to form a happens-before edge with the fence(.SeqCst)+load() in wake(). var pending = bucket.pending.fetchAdd(1, .SeqCst); assert(pending < std.math.maxInt(usize)); // If the wait gets cancelled, remove the pending count we previously added. // This is done outside the mutex lock to keep the critical section short in case of contention. var cancelled = false; defer if (cancelled) { pending = bucket.pending.fetchSub(1, .Monotonic); assert(pending > 0); }; var waiter: Waiter = undefined; { assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS); defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS); cancelled = ptr.load(.Monotonic) != expect; if (cancelled) { return; } waiter.event.init(); WaitQueue.insert(&bucket.treap, address, &waiter); } defer { assert(!waiter.is_queued); waiter.event.deinit(); } waiter.event.wait(timeout) catch { // If we fail to cancel after a timeout, it means a wake() thread dequeued us and will wake us up. // We must wait until the event is set as that's a signal that the wake() thread won't access the waiter memory anymore. // If we return early without waiting, the waiter on the stack would be invalidated and the wake() thread risks a UAF. defer if (!cancelled) waiter.event.wait(null) catch unreachable; assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS); defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS); cancelled = WaitQueue.tryRemove(&bucket.treap, address, &waiter); if (cancelled) { return error.Timeout; } }; } fn wake(ptr: *const Atomic(u32), max_waiters: u32) void { const address = Address.from(ptr); const bucket = Bucket.from(address); // Quick check if there's even anything to wake up. // The change to the ptr's value must happen before we check for pending waiters. // If not, the wake() thread could miss a sleeping waiter and have it deadlock: // // - T2: p = has pending waiters (reordered before the ptr update) // - T1: bump pending waiters // - T1: if ptr == expected: sleep() // - T2: update ptr != expected // - T2: p is false from earlier so doesn't wake (T1 missed ptr update and T2 missed T1 sleeping) // // What we really want here is a Release load, but that doesn't exist under the C11 memory model. // We could instead do `bucket.pending.fetchAdd(0, Release) == 0` which achieves effectively the same thing, // but the RMW operation unconditionally marks the cache-line as modified for others causing unnecessary fetching/contention. // // Instead we opt to do a full-fence + load instead which avoids taking ownership of the cache-line. // fence(SeqCst) effectively converts the ptr update to SeqCst and the pending load to SeqCst: creating a Store-Load barrier. // // The pending count increment in wait() must also now use SeqCst for the update + this pending load // to be in the same modification order as our load isn't using Release/Acquire to guarantee it. bucket.pending.fence(.SeqCst); if (bucket.pending.load(.Monotonic) == 0) { return; } // Keep a list of all the waiters notified and wake then up outside the mutex critical section. var notified = WaitList{}; defer if (notified.len > 0) { const pending = bucket.pending.fetchSub(notified.len, .Monotonic); assert(pending >= notified.len); while (notified.pop()) |waiter| { assert(!waiter.is_queued); waiter.event.set(); } }; assert(std.c.pthread_mutex_lock(&bucket.mutex) == .SUCCESS); defer assert(std.c.pthread_mutex_unlock(&bucket.mutex) == .SUCCESS); // Another pending check again to avoid the WaitQueue lookup if not necessary. if (bucket.pending.load(.Monotonic) > 0) { notified = WaitQueue.remove(&bucket.treap, address, max_waiters); } } }; test "Futex - smoke test" { var value = Atomic(u32).init(0); // Try waits with invalid values. Futex.wait(&value, 0xdeadbeef); Futex.timedWait(&value, 0xdeadbeef, 0) catch {}; // Try timeout waits. try testing.expectError(error.Timeout, Futex.timedWait(&value, 0, 0)); try testing.expectError(error.Timeout, Futex.timedWait(&value, 0, std.time.ns_per_ms)); // Try wakes Futex.wake(&value, 0); Futex.wake(&value, 1); Futex.wake(&value, std.math.maxInt(u32)); } test "Futex - signaling" { // This test requires spawning threads if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const num_iterations = 4; const Paddle = struct { value: Atomic(u32) = Atomic(u32).init(0), current: u32 = 0, fn hit(self: *@This()) void { _ = self.value.fetchAdd(1, .Release); Futex.wake(&self.value, 1); } fn run(self: *@This(), hit_to: *@This()) !void { while (self.current < num_iterations) { // Wait for the value to change from hit() var new_value: u32 = undefined; while (true) { new_value = self.value.load(.Acquire); if (new_value != self.current) break; Futex.wait(&self.value, self.current); } // change the internal "current" value try testing.expectEqual(new_value, self.current + 1); self.current = new_value; // hit the next paddle hit_to.hit(); } } }; var paddles = [_]Paddle{.{}} ** num_threads; var threads = [_]std.Thread{undefined} ** num_threads; // Create a circle of paddles which hit each other for (&threads, 0..) |*t, i| { const paddle = &paddles[i]; const hit_to = &paddles[(i + 1) % paddles.len]; t.* = try std.Thread.spawn(.{}, Paddle.run, .{ paddle, hit_to }); } // Hit the first paddle and wait for them all to complete by hitting each other for num_iterations. paddles[0].hit(); for (threads) |t| t.join(); for (paddles) |p| try testing.expectEqual(p.current, num_iterations); } test "Futex - broadcasting" { // This test requires spawning threads if (builtin.single_threaded) { return error.SkipZigTest; } const num_threads = 4; const num_iterations = 4; const Barrier = struct { count: Atomic(u32) = Atomic(u32).init(num_threads), futex: Atomic(u32) = Atomic(u32).init(0), fn wait(self: *@This()) !void { // Decrement the counter. // Release ensures stuff before this barrier.wait() happens before the last one. const count = self.count.fetchSub(1, .Release); try testing.expect(count <= num_threads); try testing.expect(count > 0); // First counter to reach zero wakes all other threads. // Acquire for the last counter ensures stuff before previous barrier.wait()s happened before it. // Release on futex update ensures stuff before all barrier.wait()'s happens before they all return. if (count - 1 == 0) { _ = self.count.load(.Acquire); // TODO: could be fence(Acquire) if not for TSAN self.futex.store(1, .Release); Futex.wake(&self.futex, num_threads - 1); return; } // Other threads wait until last counter wakes them up. // Acquire on futex synchronizes with last barrier count to ensure stuff before all barrier.wait()'s happen before us. while (self.futex.load(.Acquire) == 0) { Futex.wait(&self.futex, 0); } } }; const Broadcast = struct { barriers: [num_iterations]Barrier = [_]Barrier{.{}} ** num_iterations, threads: [num_threads]std.Thread = undefined, fn run(self: *@This()) !void { for (&self.barriers) |*barrier| { try barrier.wait(); } } }; var broadcast = Broadcast{}; for (&broadcast.threads) |*t| t.* = try std.Thread.spawn(.{}, Broadcast.run, .{&broadcast}); for (broadcast.threads) |t| t.join(); } /// Deadline is used to wait efficiently for a pointer's value to change using Futex and a fixed timeout. /// /// Futex's timedWait() api uses a relative duration which suffers from over-waiting /// when used in a loop which is often required due to the possibility of spurious wakeups. /// /// Deadline instead converts the relative timeout to an absolute one so that multiple calls /// to Futex timedWait() can block for and report more accurate error.Timeouts. pub const Deadline = struct { timeout: ?u64, started: std.time.Timer, /// Create the deadline to expire after the given amount of time in nanoseconds passes. /// Pass in `null` to have the deadline call `Futex.wait()` and never expire. pub fn init(expires_in_ns: ?u64) Deadline { var deadline: Deadline = undefined; deadline.timeout = expires_in_ns; // std.time.Timer is required to be supported for somewhat accurate reportings of error.Timeout. if (deadline.timeout != null) { deadline.started = std.time.Timer.start() catch unreachable; } return deadline; } /// Wait until either: /// - the `ptr`'s value changes from `expect`. /// - `Futex.wake()` is called on the `ptr`. /// - A spurious wake occurs. /// - The deadline expires; In which case `error.Timeout` is returned. pub fn wait(self: *Deadline, ptr: *const Atomic(u32), expect: u32) error{Timeout}!void { @setCold(true); // Check if we actually have a timeout to wait until. // If not just wait "forever". const timeout_ns = self.timeout orelse { return Futex.wait(ptr, expect); }; // Get how much time has passed since we started waiting // then subtract that from the init() timeout to get how much longer to wait. // Use overflow to detect when we've been waiting longer than the init() timeout. const elapsed_ns = self.started.read(); const until_timeout_ns = std.math.sub(u64, timeout_ns, elapsed_ns) catch 0; return Futex.timedWait(ptr, expect, until_timeout_ns); } }; test "Futex - Deadline" { var deadline = Deadline.init(100 * std.time.ns_per_ms); var futex_word = Atomic(u32).init(0); while (true) { deadline.wait(&futex_word, 0) catch break; } }
https://raw.githubusercontent.com/mundusnine/FoundryTools_windows_x64/b64cdb7e56db28eb710a05a089aed0daff8bc8be/lib/std/Thread/Futex.zig
//! Implementation of the IND-CCA2 post-quantum secure key encapsulation //! mechanism (KEM) CRYSTALS-Kyber, as submitted to the third round of the NIST //! Post-Quantum Cryptography (v3.02/"draft00"), and selected for standardisation. //! //! Kyber will likely change before final standardisation. //! //! The namespace suffix (currently `_d00`) refers to the version currently //! implemented, in accordance with the draft. It may not be updated if new //! versions of the draft only include editorial changes. //! //! The suffix will eventually be removed once Kyber is finalized. //! //! Quoting from the CFRG I-D: //! //! Kyber is not a Diffie-Hellman (DH) style non-interactive key //! agreement, but instead, Kyber is a Key Encapsulation Method (KEM). //! In essence, a KEM is a Public-Key Encryption (PKE) scheme where the //! plaintext cannot be specified, but is generated as a random key as //! part of the encryption. A KEM can be transformed into an unrestricted //! PKE using HPKE (RFC9180). On its own, a KEM can be used as a key //! agreement method in TLS. //! //! Kyber is an IND-CCA2 secure KEM. It is constructed by applying a //! Fujisaki--Okamato style transformation on InnerPKE, which is the //! underlying IND-CPA secure Public Key Encryption scheme. We cannot //! use InnerPKE directly, as its ciphertexts are malleable. //! //! ``` //! F.O. transform //! InnerPKE ----------------------> Kyber //! IND-CPA IND-CCA2 //! ``` //! //! Kyber is a lattice-based scheme. More precisely, its security is //! based on the learning-with-errors-and-rounding problem in module //! lattices (MLWER). The underlying polynomial ring R (defined in //! Section 5) is chosen such that multiplication is very fast using the //! number theoretic transform (NTT, see Section 5.1.3). //! //! An InnerPKE private key is a vector _s_ over R of length k which is //! _small_ in a particular way. Here k is a security parameter akin to //! the size of a prime modulus. For Kyber512, which targets AES-128's //! security level, the value of k is 2. //! //! The public key consists of two values: //! //! * _A_ a uniformly sampled k by k matrix over R _and_ //! //! * _t = A s + e_, where e is a suitably small masking vector. //! //! Distinguishing between such A s + e and a uniformly sampled t is the //! module learning-with-errors (MLWE) problem. If that is hard, then it //! is also hard to recover the private key from the public key as that //! would allow you to distinguish between those two. //! //! To save space in the public key, A is recomputed deterministically //! from a seed _rho_. //! //! A ciphertext for a message m under this public key is a pair (c_1, //! c_2) computed roughly as follows: //! //! c_1 = Compress(A^T r + e_1, d_u) //! c_2 = Compress(t^T r + e_2 + Decompress(m, 1), d_v) //! //! where //! //! * e_1, e_2 and r are small blinds; //! //! * Compress(-, d) removes some information, leaving d bits per //! coefficient and Decompress is such that Compress after Decompress //! does nothing and //! //! * d_u, d_v are scheme parameters. //! //! Distinguishing such a ciphertext and uniformly sampled (c_1, c_2) is //! an example of the full MLWER problem, see section 4.4 of [KyberV302]. //! //! To decrypt the ciphertext, one computes //! //! m = Compress(Decompress(c_2, d_v) - s^T Decompress(c_1, d_u), 1). //! //! It it not straight-forward to see that this formula is correct. In //! fact, there is negligible but non-zero probability that a ciphertext //! does not decrypt correctly given by the DFP column in Table 4. This //! failure probability can be computed by a careful automated analysis //! of the probabilities involved, see kyber_failure.py of [SecEst]. //! //! [KyberV302](https://pq-crystals.org/kyber/data/kyber-specification-round3-20210804.pdf) //! [I-D](https://github.com/bwesterb/draft-schwabe-cfrg-kyber) //! [SecEst](https://github.com/pq-crystals/security-estimates) // TODO // // - The bottleneck in Kyber are the various hash/xof calls: // - Optimize Zig's keccak implementation. // - Use SIMD to compute keccak in parallel. // - Can we track bounds of coefficients using comptime types without // duplicating code? // - Would be neater to have tests closer to the thing under test. // - When generating a keypair, we have a copy of the inner public key with // its large matrix A in both the public key and the private key. In Go we // can just have a pointer in the private key to the public key, but // how do we do this elegantly in Zig? const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const assert = std.debug.assert; const crypto = std.crypto; const math = std.math; const mem = std.mem; const RndGen = std.Random.DefaultPrng; const sha3 = crypto.hash.sha3; // Q is the parameter q ≡ 3329 = 2¹¹ + 2¹⁰ + 2⁸ + 1. const Q: i16 = 3329; // Montgomery R const R: i32 = 1 << 16; // Parameter n, degree of polynomials. const N: usize = 256; // Size of "small" vectors used in encryption blinds. const eta2: u8 = 2; const Params = struct { name: []const u8, // Width and height of the matrix A. k: u8, // Size of "small" vectors used in private key and encryption blinds. eta1: u8, // How many bits to retain of u, the private-key independent part // of the ciphertext. du: u8, // How many bits to retain of v, the private-key dependent part // of the ciphertext. dv: u8, }; pub const Kyber512 = Kyber(.{ .name = "Kyber512", .k = 2, .eta1 = 3, .du = 10, .dv = 4, }); pub const Kyber768 = Kyber(.{ .name = "Kyber768", .k = 3, .eta1 = 2, .du = 10, .dv = 4, }); pub const Kyber1024 = Kyber(.{ .name = "Kyber1024", .k = 4, .eta1 = 2, .du = 11, .dv = 5, }); const modes = [_]type{ Kyber512, Kyber768, Kyber1024 }; const h_length: usize = 32; const inner_seed_length: usize = 32; const common_encaps_seed_length: usize = 32; const common_shared_key_size: usize = 32; fn Kyber(comptime p: Params) type { return struct { // Size of a ciphertext, in bytes. pub const ciphertext_length = Poly.compressedSize(p.du) * p.k + Poly.compressedSize(p.dv); const Self = @This(); const V = Vec(p.k); const M = Mat(p.k); /// Length (in bytes) of a shared secret. pub const shared_length = common_shared_key_size; /// Length (in bytes) of a seed for deterministic encapsulation. pub const encaps_seed_length = common_encaps_seed_length; /// Length (in bytes) of a seed for key generation. pub const seed_length: usize = inner_seed_length + shared_length; /// Algorithm name. pub const name = p.name; /// A shared secret, and an encapsulated (encrypted) representation of it. pub const EncapsulatedSecret = struct { shared_secret: [shared_length]u8, ciphertext: [ciphertext_length]u8, }; /// A Kyber public key. pub const PublicKey = struct { pk: InnerPk, // Cached hpk: [h_length]u8, // H(pk) /// Size of a serialized representation of the key, in bytes. pub const bytes_length = InnerPk.bytes_length; /// Generates a shared secret, and encapsulates it for the public key. /// If `seed` is `null`, a random seed is used. This is recommended. /// If `seed` is set, encapsulation is deterministic. pub fn encaps(pk: PublicKey, seed_: ?[encaps_seed_length]u8) EncapsulatedSecret { const seed = seed_ orelse seed: { var random_seed: [encaps_seed_length]u8 = undefined; crypto.random.bytes(&random_seed); break :seed random_seed; }; var m: [inner_plaintext_length]u8 = undefined; // m = H(seed) var h = sha3.Sha3_256.init(.{}); h.update(&seed); h.final(&m); // (K', r) = G(m ‖ H(pk)) var kr: [inner_plaintext_length + h_length]u8 = undefined; var g = sha3.Sha3_512.init(.{}); g.update(&m); g.update(&pk.hpk); g.final(&kr); // c = innerEncrypy(pk, m, r) const ct = pk.pk.encrypt(&m, kr[32..64]); // Compute H(c) and put in second slot of kr, which will be (K', H(c)). h = sha3.Sha3_256.init(.{}); h.update(&ct); h.final(kr[32..64]); // K = KDF(K' ‖ H(c)) var kdf = sha3.Shake256.init(.{}); kdf.update(&kr); var ss: [shared_length]u8 = undefined; kdf.squeeze(&ss); return EncapsulatedSecret{ .shared_secret = ss, .ciphertext = ct, }; } /// Serializes the key into a byte array. pub fn toBytes(pk: PublicKey) [bytes_length]u8 { return pk.pk.toBytes(); } /// Deserializes the key from a byte array. pub fn fromBytes(buf: *const [bytes_length]u8) !PublicKey { var ret: PublicKey = undefined; ret.pk = InnerPk.fromBytes(buf[0..InnerPk.bytes_length]); var h = sha3.Sha3_256.init(.{}); h.update(buf); h.final(&ret.hpk); return ret; } }; /// A Kyber secret key. pub const SecretKey = struct { sk: InnerSk, pk: InnerPk, hpk: [h_length]u8, // H(pk) z: [shared_length]u8, /// Size of a serialized representation of the key, in bytes. pub const bytes_length: usize = InnerSk.bytes_length + InnerPk.bytes_length + h_length + shared_length; /// Decapsulates the shared secret within ct using the private key. pub fn decaps(sk: SecretKey, ct: *const [ciphertext_length]u8) ![shared_length]u8 { // m' = innerDec(ct) const m2 = sk.sk.decrypt(ct); // (K'', r') = G(m' ‖ H(pk)) var kr2: [64]u8 = undefined; var g = sha3.Sha3_512.init(.{}); g.update(&m2); g.update(&sk.hpk); g.final(&kr2); // ct' = innerEnc(pk, m', r') const ct2 = sk.pk.encrypt(&m2, kr2[32..64]); // Compute H(ct) and put in the second slot of kr2 which will be (K'', H(ct)). var h = sha3.Sha3_256.init(.{}); h.update(ct); h.final(kr2[32..64]); // Replace K'' by z in the first slot of kr2 if ct ≠ ct'. cmov(32, kr2[0..32], sk.z, ctneq(ciphertext_length, ct.*, ct2)); // K = KDF(K''/z, H(c)) var kdf = sha3.Shake256.init(.{}); var ss: [shared_length]u8 = undefined; kdf.update(&kr2); kdf.squeeze(&ss); return ss; } /// Serializes the key into a byte array. pub fn toBytes(sk: SecretKey) [bytes_length]u8 { return sk.sk.toBytes() ++ sk.pk.toBytes() ++ sk.hpk ++ sk.z; } /// Deserializes the key from a byte array. pub fn fromBytes(buf: *const [bytes_length]u8) !SecretKey { var ret: SecretKey = undefined; comptime var s: usize = 0; ret.sk = InnerSk.fromBytes(buf[s .. s + InnerSk.bytes_length]); s += InnerSk.bytes_length; ret.pk = InnerPk.fromBytes(buf[s .. s + InnerPk.bytes_length]); s += InnerPk.bytes_length; ret.hpk = buf[s..][0..h_length].*; s += h_length; ret.z = buf[s..][0..shared_length].*; return ret; } }; /// A Kyber key pair. pub const KeyPair = struct { secret_key: SecretKey, public_key: PublicKey, /// Create a new key pair. /// If seed is null, a random seed will be generated. /// If a seed is provided, the key pair will be determinsitic. pub fn create(seed_: ?[seed_length]u8) !KeyPair { const seed = seed_ orelse sk: { var random_seed: [seed_length]u8 = undefined; crypto.random.bytes(&random_seed); break :sk random_seed; }; var ret: KeyPair = undefined; ret.secret_key.z = seed[inner_seed_length..seed_length].*; // Generate inner key innerKeyFromSeed( seed[0..inner_seed_length].*, &ret.public_key.pk, &ret.secret_key.sk, ); ret.secret_key.pk = ret.public_key.pk; // Copy over z from seed. ret.secret_key.z = seed[inner_seed_length..seed_length].*; // Compute H(pk) var h = sha3.Sha3_256.init(.{}); h.update(&ret.public_key.pk.toBytes()); h.final(&ret.secret_key.hpk); ret.public_key.hpk = ret.secret_key.hpk; return ret; } }; // Size of plaintexts of the in const inner_plaintext_length: usize = Poly.compressedSize(1); const InnerPk = struct { rho: [32]u8, // ρ, the seed for the matrix A th: V, // NTT(t), normalized // Cached values aT: M, const bytes_length = V.bytes_length + 32; fn encrypt( pk: InnerPk, pt: *const [inner_plaintext_length]u8, seed: *const [32]u8, ) [ciphertext_length]u8 { // Sample r, e₁ and e₂ appropriately const rh = V.noise(p.eta1, 0, seed).ntt().barrettReduce(); const e1 = V.noise(eta2, p.k, seed); const e2 = Poly.noise(eta2, 2 * p.k, seed); // Next we compute u = Aᵀ r + e₁. First Aᵀ. var u: V = undefined; for (0..p.k) |i| { // Note that coefficients of r are bounded by q and those of Aᵀ // are bounded by 4.5q and so their product is bounded by 2¹⁵q // as required for multiplication. u.ps[i] = pk.aT.vs[i].dotHat(rh); } // Aᵀ and r were not in Montgomery form, so the Montgomery // multiplications in the inner product added a factor R⁻¹ which // the InvNTT cancels out. u = u.barrettReduce().invNTT().add(e1).normalize(); // Next, compute v = <t, r> + e₂ + Decompress_q(m, 1) const v = pk.th.dotHat(rh).barrettReduce().invNTT() .add(Poly.decompress(1, pt)).add(e2).normalize(); return u.compress(p.du) ++ v.compress(p.dv); } fn toBytes(pk: InnerPk) [bytes_length]u8 { return pk.th.toBytes() ++ pk.rho; } fn fromBytes(buf: *const [bytes_length]u8) InnerPk { var ret: InnerPk = undefined; ret.th = V.fromBytes(buf[0..V.bytes_length]).normalize(); ret.rho = buf[V.bytes_length..bytes_length].*; ret.aT = M.uniform(ret.rho, true); return ret; } }; // Private key of the inner PKE const InnerSk = struct { sh: V, // NTT(s), normalized const bytes_length = V.bytes_length; fn decrypt(sk: InnerSk, ct: *const [ciphertext_length]u8) [inner_plaintext_length]u8 { const u = V.decompress(p.du, ct[0..comptime V.compressedSize(p.du)]); const v = Poly.decompress( p.dv, ct[comptime V.compressedSize(p.du)..ciphertext_length], ); // Compute m = v - <s, u> return v.sub(sk.sh.dotHat(u.ntt()).barrettReduce().invNTT()) .normalize().compress(1); } fn toBytes(sk: InnerSk) [bytes_length]u8 { return sk.sh.toBytes(); } fn fromBytes(buf: *const [bytes_length]u8) InnerSk { var ret: InnerSk = undefined; ret.sh = V.fromBytes(buf).normalize(); return ret; } }; // Derives inner PKE keypair from given seed. fn innerKeyFromSeed(seed: [inner_seed_length]u8, pk: *InnerPk, sk: *InnerSk) void { var expanded_seed: [64]u8 = undefined; var h = sha3.Sha3_512.init(.{}); h.update(&seed); h.final(&expanded_seed); pk.rho = expanded_seed[0..32].*; const sigma = expanded_seed[32..64]; pk.aT = M.uniform(pk.rho, false); // Expand ρ to A; we'll transpose later on // Sample secret vector s. sk.sh = V.noise(p.eta1, 0, sigma).ntt().normalize(); const eh = Vec(p.k).noise(p.eta1, p.k, sigma).ntt(); // sample blind e. var th: V = undefined; // Next, we compute t = A s + e. for (0..p.k) |i| { // Note that coefficients of s are bounded by q and those of A // are bounded by 4.5q and so their product is bounded by 2¹⁵q // as required for multiplication. // A and s were not in Montgomery form, so the Montgomery // multiplications in the inner product added a factor R⁻¹ which // we'll cancel out with toMont(). This will also ensure the // coefficients of th are bounded in absolute value by q. th.ps[i] = pk.aT.vs[i].dotHat(sk.sh).toMont(); } pk.th = th.add(eh).normalize(); // bounded by 8q pk.aT = pk.aT.transpose(); } }; } // R mod q const r_mod_q: i32 = @rem(@as(i32, R), Q); // R² mod q const r2_mod_q: i32 = @rem(r_mod_q * r_mod_q, Q); // ζ is the degree 256 primitive root of unity used for the NTT. const zeta: i16 = 17; // (128)⁻¹ R². Used in inverse NTT. const r2_over_128: i32 = @mod(invertMod(128, Q) * r2_mod_q, Q); // zetas lists precomputed powers of the primitive root of unity in // Montgomery representation used for the NTT: // // zetas[i] = ζᵇʳᵛ⁽ⁱ⁾ R mod q // // where ζ = 17, brv(i) is the bitreversal of a 7-bit number and R=2¹⁶ mod q. const zetas = computeZetas(); // invNTTReductions keeps track of which coefficients to apply Barrett // reduction to in Poly.invNTT(). // // Generated lazily: once a butterfly is computed which is about to // overflow the i16, the largest coefficient is reduced. If that is // not enough, the other coefficient is reduced as well. // // This is actually optimal, as proven in https://eprint.iacr.org/2020/1377.pdf // TODO generate comptime? const inv_ntt_reductions = [_]i16{ -1, // after layer 1 -1, // after layer 2 16, 17, 48, 49, 80, 81, 112, 113, 144, 145, 176, 177, 208, 209, 240, 241, -1, // after layer 3 0, 1, 32, 33, 34, 35, 64, 65, 96, 97, 98, 99, 128, 129, 160, 161, 162, 163, 192, 193, 224, 225, 226, 227, -1, // after layer 4 2, 3, 66, 67, 68, 69, 70, 71, 130, 131, 194, 195, 196, 197, 198, 199, -1, // after layer 5 4, 5, 6, 7, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, -1, // after layer 6 -1, // after layer 7 }; test "invNTTReductions bounds" { // Checks whether the reductions proposed by invNTTReductions // don't overflow during invNTT(). var xs = [_]i32{1} ** 256; // start at |x| ≤ q var r: usize = 0; var layer: math.Log2Int(usize) = 1; while (layer < 8) : (layer += 1) { const w = @as(usize, 1) << layer; var i: usize = 0; while (i + w < 256) { xs[i] = xs[i] + xs[i + w]; try testing.expect(xs[i] <= 9); // we can't exceed 9q xs[i + w] = 1; i += 1; if (@mod(i, w) == 0) { i += w; } } while (true) { const j = inv_ntt_reductions[r]; r += 1; if (j < 0) { break; } xs[@as(usize, @intCast(j))] = 1; } } } // Extended euclidean algorithm. // // For a, b finds x, y such that x a + y b = gcd(a, b). Used to compute // modular inverse. fn eea(a: anytype, b: @TypeOf(a)) EeaResult(@TypeOf(a)) { if (a == 0) { return .{ .gcd = b, .x = 0, .y = 1 }; } const r = eea(@rem(b, a), a); return .{ .gcd = r.gcd, .x = r.y - @divTrunc(b, a) * r.x, .y = r.x }; } fn EeaResult(comptime T: type) type { return struct { gcd: T, x: T, y: T }; } // Returns least common multiple of a and b. fn lcm(a: anytype, b: @TypeOf(a)) @TypeOf(a) { const r = eea(a, b); return a * b / r.gcd; } // Invert modulo p. fn invertMod(a: anytype, p: @TypeOf(a)) @TypeOf(a) { const r = eea(a, p); assert(r.gcd == 1); return r.x; } // Reduce mod q for testing. fn modQ32(x: i32) i16 { var y = @as(i16, @intCast(@rem(x, @as(i32, Q)))); if (y < 0) { y += Q; } return y; } // Given -2¹⁵ q ≤ x < 2¹⁵ q, returns -q < y < q with x 2⁻¹⁶ = y (mod q). fn montReduce(x: i32) i16 { const qInv = comptime invertMod(@as(i32, Q), R); // This is Montgomery reduction with R=2¹⁶. // // Note gcd(2¹⁶, q) = 1 as q is prime. Write q' := 62209 = q⁻¹ mod R. // First we compute // // m := ((x mod R) q') mod R // = x q' mod R // = int16(x q') // = int16(int32(x) * int32(q')) // // Note that x q' might be as big as 2³² and could overflow the int32 // multiplication in the last line. However for any int32s a and b, // we have int32(int64(a)*int64(b)) = int32(a*b) and so the result is ok. const m: i16 = @truncate(@as(i32, @truncate(x *% qInv))); // Note that x - m q is divisible by R; indeed modulo R we have // // x - m q ≡ x - x q' q ≡ x - x q⁻¹ q ≡ x - x = 0. // // We return y := (x - m q) / R. Note that y is indeed correct as // modulo q we have // // y ≡ x R⁻¹ - m q R⁻¹ = x R⁻¹ // // and as both 2¹⁵ q ≤ m q, x < 2¹⁵ q, we have // 2¹⁶ q ≤ x - m q < 2¹⁶ and so q ≤ (x - m q) / R < q as desired. const yR = x - @as(i32, m) * @as(i32, Q); return @bitCast(@as(u16, @truncate(@as(u32, @bitCast(yR)) >> 16))); } test "Test montReduce" { var rnd = RndGen.init(0); for (0..1000) |_| { const bound = comptime @as(i32, Q) * (1 << 15); const x = rnd.random().intRangeLessThan(i32, -bound, bound); const y = montReduce(x); try testing.expect(-Q < y and y < Q); try testing.expectEqual(modQ32(x), modQ32(@as(i32, y) * R)); } } // Given any x, return x R mod q where R=2¹⁶. fn feToMont(x: i16) i16 { // Note |1353 x| ≤ 1353 2¹⁵ ≤ 13318 q ≤ 2¹⁵ q and so we're within // the bounds of montReduce. return montReduce(@as(i32, x) * r2_mod_q); } test "Test feToMont" { var x: i32 = -(1 << 15); while (x < 1 << 15) : (x += 1) { const y = feToMont(@as(i16, @intCast(x))); try testing.expectEqual(modQ32(@as(i32, y)), modQ32(x * r_mod_q)); } } // Given any x, compute 0 ≤ y ≤ q with x = y (mod q). // // Beware: we might have feBarrettReduce(x) = q ≠ 0 for some x. In fact, // this happens if and only if x = -nq for some positive integer n. fn feBarrettReduce(x: i16) i16 { // This is standard Barrett reduction. // // For any x we have x mod q = x - ⌊x/q⌋ q. We will use 20159/2²⁶ as // an approximation of 1/q. Note that 0 ≤ 20159/2²⁶ - 1/q ≤ 0.135/2²⁶ // and so | x 20156/2²⁶ - x/q | ≤ 2⁻¹⁰ for |x| ≤ 2¹⁶. For all x // not a multiple of q, the number x/q is further than 1/q from any integer // and so ⌊x 20156/2²⁶⌋ = ⌊x/q⌋. If x is a multiple of q and x is positive, // then x 20156/2²⁶ is larger than x/q so ⌊x 20156/2²⁶⌋ = ⌊x/q⌋ as well. // Finally, if x is negative multiple of q, then ⌊x 20156/2²⁶⌋ = ⌊x/q⌋-1. // Thus // [ q if x=-nq for pos. integer n // x - ⌊x 20156/2²⁶⌋ q = [ // [ x mod q otherwise // // To actually compute this, note that // // ⌊x 20156/2²⁶⌋ = (20159 x) >> 26. return x -% @as(i16, @intCast((@as(i32, x) * 20159) >> 26)) *% Q; } test "Test Barrett reduction" { var x: i32 = -(1 << 15); while (x < 1 << 15) : (x += 1) { var y1 = feBarrettReduce(@as(i16, @intCast(x))); const y2 = @mod(@as(i16, @intCast(x)), Q); if (x < 0 and @rem(-x, Q) == 0) { y1 -= Q; } try testing.expectEqual(y1, y2); } } // Returns x if x < q and x - q otherwise. Assumes x ≥ -29439. fn csubq(x: i16) i16 { var r = x; r -= Q; r += (r >> 15) & Q; return r; } test "Test csubq" { var x: i32 = -29439; while (x < 1 << 15) : (x += 1) { const y1 = csubq(@as(i16, @intCast(x))); var y2 = @as(i16, @intCast(x)); if (@as(i16, @intCast(x)) >= Q) { y2 -= Q; } try testing.expectEqual(y1, y2); } } // Compute a^s mod p. fn mpow(a: anytype, s: @TypeOf(a), p: @TypeOf(a)) @TypeOf(a) { var ret: @TypeOf(a) = 1; var s2 = s; var a2 = a; while (true) { if (s2 & 1 == 1) { ret = @mod(ret * a2, p); } s2 >>= 1; if (s2 == 0) { break; } a2 = @mod(a2 * a2, p); } return ret; } // Computes zetas table used by ntt and invNTT. fn computeZetas() [128]i16 { @setEvalBranchQuota(10000); var ret: [128]i16 = undefined; for (&ret, 0..) |*r, i| { const t = @as(i16, @intCast(mpow(@as(i32, zeta), @bitReverse(@as(u7, @intCast(i))), Q))); r.* = csubq(feBarrettReduce(feToMont(t))); } return ret; } // An element of our base ring R which are polynomials over ℤ_q // modulo the equation Xᴺ = -1, where q=3329 and N=256. // // This type is also used to store NTT-transformed polynomials, // see Poly.NTT(). // // Coefficients aren't always reduced. See Normalize(). const Poly = struct { cs: [N]i16, const bytes_length = N / 2 * 3; const zero: Poly = .{ .cs = .{0} ** N }; fn add(a: Poly, b: Poly) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = a.cs[i] + b.cs[i]; } return ret; } fn sub(a: Poly, b: Poly) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = a.cs[i] - b.cs[i]; } return ret; } // For testing, generates a random polynomial with for each // coefficient |x| ≤ q. fn randAbsLeqQ(rnd: anytype) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = rnd.random().intRangeAtMost(i16, -Q, Q); } return ret; } // For testing, generates a random normalized polynomial. fn randNormalized(rnd: anytype) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = rnd.random().intRangeLessThan(i16, 0, Q); } return ret; } // Executes a forward "NTT" on p. // // Assumes the coefficients are in absolute value ≤q. The resulting // coefficients are in absolute value ≤7q. If the input is in Montgomery // form, then the result is in Montgomery form and so (by linearity of the NTT) // if the input is in regular form, then the result is also in regular form. fn ntt(a: Poly) Poly { // Note that ℤ_q does not have a primitive 512ᵗʰ root of unity (as 512 // does not divide into q-1) and so we cannot do a regular NTT. ℤ_q // does have a primitive 256ᵗʰ root of unity, the smallest of which // is ζ := 17. // // Recall that our base ring R := ℤ_q[x] / (x²⁵⁶ + 1). The polynomial // x²⁵⁶+1 will not split completely (as its roots would be 512ᵗʰ roots // of unity.) However, it does split almost (using ζ¹²⁸ = -1): // // x²⁵⁶ + 1 = (x²)¹²⁸ - ζ¹²⁸ // = ((x²)⁶⁴ - ζ⁶⁴)((x²)⁶⁴ + ζ⁶⁴) // = ((x²)³² - ζ³²)((x²)³² + ζ³²)((x²)³² - ζ⁹⁶)((x²)³² + ζ⁹⁶) // ⋮ // = (x² - ζ)(x² + ζ)(x² - ζ⁶⁵)(x² + ζ⁶⁵) … (x² + ζ¹²⁷) // // Note that the powers of ζ that appear (from the second line down) are // in binary // // 0100000 1100000 // 0010000 1010000 0110000 1110000 // 0001000 1001000 0101000 1101000 0011000 1011000 0111000 1111000 // … // // That is: brv(2), brv(3), brv(4), …, where brv(x) denotes the 7-bit // bitreversal of x. These powers of ζ are given by the Zetas array. // // The polynomials x² ± ζⁱ are irreducible and coprime, hence by // the Chinese Remainder Theorem we know // // ℤ_q[x]/(x²⁵⁶+1) → ℤ_q[x]/(x²-ζ) x … x ℤ_q[x]/(x²+ζ¹²⁷) // // given by a ↦ ( a mod x²-ζ, …, a mod x²+ζ¹²⁷ ) // is an isomorphism, which is the "NTT". It can be efficiently computed by // // // a ↦ ( a mod (x²)⁶⁴ - ζ⁶⁴, a mod (x²)⁶⁴ + ζ⁶⁴ ) // ↦ ( a mod (x²)³² - ζ³², a mod (x²)³² + ζ³², // a mod (x²)⁹⁶ - ζ⁹⁶, a mod (x²)⁹⁶ + ζ⁹⁶ ) // // et cetera // If N was 8 then this can be pictured in the following diagram: // // https://cnx.org/resources/17ee4dfe517a6adda05377b25a00bf6e6c93c334/File0026.png // // Each cross is a Cooley-Tukey butterfly: it's the map // // (a, b) ↦ (a + ζb, a - ζb) // // for the appropriate power ζ for that column and row group. var p = a; var k: usize = 0; // index into zetas var l = N >> 1; while (l > 1) : (l >>= 1) { // On the nᵗʰ iteration of the l-loop, the absolute value of the // coefficients are bounded by nq. // offset effectively loops over the row groups in this column; it is // the first row in the row group. var offset: usize = 0; while (offset < N - l) : (offset += 2 * l) { k += 1; const z = @as(i32, zetas[k]); // j loops over each butterfly in the row group. for (offset..offset + l) |j| { const t = montReduce(z * @as(i32, p.cs[j + l])); p.cs[j + l] = p.cs[j] - t; p.cs[j] += t; } } } return p; } // Executes an inverse "NTT" on p and multiply by the Montgomery factor R. // // Assumes the coefficients are in absolute value ≤q. The resulting // coefficients are in absolute value ≤q. If the input is in Montgomery // form, then the result is in Montgomery form and so (by linearity) // if the input is in regular form, then the result is also in regular form. fn invNTT(a: Poly) Poly { var k: usize = 127; // index into zetas var r: usize = 0; // index into invNTTReductions var p = a; // We basically do the oppposite of NTT, but postpone dividing by 2 in the // inverse of the Cooley-Tukey butterfly and accumulate that into a big // division by 2⁷ at the end. See the comments in the ntt() function. var l: usize = 2; while (l < N) : (l <<= 1) { var offset: usize = 0; while (offset < N - l) : (offset += 2 * l) { // As we're inverting, we need powers of ζ⁻¹ (instead of ζ). // To be precise, we need ζᵇʳᵛ⁽ᵏ⁾⁻¹²⁸. However, as ζ⁻¹²⁸ = -1, // we can use the existing zetas table instead of // keeping a separate invZetas table as in Dilithium. const minZeta = @as(i32, zetas[k]); k -= 1; for (offset..offset + l) |j| { // Gentleman-Sande butterfly: (a, b) ↦ (a + b, ζ(a-b)) const t = p.cs[j + l] - p.cs[j]; p.cs[j] += p.cs[j + l]; p.cs[j + l] = montReduce(minZeta * @as(i32, t)); // Note that if we had |a| < αq and |b| < βq before the // butterfly, then now we have |a| < (α+β)q and |b| < q. } } // We let the invNTTReductions instruct us which coefficients to // Barrett reduce. while (true) { const i = inv_ntt_reductions[r]; r += 1; if (i < 0) { break; } p.cs[@as(usize, @intCast(i))] = feBarrettReduce(p.cs[@as(usize, @intCast(i))]); } } for (0..N) |j| { // Note 1441 = (128)⁻¹ R². The coefficients are bounded by 9q, so // as 1441 * 9 ≈ 2¹⁴ < 2¹⁵, we're within the required bounds // for montReduce(). p.cs[j] = montReduce(r2_over_128 * @as(i32, p.cs[j])); } return p; } // Normalizes coefficients. // // Ensures each coefficient is in {0, …, q-1}. fn normalize(a: Poly) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = csubq(feBarrettReduce(a.cs[i])); } return ret; } // Put p in Montgomery form. fn toMont(a: Poly) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = feToMont(a.cs[i]); } return ret; } // Barret reduce coefficients. // // Beware, this does not fully normalize coefficients. fn barrettReduce(a: Poly) Poly { var ret: Poly = undefined; for (0..N) |i| { ret.cs[i] = feBarrettReduce(a.cs[i]); } return ret; } fn compressedSize(comptime d: u8) usize { return @divTrunc(N * d, 8); } // Returns packed Compress_q(p, d). // // Assumes p is normalized. fn compress(p: Poly, comptime d: u8) [compressedSize(d)]u8 { @setEvalBranchQuota(10000); const q_over_2: u32 = comptime @divTrunc(Q, 2); // (q-1)/2 const two_d_min_1: u32 = comptime (1 << d) - 1; // 2ᵈ-1 var in_off: usize = 0; var out_off: usize = 0; const batch_size: usize = comptime lcm(@as(i16, d), 8); const in_batch_size: usize = comptime batch_size / d; const out_batch_size: usize = comptime batch_size / 8; const out_length: usize = comptime @divTrunc(N * d, 8); comptime assert(out_length * 8 == d * N); var out = [_]u8{0} ** out_length; while (in_off < N) { // First we compress into in. var in: [in_batch_size]u16 = undefined; inline for (0..in_batch_size) |i| { // Compress_q(x, d) = ⌈(2ᵈ/q)x⌋ mod⁺ 2ᵈ // = ⌊(2ᵈ/q)x+½⌋ mod⁺ 2ᵈ // = ⌊((x << d) + q/2) / q⌋ mod⁺ 2ᵈ // = DIV((x << d) + q/2, q) & ((1<<d) - 1) const t = @as(u24, @intCast(p.cs[in_off + i])) << d; // Division by invariant multiplication, equivalent to DIV(t + q/2, q). // A division may not be a constant-time operation, even with a constant denominator. // Here, side channels would leak information about the shared secret, see https://kyberslash.cr.yp.to // Multiplication, on the other hand, is a constant-time operation on the CPUs we currently support. comptime assert(d <= 11); comptime assert(((20642679 * @as(u64, Q)) >> 36) == 1); const u: u32 = @intCast((@as(u64, t + q_over_2) * 20642679) >> 36); in[i] = @intCast(u & two_d_min_1); } // Now we pack the d-bit integers from `in' into out as bytes. comptime var in_shift: usize = 0; comptime var j: usize = 0; comptime var i: usize = 0; inline while (i < in_batch_size) : (j += 1) { comptime var todo: usize = 8; inline while (todo > 0) { const out_shift = comptime 8 - todo; out[out_off + j] |= @as(u8, @truncate((in[i] >> in_shift) << out_shift)); const done = comptime @min(@min(d, todo), d - in_shift); todo -= done; in_shift += done; if (in_shift == d) { in_shift = 0; i += 1; } } } in_off += in_batch_size; out_off += out_batch_size; } return out; } // Set p to Decompress_q(m, d). fn decompress(comptime d: u8, in: *const [compressedSize(d)]u8) Poly { @setEvalBranchQuota(10000); const inLen = comptime @divTrunc(N * d, 8); comptime assert(inLen * 8 == d * N); var ret: Poly = undefined; var in_off: usize = 0; var out_off: usize = 0; const batch_size: usize = comptime lcm(@as(i16, d), 8); const in_batch_size: usize = comptime batch_size / 8; const out_batch_size: usize = comptime batch_size / d; while (out_off < N) { comptime var in_shift: usize = 0; comptime var j: usize = 0; comptime var i: usize = 0; inline while (i < out_batch_size) : (i += 1) { // First, unpack next coefficient. comptime var todo = d; var out: u16 = 0; inline while (todo > 0) { const out_shift = comptime d - todo; const m = comptime (1 << d) - 1; out |= (@as(u16, in[in_off + j] >> in_shift) << out_shift) & m; const done = comptime @min(@min(8, todo), 8 - in_shift); todo -= done; in_shift += done; if (in_shift == 8) { in_shift = 0; j += 1; } } // Decompress_q(x, d) = ⌈(q/2ᵈ)x⌋ // = ⌊(q/2ᵈ)x+½⌋ // = ⌊(qx + 2ᵈ⁻¹)/2ᵈ⌋ // = (qx + (1<<(d-1))) >> d const qx = @as(u32, out) * @as(u32, Q); ret.cs[out_off + i] = @as(i16, @intCast((qx + (1 << (d - 1))) >> d)); } in_off += in_batch_size; out_off += out_batch_size; } return ret; } // Returns the "pointwise" multiplication a o b. // // That is: invNTT(a o b) = invNTT(a) * invNTT(b). Assumes a and b are in // Montgomery form. Products between coefficients of a and b must be strictly // bounded in absolute value by 2¹⁵q. a o b will be in Montgomery form and // bounded in absolute value by 2q. fn mulHat(a: Poly, b: Poly) Poly { // Recall from the discussion in ntt(), that a transformed polynomial is // an element of ℤ_q[x]/(x²-ζ) x … x ℤ_q[x]/(x²+ζ¹²⁷); // that is: 128 degree-one polynomials instead of simply 256 elements // from ℤ_q as in the regular NTT. So instead of pointwise multiplication, // we multiply the 128 pairs of degree-one polynomials modulo the // right equation: // // (a₁ + a₂x)(b₁ + b₂x) = a₁b₁ + a₂b₂ζ' + (a₁b₂ + a₂b₁)x, // // where ζ' is the appropriate power of ζ. var p: Poly = undefined; var k: usize = 64; var i: usize = 0; while (i < N) : (i += 4) { const z = @as(i32, zetas[k]); k += 1; const a1b1 = montReduce(@as(i32, a.cs[i + 1]) * @as(i32, b.cs[i + 1])); const a0b0 = montReduce(@as(i32, a.cs[i]) * @as(i32, b.cs[i])); const a1b0 = montReduce(@as(i32, a.cs[i + 1]) * @as(i32, b.cs[i])); const a0b1 = montReduce(@as(i32, a.cs[i]) * @as(i32, b.cs[i + 1])); p.cs[i] = montReduce(a1b1 * z) + a0b0; p.cs[i + 1] = a0b1 + a1b0; const a3b3 = montReduce(@as(i32, a.cs[i + 3]) * @as(i32, b.cs[i + 3])); const a2b2 = montReduce(@as(i32, a.cs[i + 2]) * @as(i32, b.cs[i + 2])); const a3b2 = montReduce(@as(i32, a.cs[i + 3]) * @as(i32, b.cs[i + 2])); const a2b3 = montReduce(@as(i32, a.cs[i + 2]) * @as(i32, b.cs[i + 3])); p.cs[i + 2] = a2b2 - montReduce(a3b3 * z); p.cs[i + 3] = a2b3 + a3b2; } return p; } // Sample p from a centered binomial distribution with n=2η and p=½ - viz: // coefficients are in {-η, …, η} with probabilities // // {ncr(0, 2η)/2^2η, ncr(1, 2η)/2^2η, …, ncr(2η,2η)/2^2η} fn noise(comptime eta: u8, nonce: u8, seed: *const [32]u8) Poly { var h = sha3.Shake256.init(.{}); const suffix: [1]u8 = .{nonce}; h.update(seed); h.update(&suffix); // The distribution at hand is exactly the same as that // of (a₁ + a₂ + … + a_η) - (b₁ + … + b_η) where a_i,b_i~U(1). // Thus we need 2η bits per coefficient. const buf_len = comptime 2 * eta * N / 8; var buf: [buf_len]u8 = undefined; h.squeeze(&buf); // buf is interpreted as a₁…a_ηb₁…b_ηa₁…a_ηb₁…b_η…. We process // multiple coefficients in one batch. const T = switch (builtin.target.cpu.arch) { .x86_64, .x86 => u32, // Generates better code on Intel CPUs else => u64, // u128 might be faster on some other CPUs. }; comptime var batch_count: usize = undefined; comptime var batch_bytes: usize = undefined; comptime var mask: T = 0; comptime { batch_count = @bitSizeOf(T) / @as(usize, 2 * eta); while (@rem(N, batch_count) != 0 and batch_count > 0) : (batch_count -= 1) {} assert(batch_count > 0); assert(@rem(2 * eta * batch_count, 8) == 0); batch_bytes = 2 * eta * batch_count / 8; for (0..2 * eta * batch_count) |_| { mask <<= eta; mask |= 1; } } var ret: Poly = undefined; for (0..comptime N / batch_count) |i| { // Read coefficients into t. In the case of η=3, // we have t = a₁ + 2a₂ + 4a₃ + 8b₁ + 16b₂ + … var t: T = 0; inline for (0..batch_bytes) |j| { t |= @as(T, buf[batch_bytes * i + j]) << (8 * j); } // Accumelate `a's and `b's together by masking them out, shifting // and adding. For η=3, we have d = a₁ + a₂ + a₃ + 8(b₁ + b₂ + b₃) + … var d: T = 0; inline for (0..eta) |j| { d += (t >> j) & mask; } // Extract each a and b separately and set coefficient in polynomial. inline for (0..batch_count) |j| { const mask2 = comptime (1 << eta) - 1; const a = @as(i16, @intCast((d >> (comptime (2 * j * eta))) & mask2)); const b = @as(i16, @intCast((d >> (comptime ((2 * j + 1) * eta))) & mask2)); ret.cs[batch_count * i + j] = a - b; } } return ret; } // Sample p uniformly from the given seed and x and y coordinates. fn uniform(seed: [32]u8, x: u8, y: u8) Poly { var h = sha3.Shake128.init(.{}); const suffix: [2]u8 = .{ x, y }; h.update(&seed); h.update(&suffix); const buf_len = sha3.Shake128.block_length; // rate SHAKE-128 var buf: [buf_len]u8 = undefined; var ret: Poly = undefined; var i: usize = 0; // index into ret.cs outer: while (true) { h.squeeze(&buf); var j: usize = 0; // index into buf while (j < buf_len) : (j += 3) { const b0 = @as(u16, buf[j]); const b1 = @as(u16, buf[j + 1]); const b2 = @as(u16, buf[j + 2]); const ts: [2]u16 = .{ b0 | ((b1 & 0xf) << 8), (b1 >> 4) | (b2 << 4), }; inline for (ts) |t| { if (t < Q) { ret.cs[i] = @as(i16, @intCast(t)); i += 1; if (i == N) { break :outer; } } } } } return ret; } // Packs p. // // Assumes p is normalized (and not just Barrett reduced). fn toBytes(p: Poly) [bytes_length]u8 { var ret: [bytes_length]u8 = undefined; for (0..comptime N / 2) |i| { const t0 = @as(u16, @intCast(p.cs[2 * i])); const t1 = @as(u16, @intCast(p.cs[2 * i + 1])); ret[3 * i] = @as(u8, @truncate(t0)); ret[3 * i + 1] = @as(u8, @truncate((t0 >> 8) | (t1 << 4))); ret[3 * i + 2] = @as(u8, @truncate(t1 >> 4)); } return ret; } // Unpacks a Poly from buf. // // p will not be normalized; instead 0 ≤ p[i] < 4096. fn fromBytes(buf: *const [bytes_length]u8) Poly { var ret: Poly = undefined; for (0..comptime N / 2) |i| { const b0 = @as(i16, buf[3 * i]); const b1 = @as(i16, buf[3 * i + 1]); const b2 = @as(i16, buf[3 * i + 2]); ret.cs[2 * i] = b0 | ((b1 & 0xf) << 8); ret.cs[2 * i + 1] = (b1 >> 4) | b2 << 4; } return ret; } }; // A vector of K polynomials. fn Vec(comptime K: u8) type { return struct { ps: [K]Poly, const Self = @This(); const bytes_length = K * Poly.bytes_length; fn compressedSize(comptime d: u8) usize { return Poly.compressedSize(d) * K; } fn ntt(a: Self) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = a.ps[i].ntt(); } return ret; } fn invNTT(a: Self) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = a.ps[i].invNTT(); } return ret; } fn normalize(a: Self) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = a.ps[i].normalize(); } return ret; } fn barrettReduce(a: Self) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = a.ps[i].barrettReduce(); } return ret; } fn add(a: Self, b: Self) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = a.ps[i].add(b.ps[i]); } return ret; } fn sub(a: Self, b: Self) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = a.ps[i].sub(b.ps[i]); } return ret; } // Samples v[i] from centered binomial distribution with the given η, // seed and nonce+i. fn noise(comptime eta: u8, nonce: u8, seed: *const [32]u8) Self { var ret: Self = undefined; for (0..K) |i| { ret.ps[i] = Poly.noise(eta, nonce + @as(u8, @intCast(i)), seed); } return ret; } // Sets p to the inner product of a and b using "pointwise" multiplication. // // See MulHat() and NTT() for a description of the multiplication. // Assumes a and b are in Montgomery form. p will be in Montgomery form, // and its coefficients will be bounded in absolute value by 2kq. // If a and b are not in Montgomery form, then the action is the same // as "pointwise" multiplication followed by multiplying by R⁻¹, the inverse // of the Montgomery factor. fn dotHat(a: Self, b: Self) Poly { var ret: Poly = Poly.zero; for (0..K) |i| { ret = ret.add(a.ps[i].mulHat(b.ps[i])); } return ret; } fn compress(v: Self, comptime d: u8) [compressedSize(d)]u8 { const cs = comptime Poly.compressedSize(d); var ret: [compressedSize(d)]u8 = undefined; inline for (0..K) |i| { ret[i * cs .. (i + 1) * cs].* = v.ps[i].compress(d); } return ret; } fn decompress(comptime d: u8, buf: *const [compressedSize(d)]u8) Self { const cs = comptime Poly.compressedSize(d); var ret: Self = undefined; inline for (0..K) |i| { ret.ps[i] = Poly.decompress(d, buf[i * cs .. (i + 1) * cs]); } return ret; } /// Serializes the key into a byte array. fn toBytes(v: Self) [bytes_length]u8 { var ret: [bytes_length]u8 = undefined; inline for (0..K) |i| { ret[i * Poly.bytes_length .. (i + 1) * Poly.bytes_length].* = v.ps[i].toBytes(); } return ret; } /// Deserializes the key from a byte array. fn fromBytes(buf: *const [bytes_length]u8) Self { var ret: Self = undefined; inline for (0..K) |i| { ret.ps[i] = Poly.fromBytes( buf[i * Poly.bytes_length .. (i + 1) * Poly.bytes_length], ); } return ret; } }; } // A matrix of K vectors fn Mat(comptime K: u8) type { return struct { const Self = @This(); vs: [K]Vec(K), fn uniform(seed: [32]u8, comptime transposed: bool) Self { var ret: Self = undefined; var i: u8 = 0; while (i < K) : (i += 1) { var j: u8 = 0; while (j < K) : (j += 1) { ret.vs[i].ps[j] = Poly.uniform( seed, if (transposed) i else j, if (transposed) j else i, ); } } return ret; } // Returns transpose of A fn transpose(m: Self) Self { var ret: Self = undefined; for (0..K) |i| { for (0..K) |j| { ret.vs[i].ps[j] = m.vs[j].ps[i]; } } return ret; } }; } // Returns `true` if a ≠ b. fn ctneq(comptime len: usize, a: [len]u8, b: [len]u8) u1 { return 1 - @intFromBool(crypto.utils.timingSafeEql([len]u8, a, b)); } // Copy src into dst given b = 1. fn cmov(comptime len: usize, dst: *[len]u8, src: [len]u8, b: u1) void { const mask = @as(u8, 0) -% b; for (0..len) |i| { dst[i] ^= mask & (dst[i] ^ src[i]); } } test "MulHat" { var rnd = RndGen.init(0); for (0..100) |_| { const a = Poly.randAbsLeqQ(&rnd); const b = Poly.randAbsLeqQ(&rnd); const p2 = a.ntt().mulHat(b.ntt()).barrettReduce().invNTT().normalize(); var p: Poly = undefined; @memset(&p.cs, 0); for (0..N) |i| { for (0..N) |j| { var v = montReduce(@as(i32, a.cs[i]) * @as(i32, b.cs[j])); var k = i + j; if (k >= N) { // Recall Xᴺ = -1. k -= N; v = -v; } p.cs[k] = feBarrettReduce(v + p.cs[k]); } } p = p.toMont().normalize(); try testing.expectEqual(p, p2); } } test "NTT" { var rnd = RndGen.init(0); for (0..1000) |_| { var p = Poly.randAbsLeqQ(&rnd); const q = p.toMont().normalize(); p = p.ntt(); for (0..N) |i| { try testing.expect(p.cs[i] <= 7 * Q and -7 * Q <= p.cs[i]); } p = p.normalize().invNTT(); for (0..N) |i| { try testing.expect(p.cs[i] <= Q and -Q <= p.cs[i]); } p = p.normalize(); try testing.expectEqual(p, q); } } test "Compression" { var rnd = RndGen.init(0); inline for (.{ 1, 4, 5, 10, 11 }) |d| { for (0..1000) |_| { const p = Poly.randNormalized(&rnd); const pp = p.compress(d); const pq = Poly.decompress(d, &pp).compress(d); try testing.expectEqual(pp, pq); } } } test "noise" { var seed: [32]u8 = undefined; for (&seed, 0..) |*s, i| { s.* = @as(u8, @intCast(i)); } try testing.expectEqual(Poly.noise(3, 37, &seed).cs, .{ 0, 0, 1, -1, 0, 2, 0, -1, -1, 3, 0, 1, -2, -2, 0, 1, -2, 1, 0, -2, 3, 0, 0, 0, 1, 3, 1, 1, 2, 1, -1, -1, -1, 0, 1, 0, 1, 0, 2, 0, 1, -2, 0, -1, -1, -2, 1, -1, -1, 2, -1, 1, 1, 2, -3, -1, -1, 0, 0, 0, 0, 1, -1, -2, -2, 0, -2, 0, 0, 0, 1, 0, -1, -1, 1, -2, 2, 0, 0, 2, -2, 0, 1, 0, 1, 1, 1, 0, 1, -2, -1, -2, -1, 1, 0, 0, 0, 0, 0, 1, 0, -1, -1, 0, -1, 1, 0, 1, 0, -1, -1, 0, -2, 2, 0, -2, 1, -1, 0, 1, -1, -1, 2, 1, 0, 0, -2, -1, 2, 0, 0, 0, -1, -1, 3, 1, 0, 1, 0, 1, 0, 2, 1, 0, 0, 1, 0, 1, 0, 0, -1, -1, -1, 0, 1, 3, 1, 0, 1, 0, 1, -1, -1, -1, -1, 0, 0, -2, -1, -1, 2, 0, 1, 0, 1, 0, 2, -2, 0, 1, 1, -3, -1, -2, -1, 0, 1, 0, 1, -2, 2, 2, 1, 1, 0, -1, 0, -1, -1, 1, 0, -1, 2, 1, -1, 1, 2, -2, 1, 2, 0, 1, 2, 1, 0, 0, 2, 1, 2, 1, 0, 2, 1, 0, 0, -1, -1, 1, -1, 0, 1, -1, 2, 2, 0, 0, -1, 1, 1, 1, 1, 0, 0, -2, 0, -1, 1, 2, 0, 0, 1, 1, -1, 1, 0, 1, }); try testing.expectEqual(Poly.noise(2, 37, &seed).cs, .{ 1, 0, 1, -1, -1, -2, -1, -1, 2, 0, -1, 0, 0, -1, 1, 1, -1, 1, 0, 2, -2, 0, 1, 2, 0, 0, -1, 1, 0, -1, 1, -1, 1, 2, 1, 1, 0, -1, 1, -1, -2, -1, 1, -1, -1, -1, 2, -1, -1, 0, 0, 1, 1, -1, 1, 1, 1, 1, -1, -2, 0, 1, 0, 0, 2, 1, -1, 2, 0, 0, 1, 1, 0, -1, 0, 0, -1, -1, 2, 0, 1, -1, 2, -1, -1, -1, -1, 0, -2, 0, 2, 1, 0, 0, 0, -1, 0, 0, 0, -1, -1, 0, -1, -1, 0, -1, 0, 0, -2, 1, 1, 0, 1, 0, 1, 0, 1, 1, -1, 2, 0, 1, -1, 1, 2, 0, 0, 0, 0, -1, -1, -1, 0, 1, 0, -1, 2, 0, 0, 1, 1, 1, 0, 1, -1, 1, 2, 1, 0, 2, -1, 1, -1, -2, -1, -2, -1, 1, 0, -2, -2, -1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 2, 2, 0, 1, 0, -1, -1, 0, 2, 0, 0, -2, 1, 0, 2, 1, -1, -2, 0, 0, -1, 1, 1, 0, 0, 2, 0, 1, 1, -2, 1, -2, 1, 1, 0, 2, 0, -1, 0, -1, 0, 1, 2, 0, 1, 0, -2, 1, -2, -2, 1, -1, 0, -1, 1, 1, 0, 0, 0, 1, 0, -1, 1, 1, 0, 0, 0, 0, 1, 0, 1, -1, 0, 1, -1, -1, 2, 0, 0, 1, -1, 0, 1, -1, 0, }); } test "uniform sampling" { var seed: [32]u8 = undefined; for (&seed, 0..) |*s, i| { s.* = @as(u8, @intCast(i)); } try testing.expectEqual(Poly.uniform(seed, 1, 0).cs, .{ 797, 993, 161, 6, 2608, 2385, 2096, 2661, 1676, 247, 2440, 342, 634, 194, 1570, 2848, 986, 684, 3148, 3208, 2018, 351, 2288, 612, 1394, 170, 1521, 3119, 58, 596, 2093, 1549, 409, 2156, 1934, 1730, 1324, 388, 446, 418, 1719, 2202, 1812, 98, 1019, 2369, 214, 2699, 28, 1523, 2824, 273, 402, 2899, 246, 210, 1288, 863, 2708, 177, 3076, 349, 44, 949, 854, 1371, 957, 292, 2502, 1617, 1501, 254, 7, 1761, 2581, 2206, 2655, 1211, 629, 1274, 2358, 816, 2766, 2115, 2985, 1006, 2433, 856, 2596, 3192, 1, 1378, 2345, 707, 1891, 1669, 536, 1221, 710, 2511, 120, 1176, 322, 1897, 2309, 595, 2950, 1171, 801, 1848, 695, 2912, 1396, 1931, 1775, 2904, 893, 2507, 1810, 2873, 253, 1529, 1047, 2615, 1687, 831, 1414, 965, 3169, 1887, 753, 3246, 1937, 115, 2953, 586, 545, 1621, 1667, 3187, 1654, 1988, 1857, 512, 1239, 1219, 898, 3106, 391, 1331, 2228, 3169, 586, 2412, 845, 768, 156, 662, 478, 1693, 2632, 573, 2434, 1671, 173, 969, 364, 1663, 2701, 2169, 813, 1000, 1471, 720, 2431, 2530, 3161, 733, 1691, 527, 2634, 335, 26, 2377, 1707, 767, 3020, 950, 502, 426, 1138, 3208, 2607, 2389, 44, 1358, 1392, 2334, 875, 2097, 173, 1697, 2578, 942, 1817, 974, 1165, 2853, 1958, 2973, 3282, 271, 1236, 1677, 2230, 673, 1554, 96, 242, 1729, 2518, 1884, 2272, 71, 1382, 924, 1807, 1610, 456, 1148, 2479, 2152, 238, 2208, 2329, 713, 1175, 1196, 757, 1078, 3190, 3169, 708, 3117, 154, 1751, 3225, 1364, 154, 23, 2842, 1105, 1419, 79, 5, 2013, }); } test "Polynomial packing" { var rnd = RndGen.init(0); for (0..1000) |_| { const p = Poly.randNormalized(&rnd); try testing.expectEqual(Poly.fromBytes(&p.toBytes()), p); } } test "Test inner PKE" { var seed: [32]u8 = undefined; var pt: [32]u8 = undefined; for (&seed, &pt, 0..) |*s, *p, i| { s.* = @as(u8, @intCast(i)); p.* = @as(u8, @intCast(i + 32)); } inline for (modes) |mode| { for (0..100) |i| { var pk: mode.InnerPk = undefined; var sk: mode.InnerSk = undefined; seed[0] = @as(u8, @intCast(i)); mode.innerKeyFromSeed(seed, &pk, &sk); for (0..10) |j| { seed[1] = @as(u8, @intCast(j)); try testing.expectEqual(sk.decrypt(&pk.encrypt(&pt, &seed)), pt); } } } } test "Test happy flow" { var seed: [64]u8 = undefined; for (&seed, 0..) |*s, i| { s.* = @as(u8, @intCast(i)); } inline for (modes) |mode| { for (0..100) |i| { seed[0] = @as(u8, @intCast(i)); const kp = try mode.KeyPair.create(seed); const sk = try mode.SecretKey.fromBytes(&kp.secret_key.toBytes()); try testing.expectEqual(sk, kp.secret_key); const pk = try mode.PublicKey.fromBytes(&kp.public_key.toBytes()); try testing.expectEqual(pk, kp.public_key); for (0..10) |j| { seed[1] = @as(u8, @intCast(j)); const e = pk.encaps(seed[0..32].*); try testing.expectEqual(e.shared_secret, try sk.decaps(&e.ciphertext)); } } } } // Code to test NIST Known Answer Tests (KAT), see PQCgenKAT.c. const sha2 = crypto.hash.sha2; test "NIST KAT test" { inline for (.{ .{ Kyber512, "e9c2bd37133fcb40772f81559f14b1f58dccd1c816701be9ba6214d43baf4547" }, .{ Kyber1024, "89248f2f33f7f4f7051729111f3049c409a933ec904aedadf035f30fa5646cd5" }, .{ Kyber768, "a1e122cad3c24bc51622e4c242d8b8acbcd3f618fee4220400605ca8f9ea02c2" }, }) |modeHash| { const mode = modeHash[0]; var seed: [48]u8 = undefined; for (&seed, 0..) |*s, i| { s.* = @as(u8, @intCast(i)); } var f = sha2.Sha256.init(.{}); const fw = f.writer(); var g = NistDRBG.init(seed); try std.fmt.format(fw, "# {s}\n\n", .{mode.name}); for (0..100) |i| { g.fill(&seed); try std.fmt.format(fw, "count = {}\n", .{i}); try std.fmt.format(fw, "seed = {s}\n", .{std.fmt.fmtSliceHexUpper(&seed)}); var g2 = NistDRBG.init(seed); // This is not equivalent to g2.fill(kseed[:]). As the reference // implementation calls randombytes twice generating the keypair, // we have to do that as well. var kseed: [64]u8 = undefined; var eseed: [32]u8 = undefined; g2.fill(kseed[0..32]); g2.fill(kseed[32..64]); g2.fill(&eseed); const kp = try mode.KeyPair.create(kseed); const e = kp.public_key.encaps(eseed); const ss2 = try kp.secret_key.decaps(&e.ciphertext); try testing.expectEqual(ss2, e.shared_secret); try std.fmt.format(fw, "pk = {s}\n", .{std.fmt.fmtSliceHexUpper(&kp.public_key.toBytes())}); try std.fmt.format(fw, "sk = {s}\n", .{std.fmt.fmtSliceHexUpper(&kp.secret_key.toBytes())}); try std.fmt.format(fw, "ct = {s}\n", .{std.fmt.fmtSliceHexUpper(&e.ciphertext)}); try std.fmt.format(fw, "ss = {s}\n\n", .{std.fmt.fmtSliceHexUpper(&e.shared_secret)}); } var out: [32]u8 = undefined; f.final(&out); var outHex: [64]u8 = undefined; _ = try std.fmt.bufPrint(&outHex, "{s}", .{std.fmt.fmtSliceHexLower(&out)}); try testing.expectEqual(outHex, modeHash[1].*); } } const NistDRBG = struct { key: [32]u8, v: [16]u8, fn incV(g: *NistDRBG) void { var j: usize = 15; while (j >= 0) : (j -= 1) { if (g.v[j] == 255) { g.v[j] = 0; } else { g.v[j] += 1; break; } } } // AES256_CTR_DRBG_Update(pd, &g.key, &g.v). fn update(g: *NistDRBG, pd: ?[48]u8) void { var buf: [48]u8 = undefined; const ctx = crypto.core.aes.Aes256.initEnc(g.key); var i: usize = 0; while (i < 3) : (i += 1) { g.incV(); var block: [16]u8 = undefined; ctx.encrypt(&block, &g.v); buf[i * 16 ..][0..16].* = block; } if (pd) |p| { for (&buf, p) |*b, x| { b.* ^= x; } } g.key = buf[0..32].*; g.v = buf[32..48].*; } // randombytes. fn fill(g: *NistDRBG, out: []u8) void { var block: [16]u8 = undefined; var dst = out; const ctx = crypto.core.aes.Aes256.initEnc(g.key); while (dst.len > 0) { g.incV(); ctx.encrypt(&block, &g.v); if (dst.len < 16) { @memcpy(dst, block[0..dst.len]); break; } dst[0..block.len].* = block; dst = dst[16..dst.len]; } g.update(null); } fn init(seed: [48]u8) NistDRBG { var ret: NistDRBG = .{ .key = .{0} ** 32, .v = .{0} ** 16 }; ret.update(seed); return ret; } };
https://raw.githubusercontent.com/2lambda123/ziglang-zig/d7563a7753393d7f0d1af445276a64b8a55cb857/lib/std/crypto/kyber_d00.zig
// // Now that we've seen how methods work, let's see if we can help // our elephants out a bit more with some Elephant methods. // const std = @import("std"); const Elephant = struct { letter: u8, tail: ?*Elephant = null, visited: bool = false, // New Elephant methods! pub fn getTail(self: *Elephant) *Elephant { return self.tail.?; // Remember, this means "orelse unreachable" } pub fn hasTail(self: *Elephant) bool { return (self.tail != null); } pub fn visit(self: *Elephant) void { self.visited = true; } pub fn print(self: *Elephant) void { // Prints elephant letter and [v]isited var v: u8 = if (self.visited) 'v' else ' '; std.debug.print("{u}{u} ", .{ self.letter, v }); } }; pub fn main() void { var elephantA = Elephant{ .letter = 'A' }; var elephantB = Elephant{ .letter = 'B' }; var elephantC = Elephant{ .letter = 'C' }; // This links the elephants so that each tail "points" to the next. elephantA.tail = &elephantB; elephantB.tail = &elephantC; visitElephants(&elephantA); std.debug.print("\n", .{}); } // This function visits all elephants once, starting with the // first elephant and following the tails to the next elephant. fn visitElephants(first_elephant: *Elephant) void { var e = first_elephant; while (true) { e.print(); e.visit(); // This gets the next elephant or stops: // which method do we want here? e = if (e.hasTail()) e.tail.? else break; } } // Zig's enums can also have methods! This comment originally asked // if anyone could find instances of enum methods in the wild. The // first five pull requests were accepted and here they are: // // 1) drforester - I found one in the Zig source: // https://github.com/ziglang/zig/blob/041212a41cfaf029dc3eb9740467b721c76f406c/src/Compilation.zig#L2495 // // 2) bbuccianti - I found one! // https://github.com/ziglang/zig/blob/6787f163eb6db2b8b89c2ea6cb51d63606487e12/lib/std/debug.zig#L477 // // 3) GoldsteinE - Found many, here's one // https://github.com/ziglang/zig/blob/ce14bc7176f9e441064ffdde2d85e35fd78977f2/lib/std/target.zig#L65 // // 4) SpencerCDixon - Love this language so far :-) // https://github.com/ziglang/zig/blob/a502c160cd51ce3de80b3be945245b7a91967a85/src/zir.zig#L530 // // 5) tomkun - here's another enum method // https://github.com/ziglang/zig/blob/4ca1f4ec2e3ae1a08295bc6ed03c235cb7700ab9/src/codegen/aarch64.zig#L24
https://raw.githubusercontent.com/yuanw/didactic-fortnight/55f80ebd80f431da28f821b24fb5d2e40971e99c/zigling/exercises/048_methods2.zig
const std = @import("std"); const Self = @This(); const Token = @import("../../token/token.zig"); token: Token = undefined, value: []const u8 = undefined, pub fn format(self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { _ = fmt; _ = options; try std.fmt.format(writer, "{s}", .{self.token.lexeme}); }
https://raw.githubusercontent.com/adia-dev/tingle-lang/149ad29dab299b16bffd18a4fbc6d574235018b6/src/ast/expressions/identifier.zig
// // Being able to group values together lets us turn this: // // point1_x = 3; // point1_y = 16; // point1_z = 27; // point2_x = 7; // point2_y = 13; // point2_z = 34; // // into this: // // point1 = Point{ .x=3, .y=16, .z=27 }; // point2 = Point{ .x=7, .y=13, .z=34 }; // // The Point above is an example of a "struct" (short for "structure"). // Here's how that struct type could have been defined: // // const Point = struct{ x: u32, y: u32, z: u32 }; // // Let's store something fun with a struct: a roleplaying character! // const std = @import("std"); // We'll use an enum to specify the character class. const Class = enum { wizard, thief, bard, warrior, }; // Please add a new property to this struct called "health" and make // it a u8 integer type. const Character = struct { class: Class, gold: u32, experience: u32, health: u8, }; pub fn main() void { // Please initialize Glorp with 100 health. var glorp_the_wise = Character{ .class = Class.wizard, .gold = 20, .experience = 10, .health = 100, }; // Glorp gains some gold. glorp_the_wise.gold += 5; // Ouch! Glorp takes a punch! glorp_the_wise.health -= 10; std.debug.print("Your wizard has {} health and {} gold.\n", .{ glorp_the_wise.health, glorp_the_wise.gold, }); }
https://raw.githubusercontent.com/drewr/ziglings/404fdfe27fd148b55ed1fa107e7cd3ed79b2d668/exercises/037_structs.zig
const std = @import("std"); const RaylibVector2 = @import("root").raylib.Vector2; fn VecFunctions( comptime VecT: type, comptime N: usize, comptime NumT: type, ) type { return struct { pub inline fn fromVector(vector: @Vector(N, NumT)) VecT { return VecT{ .v = vector }; } pub inline fn clone(self: VecT) VecT { return VecT{ .v = self.v }; } pub inline fn add(a: VecT, b: VecT) VecT { return VecT{ .v = a.v + b.v }; } pub inline fn addInPlace(a: *VecT, b: VecT) *VecT { a.v += b.v; return a; } pub inline fn addScalar(a: VecT, b: NumT) VecT { return VecT{ .v = a.v + @splat(2, b) }; } pub inline fn sub(a: VecT, b: VecT) VecT { return VecT{ .v = a.v - b.v }; } pub inline fn subInPlace(a: *VecT, b: VecT) *VecT { a.v -= b.v; return a; } pub inline fn subScalar(a: VecT, b: NumT) VecT { return VecT{ .v = a.v - @splat(2, b) }; } pub inline fn mul(a: VecT, b: VecT) VecT { return VecT{ .v = a.v * b.v }; } pub inline fn mulInPlace(a: *VecT, b: VecT) *VecT { a.v *= b.v; return a; } pub inline fn mulScalar(self: VecT, k: NumT) VecT { return VecT{ .v = self.v * @splat(2, k) }; } pub inline fn mulScalarInPlace(self: *VecT, k: NumT) *VecT { self.v *= @splat(2, k); return self; } pub inline fn div(a: VecT, b: VecT) VecT { return VecT{ .v = a.v / b.v }; } pub inline fn divInPlace(a: *VecT, b: VecT) *VecT { a.v /= b.v; return a; } pub inline fn divScalar(a: VecT, b: NumT) VecT { return VecT{ .v = a.v / @splat(2, b) }; } pub inline fn dot(a: VecT, b: VecT) NumT { return @reduce(.Add, a.v * b.v); } pub inline fn sum(self: *VecT) NumT { return @reduce(.Add, self.v); } pub inline fn floor(self: VecT) VecT { return VecT{ .v = @floor(self.v) }; } pub inline fn floorInPlace(self: *VecT) *VecT { self.v = @floor(self.v); return self; } pub inline fn ceil(self: VecT) VecT { return VecT{ .v = @ceil(self.v) }; } pub inline fn ceilInPlace(self: *VecT) *VecT { self.v = @ceil(self.v); return self; } pub inline fn mag(self: VecT) NumT { return @sqrt(@reduce(.Add, self.v * self.v)); } pub inline fn fill(value: NumT) VecT { return VecT{ .v = @splat(N, value) }; } pub inline fn distanceBetween(a: VecT, b: VecT) NumT { const diff = a.v - b.v; return @sqrt(@reduce(.Add, diff * diff)); } pub fn debugPrint(self: VecT) void { std.debug.print("{s}(", .{@typeName(VecT)}); for (0..N) |i| { const v = self.v[i]; std.debug.print("{d}", .{v}); if (i < N - 1) std.debug.print(", ", .{}); } std.debug.print(")\n", .{}); } }; } pub fn Vec2(comptime T: type) type { return struct { v: @Vector(2, T), const Self = @This(); pub usingnamespace VecFunctions(Self, 2, T); pub const zero = Self.init(0, 0); pub const one = Self.init(1, 1); pub const X = Self.init(1, 0); pub const Y = Self.init(0, 1); pub inline fn equals(self: Self, other: Self) bool { return self.v[0] == other.v[0] and self.v[1] == other.v[1]; } pub inline fn init(x: T, y: T) Self { return Self{ .v = .{ x, y } }; } pub inline fn max(self: Self) T { return @max(self.v[0], self.v[1]); } pub inline fn map( self: Self, comptime TP: type, tx: fn (value: T, index: usize) TP, ) Vec2(TP) { return Vec2(TP).init(tx(self.v[0], 0), tx(self.v[1], 1)); } pub inline fn intToFloat(self: Self, comptime IntT: type) Vec2(IntT) { const map_fn = (struct { pub fn f(value: T, index: usize) IntT { _ = index; return @intToFloat(IntT, value); } }).f; return self.map(IntT, map_fn); } pub inline fn floatToInt(self: Self, comptime IntT: type) Vec2(IntT) { const map_fn = (struct { pub fn f(value: T, index: usize) IntT { _ = index; return @floatToInt(IntT, value); } }).f; return self.map(IntT, map_fn); } pub inline fn intCast(self: Self, comptime IntT: type) Vec2(IntT) { const map_fn = (struct { pub fn f(value: T, index: usize) IntT { _ = index; return @intCast(IntT, value); } }).f; return self.map(IntT, map_fn); } pub inline fn toRaylibVector2(self: Self) RaylibVector2 { return RaylibVector2{ .x = self.v[0], .y = self.v[1] }; } pub inline fn fromRaylibVector2(v: RaylibVector2) Self { return Self.init(v.x, v.y); } }; } pub fn Vec3(comptime T: type) type { return struct { v: @Vector(3, T), const Self = @This(); pub usingnamespace VecFunctions(Self, 3, T); pub const zero = Self.init(0, 0); pub inline fn init(x: T, y: T, z: T) Self { return Self{ .v = .{ x, y, z } }; } }; }
https://raw.githubusercontent.com/kyle-marshall/zigmo/be37d46077d1280035bb6f22b161ca7de3d2d080/src/math/vec.zig
const std = @import("std"); const print = std.debug.print; const math = std.math; const Complex = std.math.Complex; const ElementType = @import("./helpers.zig").ElementType; const pi = math.pi; pub fn gausswin(x: anytype, alpha: anytype) void { const T = @TypeOf(x); comptime var T_elem = ElementType(T); if ((@TypeOf(alpha) != T_elem) and (@TypeOf(alpha) != comptime_float)) { @compileError("alpha type disagreement"); } var N: usize = x.len; var Lf: T_elem = @as(T_elem, @floatFromInt(N - 1)); var tmp: T_elem = undefined; var n: T_elem = undefined; var i: usize = 0; while (i < N) : (i += 1) { n = @as(T_elem, @floatFromInt(i)) - 0.5 * Lf; tmp = alpha * n / (Lf / 2); x[i] = @exp(-0.5 * tmp * tmp); } } const eps = 1.0e-5; const n_even = 6; const n_odd = 7; test "\t gausswin window \t even length array\n" { inline for (.{ f32, f64 }) |T| { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); var x = try allocator.alloc(T, n_even); gausswin(x, 2.5); try std.testing.expectApproxEqAbs(@as(T, 0.0439369336), x[0], eps); try std.testing.expectApproxEqAbs(@as(T, 0.3246524673), x[1], eps); try std.testing.expectApproxEqAbs(@as(T, 0.8824969025), x[2], eps); try std.testing.expectApproxEqAbs(@as(T, 0.8824969025), x[3], eps); try std.testing.expectApproxEqAbs(@as(T, 0.3246524673), x[4], eps); try std.testing.expectApproxEqAbs(@as(T, 0.0439369336), x[5], eps); } } test "\t gausswin window \t odd length array\n" { inline for (.{ f32, f64 }) |T| { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); var x = try allocator.alloc(T, n_odd); gausswin(x, 2.5); try std.testing.expectApproxEqAbs(@as(T, 0.043936933), x[0], eps); try std.testing.expectApproxEqAbs(@as(T, 0.249352208), x[1], eps); try std.testing.expectApproxEqAbs(@as(T, 0.706648277), x[2], eps); try std.testing.expectApproxEqAbs(@as(T, 1.0), x[3], eps); try std.testing.expectApproxEqAbs(@as(T, 0.706648277), x[4], eps); try std.testing.expectApproxEqAbs(@as(T, 0.249352208), x[5], eps); try std.testing.expectApproxEqAbs(@as(T, 0.043936933), x[6], eps); } }
https://raw.githubusercontent.com/BlueAlmost/zsignal/70547dbf26bfac8677890a94a2d6dfef123424fb/src/gausswin.zig
const std = @import("std"); const args = @import("args"); const init = @import("commands/init.zig"); const update = @import("commands/update.zig"); const generate = @import("commands/generate.zig"); const server = @import("commands/server.zig"); const routes = @import("commands/routes.zig"); const bundle = @import("commands/bundle.zig"); const tests = @import("commands/tests.zig"); const Options = struct { help: bool = false, pub const shorthands = .{ .h = "help", }; pub const meta = .{ .usage_summary = "[COMMAND]", .option_docs = .{ .init = "Initialize a new project", .update = "Update current project to latest version of Jetzig", .generate = "Generate scaffolding", .server = "Run a development server", .routes = "List all routes in your app", .bundle = "Create a deployment bundle", .@"test" = "Run app tests", .help = "Print help and exit", }, }; }; const Verb = union(enum) { init: init.Options, update: update.Options, generate: generate.Options, server: server.Options, routes: routes.Options, bundle: bundle.Options, @"test": tests.Options, g: generate.Options, s: server.Options, r: routes.Options, b: bundle.Options, t: tests.Options, }; /// Main entrypoint for `jetzig` executable. Parses command line args and generates a new /// project, scaffolding, etc. pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer std.debug.assert(gpa.deinit() == .ok); const options = try args.parseWithVerbForCurrentProcess(Options, Verb, allocator, .print); defer options.deinit(); const writer = std.io.getStdErr().writer(); run(allocator, options, writer) catch |err| { switch (err) { error.JetzigCommandError => std.process.exit(1), else => return err, } }; if ((!options.options.help and options.verb == null) or (options.options.help and options.verb == null)) { try args.printHelp(Options, "jetzig", writer); try writer.writeAll( \\ \\Commands: \\ \\ init Initialize a new project. \\ update Update current project to latest version of Jetzig. \\ generate Generate scaffolding. \\ server Run a development server. \\ routes List all routes in your app. \\ bundle Create a deployment bundle. \\ test Run app tests. \\ \\ Pass --help to any command for more information, e.g. `jetzig init --help` \\ ); } } fn run(allocator: std.mem.Allocator, options: args.ParseArgsResult(Options, Verb), writer: anytype) !void { if (options.verb) |verb| { return switch (verb) { .init => |opts| init.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), .g, .generate => |opts| generate.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), .update => |opts| update.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), .s, .server => |opts| server.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), .r, .routes => |opts| routes.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), .b, .bundle => |opts| bundle.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), .t, .@"test" => |opts| tests.run( allocator, opts, writer, options.positionals, .{ .help = options.options.help }, ), }; } }
https://raw.githubusercontent.com/jetzig-framework/jetzig/179b5e77c3a79ca3506e318e91e8e1ade698ba30/cli/cli.zig
// cat ../../julia-play/challenges/advocode2019/1.in | zig run 1.zig const std = @import("std"); const warn = std.debug.warn; pub fn main() anyerror!void { const file = std.io.getStdIn(); const stream = &file.inStream().stream; var buf: [20]u8 = undefined; var sum: usize = 0; var sum2: usize = 0; while (try stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { var mass = try std.fmt.parseInt(usize, line, 10); sum += (mass / 3) - 2; while (mass > 6) { mass = (mass / 3) - 2; sum2 += mass; } } warn("part 1: {}\npart 2: {}\n", sum, sum2); }
https://raw.githubusercontent.com/travisstaloch/advocode2019/55ed89e9114d151178428f0eb1162483c820901e/1.zig
const rl = @import("raylib").c; const MouseButton = @import("raylib").input.MouseButton; pub fn main() void { const screen_width = 800; const screen_height = 450; rl.InitWindow(screen_width, screen_height, "raylib [core] example - mouse input"); defer rl.CloseWindow(); var ball_position = rl.Vector2{ .x = -100, .y = 100 }; var ball_color = rl.DARKBLUE; rl.SetTargetFPS(60); while (!rl.WindowShouldClose()) { { // update ball_position = rl.GetMousePosition(); ball_color = if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.left))) rl.MAROON else if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.middle))) rl.LIME else if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.right))) rl.DARKBLUE else if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.side))) rl.PURPLE else if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.extra))) rl.YELLOW else if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.forward))) rl.ORANGE else if (rl.IsMouseButtonPressed(@enumToInt(MouseButton.back))) rl.BEIGE else ball_color; } { // draw rl.BeginDrawing(); defer rl.EndDrawing(); rl.ClearBackground(rl.RAYWHITE); rl.DrawCircleV(ball_position, 40, ball_color); rl.DrawText( "move ball with mouse and click mouse button to change color", 10, 10, 20, rl.DARKGRAY, ); } } }
https://raw.githubusercontent.com/KilianVounckx/rayz/7d3df9b058b5abe49a4894c0f09aeeab58b75bc8/examples/input_mouse__c_api.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("compile_raylib", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); const raylib_flags = &[_][]const u8{ "-std=gnu99", "-DPLATFORM_DESKTOP", "-DGL_SILENCE_DEPRECATION=199309L", "-fno-sanitize=undefined" }; const raylib_srcdir = "raylib/src"; const raylib = b.addStaticLibrary("raylib", raylib_srcdir ++ "/raylib.h"); raylib.setTarget(target); raylib.setBuildMode(mode); raylib.linkLibC(); raylib.addIncludePath(raylib_srcdir ++ "/external/glfw/include"); raylib.addCSourceFiles(&.{ raylib_srcdir ++ "/raudio.c", raylib_srcdir ++ "/rcore.c", raylib_srcdir ++ "/rmodels.c", raylib_srcdir ++ "/rshapes.c", raylib_srcdir ++ "/rtext.c", raylib_srcdir ++ "/rtextures.c", raylib_srcdir ++ "/utils.c", }, raylib_flags); switch (raylib.target.toTarget().os.tag) { .windows => { raylib.addCSourceFiles(&.{raylib_srcdir ++ "/rglfw.c"}, raylib_flags); raylib.linkSystemLibrary("winmm"); raylib.linkSystemLibrary("gdi32"); raylib.linkSystemLibrary("opengl32"); raylib.addIncludePath("external/glfw/deps/mingw"); }, else => { } } exe.addIncludePath(raylib_srcdir); exe.linkLibrary(raylib); switch (exe.target.toTarget().os.tag) { .windows => { exe.linkSystemLibrary("winmm"); exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("opengl32"); }, else => { } } exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const exe_tests = b.addTest("src/main.zig"); exe_tests.setTarget(target); exe_tests.setBuildMode(mode); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&exe_tests.step); }
https://raw.githubusercontent.com/maihd/fun-with-zig/923660ba365b80ad2e24af4e6cb649ccc186023f/compile_raylib/build.zig
// // It seems we got a little carried away making everything "const u8"! // // "const" values cannot change. // "u" types are "unsigned" and cannot store negative values. // "8" means the type is 8 bits in size. // // Example: foo cannot change (it is CONSTant) // bar can change (it is VARiable): // // const foo: u8 = 20; // var bar: u8 = 20; // // Example: foo cannot be negative and can hold 0 to 255 // bar CAN be negative and can hold -128 to 127 // // const foo: u8 = 20; // const bar: i8 = -20; // // Example: foo can hold 8 bits (0 to 255) // bar can hold 16 bits (0 to 65,535) // // const foo: u8 = 20; // const bar: u16 = 2000; // // You can do just about any combination of these that you can think of: // // u32 can hold 0 to 4,294,967,295 // i64 can hold -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 // // Please fix this program so that the types can hold the desired values // and the errors go away! // const std = @import("std"); pub fn main() void { const n: u8 = 50 + 5; const pi: u32 = 314159; const negative_eleven: i8 = -11; // There are no errors in the next line, just explanation: // Perhaps you noticed before that the print function takes two // parameters. Now it will make more sense: the first parameter // is a string. The string may contain placeholders '{}', and the // second parameter is an "anonymous list literal" (don't worry // about this for now!) with the values to be printed. std.debug.print("{} {} {}\n", .{ n, pi, negative_eleven }); }
https://raw.githubusercontent.com/rjkroege/ziglings/ed4a97781b7ef89d7b6cbb0b36255eb2aa66e4ec/exercises/003_assignment.zig
const std = @import("std"); const assert = std.debug.assert; const data = @embedFile("../data/day13_input"); fn part1(positions: []Pos, folds: []Pos) void { // Should be large enough var grid = [_][655]Value{[_]Value{Value.empty} ** 655} ** 895; for (positions) |_, i| { var pos = positions[i]; const fold = folds[0]; if (fold.x == 0) { if (pos.y > fold.y) { pos.y = fold.y - (pos.y - fold.y); } } else { if (pos.x > fold.x) { pos.x = fold.x - (pos.x - fold.x); } } //std.debug.print("{}\n", .{pos}); grid[pos.y][pos.x] = Value.hash; } // Debug output //for (grid) |row| { // for (row) |val| { // switch (val) { // Value.empty => std.debug.print(".", .{}), // Value.hash => std.debug.print("#", .{}), // } // } // std.debug.print("\n", .{}); //} var count_hashes: usize = 0; for (grid) |row| { for (row) |val| { if (val == Value.hash) { count_hashes += 1; } } } std.debug.print("Day 13, part 1: num dots = {}\n", .{count_hashes}); } fn part2(positions: []Pos, folds: []Pos) void { // Should be large enough var grid = [_][40]Value{[_]Value{Value.empty} ** 40} ** 6; for (positions) |_, i| { var pos = positions[i]; for (folds) |fold| { if (fold.x == 0) { if (pos.y > fold.y) { pos.y = fold.y - (pos.y - fold.y); } } else { if (pos.x > fold.x) { pos.x = fold.x - (pos.x - fold.x); } } } grid[pos.y][pos.x] = Value.hash; } std.debug.print("Day 13, part 2: code =\n", .{}); for (grid) |row| { for (row) |val| { switch (val) { Value.empty => std.debug.print(".", .{}), Value.hash => std.debug.print("#", .{}), } } std.debug.print("\n", .{}); } } const Value = enum(u1) { empty, hash, }; const Pos = struct { x: u32, y: u32, }; var general_purpose_allocator = std.heap.GeneralPurposeAllocator(.{}){}; const gpa = general_purpose_allocator.allocator(); pub fn main() anyerror!void { var line_it = std.mem.tokenize(u8, data, "\r\n"); var positions = std.ArrayList(Pos).init(gpa); var folds = std.ArrayList(Pos).init(gpa); defer { positions.deinit(); folds.deinit(); } while (line_it.next()) |line| { if (std.mem.startsWith(u8, line, "fold along")) { var fold_it = std.mem.tokenize(u8, line, " ="); _ = fold_it.next().?; _ = fold_it.next().?; const dir = fold_it.next().?; const pos = try std.fmt.parseInt(u32, fold_it.next().?, 10); try folds.append(.{ .x = if (dir[0] == 'x') pos else 0, .y = if (dir[0] == 'y') pos else 0, }); } else { var coord_it = std.mem.tokenize(u8, line, ","); if (coord_it.next()) |x_str| { const y_str = coord_it.next().?; try positions.append(.{ .x = try std.fmt.parseInt(u32, x_str, 10), .y = try std.fmt.parseInt(u32, y_str, 10), }); } } } // Debug output to make sure we parsed correctly //for (positions.items) |pos| { // std.debug.print("{d},{d}\n", .{ pos.x, pos.y }); //} //for (folds.items) |fold| { // if (fold.x == 0) { // std.debug.print("fold along y={}\n", .{fold.y}); // } else { // std.debug.print("fold along x={}\n", .{fold.x}); // } // // Compiler error. // //std.debug.print("fold along {}={}\n", .{ // // if (fold.x == 0) "y" else "x", // // if (fold.x == 0) fold.y else fold.x, // //}); //} part1(positions.items, folds.items); part2(positions.items, folds.items); }
https://raw.githubusercontent.com/stefalie/aoc2021/dea0a68012a2283b1e0453c883641c4c5734bca1/src/day13.zig
//! GB ROM interface //! //! References I've found helpful: //! //! - Pan Docs: The Cartridge Header: https://gbdev.io/pandocs/The_Cartridge_Header.html const std = @import("std"); const print = std.debug.print; fn checksum_header(comptime T: type, comptime R: type, bytes: []T) R { var result: R = 0; for (bytes) |byte| { result = result -% byte -% 1; } return result; } fn checksum_rom(data: []const u8) u16 { var result: u16 = 0; var i: usize = 0; for (data) |byte| { if (i != 0x014E and i != 0x014F) { result +%= byte; } i += 1; } return result; } pub const Rom = struct { allocator: std.mem.Allocator, _raw_data: []u8 = undefined, ram: []u8 = undefined, logo: [48]u8 = undefined, title: [11]u8 = undefined, manufacturer_code: [4]u8 = undefined, cgb_flag: CgbFlag = undefined, new_licensee_code: [2]u8 = undefined, sgb_flag: SgbFlag = undefined, cartridge_type: CartridgeType = undefined, rom_size: RomSize = undefined, ram_size: RamSize = undefined, destination_code: DestinationCode = undefined, old_licensee_code: u8 = undefined, mask_rom_version: u8 = undefined, header_checksum: u8 = undefined, global_checksum: u16 = undefined, _bus_read: *const fn (self: *const Rom, addr: u16) u8 = undefined, _bus_write: *const fn (self: *Rom, addr: u16, data: u8) void = undefined, bank_num_mask: u7 = 1, bank1: u5 = 1, bank2: u2 = 0, banking_mode: u1 = 0, ram_enabled: bool = false, __HACK__PRINTING_DEBUG_INFO: bool = false, const HEADER_START = 0x100; const HEADER_END = 0x150; const CgbFlag = enum(u8) { CgbEnhancements = 0x80, CgbOnly = 0xC0, _, }; const SgbFlag = enum(u8) { NoSgbFunctions = 0x00, SgbFunctions = 0x03, _, }; const CartridgeType = enum(u8) { ROM_ONLY = 0x00, MBC1 = 0x01, MBC1_RAM = 0x02, MBC1_RAM_BATTERY = 0x03, MBC2 = 0x05, MBC2_BATTERY = 0x06, ROM_RAM = 0x08, ROM_RAM_BATTERY = 0x09, MMM01 = 0x0B, MMM01_RAM = 0x0C, MMM01_RAM_BATTERY = 0x0D, MBC3_TIMER_BATTERY = 0x0F, MBC3_TIMER_RAM_BATTERY = 0x10, MBC3 = 0x11, MBC3_RAM = 0x12, MBC3_RAM_BATTERY = 0x13, MBC5 = 0x19, MBC5_RAM = 0x1A, MBC5_RAM_BATTERY = 0x1B, MBC5_RUMBLE = 0x1C, MBC5_RUMBLE_RAM = 0x1D, MBC5_RUMBLE_RAM_BATTERY = 0x1E, MBC6 = 0x20, MBC7_SENSOR_RUMBLE_RAM_BATTERY = 0x22, POCKET_CAMERA = 0xFC, BANDAI_TAMA5 = 0xFD, HuC3 = 0xFE, HuC1_RAM_BATTERY = 0xFF, }; const RomSize = enum(u8) { _32KiB = 0x00, _64KiB = 0x01, _128KiB = 0x02, _256KiB = 0x03, _512KiB = 0x04, _1MiB = 0x05, _2MiB = 0x06, _4MiB = 0x07, _8MiB = 0x08, _16MiB = 0x09, _32MiB = 0x0A, _, }; const RamSize = enum(u8) { NoRam = 0x00, _8KiB = 0x02, _32KiB = 0x03, _128KiB = 0x04, _64KiB = 0x05, _, }; const DestinationCode = enum(u8) { Japanese = 0x00, NonJapanese = 0x01, _, }; const ReadError = error{ OutOfRange, }; pub fn format(self: *const Rom, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { const str = ( \\ ----------- Header ----------- \\ logo: {s} \\ {s} \\ {s} \\ title: {s} \\ manufacturer_code: {s} \\ cgb_flag: {X} \\ new_licensee_code: {s} \\ sgb_flag: {X} \\ cartridge_type: {s} \\ rom_size: {s} \\ ram_size: {X} \\ destination_code: {X} \\ old_licensee_code: {X} \\ mask_rom_version: {X} \\ header_checksum: {X} {s} \\ global_checksum: {X} {s} \\ ------- END Header ----------- ); return writer.print(str, .{ std.fmt.fmtSliceHexUpper(self.logo[0..16]), std.fmt.fmtSliceHexUpper(self.logo[16..32]), std.fmt.fmtSliceHexUpper(self.logo[32..]), self.title, std.fmt.fmtSliceHexUpper(&self.manufacturer_code), // I wish `@tagName` worked with @enumToInt(self.cgb_flag), std.fmt.fmtSliceHexUpper(&self.new_licensee_code), @enumToInt(self.sgb_flag), @tagName(self.cartridge_type), @tagName(self.rom_size), @enumToInt(self.ram_size), @enumToInt(self.destination_code), self.old_licensee_code, self.mask_rom_version, self.header_checksum, if (checksum_header(u8, u8, self._raw_data[0x0134..0x014D]) == self.header_checksum) "✅" else "❌", self.global_checksum, if (checksum_rom(self._raw_data) == self.global_checksum) "✅" else "❌", }); } pub fn from_file(file_path: []const u8, allocator: std.mem.Allocator) !Rom { var rom = Rom{ .allocator = allocator }; const file = try std.fs.cwd().openFile(file_path, .{}); defer file.close(); rom._raw_data = try file.readToEndAlloc(allocator, 32 * 1024 * 1024); { var pos: usize = HEADER_START; pos += 4; // We discard the entry point and continue... std.mem.copy(u8, &rom.logo, rom._raw_data[pos..(pos + rom.logo.len)]); pos += rom.logo.len; std.mem.copy(u8, &rom.title, rom._raw_data[pos..(pos + rom.title.len)]); pos += rom.title.len; std.mem.copy(u8, &rom.manufacturer_code, rom._raw_data[pos..(pos + rom.manufacturer_code.len)]); pos += rom.manufacturer_code.len; rom.cgb_flag = @intToEnum(CgbFlag, rom._raw_data[pos]); pos += 1; std.mem.copy(u8, &rom.new_licensee_code, rom._raw_data[pos..(pos + rom.new_licensee_code.len)]); pos += rom.new_licensee_code.len; rom.sgb_flag = @intToEnum(SgbFlag, rom._raw_data[pos]); pos += 1; rom.cartridge_type = @intToEnum(CartridgeType, rom._raw_data[pos]); switch (rom.cartridge_type) { .ROM_ONLY => { rom._bus_read = Rom.bus_read_rom_only; rom._bus_write = Rom.bus_write_rom_only; }, .MBC1 => { rom._bus_read = Rom.bus_read_mbc1; rom._bus_write = Rom.bus_write_mbc1; }, .MBC1_RAM, .MBC1_RAM_BATTERY => { rom._bus_read = Rom.bus_read_mbc1_ram; rom._bus_write = Rom.bus_write_mbc1_ram; }, .MBC3_RAM_BATTERY => { rom._bus_read = Rom.bus_read_mbc1_ram; rom._bus_write = Rom.bus_write_mbc1_ram; }, else => std.debug.panic("Unsupported mapper type: {s}", .{@tagName(rom.cartridge_type)}), } pos += 1; rom.rom_size = @intToEnum(RomSize, rom._raw_data[pos]); pos += 1; rom.ram_size = @intToEnum(RamSize, rom._raw_data[pos]); rom.ram = try switch (rom.ram_size) { .NoRam => allocator.alloc(u8, 0 * 1024), ._8KiB => allocator.alloc(u8, 8 * 1024), ._32KiB => allocator.alloc(u8, 32 * 1024), ._64KiB => allocator.alloc(u8, 64 * 1024), ._128KiB => allocator.alloc(u8, 128 * 1024), else => std.debug.panic("Unsupported ram size: {s}", .{@tagName(rom.ram_size)}), }; pos += 1; rom.destination_code = @intToEnum(DestinationCode, rom._raw_data[pos]); pos += 1; rom.old_licensee_code = rom._raw_data[pos]; pos += 1; rom.mask_rom_version = rom._raw_data[pos]; pos += 1; rom.header_checksum = rom._raw_data[pos]; pos += 1; rom.global_checksum = (@as(u16, rom._raw_data[pos]) << 8) | @as(u16, rom._raw_data[pos + 1]); } // Mask used to keep bank number in range when setting the bank number // register. // // The smallest bitmask possible to represent all valid bank numbers is // used based on the size of the rom. // // For example: // // - 32K ROM; 2 banks; ....1 (0, 1) // - 64K ROM; 4 banks; ...11 (0, 1, 2, 3) // - 128K ROM; 8 banks; ..111 (0, 1, 2, 3, ..., 7) // - 256K ROM; 16 banks; .1111 (0, 1, 2, 3, ..., 15) // - ...etc // // We can calculate this bitmask by essentially shifting a bit to the // N+1th position to get 0b100..N+1, so by subtracting 1 from this // number we get 0b111..N, a mask with N 1s rom.bank_num_mask = @truncate(u7, std.math.pow(u16, 2, @enumToInt(rom.rom_size) + 1) - 1); return rom; } // The way the logo pixels are laid out is hard to describe with words, so // I'll draw it instead: // // ``` // ADDR U8 U4 U4 U8 ADDR // 0x0104 CE C ##.. .##. 6 66 0x0106 // E ###. .##. 6 // 0x0105 ED E ###. .##. 6 66 0x0107 // D ##.# .##. 6 // ``` // // // The first four bytes represent the top-half of the `N` from the // `Nintendo` logo. // // The first byte `CE` draws the top two lines of 4 pixels, the first 4 bits // for the top row of 4 pixels, and the other 4 bits for the bottom row. // // - `C` = `0b1100`, hence `##..` // - `E` = `0b1110`, hence `###.` // // The next byte `ED` goes _down_ one 4x4 tile in the image: // // - `E` = `0b1110`, hence `###.` // - `D` = `0b1101`, hence `##.#` // // Now rather than going down again, we start over at the top and go to the // right one tile. // // We repeat this until we have moved to the right 12 tiles (48 pixels), // then move down to the bottom half of the logo and repeat the process. // // So the bytes correspond to single tiles laid out like this: // // ``` // 0 2 4 6 8 // 1 3 5 7 ... // ``` pub fn draw_logo(self: *const Rom) [8 * 48 + 7]u8 { var logo: [8 * 48 + 7]u8 = undefined; var i: usize = 0; while (i < 7) : (i += 1) { logo[(i + 1) * 48 + i] = '\n'; } // Top row of tiles: i = 0; while ((0x0104 + i) < 0x011C) : (i += 1) { const byte = self._raw_data[0x0104 + i]; const tile_x = i / 2; const tile_y = (i % 2) * 2; const start1 = tile_y * 49 + tile_x * 4; const start2 = (tile_y + 1) * 49 + tile_x * 4; const one: u8 = 1; var bit: u3 = 7; while (bit > 3) : (bit -= 1) { logo[start1 + (7 - bit)] = if ((byte & one << (bit - 0)) != 0) '#' else '.'; logo[start2 + (7 - bit)] = if ((byte & one << (bit - 4)) != 0) '#' else '.'; } } // Bottom row of tiles: i = 0; while ((0x011C + i) < 0x0134) : (i += 1) { const byte = self._raw_data[0x011C + i]; const tile_x = i / 2; const tile_y = 4 + (i % 2) * 2; const start1 = tile_y * 49 + tile_x * 4; const start2 = (tile_y + 1) * 49 + tile_x * 4; const one: u8 = 1; var bit: u3 = 7; while (bit > 3) : (bit -= 1) { logo[start1 + (7 - bit)] = if ((byte & one << (bit - 0)) != 0) '#' else '.'; logo[start2 + (7 - bit)] = if ((byte & one << (bit - 4)) != 0) '#' else '.'; } } return logo; } pub fn deinit(self: *const Rom) void { self.allocator.free(self._raw_data); self.allocator.free(self.ram); } // // Emulator methods // /// A read from the bus at a given address. pub fn bus_read(self: *const Rom, addr: u16) u8 { return self._bus_read(self, addr); } pub fn bus_write(self: *Rom, addr: u16, data: u8) void { self._bus_write(self, addr, data); } fn bus_read_rom_only(self: *const Rom, addr: u16) u8 { return self._raw_data[addr]; } fn bus_write_rom_only(_: *Rom, _: u16, _: u8) void {} fn bus_read_mbc1(self: *const Rom, addr: u16) u8 { switch (addr) { // ROM Bank X0 [read-only] 0x0000...0x3FFF => { var final_addr: u21 = @intCast(u21, addr); if (self.banking_mode == 1) { final_addr |= (@intCast(u21, self.bank2) << 19); } return self._raw_data[final_addr % self._raw_data.len]; }, // ROM Bank 01-7F [read-only] 0x4000...0x7FFF => { var final_bank_num: u7 = ((@intCast(u7, self.bank2) << 5) | (@intCast(u7, self.bank1))) & self.bank_num_mask; var final_addr: u21 = (addr & 0x3FFF) | (@intCast(u21, (final_bank_num)) << 14); const result = self._raw_data[final_addr % self._raw_data.len]; // if (!self.__HACK__PRINTING_DEBUG_INFO) { // std.debug.print("bus_read_mbc1(0x{X:0>4}) (bank1 ${X:0>2}, bank2 ${X}, final_bank_num ${X:0>2}) // ROM[0x{X:0>5}] = ${X:0>2}\n", .{ addr, self.bank1, self.bank2, final_bank_num, final_addr, result }); // } return result; }, // RAM Bank 00-03; no RAM for this cart type so always return $FF: 0xA000...0xBFFF => return 0xFF, // Should we panic here? else => return 0xFF, } } fn bus_read_mbc1_ram(self: *const Rom, addr: u16) u8 { switch (addr) { // RAM Bank 00–03 0xA000...0xBFFF => { if (!self.ram_enabled) return 0xFF; const final_addr = self.ram_addr(addr); const result = self.ram[final_addr % self.ram.len]; // std.debug.print("bus_read_mbc1_ram(0x{X:0>4}) // RAM[0x{X:0>5}] = ${X:0>2}\n", .{ addr, final_addr, result }); return result; }, else => return Rom.bus_read_mbc1(self, addr), } } fn bus_write_mbc1(self: *Rom, addr: u16, data: u8) void { switch (addr) { // ROM Bank number [write-only] 0x2000...0x3FFF => { var bank1 = @truncate(u5, data); if (bank1 == 0) { // If this register is set to $00, it behaves as if it is // set to $01. bank1 = 1; } self.bank1 = bank1; // std.debug.print("rom.bank1 = ${X:0>2} (set via ${X:0>4}=${X:0>2})\n", .{ bank1, addr, data }); }, // RAM Bank Number/Upper Bits of ROM Bank Number [write-only] 0x4000...0x5FFF => { self.bank2 = @truncate(u2, data); // std.debug.print("bank2 = {X:0>2}\n", .{self.bank2}); }, // Banking Mode Select [write-only] 0x6000...0x7FFF => { if (data & 0b1 == 0b1) { self.banking_mode = 1; } else { self.banking_mode = 0; } }, else => { // Ignored... }, } } fn bus_write_mbc1_ram(self: *Rom, addr: u16, data: u8) void { switch (addr) { // RAM Enable [write-only] 0x0000...0x1FFF => { self.ram_enabled = (data & 0x0F) == 0x0A; }, // ROM Bank Number [write-only] // 0x2000...0x3FFF - handled in else block // RAM Bank Number [write-only] // 0x4000...0x5FFF - handled in else block // Banking Mode Select [write-only] // 0x6000...0x7FFF - handled in else block // RAM Bank 00-03 0xA000...0xBFFF => { if (!self.ram_enabled) return; const final_addr = self.ram_addr(addr); self.ram[final_addr % self.ram.len] = data; // std.debug.print("write {X:0>4} ({X:0>4}) = {X:0>2}\n", .{ addr, final_addr, data }); }, else => Rom.bus_write_mbc1(self, addr, data), } } fn ram_addr(self: *const Rom, addr: u16) u15 { var final_addr: u15 = @truncate(u15, addr & 0b000_1111_1111_1111); if (self.banking_mode == 1) { final_addr |= (@intCast(u15, self.bank2) << 13); } return final_addr; } };
https://raw.githubusercontent.com/namuol/boyziigame/b0a8ec271ea647529eeb237c94b336aa8e0a140a/src/rom.zig
pub const cpu = @import("raspberrypi/cpu.zig"); pub const memory = @import("raspberrypi/memory.zig"); const board = switch (@import("build_options").board) { .rpi3 => @import("devices/bcm/bcm2837.zig"), .rpi4 => @import("devices/bcm/bcm2711.zig"), }; const Uart = @import("devices/pl011/uart.zig"); pub const console: Uart = Uart.new(memory.mmio.PL011_UART_START); pub fn init() void { comptime { _ = cpu.BOOT_CORE_ID; } // Set the UART on GPIO pins 14 & 15 board.gpio.GPFSEL1.write(.{ .fsel14 = .txd0, .fsel15 = .rxd0, }); board.gpio.setupUart(); console.init(); } comptime { @import("std").testing.refAllDecls(@This()); }
https://raw.githubusercontent.com/tdeebswihart/zkernel/eca7f0efbe669d85b2083dbfb245973bad346a3d/lib/bsp/raspberrypi.zig
const std = @import("std"); const Block = @import("block.zig"); const FCF = @import("fcf.zig"); // https://www.fileformat.info/format/foxpro/dbf.htm // TODO: docs const MagicString = [14]u8{ 0x0C, 0x47, 0x45, 0x52, 0x42, 0x49, 0x4C, 0x44, 0x42, 0x33, 0x20, 0x20, 0x20, 0x00 }; pub const Header = extern struct { formDefinitionIndex: u16, // block# - 1 lastUsedBlock: u16, // not accurate totalFileBlocks: u16, // dont count header dataRecords: u16, magicString: [14]u8, availableDBFields: u16, formLength: u16, formRevisions: u16, // 1 indexed _1: u16, emptiesLength: u16, tableViewIndex: u16, programRecordIndex: u16, _2: u16, _3: u16, nextFieldSize: u8, diskVar: [128 - 41]u8, pub fn fromBytes(raw: *[128]u8) Header { const head = std.mem.bytesToValue(Header, raw); return head; } }; fn getSlice(file_content: []const u8, file_offset: usize, count: usize) []align(1) Header { const ptr = @intFromPtr(file_content.ptr) + file_offset; return @as([*]align(1) Header, @ptrFromInt(ptr))[0..count]; } test "read header" { // 09 00 1c 00 1c 00 08 00 0c 47 45 52 42 49 4c 44 // 42 33 20 20 20 00 0d 00 26 01 02 00 00 00 00 00 // ff ff ff ff 00 00 02 00 08 00 00 00 00 00 00 00 // 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 var bytes = [_]u8{ 0x09, 0x00, 0x1c, 0x00, 0x1c, 0x00, 0x08, 0x00, 0x0c, 0x47, 0x45, 0x52, 0x42, 0x49, 0x4c, 0x44, 0x42, 0x33, 0x20, 0x20, 0x20, 0x00, 0x0d, 0x00, 0x26, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x02, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; var head = Header.fromBytes(&bytes); // std.debug.print("{s}\n", .{head}); try std.testing.expectEqual(head.formDefinitionIndex, 9); try std.testing.expectEqual(head.lastUsedBlock, 28); try std.testing.expectEqual(head.totalFileBlocks, 28); try std.testing.expectEqual(head.dataRecords, 8); try std.testing.expect(std.mem.eql(u8, &head.magicString, &MagicString)); try std.testing.expectEqual(head.availableDBFields, 13); try std.testing.expectEqual(head.formLength, 294); try std.testing.expectEqual(head.formRevisions, 2); try std.testing.expectEqual(head.emptiesLength, 0); try std.testing.expectEqual(head.tableViewIndex, 0xFFFF); try std.testing.expectEqual(head.programRecordIndex, 0xFFFF); try std.testing.expectEqual(head.nextFieldSize, 8); }
https://raw.githubusercontent.com/tsunaminoai/lastchoice/75b21301a17aaa4d67363397f93450572fa0c477/src/header.zig
// SPDX-License-Identifier: GPL-3.0 // Copyright (c) 2021 Keith Chambers // This program is free software: you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software Foundation, version 3. const std = @import("std"); pub inline fn Pixel(comptime Type: type) type { // TODO: Add error checking to type return Type; } pub inline fn Normalized(comptime Type: type) type { // TODO: Add error checking to type return Type; } pub fn Coordinates2D(comptime BaseType: type) type { return packed struct { x: BaseType, y: BaseType, }; } pub fn Dimensions2D(comptime BaseType: type) type { return packed struct { height: BaseType, width: BaseType, }; } pub fn Extent2D(comptime BaseType: type) type { return packed struct { x: BaseType, y: BaseType, height: BaseType, width: BaseType, }; } pub fn ScaleFactor2D(comptime BaseType: type) type { return packed struct { horizontal: BaseType, vertical: BaseType, }; } pub const Axis = enum(u8) { none, horizontal, vertical, diagnal, }; pub const AnchorType = enum(u8) { center, bottom_left, bottom_right, top_left, top_right, }; pub const ScreenReference = enum(u8) { left, right, top, bottom, }; pub fn Scale2D(comptime BaseType: type) type { return packed struct { x: BaseType, y: BaseType, }; } pub fn Shift2D(comptime BaseType: type) type { return packed struct { x: BaseType, y: BaseType, }; } // TODO: Remove pub const percentage = percentageToNativeDeviceCoordinates; pub const pixel = pixelToNativeDeviceCoordinateRight; pub fn percentageToNativeDeviceCoordinates(percent: f32) f32 { std.debug.assert(percent >= -1.0 and percent <= 1.0); return percent / 2.0; } /// Converts a Coordinates2D structure using absolute pixel values to one /// that uses Native Device Coordinates, normalized between -1.0 and 1.0 /// The scale factor can be calculated using the absolute screen dimensions as follows: /// scale_factor = ScaleFactor2D{ .horizontal = 2.0 / screen_dimensions.width, .veritical = 2.0 / screen_dimensions.height}; fn coordinates2DPixelToNativeDeviceCoordinateRight( coordinates: Coordinates2D(.pixel), scale_factor: ScaleFactor2D, ) Coordinates2D { return .{ .x = coordinates.x * scale_factor.horizontal, .y = coordinates.y * scale_factor.vertical, }; } /// Converts an absolute pixel value into a Native Device Coordinates value that is /// normalized between -1.0 and 1.0 /// The scale factor can be calculated using the absolute screen dimensions as follows: /// scale_factor = ScaleFactor2D{ .horizontal = 2.0 / screen_dimensions.width, .veritical = 2.0 / screen_dimensions.height}; pub fn pixelToNativeDeviceCoordinateRight(pixel_value: u32, scale_factor: f32) f32 { return -1.0 + @intToFloat(f32, pixel_value) * scale_factor; }
https://raw.githubusercontent.com/kdchambers/fliz/a8f43f8b0ffa19e90f22d36da20ed7892396b18a/src/geometry.zig
const std = @import("std"); const Vm = @import("./Vm.zig"); pub const routines = [_]Vm.NativeRoutine{ // General purpose .{ .name = "PRINT", .func = nativePrint }, .{ .name = "ASSERT", .func = nativeAssert }, .{ .name = "EQUALS", .func = nativeEquals }, .{ .name = "TO", .func = nativeTo }, // Stack manipulation .{ .name = "DROP", .func = nativeDrop }, .{ .name = "DUP", .func = nativeDup }, .{ .name = "SWAP", .func = nativeSwap }, .{ .name = "ROT", .func = nativeRot }, .{ .name = "OVER", .func = nativeOver }, .{ .name = "COUNT", .func = nativeCount }, .{ .name = "IS-EMPTY", .func = nativeIsEmpty }, // Boolean operations .{ .name = "OR", .func = nativeOr }, .{ .name = "AND", .func = nativeAnd }, .{ .name = "NOT", .func = nativeNot }, // Number comparators .{ .name = "GREATER-THAN", .func = nativeGreaterThan }, .{ .name = "GREATER-EQUAL", .func = nativeGreaterEqual }, .{ .name = "LESS-THAN", .func = nativeLessThan }, .{ .name = "LESS-EQUAL", .func = nativeLessEqual }, // Type checks .{ .name = "IS-BOOLEAN", .func = nativeIsBoolean }, .{ .name = "IS-NUMBER", .func = nativeIsNumber }, .{ .name = "IS-STRING", .func = nativeIsString }, }; inline fn popB(vm: *Vm) !bool { return switch (try vm.stack.pop()) { .b => |b| b, else => error.InvalidType, }; } inline fn peekB(vm: *Vm) !bool { const v = try vm.stack.peek(); return switch (v.*) { .b => |b| b, else => error.InvalidType, }; } inline fn pushB(vm: *Vm, b: bool) !void { try vm.stack.push(.{ .b = b }); } inline fn replaceB(vm: *Vm, b: bool) !void { const v = try vm.stack.peek(); v.* = .{ .b = b }; } inline fn popN(vm: *Vm) !i32 { return switch (try vm.stack.pop()) { .n => |n| n, else => error.InvalidType, }; } inline fn peekN(vm: *Vm) !i32 { const v = try vm.stack.peek(); return switch (v.*) { .n => |n| n, else => error.InvalidType, }; } inline fn pushN(vm: *Vm, n: i32) !void { try vm.stack.push(.{ .n = n }); } inline fn replaceN(vm: *Vm, n: i32) !void { const v = try vm.stack.peek(); v.* = .{ .n = n }; } // == GENERAL PURPOSE == // fn nativePrint(vm: *Vm) !void { const stdout = std.io.getStdOut().writer(); try (try vm.stack.pop()).print(stdout); try stdout.writeAll("\n"); } fn nativeAssert(vm: *Vm) !void { const a = try popB(vm); if (!a) return error.AssertFailed; } fn nativeEquals(vm: *Vm) !void { const a = try vm.stack.pop(); const b = try vm.stack.pop(); const res = try a.equals(b); try pushB(vm, res); } fn nativeTo(vm: *Vm) !void { const b = try popN(vm); const a = try popN(vm); var i: i32 = a; if (b > a) { while (i <= b) : (i += 1) { try pushN(vm, i); } } else { while (i >= b) : (i -= 1) { try pushN(vm, i); } } } // == STACK MANIPULATION == // fn nativeDrop(vm: *Vm) !void { try vm.stack.drop(); } fn nativeDup(vm: *Vm) !void { try vm.stack.push((try vm.stack.peek()).*); } fn nativeSwap(vm: *Vm) !void { const top = try vm.stack.pop(); const below = try vm.stack.pop(); try vm.stack.push(top); try vm.stack.push(below); } fn nativeRot(vm: *Vm) !void { const a = try vm.stack.pop(); const b = try vm.stack.pop(); const c = try vm.stack.pop(); try vm.stack.push(b); try vm.stack.push(a); try vm.stack.push(c); } fn nativeOver(vm: *Vm) !void { const a = try vm.stack.pop(); const b = try vm.stack.pop(); try vm.stack.push(b); try vm.stack.push(a); try vm.stack.push(b); } fn nativeCount(vm: *Vm) !void { try pushN(vm, @intCast(vm.stack.count)); } fn nativeIsEmpty(vm: *Vm) !void { try pushB(vm, vm.stack.count == 0); } // == BOOLEAN OPERATIONS == // fn nativeNot(vm: *Vm) !void { const b = try popB(vm); try pushB(vm, !b); } const BooleanBinaryOp = enum { @"or", @"and", }; inline fn nativeBooleanBinaryOp(vm: *Vm, comptime op: BooleanBinaryOp) !void { const a = try popB(vm); const b = try peekB(vm); const res = switch (op) { .@"or" => a or b, .@"and" => a and b, }; try replaceB(vm, res); } fn nativeOr(vm: *Vm) !void { return nativeBooleanBinaryOp(vm, .@"or"); } fn nativeAnd(vm: *Vm) !void { return nativeBooleanBinaryOp(vm, .@"and"); } // == NUMBER COMPARATORS == // const NumberComparisonOp = enum { gt, ge, lt, le, }; inline fn nativeNumberComparisonOp(vm: *Vm, comptime op: NumberComparisonOp) !void { const b = try popN(vm); const a = try peekN(vm); const res = switch (op) { .gt => a > b, .ge => a >= b, .lt => a < b, .le => a <= b, }; try replaceB(vm, res); } fn nativeGreaterThan(vm: *Vm) !void { return nativeNumberComparisonOp(vm, .gt); } fn nativeGreaterEqual(vm: *Vm) !void { return nativeNumberComparisonOp(vm, .ge); } fn nativeLessThan(vm: *Vm) !void { return nativeNumberComparisonOp(vm, .lt); } fn nativeLessEqual(vm: *Vm) !void { return nativeNumberComparisonOp(vm, .le); } // == TYPE CHECKS == fn nativeIsBoolean(vm: *Vm) !void { const v = try vm.stack.peek(); const res = switch (v.*) { .b => true, else => false, }; try pushB(vm, res); } fn nativeIsNumber(vm: *Vm) !void { const v = try vm.stack.peek(); const res = switch (v.*) { .n => true, else => false, }; try pushB(vm, res); } fn nativeIsString(vm: *Vm) !void { const v = try vm.stack.peek(); const res = switch (v.*) { .s => true, else => false, }; try pushB(vm, res); }
https://raw.githubusercontent.com/yukiisbored/zcauchemar/d23c51f0478f2f84861c2108a0bcf70a1fd1eec9/src/stdlib.zig
pub const RandomState = u32; pub fn init_random(seed: u32) RandomState { return seed; } pub fn random32(state: *RandomState) u32 { state.* +%= 0x6D2B79F5; var z = state.*; z = (z ^ z >> 15) *% (1 | z); z ^= z +% (z ^ z >> 7) *% (61 | z); return z ^ z >> 14; } pub fn randomf_range(comptime min: comptime_float, comptime max: comptime_float, state: *RandomState) f32 { const value: f32 = @floatFromInt(random32(state)); return min + ((value - 0) * (max - min) / (0xFFFF_FFFF - 0)); }
https://raw.githubusercontent.com/DanB91/Wozmon64/29920645644a04037a7906850ac58ab43312ada3/src/toolbox/src/random.zig
const std = @import("std"); const Func = struct { name: []const u8, args: []const Arg, ret: []const u8, js: []const u8, }; const Arg = struct { name: []const u8, type: []const u8, }; // TODO - i don't know what to put for GLboolean... i can't find an explicit // mention anywhere on what size it should be const zig_top = \\pub const GLenum = c_uint; \\pub const GLboolean = bool; \\pub const GLbitfield = c_uint; \\pub const GLbyte = i8; \\pub const GLshort = i16; \\pub const GLint = i32; \\pub const GLsizei = i32; \\pub const GLintptr = i64; \\pub const GLsizeiptr = i64; \\pub const GLubyte = u8; \\pub const GLushort = u16; \\pub const GLuint = u32; \\pub const GLfloat = f32; \\pub const GLclampf = f32; \\pub const GL_VERTEX_SHADER = 35633; \\pub const GL_FRAGMENT_SHADER = 35632; \\pub const GL_ARRAY_BUFFER = 34962; \\pub const GL_ELEMENT_ARRAY_BUFFER = 0x8893; \\pub const GL_TRIANGLES = 4; \\pub const GL_TRIANGLE_STRIP = 5; \\pub const GL_STATIC_DRAW = 35044; \\pub const GL_DYNAMIC_DRAW = 0x88E8; \\pub const GL_FLOAT = 5126; \\pub const GL_DEPTH_TEST = 2929; \\pub const GL_LEQUAL = 515; \\pub const GL_COLOR_BUFFER_BIT = 16384; \\pub const GL_DEPTH_BUFFER_BIT = 256; \\pub const GL_STENCIL_BUFFER_BIT = 1024; \\pub const GL_TEXTURE_2D = 3553; \\pub const GL_RGBA = 6408; \\pub const GL_UNSIGNED_BYTE = 5121; \\pub const GL_TEXTURE_MAG_FILTER = 10240; \\pub const GL_TEXTURE_MIN_FILTER = 10241; \\pub const GL_NEAREST = 9728; \\pub const GL_TEXTURE0 = 33984; \\pub const GL_BLEND = 3042; \\pub const GL_SRC_ALPHA = 770; \\pub const GL_ONE_MINUS_SRC_ALPHA = 771; \\pub const GL_ONE = 1; \\pub const GL_NO_ERROR = 0; \\pub const GL_FALSE = 0; \\pub const GL_TRUE = 1; \\pub const GL_UNPACK_ALIGNMENT = 3317; \\ \\pub const GL_TEXTURE_WRAP_S = 10242; \\pub const GL_CLAMP_TO_EDGE = 33071; \\pub const GL_TEXTURE_WRAP_T = 10243; \\pub const GL_PACK_ALIGNMENT = 3333; \\ \\pub const GL_FRAMEBUFFER = 0x8D40; \\pub const GL_RGB = 6407; \\ \\pub const GL_COLOR_ATTACHMENT0 = 0x8CE0; \\pub const GL_FRAMEBUFFER_COMPLETE = 0x8CD5; \\pub const GL_CULL_FACE = 0x0B44; \\pub const GL_CCW = 0x0901; \\pub const GL_STREAM_DRAW = 0x88E0; \\ \\// Data Types \\pub const GL_UNSIGNED_SHORT = 0x1403; \\pub const GL_UNSIGNED_INT = 0x1405; ; // memory has to be wrapped in a getter because we need the "env" before we can // even get the memory const js_top = \\export default function getWebGLEnv(canvas_element, getInstance) { \\ const getMemory = () => getInstance().exports.memory; \\ const utf8decoder = new TextDecoder(); \\ const readCharStr = (ptr, len) => \\ utf8decoder.decode(new Uint8Array(getMemory().buffer, ptr, len)); \\ const writeCharStr = (ptr, len, lenRetPtr, text) => { \\ const encoder = new TextEncoder(); \\ const message = encoder.encode(text); \\ const zigbytes = new Uint8Array(getMemory().buffer, ptr, len); \\ let zigidx = 0; \\ for (const b of message) { \\ if (zigidx >= len-1) break; \\ zigbytes[zigidx] = b; \\ zigidx += 1; \\ } \\ zigbytes[zigidx] = 0; \\ if (lenRetPtr !== 0) { \\ new Uint32Array(getMemory().buffer, lenRetPtr, 1)[0] = zigidx; \\ } \\ } \\ \\ const gl = canvas_element.getContext('webgl2', { \\ antialias: false, \\ preserveDrawingBuffer: true, \\ }); \\ \\ if (!gl) { \\ throw new Error('The browser does not support WebGL'); \\ } \\ \\ const glShaders = []; \\ const glPrograms = []; \\ const glBuffers = []; \\ const glVertexArrays = []; \\ const glTextures = []; \\ const glFramebuffers = []; \\ const glUniformLocations = []; \\ ; const js_bottom = \\} ; const funcs = [_]Func{ Func{ .name = "getScreenW", .args = &[_]Arg{}, .ret = "i32", .js = \\return gl.drawingBufferWidth; }, Func{ .name = "getScreenH", .args = &[_]Arg{}, .ret = "i32", .js = \\return gl.drawingBufferHeight; }, Func{ .name = "glActiveTexture", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, }, .ret = "void", .js = \\gl.activeTexture(target); }, Func{ .name = "glAttachShader", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, .{ .name = "shader", .type = "c_uint" }, }, .ret = "void", .js = \\gl.attachShader(glPrograms[program], glShaders[shader]); }, // TODO - glBindAttribLocation Func{ .name = "glBindBuffer", .args = &[_]Arg{ .{ .name = "type", .type = "c_uint" }, .{ .name = "buffer_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindBuffer(type, glBuffers[buffer_id]); }, Func{ .name = "glBindVertexArray", .args = &[_]Arg{ .{ .name = "vertex_array_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindVertexArray(glVertexArrays[vertex_array_id]); }, Func{ .name = "glBindFramebuffer", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "framebuffer", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindFramebuffer(target, glFramebuffers[framebuffer]); }, // TODO - glBindRenderbuffer Func{ .name = "glBindTexture", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "texture_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindTexture(target, glTextures[texture_id]); }, // TODO - glBlendColor // TODO - glBlendEquation // TODO - glBlendEquationSeparate Func{ .name = "glBlendFunc", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, .{ .name = "y", .type = "c_uint" }, }, .ret = "void", .js = \\gl.blendFunc(x, y); }, // TODO - glBlendFuncSeparate Func{ .name = "glBufferData", .args = &[_]Arg{ .{ .name = "type", .type = "c_uint" }, .{ .name = "count", .type = "c_long" }, .{ .name = "data_ptr", .type = "*const c_void" }, .{ .name = "draw_type", .type = "c_uint" }, }, .ret = "void", .js = // TODO - check for NULL? \\const bytes = new Uint8Array(getMemory().buffer, data_ptr, count); \\gl.bufferData(type, bytes, draw_type); }, // TODO - glBufferSubData Func{ .name = "glCheckFramebufferStatus", .args = &[_]Arg{ .{ .name = "target", .type = "GLenum" }, }, .ret = "GLenum", .js = \\return gl.checkFramebufferStatus(target); }, Func{ .name = "glClear", .args = &[_]Arg{ .{ .name = "mask", .type = "GLbitfield" }, }, .ret = "void", .js = \\gl.clear(mask); }, Func{ .name = "glClearColor", .args = &[_]Arg{ .{ .name = "r", .type = "f32" }, .{ .name = "g", .type = "f32" }, .{ .name = "b", .type = "f32" }, .{ .name = "a", .type = "f32" }, }, .ret = "void", .js = \\gl.clearColor(r, g, b, a); }, // TODO - glClearDepth // TODO - glClearStencil // TODO - glColorMask // TODO - glCommit Func{ .name = "glCompileShader", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, }, .ret = "void", .js = \\gl.compileShader(glShaders[shader]); }, Func{ .name = "getShaderCompileStatus", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, }, .ret = "GLboolean", .js = \\return gl.getShaderParameter(glShaders[shader], gl.COMPILE_STATUS); }, // TODO - glCompressedTexImage2D // TODO - glCompressedTexImage3D // TODO - glCompressedTexSubImage2D // TODO - glCopyTexImage2D // TODO - glCopyTexSubImage2D Func{ .name = "glCreateBuffer", .args = &[_]Arg{}, .ret = "c_uint", .js = \\glBuffers.push(gl.createBuffer()); \\return glBuffers.length - 1; }, Func{ .name = "glCreateFramebuffer", .args = &[_]Arg{}, .ret = "GLuint", .js = \\glFramebuffers.push(gl.createFramebuffer()); \\return glFramebuffers.length - 1; }, Func{ .name = "glCreateProgram", .args = &[_]Arg{}, .ret = "GLuint", .js = \\glPrograms.push(gl.createProgram()); \\return glPrograms.length - 1; }, // TODO - glCreateRenderbuffer Func{ .name = "glCreateShader", .args = &[_]Arg{ .{ .name = "shader_type", .type = "GLenum" }, }, .ret = "GLuint", .js = \\glShaders.push(gl.createShader(shader_type)); \\return glShaders.length - 1; }, Func{ .name = "glCreateTexture", .args = &[_]Arg{}, .ret = "c_uint", .js = \\glTextures.push(gl.createTexture()); \\return glTextures.length - 1; }, // TODO - glCullFace Func{ .name = "glDeleteBuffer", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteBuffer(glBuffers[id]); \\glBuffers[id] = undefined; }, // TODO - glDeleteFramebuffer Func{ .name = "glDeleteProgram", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteProgram(glPrograms[id]); \\glPrograms[id] = undefined; }, // TODO - glDeleteRenderbuffer Func{ .name = "glDeleteShader", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteShader(glShaders[id]); \\glShaders[id] = undefined; }, Func{ .name = "glDeleteTexture", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteTexture(glTextures[id]); \\glTextures[id] = undefined; }, Func{ .name = "glDepthFunc", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, }, .ret = "void", .js = \\gl.depthFunc(x); }, // TODO - glDepthMask // TODO - glDepthRange Func{ .name = "glDetachShader", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, .{ .name = "shader", .type = "c_uint" }, }, .ret = "void", .js = \\gl.detachShader(glPrograms[program], glShaders[shader]); }, Func{ .name = "glDisable", .args = &[_]Arg{ .{ .name = "cap", .type = "GLenum" }, }, .ret = "void", .js = \\gl.disable(cap); }, // TODO - glDisableVertexAttribArray Func{ .name = "glCreateVertexArray", .args = &[_]Arg{}, .ret = "c_uint", .js = \\glVertexArrays.push(gl.createVertexArray()); \\return glVertexArrays.length - 1; }, Func{ .name = "glDrawArrays", .args = &[_]Arg{ .{ .name = "type", .type = "c_uint" }, .{ .name = "offset", .type = "c_uint" }, .{ .name = "count", .type = "c_uint" }, }, .ret = "void", .js = \\gl.drawArrays(type, offset, count); }, Func{ .name = "glDrawElements", .args = &[_]Arg{ .{ .name = "mode", .type = "GLenum" }, .{ .name = "count", .type = "GLsizei" }, .{ .name = "type", .type = "GLenum" }, .{ .name = "offset", .type = "?*const c_void" }, }, .ret = "void", .js = \\gl.drawElements(mode, count, type, offset); }, Func{ .name = "glEnable", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, }, .ret = "void", .js = \\gl.enable(x); }, Func{ .name = "glEnableVertexAttribArray", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, }, .ret = "void", .js = \\gl.enableVertexAttribArray(x); }, // TODO - glFinish // TODO - glFlush // TODO - glFramebufferRenderbuffer Func{ .name = "glFramebufferTexture2D", .args = &[_]Arg{ .{ .name = "target", .type = "GLenum" }, .{ .name = "attachment", .type = "GLenum" }, .{ .name = "textarget", .type = "GLenum" }, .{ .name = "texture", .type = "GLuint" }, .{ .name = "level", .type = "GLint" }, }, .ret = "void", .js = \\gl.framebufferTexture2D(target, attachment, textarget, glTextures[texture], level); }, Func{ .name = "glFrontFace", .args = &[_]Arg{ .{ .name = "mode", .type = "GLenum" }, }, .ret = "void", .js = \\gl.frontFace(mode); }, // TODO - glGenerateMipmap // TODO - glGetActiveAttrib // TODO - glGetActiveUniform // TODO - glGetAttachedShaders Func{ .name = "glGetAttribLocation", .args = &[_]Arg{ .{ .name = "program_id", .type = "c_uint" }, .{ .name = "name", .type = "SLICE" }, }, .ret = "c_int", .js = \\return gl.getAttribLocation(glPrograms[program_id], name); }, // TODO - glGetBufferParameter // TODO - glGetContextAttributes Func{ .name = "glGetError", .args = &[_]Arg{}, .ret = "c_int", .js = \\return gl.getError(); }, // TODO - glGetExtension // TODO - glGetFramebufferAttachmentParameter // TODO - glGetParameter // TODO - glGetProgramInfoLog // TODO - glGetProgramParameter // TODO - glGetRenderbufferParameter // TODO - glGetShaderInfoLog Func{ .name = "glGetShaderInfoLog", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, .{ .name = "maxLength", .type = "GLsizei" }, .{ .name = "length", .type = "?*GLsizei" }, .{ .name = "infoLog", .type = "?[*]u8" }, }, .ret = "void", .js = \\writeCharStr(infoLog, maxLength, length, gl.getShaderInfoLog(glShaders[shader])); }, // TODO - glGetShaderParameter // TODO - glGetShaderPrecisionFormat // TODO - glGetShaderSource // TODO - glGetSupportedExtensions // TODO - glGetTexParameter // TODO - glGetUniform Func{ .name = "glGetUniformLocation", .args = &[_]Arg{ .{ .name = "program_id", .type = "c_uint" }, .{ .name = "name", .type = "SLICE" }, }, .ret = "c_int", .js = \\glUniformLocations.push(gl.getUniformLocation(glPrograms[program_id], name)); \\return glUniformLocations.length - 1; }, // TODO - glGetVertexAttrib // TODO - glGetVertexAttribOffset // TODO - glHint // TODO - glIsBuffer // TODO - glIsContextLost // TODO - glIsEnabled // TODO - glIsFramebuffer // TODO - glIsProgram // TODO - glIsRenderbuffer // TODO - glIsShader // TODO - glIsTexture // TODO - glLineWidth Func{ .name = "glLinkProgram", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, }, .ret = "void", .js = \\gl.linkProgram(glPrograms[program]); }, Func{ .name = "getProgramLinkStatus", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, }, .ret = "GLboolean", .js = \\return gl.getProgramParameter(glPrograms[program], gl.LINK_STATUS); }, Func{ .name = "glGetProgramInfoLog", .args = &[_]Arg{ .{ .name = "program", .type = "GLuint" }, .{ .name = "maxLength", .type = "GLsizei" }, .{ .name = "length", .type = "?*GLsizei" }, .{ .name = "infoLog", .type = "?[*]u8" }, }, .ret = "void", .js = \\writeCharStr(infoLog, maxLength, length, gl.getProgramInfoLog(glPrograms[program])); }, Func{ .name = "glPixelStorei", .args = &[_]Arg{ .{ .name = "pname", .type = "GLenum" }, .{ .name = "param", .type = "GLint" }, }, .ret = "void", .js = \\gl.pixelStorei(pname, param); }, // TODO - glPolygonOffset // TODO - glReadPixels // TODO - glRenderbufferStorage // TODO - glSampleCoverage // TODO - glScissor Func{ .name = "glShaderSource", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, .{ .name = "string", .type = "SLICE" }, }, .ret = "void", .js = \\gl.shaderSource(glShaders[shader], string); }, // TODO - glStencilFunc // TODO - glStencilFuncSeparate // TODO - glStencilMask // TODO - glStencilMaskSeparate // TODO - glStencilOp // TODO - glStencilOpSeparate Func{ .name = "glTexImage2D", // FIXME - take slice for data. note it needs to be optional .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "level", .type = "c_uint" }, .{ .name = "internal_format", .type = "c_uint" }, .{ .name = "width", .type = "c_int" }, .{ .name = "height", .type = "c_int" }, .{ .name = "border", .type = "c_uint" }, .{ .name = "format", .type = "c_uint" }, .{ .name = "type", .type = "c_uint" }, .{ .name = "data_ptr", .type = "?[*]const u8" }, .{ .name = "data_len", .type = "c_uint" }, }, .ret = "void", .js = \\// FIXME - look at data_ptr, not data_len, to determine NULL? \\const data = data_len > 0 ? new Uint8Array(getMemory().buffer, data_ptr, data_len) : null; \\gl.texImage2D(target, level, internal_format, width, height, border, format, type, data); }, Func{ .name = "glTexParameterf", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "pname", .type = "c_uint" }, .{ .name = "param", .type = "f32" }, }, .ret = "void", .js = \\gl.texParameterf(target, pname, param); }, Func{ .name = "glTexParameteri", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "pname", .type = "c_uint" }, .{ .name = "param", .type = "c_uint" }, }, .ret = "void", .js = \\gl.texParameteri(target, pname, param); }, // TODO - glTexSubImage2D Func{ .name = "glUniform1f", .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "x", .type = "f32" }, }, .ret = "void", .js = \\gl.uniform1f(glUniformLocations[location_id], x); }, // TODO - glUniform1fv Func{ .name = "glUniform1i", .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "x", .type = "c_int" }, }, .ret = "void", .js = \\gl.uniform1i(glUniformLocations[location_id], x); }, // TODO - glUniform1iv // TODO - glUniform2f // TODO - glUniform2fv // TODO - glUniform2i // TODO - glUniform2iv // TODO - glUniform3f // TODO - glUniform3fv // TODO - glUniform3i // TODO - glUniform3iv Func{ .name = "glUniform4f", .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "x", .type = "f32" }, .{ .name = "y", .type = "f32" }, .{ .name = "z", .type = "f32" }, .{ .name = "w", .type = "f32" }, }, .ret = "void", .js = \\gl.uniform4f(glUniformLocations[location_id], x, y, z, w); }, // TODO - glUniform4fv // TODO - glUniform4i // TODO - glUniform4iv // TODO - glUniformMatrix2fv // TODO - glUniformMatrix3fv Func{ .name = "glUniformMatrix4fv", // FIXME - take three args, not four.. transpose should be second arg .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "data_len", .type = "c_int" }, .{ .name = "transpose", .type = "c_uint" }, .{ .name = "data_ptr", .type = "[*]const f32" }, }, .ret = "void", .js = \\const floats = new Float32Array(getMemory().buffer, data_ptr, data_len * 16); \\gl.uniformMatrix4fv(glUniformLocations[location_id], transpose, floats); }, Func{ .name = "glUseProgram", .args = &[_]Arg{ .{ .name = "program_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.useProgram(glPrograms[program_id]); }, // TODO - glValidateProgram // TODO - glVertexAttrib1f // TODO - glVertexAttrib1fv // TODO - glVertexAttrib2f // TODO - glVertexAttrib2fv // TODO - glVertexAttrib3f // TODO - glVertexAttrib3fv // TODO - glVertexAttrib4f // TODO - glVertexAttrib4fv Func{ .name = "glVertexAttribPointer", .args = &[_]Arg{ .{ .name = "attrib_location", .type = "c_uint" }, .{ .name = "size", .type = "c_uint" }, .{ .name = "type", .type = "c_uint" }, .{ .name = "normalize", .type = "c_uint" }, .{ .name = "stride", .type = "c_uint" }, .{ .name = "offset", .type = "?*c_void" }, }, .ret = "void", .js = \\gl.vertexAttribPointer(attrib_location, size, type, normalize, stride, offset); }, Func{ .name = "glViewport", .args = &[_]Arg{ .{ .name = "x", .type = "c_int" }, .{ .name = "y", .type = "c_int" }, .{ .name = "width", .type = "c_int" }, .{ .name = "height", .type = "c_int" }, }, .ret = "void", .js = \\gl.viewport(x, y, width, height); }, }; fn nextNewline(s: []const u8) usize { for (s) |ch, i| { if (ch == '\n') { return i; } } return s.len; } fn writeZigFile(filename: []const u8) !void { const file = try std.fs.cwd().createFile(filename, .{}); defer file.close(); var stream = file.outStream(); try stream.print("{}\n\n", .{zig_top}); for (funcs) |func| { const any_slice = for (func.args) |arg| { if (std.mem.eql(u8, arg.type, "SLICE")) { break true; } } else false; // https://github.com/ziglang/zig/issues/3882 const fmtarg_pub = if (any_slice) "" else "pub "; const fmtarg_suf = if (any_slice) "_" else ""; try stream.print("{}extern fn {}{}(", .{ fmtarg_pub, func.name, fmtarg_suf }); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}_ptr: [*]const u8, {}_len: c_uint", .{ arg.name, arg.name }); } else { try stream.print("{}: {}", .{ arg.name, arg.type }); } } try stream.print(") {};\n", .{func.ret}); if (any_slice) { try stream.print("pub fn {}(", .{func.name}); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}: []const u8", .{arg.name}); } else { try stream.print("{}: {}", .{ arg.name, arg.type }); } } try stream.print(") {} {{\n", .{func.ret}); // https://github.com/ziglang/zig/issues/3882 const fmtarg_ret = if (std.mem.eql(u8, func.ret, "void")) "" else "return "; try stream.print(" {}{}_(", .{ fmtarg_ret, func.name }); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}.ptr, {}.len", .{ arg.name, arg.name }); } else { try stream.print("{}", .{arg.name}); } } try stream.print(");\n", .{}); try stream.print("}}\n", .{}); } } } fn writeJsFile(filename: []const u8) !void { const file = try std.fs.cwd().createFile(filename, .{}); defer file.close(); var stream = file.outStream(); try stream.print("{}\n", .{js_top}); try stream.print(" return {{\n", .{}); for (funcs) |func| { const any_slice = for (func.args) |arg| { if (std.mem.eql(u8, arg.type, "SLICE")) { break true; } } else false; // https://github.com/ziglang/zig/issues/3882 const fmtarg_suf = if (any_slice) "_" else ""; try stream.print(" {}{}(", .{ func.name, fmtarg_suf }); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}_ptr, {}_len", .{ arg.name, arg.name }); } else { try stream.print("{}", .{arg.name}); } } try stream.print(") {{\n", .{}); for (func.args) |arg| { if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print(" const {} = readCharStr({}_ptr, {}_len);\n", .{ arg.name, arg.name, arg.name }); } } var start: usize = 0; while (start < func.js.len) { const rel_newline_pos = nextNewline(func.js[start..]); try stream.print(" {}\n", .{func.js[start .. start + rel_newline_pos]}); start += rel_newline_pos + 1; } try stream.print(" }},\n", .{}); } try stream.print(" }};\n", .{}); try stream.print("{}\n", .{js_bottom}); } pub fn main() !void { try writeZigFile("src/platform/web/webgl_generated.zig"); try writeJsFile("js/webgl.js"); }
https://raw.githubusercontent.com/leroycep/hexagonal-chess/ebc60fe485830eccebab5641b0d0523231f40bc5/tools/webgl_generate.zig
pub const __builtin_bswap16 = @import("std").zig.c_builtins.__builtin_bswap16; pub const __builtin_bswap32 = @import("std").zig.c_builtins.__builtin_bswap32; pub const __builtin_bswap64 = @import("std").zig.c_builtins.__builtin_bswap64; pub const __builtin_signbit = @import("std").zig.c_builtins.__builtin_signbit; pub const __builtin_signbitf = @import("std").zig.c_builtins.__builtin_signbitf; pub const __builtin_popcount = @import("std").zig.c_builtins.__builtin_popcount; pub const __builtin_ctz = @import("std").zig.c_builtins.__builtin_ctz; pub const __builtin_clz = @import("std").zig.c_builtins.__builtin_clz; pub const __builtin_sqrt = @import("std").zig.c_builtins.__builtin_sqrt; pub const __builtin_sqrtf = @import("std").zig.c_builtins.__builtin_sqrtf; pub const __builtin_sin = @import("std").zig.c_builtins.__builtin_sin; pub const __builtin_sinf = @import("std").zig.c_builtins.__builtin_sinf; pub const __builtin_cos = @import("std").zig.c_builtins.__builtin_cos; pub const __builtin_cosf = @import("std").zig.c_builtins.__builtin_cosf; pub const __builtin_exp = @import("std").zig.c_builtins.__builtin_exp; pub const __builtin_expf = @import("std").zig.c_builtins.__builtin_expf; pub const __builtin_exp2 = @import("std").zig.c_builtins.__builtin_exp2; pub const __builtin_exp2f = @import("std").zig.c_builtins.__builtin_exp2f; pub const __builtin_log = @import("std").zig.c_builtins.__builtin_log; pub const __builtin_logf = @import("std").zig.c_builtins.__builtin_logf; pub const __builtin_log2 = @import("std").zig.c_builtins.__builtin_log2; pub const __builtin_log2f = @import("std").zig.c_builtins.__builtin_log2f; pub const __builtin_log10 = @import("std").zig.c_builtins.__builtin_log10; pub const __builtin_log10f = @import("std").zig.c_builtins.__builtin_log10f; pub const __builtin_abs = @import("std").zig.c_builtins.__builtin_abs; pub const __builtin_fabs = @import("std").zig.c_builtins.__builtin_fabs; pub const __builtin_fabsf = @import("std").zig.c_builtins.__builtin_fabsf; pub const __builtin_floor = @import("std").zig.c_builtins.__builtin_floor; pub const __builtin_floorf = @import("std").zig.c_builtins.__builtin_floorf; pub const __builtin_ceil = @import("std").zig.c_builtins.__builtin_ceil; pub const __builtin_ceilf = @import("std").zig.c_builtins.__builtin_ceilf; pub const __builtin_trunc = @import("std").zig.c_builtins.__builtin_trunc; pub const __builtin_truncf = @import("std").zig.c_builtins.__builtin_truncf; pub const __builtin_round = @import("std").zig.c_builtins.__builtin_round; pub const __builtin_roundf = @import("std").zig.c_builtins.__builtin_roundf; pub const __builtin_strlen = @import("std").zig.c_builtins.__builtin_strlen; pub const __builtin_strcmp = @import("std").zig.c_builtins.__builtin_strcmp; pub const __builtin_object_size = @import("std").zig.c_builtins.__builtin_object_size; pub const __builtin___memset_chk = @import("std").zig.c_builtins.__builtin___memset_chk; pub const __builtin_memset = @import("std").zig.c_builtins.__builtin_memset; pub const __builtin___memcpy_chk = @import("std").zig.c_builtins.__builtin___memcpy_chk; pub const __builtin_memcpy = @import("std").zig.c_builtins.__builtin_memcpy; pub const __builtin_expect = @import("std").zig.c_builtins.__builtin_expect; pub const __builtin_nanf = @import("std").zig.c_builtins.__builtin_nanf; pub const __builtin_huge_valf = @import("std").zig.c_builtins.__builtin_huge_valf; pub const __builtin_inff = @import("std").zig.c_builtins.__builtin_inff; pub const __builtin_isnan = @import("std").zig.c_builtins.__builtin_isnan; pub const __builtin_isinf = @import("std").zig.c_builtins.__builtin_isinf; pub const __builtin_isinf_sign = @import("std").zig.c_builtins.__builtin_isinf_sign; pub const struct___va_list_tag = extern struct { gp_offset: c_uint, fp_offset: c_uint, overflow_arg_area: ?*anyopaque, reg_save_area: ?*anyopaque, }; pub const __builtin_va_list = [1]struct___va_list_tag; pub const va_list = __builtin_va_list; pub const __gnuc_va_list = __builtin_va_list; pub const __u_char = u8; pub const __u_short = c_ushort; pub const __u_int = c_uint; pub const __u_long = c_ulong; pub const __int8_t = i8; pub const __uint8_t = u8; pub const __int16_t = c_short; pub const __uint16_t = c_ushort; pub const __int32_t = c_int; pub const __uint32_t = c_uint; pub const __int64_t = c_long; pub const __uint64_t = c_ulong; pub const __int_least8_t = __int8_t; pub const __uint_least8_t = __uint8_t; pub const __int_least16_t = __int16_t; pub const __uint_least16_t = __uint16_t; pub const __int_least32_t = __int32_t; pub const __uint_least32_t = __uint32_t; pub const __int_least64_t = __int64_t; pub const __uint_least64_t = __uint64_t; pub const __quad_t = c_long; pub const __u_quad_t = c_ulong; pub const __intmax_t = c_long; pub const __uintmax_t = c_ulong; pub const __dev_t = c_ulong; pub const __uid_t = c_uint; pub const __gid_t = c_uint; pub const __ino_t = c_ulong; pub const __ino64_t = c_ulong; pub const __mode_t = c_uint; pub const __nlink_t = c_ulong; pub const __off_t = c_long; pub const __off64_t = c_long; pub const __pid_t = c_int; pub const __fsid_t = extern struct { __val: [2]c_int, }; pub const __clock_t = c_long; pub const __rlim_t = c_ulong; pub const __rlim64_t = c_ulong; pub const __id_t = c_uint; pub const __time_t = c_long; pub const __useconds_t = c_uint; pub const __suseconds_t = c_long; pub const __suseconds64_t = c_long; pub const __daddr_t = c_int; pub const __key_t = c_int; pub const __clockid_t = c_int; pub const __timer_t = ?*anyopaque; pub const __blksize_t = c_long; pub const __blkcnt_t = c_long; pub const __blkcnt64_t = c_long; pub const __fsblkcnt_t = c_ulong; pub const __fsblkcnt64_t = c_ulong; pub const __fsfilcnt_t = c_ulong; pub const __fsfilcnt64_t = c_ulong; pub const __fsword_t = c_long; pub const __ssize_t = c_long; pub const __syscall_slong_t = c_long; pub const __syscall_ulong_t = c_ulong; pub const __loff_t = __off64_t; pub const __caddr_t = [*c]u8; pub const __intptr_t = c_long; pub const __socklen_t = c_uint; pub const __sig_atomic_t = c_int; const union_unnamed_1 = extern union { __wch: c_uint, __wchb: [4]u8, }; pub const __mbstate_t = extern struct { __count: c_int, __value: union_unnamed_1, }; pub const struct__G_fpos_t = extern struct { __pos: __off_t, __state: __mbstate_t, }; pub const __fpos_t = struct__G_fpos_t; pub const struct__G_fpos64_t = extern struct { __pos: __off64_t, __state: __mbstate_t, }; pub const __fpos64_t = struct__G_fpos64_t; pub const struct__IO_marker = opaque {}; pub const _IO_lock_t = anyopaque; pub const struct__IO_codecvt = opaque {}; pub const struct__IO_wide_data = opaque {}; pub const struct__IO_FILE = extern struct { _flags: c_int, _IO_read_ptr: [*c]u8, _IO_read_end: [*c]u8, _IO_read_base: [*c]u8, _IO_write_base: [*c]u8, _IO_write_ptr: [*c]u8, _IO_write_end: [*c]u8, _IO_buf_base: [*c]u8, _IO_buf_end: [*c]u8, _IO_save_base: [*c]u8, _IO_backup_base: [*c]u8, _IO_save_end: [*c]u8, _markers: ?*struct__IO_marker, _chain: [*c]struct__IO_FILE, _fileno: c_int, _flags2: c_int, _old_offset: __off_t, _cur_column: c_ushort, _vtable_offset: i8, _shortbuf: [1]u8, _lock: ?*_IO_lock_t, _offset: __off64_t, _codecvt: ?*struct__IO_codecvt, _wide_data: ?*struct__IO_wide_data, _freeres_list: [*c]struct__IO_FILE, _freeres_buf: ?*anyopaque, __pad5: usize, _mode: c_int, _unused2: [20]u8, }; pub const __FILE = struct__IO_FILE; pub const FILE = struct__IO_FILE; pub const off_t = __off_t; pub const fpos_t = __fpos_t; pub extern var stdin: [*c]FILE; pub extern var stdout: [*c]FILE; pub extern var stderr: [*c]FILE; pub extern fn remove(__filename: [*c]const u8) c_int; pub extern fn rename(__old: [*c]const u8, __new: [*c]const u8) c_int; pub extern fn renameat(__oldfd: c_int, __old: [*c]const u8, __newfd: c_int, __new: [*c]const u8) c_int; pub extern fn fclose(__stream: [*c]FILE) c_int; pub extern fn tmpfile() [*c]FILE; pub extern fn tmpnam([*c]u8) [*c]u8; pub extern fn tmpnam_r(__s: [*c]u8) [*c]u8; pub extern fn tempnam(__dir: [*c]const u8, __pfx: [*c]const u8) [*c]u8; pub extern fn fflush(__stream: [*c]FILE) c_int; pub extern fn fflush_unlocked(__stream: [*c]FILE) c_int; pub extern fn fopen(__filename: [*c]const u8, __modes: [*c]const u8) [*c]FILE; pub extern fn freopen(noalias __filename: [*c]const u8, noalias __modes: [*c]const u8, noalias __stream: [*c]FILE) [*c]FILE; pub extern fn fdopen(__fd: c_int, __modes: [*c]const u8) [*c]FILE; pub extern fn fmemopen(__s: ?*anyopaque, __len: usize, __modes: [*c]const u8) [*c]FILE; pub extern fn open_memstream(__bufloc: [*c][*c]u8, __sizeloc: [*c]usize) [*c]FILE; pub extern fn setbuf(noalias __stream: [*c]FILE, noalias __buf: [*c]u8) void; pub extern fn setvbuf(noalias __stream: [*c]FILE, noalias __buf: [*c]u8, __modes: c_int, __n: usize) c_int; pub extern fn setbuffer(noalias __stream: [*c]FILE, noalias __buf: [*c]u8, __size: usize) void; pub extern fn setlinebuf(__stream: [*c]FILE) void; pub extern fn fprintf(__stream: [*c]FILE, __format: [*c]const u8, ...) c_int; pub extern fn printf(__format: [*c]const u8, ...) c_int; pub extern fn sprintf(__s: [*c]u8, __format: [*c]const u8, ...) c_int; pub extern fn vfprintf(__s: [*c]FILE, __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub fn vprintf(arg___fmt: [*c]const u8, arg___arg: [*c]struct___va_list_tag) callconv(.C) c_int { var __fmt = arg___fmt; var __arg = arg___arg; return vfprintf(stdout, __fmt, __arg); } pub extern fn vsprintf(__s: [*c]u8, __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn snprintf(__s: [*c]u8, __maxlen: c_ulong, __format: [*c]const u8, ...) c_int; pub extern fn vsnprintf(__s: [*c]u8, __maxlen: c_ulong, __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vdprintf(__fd: c_int, noalias __fmt: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn dprintf(__fd: c_int, noalias __fmt: [*c]const u8, ...) c_int; pub extern fn fscanf(noalias __stream: [*c]FILE, noalias __format: [*c]const u8, ...) c_int; pub extern fn scanf(noalias __format: [*c]const u8, ...) c_int; pub extern fn sscanf(noalias __s: [*c]const u8, noalias __format: [*c]const u8, ...) c_int; pub const _Float32 = f32; pub const _Float64 = f64; pub const _Float32x = f64; pub const _Float64x = c_longdouble; pub extern fn vfscanf(noalias __s: [*c]FILE, noalias __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vscanf(noalias __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn vsscanf(noalias __s: [*c]const u8, noalias __format: [*c]const u8, __arg: [*c]struct___va_list_tag) c_int; pub extern fn fgetc(__stream: [*c]FILE) c_int; pub extern fn getc(__stream: [*c]FILE) c_int; pub fn getchar() callconv(.C) c_int { return getc(stdin); } pub fn getc_unlocked(arg___fp: [*c]FILE) callconv(.C) c_int { var __fp = arg___fp; return if (__builtin_expect(@bitCast(c_long, @as(c_long, @boolToInt(__fp.*._IO_read_ptr >= __fp.*._IO_read_end))), @bitCast(c_long, @as(c_long, @as(c_int, 0)))) != 0) __uflow(__fp) else @bitCast(c_int, @as(c_uint, @ptrCast([*c]u8, @alignCast(@import("std").meta.alignment(u8), blk: { const ref = &__fp.*._IO_read_ptr; const tmp = ref.*; ref.* += 1; break :blk tmp; })).*)); } pub fn getchar_unlocked() callconv(.C) c_int { return if (__builtin_expect(@bitCast(c_long, @as(c_long, @boolToInt(stdin.*._IO_read_ptr >= stdin.*._IO_read_end))), @bitCast(c_long, @as(c_long, @as(c_int, 0)))) != 0) __uflow(stdin) else @bitCast(c_int, @as(c_uint, @ptrCast([*c]u8, @alignCast(@import("std").meta.alignment(u8), blk: { const ref = &stdin.*._IO_read_ptr; const tmp = ref.*; ref.* += 1; break :blk tmp; })).*)); } pub fn fgetc_unlocked(arg___fp: [*c]FILE) callconv(.C) c_int { var __fp = arg___fp; return if (__builtin_expect(@bitCast(c_long, @as(c_long, @boolToInt(__fp.*._IO_read_ptr >= __fp.*._IO_read_end))), @bitCast(c_long, @as(c_long, @as(c_int, 0)))) != 0) __uflow(__fp) else @bitCast(c_int, @as(c_uint, @ptrCast([*c]u8, @alignCast(@import("std").meta.alignment(u8), blk: { const ref = &__fp.*._IO_read_ptr; const tmp = ref.*; ref.* += 1; break :blk tmp; })).*)); } pub extern fn fputc(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn putc(__c: c_int, __stream: [*c]FILE) c_int; pub fn putchar(arg___c: c_int) callconv(.C) c_int { var __c = arg___c; return putc(__c, stdout); } pub fn fputc_unlocked(arg___c: c_int, arg___stream: [*c]FILE) callconv(.C) c_int { var __c = arg___c; var __stream = arg___stream; return if (__builtin_expect(@bitCast(c_long, @as(c_long, @boolToInt(__stream.*._IO_write_ptr >= __stream.*._IO_write_end))), @bitCast(c_long, @as(c_long, @as(c_int, 0)))) != 0) __overflow(__stream, @bitCast(c_int, @as(c_uint, @bitCast(u8, @truncate(i8, __c))))) else @bitCast(c_int, @as(c_uint, @bitCast(u8, blk: { const tmp = @bitCast(u8, @truncate(i8, __c)); (blk_1: { const ref = &__stream.*._IO_write_ptr; const tmp_2 = ref.*; ref.* += 1; break :blk_1 tmp_2; }).* = tmp; break :blk tmp; }))); } pub fn putc_unlocked(arg___c: c_int, arg___stream: [*c]FILE) callconv(.C) c_int { var __c = arg___c; var __stream = arg___stream; return if (__builtin_expect(@bitCast(c_long, @as(c_long, @boolToInt(__stream.*._IO_write_ptr >= __stream.*._IO_write_end))), @bitCast(c_long, @as(c_long, @as(c_int, 0)))) != 0) __overflow(__stream, @bitCast(c_int, @as(c_uint, @bitCast(u8, @truncate(i8, __c))))) else @bitCast(c_int, @as(c_uint, @bitCast(u8, blk: { const tmp = @bitCast(u8, @truncate(i8, __c)); (blk_1: { const ref = &__stream.*._IO_write_ptr; const tmp_2 = ref.*; ref.* += 1; break :blk_1 tmp_2; }).* = tmp; break :blk tmp; }))); } pub fn putchar_unlocked(arg___c: c_int) callconv(.C) c_int { var __c = arg___c; return if (__builtin_expect(@bitCast(c_long, @as(c_long, @boolToInt(stdout.*._IO_write_ptr >= stdout.*._IO_write_end))), @bitCast(c_long, @as(c_long, @as(c_int, 0)))) != 0) __overflow(stdout, @bitCast(c_int, @as(c_uint, @bitCast(u8, @truncate(i8, __c))))) else @bitCast(c_int, @as(c_uint, @bitCast(u8, blk: { const tmp = @bitCast(u8, @truncate(i8, __c)); (blk_1: { const ref = &stdout.*._IO_write_ptr; const tmp_2 = ref.*; ref.* += 1; break :blk_1 tmp_2; }).* = tmp; break :blk tmp; }))); } pub extern fn getw(__stream: [*c]FILE) c_int; pub extern fn putw(__w: c_int, __stream: [*c]FILE) c_int; pub extern fn fgets(noalias __s: [*c]u8, __n: c_int, noalias __stream: [*c]FILE) [*c]u8; pub extern fn __getdelim(noalias __lineptr: [*c][*c]u8, noalias __n: [*c]usize, __delimiter: c_int, noalias __stream: [*c]FILE) __ssize_t; pub extern fn getdelim(noalias __lineptr: [*c][*c]u8, noalias __n: [*c]usize, __delimiter: c_int, noalias __stream: [*c]FILE) __ssize_t; pub extern fn getline(noalias __lineptr: [*c][*c]u8, noalias __n: [*c]usize, noalias __stream: [*c]FILE) __ssize_t; pub extern fn fputs(noalias __s: [*c]const u8, noalias __stream: [*c]FILE) c_int; pub extern fn puts(__s: [*c]const u8) c_int; pub extern fn ungetc(__c: c_int, __stream: [*c]FILE) c_int; pub extern fn fread(__ptr: ?*anyopaque, __size: c_ulong, __n: c_ulong, __stream: [*c]FILE) c_ulong; pub extern fn fwrite(__ptr: ?*const anyopaque, __size: c_ulong, __n: c_ulong, __s: [*c]FILE) c_ulong; pub extern fn fread_unlocked(noalias __ptr: ?*anyopaque, __size: usize, __n: usize, noalias __stream: [*c]FILE) usize; pub extern fn fwrite_unlocked(noalias __ptr: ?*const anyopaque, __size: usize, __n: usize, noalias __stream: [*c]FILE) usize; pub extern fn fseek(__stream: [*c]FILE, __off: c_long, __whence: c_int) c_int; pub extern fn ftell(__stream: [*c]FILE) c_long; pub extern fn rewind(__stream: [*c]FILE) void; pub extern fn fseeko(__stream: [*c]FILE, __off: __off_t, __whence: c_int) c_int; pub extern fn ftello(__stream: [*c]FILE) __off_t; pub extern fn fgetpos(noalias __stream: [*c]FILE, noalias __pos: [*c]fpos_t) c_int; pub extern fn fsetpos(__stream: [*c]FILE, __pos: [*c]const fpos_t) c_int; pub extern fn clearerr(__stream: [*c]FILE) void; pub extern fn feof(__stream: [*c]FILE) c_int; pub extern fn ferror(__stream: [*c]FILE) c_int; pub extern fn clearerr_unlocked(__stream: [*c]FILE) void; pub fn feof_unlocked(arg___stream: [*c]FILE) callconv(.C) c_int { var __stream = arg___stream; return @boolToInt((__stream.*._flags & @as(c_int, 16)) != @as(c_int, 0)); } pub fn ferror_unlocked(arg___stream: [*c]FILE) callconv(.C) c_int { var __stream = arg___stream; return @boolToInt((__stream.*._flags & @as(c_int, 32)) != @as(c_int, 0)); } pub extern fn perror(__s: [*c]const u8) void; pub extern fn fileno(__stream: [*c]FILE) c_int; pub extern fn fileno_unlocked(__stream: [*c]FILE) c_int; pub extern fn pclose(__stream: [*c]FILE) c_int; pub extern fn popen(__command: [*c]const u8, __modes: [*c]const u8) [*c]FILE; pub extern fn ctermid(__s: [*c]u8) [*c]u8; pub extern fn flockfile(__stream: [*c]FILE) void; pub extern fn ftrylockfile(__stream: [*c]FILE) c_int; pub extern fn funlockfile(__stream: [*c]FILE) void; pub extern fn __uflow([*c]FILE) c_int; pub extern fn __overflow([*c]FILE, c_int) c_int; pub extern fn memcpy(__dest: ?*anyopaque, __src: ?*const anyopaque, __n: c_ulong) ?*anyopaque; pub extern fn memmove(__dest: ?*anyopaque, __src: ?*const anyopaque, __n: c_ulong) ?*anyopaque; pub extern fn memccpy(__dest: ?*anyopaque, __src: ?*const anyopaque, __c: c_int, __n: c_ulong) ?*anyopaque; pub extern fn memset(__s: ?*anyopaque, __c: c_int, __n: c_ulong) ?*anyopaque; pub extern fn memcmp(__s1: ?*const anyopaque, __s2: ?*const anyopaque, __n: c_ulong) c_int; pub extern fn memchr(__s: ?*const anyopaque, __c: c_int, __n: c_ulong) ?*anyopaque; pub extern fn strcpy(__dest: [*c]u8, __src: [*c]const u8) [*c]u8; pub extern fn strncpy(__dest: [*c]u8, __src: [*c]const u8, __n: c_ulong) [*c]u8; pub extern fn strcat(__dest: [*c]u8, __src: [*c]const u8) [*c]u8; pub extern fn strncat(__dest: [*c]u8, __src: [*c]const u8, __n: c_ulong) [*c]u8; pub extern fn strcmp(__s1: [*c]const u8, __s2: [*c]const u8) c_int; pub extern fn strncmp(__s1: [*c]const u8, __s2: [*c]const u8, __n: c_ulong) c_int; pub extern fn strcoll(__s1: [*c]const u8, __s2: [*c]const u8) c_int; pub extern fn strxfrm(__dest: [*c]u8, __src: [*c]const u8, __n: c_ulong) c_ulong; pub const struct___locale_data = opaque {}; pub const struct___locale_struct = extern struct { __locales: [13]?*struct___locale_data, __ctype_b: [*c]const c_ushort, __ctype_tolower: [*c]const c_int, __ctype_toupper: [*c]const c_int, __names: [13][*c]const u8, }; pub const __locale_t = [*c]struct___locale_struct; pub const locale_t = __locale_t; pub extern fn strcoll_l(__s1: [*c]const u8, __s2: [*c]const u8, __l: locale_t) c_int; pub extern fn strxfrm_l(__dest: [*c]u8, __src: [*c]const u8, __n: usize, __l: locale_t) usize; pub extern fn strdup(__s: [*c]const u8) [*c]u8; pub extern fn strndup(__string: [*c]const u8, __n: c_ulong) [*c]u8; pub extern fn strchr(__s: [*c]const u8, __c: c_int) [*c]u8; pub extern fn strrchr(__s: [*c]const u8, __c: c_int) [*c]u8; pub extern fn strcspn(__s: [*c]const u8, __reject: [*c]const u8) c_ulong; pub extern fn strspn(__s: [*c]const u8, __accept: [*c]const u8) c_ulong; pub extern fn strpbrk(__s: [*c]const u8, __accept: [*c]const u8) [*c]u8; pub extern fn strstr(__haystack: [*c]const u8, __needle: [*c]const u8) [*c]u8; pub extern fn strtok(__s: [*c]u8, __delim: [*c]const u8) [*c]u8; pub extern fn __strtok_r(noalias __s: [*c]u8, noalias __delim: [*c]const u8, noalias __save_ptr: [*c][*c]u8) [*c]u8; pub extern fn strtok_r(noalias __s: [*c]u8, noalias __delim: [*c]const u8, noalias __save_ptr: [*c][*c]u8) [*c]u8; pub extern fn strlen(__s: [*c]const u8) c_ulong; pub extern fn strnlen(__string: [*c]const u8, __maxlen: usize) usize; pub extern fn strerror(__errnum: c_int) [*c]u8; pub extern fn strerror_r(__errnum: c_int, __buf: [*c]u8, __buflen: usize) c_int; pub extern fn strerror_l(__errnum: c_int, __l: locale_t) [*c]u8; pub extern fn bcmp(__s1: ?*const anyopaque, __s2: ?*const anyopaque, __n: c_ulong) c_int; pub extern fn bcopy(__src: ?*const anyopaque, __dest: ?*anyopaque, __n: usize) void; pub extern fn bzero(__s: ?*anyopaque, __n: c_ulong) void; pub extern fn index(__s: [*c]const u8, __c: c_int) [*c]u8; pub extern fn rindex(__s: [*c]const u8, __c: c_int) [*c]u8; pub extern fn ffs(__i: c_int) c_int; pub extern fn ffsl(__l: c_long) c_int; pub extern fn ffsll(__ll: c_longlong) c_int; pub extern fn strcasecmp(__s1: [*c]const u8, __s2: [*c]const u8) c_int; pub extern fn strncasecmp(__s1: [*c]const u8, __s2: [*c]const u8, __n: c_ulong) c_int; pub extern fn strcasecmp_l(__s1: [*c]const u8, __s2: [*c]const u8, __loc: locale_t) c_int; pub extern fn strncasecmp_l(__s1: [*c]const u8, __s2: [*c]const u8, __n: usize, __loc: locale_t) c_int; pub extern fn explicit_bzero(__s: ?*anyopaque, __n: usize) void; pub extern fn strsep(noalias __stringp: [*c][*c]u8, noalias __delim: [*c]const u8) [*c]u8; pub extern fn strsignal(__sig: c_int) [*c]u8; pub extern fn __stpcpy(noalias __dest: [*c]u8, noalias __src: [*c]const u8) [*c]u8; pub extern fn stpcpy(__dest: [*c]u8, __src: [*c]const u8) [*c]u8; pub extern fn __stpncpy(noalias __dest: [*c]u8, noalias __src: [*c]const u8, __n: usize) [*c]u8; pub extern fn stpncpy(__dest: [*c]u8, __src: [*c]const u8, __n: c_ulong) [*c]u8; pub extern fn scan_line(input: [*c]u8) void; pub const __INTMAX_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `L`"); // (no file):67:9 pub const __UINTMAX_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `UL`"); // (no file):73:9 pub const __INT64_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `L`"); // (no file):164:9 pub const __UINT32_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `U`"); // (no file):186:9 pub const __UINT64_C_SUFFIX__ = @compileError("unable to translate macro: undefined identifier `UL`"); // (no file):194:9 pub const __seg_gs = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):315:9 pub const __seg_fs = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // (no file):316:9 pub const __GLIBC_USE = @compileError("unable to translate macro: undefined identifier `__GLIBC_USE_`"); // /snap/zig/4722/lib/libc/include/generic-glibc/features.h:186:9 pub const __glibc_has_attribute = @compileError("unable to translate macro: undefined identifier `__has_attribute`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:44:10 pub const __glibc_has_builtin = @compileError("unable to translate macro: undefined identifier `__has_builtin`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:49:10 pub const __glibc_has_extension = @compileError("unable to translate macro: undefined identifier `__has_extension`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:54:10 pub const __THROW = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:78:11 pub const __THROWNL = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:79:11 pub const __NTH = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:80:11 pub const __NTHNL = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:81:11 pub const __CONCAT = @compileError("unable to translate C expr: unexpected token .HashHash"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:123:9 pub const __STRING = @compileError("unable to translate C expr: unexpected token .Hash"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:124:9 pub const __warnattr = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:158:10 pub const __errordecl = @compileError("unable to translate C expr: unexpected token .Keyword_extern"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:159:10 pub const __flexarr = @compileError("unable to translate C expr: unexpected token .LBracket"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:167:10 pub const __REDIRECT = @compileError("unable to translate macro: undefined identifier `__asm__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:198:10 pub const __REDIRECT_NTH = @compileError("unable to translate macro: undefined identifier `__asm__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:205:11 pub const __REDIRECT_NTHNL = @compileError("unable to translate macro: undefined identifier `__asm__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:207:11 pub const __ASMNAME2 = @compileError("unable to translate C expr: unexpected token .Identifier"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:211:10 pub const __attribute_malloc__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:232:10 pub const __attribute_alloc_size__ = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:243:10 pub const __attribute_pure__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:250:10 pub const __attribute_const__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:257:10 pub const __attribute_maybe_unused__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:263:10 pub const __attribute_used__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:272:10 pub const __attribute_noinline__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:273:10 pub const __attribute_deprecated__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:281:10 pub const __attribute_deprecated_msg__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:291:10 pub const __attribute_format_arg__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:304:10 pub const __attribute_format_strfmon__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:314:10 pub const __nonnull = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:324:11 pub const __returns_nonnull = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:337:10 pub const __attribute_warn_unused_result__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:346:10 pub const __always_inline = @compileError("unable to translate macro: undefined identifier `__inline`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:364:10 pub const __attribute_artificial__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:373:10 pub const __extern_inline = @compileError("unable to translate macro: undefined identifier `__inline`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:391:11 pub const __extern_always_inline = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:392:11 pub const __restrict_arr = @compileError("unable to translate macro: undefined identifier `__restrict`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:435:10 pub const __attribute_copy__ = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:484:10 pub const __LDBL_REDIR2_DECL = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:560:10 pub const __LDBL_REDIR_DECL = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:561:10 pub const __glibc_macro_warning1 = @compileError("unable to translate macro: undefined identifier `_Pragma`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:575:10 pub const __glibc_macro_warning = @compileError("unable to translate macro: undefined identifier `GCC`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:576:10 pub const __attr_access = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:612:11 pub const __attr_access_none = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:613:11 pub const __attr_dealloc = @compileError("unable to translate C expr: unexpected token .Eof"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:623:10 pub const __attribute_returns_twice__ = @compileError("unable to translate macro: undefined identifier `__attribute__`"); // /snap/zig/4722/lib/libc/include/generic-glibc/sys/cdefs.h:630:10 pub const va_start = @compileError("unable to translate macro: undefined identifier `__builtin_va_start`"); // /snap/zig/4722/lib/include/stdarg.h:17:9 pub const va_end = @compileError("unable to translate macro: undefined identifier `__builtin_va_end`"); // /snap/zig/4722/lib/include/stdarg.h:18:9 pub const va_arg = @compileError("unable to translate macro: undefined identifier `__builtin_va_arg`"); // /snap/zig/4722/lib/include/stdarg.h:19:9 pub const __va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // /snap/zig/4722/lib/include/stdarg.h:24:9 pub const va_copy = @compileError("unable to translate macro: undefined identifier `__builtin_va_copy`"); // /snap/zig/4722/lib/include/stdarg.h:27:9 pub const __STD_TYPE = @compileError("unable to translate C expr: unexpected token .Keyword_typedef"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/types.h:137:10 pub const __FSID_T_TYPE = @compileError("unable to translate macro: undefined identifier `__val`"); // /snap/zig/4722/lib/libc/include/x86_64-linux-gnu/bits/typesizes.h:73:9 pub const __getc_unlocked_body = @compileError("TODO postfix inc/dec expr"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/types/struct_FILE.h:102:9 pub const __putc_unlocked_body = @compileError("TODO postfix inc/dec expr"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/types/struct_FILE.h:106:9 pub const __f32 = @compileError("unable to translate macro: undefined identifier `f`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:91:12 pub const __f64x = @compileError("unable to translate macro: undefined identifier `l`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:120:13 pub const __CFLOAT32 = @compileError("unable to translate: TODO _Complex"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:149:12 pub const __CFLOAT64 = @compileError("unable to translate: TODO _Complex"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:160:13 pub const __CFLOAT32X = @compileError("unable to translate: TODO _Complex"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:169:12 pub const __CFLOAT64X = @compileError("unable to translate: TODO _Complex"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:178:13 pub const __builtin_nansf32 = @compileError("unable to translate macro: undefined identifier `__builtin_nansf`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:221:12 pub const __builtin_huge_valf64 = @compileError("unable to translate macro: undefined identifier `__builtin_huge_val`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:255:13 pub const __builtin_inff64 = @compileError("unable to translate macro: undefined identifier `__builtin_inf`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:256:13 pub const __builtin_nanf64 = @compileError("unable to translate macro: undefined identifier `__builtin_nan`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:257:13 pub const __builtin_nansf64 = @compileError("unable to translate macro: undefined identifier `__builtin_nans`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:258:13 pub const __builtin_huge_valf32x = @compileError("unable to translate macro: undefined identifier `__builtin_huge_val`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:272:12 pub const __builtin_inff32x = @compileError("unable to translate macro: undefined identifier `__builtin_inf`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:273:12 pub const __builtin_nanf32x = @compileError("unable to translate macro: undefined identifier `__builtin_nan`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:274:12 pub const __builtin_nansf32x = @compileError("unable to translate macro: undefined identifier `__builtin_nans`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:275:12 pub const __builtin_huge_valf64x = @compileError("unable to translate macro: undefined identifier `__builtin_huge_vall`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:289:13 pub const __builtin_inff64x = @compileError("unable to translate macro: undefined identifier `__builtin_infl`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:290:13 pub const __builtin_nanf64x = @compileError("unable to translate macro: undefined identifier `__builtin_nanl`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:291:13 pub const __builtin_nansf64x = @compileError("unable to translate macro: undefined identifier `__builtin_nansl`"); // /snap/zig/4722/lib/libc/include/generic-glibc/bits/floatn-common.h:292:13 pub const __llvm__ = @as(c_int, 1); pub const __clang__ = @as(c_int, 1); pub const __clang_major__ = @as(c_int, 13); pub const __clang_minor__ = @as(c_int, 0); pub const __clang_patchlevel__ = @as(c_int, 1); pub const __clang_version__ = "13.0.1 (git@github.com:ziglang/zig-bootstrap.git 81f0e6c5b902ead84753490db4f0007d08df964a)"; pub const __GNUC__ = @as(c_int, 4); pub const __GNUC_MINOR__ = @as(c_int, 2); pub const __GNUC_PATCHLEVEL__ = @as(c_int, 1); pub const __GXX_ABI_VERSION = @as(c_int, 1002); pub const __ATOMIC_RELAXED = @as(c_int, 0); pub const __ATOMIC_CONSUME = @as(c_int, 1); pub const __ATOMIC_ACQUIRE = @as(c_int, 2); pub const __ATOMIC_RELEASE = @as(c_int, 3); pub const __ATOMIC_ACQ_REL = @as(c_int, 4); pub const __ATOMIC_SEQ_CST = @as(c_int, 5); pub const __OPENCL_MEMORY_SCOPE_WORK_ITEM = @as(c_int, 0); pub const __OPENCL_MEMORY_SCOPE_WORK_GROUP = @as(c_int, 1); pub const __OPENCL_MEMORY_SCOPE_DEVICE = @as(c_int, 2); pub const __OPENCL_MEMORY_SCOPE_ALL_SVM_DEVICES = @as(c_int, 3); pub const __OPENCL_MEMORY_SCOPE_SUB_GROUP = @as(c_int, 4); pub const __PRAGMA_REDEFINE_EXTNAME = @as(c_int, 1); pub const __VERSION__ = "Clang 13.0.1 (git@github.com:ziglang/zig-bootstrap.git 81f0e6c5b902ead84753490db4f0007d08df964a)"; pub const __OBJC_BOOL_IS_BOOL = @as(c_int, 0); pub const __CONSTANT_CFSTRINGS__ = @as(c_int, 1); pub const __clang_literal_encoding__ = "UTF-8"; pub const __clang_wide_literal_encoding__ = "UTF-32"; pub const __OPTIMIZE__ = @as(c_int, 1); pub const __ORDER_LITTLE_ENDIAN__ = @as(c_int, 1234); pub const __ORDER_BIG_ENDIAN__ = @as(c_int, 4321); pub const __ORDER_PDP_ENDIAN__ = @as(c_int, 3412); pub const __BYTE_ORDER__ = __ORDER_LITTLE_ENDIAN__; pub const __LITTLE_ENDIAN__ = @as(c_int, 1); pub const _LP64 = @as(c_int, 1); pub const __LP64__ = @as(c_int, 1); pub const __CHAR_BIT__ = @as(c_int, 8); pub const __SCHAR_MAX__ = @as(c_int, 127); pub const __SHRT_MAX__ = @as(c_int, 32767); pub const __INT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __LONG_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __LONG_LONG_MAX__ = @as(c_longlong, 9223372036854775807); pub const __WCHAR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __WINT_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __INTMAX_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __SIZE_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __UINTMAX_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __PTRDIFF_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __INTPTR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __UINTPTR_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __SIZEOF_DOUBLE__ = @as(c_int, 8); pub const __SIZEOF_FLOAT__ = @as(c_int, 4); pub const __SIZEOF_INT__ = @as(c_int, 4); pub const __SIZEOF_LONG__ = @as(c_int, 8); pub const __SIZEOF_LONG_DOUBLE__ = @as(c_int, 16); pub const __SIZEOF_LONG_LONG__ = @as(c_int, 8); pub const __SIZEOF_POINTER__ = @as(c_int, 8); pub const __SIZEOF_SHORT__ = @as(c_int, 2); pub const __SIZEOF_PTRDIFF_T__ = @as(c_int, 8); pub const __SIZEOF_SIZE_T__ = @as(c_int, 8); pub const __SIZEOF_WCHAR_T__ = @as(c_int, 4); pub const __SIZEOF_WINT_T__ = @as(c_int, 4); pub const __SIZEOF_INT128__ = @as(c_int, 16); pub const __INTMAX_TYPE__ = c_long; pub const __INTMAX_FMTd__ = "ld"; pub const __INTMAX_FMTi__ = "li"; pub const __UINTMAX_TYPE__ = c_ulong; pub const __UINTMAX_FMTo__ = "lo"; pub const __UINTMAX_FMTu__ = "lu"; pub const __UINTMAX_FMTx__ = "lx"; pub const __UINTMAX_FMTX__ = "lX"; pub const __INTMAX_WIDTH__ = @as(c_int, 64); pub const __PTRDIFF_TYPE__ = c_long; pub const __PTRDIFF_FMTd__ = "ld"; pub const __PTRDIFF_FMTi__ = "li"; pub const __PTRDIFF_WIDTH__ = @as(c_int, 64); pub const __INTPTR_TYPE__ = c_long; pub const __INTPTR_FMTd__ = "ld"; pub const __INTPTR_FMTi__ = "li"; pub const __INTPTR_WIDTH__ = @as(c_int, 64); pub const __SIZE_TYPE__ = c_ulong; pub const __SIZE_FMTo__ = "lo"; pub const __SIZE_FMTu__ = "lu"; pub const __SIZE_FMTx__ = "lx"; pub const __SIZE_FMTX__ = "lX"; pub const __SIZE_WIDTH__ = @as(c_int, 64); pub const __WCHAR_TYPE__ = c_int; pub const __WCHAR_WIDTH__ = @as(c_int, 32); pub const __WINT_TYPE__ = c_uint; pub const __WINT_WIDTH__ = @as(c_int, 32); pub const __SIG_ATOMIC_WIDTH__ = @as(c_int, 32); pub const __SIG_ATOMIC_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __CHAR16_TYPE__ = c_ushort; pub const __CHAR32_TYPE__ = c_uint; pub const __UINTMAX_WIDTH__ = @as(c_int, 64); pub const __UINTPTR_TYPE__ = c_ulong; pub const __UINTPTR_FMTo__ = "lo"; pub const __UINTPTR_FMTu__ = "lu"; pub const __UINTPTR_FMTx__ = "lx"; pub const __UINTPTR_FMTX__ = "lX"; pub const __UINTPTR_WIDTH__ = @as(c_int, 64); pub const __FLT_DENORM_MIN__ = @as(f32, 1.40129846e-45); pub const __FLT_HAS_DENORM__ = @as(c_int, 1); pub const __FLT_DIG__ = @as(c_int, 6); pub const __FLT_DECIMAL_DIG__ = @as(c_int, 9); pub const __FLT_EPSILON__ = @as(f32, 1.19209290e-7); pub const __FLT_HAS_INFINITY__ = @as(c_int, 1); pub const __FLT_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __FLT_MANT_DIG__ = @as(c_int, 24); pub const __FLT_MAX_10_EXP__ = @as(c_int, 38); pub const __FLT_MAX_EXP__ = @as(c_int, 128); pub const __FLT_MAX__ = @as(f32, 3.40282347e+38); pub const __FLT_MIN_10_EXP__ = -@as(c_int, 37); pub const __FLT_MIN_EXP__ = -@as(c_int, 125); pub const __FLT_MIN__ = @as(f32, 1.17549435e-38); pub const __DBL_DENORM_MIN__ = 4.9406564584124654e-324; pub const __DBL_HAS_DENORM__ = @as(c_int, 1); pub const __DBL_DIG__ = @as(c_int, 15); pub const __DBL_DECIMAL_DIG__ = @as(c_int, 17); pub const __DBL_EPSILON__ = 2.2204460492503131e-16; pub const __DBL_HAS_INFINITY__ = @as(c_int, 1); pub const __DBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __DBL_MANT_DIG__ = @as(c_int, 53); pub const __DBL_MAX_10_EXP__ = @as(c_int, 308); pub const __DBL_MAX_EXP__ = @as(c_int, 1024); pub const __DBL_MAX__ = 1.7976931348623157e+308; pub const __DBL_MIN_10_EXP__ = -@as(c_int, 307); pub const __DBL_MIN_EXP__ = -@as(c_int, 1021); pub const __DBL_MIN__ = 2.2250738585072014e-308; pub const __LDBL_DENORM_MIN__ = @as(c_longdouble, 3.64519953188247460253e-4951); pub const __LDBL_HAS_DENORM__ = @as(c_int, 1); pub const __LDBL_DIG__ = @as(c_int, 18); pub const __LDBL_DECIMAL_DIG__ = @as(c_int, 21); pub const __LDBL_EPSILON__ = @as(c_longdouble, 1.08420217248550443401e-19); pub const __LDBL_HAS_INFINITY__ = @as(c_int, 1); pub const __LDBL_HAS_QUIET_NAN__ = @as(c_int, 1); pub const __LDBL_MANT_DIG__ = @as(c_int, 64); pub const __LDBL_MAX_10_EXP__ = @as(c_int, 4932); pub const __LDBL_MAX_EXP__ = @as(c_int, 16384); pub const __LDBL_MAX__ = @as(c_longdouble, 1.18973149535723176502e+4932); pub const __LDBL_MIN_10_EXP__ = -@as(c_int, 4931); pub const __LDBL_MIN_EXP__ = -@as(c_int, 16381); pub const __LDBL_MIN__ = @as(c_longdouble, 3.36210314311209350626e-4932); pub const __POINTER_WIDTH__ = @as(c_int, 64); pub const __BIGGEST_ALIGNMENT__ = @as(c_int, 16); pub const __WINT_UNSIGNED__ = @as(c_int, 1); pub const __INT8_TYPE__ = i8; pub const __INT8_FMTd__ = "hhd"; pub const __INT8_FMTi__ = "hhi"; pub const __INT8_C_SUFFIX__ = ""; pub const __INT16_TYPE__ = c_short; pub const __INT16_FMTd__ = "hd"; pub const __INT16_FMTi__ = "hi"; pub const __INT16_C_SUFFIX__ = ""; pub const __INT32_TYPE__ = c_int; pub const __INT32_FMTd__ = "d"; pub const __INT32_FMTi__ = "i"; pub const __INT32_C_SUFFIX__ = ""; pub const __INT64_TYPE__ = c_long; pub const __INT64_FMTd__ = "ld"; pub const __INT64_FMTi__ = "li"; pub const __UINT8_TYPE__ = u8; pub const __UINT8_FMTo__ = "hho"; pub const __UINT8_FMTu__ = "hhu"; pub const __UINT8_FMTx__ = "hhx"; pub const __UINT8_FMTX__ = "hhX"; pub const __UINT8_C_SUFFIX__ = ""; pub const __UINT8_MAX__ = @as(c_int, 255); pub const __INT8_MAX__ = @as(c_int, 127); pub const __UINT16_TYPE__ = c_ushort; pub const __UINT16_FMTo__ = "ho"; pub const __UINT16_FMTu__ = "hu"; pub const __UINT16_FMTx__ = "hx"; pub const __UINT16_FMTX__ = "hX"; pub const __UINT16_C_SUFFIX__ = ""; pub const __UINT16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __INT16_MAX__ = @as(c_int, 32767); pub const __UINT32_TYPE__ = c_uint; pub const __UINT32_FMTo__ = "o"; pub const __UINT32_FMTu__ = "u"; pub const __UINT32_FMTx__ = "x"; pub const __UINT32_FMTX__ = "X"; pub const __UINT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __INT32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __UINT64_TYPE__ = c_ulong; pub const __UINT64_FMTo__ = "lo"; pub const __UINT64_FMTu__ = "lu"; pub const __UINT64_FMTx__ = "lx"; pub const __UINT64_FMTX__ = "lX"; pub const __UINT64_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __INT64_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __INT_LEAST8_TYPE__ = i8; pub const __INT_LEAST8_MAX__ = @as(c_int, 127); pub const __INT_LEAST8_FMTd__ = "hhd"; pub const __INT_LEAST8_FMTi__ = "hhi"; pub const __UINT_LEAST8_TYPE__ = u8; pub const __UINT_LEAST8_MAX__ = @as(c_int, 255); pub const __UINT_LEAST8_FMTo__ = "hho"; pub const __UINT_LEAST8_FMTu__ = "hhu"; pub const __UINT_LEAST8_FMTx__ = "hhx"; pub const __UINT_LEAST8_FMTX__ = "hhX"; pub const __INT_LEAST16_TYPE__ = c_short; pub const __INT_LEAST16_MAX__ = @as(c_int, 32767); pub const __INT_LEAST16_FMTd__ = "hd"; pub const __INT_LEAST16_FMTi__ = "hi"; pub const __UINT_LEAST16_TYPE__ = c_ushort; pub const __UINT_LEAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_LEAST16_FMTo__ = "ho"; pub const __UINT_LEAST16_FMTu__ = "hu"; pub const __UINT_LEAST16_FMTx__ = "hx"; pub const __UINT_LEAST16_FMTX__ = "hX"; pub const __INT_LEAST32_TYPE__ = c_int; pub const __INT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_LEAST32_FMTd__ = "d"; pub const __INT_LEAST32_FMTi__ = "i"; pub const __UINT_LEAST32_TYPE__ = c_uint; pub const __UINT_LEAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_LEAST32_FMTo__ = "o"; pub const __UINT_LEAST32_FMTu__ = "u"; pub const __UINT_LEAST32_FMTx__ = "x"; pub const __UINT_LEAST32_FMTX__ = "X"; pub const __INT_LEAST64_TYPE__ = c_long; pub const __INT_LEAST64_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __INT_LEAST64_FMTd__ = "ld"; pub const __INT_LEAST64_FMTi__ = "li"; pub const __UINT_LEAST64_TYPE__ = c_ulong; pub const __UINT_LEAST64_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __UINT_LEAST64_FMTo__ = "lo"; pub const __UINT_LEAST64_FMTu__ = "lu"; pub const __UINT_LEAST64_FMTx__ = "lx"; pub const __UINT_LEAST64_FMTX__ = "lX"; pub const __INT_FAST8_TYPE__ = i8; pub const __INT_FAST8_MAX__ = @as(c_int, 127); pub const __INT_FAST8_FMTd__ = "hhd"; pub const __INT_FAST8_FMTi__ = "hhi"; pub const __UINT_FAST8_TYPE__ = u8; pub const __UINT_FAST8_MAX__ = @as(c_int, 255); pub const __UINT_FAST8_FMTo__ = "hho"; pub const __UINT_FAST8_FMTu__ = "hhu"; pub const __UINT_FAST8_FMTx__ = "hhx"; pub const __UINT_FAST8_FMTX__ = "hhX"; pub const __INT_FAST16_TYPE__ = c_short; pub const __INT_FAST16_MAX__ = @as(c_int, 32767); pub const __INT_FAST16_FMTd__ = "hd"; pub const __INT_FAST16_FMTi__ = "hi"; pub const __UINT_FAST16_TYPE__ = c_ushort; pub const __UINT_FAST16_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 65535, .decimal); pub const __UINT_FAST16_FMTo__ = "ho"; pub const __UINT_FAST16_FMTu__ = "hu"; pub const __UINT_FAST16_FMTx__ = "hx"; pub const __UINT_FAST16_FMTX__ = "hX"; pub const __INT_FAST32_TYPE__ = c_int; pub const __INT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_int, 2147483647, .decimal); pub const __INT_FAST32_FMTd__ = "d"; pub const __INT_FAST32_FMTi__ = "i"; pub const __UINT_FAST32_TYPE__ = c_uint; pub const __UINT_FAST32_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_uint, 4294967295, .decimal); pub const __UINT_FAST32_FMTo__ = "o"; pub const __UINT_FAST32_FMTu__ = "u"; pub const __UINT_FAST32_FMTx__ = "x"; pub const __UINT_FAST32_FMTX__ = "X"; pub const __INT_FAST64_TYPE__ = c_long; pub const __INT_FAST64_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_long, 9223372036854775807, .decimal); pub const __INT_FAST64_FMTd__ = "ld"; pub const __INT_FAST64_FMTi__ = "li"; pub const __UINT_FAST64_TYPE__ = c_ulong; pub const __UINT_FAST64_MAX__ = @import("std").zig.c_translation.promoteIntLiteral(c_ulong, 18446744073709551615, .decimal); pub const __UINT_FAST64_FMTo__ = "lo"; pub const __UINT_FAST64_FMTu__ = "lu"; pub const __UINT_FAST64_FMTx__ = "lx"; pub const __UINT_FAST64_FMTX__ = "lX"; pub const __USER_LABEL_PREFIX__ = ""; pub const __FINITE_MATH_ONLY__ = @as(c_int, 0); pub const __GNUC_STDC_INLINE__ = @as(c_int, 1); pub const __GCC_ATOMIC_TEST_AND_SET_TRUEVAL = @as(c_int, 1); pub const __CLANG_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __CLANG_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_BOOL_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR16_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_CHAR32_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_WCHAR_T_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_SHORT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_INT_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_LLONG_LOCK_FREE = @as(c_int, 2); pub const __GCC_ATOMIC_POINTER_LOCK_FREE = @as(c_int, 2); pub const __PIC__ = @as(c_int, 2); pub const __pic__ = @as(c_int, 2); pub const __FLT_EVAL_METHOD__ = @as(c_int, 0); pub const __FLT_RADIX__ = @as(c_int, 2); pub const __DECIMAL_DIG__ = __LDBL_DECIMAL_DIG__; pub const __SSP_STRONG__ = @as(c_int, 2); pub const __GCC_ASM_FLAG_OUTPUTS__ = @as(c_int, 1); pub const __code_model_small__ = @as(c_int, 1); pub const __amd64__ = @as(c_int, 1); pub const __amd64 = @as(c_int, 1); pub const __x86_64 = @as(c_int, 1); pub const __x86_64__ = @as(c_int, 1); pub const __SEG_GS = @as(c_int, 1); pub const __SEG_FS = @as(c_int, 1); pub const __corei7 = @as(c_int, 1); pub const __corei7__ = @as(c_int, 1); pub const __tune_corei7__ = @as(c_int, 1); pub const __REGISTER_PREFIX__ = ""; pub const __NO_MATH_INLINES = @as(c_int, 1); pub const __AES__ = @as(c_int, 1); pub const __PCLMUL__ = @as(c_int, 1); pub const __LAHF_SAHF__ = @as(c_int, 1); pub const __LZCNT__ = @as(c_int, 1); pub const __RDRND__ = @as(c_int, 1); pub const __FSGSBASE__ = @as(c_int, 1); pub const __BMI__ = @as(c_int, 1); pub const __BMI2__ = @as(c_int, 1); pub const __POPCNT__ = @as(c_int, 1); pub const __PRFCHW__ = @as(c_int, 1); pub const __RDSEED__ = @as(c_int, 1); pub const __ADX__ = @as(c_int, 1); pub const __MOVBE__ = @as(c_int, 1); pub const __FMA__ = @as(c_int, 1); pub const __F16C__ = @as(c_int, 1); pub const __FXSR__ = @as(c_int, 1); pub const __XSAVE__ = @as(c_int, 1); pub const __XSAVEOPT__ = @as(c_int, 1); pub const __XSAVEC__ = @as(c_int, 1); pub const __XSAVES__ = @as(c_int, 1); pub const __CLFLUSHOPT__ = @as(c_int, 1); pub const __SGX__ = @as(c_int, 1); pub const __INVPCID__ = @as(c_int, 1); pub const __AVX2__ = @as(c_int, 1); pub const __AVX__ = @as(c_int, 1); pub const __SSE4_2__ = @as(c_int, 1); pub const __SSE4_1__ = @as(c_int, 1); pub const __SSSE3__ = @as(c_int, 1); pub const __SSE3__ = @as(c_int, 1); pub const __SSE2__ = @as(c_int, 1); pub const __SSE2_MATH__ = @as(c_int, 1); pub const __SSE__ = @as(c_int, 1); pub const __SSE_MATH__ = @as(c_int, 1); pub const __MMX__ = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_1 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_2 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_4 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_8 = @as(c_int, 1); pub const __GCC_HAVE_SYNC_COMPARE_AND_SWAP_16 = @as(c_int, 1); pub const __SIZEOF_FLOAT128__ = @as(c_int, 16); pub const unix = @as(c_int, 1); pub const __unix = @as(c_int, 1); pub const __unix__ = @as(c_int, 1); pub const linux = @as(c_int, 1); pub const __linux = @as(c_int, 1); pub const __linux__ = @as(c_int, 1); pub const __ELF__ = @as(c_int, 1); pub const __gnu_linux__ = @as(c_int, 1); pub const __FLOAT128__ = @as(c_int, 1); pub const __STDC__ = @as(c_int, 1); pub const __STDC_HOSTED__ = @as(c_int, 1); pub const __STDC_VERSION__ = @as(c_long, 201710); pub const __STDC_UTF_16__ = @as(c_int, 1); pub const __STDC_UTF_32__ = @as(c_int, 1); pub const __GLIBC_MINOR__ = @as(c_int, 31); pub const _DEBUG = @as(c_int, 1); pub const __GCC_HAVE_DWARF2_CFI_ASM = @as(c_int, 1); pub const _STDIO_H = @as(c_int, 1); pub const __GLIBC_INTERNAL_STARTING_HEADER_IMPLEMENTATION = ""; pub const _FEATURES_H = @as(c_int, 1); pub const __KERNEL_STRICT_NAMES = ""; pub inline fn __GNUC_PREREQ(maj: anytype, min: anytype) @TypeOf(((__GNUC__ << @as(c_int, 16)) + __GNUC_MINOR__) >= ((maj << @as(c_int, 16)) + min)) { return ((__GNUC__ << @as(c_int, 16)) + __GNUC_MINOR__) >= ((maj << @as(c_int, 16)) + min); } pub inline fn __glibc_clang_prereq(maj: anytype, min: anytype) @TypeOf(((__clang_major__ << @as(c_int, 16)) + __clang_minor__) >= ((maj << @as(c_int, 16)) + min)) { return ((__clang_major__ << @as(c_int, 16)) + __clang_minor__) >= ((maj << @as(c_int, 16)) + min); } pub const _DEFAULT_SOURCE = @as(c_int, 1); pub const __GLIBC_USE_ISOC2X = @as(c_int, 0); pub const __USE_ISOC11 = @as(c_int, 1); pub const __USE_ISOC99 = @as(c_int, 1); pub const __USE_ISOC95 = @as(c_int, 1); pub const __USE_POSIX_IMPLICITLY = @as(c_int, 1); pub const _POSIX_SOURCE = @as(c_int, 1); pub const _POSIX_C_SOURCE = @as(c_long, 200809); pub const __USE_POSIX = @as(c_int, 1); pub const __USE_POSIX2 = @as(c_int, 1); pub const __USE_POSIX199309 = @as(c_int, 1); pub const __USE_POSIX199506 = @as(c_int, 1); pub const __USE_XOPEN2K = @as(c_int, 1); pub const __USE_XOPEN2K8 = @as(c_int, 1); pub const _ATFILE_SOURCE = @as(c_int, 1); pub const __WORDSIZE = @as(c_int, 64); pub const __WORDSIZE_TIME64_COMPAT32 = @as(c_int, 1); pub const __SYSCALL_WORDSIZE = @as(c_int, 64); pub const __TIMESIZE = __WORDSIZE; pub const __USE_MISC = @as(c_int, 1); pub const __USE_ATFILE = @as(c_int, 1); pub const __USE_FORTIFY_LEVEL = @as(c_int, 0); pub const __GLIBC_USE_DEPRECATED_GETS = @as(c_int, 0); pub const __GLIBC_USE_DEPRECATED_SCANF = @as(c_int, 0); pub const _STDC_PREDEF_H = @as(c_int, 1); pub const __STDC_IEC_559__ = @as(c_int, 1); pub const __STDC_IEC_559_COMPLEX__ = @as(c_int, 1); pub const __STDC_ISO_10646__ = @as(c_long, 201706); pub const __GNU_LIBRARY__ = @as(c_int, 6); pub const __GLIBC__ = @as(c_int, 2); pub inline fn __GLIBC_PREREQ(maj: anytype, min: anytype) @TypeOf(((__GLIBC__ << @as(c_int, 16)) + __GLIBC_MINOR__) >= ((maj << @as(c_int, 16)) + min)) { return ((__GLIBC__ << @as(c_int, 16)) + __GLIBC_MINOR__) >= ((maj << @as(c_int, 16)) + min); } pub const _SYS_CDEFS_H = @as(c_int, 1); pub const __LEAF = ""; pub const __LEAF_ATTR = ""; pub inline fn __P(args: anytype) @TypeOf(args) { return args; } pub inline fn __PMT(args: anytype) @TypeOf(args) { return args; } pub const __ptr_t = ?*anyopaque; pub const __BEGIN_DECLS = ""; pub const __END_DECLS = ""; pub inline fn __bos(ptr: anytype) @TypeOf(__builtin_object_size(ptr, __USE_FORTIFY_LEVEL > @as(c_int, 1))) { return __builtin_object_size(ptr, __USE_FORTIFY_LEVEL > @as(c_int, 1)); } pub inline fn __bos0(ptr: anytype) @TypeOf(__builtin_object_size(ptr, @as(c_int, 0))) { return __builtin_object_size(ptr, @as(c_int, 0)); } pub inline fn __glibc_objsize0(__o: anytype) @TypeOf(__bos0(__o)) { return __bos0(__o); } pub inline fn __glibc_objsize(__o: anytype) @TypeOf(__bos(__o)) { return __bos(__o); } pub const __glibc_c99_flexarr_available = @as(c_int, 1); pub inline fn __ASMNAME(cname: anytype) @TypeOf(__ASMNAME2(__USER_LABEL_PREFIX__, cname)) { return __ASMNAME2(__USER_LABEL_PREFIX__, cname); } pub const __wur = ""; pub const __fortify_function = __extern_always_inline ++ __attribute_artificial__; pub inline fn __glibc_unlikely(cond: anytype) @TypeOf(__builtin_expect(cond, @as(c_int, 0))) { return __builtin_expect(cond, @as(c_int, 0)); } pub inline fn __glibc_likely(cond: anytype) @TypeOf(__builtin_expect(cond, @as(c_int, 1))) { return __builtin_expect(cond, @as(c_int, 1)); } pub const __attribute_nonstring__ = ""; pub const __LDOUBLE_REDIRECTS_TO_FLOAT128_ABI = @as(c_int, 0); pub inline fn __LDBL_REDIR1(name: anytype, proto: anytype, alias: anytype) @TypeOf(name ++ proto) { _ = alias; return name ++ proto; } pub inline fn __LDBL_REDIR(name: anytype, proto: anytype) @TypeOf(name ++ proto) { return name ++ proto; } pub inline fn __LDBL_REDIR1_NTH(name: anytype, proto: anytype, alias: anytype) @TypeOf(name ++ proto ++ __THROW) { _ = alias; return name ++ proto ++ __THROW; } pub inline fn __LDBL_REDIR_NTH(name: anytype, proto: anytype) @TypeOf(name ++ proto ++ __THROW) { return name ++ proto ++ __THROW; } pub inline fn __REDIRECT_LDBL(name: anytype, proto: anytype, alias: anytype) @TypeOf(__REDIRECT(name, proto, alias)) { return __REDIRECT(name, proto, alias); } pub inline fn __REDIRECT_NTH_LDBL(name: anytype, proto: anytype, alias: anytype) @TypeOf(__REDIRECT_NTH(name, proto, alias)) { return __REDIRECT_NTH(name, proto, alias); } pub const __HAVE_GENERIC_SELECTION = @as(c_int, 1); pub const __attr_dealloc_free = ""; pub const __USE_EXTERN_INLINES = @as(c_int, 1); pub const __stub___compat_bdflush = ""; pub const __stub_chflags = ""; pub const __stub_fchflags = ""; pub const __stub_gtty = ""; pub const __stub_revoke = ""; pub const __stub_setlogin = ""; pub const __stub_sigreturn = ""; pub const __stub_stty = ""; pub const __GLIBC_USE_LIB_EXT2 = @as(c_int, 0); pub const __GLIBC_USE_IEC_60559_BFP_EXT = @as(c_int, 0); pub const __GLIBC_USE_IEC_60559_BFP_EXT_C2X = @as(c_int, 0); pub const __GLIBC_USE_IEC_60559_EXT = @as(c_int, 0); pub const __GLIBC_USE_IEC_60559_FUNCS_EXT = @as(c_int, 0); pub const __GLIBC_USE_IEC_60559_FUNCS_EXT_C2X = @as(c_int, 0); pub const __GLIBC_USE_IEC_60559_TYPES_EXT = @as(c_int, 0); pub const __need_size_t = ""; pub const __need_NULL = ""; pub const _SIZE_T = ""; pub const NULL = @import("std").zig.c_translation.cast(?*anyopaque, @as(c_int, 0)); pub const __need___va_list = ""; pub const __STDARG_H = ""; pub const _VA_LIST = ""; pub const __GNUC_VA_LIST = @as(c_int, 1); pub const _BITS_TYPES_H = @as(c_int, 1); pub const __S16_TYPE = c_short; pub const __U16_TYPE = c_ushort; pub const __S32_TYPE = c_int; pub const __U32_TYPE = c_uint; pub const __SLONGWORD_TYPE = c_long; pub const __ULONGWORD_TYPE = c_ulong; pub const __SQUAD_TYPE = c_long; pub const __UQUAD_TYPE = c_ulong; pub const __SWORD_TYPE = c_long; pub const __UWORD_TYPE = c_ulong; pub const __SLONG32_TYPE = c_int; pub const __ULONG32_TYPE = c_uint; pub const __S64_TYPE = c_long; pub const __U64_TYPE = c_ulong; pub const _BITS_TYPESIZES_H = @as(c_int, 1); pub const __SYSCALL_SLONG_TYPE = __SLONGWORD_TYPE; pub const __SYSCALL_ULONG_TYPE = __ULONGWORD_TYPE; pub const __DEV_T_TYPE = __UQUAD_TYPE; pub const __UID_T_TYPE = __U32_TYPE; pub const __GID_T_TYPE = __U32_TYPE; pub const __INO_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __INO64_T_TYPE = __UQUAD_TYPE; pub const __MODE_T_TYPE = __U32_TYPE; pub const __NLINK_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __FSWORD_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __OFF_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __OFF64_T_TYPE = __SQUAD_TYPE; pub const __PID_T_TYPE = __S32_TYPE; pub const __RLIM_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __RLIM64_T_TYPE = __UQUAD_TYPE; pub const __BLKCNT_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __BLKCNT64_T_TYPE = __SQUAD_TYPE; pub const __FSBLKCNT_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __FSBLKCNT64_T_TYPE = __UQUAD_TYPE; pub const __FSFILCNT_T_TYPE = __SYSCALL_ULONG_TYPE; pub const __FSFILCNT64_T_TYPE = __UQUAD_TYPE; pub const __ID_T_TYPE = __U32_TYPE; pub const __CLOCK_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __TIME_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __USECONDS_T_TYPE = __U32_TYPE; pub const __SUSECONDS_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __SUSECONDS64_T_TYPE = __SQUAD_TYPE; pub const __DADDR_T_TYPE = __S32_TYPE; pub const __KEY_T_TYPE = __S32_TYPE; pub const __CLOCKID_T_TYPE = __S32_TYPE; pub const __TIMER_T_TYPE = ?*anyopaque; pub const __BLKSIZE_T_TYPE = __SYSCALL_SLONG_TYPE; pub const __SSIZE_T_TYPE = __SWORD_TYPE; pub const __CPU_MASK_TYPE = __SYSCALL_ULONG_TYPE; pub const __OFF_T_MATCHES_OFF64_T = @as(c_int, 1); pub const __INO_T_MATCHES_INO64_T = @as(c_int, 1); pub const __RLIM_T_MATCHES_RLIM64_T = @as(c_int, 1); pub const __STATFS_MATCHES_STATFS64 = @as(c_int, 1); pub const __KERNEL_OLD_TIMEVAL_MATCHES_TIMEVAL64 = @as(c_int, 1); pub const __FD_SETSIZE = @as(c_int, 1024); pub const _BITS_TIME64_H = @as(c_int, 1); pub const __TIME64_T_TYPE = __TIME_T_TYPE; pub const _____fpos_t_defined = @as(c_int, 1); pub const ____mbstate_t_defined = @as(c_int, 1); pub const _____fpos64_t_defined = @as(c_int, 1); pub const ____FILE_defined = @as(c_int, 1); pub const __FILE_defined = @as(c_int, 1); pub const __struct_FILE_defined = @as(c_int, 1); pub const _IO_EOF_SEEN = @as(c_int, 0x0010); pub inline fn __feof_unlocked_body(_fp: anytype) @TypeOf((_fp.*._flags & _IO_EOF_SEEN) != @as(c_int, 0)) { return (_fp.*._flags & _IO_EOF_SEEN) != @as(c_int, 0); } pub const _IO_ERR_SEEN = @as(c_int, 0x0020); pub inline fn __ferror_unlocked_body(_fp: anytype) @TypeOf((_fp.*._flags & _IO_ERR_SEEN) != @as(c_int, 0)) { return (_fp.*._flags & _IO_ERR_SEEN) != @as(c_int, 0); } pub const _IO_USER_LOCK = @import("std").zig.c_translation.promoteIntLiteral(c_int, 0x8000, .hexadecimal); pub const _VA_LIST_DEFINED = ""; pub const __off_t_defined = ""; pub const __ssize_t_defined = ""; pub const _IOFBF = @as(c_int, 0); pub const _IOLBF = @as(c_int, 1); pub const _IONBF = @as(c_int, 2); pub const BUFSIZ = @as(c_int, 8192); pub const EOF = -@as(c_int, 1); pub const SEEK_SET = @as(c_int, 0); pub const SEEK_CUR = @as(c_int, 1); pub const SEEK_END = @as(c_int, 2); pub const P_tmpdir = "/tmp"; pub const _BITS_STDIO_LIM_H = @as(c_int, 1); pub const L_tmpnam = @as(c_int, 20); pub const TMP_MAX = @import("std").zig.c_translation.promoteIntLiteral(c_int, 238328, .decimal); pub const FILENAME_MAX = @as(c_int, 4096); pub const L_ctermid = @as(c_int, 9); pub const FOPEN_MAX = @as(c_int, 16); pub const __attr_dealloc_fclose = __attr_dealloc(fclose, @as(c_int, 1)); pub const _BITS_FLOATN_H = ""; pub const __HAVE_FLOAT128 = @as(c_int, 0); pub const __HAVE_DISTINCT_FLOAT128 = @as(c_int, 0); pub const __HAVE_FLOAT64X = @as(c_int, 1); pub const __HAVE_FLOAT64X_LONG_DOUBLE = @as(c_int, 1); pub const _BITS_FLOATN_COMMON_H = ""; pub const __HAVE_FLOAT16 = @as(c_int, 0); pub const __HAVE_FLOAT32 = @as(c_int, 1); pub const __HAVE_FLOAT64 = @as(c_int, 1); pub const __HAVE_FLOAT32X = @as(c_int, 1); pub const __HAVE_FLOAT128X = @as(c_int, 0); pub const __HAVE_DISTINCT_FLOAT16 = __HAVE_FLOAT16; pub const __HAVE_DISTINCT_FLOAT32 = @as(c_int, 0); pub const __HAVE_DISTINCT_FLOAT64 = @as(c_int, 0); pub const __HAVE_DISTINCT_FLOAT32X = @as(c_int, 0); pub const __HAVE_DISTINCT_FLOAT64X = @as(c_int, 0); pub const __HAVE_DISTINCT_FLOAT128X = __HAVE_FLOAT128X; pub const __HAVE_FLOAT128_UNLIKE_LDBL = (__HAVE_DISTINCT_FLOAT128 != 0) and (__LDBL_MANT_DIG__ != @as(c_int, 113)); pub const __HAVE_FLOATN_NOT_TYPEDEF = @as(c_int, 0); pub inline fn __f64(x: anytype) @TypeOf(x) { return x; } pub inline fn __f32x(x: anytype) @TypeOf(x) { return x; } pub inline fn __builtin_huge_valf32() @TypeOf(__builtin_huge_valf()) { return __builtin_huge_valf(); } pub inline fn __builtin_inff32() @TypeOf(__builtin_inff()) { return __builtin_inff(); } pub inline fn __builtin_nanf32(x: anytype) @TypeOf(__builtin_nanf(x)) { return __builtin_nanf(x); } pub const _BITS_STDIO_H = @as(c_int, 1); pub const __STDIO_INLINE = __extern_inline; pub const _STRING_H = @as(c_int, 1); pub const _BITS_TYPES_LOCALE_T_H = @as(c_int, 1); pub const _BITS_TYPES___LOCALE_T_H = @as(c_int, 1); pub const _STRINGS_H = @as(c_int, 1); pub const __va_list_tag = struct___va_list_tag; pub const _G_fpos_t = struct__G_fpos_t; pub const _G_fpos64_t = struct__G_fpos64_t; pub const _IO_marker = struct__IO_marker; pub const _IO_codecvt = struct__IO_codecvt; pub const _IO_wide_data = struct__IO_wide_data; pub const _IO_FILE = struct__IO_FILE; pub const __locale_data = struct___locale_data; pub const __locale_struct = struct___locale_struct;
https://raw.githubusercontent.com/veera-sivarajan/shell/255b1266fd62bfca22bdaf4d6e5b133b5d9f3d45/src/lexer.zig
// based on // options: { // target: Element; // anchor?: Element; // props?: Props; // hydrate?: boolean; // intro?: boolean; // $$inline?: boolean; // } pub const Options = struct {}; // based on // interface T$$ { // dirty: number[]; // ctx: null|any; // bound: any; // update: () => void; // callbacks: any; // after_update: any[]; // props: Record<string, 0 | string>; // fragment: null|false|Fragment; // not_equal: any; // before_update: any[]; // context: Map<any, any>; // on_mount: any[]; // on_destroy: any[]; // skip_bound: boolean; // on_disconnect: any[]; // } const Internal = struct {}; // based on // export declare class SvelteComponent { // $$: T$$; // $$set?: ($$props: any) => void; // $destroy(): void; // $on(type: any, callback: any): () => void; // $set($$props: any): void; // } // export interface SvelteComponentTyped<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any> { // $set(props?: Partial<Props>): void; // $on<K extends Extract<keyof Events, string>>(type: K, callback: (e: Events[K]) => void): () => void; // $destroy(): void; // [accessor: string]: any; // } pub fn Component(comptime Props: type, comptime _: type, comptime _: type) type { const Event = {}; return struct { const Self = @This(); internal: Internal, // probably need an allocator here // pub fn init(options: Options) Self { pub fn init(_: Options) Self { return Self{ .internal = .{} }; } // take *Self instead to set self.* = undefined? // pub fn deinit(self: Self) void {} pub fn deinit(_: Self) void {} // fn set(self: Self, props: ?Props) void {} fn set(_: Self, _: ?Props) void {} // fn on(self: Self, event_type: []u8, callback: fn (event: Event) void) fn () void { fn on(_: Self, _: []u8, _: fn (event: Event) void) fn () void { return fn () void{}; } }; }
https://raw.githubusercontent.com/pluvial/zvelte/0f418df85c40e47d9d6e5294f9a2801e122e4b7c/src/runtime/component.zig
const std = @import("std"); // Find the first occurence of a non-repeat sequence of four characters. // This will be four unique characters, where none of the characters are the same. // possible regex: /^\%(.*\(.\).*\1\)\@!.*$ // regex in zig seems to not be quite there yet. // so we'll do it with a simple algo, it's not a lot of comparisons after all. pub fn main() void { const input = "znrznnozzroronznzona"; std.debug.print("Examining:\n\"{s}\"\n\n", .{input}); var pos: usize = 0; while (pos <= (input.len - 4)) : (pos += 1) { std.debug.print("{d:3} {s}", .{ pos, input[pos .. pos + 4] }); if (no_repeats(input[pos .. pos + 4])) { std.debug.print(" *", .{}); } std.debug.print("\n", .{}); } std.debug.print("\n", .{}); } fn no_repeats(s: []const u8) bool { if (s[0] != s[1] and s[0] != s[2] and s[0] != s[3] and s[1] != s[2] and s[1] != s[3] and s[2] != s[3]) { return true; } return false; }
https://raw.githubusercontent.com/ewaldhorn/whatamess/ff94d4af6b435d30564d0e2eb5d25d6f571884fc/languages/zig/learning/assorted/non_repeater/non_repeater.zig
const page_frame_manager = @import("vm/page_frame_manager.zig"); //const BumpAllocator = page_frame_manager.BumpAllocator; var page_allocator: page_frame_manager.BumpAllocator = undefined; // Make a page frame pub fn get_page_frame_manager() *page_frame_manager.BumpAllocator { //ASSERT INITED? return &page_allocator; } pub fn init() void { //init page frame manager page_allocator = page_frame_manager.BumpAllocator.init(); }
https://raw.githubusercontent.com/jamesmintram/jimzos/8eb52e7efffb1a97eca4899ff72549f96ed3460b/kernel/src/vm.zig
const std = @import("std"); const Direction = enum { north, south, east, west }; const Value = enum(u2) { zero, one, two }; test "enum ordinal value" { try std.testing.expect(@intFromEnum(Value.zero) == 0); try std.testing.expect(@intFromEnum(Value.one) == 1); try std.testing.expect(@intFromEnum(Value.two) == 2); } const Value2 = enum(u32) { hundred = 100, thousand = 1000, million = 1000000, next, }; test "set enum ordinal value" { try std.testing.expect(@intFromEnum(Value2.hundred) == 100); try std.testing.expect(@intFromEnum(Value2.thousand) == 1000); try std.testing.expect(@intFromEnum(Value2.million) == 1000000); try std.testing.expect(@intFromEnum(Value2.next) == 1000001); } const Suit = enum { clubs, spades, diamonds, hearts, pub fn isClubs(self: Suit) bool { return self == Suit.clubs; } }; test "enum method" { try std.testing.expect(Suit.spades.isClubs() == Suit.isClubs(.spades)); } const Mode = enum { var count: u32 = 0; on, off, }; test "hmm" { Mode.count += 1; try std.testing.expect(Mode.count == 1); }
https://raw.githubusercontent.com/mgcth/learnzig/4886d0bbaf735af89ba1d59d3b166a38530f3a12/zig.guide/language/enums.zig
//! Sfc64 pseudo-random number generator from Practically Random. //! Fastest engine of pracrand and smallest footprint. //! See http://pracrand.sourceforge.net/ const std = @import("std"); const math = std.math; const Sfc64 = @This(); a: u64 = undefined, b: u64 = undefined, c: u64 = undefined, counter: u64 = undefined, const Rotation = 24; const RightShift = 11; const LeftShift = 3; pub fn init(init_s: u64) Sfc64 { var x = Sfc64{}; x.seed(init_s); return x; } pub fn random(self: *Sfc64) std.Random { return std.Random.init(self, fill); } fn next(self: *Sfc64) u64 { const tmp = self.a +% self.b +% self.counter; self.counter += 1; self.a = self.b ^ (self.b >> RightShift); self.b = self.c +% (self.c << LeftShift); self.c = math.rotl(u64, self.c, Rotation) +% tmp; return tmp; } fn seed(self: *Sfc64, init_s: u64) void { self.a = init_s; self.b = init_s; self.c = init_s; self.counter = 1; var i: u32 = 0; while (i < 12) : (i += 1) { _ = self.next(); } } pub fn fill(self: *Sfc64, buf: []u8) void { var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Complete 8 byte segments. while (i < aligned_len) : (i += 8) { var n = self.next(); comptime var j: usize = 0; inline while (j < 8) : (j += 1) { buf[i + j] = @as(u8, @truncate(n)); n >>= 8; } } // Remaining. (cuts the stream) if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @as(u8, @truncate(n)); n >>= 8; } } } test "Sfc64 sequence" { // Unfortunately there does not seem to be an official test sequence. var r = Sfc64.init(0); const seq = [_]u64{ 0x3acfa029e3cc6041, 0xf5b6515bf2ee419c, 0x1259635894a29b61, 0xb6ae75395f8ebd6, 0x225622285ce302e2, 0x520d28611395cb21, 0xdb909c818901599d, 0x8ffd195365216f57, 0xe8c4ad5e258ac04a, 0x8f8ef2c89fdb63ca, 0xf9865b01d98d8e2f, 0x46555871a65d08ba, 0x66868677c6298fcd, 0x2ce15a7e6329f57d, 0xb2f1833ca91ca79, 0x4b0890ac9bf453ca, }; for (seq) |s| { try std.testing.expectEqual(s, r.next()); } } test "Sfc64 fill" { // Unfortunately there does not seem to be an official test sequence. var r = Sfc64.init(0); const seq = [_]u64{ 0x3acfa029e3cc6041, 0xf5b6515bf2ee419c, 0x1259635894a29b61, 0xb6ae75395f8ebd6, 0x225622285ce302e2, 0x520d28611395cb21, 0xdb909c818901599d, 0x8ffd195365216f57, 0xe8c4ad5e258ac04a, 0x8f8ef2c89fdb63ca, 0xf9865b01d98d8e2f, 0x46555871a65d08ba, 0x66868677c6298fcd, 0x2ce15a7e6329f57d, 0xb2f1833ca91ca79, 0x4b0890ac9bf453ca, }; for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; std.mem.writeInt(u64, &buf0, s, .little); r.fill(&buf1); try std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } }
https://raw.githubusercontent.com/2lambda123/ziglang-zig/d7563a7753393d7f0d1af445276a64b8a55cb857/lib/std/Random/Sfc64.zig
const std = @import("std"); const Contact = @import("../models/contact.zig"); contacts: []const Contact, query: ?[]const u8, pub fn format( value: @This(), comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = fmt; _ = options; try writer.print( \\<form method="get" action="/contacts" class="tool-bar"> \\ <label for="search">Search Term</label> \\ <input id="search" type="text" name="q" value="{s}" autofocus /> \\ <input type="submit" value="Search" /> \\</form> \\ \\<table style="margin-top: 12px;"> \\ <thead> \\ <tr> \\ <td>Firstname</td> \\ <td>Lastname</td> \\ <td>Phone</td> \\ <td>Email</td> \\ <td></td> \\ </tr> \\ </thead> \\ <tbody> \\ , .{value.query orelse ""}); for (value.contacts) |contact| { if (value.query == null or value.query.?.len <= 0 or std.mem.containsAtLeast( u8, contact.email, 1, value.query.?, )) try writer.print( \\ <tr> \\ <td>{s}</td> \\ <td>{s}</td> \\ <td>{s}</td> \\ <td>{s}</td> \\ <td> \\ <a href="/contacts/{d}/edit">Edit</a> \\ <a href="/contacts/{d}">View</a> \\ </td> \\ </tr> \\ , .{ contact.firstname, contact.lastname, contact.phone, contact.email, contact.id, contact.id, }); } try writer.print( \\ </tbody> \\</table> \\ \\<p> \\ <a href="/contacts/new">Add Contact</a> \\</p> \\ , .{}); }
https://raw.githubusercontent.com/daniel1hort/contact.app/da7c3cfe44af9c2bd9974947553adb205b38c582/src/components/contractsList.zig
// SPDX-License-Identifier: MPL-2.0 // Copyright © 2024 Chris Marchesi //! A polygon plotter for fill operations. const std = @import("std"); const debug = @import("std").debug; const mem = @import("std").mem; // const options = @import("../options.zig"); const nodepkg = @import("path_nodes.zig"); const Polygon = @import("Polygon.zig"); const PolygonList = @import("PolygonList.zig"); const Point = @import("Point.zig"); const Spline = @import("Spline.zig"); const InternalError = @import("../errors.zig").InternalError; pub fn plot( alloc: mem.Allocator, nodes: std.ArrayList(nodepkg.PathNode), scale: f64, tolerance: f64, ) !PolygonList { var result = PolygonList.init(alloc); errdefer result.deinit(); var initial_point: ?Point = null; var current_point: ?Point = null; var current_polygon: ?Polygon = null; for (nodes.items, 0..) |node, i| { switch (node) { .move_to => |n| { if (current_polygon) |poly| { // Only append this polygon if it's useful (has more than 2 // corners). Otherwise, get rid of it. if (poly.corners.len > 2) { try result.append(poly); } else { poly.deinit(); current_polygon = null; } } // Check if this is the last node, and no-op if it is, as this // is the auto-added move_to node that is given after // close_path. if (i == nodes.items.len - 1) { break; } current_polygon = Polygon.init(alloc, scale); try current_polygon.?.plot(n.point, null); initial_point = n.point; current_point = n.point; }, .line_to => |n| { if (initial_point == null) return InternalError.InvalidState; if (current_point == null) return InternalError.InvalidState; if (current_polygon == null) return InternalError.InvalidState; try current_polygon.?.plot(n.point, null); current_point = n.point; }, .curve_to => |n| { if (initial_point == null) return InternalError.InvalidState; if (current_point == null) return InternalError.InvalidState; if (current_polygon == null) return InternalError.InvalidState; var ctx: SplinePlotterCtx = .{ .polygon = &current_polygon.?, .current_point = &current_point, }; var spline: Spline = .{ .a = current_point.?, .b = n.p1, .c = n.p2, .d = n.p3, .tolerance = tolerance, .plotter_impl = &.{ .ptr = &ctx, .line_to = SplinePlotterCtx.line_to, }, }; try spline.decompose(); }, .close_path => { if (initial_point == null) return InternalError.InvalidState; if (current_point == null) return InternalError.InvalidState; if (current_polygon == null) return InternalError.InvalidState; // No-op if our initial and current points are equal if (current_point.?.equal(initial_point.?)) continue; // Set the current point to the initial point. current_point = initial_point; }, } } return result; } const SplinePlotterCtx = struct { polygon: *Polygon, current_point: *?Point, fn line_to(ctx: *anyopaque, err_: *?anyerror, node: nodepkg.PathLineTo) void { const self: *SplinePlotterCtx = @ptrCast(@alignCast(ctx)); self.polygon.plot(node.point, null) catch |err| { err_.* = err; return; }; self.current_point.* = node.point; } };
https://raw.githubusercontent.com/vancluever/z2d/8d7750b7d0f9d77fd549e7740786b410dbf49a8a/src/internal/FillPlotter.zig
const concepts = @import("../lib.zig"); const concept = "UnsignedIntegral"; pub fn unsignedIntegral(comptime T: type) void { comptime { if (!concepts.traits.isIntegral(T) or concepts.traits.isSignedIntegral(T)) { concepts.fail(concept, ""); } } }
https://raw.githubusercontent.com/ibokuri/concepts/fc952a054389d3aeade915b5760c96c762651124/src/concepts/unsigned_integral.zig
const input = @embedFile("./i1.txt"); const std = @import("std"); // Moving clockwise => R // ---------------------------- // 3 // ┌─────┐ // │North│ // └─────┘ // ┌────┐ .─. ┌────┐ // 2│West│( )│East│0 // └────┘ `─' └────┘ // ┌─────┐ // │South│ // └─────┘ // 1 // ---------------------------- // Moving counter clockwise => L const Direction = enum(u32) { North = 3, // Up South = 1, // Down East = 0, // Right West = 2, // Left }; const Position = struct { x: i32, y: i32, }; pub fn main() !void { var split_iter = std.mem.split(u8, input, ", "); var position: Position = .{ .x = 0, .y = 0 }; var dir: Direction = Direction.North; while (split_iter.next()) |instr| { const turn = instr[0]; const dist = try std.fmt.parseInt(i32, instr[1..], 10); switch (turn) { 'R' => dir = @as(Direction, @enumFromInt((@intFromEnum(dir) + 1) % 4)), 'L' => dir = @as(Direction, @enumFromInt((@intFromEnum(dir) + 3) % 4)), else => return error.InvalidTurn, } switch (dir) { .North => position.y += dist, .South => position.y -= dist, .East => position.x += dist, .West => position.x -= dist, } } const result = @as(u32, std.math.absCast(position.x) + std.math.absCast(position.y)); std.debug.print("{}", .{result}); }
https://raw.githubusercontent.com/Mario-SO/advent-of-zig/99022111499fb7c9f06129f7744a8a2c6ebb56b7/src/aoc2016/day1a.zig
const std = @import("std"); const c = @import("sokol_zig"); const log = std.log.scoped(.app); pub const App = struct { const window_title = "Hello"; pub fn init(self: *@This()) !void { _ = self; } pub fn deinit(self: @This()) void { _ = self; } pub fn onInit(self: @This()) !void { _ = self; log.debug("onInit user", .{}); c.gfx.setup(.{ .environment = appEnv(), }); if (!c.gfx.sg_isvalid()) @panic("zonInit left sokol gfx in an invalid state"); c.debugtext.setup(.{ .fonts = .{ c.debugtext.sdtx_font_kc853(), .{}, .{}, .{}, .{}, .{}, .{}, .{}, }, }); if (!c.gfx.sg_isvalid()) @panic("zonInit left sokol gfx in an invalid state"); } pub fn onFrame(self: @This()) !void { _ = self; const screen_size: struct { w: f32, h: f32 } = .{ .w = @floatFromInt(c.app.sapp_width()), .h = @floatFromInt(c.app.sapp_height()), }; const str = "hello world!"; c.debugtext.sdtx_canvas(screen_size.w / 2.0, screen_size.h / 2.0); c.debugtext.sdtx_color3b(0, 0, 0); c.debugtext.sdtx_origin(8, 2); c.debugtext.sdtx_puts(str); // Render pass { var action = c.gfx.PassAction{}; action.colors[0] = .{ .load_action = .CLEAR, .store_action = .DONTCARE, .clear_value = .{ .r = 255, .g = 255, .b = 255, .a = 1 }, }; c.gfx.beginPass(.{ .action = action, .swapchain = appSwapchain(), }); defer { c.gfx.endPass(); c.gfx.commit(); } c.debugtext.sdtx_draw(); } } pub fn onEvent(self: @This(), event: c.app.Event) !void { _ = self; switch (event.type) { .INVALID, .KEY_DOWN, .KEY_UP, .CHAR, .MOUSE_DOWN, .MOUSE_UP, .MOUSE_SCROLL, .MOUSE_MOVE, .MOUSE_ENTER, .MOUSE_LEAVE, .TOUCHES_BEGAN, .TOUCHES_MOVED, .TOUCHES_ENDED, .TOUCHES_CANCELLED, .RESIZED, .ICONIFIED, .RESTORED, .FOCUSED, .UNFOCUSED, .SUSPENDED, .RESUMED, .QUIT_REQUESTED, .CLIPBOARD_PASTED, .FILES_DROPPED, .NUM, => { log.debug("event {s}", .{@tagName(event.type)}); }, } } }; fn appEnv() c.gfx.Environment { log.debug("appEnv", .{}); return .{ .defaults = .{ .color_format = @enumFromInt(c.app.sapp_color_format()), .depth_format = @enumFromInt(c.app.sapp_depth_format()), .sample_count = c.app.sapp_sample_count(), }, .metal = .{ .device = c.app.sapp_metal_get_device(), }, .d3d11 = .{ .device = c.app.sapp_d3d11_get_device(), .device_context = c.app.sapp_d3d11_get_device_context(), }, }; } fn appSwapchain() c.gfx.Swapchain { return .{ .width = c.app.sapp_width(), .height = c.app.sapp_height(), .sample_count = c.app.sapp_sample_count(), .color_format = @enumFromInt(c.app.sapp_color_format()), .depth_format = @enumFromInt(c.app.sapp_depth_format()), .metal = .{ .current_drawable = c.app.sapp_metal_get_current_drawable(), .depth_stencil_texture = c.app.sapp_metal_get_depth_stencil_texture(), .msaa_color_texture = c.app.sapp_metal_get_msaa_color_texture(), }, .d3d11 = .{ .render_view = c.app.sapp_d3d11_get_render_view(), .resolve_view = c.app.sapp_d3d11_get_resolve_view(), .depth_stencil_view = c.app.sapp_d3d11_get_depth_stencil_view(), }, .gl = .{ .framebuffer = c.app.sapp_gl_get_framebuffer() }, }; }
https://raw.githubusercontent.com/rsepassi/xos/29992dbf86781f8c2ef49745d9a3643b0eac3dfc/pkg/sokol_hello/app.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub fn Queue(T: type) type { const queue = struct { front: *node, back: *node, size: u64, allocator: Allocator, const node = struct { data: T, next: *node, }; pub fn init(allocator: Allocator) !Queue(T) { // Return default queue return .{ .front = undefined, .back = undefined, .size = 0, .allocator = allocator, }; } pub fn deinit(self: *Queue(T)) void { if (self.size == 0) return; var empty = false; // Loop until empty while (!empty) { if (self.front == self.back) empty = true; // Store new front as next in queue const newFront = self.front.next; // Deallocate font self.allocator.destroy(self.front); // Set front as new front self.front = newFront; } self.size = 0; } pub fn enQueue(self: *Queue(T), data: T) !void { const newNode = node{ .next = undefined, .data = data, }; // Allocate space for new node const newBack = try self.allocator.create(@TypeOf(newNode)); // Check if empty if (self.size == 0) { self.front = newBack; self.back = newBack; } else { self.back.next = newBack; } // Copy new node data into space newBack.* = newNode; // Point back to new back self.back = newBack; // Increment size self.size += 1; } pub fn deQueue(self: *Queue(T)) T { // Store data from front const data = self.front.data; // Store new front as next in queue const newFront = self.front.next; // Deallocate front self.allocator.destroy(self.front); // Set front as new front self.front = newFront; // Decrement size self.size -= 1; return data; } }; return queue; }
https://raw.githubusercontent.com/22102913/Common-Algorithms-Zig/bcfd4d358fe6ce6df60aec4288013043db849a33/src/queues.zig
const zignite = @import("../zignite.zig"); const expect = @import("std").testing.expect; const ProducerType = @import("producer_type.zig").ProducerType; test "empty:" { try expect(zignite.empty(i32).isEmpty()); } pub fn Empty(comptime T: type) type { return struct { pub const Type = ProducerType(@This(), T); pub const init = Type.State{}; pub fn next(_: Type.Event) Type.Action { return Type.Action._break(init); } pub const deinit = Type.nop; }; }
https://raw.githubusercontent.com/shunkeen/zignite/840dcda178be270a2e7eb273aed98e3740c82f22/src/producer/empty.zig
const std = @import("std"); const builtin = @import("builtin"); const Builder = std.build.Builder; const Allocator = std.mem.Allocator; const Sdk = @import("../Sdk.zig"); const UserConfig = Sdk.UserConfig; // This config stores tool paths for the current machine const build_config_dir = ".build_config"; const local_config_file = "android.json"; const print = std.debug.print; pub fn findUserConfig(b: *Builder, versions: Sdk.ToolchainVersions) !UserConfig { var str_buf: [5]u8 = undefined; var config = UserConfig{}; var config_dirty: bool = false; const local_config_path = pathConcat(b, build_config_dir, local_config_file); const config_path = b.pathFromRoot(local_config_path); const config_dir = b.pathFromRoot(build_config_dir); // Check for a user config file. if (std.fs.cwd().openFile(config_path, .{})) |file| { defer file.close(); const bytes = file.readToEndAlloc(b.allocator, 1 * 1000 * 1000) catch |err| { print("Unexpected error reading {s}: {s}\n", .{ config_path, @errorName(err) }); return err; }; var stream = std.json.TokenStream.init(bytes); if (std.json.parse(UserConfig, &stream, .{ .allocator = b.allocator })) |conf| { config = conf; } else |err| { print("Could not parse {s} ({s}).\n", .{ config_path, @errorName(err) }); return err; } } else |err| switch (err) { error.FileNotFound => { config_dirty = true; }, else => { print("Unexpected error opening {s}: {s}\n", .{ config_path, @errorName(err) }); return err; }, } // Verify the user config and set new values if needed // First the android home if (config.android_sdk_root.len > 0) { if (findProblemWithAndroidSdk(b, versions, config.android_sdk_root)) |problem| { print("Invalid android root directory: {s}\n {s}\n Looking for a new one.\n", .{ config.android_sdk_root, problem }); config.android_sdk_root = ""; // N.B. Don't dirty the file for this. We don't want to nuke the file if we can't find a replacement. } } if (config.android_sdk_root.len == 0) { // try to find the android home if (std.process.getEnvVarOwned(b.allocator, "ANDROID_HOME")) |value| { if (value.len > 0) { if (findProblemWithAndroidSdk(b, versions, value)) |problem| { print("Cannot use ANDROID_HOME ({s}):\n {s}\n", .{ value, problem }); } else { print("Using android sdk at ANDROID_HOME: {s}\n", .{value}); config.android_sdk_root = value; config_dirty = true; } } } else |_| { // ignore if env var is not found } } if (config.android_sdk_root.len == 0) { // try to find the android home if (std.process.getEnvVarOwned(b.allocator, "ANDROID_SDK_ROOT")) |value| { if (value.len > 0) { if (findProblemWithAndroidSdk(b, versions, value)) |problem| { print("Cannot use ANDROID_SDK_ROOT ({s}):\n {s}\n", .{ value, problem }); } else { print("Using android sdk at ANDROID_SDK_ROOT: {s}\n", .{value}); config.android_sdk_root = value; config_dirty = true; } } } else |_| { // ignore environment variable failure } } var android_studio_path: []const u8 = ""; // On windows, check for an android studio install. // If it's present, it may have the sdk path stored in the registry. // If not, check the default install location. if (builtin.os.tag == .windows) { const HKEY = ?*opaque {}; const LSTATUS = u32; const DWORD = u32; // const HKEY_CLASSES_ROOT = @intToPtr(HKEY, 0x80000000); const HKEY_CURRENT_USER = @intToPtr(HKEY, 0x80000001); const HKEY_LOCAL_MACHINE = @intToPtr(HKEY, 0x80000002); // const HKEY_USERS = @intToPtr(HKEY, 0x80000003); // const RRF_RT_ANY: DWORD = 0xFFFF; // const RRF_RT_REG_BINARY: DWORD = 0x08; // const RRF_RT_REG_DWORD: DWORD = 0x10; // const RRF_RT_REG_EXPAND_SZ: DWORD = 0x04; // const RRF_RT_REG_MULTI_SZ: DWORD = 0x20; // const RRF_RT_REG_NONE: DWORD = 0x01; // const RRF_RT_REG_QWORD: DWORD = 0x40; const RRF_RT_REG_SZ: DWORD = 0x02; // const RRF_RT_DWORD = RRF_RT_REG_DWORD | RRF_RT_REG_BINARY; // const RRF_RT_QWORD = RRF_RT_REG_QWORD | RRF_RT_REG_BINARY; // const RRF_NOEXPAND: DWORD = 0x10000000; // const RRF_ZEROONFAILURE: DWORD = 0x20000000; // const RRF_SUBKEY_WOW6464KEY: DWORD = 0x00010000; // const RRF_SUBKEY_WOW6432KEY: DWORD = 0x00020000; const ERROR_SUCCESS: LSTATUS = 0; const ERROR_MORE_DATA: LSTATUS = 234; const reg = struct { extern "Advapi32" fn RegOpenKeyA(key: HKEY, subKey: [*:0]const u8, result: *HKEY) LSTATUS; extern "Advapi32" fn RegCloseKey(key: HKEY) LSTATUS; extern "Advapi32" fn RegGetValueA(key: HKEY, subKey: ?[*:0]const u8, value: [*:0]const u8, flags: DWORD, type: ?*DWORD, data: ?*anyopaque, len: ?*DWORD) LSTATUS; fn getStringAlloc(allocator: Allocator, key: HKEY, value: [*:0]const u8) ?[]const u8 { // query the length var len: DWORD = 0; var res = RegGetValueA(key, null, value, RRF_RT_REG_SZ, null, null, &len); if (res == ERROR_SUCCESS) { if (len == 0) { return &[_]u8{}; } } else if (res != ERROR_MORE_DATA) { return null; } // get the data const buffer = allocator.alloc(u8, len) catch unreachable; len = @intCast(DWORD, buffer.len); res = RegGetValueA(key, null, value, RRF_RT_REG_SZ, null, buffer.ptr, &len); if (res == ERROR_SUCCESS) { for (buffer[0..len]) |c, i| { if (c == 0) return buffer[0..i]; } return buffer[0..len]; } allocator.free(buffer); return null; } }; // Get the android studio registry entry var android_studio_key: HKEY = for ([_]HKEY{ HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE }) |root_key| { var software: HKEY = null; if (reg.RegOpenKeyA(root_key, "software", &software) == ERROR_SUCCESS) { defer _ = reg.RegCloseKey(software); var android: HKEY = null; if (reg.RegOpenKeyA(software, "Android Studio", &android) == ERROR_SUCCESS) { if (android != null) break android; } } } else null; // Grab the paths to the android studio install and the sdk install. if (android_studio_key != null) { defer _ = reg.RegCloseKey(android_studio_key); if (reg.getStringAlloc(b.allocator, android_studio_key, "Path")) |path| { android_studio_path = path; } else { print("Could not get android studio path\n", .{}); } if (reg.getStringAlloc(b.allocator, android_studio_key, "SdkPath")) |sdk_path| { if (sdk_path.len > 0) { if (findProblemWithAndroidSdk(b, versions, sdk_path)) |problem| { print("Cannot use Android Studio sdk ({s}):\n {s}\n", .{ sdk_path, problem }); } else { print("Using android sdk from Android Studio: {s}\n", .{sdk_path}); config.android_sdk_root = sdk_path; config_dirty = true; } } } } // If we didn't find an sdk in the registry, check the default install location. // On windows, this is AppData/Local/Android. if (config.android_sdk_root.len == 0) { if (std.process.getEnvVarOwned(b.allocator, "LOCALAPPDATA")) |appdata_local| { const sdk_path = pathConcat(b, appdata_local, "Android"); if (findProblemWithAndroidSdk(b, versions, sdk_path)) |problem| { print("Cannot use default Android Studio SDK\n at {s}:\n {s}\n", .{ sdk_path, problem }); } else { print("Using android sdk from Android Studio: {s}\n", .{sdk_path}); config.android_sdk_root = sdk_path; config_dirty = true; } } else |_| { // ignore env } } } // Finally, if we still don't have an sdk, see if `adb` is on the path and try to use that. if (config.android_sdk_root.len == 0) { if (findProgramPath(b.allocator, "adb")) |path| { const sep = std.fs.path.sep; if (std.mem.lastIndexOfScalar(u8, path, sep)) |index| { var rest = path[0..index]; const parent = "platform-tools"; if (std.mem.endsWith(u8, rest, parent) and rest[rest.len - parent.len - 1] == sep) { const sdk_path = rest[0 .. rest.len - parent.len - 1]; if (findProblemWithAndroidSdk(b, versions, sdk_path)) |problem| { print("Cannot use SDK near adb\n at {s}:\n {s}\n", .{ sdk_path, problem }); } else { print("Using android sdk near adb: {s}\n", .{sdk_path}); config.android_sdk_root = sdk_path; config_dirty = true; } } } } } // Next up, NDK. if (config.android_ndk_root.len > 0) { if (findProblemWithAndroidNdk(b, versions, config.android_ndk_root)) |problem| { print("Saved NDK is invalid ({s})\n{s}\n", .{ config.android_ndk_root, problem }); config.android_ndk_root = ""; } } // first, check ANDROID_NDK_ROOT if (config.android_ndk_root.len == 0) { if (std.process.getEnvVarOwned(b.allocator, "ANDROID_NDK_ROOT")) |value| { if (value.len > 0) { if (findProblemWithAndroidNdk(b, versions, value)) |problem| { print("Cannot use ANDROID_NDK_ROOT ({s}):\n {s}\n", .{ value, problem }); } else { print("Using android ndk at ANDROID_NDK_ROOT: {s}\n", .{value}); config.android_ndk_root = value; config_dirty = true; } } } else |_| {} } // Then check for a side-by-side install if (config.android_ndk_root.len == 0) { if (config.android_sdk_root.len > 0) { const ndk_root = std.fs.path.join(b.allocator, &[_][]const u8{ config.android_sdk_root, "ndk", versions.ndk_version, }) catch unreachable; if (findProblemWithAndroidNdk(b, versions, ndk_root)) |problem| { print("Cannot use side by side NDK ({s}):\n {s}\n", .{ ndk_root, problem }); } else { print("Using side by side NDK install: {s}\n", .{ndk_root}); config.android_ndk_root = ndk_root; config_dirty = true; } } } // Finally, we need to find the JDK, for jarsigner. if (config.java_home.len > 0) { if (findProblemWithJdk(b, config.java_home)) |problem| { print("Cannot use configured java install {s}: {s}\n", .{ config.java_home, problem }); config.java_home = ""; } } // Check the JAVA_HOME variable if (config.java_home.len == 0) { if (std.process.getEnvVarOwned(b.allocator, "JAVA_HOME")) |value| { if (value.len > 0) { if (findProblemWithJdk(b, value)) |problem| { print("Cannot use JAVA_HOME ({s}):\n {s}\n", .{ value, problem }); } else { print("Using java JAVA_HOME: {s}\n", .{value}); config.java_home = value; config_dirty = true; } } } else |_| {} } // Look for `where jarsigner` if (config.java_home.len == 0) { if (findProgramPath(b.allocator, "jarsigner")) |path| { const sep = std.fs.path.sep; if (std.mem.lastIndexOfScalar(u8, path, sep)) |last_slash| { if (std.mem.lastIndexOfScalar(u8, path[0..last_slash], sep)) |second_slash| { const home = path[0..second_slash]; if (findProblemWithJdk(b, home)) |problem| { print("Cannot use java at ({s}):\n {s}\n", .{ home, problem }); } else { print("Using java at {s}\n", .{home}); config.java_home = home; config_dirty = true; } } } } } // If we have Android Studio installed, it packages a JDK. // Check for that. if (config.java_home.len == 0) { if (android_studio_path.len > 0) { const packaged_jre = pathConcat(b, android_studio_path, "jre"); if (findProblemWithJdk(b, packaged_jre)) |problem| { print("Cannot use Android Studio java at ({s}):\n {s}\n", .{ packaged_jre, problem }); } else { print("Using java from Android Studio: {s}\n", .{packaged_jre}); config.java_home = packaged_jre; config_dirty = true; } } } // Write out the new config if (config_dirty) { std.fs.cwd().makeDir(config_dir) catch {}; var file = std.fs.cwd().createFile(config_path, .{}) catch |err| { print("Couldn't write config file {s}: {s}\n\n", .{ config_path, @errorName(err) }); return err; }; defer file.close(); var buf_writer = std.io.bufferedWriter(file.writer()); std.json.stringify(config, .{}, buf_writer.writer()) catch |err| { print("Error writing config file {s}: {s}\n", .{ config_path, @errorName(err) }); return err; }; buf_writer.flush() catch |err| { print("Error writing config file {s}: {s}\n", .{ config_path, @errorName(err) }); return err; }; } // Check if the config is invalid. if (config.android_sdk_root.len == 0 or config.android_ndk_root.len == 0 or config.java_home.len == 0) { print("\nCould not find all needed tools. Please edit {s} to specify their paths.\n\n", .{local_config_path}); if (config.android_sdk_root.len == 0) { print("Android SDK root is missing. Edit the config file, or set ANDROID_SDK_ROOT to your android install.\n", .{}); print("You will need build tools version {s} and android sdk platform {s}\n\n", .{ versions.build_tools_version, versions.androidSdkString(&str_buf) }); } if (config.android_ndk_root.len == 0) { print("Android NDK root is missing. Edit the config file, or set ANDROID_NDK_ROOT to your android NDK install.\n", .{}); print("You will need NDK version {s}\n\n", .{versions.ndk_version}); } if (config.java_home.len == 0) { print("Java JDK is missing. Edit the config file, or set JAVA_HOME to your JDK install.\n", .{}); if (builtin.os.tag == .windows) { print("Installing Android Studio will also install a suitable JDK.\n", .{}); } print("\n", .{}); } std.os.exit(1); } if (config_dirty) { print("New configuration:\nSDK: {s}\nNDK: {s}\nJDK: {s}\n", .{ config.android_sdk_root, config.android_ndk_root, config.java_home }); } return config; } fn findProgramPath(allocator: Allocator, program: []const u8) ?[]const u8 { const args: []const []const u8 = if (builtin.os.tag == .windows) &[_][]const u8{ "where", program } else &[_][]const u8{ "which", program }; const proc = std.ChildProcess.init(args, allocator) catch return null; defer proc.deinit(); proc.stderr_behavior = .Close; proc.stdout_behavior = .Pipe; proc.stdin_behavior = .Close; proc.spawn() catch return null; const stdout = proc.stdout.?.readToEndAlloc(allocator, 1024) catch return null; const term = proc.wait() catch return null; switch (term) { .Exited => |rc| { if (rc != 0) return null; }, else => return null, } var path = std.mem.trim(u8, stdout, " \t\r\n"); if (std.mem.indexOfScalar(u8, path, '\n')) |index| { path = std.mem.trim(u8, path[0..index], " \t\r\n"); } if (path.len > 0) return path; return null; } // Returns the problem with an android_home path. // If it seems alright, returns null. fn findProblemWithAndroidSdk(b: *Builder, versions: Sdk.ToolchainVersions, path: []const u8) ?[]const u8 { std.fs.cwd().access(path, .{}) catch |err| { if (err == error.FileNotFound) return "Directory does not exist"; return b.fmt("Cannot access {s}, {s}", .{ path, @errorName(err) }); }; const build_tools = pathConcat(b, path, "build-tools"); std.fs.cwd().access(build_tools, .{}) catch |err| { return b.fmt("Cannot access build-tools/, {s}", .{@errorName(err)}); }; const versioned_tools = pathConcat(b, build_tools, versions.build_tools_version); std.fs.cwd().access(versioned_tools, .{}) catch |err| { if (err == error.FileNotFound) { return b.fmt("Missing build tools version {s}", .{versions.build_tools_version}); } else { return b.fmt("Cannot access build-tools/{s}/, {s}", .{ versions.build_tools_version, @errorName(err) }); } }; var str_buf: [5]u8 = undefined; const android_version_str = versions.androidSdkString(&str_buf); const platforms = pathConcat(b, path, "platforms"); const platform_version = pathConcat(b, platforms, b.fmt("android-{d}", .{versions.android_sdk_version})); std.fs.cwd().access(platform_version, .{}) catch |err| { if (err == error.FileNotFound) { return b.fmt("Missing android platform version {s}", .{android_version_str}); } else { return b.fmt("Cannot access platforms/android-{s}, {s}", .{ android_version_str, @errorName(err) }); } }; return null; } // Returns the problem with an android ndk path. // If it seems alright, returns null. fn findProblemWithAndroidNdk(b: *Builder, versions: Sdk.ToolchainVersions, path: []const u8) ?[]const u8 { std.fs.cwd().access(path, .{}) catch |err| { if (err == error.FileNotFound) return "Directory does not exist"; return b.fmt("Cannot access {s}, {s}", .{ path, @errorName(err) }); }; const ndk_include_path = std.fs.path.join(b.allocator, &[_][]const u8{ path, "sysroot", "usr", "include", }) catch unreachable; std.fs.cwd().access(ndk_include_path, .{}) catch |err| { return b.fmt("Cannot access sysroot/usr/include/, {s}\nMake sure you are using NDK {s}.", .{ @errorName(err), versions.ndk_version }); }; return null; } // Returns the problem with a jdk install. // If it seems alright, returns null. fn findProblemWithJdk(b: *Builder, path: []const u8) ?[]const u8 { std.fs.cwd().access(path, .{}) catch |err| { if (err == error.FileNotFound) return "Directory does not exist"; return b.fmt("Cannot access {s}, {s}", .{ path, @errorName(err) }); }; const target_executable = if (builtin.os.tag == .windows) "bin\\jarsigner.exe" else "bin/jarsigner"; const target_path = pathConcat(b, path, target_executable); std.fs.cwd().access(target_path, .{}) catch |err| { return b.fmt("Cannot access jarsigner, {s}", .{@errorName(err)}); }; return null; } fn pathConcat(b: *Builder, left: []const u8, right: []const u8) []const u8 { return std.fs.path.join(b.allocator, &[_][]const u8{ left, right }) catch unreachable; }
https://raw.githubusercontent.com/SpexGuy/Zig-Oculus-Quest/faa672c704e5d94940b0f76b51d50c7c32d5d866/build/auto-detect.zig
const std = @import("std"); const kernel_config = .{ .arch = std.Target.Cpu.Arch.x86_64, }; const FeatureMod = struct { add: std.Target.Cpu.Feature.Set = std.Target.Cpu.Feature.Set.empty, sub: std.Target.Cpu.Feature.Set = std.Target.Cpu.Feature.Set.empty, }; fn getFeatureMod(comptime arch: std.Target.Cpu.Arch) FeatureMod { var mod: FeatureMod = .{}; switch (arch) { .x86_64 => { const Features = std.Target.x86.Feature; mod.add.addFeature(@intFromEnum(Features.soft_float)); mod.sub.addFeature(@intFromEnum(Features.mmx)); mod.sub.addFeature(@intFromEnum(Features.sse)); mod.sub.addFeature(@intFromEnum(Features.sse2)); mod.sub.addFeature(@intFromEnum(Features.avx)); mod.sub.addFeature(@intFromEnum(Features.avx2)); }, else => @compileError("Unimplemented architecture"), } return mod; } pub fn build(b: *std.Build) void { const feature_mod = getFeatureMod(kernel_config.arch); var target: std.zig.CrossTarget = .{ .cpu_arch = kernel_config.arch, .os_tag = .freestanding, .abi = .none, .cpu_features_add = feature_mod.add, .cpu_features_sub = feature_mod.sub, }; const kernel_optimize = b.standardOptimizeOption(.{}); const kernel = b.addExecutable(.{ .name = "kernel", .root_source_file = .{ .path = "kernel/src/main.zig" }, .target = target, .optimize = kernel_optimize, }); kernel.code_model = .kernel; kernel.pie = true; kernel.setLinkerScriptPath(.{ .path = "kernel/linker.ld" }); const kernel_step = b.step("kernel", "Build the kernel"); kernel_step.dependOn(&b.addInstallArtifact(kernel).step); const limine_cmd = b.addSystemCommand(&.{ "bash", "scripts/limine.sh" }); const limine_step = b.step("limine", "Download and build limine bootloader"); limine_step.dependOn(&limine_cmd.step); const iso_cmd = b.addSystemCommand(&.{ "bash", "scripts/iso.sh" }); iso_cmd.step.dependOn(limine_step); iso_cmd.step.dependOn(kernel_step); const iso_step = b.step("iso", "Build an iso file"); iso_step.dependOn(&iso_cmd.step); const run_iso_cmd = b.addSystemCommand(&.{ "bash", "scripts/run_iso.sh" }); run_iso_cmd.step.dependOn(iso_step); const run_iso_step = b.step("run-iso", "Run ISO file in emulator"); run_iso_step.dependOn(&run_iso_cmd.step); const clean_cmd = b.addSystemCommand(&.{ "rm", "-f", "ytos.iso", "-r", "zig-cache", "zig-out", }); const clean_step = b.step("clean", "Remove all generated files"); clean_step.dependOn(&clean_cmd.step); }
https://raw.githubusercontent.com/Arnau478/ytos/4a54a3155c996be251e3ae00f5c9ad697066460d/build.zig
// https://csprimer.com/watch/fast-pangram/ const std = @import("std"); pub export fn main() void { run() catch unreachable; } fn run() !void { const in = std.io.getStdIn(); defer in.close(); var in_buf = std.io.bufferedReader(in.reader()); var reader = in_buf.reader(); const out = std.io.getStdOut(); defer out.close(); var out_buf = std.io.bufferedWriter(out.writer()); var writer = out_buf.writer(); var alloc = std.heap.page_allocator; const BIG_SIZE = std.math.maxInt(usize); while (try reader.readUntilDelimiterOrEofAlloc(alloc, '\n', BIG_SIZE)) |msg| { if (!is_panagram(msg)) continue; try writer.print("{s}\n", .{msg}); try out_buf.flush(); } } test "is_panagram works on partial phrase" { const phrase: []const u8 = "ABC def xyz"; try std.testing.expect(!is_panagram(phrase)); } test "is_panagram works on full phrase" { const phrase: []const u8 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz"; try std.testing.expect(is_panagram(phrase)); } fn is_panagram(phrase: []const u8) bool { const COUNT_ALPHA = 26; var is_present = std.bit_set.IntegerBitSet(COUNT_ALPHA).initEmpty(); for (phrase) |char| { if (!std.ascii.isAlphabetic(char)) continue; const index = std.ascii.toLower(char) - 'a'; is_present.set(index); } return is_present.count() == COUNT_ALPHA; }
https://raw.githubusercontent.com/CrepeGoat/cs-primer/35f7a2529ecfffe219365a2a67237745b2bc24af/src/computer-systems/intro-to-c/fast-pangram.zig
const common = @import("../common.zig"); const jsFree = common.jsFree; const jsCreateClass = common.jsCreateClass; const Classes = common.Classes; const toJSBool = common.toJSBool; const Undefined = common.Undefined; const True = common.True; const object = @import("../object.zig"); const Object = object.Object; const getObjectValue = object.getObjectValue; const AsyncFunction = @import("../function.zig").AsyncFunction; const WritableStream = @import("writable.zig").WritableStream; const Array = @import("../array.zig").Array; // https://github.com/cloudflare/workers-types/blob/master/index.d.ts#L989 pub const PipeToOptions = struct { preventClose: ?bool = null, preventAbort: ?bool = null, preventCancel: ?bool = null, // NOTE: This exists but will prob never be implemented. // signal: ?AbortSignal = null, pub fn toObject (self: *const PipeToOptions) Object { const obj = Object.new(); if (self.preventClose != null) { obj.setID("ignoreMethod", toJSBool(self.preventClose.?)); } // if (self.preventAbort != null) { obj.setID("ignoreMethod", toJSBool(self.preventAbort.?)); } // if (self.preventCancel != null) { obj.setID("ignoreMethod", toJSBool(self.preventCancel.?)); } return obj; } }; // TODO: Plenty of functions/structs not implemented here yet. // https://developers.cloudflare.com/workers/runtime-apis/streams/readablestream/ // https://github.com/cloudflare/workers-types/blob/master/index.d.ts#L1155 pub const ReadableStream = struct { id: u32, pub fn init (ptr: u32) ReadableStream { return ReadableStream{ .id = ptr }; } // TODO: Support inputs pub fn new () ReadableStream { return ReadableStream{ .id = jsCreateClass(Classes.ReadableStream.toInt(), Undefined) }; } pub fn free (self: ReadableStream) void { jsFree(self.id); } pub fn locked (self: *const ReadableStream) bool { const jsPtr = getObjectValue(self.id, "locked"); return jsPtr == True; } pub fn cancel (self: *const ReadableStream) void { const func = AsyncFunction{ .id = getObjectValue(self.id, "cancel") }; defer func.free(); func.call(); } pub fn pipeTo ( self: *const ReadableStream, destination: *const WritableStream, options: PipeToOptions ) void { const optObj = options.toObject(); defer optObj.free(); const func = AsyncFunction{ .id = getObjectValue(self.id, "pipeTo") }; defer func.free(); // setup args const args = Array.new(); defer args.free(); args.push(&destination); args.push(&optObj); func.call(args.id); } };
https://raw.githubusercontent.com/CraigglesO/workers-zig/af4c3475a0d01e200ccf88d79987df0e7ea815fa/lib/bindings/streams/readable.zig
const std = @import("std"); fn Parameter(comptime T: type) type { return struct { long_name: ?[]const u8 = null, short_name: u8 = 0, description: []const u8 = "", metavar: ?[]const u8 = null, default: ?T = null, value: ?T = null, allocator: ?std.mem.Allocator = null, ref: *T, const Self = @This(); fn match_option(self: *Self, raw: []const u8) bool { if (raw[0] != '-') { return false; } if (raw.len == 2 and raw[1] == self.short_name) { return true; } if (raw[1] != '-') { return false; } if (raw.len >= 2 and std.mem.eql(u8, raw[2..], self.long_name.?)) { return true; } return false; } pub fn enter(self: *Self, args: [][:0]u8, i: *usize) !bool { if (self.value != null) { return false; } else if (self.short_name == 0 and self.long_name == null) { try self.take(args, i); return true; } else if (self.match_option(args[i.*])) { i.* += 1; try self.take(args, i); return true; } return false; } pub fn take(self: *Self, args: [][:0]u8, i: *usize) !void { switch (T) { inline bool => { self.value = true; return; }, inline []const u8 => { if (i.* >= args.len) { return error.MissingValue; } self.value = args[i.*]; i.* += 1; return; }, inline [][]const u8 => { if (i.* >= args.len) { return error.MissingValue; } var list = std.ArrayList([]const u8).init(self.allocator.?); while (i.* < args.len and args[i.*][0] != '-') { try list.append(args[i.*]); i.* += 1; } self.value = list.items; }, inline else => @compileError("Unsupported type"), } } pub fn post(self: *Self) !void { if (self.value == null) { if (self.default == null) { return error.MissingValue; } self.value = self.default; } self.ref.* = self.value.?; } pub fn print_help(self: *const Self) !void { var stdout = std.io.getStdOut().writer(); try stdout.print(" ", .{}); if (self.long_name != null) { try stdout.print("--{s}", .{self.long_name.?}); if (self.short_name != 0) { try stdout.print(", ", .{}); } } if (self.short_name != 0) { try stdout.print("-{c}", .{self.short_name}); } if (self.metavar != null) { if (self.long_name != null or self.short_name != 0) { try stdout.print(" ", .{}); } try stdout.print("{s}", .{self.metavar.?}); } try stdout.print("\n", .{}); if (self.description.len != 0) { try stdout.print(" {s}\n", .{self.description}); } } }; } const ParameterTrait = union(enum) { boolean: *Parameter(bool), string: *Parameter([]const u8), strings: *Parameter([][]const u8), const Self = @This(); pub fn enter(self: *Self, args: [][:0]u8, i: *usize) !bool { return switch (self.*) { inline else => |p| p.enter(args, i), }; } pub fn post(self: *Self) !void { return switch (self.*) { inline else => |p| p.post(), }; } pub fn print_help(self: *const Self) !void { return switch (self.*) { inline else => |p| p.print_help(), }; } }; pub const Arguments = struct { arena: std.heap.ArenaAllocator, name: []const u8, version: []const u8, show_version: bool = undefined, show_help: bool = undefined, files: [][]const u8 = undefined, commands: [][]const u8 = undefined, const Self = @This(); pub fn init( allocator: std.mem.Allocator, name: []const u8, version: []const u8, ) Self { var arena = std.heap.ArenaAllocator.init(allocator); var self = Self{ .arena = arena, .name = name, .version = version, }; return self; } pub fn parse(self: *Self) !void { var allocator = self.arena.allocator(); var help = Parameter(bool){ .long_name = "help", .short_name = 'h', .description = "print the help message", .default = false, .ref = &self.show_help, }; var version = Parameter(bool){ .long_name = "version", .short_name = 'v', .description = try std.fmt.allocPrint( allocator, "print the version of {s}", .{self.name}, ), .default = false, .ref = &self.show_version, }; var files = Parameter([][]const u8){ .description = "file(s) to edit", .metavar = "FILE..", .default = &.{}, .ref = &self.files, .allocator = allocator, }; var commands = Parameter([][]const u8){ .long_name = "", .description = "command(s) to run", .metavar = "COMMAND..", .default = &.{}, .ref = &self.commands, .allocator = allocator, }; var parameters = [_]ParameterTrait{ .{ .boolean = &help }, .{ .boolean = &version }, .{ .strings = &files }, .{ .strings = &commands }, }; const args = try std.process.argsAlloc(allocator); errdefer self.deinit(); var i: usize = 1; while (i < args.len) { var found = false; for (0..parameters.len) |j| { var p = parameters[j]; found = try p.enter(args, &i); if (found) { break; } } if (!found) { return error.InvalidOption; } } for (0..parameters.len) |j| { var p = parameters[j]; try p.post(); } if (self.show_help) { try self.print_help(parameters[0..2], parameters[2..]); std.os.exit(0); } else if (self.show_version) { try self.print_version(); std.os.exit(0); } } pub fn print_help(self: *Self, options: []const ParameterTrait, positionals: []const ParameterTrait) !void { var stdout = std.io.getStdOut().writer(); try stdout.print( "Usage: {s} [OPTIONS] [FILE..] [--] [COMMAND..]\n", .{self.name}, ); try stdout.print("\n", .{}); try stdout.print("Options:\n", .{}); for (options) |p| { try p.print_help(); } if (positionals.len != 0) { try stdout.print("\n", .{}); try stdout.print("Positionals Arguments:\n", .{}); for (positionals) |p| { try p.print_help(); } } try stdout.print("\n", .{}); try stdout.print("{s}: {s}\n", .{ self.name, self.version }); } pub fn print_version(self: *Self) !void { var stdout = std.io.getStdOut().writer(); try stdout.print("{s}\n", .{self.version}); } pub fn deinit(self: *Arguments) void { self.arena.deinit(); } };
https://raw.githubusercontent.com/pseudocc/robin/0edde52fdd49508a2b759913ffbbfeab26d7ae80/src/args.zig
const std = @import("std"); const gen = @import("generate.zig"); const print = std.debug.print; const Str = []const u8; pub var items = gen.items; pub const Item = gen.Item; pub var player = gen.player; pub const ambiguous = gen.ambiguous; pub const Distance = gen.Distance; pub fn getDistanceNumber(from: ?*Item, to: ?*Item) usize { return @intFromEnum(getDistance(from, to)); } pub fn getDistance(from: ?*Item, to: ?*Item) Distance { if (to == null or from == null) { return .distUnknownObject; } if (from == to) { return .distSelf; } if (isHolding(from, to)) { return .distHeld; } if (isHolding(to, from)) { return .distLocation; } if (isHolding(from.?.location, to)) { return .distHere; } if (getPassage(from.?.location, to) != null) { return .distOverthere; } if (isHolding(from, to.?.location)) { return .distHeldContained; } if (isHolding(from.?.location, to.?.location)) { return .distHereContained; } return .distNotHere; } fn isHolding(container: ?*Item, item: ?*Item) bool { if (container == null or item == null) return false; return item.?.location == container; } pub fn actorHere() ?*Item { const location = player.location; for (&items) |*item| { if (isHolding(location, item) and item.type == .guard) { return item; } } return null; } pub fn getItem(noun: ?Str, from: ?*Item, maxDistance: Distance) ?*Item { const word = noun orelse return null; const max = @intFromEnum(maxDistance); var item: ?*Item = null; for (&items) |*value| { if (value.hasTag(word) and getDistanceNumber(from, value) <= max) { if (item != null) return &ambiguous; item = value; } } else return item; } pub fn getPassage(from: ?*Item, to: ?*Item) ?*Item { if (from == null and to == null) return null; for (&items) |*item| { if (isHolding(from, item) and item.destination == to) { return item; } } return null; } pub fn getVisible(intention: Str, noun: ?Str) ?*Item { const item = getItem(noun, player, Distance.distOverthere); // print("get item: {s}", .{item.?}) if (item == null) { if (getItem(noun, player, Distance.distNotHere) == null) { print("I don't understand {s}.\n", .{intention}); } else { print("You don't see any {s} here.\n", .{noun.?}); } } else if (item.?.isAmbiguous()) { print("Please be specific about which {s} you mean.\n", .{noun.?}); return null; } return item; } pub fn listAtLocation(location: *Item) usize { var count: usize = 0; for (&items) |*item| { if (!item.isPlayer() and item.isLocate(location)) { if (count == 0) { print("You see:\n", .{}); } print("{s}\n", .{item.desc}); count += 1; } } return count; }
https://raw.githubusercontent.com/jiangbo/todo/54b6dec1f75b8e0d195fe0f63107005438c9ce2c/zig/advent/src/world.zig
const std = @import("std"); pub const Options = struct { enable_cross_platform_determinism: bool = true, }; pub const Package = struct { target: std.Build.ResolvedTarget, options: Options, zmath: *std.Build.Module, zmath_options: *std.Build.Module, pub fn link(pkg: Package, exe: *std.Build.Step.Compile) void { exe.root_module.addImport("zmath", pkg.zmath); exe.root_module.addImport("zmath_options", pkg.zmath_options); } }; pub fn package( b: *std.Build, target: std.Build.ResolvedTarget, _: std.builtin.Mode, args: struct { options: Options = .{}, }, ) Package { const step = b.addOptions(); step.addOption( bool, "enable_cross_platform_determinism", args.options.enable_cross_platform_determinism, ); const zmath_options = step.createModule(); const zmath = b.addModule("zmath", .{ .root_source_file = .{ .path = thisDir() ++ "/src/main.zig" }, .imports = &.{ .{ .name = "zmath_options", .module = zmath_options }, }, }); return .{ .target = target, .options = args.options, .zmath = zmath, .zmath_options = zmath_options, }; } pub fn build(b: *std.Build) void { const optimize = b.standardOptimizeOption(.{}); const target = b.standardTargetOptions(.{}); _ = package(b, target, optimize, .{ .options = .{ .enable_cross_platform_determinism = b.option(bool, "enable_cross_platform_determinism", "Whether to enable cross-platform determinism.") orelse true, } }); const test_step = b.step("test", "Run zmath tests"); test_step.dependOn(runTests(b, optimize, target)); const benchmark_step = b.step("benchmark", "Run zmath benchmarks"); benchmark_step.dependOn(runBenchmarks(b, target, optimize)); } pub fn runTests( b: *std.Build, optimize: std.builtin.Mode, target: std.Build.ResolvedTarget, ) *std.Build.Step { const tests = b.addTest(.{ .name = "zmath-tests", .root_source_file = .{ .path = thisDir() ++ "/src/main.zig" }, .target = target, .optimize = optimize, }); const zmath_pkg = package(b, target, optimize, .{}); tests.root_module.addImport("zmath_options", zmath_pkg.zmath_options); return &b.addRunArtifact(tests).step; } pub fn runBenchmarks( b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, ) *std.Build.Step { const exe = b.addExecutable(.{ .name = "zmath-benchmarks", .root_source_file = .{ .path = thisDir() ++ "/src/benchmark.zig" }, .target = target, .optimize = optimize, }); const zmath_pkg = package(b, target, .ReleaseFast, .{}); exe.root_module.addImport("zmath", zmath_pkg.zmath); return &b.addRunArtifact(exe).step; } inline fn thisDir() []const u8 { return comptime std.fs.path.dirname(@src().file) orelse "."; }
https://raw.githubusercontent.com/candrewlee14/learn-opengl-zig/e4ef89200c7194766a72003f6581f200482759d1/libs/zmath/build.zig
const std = @import("std"); const utils = @import("utils.zig"); const res = @import("res.zig"); const SourceBytes = @import("literals.zig").SourceBytes; // https://learn.microsoft.com/en-us/windows/win32/menurc/about-resource-files pub const Resource = enum { accelerators, bitmap, cursor, dialog, dialogex, /// As far as I can tell, this is undocumented; the most I could find was this: /// https://www.betaarchive.com/wiki/index.php/Microsoft_KB_Archive/91697 dlginclude, /// Undocumented, basically works exactly like RCDATA dlginit, font, html, icon, menu, menuex, messagetable, plugplay, // Obsolete rcdata, stringtable, /// Undocumented toolbar, user_defined, versioninfo, vxd, // Obsolete // Types that are treated as a user-defined type when encountered, but have // special meaning without the Visual Studio GUI. We match the Win32 RC compiler // behavior by acting as if these keyword don't exist when compiling the .rc // (thereby treating them as user-defined). //textinclude, // A special resource that is interpreted by Visual C++. //typelib, // A special resource that is used with the /TLBID and /TLBOUT linker options // Types that can only be specified by numbers, they don't have keywords cursor_num, icon_num, string_num, anicursor_num, aniicon_num, fontdir_num, manifest_num, const map = std.ComptimeStringMapWithEql(Resource, .{ .{ "ACCELERATORS", .accelerators }, .{ "BITMAP", .bitmap }, .{ "CURSOR", .cursor }, .{ "DIALOG", .dialog }, .{ "DIALOGEX", .dialogex }, .{ "DLGINCLUDE", .dlginclude }, .{ "DLGINIT", .dlginit }, .{ "FONT", .font }, .{ "HTML", .html }, .{ "ICON", .icon }, .{ "MENU", .menu }, .{ "MENUEX", .menuex }, .{ "MESSAGETABLE", .messagetable }, .{ "PLUGPLAY", .plugplay }, .{ "RCDATA", .rcdata }, .{ "STRINGTABLE", .stringtable }, .{ "TOOLBAR", .toolbar }, .{ "VERSIONINFO", .versioninfo }, .{ "VXD", .vxd }, }, std.comptime_string_map.eqlAsciiIgnoreCase); pub fn fromString(bytes: SourceBytes) Resource { const maybe_ordinal = res.NameOrOrdinal.maybeOrdinalFromString(bytes); if (maybe_ordinal) |ordinal| { if (ordinal.ordinal >= 256) return .user_defined; return fromRT(@enumFromInt(ordinal.ordinal)); } return map.get(bytes.slice) orelse .user_defined; } // TODO: Some comptime validation that RT <-> Resource conversion is synced? pub fn fromRT(rt: res.RT) Resource { return switch (rt) { .ACCELERATOR => .accelerators, .ANICURSOR => .anicursor_num, .ANIICON => .aniicon_num, .BITMAP => .bitmap, .CURSOR => .cursor_num, .DIALOG => .dialog, .DLGINCLUDE => .dlginclude, .DLGINIT => .dlginit, .FONT => .font, .FONTDIR => .fontdir_num, .GROUP_CURSOR => .cursor, .GROUP_ICON => .icon, .HTML => .html, .ICON => .icon_num, .MANIFEST => .manifest_num, .MENU => .menu, .MESSAGETABLE => .messagetable, .PLUGPLAY => .plugplay, .RCDATA => .rcdata, .STRING => .string_num, .TOOLBAR => .toolbar, .VERSION => .versioninfo, .VXD => .vxd, _ => .user_defined, }; } pub fn canUseRawData(resource: Resource) bool { return switch (resource) { .user_defined, .html, .plugplay, // Obsolete .rcdata, .vxd, // Obsolete .manifest_num, .dlginit, => true, else => false, }; } pub fn nameForErrorDisplay(resource: Resource) []const u8 { return switch (resource) { // zig fmt: off .accelerators, .bitmap, .cursor, .dialog, .dialogex, .dlginclude, .dlginit, .font, .html, .icon, .menu, .menuex, .messagetable, .plugplay, .rcdata, .stringtable, .toolbar, .versioninfo, .vxd => @tagName(resource), // zig fmt: on .user_defined => "user-defined", .cursor_num => std.fmt.comptimePrint("{d} (cursor)", .{@intFromEnum(res.RT.CURSOR)}), .icon_num => std.fmt.comptimePrint("{d} (icon)", .{@intFromEnum(res.RT.ICON)}), .string_num => std.fmt.comptimePrint("{d} (string)", .{@intFromEnum(res.RT.STRING)}), .anicursor_num => std.fmt.comptimePrint("{d} (anicursor)", .{@intFromEnum(res.RT.ANICURSOR)}), .aniicon_num => std.fmt.comptimePrint("{d} (aniicon)", .{@intFromEnum(res.RT.ANIICON)}), .fontdir_num => std.fmt.comptimePrint("{d} (fontdir)", .{@intFromEnum(res.RT.FONTDIR)}), .manifest_num => std.fmt.comptimePrint("{d} (manifest)", .{@intFromEnum(res.RT.MANIFEST)}), }; } }; /// https://learn.microsoft.com/en-us/windows/win32/menurc/stringtable-resource#parameters /// https://learn.microsoft.com/en-us/windows/win32/menurc/dialog-resource#parameters /// https://learn.microsoft.com/en-us/windows/win32/menurc/dialogex-resource#parameters pub const OptionalStatements = enum { characteristics, language, version, // DIALOG caption, class, exstyle, font, menu, style, pub const map = std.ComptimeStringMapWithEql(OptionalStatements, .{ .{ "CHARACTERISTICS", .characteristics }, .{ "LANGUAGE", .language }, .{ "VERSION", .version }, }, std.comptime_string_map.eqlAsciiIgnoreCase); pub const dialog_map = std.ComptimeStringMapWithEql(OptionalStatements, .{ .{ "CAPTION", .caption }, .{ "CLASS", .class }, .{ "EXSTYLE", .exstyle }, .{ "FONT", .font }, .{ "MENU", .menu }, .{ "STYLE", .style }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; pub const Control = enum { auto3state, autocheckbox, autoradiobutton, checkbox, combobox, control, ctext, defpushbutton, edittext, hedit, iedit, groupbox, icon, listbox, ltext, pushbox, pushbutton, radiobutton, rtext, scrollbar, state3, userbutton, pub const map = std.ComptimeStringMapWithEql(Control, .{ .{ "AUTO3STATE", .auto3state }, .{ "AUTOCHECKBOX", .autocheckbox }, .{ "AUTORADIOBUTTON", .autoradiobutton }, .{ "CHECKBOX", .checkbox }, .{ "COMBOBOX", .combobox }, .{ "CONTROL", .control }, .{ "CTEXT", .ctext }, .{ "DEFPUSHBUTTON", .defpushbutton }, .{ "EDITTEXT", .edittext }, .{ "HEDIT", .hedit }, .{ "IEDIT", .iedit }, .{ "GROUPBOX", .groupbox }, .{ "ICON", .icon }, .{ "LISTBOX", .listbox }, .{ "LTEXT", .ltext }, .{ "PUSHBOX", .pushbox }, .{ "PUSHBUTTON", .pushbutton }, .{ "RADIOBUTTON", .radiobutton }, .{ "RTEXT", .rtext }, .{ "SCROLLBAR", .scrollbar }, .{ "STATE3", .state3 }, .{ "USERBUTTON", .userbutton }, }, std.comptime_string_map.eqlAsciiIgnoreCase); pub fn hasTextParam(control: Control) bool { switch (control) { .scrollbar, .listbox, .iedit, .hedit, .edittext, .combobox => return false, else => return true, } } }; pub const ControlClass = struct { pub const map = std.ComptimeStringMapWithEql(res.ControlClass, .{ .{ "BUTTON", .button }, .{ "EDIT", .edit }, .{ "STATIC", .static }, .{ "LISTBOX", .listbox }, .{ "SCROLLBAR", .scrollbar }, .{ "COMBOBOX", .combobox }, }, std.comptime_string_map.eqlAsciiIgnoreCase); /// Like `map.get` but works on WTF16 strings, for use with parsed /// string literals ("BUTTON", or even "\x42UTTON") pub fn fromWideString(str: []const u16) ?res.ControlClass { const utf16Literal = std.unicode.utf8ToUtf16LeStringLiteral; return if (ascii.eqlIgnoreCaseW(str, utf16Literal("BUTTON"))) .button else if (ascii.eqlIgnoreCaseW(str, utf16Literal("EDIT"))) .edit else if (ascii.eqlIgnoreCaseW(str, utf16Literal("STATIC"))) .static else if (ascii.eqlIgnoreCaseW(str, utf16Literal("LISTBOX"))) .listbox else if (ascii.eqlIgnoreCaseW(str, utf16Literal("SCROLLBAR"))) .scrollbar else if (ascii.eqlIgnoreCaseW(str, utf16Literal("COMBOBOX"))) .combobox else null; } }; const ascii = struct { /// Compares ASCII values case-insensitively, non-ASCII values are compared directly pub fn eqlIgnoreCaseW(a: []const u16, b: []const u16) bool { if (a.len != b.len) return false; for (a, b) |a_c, b_c| { if (a_c < 128) { if (std.ascii.toLower(@intCast(a_c)) != std.ascii.toLower(@intCast(b_c))) return false; } else { if (a_c != b_c) return false; } } return true; } }; pub const MenuItem = enum { menuitem, popup, pub const map = std.ComptimeStringMapWithEql(MenuItem, .{ .{ "MENUITEM", .menuitem }, .{ "POPUP", .popup }, }, std.comptime_string_map.eqlAsciiIgnoreCase); pub fn isSeparator(bytes: []const u8) bool { return std.ascii.eqlIgnoreCase(bytes, "SEPARATOR"); } pub const Option = enum { checked, grayed, help, inactive, menubarbreak, menubreak, pub const map = std.ComptimeStringMapWithEql(Option, .{ .{ "CHECKED", .checked }, .{ "GRAYED", .grayed }, .{ "HELP", .help }, .{ "INACTIVE", .inactive }, .{ "MENUBARBREAK", .menubarbreak }, .{ "MENUBREAK", .menubreak }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; }; pub const ToolbarButton = enum { button, separator, pub const map = std.ComptimeStringMapWithEql(ToolbarButton, .{ .{ "BUTTON", .button }, .{ "SEPARATOR", .separator }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; pub const VersionInfo = enum { file_version, product_version, file_flags_mask, file_flags, file_os, file_type, file_subtype, pub const map = std.ComptimeStringMapWithEql(VersionInfo, .{ .{ "FILEVERSION", .file_version }, .{ "PRODUCTVERSION", .product_version }, .{ "FILEFLAGSMASK", .file_flags_mask }, .{ "FILEFLAGS", .file_flags }, .{ "FILEOS", .file_os }, .{ "FILETYPE", .file_type }, .{ "FILESUBTYPE", .file_subtype }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; pub const VersionBlock = enum { block, value, pub const map = std.ComptimeStringMapWithEql(VersionBlock, .{ .{ "BLOCK", .block }, .{ "VALUE", .value }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; /// Keywords that are be the first token in a statement and (if so) dictate how the rest /// of the statement is parsed. pub const TopLevelKeywords = enum { language, version, characteristics, stringtable, pub const map = std.ComptimeStringMapWithEql(TopLevelKeywords, .{ .{ "LANGUAGE", .language }, .{ "VERSION", .version }, .{ "CHARACTERISTICS", .characteristics }, .{ "STRINGTABLE", .stringtable }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; pub const CommonResourceAttributes = enum { preload, loadoncall, fixed, moveable, discardable, pure, impure, shared, nonshared, pub const map = std.ComptimeStringMapWithEql(CommonResourceAttributes, .{ .{ "PRELOAD", .preload }, .{ "LOADONCALL", .loadoncall }, .{ "FIXED", .fixed }, .{ "MOVEABLE", .moveable }, .{ "DISCARDABLE", .discardable }, .{ "PURE", .pure }, .{ "IMPURE", .impure }, .{ "SHARED", .shared }, .{ "NONSHARED", .nonshared }, }, std.comptime_string_map.eqlAsciiIgnoreCase); }; pub const AcceleratorTypeAndOptions = enum { virtkey, ascii, noinvert, alt, shift, control, pub const map = std.ComptimeStringMapWithEql(AcceleratorTypeAndOptions, .{ .{ "VIRTKEY", .virtkey }, .{ "ASCII", .ascii }, .{ "NOINVERT", .noinvert }, .{ "ALT", .alt }, .{ "SHIFT", .shift }, .{ "CONTROL", .control }, }, std.comptime_string_map.eqlAsciiIgnoreCase); };
https://raw.githubusercontent.com/2lambda123/ziglang-zig/d7563a7753393d7f0d1af445276a64b8a55cb857/src/resinator/rc.zig
const std = @import("std"); const Token = @import("lexer.zig").Token; // TODO: // * Cleanup pratt parser. // * Cleaner interface to heap allocate expressions. const LoxValue = union(Tag) { const Tag = enum { number, string, bool, nil }; number: f32, string: []const u8, bool: bool, nil, pub fn format( self: LoxValue, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = options; _ = fmt; switch (self) { .bool => |b| try writer.print("{}", .{b}), .nil => try writer.print("nil", .{}), .number => |n| try writer.print("{d}", .{n}), .string => |s| try writer.print("\"{s}\"", .{s}), } } }; const Expr = union(Tag) { const Self = @This(); binary: Binary, grouping: Grouping, literal: LoxValue, unary: Unary, const Tag = enum { binary, grouping, literal, unary }; const Binary = struct { left: *Self, operator: Token, right: *Self, }; const Grouping = struct { expression: *Self, }; const Unary = struct { operator: Token, right: *Self, }; pub fn format( self: Self, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = options; _ = fmt; switch (self) { .binary => |b| { try writer.print("({s} {} {})", .{ b.operator.lexeme, b.left, b.right }); }, .grouping => |g| { try writer.print("(group {})", .{g.expression}); }, .literal => |l| { try writer.print("{}", .{l}); }, .unary => |u| { try writer.print("({s} {})", .{ u.operator.lexeme, u.right }); }, } } }; pub const Parser = struct { const Self = @This(); tokens: []Token, pos: usize, allocator: std.mem.Allocator, const Error = error{ UnexpectedToken, OutOfMemory, }; pub fn isOperator(t: Token.Tag) bool { return switch (t) { .bang_equal, .equal_equal, .greater, .greater_equal, .less, .less_equal, .plus, .minus, .star, .slash, => true, else => false, }; } pub fn infixLeftBP(t: Token.Tag) u8 { return switch (t) { .bang_equal, .equal_equal => 1, .greater, .greater_equal, .less, .less_equal => 3, .plus, .minus => 5, .star, .slash => 7, else => unreachable, }; } pub fn prefixRightBP(t: Token.Tag) u8 { return switch (t) { .bang => 3, .minus => 9, else => unreachable, }; } pub fn parseExpression(p: *Self) Error!*Expr { return try p.parsePratt(0); } fn parsePrimary(p: *Self) Error!*Expr { const t = p.tokens[p.pos]; switch (t.tag) { .left_paren => { p.pos += 1; var e = try p.parseExpression(); if (p.tokens[p.pos].tag != .right_paren) return error.UnexpectedToken; p.pos += 1; var res = try p.allocator.create(Expr); res.* = .{ .grouping = .{ .expression = e } }; return res; }, else => { const v = try p.parseLoxValue(); var res = try p.allocator.create(Expr); res.* = .{ .literal = v }; return res; }, } } fn parseUnary(p: *Self) Error!*Expr { const t = p.tokens[p.pos]; switch (t.tag) { .bang, .minus => { p.pos += 1; const r_bp: u8 = prefixRightBP(t.tag); var u = try p.parsePratt(r_bp); var res = try p.allocator.create(Expr); res.* = .{ .unary = .{ .operator = t, .right = u } }; return res; }, else => return try p.parsePrimary(), } } fn parsePratt(p: *Self, min_bp: u8) Error!*Expr { var lhs = try p.parseUnary(); while (p.pos < p.tokens.len) { const op = p.tokens[p.pos]; if (!isOperator(op.tag)) break; const l_bp: u8 = infixLeftBP(op.tag); const r_bp = l_bp + 1; if (l_bp < min_bp) break; p.pos += 1; var rhs = try p.parsePratt(r_bp); var res = try p.allocator.create(Expr); res.* = .{ .binary = .{ .left = lhs, .operator = op, .right = rhs } }; lhs = res; } return lhs; } fn parseLoxValue(p: *Self) Error!LoxValue { const t = p.tokens[p.pos]; switch (t.tag) { .number => { p.pos += 1; const n = std.fmt.parseFloat(f32, t.lexeme) catch unreachable; return LoxValue{ .number = n }; }, .string => { p.pos += 1; return LoxValue{ .string = t.lexeme[1 .. t.lexeme.len - 1] }; }, .true_, .false_ => { p.pos += 1; return LoxValue{ .bool = t.tag == .true_ }; }, .nil => { p.pos += 1; return LoxValue.nil; }, else => return error.UnexpectedToken, } } }; pub const Runtime = struct { const Self = @This(); allocator: std.mem.Allocator, const Error = error{ OutOfMemory, RuntimeError, }; pub fn eval(self: *Self, e: Expr) Error!LoxValue { switch (e) { .binary => |b| { const left = try self.eval(b.left.*); const right = try self.eval(b.right.*); switch (b.operator.tag) { .greater => { return .{ .bool = left.number > right.number }; }, .greater_equal => { return .{ .bool = left.number >= right.number }; }, .less => { return .{ .bool = left.number < right.number }; }, .less_equal => { return .{ .bool = left.number <= right.number }; }, .equal_equal => { return .{ .bool = isEqual(left, right) }; }, .bang_equal => { return .{ .bool = !isEqual(left, right) }; }, .plus => { // I don't think there is an alternative ... switch (left) { .number => |l_num| { switch (right) { .number => |r_num| { return .{ .number = l_num + r_num }; }, else => return error.RuntimeError, } }, .string => |l_str| { switch (right) { .string => |r_str| { var new_str = try self.allocator.alloc(u8, l_str.len + r_str.len); @memcpy(new_str[0..l_str.len], l_str); @memcpy(new_str[l_str.len..], r_str); return LoxValue{ .string = new_str }; }, else => return error.RuntimeError, } }, else => return error.RuntimeError, } }, .minus => return .{ .number = left.number - right.number }, .slash => return .{ .number = left.number / right.number }, .star => return .{ .number = left.number * right.number }, else => unreachable, } }, .grouping => |g| return try self.eval(g.expression.*), .literal => |l| return l, .unary => |u| { const right = try self.eval(u.right.*); switch (u.operator.tag) { .minus => switch (right) { .number => |r_num| return .{ .number = -r_num }, else => return error.RuntimeError, }, .bang => return .{ .bool = !isTruthy(right) }, else => unreachable, } }, } } }; fn isTruthy(l: LoxValue) bool { return switch (l) { .nil => false, .bool => |b| b, else => true, }; } fn isEqual(a: LoxValue, b: LoxValue) bool { return switch (a) { .nil => switch (b) { .nil => true, else => false, }, .string => |sa| switch (b) { .string => |sb| std.mem.eql(u8, sa, sb), else => false, }, else => std.meta.eql(a, b), }; } test "asdf" { var lexer = @import("lexer.zig").Lexer.init("2 / (2 * (3 * 2))"); var toks = std.ArrayList(Token).init(std.testing.allocator); defer toks.deinit(); lexer.scanAll(&toks) catch unreachable; var aa = std.heap.ArenaAllocator.init(std.testing.allocator); defer aa.deinit(); var p = Parser{ .tokens = toks.items, .pos = 0, .allocator = aa.allocator() }; const a = try p.parseExpression(); var env = Runtime{}; std.debug.print("\n", .{}); std.debug.print("{}\n", .{a}); std.debug.print("val = {d}\n", .{env.eval(a).number}); }
https://raw.githubusercontent.com/JamisonCleveland/zig-lox/21c0c8164c23acad2967697d575a9f7d6fb3b85d/src/ast.zig
const std = @import("std"); const toolbox = @import("toolbox.zig"); pub fn println_string(string: toolbox.String8) void { platform_print_to_console("{s}", .{string.bytes}, false); } pub fn println(comptime fmt: []const u8, args: anytype) void { platform_print_to_console(fmt, args, false); } pub fn printerr(comptime fmt: []const u8, args: anytype) void { platform_print_to_console(fmt, args, true); } pub fn panic(comptime fmt: []const u8, args: anytype) noreturn { var buffer = [_]u8{0} ** 2048; const to_print = std.fmt.bufPrint(&buffer, "PANIC: " ++ fmt ++ "\n", args) catch "Unknown error!"; @panic(to_print); } fn platform_print_to_console(comptime fmt: []const u8, args: anytype, comptime is_err: bool) void { switch (comptime toolbox.THIS_PLATFORM) { .MacOS => { var buffer = [_]u8{0} ** 2048; //TODO dynamically allocate buffer for printing. use std.fmt.count to count the size const to_print = if (is_err) std.fmt.bufPrint(&buffer, "ERROR: " ++ fmt ++ "\n", args) catch return else std.fmt.bufPrint(&buffer, fmt ++ "\n", args) catch return; _ = std.os.write(if (is_err) 2 else 1, to_print) catch {}; }, .Playdate => { var buffer = [_]u8{0} ** 128; const to_print = if (is_err) std.fmt.bufPrintZ(&buffer, "ERROR: " ++ fmt, args) catch { toolbox.playdate_log_to_console("String too long to print"); return; } else std.fmt.bufPrintZ(&buffer, fmt, args) catch { toolbox.playdate_log_to_console("String too long to print"); return; }; toolbox.playdate_log_to_console("%s", to_print.ptr); }, else => @compileError("Unsupported platform"), } //TODO support BoksOS //TODO think about stderr //TODO won't work on windows }
https://raw.githubusercontent.com/DanB91/UPWARD-for-Playdate/5d87bf7ef4ad30983ba24ad536228e4ca4ce8b63/modules/toolbox/src/print.zig
// Ported from musl, which is licensed under the MIT license: // https://git.musl-libc.org/cgit/musl/tree/COPYRIGHT // // https://git.musl-libc.org/cgit/musl/tree/src/math/sinhf.c // https://git.musl-libc.org/cgit/musl/tree/src/math/sinh.c const std = @import("../std.zig"); const math = std.math; const expect = std.testing.expect; const expo2 = @import("expo2.zig").expo2; const maxInt = std.math.maxInt; /// Returns the hyperbolic sine of x. /// /// Special Cases: /// - sinh(+-0) = +-0 /// - sinh(+-inf) = +-inf /// - sinh(nan) = nan pub fn sinh(x: anytype) @TypeOf(x) { const T = @TypeOf(x); return switch (T) { f32 => sinh32(x), f64 => sinh64(x), else => @compileError("sinh not implemented for " ++ @typeName(T)), }; } // sinh(x) = (exp(x) - 1 / exp(x)) / 2 // = (exp(x) - 1 + (exp(x) - 1) / exp(x)) / 2 // = x + x^3 / 6 + o(x^5) fn sinh32(x: f32) f32 { const u = @as(u32, @bitCast(x)); const ux = u & 0x7FFFFFFF; const ax = @as(f32, @bitCast(ux)); if (x == 0.0 or math.isNan(x)) { return x; } var h: f32 = 0.5; if (u >> 31 != 0) { h = -h; } // |x| < log(FLT_MAX) if (ux < 0x42B17217) { const t = math.expm1(ax); if (ux < 0x3F800000) { if (ux < 0x3F800000 - (12 << 23)) { return x; } else { return h * (2 * t - t * t / (t + 1)); } } return h * (t + t / (t + 1)); } // |x| > log(FLT_MAX) or nan return 2 * h * expo2(ax); } fn sinh64(x: f64) f64 { const u = @as(u64, @bitCast(x)); const w = @as(u32, @intCast(u >> 32)) & (maxInt(u32) >> 1); const ax = @as(f64, @bitCast(u & (maxInt(u64) >> 1))); if (x == 0.0 or math.isNan(x)) { return x; } var h: f32 = 0.5; if (u >> 63 != 0) { h = -h; } // |x| < log(FLT_MAX) if (w < 0x40862E42) { const t = math.expm1(ax); if (w < 0x3FF00000) { if (w < 0x3FF00000 - (26 << 20)) { return x; } else { return h * (2 * t - t * t / (t + 1)); } } // NOTE: |x| > log(0x1p26) + eps could be h * exp(x) return h * (t + t / (t + 1)); } // |x| > log(DBL_MAX) or nan return 2 * h * expo2(ax); } test "math.sinh" { try expect(sinh(@as(f32, 1.5)) == sinh32(1.5)); try expect(sinh(@as(f64, 1.5)) == sinh64(1.5)); } test "math.sinh32" { const epsilon = 0.000001; try expect(math.approxEqAbs(f32, sinh32(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f32, sinh32(0.2), 0.201336, epsilon)); try expect(math.approxEqAbs(f32, sinh32(0.8923), 1.015512, epsilon)); try expect(math.approxEqAbs(f32, sinh32(1.5), 2.129279, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-0.0), -0.0, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-0.2), -0.201336, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-0.8923), -1.015512, epsilon)); try expect(math.approxEqAbs(f32, sinh32(-1.5), -2.129279, epsilon)); } test "math.sinh64" { const epsilon = 0.000001; try expect(math.approxEqAbs(f64, sinh64(0.0), 0.0, epsilon)); try expect(math.approxEqAbs(f64, sinh64(0.2), 0.201336, epsilon)); try expect(math.approxEqAbs(f64, sinh64(0.8923), 1.015512, epsilon)); try expect(math.approxEqAbs(f64, sinh64(1.5), 2.129279, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-0.0), -0.0, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-0.2), -0.201336, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-0.8923), -1.015512, epsilon)); try expect(math.approxEqAbs(f64, sinh64(-1.5), -2.129279, epsilon)); } test "math.sinh32.special" { try expect(sinh32(0.0) == 0.0); try expect(sinh32(-0.0) == -0.0); try expect(math.isPositiveInf(sinh32(math.inf(f32)))); try expect(math.isNegativeInf(sinh32(-math.inf(f32)))); try expect(math.isNan(sinh32(math.nan(f32)))); } test "math.sinh64.special" { try expect(sinh64(0.0) == 0.0); try expect(sinh64(-0.0) == -0.0); try expect(math.isPositiveInf(sinh64(math.inf(f64)))); try expect(math.isNegativeInf(sinh64(-math.inf(f64)))); try expect(math.isNan(sinh64(math.nan(f64)))); }
https://raw.githubusercontent.com/ziglang/gotta-go-fast/c915c45c5afed9a2e2de4f4484acba2df5090c3a/src/self-hosted-parser/input_dir/math/sinh.zig
const std = @import("std"); extern const custom_global_symbol: u8; export fn getCustomGlobalSymbol() u8 { return custom_global_symbol; }
https://raw.githubusercontent.com/aherrmann/rules_zig/2c2ec8c2a3bc91e883dc307ead97e4703201e834/e2e/workspace/linker-script/lib.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const time = std.time; const engine = @import("engine"); const Player = engine.Player(SevenBag); const GameState = Player.GameState; const kicks = engine.kicks; const PeriodicTrigger = engine.PeriodicTrigger; const SevenBag = engine.bags.SevenBag; const nterm = @import("nterm"); const View = nterm.View; const root = @import("root.zig"); const neat = root.neat; const pc = root.pc; const Placement = root.Placement; const FRAMERATE = 6; const FPS_TIMING_WINDOW = 12; // pub fn main() !void { // var gpa = std.heap.GeneralPurposeAllocator(.{}){}; // const allocator = gpa.allocator(); // defer _ = gpa.deinit(); // // Add 2 to create a 1-wide empty boarder on the left and right. // try nterm.init(allocator, FPS_TIMING_WINDOW, Player.DISPLAY_W + 2, Player.DISPLAY_H + 3); // defer nterm.deinit(); // const settings = engine.GameSettings{ // .g = 0, // .target_mode = .none, // }; // const player_view = View{ // .left = 1, // .top = 0, // .width = Player.DISPLAY_W, // .height = Player.DISPLAY_H, // }; // var player = Player.init("You", SevenBag.init(0), player_view, settings); // const bot_stats_view = View{ // .left = 1, // .top = Player.DISPLAY_H, // .width = Player.DISPLAY_W + 1, // .height = 3, // }; // const nn = try neat.NN.load(allocator, "NNs/Qoshae.json"); // defer nn.deinit(allocator); // var bot = neat.Bot.init(nn, 0.5, player.settings.attack_table); // var t = time.nanoTimestamp(); // while (true) { // const placement = bot.findMoves(player.state); // if (placement.piece.kind != player.state.current.kind) { // player.hold(); // } // player.state.pos = placement.pos; // player.state.current = placement.piece; // player.hardDrop(0, &.{}); // bot_stats_view.printAt(0, 0, .white, .black, "Nodes: {d}", .{bot.node_count}); // bot_stats_view.printAt(0, 1, .white, .black, "Depth: {d}", .{bot.current_depth}); // bot_stats_view.printAt(0, 2, .white, .black, "Tresh: {d}", .{bot.move_tresh}); // const dt: u64 = @intCast(time.nanoTimestamp() - t); // player.tick(dt, 0, &.{}); // t += dt; // try player.draw(); // nterm.render() catch |err| { // if (err == error.NotInitialized) { // return; // } // return err; // }; // } // } pub fn main() !void { // All allocators appear to perform the same for `pc.findPc()` var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer _ = gpa.deinit(); // Add 2 to create a 1-wide empty boarder on the left and right. try nterm.init(allocator, std.io.getStdOut(), FPS_TIMING_WINDOW, Player.DISPLAY_W + 2, Player.DISPLAY_H); defer nterm.deinit(); const settings = engine.GameSettings{ .g = 0, .target_mode = .none, }; const player_view = View{ .left = 1, .top = 0, .width = Player.DISPLAY_W, .height = Player.DISPLAY_H, }; var player = Player.init( "You", SevenBag.init(0), kicks.srsPlus, settings, player_view, playSfxDummy, ); var placement_i: usize = 0; var pc_queue = std.ArrayList([]Placement).init(allocator); defer pc_queue.deinit(); const pc_thread = try std.Thread.spawn(.{ .allocator = allocator, }, pcThread, .{ allocator, player.state, &pc_queue }); defer pc_thread.join(); const fps_view = View{ .left = 1, .top = 0, .width = 15, .height = 1, }; var render_timer = PeriodicTrigger.init(time.ns_per_s / FRAMERATE); while (true) { if (render_timer.trigger()) |dt| { fps_view.printAt(0, 0, .white, .black, "{d:.2}FPS", .{nterm.fps()}); placePcPiece(allocator, &player, &pc_queue, &placement_i); player.tick(dt, 0, &.{}); try player.draw(); nterm.render() catch |err| { if (err == error.NotInitialized) { return; } return err; }; } else { time.sleep(1 * time.ns_per_ms); } } } fn placePcPiece(allocator: Allocator, game: *Player, queue: *std.ArrayList([]Placement), placement_i: *usize) void { if (queue.items.len == 0) { return; } const placements = queue.items[0]; const placement = placements[placement_i.*]; if (placement.piece.kind != game.state.current.kind) { game.hold(); } game.state.pos = placement.pos; game.state.current = placement.piece; game.hardDrop(0, &.{}); placement_i.* += 1; if (placement_i.* == placements.len) { allocator.free(queue.orderedRemove(0)); placement_i.* = 0; } } fn pcThread(allocator: Allocator, state: GameState, queue: *std.ArrayList([]Placement)) !void { var game = state; while (true) { const placements = try pc.findPc(allocator, game, 0, 16); for (placements) |placement| { if (game.current.kind != placement.piece.kind) { game.hold(); } game.current = placement.piece; game.pos = placement.pos; _ = game.lockCurrent(-1); game.nextPiece(); } try queue.append(placements); } } fn playSfxDummy(_: engine.player.Sfx) void {}
https://raw.githubusercontent.com/TemariVirus/Budget-Tetris-Bot/b080082fe26338d3a8c28f760368943b9a13ed17/src/main.zig
const std = @import("std"); pub fn main() !void { const name = "Пётр"; var buf: [100]u8 = undefined; const greeting = try std.fmt.bufPrint(&buf, "Привет, {s}!", .{name}); std.debug.print("{s}\n", .{greeting}); }
https://raw.githubusercontent.com/dee0xeed/learning-zig-rus/13b78318628fa85bc1cc8359e74e223ee506e6a9/src/examples/ex-ch06-06.zig
const std = @import("std"); const pipes = @import("./pipes.zig"); const fmt = std.fmt; const heap = std.heap; const io = std.io; const mem = std.mem; pub fn main() !void { var gpa = heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const stdin = io.getStdIn().reader(); const stdout = io.getStdOut().writer(); var buffer: [1024 * 1024]u8 = undefined; const len = try stdin.readAll(&buffer); const input = buffer[0..len]; var tiles = try pipes.parseTiles(allocator, input); defer pipes.freeTiles(allocator, tiles); const solution = try pipes.solve(allocator, &tiles); try stdout.print("Part 1 solution: {d}\n", .{solution[0]}); try stdout.print("Part 2 solution: {d}\n", .{solution[1]}); }
https://raw.githubusercontent.com/arntj/advent-of-code/d6a234e5bf9dd22ed10e7e215b3c262edfee61ff/2023/10/day10.zig
const std = @import("std"); const print = std.debug.print; const DemoError = error{Demo}; fn demo(good: bool) DemoError!u8 { return if (good) 19 else DemoError.Demo; } // Only need ! in return type if errors are not caught. pub fn main() !void { // Not catching possible errors. var result = try demo(true); print("result = {}\n", .{result}); // Catching possible errors. // result = demo(false) catch |err| { result = demo(false) catch |err| { print("err = {}\n", .{err}); return; }; print("result = {}\n", .{result}); }
https://raw.githubusercontent.com/mvolkmann/zig-examples/7d9877a2f2535c8bb61ceb0f2059c377f49bd079/try_catch_demo.zig
// @link "deps/zlib/libz.a" const std = @import("std"); const bun = @import("root").bun; const mimalloc = @import("./allocators/mimalloc.zig"); pub const MAX_WBITS = 15; test "Zlib Read" { const expected_text = @embedFile("./zlib.test.txt"); const input = bun.asByteSlice(@embedFile("./zlib.test.gz")); std.debug.print("zStream Size: {d}", .{@sizeOf(zStream_struct)}); var output = std.ArrayList(u8).init(std.heap.c_allocator); var writer = output.writer(); const ZlibReader = NewZlibReader(@TypeOf(&writer), 4096); var reader = try ZlibReader.init(&writer, input, std.heap.c_allocator); defer reader.deinit(); try reader.readAll(); try std.testing.expectEqualStrings(expected_text, output.items); } test "ZlibArrayList Read" { const expected_text = @embedFile("./zlib.test.txt"); const input = bun.asByteSlice(@embedFile("./zlib.test.gz")); std.debug.print("zStream Size: {d}", .{@sizeOf(zStream_struct)}); var list = std.ArrayListUnmanaged(u8){}; try list.ensureUnusedCapacity(std.heap.c_allocator, 4096); var reader = try ZlibReaderArrayList.init(input, &list, std.heap.c_allocator); defer reader.deinit(); try reader.readAll(); try std.testing.expectEqualStrings(expected_text, list.items); } pub extern fn zlibVersion() [*c]const u8; pub extern fn compress(dest: [*]Bytef, destLen: *uLongf, source: [*]const Bytef, sourceLen: uLong) c_int; pub extern fn compress2(dest: [*]Bytef, destLen: *uLongf, source: [*]const Bytef, sourceLen: uLong, level: c_int) c_int; pub extern fn compressBound(sourceLen: uLong) uLong; pub extern fn uncompress(dest: [*]Bytef, destLen: *uLongf, source: [*]const Bytef, sourceLen: uLong) c_int; pub const struct_gzFile_s = extern struct { have: c_uint, next: [*c]u8, pos: c_long, }; pub const gzFile = [*c]struct_gzFile_s; // https://zlib.net/manual.html#Stream const Byte = u8; const uInt = u32; const uLong = u64; const Bytef = Byte; const charf = u8; const intf = c_int; const uIntf = uInt; const uLongf = uLong; const voidpc = ?*const anyopaque; const voidpf = ?*anyopaque; const voidp = ?*anyopaque; const z_crc_t = c_uint; // typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size)); // typedef void (*free_func) OF((voidpf opaque, voidpf address)); pub const z_alloc_fn = ?*const fn (*anyopaque, uInt, uInt) callconv(.C) voidpf; pub const z_free_fn = ?*const fn (*anyopaque, *anyopaque) callconv(.C) void; pub const struct_internal_state = extern struct { dummy: c_int, }; // typedef struct z_stream_s { // z_const Bytef *next_in; /* next input byte */ // uInt avail_in; /* number of bytes available at next_in */ // uLong total_in; /* total number of input bytes read so far */ // Bytef *next_out; /* next output byte will go here */ // uInt avail_out; /* remaining free space at next_out */ // uLong total_out; /* total number of bytes output so far */ // z_const char *msg; /* last error message, NULL if no error */ // struct internal_state FAR *state; /* not visible by applications */ // alloc_func zalloc; /* used to allocate the internal state */ // free_func zfree; /* used to free the internal state */ // voidpf opaque; /* private data object passed to zalloc and zfree */ // int data_type; /* best guess about the data type: binary or text // for deflate, or the decoding state for inflate */ // uLong adler; /* Adler-32 or CRC-32 value of the uncompressed data */ // uLong reserved; /* reserved for future use */ // } z_stream; pub const zStream_struct = extern struct { /// next input byte next_in: [*c]const u8, /// number of bytes available at next_in avail_in: uInt, /// total number of input bytes read so far total_in: uLong, /// next output byte will go here next_out: [*c]u8, /// remaining free space at next_out avail_out: uInt, /// total number of bytes output so far total_out: uLong, /// last error message, NULL if no error err_msg: [*c]const u8, /// not visible by applications internal_state: ?*struct_internal_state, /// used to allocate the internal state alloc_func: z_alloc_fn, /// used to free the internal state free_func: z_free_fn, /// private data object passed to zalloc and zfree user_data: *anyopaque, /// best guess about the data type: binary or text for deflate, or the decoding state for inflate data_type: DataType, ///Adler-32 or CRC-32 value of the uncompressed data adler: uLong, /// reserved for future use reserved: uLong, }; pub const z_stream = zStream_struct; pub const z_streamp = *z_stream; // #define Z_BINARY 0 // #define Z_TEXT 1 // #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */ // #define Z_UNKNOWN 2 pub const DataType = enum(c_int) { Binary = 0, Text = 1, Unknown = 2, }; // #define Z_OK 0 // #define Z_STREAM_END 1 // #define Z_NEED_DICT 2 // #define Z_ERRNO (-1) // #define Z_STREAM_ERROR (-2) // #define Z_DATA_ERROR (-3) // #define Z_MEM_ERROR (-4) // #define Z_BUF_ERROR (-5) // #define Z_VERSION_ERROR (-6) pub const ReturnCode = enum(c_int) { Ok = 0, StreamEnd = 1, NeedDict = 2, ErrNo = -1, StreamError = -2, DataError = -3, MemError = -4, BufError = -5, VersionError = -6, }; // #define Z_NO_FLUSH 0 // #define Z_PARTIAL_FLUSH 1 // #define Z_SYNC_FLUSH 2 // #define Z_FULL_FLUSH 3 // #define Z_FINISH 4 // #define Z_BLOCK 5 // #define Z_TREES 6 pub const FlushValue = enum(c_int) { NoFlush = 0, PartialFlush = 1, /// Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer SyncFlush = 2, FullFlush = 3, Finish = 4, /// Z_BLOCK requests that inflate() stop if and when it gets to the next / deflate block boundary When decoding the zlib or gzip format, this will / cause inflate() to return immediately after the header and before the / first block. When doing a raw inflate, inflate() will go ahead and / process the first block, and will return when it gets to the end of that / block, or when it runs out of data. / The Z_BLOCK option assists in appending to or combining deflate streams. / To assist in this, on return inflate() always sets strm->data_type to the / number of unused bits in the last byte taken from strm->next_in, plus 64 / if inflate() is currently decoding the last block in the deflate stream, / plus 128 if inflate() returned immediately after decoding an end-of-block / code or decoding the complete header up to just before the first byte of / the deflate stream. The end-of-block will not be indicated until all of / the uncompressed data from that block has been written to strm->next_out. / The number of unused bits may in general be greater than seven, except / when bit 7 of data_type is set, in which case the number of unused bits / will be less than eight. data_type is set as noted here every time / inflate() returns for all flush options, and so can be used to determine / the amount of currently consumed input in bits. Block = 5, /// The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. Trees = 6, }; // ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); /// Initializes the internal stream state for decompression. The fields next_in, avail_in, zalloc, zfree and opaque must be initialized before by the caller. In the current version of inflate, the provided input is not read or consumed. The allocation of a sliding window will be deferred to the first call of inflate (if the decompression does not complete on the first call). If zalloc and zfree are set to Z_NULL, inflateInit updates them to use default allocation functions. /// /// inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library version is incompatible with the version assumed by the caller, or Z_STREAM_ERROR if the parameters are invalid, such as a null pointer to the structure. msg is set to null if there is no error message. inflateInit does not perform any decompression. Actual decompression will be done by inflate(). So next_in, and avail_in, next_out, and avail_out are unused and unchanged. The current implementation of inflateInit() does not process any header information—that is deferred until inflate() is called. pub extern fn inflateInit_(strm: z_streamp, version: [*c]const u8, stream_size: c_int) ReturnCode; pub extern fn inflateInit2_(strm: z_streamp, window_size: c_int, version: [*c]const u8, stream_size: c_int) ReturnCode; /// inflate decompresses as much data as possible, and stops when the input buffer becomes empty or the output buffer becomes full. It may introduce some output latency (reading input without producing any output) except when forced to flush. /// The detailed semantics are as follows. inflate performs one or both of the following actions: /// /// - Decompress more input starting at next_in and update next_in and avail_in accordingly. If not all input can be processed (because there is not enough room in the output buffer), then next_in and avail_in are updated accordingly, and processing will resume at this point for the next call of inflate(). /// - Generate more output starting at next_out and update next_out and avail_out accordingly. inflate() provides as much output as possible, until there is no more input data or no more space in the output buffer (see below about the flush parameter). /// /// Before the call of inflate(), the application should ensure that at least one of the actions is possible, by providing more input and/or consuming more output, and updating the next_* and avail_* values accordingly. If the caller of inflate() does not provide both available input and available output space, it is possible that there will be no progress made. The application can consume the uncompressed output when it wants, for example when the output buffer is full (avail_out == 0), or after each call of inflate(). If inflate returns Z_OK and with zero avail_out, it must be called again after making room in the output buffer because there might be more output pending. /// /// The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH, Z_BLOCK, or Z_TREES. Z_SYNC_FLUSH requests that inflate() flush as much output as possible to the output buffer. Z_BLOCK requests that inflate() stop if and when it gets to the next deflate block boundary. When decoding the zlib or gzip format, this will cause inflate() to return immediately after the header and before the first block. When doing a raw inflate, inflate() will go ahead and process the first block, and will return when it gets to the end of that block, or when it runs out of data. /// /// The Z_BLOCK option assists in appending to or combining deflate streams. To assist in this, on return inflate() always sets strm->data_type to the number of unused bits in the last byte taken from strm->next_in, plus 64 if inflate() is currently decoding the last block in the deflate stream, plus 128 if inflate() returned immediately after decoding an end-of-block code or decoding the complete header up to just before the first byte of the deflate stream. The end-of-block will not be indicated until all of the uncompressed data from that block has been written to strm->next_out. The number of unused bits may in general be greater than seven, except when bit 7 of data_type is set, in which case the number of unused bits will be less than eight. data_type is set as noted here every time inflate() returns for all flush options, and so can be used to determine the amount of currently consumed input in bits. /// /// The Z_TREES option behaves as Z_BLOCK does, but it also returns when the end of each deflate block header is reached, before any actual data in that block is decoded. This allows the caller to determine the length of the deflate block header for later use in random access within a deflate block. 256 is added to the value of strm->data_type when inflate() returns immediately after reaching the end of the deflate block header. /// /// inflate() should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be performed in a single step (a single call of inflate), the parameter flush should be set to Z_FINISH. In this case all pending input is processed and all pending output is flushed; avail_out must be large enough to hold all of the uncompressed data for the operation to complete. (The size of the uncompressed data may have been saved by the compressor for this purpose.) The use of Z_FINISH is not required to perform an inflation in one step. However it may be used to inform inflate that a faster approach can be used for the single inflate() call. Z_FINISH also informs inflate to not maintain a sliding window if the stream completes, which reduces inflate's memory footprint. If the stream does not complete, either because not all of the stream is provided or not enough output space is provided, then a sliding window will be allocated and inflate() can be called again to continue the operation as if Z_NO_FLUSH had been used. /// /// In this implementation, inflate() always flushes as much output as possible to the output buffer, and always uses the faster approach on the first call. So the effects of the flush parameter in this implementation are on the return value of inflate() as noted below, when inflate() returns early when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of memory for a sliding window when Z_FINISH is used. /// /// If a preset dictionary is needed after this call (see inflateSetDictionary below), inflate sets strm->adler to the Adler-32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise it sets strm->adler to the Adler-32 checksum of all output produced so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described below. At the end of the stream, inflate() checks that its computed Adler-32 checksum is equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct. /// /// inflate() will decompress and check either zlib-wrapped or gzip-wrapped deflate data. The header type is detected automatically, if requested when initializing with inflateInit2(). Any information contained in the gzip header is not retained unless inflateGetHeader() is used. When processing gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output produced so far. The CRC-32 is checked against the gzip trailer, as is the uncompressed length, modulo 2^32. /// /// inflate() returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming to the zlib format or incorrect check value, in which case strm->msg points to a string with a more specific error), Z_STREAM_ERROR if the stream structure was inconsistent (for example next_in or next_out was Z_NULL, or the state was inadvertently written over by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress was possible or if there was not enough room in the output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and inflate() can be called again with more input and more output space to continue decompressing. If Z_DATA_ERROR is returned, the application may then call inflateSync() to look for a good compression block if a partial recovery of the data is to be attempted. extern fn inflate(stream: [*c]zStream_struct, flush: FlushValue) ReturnCode; /// inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state was inconsistent. const InflateEndResult = enum(c_int) { Ok = 0, StreamEnd = 1, }; /// All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and does not flush any pending output. extern fn inflateEnd(stream: [*c]zStream_struct) InflateEndResult; pub fn NewZlibReader(comptime Writer: type, comptime buffer_size: usize) type { return struct { const ZlibReader = @This(); pub const State = enum { Uninitialized, Inflating, End, Error, }; context: Writer, input: []const u8, buf: [buffer_size]u8, zlib: zStream_struct, allocator: std.mem.Allocator, state: State = State.Uninitialized, pub fn alloc(_: *anyopaque, items: uInt, len: uInt) callconv(.C) *anyopaque { return mimalloc.mi_malloc(items * len) orelse unreachable; } pub fn free(_: *anyopaque, data: *anyopaque) callconv(.C) void { mimalloc.mi_free(data); } pub fn deinit(this: *ZlibReader) void { var allocator = this.allocator; this.end(); allocator.destroy(this); } pub fn end(this: *ZlibReader) void { if (this.state == State.Inflating) { _ = inflateEnd(&this.zlib); this.state = State.End; } } pub fn init(writer: Writer, input: []const u8, allocator: std.mem.Allocator) !*ZlibReader { var zlib_reader = try allocator.create(ZlibReader); zlib_reader.* = ZlibReader{ .context = writer, .input = input, .buf = std.mem.zeroes([buffer_size]u8), .allocator = allocator, .zlib = undefined, }; zlib_reader.zlib = zStream_struct{ .next_in = input.ptr, .avail_in = @as(uInt, @intCast(input.len)), .total_in = @as(uInt, @intCast(input.len)), .next_out = &zlib_reader.buf, .avail_out = buffer_size, .total_out = buffer_size, .err_msg = null, .alloc_func = ZlibReader.alloc, .free_func = ZlibReader.free, .internal_state = null, .user_data = zlib_reader, .data_type = DataType.Unknown, .adler = 0, .reserved = 0, }; switch (inflateInit2_(&zlib_reader.zlib, 15 + 32, zlibVersion(), @sizeOf(zStream_struct))) { ReturnCode.Ok => return zlib_reader, ReturnCode.MemError => { zlib_reader.deinit(); return error.OutOfMemory; }, ReturnCode.StreamError => { zlib_reader.deinit(); return error.InvalidArgument; }, ReturnCode.VersionError => { zlib_reader.deinit(); return error.InvalidArgument; }, else => unreachable, } } pub fn errorMessage(this: *ZlibReader) ?[]const u8 { if (this.zlib.err_msg) |msg_ptr| { return std.mem.sliceTo(msg_ptr, 0); } return null; } pub fn readAll(this: *ZlibReader) !void { while (this.state == State.Uninitialized or this.state == State.Inflating) { // Before the call of inflate(), the application should ensure // that at least one of the actions is possible, by providing // more input and/or consuming more output, and updating the // next_* and avail_* values accordingly. If the caller of // inflate() does not provide both available input and available // output space, it is possible that there will be no progress // made. The application can consume the uncompressed output // when it wants, for example when the output buffer is full // (avail_out == 0), or after each call of inflate(). If inflate // returns Z_OK and with zero avail_out, it must be called again // after making room in the output buffer because there might be // more output pending. // - Decompress more input starting at next_in and update // next_in and avail_in accordingly. If not all input can be // processed (because there is not enough room in the output // buffer), then next_in and avail_in are updated accordingly, // and processing will resume at this point for the next call // of inflate(). // - Generate more output starting at next_out and update // next_out and avail_out accordingly. inflate() provides as // much output as possible, until there is no more input data // or no more space in the output buffer (see below about the // flush parameter). if (this.zlib.avail_out == 0) { var written = try this.context.write(&this.buf); while (written < this.zlib.avail_out) { written += try this.context.write(this.buf[written..]); } this.zlib.avail_out = buffer_size; this.zlib.next_out = &this.buf; } if (this.zlib.avail_in == 0) { return error.ShortRead; } const rc = inflate(&this.zlib, FlushValue.PartialFlush); this.state = State.Inflating; switch (rc) { ReturnCode.StreamEnd => { this.state = State.End; var remainder = this.buf[0 .. buffer_size - this.zlib.avail_out]; remainder = remainder[try this.context.write(remainder)..]; while (remainder.len > 0) { remainder = remainder[try this.context.write(remainder)..]; } this.end(); return; }, ReturnCode.MemError => { this.state = State.Error; return error.OutOfMemory; }, ReturnCode.StreamError, ReturnCode.DataError, ReturnCode.BufError, ReturnCode.NeedDict, ReturnCode.VersionError, ReturnCode.ErrNo, => { this.state = State.Error; return error.ZlibError; }, ReturnCode.Ok => {}, } } } }; } pub const ZlibError = error{ OutOfMemory, InvalidArgument, ZlibError, ShortRead, }; pub const ZlibReaderArrayList = struct { const ZlibReader = ZlibReaderArrayList; pub const State = enum { Uninitialized, Inflating, End, Error, }; input: []const u8, list: std.ArrayListUnmanaged(u8), list_allocator: std.mem.Allocator, list_ptr: *std.ArrayListUnmanaged(u8), zlib: zStream_struct, allocator: std.mem.Allocator, state: State = State.Uninitialized, pub fn alloc(_: *anyopaque, items: uInt, len: uInt) callconv(.C) *anyopaque { return mimalloc.mi_malloc(items * len) orelse unreachable; } pub fn free(_: *anyopaque, data: *anyopaque) callconv(.C) void { mimalloc.mi_free(data); } pub fn deinit(this: *ZlibReader) void { var allocator = this.allocator; this.end(); allocator.destroy(this); } pub fn end(this: *ZlibReader) void { // always free with `inflateEnd` if (this.state != State.End) { _ = inflateEnd(&this.zlib); this.state = State.End; } } pub fn init( input: []const u8, list: *std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator, ) !*ZlibReader { const options: Options = .{ .windowBits = 15 + 32, }; return initWithOptions(input, list, allocator, options); } pub fn initWithOptions(input: []const u8, list: *std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator, options: Options) ZlibError!*ZlibReader { return initWithOptionsAndListAllocator(input, list, allocator, allocator, options); } pub fn initWithOptionsAndListAllocator(input: []const u8, list: *std.ArrayListUnmanaged(u8), list_allocator: std.mem.Allocator, allocator: std.mem.Allocator, options: Options) ZlibError!*ZlibReader { var zlib_reader = try allocator.create(ZlibReader); zlib_reader.* = ZlibReader{ .input = input, .list = list.*, .list_allocator = list_allocator, .list_ptr = list, .allocator = allocator, .zlib = undefined, }; zlib_reader.zlib = zStream_struct{ .next_in = input.ptr, .avail_in = @as(uInt, @intCast(input.len)), .total_in = @as(uInt, @intCast(input.len)), .next_out = zlib_reader.list.items.ptr, .avail_out = @as(u32, @intCast(zlib_reader.list.items.len)), .total_out = zlib_reader.list.items.len, .err_msg = null, .alloc_func = ZlibReader.alloc, .free_func = ZlibReader.free, .internal_state = null, .user_data = zlib_reader, .data_type = DataType.Unknown, .adler = 0, .reserved = 0, }; switch (inflateInit2_(&zlib_reader.zlib, options.windowBits, zlibVersion(), @sizeOf(zStream_struct))) { ReturnCode.Ok => return zlib_reader, ReturnCode.MemError => { zlib_reader.deinit(); return error.OutOfMemory; }, ReturnCode.StreamError => { zlib_reader.deinit(); return error.InvalidArgument; }, ReturnCode.VersionError => { zlib_reader.deinit(); return error.InvalidArgument; }, else => unreachable, } } pub fn errorMessage(this: *ZlibReader) ?[]const u8 { if (this.zlib.err_msg) |msg_ptr| { return std.mem.sliceTo(msg_ptr, 0); } return null; } pub fn readAll(this: *ZlibReader) ZlibError!void { defer { if (this.list.items.len > this.zlib.total_out) { this.list.shrinkRetainingCapacity(this.zlib.total_out); } else if (this.zlib.total_out < this.list.capacity) { this.list.items.len = this.zlib.total_out; } this.list_ptr.* = this.list; } while (this.state == State.Uninitialized or this.state == State.Inflating) { // Before the call of inflate(), the application should ensure // that at least one of the actions is possible, by providing // more input and/or consuming more output, and updating the // next_* and avail_* values accordingly. If the caller of // inflate() does not provide both available input and available // output space, it is possible that there will be no progress // made. The application can consume the uncompressed output // when it wants, for example when the output buffer is full // (avail_out == 0), or after each call of inflate(). If inflate // returns Z_OK and with zero avail_out, it must be called again // after making room in the output buffer because there might be // more output pending. // - Decompress more input starting at next_in and update // next_in and avail_in accordingly. If not all input can be // processed (because there is not enough room in the output // buffer), then next_in and avail_in are updated accordingly, // and processing will resume at this point for the next call // of inflate(). // - Generate more output starting at next_out and update // next_out and avail_out accordingly. inflate() provides as // much output as possible, until there is no more input data // or no more space in the output buffer (see below about the // flush parameter). if (this.zlib.avail_out == 0) { const initial = this.list.items.len; try this.list.ensureUnusedCapacity(this.list_allocator, 4096); this.list.expandToCapacity(); this.zlib.next_out = &this.list.items[initial]; this.zlib.avail_out = @as(u32, @intCast(this.list.items.len - initial)); } if (this.zlib.avail_in == 0) { return error.ShortRead; } const rc = inflate(&this.zlib, FlushValue.PartialFlush); this.state = State.Inflating; switch (rc) { ReturnCode.StreamEnd => { this.end(); return; }, ReturnCode.MemError => { this.state = State.Error; return error.OutOfMemory; }, ReturnCode.StreamError, ReturnCode.DataError, ReturnCode.BufError, ReturnCode.NeedDict, ReturnCode.VersionError, ReturnCode.ErrNo, => { this.state = State.Error; return error.ZlibError; }, ReturnCode.Ok => {}, } } } }; pub const Options = struct { gzip: bool = false, level: c_int = 6, method: c_int = 8, windowBits: c_int = 15, memLevel: c_int = 8, strategy: c_int = 0, }; /// /// Initializes the internal stream state for compression. The fields /// zalloc, zfree and opaque must be initialized before by the caller. If /// zalloc and zfree are set to Z_NULL, deflateInit updates them to use default /// allocation functions. /// /// The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9: /// 1 gives best speed, 9 gives best compression, 0 gives no compression at all /// (the input data is simply copied a block at a time). Z_DEFAULT_COMPRESSION /// requests a default compromise between speed and compression (currently /// equivalent to level 6). /// /// deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough /// memory, Z_STREAM_ERROR if level is not a valid compression level, or /// Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible /// with the version assumed by the caller (ZLIB_VERSION). msg is set to null /// if there is no error message. deflateInit does not perform any compression: /// this will be done by deflate(). extern fn deflateInit_(strm: z_stream, level: c_int, stream_size: c_int) c_int; /// /// deflate compresses as much data as possible, and stops when the input /// buffer becomes empty or the output buffer becomes full. It may introduce /// some output latency (reading input without producing any output) except when /// forced to flush. /// /// The detailed semantics are as follows. deflate performs one or both of the /// following actions: /// /// - Compress more input starting at next_in and update next_in and avail_in /// accordingly. If not all input can be processed (because there is not /// enough room in the output buffer), next_in and avail_in are updated and /// processing will resume at this point for the next call of deflate(). /// /// - Provide more output starting at next_out and update next_out and avail_out /// accordingly. This action is forced if the parameter flush is non zero. /// Forcing flush frequently degrades the compression ratio, so this parameter /// should be set only when necessary (in interactive applications). Some /// output may be provided even if flush is not set. /// /// Before the call of deflate(), the application should ensure that at least /// one of the actions is possible, by providing more input and/or consuming more /// output, and updating avail_in or avail_out accordingly; avail_out should /// never be zero before the call. The application can consume the compressed /// output when it wants, for example when the output buffer is full (avail_out /// == 0), or after each call of deflate(). If deflate returns Z_OK and with /// zero avail_out, it must be called again after making room in the output /// buffer because there might be more output pending. /// /// Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to /// decide how much data to accumulate before producing output, in order to /// maximize compression. /// /// If the parameter flush is set to Z_SYNC_FLUSH, all pending output is /// flushed to the output buffer and the output is aligned on a byte boundary, so /// that the decompressor can get all input data available so far. (In /// particular avail_in is zero after the call if enough output space has been /// provided before the call.) Flushing may degrade compression for some /// compression algorithms and so it should be used only when necessary. This /// completes the current deflate block and follows it with an empty stored block /// that is three bits plus filler bits to the next byte, followed by four bytes /// (00 00 ff ff). /// /// If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the /// output buffer, but the output is not aligned to a byte boundary. All of the /// input data so far will be available to the decompressor, as for Z_SYNC_FLUSH. /// This completes the current deflate block and follows it with an empty fixed /// codes block that is 10 bits long. This assures that enough bytes are output /// in order for the decompressor to finish the block before the empty fixed code /// block. /// /// If flush is set to Z_BLOCK, a deflate block is completed and emitted, as /// for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to /// seven bits of the current block are held to be written as the next byte after /// the next deflate block is completed. In this case, the decompressor may not /// be provided enough bits at this point in order to complete decompression of /// the data provided so far to the compressor. It may need to wait for the next /// block to be emitted. This is for advanced applications that need to control /// the emission of deflate blocks. /// /// If flush is set to Z_FULL_FLUSH, all output is flushed as with /// Z_SYNC_FLUSH, and the compression state is reset so that decompression can /// restart from this point if previous compressed data has been damaged or if /// random access is desired. Using Z_FULL_FLUSH too often can seriously degrade /// compression. /// /// If deflate returns with avail_out == 0, this function must be called again /// with the same value of the flush parameter and more output space (updated /// avail_out), until the flush is complete (deflate returns with non-zero /// avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that /// avail_out is greater than six to avoid repeated flush markers due to /// avail_out == 0 on return. /// /// If the parameter flush is set to Z_FINISH, pending input is processed, /// pending output is flushed and deflate returns with Z_STREAM_END if there was /// enough output space; if deflate returns with Z_OK, this function must be /// called again with Z_FINISH and more output space (updated avail_out) but no /// more input data, until it returns with Z_STREAM_END or an error. After /// deflate has returned Z_STREAM_END, the only possible operations on the stream /// are deflateReset or deflateEnd. /// /// Z_FINISH can be used immediately after deflateInit if all the compression /// is to be done in a single step. In this case, avail_out must be at least the /// value returned by deflateBound (see below). Then deflate is guaranteed to /// return Z_STREAM_END. If not enough output space is provided, deflate will /// not return Z_STREAM_END, and it must be called again as described above. /// /// deflate() sets strm->adler to the adler32 checksum of all input read /// so far (that is, total_in bytes). /// /// deflate() may update strm->data_type if it can make a good guess about /// the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered /// binary. This field is only for information purposes and does not affect the /// compression algorithm in any manner. /// /// deflate() returns Z_OK if some progress has been made (more input /// processed or more output produced), Z_STREAM_END if all input has been /// consumed and all output has been produced (only when flush is set to /// Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example /// if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible /// (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not /// fatal, and deflate() can be called again with more input and more output /// space to continue compressing. /// extern fn deflate(strm: z_streamp, flush: FlushValue) ReturnCode; /// /// All dynamically allocated data structures for this stream are freed. /// This function discards any unprocessed input and does not flush any pending /// output. /// /// deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the /// stream state was inconsistent, Z_DATA_ERROR if the stream was freed /// prematurely (some input or output was discarded). In the error case, msg /// may be set but then points to a static string (which must not be /// deallocated). extern fn deflateEnd(stream: z_streamp) ReturnCode; // deflateBound() returns an upper bound on the compressed size after // deflation of sourceLen bytes. It must be called after deflateInit() or // deflateInit2(), and after deflateSetHeader(), if used. This would be used // to allocate an output buffer for deflation in a single pass, and so would be // called before deflate(). If that first deflate() call is provided the // sourceLen input bytes, an output buffer allocated to the size returned by // deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed // to return Z_STREAM_END. Note that it is possible for the compressed size to // be larger than the value returned by deflateBound() if flush options other // than Z_FINISH or Z_NO_FLUSH are used. extern fn deflateBound(strm: z_streamp, sourceLen: u64) u64; /// /// This is another version of deflateInit with more compression options. The /// fields next_in, zalloc, zfree and opaque must be initialized before by the /// caller. /// /// The method parameter is the compression method. It must be Z_DEFLATED in /// this version of the library. /// /// The windowBits parameter is the base two logarithm of the window size /// (the size of the history buffer). It should be in the range 8..15 for this /// version of the library. Larger values of this parameter result in better /// compression at the expense of memory usage. The default value is 15 if /// deflateInit is used instead. /// /// windowBits can also be -8..-15 for raw deflate. In this case, -windowBits /// determines the window size. deflate() will then generate raw deflate data /// with no zlib header or trailer, and will not compute an adler32 check value. /// /// windowBits can also be greater than 15 for optional gzip encoding. Add /// 16 to windowBits to write a simple gzip header and trailer around the /// compressed data instead of a zlib wrapper. The gzip header will have no /// file name, no extra data, no comment, no modification time (set to zero), no /// header crc, and the operating system will be set to 255 (unknown). If a /// gzip stream is being written, strm->adler is a crc32 instead of an adler32. /// /// The memLevel parameter specifies how much memory should be allocated /// for the internal compression state. memLevel=1 uses minimum memory but is /// slow and reduces compression ratio; memLevel=9 uses maximum memory for /// optimal speed. The default value is 8. See zconf.h for total memory usage /// as a function of windowBits and memLevel. /// /// The strategy parameter is used to tune the compression algorithm. Use the /// value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a /// filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no /// string match), or Z_RLE to limit match distances to one (run-length /// encoding). Filtered data consists mostly of small values with a somewhat /// random distribution. In this case, the compression algorithm is tuned to /// compress them better. The effect of Z_FILTERED is to force more Huffman /// coding and less string matching; it is somewhat intermediate between /// Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as /// fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data. The /// strategy parameter only affects the compression ratio but not the /// correctness of the compressed output even if it is not set appropriately. /// Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler /// decoder for special applications. /// /// deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough /// memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid /// method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is /// incompatible with the version assumed by the caller (ZLIB_VERSION). msg is /// set to null if there is no error message. deflateInit2 does not perform any /// compression: this will be done by deflate(). extern fn deflateInit2_(strm: z_streamp, level: c_int, method: c_int, windowBits: c_int, memLevel: c_int, strategy: c_int, version: [*c]const u8, stream_size: c_int) ReturnCode; /// Not for streaming! pub const ZlibCompressorArrayList = struct { const ZlibCompressor = ZlibCompressorArrayList; pub const State = enum { Uninitialized, Inflating, End, Error, }; input: []const u8, list: std.ArrayListUnmanaged(u8), list_allocator: std.mem.Allocator, list_ptr: *std.ArrayListUnmanaged(u8), zlib: zStream_struct, allocator: std.mem.Allocator, state: State = State.Uninitialized, pub fn alloc(_: *anyopaque, items: uInt, len: uInt) callconv(.C) *anyopaque { return mimalloc.mi_malloc(items * len) orelse unreachable; } pub fn free(_: *anyopaque, data: *anyopaque) callconv(.C) void { mimalloc.mi_free(data); } pub fn deinit(this: *ZlibCompressor) void { var allocator = this.allocator; this.end(); allocator.destroy(this); } pub fn end(this: *ZlibCompressor) void { if (this.state != State.End) { _ = deflateEnd(&this.zlib); this.state = State.End; } } pub fn init(input: []const u8, list: *std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator, options: Options) ZlibError!*ZlibCompressor { return initWithListAllocator(input, list, allocator, allocator, options); } pub fn initWithListAllocator(input: []const u8, list: *std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator, list_allocator: std.mem.Allocator, options: Options) ZlibError!*ZlibCompressor { var zlib_reader = try allocator.create(ZlibCompressor); zlib_reader.* = ZlibCompressor{ .input = input, .list = list.*, .list_ptr = list, .list_allocator = list_allocator, .allocator = allocator, .zlib = undefined, }; zlib_reader.zlib = zStream_struct{ .next_in = input.ptr, .avail_in = @as(uInt, @intCast(input.len)), .total_in = @as(uInt, @intCast(input.len)), .next_out = zlib_reader.list.items.ptr, .avail_out = @as(u32, @intCast(zlib_reader.list.items.len)), .total_out = zlib_reader.list.items.len, .err_msg = null, .alloc_func = ZlibCompressor.alloc, .free_func = ZlibCompressor.free, .internal_state = null, .user_data = zlib_reader, .data_type = DataType.Unknown, .adler = 0, .reserved = 0, }; switch (deflateInit2_( &zlib_reader.zlib, options.level, options.method, if (!options.gzip) -options.windowBits else options.windowBits + 16, options.memLevel, options.strategy, zlibVersion(), @sizeOf(zStream_struct), )) { ReturnCode.Ok => { try zlib_reader.list.ensureTotalCapacityPrecise(list_allocator, deflateBound(&zlib_reader.zlib, input.len)); zlib_reader.list_ptr.* = zlib_reader.list; zlib_reader.zlib.avail_out = @as(uInt, @truncate(zlib_reader.list.capacity)); zlib_reader.zlib.next_out = zlib_reader.list.items.ptr; return zlib_reader; }, ReturnCode.MemError => { zlib_reader.deinit(); return error.OutOfMemory; }, ReturnCode.StreamError => { zlib_reader.deinit(); return error.InvalidArgument; }, ReturnCode.VersionError => { zlib_reader.deinit(); return error.InvalidArgument; }, else => unreachable, } } pub fn errorMessage(this: *ZlibCompressor) ?[]const u8 { if (this.zlib.err_msg) |msg_ptr| { return std.mem.sliceTo(msg_ptr, 0); } return null; } pub fn readAll(this: *ZlibCompressor) ZlibError!void { defer { this.list.shrinkRetainingCapacity(this.zlib.total_out); this.list_ptr.* = this.list; } while (this.state == State.Uninitialized or this.state == State.Inflating) { // Before the call of inflate(), the application should ensure // that at least one of the actions is possible, by providing // more input and/or consuming more output, and updating the // next_* and avail_* values accordingly. If the caller of // inflate() does not provide both available input and available // output space, it is possible that there will be no progress // made. The application can consume the uncompressed output // when it wants, for example when the output buffer is full // (avail_out == 0), or after each call of inflate(). If inflate // returns Z_OK and with zero avail_out, it must be called again // after making room in the output buffer because there might be // more output pending. // - Decompress more input starting at next_in and update // next_in and avail_in accordingly. If not all input can be // processed (because there is not enough room in the output // buffer), then next_in and avail_in are updated accordingly, // and processing will resume at this point for the next call // of inflate(). // - Generate more output starting at next_out and update // next_out and avail_out accordingly. inflate() provides as // much output as possible, until there is no more input data // or no more space in the output buffer (see below about the // flush parameter). if (this.zlib.avail_out == 0) { const initial = this.list.items.len; try this.list.ensureUnusedCapacity(this.list_allocator, 4096); this.list.expandToCapacity(); this.zlib.next_out = &this.list.items[initial]; this.zlib.avail_out = @as(u32, @intCast(this.list.items.len - initial)); } if (this.zlib.avail_out == 0) { return error.ShortRead; } const rc = deflate(&this.zlib, FlushValue.Finish); this.state = State.Inflating; switch (rc) { ReturnCode.StreamEnd => { this.list.items.len = this.zlib.total_out; this.end(); return; }, ReturnCode.MemError => { this.end(); this.state = State.Error; return error.OutOfMemory; }, ReturnCode.StreamError, ReturnCode.DataError, ReturnCode.BufError, ReturnCode.NeedDict, ReturnCode.VersionError, ReturnCode.ErrNo, => { this.end(); this.state = State.Error; return error.ZlibError; }, ReturnCode.Ok => {}, } } } };
https://raw.githubusercontent.com/beingofexistence13/multiversal-lang/dd769e3fc6182c23ef43ed4479614f43f29738c9/javascript/bun/src/zlib.zig
const std = @import("std"); const time = @import("../../time.zig"); const usb = @import("../../usb.zig"); const Host = @import("../dwc_otg_usb.zig"); const reg = @import("registers.zig"); const Self = @This(); // ---------------------------------------------------------------------- // Mutable state // ---------------------------------------------------------------------- host_registers: ?*volatile reg.HostRegisters = null, root_hub_device_status: usb.DeviceStatus = undefined, root_hub_hub_status: usb.HubStatus = undefined, root_hub_configuration: u8 = 1, port_connect_status_changed: bool = false, port_enabled_changed: bool = false, port_overcurrent_changed: bool = false, pub fn init(self: *Self, registers: *volatile reg.HostRegisters) void { self.* = .{ .host_registers = registers, .root_hub_device_status = @as(u32, 1) << usb.USB_FEATURE_SELF_POWERED, .root_hub_hub_status = .{ .hub_status = .{ .local_power_source = 1, .overcurrent = 0, }, .change_status = .{ .local_power_changed = 0, .overcurrent_changed = 0, }, }, }; } // ---------------------------------------------------------------------- // Static data // ---------------------------------------------------------------------- const root_hub_device_descriptor: usb.DeviceDescriptor = .{ .length = @sizeOf(usb.DeviceDescriptor), .descriptor_type = usb.USB_DESCRIPTOR_TYPE_DEVICE, .usb_standard_compliance = 0x200, .device_class = usb.USB_DEVICE_HUB, .device_subclass = 0, .device_protocol = 1, .max_packet_size = 64, .vendor = 0x1209, // see https://pid.codes .product = 0x0007, // see https://pid.codes .device_release = 0x0100, .manufacturer_name = 3, .product_name = 2, .serial_number = 1, .configuration_count = 1, }; const RootHubConfiguration = packed struct { configuration: usb.ConfigurationDescriptor, interface: usb.InterfaceDescriptor, endpoint: usb.EndpointDescriptor, }; const root_hub_configuration_descriptor: RootHubConfiguration = .{ .configuration = .{ .length = usb.ConfigurationDescriptor.STANDARD_LENGTH, .descriptor_type = usb.USB_DESCRIPTOR_TYPE_CONFIGURATION, .total_length = @sizeOf(RootHubConfiguration), .interface_count = 1, .configuration_value = 1, .configuration = 0, .attributes = 0xc0, // self-powered, no remote wakeup .power_max = 1, }, .interface = .{ .length = usb.InterfaceDescriptor.STANDARD_LENGTH, .descriptor_type = usb.USB_DESCRIPTOR_TYPE_INTERFACE, .interface_number = 0, .alternate_setting = 0, .endpoint_count = 1, .interface_class = usb.USB_INTERFACE_CLASS_HUB, .interface_subclass = 0, .interface_protocol = 1, // full speed hub .interface_string = 0, }, .endpoint = .{ .length = usb.EndpointDescriptor.STANDARD_LENGTH, .descriptor_type = usb.USB_DESCRIPTOR_TYPE_ENDPOINT, .endpoint_address = 0x81, // Endpoint 1, direction IN .attributes = usb.USB_ENDPOINT_TYPE_INTERRUPT, .max_packet_size = 0x04, .interval = 0x0c, }, }; fn mkStringDescriptor(comptime payload: []const u16) usb.StringDescriptor { if (payload.len > 31) @compileError("This unit only supports string descriptors up to 31 U16's long"); var body: [31]u16 = [_]u16{0} ** 31; @memcpy(body[0..payload.len], payload); return .{ .length = 2 + (2 * payload.len), .descriptor_type = usb.USB_DESCRIPTOR_TYPE_STRING, .body = body, }; } const root_hub_default_language = mkStringDescriptor(&[_]u16{0x0409}); const root_hub_serial_number = mkStringDescriptor(&[_]u16{ '0', '0', '4', '2' }); const root_hub_product_name = mkStringDescriptor(&[_]u16{ 'A', 'a', 'p', 'e', 'n', ' ', 'U', 'S', 'B', ' ', '2', '.', '0', ' ', 'R', 'o', 'o', 't', ' ', 'H', 'u', 'b' }); const root_hub_manufacturer = mkStringDescriptor(&[_]u16{ 'M', '&', 'R', ' ', 'h', 'o', 'b', 'b', 'y', ' ', 's', 'h', 'o', 'p' }); // The order of these items must correspond to the indexes in the // root_hub_device_descriptor const root_hub_strings = &[_]usb.StringDescriptor{ root_hub_default_language, root_hub_serial_number, root_hub_product_name, root_hub_manufacturer, }; const RootHubDescriptor = extern struct { base: usb.HubDescriptor, extra_data: [2]u8, }; pub const root_hub_hub_descriptor_base: usb.HubDescriptor = .{ .length = @sizeOf(usb.HubDescriptor) + 2, .descriptor_type = usb.USB_DESCRIPTOR_TYPE_HUB, .number_ports = 1, .characteristics = @bitCast(@as(u16, 0)), .power_on_to_power_good = 0, .controller_current = 1, }; const root_hub_hub_descriptor: RootHubDescriptor = .{ .base = root_hub_hub_descriptor_base, .extra_data = .{ 0x00, 0xff }, }; // ---------------------------------------------------------------------- // Hardware interaction // ---------------------------------------------------------------------- fn hostPortSafeRead(self: *Self, host_reg: *volatile reg.HostRegisters) reg.HostPortStatusAndControl { _ = self; var hw_status = host_reg.port; // We zero out some bits because they are "write clear" and we // could accidentally reset them if they read as 1 hw_status.enabled = 0; hw_status.connected_changed = 0; hw_status.enabled_changed = 0; hw_status.overcurrent_changed = 0; return hw_status; } fn hostPortDisable(self: *Self) usb.URB.Status { if (self.host_registers) |host_reg| { Host.log.debug(@src(), "hostPortDisable", .{}); var hw_status = self.hostPortSafeRead(host_reg); hw_status.enabled = 0; host_reg.port = hw_status; } return .OK; } fn hostPortPowerOn(self: *Self) usb.URB.Status { if (self.host_registers) |host_reg| { Host.log.debug(@src(), "hostPortPowerOn", .{}); var hw_status = self.hostPortSafeRead(host_reg); hw_status.power = 1; host_reg.port = hw_status; } return .OK; } fn hostPortPowerOff(self: *Self) usb.URB.Status { if (self.host_registers) |host_reg| { var hw_status = self.hostPortSafeRead(host_reg); hw_status.power = 0; host_reg.port = hw_status; } return .OK; } fn hostPortReset(self: *Self) usb.URB.Status { const regs = self.host_registers orelse return .Failed; var port = self.hostPortSafeRead(regs); // assert the reset bit port.reset = 1; regs.port = port; // wait for it to be processed time.delayMillis(100); // deassert the reset bit port.reset = 0; regs.port = port; // wait for it to be processed time.delayMillis(100); // we should see enabled go high within a short time. const enable_wait_end = time.deadlineMillis(200); while (regs.port.enabled == 0 and time.ticks() < enable_wait_end) { time.delayMillis(10); } if (regs.port.enabled == 0) { Host.log.err(@src(), "port enabled bit not observed before timeout", .{}); return .Failed; } return .OK; } // ---------------------------------------------------------------------- // Interrupt Handler // ---------------------------------------------------------------------- // This is called from the DWC core driver when it receives a 'port' // interrupt pub fn hubHandlePortInterrupt(self: *Self) void { const regs = self.host_registers orelse return; const port = regs.port; var port_dup = port; port_dup.overcurrent_changed = 0; port_dup.connected_changed = 0; port_dup.enabled_changed = 0; port_dup.enabled = 0; Host.log.debug(@src(), "host port interrupt, port 0x{x:0>8}", .{@as(u32, @bitCast(port))}); if (port.connected_changed != 0) { if (port.connected != 0) { // indicate port status change of port 1 (which is bit 1 == 0x02) usb.root_hub.status_change_buffer[0] = 0x2; usb.hubThreadWakeup(usb.root_hub); } port_dup.connected_changed = 1; // write-clear this status bit self.port_connect_status_changed = true; } if (port.enabled_changed != 0) { port_dup.enabled_changed = 1; // write-clear this status bit self.port_enabled_changed = true; // TODO - do we need to perform speed detection here? } if (port.overcurrent_changed != 0) { port_dup.overcurrent_changed = 1; // write-clear this status bit self.port_overcurrent_changed = true; } // Clear the interrupts by writing the modified control register value back regs.port = port_dup; } // ---------------------------------------------------------------------- // Request Handling Behavior // ---------------------------------------------------------------------- fn getPortSpeed(self: *Self) u8 { return switch (self.host_registers.?.port.speed) { .high => usb.USB_SPEED_HIGH, .full => usb.USB_SPEED_FULL, .low => usb.USB_SPEED_LOW, .undefined => usb.USB_SPEED_UNKNOWN, }; } fn replyWithStructure(setup: *usb.SetupPacket, out: []u8, data: []const u8) usb.URB.Status { _ = setup; const actual_length = @min(out.len, data.len); Host.log.debug(@src(), "responding with {d} bytes from 0x{x:0>8}", .{ actual_length, @intFromPtr(data.ptr) }); Host.log.sliceDump(@src(), data[0..actual_length]); @memcpy(out[0..actual_length], data[0..actual_length]); return .OK; } // zig fmt: off inline fn deviceRequest(rt: u8) bool { return rt & 0x1f == usb.REQUEST_RECIPIENT_DEVICE; } inline fn otherRequest(rt: u8) bool { return rt & 0x1f == usb.REQUEST_RECIPIENT_OTHER; } inline fn standardRequest(rt: u8) bool { return rt & 0x60 == usb.REQUEST_TYPE_STANDARD; } inline fn classRequest(rt: u8) bool { return rt & 0x60 == usb.REQUEST_TYPE_CLASS; } // zig fmt: on pub fn control(self: *Self, setup: *usb.SetupPacket, data: ?[]u8) usb.URB.Status { Host.log.debug(@src(), "processing control message, req_type 0x{x:0>2}, req 0x{x:0>2}", .{ setup.request_type, setup.request }); Host.log.sliceDump(@src(), std.mem.asBytes(setup)); const port = setup.index; if (deviceRequest(setup.request_type)) { switch (setup.request) { usb.HUB_REQUEST_CLEAR_FEATURE => { switch (setup.value) { usb.USB_HUB_FEATURE_C_LOCAL_POWER => return .OK, usb.USB_HUB_FEATURE_C_OVERCURRENT => return .OK, else => return .NotSupported, } }, usb.HUB_REQUEST_SET_FEATURE => { switch (setup.value) { usb.USB_HUB_FEATURE_C_LOCAL_POWER => return .OK, usb.USB_HUB_FEATURE_C_OVERCURRENT => return .OK, else => return .NotSupported, } }, usb.USB_REQUEST_SET_ADDRESS => return .OK, usb.USB_REQUEST_SET_CONFIGURATION => { self.root_hub_configuration = @truncate(setup.value & 0xff); return .OK; }, usb.USB_REQUEST_GET_DESCRIPTOR => { const descriptor_type = setup.value >> 8; if (standardRequest(setup.request_type)) { switch (descriptor_type) { usb.USB_DESCRIPTOR_TYPE_DEVICE => { return replyWithStructure(setup, data.?, std.mem.asBytes(&root_hub_device_descriptor)); }, usb.USB_DESCRIPTOR_TYPE_CONFIGURATION => { return replyWithStructure(setup, data.?, std.mem.asBytes(&root_hub_configuration_descriptor)); }, usb.USB_DESCRIPTOR_TYPE_STRING => { const string_index = setup.value & 0xf; if (string_index < root_hub_strings.len) { return replyWithStructure(setup, data.?, std.mem.asBytes(&root_hub_strings[string_index])); } else { return .Failed; } }, else => return .NotSupported, } } else if (classRequest(setup.request_type)) { switch (descriptor_type) { usb.USB_DESCRIPTOR_TYPE_HUB => { return replyWithStructure(setup, data.?, std.mem.asBytes(&root_hub_hub_descriptor)); }, else => return .NotSupported, } } else { return .Failed; } }, usb.HUB_REQUEST_GET_STATUS => { return replyWithStructure(setup, data.?, std.mem.asBytes(&self.root_hub_hub_status)); }, usb.USB_REQUEST_GET_CONFIGURATION => { return replyWithStructure(setup, data.?, std.mem.asBytes(&self.root_hub_configuration)); }, else => return .NotSupported, } } else if (otherRequest(setup.request_type)) { switch (setup.request) { usb.HUB_REQUEST_CLEAR_FEATURE => { Host.log.debug(@src(), "port {d} feature clear {d}", .{ port, setup.value }); if (port != 1) { return .Failed; } switch (setup.value) { usb.HUB_PORT_FEATURE_PORT_ENABLE => return self.hostPortDisable(), usb.HUB_PORT_FEATURE_PORT_POWER => return self.hostPortPowerOff(), usb.HUB_PORT_FEATURE_C_PORT_CONNECTION => { self.port_connect_status_changed = false; return .OK; }, usb.HUB_PORT_FEATURE_C_PORT_ENABLE => { self.port_enabled_changed = false; return .OK; }, usb.HUB_PORT_FEATURE_C_PORT_OVER_CURRENT => { self.port_overcurrent_changed = false; return .OK; }, else => return .OK, } }, usb.HUB_REQUEST_GET_STATUS => { if (port != 1) { return .Failed; } var status: u32 = 0; if (self.port_connect_status_changed) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_C_PORT_CONNECTION; } if (self.port_enabled_changed) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_C_PORT_ENABLE; } if (self.port_overcurrent_changed) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_C_PORT_OVER_CURRENT; } const port_control: reg.HostPortStatusAndControl = self.host_registers.?.port; Host.log.debug(@src(), "hub_request_get_status, port status is 0x{x:0>8}", .{@as(u32, @bitCast(port_control))}); if (port_control.connected != 0) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_CONNECTION; } if (port_control.enabled != 0) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_ENABLE; const speed = self.getPortSpeed(); if (speed == usb.USB_SPEED_LOW) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_LOW_SPEED; } else if (speed == usb.USB_SPEED_HIGH) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_HIGH_SPEED; } } if (port_control.overcurrent != 0) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_OVER_CURRENT; } if (port_control.reset != 0) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_RESET; } if (port_control.power != 0) { status |= @as(u32, 1) << usb.HUB_PORT_FEATURE_PORT_POWER; } return replyWithStructure(setup, data.?, std.mem.asBytes(&status)); }, usb.HUB_REQUEST_SET_FEATURE => { if (port != 1) { return .Failed; } switch (setup.value) { usb.HUB_PORT_FEATURE_PORT_POWER => return self.hostPortPowerOn(), usb.HUB_PORT_FEATURE_PORT_RESET => return self.hostPortReset(), // usb.HUB_PORT_FEATURE_PORT_SUSPEND => return .OK, else => return .OK, } }, else => return .NotSupported, } } else { return .NotSupported; } }
https://raw.githubusercontent.com/aapen/aapen/c02010f570ec1f69905afe607d2ed4080c2e8edb/src/drivers/dwc/root_hub.zig