text
stringlengths
32
314k
url
stringlengths
93
243
// // Another useful application for bit manipulation is setting bits as flags. // This is especially useful when processing lists of something and storing // the states of the entries, e.g. a list of numbers and for each prime // number a flag is set. // // As an example, let's take the Pangram exercise from Exercism: // https://exercism.org/tracks/zig/exercises/pangram // // A pangram is a sentence using every letter of the alphabet at least once. // It is case insensitive, so it doesn't matter if a letter is lower-case // or upper-case. The best known English pangram is: // // "The quick brown fox jumps over the lazy dog." // // There are several ways to select the letters that appear in the pangram // (and it doesn't matter if they appear once or several times). // // For example, you could take an array of bool and set the value to 'true' // for each letter in the order of the alphabet (a=0; b=1; etc.) found in // the sentence. However, this is neither memory efficient nor particularly // fast. Instead we choose a simpler approach that is very similar in principle: // We define a variable with at least 26 bits (e.g. u32) and set the bit for // each letter that is found in the corresponding position. // // Zig provides functions for this in the standard library, but we prefer to // solve it without these extras, after all we want to learn something. // const std = @import("std"); const ascii = std.ascii; const print = std.debug.print; pub fn main() !void { // let's check the pangram print("Is this a pangram? {?}!\n", .{isPangram("The quick brown fox jumps over the lazy dog.")}); } fn isPangram(str: []const u8) bool { // first we check if the string has at least 26 characters if (str.len < 26) return false; // we use a 32 bit variable of which we need 26 bits var bits: u32 = 0; // loop about all characters in the string for (str) |c| { // if the character is an alphabetical character if (ascii.isASCII(c) and ascii.isAlphabetic(c)) { // then we set the bit at the position // // to do this, we use a little trick: // since the letters in the ASCII table start at 65 // and are numbered sequentially, we simply subtract the // first letter (in this case the 'a') from the character // found, and thus get the position of the desired bit bits |= @as(u32, 1) << @truncate(ascii.toLower(c) - 'a'); } } // last we return the comparison if all 26 bits are set, // and if so, we know the given string is a pangram // // but what do we have to compare? return bits == 0x3ffffff; }
https://raw.githubusercontent.com/zzhaolei/ziglings/e8c3b28199122b983adf9b7a24d6477054b25758/exercises/098_bit_manipulation2.zig
const std = @import("std"); pub fn twoFer(buffer: []u8, name: ?[]const u8) anyerror![]u8 { return std.fmt.bufPrint(buffer, "One for {s}, one for me.", .{name orelse "you"}); }
https://raw.githubusercontent.com/ArturMroz/exercism/89c48a757e1e2e3b6973b8dd23366243337bbc30/zig/two-fer/two_fer.zig
pub const AllocateType = @import("tables/boot_services.zig").AllocateType; pub const BootServices = @import("tables/boot_services.zig").BootServices; pub const ConfigurationTable = @import("tables/configuration_table.zig").ConfigurationTable; pub const global_variable align(8) = @import("tables/runtime_services.zig").global_variable; pub const LocateSearchType = @import("tables/boot_services.zig").LocateSearchType; pub const MemoryDescriptor = @import("tables/boot_services.zig").MemoryDescriptor; pub const MemoryType = @import("tables/boot_services.zig").MemoryType; pub const OpenProtocolAttributes = @import("tables/boot_services.zig").OpenProtocolAttributes; pub const ProtocolInformationEntry = @import("tables/boot_services.zig").ProtocolInformationEntry; pub const ResetType = @import("tables/runtime_services.zig").ResetType; pub const RuntimeServices = @import("tables/runtime_services.zig").RuntimeServices; pub const SystemTable = @import("tables/system_table.zig").SystemTable; pub const TableHeader = @import("tables/table_header.zig").TableHeader; pub const TimerDelay = @import("tables/boot_services.zig").TimerDelay;
https://raw.githubusercontent.com/ziglang/gotta-go-fast/c915c45c5afed9a2e2de4f4484acba2df5090c3a/src/self-hosted-parser/input_dir/os/uefi/tables.zig
const std = @import("std"); const wren = @import("wren"); pub var alloc = std.testing.allocator; pub fn main() anyerror!void { // Initialize the data structures for the wrapper wren.init(alloc); defer wren.deinit(); // Set up a VM configuration using the supplied default bindings // You can override the bindings after calling this to change them var config = wren.util.defaultConfig(); // Create a new VM from our config we generated previously const vm = wren.newVM(&config); defer wren.freeVM(vm); // Run some basic Wren code try wren.util.run(vm,"main", \\ System.print("Hello from Wren!") \\ System.print("Testing line 2!") \\ System.print("Bytes: \x48\x69\x2e") \\ System.print("Interpolation: 3 + 4 = %(3 + 4)!") \\ System.print("Complex interpolation: %((1..3).map {|n| n * n}.join())") ); // A simple way of running a static Wren file using @embedFile try wren.util.run(vm,"main",@embedFile("test.wren")); }
https://raw.githubusercontent.com/NewbLuck/zig-wren/cdb4ee342c00ce17518720333a8d07203d78bdd2/example/basic.zig
pub const cell_phone = struct { pub usingnamespace @import("../locales/fa/cell_phone.zig"); }; pub const color = struct { pub usingnamespace @import("../locales/fa/color.zig"); }; pub const commerce = struct { pub usingnamespace @import("../locales/fa/commerce.zig"); }; pub const company = struct { pub usingnamespace @import("../locales/fa/company.zig"); }; pub const date = struct { pub usingnamespace @import("../locales/fa/date.zig"); }; pub const finance = struct { pub usingnamespace @import("../locales/fa/finance.zig"); }; pub const internet = struct { pub usingnamespace @import("../locales/fa/internet.zig"); }; pub const location = struct { pub usingnamespace @import("../locales/fa/location.zig"); }; pub const lorem = struct { pub usingnamespace @import("../locales/fa/lorem.zig"); }; pub const metadata = struct { pub usingnamespace @import("../locales/fa/metadata.zig"); }; pub const music = struct { pub usingnamespace @import("../locales/fa/music.zig"); }; pub const person = struct { pub usingnamespace @import("../locales/fa/person.zig"); }; pub const phone_number = struct { pub usingnamespace @import("../locales/fa/phone_number.zig"); }; pub const vehicle = struct { pub usingnamespace @import("../locales/fa/vehicle.zig"); }; pub const word = struct { pub usingnamespace @import("../locales/fa/word.zig"); };
https://raw.githubusercontent.com/cksac/faker-zig/5a51eb6e6aa4ce50a25a354affca36e8fa059675/src/locale/fa.zig
const std = @import("std"); const base64 = @import("base64.zig"); // Assume the provided code is in base64.zig export fn decodeBase64(encoded: [*c]const u8, encoded_len: usize, decoded: [*]u8, decoded_len: *usize) c_int { var allocator = std.heap.page_allocator; const encoded_slice = std.mem.slice(u8, encoded, encoded_len); var buffer = try allocator.alloc(u8, base64.standard.Decoder.calcSizeForSlice(encoded_slice) catch return -1); defer allocator.free(buffer); // Attempt to decode the base64 encoded string try base64.standard.Decoder.decode(buffer, encoded_slice) catch return -1; // Ensure the decoded buffer fits in the provided output buffer if (buffer.len > decoded_len.*) { return -2; // Output buffer is too small } // Copy the decoded bytes to the output buffer std.mem.copy(u8, decoded, buffer); decoded_len.* = buffer.len; return 0; // Success }
https://raw.githubusercontent.com/TylerKerch/TreeHacks2024/921eeadd49457d55d18ea84864b8473c063af3ad/backend/base64.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "games", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); b.installArtifact(exe); const exe_unit_tests = b.addTest(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_exe_unit_tests.step); exe.linkSystemLibrary2("raylib", .{}); exe.linkSystemLibrary2("GL", .{}); exe.linkSystemLibrary2("rt", .{}); exe.linkSystemLibrary2("dl", .{}); exe.linkSystemLibrary2("m", .{}); exe.linkSystemLibrary2("X11", .{}); }
https://raw.githubusercontent.com/Hejsil/games/f78ccccae233aefe863af9ab2ea1be41eae5cd8b/build.zig
const std = @import("std"); const Allocator = std.mem.Allocator; pub fn main() !void { const stdout = std.io.getStdOut().writer(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); try sierpinski_triangle(allocator, stdout, 4); }
https://raw.githubusercontent.com/acmeism/RosettaCodeData/29a5eea0d45a07fe7f50994dd8a253eef2c26d51/Task/Sierpinski-triangle/Zig/sierpinski-triangle-2.zig
pub const SourceFile = @import("SourceFile.zig"); pub const FileWatcher = @import("FileWatcher.zig");
https://raw.githubusercontent.com/guidoschmidt/zreload/749f5d4a982547f2e4b763ad818f445f1c450256/src/lib.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const util = @import("util.zig"); const gpa = util.gpa; pub const data = @embedFile("data/day03.txt"); const testdata = "^>v<"; test "day03_part1" { const res = part1(testdata); assert(res == 4); } pub fn part1(input: []const u8) usize { var map: [200][200]bool = comptime std.mem.zeroes([200][200]bool); var x: usize = 100; var y: usize = 100; var count: usize = 1; map[y][x] = true; for (input) |c| { switch (c) { '^' => y += 1, 'v' => y -= 1, '>' => x += 1, '<' => x -= 1, else => unreachable, } if (!map[y][x]) { count += 1; map[y][x] = true; } } return count; } test "day03_part2" { const res = part2(testdata); assert(res == 3); } pub fn part2(input: []const u8) usize { var map: [200][200]bool = comptime std.mem.zeroes([200][200]bool); var pos: [2][2]usize = .{ .{ 100, 100 }, .{ 100, 100 } }; var count: usize = 1; var step: usize = 0; map[100][100] = true; for (input) |c| { const which = step % 2; switch (c) { '^' => pos[which][1] += 1, 'v' => pos[which][1] -= 1, '>' => pos[which][0] += 1, '<' => pos[which][0] -= 1, else => unreachable, } if (!map[pos[which][1]][pos[which][0]]) { count += 1; map[pos[which][1]][pos[which][0]] = true; } step += 1; } return count; } pub fn main() !void { var timer = std.time.Timer.start() catch unreachable; const res = part1(data); const time = timer.lap(); const res2 = part2(data); const time2 = timer.lap(); print("Day 03:\n", .{}); print("\tPart 1: {}\n", .{res}); print("\tPart 2: {}\n", .{res2}); print("\tTime: {}ns\n", .{time}); print("\tTime: {}ns\n", .{time2}); } // Useful stdlib functions const tokenizeAny = std.mem.tokenizeAny; const tokenizeSeq = std.mem.tokenizeSequence; const tokenizeSca = std.mem.tokenizeScalar; const splitAny = std.mem.splitAny; const splitSeq = std.mem.splitSequence; const splitSca = std.mem.splitScalar; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.block; const asc = std.sort.asc; const desc = std.sort.desc; // Generated from template/template.zig. // Run `zig build generate` to update. // Only unmodified days will be updated.
https://raw.githubusercontent.com/jgh713/aoc/9ce203e4d6f53a81ad14e7b0eb095657df4f18e6/2015/src/day03.zig
const std = @import("std"); const utils_mod = @import("../utils.zig"); const print = utils_mod.print; const value_mod = @import("../value.zig"); const Value = value_mod.Value; const ValueDictionary = value_mod.ValueDictionary; const ValueHashMapContext = value_mod.ValueHashMapContext; const ValueSliceHashMapContext = value_mod.ValueSliceHashMapContext; const ValueTable = value_mod.ValueTable; const ValueType = value_mod.ValueType; const vm_mod = @import("../vm.zig"); const VM = vm_mod.VM; pub const GroupError = error{ invalid_type, }; fn runtimeError(comptime err: GroupError) GroupError!*Value { switch (err) { GroupError.invalid_type => print("Can only group lists values.\n", .{}), } return err; } pub fn group(vm: *VM, x: *Value) GroupError!*Value { return switch (x.as) { .list, .boolean_list, .int_list, .float_list, .char_list, .symbol_list => |list_x| blk: { if (list_x.len == 0) { const value = vm.initValue(.{ .list = &.{} }); break :blk vm.initDictionary(.{ .keys = x.ref(), .values = value }); } var hash_map = std.ArrayHashMap(*Value, *std.ArrayList(*Value), ValueHashMapContext, false).init(vm.allocator); defer hash_map.deinit(); for (list_x, 0..) |k, i| { if (hash_map.get(k)) |*list| { list.*.append(vm.initValue(.{ .int = @intCast(i64, i) })) catch std.debug.panic("Failed to append item.", .{}); } else { const list = vm.allocator.create(std.ArrayList(*Value)) catch std.debug.panic("Failed to create list.", .{}); list.* = std.ArrayList(*Value).init(vm.allocator); list.*.append(vm.initValue(.{ .int = @intCast(i64, i) })) catch std.debug.panic("Failed to append item.", .{}); hash_map.put(k.ref(), list) catch std.debug.panic("Failed to put item.", .{}); } } const keys_list = vm.allocator.dupe(*Value, hash_map.keys()) catch std.debug.panic("Failed to create list.", .{}); const keys = vm.initList(keys_list, x.as); const values_list = vm.allocator.alloc(*Value, keys_list.len) catch std.debug.panic("Failed to create list.", .{}); for (hash_map.values(), 0..) |array_list, i| { const slice = array_list.toOwnedSlice() catch std.debug.panic("Failed to create list.", .{}); values_list[i] = vm.initList(slice, .int); vm.allocator.destroy(array_list); } const values = vm.initValue(.{ .list = values_list }); break :blk vm.initDictionary(.{ .keys = keys, .values = values }); }, .dictionary => |dict_x| blk: { if (dict_x.keys.asList().len == 0) { const value = vm.initValue(.{ .list = &.{} }); break :blk vm.initDictionary(.{ .keys = dict_x.values.ref(), .values = value }); } var hash_map = std.ArrayHashMap(*Value, *std.ArrayList(*Value), ValueHashMapContext, false).init(vm.allocator); defer hash_map.deinit(); for (dict_x.values.asList(), dict_x.keys.asList()) |k, v| { if (hash_map.get(k)) |*list| { list.*.append(v.ref()) catch std.debug.panic("Failed to append item.", .{}); } else { const list = vm.allocator.create(std.ArrayList(*Value)) catch std.debug.panic("Failed to create list.", .{}); list.* = std.ArrayList(*Value).init(vm.allocator); list.*.append(v.ref()) catch std.debug.panic("Failed to append item.", .{}); hash_map.put(k.ref(), list) catch std.debug.panic("Failed to put item.", .{}); } } const keys_list = vm.allocator.dupe(*Value, hash_map.keys()) catch std.debug.panic("Failed to create list.", .{}); const keys = vm.initList(keys_list, dict_x.values.as); const values_list = vm.allocator.alloc(*Value, keys_list.len) catch std.debug.panic("Failed to create list.", .{}); for (hash_map.values(), 0..) |array_list, i| { const slice = array_list.toOwnedSlice() catch std.debug.panic("Failed to create list.", .{}); values_list[i] = vm.initList(slice, dict_x.keys.as); vm.allocator.destroy(array_list); } const values = vm.initValue(.{ .list = values_list }); break :blk vm.initDictionary(.{ .keys = keys, .values = values }); }, .table => |table_x| blk: { const table_len = table_x.values.as.list[0].asList().len; if (table_len == 0) { const key = x.ref(); const value = vm.initValue(.{ .list = &.{} }); break :blk vm.initDictionary(.{ .keys = key, .values = value }); } var hash_map = std.ArrayHashMap([]*Value, *std.ArrayList(*Value), ValueSliceHashMapContext, false).init(vm.allocator); defer hash_map.deinit(); var i: usize = 0; while (i < table_len) : (i += 1) { const k = vm.allocator.alloc(*Value, table_x.columns.as.symbol_list.len) catch std.debug.panic("Failed to create list.", .{}); for (table_x.values.as.list, 0..) |c, j| { k[j] = c.asList()[i]; } if (hash_map.get(k)) |*list| { vm.allocator.free(k); list.*.append(vm.initValue(.{ .int = @intCast(i64, i) })) catch std.debug.panic("Failed to append item.", .{}); } else { for (k) |v| _ = v.ref(); const list = vm.allocator.create(std.ArrayList(*Value)) catch std.debug.panic("Failed to create list.", .{}); list.* = std.ArrayList(*Value).init(vm.allocator); list.*.append(vm.initValue(.{ .int = @intCast(i64, i) })) catch std.debug.panic("Failed to append item.", .{}); hash_map.put(k, list) catch std.debug.panic("Failed to put item.", .{}); } } const keys_slice = hash_map.keys(); defer for (keys_slice) |v| vm.allocator.free(v); const keys_list = vm.allocator.alloc(*Value, keys_slice[0].len) catch std.debug.panic("Failed to create list.", .{}); i = 0; while (i < keys_slice[0].len) : (i += 1) { const list = vm.allocator.alloc(*Value, keys_slice.len) catch std.debug.panic("Failed to create list.", .{}); for (keys_slice, 0..) |v, j| { list[j] = v[i]; } keys_list[i] = vm.initValue(.{ .int_list = list }); } const keys = vm.initTable(.{ .columns = table_x.columns.ref(), .values = vm.initValue(.{ .list = keys_list }) }); const values_list = vm.allocator.alloc(*Value, keys_slice.len) catch std.debug.panic("Failed to create list.", .{}); for (hash_map.values(), 0..) |array_list, j| { const slice = array_list.toOwnedSlice() catch std.debug.panic("Failed to create list.", .{}); values_list[j] = vm.initList(slice, .int); vm.allocator.destroy(array_list); } const values = vm.initValue(.{ .list = values_list }); break :blk vm.initDictionary(.{ .keys = keys, .values = values }); }, else => runtimeError(GroupError.invalid_type), }; }
https://raw.githubusercontent.com/dstrachan/openk/0a739d96593fe3e1a7ebe54e5b82e2a69f64302a/src/verbs/group.zig
const std = @import("std"); const Compiler = @import("Compiler.zig"); const Context = @import("Context.zig"); const Lexer = @import("Lexer.zig"); const Node = @import("Node.zig"); const Parser = @import("Parser.zig"); fn printUsage() !void { std.log.err("Usage: zedc <your_program_file.zed>", .{}); return error.InvalidUsage; } pub fn main() !void { const allocator = std.heap.page_allocator; var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); // Command line args. var args = try std.process.argsWithAllocator(arena.allocator()); _ = args.skip(); // skip program name. // Program file. const program_filename = args.next() orelse return printUsage(); var program_file = try std.fs.cwd().openFile(program_filename, .{}); defer program_file.close(); const program_src = try program_file.readToEndAlloc(arena.allocator(), 1024 * 64); // 64K // Context const ctx = Context{ .filename = program_filename, .src = program_src }; // Frontend // Lex var lexer = Lexer{ .allocator = arena.allocator(), .ctx = ctx }; const tokens = try lexer.lex(); // Parse var parser = Parser{ .allocator = arena.allocator(), .ctx = ctx, .tokens = tokens, }; const program = try parser.parse(); // Backend / Compile to bytecode var compiler = try Compiler.init(arena.allocator(), ctx); const compiled = try compiler.compileProgram(arena.allocator(), program); // Output var buf = try std.ArrayList(u8).initCapacity(arena.allocator(), program_filename.len + 4); if (std.mem.endsWith(u8, program_filename, ".zed")) { _ = try buf.writer().print("{s}.zbc", .{program_filename[0 .. program_filename.len - 4]}); } else { _ = try buf.writer().print("{s}.zbc", .{program_filename}); } var bytecode_file = try std.fs.cwd().createFile(buf.items, .{}); var out_buf = std.io.bufferedWriter(bytecode_file.writer()); var writer = out_buf.writer(); for (compiled) |bytes| { const len_bytes = std.mem.sliceAsBytes(&[1]u16{@intCast(u16, bytes.len)}); try writer.writeAll(len_bytes); try writer.writeAll(bytes); } try out_buf.flush(); }
https://raw.githubusercontent.com/jreniel/zed/a40574112ad11db60157608ebf9e2835fb149ee6/src/zedc.zig
//! Misc things that will be moved into the standard library once this is complete const std = @import("std"); const builtin = @import("builtin"); pub const windows = struct { const HKEY = std.os.windows.HKEY; const USHORT = std.os.windows.USHORT; const ULONG = std.os.windows.ULONG; const HANDLE = std.os.windows.HANDLE; const BYTE = std.os.windows.BYTE; const UCHAR = std.os.windows.UCHAR; const WINAPI = std.os.windows.WINAPI; const LPWSTR = std.os.windows.LPWSTR; const UINT = std.os.windows.UINT; const LANGID = std.os.windows.LANGID; const ACCESS_MASK = std.os.windows.ACCESS_MASK; const NTSTATUS = std.os.windows.NTSTATUS; const BOOLEAN = std.os.windows.BOOLEAN; const UNICODE_STRING = std.os.windows.UNICODE_STRING; const PVOID = std.os.windows.PVOID; pub const ntdll = struct { pub extern "ntdll" fn NtOpenProcessToken( ProcessHandle: HANDLE, DesiredAccess: ACCESS_MASK, TokenHandle: *HANDLE, ) callconv(WINAPI) NTSTATUS; pub extern "ntdll" fn NtQueryInformationToken( TokenHandle: HANDLE, TokenInformationClass: TOKEN_INFORMATION_CLASS, TokenInformation: *anyopaque, TokenInformationLength: ULONG, ReturnLength: *ULONG, ) callconv(WINAPI) NTSTATUS; pub extern "ntdll" fn RtlConvertSidToUnicodeString( UnicodeString: *UNICODE_STRING, Sid: *SID, AllocateDestinationString: BOOLEAN, ) callconv(WINAPI) NTSTATUS; pub extern "ntdll" fn RtlExpandEnvironmentStrings_U( Environment: ?PVOID, Source: *UNICODE_STRING, Destination: *UNICODE_STRING, ReturnedLength: *ULONG, ) callconv(WINAPI) NTSTATUS; }; pub const kernel32 = struct { pub extern "kernel32" fn GetWindowsDirectoryW(lpBuffer: LPWSTR, uSize: UINT) callconv(WINAPI) UINT; pub extern "kernel32" fn GetSystemDirectoryW(lpBuffer: LPWSTR, uSize: UINT) callconv(WINAPI) UINT; pub extern "kernel32" fn GetSystemWow64DirectoryW(lpBuffer: LPWSTR, uSize: UINT) callconv(WINAPI) UINT; pub extern "kernel32" fn GetUserDefaultLangID() callconv(WINAPI) LANGID; }; // This is a hack. Instead of this hacky workaround, `SystemProcessorInformation = 1,` // should just be added to the SYSTEM_INFORMATION_CLASS enum. pub fn SystemProcessorInformationEnum() std.os.windows.SYSTEM_INFORMATION_CLASS { const val: c_int = 1; return @as(*std.os.windows.SYSTEM_INFORMATION_CLASS, @ptrFromInt(@intFromPtr(&val))).*; } pub const HKEY_CURRENT_USER: HKEY = @ptrFromInt(0x80000001); pub const HKEY_USERS: HKEY = @ptrFromInt(0x80000003); pub const GUID = struct { // copied from std/os/windows.zig const hex_offsets = switch (builtin.target.cpu.arch.endian()) { .big => [16]u6{ 0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34, }, .little => [16]u6{ 6, 4, 2, 0, 11, 9, 16, 14, 19, 21, 24, 26, 28, 30, 32, 34, }, }; /// Length of a stringified GUID in characters, including the { and } pub const string_len = 38; pub fn stringify(self: std.os.windows.GUID) [string_len:0]u8 { return stringifyImpl(self, u8); } /// Returns UTF-16 LE pub fn stringifyW(self: std.os.windows.GUID) [string_len:0]u16 { return stringifyImpl(self, u16); } /// If T is u16, returns UTF-16 LE fn stringifyImpl(self: std.os.windows.GUID, comptime T: type) [string_len:0]T { var str: [string_len:0]T = comptime init: { var arr: [string_len:0]T = undefined; const bytes = "{00000000-0000-0000-0000-000000000000}".*; for (bytes, 0..) |byte, i| { arr[i] = byte; } break :init arr; }; const bytes: [16]u8 = @bitCast(self); for (hex_offsets, 0..) |hex_offset, i| { const str_index = hex_offset + 1; const byte = bytes[i]; str[str_index] = std.mem.nativeToLittle(T, std.fmt.digitToChar(byte / 16, .upper)); str[str_index + 1] = std.mem.nativeToLittle(T, std.fmt.digitToChar(byte % 16, .upper)); } return str; } }; pub const SYSTEM_PROCESSOR_INFORMATION = extern struct { ProcessorArchitecture: USHORT, ProcessorLevel: USHORT, ProcessorRevision: USHORT, MaximumProcessors: USHORT, ProcessorFeatureBits: ULONG, }; /// x64 (AMD or Intel) pub const PROCESSOR_ARCHITECTURE_AMD64 = 9; /// ARM pub const PROCESSOR_ARCHITECTURE_ARM = 5; /// ARM64 pub const PROCESSOR_ARCHITECTURE_ARM64 = 12; /// Intel Itanium-based pub const PROCESSOR_ARCHITECTURE_IA64 = 6; /// x86 pub const PROCESSOR_ARCHITECTURE_INTEL = 0; pub const PROCESSOR_ARCHITECTURE_UNKNOWN = 0xffff; pub const TOKEN_INFORMATION_CLASS = enum(c_int) { TokenUser = 1, TokenGroups, TokenPrivileges, TokenOwner, TokenPrimaryGroup, TokenDefaultDacl, TokenSource, TokenType, TokenImpersonationLevel, TokenStatistics, TokenRestrictedSids, TokenSessionId, TokenGroupsAndPrivileges, TokenSessionReference, TokenSandBoxInert, TokenAuditPolicy, TokenOrigin, TokenElevationType, TokenLinkedToken, TokenElevation, TokenHasRestrictions, TokenAccessInformation, TokenVirtualizationAllowed, TokenVirtualizationEnabled, TokenIntegrityLevel, TokenUIAccess, TokenMandatoryPolicy, TokenLogonSid, TokenIsAppContainer, TokenCapabilities, TokenAppContainerSid, TokenAppContainerNumber, TokenUserClaimAttributes, TokenDeviceClaimAttributes, TokenRestrictedUserClaimAttributes, TokenRestrictedDeviceClaimAttributes, TokenDeviceGroups, TokenRestrictedDeviceGroups, TokenSecurityAttributes, TokenIsRestricted, TokenProcessTrustLevel, TokenPrivateNameSpace, TokenSingletonAttributes, TokenBnoIsolation, TokenChildProcessFlags, TokenIsLessPrivilegedAppContainer, TokenIsSandboxed, TokenIsAppSilo, MaxTokenInfoClass, }; /// https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_sid_identifier_authority pub const SID_IDENTIFIER_AUTHORITY = extern struct { Value: [6]BYTE, }; /// https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/ntifs/ns-ntifs-_sid pub const SID = extern struct { Revision: UCHAR, SubAuthorityCount: UCHAR, IdentifierAuthority: SID_IDENTIFIER_AUTHORITY, /// Flexible array of length SubAuthorityCount SubAuthority: [1]ULONG, pub fn subAuthority(self: *const SID) []const ULONG { return @as([*]const ULONG, @ptrCast(&self.SubAuthority))[0..self.SubAuthorityCount]; } }; /// SID_MAX_SUB_AUTHORITIES is defined in WinNT.h as 15. pub const SID_MAX_SUB_AUTHORITIES = 15; pub const SID_AND_ATTRIBUTES = extern struct { Sid: *SID, Attributes: ULONG, }; // Defined as a macro in wdm.h that returns `(HANDLE)(LONG_PTR) -1` // https://learn.microsoft.com/en-us/windows-hardware/drivers/kernel/zwcurrentprocess pub const NtCurrentProcess: HANDLE = @ptrFromInt(std.math.maxInt(usize)); // https://learn.microsoft.com/en-us/windows/win32/secauthz/access-rights-for-access-token-objects pub const TOKEN_ASSIGN_PRIMARY = 0x0001; pub const TOKEN_DUPLICATE = 0x0002; pub const TOKEN_IMPERSONATE = 0x0004; pub const TOKEN_QUERY = 0x0008; pub const TOKEN_QUERY_SOURCE = 0x0010; pub const TOKEN_ADJUST_PRIVILEGES = 0x0020; pub const TOKEN_ADJUST_GROUPS = 0x0040; pub const TOKEN_ADJUST_DEFAULT = 0x0080; pub const TOKEN_ADJUST_SESSIONID = 0x0100; pub const TOKEN_USER = extern struct { User: SID_AND_ATTRIBUTES, }; }; test "GUID" { const guid = std.os.windows.GUID{ .Data1 = 0x01234567, .Data2 = 0x89ab, .Data3 = 0xef10, .Data4 = "\x32\x54\x76\x98\xba\xdc\xfe\x91".*, }; const str = windows.GUID.stringify(guid); try std.testing.expectEqualStrings("{01234567-89AB-EF10-3254-7698BADCFE91}", &str); const str_w = windows.GUID.stringifyW(guid); try std.testing.expectEqualSlices( u16, unicode.asciiToUtf16LeStringLiteral("{01234567-89AB-EF10-3254-7698BADCFE91}"), &str_w, ); } pub const unicode = struct { /// Converts an ASCII string literal into a UTF-16LE string literal. pub fn asciiToUtf16LeStringLiteral(comptime ascii: []const u8) *const [ascii.len:0]u16 { return comptime blk: { var utf16le: [ascii.len:0]u16 = undefined; for (ascii, 0..) |c, i| { std.debug.assert(std.ascii.isASCII(c)); utf16le[i] = std.mem.nativeToLittle(u16, c); } break :blk &utf16le; }; } };
https://raw.githubusercontent.com/squeek502/get-known-folder-path/8dce70ef977400212ba88905ed4aeefed4c5915c/src/misc.zig
const builtin = @import("builtin"); const std = @import("std"); const utils = @import("../utils.zig"); const apputils = @import("./utils.zig"); const State = @import("./State.zig"); const Item = @import("../fs/Item.zig"); const ascii = std.ascii; const log = std.log.scoped(.actions); pub fn moveCursorUp(state: *State) void { state.view.cursor -|= 1; } pub fn moveCursorDown(state: *State) void { state.view.cursor += 1; } pub fn goToTop(state: *State) void { state.view.cursor = 0; } pub fn goToBottom(state: *State) !void { while (state.iterator.?.next()) |e| { try state.view.buffer.append(e); } state.view.cursor = state.view.buffer.items.len - 1; } pub fn shiftIntoParent(state: *State) !void { const item = state.getItemUnderCursor(); if (item._parent) |parent| { state.view.cursor = state.getItemIndex(parent) catch |err| switch (err) { error.NotFound => state.view.cursor, else => return err, }; } // Cursor is at current root will have to expand parent. else if (try state.manager.up()) |_| { state.view.cursor = 0; state.reiterate = true; } } pub fn shiftIntoChild(state: *State) !void { const item = state.getItemUnderCursor(); if (item.hasChildren()) { state.reiterate = true; } else { state.reiterate = try apputils.toggleItemChildren(item); } if (!state.reiterate) { return; } state.view.cursor += 1; } pub fn toggleChildrenOrOpenFile(state: *State) !void { const item = state.getItemUnderCursor(); if (try item.isDir()) { state.reiterate = try apputils.toggleItemChildren(item); return; } try openItem(state); } pub fn expandAll(state: *State) void { state.itermode = -1; state.reiterate = true; } pub fn collapseAll(state: *State) void { state.manager.root.freeChildren(null); state.view.cursor = 0; state.reiterate = true; } pub fn expandToDepth(state: *State, itermode: i32) void { state.itermode = itermode; state.reiterate = true; } pub fn changeRoot(state: *State) !void { var new_root = state.getItemUnderCursor(); if (!try new_root.isDir()) { new_root = try new_root.parent(); } if (new_root == state.manager.root) { return; } _ = try new_root.children(); state.manager.changeRoot(new_root); state.view.cursor = 0; state.reiterate = true; } pub fn toPrevFold(state: *State) void { const entry = state.getEntryUnderCursor(); const item = entry.item; const initial = state.view.cursor; var i: usize = (state.getItemIndex(item) catch return) -| 1; while (i > 0) : (i = i - 1) { const possible_sibling = state.view.buffer.items[i]; state.view.cursor = i; if (possible_sibling.depth != entry.depth) { break; } } if (state.view.cursor != initial) { return; } state.view.cursor = initial -| 1; } pub fn toNextFold(state: *State) !void { const entry = state.getEntryUnderCursor(); const item = entry.item; const initial = state.view.cursor; var i: usize = (state.getItemIndex(item) catch return) + 1; while (i < state.view.buffer.items.len) : (i = i + 1) { state.view.cursor = i; const possible_sibling = state.view.buffer.items[i]; if (possible_sibling.depth != entry.depth) { break; } if (i == (state.view.buffer.items.len - 1) and !(try state.appendOne())) { break; } } if (state.view.cursor != initial or state.view.buffer.items.len > initial + 1) { return; } state.view.cursor = initial + 1; } pub fn openItem(state: *State) !void { const item = state.getItemUnderCursor(); try utils.os.open(item.abspath()); } pub fn toggleInfo(state: *State) void { state.output.treeview.info.show = !state.output.treeview.info.show; state.view.print_all = true; } pub fn toggleSize(state: *State) void { state.output.treeview.info.size = !state.output.treeview.info.size; state.view.print_all = true; } pub fn togglePerm(state: *State) void { state.output.treeview.info.perm = !state.output.treeview.info.perm; state.view.print_all = true; } pub fn toggleIcons(state: *State) void { state.output.treeview.info.icons = !state.output.treeview.info.icons; state.view.print_all = true; } pub fn toggleTime(state: *State) void { state.output.treeview.info.time = !state.output.treeview.info.time; state.view.print_all = true; } pub fn timeModified(state: *State) void { state.output.treeview.info.time = true; state.output.treeview.info.accessed = false; state.output.treeview.info.modified = true; state.output.treeview.info.changed = false; state.view.print_all = true; } pub fn timeChanged(state: *State) void { state.output.treeview.info.time = true; state.output.treeview.info.accessed = false; state.output.treeview.info.modified = false; state.output.treeview.info.changed = true; state.view.print_all = true; } pub fn timeAccessed(state: *State) void { state.output.treeview.info.time = true; state.output.treeview.info.accessed = true; state.output.treeview.info.modified = false; state.output.treeview.info.changed = false; state.view.print_all = true; } pub fn changeDir(state: *State) !void { // Handled by shell line editing widget const item = state.getItemUnderCursor(); if (!(try item.isDir())) { return; } try state.stdout.appendSlice("cd\n"); try state.stdout.appendSlice(item.abspath()); try state.stdout.appendSlice("\n"); } pub fn search(state: *State) void { state.pre_search_cursor = state.view.cursor; state.input.search.start(); } pub fn execSearch(state: *State) !void { // Updates cursor w.r.t search query. var index: usize = 0; while (true) { defer index += 1; if (!(try state.appendUntil(index + 1))) { return; } if (!apputils.isMatch(state, index)) { continue; } state.view.cursor = index; return; } } pub fn acceptSearch(state: *State) !void { state.view.print_all = true; } pub fn dismissSearch(state: *State) void { state.view.cursor = state.pre_search_cursor; state.view.print_all = true; } pub fn command(state: *State) void { state.input.command.start(); } pub fn execCommand(state: *State) !void { // Handled by shell line editing widget for (state.input.command.string()) |c| { const char = if (ascii.isWhitespace(c)) '\n' else c; try state.stdout.append(char); } try state.stdout.appendSlice("\n"); var has_selection = false; for (state.view.buffer.items) |entry| { if (!entry.selected) continue; try state.stdout.appendSlice(entry.item.abspath()); try state.stdout.appendSlice("\n"); has_selection = true; } if (!has_selection) { const item = state.getItemUnderCursor(); try state.stdout.appendSlice(item.abspath()); try state.stdout.appendSlice("\n"); } log.info("execCommand: \"{s}\"", .{state.input.command.string()}); } pub fn dismissCommand(state: *State) void { state.view.print_all = true; } pub fn toggleSelection(state: *State) void { var entry = state.getEntryUnderCursor(); entry.selected = !entry.selected; log.debug("toggleSelection: selected={any}, {s}", .{ entry.selected, entry.item.name() }); }
https://raw.githubusercontent.com/18alantom/fex/e17853f3833391127863a30e35435af52da89a1e/app/actions.zig
const std = @import("std"); const Parser = @import("../Parser.zig"); pub const LispState = struct {}; pub const Type = union(enum(u32)) { Nil: void, // nil Char: void, // 'a' String: void, // "abc" Integer32: void, // (as i32 1) UInteger32: void, // (as u32 1) Boolean: void, // true, false List: Type, // [i32] Tuple: []Type, // (i32, f32) Function: struct { // (Fn :: (i32, i32) -> i32) args: []Type, ret: Type, }, }; pub const Expression = union(enum(u32)) { AtomI32: i32, // AtomU32: u32, // AtomF32: f32, // AtomIdentifier: []u8, // AtomTypeDefinition: Type, //AtomBoolean: bool, AtomList: []Expression, AtomSymbol: []u8, }; fn mapi32(allocator: std.mem.Allocator, str: []u8) anyerror!*Expression { const n = try allocator.create(Expression); n.* = .{ .AtomI32 = try std.fmt.parseInt(i32, str, 10), }; allocator.free(str); return n; } fn mapsymbol(allocator: std.mem.Allocator, str: []u8) anyerror!*Expression { const n = try allocator.create(Expression); n.* = .{ .AtomSymbol = str, }; return n; } pub fn atom_i32(stream: Parser.Stream, allocator: std.mem.Allocator, state: *Parser.BaseState) anyerror!Parser.Result(*Expression) { return Parser.map(stream, allocator, state, []u8, Parser.Language.integerString, *Expression, mapi32); } pub fn atom_symbol(stream: Parser.Stream, allocator: std.mem.Allocator, state: *Parser.BaseState) anyerror!Parser.Result(*Expression) { return Parser.map(stream, allocator, state, []u8, Parser.Language.identifier, *Expression, mapsymbol); } pub fn sexpr(stream: Parser.Stream, allocator: std.mem.Allocator, state: *Parser.BaseState) anyerror!Parser.Result(*Expression) { return Parser.Combinator.between( stream, allocator, state, .{ u8, *Expression, u8 }, .{ Parser.Char.symbol, .{'('} }, expr, .{ Parser.Char.symbol, .{')'} }, ); } pub fn expr(stream: Parser.Stream, allocator: std.mem.Allocator, state: *Parser.BaseState) anyerror!Parser.Result(*Expression) { return Parser.Combinator.choice(stream, allocator, state, *Expression, .{ atom_i32, atom_symbol, sexpr, }); }
https://raw.githubusercontent.com/QuentinTessier/ZigParsec/c8a00cc2ec8d67a875e3ce11f8b98ff2d90cafa8/src/examples/lisp.zig
const gl = @import("gl"); pub const ShaderError = error{ CompileError, LinkError, }; var error_buffer: [8192]u8 = undefined; var message: ?[]const u8 = null; pub fn getErrorMessage() []const u8 { if (message) |msg| { message = null; return msg; } else { @panic("no error message"); } } pub fn loadCompileErrorMessage(handle: gl.GLuint) void { if (message != null) { @panic("message must null"); } var size: gl.GLsizei = undefined; gl.getShaderInfoLog(handle, @intCast(c_int, error_buffer.len), &size, @ptrCast(*u8, &error_buffer[0])); message = error_buffer[0..@intCast(usize, size)]; } pub fn loadLinkErrorMessage(handle: gl.GLuint) void { if (message != null) { @panic("message must null"); } var size: gl.GLsizei = undefined; gl.getProgramInfoLog(handle, @intCast(c_int, error_buffer.len), &size, @ptrCast(*u8, &error_buffer[0])); message = error_buffer[0..@intCast(usize, size)]; }
https://raw.githubusercontent.com/ousttrue/zigsg/52ffe00bd9f078468331b964f878d11574db9eb4/zigsg/pkgs/glo/src/error_handling.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const backend = b.addStaticLibrary(.{ .name = "li8z", .root_source_file = b.path("src/backend.zig"), .target = target, .optimize = optimize, }); b.installArtifact(backend); const desktop_bin = b.addExecutable(.{ .name = "li8z", .root_source_file = b.path("src/desktop.zig"), .target = target, .optimize = optimize, }); const zaudio = b.dependency("zaudio", .{}); desktop_bin.root_module.addImport("zaudio", zaudio.module("root")); desktop_bin.linkLibrary(zaudio.artifact("miniaudio")); desktop_bin.addIncludePath(.{ .cwd_relative = ".packages/raylib/zig-out/include", }); desktop_bin.addObjectFile(.{ .cwd_relative = ".packages/raylib/zig-out/lib/libraylib.a" }); desktop_bin.linkLibC(); b.installArtifact(desktop_bin); const run_cmd = b.addRunArtifact(desktop_bin); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const lib_unit_tests = b.addTest(.{ .root_source_file = b.path("src/backend.zig"), .target = target, .optimize = optimize, }); const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const exe_unit_tests = b.addTest(.{ .root_source_file = b.path("src/desktop.zig"), .target = target, .optimize = optimize, }); const run_exe_unit_tests = b.addRunArtifact(exe_unit_tests); const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_lib_unit_tests.step); test_step.dependOn(&run_exe_unit_tests.step); }
https://raw.githubusercontent.com/Kapongoboy/li8z/2e96227e4089a86d1da0948698fe1a3c9e42922c/build.zig
const std = @import("std"); const root = @import("root"); const rl = @import("raylib"); const ecs = @import("../ecs/ecs.zig"); const simulation = @import("../simulation.zig"); const render = @import("../render.zig"); const input = @import("../input.zig"); const AssetManager = @import("../AssetManager.zig"); const Invariables = @import("../Invariables.zig"); const Animation = @import("../animation/animations.zig").Animation; const animator = @import("../animation/animator.zig"); const constants = @import("../constants.zig"); const movement = @import("../physics/movement.zig"); const collision = @import("../physics/collision.zig"); const Vec2 = ecs.component.Vec2; const F32 = ecs.component.F32; const crown = @import("../crown.zig"); const AudioManager = @import("../AudioManager.zig"); const audio = @import("../audio.zig"); const obstacle_height_base = 7; const obstacle_height_delta = 6; const player_gravity = Vec2.init(0, F32.init(1, 10)); const player_boost = Vec2.init(0, F32.init(-1, 4)); const vertical_obstacle_velocity = Vec2.init(-5, 0); const horizontal_obstacle_velocity = Vec2.init(-8, 0); const ObstacleKind = enum { ObstacleUpper, ObstacleLower, ObstacleBoth }; const background_layers = [_][]const u8{ "assets/sky_background_0.png", "assets/sky_background_1.png", "assets/sky_background_2.png", }; const background_scroll = [_]i16{ -1, -2, -3 }; fn spawnBackground(world: *ecs.world.World) !void { const n = @min(background_layers.len, background_scroll.len); for (0..n) |i| { for (0..2) |ix| { _ = try world.spawnWith(.{ ecs.component.Tex{ .texture_hash = AssetManager.pathHash(background_layers[i]), .w = constants.world_width_tiles, .h = constants.world_height_tiles, }, ecs.component.Pos{ .pos = .{ @intCast(constants.world_width * ix), 0 } }, ecs.component.Mov{ .velocity = Vec2.init(background_scroll[i], 0), }, }); } } } pub fn init(sim: *simulation.Simulation, timeline: input.Timeline) !void { _ = try spawnBackground(&sim.world); const rand = sim.meta.minigame_prng.random(); for (timeline.latest(), 0..) |inp, id| { if (inp.is_connected()) { try spawnPlayer(&sim.world, rand, @intCast(id)); } } try crown.init(sim, .{ 0, -16 }); } pub fn update(sim: *simulation.Simulation, inputs: input.Timeline, invar: Invariables) !void { sim.meta.minigame_timer += 1; audio.update(&sim.world); const alive = countAlivePlayers(&sim.world); if (alive <= 1) { var query = sim.world.query(&.{ ecs.component.Plr, }, &.{}); while (query.next()) |_| { const plr = try query.get(ecs.component.Plr); sim.meta.minigame_placements[plr.id] = alive - 1; } sim.meta.minigame_id = constants.minigame_scoreboard; return; } try jetpackSystem(sim, inputs.latest()); const rand = sim.meta.minigame_prng.random(); var collisions = collision.CollisionQueue.init(invar.arena) catch @panic("could not initialize collision queue"); movement.update(&sim.world, &collisions, invar.arena) catch @panic("movement system failed"); try collisionSystem(&sim.world); try pushSystem(&sim.world, &collisions); try spawnSystem(&sim.world, rand, sim.meta.minigame_timer); try deathSystem(sim, &collisions, alive); try scrollSystem(&sim.world); try particleSystem(&sim.world); animator.update(&sim.world); try crown.update(sim); } fn countAlivePlayers(world: *ecs.world.World) u32 { var count: u32 = 0; var query = world.query(&.{ ecs.component.Plr, ecs.component.Pos }, &.{}); while (query.next()) |_| { count += 1; } return count; } /// Scroll background fn scrollSystem(world: *ecs.world.World) !void { var query = world.query(&.{ecs.component.Pos}, &.{ecs.component.Col}); while (query.next()) |_| { const pos = try query.get(ecs.component.Pos); if (pos.pos[0] + constants.world_width <= 4) { // +4 to hide visible seams pos.pos[0] = constants.world_width; } } } fn collisionSystem(world: *ecs.world.World) !void { var query = world.query(&.{ ecs.component.Plr, ecs.component.Col, ecs.component.Pos, ecs.component.Mov }, &.{}); while (query.next()) |_| { const pos = try query.get(ecs.component.Pos); const mov = try query.get(ecs.component.Mov); const col = try query.get(ecs.component.Col); if (pos.pos[1] < 0) { mov.velocity.vector[1] = 0; pos.pos[1] = 0; } else if (pos.pos[1] + col.dim[1] > constants.world_height) { mov.velocity.vector[1] = 0; pos.pos[1] = constants.world_height - col.dim[1]; } } } fn pushSystem(world: *ecs.world.World, _: *collision.CollisionQueue) !void { var query = world.query(&.{ ecs.component.Plr, ecs.component.Col, ecs.component.Pos, ecs.component.Mov }, &.{}); while (query.next()) |_| { var pos = try query.get(ecs.component.Pos); const col = try query.get(ecs.component.Col); var obst_query = world.query(&.{ ecs.component.Col, ecs.component.Pos, ecs.component.Mov }, &.{ecs.component.Plr}); while (obst_query.next()) |_| { const obst_pos = try obst_query.get(ecs.component.Pos); const obst_col = try obst_query.get(ecs.component.Col); const obst_mov = try obst_query.get(ecs.component.Mov); if (collision.intersectsAt(pos, col, obst_pos, obst_col, [_]i32{ 1, 0 })) { pos.pos[0] += obst_mov.velocity.x().toInt(); } } } } fn jetpackSystem(sim: *simulation.Simulation, inputs: input.AllPlayerButtons) !void { var query = sim.world.query(&.{ ecs.component.Mov, ecs.component.Plr, ecs.component.Pos }, &.{}); while (query.next()) |_| { const plr = try query.get(ecs.component.Plr); const mov = try query.get(ecs.component.Mov); const pos = try query.get(ecs.component.Pos); const state = inputs[plr.id]; if (state.is_connected()) { if (state.vertical() > 0) { mov.velocity = mov.velocity.add(player_boost); try spawnSmokeParticles(sim, pos.pos); } } } } fn spawnSmokeParticles(sim: *simulation.Simulation, pos: @Vector(2, i32)) !void { if (sim.meta.minigame_timer % 3 != 0) return; _ = try sim.world.spawnWith(.{ ecs.component.Pos{ .pos = pos }, ecs.component.Tex{ .texture_hash = AssetManager.pathHash("assets/smash_jump_smoke.png"), .w = 2, .h = 2, .subpos = .{ -12, 8 }, .flip_vertical = true, }, ecs.component.Anm{ .animation = Animation.SmashAttackSmoke, .interval = 2, .looping = true, }, ecs.component.Tmr{ .ticks = 8 }, // lifetime ecs.component.Src{}, ecs.component.Snd{ .sound_hash = comptime AudioManager.path_to_key("assets/audio/whoosh.wav") }, }); } fn particleSystem( world: *ecs.world.World, ) !void { var query = world.query(&.{ ecs.component.Pos, ecs.component.Tex, ecs.component.Anm, ecs.component.Tmr, ecs.component.Src, }, &.{}); while (query.next()) |entity| { var tmr = try query.get(ecs.component.Tmr); if (tmr.ticks == 0) { world.kill(entity); } else { tmr.ticks -= 1; } } } fn spawnDeathParticles(sim: *simulation.Simulation, pos: @Vector(2, i32)) !void { _ = try sim.world.spawnWith(.{ ecs.component.Pos{ .pos = pos }, ecs.component.Tex{ .texture_hash = AssetManager.pathHash("assets/smash_attack_smoke.png"), .w = 2, .h = 2, }, ecs.component.Anm{ .animation = Animation.SmashAttackSmoke, .interval = 8, .looping = false, }, ecs.component.Snd{ .sound_hash = comptime AudioManager.path_to_key("assets/audio/death.wav") }, }); } fn deathSystem(sim: *simulation.Simulation, _: *collision.CollisionQueue, alive: u64) !void { var query = sim.world.query(&.{ ecs.component.Pos, ecs.component.Col }, &.{}); while (query.next()) |entity| { const col = try query.get(ecs.component.Col); const pos = try query.get(ecs.component.Pos); const right = pos.pos[0] + col.dim[0]; if (right < 0) { if (sim.world.checkSignature(entity, &.{ecs.component.Plr}, &.{})) { try spawnDeathParticles(sim, pos.pos); const plr = try sim.world.inspect(entity, ecs.component.Plr); const id = plr.id; const place = @as(u32, @intCast(alive - 1)); sim.meta.minigame_placements[id] = place; } sim.world.kill(entity); } } } fn spawnSystem(world: *ecs.world.World, rand: std.Random, ticks: u64) !void { if (ticks % @max(20, (80 -| (ticks / 160))) == 0) { spawnRandomObstacle(world, rand); } if (ticks % @max(10, (60 -| (ticks / 120))) == 0) { spawnHorizontalObstacle(world, rand); } } fn spawnVerticalObstacleUpper(world: *ecs.world.World, length: u32) void { _ = world.spawnWith(.{ ecs.component.Pos{ .pos = .{ constants.world_width, 0 } }, ecs.component.Col{ .dim = .{ 1 * constants.asset_resolution, constants.asset_resolution * @as(i32, @intCast(length)) }, .layer = collision.Layer{ .base = true, .pushing = true }, .mask = collision.Layer{ .base = false, .player = true }, }, ecs.component.Mov{ .velocity = vertical_obstacle_velocity }, ecs.component.Tex{ .texture_hash = AssetManager.pathHash("assets/error.png"), .w = 1, .h = length, }, }) catch unreachable; } fn spawnVerticalObstacleLower(world: *ecs.world.World, length: u32) void { _ = world.spawnWith(.{ ecs.component.Pos{ .pos = .{ constants.world_width, constants.world_height - @as(i32, @intCast(length)) * constants.asset_resolution } }, ecs.component.Col{ .dim = .{ constants.asset_resolution, constants.asset_resolution * @as(i32, @intCast(length)) }, .layer = collision.Layer{ .base = true }, .mask = collision.Layer{ .base = false, .player = true }, }, ecs.component.Mov{ .velocity = vertical_obstacle_velocity }, ecs.component.Tex{ .texture_hash = AssetManager.pathHash("assets/error.png"), .w = 1, .h = length, }, }) catch unreachable; } fn spawnVerticalObstacleBoth(world: *ecs.world.World, delta: i32) void { spawnVerticalObstacleUpper(world, @intCast(@divTrunc(constants.world_height_tiles - delta, 2))); spawnVerticalObstacleLower(world, @intCast(@divTrunc(constants.world_height_tiles - delta, 2))); } pub fn spawnRandomObstacle(world: *ecs.world.World, rand: std.Random) void { const kind = std.Random.enumValue(rand, ObstacleKind); switch (kind) { ObstacleKind.ObstacleLower => { const length = std.Random.intRangeAtMost(rand, u32, 7, constants.world_height_tiles - 5); spawnVerticalObstacleLower(world, length); }, ObstacleKind.ObstacleUpper => { const length = std.Random.intRangeAtMost(rand, u32, 7, constants.world_height_tiles - 5); spawnVerticalObstacleUpper(world, length); }, ObstacleKind.ObstacleBoth => { const delta = std.Random.intRangeAtMost(rand, i32, 4, 8); spawnVerticalObstacleBoth(world, delta); }, } } fn spawnHorizontalObstacle(world: *ecs.world.World, rand: std.Random) void { _ = world.spawnWith(.{ ecs.component.Pos{ .pos = .{ constants.world_width, std.Random.intRangeLessThan(rand, i32, 0, constants.world_height), }, }, ecs.component.Tex{ .texture_hash = AssetManager.pathHash("assets/error.png"), .u = 0, .v = 0, .w = 3, .h = 1, }, ecs.component.Mov{ .velocity = horizontal_obstacle_velocity, }, ecs.component.Col{ .dim = .{ 3 * constants.asset_resolution, constants.asset_resolution }, .layer = .{ .base = true, .pushing = true }, .mask = .{ .base = false, .player = true }, }, }) catch unreachable; } fn spawnPlayer(world: *ecs.world.World, rand: std.Random, id: u32) !void { _ = try world.spawnWith(.{ ecs.component.Plr{ .id = @intCast(id) }, ecs.component.Pos{ .pos = .{ std.Random.intRangeAtMost(rand, i32, 64, 112), @divTrunc(constants.world_height, 2) } }, ecs.component.Mov{ .acceleration = player_gravity, }, ecs.component.Col{ .dim = .{ 12, 10 }, .layer = collision.Layer{ .base = false, .player = true }, .mask = collision.Layer{ .base = false, .player = false, .pushing = true }, }, ecs.component.Tex{ .w = 2, .h = 1, .subpos = .{ -18, -6 }, .texture_hash = AssetManager.pathHash("assets/smash_cat.png"), .tint = constants.player_colors[id], }, ecs.component.Anm{ .animation = Animation.HnsFly, .interval = 10, .looping = true }, // ecs.component.Dbg{}, }); }
https://raw.githubusercontent.com/INDA23PlusPlus/plusplusparty/15ed55659234db31b2db7c4f1ab1ee2e8704084e/src/minigames/hot_n_steamy.zig
const std = @import("std"); const vk = @import("vulkan"); const core = @import("core"); const VkConstants = @import("vk_constants.zig"); const meshes = @import("mesh.zig"); const NeonVkContext = @import("vk_renderer.zig").NeonVkContext; const vk_pipeline = @import("vk_pipeline.zig"); const NeonVkPipelineBuilder = vk_pipeline.NeonVkPipelineBuilder; const EulerAngles = core.EulerAngles; const Mat = core.Mat; const Vectorf = core.Vectorf; const Quat = core.Quat; const zm = core.zm; const mul = zm.mul; pub const Material = struct { materialName: core.Name, textureSet: vk.DescriptorSet = .null_handle, pipeline: vk.Pipeline, layout: vk.PipelineLayout, pub fn deinit(self: *Material, ctx: *NeonVkContext) void { ctx.vkd.destroyPipeline(ctx.dev, self.pipeline, null); ctx.vkAllocator.destroyPipelineLayout(ctx.dev, self.layout); } }; pub const MaterialBuilder = struct { const Self = @This(); allocator: std.mem.Allocator, ctx: *NeonVkContext, pipelineBuilder: NeonVkPipelineBuilder, pub fn init(ctx: *NeonVkContext) MaterialBuilder { const self = MaterialBuilder{ .allocator = ctx.allocator, .ctx = ctx, }; return self; } pub fn build(self: *Self) !void { _ = self; // try self.ctx.add_material(); } pub fn deinit(self: *Self) void { _ = self; } };
https://raw.githubusercontent.com/peterino2/NeonWood/705a04e06aa60736e0af02ad00cd0d4c37f07921/engine/graphics/src/materials.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) 2004-2021 by Embedded and Real-Time Systems Laboratory /// Graduate School of Information Science, Nagoya Univ., JAPAN /// /// 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ /// ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改 /// 変・再配布(以下,利用と呼ぶ)することを無償で許諾する. /// (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作 /// 権表示,この利用条件および下記の無保証規定が,そのままの形でソー /// スコード中に含まれていること. /// (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使 /// 用できる形で再配布する場合には,再配布に伴うドキュメント(利用 /// 者マニュアルなど)に,上記の著作権表示,この利用条件および下記 /// の無保証規定を掲載すること. /// (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使 /// 用できない形で再配布する場合には,次のいずれかの条件を満たすこ /// と. /// (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著 /// 作権表示,この利用条件および下記の無保証規定を掲載すること. /// (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに /// 報告すること. /// (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損 /// 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること. /// また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理 /// 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを /// 免責すること. /// /// 本ソフトウェアは,無保証で提供されているものである.上記著作権者お /// よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的 /// に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ /// アの利用により直接的または間接的に生じたいかなる損害に関しても,そ /// の責任を負わない. /// /// $Id$ /// /// /// サンプルプログラム(1)の本体 /// /// ASPカーネルの基本的な動作を確認するためのサンプルプログラム.サン /// プルプログラム本体とコンフィギュレーション記述を,1つのZigファイ /// ルに記述する(★まだそうなっていない). /// /// プログラムの概要: /// /// ユーザインタフェースを受け持つメインタスク(MAIN_TASK)と,3つの並 /// 行実行されるタスク(TASK1〜TASK3),例外処理タスク(EXC_TASK)の5 /// つのタスクを用いる.これらの他に,システムログタスクが動作する.ま /// た,周期ハンドラ,アラームハンドラ,割込みサービスルーチン,CPU例 /// 外ハンドラ,オーバランハンドラをそれぞれ1つ用いる. /// /// 並行実行されるタスクは,task_loop回のループを実行する度に,タスク /// が実行中であることをあらわすメッセージを表示する.ループを実行する /// のは,プログラムの動作を確認しやすくするためである.また,低速なシ /// リアルポートを用いてメッセージを出力する場合に,すべてのメッセージ /// が出力できるように,メッセージの量を制限するという理由もある. /// /// 周期ハンドラ,アラームハンドラ,割込みサービスルーチンは,3つの優 /// 先度(HIGH_PRIORITY,MID_PRIORITY,LOW_PRIORITY)のレディキューを /// 回転させる.周期ハンドラは,プログラムの起動直後は停止状態になって /// いる. /// /// CPU例外ハンドラは,CPU例外からの復帰が可能な場合には,例外処理タス /// クを起動する.例外処理タスクは,CPU例外を起こしたタスクに対して, /// 終了要求を行う. /// /// メインタスクは,シリアルポートからの文字入力を行い(文字入力を待っ /// ている間は,並行実行されるタスクが実行されている),入力された文字 /// に対応した処理を実行する.入力された文字と処理の関係は次の通り. /// Control-Cまたは'Q'が入力されると,プログラムを終了する. /// /// '1' : 対象タスクをTASK1に切り換える(初期設定). /// '2' : 対象タスクをTASK2に切り換える. /// '3' : 対象タスクをTASK3に切り換える. /// 'a' : 対象タスクをact_tskにより起動する. /// 'A' : 対象タスクに対する起動要求をcan_actによりキャンセルする. /// 'e' : 対象タスクにext_tskを呼び出させ,終了させる. /// 't' : 対象タスクをter_tskにより強制終了する. /// '>' : 対象タスクの優先度をHIGH_PRIORITYにする. /// '=' : 対象タスクの優先度をMID_PRIORITYにする. /// '<' : 対象タスクの優先度をLOW_PRIORITYにする. /// 'G' : 対象タスクの優先度をget_priで読み出す. /// 's' : 対象タスクにslp_tskを呼び出させ,起床待ちにさせる. /// 'S' : 対象タスクにtslp_tsk(10秒)を呼び出させ,起床待ちにさせる. /// 'w' : 対象タスクをwup_tskにより起床する. /// 'W' : 対象タスクに対する起床要求をcan_wupによりキャンセルする. /// 'l' : 対象タスクをrel_waiにより強制的に待ち解除にする. /// 'u' : 対象タスクをsus_tskにより強制待ち状態にする. /// 'm' : 対象タスクの強制待ち状態をrsm_tskにより解除する. /// 'd' : 対象タスクにdly_tsk(10秒)を呼び出させ,時間経過待ちにさせる. /// 'x' : 対象タスクにras_terにより終了要求する. /// 'y' : 対象タスクにdis_terを呼び出させ,タスク終了を禁止する. /// 'Y' : 対象タスクにena_terを呼び出させ,タスク終了を許可する. /// 'r' : 3つの優先度(HIGH_PRIORITY,MID_PRIORITY,LOW_PRIORITY)のレ /// ディキューを回転させる. /// 'c' : 周期ハンドラを動作開始させる. /// 'C' : 周期ハンドラを動作停止させる. /// 'b' : アラームハンドラを5秒後に起動するよう動作開始させる. /// 'B' : アラームハンドラを動作停止させる. /// 'z' : 対象タスクにCPU例外を発生させる(ターゲットによっては復帰可能). /// 'Z' : 対象タスクにCPUロック状態でCPU例外を発生させる(復帰不可能). /// 'V' : 短いループを挟んで,fch_hrtで高分解能タイマを2回読む. /// 'o' : 対象タスクに対してオーバランハンドラを動作開始させる. /// 'O' : 対象タスクに対してオーバランハンドラを動作停止させる. /// 'v' : 発行したシステムコールを表示する(デフォルト). /// 'q' : 発行したシステムコールを表示しない. /// /// /// 使用するカーネルおよびライブラリ /// usingnamespace @import("../include/kernel.zig"); usingnamespace @import("../include/t_syslog.zig"); /// /// コンフィギュレーションオプションの取り込み /// pub const option = @import("../include/option.zig"); /// /// C言語ヘッダファイルの取り込み /// const c = @cImport({ @cDefine("UINT_C(val)", "val"); @cDefine("ULONG_C(val)", "val"); @cInclude("sample3.h"); @cInclude("include/t_stdlib.h"); @cInclude("syssvc/serial.h"); @cInclude("syssvc/syslog.h"); }); //#include "kernel_cfg.h" extern const TASK1: ID; extern const TASK2: ID; extern const TASK3: ID; extern const EXC_TASK: ID; extern const CYCHDR1: ID; extern const ALMHDR1: ID; /// /// サービスコールのエラーのログ出力 /// fn svc_perror(ercd: ER) void { if (ercd < 0) { syslog(LOG_ERROR, "%s (%d) reported.", .{ c.itron_strerror(ercd), SERCD(ercd) }); } } /// /// プロセッサ時間の消費 /// /// ループによりプロセッサ時間を消費する.最適化ができないように,ルー /// プ内でvolatile変数を読み込む. /// var volatile_var: u32 = undefined; noinline fn consume_time(ctime: u32) void { var i: u32 = 0; while (i < ctime) : (i += 1) { const dummy = @ptrCast(*volatile u32, &volatile_var).*; } } /// /// 並行実行されるタスクへのメッセージ領域 /// var message = [_]u8{ 0, 0, 0, }; /// /// ループ回数 /// var task_loop: u32 = undefined; // タスク内でのループ回数 /// /// タスクの表示用文字列 /// const graph = [3][]const u8{ "| ", " + ", " *", }; /// /// 並行実行されるタスク /// export fn task(exinf: EXINF) void { var n: u32 = 0; var tskno: u32 = @intCast(u32, @ptrToInt(exinf)); var ch: u8 = undefined; var pk_rovr: if (TOPPERS_SUPPORT_OVRHDR) T_ROVR else void = undefined; while (true) { n += 1; if (TOPPERS_SUPPORT_OVRHDR) { svc_perror(c.ref_ovr(TSK_SELF, &pk_rovr)); if ((pk_rovr.ovrstat & TOVR_STA) != 0) { syslog(LOG_NOTICE, "task%d is running (%03d). %s [%ld]", .{ tskno, n, graph[tskno-1], pk_rovr.leftotm }); } else { syslog(LOG_NOTICE, "task%d is running (%03d). %s", .{ tskno, n, graph[tskno-1]}); } } else { syslog(LOG_NOTICE, "task%d is running (%03d). %s", .{ tskno, n, graph[tskno-1] }); } consume_time(task_loop); ch = message[tskno-1]; message[tskno-1] = 0; switch (ch) { 'e' => { syslog(LOG_INFO, "#%d#ext_tsk()", .{ tskno }); svc_perror(c.ext_tsk()); assert(false); }, 's' => { syslog(LOG_INFO, "#%d#slp_tsk()", .{ tskno }); svc_perror(c.slp_tsk()); }, 'S' => { syslog(LOG_INFO, "#%d#tslp_tsk(10_000_000)", .{ tskno }); svc_perror(c.tslp_tsk(10_000_000)); }, 'd' => { syslog(LOG_INFO, "#%d#dly_tsk(10_000_000)", .{ tskno }); svc_perror(c.dly_tsk(10_000_000)); }, 'y' => { syslog(LOG_INFO, "#%d#dis_ter()", .{ tskno }); svc_perror(c.dis_ter()); }, 'Y' => { syslog(LOG_INFO, "#%d#ena_ter()", .{ tskno }); svc_perror(c.ena_ter()); }, 'z' => { if (@hasDecl(option.target._test, "CPUEXC1")) { syslog(LOG_NOTICE, "#%d#raise CPU exception", .{ tskno }); option.target._test.raiseCpuException(); } else { syslog(LOG_NOTICE, "CPU exception is not supported.", .{}); } }, 'Z' => { if (@hasDecl(option.target._test, "CPUEXC1")) { svc_perror(c.loc_cpu()); syslog(LOG_NOTICE, "#%d#raise CPU exception", .{ tskno }); option.target._test.raiseCpuException(); svc_perror(c.unl_cpu()); } else { syslog(LOG_NOTICE, "CPU exception is not supported.", .{}); } }, else => {}, } } } /// /// 割込みサービスルーチン /// /// HIGH_PRIORITY,MID_PRIORITY,LOW_PRIORITY の各優先度のレディキュー /// を回転させる. /// export fn intno1_isr(exinf: EXINF) void { if (@hasDecl(option.target._test, "INTNO1")) { option.target._test.intno1_clear(); svc_perror(c.rot_rdq(c.HIGH_PRIORITY)); svc_perror(c.rot_rdq(c.MID_PRIORITY)); svc_perror(c.rot_rdq(c.LOW_PRIORITY)); } } /// /// CPU例外ハンドラ /// var cpuexc_tskid: ID = undefined; // CPU例外を起こしたタスクのID // export fn cpuexc_handler(p_excinf: *c_void) void { syslog(LOG_NOTICE, "CPU exception handler (p_excinf = %08p).", .{ p_excinf }); if (c.sns_ctx() == 0) { syslog(LOG_WARNING, "sns_ctx() is not true in CPU exception handler.", .{}); } if (c.sns_dpn() == 0) { syslog(LOG_WARNING, "sns_dpn() is not true in CPU exception handler.", .{}); } syslog(LOG_INFO, "sns_loc = %d, sns_dsp = %d, xsns_dpn = %d", .{ c.sns_loc(), c.sns_dsp(), c.xsns_dpn(p_excinf) }); if (c.xsns_dpn(p_excinf) != 0) { syslog(LOG_NOTICE, "Sample program ends with exception.", .{}); svc_perror(c.ext_ker()); assert(false); } svc_perror(c.get_tid(&cpuexc_tskid)); svc_perror(c.act_tsk(EXC_TASK)); } /// /// 周期ハンドラ /// /// HIGH_PRIORITY,MID_PRIORITY,LOW_PRIORITY の各優先度のレディキュー /// を回転させる. /// export fn cyclic_handler(exinf: EXINF) void { svc_perror(c.rot_rdq(c.HIGH_PRIORITY)); svc_perror(c.rot_rdq(c.MID_PRIORITY)); svc_perror(c.rot_rdq(c.LOW_PRIORITY)); } /// /// アラームハンドラ /// /// HIGH_PRIORITY,MID_PRIORITY,LOW_PRIORITY の各優先度のレディキュー /// を回転させる. /// export fn alarm_handler(exinf: EXINF) void { svc_perror(c.rot_rdq(c.HIGH_PRIORITY)); svc_perror(c.rot_rdq(c.MID_PRIORITY)); svc_perror(c.rot_rdq(c.LOW_PRIORITY)); } /// /// 例外処理タスク /// export fn exc_task(exinf: EXINF) void { svc_perror(c.ras_ter(cpuexc_tskid)); } /// /// オーバランハンドラ /// export fn overrun_handler(tskid: ID, exinf: EXINF) void { const tskno = @intCast(u32, @ptrToInt(exinf)); syslog(LOG_NOTICE, "Overrun handler for task%d.", .{ tskno }); } /// /// メインタスク /// export fn main_task(exinf: EXINF) void { var ch: u8 = 0; var tskid: ID = TASK1; var tskno: u32 = 1; var ercd: ER_UINT = undefined; var tskpri: PRI = undefined; var stime1: SYSTIM = undefined; var stime2: SYSTIM = undefined; var hrtcnt1: HRTCNT = undefined; var hrtcnt2: HRTCNT = undefined; svc_perror(c.syslog_msk_log(c.LOG_UPTO(LOG_INFO), c.LOG_UPTO(LOG_EMERG))); syslog(LOG_NOTICE, "Sample program starts (exinf = %d).", .{ exinf }); // // シリアルポートの初期化 // // システムログタスクと同じシリアルポートを使う場合など,シリア // ルポートがオープン済みの場合にはここでE_OBJエラーになるが,支 // 障はない. // ercd = c.serial_opn_por(c.TASK_PORTID); if (ercd < 0 and MERCD(ercd) != c.E_OBJ) { syslog(LOG_ERROR, "%s (%d) reported by `serial_opn_por'.", .{ c.itron_strerror(ercd), SERCD(ercd) }); } svc_perror(c.serial_ctl_por(c.TASK_PORTID, (c.IOCTL_CRLF|c.IOCTL_FCSND|c.IOCTL_FCRCV))); // // ループ回数の設定 // // 並行実行されるタスク内でのループの回数(task_loop)は,ループ // の実行時間が約0.4秒になるように設定する.この設定のために, // LOOP_REF回のループの実行時間を,その前後でget_timを呼ぶことで // 測定し,その測定結果から空ループの実行時間が0.4秒になるループ // 回数を求め,task_loopに設定する. // // LOOP_REFは,デフォルトでは1,000,000に設定しているが,想定した // より遅いプロセッサでは,サンプルプログラムの実行開始に時間がか // かりすぎるという問題を生じる.逆に想定したより速いプロセッサで // は,LOOP_REF回のループの実行時間が短くなり,task_loopに設定す // る値の誤差が大きくなるという問題がある.そこで,そのようなター // ゲットでは,target_test.hで,LOOP_REFを適切な値に定義すること // とする. // // また,task_loopの値を固定したい場合には,その値をTASK_LOOPにマ // クロ定義する.TASK_LOOPがマクロ定義されている場合,上記の測定 // を行わずに,TASK_LOOPに定義された値をループの回数とする. // // ターゲットによっては,ループの実行時間の1回目の測定で,本来より // も長めになるものがある.このようなターゲットでは,MEASURE_TWICE // をマクロ定義することで,1回目の測定結果を捨てて,2回目の測定結 // 果を使う. // if (@hasDecl(@This(), "TASK_LOOP")) { task_loop = TASK_LOOP; } else { if (@hasDecl(@This(), "MEASURE_TWICE")) { svc_perror(c.get_tim(&stime1)); consume_time(c.LOOP_REF); svc_perror(c.get_tim(&stime2)); } svc_perror(c.get_tim(&stime1)); consume_time(c.LOOP_REF); svc_perror(c.get_tim(&stime2)); task_loop = @as(u32, c.LOOP_REF * 400) / @intCast(u32, stime2 - stime1) * 1000; } // // タスクの起動 // svc_perror(c.act_tsk(TASK1)); svc_perror(c.act_tsk(TASK2)); svc_perror(c.act_tsk(TASK3)); // // メインループ // while (ch != '\x03' and ch != 'Q') { svc_perror(c.serial_rea_dat(c.TASK_PORTID, &ch, 1)); switch (ch) { 'e', 's', 'S', 'd', 'y', 'Y', 'z', 'Z' => { message[tskno-1] = ch; }, '1' => { tskno = 1; tskid = TASK1; }, '2' => { tskno = 2; tskid = TASK2; }, '3' => { tskno = 3; tskid = TASK3; }, 'a' => { syslog(LOG_INFO, "#act_tsk(%d)", .{ tskno }); svc_perror(c.act_tsk(tskid)); }, 'A' => { syslog(LOG_INFO, "#can_act(%d)", .{ tskno }); ercd = c.can_act(tskid); svc_perror(ercd); if (ercd >= 0) { syslog(LOG_NOTICE, "can_act(%d) returns %d.", .{ tskno, ercd }); } }, 't' => { syslog(LOG_INFO, "#ter_tsk(%d)", .{ tskno }); svc_perror(c.ter_tsk(tskid)); }, '>' => { syslog(LOG_INFO, "#chg_pri(%d, HIGH_PRIORITY)", .{ tskno }); svc_perror(c.chg_pri(tskid, c.HIGH_PRIORITY)); }, '=' => { syslog(LOG_INFO, "#chg_pri(%d, MID_PRIORITY)", .{ tskno }); svc_perror(c.chg_pri(tskid, c.MID_PRIORITY)); }, '<' => { syslog(LOG_INFO, "#chg_pri(%d, LOW_PRIORITY)", .{ tskno }); svc_perror(c.chg_pri(tskid, c.LOW_PRIORITY)); }, 'G' => { syslog(LOG_INFO, "#get_pri(%d, &tskpri)", .{ tskno }); ercd = c.get_pri(tskid, &tskpri); svc_perror(ercd); if (ercd >= 0) { syslog(LOG_NOTICE, "priority of task %d is %d", .{ tskno, tskpri}); } }, 'w' => { syslog(LOG_INFO, "#wup_tsk(%d)", .{ tskno }); svc_perror(c.wup_tsk(tskid)); }, 'W' => { syslog(LOG_INFO, "#can_wup(%d)", .{ tskno }); ercd = c.can_wup(tskid); svc_perror(ercd); if (ercd >= 0) { syslog(LOG_NOTICE, "can_wup(%d) returns %d", .{ tskno, ercd }); } }, 'l' => { syslog(LOG_INFO, "#rel_wai(%d)", .{ tskno }); svc_perror(c.rel_wai(tskid)); }, 'u' => { syslog(LOG_INFO, "#sus_tsk(%d)", .{ tskno }); svc_perror(c.sus_tsk(tskid)); }, 'm' => { syslog(LOG_INFO, "#rsm_tsk(%d)", .{ tskno }); svc_perror(c.rsm_tsk(tskid)); }, 'x' => { syslog(LOG_INFO, "#ras_ter(%d)", .{ tskno }); svc_perror(c.ras_ter(tskid)); }, 'r' => { syslog(LOG_INFO, "#rot_rdq(three priorities)", .{}); svc_perror(c.rot_rdq(c.HIGH_PRIORITY)); svc_perror(c.rot_rdq(c.MID_PRIORITY)); svc_perror(c.rot_rdq(c.LOW_PRIORITY)); }, 'c' => { syslog(LOG_INFO, "#sta_cyc(CYCHDR1)", .{}); svc_perror(c.sta_cyc(CYCHDR1)); }, 'C' => { syslog(LOG_INFO, "#stp_cyc(CYCHDR1)", .{}); svc_perror(c.stp_cyc(CYCHDR1)); }, 'b' => { syslog(LOG_INFO, "#sta_alm(ALMHDR1, 5_000_000)", .{}); svc_perror(c.sta_alm(ALMHDR1, 5_000_000)); }, 'B' => { syslog(LOG_INFO, "#stp_alm(ALMHDR1)", .{}); svc_perror(c.stp_alm(ALMHDR1)); }, 'V' => { hrtcnt1 = c.fch_hrt(); consume_time(1000); hrtcnt2 = c.fch_hrt(); syslog(LOG_NOTICE, "hrtcnt1 = %tu, hrtcnt2 = %tu", .{ hrtcnt1, hrtcnt2 }); }, 'o' => { if (TOPPERS_SUPPORT_OVRHDR) { syslog(LOG_INFO, "#sta_ovr(%d, 2_000_000)", .{ tskno }); svc_perror(c.sta_ovr(tskid, 2_000_000)); } else { syslog(LOG_NOTICE, "sta_ovr is not supported.", .{}); } }, 'O' => { if (TOPPERS_SUPPORT_OVRHDR) { syslog(LOG_INFO, "#stp_ovr(%d)", .{ tskno }); svc_perror(c.stp_ovr(tskid)); } else { syslog(LOG_NOTICE, "stp_ovr is not supported.", .{}); } }, 'v' => { svc_perror(c.syslog_msk_log(c.LOG_UPTO(LOG_INFO), c.LOG_UPTO(LOG_EMERG))); }, 'q' => { svc_perror(c.syslog_msk_log(c.LOG_UPTO(LOG_NOTICE), c.LOG_UPTO(LOG_EMERG))); }, '\x03', 'Q' => {}, else => { syslog(LOG_INFO, "Unknown command: '%c'.", .{ ch }); }, } } syslog(LOG_NOTICE, "Sample program ends.", .{}); svc_perror(c.ext_ker()); assert(false); }
https://raw.githubusercontent.com/toppers/asp3_in_zig/7413474dc07ab906ac31eb367636ecf9c1cf2580/sample/sample3.zig
const std = @import("std"); const mem = std.mem; const testing = std.testing; const ArrayList = std.ArrayList; /// An operation on the bus. pub const BusOperation = enum { /// A request to read a byte from the bus. Read, /// A request to write a byte to the bus. Write, }; /// An interface for anything that can be present on the bus. pub const BusComponent = struct { /// A function to indicate if this interface should accept read or write /// requests from the bus for the given address. accept_fn: fn(bus_component: *const BusComponent, address: u16, operation: BusOperation) bool, /// A function to read a single byte from the bus given an address. read_fn: fn(bus_component: *const BusComponent, address: u16) u8, /// A function to write a single byte to the bus given an address. write_fn: fn(bus_component: *BusComponent, address: u16, byte: u8) void, /// Destroys this components. destroy_fn: fn(bus_component: *BusComponent) void, /// Indicates if the given operation at the given address is supported for /// this instance. pub inline fn accept(self: *const BusComponent, address: u16, operation: BusOperation) bool { return self.accept_fn(self, address, operation); } /// Reads the byte value at the given address. pub inline fn read(self: *const BusComponent, address: u16) u8 { return self.read_fn(self, address); } /// Writes a byte value at the given address. pub inline fn write(self: *BusComponent, address: u16, byte: u8) void { self.write_fn(self, address, byte); } /// Destroys this bus component. pub inline fn destroy(self: *BusComponent) void { self.destroy_fn(self); } }; /// A bus of components that can receive read and writes requests from a Z80 /// processor. pub const Bus = struct { const Self = @This(); _allocator: *mem.Allocator, components: ArrayList(*BusComponent), /// Creates a new bus using the given allocator to expand the list of bus /// components dynamically. pub fn create(allocator: *mem.Allocator) !*Self { var self = try allocator.create(Self); errdefer allocator.destroy(self); self._allocator = allocator; self.components = ArrayList(*BusComponent).init(allocator); return self; } /// Destroys this bus. pub fn destroy(self: *Self) void { self.components.deinit(); self._allocator.destroy(self); } /// Reads a value of the given type at the given address from all the bus /// components. /// /// If multiple components respond to the same address, a bitwise *or* will /// be applied to fold their results together. pub fn read(self: *const Self, comptime T: type, address: u16 ) T { return switch (T) { u8 => blk: { var byte: u8 = 0; for (self.components.toSliceConst()) |component| { if (component.accept(address, .Read)) { byte = byte | component.read(address); } } break :blk byte; }, i8 => @bitCast(i8, self.read(u8, address)), u16 => blk: { var low_byte: u8 = 0; var high_byte: u8 = 0; const next_address = address +% 1; for (self.components.toSliceConst()) |component| { if (component.accept(address, .Read)) { low_byte = low_byte | component.read(address); } if (component.accept(next_address, .Write)) { high_byte = high_byte | component.read(next_address); } } break :blk (@intCast(u16, high_byte) << 8) | @intCast(u16, low_byte); }, i16 => @bitCast(i16, self.read(u16, address)), else => @compileError("Invalid data type " ++ @typeName(T) ++ " to be read from the bus."), }; } /// Writes a value of the given type at the given address of all the bus /// components. /// /// If multiple component respond to the same address, they will each be /// called at that address with the same value. pub fn write(self: *Self, comptime T: type, address: u16, value: T) void { switch (T) { u8 => { for (self.components.toSlice()) |component| { if (component.accept(address, .Write)) { component.write(address, value); } } }, i8 => self.write(u8, address, @bitCast(u8, value)), u16 => { const low_byte = @intCast(u8, value % 256); const high_byte = @intCast(u8, (value >> 8) % 256); const next_address = address +% 1; for (self.components.toSlice()) |component| { if (component.accept(address, .Write)) { component.write(address, low_byte); } if (component.accept(next_address, .Write)) { component.write(next_address, high_byte); } } }, else => @compileError("Invalid data type " ++ @typeName(T) ++ " to be writen to the bus."), } } }; fn memoryAccept(bus_component: *const BusComponent, address: u16, operation: BusOperation) bool { var self = @fieldParentPtr(Memory, "_component", bus_component); if (self._memory_type == .ReadWrite or (self._memory_type == .Read and operation == .Read) or (self._memory_type == .Write and operation == .Write)) { return address >= self._start_address and address < self._end_address; } else { return false; } } fn memoryRead(bus_component: *const BusComponent, address: u16) u8 { var self = @fieldParentPtr(Memory, "_component", bus_component); return self._memory[address - self._start_address]; } fn memoryWrite(bus_component: *BusComponent, address: u16, byte: u8) void { var self = @fieldParentPtr(Memory, "_component", bus_component); self._memory[address - self._start_address] = byte; } fn memoryDestroy(bus_component: *BusComponent) void { var self = @fieldParentPtr(Memory, "_component", bus_component); self._allocator.free(self._memory); self._allocator.destroy(self); } /// A memory bus component that can either be read, write or both at the same time. pub const Memory = struct { const Self = @This(); /// The type of memory to construct. pub const MemoryType = enum { /// Read only memory Read, /// Write only memory Write, /// Read and write memory ReadWrite, }; _allocator: *mem.Allocator, _start_address: u16, _end_address: u16, _memory: []u8, _component: BusComponent, _memory_type: MemoryType, /// Creates a new memory component for addresses in the given range. pub fn create(allocator: *mem.Allocator, memory_type: MemoryType, start_address: u16, end_address: u16) !*BusComponent { var self = try allocator.create(Self); errdefer allocator.destroy(self); self._component = .{ .accept_fn = memoryAccept, .read_fn = memoryRead, .write_fn = memoryWrite, .destroy_fn = memoryDestroy, }; self._allocator = allocator; self._start_address = start_address; self._end_address = end_address; self._memory_type = memory_type; self._memory = try allocator.alloc(u8, @intCast(usize, end_address - start_address)); errdefer allocator.free(self._memory); mem.set(u8, self._memory, 0); return &self._component; } }; test "bus can read an address to get the combination of all the components' values" { var bus = try Bus.create(std.heap.page_allocator); defer bus.destroy(); var m1 = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x100, 0x200); defer m1.destroy(); var m2 = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x100, 0x200); defer m2.destroy(); try bus.components.append(m1); try bus.components.append(m2); m1.write(0x120, 0b10011001); m2.write(0x120, 0b01100110); testing.expectEqual(@intCast(u8, 0b11111111), bus.read(u8, 0x120)); } test "bus can write to an address to set the value in all components" { var bus = try Bus.create(std.heap.page_allocator); defer bus.destroy(); var m1 = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x100, 0x200); defer m1.destroy(); var m2 = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x100, 0x200); defer m2.destroy(); try bus.components.append(m1); try bus.components.append(m2); testing.expectEqual(@intCast(u8, 0), bus.read(u8, 0x150)); bus.write(u8, 0x150, 42); testing.expectEqual(@intCast(u8, 42), m1.read(0x150)); testing.expectEqual(@intCast(u8, 42), m2.read(0x150)); } test "bus can split words between multiple components" { var bus = try Bus.create(std.heap.page_allocator); defer bus.destroy(); var m1 = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x0, 0x100); defer m1.destroy(); var m2 = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x100, 0x200); defer m2.destroy(); try bus.components.append(m1); try bus.components.append(m2); bus.write(u16, 0x100 - 1, 0xCAFE); testing.expectEqual(@intCast(u8, 0xFE), m1.read(0x100 -1)); testing.expectEqual(@intCast(u8, 0xCA), m2.read(0x100)); } test "memory can only be read if declared as so" { var memory = try Memory.create(std.heap.page_allocator, .Read, 0x100, 0x200); defer memory.destroy(); testing.expect(memory.accept(0x180, .Read)); testing.expect(!memory.accept(0x180, .Write)); } test "memory can only be written if declared as so" { var memory = try Memory.create(std.heap.page_allocator, .Write, 0x100, 0x200); defer memory.destroy(); testing.expect(!memory.accept(0x180, .Read)); testing.expect(memory.accept(0x180, .Write)); } test "memory can accept any operations if both readable and writable" { var memory = try Memory.create(std.heap.page_allocator, .ReadWrite, 0x100, 0x200); defer memory.destroy(); testing.expect(memory.accept(0x180, .Read)); testing.expect(memory.accept(0x180, .Write)); } test "memory is initialized to zero" { var memory = try Memory.create(std.heap.page_allocator, .Read, 0, 0x100); defer memory.destroy(); var i: u16 = 0; while (i < 0x100) : (i += 1) { testing.expectEqual(@intCast(u8, 0), memory.read(i)); } } test "memory can be written to" { var memory = try Memory.create(std.heap.page_allocator, .Write, 0, 0x100); defer memory.destroy(); var i: u16 = 1; while (i <= 5) : (i += 1) { memory.write(0x30 + i, @intCast(u8, i)); } testing.expectEqual(@intCast(u8, 1), memory.read(0x31)); testing.expectEqual(@intCast(u8, 2), memory.read(0x32)); testing.expectEqual(@intCast(u8, 3), memory.read(0x33)); testing.expectEqual(@intCast(u8, 4), memory.read(0x34)); testing.expectEqual(@intCast(u8, 5), memory.read(0x35)); }
https://raw.githubusercontent.com/brodeuralexis/zasm-emulator/aa6b25f79eb710efde1f96261222e04d8cc326b6/src/bus.zig
const str = []const u8; const std = @import("std"); const builtin = @import("builtin"); const util = @import("util.zig"); const init = @import("./init.zig"); const repl = @import("./repl.zig"); const compile = @import("./compile.zig"); const build = @import("./build.zig"); const help = @import("./help.zig"); const process = std.process; const ChildProcess = std.ChildProcess; const Thread = std.Thread; const eq = util.eq; const readFile = util.readFile; const eql = std.mem.eql; const Allocator = std.mem.Allocator; const stderr = std.io.getStdErr(); const stdin = std.io.getStdIn(); const stdout = std.io.getStdOut(); pub fn run() void {}
https://raw.githubusercontent.com/clpi/idula/7b12447620025e86b3c460f52239337214838135/src/cli/run.zig
const std = @import("std"); const windows = std.os.windows; const builtin = @import("builtin"); const Foo = @import("root.zig").Foo; // Windows extern "kernel32" fn GetProcAddress(h_module: windows.HMODULE, fn_name: windows.LPCSTR) callconv(windows.WINAPI) ?windows.FARPROC; extern "kernel32" fn LoadLibraryA(fn_name: windows.LPCSTR) callconv(windows.WINAPI) ?windows.HMODULE; var add: *const fn (i32, i32) i32 = undefined; var makeFoo: *const fn (*std.mem.Allocator, i32, i32) *Foo = undefined; fn win32LoadDllFunctionPointers() void { const dll = LoadLibraryA("zig-out/lib/zig-dll-demo.dll"); if (dll != null) { add = @as(@TypeOf(add), @ptrCast(@alignCast(GetProcAddress(dll.?, "add")))); makeFoo = @as(@TypeOf(makeFoo), @ptrCast(@alignCast(GetProcAddress(dll.?, "makeFoo")))); } } fn loadDLLFunctionPointers() !void { var dll_file = try std.DynLib.open("zig-out/lib/zig-dll-demo.dll"); add = dll_file.lookup(@TypeOf(add), "add").?; makeFoo = dll_file.lookup(@TypeOf(makeFoo), "makeFoo").?; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); //win32LoadDllFunctionPointers(); try loadDLLFunctionPointers(); const result = add(1, 2); std.debug.print("add(1,2) = {}\n", .{result}); const foo = makeFoo(&allocator, 72, 49); std.debug.print("foo = {}\n", .{foo}); }
https://raw.githubusercontent.com/Skarsh/zig-dll-demo/3aed5223653a4307236e2be9853e7ba138ce589d/src/main.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const print = std.debug.print; const split = std.mem.splitSequence; const splitBackwards = std.mem.splitBackwardsSequence; const tokenize = std.mem.tokenizeAny; const sort = std.mem.sort; const parseInt = std.fmt.parseInt; const util = @import("util.zig"); const List = std.ArrayList; const Map = std.AutoHashMap; const INPUT_PATH = "input/05"; const Parsed = struct { seeds: []usize, maps: [7][]RangeMapping, allocator: Allocator, pub fn deinit(self: *@This()) void { self.allocator.free(self.seeds); for (self.maps) |map| { self.allocator.free(map); } } }; const RangeMapping = struct { start_src: usize, start_dst: usize, len: usize, const Self = @This(); fn getMapping(self: *const Self, n: usize) !usize { if (n >= self.start_src) { const distance_from_start = n - self.start_src; if (distance_from_start < self.len) return self.start_dst + distance_from_start; return error.TooHigh; } return error.TooLow; } fn intersect(self: *const Self, input: [2]usize) ![3]?[2]usize { const start = input[0]; const len = input[1]; if (start >= self.start_src + self.len) return error.TooHigh; if (start + len <= self.start_src) return error.TooLow; var ranges: [3]?[2]usize = .{ null, null, null }; if (start < self.start_src) { ranges[0] = .{ start, self.start_src - start, }; } if (start >= self.start_src) { ranges[1] = .{ start, @min(len, self.start_src + self.len - start), }; } else { ranges[1] = .{ self.start_src, @min(len - (self.start_src - start), self.start_src + self.len - start), }; } if (start + len > self.start_src + self.len) { ranges[2] = .{ self.start_src + self.len, len - ((self.start_src + self.len) - start) }; } return ranges; } }; fn parseInput(allocator: Allocator, raw: []const u8) Parsed { var seeds = List(usize).init(allocator); var it = split(u8, raw, "\n\n"); var seeds_str = it.next().?; var it_seeds = tokenize(u8, seeds_str, " "); _ = it_seeds.next().?; //seeds: while (it_seeds.next()) |num| { seeds.append( parseInt(usize, num, 10) catch unreachable ) catch unreachable; } var maps: [7][]RangeMapping = undefined; var i: usize = 0; while (it.next()) |section| : (i += 1) { var range_mappings = List(RangeMapping).init(allocator); var it_section = tokenize(u8, section, "\n"); _ = it_section.next().?; // map name while (it_section.next()) |range_str| { var it_range = tokenize(u8, range_str, " "); const start_dst = parseInt(usize, it_range.next().?, 10) catch unreachable; const start_src = parseInt(usize, it_range.next().?, 10) catch unreachable; const len = parseInt(usize, it_range.rest(), 10) catch unreachable; range_mappings.append(.{ .start_src = start_src, .start_dst = start_dst, .len = len, }) catch unreachable; } maps[i] = range_mappings.toOwnedSlice() catch unreachable; sort(RangeMapping, maps[i], {}, rangeMappingAsc); } return .{ .seeds = seeds.toOwnedSlice() catch unreachable, .maps = maps, .allocator = allocator, }; } fn rangeMappingAsc(_: void, a: RangeMapping, b: RangeMapping) bool { return a.start_src < b.start_src; } fn part1(parsed: Parsed) usize { const seeds = parsed.seeds; var min: usize = std.math.maxInt(usize); for (seeds) |seed| { const value = findMapping(0, seed, parsed.maps); min = @min(value, min); } return min; } fn findMapping(current_depth: usize, current_value: usize, maps: [7][]RangeMapping) usize { if (current_depth == 7) return current_value; const map = maps[current_depth]; var left: usize = 0; var right: usize = map.len - 1; while (left <= right) { const pivot = left + (right - left) / 2; const candidate = map[pivot]; const next_value = candidate.getMapping(current_value); if (next_value == error.TooHigh) { left = pivot + 1; } else if (next_value == error.TooLow) { if (pivot == 0) break; right = pivot - 1; } else { return findMapping(current_depth + 1, next_value catch unreachable, maps); } } return findMapping(current_depth + 1, current_value, maps); } fn part2(parsed: Parsed) usize { const seeds = parsed.seeds; var min: usize = std.math.maxInt(usize); var i: usize = 0; while (i < seeds.len) : (i += 2) { const seed_start = seeds[i]; const seed_count = seeds[i + 1]; const value = findMinMapping(0, .{ seed_start, seed_count }, parsed.maps); min = @min(value, min); } return min; } fn findMinMapping(current_depth: usize, current_value: [2]usize, maps: [7][]RangeMapping) usize { if (current_depth == 7) return current_value[0]; const map = maps[current_depth]; var left: usize = 0; var right: usize = map.len - 1; while (left <= right) { const pivot = left + (right - left) / 2; const candidate = map[pivot]; const intersection = candidate.intersect(current_value); if (intersection == error.TooHigh) { left = pivot + 1; } else if (intersection == error.TooLow) { if (pivot == 0) break; right = pivot - 1; } else { const ranges = intersection catch unreachable; var min: usize = std.math.maxInt(usize); if (ranges[0]) |range| { min = @min(min, findMinMapping(current_depth, range, maps)); } if (ranges[2]) |range| { min = @min(min, findMinMapping(current_depth, range, maps)); } if (ranges[1]) |range| { const start = candidate.getMapping(range[0]) catch unreachable; min = @min(min, findMinMapping(current_depth + 1, .{ start, range[1] }, maps)); } return min; } } return findMinMapping(current_depth + 1, current_value, maps); } pub fn main() !void { const allocator = std.heap.c_allocator; var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const input = try std.fs.cwd().readFileAlloc(arena.allocator(), INPUT_PATH, 1024 * 1024); const parsed = parseInput(arena.allocator(), input); const p1 = part1(parsed); const p2 = part2(parsed); print("Part1: {}\n", .{ p1 }); print("Part2: {}\n", .{ p2 }); try util.benchmark(INPUT_PATH, parseInput, part1, part2, 10000, 10000, 10000); } // // Tests // test "Part 1" { const allocator = std.testing.allocator; const input = try std.fs.cwd().readFileAlloc(allocator, INPUT_PATH ++ "test", 1024 * 1024); defer allocator.free(input); var parsed = parseInput(allocator, input); defer parsed.deinit(); try std.testing.expectEqual(@as(usize, 35), part1(parsed)); } test "Part 2" { const allocator = std.testing.allocator; const input = try std.fs.cwd().readFileAlloc(allocator, INPUT_PATH ++ "test", 1024 * 1024); defer allocator.free(input); var parsed = parseInput(allocator, input); defer parsed.deinit(); try std.testing.expectEqual(@as(usize, 46), part2(parsed)); }
https://raw.githubusercontent.com/Frechdachs/AoC/07e32616f4b8b08830eb5e4206a336ff97d61ec7/2023/05.zig
pub const area_code = [_][]const u8{ "392", "510", "512", "522", "562", "564", "592", "594", "800", "811", "822", "850", "888", "898", "900", "322", "416", "272", "472", "382", "358", "312", "242", "478", "466", "256", "266", "378", "488", "458", "228", "426", "434", "374", "248", "224", "286", "376", "364", "258", "412", "380", "284", "424", "446", "442", "222", "342", "454", "456", "438", "326", "476", "246", "216", "212", "232", "344", "370", "338", "474", "366", "352", "318", "288", "386", "348", "262", "332", "274", "422", "236", "482", "324", "252", "436", "384", "388", "452", "328", "464", "264", "362", "484", "368", "346", "414", "486", "282", "356", "462", "428", "276", "432", "226", "354", "372" }; pub const formats = [_][]const u8{ "+90-###-###-##-##", "+90-###-###-#-###" };
https://raw.githubusercontent.com/cksac/faker-zig/5a51eb6e6aa4ce50a25a354affca36e8fa059675/src/locales/tr/phone_number.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("mash", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const 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/zakinomiya/zigsh/ac41ea5de049e2feeb54dfe047a699114cbf75e4/build.zig
const std = @import("std"); const zsdl_build = @import("zsdl"); // Although this function looks imperative, note that its job is to // declaratively construct a build graph that will be executed by an external // runner. pub fn build(b: *std.Build) !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 optimization options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "nese", // In this case the main source file is merely a path, however, in more // complicated build scripts, this could be a generated file. .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const zsdl = b.dependency("zsdl", .{}); const zsdl_path = zsdl.path("").getPath(b); exe.root_module.addImport("zsdl", zsdl.module("zsdl2")); try zsdl_build.addLibraryPathsTo(exe, zsdl_path); zsdl_build.link_SDL2(exe); try zsdl_build.install_sdl2(&exe.step, target.result, .bin, zsdl_path); // This declares intent for the executable to be installed into the // standard location when the user invokes the "install" step (the default // step when running `zig build`). b.installArtifact(exe); // This *creates* a Run step in the build graph, to be executed when another // step is evaluated that depends on it. The next line below will establish // such a dependency. const run_cmd = b.addRunArtifact(exe); // By making the run step depend on the install step, it will be run from the // installation directory rather than directly from within the cache directory. // This is not necessary, however, if the application depends on other installed // files, this ensures they will be present and in the expected location. run_cmd.step.dependOn(b.getInstallStep()); // This allows the user to pass arguments to the application in the build // command itself, like this: `zig build run -- arg1 arg2 etc` if (b.args) |args| { run_cmd.addArgs(args); } // This creates a build step. It will be visible in the `zig build --help` menu, // and can be selected like this: `zig build run` // This will evaluate the `run` step rather than the default, which is "install". const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); // Creates a step for unit testing. This only builds the test executable // but does not run it. const unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); unit_tests.root_module.addImport("zsdl", zsdl.module("zsdl2")); try zsdl_build.addLibraryPathsTo(unit_tests, zsdl_path); zsdl_build.link_SDL2(unit_tests); try zsdl_build.install_sdl2(&unit_tests.step, target.result, .bin, zsdl_path); const run_unit_tests = b.addRunArtifact(unit_tests); // Similar to creating the run step earlier, this exposes a `test` step to // the `zig build --help` menu, providing a way for the user to request // running the unit tests. const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); }
https://raw.githubusercontent.com/thng292/nese/b7597b5298194564acc4251def549df21a1c118e/build.zig
// SPDX-License-Identifier: MIT // Copyright (c) 2015-2021 Zig Contributors // This file is part of [zig](https://ziglang.org/), which is MIT licensed. // The MIT license requires this copyright notice to be included in all copies // and substantial portions of the software. const std = @import("std"); const builtin = std.builtin; const page_size = std.mem.page_size; pub const tokenizer = @import("c/tokenizer.zig"); pub const Token = tokenizer.Token; pub const Tokenizer = tokenizer.Tokenizer; pub const parse = @import("c/parse.zig").parse; pub const ast = @import("c/ast.zig"); pub const builtins = @import("c/builtins.zig"); test { _ = tokenizer; } pub usingnamespace @import("os/bits.zig"); pub usingnamespace switch (std.Target.current.os.tag) { .linux => @import("c/linux.zig"), .windows => @import("c/windows.zig"), .macos, .ios, .tvos, .watchos => @import("c/darwin.zig"), .freebsd, .kfreebsd => @import("c/freebsd.zig"), .netbsd => @import("c/netbsd.zig"), .dragonfly => @import("c/dragonfly.zig"), .openbsd => @import("c/openbsd.zig"), .haiku => @import("c/haiku.zig"), .hermit => @import("c/hermit.zig"), .solaris => @import("c/solaris.zig"), .fuchsia => @import("c/fuchsia.zig"), .minix => @import("c/minix.zig"), .emscripten => @import("c/emscripten.zig"), else => struct {}, }; pub fn getErrno(rc: anytype) c_int { if (rc == -1) { return _errno().*; } else { return 0; } } /// The return type is `type` to force comptime function call execution. /// TODO: https://github.com/ziglang/zig/issues/425 /// If not linking libc, returns struct{pub const ok = false;} /// If linking musl libc, returns struct{pub const ok = true;} /// If linking gnu libc (glibc), the `ok` value will be true if the target /// version is greater than or equal to `glibc_version`. /// If linking a libc other than these, returns `false`. pub fn versionCheck(glibc_version: builtin.Version) type { return struct { pub const ok = blk: { if (!builtin.link_libc) break :blk false; if (std.Target.current.abi.isMusl()) break :blk true; if (std.Target.current.isGnuLibC()) { const ver = std.Target.current.os.version_range.linux.glibc; const order = ver.order(glibc_version); break :blk switch (order) { .gt, .eq => true, .lt => false, }; } else { break :blk false; } }; }; } pub extern "c" var environ: [*:null]?[*:0]u8; pub extern "c" fn fopen(noalias filename: [*:0]const u8, noalias modes: [*:0]const u8) ?*FILE; pub extern "c" fn fclose(stream: *FILE) c_int; pub extern "c" fn fwrite(noalias ptr: [*]const u8, size_of_type: usize, item_count: usize, noalias stream: *FILE) usize; pub extern "c" fn fread(noalias ptr: [*]u8, size_of_type: usize, item_count: usize, noalias stream: *FILE) usize; pub extern "c" fn printf(format: [*:0]const u8, ...) c_int; pub extern "c" fn abort() noreturn; pub extern "c" fn exit(code: c_int) noreturn; pub extern "c" fn _exit(code: c_int) noreturn; pub extern "c" fn isatty(fd: fd_t) c_int; pub extern "c" fn close(fd: fd_t) c_int; pub extern "c" fn lseek(fd: fd_t, offset: off_t, whence: c_int) off_t; pub extern "c" fn open(path: [*:0]const u8, oflag: c_uint, ...) c_int; pub extern "c" fn openat(fd: c_int, path: [*:0]const u8, oflag: c_uint, ...) c_int; pub extern "c" fn ftruncate(fd: c_int, length: off_t) c_int; pub extern "c" fn raise(sig: c_int) c_int; pub extern "c" fn read(fd: fd_t, buf: [*]u8, nbyte: usize) isize; pub extern "c" fn readv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint) isize; pub extern "c" fn pread(fd: fd_t, buf: [*]u8, nbyte: usize, offset: u64) isize; pub extern "c" fn preadv(fd: c_int, iov: [*]const iovec, iovcnt: c_uint, offset: u64) isize; pub extern "c" fn writev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint) isize; pub extern "c" fn pwritev(fd: c_int, iov: [*]const iovec_const, iovcnt: c_uint, offset: u64) isize; pub extern "c" fn write(fd: fd_t, buf: [*]const u8, nbyte: usize) isize; pub extern "c" fn pwrite(fd: fd_t, buf: [*]const u8, nbyte: usize, offset: u64) isize; pub extern "c" fn mmap(addr: ?*align(page_size) c_void, len: usize, prot: c_uint, flags: c_uint, fd: fd_t, offset: u64) *c_void; pub extern "c" fn munmap(addr: *align(page_size) c_void, len: usize) c_int; pub extern "c" fn mprotect(addr: *align(page_size) c_void, len: usize, prot: c_uint) c_int; pub extern "c" fn link(oldpath: [*:0]const u8, newpath: [*:0]const u8, flags: c_int) c_int; pub extern "c" fn linkat(oldfd: fd_t, oldpath: [*:0]const u8, newfd: fd_t, newpath: [*:0]const u8, flags: c_int) c_int; pub extern "c" fn unlink(path: [*:0]const u8) c_int; pub extern "c" fn unlinkat(dirfd: fd_t, path: [*:0]const u8, flags: c_uint) c_int; pub extern "c" fn getcwd(buf: [*]u8, size: usize) ?[*]u8; pub extern "c" fn waitpid(pid: c_int, stat_loc: *c_uint, options: c_uint) c_int; pub extern "c" fn fork() c_int; pub extern "c" fn access(path: [*:0]const u8, mode: c_uint) c_int; pub extern "c" fn faccessat(dirfd: fd_t, path: [*:0]const u8, mode: c_uint, flags: c_uint) c_int; pub extern "c" fn pipe(fds: *[2]fd_t) c_int; pub extern "c" fn mkdir(path: [*:0]const u8, mode: c_uint) c_int; pub extern "c" fn mkdirat(dirfd: fd_t, path: [*:0]const u8, mode: u32) c_int; pub extern "c" fn symlink(existing: [*:0]const u8, new: [*:0]const u8) c_int; pub extern "c" fn symlinkat(oldpath: [*:0]const u8, newdirfd: fd_t, newpath: [*:0]const u8) c_int; pub extern "c" fn rename(old: [*:0]const u8, new: [*:0]const u8) c_int; pub extern "c" fn renameat(olddirfd: fd_t, old: [*:0]const u8, newdirfd: fd_t, new: [*:0]const u8) c_int; pub extern "c" fn chdir(path: [*:0]const u8) c_int; pub extern "c" fn fchdir(fd: fd_t) c_int; pub extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; pub extern "c" fn dup(fd: fd_t) c_int; pub extern "c" fn dup2(old_fd: fd_t, new_fd: fd_t) c_int; pub extern "c" fn readlink(noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize; pub extern "c" fn readlinkat(dirfd: fd_t, noalias path: [*:0]const u8, noalias buf: [*]u8, bufsize: usize) isize; pub usingnamespace switch (builtin.os.tag) { .macos, .ios, .watchos, .tvos => struct { pub const realpath = @"realpath$DARWIN_EXTSN"; pub const fstatat = _fstatat; }, else => struct { pub extern "c" fn realpath(noalias file_name: [*:0]const u8, noalias resolved_name: [*]u8) ?[*:0]u8; pub extern "c" fn fstatat(dirfd: fd_t, path: [*:0]const u8, stat_buf: *libc_stat, flags: u32) c_int; }, }; pub extern "c" fn rmdir(path: [*:0]const u8) c_int; pub extern "c" fn getenv(name: [*:0]const u8) ?[*:0]u8; pub extern "c" fn sysctl(name: [*]const c_int, namelen: c_uint, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int; pub extern "c" fn sysctlbyname(name: [*:0]const u8, oldp: ?*c_void, oldlenp: ?*usize, newp: ?*c_void, newlen: usize) c_int; pub extern "c" fn sysctlnametomib(name: [*:0]const u8, mibp: ?*c_int, sizep: ?*usize) c_int; pub extern "c" fn tcgetattr(fd: fd_t, termios_p: *termios) c_int; pub extern "c" fn tcsetattr(fd: fd_t, optional_action: TCSA, termios_p: *const termios) c_int; pub extern "c" fn fcntl(fd: fd_t, cmd: c_int, ...) c_int; pub extern "c" fn flock(fd: fd_t, operation: c_int) c_int; pub extern "c" fn ioctl(fd: fd_t, request: c_int, ...) c_int; pub extern "c" fn uname(buf: *utsname) c_int; pub extern "c" fn gethostname(name: [*]u8, len: usize) c_int; pub extern "c" fn shutdown(socket: fd_t, how: c_int) c_int; pub extern "c" fn bind(socket: fd_t, address: ?*const sockaddr, address_len: socklen_t) c_int; pub extern "c" fn socketpair(domain: c_uint, sock_type: c_uint, protocol: c_uint, sv: *[2]fd_t) c_int; pub extern "c" fn listen(sockfd: fd_t, backlog: c_uint) c_int; pub extern "c" fn getsockname(sockfd: fd_t, noalias addr: *sockaddr, noalias addrlen: *socklen_t) c_int; pub extern "c" fn connect(sockfd: fd_t, sock_addr: *const sockaddr, addrlen: socklen_t) c_int; pub extern "c" fn accept(sockfd: fd_t, noalias addr: ?*sockaddr, noalias addrlen: ?*socklen_t) c_int; pub extern "c" fn accept4(sockfd: fd_t, noalias addr: ?*sockaddr, noalias addrlen: ?*socklen_t, flags: c_uint) c_int; pub extern "c" fn getsockopt(sockfd: fd_t, level: u32, optname: u32, noalias optval: ?*c_void, noalias optlen: *socklen_t) c_int; pub extern "c" fn setsockopt(sockfd: fd_t, level: u32, optname: u32, optval: ?*const c_void, optlen: socklen_t) c_int; pub extern "c" fn send(sockfd: fd_t, buf: *const c_void, len: usize, flags: u32) isize; pub extern "c" fn sendto( sockfd: fd_t, buf: *const c_void, len: usize, flags: u32, dest_addr: ?*const sockaddr, addrlen: socklen_t, ) isize; pub extern fn recv(sockfd: fd_t, arg1: ?*c_void, arg2: usize, arg3: c_int) isize; pub extern fn recvfrom( sockfd: fd_t, noalias buf: *c_void, len: usize, flags: u32, noalias src_addr: ?*sockaddr, noalias addrlen: ?*socklen_t, ) isize; pub usingnamespace switch (builtin.os.tag) { .netbsd => struct { pub const clock_getres = __clock_getres50; pub const clock_gettime = __clock_gettime50; pub const fstat = __fstat50; pub const getdents = __getdents30; pub const getrusage = __getrusage50; pub const gettimeofday = __gettimeofday50; pub const nanosleep = __nanosleep50; pub const sched_yield = __libc_thr_yield; pub const sigaction = __sigaction14; pub const sigaltstack = __sigaltstack14; pub const sigprocmask = __sigprocmask14; pub const stat = __stat50; }, .macos, .ios, .watchos, .tvos => struct { // XXX: close -> close$NOCANCEL // XXX: getdirentries -> _getdirentries64 pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; pub const fstat = _fstat; pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int; pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn sched_yield() c_int; pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int; pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *libc_stat) c_int; }, .windows => struct { // TODO: copied the else case and removed the socket function (because its in ws2_32) // need to verify which of these is actually supported on windows pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn fstat(fd: fd_t, buf: *libc_stat) c_int; pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int; pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn sched_yield() c_int; pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int; pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *libc_stat) c_int; }, else => struct { pub extern "c" fn clock_getres(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn clock_gettime(clk_id: c_int, tp: *timespec) c_int; pub extern "c" fn fstat(fd: fd_t, buf: *libc_stat) c_int; pub extern "c" fn getrusage(who: c_int, usage: *rusage) c_int; pub extern "c" fn gettimeofday(noalias tv: ?*timeval, noalias tz: ?*timezone) c_int; pub extern "c" fn nanosleep(rqtp: *const timespec, rmtp: ?*timespec) c_int; pub extern "c" fn sched_yield() c_int; pub extern "c" fn sigaction(sig: c_int, noalias act: ?*const Sigaction, noalias oact: ?*Sigaction) c_int; pub extern "c" fn sigprocmask(how: c_int, noalias set: ?*const sigset_t, noalias oset: ?*sigset_t) c_int; pub extern "c" fn socket(domain: c_uint, sock_type: c_uint, protocol: c_uint) c_int; pub extern "c" fn stat(noalias path: [*:0]const u8, noalias buf: *libc_stat) c_int; }, }; pub extern "c" fn kill(pid: pid_t, sig: c_int) c_int; pub extern "c" fn getdirentries(fd: fd_t, buf_ptr: [*]u8, nbytes: usize, basep: *i64) isize; pub extern "c" fn setuid(uid: uid_t) c_int; pub extern "c" fn setgid(gid: gid_t) c_int; pub extern "c" fn seteuid(euid: uid_t) c_int; pub extern "c" fn setegid(egid: gid_t) c_int; pub extern "c" fn setreuid(ruid: uid_t, euid: uid_t) c_int; pub extern "c" fn setregid(rgid: gid_t, egid: gid_t) c_int; pub extern "c" fn setresuid(ruid: uid_t, euid: uid_t, suid: uid_t) c_int; pub extern "c" fn setresgid(rgid: gid_t, egid: gid_t, sgid: gid_t) c_int; pub extern "c" fn malloc(usize) ?*c_void; pub extern "c" fn realloc(?*c_void, usize) ?*c_void; pub extern "c" fn free(?*c_void) void; pub extern "c" fn futimes(fd: fd_t, times: *[2]timeval) c_int; pub extern "c" fn utimes(path: [*:0]const u8, times: *[2]timeval) c_int; pub extern "c" fn utimensat(dirfd: fd_t, pathname: [*:0]const u8, times: *[2]timespec, flags: u32) c_int; pub extern "c" fn futimens(fd: fd_t, times: *const [2]timespec) c_int; pub extern "c" fn pthread_create(noalias newthread: *pthread_t, noalias attr: ?*const pthread_attr_t, start_routine: fn (?*c_void) callconv(.C) ?*c_void, noalias arg: ?*c_void) c_int; pub extern "c" fn pthread_attr_init(attr: *pthread_attr_t) c_int; pub extern "c" fn pthread_attr_setstack(attr: *pthread_attr_t, stackaddr: *c_void, stacksize: usize) c_int; pub extern "c" fn pthread_attr_setstacksize(attr: *pthread_attr_t, stacksize: usize) c_int; pub extern "c" fn pthread_attr_setguardsize(attr: *pthread_attr_t, guardsize: usize) c_int; pub extern "c" fn pthread_attr_destroy(attr: *pthread_attr_t) c_int; pub extern "c" fn pthread_self() pthread_t; pub extern "c" fn pthread_join(thread: pthread_t, arg_return: ?*?*c_void) c_int; pub extern "c" fn pthread_atfork( prepare: ?fn () callconv(.C) void, parent: ?fn () callconv(.C) void, child: ?fn () callconv(.C) void, ) c_int; pub extern "c" fn pthread_key_create(key: *pthread_key_t, destructor: ?fn (value: *c_void) callconv(.C) void) c_int; pub extern "c" fn pthread_key_delete(key: pthread_key_t) c_int; pub extern "c" fn pthread_getspecific(key: pthread_key_t) ?*c_void; pub extern "c" fn pthread_setspecific(key: pthread_key_t, value: ?*c_void) c_int; pub extern "c" fn sem_init(sem: *sem_t, pshared: c_int, value: c_uint) c_int; pub extern "c" fn sem_destroy(sem: *sem_t) c_int; pub extern "c" fn sem_post(sem: *sem_t) c_int; pub extern "c" fn sem_wait(sem: *sem_t) c_int; pub extern "c" fn sem_trywait(sem: *sem_t) c_int; pub extern "c" fn sem_timedwait(sem: *sem_t, abs_timeout: *const timespec) c_int; pub extern "c" fn sem_getvalue(sem: *sem_t, sval: *c_int) c_int; pub extern "c" fn kqueue() c_int; pub extern "c" fn kevent( kq: c_int, changelist: [*]const Kevent, nchanges: c_int, eventlist: [*]Kevent, nevents: c_int, timeout: ?*const timespec, ) c_int; pub extern "c" fn getaddrinfo( noalias node: ?[*:0]const u8, noalias service: ?[*:0]const u8, noalias hints: ?*const addrinfo, noalias res: **addrinfo, ) EAI; pub extern "c" fn freeaddrinfo(res: *addrinfo) void; pub extern "c" fn getnameinfo( noalias addr: *const sockaddr, addrlen: socklen_t, noalias host: [*]u8, hostlen: socklen_t, noalias serv: [*]u8, servlen: socklen_t, flags: u32, ) EAI; pub extern "c" fn gai_strerror(errcode: EAI) [*:0]const u8; pub extern "c" fn poll(fds: [*]pollfd, nfds: nfds_t, timeout: c_int) c_int; pub extern "c" fn ppoll(fds: [*]pollfd, nfds: nfds_t, timeout: ?*const timespec, sigmask: ?*const sigset_t) c_int; pub extern "c" fn dn_expand( msg: [*:0]const u8, eomorig: [*:0]const u8, comp_dn: [*:0]const u8, exp_dn: [*:0]u8, length: c_int, ) c_int; pub const PTHREAD_MUTEX_INITIALIZER = pthread_mutex_t{}; pub extern "c" fn pthread_mutex_lock(mutex: *pthread_mutex_t) c_int; pub extern "c" fn pthread_mutex_unlock(mutex: *pthread_mutex_t) c_int; pub extern "c" fn pthread_mutex_trylock(mutex: *pthread_mutex_t) c_int; pub extern "c" fn pthread_mutex_destroy(mutex: *pthread_mutex_t) c_int; pub const PTHREAD_COND_INITIALIZER = pthread_cond_t{}; pub extern "c" fn pthread_cond_wait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t) c_int; pub extern "c" fn pthread_cond_timedwait(noalias cond: *pthread_cond_t, noalias mutex: *pthread_mutex_t, noalias abstime: *const timespec) c_int; pub extern "c" fn pthread_cond_signal(cond: *pthread_cond_t) c_int; pub extern "c" fn pthread_cond_broadcast(cond: *pthread_cond_t) c_int; pub extern "c" fn pthread_cond_destroy(cond: *pthread_cond_t) c_int; pub extern "c" fn pthread_rwlock_destroy(rwl: *pthread_rwlock_t) callconv(.C) c_int; pub extern "c" fn pthread_rwlock_rdlock(rwl: *pthread_rwlock_t) callconv(.C) c_int; pub extern "c" fn pthread_rwlock_wrlock(rwl: *pthread_rwlock_t) callconv(.C) c_int; pub extern "c" fn pthread_rwlock_tryrdlock(rwl: *pthread_rwlock_t) callconv(.C) c_int; pub extern "c" fn pthread_rwlock_trywrlock(rwl: *pthread_rwlock_t) callconv(.C) c_int; pub extern "c" fn pthread_rwlock_unlock(rwl: *pthread_rwlock_t) callconv(.C) c_int; pub const pthread_t = *opaque {}; pub const FILE = opaque {}; pub extern "c" fn dlopen(path: [*:0]const u8, mode: c_int) ?*c_void; pub extern "c" fn dlclose(handle: *c_void) c_int; pub extern "c" fn dlsym(handle: ?*c_void, symbol: [*:0]const u8) ?*c_void; pub extern "c" fn sync() void; pub extern "c" fn syncfs(fd: c_int) c_int; pub extern "c" fn fsync(fd: c_int) c_int; pub extern "c" fn fdatasync(fd: c_int) c_int; pub extern "c" fn prctl(option: c_int, ...) c_int; pub extern "c" fn getrlimit(resource: rlimit_resource, rlim: *rlimit) c_int; pub extern "c" fn setrlimit(resource: rlimit_resource, rlim: *const rlimit) c_int; pub extern "c" fn fmemopen(noalias buf: ?*c_void, size: usize, noalias mode: [*:0]const u8) ?*FILE; pub extern "c" fn syslog(priority: c_int, message: [*:0]const u8, ...) void; pub extern "c" fn openlog(ident: [*:0]const u8, logopt: c_int, facility: c_int) void; pub extern "c" fn closelog() void; pub extern "c" fn setlogmask(maskpri: c_int) c_int; pub const max_align_t = if (std.Target.current.abi == .msvc) f64 else if (std.Target.current.isDarwin()) c_longdouble else extern struct { a: c_longlong, b: c_longdouble, };
https://raw.githubusercontent.com/dip-proto/zig/8f79f7e60937481fcf861c2941db02cbf449cdca/lib/std/c.zig
const std = @import("std"); pub const parser = @import("parser/parser.zig"); pub const base = @import("base/base.zig"); const common = @import("common.zig"); pub const MessageHeader = common.MessageHeader; pub const Opcode = common.Opcode; comptime { std.testing.refAllDecls(@This()); }
https://raw.githubusercontent.com/truemedian/wz/fa698c2493bcc084b86e77fc9baa54dac6bfed44/src/main.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("day-1", "src/main.zig"); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); const 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/mamico/adventofcode/f97f3f2da4c0c9b07227951e0ad84b22fb5775ac/day-01/build.zig
// // File: main.zig // Created on: Monday, 2023-12-04 @ 21:01:06 // Author: HackXIt (<hackxit@gmail.com>) // ----- // Last Modified: Monday, 2023-12-04 @ 23:52:36 // Modified By: HackXIt (<hackxit@gmail.com>) @ HACKXIT // ----- // const std = @import("std"); const expect = std.testing.expect; fn sumOfLine(line: []const u8) !u32 { var line_sum: u32 = 0; for (line) |val| { // TODO find leftmost and rightmost digit for sum // TODO create function for finding digit if (std.ascii.isDigit(val)) { // try std.debug.print("{d}", .{val}); line_sum += @intCast(val); } } return line_sum; } fn calibrateTrebuchet(input: []const u8) !u32 { var sum: u32 = 0; var iter = std.mem.tokenizeAny(u8, input, "\n"); while (iter.next()) |line| { sum += sumOfLine(line) catch 0; } return sum; } pub fn main() !void { const stdout = std.io.getStdOut().writer(); // const file = std.fs.cwd().openFile("input.txt", .{}) catch |err| { // std.debug.print("Error opening file: ", .{err}); // return; // }; // defer file.close(); // defer executes expression at end of current scope (i.e. after main() in this case) var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const content = try std.fs.cwd().readFileAlloc(allocator, "input.txt", 1024 * 1024); var total: u32 = calibrateTrebuchet(content) catch 0; try stdout.print("Total: {d}", .{total}); } test "simple test" { const example_input = @embedFile("sample.txt"); var sum: u32 = calibrateTrebuchet(example_input) catch 0; try expect(sum == 142); }
https://raw.githubusercontent.com/HackXIt/advent-of-code-2023/9da0ace2a824ba1364d78aa32032d337a920535e/day1/src/main.zig
//! //! Implements a N*M keyboard matrix that will be scanned in column-major order. //! const std = @import("std"); const mdf = @import("../framework.zig"); /// A single key in a 2D keyboard matrix. pub const Key = enum(u16) { // we just assume we have enough encoding space and not more than 256 cols/rows _, pub fn new(r: u8, c: u8) Key { return @as(Key, @enumFromInt((@as(u16, r) << 8) + c)); } pub fn row(key: Key) u8 { return @as(u8, @truncate(@intFromEnum(key) >> 8)); } pub fn column(key: Key) u8 { return @as(u8, @truncate(@intFromEnum(key))); } }; /// Keyboard matrix implementation via GPIOs that scans columns and checks rows. /// /// Will use `cols` as matrix drivers (outputs) and `rows` as matrix readers (inputs). pub fn KeyboardMatrix(comptime col_count: usize, comptime row_count: usize) type { return KeyboardMatrix_Generic(mdf.base.DigitalIO, col_count, row_count); } pub fn KeyboardMatrix_Generic(comptime Pin: type, comptime col_count: usize, comptime row_count: usize) type { if (col_count > 256 or row_count > 256) @compileError("cannot encode more than 256 rows or columns!"); return struct { const Matrix = @This(); /// Number of keys in this matrix. pub const key_count = col_count * row_count; /// Returns the index for the given key. Assumes that `key` is valid. pub fn index(key: Key) usize { return key.column() * row_count + key.row(); } /// A set that can store if each key is set or not. pub const Set = struct { pressed: std.StaticBitSet(key_count) = std.StaticBitSet(key_count).initEmpty(), /// Adds a key to the set. pub fn add(set: *Set, key: Key) void { set.pressed.set(index(key)); } /// Checks if a key is pressed. pub fn isPressed(set: Set, key: Key) bool { return set.pressed.isSet(index(key)); } /// Returns if any key is pressed. pub fn any(set: Set) bool { return (set.pressed.count() > 0); } }; cols: [col_count]Pin, rows: [row_count]Pin, /// Initializes all GPIOs of the matrix and returns a new instance. pub fn init( cols: [col_count]Pin, rows: [row_count]Pin, ) !Matrix { var mat = Matrix{ .cols = cols, .rows = rows, }; for (cols) |c| { try c.set_direction(.output); } for (rows) |r| { try r.set_direction(.input); try r.set_bias(.high); } try mat.set_all_to(.high); return mat; } /// Scans the matrix and returns a set of all pressed keys. pub fn scan(matrix: Matrix) !Set { var result = Set{}; try matrix.set_all_to(.high); for (matrix.cols, 0..) |c_pin, c_index| { try c_pin.write(.low); busyloop(10); for (matrix.rows, 0..) |r_pin, r_index| { const state = r_pin.read(); if (state == .low) { // someone actually pressed a key! result.add(Key.new( @as(u8, @truncate(r_index)), @as(u8, @truncate(c_index)), )); } } try c_pin.write(.high); busyloop(100); } try matrix.set_all_to(.high); return result; } fn set_all_to(matrix: Matrix, value: mdf.base.DigitalIO.State) !void { for (matrix.cols) |c| { try c.write(value); } } }; } inline fn busyloop(comptime N: comptime_int) void { for (0..N) |_| { // wait some cycles so the physics does its magic and convey // the electrons asm volatile ("" ::: "memory"); } } test KeyboardMatrix { var matrix_pins = [_]mdf.base.DigitalIO.TestDevice{ mdf.base.DigitalIO.TestDevice.init(.output, .high), mdf.base.DigitalIO.TestDevice.init(.output, .high), mdf.base.DigitalIO.TestDevice.init(.output, .high), mdf.base.DigitalIO.TestDevice.init(.output, .high), }; const rows = [_]mdf.base.DigitalIO{ matrix_pins[0].digital_io(), matrix_pins[1].digital_io(), }; const cols = [_]mdf.base.DigitalIO{ matrix_pins[2].digital_io(), matrix_pins[3].digital_io(), }; var matrix = try KeyboardMatrix(2, 2).init(&cols, &rows); const set = try matrix.scan(); _ = set; }
https://raw.githubusercontent.com/ZigEmbeddedGroup/microzig-driver-framework/50f97ff54c1f2e738b85b8d1394428612728aeb9/driver/input/keyboard-matrix.zig
const std = @import("std"); const lib = @import("lib.zig"); const constants = @import("constants.zig"); pub const STAR = constants.STAR; pub const TEXT = constants.TEXT; pub const IMAGE = constants.IMAGE; pub const AUDIO = constants.AUDIO; pub const VIDEO = constants.VIDEO; pub const APPLICATION = constants.APPLICATION; pub const MULTIPART = constants.MULTIPART; pub const MESSAGE = constants.MESSAGE; pub const MODEL = constants.MODEL; pub const FONT = constants.FONT; pub const PLAIN = constants.PLAIN; pub const HTML = constants.HTML; pub const XML = constants.XML; pub const JAVASCRIPT = constants.JAVASCRIPT; pub const CSS = constants.CSS; pub const CSV = constants.CSV; pub const EVENT_STREAM = constants.EVENT_STREAM; pub const VCARD = constants.VCARD; pub const TAB_SEPARATED_VALUES = constants.TAB_SEPARATED_VALUES; pub const JSON = constants.JSON; pub const WWW_FORM_URLENCODED = constants.WWW_FORM_URLENCODED; pub const MSGPACK = constants.MSGPACK; pub const OCTET_STREAM = constants.OCTET_STREAM; pub const PDF = constants.PDF; pub const WOFF = constants.WOFF; pub const WOFF2 = constants.WOFF2; pub const FORM_DATA = constants.FORM_DATA; pub const BMP = constants.BMP; pub const GIF = constants.GIF; pub const JPEG = constants.JPEG; pub const PNG = constants.PNG; pub const SVG = constants.SVG; pub const BASIC = constants.BASIC; pub const MPEG = constants.MPEG; pub const MP4 = constants.MP4; pub const OGG = constants.OGG; pub const CHARSET = constants.CHARSET; pub const BOUNDARY = constants.BOUNDARY; pub const TEXT_PLAIN = constants.TEXT_PLAIN; pub const TEXT_PLAIN_UTF_8 = constants.TEXT_PLAIN_UTF_8; pub const TEXT_HTML = constants.TEXT_HTML; pub const TEXT_HTML_UTF_8 = constants.TEXT_HTML_UTF_8; pub const TEXT_CSS = constants.TEXT_CSS; pub const TEXT_CSS_UTF_8 = constants.TEXT_CSS_UTF_8; pub const TEXT_JAVASCRIPT = constants.TEXT_JAVASCRIPT; pub const TEXT_XML = constants.TEXT_XML; pub const TEXT_EVENT_STREAM = constants.TEXT_EVENT_STREAM; pub const TEXT_CSV = constants.TEXT_CSV; pub const TEXT_CSV_UTF_8 = constants.TEXT_CSV_UTF_8; pub const TEXT_TAB_SEPARATED_VALUES = constants.TEXT_TAB_SEPARATED_VALUES; pub const TEXT_TAB_SEPARATED_VALUES_UTF_8 = constants.TEXT_TAB_SEPARATED_VALUES_UTF_8; pub const TEXT_VCARD = constants.TEXT_VCARD; pub const IMAGE_JPEG = constants.IMAGE_JPEG; pub const IMAGE_GIF = constants.IMAGE_GIF; pub const IMAGE_PNG = constants.IMAGE_PNG; pub const IMAGE_BMP = constants.IMAGE_BMP; pub const IMAGE_SVG = constants.IMAGE_SVG; pub const FONT_WOFF = constants.FONT_WOFF; pub const FONT_WOFF2 = constants.FONT_WOFF2; pub const APPLICATION_JSON = constants.APPLICATION_JSON; pub const APPLICATION_JAVASCRIPT = constants.APPLICATION_JAVASCRIPT; pub const APPLICATION_JAVASCRIPT_UTF_8 = constants.APPLICATION_JAVASCRIPT_UTF_8; pub const APPLICATION_WWW_FORM_URLENCODED = constants.APPLICATION_WWW_FORM_URLENCODED; pub const APPLICATION_OCTET_STREAM = constants.APPLICATION_OCTET_STREAM; pub const APPLICATION_MSGPACK = constants.APPLICATION_MSGPACK; pub const APPLICATION_PDF = constants.APPLICATION_PDF; pub const APPLICATION_DNS = constants.APPLICATION_DNS; pub const STAR_STAR = constants.STAR_STAR; pub const TEXT_STAR = constants.TEXT_STAR; pub const IMAGE_STAR = constants.IMAGE_STAR; pub const VIDEO_STAR = constants.VIDEO_STAR; pub const AUDIO_STAR = constants.AUDIO_STAR; pub const Atom = constants.Atom; pub const Mime = lib.Mime; pub const Source = lib.Source; pub const Params = lib.Params; pub const InternParams = lib.InternParams; pub const ParamSource = lib.ParamSource; pub const Indexed = lib.Indexed; pub const IndexedPair = lib.IndexedPair; const range = lib.range; pub const ParseError = error{ MissingSlash, MissingEqual, MissingQuote, InvalidToken, InvalidRange, TooLong, }; inline fn eql(a: []const u8, b: []const u8) bool { return std.mem.eql(u8, a, b); } pub fn parse(s: []const u8, can_range: bool) ParseError!Mime { if (s.len > @intCast(usize, std.math.maxInt(u16))) { return error.TooLong; } if (eql(s, "*/*")) { if (can_range) { return STAR_STAR; } return error.InvalidRange; } var start: usize = 0; var slash: u16 = 0; var it = iter{ .s = s }; while (true) { if (it.next()) |e| { if (e.c == '/' and e.i > 0) { slash = @truncate(u16, e.i); start = e.i + 1; break; } if (is_token(e.c)) continue; return error.InvalidToken; } return error.MissingSlash; } var plus: ?u16 = null; while (true) { if (it.next()) |e| { if (e.c == '+' and e.i > start) { plus = @truncate(u16, e.i); } else if (e.c == ';' and e.i > start) { start = e.i; break; } else if (e.c == ' ' and e.i > start) { start = e.i; break; } else if (e.c == '*' and e.i == start and can_range) { // sublevel star can only be the first character, and the next // must either be the end, or `;` if (it.next()) |n| { if (n.c == ';') { start = n.i; break; } return error.InvalidToken; } return Mime{ .source = intern(s, slash, .None), .slash = slash, .plus = plus, .params = .None, }; } if (is_token(e.c)) continue; return error.InvalidToken; } return Mime{ .source = intern(s, slash, .None), .slash = slash, .plus = plus, .params = .None, }; } var params = try params_from_str(s, &it, start); var source = switch (params) { .None => r: { // Getting here means there *was* a `;`, but then no parameters // after it... So let's just chop off the empty param list. std.debug.assert(s.len != start); const b = s[start]; std.debug.assert(b == ';' or b == ' '); break :r intern(s[0..start], slash, .None); }, .Utf8 => |o| intern(s, slash, .{ .Utf8 = @intCast(usize, o) }), .One => |*o| Source.dynamic_from_index(s, @intCast(usize, o.a), &[_]IndexedPair{o.b}), .Two => |*o| Source.dynamic_from_index(s, @intCast(usize, o.a), &[_]IndexedPair{ o.b, o.c }), .Custom => |*o| Source.dynamic_from_index(s, @intCast(usize, o.a), o.b.items), }; return Mime{ .source = source, .slash = slash, .plus = plus, .params = params, }; } fn params_from_str(s: []const u8, it: *iter, start_pos: usize) ParseError!ParamSource { var start = start_pos; const param_start = @intCast(u16, start); start += 1; var params: ParamSource = .None; errdefer params.deinit(); params: while (start < s.len) { var name: Indexed = .{}; name: while (true) { if (it.next()) |c| { if (c.c == ' ' and c.i == start) { start = c.i + 1; continue :params; } if (c.c == ';' and c.i == start) { start = c.i + 1; continue :params; } if (c.c == '=' and c.i > start) { name = .{ .a = @intCast(u16, start), .b = @intCast(u16, c.i), }; start = c.i + 1; break :name; } if (is_token(c.c)) continue; return error.InvalidToken; } return error.MissingEqual; } var value: Indexed = .{}; var is_quoted: bool = false; var is_quoted_pair: bool = false; value: while (true) { if (is_quoted) { if (is_quoted_pair) { is_quoted_pair = false; const c = it.next(); if (c == null) return error.MissingQuote; if (!is_restricted_quoted_char(c.?.c)) { return error.InvalidToken; } } else { const c = it.next(); if (c == null) return error.MissingQuote; if (c.?.c == '"' and c.?.i > start) { value = .{ .a = @intCast(u16, start), .b = @intCast(u16, c.?.i + 1), }; start = c.?.i + 1; break :value; } else if (c.?.c == '\\') { is_quoted_pair = true; } else if (is_restricted_quoted_char(c.?.c)) {} else { return error.InvalidToken; } } } else { const n = it.next(); if (n == null) { value = .{ .a = @intCast(u16, start), .b = @intCast(u16, s.len), }; start = s.len; break :value; } const c = n.?; if (c.c == '"' and c.i == start) { is_quoted = true; start = c.i; } else if ((c.c == ' ' or c.c == ';') and c.i > start) { value = .{ .a = @intCast(u16, start), .b = @intCast(u16, c.i), }; start = c.i + 1; break :value; } else if (is_token(c.c)) {} else { return error.InvalidToken; } } } switch (params) { .Utf8 => |b| { const i = b + 2; const cs = "charset"; const ut = "utf-8"; const charset = Indexed{ .a = i, .b = @intCast(u16, cs.len) + i, }; const utf8 = Indexed{ .a = charset.b + 1, .b = charset.b + @intCast(u16, ut.len) + 1, }; params = ParamSource{ .Two = .{ .a = param_start, .b = .{ .a = charset, .b = utf8, }, .c = .{ .a = name, .b = value, }, }, }; }, .One => |o| { params = ParamSource{ .Two = .{ .a = o.a, .b = o.b, .c = .{ .a = name, .b = value }, }, }; }, .Two => |o| { params = ParamSource.custom(o.a, &[_]IndexedPair{ o.b, o.c, .{ .a = name, .b = value }, }); }, .Custom => |*o| { o.b.append(.{ .a = name, .b = value }) catch unreachable; }, .None => { const eql0 = std.ascii.eqlIgnoreCase( "charset", range(s, name), ); const eql1 = std.ascii.eqlIgnoreCase( "utf-8", range(s, value), ); if (param_start + 2 == name.a and eql0 and eql1) { params = ParamSource{ .Utf8 = param_start }; continue :params; } params = ParamSource{ .One = .{ .a = param_start, .b = .{ .a = name, .b = value, }, }, }; }, } } return params; } const iter = struct { s: []const u8, p: usize = 0, const e = struct { c: u8, i: usize, }; fn next(self: *iter) ?e { if (self.p < self.s.len) { defer { self.p += 1; } return e{ .c = self.s[self.p], .i = self.p }; } return null; } }; const TOKEN_MAP: [256]u8 = [_]u8{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; fn is_token(c: u8) bool { return TOKEN_MAP[@intCast(usize, c)] != 0; } fn is_restricted_quoted_char(c: u8) bool { return c == 9 or (c > 31 and c != 127); } fn intern_charset_utf8(s: []const u8, slash: usize, semicolon: usize) Source { const top = s[0..slash]; const sub = s[slash + 1 .. semicolon]; if (eql(top, TEXT)) { if (eql(sub, PLAIN)) { return Atom.source(.TEXT_PLAIN_UTF_8); } if (eql(sub, HTML)) { return Atom.source(.TEXT_HTML_UTF_8); } if (eql(sub, CSS)) { return Atom.source(.TEXT_CSS_UTF_8); } if (eql(sub, CSV)) { return Atom.source(.TEXT_CSV_UTF_8); } if (eql(sub, TAB_SEPARATED_VALUES)) { return Atom.source(.TEXT_TAB_SEPARATED_VALUES_UTF_8); } } if (eql(top, APPLICATION)) { if (eql(sub, JAVASCRIPT)) { return Atom.source(.TEXT_PLAIN_UTF_8); } } return Source.dynamic(s); } fn intern_no_params(s: []const u8, slash: usize) Source { const top = s[0..slash]; const sub = s[slash + 1 ..]; switch (slash) { 4 => { if (eql(top, TEXT)) { switch (sub.len) { 1 => { if (sub[0] == '*') { return Atom.source(.TEXT_STAR); } }, 3 => { if (eql(sub, CSS)) { return Atom.source(.TEXT_CSS); } if (eql(sub, XML)) { return Atom.source(.TEXT_XML); } if (eql(sub, CSV)) { return Atom.source(.TEXT_CSV); } }, 4 => { if (eql(sub, HTML)) { return Atom.source(.TEXT_HTML); } }, 5 => { if (eql(sub, PLAIN)) { return Atom.source(.TEXT_PLAIN); } if (eql(sub, VCARD)) { return Atom.source(.TEXT_VCARD); } }, 10 => { if (eql(sub, JAVASCRIPT)) { return Atom.source(.TEXT_JAVASCRIPT); } }, 12 => { if (eql(sub, EVENT_STREAM)) { return Atom.source(.TEXT_EVENT_STREAM); } }, 20 => { if (eql(sub, TAB_SEPARATED_VALUES)) { return Atom.source(.TEXT_TAB_SEPARATED_VALUES); } }, else => {}, } } else if (eql(top, FONT)) { switch (sub.len) { 4 => { if (eql(sub, WOFF)) { return Atom.source(.FONT_WOFF); } }, 5 => { if (eql(sub, WOFF2)) { return Atom.source(.FONT_WOFF2); } }, else => {}, } } }, 5 => { if (eql(top, IMAGE)) { switch (sub.len) { 1 => { if (sub[0] == '*') { return Atom.source(.IMAGE_STAR); } }, 3 => { if (eql(sub, PNG)) { return Atom.source(.IMAGE_PNG); } if (eql(sub, GIF)) { return Atom.source(.IMAGE_GIF); } if (eql(sub, BMP)) { return Atom.source(.IMAGE_BMP); } }, 4 => { if (eql(sub, JPEG)) { return Atom.source(.IMAGE_JPEG); } }, 7 => { if (eql(sub, SVG)) { return Atom.source(.IMAGE_SVG); } }, else => {}, } } else if (eql(top, VIDEO)) { if (sub.len == 1 and sub[0] == '*') { return Atom.source(.VIDEO_STAR); } } else if (eql(top, AUDIO)) { if (sub.len == 1 and sub[0] == '*') { return Atom.source(.AUDIO_STAR); } } }, 11 => { if (eql(top, APPLICATION)) { switch (sub.len) { 3 => { if (eql(sub, PDF)) { return Atom.source(.APPLICATION_PDF); } }, 4 => { if (eql(sub, JSON)) { return Atom.source(.APPLICATION_JSON); } }, 7 => { if (eql(sub, MSGPACK)) { return Atom.source(.APPLICATION_MSGPACK); } }, 10 => { if (eql(sub, JAVASCRIPT)) { return Atom.source(.APPLICATION_JAVASCRIPT); } }, 11 => { if (eql(sub, "dns-message")) { return Atom.source(.APPLICATION_DNS); } }, 13 => { if (eql(sub, OCTET_STREAM)) { return Atom.source(.APPLICATION_OCTET_STREAM); } }, 21 => { if (eql(sub, WWW_FORM_URLENCODED)) { return Atom.source(.APPLICATION_WWW_FORM_URLENCODED); } }, else => {}, } } }, else => {}, } return Source.dynamic(s); } fn intern(s: []const u8, slash: u16, params: InternParams) Source { std.debug.assert(s.len > @intCast(usize, slash)); return switch (params) { .Utf8 => |semicolon| intern_charset_utf8(s, @intCast(usize, slash), semicolon), .None => intern_no_params(s, @intCast(usize, slash)), }; } test "test_lookup_tables" { for (TOKEN_MAP) |c, i| { const should: bool = switch (@truncate(u8, i)) { 'a'...'z', 'A'...'Z', '0'...'9', '!', '#', '$', '%', '&', '\'', '+', '-', '.', '^', '_', '`', '|', '~', => true, else => false, }; try std.testing.expect(@as(bool, c != 0) == should); } } test "text_plain" { const mime = try parse("text/plain", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expect(!mime.has_params()); try std.testing.expectEqualStrings("text/plain", mime.as_ref()); } test "text_plain_uppercase" { const mime = try parse("TEXT/PLAIN", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expect(!mime.has_params()); try std.testing.expectEqualStrings("text/plain", mime.as_ref()); } test "text_plain_charset_utf8" { const mime = try parse("text/plain; charset=utf-8", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); try std.testing.expectEqualStrings("text/plain; charset=utf-8", mime.as_ref()); } test "text_plain_charset_utf8_uppercase" { const mime = try parse("TEXT/PLAIN; CHARSET=UTF-8", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); try std.testing.expectEqualStrings("text/plain; charset=utf-8", mime.as_ref()); } test "text_plain_charset_utf8_quoted" { const mime = try parse("text/plain; charset=\"utf-8\"", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("\"utf-8\"", mime.params_("charset").?); try std.testing.expectEqualStrings("text/plain; charset=\"utf-8\"", mime.as_ref()); } test "text_plain_charset_utf8_extra" { const mime = try parse("text/plain; charset=utf-8; foo=bar", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); try std.testing.expectEqualStrings("bar", mime.params_("foo").?); try std.testing.expectEqualStrings("text/plain; charset=utf-8; foo=bar", mime.as_ref()); } test "text_plain_charset_utf8_extra_uppercase" { const mime = try parse("TEXT/PLAIN; CHARSET=UTF-8; FOO=BAR", true); defer mime.deinit(); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); try std.testing.expectEqualStrings("BAR", mime.params_("foo").?); try std.testing.expectEqualStrings("text/plain; charset=utf-8; foo=BAR", mime.as_ref()); } test "charset_utf8_extra_spaces" { const mime = try parse("text/plain ; charset=utf-8 ; foo=bar", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); try std.testing.expectEqualStrings("bar", mime.params_("foo").?); try std.testing.expectEqualStrings("text/plain ; charset=utf-8 ; foo=bar", mime.as_ref()); } test "subtype_space_before_params" { const mime = try parse("text/plain ; charset=utf-8", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); } test "params_space_before_semi" { const mime = try parse("text/plain; charset=utf-8 ; foo=ba", true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("plain", mime.subtype()); try std.testing.expectEqualStrings("utf-8", mime.params_("charset").?); } test "param_value_empty_quotes" { const mime = try parse("audio/wave; codecs=\"\"", true); try std.testing.expectEqualStrings("audio/wave; codecs=\"\"", mime.as_ref()); } test "semi_colon_but_empty_params" { const cases = [_][]const u8{ "text/event-stream;", "text/event-stream; ", "text/event-stream; ", "text/event-stream ; ", }; for (cases) |case| { const mime = try parse(case, true); try std.testing.expectEqualStrings("text", mime.type_()); try std.testing.expectEqualStrings("event-stream", mime.subtype()); try std.testing.expect(!mime.has_params()); try std.testing.expectEqualStrings("text/event-stream", mime.as_ref()); } } test "error_type_spaces" { try std.testing.expectError(error.InvalidToken, parse("te xt/plain", true)); } test "error_type_lf" { try std.testing.expectError(error.InvalidToken, parse("te\nxt/plain", true)); } test "error_type_cr" { try std.testing.expectError(error.InvalidToken, parse("te\rxt/plain", true)); } test "error_subtype_spaces" { try std.testing.expectError(error.MissingEqual, parse("text/plai n", true)); } test "error_subtype_crlf" { try std.testing.expectError(error.InvalidToken, parse("text/\r\nplain", true)); } test "error_param_name_crlf" { try std.testing.expectError(error.InvalidToken, parse("text/plain;\r\ncharset=utf-8", true)); } test "error_param_value_quoted_crlf" { try std.testing.expectError(error.InvalidToken, parse("text/plain;charset=\"\r\nutf-8\"", true)); } test "error_param_space_before_equals" { try std.testing.expectError(error.InvalidToken, parse("text/plain; charset =utf-8", true)); } test "error_param_space_after_equals" { try std.testing.expectError(error.InvalidToken, parse("text/plain; charset= utf-8", true)); }
https://raw.githubusercontent.com/yukiolabs/mime/4b3b700ad78ef85024c41f083408b94136391d93/src/parse/parse.zig
const std = @import("std"); const Runtime = @import("runtime.zig"); pub const base = @import("ipc/base.zig"); pub const socket = @import("ipc/socket.zig"); pub const Type = base.Type; /// Kinds of IPC instances pub const Kind = enum { socket, }; pub const Params = union(Kind) { socket: socket.Params, pub fn init(comptime kind: Kind) Params { return switch (kind) { .socket => .{ .socket = socket.Params.init(), }, }; } /// A zig-clap compatible parser for generating parameters pub fn parseArgument(arg: []const u8) !Params { inline for (comptime std.meta.fields(Params), comptime std.meta.fields(Kind)) |u_field, e_field| { const arg_kind_sep = if (std.mem.indexOf(u8, arg, ":")) |value| value else arg.len; if (std.mem.eql(u8, arg[0..arg_kind_sep], u_field.name)) { var p = Params.init(@intToEnum(Kind, e_field.value)); const start_index = if (arg_kind_sep + 1 < arg.len) arg_kind_sep + 1 else arg.len; @field(p, u_field.name) = try u_field.type.parseArgument(arg[start_index..]); return p; } } return error.InvalidKind; } pub fn format(self: Params, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void { try writer.writeAll(switch (self) { .socket => "socket", }); try writer.writeByte(':'); return switch (self) { .socket => |s| s.format(fmt, options, writer), }; } }; pub const Ipc = union(Kind) { socket: socket.Ipc, pub fn init(params: Params, runtime: *Runtime, allocator: ?std.mem.Allocator) !Ipc { return switch (params) { .socket => |params_socket| .{ .socket = try socket.Ipc.init(params_socket, runtime, allocator), }, }; } pub fn ref(self: *Ipc, allocator: ?std.mem.Allocator) !Ipc { return switch (self.*) { .socket => .{ .socket = try self.socket.ref(allocator), }, }; } pub fn unref(self: *Ipc) void { return switch (self.*) { .socket => self.socket.unref(), }; } pub fn toBase(self: *Ipc) base.Ipc { return switch (self.*) { .socket => self.socket.toBase(), }; } };
https://raw.githubusercontent.com/ExpidusOS/neutron/65ee6242e8ea42d072dfdaf07ee475d18ae5a3e1/src/neutron/runtime/ipc.zig
const std = @import("std"); const w4 = @import("wasm4.zig"); var frame: u64 = 0; var rng_impl = std.rand.DefaultPrng.init(0xdeadbeef); pub const rng = rng_impl.random(); pub fn update() void { // gather entropy from player inputs if (w4.GAMEPADS[0].v != 0) { rng_impl.s[0] = hash(rng_impl.s[0] ^ w4.GAMEPADS[0].v ^ (frame << 10)); } if (w4.GAMEPADS[1].v != 0) { rng_impl.s[2] = hash(rng_impl.s[2] ^ (@as(u64, w4.GAMEPADS[0].v) << 35) ^ (frame << 24)); } frame +%= 1; } // based on https://stackoverflow.com/a/70620975 pub fn hash(x: u64) u64 { var r = x; r ^= r >> 17; r *= 0xed5ad4bbac4c1b51; r ^= r >> 11; r *= 0xac4c1b5131848bab; r ^= r >> 15; r *= 0x31848babed5ad4bb; r ^= r >> 14; return r; }
https://raw.githubusercontent.com/12Boti/wloku/379277fdad85c9236623da0ef441ad2f1af03f33/src/rng.zig
const std = @import("std"); const base64 = @import("base64"); fn runEncodeBench(use_std: bool) !usize { var file = try std.fs.cwd().openFile("./benchmark/testdata/encode-test-data", .{}); defer file.close(); var buf_reader = std.io.bufferedReader(file.reader()); var in_stream = buf_reader.reader(); var buf: [1024]u8 = undefined; var out: [2048]u8 = undefined; var count: usize = 0; while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { const s = if (use_std) blk: { break :blk std.base64.standard.Encoder.encode(&out, line); } else blk: { break :blk base64.b64encode(line, &out, .default); }; _ = s; // std.debug.print("{s}\n", .{s}); count += 1; } return count; } fn runDecodeBench(use_std: bool) !usize { var file = try std.fs.cwd().openFile("./benchmark/testdata/decode-test-data", .{}); defer file.close(); var buf_reader = std.io.bufferedReader(file.reader()); var in_stream = buf_reader.reader(); var buf: [2048]u8 = undefined; var out: [2048]u8 = undefined; var count: usize = 0; while (try in_stream.readUntilDelimiterOrEof(&buf, '\n')) |line| { if (use_std) { // const length = try std.base64.standard.Decoder.calcSizeForSlice(line); try std.base64.standard.Decoder.decode(&out, line); // break :blk out[0..length]; } else { _ = try base64.b64decode(line, &out, .default); } count += 1; } return count; } pub fn main() !void { if (std.os.argv.len < 3) { std.debug.print("{s}\n", .{ \\Run with: \\--encode --std \\--encode --simd }); std.os.exit(1); } if (std.mem.eql(u8, std.mem.span(std.os.argv[1]), "--encode")) { if (std.mem.eql(u8, std.mem.span(std.os.argv[2]), "--std")) { std.debug.print("Start the std encoding benchmark\n", .{}); _ = try runEncodeBench(true); } else { std.debug.print("Start the simd encoding benchmark\n", .{}); _ = try runEncodeBench(false); } } else if (std.mem.eql(u8, std.mem.span(std.os.argv[1]), "--decode")) { if (std.mem.eql(u8, std.mem.span(std.os.argv[2]), "--std")) { std.debug.print("Start the std decoding benchmark\n", .{}); _ = try runDecodeBench(true); } else { std.debug.print("Start the simd decoding benchmark\n", .{}); _ = try runDecodeBench(false); } } }
https://raw.githubusercontent.com/dying-will-bullet/base64-simd/ac5bb035e131548cdd0f7924d55e391c39aef1d3/benchmark/main.zig
const std = @import("std"); const uefi = std.os.uefi; const io = std.io; const Guid = uefi.Guid; const Time = uefi.Time; const Status = uefi.Status; pub const FileProtocol = extern struct { revision: u64, _open: fn (*const FileProtocol, **const FileProtocol, [*:0]const u16, u64, u64) callconv(.C) Status, _close: fn (*const FileProtocol) callconv(.C) Status, _delete: fn (*const FileProtocol) callconv(.C) Status, _read: fn (*const FileProtocol, *usize, [*]u8) callconv(.C) Status, _write: fn (*const FileProtocol, *usize, [*]const u8) callconv(.C) Status, _get_position: fn (*const FileProtocol, *u64) callconv(.C) Status, _set_position: fn (*const FileProtocol, u64) callconv(.C) Status, _get_info: fn (*const FileProtocol, *align(8) const Guid, *const usize, [*]u8) callconv(.C) Status, _set_info: fn (*const FileProtocol, *align(8) const Guid, usize, [*]const u8) callconv(.C) Status, _flush: fn (*const FileProtocol) callconv(.C) Status, pub const SeekError = error{SeekError}; pub const GetSeekPosError = error{GetSeekPosError}; pub const ReadError = error{ReadError}; pub const WriteError = error{WriteError}; pub const SeekableStream = io.SeekableStream(*const FileProtocol, SeekError, GetSeekPosError, seekTo, seekBy, getPos, getEndPos); pub const Reader = io.Reader(*const FileProtocol, ReadError, readFn); pub const Writer = io.Writer(*const FileProtocol, WriteError, writeFn); pub fn seekableStream(self: *FileProtocol) SeekableStream { return .{ .context = self }; } pub fn reader(self: *FileProtocol) Reader { return .{ .context = self }; } pub fn writer(self: *FileProtocol) Writer { return .{ .context = self }; } pub fn open(self: *const FileProtocol, new_handle: **const FileProtocol, file_name: [*:0]const u16, open_mode: u64, attributes: u64) Status { return self._open(self, new_handle, file_name, open_mode, attributes); } pub fn close(self: *const FileProtocol) Status { return self._close(self); } pub fn delete(self: *const FileProtocol) Status { return self._delete(self); } pub fn read(self: *const FileProtocol, buffer_size: *usize, buffer: [*]u8) Status { return self._read(self, buffer_size, buffer); } fn readFn(self: *const FileProtocol, buffer: []u8) ReadError!usize { var size: usize = buffer.len; if (.Success != self.read(&size, buffer.ptr)) return ReadError.ReadError; return size; } pub fn write(self: *const FileProtocol, buffer_size: *usize, buffer: [*]const u8) Status { return self._write(self, buffer_size, buffer); } fn writeFn(self: *const FileProtocol, bytes: []const u8) WriteError!usize { var size: usize = bytes.len; if (.Success != self.write(&size, bytes.ptr)) return WriteError.WriteError; return size; } pub fn getPosition(self: *const FileProtocol, position: *u64) Status { return self._get_position(self, position); } fn getPos(self: *const FileProtocol) GetSeekPosError!u64 { var pos: u64 = undefined; if (.Success != self.getPosition(&pos)) return GetSeekPosError.GetSeekPosError; return pos; } fn getEndPos(self: *const FileProtocol) GetSeekPosError!u64 { // preserve the old file position var pos: u64 = undefined; if (.Success != self.getPosition(&pos)) return GetSeekPosError.GetSeekPosError; // seek to end of file to get position = file size if (.Success != self.setPosition(efi_file_position_end_of_file)) return GetSeekPosError.GetSeekPosError; // restore the old position if (.Success != self.setPosition(pos)) return GetSeekPosError.GetSeekPosError; // return the file size = position return pos; } pub fn setPosition(self: *const FileProtocol, position: u64) Status { return self._set_position(self, position); } fn seekTo(self: *const FileProtocol, pos: u64) SeekError!void { if (.Success != self.setPosition(pos)) return SeekError.SeekError; } fn seekBy(self: *const FileProtocol, offset: i64) SeekError!void { // save the old position and calculate the delta var pos: u64 = undefined; if (.Success != self.getPosition(&pos)) return SeekError.SeekError; const seek_back = offset < 0; const amt = std.math.absCast(offset); if (seek_back) { pos += amt; } else { pos -= amt; } if (.Success != self.setPosition(pos)) return SeekError.SeekError; } pub fn getInfo(self: *const FileProtocol, information_type: *align(8) const Guid, buffer_size: *usize, buffer: [*]u8) Status { return self._get_info(self, information_type, buffer_size, buffer); } pub fn setInfo(self: *const FileProtocol, information_type: *align(8) const Guid, buffer_size: usize, buffer: [*]const u8) Status { return self._set_info(self, information_type, buffer_size, buffer); } pub fn flush(self: *const FileProtocol) Status { return self._flush(self); } pub const guid align(8) = Guid{ .time_low = 0x09576e92, .time_mid = 0x6d3f, .time_high_and_version = 0x11d2, .clock_seq_high_and_reserved = 0x8e, .clock_seq_low = 0x39, .node = [_]u8{ 0x00, 0xa0, 0xc9, 0x69, 0x72, 0x3b }, }; pub const efi_file_mode_read: u64 = 0x0000000000000001; pub const efi_file_mode_write: u64 = 0x0000000000000002; pub const efi_file_mode_create: u64 = 0x8000000000000000; pub const efi_file_read_only: u64 = 0x0000000000000001; pub const efi_file_hidden: u64 = 0x0000000000000002; pub const efi_file_system: u64 = 0x0000000000000004; pub const efi_file_reserved: u64 = 0x0000000000000008; pub const efi_file_directory: u64 = 0x0000000000000010; pub const efi_file_archive: u64 = 0x0000000000000020; pub const efi_file_valid_attr: u64 = 0x0000000000000037; pub const efi_file_position_end_of_file: u64 = 0xffffffffffffffff; }; pub const FileInfo = extern struct { size: u64, file_size: u64, physical_size: u64, create_time: Time, last_access_time: Time, modification_time: Time, attribute: u64, pub fn getFileName(self: *const FileInfo) [*:0]const u16 { return @as([*:0]const u16, @ptrCast(@as([*]const u8, @ptrCast(self)) + @sizeOf(FileInfo))); } pub const efi_file_read_only: u64 = 0x0000000000000001; pub const efi_file_hidden: u64 = 0x0000000000000002; pub const efi_file_system: u64 = 0x0000000000000004; pub const efi_file_reserved: u64 = 0x0000000000000008; pub const efi_file_directory: u64 = 0x0000000000000010; pub const efi_file_archive: u64 = 0x0000000000000020; pub const efi_file_valid_attr: u64 = 0x0000000000000037; };
https://raw.githubusercontent.com/ziglang/gotta-go-fast/c915c45c5afed9a2e2de4f4484acba2df5090c3a/src/self-hosted-parser/input_dir/os/uefi/protocols/file_protocol.zig
const std = @import("std"); const Entities = @import("Entities.zig"); const Entity = @import("Entity.zig"); const World = @import("World.zig"); fn isQueryItemPointer(comptime T: type) bool { switch (@typeInfo(T)) { .Pointer => |pointer| return pointer.size == .One and !pointer.is_const, else => return false, } } fn QueryItemComponent(comptime T: type) type { if (isQueryItemPointer(T)) { return @typeInfo(T).Pointer.child; } else { return T; } } const EntityQueryItem = struct { pub const State = void; pub fn initState(world: *World) !State { _ = world; return {}; } pub fn contains(world: *World, state: State, entity: Entity) bool { _ = world; _ = state; _ = entity; return true; } pub fn fetch(world: *World, state: State, entity: Entity) ?Entity { _ = world; _ = state; return entity; } }; pub fn QueryItem(comptime T: type) type { if (T == Entity) { return EntityQueryItem; } const C = QueryItemComponent(T); return struct { pub const State = Entities.Storage; pub fn initState(world: *World) !State { return try world.entities.registerComponent(C); } pub fn contains(world: *World, state: State, entity: Entity) bool { return world.entities.containsComponentRegistered(state, entity); } pub fn fetch(world: *World, state: State, entity: Entity) ?T { const ptr = world.entities.getComponentRegistered(state, entity, C) orelse return null; if (comptime isQueryItemPointer(T)) { return ptr; } return ptr.*; } }; } pub fn With(comptime C: type) type { return struct { pub const FilterState = Entities.Storage; pub fn initState(world: *World) !FilterState { return try world.entities.registerComponent(C); } pub fn filter(world: *World, state: FilterState, entity: Entity) bool { return world.entities.containsComponentRegistered(state, entity); } }; } pub fn Without(comptime C: type) type { return struct { pub const FilterState = Entities.Storage; pub fn initState(world: *World) !FilterState { return try world.entities.registerComponent(C); } pub fn filter(world: *World, state: FilterState, entity: Entity) bool { return !world.entities.containsComponentRegistered(state, entity); } }; } pub fn FilterItem(comptime T: type) type { return struct { pub const State = T.FilterState; pub fn initState(world: *World) !State { return T.initState(world); } pub fn filter(world: *World, state: State, entity: Entity) bool { return T.filter(world, state, entity); } }; } pub fn Query(comptime Q: type) type { return QueryFilter(Q, .{}); } pub fn QueryFilter(comptime Q: type, comptime F: anytype) type { const query_info = @typeInfo(Q); if (query_info != .Struct) { @compileError("Query must be a struct with named fields"); } const query_struct = query_info.Struct; comptime var query_state_fields: []const std.builtin.Type.StructField = &.{}; comptime var query_filter_fields: []const std.builtin.Type.StructField = &.{}; for (query_struct.fields) |field| { const Item = QueryItem(field.type); const state_field = std.builtin.Type.StructField{ .name = field.name, .type = Item.State, .default_value = null, .is_comptime = false, .alignment = 0, }; query_state_fields = query_state_fields ++ .{state_field}; } for (F, 0..) |field, i| { const Item = FilterItem(field); const filter_field = std.builtin.Type.StructField{ .name = std.fmt.comptimePrint("{}", .{i}), .type = Item.State, .default_value = null, .is_comptime = false, .alignment = 0, }; query_filter_fields = query_filter_fields ++ .{filter_field}; } return struct { const Self = @This(); /// The state of the query. pub const State = struct { query: @Type(std.builtin.Type{ .Struct = .{ .layout = .auto, .fields = query_state_fields, .decls = &.{}, .is_tuple = false, }, }), filter: @Type(std.builtin.Type{ .Struct = .{ .layout = .auto, .fields = query_filter_fields, .decls = &.{}, .is_tuple = true, }, }), }; pub const SystemParamState = State; world: *World, state: State, /// Initialize the `State`, `world` **must** be the same as the `world` used to create the query /// or segmentation faults will be on the menu. pub fn initState(world: *World) !State { var state: State = undefined; inline for (query_struct.fields) |field| { const Item = QueryItem(field.type); @field(state.query, field.name) = try Item.initState(world); } inline for (F, 0..) |field, i| { const Item = FilterItem(field); state.filter[i] = try Item.initState(world); } return state; } pub fn systemParamInit(world: *World) !SystemParamState { return initState(world); } pub fn systemParamFetch(world: *World, state: *SystemParamState) !Self { return world.queryFilter(Q, F, state.*); } pub fn systemParamApply(world: *World, state: *SystemParamState) !void { _ = state; _ = world; } /// Check if the query contains the given `entity`. /// /// This ensuses that `fetch` will not return `null` for the given `entity`. pub fn contains(self: *const Self, entity: Entity) bool { inline for (query_struct.fields) |field| { const Item = QueryItem(field.type); const state = @field(self.state.query, field.name); if (!Item.contains(self.world, state, entity)) { return false; } } inline for (F, 0..) |field, i| { const Item = FilterItem(field); const state = self.state.filter[i]; if (!Item.filter(self.world, state, entity)) { return false; } } return true; } /// Fetch the query for the given `entity`. pub fn fetch(self: *const Self, entity: Entity) ?Q { var query: Q = undefined; inline for (F, 0..) |field, i| { const Item = FilterItem(field); const state = self.state.filter[i]; if (!Item.filter(self.world, state, entity)) { return null; } } inline for (query_struct.fields) |field| { const Item = QueryItem(field.type); const state = @field(self.state.query, field.name); const item = Item.fetch(self.world, state, entity) orelse return null; @field(query, field.name) = item; } return query; } pub const Iterator = struct { query: *const Self, it: Entities.EntityIterator, pub fn next(self: *Iterator) ?Q { while (self.it.next()) |entity| { return self.query.fetch(entity) orelse continue; } return null; } }; /// Create an iterator over the query. pub fn iterator(self: *const Self) Iterator { return Iterator{ .query = self, .it = self.world.entities.entityIterator(), }; } }; } /// Get the `State` associated with the given `Query` for type `Q`. /// /// This is a shorthand for `Query(Q).State`. pub fn QueryState(comptime Q: type) type { return QueryFilterState(Q, .{}); } pub fn QueryFilterState(comptime Q: type, comptime filter: anytype) type { return QueryFilter(Q, filter).State; }
https://raw.githubusercontent.com/Sudoku-Boys/Sudoku/218ea16ecc86507698861b59a496ff178a7a7587/src/engine/query.zig
const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; const c = @cImport({ @cInclude("raylib.h"); @cInclude("iconset.rgi.h"); @cDefine("RAYGUI_CUSTOM_ICONS", ""); @cDefine("RAYGUI_IMPLEMENTATION", ""); @cInclude("raygui.h"); }); state: State, pixel_size: usize, selected_tool: c_int = 0, materials: [n_materials]Material = .{ Material.water, Material.slime, Material.nitro, Material.sand, Material.heavy, }, brush_size: c_int = 3, raining: bool = false, rain_frequency: f32 = 0.1, rng: std.rand.DefaultPrng, const App = @This(); const control_size = 50; const n_materials = 5; const tools_string = tools_string: { var tools: [:0]const u8 = std.fmt.comptimePrint("#{}#", .{c.ICON_CURSOR_HAND}); for (1..n_materials + 1) |n| { tools = tools ++ std.fmt.comptimePrint(";{}", .{n}); } break :tools_string tools; }; fn init( allocator: Allocator, width: usize, height: usize, pixel_size: usize, ) !App { var state = try State.init(allocator, width, height); errdefer state.deinit(allocator); return .{ .state = state, .pixel_size = pixel_size, .rng = std.rand.DefaultPrng.init(@bitCast(std.time.timestamp())), }; } fn deinit(app: *App, allocator: Allocator) void { app.state.deinit(allocator); app.* = undefined; } fn open(app: App) void { c.InitWindow( @intCast(app.state.width * app.pixel_size), @intCast(@divExact(app.state.cells.len, app.state.width) * app.pixel_size + control_size), "Ripple Garden", ); c.SetTargetFPS(60); c.GuiSetStyle(c.TOGGLE, c.GROUP_PADDING, 0); } fn close(_: App) void { c.CloseWindow(); } fn shouldClose(_: App) bool { return c.WindowShouldClose(); } fn handleInput(app: *App) void { const state_width = app.state.width; const state_height = @divExact(app.state.cells.len, state_width); const pixel_size_int: c_int = @intCast(app.pixel_size); if (c.IsMouseButtonDown(c.MOUSE_BUTTON_LEFT)) { const mouse_x = @divFloor(c.GetMouseX(), pixel_size_int); const mouse_y = @divFloor(c.GetMouseY(), pixel_size_int); if (mouse_x >= 0 and mouse_x < state_width and mouse_y >= 0 and mouse_y < state_height) { if (app.selected_tool == 0) { app.state.doBrush( usize, mouse_x, mouse_y, @intCast(app.brush_size), makeRipple, @intCast(app.brush_size), ); } else { app.state.doBrush( Material, mouse_x, mouse_y, @intCast(app.brush_size), makeMaterial, app.materials[@intCast(app.selected_tool - 1)], ); } } } for (0..n_materials + 1) |i| { if (c.IsKeyPressed(c.KEY_ZERO + @as(c_int, @intCast(i)))) { app.selected_tool = @intCast(i); } } if (app.raining and app.rng.random().float(f32) < app.rain_frequency) { const x = app.rng.random().uintLessThan(usize, state_width); const y = app.rng.random().uintLessThan(usize, state_height); const size = app.rng.random().uintLessThan(usize, 4); app.state.doBrush( usize, @intCast(x), @intCast(y), @intCast(size), makeRipple, @intCast(size), ); } } fn makeMaterial(state: *State, x: usize, y: usize, _: f32, material: Material) void { state.cells.items(.material)[state.index(x, y)] = material; } fn makeRipple(state: *State, x: usize, y: usize, dist: f32, brush_size: usize) void { const h = &state.cells.items(.h)[state.index(x, y)]; h.* = @min(h.*, -1.0 + dist / @as(f32, @floatFromInt(brush_size))); } fn draw(app: *App) void { const state_width = app.state.width; const state_height = @divExact(app.state.cells.len, state_width); c.BeginDrawing(); defer c.EndDrawing(); c.ClearBackground(c.GetColor(@bitCast(c.GuiGetStyle(c.DEFAULT, c.BACKGROUND_COLOR)))); for (0..state_width) |x| { for (0..state_height) |y| { const cell = app.state.get(x, y); c.DrawRectangle( @intCast(x * app.pixel_size), @intCast(y * app.pixel_size), @intCast(app.pixel_size), @intCast(app.pixel_size), cell.material.color(cell.h), ); } } c.GuiSetIconScale(2); defer c.GuiSetIconScale(1); const original_text_size = c.GuiGetStyle(c.DEFAULT, c.TEXT_SIZE); c.GuiSetStyle(c.DEFAULT, c.TEXT_SIZE, original_text_size * 2); defer c.GuiSetStyle(c.DEFAULT, c.TEXT_SIZE, original_text_size); _ = c.GuiToggleGroup(.{ .x = 0, .y = @floatFromInt(state_height * app.pixel_size), .height = control_size, .width = control_size, }, tools_string, &app.selected_tool); for (app.materials, 1..) |material, i| { c.DrawRectangle( @intCast(i * control_size + 4), @intCast(state_height * app.pixel_size + 4), 8, 8, material.color(0.0), ); } _ = c.GuiSpinner(.{ .x = @floatFromInt((n_materials + 1) * control_size), .y = @floatFromInt(state_height * app.pixel_size), .height = control_size, .width = 2 * control_size, }, "", &app.brush_size, 1, 20, false); _ = c.GuiToggle(.{ .x = @floatFromInt(state_width * app.pixel_size - control_size), .y = @floatFromInt(state_height * app.pixel_size), .height = control_size, .width = control_size, }, std.fmt.comptimePrint("#{}#", .{c.ICON_RAIN}), &app.raining); } const Material = struct { /// Mass. Higher masses will result in less acceleration from displacement /// (F = ma). Must be greater than 0.0. m: f32, /// Viscosity. Higher viscosities will proportionally slow velocity. Must /// be between 0.0 and 1.0, inclusive. visc: f32, /// Hue (color component). Must be between 0.0 (inclusive) and 360.0 /// (exclusive). hue: f32, /// Value (color component). Must be between 0.0 and 1.0, inclusive. value: f32, pub const water: Material = .{ .m = 1.0, .visc = 0.01, .hue = 240.0, .value = 1.0, }; pub const slime: Material = .{ .m = 5.0, .visc = 0.5, .hue = 120.0, .value = 0.75, }; pub const nitro: Material = .{ .m = 10.0, .visc = 0.0, .hue = 0.0, .value = 0.9, }; pub const sand: Material = .{ .m = 1.0, .visc = 1.0, .hue = 60.0, .value = 0.9, }; pub const heavy: Material = .{ .m = 100.0, .visc = 0.001, .hue = 300.0, .value = 0.9, }; pub fn color(material: Material, height: f32) c.Color { return c.ColorFromHSV( material.hue, 1.0 - (height + 1.0) / 2.0, material.value, ); } }; const Cell = struct { /// Height. Must be between -1.0 and 1.0, inclusive. h: f32 = 0.0, /// Velocity. v: f32 = 0.0, /// Acceleration. Recomputed on every step. a: f32 = 0.0, material: Material = Material.water, }; const State = struct { cells: std.MultiArrayList(Cell), width: usize, pub fn init(allocator: Allocator, width: usize, height: usize) Allocator.Error!State { var cells: std.MultiArrayList(Cell) = .{}; try cells.setCapacity(allocator, width * height); for (0..cells.capacity) |_| { cells.appendAssumeCapacity(.{}); } return .{ .cells = cells, .width = width, }; } pub fn deinit(state: *State, allocator: Allocator) void { state.cells.deinit(allocator); state.* = undefined; } pub fn index(state: State, x: usize, y: usize) usize { return y * state.width + x; } pub fn get(state: State, x: usize, y: usize) Cell { return state.cells.get(state.index(x, y)); } pub fn doBrush( state: *State, comptime Ctx: type, center_x: isize, center_y: isize, brush_size: usize, action: fn (state: *State, x: usize, y: usize, dist: f32, ctx: Ctx) void, ctx: Ctx, ) void { const width = state.width; const height = @divExact(state.cells.len, width); var x_offset: isize = -@as(isize, @intCast(brush_size)); while (x_offset <= brush_size) : (x_offset += 1) { var y_offset: isize = -@as(isize, @intCast(brush_size)); while (y_offset <= brush_size) : (y_offset += 1) { const x = center_x + x_offset; const y = center_y + y_offset; const dist = std.math.hypot(f32, @floatFromInt(x_offset), @floatFromInt(y_offset)); if (x >= 0 and x < width and y >= 0 and y < height and dist <= @as(f32, @floatFromInt(brush_size))) { action(state, @intCast(x), @intCast(y), dist, ctx); } } } } pub fn step(state: *State) void { const width = state.width; const height = @divExact(state.cells.len, width); const hs = state.cells.items(.h); const vs = state.cells.items(.v); const as = state.cells.items(.a); const materials = state.cells.items(.material); for (0..width) |x| { for (0..height) |y| { var disp: f32 = -8.0 * hs[state.index(x, y)]; if (x > 0) { disp += hs[state.index(x - 1, y)]; if (y > 0) { disp += hs[state.index(x - 1, y - 1)]; } if (y < height - 1) { disp += hs[state.index(x - 1, y + 1)]; } } if (x < width - 1) { disp += hs[state.index(x + 1, y)]; if (y > 0) { disp += hs[state.index(x + 1, y - 1)]; } if (y < height - 1) { disp += hs[state.index(x + 1, y + 1)]; } } if (y > 0) { disp += hs[state.index(x, y - 1)]; } if (y < height - 1) { disp += hs[state.index(x, y + 1)]; } as[state.index(x, y)] = disp / 8.0 / materials[state.index(x, y)].m; } } for (hs, vs, as, materials) |*h, *v, *a, material| { v.* += a.*; v.* -= material.visc * v.*; h.* += v.*; h.* = @max(-1.0, @min(h.*, 1.0)); } } }; pub fn main() !void { var app = try App.init(std.heap.c_allocator, 300, 300, 3); defer app.deinit(std.heap.c_allocator); app.open(); defer app.close(); while (!app.shouldClose()) { app.state.step(); app.handleInput(); app.draw(); } }
https://raw.githubusercontent.com/ianprime0509/ripple-garden/f25d88738d31874656d29cebd4767dabef4cc897/src/App.zig
const std = @import("std"); const Builder = std.build.Builder; const Pkg = std.build.Pkg; pub fn build(b: *Builder) void { // Standard target options allows the person running `zig build` to choose // what target to build for. Here we do not override the defaults, which // means any target is allowed, and the default is native. Other options // for restricting supported target set are available. const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); const exe = b.addExecutable("bruh", "src/main.zig"); exe.addPackage(.{ .name = "irc", .path = "../../src/main.zig", .dependencies = &[_]Pkg{.{ .name = "network", .path = "../../zig-network/network.zig" }} }); exe.setTarget(target); exe.setBuildMode(mode); exe.install(); const run_cmd = exe.run(); run_cmd.step.dependOn(b.getInstallStep()); const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
https://raw.githubusercontent.com/haze/zirconium/44f8ab6eab755c8b4a8d6a527099bdae3aaacdd6/examples/bruh/build.zig
const std = @import("std"); const expect = std.testing.expect; fn parseString(comptime string: []const u8) usize { comptime { var i: usize = 0; for (string, 0..) |char, pos| { if (char == '$') i += 1; _ = pos; } return i; } } test "parsing string at comptime" { const count = comptime parseString("$$$$"); try expect(count == 4); }
https://raw.githubusercontent.com/jacksonmowry/jacksonmowry.github.io/40f9a0d2df7da0cf17b77eb4a8108584ac3e5e27/zig/string_parsing.zig
// // Now let's create a function that takes a parameter. Here's an // example that takes two parameters. As you can see, parameters // are declared just like any other types ("name": "type"): // // fn myFunction(number: u8, is_lucky: bool) { // ... // } // const std = @import("std"); pub fn main() void { std.debug.print("Powers of two: {} {} {} {}\n", .{ twoToThe(1), twoToThe(2), twoToThe(3), twoToThe(4), }); } // Please give this function the correct input parameter(s). // You'll need to figure out the parameter name and type that we're // expecting. The output type has already been specified for you. // fn twoToThe(???) u32 { return std.math.pow(u32, 2, my_number); // std.math.pow(type, a, b) takes a numeric type and two numbers // of that type and returns "a to the power of b" as that same // numeric type. }
https://raw.githubusercontent.com/samwho/ziglings/3c59fe9a6e341e04eaa154c047ce5d861a44ea8c/exercises/019_functions2.zig
const std = @import("std"); const builtin = @import("biiltin"); const Writer = struct { ptr: *anyopaque, writeAllFn: *const fn (ptr: *anyopaque, data: []const u8) anyerror!void, fn init(ptr: anytype) Writer { const T = @TypeOf(ptr); const ptr_info = @typeInfo(T); if (ptr_info != .Pointer) @compileError("ptr must be a pointer"); if (ptr_info.Pointer.size != .One) @compileError("ptr must be a single item pointer"); const gen = struct { pub fn writeAll(pointer: *anyopaque, data: []const u8) anyerror!void { const self: *File = @ptrCast(@alignCast(pointer)); try @call(.always_inline, ptr_info.Pointer.child.writeAll, .{ self, data }); } }; return .{ .ptr = ptr, .writeAllFn = gen.writeAll, }; } fn writeAll(self: Writer, data: []const u8) !void { return self.writeAllFn(self.ptr, data); } }; const File = struct { fd: std.os.fd_t, fn writeAll(self: *File, data: []const u8) !void { _ = try std.os.write(self.fd, data); } fn writer(self: *File) Writer { return Writer.init(self); } }; pub fn main() !void { var file = File{ .fd = std.io.getStdOut().handle }; const out = file.writer(); try out.writeAll("hello\n"); }
https://raw.githubusercontent.com/rsphing/algo.zig/66b4ddfcc48f9cd006e5f726145f2408b55a7848/interface.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const StringHashMap = std.StringHashMap; const mem = std.mem; const Dependency = @import("Dependency.zig"); const Entry = StringHashMap(Dependency).Entry; pub fn write(alloc: Allocator, out: anytype, deps: StringHashMap(Dependency)) !void { try out.writeAll( \\# generated by zon2nix (https://github.com/nix-community/zon2nix) \\ \\{ linkFarm, fetchzip }: \\ \\linkFarm "zig-packages" [ \\ ); const len = deps.count(); var entries = try alloc.alloc(Entry, len); var iter = deps.iterator(); for (0..len) |i| { entries[i] = iter.next().?; } mem.sortUnstable(Entry, entries, {}, lessThan); for (entries) |entry| { const key = entry.key_ptr.*; const dep = entry.value_ptr.*; try out.print( \\ {{ \\ name = "{s}"; \\ path = fetchzip {{ \\ url = "{s}"; \\ hash = "{s}"; \\ }}; \\ }} \\ , .{ key, dep.url, dep.nix_hash }); } try out.writeAll("]\n"); } fn lessThan(_: void, lhs: Entry, rhs: Entry) bool { return mem.order(u8, lhs.key_ptr.*, rhs.key_ptr.*) == .lt; }
https://raw.githubusercontent.com/nix-community/zon2nix/4394c25250810fdeb9559f3cda7a08226ce6e5a7/src/codegen.zig
const std = @import("std"); const za = @import("zalgebra"); const gl = @import("../web/webgl.zig"); const Vec3 = za.Vec3; const Mat4 = za.Mat4; const Plane = @import("../math.zig").Plane; const ShaderInfo = @import("../Model.zig").ShaderInfo; const Map = @import("../Map.zig"); const Actor = @import("Actor.zig"); const World = @import("../World.zig"); pub const Solid = @This(); pub const Face = struct { plane: Plane, vertex_start: usize, vertex_count: usize, }; actor: Actor, collidable: bool = true, model: Map.Model, vertices: std.ArrayList(Vec3), faces: std.ArrayList(Face), pub const vtable = Actor.Interface.VTable{ // TODO: connect to Actor // .deinit = deinit, .draw = draw, }; pub fn create(world: *World) !*Solid { const solid = try world.allocator.create(Solid); solid.* = .{ .actor = .{ .world = world, .local_bounds = undefined, // calculated by Map }, .model = undefined, .vertices = undefined, .faces = undefined, }; return solid; } pub fn deinit(ptr: *anyopaque, allocator: std.mem.Allocator) void { const self: *Solid = @alignCast(@ptrCast(ptr)); self.vertices.deinit(); self.faces.deinit(); allocator.destroy(self); } pub fn moveTo(self: *Solid, target: Vec3) void { const delta = target.sub(self.actor.position); // if (self.collidable) { // if (delta.length_squared() > 0.001) { // for (world.all("i_ride_platforms")) |actor| { // if (actor == self) // continue; // if (rider.riding_platform_check(this)) { // collidable = false; // rider.riding_platform_set_velocity(velocity); // rider.riding_platform_moved(delta); // collidable = true; // } // } // position += delta; // } // } else { self.actor.position = self.actor.position.add(delta); // } } pub fn draw(ptr: *anyopaque, si: ShaderInfo) void { const self: *Solid = @alignCast(@ptrCast(ptr)); const model_mat = Mat4.fromTranslate(self.actor.position); gl.glUniformMatrix4fv(si.model_loc, 1, gl.GL_FALSE, &model_mat.data[0]); self.model.draw(); }
https://raw.githubusercontent.com/fabioarnold/3d-game/ea0ad17d23cedfa9008b25f8a1dd35eb0fc4773f/src/actors/Solid.zig
const std = @import("std"); pub fn main() void { std.debug.print("Powers of two: {} {} {} {}\n", .{ twoToThe(1), twoToThe(2), twoToThe(3), twoToThe(4), }); } fn twoToThe(my_number: u32) u32 { return std.math.pow(u32, 2, my_number); }
https://raw.githubusercontent.com/4klabs/ziglings/0538ef97f1fea0b54c1b2c5be013a52e3066fc06/exercises/019_functions2.zig
const std = @import("std"); //lib base. const c = @import("c.zig"); //import all C lib declared. const AllocatorManager = @import("allocator_manager.zig").AllocatorManager; pub fn ValuePrintable(comptime type_send: type) type { return struct { value: type_send = undefined, texture: *c.SDL_Texture = undefined, renderer: *c.SDL_Renderer = undefined, pub fn init(self: *@This(), value_send: type_send, renderer_send: *c.SDL_Renderer) void { self.value = value_send; self.renderer = renderer_send; self.makeTexture() catch { return; }; } pub fn get(self: @This()) type_send { return self.value; } pub fn set(self: *@This(), value_set: type_send) void { if (self.value == value_set) return; self.value = value_set; self.makeTexture() catch { return; }; } fn makeTexture(self: *@This()) !void { if (@typeInfo(@TypeOf(self.value)) == .Optional) { //check if value is nullable. if (self.value == null) { //check if value is null. try self.makeTextureNull(); return; } try self.makeTextureNullable(); return; } //cast value to string. const str_canvas = "{d:.1}{c}"; const size_buffer_str = @as(usize, @intCast(std.fmt.count( str_canvas, .{ self.value, 0 }, ))); const buffer_str = try AllocatorManager.allocator.alloc(u8, size_buffer_str); defer AllocatorManager.allocator.free(buffer_str); const value_str: []u8 = try std.fmt.bufPrint( buffer_str, str_canvas, .{ self.value, 0, }, ); //make texture from value_string. const font: *c.TTF_Font = c.TTF_OpenFont("assets/menu/font/emmasophia.ttf", 25) orelse { std.log.err("error to open font TTF : {s}", .{c.TTF_GetError()}); return error.errorTTFopenFont; }; const color_text: c.SDL_Color = .{ .r = 255, .g = 255, .b = 255, .a = 255, }; const surface_text = c.TTF_RenderText_Solid( //Blended. font, @ptrCast(value_str), color_text, ); defer c.SDL_FreeSurface(surface_text); self.texture = c.SDL_CreateTextureFromSurface(self.renderer, surface_text) orelse { return error.errorCreateTextureSDL; }; } fn makeTextureNullable(self: *@This()) !void { //cast value to string. const str_canvas = "{?d:.1}{c}"; const size_buffer_str = @as(usize, @intCast(std.fmt.count( str_canvas, .{ self.value, 0 }, ))); const buffer_str = try AllocatorManager.allocator.alloc(u8, size_buffer_str); defer AllocatorManager.allocator.free(buffer_str); const value_str: []u8 = try std.fmt.bufPrint( buffer_str, str_canvas, .{ self.value, 0, }, ); //make texture from value_string. const font: *c.TTF_Font = c.TTF_OpenFont("assets/menu/font/emmasophia.ttf", 25) orelse { std.log.err("error to open font TTF : {s}", .{c.TTF_GetError()}); return error.errorTTFopenFont; }; const color_text: c.SDL_Color = .{ .r = 255, .g = 255, .b = 255, .a = 255, }; const surface_text = c.TTF_RenderText_Solid( //Blended. font, @ptrCast(value_str), color_text, ); defer c.SDL_FreeSurface(surface_text); self.texture = c.SDL_CreateTextureFromSurface(self.renderer, surface_text) orelse { return error.errorCreateTextureSDL; }; } fn makeTextureNull(self: *@This()) !void { //cast value to string. const str_canvas = "{s}{c}"; const size_buffer_str = @as(usize, @intCast(std.fmt.count( str_canvas, .{ "null", 0 }, ))); const buffer_str = try AllocatorManager.allocator.alloc(u8, size_buffer_str); defer AllocatorManager.allocator.free(buffer_str); const value_str: []u8 = try std.fmt.bufPrint( buffer_str, str_canvas, .{ "null", 0, }, ); //make texture from value_string. const font: *c.TTF_Font = c.TTF_OpenFont("assets/menu/font/emmasophia.ttf", 25) orelse { std.log.err("error to open font TTF : {s}", .{c.TTF_GetError()}); return error.errorTTFopenFont; }; const color_text: c.SDL_Color = .{ .r = 255, .g = 255, .b = 255, .a = 255, }; const surface_text = c.TTF_RenderText_Solid( //Blended. font, @ptrCast(value_str), color_text, ); defer c.SDL_FreeSurface(surface_text); self.texture = c.SDL_CreateTextureFromSurface(self.renderer, surface_text) orelse { return error.errorCreateTextureSDL; }; } pub fn getTexture(self: @This()) *c.SDL_Texture { return self.texture; } }; }
https://raw.githubusercontent.com/Ailten/zigTuber/695a6cd342fb02fbf1ac8ea2066d6d5a0d4d3d63/src/value_printable.zig
//! Build-time tool for generating copy-and-patch instruction templates const std = @import("std"); comptime { // So we can liberally throw around `unreachable`s without worrying about safety :) std.debug.assert(@import("builtin").mode == .Debug); } const Sections = struct { text: ?std.elf.Elf64_Shdr = null, @"rel.text": ?std.elf.Elf64_Shdr = null, @"rela.text": ?std.elf.Elf64_Shdr = null, @"data.rel.ro": ?std.elf.Elf64_Shdr = null, @"rel.data.rel.ro": ?std.elf.Elf64_Shdr = null, @"rela.data.rel.ro": ?std.elf.Elf64_Shdr = null, symtab: ?std.elf.Elf64_Shdr = null, strtab: ?std.elf.Elf64_Shdr = null, }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); var args = try std.process.argsWithAllocator(allocator); std.debug.assert(args.skip()); const templates_o = args.next().?; const templates_bin = args.next().?; const templates_zig = args.next().?; const obj_file = try std.fs.cwd().openFile(templates_o, .{}); const ehdr = try std.elf.Header.read(obj_file); var iter = ehdr.section_header_iterator(obj_file); iter.index = ehdr.shstrndx; const shstrtab = (try iter.next()).?; var sections: Sections = .{}; var text_idx: usize = undefined; var section_name = std.ArrayList(u8).init(allocator); iter.index = 0; while (try iter.next()) |shdr| { try obj_file.seekTo(shstrtab.sh_offset + shdr.sh_name); try obj_file.reader().readUntilDelimiterArrayList(&section_name, '\x00', 128); defer section_name.clearRetainingCapacity(); inline for (comptime std.meta.fieldNames(Sections)) |name| { if (std.mem.eql(u8, "." ++ name, section_name.items)) { if (comptime std.mem.eql(u8, name, "text")) { text_idx = iter.index - 1; } @field(sections, name) = shdr; break; } } } const ptr_size: u4 = if (ehdr.is_64) 8 else @panic("cannot handle 32-bit elf"); const relaFn = switch (ehdr.machine) { // .@"386" => &relaX86, .X86_64 => &relaX64, // .ARM => &relaArm32, // .AARCH64 => &relaArm64, else => @panic("unsupported architecture"), }; // Read symbol table const symtab = try allocator.alloc( std.elf.Elf64_Sym, @divExact(sections.symtab.?.sh_size, sections.symtab.?.sh_entsize), ); try obj_file.seekTo(sections.symtab.?.sh_offset); try obj_file.reader().readNoEof(std.mem.sliceAsBytes(symtab)); if (@import("builtin").cpu.arch.endian() != ehdr.endian) { for (symtab) |*sym| { std.mem.byteSwapAllFields(std.elf.Elf64_Sym, sym); } } // Read text section const text_section = try allocator.alloc(u8, sections.text.?.sh_size); try obj_file.seekTo(sections.text.?.sh_offset); try obj_file.reader().readNoEof(text_section); // Process text relocations var symbol_names = std.StringArrayHashMap(void).init(allocator); var relocations = try allocator.alloc(std.ArrayListUnmanaged(Relocation), symtab.len); for (relocations) |*rels| rels.* = .{}; var sym_name = std.ArrayList(u8).init(allocator); if (sections.@"rela.text") |shdr| { var relas = std.ArrayList(ElfRela).init(allocator); try relaFn(&relas, obj_file, shdr); for (relas.items) |rel| { const sym = symtab[rel.symbol]; if (sym.st_shndx != std.elf.SHN_UNDEF) { std.debug.panic("Expected symbol to be undefined (symbol {})", .{rel.symbol}); } try obj_file.seekTo(sections.strtab.?.sh_offset + sym.st_name); try obj_file.reader().readUntilDelimiterArrayList(&sym_name, '\x00', 1024); defer sym_name.clearRetainingCapacity(); const name_result = try symbol_names.getOrPutValue(sym_name.items, {}); name_result.key_ptr.* = try sym_name.toOwnedSlice(); const func = for (symtab, 0..) |s, i| { if (containingFunc(text_idx, s, rel.offset)) { break .{ .idx = i, .start = s.st_value, }; } } else { std.debug.panic("Could not find containing function for address {x}\n", .{rel.offset}); }; try relocations[func.idx].append(allocator, .{ .offset = @intCast(rel.offset - func.start), .symbol = @intCast(name_result.index), .addend = rel.addend, }); } } else { const shdr = sections.@"rel.text".?; _ = shdr; @panic("TODO: rel"); } // Allocate table based on size of data section const insn_table = try allocator.alloc(u32, @divExact(sections.@"data.rel.ro".?.sh_size, ptr_size)); // Process data relocations if (sections.@"rela.data.rel.ro") |shdr| { var relas = std.ArrayList(ElfRela).init(allocator); try relaFn(&relas, obj_file, shdr); for (relas.items) |rel| { const sym = symtab[rel.symbol]; if (sym.st_shndx != text_idx) { std.debug.panic( "Expected symbol to reference text section ({}), got {} (symbol {})", .{ text_idx, sym.st_shndx, rel.symbol }, ); } const sym_addr = symtab[rel.symbol].st_value; const i = @divExact(rel.offset, ptr_size); insn_table[i] = @intCast(@as(i65, sym_addr) + rel.addend); } } else { const shdr = sections.@"rel.data.rel.ro".?; _ = shdr; @panic("TODO: rel"); } var zig_source = std.ArrayList(u8).init(allocator); const w = zig_source.writer(); try w.writeAll( \\const std = @import("std"); \\ \\pub const Template = struct { \\ start: u32, \\ len: u32, \\ relocations_ptr: ?[*:Relocation.empty]const Relocation, \\ \\ pub fn code(t: Template) []const u8 { \\ return text_data[t.start .. t.start + t.len]; \\ } \\ \\ pub fn relocations(t: Template) []const Relocation { \\ if (t.relocations_ptr) |ptr| { \\ var i: usize = 0; \\ while (ptr[i].symbol != .undef) { \\ i += 1; \\ } \\ return ptr[0..i]; \\ } else { \\ return &.{}; \\ } \\ } \\}; \\ \\pub const Relocation = struct { \\ offset: u32, \\ symbol: Symbol, \\ addend: i64, \\ \\ pub const empty: Relocation = .{ \\ .offset = 0, \\ .symbol = .undef, \\ .addend = 0, \\ }; \\}; \\ \\pub const Symbol = enum { \\ undef, \\ ); for (symbol_names.keys()) |name| { try w.print(" {},\n", .{std.zig.fmtId(name)}); } try w.writeAll("};\n\n"); try w.writeAll("const text_data = @embedFile(\"templates.bin\");\n\n"); try w.print("pub const templates: [{}]Template = .{{\n", .{insn_table.len}); for (insn_table) |off| { const func = for (symtab, 0..) |sym, i| { if (containingFunc(text_idx, sym, off)) { std.debug.assert(sym.st_value == off); break .{ .idx = i, .len = sym.st_size }; } } else { std.debug.panic("Cannot find containing function for address {x}\n", .{off}); }; try w.print( \\ .{{ \\ .start = {}, \\ .len = {}, \\ .relocations_ptr = , .{ off, func.len }); const rels = relocations[func.idx].items; if (rels.len == 0) { try w.writeAll(" null"); } else { try w.writeAll(" &[_:Relocation.empty]Relocation{\n"); for (rels) |rel| { try w.print( \\ .{{ \\ .offset = {}, \\ .symbol = .{}, \\ .addend = {}, \\ }}, \\ , .{ rel.offset, std.zig.fmtId(symbol_names.keys()[rel.symbol]), rel.addend, }); } try w.writeAll(" }"); } try w.writeAll(",\n },\n"); } try w.writeAll("};\n"); try std.fs.cwd().writeFile(templates_zig, zig_source.items); try std.fs.cwd().writeFile(templates_bin, text_section); } fn containingFunc(text_idx: usize, sym: std.elf.Elf64_Sym, addr: u64) bool { return sym.st_type() == std.elf.STT_FUNC and sym.st_shndx == text_idx and addr >= sym.st_value and addr < sym.st_value + sym.st_size; } fn relaX64(array: *std.ArrayList(ElfRela), file: std.fs.File, shdr: std.elf.Elf64_Shdr) !void { try file.seekTo(shdr.sh_offset); for (0..shdr.sh_size / @sizeOf(std.elf.Elf64_Rela)) |_| { var rela: std.elf.Elf64_Rela = undefined; try file.reader().readNoEof(std.mem.asBytes(&rela)); switch (rela.r_type()) { std.elf.R_X86_64_64, std.elf.R_X86_64_REX_GOTPCRELX, std.elf.R_X86_64_GOTPCREL, std.elf.R_X86_64_GOTPCRELX, std.elf.R_X86_64_PLT32, => {}, else => std.debug.panic("Cannot handle relocation of type {} (offset 0x{x})\n", .{ rela.r_type(), rela.r_offset }), } try array.append(.{ .offset = rela.r_offset, .symbol = rela.r_sym(), .addend = rela.r_addend, }); } } const Relocation = struct { offset: u32, // Offset within function symbol: u32, // Index into symbol name table addend: i64, }; const ElfRela = struct { offset: u64, symbol: u32, addend: i64, };
https://raw.githubusercontent.com/silversquirl/chip8/9f48263f580526e5463fda693ef50fedbad77ca1/build/copy_patch_gen.zig
// Copyright (c) 2021, sin-ack <sin-ack@protonmail.com> // // SPDX-License-Identifier: GPL-3.0-only const std = @import("std"); const Allocator = std.mem.Allocator; const ref_counted = @import("./ref_counted.zig"); fn WeakHandle(comptime T: type) type { return struct { allocator: Allocator, ptr: ?*T, ref: ref_counted.RefCount, const Self = @This(); pub fn destroy(self: *Self) void { self.allocator.destroy(self); } }; } /// The struct which should be placed on objects that will be weakly referenced. /// When the object is initialized, the `init` method should be called; when /// the object is deinitialized, the `deinit` method should be called. pub fn WeakPtrBlock(comptime T: type) type { const Handle = WeakHandle(T); const Ref = ref_counted.RefPtr(Handle); return struct { handle: Ref, const Self = @This(); pub fn init(allocator: Allocator, ptr: *T) !Self { const raw_handle_object = try allocator.create(Handle); raw_handle_object.allocator = allocator; raw_handle_object.ptr = ptr; raw_handle_object.ref = .{}; return Self{ .handle = Ref.adopt(raw_handle_object) }; } pub fn deinit(self: *Self) void { self.handle.value.ptr = null; self.handle.unref(); } }; } /// A weakly-referencing pointer type. The pointer within can be attempted to be /// obtained by calling `getPointer`. If the object has already been /// deallocated, then the method will return null. Initialize with `init` and /// deinitialize with `deinit`. /// /// The passed type must have a `WeakPtrBlock(T)` object as its `weak` member. pub fn WeakPtr(comptime T: type) type { const HandleRef = ref_counted.RefPtr(WeakHandle(T)); return struct { handle: HandleRef, const Self = @This(); pub fn init(object: *T) Self { std.debug.assert(object.weak.handle.value.ptr != null); object.weak.handle.ref(); return Self{ .handle = object.weak.handle }; } pub fn deinit(self: Self) void { self.handle.unref(); } pub fn getPointer(self: Self) ?*T { return self.handle.value.ptr; } }; }
https://raw.githubusercontent.com/sin-ack/zigself/0610529f7a04ec0d0628abc3e89dafd45b995562/src/utility/weak_ref.zig
const std = @import("std"); const isNan = std.math.isNan; const isInf = std.math.isInf; const copysign = std.math.copysign; pub fn Complex(comptime T: type) type { return extern struct { real: T, imag: T, }; } /// Implementation based on Annex G of C17 Standard (N2176) pub inline fn mulc3(comptime T: type, a_in: T, b_in: T, c_in: T, d_in: T) Complex(T) { var a = a_in; var b = b_in; var c = c_in; var d = d_in; const ac = a * c; const bd = b * d; const ad = a * d; const bc = b * c; const zero: T = 0.0; const one: T = 1.0; var z = Complex(T){ .real = ac - bd, .imag = ad + bc, }; if (isNan(z.real) and isNan(z.imag)) { var recalc: bool = false; if (isInf(a) or isInf(b)) { // (a + ib) is infinite // "Box" the infinity (+/-inf goes to +/-1, all finite values go to 0) a = copysign(if (isInf(a)) one else zero, a); b = copysign(if (isInf(b)) one else zero, b); // Replace NaNs in the other factor with (signed) 0 if (isNan(c)) c = copysign(zero, c); if (isNan(d)) d = copysign(zero, d); recalc = true; } if (isInf(c) or isInf(d)) { // (c + id) is infinite // "Box" the infinity (+/-inf goes to +/-1, all finite values go to 0) c = copysign(if (isInf(c)) one else zero, c); d = copysign(if (isInf(d)) one else zero, d); // Replace NaNs in the other factor with (signed) 0 if (isNan(a)) a = copysign(zero, a); if (isNan(b)) b = copysign(zero, b); recalc = true; } if (!recalc and (isInf(ac) or isInf(bd) or isInf(ad) or isInf(bc))) { // Recover infinities from overflow by changing NaNs to 0 if (isNan(a)) a = copysign(zero, a); if (isNan(b)) b = copysign(zero, b); if (isNan(c)) c = copysign(zero, c); if (isNan(d)) d = copysign(zero, d); recalc = true; } if (recalc) { return .{ .real = std.math.inf(T) * (a * c - b * d), .imag = std.math.inf(T) * (a * d + b * c), }; } } return z; }
https://raw.githubusercontent.com/mazino3/ziglang/3db8cffa3b383011471f425983a7e98ad8a46aa5/lib/compiler_rt/mulc3.zig
const std = @import("std"); const utils = @import("utils.zig"); pub const Writer = std.net.Stream.Writer; pub const Reader = std.net.Stream.Reader; const PlaybackError = error{ PauseFailure, BadSongIndex, NotPlaying, GeneralError, ReadError }; pub fn pause(writer: Writer) anyerror!void { try writer.writeAll("pause\n"); } pub fn play(writer: Writer, reader: Reader, pos: u32) anyerror!void { try writer.print("play {d}\n", .{pos}); var resp = try utils.getResponse(reader); if (!std.mem.eql(u8, resp[0..2], "OK")) { return PlaybackError.BadSongIndex; } } pub fn previous(writer: Writer, reader: Reader) anyerror!void { _ = try writer.writeAll("previous\n"); var resp = try utils.getResponse(reader); if (!std.mem.eql(u8, resp[0..2], "OK")) { return PlaybackError.NotPlaying; } } pub fn stop(writer: Writer) anyerror!void { _ = try writer.writeAll("stop\n"); } pub fn seek(writer: Writer, reader: Reader, pos: u32, seconds: u32) anyerror!void { _ = try writer.print("seek \"{d}\" \"{d}\"\n", .{ pos, seconds }); var resp = try utils.getResponse(reader); if (!std.mem.eql(u8, resp[0..2], "OK")) { return PlaybackError.BadSongIndex; } }
https://raw.githubusercontent.com/tgmatos/mpdz/d9d396cff8cb8a34f41bd552de74f34e2061de11/src/playback.zig
pub fn main() void { std.debug.print("Hello World", .{}); }
https://raw.githubusercontent.com/resqiar/playground/de1d7dc9d5d0617cc113e969bc126007396522b5/zig/hello.zig
const Allocator = std.mem.Allocator; const std = @import("std"); pub fn Grid(comptime T: type) type { return struct { items: [][]T = &[_][]T{}, neighbor_list: std.ArrayListUnmanaged(T) = .{}, default_value: T, pub fn init(a: Allocator, width: usize, height: usize, default_value: T) !@This() { const base = try a.alloc([]T, width); for (base) |*item| { item.* = try a.alloc(T, height); @memset(item.*, default_value); } return @This(){ .items = base, .neighbor_list = try std.ArrayListUnmanaged(T).initCapacity(a, 9), .default_value = default_value, }; } pub inline fn getWidth(self: *const @This()) usize { return self.items.len; } pub inline fn getHeight(self: *const @This()) usize { if (self.getWidth() == 0) return 0; return self.items[0].len; } pub inline fn get(self: *const @This(), x: usize, y: usize) ?*T { if (!self.isValidIndex(x, y)) return null; return &self.items[x][y]; } pub inline fn set(self: *@This(), a: std.mem.Allocator, x: usize, y: usize, value: T) !void { if (x < 0 or y < 0) @panic("negative index given"); while (!self.isValidIndex(x, y)) { //std.debug.print("x: {}, y: {} desired\n", .{ x, y }); //std.debug.print("resizing: width{}, height{}\n", .{ self.getWidth(), self.getHeight() }); try self.expand(a, 2 * self.getWidth() + 1, 2 * self.getHeight() + 1); } self.items[x][y] = value; } pub inline fn getOrSet(self: *@This(), a: std.mem.Allocator, x: usize, y: usize, value: T) !*T { if (self.get(x, y)) |val| { return val; } else { try self.set(a, x, y, value); return self.get(x, y).?; } } pub fn expand(self: *@This(), a: std.mem.Allocator, new_width: usize, new_height: usize) !void { const old_width = self.items.len; self.items = try a.realloc(self.items, new_width); //alloc new columns for (self.items[old_width..new_width]) |*column| { column.* = try a.alloc(T, new_height); @memset(column.*, self.default_value); } //reallocate old columns for (self.items[0..old_width]) |*column| { column.* = try a.realloc(column.*, new_height); } } pub fn clear(self: *@This(), default_value: T) void { for (self.items) |*item| { @memset(item.*, default_value); } } pub fn deinit(self: *@This(), a: Allocator) void { for (self.items) |item| { a.free(item); } a.free(self.items); self.neighbor_list.deinit(a); } pub fn isValidIndex(self: *const @This(), x: anytype, y: anytype) bool { return x >= 0 and x < self.items.len and y >= 0 and y < self.items[x].len; } ///Must be called before json.stringify pub fn prepForStringify(self: *@This()) void { self.neighbor_list.capacity = 0; } ///finds neighbors to any given cell pub fn findNeighbors(self: *@This(), a: std.mem.Allocator, search_x: usize, search_y: usize) []T { var len: usize = 0; if (self.neighbor_list.items.len < 9) { self.neighbor_list.appendNTimes(a, self.default_value, 9) catch return self.neighbor_list.items; } for (0..3) |x_offset| { for (0..3) |y_offset| { //prevent integer overflow if (search_x + x_offset == 0 or search_y + y_offset == 0) continue; const x = search_x + x_offset - 1; const y = search_y + y_offset - 1; if (!self.isValidIndex(x, y)) { continue; } self.neighbor_list.items[len] = self.items[x][y]; len += 1; } } return self.neighbor_list.items[0..len]; } pub const Neighborhood = struct { const Row = struct { left: ?*T, middle: ?*T, right: ?*T }; top: Row = .{}, center: Row = .{}, bottom: Row = .{}, }; pub fn getNeighborhood(self: *const @This(), raw_x: usize, raw_y: usize) Neighborhood { var result: Neighborhood = undefined; const x: i128 = @intCast(raw_x); const y: i128 = @intCast(raw_y); result.top.left = self.get(@intCast(@max(x - 1, 0)), @intCast(@max(y - 1, 0))); result.top.middle = self.get(@intCast(@max(x, 0)), @intCast(@max(y - 1, 0))); result.top.right = self.get(@intCast(@max(x + 1, 0)), @intCast(@max(y - 1, 0))); result.center.left = self.get(@intCast(@max(x - 1, 0)), @intCast(@max(y, 0))); result.center.middle = self.get(@intCast(@max(x, 0)), @intCast(@max(y, 0))); result.center.right = self.get(@intCast(@max(x + 1, 0)), @intCast(@max(y, 0))); result.bottom.left = self.get(@intCast(@max(x - 1, 0)), @intCast(@max(y + 1, 0))); result.bottom.middle = self.get(@intCast(@max(x, 0)), @intCast(@max(y + 1, 0))); result.bottom.right = self.get(@intCast(@max(x + 1, 0)), @intCast(@max(y + 1, 0))); return result; } pub const Iterator = struct { items: [][]?T, x: usize = 0, y: usize = 0, pub fn next(self: *Iterator) ?T { if (self.x >= self.items.len) { return null; } const result = self.items[self.x][self.y]; self.y += 1; if (self.y >= self.items[self.x].len) { self.y = 0; self.x += 1; } return result; } }; pub fn iterator(self: *const @This()) Iterator { return .{ .items = self.items }; } }; } test "grid.zig" { const a = std.testing.allocator; var grid = try Grid(f32).init(a, 32, 32, 0); defer grid.deinit(a); try std.testing.expect(grid.getWidth() == 32); try std.testing.expect(grid.getHeight() == 32); try grid.expand(a, 56, 56); try std.testing.expect(grid.getWidth() == 56); try std.testing.expect(grid.getHeight() == 56); try grid.set(a, 1, 1, 123.0); try std.testing.expect(grid.get(1, 1).?.* == 123.0); const gotten = try grid.getOrSet(a, 123, 123, 45.0); try std.testing.expect(gotten.* == 45.0); }
https://raw.githubusercontent.com/VisenDev/ziggity/7dce0f51e093f2f9f352697b3d659be51672098d/src/grid.zig
const std = @import("std"); pub const audio_graph = @import("audio_graph.zig"); pub const system = @import("system.zig"); pub const module = @import("module.zig"); pub const modules = module.modules; pub const sample_buffer = @import("sample_buffer.zig"); const Utility = modules.Utility; const SamplePlayer = modules.SamplePlayer; const SampleBuffer = sample_buffer.SampleBuffer; pub fn main() anyerror!void {} test "" { _ = audio_graph; _ = system; _ = module; _ = modules; _ = sample_buffer; } test "main" { var sys: system.System = undefined; try sys.init(.{ .allocator = std.testing.allocator, .suggested_latency = 0.15, .device_number = 5, }); defer sys.deinit(); var graph_ctl = &sys.controller; // var play_ctl: module.Controlled(SamplePlayer) = undefined; // try play_ctl.init(std.testing.allocator, 10, modules.SamplePlayer.init()); // var play_ctlr = play_ctl.makeController(); // // var play_idx = try graph_ctl.addModule(module.Module.init(&play_ctl)); // graph_ctl.setOutput(play_idx); // // try graph_ctl.pushChanges(std.testing.allocator, sys.tm.now()); // // const file = @embedFile("../content/amen_brother.wav"); // var smp = try SampleBuffer.initWav(std.testing.allocator, file); // defer smp.deinit(); // // try play_ctlr.send(sys.tm.now(), .{ .setSample = &smp }); // try play_ctlr.send(sys.tm.now(), .{ .setPlayRate = 1. }); // try play_ctlr.send(sys.tm.now(), .{ .setPlayPosition = 1000 }); // try play_ctlr.send(sys.tm.now(), .{ .setAntiClick = true }); // try play_ctlr.send(sys.tm.now(), .play); // try play_ctlr.send(sys.tm.now() + 700000000, .pause); // try play_ctlr.send(sys.tm.now() + 970000000, .play); // try play_ctlr.send(sys.tm.now(), .{ .setLoop = true }); var sine = modules.Sine.init(440.); var sine_ctl: module.Controlled(modules.Sine) = undefined; try sine_ctl.init(std.testing.allocator, 10, &sine); defer sine_ctl.deinit(); var sine_ctlr = sine_ctl.makeController(); var util = modules.Utility.init(); var util_ctl: module.Controlled(modules.Utility) = undefined; try util_ctl.init(std.testing.allocator, 10, &util); defer util_ctl.deinit(); var util_ctlr = util_ctl.makeController(); const sine_idx = try graph_ctl.addModule(sine_ctl.module()); const util_idx = try graph_ctl.addModule(util_ctl.module()); _ = try graph_ctl.addEdge(sine_idx, util_idx, 0); graph_ctl.setOutput(util_idx); try graph_ctl.pushChanges(std.testing.allocator, sys.tm.now()); var in = std.io.getStdIn(); var buf = [_]u8{ 0, 0, 0 }; while (buf[0] != 'q') { // std.time.sleep(1000000000); _ = try in.read(&buf); try sine_ctlr.send(0, .{ .setFreq = 660 }); try util_ctlr.send(sys.tm.now(), .{ .setVolume = 0.15 }); // util.volume = 0.5; // try util_ctlr.send(0, vol0); // graph_ctl.frame(); // // _ = try in.read(&buf); // try util_ctlr.send(0, vol1); // graph_ctl.frame(); } }
https://raw.githubusercontent.com/yurapyon/kasumi/ab28ba23fb4883978be762e25f1ce93fc0f8874c/src/main.zig
const std = @import("std"); // For each location in the configuration and each group index store the number // of possible valid states from there. const DataCache = struct { cache: [][]?u64, fn init(config_len: usize, num_groups: usize, alloc: std.mem.Allocator) !DataCache { var cache = try alloc.alloc([]?u64, config_len); for (0..config_len) |i| { var group_row = try alloc.alloc(?u64, num_groups); @memset(group_row[0..], null); cache[i] = group_row; } return .{.cache = cache}; } fn lookup(self: DataCache, config_index: u8, group_index: u8) ?u64 { return self.cache[config_index][group_index]; } fn store(self: DataCache, config_index: u8, group_index: u8, val: u64) void { self.cache[config_index][group_index] = val; } }; const DataSet = struct { config: []const u8, damaged_groups: std.ArrayList(u8), cache: DataCache, fn init( config: []const u8, damaged_groups: std.ArrayList(u8), alloc: std.mem.Allocator) !DataSet { return .{ .config = config, .damaged_groups = damaged_groups, .cache = try DataCache.init(config.len, damaged_groups.items.len, alloc) }; } fn duplicate(self: DataSet, factor: u8, alloc: std.mem.Allocator) !DataSet { // Allocate enough memory for the expanded configuration. var config = try alloc.alloc(u8, factor * (self.config.len + 1) - 1); for (0..factor) |i| { @memcpy( config[i*(self.config.len + 1)..(i + 1)*(self.config.len + 1) - 1], self.config[0..self.config.len]); if (i < factor - 1) { // Insert a '?'. config[(i + 1) * (self.config.len + 1) - 1] = '?'; } } var damaged_groups = try self.damaged_groups.clone(); for (0..factor - 1) |_| { for (self.damaged_groups.items) |d| { try damaged_groups.append(d); } } return DataSet.init(config, damaged_groups, alloc); } fn count_internal(self: DataSet, config_index: u8, group_index: u8) u64 { // If all groups have been placed check that we haven't left any // known unsatisfied bad springs. if (group_index == self.damaged_groups.items.len) { if (config_index < self.config.len) { for (config_index..self.config.len) |i| { if (self.config[i] == '#') { return 0; } } } // We've got a possible configuration! return 1; } // Check that the current group would fit without overrunning the config. const group_size = self.damaged_groups.items[group_index]; if (config_index + group_size > self.config.len) { // Off the end of the grid, so impossible. return 0; } // Check for a cached result for this state. if (self.cache.lookup(config_index, group_index)) |val| { return val; } // Skip over known good springs. if (self.config[config_index] == '.') { return count_internal(self, config_index + 1, group_index); } var total: u64 = 0; // If it's a '?' then consider not placing here. if (self.config[config_index] == '?') { total = count_internal(self, config_index + 1, group_index); } // We're in the case where we place. // Check that the group wouldn't overlap with any known good springs. for (1..group_size) |i| { if (self.config[config_index + i] == '.') { // This is impossible, must be in the no placement case. return total; } } // Final check: if the next character after the group is a '#' then we // can't place here because that is a known bad spring and it would // extend the group. if (config_index + group_size < self.config.len) { if (self.config[config_index + group_size] == '#') { return total; } } // We can place the group here. total += count_internal(self, config_index + group_size + 1, group_index + 1); self.cache.store(config_index, group_index, total); return total; } fn count(self: DataSet) u64 { return count_internal(self, 0, 0); } }; pub fn main() !void { const f = try std.fs.cwd().openFile("input.txt", .{ .mode = std.fs.File.OpenMode.read_only }); defer f.close(); var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var data = std.ArrayList(DataSet).init(arena.allocator()); while (try f.reader().readUntilDelimiterOrEofAlloc(arena.allocator(), '\n', 100)) |line| { var damaged_groups = std.ArrayList(u8).init(arena.allocator()); var it = std.mem.split(u8, line, " "); const config = it.next() orelse unreachable; const damaged_groups_list = it.next() orelse unreachable; var groups_it = std.mem.split(u8, damaged_groups_list, ","); while (groups_it.next()) |tok| { try damaged_groups.append(try std.fmt.parseInt(u8, tok, 10)); } try data.append(try DataSet.init(config, damaged_groups, arena.allocator())); } var total1: u64 = 0; var total2: u64 = 0; for (data.items) |d| { var poss = d.count(); total1 += poss; const dup = try d.duplicate(5, arena.allocator()); poss = dup.count(); total2 += poss; } const stdout = std.io.getStdOut().writer(); try stdout.print("P1 {d}, P2: {d}\n", .{total1, total2}); }
https://raw.githubusercontent.com/AlexKent3141/aoc23/540e74c40a558e4b2eb2068f9d60af33b0626e66/day12/d12.zig
const std = @import("std"); pub const TicketLock = struct { serving: u64 = 0, taken: u64 = 0, pub fn lock(self: *TicketLock) void { const ticket = @atomicRmw(u64, &self.taken, .Add, 1, .seq_cst); while (true) { if (@cmpxchgWeak( u64, &self.serving, ticket, ticket, .acq_rel, .acquire, ) == null) { return; } else { std.atomic.spinLoopHint(); } } } pub fn release(self: *TicketLock) void { _ = @atomicRmw(u64, &self.serving, .Add, 1, .seq_cst); } };
https://raw.githubusercontent.com/DanB91/Wozmon64/29920645644a04037a7906850ac58ab43312ada3/src/toolbox/src/atomic.zig
const builtin = @import("builtin"); const common = @import("./common.zig"); const floatToInt = @import("./float_to_int.zig").floatToInt; pub const panic = common.panic; comptime { if (common.want_windows_v2u64_abi) { @export(__fixunsdfti_windows_x86_64, .{ .name = "__fixunsdfti", .linkage = common.linkage }); } else { @export(__fixunsdfti, .{ .name = "__fixunsdfti", .linkage = common.linkage }); } } pub fn __fixunsdfti(a: f64) callconv(.C) u128 { return floatToInt(u128, a); } const v2u64 = @Vector(2, u64); fn __fixunsdfti_windows_x86_64(a: f64) callconv(.C) v2u64 { return @bitCast(v2u64, floatToInt(u128, a)); }
https://raw.githubusercontent.com/mazino3/ziglang/3db8cffa3b383011471f425983a7e98ad8a46aa5/lib/compiler_rt/fixunsdfti.zig
//! This file is auto-generated by tools/update_cpu_features.zig. const std = @import("../std.zig"); const CpuFeature = std.Target.Cpu.Feature; const CpuModel = std.Target.Cpu.Model; pub const Feature = enum { a510, a65, a710, a76, a78, a78c, aes, aggressive_fma, alternate_sextload_cvt_f32_pattern, altnzcv, am, amvs, arith_bcc_fusion, arith_cbz_fusion, ascend_store_address, b16b16, balance_fp_ops, bf16, brbe, bti, call_saved_x10, call_saved_x11, call_saved_x12, call_saved_x13, call_saved_x14, call_saved_x15, call_saved_x18, call_saved_x8, call_saved_x9, ccdp, ccidx, ccpp, chk, clrbhb, cmp_bcc_fusion, complxnum, contextidr_el2, cortex_r82, crc, crypto, cssc, custom_cheap_as_move, d128, disable_latency_sched_heuristic, dit, dotprod, ecv, el2vmsa, el3, enable_select_opt, ete, exynos_cheap_as_move, f32mm, f64mm, fgt, fix_cortex_a53_835769, flagm, fmv, force_32bit_jump_tables, fp16fml, fp_armv8, fptoint, fullfp16, fuse_address, fuse_addsub_2reg_const1, fuse_adrp_add, fuse_aes, fuse_arith_logic, fuse_crypto_eor, fuse_csel, fuse_literals, gcs, harden_sls_blr, harden_sls_nocomdat, harden_sls_retbr, hbc, hcx, i8mm, ite, jsconv, lor, ls64, lse, lse128, lse2, lsl_fast, mec, mops, mpam, mte, neon, nmi, no_bti_at_return_twice, no_neg_immediates, no_sve_fp_ld1r, no_zcz_fp, nv, outline_atomics, pan, pan_rwv, pauth, perfmon, predictable_select_expensive, predres, prfm_slc_target, rand, ras, rasv2, rcpc, rcpc3, rcpc_immo, rdm, reserve_x1, reserve_x10, reserve_x11, reserve_x12, reserve_x13, reserve_x14, reserve_x15, reserve_x18, reserve_x2, reserve_x20, reserve_x21, reserve_x22, reserve_x23, reserve_x24, reserve_x25, reserve_x26, reserve_x27, reserve_x28, reserve_x3, reserve_x30, reserve_x4, reserve_x5, reserve_x6, reserve_x7, reserve_x9, rme, sb, sel2, sha2, sha3, slow_misaligned_128store, slow_paired_128, slow_strqro_store, sm4, sme, sme2, sme2p1, sme_f16f16, sme_f64f64, sme_i16i64, spe, spe_eef, specres2, specrestrict, ssbs, strict_align, sve, sve2, sve2_aes, sve2_bitperm, sve2_sha3, sve2_sm4, sve2p1, tagged_globals, the, tlb_rmi, tme, tpidr_el1, tpidr_el2, tpidr_el3, tpidrro_el0, tracev8_4, trbe, uaops, use_experimental_zeroing_pseudos, use_postra_scheduler, use_reciprocal_square_root, use_scalar_inc_vl, v8_1a, v8_2a, v8_3a, v8_4a, v8_5a, v8_6a, v8_7a, v8_8a, v8_9a, v8a, v8r, v9_1a, v9_2a, v9_3a, v9_4a, v9a, vh, wfxt, xs, zcm, zcz, zcz_fp_workaround, zcz_gp, }; pub const featureSet = CpuFeature.feature_set_fns(Feature).featureSet; pub const featureSetHas = CpuFeature.feature_set_fns(Feature).featureSetHas; pub const featureSetHasAny = CpuFeature.feature_set_fns(Feature).featureSetHasAny; pub const featureSetHasAll = CpuFeature.feature_set_fns(Feature).featureSetHasAll; pub const all_features = blk: { @setEvalBranchQuota(2000); const len = @typeInfo(Feature).Enum.fields.len; std.debug.assert(len <= CpuFeature.Set.needed_bit_count); var result: [len]CpuFeature = undefined; result[@intFromEnum(Feature.a510)] = .{ .llvm_name = "a510", .description = "Cortex-A510 ARM processors", .dependencies = featureSet(&[_]Feature{ .fuse_adrp_add, .fuse_aes, .use_postra_scheduler, }), }; result[@intFromEnum(Feature.a65)] = .{ .llvm_name = "a65", .description = "Cortex-A65 ARM processors", .dependencies = featureSet(&[_]Feature{ .enable_select_opt, .fuse_address, .fuse_adrp_add, .fuse_aes, .fuse_literals, .predictable_select_expensive, }), }; result[@intFromEnum(Feature.a710)] = .{ .llvm_name = "a710", .description = "Cortex-A710 ARM processors", .dependencies = featureSet(&[_]Feature{ .cmp_bcc_fusion, .enable_select_opt, .fuse_adrp_add, .fuse_aes, .lsl_fast, .predictable_select_expensive, .use_postra_scheduler, }), }; result[@intFromEnum(Feature.a76)] = .{ .llvm_name = "a76", .description = "Cortex-A76 ARM processors", .dependencies = featureSet(&[_]Feature{ .enable_select_opt, .fuse_adrp_add, .fuse_aes, .lsl_fast, .predictable_select_expensive, }), }; result[@intFromEnum(Feature.a78)] = .{ .llvm_name = "a78", .description = "Cortex-A78 ARM processors", .dependencies = featureSet(&[_]Feature{ .cmp_bcc_fusion, .enable_select_opt, .fuse_adrp_add, .fuse_aes, .lsl_fast, .predictable_select_expensive, .use_postra_scheduler, }), }; result[@intFromEnum(Feature.a78c)] = .{ .llvm_name = "a78c", .description = "Cortex-A78C ARM processors", .dependencies = featureSet(&[_]Feature{ .cmp_bcc_fusion, .enable_select_opt, .fuse_adrp_add, .fuse_aes, .lsl_fast, .predictable_select_expensive, .use_postra_scheduler, }), }; result[@intFromEnum(Feature.aes)] = .{ .llvm_name = "aes", .description = "Enable AES support (FEAT_AES, FEAT_PMULL)", .dependencies = featureSet(&[_]Feature{ .neon, }), }; result[@intFromEnum(Feature.aggressive_fma)] = .{ .llvm_name = "aggressive-fma", .description = "Enable Aggressive FMA for floating-point.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.alternate_sextload_cvt_f32_pattern)] = .{ .llvm_name = "alternate-sextload-cvt-f32-pattern", .description = "Use alternative pattern for sextload convert to f32", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.altnzcv)] = .{ .llvm_name = "altnzcv", .description = "Enable alternative NZCV format for floating point comparisons (FEAT_FlagM2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.am)] = .{ .llvm_name = "am", .description = "Enable v8.4-A Activity Monitors extension (FEAT_AMUv1)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.amvs)] = .{ .llvm_name = "amvs", .description = "Enable v8.6-A Activity Monitors Virtualization support (FEAT_AMUv1p1)", .dependencies = featureSet(&[_]Feature{ .am, }), }; result[@intFromEnum(Feature.arith_bcc_fusion)] = .{ .llvm_name = "arith-bcc-fusion", .description = "CPU fuses arithmetic+bcc operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.arith_cbz_fusion)] = .{ .llvm_name = "arith-cbz-fusion", .description = "CPU fuses arithmetic + cbz/cbnz operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ascend_store_address)] = .{ .llvm_name = "ascend-store-address", .description = "Schedule vector stores by ascending address", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.b16b16)] = .{ .llvm_name = "b16b16", .description = "Enable SVE2.1 or SME2.1 non-widening BFloat16 to BFloat16 instructions (FEAT_B16B16)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.balance_fp_ops)] = .{ .llvm_name = "balance-fp-ops", .description = "balance mix of odd and even D-registers for fp multiply(-accumulate) ops", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.bf16)] = .{ .llvm_name = "bf16", .description = "Enable BFloat16 Extension (FEAT_BF16)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.brbe)] = .{ .llvm_name = "brbe", .description = "Enable Branch Record Buffer Extension (FEAT_BRBE)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.bti)] = .{ .llvm_name = "bti", .description = "Enable Branch Target Identification (FEAT_BTI)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x10)] = .{ .llvm_name = "call-saved-x10", .description = "Make X10 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x11)] = .{ .llvm_name = "call-saved-x11", .description = "Make X11 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x12)] = .{ .llvm_name = "call-saved-x12", .description = "Make X12 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x13)] = .{ .llvm_name = "call-saved-x13", .description = "Make X13 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x14)] = .{ .llvm_name = "call-saved-x14", .description = "Make X14 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x15)] = .{ .llvm_name = "call-saved-x15", .description = "Make X15 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x18)] = .{ .llvm_name = "call-saved-x18", .description = "Make X18 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x8)] = .{ .llvm_name = "call-saved-x8", .description = "Make X8 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.call_saved_x9)] = .{ .llvm_name = "call-saved-x9", .description = "Make X9 callee saved.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ccdp)] = .{ .llvm_name = "ccdp", .description = "Enable v8.5 Cache Clean to Point of Deep Persistence (FEAT_DPB2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ccidx)] = .{ .llvm_name = "ccidx", .description = "Enable v8.3-A Extend of the CCSIDR number of sets (FEAT_CCIDX)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ccpp)] = .{ .llvm_name = "ccpp", .description = "Enable v8.2 data Cache Clean to Point of Persistence (FEAT_DPB)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.chk)] = .{ .llvm_name = "chk", .description = "Enable Armv8.0-A Check Feature Status Extension (FEAT_CHK)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.clrbhb)] = .{ .llvm_name = "clrbhb", .description = "Enable Clear BHB instruction (FEAT_CLRBHB)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.cmp_bcc_fusion)] = .{ .llvm_name = "cmp-bcc-fusion", .description = "CPU fuses cmp+bcc operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.complxnum)] = .{ .llvm_name = "complxnum", .description = "Enable v8.3-A Floating-point complex number support (FEAT_FCMA)", .dependencies = featureSet(&[_]Feature{ .neon, }), }; result[@intFromEnum(Feature.contextidr_el2)] = .{ .llvm_name = "CONTEXTIDREL2", .description = "Enable RW operand Context ID Register (EL2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.cortex_r82)] = .{ .llvm_name = "cortex-r82", .description = "Cortex-R82 ARM processors", .dependencies = featureSet(&[_]Feature{ .use_postra_scheduler, }), }; result[@intFromEnum(Feature.crc)] = .{ .llvm_name = "crc", .description = "Enable ARMv8 CRC-32 checksum instructions (FEAT_CRC32)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.crypto)] = .{ .llvm_name = "crypto", .description = "Enable cryptographic instructions", .dependencies = featureSet(&[_]Feature{ .aes, .sha2, }), }; result[@intFromEnum(Feature.cssc)] = .{ .llvm_name = "cssc", .description = "Enable Common Short Sequence Compression (CSSC) instructions (FEAT_CSSC)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.custom_cheap_as_move)] = .{ .llvm_name = "custom-cheap-as-move", .description = "Use custom handling of cheap instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.d128)] = .{ .llvm_name = "d128", .description = "Enable Armv9.4-A 128-bit Page Table Descriptors, System Registers and Instructions (FEAT_D128, FEAT_LVA3, FEAT_SYSREG128, FEAT_SYSINSTR128)", .dependencies = featureSet(&[_]Feature{ .lse128, }), }; result[@intFromEnum(Feature.disable_latency_sched_heuristic)] = .{ .llvm_name = "disable-latency-sched-heuristic", .description = "Disable latency scheduling heuristic", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.dit)] = .{ .llvm_name = "dit", .description = "Enable v8.4-A Data Independent Timing instructions (FEAT_DIT)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.dotprod)] = .{ .llvm_name = "dotprod", .description = "Enable dot product support (FEAT_DotProd)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ecv)] = .{ .llvm_name = "ecv", .description = "Enable enhanced counter virtualization extension (FEAT_ECV)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.el2vmsa)] = .{ .llvm_name = "el2vmsa", .description = "Enable Exception Level 2 Virtual Memory System Architecture", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.el3)] = .{ .llvm_name = "el3", .description = "Enable Exception Level 3", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.enable_select_opt)] = .{ .llvm_name = "enable-select-opt", .description = "Enable the select optimize pass for select loop heuristics", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ete)] = .{ .llvm_name = "ete", .description = "Enable Embedded Trace Extension (FEAT_ETE)", .dependencies = featureSet(&[_]Feature{ .trbe, }), }; result[@intFromEnum(Feature.exynos_cheap_as_move)] = .{ .llvm_name = "exynos-cheap-as-move", .description = "Use Exynos specific handling of cheap instructions", .dependencies = featureSet(&[_]Feature{ .custom_cheap_as_move, }), }; result[@intFromEnum(Feature.f32mm)] = .{ .llvm_name = "f32mm", .description = "Enable Matrix Multiply FP32 Extension (FEAT_F32MM)", .dependencies = featureSet(&[_]Feature{ .sve, }), }; result[@intFromEnum(Feature.f64mm)] = .{ .llvm_name = "f64mm", .description = "Enable Matrix Multiply FP64 Extension (FEAT_F64MM)", .dependencies = featureSet(&[_]Feature{ .sve, }), }; result[@intFromEnum(Feature.fgt)] = .{ .llvm_name = "fgt", .description = "Enable fine grained virtualization traps extension (FEAT_FGT)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fix_cortex_a53_835769)] = .{ .llvm_name = "fix-cortex-a53-835769", .description = "Mitigate Cortex-A53 Erratum 835769", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.flagm)] = .{ .llvm_name = "flagm", .description = "Enable v8.4-A Flag Manipulation Instructions (FEAT_FlagM)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fmv)] = .{ .llvm_name = "fmv", .description = "Enable Function Multi Versioning support.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.force_32bit_jump_tables)] = .{ .llvm_name = "force-32bit-jump-tables", .description = "Force jump table entries to be 32-bits wide except at MinSize", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fp16fml)] = .{ .llvm_name = "fp16fml", .description = "Enable FP16 FML instructions (FEAT_FHM)", .dependencies = featureSet(&[_]Feature{ .fullfp16, }), }; result[@intFromEnum(Feature.fp_armv8)] = .{ .llvm_name = "fp-armv8", .description = "Enable ARMv8 FP (FEAT_FP)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fptoint)] = .{ .llvm_name = "fptoint", .description = "Enable FRInt[32|64][Z|X] instructions that round a floating-point number to an integer (in FP format) forcing it to fit into a 32- or 64-bit int (FEAT_FRINTTS)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fullfp16)] = .{ .llvm_name = "fullfp16", .description = "Full FP16 (FEAT_FP16)", .dependencies = featureSet(&[_]Feature{ .fp_armv8, }), }; result[@intFromEnum(Feature.fuse_address)] = .{ .llvm_name = "fuse-address", .description = "CPU fuses address generation and memory operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_addsub_2reg_const1)] = .{ .llvm_name = "fuse-addsub-2reg-const1", .description = "CPU fuses (a + b + 1) and (a - b - 1)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_adrp_add)] = .{ .llvm_name = "fuse-adrp-add", .description = "CPU fuses adrp+add operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_aes)] = .{ .llvm_name = "fuse-aes", .description = "CPU fuses AES crypto operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_arith_logic)] = .{ .llvm_name = "fuse-arith-logic", .description = "CPU fuses arithmetic and logic operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_crypto_eor)] = .{ .llvm_name = "fuse-crypto-eor", .description = "CPU fuses AES/PMULL and EOR operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_csel)] = .{ .llvm_name = "fuse-csel", .description = "CPU fuses conditional select operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.fuse_literals)] = .{ .llvm_name = "fuse-literals", .description = "CPU fuses literal generation operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.gcs)] = .{ .llvm_name = "gcs", .description = "Enable Armv9.4-A Guarded Call Stack Extension", .dependencies = featureSet(&[_]Feature{ .chk, }), }; result[@intFromEnum(Feature.harden_sls_blr)] = .{ .llvm_name = "harden-sls-blr", .description = "Harden against straight line speculation across BLR instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.harden_sls_nocomdat)] = .{ .llvm_name = "harden-sls-nocomdat", .description = "Generate thunk code for SLS mitigation in the normal text section", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.harden_sls_retbr)] = .{ .llvm_name = "harden-sls-retbr", .description = "Harden against straight line speculation across RET and BR instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.hbc)] = .{ .llvm_name = "hbc", .description = "Enable Armv8.8-A Hinted Conditional Branches Extension (FEAT_HBC)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.hcx)] = .{ .llvm_name = "hcx", .description = "Enable Armv8.7-A HCRX_EL2 system register (FEAT_HCX)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.i8mm)] = .{ .llvm_name = "i8mm", .description = "Enable Matrix Multiply Int8 Extension (FEAT_I8MM)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ite)] = .{ .llvm_name = "ite", .description = "Enable Armv9.4-A Instrumentation Extension FEAT_ITE", .dependencies = featureSet(&[_]Feature{ .ete, }), }; result[@intFromEnum(Feature.jsconv)] = .{ .llvm_name = "jsconv", .description = "Enable v8.3-A JavaScript FP conversion instructions (FEAT_JSCVT)", .dependencies = featureSet(&[_]Feature{ .fp_armv8, }), }; result[@intFromEnum(Feature.lor)] = .{ .llvm_name = "lor", .description = "Enables ARM v8.1 Limited Ordering Regions extension (FEAT_LOR)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ls64)] = .{ .llvm_name = "ls64", .description = "Enable Armv8.7-A LD64B/ST64B Accelerator Extension (FEAT_LS64, FEAT_LS64_V, FEAT_LS64_ACCDATA)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.lse)] = .{ .llvm_name = "lse", .description = "Enable ARMv8.1 Large System Extension (LSE) atomic instructions (FEAT_LSE)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.lse128)] = .{ .llvm_name = "lse128", .description = "Enable Armv9.4-A 128-bit Atomic Instructions (FEAT_LSE128)", .dependencies = featureSet(&[_]Feature{ .lse, }), }; result[@intFromEnum(Feature.lse2)] = .{ .llvm_name = "lse2", .description = "Enable ARMv8.4 Large System Extension 2 (LSE2) atomicity rules (FEAT_LSE2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.lsl_fast)] = .{ .llvm_name = "lsl-fast", .description = "CPU has a fastpath logical shift of up to 3 places", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.mec)] = .{ .llvm_name = "mec", .description = "Enable Memory Encryption Contexts Extension", .dependencies = featureSet(&[_]Feature{ .rme, }), }; result[@intFromEnum(Feature.mops)] = .{ .llvm_name = "mops", .description = "Enable Armv8.8-A memcpy and memset acceleration instructions (FEAT_MOPS)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.mpam)] = .{ .llvm_name = "mpam", .description = "Enable v8.4-A Memory system Partitioning and Monitoring extension (FEAT_MPAM)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.mte)] = .{ .llvm_name = "mte", .description = "Enable Memory Tagging Extension (FEAT_MTE, FEAT_MTE2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.neon)] = .{ .llvm_name = "neon", .description = "Enable Advanced SIMD instructions (FEAT_AdvSIMD)", .dependencies = featureSet(&[_]Feature{ .fp_armv8, }), }; result[@intFromEnum(Feature.nmi)] = .{ .llvm_name = "nmi", .description = "Enable Armv8.8-A Non-maskable Interrupts (FEAT_NMI, FEAT_GICv3_NMI)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.no_bti_at_return_twice)] = .{ .llvm_name = "no-bti-at-return-twice", .description = "Don't place a BTI instruction after a return-twice", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.no_neg_immediates)] = .{ .llvm_name = "no-neg-immediates", .description = "Convert immediates and instructions to their negated or complemented equivalent when the immediate does not fit in the encoding.", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.no_sve_fp_ld1r)] = .{ .llvm_name = "no-sve-fp-ld1r", .description = "Avoid using LD1RX instructions for FP", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.no_zcz_fp)] = .{ .llvm_name = "no-zcz-fp", .description = "Has no zero-cycle zeroing instructions for FP registers", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.nv)] = .{ .llvm_name = "nv", .description = "Enable v8.4-A Nested Virtualization Enchancement (FEAT_NV, FEAT_NV2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.outline_atomics)] = .{ .llvm_name = "outline-atomics", .description = "Enable out of line atomics to support LSE instructions", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.pan)] = .{ .llvm_name = "pan", .description = "Enables ARM v8.1 Privileged Access-Never extension (FEAT_PAN)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.pan_rwv)] = .{ .llvm_name = "pan-rwv", .description = "Enable v8.2 PAN s1e1R and s1e1W Variants (FEAT_PAN2)", .dependencies = featureSet(&[_]Feature{ .pan, }), }; result[@intFromEnum(Feature.pauth)] = .{ .llvm_name = "pauth", .description = "Enable v8.3-A Pointer Authentication extension (FEAT_PAuth)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.perfmon)] = .{ .llvm_name = "perfmon", .description = "Enable Code Generation for ARMv8 PMUv3 Performance Monitors extension (FEAT_PMUv3)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.predictable_select_expensive)] = .{ .llvm_name = "predictable-select-expensive", .description = "Prefer likely predicted branches over selects", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.predres)] = .{ .llvm_name = "predres", .description = "Enable v8.5a execution and data prediction invalidation instructions (FEAT_SPECRES)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.prfm_slc_target)] = .{ .llvm_name = "prfm-slc-target", .description = "Enable SLC target for PRFM instruction", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.rand)] = .{ .llvm_name = "rand", .description = "Enable Random Number generation instructions (FEAT_RNG)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ras)] = .{ .llvm_name = "ras", .description = "Enable ARMv8 Reliability, Availability and Serviceability Extensions (FEAT_RAS, FEAT_RASv1p1)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.rasv2)] = .{ .llvm_name = "rasv2", .description = "Enable ARMv8.9-A Reliability, Availability and Serviceability Extensions (FEAT_RASv2)", .dependencies = featureSet(&[_]Feature{ .ras, }), }; result[@intFromEnum(Feature.rcpc)] = .{ .llvm_name = "rcpc", .description = "Enable support for RCPC extension (FEAT_LRCPC)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.rcpc3)] = .{ .llvm_name = "rcpc3", .description = "Enable Armv8.9-A RCPC instructions for A64 and Advanced SIMD and floating-point instruction set (FEAT_LRCPC3)", .dependencies = featureSet(&[_]Feature{ .rcpc_immo, }), }; result[@intFromEnum(Feature.rcpc_immo)] = .{ .llvm_name = "rcpc-immo", .description = "Enable v8.4-A RCPC instructions with Immediate Offsets (FEAT_LRCPC2)", .dependencies = featureSet(&[_]Feature{ .rcpc, }), }; result[@intFromEnum(Feature.rdm)] = .{ .llvm_name = "rdm", .description = "Enable ARMv8.1 Rounding Double Multiply Add/Subtract instructions (FEAT_RDM)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x1)] = .{ .llvm_name = "reserve-x1", .description = "Reserve X1, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x10)] = .{ .llvm_name = "reserve-x10", .description = "Reserve X10, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x11)] = .{ .llvm_name = "reserve-x11", .description = "Reserve X11, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x12)] = .{ .llvm_name = "reserve-x12", .description = "Reserve X12, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x13)] = .{ .llvm_name = "reserve-x13", .description = "Reserve X13, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x14)] = .{ .llvm_name = "reserve-x14", .description = "Reserve X14, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x15)] = .{ .llvm_name = "reserve-x15", .description = "Reserve X15, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x18)] = .{ .llvm_name = "reserve-x18", .description = "Reserve X18, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x2)] = .{ .llvm_name = "reserve-x2", .description = "Reserve X2, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x20)] = .{ .llvm_name = "reserve-x20", .description = "Reserve X20, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x21)] = .{ .llvm_name = "reserve-x21", .description = "Reserve X21, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x22)] = .{ .llvm_name = "reserve-x22", .description = "Reserve X22, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x23)] = .{ .llvm_name = "reserve-x23", .description = "Reserve X23, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x24)] = .{ .llvm_name = "reserve-x24", .description = "Reserve X24, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x25)] = .{ .llvm_name = "reserve-x25", .description = "Reserve X25, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x26)] = .{ .llvm_name = "reserve-x26", .description = "Reserve X26, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x27)] = .{ .llvm_name = "reserve-x27", .description = "Reserve X27, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x28)] = .{ .llvm_name = "reserve-x28", .description = "Reserve X28, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x3)] = .{ .llvm_name = "reserve-x3", .description = "Reserve X3, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x30)] = .{ .llvm_name = "reserve-x30", .description = "Reserve X30, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x4)] = .{ .llvm_name = "reserve-x4", .description = "Reserve X4, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x5)] = .{ .llvm_name = "reserve-x5", .description = "Reserve X5, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x6)] = .{ .llvm_name = "reserve-x6", .description = "Reserve X6, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x7)] = .{ .llvm_name = "reserve-x7", .description = "Reserve X7, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.reserve_x9)] = .{ .llvm_name = "reserve-x9", .description = "Reserve X9, making it unavailable as a GPR", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.rme)] = .{ .llvm_name = "rme", .description = "Enable Realm Management Extension (FEAT_RME)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.sb)] = .{ .llvm_name = "sb", .description = "Enable v8.5 Speculation Barrier (FEAT_SB)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.sel2)] = .{ .llvm_name = "sel2", .description = "Enable v8.4-A Secure Exception Level 2 extension (FEAT_SEL2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.sha2)] = .{ .llvm_name = "sha2", .description = "Enable SHA1 and SHA256 support (FEAT_SHA1, FEAT_SHA256)", .dependencies = featureSet(&[_]Feature{ .neon, }), }; result[@intFromEnum(Feature.sha3)] = .{ .llvm_name = "sha3", .description = "Enable SHA512 and SHA3 support (FEAT_SHA3, FEAT_SHA512)", .dependencies = featureSet(&[_]Feature{ .sha2, }), }; result[@intFromEnum(Feature.slow_misaligned_128store)] = .{ .llvm_name = "slow-misaligned-128store", .description = "Misaligned 128 bit stores are slow", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.slow_paired_128)] = .{ .llvm_name = "slow-paired-128", .description = "Paired 128 bit loads and stores are slow", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.slow_strqro_store)] = .{ .llvm_name = "slow-strqro-store", .description = "STR of Q register with register offset is slow", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.sm4)] = .{ .llvm_name = "sm4", .description = "Enable SM3 and SM4 support (FEAT_SM4, FEAT_SM3)", .dependencies = featureSet(&[_]Feature{ .neon, }), }; result[@intFromEnum(Feature.sme)] = .{ .llvm_name = "sme", .description = "Enable Scalable Matrix Extension (SME) (FEAT_SME)", .dependencies = featureSet(&[_]Feature{ .bf16, .use_scalar_inc_vl, }), }; result[@intFromEnum(Feature.sme2)] = .{ .llvm_name = "sme2", .description = "Enable Scalable Matrix Extension 2 (SME2) instructions", .dependencies = featureSet(&[_]Feature{ .sme, }), }; result[@intFromEnum(Feature.sme2p1)] = .{ .llvm_name = "sme2p1", .description = "Enable Scalable Matrix Extension 2.1 (FEAT_SME2p1) instructions", .dependencies = featureSet(&[_]Feature{ .sme2, }), }; result[@intFromEnum(Feature.sme_f16f16)] = .{ .llvm_name = "sme-f16f16", .description = "Enable SME2.1 non-widening Float16 instructions (FEAT_SME_F16F16)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.sme_f64f64)] = .{ .llvm_name = "sme-f64f64", .description = "Enable Scalable Matrix Extension (SME) F64F64 instructions (FEAT_SME_F64F64)", .dependencies = featureSet(&[_]Feature{ .sme, }), }; result[@intFromEnum(Feature.sme_i16i64)] = .{ .llvm_name = "sme-i16i64", .description = "Enable Scalable Matrix Extension (SME) I16I64 instructions (FEAT_SME_I16I64)", .dependencies = featureSet(&[_]Feature{ .sme, }), }; result[@intFromEnum(Feature.spe)] = .{ .llvm_name = "spe", .description = "Enable Statistical Profiling extension (FEAT_SPE)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.spe_eef)] = .{ .llvm_name = "spe-eef", .description = "Enable extra register in the Statistical Profiling Extension (FEAT_SPEv1p2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.specres2)] = .{ .llvm_name = "specres2", .description = "Enable Speculation Restriction Instruction (FEAT_SPECRES2)", .dependencies = featureSet(&[_]Feature{ .predres, }), }; result[@intFromEnum(Feature.specrestrict)] = .{ .llvm_name = "specrestrict", .description = "Enable architectural speculation restriction (FEAT_CSV2_2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.ssbs)] = .{ .llvm_name = "ssbs", .description = "Enable Speculative Store Bypass Safe bit (FEAT_SSBS, FEAT_SSBS2)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.strict_align)] = .{ .llvm_name = "strict-align", .description = "Disallow all unaligned memory access", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.sve)] = .{ .llvm_name = "sve", .description = "Enable Scalable Vector Extension (SVE) instructions (FEAT_SVE)", .dependencies = featureSet(&[_]Feature{ .fullfp16, }), }; result[@intFromEnum(Feature.sve2)] = .{ .llvm_name = "sve2", .description = "Enable Scalable Vector Extension 2 (SVE2) instructions (FEAT_SVE2)", .dependencies = featureSet(&[_]Feature{ .sve, .use_scalar_inc_vl, }), }; result[@intFromEnum(Feature.sve2_aes)] = .{ .llvm_name = "sve2-aes", .description = "Enable AES SVE2 instructions (FEAT_SVE_AES, FEAT_SVE_PMULL128)", .dependencies = featureSet(&[_]Feature{ .aes, .sve2, }), }; result[@intFromEnum(Feature.sve2_bitperm)] = .{ .llvm_name = "sve2-bitperm", .description = "Enable bit permutation SVE2 instructions (FEAT_SVE_BitPerm)", .dependencies = featureSet(&[_]Feature{ .sve2, }), }; result[@intFromEnum(Feature.sve2_sha3)] = .{ .llvm_name = "sve2-sha3", .description = "Enable SHA3 SVE2 instructions (FEAT_SVE_SHA3)", .dependencies = featureSet(&[_]Feature{ .sha3, .sve2, }), }; result[@intFromEnum(Feature.sve2_sm4)] = .{ .llvm_name = "sve2-sm4", .description = "Enable SM4 SVE2 instructions (FEAT_SVE_SM4)", .dependencies = featureSet(&[_]Feature{ .sm4, .sve2, }), }; result[@intFromEnum(Feature.sve2p1)] = .{ .llvm_name = "sve2p1", .description = "Enable Scalable Vector Extension 2.1 instructions", .dependencies = featureSet(&[_]Feature{ .sve2, }), }; result[@intFromEnum(Feature.tagged_globals)] = .{ .llvm_name = "tagged-globals", .description = "Use an instruction sequence for taking the address of a global that allows a memory tag in the upper address bits", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.the)] = .{ .llvm_name = "the", .description = "Enable Armv8.9-A Translation Hardening Extension (FEAT_THE)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tlb_rmi)] = .{ .llvm_name = "tlb-rmi", .description = "Enable v8.4-A TLB Range and Maintenance Instructions (FEAT_TLBIOS, FEAT_TLBIRANGE)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tme)] = .{ .llvm_name = "tme", .description = "Enable Transactional Memory Extension (FEAT_TME)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tpidr_el1)] = .{ .llvm_name = "tpidr-el1", .description = "Permit use of TPIDR_EL1 for the TLS base", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tpidr_el2)] = .{ .llvm_name = "tpidr-el2", .description = "Permit use of TPIDR_EL2 for the TLS base", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tpidr_el3)] = .{ .llvm_name = "tpidr-el3", .description = "Permit use of TPIDR_EL3 for the TLS base", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tpidrro_el0)] = .{ .llvm_name = "tpidrro-el0", .description = "Permit use of TPIDRRO_EL0 for the TLS base", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.tracev8_4)] = .{ .llvm_name = "tracev8.4", .description = "Enable v8.4-A Trace extension (FEAT_TRF)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.trbe)] = .{ .llvm_name = "trbe", .description = "Enable Trace Buffer Extension (FEAT_TRBE)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.uaops)] = .{ .llvm_name = "uaops", .description = "Enable v8.2 UAO PState (FEAT_UAO)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.use_experimental_zeroing_pseudos)] = .{ .llvm_name = "use-experimental-zeroing-pseudos", .description = "Hint to the compiler that the MOVPRFX instruction is merged with destructive operations", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.use_postra_scheduler)] = .{ .llvm_name = "use-postra-scheduler", .description = "Schedule again after register allocation", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.use_reciprocal_square_root)] = .{ .llvm_name = "use-reciprocal-square-root", .description = "Use the reciprocal square root approximation", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.use_scalar_inc_vl)] = .{ .llvm_name = "use-scalar-inc-vl", .description = "Prefer inc/dec over add+cnt", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.v8_1a)] = .{ .llvm_name = "v8.1a", .description = "Support ARM v8.1a instructions", .dependencies = featureSet(&[_]Feature{ .crc, .lor, .lse, .pan, .rdm, .v8a, .vh, }), }; result[@intFromEnum(Feature.v8_2a)] = .{ .llvm_name = "v8.2a", .description = "Support ARM v8.2a instructions", .dependencies = featureSet(&[_]Feature{ .ccpp, .pan_rwv, .ras, .uaops, .v8_1a, }), }; result[@intFromEnum(Feature.v8_3a)] = .{ .llvm_name = "v8.3a", .description = "Support ARM v8.3a instructions", .dependencies = featureSet(&[_]Feature{ .ccidx, .complxnum, .jsconv, .pauth, .rcpc, .v8_2a, }), }; result[@intFromEnum(Feature.v8_4a)] = .{ .llvm_name = "v8.4a", .description = "Support ARM v8.4a instructions", .dependencies = featureSet(&[_]Feature{ .am, .dit, .dotprod, .flagm, .lse2, .mpam, .nv, .rcpc_immo, .sel2, .tlb_rmi, .tracev8_4, .v8_3a, }), }; result[@intFromEnum(Feature.v8_5a)] = .{ .llvm_name = "v8.5a", .description = "Support ARM v8.5a instructions", .dependencies = featureSet(&[_]Feature{ .altnzcv, .bti, .ccdp, .fptoint, .predres, .sb, .specrestrict, .ssbs, .v8_4a, }), }; result[@intFromEnum(Feature.v8_6a)] = .{ .llvm_name = "v8.6a", .description = "Support ARM v8.6a instructions", .dependencies = featureSet(&[_]Feature{ .amvs, .bf16, .ecv, .fgt, .i8mm, .v8_5a, }), }; result[@intFromEnum(Feature.v8_7a)] = .{ .llvm_name = "v8.7a", .description = "Support ARM v8.7a instructions", .dependencies = featureSet(&[_]Feature{ .hcx, .v8_6a, .wfxt, .xs, }), }; result[@intFromEnum(Feature.v8_8a)] = .{ .llvm_name = "v8.8a", .description = "Support ARM v8.8a instructions", .dependencies = featureSet(&[_]Feature{ .hbc, .mops, .nmi, .v8_7a, }), }; result[@intFromEnum(Feature.v8_9a)] = .{ .llvm_name = "v8.9a", .description = "Support ARM v8.9a instructions", .dependencies = featureSet(&[_]Feature{ .chk, .clrbhb, .cssc, .prfm_slc_target, .rasv2, .specres2, .v8_8a, }), }; result[@intFromEnum(Feature.v8a)] = .{ .llvm_name = "v8a", .description = "Support ARM v8.0a instructions", .dependencies = featureSet(&[_]Feature{ .el2vmsa, .el3, .neon, }), }; result[@intFromEnum(Feature.v8r)] = .{ .llvm_name = "v8r", .description = "Support ARM v8r instructions", .dependencies = featureSet(&[_]Feature{ .ccidx, .ccpp, .complxnum, .contextidr_el2, .crc, .dit, .dotprod, .flagm, .jsconv, .lse, .pan_rwv, .pauth, .ras, .rcpc_immo, .rdm, .sel2, .specrestrict, .tlb_rmi, .tracev8_4, .uaops, }), }; result[@intFromEnum(Feature.v9_1a)] = .{ .llvm_name = "v9.1a", .description = "Support ARM v9.1a instructions", .dependencies = featureSet(&[_]Feature{ .v8_6a, .v9a, }), }; result[@intFromEnum(Feature.v9_2a)] = .{ .llvm_name = "v9.2a", .description = "Support ARM v9.2a instructions", .dependencies = featureSet(&[_]Feature{ .v8_7a, .v9_1a, }), }; result[@intFromEnum(Feature.v9_3a)] = .{ .llvm_name = "v9.3a", .description = "Support ARM v9.3a instructions", .dependencies = featureSet(&[_]Feature{ .v8_8a, .v9_2a, }), }; result[@intFromEnum(Feature.v9_4a)] = .{ .llvm_name = "v9.4a", .description = "Support ARM v9.4a instructions", .dependencies = featureSet(&[_]Feature{ .v8_9a, .v9_3a, }), }; result[@intFromEnum(Feature.v9a)] = .{ .llvm_name = "v9a", .description = "Support ARM v9a instructions", .dependencies = featureSet(&[_]Feature{ .mec, .sve2, .v8_5a, }), }; result[@intFromEnum(Feature.vh)] = .{ .llvm_name = "vh", .description = "Enables ARM v8.1 Virtual Host extension (FEAT_VHE)", .dependencies = featureSet(&[_]Feature{ .contextidr_el2, }), }; result[@intFromEnum(Feature.wfxt)] = .{ .llvm_name = "wfxt", .description = "Enable Armv8.7-A WFET and WFIT instruction (FEAT_WFxT)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.xs)] = .{ .llvm_name = "xs", .description = "Enable Armv8.7-A limited-TLB-maintenance instruction (FEAT_XS)", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.zcm)] = .{ .llvm_name = "zcm", .description = "Has zero-cycle register moves", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.zcz)] = .{ .llvm_name = "zcz", .description = "Has zero-cycle zeroing instructions", .dependencies = featureSet(&[_]Feature{ .zcz_gp, }), }; result[@intFromEnum(Feature.zcz_fp_workaround)] = .{ .llvm_name = "zcz-fp-workaround", .description = "The zero-cycle floating-point zeroing instruction has a bug", .dependencies = featureSet(&[_]Feature{}), }; result[@intFromEnum(Feature.zcz_gp)] = .{ .llvm_name = "zcz-gp", .description = "Has zero-cycle zeroing instructions for generic registers", .dependencies = featureSet(&[_]Feature{}), }; const ti = @typeInfo(Feature); for (&result, 0..) |*elem, i| { elem.index = i; elem.name = ti.Enum.fields[i].name; } break :blk result; }; pub const cpu = struct { pub const a64fx = CpuModel{ .name = "a64fx", .llvm_name = "a64fx", .features = featureSet(&[_]Feature{ .aggressive_fma, .arith_bcc_fusion, .complxnum, .perfmon, .predictable_select_expensive, .sha2, .sve, .use_postra_scheduler, .v8_2a, }), }; pub const ampere1 = CpuModel{ .name = "ampere1", .llvm_name = "ampere1", .features = featureSet(&[_]Feature{ .aes, .aggressive_fma, .arith_bcc_fusion, .cmp_bcc_fusion, .fuse_address, .fuse_aes, .fuse_literals, .lsl_fast, .perfmon, .rand, .sha3, .use_postra_scheduler, .v8_6a, }), }; pub const ampere1a = CpuModel{ .name = "ampere1a", .llvm_name = "ampere1a", .features = featureSet(&[_]Feature{ .aes, .aggressive_fma, .arith_bcc_fusion, .cmp_bcc_fusion, .fuse_address, .fuse_aes, .fuse_literals, .lsl_fast, .mte, .perfmon, .rand, .sha3, .sm4, .use_postra_scheduler, .v8_6a, }), }; pub const apple_a10 = CpuModel{ .name = "apple_a10", .llvm_name = "apple-a10", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crc, .crypto, .disable_latency_sched_heuristic, .fuse_aes, .fuse_crypto_eor, .lor, .pan, .perfmon, .rdm, .v8a, .vh, .zcm, .zcz, }), }; pub const apple_a11 = CpuModel{ .name = "apple_a11", .llvm_name = "apple-a11", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fullfp16, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8_2a, .zcm, .zcz, }), }; pub const apple_a12 = CpuModel{ .name = "apple_a12", .llvm_name = "apple-a12", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fullfp16, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8_3a, .zcm, .zcz, }), }; pub const apple_a13 = CpuModel{ .name = "apple_a13", .llvm_name = "apple-a13", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fuse_aes, .fuse_crypto_eor, .perfmon, .sha3, .v8_4a, .zcm, .zcz, }), }; pub const apple_a14 = CpuModel{ .name = "apple_a14", .llvm_name = "apple-a14", .features = featureSet(&[_]Feature{ .aggressive_fma, .alternate_sextload_cvt_f32_pattern, .altnzcv, .arith_bcc_fusion, .arith_cbz_fusion, .ccdp, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fptoint, .fuse_address, .fuse_adrp_add, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .perfmon, .predres, .sb, .sha3, .specrestrict, .ssbs, .v8_4a, .zcm, .zcz, }), }; pub const apple_a15 = CpuModel{ .name = "apple_a15", .llvm_name = "apple-a15", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fuse_address, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .perfmon, .sha3, .v8_6a, .zcm, .zcz, }), }; pub const apple_a16 = CpuModel{ .name = "apple_a16", .llvm_name = "apple-a16", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fuse_address, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .hcx, .perfmon, .sha3, .v8_6a, .zcm, .zcz, }), }; pub const apple_a7 = CpuModel{ .name = "apple_a7", .llvm_name = "apple-a7", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8a, .zcm, .zcz, .zcz_fp_workaround, }), }; pub const apple_a8 = CpuModel{ .name = "apple_a8", .llvm_name = "apple-a8", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8a, .zcm, .zcz, .zcz_fp_workaround, }), }; pub const apple_a9 = CpuModel{ .name = "apple_a9", .llvm_name = "apple-a9", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8a, .zcm, .zcz, .zcz_fp_workaround, }), }; pub const apple_latest = CpuModel{ .name = "apple_latest", .llvm_name = "apple-latest", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fuse_address, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .hcx, .perfmon, .sha3, .v8_6a, .zcm, .zcz, }), }; pub const apple_m1 = CpuModel{ .name = "apple_m1", .llvm_name = "apple-m1", .features = featureSet(&[_]Feature{ .aggressive_fma, .alternate_sextload_cvt_f32_pattern, .altnzcv, .arith_bcc_fusion, .arith_cbz_fusion, .ccdp, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fptoint, .fuse_address, .fuse_adrp_add, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .perfmon, .predres, .sb, .sha3, .specrestrict, .ssbs, .v8_4a, .zcm, .zcz, }), }; pub const apple_m2 = CpuModel{ .name = "apple_m2", .llvm_name = "apple-m2", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fp16fml, .fuse_address, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .perfmon, .sha3, .v8_6a, .zcm, .zcz, }), }; pub const apple_s4 = CpuModel{ .name = "apple_s4", .llvm_name = "apple-s4", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fullfp16, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8_3a, .zcm, .zcz, }), }; pub const apple_s5 = CpuModel{ .name = "apple_s5", .llvm_name = "apple-s5", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fullfp16, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8_3a, .zcm, .zcz, }), }; pub const carmel = CpuModel{ .name = "carmel", .llvm_name = "carmel", .features = featureSet(&[_]Feature{ .crypto, .fullfp16, .v8_2a, }), }; pub const cortex_a34 = CpuModel{ .name = "cortex_a34", .llvm_name = "cortex-a34", .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .v8a, }), }; pub const cortex_a35 = CpuModel{ .name = "cortex_a35", .llvm_name = "cortex-a35", .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .v8a, }), }; pub const cortex_a510 = CpuModel{ .name = "cortex_a510", .llvm_name = "cortex-a510", .features = featureSet(&[_]Feature{ .a510, .bf16, .ete, .fp16fml, .i8mm, .mte, .perfmon, .sve2_bitperm, .v9a, }), }; pub const cortex_a53 = CpuModel{ .name = "cortex_a53", .llvm_name = "cortex-a53", .features = featureSet(&[_]Feature{ .balance_fp_ops, .crc, .crypto, .custom_cheap_as_move, .fuse_adrp_add, .fuse_aes, .perfmon, .use_postra_scheduler, .v8a, }), }; pub const cortex_a55 = CpuModel{ .name = "cortex_a55", .llvm_name = "cortex-a55", .features = featureSet(&[_]Feature{ .crypto, .dotprod, .fullfp16, .fuse_address, .fuse_adrp_add, .fuse_aes, .perfmon, .rcpc, .use_postra_scheduler, .v8_2a, }), }; pub const cortex_a57 = CpuModel{ .name = "cortex_a57", .llvm_name = "cortex-a57", .features = featureSet(&[_]Feature{ .balance_fp_ops, .crc, .crypto, .custom_cheap_as_move, .enable_select_opt, .fuse_adrp_add, .fuse_aes, .fuse_literals, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, }), }; pub const cortex_a65 = CpuModel{ .name = "cortex_a65", .llvm_name = "cortex-a65", .features = featureSet(&[_]Feature{ .a65, .crypto, .dotprod, .fullfp16, .perfmon, .rcpc, .ssbs, .v8_2a, }), }; pub const cortex_a65ae = CpuModel{ .name = "cortex_a65ae", .llvm_name = "cortex-a65ae", .features = featureSet(&[_]Feature{ .a65, .crypto, .dotprod, .fullfp16, .perfmon, .rcpc, .ssbs, .v8_2a, }), }; pub const cortex_a710 = CpuModel{ .name = "cortex_a710", .llvm_name = "cortex-a710", .features = featureSet(&[_]Feature{ .a710, .bf16, .ete, .fp16fml, .i8mm, .mte, .perfmon, .sve2_bitperm, .v9a, }), }; pub const cortex_a715 = CpuModel{ .name = "cortex_a715", .llvm_name = "cortex-a715", .features = featureSet(&[_]Feature{ .bf16, .cmp_bcc_fusion, .enable_select_opt, .ete, .fp16fml, .fuse_adrp_add, .fuse_aes, .i8mm, .lsl_fast, .mte, .perfmon, .predictable_select_expensive, .spe, .sve2_bitperm, .use_postra_scheduler, .v9a, }), }; pub const cortex_a72 = CpuModel{ .name = "cortex_a72", .llvm_name = "cortex-a72", .features = featureSet(&[_]Feature{ .crc, .crypto, .enable_select_opt, .fuse_adrp_add, .fuse_aes, .fuse_literals, .perfmon, .predictable_select_expensive, .v8a, }), }; pub const cortex_a73 = CpuModel{ .name = "cortex_a73", .llvm_name = "cortex-a73", .features = featureSet(&[_]Feature{ .crc, .crypto, .enable_select_opt, .fuse_adrp_add, .fuse_aes, .perfmon, .predictable_select_expensive, .v8a, }), }; pub const cortex_a75 = CpuModel{ .name = "cortex_a75", .llvm_name = "cortex-a75", .features = featureSet(&[_]Feature{ .crypto, .dotprod, .enable_select_opt, .fullfp16, .fuse_adrp_add, .fuse_aes, .perfmon, .predictable_select_expensive, .rcpc, .v8_2a, }), }; pub const cortex_a76 = CpuModel{ .name = "cortex_a76", .llvm_name = "cortex-a76", .features = featureSet(&[_]Feature{ .a76, .crypto, .dotprod, .fullfp16, .perfmon, .rcpc, .ssbs, .v8_2a, }), }; pub const cortex_a76ae = CpuModel{ .name = "cortex_a76ae", .llvm_name = "cortex-a76ae", .features = featureSet(&[_]Feature{ .a76, .crypto, .dotprod, .fullfp16, .perfmon, .rcpc, .ssbs, .v8_2a, }), }; pub const cortex_a77 = CpuModel{ .name = "cortex_a77", .llvm_name = "cortex-a77", .features = featureSet(&[_]Feature{ .cmp_bcc_fusion, .crypto, .dotprod, .enable_select_opt, .fullfp16, .fuse_adrp_add, .fuse_aes, .lsl_fast, .perfmon, .predictable_select_expensive, .rcpc, .ssbs, .v8_2a, }), }; pub const cortex_a78 = CpuModel{ .name = "cortex_a78", .llvm_name = "cortex-a78", .features = featureSet(&[_]Feature{ .a78, .crypto, .dotprod, .fullfp16, .perfmon, .rcpc, .spe, .ssbs, .v8_2a, }), }; pub const cortex_a78c = CpuModel{ .name = "cortex_a78c", .llvm_name = "cortex-a78c", .features = featureSet(&[_]Feature{ .a78c, .crypto, .dotprod, .flagm, .fp16fml, .pauth, .perfmon, .rcpc, .spe, .ssbs, .v8_2a, }), }; pub const cortex_r82 = CpuModel{ .name = "cortex_r82", .llvm_name = "cortex-r82", .features = featureSet(&[_]Feature{ .cortex_r82, .fp16fml, .perfmon, .predres, .sb, .ssbs, .v8r, }), }; pub const cortex_x1 = CpuModel{ .name = "cortex_x1", .llvm_name = "cortex-x1", .features = featureSet(&[_]Feature{ .cmp_bcc_fusion, .crypto, .dotprod, .enable_select_opt, .fullfp16, .fuse_adrp_add, .fuse_aes, .lsl_fast, .perfmon, .predictable_select_expensive, .rcpc, .spe, .ssbs, .use_postra_scheduler, .v8_2a, }), }; pub const cortex_x1c = CpuModel{ .name = "cortex_x1c", .llvm_name = "cortex-x1c", .features = featureSet(&[_]Feature{ .cmp_bcc_fusion, .crypto, .dotprod, .enable_select_opt, .flagm, .fullfp16, .fuse_adrp_add, .fuse_aes, .lse2, .lsl_fast, .pauth, .perfmon, .predictable_select_expensive, .rcpc_immo, .spe, .ssbs, .use_postra_scheduler, .v8_2a, }), }; pub const cortex_x2 = CpuModel{ .name = "cortex_x2", .llvm_name = "cortex-x2", .features = featureSet(&[_]Feature{ .bf16, .cmp_bcc_fusion, .enable_select_opt, .ete, .fp16fml, .fuse_adrp_add, .fuse_aes, .i8mm, .lsl_fast, .mte, .perfmon, .predictable_select_expensive, .sve2_bitperm, .use_postra_scheduler, .v9a, }), }; pub const cortex_x3 = CpuModel{ .name = "cortex_x3", .llvm_name = "cortex-x3", .features = featureSet(&[_]Feature{ .bf16, .enable_select_opt, .ete, .fp16fml, .fuse_adrp_add, .fuse_aes, .i8mm, .lsl_fast, .mte, .perfmon, .predictable_select_expensive, .spe, .sve2_bitperm, .use_postra_scheduler, .v9a, }), }; pub const cyclone = CpuModel{ .name = "cyclone", .llvm_name = "cyclone", .features = featureSet(&[_]Feature{ .alternate_sextload_cvt_f32_pattern, .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .disable_latency_sched_heuristic, .fuse_aes, .fuse_crypto_eor, .perfmon, .v8a, .zcm, .zcz, .zcz_fp_workaround, }), }; pub const emag = CpuModel{ .name = "emag", .llvm_name = null, .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .v8a, }), }; pub const exynos_m1 = CpuModel{ .name = "exynos_m1", .llvm_name = null, .features = featureSet(&[_]Feature{ .crc, .crypto, .exynos_cheap_as_move, .force_32bit_jump_tables, .fuse_aes, .perfmon, .slow_misaligned_128store, .slow_paired_128, .use_postra_scheduler, .use_reciprocal_square_root, .v8a, }), }; pub const exynos_m2 = CpuModel{ .name = "exynos_m2", .llvm_name = null, .features = featureSet(&[_]Feature{ .crc, .crypto, .exynos_cheap_as_move, .force_32bit_jump_tables, .fuse_aes, .perfmon, .slow_misaligned_128store, .slow_paired_128, .use_postra_scheduler, .v8a, }), }; pub const exynos_m3 = CpuModel{ .name = "exynos_m3", .llvm_name = "exynos-m3", .features = featureSet(&[_]Feature{ .crc, .crypto, .exynos_cheap_as_move, .force_32bit_jump_tables, .fuse_address, .fuse_adrp_add, .fuse_aes, .fuse_csel, .fuse_literals, .lsl_fast, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, }), }; pub const exynos_m4 = CpuModel{ .name = "exynos_m4", .llvm_name = "exynos-m4", .features = featureSet(&[_]Feature{ .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .dotprod, .exynos_cheap_as_move, .force_32bit_jump_tables, .fullfp16, .fuse_address, .fuse_adrp_add, .fuse_aes, .fuse_arith_logic, .fuse_csel, .fuse_literals, .lsl_fast, .perfmon, .use_postra_scheduler, .v8_2a, .zcz, }), }; pub const exynos_m5 = CpuModel{ .name = "exynos_m5", .llvm_name = "exynos-m5", .features = featureSet(&[_]Feature{ .arith_bcc_fusion, .arith_cbz_fusion, .crypto, .dotprod, .exynos_cheap_as_move, .force_32bit_jump_tables, .fullfp16, .fuse_address, .fuse_adrp_add, .fuse_aes, .fuse_arith_logic, .fuse_csel, .fuse_literals, .lsl_fast, .perfmon, .use_postra_scheduler, .v8_2a, .zcz, }), }; pub const falkor = CpuModel{ .name = "falkor", .llvm_name = "falkor", .features = featureSet(&[_]Feature{ .crc, .crypto, .custom_cheap_as_move, .lsl_fast, .perfmon, .predictable_select_expensive, .rdm, .slow_strqro_store, .use_postra_scheduler, .v8a, .zcz, }), }; pub const generic = CpuModel{ .name = "generic", .llvm_name = "generic", .features = featureSet(&[_]Feature{ .enable_select_opt, .ete, .fuse_adrp_add, .fuse_aes, .neon, .use_postra_scheduler, }), }; pub const kryo = CpuModel{ .name = "kryo", .llvm_name = "kryo", .features = featureSet(&[_]Feature{ .crc, .crypto, .custom_cheap_as_move, .lsl_fast, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, .zcz, }), }; pub const neoverse_512tvb = CpuModel{ .name = "neoverse_512tvb", .llvm_name = "neoverse-512tvb", .features = featureSet(&[_]Feature{ .bf16, .ccdp, .crypto, .enable_select_opt, .fp16fml, .fuse_adrp_add, .fuse_aes, .i8mm, .lsl_fast, .perfmon, .predictable_select_expensive, .rand, .spe, .ssbs, .sve, .use_postra_scheduler, .v8_4a, }), }; pub const neoverse_e1 = CpuModel{ .name = "neoverse_e1", .llvm_name = "neoverse-e1", .features = featureSet(&[_]Feature{ .crypto, .dotprod, .fullfp16, .fuse_adrp_add, .fuse_aes, .perfmon, .rcpc, .ssbs, .use_postra_scheduler, .v8_2a, }), }; pub const neoverse_n1 = CpuModel{ .name = "neoverse_n1", .llvm_name = "neoverse-n1", .features = featureSet(&[_]Feature{ .crypto, .dotprod, .enable_select_opt, .fullfp16, .fuse_adrp_add, .fuse_aes, .lsl_fast, .perfmon, .predictable_select_expensive, .rcpc, .spe, .ssbs, .use_postra_scheduler, .v8_2a, }), }; pub const neoverse_n2 = CpuModel{ .name = "neoverse_n2", .llvm_name = "neoverse-n2", .features = featureSet(&[_]Feature{ .bf16, .crypto, .enable_select_opt, .ete, .fuse_adrp_add, .fuse_aes, .i8mm, .lsl_fast, .mte, .perfmon, .predictable_select_expensive, .sve2_bitperm, .use_postra_scheduler, .v8_5a, }), }; pub const neoverse_v1 = CpuModel{ .name = "neoverse_v1", .llvm_name = "neoverse-v1", .features = featureSet(&[_]Feature{ .bf16, .ccdp, .crypto, .enable_select_opt, .fp16fml, .fuse_adrp_add, .fuse_aes, .i8mm, .lsl_fast, .no_sve_fp_ld1r, .perfmon, .predictable_select_expensive, .rand, .spe, .ssbs, .sve, .use_postra_scheduler, .v8_4a, }), }; pub const neoverse_v2 = CpuModel{ .name = "neoverse_v2", .llvm_name = "neoverse-v2", .features = featureSet(&[_]Feature{ .bf16, .enable_select_opt, .ete, .fp16fml, .fuse_aes, .i8mm, .lsl_fast, .mte, .perfmon, .predictable_select_expensive, .rand, .spe, .sve2_bitperm, .use_postra_scheduler, .v9a, }), }; pub const saphira = CpuModel{ .name = "saphira", .llvm_name = "saphira", .features = featureSet(&[_]Feature{ .crypto, .custom_cheap_as_move, .lsl_fast, .perfmon, .predictable_select_expensive, .spe, .use_postra_scheduler, .v8_4a, .zcz, }), }; pub const thunderx = CpuModel{ .name = "thunderx", .llvm_name = "thunderx", .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, }), }; pub const thunderx2t99 = CpuModel{ .name = "thunderx2t99", .llvm_name = "thunderx2t99", .features = featureSet(&[_]Feature{ .aggressive_fma, .arith_bcc_fusion, .crypto, .predictable_select_expensive, .use_postra_scheduler, .v8_1a, }), }; pub const thunderx3t110 = CpuModel{ .name = "thunderx3t110", .llvm_name = "thunderx3t110", .features = featureSet(&[_]Feature{ .aggressive_fma, .arith_bcc_fusion, .balance_fp_ops, .crypto, .perfmon, .predictable_select_expensive, .strict_align, .use_postra_scheduler, .v8_3a, }), }; pub const thunderxt81 = CpuModel{ .name = "thunderxt81", .llvm_name = "thunderxt81", .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, }), }; pub const thunderxt83 = CpuModel{ .name = "thunderxt83", .llvm_name = "thunderxt83", .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, }), }; pub const thunderxt88 = CpuModel{ .name = "thunderxt88", .llvm_name = "thunderxt88", .features = featureSet(&[_]Feature{ .crc, .crypto, .perfmon, .predictable_select_expensive, .use_postra_scheduler, .v8a, }), }; pub const tsv110 = CpuModel{ .name = "tsv110", .llvm_name = "tsv110", .features = featureSet(&[_]Feature{ .crypto, .custom_cheap_as_move, .dotprod, .fp16fml, .fuse_aes, .perfmon, .spe, .use_postra_scheduler, .v8_2a, }), }; pub const xgene1 = CpuModel{ .name = "xgene1", .llvm_name = null, .features = featureSet(&[_]Feature{ .perfmon, .v8a, }), }; };
https://raw.githubusercontent.com/2lambda123/ziglang-zig/d7563a7753393d7f0d1af445276a64b8a55cb857/lib/std/Target/aarch64.zig
const std = @import("std"); const App = @import("app.zig").App; const Terminal = @import("terminal.zig"); const DB = @import("db.zig"); const ansi_term = @import("ansi-term"); const Command = union(enum) { add: []const u8, rm: []const u8, reset, help, sync, }; const helpMenu = \\Usage: sw [options] \\ \\add/a [directory] -- adds a directory to the list \\remove/rm [directory] -- removes a directory from the list \\reset -- delete all entries from the database \\help -- shows this help menu ; fn parseArgs(args: *std.process.ArgIterator) !?Command { _ = args.skip(); while (args.next()) |arg| { if (std.mem.eql(u8, arg, "add") or std.mem.eql(u8, arg, "a")) { if (args.next()) |dir| { return Command{ .add = dir }; } else { std.log.err("provide path to be added", .{}); return error.InvalidCmd; } } else if (std.mem.eql(u8, arg, "remove") or std.mem.eql(u8, arg, "rm")) { if (args.next()) |dir| { return Command{ .rm = dir }; } else { std.log.err("provide path to be removed", .{}); return error.InvalidCmd; } } else if (std.mem.eql(u8, arg, "reset")) { return .reset; } else if (std.mem.eql(u8, arg, "help")) { return .help; } else if (std.mem.eql(u8, arg, "sync")) { return .sync; } } return null; } pub fn main() !void { var arena_alloc = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_alloc.deinit(); var alloc = arena_alloc.allocator(); var db = try DB.init(alloc); var args = std.process.argsWithAllocator(alloc) catch unreachable; defer args.deinit(); const stdout = std.io.getStdOut().writer(); const command = parseArgs(&args) catch { return; }; if (command) |cmd| { switch (cmd) { .add => |dir| { const real_path = db.addEntry(dir) catch { std.log.err("unable to add entry", .{}); return; }; try stdout.print("added {s}", .{real_path}); }, .rm => |dir| { const real_path = db.removeEntry(dir) catch { std.log.err("unable to remove entry", .{}); return; }; try stdout.print("removed {s}", .{real_path}); }, .reset => try db.deleteAll(), .help => try stdout.print("{s}\n", .{helpMenu}), .sync => try db.sync(), } return; } var term = try Terminal.init(); var app = try App.init(term, db, alloc); defer app.deinit() catch {}; const selection = try app.run(); if (selection) |val| { try stdout.print("{s}\n", .{val}); } } test { std.testing.refAllDecls(@This()); }
https://raw.githubusercontent.com/1nwf/switch/a8d03f3430f7a06689b5506c4e9f837a073cc863/src/main.zig
// // Now let's create a function that takes a parameter. Here's an // example that takes two parameters. As you can see, parameters // are declared just like any other types ("name": "type"): // // fn myFunction(number: u8, is_lucky: bool) { // ... // } // const std = @import("std"); pub fn main() void { std.debug.print("Powers of two: {} {} {} {}\n", .{ twoToThe(1), twoToThe(2), twoToThe(3), twoToThe(4), }); } // Please give this function the correct input parameter(s). // You'll need to figure out the parameter name and type that we're // expecting. The output type has already been specified for you. // fn twoToThe(my_number: u32) u32 { return std.math.pow(u32, 2, my_number); // std.math.pow(type, a, b) takes a numeric type and two numbers // of that type and returns "a to the power of b" as that same // numeric type. }
https://raw.githubusercontent.com/rhysd/misc/5beb6fa40784e82452ce60af2adbb5d73903a5d7/ziglings/19_functions2.zig
pub const QueenError = error{ InitializationFailure, }; pub const Queen = struct { row: i8, col: i8, pub fn init(row: i8, col: i8) QueenError!Queen { if (row < 0 or 7 < row) { return QueenError.InitializationFailure; } if (col < 0 or 7 < col) { return QueenError.InitializationFailure; } return .{ .row = row, .col = col }; } pub fn canAttack(self: Queen, other: Queen) QueenError!bool { const drow = self.row - other.row; const dcol = self.col - other.col; return (drow == 0) or (dcol == 0) or (dcol * dcol == drow * drow); } };
https://raw.githubusercontent.com/ar90n/lab/6623f927466522ab5a47dfe67a5903da7c97d48b/sandbox/exercism/zig/queen-attack/queen_attack.zig
allocator: std.mem.Allocator, const RHI = @This(); var rhi: *RHI = undefined; fn messageCallback( source: c.GLenum, err_type: c.GLenum, id: c.GLuint, severity: c.GLenum, length: c.GLsizei, message: [*c]const c.GLchar, _: ?*const anyopaque, ) callconv(.C) void { const source_str: []const u8 = switch (source) { c.GL_DEBUG_SOURCE_API => "API", c.GL_DEBUG_SOURCE_WINDOW_SYSTEM => "WINDOW SYSTEM", c.GL_DEBUG_SOURCE_SHADER_COMPILER => "SHADER COMPILER", c.GL_DEBUG_SOURCE_THIRD_PARTY => "THIRD PARTY", c.GL_DEBUG_SOURCE_APPLICATION => "APPLICATION", else => "OTHER", }; const type_str: []const u8 = switch (err_type) { c.GL_DEBUG_TYPE_ERROR => "ERROR", c.GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR => "DEPRECATED_BEHAVIOR", c.GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR => "UNDEFINED_BEHAVIOR", c.GL_DEBUG_TYPE_PORTABILITY => "PORTABILITY", c.GL_DEBUG_TYPE_PERFORMANCE => "PERFORMANCE", c.GL_DEBUG_TYPE_MARKER => "MARKER", else => "OTHER", }; const severity_str: []const u8 = switch (severity) { c.GL_DEBUG_SEVERITY_LOW => "LOW", c.GL_DEBUG_SEVERITY_MEDIUM => "MEDIUM", c.GL_DEBUG_SEVERITY_HIGH => "HIGH", else => "NOTIFICATION", }; const msg_str: []const u8 = message[0..@intCast(length)]; std.log.err("OpenGL Error: {s}, {s}, {s}, {d} {s}\n", .{ source_str, type_str, severity_str, id, msg_str, }); } pub fn init(allocator: std.mem.Allocator) void { c.glEnable(c.GL_DEBUG_OUTPUT); c.glDebugMessageCallback(&messageCallback, null); c.glClipControl(c.GL_LOWER_LEFT, c.GL_NEGATIVE_ONE_TO_ONE); rhi = allocator.create(RHI) catch @panic("OOM"); rhi.* = .{ .allocator = allocator }; } pub fn deinit() void { rhi.allocator.destroy(rhi); } pub fn beginFrame() void { const dims = ui.windowDimensions(); c.glViewport(0, 0, @intCast(dims[0]), @intCast(dims[1])); c.glClear(c.GL_COLOR_BUFFER_BIT | c.GL_DEPTH_BUFFER_BIT); c.glClearColor(0, 0, 0, 1); } pub fn createProgram() u32 { const p = c.glCreateProgram(); return @intCast(p); } pub fn createVAO() u32 { var vao: c.GLuint = 0; c.glCreateVertexArrays(1, @ptrCast(&vao)); return @intCast(vao); } pub const attributeData = struct { position: [3]f32, color: [4]f32, }; pub fn attachBuffer(data: []attributeData) struct { vao: u32, buffer: u32 } { var buffer: c.GLuint = 0; c.glCreateBuffers(1, @ptrCast(&buffer)); const data_size: usize = @sizeOf(attributeData); const size = @as(isize, @intCast(data.len * data_size)); const data_ptr: *const anyopaque = data.ptr; c.glNamedBufferData(buffer, size, data_ptr, c.GL_STATIC_DRAW); var vao: c.GLuint = 0; c.glCreateVertexArrays(1, @ptrCast(&vao)); c.glVertexArrayVertexBuffer(vao, 0, buffer, 0, @intCast(data_size)); const vec_3_size: c.GLsizei = @intCast(@sizeOf(f32) * 3); c.glEnableVertexArrayAttrib(vao, 0); c.glEnableVertexArrayAttrib(vao, 1); c.glVertexArrayAttribFormat(vao, 0, 3, c.GL_FLOAT, c.GL_FALSE, 0); c.glVertexArrayAttribFormat(vao, 1, 4, c.GL_FLOAT, c.GL_FALSE, vec_3_size); c.glVertexArrayAttribBinding(vao, 0, 0); c.glVertexArrayAttribBinding(vao, 1, 0); return .{ .vao = vao, .buffer = buffer }; } pub fn attachShaders(program: u32, vertex: []const u8, frag: []const u8) void { const shaders = [_]struct { source: []const u8, shader_type: c.GLenum }{ .{ .source = vertex, .shader_type = c.GL_VERTEX_SHADER }, .{ .source = frag, .shader_type = c.GL_FRAGMENT_SHADER }, }; const log_len: usize = 1024; var i: usize = 0; while (i < shaders.len) : (i += 1) { const source: [:0]u8 = std.mem.concatWithSentinel(rhi.allocator, u8, &[_][]const u8{shaders[i].source}, 0) catch @panic("OOM"); defer rhi.allocator.free(source); const shader = c.glCreateShader(shaders[i].shader_type); c.glShaderSource(shader, 1, &[_][*c]const u8{source.ptr}, null); c.glCompileShader(shader); var success: c.GLint = 0; c.glGetShaderiv(shader, c.GL_COMPILE_STATUS, &success); if (success == c.GL_FALSE) { var infoLog: [log_len]u8 = std.mem.zeroes([log_len]u8); var logSize: c.GLsizei = 0; c.glGetShaderInfoLog(shader, @intCast(log_len), &logSize, @ptrCast(&infoLog)); const len: usize = @intCast(logSize); std.debug.panic("ERROR::SHADER::COMPILATION_FAILED\n{s}\n{s}\n", .{ infoLog[0..len], source }); } c.glAttachShader(@intCast(program), shader); } { c.glLinkProgram(@intCast(program)); var success: c.GLint = 0; c.glGetProgramiv(@intCast(program), c.GL_LINK_STATUS, &success); if (success == c.GL_FALSE) { var infoLog: [log_len]u8 = std.mem.zeroes([log_len]u8); var logSize: c.GLsizei = 0; c.glGetProgramInfoLog(@intCast(program), @intCast(log_len), &logSize, @ptrCast(&infoLog)); const len: usize = @intCast(logSize); std.debug.panic("ERROR::PROGRAM::LINKING_FAILED\n{s}\n", .{infoLog[0..len]}); } } return; } pub fn drawArrays(program: u32, vao: u32, count: usize) void { c.glUseProgram(@intCast(program)); c.glBindVertexArray(vao); c.glDrawArrays(c.GL_TRIANGLES, 0, @intCast(count)); } pub fn drawPoints(program: u32, vao: u32, count: usize) void { c.glUseProgram(@intCast(program)); c.glBindVertexArray(vao); c.glPointSize(30.0); c.glDrawArrays(c.GL_POINTS, 0, @intCast(count)); c.glPointSize(1.0); } pub fn setUniform1f(program: u32, name: []const u8, v: f32) void { const location: c.GLint = c.glGetUniformLocation(@intCast(program), @ptrCast(name)); c.glProgramUniform1f(@intCast(program), location, @floatCast(v)); } pub fn delete(program: u32, vao: u32, buffer: u32) void { c.glDeleteProgram(program); c.glDeleteVertexArrays(1, @ptrCast(&vao)); if (buffer != 0) c.glDeleteBuffers(1, @ptrCast(&buffer)); } const c = @cImport({ @cInclude("glad/gl.h"); }); const std = @import("std"); const ui = @import("../ui/ui.zig");
https://raw.githubusercontent.com/btipling/foundations/287121cad75f9af5d5188d2ced629e7509d96843/src/foundations/rhi/rhi.zig
const std = @import("std"); const root = @import("main.zig"); const math = std.math; const expectEqual = std.testing.expectEqual; const expect = std.testing.expect; const panic = std.debug.panic; pub const Vec2 = GenericVector(2, f32); pub const Vec2_f64 = GenericVector(2, f64); pub const Vec2_i32 = GenericVector(2, i32); pub const Vec2_usize = GenericVector(2, usize); pub const Vec3 = GenericVector(3, f32); pub const Vec3_f64 = GenericVector(3, f64); pub const Vec3_i32 = GenericVector(3, i32); pub const Vec3_usize = GenericVector(3, usize); pub const Vec4 = GenericVector(4, f32); pub const Vec4_f64 = GenericVector(4, f64); pub const Vec4_i32 = GenericVector(4, i32); pub const Vec4_usize = GenericVector(4, usize); /// A generic vector. pub fn GenericVector(comptime dimensions: comptime_int, comptime T: type) type { if (@typeInfo(T) != .Float and @typeInfo(T) != .Int) { @compileError("Vectors not implemented for " ++ @typeName(T)); } if (dimensions < 2 or dimensions > 4) { @compileError("Dimensions must be 2, 3 or 4!"); } return extern struct { const Self = @This(); data: @Vector(dimensions, T), pub usingnamespace switch (dimensions) { 2 => extern struct { /// Construct new vector. pub fn new(vx: T, vy: T) Self { return .{ .data = [2]T{ vx, vy } }; } }, 3 => extern struct { /// Construct new vector. pub fn new(vx: T, vy: T, vz: T) Self { return .{ .data = [3]T{ vx, vy, vz } }; } pub fn z(self: Self) T { return self.data[2]; } /// Shorthand for (0, 0, 1). pub fn forward() Self { return new(0, 0, 1); } /// Shorthand for (0, 0, -1). pub fn back() Self { return forward().negate(); } /// Construct the cross product (as vector) from two vectors. pub fn cross(first_vector: Self, second_vector: Self) Self { const x1 = first_vector.x(); const y1 = first_vector.y(); const z1 = first_vector.z(); const x2 = second_vector.x(); const y2 = second_vector.y(); const z2 = second_vector.z(); const result_x = (y1 * z2) - (z1 * y2); const result_y = (z1 * x2) - (x1 * z2); const result_z = (x1 * y2) - (y1 * x2); return new(result_x, result_y, result_z); } }, 4 => extern struct { /// Construct new vector. pub fn new(vx: T, vy: T, vz: T, vw: T) Self { return .{ .data = [4]T{ vx, vy, vz, vw } }; } /// Shorthand for (0, 0, 1, 0). pub fn forward() Self { return new(0, 0, 1, 0); } /// Shorthand for (0, 0, -1, 0). pub fn back() Self { return forward().negate(); } pub fn z(self: Self) T { return self.data[2]; } pub fn w(self: Self) T { return self.data[3]; } }, else => unreachable, }; pub fn x(self: Self) T { return self.data[0]; } pub fn y(self: Self) T { return self.data[1]; } /// Set all components to the same given value. pub fn set(val: T) Self { const result = @splat(dimensions, val); return .{ .data = result }; } /// Shorthand for (0..). pub fn zero() Self { return set(0); } /// Shorthand for (1..). pub fn one() Self { return set(1); } /// Shorthand for (0, 1). pub fn up() Self { return switch (dimensions) { 2 => Self.new(0, 1), 3 => Self.new(0, 1, 0), 4 => Self.new(0, 1, 0, 0), else => unreachable, }; } /// Shorthand for (0, -1). pub fn down() Self { return up().negate(); } /// Shorthand for (1, 0). pub fn right() Self { return switch (dimensions) { 2 => Self.new(1, 0), 3 => Self.new(1, 0, 0), 4 => Self.new(1, 0, 0, 0), else => unreachable, }; } /// Shorthand for (-1, 0). pub fn left() Self { return right().negate(); } /// Negate the given vector. pub fn negate(self: Self) Self { return self.scale(-1); } /// Cast a type to another type. /// It's like builtins: @intCast, @floatCast, @intToFloat, @floatToInt. pub fn cast(self: Self, comptime dest_type: type) GenericVector(dimensions, dest_type) { const dest_info = @typeInfo(dest_type); if (dest_info != .Float and dest_info != .Int) { panic("Error, dest type should be integer or float.\n", .{}); } var result: [dimensions]dest_type = undefined; for (result, 0..) |_, i| { result[i] = math.lossyCast(dest_type, self.data[i]); } return .{ .data = result }; } /// Construct new vector from slice. pub fn fromSlice(slice: []const T) Self { const result = slice[0..dimensions].*; return .{ .data = result }; } /// Transform vector to array. pub fn toArray(self: Self) [dimensions]T { return self.data; } /// Return the angle (in degrees) between two vectors. pub fn getAngle(first_vector: Self, second_vector: Self) T { const dot_product = dot(norm(first_vector), norm(second_vector)); return root.toDegrees(math.acos(dot_product)); } /// Return the length (magnitude) of given vector. /// √[x^2 + y^2 + z^2 ...] pub fn length(self: Self) T { return @sqrt(self.dot(self)); } /// Return the distance between two points. /// √[(x1 - x2)^2 + (y1 - y2)^2 + (z1 - z2)^2 ...] pub fn distance(first_vector: Self, second_vector: Self) T { return length(first_vector.sub(second_vector)); } /// Construct new normalized vector from a given one. pub fn norm(self: Self) Self { const l = self.length(); if (l == 0) { return self; } const result = self.data / @splat(dimensions, l); return .{ .data = result }; } /// Return true if two vectors are equals. pub fn eql(first_vector: Self, second_vector: Self) bool { return @reduce(.And, first_vector.data == second_vector.data); } /// Substraction between two given vector. pub fn sub(first_vector: Self, second_vector: Self) Self { const result = first_vector.data - second_vector.data; return .{ .data = result }; } /// Addition betwen two given vector. pub fn add(first_vector: Self, second_vector: Self) Self { const result = first_vector.data + second_vector.data; return .{ .data = result }; } /// Component wise multiplication betwen two given vector. pub fn mul(first_vector: Self, second_vector: Self) Self { const result = first_vector.data * second_vector.data; return .{ .data = result }; } /// Construct vector from the max components in two vectors pub fn max(first_vector: Self, second_vector: Self) Self { const result = @max(first_vector.data, second_vector.data); return .{ .data = result }; } /// Construct vector from the min components in two vectors pub fn min(first_vector: Self, second_vector: Self) Self { const result = @min(first_vector.data, second_vector.data); return .{ .data = result }; } /// Construct new vector after multiplying each components by a given scalar pub fn scale(self: Self, scalar: T) Self { const result = self.data * @splat(dimensions, scalar); return .{ .data = result }; } /// Return the dot product between two given vector. /// (x1 * x2) + (y1 * y2) + (z1 * z2) ... pub fn dot(first_vector: Self, second_vector: Self) T { return @reduce(.Add, first_vector.data * second_vector.data); } /// Linear interpolation between two vectors pub fn lerp(first_vector: Self, second_vector: Self, t: T) Self { const from = first_vector.data; const to = second_vector.data; const result = from + (to - from) * @splat(dimensions, t); return .{ .data = result }; } }; } test "zalgebra.Vectors.eql" { // Vec2 { const a = Vec2.new(1, 2); const b = Vec2.new(1, 2); const c = Vec2.new(1.5, 2); try expectEqual(Vec2.eql(a, b), true); try expectEqual(Vec2.eql(a, c), false); } // Vec3 { const a = Vec3.new(1, 2, 3); const b = Vec3.new(1, 2, 3); const c = Vec3.new(1.5, 2, 3); try expectEqual(Vec3.eql(a, b), true); try expectEqual(Vec3.eql(a, c), false); } // Vec4 { const a = Vec4.new(1, 2, 3, 4); const b = Vec4.new(1, 2, 3, 4); const c = Vec4.new(1.5, 2, 3, 4); try expectEqual(Vec4.eql(a, b), true); try expectEqual(Vec4.eql(a, c), false); } } test "zalgebra.Vectors.set" { // Vec2 { const a = Vec2.new(2.5, 2.5); const b = Vec2.set(2.5); try expectEqual(a, b); } // Vec3 { const a = Vec3.new(2.5, 2.5, 2.5); const b = Vec3.set(2.5); try expectEqual(a, b); } // Vec4 { const a = Vec4.new(2.5, 2.5, 2.5, 2.5); const b = Vec4.set(2.5); try expectEqual(a, b); } } test "zalgebra.Vectors.add" { // Vec2 { const a = Vec2.one(); const b = Vec2.one(); try expectEqual(a.add(b), Vec2.set(2)); } // Vec3 { const a = Vec3.one(); const b = Vec3.one(); try expectEqual(a.add(b), Vec3.set(2)); } // Vec4 { const a = Vec4.one(); const b = Vec4.one(); try expectEqual(a.add(b), Vec4.set(2)); } } test "zalgebra.Vectors.negate" { // Vec2 { const a = Vec2.set(5); const a_negated = Vec2.set(-5); try expectEqual(a.negate(), a_negated); } // Vec3 { const a = Vec3.set(5); const a_negated = Vec3.set(-5); try expectEqual(a.negate(), a_negated); } // Vec4 { const a = Vec4.set(5); const a_negated = Vec4.set(-5); try expectEqual(a.negate(), a_negated); } } test "zalgebra.Vectors.getAngle" { // Vec2 { const a = Vec2.right(); const b = Vec2.up(); const c = Vec2.left(); const d = Vec2.one(); try expectEqual(a.getAngle(a), 0); try expectEqual(a.getAngle(b), 90); try expectEqual(a.getAngle(c), 180); try expectEqual(a.getAngle(d), 45); } // Vec3 { const a = Vec3.right(); const b = Vec3.up(); const c = Vec3.left(); const d = Vec3.new(1, 1, 0); try expectEqual(a.getAngle(a), 0); try expectEqual(a.getAngle(b), 90); try expectEqual(a.getAngle(c), 180); try expectEqual(a.getAngle(d), 45); } // Vec4 { const a = Vec4.right(); const b = Vec4.up(); const c = Vec4.left(); const d = Vec4.new(1, 1, 0, 0); try expectEqual(a.getAngle(a), 0); try expectEqual(a.getAngle(b), 90); try expectEqual(a.getAngle(c), 180); try expectEqual(a.getAngle(d), 45); } } test "zalgebra.Vectors.toArray" { //Vec2 { const a = Vec2.up().toArray(); const b = [_]f32{ 0, 1 }; try std.testing.expectEqualSlices(f32, &a, &b); } //Vec3 { const a = Vec3.up().toArray(); const b = [_]f32{ 0, 1, 0 }; try std.testing.expectEqualSlices(f32, &a, &b); } //Vec4 { const a = Vec4.up().toArray(); const b = [_]f32{ 0, 1, 0, 0 }; try std.testing.expectEqualSlices(f32, &a, &b); } } test "zalgebra.Vectors.length" { // Vec2 { const a = Vec2.new(1.5, 2.6); try expectEqual(a.length(), 3.00166606); } // Vec3 { const a = Vec3.new(1.5, 2.6, 3.7); try expectEqual(a.length(), 4.7644519); } // Vec4 { const a = Vec4.new(1.5, 2.6, 3.7, 4.7); try expectEqual(a.length(), 6.69253301); } } test "zalgebra.Vectors.distance" { // Vec2 { const a = Vec2.zero(); const b = Vec2.left(); const c = Vec2.new(0, 5); try expectEqual(a.distance(b), 1); try expectEqual(a.distance(c), 5); } // Vec3 { const a = Vec3.zero(); const b = Vec3.left(); const c = Vec3.new(0, 5, 0); try expectEqual(a.distance(b), 1); try expectEqual(a.distance(c), 5); } // Vec4 { const a = Vec4.zero(); const b = Vec4.left(); const c = Vec4.new(0, 5, 0, 0); try expectEqual(a.distance(b), 1); try expectEqual(a.distance(c), 5); } } test "zalgebra.Vectors.normalize" { // Vec2 { const a = Vec2.new(1.5, 2.6); const a_normalized = Vec2.new(0.499722480, 0.866185605); try expectEqual(a.norm(), a_normalized); } // Vec3 { const a = Vec3.new(1.5, 2.6, 3.7); const a_normalized = Vec3.new(0.314831584, 0.545708060, 0.776584625); try expectEqual(a.norm(), a_normalized); } // Vec4 { const a = Vec4.new(1.5, 2.6, 3.7, 4.0); const a_normalized = Vec4.new(0.241121411, 0.417943745, 0.594766139, 0.642990410); try expectEqual(a.norm(), a_normalized); } } test "zalgebra.Vectors.scale" { // Vec2 { const a = Vec2.new(1, 2); const a_scaled = Vec2.new(5, 10); try expectEqual(a.scale(5), a_scaled); } // Vec3 { const a = Vec3.new(1, 2, 3); const a_scaled = Vec3.new(5, 10, 15); try expectEqual(a.scale(5), a_scaled); } // Vec4 { const a = Vec4.new(1, 2, 3, 4); const a_scaled = Vec4.new(5, 10, 15, 20); try expectEqual(a.scale(5), a_scaled); } } test "zalgebra.Vectors.dot" { // Vec2 { const a = Vec2.new(1.5, 2.6); const b = Vec2.new(2.5, 3.45); try expectEqual(a.dot(b), 12.7200002); } // Vec3 { const a = Vec3.new(1.5, 2.6, 3.7); const b = Vec3.new(2.5, 3.45, 1.0); try expectEqual(a.dot(b), 16.42); } // Vec4 { const a = Vec4.new(1.5, 2.6, 3.7, 5); const b = Vec4.new(2.5, 3.45, 1.0, 1); try expectEqual(a.dot(b), 21.4200000); } } test "zalgebra.Vectors.lerp" { // Vec2 { const a = Vec2.new(-10, 0); const b = Vec2.set(10); try expectEqual(Vec2.lerp(a, b, 0.5), Vec2.new(0, 5)); } // Vec3 { const a = Vec3.new(-10, 0, -10); const b = Vec3.set(10); try expectEqual(Vec3.lerp(a, b, 0.5), Vec3.new(0, 5, 0)); } // Vec4 { const a = Vec4.new(-10, 0, -10, -10); const b = Vec4.set(10); try expectEqual(Vec4.lerp(a, b, 0.5), Vec4.new(0, 5, 0, 0)); } } test "zalgebra.Vectors.min" { // Vec2 { const a = Vec2.new(10, -2); const b = Vec2.new(-10, 5); const minimum = Vec2.new(-10, -2); try expectEqual(Vec2.min(a, b), minimum); } // Vec3 { const a = Vec3.new(10, -2, 0); const b = Vec3.new(-10, 5, 0); const minimum = Vec3.new(-10, -2, 0); try expectEqual(Vec3.min(a, b), minimum); } // Vec4 { const a = Vec4.new(10, -2, 0, 1); const b = Vec4.new(-10, 5, 0, 1.01); const minimum = Vec4.new(-10, -2, 0, 1); try expectEqual(Vec4.min(a, b), minimum); } } test "zalgebra.Vectors.max" { // Vec2 { const a = Vec2.new(10, -2); const b = Vec2.new(-10, 5); const maximum = Vec2.new(10, 5); try expectEqual(Vec2.max(a, b), maximum); } // Vec3 { const a = Vec3.new(10, -2, 0); const b = Vec3.new(-10, 5, 0); const maximum = Vec3.new(10, 5, 0); try expectEqual(Vec3.max(a, b), maximum); } // Vec4 { const a = Vec4.new(10, -2, 0, 1); const b = Vec4.new(-10, 5, 0, 1.01); const maximum = Vec4.new(10, 5, 0, 1.01); try expectEqual(Vec4.max(a, b), maximum); } } test "zalgebra.Vectors.fromSlice" { // Vec2 { const slice = [_]f32{ 2, 4 }; try expectEqual(Vec2.fromSlice(&slice), Vec2.new(2, 4)); } // Vec3 { const slice = [_]f32{ 2, 4, 3 }; try expectEqual(Vec3.fromSlice(&slice), Vec3.new(2, 4, 3)); } // Vec4 { const slice = [_]f32{ 2, 4, 3, 6 }; try expectEqual(Vec4.fromSlice(&slice), Vec4.new(2, 4, 3, 6)); } } test "zalgebra.Vectors.cast" { // Vec2 { const a = Vec2_i32.new(3, 6); const a_usize = Vec2_usize.new(3, 6); try expectEqual(a.cast(usize), a_usize); const b = Vec2.new(3.5, 6.5); const b_f64 = Vec2_f64.new(3.5, 6.5); try expectEqual(b.cast(f64), b_f64); const c = Vec2_i32.new(3, 6); const c_f32 = Vec2.new(3, 6); try expectEqual(c.cast(f32), c_f32); const d = Vec2.new(3, 6); const d_i32 = Vec2_i32.new(3, 6); try expectEqual(d.cast(i32), d_i32); } // Vec3 { const a = Vec3_i32.new(3, 6, 2); const a_usize = Vec3_usize.new(3, 6, 2); try expectEqual(a.cast(usize), a_usize); const b = Vec3.new(3.5, 6.5, 2); const b_f64 = Vec3_f64.new(3.5, 6.5, 2); try expectEqual(b.cast(f64), b_f64); const c = Vec3_i32.new(3, 6, 2); const c_f32 = Vec3.new(3, 6, 2); try expectEqual(c.cast(f32), c_f32); const d = Vec3.new(3, 6, 2); const d_i32 = Vec3_i32.new(3, 6, 2); try expectEqual(d.cast(i32), d_i32); } // Vec4 { const a = Vec4_i32.new(3, 6, 2, 0); const a_usize = Vec4_usize.new(3, 6, 2, 0); try expectEqual(a.cast(usize), a_usize); const b = Vec4.new(3.5, 6.5, 2, 0); const b_f64 = Vec4_f64.new(3.5, 6.5, 2, 0); try expectEqual(b.cast(f64), b_f64); const c = Vec4_i32.new(3, 6, 2, 0); const c_f32 = Vec4.new(3, 6, 2, 0); try expectEqual(c.cast(f32), c_f32); const d = Vec4.new(3, 6, 2, 0); const d_i32 = Vec4_i32.new(3, 6, 2, 0); try expectEqual(d.cast(i32), d_i32); } } test "zalgebra.Vectors.cross" { // Only for Vec3 const a = Vec3.new(1.5, 2.6, 3.7); const b = Vec3.new(2.5, 3.45, 1.0); const c = Vec3.new(1.5, 2.6, 3.7); const result_1 = Vec3.cross(a, c); const result_2 = Vec3.cross(a, b); try expectEqual(result_1, Vec3.zero()); try expectEqual(result_2, Vec3.new(-10.1650009, 7.75, -1.32499980)); }
https://raw.githubusercontent.com/contextfreeinfo/taca/9ad697eae9b372620121b2c77305b1b1890ea658/examples/zig/zalgebra/generic_vector.zig
const std = @import("std"); const api = @import("../api.zig"); // backends const sdl = @import("Backends/SDL.zig"); pub const GraphicsError = error{ InitFailure, OutOfBounds, }; pub const GfxError = error{ FileNotFound, AllocFailure, InvalidFile, }; const RenderType = enum { software, hardware, }; const Backend = enum { sdl, }; const Colour = struct { r: u8, g: u8, b: u8, }; inline fn rgb888ToRgb565(r: u8, g: u8, b: u8) u16 { var short: u16 = 0; // ew again var short1: u16 = r >> 3; short1 <<= 11; var short2: u16 = g >> 2; short2 <<= 5; const short3: u16 = b >> 3; short = short1 | short2 | short3; return short; } pub const DrawingCore = struct { backend: Backend, render_type: RenderType, sdl_backend: sdl.SDLBackend, framebuffer: []u16, const Self = @This(); pub fn init(engine: *api.engine.Engine) GraphicsError!Self { var core: DrawingCore = undefined; // TODO: don't hardcode sdl backend core.backend = .sdl; // or the render type lol core.render_type = .software; core.sdl_backend = sdl.SDLBackend.init(&core, engine, engine.allocator) catch |err| { std.log.err("failed to initialise sdl! {s}", .{@errorName(err)}); return GraphicsError.InitFailure; }; return core; } pub fn deinit(self: *Self) void { if (self.backend == .sdl) { self.sdl_backend.deinit(); } } pub fn render(self: *Self, engine: *api.engine.Engine) void { if (self.backend == .sdl) { self.sdl_backend.render(engine); } } pub fn processEvents(self: *Self, engine: *api.engine.Engine) void { if (self.backend == .sdl) { self.sdl_backend.processEvents(engine); } } pub fn checkFPSCap(self: *Self, engine: *api.engine.Engine) void { if (self.backend == .sdl) { self.sdl_backend.checkFPSCap(engine); } } pub fn checkUpdateCap(self: *Self, engine: *api.engine.Engine) void { if (self.backend == .sdl) { self.sdl_backend.checkUpdateCap(engine); } } pub inline fn getPixel(gfx: *Graphic, coords: api.util.Vector2) GraphicsError!u16 { if (coords.x < gfx.size.x and coords.x >= 0 and coords.y < gfx.size.y and coords.y >= 0) { return rgb888ToRgb565(gfx.data[@as(usize, @intCast((coords.y * gfx.size.x) + coords.x))].r, gfx.data[@as(usize, @intCast((coords.y * gfx.size.x) + coords.x))].g, gfx.data[@as(usize, @intCast((coords.y * gfx.size.x) + coords.x))].b); } else { return GraphicsError.OutOfBounds; } } pub fn clearScreen(self: *Self, colour: Colour, engine: *api.engine.Engine) void { for (0..@as(usize, @intCast(engine.game_options.res.x * engine.game_options.res.y))) |i| { self.framebuffer[i] = rgb888ToRgb565(colour.r, colour.g, colour.b); } } pub fn drawSprite(self: *Self, gfx: *Graphic, sprite_pos: api.util.Vector2, sprite_res: api.util.Vector2, sprite_coords: api.util.Vector2, engine: *api.engine.Engine) GraphicsError!void { var current_fb_pos = api.util.Vector2{ .x = sprite_pos.x, .y = sprite_pos.y }; for (@as(usize, @intCast(sprite_coords.y))..@as(usize, @intCast(sprite_coords.y + sprite_res.y))) |y| { for (@as(usize, @intCast(sprite_coords.x))..@as(usize, @intCast(sprite_coords.x + sprite_res.x))) |x| { const colour = try getPixel(gfx, .{ .x = @as(i32, @intCast(x)), .y = @as(i32, @intCast(y)) }); // 16 bit magenta (255 0 255) if (colour == 0xF81F) { current_fb_pos.x += 1; continue; } if (current_fb_pos.x < engine.game_options.res.x and current_fb_pos.x >= 0 and current_fb_pos.y < engine.game_options.res.y and current_fb_pos.y >= 0) { self.framebuffer[@as(usize, @intCast((current_fb_pos.y * engine.game_options.res.x) + current_fb_pos.x))] = colour; } current_fb_pos.x += 1; } current_fb_pos.y += 1; current_fb_pos.x = sprite_pos.x; } } }; pub const Graphic = struct { size: api.util.Vector2, data: []Colour, const Self = @This(); pub fn load(engine: *api.engine.Engine, file_name: []const u8, allocator: std.mem.Allocator) !Self { var graphic: Self = std.mem.zeroes(Self); var file = api.reader.File.load(&engine.reader, file_name, allocator) catch |err| { std.log.err("failed to load m7gfx file! {s}", .{@errorName(err)}); return GfxError.FileNotFound; }; const header: []u8 = try allocator.alloc(u8, 2); try file.readByteArr(header, 2); if (!std.mem.eql(u8, header, "MG")) { std.log.err("{s} is not a valid m7gfx file!", .{file_name}); return GfxError.InvalidFile; } allocator.free(header); graphic.size.x = try file.readInt(allocator); graphic.size.y = try file.readInt(allocator); graphic.data = allocator.alloc(Colour, @as(usize, @intCast(graphic.size.x * graphic.size.y))) catch { std.log.err("failed to allocate pixel data for {s}", .{file_name}); return GfxError.AllocFailure; }; var i: usize = 0; while (i < @as(usize, @intCast(graphic.size.x * graphic.size.y))) { var colour: Colour = std.mem.zeroes(Colour); colour.r = try file.readByte(); colour.g = try file.readByte(); colour.b = try file.readByte(); const rle_sign: u8 = try file.readByte(); if (rle_sign == 0xFF) { const repeat: usize = @as(usize, try file.readByte()); for (0..repeat) |_| { graphic.data[i] = colour; i += 1; } } else { graphic.data[i] = colour; i += 1; } } file.deinit(allocator); return graphic; } pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { allocator.free(self.data); } };
https://raw.githubusercontent.com/GeffDev/mode7/91844e40e483babe876bab61ee68f5620f6ea810/src/Graphics/Drawing.zig
pub const parseFloat = @import("parse_float/parse_float.zig").parseFloat; pub const ParseFloatError = @import("parse_float/parse_float.zig").ParseFloatError; const std = @import("std"); const math = std.math; const testing = std.testing; const expect = testing.expect; const expectEqual = testing.expectEqual; const expectError = testing.expectError; const approxEqAbs = std.math.approxEqAbs; const epsilon = 1e-7; // See https://github.com/tiehuis/parse-number-fxx-test-data for a wider-selection of test-data. test "fmt.parseFloat" { inline for ([_]type{ f16, f32, f64, f128 }) |T| { try testing.expectError(error.InvalidCharacter, parseFloat(T, "")); try testing.expectError(error.InvalidCharacter, parseFloat(T, " 1")); try testing.expectError(error.InvalidCharacter, parseFloat(T, "1abc")); try testing.expectError(error.InvalidCharacter, parseFloat(T, "+")); try testing.expectError(error.InvalidCharacter, parseFloat(T, "-")); try expectEqual(try parseFloat(T, "0"), 0.0); try expectEqual(try parseFloat(T, "0"), 0.0); try expectEqual(try parseFloat(T, "+0"), 0.0); try expectEqual(try parseFloat(T, "-0"), 0.0); try expectEqual(try parseFloat(T, "0e0"), 0); try expectEqual(try parseFloat(T, "2e3"), 2000.0); try expectEqual(try parseFloat(T, "1e0"), 1.0); try expectEqual(try parseFloat(T, "-2e3"), -2000.0); try expectEqual(try parseFloat(T, "-1e0"), -1.0); try expectEqual(try parseFloat(T, "1.234e3"), 1234); try expect(approxEqAbs(T, try parseFloat(T, "3.141"), 3.141, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "-3.141"), -3.141, epsilon)); try expectEqual(try parseFloat(T, "1e-5000"), 0); try expectEqual(try parseFloat(T, "1e+5000"), std.math.inf(T)); try expectEqual(try parseFloat(T, "0.4e0066999999999999999999999999999999999999999999999999999"), std.math.inf(T)); try expect(approxEqAbs(T, try parseFloat(T, "0_1_2_3_4_5_6.7_8_9_0_0_0e0_0_1_0"), @as(T, 123456.789000e10), epsilon)); // underscore rule is simple and reduces to "can only occur between two digits" and multiple are not supported. try expectError(error.InvalidCharacter, parseFloat(T, "0123456.789000e_0010")); // cannot occur immediately after exponent try expectError(error.InvalidCharacter, parseFloat(T, "_0123456.789000e0010")); // cannot occur before any digits try expectError(error.InvalidCharacter, parseFloat(T, "0__123456.789000e_0010")); // cannot occur twice in a row try expectError(error.InvalidCharacter, parseFloat(T, "0123456_.789000e0010")); // cannot occur before decimal point try expectError(error.InvalidCharacter, parseFloat(T, "0123456.789000e0010_")); // cannot occur at end of number try expect(approxEqAbs(T, try parseFloat(T, "1e-2"), 0.01, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "1234e-2"), 12.34, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "1."), 1, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "0."), 0, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, ".1"), 0.1, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, ".0"), 0, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, ".1e-1"), 0.01, epsilon)); try expectError(error.InvalidCharacter, parseFloat(T, ".")); // At least one digit is required. try expectError(error.InvalidCharacter, parseFloat(T, ".e1")); // At least one digit is required. try expectError(error.InvalidCharacter, parseFloat(T, "0.e")); // At least one digit is required. try expect(approxEqAbs(T, try parseFloat(T, "123142.1"), 123142.1, epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "-123142.1124"), @as(T, -123142.1124), epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "0.7062146892655368"), @as(T, 0.7062146892655368), epsilon)); try expect(approxEqAbs(T, try parseFloat(T, "2.71828182845904523536"), @as(T, 2.718281828459045), epsilon)); } } test "fmt.parseFloat nan and inf" { inline for ([_]type{ f16, f32, f64, f128 }) |T| { const Z = std.meta.Int(.unsigned, @typeInfo(T).Float.bits); try expectEqual(@as(Z, @bitCast(try parseFloat(T, "nAn"))), @as(Z, @bitCast(std.math.nan(T)))); try expectEqual(try parseFloat(T, "inF"), std.math.inf(T)); try expectEqual(try parseFloat(T, "-INF"), -std.math.inf(T)); } } test "fmt.parseFloat #11169" { try expectEqual(try parseFloat(f128, "9007199254740993.0"), 9007199254740993.0); } test "fmt.parseFloat hex.special" { if (@import("builtin").zig_backend == .stage2_x86_64) return error.SkipZigTest; try testing.expect(math.isNan(try parseFloat(f32, "nAn"))); try testing.expect(math.isPositiveInf(try parseFloat(f32, "iNf"))); try testing.expect(math.isPositiveInf(try parseFloat(f32, "+Inf"))); try testing.expect(math.isNegativeInf(try parseFloat(f32, "-iNf"))); } test "fmt.parseFloat hex.zero" { try testing.expectEqual(@as(f32, 0.0), try parseFloat(f32, "0x0")); try testing.expectEqual(@as(f32, 0.0), try parseFloat(f32, "-0x0")); try testing.expectEqual(@as(f32, 0.0), try parseFloat(f32, "0x0p42")); try testing.expectEqual(@as(f32, 0.0), try parseFloat(f32, "-0x0.00000p42")); try testing.expectEqual(@as(f32, 0.0), try parseFloat(f32, "0x0.00000p666")); } test "fmt.parseFloat hex.f16" { try testing.expectEqual(try parseFloat(f16, "0x1p0"), 1.0); try testing.expectEqual(try parseFloat(f16, "-0x1p-1"), -0.5); try testing.expectEqual(try parseFloat(f16, "0x10p+10"), 16384.0); try testing.expectEqual(try parseFloat(f16, "0x10p-10"), 0.015625); // Max normalized value. try testing.expectEqual(try parseFloat(f16, "0x1.ffcp+15"), math.floatMax(f16)); try testing.expectEqual(try parseFloat(f16, "-0x1.ffcp+15"), -math.floatMax(f16)); // Min normalized value. try testing.expectEqual(try parseFloat(f16, "0x1p-14"), math.floatMin(f16)); try testing.expectEqual(try parseFloat(f16, "-0x1p-14"), -math.floatMin(f16)); // Min denormal value. try testing.expectEqual(try parseFloat(f16, "0x1p-24"), math.floatTrueMin(f16)); try testing.expectEqual(try parseFloat(f16, "-0x1p-24"), -math.floatTrueMin(f16)); } test "fmt.parseFloat hex.f32" { try testing.expectError(error.InvalidCharacter, parseFloat(f32, "0x")); try testing.expectEqual(try parseFloat(f32, "0x1p0"), 1.0); try testing.expectEqual(try parseFloat(f32, "-0x1p-1"), -0.5); try testing.expectEqual(try parseFloat(f32, "0x10p+10"), 16384.0); try testing.expectEqual(try parseFloat(f32, "0x10p-10"), 0.015625); try testing.expectEqual(try parseFloat(f32, "0x0.ffffffp128"), 0x0.ffffffp128); try testing.expectEqual(try parseFloat(f32, "0x0.1234570p-125"), 0x0.1234570p-125); // Max normalized value. try testing.expectEqual(try parseFloat(f32, "0x1.fffffeP+127"), math.floatMax(f32)); try testing.expectEqual(try parseFloat(f32, "-0x1.fffffeP+127"), -math.floatMax(f32)); // Min normalized value. try testing.expectEqual(try parseFloat(f32, "0x1p-126"), math.floatMin(f32)); try testing.expectEqual(try parseFloat(f32, "-0x1p-126"), -math.floatMin(f32)); // Min denormal value. try testing.expectEqual(try parseFloat(f32, "0x1P-149"), math.floatTrueMin(f32)); try testing.expectEqual(try parseFloat(f32, "-0x1P-149"), -math.floatTrueMin(f32)); } test "fmt.parseFloat hex.f64" { try testing.expectEqual(try parseFloat(f64, "0x1p0"), 1.0); try testing.expectEqual(try parseFloat(f64, "-0x1p-1"), -0.5); try testing.expectEqual(try parseFloat(f64, "0x10p+10"), 16384.0); try testing.expectEqual(try parseFloat(f64, "0x10p-10"), 0.015625); // Max normalized value. try testing.expectEqual(try parseFloat(f64, "0x1.fffffffffffffp+1023"), math.floatMax(f64)); try testing.expectEqual(try parseFloat(f64, "-0x1.fffffffffffffp1023"), -math.floatMax(f64)); // Min normalized value. try testing.expectEqual(try parseFloat(f64, "0x1p-1022"), math.floatMin(f64)); try testing.expectEqual(try parseFloat(f64, "-0x1p-1022"), -math.floatMin(f64)); // Min denormalized value. try testing.expectEqual(try parseFloat(f64, "0x1p-1074"), math.floatTrueMin(f64)); try testing.expectEqual(try parseFloat(f64, "-0x1p-1074"), -math.floatTrueMin(f64)); } test "fmt.parseFloat hex.f128" { try testing.expectEqual(try parseFloat(f128, "0x1p0"), 1.0); try testing.expectEqual(try parseFloat(f128, "-0x1p-1"), -0.5); try testing.expectEqual(try parseFloat(f128, "0x10p+10"), 16384.0); try testing.expectEqual(try parseFloat(f128, "0x10p-10"), 0.015625); // Max normalized value. try testing.expectEqual(try parseFloat(f128, "0xf.fffffffffffffffffffffffffff8p+16380"), math.floatMax(f128)); try testing.expectEqual(try parseFloat(f128, "-0xf.fffffffffffffffffffffffffff8p+16380"), -math.floatMax(f128)); // Min normalized value. try testing.expectEqual(try parseFloat(f128, "0x1p-16382"), math.floatMin(f128)); try testing.expectEqual(try parseFloat(f128, "-0x1p-16382"), -math.floatMin(f128)); // // Min denormalized value. try testing.expectEqual(try parseFloat(f128, "0x1p-16494"), math.floatTrueMin(f128)); try testing.expectEqual(try parseFloat(f128, "-0x1p-16494"), -math.floatTrueMin(f128)); // ensure round-to-even try testing.expectEqual(try parseFloat(f128, "0x1.edcb34a235253948765432134674fp-1"), 0x1.edcb34a235253948765432134674fp-1); }
https://raw.githubusercontent.com/beingofexistence13/multiversal-lang/dd769e3fc6182c23ef43ed4479614f43f29738c9/zig/lib/std/fmt/parse_float.zig
const std = @import("std"); const serializer = @import("serializer.zig"); pub const JsonLexicon: serializer.Lexicon = .{ .convert = _jsonLexConv, .parse = _jsonLexParse }; fn _jsonLexConv(alloc: *std.mem.Allocator, tree: *serializer.Tree) []const u8 { var bytes = std.ArrayList(u8).init(alloc); _jsonLexInner(tree.root, &bytes); return bytes.toOwnedSlice(); } fn _jsonLexInner(node: *serializer.Node, holder: *std.ArrayList(u8)) void { switch (node.data) { .Map => { holder.append('{') catch unreachable; var count = node.data.Map.count(); var current: u32 = 0; var iter = node.data.Map.iterator(); while (iter.next()) |innerNode| { holder.append('\"') catch unreachable; holder.appendSlice(innerNode.key_ptr.*) catch unreachable; holder.appendSlice("\":") catch unreachable; _jsonLexInner(innerNode.value_ptr.*, holder); if (current + 1 < count) { holder.append(',') catch unreachable; } current += 1; } holder.append('}') catch unreachable; }, .Literal => { switch (node.data.Literal) { .String => { holder.append('\"') catch unreachable; holder.appendSlice(node.data.Literal.String) catch unreachable; holder.append('\"') catch unreachable; }, .Integer => { var cast = std.fmt.allocPrint(std.heap.page_allocator, "{any}", .{node.data.Literal.Integer}) catch unreachable; defer std.heap.page_allocator.free(cast); holder.appendSlice(cast) catch unreachable; }, .Float => { var cast = std.fmt.allocPrint(std.heap.page_allocator, "{d:.5}", .{node.data.Literal.Float}) catch unreachable; defer node.tree.alloc.free(cast); holder.appendSlice(cast) catch unreachable; }, .Bool => { if (node.data.Literal.Bool == true) { holder.appendSlice("true") catch unreachable; } else { holder.appendSlice("false") catch unreachable; } }, .Null => { holder.appendSlice("null") catch unreachable; }, } }, .Array => { holder.append('[') catch unreachable; for (node.data.Array.items) |innerNode, i| { _jsonLexInner(innerNode, holder); if (i + 1 < node.data.Array.items.len) { holder.append(',') catch unreachable; } } holder.append(']') catch unreachable; }, } } fn _jsonLexParse(allocator: *std.mem.Allocator, bytes: []const u8) *serializer.Tree { return _jsonLexParseInner(allocator, bytes) catch |err| { std.debug.panic("FAILED TO SERIALIZE JSON:\n{s}\nERROR:{s}", .{ bytes, @errorName(err) }); }; } fn _jsonLexParseInner(allocator: *std.mem.Allocator, bytes: []const u8) !*serializer.Tree { var tree: *serializer.Tree = serializer.Tree.initArena(allocator); var nodeStack = std.ArrayList(*serializer.Node).init(allocator); defer nodeStack.deinit(); var tag: ?[]const u8 = null; var i: usize = 0; while (i < bytes.len) { switch (bytes[i]) { '{' => { var node = tree.newObject(); if (nodeStack.items.len == 0) { tree.root = node; } else { var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, node); tag = null; } try nodeStack.append(node); i += 1; }, '}' => { _ = nodeStack.pop(); if (nodeStack.items.len == 0) { break; } i += 1; }, '[' => { var node = tree.newArray(); if (nodeStack.items.len == 0) { tree.root = node; } else { var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, node); tag = null; } try nodeStack.append(node); i += 1; }, ']' => { _ = nodeStack.pop(); if (nodeStack.items.len == 0) { break; } i += 1; }, '"' => { var start = i + 1; var end = i + 1; while (true) { if (bytes[end] == '"' and bytes[end - 1] != '\\') { break; } end += 1; } var slice = bytes[start..end]; if (bytes[end + 1] == ':') { tag = slice; i += (end - start) + 2; continue; } std.debug.assert(nodeStack.items.len > 0); var parent = nodeStack.items[nodeStack.items.len - 1]; var dupe: []const u8 = try tree.alloc.internal().dupeZ(u8, slice); var container = tree.newString(dupe); parent.push(tag, container); tag = null; i += (end - start) + 2; }, 't' => { if (bytes[i + 1] == 'r' and bytes[i + 2] == 'u' and bytes[i + 3] == 'e') { var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, true); tag = null; i += 4; } else { i += 1; } }, 'f' => { if (bytes[i + 1] == 'a' and bytes[i + 2] == 'l' and bytes[i + 3] == 's' and bytes[i + 4] == 'e') { var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, false); tag = null; i += 5; } else { i += 1; } }, 'n' => { if (bytes[i + 1] == 'u' and bytes[i + 2] == 'l' and bytes[i + 3] == 'l') { var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, null); tag = null; i += 4; } else { i += 1; } }, '-', 48...57 => { var start = i; var end = i + 1; var period: ?usize = null; while (true) { if (bytes[end] == 46) { period = end; end += 1; continue; } if (bytes[end] >= 48 and bytes[end] <= 57) { end += 1; continue; } else { break; } } if (period) |_| { var slice = bytes[start..end]; var parse = try std.fmt.parseFloat(f32, slice); var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, parse); tag = null; } else { var slice = bytes[start..end]; var parse = try std.fmt.parseInt(i32, slice, 0); var parent: *serializer.Node = nodeStack.items[nodeStack.items.len - 1]; parent.push(tag, parse); tag = null; } i += (end - start); }, else => { i += 1; continue; }, } } return tree; } test "json lex parse" { const sample = \\{"player":{"health":10.5,"mana":20,"lives":2,"names":["steven","paul"]}} ; var tree = JsonLexicon.parse(std.testing.allocator, sample); defer tree.deinit(); var playerNode: *serializer.Node = tree.root.data.Map.get("player").?; var health = playerNode.data.Map.get("health").?; var healthValue: f32 = 0; health.into(&healthValue, null); var names = playerNode.data.Map.get("names").?.data.Array.items; try std.testing.expect(names.len == 2); try std.testing.expect(std.mem.eql(u8, names[0].data.Literal.String, "steven")); try std.testing.expect(std.mem.eql(u8, names[1].data.Literal.String, "paul")); try std.testing.expectEqual(@as(f32, 10.5), healthValue); } test "complex structure deserialize" { const structure = struct { const tagField = std.ArrayList([]const u8); const npcField = struct { name: []const u8, strength: i32, children: ?std.ArrayList([]const u8) }; const townField = struct { name: []const u8, families: std.StringHashMap(familyField), }; const familyField = struct { count: usize, notable_history: []const u8, }; npc: []npcField, town: townField, tags: std.ArrayList(tagField), }; const data = @embedFile("json/test_npc.json"); var tree = JsonLexicon.parse(std.testing.allocator, std.mem.spanZ(data)); defer tree.deinit(); var value: structure = undefined; tree.root.into(&value, null); tree.print(JsonLexicon); }
https://raw.githubusercontent.com/JonSnowbd/slingworks/2c6b059431c6944511dc55717ef226cd3baaf800/src/serializer_json.zig
const std = @import("std"); pub usingnamespace std.log.scoped(.zigscanner);
https://raw.githubusercontent.com/Sirius902/zigscanner/77d2c9567c98e82025c1ed71cf3e104efd4cf56e/src/log.zig
const GPT = @This(); const lib = @import("lib"); const assert = lib.assert; const kb = lib.kb; const mb = lib.mb; const gb = lib.gb; const CRC32 = lib.CRC32; const Disk = lib.Disk; const Filesystem = lib.Filesystem; const FAT32 = Filesystem.FAT32; const log = lib.log.scoped(.GPT); const MBR = lib.PartitionTable.MBR; const GUID = lib.uefi.Guid; const Allocator = lib.Allocator; pub const default_max_partition_count = 128; pub const min_block_size = lib.default_sector_size; pub const max_block_size = 0x1000; pub const Header = extern struct { signature: [8]u8 = "EFI PART".*, revision: [4]u8 = .{ 0, 0, 1, 0 }, header_size: u32 = @sizeOf(Header), header_crc32: u32 = 0, reserved: u32 = 0, header_lba: u64, backup_lba: u64, first_usable_lba: u64, last_usable_lba: u64, disk_guid: GUID, partition_array_lba: u64, partition_entry_count: u32, partition_entry_size: u32 = @sizeOf(Partition), partition_array_crc32: u32, reserved1: [420]u8 = [1]u8{0} ** 420, pub fn updateCrc32(header: *Header) void { header.header_crc32 = 0; header.header_crc32 = CRC32.compute(lib.asBytes(header)[0..header.header_size]); } pub fn getPartititonCountInSector(header: *const Header, disk: *const Disk) u32 { return @divExact(disk.sector_size, header.partition_entry_size); } pub fn format(header: *const Header, comptime _: []const u8, _: lib.FormatOptions, writer: anytype) @TypeOf(writer).Error!void { try lib.format(writer, "GPT header:\n", .{}); try lib.format(writer, "\tSignature: {s}\n", .{header.signature}); try lib.format(writer, "\tRevision: {any}\n", .{header.revision}); try lib.format(writer, "\tHeader size: {}\n", .{header.header_size}); try lib.format(writer, "\tHeader CRC32: 0x{x}\n", .{header.header_crc32}); try lib.format(writer, "\tHeader LBA: 0x{x}\n", .{header.header_lba}); try lib.format(writer, "\tAlternate header LBA: 0x{x}\n", .{header.backup_lba}); try lib.format(writer, "\tFirst usable LBA: 0x{x}\n", .{header.first_usable_lba}); try lib.format(writer, "\tLast usable LBA: 0x{x}\n", .{header.last_usable_lba}); try lib.format(writer, "\tDisk GUID: {}\n", .{header.disk_guid}); try lib.format(writer, "\tPartition array LBA: 0x{x}\n", .{header.partition_array_lba}); try lib.format(writer, "\tPartition entry count: {}\n", .{header.partition_entry_count}); try lib.format(writer, "\tPartition entry size: {}\n", .{header.partition_entry_size}); try lib.format(writer, "\tPartition array CRC32: 0x{x}\n", .{header.partition_array_crc32}); } pub fn compare(header: *const Header, other: *align(1) const Header) void { log.debug("{}", .{header}); log.debug("{}", .{other}); if (!lib.equal(u8, &header.signature, &other.signature)) { log.debug("Signature mismatch: {s}, {s}", .{ header.signature, other.signature }); } if (!lib.equal(u8, &header.revision, &other.revision)) { log.debug("Revision mismatch: {any}, {any}", .{ header.revision, other.revision }); } if (header.header_size != other.header_size) { log.debug("Header size mismatch: {}, {}", .{ header.header_size, other.header_size }); } if (header.header_crc32 != other.header_crc32) { log.debug("Header CRC32 mismatch: {}, {}", .{ header.header_crc32, other.header_crc32 }); } if (header.header_lba != other.header_lba) { log.debug("Header LBA mismatch: {}, {}", .{ header.header_lba, other.header_lba }); } if (header.backup_lba != other.backup_lba) { log.debug("Backup LBA mismatch: {}, {}", .{ header.backup_lba, other.backup_lba }); } if (header.first_usable_lba != other.first_usable_lba) { log.debug("First usable LBA mismatch: {}, {}", .{ header.first_usable_lba, other.first_usable_lba }); } if (header.last_usable_lba != other.last_usable_lba) { log.debug("Last usable LBA mismatch: {}, {}", .{ header.last_usable_lba, other.last_usable_lba }); } if (!header.disk_guid.eql(other.disk_guid)) { log.debug("Disk GUID mismatch: {}, {}", .{ header.disk_guid, other.disk_guid }); } if (header.partition_array_lba != other.partition_array_lba) { log.debug("Partition array LBA mismatch: {}, {}", .{ header.partition_array_lba, other.partition_array_lba }); } if (header.partition_entry_count != other.partition_entry_count) { log.debug("Partition entry count mismatch: {}, {}", .{ header.partition_entry_count, other.partition_entry_count }); } if (header.partition_entry_size != other.partition_entry_size) { log.debug("Partition entry size mismatch: {}, {}", .{ header.partition_entry_size, other.partition_entry_size }); } if (header.partition_array_crc32 != other.partition_array_crc32) { log.debug("Partition array CRC32 mismatch: {}, {}", .{ header.partition_array_crc32, other.partition_array_crc32 }); } } pub const Cache = extern struct { mbr: *MBR.Partition, header: *GPT.Header, disk: *Disk, gpt: *GPT.Partition, pub fn getFreePartitionSlot(cache: Cache) !*GPT.Partition { assert(cache.header.partition_entry_size == @sizeOf(GPT.Partition)); // TODO: undo hack return cache.gpt; // for (cache.partition_entries[0..cache.header.partition_entry_count]) |*partition_entry| { // if (partition_entry.first_lba == 0 and partition_entry.last_lba == 0) { // return partition_entry; // } // } //@panic("todo: get_free_partition_slot"); } pub fn getPartitionIndex(cache: Cache, partition: *GPT.Partition, partition_entries: []GPT.Partition) u32 { assert(cache.header.partition_entry_size == @sizeOf(GPT.Partition)); return @divExact(@as(u32, @intCast(@intFromPtr(partition) - @intFromPtr(partition_entries.ptr))), cache.header.partition_entry_size); } pub fn getPartitionSector(cache: Cache, partition: *GPT.Partition, partition_entries: []GPT.Partition) u32 { return getPartitionIndex(cache, partition, partition_entries) / cache.header.getPartititonCountInSector(cache.disk); } pub fn getPartitionEntries(cache: Cache, allocator: ?*lib.Allocator) ![]GPT.Partition { const partition_entries = try cache.disk.readSlice(GPT.Partition, cache.header.partition_entry_count, cache.header.partition_array_lba, allocator, .{}); return partition_entries; } pub inline fn updatePartitionEntry(cache: Cache, partition: *GPT.Partition, new_value: GPT.Partition) !void { if (cache.disk.type != .memory) @panic("Disk is not memory"); assert(cache.header.partition_entry_size == @sizeOf(GPT.Partition)); const partition_entries = try cache.getPartitionEntries(null); const partition_entry_bytes = lib.sliceAsBytes(partition_entries); partition.* = new_value; cache.header.partition_array_crc32 = CRC32.compute(partition_entry_bytes); cache.header.updateCrc32(); const backup_gpt_header = try cache.disk.readTypedSectors(GPT.Header, cache.header.backup_lba, null, .{}); backup_gpt_header.partition_array_crc32 = cache.header.partition_array_crc32; backup_gpt_header.updateCrc32(); const partition_entry_sector_offset = cache.getPartitionSector(partition, partition_entries); const partition_entry_byte_offset = partition_entry_sector_offset * cache.disk.sector_size; // Only commit to disk the modified sector const partition_entry_modified_sector_bytes = partition_entry_bytes[partition_entry_byte_offset .. partition_entry_byte_offset + cache.disk.sector_size]; try cache.disk.writeSlice(u8, partition_entry_modified_sector_bytes, cache.header.partition_array_lba + partition_entry_sector_offset, false); // Force write because for memory disk we only hold a pointer to the main partition entry array try cache.disk.writeSlice(u8, partition_entry_modified_sector_bytes, backup_gpt_header.partition_array_lba + partition_entry_sector_offset, true); try cache.disk.writeTypedSectors(GPT.Header, cache.header, cache.header.header_lba, false); try cache.disk.writeTypedSectors(GPT.Header, backup_gpt_header, backup_gpt_header.header_lba, false); } pub fn addPartition(cache: Cache, comptime filesystem: lib.Filesystem.Type, partition_name: []const u16, lba_start: u64, lba_end: u64, gpt_partition: ?*const GPT.Partition) !GPT.Partition.Cache { // TODO: check if we are not overwriting a partition // TODO: check filesystem specific stuff const new_partition_entry = try cache.getFreePartitionSlot(); try updatePartitionEntry(cache, new_partition_entry, GPT.Partition{ .partition_type_guid = switch (filesystem) { .fat32 => efi_guid, else => @panic("unexpected filesystem"), }, .unique_partition_guid = if (gpt_partition) |gpt_part| gpt_part.unique_partition_guid else getRandomGuid(), .first_lba = lba_start, .last_lba = lba_end, .attributes = .{}, .partition_name = blk: { var name = [1]u16{0} ** 36; @memcpy(name[0..partition_name.len], partition_name); break :blk name; }, }); return .{ .gpt = cache, .partition = new_partition_entry, }; } pub fn load(disk: *Disk, allocator: ?*Allocator) !GPT.Header.Cache { _ = allocator; _ = disk; } }; comptime { assert(@sizeOf(Header) == lib.default_sector_size); } pub fn get(disk: *Disk) !*GPT.Header { return try disk.readTypedSectors(GPT.Header, 1); } pub fn getBackup(gpt_header: *GPT.Header, disk: *Disk) !*GPT.Header { return try disk.readTypedSectors(GPT.Header, gpt_header.backup_lba); } }; var prng = lib.random.DefaultPrng.init(0); pub fn getRandomGuid() GUID { const random_array = blk: { var arr: [16]u8 = undefined; const random = prng.random(); random.bytes(&arr); break :blk arr; }; var guid = GUID{ .time_low = (@as(u32, random_array[0]) << 24) | (@as(u32, random_array[1]) << 16) | (@as(u32, random_array[2]) << 8) | random_array[3], .time_mid = (@as(u16, random_array[4]) << 8) | random_array[5], .time_high_and_version = (@as(u16, random_array[6]) << 8) | random_array[7], .clock_seq_high_and_reserved = random_array[8], .clock_seq_low = random_array[9], .node = .{ random_array[10], random_array[11], random_array[12], random_array[13], random_array[14], random_array[15] }, }; guid.clock_seq_high_and_reserved = (2 << 6) | (guid.clock_seq_high_and_reserved >> 2); guid.time_high_and_version = (4 << 12) | (guid.time_high_and_version >> 4); return guid; } pub const efi_system_partition_guid = GUID{ .time_low = 0xC12A7328, .time_mid = 0xF81F, .time_hi_and_version = 0x11D2, .clock_seq_hi_and_reserved = 0xBA, .clock_seq_low = 0x4B, .node = [_]u8{ 0x00, 0xA0, 0xC9, 0x3E, 0xC9, 0x3B } }; pub const microsoft_basic_data_partition_guid = GUID{ .time_low = 0xEBD0A0A2, .time_mid = 0xB9E5, .time_hi_and_version = 0x4433, .clock_seq_hi_and_reserved = 0x87, .clock_seq_low = 0xC0, .node = [_]u8{ 0x68, 0xB6, 0xB7, 0x26, 0x99, 0xC7 } }; pub const Partition = extern struct { partition_type_guid: GUID, unique_partition_guid: GUID, first_lba: u64, last_lba: u64, attributes: Attributes, partition_name: [36]u16, pub const per_sector = @divExact(lib.default_sector_size, @sizeOf(Partition)); pub const Cache = extern struct { gpt: GPT.Header.Cache, partition: *GPT.Partition, pub fn fromPartitionIndex(disk: *Disk, partition_index: usize, allocator: ?*lib.Allocator) !GPT.Partition.Cache { const mbr_lba = MBR.default_lba; const mbr = try disk.readTypedSectors(MBR.Partition, mbr_lba, allocator, .{}); const primary_gpt_header_lba = mbr_lba + 1; const gpt_header = try disk.readTypedSectors(GPT.Header, primary_gpt_header_lba, allocator, .{}); if (gpt_header.partition_entry_count == 0) @panic("No GPT partition entries"); assert(gpt_header.partition_entry_size == @sizeOf(GPT.Partition)); // TODO: undo hack if (partition_index < gpt_header.partition_entry_count) { if (partition_index != 0) @panic("Unsupported partition index"); const partition_entries_first_sector = try disk.readSlice(GPT.Partition, GPT.Partition.per_sector, gpt_header.partition_array_lba, allocator, .{}); const partition_entry = &partition_entries_first_sector[0]; return .{ .gpt = .{ .mbr = mbr, .header = gpt_header, .disk = disk, .gpt = partition_entry, }, .partition = partition_entry, }; } @panic("todo: fromPartitionIndex"); } }; pub const Attributes = packed struct(u64) { required_partition: bool = false, no_block_io_protocol: bool = false, legacy_bios_bootable: bool = false, reserved: u45 = 0, guid_reserved: u16 = 0, }; pub fn compare(partition: *const Partition, other: *align(1) const Partition) void { log.debug("{}", .{partition}); if (partition.first_lba != other.first_lba) { log.debug("First LBA mismatch: 0x{x}, 0x{x}", .{ partition.first_lba, other.first_lba }); } if (partition.last_lba != other.last_lba) { log.debug("Last LBA mismatch: 0x{x}, 0x{x}", .{ partition.last_lba, other.last_lba }); } for (partition.partition_name, 0..) |partition_char, char_index| { const other_char = other.partition_name[char_index]; if (partition_char != other_char) { log.debug("Char is different: {u}(0x{x}), {u}(0x{x})", .{ partition_char, partition_char, other_char, other_char }); } } } pub fn format(partition: *const Partition, comptime _: []const u8, _: lib.FormatOptions, writer: anytype) @TypeOf(writer).Error!void { try lib.format(writer, "GPT partition:\n", .{}); try lib.format(writer, "\tPartition type GUID: {}\n", .{partition.partition_type_guid}); try lib.format(writer, "\tUnique partition GUID: {}\n", .{partition.unique_partition_guid}); try lib.format(writer, "\tFirst LBA: 0x{x}\n", .{partition.first_lba}); try lib.format(writer, "\tLast LBA: 0x{x}\n", .{partition.last_lba}); try lib.format(writer, "\tAttributes: {}\n", .{partition.attributes}); try lib.format(writer, "\tPartition name: {}\n", .{lib.std.unicode.fmtUtf16le(&partition.partition_name)}); } }; pub fn create(disk: *Disk, copy_gpt_header: ?*const Header) !GPT.Header.Cache { if (disk.type != .memory) @panic("gpt: creation is only supported for memory disks"); // 1. Create MBR fake partition const mbr_lba = MBR.default_lba; const mbr = try disk.readTypedSectors(MBR.Partition, mbr_lba, null, .{}); const first_lba = mbr_lba + 1; const primary_header_lba = first_lba; mbr.partitions[0] = MBR.LegacyPartition{ .boot_indicator = 0, .starting_chs = lib.default_sector_size, .os_type = 0xee, .ending_chs = 0xff_ff_ff, .first_lba = first_lba, .size_in_lba = @as(u32, @intCast(@divExact(disk.disk_size, disk.sector_size) - 1)), }; mbr.signature = .{ 0x55, 0xaa }; try disk.writeTypedSectors(MBR.Partition, mbr, mbr_lba, false); // 2. Write GPT header const partition_count = default_max_partition_count; const partition_array_sector_count = @divExact(@sizeOf(Partition) * partition_count, disk.sector_size); // TODO: properly compute header LBA const gpt_header = try disk.readTypedSectors(GPT.Header, first_lba, null, .{}); const secondary_header_lba = mbr.partitions[0].size_in_lba; const partition_array_lba_start = first_lba + 1; const partition_entries = try disk.readSlice(GPT.Partition, partition_count, partition_array_lba_start, null, .{}); gpt_header.* = GPT.Header{ .signature = "EFI PART".*, .revision = .{ 0, 0, 1, 0 }, .header_size = @offsetOf(GPT.Header, "reserved1"), .header_crc32 = 0, // TODO .header_lba = primary_header_lba, .backup_lba = secondary_header_lba, .first_usable_lba = partition_array_lba_start + partition_array_sector_count, .last_usable_lba = secondary_header_lba - primary_header_lba - partition_array_sector_count, .disk_guid = if (copy_gpt_header) |gpth| gpth.disk_guid else getRandomGuid(), .partition_array_lba = partition_array_lba_start, .partition_entry_count = partition_count, .partition_array_crc32 = CRC32.compute(lib.sliceAsBytes(partition_entries)), }; gpt_header.updateCrc32(); try disk.writeTypedSectors(GPT.Header, gpt_header, primary_header_lba, false); var backup_gpt_header = gpt_header.*; backup_gpt_header.partition_array_lba = secondary_header_lba - primary_header_lba - partition_array_sector_count + 1; backup_gpt_header.header_lba = gpt_header.backup_lba; backup_gpt_header.backup_lba = gpt_header.header_lba; backup_gpt_header.updateCrc32(); try disk.writeTypedSectors(GPT.Header, &backup_gpt_header, secondary_header_lba, true); return .{ .mbr = mbr, .header = gpt_header, .disk = disk, .gpt = &partition_entries[0], }; } const efi_guid = GUID{ .time_low = 0xC12A7328, .time_mid = 0xF81F, .time_high_and_version = 0x11D2, .clock_seq_high_and_reserved = 0xBA, .clock_seq_low = 0x4B, //00A0C93EC93B .node = .{ 0x00, 0xa0, 0xc9, 0x3e, 0xc9, 0x3b }, }; const limine_disk_guid = GUID{ .time_low = 0xD2CB8A76, .time_mid = 0xACB3, .time_high_and_version = 0x4D4D, .clock_seq_high_and_reserved = 0x93, .clock_seq_low = 0x55, .node = .{ 0xAC, 0xAE, 0xA4, 0x6B, 0x46, 0x92 }, }; const limine_unique_partition_guid = GUID{ .time_low = 0x26D6E02E, .time_mid = 0xEED8, .time_high_and_version = 0x4802, .clock_seq_high_and_reserved = 0xba, .clock_seq_low = 0xa2, .node = .{ 0xE5, 0xAA, 0x43, 0x7F, 0xC2, 0xC5 }, }; const FilesystemCacheTypes = blk: { var types: [Filesystem.Type.count]type = undefined; types[@intFromEnum(Filesystem.Type.birth)] = void; types[@intFromEnum(Filesystem.Type.ext2)] = void; types[@intFromEnum(Filesystem.Type.fat32)] = FAT32.Cache; break :blk types; }; test "gpt size" { comptime { assert(@sizeOf(Header) == 0x200); } }
https://raw.githubusercontent.com/birth-software/birth/23a3c67990b504c487bbcf21dc4f76e898fa23b8/src/lib/partition_table/gpt.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const List = std.ArrayList; const Map = std.AutoHashMap; const StrMap = std.StringHashMap; const BitSet = std.DynamicBitSet; const Str = []const u8; var gpa_impl = std.heap.GeneralPurposeAllocator(.{}){}; pub const gpa = gpa_impl.allocator(); // Add utility functions here // Useful stdlib functions const tokenize = std.mem.tokenize; const split = std.mem.split; const indexOf = std.mem.indexOfScalar; const indexOfAny = std.mem.indexOfAny; const indexOfStr = std.mem.indexOfPosLinear; const lastIndexOf = std.mem.lastIndexOfScalar; const lastIndexOfAny = std.mem.lastIndexOfAny; const lastIndexOfStr = std.mem.lastIndexOfLinear; const trim = std.mem.trim; const sliceMin = std.mem.min; const sliceMax = std.mem.max; const parseInt = std.fmt.parseInt; const parseFloat = std.fmt.parseFloat; const min = std.math.min; const min3 = std.math.min3; const max = std.math.max; const max3 = std.math.max3; const print = std.debug.print; const assert = std.debug.assert; const sort = std.sort.sort; const asc = std.sort.asc; const desc = std.sort.desc; const eql = std.mem.eql; pub fn includes(list: []Str, value: Str) bool { for (list) |item| { if (eql(u8, item, value)) return true; } return false; } pub fn mean2Floor(comptime T: type, a: T, b: T) usize { return @divFloor(a + b, 2); } pub fn mean2Ceil(comptime T: type, a: T, b: T) !usize { return try std.math.divCeil(T, a + b, 2); }
https://raw.githubusercontent.com/famuyiwadayo/advent-of-code-2020-zig/3a8d532b9a3b1e33df21062119df8a30ac388a44/src/util.zig
//! Randomly test data and lower it down const std = @import("std"); const trait = @import("trait.zig"); pub fn forAll(comptime T: type) Iterator(T) { return Iterator(T).init(); } fn threwError(func: anytype, item: anytype) bool { const originalStackDepth: usize = blk: { if (@errorReturnTrace()) |trace| { break :blk trace.index; } else { break :blk 0; } }; func(item) catch { if (@errorReturnTrace()) |trace| { // dirty manual tinkering to avoid Zig polluting the return trace trace.index = originalStackDepth; } return true; }; return false; } pub fn testFunction(comptime T: type, duration: i64, func: fn (T) anyerror!void) anyerror!void { var iterator = Iterator(T).init(); iterator.duration = duration; const Hypothesis = struct { elements: std.ArrayList(HypothesisElement), const Self = @This(); const HypothesisElement = union(enum) { // only for numbers BiggerThan: T, SmallerThan: T, pub fn format(value: HypothesisElement, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { switch (value) { .BiggerThan => |v| { try writer.print("bigger than {d}", .{v}); }, .SmallerThan => |v| { try writer.print("smaller than {d}", .{v}); }, } } }; /// Tries to find counter-examples (case where there is no error) in the /// given time and adjust the hypothesis based on that counter-example. pub fn refine(self: *Self, time: i64, callback: fn (T) anyerror!void) void { var prng = std.rand.DefaultPrng.init(@as(u64, @bitCast(std.time.milliTimestamp()))); const random = prng.random(); const timePerElement = @divFloor(time, @as(i64, @intCast(self.elements.items.len))); for (self.elements.items) |*element| { const start = std.time.milliTimestamp(); var stepSize: T = 1000; while (std.time.milliTimestamp() < start + timePerElement) { switch (element.*) { .BiggerThan => |value| { //const add = random.uintLessThanBiased(T, stepSize); if (threwError(callback, value) and threwError(callback, value -| 1)) { element.* = .{ .BiggerThan = value -| 1 }; } // if (threwError(callback, value -| add)) { // element.* = .{ .BiggerThan = value -| add }; // stepSize *|= 2; // if (threwError(callback, value +| add)) { // element.* = .{ .BiggerThan = value +| add }; // stepSize = std.math.max(1, stepSize / 3); // } // } else { // //stepSize /= 2; // } }, .SmallerThan => |value| { const add = random.uintLessThanBiased(T, stepSize); if (threwError(callback, value +| add)) { element.* = .{ .SmallerThan = value +| add }; //stepSize *|= 2; if (stepSize < 1) stepSize = 1; } else { stepSize /= 2; } }, } } } } pub fn format(value: Self, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { for (value.elements.items) |item| { try writer.print("{}, ", .{item}); } } pub fn deinit(self: Self) void { self.elements.deinit(); } }; // This stores a number of values and tries to found what's in common between thems const BreakCondition = struct { items: []T, const Self = @This(); pub fn init(items: []T) Self { return .{ .items = items }; } pub fn hypothetize(self: *Self, callback: fn (T) anyerror!void) !Hypothesis { var elements = std.ArrayList(Hypothesis.HypothesisElement).init(std.testing.allocator); if (comptime trait.isNumber(T)) { std.sort.sort(T, self.items, {}, comptime std.sort.asc(T)); const smallest = self.items[0]; const biggest = self.items[self.items.len - 1]; try elements.append(.{ .BiggerThan = biggest }); try elements.append(.{ .SmallerThan = smallest }); } var hypothesis = Hypothesis{ .elements = elements }; std.debug.print("\nCaught {d} errors. Base hypothesis: {}", .{ self.items.len, hypothesis }); std.debug.print("\nRefining hypothesis..", .{}); hypothesis.refine(3000, callback); return hypothesis; } }; //var errorsWith = std.ArrayList(T).init(std.testing.allocator); var errorsWith = std.AutoArrayHashMap(T, void).init(std.testing.allocator); defer errorsWith.deinit(); while (iterator.next()) |item| { if (!errorsWith.contains(item)) { if (threwError(func, item)) { try errorsWith.put(item, {}); } } } if (errorsWith.count() > 0) { var breakCond = BreakCondition.init(errorsWith.keys()); const hypothesis = try breakCond.hypothetize(func); defer hypothesis.deinit(); std.debug.print("\nThe function fails when using a value that is {}\n", .{hypothesis}); std.debug.print("---\nError return trace with {any}:\n", .{errorsWith.keys()[0]}); return try func(errorsWith.keys()[0]); } } pub fn Iterator(comptime T: type) type { return struct { count: usize = 0, rand: std.rand.DefaultPrng, start: i64, /// Duration in milliseconds duration: i64, pub const Self = @This(); const DETERMINISTIC_TEST = false; pub fn init() Self { return Self{ .rand = std.rand.DefaultPrng.init(if (DETERMINISTIC_TEST) 0 else @as(u64, @truncate(@as(u128, @bitCast(std.time.nanoTimestamp()))))), .start = std.time.milliTimestamp(), .duration = 100, }; } pub fn next(self: *Self) ?T { if (!comptime std.meta.hasUniqueRepresentation(T)) { @compileError(@typeName(T) ++ " doesn't have an unique representation"); } //if (self.count >= 10) return null; if (std.time.milliTimestamp() >= self.start + self.duration) { std.log.scoped(.iterator).debug("Did {d} rounds in {d} ms", .{ self.count, std.time.milliTimestamp() - self.start }); return null; } self.count += 1; var bytes: [@sizeOf(T)]u8 = undefined; self.rand.fill(&bytes); return std.mem.bytesToValue(T, &bytes); } }; } const ColorContainer = struct { color: @import("color.zig").Color, }; test "simple struct init" { var all = forAll(@import("color.zig").Color); while (all.next()) |color| { const container = ColorContainer{ .color = color }; try std.testing.expectEqual(color, container.color); } } test "basic bisecting" { if (true) return error.SkipZigTest; // As we're seeking values under 1000 among 4 billion randomly generated values, // we need to run this test for longer try testFunction(u16, 500, struct { pub fn callback(value: u16) !void { try std.testing.expect(value > 1000); try std.testing.expect(value < 5000); } }.callback); }
https://raw.githubusercontent.com/capy-ui/capy/0f714f8317f69e283a1cdf49f2f39bdfdd88ec95/src/fuzz.zig
//! NOTE: this file is autogenerated, DO NOT MODIFY //-------------------------------------------------------------------------------- // Section: Constants (64) //-------------------------------------------------------------------------------- pub const WM_DDE_FIRST = @as(u32, 992); pub const WM_DDE_TERMINATE = @as(u32, 993); pub const WM_DDE_ADVISE = @as(u32, 994); pub const WM_DDE_UNADVISE = @as(u32, 995); pub const WM_DDE_ACK = @as(u32, 996); pub const WM_DDE_DATA = @as(u32, 997); pub const WM_DDE_REQUEST = @as(u32, 998); pub const WM_DDE_POKE = @as(u32, 999); pub const WM_DDE_EXECUTE = @as(u32, 1000); pub const WM_DDE_LAST = @as(u32, 1000); pub const CADV_LATEACK = @as(u32, 65535); pub const DDE_FACK = @as(u32, 32768); pub const DDE_FBUSY = @as(u32, 16384); pub const DDE_FDEFERUPD = @as(u32, 16384); pub const DDE_FACKREQ = @as(u32, 32768); pub const DDE_FRELEASE = @as(u32, 8192); pub const DDE_FREQUESTED = @as(u32, 4096); pub const DDE_FAPPSTATUS = @as(u32, 255); pub const DDE_FNOTPROCESSED = @as(u32, 0); pub const MSGF_DDEMGR = @as(u32, 32769); pub const CP_WINANSI = @as(u32, 1004); pub const CP_WINUNICODE = @as(u32, 1200); pub const XTYPF_NOBLOCK = @as(u32, 2); pub const XTYPF_NODATA = @as(u32, 4); pub const XTYPF_ACKREQ = @as(u32, 8); pub const XCLASS_MASK = @as(u32, 64512); pub const XCLASS_BOOL = @as(u32, 4096); pub const XCLASS_DATA = @as(u32, 8192); pub const XCLASS_FLAGS = @as(u32, 16384); pub const XCLASS_NOTIFICATION = @as(u32, 32768); pub const XTYP_MASK = @as(u32, 240); pub const XTYP_SHIFT = @as(u32, 4); pub const TIMEOUT_ASYNC = @as(u32, 4294967295); pub const QID_SYNC = @as(u32, 4294967295); pub const APPCMD_MASK = @as(i32, 4080); pub const APPCLASS_MASK = @as(i32, 15); pub const HDATA_APPOWNED = @as(u32, 1); pub const DMLERR_NO_ERROR = @as(u32, 0); pub const DMLERR_FIRST = @as(u32, 16384); pub const DMLERR_ADVACKTIMEOUT = @as(u32, 16384); pub const DMLERR_BUSY = @as(u32, 16385); pub const DMLERR_DATAACKTIMEOUT = @as(u32, 16386); pub const DMLERR_DLL_NOT_INITIALIZED = @as(u32, 16387); pub const DMLERR_DLL_USAGE = @as(u32, 16388); pub const DMLERR_EXECACKTIMEOUT = @as(u32, 16389); pub const DMLERR_INVALIDPARAMETER = @as(u32, 16390); pub const DMLERR_LOW_MEMORY = @as(u32, 16391); pub const DMLERR_MEMORY_ERROR = @as(u32, 16392); pub const DMLERR_NOTPROCESSED = @as(u32, 16393); pub const DMLERR_NO_CONV_ESTABLISHED = @as(u32, 16394); pub const DMLERR_POKEACKTIMEOUT = @as(u32, 16395); pub const DMLERR_POSTMSG_FAILED = @as(u32, 16396); pub const DMLERR_REENTRANCY = @as(u32, 16397); pub const DMLERR_SERVER_DIED = @as(u32, 16398); pub const DMLERR_SYS_ERROR = @as(u32, 16399); pub const DMLERR_UNADVACKTIMEOUT = @as(u32, 16400); pub const DMLERR_UNFOUND_QUEUE_ID = @as(u32, 16401); pub const DMLERR_LAST = @as(u32, 16401); pub const MH_CREATE = @as(u32, 1); pub const MH_KEEP = @as(u32, 2); pub const MH_DELETE = @as(u32, 3); pub const MH_CLEANUP = @as(u32, 4); pub const MAX_MONITORS = @as(u32, 4); pub const MF_MASK = @as(u32, 4278190080); //-------------------------------------------------------------------------------- // Section: Types (30) //-------------------------------------------------------------------------------- pub const HSZ = ?*opaque{}; pub const HCONV = ?*opaque{}; pub const HCONVLIST = ?*opaque{}; pub const HDDEDATA = ?*opaque{}; pub const METAFILEPICT = extern struct { mm: i32, xExt: i32, yExt: i32, hMF: HMETAFILE, }; pub const DDE_ENABLE_CALLBACK_CMD = extern enum(u32) { ENABLEALL = 0, ENABLEONE = 128, DISABLE = 8, QUERYWAITING = 2, }; pub const EC_ENABLEALL = DDE_ENABLE_CALLBACK_CMD.ENABLEALL; pub const EC_ENABLEONE = DDE_ENABLE_CALLBACK_CMD.ENABLEONE; pub const EC_DISABLE = DDE_ENABLE_CALLBACK_CMD.DISABLE; pub const EC_QUERYWAITING = DDE_ENABLE_CALLBACK_CMD.QUERYWAITING; // TODO: This Enum is marked as [Flags], what do I do with this? pub const DDE_INITIALIZE_COMMAND = extern enum(u32) { APPCLASS_MONITOR = 1, APPCLASS_STANDARD = 0, APPCMD_CLIENTONLY = 16, APPCMD_FILTERINITS = 32, CBF_FAIL_ALLSVRXACTIONS = 258048, CBF_FAIL_ADVISES = 16384, CBF_FAIL_CONNECTIONS = 8192, CBF_FAIL_EXECUTES = 32768, CBF_FAIL_POKES = 65536, CBF_FAIL_REQUESTS = 131072, CBF_FAIL_SELFCONNECTIONS = 4096, CBF_SKIP_ALLNOTIFICATIONS = 3932160, CBF_SKIP_CONNECT_CONFIRMS = 262144, CBF_SKIP_DISCONNECTS = 2097152, CBF_SKIP_REGISTRATIONS = 524288, CBF_SKIP_UNREGISTRATIONS = 1048576, MF_CALLBACKS = 134217728, MF_CONV = 1073741824, MF_ERRORS = 268435456, MF_HSZ_INFO = 16777216, MF_LINKS = 536870912, MF_POSTMSGS = 67108864, MF_SENDMSGS = 33554432, _, }; pub const APPCLASS_MONITOR = DDE_INITIALIZE_COMMAND.APPCLASS_MONITOR; pub const APPCLASS_STANDARD = DDE_INITIALIZE_COMMAND.APPCLASS_STANDARD; pub const APPCMD_CLIENTONLY = DDE_INITIALIZE_COMMAND.APPCMD_CLIENTONLY; pub const APPCMD_FILTERINITS = DDE_INITIALIZE_COMMAND.APPCMD_FILTERINITS; pub const CBF_FAIL_ALLSVRXACTIONS = DDE_INITIALIZE_COMMAND.CBF_FAIL_ALLSVRXACTIONS; pub const CBF_FAIL_ADVISES = DDE_INITIALIZE_COMMAND.CBF_FAIL_ADVISES; pub const CBF_FAIL_CONNECTIONS = DDE_INITIALIZE_COMMAND.CBF_FAIL_CONNECTIONS; pub const CBF_FAIL_EXECUTES = DDE_INITIALIZE_COMMAND.CBF_FAIL_EXECUTES; pub const CBF_FAIL_POKES = DDE_INITIALIZE_COMMAND.CBF_FAIL_POKES; pub const CBF_FAIL_REQUESTS = DDE_INITIALIZE_COMMAND.CBF_FAIL_REQUESTS; pub const CBF_FAIL_SELFCONNECTIONS = DDE_INITIALIZE_COMMAND.CBF_FAIL_SELFCONNECTIONS; pub const CBF_SKIP_ALLNOTIFICATIONS = DDE_INITIALIZE_COMMAND.CBF_SKIP_ALLNOTIFICATIONS; pub const CBF_SKIP_CONNECT_CONFIRMS = DDE_INITIALIZE_COMMAND.CBF_SKIP_CONNECT_CONFIRMS; pub const CBF_SKIP_DISCONNECTS = DDE_INITIALIZE_COMMAND.CBF_SKIP_DISCONNECTS; pub const CBF_SKIP_REGISTRATIONS = DDE_INITIALIZE_COMMAND.CBF_SKIP_REGISTRATIONS; pub const CBF_SKIP_UNREGISTRATIONS = DDE_INITIALIZE_COMMAND.CBF_SKIP_UNREGISTRATIONS; pub const MF_CALLBACKS = DDE_INITIALIZE_COMMAND.MF_CALLBACKS; pub const MF_CONV = DDE_INITIALIZE_COMMAND.MF_CONV; pub const MF_ERRORS = DDE_INITIALIZE_COMMAND.MF_ERRORS; pub const MF_HSZ_INFO = DDE_INITIALIZE_COMMAND.MF_HSZ_INFO; pub const MF_LINKS = DDE_INITIALIZE_COMMAND.MF_LINKS; pub const MF_POSTMSGS = DDE_INITIALIZE_COMMAND.MF_POSTMSGS; pub const MF_SENDMSGS = DDE_INITIALIZE_COMMAND.MF_SENDMSGS; pub const DDE_NAME_SERVICE_CMD = extern enum(u32) { REGISTER = 1, UNREGISTER = 2, FILTERON = 4, FILTEROFF = 8, }; pub const DNS_REGISTER = DDE_NAME_SERVICE_CMD.REGISTER; pub const DNS_UNREGISTER = DDE_NAME_SERVICE_CMD.UNREGISTER; pub const DNS_FILTERON = DDE_NAME_SERVICE_CMD.FILTERON; pub const DNS_FILTEROFF = DDE_NAME_SERVICE_CMD.FILTEROFF; pub const DDE_CLIENT_TRANSACTION_TYPE = extern enum(u32) { ADVSTART = 4144, ADVSTOP = 32832, EXECUTE = 16464, POKE = 16528, REQUEST = 8368, ADVDATA = 16400, ADVREQ = 8226, CONNECT = 4194, CONNECT_CONFIRM = 32882, DISCONNECT = 32962, MONITOR = 33010, REGISTER = 32930, UNREGISTER = 32978, WILDCONNECT = 8418, XACT_COMPLETE = 32896, }; pub const XTYP_ADVSTART = DDE_CLIENT_TRANSACTION_TYPE.ADVSTART; pub const XTYP_ADVSTOP = DDE_CLIENT_TRANSACTION_TYPE.ADVSTOP; pub const XTYP_EXECUTE = DDE_CLIENT_TRANSACTION_TYPE.EXECUTE; pub const XTYP_POKE = DDE_CLIENT_TRANSACTION_TYPE.POKE; pub const XTYP_REQUEST = DDE_CLIENT_TRANSACTION_TYPE.REQUEST; pub const XTYP_ADVDATA = DDE_CLIENT_TRANSACTION_TYPE.ADVDATA; pub const XTYP_ADVREQ = DDE_CLIENT_TRANSACTION_TYPE.ADVREQ; pub const XTYP_CONNECT = DDE_CLIENT_TRANSACTION_TYPE.CONNECT; pub const XTYP_CONNECT_CONFIRM = DDE_CLIENT_TRANSACTION_TYPE.CONNECT_CONFIRM; pub const XTYP_DISCONNECT = DDE_CLIENT_TRANSACTION_TYPE.DISCONNECT; pub const XTYP_MONITOR = DDE_CLIENT_TRANSACTION_TYPE.MONITOR; pub const XTYP_REGISTER = DDE_CLIENT_TRANSACTION_TYPE.REGISTER; pub const XTYP_UNREGISTER = DDE_CLIENT_TRANSACTION_TYPE.UNREGISTER; pub const XTYP_WILDCONNECT = DDE_CLIENT_TRANSACTION_TYPE.WILDCONNECT; pub const XTYP_XACT_COMPLETE = DDE_CLIENT_TRANSACTION_TYPE.XACT_COMPLETE; pub const CONVINFO_CONVERSATION_STATE = extern enum(u32) { ADVACKRCVD = 13, ADVDATAACKRCVD = 16, ADVDATASENT = 15, ADVSENT = 11, CONNECTED = 2, DATARCVD = 6, EXECACKRCVD = 10, EXECSENT = 9, INCOMPLETE = 1, INIT1 = 3, INIT2 = 4, NULL = 0, POKEACKRCVD = 8, POKESENT = 7, REQSENT = 5, UNADVACKRCVD = 14, UNADVSENT = 12, }; pub const XST_ADVACKRCVD = CONVINFO_CONVERSATION_STATE.ADVACKRCVD; pub const XST_ADVDATAACKRCVD = CONVINFO_CONVERSATION_STATE.ADVDATAACKRCVD; pub const XST_ADVDATASENT = CONVINFO_CONVERSATION_STATE.ADVDATASENT; pub const XST_ADVSENT = CONVINFO_CONVERSATION_STATE.ADVSENT; pub const XST_CONNECTED = CONVINFO_CONVERSATION_STATE.CONNECTED; pub const XST_DATARCVD = CONVINFO_CONVERSATION_STATE.DATARCVD; pub const XST_EXECACKRCVD = CONVINFO_CONVERSATION_STATE.EXECACKRCVD; pub const XST_EXECSENT = CONVINFO_CONVERSATION_STATE.EXECSENT; pub const XST_INCOMPLETE = CONVINFO_CONVERSATION_STATE.INCOMPLETE; pub const XST_INIT1 = CONVINFO_CONVERSATION_STATE.INIT1; pub const XST_INIT2 = CONVINFO_CONVERSATION_STATE.INIT2; pub const XST_NULL = CONVINFO_CONVERSATION_STATE.NULL; pub const XST_POKEACKRCVD = CONVINFO_CONVERSATION_STATE.POKEACKRCVD; pub const XST_POKESENT = CONVINFO_CONVERSATION_STATE.POKESENT; pub const XST_REQSENT = CONVINFO_CONVERSATION_STATE.REQSENT; pub const XST_UNADVACKRCVD = CONVINFO_CONVERSATION_STATE.UNADVACKRCVD; pub const XST_UNADVSENT = CONVINFO_CONVERSATION_STATE.UNADVSENT; // TODO: This Enum is marked as [Flags], what do I do with this? pub const CONVINFO_STATUS = extern enum(u32) { ADVISE = 2, BLOCKED = 8, BLOCKNEXT = 128, CLIENT = 16, CONNECTED = 1, INLIST = 64, ISLOCAL = 4, ISSELF = 256, TERMINATED = 32, _, }; pub const ST_ADVISE = CONVINFO_STATUS.ADVISE; pub const ST_BLOCKED = CONVINFO_STATUS.BLOCKED; pub const ST_BLOCKNEXT = CONVINFO_STATUS.BLOCKNEXT; pub const ST_CLIENT = CONVINFO_STATUS.CLIENT; pub const ST_CONNECTED = CONVINFO_STATUS.CONNECTED; pub const ST_INLIST = CONVINFO_STATUS.INLIST; pub const ST_ISLOCAL = CONVINFO_STATUS.ISLOCAL; pub const ST_ISSELF = CONVINFO_STATUS.ISSELF; pub const ST_TERMINATED = CONVINFO_STATUS.TERMINATED; pub const DDEACK = extern struct { _bitfield: u16, }; pub const DDEADVISE = extern struct { _bitfield: u16, cfFormat: i16, }; pub const DDEDATA = extern struct { _bitfield: u16, cfFormat: i16, Value: [1]u8, }; pub const DDEPOKE = extern struct { _bitfield: u16, cfFormat: i16, Value: [1]u8, }; pub const DDELN = extern struct { _bitfield: u16, cfFormat: i16, }; pub const DDEUP = extern struct { _bitfield: u16, cfFormat: i16, rgb: [1]u8, }; pub const HSZPAIR = extern struct { hszSvc: HSZ, hszTopic: HSZ, }; pub const CONVCONTEXT = extern struct { cb: u32, wFlags: u32, wCountryID: u32, iCodePage: i32, dwLangID: u32, dwSecurity: u32, qos: SECURITY_QUALITY_OF_SERVICE, }; pub const CONVINFO = extern struct { cb: u32, hUser: usize, hConvPartner: HCONV, hszSvcPartner: HSZ, hszServiceReq: HSZ, hszTopic: HSZ, hszItem: HSZ, wFmt: u32, wType: DDE_CLIENT_TRANSACTION_TYPE, wStatus: CONVINFO_STATUS, wConvst: CONVINFO_CONVERSATION_STATE, wLastError: u32, hConvList: HCONVLIST, ConvCtxt: CONVCONTEXT, hwnd: HWND, hwndPartner: HWND, }; pub const PFNCALLBACK = fn( wType: u32, wFmt: u32, hConv: HCONV, hsz1: HSZ, hsz2: HSZ, hData: HDDEDATA, dwData1: usize, dwData2: usize, ) callconv(@import("std").os.windows.WINAPI) HDDEDATA; pub const DDEML_MSG_HOOK_DATA = extern struct { uiLo: usize, uiHi: usize, cbData: u32, Data: [8]u32, }; pub const MONMSGSTRUCT = extern struct { cb: u32, hwndTo: HWND, dwTime: u32, hTask: HANDLE, wMsg: u32, wParam: WPARAM, lParam: LPARAM, dmhd: DDEML_MSG_HOOK_DATA, }; pub const MONCBSTRUCT = extern struct { cb: u32, dwTime: u32, hTask: HANDLE, dwRet: u32, wType: u32, wFmt: u32, hConv: HCONV, hsz1: HSZ, hsz2: HSZ, hData: HDDEDATA, dwData1: usize, dwData2: usize, cc: CONVCONTEXT, cbData: u32, Data: [8]u32, }; pub const MONHSZSTRUCTA = extern struct { cb: u32, fsAction: BOOL, dwTime: u32, hsz: HSZ, hTask: HANDLE, str: [1]CHAR, }; pub const MONHSZSTRUCTW = extern struct { cb: u32, fsAction: BOOL, dwTime: u32, hsz: HSZ, hTask: HANDLE, str: [1]u16, }; pub const MONERRSTRUCT = extern struct { cb: u32, wLastError: u32, dwTime: u32, hTask: HANDLE, }; pub const MONLINKSTRUCT = extern struct { cb: u32, dwTime: u32, hTask: HANDLE, fEstablished: BOOL, fNoData: BOOL, hszSvc: HSZ, hszTopic: HSZ, hszItem: HSZ, wFmt: u32, fServer: BOOL, hConvServer: HCONV, hConvClient: HCONV, }; pub const MONCONVSTRUCT = extern struct { cb: u32, fConnect: BOOL, dwTime: u32, hTask: HANDLE, hszSvc: HSZ, hszTopic: HSZ, hConvClient: HCONV, hConvServer: HCONV, }; pub const COPYDATASTRUCT = extern struct { dwData: usize, cbData: u32, lpData: *c_void, }; //-------------------------------------------------------------------------------- // Section: Functions (76) //-------------------------------------------------------------------------------- // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeSetQualityOfService( hwndClient: HWND, pqosNew: *const SECURITY_QUALITY_OF_SERVICE, pqosPrev: *SECURITY_QUALITY_OF_SERVICE, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ImpersonateDdeClientWindow( hWndClient: HWND, hWndServer: HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn PackDDElParam( msg: u32, uiLo: usize, uiHi: usize, ) callconv(@import("std").os.windows.WINAPI) LPARAM; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn UnpackDDElParam( msg: u32, lParam: LPARAM, puiLo: *usize, puiHi: *usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn FreeDDElParam( msg: u32, lParam: LPARAM, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ReuseDDElParam( lParam: LPARAM, msgIn: u32, msgOut: u32, uiLo: usize, uiHi: usize, ) callconv(@import("std").os.windows.WINAPI) LPARAM; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeInitializeA( pidInst: *u32, pfnCallback: PFNCALLBACK, afCmd: DDE_INITIALIZE_COMMAND, ulRes: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeInitializeW( pidInst: *u32, pfnCallback: PFNCALLBACK, afCmd: DDE_INITIALIZE_COMMAND, ulRes: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeUninitialize( idInst: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeConnectList( idInst: u32, hszService: HSZ, hszTopic: HSZ, hConvList: HCONVLIST, pCC: ?*CONVCONTEXT, ) callconv(@import("std").os.windows.WINAPI) HCONVLIST; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeQueryNextServer( hConvList: HCONVLIST, hConvPrev: HCONV, ) callconv(@import("std").os.windows.WINAPI) HCONV; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeDisconnectList( hConvList: HCONVLIST, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeConnect( idInst: u32, hszService: HSZ, hszTopic: HSZ, pCC: ?*CONVCONTEXT, ) callconv(@import("std").os.windows.WINAPI) HCONV; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeDisconnect( hConv: HCONV, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeReconnect( hConv: HCONV, ) callconv(@import("std").os.windows.WINAPI) HCONV; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeQueryConvInfo( hConv: HCONV, idTransaction: u32, pConvInfo: *CONVINFO, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeSetUserHandle( hConv: HCONV, id: u32, hUser: usize, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeAbandonTransaction( idInst: u32, hConv: HCONV, idTransaction: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdePostAdvise( idInst: u32, hszTopic: HSZ, hszItem: HSZ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeEnableCallback( idInst: u32, hConv: HCONV, wCmd: DDE_ENABLE_CALLBACK_CMD, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeImpersonateClient( hConv: HCONV, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeNameService( idInst: u32, hsz1: HSZ, hsz2: HSZ, afCmd: DDE_NAME_SERVICE_CMD, ) callconv(@import("std").os.windows.WINAPI) HDDEDATA; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeClientTransaction( pData: ?*u8, cbData: u32, hConv: HCONV, hszItem: HSZ, wFmt: u32, wType: DDE_CLIENT_TRANSACTION_TYPE, dwTimeout: u32, pdwResult: ?*u32, ) callconv(@import("std").os.windows.WINAPI) HDDEDATA; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeCreateDataHandle( idInst: u32, // TODO: what to do with BytesParamIndex 2? pSrc: ?*u8, cb: u32, cbOff: u32, hszItem: HSZ, wFmt: u32, afCmd: u32, ) callconv(@import("std").os.windows.WINAPI) HDDEDATA; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeAddData( hData: HDDEDATA, // TODO: what to do with BytesParamIndex 2? pSrc: *u8, cb: u32, cbOff: u32, ) callconv(@import("std").os.windows.WINAPI) HDDEDATA; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeGetData( hData: HDDEDATA, // TODO: what to do with BytesParamIndex 2? pDst: ?*u8, cbMax: u32, cbOff: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeAccessData( hData: HDDEDATA, pcbDataSize: ?*u32, ) callconv(@import("std").os.windows.WINAPI) *u8; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeUnaccessData( hData: HDDEDATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeFreeDataHandle( hData: HDDEDATA, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeGetLastError( idInst: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeCreateStringHandleA( idInst: u32, psz: [*:0]const u8, iCodePage: i32, ) callconv(@import("std").os.windows.WINAPI) HSZ; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeCreateStringHandleW( idInst: u32, psz: [*:0]const u16, iCodePage: i32, ) callconv(@import("std").os.windows.WINAPI) HSZ; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeQueryStringA( idInst: u32, hsz: HSZ, psz: ?[*:0]u8, cchMax: u32, iCodePage: i32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeQueryStringW( idInst: u32, hsz: HSZ, psz: ?[*:0]u16, cchMax: u32, iCodePage: i32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeFreeStringHandle( idInst: u32, hsz: HSZ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeKeepStringHandle( idInst: u32, hsz: HSZ, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn DdeCmpStringHandles( hsz1: HSZ, hsz2: HSZ, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn OpenClipboard( hWndNewOwner: HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn CloseClipboard( ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetClipboardSequenceNumber( ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetClipboardOwner( ) callconv(@import("std").os.windows.WINAPI) HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetClipboardViewer( hWndNewViewer: HWND, ) callconv(@import("std").os.windows.WINAPI) HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetClipboardViewer( ) callconv(@import("std").os.windows.WINAPI) HWND; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn ChangeClipboardChain( hWndRemove: HWND, hWndNewNext: HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn SetClipboardData( uFormat: u32, hMem: HANDLE, ) callconv(@import("std").os.windows.WINAPI) HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetClipboardData( uFormat: u32, ) callconv(@import("std").os.windows.WINAPI) HANDLE; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn RegisterClipboardFormatA( lpszFormat: [*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn RegisterClipboardFormatW( lpszFormat: [*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn CountClipboardFormats( ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn EnumClipboardFormats( format: u32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetClipboardFormatNameA( format: u32, lpszFormatName: [*:0]u8, cchMaxCount: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetClipboardFormatNameW( format: u32, lpszFormatName: [*:0]u16, cchMaxCount: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn EmptyClipboard( ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn IsClipboardFormatAvailable( format: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetPriorityClipboardFormat( paFormatPriorityList: [*]u32, cFormats: i32, ) callconv(@import("std").os.windows.WINAPI) i32; // TODO: this type is limited to platform 'windows5.0' pub extern "USER32" fn GetOpenClipboardWindow( ) callconv(@import("std").os.windows.WINAPI) HWND; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn AddClipboardFormatListener( hwnd: HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn RemoveClipboardFormatListener( hwnd: HWND, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows6.0.6000' pub extern "USER32" fn GetUpdatedClipboardFormats( lpuiFormats: [*]u32, cFormats: u32, pcFormatsOut: *u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalDeleteAtom( nAtom: u16, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn InitAtomTable( nSize: u32, ) callconv(@import("std").os.windows.WINAPI) BOOL; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn DeleteAtom( nAtom: u16, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalAddAtomA( lpString: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalAddAtomW( lpString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u16; pub extern "KERNEL32" fn GlobalAddAtomExA( lpString: ?[*:0]const u8, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u16; pub extern "KERNEL32" fn GlobalAddAtomExW( lpString: ?[*:0]const u16, Flags: u32, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalFindAtomA( lpString: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalFindAtomW( lpString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalGetAtomNameA( nAtom: u16, lpBuffer: [*:0]u8, nSize: i32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GlobalGetAtomNameW( nAtom: u16, lpBuffer: [*:0]u16, nSize: i32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn AddAtomA( lpString: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn AddAtomW( lpString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn FindAtomA( lpString: ?[*:0]const u8, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn FindAtomW( lpString: ?[*:0]const u16, ) callconv(@import("std").os.windows.WINAPI) u16; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GetAtomNameA( nAtom: u16, lpBuffer: [*:0]u8, nSize: i32, ) callconv(@import("std").os.windows.WINAPI) u32; // TODO: this type is limited to platform 'windows5.0' pub extern "KERNEL32" fn GetAtomNameW( nAtom: u16, lpBuffer: [*:0]u16, nSize: i32, ) callconv(@import("std").os.windows.WINAPI) u32; //-------------------------------------------------------------------------------- // Section: Unicode Aliases (13) //-------------------------------------------------------------------------------- pub usingnamespace switch (@import("../zig.zig").unicode_mode) { .ansi => struct { pub const MONHSZSTRUCT = MONHSZSTRUCTA; pub const DdeInitialize = DdeInitializeA; pub const DdeCreateStringHandle = DdeCreateStringHandleA; pub const DdeQueryString = DdeQueryStringA; pub const RegisterClipboardFormat = RegisterClipboardFormatA; pub const GetClipboardFormatName = GetClipboardFormatNameA; pub const GlobalAddAtom = GlobalAddAtomA; pub const GlobalAddAtomEx = GlobalAddAtomExA; pub const GlobalFindAtom = GlobalFindAtomA; pub const GlobalGetAtomName = GlobalGetAtomNameA; pub const AddAtom = AddAtomA; pub const FindAtom = FindAtomA; pub const GetAtomName = GetAtomNameA; }, .wide => struct { pub const MONHSZSTRUCT = MONHSZSTRUCTW; pub const DdeInitialize = DdeInitializeW; pub const DdeCreateStringHandle = DdeCreateStringHandleW; pub const DdeQueryString = DdeQueryStringW; pub const RegisterClipboardFormat = RegisterClipboardFormatW; pub const GetClipboardFormatName = GetClipboardFormatNameW; pub const GlobalAddAtom = GlobalAddAtomW; pub const GlobalAddAtomEx = GlobalAddAtomExW; pub const GlobalFindAtom = GlobalFindAtomW; pub const GlobalGetAtomName = GlobalGetAtomNameW; pub const AddAtom = AddAtomW; pub const FindAtom = FindAtomW; pub const GetAtomName = GetAtomNameW; }, .unspecified => if (@import("builtin").is_test) struct { pub const MONHSZSTRUCT = *opaque{}; pub const DdeInitialize = *opaque{}; pub const DdeCreateStringHandle = *opaque{}; pub const DdeQueryString = *opaque{}; pub const RegisterClipboardFormat = *opaque{}; pub const GetClipboardFormatName = *opaque{}; pub const GlobalAddAtom = *opaque{}; pub const GlobalAddAtomEx = *opaque{}; pub const GlobalFindAtom = *opaque{}; pub const GlobalGetAtomName = *opaque{}; pub const AddAtom = *opaque{}; pub const FindAtom = *opaque{}; pub const GetAtomName = *opaque{}; } else struct { pub const MONHSZSTRUCT = @compileError("'MONHSZSTRUCT' requires that UNICODE be set to true or false in the root module"); pub const DdeInitialize = @compileError("'DdeInitialize' requires that UNICODE be set to true or false in the root module"); pub const DdeCreateStringHandle = @compileError("'DdeCreateStringHandle' requires that UNICODE be set to true or false in the root module"); pub const DdeQueryString = @compileError("'DdeQueryString' requires that UNICODE be set to true or false in the root module"); pub const RegisterClipboardFormat = @compileError("'RegisterClipboardFormat' requires that UNICODE be set to true or false in the root module"); pub const GetClipboardFormatName = @compileError("'GetClipboardFormatName' requires that UNICODE be set to true or false in the root module"); pub const GlobalAddAtom = @compileError("'GlobalAddAtom' requires that UNICODE be set to true or false in the root module"); pub const GlobalAddAtomEx = @compileError("'GlobalAddAtomEx' requires that UNICODE be set to true or false in the root module"); pub const GlobalFindAtom = @compileError("'GlobalFindAtom' requires that UNICODE be set to true or false in the root module"); pub const GlobalGetAtomName = @compileError("'GlobalGetAtomName' requires that UNICODE be set to true or false in the root module"); pub const AddAtom = @compileError("'AddAtom' requires that UNICODE be set to true or false in the root module"); pub const FindAtom = @compileError("'FindAtom' requires that UNICODE be set to true or false in the root module"); pub const GetAtomName = @compileError("'GetAtomName' requires that UNICODE be set to true or false in the root module"); }, }; //-------------------------------------------------------------------------------- // Section: Imports (10) //-------------------------------------------------------------------------------- const LPARAM = @import("windows_and_messaging.zig").LPARAM; const WPARAM = @import("windows_and_messaging.zig").WPARAM; const PWSTR = @import("system_services.zig").PWSTR; const CHAR = @import("system_services.zig").CHAR; const HMETAFILE = @import("gdi.zig").HMETAFILE; const SECURITY_QUALITY_OF_SERVICE = @import("security.zig").SECURITY_QUALITY_OF_SERVICE; const HANDLE = @import("system_services.zig").HANDLE; const PSTR = @import("system_services.zig").PSTR; const BOOL = @import("system_services.zig").BOOL; const HWND = @import("windows_and_messaging.zig").HWND; test { // The following '_ = <FuncPtrType>' lines are a workaround for https://github.com/ziglang/zig/issues/4476 if (@hasDecl(@This(), "PFNCALLBACK")) { _ = PFNCALLBACK; } @setEvalBranchQuota( @import("std").meta.declarations(@This()).len * 3 ); // reference all the pub declarations if (!@import("std").builtin.is_test) return; inline for (@import("std").meta.declarations(@This())) |decl| { if (decl.is_pub) { _ = decl; } } }
https://raw.githubusercontent.com/OAguinagalde/tinyrenderer/20e140ad9a9483d6976f91c074a2e8a96e2038fb/dep/zigwin32/src/win32/api/data_exchange.zig
//! Base integer ISA, proceeded by RV32 or RV64 depending on register width const instruction = @import("../instruction.zig"); const opcode = instruction.opcode; const funct3 = instruction.funct3; const funct12 = instruction.funct12; const FenceOperands = instruction.FenceOperands; const mmu = @import("../mmu.zig"); const inst_format = @import("../inst_format.zig"); const std = @import("std"); const Signedness = std.builtin.Signedness; const JumpError = instruction.JumpError; const hart_arch = instruction.hart_arch; const SimpleHart = @import("../hart_impls.zig").Simple; const expect = std.testing.expect; const expectError = std.testing.expectError; const expectEqual = std.testing.expectEqual; const Int = std.meta.Int; const load = @import("../load.zig"); const assemble = @import("../assemble.zig"); const register = @import("../register.zig"); const Data = @import("../data.zig").Data; comptime { const extension = @import("../extension.zig"); extension.verifyExtensionInstructions(@This()); std.testing.refAllDeclsRecursive(@This()); } /// ADD Immediate /// /// x[`rd`] = x[`rs1`] +% signExtend(`imm`) /// `ADDI rd, rs1, 0` is used to implement the `MV rd, rs1` psuedoinstruction /// `ADDI 0, 0, 0` is used to encode `NOP` pub const ADDI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.ADDI }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).signed; const imm = inst.getImmediate().signExtended(arch.XLEN).signed; const res = .{ .signed = src +% imm }; context.setXRegister(inst.rd, res); } test "ADDI" { inline for (.{ 32, 64 }, .{ "rv32i", "rv64i" }) |XLEN, arch| { var hart = SimpleHart(XLEN, mmu.BasicMmu(XLEN)){ .mmu = .{} }; const file_path = try assemble.raw(arch, \\ .global _start \\ \\ _start: \\ li a0, 0 \\ li a1, 0 \\ loop: \\ addi a0, a0, 1 \\ addi a1, a1, -1 \\ ebreak \\ j loop \\ ); const file = try std.fs.openFileAbsolute(&file_path, .{}); try load.raw(&hart, file.reader()); file.close(); try std.fs.deleteFileAbsolute(&file_path); for (1..100) |i| { while (true) { if (try hart.tick()) |trap| { switch (trap) { .ebreak => break, else => unreachable } } } try expect(i == hart.getXRegister(register.a0).signed); try expect(-@as(isize, @intCast(i)) == hart.getXRegister(register.a1).signed); } // todo overflow testing } } }; /// Set Less Than Immediate /// /// x[`rd`] = if (x[`rs1`] < signExtend(`imm`)) 1 else 0 pub const SLTI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.SLTI }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).signed; const imm = inst.getImmediate().signExtended(arch.XLEN).signed; const res = .{ .unsigned = if (src < imm) @as(arch.usize, 1) else @as(arch.usize, 0) }; context.setXRegister(inst.rd, res); } }; /// Set Less Than Immediate Unsigned /// /// x[`rd`] = if (x[`rs1`] (unsigned)< signExtend(`imm`)) 1 else 0 pub const SLTIU = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.SLTIU }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).unsigned; const imm = inst.getImmediate().signExtended(arch.XLEN).unsigned; const res = .{ .unsigned = if (src < imm) @as(arch.usize, 1) else @as(arch.usize, 0) }; context.setXRegister(inst.rd, res); } }; /// AND Immediate /// /// x[`rd`] = x[`rs1`] & signExtend(`imm`) pub const ANDI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.ANDI }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).signed; const imm = inst.getImmediate().signExtended(arch.XLEN).signed; const res = .{ .signed = src & imm }; context.setXRegister(inst.rd, res); } }; /// OR Immediate /// /// x[`rd`] = x[`rs1`] | signExtend(`imm`) pub const ORI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.ORI }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).signed; const imm = inst.getImmediate().signExtended(arch.XLEN).signed; const res = .{ .signed = src | imm }; context.setXRegister(inst.rd, res); } }; /// eXclusive OR Immediate /// /// x[`rd`] = x[`rs1`] ^ signExtend(`imm`) /// `XORI rd, rs1, -1` is equivelent to psuedoinstruction `NOT rd, rs1` pub const XORI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.XORI }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).signed; const imm = inst.getImmediate().signExtended(arch.XLEN).signed; const res = .{ .signed = src ^ imm }; context.setXRegister(inst.rd, res); } }; /// Shift Left Logical Immediate /// /// x[`rd`] = x[`rs1`] << `shamt` pub const SLLI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.SLLI, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.IS) void { const src = context.getXRegister(inst.rs1).unsigned; const res = .{ .unsigned = src << inst.shamt }; context.setXRegister(inst.rd, res); } }; /// Shift Right Logical Immediate /// /// x[`rd`] = x[`rs1`] (unsigned)>> `shamt` pub const SRLI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.SRLI, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.IS) void { const src = context.getXRegister(inst.rs1).unsigned; const res = .{ .unsigned = src >> inst.shamt }; context.setXRegister(inst.rd, res); } }; /// Shift Right Arithmetic Immediate /// /// x[`rd`] = x[`rs1`] (signed)>> `shamt` pub const SRAI = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP_IMM, funct3.SRAI, 0b000_0010 }; pub fn execute(context: anytype, inst: inst_format.IS) void { const src = context.getXRegister(inst.rs1).signed; const res = .{ .signed = src >> inst.shamt }; context.setXRegister(inst.rd, res); } }; /// Load Upper Immediate /// /// x[`rd`] = signExtend(`imm` << 12) pub const LUI = struct { pub const Ext = .{ 32 }; pub const Id = .{opcode.LUI}; pub fn execute(context: anytype, inst: inst_format.U) void { const imm = inst.getImmediate().unsigned; const res = .{ .unsigned = imm }; context.setXRegister(inst.rd, res); } }; /// Add Upper Immediate to `PC` /// /// x[`rd`] = `pc` + signExtend(`imm` << 12) pub const AUIPC = struct { pub const Ext = .{ 32 }; pub const Id = .{opcode.AUIPC}; pub fn execute(context: anytype, inst: inst_format.U) void { const imm = inst.getImmediate().unsigned; const pc = context.getPc(); const res = .{ .unsigned = pc +% imm }; context.setXRegister(inst.rd, res); } }; /// ADD /// /// x[`rd`] = x[`rs1`] +% x[`rs2`] pub const ADD = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.ADD, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const arch = hart_arch(@TypeOf(context)); const src1 = context.getXRegister(inst.rs1).signExtended(arch.XLEN).signed; const src2 = context.getXRegister(inst.rs2).signExtended(arch.XLEN).signed; const res = .{ .signed = src1 +% src2 }; context.setXRegister(inst.rd, res); } }; /// Set Less Than /// /// x[`rd`] = if (x[`rs1`] (signed)< x[`rs2`]) 1 else 0 pub const SLT = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.SLT, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const arch = hart_arch(@TypeOf(context)); const src1 = context.getXRegister(inst.rs1).signed; const src2 = context.getXRegister(inst.rs2).signed; const res = .{ .unsigned = if (src1 < src2) @as(arch.usize, 1) else @as(arch.usize, 0) }; context.setXRegister(inst.rd, res); } }; /// Set Less Than Unsigned /// /// x[`rd`] = if (x[`rs1`] (unsigned)< x[`rs2`]) 1 else 0 /// `SLTU rd, x0, rs1` is equivalent to psuedoinstruction `SNEZ rd, rs` pub const SLTU = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.SLTU, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const arch = hart_arch(@TypeOf(context)); const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).unsigned; const res = .{ .unsigned = if (src1 < src2) @as(arch.usize, 1) else @as(arch.usize, 0) }; context.setXRegister(inst.rd, res); } }; /// AND /// /// x[`rd`] = x[`rs1`] & x[`rs2`] pub const AND = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.AND, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).unsigned; const res = .{ .unsigned = src1 & src2 }; context.setXRegister(inst.rd, res); } }; /// OR /// /// x[`rd`] = x[`rs1`] | x[`rs2`] pub const OR = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.OR, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).unsigned; const res = .{ .unsigned = src1 | src2 }; context.setXRegister(inst.rd, res); } }; /// eXclusive OR /// /// x[`rd`] = x[`rs1`] ^ x[`rs2`] pub const XOR = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.XOR, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).unsigned; const res = .{ .unsigned = src1 ^ src2 }; context.setXRegister(inst.rd, res); } }; /// Shift Left Logical /// /// x[`rd`] = x[`rs1`] << (x[`rs2`] & 0b1_1111) pub const SLL = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.SLL, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).truncated(5).unsigned; const res = .{ .unsigned = src1 << src2 }; context.setXRegister(inst.rd, res); } }; /// Shift Right Logical /// /// x[`rd`] = x[`rs1`] (unsigned)>> (x[`rs2`] & 0b1_1111) pub const SRL = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.SRL, 0b000_0000 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).truncated(5).unsigned; const res = .{ .unsigned = src1 >> src2 }; context.setXRegister(inst.rd, res); } }; /// SUBtract /// /// x[`rd`] = x[`rs1`] -% x[`rs2`] pub const SUB = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.SUB, 0b000_0010 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).unsigned; const src2 = context.getXRegister(inst.rs2).unsigned; const res = .{ .unsigned = src1 -% src2 }; context.setXRegister(inst.rd, res); } }; /// Shift Right Arithmetic /// /// x[`rd`] = x[`rs1`] (signed)>> (x[`rs2`] & 0b1_1111) pub const SRA = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.OP, funct3.SRA, 0b000_0010 }; pub fn execute(context: anytype, inst: inst_format.R) void { const src1 = context.getXRegister(inst.rs1).signed; const src2 = context.getXRegister(inst.rs2).truncated(5).unsigned; const res = .{ .signed = src1 >> src2 }; context.setXRegister(inst.rd, res); } }; /// Jump And Link /// /// x[`rd`] = `pc` +% 4; `pc` +%= signExtend(`imm`) /// `JAL x0, [whatever] is equivalent to psuedoinstruction `J [whatever]` (plain unconditional jump) /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address however, this is not possible when C-extension is enabled. pub const JAL = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.JAL }; pub fn execute(context: anytype, inst: inst_format.J) JumpError!void { const arch = hart_arch(@TypeOf(context)); const imm = inst.getImmediate().signExtended(arch.XLEN).unsigned; const pc = context.getPc(); const pc_set = pc +% imm; if (arch.IALIGN != 16 and pc_set % 4 != 0) { return error.InstructionAddressMisaligned; } else { context.setXRegister(inst.rd, .{ .unsigned = pc +% 4 }); context.setPc(pc_set); } } }; /// Jump And Link Register /// /// x[`rd`] = `pc` +% 4; `pc` = (x[`rs1`] +% signExtend(`imm`)) & signExtend(0b10) /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address however, this is not possible when C-extension is enabled. pub const JALR = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.JALR, 0 }; pub fn execute(context: anytype, inst: inst_format.I) JumpError!void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).signed; const imm = inst.getImmediate().signExtended(arch.XLEN).signed; const pc = context.getPc(); const pc_set: arch.usize = @bitCast((src +% imm) & 0b10); if (@TypeOf(context).IALIGN != 16 and pc_set % 4 != 0) { return error.InstructionAddressMisaligned; } else { context.setXRegister(inst.rd, .{ .unsigned = pc +% 4 }); context.setPc(pc_set); } } }; inline fn branch_execute(context: anytype, inst: inst_format.B, comptime signedness: Signedness, comptime compare: std.math.CompareOperator) JumpError!void { const arch = hart_arch(@TypeOf(context)); const src1 = switch(signedness) { .signed => context.getXRegister(inst.rs1).signed, .unsigned => context.getXRegister(inst.rs1).unsigned }; const src2 = switch(signedness) { .signed => context.getXRegister(inst.rs2).signed, .unsigned => context.getXRegister(inst.rs2).unsigned }; const condition = switch (compare) { .lt => src1 < src2, .lte => src1 <= src2, .eq => src1 == src2, .gte => src1 >= src2, .gt => src1 > src2, .neq => src1 != src2 }; if (condition) { const pc = context.getPc(); const imm = inst.getImmediate().signExtended(arch.XLEN).unsigned; const pc_set = pc +% imm; if (arch.IALIGN != 16 and pc_set % 4 != 0) { return error.InstructionAddressMisaligned; } else { context.setPc(pc_set); } } } /// Branch if EQual /// /// if (x[`rs1`] == x[`rs2`]) `pc` +%= signExtend(`imm`) /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address, however, this is not possible when C-extension is enabled. pub const BEQ = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.BRANCH, funct3.BEQ }; pub fn execute(context: anytype, inst: inst_format.B) JumpError!void { return branch_execute(context, inst, .signed, .eq); } }; /// Branch if Not eQual /// /// if (x[`rs1`] != x[`rs2`]) `pc` +%= signExtend(`imm`) /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address, however, this is not possible when C-extension is enabled. pub const BNQ = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.BRANCH, funct3.BNE }; pub fn execute(context: anytype, inst: inst_format.B) JumpError!void { return branch_execute(context, inst, .signed, .neq); } }; /// Branch if Less Than /// /// if (x[`rs1`] (signed)< x[`rs2`]) `pc` +%= signExtend(`imm`) /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address, however, this is not possible when C-extension is enabled. /// psuedoinstruction `BGT` can be implemented by flipping `rs1` and `rs2` pub const BLT = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.BRANCH, funct3.BLT }; pub fn execute(context: anytype, inst: inst_format.B) JumpError!void { return branch_execute(context, inst, .signed, .lt); } }; /// Branch if Less Than Unsigned /// /// if (x[`rs1`] (unsigned)< x[`rs2`]) `pc` +%= `imm` /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address, however, this is not possible when C-extension is enabled. /// psuedoinstruction `BGTU` can be implemented by flipping `rs1` and `rs2` pub const BLTU = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.BRANCH, funct3.BLTU }; pub fn execute(context: anytype, inst: inst_format.B) JumpError!void { return branch_execute(context, inst, .unsigned, .lt); } }; /// Branch if Greater or Equal /// /// if (x[`rs1`] (signed)>= x[`rs2`]) `pc` +%= `imm` /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address, however, this is not possible when C-extension is enabled. /// psuedoinstruction `BLE` can be implemented by flipping `rs1` and `rs2` pub const BGE = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.BRANCH, funct3.BGE }; pub fn execute(context: anytype, inst: inst_format.B) JumpError!void { return branch_execute(context, inst, .signed, .gte); } }; /// Branch if Greater or Equal Unsigned /// /// if (x[`rs1`] (unsigned)>= x[`rs2`]) `pc` +%= `imm` /// Can raise the `InstructionAddressMisaligned` exception if execution attempts /// to set PC to an invalid address, however, this is not possible when C-extension is enabled. /// psuedoinstruction `BLEU` can be implemented by flipping `rs1` and `rs2` pub const BGEU = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.BRANCH, funct3.BGEU }; pub fn execute(context: anytype, inst: inst_format.B) JumpError!void { return branch_execute(context, inst, .unsigned, .gte); } }; inline fn load_execute(context: anytype, inst: inst_format.I, comptime width: mmu.MemoryValueWidth, comptime signedness: Signedness) mmu.LoadError!void { const arch = hart_arch(@TypeOf(context)); const base = context.getXRegister(inst.rs1).unsigned; const imm = inst.getImmediate().signExtended(arch.XLEN).unsigned; const addr = base +% imm; const data = try context.load(width, addr); const res = switch (signedness) { .signed => data.signExtended(arch.XLEN), .unsigned => data.zeroExtended(arch.XLEN) }; context.setXRegister(inst.rd, res); } /// Load Byte (8 bits) /// /// x[`rd`] = signExtend(mem.load(8, x[`rs1`] +% signExtend(`imm`))) pub const LB = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.LOAD, funct3.LB }; pub fn execute(context: anytype, inst: inst_format.I) mmu.LoadError!void { return load_execute(context, inst, .byte, .signed); } }; /// Load Halfword (16 bits) /// /// x[`rd`] = signExtend(mem.load(16, x[`rs1`] +% signExtend(`imm`))) pub const LH = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.LOAD, funct3.LH }; pub fn execute(context: anytype, inst: inst_format.I) mmu.LoadError!void { return load_execute(context, inst, .halfword, .signed); } }; /// Load Word (32 bits) /// /// x[`rd`] = signExtend(mem.load(32, x[`rs1`] +% signExtend(`imm`))) pub const LW = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.LOAD, funct3.LW }; pub fn execute(context: anytype, inst: inst_format.I) mmu.LoadError!void { return load_execute(context, inst, .word, .signed); } }; /// Load Byte Unsigned (8 bits) /// /// x[`rd`] = mem.load(8, x[`rs1`] +% signExtend(`imm`)) pub const LBU = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.LOAD, funct3.LBU }; pub fn execute(context: anytype, inst: inst_format.I) mmu.LoadError!void { return load_execute(context, inst, .byte, .unsigned); } }; /// Load Halfword Unsigned (16 bits) /// /// x[`rd`] = mem.load(16, x[`rs1`] +% signExtend(`imm`)) pub const LHU = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.LOAD, funct3.LHU }; pub fn execute(context: anytype, inst: inst_format.I) mmu.LoadError!void { return load_execute(context, inst, .halfword, .unsigned); } }; inline fn store_execute(context: anytype, inst: inst_format.S, comptime width: mmu.MemoryValueWidth) mmu.StoreError!void { const arch = hart_arch(@TypeOf(context)); const base = context.getXRegister(inst.rs1).unsigned; const imm = inst.getImmediate().signExtended(arch.XLEN).unsigned; const addr = base +% imm; const src = context.getXRegister(inst.rs2).truncated(width.bits()); try context.store(width, addr, src); } /// Store Byte (8 bits) /// /// mem[x[`rs1`] +% signExtend(`imm`)] = truncate(8, x[`rs2`]) pub const SB = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.STORE, funct3.SB }; pub fn execute(context: anytype, inst: inst_format.S) mmu.StoreError!void { return store_execute(context, inst, .byte); } }; /// Store Halfword (16 bits) /// /// mem[x[`rs1`] +% signExtend(`imm`)] = truncate(16, x[`rs2`]) pub const SH = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.STORE, funct3.SH }; pub fn execute(context: anytype, inst: inst_format.S) mmu.StoreError!void { return store_execute(context, inst, .halfword); } }; /// Store Word (32 bits) /// /// mem[x[`rs1`] +% signExtend(`imm`)] = truncate(32, x[`rs2`]) pub const SW = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.STORE, funct3.SW }; pub fn execute(context: anytype, inst: inst_format.S) mmu.StoreError!void { return store_execute(context, inst, .word); } }; /// Fence pub const FENCE = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.MISC_MEM, funct3.FENCE }; pub fn execute(context: anytype, inst: inst_format.FENCE) void { const succ: FenceOperands = .{ .writes = inst.sw, .reads = inst.sr, .outputs = inst.so, .inputs = inst.si }; const pred: FenceOperands = .{ .writes = inst.pw, .reads = inst.pr, .outputs = inst.po, .inputs = inst.pi }; context.fence(inst.fm, pred, succ); } }; /// Environment Call pub const ECALL = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.SYSTEM, funct3.PRIV, funct12.ECALL }; pub fn execute(context: anytype, inst: inst_format.ENV) void { // nothing we need in the contents of the instruction, but the argument is // needed for pattern matching the instruction _ = inst; context.ecall(); } }; /// Environment Break pub const EBREAK = struct { pub const Ext = .{ 32 }; pub const Id = .{ opcode.SYSTEM, funct3.PRIV, funct12.EBREAK }; pub fn execute(context: anytype, inst: inst_format.ENV) void { // nothing we need in the contents of the instruction, but the argument is // needed for pattern matching the instruction _ = inst; context.ebreak(); } }; // RV64 ---------------------------------------------------------------------------------------------------------------- /// ADD Immediate Word (32 bits) /// /// x[`rd`] = signExtend(truncate(32, x[`rs1`]) +% signExtend(`imm`)) /// `ADDIW rd, rs1, 0` is used to implement the `SEXT.W pseudoinstruction` pub const ADDIW = struct { pub const Ext = .{ 64 }; pub const Id = .{ opcode.OP_IMM_32, funct3.ADDIW }; pub fn execute(context: anytype, inst: inst_format.I) void { const arch = hart_arch(@TypeOf(context)); const src = context.getXRegister(inst.rs1).truncated(32).signed; const imm = inst.getImmediate().signExtended(32).signed; const res = (Data(32) { .signed = src +% imm }).signExtended(arch.XLEN); context.setXRegister(inst.rd, res); } };
https://raw.githubusercontent.com/LindonKelley/riscv-emu/6dd1a4937aafb5cf350f8b961f4000e77ef04c92/src/extension/I.zig
// // One of the more common uses of 'comptime' function parameters is // passing a type to a function: // // fn foo(comptime MyType: type) void { ... } // // In fact, types are ONLY available at compile time, so the // 'comptime' keyword is required here. // // Please take a moment to put on the wizard hat which has been // provided for you. We're about to use this ability to implement // a generic function. // const print = @import("std").debug.print; pub fn main() void { // Here we declare arrays of three different types and sizes // at compile time from a function call. Neat! const s1 = makeSequence(u8, 3); // creates a [3]u8 const s2 = makeSequence(u32, 5); // creates a [5]u32 const s3 = makeSequence(i64, 7); // creates a [7]i64 print("s1={any}, s2={any}, s3={any}\n", .{ s1, s2, s3 }); } // This function is pretty wild because it executes at runtime // and is part of the final compiled program. The function is // compiled with unchanging data sizes and types. // // And yet it ALSO allows for different sizes and types. This // seems paradoxical. How could both things be true? // // To accomplish this, the Zig compiler actually generates a // separate copy of the function for every size/type combination! // So in this case, three different functions will be generated // for you, each with machine code that handles that specific // data size and type. // // Please fix this function so that the 'size' parameter: // // 1) Is guaranteed to be known at compile time. // 2) Sets the size of the array of type T (which is the // sequence we're creating and returning). // fn makeSequence(comptime T: type, ??? size: usize) [???]T { var sequence: [???]T = undefined; var i: usize = 0; while (i < size) : (i += 1) { sequence[i] = @intCast(T, i) + 1; } return sequence; }
https://raw.githubusercontent.com/booklearner/ziglings/a723a4c1df3276b31733e13b16a33e859c831188/exercises/069_comptime4.zig
// // You can also make pointers to multiple items without using a slice. // // var foo: [4]u8 = [4]u8{ 1, 2, 3, 4 }; // var foo_slice: []u8 = foo[0..]; // var foo_ptr: [*]u8 = &foo; // // The difference between foo_slice and foo_ptr is that the slice has // a known length. The pointer doesn't. It is up to YOU to keep track // of the number of u8s foo_ptr points to! // const std = @import("std"); pub fn main() void { // Take a good look at the array type to which we're coercing // the zen12 string (the REAL nature of strings will be // revealed when we've learned some additional features): const zen12: *const [21]u8 = "Memory is a resource."; // // It would also have been valid to coerce to a slice: // const zen12: []const u8 = "..."; // // Now let's turn this into a "many-item pointer": const zen_manyptr: [*]const u8 = zen12; // It's okay to access zen_manyptr just like an array or slice as // long as you keep track of the length yourself! // // A "string" in Zig is a pointer to an array of const u8 values // (or a slice of const u8 values, as we saw above). So, we could // treat a "many-item pointer" of const u8 as a string as long as // we can CONVERT IT TO A SLICE. (Hint: we do know the length!) // // Please fix this line so the print statement below can print it: const zen12_string: *const [21]u8 = zen_manyptr[0..21]; // Here's the moment of truth! std.debug.print("{s}\n", .{zen12_string}); } // // Are all of these pointer types starting to get confusing? // // FREE ZIG POINTER CHEATSHEET! (Using u8 as the example type.) // +---------------+----------------------------------------------+ // | u8 | one u8 | // | *u8 | pointer to one u8 | // | [2]u8 | two u8s | // | [*]u8 | pointer to unknown number of u8s | // | [*]const u8 | pointer to unknown number of immutable u8s | // | *[2]u8 | pointer to an array of 2 u8s | // | *const [2]u8 | pointer to an immutable array of 2 u8s | // | []u8 | slice of u8s | // | []const u8 | slice of immutable u8s | // +---------------+----------------------------------------------+
https://raw.githubusercontent.com/gmeir/ziglings/3af093bb3ac426fc57d68ed8a75bf896600c4932/exercises/054_manypointers.zig
const std = @import("std"); const PrintHelper = @import("print_helper.zig").PrintHelper; const CodegenState = @import("codegen.zig").CodegenState; const CodegenModuleState = @import("codegen.zig").CodegenModuleState; const ExpressionResult = @import("codegen.zig").ExpressionResult; const BufferDest = @import("codegen.zig").BufferDest; const FloatDest = @import("codegen.zig").FloatDest; const Instruction = @import("codegen.zig").Instruction; const State = struct { cs: *const CodegenState, cms: *const CodegenModuleState, helper: PrintHelper, pub fn print(self: *State, comptime fmt: []const u8, args: var) !void { try self.helper.print(self, fmt, args); } pub fn printArgValue(self: *State, comptime arg_format: []const u8, arg: var) !void { if (comptime std.mem.eql(u8, arg_format, "buffer_dest")) { try self.printBufferDest(arg); } else if (comptime std.mem.eql(u8, arg_format, "float_dest")) { try self.printFloatDest(arg); } else if (comptime std.mem.eql(u8, arg_format, "expression_result")) { try self.printExpressionResult(arg); } else { @compileError("unknown arg_format: \"" ++ arg_format ++ "\""); } } fn printExpressionResult(self: *State, result: ExpressionResult) std.os.WriteError!void { switch (result) { .nothing => unreachable, .temp_buffer => |temp_ref| try self.print("temp{usize}", .{temp_ref.index}), .temp_float => |temp_ref| try self.print("temp_float{usize}", .{temp_ref.index}), .literal_boolean => |value| try self.print("{bool}", .{value}), .literal_number => |value| try self.print("{number_literal}", .{value}), .literal_enum_value => |v| { try self.print("'{str}'", .{v.label}); if (v.payload) |payload| { try self.print("({expression_result})", .{payload.*}); } }, .literal_curve => |curve_index| try self.print("(curve_{usize})", .{curve_index}), .literal_track => |track_index| try self.print("(track_{usize})", .{track_index}), .literal_module => |module_index| try self.print("(module_{usize})", .{module_index}), .self_param => |i| { const module = self.cs.modules[self.cms.module_index]; try self.print("params.{str}", .{module.params[i].name}); }, .track_param => |x| { try self.print("@{str}", .{self.cs.tracks[x.track_index].params[x.param_index].name}); }, } } fn printFloatDest(self: *State, dest: FloatDest) !void { try self.print("temp_float{usize}", .{dest.temp_float_index}); } fn printBufferDest(self: *State, dest: BufferDest) !void { switch (dest) { .temp_buffer_index => |i| try self.print("temp{usize}", .{i}), .output_index => |i| try self.print("output{usize}", .{i}), } } fn indent(self: *State, indentation: usize) !void { var i: usize = 0; while (i < indentation) : (i += 1) { try self.print(" ", .{}); } } }; pub fn printBytecode(out: std.io.StreamSource.OutStream, cs: *const CodegenState, cms: *const CodegenModuleState) !void { var self: State = .{ .cs = cs, .cms = cms, .helper = PrintHelper.init(out), }; const self_module = cs.modules[cms.module_index]; try self.print("module {usize}\n", .{cms.module_index}); try self.print(" num_temp_buffers: {usize}\n", .{cms.temp_buffers.finalCount()}); try self.print(" num_temp_floats: {usize}\n", .{cms.temp_floats.finalCount()}); try self.print("bytecode:\n", .{}); for (cms.instructions.items) |instr| { try printInstruction(&self, instr, 1); } try self.print("\n", .{}); self.helper.finish(); } fn printInstruction(self: *State, instr: Instruction, indentation: usize) std.os.WriteError!void { try self.indent(indentation); switch (instr) { .copy_buffer => |x| { try self.print("{buffer_dest} = {expression_result}\n", .{ x.out, x.in }); }, .float_to_buffer => |x| { try self.print("{buffer_dest} = {expression_result}\n", .{ x.out, x.in }); }, .cob_to_buffer => |x| { const module = self.cs.modules[self.cms.module_index]; try self.print("{buffer_dest} = COB_TO_BUFFER params.{str}\n", .{ x.out, module.params[x.in_self_param].name }); }, .arith_float => |x| { try self.print("{float_dest} = ARITH_FLOAT({auto}) {expression_result}\n", .{ x.out, x.op, x.a }); }, .arith_buffer => |x| { try self.print("{buffer_dest} = ARITH_BUFFER({auto}) {expression_result}\n", .{ x.out, x.op, x.a }); }, .arith_float_float => |x| { try self.print("{float_dest} = ARITH_FLOAT_FLOAT({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b }); }, .arith_float_buffer => |x| { try self.print("{buffer_dest} = ARITH_FLOAT_BUFFER({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b }); }, .arith_buffer_float => |x| { try self.print("{buffer_dest} = ARITH_BUFFER_FLOAT({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b }); }, .arith_buffer_buffer => |x| { try self.print("{buffer_dest} = ARITH_BUFFER_BUFFER({auto}) {expression_result} {expression_result}\n", .{ x.out, x.op, x.a, x.b }); }, .call => |call| { const field_module_index = self.cms.fields.items[call.field_index].module_index; const callee_module = self.cs.modules[field_module_index]; try self.print("{buffer_dest} = CALL #{usize}(module{usize})\n", .{ call.out, call.field_index, field_module_index }); try self.indent(indentation + 1); try self.print("temps: [", .{}); for (call.temps) |temp, i| { if (i > 0) try self.print(", ", .{}); try self.print("temp{usize}", .{temp}); } try self.print("]\n", .{}); for (call.args) |arg, i| { try self.indent(indentation + 1); try self.print("{str} = {expression_result}\n", .{ callee_module.params[i].name, arg }); } }, .track_call => |track_call| { try self.print("{buffer_dest} = TRACK_CALL track_{usize} ({expression_result}):\n", .{ track_call.out, track_call.track_index, track_call.speed, }); for (track_call.instructions) |sub_instr| { try printInstruction(self, sub_instr, indentation + 1); } }, .delay => |delay| { try self.print("{buffer_dest} = DELAY (feedback provided at temps[{usize}]):\n", .{ delay.out, delay.feedback_temp_buffer_index }); for (delay.instructions) |sub_instr| { try printInstruction(self, sub_instr, indentation + 1); } //try self.print("{buffer_dest} = DELAY_END {expression_result}\n", .{delay_end.out,delay_end.inner_value}); // FIXME }, } }
https://raw.githubusercontent.com/justjosias/zang/13e78fd332c30be704863eb96e27a2a39df1bacd/src/zangscript/codegen_print.zig
const std = @import("std"); // Although this function looks imperative, note that its job is to // declaratively construct a build graph that will be executed by an external // runner. pub fn build(b: *std.Build) 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 optimization options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. Here we do not // set a preferred release mode, allowing the user to decide how to optimize. const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "ts-rust-zig-deez", // In this case the main source file is merely a path, however, in more // complicated build scripts, this could be a generated file. .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); // This declares intent for the executable to be installed into the // standard location when the user invokes the "install" step (the default // step when running `zig build`). b.installArtifact(exe); // This *creates* a RunStep in the build graph, to be executed when another // step is evaluated that depends on it. The next line below will establish // such a dependency. const run_cmd = b.addRunArtifact(exe); // By making the run step depend on the install step, it will be run from the // installation directory rather than directly from within the cache directory. // This is not necessary, however, if the application depends on other installed // files, this ensures they will be present and in the expected location. run_cmd.step.dependOn(b.getInstallStep()); // This allows the user to pass arguments to the application in the build // command itself, like this: `zig build run -- arg1 arg2 etc` if (b.args) |args| { run_cmd.addArgs(args); } // This creates a build step. It will be visible in the `zig build --help` menu, // and can be selected like this: `zig build run` // This will evaluate the `run` step rather than the default, which is "install". const run_step = b.step("run", "Run the app"); run_step.dependOn(&run_cmd.step); // Creates a step for unit testing. This only builds the test executable // but does not run it. const unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); run_unit_tests.has_side_effects = true; // prevent caching // Similar to creating the run step earlier, this exposes a `test` step to // the `zig build --help` menu, providing a way for the user to request // running the unit tests. const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); }
https://raw.githubusercontent.com/ThePrimeagen/ts-rust-zig-deez/3441b21d30a8d8488f2bec85cef4f9054891e9ea/zig/build.zig
//------------------------------------------------------------------------------ // blend.zig // Test/demonstrate blend modes. //------------------------------------------------------------------------------ const sokol = @import("sokol"); const slog = sokol.log; const sg = sokol.gfx; const sapp = sokol.app; const sgapp = sokol.app_gfx_glue; const vec3 = @import("math.zig").Vec3; const mat4 = @import("math.zig").Mat4; const shd = @import("shaders/blend.glsl.zig"); const NUM_BLEND_FACTORS = 15; const state = struct { var pass_action: sg.PassAction = .{}; var bind: sg.Bindings = .{}; var pip: [NUM_BLEND_FACTORS][NUM_BLEND_FACTORS]sg.Pipeline = undefined; var bg_pip: sg.Pipeline = .{}; var r: f32 = 0; var tick: f32 = 0; }; export fn init() void { sg.setup(.{ .pipeline_pool_size = NUM_BLEND_FACTORS * NUM_BLEND_FACTORS + 1, .context = sgapp.context(), .logger = .{ .func = slog.func }, }); state.pass_action.colors[0].action = .DONTCARE; state.pass_action.depth.action = .DONTCARE; state.pass_action.stencil.action = .DONTCARE; state.bind.vertex_buffers[0] = sg.makeBuffer(.{ .data = sg.asRange(&[_]f32 { // pos color -1.0, -1.0, 0.0, 1.0, 0.0, 0.0, 0.5, 1.0, -1.0, 0.0, 0.0, 1.0, 0.0, 0.5, -1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.5, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 0.5 }) }); // pipeline object for rendering the background var pip_desc: sg.PipelineDesc = .{ .shader = sg.makeShader(shd.bgShaderDesc(sg.queryBackend())), .primitive_type = .TRIANGLE_STRIP, }; pip_desc.layout.buffers[0].stride = 28; pip_desc.layout.attrs[shd.ATTR_vs_bg_position].format = .FLOAT2; state.bg_pip = sg.makePipeline(pip_desc); // lot of pipeline objects for rendering the blended quads pip_desc = .{ .shader = sg.makeShader(shd.quadShaderDesc(sg.queryBackend())), .primitive_type = .TRIANGLE_STRIP, .blend_color = .{ .r=1.0, .g=0.0, .b=0.0, .a=1.0 } }; pip_desc.layout.attrs[shd.ATTR_vs_quad_position].format = .FLOAT3; pip_desc.layout.attrs[shd.ATTR_vs_quad_color0].format = .FLOAT4; pip_desc.colors[0].blend = .{ .enabled = true, .src_factor_alpha = .ONE, .dst_factor_alpha = .ZERO, }; var src: usize = 0; while (src < NUM_BLEND_FACTORS): (src += 1) { var dst: usize = 0; while (dst < NUM_BLEND_FACTORS): (dst += 1) { pip_desc.colors[0].blend.src_factor_rgb = @intToEnum(sg.BlendFactor, src + 1); pip_desc.colors[0].blend.dst_factor_rgb = @intToEnum(sg.BlendFactor, dst + 1); state.pip[src][dst] = sg.makePipeline(pip_desc); } } } export fn frame() void { const time = @floatCast(f32, sapp.frameDuration()) * 60.0; sg.beginDefaultPass(state.pass_action, sapp.width(), sapp.height()); // draw background state.tick += 1.0 * time; const bg_fs_params: shd.BgFsParams = .{ .tick = state.tick }; sg.applyPipeline(state.bg_pip); sg.applyBindings(state.bind); sg.applyUniforms(.FS, shd.SLOT_bg_fs_params, sg.asRange(&bg_fs_params)); sg.draw(0, 4, 1); // draw the blended quads const proj = mat4.persp(90.0, sapp.widthf() / sapp.heightf(), 0.01, 100.0); const view = mat4.lookat(.{ .x = 0, .y = 0, .z = 25.0 }, vec3.zero(), vec3.up()); const view_proj = mat4.mul(proj, view); state.r += 0.6 * time; var r0 = state.r; var src: usize = 0; while (src < NUM_BLEND_FACTORS): (src += 1) { var dst: usize = 0; while (dst < NUM_BLEND_FACTORS): (dst += 1) { // compute model-view-proj matrix const shift = NUM_BLEND_FACTORS / 2; const t: vec3 = .{ .x = (@intToFloat(f32, dst) - shift) * 3.0, .y = (@intToFloat(f32, src) - shift) * 2.2, .z = 0.0 }; const model = mat4.mul(mat4.translate(t), mat4.rotate(r0, vec3.up())); const quad_vs_params: shd.QuadVsParams = .{ .mvp = mat4.mul(view_proj, model) }; sg.applyPipeline(state.pip[src][dst]); sg.applyBindings(state.bind); sg.applyUniforms(.VS, shd.SLOT_quad_vs_params, sg.asRange(&quad_vs_params)); sg.draw(0, 4, 1); r0 += 0.6; } } sg.endPass(); sg.commit(); } export fn cleanup() void { sg.shutdown(); } pub fn main() void { sapp.run(.{ .init_cb = init, .frame_cb = frame, .cleanup_cb = cleanup, .width = 800, .height = 600, .sample_count = 4, .window_title = "blend.zig", .icon = .{ .sokol_default = true }, .logger = .{ .func = slog.func }, }); }
https://raw.githubusercontent.com/CU-Production/nesemu.zig/5cc75ac5dd88a49c542a5fe2695134be8fa469a2/lib/sokol-zig/src/examples/blend.zig
const std = @import("std"); pub fn build(b: *std.Build) !void { const target_query: std.Target.Query = .{}; const target = b.resolveTargetQuery(target_query); const optimize = b.standardOptimizeOption(.{}); const lib = b.addStaticLibrary(.{ .name = "llvm", .root_source_file = .{.path = "src/llvm-zig.zig"}, .target = target, .optimize = optimize }); lib.defineCMacro("_FILE_OFFSET_BITS", "64"); lib.defineCMacro("__STDC_CONSTANT_MACROS", null); lib.defineCMacro("__STDC_FORMAT_MACROS", null); lib.defineCMacro("__STDC_LIMIT_MACROS", null); lib.linkSystemLibrary("z"); lib.linkLibC(); switch (target.result.os.tag) { .linux => lib.linkSystemLibrary("LLVM-17"), // Ubuntu .macos => { lib.addLibraryPath(.{ .path = "/usr/local/opt/llvm/lib" }); lib.linkSystemLibrary("LLVM"); }, else => lib.linkSystemLibrary("LLVM"), } b.installArtifact(lib); _ = try b.modules.put("llvm", &lib.root_module); _ = b.addModule("clang", .{ .root_source_file = .{ .path = "src/clang.zig", }, }); const examples = b.option(bool, "Examples", "Build all examples [default: false]") orelse false; if (examples) { buildExample(b, target, .{ .filepath = "examples/sum_module.zig", .target = target.query, .optimize = optimize, }); buildExample(b, target, .{ .filepath = "examples/factorial_module.zig", .target = target.query, .optimize = optimize, }); } buildTests(b, target); } fn buildExample(b: *std.Build, target: std.Build.ResolvedTarget, i: BuildInfo) void { const exe = b.addExecutable(.{ .name = i.filename(), .root_source_file = .{ .path = i.filepath }, .target = target, .optimize = i.optimize, }); exe.root_module.addImport("llvm", b.modules.get("llvm").?); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step(i.filename(), b.fmt("Run the {s}", .{i.filename()})); run_step.dependOn(&run_cmd.step); } const BuildInfo = struct { filepath: []const u8, target: std.zig.CrossTarget, optimize: std.builtin.OptimizeMode, fn filename(self: BuildInfo) []const u8 { var split = std.mem.splitSequence(u8, std.fs.path.basename(self.filepath), "."); return split.first(); } }; fn buildTests(b: *std.Build, target: std.Build.ResolvedTarget) void { const llvm_tests = b.addTest(.{ .root_source_file = .{ .path = "src/llvm-zig.zig" }, .target = target, .optimize = .Debug, .name = "llvm-tests", }); const clang_tests = b.addTest(.{ .root_source_file = .{ .path = "src/clang.zig" }, .target = target, .optimize = .Debug, .name = "clang-tests", }); switch (target.result.os.tag) { .linux => clang_tests.linkSystemLibrary("clang-17"), // Ubuntu .macos => { clang_tests.addLibraryPath(.{ .path = "/usr/local/opt/llvm/lib" }); clang_tests.linkSystemLibrary("clang"); }, else => clang_tests.linkSystemLibrary("clang"), } clang_tests.linkLibC(); llvm_tests.root_module.addImport("llvm", b.modules.get("llvm").?); // TODO: CI build LLVM tests with clang // llvm_tests.step.dependOn(&clang_tests.step); const run_llvm_tests = b.addRunArtifact(llvm_tests); const test_llvm_step = b.step("test", "Run LLVM-binding tests"); test_llvm_step.dependOn(&run_llvm_tests.step); }
https://raw.githubusercontent.com/kassane/llvm-zig/6cb8d824d6c67e43e371f1bd5ec3ad1cf5773021/build.zig
const std = @import("std"); const SyntaxNode = @import("SyntaxNode.zig"); const StatementSyntax = @import("StatementSyntax.zig"); const ExpressionSyntax = @import("ExpressionSyntax.zig"); const SyntaxToken = @import("SyntaxToken.zig"); const AllocError = std.mem.Allocator.Error; base: StatementSyntax, keyword_token: SyntaxToken, identifier_token: SyntaxToken, equals_token: SyntaxToken, initializer: *ExpressionSyntax, const Self = @This(); pub fn init( allocator: std.mem.Allocator, keyword_token: SyntaxToken, identifier_token: SyntaxToken, equals_token: SyntaxToken, initializer: *ExpressionSyntax, ) !*StatementSyntax { const result = try allocator.create(Self); result.* = .{ .base = StatementSyntax.init(.variable_declaration, &deinit, &children, null), .keyword_token = keyword_token, .identifier_token = identifier_token, .equals_token = equals_token, .initializer = initializer, }; return &result.base; } fn deinit(node: *const SyntaxNode, allocator: std.mem.Allocator) void { const self = StatementSyntax.downcastNode(node, Self); self.initializer.deinit(allocator); allocator.destroy(self); } fn children(node: *const SyntaxNode, allocator: std.mem.Allocator) AllocError![]*const SyntaxNode { const self = StatementSyntax.downcastNode(node, Self); return try allocator.dupe(*const SyntaxNode, &.{ &self.keyword_token.base, &self.identifier_token.base, &self.equals_token.base, &self.initializer.base, }); }
https://raw.githubusercontent.com/Phytolizer/Minsk/50609232b5d6fecccfebb68f742523b38ed8ec4e/zig/minsk/src/code_analysis/syntax/VariableDeclarationSyntax.zig
const std = @import("std"); const llvm = @import("llvm.zig"); const Allocator = std.mem.Allocator; const ValueSeq = std.ArrayListUnmanaged(llvm.Value); allocator: Allocator, write_operands: ValueSeq = undefined, read_operands: ValueSeq = undefined, pub fn init(allocator: Allocator) @This() { return .{ .allocator = allocator, .write_operands = ValueSeq.initCapacity(allocator, 1) catch { @panic("allocation failed"); }, .read_operands = ValueSeq.initCapacity(allocator, 1) catch { @panic("allocation failed"); }, }; } pub fn add_write_operand(self: *@This(), value: llvm.Value) void { self.write_operands.append(self.allocator, value) catch { @panic("allocation failed"); }; } pub fn add_read_operand(self: *@This(), value: llvm.Value) void { self.read_operands.append(self.allocator, value) catch { @panic("allocation failed"); }; } pub fn read_count(self: @This()) usize { return self.read_operands.items.len; } pub fn write_count(self: @This()) usize { return self.write_operands.items.len; } pub fn deinit(self: *@This()) void { self.write_operands.deinit(self.allocator); self.read_operands.deinit(self.allocator); self.read_operands = undefined; self.write_operands = undefined; }
https://raw.githubusercontent.com/lovebaihezi/diff-based-analyze/bb2d88328d5d858c124e2d5e0e3c957326a0ab52/src/variable_info.zig
const std = @import("std"); const tk = @import("tokamak"); const fr = @import("fridge"); const schema = @import("../schema.zig"); const llama = @import("../llama.zig"); const template = @import("../template.zig"); const completions = @import("completions.zig"); const GenerateParams = struct { model: []const u8, data: std.json.Value, max_tokens: u32 = 2048, sampling: llama.SamplingParams = .{}, }; pub fn @"GET /quick-tools"(db: *fr.Session) ![]const schema.QuickTool { return db.findAll(fr.query(schema.QuickTool).orderBy(.id, .asc)); } pub fn @"GET /quick-tools/:id"(db: *fr.Session, id: u32) !schema.QuickTool { return try db.find(schema.QuickTool, id) orelse error.NotFound; } pub fn @"POST /quick-tools"(db: *fr.Session, data: schema.QuickTool) !schema.QuickTool { return db.create(schema.QuickTool, data); } pub fn @"PUT /quick-tools/:id"(db: *fr.Session, id: u32, data: schema.QuickTool) !schema.QuickTool { try db.update(schema.QuickTool, id, data); return try db.find(schema.QuickTool, id) orelse error.NotFound; } pub fn @"POST /quick-tools/:id/generate"(ctx: *tk.Context, db: *fr.Session, id: u32, params: GenerateParams) !void { const tool = try db.find(schema.QuickTool, id) orelse return error.NotFound; const tpl = try template.Template.parse(ctx.allocator, tool.prompt); const prompt = try tpl.renderAlloc(ctx.allocator, params.data); std.log.debug("Generating with prompt: {s}", .{prompt}); return ctx.injector.call(completions.@"POST /chat/completions", .{.{ .model = params.model, .prompt = prompt, .max_tokens = params.max_tokens, .sampling = params.sampling, }}); } pub fn @"DELETE /quick-tools/:id"(db: *fr.Session, id: u32) !void { try db.delete(schema.QuickTool, id); }
https://raw.githubusercontent.com/cztomsik/ava/b3de783520a3e8bd1bed485d6f7cb6942fabf57d/src/api/quick-tools.zig
// SPDX-License-Identifier: MIT // Copyright (c) 2015-2021 Zig Contributors // This file is part of [zig](https://ziglang.org/), which is MIT licensed. // The MIT license requires this copyright notice to be included in all copies // and substantial portions of the software. const uefi = @import("std").os.uefi; const Guid = uefi.Guid; const Event = uefi.Event; const Status = uefi.Status; const MacAddress = uefi.protocols.MacAddress; const ManagedNetworkConfigData = uefi.protocols.ManagedNetworkConfigData; const SimpleNetworkMode = uefi.protocols.SimpleNetworkMode; pub const Ip6Protocol = extern struct { _get_mode_data: fn (*const Ip6Protocol, ?*Ip6ModeData, ?*ManagedNetworkConfigData, ?*SimpleNetworkMode) callconv(.C) Status, _configure: fn (*const Ip6Protocol, ?*const Ip6ConfigData) callconv(.C) Status, _groups: fn (*const Ip6Protocol, bool, ?*const Ip6Address) callconv(.C) Status, _routes: fn (*const Ip6Protocol, bool, ?*const Ip6Address, u8, ?*const Ip6Address) callconv(.C) Status, _neighbors: fn (*const Ip6Protocol, bool, *const Ip6Address, ?*const MacAddress, u32, bool) callconv(.C) Status, _transmit: fn (*const Ip6Protocol, *Ip6CompletionToken) callconv(.C) Status, _receive: fn (*const Ip6Protocol, *Ip6CompletionToken) callconv(.C) Status, _cancel: fn (*const Ip6Protocol, ?*Ip6CompletionToken) callconv(.C) Status, _poll: fn (*const Ip6Protocol) callconv(.C) Status, /// Gets the current operational settings for this instance of the EFI IPv6 Protocol driver. pub fn getModeData(self: *const Ip6Protocol, ip6_mode_data: ?*Ip6ModeData, mnp_config_data: ?*ManagedNetworkConfigData, snp_mode_data: ?*SimpleNetworkMode) Status { return self._get_mode_data(self, ip6_mode_data, mnp_config_data, snp_mode_data); } /// Assign IPv6 address and other configuration parameter to this EFI IPv6 Protocol driver instance. pub fn configure(self: *const Ip6Protocol, ip6_config_data: ?*const Ip6ConfigData) Status { return self._configure(self, ip6_config_data); } /// Joins and leaves multicast groups. pub fn groups(self: *const Ip6Protocol, join_flag: bool, group_address: ?*const Ip6Address) Status { return self._groups(self, join_flag, group_address); } /// Adds and deletes routing table entries. pub fn routes(self: *const Ip6Protocol, delete_route: bool, destination: ?*const Ip6Address, prefix_length: u8, gateway_address: ?*const Ip6Address) Status { return self._routes(self, delete_route, destination, prefix_length, gateway_address); } /// Add or delete Neighbor cache entries. pub fn neighbors(self: *const Ip6Protocol, delete_flag: bool, target_ip6_address: *const Ip6Address, target_link_address: ?*const MacAddress, timeout: u32, override: bool) Status { return self._neighbors(self, delete_flag, target_ip6_address, target_link_address, timeout, override); } /// Places outgoing data packets into the transmit queue. pub fn transmit(self: *const Ip6Protocol, token: *Ip6CompletionToken) Status { return self._transmit(self, token); } /// Places a receiving request into the receiving queue. pub fn receive(self: *const Ip6Protocol, token: *Ip6CompletionToken) Status { return self._receive(self, token); } /// Abort an asynchronous transmits or receive request. pub fn cancel(self: *const Ip6Protocol, token: ?*Ip6CompletionToken) Status { return self._cancel(self, token); } /// Polls for incoming data packets and processes outgoing data packets. pub fn poll(self: *const Ip6Protocol) Status { return self._poll(self); } pub const guid align(8) = Guid{ .time_low = 0x2c8759d5, .time_mid = 0x5c2d, .time_high_and_version = 0x66ef, .clock_seq_high_and_reserved = 0x92, .clock_seq_low = 0x5f, .node = [_]u8{ 0xb6, 0x6c, 0x10, 0x19, 0x57, 0xe2 }, }; }; pub const Ip6ModeData = extern struct { is_started: bool, max_packet_size: u32, config_data: Ip6ConfigData, is_configured: bool, address_count: u32, address_list: [*]Ip6AddressInfo, group_count: u32, group_table: [*]Ip6Address, route_count: u32, route_table: [*]Ip6RouteTable, neighbor_count: u32, neighbor_cache: [*]Ip6NeighborCache, prefix_count: u32, prefix_table: [*]Ip6AddressInfo, icmp_type_count: u32, icmp_type_list: [*]Ip6IcmpType, }; pub const Ip6ConfigData = extern struct { default_protocol: u8, accept_any_protocol: bool, accept_icmp_errors: bool, accept_promiscuous: bool, destination_address: Ip6Address, station_address: Ip6Address, traffic_class: u8, hop_limit: u8, flow_label: u32, receive_timeout: u32, transmit_timeout: u32, }; pub const Ip6Address = [16]u8; pub const Ip6AddressInfo = extern struct { address: Ip6Address, prefix_length: u8, }; pub const Ip6RouteTable = extern struct { gateway: Ip6Address, destination: Ip6Address, prefix_length: u8, }; pub const Ip6NeighborState = extern enum(u32) { Incomplete, Reachable, Stale, Delay, Probe, }; pub const Ip6NeighborCache = extern struct { neighbor: Ip6Address, link_address: MacAddress, state: Ip6NeighborState, }; pub const Ip6IcmpType = extern struct { type: u8, code: u8, }; pub const Ip6CompletionToken = extern struct { event: Event, status: Status, packet: *c_void, // union TODO };
https://raw.githubusercontent.com/dip-proto/zig/8f79f7e60937481fcf861c2941db02cbf449cdca/lib/std/os/uefi/protocols/ip6_protocol.zig
usingnamespace @import("std").math; usingnamespace @import("./math3d.zig"); pub fn clamp(val: f32, min_val: f32, max_val: f32) f32 { return min(max_val, max(min_val, val)); } pub fn saturate(f: f32) f32 { if (f < 0) return 0; if (f > 1) return 1; return f; } pub fn unlerp(ax: f32, a1: f32, a2: f32) f32 { return (ax - a1) / (a2 - a1); } pub fn smooth_damp_vec3(current: Vec3, target: Vec3, current_velocity: *Vec3, smooth_time: f32, delta_time: f32) Vec3 { const x: f32 = smooth_damp(current.x, target.x, &current_velocity.x, smooth_time, delta_time); const y: f32 = smooth_damp(current.y, target.y, &current_velocity.y, smooth_time, delta_time); const z: f32 = smooth_damp(current.z, target.z, &current_velocity.z, smooth_time, delta_time); return vec3(x, y, z); } // thanks Unity decompiled pub fn smooth_damp( current: f32, _target: f32, current_velocity: *f32, _smooth_time: f32, delta_time: f32, //max_speed: f32 = inf(f32), ) f32 { var target = _target; const max_speed = inf(f32); const smooth_time = max(0.0001, _smooth_time); var num: f32 = 2.0 / smooth_time; var num2: f32 = num * delta_time; var num3: f32 = 1.0 / (1.0 + num2 + 0.48 * num2 * num2 + 0.235 * num2 * num2 * num2); var num4: f32 = current - target; var num5: f32 = target; var num6: f32 = max_speed * smooth_time; num4 = clamp(num4, -num6, num6); target = current - num4; var num7: f32 = (current_velocity.* + num * num4) * delta_time; current_velocity.* = (current_velocity.* - num * num7) * num3; var num8: f32 = target + (num4 + num7) * num3; if ((num5 - current > 0.0) == (num8 > num5)) { num8 = num5; current_velocity.* = (num8 - num5) / delta_time; } return num8; }
https://raw.githubusercontent.com/kevinw/zig-wasm-game/31322890a15d25f1fca134980be7f043767d37a2/src/game_math.zig
const std = @import("std"); const expect = std.testing.expect; const Environment = @import("./env.zig"); const string = bun.string; const stringZ = bun.stringZ; const CodePoint = bun.CodePoint; const bun = @import("root").bun; pub const joiner = @import("./string_joiner.zig"); const log = bun.Output.scoped(.STR, true); pub const Encoding = enum { ascii, utf8, latin1, utf16, }; pub inline fn containsChar(self: string, char: u8) bool { return indexOfChar(self, char) != null; } pub inline fn contains(self: string, str: string) bool { return indexOf(self, str) != null; } pub fn w(comptime str: []const u8) [:0]const u16 { comptime var output: [str.len + 1]u16 = undefined; for (str, 0..) |c, i| { output[i] = c; } output[str.len] = 0; const Static = struct { pub const literal: [:0]const u16 = output[0 .. output.len - 1 :0]; }; return Static.literal; } pub fn toUTF16Literal(comptime str: []const u8) []const u16 { return comptime brk: { comptime var output: [str.len]u16 = undefined; for (str, 0..) |c, i| { output[i] = c; } const Static = struct { pub const literal: []const u16 = output[0..]; }; break :brk Static.literal; }; } pub const OptionalUsize = std.meta.Int(.unsigned, @bitSizeOf(usize) - 1); pub fn indexOfAny(slice: string, comptime str: anytype) ?OptionalUsize { switch (comptime str.len) { 0 => @compileError("str cannot be empty"), 1 => return indexOfChar(slice, str[0]), else => {}, } var remaining = slice; if (remaining.len == 0) return null; if (comptime Environment.enableSIMD) { while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; var cmp: AsciiVectorU1 = @bitCast(vec == @as(AsciiVector, @splat(@as(u8, str[0])))); inline for (str[1..]) |c| { cmp |= @bitCast(vec == @as(AsciiVector, @splat(@as(u8, c)))); } if (@reduce(.Max, cmp) > 0) { const bitmask = @as(AsciiVectorInt, @bitCast(cmp)); const first = @ctz(bitmask); return @as(OptionalUsize, @intCast(first + slice.len - remaining.len)); } remaining = remaining[ascii_vector_size..]; } if (comptime Environment.allow_assert) std.debug.assert(remaining.len < ascii_vector_size); } for (remaining, 0..) |c, i| { if (strings.indexOfChar(str, c) != null) { return @as(OptionalUsize, @intCast(i + slice.len - remaining.len)); } } return null; } pub fn indexOfAny16(self: []const u16, comptime str: anytype) ?OptionalUsize { for (self, 0..) |c, i| { inline for (str) |a| { if (c == a) { return @as(OptionalUsize, @intCast(i)); } } } return null; } pub inline fn containsComptime(self: string, comptime str: string) bool { var remain = self; const Int = std.meta.Int(.unsigned, str.len * 8); while (remain.len >= comptime str.len) { if (@as(Int, @bitCast(remain.ptr[0..str.len].*)) == @as(Int, @bitCast(str.ptr[0..str.len].*))) { return true; } remain = remain[str.len..]; } return false; } pub const includes = contains; pub fn inMapCaseInsensitive(self: string, comptime ComptimeStringMap: anytype) ?ComptimeStringMap.Value { return bun.String.static(self).inMapCaseInsensitive(ComptimeStringMap); } pub inline fn containsAny(in: anytype, target: string) bool { for (in) |str| if (contains(if (@TypeOf(str) == u8) &[1]u8{str} else bun.span(str), target)) return true; return false; } /// https://docs.npmjs.com/cli/v8/configuring-npm/package-json /// - The name must be less than or equal to 214 characters. This includes the scope for scoped packages. /// - The names of scoped packages can begin with a dot or an underscore. This is not permitted without a scope. /// - New packages must not have uppercase letters in the name. /// - The name ends up being part of a URL, an argument on the command line, and /// a folder name. Therefore, the name can't contain any non-URL-safe /// characters. pub inline fn isNPMPackageName(target: string) bool { if (target.len == 0) return false; if (target.len > 214) return false; const scoped = switch (target[0]) { // Old packages may have capital letters 'A'...'Z', 'a'...'z', '0'...'9', '$', '-' => false, '@' => true, else => return false, }; var slash_index: usize = 0; for (target[1..], 0..) |c, i| { switch (c) { // Old packages may have capital letters 'A'...'Z', 'a'...'z', '0'...'9', '$', '-', '_', '.' => {}, '/' => { if (!scoped) return false; if (slash_index > 0) return false; slash_index = i + 1; }, else => return false, } } return !scoped or slash_index > 0 and slash_index + 1 < target.len; } pub inline fn indexAny(in: anytype, target: string) ?usize { for (in, 0..) |str, i| if (indexOf(str, target) != null) return i; return null; } pub inline fn indexAnyComptime(target: string, comptime chars: string) ?usize { for (target, 0..) |parent, i| { inline for (chars) |char| { if (char == parent) return i; } } return null; } pub inline fn indexEqualAny(in: anytype, target: string) ?usize { for (in, 0..) |str, i| if (eqlLong(str, target, true)) return i; return null; } pub fn repeatingAlloc(allocator: std.mem.Allocator, count: usize, char: u8) ![]u8 { var buf = try allocator.alloc(u8, count); repeatingBuf(buf, char); return buf; } pub fn repeatingBuf(self: []u8, char: u8) void { @memset(self, char); } pub fn indexOfCharNeg(self: string, char: u8) i32 { var i: u32 = 0; while (i < self.len) : (i += 1) { if (self[i] == char) return @as(i32, @intCast(i)); } return -1; } /// Format a string to an ECMAScript identifier. /// Unlike the string_mutable.zig version, this always allocate/copy pub fn fmtIdentifier(name: string) FormatValidIdentifier { return FormatValidIdentifier{ .name = name }; } /// Format a string to an ECMAScript identifier. /// Different implementation than string_mutable because string_mutable may avoid allocating /// This will always allocate pub const FormatValidIdentifier = struct { name: string, const js_lexer = @import("./js_lexer.zig"); pub fn format(self: FormatValidIdentifier, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { var iterator = strings.CodepointIterator.init(self.name); var cursor = strings.CodepointIterator.Cursor{}; var has_needed_gap = false; var needs_gap = false; var start_i: usize = 0; if (!iterator.next(&cursor)) { try writer.writeAll("_"); return; } // Common case: no gap necessary. No allocation necessary. needs_gap = !js_lexer.isIdentifierStart(cursor.c); if (!needs_gap) { // Are there any non-alphanumeric chars at all? while (iterator.next(&cursor)) { if (!js_lexer.isIdentifierContinue(cursor.c) or cursor.width > 1) { needs_gap = true; start_i = cursor.i; break; } } } if (needs_gap) { needs_gap = false; if (start_i > 0) try writer.writeAll(self.name[0..start_i]); var slice = self.name[start_i..]; iterator = strings.CodepointIterator.init(slice); cursor = strings.CodepointIterator.Cursor{}; while (iterator.next(&cursor)) { if (js_lexer.isIdentifierContinue(cursor.c) and cursor.width == 1) { if (needs_gap) { try writer.writeAll("_"); needs_gap = false; has_needed_gap = true; } try writer.writeAll(slice[cursor.i .. cursor.i + @as(u32, cursor.width)]); } else if (!needs_gap) { needs_gap = true; // skip the code point, replace it with a single _ } } // If it ends with an emoji if (needs_gap) { try writer.writeAll("_"); needs_gap = false; has_needed_gap = true; } return; } try writer.writeAll(self.name); } }; pub fn indexOfSigned(self: string, str: string) i32 { const i = std.mem.indexOf(u8, self, str) orelse return -1; return @as(i32, @intCast(i)); } pub inline fn lastIndexOfChar(self: string, char: u8) ?usize { return std.mem.lastIndexOfScalar(u8, self, char); } pub inline fn lastIndexOf(self: string, str: string) ?usize { return std.mem.lastIndexOf(u8, self, str); } pub inline fn indexOf(self: string, str: string) ?usize { if (comptime !bun.Environment.isNative) { return std.mem.indexOf(u8, self, str); } const self_len = self.len; const str_len = str.len; // > Both old and new libc's have the bug that if needle is empty, // > haystack-1 (instead of haystack) is returned. And glibc 2.0 makes it // > worse, returning a pointer to the last byte of haystack. This is fixed // > in glibc 2.1. if (self_len == 0 or str_len == 0 or self_len < str_len) return null; const self_ptr = self.ptr; const str_ptr = str.ptr; if (str_len == 1) return indexOfCharUsize(self, str_ptr[0]); const start = bun.C.memmem(self_ptr, self_len, str_ptr, str_len) orelse return null; const i = @intFromPtr(start) - @intFromPtr(self_ptr); std.debug.assert(i < self_len); return @as(usize, @intCast(i)); } pub fn split(self: string, delimiter: string) SplitIterator { return SplitIterator{ .buffer = self, .index = 0, .delimiter = delimiter, }; } pub const SplitIterator = struct { buffer: []const u8, index: ?usize, delimiter: []const u8, const Self = @This(); /// Returns a slice of the first field. This never fails. /// Call this only to get the first field and then use `next` to get all subsequent fields. pub fn first(self: *Self) []const u8 { std.debug.assert(self.index.? == 0); return self.next().?; } /// Returns a slice of the next field, or null if splitting is complete. pub fn next(self: *Self) ?[]const u8 { const start = self.index orelse return null; const end = if (indexOf(self.buffer[start..], self.delimiter)) |delim_start| blk: { const del = delim_start + start; self.index = del + self.delimiter.len; break :blk delim_start + start; } else blk: { self.index = null; break :blk self.buffer.len; }; return self.buffer[start..end]; } /// Returns a slice of the remaining bytes. Does not affect iterator state. pub fn rest(self: Self) []const u8 { const end = self.buffer.len; const start = self.index orelse end; return self.buffer[start..end]; } /// Resets the iterator to the initial slice. pub fn reset(self: *Self) void { self.index = 0; } }; // -- // This is faster when the string is found, by about 2x for a 8 MB file. // It is slower when the string is NOT found // fn indexOfPosN(comptime T: type, buf: []const u8, start_index: usize, delimiter: []const u8, comptime n: comptime_int) ?usize { // const k = delimiter.len; // const V8x32 = @Vector(n, T); // const V1x32 = @Vector(n, u1); // const Vbx32 = @Vector(n, bool); // const first = @splat(n, delimiter[0]); // const last = @splat(n, delimiter[k - 1]); // var end: usize = start_index + n; // var start: usize = end - n; // while (end < buf.len) { // start = end - n; // const last_end = @min(end + k - 1, buf.len); // const last_start = last_end - n; // // Look for the first character in the delimter // const first_chunk: V8x32 = buf[start..end][0..n].*; // const last_chunk: V8x32 = buf[last_start..last_end][0..n].*; // const mask = @bitCast(V1x32, first == first_chunk) & @bitCast(V1x32, last == last_chunk); // if (@reduce(.Or, mask) != 0) { // // TODO: Use __builtin_clz??? // for (@as([n]bool, @bitCast(Vbx32, mask))) |match, i| { // if (match and eqlLong(buf[start + i .. start + i + k], delimiter, false)) { // return start + i; // } // } // } // end = @min(end + n, buf.len); // } // if (start < buf.len) return std.mem.indexOfPos(T, buf, start_index, delimiter); // return null; // Not found // } pub fn cat(allocator: std.mem.Allocator, first: string, second: string) !string { var out = try allocator.alloc(u8, first.len + second.len); bun.copy(u8, out, first); bun.copy(u8, out[first.len..], second); return out; } // 30 character string or a slice pub const StringOrTinyString = struct { pub const Max = 30; const Buffer = [Max]u8; remainder_buf: Buffer = undefined, remainder_len: u7 = 0, is_tiny_string: u1 = 0, pub inline fn slice(this: *const StringOrTinyString) []const u8 { // This is a switch expression instead of a statement to make sure it uses the faster assembly return switch (this.is_tiny_string) { 1 => this.remainder_buf[0..this.remainder_len], 0 => @as([*]const u8, @ptrFromInt(std.mem.readIntNative(usize, this.remainder_buf[0..@sizeOf(usize)])))[0..std.mem.readIntNative(usize, this.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2])], }; } pub fn deinit(this: *StringOrTinyString, _: std.mem.Allocator) void { if (this.is_tiny_string == 1) return; // var slice_ = this.slice(); // allocator.free(slice_); } pub fn initAppendIfNeeded(stringy: string, comptime Appender: type, appendy: Appender) !StringOrTinyString { if (stringy.len <= StringOrTinyString.Max) { return StringOrTinyString.init(stringy); } return StringOrTinyString.init(try appendy.append(string, stringy)); } pub fn initLowerCaseAppendIfNeeded(stringy: string, comptime Appender: type, appendy: Appender) !StringOrTinyString { if (stringy.len <= StringOrTinyString.Max) { return StringOrTinyString.initLowerCase(stringy); } return StringOrTinyString.init(try appendy.appendLowerCase(string, stringy)); } pub fn init(stringy: string) StringOrTinyString { switch (stringy.len) { 0 => { return StringOrTinyString{ .is_tiny_string = 1, .remainder_len = 0 }; }, 1...(@sizeOf(Buffer)) => { @setRuntimeSafety(false); var tiny = StringOrTinyString{ .is_tiny_string = 1, .remainder_len = @as(u7, @truncate(stringy.len)), }; @memcpy(tiny.remainder_buf[0..tiny.remainder_len], stringy[0..tiny.remainder_len]); return tiny; }, else => { var tiny = StringOrTinyString{ .is_tiny_string = 0, .remainder_len = 0, }; std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr)); std.mem.writeIntNative(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len); return tiny; }, } } pub fn initLowerCase(stringy: string) StringOrTinyString { switch (stringy.len) { 0 => { return StringOrTinyString{ .is_tiny_string = 1, .remainder_len = 0 }; }, 1...(@sizeOf(Buffer)) => { @setRuntimeSafety(false); var tiny = StringOrTinyString{ .is_tiny_string = 1, .remainder_len = @as(u7, @truncate(stringy.len)), }; _ = copyLowercase(stringy, &tiny.remainder_buf); return tiny; }, else => { var tiny = StringOrTinyString{ .is_tiny_string = 0, .remainder_len = 0, }; std.mem.writeIntNative(usize, tiny.remainder_buf[0..@sizeOf(usize)], @intFromPtr(stringy.ptr)); std.mem.writeIntNative(usize, tiny.remainder_buf[@sizeOf(usize) .. @sizeOf(usize) * 2], stringy.len); return tiny; }, } } }; pub fn copyLowercase(in: string, out: []u8) string { var in_slice = in; var out_slice = out; begin: while (true) { for (in_slice, 0..) |c, i| { switch (c) { 'A'...'Z' => { bun.copy(u8, out_slice, in_slice[0..i]); out_slice[i] = std.ascii.toLower(c); const end = i + 1; in_slice = in_slice[end..]; out_slice = out_slice[end..]; continue :begin; }, else => {}, } } bun.copy(u8, out_slice, in_slice); break :begin; } return out[0..in.len]; } pub fn copyLowercaseIfNeeded(in: string, out: []u8) string { var in_slice = in; var out_slice = out; var any = false; begin: while (true) { for (in_slice, 0..) |c, i| { switch (c) { 'A'...'Z' => { bun.copy(u8, out_slice, in_slice[0..i]); out_slice[i] = std.ascii.toLower(c); const end = i + 1; in_slice = in_slice[end..]; out_slice = out_slice[end..]; any = true; continue :begin; }, else => {}, } } if (any) bun.copy(u8, out_slice, in_slice); break :begin; } return if (any) out[0..in.len] else in; } test "indexOf" { const fixtures = .{ .{ "0123456789", "456", }, .{ "/foo/bar/baz/bacon/eggs/lettuce/tomatoe", "bacon", }, .{ "/foo/bar/baz/bacon////eggs/lettuce/tomatoe", "eggs", }, .{ "////////////////zfoo/bar/baz/bacon/eggs/lettuce/tomatoe", "/", }, .{ "/okay/well/thats/even/longer/now/well/thats/even/longer/now/well/thats/even/longer/now/foo/bar/baz/bacon/eggs/lettuce/tomatoe", "/tomatoe", }, .{ "/okay///////////so much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!much length i can't believe it!/well/thats/even/longer/now/well/thats/even/longer/now/well/thats/even/longer/now/foo/bar/baz/bacon/eggs/lettuce/tomatoe", "/tomatoe", }, }; inline for (fixtures) |pair| { try std.testing.expectEqual( indexOf(pair[0], pair[1]).?, std.mem.indexOf(u8, pair[0], pair[1]).?, ); } } test "eqlComptimeCheckLen" { try std.testing.expectEqual(eqlComptime("bun-darwin-aarch64.zip", "bun-darwin-aarch64.zip"), true); const sizes = [_]u8{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 22, 24 }; inline for (sizes) |size| { var buf: [size]u8 = undefined; @memset(&buf, 'a'); var buf_copy: [size]u8 = undefined; @memset(&buf_copy, 'a'); var bad: [size]u8 = undefined; @memset(&bad, 'b'); try std.testing.expectEqual(std.mem.eql(u8, &buf, &buf_copy), eqlComptime(&buf, comptime brk: { var buf_copy_: [size]u8 = undefined; @memset(&buf_copy_, 'a'); break :brk buf_copy_; })); try std.testing.expectEqual(std.mem.eql(u8, &buf, &bad), eqlComptime(&bad, comptime brk: { var buf_copy_: [size]u8 = undefined; @memset(&buf_copy_, 'a'); break :brk buf_copy_; })); } } test "eqlComptimeUTF16" { try std.testing.expectEqual(eqlComptimeUTF16(toUTF16Literal("bun-darwin-aarch64.zip"), "bun-darwin-aarch64.zip"), true); const sizes = [_]u16{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 23, 22, 24 }; inline for (sizes) |size| { var buf: [size]u16 = undefined; @memset(&buf, @as(u8, 'a')); var buf_copy: [size]u16 = undefined; @memset(&buf_copy, @as(u8, 'a')); var bad: [size]u16 = undefined; @memset(&bad, @as(u16, 'b')); try std.testing.expectEqual(std.mem.eql(u16, &buf, &buf_copy), eqlComptimeUTF16(&buf, comptime &brk: { var buf_copy_: [size]u8 = undefined; @memset(&buf_copy_, @as(u8, 'a')); break :brk buf_copy_; })); try std.testing.expectEqual(std.mem.eql(u16, &buf, &bad), eqlComptimeUTF16(&bad, comptime &brk: { var buf_copy_: [size]u8 = undefined; @memset(&buf_copy_, @as(u8, 'a')); break :brk buf_copy_; })); } } test "copyLowercase" { { var in = "Hello, World!"; var out = std.mem.zeroes([in.len]u8); var out_ = copyLowercase(in, &out); try std.testing.expectEqualStrings(out_, "hello, world!"); } { var in = "_ListCache"; var out = std.mem.zeroes([in.len]u8); var out_ = copyLowercase(in, &out); try std.testing.expectEqualStrings(out_, "_listcache"); } } test "StringOrTinyString" { const correct: string = "helloooooooo"; const big = "wawaweewaverylargeihaveachairwawaweewaverylargeihaveachairwawaweewaverylargeihaveachairwawaweewaverylargeihaveachair"; var str = StringOrTinyString.init(correct); try std.testing.expectEqualStrings(correct, str.slice()); str = StringOrTinyString.init(big); try std.testing.expectEqualStrings(big, str.slice()); try std.testing.expect(@sizeOf(StringOrTinyString) == 32); } test "StringOrTinyString Lowercase" { const correct: string = "HELLO!!!!!"; var str = StringOrTinyString.initLowerCase(correct); try std.testing.expectEqualStrings("hello!!!!!", str.slice()); } /// Copy a string into a buffer /// Return the copied version pub fn copy(buf: []u8, src: []const u8) []const u8 { const len = @min(buf.len, src.len); if (len > 0) @memcpy(buf[0..len], src[0..len]); return buf[0..len]; } /// startsWith except it checks for non-empty strings pub fn hasPrefix(self: string, str: string) bool { return str.len > 0 and startsWith(self, str); } pub fn startsWith(self: string, str: string) bool { if (str.len > self.len) { return false; } return eqlLong(self[0..str.len], str, false); } pub inline fn endsWith(self: string, str: string) bool { return str.len == 0 or @call(.always_inline, std.mem.endsWith, .{ u8, self, str }); } pub inline fn endsWithComptime(self: string, comptime str: anytype) bool { return self.len >= str.len and eqlComptimeIgnoreLen(self[self.len - str.len .. self.len], comptime str); } pub inline fn startsWithChar(self: string, char: u8) bool { return self.len > 0 and self[0] == char; } pub inline fn endsWithChar(self: string, char: u8) bool { return self.len == 0 or self[self.len - 1] == char; } pub fn withoutTrailingSlash(this: string) []const u8 { var href = this; while (href.len > 1 and href[href.len - 1] == '/') { href.len -= 1; } return href; } pub fn withTrailingSlash(dir: string, in: string) []const u8 { if (comptime Environment.allow_assert) std.debug.assert(bun.isSliceInBuffer(dir, in)); return in[0..@min(strings.withoutTrailingSlash(in[0..@min(dir.len + 1, in.len)]).len + 1, in.len)]; } pub fn withoutLeadingSlash(this: string) []const u8 { return std.mem.trimLeft(u8, this, "/"); } pub fn endsWithAny(self: string, str: string) bool { const end = self[self.len - 1]; for (str) |char| { if (char == end) { return true; } } return false; } // Formats a string to be safe to output in a Github action. // - Encodes "\n" as "%0A" to support multi-line strings. // https://github.com/actions/toolkit/issues/193#issuecomment-605394935 // - Strips ANSI output as it will appear malformed. pub fn githubActionWriter(writer: anytype, self: string) !void { var offset: usize = 0; const end = @as(u32, @truncate(self.len)); while (offset < end) { if (indexOfNewlineOrNonASCIIOrANSI(self, @as(u32, @truncate(offset)))) |i| { const byte = self[i]; if (byte > 0x7F) { offset += @max(wtf8ByteSequenceLength(byte), 1); continue; } if (i > 0) { try writer.writeAll(self[offset..i]); } var n: usize = 1; if (byte == '\n') { try writer.writeAll("%0A"); } else if (i + 1 < end) { const next = self[i + 1]; if (byte == '\r' and next == '\n') { n += 1; try writer.writeAll("%0A"); } else if (byte == '\x1b' and next == '[') { n += 1; if (i + 2 < end) { const remain = self[(i + 2)..@min(i + 5, end)]; if (indexOfChar(remain, 'm')) |j| { n += j + 1; } } } } offset = i + n; } else { try writer.writeAll(self[offset..end]); break; } } } pub const GithubActionFormatter = struct { text: string, pub fn format(this: GithubActionFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { try githubActionWriter(writer, this.text); } }; pub fn githubAction(self: string) strings.GithubActionFormatter { return GithubActionFormatter{ .text = self, }; } pub fn quotedWriter(writer: anytype, self: string) !void { var remain = self; if (strings.containsNewlineOrNonASCIIOrQuote(remain)) { try bun.js_printer.writeJSONString(self, @TypeOf(writer), writer, strings.Encoding.utf8); } else { try writer.writeAll("\""); try writer.writeAll(self); try writer.writeAll("\""); } } pub const QuotedFormatter = struct { text: []const u8, pub fn format(this: QuotedFormatter, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { try strings.quotedWriter(writer, this.text); } }; pub fn quotedAlloc(allocator: std.mem.Allocator, self: string) !string { var count: usize = 0; for (self) |char| { count += @intFromBool(char == '"'); } if (count == 0) { return allocator.dupe(u8, self); } var i: usize = 0; var out = try allocator.alloc(u8, self.len + count); for (self) |char| { if (char == '"') { out[i] = '\\'; i += 1; } out[i] = char; i += 1; } return out; } pub fn eqlAnyComptime(self: string, comptime list: []const string) bool { inline for (list) |item| { if (eqlComptimeCheckLenWithType(u8, self, item, true)) return true; } return false; } /// Count the occurrences of a character in an ASCII byte array /// uses SIMD pub fn countChar(self: string, char: u8) usize { var total: usize = 0; var remaining = self; const splatted: AsciiVector = @splat(char); while (remaining.len >= 16) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; const cmp = @popCount(@as(@Vector(ascii_vector_size, u1), @bitCast(vec == splatted))); total += @as(usize, @reduce(.Add, cmp)); remaining = remaining[ascii_vector_size..]; } while (remaining.len > 0) { total += @as(usize, @intFromBool(remaining[0] == char)); remaining = remaining[1..]; } return total; } test "countChar" { try std.testing.expectEqual(countChar("hello there", ' '), 1); try std.testing.expectEqual(countChar("hello;;;there", ';'), 3); try std.testing.expectEqual(countChar("hello there", 'z'), 0); try std.testing.expectEqual(countChar("hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there ", ' '), 28); try std.testing.expectEqual(countChar("hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there ", 'z'), 0); try std.testing.expectEqual(countChar("hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there hello there", ' '), 27); } pub fn endsWithAnyComptime(self: string, comptime str: string) bool { if (comptime str.len < 10) { const last = self[self.len - 1]; inline for (str) |char| { if (char == last) { return true; } } return false; } else { return endsWithAny(self, str); } } pub fn eql(self: string, other: anytype) bool { if (self.len != other.len) return false; if (comptime @TypeOf(other) == *string) { return eql(self, other.*); } for (self, 0..) |c, i| { if (other[i] != c) return false; } return true; } pub inline fn eqlInsensitive(self: string, other: anytype) bool { return std.ascii.eqlIgnoreCase(self, other); } pub fn eqlComptime(self: string, comptime alt: anytype) bool { return eqlComptimeCheckLenWithType(u8, self, alt, true); } pub fn eqlComptimeUTF16(self: []const u16, comptime alt: []const u8) bool { return eqlComptimeCheckLenWithType(u16, self, comptime toUTF16Literal(alt), true); } pub fn eqlComptimeIgnoreLen(self: string, comptime alt: anytype) bool { return eqlComptimeCheckLenWithType(u8, self, alt, false); } pub fn hasPrefixComptime(self: string, comptime alt: anytype) bool { return self.len >= alt.len and eqlComptimeCheckLenWithType(u8, self[0..alt.len], alt, false); } pub fn hasSuffixComptime(self: string, comptime alt: anytype) bool { return self.len >= alt.len and eqlComptimeCheckLenWithType(u8, self[self.len - alt.len ..], alt, false); } inline fn eqlComptimeCheckLenWithKnownType(comptime Type: type, a: []const Type, comptime b: []const Type, comptime check_len: bool) bool { @setEvalBranchQuota(9999); if (comptime check_len) { if (comptime b.len == 0) { return a.len == 0; } switch (a.len) { b.len => {}, else => return false, } } const len = comptime b.len; comptime var dword_length = b.len >> if (Environment.isNative) 3 else 2; const slice = b; const divisor = comptime @sizeOf(Type); comptime var b_ptr: usize = 0; inline while (dword_length > 0) : (dword_length -= 1) { if (@as(usize, @bitCast(a[b_ptr..][0 .. @sizeOf(usize) / divisor].*)) != comptime @as(usize, @bitCast((slice[b_ptr..])[0 .. @sizeOf(usize) / divisor].*))) return false; comptime b_ptr += @sizeOf(usize); if (comptime b_ptr == b.len) return true; } if (comptime @sizeOf(usize) == 8) { if (comptime (len & 4) != 0) { if (@as(u32, @bitCast(a[b_ptr..][0 .. @sizeOf(u32) / divisor].*)) != comptime @as(u32, @bitCast((slice[b_ptr..])[0 .. @sizeOf(u32) / divisor].*))) return false; comptime b_ptr += @sizeOf(u32); if (comptime b_ptr == b.len) return true; } } if (comptime (len & 2) != 0) { if (@as(u16, @bitCast(a[b_ptr..][0 .. @sizeOf(u16) / divisor].*)) != comptime @as(u16, @bitCast(slice[b_ptr .. b_ptr + (@sizeOf(u16) / divisor)].*))) return false; comptime b_ptr += @sizeOf(u16); if (comptime b_ptr == b.len) return true; } if ((comptime (len & 1) != 0) and a[b_ptr] != comptime b[b_ptr]) return false; return true; } /// Check if two strings are equal with one of the strings being a comptime-known value /// /// strings.eqlComptime(input, "hello world"); /// strings.eqlComptime(input, "hai"); pub inline fn eqlComptimeCheckLenWithType(comptime Type: type, a: []const Type, comptime b: anytype, comptime check_len: bool) bool { return eqlComptimeCheckLenWithKnownType(comptime Type, a, if (@typeInfo(@TypeOf(b)) != .Pointer) &b else b, comptime check_len); } pub fn eqlCaseInsensitiveASCIIIgnoreLength( a: string, b: string, ) bool { return eqlCaseInsensitiveASCII(a, b, false); } pub fn eqlCaseInsensitiveASCIIICheckLength( a: string, b: string, ) bool { return eqlCaseInsensitiveASCII(a, b, true); } pub fn eqlCaseInsensitiveASCII(a: string, b: string, comptime check_len: bool) bool { if (comptime check_len) { if (a.len != b.len) return false; if (a.len == 0) return true; } std.debug.assert(b.len > 0); std.debug.assert(a.len > 0); return bun.C.strncasecmp(a.ptr, b.ptr, a.len) == 0; } pub fn eqlLong(a_str: string, b_str: string, comptime check_len: bool) bool { const len = b_str.len; if (comptime check_len) { if (len == 0) { return a_str.len == 0; } if (a_str.len != len) { return false; } } else { if (comptime Environment.allow_assert) std.debug.assert(b_str.len == a_str.len); } const end = b_str.ptr + len; var a = a_str.ptr; var b = b_str.ptr; if (a == b) return true; { var dword_length = len >> 3; while (dword_length > 0) : (dword_length -= 1) { if (@as(usize, @bitCast(a[0..@sizeOf(usize)].*)) != @as(usize, @bitCast(b[0..@sizeOf(usize)].*))) return false; b += @sizeOf(usize); if (b == end) return true; a += @sizeOf(usize); } } if (comptime @sizeOf(usize) == 8) { if ((len & 4) != 0) { if (@as(u32, @bitCast(a[0..@sizeOf(u32)].*)) != @as(u32, @bitCast(b[0..@sizeOf(u32)].*))) return false; b += @sizeOf(u32); if (b == end) return true; a += @sizeOf(u32); } } if ((len & 2) != 0) { if (@as(u16, @bitCast(a[0..@sizeOf(u16)].*)) != @as(u16, @bitCast(b[0..@sizeOf(u16)].*))) return false; b += @sizeOf(u16); if (b == end) return true; a += @sizeOf(u16); } if (((len & 1) != 0) and a[0] != b[0]) return false; return true; } pub inline fn append(allocator: std.mem.Allocator, self: string, other: string) ![]u8 { var buf = try allocator.alloc(u8, self.len + other.len); if (self.len > 0) @memcpy(buf[0..self.len], self); if (other.len > 0) @memcpy(buf[self.len..][0..other.len], other); return buf; } pub inline fn append3(allocator: std.mem.Allocator, self: string, other: string, third: string) ![]u8 { var buf = try allocator.alloc(u8, self.len + other.len + third.len); if (self.len > 0) @memcpy(buf[0..self.len], self); if (other.len > 0) @memcpy(buf[self.len..][0..other.len], other); if (third.len > 0) @memcpy(buf[self.len + other.len ..][0..third.len], third); return buf; } pub inline fn joinBuf(out: []u8, parts: anytype, comptime parts_len: usize) []u8 { var remain = out; var count: usize = 0; comptime var i: usize = 0; inline while (i < parts_len) : (i += 1) { const part = parts[i]; bun.copy(u8, remain, part); remain = remain[part.len..]; count += part.len; } return out[0..count]; } pub fn index(self: string, str: string) i32 { if (strings.indexOf(self, str)) |i| { return @as(i32, @intCast(i)); } else { return -1; } } pub fn eqlUtf16(comptime self: string, other: []const u16) bool { if (self.len != other.len) return false; if (self.len == 0) return true; return bun.C.memcmp(bun.cast([*]const u8, self.ptr), bun.cast([*]const u8, other.ptr), self.len * @sizeOf(u16)) == 0; } pub fn toUTF8Alloc(allocator: std.mem.Allocator, js: []const u16) !string { return try toUTF8AllocWithType(allocator, []const u16, js); } pub inline fn appendUTF8MachineWordToUTF16MachineWord(output: *[@sizeOf(usize) / 2]u16, input: *const [@sizeOf(usize) / 2]u8) void { output[0 .. @sizeOf(usize) / 2].* = @as( [4]u16, @bitCast(@as( @Vector(4, u16), @as(@Vector(4, u8), @bitCast(input[0 .. @sizeOf(usize) / 2].*)), )), ); } pub inline fn copyU8IntoU16(output_: []u16, input_: []const u8) void { var output = output_; var input = input_; if (comptime Environment.allow_assert) std.debug.assert(input.len <= output.len); // https://zig.godbolt.org/z/9rTn1orcY var input_ptr = input.ptr; var output_ptr = output.ptr; const last_input_ptr = input_ptr + @min(input.len, output.len); while (last_input_ptr != input_ptr) { output_ptr[0] = input_ptr[0]; output_ptr += 1; input_ptr += 1; } } pub fn copyU8IntoU16WithAlignment(comptime alignment: u21, output_: []align(alignment) u16, input_: []const u8) void { var output = output_; var input = input_; const word = @sizeOf(usize) / 2; if (comptime Environment.allow_assert) std.debug.assert(input.len <= output.len); // un-aligned data access is slow // so we attempt to align the data while (!std.mem.isAligned(@intFromPtr(output.ptr), @alignOf(u16)) and input.len >= word) { output[0] = input[0]; output = output[1..]; input = input[1..]; } if (std.mem.isAligned(@intFromPtr(output.ptr), @alignOf(u16)) and input.len > 0) { copyU8IntoU16(@as([*]u16, @alignCast(output.ptr))[0..output.len], input); return; } for (input, 0..) |c, i| { output[i] = c; } } // pub inline fn copy(output_: []u8, input_: []const u8) void { // var output = output_; // var input = input_; // if (comptime Environment.allow_assert) std.debug.assert(input.len <= output.len); // if (input.len > @sizeOf(usize) * 4) { // comptime var i: usize = 0; // inline while (i < 4) : (i += 1) { // appendUTF8MachineWord(output[i * @sizeOf(usize) ..][0..@sizeOf(usize)], input[i * @sizeOf(usize) ..][0..@sizeOf(usize)]); // } // output = output[4 * @sizeOf(usize) ..]; // input = input[4 * @sizeOf(usize) ..]; // } // while (input.len >= @sizeOf(usize)) { // appendUTF8MachineWord(output[0..@sizeOf(usize)], input[0..@sizeOf(usize)]); // output = output[@sizeOf(usize)..]; // input = input[@sizeOf(usize)..]; // } // for (input) |c, i| { // output[i] = c; // } // } pub inline fn copyU16IntoU8(output_: []u8, comptime InputType: type, input_: InputType) void { if (comptime Environment.allow_assert) std.debug.assert(input_.len <= output_.len); var output = output_; var input = input_; if (comptime Environment.allow_assert) std.debug.assert(input.len <= output.len); // https://zig.godbolt.org/z/9rTn1orcY const group = @as(usize, 16); // end at the last group of 16 bytes var input_ptr = input.ptr; var output_ptr = output.ptr; if (comptime Environment.enableSIMD) { const end_len = (@min(input.len, output.len) & ~(group - 1)); const last_vector_ptr = input.ptr + end_len; while (last_vector_ptr != input_ptr) { const input_vec1: @Vector(group, u16) = input_ptr[0..group].*; inline for (0..group) |i| { output_ptr[i] = @as(u8, @truncate(input_vec1[i])); } output_ptr += group; input_ptr += group; } input.len -= end_len; output.len -= end_len; } const last_input_ptr = input_ptr + @min(input.len, output.len); while (last_input_ptr != input_ptr) { output_ptr[0] = @as(u8, @truncate(input_ptr[0])); output_ptr += 1; input_ptr += 1; } } const strings = @This(); pub fn copyLatin1IntoASCII(dest: []u8, src: []const u8) void { var remain = src; var to = dest; const non_ascii_offset = strings.firstNonASCII(remain) orelse @as(u32, @truncate(remain.len)); if (non_ascii_offset > 0) { @memcpy(to[0..non_ascii_offset], remain[0..non_ascii_offset]); remain = remain[non_ascii_offset..]; to = to[non_ascii_offset..]; // ascii fast path if (remain.len == 0) { return; } } if (to.len >= 16 and bun.Environment.enableSIMD) { const vector_size = 16; // https://zig.godbolt.org/z/qezsY8T3W var remain_in_u64 = remain[0 .. remain.len - (remain.len % vector_size)]; var to_in_u64 = to[0 .. to.len - (to.len % vector_size)]; var remain_as_u64 = std.mem.bytesAsSlice(u64, remain_in_u64); var to_as_u64 = std.mem.bytesAsSlice(u64, to_in_u64); const end_vector_len = @min(remain_as_u64.len, to_as_u64.len); remain_as_u64 = remain_as_u64[0..end_vector_len]; to_as_u64 = to_as_u64[0..end_vector_len]; const end_ptr = remain_as_u64.ptr + remain_as_u64.len; // using the pointer instead of the length is super important for the codegen while (end_ptr != remain_as_u64.ptr) { const buf = remain_as_u64[0]; // this gets auto-vectorized const mask = @as(u64, 0x7f7f7f7f7f7f7f7f); to_as_u64[0] = buf & mask; remain_as_u64 = remain_as_u64[1..]; to_as_u64 = to_as_u64[1..]; } remain = remain[remain_in_u64.len..]; to = to[to_in_u64.len..]; } for (to) |*to_byte| { to_byte.* = @as(u8, @as(u7, @truncate(remain[0]))); remain = remain[1..]; } } /// Convert a UTF-8 string to a UTF-16 string IF there are any non-ascii characters /// If there are no non-ascii characters, this returns null /// This is intended to be used for strings that go to JavaScript pub fn toUTF16Alloc(allocator: std.mem.Allocator, bytes: []const u8, comptime fail_if_invalid: bool) !?[]u16 { if (strings.firstNonASCII(bytes)) |i| { const output_: ?std.ArrayList(u16) = if (comptime bun.FeatureFlags.use_simdutf) simd: { const trimmed = bun.simdutf.trim.utf8(bytes); if (trimmed.len == 0) break :simd null; const out_length = bun.simdutf.length.utf16.from.utf8.le(trimmed); if (out_length == 0) break :simd null; var out = try allocator.alloc(u16, out_length); log("toUTF16 {d} UTF8 -> {d} UTF16", .{ bytes.len, out_length }); // avoid `.with_errors.le()` due to https://github.com/simdutf/simdutf/issues/213 switch (bun.simdutf.convert.utf8.to.utf16.le(trimmed, out)) { 0 => { if (comptime fail_if_invalid) { allocator.free(out); return error.InvalidByteSequence; } break :simd .{ .items = out[0..i], .capacity = out.len, .allocator = allocator, }; }, else => return out, } } else null; var output = output_ orelse fallback: { var list = try std.ArrayList(u16).initCapacity(allocator, i + 2); list.items.len = i; strings.copyU8IntoU16(list.items, bytes[0..i]); break :fallback list; }; errdefer output.deinit(); var remaining = bytes[i..]; { const sequence: [4]u8 = switch (remaining.len) { 0 => unreachable, 1 => [_]u8{ remaining[0], 0, 0, 0 }, 2 => [_]u8{ remaining[0], remaining[1], 0, 0 }, 3 => [_]u8{ remaining[0], remaining[1], remaining[2], 0 }, else => remaining[0..4].*, }; const replacement = strings.convertUTF8BytesIntoUTF16(&sequence); if (comptime fail_if_invalid) { if (replacement.fail) { if (comptime Environment.allow_assert) std.debug.assert(replacement.code_point == unicode_replacement); return error.InvalidByteSequence; } } remaining = remaining[@max(replacement.len, 1)..]; //#define U16_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2) switch (replacement.code_point) { 0...0xffff => |c| { try output.append(@as(u16, @intCast(c))); }, else => |c| { try output.appendSlice(&[_]u16{ strings.u16Lead(c), strings.u16Trail(c) }); }, } } while (strings.firstNonASCII(remaining)) |j| { const end = output.items.len; try output.ensureUnusedCapacity(j); output.items.len += j; strings.copyU8IntoU16(output.items[end..][0..j], remaining[0..j]); remaining = remaining[j..]; const sequence: [4]u8 = switch (remaining.len) { 0 => unreachable, 1 => [_]u8{ remaining[0], 0, 0, 0 }, 2 => [_]u8{ remaining[0], remaining[1], 0, 0 }, 3 => [_]u8{ remaining[0], remaining[1], remaining[2], 0 }, else => remaining[0..4].*, }; const replacement = strings.convertUTF8BytesIntoUTF16(&sequence); if (comptime fail_if_invalid) { if (replacement.fail) { if (comptime Environment.allow_assert) std.debug.assert(replacement.code_point == unicode_replacement); return error.InvalidByteSequence; } } remaining = remaining[@max(replacement.len, 1)..]; //#define U16_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2) switch (replacement.code_point) { 0...0xffff => |c| { try output.append(@as(u16, @intCast(c))); }, else => |c| { try output.appendSlice(&[_]u16{ strings.u16Lead(c), strings.u16Trail(c) }); }, } } if (remaining.len > 0) { try output.ensureTotalCapacityPrecise(output.items.len + remaining.len); output.items.len += remaining.len; strings.copyU8IntoU16(output.items[output.items.len - remaining.len ..], remaining); } return output.items; } return null; } pub fn toUTF16AllocNoTrim(allocator: std.mem.Allocator, bytes: []const u8, comptime fail_if_invalid: bool) !?[]u16 { if (strings.firstNonASCII(bytes)) |i| { const output_: ?std.ArrayList(u16) = if (comptime bun.FeatureFlags.use_simdutf) simd: { const out_length = bun.simdutf.length.utf16.from.utf8.le(bytes); if (out_length == 0) break :simd null; var out = try allocator.alloc(u16, out_length); log("toUTF16 {d} UTF8 -> {d} UTF16", .{ bytes.len, out_length }); // avoid `.with_errors.le()` due to https://github.com/simdutf/simdutf/issues/213 switch (bun.simdutf.convert.utf8.to.utf16.le(bytes, out)) { 0 => { if (comptime fail_if_invalid) { allocator.free(out); return error.InvalidByteSequence; } break :simd .{ .items = out[0..i], .capacity = out.len, .allocator = allocator, }; }, else => return out, } } else null; var output = output_ orelse fallback: { var list = try std.ArrayList(u16).initCapacity(allocator, i + 2); list.items.len = i; strings.copyU8IntoU16(list.items, bytes[0..i]); break :fallback list; }; errdefer output.deinit(); var remaining = bytes[i..]; { const sequence: [4]u8 = switch (remaining.len) { 0 => unreachable, 1 => [_]u8{ remaining[0], 0, 0, 0 }, 2 => [_]u8{ remaining[0], remaining[1], 0, 0 }, 3 => [_]u8{ remaining[0], remaining[1], remaining[2], 0 }, else => remaining[0..4].*, }; const replacement = strings.convertUTF8BytesIntoUTF16(&sequence); if (comptime fail_if_invalid) { if (replacement.fail) { if (comptime Environment.allow_assert) std.debug.assert(replacement.code_point == unicode_replacement); return error.InvalidByteSequence; } } remaining = remaining[@max(replacement.len, 1)..]; //#define U16_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2) switch (replacement.code_point) { 0...0xffff => |c| { try output.append(@as(u16, @intCast(c))); }, else => |c| { try output.appendSlice(&[_]u16{ strings.u16Lead(c), strings.u16Trail(c) }); }, } } while (strings.firstNonASCII(remaining)) |j| { const end = output.items.len; try output.ensureUnusedCapacity(j); output.items.len += j; strings.copyU8IntoU16(output.items[end..][0..j], remaining[0..j]); remaining = remaining[j..]; const sequence: [4]u8 = switch (remaining.len) { 0 => unreachable, 1 => [_]u8{ remaining[0], 0, 0, 0 }, 2 => [_]u8{ remaining[0], remaining[1], 0, 0 }, 3 => [_]u8{ remaining[0], remaining[1], remaining[2], 0 }, else => remaining[0..4].*, }; const replacement = strings.convertUTF8BytesIntoUTF16(&sequence); if (comptime fail_if_invalid) { if (replacement.fail) { if (comptime Environment.allow_assert) std.debug.assert(replacement.code_point == unicode_replacement); return error.InvalidByteSequence; } } remaining = remaining[@max(replacement.len, 1)..]; //#define U16_LENGTH(c) ((uint32_t)(c)<=0xffff ? 1 : 2) switch (replacement.code_point) { 0...0xffff => |c| { try output.append(@as(u16, @intCast(c))); }, else => |c| { try output.appendSlice(&[_]u16{ strings.u16Lead(c), strings.u16Trail(c) }); }, } } if (remaining.len > 0) { try output.ensureTotalCapacityPrecise(output.items.len + remaining.len); output.items.len += remaining.len; strings.copyU8IntoU16(output.items[output.items.len - remaining.len ..], remaining); } return output.items; } return null; } pub fn utf16CodepointWithFFFD(comptime Type: type, input: Type) UTF16Replacement { const c0 = @as(u21, input[0]); if (c0 & ~@as(u21, 0x03ff) == 0xd800) { // surrogate pair if (input.len == 1) return .{ .len = 1, }; //error.DanglingSurrogateHalf; const c1 = @as(u21, input[1]); if (c1 & ~@as(u21, 0x03ff) != 0xdc00) if (input.len == 1) { return .{ .len = 1, }; } else { return .{ .fail = true, .len = 1, .code_point = unicode_replacement, }; }; // return error.ExpectedSecondSurrogateHalf; return .{ .len = 2, .code_point = 0x10000 + (((c0 & 0x03ff) << 10) | (c1 & 0x03ff)) }; } else if (c0 & ~@as(u21, 0x03ff) == 0xdc00) { // return error.UnexpectedSecondSurrogateHalf; return .{ .fail = true, .len = 1, .code_point = unicode_replacement }; } else { return .{ .code_point = c0, .len = 1 }; } } pub fn utf16Codepoint(comptime Type: type, input: Type) UTF16Replacement { const c0 = @as(u21, input[0]); if (c0 & ~@as(u21, 0x03ff) == 0xd800) { // surrogate pair if (input.len == 1) return .{ .len = 1, }; //error.DanglingSurrogateHalf; const c1 = @as(u21, input[1]); if (c1 & ~@as(u21, 0x03ff) != 0xdc00) if (input.len == 1) return .{ .len = 1, }; // return error.ExpectedSecondSurrogateHalf; return .{ .len = 2, .code_point = 0x10000 + (((c0 & 0x03ff) << 10) | (c1 & 0x03ff)) }; } else if (c0 & ~@as(u21, 0x03ff) == 0xdc00) { // return error.UnexpectedSecondSurrogateHalf; return .{ .len = 1 }; } else { return .{ .code_point = c0, .len = 1 }; } } pub fn fromWPath(buf: []u8, utf16: []const u16) [:0]const u8 { std.debug.assert(buf.len > 0); const encode_into_result = copyUTF16IntoUTF8(buf[0 .. buf.len - 1], []const u16, utf16, false); std.debug.assert(encode_into_result.written < buf.len); buf[encode_into_result.written] = 0; return buf[0..encode_into_result.written :0]; } pub fn toWPath(wbuf: []u16, utf8: []const u8) [:0]const u16 { std.debug.assert(wbuf.len > 0); var result = bun.simdutf.convert.utf8.to.utf16.with_errors.le( utf8, wbuf[0..wbuf.len -| 1], ); // TODO: error handling // if (result.status == .surrogate) { // } return wbuf[0..result.count :0]; } pub fn convertUTF16ToUTF8(list_: std.ArrayList(u8), comptime Type: type, utf16: Type) !std.ArrayList(u8) { var list = list_; var result = bun.simdutf.convert.utf16.to.utf8.with_errors.le( utf16, list.items.ptr[0..list.capacity], ); if (result.status == .surrogate) { // Slow path: there was invalid UTF-16, so we need to convert it without simdutf. return toUTF8ListWithTypeBun(list, Type, utf16); } list.items.len = result.count; return list; } pub fn toUTF8AllocWithType(allocator: std.mem.Allocator, comptime Type: type, utf16: Type) ![]u8 { if (bun.FeatureFlags.use_simdutf and comptime Type == []const u16) { const length = bun.simdutf.length.utf8.from.utf16.le(utf16); // add 16 bytes of padding for SIMDUTF var list = try std.ArrayList(u8).initCapacity(allocator, length + 16); list = try convertUTF16ToUTF8(list, Type, utf16); return list.items; } var list = try std.ArrayList(u8).initCapacity(allocator, utf16.len); list = try toUTF8ListWithType(list, Type, utf16); return list.items; } pub fn toUTF8ListWithType(list_: std.ArrayList(u8), comptime Type: type, utf16: Type) !std.ArrayList(u8) { if (bun.FeatureFlags.use_simdutf and comptime Type == []const u16) { var list = list_; const length = bun.simdutf.length.utf8.from.utf16.le(utf16); try list.ensureTotalCapacityPrecise(length + 16); const buf = try convertUTF16ToUTF8(list, Type, utf16); if (Environment.allow_assert) { std.debug.assert(buf.items.len == length); } return buf; } return toUTF8ListWithTypeBun(list_, Type, utf16); } pub fn toUTF8FromLatin1(allocator: std.mem.Allocator, latin1: []const u8) !?std.ArrayList(u8) { if (bun.JSC.is_bindgen) unreachable; if (isAllASCII(latin1)) return null; var list = try std.ArrayList(u8).initCapacity(allocator, latin1.len); return try allocateLatin1IntoUTF8WithList(list, 0, []const u8, latin1); } pub fn toUTF8ListWithTypeBun(list_: std.ArrayList(u8), comptime Type: type, utf16: Type) !std.ArrayList(u8) { var list = list_; var utf16_remaining = utf16; while (firstNonASCII16(Type, utf16_remaining)) |i| { const to_copy = utf16_remaining[0..i]; utf16_remaining = utf16_remaining[i..]; const replacement = utf16CodepointWithFFFD(Type, utf16_remaining); utf16_remaining = utf16_remaining[replacement.len..]; const count: usize = replacement.utf8Width(); if (comptime Environment.isNative) { try list.ensureTotalCapacityPrecise(i + count + list.items.len + @as(usize, @intFromFloat((@as(f64, @floatFromInt(@as(u52, @truncate(utf16_remaining.len)))) * 1.2)))); } else { try list.ensureTotalCapacityPrecise(i + count + list.items.len + utf16_remaining.len + 4); } list.items.len += i; copyU16IntoU8( list.items[list.items.len - i ..], Type, to_copy, ); list.items.len += count; _ = encodeWTF8RuneT( list.items.ptr[list.items.len - count .. list.items.len - count + 4][0..4], u32, @as(u32, replacement.code_point), ); } if (utf16_remaining.len > 0) { try list.ensureTotalCapacityPrecise(utf16_remaining.len + list.items.len); const old_len = list.items.len; list.items.len += utf16_remaining.len; copyU16IntoU8(list.items[old_len..], Type, utf16_remaining); } log("UTF16 {d} -> {d} UTF8", .{ utf16.len, list.items.len }); return list; } pub const EncodeIntoResult = struct { read: u32 = 0, written: u32 = 0, }; pub fn allocateLatin1IntoUTF8(allocator: std.mem.Allocator, comptime Type: type, latin1_: Type) ![]u8 { if (comptime bun.FeatureFlags.latin1_is_now_ascii) { var out = try allocator.alloc(u8, latin1_.len); @memcpy(out[0..latin1_.len], latin1_); return out; } var list = try std.ArrayList(u8).initCapacity(allocator, latin1_.len); var foo = try allocateLatin1IntoUTF8WithList(list, 0, Type, latin1_); return try foo.toOwnedSlice(); } pub fn allocateLatin1IntoUTF8WithList(list_: std.ArrayList(u8), offset_into_list: usize, comptime Type: type, latin1_: Type) !std.ArrayList(u8) { var latin1 = latin1_; var i: usize = offset_into_list; var list = list_; try list.ensureUnusedCapacity(latin1.len); while (latin1.len > 0) { if (comptime Environment.allow_assert) std.debug.assert(i < list.capacity); var buf = list.items.ptr[i..list.capacity]; inner: { var count = latin1.len / ascii_vector_size; while (count > 0) : (count -= 1) { const vec: AsciiVector = latin1[0..ascii_vector_size].*; if (@reduce(.Max, vec) > 127) { const Int = u64; const size = @sizeOf(Int); // zig or LLVM doesn't do @ctz nicely with SIMD if (comptime ascii_vector_size >= 8) { { const bytes = @as(Int, @bitCast(latin1[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) std.debug.assert(latin1[first_set_byte] >= 127); buf[0..size].* = @as([size]u8, @bitCast(bytes)); buf = buf[first_set_byte..]; latin1 = latin1[first_set_byte..]; break :inner; } buf[0..size].* = @as([size]u8, @bitCast(bytes)); latin1 = latin1[size..]; buf = buf[size..]; } if (comptime ascii_vector_size >= 16) { const bytes = @as(Int, @bitCast(latin1[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) std.debug.assert(latin1[first_set_byte] >= 127); buf[0..size].* = @as([size]u8, @bitCast(bytes)); buf = buf[first_set_byte..]; latin1 = latin1[first_set_byte..]; break :inner; } } } unreachable; } buf[0..ascii_vector_size].* = @as([ascii_vector_size]u8, @bitCast(vec))[0..ascii_vector_size].*; latin1 = latin1[ascii_vector_size..]; buf = buf[ascii_vector_size..]; } while (latin1.len >= 8) { const Int = u64; const size = @sizeOf(Int); const bytes = @as(Int, @bitCast(latin1[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) std.debug.assert(latin1[first_set_byte] >= 127); buf[0..size].* = @as([size]u8, @bitCast(bytes)); latin1 = latin1[first_set_byte..]; buf = buf[first_set_byte..]; break :inner; } buf[0..size].* = @as([size]u8, @bitCast(bytes)); latin1 = latin1[size..]; buf = buf[size..]; } { if (comptime Environment.allow_assert) std.debug.assert(latin1.len < 8); const end = latin1.ptr + latin1.len; while (latin1.ptr != end and latin1[0] < 128) { buf[0] = latin1[0]; buf = buf[1..]; latin1 = latin1[1..]; } } } while (latin1.len > 0 and latin1[0] > 127) { i = @intFromPtr(buf.ptr) - @intFromPtr(list.items.ptr); list.items.len = i; try list.ensureUnusedCapacity(2 + latin1.len); buf = list.items.ptr[i..list.capacity]; buf[0..2].* = latin1ToCodepointBytesAssumeNotASCII(latin1[0]); latin1 = latin1[1..]; buf = buf[2..]; } i = @intFromPtr(buf.ptr) - @intFromPtr(list.items.ptr); list.items.len = i; } log("Latin1 {d} -> UTF8 {d}", .{ latin1_.len, i }); return list; } pub const UTF16Replacement = struct { code_point: u32 = unicode_replacement, len: u3 = 0, /// Explicit fail boolean to distinguish between a Unicode Replacement Codepoint /// that was already in there /// and a genuine error. fail: bool = false, pub inline fn utf8Width(replacement: UTF16Replacement) usize { return switch (replacement.code_point) { 0...0x7F => 1, (0x7F + 1)...0x7FF => 2, (0x7FF + 1)...0xFFFF => 3, else => 4, }; } }; // This variation matches WebKit behavior. pub fn convertUTF8BytesIntoUTF16(sequence: *const [4]u8) UTF16Replacement { if (comptime Environment.allow_assert) std.debug.assert(sequence[0] > 127); const len = wtf8ByteSequenceLengthWithInvalid(sequence[0]); switch (len) { 2 => { if (comptime Environment.allow_assert) { std.debug.assert(sequence[0] >= 0xC0); std.debug.assert(sequence[0] <= 0xDF); } if (sequence[1] < 0x80 or sequence[1] > 0xBF) { return .{ .len = 1, .fail = true }; } return .{ .len = len, .code_point = ((@as(u32, sequence[0]) << 6) + @as(u32, sequence[1])) - 0x00003080 }; }, 3 => { if (comptime Environment.allow_assert) { std.debug.assert(sequence[0] >= 0xE0); std.debug.assert(sequence[0] <= 0xEF); } switch (sequence[0]) { 0xE0 => { if (sequence[1] < 0xA0 or sequence[1] > 0xBF) { return .{ .len = 1, .fail = true }; } }, 0xED => { if (sequence[1] < 0x80 or sequence[1] > 0x9F) { return .{ .len = 1, .fail = true }; } }, else => { if (sequence[1] < 0x80 or sequence[1] > 0xBF) { return .{ .len = 1, .fail = true }; } }, } if (sequence[2] < 0x80 or sequence[2] > 0xBF) { return .{ .len = 2, .fail = true }; } return .{ .len = len, .code_point = ((@as(u32, sequence[0]) << 12) + (@as(u32, sequence[1]) << 6) + @as(u32, sequence[2])) - 0x000E2080, }; }, 4 => { switch (sequence[0]) { 0xF0 => { if (sequence[1] < 0x90 or sequence[1] > 0xBF) { return .{ .len = 1, .fail = true }; } }, 0xF4 => { if (sequence[1] < 0x80 or sequence[1] > 0x8F) { return .{ .len = 1, .fail = true }; } }, // invalid code point // this used to be an assertion 0...(0xF0 - 1), 0xF4 + 1...std.math.maxInt(@TypeOf(sequence[0])) => { return UTF16Replacement{ .len = 1, .fail = true }; }, else => { if (sequence[1] < 0x80 or sequence[1] > 0xBF) { return .{ .len = 1, .fail = true }; } }, } if (sequence[2] < 0x80 or sequence[2] > 0xBF) { return .{ .len = 2, .fail = true }; } if (sequence[3] < 0x80 or sequence[3] > 0xBF) { return .{ .len = 3, .fail = true }; } return .{ .len = 4, .code_point = ((@as(u32, sequence[0]) << 18) + (@as(u32, sequence[1]) << 12) + (@as(u32, sequence[2]) << 6) + @as(u32, sequence[3])) - 0x03C82080, }; }, // invalid unicode sequence // 1 or 0 are both invalid here else => return UTF16Replacement{ .len = 1, .fail = true }, } } pub fn copyLatin1IntoUTF8(buf_: []u8, comptime Type: type, latin1_: Type) EncodeIntoResult { return copyLatin1IntoUTF8StopOnNonASCII(buf_, Type, latin1_, false); } pub fn copyLatin1IntoUTF8StopOnNonASCII(buf_: []u8, comptime Type: type, latin1_: Type, comptime stop: bool) EncodeIntoResult { if (comptime bun.FeatureFlags.latin1_is_now_ascii) { const to_copy = @as(u32, @truncate(@min(buf_.len, latin1_.len))); @memcpy(buf_[0..to_copy], latin1_[0..to_copy]); return .{ .written = to_copy, .read = to_copy }; } var buf = buf_; var latin1 = latin1_; log("latin1 encode {d} -> {d}", .{ buf.len, latin1.len }); while (buf.len > 0 and latin1.len > 0) { inner: { var remaining_runs = @min(buf.len, latin1.len) / ascii_vector_size; while (remaining_runs > 0) : (remaining_runs -= 1) { const vec: AsciiVector = latin1[0..ascii_vector_size].*; if (@reduce(.Max, vec) > 127) { if (comptime stop) return .{ .written = std.math.maxInt(u32), .read = std.math.maxInt(u32) }; // zig or LLVM doesn't do @ctz nicely with SIMD if (comptime ascii_vector_size >= 8) { const Int = u64; const size = @sizeOf(Int); { const bytes = @as(Int, @bitCast(latin1[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; buf[0..size].* = @as([size]u8, @bitCast(bytes)); if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) std.debug.assert(latin1[first_set_byte] >= 127); buf = buf[first_set_byte..]; latin1 = latin1[first_set_byte..]; break :inner; } latin1 = latin1[size..]; buf = buf[size..]; } if (comptime ascii_vector_size >= 16) { const bytes = @as(Int, @bitCast(latin1[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; buf[0..size].* = @as([size]u8, @bitCast(bytes)); if (comptime Environment.allow_assert) std.debug.assert(mask > 0); const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) std.debug.assert(latin1[first_set_byte] >= 127); buf = buf[first_set_byte..]; latin1 = latin1[first_set_byte..]; break :inner; } } unreachable; } buf[0..ascii_vector_size].* = @as([ascii_vector_size]u8, @bitCast(vec))[0..ascii_vector_size].*; latin1 = latin1[ascii_vector_size..]; buf = buf[ascii_vector_size..]; } { const Int = u64; const size = @sizeOf(Int); while (@min(buf.len, latin1.len) >= size) { const bytes = @as(Int, @bitCast(latin1[0..size].*)); buf[0..size].* = @as([size]u8, @bitCast(bytes)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime stop) return .{ .written = std.math.maxInt(u32), .read = std.math.maxInt(u32) }; if (comptime Environment.allow_assert) std.debug.assert(latin1[first_set_byte] >= 127); buf = buf[first_set_byte..]; latin1 = latin1[first_set_byte..]; break :inner; } latin1 = latin1[size..]; buf = buf[size..]; } } { const end = latin1.ptr + @min(buf.len, latin1.len); if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(latin1.ptr + 8) > @intFromPtr(end)); const start_ptr = @intFromPtr(buf.ptr); const start_ptr_latin1 = @intFromPtr(latin1.ptr); while (latin1.ptr != end and latin1.ptr[0] <= 127) { buf.ptr[0] = latin1.ptr[0]; buf.ptr += 1; latin1.ptr += 1; } buf.len -= @intFromPtr(buf.ptr) - start_ptr; latin1.len -= @intFromPtr(latin1.ptr) - start_ptr_latin1; } } if (latin1.len > 0 and buf.len >= 2) { if (comptime stop) return .{ .written = std.math.maxInt(u32), .read = std.math.maxInt(u32) }; buf[0..2].* = latin1ToCodepointBytesAssumeNotASCII(latin1[0]); latin1 = latin1[1..]; buf = buf[2..]; } } return .{ .written = @as(u32, @truncate(buf_.len - buf.len)), .read = @as(u32, @truncate(latin1_.len - latin1.len)), }; } pub fn replaceLatin1WithUTF8(buf_: []u8) void { var latin1 = buf_; while (strings.firstNonASCII(latin1)) |i| { latin1[i..][0..2].* = latin1ToCodepointBytesAssumeNotASCII(latin1[i]); latin1 = latin1[i + 2 ..]; } } pub fn elementLengthLatin1IntoUTF8(comptime Type: type, latin1_: Type) usize { // https://zig.godbolt.org/z/zzYexPPs9 var latin1 = latin1_; const input_len = latin1.len; var total_non_ascii_count: usize = 0; // This is about 30% faster on large input compared to auto-vectorization if (comptime Environment.enableSIMD) { const end = latin1.ptr + (latin1.len - (latin1.len % ascii_vector_size)); while (latin1.ptr != end) { const vec: AsciiVector = latin1[0..ascii_vector_size].*; // Shifting a unsigned 8 bit integer to the right by 7 bits always produces a value of 0 or 1. const cmp = vec >> @as(AsciiVector, @splat( @as(u8, 7), )); // Anding that value rather than converting it into a @Vector(16, u1) produces better code from LLVM. const mask: AsciiVector = cmp & @as(AsciiVector, @splat( @as(u8, 1), )); total_non_ascii_count += @as(usize, @reduce(.Add, mask)); latin1 = latin1[ascii_vector_size..]; } // an important hint to the compiler to not auto-vectorize the loop below if (latin1.len >= ascii_vector_size) unreachable; } for (latin1) |c| { total_non_ascii_count += @as(usize, @intFromBool(c > 127)); } // each non-ascii latin1 character becomes 2 UTF8 characters return input_len + total_non_ascii_count; } const JSC = @import("root").bun.JSC; pub fn copyLatin1IntoUTF16(comptime Buffer: type, buf_: Buffer, comptime Type: type, latin1_: Type) EncodeIntoResult { var buf = buf_; var latin1 = latin1_; while (buf.len > 0 and latin1.len > 0) { const to_write = strings.firstNonASCII(latin1) orelse @as(u32, @truncate(@min(latin1.len, buf.len))); if (comptime std.meta.alignment(Buffer) != @alignOf(u16)) { strings.copyU8IntoU16WithAlignment(std.meta.alignment(Buffer), buf, latin1[0..to_write]); } else { strings.copyU8IntoU16(buf, latin1[0..to_write]); } latin1 = latin1[to_write..]; buf = buf[to_write..]; if (latin1.len > 0 and buf.len >= 1) { buf[0] = latin1ToCodepointBytesAssumeNotASCII16(latin1[0]); latin1 = latin1[1..]; buf = buf[1..]; } } return .{ .read = @as(u32, @truncate(buf_.len - buf.len)), .written = @as(u32, @truncate(latin1_.len - latin1.len)), }; } pub fn elementLengthLatin1IntoUTF16(comptime Type: type, latin1_: Type) usize { // latin1 is always at most 1 UTF-16 code unit long if (comptime std.meta.Child([]const u16) == Type) { return latin1_.len; } var count: usize = 0; var latin1 = latin1_; while (latin1.len > 0) { const function = comptime if (std.meta.Child(Type) == u8) strings.firstNonASCIIWithType else strings.firstNonASCII16; const to_write = function(Type, latin1) orelse @as(u32, @truncate(latin1.len)); count += to_write; latin1 = latin1[to_write..]; if (latin1.len > 0) { count += comptime if (std.meta.Child(Type) == u8) 2 else 1; latin1 = latin1[1..]; } } return count; } pub fn escapeHTMLForLatin1Input(allocator: std.mem.Allocator, latin1: []const u8) !Escaped(u8) { const Scalar = struct { pub const lengths: [std.math.maxInt(u8)]u4 = brk: { var values: [std.math.maxInt(u8)]u4 = undefined; for (values, 0..) |_, i| { switch (i) { '"' => { values[i] = "&quot;".len; }, '&' => { values[i] = "&amp;".len; }, '\'' => { values[i] = "&#x27;".len; }, '<' => { values[i] = "&lt;".len; }, '>' => { values[i] = "&gt;".len; }, else => { values[i] = 1; }, } } break :brk values; }; inline fn appendString(buf: [*]u8, comptime str: []const u8) usize { buf[0..str.len].* = str[0..str.len].*; return str.len; } pub inline fn append(buf: [*]u8, char: u8) usize { if (lengths[char] == 1) { buf[0] = char; return 1; } return switch (char) { '"' => appendString(buf, "&quot;"), '&' => appendString(buf, "&amp;"), '\'' => appendString(buf, "&#x27;"), '<' => appendString(buf, "&lt;"), '>' => appendString(buf, "&gt;"), else => unreachable, }; } pub inline fn push(comptime len: anytype, chars_: *const [len]u8, allo: std.mem.Allocator) Escaped(u8) { const chars = chars_.*; var total: usize = 0; comptime var remain_to_comp = len; comptime var comp_i = 0; inline while (remain_to_comp > 0) : (remain_to_comp -= 1) { total += lengths[chars[comp_i]]; comp_i += 1; } if (total == len) { return .{ .original = {} }; } var output = allo.alloc(u8, total) catch unreachable; var head = output.ptr; inline for (comptime bun.range(0, len)) |i| { head += @This().append(head, chars[i]); } return Escaped(u8){ .allocated = output }; } }; @setEvalBranchQuota(5000); switch (latin1.len) { 0 => return Escaped(u8){ .static = "" }, 1 => return switch (latin1[0]) { '"' => Escaped(u8){ .static = "&quot;" }, '&' => Escaped(u8){ .static = "&amp;" }, '\'' => Escaped(u8){ .static = "&#x27;" }, '<' => Escaped(u8){ .static = "&lt;" }, '>' => Escaped(u8){ .static = "&gt;" }, else => Escaped(u8){ .original = {} }, }, 2 => { const first: []const u8 = switch (latin1[0]) { '"' => "&quot;", '&' => "&amp;", '\'' => "&#x27;", '<' => "&lt;", '>' => "&gt;", else => latin1[0..1], }; const second: []const u8 = switch (latin1[1]) { '"' => "&quot;", '&' => "&amp;", '\'' => "&#x27;", '<' => "&lt;", '>' => "&gt;", else => latin1[1..2], }; if (first.len == 1 and second.len == 1) { return Escaped(u8){ .original = {} }; } return Escaped(u8){ .allocated = strings.append(allocator, first, second) catch unreachable }; }, // The simd implementation is slower for inputs less than 32 bytes. 3 => return Scalar.push(3, latin1[0..3], allocator), 4 => return Scalar.push(4, latin1[0..4], allocator), 5 => return Scalar.push(5, latin1[0..5], allocator), 6 => return Scalar.push(6, latin1[0..6], allocator), 7 => return Scalar.push(7, latin1[0..7], allocator), 8 => return Scalar.push(8, latin1[0..8], allocator), 9 => return Scalar.push(9, latin1[0..9], allocator), 10 => return Scalar.push(10, latin1[0..10], allocator), 11 => return Scalar.push(11, latin1[0..11], allocator), 12 => return Scalar.push(12, latin1[0..12], allocator), 13 => return Scalar.push(13, latin1[0..13], allocator), 14 => return Scalar.push(14, latin1[0..14], allocator), 15 => return Scalar.push(15, latin1[0..15], allocator), 16 => return Scalar.push(16, latin1[0..16], allocator), 17 => return Scalar.push(17, latin1[0..17], allocator), 18 => return Scalar.push(18, latin1[0..18], allocator), 19 => return Scalar.push(19, latin1[0..19], allocator), 20 => return Scalar.push(20, latin1[0..20], allocator), 21 => return Scalar.push(21, latin1[0..21], allocator), 22 => return Scalar.push(22, latin1[0..22], allocator), 23 => return Scalar.push(23, latin1[0..23], allocator), 24 => return Scalar.push(24, latin1[0..24], allocator), 25 => return Scalar.push(25, latin1[0..25], allocator), 26 => return Scalar.push(26, latin1[0..26], allocator), 27 => return Scalar.push(27, latin1[0..27], allocator), 28 => return Scalar.push(28, latin1[0..28], allocator), 29 => return Scalar.push(29, latin1[0..29], allocator), 30 => return Scalar.push(30, latin1[0..30], allocator), 31 => return Scalar.push(31, latin1[0..31], allocator), 32 => return Scalar.push(32, latin1[0..32], allocator), else => { var remaining = latin1; const vec_chars = "\"&'<>"; const vecs: [vec_chars.len]AsciiVector = comptime brk: { var _vecs: [vec_chars.len]AsciiVector = undefined; for (vec_chars, 0..) |c, i| { _vecs[i] = @splat(c); } break :brk _vecs; }; var any_needs_escape = false; var buf: std.ArrayList(u8) = std.ArrayList(u8){ .items = &.{}, .capacity = 0, .allocator = allocator, }; if (comptime Environment.enableSIMD) { // pass #1: scan for any characters that need escaping // assume most strings won't need any escaping, so don't actually allocate the buffer scan_and_allocate_lazily: while (remaining.len >= ascii_vector_size) { if (comptime Environment.allow_assert) std.debug.assert(!any_needs_escape); const vec: AsciiVector = remaining[0..ascii_vector_size].*; if (@reduce(.Max, @as(AsciiVectorU1, @bitCast((vec == vecs[0]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[1]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[2]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[3]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[4])))) == 1) { if (comptime Environment.allow_assert) std.debug.assert(buf.capacity == 0); buf = try std.ArrayList(u8).initCapacity(allocator, latin1.len + 6); const copy_len = @intFromPtr(remaining.ptr) - @intFromPtr(latin1.ptr); @memcpy(buf.items[0..copy_len], latin1[0..copy_len]); buf.items.len = copy_len; any_needs_escape = true; comptime var i: usize = 0; inline while (i < ascii_vector_size) : (i += 1) { switch (vec[i]) { '"' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&quot;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&quot;".len][0.."&quot;".len].* = "&quot;".*; buf.items.len += "&quot;".len; }, '&' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&amp;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&amp;".len][0.."&amp;".len].* = "&amp;".*; buf.items.len += "&amp;".len; }, '\'' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&#x27;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&#x27;".len][0.."&#x27;".len].* = "&#x27;".*; buf.items.len += "&#x27;".len; }, '<' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&lt;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&lt;".len][0.."&lt;".len].* = "&lt;".*; buf.items.len += "&lt;".len; }, '>' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&gt;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&gt;".len][0.."&gt;".len].* = "&gt;".*; buf.items.len += "&gt;".len; }, else => |c| { buf.appendAssumeCapacity(c); }, } } remaining = remaining[ascii_vector_size..]; break :scan_and_allocate_lazily; } remaining = remaining[ascii_vector_size..]; } } if (any_needs_escape) { // pass #2: we found something that needed an escape // so we'll go ahead and copy the buffer into a new buffer while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; if (@reduce(.Max, @as(AsciiVectorU1, @bitCast((vec == vecs[0]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[1]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[2]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[3]))) | @as(AsciiVectorU1, @bitCast((vec == vecs[4])))) == 1) { buf.ensureUnusedCapacity(ascii_vector_size + 6) catch unreachable; comptime var i: usize = 0; inline while (i < ascii_vector_size) : (i += 1) { switch (vec[i]) { '"' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&quot;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&quot;".len][0.."&quot;".len].* = "&quot;".*; buf.items.len += "&quot;".len; }, '&' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&amp;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&amp;".len][0.."&amp;".len].* = "&amp;".*; buf.items.len += "&amp;".len; }, '\'' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&#x27;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&#x27;".len][0.."&#x27;".len].* = "&#x27;".*; buf.items.len += "&#x27;".len; }, '<' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&lt;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&lt;".len][0.."&lt;".len].* = "&lt;".*; buf.items.len += "&lt;".len; }, '>' => { buf.ensureUnusedCapacity((ascii_vector_size - i) + "&gt;".len) catch unreachable; buf.items.ptr[buf.items.len .. buf.items.len + "&gt;".len][0.."&gt;".len].* = "&gt;".*; buf.items.len += "&gt;".len; }, else => |c| { buf.appendAssumeCapacity(c); }, } } remaining = remaining[ascii_vector_size..]; continue; } try buf.ensureUnusedCapacity(ascii_vector_size); buf.items.ptr[buf.items.len .. buf.items.len + ascii_vector_size][0..ascii_vector_size].* = remaining[0..ascii_vector_size].*; buf.items.len += ascii_vector_size; remaining = remaining[ascii_vector_size..]; } } var ptr = remaining.ptr; const end = remaining.ptr + remaining.len; if (!any_needs_escape) { scan_and_allocate_lazily: while (ptr != end) : (ptr += 1) { switch (ptr[0]) { '"', '&', '\'', '<', '>' => |c| { if (comptime Environment.allow_assert) std.debug.assert(buf.capacity == 0); buf = try std.ArrayList(u8).initCapacity(allocator, latin1.len + @as(usize, Scalar.lengths[c])); const copy_len = @intFromPtr(ptr) - @intFromPtr(latin1.ptr); @memcpy(buf.items[0..copy_len], latin1[0..copy_len]); buf.items.len = copy_len; any_needs_escape = true; break :scan_and_allocate_lazily; }, else => {}, } } } while (ptr != end) : (ptr += 1) { switch (ptr[0]) { '"' => { buf.appendSlice("&quot;") catch unreachable; }, '&' => { buf.appendSlice("&amp;") catch unreachable; }, '\'' => { buf.appendSlice("&#x27;") catch unreachable; // modified from escape-html; used to be '&#39' }, '<' => { buf.appendSlice("&lt;") catch unreachable; }, '>' => { buf.appendSlice("&gt;") catch unreachable; }, else => |c| { buf.append(c) catch unreachable; }, } } if (!any_needs_escape) { if (comptime Environment.allow_assert) std.debug.assert(buf.capacity == 0); return Escaped(u8){ .original = {} }; } return Escaped(u8){ .allocated = try buf.toOwnedSlice() }; }, } } fn Escaped(comptime T: type) type { return union(enum) { static: []const u8, original: void, allocated: []T, }; } pub fn escapeHTMLForUTF16Input(allocator: std.mem.Allocator, utf16: []const u16) !Escaped(u16) { const Scalar = struct { pub const lengths: [std.math.maxInt(u8)]u4 = brk: { var values: [std.math.maxInt(u8)]u4 = undefined; for (values, 0..) |_, i| { values[i] = switch (i) { '"' => "&quot;".len, '&' => "&amp;".len, '\'' => "&#x27;".len, '<' => "&lt;".len, '>' => "&gt;".len, else => 1, }; } break :brk values; }; }; switch (utf16.len) { 0 => return Escaped(u16){ .static = &[_]u8{} }, 1 => { switch (utf16[0]) { '"' => return Escaped(u16){ .static = "&quot;" }, '&' => return Escaped(u16){ .static = "&amp;" }, '\'' => return Escaped(u16){ .static = "&#x27;" }, '<' => return Escaped(u16){ .static = "&lt;" }, '>' => return Escaped(u16){ .static = "&gt;" }, else => return Escaped(u16){ .original = {} }, } }, 2 => { const first_16 = switch (utf16[0]) { '"' => toUTF16Literal("&quot;"), '&' => toUTF16Literal("&amp;"), '\'' => toUTF16Literal("&#x27;"), '<' => toUTF16Literal("&lt;"), '>' => toUTF16Literal("&gt;"), else => @as([]const u16, utf16[0..1]), }; const second_16 = switch (utf16[1]) { '"' => toUTF16Literal("&quot;"), '&' => toUTF16Literal("&amp;"), '\'' => toUTF16Literal("&#x27;"), '<' => toUTF16Literal("&lt;"), '>' => toUTF16Literal("&gt;"), else => @as([]const u16, utf16[1..2]), }; if (first_16.ptr == utf16.ptr and second_16.ptr == utf16.ptr + 1) { return Escaped(u16){ .original = {} }; } var buf = allocator.alloc(u16, first_16.len + second_16.len) catch unreachable; bun.copy(u16, buf, first_16); bun.copy(u16, buf[first_16.len..], second_16); return Escaped(u16){ .allocated = buf }; }, else => { var remaining = utf16; var any_needs_escape = false; var buf: std.ArrayList(u16) = undefined; if (comptime Environment.enableSIMD) { const vec_chars = "\"&'<>"; const vecs: [vec_chars.len]AsciiU16Vector = brk: { var _vecs: [vec_chars.len]AsciiU16Vector = undefined; for (vec_chars, 0..) |c, i| { _vecs[i] = @splat(@as(u16, c)); } break :brk _vecs; }; // pass #1: scan for any characters that need escaping // assume most strings won't need any escaping, so don't actually allocate the buffer scan_and_allocate_lazily: while (remaining.len >= ascii_u16_vector_size) { if (comptime Environment.allow_assert) std.debug.assert(!any_needs_escape); const vec: AsciiU16Vector = remaining[0..ascii_u16_vector_size].*; if (@reduce(.Max, @as(AsciiVectorU16U1, @bitCast(vec > @as(AsciiU16Vector, @splat(@as(u16, 127))))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[0]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[1]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[2]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[3]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[4])))) == 1) { var i: u16 = 0; lazy: { while (i < ascii_u16_vector_size) { switch (remaining[i]) { '"', '&', '\'', '<', '>' => { any_needs_escape = true; break :lazy; }, 128...std.math.maxInt(u16) => { const cp = utf16Codepoint([]const u16, remaining[i..]); i += @as(u16, cp.len); }, else => { i += 1; }, } } } if (!any_needs_escape) { remaining = remaining[i..]; continue :scan_and_allocate_lazily; } if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(remaining.ptr + i) >= @intFromPtr(utf16.ptr)); const to_copy = std.mem.sliceAsBytes(utf16)[0 .. @intFromPtr(remaining.ptr + i) - @intFromPtr(utf16.ptr)]; var to_copy_16 = std.mem.bytesAsSlice(u16, to_copy); buf = try std.ArrayList(u16).initCapacity(allocator, utf16.len + 6); try buf.appendSlice(to_copy_16); while (i < ascii_u16_vector_size) { switch (remaining[i]) { '"', '&', '\'', '<', '>' => |c| { const result = switch (c) { '"' => toUTF16Literal("&quot;"), '&' => toUTF16Literal("&amp;"), '\'' => toUTF16Literal("&#x27;"), '<' => toUTF16Literal("&lt;"), '>' => toUTF16Literal("&gt;"), else => unreachable, }; buf.appendSlice(result) catch unreachable; i += 1; }, 128...std.math.maxInt(u16) => { const cp = utf16Codepoint([]const u16, remaining[i..]); buf.appendSlice(remaining[i..][0..@as(usize, cp.len)]) catch unreachable; i += @as(u16, cp.len); }, else => |c| { i += 1; buf.append(c) catch unreachable; }, } } // edgecase: code point width could exceed asdcii_u16_vector_size remaining = remaining[i..]; break :scan_and_allocate_lazily; } remaining = remaining[ascii_u16_vector_size..]; } if (any_needs_escape) { // pass #2: we found something that needed an escape // but there's still some more text to // so we'll go ahead and copy the buffer into a new buffer while (remaining.len >= ascii_u16_vector_size) { const vec: AsciiU16Vector = remaining[0..ascii_u16_vector_size].*; if (@reduce(.Max, @as(AsciiVectorU16U1, @bitCast(vec > @as(AsciiU16Vector, @splat(@as(u16, 127))))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[0]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[1]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[2]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[3]))) | @as(AsciiVectorU16U1, @bitCast((vec == vecs[4])))) == 1) { buf.ensureUnusedCapacity(ascii_u16_vector_size) catch unreachable; var i: u16 = 0; while (i < ascii_u16_vector_size) { switch (remaining[i]) { '"' => { buf.appendSlice(toUTF16Literal("&quot;")) catch unreachable; i += 1; }, '&' => { buf.appendSlice(toUTF16Literal("&amp;")) catch unreachable; i += 1; }, '\'' => { buf.appendSlice(toUTF16Literal("&#x27;")) catch unreachable; // modified from escape-html; used to be '&#39' i += 1; }, '<' => { buf.appendSlice(toUTF16Literal("&lt;")) catch unreachable; i += 1; }, '>' => { buf.appendSlice(toUTF16Literal("&gt;")) catch unreachable; i += 1; }, 128...std.math.maxInt(u16) => { const cp = utf16Codepoint([]const u16, remaining[i..]); buf.appendSlice(remaining[i..][0..@as(usize, cp.len)]) catch unreachable; i += @as(u16, cp.len); }, else => |c| { buf.append(c) catch unreachable; i += 1; }, } } remaining = remaining[i..]; continue; } try buf.ensureUnusedCapacity(ascii_u16_vector_size); buf.items.ptr[buf.items.len .. buf.items.len + ascii_u16_vector_size][0..ascii_u16_vector_size].* = remaining[0..ascii_u16_vector_size].*; buf.items.len += ascii_u16_vector_size; remaining = remaining[ascii_u16_vector_size..]; } } } var ptr = remaining.ptr; const end = remaining.ptr + remaining.len; if (!any_needs_escape) { scan_and_allocate_lazily: while (ptr != end) { switch (ptr[0]) { '"', '&', '\'', '<', '>' => |c| { buf = try std.ArrayList(u16).initCapacity(allocator, utf16.len + @as(usize, Scalar.lengths[c])); if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(ptr) >= @intFromPtr(utf16.ptr)); const to_copy = std.mem.sliceAsBytes(utf16)[0 .. @intFromPtr(ptr) - @intFromPtr(utf16.ptr)]; var to_copy_16 = std.mem.bytesAsSlice(u16, to_copy); try buf.appendSlice(to_copy_16); any_needs_escape = true; break :scan_and_allocate_lazily; }, 128...std.math.maxInt(u16) => { const cp = utf16Codepoint([]const u16, ptr[0..2]); ptr += @as(u16, cp.len); }, else => { ptr += 1; }, } } } while (ptr != end) { switch (ptr[0]) { '"' => { buf.appendSlice(toUTF16Literal("&quot;")) catch unreachable; ptr += 1; }, '&' => { buf.appendSlice(toUTF16Literal("&amp;")) catch unreachable; ptr += 1; }, '\'' => { buf.appendSlice(toUTF16Literal("&#x27;")) catch unreachable; // modified from escape-html; used to be '&#39' ptr += 1; }, '<' => { buf.appendSlice(toUTF16Literal("&lt;")) catch unreachable; ptr += 1; }, '>' => { buf.appendSlice(toUTF16Literal("&gt;")) catch unreachable; ptr += 1; }, 128...std.math.maxInt(u16) => { const cp = utf16Codepoint([]const u16, ptr[0..2]); buf.appendSlice(ptr[0..@as(usize, cp.len)]) catch unreachable; ptr += @as(u16, cp.len); }, else => |c| { buf.append(c) catch unreachable; ptr += 1; }, } } if (!any_needs_escape) { return Escaped(u16){ .original = {} }; } return Escaped(u16){ .allocated = try buf.toOwnedSlice() }; }, } } test "copyLatin1IntoUTF8 - ascii" { var input: string = "hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!hello world!"; var output = std.mem.zeroes([500]u8); const result = copyLatin1IntoUTF8(&output, string, input); try std.testing.expectEqual(input.len, result.read); try std.testing.expectEqual(input.len, result.written); try std.testing.expectEqualSlices(u8, input, output[0..result.written]); } test "copyLatin1IntoUTF8 - latin1" { { var input: string = &[_]u8{ 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 32, 169 }; var output = std.mem.zeroes([500]u8); var expected = "hello world ©"; const result = copyLatin1IntoUTF8(&output, string, input); try std.testing.expectEqual(input.len, result.read); try std.testing.expectEqualSlices(u8, expected, output[0..result.written]); } { var input: string = &[_]u8{ 72, 169, 101, 108, 108, 169, 111, 32, 87, 111, 114, 169, 108, 100, 33 }; var output = std.mem.zeroes([500]u8); var expected = "H©ell©o Wor©ld!"; const result = copyLatin1IntoUTF8(&output, string, input); try std.testing.expectEqual(input.len, result.read); try std.testing.expectEqualSlices(u8, expected, output[0..result.written]); } } pub fn latin1ToCodepointAssumeNotASCII(char: u8, comptime CodePointType: type) CodePointType { return @as( CodePointType, @intCast(latin1ToCodepointBytesAssumeNotASCII16(char)), ); } const latin1_to_utf16_conversion_table = [256]u16{ 0x0000, 0x0001, 0x0002, 0x0003, 0x0004, 0x0005, 0x0006, 0x0007, // 00-07 0x0008, 0x0009, 0x000A, 0x000B, 0x000C, 0x000D, 0x000E, 0x000F, // 08-0F 0x0010, 0x0011, 0x0012, 0x0013, 0x0014, 0x0015, 0x0016, 0x0017, // 10-17 0x0018, 0x0019, 0x001A, 0x001B, 0x001C, 0x001D, 0x001E, 0x001F, // 18-1F 0x0020, 0x0021, 0x0022, 0x0023, 0x0024, 0x0025, 0x0026, 0x0027, // 20-27 0x0028, 0x0029, 0x002A, 0x002B, 0x002C, 0x002D, 0x002E, 0x002F, // 28-2F 0x0030, 0x0031, 0x0032, 0x0033, 0x0034, 0x0035, 0x0036, 0x0037, // 30-37 0x0038, 0x0039, 0x003A, 0x003B, 0x003C, 0x003D, 0x003E, 0x003F, // 38-3F 0x0040, 0x0041, 0x0042, 0x0043, 0x0044, 0x0045, 0x0046, 0x0047, // 40-47 0x0048, 0x0049, 0x004A, 0x004B, 0x004C, 0x004D, 0x004E, 0x004F, // 48-4F 0x0050, 0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057, // 50-57 0x0058, 0x0059, 0x005A, 0x005B, 0x005C, 0x005D, 0x005E, 0x005F, // 58-5F 0x0060, 0x0061, 0x0062, 0x0063, 0x0064, 0x0065, 0x0066, 0x0067, // 60-67 0x0068, 0x0069, 0x006A, 0x006B, 0x006C, 0x006D, 0x006E, 0x006F, // 68-6F 0x0070, 0x0071, 0x0072, 0x0073, 0x0074, 0x0075, 0x0076, 0x0077, // 70-77 0x0078, 0x0079, 0x007A, 0x007B, 0x007C, 0x007D, 0x007E, 0x007F, // 78-7F 0x20AC, 0x0081, 0x201A, 0x0192, 0x201E, 0x2026, 0x2020, 0x2021, // 80-87 0x02C6, 0x2030, 0x0160, 0x2039, 0x0152, 0x008D, 0x017D, 0x008F, // 88-8F 0x0090, 0x2018, 0x2019, 0x201C, 0x201D, 0x2022, 0x2013, 0x2014, // 90-97 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0x009D, 0x017E, 0x0178, // 98-9F 0x00A0, 0x00A1, 0x00A2, 0x00A3, 0x00A4, 0x00A5, 0x00A6, 0x00A7, // A0-A7 0x00A8, 0x00A9, 0x00AA, 0x00AB, 0x00AC, 0x00AD, 0x00AE, 0x00AF, // A8-AF 0x00B0, 0x00B1, 0x00B2, 0x00B3, 0x00B4, 0x00B5, 0x00B6, 0x00B7, // B0-B7 0x00B8, 0x00B9, 0x00BA, 0x00BB, 0x00BC, 0x00BD, 0x00BE, 0x00BF, // B8-BF 0x00C0, 0x00C1, 0x00C2, 0x00C3, 0x00C4, 0x00C5, 0x00C6, 0x00C7, // C0-C7 0x00C8, 0x00C9, 0x00CA, 0x00CB, 0x00CC, 0x00CD, 0x00CE, 0x00CF, // C8-CF 0x00D0, 0x00D1, 0x00D2, 0x00D3, 0x00D4, 0x00D5, 0x00D6, 0x00D7, // D0-D7 0x00D8, 0x00D9, 0x00DA, 0x00DB, 0x00DC, 0x00DD, 0x00DE, 0x00DF, // D8-DF 0x00E0, 0x00E1, 0x00E2, 0x00E3, 0x00E4, 0x00E5, 0x00E6, 0x00E7, // E0-E7 0x00E8, 0x00E9, 0x00EA, 0x00EB, 0x00EC, 0x00ED, 0x00EE, 0x00EF, // E8-EF 0x00F0, 0x00F1, 0x00F2, 0x00F3, 0x00F4, 0x00F5, 0x00F6, 0x00F7, // F0-F7 0x00F8, 0x00F9, 0x00FA, 0x00FB, 0x00FC, 0x00FD, 0x00FE, 0x00FF, // F8-FF }; pub fn latin1ToCodepointBytesAssumeNotASCII(char: u32) [2]u8 { var bytes = [4]u8{ 0, 0, 0, 0 }; _ = encodeWTF8Rune(&bytes, @as(i32, @intCast(char))); return bytes[0..2].*; } pub fn latin1ToCodepointBytesAssumeNotASCII16(char: u32) u16 { return latin1_to_utf16_conversion_table[@as(u8, @truncate(char))]; } pub fn copyUTF16IntoUTF8(buf: []u8, comptime Type: type, utf16: Type, comptime allow_partial_write: bool) EncodeIntoResult { if (comptime Type == []const u16) { if (bun.FeatureFlags.use_simdutf) { if (utf16.len == 0) return .{ .read = 0, .written = 0 }; const trimmed = bun.simdutf.trim.utf16(utf16); if (trimmed.len == 0) return .{ .read = 0, .written = 0 }; const out_len = if (buf.len <= (trimmed.len * 3 + 2)) bun.simdutf.length.utf8.from.utf16.le(trimmed) else buf.len; return copyUTF16IntoUTF8WithBuffer(buf, Type, utf16, trimmed, out_len, allow_partial_write); } } return copyUTF16IntoUTF8WithBuffer(buf, Type, utf16, utf16, utf16.len, allow_partial_write); } pub fn copyUTF16IntoUTF8WithBuffer(buf: []u8, comptime Type: type, utf16: Type, trimmed: Type, out_len: usize, comptime allow_partial_write: bool) EncodeIntoResult { var remaining = buf; var utf16_remaining = utf16; var ended_on_non_ascii = false; brk: { if (comptime Type == []const u16) { if (bun.FeatureFlags.use_simdutf) { log("UTF16 {d} -> UTF8 {d}", .{ utf16.len, out_len }); if (remaining.len >= out_len) { const result = bun.simdutf.convert.utf16.to.utf8.with_errors.le(trimmed, remaining); if (result.status == .surrogate) break :brk; return EncodeIntoResult{ .read = @as(u32, @truncate(trimmed.len)), .written = @as(u32, @truncate(result.count)), }; } } } } while (firstNonASCII16(Type, utf16_remaining)) |i| { const end = @min(i, remaining.len); if (end > 0) copyU16IntoU8(remaining, Type, utf16_remaining[0..end]); remaining = remaining[end..]; utf16_remaining = utf16_remaining[end..]; if (@min(utf16_remaining.len, remaining.len) == 0) break; const replacement = utf16CodepointWithFFFD(Type, utf16_remaining); const width: usize = replacement.utf8Width(); if (width > remaining.len) { ended_on_non_ascii = width > 1; if (comptime allow_partial_write) switch (width) { 2 => { if (remaining.len > 0) { //only first will be written remaining[0] = @as(u8, @truncate(0xC0 | (replacement.code_point >> 6))); remaining = remaining[remaining.len..]; } }, 3 => { //only first to second written switch (remaining.len) { 1 => { remaining[0] = @as(u8, @truncate(0xE0 | (replacement.code_point >> 12))); remaining = remaining[remaining.len..]; }, 2 => { remaining[0] = @as(u8, @truncate(0xE0 | (replacement.code_point >> 12))); remaining[1] = @as(u8, @truncate(0x80 | (replacement.code_point >> 6) & 0x3F)); remaining = remaining[remaining.len..]; }, else => {}, } }, 4 => { //only 1 to 3 written switch (remaining.len) { 1 => { remaining[0] = @as(u8, @truncate(0xF0 | (replacement.code_point >> 18))); remaining = remaining[remaining.len..]; }, 2 => { remaining[0] = @as(u8, @truncate(0xF0 | (replacement.code_point >> 18))); remaining[1] = @as(u8, @truncate(0x80 | (replacement.code_point >> 12) & 0x3F)); remaining = remaining[remaining.len..]; }, 3 => { remaining[0] = @as(u8, @truncate(0xF0 | (replacement.code_point >> 18))); remaining[1] = @as(u8, @truncate(0x80 | (replacement.code_point >> 12) & 0x3F)); remaining[2] = @as(u8, @truncate(0x80 | (replacement.code_point >> 6) & 0x3F)); remaining = remaining[remaining.len..]; }, else => {}, } }, else => {}, }; break; } utf16_remaining = utf16_remaining[replacement.len..]; _ = encodeWTF8RuneT(remaining.ptr[0..4], u32, @as(u32, replacement.code_point)); remaining = remaining[width..]; } if (remaining.len > 0 and !ended_on_non_ascii and utf16_remaining.len > 0) { const len = @min(remaining.len, utf16_remaining.len); copyU16IntoU8(remaining[0..len], Type, utf16_remaining[0..len]); utf16_remaining = utf16_remaining[len..]; remaining = remaining[len..]; } return .{ .read = @as(u32, @truncate(utf16.len - utf16_remaining.len)), .written = @as(u32, @truncate(buf.len - remaining.len)), }; } pub fn elementLengthUTF16IntoUTF8(comptime Type: type, utf16: Type) usize { if (bun.FeatureFlags.use_simdutf) { return bun.simdutf.length.utf8.from.utf16.le(utf16); } var utf16_remaining = utf16; var count: usize = 0; while (firstNonASCII16(Type, utf16_remaining)) |i| { count += i; utf16_remaining = utf16_remaining[i..]; const replacement = utf16Codepoint(Type, utf16_remaining); count += replacement.utf8Width(); utf16_remaining = utf16_remaining[replacement.len..]; } return count + utf16_remaining.len; } pub fn elementLengthUTF8IntoUTF16(comptime Type: type, utf8: Type) usize { var utf8_remaining = utf8; var count: usize = 0; if (bun.FeatureFlags.use_simdutf) { return bun.simdutf.length.utf16.from.utf8.le(utf8); } while (firstNonASCII(utf8_remaining)) |i| { count += i; utf8_remaining = utf8_remaining[i..]; const replacement = utf16Codepoint(Type, utf8_remaining); count += replacement.len; utf8_remaining = utf8_remaining[@min(replacement.utf8Width(), utf8_remaining.len)..]; } return count + utf8_remaining.len; } // Check utf16 string equals utf8 string without allocating extra memory pub fn utf16EqlString(text: []const u16, str: string) bool { if (text.len > str.len) { // Strings can't be equal if UTF-16 encoding is longer than UTF-8 encoding return false; } var temp = [4]u8{ 0, 0, 0, 0 }; const n = text.len; var j: usize = 0; var i: usize = 0; // TODO: is it safe to just make this u32 or u21? var r1: i32 = undefined; var k: u4 = 0; while (i < n) : (i += 1) { r1 = text[i]; if (r1 >= 0xD800 and r1 <= 0xDBFF and i + 1 < n) { const r2: i32 = text[i + 1]; if (r2 >= 0xDC00 and r2 <= 0xDFFF) { r1 = (r1 - 0xD800) << 10 | (r2 - 0xDC00) + 0x10000; i += 1; } } const width = encodeWTF8Rune(&temp, r1); if (j + width > str.len) { return false; } k = 0; while (k < width) : (k += 1) { if (temp[k] != str[j]) { return false; } j += 1; } } return j == str.len; } // This is a clone of golang's "utf8.EncodeRune" that has been modified to encode using // WTF-8 instead. See https://simonsapin.github.io/wtf-8/ for more info. pub fn encodeWTF8Rune(p: *[4]u8, r: i32) u3 { return @call( .always_inline, encodeWTF8RuneT, .{ p, u32, @as(u32, @intCast(r)), }, ); } pub fn encodeWTF8RuneT(p: *[4]u8, comptime R: type, r: R) u3 { switch (r) { 0...0x7F => { p[0] = @as(u8, @intCast(r)); return 1; }, (0x7F + 1)...0x7FF => { p[0] = @as(u8, @truncate(0xC0 | ((r >> 6)))); p[1] = @as(u8, @truncate(0x80 | (r & 0x3F))); return 2; }, (0x7FF + 1)...0xFFFF => { p[0] = @as(u8, @truncate(0xE0 | ((r >> 12)))); p[1] = @as(u8, @truncate(0x80 | ((r >> 6) & 0x3F))); p[2] = @as(u8, @truncate(0x80 | (r & 0x3F))); return 3; }, else => { p[0] = @as(u8, @truncate(0xF0 | ((r >> 18)))); p[1] = @as(u8, @truncate(0x80 | ((r >> 12) & 0x3F))); p[2] = @as(u8, @truncate(0x80 | ((r >> 6) & 0x3F))); p[3] = @as(u8, @truncate(0x80 | (r & 0x3F))); return 4; }, } } pub inline fn wtf8ByteSequenceLength(first_byte: u8) u3 { return switch (first_byte) { 0 => 0, 1...0x80 - 1 => 1, else => if ((first_byte & 0xE0) == 0xC0) @as(u3, 2) else if ((first_byte & 0xF0) == 0xE0) @as(u3, 3) else if ((first_byte & 0xF8) == 0xF0) @as(u3, 4) else @as(u3, 1), }; } /// 0 == invalid pub inline fn wtf8ByteSequenceLengthWithInvalid(first_byte: u8) u3 { return switch (first_byte) { 0...0x80 - 1 => 1, else => if ((first_byte & 0xE0) == 0xC0) @as(u3, 2) else if ((first_byte & 0xF0) == 0xE0) @as(u3, 3) else if ((first_byte & 0xF8) == 0xF0) @as(u3, 4) else @as(u3, 1), }; } /// Convert potentially ill-formed UTF-8 or UTF-16 bytes to a Unicode Codepoint. /// Invalid codepoints are replaced with `zero` parameter /// This is a clone of esbuild's decodeWTF8Rune /// which was a clone of golang's "utf8.DecodeRune" that was modified to decode using WTF-8 instead. /// Asserts a multi-byte codepoint pub inline fn decodeWTF8RuneTMultibyte(p: *const [4]u8, len: u3, comptime T: type, comptime zero: T) T { if (comptime Environment.allow_assert) std.debug.assert(len > 1); const s1 = p[1]; if ((s1 & 0xC0) != 0x80) return zero; if (len == 2) { const cp = @as(T, p[0] & 0x1F) << 6 | @as(T, s1 & 0x3F); if (cp < 0x80) return zero; return cp; } const s2 = p[2]; if ((s2 & 0xC0) != 0x80) return zero; if (len == 3) { const cp = (@as(T, p[0] & 0x0F) << 12) | (@as(T, s1 & 0x3F) << 6) | (@as(T, s2 & 0x3F)); if (cp < 0x800) return zero; return cp; } const s3 = p[3]; { const cp = (@as(T, p[0] & 0x07) << 18) | (@as(T, s1 & 0x3F) << 12) | (@as(T, s2 & 0x3F) << 6) | (@as(T, s3 & 0x3F)); if (cp < 0x10000 or cp > 0x10FFFF) return zero; return cp; } unreachable; } pub const ascii_vector_size = if (Environment.isWasm) 8 else 16; pub const ascii_u16_vector_size = if (Environment.isWasm) 4 else 8; pub const AsciiVectorInt = std.meta.Int(.unsigned, ascii_vector_size); pub const AsciiVectorIntU16 = std.meta.Int(.unsigned, ascii_u16_vector_size); pub const max_16_ascii: @Vector(ascii_vector_size, u8) = @splat(@as(u8, 127)); pub const min_16_ascii: @Vector(ascii_vector_size, u8) = @splat(@as(u8, 0x20)); pub const max_u16_ascii: @Vector(ascii_u16_vector_size, u16) = @splat(@as(u16, 127)); pub const min_u16_ascii: @Vector(ascii_u16_vector_size, u16) = @splat(@as(u16, 0x20)); pub const AsciiVector = @Vector(ascii_vector_size, u8); pub const AsciiVectorSmall = @Vector(8, u8); pub const AsciiVectorU1 = @Vector(ascii_vector_size, u1); pub const AsciiVectorU1Small = @Vector(8, u1); pub const AsciiVectorU16U1 = @Vector(ascii_u16_vector_size, u1); pub const AsciiU16Vector = @Vector(ascii_u16_vector_size, u16); pub const max_4_ascii: @Vector(4, u8) = @splat(@as(u8, 127)); pub fn isAllASCII(slice: []const u8) bool { if (bun.FeatureFlags.use_simdutf) return bun.simdutf.validate.ascii(slice); var remaining = slice; // The NEON SIMD unit is 128-bit wide and includes 16 128-bit registers that can be used as 32 64-bit registers if (comptime Environment.enableSIMD) { const remaining_end_ptr = remaining.ptr + remaining.len - (remaining.len % ascii_vector_size); while (remaining.ptr != remaining_end_ptr) : (remaining.ptr += ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; if (@reduce(.Max, vec) > 127) { return false; } } } const Int = u64; const size = @sizeOf(Int); const remaining_last8 = slice.ptr + slice.len - (slice.len % size); while (remaining.ptr != remaining_last8) : (remaining.ptr += size) { const bytes = @as(Int, @bitCast(remaining[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { return false; } } const final = slice.ptr + slice.len; while (remaining.ptr != final) : (remaining.ptr += 1) { if (remaining[0] > 127) { return false; } } return true; } pub fn isAllASCIISimple(comptime slice: []const u8) bool { for (slice) |char| { if (char > 127) { return false; } } return true; } //#define U16_LEAD(supplementary) (UChar)(((supplementary)>>10)+0xd7c0) pub inline fn u16Lead(supplementary: anytype) u16 { return @as(u16, @intCast((supplementary >> 10) + 0xd7c0)); } //#define U16_TRAIL(supplementary) (UChar)(((supplementary)&0x3ff)|0xdc00) pub inline fn u16Trail(supplementary: anytype) u16 { return @as(u16, @intCast((supplementary & 0x3ff) | 0xdc00)); } pub fn firstNonASCII(slice: []const u8) ?u32 { return firstNonASCIIWithType([]const u8, slice); } pub fn firstNonASCIIWithType(comptime Type: type, slice: Type) ?u32 { var remaining = slice; if (comptime bun.FeatureFlags.use_simdutf) { const result = bun.simdutf.validate.with_errors.ascii(slice); if (result.status == .success) { return null; } return @as(u32, @truncate(result.count)); } if (comptime Environment.enableSIMD) { if (remaining.len >= ascii_vector_size) { const remaining_start = remaining.ptr; const remaining_end = remaining.ptr + remaining.len - (remaining.len % ascii_vector_size); while (remaining.ptr != remaining_end) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; if (@reduce(.Max, vec) > 127) { const Int = u64; const size = @sizeOf(Int); remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start); { const bytes = @as(Int, @bitCast(remaining[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) { std.debug.assert(remaining[first_set_byte] > 127); var j: usize = 0; while (j < first_set_byte) : (j += 1) { std.debug.assert(remaining[j] <= 127); } } return @as(u32, first_set_byte) + @as(u32, @intCast(slice.len - remaining.len)); } remaining = remaining[size..]; } { const bytes = @as(Int, @bitCast(remaining[0..size].*)); const mask = bytes & 0x8080808080808080; if (mask > 0) { const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) { std.debug.assert(remaining[first_set_byte] > 127); var j: usize = 0; while (j < first_set_byte) : (j += 1) { std.debug.assert(remaining[j] <= 127); } } return @as(u32, first_set_byte) + @as(u32, @intCast(slice.len - remaining.len)); } } unreachable; } // the more intuitive way, using slices, produces worse codegen // specifically: it subtracts the length at the end of the loop // we don't need to do that // we only need to subtract the length once at the very end remaining.ptr += ascii_vector_size; } remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start); } } { const Int = u64; const size = @sizeOf(Int); const remaining_start = remaining.ptr; const remaining_end = remaining.ptr + remaining.len - (remaining.len % size); if (comptime Environment.enableSIMD) { // these assertions exist more so for LLVM std.debug.assert(remaining.len < ascii_vector_size); std.debug.assert(@intFromPtr(remaining.ptr + ascii_vector_size) > @intFromPtr(remaining_end)); } if (remaining.len >= size) { while (remaining.ptr != remaining_end) { const bytes = @as(Int, @bitCast(remaining[0..size].*)); // https://dotat.at/@/2022-06-27-tolower-swar.html const mask = bytes & 0x8080808080808080; if (mask > 0) { remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start); const first_set_byte = @ctz(mask) / 8; if (comptime Environment.allow_assert) { std.debug.assert(remaining[first_set_byte] > 127); var j: usize = 0; while (j < first_set_byte) : (j += 1) { std.debug.assert(remaining[j] <= 127); } } return @as(u32, first_set_byte) + @as(u32, @intCast(slice.len - remaining.len)); } remaining.ptr += size; } remaining.len -= @intFromPtr(remaining.ptr) - @intFromPtr(remaining_start); } } if (comptime Environment.allow_assert) std.debug.assert(remaining.len < 8); for (remaining) |*char| { if (char.* > 127) { // try to prevent it from reading the length of the slice return @as(u32, @truncate(@intFromPtr(char) - @intFromPtr(slice.ptr))); } } return null; } pub fn indexOfNewlineOrNonASCIIOrANSI(slice_: []const u8, offset: u32) ?u32 { const slice = slice_[offset..]; var remaining = slice; if (remaining.len == 0) return null; if (comptime Environment.enableSIMD) { while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; const cmp = @as(AsciiVectorU1, @bitCast((vec > max_16_ascii))) | @as(AsciiVectorU1, @bitCast((vec < min_16_ascii))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\r'))))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\n'))))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\x1b'))))); if (@reduce(.Max, cmp) > 0) { const bitmask = @as(AsciiVectorInt, @bitCast(cmp)); const first = @ctz(bitmask); return @as(u32, first) + @as(u32, @intCast(slice.len - remaining.len)) + offset; } remaining = remaining[ascii_vector_size..]; } if (comptime Environment.allow_assert) std.debug.assert(remaining.len < ascii_vector_size); } for (remaining) |*char_| { const char = char_.*; if (char > 127 or char < 0x20 or char == '\n' or char == '\r' or char == '\x1b') { return @as(u32, @truncate((@intFromPtr(char_) - @intFromPtr(slice.ptr)))) + offset; } } return null; } pub fn indexOfNewlineOrNonASCII(slice_: []const u8, offset: u32) ?u32 { return indexOfNewlineOrNonASCIICheckStart(slice_, offset, true); } pub fn indexOfNewlineOrNonASCIICheckStart(slice_: []const u8, offset: u32, comptime check_start: bool) ?u32 { const slice = slice_[offset..]; var remaining = slice; if (remaining.len == 0) return null; if (comptime check_start) { // this shows up in profiling if (remaining[0] > 127 or remaining[0] < 0x20 or remaining[0] == '\r' or remaining[0] == '\n') { return offset; } } if (comptime Environment.enableSIMD) { while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; const cmp = @as(AsciiVectorU1, @bitCast((vec > max_16_ascii))) | @as(AsciiVectorU1, @bitCast((vec < min_16_ascii))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\r'))))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\n'))))); if (@reduce(.Max, cmp) > 0) { const bitmask = @as(AsciiVectorInt, @bitCast(cmp)); const first = @ctz(bitmask); return @as(u32, first) + @as(u32, @intCast(slice.len - remaining.len)) + offset; } remaining = remaining[ascii_vector_size..]; } if (comptime Environment.allow_assert) std.debug.assert(remaining.len < ascii_vector_size); } for (remaining) |*char_| { const char = char_.*; if (char > 127 or char < 0x20 or char == '\n' or char == '\r') { return @as(u32, @truncate((@intFromPtr(char_) - @intFromPtr(slice.ptr)))) + offset; } } return null; } pub fn containsNewlineOrNonASCIIOrQuote(slice_: []const u8) bool { const slice = slice_; var remaining = slice; if (remaining.len == 0) return false; if (comptime Environment.enableSIMD) { while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; const cmp = @as(AsciiVectorU1, @bitCast((vec > max_16_ascii))) | @as(AsciiVectorU1, @bitCast((vec < min_16_ascii))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\r'))))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\n'))))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '"'))))); if (@reduce(.Max, cmp) > 0) { return true; } remaining = remaining[ascii_vector_size..]; } if (comptime Environment.allow_assert) std.debug.assert(remaining.len < ascii_vector_size); } for (remaining) |*char_| { const char = char_.*; if (char > 127 or char < 0x20 or char == '\n' or char == '\r' or char == '"') { return true; } } return false; } pub fn indexOfNeedsEscape(slice: []const u8) ?u32 { var remaining = slice; if (remaining.len == 0) return null; if (remaining[0] >= 127 or remaining[0] < 0x20 or remaining[0] == '\\' or remaining[0] == '"') { return 0; } if (comptime Environment.enableSIMD) { while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; const cmp = @as(AsciiVectorU1, @bitCast((vec > max_16_ascii))) | @as(AsciiVectorU1, @bitCast((vec < min_16_ascii))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '\\'))))) | @as(AsciiVectorU1, @bitCast(vec == @as(AsciiVector, @splat(@as(u8, '"'))))); if (@reduce(.Max, cmp) > 0) { const bitmask = @as(AsciiVectorInt, @bitCast(cmp)); const first = @ctz(bitmask); return @as(u32, first) + @as(u32, @truncate(@intFromPtr(remaining.ptr) - @intFromPtr(slice.ptr))); } remaining = remaining[ascii_vector_size..]; } } for (remaining) |*char_| { const char = char_.*; if (char > 127 or char < 0x20 or char == '\\' or char == '"') { return @as(u32, @truncate(@intFromPtr(char_) - @intFromPtr(slice.ptr))); } } return null; } test "indexOfNeedsEscape" { const out = indexOfNeedsEscape( \\la la la la la la la la la la la la la la la la "oh!" okay "well" , ); try std.testing.expectEqual(out.?, 48); } pub fn indexOfCharZ(sliceZ: [:0]const u8, char: u8) ?u63 { const ptr = bun.C.strchr(sliceZ.ptr, char) orelse return null; const pos = @intFromPtr(ptr) - @intFromPtr(sliceZ.ptr); if (comptime Environment.allow_assert) std.debug.assert(@intFromPtr(sliceZ.ptr) <= @intFromPtr(ptr) and @intFromPtr(ptr) < @intFromPtr(sliceZ.ptr + sliceZ.len) and pos <= sliceZ.len); return @as(u63, @truncate(pos)); } pub fn indexOfChar(slice: []const u8, char: u8) ?u32 { return @as(u32, @truncate(indexOfCharUsize(slice, char) orelse return null)); } pub fn indexOfCharUsize(slice: []const u8, char: u8) ?usize { if (slice.len == 0) return null; if (comptime !Environment.isNative) { return std.mem.indexOfScalar(u8, slice, char); } const ptr = bun.C.memchr(slice.ptr, char, slice.len) orelse return null; const i = @intFromPtr(ptr) - @intFromPtr(slice.ptr); std.debug.assert(i < slice.len); std.debug.assert(slice[i] == char); return i; } test "indexOfChar" { const pairs = .{ .{ "fooooooboooooofoooooofoooooofoooooofoooooozball", 'b', }, .{ "foooooofoooooofoooooofoooooofoooooofoooooozball", 'z', }, .{ "foooooofoooooofoooooofoooooofoooooofoooooozball", 'a', }, .{ "foooooofoooooofoooooofoooooofoooooofoooooozball", 'l', }, .{ "baconaopsdkaposdkpaosdkpaosdkaposdkpoasdkpoaskdpoaskdpoaskdpo;", ';', }, .{ ";baconaopsdkaposdkpaosdkpaosdkaposdkpoasdkpoaskdpoaskdpoaskdpo;", ';', }, }; inline for (pairs) |pair| { try std.testing.expectEqual( indexOfChar(pair.@"0", pair.@"1").?, @as(u32, @truncate(std.mem.indexOfScalar(u8, pair.@"0", pair.@"1").?)), ); } } pub fn indexOfNotChar(slice: []const u8, char: u8) ?u32 { var remaining = slice; if (remaining.len == 0) return null; if (remaining[0] != char) return 0; if (comptime Environment.enableSIMD) { while (remaining.len >= ascii_vector_size) { const vec: AsciiVector = remaining[0..ascii_vector_size].*; const cmp = @as(AsciiVector, @splat(char)) != vec; if (@reduce(.Max, @as(AsciiVectorU1, @bitCast(cmp))) > 0) { const bitmask = @as(AsciiVectorInt, @bitCast(cmp)); const first = @ctz(bitmask); return @as(u32, first) + @as(u32, @intCast(slice.len - remaining.len)); } remaining = remaining[ascii_vector_size..]; } } for (remaining) |*current| { if (current.* != char) { return @as(u32, @truncate(@intFromPtr(current) - @intFromPtr(slice.ptr))); } } return null; } const invalid_char: u8 = 0xff; const hex_table: [255]u8 = brk: { var values: [255]u8 = [_]u8{invalid_char} ** 255; values['0'] = 0; values['1'] = 1; values['2'] = 2; values['3'] = 3; values['4'] = 4; values['5'] = 5; values['6'] = 6; values['7'] = 7; values['8'] = 8; values['9'] = 9; values['A'] = 10; values['B'] = 11; values['C'] = 12; values['D'] = 13; values['E'] = 14; values['F'] = 15; values['a'] = 10; values['b'] = 11; values['c'] = 12; values['d'] = 13; values['e'] = 14; values['f'] = 15; break :brk values; }; pub fn decodeHexToBytes(destination: []u8, comptime Char: type, source: []const Char) !usize { return _decodeHexToBytes(destination, Char, source, false); } pub fn decodeHexToBytesTruncate(destination: []u8, comptime Char: type, source: []const Char) usize { return _decodeHexToBytes(destination, Char, source, true) catch 0; } inline fn _decodeHexToBytes(destination: []u8, comptime Char: type, source: []const Char, comptime truncate: bool) !usize { var remain = destination; var input = source; while (remain.len > 0 and input.len > 1) { const int = input[0..2].*; if (comptime @sizeOf(Char) > 1) { if (int[0] > std.math.maxInt(u8) or int[1] > std.math.maxInt(u8)) { if (comptime truncate) break; return error.InvalidByteSequence; } } const a = hex_table[@as(u8, @truncate(int[0]))]; const b = hex_table[@as(u8, @truncate(int[1]))]; if (a == invalid_char or b == invalid_char) { if (comptime truncate) break; return error.InvalidByteSequence; } remain[0] = a << 4 | b; remain = remain[1..]; input = input[2..]; } if (comptime !truncate) { if (remain.len > 0 and input.len > 0) return error.InvalidByteSequence; } return destination.len - remain.len; } fn byte2hex(char: u8) u8 { return switch (char) { 0...9 => char + '0', 10...15 => char - 10 + 'a', else => unreachable, }; } pub fn encodeBytesToHex(destination: []u8, source: []const u8) usize { if (comptime Environment.allow_assert) { std.debug.assert(destination.len > 0); std.debug.assert(source.len > 0); } const to_write = if (destination.len < source.len * 2) destination.len - destination.len % 2 else source.len * 2; const to_read = to_write / 2; var remaining = source[0..to_read]; var remaining_dest = destination; if (comptime Environment.enableSIMD) { var remaining_end = remaining.ptr + remaining.len - (remaining.len % 16); while (remaining.ptr != remaining_end) { const input_chunk: @Vector(16, u8) = remaining[0..16].*; const input_chunk_4: @Vector(16, u8) = input_chunk >> @as(@Vector(16, u8), @splat(@as(u8, 4))); const input_chunk_15: @Vector(16, u8) = input_chunk & @as(@Vector(16, u8), @splat(@as(u8, 15))); // This looks extremely redundant but it was the easiest way to make the compiler do the right thing // the more convienient "0123456789abcdef" string produces worse codegen // https://zig.godbolt.org/z/bfdracEeq const lower_16 = [16]u8{ byte2hex(input_chunk_4[0]), byte2hex(input_chunk_4[1]), byte2hex(input_chunk_4[2]), byte2hex(input_chunk_4[3]), byte2hex(input_chunk_4[4]), byte2hex(input_chunk_4[5]), byte2hex(input_chunk_4[6]), byte2hex(input_chunk_4[7]), byte2hex(input_chunk_4[8]), byte2hex(input_chunk_4[9]), byte2hex(input_chunk_4[10]), byte2hex(input_chunk_4[11]), byte2hex(input_chunk_4[12]), byte2hex(input_chunk_4[13]), byte2hex(input_chunk_4[14]), byte2hex(input_chunk_4[15]), }; const upper_16 = [16]u8{ byte2hex(input_chunk_15[0]), byte2hex(input_chunk_15[1]), byte2hex(input_chunk_15[2]), byte2hex(input_chunk_15[3]), byte2hex(input_chunk_15[4]), byte2hex(input_chunk_15[5]), byte2hex(input_chunk_15[6]), byte2hex(input_chunk_15[7]), byte2hex(input_chunk_15[8]), byte2hex(input_chunk_15[9]), byte2hex(input_chunk_15[10]), byte2hex(input_chunk_15[11]), byte2hex(input_chunk_15[12]), byte2hex(input_chunk_15[13]), byte2hex(input_chunk_15[14]), byte2hex(input_chunk_15[15]), }; const output_chunk = std.simd.interlace(.{ lower_16, upper_16, }); remaining_dest[0..32].* = @bitCast(output_chunk); remaining_dest = remaining_dest[32..]; remaining = remaining[16..]; } } for (remaining) |c| { const charset = "0123456789abcdef"; const buf: [2]u8 = .{ charset[c >> 4], charset[c & 15] }; remaining_dest[0..2].* = buf; remaining_dest = remaining_dest[2..]; } return to_read * 2; } test "decodeHexToBytes" { var buffer = std.mem.zeroes([1024]u8); for (buffer, 0..) |_, i| { buffer[i] = @as(u8, @truncate(i % 256)); } var written: [2048]u8 = undefined; var hex = std.fmt.bufPrint(&written, "{}", .{std.fmt.fmtSliceHexLower(&buffer)}) catch unreachable; var good: [4096]u8 = undefined; var ours_buf: [4096]u8 = undefined; var match = try std.fmt.hexToBytes(good[0..1024], hex); var ours = decodeHexToBytes(&ours_buf, u8, hex); try std.testing.expectEqualSlices(u8, match, ours_buf[0..ours]); try std.testing.expectEqualSlices(u8, &buffer, ours_buf[0..ours]); } // test "formatBytesToHex" { // var buffer = std.mem.zeroes([1024]u8); // for (buffer) |_, i| { // buffer[i] = @truncate(u8, i % 256); // } // var written: [2048]u8 = undefined; // var hex = std.fmt.bufPrint(&written, "{}", .{std.fmt.fmtSliceHexLower(&buffer)}) catch unreachable; // var ours_buf: [4096]u8 = undefined; // // var ours = formatBytesToHex(&ours_buf, &buffer); // // try std.testing.expectEqualSlices(u8, match, ours_buf[0..ours]); // try std.testing.expectEqualSlices(u8, &buffer, ours_buf[0..ours]); // } pub fn trimLeadingChar(slice: []const u8, char: u8) []const u8 { if (indexOfNotChar(slice, char)) |i| { return slice[i..]; } return ""; } pub fn firstNonASCII16(comptime Slice: type, slice: Slice) ?u32 { return firstNonASCII16CheckMin(Slice, slice, true); } /// Get the line number and the byte offsets of `line_range_count` above the desired line number /// The final element is the end index of the desired line pub fn indexOfLineNumber(text: []const u8, line: u32, comptime line_range_count: usize) ?[line_range_count + 1]u32 { var ranges = std.mem.zeroes([line_range_count + 1]u32); var remaining = text; if (remaining.len == 0 or line == 0) return null; var iter = CodepointIterator.init(text); var cursor = CodepointIterator.Cursor{}; var count: u32 = 0; while (iter.next(&cursor)) { switch (cursor.c) { '\n', '\r' => { if (cursor.c == '\r' and text[cursor.i..].len > 0 and text[cursor.i + 1] == '\n') { cursor.i += 1; } if (comptime line_range_count > 1) { comptime var i: usize = 0; inline while (i < line_range_count) : (i += 1) { std.mem.swap(u32, &ranges[i], &ranges[i + 1]); } } else { ranges[0] = ranges[1]; } ranges[line_range_count] = cursor.i; if (count == line) { return ranges; } count += 1; }, else => {}, } } return null; } /// Get N lines from the start of the text pub fn getLinesInText(text: []const u8, line: u32, comptime line_range_count: usize) ?[line_range_count][]const u8 { const ranges = indexOfLineNumber(text, line, line_range_count) orelse return null; var results = std.mem.zeroes([line_range_count][]const u8); var i: usize = 0; var any_exist = false; while (i < line_range_count) : (i += 1) { results[i] = text[ranges[i]..ranges[i + 1]]; any_exist = any_exist or results[i].len > 0; } if (!any_exist) return null; return results; } pub fn firstNonASCII16CheckMin(comptime Slice: type, slice: Slice, comptime check_min: bool) ?u32 { var remaining = slice; if (comptime Environment.enableSIMD and Environment.isNative) { const end_ptr = remaining.ptr + remaining.len - (remaining.len % ascii_u16_vector_size); if (remaining.len > ascii_u16_vector_size) { const remaining_start = remaining.ptr; while (remaining.ptr != end_ptr) { const vec: AsciiU16Vector = remaining[0..ascii_u16_vector_size].*; const max_value = @reduce(.Max, vec); if (comptime check_min) { // by using @reduce here, we make it only do one comparison // @reduce doesn't tell us the index though const min_value = @reduce(.Min, vec); if (min_value < 0x20 or max_value > 127) { remaining.len -= (@intFromPtr(remaining.ptr) - @intFromPtr(remaining_start)) / 2; // this is really slow // it does it element-wise for every single u8 on the vector // instead of doing the SIMD instructions // it removes a loop, but probably is slower in the end const cmp = @as(AsciiVectorU16U1, @bitCast(vec > max_u16_ascii)) | @as(AsciiVectorU16U1, @bitCast(vec < min_u16_ascii)); const bitmask: u8 = @as(u8, @bitCast(cmp)); const first = @ctz(bitmask); return @as(u32, @intCast(@as(u32, first) + @as(u32, @intCast(slice.len - remaining.len)))); } } else if (comptime !check_min) { if (max_value > 127) { remaining.len -= (@intFromPtr(remaining.ptr) - @intFromPtr(remaining_start)) / 2; const cmp = vec > max_u16_ascii; const bitmask: u8 = @as(u8, @bitCast(cmp)); const first = @ctz(bitmask); return @as(u32, @intCast(@as(u32, first) + @as(u32, @intCast(slice.len - remaining.len)))); } } remaining.ptr += ascii_u16_vector_size; } remaining.len -= (@intFromPtr(remaining.ptr) - @intFromPtr(remaining_start)) / 2; } } if (comptime check_min) { var i: usize = 0; for (remaining) |char| { if (char > 127 or char < 0x20) { return @as(u32, @truncate(i)); } i += 1; } } else { var i: usize = 0; for (remaining) |char| { if (char > 127) { return @as(u32, @truncate(i)); } i += 1; } } return null; } /// Fast path for printing template literal strings pub fn @"nextUTF16NonASCIIOr$`\\"( comptime Slice: type, slice: Slice, ) ?u32 { var remaining = slice; if (comptime Environment.enableSIMD and Environment.isNative) { while (remaining.len >= ascii_u16_vector_size) { const vec: AsciiU16Vector = remaining[0..ascii_u16_vector_size].*; const cmp = @as(AsciiVectorU16U1, @bitCast((vec > max_u16_ascii))) | @as(AsciiVectorU16U1, @bitCast((vec < min_u16_ascii))) | @as(AsciiVectorU16U1, @bitCast((vec == @as(AsciiU16Vector, @splat(@as(u16, '$')))))) | @as(AsciiVectorU16U1, @bitCast((vec == @as(AsciiU16Vector, @splat(@as(u16, '`')))))) | @as(AsciiVectorU16U1, @bitCast((vec == @as(AsciiU16Vector, @splat(@as(u16, '\\')))))); const bitmask = @as(u8, @bitCast(cmp)); const first = @ctz(bitmask); if (first < ascii_u16_vector_size) { return @as(u32, @intCast(@as(u32, first) + @as(u32, @intCast(slice.len - remaining.len)))); } remaining = remaining[ascii_u16_vector_size..]; } } for (remaining, 0..) |char, i| { switch (char) { '$', '`', '\\', 0...0x20 - 1, 128...std.math.maxInt(u16) => { return @as(u32, @truncate(i + (slice.len - remaining.len))); }, else => {}, } } return null; } test "indexOfNotChar" { { var yes: [312]u8 = undefined; var i: usize = 0; while (i < yes.len) { @memset(yes, 'a'); yes[i] = 'b'; if (comptime Environment.allow_assert) std.debug.assert(indexOfNotChar(&yes, 'a').? == i); i += 1; } } } test "trimLeadingChar" { { const yes = " fooo bar"; try std.testing.expectEqualStrings(trimLeadingChar(yes, ' '), "fooo bar"); } } test "isAllASCII" { const yes = "aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"; try std.testing.expectEqual(true, isAllASCII(yes)); const no = "aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdoka🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"; try std.testing.expectEqual(false, isAllASCII(no)); } test "firstNonASCII" { const yes = "aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"; try std.testing.expectEqual(true, firstNonASCII(yes) == null); { const no = "aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdoka🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123"; try std.testing.expectEqual(@as(u32, 50), firstNonASCII(no).?); } { const no = "aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd12312🙂3"; try std.testing.expectEqual(@as(u32, 366), firstNonASCII(no).?); } } test "firstNonASCII16" { @setEvalBranchQuota(99999); const yes = std.mem.bytesAsSlice(u16, toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123")); try std.testing.expectEqual(true, firstNonASCII16(@TypeOf(yes), yes) == null); { @setEvalBranchQuota(99999); const no = std.mem.bytesAsSlice(u16, toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdoka🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123")); try std.testing.expectEqual(@as(u32, 50), firstNonASCII16(@TypeOf(no), no).?); } { @setEvalBranchQuota(99999); const no = std.mem.bytesAsSlice(u16, toUTF16Literal("🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123")); try std.testing.expectEqual(@as(u32, 0), firstNonASCII16(@TypeOf(no), no).?); } { @setEvalBranchQuota(99999); const no = std.mem.bytesAsSlice(u16, toUTF16Literal("a🙂sdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123")); try std.testing.expectEqual(@as(u32, 1), firstNonASCII16(@TypeOf(no), no).?); } { @setEvalBranchQuota(99999); const no = std.mem.bytesAsSlice(u16, toUTF16Literal("aspdokasdpokasdpokasd aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd123123aspdokasdpokasdpokasdaspdokasdpokasdpokasdaspdokasdpokasdpokasd12312🙂3")); try std.testing.expectEqual(@as(u32, 366), firstNonASCII16(@TypeOf(no), no).?); } } fn getSharedBuffer() []u8 { return std.mem.asBytes(shared_temp_buffer_ptr orelse brk: { shared_temp_buffer_ptr = bun.default_allocator.create([32 * 1024]u8) catch unreachable; break :brk shared_temp_buffer_ptr.?; }); } threadlocal var shared_temp_buffer_ptr: ?*[32 * 1024]u8 = null; pub fn formatUTF16Type(comptime Slice: type, slice_: Slice, writer: anytype) !void { var chunk = getSharedBuffer(); var slice = slice_; while (slice.len > 0) { const result = strings.copyUTF16IntoUTF8(chunk, Slice, slice, true); if (result.read == 0 or result.written == 0) break; try writer.writeAll(chunk[0..result.written]); slice = slice[result.read..]; } } pub fn formatUTF16(slice_: []align(1) const u16, writer: anytype) !void { return formatUTF16Type([]align(1) const u16, slice_, writer); } pub fn formatLatin1(slice_: []const u8, writer: anytype) !void { var chunk = getSharedBuffer(); var slice = slice_; while (strings.firstNonASCII(slice)) |i| { if (i > 0) { try writer.writeAll(slice[0..i]); slice = slice[i..]; } const result = strings.copyLatin1IntoUTF8(chunk, @TypeOf(slice), slice[0..@min(chunk.len, slice.len)]); if (result.read == 0 or result.written == 0) break; try writer.writeAll(chunk[0..result.written]); slice = slice[result.read..]; } if (slice.len > 0) try writer.writeAll(slice); // write the remaining bytes } test "print UTF16" { var err = std.io.getStdErr(); const utf16 = comptime toUTF16Literal("❌ ✅ opkay "); try formatUTF16(utf16, err.writer()); // std.unicode.fmtUtf16le(utf16le: []const u16) } /// Convert potentially ill-formed UTF-8 or UTF-16 bytes to a Unicode Codepoint. /// - Invalid codepoints are replaced with `zero` parameter /// - Null bytes return 0 pub fn decodeWTF8RuneT(p: *const [4]u8, len: u3, comptime T: type, comptime zero: T) T { if (len == 0) return zero; if (len == 1) return p[0]; return decodeWTF8RuneTMultibyte(p, len, T, zero); } pub fn codepointSize(comptime R: type, r: R) u3 { return switch (r) { 0b0000_0000...0b0111_1111 => 1, 0b1100_0000...0b1101_1111 => 2, 0b1110_0000...0b1110_1111 => 3, 0b1111_0000...0b1111_0111 => 4, else => 0, }; } // /// Encode Type into UTF-8 bytes. // /// - Invalid unicode data becomes U+FFFD REPLACEMENT CHARACTER. // /// - // pub fn encodeUTF8RuneT(out: *[4]u8, comptime R: type, c: R) u3 { // switch (c) { // 0b0000_0000...0b0111_1111 => { // out[0] = @intCast(u8, c); // return 1; // }, // 0b1100_0000...0b1101_1111 => { // out[0] = @truncate(u8, 0b11000000 | (c >> 6)); // out[1] = @truncate(u8, 0b10000000 | c & 0b111111); // return 2; // }, // 0b1110_0000...0b1110_1111 => { // if (0xd800 <= c and c <= 0xdfff) { // // Replacement character // out[0..3].* = [_]u8{ 0xEF, 0xBF, 0xBD }; // return 3; // } // out[0] = @truncate(u8, 0b11100000 | (c >> 12)); // out[1] = @truncate(u8, 0b10000000 | (c >> 6) & 0b111111); // out[2] = @truncate(u8, 0b10000000 | c & 0b111111); // return 3; // }, // 0b1111_0000...0b1111_0111 => { // out[0] = @truncate(u8, 0b11110000 | (c >> 18)); // out[1] = @truncate(u8, 0b10000000 | (c >> 12) & 0b111111); // out[2] = @truncate(u8, 0b10000000 | (c >> 6) & 0b111111); // out[3] = @truncate(u8, 0b10000000 | c & 0b111111); // return 4; // }, // else => { // // Replacement character // out[0..3].* = [_]u8{ 0xEF, 0xBF, 0xBD }; // return 3; // }, // } // } pub fn containsNonBmpCodePoint(text: string) bool { var iter = CodepointIterator.init(text); var curs = CodepointIterator.Cursor{}; while (iter.next(&curs)) { if (curs.c > 0xFFFF) { return true; } } return false; } // this is std.mem.trim except it doesn't forcibly change the slice to be const pub fn trim(slice: anytype, comptime values_to_strip: []const u8) @TypeOf(slice) { var begin: usize = 0; var end: usize = slice.len; while (begin < end and std.mem.indexOfScalar(u8, values_to_strip, slice[begin]) != null) : (begin += 1) {} while (end > begin and std.mem.indexOfScalar(u8, values_to_strip, slice[end - 1]) != null) : (end -= 1) {} return slice[begin..end]; } pub fn containsNonBmpCodePointUTF16(_text: []const u16) bool { const n = _text.len; if (n > 0) { var i: usize = 0; var text = _text[0 .. n - 1]; while (i < n - 1) : (i += 1) { switch (text[i]) { // Check for a high surrogate 0xD800...0xDBFF => { // Check for a low surrogate switch (text[i + 1]) { 0xDC00...0xDFFF => { return true; }, else => {}, } }, else => {}, } } } return false; } pub fn join(slices: []const string, delimiter: string, allocator: std.mem.Allocator) !string { return try std.mem.join(allocator, delimiter, slices); } pub fn order(a: []const u8, b: []const u8) std.math.Order { const len = @min(a.len, b.len); const cmp = if (comptime Environment.isNative) bun.C.memcmp(a.ptr, b.ptr, len) else return std.mem.order(u8, a, b); return switch (std.math.sign(cmp)) { 0 => std.math.order(a.len, b.len), 1 => .gt, -1 => .lt, else => unreachable, }; } pub fn cmpStringsAsc(_: void, a: string, b: string) bool { return order(a, b) == .lt; } pub fn cmpStringsDesc(_: void, a: string, b: string) bool { return order(a, b) == .gt; } const sort_asc = std.sort.asc(u8); const sort_desc = std.sort.desc(u8); pub fn sortAsc(in: []string) void { // TODO: experiment with simd to see if it's faster std.sort.block([]const u8, in, {}, cmpStringsAsc); } pub fn sortDesc(in: []string) void { // TODO: experiment with simd to see if it's faster std.sort.block([]const u8, in, {}, cmpStringsDesc); } pub const StringArrayByIndexSorter = struct { keys: []const []const u8, pub fn lessThan(sorter: *const @This(), a: usize, b: usize) bool { return strings.order(sorter.keys[a], sorter.keys[b]) == .lt; } pub fn init(keys: []const []const u8) @This() { return .{ .keys = keys, }; } }; pub fn isASCIIHexDigit(c: u8) bool { return std.ascii.isHex(c); } pub fn toASCIIHexValue(character: u8) u8 { if (comptime Environment.allow_assert) std.debug.assert(isASCIIHexDigit(character)); return switch (character) { 0...('A' - 1) => character - '0', else => (character - 'A' + 10) & 0xF, }; } pub inline fn utf8ByteSequenceLength(first_byte: u8) u3 { return switch (first_byte) { 0b0000_0000...0b0111_1111 => 1, 0b1100_0000...0b1101_1111 => 2, 0b1110_0000...0b1110_1111 => 3, 0b1111_0000...0b1111_0111 => 4, else => 0, }; } pub fn NewCodePointIterator(comptime CodePointType: type, comptime zeroValue: comptime_int) type { return struct { const Iterator = @This(); bytes: []const u8, i: usize, next_width: usize = 0, width: u3 = 0, c: CodePointType = zeroValue, pub const Cursor = struct { i: u32 = 0, c: CodePointType = zeroValue, width: u3 = 0, }; pub fn init(str: string) Iterator { return Iterator{ .bytes = str, .i = 0, .c = zeroValue }; } pub fn initOffset(str: string, i: usize) Iterator { return Iterator{ .bytes = str, .i = i, .c = zeroValue }; } pub inline fn next(it: *const Iterator, cursor: *Cursor) bool { const pos: u32 = @as(u32, cursor.width) + cursor.i; if (pos >= it.bytes.len) { return false; } const cp_len = wtf8ByteSequenceLength(it.bytes[pos]); const error_char = comptime std.math.minInt(CodePointType); const codepoint = @as( CodePointType, switch (cp_len) { 0 => return false, 1 => it.bytes[pos], else => decodeWTF8RuneTMultibyte(it.bytes[pos..].ptr[0..4], cp_len, CodePointType, error_char), }, ); cursor.* = Cursor{ .i = pos, .c = if (error_char != codepoint) codepoint else unicode_replacement, .width = if (codepoint != error_char) cp_len else 1, }; return true; } inline fn nextCodepointSlice(it: *Iterator) []const u8 { const bytes = it.bytes; const prev = it.i; const next_ = prev + it.next_width; if (bytes.len <= next_) return ""; const cp_len = utf8ByteSequenceLength(bytes[next_]); it.next_width = cp_len; it.i = @min(next_, bytes.len); const slice = bytes[prev..][0..cp_len]; it.width = @as(u3, @intCast(slice.len)); return slice; } pub fn needsUTF8Decoding(slice: string) bool { var it = Iterator{ .bytes = slice, .i = 0 }; while (true) { const part = it.nextCodepointSlice(); @setRuntimeSafety(false); switch (part.len) { 0 => return false, 1 => continue, else => return true, } } } pub fn scanUntilQuotedValueOrEOF(iter: *Iterator, comptime quote: CodePointType) usize { while (iter.c > -1) { if (!switch (iter.nextCodepoint()) { quote => false, '\\' => brk: { if (iter.nextCodepoint() == quote) { continue; } break :brk true; }, else => true, }) { return iter.i + 1; } } return iter.i; } pub fn nextCodepoint(it: *Iterator) CodePointType { const slice = it.nextCodepointSlice(); it.c = switch (slice.len) { 0 => zeroValue, 1 => @as(CodePointType, @intCast(slice[0])), 2 => @as(CodePointType, @intCast(std.unicode.utf8Decode2(slice) catch unreachable)), 3 => @as(CodePointType, @intCast(std.unicode.utf8Decode3(slice) catch unreachable)), 4 => @as(CodePointType, @intCast(std.unicode.utf8Decode4(slice) catch unreachable)), else => unreachable, }; return it.c; } /// Look ahead at the next n codepoints without advancing the iterator. /// If fewer than n codepoints are available, then return the remainder of the string. pub fn peek(it: *Iterator, n: usize) []const u8 { const original_i = it.i; defer it.i = original_i; var end_ix = original_i; var found: usize = 0; while (found < n) : (found += 1) { const next_codepoint = it.nextCodepointSlice() orelse return it.bytes[original_i..]; end_ix += next_codepoint.len; } return it.bytes[original_i..end_ix]; } }; } pub const CodepointIterator = NewCodePointIterator(CodePoint, -1); pub const UnsignedCodepointIterator = NewCodePointIterator(u32, 0); pub fn NewLengthSorter(comptime Type: type, comptime field: string) type { return struct { const LengthSorter = @This(); pub fn lessThan(_: LengthSorter, lhs: Type, rhs: Type) bool { return @field(lhs, field).len < @field(rhs, field).len; } }; } pub fn NewGlobLengthSorter(comptime Type: type, comptime field: string) type { return struct { const GlobLengthSorter = @This(); pub fn lessThan(_: GlobLengthSorter, lhs: Type, rhs: Type) bool { // Assert: keyA ends with "/" or contains only a single "*". // Assert: keyB ends with "/" or contains only a single "*". const key_a = @field(lhs, field); const key_b = @field(rhs, field); // Let baseLengthA be the index of "*" in keyA plus one, if keyA contains "*", or the length of keyA otherwise. // Let baseLengthB be the index of "*" in keyB plus one, if keyB contains "*", or the length of keyB otherwise. const star_a = indexOfChar(key_a, '*'); const star_b = indexOfChar(key_b, '*'); const base_length_a = star_a orelse key_a.len; const base_length_b = star_b orelse key_b.len; // If baseLengthA is greater than baseLengthB, return -1. // If baseLengthB is greater than baseLengthA, return 1. if (base_length_a > base_length_b) return true; if (base_length_b > base_length_a) return false; // If keyA does not contain "*", return 1. // If keyB does not contain "*", return -1. if (star_a == null) return false; if (star_b == null) return true; // If the length of keyA is greater than the length of keyB, return -1. // If the length of keyB is greater than the length of keyA, return 1. if (key_a.len > key_b.len) return true; if (key_b.len > key_a.len) return false; return false; } }; } /// Update all strings in a struct pointing to "from" to point to "to". pub fn moveAllSlices(comptime Type: type, container: *Type, from: string, to: string) void { const fields_we_care_about = comptime brk: { var count: usize = 0; for (std.meta.fields(Type)) |field| { if (std.meta.trait.isSlice(field.type) and std.meta.Child(field.type) == u8) { count += 1; } } var fields: [count][]const u8 = undefined; count = 0; for (std.meta.fields(Type)) |field| { if (std.meta.trait.isSlice(field.type) and std.meta.Child(field.type) == u8) { fields[count] = field.name; count += 1; } } break :brk fields; }; inline for (fields_we_care_about) |name| { const slice = @field(container, name); if ((@intFromPtr(from.ptr) + from.len) >= @intFromPtr(slice.ptr) + slice.len and (@intFromPtr(from.ptr) <= @intFromPtr(slice.ptr))) { @field(container, name) = moveSlice(slice, from, to); } } } pub fn moveSlice(slice: string, from: string, to: string) string { if (comptime Environment.allow_assert) { std.debug.assert(from.len <= to.len and from.len >= slice.len); // assert we are in bounds std.debug.assert( (@intFromPtr(from.ptr) + from.len) >= @intFromPtr(slice.ptr) + slice.len and (@intFromPtr(from.ptr) <= @intFromPtr(slice.ptr)), ); std.debug.assert(eqlLong(from, to[0..from.len], false)); // data should be identical } const ptr_offset = @intFromPtr(slice.ptr) - @intFromPtr(from.ptr); const result = to[ptr_offset..][0..slice.len]; if (comptime Environment.allow_assert) std.debug.assert(eqlLong(slice, result, false)); // data should be identical return result; } test "moveSlice" { var input: string = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; var cloned = try std.heap.page_allocator.dupe(u8, input); var slice = input[20..][0..10]; try std.testing.expectEqual(eqlLong(moveSlice(slice, input, cloned), slice, false), true); } test "moveAllSlices" { const Move = struct { foo: string, bar: string, baz: string, wrong: string, }; var input: string = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; var move = Move{ .foo = input[20..], .bar = input[30..], .baz = input[10..20], .wrong = "baz" }; var cloned = try std.heap.page_allocator.dupe(u8, input); moveAllSlices(Move, &move, input, cloned); var expected = Move{ .foo = cloned[20..], .bar = cloned[30..], .baz = cloned[10..20], .wrong = "bar" }; try std.testing.expectEqual(move.foo.ptr, expected.foo.ptr); try std.testing.expectEqual(move.bar.ptr, expected.bar.ptr); try std.testing.expectEqual(move.baz.ptr, expected.baz.ptr); try std.testing.expectEqual(move.foo.len, expected.foo.len); try std.testing.expectEqual(move.bar.len, expected.bar.len); try std.testing.expectEqual(move.baz.len, expected.baz.len); try std.testing.expect(move.wrong.ptr != expected.wrong.ptr); } test "join" { var string_list = &[_]string{ "abc", "def", "123", "hello" }; const list = try join(string_list, "-", std.heap.page_allocator); try std.testing.expectEqualStrings("abc-def-123-hello", list); } test "sortAsc" { var string_list = [_]string{ "abc", "def", "123", "hello" }; var sorted_string_list = [_]string{ "123", "abc", "def", "hello" }; var sorted_join = try join(&sorted_string_list, "-", std.heap.page_allocator); sortAsc(&string_list); var string_join = try join(&string_list, "-", std.heap.page_allocator); try std.testing.expectEqualStrings(sorted_join, string_join); } test "sortDesc" { var string_list = [_]string{ "abc", "def", "123", "hello" }; var sorted_string_list = [_]string{ "hello", "def", "abc", "123" }; var sorted_join = try join(&sorted_string_list, "-", std.heap.page_allocator); sortDesc(&string_list); var string_join = try join(&string_list, "-", std.heap.page_allocator); try std.testing.expectEqualStrings(sorted_join, string_join); } pub usingnamespace @import("exact_size_matcher.zig"); pub const unicode_replacement = 0xFFFD; pub const unicode_replacement_str = brk: { var out: [std.unicode.utf8CodepointSequenceLength(unicode_replacement) catch unreachable]u8 = undefined; _ = std.unicode.utf8Encode(unicode_replacement, &out) catch unreachable; break :brk out; }; test "eqlCaseInsensitiveASCII" { try std.testing.expect(eqlCaseInsensitiveASCII("abc", "ABC", true)); try std.testing.expect(eqlCaseInsensitiveASCII("abc", "abc", true)); try std.testing.expect(eqlCaseInsensitiveASCII("aBcD", "aBcD", true)); try std.testing.expect(!eqlCaseInsensitiveASCII("aBcD", "NOOO", true)); try std.testing.expect(!eqlCaseInsensitiveASCII("aBcD", "LENGTH CHECK", true)); } pub fn isIPAddress(input: []const u8) bool { var max_ip_address_buffer: [512]u8 = undefined; if (input.len > max_ip_address_buffer.len) return false; var sockaddr: std.os.sockaddr = undefined; @memset(std.mem.asBytes(&sockaddr), 0); @memcpy(max_ip_address_buffer[0..input.len], input); max_ip_address_buffer[input.len] = 0; var ip_addr_str: [:0]const u8 = max_ip_address_buffer[0..input.len :0]; return bun.c_ares.ares_inet_pton(std.os.AF.INET, ip_addr_str.ptr, &sockaddr) != 0 or bun.c_ares.ares_inet_pton(std.os.AF.INET6, ip_addr_str.ptr, &sockaddr) != 0; } pub fn isIPV6Address(input: []const u8) bool { var max_ip_address_buffer: [512]u8 = undefined; if (input.len > max_ip_address_buffer.len) return false; var sockaddr: std.os.sockaddr = undefined; @memset(std.mem.asBytes(&sockaddr), 0); @memcpy(max_ip_address_buffer[0..input.len], input); max_ip_address_buffer[input.len] = 0; var ip_addr_str: [:0]const u8 = max_ip_address_buffer[0..input.len :0]; return bun.c_ares.ares_inet_pton(std.os.AF.INET6, ip_addr_str.ptr, &sockaddr) != 0; } pub fn cloneNormalizingSeparators( allocator: std.mem.Allocator, input: []const u8, ) ![]u8 { // remove duplicate slashes in the file path var base = withoutTrailingSlash(input); var tokenized = std.mem.tokenize(u8, base, std.fs.path.sep_str); var buf = try allocator.alloc(u8, base.len + 2); if (comptime Environment.allow_assert) std.debug.assert(base.len > 0); if (base[0] == std.fs.path.sep) { buf[0] = std.fs.path.sep; } var remain = buf[@as(usize, @intFromBool(base[0] == std.fs.path.sep))..]; while (tokenized.next()) |token| { if (token.len == 0) continue; bun.copy(u8, remain, token); remain[token.len..][0] = std.fs.path.sep; remain = remain[token.len + 1 ..]; } if ((remain.ptr - 1) != buf.ptr and (remain.ptr - 1)[0] != std.fs.path.sep) { remain[0] = std.fs.path.sep; remain = remain[1..]; } remain[0] = 0; return buf[0 .. @intFromPtr(remain.ptr) - @intFromPtr(buf.ptr)]; } pub fn leftHasAnyInRight(to_check: []const string, against: []const string) bool { for (to_check) |check| { for (against) |item| { if (eqlLong(check, item, true)) return true; } } return false; } pub fn hasPrefixWithWordBoundary(input: []const u8, comptime prefix: []const u8) bool { if (hasPrefixComptime(input, prefix)) { if (input.len == prefix.len) return true; const next = input[prefix.len..]; var bytes: [4]u8 = .{ next[0], if (next.len > 1) next[1] else 0, if (next.len > 2) next[2] else 0, if (next.len > 3) next[3] else 0, }; if (!bun.js_lexer.isIdentifierContinue(decodeWTF8RuneT(&bytes, wtf8ByteSequenceLength(next[0]), i32, -1))) { return true; } } return false; } pub fn concatWithLength( allocator: std.mem.Allocator, args: []const string, length: usize, ) !string { var out = try allocator.alloc(u8, length); var remain = out; for (args) |arg| { @memcpy(remain[0..arg.len], arg); remain = remain[arg.len..]; } std.debug.assert(remain.len == 0); // all bytes should be used return out; } pub fn concat( allocator: std.mem.Allocator, args: []const string, ) !string { var length: usize = 0; for (args) |arg| { length += arg.len; } return concatWithLength(allocator, args, length); } pub fn concatIfNeeded( allocator: std.mem.Allocator, dest: *[]const u8, args: []const string, interned_strings_to_check: []const string, ) !void { const total_length: usize = brk: { var length: usize = 0; for (args) |arg| { length += arg.len; } break :brk length; }; if (total_length == 0) { dest.* = ""; return; } if (total_length < 1024) { var stack = std.heap.stackFallback(1024, allocator); const stack_copy = concatWithLength(stack.get(), args, total_length) catch unreachable; for (interned_strings_to_check) |interned| { if (eqlLong(stack_copy, interned, true)) { dest.* = interned; return; } } } const is_needed = brk: { var out = dest.*; var remain = out; for (args) |arg| { if (args.len > remain.len) { break :brk true; } if (eqlLong(remain[0..args.len], arg, true)) { remain = remain[args.len..]; } else { break :brk true; } } break :brk false; }; if (!is_needed) return; var buf = try allocator.alloc(u8, total_length); dest.* = buf; var remain = buf[0..]; for (args) |arg| { @memcpy(remain[0..arg.len], arg); remain = remain[arg.len..]; } std.debug.assert(remain.len == 0); }
https://raw.githubusercontent.com/beingofexistence13/multiversal-lang/dd769e3fc6182c23ef43ed4479614f43f29738c9/javascript/bun/src/string_immutable.zig
const std = @import("std"); const core = @import("core.zig"); const ArrayListUnmanaged = std.ArrayListUnmanaged; const tracy = core.tracy; pub const Transform = core.Mat; pub const SceneAttachMode = enum { none, // default, parent attachment is irrelevant and not used relativePositionOnly, // only position is relative to parent transform relativeRotationOnly, // only rotation is relative to parent transform relative, // position and rotation are relative to parent transform snapToParentPositionOnly, // snaps to the parent's position, maintaining independent rotation (not implemented) snapToParentRotationOnly, // copys the parent's rotation, maintaining independent rotation (not implemented) snapToParent, // snaps to parent rotation and position }; pub const SceneMobilityMode = enum { static, // scene is updated once and never again moveable, // sceneobject is moveable and has it's final transform updated }; pub const SceneObjectPosRot = struct { position: core.Vectorf = .{ .x = 0, .y = 0, .z = 0 }, rotation: core.Rotation = core.Rotation.init(), scale: core.Vectorf = core.Vectorf.new(1.0, 1.0, 1.0), }; pub const SceneObjectSettings = struct { attachmentMode: SceneAttachMode = .none, sceneMode: SceneMobilityMode = .static, }; pub const SceneObjectRepr = struct { // fields intended to be internally used, don't touch them // unless you know what you're doing transform: core.Mat = core.zm.identity(), parent: ?core.ObjectHandle = null, attachmentMode: SceneAttachMode = .relative, }; pub const SceneObject = struct { posRot: SceneObjectPosRot, // positionRotation _repr: SceneObjectRepr, settings: SceneObjectSettings, children: ArrayListUnmanaged(core.ObjectHandle), // --- these.. are all useless lmao pub fn getPosition(self: @This()) core.Vectorf { return self.posRot.position; } pub fn getRotation(self: @This()) core.Rotation { return self.posRot.rotation; } pub fn getParent(self: @This()) ?core.ObjectHandle { return self._repr.parent; } pub fn getTransform(self: @This()) core.Transform { return self._repr.transform; } pub fn update(self: *@This()) void { self._repr.transform = core.zm.mul( core.zm.translationV(self.getPosition().toZm()), core.zm.matFromQuat(self.getRotation().quat), ); } // ---- pub fn init(params: SceneObjectInitParams) @This() { // Hmm thinking in the future we could have scene objects be f64s then crunch them down to f32s when we are submiting to gpu var self = @This(){ .posRot = .{}, ._repr = .{}, .settings = .{}, .children = .{}, }; const shouldUpdate: bool = false; // should mutate switch (params) { .transform => { self._repr.transform = params.transform; self.posRot.position = core.Vectorf.fromZm(core.zm.mul(params.transform, core.Vectorf.zero().toZm())); self.posRot.rotation = .{ .quat = core.zm.matToQuat(params.transform) }; }, .position => {}, .rotation => {}, .positionRotAngles => {}, .positionRot => {}, } if (shouldUpdate) { self.update(); } return self; } }; pub const SceneObjectInitParams = union(enum) { transform: core.Transform, position: core.Vectorf, rotation: core.Quat, positionRotAngles: struct { position: core.Vectorf = .{ .x = 0.0, .y = 0.0, .z = 0.0 }, angles: core.Vectorf = .{ .x = 0.0, .y = 0.0, .z = 0.0 }, }, positionRot: struct { position: core.Vectorf = .{ .x = 0.0, .y = 0.0, .z = 0.0 }, angles: core.Quat = core.zm.qidentity(), }, }; const SceneSet = core.SparseMultiSet(SceneObject); pub const SceneSystem = struct { pub var NeonObjectTable: core.RttiData = core.RttiData.from(@This()); allocator: std.mem.Allocator, objects: SceneSet, dynamicObjects: ArrayListUnmanaged(core.ObjectHandle) = .{}, pub const Field = SceneSet.Field; pub const FieldType = SceneSet.FieldType; // ----- creating and updating objects ----- // scene objects are the primary object type pub fn createSceneObject(self: *@This(), params: SceneObjectInitParams) !core.ObjectHandle { const newHandle = try self.objects.createObject(SceneObject.init(params)); return newHandle; } pub fn createSceneObjectWithHandle( self: *@This(), objectHandle: core.ObjectHandle, params: SceneObjectInitParams, ) !core.ObjectHandle { const newHandle = try self.objects.createWithHandle(objectHandle, SceneObject.init(params)); return newHandle; } pub fn setPosition(self: *@This(), handle: core.ObjectHandle, position: core.Vectorf) void { self.objects.get(handle, .posRot).?.*.position = position; } pub fn setRotation(self: *@This(), handle: core.ObjectHandle, rotation: core.Rotation) void { self.objects.get(handle, .posRot).?.*.rotation = rotation; } pub fn setScale(self: *@This(), handle: core.ObjectHandle, x: f32, y: f32, z: f32) void { self.objects.get(handle, .posRot).?.*.scale = .{ .x = x, .y = y, .z = z }; } pub fn setScaleV(self: *@This(), handle: core.ObjectHandle, scale: core.Vectorf) void { self.objects.get(handle, .posRot).?.*.scale = scale; } pub fn getPosition(self: *@This(), handle: core.ObjectHandle) core.Vectorf { return self.objects.get(handle, .posRot).?.position; } pub fn getRotation(self: *@This(), handle: core.ObjectHandle) core.Rotation { return self.objects.get(handle, .posRot).?.rotation; } pub fn getParent(self: *@This(), handle: core.ObjectHandle) ?core.ObjectHandle { return self.objects.get(handle, ._repr).?.parent; } pub fn getTransform(self: *@This(), handle: core.ObjectHandle) core.Transform { return self.objects.get(handle, ._repr).?.transform; } // ----- subsystem update procedures // internal update transform function fn updateTransform(self: *@This(), repr: *SceneObjectRepr, posRot: SceneObjectPosRot) void { _ = self; repr.*.transform = core.zm.mul( core.zm.mul( core.zm.scalingV(posRot.scale.toZm()), core.zm.matFromQuat(posRot.rotation.quat), ), core.zm.translationV(posRot.position.toZm()), ); } pub fn updateTransforms(self: *@This()) void { for (self.objects.denseItems(._repr), 0..) |*repr, i| { const settings = self.objects.readDense(i, .settings); if (settings.sceneMode == .moveable) { const posRot = self.objects.readDense(i, .posRot); self.updateTransform(repr, posRot.*); } } } // ----- NeonObject interace ---- pub fn init(allocator: std.mem.Allocator) !*@This() { const self = try allocator.create(@This()); self.* = .{ .allocator = allocator, .objects = SceneSet.init(allocator), }; return self; } pub fn setMobility(self: *@This(), objectHandle: core.ObjectHandle, mobility: SceneMobilityMode) !void { const settings = self.objects.get(objectHandle, .settings).?; if (mobility == .moveable) { if (settings.sceneMode == .static) { try self.dynamicObjects.append(self.allocator, objectHandle); } } if (mobility == .static) { if (settings.sceneMode == .moveable) { core.engine_errs("TODO: Changing sceneMode from moveable back to static is not supported yet."); unreachable; } } settings.*.sceneMode = mobility; } pub fn get(self: *@This(), handle: core.ObjectHandle, comptime field: Field) ?*FieldType(field) { return self.objects.get(handle, field); } pub fn tick(self: *@This(), deltaTime: f64) void { _ = self; var z = tracy.ZoneNC(@src(), "Scene System Tick", 0xAABBDD); defer z.End(); _ = deltaTime; } pub fn deinit(self: *@This()) void { self.objects.deinit(); self.allocator.destroy(self); } };
https://raw.githubusercontent.com/peterino2/NeonWood/705a04e06aa60736e0af02ad00cd0d4c37f07921/engine/core/src/scene.zig
const PacketNumberSpace = @import("../packet_number_space.zig").PacketNumberSpace; pub const PacketType = enum { // Long Header Packets // https://www.rfc-editor.org/rfc/rfc9000.html#name-long-header-packets initial, zero_rtt, handshake, retry, // This packet type is not identified by the packet type field; // but by the fact that the version field is not present. version_negotiation, // Short Header Packets // https://www.rfc-editor.org/rfc/rfc9000.html#name-short-header-packets // This is the only packet type that uses a short header in QUIC v1, so we can identify it // by the fact that header form field is equal to 0 (meaning it's a short-header packet). one_rtt, const Self = @This(); pub fn fromPacketNumberSpace(space_type: PacketNumberSpace.SpaceType) Self { return switch (space_type) { .initial => .initial, .handshake => .handshake, .application_data => .one_rtt, }; } };
https://raw.githubusercontent.com/shiguredo/quic-server-zig/5e4a03df1063cf673b4ed9811e7280e6ddb1d2cc/src/packet/packet_type.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); // Standard release options allow the person running `zig build` to select // between Debug, ReleaseSafe, ReleaseFast, and ReleaseSmall. const mode = b.standardReleaseOptions(); //const lib = b.addStaticLibrary("yz-devpkg", "src/main.zig"); //lib.setBuildMode(mode); //lib.install(); const main_tests = b.addTest("src/main.zig"); main_tests.setBuildMode(mode); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); const mmzx = b.addExecutable("mmzx", "src/mmzx.zig"); mmzx.setTarget(target); mmzx.setBuildMode(mode); mmzx.install(); const mmzx_run_cmd = mmzx.run(); mmzx_run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { mmzx_run_cmd.addArgs(args); } const mmzx_run_step = b.step("run-mmzx", "Run mmzx"); mmzx_run_step.dependOn(&mmzx_run_cmd.step); const all = b.step("all", "Build all executables"); all.dependOn(test_step); all.dependOn(&mmzx.step); all.dependOn(b.getInstallStep()); }
https://raw.githubusercontent.com/YZITE/devpkg/6fbc88ba76707b8fe673708e19a8b77300e11155/build.zig
const std = @import("std"); const Type = @import("type.zig").Type; const log2 = std.math.log2; const assert = std.debug.assert; const BigIntConst = std.math.big.int.Const; const BigIntMutable = std.math.big.int.Mutable; const Target = std.Target; const Allocator = std.mem.Allocator; const Module = @import("Module.zig"); const ir = @import("air.zig"); /// This is the raw data, with no bookkeeping, no memory awareness, /// no de-duplication, and no type system awareness. /// It's important for this type to be small. /// This union takes advantage of the fact that the first page of memory /// is unmapped, giving us 4096 possible enum tags that have no payload. pub const Value = extern union { /// If the tag value is less than Tag.no_payload_count, then no pointer /// dereference is needed. tag_if_small_enough: usize, ptr_otherwise: *Payload, pub const Tag = enum { // The first section of this enum are tags that require no payload. u8_type, i8_type, u16_type, i16_type, u32_type, i32_type, u64_type, i64_type, u128_type, i128_type, usize_type, isize_type, c_short_type, c_ushort_type, c_int_type, c_uint_type, c_long_type, c_ulong_type, c_longlong_type, c_ulonglong_type, c_longdouble_type, f16_type, f32_type, f64_type, f128_type, c_void_type, bool_type, void_type, type_type, anyerror_type, comptime_int_type, comptime_float_type, noreturn_type, anyframe_type, null_type, undefined_type, enum_literal_type, atomic_ordering_type, atomic_rmw_op_type, calling_convention_type, float_mode_type, reduce_op_type, call_options_type, export_options_type, extern_options_type, manyptr_u8_type, manyptr_const_u8_type, fn_noreturn_no_args_type, fn_void_no_args_type, fn_naked_noreturn_no_args_type, fn_ccc_void_no_args_type, single_const_pointer_to_comptime_int_type, const_slice_u8_type, undef, zero, one, void_value, unreachable_value, null_value, bool_true, bool_false, abi_align_default, empty_struct_value, empty_array, // See last_no_payload_tag below. // After this, the tag requires a payload. ty, int_type, int_u64, int_i64, int_big_positive, int_big_negative, function, extern_fn, variable, /// Represents a pointer to another immutable value. ref_val, /// Represents a comptime variables storage. comptime_alloc, /// Represents a pointer to a decl, not the value of the decl. decl_ref, elem_ptr, field_ptr, /// A slice of u8 whose memory is managed externally. bytes, /// This value is repeated some number of times. The amount of times to repeat /// is stored externally. repeated, float_16, float_32, float_64, float_128, enum_literal, /// A specific enum tag, indicated by the field index (declaration order). enum_field_index, @"error", error_union, /// An instance of a struct. @"struct", /// An instance of a union. @"union", /// This is a special value that tracks a set of types that have been stored /// to an inferred allocation. It does not support any of the normal value queries. inferred_alloc, pub const last_no_payload_tag = Tag.empty_array; pub const no_payload_count = @enumToInt(last_no_payload_tag) + 1; pub fn Type(comptime t: Tag) type { return switch (t) { .u8_type, .i8_type, .u16_type, .i16_type, .u32_type, .i32_type, .u64_type, .i64_type, .u128_type, .i128_type, .usize_type, .isize_type, .c_short_type, .c_ushort_type, .c_int_type, .c_uint_type, .c_long_type, .c_ulong_type, .c_longlong_type, .c_ulonglong_type, .c_longdouble_type, .f16_type, .f32_type, .f64_type, .f128_type, .c_void_type, .bool_type, .void_type, .type_type, .anyerror_type, .comptime_int_type, .comptime_float_type, .noreturn_type, .null_type, .undefined_type, .fn_noreturn_no_args_type, .fn_void_no_args_type, .fn_naked_noreturn_no_args_type, .fn_ccc_void_no_args_type, .single_const_pointer_to_comptime_int_type, .anyframe_type, .const_slice_u8_type, .enum_literal_type, .undef, .zero, .one, .void_value, .unreachable_value, .empty_struct_value, .empty_array, .null_value, .bool_true, .bool_false, .abi_align_default, .manyptr_u8_type, .manyptr_const_u8_type, .atomic_ordering_type, .atomic_rmw_op_type, .calling_convention_type, .float_mode_type, .reduce_op_type, .call_options_type, .export_options_type, .extern_options_type, => @compileError("Value Tag " ++ @tagName(t) ++ " has no payload"), .int_big_positive, .int_big_negative, => Payload.BigInt, .extern_fn, .decl_ref, => Payload.Decl, .ref_val, .repeated, .error_union, => Payload.SubValue, .bytes, .enum_literal, => Payload.Bytes, .enum_field_index => Payload.U32, .ty => Payload.Ty, .int_type => Payload.IntType, .int_u64 => Payload.U64, .int_i64 => Payload.I64, .function => Payload.Function, .variable => Payload.Variable, .comptime_alloc => Payload.ComptimeAlloc, .elem_ptr => Payload.ElemPtr, .field_ptr => Payload.FieldPtr, .float_16 => Payload.Float_16, .float_32 => Payload.Float_32, .float_64 => Payload.Float_64, .float_128 => Payload.Float_128, .@"error" => Payload.Error, .inferred_alloc => Payload.InferredAlloc, .@"struct" => Payload.Struct, .@"union" => Payload.Union, }; } pub fn create(comptime t: Tag, ally: *Allocator, data: Data(t)) error{OutOfMemory}!Value { const ptr = try ally.create(t.Type()); ptr.* = .{ .base = .{ .tag = t }, .data = data, }; return Value{ .ptr_otherwise = &ptr.base }; } pub fn Data(comptime t: Tag) type { return std.meta.fieldInfo(t.Type(), .data).field_type; } }; pub fn initTag(small_tag: Tag) Value { assert(@enumToInt(small_tag) < Tag.no_payload_count); return .{ .tag_if_small_enough = @enumToInt(small_tag) }; } pub fn initPayload(payload: *Payload) Value { assert(@enumToInt(payload.tag) >= Tag.no_payload_count); return .{ .ptr_otherwise = payload }; } pub fn tag(self: Value) Tag { if (self.tag_if_small_enough < Tag.no_payload_count) { return @intToEnum(Tag, @intCast(std.meta.Tag(Tag), self.tag_if_small_enough)); } else { return self.ptr_otherwise.tag; } } /// Prefer `castTag` to this. pub fn cast(self: Value, comptime T: type) ?*T { if (@hasField(T, "base_tag")) { return base.castTag(T.base_tag); } if (self.tag_if_small_enough < Tag.no_payload_count) { return null; } inline for (@typeInfo(Tag).Enum.fields) |field| { if (field.value < Tag.no_payload_count) continue; const t = @intToEnum(Tag, field.value); if (self.ptr_otherwise.tag == t) { if (T == t.Type()) { return @fieldParentPtr(T, "base", self.ptr_otherwise); } return null; } } unreachable; } pub fn castTag(self: Value, comptime t: Tag) ?*t.Type() { if (self.tag_if_small_enough < Tag.no_payload_count) return null; if (self.ptr_otherwise.tag == t) return @fieldParentPtr(t.Type(), "base", self.ptr_otherwise); return null; } pub fn copy(self: Value, allocator: *Allocator) error{OutOfMemory}!Value { if (self.tag_if_small_enough < Tag.no_payload_count) { return Value{ .tag_if_small_enough = self.tag_if_small_enough }; } else switch (self.ptr_otherwise.tag) { .u8_type, .i8_type, .u16_type, .i16_type, .u32_type, .i32_type, .u64_type, .i64_type, .u128_type, .i128_type, .usize_type, .isize_type, .c_short_type, .c_ushort_type, .c_int_type, .c_uint_type, .c_long_type, .c_ulong_type, .c_longlong_type, .c_ulonglong_type, .c_longdouble_type, .f16_type, .f32_type, .f64_type, .f128_type, .c_void_type, .bool_type, .void_type, .type_type, .anyerror_type, .comptime_int_type, .comptime_float_type, .noreturn_type, .null_type, .undefined_type, .fn_noreturn_no_args_type, .fn_void_no_args_type, .fn_naked_noreturn_no_args_type, .fn_ccc_void_no_args_type, .single_const_pointer_to_comptime_int_type, .anyframe_type, .const_slice_u8_type, .enum_literal_type, .undef, .zero, .one, .void_value, .unreachable_value, .empty_array, .null_value, .bool_true, .bool_false, .empty_struct_value, .abi_align_default, .manyptr_u8_type, .manyptr_const_u8_type, .atomic_ordering_type, .atomic_rmw_op_type, .calling_convention_type, .float_mode_type, .reduce_op_type, .call_options_type, .export_options_type, .extern_options_type, => unreachable, .ty => { const payload = self.castTag(.ty).?; const new_payload = try allocator.create(Payload.Ty); new_payload.* = .{ .base = payload.base, .data = try payload.data.copy(allocator), }; return Value{ .ptr_otherwise = &new_payload.base }; }, .int_type => return self.copyPayloadShallow(allocator, Payload.IntType), .int_u64 => return self.copyPayloadShallow(allocator, Payload.U64), .int_i64 => return self.copyPayloadShallow(allocator, Payload.I64), .int_big_positive, .int_big_negative => { const old_payload = self.cast(Payload.BigInt).?; const new_payload = try allocator.create(Payload.BigInt); new_payload.* = .{ .base = .{ .tag = self.ptr_otherwise.tag }, .data = try allocator.dupe(std.math.big.Limb, old_payload.data), }; return Value{ .ptr_otherwise = &new_payload.base }; }, .function => return self.copyPayloadShallow(allocator, Payload.Function), .extern_fn => return self.copyPayloadShallow(allocator, Payload.Decl), .variable => return self.copyPayloadShallow(allocator, Payload.Variable), .ref_val => { const payload = self.castTag(.ref_val).?; const new_payload = try allocator.create(Payload.SubValue); new_payload.* = .{ .base = payload.base, .data = try payload.data.copy(allocator), }; return Value{ .ptr_otherwise = &new_payload.base }; }, .comptime_alloc => return self.copyPayloadShallow(allocator, Payload.ComptimeAlloc), .decl_ref => return self.copyPayloadShallow(allocator, Payload.Decl), .elem_ptr => { const payload = self.castTag(.elem_ptr).?; const new_payload = try allocator.create(Payload.ElemPtr); new_payload.* = .{ .base = payload.base, .data = .{ .array_ptr = try payload.data.array_ptr.copy(allocator), .index = payload.data.index, }, }; return Value{ .ptr_otherwise = &new_payload.base }; }, .field_ptr => { const payload = self.castTag(.field_ptr).?; const new_payload = try allocator.create(Payload.FieldPtr); new_payload.* = .{ .base = payload.base, .data = .{ .container_ptr = try payload.data.container_ptr.copy(allocator), .field_index = payload.data.field_index, }, }; return Value{ .ptr_otherwise = &new_payload.base }; }, .bytes => return self.copyPayloadShallow(allocator, Payload.Bytes), .repeated => { const payload = self.castTag(.repeated).?; const new_payload = try allocator.create(Payload.SubValue); new_payload.* = .{ .base = payload.base, .data = try payload.data.copy(allocator), }; return Value{ .ptr_otherwise = &new_payload.base }; }, .float_16 => return self.copyPayloadShallow(allocator, Payload.Float_16), .float_32 => return self.copyPayloadShallow(allocator, Payload.Float_32), .float_64 => return self.copyPayloadShallow(allocator, Payload.Float_64), .float_128 => return self.copyPayloadShallow(allocator, Payload.Float_128), .enum_literal => { const payload = self.castTag(.enum_literal).?; const new_payload = try allocator.create(Payload.Bytes); new_payload.* = .{ .base = payload.base, .data = try allocator.dupe(u8, payload.data), }; return Value{ .ptr_otherwise = &new_payload.base }; }, .enum_field_index => return self.copyPayloadShallow(allocator, Payload.U32), .@"error" => return self.copyPayloadShallow(allocator, Payload.Error), .error_union => { const payload = self.castTag(.error_union).?; const new_payload = try allocator.create(Payload.SubValue); new_payload.* = .{ .base = payload.base, .data = try payload.data.copy(allocator), }; return Value{ .ptr_otherwise = &new_payload.base }; }, .@"struct" => @panic("TODO can't copy struct value without knowing the type"), .@"union" => @panic("TODO can't copy union value without knowing the type"), .inferred_alloc => unreachable, } } fn copyPayloadShallow(self: Value, allocator: *Allocator, comptime T: type) error{OutOfMemory}!Value { const payload = self.cast(T).?; const new_payload = try allocator.create(T); new_payload.* = payload.*; return Value{ .ptr_otherwise = &new_payload.base }; } /// TODO this should become a debug dump() function. In order to print values in a meaningful way /// we also need access to the type. pub fn format( self: Value, comptime fmt: []const u8, options: std.fmt.FormatOptions, out_stream: anytype, ) !void { comptime assert(fmt.len == 0); var val = self; while (true) switch (val.tag()) { .u8_type => return out_stream.writeAll("u8"), .i8_type => return out_stream.writeAll("i8"), .u16_type => return out_stream.writeAll("u16"), .i16_type => return out_stream.writeAll("i16"), .u32_type => return out_stream.writeAll("u32"), .i32_type => return out_stream.writeAll("i32"), .u64_type => return out_stream.writeAll("u64"), .i64_type => return out_stream.writeAll("i64"), .u128_type => return out_stream.writeAll("u128"), .i128_type => return out_stream.writeAll("i128"), .isize_type => return out_stream.writeAll("isize"), .usize_type => return out_stream.writeAll("usize"), .c_short_type => return out_stream.writeAll("c_short"), .c_ushort_type => return out_stream.writeAll("c_ushort"), .c_int_type => return out_stream.writeAll("c_int"), .c_uint_type => return out_stream.writeAll("c_uint"), .c_long_type => return out_stream.writeAll("c_long"), .c_ulong_type => return out_stream.writeAll("c_ulong"), .c_longlong_type => return out_stream.writeAll("c_longlong"), .c_ulonglong_type => return out_stream.writeAll("c_ulonglong"), .c_longdouble_type => return out_stream.writeAll("c_longdouble"), .f16_type => return out_stream.writeAll("f16"), .f32_type => return out_stream.writeAll("f32"), .f64_type => return out_stream.writeAll("f64"), .f128_type => return out_stream.writeAll("f128"), .c_void_type => return out_stream.writeAll("c_void"), .bool_type => return out_stream.writeAll("bool"), .void_type => return out_stream.writeAll("void"), .type_type => return out_stream.writeAll("type"), .anyerror_type => return out_stream.writeAll("anyerror"), .comptime_int_type => return out_stream.writeAll("comptime_int"), .comptime_float_type => return out_stream.writeAll("comptime_float"), .noreturn_type => return out_stream.writeAll("noreturn"), .null_type => return out_stream.writeAll("@Type(.Null)"), .undefined_type => return out_stream.writeAll("@Type(.Undefined)"), .fn_noreturn_no_args_type => return out_stream.writeAll("fn() noreturn"), .fn_void_no_args_type => return out_stream.writeAll("fn() void"), .fn_naked_noreturn_no_args_type => return out_stream.writeAll("fn() callconv(.Naked) noreturn"), .fn_ccc_void_no_args_type => return out_stream.writeAll("fn() callconv(.C) void"), .single_const_pointer_to_comptime_int_type => return out_stream.writeAll("*const comptime_int"), .anyframe_type => return out_stream.writeAll("anyframe"), .const_slice_u8_type => return out_stream.writeAll("[]const u8"), .enum_literal_type => return out_stream.writeAll("@Type(.EnumLiteral)"), .manyptr_u8_type => return out_stream.writeAll("[*]u8"), .manyptr_const_u8_type => return out_stream.writeAll("[*]const u8"), .atomic_ordering_type => return out_stream.writeAll("std.builtin.AtomicOrdering"), .atomic_rmw_op_type => return out_stream.writeAll("std.builtin.AtomicRmwOp"), .calling_convention_type => return out_stream.writeAll("std.builtin.CallingConvention"), .float_mode_type => return out_stream.writeAll("std.builtin.FloatMode"), .reduce_op_type => return out_stream.writeAll("std.builtin.ReduceOp"), .call_options_type => return out_stream.writeAll("std.builtin.CallOptions"), .export_options_type => return out_stream.writeAll("std.builtin.ExportOptions"), .extern_options_type => return out_stream.writeAll("std.builtin.ExternOptions"), .abi_align_default => return out_stream.writeAll("(default ABI alignment)"), .empty_struct_value => return out_stream.writeAll("struct {}{}"), .@"struct" => { return out_stream.writeAll("(struct value)"); }, .@"union" => { return out_stream.writeAll("(union value)"); }, .null_value => return out_stream.writeAll("null"), .undef => return out_stream.writeAll("undefined"), .zero => return out_stream.writeAll("0"), .one => return out_stream.writeAll("1"), .void_value => return out_stream.writeAll("{}"), .unreachable_value => return out_stream.writeAll("unreachable"), .bool_true => return out_stream.writeAll("true"), .bool_false => return out_stream.writeAll("false"), .ty => return val.castTag(.ty).?.data.format("", options, out_stream), .int_type => { const int_type = val.castTag(.int_type).?.data; return out_stream.print("{s}{d}", .{ if (int_type.signed) "s" else "u", int_type.bits, }); }, .int_u64 => return std.fmt.formatIntValue(val.castTag(.int_u64).?.data, "", options, out_stream), .int_i64 => return std.fmt.formatIntValue(val.castTag(.int_i64).?.data, "", options, out_stream), .int_big_positive => return out_stream.print("{}", .{val.castTag(.int_big_positive).?.asBigInt()}), .int_big_negative => return out_stream.print("{}", .{val.castTag(.int_big_negative).?.asBigInt()}), .function => return out_stream.writeAll("(function)"), .extern_fn => return out_stream.writeAll("(extern function)"), .variable => return out_stream.writeAll("(variable)"), .ref_val => { const ref_val = val.castTag(.ref_val).?.data; try out_stream.writeAll("&const "); val = ref_val; }, .comptime_alloc => { const ref_val = val.castTag(.comptime_alloc).?.data.val; try out_stream.writeAll("&"); val = ref_val; }, .decl_ref => return out_stream.writeAll("(decl ref)"), .elem_ptr => { const elem_ptr = val.castTag(.elem_ptr).?.data; try out_stream.print("&[{}] ", .{elem_ptr.index}); val = elem_ptr.array_ptr; }, .field_ptr => { const field_ptr = val.castTag(.field_ptr).?.data; try out_stream.print("fieldptr({d}) ", .{field_ptr.field_index}); val = field_ptr.container_ptr; }, .empty_array => return out_stream.writeAll(".{}"), .enum_literal => return out_stream.print(".{}", .{std.zig.fmtId(self.castTag(.enum_literal).?.data)}), .enum_field_index => return out_stream.print("(enum field {d})", .{self.castTag(.enum_field_index).?.data}), .bytes => return out_stream.print("\"{}\"", .{std.zig.fmtEscapes(self.castTag(.bytes).?.data)}), .repeated => { try out_stream.writeAll("(repeated) "); val = val.castTag(.repeated).?.data; }, .float_16 => return out_stream.print("{}", .{val.castTag(.float_16).?.data}), .float_32 => return out_stream.print("{}", .{val.castTag(.float_32).?.data}), .float_64 => return out_stream.print("{}", .{val.castTag(.float_64).?.data}), .float_128 => return out_stream.print("{}", .{val.castTag(.float_128).?.data}), .@"error" => return out_stream.print("error.{s}", .{val.castTag(.@"error").?.data.name}), // TODO to print this it should be error{ Set, Items }!T(val), but we need the type for that .error_union => return out_stream.print("error_union_val({})", .{val.castTag(.error_union).?.data}), .inferred_alloc => return out_stream.writeAll("(inferred allocation value)"), }; } /// Asserts that the value is representable as an array of bytes. /// Copies the value into a freshly allocated slice of memory, which is owned by the caller. pub fn toAllocatedBytes(self: Value, allocator: *Allocator) ![]u8 { if (self.castTag(.bytes)) |payload| { return std.mem.dupe(allocator, u8, payload.data); } if (self.castTag(.enum_literal)) |payload| { return std.mem.dupe(allocator, u8, payload.data); } if (self.castTag(.repeated)) |payload| { _ = payload; @panic("TODO implement toAllocatedBytes for this Value tag"); } if (self.castTag(.decl_ref)) |payload| { const val = try payload.data.value(); return val.toAllocatedBytes(allocator); } unreachable; } /// Asserts that the value is representable as a type. pub fn toType(self: Value, allocator: *Allocator) !Type { return switch (self.tag()) { .ty => self.castTag(.ty).?.data, .u8_type => Type.initTag(.u8), .i8_type => Type.initTag(.i8), .u16_type => Type.initTag(.u16), .i16_type => Type.initTag(.i16), .u32_type => Type.initTag(.u32), .i32_type => Type.initTag(.i32), .u64_type => Type.initTag(.u64), .i64_type => Type.initTag(.i64), .u128_type => Type.initTag(.u128), .i128_type => Type.initTag(.i128), .usize_type => Type.initTag(.usize), .isize_type => Type.initTag(.isize), .c_short_type => Type.initTag(.c_short), .c_ushort_type => Type.initTag(.c_ushort), .c_int_type => Type.initTag(.c_int), .c_uint_type => Type.initTag(.c_uint), .c_long_type => Type.initTag(.c_long), .c_ulong_type => Type.initTag(.c_ulong), .c_longlong_type => Type.initTag(.c_longlong), .c_ulonglong_type => Type.initTag(.c_ulonglong), .c_longdouble_type => Type.initTag(.c_longdouble), .f16_type => Type.initTag(.f16), .f32_type => Type.initTag(.f32), .f64_type => Type.initTag(.f64), .f128_type => Type.initTag(.f128), .c_void_type => Type.initTag(.c_void), .bool_type => Type.initTag(.bool), .void_type => Type.initTag(.void), .type_type => Type.initTag(.type), .anyerror_type => Type.initTag(.anyerror), .comptime_int_type => Type.initTag(.comptime_int), .comptime_float_type => Type.initTag(.comptime_float), .noreturn_type => Type.initTag(.noreturn), .null_type => Type.initTag(.@"null"), .undefined_type => Type.initTag(.@"undefined"), .fn_noreturn_no_args_type => Type.initTag(.fn_noreturn_no_args), .fn_void_no_args_type => Type.initTag(.fn_void_no_args), .fn_naked_noreturn_no_args_type => Type.initTag(.fn_naked_noreturn_no_args), .fn_ccc_void_no_args_type => Type.initTag(.fn_ccc_void_no_args), .single_const_pointer_to_comptime_int_type => Type.initTag(.single_const_pointer_to_comptime_int), .anyframe_type => Type.initTag(.@"anyframe"), .const_slice_u8_type => Type.initTag(.const_slice_u8), .enum_literal_type => Type.initTag(.enum_literal), .manyptr_u8_type => Type.initTag(.manyptr_u8), .manyptr_const_u8_type => Type.initTag(.manyptr_const_u8), .atomic_ordering_type => Type.initTag(.atomic_ordering), .atomic_rmw_op_type => Type.initTag(.atomic_rmw_op), .calling_convention_type => Type.initTag(.calling_convention), .float_mode_type => Type.initTag(.float_mode), .reduce_op_type => Type.initTag(.reduce_op), .call_options_type => Type.initTag(.call_options), .export_options_type => Type.initTag(.export_options), .extern_options_type => Type.initTag(.extern_options), .int_type => { const payload = self.castTag(.int_type).?.data; const new = try allocator.create(Type.Payload.Bits); new.* = .{ .base = .{ .tag = if (payload.signed) .int_signed else .int_unsigned, }, .data = payload.bits, }; return Type.initPayload(&new.base); }, .undef, .zero, .one, .void_value, .unreachable_value, .empty_array, .bool_true, .bool_false, .null_value, .int_u64, .int_i64, .int_big_positive, .int_big_negative, .function, .extern_fn, .variable, .ref_val, .comptime_alloc, .decl_ref, .elem_ptr, .field_ptr, .bytes, .repeated, .float_16, .float_32, .float_64, .float_128, .enum_literal, .enum_field_index, .@"error", .error_union, .empty_struct_value, .@"struct", .@"union", .inferred_alloc, .abi_align_default, => unreachable, }; } /// Asserts the type is an enum type. pub fn toEnum(val: Value, enum_ty: Type, comptime E: type) E { _ = enum_ty; // TODO this needs to resolve other kinds of Value tags rather than // assuming the tag will be .enum_field_index. const field_index = val.castTag(.enum_field_index).?.data; // TODO should `@intToEnum` do this `@intCast` for you? return @intToEnum(E, @intCast(@typeInfo(E).Enum.tag_type, field_index)); } /// Asserts the value is an integer. pub fn toBigInt(self: Value, space: *BigIntSpace) BigIntConst { switch (self.tag()) { .zero, .bool_false, => return BigIntMutable.init(&space.limbs, 0).toConst(), .one, .bool_true, => return BigIntMutable.init(&space.limbs, 1).toConst(), .int_u64 => return BigIntMutable.init(&space.limbs, self.castTag(.int_u64).?.data).toConst(), .int_i64 => return BigIntMutable.init(&space.limbs, self.castTag(.int_i64).?.data).toConst(), .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt(), .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt(), .undef => unreachable, else => unreachable, } } /// Asserts the value is an integer and it fits in a u64 pub fn toUnsignedInt(self: Value) u64 { switch (self.tag()) { .zero, .bool_false, => return 0, .one, .bool_true, => return 1, .int_u64 => return self.castTag(.int_u64).?.data, .int_i64 => return @intCast(u64, self.castTag(.int_i64).?.data), .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().to(u64) catch unreachable, .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().to(u64) catch unreachable, .undef => unreachable, else => unreachable, } } /// Asserts the value is an integer and it fits in a i64 pub fn toSignedInt(self: Value) i64 { switch (self.tag()) { .zero, .bool_false, => return 0, .one, .bool_true, => return 1, .int_u64 => return @intCast(i64, self.castTag(.int_u64).?.data), .int_i64 => return self.castTag(.int_i64).?.data, .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().to(i64) catch unreachable, .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().to(i64) catch unreachable, .undef => unreachable, else => unreachable, } } pub fn toBool(self: Value) bool { return switch (self.tag()) { .bool_true => true, .bool_false, .zero => false, else => unreachable, }; } /// Asserts that the value is a float or an integer. pub fn toFloat(self: Value, comptime T: type) T { return switch (self.tag()) { .float_16 => @panic("TODO soft float"), .float_32 => @floatCast(T, self.castTag(.float_32).?.data), .float_64 => @floatCast(T, self.castTag(.float_64).?.data), .float_128 => @floatCast(T, self.castTag(.float_128).?.data), .zero => 0, .one => 1, .int_u64 => @intToFloat(T, self.castTag(.int_u64).?.data), .int_i64 => @intToFloat(T, self.castTag(.int_i64).?.data), .int_big_positive, .int_big_negative => @panic("big int to f128"), else => unreachable, }; } /// Asserts the value is an integer and not undefined. /// Returns the number of bits the value requires to represent stored in twos complement form. pub fn intBitCountTwosComp(self: Value) usize { switch (self.tag()) { .zero, .bool_false, => return 0, .one, .bool_true, => return 1, .int_u64 => { const x = self.castTag(.int_u64).?.data; if (x == 0) return 0; return @intCast(usize, std.math.log2(x) + 1); }, .int_i64 => { @panic("TODO implement i64 intBitCountTwosComp"); }, .int_big_positive => return self.castTag(.int_big_positive).?.asBigInt().bitCountTwosComp(), .int_big_negative => return self.castTag(.int_big_negative).?.asBigInt().bitCountTwosComp(), else => unreachable, } } /// Asserts the value is an integer, and the destination type is ComptimeInt or Int. pub fn intFitsInType(self: Value, ty: Type, target: Target) bool { switch (self.tag()) { .zero, .undef, .bool_false, => return true, .one, .bool_true, => { const info = ty.intInfo(target); return switch (info.signedness) { .signed => info.bits >= 2, .unsigned => info.bits >= 1, }; }, .int_u64 => switch (ty.zigTypeTag()) { .Int => { const x = self.castTag(.int_u64).?.data; if (x == 0) return true; const info = ty.intInfo(target); const needed_bits = std.math.log2(x) + 1 + @boolToInt(info.signedness == .signed); return info.bits >= needed_bits; }, .ComptimeInt => return true, else => unreachable, }, .int_i64 => switch (ty.zigTypeTag()) { .Int => { const x = self.castTag(.int_i64).?.data; if (x == 0) return true; const info = ty.intInfo(target); if (info.signedness == .unsigned and x < 0) return false; @panic("TODO implement i64 intFitsInType"); }, .ComptimeInt => return true, else => unreachable, }, .int_big_positive => switch (ty.zigTypeTag()) { .Int => { const info = ty.intInfo(target); return self.castTag(.int_big_positive).?.asBigInt().fitsInTwosComp(info.signedness, info.bits); }, .ComptimeInt => return true, else => unreachable, }, .int_big_negative => switch (ty.zigTypeTag()) { .Int => { const info = ty.intInfo(target); return self.castTag(.int_big_negative).?.asBigInt().fitsInTwosComp(info.signedness, info.bits); }, .ComptimeInt => return true, else => unreachable, }, else => unreachable, } } /// Converts an integer or a float to a float. /// Returns `error.Overflow` if the value does not fit in the new type. pub fn floatCast(self: Value, allocator: *Allocator, ty: Type, target: Target) !Value { _ = target; switch (ty.tag()) { .f16 => { @panic("TODO add __trunctfhf2 to compiler-rt"); //const res = try Value.Tag.float_16.create(allocator, self.toFloat(f16)); //if (!self.eql(res)) // return error.Overflow; //return res; }, .f32 => { const res = try Value.Tag.float_32.create(allocator, self.toFloat(f32)); if (!self.eql(res)) return error.Overflow; return res; }, .f64 => { const res = try Value.Tag.float_64.create(allocator, self.toFloat(f64)); if (!self.eql(res)) return error.Overflow; return res; }, .f128, .comptime_float, .c_longdouble => { return Value.Tag.float_128.create(allocator, self.toFloat(f128)); }, else => unreachable, } } /// Asserts the value is a float pub fn floatHasFraction(self: Value) bool { return switch (self.tag()) { .zero, .one, => false, .float_16 => @rem(self.castTag(.float_16).?.data, 1) != 0, .float_32 => @rem(self.castTag(.float_32).?.data, 1) != 0, .float_64 => @rem(self.castTag(.float_64).?.data, 1) != 0, // .float_128 => @rem(self.castTag(.float_128).?.data, 1) != 0, .float_128 => @panic("TODO lld: error: undefined symbol: fmodl"), else => unreachable, }; } /// Asserts the value is numeric pub fn isZero(self: Value) bool { return switch (self.tag()) { .zero => true, .one => false, .int_u64 => self.castTag(.int_u64).?.data == 0, .int_i64 => self.castTag(.int_i64).?.data == 0, .float_16 => self.castTag(.float_16).?.data == 0, .float_32 => self.castTag(.float_32).?.data == 0, .float_64 => self.castTag(.float_64).?.data == 0, .float_128 => self.castTag(.float_128).?.data == 0, .int_big_positive => self.castTag(.int_big_positive).?.asBigInt().eqZero(), .int_big_negative => self.castTag(.int_big_negative).?.asBigInt().eqZero(), else => unreachable, }; } pub fn orderAgainstZero(lhs: Value) std.math.Order { return switch (lhs.tag()) { .zero, .bool_false, => .eq, .one, .bool_true, => .gt, .int_u64 => std.math.order(lhs.castTag(.int_u64).?.data, 0), .int_i64 => std.math.order(lhs.castTag(.int_i64).?.data, 0), .int_big_positive => lhs.castTag(.int_big_positive).?.asBigInt().orderAgainstScalar(0), .int_big_negative => lhs.castTag(.int_big_negative).?.asBigInt().orderAgainstScalar(0), .float_16 => std.math.order(lhs.castTag(.float_16).?.data, 0), .float_32 => std.math.order(lhs.castTag(.float_32).?.data, 0), .float_64 => std.math.order(lhs.castTag(.float_64).?.data, 0), .float_128 => std.math.order(lhs.castTag(.float_128).?.data, 0), else => unreachable, }; } /// Asserts the value is comparable. pub fn order(lhs: Value, rhs: Value) std.math.Order { const lhs_tag = lhs.tag(); const rhs_tag = rhs.tag(); const lhs_is_zero = lhs_tag == .zero; const rhs_is_zero = rhs_tag == .zero; if (lhs_is_zero) return rhs.orderAgainstZero().invert(); if (rhs_is_zero) return lhs.orderAgainstZero(); const lhs_float = lhs.isFloat(); const rhs_float = rhs.isFloat(); if (lhs_float and rhs_float) { if (lhs_tag == rhs_tag) { return switch (lhs.tag()) { .float_16 => return std.math.order(lhs.castTag(.float_16).?.data, rhs.castTag(.float_16).?.data), .float_32 => return std.math.order(lhs.castTag(.float_32).?.data, rhs.castTag(.float_32).?.data), .float_64 => return std.math.order(lhs.castTag(.float_64).?.data, rhs.castTag(.float_64).?.data), .float_128 => return std.math.order(lhs.castTag(.float_128).?.data, rhs.castTag(.float_128).?.data), else => unreachable, }; } } if (lhs_float or rhs_float) { const lhs_f128 = lhs.toFloat(f128); const rhs_f128 = rhs.toFloat(f128); return std.math.order(lhs_f128, rhs_f128); } var lhs_bigint_space: BigIntSpace = undefined; var rhs_bigint_space: BigIntSpace = undefined; const lhs_bigint = lhs.toBigInt(&lhs_bigint_space); const rhs_bigint = rhs.toBigInt(&rhs_bigint_space); return lhs_bigint.order(rhs_bigint); } /// Asserts the value is comparable. pub fn compare(lhs: Value, op: std.math.CompareOperator, rhs: Value) bool { return switch (op) { .eq => lhs.eql(rhs), .neq => !lhs.eql(rhs), else => order(lhs, rhs).compare(op), }; } /// Asserts the value is comparable. pub fn compareWithZero(lhs: Value, op: std.math.CompareOperator) bool { return orderAgainstZero(lhs).compare(op); } pub fn eql(a: Value, b: Value) bool { const a_tag = a.tag(); const b_tag = b.tag(); if (a_tag == b_tag) { switch (a_tag) { .void_value, .null_value => return true, .enum_literal => { const a_name = a.castTag(.enum_literal).?.data; const b_name = b.castTag(.enum_literal).?.data; return std.mem.eql(u8, a_name, b_name); }, .enum_field_index => { const a_field_index = a.castTag(.enum_field_index).?.data; const b_field_index = b.castTag(.enum_field_index).?.data; return a_field_index == b_field_index; }, else => {}, } } if (a.isType() and b.isType()) { // 128 bytes should be enough to hold both types var buf: [128]u8 = undefined; var fib = std.heap.FixedBufferAllocator.init(&buf); const a_type = a.toType(&fib.allocator) catch unreachable; const b_type = b.toType(&fib.allocator) catch unreachable; return a_type.eql(b_type); } return order(a, b).compare(.eq); } pub fn hash_u32(self: Value) u32 { return @truncate(u32, self.hash()); } pub fn hash(self: Value) u64 { var hasher = std.hash.Wyhash.init(0); switch (self.tag()) { .u8_type, .i8_type, .u16_type, .i16_type, .u32_type, .i32_type, .u64_type, .i64_type, .u128_type, .i128_type, .usize_type, .isize_type, .c_short_type, .c_ushort_type, .c_int_type, .c_uint_type, .c_long_type, .c_ulong_type, .c_longlong_type, .c_ulonglong_type, .c_longdouble_type, .f16_type, .f32_type, .f64_type, .f128_type, .c_void_type, .bool_type, .void_type, .type_type, .anyerror_type, .comptime_int_type, .comptime_float_type, .noreturn_type, .null_type, .undefined_type, .fn_noreturn_no_args_type, .fn_void_no_args_type, .fn_naked_noreturn_no_args_type, .fn_ccc_void_no_args_type, .single_const_pointer_to_comptime_int_type, .anyframe_type, .const_slice_u8_type, .enum_literal_type, .ty, .abi_align_default, => { // Directly return Type.hash, toType can only fail for .int_type. var allocator = std.heap.FixedBufferAllocator.init(&[_]u8{}); return (self.toType(&allocator.allocator) catch unreachable).hash(); }, .int_type => { const payload = self.castTag(.int_type).?.data; var int_payload = Type.Payload.Bits{ .base = .{ .tag = if (payload.signed) .int_signed else .int_unsigned, }, .data = payload.bits, }; return Type.initPayload(&int_payload.base).hash(); }, .empty_struct_value, .empty_array, => {}, .undef, .null_value, .void_value, .unreachable_value, => std.hash.autoHash(&hasher, self.tag()), .zero, .bool_false => std.hash.autoHash(&hasher, @as(u64, 0)), .one, .bool_true => std.hash.autoHash(&hasher, @as(u64, 1)), .float_16, .float_32, .float_64, .float_128 => { @panic("TODO implement Value.hash for floats"); }, .enum_literal => { const payload = self.castTag(.enum_literal).?; hasher.update(payload.data); }, .enum_field_index => { const payload = self.castTag(.enum_field_index).?; std.hash.autoHash(&hasher, payload.data); }, .bytes => { const payload = self.castTag(.bytes).?; hasher.update(payload.data); }, .int_u64 => { const payload = self.castTag(.int_u64).?; std.hash.autoHash(&hasher, payload.data); }, .int_i64 => { const payload = self.castTag(.int_i64).?; std.hash.autoHash(&hasher, payload.data); }, .repeated => { const payload = self.castTag(.repeated).?; std.hash.autoHash(&hasher, payload.data.hash()); }, .ref_val => { const payload = self.castTag(.ref_val).?; std.hash.autoHash(&hasher, payload.data.hash()); }, .comptime_alloc => { const payload = self.castTag(.comptime_alloc).?; std.hash.autoHash(&hasher, payload.data.val.hash()); }, .int_big_positive, .int_big_negative => { var space: BigIntSpace = undefined; const big = self.toBigInt(&space); if (big.limbs.len == 1) { // handle like {u,i}64 to ensure same hash as with Int{i,u}64 if (big.positive) { std.hash.autoHash(&hasher, @as(u64, big.limbs[0])); } else { std.hash.autoHash(&hasher, @as(u64, @bitCast(usize, -@bitCast(isize, big.limbs[0])))); } } else { std.hash.autoHash(&hasher, big.positive); for (big.limbs) |limb| { std.hash.autoHash(&hasher, limb); } } }, .elem_ptr => { const payload = self.castTag(.elem_ptr).?.data; std.hash.autoHash(&hasher, payload.array_ptr.hash()); std.hash.autoHash(&hasher, payload.index); }, .field_ptr => { const payload = self.castTag(.field_ptr).?.data; std.hash.autoHash(&hasher, payload.container_ptr.hash()); std.hash.autoHash(&hasher, payload.field_index); }, .decl_ref => { const decl = self.castTag(.decl_ref).?.data; std.hash.autoHash(&hasher, decl); }, .function => { const func = self.castTag(.function).?.data; std.hash.autoHash(&hasher, func); }, .extern_fn => { const decl = self.castTag(.extern_fn).?.data; std.hash.autoHash(&hasher, decl); }, .variable => { const variable = self.castTag(.variable).?.data; std.hash.autoHash(&hasher, variable); }, .@"error" => { const payload = self.castTag(.@"error").?.data; hasher.update(payload.name); }, .error_union => { const payload = self.castTag(.error_union).?.data; std.hash.autoHash(&hasher, payload.hash()); }, .inferred_alloc => unreachable, .manyptr_u8_type, .manyptr_const_u8_type, .atomic_ordering_type, .atomic_rmw_op_type, .calling_convention_type, .float_mode_type, .reduce_op_type, .call_options_type, .export_options_type, .extern_options_type, .@"struct", .@"union", => @panic("TODO this hash function looks pretty broken. audit it"), } return hasher.final(); } pub const ArrayHashContext = struct { pub fn hash(self: @This(), v: Value) u32 { _ = self; return v.hash_u32(); } pub fn eql(self: @This(), a: Value, b: Value) bool { _ = self; return a.eql(b); } }; pub const HashContext = struct { pub fn hash(self: @This(), v: Value) u64 { _ = self; return v.hash(); } pub fn eql(self: @This(), a: Value, b: Value) bool { _ = self; return a.eql(b); } }; /// Asserts the value is a pointer and dereferences it. /// Returns error.AnalysisFail if the pointer points to a Decl that failed semantic analysis. pub fn pointerDeref(self: Value, allocator: *Allocator) error{ AnalysisFail, OutOfMemory }!Value { return switch (self.tag()) { .comptime_alloc => self.castTag(.comptime_alloc).?.data.val, .ref_val => self.castTag(.ref_val).?.data, .decl_ref => self.castTag(.decl_ref).?.data.value(), .elem_ptr => { const elem_ptr = self.castTag(.elem_ptr).?.data; const array_val = try elem_ptr.array_ptr.pointerDeref(allocator); return array_val.elemValue(allocator, elem_ptr.index); }, .field_ptr => { const field_ptr = self.castTag(.field_ptr).?.data; const container_val = try field_ptr.container_ptr.pointerDeref(allocator); return container_val.fieldValue(allocator, field_ptr.field_index); }, else => unreachable, }; } /// Asserts the value is a single-item pointer to an array, or an array, /// or an unknown-length pointer, and returns the element value at the index. pub fn elemValue(self: Value, allocator: *Allocator, index: usize) error{OutOfMemory}!Value { switch (self.tag()) { .empty_array => unreachable, // out of bounds array index .bytes => return Tag.int_u64.create(allocator, self.castTag(.bytes).?.data[index]), // No matter the index; all the elements are the same! .repeated => return self.castTag(.repeated).?.data, else => unreachable, } } pub fn fieldValue(val: Value, allocator: *Allocator, index: usize) error{OutOfMemory}!Value { _ = allocator; switch (val.tag()) { .@"struct" => { const field_values = val.castTag(.@"struct").?.data; return field_values[index]; }, .@"union" => { const payload = val.castTag(.@"union").?.data; // TODO assert the tag is correct return payload.val; }, else => unreachable, } } /// Returns a pointer to the element value at the index. pub fn elemPtr(self: Value, allocator: *Allocator, index: usize) !Value { if (self.castTag(.elem_ptr)) |elem_ptr| { return Tag.elem_ptr.create(allocator, .{ .array_ptr = elem_ptr.data.array_ptr, .index = elem_ptr.data.index + index, }); } return Tag.elem_ptr.create(allocator, .{ .array_ptr = self, .index = index, }); } pub fn isUndef(self: Value) bool { return self.tag() == .undef; } /// Valid for all types. Asserts the value is not undefined and not unreachable. pub fn isNull(self: Value) bool { return switch (self.tag()) { .undef => unreachable, .unreachable_value => unreachable, .inferred_alloc => unreachable, .null_value => true, else => false, }; } /// Valid for all types. Asserts the value is not undefined and not unreachable. pub fn getError(self: Value) ?[]const u8 { return switch (self.tag()) { .error_union => { const data = self.castTag(.error_union).?.data; return if (data.tag() == .@"error") data.castTag(.@"error").?.data.name else null; }, .@"error" => self.castTag(.@"error").?.data.name, .undef => unreachable, .unreachable_value => unreachable, .inferred_alloc => unreachable, else => null, }; } /// Valid for all types. Asserts the value is not undefined. pub fn isFloat(self: Value) bool { return switch (self.tag()) { .undef => unreachable, .inferred_alloc => unreachable, .float_16, .float_32, .float_64, .float_128, => true, else => false, }; } /// Valid for all types. Asserts the value is not undefined. pub fn isType(self: Value) bool { return switch (self.tag()) { .ty, .int_type, .u8_type, .i8_type, .u16_type, .i16_type, .u32_type, .i32_type, .u64_type, .i64_type, .u128_type, .i128_type, .usize_type, .isize_type, .c_short_type, .c_ushort_type, .c_int_type, .c_uint_type, .c_long_type, .c_ulong_type, .c_longlong_type, .c_ulonglong_type, .c_longdouble_type, .f16_type, .f32_type, .f64_type, .f128_type, .c_void_type, .bool_type, .void_type, .type_type, .anyerror_type, .comptime_int_type, .comptime_float_type, .noreturn_type, .null_type, .undefined_type, .fn_noreturn_no_args_type, .fn_void_no_args_type, .fn_naked_noreturn_no_args_type, .fn_ccc_void_no_args_type, .single_const_pointer_to_comptime_int_type, .anyframe_type, .const_slice_u8_type, .enum_literal_type, .manyptr_u8_type, .manyptr_const_u8_type, .atomic_ordering_type, .atomic_rmw_op_type, .calling_convention_type, .float_mode_type, .reduce_op_type, .call_options_type, .export_options_type, .extern_options_type, => true, .zero, .one, .empty_array, .bool_true, .bool_false, .function, .extern_fn, .variable, .int_u64, .int_i64, .int_big_positive, .int_big_negative, .ref_val, .comptime_alloc, .decl_ref, .elem_ptr, .field_ptr, .bytes, .repeated, .float_16, .float_32, .float_64, .float_128, .void_value, .enum_literal, .enum_field_index, .@"error", .error_union, .empty_struct_value, .@"struct", .@"union", .null_value, .abi_align_default, => false, .undef => unreachable, .unreachable_value => unreachable, .inferred_alloc => unreachable, }; } /// This type is not copyable since it may contain pointers to its inner data. pub const Payload = struct { tag: Tag, pub const U32 = struct { base: Payload, data: u32, }; pub const U64 = struct { base: Payload, data: u64, }; pub const I64 = struct { base: Payload, data: i64, }; pub const BigInt = struct { base: Payload, data: []const std.math.big.Limb, pub fn asBigInt(self: BigInt) BigIntConst { const positive = switch (self.base.tag) { .int_big_positive => true, .int_big_negative => false, else => unreachable, }; return BigIntConst{ .limbs = self.data, .positive = positive }; } }; pub const Function = struct { base: Payload, data: *Module.Fn, }; pub const Decl = struct { base: Payload, data: *Module.Decl, }; pub const Variable = struct { base: Payload, data: *Module.Var, }; pub const SubValue = struct { base: Payload, data: Value, }; pub const ComptimeAlloc = struct { pub const base_tag = Tag.comptime_alloc; base: Payload = Payload{ .tag = base_tag }, data: struct { val: Value, runtime_index: u32, }, }; pub const ElemPtr = struct { pub const base_tag = Tag.elem_ptr; base: Payload = Payload{ .tag = base_tag }, data: struct { array_ptr: Value, index: usize, }, }; pub const FieldPtr = struct { pub const base_tag = Tag.field_ptr; base: Payload = Payload{ .tag = base_tag }, data: struct { container_ptr: Value, field_index: usize, }, }; pub const Bytes = struct { base: Payload, data: []const u8, }; pub const Ty = struct { base: Payload, data: Type, }; pub const IntType = struct { pub const base_tag = Tag.int_type; base: Payload = Payload{ .tag = base_tag }, data: struct { bits: u16, signed: bool, }, }; pub const Float_16 = struct { pub const base_tag = Tag.float_16; base: Payload = .{ .tag = base_tag }, data: f16, }; pub const Float_32 = struct { pub const base_tag = Tag.float_32; base: Payload = .{ .tag = base_tag }, data: f32, }; pub const Float_64 = struct { pub const base_tag = Tag.float_64; base: Payload = .{ .tag = base_tag }, data: f64, }; pub const Float_128 = struct { pub const base_tag = Tag.float_128; base: Payload = .{ .tag = base_tag }, data: f128, }; pub const Error = struct { base: Payload = .{ .tag = .@"error" }, data: struct { /// `name` is owned by `Module` and will be valid for the entire /// duration of the compilation. /// TODO revisit this when we have the concept of the error tag type name: []const u8, }, }; pub const InferredAlloc = struct { pub const base_tag = Tag.inferred_alloc; base: Payload = .{ .tag = base_tag }, data: struct { /// The value stored in the inferred allocation. This will go into /// peer type resolution. This is stored in a separate list so that /// the items are contiguous in memory and thus can be passed to /// `Module.resolvePeerTypes`. stored_inst_list: std.ArrayListUnmanaged(*ir.Inst) = .{}, }, }; pub const Struct = struct { pub const base_tag = Tag.@"struct"; base: Payload = .{ .tag = base_tag }, /// Field values. The number and type are according to the struct type. data: [*]Value, }; pub const Union = struct { pub const base_tag = Tag.@"union"; base: Payload = .{ .tag = base_tag }, data: struct { tag: Value, val: Value, }, }; }; /// Big enough to fit any non-BigInt value pub const BigIntSpace = struct { /// The +1 is headroom so that operations such as incrementing once or decrementing once /// are possible without using an allocator. limbs: [(@sizeOf(u64) / @sizeOf(std.math.big.Limb)) + 1]std.math.big.Limb, }; }; test "hash same value different representation" { const zero_1 = Value.initTag(.zero); var payload_1 = Value.Payload.U64{ .base = .{ .tag = .int_u64 }, .data = 0, }; const zero_2 = Value.initPayload(&payload_1.base); try std.testing.expectEqual(zero_1.hash(), zero_2.hash()); var payload_2 = Value.Payload.I64{ .base = .{ .tag = .int_i64 }, .data = 0, }; const zero_3 = Value.initPayload(&payload_2.base); try std.testing.expectEqual(zero_2.hash(), zero_3.hash()); var payload_3 = Value.Payload.BigInt{ .base = .{ .tag = .int_big_negative }, .data = &[_]std.math.big.Limb{0}, }; const zero_4 = Value.initPayload(&payload_3.base); try std.testing.expectEqual(zero_3.hash(), zero_4.hash()); }
https://raw.githubusercontent.com/collinalexbell/all-the-compilers/7f834984f71054806bfec8604e02e86b99c0f831/zig/src/value.zig
const std = @import("std"); const os = @import("std").os; const DnsPacket = @import("packet.zig").DnsPacket; const Buffer = @import("buffer.zig").Buffer; const MAX_BUFF = @import("buffer.zig").MAX_BUFF; pub fn main() !void { const addr = try std.net.Address.parseIp("127.0.0.1", 53); const sock = try std.os.socket(std.os.AF.INET, std.os.SOCK.DGRAM, std.os.IPPROTO.UDP); defer std.os.close(sock); try std.os.bind(sock, &addr.any, addr.getOsSockLen()); while (true) { var dns_packet = DnsPacket.new(); var cliaddr: std.os.linux.sockaddr = undefined; var cliaddrlen: std.os.socklen_t = @sizeOf(os.linux.sockaddr); // buffer vullen met request data const len = try os.recvfrom(sock, dns_packet.get_buffer(), 0, &cliaddr, &cliaddrlen); _ = len; // dns pakket maken van buffer try dns_packet.parse(); try dns_packet.resolve(); dns_packet.buffer.index = 0; const client_sent = try os.sendto(sock, dns_packet.to_buffer().slice_from_start(), 0, &cliaddr, cliaddrlen); _ = client_sent; } }
https://raw.githubusercontent.com/joeydewaal/DNS/62e160945d2baabfbc435d07e2a8463f910d2da6/src/main.zig
const math = @import("std").math; pub fn isArmstrongNumber(num: u128) bool { var n = num; var numDigits: u8 = 0; while (n > 0) : (n /= 10) { numDigits += 1; } n = num; var sum: u128 = 0; while (n > 0) : (n /= 10) { sum += math.pow(u128, n % 10, numDigits); } return num == sum; }
https://raw.githubusercontent.com/ArturMroz/exercism/89c48a757e1e2e3b6973b8dd23366243337bbc30/zig/armstrong-numbers/armstrong_numbers.zig
const std = @import("std"); pub const Transports = @import("client/Transports.zig"); pub const cbor_commands = @import("client/cbor_commands.zig"); pub const err = @import("client/error.zig");
https://raw.githubusercontent.com/r4gus/keylib/4a9a400ab512cf6730051fca707ef8ead5c3b818/lib/client.zig
const std = @import("std"); pub fn main() void { var value: i32 = -1; // runtime-known _ = &value; const unsigned: u32 = @intCast(value); std.debug.print("value: {}\n", .{unsigned}); } // exe=fail
https://raw.githubusercontent.com/ziglang/zig/d9bd34fd0533295044ffb4160da41f7873aff905/doc/langref/runtime_invalid_cast.zig
usingnamespace @import("std").builtin; /// Deprecated pub const arch = Target.current.cpu.arch; /// Deprecated pub const endian = Target.current.cpu.arch.endian(); pub const output_mode = OutputMode.Obj; pub const link_mode = LinkMode.Static; pub const is_test = false; pub const single_threaded = false; pub const abi = Abi.msvc; pub const cpu: Cpu = Cpu{ .arch = .x86_64, .model = &Target.x86.cpu.skylake, .features = Target.x86.featureSet(&[_]Target.x86.Feature{ .@"64bit", .@"adx", .@"aes", .@"avx", .@"avx2", .@"bmi", .@"bmi2", .@"clflushopt", .@"cmov", .@"cx16", .@"cx8", .@"ermsb", .@"f16c", .@"false_deps_popcnt", .@"fast_15bytenop", .@"fast_gather", .@"fast_scalar_fsqrt", .@"fast_shld_rotate", .@"fast_variable_shuffle", .@"fast_vector_fsqrt", .@"fma", .@"fsgsbase", .@"fxsr", .@"idivq_to_divl", .@"invpcid", .@"lzcnt", .@"macrofusion", .@"merge_to_threeway_branch", .@"mmx", .@"movbe", .@"nopl", .@"pclmul", .@"popcnt", .@"prfchw", .@"rdrnd", .@"rdseed", .@"sahf", .@"slow_3ops_lea", .@"sse", .@"sse2", .@"sse3", .@"sse4_1", .@"sse4_2", .@"ssse3", .@"vzeroupper", .@"x87", .@"xsave", .@"xsavec", .@"xsaveopt", .@"xsaves", }), }; pub const os = Os{ .tag = .windows, .version_range = .{ .windows = .{ .min = .win10_20h1, .max = .win10_20h1, }}, }; pub const object_format = ObjectFormat.coff; pub const mode = Mode.Debug; pub const link_libc = false; pub const link_libcpp = false; pub const have_error_return_tracing = true; pub const valgrind_support = false; pub const position_independent_code = true; pub const strip_debug_info = false; pub const code_model = CodeModel.default;
https://raw.githubusercontent.com/creationix/zig-wasm-async/a71d0acd089942e3d9e5e95262a4f42765646d06/src/zig-cache/o/f93d1cf410b99bfb9beef8931313d820/builtin.zig
// // Grouping values in structs is not merely convenient. It also allows // us to treat the values as a single item when storing them, passing // them to functions, etc. // // This exercise demonstrates how we can store structs in an array and // how doing so lets us print them using a loop. // const std = @import("std"); const Role = enum { wizard, thief, bard, warrior, }; const Character = struct { role: Role, gold: u32, health: u8, experience: u32, }; pub fn main() void { var chars: [2]Character = undefined; // Glorp the Wise chars[0] = Character{ .role = Role.wizard, .gold = 20, .health = 100, .experience = 10, }; // Please add "Zump the Loud" with the following properties: // // role bard // gold 10 // health 100 // experience 20 // // Feel free to run this program without adding Zump. What does // it do and why? chars[1] = Character { .role = Role.bard, .gold = 10, .health = 100, .experience = 20, }; // Printing all RPG characters in a loop: for (chars, 0..) |c, num| { std.debug.print("Character {} - G:{} H:{} XP:{}\n", .{ num + 1, c.gold, c.health, c.experience, }); } } // If you tried running the program without adding Zump as mentioned // above, you get what appear to be "garbage" values. In debug mode // (which is the default), Zig writes the repeating pattern "10101010" // in binary (or 0xAA in hex) to all undefined locations to make them // easier to spot when debugging.
https://raw.githubusercontent.com/JanBaig/Ziglings/1a963e73e62a6cd27f2a49623c337fb615a35b3e/exercises/038_structs2.zig
const std = @import("std"); const fs_utils = @import("../utils/fs.zig"); pub fn run(allocator: std.mem.Allocator, args: std.ArrayList([]const u8)) anyerror!fs_utils.InitializationResult { if (args.items.len > 0) { // this could be -h // won't handle this case for now } const isInitialized = fs_utils.isRepositoryInitialized() catch |err| { std.log.err("{}", .{err}); return fs_utils.InitializationResult{ .err = err }; }; if (isInitialized) { std.log.info("Repository already initialized.\n", .{}); return fs_utils.InitializationResult.ok; } const init_result = fs_utils.initializeRepository(allocator); switch (init_result) { .ok => { std.debug.print("Initialized git_clone directory\n", .{}); }, .err => |err| { std.debug.print("Could not initialize the repository. {}\n", .{err}); }, } return init_result; }
https://raw.githubusercontent.com/RamziA961/git_clone/f5699222792eecf48792d71f4bcee7160a58b41b/src/commands/init.zig
///! Handles a task queue for multithreading const std = @import("std"); const Allocator = std.mem.Allocator; const Thread = std.Thread; const Atomic = std.atomic.Value; const ms = std.time.ns_per_ms; /// The struct that handles task management. pub const TaskManager = struct { const Self = @This(); pub const Task = struct { data: *anyopaque, do: *const fn(data: *anyopaque) anyerror!void, next: ?*Task = null, }; const threadCount = 32; top: ?*Task = null, lock: Thread.Mutex = .{}, threads: [threadCount]Thread = undefined, done: Atomic(bool) = undefined, totalTasks: u64 = 0, // total tasks requested tasksCompleted: Atomic(u64), // total tasks completed pub fn init() Self { return Self { .done = Atomic(bool).init(false), .tasksCompleted = Atomic(u64).init(0) }; } pub fn deinit(self: *Self) void { self.done.store(true, .Monotonic); for(&self.threads) |*t| { t.join(); } } pub fn startThreads(self: *Self) !void { for(&self.threads) |*t| t.* = try Thread.spawn(.{}, doTasks, .{self}); } pub fn queue(self: *Self, task: *Task) void { self.totalTasks += 1; self.lock.lock(); defer self.lock.unlock(); task.next = self.top; self.top = task; } pub fn dequeue(self: *Self) ?*Task { self.lock.lock(); defer self.lock.unlock(); if(self.top == null) return null; const top = self.top; self.top = self.top.?.next; return top; } const inactivityDelay = 200*ms; fn doTasks(self: *Self) !void { // after 1 second of inactivity, this continually sleeps for one second. var lastActive = std.time.nanoTimestamp(); while(true) { while(self.dequeue()) |task| { try task.do(task.data); lastActive = std.time.nanoTimestamp(); _ = self.tasksCompleted.fetchAdd(1, .Monotonic); } if(std.time.nanoTimestamp()-lastActive < inactivityDelay) continue; if(self.done.load(.Monotonic)) break; std.time.sleep(inactivityDelay); } } pub fn wait(self: *Self) !void { while(self.tasksCompleted.load(.Monotonic) != self.totalTasks) { std.time.sleep(1); } } };
https://raw.githubusercontent.com/TheZipCreator/codevolution/1e96a3c88ce111a227ad587765ac8f44aafc50b5/src/task.zig
const std = @import("../std.zig"); const builtin = @import("builtin"); const root = @import("root"); const assert = std.debug.assert; const testing = std.testing; const mem = std.mem; const os = std.os; const windows = os.windows; const maxInt = std.math.maxInt; const Thread = std.Thread; const is_windows = builtin.os.tag == .windows; pub const Loop = struct { next_tick_queue: std.atomic.Queue(anyframe), os_data: OsData, final_resume_node: ResumeNode, pending_event_count: usize, extra_threads: []Thread, /// TODO change this to a pool of configurable number of threads /// and rename it to be not file-system-specific. it will become /// a thread pool for turning non-CPU-bound blocking things into /// async things. A fallback for any missing OS-specific API. fs_thread: Thread, fs_queue: std.atomic.Queue(Request), fs_end_request: Request.Node, fs_thread_wakeup: std.Thread.ResetEvent, /// For resources that have the same lifetime as the `Loop`. /// This is only used by `Loop` for the thread pool and associated resources. arena: std.heap.ArenaAllocator, /// State which manages frames that are sleeping on timers delay_queue: DelayQueue, /// Pre-allocated eventfds. All permanently active. /// This is how `Loop` sends promises to be resumed on other threads. available_eventfd_resume_nodes: std.atomic.Stack(ResumeNode.EventFd), eventfd_resume_nodes: []std.atomic.Stack(ResumeNode.EventFd).Node, pub const NextTickNode = std.atomic.Queue(anyframe).Node; pub const ResumeNode = struct { id: Id, handle: anyframe, overlapped: Overlapped, pub const overlapped_init = switch (builtin.os.tag) { .windows => windows.OVERLAPPED{ .Internal = 0, .InternalHigh = 0, .DUMMYUNIONNAME = .{ .DUMMYSTRUCTNAME = .{ .Offset = 0, .OffsetHigh = 0, }, }, .hEvent = null, }, else => {}, }; pub const Overlapped = @TypeOf(overlapped_init); pub const Id = enum { Basic, Stop, EventFd, }; pub const EventFd = switch (builtin.os.tag) { .macos, .freebsd, .netbsd, .dragonfly, .openbsd => KEventFd, .linux => struct { base: ResumeNode, epoll_op: u32, eventfd: i32, }, .windows => struct { base: ResumeNode, completion_key: usize, }, else => struct {}, }; const KEventFd = struct { base: ResumeNode, kevent: os.Kevent, }; pub const Basic = switch (builtin.os.tag) { .macos, .freebsd, .netbsd, .dragonfly, .openbsd => KEventBasic, .linux => struct { base: ResumeNode, }, .windows => struct { base: ResumeNode, }, else => @compileError("unsupported OS"), }; const KEventBasic = struct { base: ResumeNode, kev: os.Kevent, }; }; var global_instance_state: Loop = undefined; const default_instance: ?*Loop = switch (std.io.mode) { .blocking => null, .evented => &global_instance_state, }; pub const instance: ?*Loop = if (@hasDecl(root, "event_loop")) root.event_loop else default_instance; /// TODO copy elision / named return values so that the threads referencing *Loop /// have the correct pointer value. /// https://github.com/ziglang/zig/issues/2761 and https://github.com/ziglang/zig/issues/2765 pub fn init(self: *Loop) !void { if (builtin.single_threaded or (@hasDecl(root, "event_loop_mode") and root.event_loop_mode == .single_threaded)) { return self.initSingleThreaded(); } else { return self.initMultiThreaded(); } } /// After initialization, call run(). /// TODO copy elision / named return values so that the threads referencing *Loop /// have the correct pointer value. /// https://github.com/ziglang/zig/issues/2761 and https://github.com/ziglang/zig/issues/2765 pub fn initSingleThreaded(self: *Loop) !void { return self.initThreadPool(1); } /// After initialization, call run(). /// This is the same as `initThreadPool` using `Thread.getCpuCount` to determine the thread /// pool size. /// TODO copy elision / named return values so that the threads referencing *Loop /// have the correct pointer value. /// https://github.com/ziglang/zig/issues/2761 and https://github.com/ziglang/zig/issues/2765 pub fn initMultiThreaded(self: *Loop) !void { if (builtin.single_threaded) @compileError("initMultiThreaded unavailable when building in single-threaded mode"); const core_count = try Thread.getCpuCount(); return self.initThreadPool(core_count); } /// Thread count is the total thread count. The thread pool size will be /// max(thread_count - 1, 0) pub fn initThreadPool(self: *Loop, thread_count: usize) !void { self.* = Loop{ .arena = std.heap.ArenaAllocator.init(std.heap.page_allocator), .pending_event_count = 1, .os_data = undefined, .next_tick_queue = std.atomic.Queue(anyframe).init(), .extra_threads = undefined, .available_eventfd_resume_nodes = std.atomic.Stack(ResumeNode.EventFd).init(), .eventfd_resume_nodes = undefined, .final_resume_node = ResumeNode{ .id = ResumeNode.Id.Stop, .handle = undefined, .overlapped = ResumeNode.overlapped_init, }, .fs_end_request = .{ .data = .{ .msg = .end, .finish = .NoAction } }, .fs_queue = std.atomic.Queue(Request).init(), .fs_thread = undefined, .fs_thread_wakeup = undefined, .delay_queue = undefined, }; try self.fs_thread_wakeup.init(); errdefer self.fs_thread_wakeup.deinit(); errdefer self.arena.deinit(); // We need at least one of these in case the fs thread wants to use onNextTick const extra_thread_count = thread_count - 1; const resume_node_count = std.math.max(extra_thread_count, 1); self.eventfd_resume_nodes = try self.arena.allocator.alloc( std.atomic.Stack(ResumeNode.EventFd).Node, resume_node_count, ); self.extra_threads = try self.arena.allocator.alloc(Thread, extra_thread_count); try self.initOsData(extra_thread_count); errdefer self.deinitOsData(); if (!builtin.single_threaded) { self.fs_thread = try Thread.spawn(.{}, posixFsRun, .{self}); } errdefer if (!builtin.single_threaded) { self.posixFsRequest(&self.fs_end_request); self.fs_thread.join(); }; if (!builtin.single_threaded) try self.delay_queue.init(); } pub fn deinit(self: *Loop) void { self.deinitOsData(); self.fs_thread_wakeup.deinit(); self.arena.deinit(); self.* = undefined; } const InitOsDataError = os.EpollCreateError || mem.Allocator.Error || os.EventFdError || Thread.SpawnError || os.EpollCtlError || os.KEventError || windows.CreateIoCompletionPortError; const wakeup_bytes = [_]u8{0x1} ** 8; fn initOsData(self: *Loop, extra_thread_count: usize) InitOsDataError!void { nosuspend switch (builtin.os.tag) { .linux => { errdefer { while (self.available_eventfd_resume_nodes.pop()) |node| os.close(node.data.eventfd); } for (self.eventfd_resume_nodes) |*eventfd_node| { eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{ .data = ResumeNode.EventFd{ .base = ResumeNode{ .id = .EventFd, .handle = undefined, .overlapped = ResumeNode.overlapped_init, }, .eventfd = try os.eventfd(1, os.linux.EFD.CLOEXEC | os.linux.EFD.NONBLOCK), .epoll_op = os.linux.EPOLL.CTL_ADD, }, .next = undefined, }; self.available_eventfd_resume_nodes.push(eventfd_node); } self.os_data.epollfd = try os.epoll_create1(os.linux.EPOLL.CLOEXEC); errdefer os.close(self.os_data.epollfd); self.os_data.final_eventfd = try os.eventfd(0, os.linux.EFD.CLOEXEC | os.linux.EFD.NONBLOCK); errdefer os.close(self.os_data.final_eventfd); self.os_data.final_eventfd_event = os.linux.epoll_event{ .events = os.linux.EPOLL.IN, .data = os.linux.epoll_data{ .ptr = @intFromPtr(&self.final_resume_node) }, }; try os.epoll_ctl( self.os_data.epollfd, os.linux.EPOLL.CTL_ADD, self.os_data.final_eventfd, &self.os_data.final_eventfd_event, ); if (builtin.single_threaded) { assert(extra_thread_count == 0); return; } var extra_thread_index: usize = 0; errdefer { // writing 8 bytes to an eventfd cannot fail const amt = os.write(self.os_data.final_eventfd, &wakeup_bytes) catch unreachable; assert(amt == wakeup_bytes.len); while (extra_thread_index != 0) { extra_thread_index -= 1; self.extra_threads[extra_thread_index].join(); } } while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) { self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self}); } }, .macos, .freebsd, .netbsd, .dragonfly => { self.os_data.kqfd = try os.kqueue(); errdefer os.close(self.os_data.kqfd); const empty_kevs = &[0]os.Kevent{}; for (self.eventfd_resume_nodes, 0..) |*eventfd_node, i| { eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{ .data = ResumeNode.EventFd{ .base = ResumeNode{ .id = ResumeNode.Id.EventFd, .handle = undefined, .overlapped = ResumeNode.overlapped_init, }, // this one is for sending events .kevent = os.Kevent{ .ident = i, .filter = os.system.EVFILT_USER, .flags = os.system.EV_CLEAR | os.system.EV_ADD | os.system.EV_DISABLE, .fflags = 0, .data = 0, .udata = @intFromPtr(&eventfd_node.data.base), }, }, .next = undefined, }; self.available_eventfd_resume_nodes.push(eventfd_node); const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.data.kevent); _ = try os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null); eventfd_node.data.kevent.flags = os.system.EV_CLEAR | os.system.EV_ENABLE; eventfd_node.data.kevent.fflags = os.system.NOTE_TRIGGER; } // Pre-add so that we cannot get error.SystemResources // later when we try to activate it. self.os_data.final_kevent = os.Kevent{ .ident = extra_thread_count, .filter = os.system.EVFILT_USER, .flags = os.system.EV_ADD | os.system.EV_DISABLE, .fflags = 0, .data = 0, .udata = @intFromPtr(&self.final_resume_node), }; const final_kev_arr = @as(*const [1]os.Kevent, &self.os_data.final_kevent); _ = try os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null); self.os_data.final_kevent.flags = os.system.EV_ENABLE; self.os_data.final_kevent.fflags = os.system.NOTE_TRIGGER; if (builtin.single_threaded) { assert(extra_thread_count == 0); return; } var extra_thread_index: usize = 0; errdefer { _ = os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null) catch unreachable; while (extra_thread_index != 0) { extra_thread_index -= 1; self.extra_threads[extra_thread_index].join(); } } while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) { self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self}); } }, .openbsd => { self.os_data.kqfd = try os.kqueue(); errdefer os.close(self.os_data.kqfd); const empty_kevs = &[0]os.Kevent{}; for (self.eventfd_resume_nodes, 0..) |*eventfd_node, i| { eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{ .data = ResumeNode.EventFd{ .base = ResumeNode{ .id = ResumeNode.Id.EventFd, .handle = undefined, .overlapped = ResumeNode.overlapped_init, }, // this one is for sending events .kevent = os.Kevent{ .ident = i, .filter = os.system.EVFILT_TIMER, .flags = os.system.EV_CLEAR | os.system.EV_ADD | os.system.EV_DISABLE | os.system.EV_ONESHOT, .fflags = 0, .data = 0, .udata = @intFromPtr(&eventfd_node.data.base), }, }, .next = undefined, }; self.available_eventfd_resume_nodes.push(eventfd_node); const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.data.kevent); _ = try os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null); eventfd_node.data.kevent.flags = os.system.EV_CLEAR | os.system.EV_ENABLE; } // Pre-add so that we cannot get error.SystemResources // later when we try to activate it. self.os_data.final_kevent = os.Kevent{ .ident = extra_thread_count, .filter = os.system.EVFILT_TIMER, .flags = os.system.EV_ADD | os.system.EV_ONESHOT | os.system.EV_DISABLE, .fflags = 0, .data = 0, .udata = @intFromPtr(&self.final_resume_node), }; const final_kev_arr = @as(*const [1]os.Kevent, &self.os_data.final_kevent); _ = try os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null); self.os_data.final_kevent.flags = os.system.EV_ENABLE; if (builtin.single_threaded) { assert(extra_thread_count == 0); return; } var extra_thread_index: usize = 0; errdefer { _ = os.kevent(self.os_data.kqfd, final_kev_arr, empty_kevs, null) catch unreachable; while (extra_thread_index != 0) { extra_thread_index -= 1; self.extra_threads[extra_thread_index].join(); } } while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) { self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self}); } }, .windows => { self.os_data.io_port = try windows.CreateIoCompletionPort( windows.INVALID_HANDLE_VALUE, null, undefined, maxInt(windows.DWORD), ); errdefer windows.CloseHandle(self.os_data.io_port); for (self.eventfd_resume_nodes) |*eventfd_node| { eventfd_node.* = std.atomic.Stack(ResumeNode.EventFd).Node{ .data = ResumeNode.EventFd{ .base = ResumeNode{ .id = ResumeNode.Id.EventFd, .handle = undefined, .overlapped = ResumeNode.overlapped_init, }, // this one is for sending events .completion_key = @intFromPtr(&eventfd_node.data.base), }, .next = undefined, }; self.available_eventfd_resume_nodes.push(eventfd_node); } if (builtin.single_threaded) { assert(extra_thread_count == 0); return; } var extra_thread_index: usize = 0; errdefer { var i: usize = 0; while (i < extra_thread_index) : (i += 1) { while (true) { const overlapped = &self.final_resume_node.overlapped; windows.PostQueuedCompletionStatus(self.os_data.io_port, undefined, undefined, overlapped) catch continue; break; } } while (extra_thread_index != 0) { extra_thread_index -= 1; self.extra_threads[extra_thread_index].join(); } } while (extra_thread_index < extra_thread_count) : (extra_thread_index += 1) { self.extra_threads[extra_thread_index] = try Thread.spawn(.{}, workerRun, .{self}); } }, else => {}, }; } fn deinitOsData(self: *Loop) void { nosuspend switch (builtin.os.tag) { .linux => { os.close(self.os_data.final_eventfd); while (self.available_eventfd_resume_nodes.pop()) |node| os.close(node.data.eventfd); os.close(self.os_data.epollfd); }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { os.close(self.os_data.kqfd); }, .windows => { windows.CloseHandle(self.os_data.io_port); }, else => {}, }; } /// resume_node must live longer than the anyframe that it holds a reference to. /// flags must contain EPOLLET pub fn linuxAddFd(self: *Loop, fd: i32, resume_node: *ResumeNode, flags: u32) !void { assert(flags & os.linux.EPOLL.ET == os.linux.EPOLL.ET); self.beginOneEvent(); errdefer self.finishOneEvent(); try self.linuxModFd( fd, os.linux.EPOLL.CTL_ADD, flags, resume_node, ); } pub fn linuxModFd(self: *Loop, fd: i32, op: u32, flags: u32, resume_node: *ResumeNode) !void { assert(flags & os.linux.EPOLL.ET == os.linux.EPOLL.ET); var ev = os.linux.epoll_event{ .events = flags, .data = os.linux.epoll_data{ .ptr = @intFromPtr(resume_node) }, }; try os.epoll_ctl(self.os_data.epollfd, op, fd, &ev); } pub fn linuxRemoveFd(self: *Loop, fd: i32) void { os.epoll_ctl(self.os_data.epollfd, os.linux.EPOLL.CTL_DEL, fd, null) catch {}; self.finishOneEvent(); } pub fn linuxWaitFd(self: *Loop, fd: i32, flags: u32) void { assert(flags & os.linux.EPOLL.ET == os.linux.EPOLL.ET); assert(flags & os.linux.EPOLL.ONESHOT == os.linux.EPOLL.ONESHOT); var resume_node = ResumeNode.Basic{ .base = ResumeNode{ .id = .Basic, .handle = @frame(), .overlapped = ResumeNode.overlapped_init, }, }; var need_to_delete = true; defer if (need_to_delete) self.linuxRemoveFd(fd); suspend { self.linuxAddFd(fd, &resume_node.base, flags) catch |err| switch (err) { error.FileDescriptorNotRegistered => unreachable, error.OperationCausesCircularLoop => unreachable, error.FileDescriptorIncompatibleWithEpoll => unreachable, error.FileDescriptorAlreadyPresentInSet => unreachable, // evented writes to the same fd is not thread-safe error.SystemResources, error.UserResourceLimitReached, error.Unexpected, => { need_to_delete = false; // Fall back to a blocking poll(). Ideally this codepath is never hit, since // epoll should be just fine. But this is better than incorrect behavior. var poll_flags: i16 = 0; if ((flags & os.linux.EPOLL.IN) != 0) poll_flags |= os.POLL.IN; if ((flags & os.linux.EPOLL.OUT) != 0) poll_flags |= os.POLL.OUT; var pfd = [1]os.pollfd{os.pollfd{ .fd = fd, .events = poll_flags, .revents = undefined, }}; _ = os.poll(&pfd, -1) catch |poll_err| switch (poll_err) { error.NetworkSubsystemFailed => unreachable, // only possible on windows error.SystemResources, error.Unexpected, => { // Even poll() didn't work. The best we can do now is sleep for a // small duration and then hope that something changed. std.time.sleep(1 * std.time.ns_per_ms); }, }; resume @frame(); }, }; } } pub fn waitUntilFdReadable(self: *Loop, fd: os.fd_t) void { switch (builtin.os.tag) { .linux => { self.linuxWaitFd(fd, os.linux.EPOLL.ET | os.linux.EPOLL.ONESHOT | os.linux.EPOLL.IN); }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_READ, os.system.EV_ONESHOT); }, else => @compileError("Unsupported OS"), } } pub fn waitUntilFdWritable(self: *Loop, fd: os.fd_t) void { switch (builtin.os.tag) { .linux => { self.linuxWaitFd(fd, os.linux.EPOLL.ET | os.linux.EPOLL.ONESHOT | os.linux.EPOLL.OUT); }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_WRITE, os.system.EV_ONESHOT); }, else => @compileError("Unsupported OS"), } } pub fn waitUntilFdWritableOrReadable(self: *Loop, fd: os.fd_t) void { switch (builtin.os.tag) { .linux => { self.linuxWaitFd(fd, os.linux.EPOLL.ET | os.linux.EPOLL.ONESHOT | os.linux.EPOLL.OUT | os.linux.EPOLL.IN); }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_READ, os.system.EV_ONESHOT); self.bsdWaitKev(@as(usize, @intCast(fd)), os.system.EVFILT_WRITE, os.system.EV_ONESHOT); }, else => @compileError("Unsupported OS"), } } pub fn bsdWaitKev(self: *Loop, ident: usize, filter: i16, flags: u16) void { var resume_node = ResumeNode.Basic{ .base = ResumeNode{ .id = ResumeNode.Id.Basic, .handle = @frame(), .overlapped = ResumeNode.overlapped_init, }, .kev = undefined, }; defer { // If the kevent was set to be ONESHOT, it doesn't need to be deleted manually. if (flags & os.system.EV_ONESHOT != 0) { self.bsdRemoveKev(ident, filter); } } suspend { self.bsdAddKev(&resume_node, ident, filter, flags) catch unreachable; } } /// resume_node must live longer than the anyframe that it holds a reference to. pub fn bsdAddKev(self: *Loop, resume_node: *ResumeNode.Basic, ident: usize, filter: i16, flags: u16) !void { self.beginOneEvent(); errdefer self.finishOneEvent(); var kev = [1]os.Kevent{os.Kevent{ .ident = ident, .filter = filter, .flags = os.system.EV_ADD | os.system.EV_ENABLE | os.system.EV_CLEAR | flags, .fflags = 0, .data = 0, .udata = @intFromPtr(&resume_node.base), }}; const empty_kevs = &[0]os.Kevent{}; _ = try os.kevent(self.os_data.kqfd, &kev, empty_kevs, null); } pub fn bsdRemoveKev(self: *Loop, ident: usize, filter: i16) void { var kev = [1]os.Kevent{os.Kevent{ .ident = ident, .filter = filter, .flags = os.system.EV_DELETE, .fflags = 0, .data = 0, .udata = 0, }}; const empty_kevs = &[0]os.Kevent{}; _ = os.kevent(self.os_data.kqfd, &kev, empty_kevs, null) catch undefined; self.finishOneEvent(); } fn dispatch(self: *Loop) void { while (self.available_eventfd_resume_nodes.pop()) |resume_stack_node| { const next_tick_node = self.next_tick_queue.get() orelse { self.available_eventfd_resume_nodes.push(resume_stack_node); return; }; const eventfd_node = &resume_stack_node.data; eventfd_node.base.handle = next_tick_node.data; switch (builtin.os.tag) { .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { const kevent_array = @as(*const [1]os.Kevent, &eventfd_node.kevent); const empty_kevs = &[0]os.Kevent{}; _ = os.kevent(self.os_data.kqfd, kevent_array, empty_kevs, null) catch { self.next_tick_queue.unget(next_tick_node); self.available_eventfd_resume_nodes.push(resume_stack_node); return; }; }, .linux => { // the pending count is already accounted for const epoll_events = os.linux.EPOLL.ONESHOT | os.linux.EPOLL.IN | os.linux.EPOLL.OUT | os.linux.EPOLL.ET; self.linuxModFd( eventfd_node.eventfd, eventfd_node.epoll_op, epoll_events, &eventfd_node.base, ) catch { self.next_tick_queue.unget(next_tick_node); self.available_eventfd_resume_nodes.push(resume_stack_node); return; }; }, .windows => { windows.PostQueuedCompletionStatus( self.os_data.io_port, undefined, undefined, &eventfd_node.base.overlapped, ) catch { self.next_tick_queue.unget(next_tick_node); self.available_eventfd_resume_nodes.push(resume_stack_node); return; }; }, else => @compileError("unsupported OS"), } } } /// Bring your own linked list node. This means it can't fail. pub fn onNextTick(self: *Loop, node: *NextTickNode) void { self.beginOneEvent(); // finished in dispatch() self.next_tick_queue.put(node); self.dispatch(); } pub fn cancelOnNextTick(self: *Loop, node: *NextTickNode) void { if (self.next_tick_queue.remove(node)) { self.finishOneEvent(); } } pub fn run(self: *Loop) void { self.finishOneEvent(); // the reference we start with self.workerRun(); if (!builtin.single_threaded) { switch (builtin.os.tag) { .linux, .macos, .freebsd, .netbsd, .dragonfly, .openbsd, => self.fs_thread.join(), else => {}, } } for (self.extra_threads) |extra_thread| { extra_thread.join(); } @atomicStore(bool, &self.delay_queue.is_running, false, .SeqCst); self.delay_queue.event.set(); self.delay_queue.thread.join(); } /// Runs the provided function asynchronously. The function's frame is allocated /// with `allocator` and freed when the function returns. /// `func` must return void and it can be an async function. /// Yields to the event loop, running the function on the next tick. pub fn runDetached(self: *Loop, alloc: *mem.Allocator, comptime func: anytype, args: anytype) error{OutOfMemory}!void { if (!std.io.is_async) @compileError("Can't use runDetached in non-async mode!"); if (@TypeOf(@call(.{}, func, args)) != void) { @compileError("`func` must not have a return value"); } const Wrapper = struct { const Args = @TypeOf(args); fn run(func_args: Args, loop: *Loop, allocator: *mem.Allocator) void { loop.beginOneEvent(); loop.yield(); @call(.{}, func, func_args); // compile error when called with non-void ret type suspend { loop.finishOneEvent(); allocator.destroy(@frame()); } } }; var run_frame = try alloc.create(@Frame(Wrapper.run)); run_frame.* = async Wrapper.run(args, self, alloc); } /// Yielding lets the event loop run, starting any unstarted async operations. /// Note that async operations automatically start when a function yields for any other reason, /// for example, when async I/O is performed. This function is intended to be used only when /// CPU bound tasks would be waiting in the event loop but never get started because no async I/O /// is performed. pub fn yield(self: *Loop) void { suspend { var my_tick_node = NextTickNode{ .prev = undefined, .next = undefined, .data = @frame(), }; self.onNextTick(&my_tick_node); } } /// If the build is multi-threaded and there is an event loop, then it calls `yield`. Otherwise, /// does nothing. pub fn startCpuBoundOperation() void { if (builtin.single_threaded) { return; } else if (instance) |event_loop| { event_loop.yield(); } } /// call finishOneEvent when done pub fn beginOneEvent(self: *Loop) void { _ = @atomicRmw(usize, &self.pending_event_count, .Add, 1, .SeqCst); } pub fn finishOneEvent(self: *Loop) void { nosuspend { const prev = @atomicRmw(usize, &self.pending_event_count, .Sub, 1, .SeqCst); if (prev != 1) return; // cause all the threads to stop self.posixFsRequest(&self.fs_end_request); switch (builtin.os.tag) { .linux => { // writing to the eventfd will only wake up one thread, thus multiple writes // are needed to wakeup all the threads var i: usize = 0; while (i < self.extra_threads.len + 1) : (i += 1) { // writing 8 bytes to an eventfd cannot fail const amt = os.write(self.os_data.final_eventfd, &wakeup_bytes) catch unreachable; assert(amt == wakeup_bytes.len); } return; }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { const final_kevent = @as(*const [1]os.Kevent, &self.os_data.final_kevent); const empty_kevs = &[0]os.Kevent{}; // cannot fail because we already added it and this just enables it _ = os.kevent(self.os_data.kqfd, final_kevent, empty_kevs, null) catch unreachable; return; }, .windows => { var i: usize = 0; while (i < self.extra_threads.len + 1) : (i += 1) { while (true) { const overlapped = &self.final_resume_node.overlapped; windows.PostQueuedCompletionStatus(self.os_data.io_port, undefined, undefined, overlapped) catch continue; break; } } return; }, else => @compileError("unsupported OS"), } } } pub fn sleep(self: *Loop, nanoseconds: u64) void { if (builtin.single_threaded) @compileError("TODO: integrate timers with epoll/kevent/iocp for single-threaded"); suspend { const now = self.delay_queue.timer.read(); var entry: DelayQueue.Waiters.Entry = undefined; entry.init(@frame(), now + nanoseconds); self.delay_queue.waiters.insert(&entry); // Speculatively wake up the timer thread when we add a new entry. // If the timer thread is sleeping on a longer entry, we need to // interrupt it so that our entry can be expired in time. self.delay_queue.event.set(); } } const DelayQueue = struct { timer: std.time.Timer, waiters: Waiters, thread: std.Thread, event: std.Thread.AutoResetEvent, is_running: bool, /// Initialize the delay queue by spawning the timer thread /// and starting any timer resources. fn init(self: *DelayQueue) !void { self.* = DelayQueue{ .timer = try std.time.Timer.start(), .waiters = DelayQueue.Waiters{ .entries = std.atomic.Queue(anyframe).init(), }, .event = std.Thread.AutoResetEvent{}, .is_running = true, // Must be last so that it can read the other state, such as `is_running`. .thread = try std.Thread.spawn(.{}, DelayQueue.run, .{self}), }; } /// Entry point for the timer thread /// which waits for timer entries to expire and reschedules them. fn run(self: *DelayQueue) void { const loop = @fieldParentPtr(Loop, "delay_queue", self); while (@atomicLoad(bool, &self.is_running, .SeqCst)) { const now = self.timer.read(); if (self.waiters.popExpired(now)) |entry| { loop.onNextTick(&entry.node); continue; } if (self.waiters.nextExpire()) |expires| { if (now >= expires) continue; self.event.timedWait(expires - now) catch {}; } else { self.event.wait(); } } } // TODO: use a tickless heirarchical timer wheel: // https://github.com/wahern/timeout/ const Waiters = struct { entries: std.atomic.Queue(anyframe), const Entry = struct { node: NextTickNode, expires: u64, fn init(self: *Entry, frame: anyframe, expires: u64) void { self.node.data = frame; self.expires = expires; } }; /// Registers the entry into the queue of waiting frames fn insert(self: *Waiters, entry: *Entry) void { self.entries.put(&entry.node); } /// Dequeues one expired event relative to `now` fn popExpired(self: *Waiters, now: u64) ?*Entry { const entry = self.peekExpiringEntry() orelse return null; if (entry.expires > now) return null; assert(self.entries.remove(&entry.node)); return entry; } /// Returns an estimate for the amount of time /// to wait until the next waiting entry expires. fn nextExpire(self: *Waiters) ?u64 { const entry = self.peekExpiringEntry() orelse return null; return entry.expires; } fn peekExpiringEntry(self: *Waiters) ?*Entry { const held = self.entries.mutex.acquire(); defer held.release(); // starting from the head var head = self.entries.head orelse return null; // traverse the list of waiting entires to // find the Node with the smallest `expires` field var min = head; while (head.next) |node| { const minEntry = @fieldParentPtr(Entry, "node", min); const nodeEntry = @fieldParentPtr(Entry, "node", node); if (nodeEntry.expires < minEntry.expires) min = node; head = node; } return @fieldParentPtr(Entry, "node", min); } }; }; /// ------- I/0 APIs ------- pub fn accept( self: *Loop, /// This argument is a socket that has been created with `socket`, bound to a local address /// with `bind`, and is listening for connections after a `listen`. sockfd: os.socket_t, /// This argument is a pointer to a sockaddr structure. This structure is filled in with the /// address of the peer socket, as known to the communications layer. The exact format of the /// address returned addr is determined by the socket's address family (see `socket` and the /// respective protocol man pages). addr: *os.sockaddr, /// This argument is a value-result argument: the caller must initialize it to contain the /// size (in bytes) of the structure pointed to by addr; on return it will contain the actual size /// of the peer address. /// /// The returned address is truncated if the buffer provided is too small; in this case, `addr_size` /// will return a value greater than was supplied to the call. addr_size: *os.socklen_t, /// The following values can be bitwise ORed in flags to obtain different behavior: /// * `SOCK.CLOEXEC` - Set the close-on-exec (`FD_CLOEXEC`) flag on the new file descriptor. See the /// description of the `O.CLOEXEC` flag in `open` for reasons why this may be useful. flags: u32, ) os.AcceptError!os.socket_t { while (true) { return os.accept(sockfd, addr, addr_size, flags | os.SOCK.NONBLOCK) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdReadable(sockfd); continue; }, else => return err, }; } } pub fn connect(self: *Loop, sockfd: os.socket_t, sock_addr: *const os.sockaddr, len: os.socklen_t) os.ConnectError!void { os.connect(sockfd, sock_addr, len) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdWritable(sockfd); return os.getsockoptError(sockfd); }, else => return err, }; } /// Performs an async `os.open` using a separate thread. pub fn openZ(self: *Loop, file_path: [*:0]const u8, flags: u32, mode: os.mode_t) os.OpenError!os.fd_t { var req_node = Request.Node{ .data = .{ .msg = .{ .open = .{ .path = file_path, .flags = flags, .mode = mode, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.open.result; } /// Performs an async `os.opent` using a separate thread. pub fn openatZ(self: *Loop, fd: os.fd_t, file_path: [*:0]const u8, flags: u32, mode: os.mode_t) os.OpenError!os.fd_t { var req_node = Request.Node{ .data = .{ .msg = .{ .openat = .{ .fd = fd, .path = file_path, .flags = flags, .mode = mode, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.openat.result; } /// Performs an async `os.close` using a separate thread. pub fn close(self: *Loop, fd: os.fd_t) void { var req_node = Request.Node{ .data = .{ .msg = .{ .close = .{ .fd = fd } }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } } /// Performs an async `os.read` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn read(self: *Loop, fd: os.fd_t, buf: []u8, simulate_evented: bool) os.ReadError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .read = .{ .fd = fd, .buf = buf, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.read.result; } else { while (true) { return os.read(fd, buf) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdReadable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.readv` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn readv(self: *Loop, fd: os.fd_t, iov: []const os.iovec, simulate_evented: bool) os.ReadError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .readv = .{ .fd = fd, .iov = iov, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.readv.result; } else { while (true) { return os.readv(fd, iov) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdReadable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.pread` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn pread(self: *Loop, fd: os.fd_t, buf: []u8, offset: u64, simulate_evented: bool) os.PReadError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .pread = .{ .fd = fd, .buf = buf, .offset = offset, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.pread.result; } else { while (true) { return os.pread(fd, buf, offset) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdReadable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.preadv` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn preadv(self: *Loop, fd: os.fd_t, iov: []const os.iovec, offset: u64, simulate_evented: bool) os.ReadError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .preadv = .{ .fd = fd, .iov = iov, .offset = offset, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.preadv.result; } else { while (true) { return os.preadv(fd, iov, offset) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdReadable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.write` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn write(self: *Loop, fd: os.fd_t, bytes: []const u8, simulate_evented: bool) os.WriteError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .write = .{ .fd = fd, .bytes = bytes, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.write.result; } else { while (true) { return os.write(fd, bytes) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdWritable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.writev` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn writev(self: *Loop, fd: os.fd_t, iov: []const os.iovec_const, simulate_evented: bool) os.WriteError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .writev = .{ .fd = fd, .iov = iov, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.writev.result; } else { while (true) { return os.writev(fd, iov) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdWritable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.pwrite` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn pwrite(self: *Loop, fd: os.fd_t, bytes: []const u8, offset: u64, simulate_evented: bool) os.PerformsWriteError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .pwrite = .{ .fd = fd, .bytes = bytes, .offset = offset, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.pwrite.result; } else { while (true) { return os.pwrite(fd, bytes, offset) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdWritable(fd); continue; }, else => return err, }; } } } /// Performs an async `os.pwritev` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn pwritev(self: *Loop, fd: os.fd_t, iov: []const os.iovec_const, offset: u64, simulate_evented: bool) os.PWriteError!usize { if (simulate_evented) { var req_node = Request.Node{ .data = .{ .msg = .{ .pwritev = .{ .fd = fd, .iov = iov, .offset = offset, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.pwritev.result; } else { while (true) { return os.pwritev(fd, iov, offset) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdWritable(fd); continue; }, else => return err, }; } } } pub fn sendto( self: *Loop, /// The file descriptor of the sending socket. sockfd: os.fd_t, /// Message to send. buf: []const u8, flags: u32, dest_addr: ?*const os.sockaddr, addrlen: os.socklen_t, ) os.SendToError!usize { while (true) { return os.sendto(sockfd, buf, flags, dest_addr, addrlen) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdWritable(sockfd); continue; }, else => return err, }; } } pub fn recvfrom( self: *Loop, sockfd: os.fd_t, buf: []u8, flags: u32, src_addr: ?*os.sockaddr, addrlen: ?*os.socklen_t, ) os.RecvFromError!usize { while (true) { return os.recvfrom(sockfd, buf, flags, src_addr, addrlen) catch |err| switch (err) { error.WouldBlock => { self.waitUntilFdReadable(sockfd); continue; }, else => return err, }; } } /// Performs an async `os.faccessatZ` using a separate thread. /// `fd` must block and not return EAGAIN. pub fn faccessatZ( self: *Loop, dirfd: os.fd_t, path_z: [*:0]const u8, mode: u32, flags: u32, ) os.AccessError!void { var req_node = Request.Node{ .data = .{ .msg = .{ .faccessat = .{ .dirfd = dirfd, .path = path_z, .mode = mode, .flags = flags, .result = undefined, }, }, .finish = .{ .TickNode = .{ .data = @frame() } }, }, }; suspend { self.posixFsRequest(&req_node); } return req_node.data.msg.faccessat.result; } fn workerRun(self: *Loop) void { while (true) { while (true) { const next_tick_node = self.next_tick_queue.get() orelse break; self.dispatch(); resume next_tick_node.data; self.finishOneEvent(); } switch (builtin.os.tag) { .linux => { // only process 1 event so we don't steal from other threads var events: [1]os.linux.epoll_event = undefined; const count = os.epoll_wait(self.os_data.epollfd, events[0..], -1); for (events[0..count]) |ev| { const resume_node = @as(*ResumeNode, @ptrFromInt(ev.data.ptr)); const handle = resume_node.handle; const resume_node_id = resume_node.id; switch (resume_node_id) { .Basic => {}, .Stop => return, .EventFd => { const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node); event_fd_node.epoll_op = os.linux.EPOLL.CTL_MOD; const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node); self.available_eventfd_resume_nodes.push(stack_node); }, } resume handle; if (resume_node_id == ResumeNode.Id.EventFd) { self.finishOneEvent(); } } }, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => { var eventlist: [1]os.Kevent = undefined; const empty_kevs = &[0]os.Kevent{}; const count = os.kevent(self.os_data.kqfd, empty_kevs, eventlist[0..], null) catch unreachable; for (eventlist[0..count]) |ev| { const resume_node = @as(*ResumeNode, @ptrFromInt(ev.udata)); const handle = resume_node.handle; const resume_node_id = resume_node.id; switch (resume_node_id) { .Basic => { const basic_node = @fieldParentPtr(ResumeNode.Basic, "base", resume_node); basic_node.kev = ev; }, .Stop => return, .EventFd => { const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node); const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node); self.available_eventfd_resume_nodes.push(stack_node); }, } resume handle; if (resume_node_id == ResumeNode.Id.EventFd) { self.finishOneEvent(); } } }, .windows => { var completion_key: usize = undefined; const overlapped = while (true) { var nbytes: windows.DWORD = undefined; var overlapped: ?*windows.OVERLAPPED = undefined; switch (windows.GetQueuedCompletionStatus(self.os_data.io_port, &nbytes, &completion_key, &overlapped, windows.INFINITE)) { .Aborted => return, .Normal => {}, .EOF => {}, .Cancelled => continue, } if (overlapped) |o| break o; } else unreachable; // TODO else unreachable should not be necessary const resume_node = @fieldParentPtr(ResumeNode, "overlapped", overlapped); const handle = resume_node.handle; const resume_node_id = resume_node.id; switch (resume_node_id) { .Basic => {}, .Stop => return, .EventFd => { const event_fd_node = @fieldParentPtr(ResumeNode.EventFd, "base", resume_node); const stack_node = @fieldParentPtr(std.atomic.Stack(ResumeNode.EventFd).Node, "data", event_fd_node); self.available_eventfd_resume_nodes.push(stack_node); }, } resume handle; self.finishOneEvent(); }, else => @compileError("unsupported OS"), } } } fn posixFsRequest(self: *Loop, request_node: *Request.Node) void { self.beginOneEvent(); // finished in posixFsRun after processing the msg self.fs_queue.put(request_node); self.fs_thread_wakeup.set(); } fn posixFsCancel(self: *Loop, request_node: *Request.Node) void { if (self.fs_queue.remove(request_node)) { self.finishOneEvent(); } } fn posixFsRun(self: *Loop) void { nosuspend while (true) { self.fs_thread_wakeup.reset(); while (self.fs_queue.get()) |node| { switch (node.data.msg) { .end => return, .read => |*msg| { msg.result = os.read(msg.fd, msg.buf); }, .readv => |*msg| { msg.result = os.readv(msg.fd, msg.iov); }, .write => |*msg| { msg.result = os.write(msg.fd, msg.bytes); }, .writev => |*msg| { msg.result = os.writev(msg.fd, msg.iov); }, .pwrite => |*msg| { msg.result = os.pwrite(msg.fd, msg.bytes, msg.offset); }, .pwritev => |*msg| { msg.result = os.pwritev(msg.fd, msg.iov, msg.offset); }, .pread => |*msg| { msg.result = os.pread(msg.fd, msg.buf, msg.offset); }, .preadv => |*msg| { msg.result = os.preadv(msg.fd, msg.iov, msg.offset); }, .open => |*msg| { if (is_windows) unreachable; // TODO msg.result = os.openZ(msg.path, msg.flags, msg.mode); }, .openat => |*msg| { if (is_windows) unreachable; // TODO msg.result = os.openatZ(msg.fd, msg.path, msg.flags, msg.mode); }, .faccessat => |*msg| { msg.result = os.faccessatZ(msg.dirfd, msg.path, msg.mode, msg.flags); }, .close => |*msg| os.close(msg.fd), } switch (node.data.finish) { .TickNode => |*tick_node| self.onNextTick(tick_node), .NoAction => {}, } self.finishOneEvent(); } self.fs_thread_wakeup.wait(); }; } const OsData = switch (builtin.os.tag) { .linux => LinuxOsData, .macos, .freebsd, .netbsd, .dragonfly, .openbsd => KEventData, .windows => struct { io_port: windows.HANDLE, extra_thread_count: usize, }, else => struct {}, }; const KEventData = struct { kqfd: i32, final_kevent: os.Kevent, }; const LinuxOsData = struct { epollfd: i32, final_eventfd: i32, final_eventfd_event: os.linux.epoll_event, }; pub const Request = struct { msg: Msg, finish: Finish, pub const Node = std.atomic.Queue(Request).Node; pub const Finish = union(enum) { TickNode: Loop.NextTickNode, NoAction, }; pub const Msg = union(enum) { read: Read, readv: ReadV, write: Write, writev: WriteV, pwrite: PWrite, pwritev: PWriteV, pread: PRead, preadv: PReadV, open: Open, openat: OpenAt, close: Close, faccessat: FAccessAt, /// special - means the fs thread should exit end, pub const Read = struct { fd: os.fd_t, buf: []u8, result: Error!usize, pub const Error = os.ReadError; }; pub const ReadV = struct { fd: os.fd_t, iov: []const os.iovec, result: Error!usize, pub const Error = os.ReadError; }; pub const Write = struct { fd: os.fd_t, bytes: []const u8, result: Error!usize, pub const Error = os.WriteError; }; pub const WriteV = struct { fd: os.fd_t, iov: []const os.iovec_const, result: Error!usize, pub const Error = os.WriteError; }; pub const PWrite = struct { fd: os.fd_t, bytes: []const u8, offset: usize, result: Error!usize, pub const Error = os.PWriteError; }; pub const PWriteV = struct { fd: os.fd_t, iov: []const os.iovec_const, offset: usize, result: Error!usize, pub const Error = os.PWriteError; }; pub const PRead = struct { fd: os.fd_t, buf: []u8, offset: usize, result: Error!usize, pub const Error = os.PReadError; }; pub const PReadV = struct { fd: os.fd_t, iov: []const os.iovec, offset: usize, result: Error!usize, pub const Error = os.PReadError; }; pub const Open = struct { path: [*:0]const u8, flags: u32, mode: os.mode_t, result: Error!os.fd_t, pub const Error = os.OpenError; }; pub const OpenAt = struct { fd: os.fd_t, path: [*:0]const u8, flags: u32, mode: os.mode_t, result: Error!os.fd_t, pub const Error = os.OpenError; }; pub const Close = struct { fd: os.fd_t, }; pub const FAccessAt = struct { dirfd: os.fd_t, path: [*:0]const u8, mode: u32, flags: u32, result: Error!void, pub const Error = os.AccessError; }; }; }; }; test "std.event.Loop - basic" { // https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; if (true) { // https://github.com/ziglang/zig/issues/4922 return error.SkipZigTest; } var loop: Loop = undefined; try loop.initMultiThreaded(); defer loop.deinit(); loop.run(); } fn testEventLoop() i32 { return 1234; } fn testEventLoop2(h: anyframe->i32, did_it: *bool) void { const value = await h; try testing.expect(value == 1234); did_it.* = true; } var testRunDetachedData: usize = 0; test "std.event.Loop - runDetached" { // https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; if (!std.io.is_async) return error.SkipZigTest; if (true) { // https://github.com/ziglang/zig/issues/4922 return error.SkipZigTest; } var loop: Loop = undefined; try loop.initMultiThreaded(); defer loop.deinit(); // Schedule the execution, won't actually start until we start the // event loop. try loop.runDetached(std.testing.allocator, testRunDetached, .{}); // Now we can start the event loop. The function will return only // after all tasks have been completed, allowing us to synchonize // with the previous runDetached. loop.run(); try testing.expect(testRunDetachedData == 1); } fn testRunDetached() void { testRunDetachedData += 1; } test "std.event.Loop - sleep" { // https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; if (!std.io.is_async) return error.SkipZigTest; const frames = try testing.allocator.alloc(@Frame(testSleep), 10); defer testing.allocator.free(frames); const wait_time = 100 * std.time.ns_per_ms; var sleep_count: usize = 0; for (frames) |*frame| frame.* = async testSleep(wait_time, &sleep_count); for (frames) |*frame| await frame; try testing.expect(sleep_count == frames.len); } fn testSleep(wait_ns: u64, sleep_count: *usize) void { Loop.instance.?.sleep(wait_ns); _ = @atomicRmw(usize, sleep_count, .Add, 1, .SeqCst); }
https://raw.githubusercontent.com/ziglang/gotta-go-fast/c915c45c5afed9a2e2de4f4484acba2df5090c3a/src/self-hosted-parser/input_dir/event/loop.zig
const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); var list = std.TailQueue(u8){}; defer while (list.pop()) |item| { allocator.destroy(item); }; const node1 = try allocator.create(std.TailQueue(u8).Node); errdefer allocator.destroy(node1); node1.data = 1; list.append(node1); const node2 = try allocator.create(std.TailQueue(u8).Node); errdefer allocator.destroy(node2); node2.data = 2; list.append(node2); std.debug.print("len: {d}\n", .{list.len}); var it = list.first; while (it) |item| : (it = item.next) { std.debug.print("item: {}\n", .{it.?.data}); } }
https://raw.githubusercontent.com/zsytssk/zig-learn/e23ea099d24ada2776c7872e36e42eebc064d3c7/temp/tailQueue.zig
const std = @import("std"); const srcRoot = struct { fn getSrcDir() []const u8 { return std.fs.path.dirname(@src().file).?; } }.getSrcDir(); pub fn addIup(b: *std.Build, target: std.zig.CrossTarget, optimize: std.builtin.Mode) *std.Build.Step.Compile { const manifest_32 = srcRoot ++ "/iup.manifest.obj"; const manifest_64 = srcRoot ++ "/iup64.manifest.obj"; const srcdir = srcRoot ++ "/src/"; var srcCore = [_][]const u8{ srcdir ++ "/iup_animatedlabel.c", srcdir ++ "/iup_array.c", srcdir ++ "/iup_assert.c", srcdir ++ "/iup_attrib.c", srcdir ++ "/iup_backgroundbox.c", srcdir ++ "/iup_box.c", srcdir ++ "/iup_button.c", srcdir ++ "/iup.c", srcdir ++ "/iup_callback.c", srcdir ++ "/iup_cbox.c", srcdir ++ "/iup_childtree.c", srcdir ++ "/iup_classattrib.c", srcdir ++ "/iup_classbase.c", srcdir ++ "/iup_class.c", srcdir ++ "/iup_classinfo.c", srcdir ++ "/iup_config.c", srcdir ++ "/iup_detachbox.c", srcdir ++ "/iup_dialog.c", srcdir ++ "/iup_dlglist.c", srcdir ++ "/iup_draw.c", srcdir ++ "/iup_dropbutton.c", srcdir ++ "/iup_elempropdlg.c", srcdir ++ "/iup_expander.c", srcdir ++ "/iup_export.c", srcdir ++ "/iup_filedlg.c", srcdir ++ "/iup_fill.c", srcdir ++ "/iup_flatbutton.c", srcdir ++ "/iup_flatframe.c", srcdir ++ "/iup_flatlabel.c", srcdir ++ "/iup_flatlist.c", srcdir ++ "/iup_flatscrollbar.c", srcdir ++ "/iup_flatscrollbox.c", srcdir ++ "/iup_flatseparator.c", srcdir ++ "/iup_flattabs.c", srcdir ++ "/iup_flattoggle.c", srcdir ++ "/iup_flattree.c", srcdir ++ "/iup_flatval.c", srcdir ++ "/iup_focus.c", srcdir ++ "/iup_font.c", srcdir ++ "/iup_fontdlg.c", srcdir ++ "/iup_frame.c", srcdir ++ "/iup_func.c", srcdir ++ "/iup_gauge.c", srcdir ++ "/iup_getparam.c", srcdir ++ "/iup_globalattrib.c", srcdir ++ "/iup_globalsdlg.c", srcdir ++ "/iup_gridbox.c", srcdir ++ "/iup_hbox.c", srcdir ++ "/iup_image.c", srcdir ++ "/iup_key.c", srcdir ++ "/iup_label.c", srcdir ++ "/iup_layout.c", srcdir ++ "/iup_layoutdlg.c", srcdir ++ "/iup_ledlex.c", srcdir ++ "/iup_ledparse.c", srcdir ++ "/iup_linefile.c", srcdir ++ "/iup_link.c", srcdir ++ "/iup_list.c", srcdir ++ "/iup_loop.c", srcdir ++ "/iup_mask.c", srcdir ++ "/iup_maskmatch.c", srcdir ++ "/iup_maskparse.c", srcdir ++ "/iup_menu.c", srcdir ++ "/iup_messagedlg.c", srcdir ++ "/iup_multibox.c", srcdir ++ "/iup_names.c", srcdir ++ "/iup_normalizer.c", srcdir ++ "/iup_object.c", srcdir ++ "/iup_open.c", srcdir ++ "/iup_predialogs.c", srcdir ++ "/iup_progressbar.c", srcdir ++ "/iup_progressdlg.c", srcdir ++ "/iup_radio.c", srcdir ++ "/iup_recplay.c", srcdir ++ "/iup_register.c", srcdir ++ "/iup_sbox.c", srcdir ++ "/iup_scanf.c", srcdir ++ "/iup_scrollbox.c", srcdir ++ "/iup_show.c", srcdir ++ "/iup_space.c", srcdir ++ "/iup_split.c", srcdir ++ "/iup_str.c", srcdir ++ "/iup_strmessage.c", srcdir ++ "/iup_table.c", srcdir ++ "/iup_tabs.c", srcdir ++ "/iup_text.c", srcdir ++ "/iup_thread.c", srcdir ++ "/iup_timer.c", srcdir ++ "/iup_toggle.c", srcdir ++ "/iup_user.c", srcdir ++ "/iup_val.c", srcdir ++ "/iup_vbox.c", srcdir ++ "/iup_zbox.c", srcdir ++ "/iup_canvas.c", srcdir ++ "/iup_colorbar.c", srcdir ++ "/iup_colorbrowser.c", srcdir ++ "/iup_colordlg.c", srcdir ++ "/iup_colorhsi.c", srcdir ++ "/iup_datepick.c", srcdir ++ "/iup_dial.c", srcdir ++ "/iup_spin.c", srcdir ++ "/iup_tree.c", }; var srcGtk = [_][]const u8{ srcdir ++ "/gtk/iupgtk_button.c", srcdir ++ "/gtk/iupgtk_calendar.c", srcdir ++ "/gtk/iupgtk_canvas.c", srcdir ++ "/gtk/iupgtk_clipboard.c", srcdir ++ "/gtk/iupgtk_common.c", srcdir ++ "/gtk/iupgtk_dialog.c", srcdir ++ "/gtk/iupgtk_dragdrop.c", srcdir ++ "/gtk/iupgtk_draw_cairo.c", srcdir ++ "/gtk/iupgtk_filedlg.c", srcdir ++ "/gtk/iupgtk_focus.c", srcdir ++ "/gtk/iupgtk_font.c", srcdir ++ "/gtk/iupgtk_fontdlg.c", srcdir ++ "/gtk/iupgtk_frame.c", srcdir ++ "/gtk/iupgtk_globalattrib.c", srcdir ++ "/gtk/iupgtk_help.c", srcdir ++ "/gtk/iupgtk_image.c", srcdir ++ "/gtk/iupgtk_info.c", srcdir ++ "/gtk/iupgtk_image.c", srcdir ++ "/gtk/iupgtk_info.c", srcdir ++ "/gtk/iupgtk_key.c", srcdir ++ "/gtk/iupgtk_label.c", srcdir ++ "/gtk/iupgtk_list.c", srcdir ++ "/gtk/iupgtk_loop.c", srcdir ++ "/gtk/iupgtk_menu.c", srcdir ++ "/gtk/iupgtk_messagedlg.c", srcdir ++ "/gtk/iupgtk_open.c", srcdir ++ "/gtk/iupgtk_progressbar.c", srcdir ++ "/gtk/iupgtk_str.c", srcdir ++ "/gtk/iupgtk_tabs.c", srcdir ++ "/gtk/iupgtk_text.c", srcdir ++ "/gtk/iupgtk_timer.c", srcdir ++ "/gtk/iupgtk_tips.c", srcdir ++ "/gtk/iupgtk_toggle.c", srcdir ++ "/gtk/iupgtk_val.c", srcdir ++ "/gtk/iupgtk_tree.c", srcdir ++ "/mot/iupunix_info.c", srcRoot ++ "/srcgl/iup_glcanvas_x.c", }; var srcWin = [_][]const u8{ srcdir ++ "/win/iupwindows_help.c", srcdir ++ "/win/iupwindows_info.c", srcdir ++ "/win/iupwindows_main.c", srcdir ++ "/win/iupwin_brush.c", srcdir ++ "/win/iupwin_button.c", srcdir ++ "/win/iupwin_calendar.c", srcdir ++ "/win/iupwin_canvas.c", srcdir ++ "/win/iupwin_clipboard.c", srcdir ++ "/win/iupwin_common.c", srcdir ++ "/win/iupwin_datepick.c", srcdir ++ "/win/iupwin_dialog.c", srcdir ++ "/win/iupwin_dragdrop.c", srcdir ++ "/win/iupwin_draw.c", srcdir ++ "/win/iupwin_draw_gdi.c", srcdir ++ "/win/iupwin_draw_wdl.c", srcdir ++ "/win/iupwin_filedlg.c", srcdir ++ "/win/iupwin_focus.c", srcdir ++ "/win/iupwin_font.c", srcdir ++ "/win/iupwin_fontdlg.c", srcdir ++ "/win/iupwin_frame.c", srcdir ++ "/win/iupwin_globalattrib.c", srcdir ++ "/win/iupwin_handle.c", srcdir ++ "/win/iupwin_image.c", srcdir ++ "/win/iupwin_image_wdl.c", srcdir ++ "/win/iupwin_info.c", srcdir ++ "/win/iupwin_key.c", srcdir ++ "/win/iupwin_label.c", srcdir ++ "/win/iupwin_list.c", srcdir ++ "/win/iupwin_loop.c", srcdir ++ "/win/iupwin_menu.c", srcdir ++ "/win/iupwin_messagedlg.c", srcdir ++ "/win/iupwin_open.c", srcdir ++ "/win/iupwin_progressbar.c", srcdir ++ "/win/iupwin_str.c", srcdir ++ "/win/iupwin_tabs.c", srcdir ++ "/win/iupwin_text.c", srcdir ++ "/win/iupwin_timer.c", srcdir ++ "/win/iupwin_tips.c", srcdir ++ "/win/iupwin_toggle.c", srcdir ++ "/win/iupwin_touch.c", srcdir ++ "/win/iupwin_tree.c", srcdir ++ "/win/iupwin_val.c", srcdir ++ "/win/wdl/backend-d2d.c", srcdir ++ "/win/wdl/backend-dwrite.c", srcdir ++ "/win/wdl/backend-gdix.c", srcdir ++ "/win/wdl/backend-wic.c", srcdir ++ "/win/wdl/bitblt.c", srcdir ++ "/win/wdl/brush.c", srcdir ++ "/win/wdl/cachedimage.c", srcdir ++ "/win/wdl/canvas.c", srcdir ++ "/win/wdl/draw.c", srcdir ++ "/win/wdl/fill.c", srcdir ++ "/win/wdl/font.c", srcdir ++ "/win/wdl/image.c", srcdir ++ "/win/wdl/init.c", srcdir ++ "/win/wdl/memstream.c", srcdir ++ "/win/wdl/misc.c", srcdir ++ "/win/wdl/path.c", srcdir ++ "/win/wdl/string.c", srcdir ++ "/win/wdl/strokestyle.c", }; var gtkSysLibs = [_][]const u8{ "gtk+-3.0", "gdk-3.0", "m", "X11" }; var gtkSysIncludes = [_][]const u8{ "gtk+3.0", "gdk-3.0" }; var gtkIncludePath = [_][]const u8{ srcdir, srcRoot ++ "/include", srcRoot ++ "/srcgl", srcdir ++ "/gtk", srcdir ++ "/mot" }; var winIncludePath = [_][]const u8{ srcdir, srcRoot ++ "/include", srcRoot ++ "/srcgl", srcdir ++ "/win", srcdir ++ "/win/wdl" }; var winSysLibs = [_][]const u8{ "gdi32", "comdlg32", "comctl32", "uuid", "oleaut32", "ole32", }; const lib = b.addStaticLibrary(.{ .name = "iup", .target = target, .optimize = optimize }); const includeManifest: bool = false; lib.addCSourceFiles(&srcCore, &.{}); if (target.isLinux()) { lib.addCSourceFiles(&srcGtk, &.{}); for (gtkSysLibs) |value| { lib.linkSystemLibrary(value); } for (gtkSysIncludes) |value| { lib.addSystemIncludePath(value); } for (gtkIncludePath) |value| { lib.addIncludePath(value); } } else if (target.isWindows()) { lib.addCSourceFiles(&srcWin, &.{}); if (includeManifest) { if (target.getCpuArch().isX86()) { lib.addObjectFile(manifest_32); } else { lib.addObjectFile(manifest_64); } } for (winSysLibs) |value| { lib.linkSystemLibrary(value); } for (winIncludePath) |value| { lib.addIncludePath(value); } lib.defineCMacro("USE_NEW_DRAW", ""); lib.defineCMacro("_WIN32_WINNT", "0x0601"); lib.defineCMacro("WINVER", "0x0601"); lib.defineCMacro("COBJMACROS", ""); lib.defineCMacro("NOTREEVIEW", ""); lib.defineCMacro("UNICODE", ""); lib.defineCMacro("_UNICODE", ""); } lib.linkLibC(); return lib; }
https://raw.githubusercontent.com/bauripalash/cpank/ca86a38b72d0ed9e6653bd1c83291ecc207d2e4a/cpank/ext/iup/build.zig
const micro = @import("microzig"); const mmio = micro.mmio; pub const devices = struct { pub const ATmega32U2 = struct { pub const properties = struct { pub const family = "megaAVR"; pub const arch = "AVR8"; }; pub const VectorTable = extern struct { const Handler = micro.interrupt.Handler; const unhandled = micro.interrupt.unhandled; RESET: Handler = unhandled, /// External Interrupt Request 0 INT0: Handler = unhandled, /// External Interrupt Request 1 INT1: Handler = unhandled, /// External Interrupt Request 2 INT2: Handler = unhandled, /// External Interrupt Request 3 INT3: Handler = unhandled, /// External Interrupt Request 4 INT4: Handler = unhandled, /// External Interrupt Request 5 INT5: Handler = unhandled, /// External Interrupt Request 6 INT6: Handler = unhandled, /// External Interrupt Request 7 INT7: Handler = unhandled, /// Pin Change Interrupt Request 0 PCINT0: Handler = unhandled, /// Pin Change Interrupt Request 1 PCINT1: Handler = unhandled, /// USB General Interrupt Request USB_GEN: Handler = unhandled, /// USB Endpoint/Pipe Interrupt Communication Request USB_COM: Handler = unhandled, /// Watchdog Time-out Interrupt WDT: Handler = unhandled, /// Timer/Counter2 Capture Event TIMER1_CAPT: Handler = unhandled, /// Timer/Counter2 Compare Match B TIMER1_COMPA: Handler = unhandled, /// Timer/Counter2 Compare Match B TIMER1_COMPB: Handler = unhandled, /// Timer/Counter2 Compare Match C TIMER1_COMPC: Handler = unhandled, /// Timer/Counter1 Overflow TIMER1_OVF: Handler = unhandled, /// Timer/Counter0 Compare Match A TIMER0_COMPA: Handler = unhandled, /// Timer/Counter0 Compare Match B TIMER0_COMPB: Handler = unhandled, /// Timer/Counter0 Overflow TIMER0_OVF: Handler = unhandled, /// SPI Serial Transfer Complete SPI_STC: Handler = unhandled, /// USART1, Rx Complete USART1_RX: Handler = unhandled, /// USART1 Data register Empty USART1_UDRE: Handler = unhandled, /// USART1, Tx Complete USART1_TX: Handler = unhandled, /// Analog Comparator ANALOG_COMP: Handler = unhandled, /// EEPROM Ready EE_READY: Handler = unhandled, /// Store Program Memory Read SPM_READY: Handler = unhandled, }; pub const peripherals = struct { /// Fuses pub const FUSE = @as(*volatile types.peripherals.FUSE, @ptrFromInt(0x0)); /// Lockbits pub const LOCKBIT = @as(*volatile types.peripherals.LOCKBIT, @ptrFromInt(0x0)); /// I/O Port pub const PORTB = @as(*volatile types.peripherals.PORT.PORTB, @ptrFromInt(0x23)); /// I/O Port pub const PORTC = @as(*volatile types.peripherals.PORT.PORTC, @ptrFromInt(0x26)); /// I/O Port pub const PORTD = @as(*volatile types.peripherals.PORT.PORTD, @ptrFromInt(0x29)); /// Timer/Counter, 8-bit pub const TC0 = @as(*volatile types.peripherals.TC8.TC0, @ptrFromInt(0x35)); /// Timer/Counter, 16-bit pub const TC1 = @as(*volatile types.peripherals.TC16.TC1, @ptrFromInt(0x36)); /// External Interrupts pub const EXINT = @as(*volatile types.peripherals.EXINT, @ptrFromInt(0x3b)); /// CPU Registers pub const CPU = @as(*volatile types.peripherals.CPU, @ptrFromInt(0x3e)); /// EEPROM pub const EEPROM = @as(*volatile types.peripherals.EEPROM, @ptrFromInt(0x3f)); /// Phase Locked Loop pub const PLL = @as(*volatile types.peripherals.PLL, @ptrFromInt(0x49)); /// Serial Peripheral Interface pub const SPI = @as(*volatile types.peripherals.SPI, @ptrFromInt(0x4c)); /// Analog Comparator pub const AC = @as(*volatile types.peripherals.AC, @ptrFromInt(0x50)); /// Bootloader pub const BOOT_LOAD = @as(*volatile types.peripherals.BOOT_LOAD, @ptrFromInt(0x57)); /// Watchdog Timer pub const WDT = @as(*volatile types.peripherals.WDT, @ptrFromInt(0x60)); /// USB Device Registers pub const USB_DEVICE = @as(*volatile types.peripherals.USB_DEVICE, @ptrFromInt(0x63)); /// USART pub const USART1 = @as(*volatile types.peripherals.USART.USART1, @ptrFromInt(0xc8)); }; }; }; pub const types = struct { pub const peripherals = struct { /// Fuses pub const FUSE = extern struct { pub const ENUM_SUT_CKSEL = enum(u6) { /// Ext. Clock; Start-up time: 6 CK + 0 ms EXTCLK_6CK_0MS = 0x0, /// Ext. Clock; Start-up time: 6 CK + 4.1 ms EXTCLK_6CK_4MS1 = 0x10, /// Ext. Clock; Start-up time: 6 CK + 65 ms EXTCLK_6CK_65MS = 0x20, /// Int. RC Osc.; Start-up time: 6 CK + 0 ms INTRCOSC_6CK_0MS = 0x2, /// Int. RC Osc.; Start-up time: 6 CK + 4.1 ms INTRCOSC_6CK_4MS1 = 0x12, /// Int. RC Osc.; Start-up time: 6 CK + 65 ms INTRCOSC_6CK_65MS = 0x22, /// Ext. Low-Freq. Crystal; Start-up time: 32K CK + 0 ms; Int. Cap. EXTLOFXTAL_32KCK_0MS_INTCAP = 0x7, /// Ext. Low-Freq. Crystal; Start-up time: 32K CK + 4.1 ms; Int. Cap. EXTLOFXTAL_32KCK_4MS1_INTCAP = 0x17, /// Ext. Low-Freq. Crystal; Start-up time: 32K CK + 65 ms; Int. Cap. EXTLOFXTAL_32KCK_65MS_INTCAP = 0x27, /// Ext. Low-Freq. Crystal; Start-up time: 1K CK + 0 ms; Int. Cap. EXTLOFXTAL_1KCK_0MS_INTCAP = 0x6, /// Ext. Low-Freq. Crystal; Start-up time: 1K CK + 4.1 ms; Int. Cap. EXTLOFXTAL_1KCK_4MS1_INTCAP = 0x16, /// Ext. Low-Freq. Crystal; Start-up time: 1K CK + 65 ms; Int. Cap. EXTLOFXTAL_1KCK_65MS_INTCAP = 0x26, /// Ext. Low-Freq. Crystal; Start-up time: 32K CK + 0 ms EXTLOFXTAL_32KCK_0MS = 0x5, /// Ext. Low-Freq. Crystal; Start-up time: 32K CK + 4.1 ms EXTLOFXTAL_32KCK_4MS1 = 0x15, /// Ext. Low-Freq. Crystal; Start-up time: 32K CK + 65 ms EXTLOFXTAL_32KCK_65MS = 0x25, /// Ext. Low-Freq. Crystal; Start-up time: 1K CK + 0 ms EXTLOFXTAL_1KCK_0MS = 0x4, /// Ext. Low-Freq. Crystal; Start-up time: 1K CK + 4.1 ms EXTLOFXTAL_1KCK_4MS1 = 0x14, /// Ext. Low-Freq. Crystal; Start-up time: 1K CK + 65 ms EXTLOFXTAL_1KCK_65MS = 0x24, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 258 CK + 4.1 ms EXTXOSC_0MHZ4_0MHZ9_258CK_4MS1 = 0x8, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 258 CK + 65 ms EXTXOSC_0MHZ4_0MHZ9_258CK_65MS = 0x18, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 1K CK + 0 ms EXTXOSC_0MHZ4_0MHZ9_1KCK_0MS = 0x28, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 1K CK + 4.1 ms EXTXOSC_0MHZ4_0MHZ9_1KCK_4MS1 = 0x38, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 1K CK + 65 ms EXTXOSC_0MHZ4_0MHZ9_1KCK_65MS = 0x9, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 16K CK + 0 ms EXTXOSC_0MHZ4_0MHZ9_16KCK_0MS = 0x19, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 16K CK + 4.1 ms EXTXOSC_0MHZ4_0MHZ9_16KCK_4MS1 = 0x29, /// Ext. Crystal Osc. 0.4-0.9 MHz; Start-up time: 16K CK + 65 ms EXTXOSC_0MHZ4_0MHZ9_16KCK_65MS = 0x39, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 258 CK + 4.1 ms EXTXOSC_0MHZ9_3MHZ_258CK_4MS1 = 0xa, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 258 CK + 65 ms EXTXOSC_0MHZ9_3MHZ_258CK_65MS = 0x1a, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 1K CK + 0 ms EXTXOSC_0MHZ9_3MHZ_1KCK_0MS = 0x2a, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 1K CK + 4.1 ms EXTXOSC_0MHZ9_3MHZ_1KCK_4MS1 = 0x3a, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 1K CK + 65 ms EXTXOSC_0MHZ9_3MHZ_1KCK_65MS = 0xb, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 16K CK + 0 ms EXTXOSC_0MHZ9_3MHZ_16KCK_0MS = 0x1b, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 16K CK + 4.1 ms EXTXOSC_0MHZ9_3MHZ_16KCK_4MS1 = 0x2b, /// Ext. Crystal Osc. 0.9-3.0 MHz; Start-up time: 16K CK + 65 ms EXTXOSC_0MHZ9_3MHZ_16KCK_65MS = 0x3b, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 258 CK + 4.1 ms EXTXOSC_3MHZ_8MHZ_258CK_4MS1 = 0xc, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 258 CK + 65 ms EXTXOSC_3MHZ_8MHZ_258CK_65MS = 0x1c, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 1K CK + 0 ms EXTXOSC_3MHZ_8MHZ_1KCK_0MS = 0x2c, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 1K CK + 4.1 ms EXTXOSC_3MHZ_8MHZ_1KCK_4MS1 = 0x3c, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 1K CK + 65 ms EXTXOSC_3MHZ_8MHZ_1KCK_65MS = 0xd, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 16K CK + 0 ms EXTXOSC_3MHZ_8MHZ_16KCK_0MS = 0x1d, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 16K CK + 4.1 ms EXTXOSC_3MHZ_8MHZ_16KCK_4MS1 = 0x2d, /// Ext. Crystal Osc. 3.0-8.0 MHz; Start-up time: 16K CK + 65 ms EXTXOSC_3MHZ_8MHZ_16KCK_65MS = 0x3d, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 258 CK + 4.1 ms EXTXOSC_8MHZ_XX_258CK_4MS1 = 0xe, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 258 CK + 65 ms EXTXOSC_8MHZ_XX_258CK_65MS = 0x1e, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 1K CK + 0 ms EXTXOSC_8MHZ_XX_1KCK_0MS = 0x2e, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 1K CK + 4.1 ms EXTXOSC_8MHZ_XX_1KCK_4MS1 = 0x3e, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 1K CK + 65 ms EXTXOSC_8MHZ_XX_1KCK_65MS = 0xf, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 16K CK + 0 ms EXTXOSC_8MHZ_XX_16KCK_0MS = 0x1f, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 16K CK + 4.1 ms EXTXOSC_8MHZ_XX_16KCK_4MS1 = 0x2f, /// Ext. Crystal Osc. 8.0- MHz; Start-up time: 16K CK + 65 ms EXTXOSC_8MHZ_XX_16KCK_65MS = 0x3f, _, }; pub const ENUM_BOOTSZ = enum(u2) { /// Boot Flash size=256 words start address=$3F00 @"256W_3F00" = 0x3, /// Boot Flash size=512 words start address=$3E00 @"512W_3E00" = 0x2, /// Boot Flash size=1024 words start address=$3C00 @"1024W_3C00" = 0x1, /// Boot Flash size=2048 words start address=$3800 @"2048W_3800" = 0x0, }; pub const ENUM_BODLEVEL = enum(u3) { /// Brown-out detection disabled DISABLED = 0x7, /// Brown-out detection level at VCC=2.7 V @"2V7" = 0x6, /// Brown-out detection level at VCC=2.9 V @"2V9" = 0x5, /// Brown-out detection level at VCC=3.0 V @"3V0" = 0x4, /// Brown-out detection level at VCC=3.5 V @"3V5" = 0x3, /// Brown-out detection level at VCC=3.6 V @"3V6" = 0x2, /// Brown-out detection level at VCC=4.0 V @"4V0" = 0x1, /// Brown-out detection level at VCC=4.3 V @"4V3" = 0x0, }; LOW: mmio.Mmio(packed struct(u8) { /// Select Clock Source SUT_CKSEL: packed union { raw: u6, value: ENUM_SUT_CKSEL, }, /// Clock output on PORTC7 CKOUT: u1, /// Divide clock by 8 internally CKDIV8: u1, }), HIGH: mmio.Mmio(packed struct(u8) { /// Boot Reset vector Enabled BOOTRST: u1, /// Select Boot Size BOOTSZ: packed union { raw: u2, value: ENUM_BOOTSZ, }, /// Preserve EEPROM through the Chip Erase cycle EESAVE: u1, /// Watchdog timer always on WDTON: u1, /// Serial program downloading (SPI) enabled SPIEN: u1, /// Reset Disabled (Enable PC6 as i/o pin) RSTDISBL: u1, /// Debug Wire enable DWEN: u1, }), EXTENDED: mmio.Mmio(packed struct(u8) { /// Brown-out Detector trigger level BODLEVEL: packed union { raw: u3, value: ENUM_BODLEVEL, }, /// Hardware Boot Enable HWBE: u1, padding: u4, }), }; /// Lockbits pub const LOCKBIT = extern struct { pub const ENUM_LB = enum(u2) { /// Further programming and verification disabled PROG_VER_DISABLED = 0x0, /// Further programming disabled PROG_DISABLED = 0x2, /// No memory lock features enabled NO_LOCK = 0x3, _, }; pub const ENUM_BLB = enum(u2) { /// LPM and SPM prohibited in Application Section LPM_SPM_DISABLE = 0x0, /// LPM prohibited in Application Section LPM_DISABLE = 0x1, /// SPM prohibited in Application Section SPM_DISABLE = 0x2, /// No lock on SPM and LPM in Application Section NO_LOCK = 0x3, }; pub const ENUM_BLB2 = enum(u2) { /// LPM and SPM prohibited in Boot Section LPM_SPM_DISABLE = 0x0, /// LPM prohibited in Boot Section LPM_DISABLE = 0x1, /// SPM prohibited in Boot Section SPM_DISABLE = 0x2, /// No lock on SPM and LPM in Boot Section NO_LOCK = 0x3, }; LOCKBIT: mmio.Mmio(packed struct(u8) { /// Memory Lock LB: packed union { raw: u2, value: ENUM_LB, }, /// Boot Loader Protection Mode BLB0: packed union { raw: u2, value: ENUM_BLB, }, /// Boot Loader Protection Mode BLB1: packed union { raw: u2, value: ENUM_BLB2, }, padding: u2, }), }; /// I/O Port pub const PORT = struct { /// I/O Port pub const PORTB = extern struct { /// Port B Input Pins PINB: u8, /// Port B Data Direction Register DDRB: u8, /// Port B Data Register PORTB: u8, }; /// I/O Port pub const PORTD = extern struct { /// Port D Input Pins PIND: u8, /// Port D Data Direction Register DDRD: u8, /// Port D Data Register PORTD: u8, }; /// I/O Port pub const PORTC = extern struct { /// Port C Input Pins PINC: mmio.Mmio(packed struct(u8) { /// Port C Input Pins bits PINC: u3, reserved4: u1, /// Port C Input Pins bits PINC: u4, }), /// Port C Data Direction Register DDRC: mmio.Mmio(packed struct(u8) { /// Port C Data Direction Register bits DDC: u3, reserved4: u1, /// Port C Data Direction Register bits DDC: u4, }), /// Port C Data Register PORTC: mmio.Mmio(packed struct(u8) { /// Port C Data Register bits PORTC: u3, reserved4: u1, /// Port C Data Register bits PORTC: u4, }), }; }; /// Bootloader pub const BOOT_LOAD = extern struct { /// Store Program Memory Control Register SPMCSR: mmio.Mmio(packed struct(u8) { /// Store Program Memory Enable SPMEN: u1, /// Page Erase PGERS: u1, /// Page Write PGWRT: u1, /// Boot Lock Bit Set BLBSET: u1, /// Read While Write section read enable RWWSRE: u1, /// Signature Row Read SIGRD: u1, /// Read While Write Section Busy RWWSB: u1, /// SPM Interrupt Enable SPMIE: u1, }), }; /// EEPROM pub const EEPROM = extern struct { pub const EEP_MODE = enum(u2) { /// Erase and Write in one operation ERASE_AND_WRITE_IN_ONE_OPERATION = 0x0, /// Erase Only ERASE_ONLY = 0x1, /// Write Only WRITE_ONLY = 0x2, _, }; /// EEPROM Control Register EECR: mmio.Mmio(packed struct(u8) { /// EEPROM Read Enable EERE: u1, /// EEPROM Write Enable EEPE: u1, /// EEPROM Master Write Enable EEMPE: u1, /// EEPROM Ready Interrupt Enable EERIE: u1, /// EEPROM Programming Mode Bits EEPM: packed union { raw: u2, value: EEP_MODE, }, padding: u2, }), /// EEPROM Data Register EEDR: u8, /// EEPROM Address Register Low Bytes EEAR: u16, }; /// Timer/Counter, 8-bit pub const TC8 = struct { pub const CLK_SEL_3BIT_EXT = enum(u3) { /// No Clock Source (Stopped) NO_CLOCK_SOURCE_STOPPED = 0x0, /// Running, No Prescaling RUNNING_NO_PRESCALING = 0x1, /// Running, CLK/8 RUNNING_CLK_8 = 0x2, /// Running, CLK/64 RUNNING_CLK_64 = 0x3, /// Running, CLK/256 RUNNING_CLK_256 = 0x4, /// Running, CLK/1024 RUNNING_CLK_1024 = 0x5, /// Running, ExtClk Tn Falling Edge RUNNING_EXTCLK_TN_FALLING_EDGE = 0x6, /// Running, ExtClk Tn Rising Edge RUNNING_EXTCLK_TN_RISING_EDGE = 0x7, }; /// Timer/Counter, 8-bit pub const TC0 = extern struct { /// Timer/Counter0 Interrupt Flag register TIFR0: mmio.Mmio(packed struct(u8) { /// Timer/Counter0 Overflow Flag TOV0: u1, /// Timer/Counter0 Output Compare Flag 0A OCF0A: u1, /// Timer/Counter0 Output Compare Flag 0B OCF0B: u1, padding: u5, }), reserved14: [13]u8, /// General Timer/Counter Control Register GTCCR: mmio.Mmio(packed struct(u8) { /// Prescaler Reset Timer/Counter1 and Timer/Counter0 PSRSYNC: u1, reserved7: u6, /// Timer/Counter Synchronization Mode TSM: u1, }), /// Timer/Counter Control Register A TCCR0A: mmio.Mmio(packed struct(u8) { /// Waveform Generation Mode WGM0: u2, reserved4: u2, /// Compare Output Mode, Fast PWm COM0B: u2, /// Compare Output Mode, Phase Correct PWM Mode COM0A: u2, }), /// Timer/Counter Control Register B TCCR0B: mmio.Mmio(packed struct(u8) { /// Clock Select CS0: packed union { raw: u3, value: CLK_SEL_3BIT_EXT, }, WGM02: u1, reserved6: u2, /// Force Output Compare B FOC0B: u1, /// Force Output Compare A FOC0A: u1, }), /// Timer/Counter0 TCNT0: u8, /// Timer/Counter0 Output Compare Register OCR0A: u8, /// Timer/Counter0 Output Compare Register OCR0B: u8, reserved57: [37]u8, /// Timer/Counter0 Interrupt Mask Register TIMSK0: mmio.Mmio(packed struct(u8) { /// Timer/Counter0 Overflow Interrupt Enable TOIE0: u1, /// Timer/Counter0 Output Compare Match A Interrupt Enable OCIE0A: u1, /// Timer/Counter0 Output Compare Match B Interrupt Enable OCIE0B: u1, padding: u5, }), }; }; /// Timer/Counter, 16-bit pub const TC16 = struct { pub const CLK_SEL_3BIT_EXT = enum(u3) { /// No Clock Source (Stopped) NO_CLOCK_SOURCE_STOPPED = 0x0, /// Running, No Prescaling RUNNING_NO_PRESCALING = 0x1, /// Running, CLK/8 RUNNING_CLK_8 = 0x2, /// Running, CLK/64 RUNNING_CLK_64 = 0x3, /// Running, CLK/256 RUNNING_CLK_256 = 0x4, /// Running, CLK/1024 RUNNING_CLK_1024 = 0x5, /// Running, ExtClk Tn Falling Edge RUNNING_EXTCLK_TN_FALLING_EDGE = 0x6, /// Running, ExtClk Tn Rising Edge RUNNING_EXTCLK_TN_RISING_EDGE = 0x7, }; /// Timer/Counter, 16-bit pub const TC1 = extern struct { /// Timer/Counter1 Interrupt Flag register TIFR1: mmio.Mmio(packed struct(u8) { /// Timer/Counter1 Overflow Flag TOV1: u1, /// Output Compare Flag 1A OCF1A: u1, /// Output Compare Flag 1B OCF1B: u1, /// Output Compare Flag 1C OCF1C: u1, reserved5: u1, /// Input Capture Flag 1 ICF1: u1, padding: u2, }), reserved57: [56]u8, /// Timer/Counter1 Interrupt Mask Register TIMSK1: mmio.Mmio(packed struct(u8) { /// Timer/Counter1 Overflow Interrupt Enable TOIE1: u1, /// Timer/Counter1 Output Compare A Match Interrupt Enable OCIE1A: u1, /// Timer/Counter1 Output Compare B Match Interrupt Enable OCIE1B: u1, /// Timer/Counter1 Output Compare C Match Interrupt Enable OCIE1C: u1, reserved5: u1, /// Timer/Counter1 Input Capture Interrupt Enable ICIE1: u1, padding: u2, }), reserved74: [16]u8, /// Timer/Counter1 Control Register A TCCR1A: mmio.Mmio(packed struct(u8) { /// Waveform Generation Mode WGM1: u2, /// Compare Output Mode 1C, bits COM1C: u2, /// Compare Output Mode 1B, bits COM1B: u2, /// Compare Output Mode 1A, bits COM1A: u2, }), /// Timer/Counter1 Control Register B TCCR1B: mmio.Mmio(packed struct(u8) { /// Prescaler source of Timer/Counter 1 CS1: packed union { raw: u3, value: CLK_SEL_3BIT_EXT, }, /// Waveform Generation Mode WGM1: u2, reserved6: u1, /// Input Capture 1 Edge Select ICES1: u1, /// Input Capture 1 Noise Canceler ICNC1: u1, }), /// Timer/Counter 1 Control Register C TCCR1C: mmio.Mmio(packed struct(u8) { reserved5: u5, /// Force Output Compare 1C FOC1C: u1, /// Force Output Compare 1B FOC1B: u1, /// Force Output Compare 1A FOC1A: u1, }), reserved78: [1]u8, /// Timer/Counter1 Bytes TCNT1: u16, /// Timer/Counter1 Input Capture Register Bytes ICR1: u16, /// Timer/Counter1 Output Compare Register A Bytes OCR1A: u16, /// Timer/Counter1 Output Compare Register B Bytes OCR1B: u16, /// Timer/Counter1 Output Compare Register C Bytes OCR1C: u16, }; }; /// Phase Locked Loop pub const PLL = extern struct { pub const PLL_INPUT_PRESCALER = enum(u3) { /// Clock/4 CLOCK_4 = 0x3, /// Clock/8 CLOCK_8 = 0x5, _, }; /// PLL Status and Control register PLLCSR: mmio.Mmio(packed struct(u8) { /// PLL Lock Status Bit PLOCK: u1, /// PLL Enable Bit PLLE: u1, /// PLL prescaler Bits PLLP: packed union { raw: u3, value: PLL_INPUT_PRESCALER, }, padding: u3, }), }; /// USB Device Registers pub const USB_DEVICE = extern struct { /// Regulator Control Register REGCR: mmio.Mmio(packed struct(u8) { /// Regulator Disable REGDIS: u1, padding: u7, }), reserved117: [116]u8, /// USB General Control Register USBCON: mmio.Mmio(packed struct(u8) { reserved5: u5, /// Freeze USB Clock Bit FRZCLK: u1, reserved7: u1, /// USB macro Enable Bit USBE: u1, }), reserved125: [7]u8, /// USB Device Control Registers UDCON: mmio.Mmio(packed struct(u8) { /// Detach Bit DETACH: u1, /// Remote Wake-up Bit RMWKUP: u1, /// USB Reset CPU Bit RSTCPU: u1, padding: u5, }), /// USB Device Interrupt Register UDINT: mmio.Mmio(packed struct(u8) { /// Suspend Interrupt Flag SUSPI: u1, reserved2: u1, /// Start Of Frame Interrupt Flag SOFI: u1, /// End Of Reset Interrupt Flag EORSTI: u1, /// Wake-up CPU Interrupt Flag WAKEUPI: u1, /// End Of Resume Interrupt Flag EORSMI: u1, /// Upstream Resume Interrupt Flag UPRSMI: u1, padding: u1, }), /// USB Device Interrupt Enable Register UDIEN: mmio.Mmio(packed struct(u8) { /// Suspend Interrupt Enable Bit SUSPE: u1, reserved2: u1, /// Start Of Frame Interrupt Enable Bit SOFE: u1, /// End Of Reset Interrupt Enable Bit EORSTE: u1, /// Wake-up CPU Interrupt Enable Bit WAKEUPE: u1, /// End Of Resume Interrupt Enable Bit EORSME: u1, /// Upstream Resume Interrupt Enable Bit UPRSME: u1, padding: u1, }), /// USB Device Address Register UDADDR: mmio.Mmio(packed struct(u8) { /// USB Address Bits UADD: u7, /// Address Enable Bit ADDEN: u1, }), /// USB Device Frame Number High Register UDFNUM: mmio.Mmio(packed struct(u16) { /// Frame Number Upper Flag FNUM: u11, padding: u5, }), /// USB Device Micro Frame Number UDMFN: mmio.Mmio(packed struct(u8) { reserved4: u4, /// Frame Number CRC Error Flag FNCERR: u1, padding: u3, }), reserved133: [1]u8, /// USB Endpoint Interrupt Register UEINTX: mmio.Mmio(packed struct(u8) { /// Transmitter Ready Interrupt Flag TXINI: u1, /// STALLEDI Interrupt Flag STALLEDI: u1, /// Received OUT Data Interrupt Flag RXOUTI: u1, /// Received SETUP Interrupt Flag RXSTPI: u1, /// NAK OUT Received Interrupt Flag NAKOUTI: u1, /// Read/Write Allowed Flag RWAL: u1, /// NAK IN Received Interrupt Flag NAKINI: u1, /// FIFO Control Bit FIFOCON: u1, }), /// USB Endpoint Number UENUM: mmio.Mmio(packed struct(u8) { /// Endpoint Number bits EPNUM: u3, padding: u5, }), /// USB Endpoint Reset Register UERST: mmio.Mmio(packed struct(u8) { /// Endpoint FIFO Reset Bits EPRST: u5, padding: u3, }), /// USB Endpoint Control Register UECONX: mmio.Mmio(packed struct(u8) { /// Endpoint Enable Bit EPEN: u1, reserved3: u2, /// Reset Data Toggle Bit RSTDT: u1, /// STALL Request Clear Handshake Bit STALLRQC: u1, /// STALL Request Handshake Bit STALLRQ: u1, padding: u2, }), /// USB Endpoint Configuration 0 Register UECFG0X: mmio.Mmio(packed struct(u8) { /// Endpoint Direction Bit EPDIR: u1, reserved6: u5, /// Endpoint Type Bits EPTYPE: u2, }), /// USB Endpoint Configuration 1 Register UECFG1X: mmio.Mmio(packed struct(u8) { reserved1: u1, /// Endpoint Allocation Bit ALLOC: u1, /// Endpoint Bank Bits EPBK: u2, /// Endpoint Size Bits EPSIZE: u3, padding: u1, }), /// USB Endpoint Status 0 Register UESTA0X: mmio.Mmio(packed struct(u8) { /// Busy Bank Flag NBUSYBK: u2, /// Data Toggle Sequencing Flag DTSEQ: u2, reserved5: u1, /// Underflow Error Interrupt Flag UNDERFI: u1, /// Overflow Error Interrupt Flag OVERFI: u1, /// Configuration Status Flag CFGOK: u1, }), /// USB Endpoint Status 1 Register UESTA1X: mmio.Mmio(packed struct(u8) { /// Current Bank CURRBK: u2, /// Control Direction CTRLDIR: u1, padding: u5, }), /// USB Endpoint Interrupt Enable Register UEIENX: mmio.Mmio(packed struct(u8) { /// Transmitter Ready Interrupt Enable Flag TXINE: u1, /// Stalled Interrupt Enable Flag STALLEDE: u1, /// Received OUT Data Interrupt Enable Flag RXOUTE: u1, /// Received SETUP Interrupt Enable Flag RXSTPE: u1, /// NAK OUT Interrupt Enable Bit NAKOUTE: u1, reserved6: u1, /// NAK IN Interrupt Enable Bit NAKINE: u1, /// Flow Error Interrupt Enable Flag FLERRE: u1, }), /// USB Data Endpoint UEDATX: mmio.Mmio(packed struct(u8) { /// Data bits DAT: u8, }), /// USB Endpoint Byte Count Register UEBCLX: mmio.Mmio(packed struct(u8) { /// Byte Count bits BYCT: u8, }), reserved145: [1]u8, /// USB Endpoint Number Interrupt Register UEINT: mmio.Mmio(packed struct(u8) { /// Byte Count bits EPINT: u5, padding: u3, }), reserved152: [6]u8, /// USB Software Output Enable register UPOE: mmio.Mmio(packed struct(u8) { /// D- Input value DMI: u1, /// D+ Input value DPI: u1, reserved4: u2, /// USB direct drive values UPDRV: u2, /// USB Buffers Direct Drive enable configuration UPWE: u2, }), }; /// CPU Registers pub const CPU = extern struct { /// Oscillator Calibration Values pub const OSCCAL_VALUE_ADDRESSES = enum(u1) { /// 8.0 MHz @"8_0_MHz" = 0x0, _, }; pub const CPU_SLEEP_MODE_3BITS = enum(u3) { /// Idle IDLE = 0x0, /// Reserved VAL_0x01 = 0x1, /// Power Down PDOWN = 0x2, /// Power Save PSAVE = 0x3, /// Reserved VAL_0x04 = 0x4, /// Reserved VAL_0x05 = 0x5, /// Standby STDBY = 0x6, /// Extended Standby ESTDBY = 0x7, }; /// General Purpose IO Register 0 GPIOR0: mmio.Mmio(packed struct(u8) { /// General Purpose IO Register 0 bit 0 GPIOR00: u1, /// General Purpose IO Register 0 bit 1 GPIOR01: u1, /// General Purpose IO Register 0 bit 2 GPIOR02: u1, /// General Purpose IO Register 0 bit 3 GPIOR03: u1, /// General Purpose IO Register 0 bit 4 GPIOR04: u1, /// General Purpose IO Register 0 bit 5 GPIOR05: u1, /// General Purpose IO Register 0 bit 6 GPIOR06: u1, /// General Purpose IO Register 0 bit 7 GPIOR07: u1, }), reserved12: [11]u8, /// General Purpose IO Register 1 GPIOR1: mmio.Mmio(packed struct(u8) { /// General Purpose IO Register 1 bis GPIOR: u8, }), /// General Purpose IO Register 2 GPIOR2: mmio.Mmio(packed struct(u8) { /// General Purpose IO Register 2 bis GPIOR: u8, }), reserved19: [5]u8, /// debugWire communication register DWDR: u8, reserved21: [1]u8, /// Sleep Mode Control Register SMCR: mmio.Mmio(packed struct(u8) { /// Sleep Enable SE: u1, /// Sleep Mode Select bits SM: packed union { raw: u3, value: CPU_SLEEP_MODE_3BITS, }, padding: u4, }), /// MCU Status Register MCUSR: mmio.Mmio(packed struct(u8) { /// Power-on reset flag PORF: u1, /// External Reset Flag EXTRF: u1, /// Brown-out Reset Flag BORF: u1, /// Watchdog Reset Flag WDRF: u1, reserved5: u1, /// USB reset flag USBRF: u1, padding: u2, }), /// MCU Control Register MCUCR: mmio.Mmio(packed struct(u8) { /// Interrupt Vector Change Enable IVCE: u1, /// Interrupt Vector Select IVSEL: u1, reserved4: u2, /// Pull-up disable PUD: u1, padding: u3, }), reserved30: [6]u8, /// Extended Indirect Register EIND: u8, /// Stack Pointer SP: u16, /// Status Register SREG: mmio.Mmio(packed struct(u8) { /// Carry Flag C: u1, /// Zero Flag Z: u1, /// Negative Flag N: u1, /// Two's Complement Overflow Flag V: u1, /// Sign Bit S: u1, /// Half Carry Flag H: u1, /// Bit Copy Storage T: u1, /// Global Interrupt Enable I: u1, }), reserved35: [1]u8, CLKPR: mmio.Mmio(packed struct(u8) { CLKPS: u4, reserved7: u3, CLKPCE: u1, }), reserved38: [2]u8, /// Power Reduction Register0 PRR0: mmio.Mmio(packed struct(u8) { reserved2: u2, /// Power Reduction Serial Peripheral Interface PRSPI: u1, /// Power Reduction Timer/Counter1 PRTIM1: u1, reserved5: u1, /// Power Reduction Timer/Counter0 PRTIM0: u1, padding: u2, }), /// Power Reduction Register1 PRR1: mmio.Mmio(packed struct(u8) { /// Power Reduction USART1 PRUSART1: u1, reserved7: u6, /// Power Reduction USB PRUSB: u1, }), /// Oscillator Calibration Value OSCCAL: mmio.Mmio(packed struct(u8) { /// Oscillator Calibration OSCCAL: u8, }), reserved146: [105]u8, CLKSEL0: mmio.Mmio(packed struct(u8) { CLKS: u1, reserved2: u1, EXTE: u1, RCE: u1, EXSUT: u2, RCSUT: u2, }), CLKSEL1: mmio.Mmio(packed struct(u8) { EXCKSEL: u4, RCCKSEL: u4, }), CLKSTA: mmio.Mmio(packed struct(u8) { EXTON: u1, RCON: u1, padding: u6, }), }; /// External Interrupts pub const EXINT = extern struct { /// Pin Change Interrupt Flag Register PCIFR: mmio.Mmio(packed struct(u8) { /// Pin Change Interrupt Flags PCIF: u2, padding: u6, }), /// External Interrupt Flag Register EIFR: mmio.Mmio(packed struct(u8) { /// External Interrupt Flags INTF: u8, }), /// External Interrupt Mask Register EIMSK: mmio.Mmio(packed struct(u8) { /// External Interrupt Request 7 Enable INT: u8, }), reserved45: [42]u8, /// Pin Change Interrupt Control Register PCICR: mmio.Mmio(packed struct(u8) { /// Pin Change Interrupt Enables PCIE: u2, padding: u6, }), /// External Interrupt Control Register A EICRA: mmio.Mmio(packed struct(u8) { /// External Interrupt Sense Control Bit ISC0: u2, /// External Interrupt Sense Control Bit ISC1: u2, /// External Interrupt Sense Control Bit ISC2: u2, /// External Interrupt Sense Control Bit ISC3: u2, }), /// External Interrupt Control Register B EICRB: mmio.Mmio(packed struct(u8) { /// External Interrupt 7-4 Sense Control Bit ISC4: u2, /// External Interrupt 7-4 Sense Control Bit ISC5: u2, /// External Interrupt 7-4 Sense Control Bit ISC6: u2, /// External Interrupt 7-4 Sense Control Bit ISC7: u2, }), /// Pin Change Mask Register 0 PCMSK0: mmio.Mmio(packed struct(u8) { /// Pin Change Enable Masks PCINT: u8, }), /// Pin Change Mask Register 1 PCMSK1: mmio.Mmio(packed struct(u8) { PCINT: u5, padding: u3, }), }; /// USART pub const USART = struct { /// USART pub const USART1 = extern struct { /// USART Control and Status Register A UCSR1A: mmio.Mmio(packed struct(u8) { /// Multi-processor Communication Mode MPCM1: u1, /// Double the USART transmission speed U2X1: u1, /// Parity Error UPE1: u1, /// Data overRun DOR1: u1, /// Framing Error FE1: u1, /// USART Data Register Empty UDRE1: u1, /// USART Transmitt Complete TXC1: u1, /// USART Receive Complete RXC1: u1, }), /// USART Control and Status Register B UCSR1B: mmio.Mmio(packed struct(u8) { /// Transmit Data Bit 8 TXB81: u1, /// Receive Data Bit 8 RXB81: u1, /// Character Size UCSZ12: u1, /// Transmitter Enable TXEN1: u1, /// Receiver Enable RXEN1: u1, /// USART Data register Empty Interrupt Enable UDRIE1: u1, /// TX Complete Interrupt Enable TXCIE1: u1, /// RX Complete Interrupt Enable RXCIE1: u1, }), /// USART Control and Status Register C UCSR1C: mmio.Mmio(packed struct(u8) { /// Clock Polarity UCPOL1: u1, /// Character Size UCSZ1: u2, /// Stop Bit Select USBS1: u1, /// Parity Mode Bits UPM1: u2, /// USART Mode Select UMSEL1: u2, }), /// USART Control and Status Register D UCSR1D: mmio.Mmio(packed struct(u8) { /// RTS Enable RTSEN: u1, /// CTS Enable CTSEN: u1, padding: u6, }), /// USART Baud Rate Register Bytes UBRR1: u16, /// USART I/O Data Register UDR1: u8, }; }; /// Watchdog Timer pub const WDT = extern struct { /// Watchdog Timer Control Register WDTCSR: mmio.Mmio(packed struct(u8) { /// Watchdog Timer Prescaler Bits WDP_bit0: u1, /// Watchdog Timer Prescaler Bits WDP_bit1: u1, /// Watchdog Timer Prescaler Bits WDP_bit2: u1, /// Watch Dog Enable WDE: u1, /// Watchdog Change Enable WDCE: u1, /// Watchdog Timer Prescaler Bits WDP_bit3: u1, /// Watchdog Timeout Interrupt Enable WDIE: u1, /// Watchdog Timeout Interrupt Flag WDIF: u1, }), reserved2: [1]u8, /// Watchdog Timer Clock Divider WDTCKD: mmio.Mmio(packed struct(u8) { /// Watchdog Timer Clock Dividers WCLKD: u2, /// Watchdog Early Warning Interrupt Enable WDEWIE: u1, /// Watchdog Early Warning Interrupt Flag WDEWIF: u1, padding: u4, }), }; /// Analog Comparator pub const AC = extern struct { pub const ANALOG_COMP_INTERRUPT = enum(u2) { /// Interrupt on Toggle INTERRUPT_ON_TOGGLE = 0x0, /// Reserved RESERVED = 0x1, /// Interrupt on Falling Edge INTERRUPT_ON_FALLING_EDGE = 0x2, /// Interrupt on Rising Edge INTERRUPT_ON_RISING_EDGE = 0x3, }; pub const ANALOG_COMP_SELECTION_BITS = enum(u3) { /// AIN1 AIN1 = 0x0, /// AIN2 AIN2 = 0x1, /// AIN3 AIN3 = 0x2, /// AIN4 AIN4 = 0x3, /// AIN5 AIN5 = 0x4, /// AIN6 AIN6 = 0x5, _, }; /// Analog Comparator Control And Status Register ACSR: mmio.Mmio(packed struct(u8) { /// Analog Comparator Interrupt Mode Select bits ACIS: packed union { raw: u2, value: ANALOG_COMP_INTERRUPT, }, /// Analog Comparator Input Capture Enable ACIC: u1, /// Analog Comparator Interrupt Enable ACIE: u1, /// Analog Comparator Interrupt Flag ACI: u1, /// Analog Compare Output ACO: u1, /// Analog Comparator Bandgap Select ACBG: u1, /// Analog Comparator Disable ACD: u1, }), reserved45: [44]u8, /// Analog Comparator Input Multiplexer ACMUX: mmio.Mmio(packed struct(u8) { /// Analog Comparator Selection Bits CMUX: packed union { raw: u3, value: ANALOG_COMP_SELECTION_BITS, }, padding: u5, }), reserved47: [1]u8, DIDR1: mmio.Mmio(packed struct(u8) { /// AIN0 Digital Input Disable AIN0D: u1, /// AIN1 Digital Input Disable AIN1D: u1, /// AIN2 Digital Input Disable AIN2D: u1, /// AIN3 Digital Input Disable AIN3D: u1, /// AIN4 Digital Input Disable AIN4D: u1, /// AIN5 Digital Input Disable AIN5D: u1, /// AIN6 Digital Input Disable AIN6D: u1, /// AIN7 Digital Input Disable AIN7D: u1, }), }; }; };
https://raw.githubusercontent.com/burgrp/microzig-avr/f6f7a766fac9f85d2643789b46bc882ff4ade0ed/src/chips/ATmega32U2.zig