text
stringlengths
32
314k
url
stringlengths
93
243
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 = "day01", // 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 clap = b.dependency("clap", .{}); exe.addModule("clap", clap.module("clap")); // 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, }); 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/huntears/adventOfCode2023/78f9faee45a7ee04363af510293848b3db3dc6c4/day01/build.zig
const std = @import("std"); const Str = struct { // null terminated string slice data: [:0]const u8, pub fn get(self: Str, idx: usize) ?u8 { if (self.data.len > idx) { return self.data[idx]; } else { return null; // equivalent to None } } pub fn split_at(self: Str, idx: usize) ?struct { []const u8, []const u8 } { if (self.data.len > idx) { return .{ self.data[0..idx], self.data[idx..] }; } else { return null; // equivalent to None } } }; pub fn main() !void { var src = Str{ .data = "this is a string" }; if (src.split_at(5)) |t| { var x = t[0]; var y = t[1]; std.debug.print("{s}\n{s}", .{ x, y }); } return; }
https://raw.githubusercontent.com/swarnimarun/learning-rust/ae768bfbf796b5633f9768fbec03547cbfff16ee/main.zig
const std = @import("std"); const Step = std.Build.Step; const StaticPluginStep = @This(); step: Step, output_file: std.Build.GeneratedFile, static_plugins: []const []const u8, pub const base_id: Step.Id = .custom; pub const Options = struct { static_plugins: []const []const u8 = &.{}, }; pub fn create(owner: *std.Build, options: Options) *StaticPluginStep { const self = owner.allocator.create(StaticPluginStep) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = base_id, .name = "Generate Wwise static plugin C build file", .owner = owner, .makeFn = make, .first_ret_addr = @returnAddress(), }), .static_plugins = options.static_plugins, .output_file = .{ .step = &self.step }, }; return self; } fn make(step: *Step, prog_node: *std.Progress.Node) !void { _ = prog_node; const b = step.owner; const self = @fieldParentPtr(StaticPluginStep, "step", step); const gpa = b.allocator; const arena = b.allocator; var man = b.graph.cache.obtain(); defer man.deinit(); // Random bytes to make StaticPluginStep unique. Refresh this with new // random bytes when StaticPluginStep implementation is modified in a // non-backwards-compatible way. man.hash.add(@as(u32, 0xc01db1e5)); var output = std.ArrayList(u8).init(gpa); defer output.deinit(); const file_name = "wwise_c_static_plugins.cpp"; try output.appendSlice("// This file was generated by Wwise Static Plugin Step using the Zig Build System.\n"); try output.appendSlice("#include <AK/AkPlatforms.h>\n"); try output.appendSlice("#include <AK/SoundEngine/Common/AkTypes.h>\n"); try output.appendSlice("#include <AK/SoundEngine/Common/IAkPlugin.h>\n\n"); try output.appendSlice("extern \"C\" void WWISEC_HACK_RegisterAllPlugins() {{}}\n"); const writer = output.writer(); for (self.static_plugins) |static_plugin| { try writer.print("#include <AK/Plugin/{s}Factory.h>\n", .{static_plugin}); } man.hash.addBytes(output.items); if (try step.cacheHit(&man)) { const digest = man.final(); self.output_file.path = try b.cache_root.join(arena, &.{ "o", &digest, file_name, }); return; } const digest = man.final(); const sub_path = try std.fs.path.join(arena, &.{ "o", &digest, file_name }); const sub_path_dirname = std.fs.path.dirname(sub_path).?; b.cache_root.handle.makePath(sub_path_dirname) catch |err| { return step.fail("unable to make path '{}{s}': {s}", .{ b.cache_root, sub_path_dirname, @errorName(err), }); }; b.cache_root.handle.writeFile(sub_path, output.items) catch |err| { return step.fail("unable to write file '{}{s}': {s}", .{ b.cache_root, sub_path, @errorName(err), }); }; self.output_file.path = try b.cache_root.join(arena, &.{sub_path}); try man.writeManifest(); }
https://raw.githubusercontent.com/Cold-Bytes-Games/wwise-zig/0b778cf0b8f26aa120415231052eba163a3e6785/build/StaticPluginStep.zig
const std = @import("std"); const print = std.debug.print; const Cli = @import("app.zig").Cli; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; { var arena = std.heap.ArenaAllocator.init(gpa.allocator()); defer arena.deinit(); const writer = std.io.getStdOut().writer(); const reader = std.io.getStdIn().reader(); const CliApp = Cli(@TypeOf(writer), @TypeOf(reader)); var app_cli = CliApp{ .allocator = arena.allocator(), .out = writer, .in = reader, }; try app_cli.run(); } const has_leaked = gpa.detectLeaks(); std.log.debug("Has leaked: {}\n", .{has_leaked}); } // pub fn main() !void { // try longCompileTime(); // std.debug.print("DONE\n", .{}); // } // Cause of long compile times? https://github.com/ziglang/zig/issues/15266 // fn longCompileTime() !void { // // { // // var gen = std.heap.GeneralPurposeAllocator(.{}){}; // // var arena = std.heap.ArenaAllocator.init(gen.allocator()); // // defer arena.deinit(); // // const input = "http://github.com"; // // const url = try std.Uri.parse(input); // // var client = std.http.Client{ .allocator = arena.allocator() }; // // defer client.deinit(); // // var req = try client.request(.GET, url, .{ .allocator = arena.allocator() }, .{}); // // print("host: {?s}\n", .{req.uri.host}); // // } // // When I added std.http.Client.request function my compile times increased several fold from // // ~1s to ~16s. After looking deeper found that is was caused by std.crypto.tls.Client.init // // function. My guess is that is cause by some comptime stuff, probably arrays. // { // var gen = std.heap.GeneralPurposeAllocator(.{}){}; // var arena = std.heap.ArenaAllocator.init(gen.allocator()); // defer arena.deinit(); // var client = std.http.Client{ .allocator = arena.allocator() }; // const host = "github.com"; // const port = 80; // const stream = try std.net.tcpConnectToHost(arena.allocator(), host, port); // errdefer stream.close(); // const tls_client = try std.crypto.tls.Client.init(stream, client.ca_bundle, host); // _ = tls_client; // } // // { // // const w: u32 = 1080; // // const h: u32 = 40; // // // time: 1.26 sec // // // var pixels: [w * h * 3]f32 = [1]f32{0.0} ** (w * h * 3); // // // time: 4.26 sec // // // var pixels = std.mem.zeroes([w * h * 3]f32); // // // time: 1.24 sec // // var pixels = comptime std.mem.zeroes([w * h * 3]f32); // // _ = pixels; // // // pixels[69] = 42; // // } // }
https://raw.githubusercontent.com/last-arg/feedgaze/3c66d127344a18c02d25114dbf84dafd6cd75d91/src/main.zig
const std = @import("std"); const objc = @import("objc"); const runtime_support = @import("Runtime-Support"); pub const NSDraggingSessionSelectors = struct {};
https://raw.githubusercontent.com/ritalin/zig-7gui-macos/52ee58a27d60c90f48c9dc1025392bf977d01b8b/src/fw/AppKit/NSDraggingSession/selector.zig
const std = @import("std"); const input = @embedFile("day11.input"); const size = 10; const Offset = struct { x: i64, y: i64, }; fn increase(flashed: *[size][size]bool, energy: *[size][size]u8, row_idx: i64, o_idx: i64) u64 { if (row_idx < 0 or row_idx >= energy.len or o_idx < 0 or o_idx >= energy[0].len) { return 0; } const r = @intCast(usize, row_idx); const o = @intCast(usize, o_idx); if (flashed[r][o]) { return 0; } energy[r][o] += 1; if (energy[r][o] <= 9) { return 0; } return flash(flashed, energy, row_idx, o_idx); } fn flash(flashed: *[size][size]bool, energy: *[size][size]u8, row_idx: i64, o_idx: i64) u64 { const r = @intCast(usize, row_idx); const o = @intCast(usize, o_idx); var result: u64 = 1; flashed[r][o] = true; const neighbor_offsets = [_]Offset{ .{ .x = -1, .y = -1 }, .{ .x = 0, .y = -1 }, .{ .x = 1, .y = -1 }, .{ .x = -1, .y = 0 }, .{ .x = 1, .y = 0 }, .{ .x = -1, .y = 1 }, .{ .x = 0, .y = 1 }, .{ .x = 1, .y = 1 }, }; for (neighbor_offsets) |offset| { result += increase(flashed, energy, row_idx + offset.y, o_idx + offset.x); } energy[r][o] = 0; return result; } fn step(flashed: *[size][size]bool, energy: *[size][size]u8) u64 { for (flashed) |*row| { std.mem.set(bool, &row.*, false); } for (energy) |*row| { for (row.*) |*octopus| { octopus.* += 1; } } var result: usize = 0; for (energy) |*row, row_idx| { for (row.*) |octopus, o_idx| { if (octopus > 9) { result += flash(flashed, energy, @intCast(i64, row_idx), @intCast(i64, o_idx)); } } } return result; } pub fn main() anyerror!void { const timer = try std.time.Timer.start(); var lines = std.mem.tokenize(u8, input, "\r\n"); var flashed = [_][size]bool{[_]bool{false} ** size} ** size; var energy = [_][size]u8{[_]u8{0} ** size} ** size; var p1: u64 = 0; var line_idx: usize = 0; while (lines.next()) |line| : (line_idx += 1) { for (line) |c, idx| { energy[line_idx][idx] = try std.fmt.parseInt(u8, &.{c}, 10); } } var current_step: usize = 0; outer: while (true) : (current_step += 1) { const flashes = step(&flashed, &energy); if (current_step < 100) { p1 += flashes; } for (flashed) |row| { for (row) |o| { if (!o) { continue :outer; } } } current_step += 1; break; } const time = timer.read(); std.debug.print("Part1: {}\n", .{p1}); std.debug.print("Part2: {}\n", .{current_step}); std.debug.print("Runtime (excluding output): {}us\n", .{time / std.time.ns_per_us}); }
https://raw.githubusercontent.com/tschaei/advent-of-code-2021/b5edc1e35917e0d0266ced7d15bd2017a2ff1791/src/day11.zig
const std = @import("std"); const vulkan = @import("vulkan"); const l0vk = @import("./vulkan.zig"); pub const VkSemaphore = vulkan.VkSemaphore; pub const VkSemaphoreCreateFlags = packed struct(u32) { _: u32 = 0, }; pub const VkSemaphoreCreateInfo = extern struct { pNext: ?*const anyopaque = null, flags: VkSemaphoreCreateFlags = .{}, pub fn to_vulkan_ty(self: *const VkSemaphoreCreateInfo) vulkan.VkSemaphoreCreateInfo { return .{ .sType = vulkan.VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO, .pNext = self.pNext, .flags = @bitCast(self.flags), }; } }; pub const vkCreateSemaphoreError = error{ VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY, }; pub fn vkCreateSemaphore( device: l0vk.VkDevice, pCreateInfo: *const VkSemaphoreCreateInfo, pAllocator: ?*const l0vk.VkAllocationCallbacks, ) vkCreateSemaphoreError!VkSemaphore { var create_info = pCreateInfo.to_vulkan_ty(); var semaphore: vulkan.VkSemaphore = undefined; const result = vulkan.vkCreateSemaphore( device, &create_info, pAllocator, &semaphore, ); if (result != vulkan.VK_SUCCESS) { switch (result) { vulkan.VK_ERROR_OUT_OF_HOST_MEMORY => return vkCreateSemaphoreError.VK_ERROR_OUT_OF_HOST_MEMORY, vulkan.VK_ERROR_OUT_OF_DEVICE_MEMORY => return vkCreateSemaphoreError.VK_ERROR_OUT_OF_DEVICE_MEMORY, else => unreachable, } } return semaphore; } pub inline fn vkDestroySemaphore( device: l0vk.VkDevice, semaphore: VkSemaphore, pAllocator: ?*const l0vk.VkAllocationCallbacks, ) void { vulkan.vkDestroySemaphore(device, semaphore, pAllocator); } pub const VkFence = vulkan.VkFence; pub const VkFenceCreateFlags = packed struct(u32) { signaled: bool = false, _: u3 = 0, _a: u28 = 0, pub const Bits = enum(c_uint) { signaled = 0x00000001, }; }; pub const VkFenceCreateInfo = struct { pNext: ?*const anyopaque = null, flags: VkFenceCreateFlags = .{}, pub fn to_vulkan_ty(self: *const VkFenceCreateInfo) vulkan.VkFenceCreateInfo { return .{ .sType = vulkan.VK_STRUCTURE_TYPE_FENCE_CREATE_INFO, .pNext = self.pNext, .flags = @bitCast(self.flags), }; } }; pub const vkCreateFenceError = error{ VK_ERROR_OUT_OF_HOST_MEMORY, VK_ERROR_OUT_OF_DEVICE_MEMORY, }; pub fn vkCreateFence( device: l0vk.VkDevice, pCreateInfo: *const VkFenceCreateInfo, pAllocator: ?*const l0vk.VkAllocationCallbacks, ) vkCreateFenceError!VkFence { var create_info = pCreateInfo.to_vulkan_ty(); var fence: vulkan.VkFence = undefined; const result = vulkan.vkCreateFence( device, &create_info, pAllocator, &fence, ); if (result != vulkan.VK_SUCCESS) { switch (result) { vulkan.VK_ERROR_OUT_OF_HOST_MEMORY => return vkCreateFenceError.VK_ERROR_OUT_OF_HOST_MEMORY, vulkan.VK_ERROR_OUT_OF_DEVICE_MEMORY => return vkCreateFenceError.VK_ERROR_OUT_OF_DEVICE_MEMORY, else => unreachable, } } return fence; } pub inline fn vkDestroyFence( device: l0vk.VkDevice, fence: VkFence, pAllocator: ?*const l0vk.VkAllocationCallbacks, ) void { vulkan.vkDestroyFence(device, fence, pAllocator); }
https://raw.githubusercontent.com/treemcgee42/r4-engine/3f503075e591ea2831a603dbf02a4f83a25f8eed/src/core/renderer/layer0/vulkan/sync.zig
const std = @import("std"); const proto = @import("_proto.zig"); const Reader = proto.Reader; // #4 - Server finalizes with this const AuthenticationSASLFinal = @This(); data: []const u8, pub fn parse(data: []const u8) !AuthenticationSASLFinal { var reader = Reader.init(data); if (try reader.int32() != 12) { return error.NotSASLChallenge; } // can't really parse this, since it technically depends on the SASL // mechanism in use return .{ .data = reader.rest(), }; } const t = proto.testing; test "AuthenticationSASLFinal: parse" { var buf = try proto.Buffer.init(t.allocator, 128); defer buf.deinit(); { // too short try t.expectError(error.NoMoreData, AuthenticationSASLFinal.parse(buf.string())); try buf.write("123"); try t.expectError(error.NoMoreData, AuthenticationSASLFinal.parse(buf.string())); } { // wrong special sasl type buf.reset(); try buf.writeIntBig(u32, 13); try t.expectError(error.NotSASLChallenge, AuthenticationSASLFinal.parse(buf.string())); } { // success buf.reset(); try buf.writeIntBig(u32, 12); try buf.write("some server data"); const final = try AuthenticationSASLFinal.parse(buf.string()); try t.expectString("some server data", final.data); } }
https://raw.githubusercontent.com/karlseguin/pg.zig/4c43c24a42b886f2bbc9686a7323bed8cbf0ed4d/src/proto/AuthenticationSASLFinal.zig
const std = @import("std"); const c = @import("c.zig"); const global = @import("global.zig"); const AssetIdHashMap = std.AutoHashMap(AssetId, Asset); const AssetNameHashMap = std.StringHashMap(AssetId); var asset_id: AssetId = 0; var asset_id_table: AssetIdHashMap = undefined; var asset_name_table: AssetNameHashMap = undefined; /// doesn't free over-written assets pub fn load(kind: AssetKind, name: []const u8, options: AssetLoadOptions) !void { const asset = switch (kind) { .model => Asset{ .model = options.model, }, .model_animation => Asset{ .model_animation = options.model_animation, }, }; try asset_name_table.put(name, asset_id); try asset_id_table.put(asset_id, asset); asset_id += 1; } /// TODO? // pub fn unload() void {} pub fn getId(name: []const u8) AssetId { return asset_name_table.get(name).?; } pub fn getById(id: AssetId) Asset { return asset_id_table.get(id).?; } pub fn getByName(name: []const u8) Asset { return getById(getId(name)); } pub fn init() void { asset_name_table = AssetNameHashMap.init(global.mem.fba_allocator); asset_id_table = AssetIdHashMap.init(global.mem.fba_allocator); } pub fn deinit() void { asset_name_table.deinit(); asset_id_table.deinit(); } // ASSET pub const AssetId = u32; pub const AssetKind = enum { model, model_animation, }; pub const AssetLoadOptions = union(AssetKind) { model: Model, model_animation: ModelAnimation, }; pub const Asset = union(AssetKind) { model: Model, model_animation: ModelAnimation, }; // MODEL pub const Model = struct { rl_model: c.Model = undefined, pub fn init(path: []const u8) Model { return Model{ .rl_model = c.LoadModel(@ptrCast(path)), }; } pub fn deinit(self: *Model) void { c.UnloadModel(self.rl_model); self.* = undefined; } }; pub const ModelAnimation = struct { animations: [*c]c.ModelAnimation = undefined, animation_count: u32 = 0, pub fn init(path: []const u8) ModelAnimation { var anim_count: c_int = 0; const animations = c.LoadModelAnimations(@ptrCast(path), &anim_count); return ModelAnimation{ .animations = animations, .animation_count = @intCast(anim_count), }; } pub fn deinit(self: *ModelAnimation) void { c.UnloadModelAnimations(self.animations.ptr, self.animations.len); self.* = undefined; } }; pub const ModelAnimationState = struct { ani_ndx: u32 = 0, ani_frame: i32 = 0, pub fn setById(self: *ModelAnimation, ndx: u32) void { self.ani_ndx = ndx; } // TODO? // pub fn setByName(self: *ModelAnimation, name: []const u8) void {} pub fn animateModel(self: *ModelAnimationState, model: *Model, model_animation: *const ModelAnimation) void { const animation = model_animation.animations[self.ani_ndx]; self.ani_frame = @mod((self.ani_frame + 1), animation.frameCount); c.UpdateModelAnimation(model.rl_model, animation, self.ani_frame); } };
https://raw.githubusercontent.com/60fov/shoba/f34618136ef3aefac81da0ec153ed3fcfa6ba483/src/asset.zig
// generated code pub const GLenum = c_uint; pub const GLboolean = c_uint; pub const GLuint = c_uint; pub const GLint = c_int; pub const GLsizei = isize; pub const GLfloat = f32; pub const GLdouble = f64; pub const GLbitfield = c_uint; pub const GLubyte = u8; pub const GLbyte = i8; pub const GLushort = u16; pub const GLshort = i16; pub const VERSION: GLenum = 0x1F02; cullFace: extern fn (mode: GLenum) void, frontFace: extern fn (mode: GLenum) void, hint: extern fn (target: GLenum, mode: GLenum) void, lineWidth: extern fn (width: GLfloat) void, pointSize: extern fn (size: GLfloat) void, polygonMode: extern fn (face: GLenum, mode: GLenum) void, scissor: extern fn (x: GLint, y: GLint, width: GLsizei, height: GLsizei) void, texParameterf: extern fn (target: GLenum, pname: GLenum, param: GLfloat) void, texParameterfv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLfloat) void, texParameteri: extern fn (target: GLenum, pname: GLenum, param: GLint) void, texParameteriv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLint) void, texImage1D: extern fn (target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ?*const c_void) void, texImage2D: extern fn (target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ?*const c_void) void, drawBuffer: extern fn (buf: GLenum) void, clear: extern fn (mask: GLbitfield) void, clearColor: extern fn (red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) void, clearStencil: extern fn (s: GLint) void, clearDepth: extern fn (depth: GLdouble) void, stencilMask: extern fn (mask: GLuint) void, colorMask: extern fn (red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) void, depthMask: extern fn (flag: GLboolean) void, disable: extern fn (cap: GLenum) void, enable: extern fn (cap: GLenum) void, finish: extern fn () void, flush: extern fn () void, blendFunc: extern fn (sfactor: GLenum, dfactor: GLenum) void, logicOp: extern fn (opcode: GLenum) void, stencilFunc: extern fn (func: GLenum, ref: GLint, mask: GLuint) void, stencilOp: extern fn (fail: GLenum, zfail: GLenum, zpass: GLenum) void, depthFunc: extern fn (func: GLenum) void, pixelStoref: extern fn (pname: GLenum, param: GLfloat) void, pixelStorei: extern fn (pname: GLenum, param: GLint) void, readBuffer: extern fn (src: GLenum) void, readPixels: extern fn (x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ?*c_void) void, getBooleanv: extern fn (pname: GLenum, data: [*c] GLboolean) void, getDoublev: extern fn (pname: GLenum, data: [*c] GLdouble) void, getError: extern fn () GLenum, getFloatv: extern fn (pname: GLenum, data: [*c] GLfloat) void, getIntegerv: extern fn (pname: GLenum, data: [*c] GLint) void, getString: extern fn (name: GLenum) [*c] GLubyte, getTexImage: extern fn (target: GLenum, level: GLint, format: GLenum, type: GLenum, pixels: ?*c_void) void, getTexParameterfv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLfloat) void, getTexParameteriv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLint) void, getTexLevelParameterfv: extern fn (target: GLenum, level: GLint, pname: GLenum, params: [*c] GLfloat) void, getTexLevelParameteriv: extern fn (target: GLenum, level: GLint, pname: GLenum, params: [*c] GLint) void, isEnabled: extern fn (cap: GLenum) GLboolean, depthRange: extern fn (n: GLdouble, f: GLdouble) void, viewport: extern fn (x: GLint, y: GLint, width: GLsizei, height: GLsizei) void, newList: extern fn (list: GLuint, mode: GLenum) void, endList: extern fn () void, callList: extern fn (list: GLuint) void, callLists: extern fn (n: GLsizei, type: GLenum, lists: ?*const c_void) void, deleteLists: extern fn (list: GLuint, range: GLsizei) void, genLists: extern fn (range: GLsizei) GLuint, listBase: extern fn (base: GLuint) void, begin: extern fn (mode: GLenum) void, bitmap: extern fn (width: GLsizei, height: GLsizei, xorig: GLfloat, yorig: GLfloat, xmove: GLfloat, ymove: GLfloat, bitmap: [*c] GLubyte) void, color3b: extern fn (red: GLbyte, green: GLbyte, blue: GLbyte) void, color3bv: extern fn (v: [*c] GLbyte) void, color3d: extern fn (red: GLdouble, green: GLdouble, blue: GLdouble) void, color3dv: extern fn (v: [*c] GLdouble) void, color3f: extern fn (red: GLfloat, green: GLfloat, blue: GLfloat) void, color3fv: extern fn (v: [*c] GLfloat) void, color3i: extern fn (red: GLint, green: GLint, blue: GLint) void, color3iv: extern fn (v: [*c] GLint) void, color3s: extern fn (red: GLshort, green: GLshort, blue: GLshort) void, color3sv: extern fn (v: [*c] GLshort) void, color3ub: extern fn (red: GLubyte, green: GLubyte, blue: GLubyte) void, color3ubv: extern fn (v: [*c] GLubyte) void, color3ui: extern fn (red: GLuint, green: GLuint, blue: GLuint) void, color3uiv: extern fn (v: [*c] GLuint) void, color3us: extern fn (red: GLushort, green: GLushort, blue: GLushort) void, color3usv: extern fn (v: [*c] GLushort) void, color4b: extern fn (red: GLbyte, green: GLbyte, blue: GLbyte, alpha: GLbyte) void, color4bv: extern fn (v: [*c] GLbyte) void, color4d: extern fn (red: GLdouble, green: GLdouble, blue: GLdouble, alpha: GLdouble) void, color4dv: extern fn (v: [*c] GLdouble) void, color4f: extern fn (red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) void, color4fv: extern fn (v: [*c] GLfloat) void, color4i: extern fn (red: GLint, green: GLint, blue: GLint, alpha: GLint) void, color4iv: extern fn (v: [*c] GLint) void, color4s: extern fn (red: GLshort, green: GLshort, blue: GLshort, alpha: GLshort) void, color4sv: extern fn (v: [*c] GLshort) void, color4ub: extern fn (red: GLubyte, green: GLubyte, blue: GLubyte, alpha: GLubyte) void, color4ubv: extern fn (v: [*c] GLubyte) void, color4ui: extern fn (red: GLuint, green: GLuint, blue: GLuint, alpha: GLuint) void, color4uiv: extern fn (v: [*c] GLuint) void, color4us: extern fn (red: GLushort, green: GLushort, blue: GLushort, alpha: GLushort) void, color4usv: extern fn (v: [*c] GLushort) void, edgeFlag: extern fn (flag: GLboolean) void, edgeFlagv: extern fn (flag: [*c] GLboolean) void, end: extern fn () void, indexd: extern fn (c: GLdouble) void, indexdv: extern fn (c: [*c] GLdouble) void, indexf: extern fn (c: GLfloat) void, indexfv: extern fn (c: [*c] GLfloat) void, indexi: extern fn (c: GLint) void, indexiv: extern fn (c: [*c] GLint) void, indexs: extern fn (c: GLshort) void, indexsv: extern fn (c: [*c] GLshort) void, normal3b: extern fn (nx: GLbyte, ny: GLbyte, nz: GLbyte) void, normal3bv: extern fn (v: [*c] GLbyte) void, normal3d: extern fn (nx: GLdouble, ny: GLdouble, nz: GLdouble) void, normal3dv: extern fn (v: [*c] GLdouble) void, normal3f: extern fn (nx: GLfloat, ny: GLfloat, nz: GLfloat) void, normal3fv: extern fn (v: [*c] GLfloat) void, normal3i: extern fn (nx: GLint, ny: GLint, nz: GLint) void, normal3iv: extern fn (v: [*c] GLint) void, normal3s: extern fn (nx: GLshort, ny: GLshort, nz: GLshort) void, normal3sv: extern fn (v: [*c] GLshort) void, rasterPos2d: extern fn (x: GLdouble, y: GLdouble) void, rasterPos2dv: extern fn (v: [*c] GLdouble) void, rasterPos2f: extern fn (x: GLfloat, y: GLfloat) void, rasterPos2fv: extern fn (v: [*c] GLfloat) void, rasterPos2i: extern fn (x: GLint, y: GLint) void, rasterPos2iv: extern fn (v: [*c] GLint) void, rasterPos2s: extern fn (x: GLshort, y: GLshort) void, rasterPos2sv: extern fn (v: [*c] GLshort) void, rasterPos3d: extern fn (x: GLdouble, y: GLdouble, z: GLdouble) void, rasterPos3dv: extern fn (v: [*c] GLdouble) void, rasterPos3f: extern fn (x: GLfloat, y: GLfloat, z: GLfloat) void, rasterPos3fv: extern fn (v: [*c] GLfloat) void, rasterPos3i: extern fn (x: GLint, y: GLint, z: GLint) void, rasterPos3iv: extern fn (v: [*c] GLint) void, rasterPos3s: extern fn (x: GLshort, y: GLshort, z: GLshort) void, rasterPos3sv: extern fn (v: [*c] GLshort) void, rasterPos4d: extern fn (x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) void, rasterPos4dv: extern fn (v: [*c] GLdouble) void, rasterPos4f: extern fn (x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) void, rasterPos4fv: extern fn (v: [*c] GLfloat) void, rasterPos4i: extern fn (x: GLint, y: GLint, z: GLint, w: GLint) void, rasterPos4iv: extern fn (v: [*c] GLint) void, rasterPos4s: extern fn (x: GLshort, y: GLshort, z: GLshort, w: GLshort) void, rasterPos4sv: extern fn (v: [*c] GLshort) void, rectd: extern fn (x1: GLdouble, y1: GLdouble, x2: GLdouble, y2: GLdouble) void, rectdv: extern fn (v1: [*c] GLdouble, v2: [*c] GLdouble) void, rectf: extern fn (x1: GLfloat, y1: GLfloat, x2: GLfloat, y2: GLfloat) void, rectfv: extern fn (v1: [*c] GLfloat, v2: [*c] GLfloat) void, recti: extern fn (x1: GLint, y1: GLint, x2: GLint, y2: GLint) void, rectiv: extern fn (v1: [*c] GLint, v2: [*c] GLint) void, rects: extern fn (x1: GLshort, y1: GLshort, x2: GLshort, y2: GLshort) void, rectsv: extern fn (v1: [*c] GLshort, v2: [*c] GLshort) void, texCoord1d: extern fn (s: GLdouble) void, texCoord1dv: extern fn (v: [*c] GLdouble) void, texCoord1f: extern fn (s: GLfloat) void, texCoord1fv: extern fn (v: [*c] GLfloat) void, texCoord1i: extern fn (s: GLint) void, texCoord1iv: extern fn (v: [*c] GLint) void, texCoord1s: extern fn (s: GLshort) void, texCoord1sv: extern fn (v: [*c] GLshort) void, texCoord2d: extern fn (s: GLdouble, t: GLdouble) void, texCoord2dv: extern fn (v: [*c] GLdouble) void, texCoord2f: extern fn (s: GLfloat, t: GLfloat) void, texCoord2fv: extern fn (v: [*c] GLfloat) void, texCoord2i: extern fn (s: GLint, t: GLint) void, texCoord2iv: extern fn (v: [*c] GLint) void, texCoord2s: extern fn (s: GLshort, t: GLshort) void, texCoord2sv: extern fn (v: [*c] GLshort) void, texCoord3d: extern fn (s: GLdouble, t: GLdouble, r: GLdouble) void, texCoord3dv: extern fn (v: [*c] GLdouble) void, texCoord3f: extern fn (s: GLfloat, t: GLfloat, r: GLfloat) void, texCoord3fv: extern fn (v: [*c] GLfloat) void, texCoord3i: extern fn (s: GLint, t: GLint, r: GLint) void, texCoord3iv: extern fn (v: [*c] GLint) void, texCoord3s: extern fn (s: GLshort, t: GLshort, r: GLshort) void, texCoord3sv: extern fn (v: [*c] GLshort) void, texCoord4d: extern fn (s: GLdouble, t: GLdouble, r: GLdouble, q: GLdouble) void, texCoord4dv: extern fn (v: [*c] GLdouble) void, texCoord4f: extern fn (s: GLfloat, t: GLfloat, r: GLfloat, q: GLfloat) void, texCoord4fv: extern fn (v: [*c] GLfloat) void, texCoord4i: extern fn (s: GLint, t: GLint, r: GLint, q: GLint) void, texCoord4iv: extern fn (v: [*c] GLint) void, texCoord4s: extern fn (s: GLshort, t: GLshort, r: GLshort, q: GLshort) void, texCoord4sv: extern fn (v: [*c] GLshort) void, vertex2d: extern fn (x: GLdouble, y: GLdouble) void, vertex2dv: extern fn (v: [*c] GLdouble) void, vertex2f: extern fn (x: GLfloat, y: GLfloat) void, vertex2fv: extern fn (v: [*c] GLfloat) void, vertex2i: extern fn (x: GLint, y: GLint) void, vertex2iv: extern fn (v: [*c] GLint) void, vertex2s: extern fn (x: GLshort, y: GLshort) void, vertex2sv: extern fn (v: [*c] GLshort) void, vertex3d: extern fn (x: GLdouble, y: GLdouble, z: GLdouble) void, vertex3dv: extern fn (v: [*c] GLdouble) void, vertex3f: extern fn (x: GLfloat, y: GLfloat, z: GLfloat) void, vertex3fv: extern fn (v: [*c] GLfloat) void, vertex3i: extern fn (x: GLint, y: GLint, z: GLint) void, vertex3iv: extern fn (v: [*c] GLint) void, vertex3s: extern fn (x: GLshort, y: GLshort, z: GLshort) void, vertex3sv: extern fn (v: [*c] GLshort) void, vertex4d: extern fn (x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) void, vertex4dv: extern fn (v: [*c] GLdouble) void, vertex4f: extern fn (x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) void, vertex4fv: extern fn (v: [*c] GLfloat) void, vertex4i: extern fn (x: GLint, y: GLint, z: GLint, w: GLint) void, vertex4iv: extern fn (v: [*c] GLint) void, vertex4s: extern fn (x: GLshort, y: GLshort, z: GLshort, w: GLshort) void, vertex4sv: extern fn (v: [*c] GLshort) void, clipPlane: extern fn (plane: GLenum, equation: [*c] GLdouble) void, colorMaterial: extern fn (face: GLenum, mode: GLenum) void, fogf: extern fn (pname: GLenum, param: GLfloat) void, fogfv: extern fn (pname: GLenum, params: [*c] GLfloat) void, fogi: extern fn (pname: GLenum, param: GLint) void, fogiv: extern fn (pname: GLenum, params: [*c] GLint) void, lightf: extern fn (light: GLenum, pname: GLenum, param: GLfloat) void, lightfv: extern fn (light: GLenum, pname: GLenum, params: [*c] GLfloat) void, lighti: extern fn (light: GLenum, pname: GLenum, param: GLint) void, lightiv: extern fn (light: GLenum, pname: GLenum, params: [*c] GLint) void, lightModelf: extern fn (pname: GLenum, param: GLfloat) void, lightModelfv: extern fn (pname: GLenum, params: [*c] GLfloat) void, lightModeli: extern fn (pname: GLenum, param: GLint) void, lightModeliv: extern fn (pname: GLenum, params: [*c] GLint) void, lineStipple: extern fn (factor: GLint, pattern: GLushort) void, materialf: extern fn (face: GLenum, pname: GLenum, param: GLfloat) void, materialfv: extern fn (face: GLenum, pname: GLenum, params: [*c] GLfloat) void, materiali: extern fn (face: GLenum, pname: GLenum, param: GLint) void, materialiv: extern fn (face: GLenum, pname: GLenum, params: [*c] GLint) void, polygonStipple: extern fn (mask: [*c] GLubyte) void, shadeModel: extern fn (mode: GLenum) void, texEnvf: extern fn (target: GLenum, pname: GLenum, param: GLfloat) void, texEnvfv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLfloat) void, texEnvi: extern fn (target: GLenum, pname: GLenum, param: GLint) void, texEnviv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLint) void, texGend: extern fn (coord: GLenum, pname: GLenum, param: GLdouble) void, texGendv: extern fn (coord: GLenum, pname: GLenum, params: [*c] GLdouble) void, texGenf: extern fn (coord: GLenum, pname: GLenum, param: GLfloat) void, texGenfv: extern fn (coord: GLenum, pname: GLenum, params: [*c] GLfloat) void, texGeni: extern fn (coord: GLenum, pname: GLenum, param: GLint) void, texGeniv: extern fn (coord: GLenum, pname: GLenum, params: [*c] GLint) void, feedbackBuffer: extern fn (size: GLsizei, type: GLenum, buffer: [*c] GLfloat) void, selectBuffer: extern fn (size: GLsizei, buffer: [*c] GLuint) void, renderMode: extern fn (mode: GLenum) GLint, initNames: extern fn () void, loadName: extern fn (name: GLuint) void, passThrough: extern fn (token: GLfloat) void, popName: extern fn () void, pushName: extern fn (name: GLuint) void, clearAccum: extern fn (red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) void, clearIndex: extern fn (c: GLfloat) void, indexMask: extern fn (mask: GLuint) void, accum: extern fn (op: GLenum, value: GLfloat) void, popAttrib: extern fn () void, pushAttrib: extern fn (mask: GLbitfield) void, map1d: extern fn (target: GLenum, u1: GLdouble, u2: GLdouble, stride: GLint, order: GLint, points: [*c] GLdouble) void, map1f: extern fn (target: GLenum, u1: GLfloat, u2: GLfloat, stride: GLint, order: GLint, points: [*c] GLfloat) void, map2d: extern fn (target: GLenum, u1: GLdouble, u2: GLdouble, ustride: GLint, uorder: GLint, v1: GLdouble, v2: GLdouble, vstride: GLint, vorder: GLint, points: [*c] GLdouble) void, map2f: extern fn (target: GLenum, u1: GLfloat, u2: GLfloat, ustride: GLint, uorder: GLint, v1: GLfloat, v2: GLfloat, vstride: GLint, vorder: GLint, points: [*c] GLfloat) void, mapGrid1d: extern fn (un: GLint, u1: GLdouble, u2: GLdouble) void, mapGrid1f: extern fn (un: GLint, u1: GLfloat, u2: GLfloat) void, mapGrid2d: extern fn (un: GLint, u1: GLdouble, u2: GLdouble, vn: GLint, v1: GLdouble, v2: GLdouble) void, mapGrid2f: extern fn (un: GLint, u1: GLfloat, u2: GLfloat, vn: GLint, v1: GLfloat, v2: GLfloat) void, evalCoord1d: extern fn (u: GLdouble) void, evalCoord1dv: extern fn (u: [*c] GLdouble) void, evalCoord1f: extern fn (u: GLfloat) void, evalCoord1fv: extern fn (u: [*c] GLfloat) void, evalCoord2d: extern fn (u: GLdouble, v: GLdouble) void, evalCoord2dv: extern fn (u: [*c] GLdouble) void, evalCoord2f: extern fn (u: GLfloat, v: GLfloat) void, evalCoord2fv: extern fn (u: [*c] GLfloat) void, evalMesh1: extern fn (mode: GLenum, i1: GLint, i2: GLint) void, evalPoint1: extern fn (i: GLint) void, evalMesh2: extern fn (mode: GLenum, i1: GLint, i2: GLint, j1: GLint, j2: GLint) void, evalPoint2: extern fn (i: GLint, j: GLint) void, alphaFunc: extern fn (func: GLenum, ref: GLfloat) void, pixelZoom: extern fn (xfactor: GLfloat, yfactor: GLfloat) void, pixelTransferf: extern fn (pname: GLenum, param: GLfloat) void, pixelTransferi: extern fn (pname: GLenum, param: GLint) void, pixelMapfv: extern fn (map: GLenum, mapsize: GLsizei, values: [*c] GLfloat) void, pixelMapuiv: extern fn (map: GLenum, mapsize: GLsizei, values: [*c] GLuint) void, pixelMapusv: extern fn (map: GLenum, mapsize: GLsizei, values: [*c] GLushort) void, copyPixels: extern fn (x: GLint, y: GLint, width: GLsizei, height: GLsizei, type: GLenum) void, drawPixels: extern fn (width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ?*const c_void) void, getClipPlane: extern fn (plane: GLenum, equation: [*c] GLdouble) void, getLightfv: extern fn (light: GLenum, pname: GLenum, params: [*c] GLfloat) void, getLightiv: extern fn (light: GLenum, pname: GLenum, params: [*c] GLint) void, getMapdv: extern fn (target: GLenum, query: GLenum, v: [*c] GLdouble) void, getMapfv: extern fn (target: GLenum, query: GLenum, v: [*c] GLfloat) void, getMapiv: extern fn (target: GLenum, query: GLenum, v: [*c] GLint) void, getMaterialfv: extern fn (face: GLenum, pname: GLenum, params: [*c] GLfloat) void, getMaterialiv: extern fn (face: GLenum, pname: GLenum, params: [*c] GLint) void, getPixelMapfv: extern fn (map: GLenum, values: [*c] GLfloat) void, getPixelMapuiv: extern fn (map: GLenum, values: [*c] GLuint) void, getPixelMapusv: extern fn (map: GLenum, values: [*c] GLushort) void, getPolygonStipple: extern fn (mask: [*c] GLubyte) void, getTexEnvfv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLfloat) void, getTexEnviv: extern fn (target: GLenum, pname: GLenum, params: [*c] GLint) void, getTexGendv: extern fn (coord: GLenum, pname: GLenum, params: [*c] GLdouble) void, getTexGenfv: extern fn (coord: GLenum, pname: GLenum, params: [*c] GLfloat) void, getTexGeniv: extern fn (coord: GLenum, pname: GLenum, params: [*c] GLint) void, isList: extern fn (list: GLuint) GLboolean, frustum: extern fn (left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) void, loadIdentity: extern fn () void, loadMatrixf: extern fn (m: [*c] GLfloat) void, loadMatrixd: extern fn (m: [*c] GLdouble) void, matrixMode: extern fn (mode: GLenum) void, multMatrixf: extern fn (m: [*c] GLfloat) void, multMatrixd: extern fn (m: [*c] GLdouble) void, ortho: extern fn (left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) void, popMatrix: extern fn () void, pushMatrix: extern fn () void, rotated: extern fn (angle: GLdouble, x: GLdouble, y: GLdouble, z: GLdouble) void, rotatef: extern fn (angle: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) void, scaled: extern fn (x: GLdouble, y: GLdouble, z: GLdouble) void, scalef: extern fn (x: GLfloat, y: GLfloat, z: GLfloat) void, translated: extern fn (x: GLdouble, y: GLdouble, z: GLdouble) void, translatef: extern fn (x: GLfloat, y: GLfloat, z: GLfloat) void, drawArrays: extern fn (mode: GLenum, first: GLint, count: GLsizei) void, drawElements: extern fn (mode: GLenum, count: GLsizei, type: GLenum, indices: ?*const c_void) void, getPointerv: extern fn (pname: GLenum, params: ?**c_void) void, polygonOffset: extern fn (factor: GLfloat, units: GLfloat) void, copyTexImage1D: extern fn (target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, border: GLint) void, copyTexImage2D: extern fn (target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) void, copyTexSubImage1D: extern fn (target: GLenum, level: GLint, xoffset: GLint, x: GLint, y: GLint, width: GLsizei) void, copyTexSubImage2D: extern fn (target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) void, texSubImage1D: extern fn (target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, type: GLenum, pixels: ?*const c_void) void, texSubImage2D: extern fn (target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ?*const c_void) void, bindTexture: extern fn (target: GLenum, texture: GLuint) void, deleteTextures: extern fn (n: GLsizei, textures: [*c] GLuint) void, genTextures: extern fn (n: GLsizei, textures: [*c] GLuint) void, isTexture: extern fn (texture: GLuint) GLboolean, arrayElement: extern fn (i: GLint) void, colorPointer: extern fn (size: GLint, type: GLenum, stride: GLsizei, pointer: ?*const c_void) void, disableClientState: extern fn (array: GLenum) void, edgeFlagPointer: extern fn (stride: GLsizei, pointer: ?*const c_void) void, enableClientState: extern fn (array: GLenum) void, indexPointer: extern fn (type: GLenum, stride: GLsizei, pointer: ?*const c_void) void, interleavedArrays: extern fn (format: GLenum, stride: GLsizei, pointer: ?*const c_void) void, normalPointer: extern fn (type: GLenum, stride: GLsizei, pointer: ?*const c_void) void, texCoordPointer: extern fn (size: GLint, type: GLenum, stride: GLsizei, pointer: ?*const c_void) void, vertexPointer: extern fn (size: GLint, type: GLenum, stride: GLsizei, pointer: ?*const c_void) void, areTexturesResident: extern fn (n: GLsizei, textures: [*c] GLuint, residences: [*c] GLboolean) GLboolean, prioritizeTextures: extern fn (n: GLsizei, textures: [*c] GLuint, priorities: [*c] GLfloat) void, indexub: extern fn (c: GLubyte) void, indexubv: extern fn (c: [*c] GLubyte) void, popClientAttrib: extern fn () void, pushClientAttrib: extern fn (mask: GLbitfield) void, drawRangeElements: extern fn (mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, indices: ?*const c_void) void, texImage3D: extern fn (target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ?*const c_void) void, texSubImage3D: extern fn (target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pixels: ?*const c_void) void, copyTexSubImage3D: extern fn (target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) void,
https://raw.githubusercontent.com/ikskuh/ZigPaint/d821f0a3fac66a29f6ee161b62e8be947d6a2823/gl/versions/GL_VERSION_1_2.zig
const std = @import("std"); const stdx = @import("../stdx.zig"); const maybe = stdx.maybe; const mem = std.mem; const assert = std.debug.assert; const constants = @import("../constants.zig"); const vsr = @import("../vsr.zig"); const Header = vsr.Header; const MessagePool = @import("../message_pool.zig").MessagePool; const Message = @import("../message_pool.zig").MessagePool.Message; const IOPS = @import("../iops.zig").IOPS; const FIFO = @import("../fifo.zig").FIFO; const log = std.log.scoped(.client); pub fn Client(comptime StateMachine_: type, comptime MessageBus: type) type { return struct { const Self = @This(); pub const StateMachine = StateMachine_; pub const DemuxerType = StateMachine.DemuxerType; pub const Request = struct { pub const Callback = *const fn ( user_data: u128, operation: StateMachine.Operation, results: []u8, ) void; pub const RegisterCallback = *const fn ( user_data: u128, result: *const vsr.RegisterResult, ) void; message: *Message.Request, user_data: u128, callback: union(enum) { /// When message.header.operation ≠ .register request: Callback, /// When message.header.operation = .register register: RegisterCallback, }, }; allocator: mem.Allocator, message_bus: MessageBus, /// A universally unique identifier for the client (must not be zero). /// Used for routing replies back to the client via any network path (multi-path routing). /// The client ID must be ephemeral and random per process, and never persisted, so that /// lingering or zombie deployment processes cannot break correctness and/or liveness. /// A cryptographic random number generator must be used to ensure these properties. id: u128, /// The identifier for the cluster that this client intends to communicate with. cluster: u128, /// The number of replicas in the cluster. replica_count: u8, /// Only tests should ever override the release. release: vsr.Release = constants.config.process.release, /// The total number of ticks elapsed since the client was initialized. ticks: u64 = 0, /// We hash-chain request/reply checksums to verify linearizability within a client session: /// * so that the parent of the next request is the checksum of the latest reply, and /// * so that the parent of the next reply is the checksum of the latest request. parent: u128 = 0, /// The session number for the client, zero when registering a session, non-zero thereafter. session: u64 = 0, /// The request number of the next request. request_number: u32 = 0, /// The highest view number seen by the client in messages exchanged with the cluster. /// Used to locate the current primary, and provide more information to a partitioned primary. view: u32 = 0, /// Tracks a currently processing (non-register) request message submitted by `register()` /// or `raw_request()`. request_inflight: ?Request = null, /// The number of ticks without a reply before the client resends the inflight request. /// Dynamically adjusted as a function of recent request round-trip time. request_timeout: vsr.Timeout, /// The number of ticks before the client broadcasts a ping to the cluster. /// Used for end-to-end keepalive, and to discover a new primary between requests. ping_timeout: vsr.Timeout, /// Used to calculate exponential backoff with random jitter. /// Seeded with the client's ID. prng: std.rand.DefaultPrng, on_reply_context: ?*anyopaque = null, /// Used for testing. Called for replies to all operations (including `register`). on_reply_callback: ?*const fn ( client: *Self, request: *Message.Request, reply: *Message.Reply, ) void = null, pub fn init( allocator: mem.Allocator, id: u128, cluster: u128, replica_count: u8, message_pool: *MessagePool, message_bus_options: MessageBus.Options, ) !Self { assert(id > 0); assert(replica_count > 0); var message_bus = try MessageBus.init( allocator, cluster, .{ .client = id }, message_pool, Self.on_message, message_bus_options, ); errdefer message_bus.deinit(allocator); var self = Self{ .allocator = allocator, .message_bus = message_bus, .id = id, .cluster = cluster, .replica_count = replica_count, .request_timeout = .{ .name = "request_timeout", .id = id, .after = constants.rtt_ticks * constants.rtt_multiple, }, .ping_timeout = .{ .name = "ping_timeout", .id = id, .after = 30000 / constants.tick_ms, }, .prng = std.rand.DefaultPrng.init(@as(u64, @truncate(id))), }; self.ping_timeout.start(); return self; } pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { if (self.request_inflight) |inflight| self.release_message(inflight.message.base()); self.message_bus.deinit(allocator); } pub fn on_message(message_bus: *MessageBus, message: *Message) void { const self = @fieldParentPtr(Self, "message_bus", message_bus); log.debug("{}: on_message: {}", .{ self.id, message.header }); if (message.header.invalid()) |reason| { log.debug("{}: on_message: invalid ({s})", .{ self.id, reason }); return; } if (message.header.cluster != self.cluster) { log.warn("{}: on_message: wrong cluster (cluster should be {}, not {})", .{ self.id, self.cluster, message.header.cluster, }); return; } switch (message.into_any()) { .pong_client => |m| self.on_pong_client(m), .reply => |m| self.on_reply(m), .eviction => |m| self.on_eviction(m), else => { log.warn("{}: on_message: ignoring misdirected {s} message", .{ self.id, @tagName(message.header.command), }); return; }, } } pub fn tick(self: *Self) void { self.ticks += 1; self.message_bus.tick(); self.ping_timeout.tick(); self.request_timeout.tick(); if (self.ping_timeout.fired()) self.on_ping_timeout(); if (self.request_timeout.fired()) self.on_request_timeout(); } /// Sends a request message with the operation and events payload to the replica. /// There must be no other request message currently inflight. pub fn request( self: *Self, callback: Request.Callback, user_data: u128, operation: StateMachine.Operation, events: []const u8, ) void { const event_size: usize = switch (operation) { inline else => |operation_comptime| @sizeOf(StateMachine.Event(operation_comptime)), }; assert(self.request_inflight == null); assert(self.request_number > 0); assert(events.len <= constants.message_body_size_max); assert(events.len % event_size == 0); const message = self.get_message().build(.request); errdefer self.release_message(message.base()); message.header.* = .{ .client = self.id, .request = 0, // Set inside `raw_request` down below. .cluster = self.cluster, .command = .request, .release = self.release, .operation = vsr.Operation.from(StateMachine, operation), .size = @intCast(@sizeOf(Header) + events.len), }; stdx.copy_disjoint(.exact, u8, message.body(), events); self.raw_request(callback, user_data, message); } /// Sends a request, only setting request_number in the header. /// There must be no other request message currently inflight. pub fn raw_request( self: *Self, callback: Request.Callback, user_data: u128, message: *Message.Request, ) void { assert(self.request_inflight == null); assert(self.request_number > 0); assert(message.header.client == self.id); assert(message.header.release.value == self.release.value); assert(message.header.cluster == self.cluster); assert(message.header.command == .request); assert(message.header.size >= @sizeOf(Header)); assert(message.header.size <= constants.message_size_max); assert(message.header.operation.valid(StateMachine)); assert(message.header.view == 0); assert(message.header.parent == 0); assert(message.header.session == 0); assert(message.header.request == 0); if (!constants.aof_recovery) { assert(!message.header.operation.vsr_reserved()); } // TODO: Re-investigate this state for AOF as it currently traps. // assert(message.header.timestamp == 0 or constants.aof_recovery); message.header.request = self.request_number; self.request_number += 1; log.debug("{}: request: user_data={} request={} size={} {s}", .{ self.id, user_data, message.header.request, message.header.size, message.header.operation.tag_name(StateMachine), }); self.request_inflight = .{ .message = message, .user_data = user_data, .callback = .{ .request = callback }, }; self.send_request_for_the_first_time(message); } /// Acquires a message from the message bus. /// The caller must ensure that a message is available. /// /// Either use it in `client.raw_request()` or discard via `client.release_message()`, /// the reference is not guaranteed to be valid after both actions. /// Do NOT use the reference counter function `message.ref()` for storing the message. pub fn get_message(self: *Self) *Message { return self.message_bus.get_message(null); } /// Releases a message back to the message bus. pub fn release_message(self: *Self, message: *Message) void { self.message_bus.unref(message); } fn on_eviction(self: *Self, eviction: *const Message.Eviction) void { assert(eviction.header.command == .eviction); assert(eviction.header.cluster == self.cluster); if (eviction.header.client != self.id) { log.warn("{}: on_eviction: ignoring (wrong client={})", .{ self.id, eviction.header.client, }); return; } if (eviction.header.view < self.view) { log.debug("{}: on_eviction: ignoring (older view={})", .{ self.id, eviction.header.view, }); return; } assert(eviction.header.client == self.id); assert(eviction.header.view >= self.view); log.err("{}: session evicted: reason={s} (cluster_release={})", .{ self.id, @tagName(eviction.header.reason), eviction.header.release, }); @panic("session evicted"); } fn on_pong_client(self: *Self, pong: *const Message.PongClient) void { assert(pong.header.command == .pong_client); assert(pong.header.cluster == self.cluster); if (pong.header.view > self.view) { log.debug("{}: on_pong: newer view={}..{}", .{ self.id, self.view, pong.header.view, }); self.view = pong.header.view; } } fn on_reply(self: *Self, reply: *Message.Reply) void { // We check these checksums again here because this is the last time we get to downgrade // a correctness bug into a liveness bug, before we return data back to the application. assert(reply.header.valid_checksum()); assert(reply.header.valid_checksum_body(reply.body())); assert(reply.header.command == .reply); assert(reply.header.release.value == self.release.value); if (reply.header.client != self.id) { log.debug("{}: on_reply: ignoring (wrong client={})", .{ self.id, reply.header.client, }); return; } var inflight = self.request_inflight orelse { assert(reply.header.request < self.request_number); log.debug("{}: on_reply: ignoring (no inflight request)", .{self.id}); return; }; if (reply.header.request < inflight.message.header.request) { assert(inflight.message.header.request > 0); assert(inflight.message.header.operation != .register); log.debug("{}: on_reply: ignoring (request {} < {})", .{ self.id, reply.header.request, inflight.message.header.request, }); return; } assert(reply.header.request == inflight.message.header.request); assert(reply.header.request_checksum == inflight.message.header.checksum); const inflight_vsr_operation = inflight.message.header.operation; const inflight_request = inflight.message.header.request; if (inflight_vsr_operation == .register) { assert(inflight_request == 0); } else { assert(inflight_request > 0); } // Consume the inflight request here before invoking callbacks down below in case they // wish to queue a new `request_inflight`. assert(inflight.message == self.request_inflight.?.message); self.request_inflight = null; if (self.on_reply_callback) |on_reply_callback| { on_reply_callback(self, inflight.message, reply); } log.debug("{}: on_reply: user_data={} request={} size={} {s}", .{ self.id, inflight.user_data, reply.header.request, reply.header.size, reply.header.operation.tag_name(StateMachine), }); assert(reply.header.request_checksum == self.parent); assert(reply.header.client == self.id); assert(reply.header.request == inflight_request); assert(reply.header.cluster == self.cluster); assert(reply.header.op == reply.header.commit); assert(reply.header.operation == inflight_vsr_operation); // The context of this reply becomes the parent of our next request: self.parent = reply.header.context; if (reply.header.view > self.view) { log.debug("{}: on_reply: newer view={}..{}", .{ self.id, self.view, reply.header.view, }); self.view = reply.header.view; } self.request_timeout.stop(); // Release request message to ensure that inflight's callback can submit a new one. self.release_message(inflight.message.base()); inflight.message = undefined; if (inflight_vsr_operation == .register) { assert(inflight_request == 0); assert(self.session == 0); assert(reply.header.commit > 0); assert(reply.header.size == @sizeOf(Header) + @sizeOf(vsr.RegisterResult)); self.session = reply.header.commit; // The commit number becomes the session number. const result = std.mem.bytesAsValue( vsr.RegisterResult, reply.body()[0..@sizeOf(vsr.RegisterResult)], ); inflight.callback.register(inflight.user_data, result); } else { // The message is the result of raw_request(), so invoke the user callback. // NOTE: the callback is allowed to mutate `reply.body()` here. inflight.callback.request( inflight.user_data, inflight_vsr_operation.cast(StateMachine), reply.body(), ); } } fn on_ping_timeout(self: *Self) void { self.ping_timeout.reset(); const ping = Header.PingClient{ .command = .ping_client, .cluster = self.cluster, .release = self.release, .client = self.id, }; // TODO If we haven't received a pong from a replica since our last ping, then back off. self.send_header_to_replicas(ping.frame_const().*); } fn on_request_timeout(self: *Self) void { self.request_timeout.backoff(self.prng.random()); const message = self.request_inflight.?.message; assert(message.header.command == .request); assert(message.header.request < self.request_number); assert(message.header.checksum == self.parent); assert(message.header.session == self.session); log.debug("{}: on_request_timeout: resending request={} checksum={}", .{ self.id, message.header.request, message.header.checksum, }); // We assume the primary is down and round-robin through the cluster: self.send_message_to_replica( @as(u8, @intCast((self.view + self.request_timeout.attempts) % self.replica_count)), message.base(), ); } /// The caller owns the returned message, if any, which has exactly 1 reference. fn create_message_from_header(self: *Self, header: Header) *Message { assert(header.cluster == self.cluster); assert(header.size == @sizeOf(Header)); const message = self.message_bus.get_message(null); defer self.message_bus.unref(message); message.header.* = header; message.header.set_checksum_body(message.body()); message.header.set_checksum(); return message.ref(); } /// Registers a session with the cluster for the client, if this has not yet been done. pub fn register(self: *Self, callback: Request.RegisterCallback, user_data: u128) void { assert(self.request_inflight == null); assert(self.request_number == 0); const message = self.get_message().build(.request); errdefer self.release_message(message.base()); // We will set parent, session, view and checksums only when sending for the first time: message.header.* = .{ .client = self.id, .request = self.request_number, .cluster = self.cluster, .command = .request, .operation = .register, .release = self.release, }; assert(self.request_number == 0); self.request_number += 1; log.debug( "{}: register: registering a session with the cluster user_data={}", .{ self.id, user_data }, ); self.request_inflight = .{ .message = message, .user_data = user_data, .callback = .{ .register = callback }, }; self.send_request_for_the_first_time(message); } fn send_header_to_replica(self: *Self, replica: u8, header: Header) void { const message = self.create_message_from_header(header); defer self.message_bus.unref(message); self.send_message_to_replica(replica, message); } fn send_header_to_replicas(self: *Self, header: Header) void { const message = self.create_message_from_header(header); defer self.message_bus.unref(message); var replica: u8 = 0; while (replica < self.replica_count) : (replica += 1) { self.send_message_to_replica(replica, message); } } fn send_message_to_replica(self: *Self, replica: u8, message: *Message) void { log.debug("{}: sending {s} to replica {}: {}", .{ self.id, @tagName(message.header.command), replica, message.header, }); assert(replica < self.replica_count); assert(message.header.valid_checksum()); assert(message.header.cluster == self.cluster); switch (message.into_any()) { inline .request, .ping_client, => |m| assert(m.header.client == self.id), else => unreachable, } self.message_bus.send_message_to_replica(replica, message); } fn send_request_for_the_first_time(self: *Self, message: *Message.Request) void { assert(self.request_inflight.?.message == message); assert(self.request_number > 0); assert(message.header.command == .request); assert(message.header.parent == 0); assert(message.header.session == 0); assert(message.header.request < self.request_number); assert(message.header.view == 0); assert(message.header.size <= constants.message_size_max); // We set the message checksums only when sending the request for the first time, // which is when we have the checksum of the latest reply available to set as `parent`, // and similarly also the session number if requests were queued while registering: message.header.parent = self.parent; message.header.session = self.session; // We also try to include our highest view number, so we wait until the request is ready // to be sent for the first time. However, beyond that, it is not necessary to update // the view number again, for example if it should change between now and resending. message.header.view = self.view; message.header.set_checksum_body(message.body()); message.header.set_checksum(); // The checksum of this request becomes the parent of our next reply: self.parent = message.header.checksum; log.debug("{}: send_request_for_the_first_time: request={} checksum={}", .{ self.id, message.header.request, message.header.checksum, }); assert(!self.request_timeout.ticking); self.request_timeout.start(); // If our view number is out of date, then the old primary will forward our request. // If the primary is offline, then our request timeout will fire and we will round-robin. self.send_message_to_replica( @as(u8, @intCast(self.view % self.replica_count)), message.base(), ); } }; }
https://raw.githubusercontent.com/tigerbeetle/tigerbeetle/c9363f5ee82bbcee5dfd07bf0566d2b16511b579/src/vsr/client.zig
// // Loop bodies are blocks, which are also expressions. We've seen // how they can be used to evaluate and return values. To further // expand on this concept, it turns out we can also give names to // blocks by applying a 'label': // // my_label: { ... } // // Once you give a block a label, you can use 'break' to exit // from that block. // // outer_block: { // outer block // while (true) { // inner block // break :outer_block; // } // unreachable; // } // // As we've just learned, you can return a value using a break // statement. Does that mean you can return a value from any // labeled block? Yes it does! // // const foo = make_five: { // const five = 1 + 1 + 1 + 1 + 1; // break :make_five five; // }; // // Labels can also be used with loops. Being able to break out of // nested loops at a specific level is one of those things that // you won't use every day, but when the time comes, it's // incredibly convenient. Being able to return a value from an // inner loop is sometimes so handy, it almost feels like cheating // (and can help you avoid creating a lot of temporary variables). // // const bar: u8 = two_loop: while (true) { // while (true) { // break :two_loop 2; // } // } else 0; // // In the above example, the break exits from the outer loop // labeled "two_loop" and returns the value 2. The else clause is // attached to the outer two_loop and would be evaluated if the // loop somehow ended without the break having been called. // // Finally, you can also use block labels with the 'continue' // statement: // // my_while: while (true) { // continue :my_while; // } // const print = @import("std").debug.print; // As mentioned before, we'll soon understand why these two // numbers don't need explicit types. Hang in there! const ingredients = 4; const foods = 4; const Food = struct { name: []const u8, requires: [ingredients]bool, }; // Chili Macaroni Tomato Sauce Cheese // ------------------------------------------------------ // Mac & Cheese x x // Chili Mac x x // Pasta x x // Cheesy Chili x x // ------------------------------------------------------ const menu: [foods]Food = [_]Food{ Food{ .name = "Mac & Cheese", .requires = [ingredients]bool{ false, true, false, true }, }, Food{ .name = "Chili Mac", .requires = [ingredients]bool{ true, true, false, false }, }, Food{ .name = "Pasta", .requires = [ingredients]bool{ false, true, true, false }, }, Food{ .name = "Cheesy Chili", .requires = [ingredients]bool{ true, false, false, true }, }, }; pub fn main() void { // Welcome to Cafeteria USA! Choose your favorite ingredients // and we'll produce a delicious meal. // // Cafeteria Customer Note: Not all ingredient combinations // make a meal. The default meal is macaroni and cheese. // // Software Developer Note: Hard-coding the ingredient // numbers (based on array position) will be fine for our // tiny example, but it would be downright criminal in a real // application! const wanted_ingredients = [_]u8{ 0, 1 }; // Chili, Cheese // Look at each Food on the menu... const meal = food_loop: for (menu) |food| { // Now look at each required ingredient for the Food... for (food.requires, 0..) |required, required_ingredient| { // This ingredient isn't required, so skip it. if (!required) continue; // See if the customer wanted this ingredient. // (Remember that want_it will be the index number of // the ingredient based on its position in the // required ingredient list for each food.) const found = for (wanted_ingredients) |want_it| { if (required_ingredient == want_it) break true; } else false; // We did not find this required ingredient, so we // can't make this Food. Continue the outer loop. if (!found) continue :food_loop; } // If we get this far, the required ingredients were all // wanted for this Food. // // Please return this Food from the loop. break food;} else undefined; // ^ Oops! We forgot to return Mac & Cheese as the default // Food when the requested ingredients aren't found. print("Enjoy your {s}!\n", .{meal.name}); } // Challenge: You can also do away with the 'found' variable in // the inner loop. See if you can figure out how to do that!
https://raw.githubusercontent.com/trungducnguyenvn/Learn-Zig-with-ziglings/2a968a84982048624c91e6708daf4b2beda0fd5a/exercises/063_labels.zig
// --- Day 3: Binary Diagnostic --- // The submarine has been making some odd creaking noises, so you ask it to produce a diagnostic report just in case. // The diagnostic report (your puzzle input) consists of a list of binary numbers which, when decoded properly, can tell you many useful things about the conditions of the submarine. The first parameter to check is the power consumption. // You need to use the binary numbers in the diagnostic report to generate two new binary numbers (called the gamma rate and the epsilon rate). The power consumption can then be found by multiplying the gamma rate by the epsilon rate. // Each bit in the gamma rate can be determined by finding the most common bit in the corresponding position of all numbers in the diagnostic report. For example, given the following diagnostic report: // 00100 // 11110 // 10110 // 10111 // 10101 // 01111 // 00111 // 11100 // 10000 // 11001 // 00010 // 01010 // Considering only the first bit of each number, there are five 0 bits and seven 1 bits. Since the most common bit is 1, the first bit of the gamma rate is 1. // The most common second bit of the numbers in the diagnostic report is 0, so the second bit of the gamma rate is 0. // The most common value of the third, fourth, and fifth bits are 1, 1, and 0, respectively, and so the final three bits of the gamma rate are 110. // So, the gamma rate is the binary number 10110, or 22 in decimal. // The epsilon rate is calculated in a similar way; rather than use the most common bit, the least common bit from each position is used. So, the epsilon rate is 01001, or 9 in decimal. Multiplying the gamma rate (22) by the epsilon rate (9) produces the power consumption, 198. // Use the binary numbers in your diagnostic report to calculate the gamma rate and epsilon rate, then multiply them together. What is the power consumption of the submarine? (Be sure to represent your answer in decimal, not binary.) const std = @import("std"); const input = @embedFile("../input/day3.txt"); pub fn solve() !void { var lines = std.mem.tokenize(u8, input, "\n"); var nums = std.ArrayList(u32).init(std.testing.allocator); defer nums.deinit(); while (lines.next()) |line| { try nums.append(try std.fmt.parseInt(u32, line, 2)); } std.log.info("Day3 \n\tpart 1 -> {}\n\tpart 2 -> {}", .{ part1(nums), part2(nums) }); } fn part1(nums: std.ArrayList(u32)) !u32 { var i: u32 = 2048; var gamma: u32 = 0; var epsilon: u32 = 0; while (i >= 1) : (i /= 2) { var bit = try get_bit_dominant(nums, i); gamma += bit; if (bit == 0) { epsilon += i; } } return gamma * epsilon; } fn get_bit_dominant(nums: std.ArrayList(u32), weight: u32) !u32 { var counter_bit: u32 = 0; var i: u32 = 0; while (i < nums.items.len) : (i += 1) { if (nums.items[i] & weight != 0) { counter_bit += 1; } } if ((nums.items.len - counter_bit) > counter_bit) { return 0; } else { return weight; } } // --- Part Two --- // Next, you should verify the life support rating, which can be determined by multiplying the oxygen generator rating by the CO2 scrubber rating. // Both the oxygen generator rating and the CO2 scrubber rating are values that can be found in your diagnostic report - finding them is the tricky part. Both values are located using a similar process that involves filtering out values until only one remains. Before searching for either rating value, start with the full list of binary numbers from your diagnostic report and consider just the first bit of those numbers. Then: // Keep only numbers selected by the bit criteria for the type of rating value for which you are searching. Discard numbers which do not match the bit criteria. // If you only have one number left, stop; this is the rating value for which you are searching. // Otherwise, repeat the process, considering the next bit to the right. // The bit criteria depends on which type of rating value you want to find: // To find oxygen generator rating, determine the most common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 1 in the position being considered. // To find CO2 scrubber rating, determine the least common value (0 or 1) in the current bit position, and keep only numbers with that bit in that position. If 0 and 1 are equally common, keep values with a 0 in the position being considered. // For example, to determine the oxygen generator rating value using the same example diagnostic report from above: // Start with all 12 numbers and consider only the first bit of each number. There are more 1 bits (7) than 0 bits (5), so keep only the 7 numbers with a 1 in the first position: 11110, 10110, 10111, 10101, 11100, 10000, and 11001. // Then, consider the second bit of the 7 remaining numbers: there are more 0 bits (4) than 1 bits (3), so keep only the 4 numbers with a 0 in the second position: 10110, 10111, 10101, and 10000. // In the third position, three of the four numbers have a 1, so keep those three: 10110, 10111, and 10101. // In the fourth position, two of the three numbers have a 1, so keep those two: 10110 and 10111. // In the fifth position, there are an equal number of 0 bits and 1 bits (one each). So, to find the oxygen generator rating, keep the number with a 1 in that position: 10111. // As there is only one number left, stop; the oxygen generator rating is 10111, or 23 in decimal. // Then, to determine the CO2 scrubber rating value from the same example above: // Start again with all 12 numbers and consider only the first bit of each number. There are fewer 0 bits (5) than 1 bits (7), so keep only the 5 numbers with a 0 in the first position: 00100, 01111, 00111, 00010, and 01010. // Then, consider the second bit of the 5 remaining numbers: there are fewer 1 bits (2) than 0 bits (3), so keep only the 2 numbers with a 1 in the second position: 01111 and 01010. // In the third position, there are an equal number of 0 bits and 1 bits (one each). So, to find the CO2 scrubber rating, keep the number with a 0 in that position: 01010. // As there is only one number left, stop; the CO2 scrubber rating is 01010, or 10 in decimal. // Finally, to find the life support rating, multiply the oxygen generator rating (23) by the CO2 scrubber rating (10) to get 230. // Use the binary numbers in your diagnostic report to calculate the oxygen generator rating and CO2 scrubber rating, then multiply them together. What is the life support rating of the submarine? (Be sure to represent your answer in decimal, not binary.) fn part2(nums: std.ArrayList(u32)) !u32 { var tmp = nums; var i: u32 = 2048; while (i >= 1) : (i /= 2) { tmp = try get_numbers_with_common_bit(tmp, i); if (tmp.items.len == 1) { break; } } var oxygen_generator = tmp.items[0]; i = 2048; var nn = nums; while (i >= 1) : (i /= 2) { nn = try get_numbers_with_fewest_common_bit(nn, i); if (nn.items.len == 1) { break; } } var co2_scrubber: u32 = nn.items[0]; return oxygen_generator * co2_scrubber; } fn get_numbers_with_common_bit(nums: std.ArrayList(u32), weight: u32) !std.ArrayList(u32) { var nums_with_0 = std.ArrayList(u32).init(std.testing.allocator); var nums_with_1 = std.ArrayList(u32).init(std.testing.allocator); var i: u32 = 0; while (i < nums.items.len) : (i += 1) { if (nums.items[i] & weight != 0) { try nums_with_1.append(nums.items[i]); } else { try nums_with_0.append(nums.items[i]); } } if (nums_with_1.items.len >= nums_with_0.items.len) { nums_with_0.deinit(); return nums_with_1; } else { nums_with_1.deinit(); return nums_with_0; } } fn get_numbers_with_fewest_common_bit(nums: std.ArrayList(u32), weight: u32) !std.ArrayList(u32) { var nums_with_0 = std.ArrayList(u32).init(std.testing.allocator); var nums_with_1 = std.ArrayList(u32).init(std.testing.allocator); var i: u32 = 0; while (i < nums.items.len) : (i += 1) { if (nums.items[i] & weight != 0) { try nums_with_1.append(nums.items[i]); } else { try nums_with_0.append(nums.items[i]); } } if (nums_with_0.items.len <= nums_with_1.items.len) { nums_with_1.deinit(); return nums_with_0; } else { nums_with_0.deinit(); return nums_with_1; } }
https://raw.githubusercontent.com/guerinoni/advent-of-code-2021/74ca90b9f37dc3acd7c33f0f1d74704923dedebe/src/day3.zig
const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const arr = try allocator.alloc(usize, 4); allocator.free(arr); allocator.free(arr); std.debug.print("Это никогда не напечатается\n", .{}); }
https://raw.githubusercontent.com/dee0xeed/learning-zig-rus/13b78318628fa85bc1cc8359e74e223ee506e6a9/src/examples/ex-ch06-01.zig
const uart = @import("uart.zig"); const lcd = @import("vid.zig"); const std = @import("std"); extern const _binary_image_bmp_start: u8; const WIDTH: usize = 640; fn show_bmp(p: *u8, start_row: usize, start_col: usize) void { var pp: [*]u8 = undefined; var p_i: usize = @intFromPtr(p); // 指针类型转换需要对齐,指针地址未对齐的话会导致不合法行为 var q: [*]u8 = @ptrFromInt(p_i + 14); q = q + 4; const w: i32 = @as(i32, q[0]) | (@as(i32, q[1]) << 8) | (@as(i32, q[2]) << 16) | (@as(i32, q[3]) << 24); const h: i32 = @as(i32, q[4]) | (@as(i32, q[5]) << 8) | (@as(i32, q[6]) << 16) | (@as(i32, q[7]) << 24); p_i += 54; const rsize: i32 = @divTrunc((3 * w + 3), 4) * 4; p_i += @as(usize, @intCast((h - 1) * rsize)); for (start_row..(start_row + @as(usize, @intCast(h)))) |i| { pp = @ptrFromInt(p_i); for (start_col..(start_col + @as(usize, @intCast(w)))) |j| { const b = pp[0]; const g = pp[1]; const r = pp[2]; const pixel = (@as(i32, b) << 16) | (@as(i32, g) << 8) | @as(i32, r); @as([*]volatile i32, @ptrCast(lcd.fb))[i * WIDTH + j] = pixel; pp += 3; } p_i -= @as(usize, @intCast(rsize)); } var content: [125]u8 = undefined; const message = std.fmt.bufPrint(&content, "\nBMP image height={} width={}\n", .{ h, w, }) catch unreachable; uart.uart1.prints(message); } export fn main() callconv(.C) i32 { lcd.fbuf_init(); while (true) { var p = &_binary_image_bmp_start; show_bmp(p, 0, 0); uart.uart1.prints("enter a key from this UART : "); _ = uart.uart1.getc(); } return 0; }
https://raw.githubusercontent.com/XxChang/rt_embedded_os_zig/87119f411f8179c5593e136d1889643a134019a7/lcd_driver/main.zig
// https://gitlab.com/x86-psABIs/x86-64-ABI/-/jobs/artifacts/master/raw/x86-64-ABI/abi.pdf?job=build // Figure 3.4: Register Usage pub const Context = extern struct { rbx: usize = 0, // 0 r12: usize = 0, // 8 r13: usize = 0, // 16 r14: usize = 0, // 24 r15: usize = 0, // 32 rsp: usize = 0, // 40 rbp: usize = 0, // 48 rip: usize = 0, // 56 const Self = @This(); pub inline fn setStack(self: *Self, sp: usize) void { self.rsp = sp; } };
https://raw.githubusercontent.com/a1393323447/zcoroutine/bd850f7869c61f05c017b77d1692ba1b306ebf4a/src/arch/x86_64/linux/context.zig
const std = @import("std"); const ascii = std.ascii; const mem = std.mem; /// Returns the counts of the words in `s`. /// Caller owns the returned memory. pub fn countWords(allocator: mem.Allocator, s: []const u8) !std.StringHashMap(u32) { var word_count_map = std.StringHashMap(u32).init(allocator); errdefer freeKeysAndDeinit(&word_count_map); var word_builder = std.ArrayList(u8).init(allocator); defer word_builder.deinit(); for (s, 0..) |c, i| { const end_word_flag = switch (c) { ' ', '\n', '\t', '\r', ',', '.', '?', '!', '&', '@', '$', '%', '^', ':', '"' => true, else => blk: { try word_builder.append(ascii.toLower(c)); break :blk if (i == s.len - 1) true else false; }, }; if (end_word_flag and word_builder.items.len > 0) { const word_raw = word_builder.items; const start_with_apos = word_raw[0] == '\''; const end_with_apos = word_raw[word_raw.len - 1] == '\''; const begin: usize = if (start_with_apos) 1 else 0; const end: usize = if (end_with_apos) word_raw.len - 1 else word_raw.len; if (begin >= end) continue; const word = word_raw[begin..end]; if (word_count_map.get(word)) |curr_count| { try word_count_map.put(word, curr_count + 1); } else { const copied_word = try allocator.dupe(u8, word); errdefer allocator.free(copied_word); try word_count_map.put(copied_word, 1); } word_builder.clearAndFree(); } } return word_count_map; } fn freeKeysAndDeinit(self: *std.StringHashMap(u32)) void { var iter = self.keyIterator(); while (iter.next()) |key_ptr| { self.allocator.free(key_ptr.*); } self.deinit(); }
https://raw.githubusercontent.com/binhtran432k/exercism-learning/7f52068bf630aa54226acc132464c9035669b4c4/zig/word-count/word_count.zig
const std = @import("std"); fn pkgPath(comptime out: []const u8) std.build.FileSource { const outpath = comptime std.fs.path.dirname(@src().file).? ++ std.fs.path.sep_str ++ out; return .{ .path = outpath }; } 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 example0 = b.addExecutable("example-0", "src/example-0.zig"); example0.linkSystemLibrary("gtk4"); example0.linkLibC(); example0.setTarget(target); example0.setBuildMode(mode); example0.install(); example0.addPackage(.{ .name = "gtk", .source = pkgPath("libs/gtk.zig"), }); const example1 = b.addExecutable("example-1", "src/example-1.zig"); example1.linkSystemLibrary("gtk4"); example1.linkLibC(); example1.setTarget(target); example1.setBuildMode(mode); example1.install(); example1.addPackage(.{ .name = "gtk", .source = pkgPath("libs/gtk.zig"), }); const example2 = b.addExecutable("example-2", "src/example-2.zig"); example2.linkSystemLibrary("gtk4"); example2.linkLibC(); example2.setTarget(target); example2.setBuildMode(mode); example2.install(); example2.addPackage(.{ .name = "gtk", .source = pkgPath("libs/gtk.zig"), }); const example3 = b.addExecutable("example-3", "src/example-3.zig"); example3.linkSystemLibrary("gtk4"); example3.linkLibC(); example3.setTarget(target); example3.setBuildMode(mode); example3.install(); example3.addPackage(.{ .name = "gtk", .source = pkgPath("libs/gtk.zig"), }); const example4 = b.addExecutable("example-4", "src/example-4.zig"); example4.linkSystemLibrary("gtk4"); example4.linkLibC(); example4.setTarget(target); example4.setBuildMode(mode); example4.install(); example4.addPackage(.{ .name = "gtk", .source = pkgPath("libs/gtk.zig"), }); const run_cmd_0 = example0.run(); run_cmd_0.step.dependOn(b.getInstallStep()); const run_cmd_1 = example1.run(); run_cmd_1.step.dependOn(b.getInstallStep()); const run_cmd_2 = example2.run(); run_cmd_2.step.dependOn(b.getInstallStep()); //const run_cmd_3 = example3.run(); //run_cmd_3.step.dependOn(b.getInstallStep()); //const run_cmd_4 = example4.run(); //run_cmd_4.step.dependOn(b.getInstallStep()); //const run_step_0 = b.step("example0", "Run example 0"); //run_step_0.dependOn(&run_cmd_0.step); //const run_step_1 = b.step("example1", "Run example 1"); //run_step_1.dependOn(&run_cmd_1.step); //const run_step_2 = b.step("example2", "Run example 2"); //run_step_2.dependOn(&run_cmd_2.step); //const run_step_3 = b.step("example3", "Run example 3"); //run_step_3.dependOn(&run_cmd_3.step); //const run_step_4 = b.step("example4", "Run example 4"); //run_step_4.dependOn(&run_cmd_4.step); }
https://raw.githubusercontent.com/binarycraft007/gtk-examples-zig/2deafc01cbdede0abb8e13f8c1eda973a46aa21f/build.zig
const std = @import("std"); const assert = std.debug.assert; const wren = @import("./wren.zig"); const Vm = @import("./vm.zig").Vm; const Configuration = @import("./vm.zig").Configuration; const ErrorType = @import("./vm.zig").ErrorType; const WrenError = @import("./error.zig").WrenError; const EmptyUserData = struct {}; const testing = std.testing; /// Handle for method call receivers. Pretty much just a fancy wrapper around wrenGetVariable/WrenHandle. pub const Receiver = struct { const Self = @This(); vm: *Vm, module: []const u8, handle: *wren.Handle, pub fn init(vm: *Vm, module: []const u8, name: []const u8) Self { const slot_index = 0; vm.ensureSlots(1); vm.getVariable(module, name, slot_index); const handle = vm.getSlot(*wren.Handle, 0); return Self{ .vm = vm, .module = module, .handle = handle }; } pub fn deinit(self: Self) void { wren.releaseHandle(self.vm.vm, self.handle); } pub fn setSlot(self: Self, slot_index: u32) void { self.vm.setSlotHandle(0, self.handle); } }; fn printError(vm: *Vm, error_type: ErrorType, module: ?[]const u8, line: ?u32, message: []const u8) void { std.debug.print("error_type={}, module={}, line={}, message={}\n", .{ error_type, module, line, message }); } fn print(vm: *Vm, msg: []const u8) void { std.debug.print("{}", .{msg}); } test "can create receiver" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); try vm.interpret("test", \\class Foo { \\} ); _ = vm.makeReceiver("test", "Foo"); } /// Handle for methods of any kind. Even free-standing functions in wren are just calling `call()` on a function object. pub const CallHandle = struct { const Self = @This(); vm: *Vm, handle: *wren.Handle, pub fn init(vm: *Vm, method: []const u8) Self { const slot_index = 0; vm.ensureSlots(1); const handle = wren.makeCallHandle(vm.vm, @ptrCast([*c]const u8, method)); assert(handle != null); return Self{ .vm = vm, .handle = @ptrCast(*wren.Handle, handle), }; } pub fn deinit(self: Self) void { wren.releaseHandle(self.vm.vm, self.handle); } pub fn call(self: Self) !void { const res = wren.call(self.vm.vm, self.handle); if (res == .WREN_RESULT_COMPILE_ERROR) { return WrenError.CompileError; } if (res == .WREN_RESULT_RUNTIME_ERROR) { return WrenError.RuntimeError; } } }; pub fn Method(comptime Ret: anytype, comptime Args: anytype) type { if (@typeInfo(@TypeOf(Args)) != .Struct or (@typeInfo(@TypeOf(Args)) == .Struct and !@typeInfo(@TypeOf(Args)).Struct.is_tuple)) { @compileError("call argument types must be passed as a tuple"); } return struct { const Self = @This(); receiver: Receiver, call_handle: CallHandle, pub fn init(receiver: Receiver, call_handle: CallHandle) Self { return Self{ .receiver = receiver, .call_handle = call_handle }; } pub fn call(self: Self, args: anytype) !Ret { if (@typeInfo(@TypeOf(args)) != .Struct or (@typeInfo(@TypeOf(args)) == .Struct and !@typeInfo(@TypeOf(args)).Struct.is_tuple)) { @compileError("call arguments must be passed as a tuple"); } assert(args.len == Args.len); const vm = self.receiver.vm; vm.ensureSlots(Args.len + 1); self.receiver.setSlot(0); comptime var slot_index: u32 = 1; inline for (Args) |Arg| { vm.setSlot(slot_index, args[slot_index - 1]); slot_index += 1; } try self.call_handle.call(); if (Ret != void) { return vm.getSlot(Ret, 0); } } }; } test "call a free function" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("test", \\var add = Fn.new { |a, b| \\ return a + b \\} ); const receiver = vm.makeReceiver("test", "add"); defer receiver.deinit(); const call_handle = vm.makeCallHandle("call(_,_)"); defer call_handle.deinit(); const method = Method(i32, .{ i32, i32 }).init(receiver, call_handle); testing.expectEqual(@as(i32, 42), try method.call(.{ 23, 19 })); } test "call a static method" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("test", \\class Foo { \\ static test() { \\ return "hello" \\ } \\} ); const receiver = vm.makeReceiver("test", "Foo"); defer receiver.deinit(); const call_handle = vm.makeCallHandle("test()"); defer call_handle.deinit(); const method = Method([]const u8, .{}).init(receiver, call_handle); testing.expectEqualStrings("hello", try method.call(.{})); } test "call an instance method" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("test", \\class Multiplier { \\ construct new(n) { \\ _n = n \\ } \\ n=(n) { \\ _n = n \\ } \\ *(m) { \\ return _n * m \\ } \\ formatted(m) { \\ return "%(_n) * %(m) = %(this * m)" \\ } \\} \\ \\var mult = Multiplier.new(3) ); const receiver = vm.makeReceiver("test", "mult"); defer receiver.deinit(); const op_times_sig = vm.makeCallHandle("*(_)"); defer op_times_sig.deinit(); const op_times = Method(i32, .{i32}).init(receiver, op_times_sig); testing.expectEqual(@as(i32, 9), try op_times.call(.{3})); const setter_sig = vm.makeCallHandle("n=(_)"); defer setter_sig.deinit(); const setter = Method(void, .{i32}).init(receiver, setter_sig); try setter.call(.{5}); const formatted_sig = vm.makeCallHandle("formatted(_)"); defer formatted_sig.deinit(); const formatted = Method([]const u8, .{f32}).init(receiver, formatted_sig); testing.expectEqualStrings("5 * 1.1 = 5.5", try formatted.call(.{1.1})); } test "non-comptime identifiers" { var config = Configuration{}; config.errorFn = printError; config.writeFn = print; var vm: Vm = undefined; try config.newVmInPlace(EmptyUserData, &vm, null); defer vm.deinit(); try vm.interpret("test", \\class Foo { \\ static test() { \\ return "hello" \\ } \\} ); var identifier: [4]u8 = [_]u8{ 'F', 'o', 'o', 0 }; var id = identifier[0..]; const receiver = vm.makeReceiver("test", id); defer receiver.deinit(); var signature = "test()"; var sig = signature[0..]; const call_handle = vm.makeCallHandle(sig); defer call_handle.deinit(); const method = Method([]const u8, .{}).init(receiver, call_handle); testing.expectEqualStrings("hello", try method.call(.{})); }
https://raw.githubusercontent.com/koljakube/zapata/a9d2aea5144cdd0550a4ea5e051084902ff8ac85/src/zapata/call.zig
const std = @import("std"); const seika = @cImport({ @cInclude("seika/seika.h"); }); const input = @cImport({ @cInclude("seika/input/input.h"); }); pub fn main() void { const success = seika.ska_init_all("Zig Window", 800, 600, 800, 600); if (!success) { std.debug.print("Failed to initialize seika\n", .{}); return; } while (seika.ska_is_running()) { seika.ska_update(); // Exit when escape is pressed if (input.ska_input_is_key_just_pressed(input.SkaInputKey_KEYBOARD_ESCAPE, 0)) { break; } seika.ska_window_render(); } seika.ska_shutdown_all(); }
https://raw.githubusercontent.com/Chukobyte/seika-examples/ae68bdbbc32dfb075a6dfec37ee1c65b5baa8798/examples/zig_example/src/main.zig
const std = @import("std"); const all_targets = &[_]std.zig.CrossTarget{ .{ .os_tag = .macos, .cpu_arch = .aarch64 }, .{ .os_tag = .macos, .cpu_arch = .x86_64 }, .{ .os_tag = .linux, .cpu_arch = .aarch64 }, .{ .os_tag = .linux, .cpu_arch = .i386 }, .{ .os_tag = .linux, .cpu_arch = .x86_64 }, .{ .os_tag = .windows, .cpu_arch = .aarch64 }, // .{ .os_tag = .windows, .cpu_arch = .i386 }, .{ .os_tag = .windows, .cpu_arch = .x86_64 }, }; pub fn build(builder: *std.build.Builder) !void { const bin_target = builder.standardTargetOptions(.{}); const bin_mode = builder.standardReleaseOptions(); const strip_bin = builder.option(bool, "strip", "Whether to strip any resulting binaries.") orelse (bin_mode == .ReleaseFast); const all_step = builder.step("all", "Build for all targets."); inline for (all_targets) |target| { const target_bin = builder.addExecutable(std.fmt.comptimePrint("ipsum_{s}_{s}", .{ @tagName(target.cpu_arch.?), @tagName(target.os_tag.?) }), "src/main.zig"); target_bin.strip = strip_bin; target_bin.linkLibC(); target_bin.setBuildMode(bin_mode); target_bin.setTarget(target); all_step.dependOn(&builder.addInstallArtifact(target_bin).step); } const bin = builder.addExecutable("ipsum", "src/main.zig"); bin.strip = strip_bin; bin.linkLibC(); bin.setBuildMode(bin_mode); bin.setTarget(bin_target); bin.install(); }
https://raw.githubusercontent.com/sepruko/lorem-zigsum/f5413712bc23b3c76547b6d7d27c6cea3da48875/build.zig
// rabbit.zig // Rabbit Cipher pub const rabbit_instance = struct { x: [8]u32, c: [8]u32, carry: u32, x0: [4]u8, x1: [4]u8, x2: [4]u8, x3: [4]u8, x4: [4]u8, x5: [4]u8, x6: [4]u8, x7: [4]u8, }; // Left rotation of a 32-bit unsigned integer fn rabbit_rotl(x: u32, rot: u32) u32 { return (x << rot) | (x >> (32 - rot)); } // Square a 32-bit unsigned integer to obtain the 64-bit result and return // the upper 32 bits XOR the lower 32 bits fn rabbit_g_func(x: u32) u32 { // Temporary variables var a: u32 = undefined; var b: u32 = undefined; var h: u32 = undefined; var l: u32 = undefined; // Construct high and low argument for squaring a = x & 0xFFFF; b = x >> 16; // Calculate high and low result of squaring h = ((((a * a) >> 17) + (a * b)) >> 15) + (b * b); l = x * x; // Return high XOR low return h ^ l; } // Calculate the next internal state fn rabbit_next_state(p_instance: *rabbit_instance) void { // Temporary variables var g: [8]u32 = undefined; var c_old: [8]u32 = undefined; var i: u8 = 0; // Save old counter values i = 0; while (i < 8) : (i += 1) { c_old[i] = p_instance.c[i]; } // Calculate new counter values p_instance.c[0] += 0x4D34D34D + p_instance.carry; p_instance.c[1] += 0xD34D34D3 + (p_instance.c[0] < c_old[0]); p_instance.c[2] += 0x34D34D34 + (p_instance.c[1] < c_old[1]); p_instance.c[3] += 0x4D34D34D + (p_instance.c[2] < c_old[2]); p_instance.c[4] += 0xD34D34D3 + (p_instance.c[3] < c_old[3]); p_instance.c[5] += 0x34D34D34 + (p_instance.c[4] < c_old[4]); p_instance.c[6] += 0x4D34D34D + (p_instance.c[5] < c_old[5]); p_instance.c[7] += 0xD34D34D3 + (p_instance.c[6] < c_old[6]); p_instance.carry = (p_instance.c[7] < c_old[7]); // Calculate the g-functions i = 0; while (i < 8) : (i += 1) { g[i] = rabbit_g_func(p_instance.x[i] + p_instance.c[i]); } // Calculate new state values p_instance.x[0] = g[0] + rabbit_rotl(g[7], 16) + rabbit_rotl(g[6], 16); p_instance.x[1] = g[1] + rabbit_rotl(g[0], 8) + g[7]; p_instance.x[2] = g[2] + rabbit_rotl(g[1], 16) + rabbit_rotl(g[0], 16); p_instance.x[3] = g[3] + rabbit_rotl(g[2], 8) + g[1]; p_instance.x[4] = g[4] + rabbit_rotl(g[3], 16) + rabbit_rotl(g[2], 16); p_instance.x[5] = g[5] + rabbit_rotl(g[4], 8) + g[3]; p_instance.x[6] = g[6] + rabbit_rotl(g[5], 16) + rabbit_rotl(g[4], 16); p_instance.x[7] = g[7] + rabbit_rotl(g[6], 8) + g[5]; } // Initialize the cipher instance (*p_instance) as a function of the // key (p_key) pub fn rabbit_key_setup(p_instance: *rabbit_instance, p_key: []u8) !i32 { // Return error if the key size is not 16 bytes if (p_key.len != 16) { return -1; } // var k0_mask = ((1 << 5) - 1) << 0; // var k1_mask = ((1 << 5) - 1) << 4; // var k2_mask = ((1 << 5) - 1) << 8; // var k3_mask = ((1 << 5) - 1) << 12; // Temporary variables --> Generate four subkeys var k0: *[4]u8 = p_key[0..4]; var k1: *[4]u8 = p_key[4..8]; var k2: *[4]u8 = p_key[8..12]; var k3: *[4]u8 = p_key[12..16]; var i: u8 = 0; // Generate initial state variables p_instance.x0 = k0.*; p_instance.x2 = k1.*; p_instance.x4 = k2.*; p_instance.x6 = k3.*; p_instance.x1 = (k3.* << 16) | (k2.* >> 16); p_instance.x3 = (k0.* << 16) | (k3.* >> 16); p_instance.x5 = (k1.* << 16) | (k0.* >> 16); p_instance.x7 = (k2.* << 16) | (k1.* >> 16); // Generate initial counter values p_instance.c[0] = rabbit_rotl(k2, 16); p_instance.c[2] = rabbit_rotl(k3, 16); p_instance.c[4] = rabbit_rotl(k0, 16); p_instance.c[6] = rabbit_rotl(k1, 16); p_instance.c[1] = (k0 & 0xFFFF0000) | (k1 & 0xFFFF); p_instance.c[3] = (k1 & 0xFFFF0000) | (k2 & 0xFFFF); p_instance.c[5] = (k2 & 0xFFFF0000) | (k3 & 0xFFFF); p_instance.c[7] = (k3 & 0xFFFF0000) | (k0 & 0xFFFF); // Clear carry bit p_instance.carry = 0; // Iterate the system four times i = 0; while (i < 4) : (i += 1) { rabbit_next_state(p_instance); } // Modify the counters i = 0; while (i < 8) : (i += 1) { p_instance.c[i] ^= p_instance.x[(i + 4) & 0x7]; } // Return success return 0; } // Initialize the cipher instance (*p_instance) as a function of the // IV (*p_iv) and the master instance (*p_master_instance) pub fn rabbit_iv_setup(p_master_instance: *rabbit_instance, p_instance: *rabbit_instance, p_iv: [*]const u8, iv_size: usize) i32 { // Temporary variables var i_0: u32 = undefined; var i_1: u32 = undefined; var i_2: u32 = undefined; var i_3: u32 = undefined; var i: u8 = 0; // Return error if the IV size is not 8 bytes if (iv_size != 8) { return -1; } // Generate four subvectors i_0 = p_iv[0..4]; i_2 = p_iv[4..8]; i_1 = (i_0 >> 16) | (i_2 & 0xFFFF0000); i_3 = (i_2 << 16) | (i_0 & 0x0000FFFF); // Modify counter values p_instance.c[0] = p_master_instance.c[0] ^ i_0; p_instance.c[1] = p_master_instance.c[1] ^ i_1; p_instance.c[2] = p_master_instance.c[2] ^ i_2; p_instance.c[3] = p_master_instance.c[3] ^ i_3; p_instance.c[4] = p_master_instance.c[4] ^ i_0; p_instance.c[5] = p_master_instance.c[5] ^ i_1; p_instance.c[6] = p_master_instance.c[6] ^ i_2; p_instance.c[7] = p_master_instance.c[7] ^ i_3; // Copy internal state values i = 0; while (i < 8) : (i += 1) { p_instance.x[i] = p_master_instance.x[i]; } p_instance.carry = p_master_instance.carry; // Iterate the system four times i = 0; while (i < 4) : (i += 1) { rabbit_next_state(p_instance); } // Return success return 0; } // Encrypt or decrypt data pub fn rabbit_cipher(p_instance: *rabbit_instance, p_src: [*]const u8, p_dest: [*]u8, data_size: usize) i32 { // Temporary variables var i: usize = 0; // Return error if the size of the data to encrypt is // not a multiple of 16 if (data_size % 16 != 0) { return -1; } i = 0; while (i < data_size) : (i += 16) { // Iterate the system rabbit_next_state(p_instance); // Encrypt 16 bytes of data p_dest[i] = p_src[i] ^ p_instance.x[0] ^ (p_instance.x[5] >> 16) ^ (p_instance.x[3] << 16); p_dest[i + 1] = p_src[i + 1] ^ p_instance.x[2] ^ (p_instance.x[7] >> 16) ^ (p_instance.x[5] << 16); p_dest[i + 2] = p_src[i + 2] ^ p_instance.x[4] ^ (p_instance.x[1] >> 16) ^ (p_instance.x[7] << 16); p_dest[i + 3] = p_src[i + 3] ^ p_instance.x[6] ^ (p_instance.x[3] >> 16) ^ (p_instance.x[1] << 16); p_dest[i + 4] = p_src[i + 4] ^ p_instance.x[0] ^ (p_instance.x[5] >> 16) ^ (p_instance.x[3] << 16); p_dest[i + 5] = p_src[i + 5] ^ p_instance.x[2] ^ (p_instance.x[7] >> 16) ^ (p_instance.x[5] << 16); p_dest[i + 6] = p_src[i + 6] ^ p_instance.x[4] ^ (p_instance.x[1] >> 16) ^ (p_instance.x[7] << 16); p_dest[i + 7] = p_src[i + 7] ^ p_instance.x[6] ^ (p_instance.x[3] >> 16) ^ (p_instance.x[1] << 16); p_dest[i + 8] = p_src[i + 8] ^ p_instance.x[0] ^ (p_instance.x[5] >> 16) ^ (p_instance.x[3] << 16); p_dest[i + 9] = p_src[i + 9] ^ p_instance.x[2] ^ (p_instance.x[7] >> 16) ^ (p_instance.x[5] << 16); p_dest[i + 10] = p_src[i + 10] ^ p_instance.x[4] ^ (p_instance.x[1] >> 16) ^ (p_instance.x[7] << 16); p_dest[i + 11] = p_src[i + 11] ^ p_instance.x[6] ^ (p_instance.x[3] >> 16) ^ (p_instance.x[1] << 16); p_dest[i + 12] = p_src[i + 12] ^ p_instance.x[0] ^ (p_instance.x[5] >> 16) ^ (p_instance.x[3] << 16); p_dest[i + 13] = p_src[i + 13] ^ p_instance.x[2] ^ (p_instance.x[7] >> 16) ^ (p_instance.x[5] << 16); p_dest[i + 14] = p_src[i + 14] ^ p_instance.x[4] ^ (p_instance.x[1] >> 16) ^ (p_instance.x[7] << 16); p_dest[i + 15] = p_src[i + 15] ^ p_instance.x[6] ^ (p_instance.x[3] >> 16) ^ (p_instance.x[1] << 16); } // Return success return 0; }
https://raw.githubusercontent.com/BoundlessCarrot/thesis/4b9442d95ef8bda3d0c1e25cd16ac54dd465ffc4/Zig/rabbit_chatgpt.zig
const std = @import("std"); const fmt = std.fmt; /// A unique Discord ID which is chronologically sortable; /// contains a timestamp and some other metadata pub const Snowflake = []const u8; const Allocator = std.mem.Allocator; const allocPrint = fmt.allocPrint; // Discord's "beginning of the universe", the first second of 2015 pub const DISCORD_EPOCH = 1420070400000; /// converts a snowflake to a Discord timestamp (milliseconds from the first second of 2015) pub fn snowflakeToDiscordTimestamp(snowflake: Snowflake) !i64 { return try fmt.parseInt(i64, snowflake, 10) >> 22; } /// converts a snowflake to a UNIX timestamp (milliseconds from Jan 1, 1970 UTC) pub fn snowflakeToTimestamp(snowflake: Snowflake) !i64 { return try snowflakeToDiscordTimestamp(snowflake) + DISCORD_EPOCH; } /// converts a UNIX timestamp (im milliseconds) to a snowflake useful for pagination pub fn timestampToSnowflake(allocator: Allocator, timestamp: i64) !Snowflake { return allocPrint(allocator, "{d}", .{(timestamp - DISCORD_EPOCH) << 22}); } pub fn snowflakeToUserMention(allocator: Allocator, snowflake: Snowflake) ![]u8 { return allocPrint(allocator, "<@{s}>", .{snowflake}); } pub fn snowflakeToRoleMention(allocator: Allocator, snowflake: Snowflake) ![]u8 { return allocPrint(allocator, "<@&{s}>", .{snowflake}); } pub fn snowflakeToChannelMention(allocator: Allocator, snowflake: i64) ![]u8 { return allocPrint(allocator, "<#{d}>", .{snowflake}); } test "timestampFromSnowflake" { try std.testing.expect(1694531276785 == try snowflakeToTimestamp("1151172353343094815")); }
https://raw.githubusercontent.com/imkunet/ziggycord/dfb3a679f7f503fd6c58d57b53ae8fdfc2e1b25b/src/ziggycord/snowflake.zig
const std = @import("std"); const c = @cImport({ @cInclude("time.h"); // For `strftime`, `localtime_r`. }); pub const std_options = .{ .log_level = .info, }; pub const NetMessageKind = enum(u8) { MotionDetected, MotionStopped }; pub const NetMessage = packed struct { kind: NetMessageKind, duration_ms: i56, timestamp_ms: i64, }; const VIDEO_FILE_DURATION_SECONDS = 1 * std.time.s_per_min; const CLEANER_FREQUENCY_SECONDS = 1 * std.time.s_per_min; const VIDEO_FILE_MAX_RETAIN_DURATION_SECONDS = 7 * std.time.s_per_day; const VLC_UDP_PACKET_SIZE = 1316; const Viewer = struct { socket: std.posix.socket_t, need_chunking: bool, address: std.net.Address, }; const VIEWERS_COUNT = 3; const Viewers = [VIEWERS_COUNT]Viewer; var VIEWERS = [VIEWERS_COUNT]Viewer{ Viewer{ .address = std.net.Address.parseIp4("100.64.152.16", 12346) catch unreachable, .need_chunking = true, .socket = undefined, }, // iphone Viewer{ .address = std.net.Address.parseIp4("100.117.112.54", 12346) catch unreachable, .need_chunking = true, .socket = undefined, }, // ipad Viewer{ .address = std.net.Address.parseIp4("100.86.75.91", 12346) catch unreachable, .need_chunking = false, .socket = undefined, }, // laptop }; fn handle_tcp_connection_for_incoming_events(connection: *std.net.Server.Connection, event_file: *std.fs.File) !void { var reader = std.io.bufferedReader(connection.stream.reader()); while (true) { var read_buffer_event = [_]u8{0} ** @sizeOf(NetMessage); const n_read = try reader.read(&read_buffer_event); if (n_read < @sizeOf(NetMessage)) { std.log.debug("tcp read={} client likely closed the connection", .{n_read}); std.process.exit(0); } std.debug.assert(n_read == @sizeOf(NetMessage)); const message: NetMessage = std.mem.bytesToValue(NetMessage, &read_buffer_event); std.log.info("event {}", .{message}); var date: [256:0]u8 = undefined; const date_str = fill_string_from_timestamp_ms(message.timestamp_ms, &date); const writer = event_file.writer(); try std.fmt.format(writer, "{s} {}\n", .{ date_str, message.duration_ms }); } } // TODO: Should it be in another thread/process? fn broadcast_video_data_to_viewers(data: []u8) void { for (&VIEWERS) |*viewer| viewer_send: { // Why we cannot simply recv & send the same data in one go: // VLC is a viewer and only wants UDP packets smaller or equal in size to `VLC_UDP_PACKET_SIZE`. // So we have to potentially chunk one UDP packet into multiple smaller ones. const chunk_size = if (viewer.need_chunking) VLC_UDP_PACKET_SIZE else data.len; var i: usize = 0; while (i < data.len) { // Do not go past the end. const chunk_end = std.math.clamp(i + chunk_size, 0, data.len); if (std.posix.send(viewer.socket, data[i..chunk_end], 0)) |n_sent| { i += n_sent; } else |err| { std.log.debug("failed to write to viewer {}", .{err}); break :viewer_send; // Skip this problematic viewer. } } std.debug.assert(i >= data.len); } } fn handle_video_data_udp_packet(in: std.posix.socket_t, video_file: std.fs.File) void { var read_buffer = [_]u8{0} ** (1 << 16); // Max UDP packet size. Read as much as possible. if (std.posix.read(in, &read_buffer)) |n_read| { std.log.debug("udp read={}", .{n_read}); video_file.writeAll(read_buffer[0..n_read]) catch |err| { std.log.err("failed to write all to file {}", .{err}); }; broadcast_video_data_to_viewers(read_buffer[0..n_read]); } else |err| { std.log.err("failed to read udp {}", .{err}); } } fn create_video_file() !std.fs.File { const now = std.time.milliTimestamp(); var date: [256:0]u8 = undefined; const date_str = fill_string_from_timestamp_ms(now, &date); const file = try std.fs.cwd().createFileZ(date_str, .{ .read = true }); try file.seekFromEnd(0); std.log.info("new video file {s}", .{date}); return file; } fn switch_to_new_video_file(fd: i32, video_file: *std.fs.File) !void { // Read & ignore the timer value. var read_buffer = [_]u8{0} ** 8; std.debug.assert(std.posix.read(fd, &read_buffer) catch 0 == 8); video_file.*.close(); video_file.* = try create_video_file(); } // TODO: For multiple cameras we need to identify which stream it is. // Perhaps from the mpegts metadata? fn listen_udp_for_incoming_video_data() !void { const socket = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0); try std.posix.setsockopt(socket, std.posix.SOL.SOCKET, std.posix.SO.REUSEPORT, std.mem.sliceAsBytes(&[1]u32{1})); try std.posix.setsockopt(socket, std.posix.SOL.SOCKET, std.posix.SO.REUSEADDR, std.mem.sliceAsBytes(&[1]u32{1})); const address = std.net.Address.parseIp4("0.0.0.0", 12345) catch unreachable; try std.posix.bind(socket, &address.any, address.getOsSockLen()); for (&VIEWERS) |*viewer| { viewer.socket = try std.posix.socket(std.posix.AF.INET, std.posix.SOCK.DGRAM, 0); try std.posix.connect(viewer.socket, &viewer.address.any, viewer.address.getOsSockLen()); } var video_file = try create_video_file(); const timer_new_video_file = try std.posix.timerfd_create(std.posix.CLOCK.MONOTONIC, .{}); try std.posix.timerfd_settime(timer_new_video_file, .{}, &.{ .it_value = .{ .tv_sec = VIDEO_FILE_DURATION_SECONDS, .tv_nsec = 0 }, .it_interval = .{ .tv_sec = VIDEO_FILE_DURATION_SECONDS, .tv_nsec = 0 }, }, null); var poll_fds = [2]std.posix.pollfd{ .{ .fd = socket, .events = std.posix.POLL.IN, .revents = 0, }, .{ .fd = timer_new_video_file, .events = std.posix.POLL.IN, .revents = 0, } }; while (true) { _ = std.posix.poll(&poll_fds, -1) catch |err| { std.log.err("poll error {}", .{err}); // All errors here are unrecoverable so it's better to simply exit. std.process.exit(1); }; // TODO: Handle `POLL.ERR` ? if ((poll_fds[0].revents & std.posix.POLL.IN) != 0) { handle_video_data_udp_packet(poll_fds[0].fd, video_file); } else if ((poll_fds[1].revents & std.posix.POLL.IN) != 0) { try switch_to_new_video_file(poll_fds[1].fd, &video_file); } } } fn listen_tcp_for_incoming_events() !void { var event_file = try std.fs.cwd().createFile("events.txt", .{}); try event_file.seekFromEnd(0); const address = std.net.Address.parseIp4("0.0.0.0", 12345) catch unreachable; var server = try std.net.Address.listen(address, .{ .reuse_address = true }); while (true) { var connection = try server.accept(); const pid = try std.posix.fork(); if (pid > 0) { // Parent. continue; } // Child try handle_tcp_connection_for_incoming_events(&connection, &event_file); } } fn run_delete_old_video_files_forever() !void { const dir = try std.fs.cwd().openDir(".", .{ .iterate = true }); while (true) { delete_old_video_files(dir); std.time.sleep(CLEANER_FREQUENCY_SECONDS * std.time.ns_per_s); } } fn delete_old_video_file(name: []const u8, now: i128) !void { const stat = std.fs.cwd().statFile(name) catch |err| { std.log.err("failed to stat file: {s} {}", .{ name, err }); return err; }; const elapsed_seconds = @divFloor((now - stat.mtime), std.time.ns_per_s); if (elapsed_seconds < VIDEO_FILE_MAX_RETAIN_DURATION_SECONDS) return; std.fs.cwd().deleteFile(name) catch |err| { std.log.err("failed to delete file: {s} {}", .{ name, err }); }; std.log.info("deleted {s} {}", .{ name, elapsed_seconds }); } fn delete_old_video_files(dir: std.fs.Dir) void { var it = dir.iterate(); const now_ns = std.time.nanoTimestamp(); while (it.next()) |entry_opt| { if (entry_opt) |entry| { // Skip non-video files. if (entry.kind != .file) continue; if (!std.mem.startsWith(u8, entry.name, "2")) continue; delete_old_video_file(entry.name, now_ns) catch continue; } else break; // End of directory. } else |err| { std.log.err("failed to iterate over directory entries: {}", .{err}); } } fn fill_string_from_timestamp_ms(timestamp_ms: i64, out: *[256:0]u8) [:0]u8 { const timestamp_seconds: i64 = @divFloor(timestamp_ms, 1000); var time: c.struct_tm = undefined; _ = c.localtime_r(&@as(c.time_t, timestamp_seconds), &time); const date_c: [*c]u8 = @as([*c]u8, @ptrCast(@alignCast(out))); const res = c.strftime(date_c, 256, "%Y-%m-%d %H:%M:%S", @as([*c]const c.struct_tm, &time)); std.debug.assert(res > 0); return out.*[0..res :0]; } pub fn main() !void { std.log.info("viewers {any}", .{VIEWERS}); var listen_udp_for_incoming_video_data_thread = try std.Thread.spawn(.{}, listen_udp_for_incoming_video_data, .{}); try listen_udp_for_incoming_video_data_thread.setName("incoming_video"); var run_delete_old_video_files_forever_thread = try std.Thread.spawn(.{}, run_delete_old_video_files_forever, .{}); try run_delete_old_video_files_forever_thread.setName("delete_old"); try listen_tcp_for_incoming_events(); } test "fill_string_from_timestamp_ms" { const timestamp: i64 = 1_716_902_774_000; var res: [256:0]u8 = undefined; const str = fill_string_from_timestamp_ms(timestamp, &res); std.debug.print("{s}", .{str}); try std.testing.expect(std.mem.eql(u8, "2024-05-28 15:26:14", str)); }
https://raw.githubusercontent.com/gaultier/camera-center/274a41f700c9f98aea284f231da055e8bf636881/server/src/main.zig
const vm = @import("./machine.zig"); pub fn main() !void { const program = [_]u8{ 0x01, 0x01, 0x00, 0x00, // ensure that register 1 is empty 0x01, 0x00, 0x00, 0x48, // input 'H' in register 0 0x02, 0x01, 0x00, 0x00, // put 'H' on heap 0x05, 0x01, 0x00, 0x00, // increment register 1 0x01, 0x00, 0x00, 0x65, // input 'e' in register 0 0x02, 0x01, 0x00, 0x00, // put 'e' on heap 0x05, 0x01, 0x00, 0x00, // increment register 1 0x01, 0x00, 0x00, 0x6C, // input 'l' in register 0 0x02, 0x01, 0x00, 0x00, // put 'l' on heap 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'l' on heap 0x01, 0x00, 0x00, 0x6f, // input 'o' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'o' on heap 0x01, 0x00, 0x00, 0x20, // input ' ' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put ' ' on heap 0x01, 0x00, 0x00, 0x57, // input 'W' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'W' on heap 0x01, 0x00, 0x00, 0x6f, // input 'o' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'o' on heap 0x01, 0x00, 0x00, 0x72, // input 'r' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'r' on heap 0x01, 0x00, 0x00, 0x6c, // input 'l' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'l' on heap 0x01, 0x00, 0x00, 0x64, // input 'd' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'd' on heap 0x01, 0x00, 0x00, 0x21, // input '!' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put 'd' on heap 0x01, 0x00, 0x00, 0x0A, // input '\n' in register 0 0x05, 0x01, 0x00, 0x00, // increment register 1 0x02, 0x01, 0x00, 0x00, // put '\n' on heap 0x01, 0x00, 0x00, 0x01, // load register 0 with 1 for a write syscall 0x01, 0x01, 0x00, 0x00, // load register 1 with the string location 0x01, 0x02, 0x00, 0x0D, // load 13 into register 2 aka the length of the string 0x09, 0x00, 0x00, 0x00, // syscall 0x01, 0x00, 0x00, 0x00, // load register 0 with 0 for a write syscall 0x01, 0x01, 0x00, 0x0A, // load register 0 with 10 for the exit code 0x09, 0x00, 0x00, 0x00, // syscall }; var machine = vm.Machine.init(&program); machine.run(); }
https://raw.githubusercontent.com/cowboy8625/ender/1e0773d4f7c85495467731a50eba86257af552e2/libs/vm/src/main.zig
const std = @import("std"); const stdx = @import("./stdx.zig"); const MAX_DIRS = 100_000; const Dir = struct { parent: usize, size: u64, }; var dirs = std.mem.zeroes([MAX_DIRS]Dir); pub fn main() !void { const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); var buf: [1024]u8 = undefined; var curr: usize = 0; var free: usize = 1; while (try stdin.readUntilDelimiterOrEof(buf[0..], '\n')) |line| { if (line.len == 0) continue; var rest = line; if (stdx.cut(&rest, "$ ") != null) { if (stdx.cut(&rest, "ls") != null) { // nothing to do for ls. } else { if (stdx.cut(&rest, "cd ") == null) return error.BadCommand; if (std.mem.eql(u8, rest, "..")) { dirs[dirs[curr].parent].size += dirs[curr].size; curr = dirs[curr].parent; } else { dirs[free].parent = curr; curr = free; free += 1; } } } else { if (stdx.cut(&rest, "dir") != null) { // nothing to do for a dir } else { const size_s = stdx.cut(&rest, " ") orelse return error.BadFile; const size = try std.fmt.parseInt(u64, size_s, 10); dirs[curr].size += size; } } } while (curr != 0) { dirs[dirs[curr].parent].size += dirs[curr].size; curr = dirs[curr].parent; } const cutoff = 30_000_000 - (70_000_000 - dirs[0].size); var total: u64 = std.math.maxInt(u64); for (dirs[0..free]) |dir| { if (dir.size > cutoff and dir.size < total) total = dir.size; } try stdout.print("{}\n", .{total}); }
https://raw.githubusercontent.com/matklad/aoc2022/67800cfb0aa3dcb0103da06c0b6f2103f1494dc7/day7.zig
const std = @import("std"); const builtin = @import("builtin"); const tests = @import("test/tests.zig"); const Build = std.Build; const CompileStep = Build.CompileStep; const Step = Build.Step; const Child = std.process.Child; const assert = std.debug.assert; const join = std.fs.path.join; const print = std.debug.print; // When changing this version, be sure to also update README.md in two places: // 1) Getting Started // 2) Version Changes comptime { const required_zig = "0.11.0-dev.4246"; const current_zig = builtin.zig_version; const min_zig = std.SemanticVersion.parse(required_zig) catch unreachable; if (current_zig.order(min_zig) == .lt) { const error_message = \\Sorry, it looks like your version of zig is too old. :-( \\ \\Ziglings requires development build \\ \\{} \\ \\or higher. \\ \\Please download a development ("master") build from \\ \\https://ziglang.org/download/ \\ \\ ; @compileError(std.fmt.comptimePrint(error_message, .{min_zig})); } } const Kind = enum { /// Run the artifact as a normal executable. exe, /// Run the artifact as a test. @"test", }; pub const Exercise = struct { /// main_file must have the format key_name.zig. /// The key will be used as a shorthand to build just one example. main_file: []const u8, /// This is the desired output of the program. /// A program passes if its output, excluding trailing whitespace, is equal /// to this string. output: []const u8, /// This is an optional hint to give if the program does not succeed. hint: ?[]const u8 = null, /// By default, we verify output against stderr. /// Set this to true to check stdout instead. check_stdout: bool = false, /// This exercise makes use of C functions. /// We need to keep track of this, so we compile with libc. link_libc: bool = false, /// This exercise kind. kind: Kind = .exe, /// This exercise is not supported by the current Zig compiler. skip: bool = false, /// Returns the name of the main file with .zig stripped. pub fn name(self: Exercise) []const u8 { return std.fs.path.stem(self.main_file); } /// Returns the key of the main file, the string before the '_' with /// "zero padding" removed. /// For example, "001_hello.zig" has the key "1". pub fn key(self: Exercise) []const u8 { // Main file must be key_description.zig. const end_index = std.mem.indexOfScalar(u8, self.main_file, '_') orelse unreachable; // Remove zero padding by advancing index past '0's. var start_index: usize = 0; while (self.main_file[start_index] == '0') start_index += 1; return self.main_file[start_index..end_index]; } /// Returns the exercise key as an integer. pub fn number(self: Exercise) usize { return std.fmt.parseInt(usize, self.key(), 10) catch unreachable; } }; /// Build mode. const Mode = enum { /// Normal build mode: `zig build` normal, /// Named build mode: `zig build -Dn=n` named, }; pub const logo = \\ _ _ _ \\ ___(_) __ _| (_)_ __ __ _ ___ \\ |_ | |/ _' | | | '_ \ / _' / __| \\ / /| | (_| | | | | | | (_| \__ \ \\ /___|_|\__, |_|_|_| |_|\__, |___/ \\ |___/ |___/ \\ \\ "Look out! Broken programs below!" \\ \\ ; pub fn build(b: *Build) !void { if (!validate_exercises()) std.os.exit(2); use_color_escapes = false; if (std.io.getStdErr().supportsAnsiEscapeCodes()) { use_color_escapes = true; } else if (builtin.os.tag == .windows) { const w32 = struct { const WINAPI = std.os.windows.WINAPI; const DWORD = std.os.windows.DWORD; const ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004; const STD_ERROR_HANDLE: DWORD = @bitCast(@as(i32, -12)); extern "kernel32" fn GetStdHandle(id: DWORD) callconv(WINAPI) ?*anyopaque; extern "kernel32" fn GetConsoleMode(console: ?*anyopaque, out_mode: *DWORD) callconv(WINAPI) u32; extern "kernel32" fn SetConsoleMode(console: ?*anyopaque, mode: DWORD) callconv(WINAPI) u32; }; const handle = w32.GetStdHandle(w32.STD_ERROR_HANDLE); var mode: w32.DWORD = 0; if (w32.GetConsoleMode(handle, &mode) != 0) { mode |= w32.ENABLE_VIRTUAL_TERMINAL_PROCESSING; use_color_escapes = w32.SetConsoleMode(handle, mode) != 0; } } if (use_color_escapes) { red_text = "\x1b[31m"; red_bold_text = "\x1b[31;1m"; red_dim_text = "\x1b[31;2m"; green_text = "\x1b[32m"; bold_text = "\x1b[1m"; reset_text = "\x1b[0m"; } // Remove the standard install and uninstall steps. b.top_level_steps = .{}; const healed = b.option(bool, "healed", "Run exercises from patches/healed") orelse false; const override_healed_path = b.option([]const u8, "healed-path", "Override healed path"); const exno: ?usize = b.option(usize, "n", "Select exercise"); const sep = std.fs.path.sep_str; const healed_path = if (override_healed_path) |path| path else "patches" ++ sep ++ "healed"; const work_path = if (healed) healed_path else "exercises"; const header_step = PrintStep.create(b, logo); if (exno) |n| { // Named build mode: verifies a single exercise. if (n == 0 or n > exercises.len - 1) { print("unknown exercise number: {}\n", .{n}); std.os.exit(2); } const ex = exercises[n - 1]; const zigling_step = b.step( "zigling", b.fmt("Check the solution of {s}", .{ex.main_file}), ); b.default_step = zigling_step; zigling_step.dependOn(&header_step.step); const verify_step = ZiglingStep.create(b, ex, work_path, .named); verify_step.step.dependOn(&header_step.step); zigling_step.dependOn(&verify_step.step); return; } // Normal build mode: verifies all exercises according to the recommended // order. const ziglings_step = b.step("ziglings", "Check all ziglings"); b.default_step = ziglings_step; var prev_step = &header_step.step; for (exercises) |ex| { const verify_stepn = ZiglingStep.create(b, ex, work_path, .normal); verify_stepn.step.dependOn(prev_step); prev_step = &verify_stepn.step; } ziglings_step.dependOn(prev_step); const test_step = b.step("test", "Run all the tests"); test_step.dependOn(tests.addCliTests(b, &exercises)); } var use_color_escapes = false; var red_text: []const u8 = ""; var red_bold_text: []const u8 = ""; var red_dim_text: []const u8 = ""; var green_text: []const u8 = ""; var bold_text: []const u8 = ""; var reset_text: []const u8 = ""; const ZiglingStep = struct { step: Step, exercise: Exercise, work_path: []const u8, mode: Mode, pub fn create( b: *Build, exercise: Exercise, work_path: []const u8, mode: Mode, ) *ZiglingStep { const self = b.allocator.create(ZiglingStep) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = .custom, .name = exercise.main_file, .owner = b, .makeFn = make, }), .exercise = exercise, .work_path = work_path, .mode = mode, }; return self; } fn make(step: *Step, prog_node: *std.Progress.Node) !void { // NOTE: Using exit code 2 will prevent the Zig compiler to print the message: // "error: the following build command failed with exit code 1:..." const self = @fieldParentPtr(ZiglingStep, "step", step); if (self.exercise.skip) { print("Skipping {s}\n\n", .{self.exercise.main_file}); return; } const exe_path = self.compile(prog_node) catch { self.printErrors(); if (self.exercise.hint) |hint| print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text }); self.help(); std.os.exit(2); }; self.run(exe_path.?, prog_node) catch { self.printErrors(); if (self.exercise.hint) |hint| print("\n{s}Ziglings hint: {s}{s}", .{ bold_text, hint, reset_text }); self.help(); std.os.exit(2); }; // Print possible warning/debug messages. self.printErrors(); } fn run(self: *ZiglingStep, exe_path: []const u8, _: *std.Progress.Node) !void { resetLine(); print("Checking {s}...\n", .{self.exercise.main_file}); const b = self.step.owner; // Allow up to 1 MB of stdout capture. const max_output_bytes = 1 * 1024 * 1024; var result = Child.exec(.{ .allocator = b.allocator, .argv = &.{exe_path}, .cwd = b.build_root.path.?, .cwd_dir = b.build_root.handle, .max_output_bytes = max_output_bytes, }) catch |err| { return self.step.fail("unable to spawn {s}: {s}", .{ exe_path, @errorName(err), }); }; switch (self.exercise.kind) { .exe => return self.check_output(result), .@"test" => return self.check_test(result), } } fn check_output(self: *ZiglingStep, result: Child.ExecResult) !void { const b = self.step.owner; // Make sure it exited cleanly. switch (result.term) { .Exited => |code| { if (code != 0) { return self.step.fail("{s} exited with error code {d} (expected {})", .{ self.exercise.main_file, code, 0, }); } }, else => { return self.step.fail("{s} terminated unexpectedly", .{ self.exercise.main_file, }); }, } const raw_output = if (self.exercise.check_stdout) result.stdout else result.stderr; // Validate the output. // NOTE: exercise.output can never contain a CR character. // See https://ziglang.org/documentation/master/#Source-Encoding. const output = trimLines(b.allocator, raw_output) catch @panic("OOM"); const exercise_output = self.exercise.output; if (!std.mem.eql(u8, output, self.exercise.output)) { const red = red_bold_text; const reset = reset_text; // Override the coloring applied by the printError method. // NOTE: the first red and the last reset are not necessary, they // are here only for alignment. return self.step.fail( \\ \\{s}========= expected this output: =========={s} \\{s} \\{s}========= but found: ====================={s} \\{s} \\{s}=========================================={s} , .{ red, reset, exercise_output, red, reset, output, red, reset }); } print("{s}PASSED:\n{s}{s}\n\n", .{ green_text, output, reset_text }); } fn check_test(self: *ZiglingStep, result: Child.ExecResult) !void { switch (result.term) { .Exited => |code| { if (code != 0) { // The test failed. const stderr = std.mem.trimRight(u8, result.stderr, " \r\n"); return self.step.fail("\n{s}", .{stderr}); } }, else => { return self.step.fail("{s} terminated unexpectedly", .{ self.exercise.main_file, }); }, } print("{s}PASSED{s}\n\n", .{ green_text, reset_text }); } fn compile(self: *ZiglingStep, prog_node: *std.Progress.Node) !?[]const u8 { print("Compiling {s}...\n", .{self.exercise.main_file}); const b = self.step.owner; const exercise_path = self.exercise.main_file; const path = join(b.allocator, &.{ self.work_path, exercise_path }) catch @panic("OOM"); var zig_args = std.ArrayList([]const u8).init(b.allocator); defer zig_args.deinit(); zig_args.append(b.zig_exe) catch @panic("OOM"); const cmd = switch (self.exercise.kind) { .exe => "build-exe", .@"test" => "test", }; zig_args.append(cmd) catch @panic("OOM"); // Enable C support for exercises that use C functions. if (self.exercise.link_libc) { zig_args.append("-lc") catch @panic("OOM"); } zig_args.append(b.pathFromRoot(path)) catch @panic("OOM"); zig_args.append("--cache-dir") catch @panic("OOM"); zig_args.append(b.pathFromRoot(b.cache_root.path.?)) catch @panic("OOM"); zig_args.append("--listen=-") catch @panic("OOM"); return try self.step.evalZigProcess(zig_args.items, prog_node); } fn help(self: *ZiglingStep) void { const b = self.step.owner; const key = self.exercise.key(); const path = self.exercise.main_file; const cmd = switch (self.mode) { .normal => "zig build", .named => b.fmt("zig build -Dn={s}", .{key}), }; print("\n{s}Edit exercises/{s} and run '{s}' again.{s}\n", .{ red_bold_text, path, cmd, reset_text, }); } fn printErrors(self: *ZiglingStep) void { resetLine(); // Display error/warning messages. if (self.step.result_error_msgs.items.len > 0) { for (self.step.result_error_msgs.items) |msg| { print("{s}error: {s}{s}{s}{s}\n", .{ red_bold_text, reset_text, red_dim_text, msg, reset_text, }); } } // Render compile errors at the bottom of the terminal. // TODO: use the same ttyconf from the builder. const ttyconf: std.io.tty.Config = if (use_color_escapes) .escape_codes else .no_color; if (self.step.result_error_bundle.errorMessageCount() > 0) { self.step.result_error_bundle.renderToStdErr(.{ .ttyconf = ttyconf }); } } }; /// Clears the entire line and move the cursor to column zero. /// Used for clearing the compiler and build_runner progress messages. fn resetLine() void { if (use_color_escapes) print("{s}", .{"\x1b[2K\r"}); } /// Removes trailing whitespace for each line in buf, also ensuring that there /// are no trailing LF characters at the end. pub fn trimLines(allocator: std.mem.Allocator, buf: []const u8) ![]const u8 { var list = try std.ArrayList(u8).initCapacity(allocator, buf.len); var iter = std.mem.split(u8, buf, " \n"); while (iter.next()) |line| { // TODO: trimming CR characters is probably not necessary. const data = std.mem.trimRight(u8, line, " \r"); try list.appendSlice(data); try list.append('\n'); } const result = try list.toOwnedSlice(); // TODO: probably not necessary // Remove the trailing LF character, that is always present in the exercise // output. return std.mem.trimRight(u8, result, "\n"); } /// Prints a message to stderr. const PrintStep = struct { step: Step, message: []const u8, pub fn create(owner: *Build, message: []const u8) *PrintStep { const self = owner.allocator.create(PrintStep) catch @panic("OOM"); self.* = .{ .step = Step.init(.{ .id = .custom, .name = "print", .owner = owner, .makeFn = make, }), .message = message, }; return self; } fn make(step: *Step, _: *std.Progress.Node) !void { const self = @fieldParentPtr(PrintStep, "step", step); print("{s}", .{self.message}); } }; /// Checks that each exercise number, excluding the last, forms the sequence /// `[1, exercise.len)`. /// /// Additionally check that the output field lines doesn't have trailing whitespace. fn validate_exercises() bool { // Don't use the "multi-object for loop" syntax, in order to avoid a syntax // error with old Zig compilers. var i: usize = 0; for (exercises[0..]) |ex| { const exno = ex.number(); const last = 999; i += 1; if (exno != i and exno != last) { print("exercise {s} has an incorrect number: expected {}, got {s}\n", .{ ex.main_file, i, ex.key(), }); return false; } var iter = std.mem.split(u8, ex.output, "\n"); while (iter.next()) |line| { const output = std.mem.trimRight(u8, line, " \r"); if (output.len != line.len) { print("exercise {s} output field lines have trailing whitespace\n", .{ ex.main_file, }); return false; } } if (!std.mem.endsWith(u8, ex.main_file, ".zig")) { print("exercise {s} is not a zig source file\n", .{ex.main_file}); return false; } } return true; } const exercises = [_]Exercise{ .{ .main_file = "001_hello.zig", .output = "Hello world!", .hint = \\DON'T PANIC! \\Read the compiler messages above. (Something about 'main'?) \\Open up the source file as noted below and read the comments. \\ \\(Hints like these will occasionally show up, but for the \\most part, you'll be taking directions from the Zig \\compiler itself.) \\ , }, .{ .main_file = "002_std.zig", .output = "Standard Library.", }, .{ .main_file = "003_assignment.zig", .output = "55 314159 -11", .hint = "There are three mistakes in this one!", }, .{ .main_file = "004_arrays.zig", .output = "First: 2, Fourth: 7, Length: 8", .hint = "There are two things to complete here.", }, .{ .main_file = "005_arrays2.zig", .output = "LEET: 1337, Bits: 100110011001", .hint = "Fill in the two arrays.", }, .{ .main_file = "006_strings.zig", .output = "d=d ha ha ha Major Tom", .hint = "Each '???' needs something filled in.", }, .{ .main_file = "007_strings2.zig", .output = \\Ziggy played guitar \\Jamming good with Andrew Kelley \\And the Spiders from Mars , .hint = "Please fix the lyrics!", }, .{ .main_file = "008_quiz.zig", .output = "Program in Zig!", .hint = "See if you can fix the program!", }, .{ .main_file = "009_if.zig", .output = "Foo is 1!", }, .{ .main_file = "010_if2.zig", .output = "With the discount, the price is $17.", }, .{ .main_file = "011_while.zig", .output = "2 4 8 16 32 64 128 256 512 n=1024", .hint = "You probably want a 'less than' condition.", }, .{ .main_file = "012_while2.zig", .output = "2 4 8 16 32 64 128 256 512 n=1024", .hint = "It might help to look back at the previous exercise.", }, .{ .main_file = "013_while3.zig", .output = "1 2 4 7 8 11 13 14 16 17 19", }, .{ .main_file = "014_while4.zig", .output = "n=4", }, .{ .main_file = "015_for.zig", .output = "A Dramatic Story: :-) :-) :-( :-| :-) The End.", }, .{ .main_file = "016_for2.zig", .output = "The value of bits '1101': 13.", }, .{ .main_file = "017_quiz2.zig", .output = "1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16,", .hint = "This is a famous game!", }, .{ .main_file = "018_functions.zig", .output = "Answer to the Ultimate Question: 42", .hint = "Can you help write the function?", }, .{ .main_file = "019_functions2.zig", .output = "Powers of two: 2 4 8 16", }, .{ .main_file = "020_quiz3.zig", .output = "32 64 128 256", .hint = "Unexpected pop quiz! Help!", }, .{ .main_file = "021_errors.zig", .output = "2<4. 3<4. 4=4. 5>4. 6>4.", .hint = "What's the deal with fours?", }, .{ .main_file = "022_errors2.zig", .output = "I compiled!", .hint = "Get the error union type right to allow this to compile.", }, .{ .main_file = "023_errors3.zig", .output = "a=64, b=22", }, .{ .main_file = "024_errors4.zig", .output = "a=20, b=14, c=10", }, .{ .main_file = "025_errors5.zig", .output = "a=0, b=19, c=0", }, .{ .main_file = "026_hello2.zig", .output = "Hello world!", .hint = "Try using a try!", .check_stdout = true, }, .{ .main_file = "027_defer.zig", .output = "One Two", }, .{ .main_file = "028_defer2.zig", .output = "(Goat) (Cat) (Dog) (Dog) (Goat) (Unknown) done.", }, .{ .main_file = "029_errdefer.zig", .output = "Getting number...got 5. Getting number...failed!", }, .{ .main_file = "030_switch.zig", .output = "ZIG?", }, .{ .main_file = "031_switch2.zig", .output = "ZIG!", }, .{ .main_file = "032_unreachable.zig", .output = "1 2 3 9 8 7", }, .{ .main_file = "033_iferror.zig", .output = "2<4. 3<4. 4=4. 5>4. 6>4.", .hint = "Seriously, what's the deal with fours?", }, .{ .main_file = "034_quiz4.zig", .output = "my_num=42", .hint = "Can you make this work?", .check_stdout = true, }, .{ .main_file = "035_enums.zig", .output = "1 2 3 9 8 7", .hint = "This problem seems familiar...", }, .{ .main_file = "036_enums2.zig", .output = \\<p> \\ <span style="color: #ff0000">Red</span> \\ <span style="color: #00ff00">Green</span> \\ <span style="color: #0000ff">Blue</span> \\</p> , .hint = "I'm feeling blue about this.", }, .{ .main_file = "037_structs.zig", .output = "Your wizard has 90 health and 25 gold.", }, .{ .main_file = "038_structs2.zig", .output = \\Character 1 - G:20 H:100 XP:10 \\Character 2 - G:10 H:100 XP:20 , }, .{ .main_file = "039_pointers.zig", .output = "num1: 5, num2: 5", .hint = "Pointers aren't so bad.", }, .{ .main_file = "040_pointers2.zig", .output = "a: 12, b: 12", }, .{ .main_file = "041_pointers3.zig", .output = "foo=6, bar=11", }, .{ .main_file = "042_pointers4.zig", .output = "num: 5, more_nums: 1 1 5 1", }, .{ .main_file = "043_pointers5.zig", .output = \\Wizard (G:10 H:100 XP:20) \\ Mentor: Wizard (G:10000 H:100 XP:2340) , }, .{ .main_file = "044_quiz5.zig", .output = "Elephant A. Elephant B. Elephant C.", .hint = "Oh no! We forgot Elephant B!", }, .{ .main_file = "045_optionals.zig", .output = "The Ultimate Answer: 42.", }, .{ .main_file = "046_optionals2.zig", .output = "Elephant A. Elephant B. Elephant C.", .hint = "Elephants again!", }, .{ .main_file = "047_methods.zig", .output = "5 aliens. 4 aliens. 1 aliens. 0 aliens. Earth is saved!", .hint = "Use the heat ray. And the method!", }, .{ .main_file = "048_methods2.zig", .output = "A B C", .hint = "This just needs one little fix.", }, .{ .main_file = "049_quiz6.zig", .output = "A B C Cv Bv Av", .hint = "Now you're writing Zig!", }, .{ .main_file = "050_no_value.zig", .output = "That is not dead which can eternal lie / And with strange aeons even death may die.", }, .{ .main_file = "051_values.zig", .output = "1:false!. 2:true!. 3:true!. XP before:0, after:200.", }, .{ .main_file = "052_slices.zig", .output = \\Hand1: A 4 K 8 \\Hand2: 5 2 Q J , }, .{ .main_file = "053_slices2.zig", .output = "'all your base are belong to us.' 'for great justice.'", }, .{ .main_file = "054_manypointers.zig", .output = "Memory is a resource.", }, .{ .main_file = "055_unions.zig", .output = "Insect report! Ant alive is: true. Bee visited 15 flowers.", }, .{ .main_file = "056_unions2.zig", .output = "Insect report! Ant alive is: true. Bee visited 16 flowers.", }, .{ .main_file = "057_unions3.zig", .output = "Insect report! Ant alive is: true. Bee visited 17 flowers.", }, .{ .main_file = "058_quiz7.zig", .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond", .hint = "This is the biggest program we've seen yet. But you can do it!", }, .{ .main_file = "059_integers.zig", .output = "Zig is cool.", }, .{ .main_file = "060_floats.zig", .output = "Shuttle liftoff weight: 1995796kg", }, .{ .main_file = "061_coercions.zig", .output = "Letter: A", }, .{ .main_file = "062_loop_expressions.zig", .output = "Current language: Zig", .hint = "Surely the current language is 'Zig'!", }, .{ .main_file = "063_labels.zig", .output = "Enjoy your Cheesy Chili!", }, .{ .main_file = "064_builtins.zig", .output = "1101 + 0101 = 0010 (true). Without overflow: 00010010. Furthermore, 11110000 backwards is 00001111.", }, .{ .main_file = "065_builtins2.zig", .output = "A Narcissus loves all Narcissuses. He has room in his heart for: me myself.", }, .{ .main_file = "066_comptime.zig", .output = "Immutable: 12345, 987.654; Mutable: 54321, 456.789; Types: comptime_int, comptime_float, u32, f32", .hint = "It may help to read this one out loud to your favorite stuffed animal until it sinks in completely.", }, .{ .main_file = "067_comptime2.zig", .output = "A BB CCC DDDD", }, .{ .main_file = "068_comptime3.zig", .output = \\Minnow (1:32, 4 x 2) \\Shark (1:16, 8 x 5) \\Whale (1:1, 143 x 95) , }, .{ .main_file = "069_comptime4.zig", .output = "s1={ 1, 2, 3 }, s2={ 1, 2, 3, 4, 5 }, s3={ 1, 2, 3, 4, 5, 6, 7 }", }, .{ .main_file = "070_comptime5.zig", .output = \\"Quack." ducky1: true, "Squeek!" ducky2: true, ducky3: false , .hint = "Have you kept the wizard hat on?", }, .{ .main_file = "071_comptime6.zig", .output = "Narcissus has room in his heart for: me myself.", }, .{ .main_file = "072_comptime7.zig", .output = "26", }, .{ .main_file = "073_comptime8.zig", .output = "My llama value is 25.", }, .{ .main_file = "074_comptime9.zig", .output = "My llama value is 2.", }, .{ .main_file = "075_quiz8.zig", .output = "Archer's Point--2->Bridge--1->Dogwood Grove--3->Cottage--2->East Pond--1->Fox Pond", .hint = "Roll up those sleeves. You get to WRITE some code for this one.", }, .{ .main_file = "076_sentinels.zig", .output = "Array:123056. Many-item pointer:123.", }, .{ .main_file = "077_sentinels2.zig", .output = "Weird Data!", }, .{ .main_file = "078_sentinels3.zig", .output = "Weird Data!", }, .{ .main_file = "079_quoted_identifiers.zig", .output = "Sweet freedom: 55, false.", .hint = "Help us, Zig Programmer, you're our only hope!", }, .{ .main_file = "080_anonymous_structs.zig", .output = "[Circle(i32): 25,70,15] [Circle(f32): 25.2,71.0,15.7]", }, .{ .main_file = "081_anonymous_structs2.zig", .output = "x:205 y:187 radius:12", }, .{ .main_file = "082_anonymous_structs3.zig", .output = \\"0"(bool):true "1"(bool):false "2"(i32):42 "3"(f32):3.14159202e+00 , .hint = "This one is a challenge! But you have everything you need.", }, .{ .main_file = "083_anonymous_lists.zig", .output = "I say hello!", }, // Skipped because of https://github.com/ratfactor/ziglings/issues/163 // direct link: https://github.com/ziglang/zig/issues/6025 .{ .main_file = "084_async.zig", .output = "foo() A", .hint = "Read the facts. Use the facts.", .skip = true, }, .{ .main_file = "085_async2.zig", .output = "Hello async!", .skip = true, }, .{ .main_file = "086_async3.zig", .output = "5 4 3 2 1", .skip = true, }, .{ .main_file = "087_async4.zig", .output = "1 2 3 4 5", .skip = true, }, .{ .main_file = "088_async5.zig", .output = "Example Title.", .skip = true, }, .{ .main_file = "089_async6.zig", .output = ".com: Example Title, .org: Example Title.", .skip = true, }, .{ .main_file = "090_async7.zig", .output = "beef? BEEF!", .skip = true, }, .{ .main_file = "091_async8.zig", .output = "ABCDEF", .skip = true, }, .{ .main_file = "092_interfaces.zig", .output = \\Daily Insect Report: \\Ant is alive. \\Bee visited 17 flowers. \\Grasshopper hopped 32 meters. , }, .{ .main_file = "093_hello_c.zig", .output = "Hello C from Zig! - C result is 17 chars written.", .link_libc = true, }, .{ .main_file = "094_c_math.zig", .output = "The normalized angle of 765.2 degrees is 45.2 degrees.", .link_libc = true, }, .{ .main_file = "095_for3.zig", .output = "1 2 4 7 8 11 13 14 16 17 19", }, .{ .main_file = "096_memory_allocation.zig", .output = "Running Average: 0.30 0.25 0.20 0.18 0.22", }, .{ .main_file = "097_bit_manipulation.zig", .output = "x = 0; y = 1", }, .{ .main_file = "098_bit_manipulation2.zig", .output = "Is this a pangram? true!", }, .{ .main_file = "099_formatting.zig", .output = \\ \\ X | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \\---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+ \\ 1 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 \\ \\ 2 | 2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 \\ \\ 3 | 3 6 9 12 15 18 21 24 27 30 33 36 39 42 45 \\ \\ 4 | 4 8 12 16 20 24 28 32 36 40 44 48 52 56 60 \\ \\ 5 | 5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 \\ \\ 6 | 6 12 18 24 30 36 42 48 54 60 66 72 78 84 90 \\ \\ 7 | 7 14 21 28 35 42 49 56 63 70 77 84 91 98 105 \\ \\ 8 | 8 16 24 32 40 48 56 64 72 80 88 96 104 112 120 \\ \\ 9 | 9 18 27 36 45 54 63 72 81 90 99 108 117 126 135 \\ \\10 | 10 20 30 40 50 60 70 80 90 100 110 120 130 140 150 \\ \\11 | 11 22 33 44 55 66 77 88 99 110 121 132 143 154 165 \\ \\12 | 12 24 36 48 60 72 84 96 108 120 132 144 156 168 180 \\ \\13 | 13 26 39 52 65 78 91 104 117 130 143 156 169 182 195 \\ \\14 | 14 28 42 56 70 84 98 112 126 140 154 168 182 196 210 \\ \\15 | 15 30 45 60 75 90 105 120 135 150 165 180 195 210 225 , }, .{ .main_file = "100_for4.zig", .output = "Arrays match!", }, .{ .main_file = "101_for5.zig", .output = \\1. Wizard (Gold: 25, XP: 40) \\2. Bard (Gold: 11, XP: 17) \\3. Bard (Gold: 5, XP: 55) \\4. Warrior (Gold: 7392, XP: 21) , }, .{ .main_file = "102_testing.zig", .output = "", .kind = .@"test", }, .{ .main_file = "103_tokenization.zig", .output = \\My \\name \\is \\Ozymandias \\King \\of \\Kings \\Look \\on \\my \\Works \\ye \\Mighty \\and \\despair \\This little poem has 15 words! , }, .{ .main_file = "999_the_end.zig", .output = \\ \\This is the end for now! \\We hope you had fun and were able to learn a lot, so visit us again when the next exercises are available. , }, };
https://raw.githubusercontent.com/konradmalik/zig-learn/eab1c31838bad962056d7376a89d8a314ce40b0e/build.zig
// SPDX-License-Identifier: BSD 2-Clause "Simplified" License // // src/CPU.zig // // Created by: Aakash Sen Sharma, August 2023 // Copyright: (C) 2023, Aakash Sen Sharma & Contributors const Self = @This(); const Bus = @import("Bus.zig"); const DRAM = @import("DRAM.zig"); registers: [32]u64, // 64-bit CPU with 32 registers. program_counter: u64, bus: Bus, // CPU connected to Bus pub fn reset(self: *Self) void { self.registers[0] = 0x00; // 0x0 is hardwired to 0. self.registers[2] = DRAM.memory_size + DRAM.memory_base_addr_offset; // Stack pointer resides at 0x02 self.program_counter = DRAM.memory_base_addr_offset; // Set program counter to base addr self.bus.dram.reset(); } pub fn fetch(self: *Self, comptime T: type) T { const inst = self.bus.fetch(T, self.program_counter); self.program_counter += @sizeOf(T); return inst; } /// Peek into an instructions of size @sizeOf(T) bit ahead without incrementing function pointer. pub fn peek(self: *Self, comptime T: type) T { return self.bus.fetch(T, self.program_counter); } pub fn exec(self: *Self, inst: u32) i32 { _ = inst; _ = self; } pub fn dump_registers(self: *Self) void { _ = self; }
https://raw.githubusercontent.com/Shinyzenith/Zigemu-RISCV/934a91ebe4eb43cc9f6e86be6cd6827b3536e48f/src/CPU.zig
const builtin = @import("builtin"); const std = @import("std"); const testing = std.testing; // DateError enumerates possible Date-related errors. const DateError = error{ InvalidArgument, }; /// (Dominical)Letter classifies each year of the Gregorian calendar into /// 10 classes: common and leap years starting with Monday through Sunday. /// Each letter is encoded in four bits `abbb`, where `a` is `1` for the /// common year and `bbb` is a non-zero `Weekday` mapping `Mon` to 7 of /// the last day in the past year. const Letter = enum(u4) { A = 0o15, AG = 0o05, B = 0o14, BA = 0o04, C = 0o13, CB = 0o03, D = 0o12, DC = 0o02, E = 0o11, ED = 0o01, F = 0o17, FE = 0o07, G = 0o16, GF = 0o06, /// YearToLetter is the 400-years repeating pattern of dominical letters. const YearToLetter = [400]Letter{ .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .C, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .E, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .G, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, .BA, .G, .F, .E, .DC, .B, .A, .G, .FE, .D, .C, .B, .AG, .F, .E, .D, .CB, .A, .G, .F, .ED, .C, .B, .A, .GF, .E, .D, .C, }; const MdlToOl = [_]u8{ 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 255, 255, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 255, 255, 255, 255, 255, 255, 255, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 72, 74, 255, 255, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 74, 76, 255, 255, 255, 255, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 78, 80, 255, 255, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 80, 82, 255, 255, 255, 255, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 84, 86, 255, 255, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 86, 88, 255, 255, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 88, 90, 255, 255, 255, 255, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 92, 94, 255, 255, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 94, 96, 255, 255, 255, 255, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, 98, 100, }; /// from_year converts a year number into a Letter. fn from_year(year: i32) Letter { const ymod: usize = @bitCast(u32, @mod(year, 400)); return YearToLetter[ymod]; } /// ndays returns the number of days in the year. fn ndays(self: Letter) u32 { comptime if (builtin.target.cpu.arch.endian() != .Little) { @compileError("Date bit arithmetic requires little-endian architecture"); }; const ltr = @enumToInt(self); return 366 - @as(u32, ltr >> 3); } /// dm_to_doy translates day and month to the day of year. fn dm_to_doy(self: Letter, day: u5, month: u4) DateError!u9 { comptime if (builtin.target.cpu.arch.endian() != .Little) { @compileError("Date bit arithmetic requires little-endian architecture"); }; const ltr = @enumToInt(self); const leap = @as(u32, ltr >> 3); const index = (@as(u32, month) << 6) | (@as(u32, day) << 1) | (@as(u32, leap)); if (index > MdlToOl.len) { return DateError.InvalidArgument; } const doy = @truncate(u9, (index -% (@as(u32, MdlToOl[index]) & 0x3ff)) >> 1); if (doy > 365) { return DateError.InvalidArgument; } return doy; } }; test "unit:Letter:ndays" { try testing.expectEqual(365, comptime Letter.from_year(2014).ndays()); try testing.expectEqual(366, comptime Letter.from_year(2012).ndays()); try testing.expectEqual(366, comptime Letter.from_year(2000).ndays()); try testing.expectEqual(365, comptime Letter.from_year(1900).ndays()); try testing.expectEqual(366, comptime Letter.from_year(0).ndays()); try testing.expectEqual(365, comptime Letter.from_year(-1).ndays()); try testing.expectEqual(366, comptime Letter.from_year(-4).ndays()); try testing.expectEqual(365, comptime Letter.from_year(-99).ndays()); try testing.expectEqual(365, comptime Letter.from_year(-100).ndays()); try testing.expectEqual(365, comptime Letter.from_year(-399).ndays()); try testing.expectEqual(366, comptime Letter.from_year(-400).ndays()); } test "unit:Letter:dm_to_doy" { try testing.expectEqual(61, comptime (try Letter.from_year(2018).dm_to_doy(2, 3))); try testing.expectEqual(1, comptime (try Letter.from_year(2023).dm_to_doy(1, 1))); try testing.expectEqual(2, comptime (try Letter.from_year(2023).dm_to_doy(2, 1))); try testing.expectEqual(45, comptime (try Letter.from_year(2015).dm_to_doy(14, 2))); try testing.expectError(DateError.InvalidArgument, Letter.from_year(2012).dm_to_doy(0, 1)); try testing.expectError(DateError.InvalidArgument, Letter.from_year(2015).dm_to_doy(29, 2)); } /// ISO 8601 date consisting of year, ordinal date and domicial letter. pub const Date = packed struct { year: i19, doy: u9, letter: Letter, /// from_yo makes a new Date from the ordinal date (year and day of year). pub fn from_yo(year: i19, doy: u9) DateError!Date { const letter = Letter.from_year(year); if (doy < 1 or doy > letter.ndays()) { return DateError.InvalidArgument; } return .{ .year = year, .doy = doy, .letter = letter }; } /// from_ymd makes a new Date from the calendar date (year, month and day). pub fn from_ymd(year: i19, month: u4, day: u5) DateError!Date { const letter = Letter.from_year(year); const doy = letter.dm_to_doy(day, month) catch |err| return err; return .{ .year = year, .doy = doy, .letter = letter }; } }; test "unit:Date:from_yo" { try testing.expectEqual(Letter.D, comptime (try Date.from_yo(2015, 100)).letter); try testing.expectError(DateError.InvalidArgument, Date.from_yo(2015, 0)); try testing.expectEqual(2015, comptime (try Date.from_yo(2015, 365)).year); try testing.expectError(DateError.InvalidArgument, Date.from_yo(2015, 366)); try testing.expectEqual(366, comptime (try Date.from_yo(-4, 366)).doy); } test "unit:Date:from_ymd" { try testing.expectEqual(61, comptime (try Date.from_ymd(2018, 3, 2)).doy); try testing.expectEqual(45, comptime (try Date.from_ymd(2015, 2, 14)).doy); try testing.expectError(DateError.InvalidArgument, Date.from_ymd(2012, 0, 3)); try testing.expectError(DateError.InvalidArgument, Date.from_ymd(2015, 2, 29)); try testing.expectEqual(60, comptime (try Date.from_ymd(-4, 2, 29)).doy); }
https://raw.githubusercontent.com/scento/zig-date/7890d8772a53a067cdc161802cc07852ffdc6310/src/date.zig
// FNV1a - Fowler-Noll-Vo hash function // // FNV1a is a fast, non-cryptographic hash function with fairly good distribution properties. // // https://tools.ietf.org/html/draft-eastlake-fnv-14 const std = @import("std"); const testing = std.testing; pub const Fnv1a_32 = Fnv1a(u32, 0x01000193, 0x811c9dc5); pub const Fnv1a_64 = Fnv1a(u64, 0x100000001b3, 0xcbf29ce484222325); pub const Fnv1a_128 = Fnv1a(u128, 0x1000000000000000000013b, 0x6c62272e07bb014262b821756295c58d); fn Fnv1a(comptime T: type, comptime prime: T, comptime offset: T) type { return struct { const Self = @This(); value: T, pub fn init() Self { return Self{ .value = offset }; } pub fn update(self: *Self, input: []const u8) void { for (input) |b| { self.value ^= b; self.value *%= prime; } } pub fn final(self: *Self) T { return self.value; } pub fn hash(input: []const u8) T { var c = Self.init(); c.update(input); return c.final(); } }; } const verify = @import("verify.zig"); test "fnv1a-32" { try testing.expect(Fnv1a_32.hash("") == 0x811c9dc5); try testing.expect(Fnv1a_32.hash("a") == 0xe40c292c); try testing.expect(Fnv1a_32.hash("foobar") == 0xbf9cf968); try verify.iterativeApi(Fnv1a_32); } test "fnv1a-64" { try testing.expect(Fnv1a_64.hash("") == 0xcbf29ce484222325); try testing.expect(Fnv1a_64.hash("a") == 0xaf63dc4c8601ec8c); try testing.expect(Fnv1a_64.hash("foobar") == 0x85944171f73967e8); try verify.iterativeApi(Fnv1a_64); } test "fnv1a-128" { try testing.expect(Fnv1a_128.hash("") == 0x6c62272e07bb014262b821756295c58d); try testing.expect(Fnv1a_128.hash("a") == 0xd228cb696f1a8caf78912b704e4a8964); try verify.iterativeApi(Fnv1a_128); }
https://raw.githubusercontent.com/ziglang/zig/d9bd34fd0533295044ffb4160da41f7873aff905/lib/std/hash/fnv.zig
const std = @import("std"); const Func = struct { name: []const u8, args: []const Arg, ret: []const u8, js: []const u8, }; const Arg = struct { name: []const u8, type: []const u8, }; // TODO - i don't know what to put for GLboolean... i can't find an explicit // mention anywhere on what size it should be const zig_top = \\pub const GLenum = c_uint; \\pub const GLboolean = bool; \\pub const GLbitfield = c_uint; \\pub const GLbyte = i8; \\pub const GLshort = i16; \\pub const GLint = i32; \\pub const GLsizei = i32; \\pub const GLintptr = i64; \\pub const GLsizeiptr = i64; \\pub const GLubyte = u8; \\pub const GLushort = u16; \\pub const GLuint = u32; \\pub const GLfloat = f32; \\pub const GLclampf = f32; ; // memory has to be wrapped in a getter because we need the "env" before we can // even get the memory const js_top = \\export default function getWebGLEnv(canvas_element, getMemory) { \\ const readCharStr = (ptr, len) => { \\ const bytes = new Uint8Array(getMemory().buffer, ptr, len); \\ let s = ""; \\ for (let i = 0; i < len; ++i) { \\ s += String.fromCharCode(bytes[i]); \\ } \\ return s; \\ }; \\ const writeCharStr = (ptr, len, lenRetPtr, text) => { \\ const encoder = new TextEncoder(); \\ const message = encoder.encode(text); \\ const zigbytes = new Uint8Array(getMemory().buffer, ptr, len); \\ let zigidx = 0; \\ for (const b of message) { \\ if (zigidx >= len-1) break; \\ zigbytes[zigidx] = b; \\ zigidx += 1; \\ } \\ zigbytes[zigidx] = 0; \\ if (lenRetPtr !== 0) { \\ new Uint32Array(getMemory().buffer, lenRetPtr, 1)[0] = zigidx; \\ } \\ } \\ \\ const gl = canvas_element.getContext('webgl2', { \\ antialias: false, \\ preserveDrawingBuffer: true, \\ }); \\ \\ if (!gl) { \\ throw new Error('The browser does not support WebGL'); \\ } \\ \\ const glShaders = []; \\ const glPrograms = []; \\ const glBuffers = []; \\ const glTextures = []; \\ const glFramebuffers = []; \\ const glUniformLocations = []; \\ ; const js_bottom = \\} ; const funcs = [_]Func{ Func{ .name = "getScreenW", .args = &[_]Arg{}, .ret = "i32", .js = \\return gl.drawingBufferWidth; }, Func{ .name = "getScreenH", .args = &[_]Arg{}, .ret = "i32", .js = \\return gl.drawingBufferHeight; }, Func{ .name = "glActiveTexture", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, }, .ret = "void", .js = \\gl.activeTexture(target); }, Func{ .name = "glAttachShader", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, .{ .name = "shader", .type = "c_uint" }, }, .ret = "void", .js = \\gl.attachShader(glPrograms[program], glShaders[shader]); }, // TODO - glBindAttribLocation Func{ .name = "glBindBuffer", .args = &[_]Arg{ .{ .name = "type", .type = "c_uint" }, .{ .name = "buffer_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindBuffer(type, glBuffers[buffer_id]); }, Func{ .name = "glBindFramebuffer", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "framebuffer", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindFramebuffer(target, glFramebuffers[framebuffer]); }, // TODO - glBindRenderbuffer Func{ .name = "glBindTexture", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "texture_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.bindTexture(target, glTextures[texture_id]); }, // TODO - glBlendColor // TODO - glBlendEquation // TODO - glBlendEquationSeparate Func{ .name = "glBlendFunc", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, .{ .name = "y", .type = "c_uint" }, }, .ret = "void", .js = \\gl.blendFunc(x, y); }, // TODO - glBlendFuncSeparate Func{ .name = "glBufferData", .args = &[_]Arg{ .{ .name = "type", .type = "c_uint" }, .{ .name = "count", .type = "c_long" }, .{ .name = "data_ptr", .type = "*const c_void" }, .{ .name = "draw_type", .type = "c_uint" }, }, .ret = "void", .js = // TODO - check for NULL? \\const bytes = new Uint8Array(getMemory().buffer, data_ptr, count); \\gl.bufferData(type, bytes, draw_type); }, // TODO - glBufferSubData Func{ .name = "glCheckFramebufferStatus", .args = &[_]Arg{ .{ .name = "target", .type = "GLenum" }, }, .ret = "GLenum", .js = \\return gl.checkFramebufferStatus(target); }, Func{ .name = "glClear", .args = &[_]Arg{ .{ .name = "mask", .type = "GLbitfield" }, }, .ret = "void", .js = \\gl.clear(mask); }, Func{ .name = "glClearColor", .args = &[_]Arg{ .{ .name = "r", .type = "f32" }, .{ .name = "g", .type = "f32" }, .{ .name = "b", .type = "f32" }, .{ .name = "a", .type = "f32" }, }, .ret = "void", .js = \\gl.clearColor(r, g, b, a); }, // TODO - glClearDepth // TODO - glClearStencil // TODO - glColorMask // TODO - glCommit Func{ .name = "glCompileShader", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, }, .ret = "void", .js = \\gl.compileShader(glShaders[shader]); }, Func{ .name = "getShaderCompileStatus", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, }, .ret = "GLboolean", .js = \\return gl.getShaderParameter(glShaders[shader], gl.COMPILE_STATUS); }, // TODO - glCompressedTexImage2D // TODO - glCompressedTexImage3D // TODO - glCompressedTexSubImage2D // TODO - glCopyTexImage2D // TODO - glCopyTexSubImage2D Func{ .name = "glCreateBuffer", .args = &[_]Arg{}, .ret = "c_uint", .js = \\glBuffers.push(gl.createBuffer()); \\return glBuffers.length - 1; }, Func{ .name = "glCreateFramebuffer", .args = &[_]Arg{}, .ret = "GLuint", .js = \\glFramebuffers.push(gl.createFramebuffer()); \\return glFramebuffers.length - 1; }, Func{ .name = "glCreateProgram", .args = &[_]Arg{}, .ret = "GLuint", .js = \\glPrograms.push(gl.createProgram()); \\return glPrograms.length - 1; }, // TODO - glCreateRenderbuffer Func{ .name = "glCreateShader", .args = &[_]Arg{ .{ .name = "shader_type", .type = "GLenum" }, }, .ret = "GLuint", .js = \\glShaders.push(gl.createShader(shader_type)); \\return glShaders.length - 1; }, Func{ .name = "glCreateTexture", .args = &[_]Arg{}, .ret = "c_uint", .js = \\glTextures.push(gl.createTexture()); \\return glTextures.length - 1; }, // TODO - glCullFace Func{ .name = "glDeleteBuffer", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteBuffer(glBuffers[id]); \\glBuffers[id] = undefined; }, // TODO - glDeleteFramebuffer Func{ .name = "glDeleteProgram", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteProgram(glPrograms[id]); \\glPrograms[id] = undefined; }, // TODO - glDeleteRenderbuffer Func{ .name = "glDeleteShader", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteShader(glShaders[id]); \\glShaders[id] = undefined; }, Func{ .name = "glDeleteTexture", .args = &[_]Arg{ .{ .name = "id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.deleteTexture(glTextures[id]); \\glTextures[id] = undefined; }, Func{ .name = "glDepthFunc", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, }, .ret = "void", .js = \\gl.depthFunc(x); }, // TODO - glDepthMask // TODO - glDepthRange Func{ .name = "glDetachShader", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, .{ .name = "shader", .type = "c_uint" }, }, .ret = "void", .js = \\gl.detachShader(glPrograms[program], glShaders[shader]); }, Func{ .name = "glDisable", .args = &[_]Arg{ .{ .name = "cap", .type = "GLenum" }, }, .ret = "void", .js = \\gl.disable(cap); }, // TODO - glDisableVertexAttribArray Func{ .name = "glDrawArrays", .args = &[_]Arg{ .{ .name = "type", .type = "c_uint" }, .{ .name = "offset", .type = "c_uint" }, .{ .name = "count", .type = "c_uint" }, }, .ret = "void", .js = \\gl.drawArrays(type, offset, count); }, Func{ .name = "glDrawElements", .args = &[_]Arg{ .{ .name = "mode", .type = "GLenum" }, .{ .name = "count", .type = "GLsizei" }, .{ .name = "type", .type = "GLenum" }, .{ .name = "offset", .type = "?*const c_void" }, }, .ret = "void", .js = \\gl.drawElements(mode, count, type, offset); }, Func{ .name = "glEnable", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, }, .ret = "void", .js = \\gl.enable(x); }, Func{ .name = "glEnableVertexAttribArray", .args = &[_]Arg{ .{ .name = "x", .type = "c_uint" }, }, .ret = "void", .js = \\gl.enableVertexAttribArray(x); }, // TODO - glFinish // TODO - glFlush // TODO - glFramebufferRenderbuffer Func{ .name = "glFramebufferTexture2D", .args = &[_]Arg{ .{ .name = "target", .type = "GLenum" }, .{ .name = "attachment", .type = "GLenum" }, .{ .name = "textarget", .type = "GLenum" }, .{ .name = "texture", .type = "GLuint" }, .{ .name = "level", .type = "GLint" }, }, .ret = "void", .js = \\gl.framebufferTexture2D(target, attachment, textarget, glTextures[texture], level); }, Func{ .name = "glFrontFace", .args = &[_]Arg{ .{ .name = "mode", .type = "GLenum" }, }, .ret = "void", .js = \\gl.frontFace(mode); }, // TODO - glGenerateMipmap // TODO - glGetActiveAttrib // TODO - glGetActiveUniform // TODO - glGetAttachedShaders Func{ .name = "glGetAttribLocation", .args = &[_]Arg{ .{ .name = "program_id", .type = "c_uint" }, .{ .name = "name", .type = "SLICE" }, }, .ret = "c_int", .js = \\return gl.getAttribLocation(glPrograms[program_id], name); }, // TODO - glGetBufferParameter // TODO - glGetContextAttributes Func{ .name = "glGetError", .args = &[_]Arg{}, .ret = "c_int", .js = \\return gl.getError(); }, // TODO - glGetExtension // TODO - glGetFramebufferAttachmentParameter // TODO - glGetParameter // TODO - glGetProgramInfoLog // TODO - glGetProgramParameter // TODO - glGetRenderbufferParameter // TODO - glGetShaderInfoLog Func{ .name = "glGetShaderInfoLog", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, .{ .name = "maxLength", .type = "GLsizei" }, .{ .name = "length", .type = "?*GLsizei" }, .{ .name = "infoLog", .type = "?[*]u8" }, }, .ret = "void", .js = \\writeCharStr(infoLog, maxLength, length, gl.getShaderInfoLog(glShaders[shader])); }, // TODO - glGetShaderParameter // TODO - glGetShaderPrecisionFormat // TODO - glGetShaderSource // TODO - glGetSupportedExtensions // TODO - glGetTexParameter // TODO - glGetUniform Func{ .name = "glGetUniformLocation", .args = &[_]Arg{ .{ .name = "program_id", .type = "c_uint" }, .{ .name = "name", .type = "SLICE" }, }, .ret = "c_int", .js = \\glUniformLocations.push(gl.getUniformLocation(glPrograms[program_id], name)); \\return glUniformLocations.length - 1; }, // TODO - glGetVertexAttrib // TODO - glGetVertexAttribOffset // TODO - glHint // TODO - glIsBuffer // TODO - glIsContextLost // TODO - glIsEnabled // TODO - glIsFramebuffer // TODO - glIsProgram // TODO - glIsRenderbuffer // TODO - glIsShader // TODO - glIsTexture // TODO - glLineWidth Func{ .name = "glLinkProgram", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, }, .ret = "void", .js = \\gl.linkProgram(glPrograms[program]); }, Func{ .name = "getProgramLinkStatus", .args = &[_]Arg{ .{ .name = "program", .type = "c_uint" }, }, .ret = "GLboolean", .js = \\return gl.getProgramParameter(glPrograms[program], gl.LINK_STATUS); }, Func{ .name = "glGetProgramInfoLog", .args = &[_]Arg{ .{ .name = "program", .type = "GLuint" }, .{ .name = "maxLength", .type = "GLsizei" }, .{ .name = "length", .type = "?*GLsizei" }, .{ .name = "infoLog", .type = "?[*]u8" }, }, .ret = "void", .js = \\writeCharStr(infoLog, maxLength, length, gl.getProgramInfoLog(glPrograms[program])); }, Func{ .name = "glPixelStorei", .args = &[_]Arg{ .{ .name = "pname", .type = "GLenum" }, .{ .name = "param", .type = "GLint" }, }, .ret = "void", .js = \\gl.pixelStorei(pname, param); }, // TODO - glPolygonOffset // TODO - glReadPixels // TODO - glRenderbufferStorage // TODO - glSampleCoverage // TODO - glScissor Func{ .name = "glShaderSource", .args = &[_]Arg{ .{ .name = "shader", .type = "GLuint" }, .{ .name = "string", .type = "SLICE" }, }, .ret = "void", .js = \\gl.shaderSource(glShaders[shader], string); }, // TODO - glStencilFunc // TODO - glStencilFuncSeparate // TODO - glStencilMask // TODO - glStencilMaskSeparate // TODO - glStencilOp // TODO - glStencilOpSeparate Func{ .name = "glTexImage2D", // FIXME - take slice for data. note it needs to be optional .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "level", .type = "c_uint" }, .{ .name = "internal_format", .type = "c_uint" }, .{ .name = "width", .type = "c_int" }, .{ .name = "height", .type = "c_int" }, .{ .name = "border", .type = "c_uint" }, .{ .name = "format", .type = "c_uint" }, .{ .name = "type", .type = "c_uint" }, .{ .name = "data_ptr", .type = "?[*]const u8" }, .{ .name = "data_len", .type = "c_uint" }, }, .ret = "void", .js = \\// FIXME - look at data_ptr, not data_len, to determine NULL? \\const data = data_len > 0 ? new Uint8Array(getMemory().buffer, data_ptr, data_len) : null; \\gl.texImage2D(target, level, internal_format, width, height, border, format, type, data); }, Func{ .name = "glTexParameterf", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "pname", .type = "c_uint" }, .{ .name = "param", .type = "f32" }, }, .ret = "void", .js = \\gl.texParameterf(target, pname, param); }, Func{ .name = "glTexParameteri", .args = &[_]Arg{ .{ .name = "target", .type = "c_uint" }, .{ .name = "pname", .type = "c_uint" }, .{ .name = "param", .type = "c_uint" }, }, .ret = "void", .js = \\gl.texParameteri(target, pname, param); }, // TODO - glTexSubImage2D Func{ .name = "glUniform1f", .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "x", .type = "f32" }, }, .ret = "void", .js = \\gl.uniform1f(glUniformLocations[location_id], x); }, // TODO - glUniform1fv Func{ .name = "glUniform1i", .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "x", .type = "c_int" }, }, .ret = "void", .js = \\gl.uniform1i(glUniformLocations[location_id], x); }, // TODO - glUniform1iv // TODO - glUniform2f // TODO - glUniform2fv // TODO - glUniform2i // TODO - glUniform2iv // TODO - glUniform3f // TODO - glUniform3fv // TODO - glUniform3i // TODO - glUniform3iv Func{ .name = "glUniform4f", .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "x", .type = "f32" }, .{ .name = "y", .type = "f32" }, .{ .name = "z", .type = "f32" }, .{ .name = "w", .type = "f32" }, }, .ret = "void", .js = \\gl.uniform4f(glUniformLocations[location_id], x, y, z, w); }, // TODO - glUniform4fv // TODO - glUniform4i // TODO - glUniform4iv // TODO - glUniformMatrix2fv // TODO - glUniformMatrix3fv Func{ .name = "glUniformMatrix4fv", // FIXME - take three args, not four.. transpose should be second arg .args = &[_]Arg{ .{ .name = "location_id", .type = "c_int" }, .{ .name = "data_len", .type = "c_int" }, .{ .name = "transpose", .type = "c_uint" }, .{ .name = "data_ptr", .type = "[*]const f32" }, }, .ret = "void", .js = \\const floats = new Float32Array(getMemory().buffer, data_ptr, data_len * 16); \\gl.uniformMatrix4fv(glUniformLocations[location_id], transpose, floats); }, Func{ .name = "glUseProgram", .args = &[_]Arg{ .{ .name = "program_id", .type = "c_uint" }, }, .ret = "void", .js = \\gl.useProgram(glPrograms[program_id]); }, // TODO - glValidateProgram // TODO - glVertexAttrib1f // TODO - glVertexAttrib1fv // TODO - glVertexAttrib2f // TODO - glVertexAttrib2fv // TODO - glVertexAttrib3f // TODO - glVertexAttrib3fv // TODO - glVertexAttrib4f // TODO - glVertexAttrib4fv Func{ .name = "glVertexAttribPointer", .args = &[_]Arg{ .{ .name = "attrib_location", .type = "c_uint" }, .{ .name = "size", .type = "c_uint" }, .{ .name = "type", .type = "c_uint" }, .{ .name = "normalize", .type = "c_uint" }, .{ .name = "stride", .type = "c_uint" }, .{ .name = "offset", .type = "?*c_void" }, }, .ret = "void", .js = \\gl.vertexAttribPointer(attrib_location, size, type, normalize, stride, offset); }, Func{ .name = "glViewport", .args = &[_]Arg{ .{ .name = "x", .type = "c_int" }, .{ .name = "y", .type = "c_int" }, .{ .name = "width", .type = "c_int" }, .{ .name = "height", .type = "c_int" }, }, .ret = "void", .js = \\gl.viewport(x, y, width, height); }, }; fn nextNewline(s: []const u8) usize { for (s) |ch, i| { if (ch == '\n') { return i; } } return s.len; } fn writeZigFile(filename: []const u8) !void { const file = try std.fs.cwd().createFile(filename, .{}); defer file.close(); var stream = file.outStream(); try stream.print("{}\n\n", .{zig_top}); for (funcs) |func| { const any_slice = for (func.args) |arg| { if (std.mem.eql(u8, arg.type, "SLICE")) { break true; } } else false; // https://github.com/ziglang/zig/issues/3882 const fmtarg_pub = if (any_slice) "" else "pub "; const fmtarg_suf = if (any_slice) "_" else ""; try stream.print("{}extern fn {}{}(", .{ fmtarg_pub, func.name, fmtarg_suf }); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}_ptr: [*]const u8, {}_len: c_uint", .{ arg.name, arg.name }); } else { try stream.print("{}: {}", .{ arg.name, arg.type }); } } try stream.print(") {};\n", .{func.ret}); if (any_slice) { try stream.print("pub fn {}(", .{func.name}); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}: []const u8", .{arg.name}); } else { try stream.print("{}: {}", .{ arg.name, arg.type }); } } try stream.print(") {} {{\n", .{func.ret}); // https://github.com/ziglang/zig/issues/3882 const fmtarg_ret = if (std.mem.eql(u8, func.ret, "void")) "" else "return "; try stream.print(" {}{}_(", .{ fmtarg_ret, func.name }); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}.ptr, {}.len", .{ arg.name, arg.name }); } else { try stream.print("{}", .{arg.name}); } } try stream.print(");\n", .{}); try stream.print("}}\n", .{}); } } } fn writeJsFile(filename: []const u8) !void { const file = try std.fs.cwd().createFile(filename, .{}); defer file.close(); var stream = file.outStream(); try stream.print("{}\n", .{js_top}); try stream.print(" return {{\n", .{}); for (funcs) |func| { const any_slice = for (func.args) |arg| { if (std.mem.eql(u8, arg.type, "SLICE")) { break true; } } else false; // https://github.com/ziglang/zig/issues/3882 const fmtarg_suf = if (any_slice) "_" else ""; try stream.print(" {}{}(", .{ func.name, fmtarg_suf }); for (func.args) |arg, i| { if (i > 0) { try stream.print(", ", .{}); } if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print("{}_ptr, {}_len", .{ arg.name, arg.name }); } else { try stream.print("{}", .{arg.name}); } } try stream.print(") {{\n", .{}); for (func.args) |arg| { if (std.mem.eql(u8, arg.type, "SLICE")) { try stream.print(" const {} = readCharStr({}_ptr, {}_len);\n", .{ arg.name, arg.name, arg.name }); } } var start: usize = 0; while (start < func.js.len) { const rel_newline_pos = nextNewline(func.js[start..]); try stream.print(" {}\n", .{func.js[start .. start + rel_newline_pos]}); start += rel_newline_pos + 1; } try stream.print(" }},\n", .{}); } try stream.print(" }};\n", .{}); try stream.print("{}\n", .{js_bottom}); } pub fn main() !void { try writeZigFile("src/platform/web/webgl_generated.zig"); try writeJsFile("js/webgl.js"); }
https://raw.githubusercontent.com/leroycep/snake-game/9c578be67880f3f02ef25f5a96eb01ac27136a17/tools/webgl_generate.zig
const std = @import("std"); const hyperia = @import("hyperia.zig"); const SpinLock = hyperia.sync.SpinLock; const math = std.math; const time = std.time; const testing = std.testing; pub const Options = struct { // max_concurrent_attempts: usize, // TODO(kenta): use a cancellable semaphore to limit max number of concurrent attempts failure_threshold: usize, reset_timeout: usize, }; pub fn CircuitBreaker(comptime opts: Options) type { return struct { const Self = @This(); pub const State = enum { closed, open, half_open, }; lock: SpinLock = .{}, failure_count: usize = 0, last_failure_time: usize = 0, pub fn init(state: State) Self { return switch (state) { .closed => .{}, .half_open => .{ .failure_count = math.maxInt(usize) }, .open => .{ .failure_count = math.maxInt(usize), .last_failure_time = math.maxInt(usize) }, }; } pub fn run(self: *Self, current_time: usize, closure: anytype) !void { switch (self.query()) { .closed, .half_open => { closure.call() catch { self.reportFailure(current_time); return error.Failed; }; self.reportSuccess(); }, .open => return error.Broken, } } pub fn query(self: *Self, current_time: usize) State { const held = self.lock.acquire(); defer held.release(); if (self.failure_count >= opts.failure_threshold) { if (math.sub(usize, current_time, self.last_failure_time) catch 0 <= opts.reset_timeout) { return .open; } return .half_open; } return .closed; } pub fn reportFailure(self: *Self, current_time: usize) void { const held = self.lock.acquire(); defer held.release(); self.failure_count = math.add(usize, self.failure_count, 1) catch opts.failure_threshold; self.last_failure_time = current_time; } pub fn reportSuccess(self: *Self) void { const held = self.lock.acquire(); defer held.release(); self.failure_count = 0; self.last_failure_time = 0; } }; } test { testing.refAllDecls(CircuitBreaker(.{ .failure_threshold = 10, .reset_timeout = 1000 })); } test "circuit_breaker: init and query state" { const TestBreaker = CircuitBreaker(.{ .failure_threshold = 10, .reset_timeout = 1000 }); const current_time = @intCast(usize, time.milliTimestamp()); testing.expect(TestBreaker.init(.open).query(current_time) == .open); testing.expect(TestBreaker.init(.closed).query(current_time) == .closed); testing.expect(TestBreaker.init(.half_open).query(current_time) == .half_open); }
https://raw.githubusercontent.com/lithdew/hyperia/c1d166f81b6f011d9a23ef818b620e68eee3f49a/circuit_breaker.zig
const std = @import("std"); const utils = @import("utils"); pub fn main() !void { try utils.main(&execute); } var known_springs: std.ArrayList([]const u8) = undefined; var known_groups: std.ArrayList([]const i32) = undefined; var known_matches: std.ArrayList(u64) = undefined; fn execute(text: []const u8, allocator: std.mem.Allocator) !u64 { var sum: u64 = 0; var springs_list = std.ArrayList(std.ArrayList(u8)).init(allocator); defer { for (springs_list.items) |list| list.deinit(); springs_list.deinit(); } var groups_list = std.ArrayList(std.ArrayList(i32)).init(allocator); defer { for (groups_list.items) |list| list.deinit(); groups_list.deinit(); } known_springs = @TypeOf(known_springs).init(allocator); defer known_springs.deinit(); known_groups = @TypeOf(known_groups).init(allocator); defer known_groups.deinit(); known_matches = @TypeOf(known_matches).init(allocator); defer known_matches.deinit(); var lines_it = utils.tokenize(text, "\r\n"); while (lines_it.next()) |line| { var line_it = utils.tokenize(line, " "); const springs = line_it.next().?; var groups = std.ArrayList(i32).init(allocator); defer groups.deinit(); var groups_it = utils.tokenize(line_it.next().?, ","); while (groups_it.next()) |group_string| { const group = try utils.parseInt(i32, group_string); try groups.append(group); } try springs_list.append(std.ArrayList(u8).init(allocator)); var unfolded_springs = &springs_list.items[springs_list.items.len - 1]; try groups_list.append(std.ArrayList(i32).init(allocator)); var unfolded_groups = &groups_list.items[groups_list.items.len - 1]; for (0..5) |i| { if (i > 0) try unfolded_springs.append('?'); try unfolded_springs.appendSlice(springs); try unfolded_groups.appendSlice(groups.items); } const matches = try findMatches(unfolded_springs.items, unfolded_groups.items); sum += matches; } return sum; } fn findCachedResult(springs: []const u8, groups: []const i32) ?u64 { for (known_springs.items, 0..) |known_s, index| { if (std.meta.eql(springs, known_s)) { const known_g = known_groups.items[index]; if (std.meta.eql(groups, known_g)) { const known_m = known_matches.items[index]; return known_m; } } } return null; } fn storeResult(springs: []const u8, groups: []const i32, matches: u64) !void { try known_springs.append(springs); try known_groups.append(groups); try known_matches.append(matches); } fn findMatches(springs: []const u8, groups: []const i32) !u64 { if (findCachedResult(springs, groups)) |cached| { return cached; } var matches: u64 = 0; const current_group: usize = @intCast(groups[0]); const remaining_groups = groups[1..]; var required_length = current_group; for (remaining_groups) |group| required_length += @intCast(1 + group); var start_index: usize = 0; outer: while (springs.len - start_index >= required_length) : (start_index += 1) { const test_group = springs[start_index .. start_index + current_group]; for (test_group) |char| { if (char == '.') { continue :outer; } } for (springs[0..start_index]) |char| { if (char == '#') { continue :outer; } } if (remaining_groups.len == 0) { for (springs[start_index + current_group ..]) |char| { if (char == '#') { continue :outer; } } matches += 1; continue :outer; } if (springs[start_index + current_group] == '#') { continue :outer; } matches += try findMatches(springs[start_index + current_group + 1 ..], remaining_groups); } try storeResult(springs, groups, matches); return matches; } test { const text = @embedFile("example.txt"); const expected: u64 = 525152; const result = try execute(text, std.testing.allocator); try std.testing.expectEqual(expected, result); }
https://raw.githubusercontent.com/GigaGrunch/zig-advent-of-code/8f80de82aa525ea526fd87849d10e83dfe16d5dc/2023/day12/day12.zig
const fmath = @import("index.zig"); pub fn nan(comptime T: type) -> T { switch (T) { f32 => @bitCast(f32, fmath.nan_u32), f64 => @bitCast(f64, fmath.nan_u64), else => @compileError("nan not implemented for " ++ @typeName(T)), } }
https://raw.githubusercontent.com/tiehuis/zig-fmath/d563c833c7b6f49097de9f3dd1d14b82fead6a38/src/nan.zig
const std = @import("std"); const Self = @This(); /// The $4010 register that sets the sample rate and loop. const SampleRegister = packed struct { send_irq: bool = false, loop: bool = false, _unused: u2 = 0, rate: u4 = 0, }; sample: SampleRegister = .{}, sample_rate: u32 = 0, // register $4010 sample_length: u8 = 0, sample_address: u16 = 0
https://raw.githubusercontent.com/srijan-paul/nez/a07ab1121f256b4ce74a85bb94c87da9624a0c5e/src/apu.zig
const std = @import("std"); const io = @import("../../bus/io.zig"); const Scheduler = @import("../../scheduler.zig").Scheduler; const ToneSweep = @import("../ToneSweep.zig"); const Tone = @import("../Tone.zig"); const Self = @This(); pub const interval: u64 = (1 << 24) / (1 << 22); pos: u3, sched: *Scheduler, timer: u16, pub fn init(sched: *Scheduler) Self { return .{ .timer = 0, .pos = 0, .sched = sched, }; } pub fn reset(self: *Self) void { self.timer = 0; self.pos = 0; } /// Scheduler Event Handler for Square Synth Timer Expire pub fn onSquareTimerExpire(self: *Self, comptime T: type, nrx34: io.Frequency, late: u64) void { comptime std.debug.assert(T == ToneSweep or T == Tone); self.pos +%= 1; self.timer = (@as(u16, 2048) - nrx34.frequency.read()) * 4; self.sched.push(.{ .ApuChannel = if (T == ToneSweep) 0 else 1 }, @as(u64, self.timer) * interval -| late); } /// Reload Square Wave Timer pub fn reload(self: *Self, comptime T: type, value: u11) void { comptime std.debug.assert(T == ToneSweep or T == Tone); const channel = if (T == ToneSweep) 0 else 1; self.sched.removeScheduledEvent(.{ .ApuChannel = channel }); const tmp = (@as(u16, 2048) - value) * 4; // What Freq Timer should be assuming no weird behaviour self.timer = (tmp & ~@as(u16, 0x3)) | self.timer & 0x3; // Keep the last two bits from the old timer; self.sched.push(.{ .ApuChannel = channel }, @as(u64, self.timer) * interval); } pub fn sample(self: *const Self, nrx1: io.Duty) i8 { const pattern = nrx1.pattern.read(); const i = self.pos ^ 7; // index of 0 should get highest bit const result = switch (pattern) { 0b00 => @as(u8, 0b00000001) >> i, // 12.5% 0b01 => @as(u8, 0b00000011) >> i, // 25% 0b10 => @as(u8, 0b00001111) >> i, // 50% 0b11 => @as(u8, 0b11111100) >> i, // 75% }; return if (result & 1 == 1) 1 else -1; }
https://raw.githubusercontent.com/paoda/zba/b4830326ffa53f4361494eff8d3d07c0869eb67d/src/core/apu/signal/Square.zig
const std = @import("std"); const zul = @import("zul"); const zuckdb = @import("zuckdb"); const logdk = @import("logdk.zig"); const json = std.json; const Allocator = std.mem.Allocator; const ParseOptions = json.ParseOptions; pub const Event = struct { map: std.StringHashMapUnmanaged(Value), pub const List = struct { created: i64, events: []Event, arena: *std.heap.ArenaAllocator, pub fn deinit(self: *const List) void { const arena = self.arena; const allocator = arena.child_allocator; arena.deinit(); allocator.destroy(arena); } }; pub fn get(self: *const Event, field: []const u8) ?Value { return self.map.get(field); } pub fn fieldCount(self: *const Event) usize { return @intCast(self.map.count()); } pub const DataType = enum { tinyint, smallint, integer, bigint, utinyint, usmallint, uinteger, ubigint, double, bool, null, string, json, list, date, time, timestamp, uuid, }; pub const Value = union(DataType) { tinyint: i8, smallint: i16, integer: i32, bigint: i64, utinyint: u8, usmallint: u16, uinteger: u32, ubigint: u64, double: f64, bool: bool, null: void, string: []const u8, json: []const u8, list: Value.List, // might be nice to have more abstract types here, like a zul.Date, zul.Time and zul.DateTime // but in the scale of things, it's the same and having the duckdb type directly // here makes inserting into the dataset easier (which is nice, because that code // is already complicated) date: zuckdb.Date, time: zuckdb.Time, timestamp: i64, // we store this direclty as an i128 (which is what we insert into the appender) // because we parse this from a string using `zuckdb.encodeUUID` and that's // what it gives us. We could store the []const u8, but then we'd end up // parsing it twice: once to see if it IS a uuid and then once to store it. uuid: i128, pub const List = struct { json: []const u8, values: []Value, }; pub fn tryParse(self: *Value) ?Value { switch (self.*) { .string => |s| return tryParseValue(s), .list => |l| { // Wish we didn't have to do this, but without it, it would be impossible // to insert a date[], time[] or timestamptz[]. for (l.values, 0..) |v, i| { switch (v) { .string => |s| if (tryParseValue(s)) |new| { l.values[i] = new; }, else => {}, } } // This is a bit hackish. Even if we parsed members of the list, // we still return null, because we internally mutated the list. return null; }, else => return null, } } }; pub fn parse(allocator: Allocator, input: []const u8) !Event.List { const created = std.time.microTimestamp(); const arena = try allocator.create(std.heap.ArenaAllocator); errdefer allocator.destroy(arena); arena.* = std.heap.ArenaAllocator.init(allocator); errdefer arena.deinit(); const aa = arena.allocator(); const owned = try aa.dupe(u8, input); var scanner = json.Scanner.initCompleteInput(aa, owned); defer scanner.deinit(); const events = switch (try scanner.next()) { .array_begin => try Parser.bulk(aa, &scanner), .object_begin => try Parser.singleAsList(aa, &scanner), else => return error.UnexpectedToken, }; return .{ .created = created, .arena = arena, .events = events, }; } }; const Parser = struct { allocator: Allocator, map: std.StringHashMapUnmanaged(Event.Value), const Error = json.ParseError(json.Scanner); fn bulk(aa: Allocator, scanner: *json.Scanner) ![]Event { var count: usize = 0; var events = try aa.alloc(Event, 10); while (true) { switch (try scanner.next()) { .object_begin => {}, .array_end => break, else => return error.UnexpectedToken, } if (try single(aa, scanner)) |event| { if (count == events.len) { events = try aa.realloc(events, events.len + 10); } events[count] = event; count += 1; } } switch (try scanner.next()) { .end_of_document => return events[0..count], else => return error.UnexpectedToken, } } fn singleAsList(aa: Allocator, scanner: *json.Scanner) ![]Event { const event = try single(aa, scanner) orelse return &[_]Event{}; var events = try aa.alloc(Event, 1); events[0] = event; return events; } fn single(aa: Allocator, scanner: *json.Scanner) !?Event { var parser = Parser{ .allocator = aa, .map = std.StringHashMapUnmanaged(Event.Value){}, }; try parser.parseObject(aa, scanner); return if (parser.map.count() == 0) null else .{.map = parser.map}; } fn parseObject(self: *Parser, allocator: Allocator, scanner: *json.Scanner) Error!void { var field_name: []const u8 = undefined; while (true) { switch (try scanner.nextAlloc(allocator, .alloc_always)) { .allocated_string => |field| { for (field, 0..) |c, i| { field[i] = std.ascii.toLower(c); } field_name = field; const token = try scanner.nextAlloc(allocator, .alloc_if_needed); switch (try parseValue(allocator, scanner, false, token)) { .value => |v| try self.map.put(self.allocator, field_name, v), .nested_list => unreachable, // since break_on_list is false, this cannot happen, as a list will always be returned as a value } }, .object_end => break, .end_of_document => return, else => |x| { std.debug.print("{any}\n", .{x}); unreachable; }, } } } const ParseValueResult = union(enum) { value: Event.Value, nested_list: void, }; fn parseValue(allocator: Allocator, scanner: *json.Scanner, break_on_list: bool, token: json.Token) Error!ParseValueResult { switch (token) { .string, .allocated_string => |value| return .{.value = .{.string = value}}, .null => return .{.value = .{.null = {}}}, .true => return .{.value = .{.bool = true}}, .false => return .{.value = .{.bool = false}}, .number, .allocated_number => |str| { const result = try parseInteger(str); return .{.value = try result.toNumericValue(str)}; }, .array_begin => { if (break_on_list) { // Our caller doesn't want us to parse a list. So we return, telling // our caller that we have a list return .{.nested_list = {}}; } // This is messy, but we don't know if this should be treated as a list // or as a json. We treat it as json if it has a nested list. // in case we need to treat this as json, we'll grab the position and // stack height of the parser // -1 because we alreayd consumed the '[' const array_start = scanner.cursor - 1; // -1 becuase we're already increased the scanner's stack height from the array_begin const stack_height = scanner.stackHeight() - 1; var arr = std.ArrayList(Event.Value).init(allocator); while (true) { const sub_token = try scanner.nextAlloc(allocator, .alloc_if_needed); switch (sub_token) { .array_end => break, else => switch (try parseValue(allocator, scanner, true, sub_token)) { .value => |v| try arr.append(v), .nested_list => { if (break_on_list) { // If this is true, then we aren't the root list, so we just propagate this up return .{.nested_list = {}}; } try scanner.skipUntilStackHeight(stack_height); return .{.value = .{.json = scanner.input[array_start..scanner.cursor]}}; } } } } return .{.value = .{.list = .{.json = scanner.input[array_start..scanner.cursor], .values = arr.items}}}; }, .object_begin => { // -1 because we already consumed the '{' const object_start = scanner.cursor - 1; // -1 because we've already increased the scanner's stack height from this object_begin try scanner.skipUntilStackHeight(scanner.stackHeight() - 1); return .{.value = .{.json = scanner.input[object_start..scanner.cursor]}}; }, else => unreachable, } } }; // parseInteger is used both when parsing the JSON input as well as when trying to // parse a string value. When parsing the JSON input, we _know_ this has to be a number // but when parsing a string value, we're only trying to see if it works. // We don't use std.fmt.parseInt because we don't know the type of the integer. // If we use `u64`, we won't be able to represent negatives. If we use `i64` we // won't be able to fully represent `u64. const JsonIntegerResult = struct { value: u64, negative: bool, rest: []const u8, // Try to turn the JsonIntegerResult into a Event.Value. fn toNumericValue(self: JsonIntegerResult, input: []const u8) !Event.Value { if (self.rest.len > 0) { // We had more data than just our integer. // A bit of a waste to throw away self.value, but parsing floats is hard // and I rather just use std at this point. return .{.double = try std.fmt.parseFloat(f64, input)}; } const value = self.value; if (self.negative) { if (value == 0) return .{.double = -0.0}; if (value <= 128) return .{.tinyint = @intCast(-@as(i64, @intCast(value)))}; if (value <= 32768) return .{.smallint = @intCast(-@as(i64, @intCast(value)))}; if (value <= 2147483648) return .{.integer = @intCast(-@as(i64, @intCast(value)))}; if (value <= 9223372036854775807) return .{.bigint = -@as(i64, @intCast(value))}; // as far as I can tell, this is the only way to cast a 9223372036854775808 u64 into an i64 -9223372036854775808 if (value == 9223372036854775808) return .{.bigint = @intCast(-@as(i128, @intCast(value)))}; return error.InvalidNumber; } if (value <= 255) return .{.utinyint = @intCast(value)}; if (value <= 65535) return .{.usmallint = @intCast(value)}; if (value <= 4294967295) return .{.uinteger = @intCast(value)}; if (value <= 18446744073709551615) return .{.ubigint = @intCast(value)}; return error.InvalidNumber; } }; fn parseInteger(str: []const u8) error{InvalidNumber}!JsonIntegerResult { std.debug.assert(str.len != 0); var pos: usize = 0; var negative = false; if (str[0] == '-') { pos = 1; negative = true; } var n: u64 = 0; for (str[pos..]) |b| { if (b < '0' or b > '9') { break; } pos += 1; { n, const overflowed = @mulWithOverflow(n, 10); if (overflowed != 0) { return error.InvalidNumber; } } { n, const overflowed = @addWithOverflow(n, @as(u64, @intCast(b - '0'))); if (overflowed != 0) { return error.InvalidNumber; } } } return .{ .value = n, .negative = negative, .rest = str[pos..], }; } fn tryParseValue(s: []const u8) ?Event.Value { if (s.len == 0) return null; if (s.len >= 20) { // this does its own length check, but we put it in the >= 20 since it'll // avoid the function call for common short strings if (zuckdb.encodeUUID(s)) |v| { return .{.uuid = v}; } else |_| {} if (zul.DateTime.parse(s, .rfc3339)) |v| { return .{.timestamp = v.unix(.microseconds)}; } else |_| {} } if (s.len == 10) { if (zul.Date.parse(s, .rfc3339)) |v| { return .{.date = .{.year = v.year, .month = @intCast(v.month), .day = @intCast(v.day)}}; } else |_| {} } if (s.len >= 5) { if (zul.Time.parse(s, .rfc3339)) |v| { return .{.time = .{.hour = @intCast(v.hour), .min = @intCast(v.min), .sec = @intCast(v.sec), .micros = @intCast(v.micros)}}; } else |_| {} } if (parseInteger(s)) |result| { // parseInteger can return a result that is NOT an integer/float. // given "1234abc", it'll parse "1234" and set .rest to "abc". It's only // the combination of parseInteger and toNumericValue that definitively // detect an integer or float. if (result.toNumericValue(s)) |value| { return value; } else |_| {} } else |_| {} if (std.ascii.eqlIgnoreCase(s, "true")) { return .{.bool = true}; } if (std.ascii.eqlIgnoreCase(s, "false")) { return .{.bool = false}; } return null; } const t = logdk.testing; test "Event: parse non-array or non-object" { try t.expectError(error.UnexpectedToken, Event.parse(t.allocator, "123")); } test "Event: parse empty" { const event_list = try Event.parse(t.allocator, "{}"); defer event_list.deinit(); try t.expectEqual(0, event_list.events.len); } test "Event: parse empty list" { const event_list = try Event.parse(t.allocator, "[]"); defer event_list.deinit(); try t.expectEqual(0, event_list.events.len); } test "Event: parse list of empty events" { const event_list = try Event.parse(t.allocator, "[{}, {}, {}]"); defer event_list.deinit(); try t.expectEqual(0, event_list.events.len); } test "Event: parse simple" { const event_list = try Event.parse(t.allocator, \\{ \\ "key_1": true, "another_key": false, \\ "key_3": null, \\ "KEY_4": "over 9000!!", \\ "a": 0, "b": 1, "c": 6999384751, "d": -1, "e": -867211, \\ "f1": 0.0, "f2": -0, "f3": 99.33929191, "f4": -1.49E10 \\} ); defer event_list.deinit(); try assertEvent(.{ .key_1 = Event.Value{.bool = true}, .another_key = Event.Value{.bool = false}, .key_3 = Event.Value{.null = {}}, .key_4 = Event.Value{.string = "over 9000!!"}, .a = Event.Value{.utinyint = 0}, .b = Event.Value{.utinyint = 1}, .c = Event.Value{.ubigint = 6999384751}, .d = Event.Value{.tinyint = -1}, .e = Event.Value{.integer = -867211}, // ints .f1 = Event.Value{.double = 0.0}, .f2 = Event.Value{.double = -0.0}, .f3 = Event.Value{.double = 99.33929191}, .f4 = Event.Value{.double = -1.49E10} }, event_list.events[0]); } test "Event: parse array" { const event_list = try Event.parse(t.allocator, "[{\"id\":1},{\"id\":2},{\"id\":3}]"); defer event_list.deinit(); try t.expectEqual(3, event_list.events.len); try assertEvent(.{.id = Event.Value{.utinyint = 1}}, event_list.events[0]); try assertEvent(.{.id = Event.Value{.utinyint = 2}}, event_list.events[1]); try assertEvent(.{.id = Event.Value{.utinyint = 3}}, event_list.events[2]); } test "Event: parse array past initial size" { const event_list = try Event.parse(t.allocator, \\ [ \\ {"id":1}, {"id":2}, {"id":3}, {"id":4}, {"id":5}, {"id":6}, {"id":7}, {"id":8}, {"id":9}, {"id":10}, \\ {"id":11}, {"id":12}, {"id":13}, {"id":14}, {"id":15}, {"id":16}, {"id":17}, {"id":18}, {"id":19}, {"id":20}, \\ {"id":21}, {"id":22}, {"id":23}, {"id":24}, {"id":25}, {"id":26}, {"id":27}, {"id":28}, {"id":29}, {"id":30}, \\ {"id":31}, {"id":32}, {"id":33}, {"id":34} \\ ] ); defer event_list.deinit(); try t.expectEqual(34, event_list.events.len); for (0..34) |i| { try assertEvent(.{.id = Event.Value{.utinyint = @intCast(i + 1)}}, event_list.events[i]); } } test "Event: parse nesting" { const event_list = try Event.parse(t.allocator, \\{ \\ "key_1": {}, \\ "key_2": { \\ "sub_1": true, \\ "sub_2": { "handle ": 1, "x": {"even": "more", "ok": true}} \\} \\} ); defer event_list.deinit(); try assertEvent(.{ .@"key_1" = Event.Value{.json = "{}"}, .@"key_2" = Event.Value{.json = "{\n \"sub_1\": true,\n \"sub_2\": { \"handle \": 1, \"x\": {\"even\": \"more\", \"ok\": true}}\n}"}, }, event_list.events[0]); } test "Event: parse list" { const event_list = try Event.parse(t.allocator, "{\"a\": [1, -9000], \"b\": [true, 56.78912, null, {\"abc\": \"123\"}]}"); defer event_list.deinit(); try assertEvent(.{ .a = Event.Value{.list = .{ .json = "[1, -9000]", .values = @constCast(&[_]Event.Value{.{.utinyint = 1}, .{.smallint = -9000}}) }}, .b = Event.Value{.list = .{ .json = "[true, 56.78912, null, {\"abc\": \"123\"}]", .values = @constCast(&[_]Event.Value{.{.bool = true}, .{.double = 56.78912}, .{.null = {}}, .{.json = "{\"abc\": \"123\"}"}}) }}, }, event_list.events[0]); } test "Event: parse nested list" { const event_list = try Event.parse(t.allocator, "{\"a\": [1, [true, null, \"hi\"]]}"); defer event_list.deinit(); try assertEvent(.{.a = Event.Value{.json = "[1, [true, null, \"hi\"]]"}}, event_list.events[0]); } test "Event: parse list simple" { const event_list = try Event.parse(t.allocator, "{\"a\": [9999, -128]}"); defer event_list.deinit(); try assertEvent(.{.a = Event.Value{.list = .{ .json = "[9999, -128]", .values = @constCast(&[_]Event.Value{.{.usmallint = 9999}, .{.tinyint = -128}}) }}}, event_list.events[0]); } test "Event: parse positive integer" { const event_list = try Event.parse(t.allocator, "{\"pos\": [0, 1, 255, 256, 65535, 65536, 4294967295, 4294967296, 18446744073709551615]}"); defer event_list.deinit(); try assertEvent(.{ .pos = Event.Value{.list = .{ .json = "[0, 1, 255, 256, 65535, 65536, 4294967295, 4294967296, 18446744073709551615]", .values = @constCast(&[_]Event.Value{ .{.utinyint = 0}, .{.utinyint = 1}, .{.utinyint = 255}, .{.usmallint = 256}, .{.usmallint = 65535}, .{.uinteger = 65536}, .{.uinteger = 4294967295}, .{.ubigint = 4294967296}, .{.ubigint = 18446744073709551615} }) }} }, event_list.events[0]); } test "Event: parse negative integer" { const event_list = try Event.parse(t.allocator, "{\"neg\": [-0, -1, -128, -129, -32768 , -32769, -2147483648, -2147483649, -9223372036854775807, -9223372036854775808]}"); defer event_list.deinit(); try assertEvent(.{ .neg = Event.Value{.list = .{ .json = "[-0, -1, -128, -129, -32768 , -32769, -2147483648, -2147483649, -9223372036854775807, -9223372036854775808]", .values = @constCast(&[_]Event.Value{ .{.double = -0.0}, .{.tinyint = -1}, .{.tinyint = -128}, .{.smallint = -129}, .{.smallint = -32768}, .{.integer = -32769}, .{.integer = -2147483648}, .{.bigint = -2147483649}, .{.bigint = -9223372036854775807}, .{.bigint = -9223372036854775808} }) }} }, event_list.events[0]); } test "Event: parse integer overflow" { try t.expectError(error.InvalidNumber, Event.parse(t.allocator, "{\"overflow\": 18446744073709551616}")); } test "Event: tryParse string" { // just sneak this in here var non_string = Event.Value{.bool = true}; try t.expectEqual(null, non_string.tryParse()); try t.expectEqual(null, testTryParseString("")); try t.expectEqual(null, testTryParseString("over 9000!")); try t.expectEqual(null, testTryParseString("9000!")); try t.expectEqual(null, testTryParseString("t")); try t.expectEqual(null, testTryParseString("falsey")); try t.expectEqual(null, testTryParseString("2005-1-1")); try t.expectEqual(null, testTryParseString("2025-13-01")); try t.expectEqual(null, testTryParseString("2025-11-31")); try t.expectEqual(null, testTryParseString("2025-11-31T00:00:00Z")); try t.expectEqual(null, testTryParseString("2025-12-31T00:00:00+12:30")); try t.expectEqual(true, testTryParseString("true").?.bool); try t.expectEqual(true, testTryParseString("TRUE").?.bool); try t.expectEqual(true, testTryParseString("True").?.bool); try t.expectEqual(true, testTryParseString("TrUe").?.bool); try t.expectEqual(false, testTryParseString("false").?.bool); try t.expectEqual(false, testTryParseString("FALSE").?.bool); try t.expectEqual(false, testTryParseString("False").?.bool); try t.expectEqual(false, testTryParseString("FaLsE").?.bool); try t.expectEqual(0, testTryParseString("0").?.utinyint); try t.expectEqual(-128, testTryParseString("-128").?.tinyint); try t.expectEqual(10000, testTryParseString("10000").?.usmallint); try t.expectEqual(-1234, testTryParseString("-1234").?.smallint); try t.expectEqual(394918485, testTryParseString("394918485").?.uinteger); try t.expectEqual(-999999912, testTryParseString("-999999912").?.integer); try t.expectEqual(7891235891098352, testTryParseString("7891235891098352").?.ubigint); try t.expectEqual(-111123456698832, testTryParseString("-111123456698832").?.bigint); try t.expectEqual(-323993.3231332, testTryParseString("-323993.3231332").?.double); try t.expectEqual(.{.year = 2025, .month = 1, .day = 2}, testTryParseString("2025-01-02").?.date); try t.expectEqual(.{.hour = 10, .min = 22, .sec = 0, .micros = 0}, testTryParseString("10:22").?.time); try t.expectEqual(.{.hour = 15, .min = 3, .sec = 59, .micros = 123456}, testTryParseString("15:03:59.123456").?.time); try t.expectEqual(1737385439123456, testTryParseString("2025-01-20T15:03:59.123456Z").?.timestamp); try t.expectEqual(-119391408245701198339858421598325797365, testTryParseString("262e0d19-d9d8-4892-8fe1-e421fe188e0b").?.uuid); try t.expectEqual(-119391408245701198339858421598325797365, testTryParseString("262E0D19-D9D8-4892-8FE1-E421FE188E0B").?.uuid); } test "Event: tryParse list" { { var l = Event.Value{.list = .{ .json = "", .values = @constCast(&[_]Event.Value{.{.string = "200"}, .{.bool = true}, .{.string = "9000!"}}) }}; try t.expectEqual(null, l.tryParse()); try t.expectEqual(200, l.list.values[0].utinyint); try t.expectEqual(true, l.list.values[1].bool); try t.expectEqual("9000!", l.list.values[2].string); } } fn testTryParseString(str: []const u8) ?Event.Value { var v = Event.Value{.string = str}; return v.tryParse(); } fn assertEvent(expected: anytype, actual: Event) !void { const fields = @typeInfo(@TypeOf(expected)).Struct.fields; try t.expectEqual(fields.len, actual.fieldCount()); inline for (fields) |f| { const field_name = f.name; switch (@field(expected, field_name)) { .list => |expected_list| { const actual_list = actual.map.get(field_name).?.list; for (expected_list.values, actual_list.values) |expect_list_value, actual_list_value| { try t.expectEqual(expect_list_value, actual_list_value); } try t.expectEqual(expected_list.json, actual_list.json); }, else => |expected_value| try t.expectEqual(expected_value, actual.map.get(field_name).?), } } }
https://raw.githubusercontent.com/karlseguin/logdk/3ddd23295bac2cd5441e9fcbffea2e204cbf9e72/src/event.zig
// بسم الله الرحمن الرحيم وبه نستعين const std = @import("std"); const print = std.debug.print; fn sumNums(iterator: anytype) !f32 { var sum: f32 = 0; // The ".next()" method of the iterator ***modifies (mutates)*** the internal state of the iterator to advance it to the next element, hence, it has to be "var"! while (iterator.next()) |number| { sum += std.fmt.parseFloat(f32, number) catch |err| { print("Failed to parse number: \"{s}\", with error: {!}\n", .{ number, err }); continue; }; } return sum; } pub fn main() !void { print("Enter numbers separated by whitespaces:\n", .{}); // Pre-allocate on the stack 1028 bytes to store user's input: // var input_buffer: [1024]u8 = undefined; // Continously read and parse user input: while (true) { // Pre-allocate (initialized as zeros) on the stack 1028 bytes to store user's input: var buffer: std.BoundedArray(u8, std.math.pow(usize, 32, 2)) = .{}; // contains ".buffer" and ".len" fields try std.io.getStdIn().reader().streamUntilDelimiter(buffer.writer(), '\n', 1024); const trimmed_string: []const u8 = std.mem.trim(u8, buffer.slice(), " "); // ".slice()" returns a truncated (up to delimiter) view of buffer if (std.mem.eql(u8, trimmed_string, "q")) { print("Existing program...\n\n", .{}); break; } var numbers = std.mem.tokenize(u8, trimmed_string, " "); // returns an iterator print("Sum of the numbers: {d:.2}\n", .{try sumNums(&numbers)}); } }
https://raw.githubusercontent.com/OSuwaidi/zig_intro/8fce69b42f2bcf36e4cd9d9247f2dc8f6609793a/src/stack_sum.zig
const std = @import("std"); const Hkdf = std.crypto.kdf.hkdf.HkdfSha256; /// Stored by the authenticator and used to derive all other secrets pub const MasterSecret = [Hkdf.prk_length]u8; /// Create a new, random master secret pub fn create_master_secret(rand: *const fn ([]u8) void) MasterSecret { var ikm: [32]u8 = undefined; var salt: [16]u8 = undefined; rand(ikm[0..]); rand(salt[0..]); return Hkdf.extract(&salt, &ikm); }
https://raw.githubusercontent.com/r4gus/fido2/08eaea16d68dba6642d3f4da880fb4d3a4043314/src/crypto/master_secret.zig
const std = @import("std"); const uv = @import("uv.zig"); const Buf = uv.Buf; const Cast = uv.Cast; const c = uv.c; const utils = uv.utils; /// Base handle pub const Handle = extern struct { /// Type of a base handle pub const Type = c.uv_handle_type; const Self = @This(); pub const UV = c.uv_handle_t; data: ?*anyopaque, loop: [*c]c.uv_loop_t, type: Type, close_cb: c.uv_close_cb, handle_queue: [2]?*anyopaque, u: extern union { fd: c_int, reserved: [4]?*anyopaque, }, next_closing: [*c]c.uv_handle_t, flags: c_uint, usingnamespace Cast(Self); usingnamespace HandleDecls; /// Returns the size of the given handle type pub fn handleSize(@"type": Type) usize { return c.uv_handle_size(@"type"); } }; /// Base handle declarations pub const HandleDecls = struct { /// Type definition for callback passed to `Stream.readStart` and `Udp.recvStart` pub const AllocCallback = ?fn (*Handle, usize, *Buf) callconv(.C) void; pub const AllocCallbackUV = c.uv_alloc_cb; /// Type definition for callback passed to `close` pub const CloseCallback = ?fn (*Handle) callconv(.C) void; pub const CloseCallbackUV = c.uv_close_cb; /// Returns `true` if the handle is active, `false` if it’s inactive pub fn isActive(handle: anytype) bool { return c.uv_is_active(Handle.toUV(handle)) != 0; } /// Returns `true` if the handle is closing or closed, `false` otherwise pub fn isClosing(handle: anytype) bool { return c.uv_is_closing(Handle.toUV(handle)) != 0; } /// Request handle to be closed pub fn close(handle: anytype, close_cb: CloseCallback) void { c.uv_close( Handle.toUV(handle), @ptrCast(CloseCallbackUV, close_cb), ); } /// Reference the given handle pub fn ref(handle: anytype) void { return c.uv_ref(Handle.toUV(handle)); } /// Un-reference the given handle pub fn unref(handle: anytype) void { return c.uv_unref(Handle.toUV(handle)); } /// Returns non-zero if the handle referenced, zero otherwise pub fn hasRef(handle: anytype) bool { return c.uv_has_ref(Handle.toUV(handle)) != 0; } }; /// Types of a base handle pub usingnamespace struct { pub const ASYNC = c.UV_ASYNC; pub const CHECK = c.UV_CHECK; pub const FILE = c.UV_FILE; pub const FS_EVENT = c.UV_FS_EVENT; pub const FS_POLL = c.UV_FS_POLL; pub const HANDLE = c.UV_HANDLE; pub const HANDLE_TYPE_MAX = c.UV_HANDLE_TYPE_MAX; pub const IDLE = c.UV_IDLE; pub const NAMED_PIPE = c.UV_NAMED_PIPE; pub const POLL = c.UV_POLL; pub const PREPARE = c.UV_PREPARE; pub const PROCESS = c.UV_PROCESS; pub const SIGNAL = c.UV_SIGNAL; pub const STREAM = c.UV_STREAM; pub const TCP = c.UV_TCP; pub const TIMER = c.UV_TIMER; pub const TTY = c.UV_TTY; pub const UDP = c.UV_UDP; pub const UNKNOWN_HANDLE = c.UV_UNKNOWN_HANDLE; };
https://raw.githubusercontent.com/paveloom-z/zig-libuv/511e491c0fa03d7d68e50686277ff980341e21f7/src/handle.zig
const c = @import("common.zig").c; const m = @import("raymath.zig"); const builtin = @import("builtin"); const std = @import("std"); const assert = std.debug.assert; const print = std.debug.print; const clamp = std.math.clamp; const is_web_target = (builtin.target.cpu.arch == .wasm32); pub const screenWidth = 800; pub const screenHeight = 600; // wasm entrypoint export fn web_main() void { if (is_web_target) { const cwasm = @cImport({ @cInclude("emscripten/emscripten.h"); }); c.InitWindow(screenWidth, screenHeight, "Tom's Rock"); init(); cwasm.emscripten_set_main_loop(renderFrame, 0, 1); c.CloseWindow(); } } const Enemy = struct { const ShieldStatus = enum { off, warning, on, }; pos: m.Vector2, time: f32, vel: m.Vector2 = .{ .x = 0, .y = 0 }, orbit_dir: f32 = 1, drop_prob: f32 = 0.006, shield_pattern: []const f32 = ([_]f32{ 3, 6, 9 })[0..], extractor: ?usize = null, const frame_times = [_]f32{ 3.0, 3.2, 4.0 }; const Self = @This(); fn shieldTime(self: Self) f32 { return @mod(self.time, self.shield_pattern[self.shield_pattern.len - 1]); } fn shieldStatus(self: Self) ShieldStatus { const cur_time = self.shieldTime(); var ii: usize = 0; for (self.shield_pattern) |t, i| { if (cur_time < t) { ii = i; break; } } return switch (ii % 3) { 0 => .off, 1 => .warning, 2 => .on, else => unreachable, }; } fn addTime(self: *Self, t: f32) void { self.time += t; } fn frame(self: Self) usize { var ii: usize = 0; const cur_time = @mod(self.time, frame_times[frame_times.len - 1]); for (frame_times) |t, i| { if (t > cur_time) { ii = i; break; } } return ii; } }; fn InPlaceArrayList(comptime T: type) type { return struct { data: std.ArrayList(T), free_mask: std.ArrayList(bool), const Self = @This(); const Iterator = struct { list: *const Self, i: i32 = -1, fn next(self: *Iterator) ?T { assert(self.list.data.items.len == self.list.free_mask.items.len); self.i += 1; while (self.i < self.list.data.items.len and self.list.free_mask.items[@intCast(usize, self.i)]) { self.i += 1; } if (0 <= self.i and self.i < self.list.data.items.len) { return self.list.data.items[@intCast(usize, self.i)]; } else { return null; } } }; fn get(self: Self, i: usize) ?T { if (self.free_mask.items[i]) { return null; } else { return self.data.items[i]; } } fn iterator(self: Self) Iterator { return .{ .list = &self }; } fn remove(self: Self, i: usize) T { self.free_mask.items[i] = true; return self.data.items[i]; } fn add(self: *Self, val: T) usize { var free_i: ?usize = null; for (self.free_mask.items) |is_free, i| { if (is_free) { free_i = i; break; } } if (free_i) |i| { self.data.items[i] = val; self.free_mask.items[i] = false; return i; } else { self.data.append(val) catch {}; self.free_mask.append(false) catch {}; return self.data.items.len - 1; } } fn clearRetainingCapacity(self: *Self) void { self.data.clearRetainingCapacity(); self.free_mask.clearRetainingCapacity(); } fn init(allocator: std.mem.Allocator) Self { return Self{ .data = std.ArrayList(T).init(allocator), .free_mask = std.ArrayList(bool).init(allocator), }; } fn clone(self: *Self) !Self { return Self{ .data = try self.data.clone(), .free_mask = try self.free_mask.clone(), }; } fn deinit(self: Self) void { self.data.deinit(); self.free_mask.deinit(); } }; } const BossState = enum { screech, idle, swoop_grab, hold, lasers, dead, }; const boss_foot_offset = m.Vector2{ .x = -20, .y = 56 }; const State = struct { tail_pos_storage: [13]m.Vector2 = [_]m.Vector2{ .{ .x = 395.1, .y = 203.5 }, .{ .x = 386.1, .y = 208.0 }, .{ .x = 379.9, .y = 216.0 }, .{ .x = 378.0, .y = 225.8 }, .{ .x = 380.7, .y = 235.5 }, .{ .x = 387.4, .y = 243.0 }, .{ .x = 396.7, .y = 246.8 }, .{ .x = 406.8, .y = 245.9 }, .{ .x = 415.4, .y = 240.7 }, .{ .x = 420.8, .y = 232.2 }, .{ .x = 421.8, .y = 222.2 }, .{ .x = 418.3, .y = 212.8 }, .{ .x = 411.0, .y = 205.9 }, }, old_tail_pos_storage: [13]m.Vector2 = [_]m.Vector2{ .{ .x = 395.1, .y = 203.5 }, .{ .x = 386.1, .y = 208.0 }, .{ .x = 379.9, .y = 216.0 }, .{ .x = 378.0, .y = 225.8 }, .{ .x = 380.7, .y = 235.5 }, .{ .x = 387.4, .y = 243.0 }, .{ .x = 396.7, .y = 246.8 }, .{ .x = 406.8, .y = 245.9 }, .{ .x = 415.4, .y = 240.7 }, .{ .x = 420.8, .y = 232.2 }, .{ .x = 421.8, .y = 222.2 }, .{ .x = 418.3, .y = 212.8 }, .{ .x = 411.0, .y = 205.9 }, }, tail_pos: []m.Vector2, tail_old_pos: []m.Vector2, expression: enum { neutral, angry, irritated, eye_closed, eye_squeezed_closed, }, boss: ?struct { position: c.Vector2, state: BossState, hold_l: ?u32, hold_r: ?u32, health: u32, state_time: f32, i: usize, }, enemies: std.BoundedArray(Enemy, 64), lasers: std.BoundedArray([2]m.Vector2, 32), lasers_rot: f32, lasers_rot_speed: f32, extractors: InPlaceArrayList(m.Vector2), planet_health: f32, zapped_time_left: f32, current_level: usize, const Self = @This(); fn clone(self: *Self) Self { var r = self.*; // FIXME: use a bounded array for this too r.extractors = self.extractors.clone() catch @panic("couldn't clone"); return r; } fn deinit(self: *Self) void { self.extractors.deinit(); } }; fn resetPosition() void { for (state.tail_pos_storage) |*p, i| { const theta = @intToFloat(f32, i) * std.math.pi / 10 - std.math.pi / 2.0; p.* = m.Vector2Add(c.Vector2{ .x = @cos(theta) * (planet_radius + player_radius), .y = @sin(theta) * (planet_radius + player_radius), }, center); state.old_tail_pos_storage[i] = p.*; } } fn bossStep() void { assert(boss_steps.len > 0); var boss_data = &state.boss.?; boss_data.i = (boss_data.i + 1) % boss_steps.len; setBossState(boss_steps[boss_data.i]); } fn setBossState(boss_state: BossState) void { prev_boss_state = state.boss.?.state; state.boss.?.state = boss_state; state.boss.?.state_time = 0; } const SpriteSheet = struct { texture: c.Texture, frames: usize, const Self = @This(); fn width(self: Self) f32 { return @intToFloat(f32, self.texture.width) / @intToFloat(f32, self.frames); } fn frameRect(self: Self, i: usize) c.Rectangle { return c.Rectangle{ .x = self.width() * @intToFloat(f32, i), .y = 0, .width = self.width(), .height = @intToFloat(f32, self.texture.height), }; } fn drawFrameEx(self: Self, pos: m.Vector2, rotation: f32, i: usize, alpha: f32) void { c.DrawTexturePro( self.texture, self.frameRect(i), c.Rectangle{ .x = pos.x, .y = pos.y, .width = self.width(), .height = @intToFloat(f32, self.texture.height), }, m.Vector2{ .x = self.width() / 2, .y = @intToFloat(f32, @divTrunc(self.texture.height, 2)), }, radiansToDegrees(rotation), c.Color{ .r = 255, .g = 255, .b = 255, .a = @floatToInt(u8, 255 * alpha) }, ); } fn drawFrame(self: Self, pos: m.Vector2, rotation: f32, i: usize) void { self.drawFrameEx(pos, rotation, i, 1); } }; // globals var state: State = .{ .tail_pos = &([0]m.Vector2{}), .tail_old_pos = &([0]m.Vector2{}), .expression = .eye_closed, .enemies = std.BoundedArray(Enemy, 64).init(0) catch unreachable, .lasers = std.BoundedArray([2]m.Vector2, 32).init(0) catch unreachable, .lasers_rot = 0, .lasers_rot_speed = 1, .extractors = InPlaceArrayList(m.Vector2).init(gpa.allocator()), .planet_health = 360, .zapped_time_left = 0, .current_level = 0, .boss = null, }; var stars = [_]m.Vector2{.{ .x = 0, .y = 0 }} ** 40; // assets var mongoose: SpriteSheet = undefined; var explosion: SpriteSheet = undefined; var extractor: SpriteSheet = undefined; var boss: SpriteSheet = undefined; var boss_white: c.Texture = undefined; var music: [5]c.Music = undefined; var current_music: []c.Music = &([0]c.Music{}); var explosion_sound: c.Sound = undefined; var big_explosion_sound: c.Sound = undefined; var zap_sound: c.Sound = undefined; var screech_sound: c.Sound = undefined; var hit_sound: c.Sound = undefined; var font: c.Font = undefined; const font_size = 30; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var rand: std.rand.DefaultPrng = undefined; const center = m.Vector2{ .x = screenWidth / 2, .y = screenHeight / 2 }; var planet_radius: f32 = 35; const player_radius = 2; const enemy_radius = 15; const boss_radius = 55; const GameplayState = enum { dead, alive, no_control, }; var gameplay_state: GameplayState = .alive; var coroutines: Coroutines = undefined; var ui_tasks: Coroutines = undefined; var fade_to_white: f32 = 0; const CancelToken = struct {}; const levels = [_]fn (*CancelToken) callconv(.Async) void{ level_1, level_2, level_3, level_4, level_5_intro, level_5, }; var frame_i: u32 = 0; var camera = c.Camera2D{ .offset = .{ .x = screenWidth / 2, .y = screenHeight / 2 }, .target = .{ .x = screenWidth / 2, .y = screenHeight / 2 }, .rotation = 0, .zoom = 1, }; var level_start_state: State = undefined; const cancel_level = CancelToken{}; var boss_speed: f32 = 4; var boss_steps: []const BossState = &([1]BossState{.idle}); pub fn init() void { c.HideCursor(); mongoose = .{ .texture = c.LoadTexture("mongoose.png"), .frames = 3 }; explosion = .{ .texture = c.LoadTexture("explosion.png"), .frames = 8 }; extractor = .{ .texture = c.LoadTexture("extractor.png"), .frames = 1 }; boss = .{ .texture = c.LoadTexture("laughing_falcon.png"), .frames = 8 }; { // generate image (all white pixels) of boss with alpha cutout for final explosion var base_img = c.GenImageColor(@floatToInt(i32, boss.width()), boss.texture.height, c.WHITE); const img1 = c.LoadImageFromTexture(boss.texture); defer c.UnloadImage(img1); var img2 = c.ImageFromImage(img1, boss.frameRect(7)); defer c.UnloadImage(img2); // update mask var pixels = c.LoadImageColors(img2); for (pixels[0..@intCast(usize, img2.width * img2.height)]) |*p| { if (p.a == 0) { p.r = 0; p.g = 0; p.b = 0; } else { p.a = 255; p.r = 255; p.g = 255; p.b = 255; } } c.UnloadImageColors(@ptrCast([*c]c.Color, img2.data)); img2.data = pixels; c.ImageAlphaMask(&base_img, img2); boss_white = c.LoadTextureFromImage(base_img); } music = [_]c.Music{ c.LoadMusicStream("spacesnake_intro1.ogg"), c.LoadMusicStream("spacesnake_intro2.ogg"), c.LoadMusicStream("spacesnake.ogg"), c.LoadMusicStream("spacesnake_boss_intro.ogg"), c.LoadMusicStream("spacesnake_boss.ogg") }; music[0].looping = true; music[1].looping = false; music[2].looping = true; music[3].looping = false; music[4].looping = true; explosion_sound = c.LoadSound("explosion.wav"); big_explosion_sound = c.LoadSound("boss_final_explosion.ogg"); zap_sound = c.LoadSound("zap.wav"); screech_sound = c.LoadSound("screech.ogg"); hit_sound = c.LoadSound("boss_hit.wav"); //current_music = music[2..3]; current_music = music[0..1]; c.PlayMusicStream(current_music[0]); state.tail_pos = state.tail_pos_storage[0..]; state.tail_old_pos = state.old_tail_pos_storage[0..]; rand = std.rand.DefaultPrng.init(0); for (stars) |*pos| { pos.x = rand.random().float(f32) * screenWidth; pos.y = rand.random().float(f32) * screenHeight; } coroutines = Coroutines.init(gpa.allocator()); ui_tasks = Coroutines.init(gpa.allocator()); font = c.LoadFontEx("font/GamjaFlower-Regular.ttf", font_size, 0, 128); } fn drawTextEx(msg: [:0]const u8, pos: m.Vector2, tint: c.Color) void { for (msg) |char, i| { const s = [_]u8{ char, 0 }; c.DrawTextPro( font, &s, .{ .x = pos.x + @intToFloat(f32, i) * 10 - (@intToFloat(f32, msg.len) * 10) / 2, .y = pos.y - font_size / 2 }, .{ .x = 10, .y = 10 }, @sin(@floor(@mod(@floatCast(f32, c.GetTime()), 8)) + @intToFloat(f32, i) * 14132) * 14, font_size, 0, tint, ); } } fn drawText(msg: [:0]const u8, pos: m.Vector2) void { drawTextEx(msg, pos, c.WHITE); } fn toi32(v: f32) i32 { return @floatToInt(i32, v); } fn verletIntegrate(pos: []m.Vector2, old_pos: []m.Vector2) void { assert(pos.len == old_pos.len); for (pos) |*p, i| { const gravity = m.Vector2Scale(subNorm(center, p.*), 0.4); //c.DrawLineV(p.*, m.Vector2Add(p.*, m.Vector2Scale(subNorm(center, p.*), 10)), c.GREEN); const tmp = p.*; p.* = m.Vector2Add(m.Vector2Add(p.*, m.Vector2Subtract(p.*, old_pos[i])), if (state.planet_health > 0) gravity else m.Vector2Zero()); // HACK: clamp top speed so it can't phase through the planet const d = m.Vector2Subtract(tmp, pos[i]); if (m.Vector2Length(d) < planet_radius) { old_pos[i] = tmp; } else { old_pos[i] = m.Vector2Add(p.*, m.Vector2Scale(m.Vector2Normalize(d), 5)); } } } fn lineCircleIntersection(p1: m.Vector2, p2: m.Vector2, circle_pos: m.Vector2, radius: f32) ?m.Vector2 { if (m.Vector2Distance(p1, circle_pos) < radius) { // already inside -- pop out by normal return m.Vector2Scale(subNorm(p1, circle_pos), radius); } const d = m.Vector2Subtract(p2, p1); const f = m.Vector2Subtract(p1, circle_pos); const a = m.Vector2DotProduct(d, d); const b = 2 * m.Vector2DotProduct(f, d); const _c = m.Vector2DotProduct(f, f) - radius * radius; var discriminant = b * b - 4 * a * _c; if (discriminant < 0) { return null; } else { discriminant = std.math.sqrt(discriminant); const t1 = (-b - discriminant) / (2 * a); const t2 = (-b + discriminant) / (2 * a); if (t1 >= 0 and t1 <= 1) { return m.Vector2Add(p1, m.Vector2Scale(d, t1)); } if (t2 >= 0 and t2 <= 1) { return m.Vector2Add(p1, m.Vector2Scale(d, t2)); } return null; } } fn getMoveInput() ?m.Vector2 { if (gameplay_state == .alive and c.IsMouseButtonDown(c.MOUSE_BUTTON_LEFT) and state.zapped_time_left <= 0) { const mouse_pos = m.Vector3{ .x = @intToFloat(f32, c.GetMouseX()), .y = @intToFloat(f32, c.GetMouseY()), .z = 0 }; // lifted from raylib source code (GetScreenToWorld2D()) const mat_camera: m.Matrix = c.GetCameraMatrix2D(camera); const inv_mat_camera: m.Matrix = m.MatrixInvert(mat_camera); const transform = m.Vector3Transform(mouse_pos, inv_mat_camera); return m.Vector2{ .x = transform.x, .y = transform.y }; } return null; } fn getShouldShrinkInput() bool { return gameplay_state == .alive and state.zapped_time_left <= 0 and (c.IsMouseButtonDown(c.MOUSE_BUTTON_RIGHT) or c.IsKeyDown(c.KEY_SPACE)); } fn tailLeft() usize { return state.tail_pos.len - 3; } const perms = [_]u8{ 151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180 }; inline fn hash(i: i32) u8 { return perms[@intCast(usize, i & 0xFF)]; } fn grad(ihash: i32, x: f32) f32 { const h = ihash & 0x0F; var fgrad = 1.0 + @intToFloat(f32, h & 7); if ((h & 8) != 0) { fgrad = -fgrad; } return fgrad * x; } // 1d simplex noise // ported from https://github.com/SRombauts/SimplexNoise/blob/master/src/SimplexNoise.cpp#L175 export fn noise(x: f32) f32 { // Corners const i_0: i32 = @floatToInt(i32, x); const i_1 = i_0 + 1; // Distance const x0 = x - @intToFloat(f32, i_0); const x1 = x0 - 1.0; var t0 = 1.0 - x0 * x0; t0 *= t0; const n0 = t0 * t0 * grad(hash(i_0), x0); var t1 = 1.0 - x1 * x1; t1 *= t1; const n1 = t1 * t1 * grad(hash(i_1), x1); // The maximum value of this noise is 8*(3/4)^4 = 2.53125 // A factor of 0.395 scales to fit exactly within [-1,1] return 0.395 * (n0 + n1); } fn cameraShake(duration: f32, scale: f32) void { const orig_pos = camera.offset; const start_time = c.GetTime(); while (c.GetTime() < start_time + duration) { camera.offset = m.Vector2Add(orig_pos, c.Vector2{ .x = noise(@floatCast(f32, c.GetTime()) * 20) * scale, .y = noise(@floatCast(f32, c.GetTime() + 50.7) * 20) * scale }); suspend { coroutines.yield(@frame(), null); } } camera.offset = orig_pos; } fn verletSolveConstraints(pos: []m.Vector2) void { var i: u32 = 0; var snake_joint_dist: f32 = 10; if (getShouldShrinkInput()) { snake_joint_dist = 2; } while (i < pos.len - 1) : (i += 1) { var n1 = &pos[i]; var n2 = &pos[i + 1]; if (i == 0) { if (getMoveInput()) |input_pos| { var max = 0.1 + (@intToFloat(f32, numSnakeJointsOnGround()) / @intToFloat(f32, state.tail_pos.len)) * 5; if (getShouldShrinkInput()) { max += 0.5; } n1.* = m.Vector2Add(n1.*, m.Vector2ClampValue(m.Vector2Subtract(input_pos, n1.*), 0, max)); } } if (state.boss) |boss_data| { if (boss_data.state == .hold) { if (boss_data.hold_l) |joint_i| { if (i == joint_i) { n1.* = m.Vector2Add(boss_data.position, boss_foot_offset); } } if (boss_data.hold_r) |joint_i| { if (i == joint_i) { n1.* = m.Vector2Add(boss_data.position, m.Vector2{ .x = -boss_foot_offset.x, .y = boss_foot_offset.y }); } } } } { var diff = m.Vector2Subtract(n1.*, n2.*); const dist = m.Vector2Length(diff); var difference: f32 = 0; if (dist > 0) { difference = (snake_joint_dist - dist) / dist; } else { difference = 1; diff = m.Vector2Add(m.Vector2{ .x = 0, .y = 1 }, n1.*); } if (i == 0) { // give slightly more pull to the head joint. const t1 = m.Vector2Scale(diff, 0.2 * difference); const t2 = m.Vector2Scale(diff, 0.8 * difference); n1.* = m.Vector2Add(n1.*, t1); n2.* = m.Vector2Subtract(n2.*, t2); } else { const translate = m.Vector2Scale(diff, 0.5 * difference); n1.* = m.Vector2Add(n1.*, translate); n2.* = m.Vector2Subtract(n2.*, translate); } } // adds more structure/stiffness by trying to keep nodes 2 steps apart // away from each other if (i < pos.len - 2) { var n3 = &pos[i + 2]; { const diff = m.Vector2Subtract(n1.*, n3.*); const dist = m.Vector2Length(diff); var difference: f32 = 0; assert(dist != 0); difference = ((snake_joint_dist * 2) - dist) / dist; const translate = m.Vector2Scale(diff, 0.5 * difference); n1.* = m.Vector2Add(n1.*, m.Vector2Scale(translate, 0.1)); n3.* = m.Vector2Subtract(n3.*, m.Vector2Scale(translate, 0.1)); } } } } pub fn subNorm(a: m.Vector2, b: m.Vector2) m.Vector2 { return m.Vector2Normalize(m.Vector2Subtract(a, b)); } pub fn subNormScale(a: m.Vector2, b: m.Vector2, f: f32) m.Vector2 { return m.Vector2Scale(m.Vector2Normalize(m.Vector2Subtract(a, b)), f); } pub fn vecClamp(v: m.Vector2, f: f32) m.Vector2 { const l = m.Vector2Length(v); if (l < f) { return v; } else { return m.Vector2Scale(v, f / l); } } fn vecAngle(v: m.Vector2) f32 { return std.math.atan2(f32, v.y, v.x) + std.math.pi / 2.0; } pub fn vecPerpClockwise(v: m.Vector2) m.Vector2 { return .{ .x = v.y, .y = -v.x }; } pub fn subClamp(a: m.Vector2, b: m.Vector2, f: f32) m.Vector2 { var r = m.Vector2Subtract(a, b); const l = m.Vector2Length(r); if (l < f) { return r; } else { return m.Vector2Scale(r, f / l); } } fn snakeCollidingWith(enemy_pos: m.Vector2, radius: f32) bool { if (freezeFrame() or gameplay_state == .dead) { return false; } for (state.tail_pos) |p| { if (c.CheckCollisionCircles(p, player_radius, enemy_pos, radius)) { return true; } } return false; } const CircleCollision = struct { center: m.Vector2, radius: f32, }; fn blockedCollision(pos: m.Vector2) ?CircleCollision { if (freezeFrame()) { return null; } if (state.boss) |b| { if (c.CheckCollisionCircles(pos, player_radius, b.position, boss_radius)) { return CircleCollision{ .center = b.position, .radius = boss_radius }; } } if (state.planet_health > 0 and c.CheckCollisionCircles(pos, player_radius, center, planet_radius)) { return CircleCollision{ .center = center, .radius = planet_radius }; } return null; } fn numSnakeJointsOnGround() u32 { var r: u32 = 0; for (state.tail_pos) |p| { if (blockedCollision(p)) |_| { r += 1; } } return r; } inline fn radiansToDegrees(rad: f32) f32 { return rad * (360.0 / (2.0 * std.math.pi)); } const Coroutines = struct { const FramePair = struct { cancel_token: ?*CancelToken, frame: anyframe }; allocator: std.mem.Allocator, frame_arena: std.heap.ArenaAllocator, frame_pointers: std.ArrayList(FramePair), const Self = @This(); fn init(allocator: std.mem.Allocator) Self { return Self{ .allocator = allocator, .frame_arena = std.heap.ArenaAllocator.init(allocator), .frame_pointers = std.ArrayList(FramePair).init(allocator), }; } fn yield(self: *Self, fr: anytype, cancel_token: ?*CancelToken) void { const T = @typeInfo(@TypeOf(fr)).Pointer.child; var frame_ptr = self.frame_arena.allocator().create(T) catch unreachable; frame_ptr.* = fr.*; self.frame_pointers.append(.{ .cancel_token = cancel_token, .frame = frame_ptr }) catch @panic("couldn't push coroutine"); } fn cancel(self: *Self, token: *CancelToken) void { var idxs = std.BoundedArray(usize, 32).init(0) catch unreachable; for (self.frame_pointers.items) |x, i| { if (x.cancel_token) |t| { if (t == token) { idxs.append(i) catch {}; } } } std.mem.reverse(usize, idxs.slice()); for (idxs.slice()) |i| { // we don't need to free the frame we're pointing to since // it's in an arena that will auto clean up. _ = self.frame_pointers.swapRemove(i); } } fn resumeAll(self: *Self) void { // store the bytes for the current coroutines var cos = self.frame_pointers.clone() catch @panic("blarg"); defer cos.clearAndFree(); // delete old coroutine frame pointers after we're done var old_frames = self.frame_arena; defer old_frames.deinit(); // delete old coroutine frames after we're done // set up the next batch of coroutines self.frame_pointers.clearRetainingCapacity(); self.frame_arena = std.heap.ArenaAllocator.init(self.allocator); // run them all for (cos.items) |co| { resume co.frame; } } }; fn wait(interval: f32, token: ?*CancelToken) void { var start = c.GetTime(); while (c.GetTime() - start < interval) { suspend { coroutines.yield(@frame(), token); } } } fn freezeFrame() bool { return state.zapped_time_left > 1.8; } fn zap() void { // give 0.5 second window between zap times if (state.zapped_time_left < -0.5) { c.PlaySoundMulti(zap_sound); state.zapped_time_left = 2; if (tailLeft() > 0) { state.tail_pos = state.tail_pos[0 .. state.tail_pos.len - 1]; state.tail_old_pos = state.tail_old_pos[0 .. state.tail_old_pos.len - 1]; } } } fn callOnInterval(comptime f: fn () void, interval: f32) void { while (true) { var start = c.GetTime(); while (true) { suspend { coroutines.yield(@frame()); } if (c.GetTime() - start > interval) { break; } } f(); } } pub fn waitForCondition(cond: fn () bool, token: ?*CancelToken) void { while (!cond()) { suspend { coroutines.yield(@frame(), token); } } } fn allEnemiesAreDead() bool { return state.enemies.slice().len == 0 and state.boss == null; } fn tween(val: *f32, target: f32, duration: f32, token: ?*CancelToken) void { var start = c.GetTime(); var range = target - val.*; var original_val = val.*; while (c.GetTime() < start + duration) { var dist = (c.GetTime() - start) / duration; val.* = original_val + @floatCast(f32, (dist * range)); suspend { coroutines.yield(@frame(), token); } } } pub fn drawTextUntilContinue(msg: [:0]const u8, token: *CancelToken) void { suspend { ui_tasks.yield(@frame(), token); } while (!c.IsKeyPressed(c.KEY_X)) { suspend { ui_tasks.yield(@frame(), token); } drawText(msg, .{ .x = screenWidth / 2, .y = screenHeight / 2 + 140 }); drawText("(Press X to continue)", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 170 }); } } pub fn level_1(token: *CancelToken) void { gameplay_state = .no_control; current_music = music[0..1]; c.PlayMusicStream(current_music[0]); current_music[0].looping = true; c.SetMusicPitch(current_music[0], 1); camera.zoom = 2; state.expression = .eye_closed; drawTextUntilContinue("This is Tom.", token); drawTextUntilContinue("Tom likes to nap on his green rock.", token); current_music = &music; current_music[0].looping = false; wait(2, token); tween(&camera.zoom, 1, 2, token); state.enemies.append(.{ .pos = m.Vector2{ .x = screenWidth / 2, .y = screenHeight }, .time = 0, .shield_pattern = &([_]f32{ 1, 1 }) }) catch unreachable; drawTextUntilContinue("Stop the mongoose troop from sucking the planet dry!", token); gameplay_state = .alive; drawTextUntilContinue("Left click moves, right click (or SPACE) shrinks and increases speed.", token); var n_groups: u32 = 5; while (n_groups > 0) : (n_groups -= 1) { var i: u32 = 0; const t = rand.random().float(f32) * 2 * std.math.pi; var spawn_point = m.Vector2{ .x = @cos(t) * (screenWidth + 20), .y = @sin(t) * (screenWidth + 20), }; while (i < 5) : (i += 1) { state.enemies.append(.{ .pos = spawn_point, .time = 0, .shield_pattern = &([_]f32{ 1, 1 }) }) catch unreachable; wait(0.3, token); } wait(4, token); } waitForCondition(allEnemiesAreDead, token); drawTextUntilContinue("Victory!", token); } pub fn level_2(token: *CancelToken) void { state.lasers.append(.{ m.Vector2Add(center, .{ .x = -40, .y = 140 }), m.Vector2Add(center, .{ .x = 40, .y = 140 }), }) catch unreachable; c.SetMusicPitch(current_music[0], 1); camera.zoom = 2; drawTextUntilContinue("Beware the lasers!", token); wait(2, token); tween(&camera.zoom, 1, 2, token); var n_groups: u32 = 5; while (n_groups > 0) : (n_groups -= 1) { wait(4, token); var i: u32 = 0; const t = rand.random().float(f32) * 2 * std.math.pi; var spawn_point = m.Vector2{ .x = @cos(t) * (screenWidth + 20), .y = @sin(t) * (screenWidth + 20), }; while (i < 3) : (i += 1) { state.enemies.append(.{ .pos = spawn_point, .time = 0, .shield_pattern = &([_]f32{ 1, 1 }) }) catch unreachable; wait(0.3, token); } } waitForCondition(allEnemiesAreDead, token); while (!c.IsKeyPressed(c.KEY_X)) { suspend { ui_tasks.yield(@frame(), token); } drawText("Victory!", .{ .x = screenWidth / 2, .y = screenHeight / 2 }); drawText("Press X to continue", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 100 }); } } pub fn level_3(token: *CancelToken) void { state.lasers.append(.{ m.Vector2Add(center, .{ .x = 100, .y = 0 }), m.Vector2Add(center, .{ .x = 300, .y = 0 }), }) catch unreachable; state.lasers.append(.{ m.Vector2Add(center, .{ .x = -100, .y = 0 }), m.Vector2Add(center, .{ .x = -300, .y = 0 }), }) catch unreachable; c.SetMusicPitch(current_music[0], 1); camera.zoom = 2; wait(2, token); tween(&camera.zoom, 1, 2, token); var n_groups: u32 = 5; while (n_groups > 0) : (n_groups -= 1) { wait(2, token); var i: u32 = 0; const t = rand.random().float(f32) * 2 * std.math.pi; var spawn_point = m.Vector2{ .x = @cos(t) * (screenWidth + 20), .y = @sin(t) * (screenWidth + 20), }; while (i < 5) : (i += 1) { state.enemies.append(.{ .pos = spawn_point, .time = 0, .shield_pattern = &([_]f32{ 1, 1 }) }) catch unreachable; wait(0.3, token); } } waitForCondition(allEnemiesAreDead, token); while (!c.IsKeyPressed(c.KEY_X)) { suspend { ui_tasks.yield(@frame(), token); } drawText("Victory!", .{ .x = screenWidth / 2, .y = screenHeight / 2 }); drawText("Press X to continue", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 100 }); } } pub fn level_4(token: *CancelToken) void { current_music = music[2..3]; c.PlayMusicStream(current_music[0]); state.lasers.append(.{ m.Vector2Add(center, .{ .x = -100, .y = 0 }), m.Vector2Add(center, .{ .x = -150, .y = 0 }), }) catch unreachable; state.lasers.append(.{ m.Vector2Add(center, .{ .x = -250, .y = 0 }), m.Vector2Add(center, .{ .x = -500, .y = 0 }), }) catch unreachable; c.SetMusicPitch(current_music[0], 1); camera.zoom = 2; drawTextUntilContinue("Red mongooses zap too!", token); wait(2, token); tween(&camera.zoom, 1, 2, token); var n_groups: u32 = 5; while (n_groups > 0) : (n_groups -= 1) { wait(3, token); var i: u32 = 0; const t = rand.random().float(f32) * 2 * std.math.pi; var spawn_point = m.Vector2{ .x = @cos(t) * (screenWidth + 20), .y = @sin(t) * (screenWidth + 20), }; while (i < 2) : (i += 1) { state.enemies.append(.{ .pos = spawn_point, .time = 6, }) catch unreachable; wait(0.3, token); } } waitForCondition(allEnemiesAreDead, token); while (!c.IsKeyPressed(c.KEY_X)) { suspend { ui_tasks.yield(@frame(), token); } drawText("Victory!", .{ .x = screenWidth / 2, .y = screenHeight / 2 }); drawText("Press X to continue", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 100 }); } } pub fn level_5_intro(token: *CancelToken) void { gameplay_state = .no_control; boss_speed = 0.5; const s1 = c.GetTime(); while (c.GetTime() - s1 < 3) { c.SetMusicVolume(current_music[0], 1 - (@floatCast(f32, (c.GetTime() - s1) / 3))); suspend { coroutines.yield(@frame(), token); } } const s2 = c.GetTime(); current_music = music[3..]; c.PlayMusicStream(current_music[0]); state.lasers_rot_speed = 0; state.boss = .{ .position = .{ .x = screenWidth / 2, .y = -120 }, .state = .idle, .hold_l = null, .hold_r = null, .health = 64, .state_time = 0, .i = 0, }; state.expression = .angry; // wait for right time in song while (c.GetTime() - s2 < 12) { suspend { coroutines.yield(@frame(), token); } } // intro screech setBossState(.screech); } pub fn level_5(token: *CancelToken) void { gameplay_state = .alive; boss_speed = 4; boss_steps = ([_]BossState{ .idle, .swoop_grab })[0..]; while (state.boss.?.health > 40) { suspend { coroutines.yield(@frame(), token); } } // new phase setBossState(.screech); boss_steps = ([_]BossState{ .idle, .swoop_grab, .lasers })[0..]; while (state.boss.?.health > 20) { suspend { coroutines.yield(@frame(), token); } } setBossState(.screech); // calling wait() here segfaults >_< const s1 = c.GetTime(); while (s1 + 4 < c.GetTime()) { suspend { coroutines.yield(@frame(), token); } } { var j: u32 = 0; while (j < 16) : (j += 1) { var spawn_point = m.Vector2{ .x = @cos(@floatCast(f32, c.GetTime()) + @intToFloat(f32, j * 20)) * (screenWidth + 20), .y = @sin(@floatCast(f32, c.GetTime()) + @intToFloat(f32, j * 20)) * (screenWidth + 20), }; state.enemies.append(.{ .pos = spawn_point, .time = 0, .shield_pattern = &([_]f32{ 1, 1 }), .drop_prob = 0.0005 }) catch unreachable; } } const s2 = c.GetTime(); while (s2 + 4 < c.GetTime()) { suspend { coroutines.yield(@frame(), token); } } { var j: u32 = 0; while (j < 5) : (j += 1) { var spawn_point = m.Vector2{ .x = @cos(@floatCast(f32, c.GetTime()) + @intToFloat(f32, j * 20)) * (screenWidth + 20), .y = @sin(@floatCast(f32, c.GetTime()) + @intToFloat(f32, j * 20)) * (screenWidth + 20), }; state.enemies.append(.{ .pos = spawn_point, .time = 0, .shield_pattern = &([_]f32{ 3, 6, 9 }), .drop_prob = 0.00001 }) catch unreachable; } } while (state.boss.?.state != .dead or state.boss.?.state_time < 2) { suspend { coroutines.yield(@frame(), token); } } for (state.enemies.slice()) |enemy| { _ = async playSprite(enemy.pos, explosion, 0.1); state.enemies.resize(0) catch unreachable; state.extractors.clearRetainingCapacity(); } { var i: u32 = 16; const w = @intToFloat(f32, boss_white.width); const h = @intToFloat(f32, boss_white.height); c.PlaySoundMulti(big_explosion_sound); while (i > 0) : (i -= 1) { _ = async playSprite(.{ .x = state.boss.?.position.x + rand.random().float(f32) * w - w / 2, .y = state.boss.?.position.y + rand.random().float(f32) * h - h / 2, }, explosion, 0.1); suspend { coroutines.yield(@frame(), token); } } } // fade out music and fade in white box const s3 = c.GetTime(); const l = 1; while (c.GetTime() - s3 < l) { const pct = (@floatCast(f32, (c.GetTime() - s3) / l)); c.SetMusicVolume(current_music[0], 1 - pct); fade_to_white = pct; suspend { coroutines.yield(@frame(), token); } } fade_to_white = 1; state.boss = null; while (!c.IsKeyPressed(c.KEY_X)) { suspend { ui_tasks.yield(@frame(), token); } drawTextEx("Press X to continue", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 100 }, c.BLACK); } fade_to_white = 0; } fn playSprite(pos: m.Vector2, sprite: SpriteSheet, frame_time: f32) void { var i: usize = 0; var t = c.GetTime(); while (i < sprite.frames) { sprite.drawFrame(pos, 0, i); suspend { coroutines.yield(@frame(), null); } if (c.GetTime() - t > frame_time) { t = c.GetTime(); i += 1; } } } fn getDownAngle(pos: m.Vector2) f32 { return vecAngle(m.Vector2Subtract(pos, center)); } fn renderGameOver(token: *CancelToken) void { while (true) { suspend { ui_tasks.yield(@frame(), token); } drawText("Game over", center); drawText("Press R to restart", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 50 }); } } fn run_levels() void { while (state.current_level < levels.len) { resetPosition(); state.zapped_time_left = 0; state.lasers.resize(0) catch {}; level_start_state = state.clone(); var bytes: [1024]u8 align(64) = undefined; await @asyncCall(&bytes, {}, levels[state.current_level], .{cancel_level}); state.current_level += 1; state.planet_health = state.planet_health + (360 - state.planet_health) * 0.3; } current_music = music[0..1]; current_music[0].looping = true; c.SetMusicVolume(current_music[0], 1); c.PlayMusicStream(current_music[0]); camera.zoom = 1; _ = async tween(&camera.zoom, 3, 5, null); resetPosition(); gameplay_state = .no_control; state.expression = .eye_closed; while (true) { c.BeginMode2D(camera); c.DrawTextPro( font, "z", .{ .x = state.tail_pos[0].x, .y = state.tail_pos[0].y - 10 }, .{ .x = 0, .y = 0 }, @sin(@floor(@mod(@floatCast(f32, c.GetTime()), 8)) + 14132) * 14, 10, 0, c.WHITE, ); c.DrawTextPro( font, "z", .{ .x = state.tail_pos[0].x + 4, .y = state.tail_pos[0].y - 20 }, .{ .x = 0, .y = 0 }, @sin(@floor(@mod(@floatCast(f32, c.GetTime()), 8)) + 2 * 14132) * 14, 12, 0, c.WHITE, ); c.DrawTextPro( font, "z", .{ .x = state.tail_pos[0].x + 8, .y = state.tail_pos[0].y - 30 }, .{ .x = 0, .y = 0 }, @sin(@floor(@mod(@floatCast(f32, c.GetTime()), 8)) + 3 * 14132) * 14, 14, 0, c.WHITE, ); c.EndMode2D(); suspend { ui_tasks.yield(@frame(), cancel_level); } drawText("They didn't bother Tom after that.", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 140 }); drawText("Thanks for playing", .{ .x = screenWidth / 2, .y = screenHeight / 2 + 170 }); } } fn focusBoss() void { // Kinda broken. Not sure why the offset doesn't go back to the center // of the screen _ = async tween(&camera.offset.y, camera.offset.y + 120, 0.4, null); _ = async tween(&camera.zoom, 1.4, 0.4, null); wait(1, null); _ = async tween(&camera.offset.y, screenHeight / 2, 0.4, null); _ = async tween(&camera.zoom, 1, 0.4, null); } var prev_boss_state: BossState = .idle; pub export fn renderFrame() void { var prev_health = state.planet_health; const time = @floatCast(f32, c.GetTime()); if (!c.IsMusicStreamPlaying(current_music[0])) { current_music = current_music[1..current_music.len]; c.PlayMusicStream(current_music[0]); } c.UpdateMusicStream(current_music[0]); if (frame_i == 0) { _ = async run_levels(); } if (gameplay_state != .dead and (tailLeft() == 0 or state.planet_health <= 0)) { gameplay_state = .dead; // enter game over coroutines.cancel(cancel_level); ui_tasks.cancel(cancel_level); c.SetMusicPitch(current_music[0], 0.5); if (tailLeft() == 0) { state.zapped_time_left = std.math.inf(f32); } _ = async cameraShake(0.3, 10); _ = async renderGameOver(cancel_level); } if (c.IsKeyPressed(c.KEY_R)) { // don't allow restart during the cutscene if (state.current_level != 4) { coroutines.cancel(cancel_level); ui_tasks.cancel(cancel_level); state.deinit(); state = level_start_state.clone(); _ = async run_levels(); gameplay_state = .alive; c.SetMusicPitch(current_music[0], 1); fade_to_white = 0; } } if (gameplay_state == .alive) { if (c.IsMouseButtonDown(c.MOUSE_BUTTON_LEFT)) { state.expression = .angry; } else if (c.IsMouseButtonDown(c.MOUSE_BUTTON_RIGHT)) { state.expression = .eye_squeezed_closed; } else { state.expression = .irritated; } } { state.zapped_time_left -= c.GetFrameTime(); if (!freezeFrame()) { verletIntegrate(state.tail_pos, state.tail_old_pos); { var i: u32 = 0; while (i < 10) : (i += 1) { verletSolveConstraints(state.tail_pos); for (state.tail_pos) |*p| { if (blockedCollision(p.*)) |col| { p.* = m.Vector2Add(col.center, m.Vector2Scale(subNorm(p.*, col.center), col.radius + player_radius)); } } } for (state.tail_pos) |*p, j| { // if it was colliding last frame too, apply some "friction" if (blockedCollision(state.tail_old_pos[j])) |_| { p.* = m.Vector2Add(p.*, m.Vector2Scale(m.Vector2Subtract(state.tail_old_pos[j], p.*), 0.4)); // clamp movement if it's small enough if (m.Vector2Distance(p.*, state.tail_old_pos[j]) < 0.05) { p.* = state.tail_old_pos[j]; } } } } } } c.BeginDrawing(); defer c.EndDrawing(); c.ClearBackground(c.BLACK); c.BeginMode2D(camera); for (stars) |pos| { c.DrawCircleV(pos, 1, c.WHITE); } { // draw the extractors var it = state.extractors.iterator(); while (it.next()) |pos| { extractor.drawFrame(pos, getDownAngle(pos), 0); } } if (state.planet_health > 0) { // draw planet const green_hsv = c.ColorToHSV(c.DARKGREEN); const brown_hsv = c.ColorToHSV(c.BROWN); var saturation = ((1 + state.planet_health) / 361); c.DrawCircle( toi32(center.x), toi32(center.y), planet_radius, c.ColorFromHSV(green_hsv.x, saturation, green_hsv.z), ); c.DrawCircle( toi32(center.x), toi32(center.y), planet_radius - 4, c.ColorFromHSV(brown_hsv.x, saturation, brown_hsv.z), ); } { // draw snake var i: u32 = 0; const draw_zapped = state.zapped_time_left > 1.5 or (state.zapped_time_left > 0 and @mod(state.zapped_time_left, 0.2) > 0.1); while (i < state.tail_pos.len - 1) : (i += 1) { // draw snake c.DrawCircleV(state.tail_pos[i], player_radius, if (draw_zapped) c.BLACK else c.YELLOW); c.DrawLineEx(state.tail_pos[i], state.tail_pos[i + 1], 5, if (draw_zapped) c.BLACK else c.GREEN); if (draw_zapped) { c.DrawLineEx(state.tail_pos[i], state.tail_pos[i + 1], 2, c.WHITE); } } if (state.zapped_time_left > 0) { state.expression = .eye_squeezed_closed; } // draw eyebrow var perp = vecPerpClockwise(subNorm(state.tail_pos[0], state.tail_pos[1])); if (m.Vector2DotProduct(perp, subNorm(state.tail_pos[0], center)) < -0.8) { perp = m.Vector2Scale(perp, -1); } switch (state.expression) { .eye_closed => {}, .eye_squeezed_closed => {}, else => { // draw eye c.DrawCircleV(m.Vector2Scale(m.Vector2Add(state.tail_pos[0], state.tail_pos[1]), 0.5), 2, c.BLACK); }, } switch (state.expression) { .neutral => c.DrawLineEx(m.Vector2Add(m.Vector2Scale(perp, 4), state.tail_pos[0]), m.Vector2Add(perp, state.tail_pos[1]), 2, c.DARKGREEN), .angry => c.DrawLineEx(m.Vector2Add(perp, state.tail_pos[0]), m.Vector2Add(m.Vector2Scale(perp, 4), state.tail_pos[1]), 2, c.DARKGREEN), .irritated => c.DrawLineEx(m.Vector2Add(perp, state.tail_pos[0]), m.Vector2Add(perp, state.tail_pos[1]), 2, c.DARKGREEN), .eye_closed => { var d = subNorm(state.tail_pos[1], state.tail_pos[0]); c.DrawLineEx( state.tail_pos[0], m.Vector2Add(state.tail_pos[0], m.Vector2Scale(d, 7)), 1, c.DARKGREEN, ); }, .eye_squeezed_closed => { var d = subNorm(state.tail_pos[1], state.tail_pos[0]); c.DrawLineEx( state.tail_pos[0], m.Vector2Add(state.tail_pos[0], m.Vector2Add(m.Vector2Scale(perp, 2), m.Vector2Scale(d, 7))), 1, c.DARKGREEN, ); c.DrawLineEx( state.tail_pos[0], m.Vector2Add(state.tail_pos[0], m.Vector2Add(m.Vector2Scale(perp, -2), m.Vector2Scale(d, 7))), 1, c.DARKGREEN, ); }, } } { // enemies { // destroy enemies if they collide with snake var enemies_to_delete = std.BoundedArray(usize, 32).init(0) catch unreachable; for (state.enemies.slice()) |enemy, i| { if (snakeCollidingWith(enemy.pos, enemy_radius)) { if (enemy.shieldStatus() == .on) { zap(); } else { enemies_to_delete.append(i) catch {}; } } } { var j: usize = enemies_to_delete.len; while (j > 0) { // janky cuz zig is preventing int underflow when i = 0... j -= 1; const i = enemies_to_delete.constSlice()[j]; _ = async playSprite(state.enemies.slice()[i].pos, explosion, 0.1); c.SetSoundPitch(explosion_sound, 0.9 + (rand.random().float(f32) * 0.2)); c.PlaySoundMulti(explosion_sound); if (state.enemies.slice()[i].extractor) |extractor_i| { _ = async playSprite(state.extractors.get(extractor_i).?, explosion, 0.1); _ = state.extractors.remove(extractor_i); } _ = state.enemies.swapRemove(i); } } } // delete any that collide with snek boi while falling { var it = state.extractors.iterator(); while (it.next()) |pos| { const d = m.Vector2Subtract(center, pos); if (m.Vector2Length(d) > planet_radius + 10) { state.extractors.data.items[@intCast(usize, it.i)] = m.Vector2Add(m.Vector2ClampValue(d, 0, 10), pos); if (snakeCollidingWith(pos, enemy_radius)) { _ = state.extractors.remove(@intCast(usize, it.i)); for (state.enemies.slice()) |*e| { if (e.*.extractor != null and e.*.extractor.? == it.i) { e.*.extractor = null; break; } } break; } } else { // extractor on the planet state.planet_health -= @floatCast(f32, c.GetFrameTime() * 5); } } } { // movement logic for (state.enemies.slice()) |*enemy, i| { const orbit_dist = 100.0 + @intToFloat(f32, i % 3) * 20; var goal = m.Vector2Add(center, subNormScale(enemy.*.pos, center, planet_radius + orbit_dist)); const orbit_vec = vecPerpClockwise(subNormScale(center, enemy.*.pos, 2)); { // add flee to goal const closest_joint = lbl: { const h = state.tail_pos[0]; const t = state.tail_pos[state.tail_pos.len - 1]; if (m.Vector2Distance(h, enemy.*.pos) < m.Vector2Distance(t, enemy.*.pos)) { break :lbl h; } else { break :lbl t; } }; const diff = m.Vector2Subtract(enemy.*.pos, closest_joint); var d = std.math.clamp(m.Vector2Length(diff), 0, 100) / 100; const move_force = lbl: { if (enemy.*.extractor == null) { break :lbl @as(f32, 100.0); } else { break :lbl @as(f32, 10.0); } }; goal = m.Vector2Add(goal, m.Vector2Scale(subNorm( enemy.*.pos, diff, ), -(1 - d) * move_force)); // FIXME: flip logic is borked, but it's doing something for the movement right now so I'm leaving it. if (m.Vector2DotProduct(m.Vector2Normalize(diff), m.Vector2Normalize(orbit_vec)) > 0.4 and m.Vector2Length(diff) < 80) { //c.DrawTextEx(c.GetFontDefault(), "flip", m.Vector2Add(enemy.*.pos, .{ .x = 20, .y = 20 }), 10, 1, c.WHITE); enemy.*.orbit_dir = -enemy.*.orbit_dir; } } if (enemy.*.extractor == null and rand.random().float(f32) < enemy.drop_prob) { enemy.*.extractor = state.extractors.add(enemy.*.pos); } // add orbit goal = m.Vector2Add(goal, m.Vector2Scale(orbit_vec, enemy.*.orbit_dir)); //c.DrawCircleV(goal, 2, c.PURPLE); var goal_vel = subClamp(goal, enemy.*.pos, 8); var steering = subClamp(goal_vel, enemy.*.vel, 1); enemy.*.vel = vecClamp(m.Vector2Add(enemy.*.vel, steering), 10); enemy.*.pos = m.Vector2Add(enemy.*.pos, enemy.*.vel); } } // draw enemies for (state.enemies.slice()) |*e| { const d = m.Vector2Subtract(e.*.pos, center); e.*.addTime(c.GetFrameTime()); c.DrawCircleLines(@floatToInt(i32, e.*.pos.x), @floatToInt(i32, e.*.pos.y), 10, c.WHITE); const rot = std.math.atan2(f32, d.y, d.x) + (std.math.pi / 2.0); if (e.*.extractor) |i| { const extractor_pos = state.extractors.data.items[i]; const ext_d = m.Vector2Subtract(extractor_pos, center); // draw line connecting to extractor c.DrawLineV(e.*.pos, m.Vector2Add(extractor_pos, m.Vector2Scale(m.Vector2Normalize(ext_d), 10)), c.GRAY); } else { // draw inactive extractor extractor.drawFrame(m.Vector2Add(m.Vector2Scale(m.Vector2Normalize(d), -5), e.*.pos), rot, 0); } mongoose.drawFrame(e.*.pos, rot, e.*.frame()); switch (e.shieldStatus()) { .off => {}, .warning => c.DrawCircleGradient( @floatToInt(i32, e.*.pos.x), @floatToInt(i32, e.*.pos.y), 10 * (e.shieldTime() - 3) / 2, c.ColorAlpha(c.YELLOW, 0.3), c.ColorAlpha(c.YELLOW, 0.8), ), .on => c.DrawCircleGradient( @floatToInt(i32, e.*.pos.x), @floatToInt(i32, e.*.pos.y), enemy_radius, c.ColorAlpha(c.RED, 0.3), c.ColorAlpha(c.RED, 0.8), ), } } if (state.boss) |*boss_data| { var goal = m.Vector2{ .x = screenWidth / 2, .y = 90 + @sin(time) * 20 }; // HACK: clear out lasers every frame to make them immediate mode. state.lasers.resize(0) catch unreachable; boss_data.state_time += c.GetFrameTime(); switch (boss_data.state) { .idle => { const frame_time = 0.2; const idle_frames = 4; const f = @floatToInt(usize, @mod(time, idle_frames * frame_time) / frame_time); boss.drawFrame(boss_data.position, 0, f); if (boss_data.state_time > 4) { bossStep(); } }, .swoop_grab => { if (prev_boss_state != .swoop_grab) { prev_boss_state = .swoop_grab; boss_data.hold_l = null; boss_data.hold_r = null; } goal = m.Vector2Subtract(state.tail_pos[0], boss_foot_offset); boss.drawFrame(boss_data.position, 0, 4); const foot_pos_l = m.Vector2Add(boss_data.position, boss_foot_offset); const foot_pos_r = m.Vector2Add(boss_data.position, m.Vector2{ .x = -boss_foot_offset.x, .y = boss_foot_offset.y }); for (state.tail_pos) |p, joint_i| { if (m.Vector2Distance(p, foot_pos_l) < 40) { c.DrawCircleLines(@floatToInt(i32, foot_pos_l.x), @floatToInt(i32, foot_pos_l.y), m.Vector2Distance(p, foot_pos_l), c.WHITE); if (m.Vector2Distance(p, foot_pos_l) < 4) { boss_data.hold_l = @intCast(u32, joint_i); setBossState(.hold); break; } } if (m.Vector2Distance(p, foot_pos_r) < 40) { c.DrawCircleLines(@floatToInt(i32, foot_pos_r.x), @floatToInt(i32, foot_pos_r.y), m.Vector2Distance(p, foot_pos_r), c.WHITE); if (m.Vector2Distance(p, foot_pos_r) < 4) { boss_data.hold_r = @intCast(u32, joint_i); setBossState(.hold); break; } } } if (boss_data.state_time > 4) { bossStep(); } }, .hold => { if (prev_boss_state != .hold) { prev_boss_state = .hold; boss_data.state_time = 0; { // spawn enemies var i: u32 = 0; while (i < 3) : (i += 1) { var spawn_point = m.Vector2{ .x = @cos(time + @intToFloat(f32, i * 20)) * (screenWidth + 20), .y = @sin(time + @intToFloat(f32, i * 20)) * (screenWidth + 20), }; state.enemies.append(.{ .pos = spawn_point, .time = 0, .shield_pattern = &([_]f32{ 1, 1 }) }) catch unreachable; } } } boss.drawFrame(boss_data.position, 0, 5); if (boss_data.state_time > 4) { bossStep(); } }, .screech => { // on enter if (prev_boss_state != .screech) { prev_boss_state = .screech; _ = async focusBoss(); c.PlaySoundMulti(screech_sound); } boss.drawFrame(boss_data.position, 0, 6); if (boss_data.state_time > 2) { bossStep(); } }, .lasers => { const eye_level = m.Vector2Add(boss_data.position, .{ .x = 0, .y = -25 }); state.lasers.append(.{ m.Vector2Add(eye_level, .{ .x = -23, .y = 0 }), m.Vector2Add(eye_level, .{ .x = -32 - @sin((boss_data.state_time + 2) * 3) * 40, .y = 150 }), }) catch unreachable; state.lasers.append(.{ m.Vector2Add(eye_level, .{ .x = 23, .y = 0 }), m.Vector2Add(eye_level, .{ .x = 32 + @sin((boss_data.state_time + 2) * 3) * 40, .y = 150 }), }) catch unreachable; boss.drawFrame(boss_data.position, 0, 4); if (boss_data.state_time > 3) { bossStep(); } c.DrawCircleV(eye_level, 10, c.RED); }, .dead => { if (prev_boss_state != .dead) { prev_boss_state = .dead; _ = async focusBoss(); c.PlaySoundMulti(screech_sound); } if (boss_data.state_time > 2) { c.DrawTexture( boss_white, @floatToInt(i32, boss_data.position.x - @intToFloat(f32, boss_white.width) / 2), @floatToInt(i32, boss_data.position.y - @intToFloat(f32, boss_white.height) / 2), c.WHITE, ); } else { boss.drawFrame(boss_data.position, 0, 7); } }, } boss_data.position = m.Vector2Add(boss_data.position, vecClamp(m.Vector2Subtract( goal, boss_data.position, ), boss_speed)); const left_engine = m.Vector2{ .x = boss_data.position.x - 50, .y = boss_data.position.y + 20 }; const right_engine = m.Vector2{ .x = boss_data.position.x + 50, .y = boss_data.position.y + 20 }; //c.DrawCircleLines(@floatToInt(i32, boss_data.position.x), @floatToInt(i32, boss_data.position.y), boss_radius, c.PURPLE); //c.DrawCircleLines(@floatToInt(i32, left_engine.x), @floatToInt(i32, left_engine.y), enemy_radius, c.PURPLE); //c.DrawCircleLines(@floatToInt(i32, right_engine.x), @floatToInt(i32, right_engine.y), enemy_radius, c.PURPLE); if (boss_data.state != .dead) { if (snakeCollidingWith(left_engine, enemy_radius)) { _ = async playSprite(left_engine, explosion, 0.1); boss_data.position.x += 30; boss_data.health -= 1; c.PlaySoundMulti(hit_sound); } if (snakeCollidingWith(right_engine, enemy_radius)) { _ = async playSprite(right_engine, explosion, 0.1); boss_data.position.x -= 30; boss_data.health -= 1; c.PlaySoundMulti(hit_sound); } if (boss_data.health < 2) { setBossState(.dead); } } } } // rotate lasers state.lasers_rot += c.GetFrameTime(); // draw lasers for (state.lasers.slice()) |l| { var l0 = l[0]; var l1 = l[1]; if (state.lasers_rot_speed != 0) { l0 = m.Vector2Add(center, m.Vector2Rotate(m.Vector2Subtract(l[0], center), state.lasers_rot)); l1 = m.Vector2Add(center, m.Vector2Rotate(m.Vector2Subtract(l[1], center), state.lasers_rot)); } var any_tail_hit = false; for (state.tail_pos) |p| { if (lineCircleIntersection(l0, l1, p, player_radius) != null) { any_tail_hit = true; break; } } if (any_tail_hit or c.CheckCollisionLines(l0, l1, state.tail_pos[0], state.tail_old_pos[0], null)) { zap(); } const x = time * 5; const y = @sin(4 * x) + @sin(0.3 + x) + @sin(1 - 0.4 * x); c.DrawLineEx(l0, l1, 3 + y * 0.1, c.Color{ .r = 150 + @floatToInt(u8, @fabs(@trunc(20 * y))), .g = 10, .b = 10, .a = 255 }); } coroutines.resumeAll(); c.EndMode2D(); { // draw ui const color = if (state.planet_health > 70) c.GREEN else if (state.planet_health > 30) c.YELLOW else c.RED; if (prev_health != state.planet_health and frame_i % 16 < 4) {} else { c.DrawRing(center, 20, 24, 0, std.math.max(0, state.planet_health), 30, color); } c.DrawFPS(screenWidth - 80, 40); var buf: [64]u8 = undefined; drawText(std.fmt.bufPrintZ(&buf, "Tail left: {d}", .{tailLeft()}) catch "", m.Vector2{ .x = 140, .y = 40 }); if (fade_to_white > 0) { c.DrawRectangle(0, 0, screenWidth, screenHeight, c.Fade(c.WHITE, fade_to_white)); } ui_tasks.resumeAll(); } const mouse_pos = m.Vector2{ .x = @intToFloat(f32, c.GetMouseX()), .y = @intToFloat(f32, c.GetMouseY())}; if (gameplay_state == .alive) { c.DrawLineV( m.Vector2Add(mouse_pos, .{ .x = 0, .y = -5 }), m.Vector2Add(mouse_pos, .{ .x = 0, .y = 5 }), c.Color{ .r = 255, .g = 255, .b = 255, .a = 240 }, ); c.DrawLineV( m.Vector2Add(mouse_pos, .{ .x = -5, .y = 0 }), m.Vector2Add(mouse_pos, .{ .x = 5, .y = 0 }), c.Color{ .r = 255, .g = 255, .b = 255, .a = 240 }, ); } else { c.DrawCircleV(mouse_pos, 2, c.Color{ .r = 255, .g = 255, .b = 255, .a = 40 }); } frame_i += 1; }
https://raw.githubusercontent.com/charles-l/toms-rock/43f7c3eafc7ea5d3ff9aa51976865f1690e29af5/game.zig
const std = @import("std"); pub fn build(b: *std.Build) void { // Grab target & optimization options const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); // Define main EXE entry point and install artifacts const exe = b.addExecutable(.{ .name = "zkr", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); b.installArtifact(exe); // Add run artifact (depends on install) and step 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("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
https://raw.githubusercontent.com/Tythos/zkr/5920279953eb183000ce68e1e14f43a95f510a04/build.zig
const std = @import("std"); const builtin = @import("builtin"); // const Pool: fn (comptime type) type = if (builtin.single_threaded) { // @import("../fakepool.zig").Pool; // } else { // @compileError("multi-threaded not supported yet"); // }; pub fn HashMap(comptime K: type, comptime V: type, comptime Context: type) type { return struct { size: usize, root: PoolRef(Node(struct { K, V })), }; }
https://raw.githubusercontent.com/DanikVitek/monkey-lang/ae9ab1453190c79135b1352cd6a79afb0892a7a1/src/im/hash/map.zig
const std = @import("std"); const dupe = @import("std"); const builtin = @import("builtin"); fn cool() void { std.debug.print("{}", .{"cool"}); dupe.debug.print("{}", .{builtin.os}); }
https://raw.githubusercontent.com/AnnikaCodes/ziglint/d77eb9ecdd02a65b8994bdeceb264b29a7ea1428/testcases/dupe_import/duplicated.zig
//! Image data //! //! //! This describes a single 2D image. See the documentation for each related function what the //! expected pixel format is. //! //! see also: cursor_custom, window_icon //! //! It may be .owned (e.g. in the case of an image initialized by you for passing into glfw) or not //! .owned (e.g. in the case of one gotten via glfw) If it is .owned, deinit should be called to //! free the memory. It is safe to call deinit even if not .owned. const std = @import("std"); const testing = std.testing; const mem = std.mem; const c = @import("c.zig").c; const Image = @This(); /// The width of this image, in pixels. width: u32, /// The height of this image, in pixels. height: u32, /// The pixel data of this image, arranged left-to-right, top-to-bottom. pixels: []u8, /// Whether or not the pixels data is owned by you (true) or GLFW (false). owned: bool, /// Initializes a new owned image with the given size and pixel_data_len of undefined .pixel values. pub inline fn init(allocator: mem.Allocator, width: u32, height: u32, pixel_data_len: usize) !Image { const buf = try allocator.alloc(u8, pixel_data_len); return Image{ .width = width, .height = height, .pixels = buf, .owned = true, }; } /// Turns a GLFW / C image into the nicer Zig type, and sets `.owned = false`. /// /// The length of pixel data must be supplied, as GLFW's image type does not itself describe the /// number of bytes required per pixel / the length of the pixel data array. /// /// The returned memory is valid for as long as the GLFW C memory is valid. pub inline fn fromC(native: c.GLFWimage, pixel_data_len: usize) Image { return Image{ .width = @intCast(u32, native.width), .height = @intCast(u32, native.height), .pixels = native.pixels[0..pixel_data_len], .owned = false, }; } /// Turns the nicer Zig type into a GLFW / C image, for passing into GLFW C functions. /// /// The returned memory is valid for as long as the Zig memory is valid. pub inline fn toC(self: Image) c.GLFWimage { return c.GLFWimage{ .width = @intCast(c_int, self.width), .height = @intCast(c_int, self.height), .pixels = &self.pixels[0], }; } /// Deinitializes the memory using the allocator iff `.owned = true`. pub inline fn deinit(self: Image, allocator: mem.Allocator) void { if (self.owned) allocator.free(self.pixels); } test "conversion" { const allocator = testing.allocator; const image = try Image.init(allocator, 256, 256, 256 * 256 * 4); defer image.deinit(allocator); const glfw = image.toC(); _ = Image.fromC(glfw, image.width * image.height * 4); }
https://raw.githubusercontent.com/perky/ZigGraphics/f89b92f1a893c4df62d9287f376f53c8ea3cc9d1/lib/mach-glfw/src/Image.zig
const std = @import("std"); const ast = @import("ast.zig"); const Node = ast.Node; const Reporter = @import("Reporter.zig"); const Diagnostic = Reporter.Diagnostic; const Extensions = @import("Extensions.zig"); const Self = @This(); const overloads = @import("overloads.zig"); const Overload = overloads.Overload; pub const Type = union(enum) { err, bool, u32, i32, f32, f16, abstract_int, abstract_float, vec2: *const Type, vec3: *const Type, vec4: *const Type, vecN: *const Type, matrix: *Matrix, array: *Array, ref: *MemoryView, ptr: *MemoryView, atomic: *Atomic, fn_decl: *FnDecl, struct_decl: *Struct, pub const FnDecl = struct { params: []Type, ret: ?Type, }; pub fn format(self: Type, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { switch (self) { .err => try writer.writeAll("[error]"), .bool => try writer.writeAll("bool"), .u32 => try writer.writeAll("u32"), .i32 => try writer.writeAll("i32"), .f32 => try writer.writeAll("f32"), .f16 => try writer.writeAll("f16"), .abstract_int => try writer.writeAll("{integer}"), .abstract_float => try writer.writeAll("{float}"), .vec2 => |x| try writer.print("vec2<{}>", .{x}), .vec3 => |x| try writer.print("vec3<{}>", .{x}), .vec4 => |x| try writer.print("vec4<{}>", .{x}), .matrix => |x| try writer.print("mat{}x{}<{}>", .{ x.width, x.height, x.item }), .array => |x| { try writer.print("array<{}", .{x.item}); if (x.length) |len| { try writer.print(", {}", .{len}); } try writer.writeAll(">"); }, .fn_decl => |x| { try writer.writeAll("fn("); for (x.params[0..x.params.len -| 1]) |param| { try writer.print("{}, ", .{param}); } if (x.params.len != 0) { try writer.print("{})", .{x.params[x.params.len - 1]}); } else { try writer.writeAll(")"); } if (x.ret) |ret| { try writer.print(" -> {}", .{ret}); } }, .struct_decl => |x| try writer.writeAll(x.name), .atomic => |x| try writer.print("atomic<{}>", .{x.inner}), .ref => |x| try writer.print("ref<{}>", .{x.inner}), else => @panic("."), } } pub fn isConstructible(self: Type) bool { return switch (self) { .bool, .abstract_int, .abstract_float, .u32, .i32, .f32, .f16 => true, .vec => |_| true, .matrix => |_| true, .array => |arr| if (arr.length == null) false else arr.item.isConstructible(), // TODO: structures else => false, }; } pub fn isNumber(self: Type) bool { return switch (self) { .abstract_int, .abstract_float, .u32, .i32, .f32, .f16 => true, else => false, }; } pub fn normalize(src: Type) Type { return if (src == .abstract_int) .i32 else if (src == .abstract_float) .f32 else if (src == .ref) src.ref.inner else src; } /// Answers if ConversionRank(Src,Dest) != Infinity pub fn isConversionPossible(src: Type, dest: Type) bool { if (dest == .err) return true; return switch (src) { .err => true, .ref => |data| isConversionPossible(data.inner, dest), .abstract_float => dest == .abstract_float or dest == .f32 or dest == .f16, .abstract_int => dest == .abstract_int or dest == .i32 or dest == .u32 or dest == .abstract_float or dest == .f32 or dest == .f16, .i32 => dest == .i32, .u32 => dest == .u32, .f32 => dest == .f32, .f16 => dest == .f16, .bool => dest == .bool, else => false, }; } pub fn alignOf(t: Type) u32 { return switch (t) { .err => 0, .i32, .u32, .f32 => 4, .f16 => 2, .atomic => 4, else => @panic("."), }; } pub const Context = struct { pub fn hashRec(value: Type, seed: *std.hash.Wyhash) void { seed.update(&.{@intFromEnum(value)}); switch (value) { .err, .bool, .u32, .i32, .f32, .f16, .abstract_int, .abstract_float => {}, .vec2 => |x| { hashRec(x.*, seed); }, .vec3 => |x| { hashRec(x.*, seed); }, .vec4 => |x| { hashRec(x.*, seed); }, .vecN => |x| { hashRec(x.*, seed); }, .matrix => |x| { seed.update(std.mem.asBytes(&x.width)); seed.update(std.mem.asBytes(&x.height)); hashRec(x.item, seed); }, .array => |x| { seed.update(std.mem.asBytes(&x.length)); hashRec(x.item, seed); }, .ref => |x| { seed.update(&.{ @intFromEnum(x.access_mode), @intFromEnum(x.addr_space), }); hashRec(x.inner, seed); }, .ptr => |x| { seed.update(&.{ @intFromEnum(x.access_mode), @intFromEnum(x.addr_space), }); hashRec(x.inner, seed); }, .atomic => |x| { hashRec(x.inner, seed); }, .fn_decl => |x| { if (x.ret) |ret_t| { hashRec(ret_t, seed); } for (x.params) |param_t| { hashRec(param_t, seed); } }, .struct_decl => |x| { seed.update(x.name); var iter = x.members.iterator(); while (iter.next()) |entry| { seed.update(entry.key_ptr.*); hashRec(entry.value_ptr.*, seed); } }, } } pub inline fn hash(_: @This(), value: Type) u64 { var seed = std.hash.Wyhash.init(0); hashRec(value, &seed); return seed.final(); } }; }; pub const TypeGenerator = struct { args: []Type, }; pub const Vector = struct { item: Type, size: u32 = 0, }; pub const Matrix = struct { item: Type, width: u32, height: u32, }; pub const Array = struct { item: Type, length: ?u32, }; // https://www.w3.org/TR/WGSL/#ref-ptr-types pub const MemoryView = struct { addr_space: ast.AddrSpace, inner: Type, access_mode: ast.AccessMode, }; pub const Binding = struct { value: Type, flags: packed struct { is_const: bool = false, is_override: bool = false, is_function: bool = false, } = .{}, }; pub const Atomic = struct { inner: Type, }; pub const Struct = struct { name: []const u8, members: std.StringArrayHashMapUnmanaged(Type), }; pub const Env = struct { bindings: std.StringHashMapUnmanaged(Binding) = .{}, parent: ?*Env = null, pub fn getBinding(env: *const Env, name: []const u8) ?Binding { return env.bindings.get(name) orelse if (env.parent) |parent| parent.getBinding(name) else null; } }; allocator: std.mem.Allocator, source: []const u8, reporter: *Reporter, extensions: Extensions = .{}, types: std.StringHashMapUnmanaged(Type) = .{}, pub fn loadGlobalTypes(self: *Self) !void { var map = &.{ .{ "bool", .bool }, .{ "i32", .i32 }, .{ "u32", .u32 }, .{ "f32", .f32 }, }; try self.types.ensureTotalCapacity(self.allocator, map.len); inline for (map) |v| { self.types.putAssumeCapacityNoClobber(v.@"0", v.@"1"); } if (self.extensions.enable_f16) { try self.types.putNoClobber(self.allocator, "f16", .f16); } } inline fn readSpan(self: *const Self, span: ast.Span) []const u8 { return self.source[span.start..span.end]; } pub fn putBinding(self: *Self, env: *Env, span: ast.Span, binding: Binding) !void { var result = try env.bindings.getOrPut(self.allocator, self.readSpan(span)); if (result.found_existing) { self.reporter.add(Diagnostic{ .span = span, .kind = .{ .already_declared = self.readSpan(span) }, }); } else { result.value_ptr.* = binding; } } pub fn inferExpr(self: *Self, env: *Env, expr: Node) !Type { return switch (expr) { .err => .err, .identifier => |span| { var typ = env.getBinding(self.readSpan(span)); return if (typ != null and !typ.?.flags.is_function) { return typ.?.value; } else { self.reporter.add(Diagnostic{ .span = span, .kind = .{ .unknown_name = self.readSpan(span) }, }); return .err; }; }, .number_literal => |data| switch (data.kind) { .u32 => .u32, .i32 => .i32, .f32 => .f32, .f16 => .f16, .abstract_int => .abstract_int, .abstract_float => .abstract_float, }, .boolean_literal => |_| .bool, .paren => |x| return self.inferExpr(env, x.*), .deref => |data| { const value_t = try self.inferExpr(env, data.value); switch (value_t) { .ref => |x| return x.inner, else => {}, } self.reporter.add(Diagnostic{ .span = data.value.span(), .kind = .{ .invalid_deref = value_t }, }); return .err; }, .not, .negate, .bit_not => |data| { const value = try self.inferExpr(env, data.value); const op = Overload{ .kind = switch (expr) { .not => .not, .negate => .neg, .bit_not => .bit_not, else => unreachable, }, .operands = &.{value}, }; if (overloads.get(op)) |idx| { return overloads.sorted.results[idx]; } if (value == .err) { return .err; } // TODO: add diagnostic return .err; }, .cmp_and, .cmp_or, .bit_or, .bit_and => |data| { const lhs = try self.inferExpr(env, data.lhs); const rhs = try self.inferExpr(env, data.rhs); const op = Overload{ .kind = switch (expr) { .cmp_and => .cmp_and, .cmp_or => .cmp_or, .bit_or => .bit_or, .bit_and => .bit_and, else => unreachable, }, .operands = &.{ lhs.normalize(), rhs.normalize() }, }; if (overloads.get(op)) |idx| { return overloads.sorted.results[idx]; } if (lhs == .err or rhs == .err) { return .err; } // TODO: add diagnostic return .err; }, .add, .sub, .mul, .div, .mod, .bit_xor, .bit_left, .bit_right => |data| { var lhs = (try self.inferExpr(env, data.lhs)).normalize(); var rhs = (try self.inferExpr(env, data.rhs)).normalize(); if (lhs == .err or rhs == .err) { return .err; } if (!lhs.isNumber()) { self.reporter.add(Diagnostic{ .span = data.lhs.span(), .kind = .{ .expected_arithmetic_lhs = .{ .got = lhs, } }, }); } if (!Type.isConversionPossible(rhs, lhs)) { self.reporter.add(Diagnostic{ .span = data.rhs.span(), .kind = .{ .not_assignable = .{ .expected = lhs, .got = rhs, } }, }); } return lhs; }, .call => |data| { const callee = switch (data.callee) { .identifier => |span| blk: { const name = self.readSpan(span); const binding = env.getBinding(name) orelse { break :blk try self.resolveType(env, data.callee); }; break :blk binding.value; }, .template => try self.resolveType(env, data.callee), .err => { for (data.args) |arg| { _ = try self.inferExpr(env, arg); } return .err; }, else => try self.inferExpr(env, data.callee), }; switch (callee) { inline .bool, .i32, .u32, .f32 => |_, kind| { switch (data.args.len) { 0 => {}, 1 => { var arg_t = try self.inferExpr(env, data.args[0]); if (!Type.isConversionPossible(arg_t, kind)) { self.reporter.add(Diagnostic{ .span = data.args[0].span(), .kind = .{ .not_assignable = .{ .expected = kind, .got = arg_t, } }, }); return .err; } }, else => { self.reporter.add(Diagnostic{ .span = expr.span(), .kind = .{ .expected_n_args = .{ .expected = 0, .expected_max = 1, .got = @truncate(data.args.len), } } }); return .err; }, } return kind; }, .fn_decl => |fn_decl| { if (data.args.len > fn_decl.params.len) { self.reporter.add(Diagnostic{ .span = ast.Span.init( data.args[fn_decl.params.len].span().start, data.args[data.args.len -| 1].span().end, ), .kind = .{ .expected_n_args = .{ .expected = @truncate(fn_decl.params.len), .got = @truncate(data.args.len), } } }); } else if (data.args.len < fn_decl.params.len) { self.reporter.add(Diagnostic{ .span = expr.span(), .kind = .{ .expected_n_args = .{ .expected = @truncate(fn_decl.params.len), .got = @truncate(data.args.len), } } }); } var end = @min(data.args.len, fn_decl.params.len); for (data.args[0..end], fn_decl.params[0..end]) |arg, param_t| { var arg_t = try self.inferExpr(env, arg); if (!Type.isConversionPossible(arg_t, param_t)) { self.reporter.add(Diagnostic{ .span = arg.span(), .kind = .{ .not_assignable = .{ .expected = param_t, .got = arg_t, } }, }); } } for (data.args[end..]) |arg| { _ = try self.inferExpr(env, arg); } return fn_decl.ret orelse .err; }, else => { // We don't want to double-error. if (callee != .err) { self.reporter.add(Diagnostic{ .span = data.callee.span(), .kind = .{ .not_callable_type = callee }, }); } for (data.args) |arg_t| { _ = try self.inferExpr(env, arg_t); } return .err; }, } }, .equal => |data| { var lhs_t = try self.inferExpr(env, data.lhs); var rhs_t = try self.inferExpr(env, data.rhs); if (!Type.isConversionPossible(rhs_t, lhs_t)) { self.reporter.add(Diagnostic{ .span = data.rhs.span(), .kind = .{ .not_assignable = .{ .expected = lhs_t, .got = rhs_t, } }, }); } return .bool; }, .not_equal => |data| { var lhs_t = try self.inferExpr(env, data.lhs); var rhs_t = try self.inferExpr(env, data.rhs); if (!Type.isConversionPossible(rhs_t, lhs_t)) { self.reporter.add(Diagnostic{ .span = data.rhs.span(), .kind = .{ .not_assignable = .{ .expected = lhs_t, .got = rhs_t, } }, }); } return .bool; }, .member => |data| { var lhs_t = (try self.inferExpr(env, data.lhs)).normalize(); if (data.rhs == .err) return .err; var member = self.readSpan(data.rhs.identifier); if (lhs_t == .struct_decl) { if (lhs_t.struct_decl.members.get(member)) |typ| { return typ; } } self.reporter.add(Diagnostic{ .span = data.rhs.span(), .kind = .{ .no_member = .{ .typ = lhs_t, .member = member, } }, }); return .err; }, else => std.debug.panic("Unimplemented: {}", .{expr}), }; } const BuiltinTemplate = union(enum) { atomic, array, matrix: packed struct { width: u8, height: u8, }, ptr, texture_1d, texture_2d, texture_2d_array, texture_3d, texture_cube, texture_cube_array, texture_multisampled_2d, texture_storage_1d, texture_storage_2d, texture_storage_2d_array, texture_storage_3d, vec2, vec3, vec4, pub const Map = std.ComptimeStringMap(BuiltinTemplate, .{ .{ "atomic", .atomic }, .{ "array", .array }, .{ "mat2x2", .{ .matrix = .{ .width = 2, .height = 2 } } }, .{ "mat2x3", .{ .matrix = .{ .width = 2, .height = 3 } } }, .{ "mat2x4", .{ .matrix = .{ .width = 2, .height = 4 } } }, .{ "mat3x2", .{ .matrix = .{ .width = 3, .height = 2 } } }, .{ "mat3x3", .{ .matrix = .{ .width = 3, .height = 3 } } }, .{ "mat3x4", .{ .matrix = .{ .width = 3, .height = 4 } } }, .{ "mat4x2", .{ .matrix = .{ .width = 4, .height = 2 } } }, .{ "mat4x3", .{ .matrix = .{ .width = 4, .height = 3 } } }, .{ "mat4x4", .{ .matrix = .{ .width = 4, .height = 4 } } }, .{ "ptr", .ptr }, .{ "texture_1d", .texture_1d }, .{ "texture_2d", .texture_2d }, .{ "texture_2d_array", .texture_2d_array }, .{ "texture_3d", .texture_3d }, .{ "texture_cube", .texture_cube }, .{ "texture_cube_array", .texture_cube_array }, .{ "texture_multisampled_2d", .texture_multisampled_2d }, .{ "texture_storage_1d", .texture_storage_1d }, .{ "texture_storage_2d", .texture_storage_2d }, .{ "texture_storage_2d_array", .texture_storage_2d_array }, .{ "texture_storage_3d", .texture_storage_3d }, .{ "vec2", .vec2 }, .{ "vec3", .vec3 }, .{ "vec4", .vec4 }, }); }; fn resolveType(self: *Self, env: *Env, typ: Node) !Type { return switch (typ) { .identifier => |span| { var name = self.readSpan(span); var t = self.types.get(name) orelse { self.reporter.add(Diagnostic{ .span = span, .kind = .{ .unknown_type = name }, }); return .err; }; return t; }, .fn_decl => |data| { var ptr = try self.allocator.create(Type.FnDecl); var params = try self.allocator.alloc(Type, data.params.len); ptr.ret = if (data.ret) |ret| try self.resolveType(env, ret) else null; ptr.params = params; for (data.params, 0..) |node, i| { params[i] = try self.resolveType(env, node.labeled_type.typ); } return Type{ .fn_decl = ptr }; }, .struct_decl => |data| { var members: std.StringArrayHashMapUnmanaged(Type) = .{}; try members.ensureTotalCapacity(self.allocator, @truncate(data.members.len)); for (data.members) |member| { var name = self.readSpan(member.labeled_type.name); var value = try self.resolveType(env, member.labeled_type.typ); members.putAssumeCapacity(name, value); } var ptr = try self.allocator.create(Struct); ptr.* = .{ .name = self.readSpan(data.name), .members = members }; return Type{ .struct_decl = ptr }; }, .template => |data| { const kind = BuiltinTemplate.Map.get(self.readSpan(data.name)) orelse { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .unknown_type = self.readSpan(data.name) }, }); return .err; }; switch (kind) { .atomic => { if (data.args.len != 1) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .expected_n_template_args = .{ .expected = 1, .got = @truncate(data.args.len), } }, }); } var ptr = try self.allocator.create(Atomic); ptr.* = .{ .inner = try self.resolveType(env, data.args[0]) }; return Type{ .atomic = ptr }; }, .array => { if (data.args.len != 1 and data.args.len != 2) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .expected_n_template_args = .{ .expected = 1, .expected_max = 2, .got = @truncate(data.args.len), } }, }); } var ptr = try self.allocator.create(Array); ptr.* = .{ .item = try self.resolveType(env, data.args[0]), .length = null, }; return Type{ .array = ptr }; }, .matrix => |mat| { if (data.args.len != 1) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .expected_n_template_args = .{ .expected = 1, .got = @truncate(data.args.len), } }, }); } var ptr = try self.allocator.create(Matrix); ptr.* = .{ .item = try self.resolveType(env, data.args[0]), .width = mat.width, .height = mat.height, }; return Type{ .matrix = ptr }; }, .ptr => { if (data.args.len != 1) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .expected_n_template_args = .{ .expected = 1, .got = @truncate(data.args.len), } }, }); } var ptr = try self.allocator.create(MemoryView); ptr.* = .{ .addr_space = .function, .inner = try self.resolveType(env, data.args[0]), .access_mode = .read_write, }; return Type{ .ptr = ptr }; }, else => std.debug.panic("{}", .{kind}), } }, else => std.debug.panic("Unimplemented: {}", .{typ}), }; } const DependencyNode = struct { name: ast.Span, value: Node, visited: bool = false, children: union(enum) { // First stage refs: []DependencyNode.Ref, // Second stage nodes: []*DependencyNode, }, pub const Ref = struct { name: ast.Span, kind: Kind, }; pub const Kind = enum { constant, alias, function, }; }; /// Loads all global aliases. pub fn loadTypes(self: *Self, env: *Env, scope: []const Node) !void { var fallback = std.heap.stackFallback(1024, self.allocator); var allocator = fallback.get(); const DependencyKey = struct { name: []const u8, kind: DependencyNode.Kind, }; const DependencyContext = struct { pub fn hash(_: @This(), s: DependencyKey) u64 { var seed = std.hash.Wyhash.init(0); seed.update(&.{@intFromEnum(s.kind)}); seed.update(s.name); return seed.final(); } pub fn eql(ctx: @This(), a: DependencyKey, b: DependencyKey) bool { _ = ctx; return a.kind == b.kind and std.mem.eql(u8, a.name, b.name); } }; var graph = std.HashMap(DependencyKey, DependencyNode, DependencyContext, 80).init(allocator); // Create the vertices for the dependency nodes. for (scope) |node| { switch (node) { .struct_decl => |data| { var stat = try graph.getOrPut(.{ .name = self.readSpan(data.name), .kind = .alias, }); if (stat.found_existing) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .already_declared = self.readSpan(data.name) }, }); } else { stat.value_ptr.* = DependencyNode{ .name = data.name, .value = node, .children = .{ .refs = try self.getDependencies(node) }, }; } }, .type_alias => |data| { var stat = try graph.getOrPut(.{ .name = self.readSpan(data.name), .kind = .alias, }); if (stat.found_existing) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .already_declared = self.readSpan(data.name) }, }); } else { stat.value_ptr.* = DependencyNode{ .name = data.name, .value = data.value, .children = .{ .refs = try self.getDependencies(data.value) }, }; } }, .fn_decl => |data| { var stat = try graph.getOrPut(.{ .name = self.readSpan(data.name), .kind = .function, }); if (stat.found_existing) { self.reporter.add(Diagnostic{ .span = data.name, .kind = .{ .already_declared = self.readSpan(data.name) }, }); } else { var children = std.ArrayList(DependencyNode.Ref).init(allocator); for (data.params) |param_t| { try children.appendSlice(try self.getDependencies(param_t)); } if (data.ret) |ret_t| { try children.appendSlice(try self.getDependencies(ret_t)); } stat.value_ptr.* = DependencyNode{ .name = data.name, .value = node, .children = .{ .refs = try children.toOwnedSlice() }, }; } }, else => {}, } } // Exit early if no sorting work is required. if (graph.count() == 0) { return; } // Create the children for each of the dependency nodes. var iter1 = graph.iterator(); while (iter1.next()) |entry| { var refs = entry.value_ptr.children.refs; var nodes = try std.ArrayList(*DependencyNode).initCapacity(self.allocator, refs.len); for (refs) |ref| { nodes.appendAssumeCapacity( graph.getPtr(.{ .name = self.readSpan(ref.name), .kind = ref.kind, }) orelse continue, // We will report the issue later. ); } entry.value_ptr.children = .{ .nodes = try nodes.toOwnedSlice() }; } // Sort the dependencies using a topological sort. var stack = try std.ArrayList(DependencyNode).initCapacity(allocator, graph.count()); var iter2 = graph.valueIterator(); while (iter2.next()) |value| { if (!value.visited) { dfs(value, &stack); } } // Emit the declarations. for (stack.items) |node| { var resolved = try self.resolveType(env, node.value); if (node.value == .fn_decl) { try env.bindings.put( self.allocator, self.readSpan(node.value.fn_decl.name), Binding{ .value = resolved, .flags = .{ .is_function = true } }, ); continue; } try self.types.put(self.allocator, self.readSpan(node.name), resolved); } } fn getDependencies(self: *Self, node: Node) ![]DependencyNode.Ref { var deps: std.ArrayListUnmanaged(DependencyNode.Ref) = .{}; try self.pushDependencies(&deps, node); return deps.toOwnedSlice(self.allocator); } fn pushDependencies(self: *Self, deps: *std.ArrayListUnmanaged(DependencyNode.Ref), node: Node) !void { switch (node) { .struct_decl => |data| { for (data.members) |member| { try self.pushDependencies(deps, member); } }, .identifier => |span| { var name = self.readSpan(span); if (!self.types.contains(name)) { try deps.append(self.allocator, .{ .name = span, .kind = .alias, }); } }, .labeled_type => |data| { try self.pushDependencies(deps, data.typ); }, .template => |data| { for (data.args) |arg| { try self.pushDependencies(deps, arg); } }, else => {}, } } // Depth-first search on the graph. fn dfs(node: *DependencyNode, stack: *std.ArrayList(DependencyNode)) void { node.visited = true; var i: usize = 0; while (i < node.children.nodes.len) : (i += 1) { var child = node.children.nodes.ptr[i]; if (!child.visited) { dfs(child, stack); } } stack.appendAssumeCapacity(node.*); } pub fn check(self: *Self, env: *Env, node: Node) !void { switch (node) { .err => {}, .discard => {}, .const_assert => |data| { _ = try self.inferExpr(env, data.value); }, .const_decl => |data| { var value_t = try self.inferExpr(env, data.value); if (data.typ) |typ| { var t = try self.resolveType(env, typ); if (!Type.isConversionPossible(value_t, t)) { self.reporter.add(Diagnostic{ .span = data.value.span(), .kind = .{ .not_assignable = .{ .expected = t, .got = value_t, } }, }); } try self.putBinding(env, data.name, Binding{ .value = t, .flags = .{ .is_override = true } }); } else { try self.putBinding(env, data.name, Binding{ .value = value_t, .flags = .{ .is_override = true } }); } }, .override_decl => |data| { if (data.value) |value| { var value_t = try self.inferExpr(env, value); if (data.typ) |typ| { var t = try self.resolveType(env, typ); if (!Type.isConversionPossible(value_t, t)) { self.reporter.add(Diagnostic{ .span = value.span(), .kind = .{ .not_assignable = .{ .expected = t, .got = value_t, } }, }); } try self.putBinding(env, data.name, Binding{ .value = t, .flags = .{ .is_override = true } }); } else { try self.putBinding(env, data.name, Binding{ .value = value_t, .flags = .{ .is_override = true } }); } } else if (data.typ) |typ| { var t = try self.resolveType(env, typ); try self.putBinding(env, data.name, Binding{ .value = t, .flags = .{ .is_override = true } }); } }, .let_decl => |data| { var value = data.value; var value_t = try self.inferExpr(env, value); if (data.typ) |typ| { var t = try self.resolveType(env, typ); if (!Type.isConversionPossible(value_t, t)) { self.reporter.add(Diagnostic{ .span = value.span(), .kind = .{ .not_assignable = .{ .expected = t, .got = value_t, } }, }); } _ = try self.putBinding(env, data.name, Binding{ .value = t }); } else { _ = try self.putBinding(env, data.name, Binding{ .value = value_t.normalize() }); } }, .var_decl => |data| { var value_t = if (data.value) |expr| try self.inferExpr(env, expr) // TODO: verify constructible else if (data.typ) |typ| try self.resolveType(env, typ) else @panic("."); var ptr = try self.allocator.create(MemoryView); ptr.* = MemoryView{ .addr_space = data.addr_space orelse .function, .inner = value_t.normalize(), .access_mode = data.access_mode orelse .read_write, }; _ = try self.putBinding(env, data.name, Binding{ .value = Type{ .ref = ptr } }); }, .type_alias => {}, .struct_decl => {}, .fn_decl => |data| { var scope = Env{ .parent = env }; try scope.bindings.ensureTotalCapacity(self.allocator, @truncate(data.params.len)); for (data.params) |param| { var p: *ast.LabeledType = if (param == .attributed) param.attributed.inner.labeled_type else param.labeled_type; scope.bindings.putAssumeCapacity( self.readSpan(p.name), .{ .value = try self.resolveType(env, p.typ) }, ); } var ret_t = if (data.ret) |ret| try self.resolveType(env, if (ret == .attributed) ret.attributed.inner else ret) else null; for (data.scope) |n| { switch (n) { .ret => |ret_data| { if (ret_data.value) |ret| { if (ret_t) |expected_t| { var got_t = try self.inferExpr(env, ret); if (!Type.isConversionPossible(got_t, expected_t)) { self.reporter.add(Diagnostic{ .span = ret.span(), .kind = .{ .not_assignable = .{ .expected = expected_t, .got = got_t, } }, }); } } } else if (ret_t != null) { self.reporter.add(Diagnostic{ .span = n.span(), .kind = .{ .not_assignable = .{ .expected = ret_t.?, .got = .err, } }, }); } }, else => try self.check(&scope, n), } } }, .call => { _ = try self.inferExpr(env, node); }, .if_stmt => { var next: ?Node = node; while (next) |data| { var sub_env = Env{ .parent = env }; switch (data) { .if_stmt => |d| { var condition = try self.inferExpr(env, d.expression); if (condition != .bool and condition != .err) { self.reporter.add(Diagnostic{ .span = d.expression.span(), .kind = .{ .not_assignable = .{ .expected = .bool, .got = condition, } }, }); } for (d.scope) |n| { try self.check(&sub_env, n); } next = if (d.next) |n| n.* else null; }, .else_stmt => |d| { for (d.scope) |n| { try self.check(&sub_env, n); } next = null; }, else => unreachable, } } }, .attributed => |data| { try self.check(env, data.inner); }, .while_stmt => |data| { var expression = try self.inferExpr(env, data.expression); if (!Type.isConversionPossible(expression, .bool)) { self.reporter.add(Diagnostic{ .span = data.expression.span(), .kind = .{ .not_assignable = .{ .expected = .bool, .got = expression, } }, }); } var sub_env = Env{ .parent = env }; for (data.scope) |n| { try self.check(&sub_env, n); } }, .loop => |data| { var sub_env = Env{ .parent = env }; for (data.scope) |n| { try self.check(&sub_env, n); } }, .assign => |data| { var lhs_t = try self.inferExpr(env, data.lhs); if (lhs_t != .ref) { self.reporter.add(Diagnostic{ .span = data.lhs.span(), .kind = .{ .assignment_not_ref = lhs_t }, }); _ = try self.inferExpr(env, data.rhs); return; } var rhs_t = try self.inferExpr(env, data.rhs); if (!Type.isConversionPossible(rhs_t, lhs_t.ref.inner)) { self.reporter.add(Diagnostic{ .span = data.rhs.span(), .kind = .{ .not_assignable = .{ .expected = lhs_t.ref.inner, .got = rhs_t, } }, }); } }, else => std.debug.panic("Unimplemented: {}", .{node}), } }
https://raw.githubusercontent.com/sno2/gpulse/cfbce883fbc88eeaf10d20979669b74ccd7a3d3b/src/Analyzer.zig
const std = @import("std"); const expect = std.testing.expect; //////////////////////////////////////////////////////////////////////////////////////// ALLOCATORS test "allocation" { const allocator = std.heap.page_allocator; const memory = try allocator.alloc(u8, 100); defer allocator.free(memory); try expect(memory.len == 100); try expect(@TypeOf(memory) == []u8); }
https://raw.githubusercontent.com/ewaldhorn/whatamess/ff94d4af6b435d30564d0e2eb5d25d6f571884fc/languages/zig/learning/ziglearn/chap2/chapter2.zig
const Id = @import("../id.zig").Id; const Host = @import("../host.zig").Host; const Plugin = @import("../plugin.zig").Plugin; const name_size = @import("../string_sizes.zig").name_size; pub const note_ports_id: ?[*:0]const u8 = "clap.note-ports"; pub const NoteDialect = enum(u32) { clap = 1 << 0, midi = 1 << 1, midi_mpe = 1 << 2, midi2 = 1 << 3, }; pub const NotePortInfo = extern struct { id: Id, supported_dialects: NoteDialect, preferred_dialect: NoteDialect, name: [name_size]u8, }; pub const PluginNotePorts = extern struct { count: ?*const fn ( plugin: *const Plugin, is_input: bool, ) callconv(.C) u32, get: ?*const fn ( plugin: *const Plugin, index: u32, is_input: bool, info: *NotePortInfo, ) callconv(.C) bool, }; pub const NotePortsRescanFlags = enum(u32) { all = 1 << 0, names = 1 << 1, }; pub const HostNotePorts = extern struct { supportedDialects: ?*const fn ( host: *const Host, ) callconv(.C) u32, rescan: ?*const fn ( host: *const Host, flags: NotePortsRescanFlags, ) callconv(.C) void, };
https://raw.githubusercontent.com/TristanCrawford/zig-clap/f1a1616271ce7b5951429e4e6813cc6da1fd66a1/src/ext/note_ports.zig
const std = @import("std"); pub const WidowPoint2D = struct { x: i32, y: i32, }; // Shhhhhh. pub const WidowAspectRatio = WidowPoint2D; pub const WidowSize = struct { // The width and hight are both i32 and not u32 // for best compatibility with the API functions // that expects int data type for both width and height. width: i32, height: i32, const Self = @This(); pub fn scaleBy(self: *Self, scaler: f64) void { std.debug.assert(scaler > 0.0); const fwidth: f64 = @floatFromInt(self.width); const fheight: f64 = @floatFromInt(self.height); self.width = @intFromFloat(fwidth * scaler); self.height = @intFromFloat(fheight * scaler); } }; pub const WidowArea = struct { top_left: WidowPoint2D, size: WidowSize, const Self = @This(); pub fn init(x: i32, y: i32, width: i32, height: i32) Self { return Self{ .top_left = WidowPoint2D{ .x = x, .y = y }, .size = WidowSize{ .width = width, .height = height }, }; } };
https://raw.githubusercontent.com/eddineimad0/widow/10e82e84a71db1fbb4da7d88a8e15f736dc5eb73/src/common/geometry.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 = "opencl-gpgpu", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); exe.addIncludePath(.{ .path = "/usr/include/" }); exe.linkSystemLibrary("opencl"); exe.linkLibC(); b.installArtifact(exe); b.installFile("src/program.cl", "bin/program.cl"); const run_cmd = b.addRunArtifact(exe); run_cmd.step.dependOn(b.getInstallStep()); if (b.args) |args| { run_cmd.addArgs(args); } }
https://raw.githubusercontent.com/holaguz/opencl-zig/a36e33c9d516251a41446a3d73077c5739a5825a/build.zig
const DoubleStackAllocatorFlat = @import("../zigutils/src/DoubleStackAllocatorFlat.zig").DoubleStackAllocatorFlat; const Draw = @import("draw.zig"); const Platform = @import("platform/index.zig"); const loadPcx = @import("load_pcx.zig").loadPcx; const FONT_FILENAME = "../assets/font.pcx"; const FONT_CHAR_WIDTH = 8; const FONT_CHAR_HEIGHT = 8; const FONT_NUM_COLS = 16; const FONT_NUM_ROWS = 8; pub const Font = struct.{ tileset: Draw.Tileset, }; pub fn loadFont(dsaf: *DoubleStackAllocatorFlat, font: *Font) !void { const low_mark = dsaf.get_low_mark(); defer dsaf.free_to_low_mark(low_mark); const img = try loadPcx(dsaf, FONT_FILENAME, 0); font.tileset = Draw.Tileset.{ .texture = Platform.uploadTexture(img), .xtiles = FONT_NUM_COLS, .ytiles = FONT_NUM_ROWS, }; } pub fn fontDrawString(ps: *Platform.State, font: *const Font, x: i32, y: i32, string: []const u8) void { var ix = x; const w = FONT_CHAR_WIDTH; const h = FONT_CHAR_HEIGHT; for (string) |char| { const fx = @intToFloat(f32, ix); const fy = @intToFloat(f32, y); const tile = Draw.Tile.{ .tx = char % FONT_NUM_COLS, .ty = char / FONT_NUM_COLS, }; Platform.drawTile(ps, &font.tileset, tile, fx, fy, w, h, Draw.Transform.Identity); ix += FONT_CHAR_WIDTH; } }
https://raw.githubusercontent.com/bb010g/oxid/1314bc024d6394a629b0a85231ecb1187e708ff9/src/font.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 = "zig-cairo", // 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 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, }); 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/jmcph4/zig-cairo/11b9ba5ed80c87cdc1062aa4b93d94f2306d4030/build.zig
// This file is part of zig-spoon, a TUI library for the zig language. // // Copyright © 2022 Leon Henrik Plickat // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License version 3 as published // by the Free Software Foundation. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. pub const version = "0.1.0"; pub const spells = @import("lib/spells.zig"); pub const Attribute = @import("lib/Attribute.zig"); pub const Term = @import("lib/Term.zig"); pub const inputParser = @import("lib/input.zig").inputParser; pub const Input = @import("lib/input.zig").Input; pub const InputContent = @import("lib/input.zig").InputContent; pub const restrictedPaddingWriter = @import("lib/restricted_padding_writer.zig").restrictedPaddingWriter; pub const RestrictedPaddingWriter = @import("lib/restricted_padding_writer.zig").RestrictedPaddingWriter;
https://raw.githubusercontent.com/kristoff-it/zig-spoon/4a2862b0ac6a0551d83ba422755eeaa77114561b/import.zig
const builtin = std.builtin; const std = @import("std"); const io = std.io; const meta = std.meta; const native_endian = @import("builtin").target.cpu.arch.endian(); pub fn toMagicNumberNative(magic: []const u8) u32 { var result: u32 = 0; for (magic) |character, index| { result |= (@as(u32, character) << @intCast(u5, (index * 8))); } return result; } pub fn toMagicNumberForeign(magic: []const u8) u32 { var result: u32 = 0; for (magic) |character, index| { result |= (@as(u32, character) << @intCast(u5, (magic.len - 1 - index) * 8)); } return result; } pub const toMagicNumberBig = switch (native_endian) { builtin.Endian.Little => toMagicNumberForeign, builtin.Endian.Big => toMagicNumberNative, }; pub const toMagicNumberLittle = switch (native_endian) { builtin.Endian.Little => toMagicNumberNative, builtin.Endian.Big => toMagicNumberForeign, }; pub fn readStructNative(reader: io.StreamSource.Reader, comptime T: type) !T { return try reader.readStruct(T); } pub fn readStructForeign(reader: io.StreamSource.Reader, comptime T: type) !T { comptime std.debug.assert(@typeInfo(T).Struct.layout != builtin.TypeInfo.ContainerLayout.Auto); var result: T = undefined; inline for (meta.fields(T)) |entry| { switch (@typeInfo(entry.field_type)) { .ComptimeInt, .Int => { @field(result, entry.name) = try reader.readIntForeign(entry.field_type); }, .Struct => { @field(result, entry.name) = try readStructForeign(reader, entry.field_type); }, .Enum => { @field(result, entry.name) = try reader.readEnum(entry.field_type, switch (native_endian) { builtin.Endian.Little => builtin.Endian.Big, builtin.Endian.Big => builtin.Endian.Little, }); }, else => { @compileError(std.fmt.comptimePrint("Add support for type {} in readStructForeign", .{@typeName(entry.field_type)})); }, } } return result; } pub const readStructLittle = switch (native_endian) { builtin.Endian.Little => readStructNative, builtin.Endian.Big => readStructForeign, }; pub const readStructBig = switch (native_endian) { builtin.Endian.Little => readStructForeign, builtin.Endian.Big => readStructNative, };
https://raw.githubusercontent.com/EspeuteClement/Untitled-Zig-Engine/372145abe8d3e7f1d3eef2c0dff813206d7d4eea/libs/zigimg/src/utils.zig
//! Zig level of IRQ handler const std = @import("std"); const Context = @import("../context.zig").Context; const clock = @import("clock.zig"); const irq = @import("interrupt.zig"); const IRQ_BREAKPOINT: u64 = 3; const IRQ_S_TIMER: u64 = (0b1 << 63) + 5; export fn zig_handler(context: *Context, scause: usize, _: usize) void { // disable interrupts // TODO: allow some interrupts when available irq.disable(); // Handler dispatch switch (scause) { IRQ_BREAKPOINT => { std.log.debug("Break point", .{}); context.sepc += 2; // magic number to bypass ebreak itself, see https://rcore-os.github.io/rCore-Tutorial-deploy/docs/lab-1/guide/part-6.html }, IRQ_S_TIMER => clock.handle(), else => { std.log.err("Interrupt scause: {x}, [sepc] = 0x{x:0>16}", .{ scause, context.sepc }); @panic("Unknown interrupt"); }, } // Re-enable interrupts irq.enable(); } extern fn register_asm_handler() void; /// Setup pub fn init() void { register_asm_handler(); }
https://raw.githubusercontent.com/eastonman/zesty-core/b0fdb2f0a2f00737a97a1605289f3c6633558d6c/src/interrupt/handler.zig
const std = @import("std"); const video = @import("video.zig"); var row: u8 = 0; var col: u8 = 0; pub fn print(comptime fmt: []const u8, args: anytype) void { var print_buffer: [1024]u8 = undefined; var buffer = std.io.fixedBufferStream(&print_buffer); var writer = buffer.writer(); writer.print(fmt, args) catch unreachable; for (buffer.getWritten()) |ch| { putChar(ch); } } pub fn putChar(ch: u8) void { switch (ch) { '\n' => { row += 1; col = 0; }, else => { video.fb.plotChar(ch, row, col); col += 1; if (col == video.fb.maxCol) { col = 0; row += 1; } }, } if (row == video.fb.maxRow) { video.fb.scroll(); row -= 1; } }
https://raw.githubusercontent.com/ahrvojic/zrno/9fcded2199613239c1fc01f4c7caf0b1e1248a0b/kernel/src/dev/tty.zig
const std = @import("std"); pub const ExampleMath = @import("examples/math.zig"); pub const BaseState = @import("UserState.zig").BaseState; pub const MakeUserStateType = @import("UserState.zig").MakeUserStateType; pub const Result = @import("Result.zig").Result; pub const ParseError = @import("Result.zig").ParseError; pub const CSV = @import("CSV.zig").CSVParser; // TODO: Tests // TODO: Better ParserError type // TODO: Rework examples pub const Stream = @import("Stream.zig"); pub const Char = @import("Char.zig"); pub const Combinator = @import("Combinator.zig"); pub const Language = @import("Language.zig"); pub const Expression = @import("Expression.zig").BuildExpressionParser; pub fn pure(stream: Stream, _: std.mem.Allocator, _: *BaseState) anyerror!Result(void) { return Result(void).success(void{}, stream); } pub fn noop(stream: Stream, allocator: std.mem.Allocator, _: *BaseState) anyerror!Result(void) { var error_msg: ParseError = ParseError.init(allocator); try error_msg.appendSlice("Encountered parser NOOP"); return Result(void).failure(error_msg, stream); } pub fn eof(stream: Stream, allocator: std.mem.Allocator, _: *BaseState) anyerror!Result(void) { if (stream.isEOF()) return Result(void).success(void{}, stream); var error_msg = std.ArrayList(u8).init(allocator); var writer = error_msg.writer(); try writer.print("{}: Expected EndOfStream", .{stream}); return Result(void).failure(error_msg, stream); } // T: return type of the given parser // p: Resolved at comptime: // --- Either a parser has a function with no extra arguments // --- Or a tuple of a parser function and a tuple of it's arguments (e.g: .{ fn, .{ ... } }) // --- Or a structure with 2 fields, a parser function and a tuple of it's arguments (e.g: .{ .parser = fn, .args = .{ ... } }) pub inline fn runParser(stream: Stream, allocator: std.mem.Allocator, state: *BaseState, comptime T: type, p: anytype) anyerror!Result(T) { const ParserWrapperType: type = @TypeOf(p); return switch (@typeInfo(ParserWrapperType)) { .Struct => |s| if (s.is_tuple) @call(.auto, p[0], .{ stream, allocator, state } ++ p[1]) else @call(.auto, p.parser, .{ stream, allocator, state } ++ p.args), .Fn => @call(.auto, p, .{ stream, allocator, state }), else => blk: { if (std.debug.runtime_safety) @panic("Invalid Parser given with type: " ++ @typeName(ParserWrapperType)); var msg = std.ArrayList(u8).init(allocator); var writer = msg.writer(); try writer.print("Invalid Parser given with type: {s}", .{@typeName(ParserWrapperType)}); break :blk Result(T).failure(msg, stream); }, }; } // Run parsers p, if it fails, replace the error message with the given string pub inline fn label(stream: Stream, allocator: std.mem.Allocator, state: *BaseState, comptime Value: type, p: anytype, str: []const u8) anyerror!Result(Value) { const r = try runParser(stream, allocator, state, Value, p); switch (r) { .Result => return r, .Error => |err| { var error_msg = std.ArrayList(u8).init(allocator); var writer = error_msg.writer(); try writer.print("{}: {s}", .{ stream, str }); err.msg.deinit(); return Result([]Value).failure(error_msg, stream); }, } } // Return parser, never fails, always return x // Usefull has a fallback pub inline fn ret(stream: Stream, _: std.mem.Allocator, _: *BaseState, comptime Value: type, x: Value) anyerror!Result(Value) { return Result(Value).success(x, stream); } // return parser fParser and run tFunc on the result if successful pub inline fn map(stream: Stream, allocator: std.mem.Allocator, state: *BaseState, comptime From: type, fParser: anytype, comptime To: type, tFnc: *const fn (std.mem.Allocator, From) anyerror!To) anyerror!Result(To) { return switch (try runParser(stream, allocator, state, From, fParser)) { .Result => |res| Result(To).success(try tFnc(allocator, res.value), res.rest), .Error => |err| Result(To).failure(err.msg, err.rest), }; } // S: a structure // mapped_parsers: a list of parsers with it's associated field // --- Parsers are applied in the order they are given. // Example: // // const TestStruct = struct { // a: u8, // b: []const u8, // c: u8, // }; // // toStruct(stream, allocator, state, TestStruct, &.{ // .{ .a, u8, .{ Char.symbol, .{'a'} } }, // first parser, try to match 'a' and populate TestStruct.a with it. // .{ void, u8, .{ Char.symbol, .{','} } }, // Tries to match ',' but doesn't populate any field. // .{ .b, []const u8, .{ Char.string, .{"amazing"} } }, // Tries to match "amazing" and populate TestStruct.b with it. // .{ .c, u8, .{ Char.symbol, .{'c'} } }, // Tried to match 'c' and populate TestStruct.c with it. // }); pub fn toStruct(stream: Stream, allocator: std.mem.Allocator, state: *BaseState, comptime S: type, comptime mapped_parsers: anytype) anyerror!Result(S) { if (@typeInfo(S) != .Struct or @typeInfo(S).Struct.is_tuple == true) { @compileError("toStruct expectes a struct type has arguments, got another type or a tuple"); } var s: S = undefined; var str = stream; inline for (mapped_parsers) |field_parser_tuple| { const maybe_field = field_parser_tuple[0]; const t = field_parser_tuple[1]; const parser = field_parser_tuple[2]; if (@TypeOf(maybe_field) == type and maybe_field == void) { switch (try runParser(str, allocator, state, t, parser)) { .Result => |res| { str = res.rest; }, .Error => |err| return Result(S).failure(err.msg, err.rest), } } else { const field = maybe_field; switch (try runParser(str, allocator, state, t, parser)) { .Result => |res| { @field(s, std.meta.fieldInfo(S, field).name) = res.value; str = res.rest; }, .Error => |err| return Result(S).failure(err.msg, err.rest), } } } return Result(S).success(s, str); } // U: union type // mapped_parsers: a list of parsers with it's associated field // --- Parsers are applied in the order they are given. // Example: // const TaggedUnionTest = union(enum(u32)) { // a: u8, // b: []const u8, // }; // // toTaggedUnion(stream, allocator, state, TaggedUnionTest, &.{ // .{ .a, u8, .{ Char.symbol, .{'a'} } }, // If this parser succeed, return TaggedUnionTest{ .a = 'a' } // .{ .b, []const u8, .{ Char.string, .{"amazing"} } }, // If this parser succeed, return TaggedUnionTest{ .b = "amazing" } // }); pub fn toTaggedUnion(stream: Stream, allocator: std.mem.Allocator, state: *BaseState, comptime U: type, comptime mapped_parsers: anytype) anyerror!Result(U) { if (@typeInfo(U) != .Union) { @panic(""); } var error_msg = std.ArrayList(u8).init(allocator); var writer = error_msg.writer(); try writer.print("{}: Choice Parser:\n", .{stream}); inline for (mapped_parsers) |field_parser_tuple| { const field = field_parser_tuple[0]; const t = field_parser_tuple[1]; const parser = field_parser_tuple[2]; switch (try runParser(stream, allocator, state, t, parser)) { .Result => |res| { error_msg.deinit(); return Result(U).success(@unionInit(U, std.meta.fieldInfo(U, field).name, res.value), res.rest); }, .Error => |err| { try writer.print("\t{s}\n", .{err.msg.items}); err.msg.deinit(); }, } } return Result(U).failure(error_msg, stream); }
https://raw.githubusercontent.com/QuentinTessier/ZigParsec/c8a00cc2ec8d67a875e3ce11f8b98ff2d90cafa8/src/Parser.zig
/// The parser for Sifu tries to make as few decisions as possible. Mostly, it /// greedily lexes seperators like commas into their own ast nodes, separates /// vars and vals based on the first character's case, and lazily lexes non- /// strings. There are no errors, any utf-8 text is parsable. /// const Parser = @This(); const std = @import("std"); const Allocator = std.mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const panic = std.debug.panic; const util = @import("../util.zig"); const fsize = util.fsize(); const Pat = @import("ast.zig").Pat; const Ast = Pat.Node; const Pattern = @import("../pattern.zig").Pattern; const syntax = @import("syntax.zig"); const Token = syntax.Token(usize); const Term = syntax.Term; const Type = syntax.Type; const Set = util.Set; const ArrayListUnmanaged = std.ArrayListUnmanaged; const ArrayList = std.ArrayList; const Oom = Allocator.Error; const Order = std.math.Order; const mem = std.mem; const math = std.math; const assert = std.debug.assert; const debug = std.debug; const meta = std.meta; const print = util.print; // TODO add indentation tracking, and separate based on newlines+indent // TODO revert parsing to assume apps at all levels, with ops as appended, // single terms to apps (add a new branch for the current way of parsing) /// Convert this token to a term by parsing its literal value. pub fn parseTerm(term: Token) Oom!Term { return switch (term.type) { .Name, .Str, .Var, .Comment => term.lit, .Infix => term.lit, .I => if (std.fmt.parseInt(usize, term.lit, 10)) |i| i else |err| switch (err) { // token should only have consumed digits error.InvalidCharacter => unreachable, // TODO: arbitrary ints here error.Overflow => unreachable, }, .U => if (std.fmt.parseUnsigned(usize, term.lit, 10)) |i| i else |err| switch (err) { error.InvalidCharacter => unreachable, // TODO: arbitrary ints here error.Overflow => unreachable, }, .F => std.fmt.parseFloat(fsize, term.lit) catch unreachable, }; } fn consumeNewLines(lexer: anytype, reader: anytype) !bool { var consumed: bool = false; // Parse all newlines while (try lexer.peek(reader)) |next_token| if (next_token.type == .NewLine) { _ = try lexer.next(reader); consumed = true; } else break; return consumed; } const ParseError = error{ NoLeftBrace, NoRightBrace, NoLeftParen, NoRightParen, }; pub fn parseAst( allocator: Allocator, lexer: anytype, ) ![]const Ast { // TODO (ParseError || @TypeOf(lexer).Error || Allocator.Error) // No need to destroy asts, they will all be returned or cleaned up var levels = ArrayListUnmanaged(Level){}; defer levels.deinit(allocator); try levels.append(allocator, Level{}); errdefer { // TODO: add test coverage for (levels.items) |*level| { Ast.ofApps(level.root).deinit(allocator); for (level.current.items) |*ast| ast.deinit(allocator); level.current.deinit(allocator); } levels.deinit(allocator); } while (try lexer.nextLine()) |line| { defer lexer.allocator.free(line); if (try parseAppend(allocator, &levels, line)) |ast| return ast else continue; } return &.{}; } /// This encodes the values needed to parse a specific level of nesting. These /// fields would be the parameters in a recursive algorithm. const Level = struct { // This contains the current Ast being parsed. root: []const Ast = &.{}, // This is temporary storage for an op's rhs so that they don't need to be // removed from the current list when done current: ArrayListUnmanaged(Ast) = ArrayListUnmanaged(Ast){}, // This points to the last op parsed for a level of nesting. This tracks // infixes for each level of nesting, in congruence with the parse stack. // These are nullable because each level of nesting gets a new relative // tail, which is null until an op is found, and can only be written to once // the entire level of nesting is parsed (apart from another infix). Like // the parse stack, indices here correspond to a level of nesting, while // infixes mutate the element at their index as they are parsed. maybe_op_tail: ?*Ast = null, is_pattern: bool = false, /// Write the next terms to this operator, if any. Anything apart from slice /// kinds (`.Infix`, `.Match` etc.) will be apps. Returns a pointer to the /// op if one was finalized. fn finalize( level: *Level, is_op: bool, allocator: Allocator, ) ![]const Ast { const current_slice = try level.current.toOwnedSlice(allocator); if (level.maybe_op_tail) |tail| switch (tail.*) { // After we set this pointer, current_slice cannot be freed. .key, .variable, .var_apps, .pattern => @panic( "cannot finalize non-slice type\n", ), inline else => |_, tag| tail.* = @unionInit(Ast, @tagName(tag), current_slice), } else { // No tail yet means we need to init root level.root = current_slice; } // Set the next tail, if needed if (is_op) level.maybe_op_tail = &current_slice[current_slice.len - 1]; return level.root; } }; /// Does not allocate on errors or empty parses. Parses the line of tokens, /// returning a partial Ast on trailing operators or unfinished nesting. In such /// a case, null is returned and the same parser_stack must be reused to finish /// parsing. Otherwise, an Ast is returned from an ownded slice of parser_stack. // Precedence: semis < long arrow, long match < commas < infix < arrow, match // - TODO: [] should be a flat Apps instead of as an infix pub fn parseAppend( allocator: Allocator, levels: *ArrayListUnmanaged(Level), line: []const Token, ) !?[]const Ast { // These variables are relative to the current level of nesting being parsed var level = levels.pop(); for (line) |token| { const current_ast = switch (token.type) { .Name => Ast.ofLit(token), inline .Infix, .Match, .Arrow, .Comma => |tag| { const op_tag: meta.Tag(Ast) = switch (tag) { .Infix => .infix, .Arrow => .arrow, .Match => .match, .Comma => .list, else => unreachable, }; // if (level.maybe_op_tail) |tail| // if (@intFromEnum(op_tag) < @intFromEnum(level.root)) { // print("Parsing lower precedence\n", .{}); // print("Op: ", .{}); // level.root.write(stderr) catch unreachable; // print("\n", .{}); // _ = tail; // }; if (tag == .Infix) try level.current.append(allocator, Ast.ofLit(token)); // Add an apps for the trailing args try level.current.append( allocator, @unionInit(Ast, @tagName(op_tag), &.{}), ); // Right hand args for previous op with higher precedence _ = try level.finalize(true, allocator); continue; }, .LeftParen => { // Save index of the nested app to write to later try levels.append(allocator, level); // Reset vars for new nesting level level = Level{}; continue; }, .RightParen => blk: { defer level = levels.pop(); break :blk Ast.ofApps(try level.finalize(false, allocator)); }, .Var => Ast.ofVar(token.lit), .VarApps => Ast.ofVarApps(token.lit), .Str, .I, .F, .U => Ast.ofLit(token), .Comment, .NewLine => Ast.ofLit(token), else => @panic("unimplemented"), }; try level.current.append(allocator, current_ast); } const result = try level.finalize(false, allocator); // TODO: return optional void and move to caller return result; } // Convert a list of nodes into a single node, depending on its type pub fn intoNode( allocator: Allocator, kind: Ast, nodes: *ArrayListUnmanaged(Ast), ) !Ast { return switch (kind) { .apps => Ast.ofApps(try nodes.toOwnedSlice(allocator)), .pattern => blk: { print("pat\n", .{}); var pattern = Pat{}; for (nodes.items) |ast| _ = try pattern.insertNode(allocator, ast); break :blk Ast.ofPattern(pattern); }, else => @panic("unimplemented"), }; } // Assumes apps are Infix encoded (they have at least one element). fn getOpTailOrNull(ast: Ast) ?*Ast { return switch (ast) { .apps, .arrow, .match, .list => |apps| @constCast(&apps[apps.len - 1]), else => null, }; } // This function is the responsibility of the Parser, because it is the dual // to parsing. // pub fn print(ast: anytype, writer: anytype) !void { // switch (ast) { // .apps => |asts| if (asts.len > 0 and asts[0] == .key and // asts[0].key.type == .Infix) // { // const key = asts[0].key; // // An infix always forms an App with at least // // nodes, the second of which must be an App (which // // may be empty) // assert(asts.len >= 2); // assert(asts[1] == .apps); // try writer.writeAll("("); // try print(asts[1], writer); // try writer.writeByte(' '); // try writer.writeAll(key.lit); // if (asts.len >= 2) // for (asts[2..]) |arg| { // try writer.writeByte(' '); // try print(arg, writer); // }; // try writer.writeAll(")"); // } else if (asts.len > 0) { // try writer.writeAll("("); // try print(asts[0], writer); // for (asts[1..]) |it| { // try writer.writeByte(' '); // try print(it, writer); // } // try writer.writeAll(")"); // } else try writer.writeAll("()"), // .key => |key| try writer.print("{s}", .{key.lit}), // .variable => |v| try writer.print("{s}", .{v}), // .pat => |pat| try pat.print(writer), // } // } const testing = std.testing; const expectEqualStrings = testing.expectEqualStrings; const fs = std.fs; const io = std.io; const Lexer = @import("Lexer.zig") .Lexer(io.FixedBufferStream([]const u8).Reader); const List = ArrayListUnmanaged(Ast); // for debugging with zig test --test-filter, comment this import const verbose_tests = @import("build_options").verbose_tests; // const stderr = if (false) const stderr = if (verbose_tests) std.io.getStdErr().writer() else std.io.null_writer; test "simple val" { var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); var fbs = io.fixedBufferStream("Asdf"); var lexer = Lexer.init(arena.allocator(), fbs.reader()); const ast = try parseAst(arena.allocator(), &lexer); try testing.expect(ast == .apps and ast.apps.len == 1); try testing.expectEqualStrings(ast.apps[0].key.lit, "Asdf"); } fn testStrParse(str: []const u8, expecteds: []const Ast) !void { var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); var fbs = io.fixedBufferStream(str); var lexer = Lexer.init(allocator, fbs.reader()); const actuals = try parseAst(allocator, &lexer); for (expecteds, actuals.apps) |expected, actual| { try expectEqualApps(expected, actual); } } fn expectEqualApps(expected: Ast, actual: Ast) !void { try stderr.writeByte('\n'); try stderr.writeAll("Expected: "); try expected.write(stderr); try stderr.writeByte('\n'); try stderr.writeAll("Actual: "); try actual.write(stderr); try stderr.writeByte('\n'); try testing.expect(.apps == expected); try testing.expect(.apps == actual); try testing.expectEqual(expected.apps.len, actual.apps.len); // This is redundant, but it makes any failures easier to trace for (expected.apps, actual.apps) |expected_elem, actual_elem| { if (@intFromEnum(expected_elem) == @intFromEnum(actual_elem)) { switch (expected_elem) { .key => |key| { try testing.expectEqual( @as(Order, .eq), key.order(actual_elem.key), ); try testing.expectEqualDeep( key.lit, actual_elem.key.lit, ); }, .variable => |v| try testing.expect(mem.eql(u8, v, actual_elem.variable)), .apps => try expectEqualApps(expected_elem, actual_elem), .match => |_| @panic("unimplemented"), .arrow => |_| @panic("unimplemented"), .pattern => |pattern| try testing.expect( pattern.eql(actual_elem.pattern.*), ), } } else { try stderr.writeAll("Asts of different types not equal"); try testing.expectEqual(expected_elem, actual_elem); // above line should always fail debug.panic( "Asserted asts were equal despite different types", .{}, ); } } // Variants of this seem to cause the compiler to error with GenericPoison // try testing.expectEqual(@as(Order, .eq), expected.order(actual)); // try testing.expect(.eq == expected.order(actual)); } test "All Asts" { const input = \\Name1,5; \\var1. \\Infix --> \\5 < 10.V \\1 + 2.0 \\$strat \\ \\10 == 10 \\10 != 9 \\"foo".len \\[1, 2] \\{"key":1} \\// a comment \\|| \\() ; const expecteds = &[_]Ast{Ast{ .apps = &.{ .{ .key = .{ .type = .Name, .lit = "Name1", .context = 0, } }, .{ .key = .{ .type = .Name, .lit = ",", .context = 4, } }, .{ .key = .{ .type = .I, .lit = "5", .context = 5, } }, .{ .key = .{ .type = .Name, .lit = ";", .context = 6, } }, }, }}; try testStrParse(input[0..7], expecteds); // try expectEqualApps(expected, expected); // test the test function } test "App: simple vals" { const expecteds = &[_]Ast{Ast{ .apps = &.{ Ast{ .key = .{ .type = .Name, .lit = "Aa", .context = 0, } }, Ast{ .key = .{ .type = .Name, .lit = "Bb", .context = 3, } }, Ast{ .key = .{ .type = .Name, .lit = "Cc", .context = 6, } }, }, }}; try testStrParse("Aa Bb Cc", expecteds); } test "App: simple op" { const expecteds = &[_]Ast{ Ast{ .apps = &.{ Ast{ .key = .{ .type = .Infix, .lit = "+", .context = 2, }, }, Ast{ .apps = &.{Ast{ .key = .{ .type = .I, .lit = "1", .context = 0, }, }}, }, Ast{ .key = .{ .type = .I, .lit = "2", .context = 4, }, }, } }, }; try testStrParse("1 + 2", expecteds); } test "App: simple ops" { const expecteds = &[_]Ast{Ast{ .apps = &.{ Ast{ .key = .{ .type = .Infix, .lit = "+", .context = 6, } }, Ast{ .apps = &.{ Ast{ .key = .{ .type = .Infix, .lit = "+", .context = 2, } }, Ast{ .apps = &.{ Ast{ .key = .{ .type = .I, .lit = "1", .context = 0, } }, } }, Ast{ .key = .{ .type = .I, .lit = "2", .context = 4, } }, } }, Ast{ .key = .{ .type = .I, .lit = "3", .context = 8, } }, }, }}; try testStrParse("1 + 2 + 3", expecteds); } test "App: simple op, no first arg" { const expecteds = &[_]Ast{Ast{ .apps = &.{ Ast{ .key = .{ .type = .Infix, .lit = "+", .context = 2, }, }, Ast{ .apps = &.{} }, Ast{ .key = .{ .type = .I, .lit = "2", .context = 4, }, }, }, }}; try testStrParse("+ 2", expecteds); } test "App: simple op, no second arg" { const expecteds = &[_]Ast{Ast{ .apps = &.{ Ast{ .key = .{ .type = .Infix, .lit = "+", .context = 2, }, }, Ast{ .apps = &.{ Ast{ .key = .{ .type = .I, .lit = "1", .context = 0, } }, } }, }, }}; try testStrParse("1 +", expecteds); } test "App: simple parens" { const expected = Ast{ .apps = &.{ Ast{ .apps = &.{} }, Ast{ .apps = &.{} }, Ast{ .apps = &.{ Ast{ .apps = &.{} }, } }, } }; try testStrParse("()() (())", &.{expected}); } test "App: empty" { try testStrParse(" \n\n \n \n\n\n", &.{}); } test "App: nested parens 1" { const expecteds = &[_]Ast{ Ast{ .apps = &.{ Ast{ .apps = &.{} }, } }, Ast{ .apps = &.{ Ast{ .apps = &.{} }, Ast{ .apps = &.{} }, Ast{ .apps = &.{ Ast{ .apps = &.{} }, } }, } }, // Ast{.apps = &.{ ) // Ast{ .apps = &.{ ) // Ast{ .apps = &.{ ) // Ast{ .apps = &.{} }, // Ast{ .apps = &.{} }, // } }, // Ast{ .apps = &.{} }, // } }, // } }, // Ast{.apps = &.{ ) // Ast{ .apps = &.{ ) // Ast{ .apps = &.{} }, // Ast{ .apps = &.{ ) // Ast{ .apps = &.{} }, // } }, // } }, // Ast{ .apps = &.{} }, // } }, }; try testStrParse( \\ () \\ () () ( () ) // \\( // \\ ( // \\ () () // \\ ) // \\ () // \\) // \\ ( () ( ()) )( ) , expecteds); } test "App: simple newlines" { const expecteds = &[_]Ast{ Ast{ .apps = &.{ Ast{ .key = .{ .type = .Name, .lit = "Foo", .context = 0, } }, } }, Ast{ .apps = &.{ Ast{ .key = .{ .type = .Name, .lit = "Bar", .context = 0, } }, } }, }; try testStrParse( \\ Foo \\ Bar , expecteds); } test "Apps: pattern eql hash" { var arena = ArenaAllocator.init(testing.allocator); defer arena.deinit(); const allocator = arena.allocator(); var fbs1 = io.fixedBufferStream("{1,{2},3 -> A}"); var fbs2 = io.fixedBufferStream("{1, {2}, 3 -> A}"); var fbs3 = io.fixedBufferStream("{1, {2}, 3 -> B}"); var lexer1 = Lexer.init(allocator, fbs1.reader()); var lexer2 = Lexer.init(allocator, fbs2.reader()); var lexer3 = Lexer.init(allocator, fbs3.reader()); const ast1 = try parseAst(allocator, &lexer1); const ast2 = try parseAst(allocator, &lexer2); const ast3 = try parseAst(allocator, &lexer3); // try testing.expectEqualStrings(ast.?.apps[0].pat, "Asdf"); try testing.expect(ast1.eql(ast2)); try testing.expectEqual(ast1.hash(), ast2.hash()); try testing.expect(!ast1.eql(ast3)); try testing.expect(!ast2.eql(ast3)); try testing.expect(ast1.hash() != ast3.hash()); try testing.expect(ast2.hash() != ast3.hash()); }
https://raw.githubusercontent.com/Rekihyt/Sifu/9625ad48a62dd6ea3cba0e6e7f0a14c246e779ce/src/sifu/parser.zig
const std = @import("std"); const slotmap = @import("slotmap"); const Key = slotmap.Key; const SlotMap = slotmap.SlotMap; const print = std.debug.print; pub fn main() void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var persons = SlotMap([]const u8).new(&arena.allocator); const michael = persons.insert("Michael"); const christine = persons.insert("Christine"); if (persons.remove(michael)) |name| { print("Removed an entity named {s}\n", .{name}); } print("Name of entity is {s}\n", .{persons.get(christine).?.*}); }
https://raw.githubusercontent.com/mmstick/zig-slotmap/3e67e6a79c325388b9377c762ef9b47b4c11ef0f/examples/slotmap.zig
const std = @import("std"); const win = @cImport({ @cInclude("conio.h"); }); pub fn main() !void { var char : std.os.windows.UINT= @intCast(u8, win._getch() & 0xff); if (char == 224 or char == 0) { char = @intCast(u8, win._getch() & 0xff); try std.io.getStdOut().writer().print("{x}{x}", .{224, char}); } else { try std.io.getStdOut().writer().print("{x}", .{char}); } }
https://raw.githubusercontent.com/DivergentClouds/batch-utils/9dce9d0af2e2f163c48d8a552cd4dfba0ed5079c/getch/src/main.zig
//! Regular sound that can be played in the audio environment. const sf = struct { const sfml = @import("../sfml.zig"); pub usingnamespace sfml; pub usingnamespace sfml.audio; }; const Sound = @This(); // Constructor/destructor /// Inits an empty sound pub fn create() !Sound { const sound = sf.c.sfSound_create(); if (sound) |s| { return Sound{ ._ptr = s }; } else return sf.Error.nullptrUnknownReason; } /// Inits a sound with a SoundBuffer object pub fn createFromBuffer(buffer: sf.SoundBuffer) !Sound { var sound = try Sound.create(); sound.setBuffer(buffer); return sound; } /// Destroys this sound object pub fn destroy(self: *Sound) void { sf.c.sfSound_destroy(self._ptr); self._ptr = undefined; } // Sound control functions /// Plays the sound pub fn play(self: *Sound) void { sf.c.sfSound_play(self._ptr); } /// Pauses the sound pub fn pause(self: *Sound) void { sf.c.sfSound_pause(self._ptr); } /// Stops the sound and resets the player position pub fn stop(self: *Sound) void { sf.c.sfSound_stop(self._ptr); } // Getters / Setters /// Gets the buffer this sound is attached to pub fn getBuffer(self: Sound) ?sf.SoundBuffer { const buf = sf.c.sfSound_getBuffer(self._ptr); if (buf) |buffer| { return .{ ._ptr = buffer }; } else return null; } /// Sets the buffer this sound will play pub fn setBuffer(self: *Sound, buffer: sf.SoundBuffer) void { sf.c.sfSound_setBuffer(self._ptr, buffer._ptr); } /// Gets the current playing offset of the sound pub fn getPlayingOffset(self: Sound) sf.Time { return sf.Time._fromCSFML(sf.c.sfSound_getPlayingOffset(self._ptr)); } /// Sets the current playing offset of the sound pub fn setPlayingOffset(self: *Sound, offset: sf.Time) void { sf.c.sfSound_setPlayingOffset(self._ptr, offset._toCSFML()); } /// Tells whether or not this sound is in loop mode pub fn getLoop(self: Sound) bool { return sf.c.sfSound_getLoop(self._ptr) != 0; } /// Enable or disable auto loop pub fn setLoop(self: *Sound, loop: bool) void { sf.c.sfSound_setLoop(self._ptr, @intFromBool(loop)); } /// Sets the pitch of the sound pub fn getPitch(self: Sound) f32 { return sf.c.sfSound_getPitch(self._ptr); } /// Gets the pitch of the sound pub fn setPitch(self: *Sound, pitch: f32) void { sf.c.sfSound_setPitch(self._ptr, pitch); } /// Sets the volume of the sound pub fn getVolume(self: Sound) f32 { return sf.c.sfSound_getVolume(self._ptr); } /// Gets the volume of the sound pub fn setVolume(self: *Sound, volume: f32) void { sf.c.sfSound_setVolume(self._ptr, volume); } pub const getStatus = @compileError("Function is not implemented yet."); pub const setRelativeToListener = @compileError("Function is not implemented yet."); pub const isRelativeToListener = @compileError("Function is not implemented yet."); pub const setMinDistance = @compileError("Function is not implemented yet."); pub const setAttenuation = @compileError("Function is not implemented yet."); pub const getMinDistance = @compileError("Function is not implemented yet."); pub const getAttenuation = @compileError("Function is not implemented yet."); /// Pointer to the csfml sound _ptr: *sf.c.sfSound,
https://raw.githubusercontent.com/Guigui220D/zig-sfml-wrapper/b15365bf0622e7f42c13b711dbd637c6badc8492/src/sfml/audio/Sound.zig
const std = @import("std"); const MMU = @import("memory.zig"); usingnamespace @import("instructions.zig"); const Self = @This(); const TileSide: u4 = 8; const TileMapAddrs = [2]u16{ 0x9800, // 0 = 9800 -> 9BFF 0x9C00, // 1 = 9C00 -> 9FFF }; const Sprite = packed struct { y_position: u8, x_position: u8, tile_index: u8, attributes: packed struct { unused: u4, palette: u1, x_flip: u1, y_flip: u1, priority: u1, }, }; const SpriteLineLimit: usize = 10; const SpriteTableStart: u16 = 0xFE00; const SpriteTableEnd: u16 = 0xFE9F; const SpriteTableCapacity: usize = 40; const PPUState = enum { h_blank, v_blank, oam_scan, pixel_transfer, }; const HBlankDots = 204; const VBlankDots = 456; const OAMScanDots = 80; const PixelTransferDots = 172; const VBlankLine = 143; const RenderLine = 153; const FramebufferWidth = 160; const FramebufferHeight = 144; const FramebufferSize = FramebufferWidth * FramebufferHeight; mmu: *MMU, allocator: std.mem.Allocator, framebuffer: *[FramebufferSize]u8, line: u8, win_line: usize, dots: usize, ready: bool, state: PPUState, pub fn init(mmu: *MMU, allocator: std.mem.Allocator) !Self { const framebuffer = try allocator.alloc(u8, FramebufferSize); return Self{ .mmu = mmu, .allocator = allocator, .framebuffer = framebuffer[0..FramebufferSize], .line = 0, .dots = 0, .win_line = 0, .ready = false, .state = .h_blank, }; } pub fn deinit(self: *Self) void { self.allocator.free(self.framebuffer); } fn pixelColor(palette: u8, index: u2) u8 { const PixelWhite = 0xFF; const PixelLight = 0x80; const PixelDark = 0x40; const PixelBlack = 0x16; const shift = 2 * @intCast(u3, index); return switch (@truncate(u2, palette >> shift)) { 0 => PixelWhite, 1 => PixelLight, 2 => PixelDark, 3 => PixelBlack, }; } const ReadTileMode = enum { block_0, block_1 }; fn readTilePixel(self: *Self, id: u8, x: u4, y: u4, mode: ReadTileMode) u2 { const addr = switch (mode) { .block_0 => 0x8000 + 16 * @intCast(u16, id), .block_1 => 0x8800 + 16 * @intCast(u16, id +% 0x80), }; const row = self.mmu.read(u16, addr + 2 * @intCast(u16, y)); const bit1 = @truncate(u2, row >> (14 - x)) & 0b10; const bit2 = @truncate(u2, row >> (07 - x)) & 0b01; return bit1 | bit2; } fn drawBackgroundPixelLine(self: *Self) void { const lcd_control = self.mmu.ioLCDControl(); const scx = self.mmu.ioRegister(.scroll_x).*; const scy = self.mmu.ioRegister(.scroll_y).*; const palette = self.mmu.ioRegister(.bg_palette).*; const tilemap = TileMapAddrs[lcd_control.background_tilemap]; var pixel_x: u8 = 0; while (pixel_x < FramebufferWidth) : (pixel_x += 1) { const x = scx +% pixel_x; const y = scy +% self.line; const id = self.mmu.read(u8, tilemap + @intCast(u16, y / 8) * 32 + (x / 8)); const tile_x = @intCast(u4, x % 8); const tile_y = @intCast(u4, y % 8); const pixel = self.readTilePixel(id, tile_x, tile_y, switch (lcd_control.bg_win_tiledata) { 0 => .block_1, 1 => .block_0, }); const fb_index = @intCast(usize, self.line) * FramebufferWidth + pixel_x; self.framebuffer[fb_index] = pixelColor(palette, pixel); } } fn drawWindowPixelLine(self: *Self) void { const lcd_control = self.mmu.ioLCDControl(); const wx = self.mmu.ioRegister(.window_x).*; const wy = self.mmu.ioRegister(.window_y).*; if (self.line < wy) return; if (FramebufferWidth - 7 < wx) return; const palette = self.mmu.ioRegister(.bg_palette).*; const tilemap = TileMapAddrs[lcd_control.window_tilemap]; const line_y = self.win_line; self.win_line += 1; var pixel_x: u8 = if (wx > 7) wx - 7 else 0; while (pixel_x < FramebufferWidth) : (pixel_x += 1) { const x = pixel_x + 7 - wx; const y = line_y; const id = self.mmu.read(u8, tilemap + @intCast(u16, y / 8) * 32 + (x / 8)); const tile_x = @intCast(u4, x % 8); const tile_y = @intCast(u4, y % 8); const pixel = self.readTilePixel(id, tile_x, tile_y, switch (lcd_control.bg_win_tiledata) { 0 => .block_1, 1 => .block_0, }); const fb_index = @intCast(usize, self.line) * FramebufferWidth + pixel_x; self.framebuffer[fb_index] = pixelColor(palette, pixel); } } fn readSprite(self: *Self, id: u8) Sprite { return self.mmu.read(Sprite, SpriteTableStart + @sizeOf(Sprite) * id); } fn drawSpritesPixelLine(self: *Self) void { const lcd_control = self.mmu.ioLCDControl(); const actual_line: usize = self.line + 16; const sprite_height: u8 = if (lcd_control.sprites_tall) 16 else 8; var sprite_id: u8 = 0; var sprites_drawn: usize = 0; while (sprite_id < SpriteTableCapacity) : (sprite_id += 1) { // Do not draw more than 10 sprites per line. if (sprites_drawn >= SpriteLineLimit) break; const sprite = self.readSprite(sprite_id); if (sprite.y_position > actual_line) continue; if (sprite.y_position + sprite_height <= actual_line) continue; sprites_drawn += 1; const palette = switch (sprite.attributes.palette) { 0 => self.mmu.ioRegister(.spr_palette_0).*, 1 => self.mmu.ioRegister(.spr_palette_1).*, }; const spry = @truncate(u4, actual_line - sprite.y_position); var sprx = @intCast(u4, std.math.max(0, TileSide - @intCast(i16, sprite.x_position))); while (sprx < 8) : (sprx += 1) { const px = if (sprite.attributes.x_flip == 1) TileSide - 1 - sprx else sprx; const py = if (sprite.attributes.y_flip == 1) TileSide - 1 - spry else spry; const pixel = self.readTilePixel(sprite.tile_index, px, py, .block_0); const pixel_x = sprite.x_position + sprx - 8; const fb_index = @intCast(usize, self.line) * FramebufferWidth + pixel_x; self.framebuffer[fb_index] = pixelColor(palette, pixel); } } } fn drawPixelLine(self: *Self) void { const lcd_control = self.mmu.ioLCDControl(); if (lcd_control.bg_win_enable) { self.drawBackgroundPixelLine(); } if (lcd_control.bg_win_enable and lcd_control.window_enable) { self.drawWindowPixelLine(); } if (lcd_control.sprites_enable) { self.drawSpritesPixelLine(); } } fn lineNext(self: *Self) void { self.line +%= 1; const lyc = self.mmu.ioRegister(.lcd_y_compare).*; self.mmu.ioRegister(.lcd_y_coord).* = self.line; self.mmu.ioLCDStatus().lyc_equal_ly = self.line == lyc; if (self.line == lyc and self.mmu.ioLCDStatus().lyc_interrupt) { self.mmu.fireInterrupt(.lcd_status); } } fn finishFrame(self: *Self) void { self.ready = true; self.line = 0xFF; self.win_line = 0x0; self.lineNext(); } fn updateState(self: *Self, comptime new_state: PPUState) void { self.state = new_state; self.mmu.ioLCDStatus().draw_stage = switch (new_state) { .v_blank => .v_blank, .h_blank => .h_blank, .oam_scan => .oam_scan, .pixel_transfer => .pixel_transfer, }; switch (new_state) { .v_blank => if (self.mmu.ioLCDStatus().vblank_interrupt) { self.mmu.fireInterrupt(.lcd_status); }, .h_blank => if (self.mmu.ioLCDStatus().hblank_interrupt) { self.mmu.fireInterrupt(.lcd_status); }, .oam_scan => if (self.mmu.ioLCDStatus().oam_interrupt) { self.mmu.fireInterrupt(.lcd_status); }, else => {}, } } pub fn step(self: *Self, clocks: usize) bool { // Step CPU continously while PPU is off. if (!self.mmu.ioLCDControl().lcd_ppu_enable) { return true; } self.dots += clocks; switch (self.state) { .h_blank => if (self.dots >= HBlankDots) { self.dots %= HBlankDots; if (self.line == VBlankLine) { self.updateState(.v_blank); } else { self.updateState(.oam_scan); self.lineNext(); } }, .v_blank => if (self.dots >= VBlankDots) { self.dots %= VBlankDots; if (self.line == RenderLine) { self.updateState(.oam_scan); self.finishFrame(); } else { self.lineNext(); } }, .oam_scan => if (self.dots >= OAMScanDots) { self.dots %= OAMScanDots; self.updateState(.pixel_transfer); }, .pixel_transfer => if (self.dots >= PixelTransferDots) { self.dots %= PixelTransferDots; self.drawPixelLine(); self.updateState(.h_blank); }, } return !self.ready; } pub fn blit(self: *Self, screen: []u8) void { std.debug.assert(screen.len == FramebufferSize); std.mem.copy(u8, screen, self.framebuffer); self.ready = false; }
https://raw.githubusercontent.com/mihnea-s/zig_gb_emu/9739db51e7dbbb2636b4f3f87b5ea54bd2510fce/src/graphics.zig
const std = @import("std"); const Types = enum(u8) { i32 = 0x7F, }; const DecodeError = error{ InvalidMagicNumber, UnsupportedVersionNumber, UnknownSectionID, DuplicateSection, UnorderedSections, InaccurateSectionSize, MissingTypeSectionSeparator, }; const SectionID = enum { custom, type, import, function, table, memory, global, _export, start, element, code, data, data_count, }; pub fn decode_preamble(reader: anytype) !void { const magic = [_]u8{ 0x00, 0x61, 0x73, 0x6D }; if (!try reader.isBytes(&magic)) { return DecodeError.InvalidMagicNumber; } const version = [_]u8{ 0x01, 0x00, 0x00, 0x00 }; if (!try reader.isBytes(&version)) { return DecodeError.UnsupportedVersionNumber; } } pub fn decode_type(reader: anytype) !void { const size = try std.leb.readULEB128(u32, reader); var counting_reader = std.io.countingReader(reader); const buffer = counting_reader.reader(); var num_types = try std.leb.readULEB128(u32, buffer); while (num_types > 0) { if (!try buffer.isBytes(&[_]u8{0x60})) return DecodeError.MissingTypeSectionSeparator; var num_inputs = try std.leb.readULEB128(u32, buffer); while (num_inputs > 0) { const t = switch (try buffer.readByte()) { 0x7F => Types.i32, else => unreachable, }; std.debug.print("input: {any}\n", .{t}); num_inputs -= 1; } var num_outputs = try std.leb.readULEB128(u32, buffer); while (num_outputs > 0) { const t = switch (try buffer.readByte()) { else => unreachable, }; std.debug.print("output: {any}", .{t}); num_outputs -= 1; } num_types -= 1; } if (counting_reader.bytes_read != size) return DecodeError.InaccurateSectionSize; } pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); const file = try std.fs.cwd().openFile(args[1], .{}); defer file.close(); const reader = file.reader(); try decode_preamble(reader); var highest_section_id: u8 = 0; while (true) { const section_id = try reader.readByte(); if (section_id != 0 and section_id == highest_section_id) { return DecodeError.DuplicateSection; } if (section_id != 0 and section_id < highest_section_id) { return DecodeError.UnorderedSections; } switch (section_id) { 0x01 => try decode_type(reader), else => return DecodeError.UnknownSectionID, } } }
https://raw.githubusercontent.com/nafarlee/wasm-interpreter/0a1751883294055016dc981ac29fff67926960b9/src/main.zig
const std = @import("std"); const compile = @import("compiler.zig").compile; const Program = @import("compiler.zig").Program; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer _ = gpa.deinit(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len < 2) { std.debug.print("Usage: {s} <filename>\n", .{args[0]}); std.debug.print(" expected a filename\n", .{}); return; } const filePath = args[1]; const program = try compile(allocator, filePath); defer program.deinit(); for (1.., program.items) |i, b| { if (i != 0 and i % 4 == 0) { std.debug.print("{x:0>2}\n", .{b}); continue; } std.debug.print("{x:0>2} ", .{b}); } // Writing to file const binaryFileName = createBinaryFileName(filePath); const binaryFile = try std.fs.cwd().createFile(binaryFileName, .{}); defer binaryFile.close(); _ = try binaryFile.write(program.items); } fn createBinaryFileName(filePath: []const u8) []const u8 { const delimiter = "."; var parts = std.mem.split(u8, filePath, delimiter); return parts.next() orelse return ""; }
https://raw.githubusercontent.com/cowboy8625/ender/1e0773d4f7c85495467731a50eba86257af552e2/libs/assembler/src/main.zig
const expect = @import("std").testing.expect; test "defer" { var x: i16 = 5; { defer x += 2; try expect(x == 5); } try expect(x == 7); } test "multi defer" { var x: f32 = 5; { defer x += 2; defer x /= 2; } try expect(x == 4.5); }
https://raw.githubusercontent.com/UltiRequiem/ziglearn/31a38d294dc7e1bdf59ec348c3b9b94e44b224f5/defer.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const exe = b.addExecutable(.{ .name = "avrboot", .root_source_file = .{ .path = "src/main.zig", }, .target = target, .optimize = optimize, }); b.installArtifact(exe); const main_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig", }, .optimize = optimize, }); const test_step = b.step("test", "Run library tests"); test_step.dependOn(&main_tests.step); 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("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
https://raw.githubusercontent.com/ZigEmbeddedGroup/avrboot/c41f8183c7f68552f7ceb1dc2e1670ac10e94b0c/build.zig
const vk = @import("vulkan"); pub const Vertex = struct { pub const binding_description = vk.VertexInputBindingDescription{ .binding = 0, .stride = @sizeOf(Vertex), .input_rate = .vertex, }; pub const attribute_description = [_]vk.VertexInputAttributeDescription{ .{ .binding = 0, .location = 0, .format = .r32g32_sfloat, .offset = @offsetOf(Vertex, "pos"), }, .{ .binding = 0, .location = 1, .format = .r32g32b32_sfloat, .offset = @offsetOf(Vertex, "color"), }, }; pos: [2]f32, color: [3]f32, };
https://raw.githubusercontent.com/MullerLucas/hellengine_zig/88e85801fb1002b683029c480c0c46af5ef3ba6d/src/math.zig
const std = @import("std"); const print = std.debug.print; const Distances = std.StringHashMap(std.StringHashMap(usize)); pub fn main() anyerror!void { const global_allocator = std.heap.page_allocator; var file = try std.fs.cwd().openFile( "./inputs/day09.txt", .{ .read = true, }, ); var reader = std.io.bufferedReader(file.reader()).reader(); var line = std.ArrayList(u8).init(global_allocator); defer line.deinit(); var distances = Distances.init(global_allocator); defer distances.deinit(); var arena = std.heap.ArenaAllocator.init(global_allocator); defer arena.deinit(); var allocator = &arena.allocator; while (reader.readUntilDelimiterArrayList(&line, '\n', 100)) { var tokens = std.mem.tokenize(u8, line.items, " "); const from = try std.mem.Allocator.dupe(allocator, u8, tokens.next().?); _ = tokens.next(); const to = try std.mem.Allocator.dupe(allocator, u8, tokens.next().?); _ = tokens.next(); const distance = try std.fmt.parseInt(usize, tokens.next().?, 10); if (distances.getPtr(from)) |m| { try m.put(to, distance); } else { var m = std.StringHashMap(usize).init(allocator); try m.put(to, distance); try distances.put(from, m); } if (distances.getPtr(to)) |m| { try m.put(from, distance); } else { var m = std.StringHashMap(usize).init(allocator); try m.put(from, distance); try distances.put(to, m); } } else |err| { if (err != error.EndOfStream) { return err; } } var so_far = std.StringArrayHashMap(void).init(global_allocator); defer so_far.deinit(); const shortest = try shortest_path(false, distances, so_far, 0); print("Part 1: {d}\n", .{shortest}); so_far.clearRetainingCapacity(); const longest = try shortest_path(true, distances, so_far, 0); print("Part 2: {d}\n", .{longest}); } fn shortest_path(longest: bool, distances: Distances, so_far_const: std.StringArrayHashMap(void), distance_so_far: usize) anyerror!usize { var so_far = try so_far_const.clone(); defer so_far.deinit(); var keys = distances.keyIterator(); var best_route: ?usize = null; var current_distances: ?*std.StringHashMap(usize) = null; if (so_far.popOrNull()) |current| { try so_far.put(current.key, .{}); current_distances = distances.getPtr(current.key).?; } while (keys.next()) |k| { if (!so_far.contains(k.*)) { try so_far.put(k.*, .{}); defer _ = so_far.pop(); var d_so_far = distance_so_far; if (current_distances) |d| { d_so_far += d.get(k.*).?; } const distance = try shortest_path(longest, distances, so_far, d_so_far); if (best_route) |r| { if (longest and distance > r) { best_route = distance; } else if (!longest and distance < r) { best_route = distance; } } else { best_route = distance; } } } if (best_route) |s| { return s; } else { return distance_so_far; } }
https://raw.githubusercontent.com/basile-henry/aoc2015/76a8c255f0e7ea2f5b72f2f56f987a509030aacc/src/day09.zig
const std = @import("std"); const testing = std.testing; const fmt = std.fmt; pub fn hexToBytes(comptime expected_hex: []const u8) []const u8 { var expected_bytes: [expected_hex.len / 2]u8 = undefined; for (&expected_bytes, 0..) |*r, i| { r.* = fmt.parseInt(u8, expected_hex[2 * i .. 2 * i + 2], 16) catch unreachable; } return &expected_bytes; } // Hash using the specified hasher `H` asserting `expected == H(input)`. pub fn assertEqualHash(comptime Hasher: anytype, comptime expected_hex: *const [Hasher.digest_length * 2:0]u8, input: []const u8) !void { var h: [Hasher.digest_length]u8 = undefined; Hasher.hash(input, &h, .{}); try assertEqual(expected_hex, &h); } // Assert `expected` == hex(`input`) where `input` is a bytestring pub fn assertEqual(comptime expected_hex: []const u8, input: []const u8) !void { const expected_bytes = hexToBytes(expected_hex); try testing.expectEqualSlices(u8, expected_bytes, input); } pub fn equalSlices(expected_hex: []const u8, input: []const u8) bool { if (expected_hex.ptr == input.ptr and expected_hex.len == input.len) { return true; } const shortest = @min(expected_hex.len, input.len); var index: usize = 0; while (index < shortest) : (index += 1) { if (!std.meta.eql(input[index], expected_hex[index])) return false; } return true; }
https://raw.githubusercontent.com/zmovane/zjwt/74b615fbbcfc0f2cedb667c4ea6e4fbc1f6fe360/src/utils.zig
const WorldRenderer = @This(); const Camera = @import("Camera.zig"); const tilemap = @import("tilemap.zig"); const Tilemap = tilemap.Tilemap; const TileCoord = tilemap.TileCoord; const TileLayer = tilemap.TileLayer; const TileBank = tilemap.TileBank; const TileRange = tilemap.TileRange; const RenderServices = @import("render.zig").RenderServices; const Rect = @import("Rect.zig"); const zm = @import("zmath"); const std = @import("std"); const Game = @import("Game.zig"); const WaterRenderer = @import("WaterRenderer.zig"); const anim = @import("animation.zig"); const max_onscreen_tiles = 33 * 17; renderers: *RenderServices, r_water: WaterRenderer, water_buf: []WaterDraw, n_water: usize = 0, foam_buf: []FoamDraw, foam_anim_l: anim.Animator, foam_anim_r: anim.Animator, foam_anim_u: anim.Animator, foam_anim_d: anim.Animator, heart_anim: anim.Animator = anim.a_goal_heart.animationSet().createAnimator("default"), const WaterDraw = struct { dest: Rect, world_xy: zm.Vec, }; const FoamDraw = struct { dest: Rect, left: bool, right: bool, top: bool, bottom: bool, }; pub fn create(allocator: std.mem.Allocator, renderers: *RenderServices) !*WorldRenderer { var self = try allocator.create(WorldRenderer); errdefer allocator.destroy(self); self.* = .{ .renderers = renderers, // Initialized below .r_water = undefined, .water_buf = undefined, .foam_buf = undefined, .foam_anim_l = undefined, .foam_anim_r = undefined, .foam_anim_u = undefined, .foam_anim_d = undefined, }; self.water_buf = try allocator.alloc(WaterDraw, max_onscreen_tiles); errdefer allocator.free(self.water_buf); self.foam_buf = try allocator.alloc(FoamDraw, max_onscreen_tiles); errdefer allocator.free(self.foam_buf); self.r_water = WaterRenderer.create(); errdefer self.r_water.destroy(); self.foam_anim_l = anim.a_foam.animationSet().createAnimator("l"); self.foam_anim_r = anim.a_foam.animationSet().createAnimator("r"); self.foam_anim_u = anim.a_foam.animationSet().createAnimator("u"); self.foam_anim_d = anim.a_foam.animationSet().createAnimator("d"); return self; } pub fn destroy(self: *WorldRenderer, allocator: std.mem.Allocator) void { self.r_water.destroy(); allocator.free(self.water_buf); allocator.free(self.foam_buf); allocator.destroy(self); } pub fn updateAnimations(self: *WorldRenderer) void { self.foam_anim_l.update(); self.foam_anim_r.update(); self.foam_anim_u.update(); self.foam_anim_d.update(); self.heart_anim.update(); } fn renderTilemapLayer( self: *WorldRenderer, map: *const Tilemap, layer: TileLayer, bank: TileBank, range: TileRange, translate_x: i32, translate_y: i32, ) void { const source_texture = switch (bank) { .none => return, .terrain => self.renderers.texman.getNamedTexture("terrain.png"), .special => self.renderers.texman.getNamedTexture("special.png"), }; const n_tiles_wide = @as(u16, @intCast(source_texture.width / 16)); self.renderers.r_batch.begin(.{ .texture = source_texture, }); for (range.min.y..range.max.y) |y| { for (range.min.x..range.max.x) |x| { const t = map.at2DPtr(layer, x, y); // filter tiles to selected bank if (t.bank != bank) { continue; } if (t.isWater()) { const dest = Rect{ .x = @as(i32, @intCast(x * 16)) + translate_x, .y = @as(i32, @intCast(y * 16)) + translate_y, .w = 16, .h = 16, }; self.water_buf[self.n_water] = WaterDraw{ .dest = dest, .world_xy = zm.f32x4( @floatFromInt(x * 16), @floatFromInt(y * 16), 0, 0, ), }; self.foam_buf[self.n_water] = FoamDraw{ .dest = dest, .left = x > 0 and map.isValidIndex(x - 1, y) and !map.at2DPtr(layer, x - 1, y).isWater(), .right = map.isValidIndex(x + 1, y) and !map.at2DPtr(layer, x + 1, y).isWater(), .top = y > 0 and map.isValidIndex(x, y - 1) and !map.at2DPtr(layer, x, y - 1).isWater(), .bottom = map.isValidIndex(x, y + 1) and !map.at2DPtr(layer, x, y + 1).isWater(), }; // self.foam_buf[self.n_water].dest.inflate(1, 1); self.n_water += 1; } else { const src = Rect{ .x = (t.id % n_tiles_wide) * 16, .y = (t.id / n_tiles_wide) * 16, .w = 16, .h = 16, }; const dest = Rect{ .x = @as(i32, @intCast(x * 16)) + translate_x, .y = @as(i32, @intCast(y * 16)) + translate_y, .w = 16, .h = 16, }; self.renderers.r_batch.drawQuad(.{ .src = src.toRectf(), .dest = dest.toRectf(), }); } } } self.renderers.r_batch.end(); } pub fn renderTilemap(self: *WorldRenderer, cam: Camera, map: *const Tilemap, frame_count: u64) void { self.n_water = 0; const min_tile_x = @as(usize, @intCast(cam.view.left())) / 16; const min_tile_y = @as(usize, @intCast(cam.view.top())) / 16; const max_tile_x = @min( map.width, // +1 to account for partially transparent UI panel 1 + 1 + @as(usize, @intCast(cam.view.right())) / 16, ); const max_tile_y = @min( map.height, 1 + @as(usize, @intCast(cam.view.bottom())) / 16, ); const range = TileRange{ .min = TileCoord{ .x = @intCast(min_tile_x), .y = @intCast(min_tile_y) }, .max = TileCoord{ .x = @intCast(max_tile_x), .y = @intCast(max_tile_y) }, }; self.renderers.r_batch.setOutputDimensions(Game.INTERNAL_WIDTH, Game.INTERNAL_HEIGHT); self.renderTilemapLayer(map, .base, .terrain, range, -cam.view.left(), -cam.view.top()); self.renderTilemapLayer(map, .base, .special, range, -cam.view.left(), -cam.view.top()); // water_direction, water_drift, speed set on a per-map basis? const water_params = WaterRenderer.WaterRendererParams{ .water_base = self.renderers.texman.getNamedTexture("water.png"), .water_blend = self.renderers.texman.getNamedTexture("water.png"), .blend_amount = 0.3, .global_time = @as(f32, @floatFromInt(frame_count)) / 30.0, .water_direction = zm.f32x4(0.3, 0.2, 0, 0), .water_drift_range = zm.f32x4(0.2, 0.05, 0, 0), .water_drift_scale = zm.f32x4(32, 16, 0, 0), .water_speed = 1, }; self.r_water.setOutputDimensions(Game.INTERNAL_WIDTH, Game.INTERNAL_HEIGHT); self.r_water.begin(water_params); for (self.water_buf[0..self.n_water]) |cmd| { self.r_water.drawQuad(cmd.dest, cmd.world_xy); } self.r_water.end(); // render foam self.renderFoam(); // detail layer rendered on top of water self.renderTilemapLayer(map, .detail, .terrain, range, -cam.view.left(), -cam.view.top()); self.renderTilemapLayer(map, .detail, .special, range, -cam.view.left(), -cam.view.top()); } fn renderFoam( self: *WorldRenderer, ) void { const t_foam = self.renderers.texman.getNamedTexture("water_foam.png"); const l_rectf = self.foam_anim_l.getCurrentRect().toRectf(); const r_rectf = self.foam_anim_r.getCurrentRect().toRectf(); const u_rectf = self.foam_anim_u.getCurrentRect().toRectf(); const d_rectf = self.foam_anim_d.getCurrentRect().toRectf(); self.renderers.r_batch.begin(.{ .texture = t_foam, }); for (self.foam_buf[0..self.n_water]) |f| { const destf = f.dest.toRectf(); if (f.left) { self.renderers.r_batch.drawQuad(.{ .src = l_rectf, .dest = destf }); } if (f.top) { self.renderers.r_batch.drawQuad(.{ .src = u_rectf, .dest = destf }); } if (f.bottom) { self.renderers.r_batch.drawQuad(.{ .src = d_rectf, .dest = destf }); } if (f.right) { self.renderers.r_batch.drawQuad(.{ .src = r_rectf, .dest = destf }); } } self.renderers.r_batch.end(); }
https://raw.githubusercontent.com/jcmoyer/defense_of_ufeff/9a3dbc3b1166efd593410372dce6f99149839369/src/WorldRenderer.zig
const std = @import("std"); const testing = std.testing; const command = @import("./util/command.zig"); const Map = @import("./island.zig").Map; pub fn main() anyerror!u8 { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const part = command.choosePart(); var map = Map.init(allocator); defer map.deinit(); const inp = std.io.getStdIn().reader(); var buf: [1024]u8 = undefined; while (try inp.readUntilDelimiterOrEof(&buf, '\n')) |line| { try map.addLine(line); } // map.show(); var answer: usize = 0; switch (part) { .part1 => { answer = try map.getLongestStepCount(); const expected = @as(usize, 6649); try testing.expectEqual(expected, answer); }, .part2 => { answer = try map.getEnclosedTiles(); const expected = @as(usize, 601); try testing.expectEqual(expected, answer); }, } const out = std.io.getStdOut().writer(); try out.print("=== {s} ===\n", .{@tagName(part)}); try out.print("Answer: {}\n", .{answer}); try out.print("Elapsed: {}ms\n", .{command.getElapsedMs()}); return 0; }
https://raw.githubusercontent.com/gonzus/AdventOfCode/7e972b92a23db29461b2869713a3251998af5822/2023/p10/p10.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 = "algo-intro", .root_source_file = .{ .src_path = .{ .owner = b, .sub_path = "src/main.zig" } }, .target = target, .optimize = optimize, }); 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("run", "Run the app"); run_step.dependOn(&run_cmd.step); }
https://raw.githubusercontent.com/MatthewKandiah/algo-intro/8895aa621a43ab71436491269488f3f0c9fc8f87/build.zig
//! Provides easy type-safe access and traversals of the nodes of a parse tree. const syntax = @This(); const std = @import("std"); const parse = @import("parse.zig"); const Tree = parse.Tree; const Tag = parse.Tag; pub const File = ListExtractor(.file, null, ExternalDeclaration, null); pub const AnyDeclaration = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); function: FunctionDeclaration, variable: Declaration, block: BlockDeclaration, parameter: Parameter, struct_specifier: StructSpecifier, }; pub const ExternalDeclaration = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); function: FunctionDeclaration, variable: Declaration, block: BlockDeclaration, }; pub const FunctionDeclaration = Extractor(.function_declaration, struct { qualifiers: QualifierList, specifier: TypeSpecifier, identifier: Token(.identifier), parameters: ParameterList, block: Block, semi: Token(.@";"), }); pub const ParameterList = ListExtractor(.parameter_list, Token(.@"("), Parameter, Token(.@")")); pub const Parameter = Extractor(.parameter, struct { qualifiers: QualifierList, specifier: TypeSpecifier, variable: VariableDeclaration, comma: Token(.@","), }); pub const BlockDeclaration = Extractor(.block_declaration, struct { qualifiers: QualifierList, specifier: TypeSpecifier, fields: FieldList, variable: VariableDeclaration, semi: Token(.@";"), }); pub const Declaration = Extractor(.declaration, struct { qualifiers: QualifierList, specifier: TypeSpecifier, variables: Variables, semi: Token(.@";"), }); pub const Variables = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); one: VariableDeclaration, many: VariableDeclarationList, pub const Iterator = union(enum) { one: ?VariableDeclaration, many: VariableDeclarationList.Iterator, pub fn next(self: *@This(), tree: Tree) ?VariableDeclaration { switch (self.*) { .one => |*one| { const value = one.*; one.* = null; return value; }, .many => |*many| { return many.next(tree); }, } } }; pub fn iterator(self: @This()) Iterator { return switch (self) { .one => |one| .{ .one = one }, .many => |many| .{ .many = many.iterator() }, }; } }; pub const VariableDeclarationList = ListExtractor(.variable_declaration_list, null, VariableDeclaration, null); pub const VariableDeclaration = Extractor(.variable_declaration, struct { name: VariableName, eq_token: Token(.@"="), initializer: Initializer, comma: Token(.@","), }); pub const VariableName = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); identifier: Token(.identifier), array: ArraySpecifierName, pub fn getIdentifier(self: @This(), tree: Tree) ?Token(.identifier) { return switch (self) { .identifier => |token| token, .array => |array| array.prefix(tree), }; } pub fn arrayIterator(self: @This()) ?ListIterator(Array) { return switch (self) { .identifier => null, .array => |array| array.iterator(), }; } }; pub const Initializer = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); list: InitializerList, expr: Expression, }; pub const InitializerList = ListExtractor(.initializer_list, Token(.@"{"), Initializer, Token(.@"}")); pub const QualifierList = ListExtractor(.type_qualifier_list, null, Qualifier, null); pub const Qualifier = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); }; pub const TypeSpecifier = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); identifier: Token(.identifier), array_specifier: ArraySpecifierName, struct_specifier: StructSpecifier, pub fn underlyingName(self: @This(), tree: Tree) ?Token(.identifier) { switch (self) { .identifier => |ident| return ident, .array_specifier => |array| return array.prefix(tree), else => return null, } } }; pub const StructSpecifier = Extractor(.struct_specifier, struct { keyword_struct: Token(.keyword_struct), name: Token(.identifier), /// Struct fields may contain structs themselves, so we need lazy indirection here. fields: Lazy("FieldList"), }); pub const FieldList = ListExtractor(.field_declaration_list, Token(.@"{"), Declaration, Token(.@"}")); pub const ArraySpecifierName = ArraySpecifier(Token(.identifier)); pub fn ArraySpecifier(comptime Inner: type) type { return ListExtractor(.array_specifier, Inner, Array, null); } pub const Array = Extractor(.array, struct { open: Token(.@"["), value: Expression, close: Token(.@"]"), }); pub const Block = ListExtractor(.block, Token(.@"{"), Statement, Token(.@"}")); pub const Statement = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); declaration: Declaration, }; pub const ConditionList = ListExtractor(.condition_list, Token(.@"("), Statement, Token(.@")")); pub const Expression = Lazy("ExpressionUnion"); pub const ExpressionUnion = union(enum) { pub usingnamespace UnionExtractorMixin(@This()); identifier: Token(.identifier), number: Token(.number), array: ArraySpecifier(Expression), selection: Selection, }; pub const Selection = Extractor(.selection, struct { target: Expression, @".": Token(.@"."), field: Token(.identifier), }); pub fn Token(comptime tag: Tag) type { comptime std.debug.assert(tag.isToken()); return struct { pub usingnamespace ExtractorMixin(@This()); node: u32, pub fn match(tree: Tree, node: u32) ?void { return if (tree.tag(node) == tag) {} else null; } pub fn extract(_: Tree, node: u32, _: void) @This() { return .{ .node = node }; } pub fn text(self: @This(), source: []const u8, tree: Tree) []const u8 { const span = tree.token(self.node); return source[span.start..span.end]; } }; } pub fn Extractor(comptime expected_tag: Tag, comptime T: type) type { const fields = std.meta.fields(T); const FieldEnum = std.meta.FieldEnum(T); return struct { pub usingnamespace ExtractorMixin(@This()); fn Match(comptime FieldType: type) type { return struct { node_offset: ?u7 = null, result: MatchResult(FieldType) = undefined, }; } const MatchFields = @Type(.{ .Struct = .{ .layout = .auto, .fields = blk: { var match_fields: [fields.len]std.builtin.Type.StructField = undefined; for (&match_fields, fields) |*match_field, field| { match_field.* = field; match_field.type = Match(field.type); match_field.default_value = &@as(match_field.type, .{}); } break :blk &match_fields; }, .decls = &.{}, .is_tuple = false, }, }); node: u32, matches: MatchFields, pub fn match(tree: Tree, node: u32) ?void { return if (tree.tag(node) == expected_tag) {} else null; } pub fn extract(tree: Tree, node: u32, _: void) @This() { var matches = MatchFields{}; const children = tree.children(node); var current = children.start; inline for (fields) |field| { while (current < children.end) : (current += 1) { const tag = tree.tag(current); if (field.type.match(tree, current)) |result| { @field(matches, field.name) = .{ .node_offset = @intCast(current - children.start), .result = result, }; current += 1; break; } else { if (tag == .invalid or tag == .unknown) continue; break; } } } return .{ .node = node, .matches = matches }; } pub fn nodeOf(self: @This(), comptime field: FieldEnum, tree: Tree) ?u32 { const field_match = @field(self.matches, @tagName(field)); const node_offset = field_match.node_offset orelse return null; return tree.children(self.node).start + node_offset; } pub fn get(self: @This(), comptime field: FieldEnum, tree: Tree) ?std.meta.FieldType(T, field) { const field_match = @field(self.matches, @tagName(field)); const node_offset = field_match.node_offset orelse return null; const node = tree.children(self.node).start + node_offset; return std.meta.FieldType(T, field).extract(tree, node, field_match.result); } }; } pub fn ListExtractor(comptime tag: Tag, comptime Prefix: ?type, comptime Item: type, comptime Suffix: ?type) type { const PrefixMatch = if (Prefix) |P| MatchResult(P) else noreturn; const SuffixMatch = if (Suffix) |S| MatchResult(S) else noreturn; return struct { pub usingnamespace ExtractorMixin(@This()); const Self = @This(); node: u32, prefix_match: ?PrefixMatch, suffix_match: ?SuffixMatch, items: parse.Range, pub fn match(tree: Tree, node: u32) ?void { return if (tag == tree.tag(node)) {} else null; } pub fn extract(tree: Tree, node: u32, _: void) @This() { const children = tree.children(node); const empty = children.start == children.end; const prefix_match: ?PrefixMatch = blk: { if (empty) break :blk null; if (Prefix) |P| break :blk P.match(tree, children.start); break :blk null; }; const suffix_match: ?SuffixMatch = blk: { if (empty) break :blk null; if (Suffix) |S| break :blk S.match(tree, children.end - 1); break :blk null; }; return .{ .node = node, .prefix_match = prefix_match, .suffix_match = suffix_match, .items = .{ .start = children.start + @intFromBool(prefix_match != null), .end = children.end - @intFromBool(suffix_match != null), }, }; } pub usingnamespace if (Prefix) |PrefixType| struct { pub fn prefix(self: Self, tree: Tree) ?PrefixType { return PrefixType.extract(tree, self.items.start - 1, self.prefix_match orelse return null); } } else struct {}; pub usingnamespace if (Suffix) |SuffixType| struct { pub fn suffix(self: Self, tree: Tree) ?SuffixType { return SuffixType.extract(tree, self.items.end, self.suffix_match orelse return null); } } else struct {}; pub const Iterator = ListIterator(Item); pub fn iterator(self: Self) Iterator { return .{ .items = self.items, }; } }; } pub fn ListIterator(comptime Item: type) type { return struct { items: parse.Range, pub fn next(self: *@This(), tree: Tree) ?Item { while (self.items.start < self.items.end) { defer self.items.start += 1; if (Item.match(tree, self.items.start)) |res| { return Item.extract(tree, self.items.start, res); } } return null; } }; } pub fn UnionExtractorMixin(comptime Self: type) type { const fields = std.meta.fields(Self); return struct { pub usingnamespace ExtractorMixin(Self); const MatchUnion = @Type(.{ .Union = .{ .layout = .auto, .fields = blk: { var match_fields: [fields.len]std.builtin.Type.UnionField = undefined; for (&match_fields, fields) |*match_field, field| { match_field.* = .{ .name = field.name, .type = MatchResult(field.type), .alignment = 0, }; } break :blk &match_fields; }, .tag_type = std.meta.Tag(Self), .decls = &.{}, }, }); pub fn match(tree: Tree, node: u32) ?MatchUnion { inline for (fields) |field| { if (field.type.match(tree, node)) |value| { return @unionInit(MatchUnion, field.name, value); } } return null; } pub fn extract(tree: Tree, node: u32, result: MatchUnion) Self { if (fields.len == 0) return undefined; switch (std.meta.activeTag(result)) { inline else => |res| { const name = @tagName(res); const Inner = @TypeOf(@field(@as(Self, undefined), name)); return @unionInit(Self, name, Inner.extract(tree, node, @field(result, name))); }, } } pub fn getNode(self: Self) u32 { if (fields.len == 0) return undefined; switch (self) { inline else => |value| { if (@hasField(@TypeOf(value), "node")) return value.node; return value.node(); }, } } }; } /// Break type-level dependency cycles through lazy-evaluation indirection. pub fn Lazy(comptime type_name: []const u8) type { return struct { pub usingnamespace ExtractorMixin(@This()); node: u32, match_result_bytes: [4]u8, const Type = @field(syntax, type_name); const Match = MatchResult(Type); const MatchInt = std.meta.Int(.unsigned, 8 * @sizeOf(Match)); fn encodeMatchResult(res: Match) [4]u8 { switch (@sizeOf(Match)) { 0...4 => return std.mem.toBytes(res) ++ [_]u8{0} ** (4 - @sizeOf(Match)), else => return .{ 0, 0, 0, 0 }, } } fn decodeMatchResult(self: @This(), tree: Tree) Match { switch (@sizeOf(Match)) { 0...4 => return std.mem.bytesToValue(Match, self.match_result_bytes[0..@sizeOf(Match)]), else => return Type.match(tree, self.node).?, } } pub fn match(tree: Tree, node: u32) ?[4]u8 { return encodeMatchResult(Type.match(tree, node) orelse return null); } pub fn extract(_: Tree, node: u32, match_result_bytes: [4]u8) @This() { return .{ .node = node, .match_result_bytes = match_result_bytes, }; } pub fn get(self: @This(), tree: Tree) Type { const match_result = self.decodeMatchResult(tree); return Type.extract(tree, self.node, match_result); } }; } pub fn MatchResult(comptime T: type) type { const match_fn_return = @typeInfo(@TypeOf(T.match)).Fn.return_type.?; return @typeInfo(match_fn_return).Optional.child; } pub fn ExtractorMixin(comptime Self: type) type { return struct { pub fn tryExtract(tree: Tree, node: u32) ?Self { const match_result = Self.match(tree, node) orelse return null; return Self.extract(tree, node, match_result); } }; } test { std.testing.refAllDeclsRecursive(@This()); }
https://raw.githubusercontent.com/nolanderc/glsl_analyzer/3514b232795858c6a1870832d2ff033eb54103ab/src/syntax.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const core = @import("./core.zig"); const Vec2i = @import("util").Vec2i; pub const Frames = union(enum) { WaitingForSize: void, WaitingForData: struct { buffer: []u8, bytes_recevied: usize, }, pub fn init() @This() { return @This(){ .WaitingForSize = {} }; } pub fn update(this: *@This(), alloc: *Allocator, reader: anytype) !?[]u8 { while (true) { switch (this.*) { .WaitingForSize => { const n = reader.readIntLittle(u32) catch |e| switch (e) { error.WouldBlock => return null, else => |other_err| return other_err, }; this.* = .{ .WaitingForData = .{ .buffer = try alloc.alloc(u8, n), .bytes_recevied = 0, }, }; }, .WaitingForData => |*data| { data.bytes_recevied += reader.read(data.buffer[data.bytes_recevied..]) catch |e| switch (e) { error.WouldBlock => return null, else => |other_err| return other_err, }; if (data.bytes_recevied == data.buffer.len) { const message = data.buffer; this.* = .{ .WaitingForSize = {} }; return message; } }, } } } }; pub const ServerPacket = union(enum) { Init: struct { // The color the client will be color: core.piece.Piece.Color, }, ErrorMessage: ServerError, BoardUpdate: core.Board.Serialized, TurnChange: core.piece.Piece.Color, CapturedPiecesUpdate: struct { white: []core.piece.Piece, black: []core.piece.Piece, }, pub fn stringify(this: @This(), writer: anytype) !void { try writer.writeAll(std.meta.tagName(this)); try writer.writeAll(":"); const Tag = @TagType(@This()); inline for (std.meta.fields(Tag)) |field| { if (this == @field(Tag, field.name)) { try std.json.stringify(@field(this, field.name), .{}, writer); return; } } } pub fn parse(allocator: *Allocator, data: []const u8) !@This() { var split_iter = std.mem.split(data, ":"); const tag = split_iter.next().?; const packet_data = split_iter.rest(); inline for (std.meta.fields(@This())) |field| { if (std.mem.eql(u8, field.name, tag)) { const parsed = try std.json.parse(field.field_type, &std.json.TokenStream.init(packet_data), .{ .allocator = allocator, }); return @unionInit(@This(), field.name, parsed); } } return error.InvalidFormat; } pub fn parseFree(this: @This(), allocator: *Allocator) void { const Tag = @TagType(@This()); inline for (std.meta.fields(@This())) |field| { if (this == @field(Tag, field.name)) { std.json.parseFree(field.field_type, @field(this, field.name), .{ .allocator = allocator }); return; } } } }; pub const ServerError = enum(u8) { IllegalMove = 1, pub fn jsonStringify(this: @This(), options: std.json.StringifyOptions, writer: anytype) !void { const text = switch (this) { .IllegalMove => "IllegalMove", }; try std.json.stringify(text, options, writer); } }; // Packets from the client pub const ClientPacket = union(enum) { MovePiece: struct { startPos: Vec2i, endPos: Vec2i, }, pub fn stringify(this: @This(), writer: anytype) !void { try writer.writeAll(std.meta.tagName(this)); try writer.writeAll(":"); const Tag = @TagType(@This()); inline for (std.meta.fields(Tag)) |field| { if (this == @field(Tag, field.name)) { try std.json.stringify(@field(this, field.name), .{}, writer); return; } } } pub fn parse(data: []const u8) !@This() { var split_iter = std.mem.split(data, ":"); const tag = split_iter.next().?; const packet_data = split_iter.rest(); inline for (std.meta.fields(@This())) |field| { if (std.mem.eql(u8, field.name, tag)) { const parsed = try std.json.parse(field.field_type, &std.json.TokenStream.init(packet_data), .{}); return @unionInit(@This(), field.name, parsed); } } return error.InvalidFormat; } }; test "convert serverpacket to json" { var json = std.ArrayList(u8).init(std.testing.allocator); defer json.deinit(); try (ServerPacket{ .Init = .{ .color = .Black } }).stringify(json.writer()); std.testing.expectEqualSlices(u8, \\Init:{"color":"Black"} , json.items); } fn test_packet_JSON_roundtrip(data: anytype) !void { var json = std.ArrayList(u8).init(std.testing.allocator); defer json.deinit(); try data.stringify(json.writer()); const parsed = try @TypeOf(data).parse(json.items); std.testing.expectEqual(data, parsed); } test "serverpacket json stringify than parse" { try test_packet_JSON_roundtrip(ServerPacket{ .Init = .{ .color = .Black } }); try test_packet_JSON_roundtrip(ServerPacket{ .ErrorMessage = .IllegalMove }); try test_packet_JSON_roundtrip(ServerPacket{ .BoardUpdate = core.Board.init(null).serialize() }); try test_packet_JSON_roundtrip(ServerPacket{ .BoardUpdate = core.Board.init(null).serialize() }); } test "clientpacket json stringify than parse" { const vec2i = @import("util").vec2i; try test_packet_JSON_roundtrip(ClientPacket{ .MovePiece = .{ .startPos = vec2i(5, 6), .endPos = vec2i(5, 5) } }); }
https://raw.githubusercontent.com/leroycep/hexagonal-chess/ebc60fe485830eccebab5641b0d0523231f40bc5/core/protocol.zig
const std = @import("std"); const nexus = @import("nexus"); // Required for pulling symbols. pub const os = nexus.os; comptime { _ = @import("nexus").os; } const gfx = nexus.gfx.Graphics; const gfx_mode = nexus.gfx.GraphicsModes; const stdout = std.io.getStdOut().writer(); // Simple 32 bit vector const Vec2 = packed struct { x: u16, y: u16, }; pub fn main() !void { try gfx.init(gfx_mode.VGA_320x200x8bpp); // Setup the player var player_position = Vec2{ .x = 0, .y = 0 }; var player_size = Vec2{ .x = 16, .y = 16 }; // Game loop while (true) { // Move the player to the right player_position.x += 1; player_position.x %= 320; player_position.y += 1; player_position.y %= 200; // // Clear the screen to cyan gfx.clear(0xAC); // Draw the player as a red rectangle for (0..player_size.y) |y| { for (0..player_size.x) |x| { // If the position is out of bounds, skip it if (((player_position.x + x) >= 320) or ((player_position.y + y) >= 200)) { continue; } try gfx.drawPixel( @as(u16, @intCast(player_position.x + x)), @as(u16, @intCast(player_position.y + y)), 0x04, ); } } gfx.present(); } }
https://raw.githubusercontent.com/Rexicon226/neon-nexus/449bbf00446b864b4d983b85c16748ae528eabb4/programs/game.zig
const std = @import("std"); const io = @import("io"); pub fn main(args: *std.process.ArgIterator, _: std.mem.Allocator) !u8 { try io.stdOutPrint("{s}\n", .{process(args.next().?, args.next())}); return 0; } fn process(string: []const u8, suffix: ?[]const u8) []const u8 { if (string.len == 0) { return "."; } const all_slashes = blk: { for (string) |char| { if (char != '/') break :blk false; } break :blk true; }; if (all_slashes) { return "/"; } const basename = std.fs.path.basename(string); if (suffix) |suf| { if (basename.len > suf.len and std.mem.eql(u8, basename[basename.len - suf.len ..], suf)) { return basename[0 .. basename.len - suf.len]; } else { return basename; } } else { return basename; } } test "null string" { try std.testing.expectEqualSlices(u8, ".", process("", null)); } test "only slashes" { try std.testing.expectEqualSlices( u8, "/", process("////////////////////////////", null), ); } test { // absolute path try std.testing.expectEqualSlices( u8, "foo", process("/bar/baz/foo", null), ); // relative path try std.testing.expectEqualSlices( u8, "foo", process("bar/baz/foo", null), ); // single entry, relative try std.testing.expectEqualSlices( u8, "foo", process("foo", null), ); // single entry, absolute try std.testing.expectEqualSlices( u8, "foo", process("/foo", null), ); // relative, with extension try std.testing.expectEqualSlices( u8, "main.zig", process("src/main.zig", null), ); } test "trailing slashes" { try std.testing.expectEqualSlices( u8, "foo", process("/bar/baz/foo/", null), ); } test "suffix removal" { try std.testing.expectEqualSlices( u8, "foo", process("foo.txt", ".txt"), ); try std.testing.expectEqualSlices( u8, "foo.txt", process("foo.txt", "foo"), ); try std.testing.expectEqualSlices( u8, "foo", process("/bar/foo.txt", ".txt"), ); try std.testing.expectEqualSlices( u8, "foo", process("bar/foo.txt", ".txt"), ); try std.testing.expectEqualSlices( u8, "foo", process("/bar/baz/foo", ""), ); }
https://raw.githubusercontent.com/amusingimpala75/zigix/2f90b5ac1772aaab7da5c8701828b99a1c2cae9c/src/basename/main.zig
const std = @import("std"); fn Unit(comptime T: type) type { const Hack = struct { var runtime: T = undefined; }; return @TypeOf(.{Hack.runtime}); } fn Actor(comptime T: type) type { const F = std.builtin.TypeInfo.StructField; comptime var fields: []const F = &[_]F{}; inline for (@typeInfo(T).Struct.decls) |decl| { switch (decl.data) { else => {}, .Fn => |fun| { const info = @typeInfo(fun.fn_type).Fn; if (!decl.is_pub or info.args.len != 3) continue; if (info.args[0].arg_type.? != *T) continue; if (info.args[1].arg_type.? != *Context(T)) continue; fields = fields ++ [_]F{ .{ .name = decl.name, .default_value = null, .field_type = struct { pending: usize, mail: std.TailQueue(info.args[2].arg_type.?), }, }, }; }, } } const Mailbox = @Type(.{ .Struct = .{ .fields = fields, .decls = &[_]std.builtin.TypeInfo.Declaration{}, .is_tuple = false, .layout = .Auto, }, }); return struct { mailbox: Mailbox, context: Context(T), const Self = @This(); pub fn init() Self { var r: Self = undefined; inline for (std.meta.fields(Mailbox)) |field, i| { @field(r.mailbox, field.name).pending = 0; @field(r.mailbox, field.name).mail = .{}; } r.context = .{}; return r; } }; } fn Context(comptime T: type) type { return struct { const Ctx = @This(); pub fn send(ctx: Ctx, comptime method: []const u8, address: anytype, mail: anytype) void { if (!@hasDecl(address.kind, method)) @compileError("handler does not exist"); } }; } fn Address(comptime T: type) type { return struct { pid: usize, const actor = T; }; } test "basic-actor" { const T = Actor(struct { const T = @This(); pub fn unit(storage: *T, context: *Context(T), mail: void) !void {} }); var t: T = T.init(); }
https://raw.githubusercontent.com/tauoverpi/scratch/b39cda8b3cc49461e1cd270c09e740e850999de8/zig/actor.zig
const std = @import("std"); const tools = @import("tools"); const Computer = struct { const Data = i32; boot_image: []const Data, memory_bank: []Data, const insn_halt = 99; const insn_add = 1; const insn_mul = 2; const insn_input = 3; const insn_output = 4; const insn_jne = 5; // jump-if-true const insn_jeq = 6; // jump-if-false const insn_slt = 7; // less than const insn_seq = 8; // equals const insn_operands = [_][]const bool{ &[_]bool{}, // invalid &[_]bool{ false, false, true }, // add &[_]bool{ false, false, true }, // mul &[_]bool{true}, // input &[_]bool{false}, // output &[_]bool{ false, false }, // jne &[_]bool{ false, false }, // jeq &[_]bool{ false, false, true }, // slt &[_]bool{ false, false, true }, // seq }; fn read_param(c: *Computer, par: Data, mod: bool) Data { return (if (mod) par else c.memory_bank[@intCast(par)]); } fn run(c: *Computer, input: Data) Data { @memcpy(c.memory_bank, c.boot_image); const mem = c.memory_bank; var param_registers: [3]Data = undefined; var output: Data = 0; var pc: usize = 0; while (true) { // decode insn opcode const opcode_and_mods: usize = @intCast(mem[pc]); pc += 1; const opcode = opcode_and_mods % 100; const mods = [_]bool{ (opcode_and_mods / 100) % 10 != 0, (opcode_and_mods / 1000) % 10 != 0, (opcode_and_mods / 10000) % 10 != 0, }; if (opcode == insn_halt) break; // read parameters from insn operands const p = blk: { const operands = insn_operands[opcode]; const p = param_registers[0..operands.len]; var i: usize = 0; while (i < operands.len) : (i += 1) { p[i] = read_param(c, mem[pc + i], mods[i] or operands[i]); } pc += operands.len; break :blk p; }; // execute insn switch (opcode) { insn_halt => break, insn_add => mem[@intCast(p[2])] = p[0] + p[1], insn_mul => mem[@intCast(p[2])] = p[0] * p[1], insn_input => mem[@intCast(p[0])] = input, insn_output => output = p[0], insn_jne => pc = if (p[0] != 0) @intCast(p[1]) else pc, insn_jeq => pc = if (p[0] == 0) @intCast(p[1]) else pc, insn_slt => mem[@intCast(p[2])] = if (p[0] < p[1]) 1 else 0, insn_seq => mem[@intCast(p[2])] = if (p[0] == p[1]) 1 else 0, else => @panic("Illegal instruction"), } } return output; } }; pub fn run(input: []const u8, allocator: std.mem.Allocator) ![2][]const u8 { const int_count = blk: { var int_count: usize = 0; var it = std.mem.split(u8, input, ","); while (it.next()) |_| int_count += 1; break :blk int_count; }; const image = try allocator.alloc(Computer.Data, int_count); defer allocator.free(image); { var it = std.mem.split(u8, input, ","); var i: usize = 0; while (it.next()) |n_text| : (i += 1) { const trimmed = std.mem.trim(u8, n_text, " \n\r\t"); image[i] = try std.fmt.parseInt(Computer.Data, trimmed, 10); } } var computer = Computer{ .boot_image = image, .memory_bank = try allocator.alloc(Computer.Data, int_count), }; defer allocator.free(computer.memory_bank); const ans1 = try std.fmt.allocPrint(allocator, "{}", .{computer.run(1)}); const ans2 = try std.fmt.allocPrint(allocator, "{}", .{computer.run(5)}); return [_][]const u8{ ans1, ans2 }; } pub const main = tools.defaultMain("2019/day05.txt", run);
https://raw.githubusercontent.com/xxxbxxx/advent-of-code/2ad3f7c928b559a2e0e5667693c73a544e89dc42/2019/day05.zig
//! This tool generates SPIR-V features from the grammar files in the SPIRV-Headers //! (https://github.com/KhronosGroup/SPIRV-Headers/) and SPIRV-Registry (https://github.com/KhronosGroup/SPIRV-Registry/) //! repositories. Currently it only generates a basic feature set definition consisting of versions, extensions and capabilities. //! There is a lot left to be desired, as currently dependencies of extensions and dependencies on extensions aren't generated. //! This is because there are some peculiarities in the SPIR-V registries: //! - Capabilities may depend on multiple extensions, which cannot be modelled yet by std.Target. //! - Extension dependencies are not documented in a machine-readable manner. //! - Note that the grammar spec also contains definitions from extensions which aren't actually official. Most of these seem to be //! from an intel project (https://github.com/intel/llvm/, https://github.com/intel/llvm/tree/sycl/sycl/doc/extensions/SPIRV), //! and so ONLY extensions in the SPIRV-Registry should be included. const std = @import("std"); const fs = std.fs; const Allocator = std.mem.Allocator; const g = @import("spirv/grammar.zig"); const Version = struct { major: u32, minor: u32, fn parse(str: []const u8) !Version { var it = std.mem.splitScalar(u8, str, '.'); const major = it.first(); const minor = it.next() orelse return error.InvalidVersion; if (it.next() != null) return error.InvalidVersion; return Version{ .major = std.fmt.parseInt(u32, major, 10) catch return error.InvalidVersion, .minor = std.fmt.parseInt(u32, minor, 10) catch return error.InvalidVersion, }; } fn eql(a: Version, b: Version) bool { return a.major == b.major and a.minor == b.minor; } fn lessThan(ctx: void, a: Version, b: Version) bool { _ = ctx; return if (a.major == b.major) a.minor < b.minor else a.major < b.major; } }; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); const args = try std.process.argsAlloc(allocator); if (args.len <= 1) { usageAndExit(std.io.getStdErr(), args[0], 1); } if (std.mem.eql(u8, args[1], "--help")) { usageAndExit(std.io.getStdErr(), args[0], 0); } if (args.len != 3) { usageAndExit(std.io.getStdErr(), args[0], 1); } const spirv_headers_root = args[1]; const spirv_registry_root = args[2]; if (std.mem.startsWith(u8, spirv_headers_root, "-") or std.mem.startsWith(u8, spirv_registry_root, "-")) { usageAndExit(std.io.getStdErr(), args[0], 1); } // Required for json parsing. @setEvalBranchQuota(10000); const registry_path = try fs.path.join(allocator, &.{ spirv_headers_root, "include", "spirv", "unified1", "spirv.core.grammar.json" }); const registry_json = try std.fs.cwd().readFileAlloc(allocator, registry_path, std.math.maxInt(usize)); var scanner = std.json.Scanner.initCompleteInput(allocator, registry_json); var diagnostics = std.json.Diagnostics{}; scanner.enableDiagnostics(&diagnostics); const registry = std.json.parseFromTokenSourceLeaky(g.CoreRegistry, allocator, &scanner, .{}) catch |err| { std.debug.print("line,col: {},{}\n", .{ diagnostics.getLine(), diagnostics.getColumn() }); return err; }; const capabilities = for (registry.operand_kinds) |opkind| { if (std.mem.eql(u8, opkind.kind, "Capability")) break opkind.enumerants orelse return error.InvalidRegistry; } else return error.InvalidRegistry; const extensions = try gather_extensions(allocator, spirv_registry_root); const versions = try gatherVersions(allocator, registry); var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); const w = bw.writer(); try w.writeAll( \\//! This file is auto-generated by tools/update_spirv_features.zig. \\//! TODO: Dependencies of capabilities on extensions. \\//! TODO: Dependencies of extensions on extensions. \\//! TODO: Dependencies of extensions on versions. \\ \\const std = @import("../std.zig"); \\const CpuFeature = std.Target.Cpu.Feature; \\const CpuModel = std.Target.Cpu.Model; \\ \\pub const Feature = enum { \\ ); for (versions) |ver| { try w.print(" v{}_{},\n", .{ ver.major, ver.minor }); } for (extensions) |ext| { try w.print(" {},\n", .{std.zig.fmtId(ext)}); } for (capabilities) |cap| { try w.print(" {},\n", .{std.zig.fmtId(cap.enumerant)}); } try w.writeAll( \\}; \\ \\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; \\ ); for (versions, 0..) |ver, i| { try w.print( \\ result[@intFromEnum(Feature.v{0}_{1})] = .{{ \\ .llvm_name = null, \\ .description = "SPIR-V version {0}.{1}", \\ , .{ ver.major, ver.minor }); if (i == 0) { try w.writeAll( \\ .dependencies = featureSet(&[_]Feature{}), \\ }; \\ ); } else { try w.print( \\ .dependencies = featureSet(&[_]Feature{{ \\ .v{}_{}, \\ }}), \\ }}; \\ , .{ versions[i - 1].major, versions[i - 1].minor }); } } // TODO: Extension dependencies. for (extensions) |ext| { try w.print( \\ result[@intFromEnum(Feature.{s})] = .{{ \\ .llvm_name = null, \\ .description = "SPIR-V extension {s}", \\ .dependencies = featureSet(&[_]Feature{{}}), \\ }}; \\ , .{ std.zig.fmtId(ext), ext, }); } // TODO: Capability extension dependencies. for (capabilities) |cap| { try w.print( \\ result[@intFromEnum(Feature.{s})] = .{{ \\ .llvm_name = null, \\ .description = "Enable SPIR-V capability {s}", \\ .dependencies = featureSet(&[_]Feature{{ \\ , .{ std.zig.fmtId(cap.enumerant), cap.enumerant, }); if (cap.version) |ver_str| { if (!std.mem.eql(u8, ver_str, "None")) { const ver = try Version.parse(ver_str); try w.print(" .v{}_{},\n", .{ ver.major, ver.minor }); } } for (cap.capabilities) |cap_dep| { try w.print(" .{},\n", .{std.zig.fmtId(cap_dep)}); } try w.writeAll( \\ }), \\ }; \\ ); } try w.writeAll( \\ const ti = @typeInfo(Feature); \\ for (&result, 0..) |*elem, i| { \\ elem.index = i; \\ elem.name = ti.Enum.fields[i].name; \\ } \\ break :blk result; \\}; \\ ); try bw.flush(); } /// SPIRV-Registry should hold all extensions currently registered for SPIR-V. /// The *.grammar.json in SPIRV-Headers should have most of these as well, but with this we're sure to get only the actually /// registered ones. /// TODO: Unfortunately, neither repository contains a machine-readable list of extension dependencies. fn gather_extensions(allocator: Allocator, spirv_registry_root: []const u8) ![]const []const u8 { const extensions_path = try fs.path.join(allocator, &.{ spirv_registry_root, "extensions" }); var extensions_dir = try fs.cwd().openDir(extensions_path, .{ .iterate = true }); defer extensions_dir.close(); var extensions = std.ArrayList([]const u8).init(allocator); var vendor_it = extensions_dir.iterate(); while (try vendor_it.next()) |vendor_entry| { std.debug.assert(vendor_entry.kind == .directory); // If this fails, the structure of SPIRV-Registry has changed. const vendor_dir = try extensions_dir.openDir(vendor_entry.name, .{ .iterate = true }); var ext_it = vendor_dir.iterate(); while (try ext_it.next()) |ext_entry| { // There is both a HTML and asciidoc version of every spec (as well as some other directories), // we need just the name, but to avoid duplicates here we will just skip anything thats not asciidoc. if (!std.mem.endsWith(u8, ext_entry.name, ".asciidoc")) continue; // Unfortunately, some extension filenames are incorrect, so we need to look for the string in tne 'Name Strings' section. // This has the following format: // ``` // Name Strings // ------------ // // SPV_EXT_name // ``` // OR // ``` // == Name Strings // // SPV_EXT_name // ``` const ext_spec = try vendor_dir.readFileAlloc(allocator, ext_entry.name, std.math.maxInt(usize)); const name_strings = "Name Strings"; const name_strings_offset = std.mem.indexOf(u8, ext_spec, name_strings) orelse return error.InvalidRegistry; // As the specs are inconsistent on this next part, just skip any newlines/minuses var ext_start = name_strings_offset + name_strings.len + 1; while (ext_spec[ext_start] == '\n' or ext_spec[ext_start] == '-') { ext_start += 1; } const ext_end = std.mem.indexOfScalarPos(u8, ext_spec, ext_start, '\n') orelse return error.InvalidRegistry; const ext = ext_spec[ext_start..ext_end]; std.debug.assert(std.mem.startsWith(u8, ext, "SPV_")); // Sanity check, all extensions should have a name like SPV_VENDOR_extension. try extensions.append(try allocator.dupe(u8, ext)); } } return extensions.items; } fn insertVersion(versions: *std.ArrayList(Version), version: ?[]const u8) !void { const ver_str = version orelse return; if (std.mem.eql(u8, ver_str, "None")) return; const ver = try Version.parse(ver_str); for (versions.items) |existing_ver| { if (ver.eql(existing_ver)) return; } try versions.append(ver); } fn gatherVersions(allocator: Allocator, registry: g.CoreRegistry) ![]const Version { // Expected number of versions is small var versions = std.ArrayList(Version).init(allocator); for (registry.instructions) |inst| { try insertVersion(&versions, inst.version); } for (registry.operand_kinds) |opkind| { const enumerants = opkind.enumerants orelse continue; for (enumerants) |enumerant| { try insertVersion(&versions, enumerant.version); } } std.mem.sort(Version, versions.items, {}, Version.lessThan); return versions.items; } fn usageAndExit(file: fs.File, arg0: []const u8, code: u8) noreturn { file.writer().print( \\Usage: {s} /path/git/SPIRV-Headers /path/git/SPIRV-Registry \\ \\Prints to stdout Zig code which can be used to replace the file lib/std/target/spirv.zig. \\ \\SPIRV-Headers can be cloned from https://github.com/KhronosGroup/SPIRV-Headers, \\SPIRV-Registry can be cloned from https://github.com/KhronosGroup/SPIRV-Registry. \\ , .{arg0}) catch std.process.exit(1); std.process.exit(code); }
https://raw.githubusercontent.com/2lambda123/ziglang-zig/d7563a7753393d7f0d1af445276a64b8a55cb857/tools/update_spirv_features.zig
const std = @import("std"); const windows = std.os.windows; const memory = std.mem; const ArenaAllocator = std.heap.ArenaAllocator; const assert = std.debug.assert; const warn = std.debug.warn; const testing = std.testing; const win32 = @import("win32"); const time = std.time; const debug = std.debug; pub fn getAllDriveInfos(allocator: *memory.Allocator) ![]DriveInfo { const root_names = try enumerateDrives(allocator); return try getDriveInfos(allocator, root_names); } test "`getAllDriveInfos`" { const allocator = std.heap.page_allocator; const drive_infos = try getAllDriveInfos(allocator); testing.expect(drive_infos.len != 0); } pub fn getDriveInfos(allocator: *memory.Allocator, root_names: []RootPathName) ![]DriveInfo { var drive_infos = try allocator.alloc(DriveInfo, root_names.len); var free_disk_space_entries = try getFreeDiskSpace(allocator, root_names); for (drive_infos) |*di, i| { di.root_name = root_names[i]; di.drive_type = getDriveType(di.root_name); di.free_disk_space = free_disk_space_entries[i]; } return drive_infos; } pub fn getDriveInfo(allocator: *memory.Allocator, root_name: RootPathName) !DriveInfo { const drive_infos = try getDriveInfos(allocator, &[_]RootPathName{root_name}); return drive_infos[0]; } test "`getDriveInfo`" { const allocator = std.heap.page_allocator; const c_drive_info = try getDriveInfo(allocator, [_]u8{ 'C', ':', '\\', 0 }); testing.expectEqual(c_drive_info.drive_type, .Fixed); } pub const DriveInfo = struct { root_name: RootPathName, drive_type: DriveType, free_disk_space: FreeDiskSpaceResult, pub fn openInExplorer(self: DriveInfo) void { _ = win32.c.ShellExecute( null, "open", self.root_name[0..], null, null, win32.c.SW_SHOWDEFAULT, ); } }; pub const DriveType = enum { Unknown = 0, NoRootDirectory = 1, Removable = 2, Fixed = 3, Remote = 4, CDROM = 5, RAMdisk = 6, }; pub const RootPathName = [4]u8; pub const FreeDiskSpaceResult = union(enum) { FreeDiskSpace: FreeDiskSpaceData, UnableToGetDiskInfo: RootPathName, }; const FreeDiskSpaceData = struct { sectors_per_cluster: u32, bytes_per_sector: u32, number_of_free_clusters: u32, total_number_of_clusters: u32, pub fn sectorSizeInBytes(self: FreeDiskSpaceData) u64 { return self.bytes_per_sector * self.sectors_per_cluster; } pub fn freeDiskSpaceInBytes(self: FreeDiskSpaceData) u64 { return sectorSizeInBytes(self) * @as(u64, self.number_of_free_clusters); } pub fn diskSpaceInBytes(self: FreeDiskSpaceData) u64 { return sectorSizeInBytes(self) * @as(u64, self.total_number_of_clusters); } pub fn freeDiskSpaceInKiloBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.freeDiskSpaceInBytes()) / 1000.0; } pub fn diskSpaceInKiloBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.diskSpaceInBytes()) / 1000.0; } pub fn freeDiskSpaceInMegaBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.freeDiskSpaceInBytes()) / (1000.0 * 1000.0); } pub fn diskSpaceInMegaBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.diskSpaceInBytes()) / (1000.0 * 1000.0); } pub fn freeDiskSpaceInGigaBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.freeDiskSpaceInBytes()) / (1000.0 * 1000.0 * 1000.0); } pub fn diskSpaceInGigaBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.diskSpaceInBytes()) / (1000.0 * 1000.0 * 1000.0); } pub fn freeDiskSpaceInKibiBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.freeDiskSpaceInBytes()) / 1024.0; } pub fn diskSpaceInKibiBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.diskSpaceInBytes()) / 1024.0; } pub fn freeDiskSpaceInMebiBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.freeDiskSpaceInBytes()) / (1024.0 * 1024.0); } pub fn diskSpaceInMebiBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.diskSpaceInBytes()) / (1024.0 * 1024.0); } pub fn freeDiskSpaceInGibiBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.freeDiskSpaceInBytes()) / (1024.0 * 1024.0 * 1024.0); } pub fn diskSpaceInGibiBytes(self: FreeDiskSpaceData) f64 { return @intToFloat(f64, self.diskSpaceInBytes()) / (1024.0 * 1024.0 * 1024.0); } }; test "`getDriveType`" { const drives = try enumerateDrives(std.heap.page_allocator); const first_drive = getDriveType(drives[0]); testing.expect(first_drive == DriveType.Fixed); } pub fn getDriveType(root_path_name: RootPathName) DriveType { return @intToEnum(DriveType, @intCast(u3, win32.c.GetDriveTypeA(&root_path_name))); } test "`enumerateDrives`" { var arena_allocator = ArenaAllocator.init(std.heap.page_allocator); defer arena_allocator.deinit(); const allocator = &arena_allocator.allocator; const result = try enumerateDrives(allocator); testing.expect(result.len != 0); } test "`enumerateDrives` with direct allocator" { const result = try enumerateDrives(std.heap.page_allocator); testing.expect(result.len != 0); } pub fn enumerateDrives(allocator: *memory.Allocator) error{OutOfMemory}![]RootPathName { var logical_drives_mask = win32.c.GetLogicalDrives(); const logical_drive_bytes = try allocator.alloc( [4]u8, @popCount(@TypeOf(logical_drives_mask), logical_drives_mask), ); errdefer allocator.free(logical_drive_bytes); var letter: u8 = 'A'; var index: u8 = 0; while (logical_drives_mask != 0) : (logical_drives_mask >>= 1) { if ((logical_drives_mask & 1) == 1) { logical_drive_bytes[index][0] = letter; logical_drive_bytes[index][1] = ':'; logical_drive_bytes[index][2] = '\\'; logical_drive_bytes[index][3] = 0; index += 1; } letter += 1; } return logical_drive_bytes; } // uncomment to check memory usage // test "`getFreeDiskSpace` doesn't leak memory" { // const allocator = std.heap.page_allocator; // const drives = try enumerateDrives(allocator); // var i: usize = 0; // while (i < 10) : (i += 1) { // debug.warn("\nRunning: {}\n", .{i}); // var j: usize = 0; // while (j < 10000) : (j += 1) { // const disk_data = try getFreeDiskSpace(allocator, drives); // allocator.free(disk_data); // } // time.sleep(10000000); // } // } test "calculations for free disk space in 'bytes' make sense" { const allocator = std.heap.page_allocator; const result = try enumerateDrives(allocator); const free_disk_space_entries = try getFreeDiskSpace(allocator, result); var at_least_one_ok = false; testing.expect(free_disk_space_entries.len != 0); for (free_disk_space_entries) |free_disk_space_entry| { switch (free_disk_space_entry) { .FreeDiskSpace => |free_disk_space| { const free_space_bytes = free_disk_space.freeDiskSpaceInBytes(); const free_space_kilobytes = free_disk_space.freeDiskSpaceInKiloBytes(); const free_space_megabytes = free_disk_space.freeDiskSpaceInMegaBytes(); const free_space_gigabytes = free_disk_space.freeDiskSpaceInGigaBytes(); expectApproximatelyEqual( 0.1, free_space_kilobytes, @intToFloat(f64, free_space_bytes) / 1000.0, ); expectApproximatelyEqual(0.1, free_space_megabytes, free_space_kilobytes / 1000.0); expectApproximatelyEqual(0.1, free_space_gigabytes, free_space_megabytes / 1000.0); at_least_one_ok = true; }, .UnableToGetDiskInfo => {}, } } testing.expect(at_least_one_ok); } test "calculations for free disk space in '{ki,me,gi}bibytes' make sense" { const allocator = std.heap.page_allocator; const result = try enumerateDrives(allocator); const free_disk_space_entries = try getFreeDiskSpace(allocator, result); testing.expect(free_disk_space_entries.len != 0); var at_least_one_ok = false; const free_data = FreeDiskSpaceData{ .sectors_per_cluster = 1, .bytes_per_sector = 1000, .number_of_free_clusters = 1, .total_number_of_clusters = 1, }; const free_bytes = free_data.freeDiskSpaceInBytes(); const free_kibibytes = free_data.freeDiskSpaceInKibiBytes(); const free_mebibytes = free_data.freeDiskSpaceInMebiBytes(); const free_gibibytes = free_data.freeDiskSpaceInGibiBytes(); expectApproximatelyEqual(0.1, free_kibibytes, @intToFloat(f64, free_bytes) / 1024.0); expectApproximatelyEqual(0.1, free_mebibytes, free_kibibytes / 1024.0); expectApproximatelyEqual(0.1, free_gibibytes, free_mebibytes / 1024.0); for (free_disk_space_entries) |free_disk_space_entry| { switch (free_disk_space_entry) { .FreeDiskSpace => |free_disk_space| { const free_space_bytes = free_disk_space.freeDiskSpaceInBytes(); const free_space_kibibytes = free_disk_space.freeDiskSpaceInKibiBytes(); const free_space_mebibytes = free_disk_space.freeDiskSpaceInMebiBytes(); const free_space_gibibytes = free_disk_space.freeDiskSpaceInGibiBytes(); expectApproximatelyEqual( 0.1, free_space_kibibytes, @intToFloat(f64, free_space_bytes) / 1024.0, ); expectApproximatelyEqual(0.1, free_space_mebibytes, free_space_kibibytes / 1024.0); expectApproximatelyEqual(0.1, free_space_gibibytes, free_space_mebibytes / 1024.0); at_least_one_ok = true; }, .UnableToGetDiskInfo => {}, } } testing.expect(at_least_one_ok); } pub fn getFreeDiskSpace( allocator: *memory.Allocator, root_path_names: []RootPathName, ) error{OutOfMemory}![]FreeDiskSpaceResult { const disk_data = try allocator.alloc(FreeDiskSpaceResult, root_path_names.len); errdefer allocator.free(disk_data); for (root_path_names) |name, i| { var sectors_per_cluster: win32.c.ULONG = undefined; var bytes_per_sector: win32.c.ULONG = undefined; var number_of_free_clusters: win32.c.ULONG = undefined; var total_number_of_clusters: win32.c.ULONG = undefined; const result = win32.c.GetDiskFreeSpaceA( &name, &sectors_per_cluster, &bytes_per_sector, &number_of_free_clusters, &total_number_of_clusters, ); switch (result) { 0 => disk_data[i] = FreeDiskSpaceResult{ .UnableToGetDiskInfo = name }, else => disk_data[i] = FreeDiskSpaceResult{ .FreeDiskSpace = FreeDiskSpaceData{ .sectors_per_cluster = sectors_per_cluster, .bytes_per_sector = bytes_per_sector, .number_of_free_clusters = number_of_free_clusters, .total_number_of_clusters = total_number_of_clusters, }, }, } } return disk_data; } fn expectApproximatelyEqual(tolerance: f64, a: f64, b: f64) void { const diff = @fabs(a - b); testing.expect(diff < tolerance); }
https://raw.githubusercontent.com/GoNZooo/zig-disk-info/215061808ef0e034f3a055208b0b39617eb987ac/src/disk.zig
const std = @import("std"); const testing = std.testing; const Allocator = std.mem.Allocator; pub const Map = struct { allocator: Allocator, orig: std.ArrayList(isize), pub fn init(allocator: Allocator) Map { var self = Map{ .allocator = allocator, .orig = std.ArrayList(isize).init(allocator), }; return self; } pub fn deinit(self: *Map) void { self.orig.deinit(); } pub fn add_line(self: *Map, line: []const u8) !void { const num = try std.fmt.parseInt(isize, line, 10); try self.orig.append(num); } pub fn show(self: Map) void { std.debug.print("-- Map --------\n", .{}); std.debug.print(" Orig:", .{}); for (self.orig.items) |orig| { std.debug.print(" {}", .{orig}); } std.debug.print("\n", .{}); } fn sign(num: isize) isize { if (num > 0) return 1; if (num < 0) return -1; return 0; } fn add_wrap(num: isize, delta: isize) usize { return @intCast(usize, @rem(@rem(num, delta) + delta, delta)); } pub fn mix_data(self: *Map, key: isize, rounds: usize) !isize { // copy of original values var work = std.ArrayList(isize).init(self.allocator); defer work.deinit(); // mapping from pos to index var pos2idx = std.ArrayList(isize).init(self.allocator); defer pos2idx.deinit(); // mapping from index tp pos var idx2pos = std.ArrayList(isize).init(self.allocator); defer idx2pos.deinit(); var zero_orig: usize = undefined; for (self.orig.items) |num, pos| { if (num == 0) zero_orig = pos; // remember location of 0; try work.append(num * key); // copy all original values; // populate maps const p = @intCast(isize, pos); try pos2idx.append(p); try idx2pos.append(p); } const size = @intCast(isize, work.items.len); var round: usize = 0; while (round < rounds) : (round += 1) { std.debug.print("ROUND {}\n", .{round+1}); for (work.items) |num, pos| { var src_idx = pos2idx.items[pos]; var tgt_idx = src_idx + @rem(num, size - 1); // LOL const d = sign(num); var p: isize = src_idx; while (p != tgt_idx) : (p += d) { // source and target indexes var s_idx = add_wrap(p+0, size); var t_idx = add_wrap(p+d, size); // source and target positions var s_pos = @intCast(usize, idx2pos.items[s_idx]); var t_pos = @intCast(usize, idx2pos.items[t_idx]); // swap everything pos2idx.items[s_pos] = @intCast(isize, t_idx); pos2idx.items[t_pos] = @intCast(isize, s_idx); idx2pos.items[s_idx] = @intCast(isize, t_pos); idx2pos.items[t_idx] = @intCast(isize, s_pos); } } } var sum: isize = 0; var c: isize = 1000; while (c <= 3000) : (c += 1000) { const zero_idx = add_wrap(pos2idx.items[zero_orig] + c, size); const zero_pos = @intCast(usize, idx2pos.items[zero_idx]); const coord = work.items[zero_pos]; // std.debug.print("Coord at {} = {}\n", .{c, coord}); sum += coord; } return sum; } }; test "sample part 1" { std.debug.print("\n", .{}); const data: []const u8 = \\1 \\2 \\-3 \\3 \\-2 \\0 \\4 ; var map = Map.init(std.testing.allocator); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.add_line(line); } const sgc = try map.mix_data(1, 1); // map.show(); try testing.expectEqual(@as(isize, 3), sgc); } test "sample part 2" { std.debug.print("\n", .{}); const data: []const u8 = \\1 \\2 \\-3 \\3 \\-2 \\0 \\4 ; var map = Map.init(std.testing.allocator); defer map.deinit(); var it = std.mem.split(u8, data, "\n"); while (it.next()) |line| { try map.add_line(line); } const sgc = try map.mix_data(811589153, 10); // map.show(); try testing.expectEqual(@as(isize, 1623178306), sgc); }
https://raw.githubusercontent.com/gonzus/AdventOfCode/7e972b92a23db29461b2869713a3251998af5822/2022/p20/map.zig
allocator: std.mem.Allocator, version: Version, transitionTimes: []i64, transitionTypes: []u8, localTimeTypes: []LocalTimeType, designations: []u8, leapSeconds: []LeapSecond, transitionIsStd: []bool, transitionIsUT: []bool, string: []u8, posixTZ: ?Posix, const TZif = @This(); pub fn deinit(this: *@This()) void { this.allocator.free(this.transitionTimes); this.allocator.free(this.transitionTypes); this.allocator.free(this.localTimeTypes); this.allocator.free(this.designations); this.allocator.free(this.leapSeconds); this.allocator.free(this.transitionIsStd); this.allocator.free(this.transitionIsUT); this.allocator.free(this.string); } pub const TIMEZONE_VTABLE = chrono.tz.TimeZone.VTable.eraseTypes(@This(), .{ .offsetAtTimestamp = offsetAtTimestamp, .isDaylightSavingTimeAtTimestamp = isDaylightSavingTimeAtTimestamp, .designationAtTimestamp = designationAtTimestamp, .identifier = identifier, }); pub fn timeZone(this: *@This()) chrono.tz.TimeZone { return chrono.tz.TimeZone{ .ptr = this, .vtable = &TIMEZONE_VTABLE, }; } pub fn offsetAtTimestamp(this: *const @This(), utc: i64) ?i32 { const transition_type_by_timestamp = getTransitionTypeByTimestamp(this.transitionTimes, utc); switch (transition_type_by_timestamp) { .first_local_time_type => return this.localTimeTypes[0].ut_offset, .transition_index => |transition_index| { const local_time_type_idx = this.transitionTypes[transition_index]; const local_time_type = this.localTimeTypes[local_time_type_idx]; return local_time_type.ut_offset; }, .specified_by_posix_tz, .specified_by_posix_tz_or_index_0, => if (this.posixTZ) |posixTZ| { // Base offset on the TZ string return posixTZ.offsetAtTimestamp(utc); } else { switch (transition_type_by_timestamp) { .specified_by_posix_tz => return null, .specified_by_posix_tz_or_index_0 => return this.localTimeTypes[0].ut_offset, else => unreachable, } }, } } pub fn isDaylightSavingTimeAtTimestamp(this: *const @This(), utc: i64) ?bool { const transition_type_by_timestamp = getTransitionTypeByTimestamp(this.transitionTimes, utc); switch (transition_type_by_timestamp) { .first_local_time_type => return this.localTimeTypes[0].is_daylight_saving_time, .transition_index => |transition_index| { const local_time_type_idx = this.transitionTypes[transition_index]; const local_time_type = this.localTimeTypes[local_time_type_idx]; return local_time_type.is_daylight_saving_time; }, .specified_by_posix_tz, .specified_by_posix_tz_or_index_0, => if (this.posixTZ) |posixTZ| { // Base offset on the TZ string return posixTZ.isDaylightSavingTimeAtTimestamp(utc); } else { switch (transition_type_by_timestamp) { .specified_by_posix_tz => return null, .specified_by_posix_tz_or_index_0 => { return this.localTimeTypes[0].is_daylight_saving_time; }, else => unreachable, } }, } } pub fn designationAtTimestamp(this: *const @This(), utc: i64) ?[]const u8 { const transition_type_by_timestamp = getTransitionTypeByTimestamp(this.transitionTimes, utc); switch (transition_type_by_timestamp) { .first_local_time_type => { const local_time_type = this.localTimeTypes[0]; const designation_end = std.mem.indexOfScalarPos(u8, this.designations[0 .. this.designations.len - 1], local_time_type.designation_index, 0) orelse this.designations.len - 1; const designation = this.designations[local_time_type.designation_index..designation_end]; return designation; }, .transition_index => |transition_index| { const local_time_type_idx = this.transitionTypes[transition_index]; const local_time_type = this.localTimeTypes[local_time_type_idx]; const designation_end = std.mem.indexOfScalarPos(u8, this.designations[0 .. this.designations.len - 1], local_time_type.designation_index, 0) orelse this.designations.len - 1; const designation = this.designations[local_time_type.designation_index..designation_end]; return designation; }, .specified_by_posix_tz, .specified_by_posix_tz_or_index_0, => if (this.posixTZ) |posixTZ| { // Base offset on the TZ string return posixTZ.designationAtTimestamp(utc); } else { switch (transition_type_by_timestamp) { .specified_by_posix_tz => return null, .specified_by_posix_tz_or_index_0 => { const local_time_type = this.localTimeTypes[0]; const designation_end = std.mem.indexOfScalarPos(u8, this.designations[0 .. this.designations.len - 1], local_time_type.designation_index, 0) orelse this.designations.len - 1; const designation = this.designations[local_time_type.designation_index..designation_end]; return designation; }, else => unreachable, } }, } } pub fn identifier(this: *const @This()) ?chrono.tz.Identifier { _ = this; return null; } pub const ConversionResult = struct { timestamp: i64, offset: i32, is_daylight_saving_time: bool, designation: []const u8, }; fn localTimeFromUTC(this: @This(), utc: i64) ?ConversionResult { const offset = this.offsetAtTimestamp(utc) orelse return null; const is_daylight_saving_time = this.isDaylightSavingTimeAtTimestamp(utc) orelse return null; const designation = this.designationAtTimestamp(utc) orelse return null; return ConversionResult{ .timestamp = utc + offset, .offset = offset, .is_daylight_saving_time = is_daylight_saving_time, .designation = designation, }; } pub const Version = enum(u8) { V1 = 0, V2 = '2', V3 = '3', pub fn timeSize(this: @This()) u32 { return switch (this) { .V1 => 4, .V2, .V3 => 8, }; } pub fn leapSize(this: @This()) u32 { return this.timeSize() + 4; } pub fn string(this: @This()) []const u8 { return switch (this) { .V1 => "1", .V2 => "2", .V3 => "3", }; } }; pub const LocalTimeType = struct { /// An i32 specifying the number of seconds to be added to UT in order to determine local time. /// The value MUST NOT be -2**31 and SHOULD be in the range /// [-89999, 93599] (i.e., its value SHOULD be more than -25 hours /// and less than 26 hours). Avoiding -2**31 allows 32-bit clients /// to negate the value without overflow. Restricting it to /// [-89999, 93599] allows easy support by implementations that /// already support the POSIX-required range [-24:59:59, 25:59:59]. ut_offset: i32, /// A value indicating whether local time should be considered Daylight Saving Time (DST). /// /// A value of `true` indicates that this type of time is DST. /// A value of `false` indicates that this time type is standard time. is_daylight_saving_time: bool, /// A u8 specifying an index into the time zone designations, thereby /// selecting a particular designation string. Each index MUST be /// in the range [0, "charcnt" - 1]; it designates the /// NUL-terminated string of octets starting at position `designation_index` in /// the time zone designations. (This string MAY be empty.) A NUL /// octet MUST exist in the time zone designations at or after /// position `designation_index`. designation_index: u8, }; pub const LeapSecond = struct { occur: i64, corr: i32, }; const TIME_TYPE_SIZE = 6; pub const Header = struct { version: Version, isutcnt: u32, isstdcnt: u32, leapcnt: u32, timecnt: u32, typecnt: u32, charcnt: u32, pub fn dataSize(this: @This(), dataBlockVersion: Version) u32 { return this.timecnt * dataBlockVersion.timeSize() + this.timecnt + this.typecnt * TIME_TYPE_SIZE + this.charcnt + this.leapcnt * dataBlockVersion.leapSize() + this.isstdcnt + this.isutcnt; } pub fn parse(reader: anytype, seekableStream: anytype) !Header { var magic_buf: [4]u8 = undefined; try reader.readNoEof(&magic_buf); if (!std.mem.eql(u8, "TZif", &magic_buf)) { return error.TZifMissingMagic; } // Check verison const version = reader.readEnum(Version, .little) catch |err| switch (err) { error.InvalidValue => return error.UnsupportedVersion, else => |e| return e, }; if (version == .V1) { return error.UnsupportedVersion; } // Seek past reserved bytes try seekableStream.seekBy(15); return Header{ .version = version, .isutcnt = try reader.readInt(u32, .big), .isstdcnt = try reader.readInt(u32, .big), .leapcnt = try reader.readInt(u32, .big), .timecnt = try reader.readInt(u32, .big), .typecnt = try reader.readInt(u32, .big), .charcnt = try reader.readInt(u32, .big), }; } }; pub fn parse(allocator: std.mem.Allocator, reader: anytype, seekableStream: anytype) !TZif { const v1_header = try Header.parse(reader, seekableStream); try seekableStream.seekBy(v1_header.dataSize(.V1)); const v2_header = try Header.parse(reader, seekableStream); // Parse transition times var transition_times = try allocator.alloc(i64, v2_header.timecnt); errdefer allocator.free(transition_times); { var prev: i64 = -(2 << 59); // Earliest time supported, this is earlier than the big bang var i: usize = 0; while (i < transition_times.len) : (i += 1) { transition_times[i] = try reader.readInt(i64, .big); if (transition_times[i] <= prev) { return error.InvalidFormat; } prev = transition_times[i]; } } // Parse transition types const transition_types = try allocator.alloc(u8, v2_header.timecnt); errdefer allocator.free(transition_types); try reader.readNoEof(transition_types); for (transition_types) |transition_type| { if (transition_type >= v2_header.typecnt) { return error.InvalidFormat; // a transition type index is out of bounds } } // Parse local time type records var local_time_types = try allocator.alloc(LocalTimeType, v2_header.typecnt); errdefer allocator.free(local_time_types); { var i: usize = 0; while (i < local_time_types.len) : (i += 1) { local_time_types[i].ut_offset = try reader.readInt(i32, .big); local_time_types[i].is_daylight_saving_time = switch (try reader.readByte()) { 0 => false, 1 => true, else => return error.InvalidFormat, }; local_time_types[i].designation_index = try reader.readByte(); if (local_time_types[i].designation_index >= v2_header.charcnt) { return error.InvalidFormat; } } } // Read designations const time_zone_designations = try allocator.alloc(u8, v2_header.charcnt); errdefer allocator.free(time_zone_designations); try reader.readNoEof(time_zone_designations); // Parse leap seconds records var leap_seconds = try allocator.alloc(LeapSecond, v2_header.leapcnt); errdefer allocator.free(leap_seconds); { var i: usize = 0; while (i < leap_seconds.len) : (i += 1) { leap_seconds[i].occur = try reader.readInt(i64, .big); if (i == 0 and leap_seconds[i].occur < 0) { return error.InvalidFormat; } else if (i != 0 and leap_seconds[i].occur - leap_seconds[i - 1].occur < 2419199) { return error.InvalidFormat; // There must be at least 28 days worth of seconds between leap seconds } leap_seconds[i].corr = try reader.readInt(i32, .big); if (i == 0 and (leap_seconds[0].corr != 1 and leap_seconds[0].corr != -1)) { log.warn("First leap second correction is not 1 or -1: {}", .{leap_seconds[0]}); return error.InvalidFormat; } else if (i != 0) { const diff = leap_seconds[i].corr - leap_seconds[i - 1].corr; if (diff != 1 and diff != -1) { log.warn("Too large of a difference between leap seconds: {}", .{diff}); return error.InvalidFormat; } } } } // Parse standard/wall indicators var transition_is_std = try allocator.alloc(bool, v2_header.isstdcnt); errdefer allocator.free(transition_is_std); { var i: usize = 0; while (i < transition_is_std.len) : (i += 1) { transition_is_std[i] = switch (try reader.readByte()) { 1 => true, 0 => false, else => return error.InvalidFormat, }; } } // Parse UT/local indicators var transition_is_ut = try allocator.alloc(bool, v2_header.isutcnt); errdefer allocator.free(transition_is_ut); { var i: usize = 0; while (i < transition_is_ut.len) : (i += 1) { transition_is_ut[i] = switch (try reader.readByte()) { 1 => true, 0 => false, else => return error.InvalidFormat, }; } } // Parse TZ string from footer if ((try reader.readByte()) != '\n') return error.InvalidFormat; const tz_string = try reader.readUntilDelimiterAlloc(allocator, '\n', 60); errdefer allocator.free(tz_string); const posixTZ: ?Posix = if (tz_string.len > 0) try Posix.parse(tz_string) else null; return TZif{ .allocator = allocator, .version = v2_header.version, .transitionTimes = transition_times, .transitionTypes = transition_types, .localTimeTypes = local_time_types, .designations = time_zone_designations, .leapSeconds = leap_seconds, .transitionIsStd = transition_is_std, .transitionIsUT = transition_is_ut, .string = tz_string, .posixTZ = posixTZ, }; } pub fn parseFile(allocator: std.mem.Allocator, path: []const u8) !TZif { const cwd = std.fs.cwd(); const file = try cwd.openFile(path, .{}); defer file.close(); return parse(allocator, file.reader(), file.seekableStream()); } const TransitionType = union(enum) { first_local_time_type, transition_index: usize, specified_by_posix_tz, specified_by_posix_tz_or_index_0, }; /// Get the transition type of the first element in the `transition_times` array which is less than or equal to `timestamp_utc`. /// /// Returns `.transition_index` if the timestamp is contained inside the `transition_times` array. /// /// Returns `.specified_by_posix_tz_or_index_0` if the `transition_times` list is empty. /// /// Returns `.first_local_time_type` if `timestamp_utc` is before the first transition time. /// /// Returns `.specified_by_posix_tz` if `timestamp_utc` is after or on the last transition time. fn getTransitionTypeByTimestamp(transition_times: []const i64, timestamp_utc: i64) TransitionType { if (transition_times.len == 0) return .specified_by_posix_tz_or_index_0; if (timestamp_utc < transition_times[0]) return .first_local_time_type; if (timestamp_utc >= transition_times[transition_times.len - 1]) return .specified_by_posix_tz; var left: usize = 0; var right: usize = transition_times.len; while (left < right) { // Avoid overflowing in the midpoint calculation const mid = left + (right - left) / 2; // Compare the key with the midpoint element if (transition_times[mid] == timestamp_utc) { if (mid + 1 < transition_times.len) { return .{ .transition_index = mid }; } else { return .{ .transition_index = mid }; } } else if (transition_times[mid] > timestamp_utc) { right = mid; } else if (transition_times[mid] < timestamp_utc) { left = mid + 1; } } if (right >= transition_times.len) { return .specified_by_posix_tz; } else if (right > 0) { return .{ .transition_index = right - 1 }; } else { return .first_local_time_type; } } test getTransitionTypeByTimestamp { const transition_times = [7]i64{ -2334101314, -1157283000, -1155436200, -880198200, -769395600, -765376200, -712150200 }; try testing.expectEqual(TransitionType.first_local_time_type, getTransitionTypeByTimestamp(&transition_times, -2334101315)); try testing.expectEqual(TransitionType{ .transition_index = 0 }, getTransitionTypeByTimestamp(&transition_times, -2334101314)); try testing.expectEqual(TransitionType{ .transition_index = 0 }, getTransitionTypeByTimestamp(&transition_times, -2334101313)); try testing.expectEqual(TransitionType{ .transition_index = 0 }, getTransitionTypeByTimestamp(&transition_times, -1157283001)); try testing.expectEqual(TransitionType{ .transition_index = 1 }, getTransitionTypeByTimestamp(&transition_times, -1157283000)); try testing.expectEqual(TransitionType{ .transition_index = 1 }, getTransitionTypeByTimestamp(&transition_times, -1157282999)); try testing.expectEqual(TransitionType{ .transition_index = 1 }, getTransitionTypeByTimestamp(&transition_times, -1155436201)); try testing.expectEqual(TransitionType{ .transition_index = 2 }, getTransitionTypeByTimestamp(&transition_times, -1155436200)); try testing.expectEqual(TransitionType{ .transition_index = 2 }, getTransitionTypeByTimestamp(&transition_times, -1155436199)); try testing.expectEqual(TransitionType{ .transition_index = 2 }, getTransitionTypeByTimestamp(&transition_times, -880198201)); try testing.expectEqual(TransitionType{ .transition_index = 3 }, getTransitionTypeByTimestamp(&transition_times, -880198200)); try testing.expectEqual(TransitionType{ .transition_index = 3 }, getTransitionTypeByTimestamp(&transition_times, -880198199)); try testing.expectEqual(TransitionType{ .transition_index = 3 }, getTransitionTypeByTimestamp(&transition_times, -769395601)); try testing.expectEqual(TransitionType{ .transition_index = 4 }, getTransitionTypeByTimestamp(&transition_times, -769395600)); try testing.expectEqual(TransitionType{ .transition_index = 4 }, getTransitionTypeByTimestamp(&transition_times, -769395599)); try testing.expectEqual(TransitionType{ .transition_index = 4 }, getTransitionTypeByTimestamp(&transition_times, -765376201)); try testing.expectEqual(TransitionType{ .transition_index = 5 }, getTransitionTypeByTimestamp(&transition_times, -765376200)); try testing.expectEqual(TransitionType{ .transition_index = 5 }, getTransitionTypeByTimestamp(&transition_times, -765376199)); // Why is there 7 transition types if the last type is not used? try testing.expectEqual(TransitionType{ .transition_index = 5 }, getTransitionTypeByTimestamp(&transition_times, -712150201)); try testing.expectEqual(TransitionType.specified_by_posix_tz, getTransitionTypeByTimestamp(&transition_times, -712150200)); try testing.expectEqual(TransitionType.specified_by_posix_tz, getTransitionTypeByTimestamp(&transition_times, -712150199)); } test "parse invalid bytes" { var fbs = std.io.fixedBufferStream("dflkasjreklnlkvnalkfek"); try testing.expectError(error.TZifMissingMagic, parse(std.testing.allocator, fbs.reader(), fbs.seekableStream())); } test "parse UTC zoneinfo" { var fbs = std.io.fixedBufferStream(@embedFile("zoneinfo/UTC")); var res = try parse(std.testing.allocator, fbs.reader(), fbs.seekableStream()); defer res.deinit(); try testing.expectEqual(Version.V2, res.version); try testing.expectEqualSlices(i64, &[_]i64{}, res.transitionTimes); try testing.expectEqualSlices(u8, &[_]u8{}, res.transitionTypes); try testing.expectEqualSlices(LocalTimeType, &[_]LocalTimeType{.{ .ut_offset = 0, .is_daylight_saving_time = false, .designation_index = 0 }}, res.localTimeTypes); try testing.expectEqualSlices(u8, "UTC\x00", res.designations); } test "parse Pacific/Honolulu zoneinfo and calculate local times" { const transition_times = [7]i64{ -2334101314, -1157283000, -1155436200, -880198200, -769395600, -765376200, -712150200 }; const transition_types = [7]u8{ 1, 2, 1, 3, 4, 1, 5 }; const local_time_types = [6]LocalTimeType{ .{ .ut_offset = -37886, .is_daylight_saving_time = false, .designation_index = 0 }, .{ .ut_offset = -37800, .is_daylight_saving_time = false, .designation_index = 4 }, .{ .ut_offset = -34200, .is_daylight_saving_time = true, .designation_index = 8 }, .{ .ut_offset = -34200, .is_daylight_saving_time = true, .designation_index = 12 }, .{ .ut_offset = -34200, .is_daylight_saving_time = true, .designation_index = 16 }, .{ .ut_offset = -36000, .is_daylight_saving_time = false, .designation_index = 4 }, }; const designations = "LMT\x00HST\x00HDT\x00HWT\x00HPT\x00"; const is_std = &[6]bool{ false, false, false, false, true, false }; const is_ut = &[6]bool{ false, false, false, false, true, false }; const string = "HST10"; var fbs = std.io.fixedBufferStream(@embedFile("zoneinfo/Pacific/Honolulu")); var res = try parse(std.testing.allocator, fbs.reader(), fbs.seekableStream()); defer res.deinit(); try testing.expectEqual(Version.V2, res.version); try testing.expectEqualSlices(i64, &transition_times, res.transitionTimes); try testing.expectEqualSlices(u8, &transition_types, res.transitionTypes); try testing.expectEqualSlices(LocalTimeType, &local_time_types, res.localTimeTypes); try testing.expectEqualSlices(u8, designations, res.designations); try testing.expectEqualSlices(bool, is_std, res.transitionIsStd); try testing.expectEqualSlices(bool, is_ut, res.transitionIsUT); try testing.expectEqualSlices(u8, string, res.string); { const conversion = res.localTimeFromUTC(-1156939200).?; try testing.expectEqual(@as(i64, -1156973400), conversion.timestamp); try testing.expectEqual(true, conversion.is_daylight_saving_time); try testing.expectEqualSlices(u8, "HDT", conversion.designation); } { // A second before the first timezone transition const conversion = res.localTimeFromUTC(-2334101315).?; try testing.expectEqual(@as(i64, -2334101315 - 37886), conversion.timestamp); try testing.expectEqual(false, conversion.is_daylight_saving_time); try testing.expectEqualSlices(u8, "LMT", conversion.designation); } { // At the first timezone transition const conversion = res.localTimeFromUTC(-2334101314).?; try testing.expectEqual(@as(i64, -2334101314 - 37800), conversion.timestamp); try testing.expectEqual(false, conversion.is_daylight_saving_time); try testing.expectEqualSlices(u8, "HST", conversion.designation); } { // After the first timezone transition const conversion = res.localTimeFromUTC(-2334101313).?; try testing.expectEqual(@as(i64, -2334101313 - 37800), conversion.timestamp); try testing.expectEqual(false, conversion.is_daylight_saving_time); try testing.expectEqualSlices(u8, "HST", conversion.designation); } { // After the last timezone transition; conversion should be performed using the Posix TZ footer. // Taken from RFC8536 Appendix B.2 const conversion = res.localTimeFromUTC(1546300800).?; try testing.expectEqual(@as(i64, 1546300800) - 10 * std.time.s_per_hour, conversion.timestamp); try testing.expectEqual(false, conversion.is_daylight_saving_time); try testing.expectEqualSlices(u8, "HST", conversion.designation); } } const log = std.log.scoped(.tzif); const chrono = @import("../lib.zig"); const Posix = @import("./Posix.zig"); const testing = std.testing; const std = @import("std");
https://raw.githubusercontent.com/leroycep/chrono-zig/bedd9339af9b05c240956b137cb1a5b67a9b74b7/src/tz/TZif.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.zig"); const cstr = std.cstr; const unicode = std.unicode; const io = std.io; const fs = std.fs; const os = std.os; const process = std.process; const File = std.fs.File; const windows = os.windows; const mem = std.mem; const debug = std.debug; const BufMap = std.BufMap; const builtin = @import("builtin"); const Os = builtin.Os; const TailQueue = std.TailQueue; const maxInt = std.math.maxInt; const assert = std.debug.assert; pub const ChildProcess = struct { pid: if (builtin.os.tag == .windows) void else i32, handle: if (builtin.os.tag == .windows) windows.HANDLE else void, thread_handle: if (builtin.os.tag == .windows) windows.HANDLE else void, allocator: *mem.Allocator, stdin: ?File, stdout: ?File, stderr: ?File, term: ?(SpawnError!Term), argv: []const []const u8, /// Leave as null to use the current env map using the supplied allocator. env_map: ?*const BufMap, stdin_behavior: StdIo, stdout_behavior: StdIo, stderr_behavior: StdIo, /// Set to change the user id when spawning the child process. uid: if (builtin.os.tag == .windows or builtin.os.tag == .wasi) void else ?os.uid_t, /// Set to change the group id when spawning the child process. gid: if (builtin.os.tag == .windows or builtin.os.tag == .wasi) void else ?os.gid_t, /// Set to change the current working directory when spawning the child process. cwd: ?[]const u8, /// Set to change the current working directory when spawning the child process. /// This is not yet implemented for Windows. See https://github.com/ziglang/zig/issues/5190 /// Once that is done, `cwd` will be deprecated in favor of this field. cwd_dir: ?fs.Dir = null, err_pipe: if (builtin.os.tag == .windows) void else [2]os.fd_t, expand_arg0: Arg0Expand, pub const Arg0Expand = os.Arg0Expand; pub const SpawnError = error{ OutOfMemory, /// POSIX-only. `StdIo.Ignore` was selected and opening `/dev/null` returned ENODEV. NoDevice, /// Windows-only. One of: /// * `cwd` was provided and it could not be re-encoded into UTF16LE, or /// * The `PATH` or `PATHEXT` environment variable contained invalid UTF-8. InvalidUtf8, /// Windows-only. `cwd` was provided, but the path did not exist when spawning the child process. CurrentWorkingDirectoryUnlinked, } || os.ExecveError || os.SetIdError || os.ChangeCurDirError || windows.CreateProcessError || windows.WaitForSingleObjectError; pub const Term = union(enum) { Exited: u32, Signal: u32, Stopped: u32, Unknown: u32, }; pub const StdIo = enum { Inherit, Ignore, Pipe, Close, }; /// First argument in argv is the executable. /// On success must call deinit. pub fn init(argv: []const []const u8, allocator: *mem.Allocator) !*ChildProcess { const child = try allocator.create(ChildProcess); child.* = ChildProcess{ .allocator = allocator, .argv = argv, .pid = undefined, .handle = undefined, .thread_handle = undefined, .err_pipe = undefined, .term = null, .env_map = null, .cwd = null, .uid = if (builtin.os.tag == .windows or builtin.os.tag == .wasi) {} else null, .gid = if (builtin.os.tag == .windows or builtin.os.tag == .wasi) {} else null, .stdin = null, .stdout = null, .stderr = null, .stdin_behavior = StdIo.Inherit, .stdout_behavior = StdIo.Inherit, .stderr_behavior = StdIo.Inherit, .expand_arg0 = .no_expand, }; errdefer allocator.destroy(child); return child; } pub fn setUserName(self: *ChildProcess, name: []const u8) !void { const user_info = try os.getUserInfo(name); self.uid = user_info.uid; self.gid = user_info.gid; } /// On success must call `kill` or `wait`. pub fn spawn(self: *ChildProcess) SpawnError!void { if (builtin.os.tag == .windows) { return self.spawnWindows(); } else { return self.spawnPosix(); } } pub fn spawnAndWait(self: *ChildProcess) SpawnError!Term { try self.spawn(); return self.wait(); } /// Forcibly terminates child process and then cleans up all resources. pub fn kill(self: *ChildProcess) !Term { if (builtin.os.tag == .windows) { return self.killWindows(1); } else { return self.killPosix(); } } pub fn killWindows(self: *ChildProcess, exit_code: windows.UINT) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } try windows.TerminateProcess(self.handle, exit_code); try self.waitUnwrappedWindows(); return self.term.?; } pub fn killPosix(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } try os.kill(self.pid, os.SIGTERM); self.waitUnwrapped(); return self.term.?; } /// Blocks until child process terminates and then cleans up all resources. pub fn wait(self: *ChildProcess) !Term { if (builtin.os.tag == .windows) { return self.waitWindows(); } else { return self.waitPosix(); } } pub const ExecResult = struct { term: Term, stdout: []u8, stderr: []u8, }; pub const exec2 = @compileError("deprecated: exec2 is renamed to exec"); fn collectOutputPosix( child: *const ChildProcess, stdout: *std.ArrayList(u8), stderr: *std.ArrayList(u8), max_output_bytes: usize, ) !void { var poll_fds = [_]os.pollfd{ .{ .fd = child.stdout.?.handle, .events = os.POLLIN, .revents = undefined }, .{ .fd = child.stderr.?.handle, .events = os.POLLIN, .revents = undefined }, }; var dead_fds: usize = 0; // We ask for ensureCapacity with this much extra space. This has more of an // effect on small reads because once the reads start to get larger the amount // of space an ArrayList will allocate grows exponentially. const bump_amt = 512; while (dead_fds < poll_fds.len) { const events = try os.poll(&poll_fds, std.math.maxInt(i32)); if (events == 0) continue; // Try reading whatever is available before checking the error // conditions. if (poll_fds[0].revents & os.POLLIN != 0) { // stdout is ready. const new_capacity = std.math.min(stdout.items.len + bump_amt, max_output_bytes); try stdout.ensureCapacity(new_capacity); const buf = stdout.unusedCapacitySlice(); if (buf.len == 0) return error.StdoutStreamTooLong; stdout.items.len += try os.read(poll_fds[0].fd, buf); } if (poll_fds[1].revents & os.POLLIN != 0) { // stderr is ready. const new_capacity = std.math.min(stderr.items.len + bump_amt, max_output_bytes); try stderr.ensureCapacity(new_capacity); const buf = stderr.unusedCapacitySlice(); if (buf.len == 0) return error.StderrStreamTooLong; stderr.items.len += try os.read(poll_fds[1].fd, buf); } // Exclude the fds that signaled an error. if (poll_fds[0].revents & (os.POLLERR | os.POLLNVAL | os.POLLHUP) != 0) { poll_fds[0].fd = -1; dead_fds += 1; } if (poll_fds[1].revents & (os.POLLERR | os.POLLNVAL | os.POLLHUP) != 0) { poll_fds[1].fd = -1; dead_fds += 1; } } } /// Spawns a child process, waits for it, collecting stdout and stderr, and then returns. /// If it succeeds, the caller owns result.stdout and result.stderr memory. pub fn exec(args: struct { allocator: *mem.Allocator, argv: []const []const u8, cwd: ?[]const u8 = null, cwd_dir: ?fs.Dir = null, env_map: ?*const BufMap = null, max_output_bytes: usize = 50 * 1024, expand_arg0: Arg0Expand = .no_expand, }) !ExecResult { const child = try ChildProcess.init(args.argv, args.allocator); defer child.deinit(); child.stdin_behavior = .Ignore; child.stdout_behavior = .Pipe; child.stderr_behavior = .Pipe; child.cwd = args.cwd; child.cwd_dir = args.cwd_dir; child.env_map = args.env_map; child.expand_arg0 = args.expand_arg0; try child.spawn(); // TODO collect output in a deadlock-avoiding way on Windows. // https://github.com/ziglang/zig/issues/6343 if (builtin.os.tag == .windows or builtin.os.tag == .haiku) { const stdout_in = child.stdout.?.reader(); const stderr_in = child.stderr.?.reader(); const stdout = try stdout_in.readAllAlloc(args.allocator, args.max_output_bytes); errdefer args.allocator.free(stdout); const stderr = try stderr_in.readAllAlloc(args.allocator, args.max_output_bytes); errdefer args.allocator.free(stderr); return ExecResult{ .term = try child.wait(), .stdout = stdout, .stderr = stderr, }; } var stdout = std.ArrayList(u8).init(args.allocator); var stderr = std.ArrayList(u8).init(args.allocator); try collectOutputPosix(child, &stdout, &stderr, args.max_output_bytes); return ExecResult{ .term = try child.wait(), .stdout = stdout.toOwnedSlice(), .stderr = stderr.toOwnedSlice(), }; } fn waitWindows(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } try self.waitUnwrappedWindows(); return self.term.?; } fn waitPosix(self: *ChildProcess) !Term { if (self.term) |term| { self.cleanupStreams(); return term; } self.waitUnwrapped(); return self.term.?; } pub fn deinit(self: *ChildProcess) void { self.allocator.destroy(self); } fn waitUnwrappedWindows(self: *ChildProcess) !void { const result = windows.WaitForSingleObjectEx(self.handle, windows.INFINITE, false); self.term = @as(SpawnError!Term, x: { var exit_code: windows.DWORD = undefined; if (windows.kernel32.GetExitCodeProcess(self.handle, &exit_code) == 0) { break :x Term{ .Unknown = 0 }; } else { break :x Term{ .Exited = exit_code }; } }); os.close(self.handle); os.close(self.thread_handle); self.cleanupStreams(); return result; } fn waitUnwrapped(self: *ChildProcess) void { const status = os.waitpid(self.pid, 0).status; self.cleanupStreams(); self.handleWaitResult(status); } fn handleWaitResult(self: *ChildProcess, status: u32) void { self.term = self.cleanupAfterWait(status); } fn cleanupStreams(self: *ChildProcess) void { if (self.stdin) |*stdin| { stdin.close(); self.stdin = null; } if (self.stdout) |*stdout| { stdout.close(); self.stdout = null; } if (self.stderr) |*stderr| { stderr.close(); self.stderr = null; } } fn cleanupAfterWait(self: *ChildProcess, status: u32) !Term { defer destroyPipe(self.err_pipe); if (builtin.os.tag == .linux) { var fd = [1]std.os.pollfd{std.os.pollfd{ .fd = self.err_pipe[0], .events = std.os.POLLIN, .revents = undefined, }}; // Check if the eventfd buffer stores a non-zero value by polling // it, that's the error code returned by the child process. _ = std.os.poll(&fd, 0) catch unreachable; // According to eventfd(2) the descriptro is readable if the counter // has a value greater than 0 if ((fd[0].revents & std.os.POLLIN) != 0) { const err_int = try readIntFd(self.err_pipe[0]); return @errSetCast(SpawnError, @intToError(err_int)); } } else { // Write maxInt(ErrInt) to the write end of the err_pipe. This is after // waitpid, so this write is guaranteed to be after the child // pid potentially wrote an error. This way we can do a blocking // read on the error pipe and either get maxInt(ErrInt) (no error) or // an error code. try writeIntFd(self.err_pipe[1], maxInt(ErrInt)); const err_int = try readIntFd(self.err_pipe[0]); // Here we potentially return the fork child's error from the parent // pid. if (err_int != maxInt(ErrInt)) { return @errSetCast(SpawnError, @intToError(err_int)); } } return statusToTerm(status); } fn statusToTerm(status: u32) Term { return if (os.WIFEXITED(status)) Term{ .Exited = os.WEXITSTATUS(status) } else if (os.WIFSIGNALED(status)) Term{ .Signal = os.WTERMSIG(status) } else if (os.WIFSTOPPED(status)) Term{ .Stopped = os.WSTOPSIG(status) } else Term{ .Unknown = status }; } fn spawnPosix(self: *ChildProcess) SpawnError!void { const pipe_flags = if (io.is_async) os.O_NONBLOCK else 0; const stdin_pipe = if (self.stdin_behavior == StdIo.Pipe) try os.pipe2(pipe_flags) else undefined; errdefer if (self.stdin_behavior == StdIo.Pipe) { destroyPipe(stdin_pipe); }; const stdout_pipe = if (self.stdout_behavior == StdIo.Pipe) try os.pipe2(pipe_flags) else undefined; errdefer if (self.stdout_behavior == StdIo.Pipe) { destroyPipe(stdout_pipe); }; const stderr_pipe = if (self.stderr_behavior == StdIo.Pipe) try os.pipe2(pipe_flags) else undefined; errdefer if (self.stderr_behavior == StdIo.Pipe) { destroyPipe(stderr_pipe); }; const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const dev_null_fd = if (any_ignore) os.openZ("/dev/null", os.O_RDWR, 0) catch |err| switch (err) { error.PathAlreadyExists => unreachable, error.NoSpaceLeft => unreachable, error.FileTooBig => unreachable, error.DeviceBusy => unreachable, error.FileLocksNotSupported => unreachable, error.BadPathName => unreachable, // Windows-only error.WouldBlock => unreachable, else => |e| return e, } else undefined; defer { if (any_ignore) os.close(dev_null_fd); } var arena_allocator = std.heap.ArenaAllocator.init(self.allocator); defer arena_allocator.deinit(); const arena = &arena_allocator.allocator; // The POSIX standard does not allow malloc() between fork() and execve(), // and `self.allocator` may be a libc allocator. // I have personally observed the child process deadlocking when it tries // to call malloc() due to a heap allocation between fork() and execve(), // in musl v1.1.24. // Additionally, we want to reduce the number of possible ways things // can fail between fork() and execve(). // Therefore, we do all the allocation for the execve() before the fork(). // This means we must do the null-termination of argv and env vars here. const argv_buf = try arena.allocSentinel(?[*:0]u8, self.argv.len, null); for (self.argv) |arg, i| argv_buf[i] = (try arena.dupeZ(u8, arg)).ptr; const envp = m: { if (self.env_map) |env_map| { const envp_buf = try createNullDelimitedEnvMap(arena, env_map); break :m envp_buf.ptr; } else if (std.builtin.link_libc) { break :m std.c.environ; } else if (std.builtin.output_mode == .Exe) { // Then we have Zig start code and this works. // TODO type-safety for null-termination of `os.environ`. break :m @ptrCast([*:null]?[*:0]u8, os.environ.ptr); } else { // TODO come up with a solution for this. @compileError("missing std lib enhancement: ChildProcess implementation has no way to collect the environment variables to forward to the child process"); } }; // This pipe is used to communicate errors between the time of fork // and execve from the child process to the parent process. const err_pipe = blk: { if (builtin.os.tag == .linux) { const fd = try os.eventfd(0, os.EFD_CLOEXEC); // There's no distinction between the readable and the writeable // end with eventfd break :blk [2]os.fd_t{ fd, fd }; } else { break :blk try os.pipe2(os.O_CLOEXEC); } }; errdefer destroyPipe(err_pipe); const pid_result = try os.fork(); if (pid_result == 0) { // we are the child setUpChildIo(self.stdin_behavior, stdin_pipe[0], os.STDIN_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stdout_behavior, stdout_pipe[1], os.STDOUT_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); setUpChildIo(self.stderr_behavior, stderr_pipe[1], os.STDERR_FILENO, dev_null_fd) catch |err| forkChildErrReport(err_pipe[1], err); if (self.stdin_behavior == .Pipe) { os.close(stdin_pipe[0]); os.close(stdin_pipe[1]); } if (self.stdout_behavior == .Pipe) { os.close(stdout_pipe[0]); os.close(stdout_pipe[1]); } if (self.stderr_behavior == .Pipe) { os.close(stderr_pipe[0]); os.close(stderr_pipe[1]); } if (self.cwd_dir) |cwd| { os.fchdir(cwd.fd) catch |err| forkChildErrReport(err_pipe[1], err); } else if (self.cwd) |cwd| { os.chdir(cwd) catch |err| forkChildErrReport(err_pipe[1], err); } if (self.gid) |gid| { os.setregid(gid, gid) catch |err| forkChildErrReport(err_pipe[1], err); } if (self.uid) |uid| { os.setreuid(uid, uid) catch |err| forkChildErrReport(err_pipe[1], err); } const err = switch (self.expand_arg0) { .expand => os.execvpeZ_expandArg0(.expand, argv_buf.ptr[0].?, argv_buf.ptr, envp), .no_expand => os.execvpeZ_expandArg0(.no_expand, argv_buf.ptr[0].?, argv_buf.ptr, envp), }; forkChildErrReport(err_pipe[1], err); } // we are the parent const pid = @intCast(i32, pid_result); if (self.stdin_behavior == StdIo.Pipe) { self.stdin = File{ .handle = stdin_pipe[1] }; } else { self.stdin = null; } if (self.stdout_behavior == StdIo.Pipe) { self.stdout = File{ .handle = stdout_pipe[0] }; } else { self.stdout = null; } if (self.stderr_behavior == StdIo.Pipe) { self.stderr = File{ .handle = stderr_pipe[0] }; } else { self.stderr = null; } self.pid = pid; self.err_pipe = err_pipe; self.term = null; if (self.stdin_behavior == StdIo.Pipe) { os.close(stdin_pipe[0]); } if (self.stdout_behavior == StdIo.Pipe) { os.close(stdout_pipe[1]); } if (self.stderr_behavior == StdIo.Pipe) { os.close(stderr_pipe[1]); } } fn spawnWindows(self: *ChildProcess) SpawnError!void { const saAttr = windows.SECURITY_ATTRIBUTES{ .nLength = @sizeOf(windows.SECURITY_ATTRIBUTES), .bInheritHandle = windows.TRUE, .lpSecurityDescriptor = null, }; const any_ignore = (self.stdin_behavior == StdIo.Ignore or self.stdout_behavior == StdIo.Ignore or self.stderr_behavior == StdIo.Ignore); const nul_handle = if (any_ignore) // "\Device\Null" or "\??\NUL" windows.OpenFile(&[_]u16{ '\\', 'D', 'e', 'v', 'i', 'c', 'e', '\\', 'N', 'u', 'l', 'l' }, .{ .access_mask = windows.GENERIC_READ | windows.SYNCHRONIZE, .share_access = windows.FILE_SHARE_READ, .creation = windows.OPEN_EXISTING, .io_mode = .blocking, }) catch |err| switch (err) { error.PathAlreadyExists => unreachable, // not possible for "NUL" error.PipeBusy => unreachable, // not possible for "NUL" error.FileNotFound => unreachable, // not possible for "NUL" error.AccessDenied => unreachable, // not possible for "NUL" error.NameTooLong => unreachable, // not possible for "NUL" error.WouldBlock => unreachable, // not possible for "NUL" else => |e| return e, } else undefined; defer { if (any_ignore) os.close(nul_handle); } if (any_ignore) { try windows.SetHandleInformation(nul_handle, windows.HANDLE_FLAG_INHERIT, 0); } var g_hChildStd_IN_Rd: ?windows.HANDLE = null; var g_hChildStd_IN_Wr: ?windows.HANDLE = null; switch (self.stdin_behavior) { StdIo.Pipe => { try windowsMakePipeIn(&g_hChildStd_IN_Rd, &g_hChildStd_IN_Wr, &saAttr); }, StdIo.Ignore => { g_hChildStd_IN_Rd = nul_handle; }, StdIo.Inherit => { g_hChildStd_IN_Rd = windows.GetStdHandle(windows.STD_INPUT_HANDLE) catch null; }, StdIo.Close => { g_hChildStd_IN_Rd = null; }, } errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_IN_Rd, g_hChildStd_IN_Wr); }; var g_hChildStd_OUT_Rd: ?windows.HANDLE = null; var g_hChildStd_OUT_Wr: ?windows.HANDLE = null; switch (self.stdout_behavior) { StdIo.Pipe => { try windowsMakePipeOut(&g_hChildStd_OUT_Rd, &g_hChildStd_OUT_Wr, &saAttr); }, StdIo.Ignore => { g_hChildStd_OUT_Wr = nul_handle; }, StdIo.Inherit => { g_hChildStd_OUT_Wr = windows.GetStdHandle(windows.STD_OUTPUT_HANDLE) catch null; }, StdIo.Close => { g_hChildStd_OUT_Wr = null; }, } errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_OUT_Rd, g_hChildStd_OUT_Wr); }; var g_hChildStd_ERR_Rd: ?windows.HANDLE = null; var g_hChildStd_ERR_Wr: ?windows.HANDLE = null; switch (self.stderr_behavior) { StdIo.Pipe => { try windowsMakePipeOut(&g_hChildStd_ERR_Rd, &g_hChildStd_ERR_Wr, &saAttr); }, StdIo.Ignore => { g_hChildStd_ERR_Wr = nul_handle; }, StdIo.Inherit => { g_hChildStd_ERR_Wr = windows.GetStdHandle(windows.STD_ERROR_HANDLE) catch null; }, StdIo.Close => { g_hChildStd_ERR_Wr = null; }, } errdefer if (self.stdin_behavior == StdIo.Pipe) { windowsDestroyPipe(g_hChildStd_ERR_Rd, g_hChildStd_ERR_Wr); }; const cmd_line = try windowsCreateCommandLine(self.allocator, self.argv); defer self.allocator.free(cmd_line); var siStartInfo = windows.STARTUPINFOW{ .cb = @sizeOf(windows.STARTUPINFOW), .hStdError = g_hChildStd_ERR_Wr, .hStdOutput = g_hChildStd_OUT_Wr, .hStdInput = g_hChildStd_IN_Rd, .dwFlags = windows.STARTF_USESTDHANDLES, .lpReserved = null, .lpDesktop = null, .lpTitle = null, .dwX = 0, .dwY = 0, .dwXSize = 0, .dwYSize = 0, .dwXCountChars = 0, .dwYCountChars = 0, .dwFillAttribute = 0, .wShowWindow = 0, .cbReserved2 = 0, .lpReserved2 = null, }; var piProcInfo: windows.PROCESS_INFORMATION = undefined; const cwd_w = if (self.cwd) |cwd| try unicode.utf8ToUtf16LeWithNull(self.allocator, cwd) else null; defer if (cwd_w) |cwd| self.allocator.free(cwd); const cwd_w_ptr = if (cwd_w) |cwd| cwd.ptr else null; const maybe_envp_buf = if (self.env_map) |env_map| try createWindowsEnvBlock(self.allocator, env_map) else null; defer if (maybe_envp_buf) |envp_buf| self.allocator.free(envp_buf); const envp_ptr = if (maybe_envp_buf) |envp_buf| envp_buf.ptr else null; // the cwd set in ChildProcess is in effect when choosing the executable path // to match posix semantics const app_path = x: { if (self.cwd) |cwd| { const resolved = try fs.path.resolve(self.allocator, &[_][]const u8{ cwd, self.argv[0] }); defer self.allocator.free(resolved); break :x try cstr.addNullByte(self.allocator, resolved); } else { break :x try cstr.addNullByte(self.allocator, self.argv[0]); } }; defer self.allocator.free(app_path); const app_path_w = try unicode.utf8ToUtf16LeWithNull(self.allocator, app_path); defer self.allocator.free(app_path_w); const cmd_line_w = try unicode.utf8ToUtf16LeWithNull(self.allocator, cmd_line); defer self.allocator.free(cmd_line_w); windowsCreateProcess(app_path_w.ptr, cmd_line_w.ptr, envp_ptr, cwd_w_ptr, &siStartInfo, &piProcInfo) catch |no_path_err| { if (no_path_err != error.FileNotFound) return no_path_err; var free_path = true; const PATH = process.getEnvVarOwned(self.allocator, "PATH") catch |err| switch (err) { error.EnvironmentVariableNotFound => blk: { free_path = false; break :blk ""; }, else => |e| return e, }; defer if (free_path) self.allocator.free(PATH); var free_path_ext = true; const PATHEXT = process.getEnvVarOwned(self.allocator, "PATHEXT") catch |err| switch (err) { error.EnvironmentVariableNotFound => blk: { free_path_ext = false; break :blk ""; }, else => |e| return e, }; defer if (free_path_ext) self.allocator.free(PATHEXT); const app_name = self.argv[0]; var it = mem.tokenize(PATH, ";"); retry: while (it.next()) |search_path| { const path_no_ext = try fs.path.join(self.allocator, &[_][]const u8{ search_path, app_name }); defer self.allocator.free(path_no_ext); var ext_it = mem.tokenize(PATHEXT, ";"); while (ext_it.next()) |app_ext| { const joined_path = try mem.concat(self.allocator, u8, &[_][]const u8{ path_no_ext, app_ext }); defer self.allocator.free(joined_path); const joined_path_w = try unicode.utf8ToUtf16LeWithNull(self.allocator, joined_path); defer self.allocator.free(joined_path_w); if (windowsCreateProcess(joined_path_w.ptr, cmd_line_w.ptr, envp_ptr, cwd_w_ptr, &siStartInfo, &piProcInfo)) |_| { break :retry; } else |err| switch (err) { error.FileNotFound => continue, error.AccessDenied => continue, else => return err, } } } else { return no_path_err; // return the original error } }; if (g_hChildStd_IN_Wr) |h| { self.stdin = File{ .handle = h }; } else { self.stdin = null; } if (g_hChildStd_OUT_Rd) |h| { self.stdout = File{ .handle = h }; } else { self.stdout = null; } if (g_hChildStd_ERR_Rd) |h| { self.stderr = File{ .handle = h }; } else { self.stderr = null; } self.handle = piProcInfo.hProcess; self.thread_handle = piProcInfo.hThread; self.term = null; if (self.stdin_behavior == StdIo.Pipe) { os.close(g_hChildStd_IN_Rd.?); } if (self.stderr_behavior == StdIo.Pipe) { os.close(g_hChildStd_ERR_Wr.?); } if (self.stdout_behavior == StdIo.Pipe) { os.close(g_hChildStd_OUT_Wr.?); } } fn setUpChildIo(stdio: StdIo, pipe_fd: i32, std_fileno: i32, dev_null_fd: i32) !void { switch (stdio) { .Pipe => try os.dup2(pipe_fd, std_fileno), .Close => os.close(std_fileno), .Inherit => {}, .Ignore => try os.dup2(dev_null_fd, std_fileno), } } }; fn windowsCreateProcess(app_name: [*:0]u16, cmd_line: [*:0]u16, envp_ptr: ?[*]u16, cwd_ptr: ?[*:0]u16, lpStartupInfo: *windows.STARTUPINFOW, lpProcessInformation: *windows.PROCESS_INFORMATION) !void { // TODO the docs for environment pointer say: // > A pointer to the environment block for the new process. If this parameter // > is NULL, the new process uses the environment of the calling process. // > ... // > An environment block can contain either Unicode or ANSI characters. If // > the environment block pointed to by lpEnvironment contains Unicode // > characters, be sure that dwCreationFlags includes CREATE_UNICODE_ENVIRONMENT. // > If this parameter is NULL and the environment block of the parent process // > contains Unicode characters, you must also ensure that dwCreationFlags // > includes CREATE_UNICODE_ENVIRONMENT. // This seems to imply that we have to somehow know whether our process parent passed // CREATE_UNICODE_ENVIRONMENT if we want to pass NULL for the environment parameter. // Since we do not know this information that would imply that we must not pass NULL // for the parameter. // However this would imply that programs compiled with -DUNICODE could not pass // environment variables to programs that were not, which seems unlikely. // More investigation is needed. return windows.CreateProcessW( app_name, cmd_line, null, null, windows.TRUE, windows.CREATE_UNICODE_ENVIRONMENT, @ptrCast(?*c_void, envp_ptr), cwd_ptr, lpStartupInfo, lpProcessInformation, ); } /// Caller must dealloc. fn windowsCreateCommandLine(allocator: *mem.Allocator, argv: []const []const u8) ![:0]u8 { var buf = std.ArrayList(u8).init(allocator); defer buf.deinit(); for (argv) |arg, arg_i| { if (arg_i != 0) try buf.append(' '); if (mem.indexOfAny(u8, arg, " \t\n\"") == null) { try buf.appendSlice(arg); continue; } try buf.append('"'); var backslash_count: usize = 0; for (arg) |byte| { switch (byte) { '\\' => backslash_count += 1, '"' => { try buf.appendNTimes('\\', backslash_count * 2 + 1); try buf.append('"'); backslash_count = 0; }, else => { try buf.appendNTimes('\\', backslash_count); try buf.append(byte); backslash_count = 0; }, } } try buf.appendNTimes('\\', backslash_count * 2); try buf.append('"'); } return buf.toOwnedSliceSentinel(0); } fn windowsDestroyPipe(rd: ?windows.HANDLE, wr: ?windows.HANDLE) void { if (rd) |h| os.close(h); if (wr) |h| os.close(h); } fn windowsMakePipeIn(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const windows.SECURITY_ATTRIBUTES) !void { var rd_h: windows.HANDLE = undefined; var wr_h: windows.HANDLE = undefined; try windows.CreatePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windows.SetHandleInformation(wr_h, windows.HANDLE_FLAG_INHERIT, 0); rd.* = rd_h; wr.* = wr_h; } fn windowsMakePipeOut(rd: *?windows.HANDLE, wr: *?windows.HANDLE, sattr: *const windows.SECURITY_ATTRIBUTES) !void { var rd_h: windows.HANDLE = undefined; var wr_h: windows.HANDLE = undefined; try windows.CreatePipe(&rd_h, &wr_h, sattr); errdefer windowsDestroyPipe(rd_h, wr_h); try windows.SetHandleInformation(rd_h, windows.HANDLE_FLAG_INHERIT, 0); rd.* = rd_h; wr.* = wr_h; } fn destroyPipe(pipe: [2]os.fd_t) void { os.close(pipe[0]); if (pipe[0] != pipe[1]) os.close(pipe[1]); } // Child of fork calls this to report an error to the fork parent. // Then the child exits. fn forkChildErrReport(fd: i32, err: ChildProcess.SpawnError) noreturn { writeIntFd(fd, @as(ErrInt, @errorToInt(err))) catch {}; // If we're linking libc, some naughty applications may have registered atexit handlers // which we really do not want to run in the fork child. I caught LLVM doing this and // it caused a deadlock instead of doing an exit syscall. In the words of Avril Lavigne, // "Why'd you have to go and make things so complicated?" if (builtin.link_libc) { // The _exit(2) function does nothing but make the exit syscall, unlike exit(3) std.c._exit(1); } os.exit(1); } const ErrInt = std.meta.Int(.unsigned, @sizeOf(anyerror) * 8); fn writeIntFd(fd: i32, value: ErrInt) !void { const file = File{ .handle = fd, .capable_io_mode = .blocking, .intended_io_mode = .blocking, }; file.writer().writeIntNative(u64, @intCast(u64, value)) catch return error.SystemResources; } fn readIntFd(fd: i32) !ErrInt { const file = File{ .handle = fd, .capable_io_mode = .blocking, .intended_io_mode = .blocking, }; return @intCast(ErrInt, file.reader().readIntNative(u64) catch return error.SystemResources); } /// Caller must free result. pub fn createWindowsEnvBlock(allocator: *mem.Allocator, env_map: *const BufMap) ![]u16 { // count bytes needed const max_chars_needed = x: { var max_chars_needed: usize = 4; // 4 for the final 4 null bytes var it = env_map.iterator(); while (it.next()) |pair| { // +1 for '=' // +1 for null byte max_chars_needed += pair.key.len + pair.value.len + 2; } break :x max_chars_needed; }; const result = try allocator.alloc(u16, max_chars_needed); errdefer allocator.free(result); var it = env_map.iterator(); var i: usize = 0; while (it.next()) |pair| { i += try unicode.utf8ToUtf16Le(result[i..], pair.key); result[i] = '='; i += 1; i += try unicode.utf8ToUtf16Le(result[i..], pair.value); result[i] = 0; i += 1; } result[i] = 0; i += 1; result[i] = 0; i += 1; result[i] = 0; i += 1; result[i] = 0; i += 1; return allocator.shrink(result, i); } pub fn createNullDelimitedEnvMap(arena: *mem.Allocator, env_map: *const std.BufMap) ![:null]?[*:0]u8 { const envp_count = env_map.count(); const envp_buf = try arena.allocSentinel(?[*:0]u8, envp_count, null); { var it = env_map.iterator(); var i: usize = 0; while (it.next()) |pair| : (i += 1) { const env_buf = try arena.allocSentinel(u8, pair.key.len + pair.value.len + 1, 0); mem.copy(u8, env_buf, pair.key); env_buf[pair.key.len] = '='; mem.copy(u8, env_buf[pair.key.len + 1 ..], pair.value); envp_buf[i] = env_buf.ptr; } assert(i == envp_count); } return envp_buf; } test "createNullDelimitedEnvMap" { const testing = std.testing; const allocator = testing.allocator; var envmap = BufMap.init(allocator); defer envmap.deinit(); try envmap.set("HOME", "/home/ifreund"); try envmap.set("WAYLAND_DISPLAY", "wayland-1"); try envmap.set("DISPLAY", ":1"); try envmap.set("DEBUGINFOD_URLS", " "); try envmap.set("XCURSOR_SIZE", "24"); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const environ = try createNullDelimitedEnvMap(&arena.allocator, &envmap); testing.expectEqual(@as(usize, 5), environ.len); inline for (.{ "HOME=/home/ifreund", "WAYLAND_DISPLAY=wayland-1", "DISPLAY=:1", "DEBUGINFOD_URLS= ", "XCURSOR_SIZE=24", }) |target| { for (environ) |variable| { if (mem.eql(u8, mem.span(variable orelse continue), target)) break; } else { testing.expect(false); // Environment variable not found } } }
https://raw.githubusercontent.com/dip-proto/zig/8f79f7e60937481fcf861c2941db02cbf449cdca/lib/std/child_process.zig
const std = @import("std"); const Handle = windows.HANDLE; const windows = std.os.windows; pub const bindings = @import("bindings.zig"); pub const WinDivert = struct { const Self = @This(); handle: Handle, pub fn open(filter: []const u8, layer: bindings.Layer, priority: i16, flags: bindings.Flags) bindings.OpenError!Self { return Self{ .handle = try bindings.open(filter, layer, priority, flags), }; } pub fn close(self: *Self) void { bindings.close(self.handle) catch {}; } pub fn receive(self: *Self, buffer: []u8) bindings.ReceiveError!bindings.ReceiveResult { return bindings.receive(self.handle, buffer); } pub fn send(self: *Self, buffer: []u8, address: bindings.Address) bindings.SendError!c_uint { return bindings.send(self.handle, buffer, address); } }; pub const parsePacket = bindings.parsePacket;
https://raw.githubusercontent.com/SuperAuguste/windivert-zig/4f0eb63fa8190b4ea097bc940483fcd3d09c2a2e/src/windivert.zig
const std = @import("std"); pub fn build(b: *std.build.Builder) void { const test_step = b.step("test", "dummy test step to pass CI checks"); _ = test_step; }
https://raw.githubusercontent.com/nektro/zig-git/103f4e419c35b88f802bb8234ece1c0a9aa40c03/build.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 lib = b.addStaticLibrary(.{ .name = "serializer", // 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/root.zig" }, .target = target, .optimize = optimize, }); // This declares intent for the library to be installed into the standard // location when the user invokes the "install" step (the default step when // running `zig build`). b.installArtifact(lib); const exe = b.addExecutable(.{ .name = "serializer", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const exe_options = b.addOptions(); exe.root_module.addOptions("build_options", exe_options); // exe.root_module.addImport("sdl", b.dependency("sdl", .{}).module("sdl")); // const duck = b.dependency("duck", .{ // .optimize = optimize, // .target = target, // }); // // for exe, lib, tests, etc. // exe.addModule("duck", duck.module("duck")); // 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 lib_unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/root.zig" }, .target = target, .optimize = optimize, }); const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const exe_unit_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const run_exe_unit_tests = b.addRunArtifact(exe_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_lib_unit_tests.step); test_step.dependOn(&run_exe_unit_tests.step); }
https://raw.githubusercontent.com/JustinBraben/zig-clipse/46c65b990772f16cbe7fc0cc614ddfb71b4aad99/serializer/build.zig
const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}) {}; const allocator = &gpa.allocator; const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); const file = try std.fs.cwd().openFile(args[1], .{ .read = true }); defer file.close(); const reader = file.reader(); const l = try reader.readUntilDelimiterAlloc(allocator, '\n', 10000); defer allocator.free(l); const ts = try std.fmt.parseUnsigned(u64, l, 10); var min: u64 = ts; var bus: u64 = 0; const line = try reader.readUntilDelimiterAlloc(allocator, '\n', 10000); defer allocator.free(line); var bs = std.mem.split(line, ","); while (bs.next()) |b| { if (b[0] == 'x') continue; const n = try std.fmt.parseUnsigned(u64, b, 10); const wait = (ts + n - 1) / n * n - ts; if (wait < min) { min = wait; bus = n; } } std.debug.print("{}\n", .{bus * min}); }
https://raw.githubusercontent.com/jeltz/advent/c2a5671a9db86e73aa12313badb5fe4dfd344847/2020/13/13a.zig
// // Remember how a function with 'suspend' is async and calling an // async function without the 'async' keyword makes the CALLING // function async? // // fn fooThatMightSuspend(maybe: bool) void { // if (maybe) suspend {} // } // // fn bar() void { // fooThatMightSuspend(true); // Now bar() is async! // } // // But if you KNOW the function won't suspend, you can make a // promise to the compiler with the 'nosuspend' keyword: // // fn bar() void { // nosuspend fooThatMightSuspend(false); // } // // If the function does suspend and YOUR PROMISE TO THE COMPILER // IS BROKEN, the program will panic at runtime, which is // probably better than you deserve, you oathbreaker! >:-( // const print = @import("std").debug.print; pub fn main() void { // The main() function can not be async. But we know // getBeef() will not suspend with this particular // invocation. Please make this okay: var my_beef = getBeef(0); print("beef? {X}!\n", .{my_beef}); } fn getBeef(input: u32) u32 { if (input == 0xDEAD) { suspend {} } return 0xBEEF; } // // Going Deeper Into... // ...uNdeFiNEd beHAVi0r! // // We haven't discussed it yet, but runtime "safety" features // require some extra instructions in your compiled program. // Most of the time, you're going to want to keep these in. // // But in some programs, when data integrity is less important // than raw speed (some games, for example), you can compile // without these safety features. // // Instead of a safe panic when something goes wrong, your // program will now exhibit Undefined Behavior (UB), which simply // means that the Zig language does not (cannot) define what will // happen. The best case is that it will crash, but in the worst // case, it will continue to run with the wrong results and // corrupt your data or expose you to security risks. // // This program is a great way to explore UB. Once you get it // working, try calling the getBeef() function with the value // 0xDEAD so that it will invoke the 'suspend' keyword: // // getBeef(0xDEAD) // // Now when you run the program, it will panic and give you a // nice stack trace to help debug the problem. // // zig run exercises/090_async7.zig // thread 328 panic: async function called... // ... // // But see what happens when you turn off safety checks by using // ReleaseFast mode: // // zig run -O ReleaseFast exercises/090_async7.zig // beef? 0! // // This is the wrong result. On your computer, you may get a // different answer or it might crash! What exactly will happen // is UNDEFINED. Your computer is now like a wild animal, // reacting to bits and bytes of raw memory with the base // instincts of the CPU. It is both terrifying and exhilarating. //
https://raw.githubusercontent.com/BasixKOR/ziglings/b55e0127be63b041cda11fe93f6b0a25a08542ce/exercises/090_async7.zig
const std = @import("std"); const Pkg = std.build.Pkg; const Builder = std.build.Builder; const Mode = std.builtin.Mode; const CrossTarget = std.zig.CrossTarget; const pkg_bitset = Pkg { .name = "bitset", .source = .{.path = "bitset/bitset.zig"}, }; const pkg_libev = Pkg { .name = "ev", .source = .{.path = "src/lib.zig"}, .dependencies = if (USE_STAGE1) null else &.{pkg_bitset}, }; fn bin(b: *Builder, mode: *const Mode, target: *const CrossTarget, comptime source: []const[]const u8) void { inline for (source) |s| { const file = b.addExecutable(s, "examples/" ++ s ++ ".zig"); file.setBuildMode(mode.*); file.setTarget(target.*); file.addPackage(pkg_libev); file.linkLibC(); file.linkSystemLibrary("ev"); file.install(); } } const USE_STAGE1 = true; pub fn build(b: *Builder) !void { const mode = b.standardReleaseOptions(); const target = b.standardTargetOptions(.{}); b.use_stage1 = USE_STAGE1; // unit test const unit_test = b.addTest("main.zig"); unit_test.setBuildMode(mode); unit_test.setTarget(target); // lib const lib = b.addStaticLibrary("ev", "src/lib.zig"); lib.setBuildMode(mode); lib.addPackage(pkg_bitset); lib.linkLibC(); lib.install(); // bin, sync bin(b, &mode, &target, &.{"version", "stdin", "timer"}); // bin, async(not availabe in self-hosting compiler) if (USE_STAGE1) bin(b, &mode, &target, &.{"async_stdin", "async_timer"}); // bin, custom alloc bin(b, &mode, &target, &.{"stdin_alloc"}); }
https://raw.githubusercontent.com/zephyrchien/libev-zig/3c8e410ad010939bc8866b45c60afeecc7e3ce60/build.zig
//! Generic Stack Structure const std = @import("std"); const vm = @import("vm.zig"); pub const Error = error{ Overflow, Underflow, } || std.mem.Allocator.Error; const enable_checks: bool = false; /// Stack structure used for the runtime, like the evaluation stack and the /// call stack. Static stack size. pub fn Stack(comptime T: type) type { return struct { const Self = @This(); items: []T, head: usize = 0, pub fn init(allocator: std.mem.Allocator, size: usize) Self { const items = allocator.alloc(T, size) catch |err| { vm.errorHandle(err); unreachable; }; return Self{ .items = items, }; } pub fn deinit(self: *Self, allocator: std.mem.Allocator) void { allocator.free(self.items); } pub inline fn getFrame(self: *Self) usize { return self.head; } pub inline fn popFrame(self: *Self, frame: usize) void { while (self.head > frame) { _ = self.pop(); } } pub inline fn peekFrameOffset(self: *Self, frame: usize, offset: usize) *T { if (enable_checks) { if (frame + offset > self.head) { vm.errorHandle(Error.Overflow); unreachable; } } return &self.items[frame + offset]; } pub inline fn push(self: *Self, item: T) void { if (enable_checks) { if (self.head >= self.items.len) { vm.errorHandle(Error.Overflow); unreachable; } } self.items[self.head] = item; self.head += 1; } pub inline fn pop(self: *Self) T { if (enable_checks) { if (self.head == 0) { vm.errorHandle(Error.Underflow); unreachable; } } self.head -= 1; return self.items[self.head]; } pub inline fn peek(self: *Self) *T { if (enable_checks) { if (self.head == 0) { vm.errorHandle(Error.Underflow); unreachable; } } return &self.items[self.head - 1]; } }; }
https://raw.githubusercontent.com/N-Adkins/lang/cc8d9b92977262a37e1d90cdd6ad24079b369eaf/src/runtime/stack.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 ValueType = value_mod.ValueType; const vm_mod = @import("../vm.zig"); const VM = vm_mod.VM; const index = @import("index.zig").index; pub const WhereError = error{ invalid_type, negative_number, list_limit, }; fn runtimeError(comptime err: WhereError) WhereError!*Value { switch (err) { WhereError.invalid_type => print("Invalid type.\n", .{}), WhereError.negative_number => print("Cannot generate list from negative input.\n", .{}), WhereError.list_limit => print("Cannot generate a list longer than 10,085,382,816 elements.\n", .{}), } return err; } pub fn where(vm: *VM, x: *Value) WhereError!*Value { return switch (x.as) { .list => |list_x| if (list_x.len == 0) vm.initValue(.{ .int_list = &.{} }) else runtimeError(WhereError.invalid_type), .boolean_list => |bool_list_x| blk: { var list = std.ArrayList(*Value).init(vm.allocator); for (bool_list_x, 0..) |value, i| { if (value.as.boolean) list.append(vm.initValue(.{ .int = @intCast(i64, i) })) catch std.debug.panic("Failed to append item.", .{}); } break :blk vm.initValue(.{ .int_list = list.toOwnedSlice() catch std.debug.panic("Failed to create list.", .{}) }); }, .int_list => |int_list_x| blk: { var len: i64 = 0; for (int_list_x) |value| { if (value.as.int < 0) return runtimeError(WhereError.negative_number); len = std.math.add(i64, len, value.as.int) catch return runtimeError(WhereError.list_limit); } const list = vm.allocator.alloc(*Value, @intCast(usize, len)) catch return runtimeError(WhereError.list_limit); var i: usize = 0; for (int_list_x, 0..) |value, j| { if (value.as.int > 0) { const v = vm.initValueWithRefCount(0, .{ .int = @intCast(i64, j) }); for (i..i + @intCast(usize, value.as.int)) |idx| list[idx] = v.ref(); i += @intCast(usize, value.as.int); } } break :blk vm.initValue(.{ .int_list = list }); }, .dictionary => |dict_x| blk: { const indices = try where(vm, dict_x.values); defer indices.deref(vm.allocator); break :blk index(vm, dict_x.keys, indices) catch runtimeError(WhereError.invalid_type); }, else => runtimeError(WhereError.invalid_type), }; }
https://raw.githubusercontent.com/dstrachan/openk/0a739d96593fe3e1a7ebe54e5b82e2a69f64302a/src/verbs/where.zig
const std = @import("std"); const string = @import("./vm.zig").string; const size16 = @import("./vm.zig").size16; const size32 = @import("./vm.zig").size32; const naming = @import("./vm.zig").naming; const strings = @import("./vm.zig").strings; const vm_stash = @import("./vm.zig").vm_stash; const byte = @import("./type.zig").byte; const int = @import("./type.zig").int; const long = @import("./type.zig").long; const float = @import("./type.zig").float; const double = @import("./type.zig").double; const boolean = @import("./type.zig").boolean; const Value = @import("./type.zig").Value; const Class = @import("./type.zig").Class; const Method = @import("./type.zig").Method; const Reference = @import("./type.zig").Reference; const NULL = @import("./type.zig").NULL; const TRUE = @import("./type.zig").TRUE; const FALSE = @import("./type.zig").FALSE; const ObjectRef = @import("./type.zig").ObjectRef; const ArrayRef = @import("./type.zig").ArrayRef; const JavaLangString = @import("./type.zig").JavaLangString; const JavaLangClass = @import("./type.zig").JavaLangClass; const JavaLangClassLoader = @import("./type.zig").JavaLangClassLoader; const JavaLangThrowable = @import("./type.zig").JavaLangThrowable; const JavaLangThread = @import("./type.zig").JavaLangThread; const JavaLangReflectConstructor = @import("./type.zig").JavaLangReflectConstructor; const isPrimitiveType = @import("./type.zig").isPrimitiveType; const defaultValue = @import("./type.zig").defaultValue; const resolveClass = @import("./method_area.zig").resolveClass; const assignableFrom = @import("./method_area.zig").assignableFrom; const Thread = @import("./engine.zig").Thread; const Frame = @import("./engine.zig").Frame; const Context = @import("./engine.zig").Context; const Result = @import("./engine.zig").Result; const newObject = @import("./heap.zig").newObject; const newArray = @import("./heap.zig").newArray; const getJavaLangClass = @import("./heap.zig").getJavaLangClass; const getJavaLangString = @import("./heap.zig").getJavaLangString; const newJavaLangThread = @import("./heap.zig").newJavaLangThread; const newJavaLangReflectField = @import("./heap.zig").newJavaLangReflectField; const newJavaLangReflectConstructor = @import("./heap.zig").newJavaLangReflectConstructor; const setInstanceVar = @import("./heap.zig").setInstanceVar; const getInstanceVar = @import("./heap.zig").getInstanceVar; const setStaticVar = @import("./heap.zig").setStaticVar; const getStaticVar = @import("./heap.zig").getStaticVar; const toString = @import("./heap.zig").toString; const internString = @import("./heap.zig").internString; test "call" { var args = [_]Value{.{ .long = 5000 }}; _ = call("java/lang/Thread", "sleep(J)V", &args); } fn varargs(comptime T: type, args: []Value) T { var tuple: T = undefined; inline for (std.meta.fields(T), 0..) |_, i| { tuple[i] = args[i]; } return tuple; } // TODO: optimise this!! pub fn call(ctx: Context, args: []const Value) Result { const class = ctx.c.name; const name = ctx.m.name; const descriptor = ctx.m.descriptor; const qualifier = strings.concat(&[_]string{ class, ".", name, descriptor }); defer vm_stash.free(qualifier); if (strings.equals(qualifier, "java/lang/System.registerNatives()V")) { java_lang_System.registerNatives(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/System.setIn0(Ljava/io/InputStream;)V")) { java_lang_System.setIn0(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/System.setOut0(Ljava/io/PrintStream;)V")) { java_lang_System.setOut0(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/System.setErr0(Ljava/io/PrintStream;)V")) { java_lang_System.setErr0(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/System.currentTimeMillis()J")) { return .{ .@"return" = .{ .long = java_lang_System.currentTimeMillis(ctx) } }; } if (strings.equals(qualifier, "java/lang/System.nanoTime()J")) { return .{ .@"return" = .{ .long = java_lang_System.nanoTime(ctx) } }; } if (strings.equals(qualifier, "java/lang/System.arraycopy(Ljava/lang/Object;ILjava/lang/Object;II)V")) { java_lang_System.arraycopy(ctx, args[0].ref, args[1].int, args[2].ref, args[3].int, args[4].int); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/System.identityHashCode(Ljava/lang/Object;)I")) { return .{ .@"return" = .{ .int = java_lang_System.identityHashCode(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/System.initProperties(Ljava/util/Properties;)Ljava/util/Properties;")) { return .{ .@"return" = .{ .ref = java_lang_System.initProperties(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/System.mapLibraryName(Ljava/lang/String;)Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_lang_System.mapLibraryName(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Object.registerNatives()V")) { java_lang_Object.registerNatives(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Object.hashCode()I")) { return .{ .@"return" = .{ .int = java_lang_Object.hashCode(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Object.getClass()Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Object.getClass(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Object.clone()Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = java_lang_Object.clone(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Object.notifyAll()V")) { java_lang_Object.notifyAll(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Object.wait(J)V")) { java_lang_Object.wait(ctx, args[0].ref, args[1].long); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Object.notify()V")) { java_lang_Object.notifyAll(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Class.registerNatives()V")) { java_lang_Class.registerNatives(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Class.getPrimitiveClass(Ljava/lang/String;)Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getPrimitiveClass(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.desiredAssertionStatus0(Ljava/lang/Class;)Z")) { return .{ .@"return" = .{ .boolean = java_lang_Class.desiredAssertionStatus0(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getDeclaredFields0(Z)[Ljava/lang/reflect/Field;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getDeclaredFields0(ctx, args[0].ref, args[1].as(boolean).boolean) } }; } if (strings.equals(qualifier, "java/lang/Class.isPrimitive()Z")) { return .{ .@"return" = .{ .boolean = java_lang_Class.isPrimitive(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.isAssignableFrom(Ljava/lang/Class;)Z")) { return .{ .@"return" = .{ .boolean = java_lang_Class.isAssignableFrom(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getName0()Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getName0(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.forName0(Ljava/lang/String;ZLjava/lang/ClassLoader;Ljava/lang/Class;)Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Class.forName0(ctx, args[0].ref, args[1].as(boolean).boolean, args[2].ref, args[3].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.isInterface()Z")) { return .{ .@"return" = .{ .boolean = java_lang_Class.isInterface(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getDeclaredConstructors0(Z)[Ljava/lang/reflect/Constructor;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getDeclaredConstructors0(ctx, args[0].ref, args[1].as(boolean).boolean) } }; } if (strings.equals(qualifier, "java/lang/Class.getModifiers()I")) { return .{ .@"return" = .{ .int = java_lang_Class.getModifiers(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getSuperclass()Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getSuperclass(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.isArray()Z")) { return .{ .@"return" = .{ .boolean = java_lang_Class.isArray(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getComponentType()Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getComponentType(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getEnclosingMethod0()[Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getEnclosingMethod0(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.getDeclaringClass0()Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Class.getDeclaringClass0(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Class.forName0(Ljava/lang/String;ZLjava/lang/ClassLoader;Ljava/lang/Class;)Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_Class.forName0(ctx, args[0].ref, args[1].as(boolean).boolean, args[2].ref, args[3].ref) } }; } if (strings.equals(qualifier, "java/lang/ClassLoader.registerNatives()V")) { java_lang_ClassLoader.registerNatives(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/ClassLoader.findBuiltinLib(Ljava/lang/String;)Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_lang_ClassLoader.findBuiltinLib(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/ClassLoader$NativeLibrary.load(Ljava/lang/String;Z)V")) { java_lang_ClassLoader.NativeLibrary_load(ctx, args[0].ref, args[1].ref, args[2].as(boolean).boolean); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/ClassLoader.findLoadedClass0(Ljava/lang/String;)Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_ClassLoader.findLoadedClass0(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/lang/ClassLoader.defineClass1(Ljava/lang/String;[BIILjava/security/ProtectionDomain;Ljava/lang/String;)Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_ClassLoader.defineClass1(ctx, args[0].ref, args[1].ref, args[2].ref, args[3].int, args[4].int, args[5].ref, args[6].ref) } }; } if (strings.equals(qualifier, "java/lang/ClassLoader.findBootstrapClass(Ljava/lang/String;)Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = java_lang_ClassLoader.findBootstrapClass(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/lang/Package.getSystemPackage0(Ljava/lang/String;)Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_lang_Package.getSystemPackage0(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/String.intern()Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_lang_String.intern(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Float.floatToRawIntBits(F)I")) { return .{ .@"return" = .{ .int = java_lang_Float.floatToRawIntBits(ctx, args[0].float) } }; } if (strings.equals(qualifier, "java/lang/Float.intBitsToFloat(I)F")) { return .{ .@"return" = .{ .float = java_lang_Float.intBitsToFloat(ctx, args[0].int) } }; } if (strings.equals(qualifier, "java/lang/Double.doubleToRawLongBits(D)J")) { return .{ .@"return" = .{ .long = java_lang_Double.doubleToRawLongBits(ctx, args[0].double) } }; } if (strings.equals(qualifier, "java/lang/Double.longBitsToDouble(J)D")) { return .{ .@"return" = .{ .double = java_lang_Double.longBitsToDouble(ctx, args[0].long) } }; } if (strings.equals(qualifier, "java/lang/Thread.registerNatives()V")) { java_lang_Thread.registerNatives(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Thread.currentThread()Ljava/lang/Thread;")) { return .{ .@"return" = .{ .ref = java_lang_Thread.currentThread(ctx) } }; } if (strings.equals(qualifier, "java/lang/Thread.setPriority0(I)V")) { java_lang_Thread.setPriority0(ctx, args[0].ref, args[1].int); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Thread.isAlive()Z")) { return .{ .@"return" = .{ .boolean = java_lang_Thread.isAlive(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Thread.start0()V")) { java_lang_Thread.start0(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Thread.sleep(J)V")) { java_lang_Thread.sleep(ctx, args[0].long); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Thread.interrupt0()V")) { java_lang_Thread.interrupt0(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/lang/Thread.isInterrupted(Z)Z")) { return .{ .@"return" = .{ .boolean = java_lang_Thread.isInterrupted(ctx, args[0].ref, args[1].as(boolean).boolean) } }; } if (strings.equals(qualifier, "java/lang/Throwable.getStackTraceDepth()I")) { return .{ .@"return" = .{ .int = java_lang_Throwable.getStackTraceDepth(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/Throwable.fillInStackTrace(I)Ljava/lang/Throwable;")) { return .{ .@"return" = .{ .ref = java_lang_Throwable.fillInStackTrace(ctx, args[0].ref, args[1].int) } }; } if (strings.equals(qualifier, "java/lang/Throwable.getStackTraceElement(I)Ljava/lang/StackTraceElement;")) { return .{ .@"return" = .{ .ref = java_lang_Throwable.getStackTraceElement(ctx, args[0].ref, args[1].int) } }; } if (strings.equals(qualifier, "java/lang/Runtime.availableProcessors()I")) { return .{ .@"return" = .{ .int = java_lang_Runtime.availableProcessors(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/lang/StrictMath.pow(DD)D")) { return .{ .@"return" = .{ .double = java_lang_StrictMath.pow(ctx, args[0].double, args[1].double) } }; } if (strings.equals(qualifier, "java/security/AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;)Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = java_security_AccessController.doPrivileged(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/security/AccessController.doPrivileged(Ljava/security/PrivilegedAction;)Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = java_security_AccessController.doPrivileged(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/security/AccessController.getStackAccessControlContext()Ljava/security/AccessControlContext;")) { return .{ .@"return" = .{ .ref = java_security_AccessController.getStackAccessControlContext(ctx) } }; } if (strings.equals(qualifier, "java/security/AccessController.doPrivileged(Ljava/security/PrivilegedExceptionAction;Ljava/security/AccessControlContext;)Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = java_security_AccessController.doPrivilegedContext(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/lang/reflect/Array.newArray(Ljava/lang/Class;I)Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = java_lang_reflect_Array.newArray(ctx, args[0].ref, args[1].int) } }; } if (strings.equals(qualifier, "sun/misc/VM.initialize()V")) { sun_misc_VM.initialize(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "sun/misc/Unsafe.registerNatives()V")) { sun_misc_Unsafe.registerNatives(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "sun/misc/Unsafe.arrayBaseOffset(Ljava/lang/Class;)I")) { return .{ .@"return" = .{ .int = sun_misc_Unsafe.arrayBaseOffset(ctx, args[0].ref, args[0].ref) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.arrayIndexScale(Ljava/lang/Class;)I")) { return .{ .@"return" = .{ .int = sun_misc_Unsafe.arrayIndexScale(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.addressSize()I")) { return .{ .@"return" = .{ .int = sun_misc_Unsafe.addressSize(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.objectFieldOffset(Ljava/lang/reflect/Field;)J")) { return .{ .@"return" = .{ .long = sun_misc_Unsafe.objectFieldOffset(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.compareAndSwapObject(Ljava/lang/Object;JLjava/lang/Object;Ljava/lang/Object;)Z")) { return .{ .@"return" = .{ .boolean = sun_misc_Unsafe.compareAndSwapObject(ctx, args[0].ref, args[1].ref, args[2].long, args[3].ref, args[4].ref) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.getIntVolatile(Ljava/lang/Object;J)I")) { return .{ .@"return" = .{ .int = sun_misc_Unsafe.getIntVolatile(ctx, args[0].ref, args[1].ref, args[2].long) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.getObjectVolatile(Ljava/lang/Object;J)Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = sun_misc_Unsafe.getObjectVolatile(ctx, args[0].ref, args[1].ref, args[2].long) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.putObjectVolatile(Ljava/lang/Object;JLjava/lang/Object;)V")) { sun_misc_Unsafe.putObjectVolatile(ctx, args[0].ref, args[1].ref, args[2].long, args[3].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "sun/misc/Unsafe.compareAndSwapInt(Ljava/lang/Object;JII)Z")) { return .{ .@"return" = .{ .boolean = sun_misc_Unsafe.compareAndSwapInt(ctx, args[0].ref, args[1].ref, args[2].long, args[3].int, args[4].int) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.compareAndSwapLong(Ljava/lang/Object;JJJ)Z")) { return .{ .@"return" = .{ .boolean = sun_misc_Unsafe.compareAndSwapLong(ctx, args[0].ref, args[1].ref, args[2].long, args[3].long, args[4].long) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.allocateMemory(J)J")) { return .{ .@"return" = .{ .long = sun_misc_Unsafe.allocateMemory(ctx, args[0].ref, args[1].long) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.putLong(JJ)V")) { sun_misc_Unsafe.putLong(ctx, args[0].ref, args[1].long, args[2].long); return .{ .@"return" = null }; } if (strings.equals(qualifier, "sun/misc/Unsafe.getByte(J)B")) { return .{ .@"return" = .{ .byte = sun_misc_Unsafe.getByte(ctx, args[0].ref, args[1].long) } }; } if (strings.equals(qualifier, "sun/misc/Unsafe.freeMemory(J)V")) { sun_misc_Unsafe.freeMemory(ctx, args[0].ref, args[1].long); return .{ .@"return" = null }; } if (strings.equals(qualifier, "sun/misc/Unsafe.ensureClassInitialized(Ljava/lang/Class;)V")) { sun_misc_Unsafe.ensureClassInitialized(ctx, args[0].ref, args[1].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "sun/reflect/Reflection.getCallerClass()Ljava/lang/Class;")) { return .{ .@"return" = .{ .ref = sun_reflect_Reflection.getCallerClass(ctx) } }; } if (strings.equals(qualifier, "sun/reflect/Reflection.getClassAccessFlags(Ljava/lang/Class;)I")) { return .{ .@"return" = .{ .int = sun_reflect_Reflection.getClassAccessFlags(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "sun/reflect/NativeConstructorAccessorImpl.newInstance0(Ljava/lang/reflect/Constructor;[Ljava/lang/Object;)Ljava/lang/Object;")) { return .{ .@"return" = .{ .ref = sun_reflect_NativeConstructorAccessorImpl.newInstance0(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "sun/misc/URLClassPath.getLookupCacheURLs(Ljava/lang/ClassLoader;)[Ljava/net/URL;")) { return .{ .@"return" = .{ .ref = sun_misc_URLClassPath.getLookupCacheURLs(ctx, args[0].ref) } }; } if (strings.equals(qualifier, "java/io/FileDescriptor.initIDs()V")) { java_io_FileDescriptor.initIDs(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/FileInputStream.initIDs()V")) { java_io_FileInputStream.initIDs(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/FileInputStream.open0(Ljava/lang/String;)V")) { java_io_FileInputStream.open0(ctx, args[0].ref, args[1].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/FileInputStream.readBytes([BII)I")) { return .{ .@"return" = .{ .int = java_io_FileInputStream.readBytes(ctx, args[0].ref, args[1].ref, args[2].int, args[3].int) } }; } if (strings.equals(qualifier, "java/io/FileInputStream.close0()V")) { java_io_FileInputStream.close0(ctx, args[0].ref); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/FileOutputStream.initIDs()V")) { java_io_FileOutputStream.initIDs(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/FileOutputStream.writeBytes([BIIZ)V")) { java_io_FileOutputStream.writeBytes(ctx, args[0].ref, args[1].ref, args[2].int, args[3].int, args[4].as(boolean).boolean); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/UnixFileSystem.initIDs()V")) { java_io_UnixFileSystem.initIDs(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/io/UnixFileSystem.canonicalize0(Ljava/lang/String;)Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_io_UnixFileSystem.canonicalize0(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/io/UnixFileSystem.getBooleanAttributes0(Ljava/io/File;)I")) { return .{ .@"return" = .{ .int = java_io_UnixFileSystem.getBooleanAttributes0(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/io/UnixFileSystem.getLength(Ljava/io/File;)J")) { return .{ .@"return" = .{ .long = java_io_UnixFileSystem.getLength(ctx, args[0].ref, args[1].ref) } }; } if (strings.equals(qualifier, "java/util/concurrent/atomic/AtomicLong.VMSupportsCS8()Z")) { return .{ .@"return" = .{ .boolean = java_util_concurrent_atomic_AtomicLong.VMSupportsCS8(ctx) } }; } if (strings.equals(qualifier, "java/util/zip/ZipFile.initIDs()V")) { java_util_zip_ZipFile.initIDs(ctx); return .{ .@"return" = null }; } if (strings.equals(qualifier, "java/util/TimeZone.getSystemTimeZoneID(Ljava/lang/String;)Ljava/lang/String;")) { return .{ .@"return" = .{ .ref = java_util_TimeZone.getSystemTimeZoneID(ctx, args[0].ref) } }; } std.debug.panic("Native method {s} not found", .{qualifier}); } const java_lang_System = struct { // private static void registers() pub fn registerNatives(ctx: Context) void { _ = ctx; } // private static void setIn0(InputStream is) pub fn setIn0(ctx: Context, is: ObjectRef) void { const class = resolveClass(ctx.c, "java/lang/System"); setStaticVar(class, "in", "Ljava/io/InputStream;", .{ .ref = is }); } // private static void setOut0(PrintStream ps) pub fn setOut0(ctx: Context, ps: ObjectRef) void { const class = resolveClass(ctx.c, "java/lang/System"); setStaticVar(class, "out", "Ljava/io/PrintStream;", .{ .ref = ps }); } // private static void setErr0(PrintStream ps) pub fn setErr0(ctx: Context, ps: ObjectRef) void { const class = resolveClass(ctx.c, "java/lang/System"); setStaticVar(class, "err", "Ljava/io/PrintStream;", .{ .ref = ps }); } // public static long currentTimeMillis() pub fn currentTimeMillis(ctx: Context) long { _ = ctx; return std.time.milliTimestamp(); } // public static long nanoTime() pub fn nanoTime(ctx: Context) long { _ = ctx; return @intCast(std.time.nanoTimestamp()); } // public static void arraycopy(Object fromArray, int fromIndex, Object toArray, int toIndex, int length) pub fn arraycopy(ctx: Context, src: ArrayRef, srcPos: int, dest: ArrayRef, destPos: int, length: int) void { if (!src.class().is_array or !dest.class().is_array) { return ctx.f.vm_throw("java/lang/ArrayStoreException"); } if (srcPos < 0 or destPos < 0 or srcPos + length > src.len() or destPos + length > dest.len()) { return ctx.f.vm_throw("java/lang/ArrayIndexOutOfBoundsException"); } for (0..@intCast(length)) |i| { var srcIndex: usize = @intCast(srcPos); var destIndex: usize = @intCast(destPos); dest.set(@intCast(destIndex + i), src.get(@intCast(srcIndex + i))); } } // public static int identityHashCode(Object object) pub fn identityHashCode(ctx: Context, object: Reference) int { _ = ctx; return object.object().header.hash_code; } // private static Properties initProperties(Properties properties) pub fn initProperties(ctx: Context, properties: ObjectRef) ObjectRef { const setProperty = properties.class().method("setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;", false); const args = vm_stash.make(Value, 3); defer vm_stash.free(args); args[0] = .{ .ref = properties }; const map = [_]string{ "java.version", "1.8.0_152-ea", "java.home", "", //currentPath, "java.specification.name", "Java Platform API Specification", "java.specification.version", "1.8", "java.specification.vendor", "Oracle Corporation", "java.vendor", "Oracle Corporation", "java.vendor.url", "http://java.oracle.com/", "java.vendor.url.bug", "http://bugreport.sun.com/bugreport/", "java.vm.name", "Zava 64-Bit VM", "java.vm.version", "1.0.0", "java.vm.vendor", "Chao Yang", "java.vm.info", "mixed mode", "java.vm.specification.name", "Java Virtual Machine Specification", "java.vm.specification.version", "1.8", "java.vm.specification.vendor", "Oracle Corporation", "java.runtime.name", "Java(TM) SE Runtime Environment", "java.runtime.version", "1.8.0_152-ea-b05", "java.class.version", "52.0", "java.class.path", "src/classes;jdk/classes", // app classloader path "java.io.tmpdir", "/var/tmp", //classpath, //TODO "java.library.path", "", //classpath, //TODO "java.ext.dirs", "", //TODO "java.endorsed.dirs", "", //classpath, //TODO "java.awt.graphicsenv", "sun.awt.CGraphicsEnvironment", "java.awt.printerjob", "sun.lwawt.macosx.CPrinterJob", "awt.toolkit", "sun.lwawt.macosx.LWCToolkit", "path.separator", ":", "line.separator", "\n", "file.separator", "/", "file.encoding", "UTF-8", "file.encoding.pkg", "sun.io", "sun.stdout.encoding", "UTF-8", "sun.stderr.encoding", "UTF-8", "os.name", "Mac OS X", // FIXME "os.arch", "x86_64", // FIXME "os.version", "10.12.5", // FIXME "user.name", "", //user.Name, "user.home", "", //user.HomeDir, "user.country", "US", // FIXME "user.language", "en", // FIXME "user.timezone", "", // FIXME "user.dir", "", //user.HomeDir, "sun.java.launcher", "SUN_STANDARD", "sun.java.command", "", //strings.Join(os.Args, " "), "sun.boot.library.path", "", "sun.boot.class.path", "", "sun.os.patch.level", "unknown", "sun.jnu.encoding", "UTF-8", "sun.management.compiler", "HotSpot 64-Bit Tiered Compilers", "sun.arch.data.model", "64", "sun.cpu.endian", "little", "sun.io.unicode.encoding", "UnicodeBig", "sun.cpu.isalist", "", "http.nonProxyHosts", "local|*.local|169.254/16|*.169.254/16", "ftp.nonProxyHosts", "local|*.local|169.254/16|*.169.254/16", "socksNonProxyHosts", "local|*.local|169.254/16|*.169.254/16", "gopherProxySet", "false", }; var i: usize = 0; while (i < map.len) { args[1] = .{ .ref = getJavaLangString(ctx.c, map[i]) }; args[2] = .{ .ref = getJavaLangString(ctx.c, map[i + 1]) }; ctx.t.invoke(properties.class(), setProperty.?, args); i += 2; } // args[1] = .{ .ref = getJavaLangString(null, "java.vm.name") }; // args[2] = .{ .ref = getJavaLangString(null, "Zara") }; // ctx.t.invoke(properties.class(), setProperty.?, args); // args[1] = .{ .ref = getJavaLangString(null, "file.encoding") }; // args[2] = .{ .ref = getJavaLangString(null, "UTF-8") }; // ctx.t.invoke(properties.class(), setProperty.?, args); return properties; // currentPath, _ := filepath.Abs(filepath.Dir(os.Args[0]) + "/..") // user, _ := user.Current() // classpath := VM.GetSystemProperty("classpath.system") + ":" + // VM.GetSystemProperty("classpath.extension") + ":" + // VM.GetSystemProperty("classpath.application") + ":." // paths := strings.Split(classpath, ":") // var abs_paths []string // for _, seg := range paths { // abs_path, _ := filepath.Abs(seg) // abs_paths = append(abs_paths, abs_path) // } // classpath = strings.Join(abs_paths, ":") // m := map[string]string{ // "java.version": "1.8.0_152-ea", // "java.home": currentPath, // "java.specification.name": "Java Platform API Specification", // "java.specification.version": "1.8", // "java.specification.vendor": "Oracle Corporation", // "java.vendor": "Oracle Corporation", // "java.vendor.url": "http://java.oracle.com/", // "java.vendor.url.bug": "http://bugreport.sun.com/bugreport/", // "java.vm.name": "Gava 64-Bit VM", // "java.vm.version": "1.0.0", // "java.vm.vendor": "Chao Yang", // "java.vm.info": "mixed mode", // "java.vm.specification.name": "Java Virtual Machine Specification", // "java.vm.specification.version": "1.8", // "java.vm.specification.vendor": "Oracle Corporation", // "java.runtime.name": "Java(TM) SE Runtime Environment", // "java.runtime.version": "1.8.0_152-ea-b05", // "java.class.version": "52.0", // "java.class.path": classpath, // app classloader path // "java.io.tmpdir": classpath, //TODO // "java.library.path": classpath, //TODO // "java.ext.dirs": "", //TODO // "java.endorsed.dirs": classpath, //TODO // "java.awt.graphicsenv": "sun.awt.CGraphicsEnvironment", // "java.awt.printerjob": "sun.lwawt.macosx.CPrinterJob", // "awt.toolkit": "sun.lwawt.macosx.LWCToolkit", // "path.separator": ":", // "line.separator": "\n", // "file.separator": "/", // "file.encoding": "UTF-8", // "file.encoding.pkg": "sun.io", // "sun.stdout.encoding": "UTF-8", // "sun.stderr.encoding": "UTF-8", // "os.name": "Mac OS X", // FIXME // "os.arch": "x86_64", // FIXME // "os.version": "10.12.5", // FIXME // "user.name": user.Name, // "user.home": user.HomeDir, // "user.country": "US", // FIXME // "user.language": "en", // FIXME // "user.timezone": "", // FIXME // "user.dir": user.HomeDir, // "sun.java.launcher": "SUN_STANDARD", // "sun.java.command": strings.Join(os.Args, " "), // "sun.boot.library.path": "", // "sun.boot.class.path": "", // "sun.os.patch.level": "unknown", // "sun.jnu.encoding": "UTF-8", // "sun.management.compiler": "HotSpot 64-Bit Tiered Compilers", // "sun.arch.data.model": "64", // "sun.cpu.endian": "little", // "sun.io.unicode.encoding": "UnicodeBig", // "sun.cpu.isalist": "", // "http.nonProxyHosts": "local|*.local|169.254/16|*.169.254/16", // "ftp.nonProxyHosts": "local|*.local|169.254/16|*.169.254/16", // "socksNonProxyHosts": "local|*.local|169.254/16|*.169.254/16", // "gopherProxySet": "false", // } // setProperty := properties.Class().GetMethod("setProperty", "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/Object;") // for key, val := range m { // VM.InvokeMethod(setProperty, properties, VM.getJavaLangString(key), VM.getJavaLangString(val)) // } // return properties } pub fn mapLibraryName(ctx: Context, name: JavaLangString) JavaLangString { _ = ctx; return name; } }; const java_lang_Object = struct { // private static void registerNatives() pub fn registerNatives(ctx: Context) void { _ = ctx; } pub fn hashCode(ctx: Context, this: Reference) int { _ = ctx; return this.object().header.hash_code; } pub fn getClass(ctx: Context, this: Reference) JavaLangClass { return getJavaLangClass(ctx.c, this.class().descriptor); } pub fn clone(ctx: Context, this: Reference) Reference { const cloneable = resolveClass(ctx.c, "java/lang/Cloneable"); if (!assignableFrom(cloneable, this.class())) { // return ctx.f.vm_throw("java/lang/CloneNotSupportedException"); } const class = this.class(); var cloned: Reference = undefined; if (class.is_array) { cloned = newArray(ctx.c, class.name, this.len()); } else { cloned = newObject(ctx.c, class.name); } for (0..this.len()) |i| { cloned.set(@intCast(i), this.get(@intCast(i))); } return cloned; // cloneable := VM.ResolveClass("java/lang/Cloneable", TRIGGER_BY_CHECK_OBJECT_TYPE) // if !cloneable.IsAssignableFrom(this.Class()) { // VM.Throw("java/lang/CloneNotSupportedException", "Not implement java.lang.Cloneable") // } // return this.Clone() } pub fn wait(ctx: Context, this: Reference, millis: long) void { _ = ctx; _ = millis; _ = this; // // TODO timeout // monitor := this.Monitor() // if !monitor.HasOwner(VM.CurrentThread()) { // VM.Throw("java/lang/IllegalMonitorStateException", "Cannot wait() when not holding a monitor") // } // interrupted := monitor.Wait(int64(millis)) // if interrupted { // VM.Throw("java/lang/InterruptedException", "wait interrupted") // } } pub fn notifyAll(ctx: Context, this: Reference) void { _ = ctx; _ = this; // monitor := this.Monitor() // if !monitor.HasOwner(VM.CurrentThread()) { // VM.Throw("java/lang/IllegalMonitorStateException", "Cannot notifyAll() when not holding a monitor") // } // monitor.NotifyAll() } }; const java_lang_Class = struct { // private static void registerNatives() pub fn registerNatives(ctx: Context) void { _ = ctx; } // static Class getPrimitiveClass(String name) pub fn getPrimitiveClass(ctx: Context, name: JavaLangString) JavaLangClass { const java_name = toString(name); const descriptor = naming.descriptor(java_name); if (!isPrimitiveType(descriptor)) { unreachable; } return getJavaLangClass(ctx.c, descriptor); // switch name.toNativeString() { // case "byte": // return BYTE_TYPE.ClassObject() // case "short": // return SHORT_TYPE.ClassObject() // case "char": // return CHAR_TYPE.ClassObject() // case "int": // return INT_TYPE.ClassObject() // case "long": // return LONG_TYPE.ClassObject() // case "float": // return FLOAT_TYPE.ClassObject() // case "double": // return DOUBLE_TYPE.ClassObject() // case "boolean": // return boolean_TYPE.ClassObject() // default: // VM.Throw("java/lang/RuntimeException", "Not a primitive type") // } // return NULL } // private static boolean desiredAssertionStatus0(Class javaClass) pub fn desiredAssertionStatus0(ctx: Context, clazz: JavaLangClass) boolean { _ = ctx; _ = clazz; // // Always disable assertions return 0; } pub fn getDeclaredFields0(ctx: Context, this: JavaLangClass, publicOnly: boolean) ArrayRef { const class = this.object().internal.class; std.debug.assert(class != null); const fields = class.?.fields; var fieldsArrayref: ArrayRef = undefined; if (publicOnly == 1) { var len: u32 = 0; for (fields) |field| { if (field.access_flags.public) { len += 1; } } fieldsArrayref = newArray(ctx.c, "[Ljava/lang/reflect/Field;", len); for (fields, 0..) |*field, i| { if (field.access_flags.public) { fieldsArrayref.set(size16(i), .{ .ref = newJavaLangReflectField(ctx.c, this, field) }); } } } else { fieldsArrayref = newArray(ctx.c, "[Ljava/lang/reflect/Field;", size32(fields.len)); for (fields, 0..) |*field, i| { fieldsArrayref.set(size16(i), .{ .ref = newJavaLangReflectField(ctx.c, this, field) }); } } return fieldsArrayref; // class := this.retrieveType().(*Class) // fields := class.GetDeclaredFields(publicOnly.IsTrue()) // fieldObjectArr := VM.NewArrayOfName("[Ljava/lang/reflect/Field;", Int(len(fields))) // for i, field := range fields { // fieldObjectArr.SetArrayElement(Int(i), VM.NewJavaLangReflectField(field)) // } // return fieldObjectArr } pub fn isPrimitive(ctx: Context, this: JavaLangClass) boolean { _ = ctx; const name = getInstanceVar(this, "name", "Ljava/lang/String;").ref; const descriptor = toString(name); defer vm_stash.free(descriptor); return if (isPrimitiveType(descriptor)) 1 else 0; // type_ := this.retrieveType() // if _, ok := type_.(*Class); ok { // return FALSE // } // return TRUE } pub fn isAssignableFrom(ctx: Context, this: JavaLangClass, cls: JavaLangClass) boolean { _ = ctx; const class = this.object().internal.class; const clazz = cls.object().internal.class; if (class != null and clazz != null and assignableFrom(class.?, clazz.?)) { return 1; } return 0; // thisClass := this.retrieveType().(*Class) // clsClass := cls.retrieveType().(*Class) // assignable := FALSE // if thisClass.IsAssignableFrom(clsClass) { // assignable = TRUE // } // return assignable } pub fn getName0(ctx: Context, this: JavaLangClass) JavaLangString { _ = ctx; _ = this; unreachable; // return binaryNameToJavaName(this.retrieveType().Name()) } pub fn forName0(ctx: Context, name: JavaLangString, initialize: boolean, loader: JavaLangClassLoader, caller: JavaLangClass) JavaLangClass { _ = caller; _ = loader; _ = initialize; const java_name = toString(name); const descriptor = naming.descriptor(java_name); return getJavaLangClass(ctx.c, descriptor); // className := javaNameToBinaryName(name) // return VM.ResolveClass(className, TRIGGER_BY_JAVA_REFLECTION).ClassObject() } pub fn isInterface(ctx: Context, this: JavaLangClass) boolean { _ = ctx; const class = this.object().internal.class; return if (class != null and class.?.access_flags.interface) TRUE else FALSE; // if this.retrieveType().(*Class).IsInterface() { // return TRUE // } // return FALSE } pub fn getDeclaredConstructors0(ctx: Context, this: JavaLangClass, publicOnly: boolean) ArrayRef { _ = publicOnly; const class = this.object().internal.class; std.debug.assert(class != null); var constructors = vm_stash.list(*const Method); defer constructors.deinit(); for (class.?.methods) |*method| { if (strings.equals(method.name, "<init>")) { constructors.push(method); } } const len = constructors.len(); const arrayref = newArray(ctx.c, "[Ljava/lang/reflect/Constructor;", size32(len)); for (0..len) |i| { arrayref.set(@intCast(0), .{ .ref = newJavaLangReflectConstructor(ctx.c, this, constructors.get(i)) }); } return arrayref; } pub fn getModifiers(ctx: Context, this: JavaLangClass) int { _ = ctx; const class = this.object().internal.class; std.debug.assert(class != null); return @intCast(class.?.access_flags.raw); } pub fn getSuperclass(ctx: Context, this: JavaLangClass) JavaLangClass { const class = this.object().internal.class; std.debug.assert(class != null); if (strings.equals(class.?.name, "java/lang/Object")) { return NULL; } return getJavaLangClass(ctx.c, naming.descriptor(class.?.super_class)); } pub fn isArray(ctx: Context, this: JavaLangClass) boolean { _ = ctx; const class = this.object().internal.class; return if (class != null and class.?.is_array) TRUE else FALSE; } pub fn getComponentType(ctx: Context, this: JavaLangClass) JavaLangClass { const class = this.object().internal.class; std.debug.assert(class != null and class.?.is_array); return getJavaLangClass(ctx.c, class.?.component_type); } pub fn getEnclosingMethod0(ctx: Context, this: JavaLangClass) ArrayRef { _ = ctx; _ = this; unreachable; // //TODO // return NULL } pub fn getDeclaringClass0(ctx: Context, this: JavaLangClass) JavaLangClass { _ = ctx; _ = this; unreachable; // //TODO // return NULL } }; const java_lang_ClassLoader = struct { pub fn registerNatives(ctx: Context) void { _ = ctx; // TODO } pub fn findBuiltinLib(ctx: Context, name: JavaLangString) JavaLangString { _ = ctx; _ = name; unreachable; // return name } pub fn NativeLibrary_load(ctx: Context, this: JavaLangClassLoader, name: JavaLangString, flag: boolean) void { _ = ctx; _ = flag; _ = name; _ = this; // DO NOTHING } pub fn findLoadedClass0(ctx: Context, this: JavaLangClassLoader, className: JavaLangString) JavaLangClass { _ = ctx; _ = className; _ = this; unreachable; // name := javaNameToBinaryName(className) // var C = NULL // if class, ok := VM.getInitiatedClass(name, this); ok { // C = class.ClassObject() // } // if C.IsNull() { // VM.Info(" ***findLoadedClass0() %s fail [%s] \n", name, this.Class().name) // } else { // VM.Info(" ***findLoadedClass0() %s success [%s] \n", name, this.Class().name) // } // return C } pub fn findBootstrapClass(ctx: Context, this: JavaLangClassLoader, className: JavaLangString) JavaLangClass { _ = ctx; _ = className; _ = this; unreachable; // name := javaNameToBinaryName(className) // var C = NULL // if class, ok := VM.GetDefinedClass(name, NULL); ok { // C = class.ClassObject() // VM.Info(" ***findBootstrapClass() %s success [%s] *c=%p jc=%p \n", name, this.Class().name, class, class.classObject.oop) // } else { // c := VM.createClass(name, NULL, TRIGGER_BY_CHECK_OBJECT_TYPE) // if c != nil { // C = c.ClassObject() // } // } // return C } pub fn defineClass1(ctx: Context, this: JavaLangClassLoader, className: JavaLangString, byteArrRef: ArrayRef, offset: int, length: int, pd: Reference, source: JavaLangString) JavaLangClass { _ = ctx; _ = source; _ = pd; _ = length; _ = offset; _ = byteArrRef; _ = className; _ = this; unreachable; // byteArr := byteArrRef.ArrayElements()[offset : offset+length] // bytes := make([]byte, length) // for i, b := range byteArr { // bytes[i] = byte(b.(Byte)) // } // C := VM.deriveClass(javaNameToBinaryName(className), this, bytes, TRIGGER_BY_JAVA_CLASSLOADER) // //VM.link(C) // // associate JavaLangClass object // //class.classObject = VM.getJavaLangClass(class) // //// specify its defining classloader // C.ClassObject().SetInstanceVariableByName("classLoader", "Ljava/lang/ClassLoader;", this) // VM.Info(" ==after java.lang.ClassLoader#defineClass1 %s *c=%p (derived) jc=%p \n", C.name, C, C.ClassObject().oop) // //C.sourceFile = source.toNativeString() + C.Name() + ".java" // return C.ClassObject() } }; const java_lang_Package = struct { pub fn getSystemPackage0(ctx: Context, vmPackageName: JavaLangString) JavaLangString { _ = ctx; _ = vmPackageName; unreachable; // for nl, class := range VM.MethodArea.DefinedClasses { // if nl.L == nil && strings.HasPrefix(class.Name(), vmPackageName.toNativeString()) { // return vmPackageName // } // } // return NULL } }; const java_lang_String = struct { pub fn intern(ctx: Context, this: JavaLangString) JavaLangString { _ = ctx; return internString(this); } }; const java_lang_Float = struct { // public static native int floatToRawIntBits(float value) pub fn floatToRawIntBits(ctx: Context, value: float) int { _ = ctx; return @bitCast(value); } pub fn intBitsToFloat(ctx: Context, bits: int) float { _ = ctx; return @bitCast(bits); } }; const java_lang_Double = struct { // public static native int floatToRawIntBits(float value) pub fn doubleToRawLongBits(ctx: Context, value: double) long { _ = ctx; return @bitCast(value); } // public static native int floatToRawIntBits(float value) pub fn longBitsToDouble(ctx: Context, bits: long) double { _ = ctx; return @bitCast(bits); } }; const java_lang_Thread = struct { // private static void registerNatives() pub fn registerNatives(ctx: Context) void { _ = ctx; } pub fn currentThread(ctx: Context) JavaLangThread { return newJavaLangThread(ctx.c, ctx.t); } pub fn setPriority0(ctx: Context, this: Reference, priority: int) void { _ = ctx; _ = priority; _ = this; // TODO // if priority < 1 { // this.SetInstanceVariableByName("priority", "I", Int(5)) // } } pub fn isAlive(ctx: Context, this: Reference) boolean { _ = this; _ = ctx; return 0; // return FALSE } pub fn start0(ctx: Context, this: Reference) void { _ = ctx; _ = this; // if this.Class().name == "java/lang/ref/Reference$ReferenceHandler" { // return // TODO hack: ignore these threads // } // name := this.GetInstanceVariableByName("name", "Ljava/lang/String;").(JavaLangString).toNativeString() // runMethod := this.Class().GetMethod("run", "()V") // thread := VM.NewThread(name, func() { // VM.InvokeMethod(runMethod, this) // }, func() {}) // thread.threadObject = this // thread.start() } pub fn sleep(ctx: Context, millis: long) void { _ = ctx; _ = millis; // thread := VM.CurrentThread() // interrupted := thread.sleep(int64(millis)) // if interrupted { // VM.Throw("java/lang/InterruptedException", "sleep interrupted") // } } pub fn interrupt0(ctx: Context, this: JavaLangThread) void { _ = ctx; _ = this; // thread := this.retrieveThread() // thread.interrupt() } pub fn isInterrupted(ctx: Context, this: JavaLangThread, clearInterrupted: boolean) boolean { _ = ctx; _ = clearInterrupted; _ = this; unreachable; // interrupted := false // if this.retrieveThread().interrupted { // interrupted = true // } // if clearInterrupted.IsTrue() { // this.retrieveThread().interrupted = false // } // if interrupted { // return TRUE // } // return FALSE } }; const java_lang_Throwable = struct { pub fn getStackTraceDepth(ctx: Context, this: Reference) int { _ = ctx; _ = this; unreachable; // thread := VM.CurrentThread() // return Int(len(thread.vmStack) - this.Class().InheritanceDepth()) // skip how many frames } pub fn fillInStackTrace(ctx: Context, this: JavaLangThrowable, dummy: int) Reference { _ = dummy; var depth: usize = 1; // exception inheritance until object var class = this.class(); while (true) { if (strings.equals(class.super_class, "")) { break; } class = resolveClass(ctx.c, class.super_class); depth += 1; } const len = ctx.t.depth() - depth; const stackTrace = newArray(ctx.c, "[Ljava/lang/StackTraceElement;", size32(len)); for (0..len) |i| { const frame = ctx.t.stack.get(i); const stackTraceElement = newObject(ctx.c, "java/lang/StackTraceElement"); setInstanceVar(stackTraceElement, "declaringClass", "Ljava/lang/String;", .{ .ref = getJavaLangString(ctx.c, frame.class.name) }); setInstanceVar(stackTraceElement, "methodName", "Ljava/lang/String;", .{ .ref = getJavaLangString(ctx.c, frame.method.name) }); setInstanceVar(stackTraceElement, "fileName", "Ljava/lang/String;", .{ .ref = getJavaLangString(ctx.c, "") }); setInstanceVar(stackTraceElement, "lineNumber", "I", .{ .int = @intCast(frame.pc) }); // FIXME stackTrace.set(size16(len - 1 - i), .{ .ref = stackTraceElement }); } this.object().internal.stack_trace = stackTrace; // ⚠️⚠️⚠️ we are unable to set stackTrace in throwable.stackTrace, as a following instruction sets its value to empty Throwable.UNASSIGNED_STACK // ⚠️⚠️⚠️ setInstanceVar(this, "stackTrace", "[Ljava/lang/StackTraceElement;", .{ .ref = stackTrace }); return this; // thread := VM.CurrentThread() // depth := len(thread.vmStack) - this.Class().InheritanceDepth() // skip how many frames // //backtrace := NewArray("[Ljava/lang/String;", Int(depth)) // // // //for i, frame := range thread.vmStack[:depth] { // // javaClassName := strings.Replace(frame.method.class.name, "/", ".", -1) // // str := getJavaLangString(javaClassName + "." + frame.method.name + frame.getSourceFileAndLineNumber(self)) // // backtrace.SetArrayElement(Int(depth-1-i), str) // //} // // // //this.SetInstanceVariableByName("backtrace", "Ljava/lang/Object;", backtrace) // backtrace := make([]StackTraceElement, depth) // for i, frame := range thread.vmStack[:depth] { // javaClassName := strings.Replace(frame.method.class.name, "/", ".", -1) // methodName := frame.method.name // fileName := frame.getSourceFile() // lineNumber := frame.getLineNumber() // backtrace[depth-1-i] = StackTraceElement{javaClassName, methodName, fileName, lineNumber} // } // this.attachStacktrace(backtrace) // return this } pub fn getStackTraceElement(ctx: Context, this: JavaLangThrowable, i: int) ObjectRef { _ = ctx; _ = i; _ = this; unreachable; // stacktraceelement := this.retrieveStacktrace()[i] // ste := VM.NewObjectOfName("java/lang/StackTraceElement") // ste.SetInstanceVariableByName("declaringClass", "Ljava/lang/String;", VM.getJavaLangString(stacktraceelement.declaringClass)) // ste.SetInstanceVariableByName("methodName", "Ljava/lang/String;", VM.getJavaLangString(stacktraceelement.methodName)) // ste.SetInstanceVariableByName("fileName", "Ljava/lang/String;", VM.getJavaLangString(stacktraceelement.fileName)) // ste.SetInstanceVariableByName("lineNumber", "I", Int(stacktraceelement.lineNumber)) // return ste } }; const java_lang_Runtime = struct { pub fn availableProcessors(ctx: Context, this: Reference) int { _ = ctx; _ = this; // TODO return 4; // return Int(runtime.NumCPU()) } }; const java_lang_StrictMath = struct { // private static void registers() pub fn pow(ctx: Context, base: double, exponent: double) double { _ = ctx; _ = exponent; _ = base; // return Double(math.Pow(float64(base), float64(exponent))) unreachable; } }; const java_security_AccessController = struct { // because here need to call java method, so the return value will automatically be placed in the stack pub fn doPrivileged(ctx: Context, action: Reference) Reference { const method = action.class().method("run", "()Ljava/lang/Object;", false).?; const args = vm_stash.make(Value, method.parameter_descriptors.len + 1); defer vm_stash.free(args); args[0] = .{ .ref = action }; ctx.t.invoke(action.class(), method, args); std.debug.assert(ctx.t.active().?.stack.len() > 0); // assume no exception for the above method call return ctx.t.active().?.pop().as(Reference).ref; // method := action.Class().FindMethod("run", "()Ljava/lang/Object;") // return VM.InvokeMethod(method, action).(Reference) } pub fn getStackAccessControlContext(ctx: Context) Reference { _ = ctx; return NULL; // //TODO // return NULL } pub fn doPrivilegedContext(ctx: Context, action: Reference, context: Reference) Reference { _ = context; return doPrivileged(ctx, action); } }; const java_lang_reflect_Array = struct { pub fn newArray(ctx: Context, componentClassObject: JavaLangClass, length: int) ArrayRef { _ = ctx; _ = length; _ = componentClassObject; // componentType := componentClassObject.retrieveType() // return VM.NewArrayOfComponent(componentType, length) unreachable; } }; const sun_misc_VM = struct { // private static void registerNatives() pub fn initialize(ctx: Context) void { _ = ctx; } }; const sun_misc_Unsafe = struct { // private static void registerNatives() pub fn registerNatives(ctx: Context) void { _ = ctx; } pub fn arrayBaseOffset(ctx: Context, this: Reference, arrayClass: JavaLangClass) int { _ = ctx; _ = arrayClass; _ = this; return 0; // //todo // return Int(0) } pub fn arrayIndexScale(ctx: Context, this: Reference, arrayClass: JavaLangClass) int { _ = ctx; _ = arrayClass; _ = this; return 1; // //todo // return Int(1) } pub fn addressSize(ctx: Context, this: Reference) int { _ = ctx; _ = this; return 8; // //todo // return Int(8) } pub fn objectFieldOffset(ctx: Context, this: Reference, fieldObject: Reference) long { _ = this; _ = ctx; return getInstanceVar(fieldObject, "slot", "I").int; // slot := fieldObject.GetInstanceVariableByName("slot", "I").(Int) // return Long(slot) } pub fn compareAndSwapObject(ctx: Context, this: Reference, obj: Reference, offset: long, expected: Reference, newVal: Reference) boolean { _ = this; _ = ctx; std.debug.assert(obj.nonNull()); const current = obj.get(@intCast(offset)).ref; if (current.equals(expected)) { obj.set(@intCast(offset), .{ .ref = newVal }); return 1; } return 0; // if obj.IsNull() { // VM.Throw("java/lang/NullPointerException", "") // } // slots := obj.oop.slots // current := slots[offset] // if current == expected { // slots[offset] = newVal // return TRUE // } // return FALSE } pub fn compareAndSwapInt(ctx: Context, this: Reference, obj: Reference, offset: long, expected: int, newVal: int) boolean { _ = this; _ = ctx; std.debug.assert(obj.nonNull()); const current = obj.get(@intCast(offset)).int; if (current == expected) { obj.set(@intCast(offset), .{ .int = newVal }); return 1; } return 0; // if obj.IsNull() { // VM.Throw("java/lang/NullPointerException", "") // } // slots := obj.oop.slots // current := slots[offset] // if current == expected { // slots[offset] = newVal // return TRUE // } // return FALSE } pub fn compareAndSwapLong(ctx: Context, this: Reference, obj: Reference, offset: long, expected: long, newVal: long) boolean { _ = this; _ = ctx; std.debug.assert(obj.nonNull()); const current = obj.get(@intCast(offset)).long; if (current == expected) { obj.set(@intCast(offset), .{ .long = newVal }); return 1; } return 0; // if obj.IsNull() { // VM.Throw("java/lang/NullPointerException", "") // } // slots := obj.oop.slots // current := slots[offset] // if current == expected { // slots[offset] = newVal // return TRUE // } // return FALSE } pub fn getIntVolatile(ctx: Context, this: Reference, obj: Reference, offset: long) int { _ = this; _ = ctx; std.debug.assert(obj.nonNull()); return obj.get(@intCast(offset)).int; // if obj.IsNull() { // VM.Throw("java/lang/NullPointerException", "") // } // slots := obj.oop.slots // return slots[offset].(Int) } pub fn getObjectVolatile(ctx: Context, this: Reference, obj: Reference, offset: long) Reference { _ = ctx; _ = this; return obj.get(@intCast(offset)).ref; // slots := obj.oop.slots // return slots[offset].(Reference) } pub fn putObjectVolatile(ctx: Context, this: Reference, obj: Reference, offset: long, val: Reference) void { _ = ctx; _ = val; _ = offset; _ = obj; _ = this; unreachable; // slots := obj.oop.slots // slots[offset] = val } pub fn allocateMemory(ctx: Context, this: Reference, size: long) long { _ = this; _ = ctx; const mem = vm_stash.make(u8, @intCast(size)); const addr = &mem[0]; std.log.info("allocate {d} bytes from off-heap memory at 0x{x:0>8}", .{ size, addr }); return @intCast(@intFromPtr(addr)); // //TODO // return size } pub fn putLong(ctx: Context, this: Reference, address: long, val: long) void { _ = this; _ = ctx; const addr: usize = @intCast(address); const ptr: [*]u8 = @ptrFromInt(addr); const value: u64 = @bitCast(val); for (0..8) |i| { const sh: u6 = @intCast((7 - i) * 8); const b: u8 = @truncate((value >> sh) & 0xFF); ptr[i] = b; } std.log.info("put long 0x{x:0>8} from off-heap memory at 0x{x:0>8}", .{ val, addr }); // //TODO } pub fn getByte(ctx: Context, this: Reference, address: long) byte { _ = this; _ = ctx; const addr: usize = @intCast(address); const ptr: *u8 = @ptrFromInt(addr); const b: i8 = @bitCast(ptr.*); std.log.info("get a byte 0x{x:0>2} from off-heap memory at 0x{x:0>8}", .{ b, addr }); return b; // //TODO // return Byte(0x08) //0x01 big_endian } pub fn freeMemory(ctx: Context, this: Reference, size: long) void { _ = ctx; _ = size; _ = this; // // do nothing } pub fn ensureClassInitialized(ctx: Context, this: Reference, class: JavaLangClass) void { _ = ctx; _ = class; _ = this; // // LOCK ??? // if class.retrieveType().(*Class).initialized != INITIALIZED { // VM.Throw("java/lang/AssertionError", "Class has not been initialized") // } } }; const sun_reflect_Reflection = struct { pub fn getCallerClass(ctx: Context) JavaLangClass { const len = ctx.t.stack.len(); if (len < 2) { return NULL; } else { const name = ctx.t.stack.get(len - 2).class.name; const descriptor = strings.concat(&[_]string{ "L", name, ";" }); defer vm_stash.free(descriptor); return getJavaLangClass(ctx.c, descriptor); } // //todo // vmStack := VM.CurrentThread().vmStack // if len(vmStack) == 1 { // return NULL // } else { // return vmStack[len(vmStack)-2].method.class.ClassObject() // } } pub fn getClassAccessFlags(ctx: Context, classObj: JavaLangClass) int { _ = ctx; const class = classObj.object().internal.class; std.debug.assert(class != null); return @intCast(class.?.access_flags.raw); // return Int(u16toi32(classObj.retrieveType().(*Class).accessFlags)) } }; const sun_reflect_NativeConstructorAccessorImpl = struct { pub fn newInstance0(ctx: Context, constructor: JavaLangReflectConstructor, args: ArrayRef) ObjectRef { const clazz = getInstanceVar(constructor, "clazz", "Ljava/lang/Class;").ref; const class = clazz.object().internal.class; std.debug.assert(class != null); const desc = getInstanceVar(constructor, "signature", "Ljava/lang/String;").ref; const descriptor = toString(desc); const method = class.?.method("<init>", descriptor, false).?; const objeref = newObject(ctx.c, class.?.name); var arguments: []Value = undefined; if (args.nonNull()) { arguments = vm_stash.make(Value, args.len() + 1); arguments[0] = .{ .ref = objeref }; for (0..args.len()) |i| { arguments[i + 1] = args.get(size32(i)); } } else { var a = [_]Value{.{ .ref = objeref }}; arguments = &a; } ctx.t.invoke(class.?, method, arguments); return objeref; // classObject := constructor.GetInstanceVariableByName("clazz", "Ljava/lang/Class;").(JavaLangClass) // class := classObject.retrieveType().(*Class) // descriptor := constructor.GetInstanceVariableByName("signature", "Ljava/lang/String;").(JavaLangString).toNativeString() // method := class.GetConstructor(descriptor) // objeref := VM.NewObject(class) // allArgs := []Value{objeref} // if !args.IsNull() { // allArgs = append(allArgs, args.oop.slots...) // } // VM.InvokeMethod(method, allArgs...) // return objeref } }; const sun_misc_URLClassPath = struct { pub fn getLookupCacheURLs(ctx: Context, classloader: JavaLangClassLoader) ArrayRef { _ = ctx; _ = classloader; unreachable; // return VM.NewArrayOfName("[Ljava/net/URL;", 0) } }; const java_io_FileDescriptor = struct { // private static void registers() pub fn initIDs(ctx: Context) void { _ = ctx; } }; const java_io_FileInputStream = struct { pub fn initIDs(ctx: Context) void { _ = ctx; // // TODO } pub fn open0(ctx: Context, this: Reference, name: JavaLangString) void { _ = ctx; _ = name; _ = this; unreachable; // _, error := os.Open(name.toNativeString()) // if error != nil { // VM.Throw("java/io/IOException", "Cannot open file: %s", name.toNativeString()) // } } pub fn readBytes(ctx: Context, this: Reference, byteArr: ArrayRef, offset: int, length: int) int { _ = ctx; _ = length; _ = offset; _ = byteArr; _ = this; unreachable; // var file *os.File // fileDescriptor := this.GetInstanceVariableByName("fd", "Ljava/io/FileDescriptor;").(Reference) // path := this.GetInstanceVariableByName("path", "Ljava/lang/String;").(JavaLangString) // if !path.IsNull() { // f, err := os.Open(path.toNativeString()) // if err != nil { // VM.Throw("java/io/IOException", "Cannot open file: %s", path.toNativeString()) // } // file = f // } else if !fileDescriptor.IsNull() { // fd := fileDescriptor.GetInstanceVariableByName("fd", "I").(Int) // switch fd { // case 0: // file = os.Stdin // case 1: // file = os.Stdout // case 2: // file = os.Stderr // default: // file = os.NewFile(uintptr(fd), "") // } // } // if file == nil { // VM.Throw("java/io/IOException", "File cannot open") // } // bytes := make([]byte, length) // file.Seek(int64(offset), 0) // nsize, err := file.Read(bytes) // VM.ExecutionEngine.ioLogger.Info("🅹 ⤆ %s - buffer size: %d, offset: %d, len: %d, actual read: %d \n", file.Name(), byteArr.ArrayLength(), offset, length, nsize) // if err == nil || nsize == int(length) { // for i := 0; i < int(length); i++ { // byteArr.SetArrayElement(offset+Int(i), Byte(bytes[i])) // } // return Int(nsize) // } // VM.Throw("java/io/IOException", err.Error()) // return -1 } pub fn close0(ctx: Context, this: Reference) void { _ = ctx; _ = this; unreachable; // var file *os.File // fileDescriptor := this.GetInstanceVariableByName("fd", "Ljava/io/FileDescriptor;").(Reference) // path := this.GetInstanceVariableByName("path", "Ljava/lang/String;").(JavaLangString) // if !fileDescriptor.IsNull() { // fd := fileDescriptor.GetInstanceVariableByName("fd", "I").(Int) // switch fd { // case 0: // file = os.Stdin // case 1: // file = os.Stdout // case 2: // file = os.Stderr // } // } else { // f, err := os.Open(path.toNativeString()) // if err != nil { // VM.Throw("java/io/IOException", "Cannot open file: %s", path.toNativeString()) // } // file = f // } // err := file.Close() // if err != nil { // VM.Throw("java/io/IOException", "Cannot close file: %s", path) // } } }; const java_io_FileOutputStream = struct { pub fn initIDs(ctx: Context) void { _ = ctx; // // TODO } pub fn writeBytes(ctx: Context, this: Reference, byteArr: ArrayRef, offset: int, length: int, append: boolean) void { _ = ctx; const fileDescriptor = getInstanceVar(this, "fd", "Ljava/io/FileDescriptor;").ref; const path = getInstanceVar(this, "path", "Ljava/lang/String;").ref; var file: std.fs.File = undefined; if (path.nonNull()) { file = std.fs.openFileAbsolute(toString(path), .{ .mode = .read_write }) catch unreachable; defer file.close(); } else if (fileDescriptor.nonNull()) { const fd = getInstanceVar(fileDescriptor, "fd", "I").int; file = switch (fd) { 0 => std.io.getStdIn(), 1 => std.io.getStdOut(), 2 => std.io.getStdErr(), else => unreachable, }; } const bytes = vm_stash.make(u8, size32(length)); for (0..bytes.len) |i| { const j = size32(i); const o = size32(offset); bytes[i] = @bitCast(byteArr.get(j + o).byte); } if (append == 1) { var stat = file.stat() catch unreachable; file.seekTo(stat.size) catch unreachable; } _ = file.writer().print("{s}", .{bytes}) catch unreachable; // var file *os.File // fileDescriptor := this.GetInstanceVariableByName("fd", "Ljava/io/FileDescriptor;").(Reference) // path := this.GetInstanceVariableByName("path", "Ljava/lang/String;").(JavaLangString) // if !path.IsNull() { // f, err := os.Open(path.toNativeString()) // if err != nil { // VM.Throw("java/lang/IOException", "Cannot open file: %s", path.toNativeString()) // } // file = f // } else if !fileDescriptor.IsNull() { // fd := fileDescriptor.GetInstanceVariableByName("fd", "I").(Int) // switch fd { // case 0: // file = os.Stdin // case 1: // file = os.Stdout // case 2: // file = os.Stderr // default: // file = os.NewFile(uintptr(fd), "") // } // } // if file == nil { // VM.Throw("java/lang/IOException", "File cannot open") // } // if append.IsTrue() { // file.Chmod(os.ModeAppend) // } // bytes := make([]byte, byteArr.ArrayLength()) // for i := 0; i < int(byteArr.ArrayLength()); i++ { // bytes[i] = byte(int8(byteArr.GetArrayElement(Int(i)).(Byte))) // } // bytes = bytes[offset : offset+length] // //ptr := unsafe.Pointer(&bytes) // f := bufio.NewWriter(file) // defer f.Flush() // nsize, err := f.Write(bytes) // VM.ExecutionEngine.ioLogger.Info("🅹 ⤇ %s - buffer size: %d, offset: %d, len: %d, actual write: %d \n", file.Name(), byteArr.ArrayLength(), offset, length, nsize) // if err == nil { // return // } // VM.Throw("java/lang/IOException", "Cannot write to file: %s", file.Name()) } }; const java_io_UnixFileSystem = struct { pub fn initIDs(ctx: Context) void { _ = ctx; // // do nothing } // @Native public static final int BA_EXISTS = 0x01; // @Native public static final int BA_REGULAR = 0x02; // @Native public static final int BA_DIRECTORY = 0x04; // @Native public static final int BA_HIDDEN = 0x08; pub fn getBooleanAttributes0(ctx: Context, this: Reference, file: Reference) int { _ = ctx; _ = file; _ = this; unreachable; // path := file.GetInstanceVariableByName("path", "Ljava/lang/String;").(JavaLangString).toNativeString() // fileInfo, err := os.Stat(path) // attr := 0 // if err == nil { // attr |= 0x01 // if fileInfo.Mode().IsRegular() { // attr |= 0x02 // } // if fileInfo.Mode().IsDir() { // attr |= 0x04 // } // if hidden, err := IsHidden(path); hidden && err != nil { // attr |= 0x08 // } // return Int(attr) // } // VM.Throw("java/io/IOException", "Cannot get file attributes: %s", path) // return -1 } // fn IsHidden(filename :string) (bool, error) { // if runtime.GOOS != "windows" { // // unix/linux file or directory that starts with . is hidden // if filename[0:1] == "." { // return true, nil // } else { // return false, nil // } // } else { // log.Fatal("Unable to check if file is hidden under this OS") // } // return false, nil // } pub fn canonicalize0(ctx: Context, this: Reference, path: JavaLangString) JavaLangString { _ = ctx; _ = path; _ = this; unreachable; // return VM.getJavaLangString(filepath.Clean(path.toNativeString())) } pub fn getLength(ctx: Context, this: Reference, file: Reference) long { _ = ctx; _ = file; _ = this; unreachable; // path := file.GetInstanceVariableByName("path", "Ljava/lang/String;").(JavaLangString).toNativeString() // fileInfo, err := os.Stat(path) // if err == nil { // VM.ExecutionEngine.ioLogger.Info("📒 %s - length %d \n", path, fileInfo.Size()) // return Long(fileInfo.Size()) // } // VM.Throw("java/io/IOException", "Cannot get file length: %s", path) // return -1 } }; const java_util_concurrent_atomic_AtomicLong = struct { pub fn VMSupportsCS8(ctx: Context) boolean { _ = ctx; return TRUE; // return TRUE } }; const java_util_zip_ZipFile = struct { pub fn initIDs(ctx: Context) void { _ = ctx; // //DO NOTHING unreachable; } }; const java_util_TimeZone = struct { pub fn getSystemTimeZoneID(ctx: Context, javaHome: JavaLangString) JavaLangString { _ = ctx; _ = javaHome; // loc := time.Local // return VM.getJavaLangString(loc.String()) unreachable; } };
https://raw.githubusercontent.com/chaoyangnz/zava/a5578f0a65f93d6e11724771220524afc3045817/src/native.zig
const abi = @import("../abi/abi.zig"); const params = @import("../abi/abi_parameter.zig"); const std = @import("std"); const testing = std.testing; // Types const Abitype = abi.Abitype; const AbiEventParameter = params.AbiEventParameter; const AbiParameter = params.AbiParameter; const ParamType = @import("../abi/param_type.zig").ParamType; /// Sames as `AbiParametersToPrimative` but for event parameter types. pub fn AbiEventParametersDataToPrimative(comptime paramters: []const AbiEventParameter) type { if (paramters.len == 0) return @Type(.{ .Struct = .{ .layout = .auto, .fields = &.{}, .decls = &.{}, .is_tuple = true } }); var count: usize = 0; for (paramters) |param| { const EventType = AbiEventParameterToPrimativeType(param); if (EventType != void) count += 1; } var fields: [count]std.builtin.Type.StructField = undefined; count = 0; for (paramters) |paramter| { const EventType = AbiEventParameterDataToPrimative(paramter); if (EventType != void) { fields[count] = .{ .name = std.fmt.comptimePrint("{d}", .{count}), .type = EventType, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(EventType) > 0) @alignOf(EventType) else 0, }; count += 1; } } return @Type(.{ .Struct = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = true } }); } /// Sames as `AbiParameterToPrimative` but for event parameter types. pub fn AbiEventParameterDataToPrimative(comptime param: AbiEventParameter) type { return switch (param.type) { .string, .bytes => []const u8, .address => [20]u8, .fixedBytes => |fixed| [fixed]u8, .bool => bool, .int => |val| if (val % 8 != 0 or val > 256) @compileError("Invalid bits passed in to int type") else @Type(.{ .Int = .{ .signedness = .signed, .bits = val } }), .uint => |val| if (val % 8 != 0 or val > 256) @compileError("Invalid bits passed in to int type") else @Type(.{ .Int = .{ .signedness = .unsigned, .bits = val } }), .dynamicArray => []const AbiParameterToPrimative(.{ .type = param.type.dynamicArray.*, .name = param.name, .internalType = param.internalType, .components = param.components, }), .fixedArray => [param.type.fixedArray.size]AbiParameterToPrimative(.{ .type = param.type.fixedArray.child.*, .name = param.name, .internalType = param.internalType, .components = param.components, }), .tuple => { if (param.components) |components| { var fields: [components.len]std.builtin.Type.StructField = undefined; for (components, 0..) |component, i| { const FieldType = AbiParameterToPrimative(component); fields[i] = .{ .name = component.name ++ "", .type = FieldType, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(FieldType) > 0) @alignOf(FieldType) else 0, }; } return @Type(.{ .Struct = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = false } }); } else @compileError("Expected components to not be null"); }, inline else => void, }; } /// Convert sets of solidity ABI Event indexed parameters to the representing Zig types. /// This will create a tuple type of the subset of the resulting types /// generated by `AbiEventParameterToPrimativeType`. If the paramters length is /// O then the resulting type a tuple of just the Hash type. pub fn AbiEventParametersToPrimativeType(comptime event_params: []const AbiEventParameter) type { if (event_params.len == 0) { var fields: [1]std.builtin.Type.StructField = undefined; fields[0] = .{ .name = std.fmt.comptimePrint("{d}", .{0}), .type = [32]u8, .default_value = null, .is_comptime = false, .alignment = @alignOf([32]u8), }; return @Type(.{ .Struct = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = true } }); } var count: usize = 0; for (event_params) |param| { const EventType = AbiEventParameterToPrimativeType(param); if (EventType != void) count += 1; } var fields: [count + 1]std.builtin.Type.StructField = undefined; fields[0] = .{ .name = std.fmt.comptimePrint("{d}", .{0}), .type = [32]u8, .default_value = null, .is_comptime = false, .alignment = @alignOf([32]u8), }; for (event_params, 1..) |param, i| { const EventType = AbiEventParameterToPrimativeType(param); if (EventType != void) { fields[i] = .{ .name = std.fmt.comptimePrint("{d}", .{i}), .type = EventType, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(EventType) > 0) @alignOf(EventType) else 0, }; } } return @Type(.{ .Struct = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = true } }); } /// Converts the abi event parameters into native zig types /// This is intended to be used for log topic data or in /// other words were the params are indexed. pub fn AbiEventParameterToPrimativeType(comptime param: AbiEventParameter) type { if (!param.indexed) return void; return switch (param.type) { .tuple, .dynamicArray, .fixedArray, .string, .bytes => [32]u8, .address => [20]u8, .fixedBytes => |fixed| [fixed]u8, .bool => bool, .int => |val| if (val % 8 != 0 or val > 256) @compileError("Invalid bits passed in to int type") else @Type(.{ .Int = .{ .signedness = .signed, .bits = val } }), .uint => |val| if (val % 8 != 0 or val > 256) @compileError("Invalid bits passed in to int type") else @Type(.{ .Int = .{ .signedness = .unsigned, .bits = val } }), inline else => void, }; } /// Convert sets of solidity ABI paramters to the representing Zig types. /// This will create a tuple type of the subset of the resulting types /// generated by `AbiParameterToPrimative`. If the paramters length is /// O then the resulting type will be a void type. pub fn AbiParametersToPrimative(comptime paramters: []const AbiParameter) type { if (paramters.len == 0) return void; var fields: [paramters.len]std.builtin.Type.StructField = undefined; for (paramters, 0..) |paramter, i| { const FieldType = AbiParameterToPrimative(paramter); fields[i] = .{ .name = std.fmt.comptimePrint("{d}", .{i}), .type = FieldType, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(FieldType) > 0) @alignOf(FieldType) else 0, }; } return @Type(.{ .Struct = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = true } }); } /// Convert solidity ABI paramter to the representing Zig types. /// /// The resulting type will depend on the parameter passed in. /// `string, fixed/bytes and addresses` will result in the zig **string** type. /// /// For the `int/uint` type the resulting type will depend on the values attached to them. /// **If the value is not divisable by 8 or higher than 256 compilation will fail.** /// For example `ParamType{.int = 120}` will result in the **i120** type. /// /// If the param is a `dynamicArray` then the resulting type will be /// a **slice** of the set of base types set above. /// /// If the param type is a `fixedArray` then the a **array** is returned /// with its size depending on the *size* property on it. /// /// Finally for tuple type a **struct** will be created where the field names are property names /// that the components array field has. If this field is null compilation will fail. pub fn AbiParameterToPrimative(comptime param: AbiParameter) type { return switch (param.type) { .string => []const u8, .bytes => []u8, .address => [20]u8, .fixedBytes => |fixed| [fixed]u8, .bool => bool, .int => |val| if (val % 8 != 0 or val > 256) @compileError("Invalid bits passed in to int type") else @Type(.{ .Int = .{ .signedness = .signed, .bits = val } }), .uint => |val| if (val % 8 != 0 or val > 256) @compileError("Invalid bits passed in to int type") else @Type(.{ .Int = .{ .signedness = .unsigned, .bits = val } }), .dynamicArray => []const AbiParameterToPrimative(.{ .type = param.type.dynamicArray.*, .name = param.name, .internalType = param.internalType, .components = param.components, }), .fixedArray => [param.type.fixedArray.size]AbiParameterToPrimative(.{ .type = param.type.fixedArray.child.*, .name = param.name, .internalType = param.internalType, .components = param.components, }), .tuple => { if (param.components) |components| { var fields: [components.len]std.builtin.Type.StructField = undefined; for (components, 0..) |component, i| { const FieldType = AbiParameterToPrimative(component); fields[i] = .{ .name = component.name ++ "", .type = FieldType, .default_value = null, .is_comptime = false, .alignment = if (@sizeOf(FieldType) > 0) @alignOf(FieldType) else 0, }; } return @Type(.{ .Struct = .{ .layout = .auto, .fields = &fields, .decls = &.{}, .is_tuple = false } }); } else @compileError("Expected components to not be null"); }, inline else => void, }; } test "Meta" { try testing.expectEqual(AbiParametersToPrimative(&.{}), void); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .string = {} }, .name = "foo" }), []const u8); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .fixedBytes = 31 }, .name = "foo" }), [31]u8); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .uint = 120 }, .name = "foo" }), u120); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .int = 48 }, .name = "foo" }), i48); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .bytes = {} }, .name = "foo" }), []u8); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .address = {} }, .name = "foo" }), [20]u8); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .bool = {} }, .name = "foo" }), bool); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .dynamicArray = &.{ .bool = {} } }, .name = "foo" }), []const bool); try testing.expectEqual(AbiParameterToPrimative(.{ .type = .{ .fixedArray = .{ .child = &.{ .bool = {} }, .size = 2 } }, .name = "foo" }), [2]bool); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .string = {} }, .name = "foo", .indexed = true }), [32]u8); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .bytes = {} }, .name = "foo", .indexed = true }), [32]u8); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .tuple = {} }, .name = "foo", .indexed = true }), [32]u8); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .dynamicArray = &.{ .bool = {} } }, .name = "foo", .indexed = true }), [32]u8); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .fixedArray = .{ .child = &.{ .bool = {} }, .size = 2 } }, .name = "foo", .indexed = true }), [32]u8); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .bool = {} }, .name = "foo", .indexed = true }), bool); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .address = {} }, .name = "foo", .indexed = true }), [20]u8); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .uint = 64 }, .name = "foo", .indexed = true }), u64); try testing.expectEqual(AbiEventParameterToPrimativeType(.{ .type = .{ .int = 16 }, .name = "foo", .indexed = true }), i16); try expectEqualStructs(AbiParameterToPrimative(.{ .type = .{ .tuple = {} }, .name = "foo", .components = &.{.{ .type = .{ .bool = {} }, .name = "bar" }} }), struct { bar: bool }); try expectEqualStructs(AbiParameterToPrimative(.{ .type = .{ .tuple = {} }, .name = "foo", .components = &.{.{ .type = .{ .tuple = {} }, .name = "bar", .components = &.{.{ .type = .{ .bool = {} }, .name = "baz" }} }} }), struct { bar: struct { baz: bool } }); } test "EventParameters" { const event: abi.Event = .{ .type = .event, .name = "Foo", .inputs = &.{ .{ .type = .{ .uint = 256 }, .name = "bar", .indexed = true, }, }, }; const ParamsTypes = AbiEventParametersToPrimativeType(event.inputs); try expectEqualStructs(ParamsTypes, struct { [32]u8, u256 }); try expectEqualStructs(AbiEventParametersToPrimativeType(&.{}), struct { [32]u8 }); } fn expectEqualStructs(comptime expected: type, comptime actual: type) !void { const expectInfo = @typeInfo(expected).Struct; const actualInfo = @typeInfo(actual).Struct; try testing.expectEqual(expectInfo.layout, actualInfo.layout); try testing.expectEqual(expectInfo.decls.len, actualInfo.decls.len); try testing.expectEqual(expectInfo.fields.len, actualInfo.fields.len); try testing.expectEqual(expectInfo.is_tuple, actualInfo.is_tuple); inline for (expectInfo.fields, actualInfo.fields) |e, a| { try testing.expectEqualStrings(e.name, a.name); if (@typeInfo(e.type) == .Struct) return try expectEqualStructs(e.type, a.type); if (@typeInfo(e.type) == .Union) return try expectEqualUnions(e.type, a.type); try testing.expectEqual(e.type, a.type); try testing.expectEqual(e.alignment, a.alignment); } } fn expectEqualUnions(comptime expected: type, comptime actual: type) !void { const expectInfo = @typeInfo(expected).Union; const actualInfo = @typeInfo(actual).Union; try testing.expectEqual(expectInfo.layout, actualInfo.layout); try testing.expectEqual(expectInfo.decls.len, actualInfo.decls.len); try testing.expectEqual(expectInfo.fields.len, actualInfo.fields.len); inline for (expectInfo.fields, actualInfo.fields) |e, a| { try testing.expectEqualStrings(e.name, a.name); if (@typeInfo(e.type) == .Struct) return try expectEqualStructs(e.type, a.type); if (@typeInfo(e.type) == .Union) return try expectEqualUnions(e.type, a.type); try testing.expectEqual(e.type, a.type); try testing.expectEqual(e.alignment, a.alignment); } }
https://raw.githubusercontent.com/Raiden1411/zabi/beee3c26d0eaa6b426fdc62e66cf24626e3be6fa/src/meta/abi.zig
//! This module contains the representation of a chessboard and related features. const squares = @import("squares.zig"); pub const Piece = enum { pawn, knight, bishop, rook, queen, king, }; const Positions = struct { pawns: u64 = 0, knights: u64 = 0, bishops: u64 = 0, rooks: u64 = 0, queens: u64 = 0, king: u64 = 0, occupied: u64 = 0, /// Returns the mask of a given piece. pub inline fn get(self: *Positions, piece: Piece) *u64 { return switch (piece) { .pawn => &self.pawns, .knight => &self.knights, .bishop => &self.bishops, .rook => &self.rooks, .queen => &self.queens, .king => &self.king, }; } /// Returns the piece wich collides with the mask if any. pub inline fn collision(self: Positions, mask: u64) ?Piece { if (self.occupied & mask == 0) return null; if (self.pawns & mask > 0) return .pawn; if (self.knights & mask > 0) return .knight; if (self.bishops & mask > 0) return .bishop; if (self.rooks & mask > 0) return .rook; if (self.queens & mask > 0) return .queen; if (self.king & mask > 0) return .king; return null; } }; pub const Color = enum { white, black, pub inline fn other(self: Color) Color { return switch (self) { .white => .black, .black => .white, }; } }; const Castling = enum { K, // White kingside Q, // White queenside k, // Black kingside q, // Black queenside }; const CastlingRights = struct { K: bool = true, Q: bool = true, k: bool = true, q: bool = true, inline fn removeWhiteRights(self: *CastlingRights) void { self.K = false; self.Q = false; } inline fn removeBlackRights(self: *CastlingRights) void { self.k = false; self.q = false; } }; const Promotion = enum { knight, bishop, rook, queen, pub inline fn piece(self: Promotion) Piece { return switch (self) { .knight => .knight, .bishop => .bishop, .rook => .rook, .queen => .queen, }; } }; /// Representation of a move. pub const Move = struct { src: u64 = 0, dest: u64 = 0, side: Color = .white, piece: Piece = .pawn, en_passant: bool = false, capture: ?Piece = null, promotion: ?Promotion = null, castling: ?Castling = null, // src and dest must be specified for king null_move: bool = false, // Only change side is_check_evasion: bool = false, // Was in check before this move ? /// Compares two moves. pub inline fn sameAs(self: Move, other: Move) bool { if (self.src != other.src) return false; if (self.dest != other.dest) return false; if (self.promotion != other.promotion) return false; return true; } pub inline fn nullMove() Move { return .{ .null_move = true }; } }; /// Representation of a partial move (only source square, destination square and promotion if any). pub const PartialMove = struct { src: u64 = 0, dest: u64 = 0, promotion: ?Promotion = null, }; /// Representation of a chess board. pub const Board = struct { white: Positions = .{}, black: Positions = .{}, side: Color = .white, castling_rights: CastlingRights = .{}, en_passant: u64 = 0, halfmove_clock: u8 = 0, // Not implemented fullmove_number: u16 = 1, pub inline fn empty() Board { var board = Board{}; board.white.king = squares.e1; board.black.king = squares.e8; return board; } pub inline fn allies(self: *Board) *Positions { return switch (self.side) { .white => &self.white, .black => &self.black, }; } pub inline fn enemies(self: *Board) *Positions { return switch (self.side) { .white => &self.black, .black => &self.white, }; } /// Makes a move, doesn't check legality. pub inline fn make(self: *Board, move: Move) void { self.en_passant = 0; if (move.side == .black) self.fullmove_number += 1; if (!move.null_move) { blk: { if (move.castling != null) { const diff = switch (move.castling.?) { .K => squares.h1 | squares.f1, .Q => squares.a1 | squares.d1, .k => squares.h8 | squares.f8, .q => squares.a8 | squares.d8, }; self.allies().rooks ^= diff; self.allies().occupied ^= diff; break :blk; } if (move.promotion != null) { self.allies().pawns ^= move.dest; break :blk switch (move.promotion.?) { .knight => self.allies().knights ^= move.dest, .bishop => self.allies().bishops ^= move.dest, .rook => self.allies().rooks ^= move.dest, .queen => self.allies().queens ^= move.dest, }; } if (move.piece == .pawn) { if (move.src & squares.row_2 > 0 and move.dest & squares.row_4 > 0) { self.en_passant = move.dest << 8; } else if (move.src & squares.row_7 > 0 and move.dest & squares.row_5 > 0) { self.en_passant = move.dest >> 8; } } } const diff = move.src | move.dest; self.allies().get(move.piece).* ^= diff; self.allies().occupied ^= diff; if (move.capture != null) { const capture = blk: { if (move.en_passant) break :blk if (move.side == .white) move.dest << 8 else move.dest >> 8; break :blk move.dest; }; switch (capture) { squares.h1 => self.castling_rights.K = false, squares.a1 => self.castling_rights.Q = false, squares.h8 => self.castling_rights.k = false, squares.a8 => self.castling_rights.q = false, else => {}, } self.enemies().occupied ^= capture; self.enemies().get(move.capture.?).* ^= capture; } switch (move.src) { squares.e1 => self.castling_rights.removeWhiteRights(), squares.e8 => self.castling_rights.removeBlackRights(), squares.a1 => self.castling_rights.Q = false, squares.h1 => self.castling_rights.K = false, squares.a8 => self.castling_rights.q = false, squares.h8 => self.castling_rights.k = false, else => {}, } } self.side = self.side.other(); } pub inline fn copyAndMake(self: Board, move: Move) Board { var child = self; child.make(move); return child; } /// Determines a Move from the Board and the PartialMove pub inline fn completeMove(self: Board, partial: PartialMove) !Move { var board = self; var move = Move{ .src = partial.src, .dest = partial.dest, .side = board.side, .promotion = partial.promotion, .piece = board.allies().collision(partial.src) orelse return error.no_source_piece, .capture = board.enemies().collision(partial.dest), }; if (move.dest == board.en_passant and move.piece == .pawn) move.en_passant = true; if (move.piece == .king) { if (move.src == squares.e1 and move.dest == squares.g1) move.castling = .K; if (move.src == squares.e1 and move.dest == squares.c1) move.castling = .Q; if (move.src == squares.e8 and move.dest == squares.g8) move.castling = .k; if (move.src == squares.e8 and move.dest == squares.c8) move.castling = .q; } return move; } };
https://raw.githubusercontent.com/MattEstHaut/Victoire/ea23fc9af3b996ca528341371a4ea4951db73815/src/chess.zig
const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; // const allocator = gpa.allocator(); // _ = allocator; defer if (gpa.deinit() != .ok) { std.log.err("oh no, we've got a leak", .{}); } else { std.log.debug("memory managed correctly", .{}); }; const file = try std.fs.cwd().openFile(".env", .{}); defer file.close(); var buf: [1024]u8 = undefined; var stream = file.reader(); // Deliminatr 10 is the ASCII of \n while (try stream.readUntilDelimiterOrEof(&buf, 10)) |line| { var key_value = std.mem.split(u8, line, "="); const key = key_value.next() orelse ""; const value = key_value.next() orelse ""; if (std.mem.eql(u8, key, "my-api")) { std.debug.print("Value of my-api: {s}\n", .{value}); break; } } }
https://raw.githubusercontent.com/hajsf/zig-tutorial/19ef824f3430dec8987441f527e2b72f56abc3ed/zig-exe/src/env.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Writer = std.io.Writer; const dprint = std.debug.print; pub fn main() !void { const stdout_file = std.io.getStdOut().writer(); var bw = std.io.bufferedWriter(stdout_file); const stdout = bw.writer(); var gpa = std.heap.GeneralPurposeAllocator(.{}){}; var allocator = gpa.allocator(); const file = try std.fs.cwd().openFile("input.txt", .{}); defer file.close(); const input = try file.readToEndAlloc(allocator, 60 * 1024 * 1024); defer allocator.free(input); const output1 = try process1(allocator, input); try stdout.print("Result 1: {d}\n", .{output1}); const output2 = try process2(allocator, input); try stdout.print("Result 2: {d}\n", .{output2}); try bw.flush(); } const ProgramError = error{ AnyError, }; const Galaxy = struct { x: i64, y: i64, id: i64, pub fn sortByID(gs: *[]Galaxy) void { const Context = struct { fn lessThanFn(ctx: @This(), lhs: Galaxy, rhs: Galaxy) bool { _ = ctx; return lhs.id < rhs.id; } }; std.sort.insertion(Galaxy, gs.*, Context{}, Context.lessThanFn); } pub fn distanceTo(self: Galaxy, other: Galaxy) i64 { // manhattan distance const dx = self.x - other.x; const dy = self.y - other.y; return @intCast(@abs(dx) + @abs(dy)); } }; const Universe = struct { galaxies: []Galaxy, max_x: i64, max_y: i64, pub fn init(allocator: Allocator, input: []const u8) !Universe { var galaxies = std.ArrayList(Galaxy).init(allocator); var lines = std.mem.splitScalar(u8, input, '\n'); var max_x: i64 = 0; var max_y: i64 = 0; var y: i64 = 0; var id: i64 = 1; while (lines.next()) |line| { if (line.len == 0) continue; for (line, 0..) |c, x| { const _x: i64 = @intCast(x); const _y: i64 = @intCast(y); if (c == '#') { try galaxies.append(Galaxy{ .x = _x, .y = _y, .id = id, }); max_x = @max(_x, max_x); max_y = @max(_y, max_y); id += 1; } } y += 1; } return .{ .galaxies = try galaxies.toOwnedSlice(), .max_x = max_x, .max_y = max_y, }; } pub fn print(self: Universe, allocator: Allocator) !void { const stdout = std.io.getStdOut().writer(); // max values are 0-indexed const n_columns = self.max_x + 1; const n_rows = self.max_y + 1; var str = try allocator.alloc(u8, @intCast((n_columns + 1) * n_rows)); defer allocator.free(str); @memset(str, '.'); var newline_index = n_columns; while (newline_index < str.len) : (newline_index += n_columns + 1) { str[@intCast(newline_index)] = '\n'; } for (self.galaxies) |g| { const index = g.x + (n_columns + 1) * g.y; str[@intCast(index)] = '#'; } try stdout.print("{s}\n", .{str}); } pub fn isEmptyRow(self: Universe, y: i64) bool { for (self.galaxies) |g| { if (g.y == y) { return false; } } return true; } pub fn isEmptyColumn(self: Universe, x: i64) bool { for (self.galaxies) |g| { if (g.x == x) { return false; } } return true; } pub fn expandColumns(self: *Universe, from_x: i64, to_x: i64, factor: i64) void { const extra_columns = (factor - 1) * (from_x - to_x + 1); for (self.galaxies) |*g| { if (g.*.x < from_x) continue; if (from_x <= g.*.x and g.*.x <= to_x) { dprint("Expected expand to be called on empty column\n", .{}); unreachable; } g.*.x += extra_columns; } self.max_x += extra_columns; } pub fn expandRows(self: *Universe, from_y: i64, to_y: i64, factor: i64) void { const extra_rows = (factor - 1) * (from_y - to_y + 1); for (self.galaxies) |*g| { if (g.*.y < from_y) continue; if (from_y <= g.*.y and g.*.y <= to_y) { dprint("Expected expandRows to be called on empty rows\n", .{}); unreachable; } g.*.y += extra_rows; } self.max_y += extra_rows; } pub fn expand(self: *Universe, factor: i64) void { var x: i64 = 0; while (x <= self.max_x) : (x += 1) { if (!self.isEmptyColumn(x)) continue; // column x is empty // dprint("Expanding columns: {d}\n", .{x}); self.expandColumns(x, x, factor); x += factor - 1; } var y: i64 = 0; while (y <= self.max_y) : (y += 1) { if (!self.isEmptyRow(y)) continue; // column x is empty // dprint("Expanding rows: {d}\n", .{y}); self.expandRows(y, y, factor); y += factor - 1; } } }; fn process1(allocator: Allocator, input: []const u8) !i64 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const aa = arena.allocator(); // dprint("Input\n{s}\n", .{input}); var universe = try Universe.init(aa, input); // dprint("Universe:\n", .{}); // try universe.print(aa); universe.expand(2); // dprint("Universe expanded:\n", .{}); // try universe.print(aa); const gs = universe.galaxies; var distance_sum: i64 = 0; for (gs, 0..) |g1, i| { if (i == gs.len - 1) continue; for (gs[i + 1 ..]) |g2| { const distance = g1.distanceTo(g2); // dprint("Distance {d}->{d}: {d}\n", .{ g1.id, g2.id, distance }); distance_sum += distance; } } return distance_sum; } fn process2(allocator: Allocator, input: []const u8) !i64 { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const aa = arena.allocator(); // dprint("Input\n{s}\n", .{input}); var universe = try Universe.init(aa, input); // dprint("Universe:\n", .{}); // try universe.print(aa); universe.expand(1000000); // dprint("Universe expanded:\n", .{}); // try universe.print(aa); const gs = universe.galaxies; var distance_sum: i64 = 0; for (gs, 0..) |g1, i| { if (i == gs.len - 1) continue; for (gs[i + 1 ..]) |g2| { const distance = g1.distanceTo(g2); // dprint("Distance {d}->{d}: {d}\n", .{ g1.id, g2.id, distance }); distance_sum += distance; } } return distance_sum; } test "process 1: simple 1" { const data = \\...#...... \\.......#.. \\#......... \\.......... \\......#... \\.#........ \\.........# \\.......... \\.......#.. \\#...#..... ; const allocator = std.testing.allocator; try std.testing.expectEqual(@as(i64, 374), try process1(allocator, data)); }
https://raw.githubusercontent.com/rendellc/aoc/e9a0ac442477e2a1a04deb0384a941df166abfdb/2023-day11-zig/src/main.zig
const std = @import("std"); const Digit = enum(usize) { one = 1, two, three, four, five, six, seven, eight, nine, fn fromSlice(string: []const u8) ?Digit { return for (std.meta.tags(Digit)) |tag| { const name = @tagName(tag); if (name.len > string.len) continue; if (std.mem.eql(u8, name, string[0..name.len])) { break tag; } } else null; } }; pub fn solve(allocator: std.mem.Allocator, input_path: []const u8) !void { // https://www.openmsevenymind.net/Performance-of-reading-a-file-line-by-line-in-Zig/ const input_file = try std.fs.cwd().openFile(input_path, .{ .mode = .read_only }); defer input_file.close(); var buffered = std.io.bufferedReader(input_file.reader()); var reader = buffered.reader(); var line = std.ArrayList(u8).init(allocator); defer line.deinit(); var total: usize = 0; while (true) { defer line.clearRetainingCapacity(); reader.streamUntilDelimiter(line.writer(), '\n', null) catch |err| switch (err) { error.EndOfStream => break, else => return err, }; var idx: usize = 0; var found_first: bool = false; var last: usize = 0; while (idx < line.items.len) : (idx += 1) { // part 1 if (std.ascii.isDigit(line.items[idx])) { last = try std.fmt.charToDigit(line.items[idx], 10); if (!found_first) { found_first = true; total += 10 * last; } // part 2 } else if (Digit.fromSlice(line.items[idx..])) |digit| { last = @intFromEnum(digit); if (!found_first) { found_first = true; total += 10 * last; } // We need to decrement index by two: // 1 is added by the while loop // 1 is the maximum overlap between number names: sevenine, eighthree // This is completely optional, but allows us to skip parts of the line. idx += @tagName(digit).len - 2; } } total += last; } std.debug.print("total: {}\n", .{total}); } pub fn main() !void { // Set up the General Purpose allocator, this will track memory leaks, etc. var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); defer _ = gpa.deinit(); // Parse the command line arguments to get the input file const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len < 2) { std.debug.print("No input file passed\n", .{}); return; } try solve(allocator, args[1]); }
https://raw.githubusercontent.com/arrufat/advent-of-code/5485808de0bdb1fb2c72df51604de1c2ee511192/2023/src/day01.zig
const std = @import("std"); pub fn Queue(comptime T: type) type { return struct { const Self = @This(); listData: []T = undefined, length: usize = 0, capacity: usize = 0, front: usize = 0, mem_arena: ?std.heap.ArenaAllocator = undefined, mem_allocator: std.mem.Allocator = undefined, pub fn init(self: *Self, allctr: std.mem.Allocator, cap:usize) !void{ if (self.mem_arena == null) { self.mem_arena = std.heap.ArenaAllocator.init(allctr); self.mem_allocator = self.mem_arena.?.allocator(); } self.capacity = cap; self.listData = try self.mem_allocator.alloc(T, self.capacity); @memset(self.listData,@as(T, 0)); } pub fn deinit(self: *Self)void{ if (self.mem_arena == null) { return; }else { self.mem_arena.?.deinit(); } } pub fn enQueue(self: *Self, val: T) !void{ if (self.length == self.capacity) { std.debug.print( "Queue capacity met", .{}); return; } const rear = (self.front + self.length) % self.capacity; self.listData[rear] = val; self.length += 1; } pub fn deQueue(self: *Self) !void{ if (self.length == 0) { @panic( "Queue is empty" ); }else{ //const num = self.listData[self.front]; self.front = (self.front + 1) % self.capacity ; self.length -= 1; } } pub fn print(self: *Self) !void { std.debug.print( "\nPrinting Queue\n", .{}); var i:usize = self.front; while (i < self.capacity) : (i += 1) { std.debug.print("element: {}\n", .{self.listData[i]}); } } }; } var integerQueue = Queue(i32) {}; pub fn main() !void { // instantiate allocator const allocator = std.heap.page_allocator; const queueCap: usize = 10; //instantiate Queue w/ allocator try integerQueue.init(allocator, queueCap); defer integerQueue.deinit(); var i:i32 = 0; while (i < queueCap) : (i += 1) { try integerQueue.enQueue(i); } try integerQueue.print(); try integerQueue.deQueue(); try integerQueue.deQueue(); try integerQueue.deQueue(); try integerQueue.print(); }
https://raw.githubusercontent.com/anthony-aleman/Zig-Data-Structures/9e717e711014a4edf92c420b00ae62b947f32193/queue/src/main.zig
const std = @import("std"); const objc = @import("objc"); const runtime_support = @import("Runtime-Support"); pub const NSTableViewSelectors = struct { pub fn dataSource() objc.Sel { if (_sel_dataSource == null) { _sel_dataSource = objc.Sel.registerName("dataSource"); } return _sel_dataSource.?; } pub fn setDataSource() objc.Sel { if (_sel_setDataSource == null) { _sel_setDataSource = objc.Sel.registerName("setDataSource:"); } return _sel_setDataSource.?; } pub fn delegate() objc.Sel { if (_sel_delegate == null) { _sel_delegate = objc.Sel.registerName("delegate"); } return _sel_delegate.?; } pub fn setDelegate() objc.Sel { if (_sel_setDelegate == null) { _sel_setDelegate = objc.Sel.registerName("setDelegate:"); } return _sel_setDelegate.?; } pub fn headerView() objc.Sel { if (_sel_headerView == null) { _sel_headerView = objc.Sel.registerName("headerView"); } return _sel_headerView.?; } pub fn setHeaderView() objc.Sel { if (_sel_setHeaderView == null) { _sel_setHeaderView = objc.Sel.registerName("setHeaderView:"); } return _sel_setHeaderView.?; } pub fn rowHeight() objc.Sel { if (_sel_rowHeight == null) { _sel_rowHeight = objc.Sel.registerName("rowHeight"); } return _sel_rowHeight.?; } pub fn setRowHeight() objc.Sel { if (_sel_setRowHeight == null) { _sel_setRowHeight = objc.Sel.registerName("setRowHeight:"); } return _sel_setRowHeight.?; } pub fn noteHeightOfRowsWithIndexesChanged() objc.Sel { if (_sel_noteHeightOfRowsWithIndexesChanged == null) { _sel_noteHeightOfRowsWithIndexesChanged = objc.Sel.registerName("noteHeightOfRowsWithIndexesChanged:"); } return _sel_noteHeightOfRowsWithIndexesChanged.?; } pub fn addTableColumn() objc.Sel { if (_sel_addTableColumn == null) { _sel_addTableColumn = objc.Sel.registerName("addTableColumn:"); } return _sel_addTableColumn.?; } pub fn scrollRowToVisible() objc.Sel { if (_sel_scrollRowToVisible == null) { _sel_scrollRowToVisible = objc.Sel.registerName("scrollRowToVisible:"); } return _sel_scrollRowToVisible.?; } pub fn reloadDataForRowIndexesColumnIndexes() objc.Sel { if (_sel_reloadDataForRowIndexesColumnIndexes == null) { _sel_reloadDataForRowIndexesColumnIndexes = objc.Sel.registerName("reloadDataForRowIndexes:columnIndexes:"); } return _sel_reloadDataForRowIndexesColumnIndexes.?; } pub fn selectedRow() objc.Sel { if (_sel_selectedRow == null) { _sel_selectedRow = objc.Sel.registerName("selectedRow"); } return _sel_selectedRow.?; } pub fn numberOfSelectedRows() objc.Sel { if (_sel_numberOfSelectedRows == null) { _sel_numberOfSelectedRows = objc.Sel.registerName("numberOfSelectedRows"); } return _sel_numberOfSelectedRows.?; } pub fn beginUpdates() objc.Sel { if (_sel_beginUpdates == null) { _sel_beginUpdates = objc.Sel.registerName("beginUpdates"); } return _sel_beginUpdates.?; } pub fn endUpdates() objc.Sel { if (_sel_endUpdates == null) { _sel_endUpdates = objc.Sel.registerName("endUpdates"); } return _sel_endUpdates.?; } pub fn insertRowsAtIndexesWithAnimation() objc.Sel { if (_sel_insertRowsAtIndexesWithAnimation == null) { _sel_insertRowsAtIndexesWithAnimation = objc.Sel.registerName("insertRowsAtIndexes:withAnimation:"); } return _sel_insertRowsAtIndexesWithAnimation.?; } pub fn removeRowsAtIndexesWithAnimation() objc.Sel { if (_sel_removeRowsAtIndexesWithAnimation == null) { _sel_removeRowsAtIndexesWithAnimation = objc.Sel.registerName("removeRowsAtIndexes:withAnimation:"); } return _sel_removeRowsAtIndexesWithAnimation.?; } pub fn hideRowsAtIndexesWithAnimation() objc.Sel { if (_sel_hideRowsAtIndexesWithAnimation == null) { _sel_hideRowsAtIndexesWithAnimation = objc.Sel.registerName("hideRowsAtIndexes:withAnimation:"); } return _sel_hideRowsAtIndexesWithAnimation.?; } pub fn unhideRowsAtIndexesWithAnimation() objc.Sel { if (_sel_unhideRowsAtIndexesWithAnimation == null) { _sel_unhideRowsAtIndexesWithAnimation = objc.Sel.registerName("unhideRowsAtIndexes:withAnimation:"); } return _sel_unhideRowsAtIndexesWithAnimation.?; } pub fn hiddenRowIndexes() objc.Sel { if (_sel_hiddenRowIndexes == null) { _sel_hiddenRowIndexes = objc.Sel.registerName("hiddenRowIndexes"); } return _sel_hiddenRowIndexes.?; } var _sel_dataSource: ?objc.Sel = null; var _sel_setDataSource: ?objc.Sel = null; var _sel_delegate: ?objc.Sel = null; var _sel_setDelegate: ?objc.Sel = null; var _sel_headerView: ?objc.Sel = null; var _sel_setHeaderView: ?objc.Sel = null; var _sel_rowHeight: ?objc.Sel = null; var _sel_setRowHeight: ?objc.Sel = null; var _sel_noteHeightOfRowsWithIndexesChanged: ?objc.Sel = null; var _sel_addTableColumn: ?objc.Sel = null; var _sel_scrollRowToVisible: ?objc.Sel = null; var _sel_reloadDataForRowIndexesColumnIndexes: ?objc.Sel = null; var _sel_selectedRow: ?objc.Sel = null; var _sel_numberOfSelectedRows: ?objc.Sel = null; var _sel_beginUpdates: ?objc.Sel = null; var _sel_endUpdates: ?objc.Sel = null; var _sel_insertRowsAtIndexesWithAnimation: ?objc.Sel = null; var _sel_removeRowsAtIndexesWithAnimation: ?objc.Sel = null; var _sel_hideRowsAtIndexesWithAnimation: ?objc.Sel = null; var _sel_unhideRowsAtIndexesWithAnimation: ?objc.Sel = null; var _sel_hiddenRowIndexes: ?objc.Sel = null; }; pub const NSTableViewDataSourceSelectors = struct { pub fn numberOfRowsInTableView() objc.Sel { if (_sel_numberOfRowsInTableView == null) { _sel_numberOfRowsInTableView = objc.Sel.registerName("numberOfRowsInTableView:"); } return _sel_numberOfRowsInTableView.?; } pub fn tableViewObjectValueForTableColumnRow() objc.Sel { if (_sel_tableViewObjectValueForTableColumnRow == null) { _sel_tableViewObjectValueForTableColumnRow = objc.Sel.registerName("tableView:objectValueForTableColumn:row:"); } return _sel_tableViewObjectValueForTableColumnRow.?; } var _sel_numberOfRowsInTableView: ?objc.Sel = null; var _sel_tableViewObjectValueForTableColumnRow: ?objc.Sel = null; }; pub const NSTableViewDelegateSelectors = struct { pub fn tableViewDidRemoveRowViewForRow() objc.Sel { if (_sel_tableViewDidRemoveRowViewForRow == null) { _sel_tableViewDidRemoveRowViewForRow = objc.Sel.registerName("tableView:didRemoveRowView:forRow:"); } return _sel_tableViewDidRemoveRowViewForRow.?; } pub fn tableViewHeightOfRow() objc.Sel { if (_sel_tableViewHeightOfRow == null) { _sel_tableViewHeightOfRow = objc.Sel.registerName("tableView:heightOfRow:"); } return _sel_tableViewHeightOfRow.?; } pub fn tableViewSelectionDidChange() objc.Sel { if (_sel_tableViewSelectionDidChange == null) { _sel_tableViewSelectionDidChange = objc.Sel.registerName("tableViewSelectionDidChange:"); } return _sel_tableViewSelectionDidChange.?; } var _sel_tableViewDidRemoveRowViewForRow: ?objc.Sel = null; var _sel_tableViewHeightOfRow: ?objc.Sel = null; var _sel_tableViewSelectionDidChange: ?objc.Sel = null; };
https://raw.githubusercontent.com/ritalin/zig-7gui-macos/52ee58a27d60c90f48c9dc1025392bf977d01b8b/src/fw/AppKit/NSTableView/selector.zig
const std = @import("std"); const find = @import("./find.zig"); const du = @import("./du.zig"); const cat = @import("./cat.zig"); const echo = @import("./echo.zig"); const basename = @import("./basename.zig"); const dirname = @import("./dirname.zig"); const time = @import("./time.zig"); const rm = @import("./rm.zig"); const touch = @import("./touch.zig"); const ls = @import("./ls.zig"); const usage = \\Usage: rene <COMMAND> [OPTIONS] \\ \\COMMANDS: \\ find, du, cat, echo, basename, dirname, time, rm, touch, ls \\ \\Run 'rene <command> --help' for details about a specific command. \\ \\ ; pub fn main() !void { const stdout = std.io.getStdOut().writer(); var arena_instance = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena_instance.deinit(); const arena = arena_instance.allocator(); var args = try std.process.argsAlloc(arena); var cmd = std.fs.path.basename(args[0]); args = args[1..]; // if exe name is a supported cmd name => run it if (parseCmd(cmd)) |runner| { try runner(arena, args); return; } // otherwise => use next arg if (args.len == 0 or (args.len > 0 and std.mem.eql(u8, args[0], "--help"))) { try stdout.writeAll(usage); return; } cmd = args[0]; args = args[1..]; // supported cmd => run it if (parseCmd(cmd)) |runner| { try runner(arena, args); return; } // unknown cmd try stdout.writeAll(usage); try stdout.print("error: unknown command '{s}'\n", .{cmd}); std.process.exit(1); } const CmdRunner = *const fn (std.mem.Allocator, [][]const u8) anyerror!void; fn parseCmd(name: []const u8) ?CmdRunner { for (commands) |cmd| { if (std.mem.eql(u8, cmd.name, name)) { return cmd.runner; } } return null; } const Command = struct { name: []const u8, runner: CmdRunner, }; const commands = &[_]Command{ .{ .name = "du", .runner = du.run }, .{ .name = "find", .runner = find.run }, .{ .name = "cat", .runner = cat.run }, .{ .name = "echo", .runner = echo.run }, .{ .name = "basename", .runner = basename.run }, .{ .name = "dirname", .runner = dirname.run }, .{ .name = "time", .runner = time.run }, .{ .name = "rm", .runner = rm.run }, .{ .name = "touch", .runner = touch.run }, .{ .name = "ls", .runner = ls.run }, };
https://raw.githubusercontent.com/aburdulescu/rene/b5db0d0ad2cb8b8b288ce4905dc9c733ce63e0ef/src/main.zig