id
stringlengths
8
8
kind
stringclasses
2 values
fn
stringlengths
2
33
repo
stringlengths
8
38
host
stringclasses
2 values
commit
stringlengths
40
40
path
stringlengths
8
42
license
stringclasses
6 values
prompt
stringlengths
36
32.6k
suffix
stringlengths
3
25.2k
ref_body
stringlengths
37
18.5k
grader
dict
n_tests
int64
2
95
license_text
stringlengths
1.05k
16.8k
ib1-0000
fn
findFirstUnset
0xbas4lt/marble
github
df9dcc5b2191118aba6e01504abc332b63bb07c7
kernel/src/BitSet.zig
MIT
const std = @import("std"); /// Padding bits at the end are assumed to be 0. masks: []MaskInt, bit_length: usize, const BitSet = @This(); pub const MaskInt = usize; pub const ShiftInt = std.math.Log2Int(MaskInt); pub const Range = struct { /// The index of the first bit of interest. start: usize, /// Th...
} /// Finds the index of the first unset bit at or after `index`. Returns `null` if none is found. pub fn findFirstUnsetFrom(self: *const BitSet, index: usize) ?usize { std.debug.assert(index < self.bit_length); const bits = @bitSizeOf(MaskInt); var word: usize = index / bits; const start_bit: ShiftI...
var bit_offset_aligned: usize = 0; const mask = for (self.masks) |mask| { if (mask != std.math.maxInt(MaskInt)) break mask; bit_offset_aligned += @bitSizeOf(MaskInt); } else return null; const result_offset = bit_offset_aligned + @ctz(~mask); if (result_offset >= self.b...
{ "prefix": "const std = @import(\"std\");\n\n/// Padding bits at the end are assumed to be 0.\nmasks: []MaskInt,\nbit_length: usize,\n\nconst BitSet = @This();\n\npub const MaskInt = usize;\npub const ShiftInt = std.math.Log2Int(MaskInt);\n\npub const Range = struct {\n /// The index of the first bit of interest....
14
MIT License Copyright (c) 2026 Evgenii Gorbunov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
ib1-0003
fn
init
0xbas4lt/marble
github
df9dcc5b2191118aba6e01504abc332b63bb07c7
kernel/src/KernelEventLogger.zig
MIT
//! //! Kernel logger and ring buffer. //! Each write to the ring buffer advances the cursor. //! const std = @import("std"); const testing = std.testing; const builtin = @import("builtin"); const KernelEventLogger = @This(); /// `ring_buffer.len` must be a power of two. ring_buffer: []Record, /// SAFETY: Check if wr...
} pub fn log(self: *KernelEventLogger, tag: Tag) void { const clock_count: u64 = @intCast(self.clock_count_fn() orelse std.math.maxInt(u64)); const buf_index = self.total_logged_record_count % self.ring_buffer.len; self.ring_buffer[buf_index] = .{ .tag = tag, .clock_count = clock_count }; self.total_lo...
std.debug.assert(std.math.isPowerOfTwo(buffer.len)); return .{ .ring_buffer = buffer, .total_logged_record_count = 0, .clock_count_fn = clock_count_fn, };
{ "prefix": "//!\n//! Kernel logger and ring buffer.\n//! Each write to the ring buffer advances the cursor.\n//!\nconst std = @import(\"std\");\nconst testing = std.testing;\nconst builtin = @import(\"builtin\");\n\nconst KernelEventLogger = @This();\n\n/// `ring_buffer.len` must be a power of two.\nring_buffer: []R...
6
MIT License Copyright (c) 2026 Evgenii Gorbunov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
ib1-0005
fn
log
0xbas4lt/marble
github
df9dcc5b2191118aba6e01504abc332b63bb07c7
kernel/src/KernelEventLogger.zig
MIT
//! //! Kernel logger and ring buffer. //! Each write to the ring buffer advances the cursor. //! const std = @import("std"); const testing = std.testing; const builtin = @import("builtin"); const KernelEventLogger = @This(); /// `ring_buffer.len` must be a power of two. ring_buffer: []Record, /// SAFETY: Check if wr...
} pub const Iterator = struct { /// Historical index (not the wrapped one!!). /// Set by `.next()`. index: usize = 0, logger: *const KernelEventLogger, /// Returns the next available record. /// If there are no records left, returns a `null`. pub fn next(self: *@This()) ?Record { if...
const clock_count: u64 = @intCast(self.clock_count_fn() orelse std.math.maxInt(u64)); const buf_index = self.total_logged_record_count % self.ring_buffer.len; self.ring_buffer[buf_index] = .{ .tag = tag, .clock_count = clock_count }; self.total_logged_record_count +%= 1;
{ "prefix": "//!\n//! Kernel logger and ring buffer.\n//! Each write to the ring buffer advances the cursor.\n//!\nconst std = @import(\"std\");\nconst testing = std.testing;\nconst builtin = @import(\"builtin\");\n\nconst KernelEventLogger = @This();\n\n/// `ring_buffer.len` must be a power of two.\nring_buffer: []R...
6
MIT License Copyright (c) 2026 Evgenii Gorbunov Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, ...
ib1-0006
type
Zprof
ANDRVV/zprof
github
7f480e9cbe6ed34cc14d7840978186b3cb8e8ca3
src/zprof.zig
MIT
//! zprof.zig //! //! Copyright (c) Andrea Vaccaro //! //! Zprof is a zero-overhead, zero-dependency memory profiler //! that wraps any allocator written in Zig. //! Tracks allocations, detects memory leaks, and logs //! memory changes with optional thread-safe mode. //! Version 5.0.0 //! //! Original repository: https...
} fn absDiff(a: usize, b: usize) struct { std.math.Order, usize } { // in this branch integer underflow/overflow is impossible @setRuntimeSafety(false); const order = std.math.order(a, b); const diff = switch (order) { .eq => 0, .gt => a - b, .lt => b - a, }; return .{...
return struct { const Self = @This(); child_allocator: std.mem.Allocator, mutex: @TypeOf(mutex_init) = mutex_init, profiler: Profiler(config), const mutex_init = if (config.thread_safe) std.Io.Mutex.init else {}; pub fn init(child_allocator: std.mem.Allocator, wr...
{ "prefix": "//! zprof.zig\n//!\n//! Copyright (c) Andrea Vaccaro\n//!\n//! Zprof is a zero-overhead, zero-dependency memory profiler\n//! that wraps any allocator written in Zig.\n//! Tracks allocations, detects memory leaks, and logs\n//! memory changes with optional thread-safe mode.\n//! Version 5.0.0\n//!\n//! O...
12
MIT License Copyright (c) Andrea Vaccaro Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distrib...
ib1-0007
fn
deinit
ATTron/astroz
github
c4aed01077028c6e4db279d9ad50aaf626f71a57
src/Ccsds.zig
MIT
//! CCSDS packet structure const std = @import("std"); const Ccsds = @This(); header: HeaderMetadata, primaryHeader: []const u8, secondaryHeader: ?[]const u8, packets: []const u8, rawData: []const u8, allocator: std.mem.Allocator, pub fn init(pl: []const u8, allocator: std.mem.Allocator, config: ?Config) !Ccsds { ...
} /// Optional packet layout; load it with `parseConfig`. pub const Config = struct { secondaryHeaderLength: u8, }; /// CCSDS primary header fields. pub const HeaderMetadata = packed struct { version: u3, packetType: u1, secondaryHeaderFlag: bool, apid: u11, sequenceFlag: u2, packetSequenc...
self.allocator.free(self.rawData);
{ "prefix": "//! CCSDS packet structure\n\nconst std = @import(\"std\");\n\nconst Ccsds = @This();\n\nheader: HeaderMetadata,\nprimaryHeader: []const u8,\nsecondaryHeader: ?[]const u8,\npackets: []const u8,\nrawData: []const u8,\nallocator: std.mem.Allocator,\n\npub fn init(pl: []const u8, allocator: std.mem.Allocato...
2
MIT License Copyright (c) 2024 Anthony Templeton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0008
fn
init
ATTron/astroz
github
c4aed01077028c6e4db279d9ad50aaf626f71a57
src/Ccsds.zig
MIT
//! CCSDS packet structure const std = @import("std"); const Ccsds = @This(); header: HeaderMetadata, primaryHeader: []const u8, secondaryHeader: ?[]const u8, packets: []const u8, rawData: []const u8, allocator: std.mem.Allocator, pub fn init(pl: []const u8, allocator: std.mem.Allocator, config: ?Config) !Ccsds {
} pub fn deinit(self: *Ccsds) void { self.allocator.free(self.rawData); } /// Optional packet layout; load it with `parseConfig`. pub const Config = struct { secondaryHeaderLength: u8, }; /// CCSDS primary header fields. pub const HeaderMetadata = packed struct { version: u3, packetType: u1, seco...
var rawPackets = try allocator.dupe(u8, pl); // dupe so it doesn't go out of scope too early const primaryHeader = rawPackets[0..6]; const version = @as(u3, @truncate((primaryHeader[0] >> 5) & 0x07)); const packetType = @as(u1, @truncate((primaryHeader[0] >> 4) & 0x01)); const secondaryHeaderFlag =...
{ "prefix": "//! CCSDS packet structure\n\nconst std = @import(\"std\");\n\nconst Ccsds = @This();\n\nheader: HeaderMetadata,\nprimaryHeader: []const u8,\nsecondaryHeader: ?[]const u8,\npackets: []const u8,\nrawData: []const u8,\nallocator: std.mem.Allocator,\n\npub fn init(pl: []const u8, allocator: std.mem.Allocato...
2
MIT License Copyright (c) 2024 Anthony Templeton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0009
fn
parseConfig
ATTron/astroz
github
c4aed01077028c6e4db279d9ad50aaf626f71a57
src/Ccsds.zig
MIT
//! CCSDS packet structure const std = @import("std"); const Ccsds = @This(); header: HeaderMetadata, primaryHeader: []const u8, secondaryHeader: ?[]const u8, packets: []const u8, rawData: []const u8, allocator: std.mem.Allocator, pub fn init(pl: []const u8, allocator: std.mem.Allocator, config: ?Config) !Ccsds { ...
} fn readBigEndianU16(bytes: [2]u8) u16 { return @as(u16, bytes[0]) << 8 | bytes[1]; }
const parsed = try std.json.parseFromSlice(Config, allocator, configContent, .{}); defer parsed.deinit(); return parsed.value;
{ "prefix": "//! CCSDS packet structure\n\nconst std = @import(\"std\");\n\nconst Ccsds = @This();\n\nheader: HeaderMetadata,\nprimaryHeader: []const u8,\nsecondaryHeader: ?[]const u8,\npackets: []const u8,\nrawData: []const u8,\nallocator: std.mem.Allocator,\n\npub fn init(pl: []const u8, allocator: std.mem.Allocato...
2
MIT License Copyright (c) 2024 Anthony Templeton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0010
fn
deinit
ATTron/astroz
github
c4aed01077028c6e4db279d9ad50aaf626f71a57
src/Vita49.zig
MIT
//! The Vita49 packet structure const std = @import("std"); const Vita49 = @This(); header: Header, streamId: ?u32, classId: ?ClassId, iTimestamp: ?u32, fTimestamp: ?u64, payload: []const u8, trailer: ?Trailer, allocator: std.mem.Allocator, end: usize, _rawData: []const u8, pub fn init(pl: []const u8, allocator: st...
} fn getPayloadRange(header: Header, hasStreamId: bool) !struct { start: usize, end: usize } { var start: usize = 4; var end: usize = @as(usize, (header.packetSize * 4)) - 1; if (hasStreamId) { start += 4; } if (header.classId) { start += 8; } if (header.tsi != Tsi.none) { ...
self.allocator.free(self._rawData);
{ "prefix": "//! The Vita49 packet structure\n\nconst std = @import(\"std\");\n\nconst Vita49 = @This();\n\nheader: Header,\nstreamId: ?u32,\nclassId: ?ClassId,\niTimestamp: ?u32,\nfTimestamp: ?u64,\npayload: []const u8,\ntrailer: ?Trailer,\nallocator: std.mem.Allocator,\nend: usize,\n_rawData: []const u8,\n\npub fn ...
3
MIT License Copyright (c) 2024 Anthony Templeton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0011
fn
init
ATTron/astroz
github
c4aed01077028c6e4db279d9ad50aaf626f71a57
src/Vita49.zig
MIT
//! The Vita49 packet structure const std = @import("std"); const Vita49 = @This(); header: Header, streamId: ?u32, classId: ?ClassId, iTimestamp: ?u32, fTimestamp: ?u64, payload: []const u8, trailer: ?Trailer, allocator: std.mem.Allocator, end: usize, _rawData: []const u8, pub fn init(pl: []const u8, allocator: st...
} pub fn deinit(self: *Vita49) void { self.allocator.free(self._rawData); } fn getPayloadRange(header: Header, hasStreamId: bool) !struct { start: usize, end: usize } { var start: usize = 4; var end: usize = @as(usize, (header.packetSize * 4)) - 1; if (hasStreamId) { start += 4; } if (...
var stream = try allocator.dupe(u8, pl); // dupe this so it doesnt go out of scope too early if (config != null) { std.log.debug("Config found for Vita49 but this hasn't been implemented yet", .{}); } if (stream.len < 4) { return Error.InsufficientData; } const header = try Head...
{ "prefix": "//! The Vita49 packet structure\n\nconst std = @import(\"std\");\n\nconst Vita49 = @This();\n\nheader: Header,\nstreamId: ?u32,\nclassId: ?ClassId,\niTimestamp: ?u32,\nfTimestamp: ?u64,\npayload: []const u8,\ntrailer: ?Trailer,\nallocator: std.mem.Allocator,\nend: usize,\n_rawData: []const u8,\n\npub fn ...
3
MIT License Copyright (c) 2024 Anthony Templeton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0012
fn
buildCpuLevel
ATTron/oma
github
c94eae96bdf4f2cfb32c77b91c4dd11eec970d7d
src/root.zig
MIT
const std = @import("std"); const builtin = @import("builtin"); pub const CpuLevel = enum { x86_64, x86_64_v2, x86_64_v3, x86_64_v4, aarch64, aarch64_sve, aarch64_sve2, pub fn suffix(self: CpuLevel) []const u8 { return @tagName(self); } }; // Ordered highest-first so disp...
} /// Detect the CPU and resolve a function pointer in one call. The function /// type is derived from `Source`, which must be an `@import`ed module /// registered via `addMultiVersion(.name = ...)`. /// /// const dot = oma.resolveFrom(dot_product, "dot", io); /// /// If using `.name` causes a file-ownership conflic...
return levelFromFeatures(builtin.target.cpu.arch, builtin.target.cpu.features);
{ "prefix": "const std = @import(\"std\");\nconst builtin = @import(\"builtin\");\n\npub const CpuLevel = enum {\n x86_64,\n x86_64_v2,\n x86_64_v3,\n x86_64_v4,\n\n aarch64,\n aarch64_sve,\n aarch64_sve2,\n\n pub fn suffix(self: CpuLevel) []const u8 {\n return @tagName(self);\n }\n}...
2
MIT License Copyright (c) 2025 Anthony Oleinik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d...
ib1-0013
type
module
AlexBlais/dbc_parser
codeberg
2bc97405063f163fc8840741ebeed697142c6ad7
src/tripwire.zig
MIT
//! A library for injecting failures into Zig code for the express //! purpose of testing error handling paths. //! //! Improper `errdefer` is one of the highest sources of bugs in Zig code. //! Many `errdefer` points are hard to exercise in unit tests and rare //! to encounter in production, so they often hide bugs. W...
}
return struct { /// The points this module can fail at. pub const FailPoint = P; /// The error set used for failures at the failure points. pub const Error = err: { const T = if (@TypeOf(E) == type) E else @TypeOf(E); break :err switch (@typeInfo(T)) { ...
{ "prefix": "//! A library for injecting failures into Zig code for the express\n//! purpose of testing error handling paths.\n//!\n//! Improper `errdefer` is one of the highest sources of bugs in Zig code.\n//! Many `errdefer` points are hard to exercise in unit tests and rare\n//! to encounter in production, so the...
3
Copyright Alexandre Blais Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,...
ib1-0014
type
AclReassembler
AritoUser/Zig-BLE
github
38e798951c72c75adca3686b07957883cd8f77eb
src/l2cap/acl_reassembler.zig
MIT
//! # L2CAP ACL Packet Reassembly Engine //! //! Implements Bluetooth Core Specification Vol 3, Part A (L2CAP). //! Reassembles fragmented ACL Data packets (with Packet Boundary flags //! PB_FIRST_FLUSH (0b10) and PB_CONTINUING (0b01)) into full L2CAP frames //! (e.g. ATT PDUs or SMP frames) with zero dynamic allocatio...
}
return struct { const Self = @This(); rx_buffer: [max_frame_len]u8 = undefined, active_handle: ?u16 = null, expected_len: u16 = 0, cid: u16 = 0, accumulated: usize = 0, pub fn init() Self { return .{}; } pub fn reset(self: *Self...
{ "prefix": "//! # L2CAP ACL Packet Reassembly Engine\n//!\n//! Implements Bluetooth Core Specification Vol 3, Part A (L2CAP).\n//! Reassembles fragmented ACL Data packets (with Packet Boundary flags\n//! PB_FIRST_FLUSH (0b10) and PB_CONTINUING (0b01)) into full L2CAP frames\n//! (e.g. ATT PDUs or SMP frames) with ze...
2
MIT License Copyright (c) 2026 Attila / Zig-BLE Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
ib1-0015
type
PcapWriter
AritoUser/Zig-BLE
github
38e798951c72c75adca3686b07957883cd8f77eb
src/tooling/pcap.zig
MIT
//! # Zig-BLE Wireshark PCAP Exporter & Packet Logger //! //! Provides zero-allocation streaming of HCI and ATT packets directly into //! standard libpcap (.pcap) format with Link-Layer DLT_BLUETOOTH_HCI_H4 (187). //! Files generated by this module can be opened directly in Wireshark for //! real-time protocol inspecti...
} // ============================================================================ // Capture Readers: PCAP & Android Btsnoop (RFC 1761) // ============================================================================ /// Parsed PCAP packet borrowing directly from the capture buffer. pub const PcapPacket = struct { ...
return struct { writer: WriterType, header_written: bool = false, const Self = @This(); pub fn init(writer: WriterType) Self { return .{ .writer = writer, .header_written = false, }; } /// Writes the standard...
{ "prefix": "//! # Zig-BLE Wireshark PCAP Exporter & Packet Logger\n//!\n//! Provides zero-allocation streaming of HCI and ATT packets directly into\n//! standard libpcap (.pcap) format with Link-Layer DLT_BLUETOOTH_HCI_H4 (187).\n//! Files generated by this module can be opened directly in Wireshark for\n//! real-ti...
4
MIT License Copyright (c) 2026 Attila / Zig-BLE Contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
ib1-0016
fn
fromHex
AshutoshMahala/zigraph
github
21286fd65cce943892c0fc5eaa0fac690c4a4052
src/render/color/Color.zig
Apache-2.0
//! Numeric color type with perceptual color space support. //! //! `Color` stores RGBA as `f32` (0.0–1.0) and provides: //! - **Conversions:** sRGB ↔ linear RGB ↔ Oklab ↔ HSL ↔ hex string //! - **Interpolation:** `lerp()` in Oklab space (perceptually uniform) //! - **Operations:** darken, lighten, saturate, desa...
} /// Parse a hex color string, returning null on invalid input. /// Accepts `#rrggbb`, `#rrggbbaa`, or `#rgb`. pub fn parseHex(hex: []const u8) ?Color { if (hex.len == 9 and hex[0] == '#') { const r = parseHexPair(hex[1], hex[2]); const g = parseHexPair(hex[3], hex[4]); const b = parseHexP...
return parseHex(hex) orelse rgb(0, 0, 0);
{ "prefix": "//! Numeric color type with perceptual color space support.\n//!\n//! `Color` stores RGBA as `f32` (0.0–1.0) and provides:\n//! - **Conversions:** sRGB ↔ linear RGB ↔ Oklab ↔ HSL ↔ hex string\n//! - **Interpolation:** `lerp()` in Oklab space (perceptually uniform)\n//! - **Operations:** darken, lig...
17
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution ...
ib1-0017
fn
toHexAlloc
AshutoshMahala/zigraph
github
21286fd65cce943892c0fc5eaa0fac690c4a4052
src/render/color/Color.zig
Apache-2.0
//! Numeric color type with perceptual color space support. //! //! `Color` stores RGBA as `f32` (0.0–1.0) and provides: //! - **Conversions:** sRGB ↔ linear RGB ↔ Oklab ↔ HSL ↔ hex string //! - **Interpolation:** `lerp()` in Oklab space (perceptually uniform) //! - **Operations:** darken, lighten, saturate, desa...
} /// Oklab representation: perceptual lightness + a (green-red) + b (blue-yellow). pub const Oklab = struct { L: f32, a: f32, b: f32 }; /// Convert to Oklab color space (perceptually uniform). pub fn toOklab(self: Color) Oklab { const r_lin = srgbToLinear(self.r); const g_lin = srgbToLinear(self.g); cons...
if (self.a >= 1.0 - 1e-4) { const hex = self.toHex(); const slice = try allocator.alloc(u8, 7); @memcpy(slice, &hex); return slice; } else { const hex = self.toHex8(); const slice = try allocator.alloc(u8, 9); @memcpy(slice, &hex); return slice; ...
{ "prefix": "//! Numeric color type with perceptual color space support.\n//!\n//! `Color` stores RGBA as `f32` (0.0–1.0) and provides:\n//! - **Conversions:** sRGB ↔ linear RGB ↔ Oklab ↔ HSL ↔ hex string\n//! - **Interpolation:** `lerp()` in Oklab space (perceptually uniform)\n//! - **Operations:** darken, lig...
17
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution ...
ib1-0018
fn
toHsl
AshutoshMahala/zigraph
github
21286fd65cce943892c0fc5eaa0fac690c4a4052
src/render/color/Color.zig
Apache-2.0
//! Numeric color type with perceptual color space support. //! //! `Color` stores RGBA as `f32` (0.0–1.0) and provides: //! - **Conversions:** sRGB ↔ linear RGB ↔ Oklab ↔ HSL ↔ hex string //! - **Interpolation:** `lerp()` in Oklab space (perceptually uniform) //! - **Operations:** darken, lighten, saturate, desa...
} // ════════════════════════════════════════════════════════════════════════════ // Operations — produce new colors // ════════════════════════════════════════════════════════════════════════════ /// Interpolate between two colors in Oklab space (perceptually uniform). /// `t = 0.0` → self, `t = 1.0` → other. pub fn...
const max_c = @max(self.r, @max(self.g, self.b)); const min_c = @min(self.r, @min(self.g, self.b)); const delta = max_c - min_c; const l = (max_c + min_c) / 2.0; if (delta == 0) return .{ .h = 0, .s = 0, .l = l }; const s: f32 = if (l < 0.5) delta / (max_c + min_c) else delta / (2.0 - max_c -...
{ "prefix": "//! Numeric color type with perceptual color space support.\n//!\n//! `Color` stores RGBA as `f32` (0.0–1.0) and provides:\n//! - **Conversions:** sRGB ↔ linear RGB ↔ Oklab ↔ HSL ↔ hex string\n//! - **Interpolation:** `lerp()` in Oklab space (perceptually uniform)\n//! - **Operations:** darken, lig...
17
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution ...
ib1-0019
fn
note
CashWasabi/bazig
github
4c4eb27c7b6de43314af4ad743af174bc4ff8ff7
src/synth.zig
MIT
//! Sound from oscillators, sweeps and noise, with no audio files. //! A sound is a short mono clip in a slice of floats in -1..1. //! Start from silence and add notes and bursts of noise to it. //! `writeWav` turns a clip into the bytes of a 16-bit PCM WAV file. //! `audio.Engine.registerData` takes those bytes. //! /...
} /// The index of the frame `start_s` seconds in, at most `frame_count`. /// The clamp happens in floats, so a start far past the end cannot overflow. fn frameIndex(start_s: f32, rate: f32, frame_count: usize) usize { return @intFromFloat(@min(start_s * rate, @as(f32, @floatFromInt(frame_count)))); } pub const B...
assert(sample_rate > 0 and sample_rate <= max_sample_rate); assert(n.start_s >= 0 and n.length_s >= 0 and n.decay_s > 0); const rate: f32 = @floatFromInt(sample_rate); const first_idx = frameIndex(n.start_s, rate, out.len); const frame_count: usize = @intFromFloat(n.length_s * rate); const to_h...
{ "prefix": "//! Sound from oscillators, sweeps and noise, with no audio files.\n//! A sound is a short mono clip in a slice of floats in -1..1.\n//! Start from silence and add notes and bursts of noise to it.\n//! `writeWav` turns a clip into the bytes of a 16-bit PCM WAV file.\n//! `audio.Engine.registerData` takes...
10
MIT License Copyright (c) 2026 Marcel Ochs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distr...
ib1-0020
fn
wavSize
CashWasabi/bazig
github
4c4eb27c7b6de43314af4ad743af174bc4ff8ff7
src/synth.zig
MIT
//! Sound from oscillators, sweeps and noise, with no audio files. //! A sound is a short mono clip in a slice of floats in -1..1. //! Start from silence and add notes and bursts of noise to it. //! `writeWav` turns a clip into the bytes of a 16-bit PCM WAV file. //! `audio.Engine.registerData` takes those bytes. //! /...
} /// Writes `samples` as a mono 16-bit PCM WAV file into `buffer`, and returns the file's bytes. /// `buffer` holds at least `wavSize(samples.len)` bytes. /// Samples are clipped to -1..1. pub fn writeWav(samples: []const f32, sample_rate: u32, buffer: []u8) []u8 { assert(sample_rate > 0 and sample_rate <= max_sa...
return wav_header_bytes + frame_count * 2;
{ "prefix": "//! Sound from oscillators, sweeps and noise, with no audio files.\n//! A sound is a short mono clip in a slice of floats in -1..1.\n//! Start from silence and add notes and bursts of noise to it.\n//! `writeWav` turns a clip into the bytes of a 16-bit PCM WAV file.\n//! `audio.Engine.registerData` takes...
10
MIT License Copyright (c) 2026 Marcel Ochs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distr...
ib1-0021
fn
writeWav
CashWasabi/bazig
github
4c4eb27c7b6de43314af4ad743af174bc4ff8ff7
src/synth.zig
MIT
//! Sound from oscillators, sweeps and noise, with no audio files. //! A sound is a short mono clip in a slice of floats in -1..1. //! Start from silence and add notes and bursts of noise to it. //! `writeWav` turns a clip into the bytes of a 16-bit PCM WAV file. //! `audio.Engine.registerData` takes those bytes. //! /...
} const testing = std.testing; fn crossings(samples: []const f32) usize { var count: usize = 0; for (samples[0 .. samples.len - 1], samples[1..]) |x, y| count += @intFromBool((x < 0) != (y < 0)); return count; } fn peak(samples: []const f32) f32 { var highest: f32 = 0; for (samples) |s| highest =...
assert(sample_rate > 0 and sample_rate <= max_sample_rate); assert(samples.len <= max_wav_frame_count); assert(buffer.len >= wavSize(samples.len)); const data_len: u32 = @intCast(samples.len * 2); @memcpy(buffer[0..4], "RIFF"); std.mem.writeInt(u32, buffer[4..8], 36 + data_len, .little); @m...
{ "prefix": "//! Sound from oscillators, sweeps and noise, with no audio files.\n//! A sound is a short mono clip in a slice of floats in -1..1.\n//! Start from silence and add notes and bursts of noise to it.\n//! `writeWav` turns a clip into the bytes of a 16-bit PCM WAV file.\n//! `audio.Engine.registerData` takes...
10
MIT License Copyright (c) 2026 Marcel Ochs Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distr...
ib1-0022
fn
variableRange
CeoMatheusDev/ZyntraUI
github
268fb9f0c359cd6d603c4a4bdd27cbce0517356d
src/layout/virtual.zig
MIT
//! ZyntraUI — helpers de virtualização (layout/virtual). //! //! Escopo M154: cálculo PURO do intervalo de itens visíveis de um //! conteúdo rolável. O estado continua sendo do aplicativo: estes //! helpers não guardam nada, apenas dizem quais itens construir. //! //! - Culling: o backend evita RASTERIZAR o que está f...
}
if (offsets.len < 2) return .{}; const count = offsets.len - 1; if (!std.math.isFinite(scroll) or !std.math.isFinite(viewport_h)) { return .{ .start = 0, .end = count }; } const view_top = @max(0.0, scroll); const view_bottom = view_top + @max(0.0, viewport_h); // Primeiro item com...
{ "prefix": "//! ZyntraUI — helpers de virtualização (layout/virtual).\n//!\n//! Escopo M154: cálculo PURO do intervalo de itens visíveis de um\n//! conteúdo rolável. O estado continua sendo do aplicativo: estes\n//! helpers não guardam nada, apenas dizem quais itens construir.\n//!\n//! - Culling: o backend evita RA...
2
MIT License Copyright (c) 2026 CeoMatheusDev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0023
fn
measure
CeoMatheusDev/ZyntraUI
github
268fb9f0c359cd6d603c4a4bdd27cbce0517356d
src/text/metrics.zig
MIT
//! ZyntraUI — métricas de texto (text/metrics). //! //! Escopo M4: medição determinística sem backend de rasterização. //! - Decodificador UTF-8 próprio (RFC 3629) para não depender de APIs //! do std cuja estabilidade não é garantida aqui. //! - `FontMetrics` descreve uma fonte monospace-fallback; backends //! re...
} /// Retorna o índice de byte (fronteira UTF-8) até onde o texto cabe em /// `max_width`, sem contar quebras de linha como largura. `'\n'` /// interrompe a medição (retorna offset até ele). `max_width < 0` é /// `InvalidArgument`. pub fn truncateToWidth(text: []const u8, metrics: FontMetrics, max_width: f32) !usize {...
if (!metrics.isValid()) return error.InvalidMetrics; var width: f32 = 0; var cur: f32 = 0; var lines: u32 = 1; var glyphs: u32 = 0; var i: usize = 0; // Texto vazio: 1 linha vazia com altura de linha. if (text.len == 0) { return .{ .width = 0, .height = metrics.lineHeight(), .li...
{ "prefix": "//! ZyntraUI — métricas de texto (text/metrics).\n//!\n//! Escopo M4: medição determinística sem backend de rasterização.\n//! - Decodificador UTF-8 próprio (RFC 3629) para não depender de APIs\n//! do std cuja estabilidade não é garantida aqui.\n//! - `FontMetrics` descreve uma fonte monospace-fallbac...
3
MIT License Copyright (c) 2026 CeoMatheusDev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0024
fn
truncateToWidth
CeoMatheusDev/ZyntraUI
github
268fb9f0c359cd6d603c4a4bdd27cbce0517356d
src/text/metrics.zig
MIT
//! ZyntraUI — métricas de texto (text/metrics). //! //! Escopo M4: medição determinística sem backend de rasterização. //! - Decodificador UTF-8 próprio (RFC 3629) para não depender de APIs //! do std cuja estabilidade não é garantida aqui. //! - `FontMetrics` descreve uma fonte monospace-fallback; backends //! re...
}
if (!metrics.isValid()) return error.InvalidMetrics; if (!std.math.isFinite(max_width)) return error.InvalidArgument; if (max_width < 0) return error.InvalidArgument; var cur: f32 = 0; var i: usize = 0; while (i < text.len) { const d = try decodeOne(text[i..]); if (d.codepoint =...
{ "prefix": "//! ZyntraUI — métricas de texto (text/metrics).\n//!\n//! Escopo M4: medição determinística sem backend de rasterização.\n//! - Decodificador UTF-8 próprio (RFC 3629) para não depender de APIs\n//! do std cuja estabilidade não é garantida aqui.\n//! - `FontMetrics` descreve uma fonte monospace-fallbac...
3
MIT License Copyright (c) 2026 CeoMatheusDev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0025
fn
graphemeCount
CeoMatheusDev/ZyntraUI
github
268fb9f0c359cd6d603c4a4bdd27cbce0517356d
src/text/unicode.zig
MIT
//! ZyntraUI — grapheme clusters (text/unicode). //! //! Escopo M166: a distinção entre BYTES, CODEPOINTS e GRAPHEME //! CLUSTERS. O cursor de um campo de texto deve andar por CLUSTER (o //! que o usuário vê como UM caractere), nunca por byte nem por //! codepoint: "e" + acento é um caractere, um emoji com ZWJ (👨‍👩‍�...
} // --------------------------------------------------------------------------- // Testes // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // Fuzz // ----------------------------------------------------------...
var count: usize = 0; var pos: usize = 0; while (pos < text.len) { const len = graphemeLen(text, pos); if (len == 0) break; pos += len; count += 1; } return count;
{ "prefix": "//! ZyntraUI — grapheme clusters (text/unicode).\n//!\n//! Escopo M166: a distinção entre BYTES, CODEPOINTS e GRAPHEME\n//! CLUSTERS. O cursor de um campo de texto deve andar por CLUSTER (o\n//! que o usuário vê como UM caractere), nunca por byte nem por\n//! codepoint: \"e\" + acento é um caractere, um ...
11
MIT License Copyright (c) 2026 CeoMatheusDev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0026
fn
graphemeLen
CeoMatheusDev/ZyntraUI
github
268fb9f0c359cd6d603c4a4bdd27cbce0517356d
src/text/unicode.zig
MIT
//! ZyntraUI — grapheme clusters (text/unicode). //! //! Escopo M166: a distinção entre BYTES, CODEPOINTS e GRAPHEME //! CLUSTERS. O cursor de um campo de texto deve andar por CLUSTER (o //! que o usuário vê como UM caractere), nunca por byte nem por //! codepoint: "e" + acento é um caractere, um emoji com ZWJ (👨‍👩‍�...
} /// O início do codepoint que contém `offset`. fn codepointStart(text: []const u8, offset: usize) usize { if (offset >= text.len) return text.len; var o = offset; while (o > 0 and (text[o] & 0xC0) == 0x80) o -= 1; return o; } /// O início do cluster ANTERIOR (a posição anterior a `offset`). /// /// ...
if (offset >= text.len) return 0; const start = codepointStart(text, offset); var pos = start; var ri_run: usize = 0; while (pos < text.len) { // Conta os RI anteriores (paridade das bandeiras). const info = decodeAt(text, pos) catch return @max(1, pos - start); if (classOf(...
{ "prefix": "//! ZyntraUI — grapheme clusters (text/unicode).\n//!\n//! Escopo M166: a distinção entre BYTES, CODEPOINTS e GRAPHEME\n//! CLUSTERS. O cursor de um campo de texto deve andar por CLUSTER (o\n//! que o usuário vê como UM caractere), nunca por byte nem por\n//! codepoint: \"e\" + acento é um caractere, um ...
11
MIT License Copyright (c) 2026 CeoMatheusDev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0027
fn
nextGrapheme
CeoMatheusDev/ZyntraUI
github
268fb9f0c359cd6d603c4a4bdd27cbce0517356d
src/text/unicode.zig
MIT
//! ZyntraUI — grapheme clusters (text/unicode). //! //! Escopo M166: a distinção entre BYTES, CODEPOINTS e GRAPHEME //! CLUSTERS. O cursor de um campo de texto deve andar por CLUSTER (o //! que o usuário vê como UM caractere), nunca por byte nem por //! codepoint: "e" + acento é um caractere, um emoji com ZWJ (👨‍👩‍�...
} /// Quantos indicadores regionais vêm antes de `offset` (paridade). fn riRunBefore(text: []const u8, offset: usize) usize { var count: usize = 0; var pos: usize = 0; while (pos < offset and pos < text.len) { const info = decodeAt(text, pos) catch break; if (classOf(info.cp) != .regional_i...
if (offset >= text.len) return text.len; const o = codepointStart(text, @min(offset, text.len)); // A menor fronteira maior que `o`. var pos = o; while (pos < text.len) { const next = nextCodepoint(text, pos); if (next >= text.len) return text.len; if (breaksAt(text, next, r...
{ "prefix": "//! ZyntraUI — grapheme clusters (text/unicode).\n//!\n//! Escopo M166: a distinção entre BYTES, CODEPOINTS e GRAPHEME\n//! CLUSTERS. O cursor de um campo de texto deve andar por CLUSTER (o\n//! que o usuário vê como UM caractere), nunca por byte nem por\n//! codepoint: \"e\" + acento é um caractere, um ...
11
MIT License Copyright (c) 2026 CeoMatheusDev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0028
type
ChainHashMapUnmanaged
Czcfsdx/ht.zig
codeberg
bd52834c554e4371a71c896b311f844ab4723955
src/chain_hash_map.zig
MIT
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; pub const default_load_factor_threshold = 100; pub const default_buckets_capacity = 8; fn EntryBucket ( comptime K: type, comptime V: type, ) type { return struct { const Self = @This(); keys...
} //// Tests const testing = std.testing; fn id (x: u64) u64 { return x; } fn equal_u64 (x: u64, y: u64) bool { return x == y; }
if (load_factor_threshold <= 0) { @compileError("load_factor_threshold must be greater than 0."); } return struct { const Self = @This(); /// The buckets of entries. buckets: ArrayList(Bucket), /// Current number of elements in the hashmap. size: Size = 0,...
{ "prefix": "const std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\nconst ArrayList = std.ArrayList;\n\npub const default_load_factor_threshold = 100;\npub const default_buckets_capacity = 8;\n\nfn EntryBucket (\n comptime K: type,\n comptime V: type,\n) type {\n return struct {\n const ...
4
MIT License Copyright (c) 2026 Czcfsdx Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0029
type
ChainHashMapUnmanaged
Czcfsdx/ht.zig
github
09e75fa2e3e3b4d117672f05799c924ba12a0b0e
src/chain_hash_map.zig
MIT
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; pub const default_load_factor_threshold = 100; pub const default_buckets_capacity = 8; fn EntryBucket ( comptime K: type, comptime V: type, ) type { return struct { const Self = @This(); keys...
} //// Tests const testing = std.testing; fn id (x: u64) u64 { return x; } fn equal_u64 (x: u64, y: u64) bool { return x == y; }
if (load_factor_threshold <= 0) { @compileError("load_factor_threshold must be greater than 0."); } return struct { const Self = @This(); /// The buckets of entries. buckets: ArrayList(Bucket), /// Current number of elements in the hashmap. size: Size = 0,...
{ "prefix": "const std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\nconst ArrayList = std.ArrayList;\n\npub const default_load_factor_threshold = 100;\npub const default_buckets_capacity = 8;\n\nfn EntryBucket (\n comptime K: type,\n comptime V: type,\n) type {\n return struct {\n const ...
4
MIT License Copyright (c) 2026 Czcfsdx Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0030
type
OpenHashMapUnmanaged
Czcfsdx/ht.zig
codeberg
bd52834c554e4371a71c896b311f844ab4723955
src/open_hash_map.zig
MIT
const std = @import("std"); const Allocator = std.mem.Allocator; const ArrayList = std.ArrayList; pub const default_load_factor_threshold = 80; pub const default_occupied_load_factor_threshold = 70; pub const default_deleted_load_factor_threshold = 20; // Open addressing + Linear probing pub fn OpenHashMapUnmanaged( ...
} //// Tests const testing = std.testing; const testing_capacity = 16; fn id (x: u64) u64 { return x; } fn equal_u64 (x: u64, y: u64) bool { return x == y; } // test "grow capacity and empty" { // const gpa = testing.allocator; // var map = OpenHashMapUnmanaged(u64, []const u8, id, equal_u64, default_load_...
if (load_factor_threshold <= 0 or load_factor_threshold >= 100) { @compileError("load_factor_threshold must be greater than 0 and less than 100."); } if (occupied_load_factor_threshold <= 0 or occupied_load_factor_threshold >= 100) { @compileError("load_factor_threshold must be greater than...
{ "prefix": "const std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\nconst ArrayList = std.ArrayList;\n\npub const default_load_factor_threshold = 80;\npub const default_occupied_load_factor_threshold = 70;\npub const default_deleted_load_factor_threshold = 20;\n\n// Open addressing + Linear probing\npub...
2
MIT License Copyright (c) 2026 Czcfsdx Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0031
fn
indexOfDelimEnd
Deecellar/bottom-zig
github
907bb3c5b8f91c217157a01234d2f9def5993d4e
src/common.zig
MIT
//! # Bottom Encoding/Decoding Lookup Tables //! //! Provides compile-time generated lookup tables for Bottom emoji encoding: //! - BottomLut: Encodes bytes 0-255 to Bottom emoji sequences //! - BottomDecodeLut: Decodes Bottom sequences back to bytes using hash table //! //! The Bottom encoding represents bytes as comb...
} /// Find two rarest characters in needle for SIMD search heuristic. /// Returns indices of two least-common bytes based on RANK frequency table. fn findRarest(needle: []const u8) ?[2]usize { if (needle.len <= 1 or needle.len > 256) { return null; } var rare1: u8 = needle[0]; var index1: usiz...
const n = haystack.len; if (n < 8) { // Scalar scan for short inputs. var i: usize = 0; while (i < n) : (i += 1) { if (haystack[i] != 0x88) continue; if (i < 7) return null; if (std.mem.eql(u8, haystack[i - 7 ..][0..7], "\xf0\x9f\x91\x89\xf0\x9f\x91")...
{ "prefix": "//! # Bottom Encoding/Decoding Lookup Tables\n//!\n//! Provides compile-time generated lookup tables for Bottom emoji encoding:\n//! - BottomLut: Encodes bytes 0-255 to Bottom emoji sequences\n//! - BottomDecodeLut: Decodes Bottom sequences back to bytes using hash table\n//!\n//! The Bottom encoding rep...
3
The MIT License (MIT) Copyright (c) 2021 Bottom Software Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, mod...
ib1-0032
fn
canonical
Eldhus/fourneau
github
d169ac97bce5d479c11bc51edcf5fb5d8ac5f5aa
src/brotli_huffman.zig
MIT
//! Brotli's prefix codes, the encoder's side (RFC 7932 section 3): the //! bit writer, length-limited Huffman code lengths from symbol counts, //! canonical codes from lengths, and a code's compact form in a stream. const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; pu...
} /// The code for `counts`, chosen and written in its compact form: a /// simple code for up to four symbols, else a complex one (section 3). pub fn write_code( writer: *BitWriter, gpa: Allocator, counts: []const u32, code: *Code, ) !void { assert(counts.len >= 2 and counts.len <= alphabet_max); ...
assert(lengths.len <= alphabet_max); code.alphabet_size = @intCast(lengths.len); code.single = null; @memcpy(code.lengths[0..lengths.len], lengths); var counts: [length_max + 1]u16 = @splat(0); for (lengths) |length| counts[length] += 1; counts[0] = 0; var next: [length_max + 1]u16 = un...
{ "prefix": "//! Brotli's prefix codes, the encoder's side (RFC 7932 section 3): the\n//! bit writer, length-limited Huffman code lengths from symbol counts,\n//! canonical codes from lengths, and a code's compact form in a stream.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst Allocator ...
3
MIT License Copyright (c) 2026 y2k Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
ib1-0033
fn
code_lengths
Eldhus/fourneau
github
d169ac97bce5d479c11bc51edcf5fb5d8ac5f5aa
src/brotli_huffman.zig
MIT
//! Brotli's prefix codes, the encoder's side (RFC 7932 section 3): the //! bit writer, length-limited Huffman code lengths from symbol counts, //! canonical codes from lengths, and a code's compact form in a stream. const std = @import("std"); const assert = std.debug.assert; const Allocator = std.mem.Allocator; pu...
} const Node = struct { count: u64, left: i16, right: i16 }; /// One try at Huffman's code with every count at least `floor`: false /// when the code is longer than `limit`. fn huffman(counts: []const u32, floor: u32, limit: u4, lengths: []u4) bool { var leaves: [alphabet_max]u16 = undefined; var leaf_count: ...
assert(counts.len == lengths.len); assert(counts.len <= alphabet_max); @memset(lengths, 0); var floor: u32 = 1; // Each round doubles the floor: within 32 rounds every count is equal. for (0..33) |_| { if (huffman(counts, floor, limit, lengths)) return; floor *= 2; } else un...
{ "prefix": "//! Brotli's prefix codes, the encoder's side (RFC 7932 section 3): the\n//! bit writer, length-limited Huffman code lengths from symbol counts,\n//! canonical codes from lengths, and a code's compact form in a stream.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\nconst Allocator ...
3
MIT License Copyright (c) 2026 y2k Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
ib1-0034
fn
frame_header
Eldhus/fourneau
github
d169ac97bce5d479c11bc51edcf5fb5d8ac5f5aa
src/http2_frame.zig
MIT
//! HTTP/2 frames (RFC 9113 sections 4 and 6), sans-IO: the nine-byte //! header, each type's payload checked as section 6 says, and the frames //! a server writes. Every malformed frame is a refusal naming the error //! the RFC prescribes and whether it ends the stream or the connection; //! the connection's state mac...
} /// A frame written by one of the writers above, read back as a peer would. fn reparse(bytes: []const u8) Frame { const header = parse_header(bytes[0..header_bytes]); assert(bytes.len == header_bytes + header.length); return parse(header, bytes[header_bytes..]).frame; } fn expect_refusal(header: Header,...
assert(length <= frame_size_max); return .{ .length = @intCast(length), .type = kind, .flags = flags, .stream = stream };
{ "prefix": "//! HTTP/2 frames (RFC 9113 sections 4 and 6), sans-IO: the nine-byte\n//! header, each type's payload checked as section 6 says, and the frames\n//! a server writes. Every malformed frame is a refusal naming the error\n//! the RFC prescribes and whether it ends the stream or the connection;\n//! the con...
4
MIT License Copyright (c) 2026 y2k Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
ib1-0035
fn
parse_header
Eldhus/fourneau
github
d169ac97bce5d479c11bc51edcf5fb5d8ac5f5aa
src/http2_frame.zig
MIT
//! HTTP/2 frames (RFC 9113 sections 4 and 6), sans-IO: the nine-byte //! header, each type's payload checked as section 6 says, and the frames //! a server writes. Every malformed frame is a refusal naming the error //! the RFC prescribes and whether it ends the stream or the connection; //! the connection's state mac...
} pub fn write_header(out: *[header_bytes]u8, header: Header) void { std.mem.writeInt(u24, out[0..3], header.length, .big); out[3] = @backingInt(header.type); out[4] = header.flags; std.mem.writeInt(u32, out[5..9], header.stream, .big); } /// A frame as received and checked: what it carries. pub const...
return .{ .length = std.mem.readInt(u24, bytes[0..3], .big), .type = @fromBackingInt(bytes[3]), .flags = bytes[4], .stream = @truncate(std.mem.readInt(u32, bytes[5..9], .big)), };
{ "prefix": "//! HTTP/2 frames (RFC 9113 sections 4 and 6), sans-IO: the nine-byte\n//! header, each type's payload checked as section 6 says, and the frames\n//! a server writes. Every malformed frame is a refusal naming the error\n//! the RFC prescribes and whether it ends the stream or the connection;\n//! the con...
4
MIT License Copyright (c) 2026 y2k Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
ib1-0036
fn
write_window_update
Eldhus/fourneau
github
d169ac97bce5d479c11bc51edcf5fb5d8ac5f5aa
src/http2_frame.zig
MIT
//! HTTP/2 frames (RFC 9113 sections 4 and 6), sans-IO: the nine-byte //! header, each type's payload checked as section 6 says, and the frames //! a server writes. Every malformed frame is a refusal naming the error //! the RFC prescribes and whether it ends the stream or the connection; //! the connection's state mac...
} pub fn frame_header(kind: Type, flags: u8, stream: u31, length: usize) Header { assert(length <= frame_size_max); return .{ .length = @intCast(length), .type = kind, .flags = flags, .stream = stream }; } /// A frame written by one of the writers above, read back as a peer would. fn reparse(bytes: []const u8...
assert(increment > 0); write_header(out[0..header_bytes], frame_header(.window_update, 0, stream, 4)); std.mem.writeInt(u32, out[header_bytes..][0..4], increment, .big);
{ "prefix": "//! HTTP/2 frames (RFC 9113 sections 4 and 6), sans-IO: the nine-byte\n//! header, each type's payload checked as section 6 says, and the frames\n//! a server writes. Every malformed frame is a refusal naming the error\n//! the RFC prescribes and whether it ends the stream or the connection;\n//! the con...
4
MIT License Copyright (c) 2026 y2k Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
ib1-0037
fn
format
Eldhus/fourneau
github
d169ac97bce5d479c11bc51edcf5fb5d8ac5f5aa
src/http_date.zig
MIT
//! HTTP dates (RFC 9110 §5.6.7): IMF-fixdate, the one form a server sends: //! `Sun, 06 Nov 1994 08:49:37 GMT`. Pure integer arithmetic on Unix //! seconds, so it is exact and the same on every machine. const std = @import("std"); const assert = std.debug.assert; pub const length = 29; /// The last second this form...
} fn write_digits(out: []u8, value: u64) void { var rest = value; var index = out.len; while (index > 0) { index -= 1; out[index] = '0' + @as(u8, @intCast(rest % 10)); rest /= 10; } assert(rest == 0); // the value fit its field } const Civil = struct { year: u64, month: u8,...
assert(unix_seconds <= seconds_max); const days = unix_seconds / std.time.s_per_day; const second_of_day = unix_seconds % std.time.s_per_day; const date = civil_from_days(days); var out: [length]u8 = undefined; // 1970-01-01 was a Thursday. @memcpy(out[0..3], day_names[days % 7]); @memc...
{ "prefix": "//! HTTP dates (RFC 9110 §5.6.7): IMF-fixdate, the one form a server sends:\n//! `Sun, 06 Nov 1994 08:49:37 GMT`. Pure integer arithmetic on Unix\n//! seconds, so it is exact and the same on every machine.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\npub const length = 29;\n\n///...
2
MIT License Copyright (c) 2026 y2k Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, s...
ib1-0041
type
JobResult
Fusion-Engine-Labs/zob
github
7a9e73c34413bc23e41a64f0e1cf80eecc201759
src/job.zig
MIT
const std = @import("std"); /// Validates at comptime that T is a valid zob job type. /// /// Requirements: /// - T must be a struct /// - T must have a public `execute` declaration /// - `execute` must be a function /// - `execute` must take exactly one parameter (self) pub fn validateJobType(comptime T: type) void {...
} pub fn makeRunner(comptime T: type) fn (T) JobResult(T) { return struct { fn run(data: T) JobResult(T) { return data.execute(); } }.run; } const testing = std.testing; const ValidJob = struct { value: i32, pub fn execute(self: @This()) i32 { return self.value * ...
validateJobType(T); const func = @typeInfo(@TypeOf(T.execute)).@"fn"; return func.return_type.?;
{ "prefix": "const std = @import(\"std\");\n\n/// Validates at comptime that T is a valid zob job type.\n///\n/// Requirements:\n/// - T must be a struct\n/// - T must have a public `execute` declaration\n/// - `execute` must be a function\n/// - `execute` must take exactly one parameter (self)\npub fn validateJobTyp...
11
MIT License Copyright (c) 2026 Zephyr Engine Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0042
fn
makeRunner
Fusion-Engine-Labs/zob
github
7a9e73c34413bc23e41a64f0e1cf80eecc201759
src/job.zig
MIT
const std = @import("std"); /// Validates at comptime that T is a valid zob job type. /// /// Requirements: /// - T must be a struct /// - T must have a public `execute` declaration /// - `execute` must be a function /// - `execute` must take exactly one parameter (self) pub fn validateJobType(comptime T: type) void {...
} const testing = std.testing; const ValidJob = struct { value: i32, pub fn execute(self: @This()) i32 { return self.value * 2; } }; const ErrorJob = struct { should_fail: bool, pub fn execute(self: @This()) !i32 { if (self.should_fail) return error.JobFailed; return 42;...
return struct { fn run(data: T) JobResult(T) { return data.execute(); } }.run;
{ "prefix": "const std = @import(\"std\");\n\n/// Validates at comptime that T is a valid zob job type.\n///\n/// Requirements:\n/// - T must be a struct\n/// - T must have a public `execute` declaration\n/// - `execute` must be a function\n/// - `execute` must take exactly one parameter (self)\npub fn validateJobTyp...
11
MIT License Copyright (c) 2026 Zephyr Engine Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, dis...
ib1-0044
fn
isComptimeKnown
Games-by-Mason/mr_ecs
codeberg
75472fade425a7d51fde180087043b2336c1c2f1
src/meta.zig
MIT
//! Metaprogramming helpers. See also `view`. const std = @import("std"); const assert = std.debug.assert; /// Returns true if the given value is comptime known, false otherwise. pub inline fn isComptimeKnown(value: anytype) bool {
} /// Similar to `@offsetOf`, but can traverse nested fields. Escaped field names not supported. pub fn offsetOf(T: type, comptime path: []const u8) comptime_int { for (path) |c| assert(c != '@'); var Obj = T; var offset = 0; var parts = std.mem.splitScalar(u8, path, '.'); while (parts.next()) |fie...
return @typeInfo(@TypeOf(.{value})).@"struct".field_attrs[0].@"comptime";
{ "prefix": "//! Metaprogramming helpers. See also `view`.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\n/// Returns true if the given value is comptime known, false otherwise.\npub inline fn isComptimeKnown(value: anytype) bool {", "suffix": "}\n\ntest isComptimeKnown {\n try std.testing...
2
MIT License Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0045
fn
offsetOf
Games-by-Mason/mr_ecs
codeberg
75472fade425a7d51fde180087043b2336c1c2f1
src/meta.zig
MIT
//! Metaprogramming helpers. See also `view`. const std = @import("std"); const assert = std.debug.assert; /// Returns true if the given value is comptime known, false otherwise. pub inline fn isComptimeKnown(value: anytype) bool { return @typeInfo(@TypeOf(.{value})).@"struct".field_attrs[0].@"comptime"; } /// S...
}
for (path) |c| assert(c != '@'); var Obj = T; var offset = 0; var parts = std.mem.splitScalar(u8, path, '.'); while (parts.next()) |field| { offset += @offsetOf(Obj, field); Obj = @FieldType(Obj, field); } return offset;
{ "prefix": "//! Metaprogramming helpers. See also `view`.\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\n\n/// Returns true if the given value is comptime known, false otherwise.\npub inline fn isComptimeKnown(value: anytype) bool {\n return @typeInfo(@TypeOf(.{value})).@\"struct\".field_attr...
2
MIT License Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0046
type
AnyColor
Games-by-Mason/mr_gpu
codeberg
d18fca3c07ce81afab76a8a4aeb7851361710e10
src/ext/colors.zig
MIT
//! Convenience functions for color conversions. Methods operate on structs containing r/g/b/a //! fields, tuples, arrays, or vectors. //! //! These functions are mirrored in `gbms`: //! //! https://github.com/Games-by-Mason/gbms const std = @import("std"); const assert = std.debug.assert; const math = std.math; /// ...
} /// Creates an instance of `AnyColor` from a user type. pub fn anyColor(input: anytype) AnyColor(@TypeOf(input)) { const Result = AnyColor(@TypeOf(input)); var result: Result = undefined; switch (@typeInfo(@TypeOf(input))) { .float, .comptime_float, .int, .comptime_int => { result.r ...
comptime var R = void; comptime var G = void; comptime var B = void; comptime var A = void; switch (@typeInfo(Input)) { .float, .comptime_float, .int, .comptime_int => { R = Input; }, inline .array, .vector => |info| { if (info.len > 0) R = info.chil...
{ "prefix": "//! Convenience functions for color conversions. Methods operate on structs containing r/g/b/a\n//! fields, tuples, arrays, or vectors.\n//!\n//! These functions are mirrored in `gbms`:\n//!\n//! https://github.com/Games-by-Mason/gbms\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nco...
8
MIT License Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0047
fn
anyColor
Games-by-Mason/mr_gpu
codeberg
d18fca3c07ce81afab76a8a4aeb7851361710e10
src/ext/colors.zig
MIT
//! Convenience functions for color conversions. Methods operate on structs containing r/g/b/a //! fields, tuples, arrays, or vectors. //! //! These functions are mirrored in `gbms`: //! //! https://github.com/Games-by-Mason/gbms const std = @import("std"); const assert = std.debug.assert; const math = std.math; /// ...
}
const Result = AnyColor(@TypeOf(input)); var result: Result = undefined; switch (@typeInfo(@TypeOf(input))) { .float, .comptime_float, .int, .comptime_int => { result.r = input; }, inline .array, .vector => |info| { if (info.len > 0) result.r = input[0]; ...
{ "prefix": "//! Convenience functions for color conversions. Methods operate on structs containing r/g/b/a\n//! fields, tuples, arrays, or vectors.\n//!\n//! These functions are mirrored in `gbms`:\n//!\n//! https://github.com/Games-by-Mason/gbms\n\nconst std = @import(\"std\");\nconst assert = std.debug.assert;\nco...
8
MIT License Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0048
type
SlotMap
Games-by-Mason/mr_slot_map
codeberg
ca62b2c549ff6bbfb3c657380c1a1d8a801dbe25
src/root.zig
MIT
//! See `SlotMap`. const std = @import("std"); const Allocator = std.mem.Allocator; const assert = std.debug.assert; const log = std.log.scoped(.slot_map); /// Configuration for `SlotMap`. pub const KeyOptions = struct { Index: type = u32, GenerationTag: type = u32, }; /// A high performance associative cont...
} // Basically just making sure it compiles
return struct { /// A persistent `SlotMap` key. pub const Key = packed struct { pub const Generation = enum(key_options.GenerationTag) { invalid = 0, first = 1, _, pub fn format(self: @This(), writer: *std.Io.Writer) std.I...
{ "prefix": "//! See `SlotMap`.\n\nconst std = @import(\"std\");\nconst Allocator = std.mem.Allocator;\nconst assert = std.debug.assert;\nconst log = std.log.scoped(.slot_map);\n\n/// Configuration for `SlotMap`.\npub const KeyOptions = struct {\n Index: type = u32,\n GenerationTag: type = u32,\n};\n\n/// A hig...
4
MIT License Copyright (c) contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribut...
ib1-0049
type
Fixed
GasInfinity/zsflt
github
6153bfec12f5bdcfab5c23757c416aeb760e1cbd
src/zsflt.zig
MIT
pub fn Float(comptime exponent_bits: u16, comptime mantissa_bits: u16) type { return packed struct(@Int(.unsigned, 1 + exponent_bits + mantissa_bits)) { const Flt = @This(); pub const Mantissa = @Int(.unsigned, mantissa_bits); pub const Exponent = @Int(.signed, exponent_bits); pub co...
} const testing = std.testing; fn testComparingHardwareConversion(comptime A: type, comptime B: type, comptime AT: type, comptime BT: type, value: AT) !void { const zsflt_bitcasted: A = .of(value); const zsflt_converted: B = .of(zsflt_bitcasted); const hw_converted: BT = @floatCast(value); const zsfl...
const sign_bit = @intFromBool(signedness == .signed); const FixInt = @Int(signedness, sign_bit + integer_bits + fractional_bits); const AbsoluteFixInt = @Int(.unsigned, sign_bit + integer_bits + fractional_bits); return packed struct(FixInt) { const Fix = @This(); pub const Fractional...
{ "prefix": "pub fn Float(comptime exponent_bits: u16, comptime mantissa_bits: u16) type {\n return packed struct(@Int(.unsigned, 1 + exponent_bits + mantissa_bits)) {\n const Flt = @This();\n pub const Mantissa = @Int(.unsigned, mantissa_bits);\n pub const Exponent = @Int(.signed, exponent_bi...
2
Copyright © 2025 GasInfinity Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
ib1-0050
type
Float
GasInfinity/zsflt
github
6153bfec12f5bdcfab5c23757c416aeb760e1cbd
src/zsflt.zig
MIT
pub fn Float(comptime exponent_bits: u16, comptime mantissa_bits: u16) type {
} pub fn Fixed(comptime signedness: std.builtin.Signedness, comptime integer_bits: u16, comptime fractional_bits: u16) type { const sign_bit = @intFromBool(signedness == .signed); const FixInt = @Int(signedness, sign_bit + integer_bits + fractional_bits); const AbsoluteFixInt = @Int(.unsigned, sign_bit + i...
return packed struct(@Int(.unsigned, 1 + exponent_bits + mantissa_bits)) { const Flt = @This(); pub const Mantissa = @Int(.unsigned, mantissa_bits); pub const Exponent = @Int(.signed, exponent_bits); pub const BiasedExponent = enum(@Int(.unsigned, exponent_bits)) { denor...
{ "prefix": "pub fn Float(comptime exponent_bits: u16, comptime mantissa_bits: u16) type {", "suffix": "}\n\npub fn Fixed(comptime signedness: std.builtin.Signedness, comptime integer_bits: u16, comptime fractional_bits: u16) type {\n const sign_bit = @intFromBool(signedness == .signed);\n const FixInt = @Int...
2
Copyright © 2025 GasInfinity Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
ib1-0054
fn
signSchnorr
GhostKellz/zcrypto
github
6a5dfd2844e654f0728e5b741bbf5cf37fdc8cb9
src/schnorr.zig
MIT
//! Schnorr signatures over secp256k1 (BIP340), MuSig2, adaptor signatures — //! NOT IMPLEMENTED. //! //! This module defines the BIP340 wire sizes and the key/nonce/context shapes so //! callers can parse and carry Schnorr material, but it performs no signature //! operation. Every function that would produce or check...
} /// Always fails: no BIP340 backend. /// /// Returns an error rather than `false` on purpose. A `false` would imply the /// signature was checked and rejected; nothing here checks anything. pub fn verifySchnorr(message: []const u8, signature: [SCHNORR_SIGNATURE_SIZE]u8, public_key: [SCHNORR_PUBLIC_KEY_SIZE]u8) Schno...
_ = message; _ = private_key; return SchnorrError.UnsupportedAlgorithm;
{ "prefix": "//! Schnorr signatures over secp256k1 (BIP340), MuSig2, adaptor signatures —\n//! NOT IMPLEMENTED.\n//!\n//! This module defines the BIP340 wire sizes and the key/nonce/context shapes so\n//! callers can parse and carry Schnorr material, but it performs no signature\n//! operation. Every function that wo...
4
MIT License Copyright (c) 2025 CK Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0055
fn
timingSafeEqual
GhostKellz/zcrypto
github
6a5dfd2844e654f0728e5b741bbf5cf37fdc8cb9
src/timing.zig
MIT
//! Timing-Safe Cryptographic Utilities //! //! Provides constant-time operations to prevent timing side-channel attacks. //! These functions are critical for comparing secrets (keys, MACs, passwords) //! and ensuring operations complete in predictable time. //! //! ## Security Considerations //! //! Timing attacks exp...
} /// Zero a buffer with a store the optimizer is not permitted to delete. /// /// ## Parameters /// - `buffer`: Buffer to zero /// /// ## What this guarantees /// Exactly one thing: the write to `buffer` happens. A plain /// `@memset(buffer, 0)` on a buffer nothing reads afterwards is a dead store, /// and the optimi...
// Different lengths are obviously unequal // This is NOT a timing leak because length is typically public if (a.len != b.len) return false; // Constant-time comparison using bitwise operations var result: u8 = 0; for (a, b) |byte_a, byte_b| { result |= byte_a ^ byte_b; } retur...
{ "prefix": "//! Timing-Safe Cryptographic Utilities\n//!\n//! Provides constant-time operations to prevent timing side-channel attacks.\n//! These functions are critical for comparing secrets (keys, MACs, passwords)\n//! and ensuring operations complete in predictable time.\n//!\n//! ## Security Considerations\n//!\...
11
MIT License Copyright (c) 2025 CK Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0056
fn
toHex
GhostKellz/zcrypto
github
6a5dfd2844e654f0728e5b741bbf5cf37fdc8cb9
src/util.zig
MIT
//! Cryptographic utilities //! //! Helper functions for constant-time operations, padding, endian conversion, //! timestamp utilities, and other cryptographic utilities. const std = @import("std"); const builtin = @import("builtin"); // ============================================================================= //...
} /// Convert hexadecimal string to bytes pub fn fromHex(allocator: std.mem.Allocator, hex: []const u8) ![]u8 { if (hex.len % 2 != 0) return error.InvalidHexLength; const bytes = try allocator.alloc(u8, hex.len / 2); errdefer allocator.free(bytes); var i: usize = 0; while (i < hex.len) : (i += 2)...
const hex = try allocator.alloc(u8, bytes.len * 2); for (bytes, 0..) |byte, i| { const hex_chars = "0123456789abcdef"; hex[i * 2] = hex_chars[byte >> 4]; hex[i * 2 + 1] = hex_chars[byte & 0xF]; } return hex;
{ "prefix": "//! Cryptographic utilities\n//!\n//! Helper functions for constant-time operations, padding, endian conversion,\n//! timestamp utilities, and other cryptographic utilities.\n\nconst std = @import(\"std\");\nconst builtin = @import(\"builtin\");\n\n// =====================================================...
15
MIT License Copyright (c) 2025 CK Technology LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish,...
ib1-0057
fn
parseControlSettings
GhostKellz/zquic
github
401d2f8d4bf758fc1d833a2b99db0b1edfc5461f
src/http3/minimal_interop.zig
Apache-2.0
//! Bounded HTTP/3 wire primitives for the live interop probe. //! //! This deliberately supports only the zero-dynamic-table subset needed for //! an external `GET /`: peer SETTINGS, static/literal request fields, and a //! static `:status 200` response. It is not the general HTTP/3 server API. const std = @import("s...
} /// Parse the first request-stream HEADERS frame and prove it is `GET /`. /// Unknown frame types are skipped as required by HTTP/3 extensibility; known /// frames that are illegal before the initial HEADERS remain fatal. pub fn parseGetRootRequest(stream_data: []const u8) Error!Request { var cursor: usize = 0; ...
var cursor: usize = 0; if (try readVarint(stream_data, &cursor) != 0) return Error.InvalidStream; if (try readVarint(stream_data, &cursor) != 0x04) return Error.InvalidSettings; const payload_len = try lengthAsUsize(try readVarint(stream_data, &cursor)); const payload_end = std.math.add(usize, curs...
{ "prefix": "//! Bounded HTTP/3 wire primitives for the live interop probe.\n//!\n//! This deliberately supports only the zero-dynamic-table subset needed for\n//! an external `GET /`: peer SETTINGS, static/literal request fields, and a\n//! static `:status 200` response. It is not the general HTTP/3 server API.\n\nc...
3
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0058
fn
parseGetRootRequest
GhostKellz/zquic
github
401d2f8d4bf758fc1d833a2b99db0b1edfc5461f
src/http3/minimal_interop.zig
Apache-2.0
//! Bounded HTTP/3 wire primitives for the live interop probe. //! //! This deliberately supports only the zero-dynamic-table subset needed for //! an external `GET /`: peer SETTINGS, static/literal request fields, and a //! static `:status 200` response. It is not the general HTTP/3 server API. const std = @import("s...
} fn parseHeaderBlock(block: []const u8) Error!Request { var cursor: usize = 0; const required_insert_count = try readPrefixedInt(block, &cursor, 8); if (required_insert_count != 0) return Error.DynamicReference; if (cursor >= block.len) return Error.WouldBlock; // With a zero Required Insert Count...
var cursor: usize = 0; while (cursor < stream_data.len) { const frame_type = try readVarint(stream_data, &cursor); const payload_len = try lengthAsUsize(try readVarint(stream_data, &cursor)); const payload_end = std.math.add(usize, cursor, payload_len) catch return Error.InvalidHeaderBl...
{ "prefix": "//! Bounded HTTP/3 wire primitives for the live interop probe.\n//!\n//! This deliberately supports only the zero-dynamic-table subset needed for\n//! an external `GET /`: peer SETTINGS, static/literal request fields, and a\n//! static `:status 200` response. It is not the general HTTP/3 server API.\n\nc...
3
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0059
fn
transportErrorToZquicError
GhostKellz/zquic
github
401d2f8d4bf758fc1d833a2b99db0b1edfc5461f
src/utils/error.zig
Apache-2.0
//! Error Definitions for ZQUIC Library //! //! This module provides a unified error handling system for all ZQUIC operations. //! Errors are organized into categories for easier handling and debugging. //! //! ## Error Categories //! //! | Category | Errors | Description | //! |----------|--------|-------------| //! |...
} /// Error context for debugging and logging pub const ErrorContext = struct { file: []const u8, function: []const u8, line: u32, message: ?[]const u8 = null, cause: ?ZquicError = null, pub fn init(file: []const u8, function: []const u8, line: u32) ErrorContext { return ErrorContext{ ...
return switch (transport_error) { .no_error => ZquicError.InternalError, // Should not happen .internal_error => ZquicError.InternalError, .connection_refused => ZquicError.ConnectionRefused, .flow_control_error => ZquicError.FlowControlError, .stream_limit_error => ZquicErr...
{ "prefix": "//! Error Definitions for ZQUIC Library\n//!\n//! This module provides a unified error handling system for all ZQUIC operations.\n//! Errors are organized into categories for easier handling and debugging.\n//!\n//! ## Error Categories\n//!\n//! | Category | Errors | Description |\n//! |----------|------...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0060
fn
addCustom
GrayHatter/verse
github
36c8d314586559331a3422dbef4bb18f2458f7ba
src/Headers.zig
MIT
known: KnownMap, extra: ExtendedMap, const Headers = @This(); pub const empty: Headers = .{ .known = .{}, .extra = .{} }; pub const Expected = enum { accept, accept_encoding, accept_language, authorization, cookie, from, host, referer, user_agent, }; pub const Header = struct { ...
} pub fn getCustom(h: *const Headers, name: []const u8) ?HeaderList { // TODO fix me if (h.extra.get(name)) |header| { return .{ .name = name, .list = header.list, }; } else return null; } /// Returns the value associated with the given header or an error if it's mi...
// TODO normalize lower const gop = try h.extra.getOrPut(a, name); const hl: *HeaderList = gop.value_ptr; if (gop.found_existing) { try hl.*.list.append(a, value); } else { hl.* = .{ .name = name, .list = try .initCapacity(a, 4), }; hl.list.ap...
{ "prefix": "known: KnownMap,\nextra: ExtendedMap,\n\nconst Headers = @This();\n\npub const empty: Headers = .{ .known = .{}, .extra = .{} };\n\npub const Expected = enum {\n accept,\n accept_encoding,\n accept_language,\n authorization,\n cookie,\n from,\n host,\n referer,\n user_agent,\n}...
2
Copyright Verse contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
ib1-0061
fn
raze
GrayHatter/verse
github
36c8d314586559331a3422dbef4bb18f2458f7ba
src/Headers.zig
MIT
known: KnownMap, extra: ExtendedMap, const Headers = @This(); pub const empty: Headers = .{ .known = .{}, .extra = .{} }; pub const Expected = enum { accept, accept_encoding, accept_language, authorization, cookie, from, host, referer, user_agent, }; pub const Header = struct { ...
} fn normalize(_: []const u8) !void { comptime unreachable; } /// Caller is responsible for the lifetime of both `name` and `value`. Both must outlive /// `Headers` pub fn addCustom(h: *Headers, a: Allocator, name: []const u8, value: []const u8) !void { // TODO normalize lower const gop = try h.extra.getO...
const values = h.extra.values(); for (values) |*val| { val.list.deinit(a); } h.extra.deinit(a);
{ "prefix": "known: KnownMap,\nextra: ExtendedMap,\n\nconst Headers = @This();\n\npub const empty: Headers = .{ .known = .{}, .extra = .{} };\n\npub const Expected = enum {\n accept,\n accept_encoding,\n accept_language,\n authorization,\n cookie,\n from,\n host,\n referer,\n user_agent,\n}...
2
Copyright Verse contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
ib1-0062
fn
next
GrayHatter/verse
github
36c8d314586559331a3422dbef4bb18f2458f7ba
src/Uri.zig
MIT
//! Uri //! TODO write docs index: usize, path: []const u8, /// Non null when `?` is present in the URI. Does not include the first `?` query: ?[]const u8, bytes: []const u8, const Uri = @This(); pub fn init(target: []const u8) error{BadData}!Uri { var uri: Uri = .{ .index = 0, .path = target, ...
} pub fn isDir(uri: Uri) bool { return uri.path[uri.path.len - 1] == '/'; } pub fn first(uri: *Uri) []const u8 { uri.index = 0; return uri.next() orelse unreachable; } pub fn withoutPrefix(uri: Uri) ?[]const u8 { if (uri.index < uri.path.len - 1) return uri.path[uri.index..]; return null;...
const new = uri.peek() orelse return null; uri.index += new.len + 1; uri.index = uri.nextIndex(); if (new.len == 0) uri.index += 1; return new;
{ "prefix": "//! Uri\n//! TODO write docs\n\nindex: usize,\npath: []const u8,\n/// Non null when `?` is present in the URI. Does not include the first `?`\nquery: ?[]const u8,\nbytes: []const u8,\n\nconst Uri = @This();\n\npub fn init(target: []const u8) error{BadData}!Uri {\n var uri: Uri = .{\n .index = 0...
2
Copyright Verse contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
ib1-0063
fn
string
GrayHatter/verse
github
36c8d314586559331a3422dbef4bb18f2458f7ba
src/content-type.zig
MIT
//! ContentType //! //! Some of the most common ContentTypes are exposed directly as decl literals. //! //! Experimental: A few 'short' aliases are exposed for ergonomics. //! note: short aliases may be changed/removed from the API. base: ContentBase, parameter: ?CharSet = null, const ContentType = @This(); pub cons...
} pub fn fromStr(str: []const u8) !ContentType { const U = @typeInfo(ContentBase).@"union"; inline for (U.field_names, U.field_types) |name, typ| { if (startsWith(u8, str, name)) { return wrapBase(typ, str[name.len + 1 ..]); } } log.warn("unable to process content type {s}",...
return switch (ct.base) { inline else => |tag| comptimePrint( "{s}/{s}{s}", .{ @tagName(ct.base), @tagName(tag), if (ct.parameter) |param| switch (param) { inline else => |p| "; charset=" ++ @tagName(p), ...
{ "prefix": "//! ContentType\n//!\n//! Some of the most common ContentTypes are exposed directly as decl literals.\n//!\n//! Experimental: A few 'short' aliases are exposed for ergonomics.\n//! note: short aliases may be changed/removed from the API.\n\nbase: ContentBase,\nparameter: ?CharSet = null,\n\nconst Content...
5
Copyright Verse contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicen...
ib1-0064
fn
buildCpuLevel
Gshacker-cpu/oma
github
c646e2473564845f1f0216024dae693609fbf89a
src/root.zig
MIT
const std = @import("std"); const builtin = @import("builtin"); pub const CpuLevel = enum { x86_64, x86_64_v2, x86_64_v3, x86_64_v4, aarch64, aarch64_sve, aarch64_sve2, pub fn suffix(self: CpuLevel) []const u8 { return @tagName(self); } }; // Ordered highest-first so disp...
} /// Detect the CPU and resolve a function pointer in one call. The function /// type is derived from `Source`, which must be an `@import`ed module /// registered via `addMultiVersion(.name = ...)`. /// /// const dot = oma.resolveFrom(dot_product, "dot", io); /// /// If using `.name` causes a file-ownership conflic...
return levelFromFeatures(builtin.target.cpu.arch, builtin.target.cpu.features);
{ "prefix": "const std = @import(\"std\");\nconst builtin = @import(\"builtin\");\n\npub const CpuLevel = enum {\n x86_64,\n x86_64_v2,\n x86_64_v3,\n x86_64_v4,\n\n aarch64,\n aarch64_sve,\n aarch64_sve2,\n\n pub fn suffix(self: CpuLevel) []const u8 {\n return @tagName(self);\n }\n}...
2
MIT License Copyright (c) 2025 Anthony Oleinik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, d...
ib1-0065
fn
initSlice
Hejsil/spaghet
github
6b553c1f0e3e5d9073746ee21c1d8d99a030932e
src/Args.zig
MIT
//! A simple argument parser args: []const []const u8, index: usize, consumed: bool, positionals_only: bool, pub fn initSlice(args: []const []const u8) Args {
} pub fn next(args: *Args) bool { args.consumed = args.index >= args.args.len; return !args.consumed; } pub fn flag(args: *Args, names: []const []const u8) bool { if (args.consumed or args.positionals_only) return false; for (names) |name| { if (!std.mem.eql(u8, args.args[args.index],...
return .{ .args = args, .index = 0, .consumed = false, .positionals_only = false, };
{ "prefix": "//! A simple argument parser\n\nargs: []const []const u8,\nindex: usize,\nconsumed: bool,\npositionals_only: bool,\n\npub fn initSlice(args: []const []const u8) Args {", "suffix": "}\n\npub fn next(args: *Args) bool {\n args.consumed = args.index >= args.args.len;\n return !args.consumed;\n}\n\np...
6
MIT License Copyright (c) Jimmi Holst Christensen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
ib1-0066
fn
next
Hejsil/spaghet
github
6b553c1f0e3e5d9073746ee21c1d8d99a030932e
src/Args.zig
MIT
//! A simple argument parser args: []const []const u8, index: usize, consumed: bool, positionals_only: bool, pub fn initSlice(args: []const []const u8) Args { return .{ .args = args, .index = 0, .consumed = false, .positionals_only = false, }; } pub fn next(args: *Args) bool {
} pub fn flag(args: *Args, names: []const []const u8) bool { if (args.consumed or args.positionals_only) return false; for (names) |name| { if (!std.mem.eql(u8, args.args[args.index], name)) continue; args.consumed = true; args.index += 1; return true; ...
args.consumed = args.index >= args.args.len; return !args.consumed;
{ "prefix": "//! A simple argument parser\n\nargs: []const []const u8,\nindex: usize,\nconsumed: bool,\npositionals_only: bool,\n\npub fn initSlice(args: []const []const u8) Args {\n return .{\n .args = args,\n .index = 0,\n .consumed = false,\n .positionals_only = false,\n };\n}\n\n...
6
MIT License Copyright (c) Jimmi Holst Christensen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
ib1-0067
fn
option
Hejsil/spaghet
github
6b553c1f0e3e5d9073746ee21c1d8d99a030932e
src/Args.zig
MIT
//! A simple argument parser args: []const []const u8, index: usize, consumed: bool, positionals_only: bool, pub fn initSlice(args: []const []const u8) Args { return .{ .args = args, .index = 0, .consumed = false, .positionals_only = false, }; } pub fn next(args: *Args) bool {...
} pub fn positional(args: *Args) ?[]const u8 { if (args.consumed) return null; const res = args.eat(); args.consumed = true; if (!args.positionals_only and std.mem.eql(u8, res, "--")) { args.positionals_only = true; return null; } return res; } fn eat(args: *Args) []c...
if (args.consumed or args.positionals_only) return null; const arg = args.args[args.index]; for (names) |name| { if (!std.mem.startsWith(u8, arg, name)) continue; if (!std.mem.startsWith(u8, arg[name.len..], "=")) continue; args.consumed = true; ...
{ "prefix": "//! A simple argument parser\n\nargs: []const []const u8,\nindex: usize,\nconsumed: bool,\npositionals_only: bool,\n\npub fn initSlice(args: []const []const u8) Args {\n return .{\n .args = args,\n .index = 0,\n .consumed = false,\n .positionals_only = false,\n };\n}\n\n...
6
MIT License Copyright (c) Jimmi Holst Christensen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
ib1-0068
fn
enumeration
Hejsil/zig-clap
github
05faf3905e8548f5cc269a8836e154065e70128d
clap/parsers.zig
MIT
pub const default = .{ .string = string, .str = string, .u8 = int(u8, 0), .u16 = int(u16, 0), .u32 = int(u32, 0), .u64 = int(u64, 0), .usize = int(usize, 0), .i8 = int(i8, 0), .i16 = int(i16, 0), .i32 = int(i32, 0), .i64 = int(i64, 0), .isize = int(isize, 0), .f32 = f...
} fn ReturnType(comptime P: type) type { return @typeInfo(P).@"fn".return_type.?; } pub fn Result(comptime P: type) type { return @typeInfo(ReturnType(P)).error_union.payload; } const std = @import("std");
return struct { fn parse(in: []const u8) EnumError!T { return std.meta.stringToEnum(T, in) orelse error.NameNotPartOfEnum; } }.parse;
{ "prefix": "pub const default = .{\n .string = string,\n .str = string,\n .u8 = int(u8, 0),\n .u16 = int(u16, 0),\n .u32 = int(u32, 0),\n .u64 = int(u64, 0),\n .usize = int(usize, 0),\n .i8 = int(i8, 0),\n .i16 = int(i16, 0),\n .i32 = int(i32, 0),\n .i64 = int(i64, 0),\n .isize = ...
4
MIT License Copyright (c) Jimmi Holst Christensen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
ib1-0069
fn
float
Hejsil/zig-clap
github
05faf3905e8548f5cc269a8836e154065e70128d
clap/parsers.zig
MIT
pub const default = .{ .string = string, .str = string, .u8 = int(u8, 0), .u16 = int(u16, 0), .u32 = int(u32, 0), .u64 = int(u64, 0), .usize = int(usize, 0), .i8 = int(i8, 0), .i16 = int(i16, 0), .i32 = int(i32, 0), .i64 = int(i64, 0), .isize = int(isize, 0), .f32 = f...
} pub const EnumError = error{ NameNotPartOfEnum, }; /// A parser that uses `std.meta.stringToEnum` to parse the string into an enum value. On `null`, /// this function returns the error `NameNotPartOfEnum`. /// See `std.meta.stringToEnum` documentation for more information. pub fn enumeration(comptime T: type) f...
return struct { fn parse(in: []const u8) std.fmt.ParseFloatError!T { return std.fmt.parseFloat(T, in); } }.parse;
{ "prefix": "pub const default = .{\n .string = string,\n .str = string,\n .u8 = int(u8, 0),\n .u16 = int(u16, 0),\n .u32 = int(u32, 0),\n .u64 = int(u64, 0),\n .usize = int(usize, 0),\n .i8 = int(i8, 0),\n .i16 = int(i16, 0),\n .i32 = int(i32, 0),\n .i64 = int(i64, 0),\n .isize = ...
4
MIT License Copyright (c) Jimmi Holst Christensen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
ib1-0070
fn
int
Hejsil/zig-clap
github
05faf3905e8548f5cc269a8836e154065e70128d
clap/parsers.zig
MIT
pub const default = .{ .string = string, .str = string, .u8 = int(u8, 0), .u16 = int(u16, 0), .u32 = int(u32, 0), .u64 = int(u64, 0), .usize = int(usize, 0), .i8 = int(i8, 0), .i16 = int(i16, 0), .i32 = int(i32, 0), .i64 = int(i64, 0), .isize = int(isize, 0), .f32 = f...
} /// A parser that uses `std.fmt.parseFloat` to parse the string into an float value. /// See `std.fmt.parseFloat` documentation for more information. pub fn float(comptime T: type) fn ([]const u8) std.fmt.ParseFloatError!T { return struct { fn parse(in: []const u8) std.fmt.ParseFloatError!T { ...
return struct { fn parse(in: []const u8) std.fmt.ParseIntError!T { return switch (@typeInfo(T).int.signedness) { .signed => std.fmt.parseInt(T, in, base), .unsigned => std.fmt.parseUnsigned(T, in, base), }; } }.parse;
{ "prefix": "pub const default = .{\n .string = string,\n .str = string,\n .u8 = int(u8, 0),\n .u16 = int(u16, 0),\n .u32 = int(u32, 0),\n .u64 = int(u64, 0),\n .usize = int(usize, 0),\n .i8 = int(i8, 0),\n .i16 = int(i16, 0),\n .i32 = int(i32, 0),\n .i64 = int(i64, 0),\n .isize = ...
4
MIT License Copyright (c) Jimmi Holst Christensen Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish...
ib1-0071
fn
remoteUrls
Huseynteymurzade28/butaglyph
github
81e6bddfa85f7d8d0eac02260b83924642af8e21
src/git/config.zig
MIT
//! A small git-config reader: enough to look up single values such as //! `branch.<name>.remote`. Section and key names are case-insensitive, //! subsection names case-sensitive; the last occurrence of a key wins. //! `[include]` and `[includeIf]` are listed by `includes`; following them //! is up to the caller (see s...
} /// The key lines of a config file, with the section header each is under. const Walker = struct { text: []const u8, /// Offset of the next line. pos: usize = 0, /// The current `[...]` header, brackets included ("" before the first). header: []const u8 = "", fn next(w: *Walker) ?[]const u8 ...
var walker: Walker = .{ .text = c.text }; var buf: [4096]u8 = undefined; while (walker.next()) |line| { const header = parseHeader(walker.header) orelse continue; if (!std.ascii.eqlIgnoreCase(header.name, "remote") or header.sub == null) continue; const url = matchKey(line, "url", &...
{ "prefix": "//! A small git-config reader: enough to look up single values such as\n//! `branch.<name>.remote`. Section and key names are case-insensitive,\n//! subsection names case-sensitive; the last occurrence of a key wins.\n//! `[include]` and `[includeIf]` are listed by `includes`; following them\n//! is up t...
2
MIT License Copyright (c) 2026 flear (https://github.com/Huseynteymurzade28) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
ib1-0072
fn
apply
Huseynteymurzade28/butaglyph
github
81e6bddfa85f7d8d0eac02260b83924642af8e21
src/git/delta.zig
MIT
//! Git's binary delta format, used by OFS_DELTA and REF_DELTA pack entries. //! //! delta := src_size:varint dst_size:varint instruction* //! copy := 1xxxxxxx [offset bytes per bits 0-3] [size bytes per bits 4-6] //! (size 0 means 0x10000) //! insert := 0nnnnnnn n literal bytes (n = 1..127) const...
} /// Little-endian base-128 varint, as used in delta headers. fn varint(buf: []const u8, pos: *usize) Error!usize { var result: usize = 0; var shift: u6 = 0; while (true) { if (pos.* >= buf.len or shift > 56) return error.InvalidDelta; const b = buf[pos.*]; pos.* += 1; resu...
var pos: usize = 0; if (try varint(delta, &pos) != base.len) return error.InvalidDelta; if (try varint(delta, &pos) != out.len) return error.InvalidDelta; var written: usize = 0; while (pos < delta.len) { const op = delta[pos]; pos += 1; if (op & 0x80 != 0) { va...
{ "prefix": "//! Git's binary delta format, used by OFS_DELTA and REF_DELTA pack entries.\n//!\n//! delta := src_size:varint dst_size:varint instruction*\n//! copy := 1xxxxxxx [offset bytes per bits 0-3] [size bytes per bits 4-6]\n//! (size 0 means 0x10000)\n//! insert := 0nnnnnnn n literal bytes...
3
MIT License Copyright (c) 2026 flear (https://github.com/Huseynteymurzade28) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
ib1-0073
fn
resultSize
Huseynteymurzade28/butaglyph
github
81e6bddfa85f7d8d0eac02260b83924642af8e21
src/git/delta.zig
MIT
//! Git's binary delta format, used by OFS_DELTA and REF_DELTA pack entries. //! //! delta := src_size:varint dst_size:varint instruction* //! copy := 1xxxxxxx [offset bytes per bits 0-3] [size bytes per bits 4-6] //! (size 0 means 0x10000) //! insert := 0nnnnnnn n literal bytes (n = 1..127) const...
} /// Applies `delta` to `base`, writing exactly `out.len` bytes into `out` /// (`out.len` must equal `resultSize(delta)`). pub fn apply(base: []const u8, delta: []const u8, out: []u8) Error!void { var pos: usize = 0; if (try varint(delta, &pos) != base.len) return error.InvalidDelta; if (try varint(delta,...
var pos: usize = 0; _ = try varint(delta, &pos); return varint(delta, &pos);
{ "prefix": "//! Git's binary delta format, used by OFS_DELTA and REF_DELTA pack entries.\n//!\n//! delta := src_size:varint dst_size:varint instruction*\n//! copy := 1xxxxxxx [offset bytes per bits 0-3] [size bytes per bits 4-6]\n//! (size 0 means 0x10000)\n//! insert := 0nnnnnnn n literal bytes...
3
MIT License Copyright (c) 2026 flear (https://github.com/Huseynteymurzade28) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
ib1-0074
fn
wildmatch
Huseynteymurzade28/butaglyph
github
81e6bddfa85f7d8d0eac02260b83924642af8e21
src/git/ignore.zig
MIT
//! .gitignore rules, as git applies them (gitignore(5)). //! //! * A line is a pattern; `#` starts a comment, trailing spaces are dropped //! unless escaped, `!` negates, a trailing `/` matches directories only. //! * A pattern without a `/` (other than a trailing one) matches the base //! name at any depth. Other...
} /// Byte at `i`, or 0 past the end (the C code walks NUL-terminated strings). fn at(s: []const u8, i: usize) u8 { return if (i < s.len) s[i] else 0; } fn fold(c: u8, flags: Flags) u8 { return if (flags.casefold) std.ascii.toLower(c) else c; } fn isGlobSpecial(c: u8) bool { return switch (c) { '...
return doWild(pattern, 0, text, 0, flags) == .match;
{ "prefix": "//! .gitignore rules, as git applies them (gitignore(5)).\n//!\n//! * A line is a pattern; `#` starts a comment, trailing spaces are dropped\n//! unless escaped, `!` negates, a trailing `/` matches directories only.\n//! * A pattern without a `/` (other than a trailing one) matches the base\n//! name...
4
MIT License Copyright (c) 2026 flear (https://github.com/Huseynteymurzade28) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
ib1-0075
fn
hasPrivateUse
Huseynteymurzade28/butaglyph
github
81e6bddfa85f7d8d0eac02260b83924642af8e21
src/glyphs.zig
MIT
//! Symbol sets. Every module asks the active set for its default symbol; //! a module's `symbol` option in config.zon overrides it. //! Glyphs carry their own trailing spacing so the ASCII set can be tighter. pub const Set = enum { unicode, nerd, ascii }; pub const Glyphs = struct { git_branch: []const u8, g...
}
const std = @import("std"); var it = (std.unicode.Utf8View.init(s) catch return false).iterator(); while (it.nextCodepoint()) |c| { if ((c >= 0xe000 and c <= 0xf8ff) or c >= 0xf0000) return true; } return false;
{ "prefix": "//! Symbol sets. Every module asks the active set for its default symbol;\n//! a module's `symbol` option in config.zon overrides it.\n//! Glyphs carry their own trailing spacing so the ASCII set can be tighter.\n\npub const Set = enum { unicode, nerd, ascii };\n\npub const Glyphs = struct {\n git_bra...
2
MIT License Copyright (c) 2026 flear (https://github.com/Huseynteymurzade28) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
ib1-0076
fn
fingerprint
Huseynteymurzade28/butaglyph
github
81e6bddfa85f7d8d0eac02260b83924642af8e21
src/wire.zig
MIT
//! A small binary codec for the plain data that crosses the daemon socket: //! module `Config`s (client to daemon) and module `Data` (daemon to client). //! //! Supported: void, bool, integers, enums, optionals, structs, tagged unions, //! arrays and slices of any of these. Integers are little-endian at their //! natu...
} fn shape(comptime T: type, h: *std.hash.Wyhash) void { const info = @typeInfo(T); h.update(@tagName(info)); switch (info) { .void, .bool => {}, .int => |i| h.update(&.{ @backingInt(i.signedness), @truncate(i.bits), @truncate(i.bits >> 8) }), .@"enum" => |e| { shape(e.t...
return comptime blk: { @setEvalBranchQuota(1_000_000); var h = std.hash.Wyhash.init(0); shape(T, &h); break :blk h.final(); };
{ "prefix": "//! A small binary codec for the plain data that crosses the daemon socket:\n//! module `Config`s (client to daemon) and module `Data` (daemon to client).\n//!\n//! Supported: void, bool, integers, enums, optionals, structs, tagged unions,\n//! arrays and slices of any of these. Integers are little-endia...
3
MIT License Copyright (c) 2026 flear (https://github.com/Huseynteymurzade28) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, c...
ib1-0077
fn
tokenize
IridescentRose/ZeeBuffer
github
6f17370bbba1d35b8e3a6fc0fee05ab1cc6b6a95
src/lexer.zig
MPL-2.0
const std = @import("std"); const Io = std.Io; pub const TokenKind = enum(u8) { // Single-character tokens — identity-mapped to their ASCII values. comma = ',', // 44 colon = ':', // 58 semicolon = ';', // 59 equals = '=', // 61 l_bracket = '[', // 91 r_bracket = ']', // 93 l_brace = '{...
} // ── Tests ─────────────────────────────────────────────────────────────────────
var tokens = try std.ArrayList(Token).initCapacity(allocator, source.len / 4); errdefer tokens.deinit(allocator); var i: u16 = 0; if (source.len >= 3 and source[0] == 0xEF and source[1] == 0xBB and source[2] == 0xBF) { i = 3; } const kmap = KeywordMap.initComptime(KeywordPairs); ...
{ "prefix": "const std = @import(\"std\");\nconst Io = std.Io;\n\npub const TokenKind = enum(u8) {\n // Single-character tokens — identity-mapped to their ASCII values.\n comma = ',', // 44\n colon = ':', // 58\n semicolon = ';', // 59\n equals = '=', // 61\n l_bracket = '[', // 91\n r_bracket = ...
18
Mozilla Public License Version 2.0 ================================== 1. Definitions -------------- 1.1. "Contributor" means each individual or legal entity that creates, contributes to the creation of, or owns Covered Software. 1.2. "Contributor Version" means the combination of the Contributions of oth...
ib1-0081
fn
accept
J-X0-cloud/zedis
github
8babfef1b59d813ac588ae56835175d3103c55b5
src/sys.zig
MIT
//! Thin, typed wrappers over the raw Linux syscalls zedis needs. //! //! The standard library's higher level I/O interfaces are built around an //! `Io` abstraction that wants to own scheduling. A single-threaded epoll //! server wants the opposite: direct, non-blocking syscalls whose errno is //! turned into a small ...
} /// Opens a blocking TCP connection. Used by the client library and tests. pub fn connectTcp(addr: Ipv4) Error!fd_t { const fd: fd_t = @intCast(try check(linux.socket(linux.AF.INET, linux.SOCK.STREAM | linux.SOCK.CLOEXEC, 0))); errdefer close(fd); var sa = addr.toSockaddr(); while (true) { _ ...
var sa: linux.sockaddr.in = undefined; var len: linux.socklen_t = @sizeOf(linux.sockaddr.in); while (true) { const rc = check(linux.accept4(listen_fd, @ptrCast(&sa), &len, linux.SOCK.CLOEXEC | linux.SOCK.NONBLOCK)) catch |err| switch (err) { error.Interrupted => continue, el...
{ "prefix": "//! Thin, typed wrappers over the raw Linux syscalls zedis needs.\n//!\n//! The standard library's higher level I/O interfaces are built around an\n//! `Io` abstraction that wants to own scheduling. A single-threaded epoll\n//! server wants the opposite: direct, non-blocking syscalls whose errno is\n//! ...
2
MIT License Copyright (c) 2026 James Lee Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distrib...
ib1-0083
fn
localPort
J-X0-cloud/zedis
github
8babfef1b59d813ac588ae56835175d3103c55b5
src/sys.zig
MIT
//! Thin, typed wrappers over the raw Linux syscalls zedis needs. //! //! The standard library's higher level I/O interfaces are built around an //! `Io` abstraction that wants to own scheduling. A single-threaded epoll //! server wants the opposite: direct, non-blocking syscalls whose errno is //! turned into a small ...
} pub const Accepted = struct { fd: fd_t, addr: Ipv4, }; pub fn accept(listen_fd: fd_t) Error!Accepted { var sa: linux.sockaddr.in = undefined; var len: linux.socklen_t = @sizeOf(linux.sockaddr.in); while (true) { const rc = check(linux.accept4(listen_fd, @ptrCast(&sa), &len, linux.SOCK.CL...
var sa: linux.sockaddr.in = undefined; var len: linux.socklen_t = @sizeOf(linux.sockaddr.in); _ = try check(linux.getsockname(fd, @ptrCast(&sa), &len)); return std.mem.bigToNative(u16, sa.port);
{ "prefix": "//! Thin, typed wrappers over the raw Linux syscalls zedis needs.\n//!\n//! The standard library's higher level I/O interfaces are built around an\n//! `Io` abstraction that wants to own scheduling. A single-threaded epoll\n//! server wants the opposite: direct, non-blocking syscalls whose errno is\n//! ...
2
MIT License Copyright (c) 2026 James Lee Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distrib...
ib1-0084
fn
isCommitHash
JustinWoodring/zest
github
c8e438b56ccbb25cc05ccc39f3bec7d0b26e33d5
src/resolve.zig
MIT
//! Source reference parsing and Zigistry short-name resolution. //! //! Accepted install sources: //! - git URLs: https://github.com/user/repo[.git][@ref], git@host:user/repo.git //! - shorthand: github.com/user/repo[@ref], codeberg.org/user/repo[@ref] //! - short name: my-cli-tool → resolved through the Zig...
} fn jsonStr(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 { return switch (obj.get(key) orelse return null) { .string => |s| s, else => null, }; } fn freeAll(gpa: std.mem.Allocator, list: *std.ArrayList(Candidate)) void { for (list.items) |cand| { gpa.free(cand.url); ...
if (s.len < 7 or s.len > 40) return false; for (s) |c| { switch (c) { '0'...'9', 'a'...'f', 'A'...'F' => {}, else => return false, } } return true;
{ "prefix": "//! Source reference parsing and Zigistry short-name resolution.\n//!\n//! Accepted install sources:\n//! - git URLs: https://github.com/user/repo[.git][@ref], git@host:user/repo.git\n//! - shorthand: github.com/user/repo[@ref], codeberg.org/user/repo[@ref]\n//! - short name: my-cli-tool → reso...
8
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0085
fn
nameFromUrl
JustinWoodring/zest
github
c8e438b56ccbb25cc05ccc39f3bec7d0b26e33d5
src/resolve.zig
MIT
//! Source reference parsing and Zigistry short-name resolution. //! //! Accepted install sources: //! - git URLs: https://github.com/user/repo[.git][@ref], git@host:user/repo.git //! - shorthand: github.com/user/repo[@ref], codeberg.org/user/repo[@ref] //! - short name: my-cli-tool → resolved through the Zig...
} fn classifyRef(gpa: std.mem.Allocator, ref: []const u8) ParseError!Ref { if (ref.len == 0) return .{}; if (isCommitHash(ref)) return .{ .kind = .commit, .value = try gpa.dupe(u8, ref) }; // Anything else with '@' is treated as a tag first, matching the spec's // version-targeting syntax ("repo@v1.2.0...
var end = url.len; if (end > 0 and url[end - 1] == '/') end -= 1; const start = (std.mem.lastIndexOfScalar(u8, url[0..end], '/') orelse return gpa.dupe(u8, url)) + 1; var segment = url[start..end]; if (std.mem.endsWith(u8, segment, ".git")) segment = segment[0 .. segment.len - 4]; return gpa.du...
{ "prefix": "//! Source reference parsing and Zigistry short-name resolution.\n//!\n//! Accepted install sources:\n//! - git URLs: https://github.com/user/repo[.git][@ref], git@host:user/repo.git\n//! - shorthand: github.com/user/repo[@ref], codeberg.org/user/repo[@ref]\n//! - short name: my-cli-tool → reso...
8
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0086
fn
parse
JustinWoodring/zest
github
c8e438b56ccbb25cc05ccc39f3bec7d0b26e33d5
src/resolve.zig
MIT
//! Source reference parsing and Zigistry short-name resolution. //! //! Accepted install sources: //! - git URLs: https://github.com/user/repo[.git][@ref], git@host:user/repo.git //! - shorthand: github.com/user/repo[@ref], codeberg.org/user/repo[@ref] //! - short name: my-cli-tool → resolved through the Zig...
} /// Resolve a bare tool name via the Zigistry program registry. /// /// Returns `.found` for a unique case-insensitive repo-name match, /// `.ambiguous` when several distinct repositories share the name (the /// caller must disambiguate, because zest never guesses), and `null` when nothing /// matches. The registry ...
const trimmed = std.mem.trim(u8, input, " \t"); if (trimmed.len == 0) return error.InvalidSource; const bare = trimmed; const at = lastAt(bare); const repo_part = if (at) |i| bare[0..i] else bare; const ref_part = if (at) |i| bare[i + 1 ..] else ""; if (at != null and ref_part.len == 0) re...
{ "prefix": "//! Source reference parsing and Zigistry short-name resolution.\n//!\n//! Accepted install sources:\n//! - git URLs: https://github.com/user/repo[.git][@ref], git@host:user/repo.git\n//! - shorthand: github.com/user/repo[@ref], codeberg.org/user/repo[@ref]\n//! - short name: my-cli-tool → reso...
8
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0087
fn
formatRfc3339
JustinWoodring/zest
github
c8e438b56ccbb25cc05ccc39f3bec7d0b26e33d5
src/util.zig
MIT
//! Small shared helpers: buffered file I/O, atomic writes, time formatting. //! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> // //! SPDX-License-Identifier: MIT const std = @import("std"); const Io = std.Io; /// Largest accepted size for files zest reads (state.json, command output caps). pub const max_read...
} /// Current wall-clock time formatted as RFC 3339 UTC. pub fn nowRfc3339(io: Io) [20]u8 { const now = Io.Timestamp.now(io, .real); const unix_seconds: i64 = @intCast(@divTrunc(now.nanoseconds, std.time.ns_per_s)); var buf: [20]u8 = undefined; _ = formatRfc3339(&buf, unix_seconds); return buf; } ...
const secs: u64 = @intCast(@max(unix_seconds, 0)); const epoch = std.time.epoch.EpochSeconds{ .secs = secs }; const day = epoch.getEpochDay(); const year_day = day.calculateYearDay(); const month_day = year_day.calculateMonthDay(); const day_secs = epoch.getDaySeconds(); return std.fmt.bufP...
{ "prefix": "//! Small shared helpers: buffered file I/O, atomic writes, time formatting.\n//! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com>\n//\n//! SPDX-License-Identifier: MIT\nconst std = @import(\"std\");\nconst Io = std.Io;\n\n/// Largest accepted size for files zest reads (state.json, command output c...
2
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0088
fn
versionLess
JustinWoodring/zest
github
c8e438b56ccbb25cc05ccc39f3bec7d0b26e33d5
src/util.zig
MIT
//! Small shared helpers: buffered file I/O, atomic writes, time formatting. //! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> // //! SPDX-License-Identifier: MIT const std = @import("std"); const Io = std.Io; /// Largest accepted size for files zest reads (state.json, command output caps). pub const max_read...
} fn stripV(tag: []const u8) []const u8 { if (tag.len > 1 and (tag[0] == 'v' or tag[0] == 'V') and tag[1] >= '0' and tag[1] <= '9') return tag[1..]; return tag; }
const av = stripV(a); const bv = stripV(b); var ai = std.mem.splitScalar(u8, av, '.'); var bi = std.mem.splitScalar(u8, bv, '.'); while (true) { const as = ai.next(); const bs = bi.next(); if (as == null and bs == null) return false; if (as == null) return true; // s...
{ "prefix": "//! Small shared helpers: buffered file I/O, atomic writes, time formatting.\n//! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com>\n//\n//! SPDX-License-Identifier: MIT\nconst std = @import(\"std\");\nconst Io = std.Io;\n\n/// Largest accepted size for files zest reads (state.json, command output c...
2
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0089
fn
byId
JustinWoodring/zymposium
github
d40a5d3e3eb58e81b1d2ecd5eb7017163df10280
src/agents.zig
MIT
//! The agent boundaries zymposium can provision skills into. //! //! Each agent is identified by a stable `id` that appears in `config.json` and //! in the provisioning manifest, and maps to two skill directories: one under //! the user's home (global) and one under a project root (project-local). //! Copyright (c) 20...
} /// Comma-separated ids of every known agent, for error messages. pub fn idList(gpa: std.mem.Allocator) ![]u8 { var aw: Io.Writer.Allocating = .init(gpa); defer aw.deinit(); for (all, 0..) |a, i| { if (i > 0) try aw.writer.writeAll(", "); try aw.writer.writeAll(a.id); } return aw....
for (all) |a| { if (std.mem.eql(u8, a.id, id)) return a; } return null;
{ "prefix": "//! The agent boundaries zymposium can provision skills into.\n//!\n//! Each agent is identified by a stable `id` that appears in `config.json` and\n//! in the provisioning manifest, and maps to two skill directories: one under\n//! the user's home (global) and one under a project root (project-local).\n...
3
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0090
fn
parse
JustinWoodring/zymposium
github
d40a5d3e3eb58e81b1d2ecd5eb7017163df10280
src/cli.zig
MIT
//! Command-line argument parsing. //! //! Usage: //! zymposium init //! zymposium sync [options] //! zymposium list [--json] //! zymposium sources [--json] //! zymposium add <path|url> [--name <n>] //! zymposium remove <skill> //! zymposium update [skill] //! zymposium doctor [--json] //! zymposium a...
} fn eqlAny(s: []const u8, candidates: []const []const u8) bool { for (candidates) |c| { if (std.mem.eql(u8, s, c)) return true; } return false; } pub const version = "0.2.0"; pub const usage_text = \\zymposium: agent skills for Zig projects and CLI tools \\ \\Usage: \\ zymposium...
if (args.len == 0) return .about; const first = args[0]; if (eqlAny(first, &.{ "-h", "--help" })) return .{ .help = null }; if (eqlAny(first, &.{ "-V", "--version" })) return .version; if (std.mem.eql(u8, first, "help")) { if (args.len > 1) return .{ .help = try gpa.dupe(u8, args[1]) }; ...
{ "prefix": "//! Command-line argument parsing.\n//!\n//! Usage:\n//! zymposium init\n//! zymposium sync [options]\n//! zymposium list [--json]\n//! zymposium sources [--json]\n//! zymposium add <path|url> [--name <n>]\n//! zymposium remove <skill>\n//! zymposium update [skill]\n//! zymposium doctor [...
4
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0091
fn
discoverZestRoot
JustinWoodring/zymposium
github
d40a5d3e3eb58e81b1d2ecd5eb7017163df10280
src/self.zig
MIT
//! Locating the package root of the running zymposium, so it can provision //! its own skills however it was installed. //! //! zymposium ships a `skills/` directory describing itself and zest. When it //! is installed through zest, the tool manifest already points at its clone, so //! those skills are found by the or...
}
const staged = std.fs.path.join(gpa, &.{ zest_root, "self", "src" }) catch return error.OutOfMemory; defer gpa.free(staged); const zon = std.fs.path.join(gpa, &.{ staged, "build.zig.zon" }) catch return error.OutOfMemory; defer gpa.free(zon); const stat = Io.Dir.cwd().statFile(io, z...
{ "prefix": "//! Locating the package root of the running zymposium, so it can provision\n//! its own skills however it was installed.\n//!\n//! zymposium ships a `skills/` directory describing itself and zest. When it\n//! is installed through zest, the tool manifest already points at its clone, so\n//! those skills...
3
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0092
fn
findPackageRoot
JustinWoodring/zymposium
github
d40a5d3e3eb58e81b1d2ecd5eb7017163df10280
src/self.zig
MIT
//! Locating the package root of the running zymposium, so it can provision //! its own skills however it was installed. //! //! zymposium ships a `skills/` directory describing itself and zest. When it //! is installed through zest, the tool manifest already points at its clone, so //! those skills are found by the or...
} /// Locate the running installation's package root. Returns null when the /// binary has been copied somewhere without its source tree — a bare binary in /// a bin directory with no `build.zig.zon` above it — which is not an error: /// it just means there are no package skills to offer. pub fn discoverRoot(gpa: std.m...
var current: []const u8 = start; // Bounded so a pathological layout cannot spin forever; real installs are // a handful of levels deep. var depth: usize = 0; while (depth < 32) : (depth += 1) { const zon = std.fs.path.join(gpa, &.{ current, "build.zig.zon" }) catch return error...
{ "prefix": "//! Locating the package root of the running zymposium, so it can provision\n//! its own skills however it was installed.\n//!\n//! zymposium ships a `skills/` directory describing itself and zest. When it\n//! is installed through zest, the tool manifest already points at its clone, so\n//! those skills...
3
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0093
fn
formatRfc3339
JustinWoodring/zymposium
github
d40a5d3e3eb58e81b1d2ecd5eb7017163df10280
src/util.zig
MIT
//! Small shared helpers: buffered file I/O, atomic writes, timestamps, //! symlink-or-copy materialization, and version ordering. //! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> //! //! SPDX-License-Identifier: MIT const std = @import("std"); const Io = std.Io; /// Largest file zymposium will read into mem...
} /// Current wall-clock time formatted as RFC 3339 UTC. pub fn nowRfc3339(io: Io) [20]u8 { const now = Io.Timestamp.now(io, .real); const unix_seconds: i64 = @intCast(@divTrunc(now.nanoseconds, std.time.ns_per_s)); var buf: [20]u8 = undefined; _ = formatRfc3339(&buf, unix_seconds); return buf; } ...
const secs: u64 = @intCast(@max(unix_seconds, 0)); const epoch = std.time.epoch.EpochSeconds{ .secs = secs }; const day = epoch.getEpochDay(); const year_day = day.calculateYearDay(); const month_day = year_day.calculateMonthDay(); const day_secs = epoch.getDaySeconds(); return std.fmt.bufP...
{ "prefix": "//! Small shared helpers: buffered file I/O, atomic writes, timestamps,\n//! symlink-or-copy materialization, and version ordering.\n//! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com>\n//!\n//! SPDX-License-Identifier: MIT\nconst std = @import(\"std\");\nconst Io = std.Io;\n\n/// Largest file zym...
6
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0094
fn
materialize
JustinWoodring/zymposium
github
d40a5d3e3eb58e81b1d2ecd5eb7017163df10280
src/util.zig
MIT
//! Small shared helpers: buffered file I/O, atomic writes, timestamps, //! symlink-or-copy materialization, and version ordering. //! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> //! //! SPDX-License-Identifier: MIT const std = @import("std"); const Io = std.Io; /// Largest file zymposium will read into mem...
} /// Delete a file, symlink, or directory tree if present. Never fails the /// caller: a missing path is success, and a path we cannot remove is left for /// `doctor` to report. pub fn removePath(gpa: std.mem.Allocator, io: Io, path: []const u8) void { _ = gpa; const cwd = Io.Dir.cwd(); cwd.deleteTree(io,...
removePath(gpa, io, link_path); // The agent's skills directory may not exist yet on a first run. A symlink // cannot be created without its parent, and without this the very first // skill would silently degrade to a copy while later ones became links. if (std.fs.path.dirname(link_path)) |parent|...
{ "prefix": "//! Small shared helpers: buffered file I/O, atomic writes, timestamps,\n//! symlink-or-copy materialization, and version ordering.\n//! Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com>\n//!\n//! SPDX-License-Identifier: MIT\nconst std = @import(\"std\");\nconst Io = std.Io;\n\n/// Largest file zym...
6
MIT License Copyright (c) 2026 Justin Woodring <jwoodrg@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modif...
ib1-0095
fn
locate
KercyDing/jsonz
github
a836af934876f8abdc45e058377ca3d8a1cbb948
src/diagnostic/error.zig
MIT
//! The problem catalogue for `jsonz.diagnostic`: what went wrong with a JSON //! document, and the evidence needed to explain it. Messages follow the Zig //! compiler's phrasing: no trailing period, `'EOF'` for end of input. const std = @import("std"); /// A byte range of the input. A `len` of zero marks a position ...
} /// Writes `byte` the way Zig renders a character literal: `'a'`, `'\n'`, `'\x07'`. fn writeCharLiteral(writer: *std.Io.Writer, byte: u8) std.Io.Writer.Error!void { try writer.writeByte('\''); switch (byte) { '\n' => try writer.writeAll("\\n"), '\r' => try writer.writeAll("\\r"), '\t'...
const clamped = @min(offset, input.len); var line: usize = 1; var line_start: usize = 0; for (input[0..clamped], 0..) |byte, index| { if (byte == '\n') { line += 1; line_start = index + 1; } } var line_end = clamped; while (line_end < input.len and in...
{ "prefix": "//! The problem catalogue for `jsonz.diagnostic`: what went wrong with a JSON\n//! document, and the evidence needed to explain it. Messages follow the Zig\n//! compiler's phrasing: no trailing period, `'EOF'` for end of input.\n\nconst std = @import(\"std\");\n\n/// A byte range of the input. A `len` of...
3
MIT License Copyright (c) 2026 KercyDing Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distrib...
ib1-0096
fn
makeTag
KercyDing/jsonz
github
a836af934876f8abdc45e058377ca3d8a1cbb948
src/dom/pool.zig
MIT
const std = @import("std"); /// The JSON node type, stored in the low three bits of a tag. pub const Type = enum(u3) { /// Only the default tag of an unset node uses this. none = 0, null = 1, bool = 2, number = 3, string = 4, array = 5, object = 6, }; /// The node subtype, stored in th...
} pub fn nodeType(node: NodeData) Type { return node.tag.type; } pub fn nodeSubtype(node: NodeData) Subtype { return node.tag.subtype; } pub fn nodeLen(node: NodeData) usize { return node.tag.len; } /// The tag bit of an object member's name. A name is not a value, so /// `Node.values` skips it; the mut...
return .{ .type = node_type, .subtype = subtype, .len = @intCast(len), };
{ "prefix": "const std = @import(\"std\");\n\n/// The JSON node type, stored in the low three bits of a tag.\npub const Type = enum(u3) {\n /// Only the default tag of an unset node uses this.\n none = 0,\n null = 1,\n bool = 2,\n number = 3,\n string = 4,\n array = 5,\n object = 6,\n};\n\n///...
5
MIT License Copyright (c) 2026 KercyDing Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distrib...
ib1-0100
fn
typeKind
KercyDing/jsonz
github
a836af934876f8abdc45e058377ca3d8a1cbb948
src/typed/kind.zig
MIT
//! Type classification helpers for the JSON codec. const std = @import("std"); const split_fields = !@hasField(std.builtin.Type.Struct, "fields"); /// Version-independent reflection metadata for one struct field. const StructField = struct { name: [:0]const u8, type: type, default_value_ptr: ?*const any...
} fn classifyPointer( comptime T: type, comptime p: std.builtin.Type.Pointer, ) Kind { switch (p.size) { .slice => { if (p.child == u8) return .string; return .slice; }, .many => { if (p.child == u8 and p.sentinel() != null) ...
return switch (@typeInfo(T)) { .bool => .bool, .int, .comptime_int, => .int, .float, .comptime_float, => .float, .void => .void, .optional => .optional, .@"enum" => .@"enum", .@"union" => .@"union", .pointer => |p...
{ "prefix": "//! Type classification helpers for the JSON codec.\n\nconst std = @import(\"std\");\n\nconst split_fields = !@hasField(std.builtin.Type.Struct, \"fields\");\n\n/// Version-independent reflection metadata for one struct field.\nconst StructField = struct {\n name: [:0]const u8,\n type: type,\n d...
10
MIT License Copyright (c) 2026 KercyDing Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distrib...
ib1-0104
fn
parseProcPartitions
LilithSemi/blkid.zig
github
a02d934df94e0cd582f49dc5ee034927e36311ee
src/blkid/hl/enumerate.zig
Apache-2.0
const std = @import("std"); const builtin = @import("builtin"); /// Parse /proc/partitions into "/dev/<name>" paths. Caller owns each item and the slice. pub fn parseProcPartitions(gpa: std.mem.Allocator, content: []const u8) ![][]u8 {
} /// List block-device paths from /proc/partitions. Linux only (error.Unsupported elsewhere). /// procfs files report size 0, so uses a streaming reader. pub fn listBlockDevices(gpa: std.mem.Allocator, io: std.Io) ![][]u8 { if (builtin.os.tag != .linux) return error.Unsupported; var file = try std.Io.Dir.cwd(...
var list = std.ArrayList([]u8).empty; errdefer { for (list.items) |p| gpa.free(p); list.deinit(gpa); } var lines = std.mem.splitScalar(u8, content, '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t\r"); if (trimmed.len == 0) continue; ...
{ "prefix": "const std = @import(\"std\");\nconst builtin = @import(\"builtin\");\n\n/// Parse /proc/partitions into \"/dev/<name>\" paths. Caller owns each item and the slice.\npub fn parseProcPartitions(gpa: std.mem.Allocator, content: []const u8) ![][]u8 {", "suffix": "}\n\n/// List block-device paths from /proc...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0105
fn
from
LilithSemi/conduit
github
04bc0e5a264c15b30c66069e0f110cd2d4f161b6
conduit/device/serial.zig
Apache-2.0
//! The serial / UART device-class contract. A vtable over any byte-stream UART. //! Drivers (driver/ns16550a.zig, driver/pl011.zig) implement the small method //! set and wrap themselves with `Serial.from`. const std = @import("std"); const Serial = @This(); ctx: ?*anyopaque, write_fn: *const fn (ctx: ?*anyopaque, b...
} /// A `std.Io.Writer` over a serial port. It sends every write straight to the /// UART through `Serial.write`, so `std.fmt` formatting and any std API that /// takes a writer reach the console. Store it at a stable address and pass /// `&w.interface` to consumers. Bytes go out on each write. Pass an empty /// `buff...
const P = @TypeOf(impl); const gen = struct { fn write(ctx: ?*anyopaque, bytes: []const u8) void { const self: P = @ptrCast(@alignCast(ctx)); self.write(bytes); } fn read(ctx: ?*anyopaque, buf: []u8) usize { const self: P = @ptrCast(@alignCast(ctx)); ...
{ "prefix": "//! The serial / UART device-class contract. A vtable over any byte-stream UART.\n//! Drivers (driver/ns16550a.zig, driver/pl011.zig) implement the small method\n//! set and wrap themselves with `Serial.from`.\n\nconst std = @import(\"std\");\nconst Serial = @This();\n\nctx: ?*anyopaque,\nwrite_fn: *cons...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0106
fn
writer
LilithSemi/conduit
github
04bc0e5a264c15b30c66069e0f110cd2d4f161b6
conduit/device/serial.zig
Apache-2.0
//! The serial / UART device-class contract. A vtable over any byte-stream UART. //! Drivers (driver/ns16550a.zig, driver/pl011.zig) implement the small method //! set and wrap themselves with `Serial.from`. const std = @import("std"); const Serial = @This(); ctx: ?*anyopaque, write_fn: *const fn (ctx: ?*anyopaque, b...
} /// A `std.Io.Reader` over a serial port. It reads only the bytes the UART holds /// now and never blocks: a read returns 0 when nothing waits, which the /// `std.Io.Reader` contract allows (0 does not mean end of stream). Store it at /// a stable address and pass `&r.interface` to consumers. An empty `buffer` /// m...
return .{ .serial = self, .interface = .{ .vtable = &Writer.vtable, .buffer = buffer } };
{ "prefix": "//! The serial / UART device-class contract. A vtable over any byte-stream UART.\n//! Drivers (driver/ns16550a.zig, driver/pl011.zig) implement the small method\n//! set and wrap themselves with `Serial.from`.\n\nconst std = @import(\"std\");\nconst Serial = @This();\n\nctx: ?*anyopaque,\nwrite_fn: *cons...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0107
fn
first
LilithSemi/conduit
github
04bc0e5a264c15b30c66069e0f110cd2d4f161b6
conduit/match.zig
Apache-2.0
//! Device-class matching. A `Matcher` is a rule that says "a node carrying any //! of these compatible strings (DT) or HIDs (ACPI) is a device of this class". //! Matchers are `comptime`-constructible so the same table drives the comptime //! `Builder` and the runtime `Registry`. const std = @import("std"); /// The ...
}
for (table) |m| if (m.matches(ids)) return m; return null;
{ "prefix": "//! Device-class matching. A `Matcher` is a rule that says \"a node carrying any\n//! of these compatible strings (DT) or HIDs (ACPI) is a device of this class\".\n//! Matchers are `comptime`-constructible so the same table drives the comptime\n//! `Builder` and the runtime `Registry`.\n\nconst std = @im...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0108
fn
parse
LilithSemi/dbus.zig
github
ac21c343ceee75c0a5ea1793096751ca851abfa1
src/dbus/address.zig
Apache-2.0
//! D-Bus server address parsing. An address is one or more `transport:key=val,...` //! entries separated by `;`. Values are `%XX`-escaped. See the D-Bus spec's //! "Server Addresses" section. const std = @import("std"); pub const Error = error{ InvalidAddress, UnknownTransport, InvalidEscape, Invalid...
} const testing = std.testing;
var list: std.ArrayList(ServerAddress) = .empty; errdefer { for (list.items) |a| a.deinit(gpa); list.deinit(gpa); } var it = std.mem.splitScalar(u8, s, ';'); while (it.next()) |entry| { if (entry.len == 0) continue; const addr = try parseOne(gpa, entry); try ...
{ "prefix": "//! D-Bus server address parsing. An address is one or more `transport:key=val,...`\n//! entries separated by `;`. Values are `%XX`-escaped. See the D-Bus spec's\n//! \"Server Addresses\" section.\n\nconst std = @import(\"std\");\n\npub const Error = error{\n InvalidAddress,\n UnknownTransport,\n ...
6
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0109
fn
appendCookieResponse
LilithSemi/dbus.zig
github
ac21c343ceee75c0a5ea1793096751ca851abfa1
src/dbus/auth.zig
Apache-2.0
//! D-Bus SASL authentication, client side. The handshake is line-based (CRLF) //! after a leading NUL byte, and ends with BEGIN, after which the binary message //! stream starts. Mechanisms: EXTERNAL (SO_PEERCRED), DBUS_COOKIE_SHA1, ANONYMOUS, //! plus optional NEGOTIATE_UNIX_FD. See the D-Bus spec "Authentication" se...
} /// Fill `buf` with a 32-char lowercase-hex server GUID from 16 secure random /// bytes. Entropy comes from the injected `io` handle rather than a hardwired /// syscall; `randomSecure` errors instead of silently returning weak bytes. pub fn genGuid(io: std.Io, buf: *[32]u8) std.Io.RandomSecureError!void { var ra...
var sha = Sha1.init(.{}); sha.update(server_challenge); sha.update(":"); sha.update(client_challenge); sha.update(":"); sha.update(cookie); var digest: [Sha1.digest_length]u8 = undefined; sha.final(&digest); var plain: std.ArrayList(u8) = .empty; defer plain.deinit(gpa); tr...
{ "prefix": "//! D-Bus SASL authentication, client side. The handshake is line-based (CRLF)\n//! after a leading NUL byte, and ends with BEGIN, after which the binary message\n//! stream starts. Mechanisms: EXTERNAL (SO_PEERCRED), DBUS_COOKIE_SHA1, ANONYMOUS,\n//! plus optional NEGOTIATE_UNIX_FD. See the D-Bus spec \...
7
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0110
fn
spawn
LilithSemi/dbus.zig
github
ac21c343ceee75c0a5ea1793096751ca851abfa1
src/dbus/daemon/activation.zig
Apache-2.0
//! Service activation: parse `.service` files ([D-BUS Service] with Name=/Exec=), //! index them by name, and spawn a service's Exec on demand via double-fork + //! execve (so no zombie is left behind). Env/starter-address propagation and //! auto-start message queuing are follow-ups; this provides the parse + spawn /...
} const testing = std.testing;
// Build a null-terminated argv of null-terminated strings. var args: std.ArrayList([:0]u8) = .empty; defer { for (args.items) |a| gpa.free(a); args.deinit(gpa); } var it = std.mem.tokenizeScalar(u8, exec, ' '); while (it.next()) |tok| try args.append(gpa, try gpa.dupeSentinel(u...
{ "prefix": "//! Service activation: parse `.service` files ([D-BUS Service] with Name=/Exec=),\n//! index them by name, and spawn a service's Exec on demand via double-fork +\n//! execve (so no zombie is left behind). Env/starter-address propagation and\n//! auto-start message queuing are follow-ups; this provides t...
3
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0111
fn
alignmentOf
LilithSemi/dbus.zig
github
ac21c343ceee75c0a5ea1793096751ca851abfa1
src/dbus/types.zig
Apache-2.0
//! D-Bus type system: the single-character type codes, their wire alignments, //! and predicates for classifying them (basic / fixed / string-like). const std = @import("std"); pub const Type = enum(u8) { byte = 'y', boolean = 'b', int16 = 'n', uint16 = 'q', int32 = 'i', uint32 = 'u', int...
} /// Fixed-size types marshal to a constant number of bytes. pub fn isFixed(t: Type) bool { return switch (t) { .byte, .boolean, .int16, .uint16, .int32, .uint32, .int64, .uint64, .double, .unix_fd => true, else => false, }; } /// String, object path, and signature share length-prefixed wire ...
return switch (t) { .byte, .signature, .variant => 1, .int16, .uint16 => 2, .boolean, .int32, .uint32, .unix_fd, .string, .object_path, .array => 4, .int64, .uint64, .double, .struct_begin, .dict_begin => 8, .struct_end, .dict_end => 1, };
{ "prefix": "//! D-Bus type system: the single-character type codes, their wire alignments,\n//! and predicates for classifying them (basic / fixed / string-like).\n\nconst std = @import(\"std\");\n\npub const Type = enum(u8) {\n byte = 'y',\n boolean = 'b',\n int16 = 'n',\n uint16 = 'q',\n int32 = 'i'...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0112
fn
isBasic
LilithSemi/dbus.zig
github
ac21c343ceee75c0a5ea1793096751ca851abfa1
src/dbus/types.zig
Apache-2.0
//! D-Bus type system: the single-character type codes, their wire alignments, //! and predicates for classifying them (basic / fixed / string-like). const std = @import("std"); pub const Type = enum(u8) { byte = 'y', boolean = 'b', int16 = 'n', uint16 = 'q', int32 = 'i', uint32 = 'u', int...
} const testing = std.testing;
return isFixed(t) or isStringLike(t);
{ "prefix": "//! D-Bus type system: the single-character type codes, their wire alignments,\n//! and predicates for classifying them (basic / fixed / string-like).\n\nconst std = @import(\"std\");\n\npub const Type = enum(u8) {\n byte = 'y',\n boolean = 'b',\n int16 = 'n',\n uint16 = 'q',\n int32 = 'i'...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0113
fn
isFixed
LilithSemi/dbus.zig
github
ac21c343ceee75c0a5ea1793096751ca851abfa1
src/dbus/types.zig
Apache-2.0
//! D-Bus type system: the single-character type codes, their wire alignments, //! and predicates for classifying them (basic / fixed / string-like). const std = @import("std"); pub const Type = enum(u8) { byte = 'y', boolean = 'b', int16 = 'n', uint16 = 'q', int32 = 'i', uint32 = 'u', int...
} /// String, object path, and signature share length-prefixed wire encodings. pub fn isStringLike(t: Type) bool { return switch (t) { .string, .object_path, .signature => true, else => false, }; } /// Basic types are anything that is not a container (array/variant/struct/dict). pub fn isBasic...
return switch (t) { .byte, .boolean, .int16, .uint16, .int32, .uint32, .int64, .uint64, .double, .unix_fd => true, else => false, };
{ "prefix": "//! D-Bus type system: the single-character type codes, their wire alignments,\n//! and predicates for classifying them (basic / fixed / string-like).\n\nconst std = @import(\"std\");\n\npub const Type = enum(u8) {\n byte = 'y',\n boolean = 'b',\n int16 = 'n',\n uint16 = 'q',\n int32 = 'i'...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0114
fn
EVIOCGABS
LilithSemi/libinput.zig
github
45678e71738054779877d25dfed768985be5bdd4
src/libinput/evdev.zig
Apache-2.0
//! Linux evdev ABI: struct layouts, event codes, and ioctl request builders. const std = @import("std"); pub const TimeVal = extern struct { sec: isize, usec: isize }; pub const InputEvent = extern struct { time: TimeVal, type: u16, code: u16, value: i32, }; pub const InputId = extern struct { ...
} /// EVIOCGPROP(len): read the device property bitmask (INPUT_PROP_*). /// nr 0x09 comes from include/uapi/linux/input.h. pub fn EVIOCGPROP(len: usize) u32 { return ioc(IOC_READ, EV, 0x09, @intCast(len)); } pub fn EVIOCGRAB() u32 { return ioc(IOC_WRITE, EV, 0x90, @sizeOf(c_int)); } pub const AbsInfo = exter...
return ioc(IOC_READ, EV, 0x40 + abs, @sizeOf(AbsInfo));
{ "prefix": "//! Linux evdev ABI: struct layouts, event codes, and ioctl request builders.\n\nconst std = @import(\"std\");\n\ntest \"InputEvent has kernel ABI layout\" {\n // On 64-bit Linux, input_event is timeval(16) + type(2) + code(2) + value(4) = 24.\n try std.testing.expectEqual(@as(usize, 24), @sizeOf(I...
7
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0116
fn
testBit
LilithSemi/libinput.zig
github
45678e71738054779877d25dfed768985be5bdd4
src/libinput/evdev.zig
Apache-2.0
//! Linux evdev ABI: struct layouts, event codes, and ioctl request builders. const std = @import("std"); pub const TimeVal = extern struct { sec: isize, usec: isize }; pub const InputEvent = extern struct { time: TimeVal, type: u16, code: u16, value: i32, }; pub const InputId = extern struct { ...
} // _IOC encoding (asm-generic/ioctl.h): dir[31:30] size[29:16] type[15:8] nr[7:0] const IOC_NONE: u32 = 0; const IOC_WRITE: u32 = 1; const IOC_READ: u32 = 2; fn ioc(dir: u32, typ: u32, nr: u32, size: u32) u32 { return (dir << 30) | (size << 16) | (typ << 8) | nr; } const EV = 0x45; // 'E' pub fn EVIOCGID() u3...
const byte = bit / 8; if (byte >= arr.len) return false; return (arr[byte] & (@as(u8, 1) << @intCast(bit % 8))) != 0;
{ "prefix": "//! Linux evdev ABI: struct layouts, event codes, and ioctl request builders.\n\nconst std = @import(\"std\");\n\ntest \"InputEvent has kernel ABI layout\" {\n // On 64-bit Linux, input_event is timeval(16) + type(2) + code(2) + value(4) = 24.\n try std.testing.expectEqual(@as(usize, 24), @sizeOf(I...
7
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0117
fn
IO
LilithSemi/libseat.zig
github
8b3b2a66bdf3b8de1e4683fdd02de63fb47c6834
src/linux/ioctl.zig
Apache-2.0
//! The Linux `_IOC` request-number macros, in pure Zig. Device backends build //! their ioctl request numbers from these instead of hardcoding hex, so the //! layout is checked at comptime and cross-compiles with no C headers. //! //! Layout (asm-generic, used by every arch libseat targets): nr in bits 0-7, //! type i...
} pub fn IOR(io_type: u8, nr: u8, comptime T: type) u32 { return IOC(.read, io_type, nr, @sizeOf(T)); } pub fn IOW(io_type: u8, nr: u8, comptime T: type) u32 { return IOC(.write, io_type, nr, @sizeOf(T)); } pub fn IOWR(io_type: u8, nr: u8, comptime T: type) u32 { return IOC(.read_write, io_type, nr, @siz...
return IOC(.none, io_type, nr, 0);
{ "prefix": "//! The Linux `_IOC` request-number macros, in pure Zig. Device backends build\n//! their ioctl request numbers from these instead of hardcoding hex, so the\n//! layout is checked at comptime and cross-compiles with no C headers.\n//!\n//! Layout (asm-generic, used by every arch libseat targets): nr in b...
2
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0119
fn
claim
LilithSemi/udev.zig
github
5b76bbccde9ef7bcb9b6447c0f2454f2ade51733
src/udev/daemon/link_db.zig
Apache-2.0
//! link_db.zig - /run/udev/links symlink priority arbitration. //! When multiple devices claim the same symlink the device with the highest //! link_priority wins. Stamp files under //! <run_root>/links/<escaped_symlink>/<devid> record each active claim. const std = @import("std"); /// Escape a symlink relative path...
} /// Remove `devid`'s claim on `symlink` (best-effort; does not return errors). pub fn release( io: std.Io, gpa: std.mem.Allocator, run_root: []const u8, symlink: []const u8, devid: []const u8, ) void { const escaped = escapeLinkName(gpa, symlink) catch return; defer gpa.free(escaped); ...
const escaped = try escapeLinkName(gpa, symlink); defer gpa.free(escaped); const dir_path = try std.fmt.allocPrint(gpa, "{s}/links/{s}", .{ run_root, escaped }); defer gpa.free(dir_path); try std.Io.Dir.cwd().createDirPath(io, dir_path); const stamp_path = try std.fmt.allocPrint(gpa, "{s}/{s...
{ "prefix": "//! link_db.zig - /run/udev/links symlink priority arbitration.\n//! When multiple devices claim the same symlink the device with the highest\n//! link_priority wins. Stamp files under\n//! <run_root>/links/<escaped_symlink>/<devid> record each active claim.\nconst std = @import(\"std\");\n\n/// Escape ...
4
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0120
fn
escapeLinkName
LilithSemi/udev.zig
github
5b76bbccde9ef7bcb9b6447c0f2454f2ade51733
src/udev/daemon/link_db.zig
Apache-2.0
//! link_db.zig - /run/udev/links symlink priority arbitration. //! When multiple devices claim the same symlink the device with the highest //! link_priority wins. Stamp files under //! <run_root>/links/<escaped_symlink>/<devid> record each active claim. const std = @import("std"); /// Escape a symlink relative path...
} /// Record that `devid` (with `priority`) claims `symlink`, whose target node /// basename is `target`. /// Writes <run_root>/links/<escaped>/<devid> = "<priority>\n<target>\n". pub fn claim( io: std.Io, gpa: std.mem.Allocator, run_root: []const u8, symlink: []const u8, devid: []const u8, pri...
var out: std.ArrayListUnmanaged(u8) = .empty; errdefer out.deinit(gpa); for (symlink) |c| { if (c == '/') try out.appendSlice(gpa, "\\x2f") else try out.append(gpa, c); } return out.toOwnedSlice(gpa);
{ "prefix": "//! link_db.zig - /run/udev/links symlink priority arbitration.\n//! When multiple devices claim the same symlink the device with the highest\n//! link_priority wins. Stamp files under\n//! <run_root>/links/<escaped_symlink>/<devid> record each active claim.\nconst std = @import(\"std\");\n\n/// Escape ...
4
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...
ib1-0121
fn
cstr
LilithSemi/udev.zig
github
5b76bbccde9ef7bcb9b6447c0f2454f2ade51733
src/udev/hwdb/format.zig
Apache-2.0
//! On-disk structs and readers for the compiled hwdb.bin trie. //! All offsets in hwdb.bin are absolute byte offsets into the file buffer. //! All multi-byte integers are little-endian. //! No allocations: readers return views/values backed by the caller's buffer. const std = @import("std"); pub const signature = "K...
}
const o = std.math.cast(usize, off) orelse return error.Corrupt; if (o >= bytes.len) return error.Corrupt; const rest = bytes[o..]; const null_pos = std.mem.indexOfScalar(u8, rest, 0) orelse return error.Corrupt; return rest[0..null_pos];
{ "prefix": "//! On-disk structs and readers for the compiled hwdb.bin trie.\n//! All offsets in hwdb.bin are absolute byte offsets into the file buffer.\n//! All multi-byte integers are little-endian.\n//! No allocations: readers return views/values backed by the caller's buffer.\n\nconst std = @import(\"std\");\n\n...
3
Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, ...