text
stringlengths
32
314k
url
stringlengths
93
243
const std = @import("std"); const Type = std.builtin.Type; const testing = std.testing; // turns out the mask should be the size of the full struct anyway. might make this public later to be used in later // truncation but whatever // fn calc(comptime T: type, comptime field: FieldEnum(T)) type { // if (@typeInfo(T).Struct.layout != .Packed) { // @compileError("Cannot create field mask for non-packed struct"); // } // const offset = @bitOffsetOf(T, @tagName(field)); // const size = @bitSizeOf(@TypeOf(@field(@as(T, undefined), @tagName(field)))); // // return Int(.unsigned, offset + size); // } // generates a mask to isolate a field of a packed struct while keeping it shifted relative to its bit offset in the struct. // the field's value is effectively left shifted by its bit offset in the struct and bits outside the field are masked out pub fn makeTruncMask(comptime T: type, comptime field: []const u8) @Type(.{ .Int = .{ .signedness = .unsigned, .bits = @bitSizeOf(T) } }) { const offset = @bitOffsetOf(T, field); const size = @bitSizeOf(@TypeOf(@field(@as(T, undefined), field))); const size_mask = (1 << size) - 1; return size_mask << offset; } test makeTruncMask { const T = packed struct(u16) { a: u4, b: u3, c: u9, }; try testing.expectEqual(0x000F, makeTruncMask(T, "a")); try testing.expectEqual(0x0070, makeTruncMask(T, "b")); try testing.expectEqual(0xFF80, makeTruncMask(T, "c")); }
https://raw.githubusercontent.com/Khitiara/imaginarium/805dd706a8e7b4f9f64fd0df932ad12d1aa1ea7f/src/util/masking.zig
const ascii = @import("std").ascii; const alphabet = "abcdefghijklmnopqrstuvwxyz"; pub fn isPangram(str: []const u8) bool { var marks = [_]bool{false} ** 26; for (str) |strChar| { for (alphabet) |alphabetChar, i| { if (ascii.toLower(strChar) == alphabetChar) { marks[i] = true; break; } } } for (marks) |mark| if (mark == false) return false; return true; }
https://raw.githubusercontent.com/alternateved/exercism/ba9dd5d5c832f1ab345e9a94ba9294717669cc76/zig/pangram/pangram.zig
const std = @import("std"); const backend = @import("../backend.zig"); const Size = @import("../data.zig").Size; /// Toggle switch flat peer pub const FlatToggleSwitch = struct { peer: backend.PeerType, canvas: backend.Canvas, label: [:0]const u8 = "", enabled: bool = true, pub usingnamespace backend.Events(FlatToggleSwitch); pub fn create() !FlatToggleSwitch { const canvas = try backend.Canvas.create(); const events = backend.getEventUserData(canvas.peer); events.class.drawHandler = draw; return FlatToggleSwitch{ .peer = canvas.peer, .canvas = canvas }; } // TODO: themes and custom styling fn draw(ctx: *backend.Canvas.DrawContext, data: usize) void { const events = @intToPtr(*backend.EventUserData, data); const self = @intToPtr(?*FlatToggleSwitch, events.classUserdata).?; const width = @intCast(u32, backend.getWidthFromPeer(events.peer)); const height = @intCast(u32, backend.getHeightFromPeer(events.peer)); if (self.enabled) { ctx.setColor(0.8, 0.8, 0.8); } else { ctx.setColor(0.7, 0.7, 0.7); } ctx.rectangle(0, 0, width, height); ctx.fill(); const text = self.label; var layout = backend.Canvas.DrawContext.TextLayout.init(); defer layout.deinit(); ctx.setColor(1, 1, 1); layout.setFont(.{ .face = "serif", .size = 12.0 }); ctx.text(0, 0, layout, text); ctx.fill(); } pub fn setLabel(self: *FlatToggleSwitch, label: [:0]const u8) void { self.label = label; const events = backend.getEventUserData(self.peer); events.classUserdata = @ptrToInt(self); self.requestDraw() catch {}; } pub fn getLabel(self: *const FlatToggleSwitch) [:0]const u8 { return self.label; } pub fn setEnabled(self: *FlatToggleSwitch, enabled: bool) void { self.enabled = enabled; } pub fn getPreferredSize_impl(self: *const FlatToggleSwitch) Size { _ = self; return Size.init(300, 100); } };
https://raw.githubusercontent.com/SaicharanKandukuri/capy-299f994/512c88540a160cea2e824c363e7261679b558add/src/flat/toggle_switch.zig
const std = @import("std"); const gpu = @import("mach-gpu"); const glfw = @import("mach-glfw"); const util = @import("../util.zig"); const math = @import("../utils/math.zig"); const Rect = math.Rect; const MaxElements = @import("ezui.zig").MaxElements; const SwapChainFormat = gpu.Texture.Format.bgra8_unorm; pub const Renderer = struct { device: *gpu.Device, queue: *gpu.Queue, pipeline: *gpu.RenderPipeline, swapchain: *gpu.SwapChain, swapchain_desc: gpu.SwapChain.Descriptor, surface: *gpu.Surface, rect_buffer: *gpu.Buffer, bind_group: *gpu.BindGroup, pub fn init(window: glfw.Window) Renderer { gpu.Impl.init(); const instance = gpu.createInstance(null); if (instance == null) { std.log.err("Renderer, webgpu: Failed to create GPU instance\n", .{}); std.process.exit(1); } var surface: *gpu.Surface = undefined; if (util.createSurfaceForWindow(instance.?, window, comptime util.detectGLFWOptions())) |surface_| { surface = surface_; } else |err| { std.log.err("Renderer, webgpu: Failed to create Surface, {}\n", .{err}); } var response: util.RequestAdapterResponse = undefined; instance.?.requestAdapter(&gpu.RequestAdapterOptions{ .compatible_surface = surface, .power_preference = .undefined, .force_fallback_adapter = .false, }, &response, util.requestAdapterCallback); if (response.status != .success) { std.log.err("Renderer, webgpu: Failed to create GPU adapter: {s}\n", .{response.message.?}); std.process.exit(1); } // Print which adapter we are using. var props = std.mem.zeroes(gpu.Adapter.Properties); response.adapter.?.getProperties(&props); std.log.info("found {s} backend on {s} adapter: {s}, {s}\n", .{ props.backend_type.name(), props.adapter_type.name(), props.name, props.driver_description, }); const device = response.adapter.?.createDevice(null); if (device == null) { std.log.err("Renderer, webgpu: Failed to create GPU device\n", .{}); std.process.exit(1); } device.?.setUncapturedErrorCallback({}, util.printUnhandledErrorCallback); const swapchain_desc = gpu.SwapChain.Descriptor{ .label = "basic swap chain", .usage = .{ .render_attachment = true }, .format = SwapChainFormat, .width = window.getSize().width, .height = window.getSize().height, .present_mode = .fifo, }; const swapchain = device.?.createSwapChain(surface, &swapchain_desc); const rect_buffer = device.?.createBuffer(&.{ .usage = .{ .storage = true, .copy_dst = true }, .size = @sizeOf(Rect) * MaxElements, }); const vs = \\ struct Rect { \\ pos: vec2<f32>, \\ width: f32, \\ height: f32, \\ color: vec3<f32>, \\ } \\ \\ struct VertexOutput{ \\ @builtin(position) Position: vec4<f32>, \\ @location(0) color: vec3<f32>, \\ } \\ \\ @group(0) @binding(0) var<storage, read> rects: array<Rect>; \\ \\ @vertex fn main( \\ @builtin(vertex_index) VertexIndex : u32 \\ ) -> VertexOutput{ \\ \\ var out: VertexOutput; \\ \\ var rect = rects[VertexIndex / 6]; \\ var positions = array<vec2<f32>, 6>( \\ vec2<f32>(0.0, 0.0), // bottom-left \\ vec2<f32>(0.0, 1.0), // top-left \\ vec2<f32>(1.0, 0.0), // bottom-right \\ vec2<f32>(1.0, 0.0), // bottom-right \\ vec2<f32>(0.0, 1.0), // top-left \\ vec2<f32>(1.0, 1.0), // top-right \\ ); \\ var pos = positions[VertexIndex % 6]; \\ // TODO: HOW DOES THIS WORK? \\ pos.x *= rect.width; \\ pos.y *= rect.height; \\ pos.x += rect.pos.x; \\ pos.y += rect.pos.y; \\ // Raster -> NDC \\ // TODO: Remove hardcoded 250 value \\ pos.x = pos.x / 540 - 1.0; \\ pos.y = 1.0 - pos.y / 360; \\ \\ out.Position = vec4<f32>(pos.x, pos.y, 0.0, 1.0); \\ out.color = rect.color; \\ return out; \\ } ; const vs_module = device.?.createShaderModuleWGSL("my vertex shader", vs); const fs = \\ \\ struct VertexInput{ \\ @builtin(position) Position: vec4<f32>, \\ @location(0) color: vec3<f32>, \\ } \\ \\ @fragment fn main(vi: VertexInput) -> @location(0) vec4<f32> { \\ return vec4<f32>(vi.color, 1.0); \\ } ; const fs_module = device.?.createShaderModuleWGSL("my fragment shader", fs); const color_target = gpu.ColorTargetState{ .format = SwapChainFormat, .write_mask = gpu.ColorWriteMaskFlags.all, }; const fragment = gpu.FragmentState.init(.{ .module = fs_module, .entry_point = "main", .targets = &.{color_target}, }); const pipeline_descriptor = gpu.RenderPipeline.Descriptor{ .fragment = &fragment, .layout = null, .depth_stencil = null, .vertex = gpu.VertexState{ .module = vs_module, .entry_point = "main", }, .multisample = .{}, .primitive = .{}, }; const pipeline = device.?.createRenderPipeline(&pipeline_descriptor); const bind_group = device.?.createBindGroup(&gpu.BindGroup.Descriptor.init(.{ .layout = pipeline.getBindGroupLayout(0), .entries = &.{ gpu.BindGroup.Entry.buffer(0, rect_buffer, 0, @sizeOf(Rect) * MaxElements), }, })); vs_module.release(); fs_module.release(); return Renderer{ .device = device.?, .queue = device.?.getQueue(), .pipeline = pipeline, .swapchain = swapchain, .swapchain_desc = swapchain_desc, .surface = surface, .rect_buffer = rect_buffer, .bind_group = bind_group, }; } pub fn resizeSwapchain(renderer: *Renderer, width: u32, height: u32) void { _ = renderer; std.log.info("hi!!!, w:{d}, h:{d}\n", .{ width, height }); // TODO: Do something about re-sizing // renderer.swapchain_desc.width = width; // renderer.swapchain_desc.height = height; // renderer.swapchain.release(); // renderer.swapchain = renderer.device.createSwapChain(renderer.surface, &renderer.swapchain_desc); } pub fn render(renderer: *Renderer, rects: []Rect) void { renderer.device.tick(); renderer.queue.writeBuffer(renderer.rect_buffer, 0, rects); const backbuffer_view = renderer.swapchain.getCurrentTextureView().?; const color_attachment = gpu.RenderPassColorAttachment{ .view = backbuffer_view, .resolve_target = null, .clear_value = gpu.Color{ .r = 1.0, .g = 1.0, .b = 1.0, .a = 1.0 }, .load_op = .clear, .store_op = .store, }; const encoder = renderer.device.createCommandEncoder(null); const render_pass_info = gpu.RenderPassDescriptor.init(.{ .color_attachments = &.{color_attachment}, }); const pass = encoder.beginRenderPass(&render_pass_info); pass.setPipeline(renderer.pipeline); pass.setBindGroup(0, renderer.bind_group, &.{}); pass.draw(@intCast(rects.len * 6), 1, 0, 0); pass.end(); pass.release(); var command = encoder.finish(null); encoder.release(); renderer.queue.submit(&[_]*gpu.CommandBuffer{command}); command.release(); renderer.swapchain.present(); backbuffer_view.release(); } pub fn deinit(renderer: *Renderer) void { renderer.bind_group.release(); renderer.rect_buffer.release(); } };
https://raw.githubusercontent.com/Enigma-IIITS/EZUI/f1b54a75b9735544b80c1f391f25a47b21003b6b/src/ezui/renderer.zig
//! implementation of some segment tree algorithms const std = @import("std"); const assert = std.debug.assert; const print = std.debug.print; const expect = std.testing.expect; const Allocator = std.mem.Allocator; pub fn SegmentTree( comptime Type: type, comptime OpFn: fn (Type, Type) Type, ) type { return struct { const Self = @This(); backing: []Type, allocator: Allocator, length: u64, pub fn init(array: []Type, allocator: Allocator) !Self { var allocated = try allocator.alloc(Type, getCapacity(array.len)); var tmp = Self{ .backing = allocated, .allocator = allocator, .length = array.len }; tmp.build(array, 0, array.len - 1, 0); return tmp; } pub fn deinit(self: *Self) void { if (self.backing.len == 0) { return; } self.allocator.free(self.backing); } fn build(self: *Self, array: []Type, low: u64, high: u64, pos: u64) void { if (low == high) { self.backing[pos] = array[low]; return; } const mid = getMid(low, high); const leftIdx = getLeft(pos); const rightIdx = getRight(pos); self.build(array, low, mid, leftIdx); self.build(array, mid + 1, high, rightIdx); self.backing[pos] = OpFn(self.backing[leftIdx], self.backing[rightIdx]); } pub fn update(self: *Self, index: u64, value: Type) void { self.updateRecursive(index, value, 0, self.length - 1, 0); } fn updateRecursive(self: *Self, index: u64, value: Type, start: u64, end: u64, pos: u64) void { if (start == end) { self.backing[pos] = value; return; } const mid = getMid(start, end); const leftIdx = getLeft(pos); const rightIdx = getRight(pos); if (index > mid) { self.updateRecursive(index, value, mid + 1, end, rightIdx); } else { self.updateRecursive(index, value, start, mid, leftIdx); } self.backing[pos] = OpFn(self.backing[leftIdx], self.backing[rightIdx]); } pub fn query(self: *Self, start: u64, end: u64) Type { return self.queryRecursive(start, end, 0, self.length - 1, 0); } fn queryRecursive(self: *Self, qstart: u64, qend: u64, start: u64, end: u64, pos: u64) Type { if (qstart == start and qend == end) { return self.backing[pos]; } const mid = getMid(start, end); if (qstart > mid) { return self.queryRecursive(qstart, qend, mid + 1, end, getRight(pos)); } else if (qend <= mid) { return self.queryRecursive(qstart, qend, start, mid, getLeft(pos)); } const left = self.queryRecursive(qstart, mid, start, mid, getLeft(pos)); const right = self.queryRecursive(mid + 1, qend, mid + 1, end, getRight(pos)); return OpFn(left, right); } // algo: x = closest power of 2 >= n // return 2x - 1 fn getCapacity(n: u64) u64 { if (n > 1) { const leadingZeroes: u7 = @clz(n - 1); const shift: u6 = @intCast(64 - leadingZeroes + 1); const one: u64 = 1; return (one << shift) - 1; } return 1; } inline fn getMid(low: u64, high: u64) u64 { assert(low <= high); return low + (high - low) / 2; } inline fn getParent(idx: u64) u64 { return idx / 2; } inline fn getLeft(idx: u64) u64 { return 2 * idx + 1; } inline fn getRight(idx: u64) u64 { return 2 * idx + 2; } }; } fn lessThan(a: i8, b: i8) i8 { return if (a < b) a else b; } fn sum(a: i8, b: i8) i8 { return a + b; } test "Test find all" { const allocator = std.testing.allocator; var arr = [_]i8{ 5, 3, 7, 1, 4, 2 }; var rsq = try SegmentTree(i8, sum).init(&arr, allocator); defer rsq.deinit(); try expect(rsq.query(0, 5) == 22); } test "Test find middle" { const allocator = std.testing.allocator; var arr = [_]i8{ 5, 3, 7, 1, 4, 2 }; var rsq = try SegmentTree(i8, sum).init(&arr, allocator); defer rsq.deinit(); try expect(rsq.query(2, 4) == 12); } test "Test find ends" { const allocator = std.testing.allocator; var arr = [_]i8{ 5, 3, 7, 1, 4, 2 }; var rsq = try SegmentTree(i8, sum).init(&arr, allocator); defer rsq.deinit(); try expect(rsq.query(0, 2) == 15); try expect(rsq.query(3, 5) == 7); } test "Test minimum" { const allocator = std.testing.allocator; var arr = [_]i8{ 5, 3, 7, 1, 4, 2 }; var rmq = try SegmentTree(i8, lessThan).init(&arr, allocator); defer rmq.deinit(); try expect(rmq.query(0, 2) == 3); try expect(rmq.query(3, 5) == 1); try expect(rmq.query(0, 5) == 1); try expect(rmq.query(1, 4) == 1); try expect(rmq.query(4, 5) == 2); } test "test update" { const allocator = std.testing.allocator; var arr = [_]i8{ 0, 2, 3, 1, 2, 1 }; var rmq = try SegmentTree(i8, lessThan).init(&arr, allocator); defer rmq.deinit(); rmq.update(0, 5); rmq.update(1, 3); rmq.update(2, 7); rmq.update(3, 1); rmq.update(4, 4); rmq.update(5, 2); try expect(rmq.query(0, 2) == 3); try expect(rmq.query(3, 5) == 1); try expect(rmq.query(0, 5) == 1); try expect(rmq.query(1, 4) == 1); try expect(rmq.query(4, 5) == 2); }
https://raw.githubusercontent.com/JosefNatanael/zig-ds/f8e4d503115e2e717f8eb76e55d93cb562d1671e/segment-simple.zig
// Copyright (c) 2022-2023, sin-ack <sin-ack@protonmail.com> // // SPDX-License-Identifier: GPL-3.0-only const std = @import("std"); const Allocator = std.mem.Allocator; const debug = @import("../../debug.zig"); const bytecode = @import("../bytecode.zig"); const Liveness = bytecode.astcode.Liveness; const RegisterPool = bytecode.lowcode.RegisterPool; const LOW_EXECUTABLE_DUMP_DEBUG = debug.LOW_EXECUTABLE_DUMP_DEBUG; pub fn lowerExecutable(allocator: Allocator, ast_executable: *bytecode.astcode.Executable) !bytecode.lowcode.Executable.Ref { var low_executable = try bytecode.lowcode.Executable.create(allocator, ast_executable.definition_script); errdefer low_executable.unref(); for (ast_executable.blocks.items) |block| { try lowerBlock(allocator, low_executable.value, block); } if (LOW_EXECUTABLE_DUMP_DEBUG) std.debug.print("Executable dump: {}\n", .{low_executable.value}); return low_executable; } fn lowerBlock(allocator: Allocator, executable: *bytecode.lowcode.Executable, ast_block: *bytecode.astcode.Block) !void { var liveness = try Liveness.analyzeBlock(allocator, ast_block); defer liveness.deinit(allocator); var register_pool = try RegisterPool.init(allocator); defer register_pool.deinit(allocator); const low_block_index = try executable.makeBlock(); const low_block = executable.getBlock(low_block_index); const push_registers_inst_offset = try low_block.reserveInstruction(allocator); for (ast_block.instructions.items, 0..) |inst, i| { try lowerInstruction(allocator, low_block, &liveness, &register_pool, inst); register_pool.expireOldIntervals(i); } // TODO: better source location low_block.setInstruction(push_registers_inst_offset, .PushRegisters, .zero, register_pool.clobbered_registers, ast_block.instructions.items[0].source_range); low_block.seal(); } fn lowerInstruction( allocator: Allocator, block: *bytecode.lowcode.Block, liveness: *Liveness, register_pool: *RegisterPool, inst: bytecode.astcode.Instruction, ) !void { switch (inst.opcode) { .Send => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); const payload = inst.payload.Send; try block.addInstruction(allocator, .Send, target, .{ .receiver_location = register_pool.getAllocatedRegisterFor(payload.receiver_location), .selector = payload.selector, .send_index = payload.send_index, }, inst.source_range); }, .PrimSend => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); const payload = inst.payload.PrimSend; try block.addInstruction(allocator, .PrimSend, target, .{ .receiver_location = register_pool.getAllocatedRegisterFor(payload.receiver_location), .index = payload.index, }, inst.source_range); }, .SelfSend => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); const payload = inst.payload.SelfSend; try block.addInstruction(allocator, .SelfSend, target, .{ .selector = payload.selector, .send_index = payload.send_index, }, inst.source_range); }, .SelfPrimSend => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); const payload = inst.payload.SelfPrimSend; try block.addInstruction(allocator, .SelfPrimSend, target, .{ .index = payload.index }, inst.source_range); }, .PushConstantSlot => { const payload = inst.payload.PushParentableSlot; const name_location = register_pool.getAllocatedRegisterFor(payload.name_location); const value_location = register_pool.getAllocatedRegisterFor(payload.value_location); try block.addInstruction(allocator, .PushConstantSlot, .zero, .{ .name_location = name_location, .value_location = value_location, .is_parent = payload.is_parent, }, inst.source_range); }, .PushAssignableSlot => { const payload = inst.payload.PushParentableSlot; const name_location = register_pool.getAllocatedRegisterFor(payload.name_location); const value_location = register_pool.getAllocatedRegisterFor(payload.value_location); try block.addInstruction(allocator, .PushAssignableSlot, .zero, .{ .name_location = name_location, .value_location = value_location, .is_parent = payload.is_parent, }, inst.source_range); }, .PushArgumentSlot => { const payload = inst.payload.PushNonParentSlot; const name_location = register_pool.getAllocatedRegisterFor(payload.name_location); const value_location = register_pool.getAllocatedRegisterFor(payload.value_location); try block.addInstruction(allocator, .PushArgumentSlot, .zero, .{ .name_location = name_location, .value_location = value_location, }, inst.source_range); }, .CreateInteger => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); try block.addInstruction(allocator, .CreateInteger, target, inst.payload.CreateInteger, inst.source_range); }, .CreateFloatingPoint => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); try block.addInstruction(allocator, .CreateFloatingPoint, target, inst.payload.CreateFloatingPoint, inst.source_range); }, .CreateByteArray => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); try block.addInstruction(allocator, .CreateByteArray, target, inst.payload.CreateByteArray, inst.source_range); }, .CreateObject => { const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); try block.addInstruction(allocator, .CreateObject, target, .{ .slot_count = inst.payload.CreateObject.slot_count, }, inst.source_range); }, .CreateMethod => { const payload = inst.payload.CreateMethod; const method_name_location = register_pool.getAllocatedRegisterFor(payload.method_name_location); const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); try block.addInstruction(allocator, .CreateMethod, target, .{ .method_name_location = method_name_location, .slot_count = payload.slot_count, .block_index = payload.block_index, }, inst.source_range); }, .CreateBlock => { const payload = inst.payload.CreateBlock; const target = try register_pool.allocateRegister(allocator, block, liveness, inst.target); try block.addInstruction(allocator, .CreateBlock, target, .{ .slot_count = payload.slot_count, .block_index = payload.block_index, }, inst.source_range); }, .SetMethodInline => { try block.addInstruction(allocator, .SetMethodInline, .zero, {}, inst.source_range); }, .Return => { const value_location = register_pool.getAllocatedRegisterFor(inst.payload.Return.value_location); try block.addInstruction(allocator, .Return, .zero, .{ .value_location = value_location }, inst.source_range); }, .NonlocalReturn => { const value_location = register_pool.getAllocatedRegisterFor(inst.payload.Return.value_location); try block.addInstruction(allocator, .NonlocalReturn, .zero, .{ .value_location = value_location }, inst.source_range); }, .PushArg => { const argument_location = register_pool.getAllocatedRegisterFor(inst.payload.PushArg.argument_location); try block.addInstruction(allocator, .PushArg, .zero, .{ .argument_location = argument_location }, inst.source_range); }, .PushArgumentSentinel => { try block.addInstruction(allocator, .PushArgumentSentinel, .zero, {}, inst.source_range); }, .PushSlotSentinel => { try block.addInstruction(allocator, .PushSlotSentinel, .zero, {}, inst.source_range); }, .VerifyArgumentSentinel => { try block.addInstruction(allocator, .VerifyArgumentSentinel, .zero, {}, inst.source_range); }, .VerifySlotSentinel => { try block.addInstruction(allocator, .VerifySlotSentinel, .zero, {}, inst.source_range); }, .PushRegisters => unreachable, } }
https://raw.githubusercontent.com/sin-ack/zigself/0610529f7a04ec0d0628abc3e89dafd45b995562/src/runtime/bytecode/CodeGen.zig
const std = @import("std"); const common = @import("common.zig"); const FlagCtrl = packed struct(u8) { __R0: u4, timing_clear: bool, trigger_clear: bool, timer_flag: bool, trigger_flag: bool, }; const ModeCtrl = packed struct(u8) { timing_cycle_sec: enum(u3) { s0p125, s0p25, s0p5, s1, s2, s4, s8, s16 }, ignore_lowest_bit: bool, timing_mode_enable: bool, trigger_mode_enable: bool, load_low_word: bool, load_high_word: bool, }; const flag_ctrl: *volatile FlagCtrl = @ptrFromInt(0x40001030); const mode_ctrl: *volatile ModeCtrl = @ptrFromInt(0x40001031); const count_32k = common.Reg32.init(0x40001038); const trig_value = common.Reg32.init(0x40001034); pub const MAX_CYCLE_32K: u32 = 0xA8C00000; var trigger_time_activated = false; pub fn init() void { setTime(0, 0, 0); } pub fn setTime(day: u14, sec2: u16, khz32: u16) void { common.safe_access.enable(); trig_value.set(day); mode_ctrl.load_high_word = true; // Wait until actually set while (day != @as(@TypeOf(day), @truncate(trig_value.get()))) {} common.safe_access.enable(); trig_value.set((@as(u32, sec2) << 16) | khz32); mode_ctrl.load_low_word = true; common.safe_access.disable(); } // TODO: Better naming. This isn't exactly the get version of `setTime` // Gets RTC 32k cycle pub fn getTime() u32 { var _t: u32 = undefined; var time: *volatile u32 = @ptrCast(&_t); // This is how it's done by the manufacturer. // I'm not sure why it has to do this, but maybe it's trying to get a stable value? while (time.* != count_32k.get()) { time.* = count_32k.get(); } return time.*; } pub fn getTimeMillis() u32 { return getTime() / 32; } pub fn setTimingMode(enabled: bool) void { common.safe_access.enable(); mode_ctrl.timing_mode_enable = enabled; common.safe_access.disable(); } pub fn setTriggerMode(enabled: bool) void { common.safe_access.enable(); mode_ctrl.trigger_mode_enable = enabled; common.safe_access.disable(); } pub fn setTriggerTime(time: u32) void { common.safe_access.enable(); trig_value.set(time % MAX_CYCLE_32K); common.safe_access.disable(); trigger_time_activated = false; } pub fn isTriggerTimeActivated() bool { return trigger_time_activated; } export fn RTC_IRQHandler() callconv(.Naked) noreturn { defer common.mret(); flag_ctrl.timing_clear = true; flag_ctrl.trigger_clear = true; trigger_time_activated = true; }
https://raw.githubusercontent.com/semickolon/kirei/27df23f37165d8a2b597134b32948745b8b1bee5/src/platforms/ch58x/hal/rtc.zig
const std = @import("std"); const time = std.time; const Move = enum { rock, paper, scissor, }; fn parseMove(a: u8) Move { return switch (a) { 'A', 'X' => Move.rock, 'B', 'Y' => Move.paper, 'C', 'Z' => Move.scissor, else => Move.rock, }; } const Outcome = enum { win, draw, lose, }; fn parseOutcome(o: u8) Outcome { return switch (o) { 'X' => Outcome.lose, 'Y' => Outcome.draw, 'Z' => Outcome.win, else => Outcome.draw, }; } fn parseMoveOutcome(a: u8, b: u8) [2]Move { const move = parseMove(a); return [2]Move{ move, pickMove(move, parseOutcome(b)) }; } fn moveScore(move: Move) u8 { return switch (move) { .rock => 1, .paper => 2, .scissor => 3, }; } fn outcomeScore(out: Outcome) u8 { return switch (out) { .lose => 0, .draw => 3, .win => 6, }; } fn pickMove(move: Move, out: Outcome) Move { return switch (move) { .rock => { return switch (out) { .draw => Move.rock, .win => Move.paper, .lose => Move.scissor, }; }, .paper => { return switch (out) { .draw => Move.paper, .win => Move.scissor, .lose => Move.rock, }; }, .scissor => { return switch (out) { .draw => Move.scissor, .win => Move.rock, .lose => Move.paper, }; }, }; } fn outcome(move1: Move, move2: Move) Outcome { return switch (move1) { .rock => { return switch (move2) { .rock => Outcome.draw, .scissor => Outcome.lose, .paper => Outcome.win, }; }, .paper => { return switch (move2) { .paper => Outcome.draw, .rock => Outcome.lose, .scissor => Outcome.win, }; }, .scissor => { return switch (move2) { .scissor => Outcome.draw, .paper => Outcome.lose, .rock => Outcome.win, }; }, }; } fn roundScore(move1: Move, move2: Move) u32 { const out = outcome(move1, move2); return moveScore(move2) + outcomeScore(out); } pub fn main() !void { const s = time.microTimestamp(); const stdin = std.io.getStdIn().reader(); var p1: u32 = 0; var p2: u32 = 0; while (true) { var buf: [10]u8 = undefined; const line = try stdin.readUntilDelimiterOrEof(&buf, '\n'); if (line == null) break; const lines = line.?; if (lines.len < 3) break; const move1 = parseMove(lines[0]); const move2 = parseMove(lines[2]); p1 += roundScore(move1, move2); const moves = parseMoveOutcome(lines[0], lines[2]); p2 += roundScore(moves[0], moves[1]); } std.debug.print("{d}\n", .{p1}); std.debug.print("{d}\n", .{p2}); const e = time.microTimestamp(); std.debug.print("Time taken: {s}\n", .{std.fmt.fmtDurationSigned(e - s)}); }
https://raw.githubusercontent.com/dhruvasagar/comp/a12a9fbb979d5f11ddf6c984d31009a035f88944/adventofcode/2022/day02/day02.zig
const std = @import("std"); const profiler = @import("./listing_0081_nesting_profiler.zig"); const haversine_formula = @import("./listing_0065_haversine_formula.zig"); const referenceHaversine = haversine_formula.referenceHaversine; const parseHaversinePairs = @import("./listing_0079_nesting_timedblock_lookup_json_parser.zig").parseHaversinePairs; const HaversinePair = haversine_formula.HaversinePair; fn readEntireFile(allocator: std.mem.Allocator, filename: []const u8) ![]u8 { const block = profiler.timeBlockStart(@src().fn_name); defer profiler.timeBlockEnd(block); errdefer |err| std.log.err("ERROR: {s} Unable to read \"{s}\".\n", .{ @errorName(err), filename }); const file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); const stat = try file.stat(); const file_size = stat.size; const result = try file.readToEndAlloc(allocator, file_size); return result; } fn sumHaversineDistances(pair_count: u64, pairs: []const HaversinePair) f64 { const block = profiler.timeBlockStart(@src().fn_name); defer profiler.timeBlockEnd(block); var sum: f64 = 0; const sum_coef: f64 = 1 / @as(f64, @floatFromInt(pair_count)); for (pairs, 0..) |pair, idx| { if (idx >= pair_count) { break; } const earth_radius: f64 = 6372.8; const dist = referenceHaversine(pair.x0, pair.y0, pair.x1, pair.y1, earth_radius); sum += (sum_coef * dist); } return sum; } pub fn simpleHaversineMain(allocator: std.mem.Allocator, input_json_filename: []const u8, answers_filename: ?[]const u8) !void { profiler.beginProfile(); const input_json = try readEntireFile(allocator, input_json_filename); defer allocator.free(input_json); const minimum_json_pair_encoding: u32 = 6 * 4; const max_pair_count = input_json.len / minimum_json_pair_encoding; if (max_pair_count == 0) { std.log.err("ERROR: Malformed input JSON\n", .{}); return; } const pairs: []HaversinePair = try allocator.alloc(HaversinePair, max_pair_count); defer allocator.free(pairs); const pair_count = parseHaversinePairs(allocator, input_json, max_pair_count, pairs); const sum = sumHaversineDistances(pair_count, pairs); std.log.info("Input size: {d}", .{input_json.len}); std.log.info("Pair count: {d}", .{pair_count}); std.log.info("Haversine sum: {d:.16}", .{sum}); if (answers_filename) |_| { const answers_f64 = try readEntireFile(allocator, answers_filename.?); defer allocator.free(answers_f64); if (answers_f64.len >= @sizeOf(f64)) { const answer_values: []f64 = std.mem.bytesAsSlice(f64, @as([]align(@sizeOf(f64)) u8, @alignCast(answers_f64))); std.log.info("", .{}); std.log.info("Validation", .{}); const ref_answer_count = answer_values.len - 1; if (pair_count != ref_answer_count) { std.log.err("FAILED - pair count doesn't match {d}.", .{pair_count}); } const ref_sum = answer_values[ref_answer_count]; std.log.info("Reference sum: {d:.16}", .{ref_sum}); std.log.info("Difference: {d:.16}", .{sum - ref_sum}); std.log.info("", .{}); } } profiler.endAndPrintProfile(); } pub fn main() !void { const allocator = std.heap.c_allocator; if (std.os.argv.len != 2 and std.os.argv.len != 3) { std.log.err("Usage: {s} [haversine_input.json]\n", .{std.os.argv[0]}); std.log.err(" {s} [haversine_input.json] [answers.f64]\n", .{std.os.argv[0]}); return; } const input_json_filename = std.mem.sliceTo(std.os.argv[1], 0); const answers_filename = if (std.os.argv.len == 3) std.mem.sliceTo(std.os.argv[2], 0) else null; try simpleHaversineMain(allocator, input_json_filename, answers_filename); } test { const allocator = std.testing.allocator; try simpleHaversineMain(allocator, "data_10_flex.json", "data_10_haveranswer.f64"); }
https://raw.githubusercontent.com/santiagocabrera96/computer-enhance-zig/ff61abb1e93a2d0a6e2c3d1f8df090c0c04e705b/part2/src/listing_0082_nesting_haversine_main.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const module = b.createModule(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, .link_libc = true, .link_libcpp = true, }); module.linkSystemLibrary("rocksdb", .{}); const lib_unit_tests = b.addTest(.{ .root_source_file = b.path("src/root.zig"), .target = target, .optimize = optimize, }); const run_lib_unit_tests = b.addRunArtifact(lib_unit_tests); const test_step = b.step("test", "Run unit tests"); const run_step = b.step("run", "Run all examples"); test_step.dependOn(&run_lib_unit_tests.step); buildExample(b, "basic", run_step, target, optimize, module); buildExample(b, "cf", run_step, target, optimize, module); } fn buildExample( b: *std.Build, comptime name: []const u8, run_all: *std.Build.Step, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, module: *std.Build.Module, ) void { const exe = b.addExecutable(.{ .name = name, .root_source_file = b.path(std.fmt.comptimePrint("examples/{s}.zig", .{name})), .target = target, .optimize = optimize, }); exe.root_module.addImport("rocksdb", module); b.installArtifact(exe); const run_cmd = b.addRunArtifact(exe); if (b.args) |args| { run_cmd.addArgs(args); } const run_step = b.step("run-" ++ name, "Run the app"); run_step.dependOn(&run_cmd.step); run_all.dependOn(&run_cmd.step); }
https://raw.githubusercontent.com/jiacai2050/zig-rocksdb/dafac357d0d46eeb6f088e52df6331833bc683fe/build.zig
usingnamespace @import("zalgebra"); const c = @import("c.zig"); const c_allocator = @import("std").heap.c_allocator; const panic = @import("std").debug.panic; pub const Shader = struct { name: []const u8, program_id: u32, vertex_id: u32, fragment_id: u32, geometry_id: ?u32, pub fn create(name: []const u8, vert_content: []const u8, frag_content: []const u8) !Shader { var sp: Shader = undefined; sp.name = name; { sp.vertex_id = c.glCreateShader(c.GL_VERTEX_SHADER); const source_ptr: ?[*]const u8 = vert_content.ptr; const source_len = @intCast(c.GLint, vert_content.len); c.glShaderSource(sp.vertex_id, 1, &source_ptr, &source_len); c.glCompileShader(sp.vertex_id); var ok: c.GLint = undefined; c.glGetShaderiv(sp.vertex_id, c.GL_COMPILE_STATUS, &ok); if (ok == 0) { var error_size: c.GLint = undefined; c.glGetShaderiv(sp.vertex_id, c.GL_INFO_LOG_LENGTH, &error_size); const message = try c_allocator.alloc(u8, @intCast(usize, error_size)); c.glGetShaderInfoLog(sp.vertex_id, error_size, &error_size, message.ptr); panic("Error compiling vertex shader:\n{s}\n", .{message}); } } { sp.fragment_id = c.glCreateShader(c.GL_FRAGMENT_SHADER); const source_ptr: ?[*]const u8 = frag_content.ptr; const source_len = @intCast(c.GLint, frag_content.len); c.glShaderSource(sp.fragment_id, 1, &source_ptr, &source_len); c.glCompileShader(sp.fragment_id); var ok: c.GLint = undefined; c.glGetShaderiv(sp.fragment_id, c.GL_COMPILE_STATUS, &ok); if (ok == 0) { var error_size: c.GLint = undefined; c.glGetShaderiv(sp.fragment_id, c.GL_INFO_LOG_LENGTH, &error_size); const message = try c_allocator.alloc(u8, @intCast(usize, error_size)); c.glGetShaderInfoLog(sp.fragment_id, error_size, &error_size, message.ptr); panic("Error compiling fragment shader:\n{s}\n", .{message}); } } sp.program_id = c.glCreateProgram(); c.glAttachShader(sp.program_id, sp.vertex_id); c.glAttachShader(sp.program_id, sp.fragment_id); c.glLinkProgram(sp.program_id); var ok: c.GLint = undefined; c.glGetProgramiv(sp.program_id, c.GL_LINK_STATUS, &ok); if (ok == 0) { var error_size: c.GLint = undefined; c.glGetProgramiv(sp.program_id, c.GL_INFO_LOG_LENGTH, &error_size); const message = try c_allocator.alloc(u8, @intCast(usize, error_size)); c.glGetProgramInfoLog(sp.program_id, error_size, &error_size, message.ptr); panic("Error linking shader program: {s}\n", .{message}); } // Cleanup shaders (from gl doc). c.glDeleteShader(sp.vertex_id); c.glDeleteShader(sp.fragment_id); return sp; } pub fn setMat4(sp: Shader, name: [*c]const u8, value: *const Mat4) void { const id = c.glGetUniformLocation(sp.program_id, name); c.glUniformMatrix4fv(id, 1, c.GL_FALSE, value.getData()); } pub fn setBool(sp: Shader, name: [*c]const u8, value: bool) void { const id = c.glGetUniformLocation(sp.program_id, name); c.glUniform1i(id, @boolToInt(value)); } pub fn setFloat(sp: Shader, name: [*c]const u8, value: f32) void { const id = c.glGetUniformLocation(sp.program_id, name); c.glUniform1f(id, value); } pub fn setRgb(sp: Shader, name: [*c]const u8, value: *const Vec3) void { const id = c.glGetUniformLocation(sp.program_id, name); c.glUniform3f(id, value.x / 255.0, value.y / 255.0, value.z / 255.0); } pub fn setRgba(sp: Shader, name: [*c]const u8, value: *const Vec4) void { const id = c.glGetUniformLocation(sp.program_id, name); c.glUniform4f(id, value.x / 255.0, value.y / 255.0, value.z / 255.0, value.w); } };
https://raw.githubusercontent.com/kooparse/mogwai/90fbdb659f42bc7bbd9ee8d6612cd4ebb4ea7ea9/exemples/common/shader.zig
// // Copyright (C) Palash Bauri // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. // // SPDX-License-Identifier: MPL-2.0 const BN_INFINITY = "অসীম"; const BN_NAN = "অসংজ্ঞাত"; const BN_TRUE = "সত্যি"; const BN_FALSE = "মিথ্যা"; const BN_NIL = "নিল"; const BN_UNKNOWN = "অজানা মান"; const std = @import("std"); const PObj = @import("object.zig").PObj; const Gc = @import("gc.zig").Gc; const writer = @import("writer.zig"); const utils = @import("utils.zig"); const BnName = @import("bengali/names.zig"); const math = std.math; pub const PValueType = enum(u8) { Pt_Num, Pt_Bool, Pt_Nil, Pt_Obj, Pt_Unknown, pub fn toSimpleString(self: PValueType) []const u8 { switch (self) { .Pt_Num => return BnName.simpleNameNumber, .Pt_Bool => return BnName.simpleNameBool, .Pt_Nil => return BnName.simpleNameNil, .Pt_Obj => return BnName.simpleNameObject, .Pt_Unknown => return BnName.simpleNameUnknown, } } pub fn toString(self: PValueType) []const u8 { switch (self) { .Pt_Num => return "VAL_NUM", .Pt_Bool => return "VAL_BOOL", .Pt_Nil => return "VAL_NIL", .Pt_Obj => return "VAL_OBJ", .Pt_Unknown => return "VAL_UNKNOWN", } } }; pub const PValue = packed struct { data: u64, const QNAN: u64 = 0x7ffc000000000000; const SIGN_BIT: u64 = 0x8000000000000000; const TAG_NIL = 1; const TAG_FALSE = 2; const TAG_TRUE = 3; const NIL_VAL = PValue{ .data = QNAN | TAG_NIL }; const FALSE_VAL = PValue{ .data = QNAN | TAG_FALSE }; const TRUE_VAL = PValue{ .data = QNAN | TAG_TRUE }; const Self = @This(); pub fn getLen(self: Self) ?usize { if (self.isObj()) return self.asObj().getLen(); return null; } pub fn hash(self: Self) u32 { const data = self.data; var result: u32 = 0; if (utils.IS_WASM) { var hasher = std.hash.Fnv1a_32.init(); std.hash.autoHash(&hasher, data); result = hasher.final(); } else { var hasher = std.hash.XxHash32.init(@intCast(std.time.timestamp())); std.hash.autoHash(&hasher, data); result = hasher.final(); } return result; } /// is value a bool pub fn isBool(self: Self) bool { return (self.data | 1) == TRUE_VAL.data; } /// is value a nil pub fn isNil(self: Self) bool { return self.data == NIL_VAL.data; } /// is value a nil pub fn isNumber(self: Self) bool { return (self.data & QNAN) != QNAN; } /// is value a object pub fn isObj(self: Self) bool { return (self.data & (QNAN | SIGN_BIT)) == (QNAN | SIGN_BIT); } pub fn isMod(self: Self) bool { if (!self.isObj()) return false; if (!self.asObj().isMod()) return false; return true; } pub fn isError(self: Self) bool { return self.isObj() and self.asObj().isOError(); } pub fn isString(self: Self) bool { if (self.isObj()) { return self.asObj().isString(); } return false; } pub fn makeComptimeError( gc: *Gc, comptime msg: []const u8, args: anytype, ) ?PValue { const rawO = gc.newObj(.Ot_Error, PObj.OError) catch return null; rawO.parent().isMarked = true; if (!rawO.initU8Args(gc, msg, args)) return null; const val = PValue.makeObj(rawO.parent()); rawO.parent().isMarked = false; return val; } pub fn makeError(gc: *Gc, msg: []const u8) ?PValue { const rawO = gc.newObj(.Ot_Error, PObj.OError) catch return null; rawO.parent().isMarked = true; if (!rawO.initU8(gc, msg)) return null; const val = PValue.makeObj(rawO.parent()); rawO.parent().isMarked = false; return val; } /// get a number value as `f64` pub fn asNumber(self: Self) f64 { if (self.isNumber()) { return @bitCast(self.data); } else { return 0; } } /// get a bool value as `bool` pub fn asBool(self: Self) bool { if (self.isBool()) { return self.data == TRUE_VAL.data; } else { return false; } } pub fn asObj(self: Self) *PObj { const v: usize = @intCast(self.data & ~(SIGN_BIT | QNAN)); return @ptrFromInt(v); } /// Create a new number value pub fn makeNumber(n: f64) PValue { return PValue{ .data = @bitCast(n) }; } /// Create a new bool value pub fn makeBool(b: bool) PValue { if (b) { return TRUE_VAL; } else { return FALSE_VAL; } } /// Create a new nil value pub fn makeNil() PValue { return NIL_VAL; } pub fn makeObj(o: *PObj) PValue { return PValue{ .data = SIGN_BIT | QNAN | @intFromPtr(o), }; } /// Return a new value with with negative value of itself; /// If `self` is not a number return itself pub fn makeNeg(self: Self) PValue { if (self.isNumber()) { return PValue.makeNumber(-self.asNumber()); } else { return self; } } pub fn getType(self: Self) PValueType { if (self.isNumber()) { return .Pt_Num; } else if (self.isBool()) { return .Pt_Bool; } else if (self.isNil()) { return .Pt_Nil; } else if (self.isObj()) { return .Pt_Obj; } return .Pt_Unknown; } pub fn getTypeAsString(self: Self) []const u8 { switch (self.getType()) { .Pt_Num, .Pt_Bool, .Pt_Nil, .Pt_Unknown, => return self.getType().toString(), .Pt_Obj => { return self.asObj().getType().toString(); }, } } pub fn getTypeAsSimpleStr(self: Self) []const u8 { switch (self.getType()) { .Pt_Num, .Pt_Bool, .Pt_Nil, .Pt_Unknown, => return self.getType().toSimpleString(), .Pt_Obj => { return self.asObj().getType().toSimpleString(); }, } } pub fn isEqual(self: Self, other: PValue) bool { if (self.getType() != other.getType()) { return false; } if (self.isBool()) { return self.asBool() == other.asBool(); } else if (self.isNumber()) { return self.asNumber() == other.asNumber(); } else if (self.isNil()) { return true; } else if (self.isObj()) { return self.asObj().isEqual(other.asObj()); } return false; } /// Chec if value is falsy pub fn isFalsy(self: Self) bool { if (self.isBool()) { return !self.asBool(); } else if (self.isNil()) { return true; } else { return false; } } /// Print value of PValue to console pub fn printVal(self: Self, gc: *Gc) bool { if (self.isNil()) { gc.pstdout.print(BN_NIL, .{}) catch return false; } else if (self.isBool()) { const b: bool = self.asBool(); if (b) { gc.pstdout.print(BN_TRUE, .{}) catch return false; } else { gc.pstdout.print(BN_FALSE, .{}) catch return false; } } else if (self.isNumber()) { const n: f64 = self.asNumber(); if (math.isInf(n)) { gc.pstdout.print(BN_INFINITY, .{}) catch return false; } else if (math.isNan(n)) { gc.pstdout.print(BN_NAN, .{}) catch return false; } else { gc.pstdout.print("{d}", .{n}) catch return false; } } else if (self.isObj()) { return self.asObj().printObj(gc); } else { gc.pstdout.print(BN_UNKNOWN, .{}) catch return false; } return true; } /// Convert value to string /// you must free the result pub fn toString(self: Self, al: std.mem.Allocator) ![]u8 { if (self.isNil()) { const r = try std.fmt.allocPrint(al, BN_NIL, .{}); return r; } else if (self.isBool()) { if (self.asBool()) { const r = try std.fmt.allocPrint(al, BN_TRUE, .{}); return r; } else { const r = try std.fmt.allocPrint(al, BN_FALSE, .{}); return r; } } else if (self.isNumber()) { var mstr: []u8 = undefined; const num = self.asNumber(); if (math.isInf(num)) { mstr = try std.fmt.allocPrint(al, BN_INFINITY, .{}); } else if (math.isNan(num)) { mstr = try std.fmt.allocPrint(al, BN_NAN, .{}); } else { mstr = try std.fmt.allocPrint(al, "{d}", .{self.asNumber()}); } return mstr; } else if (self.isObj()) { return try self.asObj().toString(al); } var r = try al.alloc(u8, 1); r[0] = '_'; return r; } }; test "bool values" { try std.testing.expect(PValue.makeBool(true).asBool() == true); try std.testing.expectEqual(false, PValue.makeBool(!true).asBool()); try std.testing.expectEqual(false, PValue.makeBool(true).isNumber()); try std.testing.expectEqual(false, PValue.makeBool(true).isNil()); try std.testing.expectEqual(false, PValue.makeBool(true).isFalsy()); try std.testing.expectEqual(true, PValue.makeBool(false).isFalsy()); } test "number values" { const hundred: f64 = 100.0; const nnnn: f64 = 99.99; try std.testing.expect( PValue.makeNumber(@floatCast(100)).asNumber() == hundred, ); try std.testing.expect( PValue.makeNumber(@floatCast(99.99)).asNumber() == nnnn, ); try std.testing.expect(PValue.makeNumber(@floatCast(1)).isBool() == false); try std.testing.expect(PValue.makeNumber(@floatCast(1)).isNil() == false); } test "nil value" { try std.testing.expectEqual(PValue.makeNil(), PValue.makeNil()); try std.testing.expectEqual(true, PValue.makeNil().isNil()); try std.testing.expectEqual(false, PValue.makeNil().isBool()); try std.testing.expectEqual(false, PValue.makeNil().isNumber()); }
https://raw.githubusercontent.com/bauripalash/pankti/191b8dede7c6fd8f5c72a75a7217438e11213824/src/value.zig
pub const version = @import("std").SemanticVersion{ .major = 0, .minor = 9, .patch = 2 }; const std = @import("std"); const assert = std.debug.assert; pub fn init(allocator: std.mem.Allocator) void { assert(mem_allocator == null); mem_allocator = allocator; mem_allocations = std.AutoHashMap(usize, usize).init(allocator); // stb image zstbiMallocPtr = zstbiMalloc; zstbiReallocPtr = zstbiRealloc; zstbiFreePtr = zstbiFree; // stb image resize zstbirMallocPtr = zstbirMalloc; zstbirFreePtr = zstbirFree; // stb image write zstbiwMallocPtr = zstbiMalloc; zstbiwReallocPtr = zstbiRealloc; zstbiwFreePtr = zstbiFree; } pub fn deinit() void { assert(mem_allocator != null); assert(mem_allocations.?.count() == 0); mem_allocations.?.deinit(); mem_allocations = null; mem_allocator = null; } pub const JpgWriteSettings = struct { quality: u32, }; pub const ImageWriteFormat = union(enum) { png, jpg: JpgWriteSettings, }; pub const ImageWriteError = error{ CouldNotWriteImage, }; pub const Image = struct { data: []u8, width: u32, height: u32, num_components: u32, bytes_per_component: u32, bytes_per_row: u32, is_hdr: bool, pub fn info(pathname: [:0]const u8) struct { is_supported: bool, width: u32, height: u32, num_components: u32, } { var w: c_int = 0; var h: c_int = 0; var c: c_int = 0; const is_supported = stbi_info(pathname, &w, &h, &c); return .{ .is_supported = is_supported, .width = @intCast(u32, w), .height = @intCast(u32, h), .num_components = @intCast(u32, c), }; } pub fn init(pathname: [:0]const u8, forced_num_channels: u32) !Image { var width: u32 = 0; var height: u32 = 0; var num_components: u32 = 0; var bytes_per_component: u32 = 0; var bytes_per_row: u32 = 0; var is_hdr = false; const data = if (isHdr(pathname)) data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_loadf( pathname, &x, &y, &ch, @intCast(c_int, forced_num_channels), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_channels == 0) @intCast(u32, ch) else forced_num_channels; width = @intCast(u32, x); height = @intCast(u32, y); bytes_per_component = 2; bytes_per_row = width * num_components * bytes_per_component; is_hdr = true; // Convert each component from f32 to f16. var ptr_f16 = @ptrCast([*]f16, ptr.?); const num = width * height * num_components; var i: u32 = 0; while (i < num) : (i += 1) { ptr_f16[i] = @floatCast(f16, ptr.?[i]); } break :data @ptrCast([*]u8, ptr_f16)[0 .. height * bytes_per_row]; } else data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const is_16bit = is16bit(pathname); const ptr = if (is_16bit) @ptrCast(?[*]u8, stbi_load_16( pathname, &x, &y, &ch, @intCast(c_int, forced_num_channels), )) else stbi_load( pathname, &x, &y, &ch, @intCast(c_int, forced_num_channels), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_channels == 0) @intCast(u32, ch) else forced_num_channels; width = @intCast(u32, x); height = @intCast(u32, y); bytes_per_component = if (is_16bit) 2 else 1; bytes_per_row = width * num_components * bytes_per_component; is_hdr = false; break :data @ptrCast([*]u8, ptr)[0 .. height * bytes_per_row]; }; return Image{ .data = data, .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = is_hdr, }; } pub fn initFromData(data: []const u8, forced_num_channels: u32) !Image { // TODO: Add support for HDR images (https://github.com/michal-z/zig-gamedev/issues/155). var width: u32 = 0; var height: u32 = 0; var num_components: u32 = 0; var bytes_per_component: u32 = 0; var bytes_per_row: u32 = 0; const image_data = data: { var x: c_int = undefined; var y: c_int = undefined; var ch: c_int = undefined; const ptr = stbi_load_from_memory( data.ptr, @intCast(c_int, data.len), &x, &y, &ch, @intCast(c_int, forced_num_channels), ); if (ptr == null) return error.ImageInitFailed; num_components = if (forced_num_channels == 0) @intCast(u32, ch) else forced_num_channels; width = @intCast(u32, x); height = @intCast(u32, y); bytes_per_component = 1; bytes_per_row = width * num_components * bytes_per_component; break :data @ptrCast([*]u8, ptr)[0 .. height * bytes_per_row]; }; return Image{ .data = image_data, .width = width, .height = height, .num_components = num_components, .bytes_per_component = bytes_per_component, .bytes_per_row = bytes_per_row, .is_hdr = false, }; } pub fn resize(image: *const Image, new_width: u32, new_height: u32) Image { // TODO: Add support for HDR images const new_bytes_per_row = new_width * image.num_components * image.bytes_per_component; const new_size = new_height * new_bytes_per_row; const new_data = @ptrCast([*]u8, zstbiMalloc(new_size)); stbir_resize_uint8( image.data.ptr, @intCast(c_int, image.width), @intCast(c_int, image.height), 0, new_data, @intCast(c_int, new_width), @intCast(c_int, new_height), 0, @intCast(c_int, image.num_components), ); return .{ .data = new_data[0..new_size], .width = new_width, .height = new_height, .num_components = image.num_components, .bytes_per_component = image.bytes_per_component, .bytes_per_row = new_bytes_per_row, .is_hdr = image.is_hdr, }; } pub fn writeToFile( self: *const Image, filename: [:0]const u8, image_format: ImageWriteFormat, ) ImageWriteError!void { const w = @intCast(c_int, self.width); const h = @intCast(c_int, self.height); const comp = @intCast(c_int, self.num_components); const result = switch (image_format) { .png => stbi_write_png(filename.ptr, w, h, comp, self.data.ptr, 0), .jpg => |settings| stbi_write_jpg( filename.ptr, w, h, comp, self.data.ptr, @intCast(c_int, settings.quality), ), }; // if the result is 0 then it means an error occured (per stb image write docs) if (result == 0) { return ImageWriteError.CouldNotWriteImage; } } pub fn deinit(image: *Image) void { stbi_image_free(image.data.ptr); image.* = undefined; } }; /// `pub fn setHdrToLdrScale(scale: f32) void` pub const setHdrToLdrScale = stbi_hdr_to_ldr_scale; /// `pub fn setHdrToLdrGamma(gamma: f32) void` pub const setHdrToLdrGamma = stbi_hdr_to_ldr_gamma; /// `pub fn setLdrToHdrScale(scale: f32) void` pub const setLdrToHdrScale = stbi_ldr_to_hdr_scale; /// `pub fn setLdrToHdrGamma(gamma: f32) void` pub const setLdrToHdrGamma = stbi_ldr_to_hdr_gamma; pub fn isHdr(filename: [:0]const u8) bool { return stbi_is_hdr(filename) != 0; } pub fn is16bit(filename: [:0]const u8) bool { return stbi_is_16_bit(filename) != 0; } pub fn setFlipVerticallyOnLoad(should_flip: bool) void { stbi_set_flip_vertically_on_load(if (should_flip) 1 else 0); } var mem_allocator: ?std.mem.Allocator = null; var mem_allocations: ?std.AutoHashMap(usize, usize) = null; var mem_mutex: std.Thread.Mutex = .{}; const mem_alignment = 16; extern var zstbiMallocPtr: ?*const fn (size: usize) callconv(.C) ?*anyopaque; extern var zstbiwMallocPtr: ?*const fn (size: usize) callconv(.C) ?*anyopaque; fn zstbiMalloc(size: usize) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const mem = mem_allocator.?.alignedAlloc( u8, mem_alignment, size, ) catch @panic("zstbi: out of memory"); mem_allocations.?.put(@ptrToInt(mem.ptr), size) catch @panic("zstbi: out of memory"); return mem.ptr; } extern var zstbiReallocPtr: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque; extern var zstbiwReallocPtr: ?*const fn (ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque; fn zstbiRealloc(ptr: ?*anyopaque, size: usize) callconv(.C) ?*anyopaque { mem_mutex.lock(); defer mem_mutex.unlock(); const old_size = if (ptr != null) mem_allocations.?.get(@ptrToInt(ptr.?)).? else 0; const old_mem = if (old_size > 0) @ptrCast([*]align(mem_alignment) u8, @alignCast(mem_alignment, ptr))[0..old_size] else @as([*]align(mem_alignment) u8, undefined)[0..0]; const new_mem = mem_allocator.?.realloc(old_mem, size) catch @panic("zstbi: out of memory"); if (ptr != null) { const removed = mem_allocations.?.remove(@ptrToInt(ptr.?)); std.debug.assert(removed); } mem_allocations.?.put(@ptrToInt(new_mem.ptr), size) catch @panic("zstbi: out of memory"); return new_mem.ptr; } extern var zstbiFreePtr: ?*const fn (maybe_ptr: ?*anyopaque) callconv(.C) void; extern var zstbiwFreePtr: ?*const fn (maybe_ptr: ?*anyopaque) callconv(.C) void; fn zstbiFree(maybe_ptr: ?*anyopaque) callconv(.C) void { if (maybe_ptr) |ptr| { mem_mutex.lock(); defer mem_mutex.unlock(); const size = mem_allocations.?.fetchRemove(@ptrToInt(ptr)).?.value; const mem = @ptrCast([*]align(mem_alignment) u8, @alignCast(mem_alignment, ptr))[0..size]; mem_allocator.?.free(mem); } } extern var zstbirMallocPtr: ?*const fn (size: usize, maybe_context: ?*anyopaque) callconv(.C) ?*anyopaque; fn zstbirMalloc(size: usize, _: ?*anyopaque) callconv(.C) ?*anyopaque { return zstbiMalloc(size); } extern var zstbirFreePtr: ?*const fn (maybe_ptr: ?*anyopaque, maybe_context: ?*anyopaque) callconv(.C) void; fn zstbirFree(maybe_ptr: ?*anyopaque, _: ?*anyopaque) callconv(.C) void { zstbiFree(maybe_ptr); } extern fn stbi_info(filename: [*:0]const u8, x: *c_int, y: *c_int, comp: *c_int) c_int; extern fn stbi_load( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u8; extern fn stbi_load_16( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u16; extern fn stbi_loadf( filename: [*:0]const u8, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]f32; pub extern fn stbi_load_from_memory( buffer: [*]const u8, len: c_int, x: *c_int, y: *c_int, channels_in_file: *c_int, desired_channels: c_int, ) ?[*]u8; extern fn stbi_image_free(image_data: ?[*]u8) void; extern fn stbi_hdr_to_ldr_scale(scale: f32) void; extern fn stbi_hdr_to_ldr_gamma(gamma: f32) void; extern fn stbi_ldr_to_hdr_scale(scale: f32) void; extern fn stbi_ldr_to_hdr_gamma(gamma: f32) void; extern fn stbi_is_16_bit(filename: [*:0]const u8) c_int; extern fn stbi_is_hdr(filename: [*:0]const u8) c_int; extern fn stbi_set_flip_vertically_on_load(flag_true_if_should_flip: c_int) void; extern fn stbir_resize_uint8( input_pixels: [*]const u8, input_w: c_int, input_h: c_int, input_stride_in_bytes: c_int, output_pixels: [*]u8, output_w: c_int, output_h: c_int, output_stride_in_bytes: c_int, num_channels: c_int, ) void; extern fn stbi_write_jpg( filename: [*:0]const u8, w: c_int, h: c_int, comp: c_int, data: [*]const u8, quality: c_int, ) c_int; extern fn stbi_write_png( filename: [*:0]const u8, w: c_int, h: c_int, comp: c_int, data: [*]const u8, stride_in_bytes: c_int, ) c_int; test "zstbi.basic" { init(std.testing.allocator); defer deinit(); }
https://raw.githubusercontent.com/craftlinks/zig_learn_opengl/7208f4402c44d9cb697705218b2bbbc82a8ccdd2/libs/zstbi/src/zstbi.zig
const std = @import("std"); const ast = @import("ast.zig"); const intrinsics = @import("intrinsics.zig"); const gc = @import("boehm.zig"); const util = @import("util.zig"); const linereader = @import("linereader.zig"); const Token = ast.Token; const Expr = ast.Expr; const ExprType = ast.ExprType; const ExprValue = ast.ExprValue; const Env = ast.Env; const ExprErrors = ast.ExprErrors; const isFalsy = util.isFalsy; const requireExactArgCount = util.requireExactArgCount; const requireMinimumArgCount = util.requireMinimumArgCount; const requireType = util.requireType; /// The expression reader and evaluator pub const Interpreter = struct { env: *Env, exit_code: ?u8 = null, gensym_seq: u64 = 0, verbose: bool = false, /// Reset before every evaluation, and set if an error occurs during the evaluation. has_errors: bool = false, break_seen: bool = false, allocator: std.mem.Allocator, /// Set up the root environment by binding a core set of intrinsics. /// The rest of the standard Bio functions are loaded from std.lisp pub fn init() !*Interpreter { var allocator = gc.allocator(); var instance = try allocator.create(Interpreter); instance.* = Interpreter{ .env = try ast.makeEnv(null, "global"), .allocator = gc.allocator(), }; // Make all built-in functions, symbols and numeric constants available in the root environment try instance.env.populateWithIntrinsics(); return instance; } pub fn deinit(_: *Interpreter) void {} /// Print user friendly errors pub fn printError(_: *Interpreter, err: anyerror) !void { if (err == ExprErrors.AlreadyReported) return; try std.io.getStdErr().writer().print("{s}\n", .{ast.errString(err)}); } /// Print a formatted runtime error message, including source information. pub fn printErrorFmt(self: *Interpreter, expr: *Expr, comptime fmt: []const u8, args: anytype) !void { var stdout = std.io.getStdErr().writer(); if (expr.tok) |tok| { const file = if (tok.file.path) |path| path else "eval"; const info = ast.SourceInfo.compute(tok); try stdout.print("\x1b[1m{s}:{d}:{d}: error: ", .{ file, info.line + 1, info.column + 1 }); try stdout.print(fmt, args); // var line = try gc.allocator().dupe(u8, info.source_line); const content = tok.file.content; if (info.line_start <= tok.start and tok.end <= info.line_end) { const indentation = " "; try stdout.print("\n", .{}); try stdout.print("\x1b[0m\n{s}", .{indentation}); try stdout.print("{s}", .{content[info.line_start..tok.start]}); try stdout.print("\x1b[92;4m{s}\x1b[0m", .{content[tok.start..tok.end]}); try stdout.print("{s}\n", .{content[tok.end..info.line_end]}); // Print ^----- indicator const caret_offset = tok.start - info.line_start; const filler = try gc.allocator().alloc(u8, caret_offset); @memset(filler, ' '); try stdout.print("\x1b[92m{s}{s}✗~~~\x1b[0m", .{ indentation, filler }); } } else try stdout.print(fmt, args); try stdout.print("\n", .{}); self.has_errors = true; } /// Evaluate an expression pub fn eval(self: *Interpreter, environment: *Env, expr: *Expr) anyerror!*Expr { var maybe_next: ?*Expr = expr; var env: *Env = environment; var func_lookup_env: ?*Env = null; var seen_macro_expand = false; self.has_errors = false; tailcall_optimization_loop: while (maybe_next) |e| { if (self.exit_code) |_| { return ast.getIntrinsic(.nil); } if (e.isIntrinsic(.@"&break")) { self.break_seen = true; return ast.getIntrinsic(.nil); } switch (e.val) { ExprValue.num, ExprValue.env, ExprValue.any => { return e; }, ExprValue.sym => |sym| { if (env.lookup(sym, true)) |val| { return val; } else { try self.printErrorFmt(e, "{s} is not defined", .{sym}); return ast.getIntrinsic(.nil); } }, ExprValue.lst => |list| { if (list.items.len == 0) { return ast.getIntrinsic(.nil); } const args_slice = list.items[1..]; if (list.items[0].isIntrinsic(.macroexpand)) { // Signal that we don't want to evaluate the expression returned by the macro seen_macro_expand = true; maybe_next = args_slice[args_slice.len - 1]; continue; } else if (list.items[0].isIntrinsic(.begin)) { var res: *Expr = ast.getIntrinsic(.nil); for (args_slice[0 .. args_slice.len - 1]) |arg| { res = try self.eval(env, arg); } maybe_next = args_slice[args_slice.len - 1]; continue; } else if (list.items[0].isIntrinsic(.cond)) { try requireMinimumArgCount(2, args_slice); const else_branch = args_slice[args_slice.len - 1]; if (else_branch.val != ExprType.lst or else_branch.val.lst.items.len != 1) { try self.printErrorFmt(e, "Last expression in cond must be a single-expression list", .{}); return ExprErrors.AlreadyReported; } for (args_slice) |branch| { if (branch == else_branch) { maybe_next = branch.val.lst.items[0]; continue :tailcall_optimization_loop; } else if (branch.val == ExprType.lst) { try requireExactArgCount(2, branch.val.lst.items); const predicate = try self.eval(env, branch.val.lst.items[0]); if (predicate.isIntrinsic(.@"#t")) { maybe_next = branch.val.lst.items[1]; continue :tailcall_optimization_loop; } } else { try self.printErrorFmt(e, "Invalid switch syntax", .{}); return ExprErrors.AlreadyReported; } } return ast.getIntrinsic(.nil); } else if (list.items[0].isIntrinsic(.@"if")) { try requireMinimumArgCount(2, args_slice); var branch: usize = 1; const predicate = try self.eval(env, args_slice[0]); if (!predicate.isIntrinsic(.@"#t")) { // Anything not defined as falsy is considered true in a boolean context if (isFalsy(predicate)) { branch += 1; } } if (branch < args_slice.len) { maybe_next = args_slice[branch]; continue :tailcall_optimization_loop; } else { return ast.getIntrinsic(.nil); } } // Look up intrinsic, lambda, macro or env by name. If not found, the lookup has already reported the error. var func = try self.eval(if (func_lookup_env) |fle| fle else env, list.items[0]); func_lookup_env = null; if (func.isIntrinsic(.nil)) { return ast.getIntrinsic(.nil); } const kind = func.val; switch (kind) { // Look up a symbol or call a function in the given environment ExprValue.env => |target_env| { if (args_slice.len == 0 or (args_slice[0].val != ExprType.sym and args_slice[0].val != ExprType.lst)) { const arg_str = if (args_slice.len > 0) try args_slice[0].toStringAlloc() else "[no argument]"; try self.printErrorFmt(e, "Missing symbol or call in environment lookup: {s}", .{arg_str}); return ExprErrors.AlreadyReported; } if (args_slice[0].val == ExprType.lst) { maybe_next = args_slice[0]; func_lookup_env = target_env; continue :tailcall_optimization_loop; } else if (target_env.lookup(args_slice[0].val.sym, false)) |match| { return match; } else { try self.printErrorFmt(e, "Symbol not found in given environment: {s}", .{args_slice[0].val.sym}); return ExprErrors.AlreadyReported; } }, // Evaluate an intrinsic function ExprValue.fun => |fun| { return fun(self, env, args_slice) catch |err| { try self.printErrorFmt(e, "{s}", .{ast.errString(err)}); return ast.getIntrinsic(.nil); }; }, // Evaluate a previously defined lambda or macro ExprValue.lam, ExprValue.mac => |fun| { try requireType(self, fun.items[0], ExprType.lst); const parent_env = if (kind == ExprType.lam) func.env else env; const kind_str = if (kind == ExprType.lam) "lambda" else "macro"; var local_env = try ast.makeEnv(parent_env, kind_str); const formals = fun.items[0].val.lst.items; var formal_param_count = formals.len; var logical_arg_count = args_slice.len; var eval_formal_count: usize = 0; // Bind arguments to the new environment for (formals, 0..) |param, index| { if (param.val == ExprType.sym) { if (param.isIntrinsic(.@"&rest")) { formal_param_count -= 1; var rest_args = try ast.makeListExpr(null); for (args_slice[index..]) |rest_param| { logical_arg_count -= 1; if (kind == ExprType.lam) { try rest_args.val.lst.append(try self.eval(env, rest_param)); } else { try rest_args.val.lst.append(rest_param); } } logical_arg_count += 1; try local_env.putWithSymbol(formals[index + 1], rest_args); break; } if (param.isIntrinsic(.@"&eval")) { eval_formal_count += 1; formal_param_count -= 1; continue; } // Arguments are eagerly evaluated for lambdas, lazily for macros (that is, the expression is passed unevaluated) // If a macro formal parameter is preceded by "&eval", then that argument is eagerly evaluated anyway. if (index - eval_formal_count < args_slice.len) { if (kind == ExprType.lam or eval_formal_count > 0) { try local_env.putWithSymbol(param, try self.eval(env, args_slice[index - eval_formal_count])); eval_formal_count = 0; } else { try local_env.putWithSymbol(param, args_slice[index]); } } } else { try self.printErrorFmt(e, "Formal parameter to {s} is not a symbol: {s}", .{ kind_str, try param.toStringAlloc() }); } } if (logical_arg_count != formal_param_count) { try self.printErrorFmt(e, "{s} received {d} arguments, expected {d}", .{ kind_str, args_slice.len, formal_param_count }); return ast.getIntrinsic(.nil); } // Evaluate body, except the last expression which is TCO'ed var result: *Expr = undefined; for (fun.items[1 .. fun.items.len - 1]) |body_expr| { result = self.eval(local_env, body_expr) catch |err| { try self.printErrorFmt(body_expr, "{s}: Could not evaluate {s} body", .{ ast.errString(err), kind_str }); return ast.getIntrinsic(.nil); }; if (self.has_errors) { return ast.getIntrinsic(.nil); } } // For lambdas, we set up the next iteration to eval the last expression, while for // macros we just evaluate it on the assumption it's a quoted expression, which is // then evaluated in the next TCO iteration. const last_expr = fun.items[fun.items.len - 1]; if (kind == ExprValue.lam) { env = local_env; maybe_next = last_expr; continue; } else { result = self.eval(local_env, last_expr) catch |err| { try self.printErrorFmt(last_expr, "{s}: Could not evaluate {s} body", .{ ast.errString(err), kind_str }); return ast.getIntrinsic(.nil); }; if (seen_macro_expand) { return result; } env = parent_env.?; maybe_next = result; continue; } }, else => { try self.printErrorFmt(e, "Not a function or macro: {s}", .{try list.items[0].toStringAlloc()}); return ast.getIntrinsic(.nil); }, } return ast.getIntrinsic(.nil); }, // This allows us to create intrinsics that pass intrinsics as arguments ExprValue.fun => { return e; }, else => { try self.printErrorFmt(e, "Invalid expression", .{}); return ast.getIntrinsic(.nil); }, } } return ast.getIntrinsic(.nil); } // REPL pub fn readEvalPrint(self: *Interpreter) !void { const logo = \\ \\ .. .. \\ λλ '(λλ. `λλ \\ λλ λ λλ Bio is a Lisp written in Zig \\ λλ' λλ `λλ Docs at github.com/cryptocode/bio \\ λλ BIO! λλ \\ λλ λλ'`λ λλ Use arrow up/down for history \\ λλ. ,λ' λλ ,λλ You can also run bio files with \\ λλ λλ' λλ) .λλ "bio run <file>" \\ λλ . .λλ \\ `` '' ; try std.io.getStdOut().writer().print("{s}\n\n", .{logo}); var buf = std.ArrayList(u8).init(gc.allocator()); main_loop: while (true) { buf.clearRetainingCapacity(); var file = ast.File{ .content = "" }; var parser = ast.Parser.init(&file); try linereader.linenoise_wrapper.printPrompt("bio: "); while (true) { // We're not actually seeing \n, instead linenoise hands us an EOF error, which we ignore linereader.linenoise_reader.streamUntilDelimiter(buf.writer(), '\n', null) catch {}; parser.updateSource(buf.items); parser.parse() catch |err| { try self.printError(err); continue :main_loop; }; if (parser.missingRightParen()) { try linereader.linenoise_wrapper.printPrompt(" "); } else break; } _ = try linereader.linenoise_wrapper.addToHistory(buf.items); for (parser.cur.val.lst.items) |expr| { var res = self.eval(self.env, expr) catch |err| { try self.printError(err); break; }; // Update the last expression and print it try self.env.put("#?", res); if (!res.isNil() or self.verbose) { try res.print(); } try std.io.getStdOut().writer().print("\n", .{}); if (self.exit_code) |exit_code| { self.deinit(); std.process.exit(exit_code); } } } try std.io.getStdOut().writer().print("Got {s}\n", .{buf.items}); } };
https://raw.githubusercontent.com/cryptocode/bio/e525af48db08bd4fcc58f6a7f072b4350089fd64/src/interpreter.zig
const std = @import("std"); const xev = @import("xev"); const Task = xev.ThreadPool.Task; pub const Job = struct { task: Task, results: []Application = &.{}, allocator: std.mem.Allocator, wg: xev.Async, done: bool = false, }; pub fn indexApplications(allocator: std.mem.Allocator) []Application { const data_dirs = std.os.getenv("XDG_DATA_DIRS") orelse { std.log.warn("couldn't find XDG_DATA_DIRS", .{}); return &.{}; }; var applications = std.ArrayList(Application).init(allocator); var iter = std.mem.splitScalar(u8, data_dirs, ':'); var map = std.StringHashMap(Icon).init(allocator); defer map.deinit(); var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); while (iter.next()) |path| { getApplications(allocator, path, &applications) catch {}; resolveIcons(arena.allocator(), path, &map) catch {}; } for (applications.items) |*app| { app.*.iconPath = if (map.get(app.*.icon)) |i| allocator.dupe(u8, i.path) catch { @panic("oom"); } else ""; } return applications.toOwnedSlice() catch { @panic("oom"); }; } pub const DesiredSize = 32; pub const Icon = struct { size: u16, path: []const u8, }; fn log2Diff(a: u16, b: u16) u16 { const al = std.math.log2(a); const bl = std.math.log2(b); if (bl > al) return bl - al; return al - bl; } pub fn resolveIcons( allocator: std.mem.Allocator, path: []const u8, map: *std.StringHashMap(Icon), ) !void { const parent = try std.fs.openDirAbsolute(path, .{}); const icons = try parent.openDir("icons", .{ .iterate = true }); var walker = try icons.walk(allocator); defer walker.deinit(); while (try walker.next()) |entry| { if (entry.kind != .file and entry.kind != .sym_link) continue; const extension = std.fs.path.extension(entry.path); if (!std.mem.eql(u8, extension, ".png")) continue; const stem = std.fs.path.stem(entry.basename); const fullPath = try std.fs.path.resolve( allocator, &.{ path, "icons", entry.path }, ); const size = try getSize(fullPath); if (map.get(stem)) |v| { // if we already have the desired size, skip // if the new icon would be smaller than the desired (and our existing), skip if (v.size == DesiredSize or (size < v.size and size < DesiredSize)) continue; const current = log2Diff(v.size, DesiredSize); const potential = log2Diff(size, DesiredSize); // icons are scaled in (roughly) powers of two // log2 normalizes this difference so we can make a simple comparison if (potential < current) { try map.put(try allocator.dupe(u8, stem), Icon{ .size = size, .path = fullPath, }); } } else { try map.put(try allocator.dupe(u8, stem), Icon{ .size = size, .path = fullPath, }); } } } fn getSize(path: []const u8) !u16 { const parent = std.fs.path.dirname(path); if (parent) |p| { if (std.ascii.isDigit(std.fs.path.basename(p)[0])) { return convertSize(std.fs.path.basename(p)); } else if (std.fs.path.dirname(p)) |buffer| { const base = std.fs.path.basename(buffer); return convertSize(base); } } return 0; } fn convertSize(base: []const u8) !u16 { var split = std.mem.splitScalar(u8, base, 'x'); const size = split.next(); if (size == null) return error.EmptyDirectory; return try std.fmt.parseUnsigned(u16, size.?, 10); } pub fn getApplications(allocator: std.mem.Allocator, path: []const u8, list: *std.ArrayList(Application)) !void { const parent = try std.fs.openDirAbsolute(path, .{}); const applications = try parent.openDir("applications", .{ .iterate = true }); var walker = try applications.walk(allocator); defer walker.deinit(); while (try walker.next()) |entry| { if (entry.kind == .file or entry.kind == .sym_link) { const extension = std.fs.path.extension(entry.path); if (!std.mem.eql(u8, extension, ".desktop")) continue; if (parseApplication(allocator, applications, entry.path) catch continue) |application| { try list.append(application); } } } } pub const Application = struct { name: []const u8 = "", exec: []const u8 = "", icon: []const u8 = "", iconPath: []const u8 = "", pub fn deinit(self: *const Application, allocator: std.mem.Allocator) void { allocator.free(self.name); allocator.free(self.exec); allocator.free(self.icon); allocator.free(self.iconPath); } }; // crude parser for the .desktop format fn parseApplication(allocator: std.mem.Allocator, dir: std.fs.Dir, path: []const u8) !?Application { var file = try dir.openFile(path, .{}); const contents = try file.readToEndAlloc( allocator, 1024 * 1024 * 1024, ); defer allocator.free(contents); var application = Application{}; if (std.mem.indexOf(u8, contents, "[Desktop Entry]")) |start| { var lines = std.mem.splitScalar(u8, contents[start..], '\n'); while (lines.next()) |line| { if (std.mem.startsWith(u8, line, "#")) continue; // if (std.mem.startsWith(u8, line, "[")) break; var split = std.mem.splitScalar(u8, line, '='); const key = split.next(); const value = split.rest(); if (key == null) continue; if (std.mem.eql(u8, key.?, "Name")) { application.name = value; } else if (std.mem.eql(u8, key.?, "Exec")) { application.exec = value; } else if (std.mem.eql(u8, key.?, "Icon")) { application.icon = value; } else if (std.mem.eql(u8, key.?, "Type")) { if (!std.mem.eql(u8, std.mem.trim( u8, value, " \r", ), "Application")) return null; } else if (std.mem.eql(u8, key.?, "NoDisplay")) { if (std.mem.eql(u8, value, "true")) return null; } } } const app = .{ .name = try allocator.dupe(u8, application.name), .icon = try allocator.dupe(u8, application.icon), .exec = try allocator.dupe(u8, application.exec), }; return app; } test "parse format" { _ = indexApplications(std.testing.allocator); }
https://raw.githubusercontent.com/ajkachnic/ora/702b30e88319364d0d215a541d7e9eee8fcd9723/src/tools/application.zig
const std = @import("std"); const thread = std.thread; const Game = @import("../model/game.zig").Game; const State = @import("../model/game.zig").State; const Action = @import("../model/action.zig").Action; const http = std.http; const Allocator = std.mem.Allocator; const r = @cImport({ @cInclude("raylib.h"); }); const HttpClient = http.Client; fn httpGet(allocator: Allocator, url: []const u8) ![]const u8 { var client = HttpClient{ .allocator = allocator }; errdefer client.deinit(); { const uri = try std.Uri.parse(url); const headers_buf = try allocator.alloc(u8, 2048); defer allocator.free(headers_buf); var req = try client.open(.GET, uri, .{ .server_header_buffer = headers_buf }); defer req.deinit(); try req.send(); try req.wait(); const body = try req.reader().readAllAlloc(allocator, 8192000); return body; } } const Image = struct { width: usize, height: usize, id: []u8, url: []u8, author: []u8 = "", }; pub const GptAgent = struct { player_idx: u8, game: *Game, game_version: usize, state: *State, turn_idx_cache: u8, pub fn init(game: *Game, player_idx: u8) GptAgent { var allocator = std.heap.page_allocator; // const body = httpGet(allocator, "http://google.com/") catch |err| x: { // std.debug.print("error: {}\n", .{err}); // break :x ""; // }; const body = httpGet(allocator, "https://api.thecatapi.com/v1/images/search") catch unreachable; defer allocator.free(body); std.debug.print("body: {s}\n", .{body}); const parsed = std.json.parseFromSlice([]Image, allocator, body, .{ .ignore_unknown_fields = true, }) catch unreachable; defer parsed.deinit(); std.debug.print("parsed: {d}\n", .{parsed.value.len}); std.debug.print("image id: {s}\n", .{parsed.value[0].id}); std.debug.print("image url: {s}\n", .{parsed.value[0].url}); std.debug.print("image width: {d}\n", .{parsed.value[0].width}); std.debug.print("image height: {d}\n", .{parsed.value[0].height}); return GptAgent{ .player_idx = player_idx, .game = game, .game_version = game.getVersion(), .state = @constCast(&game.getState()), .turn_idx_cache = 255, }; } pub fn run(self: *GptAgent) !void { while (!r.WindowShouldClose()) { if (self.game.getVersion() != self.game_version) { self.game_version = self.game.getVersion(); self.state = @constCast(&self.game.getState()); } if (self.turn_idx_cache == self.state.turn_idx) { // the turn doesn't change, do nothing std.time.sleep(100 * std.time.ns_per_ms); continue; } // update turn cache self.turn_idx_cache = self.state.turn_idx; // now contact GPT service for next move if (self.turn_idx_cache == self.player_idx) { std.debug.print("GPT agent is thinking...\n", .{}); // interaction with GPT service while (true) { std.time.sleep(100 * std.time.ns_per_ms); } } std.time.sleep(100 * std.time.ns_per_ms); } } };
https://raw.githubusercontent.com/bhou/pioupiou/82701c42c092692863de9f45ade571fbd7f59cef/src/agents/gpt.zig
// -------------------------------------------------------------------------- // Imports // -------------------------------------------------------------------------- const std = @import("std"); const readU16Array = @import("../utils/loaders.zig").readU16Array; const readI16Array = @import("../utils/loaders.zig").readI16Array; const convertU8ArraytoColors = @import("../utils/loaders.zig").convertU8ArraytoColors; const ZigOS = @import("../zigos.zig").ZigOS; const LogicalFB = @import("../zigos.zig").LogicalFB; const Color = @import("../zigos.zig").Color; const RenderTarget = @import("../zigos.zig").RenderTarget; const RenderBuffer = @import("../zigos.zig").RenderBuffer; const Scrolltext = @import("../effects/scrolltext.zig").Scrolltext; const Background = @import("../effects/background.zig").Background; const Console = @import("../utils/debug.zig").Console; // -------------------------------------------------------------------------- // Constants // -------------------------------------------------------------------------- const HEIGHT: u16 = @import("../zigos.zig").HEIGHT; const WIDTH: u16 = @import("../zigos.zig").WIDTH; // scrolltext pub const NB_FONTS: u8 = 11; const fonts_b = @embedFile("../assets/screens/bladerunners/fonts_pal.raw"); const SCROLL_TEXT = " WELCOME TO 'DUNGEON MASTER' -- CRACKED BY THE cdefghijkl -- THIS GAME IS CRACKED FOR THE BLADE RUNNERS - THE ULTIMATE CRACKER CREW...HELLO BOSS,TEX,CSS,TNT-CREW,MMC,BXC,TSUNOO,1001-CREW,AND OF COURSE YOU......DUNGEON MASTER WAS A VERY GOOD PROTECTED GAME THAT TOOK A LONG TIME TO CRACK. SO IF YOU ARE REQUESTED TO PUT IN THE DUNGEON MASTER DISK JUST IGNORE THAT MESSAGE AND CONTINUE (PRESSING THE RETURN KEY) YOUR GAME...THANKS TO MMC FOR THE ORIGINAL THAT WAS AFTERWARDS NEARLY UNREADABLE! TO CHANGE THE TUNE TOGGLE WITH F1/F2 SO YOU WILL LISTEN TO BOTH OF THE RAMPAGE MUSIC PIECES AGAIN COMPOSED BY WHITTIE-BABY!..."; const SCROLL_CHAR_WIDTH = 32; const SCROLL_CHAR_HEIGHT = 32; const SCROLL_SPEED = 2; const SCROLL_CHARS = " ! #$%&'()*+,-./0123456789:;<=>? ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]ˆ_`abcdefghijklmnopqrstuvwxyz"; // palettes const font_pal = convertU8ArraytoColors(@embedFile("../assets/screens/bladerunners/fonts_pal.dat")); // rasters const font_rasters_b = convertU8ArraytoColors(@embedFile("../assets/screens/bladerunners/raster_font_pal.dat")); const back_rasters_b = convertU8ArraytoColors(@embedFile("../assets/screens/bladerunners/raster_back_pal.dat")); // -------------------------------------------------------------------------- // Variables // -------------------------------------------------------------------------- var raster_index: u8 = 0; // -------------------------------------------------------------------------- // Demo // -------------------------------------------------------------------------- fn handler_hbl(zigos: *ZigOS, line: u16) void { if(line >= 40 and line < 240) { zigos.setBackgroundColor(back_rasters_b[(line + 12 + raster_index) % 255]); } else { zigos.setBackgroundColor(Color{ .r = 0, .g = 0, .b = 0, .a = 0 }); } } fn handler_back(fb: *LogicalFB, zigos: *ZigOS, line: u16, col: u16) void { if(line >= 40 and line < 240) { fb.setPaletteEntry(0, back_rasters_b[(line - 40 + raster_index) % 255]); } _ = zigos; _ = col; } fn handler_scroller(fb: *LogicalFB, zigos: *ZigOS, line: u16, col: u16) void { const back_color: Color = Color{ .r = 0, .g = 0, .b = 0, .a = 0 }; if (line >= 40 and line < 240 ) { fb.setPaletteEntry(1, font_rasters_b[(line - 40) % 200]); } if (line == 240) { fb.setPaletteEntry(1, back_color); } _ = zigos; _ = col; } pub const Demo = struct { name: u8 = 0, frame_counter: u32 = 0, scrolltext: Scrolltext(NB_FONTS) = undefined, logo: Background = undefined, offset_table: [320]u16 = undefined, scroller_offset: u16 = 0, scroller_target: RenderTarget = undefined, pub fn init(self: *Demo, zigos: *ZigOS) void { Console.log("Demo init", .{}); // first plane var fb: *LogicalFB = &zigos.lfbs[0]; fb.is_enabled = true; // HBL Handler for the raster effect fb.setFrameBufferHBLHandler(0, handler_back); fb.setPaletteEntry(0, Color{ .r = 0, .g = 0, .b = 0, .a = 0 }); // second plane fb = &zigos.lfbs[1]; fb.is_enabled = true; fb.setPalette(font_pal); // HBL Handler for the raster effect fb.setFrameBufferHBLHandler(0, handler_scroller); zigos.setHBLHandler(handler_hbl); var i: usize = 0; var counter : f32 = 0; while(i < 320) : ( i += 1) { const f_sin: f32 = @fabs(@sin(counter)) * 14; self.offset_table[i] = @floatToInt(u16, f_sin); counter += 0.04; } var buffer = [_]u8{0} ** (WIDTH * SCROLL_CHAR_HEIGHT); var render_buffer: RenderBuffer = .{ .buffer = &buffer, .width = WIDTH, .height = SCROLL_CHAR_HEIGHT }; self.scroller_target = .{ .render_buffer = &render_buffer }; self.scrolltext = Scrolltext(NB_FONTS).init(self.scroller_target, fonts_b, SCROLL_CHARS, SCROLL_CHAR_WIDTH, SCROLL_CHAR_HEIGHT, SCROLL_TEXT, SCROLL_SPEED, 0, null, null, null); self.scroller_offset = 0; Console.log("demo init done!", .{}); } pub fn update(self: *Demo, zigos: *ZigOS, elapsed_time: f32) void { self.scrolltext.update(); self.frame_counter += 1; if (self.frame_counter == 2) { raster_index += 1; self.frame_counter = 0; } self.scroller_offset += 1; if(self.scroller_offset == self.offset_table.len) self.scroller_offset = 0; _ = zigos; _ = elapsed_time; } pub fn render(self: *Demo, zigos: *ZigOS, elapsed_time: f32) void { var fb = &zigos.lfbs[1]; fb.clearFrameBuffer(0); self.scroller_target.clearFrameBuffer(0); self.scrolltext.render(); // copy scrolltext 7 times var one_row: u16 = 0; const sine_offset: u16 = self.offset_table[self.scroller_offset]; var row_height: u16 = WIDTH * (SCROLL_CHAR_HEIGHT - sine_offset); while(one_row < row_height) : ( one_row += 1) { fb.fb[one_row] = self.scroller_target.render_buffer.buffer[one_row + (WIDTH * sine_offset)]; } var i: u16 = 0; while(i < (WIDTH*SCROLL_CHAR_HEIGHT)) : ( i += 1) { fb.fb[i + (( 32 - sine_offset ) * WIDTH)] = self.scroller_target.render_buffer.buffer[i]; fb.fb[i + (( 64 - sine_offset ) * WIDTH)] = self.scroller_target.render_buffer.buffer[i]; fb.fb[i + (( 96 - sine_offset ) * WIDTH)] = self.scroller_target.render_buffer.buffer[i]; fb.fb[i + (( 128 - sine_offset ) * WIDTH)] = self.scroller_target.render_buffer.buffer[i]; fb.fb[i + (( 160 - sine_offset ) * WIDTH)] = self.scroller_target.render_buffer.buffer[i]; } one_row = 0; row_height = WIDTH * @min(32, 200 - (192 - sine_offset)); while(one_row < row_height) : ( one_row += 1) { fb.fb[one_row + (( 192 - sine_offset ) * WIDTH)] = self.scroller_target.render_buffer.buffer[one_row]; } _ = elapsed_time; } };
https://raw.githubusercontent.com/shazz/ZigMachine/ae4d23e2749f9bdbc6ad225909e63e6c5df487b8/src/scenes/bladerunners.zig
const std = @import("std"); const input = @embedFile("input.txt"); // const input = @embedFile("input_small_2.txt"); // const input_len = 8; const input_len = 757; pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const alloc = gpa.allocator(); { var productions = std.StringHashMap([2][]const u8).init(alloc); defer productions.deinit(); var start_2 = std.ArrayList([]const u8).init(alloc); defer start_2.deinit(); var it = std.mem.tokenize(u8, input, "\n=(), "); const lrpattern = it.next().?; while (it.next()) |tok| { const k = tok; const a = [2][]const u8{ it.next().?, it.next().? }; try productions.put(k, a); if (k[2] == 'A') try start_2.append(tok); } { var step: usize = 0; while (true) : (step += 1) { // std.debug.print("{s} -->", .{start}); const p = @mod(step, lrpattern.len); for (start_2.items) |*s| { const production = productions.get(s.*).?; s.* = if (lrpattern[p] == 'L') production[0] else production[1]; } // std.debug.print("{s} {s} {}\n", .{ start, lrpattern[p .. p + 1], p }); for (start_2.items) |s| { if (!(s[2] == 'Z')) break; } else { break; } std.debug.print("start_2 {s} step: {}\n", .{ start_2.items, step }); } step += 1; std.debug.print("steps: {}\n", .{step}); } } }
https://raw.githubusercontent.com/nsksbjii/Advent-of-Code-zig/0d98a270e88fa9c1c48fa5523f609ddff379f17e/2023/day8/main2.zig
const std = @import("std"); const Api = @import("../../api/schema.zig").Api; const bun = @import("root").bun; const MimeType = @import("../../bun_dev_http_server.zig").MimeType; const ZigURL = @import("../../url.zig").URL; const HTTPClient = @import("root").bun.HTTP; const NetworkThread = HTTPClient.NetworkThread; const AsyncIO = NetworkThread.AsyncIO; const JSC = @import("root").bun.JSC; const js = JSC.C; const Method = @import("../../http/method.zig").Method; const FetchHeaders = JSC.FetchHeaders; const ObjectPool = @import("../../pool.zig").ObjectPool; const SystemError = JSC.SystemError; const Output = @import("root").bun.Output; const MutableString = @import("root").bun.MutableString; const strings = @import("root").bun.strings; const string = @import("root").bun.string; const default_allocator = @import("root").bun.default_allocator; const FeatureFlags = @import("root").bun.FeatureFlags; const ArrayBuffer = @import("../base.zig").ArrayBuffer; const Properties = @import("../base.zig").Properties; const getAllocator = @import("../base.zig").getAllocator; const Environment = @import("../../env.zig"); const ZigString = JSC.ZigString; const IdentityContext = @import("../../identity_context.zig").IdentityContext; const JSPromise = JSC.JSPromise; const JSValue = JSC.JSValue; const JSError = JSC.JSError; const JSGlobalObject = JSC.JSGlobalObject; const NullableAllocator = @import("../../nullable_allocator.zig").NullableAllocator; const VirtualMachine = JSC.VirtualMachine; const Task = JSC.Task; const JSPrinter = bun.js_printer; const picohttp = @import("root").bun.picohttp; const StringJoiner = @import("../../string_joiner.zig"); const uws = @import("root").bun.uws; const null_fd = bun.invalid_fd; const Response = JSC.WebCore.Response; const Body = JSC.WebCore.Body; const Request = JSC.WebCore.Request; const PathOrBlob = union(enum) { path: JSC.Node.PathOrFileDescriptor, blob: Blob, pub fn fromJSNoCopy(ctx: js.JSContextRef, args: *JSC.Node.ArgumentsSlice, exception: js.ExceptionRef) ?PathOrBlob { if (JSC.Node.PathOrFileDescriptor.fromJS(ctx, args, args.arena.allocator(), exception)) |path| { return PathOrBlob{ .path = path, }; } const arg = args.nextEat() orelse return null; if (arg.as(Blob)) |blob| { return PathOrBlob{ .blob = blob.*, }; } return null; } }; pub const Blob = struct { const bloblog = Output.scoped(.Blob, false); pub usingnamespace JSC.Codegen.JSBlob; size: SizeType = 0, offset: SizeType = 0, /// When set, the blob will be freed on finalization callbacks /// If the blob is contained in Response or Request, this must be null allocator: ?std.mem.Allocator = null, store: ?*Store = null, content_type: string = "", content_type_allocated: bool = false, content_type_was_set: bool = false, /// JavaScriptCore strings are either latin1 or UTF-16 /// When UTF-16, they're nearly always due to non-ascii characters is_all_ascii: ?bool = null, /// Was it created via file constructor? is_jsdom_file: bool = false, globalThis: *JSGlobalObject = undefined, last_modified: f64 = 0.0, /// Max int of double precision /// 9 petabytes is probably enough for awhile /// We want to avoid coercing to a BigInt because that's a heap allocation /// and it's generally just harder to use pub const SizeType = u52; pub const max_size = std.math.maxInt(SizeType); /// According to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date, /// maximum Date in JavaScript is less than Number.MAX_SAFE_INTEGER (u52). pub const JSTimeType = u52; pub const init_timestamp = std.math.maxInt(JSTimeType); const serialization_version: u8 = 1; const reserved_space_for_serialization: u32 = 128; pub fn getFormDataEncoding(this: *Blob) ?*bun.FormData.AsyncFormData { var content_type_slice: ZigString.Slice = this.getContentType() orelse return null; defer content_type_slice.deinit(); const encoding = bun.FormData.Encoding.get(content_type_slice.slice()) orelse return null; return bun.FormData.AsyncFormData.init(this.allocator orelse bun.default_allocator, encoding) catch unreachable; } pub fn hasContentTypeFromUser(this: *const Blob) bool { return this.content_type_was_set or (this.store != null and this.store.?.data == .file); } const FormDataContext = struct { allocator: std.mem.Allocator, joiner: StringJoiner, boundary: []const u8, failed: bool = false, globalThis: *JSC.JSGlobalObject, pub fn onEntry(this: *FormDataContext, name: ZigString, entry: JSC.DOMFormData.FormDataEntry) void { if (this.failed) return; var globalThis = this.globalThis; const allocator = this.allocator; const joiner = &this.joiner; const boundary = this.boundary; joiner.append("--", 0, null); joiner.append(boundary, 0, null); joiner.append("\r\n", 0, null); joiner.append("Content-Disposition: form-data; name=\"", 0, null); const name_slice = name.toSlice(allocator); joiner.append(name_slice.slice(), 0, name_slice.allocator.get()); name_slice.deinit(); switch (entry) { .string => |value| { joiner.append("\"\r\n\r\n", 0, null); const value_slice = value.toSlice(allocator); joiner.append(value_slice.slice(), 0, value_slice.allocator.get()); }, .file => |value| { joiner.append("\"; filename=\"", 0, null); const filename_slice = value.filename.toSlice(allocator); joiner.append(filename_slice.slice(), 0, filename_slice.allocator.get()); filename_slice.deinit(); joiner.append("\"\r\n", 0, null); const blob = value.blob; const content_type = if (blob.content_type.len > 0) blob.content_type else "application/octet-stream"; joiner.append("Content-Type: ", 0, null); joiner.append(content_type, 0, null); joiner.append("\r\n\r\n", 0, null); if (blob.store) |store| { blob.resolveSize(); switch (store.data) { .file => |file| { // TODO: make this async + lazy const res = JSC.Node.NodeFS.readFile( globalThis.bunVM().nodeFS(), .{ .encoding = .buffer, .path = file.pathlike, .offset = blob.offset, .max_size = blob.size, }, .sync, ); switch (res) { .err => |err| { globalThis.throwValue(err.toJSC(globalThis)); this.failed = true; }, .result => |result| { joiner.append(result.slice(), 0, result.buffer.allocator); }, } }, .bytes => |_| { joiner.append(blob.sharedView(), 0, null); }, } } }, } joiner.append("\r\n", 0, null); } }; pub fn getContentType( this: *Blob, ) ?ZigString.Slice { if (this.content_type.len > 0) return ZigString.Slice.fromUTF8NeverFree(this.content_type); return null; } const StructuredCloneWriter = struct { ctx: *anyopaque, impl: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(.C) void, pub const WriteError = error{}; pub fn write(this: StructuredCloneWriter, bytes: []const u8) WriteError!usize { this.impl(this.ctx, bytes.ptr, @as(u32, @truncate(bytes.len))); return bytes.len; } }; fn _onStructuredCloneSerialize( this: *Blob, comptime Writer: type, writer: Writer, ) !void { try writer.writeInt(u8, serialization_version, .little); try writer.writeInt(u64, @as(u64, @intCast(this.offset)), .little); try writer.writeInt(u32, @as(u32, @truncate(this.content_type.len)), .little); _ = try writer.write(this.content_type); try writer.writeInt(u8, @intFromBool(this.content_type_was_set), .little); const store_tag: Store.SerializeTag = if (this.store) |store| if (store.data == .file) .file else .bytes else .empty; try writer.writeInt(u8, @intFromEnum(store_tag), .little); this.resolveSize(); if (this.store) |store| { try store.serialize(Writer, writer); } // reserved space for future use _ = try writer.write(&[_]u8{0} ** reserved_space_for_serialization); } pub fn onStructuredCloneSerialize( this: *Blob, globalThis: *JSC.JSGlobalObject, ctx: *anyopaque, writeBytes: *const fn (*anyopaque, ptr: [*]const u8, len: u32) callconv(.C) void, ) callconv(.C) void { _ = globalThis; const Writer = std.io.Writer(StructuredCloneWriter, StructuredCloneWriter.WriteError, StructuredCloneWriter.write); var writer = Writer{ .context = .{ .ctx = ctx, .impl = writeBytes, }, }; _onStructuredCloneSerialize(this, Writer, writer) catch return .zero; } pub fn onStructuredCloneTransfer( this: *Blob, globalThis: *JSC.JSGlobalObject, ctx: *anyopaque, write: *const fn (*anyopaque, ptr: [*]const u8, len: usize) callconv(.C) void, ) callconv(.C) void { _ = write; _ = ctx; _ = this; _ = globalThis; } fn readSlice( reader: anytype, len: usize, allocator: std.mem.Allocator, ) ![]u8 { var slice = try allocator.alloc(u8, len); slice = slice[0..try reader.read(slice)]; if (slice.len != len) return error.TooSmall; return slice; } fn _onStructuredCloneDeserialize( globalThis: *JSC.JSGlobalObject, comptime Reader: type, reader: Reader, ) !JSValue { const allocator = globalThis.allocator(); const version = try reader.readInt(u8, .little); _ = version; const offset = try reader.readInt(u64, .little); const content_type_len = try reader.readInt(u32, .little); const content_type = try readSlice(reader, content_type_len, allocator); const content_type_was_set: bool = try reader.readInt(u8, .little) != 0; const store_tag = try reader.readEnum(Store.SerializeTag, .little); const blob: *Blob = switch (store_tag) { .bytes => brk: { const bytes_len = try reader.readInt(u32, .little); const bytes = try readSlice(reader, bytes_len, allocator); var blob = Blob.init(bytes, allocator, globalThis); var blob_ = try allocator.create(Blob); blob_.* = blob; break :brk blob_; }, .file => brk: { const pathlike_tag = try reader.readEnum(JSC.Node.PathOrFileDescriptor.SerializeTag, .little); switch (pathlike_tag) { .fd => { const fd = @as(bun.FileDescriptor, @intCast(try reader.readInt(bun.FileDescriptor, .little))); var blob = try allocator.create(Blob); blob.* = Blob.findOrCreateFileFromPath( JSC.Node.PathOrFileDescriptor{ .fd = fd, }, globalThis, ); break :brk blob; }, .path => { const path_len = try reader.readInt(u32, .little); const path = try readSlice(reader, path_len, default_allocator); var blob = try allocator.create(Blob); blob.* = Blob.findOrCreateFileFromPath( JSC.Node.PathOrFileDescriptor{ .path = .{ .string = bun.PathString.init(path), }, }, globalThis, ); break :brk blob; }, } return .zero; }, .empty => brk: { var blob = try allocator.create(Blob); blob.* = Blob.initEmpty(globalThis); break :brk blob; }, }; blob.allocator = allocator; blob.offset = @as(u52, @intCast(offset)); if (content_type.len > 0) { blob.content_type = content_type; blob.content_type_allocated = true; blob.content_type_was_set = content_type_was_set; } return blob.toJS(globalThis); } pub fn onStructuredCloneDeserialize( globalThis: *JSC.JSGlobalObject, ptr: [*]u8, end: [*]u8, ) callconv(.C) JSValue { const total_length: usize = @intFromPtr(end) - @intFromPtr(ptr); var buffer_stream = std.io.fixedBufferStream(ptr[0..total_length]); var reader = buffer_stream.reader(); const blob = _onStructuredCloneDeserialize(globalThis, @TypeOf(reader), reader) catch return .zero; if (Environment.allow_assert) { std.debug.assert(total_length - reader.context.pos == reserved_space_for_serialization); } return blob; } const URLSearchParamsConverter = struct { allocator: std.mem.Allocator, buf: []u8 = "", globalThis: *JSC.JSGlobalObject, pub fn convert(this: *URLSearchParamsConverter, str: ZigString) void { var out = str.toSlice(this.allocator).cloneIfNeeded(this.allocator) catch unreachable; this.buf = bun.constStrToU8(out.slice()); } }; pub fn fromURLSearchParams( globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, search_params: *JSC.URLSearchParams, ) Blob { var converter = URLSearchParamsConverter{ .allocator = allocator, .globalThis = globalThis, }; search_params.toString(URLSearchParamsConverter, &converter, URLSearchParamsConverter.convert); var store = Blob.Store.init(converter.buf, allocator) catch unreachable; store.mime_type = MimeType.all.@"application/x-www-form-urlencoded"; var blob = Blob.initWithStore(store, globalThis); blob.content_type = store.mime_type.value; blob.content_type_was_set = true; return blob; } pub fn fromDOMFormData( globalThis: *JSC.JSGlobalObject, allocator: std.mem.Allocator, form_data: *JSC.DOMFormData, ) Blob { var arena = @import("root").bun.ArenaAllocator.init(allocator); defer arena.deinit(); var stack_allocator = std.heap.stackFallback(1024, arena.allocator()); var stack_mem_all = stack_allocator.get(); var hex_buf: [70]u8 = undefined; const boundary = brk: { var random = globalThis.bunVM().rareData().nextUUID().bytes; var formatter = std.fmt.fmtSliceHexLower(&random); break :brk std.fmt.bufPrint(&hex_buf, "-WebkitFormBoundary{any}", .{formatter}) catch unreachable; }; var context = FormDataContext{ .allocator = allocator, .joiner = StringJoiner{ .use_pool = false, .node_allocator = stack_mem_all }, .boundary = boundary, .globalThis = globalThis, }; form_data.forEach(FormDataContext, &context, FormDataContext.onEntry); if (context.failed) { return Blob.initEmpty(globalThis); } context.joiner.append("--", 0, null); context.joiner.append(boundary, 0, null); context.joiner.append("--\r\n", 0, null); var store = Blob.Store.init(context.joiner.done(allocator) catch unreachable, allocator) catch unreachable; var blob = Blob.initWithStore(store, globalThis); blob.content_type = std.fmt.allocPrint(allocator, "multipart/form-data; boundary=\"{s}\"", .{boundary}) catch unreachable; blob.content_type_allocated = true; blob.content_type_was_set = true; return blob; } pub fn contentType(this: *const Blob) string { return this.content_type; } pub fn isDetached(this: *const Blob) bool { return this.store == null; } export fn Blob__dupeFromJS(value: JSC.JSValue) ?*Blob { var this = Blob.fromJS(value) orelse return null; return Blob__dupe(this); } export fn Blob__setAsFile(this: *Blob, path_str: *bun.String) *Blob { this.is_jsdom_file = true; // This is not 100% correct... if (this.store) |store| { if (store.data == .bytes) { if (store.data.bytes.stored_name.len == 0) { var utf8 = path_str.toUTF8WithoutRef(bun.default_allocator).clone(bun.default_allocator) catch unreachable; store.data.bytes.stored_name = bun.PathString.init(utf8.slice()); } } } return this; } export fn Blob__dupe(ptr: *anyopaque) *Blob { var this = bun.cast(*Blob, ptr); var new = bun.default_allocator.create(Blob) catch unreachable; new.* = this.dupeWithContentType(true); new.allocator = bun.default_allocator; return new; } export fn Blob__destroy(this: *Blob) void { this.finalize(); } export fn Blob__getFileNameString(this: *Blob) callconv(.C) bun.String { if (this.getFileName()) |filename| { return bun.String.fromBytes(filename); } return bun.String.empty; } comptime { _ = Blob__dupeFromJS; _ = Blob__destroy; _ = Blob__dupe; _ = Blob__setAsFile; _ = Blob__getFileNameString; } pub fn writeFormatForSize(size: usize, writer: anytype, comptime enable_ansi_colors: bool) !void { try writer.writeAll(comptime Output.prettyFmt("<r>Blob<r>", enable_ansi_colors)); try writer.print( comptime Output.prettyFmt(" (<yellow>{any}<r>)", enable_ansi_colors), .{ bun.fmt.size(size), }, ); } pub fn writeFormat(this: *const Blob, comptime Formatter: type, formatter: *Formatter, writer: anytype, comptime enable_ansi_colors: bool) !void { const Writer = @TypeOf(writer); if (this.isDetached()) { try writer.writeAll(comptime Output.prettyFmt("<d>[<r>Blob<r> detached<d>]<r>", enable_ansi_colors)); return; } { var store = this.store.?; switch (store.data) { .file => |file| { try writer.writeAll(comptime Output.prettyFmt("<r>FileRef<r>", enable_ansi_colors)); switch (file.pathlike) { .path => |path| { try writer.print( comptime Output.prettyFmt(" (<green>\"{s}\"<r>)<r>", enable_ansi_colors), .{ path.slice(), }, ); }, .fd => |fd| { try writer.print( comptime Output.prettyFmt(" (<r>fd: <yellow>{d}<r>)<r>", enable_ansi_colors), .{ fd, }, ); }, } }, .bytes => { try writeFormatForSize(this.size, writer, enable_ansi_colors); }, } } if (this.content_type.len > 0 or this.offset > 0) { try writer.writeAll(" {\n"); { formatter.indent += 1; defer formatter.indent -= 1; if (this.content_type.len > 0) { try formatter.writeIndent(Writer, writer); try writer.print( comptime Output.prettyFmt("type: <green>\"{s}\"<r>", enable_ansi_colors), .{ this.content_type, }, ); if (this.offset > 0) { formatter.printComma(Writer, writer, enable_ansi_colors) catch unreachable; } try writer.writeAll("\n"); } if (this.offset > 0) { try formatter.writeIndent(Writer, writer); try writer.print( comptime Output.prettyFmt("offset: <yellow>{d}<r>\n", enable_ansi_colors), .{ this.offset, }, ); } } try formatter.writeIndent(Writer, writer); try writer.writeAll("}"); } } const CopyFilePromiseHandler = struct { promise: *JSPromise, globalThis: *JSGlobalObject, pub fn run(handler: *@This(), blob_: Store.CopyFile.ResultType) void { var promise = handler.promise; var globalThis = handler.globalThis; bun.default_allocator.destroy(handler); var blob = blob_ catch |err| { var error_string = ZigString.init( std.fmt.allocPrint(bun.default_allocator, "Failed to write file \"{s}\"", .{bun.asByteSlice(@errorName(err))}) catch unreachable, ); error_string.mark(); promise.reject(globalThis, error_string.toErrorInstance(globalThis)); return; }; var _blob = bun.default_allocator.create(Blob) catch unreachable; _blob.* = blob; _blob.allocator = bun.default_allocator; promise.resolve( globalThis, ); } }; const WriteFileWaitFromLockedValueTask = struct { file_blob: Blob, globalThis: *JSGlobalObject, promise: *JSPromise, pub fn thenWrap(this: *anyopaque, value: *Body.Value) void { then(bun.cast(*WriteFileWaitFromLockedValueTask, this), value); } pub fn then(this: *WriteFileWaitFromLockedValueTask, value: *Body.Value) void { var promise = this.promise; var globalThis = this.globalThis; var file_blob = this.file_blob; switch (value.*) { .Error => |err| { file_blob.detach(); _ = value.use(); bun.default_allocator.destroy(this); promise.reject(globalThis, err); }, .Used => { file_blob.detach(); _ = value.use(); bun.default_allocator.destroy(this); promise.reject(globalThis, ZigString.init("Body was used after it was consumed").toErrorInstance(globalThis)); }, .WTFStringImpl, .InternalBlob, .Null, .Empty, .Blob, => { var blob = value.use(); // TODO: this should be one promise not two! const new_promise = writeFileWithSourceDestination(globalThis, &blob, &file_blob); if (new_promise.asAnyPromise()) |_promise| { switch (_promise.status(globalThis.vm())) { .Pending => { promise.resolve( globalThis, new_promise, ); }, .Rejected => { promise.reject(globalThis, _promise.result(globalThis.vm())); }, else => { promise.resolve(globalThis, _promise.result(globalThis.vm())); }, } } file_blob.detach(); bun.default_allocator.destroy(this); }, .Locked => { value.Locked.onReceiveValue = thenWrap; value.Locked.task = this; }, } } }; pub fn writeFileWithSourceDestination( ctx: JSC.C.JSContextRef, source_blob: *Blob, destination_blob: *Blob, ) JSC.JSValue { const destination_type = std.meta.activeTag(destination_blob.store.?.data); // Writing an empty string to a file is a no-op if (source_blob.store == null) { destination_blob.detach(); return JSC.JSPromise.resolvedPromiseValue(ctx.ptr(), JSC.JSValue.jsNumber(0)); } const source_type = std.meta.activeTag(source_blob.store.?.data); if (destination_type == .file and source_type == .bytes) { var write_file_promise = bun.default_allocator.create(WriteFilePromise) catch unreachable; write_file_promise.* = .{ .globalThis = ctx.ptr(), }; var file_copier = Store.WriteFile.create( bun.default_allocator, destination_blob.*, source_blob.*, *WriteFilePromise, write_file_promise, WriteFilePromise.run, ) catch unreachable; var task = Store.WriteFile.WriteFileTask.createOnJSThread(bun.default_allocator, ctx.ptr(), file_copier) catch unreachable; // Defer promise creation until we're just about to schedule the task var promise = JSC.JSPromise.create(ctx.ptr()); const promise_value = promise.asValue(ctx); write_file_promise.promise.strong.set(ctx, promise_value); promise_value.ensureStillAlive(); task.schedule(); return promise_value; } // If this is file <> file, we can just copy the file else if (destination_type == .file and source_type == .file) { var file_copier = Store.CopyFile.create( bun.default_allocator, destination_blob.store.?, source_blob.store.?, destination_blob.offset, destination_blob.size, ctx.ptr(), ) catch unreachable; file_copier.schedule(); return file_copier.promise.value(); } else if (destination_type == .bytes and source_type == .bytes) { // If this is bytes <> bytes, we can just duplicate it // this is an edgecase // it will happen if someone did Bun.write(new Blob([123]), new Blob([456])) // eventually, this could be like Buffer.concat var clone = source_blob.dupe(); clone.allocator = bun.default_allocator; var cloned = bun.default_allocator.create(Blob) catch unreachable; cloned.* = clone; return JSPromise.resolvedPromiseValue(ctx.ptr(), cloned.toJS(ctx)); } else if (destination_type == .bytes and source_type == .file) { var fake_call_frame: [8]JSC.JSValue = undefined; @memset(@as([*]u8, @ptrCast(&fake_call_frame))[0..@sizeOf(@TypeOf(fake_call_frame))], 0); const blob_value = source_blob.getSlice(ctx, @as(*JSC.CallFrame, @ptrCast(&fake_call_frame))); return JSPromise.resolvedPromiseValue( ctx.ptr(), blob_value, ); } unreachable; } pub fn writeFile( globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { const arguments = callframe.arguments(2).slice(); var args = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), arguments); defer args.deinit(); var exception_ = [1]JSC.JSValueRef{null}; var exception = &exception_; // accept a path or a blob var path_or_blob = PathOrBlob.fromJSNoCopy(globalThis, &args, exception) orelse { if (exception[0] != null) { globalThis.throwValue(exception[0].?.value()); } else { globalThis.throwInvalidArguments("Bun.write expects a path, file descriptor or a blob", .{}); } return .zero; }; var data = args.nextEat() orelse { globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); return .zero; }; if (data.isEmptyOrUndefinedOrNull()) { globalThis.throwInvalidArguments("Bun.write(pathOrFdOrBlob, blob) expects a Blob-y thing to write", .{}); return .zero; } if (path_or_blob == .blob) { if (path_or_blob.blob.store == null) { globalThis.throwInvalidArguments("Blob is detached", .{}); return .zero; } else { // TODO only reset last_modified on success pathes instead of // resetting last_modified at the beginning for better performance. if (path_or_blob.blob.store.?.data == .file) { // reset last_modified to force getLastModified() to reload after writing. path_or_blob.blob.store.?.data.file.last_modified = init_timestamp; } } } var input_store: ?*Store = if (path_or_blob == .blob) path_or_blob.blob.store else null; if (input_store) |st| st.ref(); defer if (input_store) |st| st.deref(); var needs_async = false; if (data.isString()) { defer if (!needs_async and path_or_blob == .path) path_or_blob.path.deinit(); const len = data.getLength(globalThis); if (len < 256 * 1024 or bun.isMissingIOUring()) { const str = data.toBunString(globalThis); const pathlike: JSC.Node.PathOrFileDescriptor = if (path_or_blob == .path) path_or_blob.path else path_or_blob.blob.store.?.data.file.pathlike; if (pathlike == .path) { const result = writeStringToFileFast( globalThis, pathlike, str, &needs_async, true, ); if (!needs_async) { return result; } } else { const result = writeStringToFileFast( globalThis, pathlike, str, &needs_async, false, ); if (!needs_async) { return result; } } } } else if (data.asArrayBuffer(globalThis)) |buffer_view| { defer if (!needs_async and path_or_blob == .path) path_or_blob.path.deinit(); if (buffer_view.byte_len < 256 * 1024 or bun.isMissingIOUring()) { const pathlike: JSC.Node.PathOrFileDescriptor = if (path_or_blob == .path) path_or_blob.path else path_or_blob.blob.store.?.data.file.pathlike; if (pathlike == .path) { const result = writeBytesToFileFast( globalThis, pathlike, buffer_view.byteSlice(), &needs_async, true, ); if (!needs_async) { return result; } } else { const result = writeBytesToFileFast( globalThis, pathlike, buffer_view.byteSlice(), &needs_async, false, ); if (!needs_async) { return result; } } } } // if path_or_blob is a path, convert it into a file blob var destination_blob: Blob = if (path_or_blob == .path) Blob.findOrCreateFileFromPath(path_or_blob.path, globalThis) else path_or_blob.blob.dupe(); if (destination_blob.store == null) { globalThis.throwInvalidArguments("Writing to an empty blob is not implemented yet", .{}); return .zero; } // TODO: implement a writeev() fast path var source_blob: Blob = brk: { if (data.as(Response)) |response| { switch (response.body.value) { .WTFStringImpl, .InternalBlob, .Used, .Empty, .Blob, .Null, => { break :brk response.body.use(); }, .Error => { destination_blob.detach(); const err = response.body.value.Error; err.unprotect(); _ = response.body.value.use(); return JSC.JSPromise.rejectedPromiseValue(globalThis, err); }, .Locked => { var task = bun.default_allocator.create(WriteFileWaitFromLockedValueTask) catch unreachable; var promise = JSC.JSPromise.create(globalThis); task.* = WriteFileWaitFromLockedValueTask{ .globalThis = globalThis, .file_blob = destination_blob, .promise = promise, }; response.body.value.Locked.task = task; response.body.value.Locked.onReceiveValue = WriteFileWaitFromLockedValueTask.thenWrap; return promise.asValue(globalThis); }, } } if (data.as(Request)) |request| { switch (request.body.value) { .WTFStringImpl, .InternalBlob, .Used, .Empty, .Blob, .Null, => { break :brk request.body.value.use(); }, .Error => { destination_blob.detach(); const err = request.body.value.Error; err.unprotect(); _ = request.body.value.use(); return JSC.JSPromise.rejectedPromiseValue(globalThis, err); }, .Locked => { var task = bun.default_allocator.create(WriteFileWaitFromLockedValueTask) catch unreachable; var promise = JSC.JSPromise.create(globalThis); task.* = WriteFileWaitFromLockedValueTask{ .globalThis = globalThis, .file_blob = destination_blob, .promise = promise, }; request.body.value.Locked.task = task; request.body.value.Locked.onReceiveValue = WriteFileWaitFromLockedValueTask.thenWrap; return promise.asValue(globalThis); }, } } break :brk Blob.get( globalThis, data, false, false, ) catch |err| { if (err == error.InvalidArguments) { globalThis.throwInvalidArguments( "Expected an Array", .{}, ); return .zero; } globalThis.throwOutOfMemory(); return .zero; }; }; var destination_store = destination_blob.store; if (destination_store) |store| { store.ref(); } defer { if (destination_store) |store| { store.deref(); } } return writeFileWithSourceDestination(globalThis, &source_blob, &destination_blob); } const write_permissions = 0o664; fn writeStringToFileFast( globalThis: *JSC.JSGlobalObject, pathlike: JSC.Node.PathOrFileDescriptor, str: bun.String, needs_async: *bool, comptime needs_open: bool, ) JSC.JSValue { const fd: bun.FileDescriptor = if (comptime !needs_open) pathlike.fd else brk: { var file_path: [bun.MAX_PATH_BYTES]u8 = undefined; switch (bun.sys.open( pathlike.path.sliceZ(&file_path), // we deliberately don't use O_TRUNC here // it's a perf optimization std.os.O.WRONLY | std.os.O.CREAT | std.os.O.NONBLOCK, write_permissions, )) { .result => |result| { break :brk result; }, .err => |err| { return JSC.JSPromise.rejectedPromiseValue( globalThis, err.withPath(pathlike.path.slice()).toJSC(globalThis), ); }, } unreachable; }; var truncate = needs_open or str.isEmpty(); var jsc_vm = globalThis.bunVM(); var written: usize = 0; defer { // we only truncate if it's a path // if it's a file descriptor, we assume they want manual control over that behavior if (truncate) { _ = bun.sys.ftruncate(fd, @as(i64, @intCast(written))); } if (needs_open) { _ = bun.sys.close(fd); } } if (!str.isEmpty()) { var decoded = str.toUTF8(jsc_vm.allocator); defer decoded.deinit(); var remain = decoded.slice(); while (remain.len > 0) { const result = bun.sys.write(fd, remain); switch (result) { .result => |res| { written += res; remain = remain[res..]; if (res == 0) break; }, .err => |err| { truncate = false; if (err.getErrno() == .AGAIN) { needs_async.* = true; return .zero; } if (comptime !needs_open) { return JSC.JSPromise.rejectedPromiseValue(globalThis, err.toJSC(globalThis)); } return JSC.JSPromise.rejectedPromiseValue( globalThis, err.withPath(pathlike.path.slice()).toJSC(globalThis), ); }, } } } return JSC.JSPromise.resolvedPromiseValue(globalThis, JSC.JSValue.jsNumber(written)); } fn writeBytesToFileFast( globalThis: *JSC.JSGlobalObject, pathlike: JSC.Node.PathOrFileDescriptor, bytes: []const u8, needs_async: *bool, comptime needs_open: bool, ) JSC.JSValue { const fd: bun.FileDescriptor = if (comptime !needs_open) pathlike.fd else brk: { var file_path: [bun.MAX_PATH_BYTES]u8 = undefined; switch (bun.sys.open( pathlike.path.sliceZ(&file_path), // we deliberately don't use O_TRUNC here // it's a perf optimization std.os.O.WRONLY | std.os.O.CREAT | std.os.O.NONBLOCK, write_permissions, )) { .result => |result| { break :brk result; }, .err => |err| { return JSC.JSPromise.rejectedPromiseValue( globalThis, err.withPath(pathlike.path.slice()).toJSC(globalThis), ); }, } unreachable; }; var truncate = needs_open or bytes.len == 0; var written: usize = 0; defer { if (truncate) { _ = bun.sys.ftruncate(fd, @as(i64, @intCast(written))); } if (needs_open) { _ = bun.sys.close(fd); } } var remain = bytes; const end = remain.ptr + remain.len; while (remain.ptr != end) { const result = bun.sys.write(fd, remain); switch (result) { .result => |res| { written += res; remain = remain[res..]; if (res == 0) break; }, .err => |err| { truncate = false; if (err.getErrno() == .AGAIN) { needs_async.* = true; return .zero; } if (comptime !needs_open) { return JSC.JSPromise.rejectedPromiseValue(globalThis, err.toJSC(globalThis)); } return JSC.JSPromise.rejectedPromiseValue( globalThis, err.withPath(pathlike.path.slice()).toJSC(globalThis), ); }, } } return JSC.JSPromise.resolvedPromiseValue(globalThis, JSC.JSValue.jsNumber(written)); } pub export fn JSDOMFile__hasInstance(_: JSC.JSValue, _: *JSC.JSGlobalObject, value: JSC.JSValue) callconv(.C) bool { JSC.markBinding(@src()); var blob = value.as(Blob) orelse return false; return blob.is_jsdom_file; } pub export fn JSDOMFile__construct( globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) ?*Blob { JSC.markBinding(@src()); var allocator = bun.default_allocator; var blob: Blob = undefined; var arguments = callframe.arguments(3); var args = arguments.ptr[0..arguments.len]; if (args.len < 2) { globalThis.throwInvalidArguments("new File(bits, name) expects at least 2 arguments", .{}); return null; } const name_value_str = bun.String.tryFromJS(args[1], globalThis) orelse { globalThis.throwInvalidArguments("new File(bits, name) expects string as the second argument", .{}); return null; }; blob = get(globalThis, args[0], false, true) catch |err| { if (err == error.InvalidArguments) { globalThis.throwInvalidArguments("new File(bits, name) expects iterable as the first argument", .{}); return null; } globalThis.throwOutOfMemory(); return null; }; if (blob.store) |store_| { store_.data.bytes.stored_name = bun.PathString.init( (name_value_str.toUTF8WithoutRef(bun.default_allocator).clone(bun.default_allocator) catch unreachable).slice(), ); } if (args.len > 2) { const options = args[2]; if (options.isObject()) { // type, the ASCII-encoded string in lower case // representing the media type of the Blob. // Normative conditions for this member are provided // in the § 3.1 Constructors. if (options.get(globalThis, "type")) |content_type| { inner: { if (content_type.isString()) { var content_type_str = content_type.toSlice(globalThis, bun.default_allocator); defer content_type_str.deinit(); var slice = content_type_str.slice(); if (!strings.isAllASCII(slice)) { break :inner; } blob.content_type_was_set = true; if (globalThis.bunVM().mimeType(slice)) |mime| { blob.content_type = mime.value; break :inner; } var content_type_buf = allocator.alloc(u8, slice.len) catch unreachable; blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } } } if (options.getTruthy(globalThis, "lastModified")) |last_modified| { blob.last_modified = last_modified.coerce(f64, globalThis); } } } if (blob.content_type.len == 0) { blob.content_type = ""; blob.content_type_was_set = false; } var blob_ = allocator.create(Blob) catch unreachable; blob_.* = blob; blob_.allocator = allocator; blob_.is_jsdom_file = true; return blob_; } fn estimatedByteSize(this: *Blob) usize { // in-memory size. not the size on disk. if (this.size != Blob.max_size) { return this.size; } var store = this.store orelse return 0; if (store.data == .bytes) { return store.data.bytes.len; } return 0; } pub fn estimatedSize(this: *Blob) callconv(.C) usize { var size = this.estimatedByteSize() + @sizeOf(Blob); if (this.store) |store| { size += @sizeOf(Blob.Store); size += switch (store.data) { .bytes => store.data.bytes.stored_name.estimatedSize(), .file => store.data.file.pathlike.estimatedSize(), }; } return size + (this.content_type.len * @as(usize, @intFromBool(this.content_type_allocated))); } comptime { if (!JSC.is_bindgen) { _ = JSDOMFile__hasInstance; _ = JSDOMFile__construct; } } pub fn constructBunFile( globalObject: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var vm = globalObject.bunVM(); const arguments = callframe.arguments(2).slice(); var args = JSC.Node.ArgumentsSlice.init(vm, arguments); defer args.deinit(); var exception_ = [1]JSC.JSValueRef{null}; var exception = &exception_; const path = JSC.Node.PathOrFileDescriptor.fromJS(globalObject, &args, args.arena.allocator(), exception) orelse { if (exception_[0] == null) { globalObject.throwInvalidArguments("Expected file path string or file descriptor", .{}); } else { globalObject.throwValue(exception_[0].?.value()); } return .undefined; }; var blob = Blob.findOrCreateFileFromPath(path, globalObject); if (arguments.len >= 2) { const opts = arguments[1]; if (opts.isObject()) { if (opts.getTruthy(globalObject, "type")) |file_type| { inner: { if (file_type.isString()) { var allocator = bun.default_allocator; var str = file_type.toSlice(globalObject, bun.default_allocator); defer str.deinit(); const slice = str.slice(); if (!strings.isAllASCII(slice)) { break :inner; } blob.content_type_was_set = true; if (vm.mimeType(str.slice())) |entry| { blob.content_type = entry.value; break :inner; } var content_type_buf = allocator.alloc(u8, slice.len) catch unreachable; blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } } } if (opts.getTruthy(globalObject, "lastModified")) |last_modified| { blob.last_modified = last_modified.coerce(f64, globalObject); } } } var ptr = bun.default_allocator.create(Blob) catch unreachable; ptr.* = blob; ptr.allocator = bun.default_allocator; return ptr.toJS(globalObject); } pub fn findOrCreateFileFromPath(path_: JSC.Node.PathOrFileDescriptor, globalThis: *JSGlobalObject) Blob { var vm = globalThis.bunVM(); const allocator = vm.allocator; const path: JSC.Node.PathOrFileDescriptor = brk: { switch (path_) { .path => { const slice = path_.path.slice(); if (vm.standalone_module_graph) |graph| { if (graph.find(slice)) |file| { return file.blob(globalThis).dupe(); } } var cloned = (allocator.dupeZ(u8, slice) catch unreachable)[0..slice.len]; break :brk .{ .path = .{ .string = bun.PathString.init(cloned), }, }; }, .fd => { switch (bun.FDTag.get(path_.fd)) { .stdin => return Blob.initWithStore( vm.rareData().stdin(), globalThis, ), .stderr => return Blob.initWithStore( vm.rareData().stderr(), globalThis, ), .stdout => return Blob.initWithStore( vm.rareData().stdout(), globalThis, ), else => {}, } break :brk path_; }, } }; return Blob.initWithStore(Blob.Store.initFile(path, null, allocator) catch unreachable, globalThis); } pub const Store = struct { data: Data, mime_type: MimeType = MimeType.none, ref_count: u32 = 0, is_all_ascii: ?bool = null, allocator: std.mem.Allocator, pub fn size(this: *const Store) SizeType { return switch (this.data) { .bytes => this.data.bytes.len, .file => Blob.max_size, }; } pub const Map = std.HashMap(u64, *JSC.WebCore.Blob.Store, IdentityContext(u64), 80); pub const Data = union(enum) { bytes: ByteStore, file: FileStore, }; pub fn ref(this: *Store) void { std.debug.assert(this.ref_count > 0); this.ref_count += 1; } pub fn external(ptr: ?*anyopaque, _: ?*anyopaque, _: usize) callconv(.C) void { if (ptr == null) return; var this = bun.cast(*Store, ptr); this.deref(); } pub fn initFile(pathlike: JSC.Node.PathOrFileDescriptor, mime_type: ?HTTPClient.MimeType, allocator: std.mem.Allocator) !*Store { var store = try allocator.create(Blob.Store); store.* = .{ .data = .{ .file = FileStore.init( pathlike, mime_type orelse brk: { if (pathlike == .path) { const sliced = pathlike.path.slice(); if (sliced.len > 0) { var extname = std.fs.path.extension(sliced); extname = std.mem.trim(u8, extname, "."); if (HTTPClient.MimeType.byExtensionNoDefault(extname)) |mime| { break :brk mime; } } } break :brk null; }, ), }, .allocator = allocator, .ref_count = 1, }; return store; } pub fn init(bytes: []u8, allocator: std.mem.Allocator) !*Store { var store = try allocator.create(Blob.Store); store.* = .{ .data = .{ .bytes = ByteStore.init(bytes, allocator) }, .allocator = allocator, .ref_count = 1, }; return store; } pub fn sharedView(this: Store) []u8 { if (this.data == .bytes) return this.data.bytes.slice(); return &[_]u8{}; } pub fn deref(this: *Blob.Store) void { std.debug.assert(this.ref_count >= 1); this.ref_count -= 1; if (this.ref_count == 0) { this.deinit(); } } pub fn deinit(this: *Blob.Store) void { const allocator = this.allocator; switch (this.data) { .bytes => |*bytes| { bytes.deinit(); }, .file => |file| { if (file.pathlike == .path) { allocator.free(bun.constStrToU8(file.pathlike.path.slice())); } }, } allocator.destroy(this); } const SerializeTag = enum(u8) { file = 0, bytes = 1, empty = 2, }; pub fn serialize(this: *Store, comptime Writer: type, writer: Writer) !void { switch (this.data) { .file => |file| { const pathlike_tag: JSC.Node.PathOrFileDescriptor.SerializeTag = if (file.pathlike == .fd) .fd else .path; try writer.writeInt(u8, @intFromEnum(pathlike_tag), .little); switch (file.pathlike) { .fd => |fd| { try writer.writeInt(u32, @as(u32, @intCast(fd)), .little); }, .path => |path| { const path_slice = path.slice(); try writer.writeInt(u32, @as(u32, @truncate(path_slice.len)), .little); _ = try writer.write(path_slice); }, } }, .bytes => |bytes| { const slice = bytes.slice(); try writer.writeInt(u32, @as(u32, @truncate(slice.len)), .little); _ = try writer.write(slice); }, } } pub fn fromArrayList(list: std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator) !*Blob.Store { return try Blob.Store.init(list.items, allocator); } pub fn FileOpenerMixin(comptime This: type) type { return struct { open_completion: AsyncIO.Completion = undefined, context: *This, const State = @This(); /// This is a workaround for some versions of IO uring returning /// EAGAIN when reading a file opened with O_NONBLOCK. Since io_uring waits, we don't need to wait. const non_block_without_io_uring = if (Environment.isLinux) 0 else std.os.O.NONBLOCK; const __opener_flags = non_block_without_io_uring | std.os.O.CLOEXEC; const open_flags_ = if (@hasDecl(This, "open_flags")) This.open_flags | __opener_flags else std.os.O.RDONLY | __opener_flags; pub fn getFdMac(this: *This) bun.FileDescriptor { var buf: [bun.MAX_PATH_BYTES]u8 = undefined; var path_string = if (@hasField(This, "file_store")) this.file_store.pathlike.path else this.file_blob.store.?.data.file.pathlike.path; var path = path_string.sliceZ(&buf); this.opened_fd = switch (bun.sys.open(path, open_flags_, JSC.Node.default_permission)) { .result => |fd| fd, .err => |err| { this.errno = AsyncIO.asError(err.errno); this.system_error = err.withPath(path_string.slice()).toSystemError(); this.opened_fd = null_fd; return null_fd; }, }; return this.opened_fd; } pub const OpenCallback = *const fn (*This, bun.FileDescriptor) void; pub fn getFd(this: *This, comptime Callback: OpenCallback) void { if (this.opened_fd != null_fd) { Callback(this, this.opened_fd); return; } if (@hasField(This, "file_store")) { const pathlike = this.file_store.pathlike; if (pathlike == .fd) { this.opened_fd = pathlike.fd; Callback(this, this.opened_fd); return; } } else { const pathlike = this.file_blob.store.?.data.file.pathlike; if (pathlike == .fd) { this.opened_fd = pathlike.fd; Callback(this, this.opened_fd); return; } } if (comptime Environment.isMac) { Callback(this, this.getFdMac()); } else { this.getFdLinux(Callback); } } const WrappedOpenCallback = *const fn (*State, *HTTPClient.NetworkThread.Completion, AsyncIO.OpenError!bun.FileDescriptor) void; fn OpenCallbackWrapper(comptime Callback: OpenCallback) WrappedOpenCallback { return struct { const callback = Callback; const StateHolder = State; pub fn onOpen(state: *State, completion: *HTTPClient.NetworkThread.Completion, result: AsyncIO.OpenError!bun.FileDescriptor) void { var this = state.context; var path_buffer = completion.operation.open.path; defer bun.default_allocator.free(bun.span(path_buffer)); defer bun.default_allocator.destroy(state); if (comptime Environment.isPosix) { this.opened_fd = result catch { this.errno = AsyncIO.asError(-completion.result); // do not use path_buffer here because it is a temporary var path_string = if (@hasField(This, "file_store")) this.file_store.pathlike.path else this.file_blob.store.?.data.file.pathlike.path; this.system_error = (bun.sys.Error{ .errno = @as(bun.sys.Error.Int, @intCast(-completion.result)), .path = path_string.slice(), .syscall = .open, }).toSystemError(); callback(this, null_fd); return; }; } else if (comptime Environment.isWindows) { this.opened_fd = result catch |err| { this.errno = err; // do not use path_buffer here because it is a temporary var path_string = if (@hasField(This, "file_store")) this.file_store.pathlike.path else this.file_blob.store.?.data.file.pathlike.path; this.system_error = (bun.sys.Error{ .errno = @as(bun.sys.Error.Int, @intFromEnum(bun.C.SystemErrno.fromError(err).?)), .path = path_string.slice(), .syscall = .open, }).toSystemError(); callback(this, null_fd); return; }; } else { @compileError("Unsupported platform"); } callback(this, this.opened_fd); } }.onOpen; } pub fn getFdLinux(this: *This, comptime callback: OpenCallback) void { var aio = &AsyncIO.global; var path_string = if (@hasField(This, "file_store")) this.file_store.pathlike.path else this.file_blob.store.?.data.file.pathlike.path; var holder = bun.default_allocator.create(State) catch unreachable; holder.* = .{ .context = this, }; var path_buffer = bun.default_allocator.dupeZ(u8, path_string.slice()) catch unreachable; aio.open( *State, holder, comptime OpenCallbackWrapper(callback), &holder.open_completion, path_buffer, open_flags_, JSC.Node.default_permission, ); } }; } pub fn FileCloserMixin(comptime This: type) type { return struct { const Closer = @This(); close_completion: AsyncIO.Completion = undefined, pub fn doClose(this: *This) void { const fd = this.opened_fd; std.debug.assert(fd != null_fd); var aio = &AsyncIO.global; var closer = bun.default_allocator.create(Closer) catch unreachable; aio.close( *Closer, closer, onClose, &closer.close_completion, fd, ); this.opened_fd = null_fd; } pub fn onClose(closer: *Closer, _: *HTTPClient.NetworkThread.Completion, _: AsyncIO.CloseError!void) void { bun.default_allocator.destroy(closer); } }; } pub const ReadFile = struct { file_store: FileStore, byte_store: ByteStore = ByteStore{ .allocator = bun.default_allocator }, store: ?*Store = null, offset: SizeType = 0, max_length: SizeType = Blob.max_size, opened_fd: bun.FileDescriptor = null_fd, read_completion: HTTPClient.NetworkThread.Completion = undefined, read_len: SizeType = 0, read_off: SizeType = 0, read_eof: bool = false, size: SizeType = 0, buffer: []u8 = undefined, task: HTTPClient.NetworkThread.Task = undefined, system_error: ?JSC.SystemError = null, errno: ?anyerror = null, onCompleteCtx: *anyopaque = undefined, onCompleteCallback: OnReadFileCallback = undefined, io_task: ?*ReadFileTask = null, pub const Read = struct { buf: []u8, is_temporary: bool = false, total_size: SizeType = 0, }; pub const ResultType = SystemError.Maybe(Read); pub const OnReadFileCallback = *const fn (ctx: *anyopaque, bytes: ResultType) void; pub usingnamespace FileOpenerMixin(ReadFile); pub usingnamespace FileCloserMixin(ReadFile); pub fn createWithCtx( allocator: std.mem.Allocator, store: *Store, onReadFileContext: *anyopaque, onCompleteCallback: OnReadFileCallback, off: SizeType, max_len: SizeType, ) !*ReadFile { var read_file = try allocator.create(ReadFile); read_file.* = ReadFile{ .file_store = store.data.file, .offset = off, .max_length = max_len, .store = store, .onCompleteCtx = onReadFileContext, .onCompleteCallback = onCompleteCallback, }; store.ref(); return read_file; } pub fn create( allocator: std.mem.Allocator, store: *Store, off: SizeType, max_len: SizeType, comptime Context: type, context: Context, comptime callback: fn (ctx: Context, bytes: ResultType) void, ) !*ReadFile { const Handler = struct { pub fn run(ptr: *anyopaque, bytes: ResultType) void { callback(bun.cast(Context, ptr), bytes); } }; return try ReadFile.createWithCtx(allocator, store, @as(*anyopaque, @ptrCast(context)), Handler.run, off, max_len); } pub fn doRead(this: *ReadFile) void { var aio = &AsyncIO.global; var remaining = this.buffer[this.read_off..]; this.read_len = 0; aio.read( *ReadFile, this, onRead, &this.read_completion, this.opened_fd, remaining[0..@min(remaining.len, this.max_length - this.read_off)], this.offset + this.read_off, ); } pub const ReadFileTask = JSC.IOTask(@This()); pub fn then(this: *ReadFile, _: *JSC.JSGlobalObject) void { var cb = this.onCompleteCallback; var cb_ctx = this.onCompleteCtx; if (this.store == null and this.system_error != null) { var system_error = this.system_error.?; bun.default_allocator.destroy(this); cb(cb_ctx, ResultType{ .err = system_error }); return; } else if (this.store == null) { bun.default_allocator.destroy(this); cb(cb_ctx, ResultType{ .err = SystemError{ .code = bun.String.static("INTERNAL_ERROR"), .message = bun.String.static("assertion failure - store should not be null"), .syscall = bun.String.static("read"), }, }); return; } var store = this.store.?; var buf = this.buffer; defer store.deref(); defer bun.default_allocator.destroy(this); if (this.system_error) |err| { cb(cb_ctx, ResultType{ .err = err }); return; } cb(cb_ctx, .{ .result = .{ .buf = buf, .total_size = this.size, .is_temporary = true } }); } pub fn run(this: *ReadFile, task: *ReadFileTask) void { this.runAsync(task); } pub fn onRead(this: *ReadFile, completion: *HTTPClient.NetworkThread.Completion, result: AsyncIO.ReadError!usize) void { defer this.doReadLoop(); const read_len = @as(SizeType, @truncate(result catch |err| { if (@hasField(HTTPClient.NetworkThread.Completion, "result")) { this.errno = AsyncIO.asError(-completion.result); this.system_error = (bun.sys.Error{ .errno = @as(bun.sys.Error.Int, @intCast(-completion.result)), .syscall = .read, }).toSystemError(); } else { this.system_error = JSC.SystemError{ .code = bun.String.static(bun.asByteSlice(@errorName(err))), .path = if (this.file_store.pathlike == .path) bun.String.create(this.file_store.pathlike.path.slice()) else bun.String.empty, .syscall = bun.String.static("read"), }; this.errno = err; } this.read_len = 0; return; })); this.read_eof = read_len == 0; this.read_len = read_len; } fn runAsync(this: *ReadFile, task: *ReadFileTask) void { this.io_task = task; if (this.file_store.pathlike == .fd) { this.opened_fd = this.file_store.pathlike.fd; } this.getFd(runAsyncWithFD); } fn onFinish(this: *ReadFile) void { const fd = this.opened_fd; const file = &this.file_store; const needs_close = fd != null_fd and file.pathlike == .path and fd > 2; this.size = @max(this.read_len, this.size); if (needs_close) { this.doClose(); } if (this.io_task) |io_task| { io_task.onFinish(); this.io_task = null; } } fn resolveSizeAndLastModified(this: *ReadFile, fd: bun.FileDescriptor) void { if (comptime Environment.isWindows) { bun.todo(@src(), {}); return; } const stat: bun.Stat = switch (bun.sys.fstat(fd)) { .result => |result| result, .err => |err| { this.errno = AsyncIO.asError(err.errno); this.system_error = err.toSystemError(); return; }, }; if (this.store) |store| { if (store.data == .file) { store.data.file.last_modified = toJSTime(stat.mtime().tv_sec, stat.mtime().tv_nsec); } } if (std.os.S.ISDIR(stat.mode)) { this.errno = error.EISDIR; this.system_error = JSC.SystemError{ .code = bun.String.static("EISDIR"), .path = if (this.file_store.pathlike == .path) bun.String.create(this.file_store.pathlike.path.slice()) else bun.String.empty, .message = bun.String.static("Directories cannot be read like files"), .syscall = bun.String.static("read"), }; return; } if (stat.size > 0 and bun.isRegularFile(stat.mode)) { this.size = @min( @as(SizeType, @truncate(@as(SizeType, @intCast(@max(@as(i64, @intCast(stat.size)), 0))))), this.max_length, ); // read up to 4k at a time if // they didn't explicitly set a size and we're reading from something that's not a regular file } else if (stat.size == 0 and !bun.isRegularFile(stat.mode)) { this.size = if (this.max_length == Blob.max_size) 4096 else this.max_length; } } fn runAsyncWithFD(this: *ReadFile, fd: bun.FileDescriptor) void { if (this.errno != null) { this.onFinish(); return; } this.resolveSizeAndLastModified(fd); if (this.errno != null) return this.onFinish(); if (this.size == 0) { this.buffer = &[_]u8{}; this.byte_store = ByteStore.init(this.buffer, bun.default_allocator); this.onFinish(); } this.buffer = bun.default_allocator.alloc(u8, this.size) catch |err| { this.errno = err; this.onFinish(); return; }; this.read_len = 0; this.doReadLoop(); } fn doReadLoop(this: *ReadFile) void { this.read_off += this.read_len; var remain = this.buffer[@min(this.read_off, @as(Blob.SizeType, @truncate(this.buffer.len)))..]; if (remain.len > 0 and this.errno == null and !this.read_eof) { this.doRead(); return; } _ = bun.default_allocator.resize(this.buffer, this.read_off); this.buffer = this.buffer[0..this.read_off]; this.byte_store = ByteStore.init(this.buffer, bun.default_allocator); this.onFinish(); } }; pub const WriteFile = struct { file_blob: Blob, bytes_blob: Blob, opened_fd: bun.FileDescriptor = null_fd, system_error: ?JSC.SystemError = null, errno: ?anyerror = null, write_completion: HTTPClient.NetworkThread.Completion = undefined, task: HTTPClient.NetworkThread.Task = undefined, io_task: ?*WriteFileTask = null, onCompleteCtx: *anyopaque = undefined, onCompleteCallback: OnWriteFileCallback = undefined, wrote: usize = 0, pub const ResultType = SystemError.Maybe(SizeType); pub const OnWriteFileCallback = *const fn (ctx: *anyopaque, count: ResultType) void; pub usingnamespace FileOpenerMixin(WriteFile); pub usingnamespace FileCloserMixin(WriteFile); // Do not open with APPEND because we may use pwrite() pub const open_flags = std.os.O.WRONLY | std.os.O.CREAT | std.os.O.TRUNC; pub fn createWithCtx( allocator: std.mem.Allocator, file_blob: Blob, bytes_blob: Blob, onWriteFileContext: *anyopaque, onCompleteCallback: OnWriteFileCallback, ) !*WriteFile { var read_file = try allocator.create(WriteFile); read_file.* = WriteFile{ .file_blob = file_blob, .bytes_blob = bytes_blob, .onCompleteCtx = onWriteFileContext, .onCompleteCallback = onCompleteCallback, }; file_blob.store.?.ref(); bytes_blob.store.?.ref(); return read_file; } pub fn create( allocator: std.mem.Allocator, file_blob: Blob, bytes_blob: Blob, comptime Context: type, context: Context, comptime callback: fn (ctx: Context, bytes: ResultType) void, ) !*WriteFile { const Handler = struct { pub fn run(ptr: *anyopaque, bytes: ResultType) void { callback(bun.cast(Context, ptr), bytes); } }; return try WriteFile.createWithCtx( allocator, file_blob, bytes_blob, @as(*anyopaque, @ptrCast(context)), Handler.run, ); } pub fn doWrite( this: *WriteFile, buffer: []const u8, file_offset: u64, ) void { var aio = &AsyncIO.global; this.wrote = 0; const fd = this.opened_fd; std.debug.assert(fd != null_fd); aio.write( *WriteFile, this, onWrite, &this.write_completion, fd, buffer, if (fd > 2) file_offset else 0, ); } pub const WriteFileTask = JSC.IOTask(@This()); pub fn then(this: *WriteFile, _: *JSC.JSGlobalObject) void { var cb = this.onCompleteCallback; var cb_ctx = this.onCompleteCtx; this.bytes_blob.store.?.deref(); this.file_blob.store.?.deref(); if (this.system_error) |err| { bun.default_allocator.destroy(this); cb(cb_ctx, .{ .err = err, }); return; } const wrote = this.wrote; bun.default_allocator.destroy(this); cb(cb_ctx, .{ .result = @as(SizeType, @truncate(wrote)) }); } pub fn run(this: *WriteFile, task: *WriteFileTask) void { this.io_task = task; this.runAsync(); } pub fn onWrite(this: *WriteFile, _: *HTTPClient.NetworkThread.Completion, result: AsyncIO.WriteError!usize) void { defer this.doWriteLoop(); this.wrote += @as(SizeType, @truncate(result catch |errno| { this.errno = errno; this.system_error = this.system_error orelse JSC.SystemError{ .code = bun.String.static(bun.asByteSlice(@errorName(errno))), .syscall = bun.String.static("write"), }; this.wrote = 0; return; })); } fn runAsync(this: *WriteFile) void { this.getFd(runWithFD); } fn onFinish(this: *WriteFile) void { const fd = this.opened_fd; const file = this.file_blob.store.?.data.file; const needs_close = fd != null_fd and file.pathlike == .path and fd > 2; if (needs_close) { this.doClose(); } if (this.io_task) |io_task| { io_task.onFinish(); this.io_task = null; } } fn runWithFD(this: *WriteFile, fd: bun.FileDescriptor) void { if (fd == null_fd or this.errno != null) { this.onFinish(); return; } this.doWriteLoop(); } fn doWriteLoop(this: *WriteFile) void { var remain = this.bytes_blob.sharedView(); var file_offset = this.file_blob.offset; const this_tick = file_offset + this.wrote; remain = remain[@min(this.wrote, remain.len)..]; if (remain.len > 0 and this.errno == null) { this.doWrite(remain, this_tick); } else { this.onFinish(); } } }; pub const IOWhich = enum { source, destination, both, }; const unsupported_directory_error = SystemError{ .errno = @as(c_int, @intCast(@intFromEnum(bun.C.SystemErrno.EISDIR))), .message = bun.String.static("That doesn't work on folders"), .syscall = bun.String.static("fstat"), }; const unsupported_non_regular_file_error = SystemError{ .errno = @as(c_int, @intCast(@intFromEnum(bun.C.SystemErrno.ENOTSUP))), .message = bun.String.static("Non-regular files aren't supported yet"), .syscall = bun.String.static("fstat"), }; // blocking, but off the main thread pub const CopyFile = struct { destination_file_store: FileStore, source_file_store: FileStore, store: ?*Store = null, source_store: ?*Store = null, offset: SizeType = 0, size: SizeType = 0, max_length: SizeType = Blob.max_size, destination_fd: bun.FileDescriptor = null_fd, source_fd: bun.FileDescriptor = null_fd, system_error: ?SystemError = null, read_len: SizeType = 0, read_off: SizeType = 0, globalThis: *JSGlobalObject, pub const ResultType = anyerror!SizeType; pub const Callback = *const fn (ctx: *anyopaque, len: ResultType) void; pub const CopyFilePromiseTask = JSC.ConcurrentPromiseTask(CopyFile); pub const CopyFilePromiseTaskEventLoopTask = CopyFilePromiseTask.EventLoopTask; pub fn create( allocator: std.mem.Allocator, store: *Store, source_store: *Store, off: SizeType, max_len: SizeType, globalThis: *JSC.JSGlobalObject, ) !*CopyFilePromiseTask { var read_file = try allocator.create(CopyFile); read_file.* = CopyFile{ .store = store, .source_store = source_store, .offset = off, .max_length = max_len, .globalThis = globalThis, .destination_file_store = store.data.file, .source_file_store = source_store.data.file, }; store.ref(); source_store.ref(); return try CopyFilePromiseTask.createOnJSThread(allocator, globalThis, read_file); } const linux = std.os.linux; const darwin = std.os.darwin; pub fn deinit(this: *CopyFile) void { if (this.source_file_store.pathlike == .path) { if (this.source_file_store.pathlike.path == .string and this.system_error == null) { bun.default_allocator.free(bun.constStrToU8(this.source_file_store.pathlike.path.slice())); } } this.store.?.deref(); bun.default_allocator.destroy(this); } pub fn reject(this: *CopyFile, promise: *JSC.JSPromise) void { var globalThis = this.globalThis; var system_error: SystemError = this.system_error orelse SystemError{}; if (this.source_file_store.pathlike == .path and system_error.path.isEmpty()) { system_error.path = bun.String.create(this.source_file_store.pathlike.path.slice()); } if (system_error.message.isEmpty()) { system_error.message = bun.String.static("Failed to copy file"); } var instance = system_error.toErrorInstance(this.globalThis); if (this.store) |store| { store.deref(); } promise.reject(globalThis, instance); } pub fn then(this: *CopyFile, promise: *JSC.JSPromise) void { this.source_store.?.deref(); if (this.system_error != null) { this.reject(promise); return; } promise.resolve(this.globalThis, JSC.JSValue.jsNumberFromUint64(this.read_len)); } pub fn run(this: *CopyFile) void { this.runAsync(); } pub fn doClose(this: *CopyFile) void { const close_input = this.destination_file_store.pathlike != .fd and this.destination_fd != null_fd; const close_output = this.source_file_store.pathlike != .fd and this.source_fd != null_fd; if (close_input and close_output) { this.doCloseFile(.both); } else if (close_input) { this.doCloseFile(.destination); } else if (close_output) { this.doCloseFile(.source); } } const os = std.os; pub fn doCloseFile(this: *CopyFile, comptime which: IOWhich) void { switch (which) { .both => { _ = bun.sys.close(this.destination_fd); _ = bun.sys.close(this.source_fd); }, .destination => { _ = bun.sys.close(this.destination_fd); }, .source => { _ = bun.sys.close(this.source_fd); }, } } const O = if (Environment.isLinux) linux.O else std.os.O; const open_destination_flags = O.CLOEXEC | O.CREAT | O.WRONLY | O.TRUNC; const open_source_flags = O.CLOEXEC | O.RDONLY; pub fn doOpenFile(this: *CopyFile, comptime which: IOWhich) !void { // open source file first // if it fails, we don't want the extra destination file hanging out if (which == .both or which == .source) { this.source_fd = switch (bun.sys.open( this.source_file_store.pathlike.path.sliceZAssume(), open_source_flags, 0, )) { .result => |result| result, .err => |errno| { this.system_error = errno.toSystemError(); return AsyncIO.asError(errno.errno); }, }; } if (which == .both or which == .destination) { this.destination_fd = switch (bun.sys.open( this.destination_file_store.pathlike.path.sliceZAssume(), open_destination_flags, JSC.Node.default_permission, )) { .result => |result| result, .err => |errno| { if (which == .both) { _ = bun.sys.close(this.source_fd); this.source_fd = 0; } this.system_error = errno.withPath(this.destination_file_store.pathlike.path.slice()).toSystemError(); return AsyncIO.asError(errno.errno); }, }; } } const TryWith = enum { sendfile, copy_file_range, splice, pub const tag = std.EnumMap(TryWith, bun.sys.Tag).init(.{ .sendfile = .sendfile, .copy_file_range = .copy_file_range, .splice = .splice, }); }; pub fn doCopyFileRange( this: *CopyFile, comptime use: TryWith, comptime clear_append_if_invalid: bool, ) anyerror!void { this.read_off += this.offset; var remain = @as(usize, this.max_length); const unknown_size = remain == max_size or remain == 0; if (unknown_size) { // sometimes stat lies // let's give it 4096 and see how it goes remain = 4096; } var total_written: usize = 0; const src_fd = this.source_fd; const dest_fd = this.destination_fd; defer { this.read_len = @as(SizeType, @truncate(total_written)); } var has_unset_append = false; // If they can't use copy_file_range, they probably also can't // use sendfile() or splice() if (!bun.canUseCopyFileRangeSyscall()) { switch (JSC.Node.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return AsyncIO.asError(err.errno); }, .result => { _ = linux.ftruncate(dest_fd, @as(std.os.off_t, @intCast(total_written))); return; }, } } while (true) { const written = switch (comptime use) { .copy_file_range => linux.copy_file_range(src_fd, null, dest_fd, null, remain, 0), .sendfile => linux.sendfile(dest_fd, src_fd, null, remain), .splice => bun.C.splice(src_fd, null, dest_fd, null, remain, 0), }; switch (linux.getErrno(written)) { .SUCCESS => {}, .NOSYS, .XDEV => { switch (JSC.Node.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return AsyncIO.asError(err.errno); }, .result => { _ = linux.ftruncate(dest_fd, @as(std.os.off_t, @intCast(total_written))); return; }, } }, .INVAL => { if (comptime clear_append_if_invalid) { if (!has_unset_append) { // https://kylelaker.com/2018/08/31/stdout-oappend.html // make() can set STDOUT / STDERR to O_APPEND // this messes up sendfile() has_unset_append = true; const flags = linux.fcntl(dest_fd, linux.F.GETFL, 0); if ((flags & O.APPEND) != 0) { _ = linux.fcntl(dest_fd, linux.F.SETFL, flags ^ O.APPEND); continue; } } } // If the Linux machine doesn't support // copy_file_range or the file descrpitor is // incompatible with the chosen syscall, fall back // to a read/write loop if (total_written == 0) { switch (JSC.Node.NodeFS.copyFileUsingReadWriteLoop("", "", src_fd, dest_fd, if (unknown_size) 0 else remain, &total_written)) { .err => |err| { this.system_error = err.toSystemError(); return AsyncIO.asError(err.errno); }, .result => { _ = linux.ftruncate(dest_fd, @as(std.os.off_t, @intCast(total_written))); return; }, } } this.system_error = (bun.sys.Error{ .errno = @as(bun.sys.Error.Int, @intCast(@intFromEnum(linux.E.INVAL))), .syscall = TryWith.tag.get(use).?, }).toSystemError(); return AsyncIO.asError(linux.E.INVAL); }, else => |errno| { this.system_error = (bun.sys.Error{ .errno = @as(bun.sys.Error.Int, @intCast(@intFromEnum(errno))), .syscall = TryWith.tag.get(use).?, }).toSystemError(); return AsyncIO.asError(errno); }, } // wrote zero bytes means EOF remain -|= written; total_written += written; if (written == 0 or remain == 0) break; } } pub fn doFCopyFile(this: *CopyFile) anyerror!void { switch (bun.sys.fcopyfile(this.source_fd, this.destination_fd, os.system.COPYFILE_DATA)) { .err => |errno| { this.system_error = errno.toSystemError(); return AsyncIO.asError(errno.errno); }, .result => {}, } } pub fn doClonefile(this: *CopyFile) anyerror!void { var source_buf: [bun.MAX_PATH_BYTES]u8 = undefined; var dest_buf: [bun.MAX_PATH_BYTES]u8 = undefined; switch (bun.sys.clonefile( this.source_file_store.pathlike.path.sliceZ(&source_buf), this.destination_file_store.pathlike.path.sliceZ( &dest_buf, ), )) { .err => |errno| { this.system_error = errno.toSystemError(); return AsyncIO.asError(errno.errno); }, .result => {}, } } pub fn runAsync(this: *CopyFile) void { // defer task.onFinish(); var stat_: ?bun.Stat = null; if (this.destination_file_store.pathlike == .fd) { this.destination_fd = this.destination_file_store.pathlike.fd; } if (this.source_file_store.pathlike == .fd) { this.source_fd = this.source_file_store.pathlike.fd; } if (comptime Environment.isWindows) { this.system_error = SystemError{ .code = bun.String.static("TODO"), .syscall = bun.String.static("CopyFileEx"), .message = bun.String.static("Not implemented on Windows yet"), }; return; } // Do we need to open both files? if (this.destination_fd == null_fd and this.source_fd == null_fd) { // First, we attempt to clonefile() on macOS // This is the fastest way to copy a file. if (comptime Environment.isMac) { if (this.offset == 0 and this.source_file_store.pathlike == .path and this.destination_file_store.pathlike == .path) { do_clonefile: { // stat the output file, make sure it: // 1. Exists switch (bun.sys.stat(this.source_file_store.pathlike.path.sliceZAssume())) { .result => |result| { stat_ = result; if (os.S.ISDIR(result.mode)) { this.system_error = unsupported_directory_error; return; } if (!os.S.ISREG(result.mode)) break :do_clonefile; }, .err => |err| { // If we can't stat it, we also can't copy it. this.system_error = err.toSystemError(); return; }, } if (this.doClonefile()) { if (this.max_length != Blob.max_size and this.max_length < @as(SizeType, @intCast(stat_.?.size))) { // If this fails...well, there's not much we can do about it. _ = bun.C.truncate( this.destination_file_store.pathlike.path.sliceZAssume(), @as(std.os.off_t, @intCast(this.max_length)), ); this.read_len = @as(SizeType, @intCast(this.max_length)); } else { this.read_len = @as(SizeType, @intCast(stat_.?.size)); } return; } else |_| { // this may still fail, in which case we just continue trying with fcopyfile // it can fail when the input file already exists // or if the output is not a directory // or if it's a network volume this.system_error = null; } } } } this.doOpenFile(.both) catch return; // Do we need to open only one file? } else if (this.destination_fd == null_fd) { this.source_fd = this.source_file_store.pathlike.fd; this.doOpenFile(.destination) catch return; // Do we need to open only one file? } else if (this.source_fd == null_fd) { this.destination_fd = this.destination_file_store.pathlike.fd; this.doOpenFile(.source) catch return; } if (this.system_error != null) { return; } std.debug.assert(this.destination_fd != null_fd); std.debug.assert(this.source_fd != null_fd); if (this.destination_file_store.pathlike == .fd) {} const stat: bun.Stat = stat_ orelse switch (bun.sys.fstat(this.source_fd)) { .result => |result| result, .err => |err| { this.doClose(); this.system_error = err.toSystemError(); return; }, }; if (os.S.ISDIR(stat.mode)) { this.system_error = unsupported_directory_error; this.doClose(); return; } if (stat.size != 0) { this.max_length = @max(@min(@as(SizeType, @intCast(stat.size)), this.max_length), this.offset) - this.offset; if (this.max_length == 0) { this.doClose(); return; } if (os.S.ISREG(stat.mode) and this.max_length > bun.C.preallocate_length and this.max_length != Blob.max_size) { bun.C.preallocate_file(this.destination_fd, 0, this.max_length) catch {}; } } if (comptime Environment.isLinux) { // Bun.write(Bun.file("a"), Bun.file("b")) if (os.S.ISREG(stat.mode) and (os.S.ISREG(this.destination_file_store.mode) or this.destination_file_store.mode == 0)) { if (this.destination_file_store.is_atty orelse false) { this.doCopyFileRange(.copy_file_range, true) catch {}; } else { this.doCopyFileRange(.copy_file_range, false) catch {}; } this.doClose(); return; } // $ bun run foo.js | bun run bar.js if (os.S.ISFIFO(stat.mode) and os.S.ISFIFO(this.destination_file_store.mode)) { if (this.destination_file_store.is_atty orelse false) { this.doCopyFileRange(.splice, true) catch {}; } else { this.doCopyFileRange(.splice, false) catch {}; } this.doClose(); return; } if (os.S.ISREG(stat.mode) or os.S.ISCHR(stat.mode) or os.S.ISSOCK(stat.mode)) { if (this.destination_file_store.is_atty orelse false) { this.doCopyFileRange(.sendfile, true) catch {}; } else { this.doCopyFileRange(.sendfile, false) catch {}; } this.doClose(); return; } this.system_error = unsupported_non_regular_file_error; this.doClose(); return; } if (comptime Environment.isMac) { this.doFCopyFile() catch { this.doClose(); return; }; if (stat.size != 0 and @as(SizeType, @intCast(stat.size)) > this.max_length) { _ = darwin.ftruncate(this.destination_fd, @as(std.os.off_t, @intCast(this.max_length))); } this.doClose(); } else { @compileError("TODO: implement copyfile"); } } }; }; pub const FileStore = struct { pathlike: JSC.Node.PathOrFileDescriptor, mime_type: HTTPClient.MimeType = HTTPClient.MimeType.other, is_atty: ?bool = null, mode: bun.Mode = 0, seekable: ?bool = null, max_size: SizeType = Blob.max_size, // milliseconds since ECMAScript epoch last_modified: JSTimeType = init_timestamp, pub fn isSeekable(this: *const FileStore) ?bool { if (this.seekable) |seekable| { return seekable; } if (this.mode != 0) { return bun.isRegularFile(this.mode); } return null; } pub fn init(pathlike: JSC.Node.PathOrFileDescriptor, mime_type: ?HTTPClient.MimeType) FileStore { return .{ .pathlike = pathlike, .mime_type = mime_type orelse HTTPClient.MimeType.other }; } }; pub const ByteStore = struct { ptr: [*]u8 = undefined, len: SizeType = 0, cap: SizeType = 0, allocator: std.mem.Allocator, /// Used by standalone module graph and the File constructor stored_name: bun.PathString = bun.PathString.empty, pub fn init(bytes: []u8, allocator: std.mem.Allocator) ByteStore { return .{ .ptr = bytes.ptr, .len = @as(SizeType, @truncate(bytes.len)), .cap = @as(SizeType, @truncate(bytes.len)), .allocator = allocator, }; } pub fn fromArrayList(list: std.ArrayListUnmanaged(u8), allocator: std.mem.Allocator) !*ByteStore { return ByteStore.init(list.items, allocator); } pub fn slice(this: ByteStore) []u8 { return this.ptr[0..this.len]; } pub fn deinit(this: *ByteStore) void { bun.default_allocator.free(this.stored_name.slice()); this.allocator.free(this.ptr[0..this.cap]); } pub fn asArrayList(this: ByteStore) std.ArrayListUnmanaged(u8) { return this.asArrayListLeak(); } pub fn asArrayListLeak(this: ByteStore) std.ArrayListUnmanaged(u8) { return .{ .items = this.ptr[0..this.len], .capacity = this.cap, }; } }; pub fn getStream( this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var recommended_chunk_size: SizeType = 0; var arguments_ = callframe.arguments(2); var arguments = arguments_.ptr[0..arguments_.len]; if (arguments.len > 0) { if (!arguments[0].isNumber() and !arguments[0].isUndefinedOrNull()) { globalThis.throwInvalidArguments("chunkSize must be a number", .{}); return JSValue.jsUndefined(); } recommended_chunk_size = @as(SizeType, @intCast(@max(0, @as(i52, @truncate(arguments[0].toInt64()))))); } return JSC.WebCore.ReadableStream.fromBlob( globalThis, this, recommended_chunk_size, ); } fn promisified( value: JSC.JSValue, global: *JSGlobalObject, ) JSC.JSValue { return JSC.JSPromise.wrap(global, value); } pub fn getText( this: *Blob, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); return promisified(this.toString(globalThis, .clone), globalThis); } pub fn getTextTransfer( this: *Blob, globalObject: *JSC.JSGlobalObject, ) JSC.JSValue { var store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); return promisified(this.toString(globalObject, .transfer), globalObject); } pub fn getJSON( this: *Blob, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); return promisified(this.toJSON(globalThis, .share), globalThis); } pub fn getArrayBufferTransfer( this: *Blob, globalThis: *JSC.JSGlobalObject, ) JSC.JSValue { var store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); return promisified(this.toArrayBuffer(globalThis, .transfer), globalThis); } pub fn getArrayBuffer( this: *Blob, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame, ) callconv(.C) JSValue { var store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); return promisified(this.toArrayBuffer(globalThis, .clone), globalThis); } pub fn getFormData( this: *Blob, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame, ) callconv(.C) JSValue { var store = this.store; if (store) |st| st.ref(); defer if (store) |st| st.deref(); return promisified(this.toFormData(globalThis, .temporary), globalThis); } fn getExistsSync(this: *Blob) JSC.JSValue { if (this.size == Blob.max_size) { this.resolveSize(); } // If there's no store that means it's empty and we just return true // it will not error to return an empty Blob var store = this.store orelse return JSValue.jsBoolean(true); if (store.data == .bytes) { // Bytes will never error return JSValue.jsBoolean(true); } if (comptime Environment.isWindows) { this.globalThis.throwTODO("exists is not implemented on Windows"); return JSValue.jsUndefined(); } // We say regular files and pipes exist. // This is mostly meant for "Can we use this in new Response(file)?" return JSValue.jsBoolean(bun.isRegularFile(store.data.file.mode) or std.os.S.ISFIFO(store.data.file.mode)); } // This mostly means 'can it be read?' pub fn getExists( this: *Blob, globalThis: *JSC.JSGlobalObject, _: *JSC.CallFrame, ) callconv(.C) JSValue { return JSC.JSPromise.resolvedPromiseValue(globalThis, this.getExistsSync()); } pub fn getWriter( this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var arguments_ = callframe.arguments(1); var arguments = arguments_.ptr[0..arguments_.len]; if (!arguments.ptr[0].isEmptyOrUndefinedOrNull() and !arguments.ptr[0].isObject()) { globalThis.throwInvalidArguments("options must be an object or undefined", .{}); return JSValue.jsUndefined(); } var store = this.store orelse { globalThis.throwInvalidArguments("Blob is detached", .{}); return JSValue.jsUndefined(); }; if (store.data != .file) { globalThis.throwInvalidArguments("Blob is read-only", .{}); return JSValue.jsUndefined(); } var sink = JSC.WebCore.FileSink.init(globalThis.allocator(), null) catch |err| { globalThis.throwInvalidArguments("Failed to create FileSink: {s}", .{@errorName(err)}); return JSValue.jsUndefined(); }; const input_path: JSC.WebCore.PathOrFileDescriptor = brk: { if (store.data.file.pathlike == .fd) { break :brk .{ .fd = store.data.file.pathlike.fd }; } else { break :brk .{ .path = ZigString.Slice.fromUTF8NeverFree( store.data.file.pathlike.path.slice(), ).clone( globalThis.allocator(), ) catch unreachable, }; } }; defer input_path.deinit(); var stream_start: JSC.WebCore.StreamStart = .{ .FileSink = .{ .input_path = input_path, }, }; if (arguments.len > 0 and arguments.ptr[0].isObject()) { stream_start = JSC.WebCore.StreamStart.fromJSWithTag(globalThis, arguments[0], .FileSink); stream_start.FileSink.input_path = input_path; } switch (sink.start(stream_start)) { .err => |err| { globalThis.vm().throwError(globalThis, err.toJSC(globalThis)); sink.finalize(); return JSC.JSValue.zero; }, else => {}, } return sink.toJS(globalThis); } /// https://w3c.github.io/FileAPI/#slice-method-algo /// The slice() method returns a new Blob object with bytes ranging from the /// optional start parameter up to but not including the optional end /// parameter, and with a type attribute that is the value of the optional /// contentType parameter. It must act as follows: pub fn getSlice( this: *Blob, globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) JSC.JSValue { var allocator = globalThis.allocator(); var arguments_ = callframe.arguments(3); var args = arguments_.ptr[0..arguments_.len]; if (this.size == 0) { const empty = Blob.initEmpty(globalThis); var ptr = allocator.create(Blob) catch { return JSC.JSValue.jsUndefined(); }; ptr.* = empty; ptr.allocator = allocator; return ptr.toJS(globalThis); } // If the optional start parameter is not used as a parameter when making this call, let relativeStart be 0. var relativeStart: i64 = 0; // If the optional end parameter is not used as a parameter when making this call, let relativeEnd be size. var relativeEnd: i64 = @as(i64, @intCast(this.size)); if (args.ptr[0].isString()) { args.ptr[2] = args.ptr[0]; args.ptr[1] = .zero; args.ptr[0] = .zero; args.len = 3; } else if (args.ptr[1].isString()) { args.ptr[2] = args.ptr[1]; args.ptr[1] = .zero; args.len = 3; } var args_iter = JSC.Node.ArgumentsSlice.init(globalThis.bunVM(), args); if (args_iter.nextEat()) |start_| { if (start_.isNumber()) { const start = start_.toInt64(); if (start < 0) { // If the optional start parameter is negative, let relativeStart be start + size. relativeStart = @as(i64, @intCast(@max(start +% @as(i64, @intCast(this.size)), 0))); } else { // Otherwise, let relativeStart be start. relativeStart = @min(@as(i64, @intCast(start)), @as(i64, @intCast(this.size))); } } } if (args_iter.nextEat()) |end_| { if (end_.isNumber()) { const end = end_.toInt64(); // If end is negative, let relativeEnd be max((size + end), 0). if (end < 0) { // If the optional start parameter is negative, let relativeStart be start + size. relativeEnd = @as(i64, @intCast(@max(end +% @as(i64, @intCast(this.size)), 0))); } else { // Otherwise, let relativeStart be start. relativeEnd = @min(@as(i64, @intCast(end)), @as(i64, @intCast(this.size))); } } } var content_type: string = ""; var content_type_was_allocated = false; if (args_iter.nextEat()) |content_type_| { inner: { if (content_type_.isString()) { var zig_str = content_type_.getZigString(globalThis); var slicer = zig_str.toSlice(bun.default_allocator); defer slicer.deinit(); var slice = slicer.slice(); if (!strings.isAllASCII(slice)) { break :inner; } if (globalThis.bunVM().mimeType(slice)) |mime| { content_type = mime.value; break :inner; } content_type_was_allocated = slice.len > 0; var content_type_buf = allocator.alloc(u8, slice.len) catch unreachable; content_type = strings.copyLowercase(slice, content_type_buf); } } } const offset = this.offset +| @as(SizeType, @intCast(relativeStart)); const len = @as(SizeType, @intCast(@max(relativeEnd -| relativeStart, 0))); // This copies over the is_all_ascii flag // which is okay because this will only be a <= slice var blob = this.dupe(); blob.offset = offset; blob.size = len; // infer the content type if it was not specified if (content_type.len == 0 and this.content_type.len > 0 and !this.content_type_allocated) content_type = this.content_type; blob.content_type = content_type; blob.content_type_allocated = content_type_was_allocated; blob.content_type_was_set = this.content_type_was_set or content_type_was_allocated; var blob_ = allocator.create(Blob) catch unreachable; blob_.* = blob; blob_.allocator = allocator; return blob_.toJS(globalThis); } pub fn getMimeType(this: *const Blob) ?bun.HTTP.MimeType { if (this.store) |store| { return store.mime_type; } return null; } pub fn getType( this: *Blob, globalThis: *JSC.JSGlobalObject, ) callconv(.C) JSValue { if (this.content_type.len > 0) { if (this.content_type_allocated) { return ZigString.init(this.content_type).toValueGC(globalThis); } return ZigString.init(this.content_type).toValueGC(globalThis); } if (this.store) |store| { return ZigString.init(store.mime_type.value).toValueGC(globalThis); } return ZigString.Empty.toValue(globalThis); } // TODO: Move this to a separate `File` object or BunFile pub fn getName( this: *Blob, globalThis: *JSC.JSGlobalObject, ) callconv(.C) JSValue { if (this.getFileName()) |path| { var str = bun.String.create(path); return str.toJS(globalThis); } return JSValue.undefined; } pub fn getFileName( this: *const Blob, ) ?[]const u8 { if (this.store) |store| { if (store.data == .file) { if (store.data.file.pathlike == .path) { return store.data.file.pathlike.path.slice(); } // we shouldn't return Number here. } else if (store.data == .bytes) { if (store.data.bytes.stored_name.slice().len > 0) return store.data.bytes.stored_name.slice(); } } return null; } // TODO: Move this to a separate `File` object or BunFile pub fn getLastModified( this: *Blob, _: *JSC.JSGlobalObject, ) callconv(.C) JSValue { if (this.store) |store| { if (store.data == .file) { // last_modified can be already set during read. if (store.data.file.last_modified == init_timestamp) { resolveFileStat(store); } return JSValue.jsNumber(store.data.file.last_modified); } } if (this.is_jsdom_file) { return JSValue.jsNumber(this.last_modified); } return JSValue.jsNumber(init_timestamp); } pub fn getSizeForBindings(this: *Blob) u64 { if (this.size == Blob.max_size) { this.resolveSize(); } // If the file doesn't exist or is not seekable // signal that the size is unknown. if (this.store != null and this.store.?.data == .file and !(this.store.?.data.file.seekable orelse false)) { return std.math.maxInt(u64); } if (this.size == Blob.max_size) return std.math.maxInt(u64); return this.size; } export fn Bun__Blob__getSizeForBindings(this: *Blob) callconv(.C) u64 { return this.getSizeForBindings(); } comptime { if (!JSC.is_bindgen) { _ = Bun__Blob__getSizeForBindings; } } pub fn getSize(this: *Blob, _: *JSC.JSGlobalObject) callconv(.C) JSValue { if (this.size == Blob.max_size) { this.resolveSize(); if (this.size == Blob.max_size and this.store != null) { return JSC.jsNumber(std.math.inf(f64)); } else if (this.size == 0 and this.store != null) { if (this.store.?.data == .file and (this.store.?.data.file.seekable orelse true) == false and this.store.?.data.file.max_size == Blob.max_size) { return JSC.jsNumber(std.math.inf(f64)); } } } return JSValue.jsNumber(this.size); } pub fn resolveSize(this: *Blob) void { if (this.store) |store| { if (store.data == .bytes) { const offset = this.offset; const store_size = store.size(); if (store_size != Blob.max_size) { this.offset = @min(store_size, offset); this.size = store_size - offset; } return; } else if (store.data == .file) { if (store.data.file.seekable == null) { resolveFileStat(store); } if (store.data.file.seekable != null and store.data.file.max_size != Blob.max_size) { const store_size = store.data.file.max_size; const offset = this.offset; this.offset = @min(store_size, offset); this.size = store_size -| offset; return; } } this.size = 0; } else { this.size = 0; } } fn toJSTime(sec: isize, nsec: isize) JSTimeType { const millisec = @as(u64, @intCast(@divTrunc(nsec, std.time.ns_per_ms))); return @as(JSTimeType, @truncate(@as(u64, @intCast(sec * std.time.ms_per_s)) + millisec)); } /// resolve file stat like size, last_modified fn resolveFileStat(store: *Store) void { if (comptime Environment.isWindows) { bun.todo(@src(), {}); return; } if (store.data.file.pathlike == .path) { var buffer: [bun.MAX_PATH_BYTES]u8 = undefined; switch (bun.sys.stat(store.data.file.pathlike.path.sliceZ(&buffer))) { .result => |stat| { store.data.file.max_size = if (bun.isRegularFile(stat.mode) or stat.size > 0) @as(SizeType, @truncate(@as(u64, @intCast(@max(stat.size, 0))))) else Blob.max_size; store.data.file.mode = stat.mode; store.data.file.seekable = bun.isRegularFile(stat.mode); store.data.file.last_modified = toJSTime(stat.mtime().tv_sec, stat.mtime().tv_nsec); }, // the file may not exist yet. Thats's okay. else => {}, } } else if (store.data.file.pathlike == .fd) { switch (bun.sys.fstat(store.data.file.pathlike.fd)) { .result => |stat| { store.data.file.max_size = if (bun.isRegularFile(stat.mode) or stat.size > 0) @as(SizeType, @truncate(@as(u64, @intCast(@max(stat.size, 0))))) else Blob.max_size; store.data.file.mode = stat.mode; store.data.file.seekable = bun.isRegularFile(stat.mode); store.data.file.last_modified = toJSTime(stat.mtime().tv_sec, stat.mtime().tv_nsec); }, // the file may not exist yet. Thats's okay. else => {}, } } } pub fn constructor( globalThis: *JSC.JSGlobalObject, callframe: *JSC.CallFrame, ) callconv(.C) ?*Blob { var allocator = globalThis.allocator(); var blob: Blob = undefined; var arguments = callframe.arguments(2); var args = arguments.ptr[0..arguments.len]; switch (args.len) { 0 => { var empty: []u8 = &[_]u8{}; blob = Blob.init(empty, allocator, globalThis); }, else => { blob = get(globalThis, args[0], false, true) catch |err| { if (err == error.InvalidArguments) { globalThis.throwInvalidArguments("new Blob() expects an Array", .{}); return null; } globalThis.throw("out of memory", .{}); return null; }; if (args.len > 1) { const options = args[1]; if (options.isObject()) { // type, the ASCII-encoded string in lower case // representing the media type of the Blob. // Normative conditions for this member are provided // in the § 3.1 Constructors. if (options.get(globalThis, "type")) |content_type| { inner: { if (content_type.isString()) { var content_type_str = content_type.toSlice(globalThis, bun.default_allocator); defer content_type_str.deinit(); var slice = content_type_str.slice(); if (!strings.isAllASCII(slice)) { break :inner; } blob.content_type_was_set = true; if (globalThis.bunVM().mimeType(slice)) |mime| { blob.content_type = mime.value; break :inner; } var content_type_buf = allocator.alloc(u8, slice.len) catch unreachable; blob.content_type = strings.copyLowercase(slice, content_type_buf); blob.content_type_allocated = true; } } } } } if (blob.content_type.len == 0) { blob.content_type = ""; blob.content_type_was_set = false; } }, } var blob_ = allocator.create(Blob) catch unreachable; blob_.* = blob; blob_.allocator = allocator; return blob_; } pub fn finalize(this: *Blob) callconv(.C) void { this.deinit(); } pub fn initWithAllASCII(bytes: []u8, allocator: std.mem.Allocator, globalThis: *JSGlobalObject, is_all_ascii: bool) Blob { // avoid allocating a Blob.Store if the buffer is actually empty var store: ?*Blob.Store = null; if (bytes.len > 0) { store = Blob.Store.init(bytes, allocator) catch unreachable; store.?.is_all_ascii = is_all_ascii; } return Blob{ .size = @as(SizeType, @truncate(bytes.len)), .store = store, .allocator = null, .content_type = "", .globalThis = globalThis, .is_all_ascii = is_all_ascii, }; } pub fn init(bytes: []u8, allocator: std.mem.Allocator, globalThis: *JSGlobalObject) Blob { return Blob{ .size = @as(SizeType, @truncate(bytes.len)), .store = if (bytes.len > 0) Blob.Store.init(bytes, allocator) catch unreachable else null, .allocator = null, .content_type = "", .globalThis = globalThis, }; } pub fn create( bytes_: []const u8, allocator: std.mem.Allocator, globalThis: *JSGlobalObject, was_string: bool, ) Blob { var bytes = allocator.dupe(u8, bytes_) catch @panic("Out of memory"); return Blob{ .size = @as(SizeType, @truncate(bytes_.len)), .store = if (bytes.len > 0) Blob.Store.init(bytes, allocator) catch unreachable else null, .allocator = null, .content_type = if (was_string) MimeType.text.value else "", .globalThis = globalThis, }; } pub fn initWithStore(store: *Blob.Store, globalThis: *JSGlobalObject) Blob { return Blob{ .size = store.size(), .store = store, .allocator = null, .content_type = if (store.data == .file) store.data.file.mime_type.value else "", .globalThis = globalThis, }; } pub fn initEmpty(globalThis: *JSGlobalObject) Blob { return Blob{ .size = 0, .store = null, .allocator = null, .content_type = "", .globalThis = globalThis, }; } // Transferring doesn't change the reference count // It is a move inline fn transfer(this: *Blob) void { this.store = null; } pub fn detach(this: *Blob) void { if (this.store != null) this.store.?.deref(); this.store = null; } /// This does not duplicate /// This creates a new view /// and increment the reference count pub fn dupe(this: *const Blob) Blob { return this.dupeWithContentType(false); } pub fn dupeWithContentType(this: *const Blob, include_content_type: bool) Blob { if (this.store != null) this.store.?.ref(); var duped = this.*; if (duped.content_type_allocated and duped.allocator != null and !include_content_type) { // for now, we just want to avoid a use-after-free here if (JSC.VirtualMachine.get().mimeType(duped.content_type)) |mime| { duped.content_type = mime.value; } else { // TODO: fix this // this is a bug. // it means whenever duped.content_type = ""; } duped.content_type_allocated = false; duped.content_type_was_set = false; if (this.content_type_was_set) { duped.content_type_was_set = duped.content_type.len > 0; } } else if (duped.content_type_allocated and duped.allocator != null and include_content_type) { duped.content_type = bun.default_allocator.dupe(u8, this.content_type) catch @panic("Out of memory"); } duped.allocator = null; return duped; } pub fn deinit(this: *Blob) void { this.detach(); if (this.allocator) |alloc| { this.allocator = null; alloc.destroy(this); } } pub fn sharedView(this: *const Blob) []const u8 { if (this.size == 0 or this.store == null) return ""; var slice_ = this.store.?.sharedView(); if (slice_.len == 0) return ""; slice_ = slice_[this.offset..]; return slice_[0..@min(slice_.len, @as(usize, this.size))]; } pub const Lifetime = JSC.WebCore.Lifetime; pub fn setIsASCIIFlag(this: *Blob, is_all_ascii: bool) void { this.is_all_ascii = is_all_ascii; // if this Blob represents the entire binary data // which will be pretty common // we can update the store's is_all_ascii flag // and any other Blob that points to the same store // can skip checking the encoding if (this.size > 0 and this.offset == 0 and this.store.?.data == .bytes) { this.store.?.is_all_ascii = is_all_ascii; } } pub fn NewReadFileHandler(comptime Function: anytype) type { return struct { context: Blob, promise: JSPromise.Strong = .{}, globalThis: *JSGlobalObject, pub fn run(handler: *@This(), bytes_: Blob.Store.ReadFile.ResultType) void { var promise = handler.promise.swap(); var blob = handler.context; blob.allocator = null; var globalThis = handler.globalThis; bun.default_allocator.destroy(handler); switch (bytes_) { .result => |result| { const bytes = result.buf; if (blob.size > 0) blob.size = @min(@as(u32, @truncate(bytes.len)), blob.size); const value = Function(&blob, globalThis, bytes, .temporary); // invalid JSON needs to be rejected if (value.isAnyError()) { promise.reject(globalThis, value); } else { promise.resolve(globalThis, value); } }, .err => |err| { promise.reject(globalThis, err.toErrorInstance(globalThis)); }, } } }; } pub const WriteFilePromise = struct { promise: JSPromise.Strong = .{}, globalThis: *JSGlobalObject, pub fn run(handler: *@This(), count: Blob.Store.WriteFile.ResultType) void { var promise = handler.promise.swap(); var globalThis = handler.globalThis; bun.default_allocator.destroy(handler); const value = promise.asValue(globalThis); value.ensureStillAlive(); switch (count) { .err => |err| { promise.reject(globalThis, err.toErrorInstance(globalThis)); }, .result => |wrote| { promise.resolve(globalThis, JSC.JSValue.jsNumberFromUint64(wrote)); }, } } }; pub fn NewInternalReadFileHandler(comptime Context: type, comptime Function: anytype) type { return struct { pub fn run(handler: *anyopaque, bytes_: Store.ReadFile.ResultType) void { Function(bun.cast(Context, handler), bytes_); } }; } pub fn doReadFileInternal(this: *Blob, comptime Handler: type, ctx: Handler, comptime Function: anytype, global: *JSGlobalObject) void { var file_read = Store.ReadFile.createWithCtx( bun.default_allocator, this.store.?, ctx, NewInternalReadFileHandler(Handler, Function).run, this.offset, this.size, ) catch unreachable; var read_file_task = Store.ReadFile.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch unreachable; read_file_task.schedule(); } pub fn doReadFile(this: *Blob, comptime Function: anytype, global: *JSGlobalObject) JSValue { bloblog("doReadFile", .{}); const Handler = NewReadFileHandler(Function); var handler = bun.default_allocator.create(Handler) catch unreachable; handler.* = Handler{ .context = this.*, .globalThis = global, }; var file_read = Store.ReadFile.create( bun.default_allocator, this.store.?, this.offset, this.size, *Handler, handler, Handler.run, ) catch unreachable; var read_file_task = Store.ReadFile.ReadFileTask.createOnJSThread(bun.default_allocator, global, file_read) catch unreachable; // Create the Promise only after the store has been ref()'d. // The garbage collector runs on memory allocations // The JSPromise is the next GC'd memory allocation. // This shouldn't really fix anything, but it's a little safer. var promise = JSPromise.create(global); const promise_value = promise.asValue(global); promise_value.ensureStillAlive(); handler.promise.strong.set(global, promise_value); read_file_task.schedule(); bloblog("doReadFile: read_file_task scheduled", .{}); return promise_value; } pub fn needsToReadFile(this: *const Blob) bool { return this.store != null and this.store.?.data == .file; } pub fn toStringWithBytes(this: *Blob, global: *JSGlobalObject, buf: []const u8, comptime lifetime: Lifetime) JSValue { // null == unknown // false == can't be const could_be_all_ascii = this.is_all_ascii orelse this.store.?.is_all_ascii; if (could_be_all_ascii == null or !could_be_all_ascii.?) { // if toUTF16Alloc returns null, it means there are no non-ASCII characters // instead of erroring, invalid characters will become a U+FFFD replacement character if (strings.toUTF16Alloc(bun.default_allocator, buf, false) catch unreachable) |external| { if (lifetime != .temporary) this.setIsASCIIFlag(false); if (lifetime == .transfer) { this.detach(); } if (lifetime == .temporary) { bun.default_allocator.free(bun.constStrToU8(buf)); } return ZigString.toExternalU16(external.ptr, external.len, global); } if (lifetime != .temporary) this.setIsASCIIFlag(true); } if (buf.len == 0) { return ZigString.Empty.toValue(global); } switch (comptime lifetime) { // strings are immutable // we don't need to clone .clone => { this.store.?.ref(); return ZigString.init(buf).external(global, this.store.?, Store.external); }, .transfer => { var store = this.store.?; std.debug.assert(store.data == .bytes); this.transfer(); return ZigString.init(buf).external(global, store, Store.external); }, // strings are immutable // sharing isn't really a thing .share => { this.store.?.ref(); return ZigString.init(buf).external(global, this.store.?, Store.external); }, .temporary => { return ZigString.init(buf).toExternalValue(global); }, } } pub fn toString(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime) JSValue { if (this.needsToReadFile()) { return this.doReadFile(toStringWithBytes, global); } const view_: []u8 = bun.constStrToU8(this.sharedView()); if (view_.len == 0) return ZigString.Empty.toValue(global); return toStringWithBytes(this, global, view_, lifetime); } pub fn toJSON(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime) JSValue { if (this.needsToReadFile()) { return this.doReadFile(toJSONWithBytes, global); } var view_ = this.sharedView(); return toJSONWithBytes(this, global, view_, lifetime); } pub fn toJSONWithBytes(this: *Blob, global: *JSGlobalObject, buf: []const u8, comptime lifetime: Lifetime) JSValue { if (buf.len == 0) return global.createSyntaxErrorInstance("Unexpected end of JSON input", .{}); // null == unknown // false == can't be const could_be_all_ascii = this.is_all_ascii orelse this.store.?.is_all_ascii; defer if (comptime lifetime == .temporary) bun.default_allocator.free(bun.constStrToU8(buf)); if (could_be_all_ascii == null or !could_be_all_ascii.?) { var stack_fallback = std.heap.stackFallback(4096, bun.default_allocator); const allocator = stack_fallback.get(); // if toUTF16Alloc returns null, it means there are no non-ASCII characters if (strings.toUTF16Alloc(allocator, buf, false) catch null) |external| { if (comptime lifetime != .temporary) this.setIsASCIIFlag(false); const result = ZigString.init16(external).toJSONObject(global); allocator.free(external); return result; } if (comptime lifetime != .temporary) this.setIsASCIIFlag(true); } return ZigString.init(buf).toJSONObject(global); } pub fn toFormDataWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u8, comptime _: Lifetime) JSValue { var encoder = this.getFormDataEncoding() orelse return { return ZigString.init("Invalid encoding").toErrorInstance(global); }; defer encoder.deinit(); return bun.FormData.toJS(global, buf, encoder.encoding) catch |err| global.createErrorInstance("FormData encoding failed: {s}", .{@errorName(err)}); } pub fn toArrayBufferWithBytes(this: *Blob, global: *JSGlobalObject, buf: []u8, comptime lifetime: Lifetime) JSValue { switch (comptime lifetime) { .clone => { return JSC.ArrayBuffer.create(global, buf, .ArrayBuffer); }, .share => { this.store.?.ref(); return JSC.ArrayBuffer.fromBytes(buf, .ArrayBuffer).toJSWithContext( global, this.store.?, JSC.BlobArrayBuffer_deallocator, null, ); }, .transfer => { var store = this.store.?; this.transfer(); return JSC.ArrayBuffer.fromBytes(buf, .ArrayBuffer).toJSWithContext( global, store, JSC.BlobArrayBuffer_deallocator, null, ); }, .temporary => { return JSC.ArrayBuffer.fromBytes(buf, .ArrayBuffer).toJS( global, null, ); }, } } pub fn toArrayBuffer(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime) JSValue { bloblog("toArrayBuffer", .{}); if (this.needsToReadFile()) { return this.doReadFile(toArrayBufferWithBytes, global); } var view_ = this.sharedView(); if (view_.len == 0) return JSC.ArrayBuffer.create(global, "", .ArrayBuffer); return toArrayBufferWithBytes(this, global, bun.constStrToU8(view_), lifetime); } pub fn toFormData(this: *Blob, global: *JSGlobalObject, comptime lifetime: Lifetime) JSValue { if (this.needsToReadFile()) { return this.doReadFile(toFormDataWithBytes, global); } var view_ = this.sharedView(); if (view_.len == 0) return JSC.DOMFormData.create(global); return toFormDataWithBytes(this, global, bun.constStrToU8(view_), lifetime); } pub inline fn get( global: *JSGlobalObject, arg: JSValue, comptime move: bool, comptime require_array: bool, ) anyerror!Blob { return fromJSMovable(global, arg, move, require_array); } pub inline fn fromJSMove(global: *JSGlobalObject, arg: JSValue) anyerror!Blob { return fromJSWithoutDeferGC(global, arg, true, false); } pub inline fn fromJSClone(global: *JSGlobalObject, arg: JSValue) anyerror!Blob { return fromJSWithoutDeferGC(global, arg, false, true); } pub inline fn fromJSCloneOptionalArray(global: *JSGlobalObject, arg: JSValue) anyerror!Blob { return fromJSWithoutDeferGC(global, arg, false, false); } fn fromJSMovable( global: *JSGlobalObject, arg: JSValue, comptime move: bool, comptime require_array: bool, ) anyerror!Blob { const FromJSFunction = if (comptime move and !require_array) fromJSMove else if (!require_array) fromJSCloneOptionalArray else fromJSClone; return FromJSFunction(global, arg); } fn fromJSWithoutDeferGC( global: *JSGlobalObject, arg: JSValue, comptime move: bool, comptime require_array: bool, ) anyerror!Blob { var current = arg; if (current.isUndefinedOrNull()) { return Blob{ .globalThis = global }; } var top_value = current; var might_only_be_one_thing = false; arg.ensureStillAlive(); defer arg.ensureStillAlive(); switch (current.jsTypeLoose()) { .Array, .DerivedArray => { var top_iter = JSC.JSArrayIterator.init(current, global); might_only_be_one_thing = top_iter.len == 1; if (top_iter.len == 0) { return Blob{ .globalThis = global }; } if (might_only_be_one_thing) { top_value = top_iter.next().?; } }, else => { might_only_be_one_thing = true; if (require_array) { return error.InvalidArguments; } }, } if (might_only_be_one_thing or !move) { // Fast path: one item, we don't need to join switch (top_value.jsTypeLoose()) { .Cell, .NumberObject, JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject, => { var sliced = top_value.toSlice(global, bun.default_allocator); const is_all_ascii = !sliced.isAllocated(); if (!sliced.isAllocated() and sliced.len > 0) { sliced.ptr = @as([*]const u8, @ptrCast((try bun.default_allocator.dupe(u8, sliced.slice())).ptr)); sliced.allocator = NullableAllocator.init(bun.default_allocator); } return Blob.initWithAllASCII(bun.constStrToU8(sliced.slice()), bun.default_allocator, global, is_all_ascii); }, JSC.JSValue.JSType.ArrayBuffer, JSC.JSValue.JSType.Int8Array, JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.Uint8ClampedArray, JSC.JSValue.JSType.Int16Array, JSC.JSValue.JSType.Uint16Array, JSC.JSValue.JSType.Int32Array, JSC.JSValue.JSType.Uint32Array, JSC.JSValue.JSType.Float32Array, JSC.JSValue.JSType.Float64Array, JSC.JSValue.JSType.BigInt64Array, JSC.JSValue.JSType.BigUint64Array, JSC.JSValue.JSType.DataView, => { var buf = try bun.default_allocator.dupe(u8, top_value.asArrayBuffer(global).?.byteSlice()); return Blob.init(buf, bun.default_allocator, global); }, .DOMWrapper => { if (top_value.as(Blob)) |blob| { if (comptime move) { var _blob = blob.*; _blob.allocator = null; blob.transfer(); return _blob; } else { return blob.dupe(); } } else if (top_value.as(JSC.API.BuildArtifact)) |build| { if (comptime move) { // I don't think this case should happen? var blob = build.blob; blob.transfer(); return blob; } else { return build.blob.dupe(); } } else if (current.toSliceClone(global)) |sliced| { if (sliced.allocator.get()) |allocator| { return Blob.initWithAllASCII(bun.constStrToU8(sliced.slice()), allocator, global, false); } } }, else => {}, } } var stack_allocator = std.heap.stackFallback(1024, bun.default_allocator); var stack_mem_all = stack_allocator.get(); var stack: std.ArrayList(JSValue) = std.ArrayList(JSValue).init(stack_mem_all); var joiner = StringJoiner{ .use_pool = false, .node_allocator = stack_mem_all }; var could_have_non_ascii = false; defer if (stack_allocator.fixed_buffer_allocator.end_index >= 1024) stack.deinit(); while (true) { switch (current.jsTypeLoose()) { .NumberObject, JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject, => { var sliced = current.toSlice(global, bun.default_allocator); const allocator = sliced.allocator.get(); could_have_non_ascii = could_have_non_ascii or allocator != null; joiner.append( sliced.slice(), 0, allocator, ); }, .Array, .DerivedArray => { var iter = JSC.JSArrayIterator.init(current, global); try stack.ensureUnusedCapacity(iter.len); var any_arrays = false; while (iter.next()) |item| { if (item.isUndefinedOrNull()) continue; // When it's a string or ArrayBuffer inside an array, we can avoid the extra push/pop // we only really want this for nested arrays // However, we must preserve the order // That means if there are any arrays // we have to restart the loop if (!any_arrays) { switch (item.jsTypeLoose()) { .NumberObject, .Cell, JSC.JSValue.JSType.String, JSC.JSValue.JSType.StringObject, JSC.JSValue.JSType.DerivedStringObject, => { var sliced = item.toSlice(global, bun.default_allocator); const allocator = sliced.allocator.get(); could_have_non_ascii = could_have_non_ascii or allocator != null; joiner.append( sliced.slice(), 0, allocator, ); continue; }, JSC.JSValue.JSType.ArrayBuffer, JSC.JSValue.JSType.Int8Array, JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.Uint8ClampedArray, JSC.JSValue.JSType.Int16Array, JSC.JSValue.JSType.Uint16Array, JSC.JSValue.JSType.Int32Array, JSC.JSValue.JSType.Uint32Array, JSC.JSValue.JSType.Float32Array, JSC.JSValue.JSType.Float64Array, JSC.JSValue.JSType.BigInt64Array, JSC.JSValue.JSType.BigUint64Array, JSC.JSValue.JSType.DataView, => { could_have_non_ascii = true; var buf = item.asArrayBuffer(global).?; joiner.append(buf.byteSlice(), 0, null); continue; }, .Array, .DerivedArray => { any_arrays = true; could_have_non_ascii = true; break; }, .DOMWrapper => { if (item.as(Blob)) |blob| { could_have_non_ascii = could_have_non_ascii or !(blob.is_all_ascii orelse false); joiner.append(blob.sharedView(), 0, null); continue; } else if (current.toSliceClone(global)) |sliced| { const allocator = sliced.allocator.get(); could_have_non_ascii = could_have_non_ascii or allocator != null; joiner.append( sliced.slice(), 0, allocator, ); } }, else => {}, } } stack.appendAssumeCapacity(item); } }, .DOMWrapper => { if (current.as(Blob)) |blob| { could_have_non_ascii = could_have_non_ascii or !(blob.is_all_ascii orelse false); joiner.append(blob.sharedView(), 0, null); } else if (current.toSliceClone(global)) |sliced| { const allocator = sliced.allocator.get(); could_have_non_ascii = could_have_non_ascii or allocator != null; joiner.append( sliced.slice(), 0, allocator, ); } }, JSC.JSValue.JSType.ArrayBuffer, JSC.JSValue.JSType.Int8Array, JSC.JSValue.JSType.Uint8Array, JSC.JSValue.JSType.Uint8ClampedArray, JSC.JSValue.JSType.Int16Array, JSC.JSValue.JSType.Uint16Array, JSC.JSValue.JSType.Int32Array, JSC.JSValue.JSType.Uint32Array, JSC.JSValue.JSType.Float32Array, JSC.JSValue.JSType.Float64Array, JSC.JSValue.JSType.BigInt64Array, JSC.JSValue.JSType.BigUint64Array, JSC.JSValue.JSType.DataView, => { var buf = current.asArrayBuffer(global).?; joiner.append(buf.slice(), 0, null); could_have_non_ascii = true; }, else => { var sliced = current.toSlice(global, bun.default_allocator); const allocator = sliced.allocator.get(); could_have_non_ascii = could_have_non_ascii or allocator != null; joiner.append( sliced.slice(), 0, allocator, ); }, } current = stack.popOrNull() orelse break; } var joined = try joiner.done(bun.default_allocator); if (!could_have_non_ascii) { return Blob.initWithAllASCII(joined, bun.default_allocator, global, true); } return Blob.init(joined, bun.default_allocator, global); } }; pub const AnyBlob = union(enum) { Blob: Blob, // InlineBlob: InlineBlob, InternalBlob: InternalBlob, WTFStringImpl: bun.WTF.StringImpl, pub fn getFileName(this: *const AnyBlob) ?[]const u8 { return switch (this.*) { .Blob => this.Blob.getFileName(), .WTFStringImpl => null, .InternalBlob => null, }; } pub inline fn fastSize(this: *const AnyBlob) Blob.SizeType { return switch (this.*) { .Blob => this.Blob.size, .WTFStringImpl => @as(Blob.SizeType, @truncate(this.WTFStringImpl.byteLength())), else => @as(Blob.SizeType, @truncate(this.slice().len)), }; } pub fn hasContentTypeFromUser(this: AnyBlob) bool { return switch (this) { .Blob => this.Blob.hasContentTypeFromUser(), .WTFStringImpl => false, .InternalBlob => false, }; } pub fn toJSON(this: *AnyBlob, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) JSValue { switch (this.*) { .Blob => return this.Blob.toJSON(global, lifetime), // .InlineBlob => { // if (this.InlineBlob.len == 0) { // return JSValue.jsNull(); // } // var str = this.InlineBlob.toStringOwned(global); // return str.parseJSON(global); // }, .InternalBlob => { if (this.InternalBlob.bytes.items.len == 0) { return JSValue.jsNull(); } const str = this.InternalBlob.toJSON(global); // the GC will collect the string this.* = .{ .Blob = .{}, }; return str; }, .WTFStringImpl => { var str = bun.String.init(this.WTFStringImpl); defer str.deref(); this.* = .{ .Blob = .{}, }; if (str.length() == 0) { return JSValue.jsNull(); } return str.toJSForParseJSON(global); }, } } pub fn toString(this: *AnyBlob, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) JSValue { switch (this.*) { .Blob => return this.Blob.toString(global, lifetime), // .InlineBlob => { // if (this.InlineBlob.len == 0) { // return ZigString.Empty.toValue(global); // } // const owned = this.InlineBlob.toStringOwned(global); // this.* = .{ .InlineBlob = .{ .len = 0 } }; // return owned; // }, .InternalBlob => { if (this.InternalBlob.bytes.items.len == 0) { return ZigString.Empty.toValue(global); } const owned = this.InternalBlob.toStringOwned(global); this.* = .{ .Blob = .{} }; return owned; }, .WTFStringImpl => { var str = bun.String.init(this.WTFStringImpl); defer str.deref(); this.* = .{ .Blob = .{} }; return str.toJS(global); }, } } pub fn toArrayBuffer(this: *AnyBlob, global: *JSGlobalObject, comptime lifetime: JSC.WebCore.Lifetime) JSValue { switch (this.*) { .Blob => return this.Blob.toArrayBuffer(global, lifetime), // .InlineBlob => { // if (this.InlineBlob.len == 0) { // return JSC.ArrayBuffer.create(global, "", .ArrayBuffer); // } // var bytes = this.InlineBlob.sliceConst(); // this.InlineBlob.len = 0; // const value = JSC.ArrayBuffer.create( // global, // bytes, // .ArrayBuffer, // ); // return value; // }, .InternalBlob => { if (this.InternalBlob.bytes.items.len == 0) { return JSC.ArrayBuffer.create(global, "", .ArrayBuffer); } var bytes = this.InternalBlob.toOwnedSlice(); this.* = .{ .Blob = .{} }; const value = JSC.ArrayBuffer.fromBytes( bytes, .ArrayBuffer, ); return value.toJS(global, null); }, .WTFStringImpl => { const str = bun.String.init(this.WTFStringImpl); this.* = .{ .Blob = .{} }; defer str.deref(); const out_bytes = str.toUTF8WithoutRef(bun.default_allocator); if (out_bytes.isAllocated()) { const value = JSC.ArrayBuffer.fromBytes( @constCast(out_bytes.slice()), .ArrayBuffer, ); return value.toJS(global, null); } return JSC.ArrayBuffer.create(global, out_bytes.slice(), .ArrayBuffer); }, } } pub inline fn size(this: *const AnyBlob) Blob.SizeType { return switch (this.*) { .Blob => this.Blob.size, .WTFStringImpl => @as(Blob.SizeType, @truncate(this.WTFStringImpl.utf8ByteLength())), else => @as(Blob.SizeType, @truncate(this.slice().len)), }; } pub fn from(this: *AnyBlob, list: std.ArrayList(u8)) void { this.* = .{ .InternalBlob = InternalBlob{ .bytes = list, }, }; } pub fn isDetached(this: *const AnyBlob) bool { return switch (this.*) { .Blob => |blob| blob.isDetached(), .InternalBlob => this.InternalBlob.bytes.items.len == 0, .WTFStringImpl => this.WTFStringImpl.length() == 0, }; } pub fn store(this: *const @This()) ?*Blob.Store { if (this.* == .Blob) { return this.Blob.store; } return null; } pub fn contentType(self: *const @This()) []const u8 { return switch (self.*) { .Blob => self.Blob.content_type, .WTFStringImpl => MimeType.text.value, // .InlineBlob => self.InlineBlob.contentType(), .InternalBlob => self.InternalBlob.contentType(), }; } pub fn wasString(self: *const @This()) bool { return switch (self.*) { .Blob => self.Blob.is_all_ascii orelse false, .WTFStringImpl => true, // .InlineBlob => self.InlineBlob.was_string, .InternalBlob => self.InternalBlob.was_string, }; } pub inline fn slice(self: *const @This()) []const u8 { return switch (self.*) { .Blob => self.Blob.sharedView(), .WTFStringImpl => self.WTFStringImpl.utf8Slice(), // .InlineBlob => self.InlineBlob.sliceConst(), .InternalBlob => self.InternalBlob.sliceConst(), }; } pub fn needsToReadFile(self: *const @This()) bool { return switch (self.*) { .Blob => self.Blob.needsToReadFile(), .WTFStringImpl, .InternalBlob => false, }; } pub fn detach(self: *@This()) void { return switch (self.*) { .Blob => { self.Blob.detach(); self.* = .{ .Blob = .{}, }; }, // .InlineBlob => { // self.InlineBlob.len = 0; // }, .InternalBlob => { self.InternalBlob.bytes.clearAndFree(); self.* = .{ .Blob = .{}, }; }, .WTFStringImpl => { self.WTFStringImpl.deref(); self.* = .{ .Blob = .{}, }; }, }; } }; /// A single-use Blob pub const InternalBlob = struct { bytes: std.ArrayList(u8), was_string: bool = false, pub fn toStringOwned(this: *@This(), globalThis: *JSC.JSGlobalObject) JSValue { if (strings.toUTF16Alloc(globalThis.allocator(), this.bytes.items, false) catch &[_]u16{}) |out| { const return_value = ZigString.toExternalU16(out.ptr, out.len, globalThis); return_value.ensureStillAlive(); this.deinit(); return return_value; } else { var str = ZigString.init(this.toOwnedSlice()); str.mark(); return str.toExternalValue(globalThis); } } pub fn toJSON(this: *@This(), globalThis: *JSC.JSGlobalObject) JSValue { const str_bytes = ZigString.init(this.bytes.items).withEncoding(); const json = str_bytes.toJSONObject(globalThis); this.deinit(); return json; } pub inline fn sliceConst(this: *const @This()) []const u8 { return this.bytes.items; } pub fn deinit(this: *@This()) void { this.bytes.clearAndFree(); } pub inline fn slice(this: @This()) []u8 { return this.bytes.items; } pub fn toOwnedSlice(this: *@This()) []u8 { var bytes = this.bytes.items; this.bytes.items = &.{}; this.bytes.capacity = 0; return bytes; } pub fn clearAndFree(this: *@This()) void { this.bytes.clearAndFree(); } pub fn contentType(self: *const @This()) []const u8 { if (self.was_string) { return MimeType.text.value; } return MimeType.other.value; } }; /// A blob which stores all the data in the same space as a real Blob /// This is an optimization for small Response and Request bodies /// It means that we can avoid an additional heap allocation for a small response pub const InlineBlob = extern struct { const real_blob_size = @sizeOf(Blob); pub const IntSize = u8; pub const available_bytes = real_blob_size - @sizeOf(IntSize) - 1 - 1; bytes: [available_bytes]u8 align(1) = undefined, len: IntSize align(1) = 0, was_string: bool align(1) = false, pub fn concat(first: []const u8, second: []const u8) InlineBlob { const total = first.len + second.len; std.debug.assert(total <= available_bytes); var inline_blob: JSC.WebCore.InlineBlob = .{}; var bytes_slice = inline_blob.bytes[0..total]; if (first.len > 0) @memcpy(bytes_slice[0..first.len], first); if (second.len > 0) @memcpy(bytes_slice[first.len..][0..second.len], second); inline_blob.len = @as(@TypeOf(inline_blob.len), @truncate(total)); return inline_blob; } fn internalInit(data: []const u8, was_string: bool) InlineBlob { std.debug.assert(data.len <= available_bytes); var blob = InlineBlob{ .len = @as(IntSize, @intCast(data.len)), .was_string = was_string, }; if (data.len > 0) @memcpy(blob.bytes[0..data.len], data); return blob; } pub fn init(data: []const u8) InlineBlob { return internalInit(data, false); } pub fn initString(data: []const u8) InlineBlob { return internalInit(data, true); } pub fn toStringOwned(this: *@This(), globalThis: *JSC.JSGlobalObject) JSValue { if (this.len == 0) return ZigString.Empty.toValue(globalThis); var str = ZigString.init(this.sliceConst()); if (!strings.isAllASCII(this.sliceConst())) { str.markUTF8(); } const out = str.toValueGC(globalThis); out.ensureStillAlive(); this.len = 0; return out; } pub fn contentType(self: *const @This()) []const u8 { if (self.was_string) { return MimeType.text.value; } return MimeType.other.value; } pub fn deinit(_: *@This()) void {} pub inline fn slice(this: *@This()) []u8 { return this.bytes[0..this.len]; } pub inline fn sliceConst(this: *const @This()) []const u8 { return this.bytes[0..this.len]; } pub fn toOwnedSlice(this: *@This()) []u8 { return this.slice(); } pub fn clearAndFree(_: *@This()) void {} };
https://raw.githubusercontent.com/ziord/bun/7fb06c0488da302b56507191841d25ef3c62c0c8/src/bun.js/webcore/blob.zig
const std = @import("std"); const g = @import("spirv/grammar.zig"); 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 != 2) { usageAndExit(std.io.getStdErr(), args[0], 1); } const spec_path = args[1]; const spec = try std.fs.cwd().readFileAlloc(allocator, spec_path, std.math.maxInt(usize)); // Required for json parsing. @setEvalBranchQuota(10000); var tokens = std.json.TokenStream.init(spec); var registry = try std.json.parse(g.Registry, &tokens, .{ .allocator = allocator }); var bw = std.io.bufferedWriter(std.io.getStdOut().writer()); try render(bw.writer(), registry); try bw.flush(); } fn render(writer: anytype, registry: g.Registry) !void { try writer.writeAll( \\//! This file is auto-generated by tools/gen_spirv_spec.zig. \\ \\const Version = @import("std").builtin.Version; \\ ); switch (registry) { .core => |core_reg| { try writer.print( \\pub const version = Version{{ .major = {}, .minor = {}, .patch = {} }}; \\pub const magic_number: u32 = {s}; \\ , .{ core_reg.major_version, core_reg.minor_version, core_reg.revision, core_reg.magic_number }, ); try renderOpcodes(writer, core_reg.instructions); try renderOperandKinds(writer, core_reg.operand_kinds); }, .extension => |ext_reg| { try writer.print( \\pub const version = Version{{ .major = {}, .minor = 0, .patch = {} }}; \\ , .{ ext_reg.version, ext_reg.revision }, ); try renderOpcodes(writer, ext_reg.instructions); try renderOperandKinds(writer, ext_reg.operand_kinds); }, } } fn renderOpcodes(writer: anytype, instructions: []const g.Instruction) !void { try writer.writeAll("pub const Opcode = extern enum(u16) {\n"); for (instructions) |instr| { try writer.print(" {} = {},\n", .{ std.zig.fmtId(instr.opname), instr.opcode }); } try writer.writeAll(" _,\n};\n"); } fn renderOperandKinds(writer: anytype, kinds: []const g.OperandKind) !void { for (kinds) |kind| { switch (kind.category) { .ValueEnum => try renderValueEnum(writer, kind), .BitEnum => try renderBitEnum(writer, kind), else => {}, } } } fn renderValueEnum(writer: anytype, enumeration: g.OperandKind) !void { try writer.print("pub const {s} = extern enum(u32) {{\n", .{enumeration.kind}); const enumerants = enumeration.enumerants orelse return error.InvalidRegistry; for (enumerants) |enumerant| { if (enumerant.value != .int) return error.InvalidRegistry; try writer.print(" {} = {},\n", .{ std.zig.fmtId(enumerant.enumerant), enumerant.value.int }); } try writer.writeAll(" _,\n};\n"); } fn renderBitEnum(writer: anytype, enumeration: g.OperandKind) !void { try writer.print("pub const {s} = packed struct {{\n", .{enumeration.kind}); var flags_by_bitpos = [_]?[]const u8{null} ** 32; const enumerants = enumeration.enumerants orelse return error.InvalidRegistry; for (enumerants) |enumerant| { if (enumerant.value != .bitflag) return error.InvalidRegistry; const value = try parseHexInt(enumerant.value.bitflag); if (@popCount(u32, value) != 1) { continue; // Skip combinations and 'none' items } var bitpos = std.math.log2_int(u32, value); if (flags_by_bitpos[bitpos]) |*existing| { // Keep the shortest if (enumerant.enumerant.len < existing.len) existing.* = enumerant.enumerant; } else { flags_by_bitpos[bitpos] = enumerant.enumerant; } } for (flags_by_bitpos) |maybe_flag_name, bitpos| { try writer.writeAll(" "); if (maybe_flag_name) |flag_name| { try writer.writeAll(flag_name); } else { try writer.print("_reserved_bit_{}", .{bitpos}); } try writer.writeAll(": bool "); if (bitpos == 0) { // Force alignment to integer boundaries try writer.writeAll("align(@alignOf(u32)) "); } try writer.writeAll("= false,\n"); } try writer.writeAll("};\n"); } fn parseHexInt(text: []const u8) !u31 { const prefix = "0x"; if (!std.mem.startsWith(u8, text, prefix)) return error.InvalidHexInt; return try std.fmt.parseInt(u31, text[prefix.len..], 16); } fn usageAndExit(file: std.fs.File, arg0: []const u8, code: u8) noreturn { file.writer().print( \\Usage: {s} <spirv json spec> \\ \\Generates Zig bindings for a SPIR-V specification .json (either core or \\extinst versions). The result, printed to stdout, should be used to update \\files in src/codegen/spirv. \\ \\The relevant specifications can be obtained from the SPIR-V registry: \\https://github.com/KhronosGroup/SPIRV-Headers/blob/master/include/spirv/unified1/ \\ , .{arg0}) catch std.process.exit(1); std.process.exit(code); }
https://raw.githubusercontent.com/collinalexbell/all-the-compilers/7f834984f71054806bfec8604e02e86b99c0f831/zig/tools/gen_spirv_spec.zig
const std = @import("std"); const debug = std.debug; pub fn squareOfSum(number: usize) usize { var sum: usize = 0; for (0..(number + 1)) |n| { sum += n; } return sum * sum; } pub fn sumOfSquares(number: usize) usize { var sum: usize = 0; for (0..(number + 1)) |n| { sum += n * n; } return sum; } pub fn differenceOfSquares(number: usize) usize { return squareOfSum(number) - sumOfSquares(number); }
https://raw.githubusercontent.com/charlieroth/exercism/87e3f2922f55fab57d3b1005ec1567f9d919fb27/zig/difference-of-squares/difference_of_squares.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const opts = .{ .target = target, .optimize = optimize }; const neat_module = b.dependency("zigNEAT", opts).module("zigNEAT"); const exe = b.addExecutable(.{ .name = "CartPole-example", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, .link_libc = true, // for C allocator }); exe.addModule("zigNEAT", neat_module); // build the executable 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/cryptodeal/zig-NEAT/cb360c15dc6106391d654861719dac64ef8407de/examples/cartpole/build.zig
const std = @import("std"); const georgios = @import("georgios"); const utils = @import("utils"); const kernel = @import("kernel.zig"); const print = @import("print.zig"); const MinBuddyAllocator = @import("buddy_allocator.zig").MinBuddyAllocator; const console_writer = kernel.console_writer; const platform = @import("platform.zig"); pub const AllocError = georgios.memory.AllocError; pub const FreeError = georgios.memory.FreeError; pub const MemoryError = georgios.memory.MemoryError; pub const Range = struct { start: usize = 0, size: usize = 0, pub fn from_bytes(bytes: []const u8) Range { return .{.start = @ptrToInt(bytes.ptr), .size = bytes.len}; } pub fn end(self: *const Range) usize { return self.start + self.size; } pub fn to_ptr(self: *const Range, comptime PtrType: type) PtrType { return @intToPtr(PtrType, self.start); } pub fn to_slice(self: *const Range, comptime Type: type) []Type { return self.to_ptr([*]Type)[0..self.size / @sizeOf(Type)]; } }; /// Used by the platform to provide what real memory can be used for the real /// memory allocator. pub const RealMemoryMap = struct { const FrameGroup = struct { start: usize, frame_count: usize, }; frame_groups: [64]FrameGroup = undefined, frame_group_count: usize = 0, total_frame_count: usize = 0, fn invalid(self: *RealMemoryMap) bool { return self.frame_group_count == 0 or self.total_frame_count == 0; } /// Directly add a frame group. fn add_frame_group_impl(self: *RealMemoryMap, start: usize, frame_count: usize) void { if ((self.frame_group_count + 1) >= self.frame_groups.len) { @panic("Too many frame groups!"); } self.frame_groups[self.frame_group_count] = FrameGroup{ .start = start, .frame_count = frame_count, }; self.frame_group_count += 1; self.total_frame_count += frame_count; } /// Given a memory range, add a frame group if there are frames that can /// fit in it. pub fn add_frame_group(self: *RealMemoryMap, start: usize, end: usize) void { const aligned_start = utils.align_up(start, platform.frame_size); const aligned_end = utils.align_down(end, platform.frame_size); if (aligned_start < aligned_end) { self.add_frame_group_impl(aligned_start, (aligned_end - aligned_start) / platform.frame_size); } } }; var alloc_debug = false; pub const Allocator = struct { alloc_impl: fn(*Allocator, usize, usize) AllocError![]u8, free_impl: fn(*Allocator, []const u8, usize) FreeError!void, pub fn alloc(self: *Allocator, comptime Type: type) AllocError!*Type { if (alloc_debug) print.string( "Allocator.alloc: " ++ @typeName(Type) ++ "\n"); const rv = @ptrCast(*Type, @alignCast( @alignOf(Type), (try self.alloc_impl(self, @sizeOf(Type), @alignOf(Type))).ptr)); if (alloc_debug) print.format( "Allocator.alloc: " ++ @typeName(Type) ++ ": {:a}\n", .{@ptrToInt(rv)}); return rv; } pub fn free(self: *Allocator, value: anytype) FreeError!void { const traits = @typeInfo(@TypeOf(value)).Pointer; const bytes = utils.to_bytes(value); if (alloc_debug) print.format("Allocator.free: " ++ @typeName(@TypeOf(value)) ++ ": {:a}\n", .{@ptrToInt(bytes.ptr)}); try self.free_impl(self, bytes, traits.alignment); } pub fn alloc_array( self: *Allocator, comptime Type: type, count: usize) AllocError![]Type { if (alloc_debug) print.format( "Allocator.alloc_array: [{}]" ++ @typeName(Type) ++ "\n", .{count}); if (count == 0) { return AllocError.ZeroSizedAlloc; } const rv = @ptrCast([*]Type, @alignCast(@alignOf(Type), (try self.alloc_impl(self, @sizeOf(Type) * count, @alignOf(Type))).ptr))[0..count]; if (alloc_debug) print.format("Allocator.alloc_array: [{}]" ++ @typeName(Type) ++ ": {:a}\n", .{count, @ptrToInt(rv.ptr)}); return rv; } pub fn free_array(self: *Allocator, array: anytype) FreeError!void { const traits = @typeInfo(@TypeOf(array)).Pointer; if (alloc_debug) print.format( "Allocator.free_array: [{}]" ++ @typeName(traits.child) ++ ": {:a}\n", .{array.len, @ptrToInt(array.ptr)}); try self.free_impl(self, utils.to_const_bytes(array), traits.alignment); } pub fn alloc_range(self: *Allocator, size: usize) AllocError!Range { if (alloc_debug) print.format("Allocator.alloc_range: {}\n", .{size}); if (size == 0) { return AllocError.ZeroSizedAlloc; } const rv = Range{ .start = @ptrToInt((try self.alloc_impl(self, size, 1)).ptr), .size = size}; if (alloc_debug) print.format("Allocator.alloc_range: {}: {:a}\n", .{size, rv.start}); return rv; } pub fn free_range(self: *Allocator, range: Range) FreeError!void { if (alloc_debug) print.format( "Allocator.free_range: {}: {:a}\n", .{range.size, range.start}); try self.free_impl(self, range.to_slice(u8), 1); } fn std_alloc(self: *Allocator, n: usize, ptr_align: u29, len_align: u29, ra: usize) ![]u8 { _ = len_align; _ = ra; return self.alloc_impl(self, n, ptr_align) catch return std.mem.Allocator.Error.OutOfMemory; } fn std_resize(self: *Allocator, buf: []u8, buf_align: u29, new_len: usize, len_align: u29, ret_addr: usize) ?usize { _ = self; _ = buf_align; _ = len_align; _ = ret_addr; // TODO if (new_len <= buf.len) { return new_len; } else { return null; } } fn std_free(self: *Allocator, buf: []u8, buf_align: u29, ret_addr: usize) void { _ = ret_addr; self.free_impl(self, buf, buf_align) catch return; } pub fn std_allocator(self: *Allocator) std.mem.Allocator { return std.mem.Allocator.init(self, std_alloc, std_resize, std_free); } }; pub const UnitTestAllocator = struct { const Self = @This(); allocator: Allocator = undefined, impl: utils.TestAlloc = undefined, alloc: std.mem.Allocator = undefined, pub fn init(self: *Self) void { self.impl = .{}; self.alloc = self.impl.alloc(); self.allocator.alloc_impl = Self.alloc; self.allocator.free_impl = Self.free; } pub fn done_no_checks(self: *Self) void { self.impl.deinit(.NoPanic); } pub fn done(self: *Self) void { self.impl.deinit(.Panic); } pub fn done_check_if(self: *Self, condition: *bool) void { if (condition.*) { self.done(); } else { self.done_no_checks(); } } pub fn alloc(allocator: *Allocator, size: usize, align_to: usize) AllocError![]u8 { const self = @fieldParentPtr(Self, "allocator", allocator); const align_u29 = @truncate(u29, align_to); const rv = self.alloc.allocBytes(align_u29, size, align_u29, @returnAddress()) catch return AllocError.OutOfMemory; // std.debug.print("alloc {x}: {}\n", .{@ptrToInt(rv.ptr), rv.len}); return rv; } pub fn free(allocator: *Allocator, value: []const u8, aligned_to: usize) FreeError!void { // std.debug.print("free {x}: {}\n", .{@ptrToInt(value.ptr), value.len}); const self = @fieldParentPtr(Self, "allocator", allocator); _ = self.alloc.rawFree( @intToPtr([*]u8, @ptrToInt(value.ptr))[0..value.len], @truncate(u29, aligned_to), @returnAddress()); } }; /// Used by the kernel to manage system memory pub const Manager = struct { const alloc_size = utils.Mi(1); const AllocImplType = MinBuddyAllocator(alloc_size); impl: platform.MemoryMgrImpl = .{}, total_frame_count: usize = 0, free_frame_count: usize = 0, alloc_range: Range = undefined, alloc_impl_range: Range = undefined, alloc_impl: *AllocImplType = undefined, alloc: *Allocator = undefined, big_alloc: *Allocator = undefined, /// To be called by the platform after it can give "map". pub fn init(self: *Manager, map: *RealMemoryMap) !void { print.debug_format( \\ - Initializing Memory System \\ - Start of kernel: \\ - Real: {:a} \\ - Virtual: {:a} \\ - End of kernel: \\ - Real: {:a} \\ - Virtual: {:a} \\ - Size of kernel is {} B ({} KiB) \\ - Frame Size: {} B ({} KiB) \\ , .{ platform.kernel_real_start(), platform.kernel_virtual_start(), platform.kernel_real_end(), platform.kernel_virtual_end(), platform.kernel_size(), platform.kernel_size() >> 10, platform.frame_size, platform.frame_size >> 10}); // Process RealMemoryMap if (map.invalid()) { @panic("RealMemoryMap is invalid!"); } print.debug_string(" - Frame Groups:\n"); for (map.frame_groups[0..map.frame_group_count]) |*i| { print.debug_format(" - {} Frames starting at {:a}\n", .{i.frame_count, i.start}); } // Initialize Platform Implementation // After this we should be able to manage all the memory on the system. self.impl.init(self, map); // List Memory const total_memory: usize = map.total_frame_count * platform.frame_size; const indent = if (print.debug_print) " - " else ""; print.format( "{}Total Available Memory: {} B ({} KiB/{} MiB/{} GiB)\n", .{ indent, total_memory, total_memory >> 10, total_memory >> 20, total_memory >> 30}); self.alloc_impl = try self.big_alloc.alloc(AllocImplType); try self.alloc_impl.init(@alignCast(AllocImplType.area_align, try self.big_alloc.alloc([alloc_size]u8))); self.alloc = &self.alloc_impl.allocator; kernel.alloc = self.alloc; kernel.big_alloc = self.big_alloc; } pub fn print_status(self: *Manager) void { const free_size = std.fmt.fmtIntSizeBin(self.free_frame_count * platform.frame_size); const total_size = std.fmt.fmtIntSizeBin(self.total_frame_count * platform.frame_size); try console_writer.print("{}/{} free frames totaling {}/{}\n", .{self.free_frame_count, self.total_frame_count, free_size, total_size}); } };
https://raw.githubusercontent.com/iguessthislldo/georgios/7241783f787965aeff8d829610c9ce256ec86224/kernel/memory.zig
const std = @import("std"); const disk = @import("disk.zig"); const term = @import("term.zig"); const fs = @import("extended/fs.zig"); const mem = std.mem; const Allocator = mem.Allocator; const Parameters = fs.Parameters; var parameters: Parameters = undefined; var relative: usize = undefined; var manager: Allocator = undefined; var files: std.StringHashMap(*File) = undefined; pub fn init(allocator: Allocator) void { parameters = @intToPtr(*Parameters, 0x7C00).*; var total_sectors = @as(u32, parameters.total_sectors16); if (total_sectors == 0) { total_sectors = parameters.total_sectors32; } var fat_size = parameters.extended32().table_size32; var first_data_sector = parameters.reserved_sectors + (parameters.fat_count * fat_size); var data_sectors = total_sectors - (parameters.reserved_sectors + parameters.fat_count * fat_size); relative = first_data_sector + data_sectors; manager = allocator; files = std.StringHashMap(*File).init(allocator); term.printf("first availible sector: {}\r\n", .{relative}); } pub fn new(name: []const u8, size: usize) !*File { var file = try manager.create(File); try file.init(name, size); try files.put(name, file); return file; } pub fn open(name: []const u8) !*File { var file = files.get(name) orelse { term.printf("file `{s}` does not exist\r\n", .{name}); return std.os.AcceptError.FileNotFound; }; return file; } pub const File = struct { name: []const u8, cache: [512]u8, sector: usize, size: usize, offset: usize, const Self = @This(); pub fn init(self: *Self, name: []const u8, size: usize) !void { const sectors = (size + 511 & ~@as(usize, 511)) / 512; defer self.name = name; self.sector = relative; self.size = size; self.offset = 0; try disk.read(self.sector, self.view()); relative += sectors; } fn die(err: anyerror) void { term.printf("disk error: {s}\r\n", .{@errorName(err)}); } pub fn write(self: *Self, buffer: []u8) !void { if (self.offset + buffer.len >= self.size) { return std.os.AccessError.InputTooLong; } var result = self.offset + buffer.len; defer self.offset = result; defer self.reload() catch |err| die(err); try disk.write(self.sector + self.offset / 512, @ptrCast([*]align(1) u16, buffer)[0 .. buffer.len / 2]); } pub fn seek(self: *Self, offset: usize) !void { if (offset >= self.size) { return std.os.AccessError.InputTooLong; } self.offset = offset; try self.reload(); } pub fn peek(self: *Self) u8 { if (self.offset >= self.size) { return 0; } const ch = self.cache[self.offset % 512]; return ch; } pub fn getchar(self: *Self) u8 { if (self.offset >= self.size) { return 0; } const ch = self.cache[self.offset % 512]; self.offset += 1; if (self.offset % 512 == 0) { self.reload() catch |err| die(err); } return ch; } pub fn putback(self: *Self, ch: u8) void { _ = ch; if (self.offset > 0) { self.offset -= 1; } if (self.offset % 512 == 511) { self.reload() catch |err| die(err); } } fn view(self: *Self) []align(1) u16 { return @ptrCast([*]align(1) u16, &self.cache)[0..256]; } fn reload(self: *Self) !void { try disk.read(self.sector + self.offset / 512, self.view()); } };
https://raw.githubusercontent.com/sajjadium/ctf-archives/b7012a5fc5454f8c74ce534ecf4da521c5b9595e/ctfs/AmateursCTF/2023/pwn/simpleOS/src/fs.zig
const std = @import("std"); const assert = std.debug.assert; const Enemy = @import("enemy.zig").Enemy; const GameState = @import("GameState.zig"); const JS = @import("JS.zig"); const Projectile = @import("projectile.zig").Projectile; const utils = @import("utils.zig"); const Ball2D = utils.Ball2D; const RGBColor = utils.RGBColor; const Vector2D = utils.Vector2D; const Particle = struct { ball: Ball2D, const Self = @This(); const friction = 0.99; pub fn init(pos: Vector2D, vel: Vector2D, radius: f32, color: RGBColor) Self { assert(0.0 <= radius); return .{ .ball = Ball2D.init(pos, vel, radius, color), }; } pub fn update(self: *Self) void { // Particles slow down as they move away from the impacted area. self.ball.vel.x *= friction; self.ball.vel.y *= friction; self.ball.pos.x += self.ball.vel.x; self.ball.pos.y += self.ball.vel.y; // Particles also become more transparent as they move away. // When the transparency reaches 0, the particle is removed (see below). self.ball.color.a -= 0.01; } pub fn draw(self: Self) void { JS.drawBall2D(self.ball); } }; pub const ParticleArrayList = struct { array_list: std.ArrayListUnmanaged(Particle), const Self = @This(); pub fn init() Self { return .{ .array_list = std.ArrayListUnmanaged(Particle){}, }; } pub fn reset(self: *Self, game_state: *GameState) void { self.array_list.clearAndFree(game_state.allocator); } pub inline fn count(self: Self) usize { return self.array_list.items.len; } pub inline fn delete(self: *Self, index: usize) void { _ = self.array_list.swapRemove(index); } pub inline fn push(self: *Self, game_state: *GameState, particle: Particle) void { self.array_list.append(game_state.allocator, particle) catch unreachable; } pub fn generate(self: *Self, game_state: *GameState, enemy: *Enemy, projectile: *Projectile) void { const pos = projectile.ball.pos; var i: f32 = 0.0; // The size of the enemy determines how many particles will be produced. while (i < enemy.ball.radius) : (i += 1.0) { // The particle generated goes in a random direction. const vel = Vector2D.init( (JS.random() * 2 - 1) * (4 * JS.random()), (JS.random() * 2 - 1) * (4 * JS.random()), ); const radius = JS.random() * 2; const particle = Particle.init(pos, vel, radius, enemy.ball.color); self.push(game_state, particle); } } pub fn step(self: *Self, game_state: *GameState) void { const board = game_state.board; var items = self.array_list.items; var i: usize = 0; while (i < self.count()) { var particle = &items[i]; if (particle.ball.color.a <= 0.0 or board.isOutOfBoundary(particle.ball)) { // Don't update the index if we remove an item from the list, it still valid. self.delete(i); continue; } i += 1; } for (items) |*particle| { particle.update(); particle.draw(); } } };
https://raw.githubusercontent.com/daneelsan/Dodgeballz/ac3f94ce0b54c86720d545c21f506c1aff6cd248/src/particle.zig
const std = @import("std"); pub fn isArmstrongNumber(num: u128) bool { const num_digits = digit_count(num); var remainder: u128 = num; var armstrong_sum: u128 = 0; while (remainder != 0) : (remainder /= 10) armstrong_sum += std.math.pow(u128, remainder % 10, num_digits); return armstrong_sum == num; } fn digit_count(num: u128) u8 { var count: u8 = 0; var remainder = num; while (remainder != 0) : (remainder /= 10) count += 1; return count; }
https://raw.githubusercontent.com/ErikSchierboom/exercism/000175f6b73decb604d41aa0bbd250d11e0cea84/zig/armstrong-numbers/armstrong_numbers.zig
// Set the resolved type for labels to .symbol_def. // The resolved constant for these expressions is the raw symbol name. // Any labels which do not begin with `_` and are not in a stack section will be added to the global symbol table. // Create Sections for each named section block and set the Block.section handle to reference it. pub fn process_labels_and_sections(a: *Assembler, file: *Source_File) void { const s = file.slices(); const insn_operations = s.insn.items(.operation); const insn_labels = s.insn.items(.label); const insn_params = s.insn.items(.params); const expr_infos = s.expr.items(.info); const block_labels = s.block.items(.labels); for (0.., s.block.items(.first_insn), s.block.items(.end_insn)) |block_handle_usize, first_insn, end_insn| { const block_handle: Source_File.Block.Handle = @intCast(block_handle_usize); const private_labels = &block_labels[block_handle]; var is_stack_block = false; for (first_insn.., insn_operations[first_insn..end_insn]) |insn_handle_usize, op| { const insn_handle: Instruction.Handle = @intCast(insn_handle_usize); switch (op) { .section, .boot, .code, .kcode, .entry, .kentry, .data, .kdata, .@"const", .kconst, .stack => { s.block.items(.block_type)[block_handle] = op; var maybe_section_name: ?[]const u8 = null; if (insn_params[insn_handle]) |section_name_expr| { const symbol_constant = resolve_symbol_def_expr(a, s, section_name_expr); maybe_section_name = symbol_constant.as_string(); } if (op == .stack) { is_stack_block = true; process_stack_block(a, s, block_handle, insn_handle, maybe_section_name); } else { process_section_block(a, s, block_handle, insn_handle, Section.Kind.from_directive(op), maybe_section_name); } }, .def => { const params_expr = insn_params[insn_handle].?; const symbol_expr = s.expr.items(.info)[params_expr].list.left; _ = resolve_symbol_def_expr(a, s, symbol_expr); }, .undef, .push, .pop => { if (insn_params[insn_handle]) |params| { _ = resolve_symbol_def_expr_list(a, s, params); } }, .local => { const params_expr = insn_params[insn_handle].?; const bin = expr_infos[params_expr].list; const symbol_name = resolve_symbol_def_expr(a, s, bin.left).as_string(); const result = s.file.locals.getOrPut(a.gpa, symbol_name) catch @panic("OOM"); if (result.found_existing) { const target_insn_handle = result.value_ptr.instruction_handle(s); const line_number = s.insn.items(.line_number)[target_insn_handle]; a.record_expr_error_fmt(s.file.handle, params_expr, "Duplicate .local name (canonical symbol is at line {})", .{ line_number }, .{}); } else { result.value_ptr.* = .{ .expression = bin.right }; } }, .none, .nil, .org, .@"align", .keep, .insn, .bound_insn, .db, .dw, .dd, .zb, .zw, .zd, .range => {}, } } for (first_insn.., insn_labels[first_insn..end_insn]) |insn_handle_usize, maybe_label_expr| { const insn_handle: Instruction.Handle = @intCast(insn_handle_usize); if (maybe_label_expr) |label_expr| switch (expr_infos[label_expr]) { .local_label_def => |inner_label_expr| { const symbol_constant = resolve_symbol_def_expr(a, s, inner_label_expr); const symbol_name = symbol_constant.as_string(); const result = s.file.locals.getOrPut(a.gpa, symbol_name) catch @panic("OOM"); if (result.found_existing) { const target_insn_handle = result.value_ptr.instruction_handle(s); const line_number = s.insn.items(.line_number)[target_insn_handle]; a.record_expr_error_fmt(s.file.handle, label_expr, "Duplicate .local name (canonical symbol is at line {})", .{ line_number }, .{}); } else { result.value_ptr.* = .{ .instruction = .{ .file = file.handle, .instruction = insn_handle, }}; } }, else => { const symbol_constant = resolve_symbol_def_expr(a, s, label_expr); const symbol_name = symbol_constant.as_string(); if (is_stack_block or std.mem.startsWith(u8, symbol_name, "_")) { const result = private_labels.getOrPut(a.gpa, symbol_name) catch @panic("OOM"); if (result.found_existing) { const target_line_number = s.insn.items(.line_number)[result.value_ptr.*]; a.record_expr_error_fmt(s.file.handle, label_expr, "Duplicate private label (canonical label is at line {})", .{ target_line_number }, .{}); } else { result.value_ptr.* = insn_handle; } } else { const result = a.public_labels.getOrPut(a.gpa, symbol_name) catch @panic("OOM"); if (result.found_existing) { const target_file = a.get_source(result.value_ptr.file); const target_line_number = target_file.instructions.items(.line_number)[result.value_ptr.instruction]; a.record_expr_error_fmt(s.file.handle, label_expr, "Duplicate label (canonical label is at line {} in {s})", .{ target_line_number, target_file.name }, .{}); } else { result.value_ptr.* = .{ .file = file.handle, .instruction = insn_handle, }; } } }, }; } } } fn process_stack_block(a: *Assembler, s: Source_File.Slices, block_handle: Source_File.Block.Handle, insn_handle: Instruction.Handle, maybe_stack_name: ?[]const u8) void { const name = maybe_stack_name orelse ""; const result = s.file.stacks.getOrPut(a.gpa, name) catch @panic("OOM"); if (result.found_existing) { const canonical_insn_handle = s.block.items(.first_insn)[result.value_ptr.*]; const canonical_line_number = s.insn.items(.line_number)[canonical_insn_handle]; a.record_insn_error_fmt(s.file.handle, insn_handle, "Ignoring duplicate .stack block; canonical block is at line {}", .{ canonical_line_number }, .{}); } else { result.value_ptr.* = block_handle; } } fn process_section_block(a: *Assembler, s: Source_File.Slices, block_handle: Source_File.Block.Handle, insn_handle: Instruction.Handle, kind: Section.Kind, maybe_section_name: ?[]const u8) void { const section_name = maybe_section_name orelse kind.default_name(); var range: ?Assembler.Address_Range = null; if (kind == .boot) { range = .{ .first = 0, .len = 0x1_0000, }; } const entry = a.sections.getOrPutValue(a.gpa, section_name, .{ .name = section_name, .kind = kind, .has_chunks = false, .range = range, }) catch @panic("OOM"); const found_kind = entry.value_ptr.kind; if (found_kind != kind) { a.record_insn_error_fmt(s.file.handle, insn_handle, "Section already exists; expected .{s}", .{ @tagName(found_kind) }, .{}); } s.block.items(.section)[block_handle] = @intCast(entry.index); } fn resolve_symbol_def_expr_list(a: *Assembler, s: Source_File.Slices, symbol_def_expr: Expression.Handle) void { const infos = s.expr.items(.info); var expr = symbol_def_expr; while (infos[expr] == .list) { const bin = infos[expr].list; _ = resolve_symbol_def_expr(a, s, bin.left); expr = bin.right; } _ = resolve_symbol_def_expr(a, s, expr); } fn resolve_symbol_def_expr(a: *Assembler, s: Source_File.Slices, symbol_def_expr: Expression.Handle) *const Constant { const symbol_name = symbols.parse_symbol(a, s, symbol_def_expr); s.expr.items(.resolved_constant)[symbol_def_expr] = symbol_name; s.expr.items(.resolved_type)[symbol_def_expr] = .symbol_def; return symbol_name; } pub fn resolve_expression_types(a: *Assembler) bool { var made_progress = true; var unresolved = true; while (made_progress) { made_progress = false; unresolved = false; for (a.files.items) |*file| { var slices = file.slices(); for (slices.expr.items(.resolved_type), 0..) |expr_type, expr_handle| { if (expr_type == .unknown) { if (try_resolve_expr_type(a, slices, @intCast(expr_handle))) { made_progress = true; } else { unresolved = true; } } } } } if (unresolved) { for (a.files.items) |*file| { const expr_slice = file.expressions.slice(); const resolved_types = expr_slice.items(.resolved_type); for (resolved_types, 0..) |expr_type, expr_handle| { if (expr_type == .unknown) { a.record_expr_error(file.handle, @intCast(expr_handle), "Could not determine type for expression", .{}); resolved_types[expr_handle] = .poison; } } } return false; } return true; } pub fn try_resolve_expr_type(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) bool { const expr_infos = s.expr.items(.info); var expr_resolved_types = s.expr.items(.resolved_type); std.debug.assert(expr_resolved_types[expr_handle] == .unknown); const info = expr_infos[expr_handle]; switch (info) { .list, .arrow => expr_resolved_types[expr_handle] = .poison, .literal_int => { const token_handle = s.expr.items(.token)[expr_handle]; const token = s.file.tokens.get(token_handle); if (Constant.init_int_literal(a.gpa, &a.constant_temp, token.location(s.file.source))) |constant| { expr_resolved_types[expr_handle] = Expression.Type.constant(); s.expr.items(.resolved_constant)[expr_handle] = constant.intern(a.arena, a.gpa, &a.constants); } else |err| { switch (err) { error.Overflow => a.record_expr_error(s.file.handle, expr_handle, "Integer literal too large", .{}), error.InvalidCharacter => a.record_expr_error(s.file.handle, expr_handle, "Invalid character in integer literal", .{}), } expr_resolved_types[expr_handle] = .poison; } }, .literal_str => { var token_handle = s.expr.items(.token)[expr_handle]; var token = s.file.tokens.get(token_handle); if (token.kind == .str_literal_raw) { const token_kinds = s.file.tokens.items(.kind); a.constant_temp.clearRetainingCapacity(); var raw = token.location(s.file.source); if (raw[raw.len - 1] == '\n') { raw.len -= 1; } if (raw[raw.len - 1] == '\r') { raw.len -= 1; } a.constant_temp.appendSlice(a.gpa, raw[2..]) catch @panic("OOM"); token_handle += 1; while (true) { switch (token_kinds[token_handle]) { .str_literal_raw => { token = s.file.tokens.get(token_handle); raw = token.location(s.file.source); if (raw[raw.len - 1] == '\n') { raw.len -= 1; } if (raw[raw.len - 1] == '\r') { raw.len -= 1; } a.constant_temp.append(a.gpa, '\n') catch @panic("OOM"); a.constant_temp.appendSlice(a.gpa, raw[2..]) catch @panic("OOM"); }, .linespace => {}, else => break, } token_handle += 1; } const constant = Constant.init_string(a.constant_temp.items); expr_resolved_types[expr_handle] = Expression.Type.constant(); s.expr.items(.resolved_constant)[expr_handle] = constant.intern(a.arena, a.gpa, &a.constants); } else if (Constant.init_string_literal(a.gpa, &a.constant_temp, token.location(s.file.source))) |constant| { expr_resolved_types[expr_handle] = Expression.Type.constant(); s.expr.items(.resolved_constant)[expr_handle] = constant.intern(a.arena, a.gpa, &a.constants); } else |err| { switch (err) { error.Overflow => a.record_expr_error(s.file.handle, expr_handle, "Invalid decimal byte in string literal escape sequence", .{}), error.InvalidCharacter => a.record_expr_error(s.file.handle, expr_handle, "Invalid character in string literal", .{}), error.InvalidCodepoint => a.record_expr_error(s.file.handle, expr_handle, "Invalid codepoint in string literal escape sequence", .{}), error.InvalidBase64 => a.record_expr_error(s.file.handle, expr_handle, "Invalid base64 in string literal escape sequence", .{}), error.UnclosedLiteral => a.record_expr_error(s.file.handle, expr_handle, "String literal is missing closing '\"' character", .{}), error.IncompleteEscape => a.record_expr_error(s.file.handle, expr_handle, "String literal contains an incomplete escape sequence", .{}), } expr_resolved_types[expr_handle] = .poison; } }, .literal_reg => { // SFR types are preassigned when parsed, so we can assume we're dealing with a GPR name. const token_handle = s.expr.items(.token)[expr_handle]; const token = s.file.tokens.get(token_handle); const name = token.location(s.file.source); const index = std.fmt.parseUnsigned(Register_Index, name[1..], 10) catch unreachable; const reg_type: Expression.Type = switch (name[0]) { 'r', 'R' => Expression.Type.reg(16, index, null), 'x', 'X' => Expression.Type.reg(32, index, null), 'b', 'B' => Expression.Type.reg(8, index, null), else => unreachable, }; expr_resolved_types[expr_handle] = reg_type; }, .literal_current_address => { const token_handle = s.expr.items(.token)[expr_handle]; const block_handle = s.file.find_block_by_token(token_handle); if (s.block.items(.block_type)[block_handle]) |op| { expr_resolved_types[expr_handle] = switch (op) { .none, .nil, .insn, .bound_insn, .org, .@"align", .keep, .range, .def, .undef, .local, .db, .dw, .dd, .zb, .zw, .zd, .push, .pop, => unreachable, .section => Expression.Type.absolute_address(.data), .boot, .code, .kcode, .entry, .kentry => Expression.Type.relative_address(.insn, Expression.Type.sr(.ip)), .data, .kdata, .@"const", .kconst => Expression.Type.relative_address(.data, Expression.Type.sr(.ip)), .stack => Expression.Type.relative_address(.stack, Expression.Type.sr(.sp)), } catch unreachable; } else { // Block does not have a section handle, so it's an .info section by default expr_resolved_types[expr_handle] = Expression.Type.absolute_address(.data); } s.expr.items(.flags)[expr_handle].insert(.constant_depends_on_layout); return true; }, .literal_symbol_ref => { const token_handle = s.expr.items(.token)[expr_handle]; const symbol_literal = s.file.tokens.get(token_handle).location(s.file.source); const symbol_constant = Constant.init_symbol_literal(a.gpa, &a.constant_temp, symbol_literal); return try_resolve_symbol_type(a, s, expr_handle, token_handle, symbol_constant.as_string()); }, .directive_symbol_ref => |inner_expr| { if (s.expr.items(.resolved_constant)[inner_expr]) |symbol| { return try_resolve_symbol_type(a, s, expr_handle, s.expr.items(.token)[expr_handle], symbol.as_string()); } else return false; }, .literal_symbol_def, .directive_symbol_def => { _ = resolve_symbol_def_expr(a, s, expr_handle); }, .local_label_def => |inner_expr_handle| { const symbol_name = resolve_symbol_def_expr(a, s, inner_expr_handle); s.expr.items(.resolved_constant)[expr_handle] = symbol_name; expr_resolved_types[expr_handle] = .symbol_def; }, // unary operators: .negate, .complement, .crlf_cast, .lf_cast, .index_to_reg8, .index_to_reg16, .index_to_reg32, .reg_to_index, .signed_cast, .unsigned_cast, .remove_signedness_cast, .absolute_address_cast, .data_address_cast, .insn_address_cast, .stack_address_cast, .remove_address_cast, => |inner_expr| { const inner_type = expr_resolved_types[inner_expr]; if (inner_type == .unknown) return false; if (inner_type == .poison) { expr_resolved_types[expr_handle] = .poison; return true; } defer resolve_constant_depends_on_layout(s, expr_handle, inner_expr); switch (info) { .negate, .complement, .crlf_cast, .lf_cast => { if (inner_type.is_constant()) { expr_resolved_types[expr_handle] = Expression.Type.constant(); return true; } a.record_expr_error(s.file.handle, expr_handle, "Operand must be a constant expression", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, .index_to_reg8, .index_to_reg16, .index_to_reg32 => { if (s.expr.items(.flags)[inner_expr].contains(.constant_depends_on_layout)) { a.record_expr_error(s.file.handle, expr_handle, "Operand cannot vary on memory layout", .{}); expr_resolved_types[expr_handle] = .poison; return true; } if (inner_type.is_constant()) { const constant = layout.resolve_expression_constant(a, s, 0, inner_expr) orelse { expr_resolved_types[expr_handle] = .poison; return true; }; const index = constant.as_int(Register_Index) catch { a.record_expr_error(s.file.handle, expr_handle, "Operand out of range", .{}); expr_resolved_types[expr_handle] = .poison; return true; }; expr_resolved_types[expr_handle] = switch (info) { .index_to_reg8 => Expression.Type.reg(8, index, null), .index_to_reg16 => Expression.Type.reg(16, index, null), .index_to_reg32 => Expression.Type.reg(32, index, null), else => unreachable, }; return true; } a.record_expr_error(s.file.handle, expr_handle, "Operand must be a constant expression", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, .reg_to_index => { if (inner_type.simple_base()) |base| { if (base.register_index()) |index| { const constant = Constant.init_int(index); s.expr.items(.resolved_constant)[expr_handle] = constant.intern(a.arena, a.gpa, &a.constants); expr_resolved_types[expr_handle] = Expression.Type.constant(); return true; } } a.record_expr_error(s.file.handle, expr_handle, "Operand must be a GPR expression", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, .signed_cast, .unsigned_cast, .remove_signedness_cast => { if (inner_type.is_constant()) { if (info == .remove_signedness_cast) { a.record_expr_error(s.file.handle, expr_handle, "Operand must be a GPR expression", .{}); expr_resolved_types[expr_handle] = .poison; } else { expr_resolved_types[expr_handle] = Expression.Type.constant(); } return true; } else if (inner_type.simple_base()) |base| { switch (base) { .reg8, .reg16, .reg32 => |reg| { const signedness: ?Signedness = switch (info) { .signed_cast => .signed, .unsigned_cast => .unsigned, .remove_signedness_cast => null, else => unreachable, }; expr_resolved_types[expr_handle] = switch (base) { .reg8 => Expression.Type.reg(8, reg.index, signedness), .reg16 => Expression.Type.reg(16, reg.index, signedness), .reg32 => Expression.Type.reg(32, reg.index, signedness), else => unreachable, }; return true; }, else => {}, } } a.record_expr_error(s.file.handle, expr_handle, "Operand must be a constant or GPR expression", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, .absolute_address_cast => { if (inner_type.base_offset_type()) |bot| { if (bot.base == .sr and bot.base.sr == .ip) { var builder: Expression.Type_Builder = .{}; builder.add(inner_type); builder.subtract(Expression.Type.sr(.ip)); expr_resolved_types[expr_handle] = builder.build() catch unreachable; return true; } } a.record_expr_error(s.file.handle, expr_handle, "Operand must be an IP-relative expression", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, .data_address_cast, .insn_address_cast, .stack_address_cast => { if (inner_type.base_offset_type()) |bot| { const new_space: Address_Space = switch (info) { .data_address_cast => .data, .insn_address_cast => .insn, .stack_address_cast => .stack, else => unreachable, }; if (inner_type.address_space()) |current_space| { if (current_space != new_space) { a.record_expr_error(s.file.handle, expr_handle, "Casting directly between address spaces is not allowed. Use `.raw` first if you really want this.", .{}); expr_resolved_types[expr_handle] = .poison; return true; } } expr_resolved_types[expr_handle] = switch (new_space) { inline else => |space| Expression.Type.address_space_cast(space, bot) }; return true; } a.record_expr_error(s.file.handle, expr_handle, "Invalid operand for address space cast", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, .remove_address_cast => { if (inner_type.base_offset_type()) |bot| { expr_resolved_types[expr_handle] = .{ .raw = bot }; return true; } a.record_expr_error(s.file.handle, expr_handle, "Invalid operand for address space cast", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, else => unreachable, } unreachable; // no fallthrough to avoid bugs }, // binary operators: .plus => |bin| { var builder: Expression.Type_Builder = .{}; builder.add(expr_resolved_types[bin.left]); builder.add(expr_resolved_types[bin.right]); const result_type = builder.build() catch t: { a.record_expr_error(s.file.handle, expr_handle, "Cannot represent result of symbolic addition", .{}); break :t .poison; }; if (result_type == .unknown) return false; expr_resolved_types[expr_handle] = result_type; resolve_constant_depends_on_layout_binary(s, expr_handle, bin); }, .minus => |bin| { var builder: Expression.Type_Builder = .{}; builder.add(expr_resolved_types[bin.left]); builder.subtract(expr_resolved_types[bin.right]); const result_type = builder.build() catch t: { a.record_expr_error(s.file.handle, expr_handle, "Cannot represent result of symbolic subtraction", .{}); break :t .poison; }; if (result_type == .unknown) return false; expr_resolved_types[expr_handle] = result_type; resolve_constant_depends_on_layout_binary(s, expr_handle, bin); }, .multiply, .shl, .shr, .concat, .concat_repeat, .bitwise_or, .bitwise_xor, .bitwise_and, .length_cast, .truncate, .sign_extend, .zero_extend => |bin| { const left = expr_resolved_types[bin.left]; const right = expr_resolved_types[bin.right]; if (left == .poison or right == .poison) { expr_resolved_types[expr_handle] = .poison; return true; } if (left == .unknown or right == .unknown) return false; if (left.is_constant() and right.is_constant()) { expr_resolved_types[expr_handle] = Expression.Type.constant(); } else { a.record_expr_error(s.file.handle, expr_handle, "Both operands must be constant expressions", .{}); expr_resolved_types[expr_handle] = .poison; } resolve_constant_depends_on_layout_binary(s, expr_handle, bin); }, } return true; } fn resolve_constant_depends_on_layout(s: Source_File.Slices, expr_handle: Expression.Handle, dependent_expr: Expression.Handle) void { var expr_flags = s.expr.items(.flags); if (expr_flags[dependent_expr].contains(.constant_depends_on_layout)) { expr_flags[expr_handle].insert(.constant_depends_on_layout); } } fn resolve_constant_depends_on_layout_binary(s: Source_File.Slices, expr_handle: Expression.Handle, bin: Expression.Binary) void { var expr_flags = s.expr.items(.flags); if (expr_flags[bin.left].contains(.constant_depends_on_layout) or expr_flags[bin.right].contains(.constant_depends_on_layout)) { expr_flags[expr_handle].insert(.constant_depends_on_layout); } } fn try_resolve_symbol_type(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle, token_handle: Token.Handle, symbol: []const u8) bool { var expr_resolved_types = s.expr.items(.resolved_type); var expr_flags = s.expr.items(.flags); switch (symbols.lookup_symbol(a, s, token_handle, symbol, false)) { .expression => |target_expr_handle| { const target_type = expr_resolved_types[target_expr_handle]; if (target_type != .unknown) { expr_resolved_types[expr_handle] = target_type; if (expr_flags[target_expr_handle].contains(.constant_depends_on_layout)) { expr_flags[expr_handle].insert(.constant_depends_on_layout); } return true; } }, .instruction => |insn_ref| { const sym_file = a.get_source(insn_ref.file); const block_handle = sym_file.find_block_by_instruction(insn_ref.instruction); if (sym_file.blocks.items(.block_type)[block_handle]) |op| { expr_resolved_types[expr_handle] = switch (op) { .none, .nil, .insn, .bound_insn, .org, .@"align", .keep, .range, .def, .undef, .local, .db, .dw, .dd, .zb, .zw, .zd, .push, .pop, => unreachable, .section => Expression.Type.absolute_address(.data), .boot, .code, .kcode, .entry, .kentry => Expression.Type.relative_address(.insn, Expression.Type.sr(.ip)), .data, .kdata, .@"const", .kconst => Expression.Type.relative_address(.data, Expression.Type.sr(.ip)), .stack => Expression.Type.relative_address(.stack, Expression.Type.sr(.sp)), // maybe this should be unreachable? } catch unreachable; } else { // Block does not have a section handle, so it's an .info section by default expr_resolved_types[expr_handle] = Expression.Type.absolute_address(.data); } expr_flags[expr_handle].insert(.constant_depends_on_layout); return true; }, .stack => { expr_resolved_types[expr_handle] = Expression.Type.relative_address(.stack, Expression.Type.sr(.sp)) catch unreachable; expr_flags[expr_handle].insert(.constant_depends_on_layout); }, .not_found => { a.record_expr_error(s.file.handle, expr_handle, "Reference to undefined symbol", .{}); expr_resolved_types[expr_handle] = .poison; return true; }, } return false; } pub fn check_instructions_and_directives_in_file(a: *Assembler, s: Source_File.Slices) void { var insn_operations = s.insn.items(.operation); var insn_params = s.insn.items(.params); var pushed_stacks = std.ArrayList([]const u8).init(a.gpa); defer pushed_stacks.deinit(); for (s.block.items(.first_insn), s.block.items(.end_insn)) |first_insn, end_insn| { var allow_code = false; var allow_data = false; var allow_range = false; for (first_insn.., insn_operations[first_insn..end_insn], insn_params[first_insn..end_insn]) |insn_handle_usize, op, maybe_params| { const insn_handle: Instruction.Handle = @intCast(insn_handle_usize); switch (op) { .boot => { allow_code = true; allow_data = true; allow_range = false; }, .section => { allow_code = true; allow_data = true; allow_range = true; }, .code, .kcode, .entry, .kentry => { allow_code = true; allow_data = false; allow_range = true; }, .data, .kdata, .@"const", .kconst => { allow_code = false; allow_data = true; allow_range = true; }, .stack => { allow_code = false; allow_data = true; allow_range = false; }, .org => check_org_params(a, s, insn_handle, maybe_params), .@"align" => check_align_params(a, s, insn_handle, maybe_params), .bound_insn => unreachable, .insn => { if (!allow_code) { a.record_insn_error(s.file.handle, insn_handle, "Instructions are not allowed in .data/.kdata/.const/.kconst/.stack sections", .{}); } check_instruction_depends_on_layout(s, insn_handle, maybe_params); }, .db, .dw, .dd => { if (!allow_data) { a.record_insn_error(s.file.handle, insn_handle, "Data directives are not allowed in .entry/.kentry/.code/.kcode sections", .{}); } if (maybe_params) |params_expr| { check_data_directive_expr_list(a, s, params_expr); } else { a.record_insn_error(s.file.handle, insn_handle, "Expected at least one data expression", .{}); } check_instruction_depends_on_layout(s, insn_handle, maybe_params); }, .zb, .zw, .zd => { if (!allow_data) { a.record_insn_error(s.file.handle, insn_handle, "Data directives are not allowed in .entry/.kentry/.code/.kcode sections", .{}); } if (maybe_params) |params_expr| { if (s.expr.items(.resolved_type)[params_expr].is_non_constant()) { a.record_expr_error(s.file.handle, params_expr, "Expected constant expression", .{}); } } check_instruction_depends_on_layout(s, insn_handle, maybe_params); }, .push => { if (!allow_code) { a.record_insn_error(s.file.handle, insn_handle, "Instructions are not allowed in .data/.kdata/.const/.kconst/.stack sections", .{}); } check_pushed_stacks(a, s, insn_handle, maybe_params, &pushed_stacks); }, .pop => { if (!allow_code) { a.record_insn_error(s.file.handle, insn_handle, "Instructions are not allowed in .data/.kdata/.const/.kconst/.stack sections", .{}); } check_popped_stacks(a, s, insn_handle, maybe_params, &pushed_stacks); }, .none, .nil, .keep => if (maybe_params) |params_expr| { a.record_expr_error(s.file.handle, params_expr, "Expected no parameters", .{}); }, .range => { if (!allow_range) { a.record_insn_error(s.file.handle, insn_handle, ".range directive is only allowed in non-boot sections", .{}); } else { check_range_params(a, s, insn_handle, maybe_params); } }, .def, .local => {}, .undef => if (maybe_params) |params_expr| { check_undef_expr_list(a, s, params_expr); } else { a.record_insn_error(s.file.handle, insn_handle, "Expected at least one .def symbol name", .{}); }, } } pushed_stacks.clearRetainingCapacity(); } } fn check_instruction_depends_on_layout(s: Source_File.Slices, insn_handle: Instruction.Handle, maybe_params: ?Expression.Handle) void { if (maybe_params) |params_handle| { if (instruction_has_layout_dependent_params(s, params_handle)) { s.insn.items(.flags)[insn_handle].insert(.depends_on_layout); return; } } } fn instruction_has_layout_dependent_params(s: Source_File.Slices, params_handle: Expression.Handle) bool { if (s.expr.items(.flags)[params_handle].contains(.constant_depends_on_layout)) return true; switch (s.expr.items(.info)[params_handle]) { .list => |bin| { return instruction_has_layout_dependent_params(s, bin.left) or instruction_has_layout_dependent_params(s, bin.right); }, else => {}, } return false; } fn check_pushed_stacks(a: *Assembler, s: Source_File.Slices, insn_handle: Instruction.Handle, maybe_params: ?Expression.Handle, pushed_stacks: *std.ArrayList([]const u8)) void { const expr_infos = s.expr.items(.info); var depends_on_layout = false; var maybe_expr_handle = maybe_params; while (maybe_expr_handle) |expr_handle| { switch (expr_infos[expr_handle]) { .list => |bin| { depends_on_layout = check_pushed_stack(a, s, bin.left, pushed_stacks) or depends_on_layout; maybe_expr_handle = bin.right; }, else => { depends_on_layout = check_pushed_stack(a, s, expr_handle, pushed_stacks) or depends_on_layout; break; } } } else { a.record_insn_error(s.file.handle, insn_handle, "Expected at least one stack block name", .{}); } if (depends_on_layout) { s.insn.items(.flags)[insn_handle].insert(.depends_on_layout); } } fn check_pushed_stack(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle, pushed_stacks: *std.ArrayList([]const u8)) bool { const insn_flags = s.insn.items(.flags); var depends_on_layout = false; const stack_block_name = symbols.parse_symbol(a, s, expr_handle).as_string(); for (pushed_stacks.items) |name| { if (std.mem.eql(u8, name, stack_block_name)) { a.record_expr_error(s.file.handle, expr_handle, "This stack block has already been pushed", .{}); return false; } } pushed_stacks.append(stack_block_name) catch @panic("OOM"); if (s.file.stacks.get(stack_block_name)) |stack_block_handle| { var iter = s.block_instructions(stack_block_handle); while (iter.next()) |insn_handle| { depends_on_layout = depends_on_layout or insn_flags[insn_handle].contains(.depends_on_layout); } } else { a.record_expr_error(s.file.handle, expr_handle, "No .stack block found with this name", .{}); } return depends_on_layout; } fn check_popped_stacks(a: *Assembler, s: Source_File.Slices, insn_handle: Instruction.Handle, maybe_params: ?Expression.Handle, pushed_stacks: *std.ArrayList([]const u8)) void { const expr_infos = s.expr.items(.info); var num_blocks_popped: usize = 0; var maybe_expr_handle = maybe_params; while (maybe_expr_handle) |expr_handle| switch (expr_infos[expr_handle]) { .list => |bin| { num_blocks_popped += 1; maybe_expr_handle = bin.right; }, else => { num_blocks_popped += 1; maybe_expr_handle = null; } }; if (num_blocks_popped == 0) { a.record_insn_error(s.file.handle, insn_handle, "Expected at least one stack block name", .{}); } var depends_on_layout = false; maybe_expr_handle = maybe_params; while (maybe_expr_handle) |expr_handle| switch (expr_infos[expr_handle]) { .list => |bin| { depends_on_layout = check_popped_stack(a, s, bin.left, pushed_stacks, &num_blocks_popped) or depends_on_layout; maybe_expr_handle = bin.right; }, else => { depends_on_layout = check_popped_stack(a, s, expr_handle, pushed_stacks, &num_blocks_popped) or depends_on_layout; maybe_expr_handle = null; } }; if (depends_on_layout) { s.insn.items(.flags)[insn_handle].insert(.depends_on_layout); } } fn check_popped_stack(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle, pushed_stacks: *std.ArrayList([]const u8), num_blocks_to_pop: *usize) bool { const insn_flags = s.insn.items(.flags); var depends_on_layout = false; const stack_block_name = symbols.parse_symbol(a, s, expr_handle).as_string(); for (0.., pushed_stacks.items) |i, name| { if (std.mem.eql(u8, name, stack_block_name)) { if (i + num_blocks_to_pop.* < pushed_stacks.items.len) { a.record_expr_error(s.file.handle, expr_handle, "Stack blocks must be popped in the reverse order they were pushed!", .{}); } else { num_blocks_to_pop.* -= 1; } _ = pushed_stacks.orderedRemove(i); break; } } else { a.record_expr_error(s.file.handle, expr_handle, "This stack block has already been popped or was never pushed!", .{}); return false; } if (s.file.stacks.get(stack_block_name)) |stack_block_handle| { var iter = s.block_instructions(stack_block_handle); while (iter.next()) |insn_handle| { depends_on_layout = depends_on_layout or insn_flags[insn_handle].contains(.depends_on_layout); } } else { a.record_expr_error(s.file.handle, expr_handle, "No .stack block found with this name", .{}); } return depends_on_layout; } fn check_undef_expr_list(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) void { const infos = s.expr.items(.info); var expr = expr_handle; while (infos[expr] == .list) { const bin = infos[expr].list; _ = check_undef_expr(a, s, bin.left); expr = bin.right; } _ = check_undef_expr(a, s, expr); } fn check_undef_expr(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) void { const symbol_name = symbols.parse_symbol(a, s, expr_handle); const token = s.expr.items(.token)[expr_handle]; switch (symbols.lookup_symbol(a, s, token, symbol_name.as_string(), false)) { .expression => {}, .not_found => { a.record_expr_error(s.file.handle, expr_handle, "Symbol must be defined before it can be un-defined", .{}); }, .instruction => { a.record_expr_error(s.file.handle, expr_handle, "Labels cannot be un-defined", .{}); }, .stack => { a.record_expr_error(s.file.handle, expr_handle, "Stack labels cannot be un-defined", .{}); }, } } fn check_data_directive_expr_list(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) void { const infos = s.expr.items(.info); var expr = expr_handle; while (true) { switch (infos[expr]) { .list => |bin| { check_data_directive_expr(a, s, bin.left); expr = bin.right; }, else => break, } } check_data_directive_expr(a, s, expr); } fn check_data_directive_expr(a: *Assembler, s: Source_File.Slices, expr_handle: Expression.Handle) void { const expr_type = s.expr.items(.resolved_type)[expr_handle]; if (expr_type.base_offset_type() != null and !expr_type.is_constant()) { a.record_expr_error(s.file.handle, expr_handle, "Expected constant expression", .{}); } } fn check_org_params(a: *Assembler, s: Source_File.Slices, insn_handle: Instruction.Handle, maybe_params: ?Expression.Handle) void { const expr_resolved_types = s.expr.items(.resolved_type); var params = [_]?Expression.Handle{null}; get_param_handles(a, s, maybe_params, &params); if (params[0]) |address_expr| { const expr_type = expr_resolved_types[address_expr]; if (expr_type.base_offset_type()) |bot| { if (bot.base == .sr and bot.base.sr == .ip and bot.offset == .constant) { a.record_expr_error(s.file.handle, address_expr, "Expected absolute address, not relative; try using '@'", .{}); } else if (bot.base != .constant) { a.record_expr_error(s.file.handle, address_expr, "Expected constant or absolute address", .{}); } } } else { a.record_insn_error(s.file.handle, insn_handle, ".org directive must be followed by address expression", .{}); } } fn check_align_params(a: *Assembler, s: Source_File.Slices, insn_handle: Instruction.Handle, maybe_params: ?Expression.Handle) void { const expr_resolved_types = s.expr.items(.resolved_type); var params = [_]?Expression.Handle{null} ** 2; get_param_handles(a, s, maybe_params, &params); if (params[0]) |align_expr| { if (expr_resolved_types[align_expr].is_non_constant()) { a.record_expr_error(s.file.handle, align_expr, "Expected constant", .{}); } } else { a.record_insn_error(s.file.handle, insn_handle, ".align directive must be followed by constant expression", .{}); } if (params[1]) |offset_expr| { if (expr_resolved_types[offset_expr].is_non_constant()) { a.record_expr_error(s.file.handle, offset_expr, "Expected constant", .{}); } } } fn check_range_params(a: *Assembler, s: Source_File.Slices, insn_handle: Instruction.Handle, maybe_params: ?Expression.Handle) void { const expr_flags = s.expr.items(.flags); const expr_resolved_types = s.expr.items(.resolved_type); var params = [_]?Expression.Handle{null} ** 2; get_param_handles(a, s, maybe_params, &params); var range = Assembler.Address_Range{ .first = 0, .len = 0, }; if (params[0]) |expr| { if (expr_resolved_types[expr].is_non_constant()) { a.record_expr_error(s.file.handle, expr, "Expected minimum address constant", .{}); } if (expr_flags[expr].contains(.constant_depends_on_layout)) { a.record_expr_error(s.file.handle, expr, "Expression cannot depend on layout", .{}); } else { const constant = layout.resolve_expression_constant_or_default(a, s, 0, expr, 0x1000); range.first = constant.as_int(u32) catch a: { a.record_expr_error(s.file.handle, expr, "Expression must fit in u32", .{}); break :a 0x1000; }; if (hw.addr.Offset.init(@truncate(range.first)).raw() != 0) { a.record_expr_error(s.file.handle, expr, "Expected an address with a page offset of 0", .{}); } } } if (params[1]) |expr| { if (expr_resolved_types[expr].is_non_constant()) { a.record_expr_error(s.file.handle, expr, "Expected maximum address constant", .{}); } if (expr_flags[expr].contains(.constant_depends_on_layout)) { a.record_expr_error(s.file.handle, expr, "Expression cannot depend on layout", .{}); } else { const constant = layout.resolve_expression_constant_or_default(a, s, 0, expr, 0xFFFF_FFFF); const last = constant.as_int(u32) catch a: { a.record_expr_error(s.file.handle, expr, "Expression must fit in u32", .{}); break :a 0xFFFF_FFFF; }; if (hw.addr.Offset.init(@truncate(last)) != hw.addr.Offset.max) { a.record_expr_error(s.file.handle, expr, "Expected an address with a page offset of 0xFFF", .{}); } range.len = @as(usize, last - range.first) + 1; const block_handle = s.file.find_block_by_instruction(insn_handle); const section_handle = s.file.blocks.items(.section)[block_handle].?; const section = a.get_section_ptr(section_handle); if (section.range) |_| { a.record_insn_error(s.file.handle, insn_handle, "Multiple .range directives found for this section; ignoring this one", .{}); } else { section.range = range; } } } else { a.record_insn_error(s.file.handle, insn_handle, ".range directive must be followed by <min_address>, <max_address> constant expressions", .{}); } } fn get_param_handles(a: *Assembler, s: Source_File.Slices, maybe_params_expr: ?Expression.Handle, out: []?Expression.Handle) void { if (out.len == 0) return; if (maybe_params_expr) |params_expr| { var expr_handle = params_expr; const expr_infos = s.expr.items(.info); for (out) |*p| { switch (expr_infos[expr_handle]) { .list => |bin| { p.* = bin.left; expr_handle = bin.right; }, else => { p.* = expr_handle; return; } } } a.record_expr_error(s.file.handle, expr_handle, "Too many parameters", .{}); } } pub fn check_symbol_ambiguity_in_file(a: *Assembler, s: Source_File.Slices) void { const expr_tokens = s.expr.items(.token); for (0.., s.expr.items(.info)) |expr_handle, info| switch (info) { .literal_symbol_ref, .directive_symbol_ref => { const constant = symbols.parse_symbol(a, s, @intCast(expr_handle)); _ = symbols.lookup_symbol(a, s, expr_tokens[expr_handle], constant.as_string(), true); }, else => {}, }; } const Token = lex.Token; const lex = @import("lex.zig"); const symbols = @import("symbols.zig"); const layout = @import("layout.zig"); const Assembler = @import("Assembler.zig"); const Block = Source_File.Block; const Source_File = @import("Source_File.zig"); const Instruction = @import("Instruction.zig"); const Expression = @import("Expression.zig"); const Constant = @import("Constant.zig"); const Section = @import("Section.zig"); const Error = @import("Error.zig"); const Address_Space = isa.Address_Space; const isa = arch.isa; const Register_Index = hw.Register_Index; const hw = arch.hw; const arch = @import("lib_arch"); const Signedness = std.builtin.Signedness; const std = @import("std");
https://raw.githubusercontent.com/bcrist/vera/3fa048b730dedfc3551ecf352792a8322466867a/lib/assembler/typechecking.zig
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2024 Lee Cannon <leecannon@leecannon.xyz> const std = @import("std"); const core = @import("core"); const kernel = @import("kernel"); const limine = @import("limine"); export fn _start() callconv(.C) noreturn { @call(.never_inline, @import("init.zig").initStage1, .{}) catch |err| { core.panicFmt("unhandled error: {s}", .{@errorName(err)}); }; core.panic("`init.initStage1` returned"); } pub const KernelBaseAddress = struct { virtual: core.VirtualAddress, physical: core.PhysicalAddress, }; /// Returns the kernel virtual and physical base addresses provided by the bootloader, if any. pub fn kernelBaseAddress() ?KernelBaseAddress { if (limine_requests.kernel_address.response) |resp| { return .{ .virtual = resp.virtual_base, .physical = resp.physical_base, }; } return null; } /// Returns the direct map address provided by the bootloader, if any. pub fn directMapAddress() ?core.VirtualAddress { if (limine_requests.hhdm.response) |resp| { return resp.offset; } return null; } /// Returns an iterator over the memory map entries, iterating in the given direction. pub fn memoryMap(direction: Direction) MemoryMapIterator { const memmap_response = limine_requests.memmap.response orelse core.panic("no memory map from the bootloader"); const entries = memmap_response.entries(); return .{ .limine = .{ .index = switch (direction) { .forwards => 0, .backwards => entries.len, }, .entries = entries, .direction = direction, }, }; } /// An entry in the memory map provided by the bootloader. pub const MemoryMapEntry = struct { range: core.PhysicalRange, type: Type, pub const Type = enum { free, in_use, reserved, reclaimable, unusable, }; pub fn print(entry: MemoryMapEntry, writer: std.io.AnyWriter, indent: usize) !void { try writer.writeAll("MemoryMapEntry - "); try writer.writeAll(@tagName(entry.type)); try writer.writeAll(" - "); try entry.range.print(writer, indent); } pub inline fn format( value: MemoryMapEntry, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype, ) !void { _ = options; _ = fmt; return if (@TypeOf(writer) == std.io.AnyWriter) print(value, writer, 0) else print(value, writer.any(), 0); } fn __helpZls() void { MemoryMapEntry.print(undefined, @as(std.fs.File.Writer, undefined), 0); } }; /// An iterator over the memory map entries provided by the bootloader. pub const MemoryMapIterator = union(enum) { limine: LimineMemoryMapIterator, /// Returns the next memory map entry from the iterator, if any remain. pub fn next(self: *MemoryMapIterator) ?MemoryMapEntry { return switch (self.*) { inline else => |*i| i.next(), }; } }; pub const Direction = enum { forwards, backwards, }; const LimineMemoryMapIterator = struct { index: usize, entries: []const *const limine.Memmap.Entry, direction: Direction, pub fn next(self: *LimineMemoryMapIterator) ?MemoryMapEntry { const limine_entry = switch (self.direction) { .backwards => blk: { if (self.index == 0) return null; self.index -= 1; break :blk self.entries[self.index]; }, .forwards => blk: { if (self.index >= self.entries.len) return null; const entry = self.entries[self.index]; self.index += 1; break :blk entry; }, }; return .{ .range = core.PhysicalRange.fromAddr(limine_entry.base, limine_entry.length), .type = switch (limine_entry.type) { .usable => .free, .kernel_and_modules, .framebuffer => .in_use, .reserved, .acpi_nvs => .reserved, .acpi_reclaimable, .bootloader_reclaimable => .reclaimable, .bad_memory => .unusable, else => .unusable, }, }; } }; /// Returns the ACPI RSDP address provided by the bootloader, if any. pub fn rsdp() ?core.VirtualAddress { if (limine_requests.rsdp.response) |resp| { return resp.address; } return null; } pub fn x2apicEnabled() bool { if (kernel.arch.arch != .x64) @compileError("x2apicEnabled can only be called on x64"); const smp_response = limine_requests.smp.response orelse return false; return smp_response.flags.x2apic_enabled; } pub fn cpuDescriptors() CpuDescriptorIterator { const smp_response = limine_requests.smp.response orelse core.panic("no cpu descriptors from the bootloader"); const entries = smp_response.cpus(); return .{ .limine = .{ .index = 0, .entries = entries, }, }; } pub const CpuDescriptor = struct { _raw: Raw, pub fn boot( self: CpuDescriptor, cpu: *kernel.Cpu, comptime targetFn: fn (cpu: *kernel.Cpu) noreturn, ) void { switch (self._raw) { .limine => |limine_info| { const trampolineFn = struct { fn trampolineFn(smp_info: *const limine.SMP.Response.SMPInfo) callconv(.C) noreturn { targetFn(@ptrFromInt(smp_info.extra_argument)); } }.trampolineFn; @atomicStore( usize, &limine_info.extra_argument, @intFromPtr(cpu), .release, ); @atomicStore( ?*const fn (*const limine.SMP.Response.SMPInfo) callconv(.C) noreturn, &limine_info.goto_address, &trampolineFn, .release, ); }, } } pub fn acpiId(self: CpuDescriptor) u32 { return switch (self._raw) { .limine => |limine_info| limine_info.processor_id, }; } pub fn lapicId(self: CpuDescriptor) u32 { if (kernel.arch.arch != .x64) @compileError("apicId can only be called on x64"); return switch (self._raw) { .limine => |limine_info| limine_info.lapic_id, }; } pub const Raw = union(enum) { limine: *limine.SMP.Response.SMPInfo, }; }; /// An iterator over the cpu descriptors provided by the bootloader. pub const CpuDescriptorIterator = union(enum) { limine: LimineCpuDescriptorIterator, pub fn count(self: CpuDescriptorIterator) usize { return switch (self) { inline else => |i| i.count(), }; } /// Returns the next cpu descriptor from the iterator, if any remain. pub fn next(self: *CpuDescriptorIterator) ?CpuDescriptor { return switch (self.*) { inline else => |*i| i.next(), }; } }; const LimineCpuDescriptorIterator = struct { index: usize, entries: []*limine.SMP.Response.SMPInfo, pub fn count(self: LimineCpuDescriptorIterator) usize { return self.entries.len; } pub fn next(self: *LimineCpuDescriptorIterator) ?CpuDescriptor { if (self.index >= self.entries.len) return null; const smp_info = self.entries[self.index]; self.index += 1; return .{ ._raw = .{ .limine = smp_info }, }; } }; const limine_requests = struct { export var limine_revison: limine.BaseRevison = .{ .revison = 1 }; export var kernel_address: limine.KernelAddress = .{}; export var hhdm: limine.HHDM = .{}; export var memmap: limine.Memmap = .{}; export var rsdp: limine.RSDP = .{}; export var smp: limine.SMP = .{ .flags = .{ .x2apic = true } }; }; comptime { _ = &limine_requests; }
https://raw.githubusercontent.com/CascadeOS/CascadeOS/07e8248e8a189b1ff74c21b60f0eb80bfe6f9574/kernel/boot.zig
const escape = @import("details/escape.zig"); const std = @import("std"); const FormatterInterface = @import("../../../json.zig").ser.Formatter; pub fn Formatter(comptime Writer: type) type { return struct { const Self = @This(); pub usingnamespace FormatterInterface( Self, Writer, .{ .writeBool = writeBool, .writeCharEscape = writeCharEscape, .writeInt = writeInt, .writeFloat = writeFloat, .writeNull = writeNull, .writeNumberString = writeNumberString, .writeRawFragment = writeRawFragment, .writeStringFragment = writeStringFragment, .beginArray = beginArray, .beginArrayValue = beginArrayValue, .beginString = beginString, .beginObject = beginObject, .beginObjectKey = beginObjectKey, .beginObjectValue = beginObjectValue, .endArray = endArray, .endArrayValue = endArrayValue, .endObject = endObject, .endObjectKey = endObjectKey, .endObjectValue = endObjectValue, .endString = endString, }, ); fn writeNull(_: Self, w: Writer) Writer.Error!void { try w.writeAll("null"); } fn writeBool(_: Self, w: Writer, v: bool) Writer.Error!void { try w.writeAll(if (v) "true" else "false"); } fn writeInt(_: Self, w: Writer, v: anytype) Writer.Error!void { try std.fmt.formatInt(v, 10, .lower, .{}, w); } fn writeFloat(_: Self, w: Writer, v: anytype) Writer.Error!void { try std.fmt.formatType(v, "", std.fmt.FormatOptions{}, w, std.fmt.default_max_depth); } fn writeNumberString(_: Self, w: Writer, v: []const u8) Writer.Error!void { try w.writeAll(v); } fn beginString(_: Self, w: Writer) Writer.Error!void { try w.writeAll("\""); } fn endString(_: Self, w: Writer) Writer.Error!void { try w.writeAll("\""); } fn writeStringFragment(_: Self, w: Writer, v: []const u8) Writer.Error!void { try w.writeAll(v); } fn writeCharEscape(_: Self, w: Writer, v: u21) Writer.Error!void { try escape.escapeChar(v, w); } fn beginArray(_: Self, w: Writer) Writer.Error!void { try w.writeAll("["); } fn endArray(_: Self, w: Writer) Writer.Error!void { try w.writeAll("]"); } fn beginArrayValue(_: Self, w: Writer, first: bool) Writer.Error!void { if (!first) try w.writeAll(","); } fn endArrayValue(_: Self, _: Writer) Writer.Error!void {} fn beginObject(_: Self, w: Writer) Writer.Error!void { try w.writeAll("{"); } fn endObject(_: Self, w: Writer) Writer.Error!void { try w.writeAll("}"); } fn beginObjectKey(_: Self, w: Writer, first: bool) Writer.Error!void { if (!first) try w.writeAll(","); } fn endObjectKey(_: Self, _: Writer) Writer.Error!void {} fn beginObjectValue(_: Self, w: Writer) Writer.Error!void { try w.writeAll(":"); } fn endObjectValue(_: Self, _: Writer) Writer.Error!void {} fn writeRawFragment(_: Self, w: Writer, v: []const u8) Writer.Error!void { try w.writeAll(v); } }; }
https://raw.githubusercontent.com/getty-zig/json/11946ff9d2f159cb06aaf423ce13bd8aa2a481e7/src/ser/impl/formatter/compact.zig
export fn foo() void {} // obj
https://raw.githubusercontent.com/ziglang/zig/d9bd34fd0533295044ffb4160da41f7873aff905/doc/langref/export_builtin_equivalent_code.zig
const std = @import("std"); const flecs = @import("flecs"); const q = flecs.queries; pub const Velocity = struct { x: f32, y: f32 }; pub const Position = struct { x: f32, y: f32 }; pub const Acceleration = struct { x: f32, y: f32 }; pub fn main() !void { var world = flecs.World.init(); defer world.deinit(); world.newWrappedRunSystem("MoveWrap", .on_update, ComponentData, moveWrapped); world.newWrappedRunSystem("Move2Wrap", .on_update, ComponentData, move2Wrapped); world.newWrappedRunSystem("AccelWrap", .on_update, AccelComponentData, accelWrapped); const entity1 = world.newEntity(); entity1.setName("MyEntityYo"); const entity2 = world.newEntityWithName("MyEntity2"); const entity3 = world.newEntityWithName("HasAccel"); const entity4 = world.newEntityWithName("HasNoVel"); entity1.set(Position{ .x = 0, .y = 0 }); entity1.set(Velocity{ .x = 0.1, .y = 0.1 }); entity2.set(Position{ .x = 2, .y = 2 }); entity2.set(Velocity{ .x = 0.2, .y = 0.2 }); entity3.set(Position{ .x = 3, .y = 3 }); entity3.set(Velocity{ .x = 0.3, .y = 0.3 }); entity3.set(Acceleration{ .x = 1.2, .y = 1.2 }); entity4.set(Position{ .x = 4, .y = 4 }); entity4.set(Acceleration{ .x = 1.2, .y = 1.2 }); std.debug.print("tick\n", .{}); world.progress(0); std.debug.print("tick\n", .{}); world.progress(0); // open the web explorer at https://www.flecs.dev/explorer/?remote=true _ = flecs.c.ecs_app_run(world.world, &std.mem.zeroInit(flecs.c.ecs_app_desc_t, .{ .target_fps = 1, .delta_time = 1, .threads = 8, .enable_rest = true, })); } const ComponentData = struct { pos: *Position, vel: *Velocity }; const AccelComponentData = struct { pos: *Position, vel: *Velocity, accel: *Acceleration }; fn moveWrapped(iter: *flecs.Iterator(ComponentData)) void { while (iter.next()) |e| { std.debug.print("Move wrapped: p: {d}, v: {d} - {s}\n", .{ e.pos, e.vel, iter.entity().getName() }); } } fn move2Wrapped(iter: *flecs.Iterator(ComponentData)) void { while (iter.next()) |e| { std.debug.print("Move2 wrapped: p: {d}, v: {d} - {s}\n", .{ e.pos, e.vel, iter.entity().getName() }); } } fn accelWrapped(iter: *flecs.Iterator(AccelComponentData)) void { while (iter.next()) |e| { std.debug.print("Accel wrapped: p: {d}, v: {d} - {s}\n", .{ e.pos, e.vel, iter.entity().getName() }); } }
https://raw.githubusercontent.com/prime31/zig-flecs/1350d78d00dd6528b2d645a1e7275e1b6390a288/examples/systems.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 builtin = @import("builtin"); const assert = std.debug.assert; const testing = std.testing; const mem = std.mem; const Loop = std.event.Loop; /// Thread-safe async/await lock. /// Functions which are waiting for the lock are suspended, and /// are resumed when the lock is released, in order. /// Many readers can hold the lock at the same time; however locking for writing is exclusive. /// When a read lock is held, it will not be released until the reader queue is empty. /// When a write lock is held, it will not be released until the writer queue is empty. /// TODO: make this API also work in blocking I/O mode pub const RwLock = struct { shared_state: State, writer_queue: Queue, reader_queue: Queue, writer_queue_empty: bool, reader_queue_empty: bool, reader_lock_count: usize, const State = enum(u8) { Unlocked, WriteLock, ReadLock, }; const Queue = std.atomic.Queue(anyframe); const global_event_loop = Loop.instance orelse @compileError("std.event.RwLock currently only works with event-based I/O"); pub const HeldRead = struct { lock: *RwLock, pub fn release(self: HeldRead) void { // If other readers still hold the lock, we're done. if (@atomicRmw(usize, &self.lock.reader_lock_count, .Sub, 1, .SeqCst) != 1) { return; } @atomicStore(bool, &self.lock.reader_queue_empty, true, .SeqCst); if (@cmpxchgStrong(State, &self.lock.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) { // Didn't unlock. Someone else's problem. return; } self.lock.commonPostUnlock(); } }; pub const HeldWrite = struct { lock: *RwLock, pub fn release(self: HeldWrite) void { // See if we can leave it locked for writing, and pass the lock to the next writer // in the queue to grab the lock. if (self.lock.writer_queue.get()) |node| { global_event_loop.onNextTick(node); return; } // We need to release the write lock. Check if any readers are waiting to grab the lock. if (!@atomicLoad(bool, &self.lock.reader_queue_empty, .SeqCst)) { // Switch to a read lock. @atomicStore(State, &self.lock.shared_state, .ReadLock, .SeqCst); while (self.lock.reader_queue.get()) |node| { global_event_loop.onNextTick(node); } return; } @atomicStore(bool, &self.lock.writer_queue_empty, true, .SeqCst); @atomicStore(State, &self.lock.shared_state, .Unlocked, .SeqCst); self.lock.commonPostUnlock(); } }; pub fn init() RwLock { return .{ .shared_state = .Unlocked, .writer_queue = Queue.init(), .writer_queue_empty = true, .reader_queue = Queue.init(), .reader_queue_empty = true, .reader_lock_count = 0, }; } /// Must be called when not locked. Not thread safe. /// All calls to acquire() and release() must complete before calling deinit(). pub fn deinit(self: *RwLock) void { assert(self.shared_state == .Unlocked); while (self.writer_queue.get()) |node| resume node.data; while (self.reader_queue.get()) |node| resume node.data; } pub fn acquireRead(self: *RwLock) callconv(.Async) HeldRead { _ = @atomicRmw(usize, &self.reader_lock_count, .Add, 1, .SeqCst); suspend { var my_tick_node = Loop.NextTickNode{ .data = @frame(), .prev = undefined, .next = undefined, }; self.reader_queue.put(&my_tick_node); // At this point, we are in the reader_queue, so we might have already been resumed. // We set this bit so that later we can rely on the fact, that if reader_queue_empty == true, // some actor will attempt to grab the lock. @atomicStore(bool, &self.reader_queue_empty, false, .SeqCst); // Here we don't care if we are the one to do the locking or if it was already locked for reading. const have_read_lock = if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst)) |old_state| old_state == .ReadLock else true; if (have_read_lock) { // Give out all the read locks. if (self.reader_queue.get()) |first_node| { while (self.reader_queue.get()) |node| { global_event_loop.onNextTick(node); } resume first_node.data; } } } return HeldRead{ .lock = self }; } pub fn acquireWrite(self: *RwLock) callconv(.Async) HeldWrite { suspend { var my_tick_node = Loop.NextTickNode{ .data = @frame(), .prev = undefined, .next = undefined, }; self.writer_queue.put(&my_tick_node); // At this point, we are in the writer_queue, so we might have already been resumed. // We set this bit so that later we can rely on the fact, that if writer_queue_empty == true, // some actor will attempt to grab the lock. @atomicStore(bool, &self.writer_queue_empty, false, .SeqCst); // Here we must be the one to acquire the write lock. It cannot already be locked. if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) == null) { // We now have a write lock. if (self.writer_queue.get()) |node| { // Whether this node is us or someone else, we tail resume it. resume node.data; } } } return HeldWrite{ .lock = self }; } fn commonPostUnlock(self: *RwLock) void { while (true) { // There might be a writer_queue item or a reader_queue item // If we check and both are empty, we can be done, because the other actors will try to // obtain the lock. // But if there's a writer_queue item or a reader_queue item, // we are the actor which must loop and attempt to grab the lock again. if (!@atomicLoad(bool, &self.writer_queue_empty, .SeqCst)) { if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .WriteLock, .SeqCst, .SeqCst) != null) { // We did not obtain the lock. Great, the queues are someone else's problem. return; } // If there's an item in the writer queue, give them the lock, and we're done. if (self.writer_queue.get()) |node| { global_event_loop.onNextTick(node); return; } // Release the lock again. @atomicStore(bool, &self.writer_queue_empty, true, .SeqCst); @atomicStore(State, &self.shared_state, .Unlocked, .SeqCst); continue; } if (!@atomicLoad(bool, &self.reader_queue_empty, .SeqCst)) { if (@cmpxchgStrong(State, &self.shared_state, .Unlocked, .ReadLock, .SeqCst, .SeqCst) != null) { // We did not obtain the lock. Great, the queues are someone else's problem. return; } // If there are any items in the reader queue, give out all the reader locks, and we're done. if (self.reader_queue.get()) |first_node| { global_event_loop.onNextTick(first_node); while (self.reader_queue.get()) |node| { global_event_loop.onNextTick(node); } return; } // Release the lock again. @atomicStore(bool, &self.reader_queue_empty, true, .SeqCst); if (@cmpxchgStrong(State, &self.shared_state, .ReadLock, .Unlocked, .SeqCst, .SeqCst) != null) { // Didn't unlock. Someone else's problem. return; } continue; } return; } } }; test "std.event.RwLock" { // https://github.com/ziglang/zig/issues/2377 if (true) return error.SkipZigTest; // https://github.com/ziglang/zig/issues/1908 if (builtin.single_threaded) return error.SkipZigTest; // TODO provide a way to run tests in evented I/O mode if (!std.io.is_async) return error.SkipZigTest; var lock = RwLock.init(); defer lock.deinit(); const handle = testLock(std.heap.page_allocator, &lock); const expected_result = [1]i32{shared_it_count * @intCast(i32, shared_test_data.len)} ** shared_test_data.len; testing.expectEqualSlices(i32, expected_result, shared_test_data); } fn testLock(allocator: *Allocator, lock: *RwLock) callconv(.Async) void { var read_nodes: [100]Loop.NextTickNode = undefined; for (read_nodes) |*read_node| { const frame = allocator.create(@Frame(readRunner)) catch @panic("memory"); read_node.data = frame; frame.* = async readRunner(lock); Loop.instance.?.onNextTick(read_node); } var write_nodes: [shared_it_count]Loop.NextTickNode = undefined; for (write_nodes) |*write_node| { const frame = allocator.create(@Frame(writeRunner)) catch @panic("memory"); write_node.data = frame; frame.* = async writeRunner(lock); Loop.instance.?.onNextTick(write_node); } for (write_nodes) |*write_node| { const casted = @ptrCast(*const @Frame(writeRunner), write_node.data); await casted; allocator.destroy(casted); } for (read_nodes) |*read_node| { const casted = @ptrCast(*const @Frame(readRunner), read_node.data); await casted; allocator.destroy(casted); } } const shared_it_count = 10; var shared_test_data = [1]i32{0} ** 10; var shared_test_index: usize = 0; var shared_count: usize = 0; fn writeRunner(lock: *RwLock) callconv(.Async) void { suspend {} // resumed by onNextTick var i: usize = 0; while (i < shared_test_data.len) : (i += 1) { std.time.sleep(100 * std.time.microsecond); const lock_promise = async lock.acquireWrite(); const handle = await lock_promise; defer handle.release(); shared_count += 1; while (shared_test_index < shared_test_data.len) : (shared_test_index += 1) { shared_test_data[shared_test_index] = shared_test_data[shared_test_index] + 1; } shared_test_index = 0; } } fn readRunner(lock: *RwLock) callconv(.Async) void { suspend {} // resumed by onNextTick std.time.sleep(1); var i: usize = 0; while (i < shared_test_data.len) : (i += 1) { const lock_promise = async lock.acquireRead(); const handle = await lock_promise; defer handle.release(); testing.expect(shared_test_index == 0); testing.expect(shared_test_data[i] == @intCast(i32, shared_count)); } }
https://raw.githubusercontent.com/dip-proto/zig/8f79f7e60937481fcf861c2941db02cbf449cdca/lib/std/event/rwlock.zig
const std = @import("std"); const main = @import("root"); const graphics = main.graphics; const draw = graphics.draw; const Shader = graphics.Shader; const TextBuffer = graphics.TextBuffer; const Texture = graphics.Texture; const vec = main.vec; const Vec2f = vec.Vec2f; const gui = @import("../gui.zig"); const GuiComponent = gui.GuiComponent; const Icon = GuiComponent.Icon; const Label = GuiComponent.Label; const Button = @This(); const border: f32 = 3; const fontSize: f32 = 16; const Textures = struct { texture: Texture, outlineTexture: Texture, outlineTextureSize: Vec2f, pub fn init(basePath: []const u8) Textures { var self: Textures = undefined; const buttonPath = std.fmt.allocPrint(main.stackAllocator.allocator, "{s}.png", .{basePath}) catch unreachable; defer main.stackAllocator.free(buttonPath); self.texture = Texture.initFromFile(buttonPath); const outlinePath = std.fmt.allocPrint(main.stackAllocator.allocator, "{s}_outline.png", .{basePath}) catch unreachable; defer main.stackAllocator.free(outlinePath); self.outlineTexture = Texture.initFromFile(outlinePath); self.outlineTextureSize = @floatFromInt(self.outlineTexture.size()); return self; } pub fn deinit(self: Textures) void { self.texture.deinit(); self.outlineTexture.deinit(); } }; var normalTextures: Textures = undefined; var hoveredTextures: Textures = undefined; var pressedTextures: Textures = undefined; pub var shader: Shader = undefined; pub var buttonUniforms: struct { screen: c_int, start: c_int, size: c_int, color: c_int, scale: c_int, image: c_int, } = undefined; pos: Vec2f, size: Vec2f, pressed: bool = false, hovered: bool = false, onAction: gui.Callback, child: GuiComponent, pub fn __init() void { shader = Shader.initAndGetUniforms("assets/cubyz/shaders/ui/button.vs", "assets/cubyz/shaders/ui/button.fs", &buttonUniforms); shader.bind(); graphics.c.glUniform1i(buttonUniforms.image, 0); normalTextures = Textures.init("assets/cubyz/ui/button"); hoveredTextures = Textures.init("assets/cubyz/ui/button_hovered"); pressedTextures = Textures.init("assets/cubyz/ui/button_pressed"); } pub fn __deinit() void { shader.deinit(); normalTextures.deinit(); hoveredTextures.deinit(); pressedTextures.deinit(); } fn defaultOnAction(_: usize) void {} pub fn initText(pos: Vec2f, width: f32, text: []const u8, onAction: gui.Callback) *Button { const label = Label.init(undefined, width - 3*border, text, .center); const self = main.globalAllocator.create(Button); self.* = Button { .pos = pos, .size = Vec2f{width, label.size[1] + 3*border}, .onAction = onAction, .child = label.toComponent(), }; return self; } pub fn initIcon(pos: Vec2f, iconSize: Vec2f, iconTexture: Texture, hasShadow: bool, onAction: gui.Callback) *Button { const icon = Icon.init(undefined, iconSize, iconTexture, hasShadow); const self = main.globalAllocator.create(Button); self.* = Button { .pos = pos, .size = icon.size + @as(Vec2f, @splat(3*border)), .onAction = onAction, .child = icon.toComponent(), }; return self; } pub fn deinit(self: *const Button) void { self.child.deinit(); main.globalAllocator.destroy(self); } pub fn toComponent(self: *Button) GuiComponent { return GuiComponent { .button = self }; } pub fn updateHovered(self: *Button, _: Vec2f) void { self.hovered = true; } pub fn mainButtonPressed(self: *Button, _: Vec2f) void { self.pressed = true; } pub fn mainButtonReleased(self: *Button, mousePosition: Vec2f) void { if(self.pressed) { self.pressed = false; if(GuiComponent.contains(self.pos, self.size, mousePosition)) { self.onAction.run(); } } } pub fn render(self: *Button, mousePosition: Vec2f) void { const textures = if(self.pressed) pressedTextures else if(GuiComponent.contains(self.pos, self.size, mousePosition) and self.hovered) hoveredTextures else normalTextures; draw.setColor(0xff000000); textures.texture.bindTo(0); shader.bind(); self.hovered = false; draw.customShadedRect(buttonUniforms, self.pos + Vec2f{2, 2}, self.size - Vec2f{4, 4}); { // Draw the outline using the 9-slice texture. const cornerSize = (textures.outlineTextureSize - Vec2f{1, 1}); const cornerSizeUV = (textures.outlineTextureSize - Vec2f{1, 1})/Vec2f{2, 2}/textures.outlineTextureSize; const lowerTexture = (textures.outlineTextureSize - Vec2f{1, 1})/Vec2f{2, 2}/textures.outlineTextureSize; const upperTexture = (textures.outlineTextureSize + Vec2f{1, 1})/Vec2f{2, 2}/textures.outlineTextureSize; textures.outlineTexture.bindTo(0); draw.setColor(0xffffffff); // Corners: graphics.draw.boundSubImage(self.pos + Vec2f{0, 0}, cornerSize, .{0, 0}, cornerSizeUV); graphics.draw.boundSubImage(self.pos + Vec2f{self.size[0], 0} - Vec2f{cornerSize[0], 0}, cornerSize, .{upperTexture[0], 0}, cornerSizeUV); graphics.draw.boundSubImage(self.pos + Vec2f{0, self.size[1]} - Vec2f{0, cornerSize[1]}, cornerSize, .{0, upperTexture[1]}, cornerSizeUV); graphics.draw.boundSubImage(self.pos + self.size - cornerSize, cornerSize, upperTexture, cornerSizeUV); // Edges: graphics.draw.boundSubImage(self.pos + Vec2f{cornerSize[0], 0}, Vec2f{self.size[0] - 2*cornerSize[0], cornerSize[1]}, .{lowerTexture[0], 0}, .{upperTexture[0] - lowerTexture[0], cornerSizeUV[1]}); graphics.draw.boundSubImage(self.pos + Vec2f{cornerSize[0], self.size[1] - cornerSize[1]}, Vec2f{self.size[0] - 2*cornerSize[0], cornerSize[1]}, .{lowerTexture[0], upperTexture[1]}, .{upperTexture[0] - lowerTexture[0], cornerSizeUV[1]}); graphics.draw.boundSubImage(self.pos + Vec2f{0, cornerSize[1]}, Vec2f{cornerSize[0], self.size[1] - 2*cornerSize[1]}, .{0, lowerTexture[1]}, .{cornerSizeUV[0], upperTexture[1] - lowerTexture[1]}); graphics.draw.boundSubImage(self.pos + Vec2f{self.size[0] - cornerSize[0], cornerSize[1]}, Vec2f{cornerSize[0], self.size[1] - 2*cornerSize[1]}, .{upperTexture[0], lowerTexture[1]}, .{cornerSizeUV[0], upperTexture[1] - lowerTexture[1]}); } const textPos = self.pos + self.size/@as(Vec2f, @splat(2.0)) - self.child.size()/@as(Vec2f, @splat(2.0)); self.child.mutPos().* = textPos; self.child.render(mousePosition - self.pos); }
https://raw.githubusercontent.com/PixelGuys/Cubyz/df0e809845a161678d91f4e5e0dcd24e67c4b6c0/src/gui/components/Button.zig
const base = @import("base"); const math = base.math; const Vec4f = math.Vec4f; pub const Result = struct { reflection: Vec4f, pub fn init(reflection: Vec4f, p: f32) Result { return .{ .reflection = .{ reflection[0], reflection[1], reflection[2], p } }; } pub fn empty() Result { return .{ .reflection = @splat(0.0) }; } pub fn pdf(self: Result) f32 { return self.reflection[3]; } pub fn setPdf(self: *Result, p: f32) void { self.reflection[3] = p; } pub fn mulAssignPdf(self: *Result, p: f32) void { self.reflection[3] *= p; } }; pub const Sample = struct { pub const Class = packed struct { reflection: bool = false, transmission: bool = false, diffuse: bool = false, glossy: bool = false, specular: bool = false, straight: bool = false, }; reflection: Vec4f, wi: Vec4f, pdf: f32, split_weight: f32, wavelength: f32, class: Class, }; pub const Samples = [2]Sample;
https://raw.githubusercontent.com/Opioid/zyg/d8eacc469020972fd11eb5c6c21ce5115d943581/src/core/scene/material/bxdf.zig
const std = @import("std"); const builtin = @import("builtin"); // A tiny circular buffer to store queries we are interested in receiving the replies from. // Also tracks the current sequence id, so ignoreEvent must be called for every request. pub const ReplyBuffer = struct { const ReplyEvent = struct { seq: u32, id: u32, }; // The size of this buffer sets a hard cap on the amount of in-flight events we can // keep track of at the same time. Note that this does not include events we don't // care about the response from, or we don't need to know exactly what triggered the // event to be able to handle properly. mem: [8]ReplyEvent = undefined, tail: u8 = 0, head: u8 = 0, seq_next: u32 = 1, pub fn len(self: *ReplyBuffer) usize { var hp: usize = self.head; if (self.head < self.tail) hp += self.mem.len; return hp - self.tail; } pub fn push(self: *ReplyBuffer, id: u32) !void { if (self.len() == self.mem.len - 1) return error.OutOfMemory; self.mem[self.head] = .{ .id = id, .seq = self.seq_next }; self.seq_next += 1; self.head = @intCast(u8, (self.head + 1) % self.mem.len); } pub fn ignoreEvent(self: *ReplyBuffer) void { self.seq_next += 1; } pub fn get(self: *ReplyBuffer, seq: u32) ?u32 { while (self.len() > 0) { const tailp = self.tail; const ev = self.mem[tailp]; if (ev.seq < seq) { unreachable; } else if (ev.seq == seq) { self.tail = @intCast(u8, (self.tail + 1) % self.mem.len); return ev.id; } else { return null; } } return null; } };
https://raw.githubusercontent.com/Aransentin/zigwin/4df40163aad0eb52be6b150ff6add668a1348bb2/src/x11/replybuffer.zig
const std = @import("std"); const math = std.math; const print = std.debug.print; const Complex = std.math.Complex; const isSignedInt = std.meta.trait.isSignedInt; const Allocator = std.mem.Allocator; const ValueType = @import("type_helpers").ValueType; // Conjugate Pair Lookup Table ---------------------------------------- pub const CP = struct { pub fn input_lut_init(comptime T: type, N: T, input_lut: [*]T) void { const log2_N: T = math.log2(N); const r = @bitSizeOf(T) - log2_N; const val_to_shift: T = math.shl(T, 1, @bitSizeOf(T) - 3); var p: T = 0; var q: T = 0; var h: T = 0; var hn: T = 0; while (h < N) : (h = hn) { // eval binary carry sequency hn = h + 2; var c: T = @bitSizeOf(T) - 2 - @clz(h ^ hn); // input indices var i_0: T = math.shr(T, (p -% q), r); input_lut[h / 2] = i_0; // advance to next input index var m2: T = math.shr(T, val_to_shift, c); var m1: T = m2 - 1; var m: T = p & m2; q = (q & m1) | m; p = (p & m1) | ((m ^ m2) << 1); } } }; // Split Radix Lookup Table ---------------------------------------- pub const SR = struct { pub fn input_lut_init(comptime T: type, N: T, input_lut: [*]T) void { const log2_N: T = math.log2(N); lut_dr(T, log2_N, 0, log2_N, 0, input_lut); } pub fn lut_dr(comptime T: type, log2_N: T, out: T, l: T, i: T, input_lut: [*]T) void { var is: T = math.shl(T, 1, log2_N - l); var os: T = math.shl(T, 1, l -% 2); switch (l) { 1 => { input_lut[out / 2] = i; }, 2 => { lut_dr(T, log2_N, out, 1, i, input_lut); input_lut[1 + out / 2] = i + is; }, else => { lut_dr(T, log2_N, out, l - 1, i, input_lut); lut_dr(T, log2_N, out + os * 2, l - 2, i + is, input_lut); lut_dr(T, log2_N, out + 3 * os, l - 2, i + 3 * is, input_lut); }, } } pub fn jacobsthal(n: anytype) @TypeOf(n) { comptime var T = @TypeOf(n); if (comptime isSignedInt(T)) { @compileError("accepts only unsigned integer types"); } // returns the n-th jacobsthal number using closed-for equation // J(n) = (2^n - (-1)^n) / 3 if (n & 1 == 1) { return ((math.shl(T, 1, n) + 1) / 3); } else { return ((math.shl(T, 1, n) - 1) / 3); } } // NOTE: do the allocations for sr_sched_cnt, and sr_sched_off elsewhere pub fn sched_lut_init(comptime T: type, N: T, sched_cnt: [*]T, sched_off: [*]T) void { const log2_N: T = math.log2(N); var i: T = 0; while (i < log2_N) : (i += 1) { sched_cnt[i] = jacobsthal(log2_N - i); } i = 0; var j: T = 0; while (j < sched_cnt[0]) : (i += 1) { if ((@clz(i ^ (i + 1)) & 1) == 1) { sched_off[j] = i; j += 1; } } sched_off[j] = N; } };
https://raw.githubusercontent.com/BlueAlmost/zfft-orchard/b83445ab809b26e5e5dfd3092a2d695355cab02a/src/LUT.zig
// code taken from here: https://zig.news/kilianvounckx/zig-interfaces-for-the-uninitiated-an-update-4gf1 const std = @import("std"); const Iterator = struct { const Self = @This(); ptr: *anyopaque, nextFn: fn (*anyopaque) ?u32, pub fn init(ptr: anytype) Self { const Ptr = @TypeOf(ptr); const ptr_info = @typeInfo(Ptr); if (ptr_info != .Pointer) @compileError("ptr must be a pointer"); if (ptr_info.Pointer.size != .One) @compileError("ptr must be a single item pointer"); const gen = struct { pub fn nextImpl(pointer: *anyopaque) ?u32 { const self = @as(Ptr, @ptrCast(@alignCast(pointer))); return @call(.{ .modifier = .always_inline }, ptr_info.Pointer.child.next, .{self}); } }; return .{ .ptr = ptr, .nextFn = gen.nextImpl, }; } }; const Range = struct { const Self = @This(); start: u32 = 0, end: u32, step: u32 = 1, pub fn next(self: *Self) ?u32 { if (self.start >= self.end) return null; const result = self.start; self.start += self.step; return result; } pub fn iterator(self: *Self) Iterator { return Iterator.init(self); } }; pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); } test "Range" { var range = Range{ .end = 5 }; const iter = range.iterator(); try std.testing.expectEqual(@as(?u32, 0), iter.next()); try std.testing.expectEqual(@as(?u32, 1), iter.next()); try std.testing.expectEqual(@as(?u32, 2), iter.next()); try std.testing.expectEqual(@as(?u32, 3), iter.next()); try std.testing.expectEqual(@as(?u32, 4), iter.next()); try std.testing.expectEqual(@as(?u32, null), iter.next()); try std.testing.expectEqual(@as(?u32, null), iter.next()); }
https://raw.githubusercontent.com/lhk/zig_runtime_polymorphism/b854f616ebc86b5f675b2612c7da522ce1b4b757/src/blogpost.zig
const std = @import("std"); const slotmap = @import("slotmap"); const Key = slotmap.Key; const SlotMap = slotmap.SlotMap; const SecondaryMap = slotmap.SecondaryMap; const print = std.debug.print; pub fn main() void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); var users = SlotMap(u64).new(&arena.allocator); var names = SecondaryMap([]const u8).new(&arena.allocator); const user1 = users.insert(1000); names.insert(user1, "Michael"); const user2 = users.insert(1001); names.insert(user2, "Christine"); var iterator = users.iter(); while (iterator.next()) |user| { if (names.get(user.key)) |name| { print("Found user {} whose name is {s}\n", .{user.value.*, name.*}); } } }
https://raw.githubusercontent.com/mmstick/zig-slotmap/3e67e6a79c325388b9377c762ef9b47b4c11ef0f/examples/secondary.zig
const std = @import("std"); const rg = @import("../../renderer/render_graph/render_graph.zig"); const application = @import("../../application/application.zig"); const Config = @import("../../application/config.zig").Config; const DefaultRenderer = @import("../../renderer/default_renderer.zig").DefaultRenderer; const System = @import("../../system/system.zig").System; const ToolUI = @import("../tool_ui.zig").ToolUI; const MeshViewerWindow = @import("mesh_viewer_window.zig").MeshViewerWindow; fn setDefaultSettings() void { var config: *Config = application.app.config; config.putBool("swapchain_vsync", true); } pub fn main() !void { const allocator: std.mem.Allocator = std.testing.allocator; var renderer: DefaultRenderer = undefined; renderer.init("Main Renderer", allocator); var tool_ui: ToolUI = undefined; tool_ui.init(allocator); defer tool_ui.deinit(); var window: MeshViewerWindow = undefined; window.init("Mesh Viewer", allocator, &tool_ui.ui.rg_pass); tool_ui.windows.append(&window.window) catch unreachable; try rg.global_render_graph.passes.append(&tool_ui.ui.rg_pass); const systems: []*System = &[_]*System{ &renderer.system, &tool_ui.ui.system, }; application.initGlobalData(allocator); defer application.deinitGlobalData(); const app: *application.Application = &application.app; app.init("Nyancore Mesh Viewer", allocator, systems); defer app.deinit(); setDefaultSettings(); try app.initSystems(); defer app.deinitSystems(); try app.mainLoop(); }
https://raw.githubusercontent.com/Black-Cat/nyancore/257e111e77dfa8288e0d14a9055a137b3113f1c8/src/tools/mesh_viewer/main.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-interpreter", // 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/OfflineBrain/monkey-zig-interpreter/2750c4079729aeb77733a16815f2c422ea4a984f/build.zig
pub const stm32f407vet6 = @import("stm32f407vet6.zig"); pub const stm32f429bit6 = @import("stm32f429bit6.zig"); pub const stm32l475vet6 = @import("stm32l475vet6.zig"); pub const stm32mp157x = @import("stm32mp157x.zig"); // "not good smell" pub const reg = @import("reg/reg.zig");
https://raw.githubusercontent.com/octopus-os-org/octopus/9611e81199a624f5815be0b842b99eb3e3e29695/octopus/chip/st/st.zig
const pad = @import("assets.zig").padding; const rotate_speed = @import("settings.zig").rotate_speed; const std = @import("std"); const map = @import("map.zig"); const math = @import("std").math; const utils = @import("utils.zig"); pub const px_per_tile: i16 = 50; //88; pub const size_mult: f32 = 5.0; //8.0; pub var x = std.atomic.Value(f32).init(0.0); pub var y = std.atomic.Value(f32).init(0.0); pub var z = std.atomic.Value(f32).init(0.0); pub var minimap_zoom: f32 = 4.0; pub var quake = false; pub var quake_amount: f32 = 0.0; pub var cos: f32 = 0.0; pub var sin: f32 = 0.0; pub var clip_x: f32 = 0.0; pub var clip_y: f32 = 0.0; pub var angle: f32 = 0.0; pub var min_x: u32 = 0; pub var min_y: u32 = 0; pub var max_x: u32 = 0; pub var max_y: u32 = 0; pub var max_dist_sq: f32 = 0.0; pub var screen_width: f32 = 1280.0; pub var screen_height: f32 = 720.0; pub var clip_scale_x: f32 = 2.0 / 1280.0; pub var clip_scale_y: f32 = 2.0 / 720.0; pub var scale: f32 = 1.0; pub fn update(target_x: f32, target_y: f32, dt: f32, rotate: i8) void { var tx: f32 = target_x; var ty: f32 = target_y; if (quake) { const max_quake = 0.5; const quake_buildup_ms = 10000; quake_amount += dt * max_quake / quake_buildup_ms; if (quake_amount > max_quake) quake_amount = max_quake; tx += utils.plusMinus(quake_amount); ty += utils.plusMinus(quake_amount); } x.store(tx, .Release); y.store(ty, .Release); if (rotate != 0) { const float_rotate: f32 = @floatFromInt(rotate); angle = @mod(angle + dt * rotate_speed * float_rotate, math.tau); } const cos_angle = @cos(angle); const sin_angle = @sin(angle); cos = cos_angle * px_per_tile * scale; sin = sin_angle * px_per_tile * scale; clip_x = (tx * cos_angle + ty * sin_angle) * -px_per_tile * scale; clip_y = (tx * -sin_angle + ty * cos_angle) * -px_per_tile * scale; const w_half = screen_width / (2 * px_per_tile * scale); const h_half = screen_height / (2 * px_per_tile * scale); max_dist_sq = w_half * w_half + h_half * h_half; const max_dist = @ceil(@sqrt(max_dist_sq)); const min_x_dt = tx - max_dist; min_x = if (min_x_dt < 0) 0 else @intFromFloat(min_x_dt); min_x = @max(0, min_x); max_x = @intFromFloat(tx + max_dist); max_x = @min(map.width - 1, max_x); const min_y_dt = ty - max_dist; min_y = if (min_y_dt < 0) 0 else @intFromFloat(min_y_dt); min_y = @max(0, min_y); max_y = @intFromFloat(ty + max_dist); max_y = @min(map.height - 1, max_y); } pub inline fn rotateAroundCameraClip(x_in: f32, y_in: f32) utils.Point { return utils.Point{ .x = x_in * cos + y_in * sin + clip_x, .y = x_in * -sin + y_in * cos + clip_y, }; } pub inline fn rotateAroundCamera(x_in: f32, y_in: f32) utils.Point { return utils.Point{ .x = x_in * cos + y_in * sin + clip_x + screen_width / 2.0, .y = x_in * -sin + y_in * cos + clip_y + screen_height / 2.0, }; } pub inline fn visibleInCamera(x_in: f32, y_in: f32) bool { if (x_in < 0 or y_in < 0) return false; const floor_x: u32 = @intFromFloat(@floor(x_in)); const floor_y: u32 = @intFromFloat(@floor(y_in)); return !(floor_x < min_x or floor_x > max_x or floor_y < min_y or floor_y > max_y); } pub fn screenToWorld(x_in: f32, y_in: f32) utils.Point { const cos_angle = @cos(angle); const sin_angle = @sin(angle); const x_div = (x_in - screen_width / 2.0) / px_per_tile * scale; const y_div = (y_in - screen_height / 2.0) / px_per_tile * scale; return utils.Point{ .x = x.load(.Acquire) + x_div * cos_angle - y_div * sin_angle, .y = y.load(.Acquire) + x_div * sin_angle + y_div * cos_angle, }; }
https://raw.githubusercontent.com/Slendergo/zig-client/a2248790993ec2611863e9e1f8ff5b50592c3d11/src/camera.zig
const math = @import("math.zig"); const Transform = @import("Transform.zig"); const GlobalTransform = @This(); translation: math.Vec3 = math.Vec3.ZERO, rotation: math.Quat = math.Quat.IDENTITY, scale: math.Vec3 = math.Vec3.ONE, pub fn transformPoint(self: GlobalTransform, point: math.Vec3) math.Vec3 { var p = self.scale.mul(point); p = self.rotation.inv().mul(p); p = self.translation.add(p); return p; } pub fn transform(self: GlobalTransform, t: Transform) GlobalTransform { const translation = self.transformPoint(t.translation); const rotation = self.rotation.mul(t.rotation); const scale = self.scale.mul(t.scale); return .{ .translation = translation, .rotation = rotation, .scale = scale, }; } pub fn computeMatrix(self: GlobalTransform) math.Mat4 { var matrix = math.Mat4.scale(self.scale); matrix = matrix.mul(self.rotation.asMat4()); matrix = matrix.mul(math.Mat4.translate(self.translation)); return matrix; }
https://raw.githubusercontent.com/Sudoku-Boys/Sudoku/218ea16ecc86507698861b59a496ff178a7a7587/src/engine/GlobalTransform.zig
const std = @import("std"); const SinglyLinkedList = std.SinglyLinkedList; const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; const aoc = @import("aoc"); const expectEqual = aoc.expectEqual; // TODO: refactor the struct to hold a slice pub fn Permutations(comptime T: type) type { return struct { items: []const T, counter: usize, // current iteration counter i: usize, // current stack pointer max: usize, // maximum count of iterations const Self = @This(); pub fn init(items: []const T) Self { return .{ .items = items, .counter = 0, .max = factorial(items.len), }; } pub fn next(self: *Self) void { if (self.counter == 0) { self.counter += 1; return; } else { self.counter += 1; } } }; } inline fn swap(comptime T: type, items: []T, from: usize, to: usize) void { std.debug.assert(from < items.len); std.debug.assert(to < items.len); var temp: T = items[to]; items[to] = items[from]; items[from] = temp; } inline fn copy(comptime T: type, allocator: Allocator, source: []const T) ![]T { var new = try allocator.alloc(T, source.len); std.mem.copy(T, new, source); return new; } pub fn factorial(n: u64) u64 { // TODO: quite a hack, rewrite var result: u64 = 1; var i: usize = 0; while (i < n) : (i += 1) { result *= i; } return result; } test { const allocator = std.testing.allocator; var items: [3]usize = .{ 1, 2, 3 }; var pms = Permutations(usize).init(allocator); defer pms.deinit(); try pms.permute(&items); try std.testing.expectEqualSlices(usize, &[_]usize{ 1, 2, 3 }, &items); // original is unmodified try std.testing.expect(&items != pms.items.items[0].ptr); // original is different from the first array try expectEqual(6, pms.items.items.len); // we have six permutations from three items try std.testing.expectEqualSlices(usize, &[_]usize{ 1, 2, 3 }, pms.items.items[0]); try std.testing.expectEqualSlices(usize, &[_]usize{ 2, 1, 3 }, pms.items.items[1]); try std.testing.expectEqualSlices(usize, &[_]usize{ 3, 1, 2 }, pms.items.items[2]); try std.testing.expectEqualSlices(usize, &[_]usize{ 1, 3, 2 }, pms.items.items[3]); try std.testing.expectEqualSlices(usize, &[_]usize{ 2, 3, 1 }, pms.items.items[4]); try std.testing.expectEqualSlices(usize, &[_]usize{ 3, 2, 1 }, pms.items.items[5]); } // TODO: implement a better method (with generators / iterators) - this takes forever to run. test { const allocator = std.testing.allocator; var pms = Permutations(usize).init(allocator); defer pms.deinit(); try pms.permute(&[_]usize{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); }
https://raw.githubusercontent.com/erplsf/adventofcode/b969bf82b00ff7d2e7e0b1ca6c36a12b5865cff0/zig/src/permute_v2.zig
//https://github.com/dmgk/zig-uuid const std = @import("std"); const crypto = std.crypto; const fmt = std.fmt; const testing = std.testing; const bun = @import("root").bun; pub const Error = error{InvalidUUID}; const UUID = @This(); bytes: [16]u8, pub fn init() UUID { var uuid = UUID{ .bytes = undefined }; bun.rand(&uuid.bytes); // Version 4 uuid.bytes[6] = (uuid.bytes[6] & 0x0f) | 0x40; // Variant 1 uuid.bytes[8] = (uuid.bytes[8] & 0x3f) | 0x80; return uuid; } pub fn initWith(bytes: *const [16]u8) UUID { var uuid = UUID{ .bytes = bytes.* }; uuid.bytes[6] = (uuid.bytes[6] & 0x0f) | 0x40; uuid.bytes[8] = (uuid.bytes[8] & 0x3f) | 0x80; return uuid; } // Indices in the UUID string representation for each byte. const encoded_pos = [16]u8{ 0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34 }; // Hex to nibble mapping. const hex_to_nibble = [256]u8{ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, }; pub fn format( self: UUID, comptime layout: []const u8, options: fmt.FormatOptions, writer: anytype, ) !void { _ = options; // currently unused if (comptime layout.len != 0 and layout[0] != 's') @compileError("Unsupported format specifier for UUID type: '" ++ layout ++ "'."); var buf: [36]u8 = undefined; self.print(&buf); try fmt.format(writer, "{s}", .{buf}); } pub fn print( self: UUID, buf: *[36]u8, ) void { const hex = "0123456789abcdef"; const bytes = self.bytes; buf[8] = '-'; buf[13] = '-'; buf[18] = '-'; buf[23] = '-'; inline for (encoded_pos, 0..) |i, j| { buf[comptime i + 0] = hex[bytes[j] >> 4]; buf[comptime i + 1] = hex[bytes[j] & 0x0f]; } } pub fn parse(buf: []const u8) Error!UUID { var uuid = UUID{ .bytes = undefined }; if (buf.len != 36 or buf[8] != '-' or buf[13] != '-' or buf[18] != '-' or buf[23] != '-') return Error.InvalidUUID; inline for (encoded_pos, 0..) |i, j| { const hi = hex_to_nibble[buf[i + 0]]; const lo = hex_to_nibble[buf[i + 1]]; if (hi == 0xff or lo == 0xff) { return Error.InvalidUUID; } uuid.bytes[j] = hi << 4 | lo; } return uuid; } // Zero UUID pub const zero: UUID = .{ .bytes = .{0} ** 16 }; // Convenience function to return a new v4 UUID. pub fn newV4() UUID { return UUID.init(); }
https://raw.githubusercontent.com/resourcemod/sidejs/2eb853f13a96d6434fe9dba78906a390b1eb90fa/src/js/bun-bun-v1.0.30/src/bun.js/uuid.zig
const scanner = @import("scanner.zig"); const chunk = @import("chunk.zig"); const value = @import("value.zig"); const config = @import("config.zig"); const std = @import("std"); const GPAlloc = std.heap.GeneralPurposeAllocator(.{}); const Token = scanner.Token; const TokenType = scanner.TokenType; const vm = @import("vm.zig"); const Obj = value.Obj; const Value = value.Value; const assert = std.debug.assert; const uSlot = chunk.uSlot; const expect = std.testing.expect; const expectEqual = std.testing.expectEqual; const ParseError = error{ InvalidCharacter, FloatParseError, UnexpectedToken, UnexpectedEOF, ExpectedRightParen, ExpectedMinus, ExpectedMathOp, ExpectedExpression, ExpectedInfix, ExpectedStatement, ExpectedSemicolon, ExpectedEquals, ExpectedIdent, ExpectedParen, OutOfMemory, TooManyLocalVariables, TooManyCompileErrors, LocalAlreadyExists, CannotSetConst, JumpTooBig, } || scanner.ScanError || chunk.ChunkError; pub fn compileAndRunProgram(s: []const u8, a: std.mem.Allocator) !void { var ch = chunk.Chunk.init(a); defer ch.deinit(a); var p: Parser = try Parser.init(s, a, &ch); defer p.deinit(); try p.program(); try ch.addOp(.EXIT); if (config.PRINT_CHUNK) ch.print(std.debug); var theVm = vm.VM.init(&ch, a); defer theVm.deinit(); _ = try theVm.run(); } pub fn compileAndRunExpression(s: []const u8, a: *std.mem.Allocator) !value.Value { var ch = chunk.Chunk.init(a); defer ch.deinit(a); var p: Parser = try Parser.init(s, a, &ch); defer p.deinit(); try p.expression(); try ch.addOp(.RETURN); var theVm = vm.VM.init(&ch, a); defer theVm.deinit(); return try theVm.run(); } const ParseErrorData = struct { err: ParseError, token: Token, pub fn print(self: @This()) void { std.debug.print("Error {} : at {}\n\n", .{ self.err, self.token }); } }; const Local = struct { name: []const u8, depth: ?usize = null, isConst: bool, }; const FoundLocal = struct { slot: uSlot, isC: bool, }; //BOOK - Compiler, Allocator must alway be the same; const Scope = struct { const LList = std.ArrayListUnmanaged(Local); prev: ?*Scope, locals: LList, depth: usize, pub fn init(alloc: std.mem.Allocator) !*@This() { var res: *Scope = try alloc.create(Scope); res.locals = LList{}; res.prev = null; res.depth = 0; return res; } pub fn parent(self: *@This(), alloc: std.mem.Allocator) ?*@This() { var p = self.prev; alloc.destory(self); return p; } pub fn incDepth(self: *@This()) void { self.depth += 1; } pub fn addLocal(self: *@This(), alloc: std.mem.Allocator, name: []const u8, isConst: bool) ParseError!void { var loc = Local{ .name = name, .depth = null, .isConst = isConst, }; try self.locals.append(alloc, loc); } pub fn decDepth(self: *@This()) u8 { var res: u8 = 0; while (self.locals.items.len > 0) : (self.locals.items.len -= 1) { var dp = self.locals.items[self.locals.items.len - 1].depth; if (dp) |d| { if (d < self.depth) { return res; } } res += 1; } return res; } pub fn initDepth(self: *@This()) void { self.locals.items[self.locals.items.len - 1].depth = self.depth; } pub fn deinit(self: *@This(), alloc: std.mem.Allocator) void { if (self.prev) |p| { p.deinit(alloc); } self.locals.deinit(alloc); alloc.destroy(self); } pub fn levelLocalExists(self: *@This(), s: []const u8) bool { if (self.locals.items.len == 0) return false; var i = self.locals.items.len - 1; while (true) : (i -= 1) { var loc = &self.locals.items[i]; if (loc.depth) |dp| { if (dp < self.depth) { return false; } } if (std.mem.eql(u8, loc.name, s)) { std.debug.print("EQL {s} : {s}\n\n", .{ loc.name, s }); return true; } if (i == 0) return false; } } pub fn findLocal(self: *@This(), s: []const u8) ?FoundLocal { if (self.locals.items.len == 0) return null; var i = self.locals.items.len - 1; while (true) : (i -= 1) { if (std.mem.eql(u8, self.locals.items[i].name, s)) { return FoundLocal{ .slot = @intCast(uSlot, i), .isC = self.locals.items[i].isConst }; } if (i == 0) return null; } } }; const Parser = struct { peek: ?Token, scanner: scanner.Tokenizer, chk: *chunk.Chunk, alloc: std.mem.Allocator, errors: std.ArrayList(ParseErrorData), scope: *Scope, pub fn err(self: *@This(), e: ParseError) ParseError { const edata = ParseErrorData{ .err = e, .token = self.takeToken() catch |e3| return e3, }; edata.print(); self.errors.append(edata) catch |e2| return e2; return e; } pub fn init(s: []const u8, alloc: std.mem.Allocator, ch: *chunk.Chunk) !@This() { var sc = scanner.Tokenizer.init(s); return Parser{ .peek = null, .scanner = sc, .chk = ch, .alloc = alloc, .errors = std.ArrayList(ParseErrorData).init(alloc), .scope = try Scope.init(alloc), }; } pub fn deinit(self: @This()) void { self.errors.deinit(); self.scope.deinit(self.alloc); } pub fn peekToken(this: *@This()) ParseError!Token { if (this.peek) |p| { return p; } var nx = this.scanner.nextToken() catch |e| return this.err(e); this.peek = nx; return nx; } pub fn takeToken(this: *@This()) ParseError!Token { if (this.peek) |p| { this.peek = null; return p; } return this.scanner.nextToken() catch |e| return this.err(e); } pub fn consume(self: *@This(), tk: TokenType, e: ParseError) ParseError!void { var nt = try self.takeToken(); if (nt.kind != tk) { return e; } } pub fn tryConsume(self: *@This(), tk: TokenType) bool { var nt = self.peekToken() catch return false; if (nt.kind == tk) { self.peek = null; return true; } return false; } pub fn program(self: *@This()) ParseError!void { var curr = try self.peekToken(); while (curr.kind != .EOF) { self.declaration() catch { try self.endErrLine(); }; curr = try self.peekToken(); } if (self.errors.items.len > 0) { return error.TooManyCompileErrors; } } pub fn endErrLine(self: *@This()) ParseError!void { while (true) { var curr = try self.takeToken(); switch (curr.kind) { .EOF, .SEMICOLON => return, else => {}, } } } pub fn declaration(self: *@This()) ParseError!void { var curr = try self.takeToken(); switch (curr.kind) { .VAR => try self.varDeclaration(false), .CONST => try self.varDeclaration(true), else => { self.peek = curr; try self.statement(); }, } } pub fn statement(self: *@This()) ParseError!void { var curr = try self.takeToken(); switch (curr.kind) { .PRINT => try self.printStatement(), .LEFT_BRACE => { self.scope.incDepth(); try self.block(); var pops = self.scope.decDepth(); while (pops < 0) : (pops -= 1) self.chk.addOp(.POP); }, .IF => { try self.ifStatement(); }, .WHILE => { try self.whileStatement(); }, .FOR => { try self.forStatement(); }, else => { self.peek = curr; try self.expressionStatement(); }, } } pub fn block(self: *@This()) ParseError!void { self.peek = null; while (true) { var curr = try self.peekToken(); switch (curr.kind) { .RIGHT_BRACE => { self.peek = null; return; }, .EOF => return self.err(error.UnexpectedEOF), else => try self.declaration(), } } } pub fn varDeclaration(self: *@This(), isConst: bool) ParseError!void { self.peek = null; const nameTok = try self.takeToken(); if (nameTok.kind != .IDENT) { return self.err(error.ExpectedIdent); } const eqTok = try self.takeToken(); switch (eqTok.kind) { .EQUAL => try self.expression(), .SEMICOLON => { try self.chk.addOp(.NIL); try self.defineVariable(nameTok, isConst); return; }, else => return self.err(ParseError.ExpectedEquals), } try self.consume(.SEMICOLON, error.ExpectedSemicolon); try self.defineVariable(nameTok, isConst); } pub fn defineVariable(self: *@This(), tok: Token, isConst: bool) ParseError!void { const tname = self.scanner.tokenStr(tok); var tval = try Value.fromStr(tname, self.alloc); if (self.scope.depth > 0) { if (self.scope.levelLocalExists(tname)) { return self.err(error.LocalAlreadyExists); } self.scope.addLocal(self.alloc, tname, isConst) catch |e| return self.err(e); self.scope.initDepth(); return; } try self.chk.addConst(.DEFINE_GLOBAL, tval); } pub fn ifStatement(self: *@This()) ParseError!void { try self.consume(.LEFT_PAREN, error.ExpectedParen); try self.expression(); try self.consume(.RIGHT_PAREN, error.ExpectedParen); var thenJump = try self.chk.addJump(.JUMP_IF_FALSE); try self.chk.addOp(.POP); try self.statement(); var elseJump = try self.chk.addJump(.JUMP); try self.chk.patchJump(thenJump); if (self.tryConsume(.ELSE)) { try self.chk.addOp(.POP); try self.statement(); } try self.chk.patchJump(elseJump); } pub fn whileStatement(self: *@This()) ParseError!void { var pos = self.chk.pos(); self.peek = null; try self.consume(.LEFT_PAREN, error.ExpectedParen); try self.expression(); try self.consume(.RIGHT_PAREN, error.ExpectedParen); const exit = try self.chk.addJump(.JUMP_IF_FALSE); try self.statement(); try self.chk.addLoop(pos); try self.chk.patchJump(exit); try self.chk.addOp(.POP); } pub fn forStatement(self: *@This()) ParseError!void { self.peek = null; self.scope.incDepth(); try self.consume(.LEFT_PAREN, error.ExpectedParen); //Initialize var pk = try self.peekToken(); if (pk.kind == .SEMICOLON) { self.peek = null; } else { try self.declaration(); } //Condition var conLoop = self.chk.pos(); pk = try self.peekToken(); if (pk.kind == .SEMICOLON) { try self.chk.addOp(.TRUE); } else { try self.expression(); try self.consume(.SEMICOLON, error.ExpectedSemicolon); } var quitJump = try self.chk.addJump(.JUMP_IF_FALSE); //std.debug.print("CONDITION COMPLETE {}\n", .{self.peekToken()}); //Increment var incLoop = self.chk.pos(); pk = try self.peekToken(); if (pk.kind == .RIGHT_PAREN) { incLoop = conLoop; self.peek = null; } else { const incJump = try self.chk.addJump(.JUMP); incLoop = self.chk.pos(); try self.expression(); try self.chk.addOp(.POP); //std.debug.print("INC EXPRESSION COMPLETE \n", .{}); try self.consume(.RIGHT_PAREN, error.ExpectedParen); //std.debug.print("INC PAREN COMPLETE\n", .{}); try self.chk.addLoop(conLoop); try self.chk.patchJump(incJump); } try self.statement(); try self.chk.addLoop(incLoop); //std.debug.print("INCREMENT COMPLETE\n", .{}); try self.chk.patchJump(quitJump); //exit var pops = self.scope.decDepth(); while (pops < 0) : (pops -= 1) self.chk.addOp(.POP); } pub fn expression(self: *@This()) ParseError!void { try self.parsePrecedence(.ASSIGNMENT); } pub fn expressionStatement(self: *@This()) ParseError!void { try self.expression(); try self.consume(.SEMICOLON, error.ExpectedSemicolon); try self.chk.addOp(.POP); } pub fn printStatement(self: *@This()) ParseError!void { self.peek = null; try self.expression(); // -- find out what next token really is. //var pk = try self.peekToken(); //std.debug.print("{}\n", .{pk}); // -- try self.consume(.SEMICOLON, error.ExpectedSemicolon); try self.chk.addOp(.PRINT); } pub fn parsePrecedence(self: *@This(), prec: Precedence) ParseError!void { var curr = try self.peekToken(); const canAssign = @enumToInt(prec) <= @enumToInt(Precedence.ASSIGNMENT); const preFn: ParseFn = getRule(curr.kind).prefix orelse return self.err(error.ExpectedExpression); try preFn(self, canAssign); curr = try self.peekToken(); while (@enumToInt(prec) <= @enumToInt(getRule(curr.kind).precedence)) { const inFn: ParseFn = getRule(curr.kind).infix orelse return self.err(error.ExpectedInfix); try inFn(self, canAssign); curr = try self.peekToken(); } } pub fn literal(self: *@This(), _: bool) ParseError!void { var curr = try self.takeToken(); switch (curr.kind) { .FALSE => try self.chk.addOp(.FALSE), .TRUE => try self.chk.addOp(.TRUE), .NIL => try self.chk.addOp(.NIL), else => unreachable, } } pub fn grouping(self: *@This(), _: bool) ParseError!void { self.peek = null; try self.expression(); try self.consume(.RIGHT_PAREN, error.ExpectedRightParen); } pub fn unary(self: *@This(), _: bool) ParseError!void { const op = try self.takeToken(); try self.expression(); switch (op.kind) { .MINUS => try self.chk.addOp(.NEGATE), .BANG => try self.chk.addOp(.NOT), else => return self.err(error.ExpectedMinus), } } pub fn binary(self: *@This(), _: bool) ParseError!void { const op = try self.takeToken(); const rule = getRule(op.kind); try self.parsePrecedence(rule.precedence.inc()); switch (op.kind) { .PLUS => try self.chk.addOp(.ADD), .MINUS => try self.chk.addOp(.SUB), .STAR => try self.chk.addOp(.MUL), .SLASH => try self.chk.addOp(.DIV), .EQUAL_EQUAL => try self.chk.addOp(.EQUAL), .LESS => try self.chk.addOp(.LESS), .GREATER => try self.chk.addOp(.GREATER), .BANG_EQUAL => { try self.chk.addOp(.EQUAL); try self.chk.addOp(.NOT); }, .LESS_EQUAL => { try self.chk.addOp(.GREATER); try self.chk.addOp(.NOT); }, .GREATER_EQUAL => { try self.chk.addOp(.LESS); try self.chk.addOp(.NOT); }, else => return self.err(error.ExpectedMathOp), } } pub fn number(self: *@This(), _: bool) ParseError!void { var curr = try self.takeToken(); var s = self.scanner.tokenStr(curr); var val = try std.fmt.parseFloat(f64, s); try self.chk.addConst(.CONSTANT, .{ .NUMBER = val }); } pub fn string(self: *@This(), _: bool) ParseError!void { var curr = try self.takeToken(); var s_orig = self.scanner.tokenStr(curr); //remove quotes var val = try Value.fromStr(s_orig[1 .. s_orig.len - 1], self.alloc); try self.chk.addConst(.CONSTANT, val); } pub fn variable(self: *@This(), canAssign: bool) ParseError!void { try self.namedVariable(canAssign); } pub fn namedVariable(self: *@This(), canAssign: bool) ParseError!void { var curr = try self.takeToken(); assert(curr.kind == .IDENT); var name = self.scanner.tokenStr(curr); var val = try Value.fromStr(name, self.alloc); var eqTok = try self.peekToken(); if (eqTok.kind == .EQUAL and canAssign) { self.peek = null; try self.expression(); if (self.scope.findLocal(name)) |tp| { if (tp.isC) return self.err(error.CannotSetConst); try self.chk.addWithSlot(.SET_LOCAL, tp.slot); } else try self.chk.addConst(.SET_GLOBAL, val); } else { if (self.scope.findLocal(name)) |tp| { try self.chk.addWithSlot(.GET_LOCAL, tp.slot); } else try self.chk.addConst(.GET_GLOBAL, val); } } pub fn and_(self: *@This(), _: bool) ParseError!void { self.peek = null; var off = try self.chk.addJump(.JUMP_IF_FALSE); try self.chk.addOp(.POP); try self.parsePrecedence(.AND); try self.chk.patchJump(off); } pub fn or_(self: *@This(), _: bool) ParseError!void { self.peek = null; var fhop = try self.chk.addJump(.JUMP_IF_FALSE); var true_jump = try self.chk.addJump(.JUMP); try self.chk.patchJump(fhop); try self.chk.addOp(.POP); try self.parsePrecedence(.OR); try self.chk.patchJump(true_jump); } }; const Precedence = enum(u8) { NONE, ASSIGNMENT, // = OR, // or AND, // and EQUALITY, // == != COMPARISON, // < > <= >= TERM, // + - FACTOR, // * / UNARY, // ! - CALL, // . () PRIMARY, fn inc(self: @This()) @This() { if (self == .PRIMARY) return .PRIMARY; return @intToEnum(@This(), @enumToInt(self) + 1); } }; const ParseFn = fn (*Parser, bool) ParseError!void; const ParseRule = struct { prefix: ?ParseFn = null, infix: ?ParseFn = null, precedence: Precedence = .NONE, }; fn getRule(tk: TokenType) ParseRule { return switch (tk) { .LEFT_PAREN => .{ .prefix = Parser.grouping, .infix = null }, .MINUS => .{ .prefix = Parser.unary, .infix = Parser.binary, .precedence = .TERM }, .PLUS => .{ .infix = Parser.binary, .precedence = .TERM }, .STAR, .SLASH => .{ .infix = Parser.binary, .precedence = .FACTOR }, .BANG => .{ .prefix = Parser.unary, .precedence = .NONE }, .NUMBER => .{ .prefix = Parser.number }, .FALSE, .TRUE, .NIL => .{ .prefix = Parser.literal, .precedence = .NONE }, .GREATER, .LESS, .LESS_EQUAL, .GREATER_EQUAL => .{ .infix = Parser.binary, .precedence = .COMPARISON }, .EQUAL_EQUAL => .{ .infix = Parser.binary, .precedence = .EQUALITY }, .STRING => .{ .prefix = Parser.string }, .IDENT => .{ .prefix = Parser.variable }, .AND => .{ .infix = Parser.and_, .precedence = .AND }, .OR => .{ .infix = Parser.or_, .precedence = .OR }, else => .{}, }; } test "rule table functions" { try expect(std.meta.eql(getRule(.LEFT_PAREN), ParseRule{ .prefix = Parser.grouping, .infix = null, .precedence = .NONE })); } test "compiles and runs" { var alloc = std.testing.allocator; var res = try compileAndRunExpression("4 + 5 - (3* 2)", alloc); try expectEqual(res, .{ .NUMBER = 3 }); } test "compile and run bool" { var res = try compileAndRunExpression("!(3-3)", std.testing.allocator); try expectEqual(res, value.Value{ .BOOL = true }); } test "bools equality" { var res = try compileAndRunExpression("(4 + 6 > 3 + 6)", std.testing.allocator); //std.debug.print("bools eq : {}", .{res}); const v = value.Value{ .BOOL = true }; try expect(try v.equal(res)); } test "string equality" { var alloc = std.testing.allocator; var res = try compileAndRunExpression( \\"hello" == ("hel" + "lo") , alloc); //std.debug.print("HELLO eq : {s}\n", .{res.asStr()}); const v = value.Value{ .BOOL = true }; try expect(try v.equal(res)); }
https://raw.githubusercontent.com/storyfeet/crafting_zlox/8d470acaca5157a13c441add346953c2e1953878/src/compiler.zig
pub fn showBlockTextureGen() void { showSettingsScreen(blecs.components.screen.TextureGen); } pub fn showBlockEditor() void { showSettingsScreen(blecs.components.screen.BlockEditor); } pub fn showChunkEditor() void { showSettingsScreen(blecs.components.screen.ChunkEditor); } pub fn showCharacterEditor() void { showSettingsScreen(blecs.components.screen.CharacterEditor); } pub fn showTerrainEditor() void { showSettingsScreen(blecs.components.screen.TerrainEditor); } pub fn showTitleScreen() void { showSettingsScreen(blecs.components.screen.TitleScreen); } pub fn showSettingUpScreen() void { showSettingsScreen(blecs.components.screen.SettingUpScreen); } pub fn showLoadingScreen() void { showSettingsScreen(blecs.components.screen.LoadingScreen); } pub fn showCreateWorldScreen() void { showSettingsScreen(blecs.components.screen.CreateWorldScreen); } pub fn showDisplaySettingsScreen() void { showSettingsScreen(blecs.components.screen.DisplaySettings); } pub fn toggleScreens() void { const world = game.state.world; const screen: *const blecs.components.screen.Screen = blecs.ecs.get( world, game.state.entities.screen, blecs.components.screen.Screen, ) orelse @panic("no screen"); if (blecs.ecs.has_id(world, screen.current, blecs.ecs.id(blecs.components.screen.Game))) { return showTitleScreen(); } if (blecs.ecs.has_id(game.state.world, screen.current, blecs.ecs.id(blecs.components.screen.TitleScreen))) { return showGameScreen(); } return showTitleScreen(); } pub fn showSettingsScreen(comptime T: type) void { const screen: *blecs.components.screen.Screen = blecs.ecs.get_mut( game.state.world, game.state.entities.screen, blecs.components.screen.Screen, ) orelse @panic("no screen"); // reset any setting ui state and previous demo objects added to the settings screen blecs.entities.screen.clearDemoObjects(); game.state.ui.clearUISettingsState(); // clear out the screens previous child, world or setting, this doesn't clear world objects, they are not cleared blecs.helpers.delete_children(game.state.world, game.state.entities.screen); // make a new current screen of the settings type screen.current = blecs.helpers.new_child(game.state.world, game.state.entities.screen); blecs.ecs.add(game.state.world, screen.current, blecs.components.screen.Settings); // Remove the game info UI blecs.ecs.remove(game.state.world, game.state.entities.ui, blecs.components.ui.GameInfo); // Add the menu UI, all settings have this blecs.ecs.add(game.state.world, game.state.entities.ui, blecs.components.ui.Menu); // Remove any post perspective setting from the transforms sent for settings, as they may differ for different setting screens blecs.ecs.remove(game.state.world, game.state.entities.settings_camera, blecs.components.screen.PostPerspective); // Add the specific setting screen blecs.ecs.add(game.state.world, screen.current, T); } pub fn showGameScreen() void { const screen: *blecs.components.screen.Screen = blecs.ecs.get_mut( game.state.world, game.state.entities.screen, blecs.components.screen.Screen, ) orelse @panic("no screen"); // Same as for settings but we don't clear anything, just change back to the game blecs.helpers.delete_children(game.state.world, game.state.entities.screen); screen.current = blecs.helpers.new_child(game.state.world, game.state.entities.screen); blecs.ecs.add(game.state.world, screen.current, blecs.components.screen.Game); blecs.ecs.add(game.state.world, game.state.entities.ui, blecs.components.ui.GameInfo); blecs.ecs.remove(game.state.world, game.state.entities.ui, blecs.components.ui.Menu); } pub fn toggleCameraOptions() void { toggleUI(blecs.components.ui.SettingsCamera); } pub fn toggleDemoCubeOptions() void { toggleUI(blecs.components.ui.DemoCube); } pub fn toggleDemoChunkOptions() void { toggleUI(blecs.components.ui.DemoChunk); } pub fn toggleDemoCharacterOptions() void { toggleUI(blecs.components.ui.DemoCharacter); } pub fn toggleGameChunksInfo() void { toggleUI(blecs.components.ui.GameChunksInfo); } pub fn toggleGameMobInfo() void { toggleUI(blecs.components.ui.GameMobInfo); } pub fn toggleLightingControls() void { toggleUI(blecs.components.ui.LightingControls); } pub fn toggleWorldManagement() void { toggleUI(blecs.components.ui.WorldManagement); } fn toggleUI(comptime T: type) void { const world = game.state.world; const entity = game.state.entities.ui; const ui: *blecs.components.ui.UI = blecs.ecs.get_mut(world, entity, blecs.components.ui.UI) orelse return; if (blecs.ecs.has_id(world, entity, blecs.ecs.id(T))) { blecs.ecs.remove(world, entity, T); ui.dialog_count -= 1; if (ui.dialog_count < 0) std.debug.panic("invalid ui dialog count: {d}\n", .{ui.dialog_count}); return; } blecs.ecs.add(world, entity, T); ui.dialog_count += 1; } pub fn toggleWireframe(entity: blecs.ecs.entity_t) void { if (blecs.ecs.has_id(game.state.world, entity, blecs.ecs.id(blecs.components.gfx.Wireframe))) { blecs.ecs.remove(game.state.world, entity, blecs.components.gfx.Wireframe); return; } blecs.ecs.add(game.state.world, entity, blecs.components.gfx.Wireframe); } const std = @import("std"); const blecs = @import("../blecs.zig"); const game = @import("../../game.zig");
https://raw.githubusercontent.com/btipling/blockens/76087f14d79a303f4cae8d09d8cfaaf86a69a0e0/src/game/blecs/systems/screen_helpers.zig
const std = @import("std"); const assert = std.debug.assert; const c = @import("c.zig"); const translate = @import("translate.zig"); export fn napi_register_module_v1(env: c.napi_env, exports: c.napi_value) c.napi_value { translate.register_function(env, exports, "greet", greet) catch return null; return exports; } fn greet(env: c.napi_env, info: c.napi_callback_info) callconv(.C) c.napi_value { return translate.create_string(env, "world") catch return null; }
https://raw.githubusercontent.com/staltz/zig-nodejs-example/f68ba9852114e614dbdee58ac03e41b00dfcff36/src/lib.zig
// Inspired by: https://gist.github.com/Accalmie/d328287c05f0a417892f // Simple Sniffer in winsock by Silver Moon ( m00n.silv3r@gmail.com ) const std = @import("std"); const ws = @cImport(@cInclude("winsock2.h")); const Protocol = enum(u8) { TCP = 6, UDP = 17 }; // Bit field order reversed because data is received as Big Endian but we are running on // Little Endian hardware const IPV4HeaderBE = packed struct { _header_len: u4, version: u4, tos: u8, _total_len: u16, _identification: u16, fragment_offset: u5, flags: u3, fragment_offset_1: u8, ttl: u8, protocol: u8, _hdr_checksum: u16, _src_addr: u32, _dest_addr: u32, pub fn header_len_byte_size(self: *IPV4HeaderBE) u8 { return @intCast(u8, self._header_len) * 4; } pub fn total_len(self: *IPV4HeaderBE) u16 { return ws.ntohs(self._total_len); } pub fn identification(self: *IPV4HeaderBE) u16 { return ws.ntohs(self._identification); } pub fn hdr_checksum(self: *IPV4HeaderBE) u16 { return ws.ntohs(self._hdr_checksum); } pub fn src_addr(self: *IPV4HeaderBE) [*c]u8 { var source = std.mem.zeroInit(ws.sockaddr_in, .{}); source.sin_addr.S_un.S_addr = self._src_addr; return ws.inet_ntoa(source.sin_addr); } pub fn dest_addr(self: *IPV4HeaderBE) [*c]u8 { var dest = std.mem.zeroInit(ws.sockaddr_in, .{}); dest.sin_addr.S_un.S_addr = self._dest_addr; return ws.inet_ntoa(dest.sin_addr); } }; const UDPHeaderBE = packed struct { _source_port: u16, _dest_port: u16, _udp_length: u16, _udp_checksum: u16, pub fn source_port(self: *UDPHeaderBE) u16 { return ws.ntohs(self._source_port); } pub fn dest_port(self: *UDPHeaderBE) u16 { return ws.ntohs(self._dest_port); } pub fn udp_length(self: *UDPHeaderBE) u16 { return ws.ntohs(self._udp_length); } pub fn udp_checksum(self: *UDPHeaderBE) u16 { return ws.ntohs(self._udp_checksum); } }; // Bit field order reversed because data is received as Big Endian but we are running on // Little Endian hardware const TCPHeaderBE = packed struct { _source_port: u16, _dest_port: u16, _sequence_num: u32, _acknowledge: u32, reserved: u4, _header_len: u4, fin: u1, syn: u1, rst: u1, psh: u1, ack: u1, urg: u1, ecn: u1, cwr: u1, _window_size: u16, _checksum: u16, urgent_pointer: u16, pub fn source_port(self: *TCPHeaderBE) u16 { return ws.ntohs(self._source_port); } pub fn dest_port(self: *TCPHeaderBE) u16 { return ws.ntohs(self._dest_port); } pub fn sequence_num(self: *TCPHeaderBE) u32 { return ws.ntohl(self._sequence_num); } pub fn acknowledge(self: *TCPHeaderBE) u32 { return ws.ntohl(self._acknowledge); } pub fn header_len_byte_size(self: *TCPHeaderBE) u8 { return @intCast(u8, self._header_len) * 4; } pub fn window_size(self: *TCPHeaderBE) u32 { return ws.ntohs(self._window_size); } pub fn checksum(self: *TCPHeaderBE) u32 { return ws.ntohs(self._checksum); } }; comptime { if (@sizeOf(IPV4HeaderBE) != 20) { @compileError("IPV4HeaderBE should be 20 bytes"); } if (@sizeOf(TCPHeaderBE) != 20) { @compileError("TCPHeaderBE should be 20 bytes"); } if (@sizeOf(UDPHeaderBE) != 8) { @compileError("UDPHeaderBE should be 4 bytes"); } } const PacketSnifferError = error{ WSASTARTUP_FAILED, INVALID_SOCKET, INVALID_HOSTNAME, INVALID_NETWORK_INTERFACE, BIND_FAILED, WSAIOCTL_FAILED, }; pub const PacketSniffer = struct { sniffing_socket: ws.SOCKET = undefined, const Self = @This(); pub fn run(self: *Self) PacketSnifferError!void { // Initialize WSA if (ws.WSAStartup(ws.MAKEWORD(2, 2), &std.mem.zeroInit(ws.WSADATA, .{})) != 0) { std.debug.print("Failed to create raw socket\n", .{}); return error.WSASTARTUP_FAILED; } // Create a raw socket (Requires administrator permission) self.sniffing_socket = ws.socket(ws.AF_INET, ws.SOCK_RAW, ws.IPPROTO_IP); if (self.sniffing_socket == ws.INVALID_SOCKET) { std.debug.print("Failed to create raw socket, make sure this is running as administrator\n", .{}); return error.INVALID_SOCKET; } // Get hostname var hostname: [100]u8 = undefined; if (ws.gethostname(@ptrCast([*c]u8, &hostname), @sizeOf(u8) * hostname.len) == ws.SOCKET_ERROR) { return error.INVALID_HOSTNAME; } // Get network interfaces var local: *ws.hostent = ws.gethostbyname(@ptrCast([*c]u8, &hostname)); var dest = std.mem.zeroInit(ws.sockaddr_in, .{}); dest.sin_family = ws.AF_INET; dest.sin_port = 0; std.debug.print("Choose a network interface: \n", .{}); // Display the network interface var network_interface_index: u8 = 0; while (local.h_addr_list[network_interface_index]) |network_interface| { var tmp_addr = std.mem.zeroInit(ws.sockaddr_in, .{}); @memcpy(@ptrCast([*]u8, &tmp_addr.sin_addr.S_un.S_addr), @ptrCast([*]const u8, network_interface), @sizeOf(u64)); std.debug.print("[{}] {s}\n", .{ network_interface_index, ws.inet_ntoa(tmp_addr.sin_addr) }); network_interface_index += 1; } // Choose the desired network interface const stdin = std.io.getStdIn().reader(); // FIXME: only supports up to 9 interfaces const ascii_input = try stdin.readByte() catch error.INVALID_NETWORK_INTERFACE; var captured_network_interface: u32 = ascii_input - '0'; var captured_ip = local.h_addr_list[captured_network_interface]; @memcpy(@ptrCast([*]u8, &dest.sin_addr.S_un.S_addr), @ptrCast([*]const u8, captured_ip), @sizeOf(u64)); // Bind the sniffer on the desired port if (ws.bind(self.sniffing_socket, @ptrCast([*c]const ws.sockaddr, &dest), @sizeOf(ws.sockaddr_in)) == ws.SOCKET_ERROR) { std.debug.print("Socket binding failed\n", .{}); return error.BIND_FAILED; } var j: u32 = 1; const wasiotcl_result = ws.WSAIoctl( self.sniffing_socket, ws._WSAIOW(@intCast(u32, ws.IOC_VENDOR), @as(u32, 1)), &j, @sizeOf(u32), null, @as(u32, 0), &captured_network_interface, 0, null, ); if (wasiotcl_result == ws.SOCKET_ERROR) { std.debug.print("WSAIOCTL_FAILED failed\n", .{}); return error.WSAIOCTL_FAILED; } try self.sniff(); } fn sniff(self: *Self) PacketSnifferError!void { std.debug.print("Stared sniffing\n", .{}); var tmp_buf: [std.math.maxInt(u16)]u8 = undefined; while (true) { const recv_result = ws.recvfrom(self.sniffing_socket, &tmp_buf, std.math.maxInt(u16), 0, 0, 0); if (recv_result == ws.SOCKET_ERROR) { std.debug.print("RECV Error = {}\n", .{ws.WSAGetLastError()}); } const len = @intCast(usize, recv_result); std.debug.print("[RAW] {}\n", .{std.fmt.fmtSliceHexLower(tmp_buf[0..len])}); var buf_slice = tmp_buf[0..len]; try process_ipv4_packet(buf_slice); std.debug.print("\n", .{}); } } fn process_ipv4_packet(buffer: []u8) PacketSnifferError!void { var ipv4_header: *IPV4HeaderBE = @ptrCast(*IPV4HeaderBE, buffer); std.debug.print("[IPV4] {s}\n", .{ipv4_header}); switch (ipv4_header.protocol) { @enumToInt(Protocol.TCP) => try process_tcp_packet(buffer), @enumToInt(Protocol.UDP) => try process_udp_packet(buffer), else => std.debug.print("Unsupported packet type: {}\n", .{ipv4_header.protocol}), } } fn process_tcp_packet(buffer: []u8) PacketSnifferError!void { var ipv4_header: *IPV4HeaderBE = @ptrCast(*IPV4HeaderBE, buffer); var tcp_header: *TCPHeaderBE = @ptrCast(*TCPHeaderBE, buffer[ipv4_header.header_len_byte_size()..]); std.debug.print("[TCP] {s}\n", .{tcp_header}); std.debug.print("{s} -> {s} [{} -> {}] {} bytes\n", .{ ipv4_header.src_addr(), ipv4_header.dest_addr(), tcp_header.source_port(), tcp_header.dest_port(), buffer.len }); } fn process_udp_packet(buffer: []u8) PacketSnifferError!void { var ipv4_header: *IPV4HeaderBE = @ptrCast(*IPV4HeaderBE, buffer); var udp_header: *UDPHeaderBE = @ptrCast(*UDPHeaderBE, buffer[ipv4_header.header_len_byte_size()..]); std.debug.print("[UDP] {s}\n", .{udp_header}); std.debug.print("{s} -> {s} [{} -> {}] {} bytes\n", .{ ipv4_header.src_addr(), ipv4_header.dest_addr(), udp_header.source_port(), udp_header.dest_port(), buffer.len }); } };
https://raw.githubusercontent.com/tris790/packet-sniffer/d52d9be9d18da1df8472f02d0db9d36f208ae23b/src/packet_sniffer.zig
//comptime //{ // asm ( // \\ .set ALIGN, 1 << 0 // \\ .set MEMINFO, 1 << 1 // \\ .set FLAGS, ALIGN | MEMINFO // \\ .set MAGIC, 0x1BADB002 // \\ .set CHECKSUM, -(MAGIC + FLAGS) // \\ // \\ .section .multiboot // \\ .align 4 // \\ .long MAGIC // \\ .long FLAGS // \\ .long CHECKSUM // ); //} const ALIGN = 1 << 0; const MEMINFO = 1 << 1; const MAGIC = 0x1BADB002; const FLAGS = ALIGN | MEMINFO; const MultiBoot = packed struct { magic: i32 = MAGIC, flags: i32, checksum: i32, _: i32 = 0, }; export var multiboot align(4) linksection(".multiboot") = MultiBoot { .flags = FLAGS, .checksum = -(MAGIC + FLAGS), }; export var kernel_stack: [32 * 1024]u8 align(16) linksection(".bss") = undefined; extern fn kmain() void; export fn _start() align(16) linksection(".text.boot") callconv(.Naked) noreturn { // Setup the stack and call kernel asm volatile ( \\ movl %[stk], %esp \\ call kmain : : [stk] "{ecx}" (@intFromPtr(&kernel_stack) + @sizeOf(@TypeOf(kernel_stack))), ); while(true) {} }
https://raw.githubusercontent.com/Kbz-8/42_KFS/decb1dfa62f1ca893094f3f6fd5ed6e43a53c4d9/sources/kernel/arch/x86/boot.zig
// File: binary_search_tree.zig // Created Time: 2023-01-15 // Author: sjinzh (sjinzh@gmail.com) const std = @import("std"); const inc = @import("include"); // 二叉搜索树 pub fn BinarySearchTree(comptime T: type) type { return struct { const Self = @This(); root: ?*inc.TreeNode(T) = null, mem_arena: ?std.heap.ArenaAllocator = null, mem_allocator: std.mem.Allocator = undefined, // 内存分配器 // 构造方法 pub fn init(self: *Self, allocator: std.mem.Allocator, nums: []T) !void { if (self.mem_arena == null) { self.mem_arena = std.heap.ArenaAllocator.init(allocator); self.mem_allocator = self.mem_arena.?.allocator(); } std.mem.sort(T, nums, {}, comptime std.sort.asc(T)); // 排序数组 self.root = try self.buildTree(nums, 0, nums.len - 1); // 构建二叉搜索树 } // 析构方法 pub fn deinit(self: *Self) void { if (self.mem_arena == null) return; self.mem_arena.?.deinit(); } // 构建二叉搜索树 fn buildTree(self: *Self, nums: []T, i: usize, j: usize) !?*inc.TreeNode(T) { if (i > j) return null; // 将数组中间节点作为根节点 var mid = (i + j) / 2; var node = try self.mem_allocator.create(inc.TreeNode(T)); node.init(nums[mid]); // 递归建立左子树和右子树 if (mid >= 1) node.left = try self.buildTree(nums, i, mid - 1); node.right = try self.buildTree(nums, mid + 1, j); return node; } // 获取二叉树根节点 fn getRoot(self: *Self) ?*inc.TreeNode(T) { return self.root; } // 查找节点 fn search(self: *Self, num: T) ?*inc.TreeNode(T) { var cur = self.root; // 循环查找,越过叶节点后跳出 while (cur != null) { // 目标节点在 cur 的右子树中 if (cur.?.val < num) { cur = cur.?.right; // 目标节点在 cur 的左子树中 } else if (cur.?.val > num) { cur = cur.?.left; // 找到目标节点,跳出循环 } else { break; } } // 返回目标节点 return cur; } // 插入节点 fn insert(self: *Self, num: T) !void { // 若树为空,则初始化根节点 if (self.root == null) { self.root = try self.mem_allocator.create(inc.TreeNode(T)); return; } var cur = self.root; var pre: ?*inc.TreeNode(T) = null; // 循环查找,越过叶节点后跳出 while (cur != null) { // 找到重复节点,直接返回 if (cur.?.val == num) return; pre = cur; // 插入位置在 cur 的右子树中 if (cur.?.val < num) { cur = cur.?.right; // 插入位置在 cur 的左子树中 } else { cur = cur.?.left; } } // 插入节点 var node = try self.mem_allocator.create(inc.TreeNode(T)); node.init(num); if (pre.?.val < num) { pre.?.right = node; } else { pre.?.left = node; } } // 删除节点 fn remove(self: *Self, num: T) void { // 若树为空,直接提前返回 if (self.root == null) return; var cur = self.root; var pre: ?*inc.TreeNode(T) = null; // 循环查找,越过叶节点后跳出 while (cur != null) { // 找到待删除节点,跳出循环 if (cur.?.val == num) break; pre = cur; // 待删除节点在 cur 的右子树中 if (cur.?.val < num) { cur = cur.?.right; // 待删除节点在 cur 的左子树中 } else { cur = cur.?.left; } } // 若无待删除节点,则直接返回 if (cur == null) return; // 子节点数量 = 0 or 1 if (cur.?.left == null or cur.?.right == null) { // 当子节点数量 = 0 / 1 时, child = null / 该子节点 var child = if (cur.?.left != null) cur.?.left else cur.?.right; // 删除节点 cur if (pre.?.left == cur) { pre.?.left = child; } else { pre.?.right = child; } // 子节点数量 = 2 } else { // 获取中序遍历中 cur 的下一个节点 var tmp = cur.?.right; while (tmp.?.left != null) { tmp = tmp.?.left; } var tmp_val = tmp.?.val; // 递归删除节点 tmp self.remove(tmp.?.val); // 用 tmp 覆盖 cur cur.?.val = tmp_val; } } }; } // Driver Code pub fn main() !void { // 初始化二叉树 var nums = [_]i32{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; var bst = BinarySearchTree(i32){}; try bst.init(std.heap.page_allocator, &nums); defer bst.deinit(); std.debug.print("初始化的二叉树为\n", .{}); try inc.PrintUtil.printTree(bst.getRoot(), null, false); // 查找节点 var node = bst.search(7); std.debug.print("\n查找到的节点对象为 {any},节点值 = {}\n", .{node, node.?.val}); // 插入节点 try bst.insert(16); std.debug.print("\n插入节点 16 后,二叉树为\n", .{}); try inc.PrintUtil.printTree(bst.getRoot(), null, false); // 删除节点 bst.remove(1); std.debug.print("\n删除节点 1 后,二叉树为\n", .{}); try inc.PrintUtil.printTree(bst.getRoot(), null, false); bst.remove(2); std.debug.print("\n删除节点 2 后,二叉树为\n", .{}); try inc.PrintUtil.printTree(bst.getRoot(), null, false); bst.remove(4); std.debug.print("\n删除节点 4 后,二叉树为\n", .{}); try inc.PrintUtil.printTree(bst.getRoot(), null, false); _ = try std.io.getStdIn().reader().readByte(); }
https://raw.githubusercontent.com/qianjiangboy/hello-algo/9baf4a1753ab097e574046431dfbbd488a6739b8/codes/zig/chapter_tree/binary_search_tree.zig
const std = @import("std"); const sdl = @import("sdl.zig"); const settings = @import("settings.zig"); const game = @import("game"); const math = @import("math.zig"); pub const Event = enum { exit, ok, }; pub fn handleInput(state: *game.GameState) Event { var event: sdl.SDL_Event = undefined; while (sdl.SDL_PollEvent(&event) != 0) { switch (event.type) { sdl.SDL_QUIT => return .exit, sdl.SDL_KEYDOWN => handleKeyDown(&event.key, state), sdl.SDL_KEYUP => handleKeyUp(&event.key, state), sdl.SDL_MOUSEBUTTONUP => handleMouseUp(&event.button, state), sdl.SDL_MOUSEBUTTONDOWN => handleMouseDown(&event.button, state), else => {}, } } return .ok; } pub fn handleKeyDown(event: *sdl.SDL_KeyboardEvent, state: *game.GameState) void { if (event.repeat == 0 and event.keysym.scancode < settings.MAX_KEYBOARD_KEYS) { state.keyboard[event.keysym.scancode] = true; } } pub fn handleKeyUp(event: *sdl.SDL_KeyboardEvent, state: *game.GameState) void { if (event.repeat == 0 and event.keysym.scancode < settings.MAX_KEYBOARD_KEYS) { state.keyboard[event.keysym.scancode] = false; } } pub fn handleMouseDown(event: *sdl.SDL_MouseButtonEvent, state: *game.GameState) void { if (event.clicks == 1 and event.button < settings.MAX_MOUSE_BUTTONS) { state.mouse[event.button] = true; } } pub fn handleMouseUp(event: *sdl.SDL_MouseButtonEvent, state: *game.GameState) void { if (event.button < settings.MAX_MOUSE_BUTTONS) { state.mouse[event.button] = false; } }
https://raw.githubusercontent.com/j-helland/zig-htn-demo/a8a2dbc1b606f25631c29e3b3f829230da1e558e/src/input.zig
const std = @import("std"); const print = std.debug.print; pub fn main() !void { try solve("d09/test1"); try solve("d09/input"); } fn solve(filename: []const u8) !void { const file = try std.fs.cwd().openFile(filename, .{}); defer file.close(); var buf_reader = std.io.bufferedReader(file.reader()); const in_stream = buf_reader.reader(); var buffer: [1024]u8 = undefined; var oasis_prev: i64 = 0; var oasis_next: i64 = 0; while (try in_stream.readUntilDelimiterOrEof(&buffer, '\n')) |line| { var chunks = std.mem.split(u8, line, " "); var readings_buf: [256]i64 = undefined; var readings_count: usize = 0; while (chunks.next()) |chunk| { readings_buf[readings_count] = try std.fmt.parseInt(i64, chunk, 10); readings_count += 1; } const readings = readings_buf[0..readings_count]; var reading_deltas = [_]i64{0} ** 64; var last_delta = readings.len - 1; for (0..last_delta) |i| { reading_deltas[i] = readings[i + 1] - readings[i]; } var first_vals = [_]i64{0} ** 64; first_vals[0] = readings[0]; first_vals[1] = reading_deltas[0]; var last_vals = [_]i64{0} ** 64; last_vals[0] = readings[readings.len - 1]; last_vals[1] = reading_deltas[last_delta - 1]; last_delta -= 1; var last_val_i: usize = 2; while (std.mem.min(i64, &reading_deltas) != 0 or std.mem.max(i64, &reading_deltas) != 0) { for (0..last_delta) |i| { reading_deltas[i] = reading_deltas[i + 1] - reading_deltas[i]; } last_vals[last_val_i] = reading_deltas[last_delta - 1]; first_vals[last_val_i] = reading_deltas[0]; reading_deltas[last_delta] = 0; last_delta -= 1; last_val_i += 1; } var next: i64 = 0; for (0..last_val_i) |lvi| next += last_vals[lvi]; oasis_next += next; var prev: i64 = first_vals[last_val_i - 1]; for (1..last_val_i) |lvi| prev = first_vals[last_val_i - lvi - 1] - prev; oasis_prev += prev; } print("OASIS {d}..{d}\n", .{ oasis_prev, oasis_next }); }
https://raw.githubusercontent.com/andrewflbarnes/advent-of-code-2023/852c602dac382ff738e7a41c003bd51e6e947939/d09/soln.zig
// Copyright 2024 The Nushift Authors. // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // https://www.boost.org/LICENSE_1_0.txt) const std = @import("std"); pub const FBSWriter = std.io.FixedBufferStream([]u8).Writer; pub const FBSWriteError = std.io.FixedBufferStream([]u8).WriteError; pub fn writeU64Seq(writer: FBSWriter, seq: []const u64) FBSWriteError!void { try std.leb.writeULEB128(writer, seq.len); for (seq) |elem| { try std.leb.writeULEB128(writer, elem); } } pub fn writeF64Seq(writer: FBSWriter, seq: []const f64) FBSWriteError!void { try std.leb.writeULEB128(writer, seq.len); for (seq) |elem| { try writeF64(writer, elem); } } pub fn writeF64(writer: FBSWriter, value: f64) FBSWriteError!void { try writer.writeIntLittle(u64, @as(u64, @bitCast(value))); } pub fn writeStr(writer: FBSWriter, str: []const u8) FBSWriteError!void { try std.leb.writeULEB128(writer, str.len); _ = try writer.write(str); }
https://raw.githubusercontent.com/davepollack/nushift/83f074c7bb2a2fa8405818eee8be8526c24ff4f8/examples/hello-world/src/writing.zig
const std = @import("std"); pub fn main() !void { var file = try std.fs.cwd().openFile("input.txt", .{}); defer file.close(); var buf_reader = std.io.bufferedReader(file.reader()); var in_stream = buf_reader.reader(); // -1 is "unset" flag var first: i32 = -1; var last: i32 = 0; var sum: i32 = 0; while (true) { var byte = in_stream.readByte() catch { // end of file break; }; // check byte is a number if ('0' <= byte and byte <= '9') { if(first == -1) { // first is not set, this is first digit first = byte - '0'; } last = byte - '0'; } if (byte == '\n') { // end of line: append result to sum sum += 10 * first + last; first = -1; } } std.debug.print("{}\n", .{sum}); }
https://raw.githubusercontent.com/VirgileHenry/aoc-zig/ceb7feb4ee0f26d6cc82d7c3c8fa6a7fdf42dba4/day1/part1/src/main.zig
const assert = @import("std").debug.assert; pub const DrawListSharedData = opaque {}; pub const Context = opaque {}; pub const DrawCallback = ?fn (parent_list: ?*const DrawList, cmd: ?*const DrawCmd) callconv(.C) void; pub const DrawIdx = u16; pub const ID = u32; pub const InputTextCallback = ?fn (data: ?*InputTextCallbackData) callconv(.C) i32; pub const SizeCallback = ?fn (data: ?*SizeCallbackData) callconv(.C) void; pub const TextureID = ?*c_void; pub const Wchar = u16; pub const DrawCallback_ResetRenderState = @intToPtr(DrawCallback, ~@as(usize, 0)); pub const VERSION = "1.75"; pub fn CHECKVERSION() void { if (@import("builtin").mode != .ReleaseFast) { @import("std").debug.assert(raw.igDebugCheckVersionAndDataLayout(VERSION, @sizeOf(IO), @sizeOf(Style), @sizeOf(Vec2), @sizeOf(Vec4), @sizeOf(DrawVert), @sizeOf(DrawIdx))); } } pub const FLT_MAX = @import("std").math.f32_max; pub const FlagsInt = u32; pub fn FlagsMixin(comptime FlagType: type) type { comptime assert(@sizeOf(FlagType) == 4); return struct { pub fn toInt(self: FlagType) FlagsInt { return @bitCast(FlagsInt, self); } pub fn fromInt(value: FlagsInt) FlagType { return @bitCast(FlagType, value); } pub fn with(a: FlagType, b: FlagType) FlagType { return fromInt(toInt(a) | toInt(b)); } pub fn only(a: FlagType, b: FlagType) FlagType { return fromInt(toInt(a) & toInt(b)); } pub fn without(a: FlagType, b: FlagType) FlagType { return fromInt(toInt(a) & ~toInt(b)); } pub fn hasAllSet(a: FlagType, b: FlagType) bool { return (toInt(a) & toInt(b)) == toInt(b); } pub fn hasAnySet(a: FlagType, b: FlagType) bool { return (toInt(a) & toInt(b)) != 0; } pub fn isEmpty(a: FlagType) bool { return toInt(a) == 0; } }; } pub const DrawCornerFlagsInt = FlagsInt; pub const DrawCornerFlags = packed struct { TopLeft: bool = false, TopRight: bool = false, BotLeft: bool = false, BotRight: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const Top = Self{ .TopLeft=true, .TopRight=true }; pub const Bot = Self{ .BotLeft=true, .BotRight=true }; pub const Left = Self{ .TopLeft=true, .BotLeft=true }; pub const Right = Self{ .TopRight=true, .BotRight=true }; pub const All = Self{ .TopLeft=true, .TopRight=true, .BotLeft=true, .BotRight=true }; pub usingnamespace FlagsMixin(Self); }; pub const DrawListFlagsInt = FlagsInt; pub const DrawListFlags = packed struct { AntiAliasedLines: bool = false, AntiAliasedFill: bool = false, AllowVtxOffset: bool = false, __reserved_bit_03: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const FontAtlasFlagsInt = FlagsInt; pub const FontAtlasFlags = packed struct { NoPowerOfTwoHeight: bool = false, NoMouseCursors: bool = false, __reserved_bit_02: bool = false, __reserved_bit_03: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const BackendFlagsInt = FlagsInt; pub const BackendFlags = packed struct { HasGamepad: bool = false, HasMouseCursors: bool = false, HasSetMousePos: bool = false, RendererHasVtxOffset: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const ColorEditFlagsInt = FlagsInt; pub const ColorEditFlags = packed struct { __reserved_bit_00: bool = false, NoAlpha: bool = false, NoPicker: bool = false, NoOptions: bool = false, NoSmallPreview: bool = false, NoInputs: bool = false, NoTooltip: bool = false, NoLabel: bool = false, NoSidePreview: bool = false, NoDragDrop: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, AlphaBar: bool = false, AlphaPreview: bool = false, AlphaPreviewHalf: bool = false, HDR: bool = false, DisplayRGB: bool = false, DisplayHSV: bool = false, DisplayHex: bool = false, Uint8: bool = false, Float: bool = false, PickerHueBar: bool = false, PickerHueWheel: bool = false, InputRGB: bool = false, InputHSV: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const _OptionsDefault = Self{ .DisplayRGB=true, .Uint8=true, .PickerHueBar=true, .InputRGB=true }; pub const _DisplayMask = Self{ .DisplayRGB=true, .DisplayHSV=true, .DisplayHex=true }; pub const _DataTypeMask = Self{ .Uint8=true, .Float=true }; pub const _PickerMask = Self{ .PickerHueBar=true, .PickerHueWheel=true }; pub const _InputMask = Self{ .InputRGB=true, .InputHSV=true }; pub usingnamespace FlagsMixin(Self); }; pub const ComboFlagsInt = FlagsInt; pub const ComboFlags = packed struct { PopupAlignLeft: bool = false, HeightSmall: bool = false, HeightRegular: bool = false, HeightLarge: bool = false, HeightLargest: bool = false, NoArrowButton: bool = false, NoPreview: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const HeightMask_ = Self{ .HeightSmall=true, .HeightRegular=true, .HeightLarge=true, .HeightLargest=true }; pub usingnamespace FlagsMixin(Self); }; pub const CondFlagsInt = FlagsInt; pub const CondFlags = packed struct { Always: bool = false, Once: bool = false, FirstUseEver: bool = false, Appearing: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, pub usingnamespace FlagsMixin(@This()); }; pub const ConfigFlagsInt = FlagsInt; pub const ConfigFlags = packed struct { NavEnableKeyboard: bool = false, NavEnableGamepad: bool = false, NavEnableSetMousePos: bool = false, NavNoCaptureKeyboard: bool = false, NoMouse: bool = false, NoMouseCursorChange: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, IsSRGB: bool = false, IsTouchScreen: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const DragDropFlagsInt = FlagsInt; pub const DragDropFlags = packed struct { SourceNoPreviewTooltip: bool = false, SourceNoDisableHover: bool = false, SourceNoHoldToOpenOthers: bool = false, SourceAllowNullID: bool = false, SourceExtern: bool = false, SourceAutoExpirePayload: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, AcceptBeforeDelivery: bool = false, AcceptNoDrawDefaultRect: bool = false, AcceptNoPreviewTooltip: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const AcceptPeekOnly = Self{ .AcceptBeforeDelivery=true, .AcceptNoDrawDefaultRect=true }; pub usingnamespace FlagsMixin(Self); }; pub const FocusedFlagsInt = FlagsInt; pub const FocusedFlags = packed struct { ChildWindows: bool = false, RootWindow: bool = false, AnyWindow: bool = false, __reserved_bit_03: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const RootAndChildWindows = Self{ .ChildWindows=true, .RootWindow=true }; pub usingnamespace FlagsMixin(Self); }; pub const HoveredFlagsInt = FlagsInt; pub const HoveredFlags = packed struct { ChildWindows: bool = false, RootWindow: bool = false, AnyWindow: bool = false, AllowWhenBlockedByPopup: bool = false, __reserved_bit_04: bool = false, AllowWhenBlockedByActiveItem: bool = false, AllowWhenOverlapped: bool = false, AllowWhenDisabled: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const RectOnly = Self{ .AllowWhenBlockedByPopup=true, .AllowWhenBlockedByActiveItem=true, .AllowWhenOverlapped=true }; pub const RootAndChildWindows = Self{ .ChildWindows=true, .RootWindow=true }; pub usingnamespace FlagsMixin(Self); }; pub const InputTextFlagsInt = FlagsInt; pub const InputTextFlags = packed struct { CharsDecimal: bool = false, CharsHexadecimal: bool = false, CharsUppercase: bool = false, CharsNoBlank: bool = false, AutoSelectAll: bool = false, EnterReturnsTrue: bool = false, CallbackCompletion: bool = false, CallbackHistory: bool = false, CallbackAlways: bool = false, CallbackCharFilter: bool = false, AllowTabInput: bool = false, CtrlEnterForNewLine: bool = false, NoHorizontalScroll: bool = false, AlwaysInsertMode: bool = false, ReadOnly: bool = false, Password: bool = false, NoUndoRedo: bool = false, CharsScientific: bool = false, CallbackResize: bool = false, __reserved_bit_19: bool = false, Multiline: bool = false, NoMarkEdited: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const SelectableFlagsInt = FlagsInt; pub const SelectableFlags = packed struct { DontClosePopups: bool = false, SpanAllColumns: bool = false, AllowDoubleClick: bool = false, Disabled: bool = false, AllowItemOverlap: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const TabBarFlagsInt = FlagsInt; pub const TabBarFlags = packed struct { Reorderable: bool = false, AutoSelectNewTabs: bool = false, TabListPopupButton: bool = false, NoCloseWithMiddleMouseButton: bool = false, NoTabListScrollingButtons: bool = false, NoTooltip: bool = false, FittingPolicyResizeDown: bool = false, FittingPolicyScroll: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const FittingPolicyMask_ = Self{ .FittingPolicyResizeDown=true, .FittingPolicyScroll=true }; pub const FittingPolicyDefault_ = Self{ .FittingPolicyResizeDown=true }; pub usingnamespace FlagsMixin(Self); }; pub const TabItemFlagsInt = FlagsInt; pub const TabItemFlags = packed struct { UnsavedDocument: bool = false, SetSelected: bool = false, NoCloseWithMiddleMouseButton: bool = false, NoPushId: bool = false, __reserved_bit_04: bool = false, __reserved_bit_05: bool = false, __reserved_bit_06: bool = false, __reserved_bit_07: bool = false, __reserved_bit_08: bool = false, __reserved_bit_09: bool = false, __reserved_bit_10: bool = false, __reserved_bit_11: bool = false, __reserved_bit_12: bool = false, __reserved_bit_13: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub usingnamespace FlagsMixin(Self); }; pub const TreeNodeFlagsInt = FlagsInt; pub const TreeNodeFlags = packed struct { Selected: bool = false, Framed: bool = false, AllowItemOverlap: bool = false, NoTreePushOnOpen: bool = false, NoAutoOpenOnLog: bool = false, DefaultOpen: bool = false, OpenOnDoubleClick: bool = false, OpenOnArrow: bool = false, Leaf: bool = false, Bullet: bool = false, FramePadding: bool = false, SpanAvailWidth: bool = false, SpanFullWidth: bool = false, NavLeftJumpsBackHere: bool = false, __reserved_bit_14: bool = false, __reserved_bit_15: bool = false, __reserved_bit_16: bool = false, __reserved_bit_17: bool = false, __reserved_bit_18: bool = false, __reserved_bit_19: bool = false, __reserved_bit_20: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, __reserved_bit_23: bool = false, __reserved_bit_24: bool = false, __reserved_bit_25: bool = false, __reserved_bit_26: bool = false, __reserved_bit_27: bool = false, __reserved_bit_28: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const CollapsingHeader = Self{ .Framed=true, .NoTreePushOnOpen=true, .NoAutoOpenOnLog=true }; pub usingnamespace FlagsMixin(Self); }; pub const WindowFlagsInt = FlagsInt; pub const WindowFlags = packed struct { NoTitleBar: bool = false, NoResize: bool = false, NoMove: bool = false, NoScrollbar: bool = false, NoScrollWithMouse: bool = false, NoCollapse: bool = false, AlwaysAutoResize: bool = false, NoBackground: bool = false, NoSavedSettings: bool = false, NoMouseInputs: bool = false, MenuBar: bool = false, HorizontalScrollbar: bool = false, NoFocusOnAppearing: bool = false, NoBringToFrontOnFocus: bool = false, AlwaysVerticalScrollbar: bool = false, AlwaysHorizontalScrollbar: bool = false, AlwaysUseWindowPadding: bool = false, __reserved_bit_17: bool = false, NoNavInputs: bool = false, NoNavFocus: bool = false, UnsavedDocument: bool = false, __reserved_bit_21: bool = false, __reserved_bit_22: bool = false, NavFlattened: bool = false, ChildWindow: bool = false, Tooltip: bool = false, Popup: bool = false, Modal: bool = false, ChildMenu: bool = false, __reserved_bit_29: bool = false, __reserved_bit_30: bool = false, __reserved_bit_31: bool = false, const Self = @This(); pub const None = Self{}; pub const NoNav = Self{ .NoNavInputs=true, .NoNavFocus=true }; pub const NoDecoration = Self{ .NoTitleBar=true, .NoResize=true, .NoScrollbar=true, .NoCollapse=true }; pub const NoInputs = Self{ .NoMouseInputs=true, .NoNavInputs=true, .NoNavFocus=true }; pub usingnamespace FlagsMixin(Self); }; pub const Col = extern enum { Text = 0, TextDisabled = 1, WindowBg = 2, ChildBg = 3, PopupBg = 4, Border = 5, BorderShadow = 6, FrameBg = 7, FrameBgHovered = 8, FrameBgActive = 9, TitleBg = 10, TitleBgActive = 11, TitleBgCollapsed = 12, MenuBarBg = 13, ScrollbarBg = 14, ScrollbarGrab = 15, ScrollbarGrabHovered = 16, ScrollbarGrabActive = 17, CheckMark = 18, SliderGrab = 19, SliderGrabActive = 20, Button = 21, ButtonHovered = 22, ButtonActive = 23, Header = 24, HeaderHovered = 25, HeaderActive = 26, Separator = 27, SeparatorHovered = 28, SeparatorActive = 29, ResizeGrip = 30, ResizeGripHovered = 31, ResizeGripActive = 32, Tab = 33, TabHovered = 34, TabActive = 35, TabUnfocused = 36, TabUnfocusedActive = 37, PlotLines = 38, PlotLinesHovered = 39, PlotHistogram = 40, PlotHistogramHovered = 41, TextSelectedBg = 42, DragDropTarget = 43, NavHighlight = 44, NavWindowingHighlight = 45, NavWindowingDimBg = 46, ModalWindowDimBg = 47, pub const COUNT = 48; }; pub const DataType = extern enum { S8 = 0, U8 = 1, S16 = 2, U16 = 3, S32 = 4, U32 = 5, S64 = 6, U64 = 7, Float = 8, Double = 9, pub const COUNT = 10; }; pub const Dir = extern enum { None = -1, Left = 0, Right = 1, Up = 2, Down = 3, pub const COUNT = 4; }; pub const Key = extern enum { Tab = 0, LeftArrow = 1, RightArrow = 2, UpArrow = 3, DownArrow = 4, PageUp = 5, PageDown = 6, Home = 7, End = 8, Insert = 9, Delete = 10, Backspace = 11, Space = 12, Enter = 13, Escape = 14, KeyPadEnter = 15, A = 16, C = 17, V = 18, X = 19, Y = 20, Z = 21, pub const COUNT = 22; }; pub const MouseButton = extern enum { Left = 0, Right = 1, Middle = 2, pub const COUNT = 5; }; pub const MouseCursor = extern enum { None = -1, Arrow = 0, TextInput = 1, ResizeAll = 2, ResizeNS = 3, ResizeEW = 4, ResizeNESW = 5, ResizeNWSE = 6, Hand = 7, NotAllowed = 8, pub const COUNT = 9; }; pub const NavInput = extern enum { Activate = 0, Cancel = 1, Input = 2, Menu = 3, DpadLeft = 4, DpadRight = 5, DpadUp = 6, DpadDown = 7, LStickLeft = 8, LStickRight = 9, LStickUp = 10, LStickDown = 11, FocusPrev = 12, FocusNext = 13, TweakSlow = 14, TweakFast = 15, KeyMenu_ = 16, KeyLeft_ = 17, KeyRight_ = 18, KeyUp_ = 19, KeyDown_ = 20, pub const COUNT = 21; pub const Self = @This(); pub const InternalStart_ = Self.KeyMenu_; }; pub const StyleVar = extern enum { Alpha = 0, WindowPadding = 1, WindowRounding = 2, WindowBorderSize = 3, WindowMinSize = 4, WindowTitleAlign = 5, ChildRounding = 6, ChildBorderSize = 7, PopupRounding = 8, PopupBorderSize = 9, FramePadding = 10, FrameRounding = 11, FrameBorderSize = 12, ItemSpacing = 13, ItemInnerSpacing = 14, IndentSpacing = 15, ScrollbarSize = 16, ScrollbarRounding = 17, GrabMinSize = 18, GrabRounding = 19, TabRounding = 20, ButtonTextAlign = 21, SelectableTextAlign = 22, pub const COUNT = 23; }; pub const Color = extern struct { Value: Vec4, pub inline fn HSVExt(self: *Color, h: f32, s: f32, v: f32, a: f32) Color { var out: Color = undefined; raw.ImColor_HSV_nonUDT(&out, self, h, s, v, a); return out; } pub inline fn HSV(self: *Color, h: f32, s: f32, v: f32) Color { return HSVExt(self, h, s, v, 1.0); } /// init(self: *Color) void pub const init = raw.ImColor_ImColor; /// initIntExt(self: *Color, r: i32, g: i32, b: i32, a: i32) void pub const initIntExt = raw.ImColor_ImColorInt; pub inline fn initInt(self: *Color, r: i32, g: i32, b: i32) void { return initIntExt(self, r, g, b, 255); } /// initU32(self: *Color, rgba: u32) void pub const initU32 = raw.ImColor_ImColorU32; /// initFloatExt(self: *Color, r: f32, g: f32, b: f32, a: f32) void pub const initFloatExt = raw.ImColor_ImColorFloat; pub inline fn initFloat(self: *Color, r: f32, g: f32, b: f32) void { return initFloatExt(self, r, g, b, 1.0); } /// initVec4(self: *Color, col: Vec4) void pub const initVec4 = raw.ImColor_ImColorVec4; /// SetHSVExt(self: *Color, h: f32, s: f32, v: f32, a: f32) void pub const SetHSVExt = raw.ImColor_SetHSV; pub inline fn SetHSV(self: *Color, h: f32, s: f32, v: f32) void { return SetHSVExt(self, h, s, v, 1.0); } /// deinit(self: *Color) void pub const deinit = raw.ImColor_destroy; }; pub const DrawChannel = extern struct { _CmdBuffer: Vector(DrawCmd), _IdxBuffer: Vector(DrawIdx), }; pub const DrawCmd = extern struct { ElemCount: u32, ClipRect: Vec4, TextureId: TextureID, VtxOffset: u32, IdxOffset: u32, UserCallback: DrawCallback, UserCallbackData: ?*c_void, /// init(self: *DrawCmd) void pub const init = raw.ImDrawCmd_ImDrawCmd; /// deinit(self: *DrawCmd) void pub const deinit = raw.ImDrawCmd_destroy; }; pub const DrawData = extern struct { Valid: bool, CmdLists: ?[*]*DrawList, CmdListsCount: i32, TotalIdxCount: i32, TotalVtxCount: i32, DisplayPos: Vec2, DisplaySize: Vec2, FramebufferScale: Vec2, /// Clear(self: *DrawData) void pub const Clear = raw.ImDrawData_Clear; /// DeIndexAllBuffers(self: *DrawData) void pub const DeIndexAllBuffers = raw.ImDrawData_DeIndexAllBuffers; /// init(self: *DrawData) void pub const init = raw.ImDrawData_ImDrawData; /// ScaleClipRects(self: *DrawData, fb_scale: Vec2) void pub const ScaleClipRects = raw.ImDrawData_ScaleClipRects; /// deinit(self: *DrawData) void pub const deinit = raw.ImDrawData_destroy; }; pub const DrawList = extern struct { CmdBuffer: Vector(DrawCmd), IdxBuffer: Vector(DrawIdx), VtxBuffer: Vector(DrawVert), Flags: DrawListFlags align(4), _Data: ?*const DrawListSharedData, _OwnerName: ?[*:0]const u8, _VtxCurrentOffset: u32, _VtxCurrentIdx: u32, _VtxWritePtr: ?[*]DrawVert, _IdxWritePtr: ?[*]DrawIdx, _ClipRectStack: Vector(Vec4), _TextureIdStack: Vector(TextureID), _Path: Vector(Vec2), _Splitter: DrawListSplitter, /// AddBezierCurveExt(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32, thickness: f32, num_segments: i32) void pub const AddBezierCurveExt = raw.ImDrawList_AddBezierCurve; pub inline fn AddBezierCurve(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32, thickness: f32) void { return AddBezierCurveExt(self, p1, p2, p3, p4, col, thickness, 0); } /// AddCallback(self: *DrawList, callback: DrawCallback, callback_data: ?*c_void) void pub const AddCallback = raw.ImDrawList_AddCallback; /// AddCircleExt(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32, thickness: f32) void pub const AddCircleExt = raw.ImDrawList_AddCircle; pub inline fn AddCircle(self: *DrawList, center: Vec2, radius: f32, col: u32) void { return AddCircleExt(self, center, radius, col, 12, 1.0); } /// AddCircleFilledExt(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32) void pub const AddCircleFilledExt = raw.ImDrawList_AddCircleFilled; pub inline fn AddCircleFilled(self: *DrawList, center: Vec2, radius: f32, col: u32) void { return AddCircleFilledExt(self, center, radius, col, 12); } /// AddConvexPolyFilled(self: *DrawList, points: ?[*]const Vec2, num_points: i32, col: u32) void pub const AddConvexPolyFilled = raw.ImDrawList_AddConvexPolyFilled; /// AddDrawCmd(self: *DrawList) void pub const AddDrawCmd = raw.ImDrawList_AddDrawCmd; /// AddImageExt(self: *DrawList, user_texture_id: TextureID, p_min: Vec2, p_max: Vec2, uv_min: Vec2, uv_max: Vec2, col: u32) void pub const AddImageExt = raw.ImDrawList_AddImage; pub inline fn AddImage(self: *DrawList, user_texture_id: TextureID, p_min: Vec2, p_max: Vec2) void { return AddImageExt(self, user_texture_id, p_min, p_max, .{.x=0,.y=0}, .{.x=1,.y=1}, 0xFFFFFFFF); } /// AddImageQuadExt(self: *DrawList, user_texture_id: TextureID, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, uv1: Vec2, uv2: Vec2, uv3: Vec2, uv4: Vec2, col: u32) void pub const AddImageQuadExt = raw.ImDrawList_AddImageQuad; pub inline fn AddImageQuad(self: *DrawList, user_texture_id: TextureID, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2) void { return AddImageQuadExt(self, user_texture_id, p1, p2, p3, p4, .{.x=0,.y=0}, .{.x=1,.y=0}, .{.x=1,.y=1}, .{.x=0,.y=1}, 0xFFFFFFFF); } pub inline fn AddImageRoundedExt(self: *DrawList, user_texture_id: TextureID, p_min: Vec2, p_max: Vec2, uv_min: Vec2, uv_max: Vec2, col: u32, rounding: f32, rounding_corners: DrawCornerFlags) void { return raw.ImDrawList_AddImageRounded(self, user_texture_id, p_min, p_max, uv_min, uv_max, col, rounding, rounding_corners.toInt()); } pub inline fn AddImageRounded(self: *DrawList, user_texture_id: TextureID, p_min: Vec2, p_max: Vec2, uv_min: Vec2, uv_max: Vec2, col: u32, rounding: f32) void { return AddImageRoundedExt(self, user_texture_id, p_min, p_max, uv_min, uv_max, col, rounding, DrawCornerFlags.All); } /// AddLineExt(self: *DrawList, p1: Vec2, p2: Vec2, col: u32, thickness: f32) void pub const AddLineExt = raw.ImDrawList_AddLine; pub inline fn AddLine(self: *DrawList, p1: Vec2, p2: Vec2, col: u32) void { return AddLineExt(self, p1, p2, col, 1.0); } /// AddNgonExt(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32, thickness: f32) void pub const AddNgonExt = raw.ImDrawList_AddNgon; pub inline fn AddNgon(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32) void { return AddNgonExt(self, center, radius, col, num_segments, 1.0); } /// AddNgonFilled(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32) void pub const AddNgonFilled = raw.ImDrawList_AddNgonFilled; /// AddPolyline(self: *DrawList, points: ?[*]const Vec2, num_points: i32, col: u32, closed: bool, thickness: f32) void pub const AddPolyline = raw.ImDrawList_AddPolyline; /// AddQuadExt(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32, thickness: f32) void pub const AddQuadExt = raw.ImDrawList_AddQuad; pub inline fn AddQuad(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32) void { return AddQuadExt(self, p1, p2, p3, p4, col, 1.0); } /// AddQuadFilled(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32) void pub const AddQuadFilled = raw.ImDrawList_AddQuadFilled; pub inline fn AddRectExt(self: *DrawList, p_min: Vec2, p_max: Vec2, col: u32, rounding: f32, rounding_corners: DrawCornerFlags, thickness: f32) void { return raw.ImDrawList_AddRect(self, p_min, p_max, col, rounding, rounding_corners.toInt(), thickness); } pub inline fn AddRect(self: *DrawList, p_min: Vec2, p_max: Vec2, col: u32) void { return AddRectExt(self, p_min, p_max, col, 0.0, DrawCornerFlags.All, 1.0); } pub inline fn AddRectFilledExt(self: *DrawList, p_min: Vec2, p_max: Vec2, col: u32, rounding: f32, rounding_corners: DrawCornerFlags) void { return raw.ImDrawList_AddRectFilled(self, p_min, p_max, col, rounding, rounding_corners.toInt()); } pub inline fn AddRectFilled(self: *DrawList, p_min: Vec2, p_max: Vec2, col: u32) void { return AddRectFilledExt(self, p_min, p_max, col, 0.0, DrawCornerFlags.All); } /// AddRectFilledMultiColor(self: *DrawList, p_min: Vec2, p_max: Vec2, col_upr_left: u32, col_upr_right: u32, col_bot_right: u32, col_bot_left: u32) void pub const AddRectFilledMultiColor = raw.ImDrawList_AddRectFilledMultiColor; /// AddTextVec2Ext(self: *DrawList, pos: Vec2, col: u32, text_begin: ?[*]const u8, text_end: ?[*]const u8) void pub const AddTextVec2Ext = raw.ImDrawList_AddTextVec2; pub inline fn AddTextVec2(self: *DrawList, pos: Vec2, col: u32, text_begin: ?[*]const u8) void { return AddTextVec2Ext(self, pos, col, text_begin, null); } /// AddTextFontPtrExt(self: *DrawList, font: ?*const Font, font_size: f32, pos: Vec2, col: u32, text_begin: ?[*]const u8, text_end: ?[*]const u8, wrap_width: f32, cpu_fine_clip_rect: ?*const Vec4) void pub const AddTextFontPtrExt = raw.ImDrawList_AddTextFontPtr; pub inline fn AddTextFontPtr(self: *DrawList, font: ?*const Font, font_size: f32, pos: Vec2, col: u32, text_begin: ?[*]const u8) void { return AddTextFontPtrExt(self, font, font_size, pos, col, text_begin, null, 0.0, null); } /// AddTriangleExt(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, col: u32, thickness: f32) void pub const AddTriangleExt = raw.ImDrawList_AddTriangle; pub inline fn AddTriangle(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, col: u32) void { return AddTriangleExt(self, p1, p2, p3, col, 1.0); } /// AddTriangleFilled(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, col: u32) void pub const AddTriangleFilled = raw.ImDrawList_AddTriangleFilled; /// ChannelsMerge(self: *DrawList) void pub const ChannelsMerge = raw.ImDrawList_ChannelsMerge; /// ChannelsSetCurrent(self: *DrawList, n: i32) void pub const ChannelsSetCurrent = raw.ImDrawList_ChannelsSetCurrent; /// ChannelsSplit(self: *DrawList, count: i32) void pub const ChannelsSplit = raw.ImDrawList_ChannelsSplit; /// Clear(self: *DrawList) void pub const Clear = raw.ImDrawList_Clear; /// ClearFreeMemory(self: *DrawList) void pub const ClearFreeMemory = raw.ImDrawList_ClearFreeMemory; /// CloneOutput(self: *const DrawList) ?*DrawList pub const CloneOutput = raw.ImDrawList_CloneOutput; pub inline fn GetClipRectMax(self: *const DrawList) Vec2 { var out: Vec2 = undefined; raw.ImDrawList_GetClipRectMax_nonUDT(&out, self); return out; } pub inline fn GetClipRectMin(self: *const DrawList) Vec2 { var out: Vec2 = undefined; raw.ImDrawList_GetClipRectMin_nonUDT(&out, self); return out; } /// init(self: *DrawList, shared_data: ?*const DrawListSharedData) void pub const init = raw.ImDrawList_ImDrawList; /// PathArcToExt(self: *DrawList, center: Vec2, radius: f32, a_min: f32, a_max: f32, num_segments: i32) void pub const PathArcToExt = raw.ImDrawList_PathArcTo; pub inline fn PathArcTo(self: *DrawList, center: Vec2, radius: f32, a_min: f32, a_max: f32) void { return PathArcToExt(self, center, radius, a_min, a_max, 10); } /// PathArcToFast(self: *DrawList, center: Vec2, radius: f32, a_min_of_12: i32, a_max_of_12: i32) void pub const PathArcToFast = raw.ImDrawList_PathArcToFast; /// PathBezierCurveToExt(self: *DrawList, p2: Vec2, p3: Vec2, p4: Vec2, num_segments: i32) void pub const PathBezierCurveToExt = raw.ImDrawList_PathBezierCurveTo; pub inline fn PathBezierCurveTo(self: *DrawList, p2: Vec2, p3: Vec2, p4: Vec2) void { return PathBezierCurveToExt(self, p2, p3, p4, 0); } /// PathClear(self: *DrawList) void pub const PathClear = raw.ImDrawList_PathClear; /// PathFillConvex(self: *DrawList, col: u32) void pub const PathFillConvex = raw.ImDrawList_PathFillConvex; /// PathLineTo(self: *DrawList, pos: Vec2) void pub const PathLineTo = raw.ImDrawList_PathLineTo; /// PathLineToMergeDuplicate(self: *DrawList, pos: Vec2) void pub const PathLineToMergeDuplicate = raw.ImDrawList_PathLineToMergeDuplicate; pub inline fn PathRectExt(self: *DrawList, rect_min: Vec2, rect_max: Vec2, rounding: f32, rounding_corners: DrawCornerFlags) void { return raw.ImDrawList_PathRect(self, rect_min, rect_max, rounding, rounding_corners.toInt()); } pub inline fn PathRect(self: *DrawList, rect_min: Vec2, rect_max: Vec2) void { return PathRectExt(self, rect_min, rect_max, 0.0, DrawCornerFlags.All); } /// PathStrokeExt(self: *DrawList, col: u32, closed: bool, thickness: f32) void pub const PathStrokeExt = raw.ImDrawList_PathStroke; pub inline fn PathStroke(self: *DrawList, col: u32, closed: bool) void { return PathStrokeExt(self, col, closed, 1.0); } /// PopClipRect(self: *DrawList) void pub const PopClipRect = raw.ImDrawList_PopClipRect; /// PopTextureID(self: *DrawList) void pub const PopTextureID = raw.ImDrawList_PopTextureID; /// PrimQuadUV(self: *DrawList, a: Vec2, b: Vec2, c: Vec2, d: Vec2, uv_a: Vec2, uv_b: Vec2, uv_c: Vec2, uv_d: Vec2, col: u32) void pub const PrimQuadUV = raw.ImDrawList_PrimQuadUV; /// PrimRect(self: *DrawList, a: Vec2, b: Vec2, col: u32) void pub const PrimRect = raw.ImDrawList_PrimRect; /// PrimRectUV(self: *DrawList, a: Vec2, b: Vec2, uv_a: Vec2, uv_b: Vec2, col: u32) void pub const PrimRectUV = raw.ImDrawList_PrimRectUV; /// PrimReserve(self: *DrawList, idx_count: i32, vtx_count: i32) void pub const PrimReserve = raw.ImDrawList_PrimReserve; /// PrimUnreserve(self: *DrawList, idx_count: i32, vtx_count: i32) void pub const PrimUnreserve = raw.ImDrawList_PrimUnreserve; /// PrimVtx(self: *DrawList, pos: Vec2, uv: Vec2, col: u32) void pub const PrimVtx = raw.ImDrawList_PrimVtx; /// PrimWriteIdx(self: *DrawList, idx: DrawIdx) void pub const PrimWriteIdx = raw.ImDrawList_PrimWriteIdx; /// PrimWriteVtx(self: *DrawList, pos: Vec2, uv: Vec2, col: u32) void pub const PrimWriteVtx = raw.ImDrawList_PrimWriteVtx; /// PushClipRectExt(self: *DrawList, clip_rect_min: Vec2, clip_rect_max: Vec2, intersect_with_current_clip_rect: bool) void pub const PushClipRectExt = raw.ImDrawList_PushClipRect; pub inline fn PushClipRect(self: *DrawList, clip_rect_min: Vec2, clip_rect_max: Vec2) void { return PushClipRectExt(self, clip_rect_min, clip_rect_max, false); } /// PushClipRectFullScreen(self: *DrawList) void pub const PushClipRectFullScreen = raw.ImDrawList_PushClipRectFullScreen; /// PushTextureID(self: *DrawList, texture_id: TextureID) void pub const PushTextureID = raw.ImDrawList_PushTextureID; /// UpdateClipRect(self: *DrawList) void pub const UpdateClipRect = raw.ImDrawList_UpdateClipRect; /// UpdateTextureID(self: *DrawList) void pub const UpdateTextureID = raw.ImDrawList_UpdateTextureID; /// deinit(self: *DrawList) void pub const deinit = raw.ImDrawList_destroy; }; pub const DrawListSplitter = extern struct { _Current: i32, _Count: i32, _Channels: Vector(DrawChannel), /// Clear(self: *DrawListSplitter) void pub const Clear = raw.ImDrawListSplitter_Clear; /// ClearFreeMemory(self: *DrawListSplitter) void pub const ClearFreeMemory = raw.ImDrawListSplitter_ClearFreeMemory; /// init(self: *DrawListSplitter) void pub const init = raw.ImDrawListSplitter_ImDrawListSplitter; /// Merge(self: *DrawListSplitter, draw_list: ?*DrawList) void pub const Merge = raw.ImDrawListSplitter_Merge; /// SetCurrentChannel(self: *DrawListSplitter, draw_list: ?*DrawList, channel_idx: i32) void pub const SetCurrentChannel = raw.ImDrawListSplitter_SetCurrentChannel; /// Split(self: *DrawListSplitter, draw_list: ?*DrawList, count: i32) void pub const Split = raw.ImDrawListSplitter_Split; /// deinit(self: *DrawListSplitter) void pub const deinit = raw.ImDrawListSplitter_destroy; }; pub const DrawVert = extern struct { pos: Vec2, uv: Vec2, col: u32, }; pub const Font = extern struct { IndexAdvanceX: Vector(f32), FallbackAdvanceX: f32, FontSize: f32, IndexLookup: Vector(Wchar), Glyphs: Vector(FontGlyph), FallbackGlyph: ?*const FontGlyph, DisplayOffset: Vec2, ContainerAtlas: ?*FontAtlas, ConfigData: ?*const FontConfig, ConfigDataCount: i16, FallbackChar: Wchar, EllipsisChar: Wchar, DirtyLookupTables: bool, Scale: f32, Ascent: f32, Descent: f32, MetricsTotalSurface: i32, /// AddGlyph(self: *Font, c: Wchar, x0: f32, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, advance_x: f32) void pub const AddGlyph = raw.ImFont_AddGlyph; /// AddRemapCharExt(self: *Font, dst: Wchar, src: Wchar, overwrite_dst: bool) void pub const AddRemapCharExt = raw.ImFont_AddRemapChar; pub inline fn AddRemapChar(self: *Font, dst: Wchar, src: Wchar) void { return AddRemapCharExt(self, dst, src, true); } /// BuildLookupTable(self: *Font) void pub const BuildLookupTable = raw.ImFont_BuildLookupTable; pub inline fn CalcTextSizeAExt(self: *const Font, size: f32, max_width: f32, wrap_width: f32, text_begin: ?[*]const u8, text_end: ?[*]const u8, remaining: ?*?[*:0]const u8) Vec2 { var out: Vec2 = undefined; raw.ImFont_CalcTextSizeA_nonUDT(&out, self, size, max_width, wrap_width, text_begin, text_end, remaining); return out; } pub inline fn CalcTextSizeA(self: *const Font, size: f32, max_width: f32, wrap_width: f32, text_begin: ?[*]const u8) Vec2 { return CalcTextSizeAExt(self, size, max_width, wrap_width, text_begin, null, null); } /// CalcWordWrapPositionA(self: *const Font, scale: f32, text: ?[*]const u8, text_end: ?[*]const u8, wrap_width: f32) ?[*]const u8 pub const CalcWordWrapPositionA = raw.ImFont_CalcWordWrapPositionA; /// ClearOutputData(self: *Font) void pub const ClearOutputData = raw.ImFont_ClearOutputData; /// FindGlyph(self: *const Font, c: Wchar) ?*const FontGlyph pub const FindGlyph = raw.ImFont_FindGlyph; /// FindGlyphNoFallback(self: *const Font, c: Wchar) ?*const FontGlyph pub const FindGlyphNoFallback = raw.ImFont_FindGlyphNoFallback; /// GetCharAdvance(self: *const Font, c: Wchar) f32 pub const GetCharAdvance = raw.ImFont_GetCharAdvance; /// GetDebugName(self: *const Font) ?[*:0]const u8 pub const GetDebugName = raw.ImFont_GetDebugName; /// GrowIndex(self: *Font, new_size: i32) void pub const GrowIndex = raw.ImFont_GrowIndex; /// init(self: *Font) void pub const init = raw.ImFont_ImFont; /// IsLoaded(self: *const Font) bool pub const IsLoaded = raw.ImFont_IsLoaded; /// RenderChar(self: *const Font, draw_list: ?*DrawList, size: f32, pos: Vec2, col: u32, c: Wchar) void pub const RenderChar = raw.ImFont_RenderChar; /// RenderTextExt(self: *const Font, draw_list: ?*DrawList, size: f32, pos: Vec2, col: u32, clip_rect: Vec4, text_begin: ?[*]const u8, text_end: ?[*]const u8, wrap_width: f32, cpu_fine_clip: bool) void pub const RenderTextExt = raw.ImFont_RenderText; pub inline fn RenderText(self: *const Font, draw_list: ?*DrawList, size: f32, pos: Vec2, col: u32, clip_rect: Vec4, text_begin: ?[*]const u8, text_end: ?[*]const u8) void { return RenderTextExt(self, draw_list, size, pos, col, clip_rect, text_begin, text_end, 0.0, false); } /// SetFallbackChar(self: *Font, c: Wchar) void pub const SetFallbackChar = raw.ImFont_SetFallbackChar; /// deinit(self: *Font) void pub const deinit = raw.ImFont_destroy; }; pub const FontAtlas = extern struct { Locked: bool, Flags: FontAtlasFlags align(4), TexID: TextureID, TexDesiredWidth: i32, TexGlyphPadding: i32, TexPixelsAlpha8: ?[*]u8, TexPixelsRGBA32: ?[*]u32, TexWidth: i32, TexHeight: i32, TexUvScale: Vec2, TexUvWhitePixel: Vec2, Fonts: Vector(*Font), CustomRects: Vector(FontAtlasCustomRect), ConfigData: Vector(FontConfig), CustomRectIds: [1]i32, /// AddCustomRectFontGlyphExt(self: *FontAtlas, font: ?*Font, id: Wchar, width: i32, height: i32, advance_x: f32, offset: Vec2) i32 pub const AddCustomRectFontGlyphExt = raw.ImFontAtlas_AddCustomRectFontGlyph; pub inline fn AddCustomRectFontGlyph(self: *FontAtlas, font: ?*Font, id: Wchar, width: i32, height: i32, advance_x: f32) i32 { return AddCustomRectFontGlyphExt(self, font, id, width, height, advance_x, .{.x=0,.y=0}); } /// AddCustomRectRegular(self: *FontAtlas, id: u32, width: i32, height: i32) i32 pub const AddCustomRectRegular = raw.ImFontAtlas_AddCustomRectRegular; /// AddFont(self: *FontAtlas, font_cfg: ?*const FontConfig) ?*Font pub const AddFont = raw.ImFontAtlas_AddFont; /// AddFontDefaultExt(self: *FontAtlas, font_cfg: ?*const FontConfig) ?*Font pub const AddFontDefaultExt = raw.ImFontAtlas_AddFontDefault; pub inline fn AddFontDefault(self: *FontAtlas) ?*Font { return AddFontDefaultExt(self, null); } /// AddFontFromFileTTFExt(self: *FontAtlas, filename: ?[*:0]const u8, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) ?*Font pub const AddFontFromFileTTFExt = raw.ImFontAtlas_AddFontFromFileTTF; pub inline fn AddFontFromFileTTF(self: *FontAtlas, filename: ?[*:0]const u8, size_pixels: f32) ?*Font { return AddFontFromFileTTFExt(self, filename, size_pixels, null, null); } /// AddFontFromMemoryCompressedBase85TTFExt(self: *FontAtlas, compressed_font_data_base85: ?[*]const u8, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) ?*Font pub const AddFontFromMemoryCompressedBase85TTFExt = raw.ImFontAtlas_AddFontFromMemoryCompressedBase85TTF; pub inline fn AddFontFromMemoryCompressedBase85TTF(self: *FontAtlas, compressed_font_data_base85: ?[*]const u8, size_pixels: f32) ?*Font { return AddFontFromMemoryCompressedBase85TTFExt(self, compressed_font_data_base85, size_pixels, null, null); } /// AddFontFromMemoryCompressedTTFExt(self: *FontAtlas, compressed_font_data: ?*const c_void, compressed_font_size: i32, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) ?*Font pub const AddFontFromMemoryCompressedTTFExt = raw.ImFontAtlas_AddFontFromMemoryCompressedTTF; pub inline fn AddFontFromMemoryCompressedTTF(self: *FontAtlas, compressed_font_data: ?*const c_void, compressed_font_size: i32, size_pixels: f32) ?*Font { return AddFontFromMemoryCompressedTTFExt(self, compressed_font_data, compressed_font_size, size_pixels, null, null); } /// AddFontFromMemoryTTFExt(self: *FontAtlas, font_data: ?*c_void, font_size: i32, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) ?*Font pub const AddFontFromMemoryTTFExt = raw.ImFontAtlas_AddFontFromMemoryTTF; pub inline fn AddFontFromMemoryTTF(self: *FontAtlas, font_data: ?*c_void, font_size: i32, size_pixels: f32) ?*Font { return AddFontFromMemoryTTFExt(self, font_data, font_size, size_pixels, null, null); } /// Build(self: *FontAtlas) bool pub const Build = raw.ImFontAtlas_Build; /// CalcCustomRectUV(self: *const FontAtlas, rect: ?*const FontAtlasCustomRect, out_uv_min: ?*Vec2, out_uv_max: ?*Vec2) void pub const CalcCustomRectUV = raw.ImFontAtlas_CalcCustomRectUV; /// Clear(self: *FontAtlas) void pub const Clear = raw.ImFontAtlas_Clear; /// ClearFonts(self: *FontAtlas) void pub const ClearFonts = raw.ImFontAtlas_ClearFonts; /// ClearInputData(self: *FontAtlas) void pub const ClearInputData = raw.ImFontAtlas_ClearInputData; /// ClearTexData(self: *FontAtlas) void pub const ClearTexData = raw.ImFontAtlas_ClearTexData; /// GetCustomRectByIndex(self: *const FontAtlas, index: i32) ?*const FontAtlasCustomRect pub const GetCustomRectByIndex = raw.ImFontAtlas_GetCustomRectByIndex; /// GetGlyphRangesChineseFull(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesChineseFull = raw.ImFontAtlas_GetGlyphRangesChineseFull; /// GetGlyphRangesChineseSimplifiedCommon(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesChineseSimplifiedCommon = raw.ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon; /// GetGlyphRangesCyrillic(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesCyrillic = raw.ImFontAtlas_GetGlyphRangesCyrillic; /// GetGlyphRangesDefault(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesDefault = raw.ImFontAtlas_GetGlyphRangesDefault; /// GetGlyphRangesJapanese(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesJapanese = raw.ImFontAtlas_GetGlyphRangesJapanese; /// GetGlyphRangesKorean(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesKorean = raw.ImFontAtlas_GetGlyphRangesKorean; /// GetGlyphRangesThai(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesThai = raw.ImFontAtlas_GetGlyphRangesThai; /// GetGlyphRangesVietnamese(self: *FontAtlas) ?*const Wchar pub const GetGlyphRangesVietnamese = raw.ImFontAtlas_GetGlyphRangesVietnamese; /// GetMouseCursorTexData(self: *FontAtlas, cursor: MouseCursor, out_offset: ?*Vec2, out_size: ?*Vec2, out_uv_border: *[2]Vec2, out_uv_fill: *[2]Vec2) bool pub const GetMouseCursorTexData = raw.ImFontAtlas_GetMouseCursorTexData; /// GetTexDataAsAlpha8Ext(self: *FontAtlas, out_pixels: *?[*]u8, out_width: *i32, out_height: *i32, out_bytes_per_pixel: ?*i32) void pub const GetTexDataAsAlpha8Ext = raw.ImFontAtlas_GetTexDataAsAlpha8; pub inline fn GetTexDataAsAlpha8(self: *FontAtlas, out_pixels: *?[*]u8, out_width: *i32, out_height: *i32) void { return GetTexDataAsAlpha8Ext(self, out_pixels, out_width, out_height, null); } /// GetTexDataAsRGBA32Ext(self: *FontAtlas, out_pixels: *?[*]u8, out_width: *i32, out_height: *i32, out_bytes_per_pixel: ?*i32) void pub const GetTexDataAsRGBA32Ext = raw.ImFontAtlas_GetTexDataAsRGBA32; pub inline fn GetTexDataAsRGBA32(self: *FontAtlas, out_pixels: *?[*]u8, out_width: *i32, out_height: *i32) void { return GetTexDataAsRGBA32Ext(self, out_pixels, out_width, out_height, null); } /// init(self: *FontAtlas) void pub const init = raw.ImFontAtlas_ImFontAtlas; /// IsBuilt(self: *const FontAtlas) bool pub const IsBuilt = raw.ImFontAtlas_IsBuilt; /// SetTexID(self: *FontAtlas, id: TextureID) void pub const SetTexID = raw.ImFontAtlas_SetTexID; /// deinit(self: *FontAtlas) void pub const deinit = raw.ImFontAtlas_destroy; }; pub const FontAtlasCustomRect = extern struct { ID: u32, Width: u16, Height: u16, X: u16, Y: u16, GlyphAdvanceX: f32, GlyphOffset: Vec2, Font: ?*Font, /// init(self: *FontAtlasCustomRect) void pub const init = raw.ImFontAtlasCustomRect_ImFontAtlasCustomRect; /// IsPacked(self: *const FontAtlasCustomRect) bool pub const IsPacked = raw.ImFontAtlasCustomRect_IsPacked; /// deinit(self: *FontAtlasCustomRect) void pub const deinit = raw.ImFontAtlasCustomRect_destroy; }; pub const FontConfig = extern struct { FontData: ?*c_void, FontDataSize: i32, FontDataOwnedByAtlas: bool, FontNo: i32, SizePixels: f32, OversampleH: i32, OversampleV: i32, PixelSnapH: bool, GlyphExtraSpacing: Vec2, GlyphOffset: Vec2, GlyphRanges: ?[*:0]const Wchar, GlyphMinAdvanceX: f32, GlyphMaxAdvanceX: f32, MergeMode: bool, RasterizerFlags: u32, RasterizerMultiply: f32, EllipsisChar: Wchar, Name: [40]u8, DstFont: ?*Font, /// init(self: *FontConfig) void pub const init = raw.ImFontConfig_ImFontConfig; /// deinit(self: *FontConfig) void pub const deinit = raw.ImFontConfig_destroy; }; pub const FontGlyph = extern struct { Codepoint: Wchar, AdvanceX: f32, X0: f32, Y0: f32, X1: f32, Y1: f32, U0: f32, V0: f32, U1: f32, V1: f32, }; pub const FontGlyphRangesBuilder = extern struct { UsedChars: Vector(u32), /// AddChar(self: *FontGlyphRangesBuilder, c: Wchar) void pub const AddChar = raw.ImFontGlyphRangesBuilder_AddChar; /// AddRanges(self: *FontGlyphRangesBuilder, ranges: ?[*:0]const Wchar) void pub const AddRanges = raw.ImFontGlyphRangesBuilder_AddRanges; /// AddTextExt(self: *FontGlyphRangesBuilder, text: ?[*]const u8, text_end: ?[*]const u8) void pub const AddTextExt = raw.ImFontGlyphRangesBuilder_AddText; pub inline fn AddText(self: *FontGlyphRangesBuilder, text: ?[*]const u8) void { return AddTextExt(self, text, null); } /// BuildRanges(self: *FontGlyphRangesBuilder, out_ranges: *Vector(Wchar)) void pub const BuildRanges = raw.ImFontGlyphRangesBuilder_BuildRanges; /// Clear(self: *FontGlyphRangesBuilder) void pub const Clear = raw.ImFontGlyphRangesBuilder_Clear; /// GetBit(self: *const FontGlyphRangesBuilder, n: i32) bool pub const GetBit = raw.ImFontGlyphRangesBuilder_GetBit; /// init(self: *FontGlyphRangesBuilder) void pub const init = raw.ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder; /// SetBit(self: *FontGlyphRangesBuilder, n: i32) void pub const SetBit = raw.ImFontGlyphRangesBuilder_SetBit; /// deinit(self: *FontGlyphRangesBuilder) void pub const deinit = raw.ImFontGlyphRangesBuilder_destroy; }; pub const IO = extern struct { ConfigFlags: ConfigFlags align(4), BackendFlags: BackendFlags align(4), DisplaySize: Vec2, DeltaTime: f32, IniSavingRate: f32, IniFilename: ?[*:0]const u8, LogFilename: ?[*:0]const u8, MouseDoubleClickTime: f32, MouseDoubleClickMaxDist: f32, MouseDragThreshold: f32, KeyMap: [Key.COUNT]i32, KeyRepeatDelay: f32, KeyRepeatRate: f32, UserData: ?*c_void, Fonts: ?*FontAtlas, FontGlobalScale: f32, FontAllowUserScaling: bool, FontDefault: ?*Font, DisplayFramebufferScale: Vec2, MouseDrawCursor: bool, ConfigMacOSXBehaviors: bool, ConfigInputTextCursorBlink: bool, ConfigWindowsResizeFromEdges: bool, ConfigWindowsMoveFromTitleBarOnly: bool, ConfigWindowsMemoryCompactTimer: f32, BackendPlatformName: ?[*:0]const u8, BackendRendererName: ?[*:0]const u8, BackendPlatformUserData: ?*c_void, BackendRendererUserData: ?*c_void, BackendLanguageUserData: ?*c_void, GetClipboardTextFn: ?fn (user_data: ?*c_void) callconv(.C) ?[*:0]const u8, SetClipboardTextFn: ?fn (user_data: ?*c_void, text: ?[*:0]const u8) callconv(.C) void, ClipboardUserData: ?*c_void, ImeSetInputScreenPosFn: ?fn (x: i32, y: i32) callconv(.C) void, ImeWindowHandle: ?*c_void, RenderDrawListsFnUnused: ?*c_void, MousePos: Vec2, MouseDown: [5]bool, MouseWheel: f32, MouseWheelH: f32, KeyCtrl: bool, KeyShift: bool, KeyAlt: bool, KeySuper: bool, KeysDown: [512]bool, NavInputs: [NavInput.COUNT]f32, WantCaptureMouse: bool, WantCaptureKeyboard: bool, WantTextInput: bool, WantSetMousePos: bool, WantSaveIniSettings: bool, NavActive: bool, NavVisible: bool, Framerate: f32, MetricsRenderVertices: i32, MetricsRenderIndices: i32, MetricsRenderWindows: i32, MetricsActiveWindows: i32, MetricsActiveAllocations: i32, MouseDelta: Vec2, MousePosPrev: Vec2, MouseClickedPos: [5]Vec2, MouseClickedTime: [5]f64, MouseClicked: [5]bool, MouseDoubleClicked: [5]bool, MouseReleased: [5]bool, MouseDownOwned: [5]bool, MouseDownWasDoubleClick: [5]bool, MouseDownDuration: [5]f32, MouseDownDurationPrev: [5]f32, MouseDragMaxDistanceAbs: [5]Vec2, MouseDragMaxDistanceSqr: [5]f32, KeysDownDuration: [512]f32, KeysDownDurationPrev: [512]f32, NavInputsDownDuration: [NavInput.COUNT]f32, NavInputsDownDurationPrev: [NavInput.COUNT]f32, InputQueueCharacters: Vector(Wchar), /// AddInputCharacter(self: *IO, c: u32) void pub const AddInputCharacter = raw.ImGuiIO_AddInputCharacter; /// AddInputCharactersUTF8(self: *IO, str: ?[*:0]const u8) void pub const AddInputCharactersUTF8 = raw.ImGuiIO_AddInputCharactersUTF8; /// ClearInputCharacters(self: *IO) void pub const ClearInputCharacters = raw.ImGuiIO_ClearInputCharacters; /// init(self: *IO) void pub const init = raw.ImGuiIO_ImGuiIO; /// deinit(self: *IO) void pub const deinit = raw.ImGuiIO_destroy; }; pub const InputTextCallbackData = extern struct { EventFlag: InputTextFlags align(4), Flags: InputTextFlags align(4), UserData: ?*c_void, EventChar: Wchar, EventKey: Key, Buf: ?[*]u8, BufTextLen: i32, BufSize: i32, BufDirty: bool, CursorPos: i32, SelectionStart: i32, SelectionEnd: i32, /// DeleteChars(self: *InputTextCallbackData, pos: i32, bytes_count: i32) void pub const DeleteChars = raw.ImGuiInputTextCallbackData_DeleteChars; /// HasSelection(self: *const InputTextCallbackData) bool pub const HasSelection = raw.ImGuiInputTextCallbackData_HasSelection; /// init(self: *InputTextCallbackData) void pub const init = raw.ImGuiInputTextCallbackData_ImGuiInputTextCallbackData; /// InsertCharsExt(self: *InputTextCallbackData, pos: i32, text: ?[*]const u8, text_end: ?[*]const u8) void pub const InsertCharsExt = raw.ImGuiInputTextCallbackData_InsertChars; pub inline fn InsertChars(self: *InputTextCallbackData, pos: i32, text: ?[*]const u8) void { return InsertCharsExt(self, pos, text, null); } /// deinit(self: *InputTextCallbackData) void pub const deinit = raw.ImGuiInputTextCallbackData_destroy; }; pub const ListClipper = extern struct { DisplayStart: i32, DisplayEnd: i32, ItemsCount: i32, StepNo: i32, ItemsHeight: f32, StartPosY: f32, /// BeginExt(self: *ListClipper, items_count: i32, items_height: f32) void pub const BeginExt = raw.ImGuiListClipper_Begin; pub inline fn Begin(self: *ListClipper, items_count: i32) void { return BeginExt(self, items_count, -1.0); } /// End(self: *ListClipper) void pub const End = raw.ImGuiListClipper_End; /// initExt(self: *ListClipper, items_count: i32, items_height: f32) void pub const initExt = raw.ImGuiListClipper_ImGuiListClipper; pub inline fn init(self: *ListClipper) void { return initExt(self, -1, -1.0); } /// Step(self: *ListClipper) bool pub const Step = raw.ImGuiListClipper_Step; /// deinit(self: *ListClipper) void pub const deinit = raw.ImGuiListClipper_destroy; }; pub const OnceUponAFrame = extern struct { RefFrame: i32, /// init(self: *OnceUponAFrame) void pub const init = raw.ImGuiOnceUponAFrame_ImGuiOnceUponAFrame; /// deinit(self: *OnceUponAFrame) void pub const deinit = raw.ImGuiOnceUponAFrame_destroy; }; pub const Payload = extern struct { Data: ?*c_void, DataSize: i32, SourceId: ID, SourceParentId: ID, DataFrameCount: i32, DataType: [32+1]u8, Preview: bool, Delivery: bool, /// Clear(self: *Payload) void pub const Clear = raw.ImGuiPayload_Clear; /// init(self: *Payload) void pub const init = raw.ImGuiPayload_ImGuiPayload; /// IsDataType(self: *const Payload, kind: ?[*:0]const u8) bool pub const IsDataType = raw.ImGuiPayload_IsDataType; /// IsDelivery(self: *const Payload) bool pub const IsDelivery = raw.ImGuiPayload_IsDelivery; /// IsPreview(self: *const Payload) bool pub const IsPreview = raw.ImGuiPayload_IsPreview; /// deinit(self: *Payload) void pub const deinit = raw.ImGuiPayload_destroy; }; pub const SizeCallbackData = extern struct { UserData: ?*c_void, Pos: Vec2, CurrentSize: Vec2, DesiredSize: Vec2, }; pub const Storage = extern struct { Data: Vector(StoragePair), /// BuildSortByKey(self: *Storage) void pub const BuildSortByKey = raw.ImGuiStorage_BuildSortByKey; /// Clear(self: *Storage) void pub const Clear = raw.ImGuiStorage_Clear; /// GetBoolExt(self: *const Storage, key: ID, default_val: bool) bool pub const GetBoolExt = raw.ImGuiStorage_GetBool; pub inline fn GetBool(self: *const Storage, key: ID) bool { return GetBoolExt(self, key, false); } /// GetBoolRefExt(self: *Storage, key: ID, default_val: bool) ?*bool pub const GetBoolRefExt = raw.ImGuiStorage_GetBoolRef; pub inline fn GetBoolRef(self: *Storage, key: ID) ?*bool { return GetBoolRefExt(self, key, false); } /// GetFloatExt(self: *const Storage, key: ID, default_val: f32) f32 pub const GetFloatExt = raw.ImGuiStorage_GetFloat; pub inline fn GetFloat(self: *const Storage, key: ID) f32 { return GetFloatExt(self, key, 0.0); } /// GetFloatRefExt(self: *Storage, key: ID, default_val: f32) ?*f32 pub const GetFloatRefExt = raw.ImGuiStorage_GetFloatRef; pub inline fn GetFloatRef(self: *Storage, key: ID) ?*f32 { return GetFloatRefExt(self, key, 0.0); } /// GetIntExt(self: *const Storage, key: ID, default_val: i32) i32 pub const GetIntExt = raw.ImGuiStorage_GetInt; pub inline fn GetInt(self: *const Storage, key: ID) i32 { return GetIntExt(self, key, 0); } /// GetIntRefExt(self: *Storage, key: ID, default_val: i32) ?*i32 pub const GetIntRefExt = raw.ImGuiStorage_GetIntRef; pub inline fn GetIntRef(self: *Storage, key: ID) ?*i32 { return GetIntRefExt(self, key, 0); } /// GetVoidPtr(self: *const Storage, key: ID) ?*c_void pub const GetVoidPtr = raw.ImGuiStorage_GetVoidPtr; /// GetVoidPtrRefExt(self: *Storage, key: ID, default_val: ?*c_void) ?*?*c_void pub const GetVoidPtrRefExt = raw.ImGuiStorage_GetVoidPtrRef; pub inline fn GetVoidPtrRef(self: *Storage, key: ID) ?*?*c_void { return GetVoidPtrRefExt(self, key, null); } /// SetAllInt(self: *Storage, val: i32) void pub const SetAllInt = raw.ImGuiStorage_SetAllInt; /// SetBool(self: *Storage, key: ID, val: bool) void pub const SetBool = raw.ImGuiStorage_SetBool; /// SetFloat(self: *Storage, key: ID, val: f32) void pub const SetFloat = raw.ImGuiStorage_SetFloat; /// SetInt(self: *Storage, key: ID, val: i32) void pub const SetInt = raw.ImGuiStorage_SetInt; /// SetVoidPtr(self: *Storage, key: ID, val: ?*c_void) void pub const SetVoidPtr = raw.ImGuiStorage_SetVoidPtr; }; pub const StoragePair = extern struct { key: ID, value: extern union { val_i: i32, val_f: f32, val_p: ?*c_void }, /// initInt(self: *StoragePair, _key: ID, _val_i: i32) void pub const initInt = raw.ImGuiStoragePair_ImGuiStoragePairInt; /// initFloat(self: *StoragePair, _key: ID, _val_f: f32) void pub const initFloat = raw.ImGuiStoragePair_ImGuiStoragePairFloat; /// initPtr(self: *StoragePair, _key: ID, _val_p: ?*c_void) void pub const initPtr = raw.ImGuiStoragePair_ImGuiStoragePairPtr; /// deinit(self: *StoragePair) void pub const deinit = raw.ImGuiStoragePair_destroy; }; pub const Style = extern struct { Alpha: f32, WindowPadding: Vec2, WindowRounding: f32, WindowBorderSize: f32, WindowMinSize: Vec2, WindowTitleAlign: Vec2, WindowMenuButtonPosition: Dir, ChildRounding: f32, ChildBorderSize: f32, PopupRounding: f32, PopupBorderSize: f32, FramePadding: Vec2, FrameRounding: f32, FrameBorderSize: f32, ItemSpacing: Vec2, ItemInnerSpacing: Vec2, TouchExtraPadding: Vec2, IndentSpacing: f32, ColumnsMinSpacing: f32, ScrollbarSize: f32, ScrollbarRounding: f32, GrabMinSize: f32, GrabRounding: f32, TabRounding: f32, TabBorderSize: f32, ColorButtonPosition: Dir, ButtonTextAlign: Vec2, SelectableTextAlign: Vec2, DisplayWindowPadding: Vec2, DisplaySafeAreaPadding: Vec2, MouseCursorScale: f32, AntiAliasedLines: bool, AntiAliasedFill: bool, CurveTessellationTol: f32, CircleSegmentMaxError: f32, Colors: [Col.COUNT]Vec4, /// init(self: *Style) void pub const init = raw.ImGuiStyle_ImGuiStyle; /// ScaleAllSizes(self: *Style, scale_factor: f32) void pub const ScaleAllSizes = raw.ImGuiStyle_ScaleAllSizes; /// deinit(self: *Style) void pub const deinit = raw.ImGuiStyle_destroy; }; pub const TextBuffer = extern struct { Buf: Vector(u8), /// init(self: *TextBuffer) void pub const init = raw.ImGuiTextBuffer_ImGuiTextBuffer; /// appendExt(self: *TextBuffer, str: ?[*]const u8, str_end: ?[*]const u8) void pub const appendExt = raw.ImGuiTextBuffer_append; pub inline fn append(self: *TextBuffer, str: ?[*]const u8) void { return appendExt(self, str, null); } /// appendf(self: *TextBuffer, fmt: ?[*:0]const u8, ...: ...) void pub const appendf = raw.ImGuiTextBuffer_appendf; /// begin(self: *const TextBuffer) [*]const u8 pub const begin = raw.ImGuiTextBuffer_begin; /// c_str(self: *const TextBuffer) [*:0]const u8 pub const c_str = raw.ImGuiTextBuffer_c_str; /// clear(self: *TextBuffer) void pub const clear = raw.ImGuiTextBuffer_clear; /// deinit(self: *TextBuffer) void pub const deinit = raw.ImGuiTextBuffer_destroy; /// empty(self: *const TextBuffer) bool pub const empty = raw.ImGuiTextBuffer_empty; /// end(self: *const TextBuffer) [*]const u8 pub const end = raw.ImGuiTextBuffer_end; /// reserve(self: *TextBuffer, capacity: i32) void pub const reserve = raw.ImGuiTextBuffer_reserve; /// size(self: *const TextBuffer) i32 pub const size = raw.ImGuiTextBuffer_size; }; pub const TextFilter = extern struct { InputBuf: [256]u8, Filters: Vector(TextRange), CountGrep: i32, /// Build(self: *TextFilter) void pub const Build = raw.ImGuiTextFilter_Build; /// Clear(self: *TextFilter) void pub const Clear = raw.ImGuiTextFilter_Clear; /// DrawExt(self: *TextFilter, label: ?[*:0]const u8, width: f32) bool pub const DrawExt = raw.ImGuiTextFilter_Draw; pub inline fn Draw(self: *TextFilter) bool { return DrawExt(self, "Filter(inc,-exc)", 0.0); } /// initExt(self: *TextFilter, default_filter: ?[*:0]const u8) void pub const initExt = raw.ImGuiTextFilter_ImGuiTextFilter; pub inline fn init(self: *TextFilter) void { return initExt(self, ""); } /// IsActive(self: *const TextFilter) bool pub const IsActive = raw.ImGuiTextFilter_IsActive; /// PassFilterExt(self: *const TextFilter, text: ?[*]const u8, text_end: ?[*]const u8) bool pub const PassFilterExt = raw.ImGuiTextFilter_PassFilter; pub inline fn PassFilter(self: *const TextFilter, text: ?[*]const u8) bool { return PassFilterExt(self, text, null); } /// deinit(self: *TextFilter) void pub const deinit = raw.ImGuiTextFilter_destroy; }; pub const TextRange = extern struct { b: ?[*]const u8, e: ?[*]const u8, /// init(self: *TextRange) void pub const init = raw.ImGuiTextRange_ImGuiTextRange; /// initStr(self: *TextRange, _b: ?[*]const u8, _e: ?[*]const u8) void pub const initStr = raw.ImGuiTextRange_ImGuiTextRangeStr; /// deinit(self: *TextRange) void pub const deinit = raw.ImGuiTextRange_destroy; /// empty(self: *const TextRange) bool pub const empty = raw.ImGuiTextRange_empty; /// split(self: *const TextRange, separator: u8, out: ?*Vector(TextRange)) void pub const split = raw.ImGuiTextRange_split; }; const math = @import("math"); pub const Vec2 = math.vector.glm.Vec2; pub const Vec4 = math.vector.glm.Vec4; // pub const Vec2 = extern struct { // x: f32, // y: f32, // /// init(self: *Vec2) void // pub const init = raw.ImVec2_ImVec2; // /// initFloat(self: *Vec2, _x: f32, _y: f32) void // pub const initFloat = raw.ImVec2_ImVec2Float; // /// deinit(self: *Vec2) void // pub const deinit = raw.ImVec2_destroy; // }; // pub const Vec4 = extern struct { // x: f32, // y: f32, // z: f32, // w: f32, // /// init(self: *Vec4) void // pub const init = raw.ImVec4_ImVec4; // /// initFloat(self: *Vec4, _x: f32, _y: f32, _z: f32, _w: f32) void // pub const initFloat = raw.ImVec4_ImVec4Float; // /// deinit(self: *Vec4) void // pub const deinit = raw.ImVec4_destroy; // }; const FTABLE_ImVector_ImDrawChannel = struct { /// init(self: *Vector(DrawChannel)) void pub const init = raw.ImVector_ImDrawChannel_ImVector_ImDrawChannel; /// initVector(self: *Vector(DrawChannel), src: Vector(DrawChannel)) void pub const initVector = raw.ImVector_ImDrawChannel_ImVector_ImDrawChannelVector; /// _grow_capacity(self: *const Vector(DrawChannel), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImDrawChannel__grow_capacity; /// back(self: *Vector(DrawChannel)) *DrawChannel pub const back = raw.ImVector_ImDrawChannel_back; /// back_const(self: *const Vector(DrawChannel)) *const DrawChannel pub const back_const = raw.ImVector_ImDrawChannel_back_const; /// begin(self: *Vector(DrawChannel)) [*]DrawChannel pub const begin = raw.ImVector_ImDrawChannel_begin; /// begin_const(self: *const Vector(DrawChannel)) [*]const DrawChannel pub const begin_const = raw.ImVector_ImDrawChannel_begin_const; /// capacity(self: *const Vector(DrawChannel)) i32 pub const capacity = raw.ImVector_ImDrawChannel_capacity; /// clear(self: *Vector(DrawChannel)) void pub const clear = raw.ImVector_ImDrawChannel_clear; /// deinit(self: *Vector(DrawChannel)) void pub const deinit = raw.ImVector_ImDrawChannel_destroy; /// empty(self: *const Vector(DrawChannel)) bool pub const empty = raw.ImVector_ImDrawChannel_empty; /// end(self: *Vector(DrawChannel)) [*]DrawChannel pub const end = raw.ImVector_ImDrawChannel_end; /// end_const(self: *const Vector(DrawChannel)) [*]const DrawChannel pub const end_const = raw.ImVector_ImDrawChannel_end_const; /// erase(self: *Vector(DrawChannel), it: [*]const DrawChannel) [*]DrawChannel pub const erase = raw.ImVector_ImDrawChannel_erase; /// eraseTPtr(self: *Vector(DrawChannel), it: [*]const DrawChannel, it_last: [*]const DrawChannel) [*]DrawChannel pub const eraseTPtr = raw.ImVector_ImDrawChannel_eraseTPtr; /// erase_unsorted(self: *Vector(DrawChannel), it: [*]const DrawChannel) [*]DrawChannel pub const erase_unsorted = raw.ImVector_ImDrawChannel_erase_unsorted; /// front(self: *Vector(DrawChannel)) *DrawChannel pub const front = raw.ImVector_ImDrawChannel_front; /// front_const(self: *const Vector(DrawChannel)) *const DrawChannel pub const front_const = raw.ImVector_ImDrawChannel_front_const; /// index_from_ptr(self: *const Vector(DrawChannel), it: [*]const DrawChannel) i32 pub const index_from_ptr = raw.ImVector_ImDrawChannel_index_from_ptr; /// insert(self: *Vector(DrawChannel), it: [*]const DrawChannel, v: DrawChannel) [*]DrawChannel pub const insert = raw.ImVector_ImDrawChannel_insert; /// pop_back(self: *Vector(DrawChannel)) void pub const pop_back = raw.ImVector_ImDrawChannel_pop_back; /// push_back(self: *Vector(DrawChannel), v: DrawChannel) void pub const push_back = raw.ImVector_ImDrawChannel_push_back; /// push_front(self: *Vector(DrawChannel), v: DrawChannel) void pub const push_front = raw.ImVector_ImDrawChannel_push_front; /// reserve(self: *Vector(DrawChannel), new_capacity: i32) void pub const reserve = raw.ImVector_ImDrawChannel_reserve; /// resize(self: *Vector(DrawChannel), new_size: i32) void pub const resize = raw.ImVector_ImDrawChannel_resize; /// resizeT(self: *Vector(DrawChannel), new_size: i32, v: DrawChannel) void pub const resizeT = raw.ImVector_ImDrawChannel_resizeT; /// shrink(self: *Vector(DrawChannel), new_size: i32) void pub const shrink = raw.ImVector_ImDrawChannel_shrink; /// size(self: *const Vector(DrawChannel)) i32 pub const size = raw.ImVector_ImDrawChannel_size; /// size_in_bytes(self: *const Vector(DrawChannel)) i32 pub const size_in_bytes = raw.ImVector_ImDrawChannel_size_in_bytes; /// swap(self: *Vector(DrawChannel), rhs: *Vector(DrawChannel)) void pub const swap = raw.ImVector_ImDrawChannel_swap; }; const FTABLE_ImVector_ImDrawCmd = struct { /// init(self: *Vector(DrawCmd)) void pub const init = raw.ImVector_ImDrawCmd_ImVector_ImDrawCmd; /// initVector(self: *Vector(DrawCmd), src: Vector(DrawCmd)) void pub const initVector = raw.ImVector_ImDrawCmd_ImVector_ImDrawCmdVector; /// _grow_capacity(self: *const Vector(DrawCmd), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImDrawCmd__grow_capacity; /// back(self: *Vector(DrawCmd)) *DrawCmd pub const back = raw.ImVector_ImDrawCmd_back; /// back_const(self: *const Vector(DrawCmd)) *const DrawCmd pub const back_const = raw.ImVector_ImDrawCmd_back_const; /// begin(self: *Vector(DrawCmd)) [*]DrawCmd pub const begin = raw.ImVector_ImDrawCmd_begin; /// begin_const(self: *const Vector(DrawCmd)) [*]const DrawCmd pub const begin_const = raw.ImVector_ImDrawCmd_begin_const; /// capacity(self: *const Vector(DrawCmd)) i32 pub const capacity = raw.ImVector_ImDrawCmd_capacity; /// clear(self: *Vector(DrawCmd)) void pub const clear = raw.ImVector_ImDrawCmd_clear; /// deinit(self: *Vector(DrawCmd)) void pub const deinit = raw.ImVector_ImDrawCmd_destroy; /// empty(self: *const Vector(DrawCmd)) bool pub const empty = raw.ImVector_ImDrawCmd_empty; /// end(self: *Vector(DrawCmd)) [*]DrawCmd pub const end = raw.ImVector_ImDrawCmd_end; /// end_const(self: *const Vector(DrawCmd)) [*]const DrawCmd pub const end_const = raw.ImVector_ImDrawCmd_end_const; /// erase(self: *Vector(DrawCmd), it: [*]const DrawCmd) [*]DrawCmd pub const erase = raw.ImVector_ImDrawCmd_erase; /// eraseTPtr(self: *Vector(DrawCmd), it: [*]const DrawCmd, it_last: [*]const DrawCmd) [*]DrawCmd pub const eraseTPtr = raw.ImVector_ImDrawCmd_eraseTPtr; /// erase_unsorted(self: *Vector(DrawCmd), it: [*]const DrawCmd) [*]DrawCmd pub const erase_unsorted = raw.ImVector_ImDrawCmd_erase_unsorted; /// front(self: *Vector(DrawCmd)) *DrawCmd pub const front = raw.ImVector_ImDrawCmd_front; /// front_const(self: *const Vector(DrawCmd)) *const DrawCmd pub const front_const = raw.ImVector_ImDrawCmd_front_const; /// index_from_ptr(self: *const Vector(DrawCmd), it: [*]const DrawCmd) i32 pub const index_from_ptr = raw.ImVector_ImDrawCmd_index_from_ptr; /// insert(self: *Vector(DrawCmd), it: [*]const DrawCmd, v: DrawCmd) [*]DrawCmd pub const insert = raw.ImVector_ImDrawCmd_insert; /// pop_back(self: *Vector(DrawCmd)) void pub const pop_back = raw.ImVector_ImDrawCmd_pop_back; /// push_back(self: *Vector(DrawCmd), v: DrawCmd) void pub const push_back = raw.ImVector_ImDrawCmd_push_back; /// push_front(self: *Vector(DrawCmd), v: DrawCmd) void pub const push_front = raw.ImVector_ImDrawCmd_push_front; /// reserve(self: *Vector(DrawCmd), new_capacity: i32) void pub const reserve = raw.ImVector_ImDrawCmd_reserve; /// resize(self: *Vector(DrawCmd), new_size: i32) void pub const resize = raw.ImVector_ImDrawCmd_resize; /// resizeT(self: *Vector(DrawCmd), new_size: i32, v: DrawCmd) void pub const resizeT = raw.ImVector_ImDrawCmd_resizeT; /// shrink(self: *Vector(DrawCmd), new_size: i32) void pub const shrink = raw.ImVector_ImDrawCmd_shrink; /// size(self: *const Vector(DrawCmd)) i32 pub const size = raw.ImVector_ImDrawCmd_size; /// size_in_bytes(self: *const Vector(DrawCmd)) i32 pub const size_in_bytes = raw.ImVector_ImDrawCmd_size_in_bytes; /// swap(self: *Vector(DrawCmd), rhs: *Vector(DrawCmd)) void pub const swap = raw.ImVector_ImDrawCmd_swap; }; const FTABLE_ImVector_ImDrawIdx = struct { /// init(self: *Vector(DrawIdx)) void pub const init = raw.ImVector_ImDrawIdx_ImVector_ImDrawIdx; /// initVector(self: *Vector(DrawIdx), src: Vector(DrawIdx)) void pub const initVector = raw.ImVector_ImDrawIdx_ImVector_ImDrawIdxVector; /// _grow_capacity(self: *const Vector(DrawIdx), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImDrawIdx__grow_capacity; /// back(self: *Vector(DrawIdx)) *DrawIdx pub const back = raw.ImVector_ImDrawIdx_back; /// back_const(self: *const Vector(DrawIdx)) *const DrawIdx pub const back_const = raw.ImVector_ImDrawIdx_back_const; /// begin(self: *Vector(DrawIdx)) [*]DrawIdx pub const begin = raw.ImVector_ImDrawIdx_begin; /// begin_const(self: *const Vector(DrawIdx)) [*]const DrawIdx pub const begin_const = raw.ImVector_ImDrawIdx_begin_const; /// capacity(self: *const Vector(DrawIdx)) i32 pub const capacity = raw.ImVector_ImDrawIdx_capacity; /// clear(self: *Vector(DrawIdx)) void pub const clear = raw.ImVector_ImDrawIdx_clear; /// contains(self: *const Vector(DrawIdx), v: DrawIdx) bool pub const contains = raw.ImVector_ImDrawIdx_contains; /// deinit(self: *Vector(DrawIdx)) void pub const deinit = raw.ImVector_ImDrawIdx_destroy; /// empty(self: *const Vector(DrawIdx)) bool pub const empty = raw.ImVector_ImDrawIdx_empty; /// end(self: *Vector(DrawIdx)) [*]DrawIdx pub const end = raw.ImVector_ImDrawIdx_end; /// end_const(self: *const Vector(DrawIdx)) [*]const DrawIdx pub const end_const = raw.ImVector_ImDrawIdx_end_const; /// erase(self: *Vector(DrawIdx), it: [*]const DrawIdx) [*]DrawIdx pub const erase = raw.ImVector_ImDrawIdx_erase; /// eraseTPtr(self: *Vector(DrawIdx), it: [*]const DrawIdx, it_last: [*]const DrawIdx) [*]DrawIdx pub const eraseTPtr = raw.ImVector_ImDrawIdx_eraseTPtr; /// erase_unsorted(self: *Vector(DrawIdx), it: [*]const DrawIdx) [*]DrawIdx pub const erase_unsorted = raw.ImVector_ImDrawIdx_erase_unsorted; /// find(self: *Vector(DrawIdx), v: DrawIdx) [*]DrawIdx pub const find = raw.ImVector_ImDrawIdx_find; /// find_const(self: *const Vector(DrawIdx), v: DrawIdx) [*]const DrawIdx pub const find_const = raw.ImVector_ImDrawIdx_find_const; /// find_erase(self: *Vector(DrawIdx), v: DrawIdx) bool pub const find_erase = raw.ImVector_ImDrawIdx_find_erase; /// find_erase_unsorted(self: *Vector(DrawIdx), v: DrawIdx) bool pub const find_erase_unsorted = raw.ImVector_ImDrawIdx_find_erase_unsorted; /// front(self: *Vector(DrawIdx)) *DrawIdx pub const front = raw.ImVector_ImDrawIdx_front; /// front_const(self: *const Vector(DrawIdx)) *const DrawIdx pub const front_const = raw.ImVector_ImDrawIdx_front_const; /// index_from_ptr(self: *const Vector(DrawIdx), it: [*]const DrawIdx) i32 pub const index_from_ptr = raw.ImVector_ImDrawIdx_index_from_ptr; /// insert(self: *Vector(DrawIdx), it: [*]const DrawIdx, v: DrawIdx) [*]DrawIdx pub const insert = raw.ImVector_ImDrawIdx_insert; /// pop_back(self: *Vector(DrawIdx)) void pub const pop_back = raw.ImVector_ImDrawIdx_pop_back; /// push_back(self: *Vector(DrawIdx), v: DrawIdx) void pub const push_back = raw.ImVector_ImDrawIdx_push_back; /// push_front(self: *Vector(DrawIdx), v: DrawIdx) void pub const push_front = raw.ImVector_ImDrawIdx_push_front; /// reserve(self: *Vector(DrawIdx), new_capacity: i32) void pub const reserve = raw.ImVector_ImDrawIdx_reserve; /// resize(self: *Vector(DrawIdx), new_size: i32) void pub const resize = raw.ImVector_ImDrawIdx_resize; /// resizeT(self: *Vector(DrawIdx), new_size: i32, v: DrawIdx) void pub const resizeT = raw.ImVector_ImDrawIdx_resizeT; /// shrink(self: *Vector(DrawIdx), new_size: i32) void pub const shrink = raw.ImVector_ImDrawIdx_shrink; /// size(self: *const Vector(DrawIdx)) i32 pub const size = raw.ImVector_ImDrawIdx_size; /// size_in_bytes(self: *const Vector(DrawIdx)) i32 pub const size_in_bytes = raw.ImVector_ImDrawIdx_size_in_bytes; /// swap(self: *Vector(DrawIdx), rhs: *Vector(DrawIdx)) void pub const swap = raw.ImVector_ImDrawIdx_swap; }; const FTABLE_ImVector_ImDrawVert = struct { /// init(self: *Vector(DrawVert)) void pub const init = raw.ImVector_ImDrawVert_ImVector_ImDrawVert; /// initVector(self: *Vector(DrawVert), src: Vector(DrawVert)) void pub const initVector = raw.ImVector_ImDrawVert_ImVector_ImDrawVertVector; /// _grow_capacity(self: *const Vector(DrawVert), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImDrawVert__grow_capacity; /// back(self: *Vector(DrawVert)) *DrawVert pub const back = raw.ImVector_ImDrawVert_back; /// back_const(self: *const Vector(DrawVert)) *const DrawVert pub const back_const = raw.ImVector_ImDrawVert_back_const; /// begin(self: *Vector(DrawVert)) [*]DrawVert pub const begin = raw.ImVector_ImDrawVert_begin; /// begin_const(self: *const Vector(DrawVert)) [*]const DrawVert pub const begin_const = raw.ImVector_ImDrawVert_begin_const; /// capacity(self: *const Vector(DrawVert)) i32 pub const capacity = raw.ImVector_ImDrawVert_capacity; /// clear(self: *Vector(DrawVert)) void pub const clear = raw.ImVector_ImDrawVert_clear; /// deinit(self: *Vector(DrawVert)) void pub const deinit = raw.ImVector_ImDrawVert_destroy; /// empty(self: *const Vector(DrawVert)) bool pub const empty = raw.ImVector_ImDrawVert_empty; /// end(self: *Vector(DrawVert)) [*]DrawVert pub const end = raw.ImVector_ImDrawVert_end; /// end_const(self: *const Vector(DrawVert)) [*]const DrawVert pub const end_const = raw.ImVector_ImDrawVert_end_const; /// erase(self: *Vector(DrawVert), it: [*]const DrawVert) [*]DrawVert pub const erase = raw.ImVector_ImDrawVert_erase; /// eraseTPtr(self: *Vector(DrawVert), it: [*]const DrawVert, it_last: [*]const DrawVert) [*]DrawVert pub const eraseTPtr = raw.ImVector_ImDrawVert_eraseTPtr; /// erase_unsorted(self: *Vector(DrawVert), it: [*]const DrawVert) [*]DrawVert pub const erase_unsorted = raw.ImVector_ImDrawVert_erase_unsorted; /// front(self: *Vector(DrawVert)) *DrawVert pub const front = raw.ImVector_ImDrawVert_front; /// front_const(self: *const Vector(DrawVert)) *const DrawVert pub const front_const = raw.ImVector_ImDrawVert_front_const; /// index_from_ptr(self: *const Vector(DrawVert), it: [*]const DrawVert) i32 pub const index_from_ptr = raw.ImVector_ImDrawVert_index_from_ptr; /// insert(self: *Vector(DrawVert), it: [*]const DrawVert, v: DrawVert) [*]DrawVert pub const insert = raw.ImVector_ImDrawVert_insert; /// pop_back(self: *Vector(DrawVert)) void pub const pop_back = raw.ImVector_ImDrawVert_pop_back; /// push_back(self: *Vector(DrawVert), v: DrawVert) void pub const push_back = raw.ImVector_ImDrawVert_push_back; /// push_front(self: *Vector(DrawVert), v: DrawVert) void pub const push_front = raw.ImVector_ImDrawVert_push_front; /// reserve(self: *Vector(DrawVert), new_capacity: i32) void pub const reserve = raw.ImVector_ImDrawVert_reserve; /// resize(self: *Vector(DrawVert), new_size: i32) void pub const resize = raw.ImVector_ImDrawVert_resize; /// resizeT(self: *Vector(DrawVert), new_size: i32, v: DrawVert) void pub const resizeT = raw.ImVector_ImDrawVert_resizeT; /// shrink(self: *Vector(DrawVert), new_size: i32) void pub const shrink = raw.ImVector_ImDrawVert_shrink; /// size(self: *const Vector(DrawVert)) i32 pub const size = raw.ImVector_ImDrawVert_size; /// size_in_bytes(self: *const Vector(DrawVert)) i32 pub const size_in_bytes = raw.ImVector_ImDrawVert_size_in_bytes; /// swap(self: *Vector(DrawVert), rhs: *Vector(DrawVert)) void pub const swap = raw.ImVector_ImDrawVert_swap; }; const FTABLE_ImVector_ImFontPtr = struct { /// init(self: *Vector(*Font)) void pub const init = raw.ImVector_ImFontPtr_ImVector_ImFontPtr; /// initVector(self: *Vector(*Font), src: Vector(*Font)) void pub const initVector = raw.ImVector_ImFontPtr_ImVector_ImFontPtrVector; /// _grow_capacity(self: *const Vector(*Font), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImFontPtr__grow_capacity; /// back(self: *Vector(*Font)) **Font pub const back = raw.ImVector_ImFontPtr_back; /// back_const(self: *const Vector(*Font)) *const *Font pub const back_const = raw.ImVector_ImFontPtr_back_const; /// begin(self: *Vector(*Font)) [*]*Font pub const begin = raw.ImVector_ImFontPtr_begin; /// begin_const(self: *const Vector(*Font)) [*]const *Font pub const begin_const = raw.ImVector_ImFontPtr_begin_const; /// capacity(self: *const Vector(*Font)) i32 pub const capacity = raw.ImVector_ImFontPtr_capacity; /// clear(self: *Vector(*Font)) void pub const clear = raw.ImVector_ImFontPtr_clear; /// contains(self: *const Vector(*Font), v: *Font) bool pub const contains = raw.ImVector_ImFontPtr_contains; /// deinit(self: *Vector(*Font)) void pub const deinit = raw.ImVector_ImFontPtr_destroy; /// empty(self: *const Vector(*Font)) bool pub const empty = raw.ImVector_ImFontPtr_empty; /// end(self: *Vector(*Font)) [*]*Font pub const end = raw.ImVector_ImFontPtr_end; /// end_const(self: *const Vector(*Font)) [*]const *Font pub const end_const = raw.ImVector_ImFontPtr_end_const; /// erase(self: *Vector(*Font), it: [*]const *Font) [*]*Font pub const erase = raw.ImVector_ImFontPtr_erase; /// eraseTPtr(self: *Vector(*Font), it: [*]const *Font, it_last: [*]const *Font) [*]*Font pub const eraseTPtr = raw.ImVector_ImFontPtr_eraseTPtr; /// erase_unsorted(self: *Vector(*Font), it: [*]const *Font) [*]*Font pub const erase_unsorted = raw.ImVector_ImFontPtr_erase_unsorted; /// find(self: *Vector(*Font), v: *Font) [*]*Font pub const find = raw.ImVector_ImFontPtr_find; /// find_const(self: *const Vector(*Font), v: *Font) [*]const *Font pub const find_const = raw.ImVector_ImFontPtr_find_const; /// find_erase(self: *Vector(*Font), v: *Font) bool pub const find_erase = raw.ImVector_ImFontPtr_find_erase; /// find_erase_unsorted(self: *Vector(*Font), v: *Font) bool pub const find_erase_unsorted = raw.ImVector_ImFontPtr_find_erase_unsorted; /// front(self: *Vector(*Font)) **Font pub const front = raw.ImVector_ImFontPtr_front; /// front_const(self: *const Vector(*Font)) *const *Font pub const front_const = raw.ImVector_ImFontPtr_front_const; /// index_from_ptr(self: *const Vector(*Font), it: [*]const *Font) i32 pub const index_from_ptr = raw.ImVector_ImFontPtr_index_from_ptr; /// insert(self: *Vector(*Font), it: [*]const *Font, v: *Font) [*]*Font pub const insert = raw.ImVector_ImFontPtr_insert; /// pop_back(self: *Vector(*Font)) void pub const pop_back = raw.ImVector_ImFontPtr_pop_back; /// push_back(self: *Vector(*Font), v: *Font) void pub const push_back = raw.ImVector_ImFontPtr_push_back; /// push_front(self: *Vector(*Font), v: *Font) void pub const push_front = raw.ImVector_ImFontPtr_push_front; /// reserve(self: *Vector(*Font), new_capacity: i32) void pub const reserve = raw.ImVector_ImFontPtr_reserve; /// resize(self: *Vector(*Font), new_size: i32) void pub const resize = raw.ImVector_ImFontPtr_resize; /// resizeT(self: *Vector(*Font), new_size: i32, v: *Font) void pub const resizeT = raw.ImVector_ImFontPtr_resizeT; /// shrink(self: *Vector(*Font), new_size: i32) void pub const shrink = raw.ImVector_ImFontPtr_shrink; /// size(self: *const Vector(*Font)) i32 pub const size = raw.ImVector_ImFontPtr_size; /// size_in_bytes(self: *const Vector(*Font)) i32 pub const size_in_bytes = raw.ImVector_ImFontPtr_size_in_bytes; /// swap(self: *Vector(*Font), rhs: *Vector(*Font)) void pub const swap = raw.ImVector_ImFontPtr_swap; }; const FTABLE_ImVector_ImFontAtlasCustomRect = struct { /// init(self: *Vector(FontAtlasCustomRect)) void pub const init = raw.ImVector_ImFontAtlasCustomRect_ImVector_ImFontAtlasCustomRect; /// initVector(self: *Vector(FontAtlasCustomRect), src: Vector(FontAtlasCustomRect)) void pub const initVector = raw.ImVector_ImFontAtlasCustomRect_ImVector_ImFontAtlasCustomRectVector; /// _grow_capacity(self: *const Vector(FontAtlasCustomRect), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImFontAtlasCustomRect__grow_capacity; /// back(self: *Vector(FontAtlasCustomRect)) *FontAtlasCustomRect pub const back = raw.ImVector_ImFontAtlasCustomRect_back; /// back_const(self: *const Vector(FontAtlasCustomRect)) *const FontAtlasCustomRect pub const back_const = raw.ImVector_ImFontAtlasCustomRect_back_const; /// begin(self: *Vector(FontAtlasCustomRect)) [*]FontAtlasCustomRect pub const begin = raw.ImVector_ImFontAtlasCustomRect_begin; /// begin_const(self: *const Vector(FontAtlasCustomRect)) [*]const FontAtlasCustomRect pub const begin_const = raw.ImVector_ImFontAtlasCustomRect_begin_const; /// capacity(self: *const Vector(FontAtlasCustomRect)) i32 pub const capacity = raw.ImVector_ImFontAtlasCustomRect_capacity; /// clear(self: *Vector(FontAtlasCustomRect)) void pub const clear = raw.ImVector_ImFontAtlasCustomRect_clear; /// deinit(self: *Vector(FontAtlasCustomRect)) void pub const deinit = raw.ImVector_ImFontAtlasCustomRect_destroy; /// empty(self: *const Vector(FontAtlasCustomRect)) bool pub const empty = raw.ImVector_ImFontAtlasCustomRect_empty; /// end(self: *Vector(FontAtlasCustomRect)) [*]FontAtlasCustomRect pub const end = raw.ImVector_ImFontAtlasCustomRect_end; /// end_const(self: *const Vector(FontAtlasCustomRect)) [*]const FontAtlasCustomRect pub const end_const = raw.ImVector_ImFontAtlasCustomRect_end_const; /// erase(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect) [*]FontAtlasCustomRect pub const erase = raw.ImVector_ImFontAtlasCustomRect_erase; /// eraseTPtr(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect, it_last: [*]const FontAtlasCustomRect) [*]FontAtlasCustomRect pub const eraseTPtr = raw.ImVector_ImFontAtlasCustomRect_eraseTPtr; /// erase_unsorted(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect) [*]FontAtlasCustomRect pub const erase_unsorted = raw.ImVector_ImFontAtlasCustomRect_erase_unsorted; /// front(self: *Vector(FontAtlasCustomRect)) *FontAtlasCustomRect pub const front = raw.ImVector_ImFontAtlasCustomRect_front; /// front_const(self: *const Vector(FontAtlasCustomRect)) *const FontAtlasCustomRect pub const front_const = raw.ImVector_ImFontAtlasCustomRect_front_const; /// index_from_ptr(self: *const Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect) i32 pub const index_from_ptr = raw.ImVector_ImFontAtlasCustomRect_index_from_ptr; /// insert(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect, v: FontAtlasCustomRect) [*]FontAtlasCustomRect pub const insert = raw.ImVector_ImFontAtlasCustomRect_insert; /// pop_back(self: *Vector(FontAtlasCustomRect)) void pub const pop_back = raw.ImVector_ImFontAtlasCustomRect_pop_back; /// push_back(self: *Vector(FontAtlasCustomRect), v: FontAtlasCustomRect) void pub const push_back = raw.ImVector_ImFontAtlasCustomRect_push_back; /// push_front(self: *Vector(FontAtlasCustomRect), v: FontAtlasCustomRect) void pub const push_front = raw.ImVector_ImFontAtlasCustomRect_push_front; /// reserve(self: *Vector(FontAtlasCustomRect), new_capacity: i32) void pub const reserve = raw.ImVector_ImFontAtlasCustomRect_reserve; /// resize(self: *Vector(FontAtlasCustomRect), new_size: i32) void pub const resize = raw.ImVector_ImFontAtlasCustomRect_resize; /// resizeT(self: *Vector(FontAtlasCustomRect), new_size: i32, v: FontAtlasCustomRect) void pub const resizeT = raw.ImVector_ImFontAtlasCustomRect_resizeT; /// shrink(self: *Vector(FontAtlasCustomRect), new_size: i32) void pub const shrink = raw.ImVector_ImFontAtlasCustomRect_shrink; /// size(self: *const Vector(FontAtlasCustomRect)) i32 pub const size = raw.ImVector_ImFontAtlasCustomRect_size; /// size_in_bytes(self: *const Vector(FontAtlasCustomRect)) i32 pub const size_in_bytes = raw.ImVector_ImFontAtlasCustomRect_size_in_bytes; /// swap(self: *Vector(FontAtlasCustomRect), rhs: *Vector(FontAtlasCustomRect)) void pub const swap = raw.ImVector_ImFontAtlasCustomRect_swap; }; const FTABLE_ImVector_ImFontConfig = struct { /// init(self: *Vector(FontConfig)) void pub const init = raw.ImVector_ImFontConfig_ImVector_ImFontConfig; /// initVector(self: *Vector(FontConfig), src: Vector(FontConfig)) void pub const initVector = raw.ImVector_ImFontConfig_ImVector_ImFontConfigVector; /// _grow_capacity(self: *const Vector(FontConfig), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImFontConfig__grow_capacity; /// back(self: *Vector(FontConfig)) *FontConfig pub const back = raw.ImVector_ImFontConfig_back; /// back_const(self: *const Vector(FontConfig)) *const FontConfig pub const back_const = raw.ImVector_ImFontConfig_back_const; /// begin(self: *Vector(FontConfig)) [*]FontConfig pub const begin = raw.ImVector_ImFontConfig_begin; /// begin_const(self: *const Vector(FontConfig)) [*]const FontConfig pub const begin_const = raw.ImVector_ImFontConfig_begin_const; /// capacity(self: *const Vector(FontConfig)) i32 pub const capacity = raw.ImVector_ImFontConfig_capacity; /// clear(self: *Vector(FontConfig)) void pub const clear = raw.ImVector_ImFontConfig_clear; /// deinit(self: *Vector(FontConfig)) void pub const deinit = raw.ImVector_ImFontConfig_destroy; /// empty(self: *const Vector(FontConfig)) bool pub const empty = raw.ImVector_ImFontConfig_empty; /// end(self: *Vector(FontConfig)) [*]FontConfig pub const end = raw.ImVector_ImFontConfig_end; /// end_const(self: *const Vector(FontConfig)) [*]const FontConfig pub const end_const = raw.ImVector_ImFontConfig_end_const; /// erase(self: *Vector(FontConfig), it: [*]const FontConfig) [*]FontConfig pub const erase = raw.ImVector_ImFontConfig_erase; /// eraseTPtr(self: *Vector(FontConfig), it: [*]const FontConfig, it_last: [*]const FontConfig) [*]FontConfig pub const eraseTPtr = raw.ImVector_ImFontConfig_eraseTPtr; /// erase_unsorted(self: *Vector(FontConfig), it: [*]const FontConfig) [*]FontConfig pub const erase_unsorted = raw.ImVector_ImFontConfig_erase_unsorted; /// front(self: *Vector(FontConfig)) *FontConfig pub const front = raw.ImVector_ImFontConfig_front; /// front_const(self: *const Vector(FontConfig)) *const FontConfig pub const front_const = raw.ImVector_ImFontConfig_front_const; /// index_from_ptr(self: *const Vector(FontConfig), it: [*]const FontConfig) i32 pub const index_from_ptr = raw.ImVector_ImFontConfig_index_from_ptr; /// insert(self: *Vector(FontConfig), it: [*]const FontConfig, v: FontConfig) [*]FontConfig pub const insert = raw.ImVector_ImFontConfig_insert; /// pop_back(self: *Vector(FontConfig)) void pub const pop_back = raw.ImVector_ImFontConfig_pop_back; /// push_back(self: *Vector(FontConfig), v: FontConfig) void pub const push_back = raw.ImVector_ImFontConfig_push_back; /// push_front(self: *Vector(FontConfig), v: FontConfig) void pub const push_front = raw.ImVector_ImFontConfig_push_front; /// reserve(self: *Vector(FontConfig), new_capacity: i32) void pub const reserve = raw.ImVector_ImFontConfig_reserve; /// resize(self: *Vector(FontConfig), new_size: i32) void pub const resize = raw.ImVector_ImFontConfig_resize; /// resizeT(self: *Vector(FontConfig), new_size: i32, v: FontConfig) void pub const resizeT = raw.ImVector_ImFontConfig_resizeT; /// shrink(self: *Vector(FontConfig), new_size: i32) void pub const shrink = raw.ImVector_ImFontConfig_shrink; /// size(self: *const Vector(FontConfig)) i32 pub const size = raw.ImVector_ImFontConfig_size; /// size_in_bytes(self: *const Vector(FontConfig)) i32 pub const size_in_bytes = raw.ImVector_ImFontConfig_size_in_bytes; /// swap(self: *Vector(FontConfig), rhs: *Vector(FontConfig)) void pub const swap = raw.ImVector_ImFontConfig_swap; }; const FTABLE_ImVector_ImFontGlyph = struct { /// init(self: *Vector(FontGlyph)) void pub const init = raw.ImVector_ImFontGlyph_ImVector_ImFontGlyph; /// initVector(self: *Vector(FontGlyph), src: Vector(FontGlyph)) void pub const initVector = raw.ImVector_ImFontGlyph_ImVector_ImFontGlyphVector; /// _grow_capacity(self: *const Vector(FontGlyph), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImFontGlyph__grow_capacity; /// back(self: *Vector(FontGlyph)) *FontGlyph pub const back = raw.ImVector_ImFontGlyph_back; /// back_const(self: *const Vector(FontGlyph)) *const FontGlyph pub const back_const = raw.ImVector_ImFontGlyph_back_const; /// begin(self: *Vector(FontGlyph)) [*]FontGlyph pub const begin = raw.ImVector_ImFontGlyph_begin; /// begin_const(self: *const Vector(FontGlyph)) [*]const FontGlyph pub const begin_const = raw.ImVector_ImFontGlyph_begin_const; /// capacity(self: *const Vector(FontGlyph)) i32 pub const capacity = raw.ImVector_ImFontGlyph_capacity; /// clear(self: *Vector(FontGlyph)) void pub const clear = raw.ImVector_ImFontGlyph_clear; /// deinit(self: *Vector(FontGlyph)) void pub const deinit = raw.ImVector_ImFontGlyph_destroy; /// empty(self: *const Vector(FontGlyph)) bool pub const empty = raw.ImVector_ImFontGlyph_empty; /// end(self: *Vector(FontGlyph)) [*]FontGlyph pub const end = raw.ImVector_ImFontGlyph_end; /// end_const(self: *const Vector(FontGlyph)) [*]const FontGlyph pub const end_const = raw.ImVector_ImFontGlyph_end_const; /// erase(self: *Vector(FontGlyph), it: [*]const FontGlyph) [*]FontGlyph pub const erase = raw.ImVector_ImFontGlyph_erase; /// eraseTPtr(self: *Vector(FontGlyph), it: [*]const FontGlyph, it_last: [*]const FontGlyph) [*]FontGlyph pub const eraseTPtr = raw.ImVector_ImFontGlyph_eraseTPtr; /// erase_unsorted(self: *Vector(FontGlyph), it: [*]const FontGlyph) [*]FontGlyph pub const erase_unsorted = raw.ImVector_ImFontGlyph_erase_unsorted; /// front(self: *Vector(FontGlyph)) *FontGlyph pub const front = raw.ImVector_ImFontGlyph_front; /// front_const(self: *const Vector(FontGlyph)) *const FontGlyph pub const front_const = raw.ImVector_ImFontGlyph_front_const; /// index_from_ptr(self: *const Vector(FontGlyph), it: [*]const FontGlyph) i32 pub const index_from_ptr = raw.ImVector_ImFontGlyph_index_from_ptr; /// insert(self: *Vector(FontGlyph), it: [*]const FontGlyph, v: FontGlyph) [*]FontGlyph pub const insert = raw.ImVector_ImFontGlyph_insert; /// pop_back(self: *Vector(FontGlyph)) void pub const pop_back = raw.ImVector_ImFontGlyph_pop_back; /// push_back(self: *Vector(FontGlyph), v: FontGlyph) void pub const push_back = raw.ImVector_ImFontGlyph_push_back; /// push_front(self: *Vector(FontGlyph), v: FontGlyph) void pub const push_front = raw.ImVector_ImFontGlyph_push_front; /// reserve(self: *Vector(FontGlyph), new_capacity: i32) void pub const reserve = raw.ImVector_ImFontGlyph_reserve; /// resize(self: *Vector(FontGlyph), new_size: i32) void pub const resize = raw.ImVector_ImFontGlyph_resize; /// resizeT(self: *Vector(FontGlyph), new_size: i32, v: FontGlyph) void pub const resizeT = raw.ImVector_ImFontGlyph_resizeT; /// shrink(self: *Vector(FontGlyph), new_size: i32) void pub const shrink = raw.ImVector_ImFontGlyph_shrink; /// size(self: *const Vector(FontGlyph)) i32 pub const size = raw.ImVector_ImFontGlyph_size; /// size_in_bytes(self: *const Vector(FontGlyph)) i32 pub const size_in_bytes = raw.ImVector_ImFontGlyph_size_in_bytes; /// swap(self: *Vector(FontGlyph), rhs: *Vector(FontGlyph)) void pub const swap = raw.ImVector_ImFontGlyph_swap; }; const FTABLE_ImVector_ImGuiStoragePair = struct { /// init(self: *Vector(StoragePair)) void pub const init = raw.ImVector_ImGuiStoragePair_ImVector_ImGuiStoragePair; /// initVector(self: *Vector(StoragePair), src: Vector(StoragePair)) void pub const initVector = raw.ImVector_ImGuiStoragePair_ImVector_ImGuiStoragePairVector; /// _grow_capacity(self: *const Vector(StoragePair), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImGuiStoragePair__grow_capacity; /// back(self: *Vector(StoragePair)) *StoragePair pub const back = raw.ImVector_ImGuiStoragePair_back; /// back_const(self: *const Vector(StoragePair)) *const StoragePair pub const back_const = raw.ImVector_ImGuiStoragePair_back_const; /// begin(self: *Vector(StoragePair)) [*]StoragePair pub const begin = raw.ImVector_ImGuiStoragePair_begin; /// begin_const(self: *const Vector(StoragePair)) [*]const StoragePair pub const begin_const = raw.ImVector_ImGuiStoragePair_begin_const; /// capacity(self: *const Vector(StoragePair)) i32 pub const capacity = raw.ImVector_ImGuiStoragePair_capacity; /// clear(self: *Vector(StoragePair)) void pub const clear = raw.ImVector_ImGuiStoragePair_clear; /// deinit(self: *Vector(StoragePair)) void pub const deinit = raw.ImVector_ImGuiStoragePair_destroy; /// empty(self: *const Vector(StoragePair)) bool pub const empty = raw.ImVector_ImGuiStoragePair_empty; /// end(self: *Vector(StoragePair)) [*]StoragePair pub const end = raw.ImVector_ImGuiStoragePair_end; /// end_const(self: *const Vector(StoragePair)) [*]const StoragePair pub const end_const = raw.ImVector_ImGuiStoragePair_end_const; /// erase(self: *Vector(StoragePair), it: [*]const StoragePair) [*]StoragePair pub const erase = raw.ImVector_ImGuiStoragePair_erase; /// eraseTPtr(self: *Vector(StoragePair), it: [*]const StoragePair, it_last: [*]const StoragePair) [*]StoragePair pub const eraseTPtr = raw.ImVector_ImGuiStoragePair_eraseTPtr; /// erase_unsorted(self: *Vector(StoragePair), it: [*]const StoragePair) [*]StoragePair pub const erase_unsorted = raw.ImVector_ImGuiStoragePair_erase_unsorted; /// front(self: *Vector(StoragePair)) *StoragePair pub const front = raw.ImVector_ImGuiStoragePair_front; /// front_const(self: *const Vector(StoragePair)) *const StoragePair pub const front_const = raw.ImVector_ImGuiStoragePair_front_const; /// index_from_ptr(self: *const Vector(StoragePair), it: [*]const StoragePair) i32 pub const index_from_ptr = raw.ImVector_ImGuiStoragePair_index_from_ptr; /// insert(self: *Vector(StoragePair), it: [*]const StoragePair, v: StoragePair) [*]StoragePair pub const insert = raw.ImVector_ImGuiStoragePair_insert; /// pop_back(self: *Vector(StoragePair)) void pub const pop_back = raw.ImVector_ImGuiStoragePair_pop_back; /// push_back(self: *Vector(StoragePair), v: StoragePair) void pub const push_back = raw.ImVector_ImGuiStoragePair_push_back; /// push_front(self: *Vector(StoragePair), v: StoragePair) void pub const push_front = raw.ImVector_ImGuiStoragePair_push_front; /// reserve(self: *Vector(StoragePair), new_capacity: i32) void pub const reserve = raw.ImVector_ImGuiStoragePair_reserve; /// resize(self: *Vector(StoragePair), new_size: i32) void pub const resize = raw.ImVector_ImGuiStoragePair_resize; /// resizeT(self: *Vector(StoragePair), new_size: i32, v: StoragePair) void pub const resizeT = raw.ImVector_ImGuiStoragePair_resizeT; /// shrink(self: *Vector(StoragePair), new_size: i32) void pub const shrink = raw.ImVector_ImGuiStoragePair_shrink; /// size(self: *const Vector(StoragePair)) i32 pub const size = raw.ImVector_ImGuiStoragePair_size; /// size_in_bytes(self: *const Vector(StoragePair)) i32 pub const size_in_bytes = raw.ImVector_ImGuiStoragePair_size_in_bytes; /// swap(self: *Vector(StoragePair), rhs: *Vector(StoragePair)) void pub const swap = raw.ImVector_ImGuiStoragePair_swap; }; const FTABLE_ImVector_ImGuiTextRange = struct { /// init(self: *Vector(TextRange)) void pub const init = raw.ImVector_ImGuiTextRange_ImVector_ImGuiTextRange; /// initVector(self: *Vector(TextRange), src: Vector(TextRange)) void pub const initVector = raw.ImVector_ImGuiTextRange_ImVector_ImGuiTextRangeVector; /// _grow_capacity(self: *const Vector(TextRange), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImGuiTextRange__grow_capacity; /// back(self: *Vector(TextRange)) *TextRange pub const back = raw.ImVector_ImGuiTextRange_back; /// back_const(self: *const Vector(TextRange)) *const TextRange pub const back_const = raw.ImVector_ImGuiTextRange_back_const; /// begin(self: *Vector(TextRange)) [*]TextRange pub const begin = raw.ImVector_ImGuiTextRange_begin; /// begin_const(self: *const Vector(TextRange)) [*]const TextRange pub const begin_const = raw.ImVector_ImGuiTextRange_begin_const; /// capacity(self: *const Vector(TextRange)) i32 pub const capacity = raw.ImVector_ImGuiTextRange_capacity; /// clear(self: *Vector(TextRange)) void pub const clear = raw.ImVector_ImGuiTextRange_clear; /// deinit(self: *Vector(TextRange)) void pub const deinit = raw.ImVector_ImGuiTextRange_destroy; /// empty(self: *const Vector(TextRange)) bool pub const empty = raw.ImVector_ImGuiTextRange_empty; /// end(self: *Vector(TextRange)) [*]TextRange pub const end = raw.ImVector_ImGuiTextRange_end; /// end_const(self: *const Vector(TextRange)) [*]const TextRange pub const end_const = raw.ImVector_ImGuiTextRange_end_const; /// erase(self: *Vector(TextRange), it: [*]const TextRange) [*]TextRange pub const erase = raw.ImVector_ImGuiTextRange_erase; /// eraseTPtr(self: *Vector(TextRange), it: [*]const TextRange, it_last: [*]const TextRange) [*]TextRange pub const eraseTPtr = raw.ImVector_ImGuiTextRange_eraseTPtr; /// erase_unsorted(self: *Vector(TextRange), it: [*]const TextRange) [*]TextRange pub const erase_unsorted = raw.ImVector_ImGuiTextRange_erase_unsorted; /// front(self: *Vector(TextRange)) *TextRange pub const front = raw.ImVector_ImGuiTextRange_front; /// front_const(self: *const Vector(TextRange)) *const TextRange pub const front_const = raw.ImVector_ImGuiTextRange_front_const; /// index_from_ptr(self: *const Vector(TextRange), it: [*]const TextRange) i32 pub const index_from_ptr = raw.ImVector_ImGuiTextRange_index_from_ptr; /// insert(self: *Vector(TextRange), it: [*]const TextRange, v: TextRange) [*]TextRange pub const insert = raw.ImVector_ImGuiTextRange_insert; /// pop_back(self: *Vector(TextRange)) void pub const pop_back = raw.ImVector_ImGuiTextRange_pop_back; /// push_back(self: *Vector(TextRange), v: TextRange) void pub const push_back = raw.ImVector_ImGuiTextRange_push_back; /// push_front(self: *Vector(TextRange), v: TextRange) void pub const push_front = raw.ImVector_ImGuiTextRange_push_front; /// reserve(self: *Vector(TextRange), new_capacity: i32) void pub const reserve = raw.ImVector_ImGuiTextRange_reserve; /// resize(self: *Vector(TextRange), new_size: i32) void pub const resize = raw.ImVector_ImGuiTextRange_resize; /// resizeT(self: *Vector(TextRange), new_size: i32, v: TextRange) void pub const resizeT = raw.ImVector_ImGuiTextRange_resizeT; /// shrink(self: *Vector(TextRange), new_size: i32) void pub const shrink = raw.ImVector_ImGuiTextRange_shrink; /// size(self: *const Vector(TextRange)) i32 pub const size = raw.ImVector_ImGuiTextRange_size; /// size_in_bytes(self: *const Vector(TextRange)) i32 pub const size_in_bytes = raw.ImVector_ImGuiTextRange_size_in_bytes; /// swap(self: *Vector(TextRange), rhs: *Vector(TextRange)) void pub const swap = raw.ImVector_ImGuiTextRange_swap; }; const FTABLE_ImVector_ImTextureID = struct { /// init(self: *Vector(TextureID)) void pub const init = raw.ImVector_ImTextureID_ImVector_ImTextureID; /// initVector(self: *Vector(TextureID), src: Vector(TextureID)) void pub const initVector = raw.ImVector_ImTextureID_ImVector_ImTextureIDVector; /// _grow_capacity(self: *const Vector(TextureID), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImTextureID__grow_capacity; /// back(self: *Vector(TextureID)) *TextureID pub const back = raw.ImVector_ImTextureID_back; /// back_const(self: *const Vector(TextureID)) *const TextureID pub const back_const = raw.ImVector_ImTextureID_back_const; /// begin(self: *Vector(TextureID)) [*]TextureID pub const begin = raw.ImVector_ImTextureID_begin; /// begin_const(self: *const Vector(TextureID)) [*]const TextureID pub const begin_const = raw.ImVector_ImTextureID_begin_const; /// capacity(self: *const Vector(TextureID)) i32 pub const capacity = raw.ImVector_ImTextureID_capacity; /// clear(self: *Vector(TextureID)) void pub const clear = raw.ImVector_ImTextureID_clear; /// contains(self: *const Vector(TextureID), v: TextureID) bool pub const contains = raw.ImVector_ImTextureID_contains; /// deinit(self: *Vector(TextureID)) void pub const deinit = raw.ImVector_ImTextureID_destroy; /// empty(self: *const Vector(TextureID)) bool pub const empty = raw.ImVector_ImTextureID_empty; /// end(self: *Vector(TextureID)) [*]TextureID pub const end = raw.ImVector_ImTextureID_end; /// end_const(self: *const Vector(TextureID)) [*]const TextureID pub const end_const = raw.ImVector_ImTextureID_end_const; /// erase(self: *Vector(TextureID), it: [*]const TextureID) [*]TextureID pub const erase = raw.ImVector_ImTextureID_erase; /// eraseTPtr(self: *Vector(TextureID), it: [*]const TextureID, it_last: [*]const TextureID) [*]TextureID pub const eraseTPtr = raw.ImVector_ImTextureID_eraseTPtr; /// erase_unsorted(self: *Vector(TextureID), it: [*]const TextureID) [*]TextureID pub const erase_unsorted = raw.ImVector_ImTextureID_erase_unsorted; /// find(self: *Vector(TextureID), v: TextureID) [*]TextureID pub const find = raw.ImVector_ImTextureID_find; /// find_const(self: *const Vector(TextureID), v: TextureID) [*]const TextureID pub const find_const = raw.ImVector_ImTextureID_find_const; /// find_erase(self: *Vector(TextureID), v: TextureID) bool pub const find_erase = raw.ImVector_ImTextureID_find_erase; /// find_erase_unsorted(self: *Vector(TextureID), v: TextureID) bool pub const find_erase_unsorted = raw.ImVector_ImTextureID_find_erase_unsorted; /// front(self: *Vector(TextureID)) *TextureID pub const front = raw.ImVector_ImTextureID_front; /// front_const(self: *const Vector(TextureID)) *const TextureID pub const front_const = raw.ImVector_ImTextureID_front_const; /// index_from_ptr(self: *const Vector(TextureID), it: [*]const TextureID) i32 pub const index_from_ptr = raw.ImVector_ImTextureID_index_from_ptr; /// insert(self: *Vector(TextureID), it: [*]const TextureID, v: TextureID) [*]TextureID pub const insert = raw.ImVector_ImTextureID_insert; /// pop_back(self: *Vector(TextureID)) void pub const pop_back = raw.ImVector_ImTextureID_pop_back; /// push_back(self: *Vector(TextureID), v: TextureID) void pub const push_back = raw.ImVector_ImTextureID_push_back; /// push_front(self: *Vector(TextureID), v: TextureID) void pub const push_front = raw.ImVector_ImTextureID_push_front; /// reserve(self: *Vector(TextureID), new_capacity: i32) void pub const reserve = raw.ImVector_ImTextureID_reserve; /// resize(self: *Vector(TextureID), new_size: i32) void pub const resize = raw.ImVector_ImTextureID_resize; /// resizeT(self: *Vector(TextureID), new_size: i32, v: TextureID) void pub const resizeT = raw.ImVector_ImTextureID_resizeT; /// shrink(self: *Vector(TextureID), new_size: i32) void pub const shrink = raw.ImVector_ImTextureID_shrink; /// size(self: *const Vector(TextureID)) i32 pub const size = raw.ImVector_ImTextureID_size; /// size_in_bytes(self: *const Vector(TextureID)) i32 pub const size_in_bytes = raw.ImVector_ImTextureID_size_in_bytes; /// swap(self: *Vector(TextureID), rhs: *Vector(TextureID)) void pub const swap = raw.ImVector_ImTextureID_swap; }; const FTABLE_ImVector_ImU32 = struct { /// init(self: *Vector(u32)) void pub const init = raw.ImVector_ImU32_ImVector_ImU32; /// initVector(self: *Vector(u32), src: Vector(u32)) void pub const initVector = raw.ImVector_ImU32_ImVector_ImU32Vector; /// _grow_capacity(self: *const Vector(u32), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImU32__grow_capacity; /// back(self: *Vector(u32)) *u32 pub const back = raw.ImVector_ImU32_back; /// back_const(self: *const Vector(u32)) *const u32 pub const back_const = raw.ImVector_ImU32_back_const; /// begin(self: *Vector(u32)) [*]u32 pub const begin = raw.ImVector_ImU32_begin; /// begin_const(self: *const Vector(u32)) [*]const u32 pub const begin_const = raw.ImVector_ImU32_begin_const; /// capacity(self: *const Vector(u32)) i32 pub const capacity = raw.ImVector_ImU32_capacity; /// clear(self: *Vector(u32)) void pub const clear = raw.ImVector_ImU32_clear; /// contains(self: *const Vector(u32), v: u32) bool pub const contains = raw.ImVector_ImU32_contains; /// deinit(self: *Vector(u32)) void pub const deinit = raw.ImVector_ImU32_destroy; /// empty(self: *const Vector(u32)) bool pub const empty = raw.ImVector_ImU32_empty; /// end(self: *Vector(u32)) [*]u32 pub const end = raw.ImVector_ImU32_end; /// end_const(self: *const Vector(u32)) [*]const u32 pub const end_const = raw.ImVector_ImU32_end_const; /// erase(self: *Vector(u32), it: [*]const u32) [*]u32 pub const erase = raw.ImVector_ImU32_erase; /// eraseTPtr(self: *Vector(u32), it: [*]const u32, it_last: [*]const u32) [*]u32 pub const eraseTPtr = raw.ImVector_ImU32_eraseTPtr; /// erase_unsorted(self: *Vector(u32), it: [*]const u32) [*]u32 pub const erase_unsorted = raw.ImVector_ImU32_erase_unsorted; /// find(self: *Vector(u32), v: u32) [*]u32 pub const find = raw.ImVector_ImU32_find; /// find_const(self: *const Vector(u32), v: u32) [*]const u32 pub const find_const = raw.ImVector_ImU32_find_const; /// find_erase(self: *Vector(u32), v: u32) bool pub const find_erase = raw.ImVector_ImU32_find_erase; /// find_erase_unsorted(self: *Vector(u32), v: u32) bool pub const find_erase_unsorted = raw.ImVector_ImU32_find_erase_unsorted; /// front(self: *Vector(u32)) *u32 pub const front = raw.ImVector_ImU32_front; /// front_const(self: *const Vector(u32)) *const u32 pub const front_const = raw.ImVector_ImU32_front_const; /// index_from_ptr(self: *const Vector(u32), it: [*]const u32) i32 pub const index_from_ptr = raw.ImVector_ImU32_index_from_ptr; /// insert(self: *Vector(u32), it: [*]const u32, v: u32) [*]u32 pub const insert = raw.ImVector_ImU32_insert; /// pop_back(self: *Vector(u32)) void pub const pop_back = raw.ImVector_ImU32_pop_back; /// push_back(self: *Vector(u32), v: u32) void pub const push_back = raw.ImVector_ImU32_push_back; /// push_front(self: *Vector(u32), v: u32) void pub const push_front = raw.ImVector_ImU32_push_front; /// reserve(self: *Vector(u32), new_capacity: i32) void pub const reserve = raw.ImVector_ImU32_reserve; /// resize(self: *Vector(u32), new_size: i32) void pub const resize = raw.ImVector_ImU32_resize; /// resizeT(self: *Vector(u32), new_size: i32, v: u32) void pub const resizeT = raw.ImVector_ImU32_resizeT; /// shrink(self: *Vector(u32), new_size: i32) void pub const shrink = raw.ImVector_ImU32_shrink; /// size(self: *const Vector(u32)) i32 pub const size = raw.ImVector_ImU32_size; /// size_in_bytes(self: *const Vector(u32)) i32 pub const size_in_bytes = raw.ImVector_ImU32_size_in_bytes; /// swap(self: *Vector(u32), rhs: *Vector(u32)) void pub const swap = raw.ImVector_ImU32_swap; }; const FTABLE_ImVector_ImVec2 = struct { /// init(self: *Vector(Vec2)) void pub const init = raw.ImVector_ImVec2_ImVector_ImVec2; /// initVector(self: *Vector(Vec2), src: Vector(Vec2)) void pub const initVector = raw.ImVector_ImVec2_ImVector_ImVec2Vector; /// _grow_capacity(self: *const Vector(Vec2), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImVec2__grow_capacity; /// back(self: *Vector(Vec2)) *Vec2 pub const back = raw.ImVector_ImVec2_back; /// back_const(self: *const Vector(Vec2)) *const Vec2 pub const back_const = raw.ImVector_ImVec2_back_const; /// begin(self: *Vector(Vec2)) [*]Vec2 pub const begin = raw.ImVector_ImVec2_begin; /// begin_const(self: *const Vector(Vec2)) [*]const Vec2 pub const begin_const = raw.ImVector_ImVec2_begin_const; /// capacity(self: *const Vector(Vec2)) i32 pub const capacity = raw.ImVector_ImVec2_capacity; /// clear(self: *Vector(Vec2)) void pub const clear = raw.ImVector_ImVec2_clear; /// deinit(self: *Vector(Vec2)) void pub const deinit = raw.ImVector_ImVec2_destroy; /// empty(self: *const Vector(Vec2)) bool pub const empty = raw.ImVector_ImVec2_empty; /// end(self: *Vector(Vec2)) [*]Vec2 pub const end = raw.ImVector_ImVec2_end; /// end_const(self: *const Vector(Vec2)) [*]const Vec2 pub const end_const = raw.ImVector_ImVec2_end_const; /// erase(self: *Vector(Vec2), it: [*]const Vec2) [*]Vec2 pub const erase = raw.ImVector_ImVec2_erase; /// eraseTPtr(self: *Vector(Vec2), it: [*]const Vec2, it_last: [*]const Vec2) [*]Vec2 pub const eraseTPtr = raw.ImVector_ImVec2_eraseTPtr; /// erase_unsorted(self: *Vector(Vec2), it: [*]const Vec2) [*]Vec2 pub const erase_unsorted = raw.ImVector_ImVec2_erase_unsorted; /// front(self: *Vector(Vec2)) *Vec2 pub const front = raw.ImVector_ImVec2_front; /// front_const(self: *const Vector(Vec2)) *const Vec2 pub const front_const = raw.ImVector_ImVec2_front_const; /// index_from_ptr(self: *const Vector(Vec2), it: [*]const Vec2) i32 pub const index_from_ptr = raw.ImVector_ImVec2_index_from_ptr; /// insert(self: *Vector(Vec2), it: [*]const Vec2, v: Vec2) [*]Vec2 pub const insert = raw.ImVector_ImVec2_insert; /// pop_back(self: *Vector(Vec2)) void pub const pop_back = raw.ImVector_ImVec2_pop_back; /// push_back(self: *Vector(Vec2), v: Vec2) void pub const push_back = raw.ImVector_ImVec2_push_back; /// push_front(self: *Vector(Vec2), v: Vec2) void pub const push_front = raw.ImVector_ImVec2_push_front; /// reserve(self: *Vector(Vec2), new_capacity: i32) void pub const reserve = raw.ImVector_ImVec2_reserve; /// resize(self: *Vector(Vec2), new_size: i32) void pub const resize = raw.ImVector_ImVec2_resize; /// resizeT(self: *Vector(Vec2), new_size: i32, v: Vec2) void pub const resizeT = raw.ImVector_ImVec2_resizeT; /// shrink(self: *Vector(Vec2), new_size: i32) void pub const shrink = raw.ImVector_ImVec2_shrink; /// size(self: *const Vector(Vec2)) i32 pub const size = raw.ImVector_ImVec2_size; /// size_in_bytes(self: *const Vector(Vec2)) i32 pub const size_in_bytes = raw.ImVector_ImVec2_size_in_bytes; /// swap(self: *Vector(Vec2), rhs: *Vector(Vec2)) void pub const swap = raw.ImVector_ImVec2_swap; }; const FTABLE_ImVector_ImVec4 = struct { /// init(self: *Vector(Vec4)) void pub const init = raw.ImVector_ImVec4_ImVector_ImVec4; /// initVector(self: *Vector(Vec4), src: Vector(Vec4)) void pub const initVector = raw.ImVector_ImVec4_ImVector_ImVec4Vector; /// _grow_capacity(self: *const Vector(Vec4), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImVec4__grow_capacity; /// back(self: *Vector(Vec4)) *Vec4 pub const back = raw.ImVector_ImVec4_back; /// back_const(self: *const Vector(Vec4)) *const Vec4 pub const back_const = raw.ImVector_ImVec4_back_const; /// begin(self: *Vector(Vec4)) [*]Vec4 pub const begin = raw.ImVector_ImVec4_begin; /// begin_const(self: *const Vector(Vec4)) [*]const Vec4 pub const begin_const = raw.ImVector_ImVec4_begin_const; /// capacity(self: *const Vector(Vec4)) i32 pub const capacity = raw.ImVector_ImVec4_capacity; /// clear(self: *Vector(Vec4)) void pub const clear = raw.ImVector_ImVec4_clear; /// deinit(self: *Vector(Vec4)) void pub const deinit = raw.ImVector_ImVec4_destroy; /// empty(self: *const Vector(Vec4)) bool pub const empty = raw.ImVector_ImVec4_empty; /// end(self: *Vector(Vec4)) [*]Vec4 pub const end = raw.ImVector_ImVec4_end; /// end_const(self: *const Vector(Vec4)) [*]const Vec4 pub const end_const = raw.ImVector_ImVec4_end_const; /// erase(self: *Vector(Vec4), it: [*]const Vec4) [*]Vec4 pub const erase = raw.ImVector_ImVec4_erase; /// eraseTPtr(self: *Vector(Vec4), it: [*]const Vec4, it_last: [*]const Vec4) [*]Vec4 pub const eraseTPtr = raw.ImVector_ImVec4_eraseTPtr; /// erase_unsorted(self: *Vector(Vec4), it: [*]const Vec4) [*]Vec4 pub const erase_unsorted = raw.ImVector_ImVec4_erase_unsorted; /// front(self: *Vector(Vec4)) *Vec4 pub const front = raw.ImVector_ImVec4_front; /// front_const(self: *const Vector(Vec4)) *const Vec4 pub const front_const = raw.ImVector_ImVec4_front_const; /// index_from_ptr(self: *const Vector(Vec4), it: [*]const Vec4) i32 pub const index_from_ptr = raw.ImVector_ImVec4_index_from_ptr; /// insert(self: *Vector(Vec4), it: [*]const Vec4, v: Vec4) [*]Vec4 pub const insert = raw.ImVector_ImVec4_insert; /// pop_back(self: *Vector(Vec4)) void pub const pop_back = raw.ImVector_ImVec4_pop_back; /// push_back(self: *Vector(Vec4), v: Vec4) void pub const push_back = raw.ImVector_ImVec4_push_back; /// push_front(self: *Vector(Vec4), v: Vec4) void pub const push_front = raw.ImVector_ImVec4_push_front; /// reserve(self: *Vector(Vec4), new_capacity: i32) void pub const reserve = raw.ImVector_ImVec4_reserve; /// resize(self: *Vector(Vec4), new_size: i32) void pub const resize = raw.ImVector_ImVec4_resize; /// resizeT(self: *Vector(Vec4), new_size: i32, v: Vec4) void pub const resizeT = raw.ImVector_ImVec4_resizeT; /// shrink(self: *Vector(Vec4), new_size: i32) void pub const shrink = raw.ImVector_ImVec4_shrink; /// size(self: *const Vector(Vec4)) i32 pub const size = raw.ImVector_ImVec4_size; /// size_in_bytes(self: *const Vector(Vec4)) i32 pub const size_in_bytes = raw.ImVector_ImVec4_size_in_bytes; /// swap(self: *Vector(Vec4), rhs: *Vector(Vec4)) void pub const swap = raw.ImVector_ImVec4_swap; }; const FTABLE_ImVector_ImWchar = struct { /// init(self: *Vector(Wchar)) void pub const init = raw.ImVector_ImWchar_ImVector_ImWchar; /// initVector(self: *Vector(Wchar), src: Vector(Wchar)) void pub const initVector = raw.ImVector_ImWchar_ImVector_ImWcharVector; /// _grow_capacity(self: *const Vector(Wchar), sz: i32) i32 pub const _grow_capacity = raw.ImVector_ImWchar__grow_capacity; /// back(self: *Vector(Wchar)) *Wchar pub const back = raw.ImVector_ImWchar_back; /// back_const(self: *const Vector(Wchar)) *const Wchar pub const back_const = raw.ImVector_ImWchar_back_const; /// begin(self: *Vector(Wchar)) [*]Wchar pub const begin = raw.ImVector_ImWchar_begin; /// begin_const(self: *const Vector(Wchar)) [*]const Wchar pub const begin_const = raw.ImVector_ImWchar_begin_const; /// capacity(self: *const Vector(Wchar)) i32 pub const capacity = raw.ImVector_ImWchar_capacity; /// clear(self: *Vector(Wchar)) void pub const clear = raw.ImVector_ImWchar_clear; /// contains(self: *const Vector(Wchar), v: Wchar) bool pub const contains = raw.ImVector_ImWchar_contains; /// deinit(self: *Vector(Wchar)) void pub const deinit = raw.ImVector_ImWchar_destroy; /// empty(self: *const Vector(Wchar)) bool pub const empty = raw.ImVector_ImWchar_empty; /// end(self: *Vector(Wchar)) [*]Wchar pub const end = raw.ImVector_ImWchar_end; /// end_const(self: *const Vector(Wchar)) [*]const Wchar pub const end_const = raw.ImVector_ImWchar_end_const; /// erase(self: *Vector(Wchar), it: [*]const Wchar) [*]Wchar pub const erase = raw.ImVector_ImWchar_erase; /// eraseTPtr(self: *Vector(Wchar), it: [*]const Wchar, it_last: [*]const Wchar) [*]Wchar pub const eraseTPtr = raw.ImVector_ImWchar_eraseTPtr; /// erase_unsorted(self: *Vector(Wchar), it: [*]const Wchar) [*]Wchar pub const erase_unsorted = raw.ImVector_ImWchar_erase_unsorted; /// find(self: *Vector(Wchar), v: Wchar) [*]Wchar pub const find = raw.ImVector_ImWchar_find; /// find_const(self: *const Vector(Wchar), v: Wchar) [*]const Wchar pub const find_const = raw.ImVector_ImWchar_find_const; /// find_erase(self: *Vector(Wchar), v: Wchar) bool pub const find_erase = raw.ImVector_ImWchar_find_erase; /// find_erase_unsorted(self: *Vector(Wchar), v: Wchar) bool pub const find_erase_unsorted = raw.ImVector_ImWchar_find_erase_unsorted; /// front(self: *Vector(Wchar)) *Wchar pub const front = raw.ImVector_ImWchar_front; /// front_const(self: *const Vector(Wchar)) *const Wchar pub const front_const = raw.ImVector_ImWchar_front_const; /// index_from_ptr(self: *const Vector(Wchar), it: [*]const Wchar) i32 pub const index_from_ptr = raw.ImVector_ImWchar_index_from_ptr; /// insert(self: *Vector(Wchar), it: [*]const Wchar, v: Wchar) [*]Wchar pub const insert = raw.ImVector_ImWchar_insert; /// pop_back(self: *Vector(Wchar)) void pub const pop_back = raw.ImVector_ImWchar_pop_back; /// push_back(self: *Vector(Wchar), v: Wchar) void pub const push_back = raw.ImVector_ImWchar_push_back; /// push_front(self: *Vector(Wchar), v: Wchar) void pub const push_front = raw.ImVector_ImWchar_push_front; /// reserve(self: *Vector(Wchar), new_capacity: i32) void pub const reserve = raw.ImVector_ImWchar_reserve; /// resize(self: *Vector(Wchar), new_size: i32) void pub const resize = raw.ImVector_ImWchar_resize; /// resizeT(self: *Vector(Wchar), new_size: i32, v: Wchar) void pub const resizeT = raw.ImVector_ImWchar_resizeT; /// shrink(self: *Vector(Wchar), new_size: i32) void pub const shrink = raw.ImVector_ImWchar_shrink; /// size(self: *const Vector(Wchar)) i32 pub const size = raw.ImVector_ImWchar_size; /// size_in_bytes(self: *const Vector(Wchar)) i32 pub const size_in_bytes = raw.ImVector_ImWchar_size_in_bytes; /// swap(self: *Vector(Wchar), rhs: *Vector(Wchar)) void pub const swap = raw.ImVector_ImWchar_swap; }; const FTABLE_ImVector_char = struct { /// init(self: *Vector(u8)) void pub const init = raw.ImVector_char_ImVector_char; /// initVector(self: *Vector(u8), src: Vector(u8)) void pub const initVector = raw.ImVector_char_ImVector_charVector; /// _grow_capacity(self: *const Vector(u8), sz: i32) i32 pub const _grow_capacity = raw.ImVector_char__grow_capacity; /// back(self: *Vector(u8)) *u8 pub const back = raw.ImVector_char_back; /// back_const(self: *const Vector(u8)) *const u8 pub const back_const = raw.ImVector_char_back_const; /// begin(self: *Vector(u8)) [*]u8 pub const begin = raw.ImVector_char_begin; /// begin_const(self: *const Vector(u8)) [*]const u8 pub const begin_const = raw.ImVector_char_begin_const; /// capacity(self: *const Vector(u8)) i32 pub const capacity = raw.ImVector_char_capacity; /// clear(self: *Vector(u8)) void pub const clear = raw.ImVector_char_clear; /// contains(self: *const Vector(u8), v: u8) bool pub const contains = raw.ImVector_char_contains; /// deinit(self: *Vector(u8)) void pub const deinit = raw.ImVector_char_destroy; /// empty(self: *const Vector(u8)) bool pub const empty = raw.ImVector_char_empty; /// end(self: *Vector(u8)) [*]u8 pub const end = raw.ImVector_char_end; /// end_const(self: *const Vector(u8)) [*]const u8 pub const end_const = raw.ImVector_char_end_const; /// erase(self: *Vector(u8), it: [*]const u8) [*]u8 pub const erase = raw.ImVector_char_erase; /// eraseTPtr(self: *Vector(u8), it: [*]const u8, it_last: [*]const u8) [*]u8 pub const eraseTPtr = raw.ImVector_char_eraseTPtr; /// erase_unsorted(self: *Vector(u8), it: [*]const u8) [*]u8 pub const erase_unsorted = raw.ImVector_char_erase_unsorted; /// find(self: *Vector(u8), v: u8) [*]u8 pub const find = raw.ImVector_char_find; /// find_const(self: *const Vector(u8), v: u8) [*]const u8 pub const find_const = raw.ImVector_char_find_const; /// find_erase(self: *Vector(u8), v: u8) bool pub const find_erase = raw.ImVector_char_find_erase; /// find_erase_unsorted(self: *Vector(u8), v: u8) bool pub const find_erase_unsorted = raw.ImVector_char_find_erase_unsorted; /// front(self: *Vector(u8)) *u8 pub const front = raw.ImVector_char_front; /// front_const(self: *const Vector(u8)) *const u8 pub const front_const = raw.ImVector_char_front_const; /// index_from_ptr(self: *const Vector(u8), it: [*]const u8) i32 pub const index_from_ptr = raw.ImVector_char_index_from_ptr; /// insert(self: *Vector(u8), it: [*]const u8, v: u8) [*]u8 pub const insert = raw.ImVector_char_insert; /// pop_back(self: *Vector(u8)) void pub const pop_back = raw.ImVector_char_pop_back; /// push_back(self: *Vector(u8), v: u8) void pub const push_back = raw.ImVector_char_push_back; /// push_front(self: *Vector(u8), v: u8) void pub const push_front = raw.ImVector_char_push_front; /// reserve(self: *Vector(u8), new_capacity: i32) void pub const reserve = raw.ImVector_char_reserve; /// resize(self: *Vector(u8), new_size: i32) void pub const resize = raw.ImVector_char_resize; /// resizeT(self: *Vector(u8), new_size: i32, v: u8) void pub const resizeT = raw.ImVector_char_resizeT; /// shrink(self: *Vector(u8), new_size: i32) void pub const shrink = raw.ImVector_char_shrink; /// size(self: *const Vector(u8)) i32 pub const size = raw.ImVector_char_size; /// size_in_bytes(self: *const Vector(u8)) i32 pub const size_in_bytes = raw.ImVector_char_size_in_bytes; /// swap(self: *Vector(u8), rhs: *Vector(u8)) void pub const swap = raw.ImVector_char_swap; }; const FTABLE_ImVector_float = struct { /// init(self: *Vector(f32)) void pub const init = raw.ImVector_float_ImVector_float; /// initVector(self: *Vector(f32), src: Vector(f32)) void pub const initVector = raw.ImVector_float_ImVector_floatVector; /// _grow_capacity(self: *const Vector(f32), sz: i32) i32 pub const _grow_capacity = raw.ImVector_float__grow_capacity; /// back(self: *Vector(f32)) *f32 pub const back = raw.ImVector_float_back; /// back_const(self: *const Vector(f32)) *const f32 pub const back_const = raw.ImVector_float_back_const; /// begin(self: *Vector(f32)) [*]f32 pub const begin = raw.ImVector_float_begin; /// begin_const(self: *const Vector(f32)) [*]const f32 pub const begin_const = raw.ImVector_float_begin_const; /// capacity(self: *const Vector(f32)) i32 pub const capacity = raw.ImVector_float_capacity; /// clear(self: *Vector(f32)) void pub const clear = raw.ImVector_float_clear; /// contains(self: *const Vector(f32), v: f32) bool pub const contains = raw.ImVector_float_contains; /// deinit(self: *Vector(f32)) void pub const deinit = raw.ImVector_float_destroy; /// empty(self: *const Vector(f32)) bool pub const empty = raw.ImVector_float_empty; /// end(self: *Vector(f32)) [*]f32 pub const end = raw.ImVector_float_end; /// end_const(self: *const Vector(f32)) [*]const f32 pub const end_const = raw.ImVector_float_end_const; /// erase(self: *Vector(f32), it: [*]const f32) [*]f32 pub const erase = raw.ImVector_float_erase; /// eraseTPtr(self: *Vector(f32), it: [*]const f32, it_last: [*]const f32) [*]f32 pub const eraseTPtr = raw.ImVector_float_eraseTPtr; /// erase_unsorted(self: *Vector(f32), it: [*]const f32) [*]f32 pub const erase_unsorted = raw.ImVector_float_erase_unsorted; /// find(self: *Vector(f32), v: f32) [*]f32 pub const find = raw.ImVector_float_find; /// find_const(self: *const Vector(f32), v: f32) [*]const f32 pub const find_const = raw.ImVector_float_find_const; /// find_erase(self: *Vector(f32), v: f32) bool pub const find_erase = raw.ImVector_float_find_erase; /// find_erase_unsorted(self: *Vector(f32), v: f32) bool pub const find_erase_unsorted = raw.ImVector_float_find_erase_unsorted; /// front(self: *Vector(f32)) *f32 pub const front = raw.ImVector_float_front; /// front_const(self: *const Vector(f32)) *const f32 pub const front_const = raw.ImVector_float_front_const; /// index_from_ptr(self: *const Vector(f32), it: [*]const f32) i32 pub const index_from_ptr = raw.ImVector_float_index_from_ptr; /// insert(self: *Vector(f32), it: [*]const f32, v: f32) [*]f32 pub const insert = raw.ImVector_float_insert; /// pop_back(self: *Vector(f32)) void pub const pop_back = raw.ImVector_float_pop_back; /// push_back(self: *Vector(f32), v: f32) void pub const push_back = raw.ImVector_float_push_back; /// push_front(self: *Vector(f32), v: f32) void pub const push_front = raw.ImVector_float_push_front; /// reserve(self: *Vector(f32), new_capacity: i32) void pub const reserve = raw.ImVector_float_reserve; /// resize(self: *Vector(f32), new_size: i32) void pub const resize = raw.ImVector_float_resize; /// resizeT(self: *Vector(f32), new_size: i32, v: f32) void pub const resizeT = raw.ImVector_float_resizeT; /// shrink(self: *Vector(f32), new_size: i32) void pub const shrink = raw.ImVector_float_shrink; /// size(self: *const Vector(f32)) i32 pub const size = raw.ImVector_float_size; /// size_in_bytes(self: *const Vector(f32)) i32 pub const size_in_bytes = raw.ImVector_float_size_in_bytes; /// swap(self: *Vector(f32), rhs: *Vector(f32)) void pub const swap = raw.ImVector_float_swap; }; fn getFTABLE_ImVector(comptime T: type) type { if (T == DrawChannel) return FTABLE_ImVector_ImDrawChannel; if (T == DrawCmd) return FTABLE_ImVector_ImDrawCmd; if (T == DrawIdx) return FTABLE_ImVector_ImDrawIdx; if (T == DrawVert) return FTABLE_ImVector_ImDrawVert; if (T == *Font) return FTABLE_ImVector_ImFontPtr; if (T == FontAtlasCustomRect) return FTABLE_ImVector_ImFontAtlasCustomRect; if (T == FontConfig) return FTABLE_ImVector_ImFontConfig; if (T == FontGlyph) return FTABLE_ImVector_ImFontGlyph; if (T == StoragePair) return FTABLE_ImVector_ImGuiStoragePair; if (T == TextRange) return FTABLE_ImVector_ImGuiTextRange; if (T == TextureID) return FTABLE_ImVector_ImTextureID; if (T == u32) return FTABLE_ImVector_ImU32; if (T == Vec2) return FTABLE_ImVector_ImVec2; if (T == Vec4) return FTABLE_ImVector_ImVec4; if (T == Wchar) return FTABLE_ImVector_ImWchar; if (T == u8) return FTABLE_ImVector_char; if (T == f32) return FTABLE_ImVector_float; @compileError("Invalid Vector type"); } pub fn Vector(comptime T: type) type { return extern struct { len: i32, capacity: i32, items: [*]T, pub usingnamespace getFTABLE_ImVector(T); pub fn slice(self: * const @This()) []T { return self.items[0..@intCast(usize, self.len)]; } }; } pub inline fn AcceptDragDropPayloadExt(kind: ?[*:0]const u8, flags: DragDropFlags) ?*const Payload { return raw.igAcceptDragDropPayload(kind, flags.toInt()); } pub inline fn AcceptDragDropPayload(kind: ?[*:0]const u8) ?*const Payload { return AcceptDragDropPayloadExt(kind, .{}); } /// AlignTextToFramePadding() void pub const AlignTextToFramePadding = raw.igAlignTextToFramePadding; /// ArrowButton(str_id: ?[*:0]const u8, dir: Dir) bool pub const ArrowButton = raw.igArrowButton; pub inline fn BeginExt(name: ?[*:0]const u8, p_open: ?*bool, flags: WindowFlags) bool { return raw.igBegin(name, p_open, flags.toInt()); } pub inline fn Begin(name: ?[*:0]const u8) bool { return BeginExt(name, null, .{}); } pub inline fn BeginChildStrExt(str_id: ?[*:0]const u8, size: Vec2, border: bool, flags: WindowFlags) bool { return raw.igBeginChildStr(str_id, size, border, flags.toInt()); } pub inline fn BeginChildStr(str_id: ?[*:0]const u8) bool { return BeginChildStrExt(str_id, .{.x=0,.y=0}, false, .{}); } pub inline fn BeginChildIDExt(id: ID, size: Vec2, border: bool, flags: WindowFlags) bool { return raw.igBeginChildID(id, size, border, flags.toInt()); } pub inline fn BeginChildID(id: ID) bool { return BeginChildIDExt(id, .{.x=0,.y=0}, false, .{}); } pub inline fn BeginChildFrameExt(id: ID, size: Vec2, flags: WindowFlags) bool { return raw.igBeginChildFrame(id, size, flags.toInt()); } pub inline fn BeginChildFrame(id: ID, size: Vec2) bool { return BeginChildFrameExt(id, size, .{}); } pub inline fn BeginComboExt(label: ?[*:0]const u8, preview_value: ?[*:0]const u8, flags: ComboFlags) bool { return raw.igBeginCombo(label, preview_value, flags.toInt()); } pub inline fn BeginCombo(label: ?[*:0]const u8, preview_value: ?[*:0]const u8) bool { return BeginComboExt(label, preview_value, .{}); } pub inline fn BeginDragDropSourceExt(flags: DragDropFlags) bool { return raw.igBeginDragDropSource(flags.toInt()); } pub inline fn BeginDragDropSource() bool { return BeginDragDropSourceExt(.{}); } /// BeginDragDropTarget() bool pub const BeginDragDropTarget = raw.igBeginDragDropTarget; /// BeginGroup() void pub const BeginGroup = raw.igBeginGroup; /// BeginMainMenuBar() bool pub const BeginMainMenuBar = raw.igBeginMainMenuBar; /// BeginMenuExt(label: ?[*:0]const u8, enabled: bool) bool pub const BeginMenuExt = raw.igBeginMenu; pub inline fn BeginMenu(label: ?[*:0]const u8) bool { return BeginMenuExt(label, true); } /// BeginMenuBar() bool pub const BeginMenuBar = raw.igBeginMenuBar; pub inline fn BeginPopupExt(str_id: ?[*:0]const u8, flags: WindowFlags) bool { return raw.igBeginPopup(str_id, flags.toInt()); } pub inline fn BeginPopup(str_id: ?[*:0]const u8) bool { return BeginPopupExt(str_id, .{}); } /// BeginPopupContextItemExt(str_id: ?[*:0]const u8, mouse_button: MouseButton) bool pub const BeginPopupContextItemExt = raw.igBeginPopupContextItem; pub inline fn BeginPopupContextItem() bool { return BeginPopupContextItemExt(null, .Right); } /// BeginPopupContextVoidExt(str_id: ?[*:0]const u8, mouse_button: MouseButton) bool pub const BeginPopupContextVoidExt = raw.igBeginPopupContextVoid; pub inline fn BeginPopupContextVoid() bool { return BeginPopupContextVoidExt(null, .Right); } /// BeginPopupContextWindowExt(str_id: ?[*:0]const u8, mouse_button: MouseButton, also_over_items: bool) bool pub const BeginPopupContextWindowExt = raw.igBeginPopupContextWindow; pub inline fn BeginPopupContextWindow() bool { return BeginPopupContextWindowExt(null, .Right, true); } pub inline fn BeginPopupModalExt(name: ?[*:0]const u8, p_open: ?*bool, flags: WindowFlags) bool { return raw.igBeginPopupModal(name, p_open, flags.toInt()); } pub inline fn BeginPopupModal(name: ?[*:0]const u8) bool { return BeginPopupModalExt(name, null, .{}); } pub inline fn BeginTabBarExt(str_id: ?[*:0]const u8, flags: TabBarFlags) bool { return raw.igBeginTabBar(str_id, flags.toInt()); } pub inline fn BeginTabBar(str_id: ?[*:0]const u8) bool { return BeginTabBarExt(str_id, .{}); } pub inline fn BeginTabItemExt(label: ?[*:0]const u8, p_open: ?*bool, flags: TabItemFlags) bool { return raw.igBeginTabItem(label, p_open, flags.toInt()); } pub inline fn BeginTabItem(label: ?[*:0]const u8) bool { return BeginTabItemExt(label, null, .{}); } /// BeginTooltip() void pub const BeginTooltip = raw.igBeginTooltip; /// Bullet() void pub const Bullet = raw.igBullet; /// BulletText(fmt: ?[*:0]const u8, ...: ...) void pub const BulletText = raw.igBulletText; /// ButtonExt(label: ?[*:0]const u8, size: Vec2) bool pub const ButtonExt = raw.igButton; pub inline fn Button(label: ?[*:0]const u8) bool { return ButtonExt(label, .{.x=0,.y=0}); } /// CalcItemWidth() f32 pub const CalcItemWidth = raw.igCalcItemWidth; /// CalcListClipping(items_count: i32, items_height: f32, out_items_display_start: *i32, out_items_display_end: *i32) void pub const CalcListClipping = raw.igCalcListClipping; pub inline fn CalcTextSizeExt(text: ?[*]const u8, text_end: ?[*]const u8, hide_text_after_double_hash: bool, wrap_width: f32) Vec2 { var out: Vec2 = undefined; raw.igCalcTextSize_nonUDT(&out, text, text_end, hide_text_after_double_hash, wrap_width); return out; } pub inline fn CalcTextSize(text: ?[*]const u8) Vec2 { return CalcTextSizeExt(text, null, false, -1.0); } /// CaptureKeyboardFromAppExt(want_capture_keyboard_value: bool) void pub const CaptureKeyboardFromAppExt = raw.igCaptureKeyboardFromApp; pub inline fn CaptureKeyboardFromApp() void { return CaptureKeyboardFromAppExt(true); } /// CaptureMouseFromAppExt(want_capture_mouse_value: bool) void pub const CaptureMouseFromAppExt = raw.igCaptureMouseFromApp; pub inline fn CaptureMouseFromApp() void { return CaptureMouseFromAppExt(true); } /// Checkbox(label: ?[*:0]const u8, v: *bool) bool pub const Checkbox = raw.igCheckbox; /// CheckboxFlags(label: ?[*:0]const u8, flags: ?*u32, flags_value: u32) bool pub const CheckboxFlags = raw.igCheckboxFlags; /// CloseCurrentPopup() void pub const CloseCurrentPopup = raw.igCloseCurrentPopup; pub inline fn CollapsingHeaderExt(label: ?[*:0]const u8, flags: TreeNodeFlags) bool { return raw.igCollapsingHeader(label, flags.toInt()); } pub inline fn CollapsingHeader(label: ?[*:0]const u8) bool { return CollapsingHeaderExt(label, .{}); } pub inline fn CollapsingHeaderBoolPtrExt(label: ?[*:0]const u8, p_open: ?*bool, flags: TreeNodeFlags) bool { return raw.igCollapsingHeaderBoolPtr(label, p_open, flags.toInt()); } pub inline fn CollapsingHeaderBoolPtr(label: ?[*:0]const u8, p_open: ?*bool) bool { return CollapsingHeaderBoolPtrExt(label, p_open, .{}); } pub inline fn ColorButtonExt(desc_id: ?[*:0]const u8, col: Vec4, flags: ColorEditFlags, size: Vec2) bool { return raw.igColorButton(desc_id, col, flags.toInt(), size); } pub inline fn ColorButton(desc_id: ?[*:0]const u8, col: Vec4) bool { return ColorButtonExt(desc_id, col, .{}, .{.x=0,.y=0}); } /// ColorConvertFloat4ToU32(in: Vec4) u32 pub const ColorConvertFloat4ToU32 = raw.igColorConvertFloat4ToU32; /// ColorConvertHSVtoRGB(h: f32, s: f32, v: f32, out_r: *f32, out_g: *f32, out_b: *f32) void pub const ColorConvertHSVtoRGB = raw.igColorConvertHSVtoRGB; /// ColorConvertRGBtoHSV(r: f32, g: f32, b: f32, out_h: *f32, out_s: *f32, out_v: *f32) void pub const ColorConvertRGBtoHSV = raw.igColorConvertRGBtoHSV; pub inline fn ColorConvertU32ToFloat4(in: u32) Vec4 { var out: Vec4 = undefined; raw.igColorConvertU32ToFloat4_nonUDT(&out, in); return out; } pub inline fn ColorEdit3Ext(label: ?[*:0]const u8, col: *[3]f32, flags: ColorEditFlags) bool { return raw.igColorEdit3(label, col, flags.toInt()); } pub inline fn ColorEdit3(label: ?[*:0]const u8, col: *[3]f32) bool { return ColorEdit3Ext(label, col, .{}); } pub inline fn ColorEdit4Ext(label: ?[*:0]const u8, col: *[4]f32, flags: ColorEditFlags) bool { return raw.igColorEdit4(label, col, flags.toInt()); } pub inline fn ColorEdit4(label: ?[*:0]const u8, col: *[4]f32) bool { return ColorEdit4Ext(label, col, .{}); } pub inline fn ColorPicker3Ext(label: ?[*:0]const u8, col: *[3]f32, flags: ColorEditFlags) bool { return raw.igColorPicker3(label, col, flags.toInt()); } pub inline fn ColorPicker3(label: ?[*:0]const u8, col: *[3]f32) bool { return ColorPicker3Ext(label, col, .{}); } pub inline fn ColorPicker4Ext(label: ?[*:0]const u8, col: *[4]f32, flags: ColorEditFlags, ref_col: ?*const[4]f32) bool { return raw.igColorPicker4(label, col, flags.toInt(), ref_col); } pub inline fn ColorPicker4(label: ?[*:0]const u8, col: *[4]f32) bool { return ColorPicker4Ext(label, col, .{}, null); } /// ColumnsExt(count: i32, id: ?[*:0]const u8, border: bool) void pub const ColumnsExt = raw.igColumns; pub inline fn Columns() void { return ColumnsExt(1, null, true); } /// ComboExt(label: ?[*:0]const u8, current_item: ?*i32, items: [*]const[*:0]const u8, items_count: i32, popup_max_height_in_items: i32) bool pub const ComboExt = raw.igCombo; pub inline fn Combo(label: ?[*:0]const u8, current_item: ?*i32, items: [*]const[*:0]const u8, items_count: i32) bool { return ComboExt(label, current_item, items, items_count, -1); } /// ComboStrExt(label: ?[*:0]const u8, current_item: ?*i32, items_separated_by_zeros: ?[*]const u8, popup_max_height_in_items: i32) bool pub const ComboStrExt = raw.igComboStr; pub inline fn ComboStr(label: ?[*:0]const u8, current_item: ?*i32, items_separated_by_zeros: ?[*]const u8) bool { return ComboStrExt(label, current_item, items_separated_by_zeros, -1); } /// ComboFnPtrExt(label: ?[*:0]const u8, current_item: ?*i32, items_getter: ?fn (data: ?*c_void, idx: i32, out_text: *?[*:0]const u8) callconv(.C) bool, data: ?*c_void, items_count: i32, popup_max_height_in_items: i32) bool pub const ComboFnPtrExt = raw.igComboFnPtr; pub inline fn ComboFnPtr(label: ?[*:0]const u8, current_item: ?*i32, items_getter: ?fn (data: ?*c_void, idx: i32, out_text: *?[*:0]const u8) callconv(.C) bool, data: ?*c_void, items_count: i32) bool { return ComboFnPtrExt(label, current_item, items_getter, data, items_count, -1); } /// CreateContextExt(shared_font_atlas: ?*FontAtlas) ?*Context pub const CreateContextExt = raw.igCreateContext; pub inline fn CreateContext() ?*Context { return CreateContextExt(null); } /// DebugCheckVersionAndDataLayout(version_str: ?[*:0]const u8, sz_io: usize, sz_style: usize, sz_vec2: usize, sz_vec4: usize, sz_drawvert: usize, sz_drawidx: usize) bool pub const DebugCheckVersionAndDataLayout = raw.igDebugCheckVersionAndDataLayout; /// DestroyContextExt(ctx: ?*Context) void pub const DestroyContextExt = raw.igDestroyContext; pub inline fn DestroyContext() void { return DestroyContextExt(null); } /// DragFloatExt(label: ?[*:0]const u8, v: *f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const DragFloatExt = raw.igDragFloat; pub inline fn DragFloat(label: ?[*:0]const u8, v: *f32) bool { return DragFloatExt(label, v, 1.0, 0.0, 0.0, "%.3f", 1.0); } /// DragFloat2Ext(label: ?[*:0]const u8, v: *[2]f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const DragFloat2Ext = raw.igDragFloat2; pub inline fn DragFloat2(label: ?[*:0]const u8, v: *[2]f32) bool { return DragFloat2Ext(label, v, 1.0, 0.0, 0.0, "%.3f", 1.0); } /// DragFloat3Ext(label: ?[*:0]const u8, v: *[3]f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const DragFloat3Ext = raw.igDragFloat3; pub inline fn DragFloat3(label: ?[*:0]const u8, v: *[3]f32) bool { return DragFloat3Ext(label, v, 1.0, 0.0, 0.0, "%.3f", 1.0); } /// DragFloat4Ext(label: ?[*:0]const u8, v: *[4]f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const DragFloat4Ext = raw.igDragFloat4; pub inline fn DragFloat4(label: ?[*:0]const u8, v: *[4]f32) bool { return DragFloat4Ext(label, v, 1.0, 0.0, 0.0, "%.3f", 1.0); } /// DragFloatRange2Ext(label: ?[*:0]const u8, v_current_min: *f32, v_current_max: *f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, format_max: ?[*:0]const u8, power: f32) bool pub const DragFloatRange2Ext = raw.igDragFloatRange2; pub inline fn DragFloatRange2(label: ?[*:0]const u8, v_current_min: *f32, v_current_max: *f32) bool { return DragFloatRange2Ext(label, v_current_min, v_current_max, 1.0, 0.0, 0.0, "%.3f", null, 1.0); } /// DragIntExt(label: ?[*:0]const u8, v: *i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const DragIntExt = raw.igDragInt; pub inline fn DragInt(label: ?[*:0]const u8, v: *i32) bool { return DragIntExt(label, v, 1.0, 0, 0, "%d"); } /// DragInt2Ext(label: ?[*:0]const u8, v: *[2]i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const DragInt2Ext = raw.igDragInt2; pub inline fn DragInt2(label: ?[*:0]const u8, v: *[2]i32) bool { return DragInt2Ext(label, v, 1.0, 0, 0, "%d"); } /// DragInt3Ext(label: ?[*:0]const u8, v: *[3]i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const DragInt3Ext = raw.igDragInt3; pub inline fn DragInt3(label: ?[*:0]const u8, v: *[3]i32) bool { return DragInt3Ext(label, v, 1.0, 0, 0, "%d"); } /// DragInt4Ext(label: ?[*:0]const u8, v: *[4]i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const DragInt4Ext = raw.igDragInt4; pub inline fn DragInt4(label: ?[*:0]const u8, v: *[4]i32) bool { return DragInt4Ext(label, v, 1.0, 0, 0, "%d"); } /// DragIntRange2Ext(label: ?[*:0]const u8, v_current_min: *i32, v_current_max: *i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8, format_max: ?[*:0]const u8) bool pub const DragIntRange2Ext = raw.igDragIntRange2; pub inline fn DragIntRange2(label: ?[*:0]const u8, v_current_min: *i32, v_current_max: *i32) bool { return DragIntRange2Ext(label, v_current_min, v_current_max, 1.0, 0, 0, "%d", null); } /// DragScalarExt(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) bool pub const DragScalarExt = raw.igDragScalar; pub inline fn DragScalar(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, v_speed: f32) bool { return DragScalarExt(label, data_type, p_data, v_speed, null, null, null, 1.0); } /// DragScalarNExt(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) bool pub const DragScalarNExt = raw.igDragScalarN; pub inline fn DragScalarN(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, v_speed: f32) bool { return DragScalarNExt(label, data_type, p_data, components, v_speed, null, null, null, 1.0); } /// Dummy(size: Vec2) void pub const Dummy = raw.igDummy; /// End() void pub const End = raw.igEnd; /// EndChild() void pub const EndChild = raw.igEndChild; /// EndChildFrame() void pub const EndChildFrame = raw.igEndChildFrame; /// EndCombo() void pub const EndCombo = raw.igEndCombo; /// EndDragDropSource() void pub const EndDragDropSource = raw.igEndDragDropSource; /// EndDragDropTarget() void pub const EndDragDropTarget = raw.igEndDragDropTarget; /// EndFrame() void pub const EndFrame = raw.igEndFrame; /// EndGroup() void pub const EndGroup = raw.igEndGroup; /// EndMainMenuBar() void pub const EndMainMenuBar = raw.igEndMainMenuBar; /// EndMenu() void pub const EndMenu = raw.igEndMenu; /// EndMenuBar() void pub const EndMenuBar = raw.igEndMenuBar; /// EndPopup() void pub const EndPopup = raw.igEndPopup; /// EndTabBar() void pub const EndTabBar = raw.igEndTabBar; /// EndTabItem() void pub const EndTabItem = raw.igEndTabItem; /// EndTooltip() void pub const EndTooltip = raw.igEndTooltip; /// GetBackgroundDrawList() ?*DrawList pub const GetBackgroundDrawList = raw.igGetBackgroundDrawList; /// GetClipboardText() ?[*:0]const u8 pub const GetClipboardText = raw.igGetClipboardText; /// GetColorU32Ext(idx: Col, alpha_mul: f32) u32 pub const GetColorU32Ext = raw.igGetColorU32; pub inline fn GetColorU32(idx: Col) u32 { return GetColorU32Ext(idx, 1.0); } /// GetColorU32Vec4(col: Vec4) u32 pub const GetColorU32Vec4 = raw.igGetColorU32Vec4; /// GetColorU32U32(col: u32) u32 pub const GetColorU32U32 = raw.igGetColorU32U32; /// GetColumnIndex() i32 pub const GetColumnIndex = raw.igGetColumnIndex; /// GetColumnOffsetExt(column_index: i32) f32 pub const GetColumnOffsetExt = raw.igGetColumnOffset; pub inline fn GetColumnOffset() f32 { return GetColumnOffsetExt(-1); } /// GetColumnWidthExt(column_index: i32) f32 pub const GetColumnWidthExt = raw.igGetColumnWidth; pub inline fn GetColumnWidth() f32 { return GetColumnWidthExt(-1); } /// GetColumnsCount() i32 pub const GetColumnsCount = raw.igGetColumnsCount; pub inline fn GetContentRegionAvail() Vec2 { var out: Vec2 = undefined; raw.igGetContentRegionAvail_nonUDT(&out); return out; } pub inline fn GetContentRegionMax() Vec2 { var out: Vec2 = undefined; raw.igGetContentRegionMax_nonUDT(&out); return out; } /// GetCurrentContext() ?*Context pub const GetCurrentContext = raw.igGetCurrentContext; pub inline fn GetCursorPos() Vec2 { var out: Vec2 = undefined; raw.igGetCursorPos_nonUDT(&out); return out; } /// GetCursorPosX() f32 pub const GetCursorPosX = raw.igGetCursorPosX; /// GetCursorPosY() f32 pub const GetCursorPosY = raw.igGetCursorPosY; pub inline fn GetCursorScreenPos() Vec2 { var out: Vec2 = undefined; raw.igGetCursorScreenPos_nonUDT(&out); return out; } pub inline fn GetCursorStartPos() Vec2 { var out: Vec2 = undefined; raw.igGetCursorStartPos_nonUDT(&out); return out; } /// GetDragDropPayload() ?*const Payload pub const GetDragDropPayload = raw.igGetDragDropPayload; /// GetDrawData() *DrawData pub const GetDrawData = raw.igGetDrawData; /// GetDrawListSharedData() ?*DrawListSharedData pub const GetDrawListSharedData = raw.igGetDrawListSharedData; /// GetFont() ?*Font pub const GetFont = raw.igGetFont; /// GetFontSize() f32 pub const GetFontSize = raw.igGetFontSize; pub inline fn GetFontTexUvWhitePixel() Vec2 { var out: Vec2 = undefined; raw.igGetFontTexUvWhitePixel_nonUDT(&out); return out; } /// GetForegroundDrawList() ?*DrawList pub const GetForegroundDrawList = raw.igGetForegroundDrawList; /// GetFrameCount() i32 pub const GetFrameCount = raw.igGetFrameCount; /// GetFrameHeight() f32 pub const GetFrameHeight = raw.igGetFrameHeight; /// GetFrameHeightWithSpacing() f32 pub const GetFrameHeightWithSpacing = raw.igGetFrameHeightWithSpacing; /// GetIDStr(str_id: ?[*:0]const u8) ID pub const GetIDStr = raw.igGetIDStr; /// GetIDRange(str_id_begin: ?[*]const u8, str_id_end: ?[*]const u8) ID pub const GetIDRange = raw.igGetIDRange; /// GetIDPtr(ptr_id: ?*const c_void) ID pub const GetIDPtr = raw.igGetIDPtr; /// GetIO() *IO pub const GetIO = raw.igGetIO; pub inline fn GetItemRectMax() Vec2 { var out: Vec2 = undefined; raw.igGetItemRectMax_nonUDT(&out); return out; } pub inline fn GetItemRectMin() Vec2 { var out: Vec2 = undefined; raw.igGetItemRectMin_nonUDT(&out); return out; } pub inline fn GetItemRectSize() Vec2 { var out: Vec2 = undefined; raw.igGetItemRectSize_nonUDT(&out); return out; } /// GetKeyIndex(imgui_key: Key) i32 pub const GetKeyIndex = raw.igGetKeyIndex; /// GetKeyPressedAmount(key_index: i32, repeat_delay: f32, rate: f32) i32 pub const GetKeyPressedAmount = raw.igGetKeyPressedAmount; /// GetMouseCursor() MouseCursor pub const GetMouseCursor = raw.igGetMouseCursor; pub inline fn GetMouseDragDeltaExt(button: MouseButton, lock_threshold: f32) Vec2 { var out: Vec2 = undefined; raw.igGetMouseDragDelta_nonUDT(&out, button, lock_threshold); return out; } pub inline fn GetMouseDragDelta() Vec2 { return GetMouseDragDeltaExt(.Left, -1.0); } pub inline fn GetMousePos() Vec2 { var out: Vec2 = undefined; raw.igGetMousePos_nonUDT(&out); return out; } pub inline fn GetMousePosOnOpeningCurrentPopup() Vec2 { var out: Vec2 = undefined; raw.igGetMousePosOnOpeningCurrentPopup_nonUDT(&out); return out; } /// GetScrollMaxX() f32 pub const GetScrollMaxX = raw.igGetScrollMaxX; /// GetScrollMaxY() f32 pub const GetScrollMaxY = raw.igGetScrollMaxY; /// GetScrollX() f32 pub const GetScrollX = raw.igGetScrollX; /// GetScrollY() f32 pub const GetScrollY = raw.igGetScrollY; /// GetStateStorage() ?*Storage pub const GetStateStorage = raw.igGetStateStorage; /// GetStyle() ?*Style pub const GetStyle = raw.igGetStyle; /// GetStyleColorName(idx: Col) ?[*:0]const u8 pub const GetStyleColorName = raw.igGetStyleColorName; /// GetStyleColorVec4(idx: Col) ?*const Vec4 pub const GetStyleColorVec4 = raw.igGetStyleColorVec4; /// GetTextLineHeight() f32 pub const GetTextLineHeight = raw.igGetTextLineHeight; /// GetTextLineHeightWithSpacing() f32 pub const GetTextLineHeightWithSpacing = raw.igGetTextLineHeightWithSpacing; /// GetTime() f64 pub const GetTime = raw.igGetTime; /// GetTreeNodeToLabelSpacing() f32 pub const GetTreeNodeToLabelSpacing = raw.igGetTreeNodeToLabelSpacing; /// GetVersion() ?[*:0]const u8 pub const GetVersion = raw.igGetVersion; pub inline fn GetWindowContentRegionMax() Vec2 { var out: Vec2 = undefined; raw.igGetWindowContentRegionMax_nonUDT(&out); return out; } pub inline fn GetWindowContentRegionMin() Vec2 { var out: Vec2 = undefined; raw.igGetWindowContentRegionMin_nonUDT(&out); return out; } /// GetWindowContentRegionWidth() f32 pub const GetWindowContentRegionWidth = raw.igGetWindowContentRegionWidth; /// GetWindowDrawList() ?*DrawList pub const GetWindowDrawList = raw.igGetWindowDrawList; /// GetWindowHeight() f32 pub const GetWindowHeight = raw.igGetWindowHeight; pub inline fn GetWindowPos() Vec2 { var out: Vec2 = undefined; raw.igGetWindowPos_nonUDT(&out); return out; } pub inline fn GetWindowSize() Vec2 { var out: Vec2 = undefined; raw.igGetWindowSize_nonUDT(&out); return out; } /// GetWindowWidth() f32 pub const GetWindowWidth = raw.igGetWindowWidth; /// ImageExt(user_texture_id: TextureID, size: Vec2, uv0: Vec2, uv1: Vec2, tint_col: Vec4, border_col: Vec4) void pub const ImageExt = raw.igImage; pub inline fn Image(user_texture_id: TextureID, size: Vec2) void { return ImageExt(user_texture_id, size, .{.x=0,.y=0}, .{.x=1,.y=1}, .{.x=1,.y=1,.z=1,.w=1}, .{.x=0,.y=0,.z=0,.w=0}); } /// ImageButtonExt(user_texture_id: TextureID, size: Vec2, uv0: Vec2, uv1: Vec2, frame_padding: i32, bg_col: Vec4, tint_col: Vec4) bool pub const ImageButtonExt = raw.igImageButton; pub inline fn ImageButton(user_texture_id: TextureID, size: Vec2) bool { return ImageButtonExt(user_texture_id, size, .{.x=0,.y=0}, .{.x=1,.y=1}, -1, .{.x=0,.y=0,.z=0,.w=0}, .{.x=1,.y=1,.z=1,.w=1}); } /// IndentExt(indent_w: f32) void pub const IndentExt = raw.igIndent; pub inline fn Indent() void { return IndentExt(0.0); } pub inline fn InputDoubleExt(label: ?[*:0]const u8, v: *f64, step: f64, step_fast: f64, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputDouble(label, v, step, step_fast, format, flags.toInt()); } pub inline fn InputDouble(label: ?[*:0]const u8, v: *f64) bool { return InputDoubleExt(label, v, 0.0, 0.0, "%.6f", .{}); } pub inline fn InputFloatExt(label: ?[*:0]const u8, v: *f32, step: f32, step_fast: f32, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputFloat(label, v, step, step_fast, format, flags.toInt()); } pub inline fn InputFloat(label: ?[*:0]const u8, v: *f32) bool { return InputFloatExt(label, v, 0.0, 0.0, "%.3f", .{}); } pub inline fn InputFloat2Ext(label: ?[*:0]const u8, v: *[2]f32, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputFloat2(label, v, format, flags.toInt()); } pub inline fn InputFloat2(label: ?[*:0]const u8, v: *[2]f32) bool { return InputFloat2Ext(label, v, "%.3f", .{}); } pub inline fn InputFloat3Ext(label: ?[*:0]const u8, v: *[3]f32, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputFloat3(label, v, format, flags.toInt()); } pub inline fn InputFloat3(label: ?[*:0]const u8, v: *[3]f32) bool { return InputFloat3Ext(label, v, "%.3f", .{}); } pub inline fn InputFloat4Ext(label: ?[*:0]const u8, v: *[4]f32, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputFloat4(label, v, format, flags.toInt()); } pub inline fn InputFloat4(label: ?[*:0]const u8, v: *[4]f32) bool { return InputFloat4Ext(label, v, "%.3f", .{}); } pub inline fn InputIntExt(label: ?[*:0]const u8, v: *i32, step: i32, step_fast: i32, flags: InputTextFlags) bool { return raw.igInputInt(label, v, step, step_fast, flags.toInt()); } pub inline fn InputInt(label: ?[*:0]const u8, v: *i32) bool { return InputIntExt(label, v, 1, 100, .{}); } pub inline fn InputInt2Ext(label: ?[*:0]const u8, v: *[2]i32, flags: InputTextFlags) bool { return raw.igInputInt2(label, v, flags.toInt()); } pub inline fn InputInt2(label: ?[*:0]const u8, v: *[2]i32) bool { return InputInt2Ext(label, v, .{}); } pub inline fn InputInt3Ext(label: ?[*:0]const u8, v: *[3]i32, flags: InputTextFlags) bool { return raw.igInputInt3(label, v, flags.toInt()); } pub inline fn InputInt3(label: ?[*:0]const u8, v: *[3]i32) bool { return InputInt3Ext(label, v, .{}); } pub inline fn InputInt4Ext(label: ?[*:0]const u8, v: *[4]i32, flags: InputTextFlags) bool { return raw.igInputInt4(label, v, flags.toInt()); } pub inline fn InputInt4(label: ?[*:0]const u8, v: *[4]i32) bool { return InputInt4Ext(label, v, .{}); } pub inline fn InputScalarExt(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, p_step: ?*const c_void, p_step_fast: ?*const c_void, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputScalar(label, data_type, p_data, p_step, p_step_fast, format, flags.toInt()); } pub inline fn InputScalar(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void) bool { return InputScalarExt(label, data_type, p_data, null, null, null, .{}); } pub inline fn InputScalarNExt(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, p_step: ?*const c_void, p_step_fast: ?*const c_void, format: ?[*:0]const u8, flags: InputTextFlags) bool { return raw.igInputScalarN(label, data_type, p_data, components, p_step, p_step_fast, format, flags.toInt()); } pub inline fn InputScalarN(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32) bool { return InputScalarNExt(label, data_type, p_data, components, null, null, null, .{}); } pub inline fn InputTextExt(label: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize, flags: InputTextFlags, callback: InputTextCallback, user_data: ?*c_void) bool { return raw.igInputText(label, buf, buf_size, flags.toInt(), callback, user_data); } pub inline fn InputText(label: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize) bool { return InputTextExt(label, buf, buf_size, .{}, null, null); } pub inline fn InputTextMultilineExt(label: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize, size: Vec2, flags: InputTextFlags, callback: InputTextCallback, user_data: ?*c_void) bool { return raw.igInputTextMultiline(label, buf, buf_size, size, flags.toInt(), callback, user_data); } pub inline fn InputTextMultiline(label: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize) bool { return InputTextMultilineExt(label, buf, buf_size, .{.x=0,.y=0}, .{}, null, null); } pub inline fn InputTextWithHintExt(label: ?[*:0]const u8, hint: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize, flags: InputTextFlags, callback: InputTextCallback, user_data: ?*c_void) bool { return raw.igInputTextWithHint(label, hint, buf, buf_size, flags.toInt(), callback, user_data); } pub inline fn InputTextWithHint(label: ?[*:0]const u8, hint: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize) bool { return InputTextWithHintExt(label, hint, buf, buf_size, .{}, null, null); } /// InvisibleButton(str_id: ?[*:0]const u8, size: Vec2) bool pub const InvisibleButton = raw.igInvisibleButton; /// IsAnyItemActive() bool pub const IsAnyItemActive = raw.igIsAnyItemActive; /// IsAnyItemFocused() bool pub const IsAnyItemFocused = raw.igIsAnyItemFocused; /// IsAnyItemHovered() bool pub const IsAnyItemHovered = raw.igIsAnyItemHovered; /// IsAnyMouseDown() bool pub const IsAnyMouseDown = raw.igIsAnyMouseDown; /// IsItemActivated() bool pub const IsItemActivated = raw.igIsItemActivated; /// IsItemActive() bool pub const IsItemActive = raw.igIsItemActive; /// IsItemClickedExt(mouse_button: MouseButton) bool pub const IsItemClickedExt = raw.igIsItemClicked; pub inline fn IsItemClicked() bool { return IsItemClickedExt(.Left); } /// IsItemDeactivated() bool pub const IsItemDeactivated = raw.igIsItemDeactivated; /// IsItemDeactivatedAfterEdit() bool pub const IsItemDeactivatedAfterEdit = raw.igIsItemDeactivatedAfterEdit; /// IsItemEdited() bool pub const IsItemEdited = raw.igIsItemEdited; /// IsItemFocused() bool pub const IsItemFocused = raw.igIsItemFocused; pub inline fn IsItemHoveredExt(flags: HoveredFlags) bool { return raw.igIsItemHovered(flags.toInt()); } pub inline fn IsItemHovered() bool { return IsItemHoveredExt(.{}); } /// IsItemToggledOpen() bool pub const IsItemToggledOpen = raw.igIsItemToggledOpen; /// IsItemVisible() bool pub const IsItemVisible = raw.igIsItemVisible; /// IsKeyDown(user_key_index: i32) bool pub const IsKeyDown = raw.igIsKeyDown; /// IsKeyPressedExt(user_key_index: i32, repeat: bool) bool pub const IsKeyPressedExt = raw.igIsKeyPressed; pub inline fn IsKeyPressed(user_key_index: i32) bool { return IsKeyPressedExt(user_key_index, true); } /// IsKeyReleased(user_key_index: i32) bool pub const IsKeyReleased = raw.igIsKeyReleased; /// IsMouseClickedExt(button: MouseButton, repeat: bool) bool pub const IsMouseClickedExt = raw.igIsMouseClicked; pub inline fn IsMouseClicked(button: MouseButton) bool { return IsMouseClickedExt(button, false); } /// IsMouseDoubleClicked(button: MouseButton) bool pub const IsMouseDoubleClicked = raw.igIsMouseDoubleClicked; /// IsMouseDown(button: MouseButton) bool pub const IsMouseDown = raw.igIsMouseDown; /// IsMouseDraggingExt(button: MouseButton, lock_threshold: f32) bool pub const IsMouseDraggingExt = raw.igIsMouseDragging; pub inline fn IsMouseDragging(button: MouseButton) bool { return IsMouseDraggingExt(button, -1.0); } /// IsMouseHoveringRectExt(r_min: Vec2, r_max: Vec2, clip: bool) bool pub const IsMouseHoveringRectExt = raw.igIsMouseHoveringRect; pub inline fn IsMouseHoveringRect(r_min: Vec2, r_max: Vec2) bool { return IsMouseHoveringRectExt(r_min, r_max, true); } /// IsMousePosValidExt(mouse_pos: ?*const Vec2) bool pub const IsMousePosValidExt = raw.igIsMousePosValid; pub inline fn IsMousePosValid() bool { return IsMousePosValidExt(null); } /// IsMouseReleased(button: MouseButton) bool pub const IsMouseReleased = raw.igIsMouseReleased; /// IsPopupOpen(str_id: ?[*:0]const u8) bool pub const IsPopupOpen = raw.igIsPopupOpen; /// IsRectVisible(size: Vec2) bool pub const IsRectVisible = raw.igIsRectVisible; /// IsRectVisibleVec2(rect_min: Vec2, rect_max: Vec2) bool pub const IsRectVisibleVec2 = raw.igIsRectVisibleVec2; /// IsWindowAppearing() bool pub const IsWindowAppearing = raw.igIsWindowAppearing; /// IsWindowCollapsed() bool pub const IsWindowCollapsed = raw.igIsWindowCollapsed; pub inline fn IsWindowFocusedExt(flags: FocusedFlags) bool { return raw.igIsWindowFocused(flags.toInt()); } pub inline fn IsWindowFocused() bool { return IsWindowFocusedExt(.{}); } pub inline fn IsWindowHoveredExt(flags: HoveredFlags) bool { return raw.igIsWindowHovered(flags.toInt()); } pub inline fn IsWindowHovered() bool { return IsWindowHoveredExt(.{}); } /// LabelText(label: ?[*:0]const u8, fmt: ?[*:0]const u8, ...: ...) void pub const LabelText = raw.igLabelText; /// ListBoxStr_arrExt(label: ?[*:0]const u8, current_item: ?*i32, items: [*]const[*:0]const u8, items_count: i32, height_in_items: i32) bool pub const ListBoxStr_arrExt = raw.igListBoxStr_arr; pub inline fn ListBoxStr_arr(label: ?[*:0]const u8, current_item: ?*i32, items: [*]const[*:0]const u8, items_count: i32) bool { return ListBoxStr_arrExt(label, current_item, items, items_count, -1); } /// ListBoxFnPtrExt(label: ?[*:0]const u8, current_item: ?*i32, items_getter: ?fn (data: ?*c_void, idx: i32, out_text: *?[*:0]const u8) callconv(.C) bool, data: ?*c_void, items_count: i32, height_in_items: i32) bool pub const ListBoxFnPtrExt = raw.igListBoxFnPtr; pub inline fn ListBoxFnPtr(label: ?[*:0]const u8, current_item: ?*i32, items_getter: ?fn (data: ?*c_void, idx: i32, out_text: *?[*:0]const u8) callconv(.C) bool, data: ?*c_void, items_count: i32) bool { return ListBoxFnPtrExt(label, current_item, items_getter, data, items_count, -1); } /// ListBoxFooter() void pub const ListBoxFooter = raw.igListBoxFooter; /// ListBoxHeaderVec2Ext(label: ?[*:0]const u8, size: Vec2) bool pub const ListBoxHeaderVec2Ext = raw.igListBoxHeaderVec2; pub inline fn ListBoxHeaderVec2(label: ?[*:0]const u8) bool { return ListBoxHeaderVec2Ext(label, .{.x=0,.y=0}); } /// ListBoxHeaderIntExt(label: ?[*:0]const u8, items_count: i32, height_in_items: i32) bool pub const ListBoxHeaderIntExt = raw.igListBoxHeaderInt; pub inline fn ListBoxHeaderInt(label: ?[*:0]const u8, items_count: i32) bool { return ListBoxHeaderIntExt(label, items_count, -1); } /// LoadIniSettingsFromDisk(ini_filename: ?[*:0]const u8) void pub const LoadIniSettingsFromDisk = raw.igLoadIniSettingsFromDisk; /// LoadIniSettingsFromMemoryExt(ini_data: ?[*]const u8, ini_size: usize) void pub const LoadIniSettingsFromMemoryExt = raw.igLoadIniSettingsFromMemory; pub inline fn LoadIniSettingsFromMemory(ini_data: ?[*]const u8) void { return LoadIniSettingsFromMemoryExt(ini_data, 0); } /// LogButtons() void pub const LogButtons = raw.igLogButtons; /// LogFinish() void pub const LogFinish = raw.igLogFinish; /// LogText(fmt: ?[*:0]const u8, ...: ...) void pub const LogText = raw.igLogText; /// LogToClipboardExt(auto_open_depth: i32) void pub const LogToClipboardExt = raw.igLogToClipboard; pub inline fn LogToClipboard() void { return LogToClipboardExt(-1); } /// LogToFileExt(auto_open_depth: i32, filename: ?[*:0]const u8) void pub const LogToFileExt = raw.igLogToFile; pub inline fn LogToFile() void { return LogToFileExt(-1, null); } /// LogToTTYExt(auto_open_depth: i32) void pub const LogToTTYExt = raw.igLogToTTY; pub inline fn LogToTTY() void { return LogToTTYExt(-1); } /// MemAlloc(size: usize) ?*c_void pub const MemAlloc = raw.igMemAlloc; /// MemFree(ptr: ?*c_void) void pub const MemFree = raw.igMemFree; /// MenuItemBoolExt(label: ?[*:0]const u8, shortcut: ?[*:0]const u8, selected: bool, enabled: bool) bool pub const MenuItemBoolExt = raw.igMenuItemBool; pub inline fn MenuItemBool(label: ?[*:0]const u8) bool { return MenuItemBoolExt(label, null, false, true); } /// MenuItemBoolPtrExt(label: ?[*:0]const u8, shortcut: ?[*:0]const u8, p_selected: ?*bool, enabled: bool) bool pub const MenuItemBoolPtrExt = raw.igMenuItemBoolPtr; pub inline fn MenuItemBoolPtr(label: ?[*:0]const u8, shortcut: ?[*:0]const u8, p_selected: ?*bool) bool { return MenuItemBoolPtrExt(label, shortcut, p_selected, true); } /// NewFrame() void pub const NewFrame = raw.igNewFrame; /// NewLine() void pub const NewLine = raw.igNewLine; /// NextColumn() void pub const NextColumn = raw.igNextColumn; /// OpenPopup(str_id: ?[*:0]const u8) void pub const OpenPopup = raw.igOpenPopup; /// OpenPopupOnItemClickExt(str_id: ?[*:0]const u8, mouse_button: MouseButton) bool pub const OpenPopupOnItemClickExt = raw.igOpenPopupOnItemClick; pub inline fn OpenPopupOnItemClick() bool { return OpenPopupOnItemClickExt(null, .Right); } /// PlotHistogramFloatPtrExt(label: ?[*:0]const u8, values: *const f32, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2, stride: i32) void pub const PlotHistogramFloatPtrExt = raw.igPlotHistogramFloatPtr; pub inline fn PlotHistogramFloatPtr(label: ?[*:0]const u8, values: *const f32, values_count: i32) void { return PlotHistogramFloatPtrExt(label, values, values_count, 0, null, FLT_MAX, FLT_MAX, .{.x=0,.y=0}, @sizeOf(f32)); } /// PlotHistogramFnPtrExt(label: ?[*:0]const u8, values_getter: ?fn (data: ?*c_void, idx: i32) callconv(.C) f32, data: ?*c_void, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2) void pub const PlotHistogramFnPtrExt = raw.igPlotHistogramFnPtr; pub inline fn PlotHistogramFnPtr(label: ?[*:0]const u8, values_getter: ?fn (data: ?*c_void, idx: i32) callconv(.C) f32, data: ?*c_void, values_count: i32) void { return PlotHistogramFnPtrExt(label, values_getter, data, values_count, 0, null, FLT_MAX, FLT_MAX, .{.x=0,.y=0}); } /// PlotLinesExt(label: ?[*:0]const u8, values: *const f32, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2, stride: i32) void pub const PlotLinesExt = raw.igPlotLines; pub inline fn PlotLines(label: ?[*:0]const u8, values: *const f32, values_count: i32) void { return PlotLinesExt(label, values, values_count, 0, null, FLT_MAX, FLT_MAX, .{.x=0,.y=0}, @sizeOf(f32)); } /// PlotLinesFnPtrExt(label: ?[*:0]const u8, values_getter: ?fn (data: ?*c_void, idx: i32) callconv(.C) f32, data: ?*c_void, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2) void pub const PlotLinesFnPtrExt = raw.igPlotLinesFnPtr; pub inline fn PlotLinesFnPtr(label: ?[*:0]const u8, values_getter: ?fn (data: ?*c_void, idx: i32) callconv(.C) f32, data: ?*c_void, values_count: i32) void { return PlotLinesFnPtrExt(label, values_getter, data, values_count, 0, null, FLT_MAX, FLT_MAX, .{.x=0,.y=0}); } /// PopAllowKeyboardFocus() void pub const PopAllowKeyboardFocus = raw.igPopAllowKeyboardFocus; /// PopButtonRepeat() void pub const PopButtonRepeat = raw.igPopButtonRepeat; /// PopClipRect() void pub const PopClipRect = raw.igPopClipRect; /// PopFont() void pub const PopFont = raw.igPopFont; /// PopID() void pub const PopID = raw.igPopID; /// PopItemWidth() void pub const PopItemWidth = raw.igPopItemWidth; /// PopStyleColorExt(count: i32) void pub const PopStyleColorExt = raw.igPopStyleColor; pub inline fn PopStyleColor() void { return PopStyleColorExt(1); } /// PopStyleVarExt(count: i32) void pub const PopStyleVarExt = raw.igPopStyleVar; pub inline fn PopStyleVar() void { return PopStyleVarExt(1); } /// PopTextWrapPos() void pub const PopTextWrapPos = raw.igPopTextWrapPos; /// ProgressBarExt(fraction: f32, size_arg: Vec2, overlay: ?[*:0]const u8) void pub const ProgressBarExt = raw.igProgressBar; pub inline fn ProgressBar(fraction: f32) void { return ProgressBarExt(fraction, .{.x=-1,.y=0}, null); } /// PushAllowKeyboardFocus(allow_keyboard_focus: bool) void pub const PushAllowKeyboardFocus = raw.igPushAllowKeyboardFocus; /// PushButtonRepeat(repeat: bool) void pub const PushButtonRepeat = raw.igPushButtonRepeat; /// PushClipRect(clip_rect_min: Vec2, clip_rect_max: Vec2, intersect_with_current_clip_rect: bool) void pub const PushClipRect = raw.igPushClipRect; /// PushFont(font: ?*Font) void pub const PushFont = raw.igPushFont; /// PushIDStr(str_id: ?[*:0]const u8) void pub const PushIDStr = raw.igPushIDStr; /// PushIDRange(str_id_begin: ?[*]const u8, str_id_end: ?[*]const u8) void pub const PushIDRange = raw.igPushIDRange; /// PushIDPtr(ptr_id: ?*const c_void) void pub const PushIDPtr = raw.igPushIDPtr; /// PushIDInt(int_id: i32) void pub const PushIDInt = raw.igPushIDInt; /// PushItemWidth(item_width: f32) void pub const PushItemWidth = raw.igPushItemWidth; /// PushStyleColorU32(idx: Col, col: u32) void pub const PushStyleColorU32 = raw.igPushStyleColorU32; /// PushStyleColorVec4(idx: Col, col: Vec4) void pub const PushStyleColorVec4 = raw.igPushStyleColorVec4; /// PushStyleVarFloat(idx: StyleVar, val: f32) void pub const PushStyleVarFloat = raw.igPushStyleVarFloat; /// PushStyleVarVec2(idx: StyleVar, val: Vec2) void pub const PushStyleVarVec2 = raw.igPushStyleVarVec2; /// PushTextWrapPosExt(wrap_local_pos_x: f32) void pub const PushTextWrapPosExt = raw.igPushTextWrapPos; pub inline fn PushTextWrapPos() void { return PushTextWrapPosExt(0.0); } /// RadioButtonBool(label: ?[*:0]const u8, active: bool) bool pub const RadioButtonBool = raw.igRadioButtonBool; /// RadioButtonIntPtr(label: ?[*:0]const u8, v: *i32, v_button: i32) bool pub const RadioButtonIntPtr = raw.igRadioButtonIntPtr; /// Render() void pub const Render = raw.igRender; /// ResetMouseDragDeltaExt(button: MouseButton) void pub const ResetMouseDragDeltaExt = raw.igResetMouseDragDelta; pub inline fn ResetMouseDragDelta() void { return ResetMouseDragDeltaExt(.Left); } /// SameLineExt(offset_from_start_x: f32, spacing: f32) void pub const SameLineExt = raw.igSameLine; pub inline fn SameLine() void { return SameLineExt(0.0, -1.0); } /// SaveIniSettingsToDisk(ini_filename: ?[*:0]const u8) void pub const SaveIniSettingsToDisk = raw.igSaveIniSettingsToDisk; /// SaveIniSettingsToMemoryExt(out_ini_size: ?*usize) ?[*:0]const u8 pub const SaveIniSettingsToMemoryExt = raw.igSaveIniSettingsToMemory; pub inline fn SaveIniSettingsToMemory() ?[*:0]const u8 { return SaveIniSettingsToMemoryExt(null); } pub inline fn SelectableBoolExt(label: ?[*:0]const u8, selected: bool, flags: SelectableFlags, size: Vec2) bool { return raw.igSelectableBool(label, selected, flags.toInt(), size); } pub inline fn SelectableBool(label: ?[*:0]const u8) bool { return SelectableBoolExt(label, false, .{}, .{.x=0,.y=0}); } pub inline fn SelectableBoolPtrExt(label: ?[*:0]const u8, p_selected: ?*bool, flags: SelectableFlags, size: Vec2) bool { return raw.igSelectableBoolPtr(label, p_selected, flags.toInt(), size); } pub inline fn SelectableBoolPtr(label: ?[*:0]const u8, p_selected: ?*bool) bool { return SelectableBoolPtrExt(label, p_selected, .{}, .{.x=0,.y=0}); } /// Separator() void pub const Separator = raw.igSeparator; /// SetAllocatorFunctionsExt(alloc_func: ?fn (sz: usize, user_data: ?*c_void) callconv(.C) ?*c_void, free_func: ?fn (ptr: ?*c_void, user_data: ?*c_void) callconv(.C) void, user_data: ?*c_void) void pub const SetAllocatorFunctionsExt = raw.igSetAllocatorFunctions; pub inline fn SetAllocatorFunctions(alloc_func: ?fn (sz: usize, user_data: ?*c_void) callconv(.C) ?*c_void, free_func: ?fn (ptr: ?*c_void, user_data: ?*c_void) callconv(.C) void) void { return SetAllocatorFunctionsExt(alloc_func, free_func, null); } /// SetClipboardText(text: ?[*:0]const u8) void pub const SetClipboardText = raw.igSetClipboardText; pub inline fn SetColorEditOptions(flags: ColorEditFlags) void { return raw.igSetColorEditOptions(flags.toInt()); } /// SetColumnOffset(column_index: i32, offset_x: f32) void pub const SetColumnOffset = raw.igSetColumnOffset; /// SetColumnWidth(column_index: i32, width: f32) void pub const SetColumnWidth = raw.igSetColumnWidth; /// SetCurrentContext(ctx: ?*Context) void pub const SetCurrentContext = raw.igSetCurrentContext; /// SetCursorPos(local_pos: Vec2) void pub const SetCursorPos = raw.igSetCursorPos; /// SetCursorPosX(local_x: f32) void pub const SetCursorPosX = raw.igSetCursorPosX; /// SetCursorPosY(local_y: f32) void pub const SetCursorPosY = raw.igSetCursorPosY; /// SetCursorScreenPos(pos: Vec2) void pub const SetCursorScreenPos = raw.igSetCursorScreenPos; pub inline fn SetDragDropPayloadExt(kind: ?[*:0]const u8, data: ?*const c_void, sz: usize, cond: CondFlags) bool { return raw.igSetDragDropPayload(kind, data, sz, cond.toInt()); } pub inline fn SetDragDropPayload(kind: ?[*:0]const u8, data: ?*const c_void, sz: usize) bool { return SetDragDropPayloadExt(kind, data, sz, .{}); } /// SetItemAllowOverlap() void pub const SetItemAllowOverlap = raw.igSetItemAllowOverlap; /// SetItemDefaultFocus() void pub const SetItemDefaultFocus = raw.igSetItemDefaultFocus; /// SetKeyboardFocusHereExt(offset: i32) void pub const SetKeyboardFocusHereExt = raw.igSetKeyboardFocusHere; pub inline fn SetKeyboardFocusHere() void { return SetKeyboardFocusHereExt(0); } /// SetMouseCursor(cursor_type: MouseCursor) void pub const SetMouseCursor = raw.igSetMouseCursor; pub inline fn SetNextItemOpenExt(is_open: bool, cond: CondFlags) void { return raw.igSetNextItemOpen(is_open, cond.toInt()); } pub inline fn SetNextItemOpen(is_open: bool) void { return SetNextItemOpenExt(is_open, .{}); } /// SetNextItemWidth(item_width: f32) void pub const SetNextItemWidth = raw.igSetNextItemWidth; /// SetNextWindowBgAlpha(alpha: f32) void pub const SetNextWindowBgAlpha = raw.igSetNextWindowBgAlpha; pub inline fn SetNextWindowCollapsedExt(collapsed: bool, cond: CondFlags) void { return raw.igSetNextWindowCollapsed(collapsed, cond.toInt()); } pub inline fn SetNextWindowCollapsed(collapsed: bool) void { return SetNextWindowCollapsedExt(collapsed, .{}); } /// SetNextWindowContentSize(size: Vec2) void pub const SetNextWindowContentSize = raw.igSetNextWindowContentSize; /// SetNextWindowFocus() void pub const SetNextWindowFocus = raw.igSetNextWindowFocus; pub inline fn SetNextWindowPosExt(pos: Vec2, cond: CondFlags, pivot: Vec2) void { return raw.igSetNextWindowPos(pos, cond.toInt(), pivot); } pub inline fn SetNextWindowPos(pos: Vec2) void { return SetNextWindowPosExt(pos, .{}, .{.x=0,.y=0}); } pub inline fn SetNextWindowSizeExt(size: Vec2, cond: CondFlags) void { return raw.igSetNextWindowSize(size, cond.toInt()); } pub inline fn SetNextWindowSize(size: Vec2) void { return SetNextWindowSizeExt(size, .{}); } /// SetNextWindowSizeConstraintsExt(size_min: Vec2, size_max: Vec2, custom_callback: SizeCallback, custom_callback_data: ?*c_void) void pub const SetNextWindowSizeConstraintsExt = raw.igSetNextWindowSizeConstraints; pub inline fn SetNextWindowSizeConstraints(size_min: Vec2, size_max: Vec2) void { return SetNextWindowSizeConstraintsExt(size_min, size_max, null, null); } /// SetScrollFromPosXExt(local_x: f32, center_x_ratio: f32) void pub const SetScrollFromPosXExt = raw.igSetScrollFromPosX; pub inline fn SetScrollFromPosX(local_x: f32) void { return SetScrollFromPosXExt(local_x, 0.5); } /// SetScrollFromPosYExt(local_y: f32, center_y_ratio: f32) void pub const SetScrollFromPosYExt = raw.igSetScrollFromPosY; pub inline fn SetScrollFromPosY(local_y: f32) void { return SetScrollFromPosYExt(local_y, 0.5); } /// SetScrollHereXExt(center_x_ratio: f32) void pub const SetScrollHereXExt = raw.igSetScrollHereX; pub inline fn SetScrollHereX() void { return SetScrollHereXExt(0.5); } /// SetScrollHereYExt(center_y_ratio: f32) void pub const SetScrollHereYExt = raw.igSetScrollHereY; pub inline fn SetScrollHereY() void { return SetScrollHereYExt(0.5); } /// SetScrollX(scroll_x: f32) void pub const SetScrollX = raw.igSetScrollX; /// SetScrollY(scroll_y: f32) void pub const SetScrollY = raw.igSetScrollY; /// SetStateStorage(storage: ?*Storage) void pub const SetStateStorage = raw.igSetStateStorage; /// SetTabItemClosed(tab_or_docked_window_label: ?[*:0]const u8) void pub const SetTabItemClosed = raw.igSetTabItemClosed; /// SetTooltip(fmt: ?[*:0]const u8, ...: ...) void pub const SetTooltip = raw.igSetTooltip; pub inline fn SetWindowCollapsedBoolExt(collapsed: bool, cond: CondFlags) void { return raw.igSetWindowCollapsedBool(collapsed, cond.toInt()); } pub inline fn SetWindowCollapsedBool(collapsed: bool) void { return SetWindowCollapsedBoolExt(collapsed, .{}); } pub inline fn SetWindowCollapsedStrExt(name: ?[*:0]const u8, collapsed: bool, cond: CondFlags) void { return raw.igSetWindowCollapsedStr(name, collapsed, cond.toInt()); } pub inline fn SetWindowCollapsedStr(name: ?[*:0]const u8, collapsed: bool) void { return SetWindowCollapsedStrExt(name, collapsed, .{}); } /// SetWindowFocus() void pub const SetWindowFocus = raw.igSetWindowFocus; /// SetWindowFocusStr(name: ?[*:0]const u8) void pub const SetWindowFocusStr = raw.igSetWindowFocusStr; /// SetWindowFontScale(scale: f32) void pub const SetWindowFontScale = raw.igSetWindowFontScale; pub inline fn SetWindowPosVec2Ext(pos: Vec2, cond: CondFlags) void { return raw.igSetWindowPosVec2(pos, cond.toInt()); } pub inline fn SetWindowPosVec2(pos: Vec2) void { return SetWindowPosVec2Ext(pos, .{}); } pub inline fn SetWindowPosStrExt(name: ?[*:0]const u8, pos: Vec2, cond: CondFlags) void { return raw.igSetWindowPosStr(name, pos, cond.toInt()); } pub inline fn SetWindowPosStr(name: ?[*:0]const u8, pos: Vec2) void { return SetWindowPosStrExt(name, pos, .{}); } pub inline fn SetWindowSizeVec2Ext(size: Vec2, cond: CondFlags) void { return raw.igSetWindowSizeVec2(size, cond.toInt()); } pub inline fn SetWindowSizeVec2(size: Vec2) void { return SetWindowSizeVec2Ext(size, .{}); } pub inline fn SetWindowSizeStrExt(name: ?[*:0]const u8, size: Vec2, cond: CondFlags) void { return raw.igSetWindowSizeStr(name, size, cond.toInt()); } pub inline fn SetWindowSizeStr(name: ?[*:0]const u8, size: Vec2) void { return SetWindowSizeStrExt(name, size, .{}); } /// ShowAboutWindowExt(p_open: ?*bool) void pub const ShowAboutWindowExt = raw.igShowAboutWindow; pub inline fn ShowAboutWindow() void { return ShowAboutWindowExt(null); } /// ShowDemoWindowExt(p_open: ?*bool) void pub const ShowDemoWindowExt = raw.igShowDemoWindow; pub inline fn ShowDemoWindow() void { return ShowDemoWindowExt(null); } /// ShowFontSelector(label: ?[*:0]const u8) void pub const ShowFontSelector = raw.igShowFontSelector; /// ShowMetricsWindowExt(p_open: ?*bool) void pub const ShowMetricsWindowExt = raw.igShowMetricsWindow; pub inline fn ShowMetricsWindow() void { return ShowMetricsWindowExt(null); } /// ShowStyleEditorExt(ref: ?*Style) void pub const ShowStyleEditorExt = raw.igShowStyleEditor; pub inline fn ShowStyleEditor() void { return ShowStyleEditorExt(null); } /// ShowStyleSelector(label: ?[*:0]const u8) bool pub const ShowStyleSelector = raw.igShowStyleSelector; /// ShowUserGuide() void pub const ShowUserGuide = raw.igShowUserGuide; /// SliderAngleExt(label: ?[*:0]const u8, v_rad: *f32, v_degrees_min: f32, v_degrees_max: f32, format: ?[*:0]const u8) bool pub const SliderAngleExt = raw.igSliderAngle; pub inline fn SliderAngle(label: ?[*:0]const u8, v_rad: *f32) bool { return SliderAngleExt(label, v_rad, -360.0, 360.0, "%.0f deg"); } /// SliderFloatExt(label: ?[*:0]const u8, v: *f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const SliderFloatExt = raw.igSliderFloat; pub inline fn SliderFloat(label: ?[*:0]const u8, v: *f32, v_min: f32, v_max: f32) bool { return SliderFloatExt(label, v, v_min, v_max, "%.3f", 1.0); } /// SliderFloat2Ext(label: ?[*:0]const u8, v: *[2]f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const SliderFloat2Ext = raw.igSliderFloat2; pub inline fn SliderFloat2(label: ?[*:0]const u8, v: *[2]f32, v_min: f32, v_max: f32) bool { return SliderFloat2Ext(label, v, v_min, v_max, "%.3f", 1.0); } /// SliderFloat3Ext(label: ?[*:0]const u8, v: *[3]f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const SliderFloat3Ext = raw.igSliderFloat3; pub inline fn SliderFloat3(label: ?[*:0]const u8, v: *[3]f32, v_min: f32, v_max: f32) bool { return SliderFloat3Ext(label, v, v_min, v_max, "%.3f", 1.0); } /// SliderFloat4Ext(label: ?[*:0]const u8, v: *[4]f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const SliderFloat4Ext = raw.igSliderFloat4; pub inline fn SliderFloat4(label: ?[*:0]const u8, v: *[4]f32, v_min: f32, v_max: f32) bool { return SliderFloat4Ext(label, v, v_min, v_max, "%.3f", 1.0); } /// SliderIntExt(label: ?[*:0]const u8, v: *i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const SliderIntExt = raw.igSliderInt; pub inline fn SliderInt(label: ?[*:0]const u8, v: *i32, v_min: i32, v_max: i32) bool { return SliderIntExt(label, v, v_min, v_max, "%d"); } /// SliderInt2Ext(label: ?[*:0]const u8, v: *[2]i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const SliderInt2Ext = raw.igSliderInt2; pub inline fn SliderInt2(label: ?[*:0]const u8, v: *[2]i32, v_min: i32, v_max: i32) bool { return SliderInt2Ext(label, v, v_min, v_max, "%d"); } /// SliderInt3Ext(label: ?[*:0]const u8, v: *[3]i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const SliderInt3Ext = raw.igSliderInt3; pub inline fn SliderInt3(label: ?[*:0]const u8, v: *[3]i32, v_min: i32, v_max: i32) bool { return SliderInt3Ext(label, v, v_min, v_max, "%d"); } /// SliderInt4Ext(label: ?[*:0]const u8, v: *[4]i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const SliderInt4Ext = raw.igSliderInt4; pub inline fn SliderInt4(label: ?[*:0]const u8, v: *[4]i32, v_min: i32, v_max: i32) bool { return SliderInt4Ext(label, v, v_min, v_max, "%d"); } /// SliderScalarExt(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) bool pub const SliderScalarExt = raw.igSliderScalar; pub inline fn SliderScalar(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void) bool { return SliderScalarExt(label, data_type, p_data, p_min, p_max, null, 1.0); } /// SliderScalarNExt(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) bool pub const SliderScalarNExt = raw.igSliderScalarN; pub inline fn SliderScalarN(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, p_min: ?*const c_void, p_max: ?*const c_void) bool { return SliderScalarNExt(label, data_type, p_data, components, p_min, p_max, null, 1.0); } /// SmallButton(label: ?[*:0]const u8) bool pub const SmallButton = raw.igSmallButton; /// Spacing() void pub const Spacing = raw.igSpacing; /// StyleColorsClassicExt(dst: ?*Style) void pub const StyleColorsClassicExt = raw.igStyleColorsClassic; pub inline fn StyleColorsClassic() void { return StyleColorsClassicExt(null); } /// StyleColorsDarkExt(dst: ?*Style) void pub const StyleColorsDarkExt = raw.igStyleColorsDark; pub inline fn StyleColorsDark() void { return StyleColorsDarkExt(null); } /// StyleColorsLightExt(dst: ?*Style) void pub const StyleColorsLightExt = raw.igStyleColorsLight; pub inline fn StyleColorsLight() void { return StyleColorsLightExt(null); } /// Text(fmt: ?[*:0]const u8, ...: ...) void pub const Text = raw.igText; /// TextColored(col: Vec4, fmt: ?[*:0]const u8, ...: ...) void pub const TextColored = raw.igTextColored; /// TextDisabled(fmt: ?[*:0]const u8, ...: ...) void pub const TextDisabled = raw.igTextDisabled; /// TextUnformattedExt(text: ?[*]const u8, text_end: ?[*]const u8) void pub const TextUnformattedExt = raw.igTextUnformatted; pub inline fn TextUnformatted(text: ?[*]const u8) void { return TextUnformattedExt(text, null); } /// TextWrapped(fmt: ?[*:0]const u8, ...: ...) void pub const TextWrapped = raw.igTextWrapped; /// TreeNodeStr(label: ?[*:0]const u8) bool pub const TreeNodeStr = raw.igTreeNodeStr; /// TreeNodeStrStr(str_id: ?[*:0]const u8, fmt: ?[*:0]const u8, ...: ...) bool pub const TreeNodeStrStr = raw.igTreeNodeStrStr; /// TreeNodePtr(ptr_id: ?*const c_void, fmt: ?[*:0]const u8, ...: ...) bool pub const TreeNodePtr = raw.igTreeNodePtr; pub inline fn TreeNodeExStrExt(label: ?[*:0]const u8, flags: TreeNodeFlags) bool { return raw.igTreeNodeExStr(label, flags.toInt()); } pub inline fn TreeNodeExStr(label: ?[*:0]const u8) bool { return TreeNodeExStrExt(label, .{}); } /// TreeNodeExStrStr(str_id: ?[*:0]const u8, flags: TreeNodeFlags, fmt: ?[*:0]const u8, ...: ...) bool pub const TreeNodeExStrStr = raw.igTreeNodeExStrStr; /// TreeNodeExPtr(ptr_id: ?*const c_void, flags: TreeNodeFlags, fmt: ?[*:0]const u8, ...: ...) bool pub const TreeNodeExPtr = raw.igTreeNodeExPtr; /// TreePop() void pub const TreePop = raw.igTreePop; /// TreePushStr(str_id: ?[*:0]const u8) void pub const TreePushStr = raw.igTreePushStr; /// TreePushPtrExt(ptr_id: ?*const c_void) void pub const TreePushPtrExt = raw.igTreePushPtr; pub inline fn TreePushPtr() void { return TreePushPtrExt(null); } /// UnindentExt(indent_w: f32) void pub const UnindentExt = raw.igUnindent; pub inline fn Unindent() void { return UnindentExt(0.0); } /// VSliderFloatExt(label: ?[*:0]const u8, size: Vec2, v: *f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) bool pub const VSliderFloatExt = raw.igVSliderFloat; pub inline fn VSliderFloat(label: ?[*:0]const u8, size: Vec2, v: *f32, v_min: f32, v_max: f32) bool { return VSliderFloatExt(label, size, v, v_min, v_max, "%.3f", 1.0); } /// VSliderIntExt(label: ?[*:0]const u8, size: Vec2, v: *i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) bool pub const VSliderIntExt = raw.igVSliderInt; pub inline fn VSliderInt(label: ?[*:0]const u8, size: Vec2, v: *i32, v_min: i32, v_max: i32) bool { return VSliderIntExt(label, size, v, v_min, v_max, "%d"); } /// VSliderScalarExt(label: ?[*:0]const u8, size: Vec2, data_type: DataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) bool pub const VSliderScalarExt = raw.igVSliderScalar; pub inline fn VSliderScalar(label: ?[*:0]const u8, size: Vec2, data_type: DataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void) bool { return VSliderScalarExt(label, size, data_type, p_data, p_min, p_max, null, 1.0); } /// ValueBool(prefix: ?[*:0]const u8, b: bool) void pub const ValueBool = raw.igValueBool; /// ValueInt(prefix: ?[*:0]const u8, v: i32) void pub const ValueInt = raw.igValueInt; /// ValueUint(prefix: ?[*:0]const u8, v: u32) void pub const ValueUint = raw.igValueUint; /// ValueFloatExt(prefix: ?[*:0]const u8, v: f32, float_format: ?[*:0]const u8) void pub const ValueFloatExt = raw.igValueFloat; pub inline fn ValueFloat(prefix: ?[*:0]const u8, v: f32) void { return ValueFloatExt(prefix, v, null); } pub const raw = struct { pub extern fn ImColor_HSV_nonUDT(pOut: *Color, self: *Color, h: f32, s: f32, v: f32, a: f32) callconv(.C) void; pub extern fn ImColor_ImColor(self: *Color) callconv(.C) void; pub extern fn ImColor_ImColorInt(self: *Color, r: i32, g: i32, b: i32, a: i32) callconv(.C) void; pub extern fn ImColor_ImColorU32(self: *Color, rgba: u32) callconv(.C) void; pub extern fn ImColor_ImColorFloat(self: *Color, r: f32, g: f32, b: f32, a: f32) callconv(.C) void; pub extern fn ImColor_ImColorVec4(self: *Color, col: Vec4) callconv(.C) void; pub extern fn ImColor_SetHSV(self: *Color, h: f32, s: f32, v: f32, a: f32) callconv(.C) void; pub extern fn ImColor_destroy(self: *Color) callconv(.C) void; pub extern fn ImDrawCmd_ImDrawCmd(self: *DrawCmd) callconv(.C) void; pub extern fn ImDrawCmd_destroy(self: *DrawCmd) callconv(.C) void; pub extern fn ImDrawData_Clear(self: *DrawData) callconv(.C) void; pub extern fn ImDrawData_DeIndexAllBuffers(self: *DrawData) callconv(.C) void; pub extern fn ImDrawData_ImDrawData(self: *DrawData) callconv(.C) void; pub extern fn ImDrawData_ScaleClipRects(self: *DrawData, fb_scale: Vec2) callconv(.C) void; pub extern fn ImDrawData_destroy(self: *DrawData) callconv(.C) void; pub extern fn ImDrawListSplitter_Clear(self: *DrawListSplitter) callconv(.C) void; pub extern fn ImDrawListSplitter_ClearFreeMemory(self: *DrawListSplitter) callconv(.C) void; pub extern fn ImDrawListSplitter_ImDrawListSplitter(self: *DrawListSplitter) callconv(.C) void; pub extern fn ImDrawListSplitter_Merge(self: *DrawListSplitter, draw_list: ?*DrawList) callconv(.C) void; pub extern fn ImDrawListSplitter_SetCurrentChannel(self: *DrawListSplitter, draw_list: ?*DrawList, channel_idx: i32) callconv(.C) void; pub extern fn ImDrawListSplitter_Split(self: *DrawListSplitter, draw_list: ?*DrawList, count: i32) callconv(.C) void; pub extern fn ImDrawListSplitter_destroy(self: *DrawListSplitter) callconv(.C) void; pub extern fn ImDrawList_AddBezierCurve(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32, thickness: f32, num_segments: i32) callconv(.C) void; pub extern fn ImDrawList_AddCallback(self: *DrawList, callback: DrawCallback, callback_data: ?*c_void) callconv(.C) void; pub extern fn ImDrawList_AddCircle(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddCircleFilled(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32) callconv(.C) void; pub extern fn ImDrawList_AddConvexPolyFilled(self: *DrawList, points: ?[*]const Vec2, num_points: i32, col: u32) callconv(.C) void; pub extern fn ImDrawList_AddDrawCmd(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_AddImage(self: *DrawList, user_texture_id: TextureID, p_min: Vec2, p_max: Vec2, uv_min: Vec2, uv_max: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_AddImageQuad(self: *DrawList, user_texture_id: TextureID, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, uv1: Vec2, uv2: Vec2, uv3: Vec2, uv4: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_AddImageRounded(self: *DrawList, user_texture_id: TextureID, p_min: Vec2, p_max: Vec2, uv_min: Vec2, uv_max: Vec2, col: u32, rounding: f32, rounding_corners: DrawCornerFlagsInt) callconv(.C) void; pub extern fn ImDrawList_AddLine(self: *DrawList, p1: Vec2, p2: Vec2, col: u32, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddNgon(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddNgonFilled(self: *DrawList, center: Vec2, radius: f32, col: u32, num_segments: i32) callconv(.C) void; pub extern fn ImDrawList_AddPolyline(self: *DrawList, points: ?[*]const Vec2, num_points: i32, col: u32, closed: bool, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddQuad(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddQuadFilled(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, p4: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_AddRect(self: *DrawList, p_min: Vec2, p_max: Vec2, col: u32, rounding: f32, rounding_corners: DrawCornerFlagsInt, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddRectFilled(self: *DrawList, p_min: Vec2, p_max: Vec2, col: u32, rounding: f32, rounding_corners: DrawCornerFlagsInt) callconv(.C) void; pub extern fn ImDrawList_AddRectFilledMultiColor(self: *DrawList, p_min: Vec2, p_max: Vec2, col_upr_left: u32, col_upr_right: u32, col_bot_right: u32, col_bot_left: u32) callconv(.C) void; pub extern fn ImDrawList_AddTextVec2(self: *DrawList, pos: Vec2, col: u32, text_begin: ?[*]const u8, text_end: ?[*]const u8) callconv(.C) void; pub extern fn ImDrawList_AddTextFontPtr(self: *DrawList, font: ?*const Font, font_size: f32, pos: Vec2, col: u32, text_begin: ?[*]const u8, text_end: ?[*]const u8, wrap_width: f32, cpu_fine_clip_rect: ?*const Vec4) callconv(.C) void; pub extern fn ImDrawList_AddTriangle(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, col: u32, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_AddTriangleFilled(self: *DrawList, p1: Vec2, p2: Vec2, p3: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_ChannelsMerge(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_ChannelsSetCurrent(self: *DrawList, n: i32) callconv(.C) void; pub extern fn ImDrawList_ChannelsSplit(self: *DrawList, count: i32) callconv(.C) void; pub extern fn ImDrawList_Clear(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_ClearFreeMemory(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_CloneOutput(self: *const DrawList) callconv(.C) ?*DrawList; pub extern fn ImDrawList_GetClipRectMax_nonUDT(pOut: *Vec2, self: *const DrawList) callconv(.C) void; pub extern fn ImDrawList_GetClipRectMin_nonUDT(pOut: *Vec2, self: *const DrawList) callconv(.C) void; pub extern fn ImDrawList_ImDrawList(self: *DrawList, shared_data: ?*const DrawListSharedData) callconv(.C) void; pub extern fn ImDrawList_PathArcTo(self: *DrawList, center: Vec2, radius: f32, a_min: f32, a_max: f32, num_segments: i32) callconv(.C) void; pub extern fn ImDrawList_PathArcToFast(self: *DrawList, center: Vec2, radius: f32, a_min_of_12: i32, a_max_of_12: i32) callconv(.C) void; pub extern fn ImDrawList_PathBezierCurveTo(self: *DrawList, p2: Vec2, p3: Vec2, p4: Vec2, num_segments: i32) callconv(.C) void; pub extern fn ImDrawList_PathClear(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_PathFillConvex(self: *DrawList, col: u32) callconv(.C) void; pub extern fn ImDrawList_PathLineTo(self: *DrawList, pos: Vec2) callconv(.C) void; pub extern fn ImDrawList_PathLineToMergeDuplicate(self: *DrawList, pos: Vec2) callconv(.C) void; pub extern fn ImDrawList_PathRect(self: *DrawList, rect_min: Vec2, rect_max: Vec2, rounding: f32, rounding_corners: DrawCornerFlagsInt) callconv(.C) void; pub extern fn ImDrawList_PathStroke(self: *DrawList, col: u32, closed: bool, thickness: f32) callconv(.C) void; pub extern fn ImDrawList_PopClipRect(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_PopTextureID(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_PrimQuadUV(self: *DrawList, a: Vec2, b: Vec2, c: Vec2, d: Vec2, uv_a: Vec2, uv_b: Vec2, uv_c: Vec2, uv_d: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_PrimRect(self: *DrawList, a: Vec2, b: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_PrimRectUV(self: *DrawList, a: Vec2, b: Vec2, uv_a: Vec2, uv_b: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_PrimReserve(self: *DrawList, idx_count: i32, vtx_count: i32) callconv(.C) void; pub extern fn ImDrawList_PrimUnreserve(self: *DrawList, idx_count: i32, vtx_count: i32) callconv(.C) void; pub extern fn ImDrawList_PrimVtx(self: *DrawList, pos: Vec2, uv: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_PrimWriteIdx(self: *DrawList, idx: DrawIdx) callconv(.C) void; pub extern fn ImDrawList_PrimWriteVtx(self: *DrawList, pos: Vec2, uv: Vec2, col: u32) callconv(.C) void; pub extern fn ImDrawList_PushClipRect(self: *DrawList, clip_rect_min: Vec2, clip_rect_max: Vec2, intersect_with_current_clip_rect: bool) callconv(.C) void; pub extern fn ImDrawList_PushClipRectFullScreen(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_PushTextureID(self: *DrawList, texture_id: TextureID) callconv(.C) void; pub extern fn ImDrawList_UpdateClipRect(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_UpdateTextureID(self: *DrawList) callconv(.C) void; pub extern fn ImDrawList_destroy(self: *DrawList) callconv(.C) void; pub extern fn ImFontAtlasCustomRect_ImFontAtlasCustomRect(self: *FontAtlasCustomRect) callconv(.C) void; pub extern fn ImFontAtlasCustomRect_IsPacked(self: *const FontAtlasCustomRect) callconv(.C) bool; pub extern fn ImFontAtlasCustomRect_destroy(self: *FontAtlasCustomRect) callconv(.C) void; pub extern fn ImFontAtlas_AddCustomRectFontGlyph(self: *FontAtlas, font: ?*Font, id: Wchar, width: i32, height: i32, advance_x: f32, offset: Vec2) callconv(.C) i32; pub extern fn ImFontAtlas_AddCustomRectRegular(self: *FontAtlas, id: u32, width: i32, height: i32) callconv(.C) i32; pub extern fn ImFontAtlas_AddFont(self: *FontAtlas, font_cfg: ?*const FontConfig) callconv(.C) ?*Font; pub extern fn ImFontAtlas_AddFontDefault(self: *FontAtlas, font_cfg: ?*const FontConfig) callconv(.C) ?*Font; pub extern fn ImFontAtlas_AddFontFromFileTTF(self: *FontAtlas, filename: ?[*:0]const u8, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) callconv(.C) ?*Font; pub extern fn ImFontAtlas_AddFontFromMemoryCompressedBase85TTF(self: *FontAtlas, compressed_font_data_base85: ?[*]const u8, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) callconv(.C) ?*Font; pub extern fn ImFontAtlas_AddFontFromMemoryCompressedTTF(self: *FontAtlas, compressed_font_data: ?*const c_void, compressed_font_size: i32, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) callconv(.C) ?*Font; pub extern fn ImFontAtlas_AddFontFromMemoryTTF(self: *FontAtlas, font_data: ?*c_void, font_size: i32, size_pixels: f32, font_cfg: ?*const FontConfig, glyph_ranges: ?[*:0]const Wchar) callconv(.C) ?*Font; pub extern fn ImFontAtlas_Build(self: *FontAtlas) callconv(.C) bool; pub extern fn ImFontAtlas_CalcCustomRectUV(self: *const FontAtlas, rect: ?*const FontAtlasCustomRect, out_uv_min: ?*Vec2, out_uv_max: ?*Vec2) callconv(.C) void; pub extern fn ImFontAtlas_Clear(self: *FontAtlas) callconv(.C) void; pub extern fn ImFontAtlas_ClearFonts(self: *FontAtlas) callconv(.C) void; pub extern fn ImFontAtlas_ClearInputData(self: *FontAtlas) callconv(.C) void; pub extern fn ImFontAtlas_ClearTexData(self: *FontAtlas) callconv(.C) void; pub extern fn ImFontAtlas_GetCustomRectByIndex(self: *const FontAtlas, index: i32) callconv(.C) ?*const FontAtlasCustomRect; pub extern fn ImFontAtlas_GetGlyphRangesChineseFull(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesChineseSimplifiedCommon(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesCyrillic(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesDefault(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesJapanese(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesKorean(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesThai(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetGlyphRangesVietnamese(self: *FontAtlas) callconv(.C) ?*const Wchar; pub extern fn ImFontAtlas_GetMouseCursorTexData(self: *FontAtlas, cursor: MouseCursor, out_offset: ?*Vec2, out_size: ?*Vec2, out_uv_border: *[2]Vec2, out_uv_fill: *[2]Vec2) callconv(.C) bool; pub extern fn ImFontAtlas_GetTexDataAsAlpha8(self: *FontAtlas, out_pixels: *?[*]u8, out_width: *i32, out_height: *i32, out_bytes_per_pixel: ?*i32) callconv(.C) void; pub extern fn ImFontAtlas_GetTexDataAsRGBA32(self: *FontAtlas, out_pixels: *?[*]u8, out_width: *i32, out_height: *i32, out_bytes_per_pixel: ?*i32) callconv(.C) void; pub extern fn ImFontAtlas_ImFontAtlas(self: *FontAtlas) callconv(.C) void; pub extern fn ImFontAtlas_IsBuilt(self: *const FontAtlas) callconv(.C) bool; pub extern fn ImFontAtlas_SetTexID(self: *FontAtlas, id: TextureID) callconv(.C) void; pub extern fn ImFontAtlas_destroy(self: *FontAtlas) callconv(.C) void; pub extern fn ImFontConfig_ImFontConfig(self: *FontConfig) callconv(.C) void; pub extern fn ImFontConfig_destroy(self: *FontConfig) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_AddChar(self: *FontGlyphRangesBuilder, c: Wchar) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_AddRanges(self: *FontGlyphRangesBuilder, ranges: ?[*:0]const Wchar) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_AddText(self: *FontGlyphRangesBuilder, text: ?[*]const u8, text_end: ?[*]const u8) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_BuildRanges(self: *FontGlyphRangesBuilder, out_ranges: *Vector(Wchar)) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_Clear(self: *FontGlyphRangesBuilder) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_GetBit(self: *const FontGlyphRangesBuilder, n: i32) callconv(.C) bool; pub extern fn ImFontGlyphRangesBuilder_ImFontGlyphRangesBuilder(self: *FontGlyphRangesBuilder) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_SetBit(self: *FontGlyphRangesBuilder, n: i32) callconv(.C) void; pub extern fn ImFontGlyphRangesBuilder_destroy(self: *FontGlyphRangesBuilder) callconv(.C) void; pub extern fn ImFont_AddGlyph(self: *Font, c: Wchar, x0: f32, y0: f32, x1: f32, y1: f32, u0: f32, v0: f32, u1: f32, v1: f32, advance_x: f32) callconv(.C) void; pub extern fn ImFont_AddRemapChar(self: *Font, dst: Wchar, src: Wchar, overwrite_dst: bool) callconv(.C) void; pub extern fn ImFont_BuildLookupTable(self: *Font) callconv(.C) void; pub extern fn ImFont_CalcTextSizeA_nonUDT(pOut: *Vec2, self: *const Font, size: f32, max_width: f32, wrap_width: f32, text_begin: ?[*]const u8, text_end: ?[*]const u8, remaining: ?*?[*:0]const u8) callconv(.C) void; pub extern fn ImFont_CalcWordWrapPositionA(self: *const Font, scale: f32, text: ?[*]const u8, text_end: ?[*]const u8, wrap_width: f32) callconv(.C) ?[*]const u8; pub extern fn ImFont_ClearOutputData(self: *Font) callconv(.C) void; pub extern fn ImFont_FindGlyph(self: *const Font, c: Wchar) callconv(.C) ?*const FontGlyph; pub extern fn ImFont_FindGlyphNoFallback(self: *const Font, c: Wchar) callconv(.C) ?*const FontGlyph; pub extern fn ImFont_GetCharAdvance(self: *const Font, c: Wchar) callconv(.C) f32; pub extern fn ImFont_GetDebugName(self: *const Font) callconv(.C) ?[*:0]const u8; pub extern fn ImFont_GrowIndex(self: *Font, new_size: i32) callconv(.C) void; pub extern fn ImFont_ImFont(self: *Font) callconv(.C) void; pub extern fn ImFont_IsLoaded(self: *const Font) callconv(.C) bool; pub extern fn ImFont_RenderChar(self: *const Font, draw_list: ?*DrawList, size: f32, pos: Vec2, col: u32, c: Wchar) callconv(.C) void; pub extern fn ImFont_RenderText(self: *const Font, draw_list: ?*DrawList, size: f32, pos: Vec2, col: u32, clip_rect: Vec4, text_begin: ?[*]const u8, text_end: ?[*]const u8, wrap_width: f32, cpu_fine_clip: bool) callconv(.C) void; pub extern fn ImFont_SetFallbackChar(self: *Font, c: Wchar) callconv(.C) void; pub extern fn ImFont_destroy(self: *Font) callconv(.C) void; pub extern fn ImGuiIO_AddInputCharacter(self: *IO, c: u32) callconv(.C) void; pub extern fn ImGuiIO_AddInputCharactersUTF8(self: *IO, str: ?[*:0]const u8) callconv(.C) void; pub extern fn ImGuiIO_ClearInputCharacters(self: *IO) callconv(.C) void; pub extern fn ImGuiIO_ImGuiIO(self: *IO) callconv(.C) void; pub extern fn ImGuiIO_destroy(self: *IO) callconv(.C) void; pub extern fn ImGuiInputTextCallbackData_DeleteChars(self: *InputTextCallbackData, pos: i32, bytes_count: i32) callconv(.C) void; pub extern fn ImGuiInputTextCallbackData_HasSelection(self: *const InputTextCallbackData) callconv(.C) bool; pub extern fn ImGuiInputTextCallbackData_ImGuiInputTextCallbackData(self: *InputTextCallbackData) callconv(.C) void; pub extern fn ImGuiInputTextCallbackData_InsertChars(self: *InputTextCallbackData, pos: i32, text: ?[*]const u8, text_end: ?[*]const u8) callconv(.C) void; pub extern fn ImGuiInputTextCallbackData_destroy(self: *InputTextCallbackData) callconv(.C) void; pub extern fn ImGuiListClipper_Begin(self: *ListClipper, items_count: i32, items_height: f32) callconv(.C) void; pub extern fn ImGuiListClipper_End(self: *ListClipper) callconv(.C) void; pub extern fn ImGuiListClipper_ImGuiListClipper(self: *ListClipper, items_count: i32, items_height: f32) callconv(.C) void; pub extern fn ImGuiListClipper_Step(self: *ListClipper) callconv(.C) bool; pub extern fn ImGuiListClipper_destroy(self: *ListClipper) callconv(.C) void; pub extern fn ImGuiOnceUponAFrame_ImGuiOnceUponAFrame(self: *OnceUponAFrame) callconv(.C) void; pub extern fn ImGuiOnceUponAFrame_destroy(self: *OnceUponAFrame) callconv(.C) void; pub extern fn ImGuiPayload_Clear(self: *Payload) callconv(.C) void; pub extern fn ImGuiPayload_ImGuiPayload(self: *Payload) callconv(.C) void; pub extern fn ImGuiPayload_IsDataType(self: *const Payload, kind: ?[*:0]const u8) callconv(.C) bool; pub extern fn ImGuiPayload_IsDelivery(self: *const Payload) callconv(.C) bool; pub extern fn ImGuiPayload_IsPreview(self: *const Payload) callconv(.C) bool; pub extern fn ImGuiPayload_destroy(self: *Payload) callconv(.C) void; pub extern fn ImGuiStoragePair_ImGuiStoragePairInt(self: *StoragePair, _key: ID, _val_i: i32) callconv(.C) void; pub extern fn ImGuiStoragePair_ImGuiStoragePairFloat(self: *StoragePair, _key: ID, _val_f: f32) callconv(.C) void; pub extern fn ImGuiStoragePair_ImGuiStoragePairPtr(self: *StoragePair, _key: ID, _val_p: ?*c_void) callconv(.C) void; pub extern fn ImGuiStoragePair_destroy(self: *StoragePair) callconv(.C) void; pub extern fn ImGuiStorage_BuildSortByKey(self: *Storage) callconv(.C) void; pub extern fn ImGuiStorage_Clear(self: *Storage) callconv(.C) void; pub extern fn ImGuiStorage_GetBool(self: *const Storage, key: ID, default_val: bool) callconv(.C) bool; pub extern fn ImGuiStorage_GetBoolRef(self: *Storage, key: ID, default_val: bool) callconv(.C) ?*bool; pub extern fn ImGuiStorage_GetFloat(self: *const Storage, key: ID, default_val: f32) callconv(.C) f32; pub extern fn ImGuiStorage_GetFloatRef(self: *Storage, key: ID, default_val: f32) callconv(.C) ?*f32; pub extern fn ImGuiStorage_GetInt(self: *const Storage, key: ID, default_val: i32) callconv(.C) i32; pub extern fn ImGuiStorage_GetIntRef(self: *Storage, key: ID, default_val: i32) callconv(.C) ?*i32; pub extern fn ImGuiStorage_GetVoidPtr(self: *const Storage, key: ID) callconv(.C) ?*c_void; pub extern fn ImGuiStorage_GetVoidPtrRef(self: *Storage, key: ID, default_val: ?*c_void) callconv(.C) ?*?*c_void; pub extern fn ImGuiStorage_SetAllInt(self: *Storage, val: i32) callconv(.C) void; pub extern fn ImGuiStorage_SetBool(self: *Storage, key: ID, val: bool) callconv(.C) void; pub extern fn ImGuiStorage_SetFloat(self: *Storage, key: ID, val: f32) callconv(.C) void; pub extern fn ImGuiStorage_SetInt(self: *Storage, key: ID, val: i32) callconv(.C) void; pub extern fn ImGuiStorage_SetVoidPtr(self: *Storage, key: ID, val: ?*c_void) callconv(.C) void; pub extern fn ImGuiStyle_ImGuiStyle(self: *Style) callconv(.C) void; pub extern fn ImGuiStyle_ScaleAllSizes(self: *Style, scale_factor: f32) callconv(.C) void; pub extern fn ImGuiStyle_destroy(self: *Style) callconv(.C) void; pub extern fn ImGuiTextBuffer_ImGuiTextBuffer(self: *TextBuffer) callconv(.C) void; pub extern fn ImGuiTextBuffer_append(self: *TextBuffer, str: ?[*]const u8, str_end: ?[*]const u8) callconv(.C) void; pub extern fn ImGuiTextBuffer_appendf(self: *TextBuffer, fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn ImGuiTextBuffer_begin(self: *const TextBuffer) callconv(.C) [*]const u8; pub extern fn ImGuiTextBuffer_c_str(self: *const TextBuffer) callconv(.C) [*:0]const u8; pub extern fn ImGuiTextBuffer_clear(self: *TextBuffer) callconv(.C) void; pub extern fn ImGuiTextBuffer_destroy(self: *TextBuffer) callconv(.C) void; pub extern fn ImGuiTextBuffer_empty(self: *const TextBuffer) callconv(.C) bool; pub extern fn ImGuiTextBuffer_end(self: *const TextBuffer) callconv(.C) [*]const u8; pub extern fn ImGuiTextBuffer_reserve(self: *TextBuffer, capacity: i32) callconv(.C) void; pub extern fn ImGuiTextBuffer_size(self: *const TextBuffer) callconv(.C) i32; pub extern fn ImGuiTextFilter_Build(self: *TextFilter) callconv(.C) void; pub extern fn ImGuiTextFilter_Clear(self: *TextFilter) callconv(.C) void; pub extern fn ImGuiTextFilter_Draw(self: *TextFilter, label: ?[*:0]const u8, width: f32) callconv(.C) bool; pub extern fn ImGuiTextFilter_ImGuiTextFilter(self: *TextFilter, default_filter: ?[*:0]const u8) callconv(.C) void; pub extern fn ImGuiTextFilter_IsActive(self: *const TextFilter) callconv(.C) bool; pub extern fn ImGuiTextFilter_PassFilter(self: *const TextFilter, text: ?[*]const u8, text_end: ?[*]const u8) callconv(.C) bool; pub extern fn ImGuiTextFilter_destroy(self: *TextFilter) callconv(.C) void; pub extern fn ImGuiTextRange_ImGuiTextRange(self: *TextRange) callconv(.C) void; pub extern fn ImGuiTextRange_ImGuiTextRangeStr(self: *TextRange, _b: ?[*]const u8, _e: ?[*]const u8) callconv(.C) void; pub extern fn ImGuiTextRange_destroy(self: *TextRange) callconv(.C) void; pub extern fn ImGuiTextRange_empty(self: *const TextRange) callconv(.C) bool; pub extern fn ImGuiTextRange_split(self: *const TextRange, separator: u8, out: ?*Vector(TextRange)) callconv(.C) void; pub extern fn ImVec2_ImVec2(self: *Vec2) callconv(.C) void; pub extern fn ImVec2_ImVec2Float(self: *Vec2, _x: f32, _y: f32) callconv(.C) void; pub extern fn ImVec2_destroy(self: *Vec2) callconv(.C) void; pub extern fn ImVec4_ImVec4(self: *Vec4) callconv(.C) void; pub extern fn ImVec4_ImVec4Float(self: *Vec4, _x: f32, _y: f32, _z: f32, _w: f32) callconv(.C) void; pub extern fn ImVec4_destroy(self: *Vec4) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_ImVector_ImDrawChannel(self: *Vector(DrawChannel)) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_ImVector_ImDrawCmd(self: *Vector(DrawCmd)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_ImVector_ImDrawIdx(self: *Vector(DrawIdx)) callconv(.C) void; pub extern fn ImVector_ImDrawVert_ImVector_ImDrawVert(self: *Vector(DrawVert)) callconv(.C) void; pub extern fn ImVector_ImFontPtr_ImVector_ImFontPtr(self: *Vector(*Font)) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_ImVector_ImFontAtlasCustomRect(self: *Vector(FontAtlasCustomRect)) callconv(.C) void; pub extern fn ImVector_ImFontConfig_ImVector_ImFontConfig(self: *Vector(FontConfig)) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_ImVector_ImFontGlyph(self: *Vector(FontGlyph)) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_ImVector_ImGuiStoragePair(self: *Vector(StoragePair)) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_ImVector_ImGuiTextRange(self: *Vector(TextRange)) callconv(.C) void; pub extern fn ImVector_ImTextureID_ImVector_ImTextureID(self: *Vector(TextureID)) callconv(.C) void; pub extern fn ImVector_ImU32_ImVector_ImU32(self: *Vector(u32)) callconv(.C) void; pub extern fn ImVector_ImVec2_ImVector_ImVec2(self: *Vector(Vec2)) callconv(.C) void; pub extern fn ImVector_ImVec4_ImVector_ImVec4(self: *Vector(Vec4)) callconv(.C) void; pub extern fn ImVector_ImWchar_ImVector_ImWchar(self: *Vector(Wchar)) callconv(.C) void; pub extern fn ImVector_char_ImVector_char(self: *Vector(u8)) callconv(.C) void; pub extern fn ImVector_float_ImVector_float(self: *Vector(f32)) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_ImVector_ImDrawChannelVector(self: *Vector(DrawChannel), src: Vector(DrawChannel)) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_ImVector_ImDrawCmdVector(self: *Vector(DrawCmd), src: Vector(DrawCmd)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_ImVector_ImDrawIdxVector(self: *Vector(DrawIdx), src: Vector(DrawIdx)) callconv(.C) void; pub extern fn ImVector_ImDrawVert_ImVector_ImDrawVertVector(self: *Vector(DrawVert), src: Vector(DrawVert)) callconv(.C) void; pub extern fn ImVector_ImFontPtr_ImVector_ImFontPtrVector(self: *Vector(*Font), src: Vector(*Font)) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_ImVector_ImFontAtlasCustomRectVector(self: *Vector(FontAtlasCustomRect), src: Vector(FontAtlasCustomRect)) callconv(.C) void; pub extern fn ImVector_ImFontConfig_ImVector_ImFontConfigVector(self: *Vector(FontConfig), src: Vector(FontConfig)) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_ImVector_ImFontGlyphVector(self: *Vector(FontGlyph), src: Vector(FontGlyph)) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_ImVector_ImGuiStoragePairVector(self: *Vector(StoragePair), src: Vector(StoragePair)) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_ImVector_ImGuiTextRangeVector(self: *Vector(TextRange), src: Vector(TextRange)) callconv(.C) void; pub extern fn ImVector_ImTextureID_ImVector_ImTextureIDVector(self: *Vector(TextureID), src: Vector(TextureID)) callconv(.C) void; pub extern fn ImVector_ImU32_ImVector_ImU32Vector(self: *Vector(u32), src: Vector(u32)) callconv(.C) void; pub extern fn ImVector_ImVec2_ImVector_ImVec2Vector(self: *Vector(Vec2), src: Vector(Vec2)) callconv(.C) void; pub extern fn ImVector_ImVec4_ImVector_ImVec4Vector(self: *Vector(Vec4), src: Vector(Vec4)) callconv(.C) void; pub extern fn ImVector_ImWchar_ImVector_ImWcharVector(self: *Vector(Wchar), src: Vector(Wchar)) callconv(.C) void; pub extern fn ImVector_char_ImVector_charVector(self: *Vector(u8), src: Vector(u8)) callconv(.C) void; pub extern fn ImVector_float_ImVector_floatVector(self: *Vector(f32), src: Vector(f32)) callconv(.C) void; pub extern fn ImVector_ImDrawChannel__grow_capacity(self: *const Vector(DrawChannel), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImDrawCmd__grow_capacity(self: *const Vector(DrawCmd), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImDrawIdx__grow_capacity(self: *const Vector(DrawIdx), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImDrawVert__grow_capacity(self: *const Vector(DrawVert), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImFontPtr__grow_capacity(self: *const Vector(*Font), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImFontAtlasCustomRect__grow_capacity(self: *const Vector(FontAtlasCustomRect), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImFontConfig__grow_capacity(self: *const Vector(FontConfig), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImFontGlyph__grow_capacity(self: *const Vector(FontGlyph), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImGuiStoragePair__grow_capacity(self: *const Vector(StoragePair), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImGuiTextRange__grow_capacity(self: *const Vector(TextRange), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImTextureID__grow_capacity(self: *const Vector(TextureID), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImU32__grow_capacity(self: *const Vector(u32), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImVec2__grow_capacity(self: *const Vector(Vec2), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImVec4__grow_capacity(self: *const Vector(Vec4), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImWchar__grow_capacity(self: *const Vector(Wchar), sz: i32) callconv(.C) i32; pub extern fn ImVector_char__grow_capacity(self: *const Vector(u8), sz: i32) callconv(.C) i32; pub extern fn ImVector_float__grow_capacity(self: *const Vector(f32), sz: i32) callconv(.C) i32; pub extern fn ImVector_ImDrawChannel_back(self: *Vector(DrawChannel)) callconv(.C) *DrawChannel; pub extern fn ImVector_ImDrawCmd_back(self: *Vector(DrawCmd)) callconv(.C) *DrawCmd; pub extern fn ImVector_ImDrawIdx_back(self: *Vector(DrawIdx)) callconv(.C) *DrawIdx; pub extern fn ImVector_ImDrawVert_back(self: *Vector(DrawVert)) callconv(.C) *DrawVert; pub extern fn ImVector_ImFontPtr_back(self: *Vector(*Font)) callconv(.C) **Font; pub extern fn ImVector_ImFontAtlasCustomRect_back(self: *Vector(FontAtlasCustomRect)) callconv(.C) *FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_back(self: *Vector(FontConfig)) callconv(.C) *FontConfig; pub extern fn ImVector_ImFontGlyph_back(self: *Vector(FontGlyph)) callconv(.C) *FontGlyph; pub extern fn ImVector_ImGuiStoragePair_back(self: *Vector(StoragePair)) callconv(.C) *StoragePair; pub extern fn ImVector_ImGuiTextRange_back(self: *Vector(TextRange)) callconv(.C) *TextRange; pub extern fn ImVector_ImTextureID_back(self: *Vector(TextureID)) callconv(.C) *TextureID; pub extern fn ImVector_ImU32_back(self: *Vector(u32)) callconv(.C) *u32; pub extern fn ImVector_ImVec2_back(self: *Vector(Vec2)) callconv(.C) *Vec2; pub extern fn ImVector_ImVec4_back(self: *Vector(Vec4)) callconv(.C) *Vec4; pub extern fn ImVector_ImWchar_back(self: *Vector(Wchar)) callconv(.C) *Wchar; pub extern fn ImVector_char_back(self: *Vector(u8)) callconv(.C) *u8; pub extern fn ImVector_float_back(self: *Vector(f32)) callconv(.C) *f32; pub extern fn ImVector_ImDrawChannel_back_const(self: *const Vector(DrawChannel)) callconv(.C) *const DrawChannel; pub extern fn ImVector_ImDrawCmd_back_const(self: *const Vector(DrawCmd)) callconv(.C) *const DrawCmd; pub extern fn ImVector_ImDrawIdx_back_const(self: *const Vector(DrawIdx)) callconv(.C) *const DrawIdx; pub extern fn ImVector_ImDrawVert_back_const(self: *const Vector(DrawVert)) callconv(.C) *const DrawVert; pub extern fn ImVector_ImFontPtr_back_const(self: *const Vector(*Font)) callconv(.C) *const *Font; pub extern fn ImVector_ImFontAtlasCustomRect_back_const(self: *const Vector(FontAtlasCustomRect)) callconv(.C) *const FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_back_const(self: *const Vector(FontConfig)) callconv(.C) *const FontConfig; pub extern fn ImVector_ImFontGlyph_back_const(self: *const Vector(FontGlyph)) callconv(.C) *const FontGlyph; pub extern fn ImVector_ImGuiStoragePair_back_const(self: *const Vector(StoragePair)) callconv(.C) *const StoragePair; pub extern fn ImVector_ImGuiTextRange_back_const(self: *const Vector(TextRange)) callconv(.C) *const TextRange; pub extern fn ImVector_ImTextureID_back_const(self: *const Vector(TextureID)) callconv(.C) *const TextureID; pub extern fn ImVector_ImU32_back_const(self: *const Vector(u32)) callconv(.C) *const u32; pub extern fn ImVector_ImVec2_back_const(self: *const Vector(Vec2)) callconv(.C) *const Vec2; pub extern fn ImVector_ImVec4_back_const(self: *const Vector(Vec4)) callconv(.C) *const Vec4; pub extern fn ImVector_ImWchar_back_const(self: *const Vector(Wchar)) callconv(.C) *const Wchar; pub extern fn ImVector_char_back_const(self: *const Vector(u8)) callconv(.C) *const u8; pub extern fn ImVector_float_back_const(self: *const Vector(f32)) callconv(.C) *const f32; pub extern fn ImVector_ImDrawChannel_begin(self: *Vector(DrawChannel)) callconv(.C) [*]DrawChannel; pub extern fn ImVector_ImDrawCmd_begin(self: *Vector(DrawCmd)) callconv(.C) [*]DrawCmd; pub extern fn ImVector_ImDrawIdx_begin(self: *Vector(DrawIdx)) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImDrawVert_begin(self: *Vector(DrawVert)) callconv(.C) [*]DrawVert; pub extern fn ImVector_ImFontPtr_begin(self: *Vector(*Font)) callconv(.C) [*]*Font; pub extern fn ImVector_ImFontAtlasCustomRect_begin(self: *Vector(FontAtlasCustomRect)) callconv(.C) [*]FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_begin(self: *Vector(FontConfig)) callconv(.C) [*]FontConfig; pub extern fn ImVector_ImFontGlyph_begin(self: *Vector(FontGlyph)) callconv(.C) [*]FontGlyph; pub extern fn ImVector_ImGuiStoragePair_begin(self: *Vector(StoragePair)) callconv(.C) [*]StoragePair; pub extern fn ImVector_ImGuiTextRange_begin(self: *Vector(TextRange)) callconv(.C) [*]TextRange; pub extern fn ImVector_ImTextureID_begin(self: *Vector(TextureID)) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_begin(self: *Vector(u32)) callconv(.C) [*]u32; pub extern fn ImVector_ImVec2_begin(self: *Vector(Vec2)) callconv(.C) [*]Vec2; pub extern fn ImVector_ImVec4_begin(self: *Vector(Vec4)) callconv(.C) [*]Vec4; pub extern fn ImVector_ImWchar_begin(self: *Vector(Wchar)) callconv(.C) [*]Wchar; pub extern fn ImVector_char_begin(self: *Vector(u8)) callconv(.C) [*]u8; pub extern fn ImVector_float_begin(self: *Vector(f32)) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawChannel_begin_const(self: *const Vector(DrawChannel)) callconv(.C) [*]const DrawChannel; pub extern fn ImVector_ImDrawCmd_begin_const(self: *const Vector(DrawCmd)) callconv(.C) [*]const DrawCmd; pub extern fn ImVector_ImDrawIdx_begin_const(self: *const Vector(DrawIdx)) callconv(.C) [*]const DrawIdx; pub extern fn ImVector_ImDrawVert_begin_const(self: *const Vector(DrawVert)) callconv(.C) [*]const DrawVert; pub extern fn ImVector_ImFontPtr_begin_const(self: *const Vector(*Font)) callconv(.C) [*]const *Font; pub extern fn ImVector_ImFontAtlasCustomRect_begin_const(self: *const Vector(FontAtlasCustomRect)) callconv(.C) [*]const FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_begin_const(self: *const Vector(FontConfig)) callconv(.C) [*]const FontConfig; pub extern fn ImVector_ImFontGlyph_begin_const(self: *const Vector(FontGlyph)) callconv(.C) [*]const FontGlyph; pub extern fn ImVector_ImGuiStoragePair_begin_const(self: *const Vector(StoragePair)) callconv(.C) [*]const StoragePair; pub extern fn ImVector_ImGuiTextRange_begin_const(self: *const Vector(TextRange)) callconv(.C) [*]const TextRange; pub extern fn ImVector_ImTextureID_begin_const(self: *const Vector(TextureID)) callconv(.C) [*]const TextureID; pub extern fn ImVector_ImU32_begin_const(self: *const Vector(u32)) callconv(.C) [*]const u32; pub extern fn ImVector_ImVec2_begin_const(self: *const Vector(Vec2)) callconv(.C) [*]const Vec2; pub extern fn ImVector_ImVec4_begin_const(self: *const Vector(Vec4)) callconv(.C) [*]const Vec4; pub extern fn ImVector_ImWchar_begin_const(self: *const Vector(Wchar)) callconv(.C) [*]const Wchar; pub extern fn ImVector_char_begin_const(self: *const Vector(u8)) callconv(.C) [*]const u8; pub extern fn ImVector_float_begin_const(self: *const Vector(f32)) callconv(.C) [*]const f32; pub extern fn ImVector_ImDrawChannel_capacity(self: *const Vector(DrawChannel)) callconv(.C) i32; pub extern fn ImVector_ImDrawCmd_capacity(self: *const Vector(DrawCmd)) callconv(.C) i32; pub extern fn ImVector_ImDrawIdx_capacity(self: *const Vector(DrawIdx)) callconv(.C) i32; pub extern fn ImVector_ImDrawVert_capacity(self: *const Vector(DrawVert)) callconv(.C) i32; pub extern fn ImVector_ImFontPtr_capacity(self: *const Vector(*Font)) callconv(.C) i32; pub extern fn ImVector_ImFontAtlasCustomRect_capacity(self: *const Vector(FontAtlasCustomRect)) callconv(.C) i32; pub extern fn ImVector_ImFontConfig_capacity(self: *const Vector(FontConfig)) callconv(.C) i32; pub extern fn ImVector_ImFontGlyph_capacity(self: *const Vector(FontGlyph)) callconv(.C) i32; pub extern fn ImVector_ImGuiStoragePair_capacity(self: *const Vector(StoragePair)) callconv(.C) i32; pub extern fn ImVector_ImGuiTextRange_capacity(self: *const Vector(TextRange)) callconv(.C) i32; pub extern fn ImVector_ImTextureID_capacity(self: *const Vector(TextureID)) callconv(.C) i32; pub extern fn ImVector_ImU32_capacity(self: *const Vector(u32)) callconv(.C) i32; pub extern fn ImVector_ImVec2_capacity(self: *const Vector(Vec2)) callconv(.C) i32; pub extern fn ImVector_ImVec4_capacity(self: *const Vector(Vec4)) callconv(.C) i32; pub extern fn ImVector_ImWchar_capacity(self: *const Vector(Wchar)) callconv(.C) i32; pub extern fn ImVector_char_capacity(self: *const Vector(u8)) callconv(.C) i32; pub extern fn ImVector_float_capacity(self: *const Vector(f32)) callconv(.C) i32; pub extern fn ImVector_ImDrawChannel_clear(self: *Vector(DrawChannel)) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_clear(self: *Vector(DrawCmd)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_clear(self: *Vector(DrawIdx)) callconv(.C) void; pub extern fn ImVector_ImDrawVert_clear(self: *Vector(DrawVert)) callconv(.C) void; pub extern fn ImVector_ImFontPtr_clear(self: *Vector(*Font)) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_clear(self: *Vector(FontAtlasCustomRect)) callconv(.C) void; pub extern fn ImVector_ImFontConfig_clear(self: *Vector(FontConfig)) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_clear(self: *Vector(FontGlyph)) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_clear(self: *Vector(StoragePair)) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_clear(self: *Vector(TextRange)) callconv(.C) void; pub extern fn ImVector_ImTextureID_clear(self: *Vector(TextureID)) callconv(.C) void; pub extern fn ImVector_ImU32_clear(self: *Vector(u32)) callconv(.C) void; pub extern fn ImVector_ImVec2_clear(self: *Vector(Vec2)) callconv(.C) void; pub extern fn ImVector_ImVec4_clear(self: *Vector(Vec4)) callconv(.C) void; pub extern fn ImVector_ImWchar_clear(self: *Vector(Wchar)) callconv(.C) void; pub extern fn ImVector_char_clear(self: *Vector(u8)) callconv(.C) void; pub extern fn ImVector_float_clear(self: *Vector(f32)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_contains(self: *const Vector(DrawIdx), v: DrawIdx) callconv(.C) bool; pub extern fn ImVector_ImFontPtr_contains(self: *const Vector(*Font), v: *Font) callconv(.C) bool; pub extern fn ImVector_ImTextureID_contains(self: *const Vector(TextureID), v: TextureID) callconv(.C) bool; pub extern fn ImVector_ImU32_contains(self: *const Vector(u32), v: u32) callconv(.C) bool; pub extern fn ImVector_ImWchar_contains(self: *const Vector(Wchar), v: Wchar) callconv(.C) bool; pub extern fn ImVector_char_contains(self: *const Vector(u8), v: u8) callconv(.C) bool; pub extern fn ImVector_float_contains(self: *const Vector(f32), v: f32) callconv(.C) bool; pub extern fn ImVector_ImDrawChannel_destroy(self: *Vector(DrawChannel)) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_destroy(self: *Vector(DrawCmd)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_destroy(self: *Vector(DrawIdx)) callconv(.C) void; pub extern fn ImVector_ImDrawVert_destroy(self: *Vector(DrawVert)) callconv(.C) void; pub extern fn ImVector_ImFontPtr_destroy(self: *Vector(*Font)) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_destroy(self: *Vector(FontAtlasCustomRect)) callconv(.C) void; pub extern fn ImVector_ImFontConfig_destroy(self: *Vector(FontConfig)) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_destroy(self: *Vector(FontGlyph)) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_destroy(self: *Vector(StoragePair)) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_destroy(self: *Vector(TextRange)) callconv(.C) void; pub extern fn ImVector_ImTextureID_destroy(self: *Vector(TextureID)) callconv(.C) void; pub extern fn ImVector_ImU32_destroy(self: *Vector(u32)) callconv(.C) void; pub extern fn ImVector_ImVec2_destroy(self: *Vector(Vec2)) callconv(.C) void; pub extern fn ImVector_ImVec4_destroy(self: *Vector(Vec4)) callconv(.C) void; pub extern fn ImVector_ImWchar_destroy(self: *Vector(Wchar)) callconv(.C) void; pub extern fn ImVector_char_destroy(self: *Vector(u8)) callconv(.C) void; pub extern fn ImVector_float_destroy(self: *Vector(f32)) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_empty(self: *const Vector(DrawChannel)) callconv(.C) bool; pub extern fn ImVector_ImDrawCmd_empty(self: *const Vector(DrawCmd)) callconv(.C) bool; pub extern fn ImVector_ImDrawIdx_empty(self: *const Vector(DrawIdx)) callconv(.C) bool; pub extern fn ImVector_ImDrawVert_empty(self: *const Vector(DrawVert)) callconv(.C) bool; pub extern fn ImVector_ImFontPtr_empty(self: *const Vector(*Font)) callconv(.C) bool; pub extern fn ImVector_ImFontAtlasCustomRect_empty(self: *const Vector(FontAtlasCustomRect)) callconv(.C) bool; pub extern fn ImVector_ImFontConfig_empty(self: *const Vector(FontConfig)) callconv(.C) bool; pub extern fn ImVector_ImFontGlyph_empty(self: *const Vector(FontGlyph)) callconv(.C) bool; pub extern fn ImVector_ImGuiStoragePair_empty(self: *const Vector(StoragePair)) callconv(.C) bool; pub extern fn ImVector_ImGuiTextRange_empty(self: *const Vector(TextRange)) callconv(.C) bool; pub extern fn ImVector_ImTextureID_empty(self: *const Vector(TextureID)) callconv(.C) bool; pub extern fn ImVector_ImU32_empty(self: *const Vector(u32)) callconv(.C) bool; pub extern fn ImVector_ImVec2_empty(self: *const Vector(Vec2)) callconv(.C) bool; pub extern fn ImVector_ImVec4_empty(self: *const Vector(Vec4)) callconv(.C) bool; pub extern fn ImVector_ImWchar_empty(self: *const Vector(Wchar)) callconv(.C) bool; pub extern fn ImVector_char_empty(self: *const Vector(u8)) callconv(.C) bool; pub extern fn ImVector_float_empty(self: *const Vector(f32)) callconv(.C) bool; pub extern fn ImVector_ImDrawChannel_end(self: *Vector(DrawChannel)) callconv(.C) [*]DrawChannel; pub extern fn ImVector_ImDrawCmd_end(self: *Vector(DrawCmd)) callconv(.C) [*]DrawCmd; pub extern fn ImVector_ImDrawIdx_end(self: *Vector(DrawIdx)) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImDrawVert_end(self: *Vector(DrawVert)) callconv(.C) [*]DrawVert; pub extern fn ImVector_ImFontPtr_end(self: *Vector(*Font)) callconv(.C) [*]*Font; pub extern fn ImVector_ImFontAtlasCustomRect_end(self: *Vector(FontAtlasCustomRect)) callconv(.C) [*]FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_end(self: *Vector(FontConfig)) callconv(.C) [*]FontConfig; pub extern fn ImVector_ImFontGlyph_end(self: *Vector(FontGlyph)) callconv(.C) [*]FontGlyph; pub extern fn ImVector_ImGuiStoragePair_end(self: *Vector(StoragePair)) callconv(.C) [*]StoragePair; pub extern fn ImVector_ImGuiTextRange_end(self: *Vector(TextRange)) callconv(.C) [*]TextRange; pub extern fn ImVector_ImTextureID_end(self: *Vector(TextureID)) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_end(self: *Vector(u32)) callconv(.C) [*]u32; pub extern fn ImVector_ImVec2_end(self: *Vector(Vec2)) callconv(.C) [*]Vec2; pub extern fn ImVector_ImVec4_end(self: *Vector(Vec4)) callconv(.C) [*]Vec4; pub extern fn ImVector_ImWchar_end(self: *Vector(Wchar)) callconv(.C) [*]Wchar; pub extern fn ImVector_char_end(self: *Vector(u8)) callconv(.C) [*]u8; pub extern fn ImVector_float_end(self: *Vector(f32)) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawChannel_end_const(self: *const Vector(DrawChannel)) callconv(.C) [*]const DrawChannel; pub extern fn ImVector_ImDrawCmd_end_const(self: *const Vector(DrawCmd)) callconv(.C) [*]const DrawCmd; pub extern fn ImVector_ImDrawIdx_end_const(self: *const Vector(DrawIdx)) callconv(.C) [*]const DrawIdx; pub extern fn ImVector_ImDrawVert_end_const(self: *const Vector(DrawVert)) callconv(.C) [*]const DrawVert; pub extern fn ImVector_ImFontPtr_end_const(self: *const Vector(*Font)) callconv(.C) [*]const *Font; pub extern fn ImVector_ImFontAtlasCustomRect_end_const(self: *const Vector(FontAtlasCustomRect)) callconv(.C) [*]const FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_end_const(self: *const Vector(FontConfig)) callconv(.C) [*]const FontConfig; pub extern fn ImVector_ImFontGlyph_end_const(self: *const Vector(FontGlyph)) callconv(.C) [*]const FontGlyph; pub extern fn ImVector_ImGuiStoragePair_end_const(self: *const Vector(StoragePair)) callconv(.C) [*]const StoragePair; pub extern fn ImVector_ImGuiTextRange_end_const(self: *const Vector(TextRange)) callconv(.C) [*]const TextRange; pub extern fn ImVector_ImTextureID_end_const(self: *const Vector(TextureID)) callconv(.C) [*]const TextureID; pub extern fn ImVector_ImU32_end_const(self: *const Vector(u32)) callconv(.C) [*]const u32; pub extern fn ImVector_ImVec2_end_const(self: *const Vector(Vec2)) callconv(.C) [*]const Vec2; pub extern fn ImVector_ImVec4_end_const(self: *const Vector(Vec4)) callconv(.C) [*]const Vec4; pub extern fn ImVector_ImWchar_end_const(self: *const Vector(Wchar)) callconv(.C) [*]const Wchar; pub extern fn ImVector_char_end_const(self: *const Vector(u8)) callconv(.C) [*]const u8; pub extern fn ImVector_float_end_const(self: *const Vector(f32)) callconv(.C) [*]const f32; pub extern fn ImVector_ImDrawChannel_erase(self: *Vector(DrawChannel), it: [*]const DrawChannel) callconv(.C) [*]DrawChannel; pub extern fn ImVector_ImDrawCmd_erase(self: *Vector(DrawCmd), it: [*]const DrawCmd) callconv(.C) [*]DrawCmd; pub extern fn ImVector_ImDrawIdx_erase(self: *Vector(DrawIdx), it: [*]const DrawIdx) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImDrawVert_erase(self: *Vector(DrawVert), it: [*]const DrawVert) callconv(.C) [*]DrawVert; pub extern fn ImVector_ImFontPtr_erase(self: *Vector(*Font), it: [*]const *Font) callconv(.C) [*]*Font; pub extern fn ImVector_ImFontAtlasCustomRect_erase(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect) callconv(.C) [*]FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_erase(self: *Vector(FontConfig), it: [*]const FontConfig) callconv(.C) [*]FontConfig; pub extern fn ImVector_ImFontGlyph_erase(self: *Vector(FontGlyph), it: [*]const FontGlyph) callconv(.C) [*]FontGlyph; pub extern fn ImVector_ImGuiStoragePair_erase(self: *Vector(StoragePair), it: [*]const StoragePair) callconv(.C) [*]StoragePair; pub extern fn ImVector_ImGuiTextRange_erase(self: *Vector(TextRange), it: [*]const TextRange) callconv(.C) [*]TextRange; pub extern fn ImVector_ImTextureID_erase(self: *Vector(TextureID), it: [*]const TextureID) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_erase(self: *Vector(u32), it: [*]const u32) callconv(.C) [*]u32; pub extern fn ImVector_ImVec2_erase(self: *Vector(Vec2), it: [*]const Vec2) callconv(.C) [*]Vec2; pub extern fn ImVector_ImVec4_erase(self: *Vector(Vec4), it: [*]const Vec4) callconv(.C) [*]Vec4; pub extern fn ImVector_ImWchar_erase(self: *Vector(Wchar), it: [*]const Wchar) callconv(.C) [*]Wchar; pub extern fn ImVector_char_erase(self: *Vector(u8), it: [*]const u8) callconv(.C) [*]u8; pub extern fn ImVector_float_erase(self: *Vector(f32), it: [*]const f32) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawChannel_eraseTPtr(self: *Vector(DrawChannel), it: [*]const DrawChannel, it_last: [*]const DrawChannel) callconv(.C) [*]DrawChannel; pub extern fn ImVector_ImDrawCmd_eraseTPtr(self: *Vector(DrawCmd), it: [*]const DrawCmd, it_last: [*]const DrawCmd) callconv(.C) [*]DrawCmd; pub extern fn ImVector_ImDrawIdx_eraseTPtr(self: *Vector(DrawIdx), it: [*]const DrawIdx, it_last: [*]const DrawIdx) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImDrawVert_eraseTPtr(self: *Vector(DrawVert), it: [*]const DrawVert, it_last: [*]const DrawVert) callconv(.C) [*]DrawVert; pub extern fn ImVector_ImFontPtr_eraseTPtr(self: *Vector(*Font), it: [*]const *Font, it_last: [*]const *Font) callconv(.C) [*]*Font; pub extern fn ImVector_ImFontAtlasCustomRect_eraseTPtr(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect, it_last: [*]const FontAtlasCustomRect) callconv(.C) [*]FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_eraseTPtr(self: *Vector(FontConfig), it: [*]const FontConfig, it_last: [*]const FontConfig) callconv(.C) [*]FontConfig; pub extern fn ImVector_ImFontGlyph_eraseTPtr(self: *Vector(FontGlyph), it: [*]const FontGlyph, it_last: [*]const FontGlyph) callconv(.C) [*]FontGlyph; pub extern fn ImVector_ImGuiStoragePair_eraseTPtr(self: *Vector(StoragePair), it: [*]const StoragePair, it_last: [*]const StoragePair) callconv(.C) [*]StoragePair; pub extern fn ImVector_ImGuiTextRange_eraseTPtr(self: *Vector(TextRange), it: [*]const TextRange, it_last: [*]const TextRange) callconv(.C) [*]TextRange; pub extern fn ImVector_ImTextureID_eraseTPtr(self: *Vector(TextureID), it: [*]const TextureID, it_last: [*]const TextureID) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_eraseTPtr(self: *Vector(u32), it: [*]const u32, it_last: [*]const u32) callconv(.C) [*]u32; pub extern fn ImVector_ImVec2_eraseTPtr(self: *Vector(Vec2), it: [*]const Vec2, it_last: [*]const Vec2) callconv(.C) [*]Vec2; pub extern fn ImVector_ImVec4_eraseTPtr(self: *Vector(Vec4), it: [*]const Vec4, it_last: [*]const Vec4) callconv(.C) [*]Vec4; pub extern fn ImVector_ImWchar_eraseTPtr(self: *Vector(Wchar), it: [*]const Wchar, it_last: [*]const Wchar) callconv(.C) [*]Wchar; pub extern fn ImVector_char_eraseTPtr(self: *Vector(u8), it: [*]const u8, it_last: [*]const u8) callconv(.C) [*]u8; pub extern fn ImVector_float_eraseTPtr(self: *Vector(f32), it: [*]const f32, it_last: [*]const f32) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawChannel_erase_unsorted(self: *Vector(DrawChannel), it: [*]const DrawChannel) callconv(.C) [*]DrawChannel; pub extern fn ImVector_ImDrawCmd_erase_unsorted(self: *Vector(DrawCmd), it: [*]const DrawCmd) callconv(.C) [*]DrawCmd; pub extern fn ImVector_ImDrawIdx_erase_unsorted(self: *Vector(DrawIdx), it: [*]const DrawIdx) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImDrawVert_erase_unsorted(self: *Vector(DrawVert), it: [*]const DrawVert) callconv(.C) [*]DrawVert; pub extern fn ImVector_ImFontPtr_erase_unsorted(self: *Vector(*Font), it: [*]const *Font) callconv(.C) [*]*Font; pub extern fn ImVector_ImFontAtlasCustomRect_erase_unsorted(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect) callconv(.C) [*]FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_erase_unsorted(self: *Vector(FontConfig), it: [*]const FontConfig) callconv(.C) [*]FontConfig; pub extern fn ImVector_ImFontGlyph_erase_unsorted(self: *Vector(FontGlyph), it: [*]const FontGlyph) callconv(.C) [*]FontGlyph; pub extern fn ImVector_ImGuiStoragePair_erase_unsorted(self: *Vector(StoragePair), it: [*]const StoragePair) callconv(.C) [*]StoragePair; pub extern fn ImVector_ImGuiTextRange_erase_unsorted(self: *Vector(TextRange), it: [*]const TextRange) callconv(.C) [*]TextRange; pub extern fn ImVector_ImTextureID_erase_unsorted(self: *Vector(TextureID), it: [*]const TextureID) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_erase_unsorted(self: *Vector(u32), it: [*]const u32) callconv(.C) [*]u32; pub extern fn ImVector_ImVec2_erase_unsorted(self: *Vector(Vec2), it: [*]const Vec2) callconv(.C) [*]Vec2; pub extern fn ImVector_ImVec4_erase_unsorted(self: *Vector(Vec4), it: [*]const Vec4) callconv(.C) [*]Vec4; pub extern fn ImVector_ImWchar_erase_unsorted(self: *Vector(Wchar), it: [*]const Wchar) callconv(.C) [*]Wchar; pub extern fn ImVector_char_erase_unsorted(self: *Vector(u8), it: [*]const u8) callconv(.C) [*]u8; pub extern fn ImVector_float_erase_unsorted(self: *Vector(f32), it: [*]const f32) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawIdx_find(self: *Vector(DrawIdx), v: DrawIdx) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImFontPtr_find(self: *Vector(*Font), v: *Font) callconv(.C) [*]*Font; pub extern fn ImVector_ImTextureID_find(self: *Vector(TextureID), v: TextureID) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_find(self: *Vector(u32), v: u32) callconv(.C) [*]u32; pub extern fn ImVector_ImWchar_find(self: *Vector(Wchar), v: Wchar) callconv(.C) [*]Wchar; pub extern fn ImVector_char_find(self: *Vector(u8), v: u8) callconv(.C) [*]u8; pub extern fn ImVector_float_find(self: *Vector(f32), v: f32) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawIdx_find_const(self: *const Vector(DrawIdx), v: DrawIdx) callconv(.C) [*]const DrawIdx; pub extern fn ImVector_ImFontPtr_find_const(self: *const Vector(*Font), v: *Font) callconv(.C) [*]const *Font; pub extern fn ImVector_ImTextureID_find_const(self: *const Vector(TextureID), v: TextureID) callconv(.C) [*]const TextureID; pub extern fn ImVector_ImU32_find_const(self: *const Vector(u32), v: u32) callconv(.C) [*]const u32; pub extern fn ImVector_ImWchar_find_const(self: *const Vector(Wchar), v: Wchar) callconv(.C) [*]const Wchar; pub extern fn ImVector_char_find_const(self: *const Vector(u8), v: u8) callconv(.C) [*]const u8; pub extern fn ImVector_float_find_const(self: *const Vector(f32), v: f32) callconv(.C) [*]const f32; pub extern fn ImVector_ImDrawIdx_find_erase(self: *Vector(DrawIdx), v: DrawIdx) callconv(.C) bool; pub extern fn ImVector_ImFontPtr_find_erase(self: *Vector(*Font), v: *Font) callconv(.C) bool; pub extern fn ImVector_ImTextureID_find_erase(self: *Vector(TextureID), v: TextureID) callconv(.C) bool; pub extern fn ImVector_ImU32_find_erase(self: *Vector(u32), v: u32) callconv(.C) bool; pub extern fn ImVector_ImWchar_find_erase(self: *Vector(Wchar), v: Wchar) callconv(.C) bool; pub extern fn ImVector_char_find_erase(self: *Vector(u8), v: u8) callconv(.C) bool; pub extern fn ImVector_float_find_erase(self: *Vector(f32), v: f32) callconv(.C) bool; pub extern fn ImVector_ImDrawIdx_find_erase_unsorted(self: *Vector(DrawIdx), v: DrawIdx) callconv(.C) bool; pub extern fn ImVector_ImFontPtr_find_erase_unsorted(self: *Vector(*Font), v: *Font) callconv(.C) bool; pub extern fn ImVector_ImTextureID_find_erase_unsorted(self: *Vector(TextureID), v: TextureID) callconv(.C) bool; pub extern fn ImVector_ImU32_find_erase_unsorted(self: *Vector(u32), v: u32) callconv(.C) bool; pub extern fn ImVector_ImWchar_find_erase_unsorted(self: *Vector(Wchar), v: Wchar) callconv(.C) bool; pub extern fn ImVector_char_find_erase_unsorted(self: *Vector(u8), v: u8) callconv(.C) bool; pub extern fn ImVector_float_find_erase_unsorted(self: *Vector(f32), v: f32) callconv(.C) bool; pub extern fn ImVector_ImDrawChannel_front(self: *Vector(DrawChannel)) callconv(.C) *DrawChannel; pub extern fn ImVector_ImDrawCmd_front(self: *Vector(DrawCmd)) callconv(.C) *DrawCmd; pub extern fn ImVector_ImDrawIdx_front(self: *Vector(DrawIdx)) callconv(.C) *DrawIdx; pub extern fn ImVector_ImDrawVert_front(self: *Vector(DrawVert)) callconv(.C) *DrawVert; pub extern fn ImVector_ImFontPtr_front(self: *Vector(*Font)) callconv(.C) **Font; pub extern fn ImVector_ImFontAtlasCustomRect_front(self: *Vector(FontAtlasCustomRect)) callconv(.C) *FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_front(self: *Vector(FontConfig)) callconv(.C) *FontConfig; pub extern fn ImVector_ImFontGlyph_front(self: *Vector(FontGlyph)) callconv(.C) *FontGlyph; pub extern fn ImVector_ImGuiStoragePair_front(self: *Vector(StoragePair)) callconv(.C) *StoragePair; pub extern fn ImVector_ImGuiTextRange_front(self: *Vector(TextRange)) callconv(.C) *TextRange; pub extern fn ImVector_ImTextureID_front(self: *Vector(TextureID)) callconv(.C) *TextureID; pub extern fn ImVector_ImU32_front(self: *Vector(u32)) callconv(.C) *u32; pub extern fn ImVector_ImVec2_front(self: *Vector(Vec2)) callconv(.C) *Vec2; pub extern fn ImVector_ImVec4_front(self: *Vector(Vec4)) callconv(.C) *Vec4; pub extern fn ImVector_ImWchar_front(self: *Vector(Wchar)) callconv(.C) *Wchar; pub extern fn ImVector_char_front(self: *Vector(u8)) callconv(.C) *u8; pub extern fn ImVector_float_front(self: *Vector(f32)) callconv(.C) *f32; pub extern fn ImVector_ImDrawChannel_front_const(self: *const Vector(DrawChannel)) callconv(.C) *const DrawChannel; pub extern fn ImVector_ImDrawCmd_front_const(self: *const Vector(DrawCmd)) callconv(.C) *const DrawCmd; pub extern fn ImVector_ImDrawIdx_front_const(self: *const Vector(DrawIdx)) callconv(.C) *const DrawIdx; pub extern fn ImVector_ImDrawVert_front_const(self: *const Vector(DrawVert)) callconv(.C) *const DrawVert; pub extern fn ImVector_ImFontPtr_front_const(self: *const Vector(*Font)) callconv(.C) *const *Font; pub extern fn ImVector_ImFontAtlasCustomRect_front_const(self: *const Vector(FontAtlasCustomRect)) callconv(.C) *const FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_front_const(self: *const Vector(FontConfig)) callconv(.C) *const FontConfig; pub extern fn ImVector_ImFontGlyph_front_const(self: *const Vector(FontGlyph)) callconv(.C) *const FontGlyph; pub extern fn ImVector_ImGuiStoragePair_front_const(self: *const Vector(StoragePair)) callconv(.C) *const StoragePair; pub extern fn ImVector_ImGuiTextRange_front_const(self: *const Vector(TextRange)) callconv(.C) *const TextRange; pub extern fn ImVector_ImTextureID_front_const(self: *const Vector(TextureID)) callconv(.C) *const TextureID; pub extern fn ImVector_ImU32_front_const(self: *const Vector(u32)) callconv(.C) *const u32; pub extern fn ImVector_ImVec2_front_const(self: *const Vector(Vec2)) callconv(.C) *const Vec2; pub extern fn ImVector_ImVec4_front_const(self: *const Vector(Vec4)) callconv(.C) *const Vec4; pub extern fn ImVector_ImWchar_front_const(self: *const Vector(Wchar)) callconv(.C) *const Wchar; pub extern fn ImVector_char_front_const(self: *const Vector(u8)) callconv(.C) *const u8; pub extern fn ImVector_float_front_const(self: *const Vector(f32)) callconv(.C) *const f32; pub extern fn ImVector_ImDrawChannel_index_from_ptr(self: *const Vector(DrawChannel), it: [*]const DrawChannel) callconv(.C) i32; pub extern fn ImVector_ImDrawCmd_index_from_ptr(self: *const Vector(DrawCmd), it: [*]const DrawCmd) callconv(.C) i32; pub extern fn ImVector_ImDrawIdx_index_from_ptr(self: *const Vector(DrawIdx), it: [*]const DrawIdx) callconv(.C) i32; pub extern fn ImVector_ImDrawVert_index_from_ptr(self: *const Vector(DrawVert), it: [*]const DrawVert) callconv(.C) i32; pub extern fn ImVector_ImFontPtr_index_from_ptr(self: *const Vector(*Font), it: [*]const *Font) callconv(.C) i32; pub extern fn ImVector_ImFontAtlasCustomRect_index_from_ptr(self: *const Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect) callconv(.C) i32; pub extern fn ImVector_ImFontConfig_index_from_ptr(self: *const Vector(FontConfig), it: [*]const FontConfig) callconv(.C) i32; pub extern fn ImVector_ImFontGlyph_index_from_ptr(self: *const Vector(FontGlyph), it: [*]const FontGlyph) callconv(.C) i32; pub extern fn ImVector_ImGuiStoragePair_index_from_ptr(self: *const Vector(StoragePair), it: [*]const StoragePair) callconv(.C) i32; pub extern fn ImVector_ImGuiTextRange_index_from_ptr(self: *const Vector(TextRange), it: [*]const TextRange) callconv(.C) i32; pub extern fn ImVector_ImTextureID_index_from_ptr(self: *const Vector(TextureID), it: [*]const TextureID) callconv(.C) i32; pub extern fn ImVector_ImU32_index_from_ptr(self: *const Vector(u32), it: [*]const u32) callconv(.C) i32; pub extern fn ImVector_ImVec2_index_from_ptr(self: *const Vector(Vec2), it: [*]const Vec2) callconv(.C) i32; pub extern fn ImVector_ImVec4_index_from_ptr(self: *const Vector(Vec4), it: [*]const Vec4) callconv(.C) i32; pub extern fn ImVector_ImWchar_index_from_ptr(self: *const Vector(Wchar), it: [*]const Wchar) callconv(.C) i32; pub extern fn ImVector_char_index_from_ptr(self: *const Vector(u8), it: [*]const u8) callconv(.C) i32; pub extern fn ImVector_float_index_from_ptr(self: *const Vector(f32), it: [*]const f32) callconv(.C) i32; pub extern fn ImVector_ImDrawChannel_insert(self: *Vector(DrawChannel), it: [*]const DrawChannel, v: DrawChannel) callconv(.C) [*]DrawChannel; pub extern fn ImVector_ImDrawCmd_insert(self: *Vector(DrawCmd), it: [*]const DrawCmd, v: DrawCmd) callconv(.C) [*]DrawCmd; pub extern fn ImVector_ImDrawIdx_insert(self: *Vector(DrawIdx), it: [*]const DrawIdx, v: DrawIdx) callconv(.C) [*]DrawIdx; pub extern fn ImVector_ImDrawVert_insert(self: *Vector(DrawVert), it: [*]const DrawVert, v: DrawVert) callconv(.C) [*]DrawVert; pub extern fn ImVector_ImFontPtr_insert(self: *Vector(*Font), it: [*]const *Font, v: *Font) callconv(.C) [*]*Font; pub extern fn ImVector_ImFontAtlasCustomRect_insert(self: *Vector(FontAtlasCustomRect), it: [*]const FontAtlasCustomRect, v: FontAtlasCustomRect) callconv(.C) [*]FontAtlasCustomRect; pub extern fn ImVector_ImFontConfig_insert(self: *Vector(FontConfig), it: [*]const FontConfig, v: FontConfig) callconv(.C) [*]FontConfig; pub extern fn ImVector_ImFontGlyph_insert(self: *Vector(FontGlyph), it: [*]const FontGlyph, v: FontGlyph) callconv(.C) [*]FontGlyph; pub extern fn ImVector_ImGuiStoragePair_insert(self: *Vector(StoragePair), it: [*]const StoragePair, v: StoragePair) callconv(.C) [*]StoragePair; pub extern fn ImVector_ImGuiTextRange_insert(self: *Vector(TextRange), it: [*]const TextRange, v: TextRange) callconv(.C) [*]TextRange; pub extern fn ImVector_ImTextureID_insert(self: *Vector(TextureID), it: [*]const TextureID, v: TextureID) callconv(.C) [*]TextureID; pub extern fn ImVector_ImU32_insert(self: *Vector(u32), it: [*]const u32, v: u32) callconv(.C) [*]u32; pub extern fn ImVector_ImVec2_insert(self: *Vector(Vec2), it: [*]const Vec2, v: Vec2) callconv(.C) [*]Vec2; pub extern fn ImVector_ImVec4_insert(self: *Vector(Vec4), it: [*]const Vec4, v: Vec4) callconv(.C) [*]Vec4; pub extern fn ImVector_ImWchar_insert(self: *Vector(Wchar), it: [*]const Wchar, v: Wchar) callconv(.C) [*]Wchar; pub extern fn ImVector_char_insert(self: *Vector(u8), it: [*]const u8, v: u8) callconv(.C) [*]u8; pub extern fn ImVector_float_insert(self: *Vector(f32), it: [*]const f32, v: f32) callconv(.C) [*]f32; pub extern fn ImVector_ImDrawChannel_pop_back(self: *Vector(DrawChannel)) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_pop_back(self: *Vector(DrawCmd)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_pop_back(self: *Vector(DrawIdx)) callconv(.C) void; pub extern fn ImVector_ImDrawVert_pop_back(self: *Vector(DrawVert)) callconv(.C) void; pub extern fn ImVector_ImFontPtr_pop_back(self: *Vector(*Font)) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_pop_back(self: *Vector(FontAtlasCustomRect)) callconv(.C) void; pub extern fn ImVector_ImFontConfig_pop_back(self: *Vector(FontConfig)) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_pop_back(self: *Vector(FontGlyph)) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_pop_back(self: *Vector(StoragePair)) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_pop_back(self: *Vector(TextRange)) callconv(.C) void; pub extern fn ImVector_ImTextureID_pop_back(self: *Vector(TextureID)) callconv(.C) void; pub extern fn ImVector_ImU32_pop_back(self: *Vector(u32)) callconv(.C) void; pub extern fn ImVector_ImVec2_pop_back(self: *Vector(Vec2)) callconv(.C) void; pub extern fn ImVector_ImVec4_pop_back(self: *Vector(Vec4)) callconv(.C) void; pub extern fn ImVector_ImWchar_pop_back(self: *Vector(Wchar)) callconv(.C) void; pub extern fn ImVector_char_pop_back(self: *Vector(u8)) callconv(.C) void; pub extern fn ImVector_float_pop_back(self: *Vector(f32)) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_push_back(self: *Vector(DrawChannel), v: DrawChannel) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_push_back(self: *Vector(DrawCmd), v: DrawCmd) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_push_back(self: *Vector(DrawIdx), v: DrawIdx) callconv(.C) void; pub extern fn ImVector_ImDrawVert_push_back(self: *Vector(DrawVert), v: DrawVert) callconv(.C) void; pub extern fn ImVector_ImFontPtr_push_back(self: *Vector(*Font), v: *Font) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_push_back(self: *Vector(FontAtlasCustomRect), v: FontAtlasCustomRect) callconv(.C) void; pub extern fn ImVector_ImFontConfig_push_back(self: *Vector(FontConfig), v: FontConfig) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_push_back(self: *Vector(FontGlyph), v: FontGlyph) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_push_back(self: *Vector(StoragePair), v: StoragePair) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_push_back(self: *Vector(TextRange), v: TextRange) callconv(.C) void; pub extern fn ImVector_ImTextureID_push_back(self: *Vector(TextureID), v: TextureID) callconv(.C) void; pub extern fn ImVector_ImU32_push_back(self: *Vector(u32), v: u32) callconv(.C) void; pub extern fn ImVector_ImVec2_push_back(self: *Vector(Vec2), v: Vec2) callconv(.C) void; pub extern fn ImVector_ImVec4_push_back(self: *Vector(Vec4), v: Vec4) callconv(.C) void; pub extern fn ImVector_ImWchar_push_back(self: *Vector(Wchar), v: Wchar) callconv(.C) void; pub extern fn ImVector_char_push_back(self: *Vector(u8), v: u8) callconv(.C) void; pub extern fn ImVector_float_push_back(self: *Vector(f32), v: f32) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_push_front(self: *Vector(DrawChannel), v: DrawChannel) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_push_front(self: *Vector(DrawCmd), v: DrawCmd) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_push_front(self: *Vector(DrawIdx), v: DrawIdx) callconv(.C) void; pub extern fn ImVector_ImDrawVert_push_front(self: *Vector(DrawVert), v: DrawVert) callconv(.C) void; pub extern fn ImVector_ImFontPtr_push_front(self: *Vector(*Font), v: *Font) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_push_front(self: *Vector(FontAtlasCustomRect), v: FontAtlasCustomRect) callconv(.C) void; pub extern fn ImVector_ImFontConfig_push_front(self: *Vector(FontConfig), v: FontConfig) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_push_front(self: *Vector(FontGlyph), v: FontGlyph) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_push_front(self: *Vector(StoragePair), v: StoragePair) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_push_front(self: *Vector(TextRange), v: TextRange) callconv(.C) void; pub extern fn ImVector_ImTextureID_push_front(self: *Vector(TextureID), v: TextureID) callconv(.C) void; pub extern fn ImVector_ImU32_push_front(self: *Vector(u32), v: u32) callconv(.C) void; pub extern fn ImVector_ImVec2_push_front(self: *Vector(Vec2), v: Vec2) callconv(.C) void; pub extern fn ImVector_ImVec4_push_front(self: *Vector(Vec4), v: Vec4) callconv(.C) void; pub extern fn ImVector_ImWchar_push_front(self: *Vector(Wchar), v: Wchar) callconv(.C) void; pub extern fn ImVector_char_push_front(self: *Vector(u8), v: u8) callconv(.C) void; pub extern fn ImVector_float_push_front(self: *Vector(f32), v: f32) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_reserve(self: *Vector(DrawChannel), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_reserve(self: *Vector(DrawCmd), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_reserve(self: *Vector(DrawIdx), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImDrawVert_reserve(self: *Vector(DrawVert), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImFontPtr_reserve(self: *Vector(*Font), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_reserve(self: *Vector(FontAtlasCustomRect), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImFontConfig_reserve(self: *Vector(FontConfig), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_reserve(self: *Vector(FontGlyph), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_reserve(self: *Vector(StoragePair), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_reserve(self: *Vector(TextRange), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImTextureID_reserve(self: *Vector(TextureID), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImU32_reserve(self: *Vector(u32), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImVec2_reserve(self: *Vector(Vec2), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImVec4_reserve(self: *Vector(Vec4), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImWchar_reserve(self: *Vector(Wchar), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_char_reserve(self: *Vector(u8), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_float_reserve(self: *Vector(f32), new_capacity: i32) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_resize(self: *Vector(DrawChannel), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_resize(self: *Vector(DrawCmd), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_resize(self: *Vector(DrawIdx), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawVert_resize(self: *Vector(DrawVert), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontPtr_resize(self: *Vector(*Font), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_resize(self: *Vector(FontAtlasCustomRect), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontConfig_resize(self: *Vector(FontConfig), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_resize(self: *Vector(FontGlyph), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_resize(self: *Vector(StoragePair), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_resize(self: *Vector(TextRange), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImTextureID_resize(self: *Vector(TextureID), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImU32_resize(self: *Vector(u32), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImVec2_resize(self: *Vector(Vec2), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImVec4_resize(self: *Vector(Vec4), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImWchar_resize(self: *Vector(Wchar), new_size: i32) callconv(.C) void; pub extern fn ImVector_char_resize(self: *Vector(u8), new_size: i32) callconv(.C) void; pub extern fn ImVector_float_resize(self: *Vector(f32), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_resizeT(self: *Vector(DrawChannel), new_size: i32, v: DrawChannel) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_resizeT(self: *Vector(DrawCmd), new_size: i32, v: DrawCmd) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_resizeT(self: *Vector(DrawIdx), new_size: i32, v: DrawIdx) callconv(.C) void; pub extern fn ImVector_ImDrawVert_resizeT(self: *Vector(DrawVert), new_size: i32, v: DrawVert) callconv(.C) void; pub extern fn ImVector_ImFontPtr_resizeT(self: *Vector(*Font), new_size: i32, v: *Font) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_resizeT(self: *Vector(FontAtlasCustomRect), new_size: i32, v: FontAtlasCustomRect) callconv(.C) void; pub extern fn ImVector_ImFontConfig_resizeT(self: *Vector(FontConfig), new_size: i32, v: FontConfig) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_resizeT(self: *Vector(FontGlyph), new_size: i32, v: FontGlyph) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_resizeT(self: *Vector(StoragePair), new_size: i32, v: StoragePair) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_resizeT(self: *Vector(TextRange), new_size: i32, v: TextRange) callconv(.C) void; pub extern fn ImVector_ImTextureID_resizeT(self: *Vector(TextureID), new_size: i32, v: TextureID) callconv(.C) void; pub extern fn ImVector_ImU32_resizeT(self: *Vector(u32), new_size: i32, v: u32) callconv(.C) void; pub extern fn ImVector_ImVec2_resizeT(self: *Vector(Vec2), new_size: i32, v: Vec2) callconv(.C) void; pub extern fn ImVector_ImVec4_resizeT(self: *Vector(Vec4), new_size: i32, v: Vec4) callconv(.C) void; pub extern fn ImVector_ImWchar_resizeT(self: *Vector(Wchar), new_size: i32, v: Wchar) callconv(.C) void; pub extern fn ImVector_char_resizeT(self: *Vector(u8), new_size: i32, v: u8) callconv(.C) void; pub extern fn ImVector_float_resizeT(self: *Vector(f32), new_size: i32, v: f32) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_shrink(self: *Vector(DrawChannel), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_shrink(self: *Vector(DrawCmd), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_shrink(self: *Vector(DrawIdx), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawVert_shrink(self: *Vector(DrawVert), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontPtr_shrink(self: *Vector(*Font), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_shrink(self: *Vector(FontAtlasCustomRect), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontConfig_shrink(self: *Vector(FontConfig), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_shrink(self: *Vector(FontGlyph), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_shrink(self: *Vector(StoragePair), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_shrink(self: *Vector(TextRange), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImTextureID_shrink(self: *Vector(TextureID), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImU32_shrink(self: *Vector(u32), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImVec2_shrink(self: *Vector(Vec2), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImVec4_shrink(self: *Vector(Vec4), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImWchar_shrink(self: *Vector(Wchar), new_size: i32) callconv(.C) void; pub extern fn ImVector_char_shrink(self: *Vector(u8), new_size: i32) callconv(.C) void; pub extern fn ImVector_float_shrink(self: *Vector(f32), new_size: i32) callconv(.C) void; pub extern fn ImVector_ImDrawChannel_size(self: *const Vector(DrawChannel)) callconv(.C) i32; pub extern fn ImVector_ImDrawCmd_size(self: *const Vector(DrawCmd)) callconv(.C) i32; pub extern fn ImVector_ImDrawIdx_size(self: *const Vector(DrawIdx)) callconv(.C) i32; pub extern fn ImVector_ImDrawVert_size(self: *const Vector(DrawVert)) callconv(.C) i32; pub extern fn ImVector_ImFontPtr_size(self: *const Vector(*Font)) callconv(.C) i32; pub extern fn ImVector_ImFontAtlasCustomRect_size(self: *const Vector(FontAtlasCustomRect)) callconv(.C) i32; pub extern fn ImVector_ImFontConfig_size(self: *const Vector(FontConfig)) callconv(.C) i32; pub extern fn ImVector_ImFontGlyph_size(self: *const Vector(FontGlyph)) callconv(.C) i32; pub extern fn ImVector_ImGuiStoragePair_size(self: *const Vector(StoragePair)) callconv(.C) i32; pub extern fn ImVector_ImGuiTextRange_size(self: *const Vector(TextRange)) callconv(.C) i32; pub extern fn ImVector_ImTextureID_size(self: *const Vector(TextureID)) callconv(.C) i32; pub extern fn ImVector_ImU32_size(self: *const Vector(u32)) callconv(.C) i32; pub extern fn ImVector_ImVec2_size(self: *const Vector(Vec2)) callconv(.C) i32; pub extern fn ImVector_ImVec4_size(self: *const Vector(Vec4)) callconv(.C) i32; pub extern fn ImVector_ImWchar_size(self: *const Vector(Wchar)) callconv(.C) i32; pub extern fn ImVector_char_size(self: *const Vector(u8)) callconv(.C) i32; pub extern fn ImVector_float_size(self: *const Vector(f32)) callconv(.C) i32; pub extern fn ImVector_ImDrawChannel_size_in_bytes(self: *const Vector(DrawChannel)) callconv(.C) i32; pub extern fn ImVector_ImDrawCmd_size_in_bytes(self: *const Vector(DrawCmd)) callconv(.C) i32; pub extern fn ImVector_ImDrawIdx_size_in_bytes(self: *const Vector(DrawIdx)) callconv(.C) i32; pub extern fn ImVector_ImDrawVert_size_in_bytes(self: *const Vector(DrawVert)) callconv(.C) i32; pub extern fn ImVector_ImFontPtr_size_in_bytes(self: *const Vector(*Font)) callconv(.C) i32; pub extern fn ImVector_ImFontAtlasCustomRect_size_in_bytes(self: *const Vector(FontAtlasCustomRect)) callconv(.C) i32; pub extern fn ImVector_ImFontConfig_size_in_bytes(self: *const Vector(FontConfig)) callconv(.C) i32; pub extern fn ImVector_ImFontGlyph_size_in_bytes(self: *const Vector(FontGlyph)) callconv(.C) i32; pub extern fn ImVector_ImGuiStoragePair_size_in_bytes(self: *const Vector(StoragePair)) callconv(.C) i32; pub extern fn ImVector_ImGuiTextRange_size_in_bytes(self: *const Vector(TextRange)) callconv(.C) i32; pub extern fn ImVector_ImTextureID_size_in_bytes(self: *const Vector(TextureID)) callconv(.C) i32; pub extern fn ImVector_ImU32_size_in_bytes(self: *const Vector(u32)) callconv(.C) i32; pub extern fn ImVector_ImVec2_size_in_bytes(self: *const Vector(Vec2)) callconv(.C) i32; pub extern fn ImVector_ImVec4_size_in_bytes(self: *const Vector(Vec4)) callconv(.C) i32; pub extern fn ImVector_ImWchar_size_in_bytes(self: *const Vector(Wchar)) callconv(.C) i32; pub extern fn ImVector_char_size_in_bytes(self: *const Vector(u8)) callconv(.C) i32; pub extern fn ImVector_float_size_in_bytes(self: *const Vector(f32)) callconv(.C) i32; pub extern fn ImVector_ImDrawChannel_swap(self: *Vector(DrawChannel), rhs: *Vector(DrawChannel)) callconv(.C) void; pub extern fn ImVector_ImDrawCmd_swap(self: *Vector(DrawCmd), rhs: *Vector(DrawCmd)) callconv(.C) void; pub extern fn ImVector_ImDrawIdx_swap(self: *Vector(DrawIdx), rhs: *Vector(DrawIdx)) callconv(.C) void; pub extern fn ImVector_ImDrawVert_swap(self: *Vector(DrawVert), rhs: *Vector(DrawVert)) callconv(.C) void; pub extern fn ImVector_ImFontPtr_swap(self: *Vector(*Font), rhs: *Vector(*Font)) callconv(.C) void; pub extern fn ImVector_ImFontAtlasCustomRect_swap(self: *Vector(FontAtlasCustomRect), rhs: *Vector(FontAtlasCustomRect)) callconv(.C) void; pub extern fn ImVector_ImFontConfig_swap(self: *Vector(FontConfig), rhs: *Vector(FontConfig)) callconv(.C) void; pub extern fn ImVector_ImFontGlyph_swap(self: *Vector(FontGlyph), rhs: *Vector(FontGlyph)) callconv(.C) void; pub extern fn ImVector_ImGuiStoragePair_swap(self: *Vector(StoragePair), rhs: *Vector(StoragePair)) callconv(.C) void; pub extern fn ImVector_ImGuiTextRange_swap(self: *Vector(TextRange), rhs: *Vector(TextRange)) callconv(.C) void; pub extern fn ImVector_ImTextureID_swap(self: *Vector(TextureID), rhs: *Vector(TextureID)) callconv(.C) void; pub extern fn ImVector_ImU32_swap(self: *Vector(u32), rhs: *Vector(u32)) callconv(.C) void; pub extern fn ImVector_ImVec2_swap(self: *Vector(Vec2), rhs: *Vector(Vec2)) callconv(.C) void; pub extern fn ImVector_ImVec4_swap(self: *Vector(Vec4), rhs: *Vector(Vec4)) callconv(.C) void; pub extern fn ImVector_ImWchar_swap(self: *Vector(Wchar), rhs: *Vector(Wchar)) callconv(.C) void; pub extern fn ImVector_char_swap(self: *Vector(u8), rhs: *Vector(u8)) callconv(.C) void; pub extern fn ImVector_float_swap(self: *Vector(f32), rhs: *Vector(f32)) callconv(.C) void; pub extern fn igAcceptDragDropPayload(kind: ?[*:0]const u8, flags: DragDropFlagsInt) callconv(.C) ?*const Payload; pub extern fn igAlignTextToFramePadding() callconv(.C) void; pub extern fn igArrowButton(str_id: ?[*:0]const u8, dir: Dir) callconv(.C) bool; pub extern fn igBegin(name: ?[*:0]const u8, p_open: ?*bool, flags: WindowFlagsInt) callconv(.C) bool; pub extern fn igBeginChildStr(str_id: ?[*:0]const u8, size: Vec2, border: bool, flags: WindowFlagsInt) callconv(.C) bool; pub extern fn igBeginChildID(id: ID, size: Vec2, border: bool, flags: WindowFlagsInt) callconv(.C) bool; pub extern fn igBeginChildFrame(id: ID, size: Vec2, flags: WindowFlagsInt) callconv(.C) bool; pub extern fn igBeginCombo(label: ?[*:0]const u8, preview_value: ?[*:0]const u8, flags: ComboFlagsInt) callconv(.C) bool; pub extern fn igBeginDragDropSource(flags: DragDropFlagsInt) callconv(.C) bool; pub extern fn igBeginDragDropTarget() callconv(.C) bool; pub extern fn igBeginGroup() callconv(.C) void; pub extern fn igBeginMainMenuBar() callconv(.C) bool; pub extern fn igBeginMenu(label: ?[*:0]const u8, enabled: bool) callconv(.C) bool; pub extern fn igBeginMenuBar() callconv(.C) bool; pub extern fn igBeginPopup(str_id: ?[*:0]const u8, flags: WindowFlagsInt) callconv(.C) bool; pub extern fn igBeginPopupContextItem(str_id: ?[*:0]const u8, mouse_button: MouseButton) callconv(.C) bool; pub extern fn igBeginPopupContextVoid(str_id: ?[*:0]const u8, mouse_button: MouseButton) callconv(.C) bool; pub extern fn igBeginPopupContextWindow(str_id: ?[*:0]const u8, mouse_button: MouseButton, also_over_items: bool) callconv(.C) bool; pub extern fn igBeginPopupModal(name: ?[*:0]const u8, p_open: ?*bool, flags: WindowFlagsInt) callconv(.C) bool; pub extern fn igBeginTabBar(str_id: ?[*:0]const u8, flags: TabBarFlagsInt) callconv(.C) bool; pub extern fn igBeginTabItem(label: ?[*:0]const u8, p_open: ?*bool, flags: TabItemFlagsInt) callconv(.C) bool; pub extern fn igBeginTooltip() callconv(.C) void; pub extern fn igBullet() callconv(.C) void; pub extern fn igBulletText(fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igButton(label: ?[*:0]const u8, size: Vec2) callconv(.C) bool; pub extern fn igCalcItemWidth() callconv(.C) f32; pub extern fn igCalcListClipping(items_count: i32, items_height: f32, out_items_display_start: *i32, out_items_display_end: *i32) callconv(.C) void; pub extern fn igCalcTextSize_nonUDT(pOut: *Vec2, text: ?[*]const u8, text_end: ?[*]const u8, hide_text_after_double_hash: bool, wrap_width: f32) callconv(.C) void; pub extern fn igCaptureKeyboardFromApp(want_capture_keyboard_value: bool) callconv(.C) void; pub extern fn igCaptureMouseFromApp(want_capture_mouse_value: bool) callconv(.C) void; pub extern fn igCheckbox(label: ?[*:0]const u8, v: *bool) callconv(.C) bool; pub extern fn igCheckboxFlags(label: ?[*:0]const u8, flags: ?*u32, flags_value: u32) callconv(.C) bool; pub extern fn igCloseCurrentPopup() callconv(.C) void; pub extern fn igCollapsingHeader(label: ?[*:0]const u8, flags: TreeNodeFlagsInt) callconv(.C) bool; pub extern fn igCollapsingHeaderBoolPtr(label: ?[*:0]const u8, p_open: ?*bool, flags: TreeNodeFlagsInt) callconv(.C) bool; pub extern fn igColorButton(desc_id: ?[*:0]const u8, col: Vec4, flags: ColorEditFlagsInt, size: Vec2) callconv(.C) bool; pub extern fn igColorConvertFloat4ToU32(in: Vec4) callconv(.C) u32; pub extern fn igColorConvertHSVtoRGB(h: f32, s: f32, v: f32, out_r: *f32, out_g: *f32, out_b: *f32) callconv(.C) void; pub extern fn igColorConvertRGBtoHSV(r: f32, g: f32, b: f32, out_h: *f32, out_s: *f32, out_v: *f32) callconv(.C) void; pub extern fn igColorConvertU32ToFloat4_nonUDT(pOut: *Vec4, in: u32) callconv(.C) void; pub extern fn igColorEdit3(label: ?[*:0]const u8, col: *[3]f32, flags: ColorEditFlagsInt) callconv(.C) bool; pub extern fn igColorEdit4(label: ?[*:0]const u8, col: *[4]f32, flags: ColorEditFlagsInt) callconv(.C) bool; pub extern fn igColorPicker3(label: ?[*:0]const u8, col: *[3]f32, flags: ColorEditFlagsInt) callconv(.C) bool; pub extern fn igColorPicker4(label: ?[*:0]const u8, col: *[4]f32, flags: ColorEditFlagsInt, ref_col: ?*const[4]f32) callconv(.C) bool; pub extern fn igColumns(count: i32, id: ?[*:0]const u8, border: bool) callconv(.C) void; pub extern fn igCombo(label: ?[*:0]const u8, current_item: ?*i32, items: [*]const[*:0]const u8, items_count: i32, popup_max_height_in_items: i32) callconv(.C) bool; pub extern fn igComboStr(label: ?[*:0]const u8, current_item: ?*i32, items_separated_by_zeros: ?[*]const u8, popup_max_height_in_items: i32) callconv(.C) bool; pub extern fn igComboFnPtr(label: ?[*:0]const u8, current_item: ?*i32, items_getter: ?fn (data: ?*c_void, idx: i32, out_text: *?[*:0]const u8) callconv(.C) bool, data: ?*c_void, items_count: i32, popup_max_height_in_items: i32) callconv(.C) bool; pub extern fn igCreateContext(shared_font_atlas: ?*FontAtlas) callconv(.C) ?*Context; pub extern fn igDebugCheckVersionAndDataLayout(version_str: ?[*:0]const u8, sz_io: usize, sz_style: usize, sz_vec2: usize, sz_vec4: usize, sz_drawvert: usize, sz_drawidx: usize) callconv(.C) bool; pub extern fn igDestroyContext(ctx: ?*Context) callconv(.C) void; pub extern fn igDragFloat(label: ?[*:0]const u8, v: *f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDragFloat2(label: ?[*:0]const u8, v: *[2]f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDragFloat3(label: ?[*:0]const u8, v: *[3]f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDragFloat4(label: ?[*:0]const u8, v: *[4]f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDragFloatRange2(label: ?[*:0]const u8, v_current_min: *f32, v_current_max: *f32, v_speed: f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, format_max: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDragInt(label: ?[*:0]const u8, v: *i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igDragInt2(label: ?[*:0]const u8, v: *[2]i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igDragInt3(label: ?[*:0]const u8, v: *[3]i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igDragInt4(label: ?[*:0]const u8, v: *[4]i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igDragIntRange2(label: ?[*:0]const u8, v_current_min: *i32, v_current_max: *i32, v_speed: f32, v_min: i32, v_max: i32, format: ?[*:0]const u8, format_max: ?[*:0]const u8) callconv(.C) bool; pub extern fn igDragScalar(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDragScalarN(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, v_speed: f32, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igDummy(size: Vec2) callconv(.C) void; pub extern fn igEnd() callconv(.C) void; pub extern fn igEndChild() callconv(.C) void; pub extern fn igEndChildFrame() callconv(.C) void; pub extern fn igEndCombo() callconv(.C) void; pub extern fn igEndDragDropSource() callconv(.C) void; pub extern fn igEndDragDropTarget() callconv(.C) void; pub extern fn igEndFrame() callconv(.C) void; pub extern fn igEndGroup() callconv(.C) void; pub extern fn igEndMainMenuBar() callconv(.C) void; pub extern fn igEndMenu() callconv(.C) void; pub extern fn igEndMenuBar() callconv(.C) void; pub extern fn igEndPopup() callconv(.C) void; pub extern fn igEndTabBar() callconv(.C) void; pub extern fn igEndTabItem() callconv(.C) void; pub extern fn igEndTooltip() callconv(.C) void; pub extern fn igGetBackgroundDrawList() callconv(.C) ?*DrawList; pub extern fn igGetClipboardText() callconv(.C) ?[*:0]const u8; pub extern fn igGetColorU32(idx: Col, alpha_mul: f32) callconv(.C) u32; pub extern fn igGetColorU32Vec4(col: Vec4) callconv(.C) u32; pub extern fn igGetColorU32U32(col: u32) callconv(.C) u32; pub extern fn igGetColumnIndex() callconv(.C) i32; pub extern fn igGetColumnOffset(column_index: i32) callconv(.C) f32; pub extern fn igGetColumnWidth(column_index: i32) callconv(.C) f32; pub extern fn igGetColumnsCount() callconv(.C) i32; pub extern fn igGetContentRegionAvail_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetContentRegionMax_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetCurrentContext() callconv(.C) ?*Context; pub extern fn igGetCursorPos_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetCursorPosX() callconv(.C) f32; pub extern fn igGetCursorPosY() callconv(.C) f32; pub extern fn igGetCursorScreenPos_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetCursorStartPos_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetDragDropPayload() callconv(.C) ?*const Payload; pub extern fn igGetDrawData() callconv(.C) *DrawData; pub extern fn igGetDrawListSharedData() callconv(.C) ?*DrawListSharedData; pub extern fn igGetFont() callconv(.C) ?*Font; pub extern fn igGetFontSize() callconv(.C) f32; pub extern fn igGetFontTexUvWhitePixel_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetForegroundDrawList() callconv(.C) ?*DrawList; pub extern fn igGetFrameCount() callconv(.C) i32; pub extern fn igGetFrameHeight() callconv(.C) f32; pub extern fn igGetFrameHeightWithSpacing() callconv(.C) f32; pub extern fn igGetIDStr(str_id: ?[*:0]const u8) callconv(.C) ID; pub extern fn igGetIDRange(str_id_begin: ?[*]const u8, str_id_end: ?[*]const u8) callconv(.C) ID; pub extern fn igGetIDPtr(ptr_id: ?*const c_void) callconv(.C) ID; pub extern fn igGetIO() callconv(.C) *IO; pub extern fn igGetItemRectMax_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetItemRectMin_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetItemRectSize_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetKeyIndex(imgui_key: Key) callconv(.C) i32; pub extern fn igGetKeyPressedAmount(key_index: i32, repeat_delay: f32, rate: f32) callconv(.C) i32; pub extern fn igGetMouseCursor() callconv(.C) MouseCursor; pub extern fn igGetMouseDragDelta_nonUDT(pOut: *Vec2, button: MouseButton, lock_threshold: f32) callconv(.C) void; pub extern fn igGetMousePos_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetMousePosOnOpeningCurrentPopup_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetScrollMaxX() callconv(.C) f32; pub extern fn igGetScrollMaxY() callconv(.C) f32; pub extern fn igGetScrollX() callconv(.C) f32; pub extern fn igGetScrollY() callconv(.C) f32; pub extern fn igGetStateStorage() callconv(.C) ?*Storage; pub extern fn igGetStyle() callconv(.C) ?*Style; pub extern fn igGetStyleColorName(idx: Col) callconv(.C) ?[*:0]const u8; pub extern fn igGetStyleColorVec4(idx: Col) callconv(.C) ?*const Vec4; pub extern fn igGetTextLineHeight() callconv(.C) f32; pub extern fn igGetTextLineHeightWithSpacing() callconv(.C) f32; pub extern fn igGetTime() callconv(.C) f64; pub extern fn igGetTreeNodeToLabelSpacing() callconv(.C) f32; pub extern fn igGetVersion() callconv(.C) ?[*:0]const u8; pub extern fn igGetWindowContentRegionMax_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetWindowContentRegionMin_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetWindowContentRegionWidth() callconv(.C) f32; pub extern fn igGetWindowDrawList() callconv(.C) ?*DrawList; pub extern fn igGetWindowHeight() callconv(.C) f32; pub extern fn igGetWindowPos_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetWindowSize_nonUDT(pOut: *Vec2) callconv(.C) void; pub extern fn igGetWindowWidth() callconv(.C) f32; pub extern fn igImage(user_texture_id: TextureID, size: Vec2, uv0: Vec2, uv1: Vec2, tint_col: Vec4, border_col: Vec4) callconv(.C) void; pub extern fn igImageButton(user_texture_id: TextureID, size: Vec2, uv0: Vec2, uv1: Vec2, frame_padding: i32, bg_col: Vec4, tint_col: Vec4) callconv(.C) bool; pub extern fn igIndent(indent_w: f32) callconv(.C) void; pub extern fn igInputDouble(label: ?[*:0]const u8, v: *f64, step: f64, step_fast: f64, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputFloat(label: ?[*:0]const u8, v: *f32, step: f32, step_fast: f32, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputFloat2(label: ?[*:0]const u8, v: *[2]f32, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputFloat3(label: ?[*:0]const u8, v: *[3]f32, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputFloat4(label: ?[*:0]const u8, v: *[4]f32, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputInt(label: ?[*:0]const u8, v: *i32, step: i32, step_fast: i32, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputInt2(label: ?[*:0]const u8, v: *[2]i32, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputInt3(label: ?[*:0]const u8, v: *[3]i32, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputInt4(label: ?[*:0]const u8, v: *[4]i32, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputScalar(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, p_step: ?*const c_void, p_step_fast: ?*const c_void, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputScalarN(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, p_step: ?*const c_void, p_step_fast: ?*const c_void, format: ?[*:0]const u8, flags: InputTextFlagsInt) callconv(.C) bool; pub extern fn igInputText(label: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize, flags: InputTextFlagsInt, callback: InputTextCallback, user_data: ?*c_void) callconv(.C) bool; pub extern fn igInputTextMultiline(label: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize, size: Vec2, flags: InputTextFlagsInt, callback: InputTextCallback, user_data: ?*c_void) callconv(.C) bool; pub extern fn igInputTextWithHint(label: ?[*:0]const u8, hint: ?[*:0]const u8, buf: ?[*]u8, buf_size: usize, flags: InputTextFlagsInt, callback: InputTextCallback, user_data: ?*c_void) callconv(.C) bool; pub extern fn igInvisibleButton(str_id: ?[*:0]const u8, size: Vec2) callconv(.C) bool; pub extern fn igIsAnyItemActive() callconv(.C) bool; pub extern fn igIsAnyItemFocused() callconv(.C) bool; pub extern fn igIsAnyItemHovered() callconv(.C) bool; pub extern fn igIsAnyMouseDown() callconv(.C) bool; pub extern fn igIsItemActivated() callconv(.C) bool; pub extern fn igIsItemActive() callconv(.C) bool; pub extern fn igIsItemClicked(mouse_button: MouseButton) callconv(.C) bool; pub extern fn igIsItemDeactivated() callconv(.C) bool; pub extern fn igIsItemDeactivatedAfterEdit() callconv(.C) bool; pub extern fn igIsItemEdited() callconv(.C) bool; pub extern fn igIsItemFocused() callconv(.C) bool; pub extern fn igIsItemHovered(flags: HoveredFlagsInt) callconv(.C) bool; pub extern fn igIsItemToggledOpen() callconv(.C) bool; pub extern fn igIsItemVisible() callconv(.C) bool; pub extern fn igIsKeyDown(user_key_index: i32) callconv(.C) bool; pub extern fn igIsKeyPressed(user_key_index: i32, repeat: bool) callconv(.C) bool; pub extern fn igIsKeyReleased(user_key_index: i32) callconv(.C) bool; pub extern fn igIsMouseClicked(button: MouseButton, repeat: bool) callconv(.C) bool; pub extern fn igIsMouseDoubleClicked(button: MouseButton) callconv(.C) bool; pub extern fn igIsMouseDown(button: MouseButton) callconv(.C) bool; pub extern fn igIsMouseDragging(button: MouseButton, lock_threshold: f32) callconv(.C) bool; pub extern fn igIsMouseHoveringRect(r_min: Vec2, r_max: Vec2, clip: bool) callconv(.C) bool; pub extern fn igIsMousePosValid(mouse_pos: ?*const Vec2) callconv(.C) bool; pub extern fn igIsMouseReleased(button: MouseButton) callconv(.C) bool; pub extern fn igIsPopupOpen(str_id: ?[*:0]const u8) callconv(.C) bool; pub extern fn igIsRectVisible(size: Vec2) callconv(.C) bool; pub extern fn igIsRectVisibleVec2(rect_min: Vec2, rect_max: Vec2) callconv(.C) bool; pub extern fn igIsWindowAppearing() callconv(.C) bool; pub extern fn igIsWindowCollapsed() callconv(.C) bool; pub extern fn igIsWindowFocused(flags: FocusedFlagsInt) callconv(.C) bool; pub extern fn igIsWindowHovered(flags: HoveredFlagsInt) callconv(.C) bool; pub extern fn igLabelText(label: ?[*:0]const u8, fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igListBoxStr_arr(label: ?[*:0]const u8, current_item: ?*i32, items: [*]const[*:0]const u8, items_count: i32, height_in_items: i32) callconv(.C) bool; pub extern fn igListBoxFnPtr(label: ?[*:0]const u8, current_item: ?*i32, items_getter: ?fn (data: ?*c_void, idx: i32, out_text: *?[*:0]const u8) callconv(.C) bool, data: ?*c_void, items_count: i32, height_in_items: i32) callconv(.C) bool; pub extern fn igListBoxFooter() callconv(.C) void; pub extern fn igListBoxHeaderVec2(label: ?[*:0]const u8, size: Vec2) callconv(.C) bool; pub extern fn igListBoxHeaderInt(label: ?[*:0]const u8, items_count: i32, height_in_items: i32) callconv(.C) bool; pub extern fn igLoadIniSettingsFromDisk(ini_filename: ?[*:0]const u8) callconv(.C) void; pub extern fn igLoadIniSettingsFromMemory(ini_data: ?[*]const u8, ini_size: usize) callconv(.C) void; pub extern fn igLogButtons() callconv(.C) void; pub extern fn igLogFinish() callconv(.C) void; pub extern fn igLogText(fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igLogToClipboard(auto_open_depth: i32) callconv(.C) void; pub extern fn igLogToFile(auto_open_depth: i32, filename: ?[*:0]const u8) callconv(.C) void; pub extern fn igLogToTTY(auto_open_depth: i32) callconv(.C) void; pub extern fn igMemAlloc(size: usize) callconv(.C) ?*c_void; pub extern fn igMemFree(ptr: ?*c_void) callconv(.C) void; pub extern fn igMenuItemBool(label: ?[*:0]const u8, shortcut: ?[*:0]const u8, selected: bool, enabled: bool) callconv(.C) bool; pub extern fn igMenuItemBoolPtr(label: ?[*:0]const u8, shortcut: ?[*:0]const u8, p_selected: ?*bool, enabled: bool) callconv(.C) bool; pub extern fn igNewFrame() callconv(.C) void; pub extern fn igNewLine() callconv(.C) void; pub extern fn igNextColumn() callconv(.C) void; pub extern fn igOpenPopup(str_id: ?[*:0]const u8) callconv(.C) void; pub extern fn igOpenPopupOnItemClick(str_id: ?[*:0]const u8, mouse_button: MouseButton) callconv(.C) bool; pub extern fn igPlotHistogramFloatPtr(label: ?[*:0]const u8, values: *const f32, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2, stride: i32) callconv(.C) void; pub extern fn igPlotHistogramFnPtr(label: ?[*:0]const u8, values_getter: ?fn (data: ?*c_void, idx: i32) callconv(.C) f32, data: ?*c_void, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2) callconv(.C) void; pub extern fn igPlotLines(label: ?[*:0]const u8, values: *const f32, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2, stride: i32) callconv(.C) void; pub extern fn igPlotLinesFnPtr(label: ?[*:0]const u8, values_getter: ?fn (data: ?*c_void, idx: i32) callconv(.C) f32, data: ?*c_void, values_count: i32, values_offset: i32, overlay_text: ?[*:0]const u8, scale_min: f32, scale_max: f32, graph_size: Vec2) callconv(.C) void; pub extern fn igPopAllowKeyboardFocus() callconv(.C) void; pub extern fn igPopButtonRepeat() callconv(.C) void; pub extern fn igPopClipRect() callconv(.C) void; pub extern fn igPopFont() callconv(.C) void; pub extern fn igPopID() callconv(.C) void; pub extern fn igPopItemWidth() callconv(.C) void; pub extern fn igPopStyleColor(count: i32) callconv(.C) void; pub extern fn igPopStyleVar(count: i32) callconv(.C) void; pub extern fn igPopTextWrapPos() callconv(.C) void; pub extern fn igProgressBar(fraction: f32, size_arg: Vec2, overlay: ?[*:0]const u8) callconv(.C) void; pub extern fn igPushAllowKeyboardFocus(allow_keyboard_focus: bool) callconv(.C) void; pub extern fn igPushButtonRepeat(repeat: bool) callconv(.C) void; pub extern fn igPushClipRect(clip_rect_min: Vec2, clip_rect_max: Vec2, intersect_with_current_clip_rect: bool) callconv(.C) void; pub extern fn igPushFont(font: ?*Font) callconv(.C) void; pub extern fn igPushIDStr(str_id: ?[*:0]const u8) callconv(.C) void; pub extern fn igPushIDRange(str_id_begin: ?[*]const u8, str_id_end: ?[*]const u8) callconv(.C) void; pub extern fn igPushIDPtr(ptr_id: ?*const c_void) callconv(.C) void; pub extern fn igPushIDInt(int_id: i32) callconv(.C) void; pub extern fn igPushItemWidth(item_width: f32) callconv(.C) void; pub extern fn igPushStyleColorU32(idx: Col, col: u32) callconv(.C) void; pub extern fn igPushStyleColorVec4(idx: Col, col: Vec4) callconv(.C) void; pub extern fn igPushStyleVarFloat(idx: StyleVar, val: f32) callconv(.C) void; pub extern fn igPushStyleVarVec2(idx: StyleVar, val: Vec2) callconv(.C) void; pub extern fn igPushTextWrapPos(wrap_local_pos_x: f32) callconv(.C) void; pub extern fn igRadioButtonBool(label: ?[*:0]const u8, active: bool) callconv(.C) bool; pub extern fn igRadioButtonIntPtr(label: ?[*:0]const u8, v: *i32, v_button: i32) callconv(.C) bool; pub extern fn igRender() callconv(.C) void; pub extern fn igResetMouseDragDelta(button: MouseButton) callconv(.C) void; pub extern fn igSameLine(offset_from_start_x: f32, spacing: f32) callconv(.C) void; pub extern fn igSaveIniSettingsToDisk(ini_filename: ?[*:0]const u8) callconv(.C) void; pub extern fn igSaveIniSettingsToMemory(out_ini_size: ?*usize) callconv(.C) ?[*:0]const u8; pub extern fn igSelectableBool(label: ?[*:0]const u8, selected: bool, flags: SelectableFlagsInt, size: Vec2) callconv(.C) bool; pub extern fn igSelectableBoolPtr(label: ?[*:0]const u8, p_selected: ?*bool, flags: SelectableFlagsInt, size: Vec2) callconv(.C) bool; pub extern fn igSeparator() callconv(.C) void; pub extern fn igSetAllocatorFunctions(alloc_func: ?fn (sz: usize, user_data: ?*c_void) callconv(.C) ?*c_void, free_func: ?fn (ptr: ?*c_void, user_data: ?*c_void) callconv(.C) void, user_data: ?*c_void) callconv(.C) void; pub extern fn igSetClipboardText(text: ?[*:0]const u8) callconv(.C) void; pub extern fn igSetColorEditOptions(flags: ColorEditFlagsInt) callconv(.C) void; pub extern fn igSetColumnOffset(column_index: i32, offset_x: f32) callconv(.C) void; pub extern fn igSetColumnWidth(column_index: i32, width: f32) callconv(.C) void; pub extern fn igSetCurrentContext(ctx: ?*Context) callconv(.C) void; pub extern fn igSetCursorPos(local_pos: Vec2) callconv(.C) void; pub extern fn igSetCursorPosX(local_x: f32) callconv(.C) void; pub extern fn igSetCursorPosY(local_y: f32) callconv(.C) void; pub extern fn igSetCursorScreenPos(pos: Vec2) callconv(.C) void; pub extern fn igSetDragDropPayload(kind: ?[*:0]const u8, data: ?*const c_void, sz: usize, cond: CondFlagsInt) callconv(.C) bool; pub extern fn igSetItemAllowOverlap() callconv(.C) void; pub extern fn igSetItemDefaultFocus() callconv(.C) void; pub extern fn igSetKeyboardFocusHere(offset: i32) callconv(.C) void; pub extern fn igSetMouseCursor(cursor_type: MouseCursor) callconv(.C) void; pub extern fn igSetNextItemOpen(is_open: bool, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetNextItemWidth(item_width: f32) callconv(.C) void; pub extern fn igSetNextWindowBgAlpha(alpha: f32) callconv(.C) void; pub extern fn igSetNextWindowCollapsed(collapsed: bool, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetNextWindowContentSize(size: Vec2) callconv(.C) void; pub extern fn igSetNextWindowFocus() callconv(.C) void; pub extern fn igSetNextWindowPos(pos: Vec2, cond: CondFlagsInt, pivot: Vec2) callconv(.C) void; pub extern fn igSetNextWindowSize(size: Vec2, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetNextWindowSizeConstraints(size_min: Vec2, size_max: Vec2, custom_callback: SizeCallback, custom_callback_data: ?*c_void) callconv(.C) void; pub extern fn igSetScrollFromPosX(local_x: f32, center_x_ratio: f32) callconv(.C) void; pub extern fn igSetScrollFromPosY(local_y: f32, center_y_ratio: f32) callconv(.C) void; pub extern fn igSetScrollHereX(center_x_ratio: f32) callconv(.C) void; pub extern fn igSetScrollHereY(center_y_ratio: f32) callconv(.C) void; pub extern fn igSetScrollX(scroll_x: f32) callconv(.C) void; pub extern fn igSetScrollY(scroll_y: f32) callconv(.C) void; pub extern fn igSetStateStorage(storage: ?*Storage) callconv(.C) void; pub extern fn igSetTabItemClosed(tab_or_docked_window_label: ?[*:0]const u8) callconv(.C) void; pub extern fn igSetTooltip(fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igSetWindowCollapsedBool(collapsed: bool, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetWindowCollapsedStr(name: ?[*:0]const u8, collapsed: bool, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetWindowFocus() callconv(.C) void; pub extern fn igSetWindowFocusStr(name: ?[*:0]const u8) callconv(.C) void; pub extern fn igSetWindowFontScale(scale: f32) callconv(.C) void; pub extern fn igSetWindowPosVec2(pos: Vec2, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetWindowPosStr(name: ?[*:0]const u8, pos: Vec2, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetWindowSizeVec2(size: Vec2, cond: CondFlagsInt) callconv(.C) void; pub extern fn igSetWindowSizeStr(name: ?[*:0]const u8, size: Vec2, cond: CondFlagsInt) callconv(.C) void; pub extern fn igShowAboutWindow(p_open: ?*bool) callconv(.C) void; pub extern fn igShowDemoWindow(p_open: ?*bool) callconv(.C) void; pub extern fn igShowFontSelector(label: ?[*:0]const u8) callconv(.C) void; pub extern fn igShowMetricsWindow(p_open: ?*bool) callconv(.C) void; pub extern fn igShowStyleEditor(ref: ?*Style) callconv(.C) void; pub extern fn igShowStyleSelector(label: ?[*:0]const u8) callconv(.C) bool; pub extern fn igShowUserGuide() callconv(.C) void; pub extern fn igSliderAngle(label: ?[*:0]const u8, v_rad: *f32, v_degrees_min: f32, v_degrees_max: f32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igSliderFloat(label: ?[*:0]const u8, v: *f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igSliderFloat2(label: ?[*:0]const u8, v: *[2]f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igSliderFloat3(label: ?[*:0]const u8, v: *[3]f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igSliderFloat4(label: ?[*:0]const u8, v: *[4]f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igSliderInt(label: ?[*:0]const u8, v: *i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igSliderInt2(label: ?[*:0]const u8, v: *[2]i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igSliderInt3(label: ?[*:0]const u8, v: *[3]i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igSliderInt4(label: ?[*:0]const u8, v: *[4]i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igSliderScalar(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igSliderScalarN(label: ?[*:0]const u8, data_type: DataType, p_data: ?*c_void, components: i32, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igSmallButton(label: ?[*:0]const u8) callconv(.C) bool; pub extern fn igSpacing() callconv(.C) void; pub extern fn igStyleColorsClassic(dst: ?*Style) callconv(.C) void; pub extern fn igStyleColorsDark(dst: ?*Style) callconv(.C) void; pub extern fn igStyleColorsLight(dst: ?*Style) callconv(.C) void; pub extern fn igText(fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igTextColored(col: Vec4, fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igTextDisabled(fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igTextUnformatted(text: ?[*]const u8, text_end: ?[*]const u8) callconv(.C) void; pub extern fn igTextWrapped(fmt: ?[*:0]const u8, ...) callconv(.C) void; pub extern fn igTreeNodeStr(label: ?[*:0]const u8) callconv(.C) bool; pub extern fn igTreeNodeStrStr(str_id: ?[*:0]const u8, fmt: ?[*:0]const u8, ...) callconv(.C) bool; pub extern fn igTreeNodePtr(ptr_id: ?*const c_void, fmt: ?[*:0]const u8, ...) callconv(.C) bool; pub extern fn igTreeNodeExStr(label: ?[*:0]const u8, flags: TreeNodeFlagsInt) callconv(.C) bool; pub extern fn igTreeNodeExStrStr(str_id: ?[*:0]const u8, flags: TreeNodeFlagsInt, fmt: ?[*:0]const u8, ...) callconv(.C) bool; pub extern fn igTreeNodeExPtr(ptr_id: ?*const c_void, flags: TreeNodeFlagsInt, fmt: ?[*:0]const u8, ...) callconv(.C) bool; pub extern fn igTreePop() callconv(.C) void; pub extern fn igTreePushStr(str_id: ?[*:0]const u8) callconv(.C) void; pub extern fn igTreePushPtr(ptr_id: ?*const c_void) callconv(.C) void; pub extern fn igUnindent(indent_w: f32) callconv(.C) void; pub extern fn igVSliderFloat(label: ?[*:0]const u8, size: Vec2, v: *f32, v_min: f32, v_max: f32, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igVSliderInt(label: ?[*:0]const u8, size: Vec2, v: *i32, v_min: i32, v_max: i32, format: ?[*:0]const u8) callconv(.C) bool; pub extern fn igVSliderScalar(label: ?[*:0]const u8, size: Vec2, data_type: DataType, p_data: ?*c_void, p_min: ?*const c_void, p_max: ?*const c_void, format: ?[*:0]const u8, power: f32) callconv(.C) bool; pub extern fn igValueBool(prefix: ?[*:0]const u8, b: bool) callconv(.C) void; pub extern fn igValueInt(prefix: ?[*:0]const u8, v: i32) callconv(.C) void; pub extern fn igValueUint(prefix: ?[*:0]const u8, v: u32) callconv(.C) void; pub extern fn igValueFloat(prefix: ?[*:0]const u8, v: f32, float_format: ?[*:0]const u8) callconv(.C) void; };
https://raw.githubusercontent.com/digitalcreature/ube/c5e5c9f4b54f1981ead8337faf4513c83b92fc01/src/imgui/imgui.zig
usingnamespace @import("./common.zig"); const Input = struct { time: u64, ids: []const u64, }; pub fn cleanInput(allocator: *mem.Allocator, file: []const u8) !*Input { var input = try allocator.create(Input); var lines = mem.tokenize(file, "\n"); input.time = try parseInt(u64, lines.next().?, 10); var ids_str = lines.next().?; var count: usize = 0; var entries = mem.tokenize(ids_str, ","); while (entries.next()) |entry| count += 1; var ids = try allocator.alloc(u64, count); entries = mem.tokenize(ids_str, ","); var i: usize = 0; while (entries.next()) |bus| { ids[i] = parseInt(u64, bus, 10) catch 0; i += 1; } input.ids = ids; return input; } const test_input = \\939 \\7,13,x,x,59,x,31,19 ; test "cleanInput" { var input = try cleanInput(testing.allocator, test_input); defer testing.allocator.free(input.ids); defer testing.allocator.destroy(input); testing.expectEqual(@intCast(u64, 939), input.time); testing.expectEqualSlices(u64, &[_]u64{ 7, 13, 0, 0, 59, 0, 31, 19 }, input.ids); } fn timeUntilDeparture(id: u64, time: u64) u64 { return id - @mod(time, id); } pub fn part1(input: Input) !u64 { var min: u64 = input.ids[0]; for (input.ids) |bus| { if (bus == 0) continue; const next_bus = timeUntilDeparture(bus, input.time); const next_min = timeUntilDeparture(min, input.time); if (next_bus < next_min) min = bus; } return min * timeUntilDeparture(min, input.time); } test "part1" { const input = try cleanInput(testing.allocator, test_input); defer testing.allocator.free(input.ids); defer testing.allocator.destroy(input); testing.expectEqual(@intCast(u64, 295), try part1(input.*)); } pub fn part2(allocator: *mem.Allocator, input: Input) !u64 { var remainders = try allocator.alloc(u64, input.ids.len); defer allocator.free(remainders); for (input.ids) |id, i| { if (id == 0) continue; remainders[i] = @intCast(u64, @mod(@intCast(i64, id) - @intCast(i64, i), @intCast(i64, id))); } var time: u64 = 0; var step: u64 = 1; for (input.ids) |id, i| { if (id == 0) continue; while (@mod(time, id) != remainders[i]) time += step; step *= id; } return time; } test "part2" { var input = try cleanInput(testing.allocator, test_input); testing.expectEqual(@intCast(u64, 1068781), try part2(testing.allocator, input.*)); testing.allocator.free(input.ids); testing.allocator.destroy(input); input = try cleanInput(testing.allocator, \\0 \\17,x,13,19 ); testing.expectEqual(@intCast(u64, 3417), try part2(testing.allocator, input.*)); testing.allocator.free(input.ids); testing.allocator.destroy(input); input = try cleanInput(testing.allocator, \\0 \\67,7,59,61 ); testing.expectEqual(@intCast(u64, 754018), try part2(testing.allocator, input.*)); testing.allocator.free(input.ids); testing.allocator.destroy(input); input = try cleanInput(testing.allocator, \\0 \\67,x,7,59,61 ); testing.expectEqual(@intCast(u64, 779210), try part2(testing.allocator, input.*)); testing.allocator.free(input.ids); testing.allocator.destroy(input); input = try cleanInput(testing.allocator, \\0 \\67,7,x,59,61 ); testing.expectEqual(@intCast(u64, 1261476), try part2(testing.allocator, input.*)); testing.allocator.free(input.ids); testing.allocator.destroy(input); input = try cleanInput(testing.allocator, \\0 \\1789,37,47,1889 ); testing.expectEqual(@intCast(u64, 1202161486), try part2(testing.allocator, input.*)); testing.allocator.free(input.ids); testing.allocator.destroy(input); } pub fn main() !void { const file = try common.readFile(alloc, "inputs/day13.txt"); defer alloc.free(file); const input = try cleanInput(alloc, file); defer alloc.destroy(input); warn("part1: {}\n", .{try part1(input.*)}); warn("part2: {}\n", .{try part2(alloc, input.*)}); }
https://raw.githubusercontent.com/meatcar/adventofcode/0639eac0a8f191db2bd745942b208658b73a469b/2020/days/day13.zig
const std = @import("std"); pub inline fn fromMegabytes(mb: f64) f64 { return mb * 1024 * 1024; } pub inline fn toMegabytes(bytes: f64) f64 { return bytes / 1024 / 1024; }
https://raw.githubusercontent.com/Wraith29/zvm/9046774d8f34df89214db780cc877f4384ee4d54/src/size.zig
const std = @import("std"); const imgui_app = @import("./imgui_app.zig"); const fbo_dock = @import("./fbo_dock.zig"); const dockspace = @import("./dockspace.zig"); pub const ImGuiApp = imgui_app.ImGuiApp; pub const FboDock = fbo_dock.FboDock; pub const MouseInput = fbo_dock.MouseInput; pub const Dock = dockspace.Dock; pub fn localFormat(comptime fmt: []const u8, values: anytype) [*:0]const u8 { const S = struct { var buf: [8192]u8 = undefined; }; const label = std.fmt.bufPrint(&S.buf, fmt, values) catch unreachable; S.buf[label.len] = 0; return @ptrCast([*:0]const u8, &S.buf[0]); }
https://raw.githubusercontent.com/ousttrue/zigcell/5675ff842ac6cee1868f5c66fd9a70fb60a1b7e7/pkgs/imutil/src/main.zig
// Copyright (C) 2024 Robert A. Wallis, all rights reserved. const std = @import("std"); pub fn extension(filename: []const u8) ?[]const u8 { if (std.mem.lastIndexOf(u8, filename, ".")) |pos| { return filename[pos..]; } return null; } test extension { try std.testing.expectEqualStrings(".jpg", extension("success-kid.jpg").?); try std.testing.expectEqualStrings(".DS_Store", extension(".DS_Store").?); try std.testing.expectEqualStrings("none", extension("LICENSE") orelse "none"); const oprah_bees = "oprah-bees.gif".*; const fellow_kids = "fellow-kids.gif".*; const oprah_bees_ext = extension(&oprah_bees).?; const fellow_kids_ext = extension(&fellow_kids).?; try std.testing.expectEqualStrings(oprah_bees_ext, fellow_kids_ext); const hashString = std.hash_map.hashString; try std.testing.expectEqual(hashString(oprah_bees_ext), hashString(fellow_kids_ext)); }
https://raw.githubusercontent.com/robert-wallis/dirstat/4ca0e171459dc19f6790a3e71beb4819ccb3bb51/src/string.zig
const std = @import("std"); const registry = @import("registry.zig"); const xml = @import("../xml.zig"); const cparse = @import("c-parse.zig"); const mem = std.mem; const Allocator = mem.Allocator; const ArenaAllocator = std.heap.ArenaAllocator; const api_constants_name = "API Constants"; pub const ParseResult = struct { arena: ArenaAllocator, registry: registry.Registry, pub fn deinit(self: ParseResult) void { self.arena.deinit(); } }; pub fn parseXml(backing_allocator: *Allocator, root: *xml.Element) !ParseResult { var arena = ArenaAllocator.init(backing_allocator); errdefer arena.deinit(); const allocator = &arena.allocator; var reg = registry.Registry{ .copyright = root.getCharData("comment") orelse return error.InvalidRegistry, .decls = try parseDeclarations(allocator, root), .api_constants = try parseApiConstants(allocator, root), .tags = try parseTags(allocator, root), .features = try parseFeatures(allocator, root), .extensions = try parseExtensions(allocator, root), }; return ParseResult{ .arena = arena, .registry = reg, }; } fn parseDeclarations(allocator: *Allocator, root: *xml.Element) ![]registry.Declaration { var types_elem = root.findChildByTag("types") orelse return error.InvalidRegistry; var commands_elem = root.findChildByTag("commands") orelse return error.InvalidRegistry; const decl_upper_bound = types_elem.children.count() + commands_elem.children.count(); const decls = try allocator.alloc(registry.Declaration, decl_upper_bound); var count: usize = 0; count += try parseTypes(allocator, decls, types_elem); count += try parseEnums(allocator, decls[count..], root); count += try parseCommands(allocator, decls[count..], commands_elem); return allocator.shrink(decls, count); } fn parseTypes(allocator: *Allocator, out: []registry.Declaration, types_elem: *xml.Element) !usize { var i: usize = 0; var it = types_elem.findChildrenByTag("type"); while (it.next()) |ty| { out[i] = blk: { const category = ty.getAttribute("category") orelse { break :blk try parseForeigntype(ty); }; if (mem.eql(u8, category, "bitmask")) { break :blk try parseBitmaskType(ty); } else if (mem.eql(u8, category, "handle")) { break :blk try parseHandleType(ty); } else if (mem.eql(u8, category, "basetype")) { break :blk try parseBaseType(allocator, ty); } else if (mem.eql(u8, category, "struct")) { break :blk try parseContainer(allocator, ty, false); } else if (mem.eql(u8, category, "union")) { break :blk try parseContainer(allocator, ty, true); } else if (mem.eql(u8, category, "funcpointer")) { break :blk try parseFuncPointer(allocator, ty); } else if (mem.eql(u8, category, "enum")) { break :blk (try parseEnumAlias(allocator, ty)) orelse continue; } continue; }; i += 1; } return i; } fn parseForeigntype(ty: *xml.Element) !registry.Declaration { const name = ty.getAttribute("name") orelse return error.InvalidRegistry; const depends = ty.getAttribute("requires") orelse if (mem.eql(u8, name, "int")) "vk_platform" // for some reason, int doesn't depend on vk_platform (but the other c types do) else return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{.foreign = .{.depends = depends}}, }; } fn parseBitmaskType(ty: *xml.Element) !registry.Declaration { if (ty.getAttribute("name")) |name| { const alias = ty.getAttribute("alias") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{.alias = .{.name = alias, .target = .other_type}}, }; } else { return registry.Declaration{ .name = ty.getCharData("name") orelse return error.InvalidRegistry, .decl_type = .{.bitmask = .{.bits_enum = ty.getAttribute("requires")}}, }; } } fn parseHandleType(ty: *xml.Element) !registry.Declaration { // Parent is not handled in case of an alias if (ty.getAttribute("name")) |name| { const alias = ty.getAttribute("alias") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{.alias = .{.name = alias, .target = .other_type}}, }; } else { const name = ty.getCharData("name") orelse return error.InvalidRegistry; const handle_type = ty.getCharData("type") orelse return error.InvalidRegistry; const dispatchable = mem.eql(u8, handle_type, "VK_DEFINE_HANDLE"); if (!dispatchable and !mem.eql(u8, handle_type, "VK_DEFINE_NON_DISPATCHABLE_HANDLE")) { return error.InvalidRegistry; } return registry.Declaration{ .name = name, .decl_type = .{ .handle = .{ .parent = ty.getAttribute("parent"), .is_dispatchable = dispatchable, } }, }; } } fn parseBaseType(allocator: *Allocator, ty: *xml.Element) !registry.Declaration { const name = ty.getCharData("name") orelse return error.InvalidRegistry; if (ty.getCharData("type")) |_| { var tok = cparse.XmlCTokenizer.init(ty); return try cparse.parseTypedef(allocator, &tok); } else { // Either ANativeWindow, AHardwareBuffer or CAMetalLayer. The latter has a lot of // macros, which is why this part is not built into the xml/c parser. return registry.Declaration{ .name = name, .decl_type = .{.opaque = {}}, }; } } fn parseContainer(allocator: *Allocator, ty: *xml.Element, is_union: bool) !registry.Declaration { const name = ty.getAttribute("name") orelse return error.InvalidRegistry; if (ty.getAttribute("alias")) |alias| { return registry.Declaration{ .name = name, .decl_type = .{.alias = .{.name = alias, .target = .other_type}}, }; } var members = try allocator.alloc(registry.Container.Field, ty.children.count()); var i: usize = 0; var it = ty.findChildrenByTag("member"); while (it.next()) |member| { var xctok = cparse.XmlCTokenizer.init(member); members[i] = try cparse.parseMember(allocator, &xctok); i += 1; } members = allocator.shrink(members, i); it = ty.findChildrenByTag("member"); for (members) |*member| { const member_elem = it.next().?; try parsePointerMeta(.{.container = members}, &member.field_type, member_elem); // pNext isn't properly marked as optional, so just manually override it, if (mem.eql(u8, member.name, "pNext")) { member.field_type.pointer.is_optional = true; } } return registry.Declaration { .name = name, .decl_type = .{ .container = .{ .fields = members, .is_union = is_union, } } }; } fn parseFuncPointer(allocator: *Allocator, ty: *xml.Element) !registry.Declaration { var xctok = cparse.XmlCTokenizer.init(ty); return try cparse.parseTypedef(allocator, &xctok); } // For some reason, the DeclarationType cannot be passed to lenToPointerSize, as // that causes the Zig compiler to generate invalid code for the function. Using a // dedicated enum fixes the issue... const Fields = union(enum) { command: []registry.Command.Param, container: []registry.Container.Field, }; fn lenToPointerSize(fields: Fields, len: []const u8) registry.Pointer.PointerSize { switch (fields) { .command => |params| { for (params) |*param| { if (mem.eql(u8, param.name, len)) { param.is_buffer_len = true; return .{.other_field = param.name}; } } }, .container => |members| { for (members) |*member| { if (mem.eql(u8, member.name, len)) { member.is_buffer_len = true; return .{.other_field = member.name}; } } }, } if (mem.eql(u8, len, "null-terminated")) { return .zero_terminated; } else { return .many; } } fn parsePointerMeta(fields: Fields, type_info: *registry.TypeInfo, elem: *xml.Element) !void { if (elem.getAttribute("len")) |lens| { var it = mem.split(lens, ","); var current_type_info = type_info; while (current_type_info.* == .pointer) { // TODO: Check altlen const size = if (it.next()) |len_str| lenToPointerSize(fields, len_str) else .one; current_type_info.pointer.size = size; current_type_info = current_type_info.pointer.child; } if (it.next()) |_| { // There are more elements in the `len` attribute than there are pointers // Something probably went wrong return error.InvalidRegistry; } } if (elem.getAttribute("optional")) |optionals| { var it = mem.split(optionals, ","); var current_type_info = type_info; while (current_type_info.* == .pointer) { if (it.next()) |current_optional| { current_type_info.pointer.is_optional = mem.eql(u8, current_optional, "true"); } else { // There is no information for this pointer, probably incorrect. return error.InvalidRegistry; } current_type_info = current_type_info.pointer.child; } } } fn parseEnumAlias(allocator: *Allocator, elem: *xml.Element) !?registry.Declaration { if (elem.getAttribute("alias")) |alias| { const name = elem.getAttribute("name") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{.alias = .{.name = alias, .target = .other_type}}, }; } return null; } fn parseEnums(allocator: *Allocator, out: []registry.Declaration, root: *xml.Element) !usize { var i: usize = 0; var it = root.findChildrenByTag("enums"); while (it.next()) |enums| { const name = enums.getAttribute("name") orelse return error.InvalidRegistry; if (mem.eql(u8, name, api_constants_name)) { continue; } out[i] = .{ .name = name, .decl_type = .{.enumeration = try parseEnumFields(allocator, enums)}, }; i += 1; } return i; } fn parseEnumFields(allocator: *Allocator, elem: *xml.Element) !registry.Enum { // TODO: `type` was added recently, fall back to checking endswith FlagBits for older versions? const enum_type = elem.getAttribute("type") orelse return error.InvalidRegistry; const is_bitmask = mem.eql(u8, enum_type, "bitmask"); if (!is_bitmask and !mem.eql(u8, enum_type, "enum")) { return error.InvalidRegistry; } const fields = try allocator.alloc(registry.Enum.Field, elem.children.count()); var i: usize = 0; var it = elem.findChildrenByTag("enum"); while (it.next()) |field| { fields[i] = try parseEnumField(field); i += 1; } return registry.Enum{ .fields = allocator.shrink(fields, i), .is_bitmask = is_bitmask, }; } fn parseEnumField(field: *xml.Element) !registry.Enum.Field { const is_compat_alias = if (field.getAttribute("comment")) |comment| mem.eql(u8, comment, "Backwards-compatible alias containing a typo") or mem.eql(u8, comment, "Deprecated name for backwards compatibility") else false; const name = field.getAttribute("name") orelse return error.InvalidRegistry; const value: registry.Enum.Value = blk: { // An enum variant's value could be defined by any of the following attributes: // - value: Straight up value of the enum variant, in either base 10 or 16 (prefixed with 0x). // - bitpos: Used for bitmasks, and can also be set in extensions. // - alias: The field is an alias of another variant within the same enum. // - offset: Used with features and extensions, where a non-bitpos value is added to an enum. // The value is given by `1e9 + (extr_nr - 1) * 1e3 + offset`, where `ext_nr` is either // given by the `extnumber` field (in the case of a feature), or given in the parent <extension> // tag. In the latter case its passed via the `ext_nr` parameter. if (field.getAttribute("value")) |value| { if (mem.startsWith(u8, value, "0x")) { break :blk .{.bit_vector = try std.fmt.parseInt(i32, value[2..], 16)}; } else { break :blk .{.int = try std.fmt.parseInt(i32, value, 10)}; } } else if (field.getAttribute("bitpos")) |bitpos| { break :blk .{.bitpos = try std.fmt.parseInt(u5, bitpos, 10)}; } else if (field.getAttribute("alias")) |alias| { break :blk .{.alias = .{.name = alias, .is_compat_alias = is_compat_alias}}; } else { return error.InvalidRegistry; } }; return registry.Enum.Field{ .name = name, .value = value, }; } fn parseCommands(allocator: *Allocator, out: []registry.Declaration, commands_elem: *xml.Element) !usize { var i: usize = 0; var it = commands_elem.findChildrenByTag("command"); while (it.next()) |elem| { out[i] = try parseCommand(allocator, elem); i += 1; } return i; } fn splitCommaAlloc(allocator: *Allocator, text: []const u8) ![][]const u8 { var n_codes: usize = 1; for (text) |c| { if (c == ',') n_codes += 1; } const codes = try allocator.alloc([]const u8, n_codes); var it = mem.split(text, ","); for (codes) |*code| { code.* = it.next().?; } return codes; } fn parseCommand(allocator: *Allocator, elem: *xml.Element) !registry.Declaration { if (elem.getAttribute("alias")) |alias| { const name = elem.getAttribute("name") orelse return error.InvalidRegistry; return registry.Declaration{ .name = name, .decl_type = .{.alias = .{.name = alias, .target = .other_command}} }; } const proto = elem.findChildByTag("proto") orelse return error.InvalidRegistry; var proto_xctok = cparse.XmlCTokenizer.init(proto); const command_decl = try cparse.parseParamOrProto(allocator, &proto_xctok); var params = try allocator.alloc(registry.Command.Param, elem.children.count()); var i: usize = 0; var it = elem.findChildrenByTag("param"); while (it.next()) |param| { var xctok = cparse.XmlCTokenizer.init(param); const decl = try cparse.parseParamOrProto(allocator, &xctok); params[i] = .{ .name = decl.name, .param_type = decl.decl_type.typedef, .is_buffer_len = false, }; i += 1; } const return_type = try allocator.create(registry.TypeInfo); return_type.* = command_decl.decl_type.typedef; const success_codes = if (elem.getAttribute("successcodes")) |codes| try splitCommaAlloc(allocator, codes) else &[_][]const u8{}; const error_codes = if (elem.getAttribute("errorcodes")) |codes| try splitCommaAlloc(allocator, codes) else &[_][]const u8{}; params = allocator.shrink(params, i); it = elem.findChildrenByTag("param"); for (params) |*param| { const param_elem = it.next().?; try parsePointerMeta(.{.command = params}, &param.param_type, param_elem); } return registry.Declaration { .name = command_decl.name, .decl_type = .{ .command = .{ .params = params, .return_type = return_type, .success_codes = success_codes, .error_codes = error_codes, } } }; } fn parseApiConstants(allocator: *Allocator, root: *xml.Element) ![]registry.ApiConstant { var enums = blk: { var it = root.findChildrenByTag("enums"); while (it.next()) |child| { const name = child.getAttribute("name") orelse continue; if (mem.eql(u8, name, api_constants_name)) { break :blk child; } } return error.InvalidRegistry; }; var types = root.findChildByTag("types") orelse return error.InvalidRegistry; const n_defines = blk: { var n_defines: usize = 0; var it = types.findChildrenByTag("type"); while (it.next()) |ty| { if (ty.getAttribute("category")) |category| { if (mem.eql(u8, category, "define")) { n_defines += 1; } } } break :blk n_defines; }; const constants = try allocator.alloc(registry.ApiConstant, enums.children.count() + n_defines); var i: usize = 0; var it = enums.findChildrenByTag("enum"); while (it.next()) |constant| { const expr = if (constant.getAttribute("value")) |expr| expr else if (constant.getAttribute("alias")) |alias| alias else return error.InvalidRegistry; constants[i] = .{ .name = constant.getAttribute("name") orelse return error.InvalidRegistry, .value = .{.expr = expr}, }; i += 1; } i += try parseDefines(types, constants[i..]); return allocator.shrink(constants, i); } fn parseDefines(types: *xml.Element, out: []registry.ApiConstant) !usize { var i: usize = 0; var it = types.findChildrenByTag("type"); while (it.next()) |ty| { const category = ty.getAttribute("category") orelse continue; if (!mem.eql(u8, category, "define")) { continue; } const name = ty.getCharData("name") orelse continue; if (mem.eql(u8, name, "VK_HEADER_VERSION")) { out[i] = .{ .name = name, .value = .{.expr = mem.trim(u8, ty.children.at(2).CharData, " ")}, }; } else { var xctok = cparse.XmlCTokenizer.init(ty); out[i] = .{ .name = name, .value = .{ .version = cparse.parseVersion(&xctok) catch continue }, }; } i += 1; } return i; } fn parseTags(allocator: *Allocator, root: *xml.Element) ![]registry.Tag { var tags_elem = root.findChildByTag("tags") orelse return error.InvalidRegistry; const tags = try allocator.alloc(registry.Tag, tags_elem.children.count()); var i: usize = 0; var it = tags_elem.findChildrenByTag("tag"); while (it.next()) |tag| { tags[i] = .{ .name = tag.getAttribute("name") orelse return error.InvalidRegistry, .author = tag.getAttribute("author") orelse return error.InvalidRegistry, }; i += 1; } return allocator.shrink(tags, i); } fn parseFeatures(allocator: *Allocator, root: *xml.Element) ![]registry.Feature { var it = root.findChildrenByTag("feature"); var count: usize = 0; while (it.next()) |_| count += 1; const features = try allocator.alloc(registry.Feature, count); var i: usize = 0; it = root.findChildrenByTag("feature"); while (it.next()) |feature| { features[i] = try parseFeature(allocator, feature); i += 1; } return features; } fn parseFeature(allocator: *Allocator, feature: *xml.Element) !registry.Feature { const name = feature.getAttribute("name") orelse return error.InvalidRegistry; const feature_level = blk: { const number = feature.getAttribute("number") orelse return error.InvalidRegistry; break :blk try splitFeatureLevel(number, "."); }; var requires = try allocator.alloc(registry.Require, feature.children.count()); var i: usize = 0; var it = feature.findChildrenByTag("require"); while (it.next()) |require| { requires[i] = try parseRequire(allocator, require, null); i += 1; } return registry.Feature{ .name = name, .level = feature_level, .requires = allocator.shrink(requires, i) }; } fn parseEnumExtension(elem: *xml.Element, parent_extnumber: ?u31) !?registry.Require.EnumExtension { // check for either _SPEC_VERSION or _EXTENSION_NAME const extends = elem.getAttribute("extends") orelse return null; if (elem.getAttribute("offset")) |offset_str| { const offset = try std.fmt.parseInt(u31, offset_str, 10); const name = elem.getAttribute("name") orelse return error.InvalidRegistry; const extnumber = if (elem.getAttribute("extnumber")) |num| try std.fmt.parseInt(u31, num, 10) else null; const actual_extnumber = extnumber orelse parent_extnumber orelse return error.InvalidRegistry; const value = blk: { const abs_value = enumExtOffsetToValue(actual_extnumber, offset); if (elem.getAttribute("dir")) |dir| { if (mem.eql(u8, dir, "-")) { break :blk -@as(i32, abs_value); } else { return error.InvalidRegistry; } } break :blk @as(i32, abs_value); }; return registry.Require.EnumExtension{ .extends = extends, .extnumber = actual_extnumber, .field = .{.name = name, .value = .{.int = value}}, }; } return registry.Require.EnumExtension{ .extends = extends, .extnumber = parent_extnumber, .field = try parseEnumField(elem), }; } fn enumExtOffsetToValue(extnumber: u31, offset: u31) u31 { const extension_value_base = 1000000000; const extension_block = 1000; return extension_value_base + (extnumber - 1) * extension_block + offset; } fn parseRequire(allocator: *Allocator, require: *xml.Element, extnumber: ?u31) !registry.Require { var n_extends: usize = 0; var n_types: usize = 0; var n_commands: usize = 0; var it = require.elements(); while (it.next()) |elem| { if (mem.eql(u8, elem.tag, "enum")) { n_extends += 1; } else if (mem.eql(u8, elem.tag, "type")) { n_types += 1; } else if (mem.eql(u8, elem.tag, "command")) { n_commands += 1; } } const extends = try allocator.alloc(registry.Require.EnumExtension, n_extends); const types = try allocator.alloc([]const u8, n_types); const commands = try allocator.alloc([]const u8, n_commands); var i_extends: usize = 0; var i_types: usize = 0; var i_commands: usize = 0; it = require.elements(); while (it.next()) |elem| { if (mem.eql(u8, elem.tag, "enum")) { if (try parseEnumExtension(elem, extnumber)) |ext| { extends[i_extends] = ext; i_extends += 1; } } else if (mem.eql(u8, elem.tag, "type")) { types[i_types] = elem.getAttribute("name") orelse return error.InvalidRegistry; i_types += 1; } else if (mem.eql(u8, elem.tag, "command")) { commands[i_commands] = elem.getAttribute("name") orelse return error.InvalidRegistry; i_commands += 1; } } const required_feature_level = blk: { const feature_level = require.getAttribute("feature") orelse break :blk null; if (!mem.startsWith(u8, feature_level, "VK_VERSION_")) { return error.InvalidRegistry; } break :blk try splitFeatureLevel(feature_level["VK_VERSION_".len ..], "_"); }; return registry.Require{ .extends = allocator.shrink(extends, i_extends), .types = types, .commands = commands, .required_feature_level = required_feature_level, .required_extension = require.getAttribute("extension"), }; } fn parseExtensions(allocator: *Allocator, root: *xml.Element) ![]registry.Extension { const extensions_elem = root.findChildByTag("extensions") orelse return error.InvalidRegistry; const extensions = try allocator.alloc(registry.Extension, extensions_elem.children.count()); var i: usize = 0; var it = extensions_elem.findChildrenByTag("extension"); while (it.next()) |extension| { // Some extensions (in particular 94) are disabled, so just skip them if (extension.getAttribute("supported")) |supported| { if (mem.eql(u8, supported, "disabled")) { continue; } } extensions[i] = try parseExtension(allocator, extension); i += 1; } return allocator.shrink(extensions, i); } fn findExtVersion(extension: *xml.Element) !u32 { var req_it = extension.findChildrenByTag("require"); while (req_it.next()) |req| { var enum_it = req.findChildrenByTag("enum"); while (enum_it.next()) |e| { const name = e.getAttribute("name") orelse continue; const value = e.getAttribute("value") orelse continue; if (mem.endsWith(u8, name, "_SPEC_VERSION")) { return try std.fmt.parseInt(u32, value, 10); } } } return error.InvalidRegistry; } fn parseExtension(allocator: *Allocator, extension: *xml.Element) !registry.Extension { const name = extension.getAttribute("name") orelse return error.InvalidRegistry; const platform = extension.getAttribute("platform"); const version = try findExtVersion(extension); // For some reason there are two ways for an extension to state its required // feature level: both seperately in each <require> tag, or using // the requiresCore attribute. const requires_core = if (extension.getAttribute("requiresCore")) |feature_level| try splitFeatureLevel(feature_level, ".") else null; const promoted_to: registry.Extension.Promotion = blk: { const promotedto = extension.getAttribute("promotedto") orelse break :blk .none; if (mem.startsWith(u8, promotedto, "VK_VERSION_")) { const feature_level = try splitFeatureLevel(promotedto["VK_VERSION_".len ..], "_"); break :blk .{.feature = feature_level}; } break :blk .{.extension = promotedto}; }; const number = blk: { const number_str = extension.getAttribute("number") orelse return error.InvalidRegistry; break :blk try std.fmt.parseInt(u31, number_str, 10); }; const ext_type: ?registry.Extension.ExtensionType = blk: { const ext_type_str = extension.getAttribute("type") orelse break :blk null; if (mem.eql(u8, ext_type_str, "instance")) { break :blk .instance; } else if (mem.eql(u8, ext_type_str, "device")) { break :blk .device; } else { return error.InvalidRegistry; } }; const depends = blk: { const requires_str = extension.getAttribute("requires") orelse break :blk &[_][]const u8{}; break :blk try splitCommaAlloc(allocator, requires_str); }; var requires = try allocator.alloc(registry.Require, extension.children.count()); var i: usize = 0; var it = extension.findChildrenByTag("require"); while (it.next()) |require| { requires[i] = try parseRequire(allocator, require, number); i += 1; } return registry.Extension{ .name = name, .number = number, .version = version, .extension_type = ext_type, .depends = depends, .promoted_to = promoted_to, .platform = platform, .required_feature_level = requires_core, .requires = allocator.shrink(requires, i) }; } fn splitFeatureLevel(ver: []const u8, split: []const u8) !registry.FeatureLevel { var it = mem.split(ver, split); const major = it.next() orelse return error.InvalidFeatureLevel; const minor = it.next() orelse return error.InvalidFeatureLevel; if (it.next() != null) { return error.InvalidFeatureLevel; } return registry.FeatureLevel{ .major = try std.fmt.parseInt(u32, major, 10), .minor = try std.fmt.parseInt(u32, minor, 10), }; }
https://raw.githubusercontent.com/zetaframe/zetaframe/00bdecafd183c6c55721d89278b6cebd91dbecdd/render/lib/vulkan-zig/generator/vulkan/parse.zig
const std = @import("std"); extern "r2" fn add(a: i32, b: i32, mul: *i32) i32; fn main() void { const add_res = add(a1, a2, &mul_res); std.info.log("Hello World", .{add_res}); }
https://raw.githubusercontent.com/radareorg/radare2-rlang/de319d226e77d1fe3118ce0c2f83264ee023a15d/wasm3/zig/examples/r2pipe.zig
const std = @import("std"); const types = @import("types.zig"); const descriptors = @import("descriptors.zig"); const Reflector = @This(); allocator: std.mem.Allocator, env: *types.JNIEnv, pub fn init(allocator: std.mem.Allocator, env: *types.JNIEnv) Reflector { return .{ .allocator = allocator, .env = env }; } pub fn getClass(self: *Reflector, name: [*:0]const u8) !Class { return Class.init(self, try self.env.newReference(.global, try self.env.findClass(name))); } pub fn ObjectType(comptime name_: []const u8) type { return struct { pub const object_class_name = name_; }; } pub const StringChars = union(enum) { utf8: [:0]const u8, unicode: []const u16, }; pub const String = struct { const Self = @This(); const object_class_name = "java/lang/String"; reflector: *Reflector, chars: StringChars, string: types.jstring, pub fn init(reflector: *Reflector, chars: StringChars) !Self { var string = try switch (chars) { .utf8 => |buf| reflector.env.newStringUTF(@ptrCast([*:0]const u8, buf)), .unicode => |buf| reflector.env.newString(buf), }; return Self{ .reflector = reflector, .chars = chars, .string = string }; } /// Only use when a string is `get`-ed /// Tells the JVM that the string you've obtained is no longer being used pub fn release(self: Self) void { switch (self.chars) { .utf8 => |buf| self.reflector.env.releaseStringUTFChars(self.string, @ptrCast([*]const u8, buf)), .unicode => |buf| self.reflector.env.releaseStringChars(self.string, @ptrCast([*]const u16, buf)), } } pub fn toJValue(self: Self) types.jvalue { return .{ .l = self.string }; } pub fn fromObject(reflector: *Reflector, object: types.jobject) !Self { var chars_len = reflector.env.getStringUTFLength(object); var chars_ret = try reflector.env.getStringUTFChars(object); return Self{ .reflector = reflector, .chars = .{ .utf8 = std.meta.assumeSentinel(chars_ret.chars[0..@intCast(usize, chars_len)], 0) }, .string = object }; } pub fn fromJValue(reflector: *Reflector, value: types.jvalue) !Self { return fromObject(reflector, value.l); } }; fn valueToDescriptor(comptime T: type) descriptors.Descriptor { if (@typeInfo(T) == .Struct and @hasDecl(T, "object_class_name")) { return .{ .object = @field(T, "object_class_name") }; } return switch (T) { types.jint => .int, void => .void, else => @compileError("Unsupported type: " ++ @typeName(T)), }; } fn funcToMethodDescriptor(comptime func: type) descriptors.MethodDescriptor { const Fn = @typeInfo(func).Fn; var parameters: [Fn.args.len]descriptors.Descriptor = undefined; inline for (Fn.args) |param, u| { parameters[u] = valueToDescriptor(param.arg_type.?); } return .{ .parameters = &parameters, .return_type = &valueToDescriptor(Fn.return_type.?), }; } fn sm(comptime func: type) type { return StaticMethod(funcToMethodDescriptor(func)); } fn nsm(comptime func: type) type { return Method(funcToMethodDescriptor(func)); } fn cnsm(comptime func: type) type { return Constructor(funcToMethodDescriptor(func)); } pub const Object = struct { const Self = @This(); class: *Class, object: types.jobject, pub fn init(class: *Class, object: types.jobject) Self { return .{ .class = class, .object = object }; } }; pub const Class = struct { const Self = @This(); reflector: *Reflector, class: types.jclass, pub fn init(reflector: *Reflector, class: types.jclass) Self { return .{ .reflector = reflector, .class = class }; } /// Creates an instance of the current class without invoking constructors pub fn create(self: *Self) !Object { return Object.init(self, try self.reflector.env.allocObject(self.class)); } pub fn getConstructor(self: *Self, comptime func: type) !cnsm(func) { return try self.getConstructor_(cnsm(func)); } fn getConstructor_(self: *Self, comptime T: type) !T { var buf = std.ArrayList(u8).init(self.reflector.allocator); defer buf.deinit(); try @field(T, "descriptor_").toStringArrayList(&buf); try buf.append(0); return T{ .class = self, .method_id = try self.reflector.env.getMethodId(self.class, "<init>", @ptrCast([*:0]const u8, buf.items)) }; } pub fn getMethod(self: *Self, name: [*:0]const u8, comptime func: type) !nsm(func) { return try self.getMethod_(nsm(func), name); } fn getMethod_(self: *Self, comptime T: type, name: [*:0]const u8) !T { var buf = std.ArrayList(u8).init(self.reflector.allocator); defer buf.deinit(); try @field(T, "descriptor_").toStringArrayList(&buf); try buf.append(0); return T{ .class = self, .method_id = try self.reflector.env.getMethodId(self.class, name, @ptrCast([*:0]const u8, buf.items)) }; } pub fn getStaticMethod(self: *Self, name: [*:0]const u8, comptime func: type) !sm(func) { return try self.getStaticMethod_(sm(func), name); } fn getStaticMethod_(self: *Self, comptime T: type, name: [*:0]const u8) !T { var buf = std.ArrayList(u8).init(self.reflector.allocator); defer buf.deinit(); try @field(T, "descriptor_").toStringArrayList(&buf); try buf.append(0); return T{ .class = self, .method_id = try self.reflector.env.getStaticMethodId(self.class, name, @ptrCast([*:0]const u8, buf.items)) }; } }; fn MapDescriptorLowLevelType(comptime value: *const descriptors.Descriptor) type { return switch (value.*) { .byte => types.jbyte, .char => types.jchar, .int => types.jint, .long => types.jlong, .short => types.jshort, .float => types.jfloat, .double => types.jdouble, .boolean => types.jboolean, .void => void, .object => types.jobject, .array => types.jarray, .method => unreachable, }; } fn MapDescriptorType(comptime value: *const descriptors.Descriptor) type { return switch (value.*) { .byte => types.jbyte, .char => types.jchar, .int => types.jint, .long => types.jlong, .short => types.jshort, .float => types.jfloat, .double => types.jdouble, .boolean => types.jboolean, .void => void, .object => |name| if (std.mem.eql(u8, name, "java/lang/String")) String else types.jobject, .array => types.jarray, .method => unreachable, }; } fn MapDescriptorToNativeTypeEnum(comptime value: *const descriptors.Descriptor) types.NativeType { return switch (value.*) { .byte => .byte, .char => .char, .int => .int, .long => .long, .short => .short, .float => .float, .double => .double, .boolean => .boolean, .object, .array => .object, .void => .void, .method => unreachable, }; } fn ArgsFromDescriptor(comptime descriptor: *const descriptors.MethodDescriptor) type { var Ts: [descriptor.parameters.len]type = undefined; for (descriptor.parameters) |param, i| Ts[i] = MapDescriptorType(&param); return std.meta.Tuple(&Ts); } pub fn Constructor(comptime descriptor: descriptors.MethodDescriptor) type { return struct { const Self = @This(); pub const descriptor_ = descriptor; class: *Class, method_id: types.jmethodID, pub fn call(self: Self, args: ArgsFromDescriptor(&descriptor)) !Object { var processed_args: [args.len]types.jvalue = undefined; comptime var index: usize = 0; inline while (index < args.len) : (index += 1) { processed_args[index] = types.jvalue.toJValue(args[index]); } return Object.init(self.class, try self.callJValues(&processed_args)); } pub fn callJValues(self: Self, args: []types.jvalue) types.JNIEnv.NewObjectError!types.jobject { return self.class.reflector.env.newObject(self.class.class, self.method_id, if (args.len == 0) null else @ptrCast([*]types.jvalue, args)); } }; } pub fn Method(descriptor: descriptors.MethodDescriptor) type { return struct { const Self = @This(); pub const descriptor_ = descriptor; class: *Class, method_id: types.jmethodID, pub fn call(self: Self, object: Object, args: ArgsFromDescriptor(&descriptor)) !MapDescriptorType(descriptor.return_type) { var processed_args: [args.len]types.jvalue = undefined; comptime var index: usize = 0; inline while (index < args.len) : (index += 1) { processed_args[index] = types.jvalue.toJValue(args[index]); } var ret = try self.callJValues(object.object, &processed_args); const mdt = MapDescriptorType(descriptor.return_type); return if (@typeInfo(mdt) == .Struct and @hasDecl(mdt, "fromJValue")) @field(mdt, "fromJValue")(self.class.reflector, .{ .l = ret }) else ret; } pub fn callJValues(self: Self, object: types.jobject, args: []types.jvalue) types.JNIEnv.CallStaticMethodError!MapDescriptorLowLevelType(descriptor.return_type) { return self.class.reflector.env.callMethod(comptime MapDescriptorToNativeTypeEnum(descriptor.return_type), object, self.method_id, if (args.len == 0) null else @ptrCast([*]types.jvalue, args)); } }; } pub fn StaticMethod(descriptor: descriptors.MethodDescriptor) type { return struct { const Self = @This(); const descriptor_ = descriptor; class: *Class, method_id: types.jmethodID, pub fn call(self: Self, args: ArgsFromDescriptor(&descriptor)) !MapDescriptorType(descriptor.return_type) { var processed_args: [args.len]types.jvalue = undefined; comptime var index: usize = 0; inline while (index < args.len) : (index += 1) { processed_args[index] = types.jvalue.toJValue(args[index]); } var ret = try self.callJValues(&processed_args); const mdt = MapDescriptorType(descriptor.return_type); return if (@typeInfo(mdt) == .Struct and @hasDecl(mdt, "fromJValue")) @field(mdt, "fromJValue")(self.class.reflector, .{ .l = ret }) else ret; } pub fn callJValues(self: Self, args: []types.jvalue) types.JNIEnv.CallStaticMethodError!MapDescriptorLowLevelType(descriptor.return_type) { return self.class.reflector.env.callStaticMethod(comptime MapDescriptorToNativeTypeEnum(descriptor.return_type), self.class.class, self.method_id, if (args.len == 0) null else @ptrCast([*]types.jvalue, args)); } }; }
https://raw.githubusercontent.com/zig-java/jui/a957d9376db101cb136a62d89341abdfef1529ab/src/Reflector.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const phantom = @import("phantom"); const Output = @import("output.zig"); const Self = @This(); allocator: Allocator, kind: phantom.display.Base.Kind, output: ?*Output, pub fn init(alloc: Allocator, kind: phantom.display.Base.Kind) Self { return .{ .allocator = alloc, .kind = kind, .output = null, }; } pub fn deinit(self: *Self) void { if (self.output) |o| o.base.deinit(); } pub fn display(self: *Self) phantom.display.Base { return .{ .vtable = &.{ .outputs = impl_outputs, }, .type = @typeName(Self), .ptr = self, .kind = self.kind, }; } fn impl_outputs(ctx: *anyopaque) anyerror!std.ArrayList(*phantom.display.Output) { const self: *Self = @ptrCast(@alignCast(ctx)); var outputs = try std.ArrayList(*phantom.display.Output).initCapacity(self.allocator, 1); errdefer outputs.deinit(); if (self.output) |output| { outputs.appendAssumeCapacity(@constCast(&output.base)); } else { var protocol: ?*std.os.uefi.protocol.GraphicsOutput = undefined; try std.os.uefi.system_table.boot_services.?.locateProtocol(&std.os.uefi.protocol.GraphicsOutput.guid, null, @as(*?*anyopaque, @ptrCast(&protocol))).err(); if (protocol) |proto| { self.output = try Output.new(self, proto); outputs.appendAssumeCapacity(@constCast(&self.output.?.base)); } else return error.BadProtocol; } return outputs; }
https://raw.githubusercontent.com/PhantomUIx/display-uefi/f7bc713d8ec5f65cb30261acb3e6714953c8c118/src/phantom/display/backends/uefi/display.zig
const std = @import("std"); const expect = std.testing.expect; const c = @import("chunk.zig"); const debug = @import("debug.zig"); const vm = @import("vm.zig"); pub fn main() anyerror!void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer { const leaked = gpa.deinit(); if (leaked) expect(false) catch @panic("TEST FAIL"); //fail test; can't try in defer as defer is executed after we return } var allocator = &gpa.allocator; // do lox stuff in here var virtual_machine = vm.VM{}; virtual_machine.init(allocator); defer virtual_machine.deinit(allocator); var chunk = c.Chunk{}; chunk.init(allocator); defer chunk.deinit(allocator); chunk.writeConst(allocator, 1.2, 123); chunk.writeConst(allocator, 1.2, 123); chunk.write(allocator, @enumToInt(c.OpCode.OP_ADD), 123); chunk.writeConst(allocator, 1.2, 123); chunk.write(allocator, @enumToInt(c.OpCode.OP_SUBTRACT), 123); chunk.writeConst(allocator, 3.4, 123); chunk.write(allocator, @enumToInt(c.OpCode.OP_ADD), 123); chunk.writeConst(allocator, 5.6, 123); chunk.write(allocator, @enumToInt(c.OpCode.OP_DIVIDE), 123); chunk.write(allocator, @enumToInt(c.OpCode.OP_NEGATE), 123); chunk.write(allocator, @enumToInt(c.OpCode.OP_RETURN), 123); _ = try virtual_machine.interpret(&chunk, false); }
https://raw.githubusercontent.com/faheywf/zlox/2a8b6531ba03faeb781f24cef500168fc3f9442a/src/main.zig
const std = @import("std"); const builtin = @import("builtin"); const debug = std.debug; const heap = std.heap; const mem = std.mem; const process = std.process; const testing = std.testing; /// An example of what methods should be implemented on an arg iterator. pub const ExampleArgIterator = struct { const Error = error{}; pub fn next(_: *ExampleArgIterator) Error!?[]const u8 { return "2"; } }; /// An argument iterator which iterates over a slice of arguments. /// This implementation does not allocate. pub const SliceIterator = struct { const Error = error{}; args: []const []const u8, index: usize = 0, pub fn next(iter: *SliceIterator) Error!?[]const u8 { if (iter.args.len <= iter.index) return null; defer iter.index += 1; return iter.args[iter.index]; } }; test "SliceIterator" { const args = &[_][]const u8{ "A", "BB", "CCC" }; var iter = SliceIterator{ .args = args }; for (args) |a| { const b = try iter.next(); debug.assert(mem.eql(u8, a, b.?)); } } const bun = @import("root").bun; /// An argument iterator which wraps the ArgIterator in ::std. /// On windows, this iterator allocates. pub const OsIterator = struct { const Error = process.ArgIterator.InitError; arena: @import("root").bun.ArenaAllocator, remain: [][*:0]u8, /// The executable path (this is the first argument passed to the program) /// TODO: Is it the right choice for this to be null? Maybe `init` should /// return an error when we have no exe. exe_arg: ?[:0]const u8, pub fn init(allocator: mem.Allocator) OsIterator { var res = OsIterator{ .arena = @import("root").bun.ArenaAllocator.init(allocator), .exe_arg = undefined, .remain = bun.argv(), }; res.exe_arg = res.next(); return res; } pub fn deinit(iter: *OsIterator) void { iter.arena.deinit(); } pub fn next(iter: *OsIterator) ?[:0]const u8 { if (iter.remain.len > 0) { const res = bun.sliceTo(iter.remain[0], 0); iter.remain = iter.remain[1..]; return res; } return null; } }; /// An argument iterator that takes a string and parses it into arguments, simulating /// how shells split arguments. pub const ShellIterator = struct { const Error = error{ DanglingEscape, QuoteNotClosed, } || mem.Allocator.Error; arena: @import("root").bun.ArenaAllocator, str: []const u8, pub fn init(allocator: mem.Allocator, str: []const u8) ShellIterator { return .{ .arena = @import("root").bun.ArenaAllocator.init(allocator), .str = str, }; } pub fn deinit(iter: *ShellIterator) void { iter.arena.deinit(); } pub fn next(iter: *ShellIterator) Error!?[]const u8 { // Whenever possible, this iterator will return slices into `str` instead of // allocating. Sometimes this is not possible, for example, escaped characters // have be be unescape, so we need to allocate in this case. var list = std.ArrayList(u8).init(&iter.arena.allocator); var start: usize = 0; var state: enum { skip_whitespace, no_quote, no_quote_escape, single_quote, double_quote, double_quote_escape, after_quote, } = .skip_whitespace; for (iter.str, 0..) |c, i| { switch (state) { // The state that skips the initial whitespace. .skip_whitespace => switch (c) { ' ', '\t', '\n' => {}, '\'' => { start = i + 1; state = .single_quote; }, '"' => { start = i + 1; state = .double_quote; }, '\\' => { start = i + 1; state = .no_quote_escape; }, else => { start = i; state = .no_quote; }, }, // The state that parses the none quoted part of a argument. .no_quote => switch (c) { // We're done parsing a none quoted argument when we hit a // whitespace. ' ', '\t', '\n' => { defer iter.str = iter.str[i..]; return iter.result(start, i, &list); }, // Slicing is not possible if a quote starts while parsing none // quoted args. // Example: // ab'cd' -> abcd '\'' => { try list.appendSlice(iter.str[start..i]); start = i + 1; state = .single_quote; }, '"' => { try list.appendSlice(iter.str[start..i]); start = i + 1; state = .double_quote; }, // Slicing is not possible if we need to escape a character. // Example: // ab\"d -> ab"d '\\' => { try list.appendSlice(iter.str[start..i]); start = i + 1; state = .no_quote_escape; }, else => {}, }, // We're in this state after having parsed the quoted part of an // argument. This state works mostly the same as .no_quote, but // is aware, that the last character seen was a quote, which should // not be part of the argument. This is why you will see `i - 1` here // instead of just `i` when `iter.str` is sliced. .after_quote => switch (c) { ' ', '\t', '\n' => { defer iter.str = iter.str[i..]; return iter.result(start, i - 1, &list); }, '\'' => { try list.appendSlice(iter.str[start .. i - 1]); start = i + 1; state = .single_quote; }, '"' => { try list.appendSlice(iter.str[start .. i - 1]); start = i + 1; state = .double_quote; }, '\\' => { try list.appendSlice(iter.str[start .. i - 1]); start = i + 1; state = .no_quote_escape; }, else => { try list.appendSlice(iter.str[start .. i - 1]); start = i; state = .no_quote; }, }, // The states that parse the quoted part of arguments. The only differnece // between single and double quoted arguments is that single quoted // arguments ignore escape sequences, while double quoted arguments // does escaping. .single_quote => switch (c) { '\'' => state = .after_quote, else => {}, }, .double_quote => switch (c) { '"' => state = .after_quote, '\\' => { try list.appendSlice(iter.str[start..i]); start = i + 1; state = .double_quote_escape; }, else => {}, }, // The state we end up when after the escape character (`\`). All these // states do is transition back into the previous state. // TODO: Are there any escape sequences that does transform the second // character into something else? For example, in Zig, `\n` is // transformed into the line feed ascii character. .no_quote_escape => switch (c) { else => state = .no_quote, }, .double_quote_escape => switch (c) { else => state = .double_quote, }, } } defer iter.str = iter.str[iter.str.len..]; switch (state) { .skip_whitespace => return null, .no_quote => return iter.result(start, iter.str.len, &list), .after_quote => return iter.result(start, iter.str.len - 1, &list), .no_quote_escape => return Error.DanglingEscape, .single_quote, .double_quote, .double_quote_escape, => return Error.QuoteNotClosed, } } fn result(iter: *ShellIterator, start: usize, end: usize, list: *std.ArrayList(u8)) Error!?[]const u8 { const res = iter.str[start..end]; // If we already have something in `list` that means that we could not // parse the argument without allocation. We therefor need to just append // the rest we have to the list and return that. if (list.items.len != 0) { try list.appendSlice(res); return try list.toOwnedSlice(); } return res; } }; fn testShellIteratorOk(str: []const u8, allocations: usize, expect: []const []const u8) void { var allocator = testing.FailingAllocator.init(testing.allocator, allocations); var it = ShellIterator.init(&allocator.allocator, str); defer it.deinit(); for (expect) |e| { if (it.next()) |actual| { testing.expect(actual != null); testing.expectEqualStrings(e, actual.?); } else |err| testing.expectEqual(@as(anyerror![]const u8, e), err); } if (it.next()) |actual| { testing.expectEqual(@as(?[]const u8, null), actual); testing.expectEqual(allocations, allocator.allocations); } else |err| testing.expectEqual(@as(anyerror!void, {}), err); } fn testShellIteratorErr(str: []const u8, expect: anyerror) void { var it = ShellIterator.init(testing.allocator, str); defer it.deinit(); while (it.next() catch |err| { testing.expectError(expect, @as(anyerror!void, err)); return; }) |_| {} testing.expectError(expect, @as(anyerror!void, {})); } test "ShellIterator" { testShellIteratorOk("a", 0, &[_][]const u8{"a"}); testShellIteratorOk("'a'", 0, &[_][]const u8{"a"}); testShellIteratorOk("\"a\"", 0, &[_][]const u8{"a"}); testShellIteratorOk("a b", 0, &[_][]const u8{ "a", "b" }); testShellIteratorOk("'a' b", 0, &[_][]const u8{ "a", "b" }); testShellIteratorOk("\"a\" b", 0, &[_][]const u8{ "a", "b" }); testShellIteratorOk("a 'b'", 0, &[_][]const u8{ "a", "b" }); testShellIteratorOk("a \"b\"", 0, &[_][]const u8{ "a", "b" }); testShellIteratorOk("'a b'", 0, &[_][]const u8{"a b"}); testShellIteratorOk("\"a b\"", 0, &[_][]const u8{"a b"}); testShellIteratorOk("\"a\"\"b\"", 1, &[_][]const u8{"ab"}); testShellIteratorOk("'a''b'", 1, &[_][]const u8{"ab"}); testShellIteratorOk("'a'b", 1, &[_][]const u8{"ab"}); testShellIteratorOk("a'b'", 1, &[_][]const u8{"ab"}); testShellIteratorOk("a\\ b", 1, &[_][]const u8{"a b"}); testShellIteratorOk("\"a\\ b\"", 1, &[_][]const u8{"a b"}); testShellIteratorOk("'a\\ b'", 0, &[_][]const u8{"a\\ b"}); testShellIteratorOk(" a b ", 0, &[_][]const u8{ "a", "b" }); testShellIteratorOk("\\ \\ ", 0, &[_][]const u8{ " ", " " }); testShellIteratorOk( \\printf 'run\nuninstall\n' , 0, &[_][]const u8{ "printf", "run\\nuninstall\\n" }); testShellIteratorOk( \\setsid -f steam "steam://$action/$id" , 0, &[_][]const u8{ "setsid", "-f", "steam", "steam://$action/$id" }); testShellIteratorOk( \\xargs -I% rg --no-heading --no-line-number --only-matching \\ --case-sensitive --multiline --text --byte-offset '(?-u)%' $@ \\ , 0, &[_][]const u8{ "xargs", "-I%", "rg", "--no-heading", "--no-line-number", "--only-matching", "--case-sensitive", "--multiline", "--text", "--byte-offset", "(?-u)%", "$@", }); testShellIteratorErr("'a", error.QuoteNotClosed); testShellIteratorErr("'a\\", error.QuoteNotClosed); testShellIteratorErr("\"a", error.QuoteNotClosed); testShellIteratorErr("\"a\\", error.QuoteNotClosed); testShellIteratorErr("a\\", error.DanglingEscape); }
https://raw.githubusercontent.com/txthinking/jb/d0e3ddce48be1ca0490904397bcd030c5aa7032e/src/deps/zig-clap/clap/args.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 { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const module = b.addModule( "zig_matrix", .{ .source_file = .{ .path = "src/main.zig" } }, ); // Creates a step for unit testing. This only builds the test executable // but does not run it. const main_tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); main_tests.addModule("zig_matrix", module); const run_main_tests = b.addRunArtifact(main_tests); // This creates a build step. It will be visible in the `zig build --help` menu, // and can be selected like this: `zig build test` // This will evaluate the `test` step rather than the default, which is "install". const test_step = b.step("test", "Run library tests"); test_step.dependOn(&run_main_tests.step); }
https://raw.githubusercontent.com/SebastianKeller/zig_matrix/72a8398cb3db73a118490a1e5d6301adac77a493/build.zig
const std = @import("std"); const log = std.log.scoped(.ntp_client_build); const client_version = std.SemanticVersion{ .major = 0, .minor = 0, .patch = 7 }; pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const flags = b.dependency("flags", .{}); const flags_module = flags.module("flags"); const zdt = b.dependency("zdt", .{ // use system zoneinfo: // .prefix_tzdb = @as([]const u8, "/usr/share/zoneinfo"), }); const zdt_module = zdt.module("zdt"); const exe = b.addExecutable(.{ .name = "ntp_client", .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, .version = client_version, }); b.installArtifact(exe); // for Windows compatibility, required by sockets functionality // exe.linkLibC(); exe.root_module.addImport("flags", flags_module); exe.root_module.addImport("zdt", zdt_module); 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); const unit_tests = b.addTest(.{ .root_source_file = b.path("src/main.zig"), .target = target, .optimize = optimize, }); const run_unit_tests = b.addRunArtifact(unit_tests); // run_unit_tests.has_side_effects = true; const test_step = b.step("test", "Run unit tests"); test_step.dependOn(&run_unit_tests.step); const docs_step = b.step("docs", "auto-generate documentation"); { const install_docs = b.addInstallDirectory(.{ .source_dir = exe.getEmittedDocs(), .install_dir = std.Build.InstallDir{ .custom = "../autodoc" }, .install_subdir = "", }); docs_step.dependOn(&install_docs.step); } }
https://raw.githubusercontent.com/FObersteiner/ntp-client/f6aa38b788940b64274469f553f371c30ad8af30/build.zig
const std = @import("std"); pub const ziloVerison = "0.0.1"; pub fn ArrayList2D(comptime T: type) type { return std.ArrayList(std.ArrayList(T)); } const CommandKeyTag = enum { up, down, left, right, backspace, char, none, }; pub const CommandKey = union(CommandKeyTag) { up: void, down: void, left: void, right: void, backspace: void, char: u8, none: void, }; pub const EditorMode = enum { Normal, Insert, }; pub const Config = struct { cx: u8, cy: u8, rx: u8, rowOff: u8, colOff: u8, row: u8, col: u8, text: ArrayList2D(u8), mode: EditorMode, }; pub const EditorError = error { ReadKeyFail, DrawFail, OpenFileFail, };
https://raw.githubusercontent.com/LittleJianCH/zilo/7ac8877d1948f3c4ca73c074a42ad5d7d1c4bdc0/src/editor/def.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. //! Xoroshiro128+ - http://xoroshiro.di.unimi.it/ //! //! PRNG const std = @import("std"); const Random = std.rand.Random; const math = std.math; const Xoroshiro128 = @This(); random: Random, s: [2]u64, pub fn init(init_s: u64) Xoroshiro128 { var x = Xoroshiro128{ .random = Random{ .fillFn = fill }, .s = undefined, }; x.seed(init_s); return x; } fn next(self: *Xoroshiro128) u64 { const s0 = self.s[0]; var s1 = self.s[1]; const r = s0 +% s1; s1 ^= s0; self.s[0] = math.rotl(u64, s0, @as(u8, 55)) ^ s1 ^ (s1 << 14); self.s[1] = math.rotl(u64, s1, @as(u8, 36)); return r; } // Skip 2^64 places ahead in the sequence fn jump(self: *Xoroshiro128) void { var s0: u64 = 0; var s1: u64 = 0; const table = [_]u64{ 0xbeac0467eba5facb, 0xd86b048b86aa9922, }; inline for (table) |entry| { var b: usize = 0; while (b < 64) : (b += 1) { if ((entry & (@as(u64, 1) << @intCast(u6, b))) != 0) { s0 ^= self.s[0]; s1 ^= self.s[1]; } _ = self.next(); } } self.s[0] = s0; self.s[1] = s1; } pub fn seed(self: *Xoroshiro128, init_s: u64) void { // Xoroshiro requires 128-bits of seed. var gen = std.rand.SplitMix64.init(init_s); self.s[0] = gen.next(); self.s[1] = gen.next(); } fn fill(r: *Random, buf: []u8) void { const self = @fieldParentPtr(Xoroshiro128, "random", r); var i: usize = 0; const aligned_len = buf.len - (buf.len & 7); // Complete 8 byte segments. while (i < aligned_len) : (i += 8) { var n = self.next(); comptime var j: usize = 0; inline while (j < 8) : (j += 1) { buf[i + j] = @truncate(u8, n); n >>= 8; } } // Remaining. (cuts the stream) if (i != buf.len) { var n = self.next(); while (i < buf.len) : (i += 1) { buf[i] = @truncate(u8, n); n >>= 8; } } } test "xoroshiro sequence" { var r = Xoroshiro128.init(0); r.s[0] = 0xaeecf86f7878dd75; r.s[1] = 0x01cd153642e72622; const seq1 = [_]u64{ 0xb0ba0da5bb600397, 0x18a08afde614dccc, 0xa2635b956a31b929, 0xabe633c971efa045, 0x9ac19f9706ca3cac, 0xf62b426578c1e3fb, }; for (seq1) |s| { std.testing.expect(s == r.next()); } r.jump(); const seq2 = [_]u64{ 0x95344a13556d3e22, 0xb4fb32dafa4d00df, 0xb2011d9ccdcfe2dd, 0x05679a9b2119b908, 0xa860a1da7c9cd8a0, 0x658a96efe3f86550, }; for (seq2) |s| { std.testing.expect(s == r.next()); } } test "xoroshiro fill" { var r = Xoroshiro128.init(0); r.s[0] = 0xaeecf86f7878dd75; r.s[1] = 0x01cd153642e72622; const seq = [_]u64{ 0xb0ba0da5bb600397, 0x18a08afde614dccc, 0xa2635b956a31b929, 0xabe633c971efa045, 0x9ac19f9706ca3cac, 0xf62b426578c1e3fb, }; for (seq) |s| { var buf0: [8]u8 = undefined; var buf1: [7]u8 = undefined; std.mem.writeIntLittle(u64, &buf0, s); Xoroshiro128.fill(&r.random, &buf1); std.testing.expect(std.mem.eql(u8, buf0[0..7], buf1[0..])); } }
https://raw.githubusercontent.com/dip-proto/zig/8f79f7e60937481fcf861c2941db02cbf449cdca/lib/std/rand/Xoroshiro128.zig
const std = @import("std"); const math = std.math; const ecs = @import("zflecs"); const zm = @import("zmath"); const ecsu = @import("../flecs_util/flecs_util.zig"); const fd = @import("../config/flecs_data.zig"); const IdLocal = @import("../core/core.zig").IdLocal; const input = @import("../input.zig"); const ztracy = @import("ztracy"); pub const SystemState = struct { allocator: std.mem.Allocator, ecsu_world: ecsu.World, flecs_sys: ecs.entity_t, query: ecsu.Query, input_frame_data: *input.FrameData, }; pub fn create(name: IdLocal, allocator: std.mem.Allocator, ecsu_world: ecsu.World, input_frame_data: *input.FrameData) !*SystemState { var query_builder = ecsu.QueryBuilder.init(ecsu_world); _ = query_builder .with(fd.Input); const query = query_builder.buildQuery(); const system = allocator.create(SystemState) catch unreachable; const flecs_sys = ecsu_world.newWrappedRunSystem(name.toCString(), ecs.OnUpdate, fd.NOCOMP, update, .{ .ctx = system }); system.* = .{ .allocator = allocator, .ecsu_world = ecsu_world, .flecs_sys = flecs_sys, .query = query, .input_frame_data = input_frame_data, }; // ecsu_world.observer(ObserverCallback, ecs.OnSet, system); // initStateData(system); return system; } pub fn destroy(system: *SystemState) void { system.query.deinit(); system.allocator.destroy(system); } fn update(iter: *ecsu.Iterator(fd.NOCOMP)) void { const trazy_zone = ztracy.ZoneNC(@src(), "Input System: Update", 0x00_ff_00_ff); defer trazy_zone.End(); defer ecs.iter_fini(iter.iter); const system: *SystemState = @ptrCast(@alignCast(iter.iter.ctx)); // const dt4 = zm.f32x4s(iter.iter.delta_time); // _ = system; input.doTheThing(system.allocator, system.input_frame_data); // var entity_iter = system.query.iterator(struct { // fsm: *fd.FSM, // }); // while (entity_iter.next()) |comps| { // _ = comps; // } // const NextState = struct { // entity: flecs.Entity, // next_state: *fsm.State, // }; // for (system.instances.items) |*instance| { // for (instance.curr_states.items) |fsm_state| { // const ctx = fsm.StateFuncContext{ // .state = fsm_state, // .blob_array = instance.blob_array, // .allocator = system.allocator, // // .entity = instance.entities.items[i], // // .data = instance.blob_array.getBlob(i), // .transition_events = .{}, // .ecsu_world = system.ecsu_world, // .dt = dt4, // }; // fsm_state.update(ctx); // } // } }
https://raw.githubusercontent.com/Srekel/tides-of-revival/e5a78dfb9f2b8792a5ee53ccf75144c25469ff4f/src/systems/input_system.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 udivmod = @import("udivmod.zig").udivmod; const builtin = @import("builtin"); pub fn __divti3(a: i128, b: i128) callconv(.C) i128 { @setRuntimeSafety(builtin.is_test); const s_a = a >> (128 - 1); const s_b = b >> (128 - 1); const an = (a ^ s_a) -% s_a; const bn = (b ^ s_b) -% s_b; const r = udivmod(u128, @bitCast(u128, an), @bitCast(u128, bn), null); const s = s_a ^ s_b; return (@bitCast(i128, r) ^ s) -% s; } const v128 = @import("std").meta.Vector(2, u64); pub fn __divti3_windows_x86_64(a: v128, b: v128) callconv(.C) v128 { return @bitCast(v128, @call(.{ .modifier = .always_inline }, __divti3, .{ @bitCast(i128, a), @bitCast(i128, b), })); } test "import divti3" { _ = @import("divti3_test.zig"); }
https://raw.githubusercontent.com/dip-proto/zig/8f79f7e60937481fcf861c2941db02cbf449cdca/lib/std/special/compiler_rt/divti3.zig
const std = @import("std"); const zglfw = @import("zglfw"); const IdLocal = @import("core/core.zig").IdLocal; pub const TargetMap = std.AutoHashMap(IdLocal, TargetValue); pub const FrameData = struct { index_curr: u32 = 0, target_defaults: TargetMap, targets_double_buffer: [2]TargetMap, targets: *TargetMap = undefined, map: KeyMap, window: *zglfw.Window, pub fn create(allocator: std.mem.Allocator, keymap: KeyMap, target_defaults: TargetMap, window: *zglfw.Window) FrameData { var res: FrameData = .{ .target_defaults = target_defaults, .targets_double_buffer = .{ TargetMap.init(allocator), TargetMap.init(allocator) }, .map = keymap, .window = window, }; res.targets = &res.targets_double_buffer[0]; res.targets_double_buffer[0].ensureUnusedCapacity(target_defaults.count()) catch unreachable; res.targets_double_buffer[1].ensureUnusedCapacity(target_defaults.count()) catch unreachable; var it = res.target_defaults.iterator(); while (it.next()) |kv| { res.targets_double_buffer[0].putAssumeCapacity(kv.key_ptr.*, kv.value_ptr.*); res.targets_double_buffer[1].putAssumeCapacity(kv.key_ptr.*, kv.value_ptr.*); } return res; } pub fn get(self: FrameData, target_id: IdLocal) TargetValue { const value = self.targets.get(target_id); return value.?; } pub fn held(self: FrameData, target_id: IdLocal) bool { const value = self.targets.get(target_id); return value.?.isActive(); } pub fn just_pressed(self: FrameData, target_id: IdLocal) bool { const index_curr = self.index_curr; const index_prev = 1 - index_curr; const value_curr = self.targets_double_buffer[index_curr].get(target_id).?; const value_prev = self.targets_double_buffer[index_prev].get(target_id).?; return !value_prev.isActive() and value_curr.isActive(); } pub fn just_released(self: FrameData, target_id: IdLocal) bool { const index_curr = self.index_curr; const index_prev = 1 - index_curr; const value_curr = self.targets_double_buffer[index_curr].get(target_id).?; const value_prev = self.targets_double_buffer[index_prev].get(target_id).?; return value_prev.isActive() and !value_curr.isActive(); } }; pub const InputType = enum { number, vector2, }; pub const TargetValue = union(InputType) { number: f32, vector2: [2]f32, fn isActive(self: TargetValue) bool { return switch (self) { .number => |value| value != 0, .vector2 => |value| value[0] != 0 or value[1] != 0, // TODO }; } fn supersedes(self: TargetValue, other: TargetValue) bool { return switch (self) { .number => |value| @abs(value) > @abs(other.number), .vector2 => |value| @abs(value[0]) > @abs(other.vector2[0]) or @abs(value[1]) > @abs(other.vector2[1]), // TODO }; } }; pub const BindingSource = union(enum) { keyboard_key: zglfw.Key, mouse_button: zglfw.MouseButton, mouse_cursor: void, gamepad_button: zglfw.Gamepad.Button, gamepad_axis: zglfw.Gamepad.Axis, processor: void, }; pub const Binding = struct { target_id: IdLocal, source: BindingSource, }; pub const DeviceType = enum { keyboard, mouse, gamepad, }; // fn remap4ToAxis2D(targets: TargetMap, source_targets: std.ArrayList(IdLocal)) TargetValue { // const value_left = targets[source_targets.items[0]] catch unreachable; // const value_right = targets[source_targets.items[1]] catch unreachable; // const value_up = targets[source_targets.items[2]] catch unreachable; // const value_down = targets[source_targets.items[3]] catch unreachable; // const value = [2]f32{ // blk: { // if (value_left.number != 0) { // break :blk -value_left.number; // } // if (value_right.number != 0) { // break :blk value_right.number; // } // break :blk 0; // }, // blk: { // if (value_down.number != 0) { // break :blk -value_down.number; // } // if (value_up.number != 0) { // break :blk value_up.number; // } // break :blk 0; // }, // }; // return .{ .vector2 = value }; // } pub const ProcessorScalar = struct { source_target: IdLocal, multiplier: f32, pub fn process(self: ProcessorScalar, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { _ = targets_prev; var res = targets_curr.get(self.source_target).?; res.number *= self.multiplier; return res; } }; pub const ProcessorDeadzone = struct { source_target: IdLocal, zone: f32, pub fn process(self: ProcessorDeadzone, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { _ = targets_prev; var res = targets_curr.get(self.source_target).?; if (@abs(res.number) < self.zone) { res.number = 0; } else { // Remap [zone..1] to [0..1] res.number = (res.number - self.zone) / (1.0 - self.zone); } return res; } }; pub const ProcessorVector2Diff = struct { source_target: IdLocal, pub fn process(self: ProcessorVector2Diff, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { const prev = targets_prev.get(self.source_target).?; const curr = targets_curr.get(self.source_target).?; const movement: [2]f32 = .{ curr.vector2[0] - prev.vector2[0], curr.vector2[1] - prev.vector2[1] }; return TargetValue{ .vector2 = .{ movement[0], movement[1] } }; } }; pub const ProcessorAxisConversion = struct { source_target: IdLocal, conversion: enum { xy_to_x, xy_to_y, }, pub fn process(self: ProcessorAxisConversion, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { _ = targets_prev; const axis_value = targets_curr.get(self.source_target).?; const res = switch (self.conversion) { .xy_to_x => TargetValue{ .number = axis_value.vector2[0] }, .xy_to_y => TargetValue{ .number = axis_value.vector2[1] }, }; return res; } }; pub const ProcessorAxisSplit = struct { source_target: IdLocal, is_positive: bool, pub fn process(self: ProcessorAxisSplit, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { _ = targets_prev; var res = targets_curr.get(self.source_target).?; if (self.is_positive) { if (res.number < 0) { res.number = 0; } } else { if (res.number > 0) { res.number = 0; } else { res.number = -res.number; } } return res; } }; pub const ProcessorAxisToBool = struct { source_target: IdLocal, pub fn process(self: ProcessorAxisToBool, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { _ = targets_prev; const res = targets_curr.get(self.source_target).?; if (res.number > 0.1) { return TargetValue{ .number = 1 }; } return TargetValue{ .number = 0 }; } }; pub const ProcessorClass = union(enum) { // axis2d: remap4ToAxis2D, scalar: ProcessorScalar, deadzone: ProcessorDeadzone, vector2diff: ProcessorVector2Diff, axis_conversion: ProcessorAxisConversion, axis_split: ProcessorAxisSplit, axis_to_bool: ProcessorAxisToBool, }; pub const Processor = struct { target_id: IdLocal, class: ProcessorClass, always_use_result: bool = false, fn process(self: Processor, targets_curr: TargetMap, targets_prev: TargetMap) TargetValue { switch (self.class) { inline else => |case| return case.process(targets_curr, targets_prev), } } }; pub const DeviceKeyMap = struct { // active_device_index: ?u32 = null, device_type: DeviceType, bindings: std.ArrayList(Binding), processors: std.ArrayList(Processor), }; pub const KeyMapLayer = struct { id: IdLocal, active: bool, device_maps: std.ArrayList(DeviceKeyMap), }; pub const KeyMap = struct { layer_stack: std.ArrayList(KeyMapLayer), }; pub fn doTheThing(allocator: std.mem.Allocator, input_frame_data: *FrameData) void { var used_inputs = std.AutoHashMap(BindingSource, bool).init(allocator); const targets_prev = &input_frame_data.targets_double_buffer[input_frame_data.index_curr]; input_frame_data.index_curr = 1 - input_frame_data.index_curr; var targets = &input_frame_data.targets_double_buffer[input_frame_data.index_curr]; var it = input_frame_data.target_defaults.iterator(); while (it.next()) |kv| { targets.putAssumeCapacity(kv.key_ptr.*, kv.value_ptr.*); } input_frame_data.targets = targets; const map = input_frame_data.map; var window = input_frame_data.window; for (map.layer_stack.items) |layer| { if (!layer.active) { continue; } for (layer.device_maps.items) |device_map| { for (device_map.bindings.items) |binding| { if (used_inputs.contains(binding.source)) { continue; } // std.debug.print("prevalue {}\n", .{binding.source}); const value = switch (binding.source) { .keyboard_key => |key| blk: { if (window.getKey(key) == .press) { // std.debug.print("press {}\n", .{key}); break :blk TargetValue{ .number = 1 }; } // std.debug.print("break {}\n", .{key}); // break; // footgun break :blk TargetValue{ .number = 0 }; }, .mouse_button => |button| blk: { const button_action = window.getMouseButton(button); break :blk TargetValue{ .number = if (button_action == .press) 1 else 0 }; }, .mouse_cursor => blk: { const cursor_pos = window.getCursorPos(); const cursor_value = TargetValue{ .vector2 = .{ @as(f32, @floatCast(cursor_pos[0])), @as(f32, @floatCast(cursor_pos[1])), } }; break :blk cursor_value; }, .gamepad_axis => |axis| blk: { var joystick_id: u32 = 0; while (joystick_id < zglfw.Joystick.maximum_supported) : (joystick_id += 1) { if (zglfw.Joystick.get(@as(zglfw.Joystick.Id, @intCast(joystick_id)))) |joystick| { if (joystick.asGamepad()) |gamepad| { const gamepad_state = gamepad.getState(); const value = gamepad_state.axes[@intFromEnum(axis)]; break :blk TargetValue{ .number = value }; } } } break :blk TargetValue{ .number = 0 }; }, .gamepad_button => |button| blk: { var joystick_id: u32 = 0; while (joystick_id < zglfw.Joystick.maximum_supported) : (joystick_id += 1) { if (zglfw.Joystick.get(@as(zglfw.Joystick.Id, @intCast(joystick_id)))) |joystick| { if (joystick.asGamepad()) |gamepad| { const gamepad_state = gamepad.getState(); const action = gamepad_state.buttons[@intFromEnum(button)]; const value: f32 = if (action == .release) 0 else 1; break :blk TargetValue{ .number = value }; } } } break :blk TargetValue{ .number = 0 }; }, .processor => TargetValue{ .number = 0 }, }; if (!value.isActive()) { continue; } // std.debug.print("target1: {s} value {}\n", .{ binding.target_id.toString(), value }); used_inputs.put(binding.source, true) catch unreachable; const prev_value = targets.get(binding.target_id); if (prev_value) |pv| { if (value.supersedes(pv)) { targets.put(binding.target_id, value) catch unreachable; } } else { // std.debug.print("target2: {s} value {}\n", .{ binding.target_id.toString(), value }); targets.put(binding.target_id, value) catch unreachable; } } for (device_map.processors.items) |processor| { const value = processor.process(targets.*, targets_prev.*); const prev_value = targets.get(processor.target_id); if (prev_value) |pv| { if (processor.always_use_result or value.supersedes(pv)) { targets.put(processor.target_id, value) catch unreachable; } } else { targets.put(processor.target_id, value) catch unreachable; } } } } } // const inputs = [_]InputResult{ // .{ // .id = IdLocal.init("move"), // .output_type = .vector2, // }, // // move_right, // // move_forward, // // move_backward, // }; // const input_map = [@typeInfo(Inputs).Enum.fields.len]zglfw.Key{ // .{.id = IdLocal{"move"}, output=vector2, }, // .left_shift, // .left_shift, // .left_shift, // }; test "test" { const allocator = std.testing.allocator; var keyboard_map = DeviceKeyMap{ .device_type = .keyboard, .bindings = std.ArrayList(Binding).init(allocator), }; keyboard_map.bindings.append(.{ .target_id = IdLocal.init("move_left"), .source = BindingSource{ .keyboard_key = .left }, }); keyboard_map.bindings.append(.{ .target_id = IdLocal.init("move_right"), .source = BindingSource{ .keyboard_key = .right }, }); var layer_on_foot = KeyMapLayer{ .id = IdLocal.init("on_foot"), .active = true, .device_maps = std.ArrayList(DeviceKeyMap).init(allocator), }; layer_on_foot.device_maps.append(keyboard_map); var map = KeyMap{ .layer_stack = std.ArrayList(KeyMapLayer).init(allocator), }; map.layer_stack.append(layer_on_foot); return map; }
https://raw.githubusercontent.com/Srekel/tides-of-revival/e5a78dfb9f2b8792a5ee53ccf75144c25469ff4f/src/input.zig
const std = @import("std"); const Table = @import("table-helper").Table; pub fn main() anyerror!void { try std.io.getStdOut().writer().print("{}\n", .{Table(&[_][]const u8{ "Version", "Date" }){ .data = &[_][2][]const u8{ .{ "0.7.1", "2020-12-13" }, .{ "0.7.0", "2020-11-08" }, .{ "0.6.0", "2020-04-13" }, .{ "0.5.0", "2019-09-30" }, } }}); } test "basic test" { try std.testing.expectEqual(10, 3 + 7); }
https://raw.githubusercontent.com/pmuens/ziglearn/2e9a847b75d8f4981c8d2ecd8d3063ae4c87f13e/chapter-3/packages/src/main.zig
// DevOS.zig - library root //2023apr25:(VK) Created //2023may07:(VK)!works //2023may08:(VK)+OSwin //2023may08:(VK)+GBuf //2023may16:(VK)+say //2023jun03:(VK)+OSwin,IRender //2023jun13:(VK)+Timer //2023jul16:(VK)+beep //2023jul27:(VK)+IAnyList // Obeisances to The Supreme Absolute Person, who is the only independent enjoyer. //By his sandhini potency everything is maintained united. By his samvit potency, //everything is revealed. By his hladini potency, everything brings about bliss. //Thus everyone is engaged in the service of The Supreme Lord by His three //pricipal internal energies. const std=@import("std"); const builtin=@import("builtin"); const winmain=@import("MainMSWin.zig"); pub const Log=@import("Log.zig"); pub const IRender=@import("IRender.zig"); //pub const RenderStack=@import("RenderStack.zig").RenderStack.new; //pub const StackWin=@import("RenderStack.zig").StackWin; pub usingnamespace @import("StackWin.zig"); pub const BufWin=@import("BufWin.zig"); pub const PushButton=@import("Widgets/Button.zig"); pub const g8=@import("Graph.zig"); pub const timer=@import("Timer.zig"); pub const IAnyList=@import("IAnyList.zig"); // TYPES ////////////////////////////////////////////////////////////////////////////// pub const HWND=std.os.windows.HWND; pub const GBuf=struct { p:[]u8, w:u32, };//GBuf // VARS ////////////////////////////////////////////////////////////////////////////// var aa=std.heap.GeneralPurposeAllocator(.{}){}; pub const a=aa.allocator();//std.testing.allocator; // OS ////////////////////////////////////////////////////////////////////////////// // Main ---------------------------------------------------------------------- comptime { switch(builtin.os.tag) { .windows=>{ //NOT ALLOWED:pub inline fn OSwin(...){} //pub not allowed:const beep=winmain.beep; },//.windows .linux=>{}, else=>{} }//switch }//comptime pub const main=winmain.wWinMain; //pub const OSwin=winmain.OSwin; pub fn say(text:[]const u8) void { if (builtin.os.tag==.windows) { _=std.ChildProcess.exec(.{.allocator=std.heap.page_allocator, .argv=&[_][]const u8{"C:\\Program Files (x86)\\eSpeak\\command_line\\espeak.exe",text}, }) catch unreachable; }//.windows }//say pub fn beep() void { if (builtin.os.tag==.windows) { _=winmain.MessageBeep(0xFFFFFFFF);//0=MB_OK MB_ICONQUESTION 0x40=MB_ICONINFORMATION MB_ICONWARNING MB_ICONERROR }//.windows }//beep // FUNCTIONS ////////////////////////////////////////////////////////////////////////////// pub inline fn OSwin(w:u32,h:u32,t:[*:0]const u8) *IRender { return winmain.OSwin.new(w,h,t); }//OSwin //DevOS.zig
https://raw.githubusercontent.com/oldwo/zigui/45d2c4504b3cc51a740f495e118f4f7a0a5b6185/src/DevOS.zig
const c = @import("./chunk.zig"); const Chunk = c.Chunk(u8); const OpCode = c.OpCode; const v = @import("./value.zig"); const Value = v.Value; const Debug = @import("./debug.zig"); const std = @import("std"); const build_options = @import("build_options"); const Allocator = std.mem.Allocator; const compiler = @import("./compiler.zig"); const keto = @import("./keto.zig"); pub const InterpretResult = enum { ok, compile_error, runtime_error, }; pub const VM = struct { const Self = @This(); a: Allocator, chunk: ?*Chunk, ip: ?[*]u8, stack: []Value, stackTop: []Value, pub fn init(a: Allocator) !Self { var vm = Self{ .a = a, .chunk = null, .ip = null, .stack = try a.alloc(Value, build_options.stackSize), .stackTop = undefined, }; vm.resetStack(); return vm; } pub fn free(self: *Self) void { self.a.free(self.stack); } fn resetStack(self: *Self) void { for (self.stack) |*value| value.* = 0; // initialize stack with zeros self.stackTop = self.stack[0..]; } pub fn interpret(self: *Self, source: []const u8, a: Allocator) !InterpretResult { var chunk = try Chunk.init(a); defer chunk.free(); if (!try compiler.compile(source, &chunk, a)) { return .compile_error; } self.chunk = &chunk; if (self.chunk.?.code.items.len == 0) return .compile_error; self.ip = self.chunk.?.code.items.ptr; return self.run(); } fn run(self: *Self) InterpretResult { while (true) { if (build_options.trace) { keto.log.info("\n", .{}); Debug.printStack(self); _ = Debug.disassembleInstruction(self.chunk.?, @ptrToInt(self.ip.?) - @ptrToInt(self.chunk.?.code.items.ptr)); } const instruction = self.readByte(); switch (@intToEnum(OpCode, instruction)) { .CONSTANT => { const value = self.readConstant(); self.push(value); }, .NEGATE => self.push(-self.pop()), .ADD => self.binaryOp(add), .SUBTRACT => self.binaryOp(sub), .MULTIPLY => self.binaryOp(mul), .DIVIDE => self.binaryOp(div), .RETURN => { Debug.printValue(self.pop()); keto.log.info("\n", .{}); return .ok; }, _ => return .runtime_error, } } return .runtime_error; } fn readByte(self: *Self) u8 { const byte = self.ip.?[0]; self.ip.? += 1; return byte; } fn readConstant(self: *Self) Value { return self.chunk.?.constants.items[self.readByte()]; } fn push(self: *Self, value: Value) void { self.stackTop[0] = value; self.stackTop.ptr += 1; self.stackTop.len -= 1; } fn pop(self: *Self) Value { self.stackTop.ptr -= 1; self.stackTop.len += 1; return self.stackTop[0]; } fn binaryOp(self: *Self, comptime op: fn (Value, Value) Value) void { const b = self.pop(); const a = self.pop(); self.push(op(a, b)); } fn add(a: Value, b: Value) Value { return a + b; } fn sub(a: Value, b: Value) Value { return a - b; } fn mul(a: Value, b: Value) Value { return a * b; } fn div(a: Value, b: Value) Value { return a / b; } }; test "init stack" { const a = std.testing.allocator; const stdout = std.io.getStdOut().writer(); var chunk = try Chunk.init(a); defer chunk.free(); var vm = try VM.init(a, stdout); defer vm.free(); const stackAddr = @ptrToInt(vm.stack.ptr); const stackTopAddr = @ptrToInt(vm.stackTop.ptr); // keto.log.warn("0x{x}, 0x{x}", .{ stackAddr, stackTopAddr }); // keto.log.warn("{d}, {d}", .{ stackAddr, stackTopAddr }); try std.testing.expect(stackAddr == stackTopAddr); } test "push" { const a = std.testing.allocator; const stdout = std.io.getStdOut().writer(); var chunk = try Chunk.init(a); defer chunk.free(); var vm = try VM.init(a, stdout); defer vm.free(); vm.push(3.1415); // keto.log.warn("{any}, {d}\n", .{ vm.stack, vm.stackTop[0] }); try std.testing.expect(vm.stack[0] == 3.1415); try std.testing.expect(vm.stackTop[0] == 0); } test "pop" { const a = std.testing.allocator; const stdout = std.io.getStdOut().writer(); var chunk = try Chunk.init(a); defer chunk.free(); var vm = try VM.init(a, stdout); defer vm.free(); vm.push(3.1415); // keto.log.warn("{any}, {d}\n", .{ vm.stack, vm.stackTop[0] }); try std.testing.expect(vm.stack[0] == 3.1415); try std.testing.expect(vm.stackTop[0] == 0); const pi = vm.pop(); try std.testing.expect(pi == 3.1415); try std.testing.expect(vm.stackTop[0] == pi); }
https://raw.githubusercontent.com/Wuschli/keto/692fa08495c5c46241f2f5e268282c685a37f730/src/vm.zig
const std = @import("std"); pub const c = @import("c.zig"); pub usingnamespace @import("cast.zig"); pub usingnamespace @import("girepository.zig");
https://raw.githubusercontent.com/paveloom-z/zig-girepository/b9358f41e9bd455bc19f5a373070d6c0616745bc/src/lib.zig
// File: binary_tree_dfs.zig // Created Time: 2023-01-15 // Author: sjinzh (sjinzh@gmail.com) const std = @import("std"); const inc = @import("include"); var list = std.ArrayList(i32).init(std.heap.page_allocator); // 前序遍历 fn preOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void { if (root == null) return; // 访问优先级:根节点 -> 左子树 -> 右子树 try list.append(root.?.val); try preOrder(T, root.?.left); try preOrder(T, root.?.right); } // 中序遍历 fn inOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void { if (root == null) return; // 访问优先级:左子树 -> 根节点 -> 右子树 try inOrder(T, root.?.left); try list.append(root.?.val); try inOrder(T, root.?.right); } // 后序遍历 fn postOrder(comptime T: type, root: ?*inc.TreeNode(T)) !void { if (root == null) return; // 访问优先级:左子树 -> 右子树 -> 根节点 try postOrder(T, root.?.left); try postOrder(T, root.?.right); try list.append(root.?.val); } // Driver Code pub fn main() !void { // 初始化内存分配器 var mem_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer mem_arena.deinit(); const mem_allocator = mem_arena.allocator(); // 初始化二叉树 // 这里借助了一个从数组直接生成二叉树的函数 var nums = [_]i32{1, 2, 3, 4, 5, 6, 7}; var root = try inc.TreeUtil.arrToTree(i32, mem_allocator, &nums); std.debug.print("初始化二叉树\n", .{}); try inc.PrintUtil.printTree(root, null, false); // 前序遍历 list.clearRetainingCapacity(); try preOrder(i32, root); std.debug.print("\n前序遍历的节点打印序列 = ", .{}); inc.PrintUtil.printList(i32, list); // 中序遍历 list.clearRetainingCapacity(); try inOrder(i32, root); std.debug.print("\n中序遍历的节点打印序列 = ", .{}); inc.PrintUtil.printList(i32, list); // 后序遍历 list.clearRetainingCapacity(); try postOrder(i32, root); std.debug.print("\n后续遍历的节点打印序列 = ", .{}); inc.PrintUtil.printList(i32, list); _ = try std.io.getStdIn().reader().readByte(); }
https://raw.githubusercontent.com/codingonion/hello-algo-zig/8a860aec2e5d5b30653b6611224fcbc823055d2b/chapter_tree/binary_tree_dfs.zig
// SPDX-License-Identifier: MIT // SPDX-FileCopyrightText: 2024 Lee Cannon <leecannon@leecannon.xyz> const std = @import("std"); const LibraryDependency = @import("LibraryDependency.zig"); const ApplicationDescription = @This(); /// The name of the application: /// - used for the path to the root file `apps/{name}/{name}.zig` /// - used in any build steps created for the application name: []const u8, /// The applications dependencies. dependencies: []const LibraryDependency = &.{}, /// Allows for custom configuration of the application. custom_configuration: ?*const fn ( b: *std.Build, application_description: ApplicationDescription, exe: *std.Build.Step.Compile, ) void = null,
https://raw.githubusercontent.com/CascadeOS/CascadeOS/07e8248e8a189b1ff74c21b60f0eb80bfe6f9574/build/ApplicationDescription.zig
//! Creating paths and manipulating path data. const std = @import("std"); const c = @import("../c.zig"); const PathDataType = @import("../enums.zig").PathDataType; const Error = @import("../utilities/error_handling.zig").Error; /// Convenience struct to iterate over the data elements in a Cairo path. const PathIterator = struct { /// Index for the data elements. The increment varies according the header /// of the PathDataType (see the next() method). i: usize, /// Number of elements in the data array. An empty path has num_data = 0. num_data: c_int, /// Elements in the path. A path is represented as an array of /// cairo_path_data_t, which is a C union of headers and points. /// It's an optional pointer, since an empty path has no data elements. data: ?[*]c.union__cairo_path_data_t, const Self = @This(); /// Get the next PathDataType from the array of cairo_path_data_t elements. pub fn next(self: *Self) ?PathDataType { if (self.i >= self.num_data) { return null; } // The value of step varies, since the length value of the header is the // number of array elements for the current portion including the header // (ie. length == 1 + # of points) // https://cairographics.org/manual/cairo-Paths.html#cairo-path-data-t defer self.i += @intCast(usize, self.data.?[self.i].header.length); // step return PathDataType.fromCairoEnum(self.data.?[self.i].header.type); } }; // TODO: add method to construct a Path manually (useful in tests and maybe elsewhere). /// Wrapper for the Cairo cairo_path_t C struct. /// Note that most of the functions defined in the cairo-Paths section of the /// Cairo C API are defined in zig-cairo Context, since they require a cairo_t /// as their first parameter. pub const Path = struct { /// The original cairo_path_t C struct. /// https://cairographics.org/manual/cairo-Paths.html#cairo-path-t c_ptr: *c.struct_cairo_path, const Self = @This(); /// Immediately release all memory associated with the wrapped cairo_path_t. /// https://cairographics.org/manual/cairo-Paths.html#cairo-path-destroy pub fn destroy(self: *Self) void { c.cairo_path_destroy(self.c_ptr); } /// Convenience method to avoid having to manually iterate over /// cairo_path_data_t, which is an optional C pointer of unknown length. pub fn iterator(self: *Self) PathIterator { // TODO: it would be nicer to use a Zig slice. How can I build it from a // C pointer? return PathIterator{ .i = 0, .data = self.c_ptr.data, // it's @ptrCast(?[*]c.union__cairo_path_data_t, self.c_ptr.data); .num_data = self.c_ptr.num_data, }; } // TODO: read Cairo source code to understand which status to check here. /// Check whether an error has previously occurred for this path. /// https://cairographics.org/manual/cairo-cairo-t.html#cairo-status pub fn status(c_ptr: *c.struct_cairo_path) !void { const c_integer = c_ptr.status; return switch (c_integer) { c.CAIRO_STATUS_SUCCESS => {}, // nothing to do if successful c.CAIRO_STATUS_NO_MEMORY => Error.NoMemory, c.CAIRO_STATUS_INVALID_PATH_DATA => Error.InvalidPathData, else => std.debug.panic("cairo_status_t member {} not handled.", .{c_integer}), }; } };
https://raw.githubusercontent.com/jackdbd/zig-cairo/c2736f512b5a48a5ad38a15973b2879166da1d8a/src/drawing/path.zig
const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); const use_native_backend = b.option(bool, "native-backend", "Use Zig's native x86 backend for compilation") orelse false; const exe = b.addExecutable(.{ .name = "cellulator", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, .use_llvm = !use_native_backend, .use_lld = !use_native_backend, }); const spoon = b.dependency("shovel", .{ .target = target, .optimize = optimize, }).module("shovel"); const wcwidth = b.dependency("wcwidth", .{ .target = target, .optimize = optimize, }).module("wcwidth"); const ziglua = b.dependency("ziglua", .{ .target = target, .optimize = optimize, .lang = .lua54, }).module("ziglua"); exe.root_module.addImport("ziglua", ziglua); exe.root_module.addImport("spoon", spoon); exe.root_module.addImport("wcwidth", wcwidth); 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 program"); run_step.dependOn(&run_cmd.step); const filter = b.option([]const u8, "test-filter", "Skip tests that do not match filter"); const tests = b.addTest(.{ .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, .filter = filter, .use_llvm = !use_native_backend, .use_lld = !use_native_backend, }); const fast_tests = b.option(bool, "fast-tests", "Skip slow tests") orelse false; const opts = b.addOptions(); opts.addOption(bool, "fast_tests", fast_tests); tests.root_module.addOptions("compile_opts", opts); tests.root_module.addImport("ziglua", ziglua); tests.root_module.addImport("spoon", spoon); tests.root_module.addImport("wcwidth", wcwidth); const run_tests = b.addRunArtifact(tests); const test_step = b.step("test", "Run all unit tests"); test_step.dependOn(&run_tests.step); const test_exe_step = b.step("test-exe", "Build test executable"); const install_step = b.addInstallArtifact(tests, .{}); test_exe_step.dependOn(&install_step.step); }
https://raw.githubusercontent.com/efjimm/Cellulator/ddd3986732591780485279d2ba08c8ffb1eed7d7/build.zig
const zss = @import("zss"); const tokenize = zss.syntax.tokenize; const parse = zss.syntax.parse; const Utf8String = zss.util.Utf8String; const std = @import("std"); pub fn main() !u8 { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len > 2) return 1; var stdout = std.io.getStdOut().writer(); const input = try std.io.getStdIn().reader().readAllAlloc(allocator, 1_000_000); defer allocator.free(input); const string = Utf8String{ .data = input }; if (args.len == 1 or std.mem.eql(u8, args[1], "stylesheet")) { const source = try parse.Source.init(string); var tree = try parse.parseCssStylesheet(source, allocator); defer tree.deinit(allocator); try zss.syntax.ComponentTree.debug.print(tree, allocator, stdout); } else if (std.mem.eql(u8, args[1], "components")) { const source = try parse.Source.init(string); var tree = try parse.parseListOfComponentValues(source, allocator); defer tree.deinit(allocator); try zss.syntax.ComponentTree.debug.print(tree, allocator, stdout); } else if (std.mem.eql(u8, args[1], "tokens")) { const source = try tokenize.Source.init(string); var location = tokenize.Source.Location{}; var i: usize = 0; while (true) { const next = try zss.syntax.tokenize.nextToken(source, location); location = next.next_location; try stdout.print("{}: {s}\n", .{ i, @tagName(next.token) }); i += 1; if (next.token == .token_eof) break; } } else { return 1; } return 0; }
https://raw.githubusercontent.com/chadwain/zss/e65690f7f0802222f300e7fbe70bc41f2d202030/examples/parse.zig
const bun = @import("root").bun; const std = @import("std"); const LineOffsetTable = bun.sourcemap.LineOffsetTable; const SourceMap = bun.sourcemap; const Bitset = bun.bit_set.DynamicBitSetUnmanaged; const Output = bun.Output; const prettyFmt = Output.prettyFmt; /// Our code coverage currently only deals with lines of code, not statements or branches. /// JSC doesn't expose function names in their coverage data, so we don't include that either :(. /// Since we only need to store line numbers, our job gets simpler /// /// We can use two bitsets to store code coverage data for a given file /// 1. executable_lines /// 2. lines_which_have_executed /// /// Not all lines of code are executable. Comments, whitespace, empty lines, etc. are not executable. /// It's not a problem for anyone if comments, whitespace, empty lines etc are not executed, so those should always be omitted from coverage reports /// /// We use two bitsets since the typical size will be decently small, /// bitsets are simple and bitsets are relatively fast to construct and query /// pub const CodeCoverageReport = struct { source_url: bun.JSC.ZigString.Slice, executable_lines: Bitset, lines_which_have_executed: Bitset, functions: std.ArrayListUnmanaged(Block), functions_which_have_executed: Bitset, stmts_which_have_executed: Bitset, stmts: std.ArrayListUnmanaged(Block), total_lines: u32 = 0, pub const Block = struct { start_line: u32 = 0, end_line: u32 = 0, }; pub fn linesCoverageFraction(this: *const CodeCoverageReport) f64 { var intersected = this.executable_lines.clone(bun.default_allocator) catch @panic("OOM"); defer intersected.deinit(bun.default_allocator); intersected.setIntersection(this.lines_which_have_executed); const total_count: f64 = @floatFromInt(this.executable_lines.count()); if (total_count == 0) { return 1.0; } const intersected_count: f64 = @floatFromInt(intersected.count()); return (intersected_count / total_count); } pub fn stmtsCoverageFraction(this: *const CodeCoverageReport) f64 { const total_count: f64 = @floatFromInt(this.stmts.items.len); if (total_count == 0) { return 1.0; } return ((@as(f64, @floatFromInt(this.stmts_which_have_executed.count()))) / (total_count)); } pub fn functionCoverageFraction(this: *const CodeCoverageReport) f64 { const total_count: f64 = @floatFromInt(this.functions.items.len); if (total_count == 0) { return 1.0; } return (@as(f64, @floatFromInt(this.functions_which_have_executed.count())) / total_count); } pub fn writeFormatWithValues( filename: []const u8, max_filename_length: usize, vals: CoverageFraction, failing: CoverageFraction, failed: bool, writer: anytype, indent_name: bool, comptime enable_colors: bool, ) !void { if (comptime enable_colors) { if (failed) { try writer.writeAll(comptime prettyFmt("<r><b><red>", true)); } else { try writer.writeAll(comptime prettyFmt("<r><b><green>", true)); } } if (indent_name) { try writer.writeAll(" "); } try writer.writeAll(filename); try writer.writeByteNTimes(' ', (max_filename_length - filename.len + @as(usize, @intFromBool(!indent_name)))); try writer.writeAll(comptime prettyFmt("<r><d> | <r>", enable_colors)); if (comptime enable_colors) { if (vals.functions < failing.functions) { try writer.writeAll(comptime prettyFmt("<b><red>", true)); } else { try writer.writeAll(comptime prettyFmt("<b><green>", true)); } } try writer.print("{d: >7.2}", .{vals.functions * 100.0}); // try writer.writeAll(comptime prettyFmt("<r><d> | <r>", enable_colors)); // if (comptime enable_colors) { // // if (vals.stmts < failing.stmts) { // try writer.writeAll(comptime prettyFmt("<d>", true)); // // } else { // // try writer.writeAll(comptime prettyFmt("<d>", true)); // // } // } // try writer.print("{d: >8.2}", .{vals.stmts * 100.0}); try writer.writeAll(comptime prettyFmt("<r><d> | <r>", enable_colors)); if (comptime enable_colors) { if (vals.lines < failing.lines) { try writer.writeAll(comptime prettyFmt("<b><red>", true)); } else { try writer.writeAll(comptime prettyFmt("<b><green>", true)); } } try writer.print("{d: >7.2}", .{vals.lines * 100.0}); } pub fn writeFormat( report: *const CodeCoverageReport, max_filename_length: usize, fraction: *CoverageFraction, base_path: []const u8, writer: anytype, comptime enable_colors: bool, ) !void { const failing = fraction.*; const fns = report.functionCoverageFraction(); const lines = report.linesCoverageFraction(); const stmts = report.stmtsCoverageFraction(); fraction.functions = fns; fraction.lines = lines; fraction.stmts = stmts; const failed = fns < failing.functions or lines < failing.lines; // or stmts < failing.stmts; fraction.failing = failed; var filename = report.source_url.slice(); if (base_path.len > 0) { filename = bun.path.relative(base_path, filename); } try writeFormatWithValues( filename, max_filename_length, fraction.*, failing, failed, writer, true, enable_colors, ); try writer.writeAll(comptime prettyFmt("<r><d> | <r>", enable_colors)); var executable_lines_that_havent_been_executed = report.lines_which_have_executed.clone(bun.default_allocator) catch @panic("OOM"); defer executable_lines_that_havent_been_executed.deinit(bun.default_allocator); executable_lines_that_havent_been_executed.toggleAll(); // This sets statements in executed scopes executable_lines_that_havent_been_executed.setIntersection(report.executable_lines); var iter = executable_lines_that_havent_been_executed.iterator(.{}); var start_of_line_range: usize = 0; var prev_line: usize = 0; var is_first = true; while (iter.next()) |next_line| { if (next_line == (prev_line + 1)) { prev_line = next_line; continue; } else if (is_first and start_of_line_range == 0 and prev_line == 0) { start_of_line_range = next_line; prev_line = next_line; continue; } if (is_first) { is_first = false; } else { try writer.print(comptime prettyFmt("<r><d>,<r>", enable_colors), .{}); } if (start_of_line_range == prev_line) { try writer.print(comptime prettyFmt("<red>{d}", enable_colors), .{start_of_line_range + 1}); } else { try writer.print(comptime prettyFmt("<red>{d}-{d}", enable_colors), .{ start_of_line_range + 1, prev_line + 1 }); } prev_line = next_line; start_of_line_range = next_line; } if (prev_line != start_of_line_range) { if (is_first) { is_first = false; } else { try writer.print(comptime prettyFmt("<r><d>,<r>", enable_colors), .{}); } if (start_of_line_range == prev_line) { try writer.print(comptime prettyFmt("<red>{d}", enable_colors), .{start_of_line_range + 1}); } else { try writer.print(comptime prettyFmt("<red>{d}-{d}", enable_colors), .{ start_of_line_range + 1, prev_line + 1 }); } } } pub fn deinit(this: *CodeCoverageReport, allocator: std.mem.Allocator) void { this.executable_lines.deinit(allocator); this.lines_which_have_executed.deinit(allocator); this.functions.deinit(allocator); this.stmts.deinit(allocator); this.functions_which_have_executed.deinit(allocator); this.stmts_which_have_executed.deinit(allocator); } extern fn CodeCoverage__withBlocksAndFunctions( *bun.JSC.VM, i32, *anyopaque, bool, *const fn ( *Generator, [*]const BasicBlockRange, usize, usize, bool, ) callconv(.C) void, ) bool; const Generator = struct { allocator: std.mem.Allocator, byte_range_mapping: *ByteRangeMapping, result: *?CodeCoverageReport, pub fn do( this: *@This(), blocks_ptr: [*]const BasicBlockRange, blocks_len: usize, function_start_offset: usize, ignore_sourcemap: bool, ) callconv(.C) void { const blocks: []const BasicBlockRange = blocks_ptr[0..function_start_offset]; var function_blocks: []const BasicBlockRange = blocks_ptr[function_start_offset..blocks_len]; if (function_blocks.len > 1) { function_blocks = function_blocks[1..]; } if (blocks.len == 0) { return; } this.result.* = this.byte_range_mapping.generateCodeCoverageReportFromBlocks( this.allocator, this.byte_range_mapping.source_url, blocks, function_blocks, ignore_sourcemap, ) catch null; } }; pub fn generate( globalThis: *bun.JSC.JSGlobalObject, allocator: std.mem.Allocator, byte_range_mapping: *ByteRangeMapping, ignore_sourcemap_: bool, ) ?CodeCoverageReport { bun.JSC.markBinding(@src()); const vm = globalThis.vm(); var result: ?CodeCoverageReport = null; var generator = Generator{ .result = &result, .allocator = allocator, .byte_range_mapping = byte_range_mapping, }; if (!CodeCoverage__withBlocksAndFunctions( vm, byte_range_mapping.source_id, &generator, ignore_sourcemap_, &Generator.do, )) { return null; } return result; } }; const BasicBlockRange = extern struct { startOffset: c_int = 0, endOffset: c_int = 0, hasExecuted: bool = false, executionCount: usize = 0, }; pub const ByteRangeMapping = struct { line_offset_table: LineOffsetTable.List = .{}, source_id: i32, source_url: bun.JSC.ZigString.Slice, pub fn isLessThan(_: void, a: ByteRangeMapping, b: ByteRangeMapping) bool { return bun.strings.order(a.source_url.slice(), b.source_url.slice()) == .lt; } pub const HashMap = std.HashMap(u64, ByteRangeMapping, bun.IdentityContext(u64), std.hash_map.default_max_load_percentage); pub fn deinit(this: *ByteRangeMapping) void { this.line_offset_table.deinit(bun.default_allocator); } pub threadlocal var map: ?*HashMap = null; pub fn generate(str: bun.String, source_contents_str: bun.String, source_id: i32) callconv(.C) void { var _map = map orelse brk: { map = bun.JSC.VirtualMachine.get().allocator.create(HashMap) catch @panic("OOM"); map.?.* = HashMap.init(bun.JSC.VirtualMachine.get().allocator); break :brk map.?; }; var slice = str.toUTF8(bun.default_allocator); const hash = bun.hash(slice.slice()); var entry = _map.getOrPut(hash) catch @panic("Out of memory"); if (entry.found_existing) { entry.value_ptr.deinit(); } var source_contents = source_contents_str.toUTF8(bun.default_allocator); defer source_contents.deinit(); entry.value_ptr.* = compute(source_contents.slice(), source_id, slice); } pub fn getSourceID(this: *ByteRangeMapping) callconv(.C) i32 { return this.source_id; } pub fn find(path: bun.String) callconv(.C) ?*ByteRangeMapping { var slice = path.toUTF8(bun.default_allocator); defer slice.deinit(); var map_ = map orelse return null; const hash = bun.hash(slice.slice()); const entry = map_.getPtr(hash) orelse return null; return entry; } pub fn generateCodeCoverageReportFromBlocks( this: *ByteRangeMapping, allocator: std.mem.Allocator, source_url: bun.JSC.ZigString.Slice, blocks: []const BasicBlockRange, function_blocks: []const BasicBlockRange, ignore_sourcemap: bool, ) !CodeCoverageReport { const line_starts = this.line_offset_table.items(.byte_offset_to_start_of_line); var executable_lines: Bitset = Bitset{}; var lines_which_have_executed: Bitset = Bitset{}; const parsed_mappings_ = bun.JSC.VirtualMachine.get().source_mappings.get( source_url.slice(), ); var functions = std.ArrayListUnmanaged(CodeCoverageReport.Block){}; try functions.ensureTotalCapacityPrecise(allocator, function_blocks.len); errdefer functions.deinit(allocator); var functions_which_have_executed: Bitset = try Bitset.initEmpty(allocator, function_blocks.len); errdefer functions_which_have_executed.deinit(allocator); var stmts_which_have_executed: Bitset = try Bitset.initEmpty(allocator, blocks.len); errdefer stmts_which_have_executed.deinit(allocator); var stmts = std.ArrayListUnmanaged(CodeCoverageReport.Block){}; try stmts.ensureTotalCapacityPrecise(allocator, function_blocks.len); errdefer stmts.deinit(allocator); errdefer executable_lines.deinit(allocator); errdefer lines_which_have_executed.deinit(allocator); var line_count: u32 = 0; if (ignore_sourcemap or parsed_mappings_ == null) { line_count = @truncate(line_starts.len); executable_lines = try Bitset.initEmpty(allocator, line_count); lines_which_have_executed = try Bitset.initEmpty(allocator, line_count); for (blocks, 0..) |block, i| { const min: usize = @intCast(@min(block.startOffset, block.endOffset)); const max: usize = @intCast(@max(block.startOffset, block.endOffset)); var min_line: u32 = std.math.maxInt(u32); var max_line: u32 = 0; const has_executed = block.hasExecuted or block.executionCount > 0; for (min..max) |byte_offset| { const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; const line_start_byte_offset = line_starts[new_line_index]; if (line_start_byte_offset >= byte_offset) { continue; } const line: u32 = @intCast(new_line_index); min_line = @min(min_line, line); max_line = @max(max_line, line); executable_lines.set(@intCast(new_line_index)); if (has_executed) { lines_which_have_executed.set(@intCast(new_line_index)); } } if (min_line != std.math.maxInt(u32)) { if (has_executed) stmts_which_have_executed.set(i); try stmts.append(allocator, .{ .start_line = min_line, .end_line = max_line, }); } } for (function_blocks, 0..) |function, i| { const min: usize = @intCast(@min(function.startOffset, function.endOffset)); const max: usize = @intCast(@max(function.startOffset, function.endOffset)); var min_line: u32 = std.math.maxInt(u32); var max_line: u32 = 0; for (min..max) |byte_offset| { const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; const line_start_byte_offset = line_starts[new_line_index]; if (line_start_byte_offset >= byte_offset) { continue; } const line: u32 = @intCast(new_line_index); min_line = @min(min_line, line); max_line = @max(max_line, line); } const did_fn_execute = function.executionCount > 0 or function.hasExecuted; // only mark the lines as executable if the function has not executed // functions that have executed have non-executable lines in them and thats fine. if (!did_fn_execute) { const end = @min(max_line, line_count); for (min_line..end) |line| { executable_lines.set(line); lines_which_have_executed.unset(line); } } try functions.append(allocator, .{ .start_line = min_line, .end_line = max_line, }); if (did_fn_execute) functions_which_have_executed.set(i); } } else if (parsed_mappings_) |parsed_mapping| { line_count = @as(u32, @truncate(parsed_mapping.input_line_count)) + 1; executable_lines = try Bitset.initEmpty(allocator, line_count); lines_which_have_executed = try Bitset.initEmpty(allocator, line_count); for (blocks, 0..) |block, i| { const min: usize = @intCast(@min(block.startOffset, block.endOffset)); const max: usize = @intCast(@max(block.startOffset, block.endOffset)); var min_line: u32 = std.math.maxInt(u32); var max_line: u32 = 0; const has_executed = block.hasExecuted or block.executionCount > 0; for (min..max) |byte_offset| { const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; const line_start_byte_offset = line_starts[new_line_index]; if (line_start_byte_offset >= byte_offset) { continue; } const column_position = byte_offset -| line_start_byte_offset; if (SourceMap.Mapping.find(parsed_mapping.mappings, @intCast(new_line_index), @intCast(column_position))) |point| { if (point.original.lines < 0) continue; const line: u32 = @as(u32, @intCast(point.original.lines)); executable_lines.set(line); if (has_executed) { lines_which_have_executed.set(line); } min_line = @min(min_line, line); max_line = @max(max_line, line); } } if (min_line != std.math.maxInt(u32)) { try stmts.append(allocator, .{ .start_line = min_line, .end_line = max_line, }); if (has_executed) stmts_which_have_executed.set(i); } } for (function_blocks, 0..) |function, i| { const min: usize = @intCast(@min(function.startOffset, function.endOffset)); const max: usize = @intCast(@max(function.startOffset, function.endOffset)); var min_line: u32 = std.math.maxInt(u32); var max_line: u32 = 0; for (min..max) |byte_offset| { const new_line_index = LineOffsetTable.findIndex(line_starts, .{ .start = @intCast(byte_offset) }) orelse continue; const line_start_byte_offset = line_starts[new_line_index]; if (line_start_byte_offset >= byte_offset) { continue; } const column_position = byte_offset -| line_start_byte_offset; if (SourceMap.Mapping.find(parsed_mapping.mappings, @intCast(new_line_index), @intCast(column_position))) |point| { if (point.original.lines < 0) continue; const line: u32 = @as(u32, @intCast(point.original.lines)); min_line = @min(min_line, line); max_line = @max(max_line, line); } } // no sourcemaps? ignore it if (min_line == std.math.maxInt(u32) and max_line == 0) { continue; } const did_fn_execute = function.executionCount > 0 or function.hasExecuted; // only mark the lines as executable if the function has not executed // functions that have executed have non-executable lines in them and thats fine. if (!did_fn_execute) { const end = @min(max_line, line_count); for (min_line..end) |line| { executable_lines.set(line); lines_which_have_executed.unset(line); } } try functions.append(allocator, .{ .start_line = min_line, .end_line = max_line, }); if (did_fn_execute) functions_which_have_executed.set(i); } } else { unreachable; } return CodeCoverageReport{ .source_url = source_url, .functions = functions, .executable_lines = executable_lines, .lines_which_have_executed = lines_which_have_executed, .total_lines = line_count, .stmts = stmts, .functions_which_have_executed = functions_which_have_executed, .stmts_which_have_executed = stmts_which_have_executed, }; } pub fn findExecutedLines( globalThis: *bun.JSC.JSGlobalObject, source_url: bun.String, blocks_ptr: [*]const BasicBlockRange, blocks_len: usize, function_start_offset: usize, ignore_sourcemap: bool, ) callconv(.C) bun.JSC.JSValue { var this = ByteRangeMapping.find(source_url) orelse return bun.JSC.JSValue.null; const blocks: []const BasicBlockRange = blocks_ptr[0..function_start_offset]; var function_blocks: []const BasicBlockRange = blocks_ptr[function_start_offset..blocks_len]; if (function_blocks.len > 1) { function_blocks = function_blocks[1..]; } var url_slice = source_url.toUTF8(bun.default_allocator); defer url_slice.deinit(); var report = this.generateCodeCoverageReportFromBlocks(bun.default_allocator, url_slice, blocks, function_blocks, ignore_sourcemap) catch { globalThis.throwOutOfMemory(); return .zero; }; defer report.deinit(bun.default_allocator); var coverage_fraction = CoverageFraction{}; var mutable_str = bun.MutableString.initEmpty(bun.default_allocator); defer mutable_str.deinit(); var buffered_writer = mutable_str.bufferedWriter(); var writer = buffered_writer.writer(); report.writeFormat(source_url.utf8ByteLength(), &coverage_fraction, "", &writer, false) catch { globalThis.throwOutOfMemory(); return .zero; }; buffered_writer.flush() catch { globalThis.throwOutOfMemory(); return .zero; }; var str = bun.String.createUTF8(mutable_str.toOwnedSliceLeaky()); defer str.deref(); return str.toJS(globalThis); } pub fn compute(source_contents: []const u8, source_id: i32, source_url: bun.JSC.ZigString.Slice) ByteRangeMapping { return ByteRangeMapping{ .line_offset_table = LineOffsetTable.generate(bun.JSC.VirtualMachine.get().allocator, source_contents, 0), .source_id = source_id, .source_url = source_url, }; } }; comptime { if (bun.Environment.isNative) { @export(ByteRangeMapping.generate, .{ .name = "ByteRangeMapping__generate" }); @export(ByteRangeMapping.findExecutedLines, .{ .name = "ByteRangeMapping__findExecutedLines" }); @export(ByteRangeMapping.find, .{ .name = "ByteRangeMapping__find" }); @export(ByteRangeMapping.getSourceID, .{ .name = "ByteRangeMapping__getSourceID" }); } } pub const CoverageFraction = struct { functions: f64 = 0.9, lines: f64 = 0.9, // This metric is less accurate right now stmts: f64 = 0.75, failing: bool = false, };
https://raw.githubusercontent.com/resourcemod/sidejs/2eb853f13a96d6434fe9dba78906a390b1eb90fa/src/js/bun-bun-v1.0.30/src/sourcemap/CodeCoverage.zig
const std = @import("std"); const utils = @import("utils.zig"); pub fn main() !void { const lines = utils.readFileLines("day3_input.txt"); var map = utils.makeMap(utils.Pos, usize); var p = utils.Pos{}; var steps: usize = 0; var it = std.mem.separate(lines[0], ","); while (it.next()) |d| { var n = utils.parseInt(i64, d[1..]); while (n > 0) : (n -= 1) { p = p.move(utils.Dir.fromUDLR(d[0])); steps += 1; _ = try map.put(p, steps); } } p = utils.Pos{}; steps = 0; it = std.mem.separate(lines[1], ","); var bestDist: i64 = 99999999; var bestSteps: usize = 99999999; while (it.next()) |d| { var n = utils.parseInt(i64, d[1..]); while (n > 0) : (n -= 1) { p = p.move(utils.Dir.fromUDLR(d[0])); steps += 1; if (map.getValue(p)) |other_steps| { bestDist = std.math.min(bestDist, p.manhattan_dist(utils.Pos{})); bestSteps = std.math.min(bestSteps, steps + other_steps); } } } utils.println(bestDist); utils.println(bestSteps); }
https://raw.githubusercontent.com/lukechampine/advent/fb5db7bc2f413760f6e8f4982b905d664bff0279/2019/day3.zig
const std = @import("std"); const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); const expect = std.testing.expect; pub fn main() !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = &arena.allocator; const input = try stdin.readAllAlloc(allocator, 9268); const result = try run(allocator, input); try stdout.print("{}\n", .{result}); } pub fn run(allocator: *std.mem.Allocator, input: []const u8) !isize { var map = std.AutoHashMap(Point, usize).init(allocator); defer map.deinit(); var lines = std.mem.tokenize(input, "\n"); while (lines.next()) |line| { const entry = try parse_entry(line); try mark(&map, entry.from); const x_dir = calculate_dir(entry.from.x, entry.to.x); const y_dir = calculate_dir(entry.from.y, entry.to.y); var x: isize = @intCast(isize, entry.from.x) + x_dir; var y: isize = @intCast(isize, entry.from.y) + y_dir; const to_x: isize = @intCast(isize, entry.to.x); const to_y: isize = @intCast(isize, entry.to.y); while (x != to_x or y != to_y) : ({ x += x_dir; y += y_dir; }) { try mark(&map, .{ .x = @intCast(usize, x), .y = @intCast(usize, y) }); } try mark(&map, entry.to); } var sum: isize = 0; var counts = map.valueIterator(); while (counts.next()) |count| { if (count.* >= 2) { sum += 1; } } return sum; } const Point = struct { x: usize, y: usize, }; const Line = struct { from: Point, to: Point, }; fn parse_entry(entry: []const u8) !Line { var it = std.mem.tokenize(entry, " "); const from = try parse_point(it.next().?); try expect(std.mem.eql(u8, it.next().?, "->")); const to = try parse_point(it.next().?); return Line{ .from = from, .to = to }; } fn parse_point(s: []const u8) !Point { var it = std.mem.tokenize(s, ","); return Point{ .x = try std.fmt.parseInt(usize, it.next().?, 10), .y = try std.fmt.parseInt(usize, it.next().?, 10), }; } fn mark(map: *std.AutoHashMap(Point, usize), point: Point) !void { var entry = try map.getOrPut(point); if (!entry.found_existing) { entry.value_ptr.* = 0; } entry.value_ptr.* += 1; } fn calculate_dir(from: usize, to: usize) isize { if (to > from) { return 1; } else if (to < from) { return -1; } else { return 0; } } fn print_map(map: std.AutoHashMap(Point, usize), width: usize, height: usize) void { std.debug.print("\n", .{}); var y: usize = 0; while (y < height) : (y += 1) { var x: usize = 0; while (x < width) : (x += 1) { if (map.get(Point{ .x = x, .y = y })) |count| { std.debug.print("{}", .{count}); } else { std.debug.print(".", .{}); } } std.debug.print("\n", .{}); } std.debug.print("\n", .{}); } test "example scenario" { const result = try run(std.testing.allocator, \\0,9 -> 5,9 \\8,0 -> 0,8 \\9,4 -> 3,4 \\2,2 -> 2,1 \\7,0 -> 7,4 \\6,4 -> 2,0 \\0,9 -> 2,9 \\3,4 -> 1,4 \\0,0 -> 8,8 \\5,5 -> 8,2 ); try expect(result == 12); }
https://raw.githubusercontent.com/dradtke/advent/8c420c8ff28f102c56e5c05852c6d2845edb2ce5/2021/zig/day05/part2.zig
// // ------------------------------------------------------------ // TOP SECRET TOP SECRET TOP SECRET TOP SECRET TOP SECRET // ------------------------------------------------------------ // // Are you ready for the THE TRUTH about Zig string literals? // // Here it is: // // @TypeOf("foo") == *const [3:0]u8 // // Which means a string literal is a "constant pointer to a // zero-terminated (null-terminated) fixed-size array of u8". // // Now you know. You've earned it. Welcome to the secret club! // // ------------------------------------------------------------ // // Why do we bother using a zero/null sentinel to terminate // strings in Zig when we already have a known length? // // Versatility! Zig strings are compatible with C strings (which // are null-terminated) AND can be coerced to a variety of other // Zig types: // // const a: [5]u8 = "array".*; // const b: *const [16]u8 = "pointer to array"; // const c: []const u8 = "slice"; // const d: [:0]const u8 = "slice with sentinel"; // const e: [*:0]const u8 = "many-item pointer with sentinel"; // const f: [*]const u8 = "many-item pointer"; // // All but 'f' may be printed. (A many-item pointer without a // sentinel is not safe to print because we don't know where it // ends!) // const print = @import("std").debug.print; const WeirdContainer = struct { data: [*]const u8, length: usize, }; pub fn main() void { // WeirdContainer is an awkward way to house a string. // // Being a many-item pointer (with no sentinel termination), // the 'data' field "loses" the length information AND the // sentinel termination of the string literal "Weird Data!". // // Luckily, the 'length' field makes it possible to still // work with this value. const foo = WeirdContainer{ .data = "Weird Data!", .length = 11, }; // How do we get a printable value from 'foo'? One way is to // turn it into something with a known length. We do have a // length... You've actually solved this problem before! // // Here's a big hint: do you remember how to take a slice? const printable: []const u8 = foo.data[0..foo.length]; print("{s}\n", .{printable}); }
https://raw.githubusercontent.com/JolliestJames/ziglings/9bb24bb99e4811c1ad6c78db654cffc0758138b6/exercises/077_sentinels2.zig
const std = @import("std"); /// Zig version. When writing code that supports multiple versions of Zig, prefer /// feature detection (i.e. with `@hasDecl` or `@hasField`) over version checks. pub const zig_version = std.SemanticVersion.parse("0.9.1") catch unreachable; /// Temporary until self-hosted is feature complete. pub const zig_is_stage2 = false; /// Temporary until self-hosted supports the `cpu.arch` value. pub const stage2_arch: std.Target.Cpu.Arch = .aarch64; /// Temporary until self-hosted can call `std.Target.x86.featureSetHas` at comptime. pub const stage2_x86_cx16 = false; pub const output_mode = std.builtin.OutputMode.Exe; pub const link_mode = std.builtin.LinkMode.Dynamic; pub const is_test = false; pub const single_threaded = false; pub const abi = std.Target.Abi.gnu; pub const cpu: std.Target.Cpu = .{ .arch = .aarch64, .model = &std.Target.aarch64.cpu.apple_a14, .features = std.Target.aarch64.featureSet(&[_]std.Target.aarch64.Feature{ .aes, .aggressive_fma, .alternate_sextload_cvt_f32_pattern, .altnzcv, .am, .arith_bcc_fusion, .arith_cbz_fusion, .ccdp, .ccidx, .ccpp, .complxnum, .contextidr_el2, .crc, .crypto, .disable_latency_sched_heuristic, .dit, .dotprod, .flagm, .fp16fml, .fp_armv8, .fptoint, .fullfp16, .fuse_address, .fuse_aes, .fuse_arith_logic, .fuse_crypto_eor, .fuse_csel, .fuse_literals, .jsconv, .lor, .lse, .mpam, .neon, .nv, .pan, .pan_rwv, .pauth, .perfmon, .pmu, .predres, .ras, .rcpc, .rcpc_immo, .rdm, .sb, .sel2, .sha2, .sha3, .specrestrict, .ssbs, .tlb_rmi, .tracev8_4, .uaops, .v8_1a, .v8_2a, .v8_3a, .v8_4a, .v8a, .vh, .zcm, .zcz, .zcz_gp, }), }; pub const os = std.Target.Os{ .tag = .macos, .version_range = .{ .semver = .{ .min = .{ .major = 12, .minor = 1, .patch = 0, }, .max = .{ .major = 12, .minor = 1, .patch = 0, }, }}, }; pub const target = std.Target{ .cpu = cpu, .os = os, .abi = abi, }; pub const object_format = std.Target.ObjectFormat.macho; pub const mode = std.builtin.Mode.Debug; pub const link_libc = true; pub const link_libcpp = false; pub const have_error_return_tracing = true; pub const valgrind_support = false; pub const position_independent_code = true; pub const position_independent_executable = true; pub const strip_debug_info = false; pub const code_model = std.builtin.CodeModel.default;
https://raw.githubusercontent.com/pierback/glob-delete/4cf18a452d3acaf281698a1f70804c7eccb11dfb/zig-cache/o/9782c9449f2be494fc3cfbf74ce55b1c/builtin.zig
const std = @import("std"); const zaudio = @import("zaudio"); fn data_callback(device: *zaudio.Device, output: ?*anyopaque, input: ?*const anyopaque, frame_count: u32) callconv(.C) void { _ = frame_count; _ = input; _ = output; _ = device; std.log.info("here", .{}); } fn create() !void { var cfg = zaudio.Device.Config.init(.playback); cfg.playback.format = .float32; cfg.playback.channels = 2; cfg.sample_rate = 48_000; cfg.data_callback = data_callback; const device = try zaudio.Device.create(null, cfg); try device.start(); std.time.sleep(1_000_000_000); try device.stop(); } pub fn main() !void { // Prints to stderr (it's a shortcut based on `std.io.getStdErr()`) std.debug.print("All your {s} are belong to us.\n", .{"codebase"}); try create(); } test "simple test" { var list = std.ArrayList(i32).init(std.testing.allocator); defer list.deinit(); // try commenting this out and see if zig detects the memory leak! try list.append(42); try std.testing.expectEqual(@as(i32, 42), list.pop()); }
https://raw.githubusercontent.com/marloncalvo/space-glow-zig/bbb28bc53f3895931d966bf7f245a0faa71755cb/src/main.zig
// The Table struct presents a "view" over our rx buffer that we // can query without needing to allocate memory into, say, a hash // map. For small tables (I assume we'll only see smallish tables) // this should be fine performance-wise. const std = @import("std"); const mem = std.mem; const WireBuffer = @import("wire.zig").WireBuffer; pub const Table = struct { // a slice of our rx_buffer (with its own head and end) buf: WireBuffer = undefined, len: usize = 0, const Self = @This(); pub fn init(buffer: []u8) Table { var t = Table{ .buf = WireBuffer.init(buffer), .len = 0, }; t.buf.writeU32(0); return t; } // Lookup a value in the table. Note we need to know the type // we expect at compile time. We might not know this at which // point I guess I need a union. By the time we call lookup we // should already have validated the frame, so I think we maybe // can't error here. pub fn lookup(self: *Self, comptime T: type, key: []const u8) ?T { defer self.buf.reset(); const length = self.buf.readU32(); while (self.buf.isMoreData()) { const current_key = self.buf.readShortString(); const correct_key = std.mem.eql(u8, key, current_key); const t = self.buf.readU8(); switch (t) { 'F' => { var table = self.buf.readTable(); if (@TypeOf(table) == T and correct_key) return table; }, 't' => { const b = self.buf.readBool(); if (@TypeOf(b) == T and correct_key) return b; }, 's' => { const s = self.buf.readShortString(); if (@TypeOf(s) == T and correct_key) return s; }, 'S' => { const s = self.buf.readLongString(); if (@TypeOf(s) == T and correct_key) return s; }, else => { // TODO: support all types as continue will return garbage continue; }, } } return null; } pub fn insertTable(self: *Self, key: []const u8, table: *Table) void { self.buf.writeShortString(key); self.buf.writeU8('F'); self.buf.writeTable(table); self.updateLength(); } pub fn insertBool(self: *Self, key: []const u8, boolean: bool) void { self.buf.writeShortString(key); self.buf.writeU8('t'); self.buf.writeBool(boolean); self.updateLength(); } // Apparently actual implementations don't use 's' for short string // (and therefore) I assume they don't use short strings (in tables) // at all // pub fn insertShortString(self: *Self, key: []u8, string: []u8) void { // self.buf.writeShortString(key); // self.buf.writeU8('s'); // self.buf.writeShortString(string); // self.updateLength(); // } pub fn insertLongString(self: *Self, key: []const u8, string: []const u8) void { self.buf.writeShortString(key); self.buf.writeU8('S'); self.buf.writeLongString(string); self.updateLength(); } fn updateLength(self: *Self) void { mem.writeInt(u32, @ptrCast(*[@sizeOf(u32)]u8, &self.buf.mem[0]), @intCast(u32, self.buf.head - @sizeOf(u32)), .Big); } pub fn print(self: *Self) void { for (self.buf.mem[0..self.buf.head]) |x| { std.debug.warn("0x{x:0>2} ", .{x}); } std.debug.warn("\n", .{}); } };
https://raw.githubusercontent.com/malcolmstill/zig-amqp/6f2ae2061a9fb6e6ca9d6770f3cfdc8e67c5fa8a/src/table.zig
const lib = @import("lib"); const assert = lib.assert; const config = lib.config; const Allocator = lib.Allocator; const ELF = lib.ELF(64); const log = lib.log.scoped(.uefi); const PhysicalAddress = lib.PhysicalAddress; const PhysicalMemoryRegion = lib.PhysicalMemoryRegion; const VirtualAddress = lib.VirtualAddress; const VirtualMemoryRegion = lib.VirtualMemoryRegion; const bootloader = @import("bootloader"); const uefi = @import("uefi"); const BootloaderInformation = uefi.BootloaderInformation; const BootServices = uefi.BootServices; const ConfigurationTable = uefi.ConfigurationTable; const FileProtocol = uefi.FileProtocol; const Handle = uefi.Handle; const LoadedImageProtocol = uefi.LoadedImageProtocol; const LoadKernelFunction = uefi.LoadKernelFunction; const MemoryCategory = uefi.MemoryCategory; const MemoryDescriptor = uefi.MemoryDescriptor; const ProgramSegment = uefi.ProgramSegment; const Protocol = uefi.Protocol; const page_table_estimated_size = uefi.page_table_estimated_size; const SimpleFilesystemProtocol = uefi.SimpleFilesystemProtocol; const SystemTable = uefi.SystemTable; const privileged = @import("privileged"); const ACPI = privileged.ACPI; const PageAllocator = privileged.PageAllocator; pub const writer = privileged.writer; const CPU = privileged.arch.CPU; const GDT = privileged.arch.x86_64.GDT; const paging = privileged.arch.paging; const Stage = enum { boot_services, after_boot_services, trampoline, }; pub const std_options = struct { pub const log_level = lib.std.log.Level.debug; pub fn logFn(comptime level: lib.std.log.Level, comptime scope: @TypeOf(.EnumLiteral), comptime format: []const u8, args: anytype) void { const scope_prefix = if (scope == .default) ": " else "(" ++ @tagName(scope) ++ "): "; const prefix = "[" ++ @tagName(level) ++ "] " ++ scope_prefix; switch (lib.cpu.arch) { .x86_64 => { lib.format(writer, prefix ++ format ++ "\n", args) catch {}; }, else => @compileError("Unsupported CPU architecture"), } } }; const practical_memory_map_descriptor_size = 0x30; const practical_memory_map_descriptor_count = 256; pub fn panic(message: []const u8, _: ?*lib.StackTrace, _: ?usize) noreturn { writer.writeAll("[uefi] [PANIC] ") catch {}; writer.writeAll(message) catch {}; writer.writeAll("\r\n") catch {}; privileged.shutdown(.failure); } const Filesystem = extern struct { root: *FileProtocol, buffer: [0x200 * 10]u8 = undefined, pub fn deinitialize(filesystem: *Filesystem) !void { _ = filesystem; } pub fn readFile(filesystem: *Filesystem, file_path: []const u8, file_buffer: []u8) ![]const u8 { const file = try filesystem.openFile(file_path); var size: u64 = file_buffer.len; try uefi.Try(file.handle.read(&size, file_buffer.ptr)); if (file_buffer.len < size) @panic("readFileFast"); return file_buffer[0..size]; } pub fn sneakFile(filesystem: *Filesystem, file_path: []const u8, size: usize) ![]const u8 { _ = size; const file = try filesystem.readFile(file_path, &filesystem.buffer); return file; } const FileDescriptor = struct { handle: *FileProtocol, path_size: u32, }; pub fn getFileSize(filesystem: *Filesystem, file_path: []const u8) !u32 { const file = try filesystem.openFile(file_path); var file_info_buffer: [@sizeOf(uefi.FileInfo) + 0x100]u8 align(@alignOf(uefi.FileInfo)) = undefined; var file_info_size = file_info_buffer.len; try uefi.Try(file.handle.getInfo(&uefi.FileInfo.guid, &file_info_size, &file_info_buffer)); if (file_info_buffer.len < file_info_size) @panic("getFileSize"); const file_info = @as(*uefi.FileInfo, @ptrCast(&file_info_buffer)); return @as(u32, @intCast(file_info.file_size)); } fn openFile(filesystem: *Filesystem, file_path: []const u8) !FileDescriptor { const init = @fieldParentPtr(Initialization, "filesystem", filesystem); if (init.exited_boot_services) { return Error.boot_services_exited; } var file: *FileProtocol = undefined; var path_buffer: [256:0]u16 = undefined; const length = try lib.unicode.utf8ToUtf16Le(&path_buffer, file_path); path_buffer[length] = 0; const path = path_buffer[0..length :0]; const uefi_path = if (path[0] == '/') path[1..] else path; try uefi.Try(filesystem.root.open(&file, uefi_path, FileProtocol.efi_file_mode_read, 0)); const result = FileDescriptor{ .handle = file, .path_size = @as(u32, @intCast(path.len * @sizeOf(u16))), }; return result; } pub fn getSectorSize(filesystem: *Filesystem) u16 { _ = filesystem; return lib.default_sector_size; } }; const MemoryMap = extern struct { size: usize = buffer_len, key: usize, descriptor_size: usize, descriptor_version: u32, buffer: [buffer_len]u8 align(@alignOf(MemoryDescriptor)) = undefined, offset: usize = 0, entry_count: u32, const buffer_len = practical_memory_map_descriptor_size * practical_memory_map_descriptor_count; pub fn getEntryCount(memory_map: *const MemoryMap) u32 { return memory_map.entry_count; } pub fn next(memory_map: *MemoryMap) !?bootloader.MemoryMapEntry { if (memory_map.offset < memory_map.size) { const entry = @as(*MemoryDescriptor, @ptrCast(@alignCast(memory_map.buffer[memory_map.offset..].ptr))).*; memory_map.offset += memory_map.descriptor_size; const result = bootloader.MemoryMapEntry{ .region = PhysicalMemoryRegion.new(.{ .address = PhysicalAddress.new(entry.physical_start), .size = entry.number_of_pages << uefi.page_shifter, }), .type = switch (entry.type) { .ReservedMemoryType, .LoaderCode, .LoaderData, .BootServicesCode, .BootServicesData, .RuntimeServicesCode, .RuntimeServicesData, .ACPIReclaimMemory, .ACPIMemoryNVS, .MemoryMappedIO, .MemoryMappedIOPortSpace, .PalCode, .PersistentMemory => .reserved, .ConventionalMemory => .usable, .UnusableMemory => .bad_memory, else => @panic("Unknown type"), }, }; return result; } return null; } fn getHostRegion(memory_map: *MemoryMap, length_size_tuples: bootloader.LengthSizeTuples) !PhysicalMemoryRegion { var memory: []align(uefi.page_size) u8 = undefined; const memory_size = length_size_tuples.getAlignedTotalSize(); try uefi.Try(memory_map.boot_services.allocatePages(.AllocateAnyPages, .LoaderData, memory_size >> uefi.page_shifter, &memory.ptr)); memory.len = memory_size; @memset(memory, 0); return PhysicalMemoryRegion.fromByteSlice(.{ .slice = memory }); } }; const Initialization = struct { filesystem: Filesystem, framebuffer: bootloader.Framebuffer, architecture: switch (lib.cpu.arch) { .x86_64 => struct { rsdp: *ACPI.RSDP.Descriptor1, }, else => @compileError("Architecture not supported"), }, boot_services: *uefi.BootServices, handle: uefi.Handle, // system_table: *uefi.SystemTable, early_initialized: bool = false, filesystem_initialized: bool = false, memory_map_initialized: bool = false, framebuffer_initialized: bool = false, exited_boot_services: bool = false, memory_map: MemoryMap, pub fn getRSDPAddress(init: *Initialization) u32 { return @as(u32, @intCast(@intFromPtr(init.architecture.rsdp))); } pub fn getCPUCount(init: *Initialization) !u32 { return switch (lib.cpu.arch) { .x86_64 => blk: { const madt_header = try init.architecture.rsdp.findTable(.APIC); const madt = @as(*align(1) const ACPI.MADT, @ptrCast(madt_header)); break :blk madt.getCPUCount(); }, else => @compileError("Architecture not supported"), }; } pub fn initialize(init: *Initialization) !void { defer init.early_initialized = true; const system_table = uefi.getSystemTable(); const handle = uefi.getHandle(); const boot_services = system_table.boot_services orelse @panic("boot services"); const out = system_table.con_out orelse @panic("con out"); try uefi.Try(out.reset(true)); try uefi.Try(out.clearScreen()); init.* = .{ .memory_map = .{ .key = 0, .descriptor_size = 0, .descriptor_version = 0, .entry_count = 0, }, .filesystem = .{ .root = blk: { const loaded_image = try Protocol.open(LoadedImageProtocol, boot_services, handle); const filesystem_protocol = try Protocol.open(SimpleFilesystemProtocol, boot_services, loaded_image.device_handle orelse @panic("No device handle")); var root: *FileProtocol = undefined; try uefi.Try(filesystem_protocol.openVolume(&root)); break :blk root; }, }, .framebuffer = blk: { const gop = try Protocol.locate(uefi.GraphicsOutputProtocol, boot_services); const pixel_format_info: struct { red_color_mask: bootloader.Framebuffer.ColorMask, blue_color_mask: bootloader.Framebuffer.ColorMask, green_color_mask: bootloader.Framebuffer.ColorMask, bpp: u8, } = switch (gop.mode.info.pixel_format) { .PixelRedGreenBlueReserved8BitPerColor => .{ .red_color_mask = .{ .size = 8, .shift = 0 }, .green_color_mask = .{ .size = 8, .shift = 8 }, .blue_color_mask = .{ .size = 8, .shift = 16 }, .bpp = 32, }, .PixelBlueGreenRedReserved8BitPerColor => .{ .red_color_mask = .{ .size = 8, .shift = 16 }, .green_color_mask = .{ .size = 8, .shift = 8 }, .blue_color_mask = .{ .size = 8, .shift = 0 }, .bpp = 32, }, .PixelBitMask, .PixelBltOnly => @panic("Unsupported pixel format"), .PixelFormatMax => @panic("Corrupted pixel format"), }; break :blk bootloader.Framebuffer{ .address = gop.mode.frame_buffer_base, .pitch = @divExact(gop.mode.info.pixels_per_scan_line * pixel_format_info.bpp, @bitSizeOf(u8)), .width = gop.mode.info.horizontal_resolution, .height = gop.mode.info.vertical_resolution, .bpp = pixel_format_info.bpp, .red_mask = pixel_format_info.red_color_mask, .green_mask = pixel_format_info.green_color_mask, .blue_mask = pixel_format_info.blue_color_mask, .memory_model = 0x06, }; }, .boot_services = boot_services, .handle = handle, .architecture = switch (lib.cpu.arch) { .x86_64 => .{ .rsdp = for (system_table.configuration_table[0..system_table.number_of_table_entries]) |configuration_table| { if (configuration_table.vendor_guid.eql(ConfigurationTable.acpi_20_table_guid)) { break @as(*ACPI.RSDP.Descriptor1, @ptrCast(@alignCast(configuration_table.vendor_table))); } } else return Error.rsdp_not_found, }, else => @compileError("Architecture not supported"), }, }; _ = boot_services.getMemoryMap(&init.memory_map.size, @as([*]MemoryDescriptor, @ptrCast(&init.memory_map.buffer)), &init.memory_map.key, &init.memory_map.descriptor_size, &init.memory_map.descriptor_version); init.memory_map.entry_count = @as(u32, @intCast(@divExact(init.memory_map.size, init.memory_map.descriptor_size))); assert(init.memory_map.entry_count > 0); init.filesystem_initialized = true; init.memory_map_initialized = true; init.framebuffer_initialized = true; } pub fn deinitializeMemoryMap(init: *Initialization) !void { if (!init.exited_boot_services) { // Add the region for the bootloader information init.memory_map.size += init.memory_map.descriptor_size; const expected_memory_map_size = init.memory_map.size; const expected_memory_map_descriptor_size = init.memory_map.descriptor_size; const expected_memory_map_descriptor_version = init.memory_map.descriptor_version; blk: while (init.memory_map.size < MemoryMap.buffer_len) : (init.memory_map.size += init.memory_map.descriptor_size) { uefi.Try(init.boot_services.getMemoryMap(&init.memory_map.size, @as([*]MemoryDescriptor, @ptrCast(&init.memory_map.buffer)), &init.memory_map.key, &init.memory_map.descriptor_size, &init.memory_map.descriptor_version)) catch continue; init.exited_boot_services = true; break :blk; } else { @panic("Cannot satisfy memory map requirements"); } if (expected_memory_map_size != init.memory_map.size) { log.warn("Old memory map size: {}. New memory map size: {}", .{ expected_memory_map_size, init.memory_map.size }); } if (expected_memory_map_descriptor_size != init.memory_map.descriptor_size) { @panic("Descriptor size change"); } if (expected_memory_map_descriptor_version != init.memory_map.descriptor_version) { @panic("Descriptor version change"); } const real_memory_map_entry_count = @divExact(init.memory_map.size, init.memory_map.descriptor_size); const expected_memory_map_entry_count = @divExact(expected_memory_map_size, expected_memory_map_descriptor_size); const diff = @as(i16, @intCast(expected_memory_map_entry_count)) - @as(i16, @intCast(real_memory_map_entry_count)); if (diff < 0) { @panic("Memory map entry count diff < 0"); } // bootloader_information.configuration.memory_map_diff = @intCast(u8, diff); log.debug("Exiting boot services...", .{}); try uefi.Try(init.boot_services.exitBootServices(init.handle, init.memory_map.key)); log.debug("Exited boot services...", .{}); privileged.arch.disableInterrupts(); } init.memory_map.offset = 0; } pub fn ensureLoaderIsMapped(init: *Initialization, minimal_paging: paging.Specific, page_allocator: PageAllocator, bootloader_information: *bootloader.Information) !void { _ = bootloader_information; // Actually mapping the whole uefi executable so we don't have random problems with code being dereferenced by the trampoline switch (lib.cpu.arch) { .x86_64 => { const trampoline_code_start = @intFromPtr(&bootloader.arch.x86_64.jumpToKernel); try init.deinitializeMemoryMap(); while (try init.memory_map.next()) |entry| { if (entry.region.address.value() < trampoline_code_start and trampoline_code_start < entry.region.address.offset(entry.region.size).value()) { const code_physical_region = entry.region; const code_virtual_address = code_physical_region.address.toIdentityMappedVirtualAddress(); try minimal_paging.map(code_physical_region.address, code_virtual_address, code_physical_region.size, .{ .write = false, .execute = true }, page_allocator); return; } } }, else => @compileError("Architecture not supported"), } return Error.map_failed; } pub fn ensureStackIsMapped(init: *Initialization, minimal_paging: paging.Specific, page_allocator: PageAllocator) !void { const rsp = asm volatile ( \\mov %rsp, %[rsp] : [rsp] "=r" (-> u64), ); while (try init.memory_map.next()) |entry| { if (entry.region.address.value() < rsp and rsp < entry.region.address.offset(entry.region.size).value()) { const rsp_region_physical_address = entry.region.address; const rsp_region_virtual_address = rsp_region_physical_address.toIdentityMappedVirtualAddress(); if (entry.region.size == 0) return Error.region_empty; try minimal_paging.map(rsp_region_physical_address, rsp_region_virtual_address, entry.region.size, .{ .write = true, .execute = false }, page_allocator); return; } } return Error.map_failed; } }; var initialization: Initialization = undefined; const Error = error{ map_failed, region_empty, rsdp_not_found, boot_services_exited, }; pub fn main() noreturn { // var filesystem: Filesystem = .{ // .boot_services = boot_services, // .handle = handle, // .root = undefined, // }; // var mmap: MemoryMap = .{ // .boot_services = boot_services, // .handle = handle, // }; // var fb = Framebuffer{ // .boot_services = boot_services, // }; // var vas = VAS{ // .mmap = &mmap, // }; initialization.initialize() catch |err| { @panic(@errorName(err)); }; bootloader.Information.initialize(&initialization, .birth, .uefi) catch |err| { @panic(@errorName(err)); }; }
https://raw.githubusercontent.com/birth-software/birth/23a3c67990b504c487bbcf21dc4f76e898fa23b8/src/bootloader/birth/uefi/main.zig
const std = @import("std"); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const allocator = gpa.allocator(); const args = try std.process.argsAlloc(allocator); defer std.process.argsFree(allocator, args); if (args.len != 2) { std.log.err("Usage: {s} <program>", .{args[0]}); return error.BadArgCount; } var program_file = try std.fs.cwd().openFile(args[1], .{}); defer program_file.close(); try setup_interpret(program_file, allocator); } // `std.math.big.int`s are too unwieldy for this const Nat = u256; fn setup_interpret(program: std.fs.File, allocator: std.mem.Allocator) !void { var registers: [3]Nat = .{ 0, 0, 0 }; var stacks: [2]*std.ArrayList(Nat) = undefined; stacks[0] = @constCast(&std.ArrayList(Nat).init(allocator)); defer stacks[0].deinit(); stacks[1] = @constCast(&std.ArrayList(Nat).init(allocator)); defer stacks[1].deinit(); try interpret( program, allocator, &registers, &stacks, ); } const Command = enum(u8) { dw_not = '~', // (base - 1) - a dw_or = '|', // min(a + b, (base - 1)) dw_xor = '^', // (a + b) mod base dw_and = '&', // min(a * b, (base - 1)) dw_mand = '*', // (a * b) mod base shift_left = '<', // A * pow(base, B) shift_right = '>', // floor(A / pow(base, B)) digit_count = '/', set_base = '_', swap_stacks = '$', cycle_registers = '%', push_a = '@', pop_a = '!', push_0 = '0', push_1 = '1', skip_block = '?', loop_block = '"', start_block = '(', end_block = ')', input = 'i', output = 'o', comment = '#', _, }; const RegisterId = enum(u2) { a, b, c, }; fn interpret( program: std.fs.File, allocator: std.mem.Allocator, registers: *[3]Nat, stacks: *[2]*std.ArrayList(Nat), ) !void { const stdin = std.io.getStdIn().reader(); const stdout = std.io.getStdOut().writer(); var blocks = std.ArrayList(usize).init(allocator); defer blocks.deinit(); var base: Nat = 2; // which register is treated as A var a_register: u2 = 0; // which stack is treated as X var x_stack: u1 = 0; const program_reader = program.reader(); const seekable_program = program.seekableStream(); while (program_reader.readByte() catch null) |byte| { // TODO: better error handling errdefer { const stderr = std.io.getStdErr().writer(); stderr.print( "Error at index {d}: {c}\n", .{ // if you have a larger file, you have bigger problems @as( i64, @intCast(seekable_program.getPos() catch std.math.maxInt(u64)), ), byte, }, ) catch {}; } const command: Command = @enumFromInt(byte); switch (command) { .dw_not => { try push( stacks[x_stack], try dwNot( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.c, a_register)], base, ), ); }, .dw_or => { try push( stacks[x_stack], try dwOr( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], registers[getRegisterId(.c, a_register)], base, ), ); }, .dw_xor => { try push( stacks[x_stack], try dwXor( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], registers[getRegisterId(.c, a_register)], base, ), ); }, .dw_and => { try push( stacks[x_stack], try dwAnd( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], registers[getRegisterId(.c, a_register)], base, ), ); }, .dw_mand => { try push( stacks[x_stack], try dwMand( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], registers[getRegisterId(.c, a_register)], base, ), ); }, .shift_left => { try push( stacks[x_stack], try shiftLeft( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], base, ), ); }, .shift_right => { try push( stacks[x_stack], try shiftRight( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], base, ), ); }, .digit_count => { try push( stacks[x_stack], try digitCount( registers[getRegisterId(.a, a_register)], base, ), ); }, .set_base => { base = registers[getRegisterId(.a, a_register)]; if (base < 2) return error.BaseUndeflow; }, .swap_stacks => { x_stack +%= 1; }, .cycle_registers => { if (a_register == 0) a_register = 2 else a_register -= 1; }, .push_a => { try push( stacks[x_stack], registers[getRegisterId(.a, a_register)], ); }, .pop_a => { registers[getRegisterId(.a, a_register)] = try pop(stacks[x_stack]); }, .push_0 => { try push( stacks[x_stack], 0, ); }, .push_1 => { try push( stacks[x_stack], 1, ); }, .skip_block => { if (try checkLeq( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], registers[getRegisterId(.c, a_register)], base, )) { var depth: usize = 1; while (program_reader.readByte() catch null) |inner_byte| : ({ if (depth == 0) break; }) { if (inner_byte == @intFromEnum(Command.start_block)) { depth += 1; } else if (inner_byte == @intFromEnum(Command.end_block)) { depth -= 1; } } else { // reached end of file if (depth - 1 != 0) return error.UnclosedBlock else return; } try seekable_program.seekBy(-1); // go to the end_block } }, .loop_block => { if (try checkGt( registers[getRegisterId(.a, a_register)], registers[getRegisterId(.b, a_register)], registers[getRegisterId(.c, a_register)], base, )) { try seekable_program.seekTo(blocks.getLastOrNull() orelse 0); } }, .start_block => { try blocks.append(try seekable_program.getPos()); }, .end_block => { _ = blocks.popOrNull() orelse return error.UnopenedBlock; }, .input => { var input_buffer = std.ArrayList(u8).init(allocator); defer input_buffer.deinit(); try stdin.streamUntilDelimiter(input_buffer.writer(), '\n', null); try push( stacks[x_stack], try std.fmt.parseUnsigned(Nat, input_buffer.items, 10), ); }, .output => { try std.fmt.formatInt( registers[getRegisterId(.a, a_register)], 10, .lower, .{}, stdout, ); try stdout.writeByte('\n'); }, .comment => { while (program_reader.readByte() catch null) |inner_byte| { if (inner_byte == '\n') break; } }, _ => { if (!std.ascii.isWhitespace(byte)) return error.BadCommand; }, } } } fn getRegisterId(register_id: RegisterId, a_id: u2) u2 { const id_plus_offset: u3 = @intFromEnum(register_id) + a_id; return @intCast(id_plus_offset % 3); } fn push(stack: *std.ArrayList(Nat), value: Nat) !void { try stack.append(value); } fn pop(stack: *std.ArrayList(Nat)) !Nat { return stack.popOrNull() orelse return error.StackUnderflow; } fn dwNot(a: Nat, c: Nat, base: Nat) !Nat { var result: Nat = a; var index: Nat = 0; while (index < c) : (index += 1) { const current_digit = try getDigit(result, base, index); result = try setDigit( result, base, index, (base - 1) - current_digit, ); } return result; } fn dwOr(a: Nat, b: Nat, c: Nat, base: Nat) !Nat { var result: Nat = a; var index: Nat = 0; while (index < c) : (index += 1) { const current_digit_a = try getDigit(a, base, index); const current_digit_b = try getDigit(b, base, index); result = try setDigit( result, base, index, @min(current_digit_a + current_digit_b, base - 1), ); } return result; } fn dwXor(a: Nat, b: Nat, c: Nat, base: Nat) !Nat { var result: Nat = a; var index: Nat = 0; while (index < c) : (index += 1) { const current_digit_a = try getDigit(a, base, index); const current_digit_b = try getDigit(b, base, index); result = try setDigit( result, base, index, (current_digit_a + current_digit_b) % base, ); } return result; } fn dwAnd(a: Nat, b: Nat, c: Nat, base: Nat) !Nat { var result: Nat = a; var index: Nat = 0; while (index < c) : (index += 1) { const current_digit_a = try getDigit(a, base, index); const current_digit_b = try getDigit(b, base, index); result = try setDigit( result, base, index, @min(current_digit_a * current_digit_b, base - 1), ); } return result; } // modular and fn dwMand(a: Nat, b: Nat, c: Nat, base: Nat) !Nat { var result: Nat = a; var index: Nat = 0; while (index < c) : (index += 1) { const current_digit_a = try getDigit(a, base, index); const current_digit_b = try getDigit(b, base, index); result = try setDigit( result, base, index, (current_digit_a * current_digit_b) % base, ); } return result; } fn shiftLeft(a: Nat, b: Nat, base: Nat) !Nat { const shift_amount = try std.math.powi(Nat, base, b); return try std.math.mul(Nat, a, shift_amount); } fn shiftRight(a: Nat, b: Nat, base: Nat) !Nat { const shift_amount = try std.math.powi(Nat, base, b); return a / shift_amount; } fn digitCount(a: Nat, base: Nat) !Nat { if (a == 0) return 0; return std.math.log_int(Nat, base, a) + 1; } fn checkLeq(a: Nat, b: Nat, c: Nat, base: Nat) !bool { var index: Nat = c + 1; while (index > 0) { index -= 1; const a_digit = try getDigit(a, base, index); const b_digit = try getDigit(b, base, index); if (a_digit > b_digit) { return false; } else if (a_digit == b_digit) { continue; } else { return true; } } return true; } fn checkGt(a: Nat, b: Nat, c: Nat, base: Nat) !bool { var index: Nat = c + 1; while (index > 0) { index -= 1; const a_digit = try getDigit(a, base, index); const b_digit = try getDigit(b, base, index); if (a_digit > b_digit) { return true; } else if (a_digit == b_digit) { continue; } else { return false; } } return false; } fn getDigit( value: Nat, base: Nat, index: Nat, ) !Nat { const place_value = try std.math.powi(Nat, base, index); const shifted_down = value / place_value; return shifted_down % base; } fn setDigit( value: Nat, base: Nat, index: Nat, new_digit: Nat, ) !Nat { if (new_digit >= base) return error.DigitTooLarge; const place_value = try std.math.powi(Nat, base, index); const old_digit = try getDigit(value, base, index); const shifted_old_digit = old_digit * place_value; const shifted_new_digit = new_digit * place_value; const value_without_digit = value - shifted_old_digit; const result = try std.math.add(Nat, value_without_digit, shifted_new_digit); return result; }
https://raw.githubusercontent.com/DivergentClouds/wise/c44b3155ff9be92f0858291eef93547ab37c80c5/src/main.zig
const std = @import("std"); const print = std.debug.print; const tools = @import("../utils/tools.zig"); const cmd = @import("../utils/commands.zig"); const Cli = @import("../main.zig").Cli; pub fn app(cli: Cli) !void { try tools.titleMaker("ZIX Configuration"); cmd.configPrint(cli.repo, tools.boolToString(cli.update), tools.boolToString(cli.diff)); if (try tools.confirm(true, null)) { try tools.titleMaker("Git Pull"); try tools.runCmd(cmd.gitPullCmd); try tools.titleMaker("Nix Update"); try tools.titleMaker("Git Changes"); try tools.titleMaker("Nixos Rebuild"); try tools.titleMaker("Nix Diff"); try tools.runCmd(cmd.nixDiffCmd); try tools.titleMaker("Current Directory"); try tools.runCmd("ls -a"); } }
https://raw.githubusercontent.com/alvaro17f/zix/bebb630f1b670a8f0a53358c4c96b92dc7454d51/src/app/app.zig
const std = @import("std"); const c = @import("c.zig").c; const DefaultPrng = std.rand.DefaultPrng; const CELL_WIDTH = @import("main.zig").CELL_WIDTH; const CELL_HEIGHT = @import("main.zig").CELL_HEIGHT; pub const Cell = enum { dead, alive }; var gpa = std.heap.GeneralPurposeAllocator(.{}){}; const allocator = gpa.allocator(); const IndexOutOfBoundsError = error{OutOfBounds}; pub const Grid = struct { pub const Self = @This(); width: u32, height: u32, current_cells: []Cell, next_gen_cells: []Cell, generation: u32, prng: DefaultPrng, rects: []c.SDL_Rect, renderer: ?*c.SDL_Renderer, pub fn init(width: u32, height: u32, renderer: ?*c.SDL_Renderer) !Self { const current_cells: []Cell = try allocator.alloc(Cell, width * height); const next_gen_cells: []Cell = try allocator.alloc(Cell, width * height); const rects: []c.SDL_Rect = try allocator.alloc(c.SDL_Rect, width * height); const prng = DefaultPrng.init(blk: { var seed: u64 = undefined; try std.os.getrandom(std.mem.asBytes(&seed)); break :blk seed; }); return Self{ .width = width, .height = height, .current_cells = current_cells, .next_gen_cells = next_gen_cells, .generation = 0, .prng = prng, .rects = rects, .renderer = renderer, }; } pub fn init_rects(self: *Self) void { const border_size: c_int = 2; for (0..self.height) |y| { for (0..self.width) |x| { const x_cint: c_int = @intCast(x); const y_cint: c_int = @intCast(y); const cell_width_cint: c_int = @intCast(CELL_WIDTH); const cell_height_cint: c_int = @intCast(CELL_HEIGHT); self.rects[y * self.width + x] = c.SDL_Rect{ .x = (x_cint * cell_width_cint) + border_size, .y = (y_cint * cell_height_cint) + border_size, .w = cell_width_cint - (border_size * 2), .h = cell_height_cint - (border_size * 2), }; } } } pub fn deinit(self: Self) void { defer allocator.free(self.current_cells); defer allocator.free(self.next_gen_cells); defer allocator.free(self.rects); } /// Formula index(x, y) = y * width + x fn getIndex(self: Self, x: usize, y: usize) IndexOutOfBoundsError!usize { if (y >= 0 and y < self.height and x >= 0 and x < self.width) { return y * self.width + x; } else { return error.OutOfBounds; } } fn checkIndexOutOfBounds(self: Self, idx: usize) IndexOutOfBoundsError!void { if (idx < 0 or idx >= self.width * self.height) { return error.OutOfBounds; } } fn getX(self: Self, idx: usize) IndexOutOfBoundsError!u32 { try self.checkIndexOutOfBounds(idx); const idx_u32: u32 = @intCast(idx); return @mod(idx_u32, self.width); } fn getY(self: Self, idx: usize) IndexOutOfBoundsError!u32 { try self.checkIndexOutOfBounds(idx); return @intCast(idx / self.width); } /// Assumes that there is a finite board, so there are special /// check for the corner and top, right, bottom and left cases. fn liveNeighbourCount(self: Self, x: usize, y: usize) IndexOutOfBoundsError!u8 { var count: u8 = 0; // We skip calculating alive neighbours for the outer border of the board. if (y > 0 and y < self.height - 1 and x > 0 and x < self.width - 1) { // Every cell has 8 neigbours // TODO: This whole thing is pretty dogwater, need to find a better way var col: i32 = -1; var row: i32 = -1; while (row <= 1) : (row += 1) { while (col <= 1) : (col += 1) { // This is the check for the cell itself, should not do anything here. if (row == 0 and col == 0) { // continue } else { // TODO: This is sooo soo bad, find a better way const x_i32: i32 = @intCast(x); const y_i32: i32 = @intCast(y); const neighbour_x_idx = x_i32 + col; const neighbour_y_idx = y_i32 + row; const neighbour_x_idx_usize: usize = @intCast(neighbour_x_idx); const neighbour_y_idx_usize: usize = @intCast(neighbour_y_idx); const idx = try self.getIndex(neighbour_x_idx_usize, neighbour_y_idx_usize); if (self.current_cells[idx] == .alive) { count += 1; } } } col = -1; } } return count; } fn liveCellsCount(self: Self) u32 { var count: u32 = 0; for (self.current_cells) |cell| { if (cell == .alive) { count += 1; } } return count; } /// The universe of the Game of Life is an infinite two-dimensional orthogonal grid of square cells, /// each of which is in one of two possible states, alive or dead, or "populated" or "unpopulated". /// Every cell interacts with its eight neighbours, which are the cells that are horizontally, vertically, /// or diagonally adjacent. At each step in time, the following transitions occur: /// 1. Any live cell with fewer than two live neighbours dies, as if caused by underpopulation. /// 2. Any live cell with two or three live neighbours lives on to the next generation. /// 3. Any live cell with more than three live neighbours dies, as if by overpopulation. /// 4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction. pub fn tick(self: *Self) !void { // Make copy of the old cells state, this allocates each tick, which is pretty unecessary const next_gen_cells_many_ptr: [*]Cell = @ptrCast(self.next_gen_cells); clearCellsToDead(next_gen_cells_many_ptr, self.next_gen_cells.len); var idx: usize = 0; for (0..self.height) |y| { for (0..self.width) |x| { const live_neighbour_count = try self.liveNeighbourCount(x, y); const current_cell = self.current_cells[idx]; if (current_cell == .alive and live_neighbour_count < 2) { self.next_gen_cells[idx] = .dead; } else if (current_cell == .alive and (live_neighbour_count == 2 or live_neighbour_count == 3)) { self.next_gen_cells[idx] = .alive; } else if (current_cell == .alive and live_neighbour_count > 3) { self.next_gen_cells[idx] = .dead; } else if (self.current_cells[idx] == .dead and live_neighbour_count == 3) { self.next_gen_cells[idx] = .alive; } idx += 1; } } @memcpy(self.current_cells, self.next_gen_cells); self.generation += 1; } pub fn draw(self: Self) void { // Batching draw calls to rects, would increase performance //_ = c.SDL_SetRenderDrawColor(renderer, 100, 100, 100, 255); //_ = c.SDL_RenderDrawRects(renderer, cells_many_ptr, num_cells_horizontal_cint * num_cells_vertical_cint); //_ = c.SDL_SetRenderDrawColor(renderer, 255, 255, 255, 255); //_ = c.SDL_RenderFillRects(renderer, cells_many_ptr, num_cells_horizontal_cint * num_cells_vertical_cint); for (0..(self.width * self.height)) |rect_idx| { if (self.current_cells[rect_idx] == .alive) { _ = c.SDL_SetRenderDrawColor(self.renderer, 255, 255, 255, 255); _ = c.SDL_RenderFillRect(self.renderer, &self.rects[rect_idx]); } else { _ = c.SDL_SetRenderDrawColor(self.renderer, 100, 100, 100, 255); _ = c.SDL_RenderDrawRect(self.renderer, &self.rects[rect_idx]); _ = c.SDL_SetRenderDrawColor(self.renderer, 64, 64, 64, 255); _ = c.SDL_RenderFillRect(self.renderer, &self.rects[rect_idx]); } } c.SDL_RenderPresent(self.renderer); } pub fn handleMouseEvent(self: *Self, event: c.SDL_MouseButtonEvent, cell_width: c_int, cell_height: c_int) void { switch (event.button) { c.SDL_BUTTON_LEFT => { var x: c_int = 0; var y: c_int = 0; _ = c.SDL_GetMouseState(&x, &y); const rect_x = @divFloor(x, cell_width); const rect_y = @divFloor(y, cell_height); const width_cint: c_int = @intCast(self.width); const cell_idx = (rect_y * width_cint) + rect_x; const cell_idx_usize: usize = @intCast(cell_idx); if (self.current_cells[cell_idx_usize] == .alive) { self.current_cells[cell_idx_usize] = .dead; } else { self.current_cells[cell_idx_usize] = .alive; } }, else => {}, } } pub fn clearCellsToDead(cells: [*]Cell, len: usize) void { for (0..len) |idx| { cells[idx] = .dead; } } pub fn setCellsRandomlyAlive(self: *Self) void { for (0..self.width * self.height) |idx| { const rand = self.prng.random(); if (@mod(rand.int(u32), 4) == 0) { self.current_cells[idx] = .alive; } } } pub fn reset(self: *Self) void { const current_cells_many_ptr: [*]Cell = @ptrCast(self.current_cells); clearCellsToDead(current_cells_many_ptr, self.current_cells.len); const next_gen_cells_many_ptr: [*]Cell = @ptrCast(self.next_gen_cells); clearCellsToDead(next_gen_cells_many_ptr, self.next_gen_cells.len); } }; test "test getX" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); try std.testing.expectEqual(@as(u32, 0), try grid.getX(0)); try std.testing.expectEqual(@as(u32, 3), try grid.getX(3)); try std.testing.expectEqual(@as(u32, 9), try grid.getX(9)); try std.testing.expectEqual(@as(u32, 0), try grid.getX(10)); try std.testing.expectEqual(@as(u32, 3), try grid.getX(13)); try std.testing.expectEqual(@as(u32, 9), try grid.getX(19)); try std.testing.expectEqual(@as(u32, 9), try grid.getX(99)); // Test OutOfIndexError cases try std.testing.expectError(error.OutOfBounds, grid.getX(100)); } test "test getY" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); try std.testing.expectEqual(@as(u32, 0), try grid.getY(0)); try std.testing.expectEqual(@as(u32, 0), try grid.getY(9)); try std.testing.expectEqual(@as(u32, 1), try grid.getY(11)); try std.testing.expectEqual(@as(u32, 9), try grid.getY(99)); // Test OutOfIndexError cases try std.testing.expectError(error.OutOfBounds, grid.getY(100)); } test "test getIndex" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); // a: row = 1, col = 2, idx = 12 // b: row = 0, col = 0, idx = 0 // c: row = 8, col = 4, idx = 84 // d: row = 9, col = 9, idx = 99 // b * * * * * * * * * // * * a * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * c * * * * * // * * * * * * * * * d try std.testing.expectEqual(@as(usize, 0), try grid.getIndex(0, 0)); try std.testing.expectEqual(@as(usize, 12), try grid.getIndex(2, 1)); try std.testing.expectEqual(@as(usize, 84), try grid.getIndex(4, 8)); try std.testing.expectEqual(@as(usize, 99), try grid.getIndex(9, 9)); // Test OutOfIndexError cases try std.testing.expectError(error.OutOfBounds, grid.getIndex(10, 0)); } test "test liveNeighbourCount" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); // x= 2, y = 1 // * D D A * * * * * * // * A x D * * * * * * // * D A D * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * grid.current_cells[3] = .alive; grid.current_cells[11] = .alive; grid.current_cells[22] = .alive; try std.testing.expectEqual(@as(u8, 3), try grid.liveNeighbourCount(2, 1)); // x = 8, y = 8 // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * A // * * * * * * * * x * // * * * * * * * * * A grid.current_cells[79] = .alive; grid.current_cells[99] = .alive; try std.testing.expectEqual(@as(u8, 2), try grid.liveNeighbourCount(8, 8)); // Corner cases, all of these should return zero // x = 0, y = 0 // X * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * A // * * * * * * * * x * // * * * * * * * * * A } test "test liveNeighbourCount upper left corner" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); // x = 0, y = 0 // X A * * * * * * * * // A A * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * grid.current_cells[1] = .alive; grid.current_cells[10] = .alive; grid.current_cells[11] = .alive; try std.testing.expectEqual(@as(u8, 0), try grid.liveNeighbourCount(0, 0)); } test "test liveNeighbourCount upper right corner" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); // x = 9, y = 0 // * * * * * * * * A X // * * * * * * * * * A // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * grid.current_cells[8] = .alive; grid.current_cells[19] = .alive; try std.testing.expectEqual(@as(u8, 0), try grid.liveNeighbourCount(9, 0)); } test "test liveNeighbourCount lower right corner" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); // x = 9, y = 9 // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * A // * * * * * * * * A X grid.current_cells[89] = .alive; grid.current_cells[98] = .alive; try std.testing.expectEqual(@as(u8, 0), try grid.liveNeighbourCount(9, 9)); } test "test liveNeighbourCount lower left corner" { const grid_width: u32 = 10; const grid_height: u32 = 10; var grid = try Grid.init(grid_width, grid_height, null); // x = 0, y = 9 // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * * * * * * * * * * // * A * * * * * * * * // x * * * * * * * * * grid.current_cells[81] = .alive; try std.testing.expectEqual(@as(u8, 0), try grid.liveNeighbourCount(0, 9)); } test "test tick 1" { const grid_width: u32 = 4; const grid_height: u32 = 4; var grid = try Grid.init(grid_width, grid_height, null); const new_cells: [*]Cell = @ptrCast(grid.current_cells); Grid.clearCellsToDead(new_cells, grid.current_cells.len); // Cell to test // x = 2, y = 1, .alive // A * * * // * X * * // * * A * // * * * * grid.current_cells[0] = .alive; grid.current_cells[5] = .alive; grid.current_cells[10] = .alive; try std.testing.expectEqual(@as(u8, 2), try grid.liveNeighbourCount(1, 1)); const idx = try grid.getIndex(1, 1); try std.testing.expectEqual(Cell.alive, grid.current_cells[idx]); try grid.tick(); // Expected outcomefter tick // Cell to test // x = 2, y = 1, X .alive // A * * * // * X * * // * * A * // * * * * try std.testing.expectEqual(Cell.alive, grid.current_cells[idx]); try std.testing.expectEqual(@as(u32, 1), grid.liveCellsCount()); } test "test tick 2" { const grid_width: u32 = 5; const grid_height: u32 = 5; var grid = try Grid.init(grid_width, grid_height, null); const new_cells: [*]Cell = @ptrCast(grid.current_cells); Grid.clearCellsToDead(new_cells, grid.current_cells.len); // Cell to test // x = 2, y = 2, X is .alive, idx = 12 // * * * * * // * A * A * // * * X * * // * A * A * // * * * * * grid.current_cells[6] = .alive; grid.current_cells[8] = .alive; grid.current_cells[12] = .alive; grid.current_cells[16] = .alive; grid.current_cells[18] = .alive; try std.testing.expectEqual(@as(u8, 4), try grid.liveNeighbourCount(2, 2)); try std.testing.expectEqual(@as(u32, 5), grid.liveCellsCount()); const idx = try grid.getIndex(2, 2); try std.testing.expectEqual(Cell.alive, grid.current_cells[idx]); try grid.tick(); // Expected outcomefter tick // Cell to test // x = 2, y = 2, .dead, idx = 12 // * * * * * // * * A * * // * A X A * // * * A * * // * * * * * try std.testing.expectEqual(Cell.dead, grid.current_cells[idx]); try std.testing.expectEqual(Cell.alive, grid.current_cells[7]); try std.testing.expectEqual(Cell.alive, grid.current_cells[11]); try std.testing.expectEqual(Cell.alive, grid.current_cells[13]); try std.testing.expectEqual(Cell.alive, grid.current_cells[17]); try std.testing.expectEqual(@as(u32, 4), grid.liveCellsCount()); }
https://raw.githubusercontent.com/Skarsh/zig-conway/0fb702dbf4925d2a35e8b33b5d905246feb8470e/src/grid.zig
const std = @import("std"); const Point = @This(); x: f32 = 0, y: f32 = 0, pub fn nonZero(self: *const Point) bool { return (self.x != 0 or self.y != 0); } pub fn plus(self: *const Point, b: Point) Point { return Point{ .x = self.x + b.x, .y = self.y + b.y }; } pub fn diff(a: Point, b: Point) Point { return Point{ .x = a.x - b.x, .y = a.y - b.y }; } pub fn scale(self: *const Point, s: f32) Point { return Point{ .x = self.x * s, .y = self.y * s }; } pub fn equals(self: *const Point, b: Point) bool { return (self.x == b.x and self.y == b.y); } pub fn length(self: *const Point) f32 { return @sqrt((self.x * self.x) + (self.y * self.y)); } pub fn normalize(self: *const Point) Point { const d2 = self.x * self.x + self.y * self.y; if (d2 == 0) { return Point{ .x = 1.0, .y = 0.0 }; } else { const inv_len = 1.0 / @sqrt(d2); return Point{ .x = self.x * inv_len, .y = self.y * inv_len }; } } pub fn format(self: *const Point, comptime _: []const u8, _: std.fmt.FormatOptions, writer: anytype) !void { try std.fmt.format(writer, "Point{{ {d} {d} }}", .{ self.x, self.y }); }
https://raw.githubusercontent.com/david-vanderson/dvui/8645f753c1b2eb93f1bd795e2d24469f5493b670/src/Point.zig
const std = @import("std"); const Allocator = std.mem.Allocator; const Arr = std.ArrayListUnmanaged(u32); pub fn main() !void { var gpa = std.heap.GeneralPurposeAllocator(.{}){}; defer _ = gpa.deinit(); const alloc = gpa.allocator(); const program = program: { const program_text = program_text: { const in_file = in_file: { var args = std.process.args(); defer args.deinit(); const exe_name = try args.next(alloc) orelse return; defer alloc.free(exe_name); const path = try args.next(alloc) orelse { const stderr = std.io.getStdErr().writer(); stderr.print("Usage: {s} [infile]\n", .{exe_name}) catch {}; return; }; defer alloc.free(path); break :in_file try std.fs.cwd().openFile(path, .{}); }; defer in_file.close(); const max_size = 1024 * 1024; break :program_text try in_file.readToEndAlloc(alloc, max_size); }; defer alloc.free(program_text); var program = Arr{}; errdefer program.deinit(alloc); var iter = std.mem.split(u8, program_text, "\n"); while (iter.next()) |line_raw| { var line = line_raw; if (line.len > 1 and line[line.len - 1] == '\r') line.len -= 1; const val = std.fmt.parseInt(u32, line, 10) catch 0; try program.append(alloc, val); } break :program program; }; var state = State{ .memory = program }; defer state.deinit(alloc); const result = try state.exec(alloc); const stdout = std.io.getStdOut().writer(); stdout.print("{any}\n", .{result}) catch {}; } const State = struct { memory: Arr, stack: Arr = .{}, fn deinit(self: *State, alloc: Allocator) void { self.memory.deinit(alloc); self.stack.deinit(alloc); } fn get(self: State, idx: u32) u32 { return if (idx < self.memory.items.len) self.memory.items[idx] else 0; } fn set(self: *State, alloc: Allocator, idx: u32, val: u32) !void { if (idx == std.math.maxInt(usize)) @panic("too big..."); const padding = @as(usize, idx) + 1 -| self.memory.items.len; try self.memory.appendNTimes(alloc, 0, padding); self.memory.items[idx] = val; } fn pop(self: *State) u32 { return self.stack.popOrNull() orelse 0; } fn peekPtr(self: State) ?*u32 { const stack = self.stack.items; return if (stack.len > 0) &stack[stack.len - 1] else null; } fn peek(self: State) u32 { return (self.peekPtr() orelse return 0).*; } fn push(self: *State, alloc: Allocator, x: u32) !void { try self.stack.append(alloc, x); } fn exec(self: *State, alloc: Allocator) ![]const u32 { var idx: u32 = 0; while (true) { const next_idx = self.get(idx); const ht = self.stack.items.len; switch (next_idx % 10) { // PushNxt 0 => try self.push(alloc, self.get(next_idx +% 1)), // PushAddr 1 => try self.push(alloc, self.get(self.pop())), // PopAddr 2 => try self.set(alloc, self.pop(), self.pop()), // Duplicate 3 => try self.push(alloc, self.peek()), // Swap 4 => if (ht >= 2) { const stack = self.stack.items; std.mem.swap( u32, &stack[stack.len - 1], &stack[stack.len - 2], ); } else try self.push(alloc, 0), // Add 5 => if (ht >= 2) { const x = self.pop(); self.peekPtr().?.* +%= x; }, // Sub 6 => if (ht >= 2) { const x = self.pop(); self.peekPtr().?.* -%= x; } else if (ht == 1) { self.peekPtr().?.* *%= std.math.maxInt(u32); }, // Mul 7 => if (ht >= 2) { const x = self.pop(); self.peekPtr().?.* *%= x; }, // Div 8 => if (ht >= 2) { const x = self.pop(); if (x == 0) @panic("division by zero"); self.peekPtr().?.* /= x; }, // Quit 9 => { const next_next_idx = self.get(next_idx); return self.memory.items[next_next_idx..]; }, else => unreachable, } idx = next_idx; } } };
https://raw.githubusercontent.com/Reconcyl/eso/bc48a02d77517840fa86c95382aa5f02fa900f2c/morbusz/main.zig
const gfx = @import("gfx"); const math = @import("std").math; const Renderer = @import("Renderer.zig"); const Rect = Renderer.Rect; const Sprite = Renderer.Sprite; const effects_tex = gfx.effects; const teleport_tex = gfx.teleport; pub const hurt_fx = gfx.hurt; pub fn load() void { effects_tex.loadFromUrl("img/effects.png", 120, 24); teleport_tex.loadFromUrl("img/teleport.png", 24, 32); hurt_fx.loadFromUrl("img/hurt.png", 24, 24); } pub fn drawDeathEffect(x: i32, y: i32, counter: u32) void { const frame = @as(i32, @intCast((counter / 3) % 6)); const src_rect = Rect.init(frame * 24, 0, 24, 24); var i: usize = 0; while (i < 8) : (i += 1) { const angle: f32 = math.pi * @as(f32, @floatFromInt(i)) / 4.0; const r: f32 = 2 * @as(f32, @floatFromInt(counter)); const dx = x + @as(i32, @intFromFloat(r * @cos(angle))); const dy = y + @as(i32, @intFromFloat(r * @sin(angle))); Sprite.drawFrame(effects_tex, src_rect, dx, dy); } } pub fn drawDeathEffectSmall(x: i32, y: i32, counter: u8) void { const frame = counter; if (frame > 4) return; const src_rect = Rect.init(frame * 24, 0, 24, 24); Sprite.drawFrame(effects_tex, src_rect, x - 12, y - 12); } pub fn drawTeleportEffect(player_x: i32, player_y: i32, counter: u8) void { if (counter < 32) return; const frame: i32 = counter - 32; const x = player_x; var y = player_y; if (frame <= 10 or frame == 15) { if (frame != 15) y -= 16 * (10 - frame); const src_rect = Rect.init(8, 0, 8, 8); var i: i32 = 0; while (i < 4) : (i += 1) { Sprite.drawFrame(teleport_tex, src_rect, x - 4, y + i * 8 - 32); } } else if (frame <= 12) { Sprite.drawFrame(teleport_tex, Rect.init(0, 16, 24, 16), x - 12, y - 16); Sprite.drawFrame(teleport_tex, Rect.init(0, 16, 24, 8), x - 12, y - 24); Sprite.drawFrame(teleport_tex, Rect.init(8, 8, 8, 8), x - 4, y - 32); } else if (frame <= 14) { Sprite.drawFrame(teleport_tex, Rect.init(0, 24, 24, 8), x - 12, y - 8); Sprite.drawFrame(teleport_tex, Rect.init(8, 8, 8, 8), x - 4, y - 16); } }
https://raw.githubusercontent.com/ZigEmbeddedGroup/sycl-badge/0087e9a138dd9c816be545000a5a39ecbd6e0e15/showcase/carts/zeroman/src/effects.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 = "particle_toy", // 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 = "particle_toy", .root_source_file = .{ .path = "src/main.zig" }, .target = target, .optimize = optimize, }); const raylib_lib = std.Build.LazyPath { .path = "C:/raylib/raylib/zig-out/lib/raylib.lib", }; const raylib_include = std.Build.LazyPath { .path = "C:/raylib/raylib/zig-out/include", }; exe.linkLibC(); exe.addObjectFile(raylib_lib.dupe(b)); exe.addIncludePath(raylib_include.dupe(b)); exe.linkSystemLibrary("winmm"); exe.linkSystemLibrary("gdi32"); exe.linkSystemLibrary("opengl32"); // 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/Molcarrus/ParticleMagnet-Zig/8e376bf676aa7bef9ccce34788a799b75348ea8b/build.zig
const lib = @import("lib.zig"); const std = @import("std"); extern var end: [*]u8; extern var timer_scratch: *u64; fn intToString(int: u64, buf: []u8) []const u8 { return std.fmt.bufPrint(buf, "0x{x}", .{int}) catch ""; } pub export fn main() void { var buf: [20]u8 = undefined; const ptr: *u64 = @ptrFromInt(@intFromPtr(&timer_scratch) + 3 * @sizeOf(u64)); const s = intToString(ptr.*, &buf); lib.print("Hello, World!"); lib.print(s); }
https://raw.githubusercontent.com/csirak/zestos/1a6b7a20ab388827d5d9ebae8a2e245e2e73b702/kernel/main.zig